ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/osprai/osprai/trunk/ba_class.py
(Generate patch)
# Line 1 | Line 1
1   """
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.
2 > ba_class
3 > --------
4 >
5 > Biosensor Array class for storing SPRI data.
6 > This contains an array of SPR sensorgrams with their
7 > associated models and parameters.
8 > This can also contain the microarray geometery.
9 >
10 > .. moduleauthor:: Christopher Lausted,
11 >                  Institute for Systems Biology,
12 >                  Yuhang Wan,
13 >                  OSPRAI developers.  
14 >                  
15 > Examples::
16 >
17 >  >>> ba1 = BiosensorArray(800,1500)     ## Allocate object with 800 spots of 1500 time points.
18 >  >>> ba1.roi[799].time[1499] = 7502.1   ## Set time in seconds.
19 >  >>> ba1.roi[799].value[1499] = 0.50    ## Set SPR reflectance signal.
20 >  >>> ba1.roi[799].name = "anti-IgG"     ## Set name of microarray feature.
21 >  >>> print ba1.roi[799].name
22 >  anti-IgG
23 >  >>> ba1 = BiosensorArray(1, 300)
24 >  >>> ba1.roi[0].simulate(bulkRI=1000, kon=1e4, koff=1e-2, conc=1e-6)
25 >  >>> print round(ba1.roi[0].value[299], 2)
26 >  160.64
27   """
28 < __version__ = "100408"
28 > __version__ = "110426"
29 >
30  
31   ## Import libraries.
32   import numpy as np
16 import matplotlib.pyplot as plt
33   from datetime import date
34  
35  
36   class BiosensorArray(object):
37 <    """The Biosensor Array class holds all ROIs/spots from an SPRI microarray run."""
37 >    """
38 >    The Biosensor Array class holds all ROIs (spots)
39 >    from an SPRI microarray run.
40 >    
41 >    ================ =============== =======================================
42 >    Property         Type            Description
43 >    ---------------- --------------- ---------------------------------------
44 >    roi              list of object  List of RegOfInterest objects.
45 >    rois             integer         Size of roi (Number of ROIs).
46 >    dpoints          integer         Number of datapoints in each ROI.
47 >    primarydatafiles list of string  List of file names.
48 >    comments         list of string  List of comments regarding experiments.
49 >    ================ =============== =======================================
50 >    """
51 >    
52      def __init__(self, roi_size, datapoint_size):
53          """This object is dimensioned upon initialization.""" ## Might improve speed.
54          ## Use a list comprehension to dimension list of classes.
# Line 29 | Line 59
59          ## Use these to keep track of laboratory notes.
60          self.primarydatafiles = [""]  ## Like "spritdata.txt"
61          self.comments = [""]          ## Like "Antibody data from 1 Jan 2010"
62 +        return
63          
64      def xy2uid(self, gx, gy, x, y):
65          """Given roi coordinates, find corresponding uid (index)."""
66          coor1 = (gx, gy, x, y)
67 <        for ob in self.roi:
68 <            coor2 = (ob.gridx, ob.gridy, ob.spotx, ob.spoty)
69 <            if (coor1==coor2): return ob.uid  ## Success.
67 >        for roi in self.roi:
68 >            coor2 = (roi.gridx, roi.gridy, roi.spotx, roi.spoty)
69 >            if (coor1==coor2): return roi.uid  ## Success.
70          return -1  ## Failure.
71          
72      def set_plot_all(self):
73          """Choose to plot every sensorgram."""
74 <        for ob in self.roi: ob.plottable = True
74 >        for roi in self.roi: roi.plottable = True
75 >        return
76          
77      def set_plot_list(self, ilist):
78          """Choose a list of sensorgrams to plot"""
79 <        for ob in self.roi: ob.plottable = False
79 >        for roi in self.roi: roi.plottable = False
80          for i in ilist: self.roi[i].plottable = True
81 <    
82 <    ## A pyplot feature for testing purposes.
83 <    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.
81 >        return
82 >        
83 >    """End of BiosensorArray class definition."""
84  
85  
86   class RegOfInterest(object):
87 <    """This Region Of Interest class can hold one SPR sensorgram."""
87 >    """
88 >    This Region Of Interest class can hold one SPR sensorgram.
89 >    
90 >    =========== =============== =============================================
91 >    Property    Type            Description
92 >    ----------- --------------- ---------------------------------------------
93 >    uid         integer         Unique ID integer. Never changes.
94 >    index       integer         Changes if ba size changes (add/remove rois).
95 >    time        nparray         Usually seconds.
96 >    value       nparray         Arbitrary units.
97 >    dpoints     integer         Can use for bounds checking.
98 >    name        string          Name of ROI.
99 >    desc        string          Description of ROI
100 >    
101 >    gridx       integer         Can be Block number from GAL file.  
102 >    gridy       integer         Unused?
103 >    spotx       integer         ROI column number.
104 >    spoty       integer         ROI row number.
105 >    bgroi       list of integer One or more background ROIs.
106 >    calibM      float           Slope used for calibration
107 >    calibB      float           Intercept used for calibration.
108 >    plottable   boolean         Whether to plot
109 >    
110 >    injconc     list of float   One or more analyte concentrations.
111 >    injstart    list of float   One or more injection start times.
112 >    injstop     list of float   One or more injection start times.
113 >    injrind     list of float   One or more expected refractive index jumps.
114 >    
115 >    flow        float           Flowrate of injection.
116 >    model       ref to funct    Model describing this ROI.
117 >    params      dict of dict    Parameters for this model.
118 >    =========== =============== =============================================
119 >    """
120 >    
121      def __init__(self, i, datapoint_size):
122          """
123          Each ROI in a list needs a unique ID number which will be i+1.
# Line 94 | Line 145
145          self.injstop = [0.0]     ## One or more injection start times.
146          self.injrind = [0.0]     ## One or more expected refractive index jumps.
147          self.flow = 0            ## Flowrate of injection.
148 +        ## Curve fitting information.  Model and model parameters.
149 +        ## Example model is reference to function like data=simple1to1(times,params)
150 +        ## Example params = {'Rmax': {'value':1, 'min':0, 'max':10, 'fixed':'float'} }
151 +        self.model = None    ## Model describing this roi. Reference to a function.
152 +        self.params = []     ## Parameters for this model. A dictionary of dictionaries.
153          
154      def time2dp(self, t):
155          """Find datapoint closest to given time."""
156 <        pos2 = self.time.searchsorted(t)  ## Time point just after t.
157 <        pos1 = max(pos2-1,0)
156 >        pos2 = self.time.searchsorted(t)    ## Time point just after t.
157 >        pos2 = min(pos2, len(self.time)-1)  ## Avoid indexing error.
158 >        pos1 = max(pos2-1,0)                ## Time point just before t.
159          t2 = abs(self.time[pos2] - t)
160          t1 = abs(self.time[pos1] - t)
161 +        ## Decide if time point just before or just after is closer.
162          if (t2<t1):
163              return pos2
164          else:
165              return pos1
166 <        
167 <    ## End of RegOfInterest definition.
166 >            
167 >    def time2val(self, t1, t2):
168 >        """Return list of SPR values between t1 and t2"""
169 >        dp1, dp2 = self.time2dp(t1), self.time2dp(t2)
170 >        return [self.value[i] for i in range(dp1, dp2)]
171  
172 <
173 < ## Here are a few lines to test this class.
174 < if __name__ == '__main__':
175 <    print "Starting demo..."
176 <    print "Test plotting..."
177 <    x = BiosensorArray(10,10)
178 <    x.roi[0].time = np.arange(10)
179 <    x.roi[0].value = np.arange(10)**2
180 <    x.roi[1].time = np.arange(10)
181 <    x.roi[1].value = np.arange(10)**1.5
182 <    x.roi[9].time = np.arange(10)
183 <    x.roi[9].value = np.arange(10)**1
184 <    #x.set_plot_all()
185 <    x.set_plot_list([0,1,9])
186 <    x.plot()
187 <    print "Test xy2uid... 9 =",
188 <    x.roi[9].gridx = 2
189 <    print x.xy2uid(2,0,0,0)
190 <    print "Test time2dp... 5.6 =>",
191 <    print x.roi[9].time2dp(5.6)
192 <    print "Demo finished."
193 <    
172 >    def simulate(self, bulkRI=1000, kon=1e4, koff=1e-2, conc=1e-6):
173 >        """
174 >        Fill ROI with simulated data from simple 1:1 binding.
175 >        The following parameters are hard-coded:
176 >          Time 35-65 features jump of bulkRI.
177 >          Time 100-200 has binding using kon, conc.
178 >          Also jump of bulkRI/10.
179 >          Time 200-300 has dissociation using koff.
180 >        The model formulas are:
181 >          alpha = c*kon+koff
182 >          Req = Rmax*c*kon / alpha
183 >          R = Req * [1 - exp(-t*alpha)]
184 >        """
185 >        ## Error checking.
186 >        if (koff <= 0): raise Exception, "Simulation koff must be >0"
187 >        if (kon < 0): raise Exception, "Simulation kon must be >=0"
188 >        if (conc < 0): raise Exception, "Simulation conc must be >=0"
189 >        ## Start with flat line for 300 sec.
190 >        self.time = np.arange(300)
191 >        self.value = np.zeros(300)
192 >        ## Add bulk refractive index jumps.
193 >        self.value[35:65] += bulkRI
194 >        self.value[100:199] += (0.1 * bulkRI)
195 >        ## Add binding.
196 >        rmax = 1000
197 >        alpha = conc * kon + koff
198 >        req = rmax * conc * kon / alpha
199 >        for t in range(100):
200 >             self.value[t+100] += req * (1 - np.exp(-t * alpha))
201 >        ## Add dissociation
202 >        response = req * (1 - np.exp(-100 * alpha))
203 >        for t in range(100):
204 >            self.value[t+200] += response * np.exp(-t * koff)
205 >        return
206      
207 < ################################# End of module #################################
208 < """
209 < class classSprArray:
210 <    time = np.zeros(0, dtype=float)  # 0,5,10...seconds.
211 <    sproi = []  # List of classSprRoi objects.
212 <    _calibrated = False  # Private variable.
213 <    _bgsubtracted = False  # Private variable.
214 <    
215 <    ## Apply calibration factors to all data.
216 <    def calibrate(self):
217 <        self._calibrated = True
218 <        for i in self.sproi:
219 <            i.oldvalue = i.value.copy()
220 <            i.value = i.value * i.calibM + i.calibB
221 <    def calibrated(self):
222 <        return self._calibrated
223 <        
224 <    ## Apply background subtraction
225 <    def bgsubtract(self):
226 <        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
207 >    """End of RegOfInterest definition."""
208 >
209 >
210 > def _test():
211 >    """
212 >    Automatic Code testing with doctest.
213 >    Doctest runs the example code in the docstrings.
214 >    Enable use of ellipses as wildcard for returned text.
215 >    """
216 >    import doctest
217 >    doctest.testmod(optionflags=doctest.ELLIPSIS)
218 >
219 >
220 > if __name__ == "__main__":
221 >    """
222 >    Code testing.  
223 >    Simply execute 'python ba_class.py'.
224 >    """
225 >    _test()
226 >
227  
187 """
228 + ########################### End of module ############################

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines