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