ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/osprai/osprai/trunk/fit_module.py
Revision: 19
Committed: Fri Apr 23 01:45:38 2010 UTC (9 years, 1 month ago) by clausted
File size: 2528 byte(s)
Log Message:
Introduction of the fit_module.  This provides ordinary Levenberg-Marquart curvefitting.  The user can choose which model parameters are fixed and which are allowed to float.  Next, we can add a constrained version.

Line File contents
1 """
2 fit: Curve-fitting module for SPRI data.
3 Christopher Lausted, Institute for Systems Biology,
4 OSPRAI developers
5 Last modified on 100422 (yymmdd)
6
7 Example:
8 #import fit_module as fit
9 #import mdl_module as mdl
10 #ba1.roi[0].model = mdl.drift
11 #ba1.roi[0].params = {'rate': {'value':1, 'min':-100.0, 'max':100.0, 'fixed':False} }
12 #success = lma(ba1.roi[0])
13 #for i in ba1.roi: lma(i)
14 """
15 __version__ = "100422"
16
17
18 ## Import libraries
19 import ba_class as ba
20 import numpy as np
21 from scipy.optimize import leastsq
22 from copy import deepcopy
23
24
25 def lma(roi):
26 """
27 Normal Levenberg-Marquart fitting based on SciPy.
28 This function takes a single ba_class RegionOfInterest object (roi).
29 It modifies roi.params in place. It returns the number of iterations completed.
30 """
31 time = roi.time
32 data = roi.value
33 params = roi.params
34 checkparams(params)
35 ## Create list initial values for the floating parameters.
36 p0 = [dict['value'] for key,dict in params.iteritems() if (dict['fixed'] != True)]
37 ## Error function.
38 erf = lambda p: (model_interface(roi, time, data, p) - data)
39 ## Fit.
40 #p1, success = leastsq(erf, p0, args=(), maxfev=10000)
41 p1, success = leastsq(erf, p0, maxfev=10000)
42 return success
43 ## End of constlma() function.
44
45
46 def model_interface(roi, time, data, pfloat):
47 """
48 Use the model assigned to this roi to simulation data vs time.
49 Provide a list of values for the floating parameters (pfloat).
50 This function will write the values to the parameter dictionary (roi.params).
51 This allows the LMA fitter to adjust the parameters in place.
52 """
53 for i,key in enumerate(roi.params):
54 if (roi.params[key]['fixed'] != True):
55 roi.params[key]['value'] = pfloat[i]
56 return roi.model(time, data, roi.params)
57
58
59 def checkparams(params):
60 """
61 Check that each dictionary in the params dictionary contains the four
62 keys (value, min, max, fixed) and add them if necessary. Default is 'fixed':True.
63 """
64 for key,dict in params.iteritems():
65 if ('value' not in dict.keys()): dict['value'] = 0
66 if ('min' not in dict.keys()): dict['min'] = dict['value']
67 if ('max' not in dict.keys()): dict['max'] = dict['value']
68 if ('fixed' not in dict.keys()): dict['fixed'] = True
69 return
70 ## End of checkparams() function.
71
72
73 ################################# End of module #################################