ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/osprai/osprai/trunk/modelclass.py
Revision: 25
Committed: Wed Apr 28 20:22:24 2010 UTC (9 years, 5 months ago) by rjaynes
File size: 6771 byte(s)
Log Message:
Add py and obj files to allow modeling of more SPR experiments with converter and curvefitting modules.  This is the work of Yuhang Wan and Rui Hou.

1. In "converter.py": 
      Add the saving and reading function for the sprclass data object.
      Also add function "keyfile_read_fake" to provide default information for SPRit and ICM formats in case of the bug when do background_subtract.
      Fix the bugs in "background_subtract".
      Tested by DAM and ICM formats.
2. In model modules:
      "modelclass.py" is the parent class for all the other model classes that performs the theoretical simulating, loading and saving of the parameter or simulated data. Rui and I also add some other model modules like competing model, twostate model, parallel model, and the time variable concentrated models, where the simulated result is compared with Clamp's simulation to make sure the equations are correct. 
       The basicmodel and basicmodel_varyC class are tested. 
3. In "curvefitting.py":
      Add typical pipeline for operation. The examples are packed with the file. 
      Add function to show the Elapsed time for each fitting.
Line File contents
1 """
2 ModelClass: Provide the parent class for all the other model classes.
3 Perform the theoretical simulating, loading and saving of the parameter or simulated data.
4
5 Yuhang Wan
6 Last modified on 100427 (yymmdd)
7
8 Typical Pipeline (work together with some son_class, take the basicmodel as example):
9 >from modelclass import * (already embodied in the son_class body)
10 >import modelbasic as bm
11 >m = bm.basicmodel()
12 >m.check_attribute()
13 >m.wizard() or m.load_model('model.obj')
14 >m.simulate(t=range(1200))
15 >m.save_model('newmodel')
16 >m.save_parainfo('parainfo.txt')
17 >m.save_sim_data('sim.dat')
18
19 """
20 __version__ = "100427"
21
22 import numpy as np
23 import pylab as plt
24 import copy
25 import os
26 import pickle
27
28 class modelclass(object):
29 """The data attributes of the class:
30 parainfo: the parameter information
31 sim_data: the simulated data
32 """
33 def __init__ (self, parainfo=[], sim_data=[]):
34 self.parainfo = parainfo
35 self.sim_data = sim_data
36
37 def updatemodel(self, parainfo):
38 """
39 This function helps to update the parameter information.
40 Usually used when you want to keep the fitted value as the
41 initial guess for next curve fitting.
42 """
43 self.parainfo = parainfo
44 return
45
46 def simulate(self,t):
47 """ This function helps to simulate a group of theoretical results.
48 """
49 parainfo=copy.deepcopy(self.parainfo)
50 if parainfo == []:
51 print "Warning: no parameter import! \nPlease load parameter file or follow the wizard."
52 return
53 sim_data=[]
54 sim_data.append(np.array(t))
55 plt.title('Simulation curve')
56 plt.xlabel('Time (s)')
57 plt.ylabel('Response (uRIU)')
58 plt.grid(True)
59
60 ## check if the number of the parainfo item makes sense
61 tmplist,tmpindex = [], []
62 for i in parainfo:
63 if type(i['value']) != list:
64 if i['number'] != 1:
65 print "Warning: the 'number' of '%s' should be '1'." %i['name']
66 else:
67 if i['number'] != len(i['value']):
68 print "Error: the number of the '%s' value set doesn't match with the assumed number" %i['name']
69 print "number: %d\nvalue: %s" %(i['number'], i['value'])
70 return
71 else:
72 tmplist.append(i['number'])
73 tmpindex.append(parainfo.index(i))
74 tmplist = list(set(tmplist))
75 if len(tmplist) == 1:
76 for i in range(tmplist[0]):
77 for j in tmpindex:
78 parainfo[j]['value']=self.parainfo[j]['value'][i]
79 gt=self.function(t, parainfo)
80 plt.plot(t, gt)
81 sim_data.append(gt)
82
83 elif len(tmplist) == 0:
84 gt=self.function(t, parainfo)
85 plt.plot(t, gt)
86 sim_data.append(gt)
87
88 else:##len(tmplist) > 1:
89 print "Error: the number of parameters don't match with each other. "
90 for i in tmpindex:
91 p = parainfo[i]
92 print "name: %s,\tnumber: %d,\tvalue: %s " %(p['name'],p['number'],p['value'])
93 return
94
95 plt.show()
96 self.sim_data = sim_data
97 return
98
99 def save_sim_data(self, f_data_name):
100 """ This function helps to save the simulated data.
101 """
102 np.savetxt('temp.txt',np.transpose(self.sim_data),fmt='%f')
103 fp=file('temp.txt','r')
104 fout=file(f_data_name,'w+')
105 count = len(fp.readlines())
106 fp.seek(0)
107 for i in range(count):
108 temp=fp.readline()
109 fout.write(temp.replace(' ','\t'))
110 fp.close()
111 fout.close()
112 print '-------The path of the saved simulated data is "', os.getcwd(),'"-------'
113 return
114
115
116 def save_model(self, f_obj_name):
117 """ This function helps to save the class object that contains all the infomation.
118 """
119 f_obj_name = f_obj_name + '.obj' # the file extension of the saved data object is .obj
120 fout = file(f_obj_name, 'w+')
121 pickle.dump(self, fout)
122 fout.close()
123 print '-------The path of the exported obj is "', os.getcwd(),'"-------'
124 return
125
126 def load_model(self, f_obj_name):
127 """ This function helps to load the whole class object from an existing file.
128 """
129 fp = file(f_obj_name, 'r+')
130 obj = pickle.load(fp)
131 fp.close()
132 print '-------File "', f_obj_name, '" is loaded. -------'
133 return obj
134
135 ##----------------------not finished part-------------------------
136 def save_parainfo(self, f_para_name):
137 """ This function helps to export the parameter infomation into a txt file.
138 The exported file can be edited manually.
139 In the format like:
140 name rmax c ka kd
141 fixed 0(/F) 1(/T) 0(/F) 0(/F)
142 number 1 3 1 1
143 value 250 1e-9 1e5 1e-3
144 2e-9
145 4e-9
146 """
147
148 def load_parainfo(self, f_para_name):
149 """ This function helps to import the parameter infomation
150 into a list of dictionaries from a txt file.
151 """
152 ##----------------------not finished part---------------------------
153
154 def check_attribute(self):
155 """ This function helps to check the attributes of the class object
156 and look for help information.
157 """
158 print self.__doc__
159 print "The usable data attributes are: "
160 for i in self.__dict__.keys():
161 if self.__dict__[i] != []:
162 print "\t",i
163
164 print "\nThe callable methods are: "
165 method_list = dir(self)
166 for i in method_list:
167 if not i.startswith('__') and i not in self.__dict__:
168 print "\t",i
169
170 while True:
171 method = str.lower(raw_input("Enter the method name for help (q for quit): " ))
172 if method == "q":
173 break
174 try:
175 print "=="*30
176 i = method_list.index(method)
177 print self.__getattribute__(method_list[i]).__doc__
178 except ValueError:
179 print method,"is not a method defined in class."
180 print " "
181 return
182
183 ##### End of model class definition.