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 | import sys |
---|
11 | from scipy import optimize |
---|
12 | |
---|
13 | from sans.fit.AbstractFitEngine import FitEngine |
---|
14 | from sans.fit.AbstractFitEngine import SansAssembly |
---|
15 | from sans.fit.AbstractFitEngine import FitAbort |
---|
16 | IS_MAC = True |
---|
17 | if sys.platform.count("win32") > 0: |
---|
18 | IS_MAC = False |
---|
19 | |
---|
20 | class fitresult(object): |
---|
21 | """ |
---|
22 | Storing fit result |
---|
23 | """ |
---|
24 | def __init__(self, model=None, param_list=None): |
---|
25 | self.calls = None |
---|
26 | self.fitness = None |
---|
27 | self.chisqr = None |
---|
28 | self.pvec = None |
---|
29 | self.cov = None |
---|
30 | self.info = None |
---|
31 | self.mesg = None |
---|
32 | self.success = None |
---|
33 | self.stderr = None |
---|
34 | self.parameters = None |
---|
35 | self.is_mac = IS_MAC |
---|
36 | self.model = model |
---|
37 | self.param_list = param_list |
---|
38 | self.iterations = 0 |
---|
39 | |
---|
40 | def set_model(self, model): |
---|
41 | """ |
---|
42 | """ |
---|
43 | self.model = model |
---|
44 | |
---|
45 | def set_fitness(self, fitness): |
---|
46 | """ |
---|
47 | """ |
---|
48 | self.fitness = fitness |
---|
49 | |
---|
50 | def __str__(self): |
---|
51 | """ |
---|
52 | """ |
---|
53 | if self.pvec == None and self.model is None and self.param_list is None: |
---|
54 | return "No results" |
---|
55 | n = len(self.model.parameterset) |
---|
56 | self.iterations += 1 |
---|
57 | result_param = zip(xrange(n), self.model.parameterset) |
---|
58 | msg1 = ["[Iteration #: %s ]" % self.iterations] |
---|
59 | msg3 = ["=== goodness of fit: %s ===" % (str(self.fitness))] |
---|
60 | if not self.is_mac: |
---|
61 | msg2 = ["P%-3d %s......|.....%s" % \ |
---|
62 | (p[0], p[1], p[1].value)\ |
---|
63 | for p in result_param if p[1].name in self.param_list] |
---|
64 | msg = msg1 + msg3 + msg2 |
---|
65 | else: |
---|
66 | msg = msg1 + msg3 |
---|
67 | msg = "\n".join(msg) |
---|
68 | return msg |
---|
69 | |
---|
70 | def print_summary(self): |
---|
71 | """ |
---|
72 | """ |
---|
73 | print self |
---|
74 | |
---|
75 | class ScipyFit(FitEngine): |
---|
76 | """ |
---|
77 | ScipyFit performs the Fit.This class can be used as follow: |
---|
78 | #Do the fit SCIPY |
---|
79 | create an engine: engine = ScipyFit() |
---|
80 | Use data must be of type plottable |
---|
81 | Use a sans model |
---|
82 | |
---|
83 | Add data with a dictionnary of FitArrangeDict where Uid is a key and data |
---|
84 | is saved in FitArrange object. |
---|
85 | engine.set_data(data,Uid) |
---|
86 | |
---|
87 | Set model parameter "M1"= model.name add {model.parameter.name:value}. |
---|
88 | |
---|
89 | :note: Set_param() if used must always preceded set_model() |
---|
90 | for the fit to be performed.In case of Scipyfit set_param is called in |
---|
91 | fit () automatically. |
---|
92 | |
---|
93 | engine.set_param( model,"M1", {'A':2,'B':4}) |
---|
94 | |
---|
95 | Add model with a dictionnary of FitArrangeDict{} where Uid is a key and model |
---|
96 | is save in FitArrange object. |
---|
97 | engine.set_model(model,Uid) |
---|
98 | |
---|
99 | engine.fit return chisqr,[model.parameter 1,2,..],[[err1....][..err2...]] |
---|
100 | chisqr1, out1, cov1=engine.fit({model.parameter.name:value},qmin,qmax) |
---|
101 | """ |
---|
102 | def __init__(self): |
---|
103 | """ |
---|
104 | Creates a dictionary (self.fit_arrange_dict={})of FitArrange elements |
---|
105 | with Uid as keys |
---|
106 | """ |
---|
107 | FitEngine.__init__(self) |
---|
108 | self.fit_arrange_dict = {} |
---|
109 | self.param_list = [] |
---|
110 | self.curr_thread = None |
---|
111 | #def fit(self, *args, **kw): |
---|
112 | # return profile(self._fit, *args, **kw) |
---|
113 | |
---|
114 | def fit(self, q=None, handler=None, curr_thread=None, ftol=1.49012e-8): |
---|
115 | """ |
---|
116 | """ |
---|
117 | fitproblem = [] |
---|
118 | for fproblem in self.fit_arrange_dict.itervalues(): |
---|
119 | if fproblem.get_to_fit() == 1: |
---|
120 | fitproblem.append(fproblem) |
---|
121 | if len(fitproblem) > 1 : |
---|
122 | msg = "Scipy can't fit more than a single fit problem at a time." |
---|
123 | raise RuntimeError, msg |
---|
124 | return |
---|
125 | elif len(fitproblem) == 0 : |
---|
126 | raise RuntimeError, "No Assembly scheduled for Scipy fitting." |
---|
127 | return |
---|
128 | |
---|
129 | listdata = [] |
---|
130 | model = fitproblem[0].get_model() |
---|
131 | listdata = fitproblem[0].get_data() |
---|
132 | # Concatenate dList set (contains one or more data)before fitting |
---|
133 | data = listdata |
---|
134 | |
---|
135 | self.curr_thread = curr_thread |
---|
136 | ftol = ftol |
---|
137 | |
---|
138 | # Check the initial value if it is within range |
---|
139 | self._check_param_range(model) |
---|
140 | |
---|
141 | result = fitresult(model=model, param_list=self.param_list) |
---|
142 | if handler is not None: |
---|
143 | handler.set_result(result=result) |
---|
144 | #try: |
---|
145 | functor = SansAssembly(self.param_list, model, data, handler=handler, |
---|
146 | fitresult=result, curr_thread= self.curr_thread) |
---|
147 | try: |
---|
148 | out, cov_x, _, mesg, success = optimize.leastsq(functor, |
---|
149 | model.get_params(self.param_list), |
---|
150 | ftol=ftol, |
---|
151 | full_output=1, |
---|
152 | warning=True) |
---|
153 | except KeyboardInterrupt: |
---|
154 | msg = "Fitting: Terminated!!!" |
---|
155 | handler.error(msg) |
---|
156 | raise KeyboardInterrupt, msg #<= more stable |
---|
157 | #less stable below |
---|
158 | """ |
---|
159 | if hasattr(sys, 'last_type') and sys.last_type == KeyboardInterrupt: |
---|
160 | if handler is not None: |
---|
161 | msg = "Fitting: Terminated!!!" |
---|
162 | handler.error(msg) |
---|
163 | result = handler.get_result() |
---|
164 | return result |
---|
165 | else: |
---|
166 | raise |
---|
167 | """ |
---|
168 | except: |
---|
169 | raise |
---|
170 | chisqr = functor.chisq() |
---|
171 | if cov_x is not None and numpy.isfinite(cov_x).all(): |
---|
172 | stderr = numpy.sqrt(numpy.diag(cov_x)) |
---|
173 | else: |
---|
174 | stderr = None |
---|
175 | |
---|
176 | if not (numpy.isnan(out).any()) and (cov_x != None): |
---|
177 | result.fitness = chisqr |
---|
178 | result.stderr = stderr |
---|
179 | result.pvec = out |
---|
180 | result.success = success |
---|
181 | if q is not None: |
---|
182 | q.put(result) |
---|
183 | return q |
---|
184 | if success < 1 or success > 5: |
---|
185 | result = None |
---|
186 | return result |
---|
187 | else: |
---|
188 | return None |
---|
189 | # Error will be present to the client, not here |
---|
190 | #else: |
---|
191 | # raise ValueError, "SVD did not converge" + str(mesg) |
---|
192 | |
---|
193 | def _check_param_range(self, model): |
---|
194 | """ |
---|
195 | Check parameter range and set the initial value inside |
---|
196 | if it is out of range. |
---|
197 | |
---|
198 | : model: park model object |
---|
199 | """ |
---|
200 | is_outofbound = False |
---|
201 | # loop through parameterset |
---|
202 | for p in model.parameterset: |
---|
203 | param_name = p.get_name() |
---|
204 | # proceed only if the parameter name is in the list of fitting |
---|
205 | if param_name in self.param_list: |
---|
206 | # if the range was defined, check the range |
---|
207 | if numpy.isfinite(p.range[0]): |
---|
208 | if p.value <= p.range[0]: |
---|
209 | # 10 % backing up from the border if not zero |
---|
210 | # for Scipy engine to work properly. |
---|
211 | shift = self._get_zero_shift(p.range[0]) |
---|
212 | new_value = p.range[0] + shift |
---|
213 | p.value = new_value |
---|
214 | is_outofbound = True |
---|
215 | if numpy.isfinite(p.range[1]): |
---|
216 | if p.value >= p.range[1]: |
---|
217 | shift = self._get_zero_shift(p.range[1]) |
---|
218 | # 10 % backing up from the border if not zero |
---|
219 | # for Scipy engine to work properly. |
---|
220 | new_value = p.range[1] - shift |
---|
221 | # Check one more time if the new value goes below |
---|
222 | # the low bound, If so, re-evaluate the value |
---|
223 | # with the mean of the range. |
---|
224 | if numpy.isfinite(p.range[0]): |
---|
225 | if new_value < p.range[0]: |
---|
226 | new_value = (p.range[0] + p.range[1]) / 2.0 |
---|
227 | # Todo: |
---|
228 | # Need to think about when both min and max are same. |
---|
229 | p.value = new_value |
---|
230 | is_outofbound = True |
---|
231 | |
---|
232 | return is_outofbound |
---|
233 | |
---|
234 | def _get_zero_shift(self, range): |
---|
235 | """ |
---|
236 | Get 10% shift of the param value = 0 based on the range value |
---|
237 | |
---|
238 | : param range: min or max value of the bounds |
---|
239 | """ |
---|
240 | if range == 0: |
---|
241 | shift = 0.1 |
---|
242 | else: |
---|
243 | shift = 0.1 * range |
---|
244 | |
---|
245 | return shift |
---|
246 | |
---|
247 | |
---|
248 | #def profile(fn, *args, **kw): |
---|
249 | # import cProfile, pstats, os |
---|
250 | # global call_result |
---|
251 | # def call(): |
---|
252 | # global call_result |
---|
253 | # call_result = fn(*args, **kw) |
---|
254 | # cProfile.runctx('call()', dict(call=call), {}, 'profile.out') |
---|
255 | # stats = pstats.Stats('profile.out') |
---|
256 | # stats.sort_stats('time') |
---|
257 | # stats.sort_stats('calls') |
---|
258 | # stats.print_stats() |
---|
259 | # os.unlink('profile.out') |
---|
260 | # return call_result |
---|
261 | |
---|
262 | |
---|