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