ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/osprai/osprai/trunk/ba_class.py
Revision: 7
Committed: Fri Apr 9 17:11:42 2010 UTC (8 years, 11 months ago) by clausted
File size: 6934 byte(s)
Log Message:
Initial addition of ba_class, an alternative to SPRdataclass.  This class, ba or Biosensor Array, has one internal structure rather than different internal structures depending on whether SPRit or Biacore or other data was imported.  This makes the code smaller and more readable.  It provides default values, usually 0 or null text, that make it easier to import and export different file formats.  We also add io_module to provide import and export features.  We also add test.py as a convenience for testing and demonstration.
Line User Rev File contents
1 clausted 7 """
2     ba: Biosensor Array class for storing SPRI data.
3     Christopher Lausted, Institute for Systems Biology
4     Last modified on 100408 (yymmdd)
5    
6     Examples:
7     #ba1 = BiosensorArray(800,1500) ## Allocate object with 800 spots of 1500 time points.
8     #ba1.roi[799].time[1499] = 7502.1 ## Set time in seconds.
9     #ba1.roi[799].value[1499] = 0.50 ## Set SPR reflectance signal.
10     #ba1.roi[799].name = "anti-IgG" ## Set name of microarray feature.
11     """
12     __version__ = "100408"
13    
14     ## Import libraries.
15     import numpy as np
16     import matplotlib.pyplot as plt
17     from datetime import date
18    
19    
20     class BiosensorArray(object):
21     """The Biosensor Array class holds all ROIs/spots from an SPRI microarray run."""
22     def __init__(self, roi_size, datapoint_size):
23     """This object is dimensioned upon initialization.""" ## Might improve speed.
24     ## Use a list comprehension to dimension list of classes.
25     self.roi = [RegOfInterest(i,datapoint_size) for i in range(roi_size)]
26     ## Remember the dimensions for quick bounds-checking later.
27     self.rois = roi_size
28     self.dpoints = datapoint_size
29     ## Use these to keep track of laboratory notes.
30     self.primarydatafiles = [""] ## Like "spritdata.txt"
31     self.comments = [""] ## Like "Antibody data from 1 Jan 2010"
32    
33     def xy2uid(self, gx, gy, x, y):
34     """Given roi coordinates, find corresponding uid (index)."""
35     coor1 = (gx, gy, x, y)
36     for ob in self.roi:
37     coor2 = (ob.gridx, ob.gridy, ob.spotx, ob.spoty)
38     if (coor1==coor2): return ob.uid ## Success.
39     return -1 ## Failure.
40    
41     def set_plot_all(self):
42     """Choose to plot every sensorgram."""
43     for ob in self.roi: ob.plottable = True
44    
45     def set_plot_list(self, ilist):
46     """Choose a list of sensorgrams to plot"""
47     for ob in self.roi: ob.plottable = False
48     for i in ilist: self.roi[i].plottable = True
49    
50     ## A pyplot feature for testing purposes.
51     def plot(self):
52     """Show plot of the selected sensorgrams."""
53     plt.clf()
54     plt.title('SPR Data plotted %s' % date.today().isoformat())
55     plt.xlabel('Time (s)')
56     plt.ylabel('SPR Response')
57     plt.grid(True)
58     ## Plot traces.
59     for ob in self.roi:
60     if (ob.plottable==True):
61     mylabel = "%i:%s" % (ob.index,ob.name)
62     plt.plot(ob.time, ob.value, label=mylabel)
63     plt.legend(loc='best')
64     plt.show()
65     ### End of BiosensorArray class definition.
66    
67    
68     class RegOfInterest(object):
69     """This Region Of Interest class can hold one SPR sensorgram."""
70     def __init__(self, i, datapoint_size):
71     """
72     Each ROI in a list needs a unique ID number which will be i+1.
73     The time and value arrays must be allocated using datapoint_size.
74     """
75     self.uid = i+1 ## Unique ID integer. Never changes.
76     self.index = i ## Changes if ba size changes (add/remove rois).
77     self.time = np.zeros(datapoint_size, dtype=float) ## Usually seconds.
78     self.value = np.zeros(datapoint_size, dtype=float) ## Arbitrary units.
79     self.dpoints = datapoint_size ## Can use for bounds checking.
80     ## Useful optional information. Usually from GAL or Key files.
81     self.name = "Spot%i" % (i+1)
82     self.desc = "Description"
83     self.gridx = 0 ## Can be Block number from GAL file.
84     self.gridy = 0 ## Unused?
85     self.spotx = 0 ## ROI column number.
86     self.spoty = 0 ## ROI row number.
87     self.bgroi = [0] ## One or more background ROIs.
88     self.calibM = 1 ## Slope used for calibration
89     self.calibB = 0 ## Intercept used for calibration.
90     self.plottable = True ## Whether to plot
91     ## Optional injection information. Usually from Clamp or ICM Method files.
92     self.injconc = [0.0] ## One or more analyte concentrations.
93     self.injstart = [0.0] ## One or more injection start times.
94     self.injstop = [0.0] ## One or more injection start times.
95     self.injrind = [0.0] ## One or more expected refractive index jumps.
96     self.flow = 0 ## Flowrate of injection.
97    
98     def time2dp(self, t):
99     """Find datapoint closest to given time."""
100     pos2 = self.time.searchsorted(t) ## Time point just after t.
101     pos1 = max(pos2-1,0)
102     t2 = abs(self.time[pos2] - t)
103     t1 = abs(self.time[pos1] - t)
104     if (t2<t1):
105     return pos2
106     else:
107     return pos1
108    
109     ## End of RegOfInterest definition.
110    
111    
112     ## Here are a few lines to test this class.
113     if __name__ == '__main__':
114     print "Starting demo..."
115     print "Test plotting..."
116     x = BiosensorArray(10,10)
117     x.roi[0].time = np.arange(10)
118     x.roi[0].value = np.arange(10)**2
119     x.roi[1].time = np.arange(10)
120     x.roi[1].value = np.arange(10)**1.5
121     x.roi[9].time = np.arange(10)
122     x.roi[9].value = np.arange(10)**1
123     #x.set_plot_all()
124     x.set_plot_list([0,1,9])
125     x.plot()
126     print "Test xy2uid... 9 =",
127     x.roi[9].gridx = 2
128     print x.xy2uid(2,0,0,0)
129     print "Test time2dp... 5.6 =>",
130     print x.roi[9].time2dp(5.6)
131     print "Demo finished."
132    
133    
134     ################################# End of module #################################
135     """
136     class classSprArray:
137     time = np.zeros(0, dtype=float) # 0,5,10...seconds.
138     sproi = [] # List of classSprRoi objects.
139     _calibrated = False # Private variable.
140     _bgsubtracted = False # Private variable.
141    
142     ## Apply calibration factors to all data.
143     def calibrate(self):
144     self._calibrated = True
145     for i in self.sproi:
146     i.oldvalue = i.value.copy()
147     i.value = i.value * i.calibM + i.calibB
148     def calibrated(self):
149     return self._calibrated
150    
151     ## Apply background subtraction
152     def bgsubtract(self):
153     self._bgsubtracted = True
154     for i in self.sproi:
155     i.oldvalue = i.value.copy()
156     for i in self.sproi:
157     if (i.bgroi<=len(self.sproi)):
158     i.value = i.value - self.sproi[i.bgroi].oldvalue
159     else:
160     print "Index out of range in classSprArray"
161     def bgsubtracted(self):
162     return self._bgsubtracted
163    
164     def addsproi(self):
165     newroi = classSprRoi()
166     self.sproi.append(newroi)
167    
168     ## End classSprArray definition.
169    
170     Unused examples:
171    
172     class Person(object):
173     def get_full_name(self):
174     return "%s %s" % (self.first_name, self.last_name)
175     def set_full_name(self, full_name):
176     self.first_name, self.last_name = full_name.split()
177     full_name = property(get_full_name, set_full_name)
178    
179     class Example(object):
180     def __init__(self):
181     self.data = []
182    
183     @property
184     def something(self):
185     return whatever
186    
187     """