[aa36f96] | 1 | |
---|
| 2 | |
---|
[792db7d5] | 3 | """ |
---|
[aa36f96] | 4 | ScipyFitting module contains FitArrange , ScipyFit, |
---|
| 5 | Parameter classes.All listed classes work together to perform a |
---|
| 6 | simple fit with scipy optimizer. |
---|
[792db7d5] | 7 | """ |
---|
[61cb28d] | 8 | |
---|
[88b5e83] | 9 | import numpy |
---|
[511c6810] | 10 | import sys |
---|
[2446b66] | 11 | |
---|
[7705306] | 12 | |
---|
[b2f25dc5] | 13 | from sans.fit.AbstractFitEngine import FitEngine |
---|
| 14 | from sans.fit.AbstractFitEngine import SansAssembly |
---|
[511c6810] | 15 | from sans.fit.AbstractFitEngine import FitAbort |
---|
[634ca14] | 16 | from sans.fit.AbstractFitEngine import Model |
---|
[444c900e] | 17 | from sans.fit.AbstractFitEngine import FResult |
---|
[88b5e83] | 18 | |
---|
[4c718654] | 19 | class ScipyFit(FitEngine): |
---|
[7705306] | 20 | """ |
---|
[aa36f96] | 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) |
---|
[7705306] | 45 | """ |
---|
[792db7d5] | 46 | def __init__(self): |
---|
| 47 | """ |
---|
[b2f25dc5] | 48 | Creates a dictionary (self.fit_arrange_dict={})of FitArrange elements |
---|
[aa36f96] | 49 | with Uid as keys |
---|
[792db7d5] | 50 | """ |
---|
[b2f25dc5] | 51 | FitEngine.__init__(self) |
---|
| 52 | self.fit_arrange_dict = {} |
---|
| 53 | self.param_list = [] |
---|
[c4d6900] | 54 | self.curr_thread = None |
---|
[d9dc518] | 55 | #def fit(self, *args, **kw): |
---|
| 56 | # return profile(self._fit, *args, **kw) |
---|
[393f0f3] | 57 | |
---|
[93de635d] | 58 | def fit(self, q=None, handler=None, curr_thread=None, ftol=1.49012e-8): |
---|
[aa36f96] | 59 | """ |
---|
| 60 | """ |
---|
[89f3b66] | 61 | fitproblem = [] |
---|
[c4d6900] | 62 | for fproblem in self.fit_arrange_dict.itervalues(): |
---|
[89f3b66] | 63 | if fproblem.get_to_fit() == 1: |
---|
[393f0f3] | 64 | fitproblem.append(fproblem) |
---|
[89f3b66] | 65 | if len(fitproblem) > 1 : |
---|
[e0072082] | 66 | msg = "Scipy can't fit more than a single fit problem at a time." |
---|
| 67 | raise RuntimeError, msg |
---|
[a9e04aa] | 68 | return |
---|
[89f3b66] | 69 | elif len(fitproblem) == 0 : |
---|
[a9e04aa] | 70 | raise RuntimeError, "No Assembly scheduled for Scipy fitting." |
---|
| 71 | return |
---|
| 72 | |
---|
[89f3b66] | 73 | listdata = [] |
---|
[393f0f3] | 74 | model = fitproblem[0].get_model() |
---|
| 75 | listdata = fitproblem[0].get_data() |
---|
[792db7d5] | 76 | # Concatenate dList set (contains one or more data)before fitting |
---|
[e0072082] | 77 | data = listdata |
---|
[852354c8] | 78 | |
---|
[89f3b66] | 79 | self.curr_thread = curr_thread |
---|
[93de635d] | 80 | ftol = ftol |
---|
[852354c8] | 81 | |
---|
| 82 | # Check the initial value if it is within range |
---|
| 83 | self._check_param_range(model) |
---|
| 84 | |
---|
[444c900e] | 85 | result = FResult(model=model, data=data, param_list=self.param_list) |
---|
[852354c8] | 86 | if handler is not None: |
---|
| 87 | handler.set_result(result=result) |
---|
[511c6810] | 88 | try: |
---|
[2446b66] | 89 | # This import must be here; otherwise it will be confused when more |
---|
| 90 | # than one thread exist. |
---|
| 91 | from scipy import optimize |
---|
| 92 | |
---|
| 93 | functor = SansAssembly(self.param_list, model, data, handler=handler,\ |
---|
| 94 | fitresult=result, curr_thread= curr_thread) |
---|
[db427ec] | 95 | out, cov_x, _, mesg, success = optimize.leastsq(functor, |
---|
[c4d6900] | 96 | model.get_params(self.param_list), |
---|
[852354c8] | 97 | ftol=ftol, |
---|
[c4d6900] | 98 | full_output=1, |
---|
| 99 | warning=True) |
---|
[425e49ca] | 100 | |
---|
[acfff8b] | 101 | except KeyboardInterrupt: |
---|
| 102 | msg = "Fitting: Terminated!!!" |
---|
| 103 | handler.error(msg) |
---|
| 104 | raise KeyboardInterrupt, msg #<= more stable |
---|
| 105 | #less stable below |
---|
| 106 | """ |
---|
| 107 | if hasattr(sys, 'last_type') and sys.last_type == KeyboardInterrupt: |
---|
[852354c8] | 108 | if handler is not None: |
---|
[acfff8b] | 109 | msg = "Fitting: Terminated!!!" |
---|
| 110 | handler.error(msg) |
---|
[852354c8] | 111 | result = handler.get_result() |
---|
| 112 | return result |
---|
[511c6810] | 113 | else: |
---|
| 114 | raise |
---|
[acfff8b] | 115 | """ |
---|
[e0e22f2c] | 116 | except: |
---|
| 117 | raise |
---|
[c4d6900] | 118 | chisqr = functor.chisq() |
---|
[fd6b789] | 119 | if cov_x is not None and numpy.isfinite(cov_x).all(): |
---|
| 120 | stderr = numpy.sqrt(numpy.diag(cov_x)) |
---|
| 121 | else: |
---|
[e0072082] | 122 | stderr = None |
---|
[511c6810] | 123 | |
---|
[852354c8] | 124 | if not (numpy.isnan(out).any()) and (cov_x != None): |
---|
| 125 | result.fitness = chisqr |
---|
| 126 | result.stderr = stderr |
---|
| 127 | result.pvec = out |
---|
| 128 | result.success = success |
---|
[425e49ca] | 129 | result.theory = functor.theory |
---|
[d91d2c9] | 130 | #print "scipy", result.inputs |
---|
[a15da09] | 131 | if q is not None: |
---|
[852354c8] | 132 | q.put(result) |
---|
| 133 | return q |
---|
[4fb520d] | 134 | if success < 1 or success > 5: |
---|
[120d9f6] | 135 | result = None |
---|
[444c900e] | 136 | return [result] |
---|
| 137 | """ |
---|
[120d9f6] | 138 | else: |
---|
| 139 | return None |
---|
[444c900e] | 140 | """ |
---|
[852354c8] | 141 | # Error will be present to the client, not here |
---|
| 142 | #else: |
---|
| 143 | # raise ValueError, "SVD did not converge" + str(mesg) |
---|
| 144 | |
---|
| 145 | def _check_param_range(self, model): |
---|
| 146 | """ |
---|
| 147 | Check parameter range and set the initial value inside |
---|
| 148 | if it is out of range. |
---|
| 149 | |
---|
| 150 | : model: park model object |
---|
| 151 | """ |
---|
| 152 | is_outofbound = False |
---|
| 153 | # loop through parameterset |
---|
| 154 | for p in model.parameterset: |
---|
| 155 | param_name = p.get_name() |
---|
| 156 | # proceed only if the parameter name is in the list of fitting |
---|
| 157 | if param_name in self.param_list: |
---|
| 158 | # if the range was defined, check the range |
---|
| 159 | if numpy.isfinite(p.range[0]): |
---|
| 160 | if p.value <= p.range[0]: |
---|
| 161 | # 10 % backing up from the border if not zero |
---|
| 162 | # for Scipy engine to work properly. |
---|
| 163 | shift = self._get_zero_shift(p.range[0]) |
---|
| 164 | new_value = p.range[0] + shift |
---|
| 165 | p.value = new_value |
---|
| 166 | is_outofbound = True |
---|
| 167 | if numpy.isfinite(p.range[1]): |
---|
| 168 | if p.value >= p.range[1]: |
---|
| 169 | shift = self._get_zero_shift(p.range[1]) |
---|
| 170 | # 10 % backing up from the border if not zero |
---|
| 171 | # for Scipy engine to work properly. |
---|
| 172 | new_value = p.range[1] - shift |
---|
| 173 | # Check one more time if the new value goes below |
---|
| 174 | # the low bound, If so, re-evaluate the value |
---|
| 175 | # with the mean of the range. |
---|
| 176 | if numpy.isfinite(p.range[0]): |
---|
| 177 | if new_value < p.range[0]: |
---|
| 178 | new_value = (p.range[0] + p.range[1]) / 2.0 |
---|
| 179 | # Todo: |
---|
| 180 | # Need to think about when both min and max are same. |
---|
| 181 | p.value = new_value |
---|
| 182 | is_outofbound = True |
---|
| 183 | |
---|
| 184 | return is_outofbound |
---|
| 185 | |
---|
| 186 | def _get_zero_shift(self, range): |
---|
| 187 | """ |
---|
| 188 | Get 10% shift of the param value = 0 based on the range value |
---|
| 189 | |
---|
| 190 | : param range: min or max value of the bounds |
---|
| 191 | """ |
---|
| 192 | if range == 0: |
---|
| 193 | shift = 0.1 |
---|
| 194 | else: |
---|
| 195 | shift = 0.1 * range |
---|
| 196 | |
---|
| 197 | return shift |
---|
| 198 | |
---|
[e0072082] | 199 | |
---|
[c4d6900] | 200 | #def profile(fn, *args, **kw): |
---|
| 201 | # import cProfile, pstats, os |
---|
| 202 | # global call_result |
---|
| 203 | # def call(): |
---|
| 204 | # global call_result |
---|
| 205 | # call_result = fn(*args, **kw) |
---|
| 206 | # cProfile.runctx('call()', dict(call=call), {}, 'profile.out') |
---|
| 207 | # stats = pstats.Stats('profile.out') |
---|
| 208 | # stats.sort_stats('time') |
---|
| 209 | # stats.sort_stats('calls') |
---|
| 210 | # stats.print_stats() |
---|
| 211 | # os.unlink('profile.out') |
---|
| 212 | # return call_result |
---|
[9c648c7] | 213 | |
---|
[48882d1] | 214 | |
---|