source: sasview/park_integration/src/sans/fit/AbstractFitEngine.py @ c935fac

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since c935fac was e8f7c47, checked in by Jae Cho <jhjcho@…>, 13 years ago

removed print comment

  • Property mode set to 100644
File size: 27.9 KB
RevLine 
[aa36f96]1
[89f3b66]2import  copy
[c4d6900]3#import logging
[444c900e]4import sys
[89f3b66]5import numpy
6import math
7import park
[41517a6]8from sans.dataloader.data_info import Data1D
9from sans.dataloader.data_info import Data2D
[4b5bd73]10import time
11_SMALLVALUE = 1.0e-10   
[b2f25dc5]12   
[48882d1]13class SansParameter(park.Parameter):
14    """
[aa36f96]15    SANS model parameters for use in the PARK fitting service.
16    The parameter attribute value is redirected to the underlying
17    parameter value in the SANS model.
[48882d1]18    """
[1cff677]19    def __init__(self, name, model, data):
[ca6d914]20        """
[aa36f96]21        :param name: the name of the model parameter
22        :param model: the sans model to wrap as a park model
23       
[ca6d914]24        """
[c4d6900]25        park.Parameter.__init__(self, name)
[89f3b66]26        self._model, self._name = model, name
[1cff677]27        self.data = data
28        self.model = model
[ca6d914]29        #set the value for the parameter of the given name
30        self.set(model.getParam(name))
[48882d1]31         
[ca6d914]32    def _getvalue(self):
33        """
[aa36f96]34        override the _getvalue of park parameter
35       
36        :return value the parameter associates with self.name
37       
[ca6d914]38        """
39        return self._model.getParam(self.name)
[48882d1]40   
[89f3b66]41    def _setvalue(self, value):
[ca6d914]42        """
[aa36f96]43        override the _setvalue pf park parameter
44       
45        :param value: the value to set on a given parameter
46       
[ca6d914]47        """
[48882d1]48        self._model.setParam(self.name, value)
49       
[c4d6900]50    value = property(_getvalue, _setvalue)
[48882d1]51   
52    def _getrange(self):
[ca6d914]53        """
[aa36f96]54        Override _getrange of park parameter
55        return the range of parameter
[ca6d914]56        """
[920a6e5]57        #if not  self.name in self._model.getDispParamList():
[89f3b66]58        lo, hi = self._model.details[self.name][1:3]
[920a6e5]59        if lo is None: lo = -numpy.inf
60        if hi is None: hi = numpy.inf
61        #else:
62            #lo,hi = self._model.details[self.name][1:]
63            #if lo is None: lo = -numpy.inf
64            #if hi is None: hi = numpy.inf
[e0e22f2c]65        if lo > hi:
[05f14dd]66            raise ValueError,"wrong fit range for parameters"
67       
[89f3b66]68        return lo, hi
[48882d1]69   
[b2f25dc5]70    def get_name(self):
71        """
72        """
73        return self._getname()
74   
[89f3b66]75    def _setrange(self, r):
[ca6d914]76        """
[aa36f96]77        override _setrange of park parameter
78       
79        :param r: the value of the range to set
80       
[ca6d914]81        """
[12b76cf]82        self._model.details[self.name][1:3] = r
[89f3b66]83    range = property(_getrange, _setrange)
[a9e04aa]84   
85class Model(park.Model):
[48882d1]86    """
[aa36f96]87    PARK wrapper for SANS models.
[48882d1]88    """
[1cff677]89    def __init__(self, sans_model, sans_data=None, **kw):
[ca6d914]90        """
[aa36f96]91        :param sans_model: the sans model to wrap using park interface
92       
[ca6d914]93        """
[a9e04aa]94        park.Model.__init__(self, **kw)
[48882d1]95        self.model = sans_model
[ca6d914]96        self.name = sans_model.name
[1cff677]97        self.data = sans_data
[ca6d914]98        #list of parameters names
[48882d1]99        self.sansp = sans_model.getParamList()
[ca6d914]100        #list of park parameter
[1cff677]101        self.parkp = [SansParameter(p, sans_model, sans_data) for p in self.sansp]
[ca6d914]102        #list of parameterset
[89f3b66]103        self.parameterset = park.ParameterSet(sans_model.name, pars=self.parkp)
104        self.pars = []
[ca6d914]105 
[c4d6900]106    def get_params(self, fitparams):
[ca6d914]107        """
[aa36f96]108        return a list of value of paramter to fit
109       
110        :param fitparams: list of paramaters name to fit
111       
[ca6d914]112        """
[c4d6900]113        list_params = []
[89f3b66]114        self.pars = []
115        self.pars = fitparams
[48882d1]116        for item in fitparams:
117            for element in self.parkp:
[c4d6900]118                if element.name == str(item):
119                    list_params.append(element.value)
120        return list_params
[48882d1]121   
[c4d6900]122    def set_params(self, paramlist, params):
[ca6d914]123        """
[aa36f96]124        Set value for parameters to fit
125       
126        :param params: list of value for parameters to fit
127       
[ca6d914]128        """
[e71440c]129        try:
130            for i in range(len(self.parkp)):
131                for j in range(len(paramlist)):
[89f3b66]132                    if self.parkp[i].name == paramlist[j]:
[e71440c]133                        self.parkp[i].value = params[j]
[89f3b66]134                        self.model.setParam(self.parkp[i].name, params[j])
[e71440c]135        except:
136            raise
[ca6d914]137 
[89f3b66]138    def eval(self, x):
[ca6d914]139        """
[aa36f96]140        override eval method of park model.
141       
142        :param x: the x value used to compute a function
143       
[ca6d914]144        """
[d8a2e31]145        try:
[393f0f3]146            return self.model.evalDistribution(x)
[d8a2e31]147        except:
[393f0f3]148            raise
[c4d6900]149       
150    def eval_derivs(self, x, pars=[]):
151        """
152        Evaluate the model and derivatives wrt pars at x.
153
154        pars is a list of the names of the parameters for which derivatives
155        are desired.
156
157        This method needs to be specialized in the model to evaluate the
158        model function.  Alternatively, the model can implement is own
159        version of residuals which calculates the residuals directly
160        instead of calling eval.
161        """
162        return []
163
[a9e04aa]164
[b64fa56]165   
[1e3169c]166class FitData1D(Data1D):
167    """
[aa36f96]168    Wrapper class  for SANS data
169    FitData1D inherits from DataLoader.data_info.Data1D. Implements
170    a way to get residuals from data.
[1e3169c]171    """
[634ca14]172    def __init__(self, x, y, dx=None, dy=None, smearer=None, data=None):
[7d0c1a8]173        """
[aa36f96]174        :param smearer: is an object of class QSmearer or SlitSmearer
175           that will smear the theory data (slit smearing or resolution
176           smearing) when set.
177       
178        The proper way to set the smearing object would be to
179        do the following: ::
180       
[109e60ab]181            from DataLoader.qsmearing import smear_selection
[1e3169c]182            smearer = smear_selection(some_data)
183            fitdata1d = FitData1D( x= [1,3,..,],
184                                    y= [3,4,..,8],
185                                    dx=None,
186                                    dy=[1,2...], smearer= smearer)
[aa36f96]187       
188        :Note: that some_data _HAS_ to be of class DataLoader.data_info.Data1D
[109e60ab]189            Setting it back to None will turn smearing off.
190           
[7d0c1a8]191        """
[89f3b66]192        Data1D.__init__(self, x=x, y=y, dx=dx, dy=dy)
[634ca14]193        self.sans_data = data
[b461b6d7]194        self.smearer = smearer
[c4d6900]195        self._first_unsmeared_bin = None
196        self._last_unsmeared_bin = None
[189be4e]197        # Check error bar; if no error bar found, set it constant(=1)
[c4d6900]198        # TODO: Should provide an option for users to set it like percent,
199        # constant, or dy data
[89f3b66]200        if dy == None or dy == [] or dy.all() == 0:
201            self.dy = numpy.ones(len(y)) 
[189be4e]202        else:
[89f3b66]203            self.dy = numpy.asarray(dy).copy()
[189be4e]204
[109e60ab]205        ## Min Q-value
[4bd557d]206        #Skip the Q=0 point, especially when y(q=0)=None at x[0].
[89f3b66]207        if min (self.x) == 0.0 and self.x[0] == 0 and\
208                     not numpy.isfinite(self.y[0]):
[1e3169c]209            self.qmin = min(self.x[self.x!=0])
[773806e]210        else:                             
[89f3b66]211            self.qmin = min(self.x)
[109e60ab]212        ## Max Q-value
[89f3b66]213        self.qmax = max(self.x)
[058b2d7]214       
[72c7d31]215        # Range used for input to smearing
216        self._qmin_unsmeared = self.qmin
217        self._qmax_unsmeared = self.qmax
[fd0d30fd]218        # Identify the bin range for the unsmeared and smeared spaces
[89f3b66]219        self.idx = (self.x >= self.qmin) & (self.x <= self.qmax)
220        self.idx_unsmeared = (self.x >= self._qmin_unsmeared) \
221                            & (self.x <= self._qmax_unsmeared)
[fd0d30fd]222 
[c4d6900]223    def set_fit_range(self, qmin=None, qmax=None):
[7d0c1a8]224        """ to set the fit range"""
[09975cbb]225        # Skip Q=0 point, (especially for y(q=0)=None at x[0]).
[189be4e]226        # ToDo: Find better way to do it.
[89f3b66]227        if qmin == 0.0 and not numpy.isfinite(self.y[qmin]):
228            self.qmin = min(self.x[self.x != 0])
229        elif qmin != None:                       
[773806e]230            self.qmin = qmin           
[89f3b66]231        if qmax != None:
[eef2e0ed]232            self.qmax = qmax
[4bb2917]233        # Determine the range needed in unsmeared-Q to cover
234        # the smeared Q range
[72c7d31]235        self._qmin_unsmeared = self.qmin
236        self._qmax_unsmeared = self.qmax   
237       
[4bb2917]238        self._first_unsmeared_bin = 0
[89f3b66]239        self._last_unsmeared_bin  = len(self.x) - 1
[4bb2917]240       
[c4d6900]241        if self.smearer != None:
[89f3b66]242            self._first_unsmeared_bin, self._last_unsmeared_bin = \
243                    self.smearer.get_bin_range(self.qmin, self.qmax)
[1e3169c]244            self._qmin_unsmeared = self.x[self._first_unsmeared_bin]
245            self._qmax_unsmeared = self.x[self._last_unsmeared_bin]
[4bb2917]246           
[fd0d30fd]247        # Identify the bin range for the unsmeared and smeared spaces
[89f3b66]248        self.idx = (self.x >= self.qmin) & (self.x <= self.qmax)
249        ## zero error can not participate for fitting
250        self.idx = self.idx & (self.dy != 0) 
251        self.idx_unsmeared = (self.x >= self._qmin_unsmeared) \
252                            & (self.x <= self._qmax_unsmeared)
[fd0d30fd]253 
[c4d6900]254    def get_fit_range(self):
[7d0c1a8]255        """
[aa36f96]256        return the range of data.x to fit
[7d0c1a8]257        """
258        return self.qmin, self.qmax
[72c7d31]259       
[7d0c1a8]260    def residuals(self, fn):
[72c7d31]261        """
[aa36f96]262        Compute residuals.
263       
264        If self.smearer has been set, use if to smear
265        the data before computing chi squared.
266       
267        :param fn: function that return model value
268       
269        :return: residuals
270       
[109e60ab]271        """
272        # Compute theory data f(x)
[89f3b66]273        fx = numpy.zeros(len(self.x))
[7e752fe]274        fx[self.idx_unsmeared] = fn(self.x[self.idx_unsmeared])
[fd0d30fd]275       
[d5b488b]276        ## Smear theory data
[109e60ab]277        if self.smearer is not None:
[89f3b66]278            fx = self.smearer(fx, self._first_unsmeared_bin, 
279                              self._last_unsmeared_bin)
[d5b488b]280        ## Sanity check
[89f3b66]281        if numpy.size(self.dy) != numpy.size(fx):
282            msg = "FitData1D: invalid error array "
283            msg += "%d <> %d" % (numpy.shape(self.dy), numpy.size(fx))                                                     
284            raise RuntimeError, msg 
[425e49ca]285        return (self.y[self.idx] - fx[self.idx]) / self.dy[self.idx], fx[self.idx]
[444c900e]286           
[72c7d31]287     
[7d0c1a8]288    def residuals_deriv(self, model, pars=[]):
289        """
[aa36f96]290        :return: residuals derivatives .
291       
292        :note: in this case just return empty array
293       
[7d0c1a8]294        """
295        return []
296   
[1e3169c]297class FitData2D(Data2D):
[7d0c1a8]298    """ Wrapper class  for SANS data """
[89f3b66]299    def __init__(self, sans_data2d, data=None, err_data=None):
[c4d6900]300        Data2D.__init__(self, data=data, err_data=err_data)
[7d0c1a8]301        """
[aa36f96]302        Data can be initital with a data (sans plottable)
303        or with vectors.
[7d0c1a8]304        """
[89f3b66]305        self.res_err_image = []
[444c900e]306        self.idx = []
[89f3b66]307        self.qmin = None
308        self.qmax = None
[f72333f]309        self.smearer = None
[c4d6900]310        self.radius = 0
311        self.res_err_data = []
[634ca14]312        self.sans_data = sans_data2d
[89f3b66]313        self.set_data(sans_data2d)
[f72333f]314
[89f3b66]315    def set_data(self, sans_data2d, qmin=None, qmax=None):
[1e3169c]316        """
[aa36f96]317        Determine the correct qx_data and qy_data within range to fit
[1e3169c]318        """
[89f3b66]319        self.data = sans_data2d.data
[83195f7]320        self.err_data = sans_data2d.err_data
321        self.qx_data = sans_data2d.qx_data
322        self.qy_data = sans_data2d.qy_data
[89f3b66]323        self.mask = sans_data2d.mask
[83195f7]324
325        x_max = max(math.fabs(sans_data2d.xmin), math.fabs(sans_data2d.xmax))
326        y_max = max(math.fabs(sans_data2d.ymin), math.fabs(sans_data2d.ymax))
[20d30e9]327       
328        ## fitting range
[027e8f2]329        if qmin == None:
330            self.qmin = 1e-16
331        if qmax == None:
[89f3b66]332            self.qmax = math.sqrt(x_max * x_max + y_max * y_max)
[70bf68c]333        ## new error image for fitting purpose
[89f3b66]334        if self.err_data == None or self.err_data == []:
335            self.res_err_data = numpy.ones(len(self.data))
[70bf68c]336        else:
[da58fcc]337            self.res_err_data = copy.deepcopy(self.err_data)
[9e8c150]338        #self.res_err_data[self.res_err_data==0]=1
[d8a2e31]339       
[89f3b66]340        self.radius = numpy.sqrt(self.qx_data**2 + self.qy_data**2)
[83195f7]341       
342        # Note: mask = True: for MASK while mask = False for NOT to mask
[444c900e]343        self.idx = ((self.qmin <= self.radius)&\
[89f3b66]344                            (self.radius <= self.qmax))
[444c900e]345        self.idx = (self.idx) & (self.mask)
346        self.idx = (self.idx) & (numpy.isfinite(self.data))
[f72333f]347       
[c4d6900]348    def set_smearer(self, smearer): 
[f72333f]349        """
[aa36f96]350        Set smearer
[f72333f]351        """
352        if smearer == None:
353            return
354        self.smearer = smearer
[444c900e]355        self.smearer.set_index(self.idx)
[f72333f]356        self.smearer.get_data()
357
[c4d6900]358    def set_fit_range(self, qmin=None, qmax=None):
[7d0c1a8]359        """ to set the fit range"""
[89f3b66]360        if qmin == 0.0:
[773806e]361            self.qmin = 1e-16
[89f3b66]362        elif qmin != None:                       
[773806e]363            self.qmin = qmin           
[89f3b66]364        if qmax != None:
365            self.qmax = qmax       
366        self.radius = numpy.sqrt(self.qx_data**2 + self.qy_data**2)
367        self.index_model = ((self.qmin <= self.radius)&\
368                            (self.radius <= self.qmax))
[444c900e]369        self.idx = (self.idx) &(self.mask)
370        self.idx = (self.idx) & (numpy.isfinite(self.data))
371        self.idx = (self.idx) & (self.res_err_data != 0)
[aa36f96]372       
[c4d6900]373    def get_fit_range(self):
[7d0c1a8]374        """
[aa36f96]375        return the range of data.x to fit
[7d0c1a8]376        """
[20d30e9]377        return self.qmin, self.qmax
[7d0c1a8]378     
[d8a2e31]379    def residuals(self, fn): 
[83195f7]380        """
[aa36f96]381        return the residuals
[f72333f]382        """ 
383        if self.smearer != None:
[444c900e]384            fn.set_index(self.idx)
[f72333f]385            # Get necessary data from self.data and set the data for smearing
386            fn.get_data()
387
388            gn = fn.get_value() 
389        else:
[444c900e]390            gn = fn([self.qx_data[self.idx],
391                     self.qy_data[self.idx]])
[83195f7]392        # use only the data point within ROI range
[d8661fb]393        res = (self.data[self.idx] - gn)/self.res_err_data[self.idx]
[444c900e]394        return res, gn
[0e51519]395       
[7d0c1a8]396    def residuals_deriv(self, model, pars=[]):
397        """
[aa36f96]398        :return: residuals derivatives .
399       
400        :note: in this case just return empty array
401       
[7d0c1a8]402        """
403        return []
[48882d1]404   
[4bd557d]405class FitAbort(Exception):
406    """
[aa36f96]407    Exception raise to stop the fit
[4bd557d]408    """
[1ab9dc1]409    #pass
410    #print"Creating fit abort Exception"
[4bd557d]411
412
[70bf68c]413class SansAssembly:
[ca6d914]414    """
[aa36f96]415    Sans Assembly class a class wrapper to be call in optimizer.leastsq method
[ca6d914]416    """
[e0072082]417    def __init__(self, paramlist, model=None , data=None, fitresult=None,
418                 handler=None, curr_thread=None):
[ca6d914]419        """
[aa36f96]420        :param Model: the model wrapper fro sans -model
421        :param Data: the data wrapper for sans data
422       
[ca6d914]423        """
[e0072082]424        self.model = model
425        self.data  = data
426        self.paramlist = paramlist
427        self.curr_thread = curr_thread
428        self.handler = handler
429        self.fitresult = fitresult
430        self.res = []
[4b5bd73]431        self.true_res = []
[e0072082]432        self.func_name = "Functor"
[425e49ca]433        self.theory = None
[e0072082]434       
[c4d6900]435    #def chisq(self, params):
436    def chisq(self):
[48882d1]437        """
[aa36f96]438        Calculates chi^2
439       
440        :param params: list of parameter values
441       
442        :return: chi^2
443       
[48882d1]444        """
445        sum = 0
[4b5bd73]446        for item in self.true_res:
[c4d6900]447            sum += item * item
[4b5bd73]448        if len(self.true_res) == 0:
[4bd557d]449            return None
[4b5bd73]450        return sum / len(self.true_res)
[20d30e9]451   
[c4d6900]452    def __call__(self, params):
[ca6d914]453        """
[aa36f96]454        Compute residuals
455       
456        :param params: value of parameters to fit
457       
[4b5bd73]458        """ 
459        #import thread
460        self.model.set_params(self.paramlist, params)
[5722d66]461        self.true_res, theory = self.data.residuals(self.model.eval)
462        self.theory = copy.deepcopy(theory)
[4b5bd73]463        # check parameters range
464        if self.check_param_range():
465            # if the param value is outside of the bound
466            # just silent return res = inf
467            return self.res
468        self.res = self.true_res       
[e0072082]469        if self.fitresult is not None and  self.handler is not None:
470            self.fitresult.set_model(model=self.model)
[444c900e]471            self.fitresult.residuals = self.true_res
472            self.fitresult.theory = theory
[4b5bd73]473            #fitness = self.chisq(params=params)
[c4d6900]474            fitness = self.chisq()
[511c6810]475            self.fitresult.pvec = params
[90c9cdf]476            self.fitresult.set_fitness(fitness=fitness)
[e0072082]477            self.handler.set_result(result=self.fitresult)
[4b5bd73]478            self.handler.update_fit()
479
[511c6810]480            if self.curr_thread != None :
[d5f0f5e3]481                try:
[078f2f2]482                    self.curr_thread.isquit()
483                except:
[acfff8b]484                    msg = "Fitting: Terminated...       Note: Forcing to stop " 
485                    msg += "fitting may cause a 'Functor error message' "
486                    msg += "being recorded in the log file....."
[1ab9dc1]487                    self.handler.error(msg)
488                    raise
489                    #return
[12cd4ec]490         
[48882d1]491        return self.res
492   
[4b5bd73]493    def check_param_range(self):
494        """
495        Check the lower and upper bound of the parameter value
496        and set res to the inf if the value is outside of the
497        range
498        :limitation: the initial values must be within range.
499        """
500
[bdc25e2]501        #time.sleep(0.01)
[4b5bd73]502        is_outofbound = False
503        # loop through the fit parameters
504        for p in self.model.parameterset:
505            param_name = p.get_name()
506            if param_name in self.paramlist:
507               
508                # if the range was defined, check the range
509                if numpy.isfinite(p.range[0]):
510                    if p.value == 0:
511                        # This value works on Scipy
512                        # Do not change numbers below
513                        value = _SMALLVALUE
514                    else:
515                        value = p.value
516                    # For leastsq, it needs a bit step back from the boundary
517                    val = p.range[0] - value * _SMALLVALUE
518                    if p.value < val: 
519                        self.res *= 1e+6
520                       
521                        is_outofbound = True
522                        break
523                if numpy.isfinite(p.range[1]):
524                    # This value works on Scipy
525                    # Do not change numbers below
526                    if p.value == 0:
527                        value = _SMALLVALUE
528                    else:
529                        value = p.value
530                    # For leastsq, it needs a bit step back from the boundary
531                    val = p.range[1] + value * _SMALLVALUE
532                    if p.value > val:
533                        self.res *= 1e+6
534                        is_outofbound = True
535                        break
536
537        return is_outofbound
538   
539   
[4c718654]540class FitEngine:
[ee5b04c]541    def __init__(self):
[ca6d914]542        """
[aa36f96]543        Base class for scipy and park fit engine
[ca6d914]544        """
545        #List of parameter names to fit
[b2f25dc5]546        self.param_list = []
[ca6d914]547        #Dictionnary of fitArrange element (fit problems)
[b2f25dc5]548        self.fit_arrange_dict = {}
[7db52f1]549       
[1cff677]550    def set_model(self, model,  id,  pars=[], constraints=[], data=None):
[4c718654]551        """
[c4d6900]552        set a model on a given  in the fit engine.
[aa36f96]553       
554        :param model: sans.models type
[c4d6900]555        :param : is the key of the fitArrange dictionary where model is
[aa36f96]556                saved as a value
557        :param pars: the list of parameters to fit
558        :param constraints: list of
559            tuple (name of parameter, value of parameters)
560            the value of parameter must be a string to constraint 2 different
561            parameters.
562            Example: 
563            we want to fit 2 model M1 and M2 both have parameters A and B.
564            constraints can be:
565             constraints = [(M1.A, M2.B+2), (M1.B= M2.A *5),...,]
566           
567             
568        :note: pars must contains only name of existing model's parameters
569       
[ca6d914]570        """
[fd6b789]571        if model == None:
572            raise ValueError, "AbstractFitEngine: Need to set model to fit"
[393f0f3]573       
[89f3b66]574        new_model = model
[393f0f3]575        if not issubclass(model.__class__, Model):
[1cff677]576            new_model = Model(model, data)
[fd6b789]577       
[89f3b66]578        if len(constraints) > 0:
[fd6b789]579            for constraint in constraints:
580                name, value = constraint
581                try:
[89f3b66]582                    new_model.parameterset[str(name)].set(str(value))
[fd6b789]583                except:
[89f3b66]584                    msg = "Fit Engine: Error occurs when setting the constraint"
[c4d6900]585                    msg += " %s for parameter %s " % (value, name)
[fd6b789]586                    raise ValueError, msg
587               
[89f3b66]588        if len(pars) > 0:
589            temp = []
[fd6b789]590            for item in pars:
591                if item in new_model.model.getParamList():
592                    temp.append(item)
[b2f25dc5]593                    self.param_list.append(item)
[fd6b789]594                else:
595                   
[89f3b66]596                    msg = "wrong parameter %s used" % str(item)
597                    msg += "to set model %s. Choose" % str(new_model.model.name)
598                    msg += "parameter name within %s" % \
599                                str(new_model.model.getParamList())
600                    raise ValueError, msg
[fd6b789]601             
[c4d6900]602            #A fitArrange is already created but contains data_list only at id
603            if self.fit_arrange_dict.has_key(id):
604                self.fit_arrange_dict[id].set_model(new_model)
605                self.fit_arrange_dict[id].pars = pars
[6831a99]606            else:
[c4d6900]607            #no fitArrange object has been create with this id
[48882d1]608                fitproblem = FitArrange()
[fd6b789]609                fitproblem.set_model(new_model)
[89f3b66]610                fitproblem.pars = pars
[c4d6900]611                self.fit_arrange_dict[id] = fitproblem
[7db52f1]612                vals = []
613                for name in pars:
614                    vals.append(new_model.model.getParam(name))
615                self.fit_arrange_dict[id].vals = vals
[d4b0687]616        else:
[6831a99]617            raise ValueError, "park_integration:missing parameters"
[48882d1]618   
[c4d6900]619    def set_data(self, data, id, smearer=None, qmin=None, qmax=None):
[aa36f96]620        """
621        Receives plottable, creates a list of data to fit,set data
622        in a FitArrange object and adds that object in a dictionary
[c4d6900]623        with key id.
[aa36f96]624       
625        :param data: data added
[c4d6900]626        :param id: unique key corresponding to a fitArrange object with data
[aa36f96]627       
[ca6d914]628        """
[89f3b66]629        if data.__class__.__name__ == 'Data2D':
630            fitdata = FitData2D(sans_data2d=data, data=data.data,
631                                 err_data=data.err_data)
[f8ce013]632        else:
[89f3b66]633            fitdata = FitData1D(x=data.x, y=data.y ,
634                                 dx=data.dx, dy=data.dy, smearer=smearer)
[634ca14]635        fitdata.sans_data = data
[393f0f3]636       
[c4d6900]637        fitdata.set_fit_range(qmin=qmin, qmax=qmax)
638        #A fitArrange is already created but contains model only at id
639        if self.fit_arrange_dict.has_key(id):
640            self.fit_arrange_dict[id].add_data(fitdata)
[d4b0687]641        else:
[c4d6900]642        #no fitArrange object has been create with this id
[89f3b66]643            fitproblem = FitArrange()
[f8ce013]644            fitproblem.add_data(fitdata)
[c4d6900]645            self.fit_arrange_dict[id] = fitproblem   
[20d30e9]646   
[c4d6900]647    def get_model(self, id):
[d4b0687]648        """
[aa36f96]649       
[c4d6900]650        :param id: id is key in the dictionary containing the model to return
[aa36f96]651       
[c4d6900]652        :return:  a model at this id or None if no FitArrange element was
653            created with this id
[aa36f96]654           
[d4b0687]655        """
[c4d6900]656        if self.fit_arrange_dict.has_key(id):
657            return self.fit_arrange_dict[id].get_model()
[d4b0687]658        else:
659            return None
660   
[c4d6900]661    def remove_fit_problem(self, id):
662        """remove   fitarrange in id"""
663        if self.fit_arrange_dict.has_key(id):
664            del self.fit_arrange_dict[id]
[a9e04aa]665           
[c4d6900]666    def select_problem_for_fit(self, id, value):
[a9e04aa]667        """
[c4d6900]668        select a couple of model and data at the id position in dictionary
[aa36f96]669        and set in self.selected value to value
670       
671        :param value: the value to allow fitting.
672                can only have the value one or zero
673               
[a9e04aa]674        """
[c4d6900]675        if self.fit_arrange_dict.has_key(id):
676            self.fit_arrange_dict[id].set_to_fit(value)
[eef2e0ed]677             
[c4d6900]678    def get_problem_to_fit(self, id):
[a9e04aa]679        """
[c4d6900]680        return the self.selected value of the fit problem of id
[aa36f96]681       
[c4d6900]682        :param id: the id of the problem
[aa36f96]683       
[a9e04aa]684        """
[c4d6900]685        if self.fit_arrange_dict.has_key(id):
686            self.fit_arrange_dict[id].get_to_fit()
[4c718654]687   
[d4b0687]688class FitArrange:
689    def __init__(self):
690        """
[aa36f96]691        Class FitArrange contains a set of data for a given model
692        to perform the Fit.FitArrange must contain exactly one model
693        and at least one data for the fit to be performed.
694       
695        model: the model selected by the user
696        Ldata: a list of data what the user wants to fit
[d4b0687]697           
698        """
699        self.model = None
[c4d6900]700        self.data_list = []
[89f3b66]701        self.pars = []
[7db52f1]702        self.vals = []
[a9e04aa]703        #self.selected  is zero when this fit problem is not schedule to fit
704        #self.selected is 1 when schedule to fit
705        self.selected = 0
[d4b0687]706       
[89f3b66]707    def set_model(self, model):
[d4b0687]708        """
[aa36f96]709        set_model save a copy of the model
710       
711        :param model: the model being set
712       
[d4b0687]713        """
714        self.model = model
715       
[89f3b66]716    def add_data(self, data):
[d4b0687]717        """
[c4d6900]718        add_data fill a self.data_list with data to fit
[aa36f96]719       
720        :param data: Data to add in the list 
721       
[d4b0687]722        """
[c4d6900]723        if not data in self.data_list:
724            self.data_list.append(data)
[d4b0687]725           
726    def get_model(self):
[aa36f96]727        """
728       
729        :return: saved model
730       
731        """
[d4b0687]732        return self.model   
733     
734    def get_data(self):
[aa36f96]735        """
736       
[c4d6900]737        :return: list of data data_list
[aa36f96]738       
739        """
[c4d6900]740        #return self.data_list
741        return self.data_list[0] 
[d4b0687]742     
[89f3b66]743    def remove_data(self, data):
[d4b0687]744        """
[aa36f96]745        Remove one element from the list
746       
[c4d6900]747        :param data: Data to remove from data_list
[aa36f96]748       
[d4b0687]749        """
[c4d6900]750        if data in self.data_list:
751            self.data_list.remove(data)
[aa36f96]752           
[a9e04aa]753    def set_to_fit (self, value=0):
754        """
[aa36f96]755        set self.selected to 0 or 1  for other values raise an exception
756       
757        :param value: integer between 0 or 1
758       
[a9e04aa]759        """
[89f3b66]760        self.selected = value
[a9e04aa]761       
762    def get_to_fit(self):
763        """
[aa36f96]764        return self.selected value
[a9e04aa]765        """
766        return self.selected
[444c900e]767   
768   
769IS_MAC = True
770if sys.platform.count("win32") > 0:
771    IS_MAC = False
772   
773class FResult(object):
774    """
775    Storing fit result
776    """
777    def __init__(self, model=None, param_list=None, data=None):
778        self.calls = None
779        self.fitness = None
780        self.chisqr = None
781        self.pvec = []
782        self.cov = []
783        self.info = None
784        self.mesg = None
785        self.success = None
786        self.stderr = None
787        self.residuals = []
788        self.index = []
789        self.parameters = None
790        self.is_mac = IS_MAC
791        self.model = model
792        self.data = data
793        self.theory = []
794        self.param_list = param_list
795        self.iterations = 0
796        self.inputs = []
797        if self.model is not None and self.data is not None:
798            self.inputs = [(self.model, self.data)]
799     
800    def set_model(self, model):
801        """
802        """
803        self.model = model
804       
805    def set_fitness(self, fitness):
806        """
807        """
808        self.fitness = fitness
809       
810    def __str__(self):
811        """
812        """
813        if self.pvec == None and self.model is None and self.param_list is None:
814            return "No results"
815        n = len(self.model.parameterset)
816        self.iterations += 1
817        result_param = zip(xrange(n), self.model.parameterset)
818        msg1 = ["[Iteration #: %s ]" % self.iterations]
819        msg3 = ["=== goodness of fit: %s ===" % (str(self.fitness))]
820        if not self.is_mac:
821            msg2 = ["P%-3d  %s......|.....%s" % \
822                (p[0], p[1], p[1].value)\
823                  for p in result_param if p[1].name in self.param_list]
824            msg =  msg1 + msg3 + msg2
825        else:
826            msg = msg1 + msg3
827        msg = "\n".join(msg)
828        return msg
829   
830    def print_summary(self):
831        """
832        """
833        print self 
Note: See TracBrowser for help on using the repository browser.