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

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 eb4f2fd was 634ca14, checked in by Gervaise Alina <gervyh@…>, 13 years ago

making sure each result know it data and model

  • Property mode set to 100644
File size: 25.8 KB
RevLine 
[aa36f96]1
[89f3b66]2import  copy
[c4d6900]3#import logging
4#import 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 
285        return (self.y[self.idx] - fx[self.idx]) / self.dy[self.idx]
[72c7d31]286     
[7d0c1a8]287    def residuals_deriv(self, model, pars=[]):
288        """
[aa36f96]289        :return: residuals derivatives .
290       
291        :note: in this case just return empty array
292       
[7d0c1a8]293        """
294        return []
295   
[1e3169c]296class FitData2D(Data2D):
[7d0c1a8]297    """ Wrapper class  for SANS data """
[89f3b66]298    def __init__(self, sans_data2d, data=None, err_data=None):
[c4d6900]299        Data2D.__init__(self, data=data, err_data=err_data)
[7d0c1a8]300        """
[aa36f96]301        Data can be initital with a data (sans plottable)
302        or with vectors.
[7d0c1a8]303        """
[89f3b66]304        self.res_err_image = []
305        self.index_model = []
306        self.qmin = None
307        self.qmax = None
[f72333f]308        self.smearer = None
[c4d6900]309        self.radius = 0
310        self.res_err_data = []
[634ca14]311        self.sans_data = sans_data2d
[89f3b66]312        self.set_data(sans_data2d)
[f72333f]313
[89f3b66]314    def set_data(self, sans_data2d, qmin=None, qmax=None):
[1e3169c]315        """
[aa36f96]316        Determine the correct qx_data and qy_data within range to fit
[1e3169c]317        """
[89f3b66]318        self.data = sans_data2d.data
[83195f7]319        self.err_data = sans_data2d.err_data
320        self.qx_data = sans_data2d.qx_data
321        self.qy_data = sans_data2d.qy_data
[89f3b66]322        self.mask = sans_data2d.mask
[83195f7]323
324        x_max = max(math.fabs(sans_data2d.xmin), math.fabs(sans_data2d.xmax))
325        y_max = max(math.fabs(sans_data2d.ymin), math.fabs(sans_data2d.ymax))
[20d30e9]326       
327        ## fitting range
[027e8f2]328        if qmin == None:
329            self.qmin = 1e-16
330        if qmax == None:
[89f3b66]331            self.qmax = math.sqrt(x_max * x_max + y_max * y_max)
[70bf68c]332        ## new error image for fitting purpose
[89f3b66]333        if self.err_data == None or self.err_data == []:
334            self.res_err_data = numpy.ones(len(self.data))
[70bf68c]335        else:
[da58fcc]336            self.res_err_data = copy.deepcopy(self.err_data)
[9e8c150]337        #self.res_err_data[self.res_err_data==0]=1
[d8a2e31]338       
[89f3b66]339        self.radius = numpy.sqrt(self.qx_data**2 + self.qy_data**2)
[83195f7]340       
341        # Note: mask = True: for MASK while mask = False for NOT to mask
[89f3b66]342        self.index_model = ((self.qmin <= self.radius)&\
343                            (self.radius <= self.qmax))
[36bc34e]344        self.index_model = (self.index_model) & (self.mask)
345        self.index_model = (self.index_model) & (numpy.isfinite(self.data))
[f72333f]346       
[c4d6900]347    def set_smearer(self, smearer): 
[f72333f]348        """
[aa36f96]349        Set smearer
[f72333f]350        """
351        if smearer == None:
352            return
353        self.smearer = smearer
354        self.smearer.set_index(self.index_model)
355        self.smearer.get_data()
356
[c4d6900]357    def set_fit_range(self, qmin=None, qmax=None):
[7d0c1a8]358        """ to set the fit range"""
[89f3b66]359        if qmin == 0.0:
[773806e]360            self.qmin = 1e-16
[89f3b66]361        elif qmin != None:                       
[773806e]362            self.qmin = qmin           
[89f3b66]363        if qmax != None:
364            self.qmax = qmax       
365        self.radius = numpy.sqrt(self.qx_data**2 + self.qy_data**2)
366        self.index_model = ((self.qmin <= self.radius)&\
367                            (self.radius <= self.qmax))
[36bc34e]368        self.index_model = (self.index_model) &(self.mask)
369        self.index_model = (self.index_model) & (numpy.isfinite(self.data))
[c4d6900]370        self.index_model = (self.index_model) & (self.res_err_data != 0)
[aa36f96]371       
[c4d6900]372    def get_fit_range(self):
[7d0c1a8]373        """
[aa36f96]374        return the range of data.x to fit
[7d0c1a8]375        """
[20d30e9]376        return self.qmin, self.qmax
[7d0c1a8]377     
[d8a2e31]378    def residuals(self, fn): 
[83195f7]379        """
[aa36f96]380        return the residuals
[f72333f]381        """ 
382        if self.smearer != None:
383            fn.set_index(self.index_model)
384            # Get necessary data from self.data and set the data for smearing
385            fn.get_data()
386
387            gn = fn.get_value() 
388        else:
[89f3b66]389            gn = fn([self.qx_data[self.index_model],
390                     self.qy_data[self.index_model]])
[83195f7]391        # use only the data point within ROI range
[89f3b66]392        res = (self.data[self.index_model] - gn)/\
393                    self.res_err_data[self.index_model]
[83195f7]394        return res
[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"
433       
[c4d6900]434    #def chisq(self, params):
435    def chisq(self):
[48882d1]436        """
[aa36f96]437        Calculates chi^2
438       
439        :param params: list of parameter values
440       
441        :return: chi^2
442       
[48882d1]443        """
444        sum = 0
[4b5bd73]445        for item in self.true_res:
[c4d6900]446            sum += item * item
[4b5bd73]447        if len(self.true_res) == 0:
[4bd557d]448            return None
[4b5bd73]449        return sum / len(self.true_res)
[20d30e9]450   
[c4d6900]451    def __call__(self, params):
[ca6d914]452        """
[aa36f96]453        Compute residuals
454       
455        :param params: value of parameters to fit
456       
[4b5bd73]457        """ 
458        #import thread
459        self.model.set_params(self.paramlist, params)
460        self.true_res = self.data.residuals(self.model.eval)
461        # check parameters range
462        if self.check_param_range():
463            # if the param value is outside of the bound
464            # just silent return res = inf
465            return self.res
466        self.res = self.true_res       
[e0072082]467        if self.fitresult is not None and  self.handler is not None:
468            self.fitresult.set_model(model=self.model)
[4b5bd73]469            #fitness = self.chisq(params=params)
[c4d6900]470            fitness = self.chisq()
[511c6810]471            self.fitresult.pvec = params
[90c9cdf]472            self.fitresult.set_fitness(fitness=fitness)
[e0072082]473            self.handler.set_result(result=self.fitresult)
[4b5bd73]474            self.handler.update_fit()
475
[511c6810]476            if self.curr_thread != None :
[d5f0f5e3]477                try:
[078f2f2]478                    self.curr_thread.isquit()
479                except:
[acfff8b]480                    msg = "Fitting: Terminated...       Note: Forcing to stop " 
481                    msg += "fitting may cause a 'Functor error message' "
482                    msg += "being recorded in the log file....."
[1ab9dc1]483                    self.handler.error(msg)
484                    raise
485                    #return
[12cd4ec]486         
[48882d1]487        return self.res
488   
[4b5bd73]489    def check_param_range(self):
490        """
491        Check the lower and upper bound of the parameter value
492        and set res to the inf if the value is outside of the
493        range
494        :limitation: the initial values must be within range.
495        """
496
[bdc25e2]497        #time.sleep(0.01)
[4b5bd73]498        is_outofbound = False
499        # loop through the fit parameters
500        for p in self.model.parameterset:
501            param_name = p.get_name()
502            if param_name in self.paramlist:
503               
504                # if the range was defined, check the range
505                if numpy.isfinite(p.range[0]):
506                    if p.value == 0:
507                        # This value works on Scipy
508                        # Do not change numbers below
509                        value = _SMALLVALUE
510                    else:
511                        value = p.value
512                    # For leastsq, it needs a bit step back from the boundary
513                    val = p.range[0] - value * _SMALLVALUE
514                    if p.value < val: 
515                        self.res *= 1e+6
516                       
517                        is_outofbound = True
518                        break
519                if numpy.isfinite(p.range[1]):
520                    # This value works on Scipy
521                    # Do not change numbers below
522                    if p.value == 0:
523                        value = _SMALLVALUE
524                    else:
525                        value = p.value
526                    # For leastsq, it needs a bit step back from the boundary
527                    val = p.range[1] + value * _SMALLVALUE
528                    if p.value > val:
529                        self.res *= 1e+6
530                        is_outofbound = True
531                        break
532
533        return is_outofbound
534   
535   
[4c718654]536class FitEngine:
[ee5b04c]537    def __init__(self):
[ca6d914]538        """
[aa36f96]539        Base class for scipy and park fit engine
[ca6d914]540        """
541        #List of parameter names to fit
[b2f25dc5]542        self.param_list = []
[ca6d914]543        #Dictionnary of fitArrange element (fit problems)
[b2f25dc5]544        self.fit_arrange_dict = {}
[c4d6900]545 
[1cff677]546    def set_model(self, model,  id,  pars=[], constraints=[], data=None):
[4c718654]547        """
[c4d6900]548        set a model on a given  in the fit engine.
[aa36f96]549       
550        :param model: sans.models type
[c4d6900]551        :param : is the key of the fitArrange dictionary where model is
[aa36f96]552                saved as a value
553        :param pars: the list of parameters to fit
554        :param constraints: list of
555            tuple (name of parameter, value of parameters)
556            the value of parameter must be a string to constraint 2 different
557            parameters.
558            Example: 
559            we want to fit 2 model M1 and M2 both have parameters A and B.
560            constraints can be:
561             constraints = [(M1.A, M2.B+2), (M1.B= M2.A *5),...,]
562           
563             
564        :note: pars must contains only name of existing model's parameters
565       
[ca6d914]566        """
[fd6b789]567        if model == None:
568            raise ValueError, "AbstractFitEngine: Need to set model to fit"
[393f0f3]569       
[89f3b66]570        new_model = model
[393f0f3]571        if not issubclass(model.__class__, Model):
[1cff677]572            new_model = Model(model, data)
[fd6b789]573       
[89f3b66]574        if len(constraints) > 0:
[fd6b789]575            for constraint in constraints:
576                name, value = constraint
577                try:
[89f3b66]578                    new_model.parameterset[str(name)].set(str(value))
[fd6b789]579                except:
[89f3b66]580                    msg = "Fit Engine: Error occurs when setting the constraint"
[c4d6900]581                    msg += " %s for parameter %s " % (value, name)
[fd6b789]582                    raise ValueError, msg
583               
[89f3b66]584        if len(pars) > 0:
585            temp = []
[fd6b789]586            for item in pars:
587                if item in new_model.model.getParamList():
588                    temp.append(item)
[b2f25dc5]589                    self.param_list.append(item)
[fd6b789]590                else:
591                   
[89f3b66]592                    msg = "wrong parameter %s used" % str(item)
593                    msg += "to set model %s. Choose" % str(new_model.model.name)
594                    msg += "parameter name within %s" % \
595                                str(new_model.model.getParamList())
596                    raise ValueError, msg
[fd6b789]597             
[c4d6900]598            #A fitArrange is already created but contains data_list only at id
599            if self.fit_arrange_dict.has_key(id):
600                self.fit_arrange_dict[id].set_model(new_model)
601                self.fit_arrange_dict[id].pars = pars
[6831a99]602            else:
[c4d6900]603            #no fitArrange object has been create with this id
[48882d1]604                fitproblem = FitArrange()
[fd6b789]605                fitproblem.set_model(new_model)
[89f3b66]606                fitproblem.pars = pars
[c4d6900]607                self.fit_arrange_dict[id] = fitproblem
[aed7c57]608               
[d4b0687]609        else:
[6831a99]610            raise ValueError, "park_integration:missing parameters"
[48882d1]611   
[c4d6900]612    def set_data(self, data, id, smearer=None, qmin=None, qmax=None):
[aa36f96]613        """
614        Receives plottable, creates a list of data to fit,set data
615        in a FitArrange object and adds that object in a dictionary
[c4d6900]616        with key id.
[aa36f96]617       
618        :param data: data added
[c4d6900]619        :param id: unique key corresponding to a fitArrange object with data
[aa36f96]620       
[ca6d914]621        """
[89f3b66]622        if data.__class__.__name__ == 'Data2D':
623            fitdata = FitData2D(sans_data2d=data, data=data.data,
624                                 err_data=data.err_data)
[f8ce013]625        else:
[89f3b66]626            fitdata = FitData1D(x=data.x, y=data.y ,
627                                 dx=data.dx, dy=data.dy, smearer=smearer)
[634ca14]628        fitdata.sans_data = data
[393f0f3]629       
[c4d6900]630        fitdata.set_fit_range(qmin=qmin, qmax=qmax)
631        #A fitArrange is already created but contains model only at id
632        if self.fit_arrange_dict.has_key(id):
633            self.fit_arrange_dict[id].add_data(fitdata)
[d4b0687]634        else:
[c4d6900]635        #no fitArrange object has been create with this id
[89f3b66]636            fitproblem = FitArrange()
[f8ce013]637            fitproblem.add_data(fitdata)
[c4d6900]638            self.fit_arrange_dict[id] = fitproblem   
[20d30e9]639   
[c4d6900]640    def get_model(self, id):
[d4b0687]641        """
[aa36f96]642       
[c4d6900]643        :param id: id is key in the dictionary containing the model to return
[aa36f96]644       
[c4d6900]645        :return:  a model at this id or None if no FitArrange element was
646            created with this id
[aa36f96]647           
[d4b0687]648        """
[c4d6900]649        if self.fit_arrange_dict.has_key(id):
650            return self.fit_arrange_dict[id].get_model()
[d4b0687]651        else:
652            return None
653   
[c4d6900]654    def remove_fit_problem(self, id):
655        """remove   fitarrange in id"""
656        if self.fit_arrange_dict.has_key(id):
657            del self.fit_arrange_dict[id]
[a9e04aa]658           
[c4d6900]659    def select_problem_for_fit(self, id, value):
[a9e04aa]660        """
[c4d6900]661        select a couple of model and data at the id position in dictionary
[aa36f96]662        and set in self.selected value to value
663       
664        :param value: the value to allow fitting.
665                can only have the value one or zero
666               
[a9e04aa]667        """
[c4d6900]668        if self.fit_arrange_dict.has_key(id):
669            self.fit_arrange_dict[id].set_to_fit(value)
[eef2e0ed]670             
[c4d6900]671    def get_problem_to_fit(self, id):
[a9e04aa]672        """
[c4d6900]673        return the self.selected value of the fit problem of id
[aa36f96]674       
[c4d6900]675        :param id: the id of the problem
[aa36f96]676       
[a9e04aa]677        """
[c4d6900]678        if self.fit_arrange_dict.has_key(id):
679            self.fit_arrange_dict[id].get_to_fit()
[4c718654]680   
[d4b0687]681class FitArrange:
682    def __init__(self):
683        """
[aa36f96]684        Class FitArrange contains a set of data for a given model
685        to perform the Fit.FitArrange must contain exactly one model
686        and at least one data for the fit to be performed.
687       
688        model: the model selected by the user
689        Ldata: a list of data what the user wants to fit
[d4b0687]690           
691        """
692        self.model = None
[c4d6900]693        self.data_list = []
[89f3b66]694        self.pars = []
[a9e04aa]695        #self.selected  is zero when this fit problem is not schedule to fit
696        #self.selected is 1 when schedule to fit
697        self.selected = 0
[d4b0687]698       
[89f3b66]699    def set_model(self, model):
[d4b0687]700        """
[aa36f96]701        set_model save a copy of the model
702       
703        :param model: the model being set
704       
[d4b0687]705        """
706        self.model = model
707       
[89f3b66]708    def add_data(self, data):
[d4b0687]709        """
[c4d6900]710        add_data fill a self.data_list with data to fit
[aa36f96]711       
712        :param data: Data to add in the list 
713       
[d4b0687]714        """
[c4d6900]715        if not data in self.data_list:
716            self.data_list.append(data)
[d4b0687]717           
718    def get_model(self):
[aa36f96]719        """
720       
721        :return: saved model
722       
723        """
[d4b0687]724        return self.model   
725     
726    def get_data(self):
[aa36f96]727        """
728       
[c4d6900]729        :return: list of data data_list
[aa36f96]730       
731        """
[c4d6900]732        #return self.data_list
733        return self.data_list[0] 
[d4b0687]734     
[89f3b66]735    def remove_data(self, data):
[d4b0687]736        """
[aa36f96]737        Remove one element from the list
738       
[c4d6900]739        :param data: Data to remove from data_list
[aa36f96]740       
[d4b0687]741        """
[c4d6900]742        if data in self.data_list:
743            self.data_list.remove(data)
[aa36f96]744           
[a9e04aa]745    def set_to_fit (self, value=0):
746        """
[aa36f96]747        set self.selected to 0 or 1  for other values raise an exception
748       
749        :param value: integer between 0 or 1
750       
[a9e04aa]751        """
[89f3b66]752        self.selected = value
[a9e04aa]753       
754    def get_to_fit(self):
755        """
[aa36f96]756        return self.selected value
[a9e04aa]757        """
758        return self.selected
Note: See TracBrowser for help on using the repository browser.