[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 | |
---|
[ba7dceb] | 58 | def fit(self, msg_q=None, |
---|
| 59 | q=None, handler=None, curr_thread=None, |
---|
[7db52f1] | 60 | ftol=1.49012e-8, reset_flag=False): |
---|
[aa36f96] | 61 | """ |
---|
| 62 | """ |
---|
[89f3b66] | 63 | fitproblem = [] |
---|
[c4d6900] | 64 | for fproblem in self.fit_arrange_dict.itervalues(): |
---|
[89f3b66] | 65 | if fproblem.get_to_fit() == 1: |
---|
[393f0f3] | 66 | fitproblem.append(fproblem) |
---|
[89f3b66] | 67 | if len(fitproblem) > 1 : |
---|
[e0072082] | 68 | msg = "Scipy can't fit more than a single fit problem at a time." |
---|
| 69 | raise RuntimeError, msg |
---|
[a9e04aa] | 70 | return |
---|
[89f3b66] | 71 | elif len(fitproblem) == 0 : |
---|
[a9e04aa] | 72 | raise RuntimeError, "No Assembly scheduled for Scipy fitting." |
---|
| 73 | return |
---|
[393f0f3] | 74 | model = fitproblem[0].get_model() |
---|
[7db52f1] | 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 = [] |
---|
[393f0f3] | 81 | listdata = fitproblem[0].get_data() |
---|
[792db7d5] | 82 | # Concatenate dList set (contains one or more data)before fitting |
---|
[e0072082] | 83 | data = listdata |
---|
[852354c8] | 84 | |
---|
[89f3b66] | 85 | self.curr_thread = curr_thread |
---|
[93de635d] | 86 | ftol = ftol |
---|
[852354c8] | 87 | |
---|
| 88 | # Check the initial value if it is within range |
---|
| 89 | self._check_param_range(model) |
---|
| 90 | |
---|
[444c900e] | 91 | result = FResult(model=model, data=data, param_list=self.param_list) |
---|
[06e7c26] | 92 | result.pars = fitproblem[0].pars |
---|
| 93 | result.fitter_id = self.fitter_id |
---|
[852354c8] | 94 | if handler is not None: |
---|
| 95 | handler.set_result(result=result) |
---|
[511c6810] | 96 | try: |
---|
[2446b66] | 97 | # This import must be here; otherwise it will be confused when more |
---|
| 98 | # than one thread exist. |
---|
| 99 | from scipy import optimize |
---|
| 100 | |
---|
[ba7dceb] | 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) |
---|
[db427ec] | 108 | out, cov_x, _, mesg, success = optimize.leastsq(functor, |
---|
[c4d6900] | 109 | model.get_params(self.param_list), |
---|
[852354c8] | 110 | ftol=ftol, |
---|
[0e8fca0] | 111 | full_output=1) |
---|
[2d0756a5] | 112 | except: |
---|
[acfff8b] | 113 | if hasattr(sys, 'last_type') and sys.last_type == KeyboardInterrupt: |
---|
[852354c8] | 114 | if handler is not None: |
---|
[acfff8b] | 115 | msg = "Fitting: Terminated!!!" |
---|
| 116 | handler.error(msg) |
---|
[2d0756a5] | 117 | raise KeyboardInterrupt, msg |
---|
[511c6810] | 118 | else: |
---|
[2d0756a5] | 119 | raise |
---|
[c4d6900] | 120 | chisqr = functor.chisq() |
---|
[15f68ce] | 121 | |
---|
[fd6b789] | 122 | if cov_x is not None and numpy.isfinite(cov_x).all(): |
---|
| 123 | stderr = numpy.sqrt(numpy.diag(cov_x)) |
---|
| 124 | else: |
---|
[15f68ce] | 125 | stderr = [] |
---|
[d8661fb] | 126 | |
---|
| 127 | result.index = data.idx |
---|
[15f68ce] | 128 | result.fitness = chisqr |
---|
| 129 | result.stderr = stderr |
---|
| 130 | result.pvec = out |
---|
| 131 | result.success = success |
---|
| 132 | result.theory = functor.theory |
---|
[fe10df5] | 133 | if handler is not None: |
---|
[cc694d0] | 134 | handler.set_result(result=result) |
---|
[ee19117] | 135 | handler.update_fit(last=True) |
---|
[15f68ce] | 136 | if q is not None: |
---|
| 137 | q.put(result) |
---|
| 138 | return q |
---|
| 139 | if success < 1 or success > 5: |
---|
| 140 | result.fitness = None |
---|
[444c900e] | 141 | return [result] |
---|
[15f68ce] | 142 | |
---|
[852354c8] | 143 | |
---|
| 144 | def _check_param_range(self, model): |
---|
| 145 | """ |
---|
| 146 | Check parameter range and set the initial value inside |
---|
| 147 | if it is out of range. |
---|
| 148 | |
---|
| 149 | : model: park model object |
---|
| 150 | """ |
---|
| 151 | is_outofbound = False |
---|
| 152 | # loop through parameterset |
---|
| 153 | for p in model.parameterset: |
---|
| 154 | param_name = p.get_name() |
---|
| 155 | # proceed only if the parameter name is in the list of fitting |
---|
| 156 | if param_name in self.param_list: |
---|
| 157 | # if the range was defined, check the range |
---|
| 158 | if numpy.isfinite(p.range[0]): |
---|
| 159 | if p.value <= p.range[0]: |
---|
| 160 | # 10 % backing up from the border if not zero |
---|
| 161 | # for Scipy engine to work properly. |
---|
| 162 | shift = self._get_zero_shift(p.range[0]) |
---|
| 163 | new_value = p.range[0] + shift |
---|
| 164 | p.value = new_value |
---|
| 165 | is_outofbound = True |
---|
| 166 | if numpy.isfinite(p.range[1]): |
---|
| 167 | if p.value >= p.range[1]: |
---|
| 168 | shift = self._get_zero_shift(p.range[1]) |
---|
| 169 | # 10 % backing up from the border if not zero |
---|
| 170 | # for Scipy engine to work properly. |
---|
| 171 | new_value = p.range[1] - shift |
---|
| 172 | # Check one more time if the new value goes below |
---|
| 173 | # the low bound, If so, re-evaluate the value |
---|
| 174 | # with the mean of the range. |
---|
| 175 | if numpy.isfinite(p.range[0]): |
---|
| 176 | if new_value < p.range[0]: |
---|
| 177 | new_value = (p.range[0] + p.range[1]) / 2.0 |
---|
| 178 | # Todo: |
---|
| 179 | # Need to think about when both min and max are same. |
---|
| 180 | p.value = new_value |
---|
| 181 | is_outofbound = True |
---|
| 182 | |
---|
| 183 | return is_outofbound |
---|
| 184 | |
---|
| 185 | def _get_zero_shift(self, range): |
---|
| 186 | """ |
---|
| 187 | Get 10% shift of the param value = 0 based on the range value |
---|
| 188 | |
---|
| 189 | : param range: min or max value of the bounds |
---|
| 190 | """ |
---|
| 191 | if range == 0: |
---|
| 192 | shift = 0.1 |
---|
| 193 | else: |
---|
| 194 | shift = 0.1 * range |
---|
| 195 | |
---|
| 196 | return shift |
---|
| 197 | |
---|
[e0072082] | 198 | |
---|
[c4d6900] | 199 | #def profile(fn, *args, **kw): |
---|
| 200 | # import cProfile, pstats, os |
---|
| 201 | # global call_result |
---|
| 202 | # def call(): |
---|
| 203 | # global call_result |
---|
| 204 | # call_result = fn(*args, **kw) |
---|
| 205 | # cProfile.runctx('call()', dict(call=call), {}, 'profile.out') |
---|
| 206 | # stats = pstats.Stats('profile.out') |
---|
| 207 | # stats.sort_stats('time') |
---|
| 208 | # stats.sort_stats('calls') |
---|
| 209 | # stats.print_stats() |
---|
| 210 | # os.unlink('profile.out') |
---|
| 211 | # return call_result |
---|
[9c648c7] | 212 | |
---|
[48882d1] | 213 | |
---|