[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 |
---|
[7705306] | 11 | from scipy import optimize |
---|
| 12 | |
---|
[b2f25dc5] | 13 | from sans.fit.AbstractFitEngine import FitEngine |
---|
| 14 | from sans.fit.AbstractFitEngine import SansAssembly |
---|
[511c6810] | 15 | from sans.fit.AbstractFitEngine import FitAbort |
---|
| 16 | |
---|
[e0072082] | 17 | class fitresult(object): |
---|
[48882d1] | 18 | """ |
---|
[aa36f96] | 19 | Storing fit result |
---|
[48882d1] | 20 | """ |
---|
[c4d6900] | 21 | def __init__(self, model=None, param_list=None): |
---|
[89f3b66] | 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 |
---|
[e0072082] | 31 | self.parameters = None |
---|
| 32 | self.model = model |
---|
[c4d6900] | 33 | self.param_list = param_list |
---|
[d603001] | 34 | self.iterations = 0 |
---|
[e0072082] | 35 | |
---|
| 36 | def set_model(self, model): |
---|
[aa36f96] | 37 | """ |
---|
| 38 | """ |
---|
[e0072082] | 39 | self.model = model |
---|
| 40 | |
---|
[90c9cdf] | 41 | def set_fitness(self, fitness): |
---|
[aa36f96] | 42 | """ |
---|
| 43 | """ |
---|
[90c9cdf] | 44 | self.fitness = fitness |
---|
| 45 | |
---|
[e0072082] | 46 | def __str__(self): |
---|
[aa36f96] | 47 | """ |
---|
| 48 | """ |
---|
[b2f25dc5] | 49 | if self.pvec == None and self.model is None and self.param_list is None: |
---|
[e0072082] | 50 | return "No results" |
---|
| 51 | n = len(self.model.parameterset) |
---|
[d603001] | 52 | self.iterations += 1 |
---|
[e0072082] | 53 | result_param = zip(xrange(n), self.model.parameterset) |
---|
[852354c8] | 54 | msg1 = ["[Iteration #: %s ]" % self.iterations] |
---|
| 55 | msg2 = ["P%-3d %s......|.....%s" % \ |
---|
| 56 | (p[0], p[1], p[1].value)\ |
---|
[b2f25dc5] | 57 | for p in result_param if p[1].name in self.param_list] |
---|
[852354c8] | 58 | |
---|
| 59 | msg3 = ["=== goodness of fit: %s ===" % (str(self.fitness))] |
---|
| 60 | msg = msg1 + msg3 + msg2 |
---|
[c4d6900] | 61 | return "\n".join(msg) |
---|
[48882d1] | 62 | |
---|
[e0072082] | 63 | def print_summary(self): |
---|
[aa36f96] | 64 | """ |
---|
| 65 | """ |
---|
[e0072082] | 66 | print self |
---|
[88b5e83] | 67 | |
---|
[4c718654] | 68 | class ScipyFit(FitEngine): |
---|
[7705306] | 69 | """ |
---|
[aa36f96] | 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) |
---|
[7705306] | 94 | """ |
---|
[792db7d5] | 95 | def __init__(self): |
---|
| 96 | """ |
---|
[b2f25dc5] | 97 | Creates a dictionary (self.fit_arrange_dict={})of FitArrange elements |
---|
[aa36f96] | 98 | with Uid as keys |
---|
[792db7d5] | 99 | """ |
---|
[b2f25dc5] | 100 | FitEngine.__init__(self) |
---|
| 101 | self.fit_arrange_dict = {} |
---|
| 102 | self.param_list = [] |
---|
[c4d6900] | 103 | self.curr_thread = None |
---|
[d9dc518] | 104 | #def fit(self, *args, **kw): |
---|
| 105 | # return profile(self._fit, *args, **kw) |
---|
[393f0f3] | 106 | |
---|
[93de635d] | 107 | def fit(self, q=None, handler=None, curr_thread=None, ftol=1.49012e-8): |
---|
[aa36f96] | 108 | """ |
---|
| 109 | """ |
---|
[89f3b66] | 110 | fitproblem = [] |
---|
[c4d6900] | 111 | for fproblem in self.fit_arrange_dict.itervalues(): |
---|
[89f3b66] | 112 | if fproblem.get_to_fit() == 1: |
---|
[393f0f3] | 113 | fitproblem.append(fproblem) |
---|
[89f3b66] | 114 | if len(fitproblem) > 1 : |
---|
[e0072082] | 115 | msg = "Scipy can't fit more than a single fit problem at a time." |
---|
| 116 | raise RuntimeError, msg |
---|
[a9e04aa] | 117 | return |
---|
[89f3b66] | 118 | elif len(fitproblem) == 0 : |
---|
[a9e04aa] | 119 | raise RuntimeError, "No Assembly scheduled for Scipy fitting." |
---|
| 120 | return |
---|
| 121 | |
---|
[89f3b66] | 122 | listdata = [] |
---|
[393f0f3] | 123 | model = fitproblem[0].get_model() |
---|
| 124 | listdata = fitproblem[0].get_data() |
---|
[792db7d5] | 125 | # Concatenate dList set (contains one or more data)before fitting |
---|
[e0072082] | 126 | data = listdata |
---|
[852354c8] | 127 | |
---|
[89f3b66] | 128 | self.curr_thread = curr_thread |
---|
[93de635d] | 129 | ftol = ftol |
---|
[852354c8] | 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) |
---|
[fd6b789] | 137 | #try: |
---|
[852354c8] | 138 | functor = SansAssembly(self.param_list, model, data, handler=handler, |
---|
| 139 | fitresult=result, curr_thread= self.curr_thread) |
---|
[511c6810] | 140 | try: |
---|
[852354c8] | 141 | out, cov_x, _, mesg, success = optimize.leastsq(functor, |
---|
[c4d6900] | 142 | model.get_params(self.param_list), |
---|
[852354c8] | 143 | ftol=ftol, |
---|
[c4d6900] | 144 | full_output=1, |
---|
| 145 | warning=True) |
---|
[511c6810] | 146 | except: |
---|
[9a608ed] | 147 | if hasattr(sys, 'last_type') and sys.last_type == FitAbort: |
---|
[852354c8] | 148 | if handler is not None: |
---|
[511c6810] | 149 | msg = "Fit Stop!" |
---|
| 150 | #self.handler.error(msg) |
---|
[852354c8] | 151 | result = handler.get_result() |
---|
| 152 | return result |
---|
[511c6810] | 153 | else: |
---|
| 154 | raise |
---|
| 155 | |
---|
[c4d6900] | 156 | chisqr = functor.chisq() |
---|
[fd6b789] | 157 | if cov_x is not None and numpy.isfinite(cov_x).all(): |
---|
| 158 | stderr = numpy.sqrt(numpy.diag(cov_x)) |
---|
| 159 | else: |
---|
[e0072082] | 160 | stderr = None |
---|
[511c6810] | 161 | |
---|
[852354c8] | 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 | |
---|
[e0072082] | 230 | |
---|
[c4d6900] | 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 |
---|
[9c648c7] | 244 | |
---|
[48882d1] | 245 | |
---|