ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/osprai/osprai/trunk/ba_class.py
Revision: 17
Committed: Thu Apr 22 00:22:37 2010 UTC (9 years, 1 month ago) by clausted
File size: 6244 byte(s)
Log Message:
Start work on curve fitting.  Added two properties, model and params, to ba.roi in ba_class.  Add mdl_module which will hold functions that model SPR interactions.  
Line File contents
1 """
2 ba: Biosensor Array class for storing SPRI data.
3 Christopher Lausted, Institute for Systems Biology,
4 Yuhang Wan, OSPRAI developers
5 Last modified on 100421 (yymmdd)
6
7 Examples:
8 #ba1 = BiosensorArray(800,1500) ## Allocate object with 800 spots of 1500 time points.
9 #ba1.roi[799].time[1499] = 7502.1 ## Set time in seconds.
10 #ba1.roi[799].value[1499] = 0.50 ## Set SPR reflectance signal.
11 #ba1.roi[799].name = "anti-IgG" ## Set name of microarray feature.
12 """
13 __version__ = "100421"
14
15 ## Import libraries.
16 import numpy as np
17 import matplotlib.pyplot as plt
18 from datetime import date
19
20
21 class BiosensorArray(object):
22 """The Biosensor Array class holds all ROIs/spots from an SPRI microarray run."""
23 def __init__(self, roi_size, datapoint_size):
24 """This object is dimensioned upon initialization.""" ## Might improve speed.
25 ## Use a list comprehension to dimension list of classes.
26 self.roi = [RegOfInterest(i,datapoint_size) for i in range(roi_size)]
27 ## Remember the dimensions for quick bounds-checking later.
28 self.rois = roi_size
29 self.dpoints = datapoint_size
30 ## Use these to keep track of laboratory notes.
31 self.primarydatafiles = [""] ## Like "spritdata.txt"
32 self.comments = [""] ## Like "Antibody data from 1 Jan 2010"
33
34 def xy2uid(self, gx, gy, x, y):
35 """Given roi coordinates, find corresponding uid (index)."""
36 coor1 = (gx, gy, x, y)
37 for ob in self.roi:
38 coor2 = (ob.gridx, ob.gridy, ob.spotx, ob.spoty)
39 if (coor1==coor2): return ob.uid ## Success.
40 return -1 ## Failure.
41
42 def set_plot_all(self):
43 """Choose to plot every sensorgram."""
44 for ob in self.roi: ob.plottable = True
45
46 def set_plot_list(self, ilist):
47 """Choose a list of sensorgrams to plot"""
48 for ob in self.roi: ob.plottable = False
49 for i in ilist: self.roi[i].plottable = True
50
51 ## A pyplot feature for testing purposes.
52 def plot(self):
53 """Show plot of the selected sensorgrams."""
54 plt.clf()
55 plt.title('SPR Data plotted %s' % date.today().isoformat())
56 plt.xlabel('Time (s)')
57 plt.ylabel('SPR Response')
58 plt.grid(True)
59 ## Plot traces.
60 for ob in self.roi:
61 if (ob.plottable==True):
62 mylabel = "%i:%s" % (ob.index,ob.name)
63 plt.plot(ob.time, ob.value, label=mylabel)
64 plt.legend(loc='best')
65 plt.show()
66 ### End of BiosensorArray class definition.
67
68
69 class RegOfInterest(object):
70 """This Region Of Interest class can hold one SPR sensorgram."""
71 def __init__(self, i, datapoint_size):
72 """
73 Each ROI in a list needs a unique ID number which will be i+1.
74 The time and value arrays must be allocated using datapoint_size.
75 """
76 self.uid = i+1 ## Unique ID integer. Never changes.
77 self.index = i ## Changes if ba size changes (add/remove rois).
78 self.time = np.zeros(datapoint_size, dtype=float) ## Usually seconds.
79 self.value = np.zeros(datapoint_size, dtype=float) ## Arbitrary units.
80 self.dpoints = datapoint_size ## Can use for bounds checking.
81 ## Useful optional information. Usually from GAL or Key files.
82 self.name = "Spot%i" % (i+1)
83 self.desc = "Description"
84 self.gridx = 0 ## Can be Block number from GAL file.
85 self.gridy = 0 ## Unused?
86 self.spotx = 0 ## ROI column number.
87 self.spoty = 0 ## ROI row number.
88 self.bgroi = [0] ## One or more background ROIs.
89 self.calibM = 1 ## Slope used for calibration
90 self.calibB = 0 ## Intercept used for calibration.
91 self.plottable = True ## Whether to plot
92 ## Optional injection information. Usually from Clamp or ICM Method files.
93 self.injconc = [0.0] ## One or more analyte concentrations.
94 self.injstart = [0.0] ## One or more injection start times.
95 self.injstop = [0.0] ## One or more injection start times.
96 self.injrind = [0.0] ## One or more expected refractive index jumps.
97 self.flow = 0 ## Flowrate of injection.
98 ## Curve fitting information. Model and model parameters.
99 ## Example model is reference to function like data=simple1to1(times,params)
100 ## Example params = {'Rmax': {'value':1, 'min':0, 'max':10, 'fixed':False} }
101 self.model = None ## Model describing this roi. Reference to a function.
102 self.params = [] ## Parameters for this model. A dictionary of dictionaries.
103
104 def time2dp(self, t):
105 """Find datapoint closest to given time."""
106 pos2 = self.time.searchsorted(t) ## Time point just after t.
107 pos2 = min(pos2, len(self.time)-1) ## Avoid indexing error.
108 pos1 = max(pos2-1,0) ## Time point just before t.
109 t2 = abs(self.time[pos2] - t)
110 t1 = abs(self.time[pos1] - t)
111 ## Decide if time point just before or just after is closer.
112 if (t2<t1):
113 return pos2
114 else:
115 return pos1
116
117 def time2val(self, t1, t2):
118 """Return list of SPR values between t1 and t2"""
119 dp1, dp2 = self.time2dp(t1), self.time2dp(t2)
120 return [self.value[i] for i in range(dp1, dp2)]
121
122 ## End of RegOfInterest definition.
123
124
125 ## Here are a few lines to test this class.
126 if __name__ == '__main__':
127 print "Starting demo..."
128 print "Test plotting..."
129 x = BiosensorArray(10,10)
130 x.roi[0].time = np.arange(10)
131 x.roi[0].value = np.arange(10)**2
132 x.roi[1].time = np.arange(10)
133 x.roi[1].value = np.arange(10)**1.5
134 x.roi[9].time = np.arange(10)
135 x.roi[9].value = np.arange(10)**1
136 #x.set_plot_all()
137 x.set_plot_list([0,1,9])
138 x.plot()
139 print "Test xy2uid... 9 =",
140 x.roi[9].gridx = 2
141 print x.xy2uid(2,0,0,0)
142 print "Test time2dp... 5.6 =>",
143 print x.roi[9].time2dp(5.6)
144 print "Demo finished."
145
146
147 ################################# End of module #################################