1 | |
---|
2 | |
---|
3 | """ |
---|
4 | ScipyFitting module contains FitArrange , ScipyFit, |
---|
5 | Parameter classes.All listed classes work together to perform a |
---|
6 | simple fit with scipy optimizer. |
---|
7 | """ |
---|
8 | |
---|
9 | import numpy |
---|
10 | from scipy import optimize |
---|
11 | |
---|
12 | from AbstractFitEngine import FitEngine, SansAssembly,FitAbort |
---|
13 | |
---|
14 | class fitresult(object): |
---|
15 | """ |
---|
16 | Storing fit result |
---|
17 | """ |
---|
18 | def __init__(self, model=None, paramList=None): |
---|
19 | self.calls = None |
---|
20 | self.fitness = None |
---|
21 | self.chisqr = None |
---|
22 | self.pvec = None |
---|
23 | self.cov = None |
---|
24 | self.info = None |
---|
25 | self.mesg = None |
---|
26 | self.success = None |
---|
27 | self.stderr = None |
---|
28 | self.parameters = None |
---|
29 | self.model = model |
---|
30 | self.paramList = paramList |
---|
31 | |
---|
32 | def set_model(self, model): |
---|
33 | """ |
---|
34 | """ |
---|
35 | self.model = model |
---|
36 | |
---|
37 | def set_fitness(self, fitness): |
---|
38 | """ |
---|
39 | """ |
---|
40 | self.fitness = fitness |
---|
41 | |
---|
42 | def __str__(self): |
---|
43 | """ |
---|
44 | """ |
---|
45 | if self.pvec == None and self.model is None and self.paramList is None: |
---|
46 | return "No results" |
---|
47 | n = len(self.model.parameterset) |
---|
48 | |
---|
49 | result_param = zip(xrange(n), self.model.parameterset) |
---|
50 | L = ["P%-3d %s......|.....%s"%(p[0], p[1], p[1].value) for p in result_param if p[1].name in self.paramList ] |
---|
51 | L.append("=== goodness of fit: %s"%(str(self.fitness))) |
---|
52 | return "\n".join(L) |
---|
53 | |
---|
54 | def print_summary(self): |
---|
55 | """ |
---|
56 | """ |
---|
57 | print self |
---|
58 | |
---|
59 | class ScipyFit(FitEngine): |
---|
60 | """ |
---|
61 | ScipyFit performs the Fit.This class can be used as follow: |
---|
62 | #Do the fit SCIPY |
---|
63 | create an engine: engine = ScipyFit() |
---|
64 | Use data must be of type plottable |
---|
65 | Use a sans model |
---|
66 | |
---|
67 | Add data with a dictionnary of FitArrangeDict where Uid is a key and data |
---|
68 | is saved in FitArrange object. |
---|
69 | engine.set_data(data,Uid) |
---|
70 | |
---|
71 | Set model parameter "M1"= model.name add {model.parameter.name:value}. |
---|
72 | |
---|
73 | :note: Set_param() if used must always preceded set_model() |
---|
74 | for the fit to be performed.In case of Scipyfit set_param is called in |
---|
75 | fit () automatically. |
---|
76 | |
---|
77 | engine.set_param( model,"M1", {'A':2,'B':4}) |
---|
78 | |
---|
79 | Add model with a dictionnary of FitArrangeDict{} where Uid is a key and model |
---|
80 | is save in FitArrange object. |
---|
81 | engine.set_model(model,Uid) |
---|
82 | |
---|
83 | engine.fit return chisqr,[model.parameter 1,2,..],[[err1....][..err2...]] |
---|
84 | chisqr1, out1, cov1=engine.fit({model.parameter.name:value},qmin,qmax) |
---|
85 | """ |
---|
86 | def __init__(self): |
---|
87 | """ |
---|
88 | Creates a dictionary (self.fitArrangeDict={})of FitArrange elements |
---|
89 | with Uid as keys |
---|
90 | """ |
---|
91 | self.fitArrangeDict={} |
---|
92 | self.paramList=[] |
---|
93 | #def fit(self, *args, **kw): |
---|
94 | # return profile(self._fit, *args, **kw) |
---|
95 | |
---|
96 | def fit(self, q=None, handler=None, curr_thread=None): |
---|
97 | """ |
---|
98 | """ |
---|
99 | fitproblem=[] |
---|
100 | for id ,fproblem in self.fitArrangeDict.iteritems(): |
---|
101 | if fproblem.get_to_fit()==1: |
---|
102 | fitproblem.append(fproblem) |
---|
103 | if len(fitproblem)>1 : |
---|
104 | msg = "Scipy can't fit more than a single fit problem at a time." |
---|
105 | raise RuntimeError, msg |
---|
106 | return |
---|
107 | elif len(fitproblem)==0 : |
---|
108 | raise RuntimeError, "No Assembly scheduled for Scipy fitting." |
---|
109 | return |
---|
110 | |
---|
111 | listdata=[] |
---|
112 | model = fitproblem[0].get_model() |
---|
113 | listdata = fitproblem[0].get_data() |
---|
114 | # Concatenate dList set (contains one or more data)before fitting |
---|
115 | data = listdata |
---|
116 | self.curr_thread= curr_thread |
---|
117 | result = fitresult(model=model, paramList=self.paramList) |
---|
118 | if handler is not None: |
---|
119 | handler.set_result(result=result) |
---|
120 | #try: |
---|
121 | functor = SansAssembly(self.paramList, model, data, handler=handler, |
---|
122 | fitresult=result,curr_thread= self.curr_thread) |
---|
123 | |
---|
124 | |
---|
125 | out, cov_x, info, mesg, success = optimize.leastsq(functor, |
---|
126 | model.getParams(self.paramList), |
---|
127 | full_output=1, warning=True) |
---|
128 | |
---|
129 | chisqr = functor.chisq(out) |
---|
130 | |
---|
131 | if cov_x is not None and numpy.isfinite(cov_x).all(): |
---|
132 | stderr = numpy.sqrt(numpy.diag(cov_x)) |
---|
133 | else: |
---|
134 | stderr = None |
---|
135 | if not (numpy.isnan(out).any()) or ( cov_x !=None) : |
---|
136 | result.fitness = chisqr |
---|
137 | result.stderr = stderr |
---|
138 | result.pvec = out |
---|
139 | result.success = success |
---|
140 | #print result |
---|
141 | if q is not None: |
---|
142 | #print "went here" |
---|
143 | q.put(result) |
---|
144 | #print "get q scipy fit enfine",q.get() |
---|
145 | return q |
---|
146 | return result |
---|
147 | else: |
---|
148 | raise ValueError, "SVD did not converge"+str(success) |
---|
149 | |
---|
150 | |
---|
151 | |
---|
152 | def profile(fn, *args, **kw): |
---|
153 | import cProfile, pstats, os |
---|
154 | global call_result |
---|
155 | def call(): |
---|
156 | global call_result |
---|
157 | call_result = fn(*args, **kw) |
---|
158 | cProfile.runctx('call()', dict(call=call), {}, 'profile.out') |
---|
159 | stats = pstats.Stats('profile.out') |
---|
160 | #stats.sort_stats('time') |
---|
161 | stats.sort_stats('calls') |
---|
162 | stats.print_stats() |
---|
163 | os.unlink('profile.out') |
---|
164 | return call_result |
---|
165 | |
---|
166 | |
---|