ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/osprai/osprai/trunk/fit_module.py
(Generate patch)
# Line 22 | Line 22
22                    OSPRAI developers.
23                    
24   Examples::
25 <
26 <  >>> import fit_module as fit
27 <  >>> import mdl_module as mdl
28 <  >>> ba.roi[0].model = mdl.drift
29 <  >>> ba.roi[1].model = mdl.drift
30 <  >>> p1 = {'rate': {'value':1.0, 'min':-100.0, 'max':100.0, 'fixed':'float'} }
31 <  >>> p2 = dict(rate=dict(value=1.0, min=-100.0, max=100.0, fixed=True))
32 <  >>> ba.roi[0].params = p1
33 <  >>> ba.roi[1].params = p2
34 <  >>> i = mclma(ba.roi)
25 >  
26 >  >>> import osprai_one as osp, numpy as np
27 >  >>> ba1 = osp.BiosensorArray(1,300)
28 >  >>> roi = ba1.roi[0]
29 >  >>> ## Simple 1to1 binding curve.
30 >  >>> ## Note KD = 2.2e-2 / 4.4e-4 = 5e-7, log10(5e-7) = -6.3
31 >  >>> roi.simulate(bulkRI=0.0, kon=4.4e4, koff=2.2e-2, conc=7.7e-7)
32 >  >>> ## Create a copy ba2 and use for fitting three parameters.
33 >  >>> ba2 = osp.deepcopy(ba1)
34 >  >>> roi = ba2.roi[0]
35 >  >>> roi.model = osp.simple1to1
36 >  >>> roi.params = osp.simple1to1_def_params()
37 >  >>> roi.params['rmax']['fixed'] = 'float'
38 >  >>> roi.params['kon']['fixed'] = 'float'
39 >  >>> roi.params['koff']['fixed'] = 'float'
40 >  >>> roi.params['conc']['value'] = 7.7e-7
41 >  >>> ## Do curvefitting, then check result.
42 >  >>> osp.mclma(ba2.roi, verbose=False)
43 >  2
44 >  >>> roi.value = osp.zeros(len(roi.value))
45 >  >>> roi.value = roi.model(roi.time, roi.value, roi.params)
46 >  >>> kD = float(roi.params['koff']['value']) / float(roi.params['kon']['value'])
47 >  >>> print round((np.log10(kD)), 1)
48 >  -6.3
49 >  
50   """
51 < __version__ = "110216"
51 > __version__ = "110519"
52  
53  
54   ## Import libraries
# Line 163 | Line 178
178          if (params[key]['fixed'] != True):
179              a, b = params[key]['min'], params[key]['max']
180              p0[i] = __itransform(a, b, float(p0[i]))
166            #Next line for troublshooting.
167            #print key, params[key]['value'], p0[i]
181      
182      ## Fit.
183      p1, success = leastsq(__cerf, p0, args=(roi), maxfev=999)
# Line 193 | Line 206
206      """End of constrained lma erf() function."""
207      
208    
209 < def mclma(rois):
209 > def mclma(rois, maxiter=999, verbose=True):
210      """
211      *Multiple-curve Constrained Levenberg-Marquart Algorithm.*
212      Least-squares curve-fitting is performed on the data in the specified ROIs.
213      The ROIs must contain SPR data, a model, and initial (guess) parameters.
214      The roi.params values are modified in place.
215 <    The maximum number of iterations is set to 999.
215 >    The ``maxiter`` specifies the maximum number of iterations (default 999).
216 >    The ``verbose`` option is used to display progress (default True).
217      
218      :param rois: ROI containing data, a model, and initial parameter guesses.
219      :type rois: List of RegOfInterest
# Line 221 | Line 235
235                  ## Perform transform based on min/max constraints.
236                  a, b = float(pd['min']), float(pd['max'])
237                  pval[-1] = __itransform(a, b, float(pval[-1]))
238 <                ## Print out intial guess and its transform. Temporary.
239 <                print pkey, pd['value'], pval[-1]
238 >                ## Print intial guess and its transform, if wanted.
239 >                if verbose: print pkey, pd['value'], pval[-1]
240              else:  
241                  ## Shared, fixed to a floating parameter in another ROI.
242                  pass
243      
244      ## Fit.
245 <    p1, success = leastsq(__mcerf, pval, args=(rois), maxfev=999)
245 >    p1, success = leastsq(__mcerf, pval, args=(rois,verbose), maxfev=maxiter)
246      return success
247      """End of multi-roi constrained lma() function."""
248      
249      
250 < def __mcerf(pfloat, rois):
250 > def __mcerf(pfloat, rois, verbose=True):
251      """
252      Error estimation function for use with constrained LMA.
253      Use the model assigned to this roi to simulation data vs time.  
# Line 247 | Line 261
261      ## Insert the new guesses from pfloat into ROI parameters.
262      ## First, get all of the floating parameters done.
263      for j,roi in enumerate(rois):
264 <        print j, # Temp
264 >        if verbose: print j,
265          ## For each parameter with its dictionary...
266          for pkey,pd in roi.params.iteritems():
267              if (pd['fixed'] == 'float'):
# Line 255 | Line 269
269                  i += 1
270                  a, b = float(pd['min']), float(pd['max'])
271                  pd['value'] = __transform(a, b, pfloat[i])
272 <                print "%s %.4f" % (pkey, pd['value']), # Temp.
272 >                ## Print current state of floating param, if wanted.
273 >                if verbose: print "%s %.4f" % (pkey, pd['value']),
274                  
275      ## Second, do the floating parameters shared across ROIs.
276      for j,roi in enumerate(rois):
# Line 272 | Line 287
287      for roi in rois:
288          e = roi.model(roi.time, roi.value, roi.params) - roi.value
289          erf = hstack( (erf, e) )  ## Concatenation of nparrays.
290 <    print "ssq %0.1f" % sum(erf**2) # Temp.
290 >    ## Print sum of squares value, if wanted.
291 >    if verbose: print "ssq %0.1f" % sum(erf**2)
292      
293      return erf
294      """End of multi-roi constrained lma error function mcerf()."""
279    
280    
281 ################################# End of module #################################
295 +
296 +
297 +
298 + def _test():
299 +    """
300 +    Automatic Code testing with doctest.
301 +    Enable use of ellipses as wildcard for returned text.
302 +    Doctest runs the example code in the docstrings.
303 +    """
304 +    import doctest
305 +    doctest.testmod(optionflags=doctest.ELLIPSIS)
306 +    return
307 +
308 + if __name__ == "__main__":
309 +    """Use 'python fit_module.py' for code testing."""
310 +    _test()
311 +
312 +
313 + ################################# End of module #################################

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines