Changeset 6fe5100 in sasview


Ignore:
Timestamp:
Apr 6, 2014 5:29:59 AM (10 years ago)
Author:
pkienzle
Branches:
master, ESS_GUI, ESS_GUI_Docs, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_iss959, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc, costrafo411, magnetic_scatt, release-4.1.1, release-4.1.2, release-4.2.2, release_4.0.1, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
Children:
95d58d3
Parents:
960fdbb
Message:

Bumps first pass. Fitting works but no pretty pictures

Files:
1 added
17 edited

Legend:

Unmodified
Added
Removed
  • run.py

    rbbd97e5 r6fe5100  
    88Usage: 
    99 
    10 ./run.py [args] 
     10./run.py [(module|script) args...] 
     11 
     12Without arguments run.py runs sasview.  With arguments, run.py will run 
     13the given module or script. 
    1114""" 
    1215 
     
    122125 
    123126if __name__ == "__main__": 
    124     # start sasview 
    125     #import multiprocessing 
    126     #multiprocessing.freeze_support() 
    127127    prepare() 
    128     from sans.sansview.sansview import SasView 
    129     SasView() 
     128    from sans.sansview.sansview import run 
     129    run() 
  • sansview/sansview.py

    re2271c5 r6fe5100  
    3636PLUGIN_MODEL_DIR = 'plugin_models' 
    3737APP_NAME = 'SasView' 
    38 def run(): 
    39     sys.path.append(os.path.join("..","..","..")) 
    40     from multiprocessing import freeze_support 
    41     freeze_support() 
    42     sasview = SasView() 
    43          
     38 
    4439class SasViewApp(gui_manager.ViewApp): 
    4540    """ 
     
    113108        self.gui.clean_plugin_models(PLUGIN_MODEL_DIR) 
    114109        # Start the main loop 
    115         self.gui.MainLoop()   
    116         
     110        self.gui.MainLoop() 
    117111 
    118112 
    119 if __name__ == "__main__":  
     113def run(): 
    120114    from multiprocessing import freeze_support 
    121115    freeze_support() 
    122     #Process(target=SasView).start() 
    123     sasview = SasView() 
     116    if len(sys.argv) > 1: 
     117        thing_to_run = sys.argv[1] 
     118        sys.argv = sys.argv[1:] 
     119        import runpy 
     120        if os.path.exists(thing_to_run): 
     121            runpy.run_path(thing_to_run) 
     122        else: 
     123            runpy.run_module(thing_to_run) 
     124    else: 
     125        SasView() 
    124126 
    125     
     127if __name__ == "__main__": 
     128    run() 
     129 
  • sansview/setup_exe.py

    r27b7acc r6fe5100  
    319319'reportlab.platypus', 
    320320]) 
     321packages.append('IPython') 
    321322includes = ['site'] 
    322323 
  • setup.py

    r968aa6e r6fe5100  
    6969     
    7070     
    71 enable_openmp = True                     
     71enable_openmp = False 
    7272 
    7373if sys.platform =='darwin': 
  • src/sans/fit/AbstractFitEngine.py

    r6c00702 r6fe5100  
    33#import logging 
    44import sys 
     5import math 
    56import numpy 
    6 import math 
    7 import park 
     7 
    88from sans.dataloader.data_info import Data1D 
    99from sans.dataloader.data_info import Data2D 
    10 _SMALLVALUE = 1.0e-10     
    11      
    12 class SansParameter(park.Parameter): 
    13     """ 
    14     SANS model parameters for use in the PARK fitting service. 
    15     The parameter attribute value is redirected to the underlying 
    16     parameter value in the SANS model. 
    17     """ 
    18     def __init__(self, name, model, data): 
    19         """ 
    20             :param name: the name of the model parameter 
    21             :param model: the sans model to wrap as a park model 
    22         """ 
    23         park.Parameter.__init__(self, name) 
    24         self._model, self._name = model, name 
    25         self.data = data 
    26         self.model = model 
    27         #set the value for the parameter of the given name 
    28         self.set(model.getParam(name)) 
    29           
    30     def _getvalue(self): 
    31         """ 
    32         override the _getvalue of park parameter 
    33          
    34         :return value the parameter associates with self.name 
    35          
    36         """ 
    37         return self._model.getParam(self.name) 
    38      
    39     def _setvalue(self, value): 
    40         """ 
    41         override the _setvalue pf park parameter 
    42          
    43         :param value: the value to set on a given parameter 
    44          
    45         """ 
    46         self._model.setParam(self.name, value) 
    47          
    48     value = property(_getvalue, _setvalue) 
    49      
    50     def _getrange(self): 
    51         """ 
    52         Override _getrange of park parameter 
    53         return the range of parameter 
    54         """ 
    55         #if not  self.name in self._model.getDispParamList(): 
    56         lo, hi = self._model.details[self.name][1:3] 
    57         if lo is None: lo = -numpy.inf 
    58         if hi is None: hi = numpy.inf 
    59         if lo > hi: 
    60             raise ValueError, "wrong fit range for parameters" 
    61          
    62         return lo, hi 
    63      
    64     def get_name(self): 
    65         """ 
    66         """ 
    67         return self._getname() 
    68      
    69     def _setrange(self, r): 
    70         """ 
    71         override _setrange of park parameter 
    72          
    73         :param r: the value of the range to set 
    74          
    75         """ 
    76         self._model.details[self.name][1:3] = r 
    77     range = property(_getrange, _setrange) 
    78      
    79      
    80 class Model(park.Model): 
    81     """ 
    82     PARK wrapper for SANS models. 
     10_SMALLVALUE = 1.0e-10 
     11 
     12# Note: duplicated from park 
     13class FitHandler(object): 
     14    """ 
     15    Abstract interface for fit thread handler. 
     16 
     17    The methods in this class are called by the optimizer as the fit 
     18    progresses. 
     19 
     20    Note that it is up to the optimizer to call the fit handler correctly, 
     21    reporting all status changes and maintaining the 'done' flag. 
     22    """ 
     23    done = False 
     24    """True when the fit job is complete""" 
     25    result = None 
     26    """The current best result of the fit""" 
     27 
     28    def improvement(self): 
     29        """ 
     30        Called when a result is observed which is better than previous 
     31        results from the fit. 
     32 
     33        result is a FitResult object, with parameters, #calls and fitness. 
     34        """ 
     35    def error(self, msg): 
     36        """ 
     37        Model had an error; print traceback 
     38        """ 
     39    def progress(self, current, expected): 
     40        """ 
     41        Called each cycle of the fit, reporting the current and the 
     42        expected amount of work.   The meaning of these values is 
     43        optimizer dependent, but they can be converted into a percent 
     44        complete using (100*current)//expected. 
     45 
     46        Progress is updated each iteration of the fit, whatever that 
     47        means for the particular optimization algorithm.  It is called 
     48        after any calls to improvement for the iteration so that the 
     49        update handler can control I/O bandwidth by suppressing 
     50        intermediate improvements until the fit is complete. 
     51        """ 
     52    def finalize(self): 
     53        """ 
     54        Fit is complete; best results are reported 
     55        """ 
     56    def abort(self): 
     57        """ 
     58        Fit was aborted. 
     59        """ 
     60 
     61class Model: 
     62    """ 
     63    Fit wrapper for SANS models. 
    8364    """ 
    8465    def __init__(self, sans_model, sans_data=None, **kw): 
    8566        """ 
    8667        :param sans_model: the sans model to wrap using park interface 
    87          
    88         """ 
    89         park.Model.__init__(self, **kw) 
     68 
     69        """ 
    9070        self.model = sans_model 
    9171        self.name = sans_model.name 
    9272        self.data = sans_data 
    93         #list of parameters names 
    94         self.sansp = sans_model.getParamList() 
    95         #list of park parameter 
    96         self.parkp = [SansParameter(p, sans_model, sans_data) for p in self.sansp] 
    97         #list of parameter set 
    98         self.parameterset = park.ParameterSet(sans_model.name, pars=self.parkp) 
    99         self.pars = [] 
    100    
     73 
    10174    def get_params(self, fitparams): 
    10275        """ 
    10376        return a list of value of paramter to fit 
    104          
     77 
    10578        :param fitparams: list of paramaters name to fit 
    106          
    107         """ 
    108         list_params = [] 
    109         self.pars = [] 
    110         self.pars = fitparams 
    111         for item in fitparams: 
    112             for element in self.parkp: 
    113                 if element.name == str(item): 
    114                     list_params.append(element.value) 
    115         return list_params 
    116      
     79 
     80        """ 
     81        return [self.model.getParam(k) for k in fitparams] 
     82 
    11783    def set_params(self, paramlist, params): 
    11884        """ 
    11985        Set value for parameters to fit 
    120          
     86 
    12187        :param params: list of value for parameters to fit 
    122          
    123         """ 
    124         try: 
    125             for i in range(len(self.parkp)): 
    126                 for j in range(len(paramlist)): 
    127                     if self.parkp[i].name == paramlist[j]: 
    128                         self.parkp[i].value = params[j] 
    129                         self.model.setParam(self.parkp[i].name, params[j]) 
    130         except: 
    131             raise 
    132    
     88 
     89        """ 
     90        for k,v in zip(paramlist, params): 
     91            self.model.setParam(k,v) 
     92 
     93    def set(self, **kw): 
     94        self.set_params(*zip(*kw.items())) 
     95 
    13396    def eval(self, x): 
    13497        """ 
    13598            Override eval method of park model. 
    136          
     99 
    137100            :param x: the x value used to compute a function 
    138101        """ 
     
    141104        except: 
    142105            raise 
    143          
     106 
    144107    def eval_derivs(self, x, pars=[]): 
    145108        """ 
     
    154117        instead of calling eval. 
    155118        """ 
    156         return [] 
    157  
    158      
     119        raise NotImplementedError('no derivatives available') 
     120 
     121    def __call__(self, x): 
     122        return self.eval(x) 
     123 
    159124class FitData1D(Data1D): 
    160125    """ 
     
    185150        """ 
    186151        Data1D.__init__(self, x=x, y=y, dx=dx, dy=dy) 
     152        self.num_points = len(x) 
    187153        self.sans_data = data 
    188154        self.smearer = smearer 
     
    298264        """ 
    299265        self.res_err_image = [] 
     266        self.num_points = data.size 
    300267        self.idx = [] 
    301268        self.qmin = None 
     
    409376 
    410377 
    411 class SansAssembly: 
    412     """ 
    413     Sans Assembly class a class wrapper to be call in optimizer.leastsq method 
    414     """ 
    415     def __init__(self, paramlist, model=None, data=None, fitresult=None, 
    416                  handler=None, curr_thread=None, msg_q=None): 
    417         """ 
    418         :param Model: the model wrapper fro sans -model 
    419         :param Data: the data wrapper for sans data 
    420          
    421         """ 
    422         self.model = model 
    423         self.data = data 
    424         self.paramlist = paramlist 
    425         self.msg_q = msg_q 
    426         self.curr_thread = curr_thread 
    427         self.handler = handler 
    428         self.fitresult = fitresult 
    429         self.res = [] 
    430         self.true_res = [] 
    431         self.func_name = "Functor" 
    432         self.theory = None 
    433          
    434     def chisq(self): 
    435         """ 
    436         Calculates chi^2 
    437          
    438         :param params: list of parameter values 
    439          
    440         :return: chi^2 
    441          
    442         """ 
    443         total = 0 
    444         for item in self.true_res: 
    445             total += item * item 
    446         if len(self.true_res) == 0: 
    447             return None 
    448         return total / len(self.true_res) 
    449      
    450     def __call__(self, params): 
    451         """ 
    452             Compute residuals 
    453             :param params: value of parameters to fit 
    454         """ 
    455         #import thread 
    456         self.model.set_params(self.paramlist, params) 
    457         #print "params", params 
    458         self.true_res, theory = self.data.residuals(self.model.eval) 
    459         self.theory = copy.deepcopy(theory) 
    460         # check parameters range 
    461         if self.check_param_range(): 
    462             # if the param value is outside of the bound 
    463             # just silent return res = inf 
    464             return self.res 
    465         self.res = self.true_res 
    466          
    467         if self.fitresult is not None: 
    468             self.fitresult.set_model(model=self.model) 
    469             self.fitresult.residuals = self.true_res 
    470             self.fitresult.iterations += 1 
    471             self.fitresult.theory = theory 
    472             
    473             #fitness = self.chisq(params=params) 
    474             fitness = self.chisq() 
    475             self.fitresult.pvec = params 
    476             self.fitresult.set_fitness(fitness=fitness) 
    477             if self.msg_q is not None: 
    478                 self.msg_q.put(self.fitresult) 
    479                  
    480             if self.handler is not None: 
    481                 self.handler.set_result(result=self.fitresult) 
    482                 self.handler.update_fit() 
    483  
    484             if self.curr_thread != None: 
    485                 try: 
    486                     self.curr_thread.isquit() 
    487                 except: 
    488                     #msg = "Fitting: Terminated...       Note: Forcing to stop " 
    489                     #msg += "fitting may cause a 'Functor error message' " 
    490                     #msg += "being recorded in the log file....." 
    491                     #self.handler.stop(msg) 
    492                     raise 
    493           
    494         return self.res 
    495      
    496     def check_param_range(self): 
    497         """ 
    498         Check the lower and upper bound of the parameter value 
    499         and set res to the inf if the value is outside of the 
    500         range 
    501         :limitation: the initial values must be within range. 
    502         """ 
    503  
    504         #time.sleep(0.01) 
    505         is_outofbound = False 
    506         # loop through the fit parameters 
    507         for p in self.model.parameterset: 
    508             param_name = p.get_name() 
    509             if param_name in self.paramlist: 
    510                  
    511                 # if the range was defined, check the range 
    512                 if numpy.isfinite(p.range[0]): 
    513                     if p.value == 0: 
    514                         # This value works on Scipy 
    515                         # Do not change numbers below 
    516                         value = _SMALLVALUE 
    517                     else: 
    518                         value = p.value 
    519                     # For leastsq, it needs a bit step back from the boundary 
    520                     val = p.range[0] - value * _SMALLVALUE 
    521                     if p.value < val: 
    522                         self.res *= 1e+6 
    523                          
    524                         is_outofbound = True 
    525                         break 
    526                 if numpy.isfinite(p.range[1]): 
    527                     # This value works on Scipy 
    528                     # Do not change numbers below 
    529                     if p.value == 0: 
    530                         value = _SMALLVALUE 
    531                     else: 
    532                         value = p.value 
    533                     # For leastsq, it needs a bit step back from the boundary 
    534                     val = p.range[1] + value * _SMALLVALUE 
    535                     if p.value > val: 
    536                         self.res *= 1e+6 
    537                         is_outofbound = True 
    538                         break 
    539  
    540         return is_outofbound 
    541      
    542      
     378 
    543379class FitEngine: 
    544380    def __init__(self): 
     
    754590     
    755591     
    756 IS_MAC = True 
    757 if sys.platform.count("win32") > 0: 
    758     IS_MAC = False 
    759  
    760  
    761592class FResult(object): 
    762593    """ 
     
    777608        self.index = [] 
    778609        self.parameters = None 
    779         self.is_mac = IS_MAC 
    780610        self.model = model 
    781611        self.data = data 
     
    803633        if self.pvec == None and self.model is None and self.param_list is None: 
    804634            return "No results" 
    805         n = len(self.model.parameterset) 
    806          
    807         result_param = zip(xrange(n), self.model.parameterset) 
    808         msg1 = ["[Iteration #: %s ]" % self.iterations] 
    809         msg3 = ["=== goodness of fit: %s ===" % (str(self.fitness))] 
    810         if not self.is_mac: 
    811             msg2 = ["P%-3d  %s......|.....%s" % \ 
    812                 (p[0], p[1], p[1].value)\ 
    813                   for p in result_param if p[1].name in self.param_list] 
    814             msg = msg1 + msg3 + msg2 
    815         else: 
    816             msg = msg1 + msg3 
    817         msg = "\n".join(msg) 
    818         return msg 
     635 
     636        pars = enumerate(self.model.model.getParamList()) 
     637        msg1 = "[Iteration #: %s ]" % self.iterations 
     638        msg3 = "=== goodness of fit: %s ===" % (str(self.fitness)) 
     639        msg2 = ["P%-3d  %s......|.....%s" % (i, v, self.model.model.getParam(v)) 
     640                for i,v in pars if v in self.param_list] 
     641        msg = [msg1, msg3] + msg2 
     642        return "\n".join(msg) 
    819643     
    820644    def print_summary(self): 
  • src/sans/fit/Fitting.py

    r5777106 r6fe5100  
    88from sans.fit.ScipyFitting import ScipyFit 
    99from sans.fit.ParkFitting import ParkFit 
     10from sans.fit.BumpsFitting import BumpsFit 
    1011 
     12ENGINES={ 
     13    'scipy': ScipyFit, 
     14    'park': ParkFit, 
     15    'bumps': BumpsFit, 
     16} 
    1117 
    1218class Fit(object): 
     
    5965              
    6066        """ 
    61         if word == "scipy": 
    62             self._engine = ScipyFit() 
    63         elif word == "park": 
    64             self._engine = ParkFit() 
    65         else: 
    66             raise ValueError, "enter the keyword scipy or park" 
     67        try: 
     68            self._engine = ENGINES[word]() 
     69        except KeyError, exc: 
     70            raise KeyError("fit engine should be one of scipy, park or bumps") 
    6771 
    6872    def fit(self, msg_q=None, q=None, handler=None,  
  • src/sans/fit/Loader.py

    r5777106 r6fe5100  
    88    This class is loading values from given file or value giving by the user 
    99    """ 
    10      
    1110    def __init__(self, x=None, y=None, dx=None, dy=None): 
     11        raise NotImplementedError("a code search shows that this code is not active, and you are not seeing this message") 
    1212        # variable to store loaded values 
    1313        self.x = x 
  • src/sans/fit/ParkFitting.py

    r9d6d5ba r6fe5100  
    2424from sans.fit.AbstractFitEngine import FitEngine 
    2525from sans.fit.AbstractFitEngine import FResult 
    26    
     26 
     27class SansParameter(park.Parameter): 
     28    """ 
     29    SANS model parameters for use in the PARK fitting service. 
     30    The parameter attribute value is redirected to the underlying 
     31    parameter value in the SANS model. 
     32    """ 
     33    def __init__(self, name, model, data): 
     34        """ 
     35            :param name: the name of the model parameter 
     36            :param model: the sans model to wrap as a park model 
     37        """ 
     38        park.Parameter.__init__(self, name) 
     39        self._model, self._name = model, name 
     40        self.data = data 
     41        self.model = model 
     42        #set the value for the parameter of the given name 
     43        self.set(model.getParam(name)) 
     44 
     45    def _getvalue(self): 
     46        """ 
     47        override the _getvalue of park parameter 
     48 
     49        :return value the parameter associates with self.name 
     50 
     51        """ 
     52        return self._model.getParam(self.name) 
     53 
     54    def _setvalue(self, value): 
     55        """ 
     56        override the _setvalue pf park parameter 
     57 
     58        :param value: the value to set on a given parameter 
     59 
     60        """ 
     61        self._model.setParam(self.name, value) 
     62 
     63    value = property(_getvalue, _setvalue) 
     64 
     65    def _getrange(self): 
     66        """ 
     67        Override _getrange of park parameter 
     68        return the range of parameter 
     69        """ 
     70        #if not  self.name in self._model.getDispParamList(): 
     71        lo, hi = self._model.details[self.name][1:3] 
     72        if lo is None: lo = -numpy.inf 
     73        if hi is None: hi = numpy.inf 
     74        if lo > hi: 
     75            raise ValueError, "wrong fit range for parameters" 
     76 
     77        return lo, hi 
     78 
     79    def get_name(self): 
     80        """ 
     81        """ 
     82        return self._getname() 
     83 
     84    def _setrange(self, r): 
     85        """ 
     86        override _setrange of park parameter 
     87 
     88        :param r: the value of the range to set 
     89 
     90        """ 
     91        self._model.details[self.name][1:3] = r 
     92    range = property(_getrange, _setrange) 
     93 
     94 
     95class Model(park.Model): 
     96    """ 
     97    PARK wrapper for SANS models. 
     98    """ 
     99    def __init__(self, sans_model, sans_data=None, **kw): 
     100        """ 
     101        :param sans_model: the sans model to wrap using park interface 
     102 
     103        """ 
     104        park.Model.__init__(self, **kw) 
     105        self.model = sans_model 
     106        self.name = sans_model.name 
     107        self.data = sans_data 
     108        #list of parameters names 
     109        self.sansp = sans_model.getParamList() 
     110        #list of park parameter 
     111        self.parkp = [SansParameter(p, sans_model, sans_data) for p in self.sansp] 
     112        #list of parameter set 
     113        self.parameterset = park.ParameterSet(sans_model.name, pars=self.parkp) 
     114        self.pars = [] 
     115 
     116    def get_params(self, fitparams): 
     117        """ 
     118        return a list of value of paramter to fit 
     119 
     120        :param fitparams: list of paramaters name to fit 
     121 
     122        """ 
     123        list_params = [] 
     124        self.pars = [] 
     125        self.pars = fitparams 
     126        for item in fitparams: 
     127            for element in self.parkp: 
     128                if element.name == str(item): 
     129                    list_params.append(element.value) 
     130        return list_params 
     131 
     132    def set_params(self, paramlist, params): 
     133        """ 
     134        Set value for parameters to fit 
     135 
     136        :param params: list of value for parameters to fit 
     137 
     138        """ 
     139        try: 
     140            for i in range(len(self.parkp)): 
     141                for j in range(len(paramlist)): 
     142                    if self.parkp[i].name == paramlist[j]: 
     143                        self.parkp[i].value = params[j] 
     144                        self.model.setParam(self.parkp[i].name, params[j]) 
     145        except: 
     146            raise 
     147 
     148    def eval(self, x): 
     149        """ 
     150            Override eval method of park model. 
     151 
     152            :param x: the x value used to compute a function 
     153        """ 
     154        try: 
     155            return self.model.evalDistribution(x) 
     156        except: 
     157            raise 
     158 
     159    def eval_derivs(self, x, pars=[]): 
     160        """ 
     161        Evaluate the model and derivatives wrt pars at x. 
     162 
     163        pars is a list of the names of the parameters for which derivatives 
     164        are desired. 
     165 
     166        This method needs to be specialized in the model to evaluate the 
     167        model function.  Alternatively, the model can implement is own 
     168        version of residuals which calculates the residuals directly 
     169        instead of calling eval. 
     170        """ 
     171        return [] 
     172 
     173 
    27174class SansFitResult(fitresult.FitResult): 
    28175    def __init__(self, *args, **kwrds): 
     
    383530    def fit(self, msg_q=None,  
    384531            q=None, handler=None, curr_thread=None,  
    385                                         ftol=1.49012e-8, reset_flag=False): 
     532            ftol=1.49012e-8, reset_flag=False): 
    386533        """ 
    387534        Performs fit with park.fit module.It can  perform fit with one model 
  • src/sans/fit/ScipyFitting.py

    r5777106 r6fe5100  
    1  
    2  
    31""" 
    42ScipyFitting module contains FitArrange , ScipyFit, 
     
    64simple fit with scipy optimizer. 
    75""" 
     6import sys 
     7import copy 
    88 
    99import numpy  
    10 import sys 
    11  
    1210 
    1311from sans.fit.AbstractFitEngine import FitEngine 
    14 from sans.fit.AbstractFitEngine import SansAssembly 
    15 from sans.fit.AbstractFitEngine import FitAbort 
    16 from sans.fit.AbstractFitEngine import Model 
    17 from sans.fit.AbstractFitEngine import FResult  
     12from sans.fit.AbstractFitEngine import FResult 
     13 
     14class SansAssembly: 
     15    """ 
     16    Sans Assembly class a class wrapper to be call in optimizer.leastsq method 
     17    """ 
     18    def __init__(self, paramlist, model=None, data=None, fitresult=None, 
     19                 handler=None, curr_thread=None, msg_q=None): 
     20        """ 
     21        :param Model: the model wrapper fro sans -model 
     22        :param Data: the data wrapper for sans data 
     23 
     24        """ 
     25        self.model = model 
     26        self.data = data 
     27        self.paramlist = paramlist 
     28        self.msg_q = msg_q 
     29        self.curr_thread = curr_thread 
     30        self.handler = handler 
     31        self.fitresult = fitresult 
     32        self.res = [] 
     33        self.true_res = [] 
     34        self.func_name = "Functor" 
     35        self.theory = None 
     36 
     37    def chisq(self): 
     38        """ 
     39        Calculates chi^2 
     40 
     41        :param params: list of parameter values 
     42 
     43        :return: chi^2 
     44 
     45        """ 
     46        total = 0 
     47        for item in self.true_res: 
     48            total += item * item 
     49        if len(self.true_res) == 0: 
     50            return None 
     51        return total / len(self.true_res) 
     52 
     53    def __call__(self, params): 
     54        """ 
     55            Compute residuals 
     56            :param params: value of parameters to fit 
     57        """ 
     58        #import thread 
     59        self.model.set_params(self.paramlist, params) 
     60        #print "params", params 
     61        self.true_res, theory = self.data.residuals(self.model.eval) 
     62        self.theory = copy.deepcopy(theory) 
     63        # check parameters range 
     64        if self.check_param_range(): 
     65            # if the param value is outside of the bound 
     66            # just silent return res = inf 
     67            return self.res 
     68        self.res = self.true_res 
     69 
     70        if self.fitresult is not None: 
     71            self.fitresult.set_model(model=self.model) 
     72            self.fitresult.residuals = self.true_res 
     73            self.fitresult.iterations += 1 
     74            self.fitresult.theory = theory 
     75 
     76            #fitness = self.chisq(params=params) 
     77            fitness = self.chisq() 
     78            self.fitresult.pvec = params 
     79            self.fitresult.set_fitness(fitness=fitness) 
     80            if self.msg_q is not None: 
     81                self.msg_q.put(self.fitresult) 
     82 
     83            if self.handler is not None: 
     84                self.handler.set_result(result=self.fitresult) 
     85                self.handler.update_fit() 
     86 
     87            if self.curr_thread != None: 
     88                try: 
     89                    self.curr_thread.isquit() 
     90                except: 
     91                    #msg = "Fitting: Terminated...       Note: Forcing to stop " 
     92                    #msg += "fitting may cause a 'Functor error message' " 
     93                    #msg += "being recorded in the log file....." 
     94                    #self.handler.stop(msg) 
     95                    raise 
     96 
     97        return self.res 
     98 
     99    def check_param_range(self): 
     100        """ 
     101        Check the lower and upper bound of the parameter value 
     102        and set res to the inf if the value is outside of the 
     103        range 
     104        :limitation: the initial values must be within range. 
     105        """ 
     106 
     107        #time.sleep(0.01) 
     108        is_outofbound = False 
     109        # loop through the fit parameters 
     110        model = self.model.model 
     111        for p in self.paramlist: 
     112            value = model.getParam(p) 
     113            low,high = model.details[p][1:3] 
     114            if low is not None and numpy.isfinite(low): 
     115                if p.value == 0: 
     116                    # This value works on Scipy 
     117                    # Do not change numbers below 
     118                    value = _SMALLVALUE 
     119                # For leastsq, it needs a bit step back from the boundary 
     120                val = low - value * _SMALLVALUE 
     121                if value < val: 
     122                    self.res *= 1e+6 
     123                    is_outofbound = True 
     124                    break 
     125            if high is not None and numpy.isfinite(high): 
     126                # This value works on Scipy 
     127                # Do not change numbers below 
     128                if value == 0: 
     129                    value = _SMALLVALUE 
     130                # For leastsq, it needs a bit step back from the boundary 
     131                val = high + value * _SMALLVALUE 
     132                if value > val: 
     133                    self.res *= 1e+6 
     134                    is_outofbound = True 
     135                    break 
     136 
     137        return is_outofbound 
    18138 
    19139class ScipyFit(FitEngine): 
     
    50170        """ 
    51171        FitEngine.__init__(self) 
    52         self.fit_arrange_dict = {} 
    53         self.param_list = [] 
    54172        self.curr_thread = None 
    55173    #def fit(self, *args, **kw): 
     
    68186            msg = "Scipy can't fit more than a single fit problem at a time." 
    69187            raise RuntimeError, msg 
    70             return 
    71         elif len(fitproblem) == 0 :  
     188        elif len(fitproblem) == 0 : 
    72189            raise RuntimeError, "No Assembly scheduled for Scipy fitting." 
    73             return 
    74190        model = fitproblem[0].get_model() 
    75191        if reset_flag: 
     
    87203         
    88204        # Check the initial value if it is within range 
    89         self._check_param_range(model) 
     205        _check_param_range(model.model, self.param_list) 
    90206         
    91207        result = FResult(model=model, data=data, param_list=self.param_list) 
     
    94210        if handler is not None: 
    95211            handler.set_result(result=result) 
     212        functor = SansAssembly(paramlist=self.param_list, 
     213                               model=model, 
     214                               data=data, 
     215                               handler=handler, 
     216                               fitresult=result, 
     217                               curr_thread=curr_thread, 
     218                               msg_q=msg_q) 
    96219        try: 
    97220            # This import must be here; otherwise it will be confused when more 
     
    99222            from scipy import optimize 
    100223             
    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) 
    108224            out, cov_x, _, mesg, success = optimize.leastsq(functor, 
    109225                                            model.get_params(self.param_list), 
    110                                                     ftol=ftol, 
    111                                                     full_output=1) 
     226                                            ftol=ftol, 
     227                                            full_output=1) 
    112228        except: 
    113229            if hasattr(sys, 'last_type') and sys.last_type == KeyboardInterrupt: 
     
    142258 
    143259         
    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      
     260def _check_param_range(model, param_list): 
     261    """ 
     262    Check parameter range and set the initial value inside 
     263    if it is out of range. 
     264 
     265    : model: park model object 
     266    """ 
     267    # loop through parameterset 
     268    for p in param_list: 
     269        value = model.getParam(p) 
     270        low,high = model.details[p][1:3] 
     271        # if the range was defined, check the range 
     272        if low is not None and value <= low: 
     273            value = low + _get_zero_shift(low) 
     274        if high is not None and value > high: 
     275            value = high - _get_zero_shift(high) 
     276            # Check one more time if the new value goes below 
     277            # the low bound, If so, re-evaluate the value 
     278            # with the mean of the range. 
     279            if low is not None and value < low: 
     280                value = 0.5 * (low+high) 
     281        model.setParam(p, value) 
     282 
     283def _get_zero_shift(limit): 
     284    """ 
     285    Get 10% shift of the param value = 0 based on the range value 
     286 
     287    : param range: min or max value of the bounds 
     288    """ 
     289    return 0.1 (limit if limit != 0.0 else 1.0) 
     290 
    198291     
    199292#def profile(fn, *args, **kw): 
  • src/sans/fit/__init__.py

    r5777106 r6fe5100  
     1from .AbstractFitEngine import FitHandler 
  • src/sans/perspectives/fitting/basepage.py

    r27b7acc r6fe5100  
    808808            infor = "warning" 
    809809        else: 
    810             msg = "Error was occured " 
    811             msg += ": No valid parameter values to paste from the clipboard..." 
     810            msg = "Error occured: " 
     811            msg += "No valid parameter values to paste from the clipboard..." 
    812812            infor = "error" 
    813813            wx.PostEvent(self._manager.parent, 
     
    21492149                else: 
    21502150                    tcrtl.SetBackgroundColour("pink") 
    2151                     msg = "Model Error:wrong value entered: %s" % sys.exc_value 
     2151                    msg = "Model Error: wrong value entered: %s" % sys.exc_value 
    21522152                    wx.PostEvent(self.parent, StatusEvent(status=msg)) 
    21532153                    return 
    21542154            except: 
    21552155                tcrtl.SetBackgroundColour("pink") 
    2156                 msg = "Model Error:wrong value entered: %s" % sys.exc_value 
     2156                msg = "Model Error: wrong value entered: %s" % sys.exc_value 
    21572157                wx.PostEvent(self.parent, StatusEvent(status=msg)) 
    21582158                return 
     
    21652165                        #is_modified = True 
    21662166                else: 
    2167                     msg = "Cannot Plot :No npts in that Qrange!!!  " 
     2167                    msg = "Cannot plot: No points in Q range!!!  " 
    21682168                    wx.PostEvent(self.parent, StatusEvent(status=msg)) 
    21692169        else: 
    21702170            tcrtl.SetBackgroundColour("pink") 
    2171             msg = "Model Error:wrong value entered!!!" 
     2171            msg = "Model Error: wrong value entered!!!" 
    21722172            wx.PostEvent(self.parent, StatusEvent(status=msg)) 
    21732173        self.save_current_state() 
     
    22062206                else: 
    22072207                    tcrtl.SetBackgroundColour("pink") 
    2208                     msg = "Model Error:wrong value entered: %s" % sys.exc_value 
     2208                    msg = "Model Error: wrong value entered: %s" % sys.exc_value 
    22092209                    wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 
    22102210                    return 
    22112211            except: 
    22122212                tcrtl.SetBackgroundColour("pink") 
    2213                 msg = "Model Error:wrong value entered: %s" % sys.exc_value 
     2213                msg = "Model Error: wrong value entered: %s" % sys.exc_value 
    22142214                wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 
    22152215                return 
     
    22222222                        is_modified = True 
    22232223                else: 
    2224                     msg = "Cannot Plot :No npts in that Qrange!!!  " 
     2224                    msg = "Cannot Plot: No points in Q range!!!  " 
    22252225                    wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 
    22262226        else: 
    22272227            tcrtl.SetBackgroundColour("pink") 
    2228             msg = "Model Error:wrong value entered!!!" 
     2228            msg = "Model Error: wrong value entered!!!" 
    22292229            wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 
    22302230        self.save_current_state() 
     
    23972397                self.qmax.SetBackgroundColour("pink") 
    23982398                self.qmax.Refresh() 
    2399                 msg = "Npts of Data Error :" 
    2400                 msg += "No or too little npts of %s." % data.name 
     2399                msg = "Data Error: " 
     2400                msg += "Too few points in %s." % data.name 
    24012401                wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 
    24022402                self.fitrange = False 
     
    24322432                self.qmax.SetBackgroundColour("pink") 
    24332433                self.qmax.Refresh() 
    2434                 msg = "Npts of Data Error :" 
    2435                 msg += "No or too little npts of %s." % data.name 
     2434                msg = "Data Error: " 
     2435                msg += "Too few points in %s." % data.name 
    24362436                wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 
    24372437                self.fitrange = False 
     
    24842484                                            
    24852485                        except: 
    2486                             msg = "Wrong Fit parameter range entered " 
     2486                            msg = "Wrong fit parameter range entered" 
    24872487                            wx.PostEvent(self._manager.parent, 
    24882488                                         StatusEvent(status=msg)) 
  • src/sans/perspectives/fitting/console.py

    r5777106 r6fe5100  
    55import time 
    66import wx 
    7 import park 
    8 from park.fitresult import FitHandler 
     7from sans.fit import FitHandler 
    98 
    109class ConsoleUpdate(FitHandler): 
  • src/sans/perspectives/fitting/fitting.py

    r767514a r6fe5100  
    111111        self.scipy_id = wx.NewId() 
    112112        self.park_id = wx.NewId() 
     113        self.bumps_id = wx.NewId() 
    113114        self.menu1 = None 
    114115        self.new_model_frame = None 
     
    198199        wx.EVT_MENU(owner, self.park_id, self._onset_engine_park) 
    199200         
     201        bumps_help = "Bumps: fitting and uncertainty analysis. More in Help window...." 
     202        self.menu1.AppendCheckItem(self.bumps_id, "Bumps fit", 
     203                                   bumps_help) 
     204        wx.EVT_MENU(owner, self.bumps_id, self._onset_engine_bumps) 
     205         
    200206        self.menu1.FindItemById(self.scipy_id).Check(True) 
    201207        self.menu1.FindItemById(self.park_id).Check(False) 
     208        self.menu1.FindItemById(self.bumps_id).Check(False) 
    202209        self.menu1.AppendSeparator() 
    203210        self.id_tol = wx.NewId() 
     
    207214                                   ftol_help) 
    208215        wx.EVT_MENU(owner, self.id_tol, self.show_ftol_dialog) 
     216 
     217        self.id_bumps_options = wx.NewId() 
     218        bopts_help = "Bumps fitting options" 
     219        self.menu1.Append(self.id_bumps_options, 'Bumps &Options', bopts_help) 
     220        wx.EVT_MENU(owner, self.id_bumps_options, self.on_bumps_options) 
     221        self.bumps_options_menu = self.menu1.FindItemById(self.id_bumps_options) 
     222        self.bumps_options_menu.Enable(True) 
    209223        self.menu1.AppendSeparator() 
    210224         
     
    819833        dialog.Destroy() 
    820834 
     835    def on_bumps_options(self, event=None): 
     836        from bumps.gui.fit_dialog import OpenFitOptions 
     837        OpenFitOptions() 
     838 
    821839    def stop_fit(self, uid): 
    822840        """ 
     
    959977        self._gui_engine = self._return_engine_type() 
    960978        self.fitproblem_count = fitproblem_count 
    961         if self._fit_engine == "park": 
     979        if self._fit_engine in ("park","bumps"): 
    962980            engineType = "Simultaneous Fit" 
    963981        else: 
     
    16821700        self._on_change_engine('scipy') 
    16831701        
     1702    def _onset_engine_bumps(self, event): 
     1703        """  
     1704        set engine to bumps 
     1705        """ 
     1706        self._on_change_engine('bumps') 
     1707        
    16841708    def _on_slicer_event(self, event): 
    16851709        """ 
     
    17331757            self.menu1.FindItemById(self.park_id).Check(True) 
    17341758            self.menu1.FindItemById(self.scipy_id).Check(False) 
     1759            self.menu1.FindItemById(self.bumps_id).Check(False) 
     1760        elif engine == "scipy": 
     1761            self.menu1.FindItemById(self.park_id).Check(False) 
     1762            self.menu1.FindItemById(self.scipy_id).Check(True) 
     1763            self.menu1.FindItemById(self.bumps_id).Check(False) 
    17351764        else: 
    17361765            self.menu1.FindItemById(self.park_id).Check(False) 
    1737             self.menu1.FindItemById(self.scipy_id).Check(True) 
     1766            self.menu1.FindItemById(self.scipy_id).Check(False) 
     1767            self.menu1.FindItemById(self.bumps_id).Check(True) 
    17381768        ## post a message to status bar 
    17391769        msg = "Engine set to: %s" % self._fit_engine 
  • test/park_integration/test/test_fit_line.py

    rda5d8e8 r6fe5100  
    44""" 
    55import unittest 
     6import math 
    67 
    78from sans.fit.AbstractFitEngine import Model 
     
    1112from sans.models.Constant import Constant 
    1213 
    13 import math 
    1414class testFitModule(unittest.TestCase): 
    1515    """ test fitting """ 
     
    2121        data.name = data.filename 
    2222        #Importing the Fit module 
    23         fitter = Fit('scipy') 
     23        from bumps import fitters 
     24        fitters.FIT_DEFAULT = 'dream' 
     25        print fitters.FIT_OPTIONS['dream'].__dict__ 
     26        fitter = Fit('bumps') 
    2427        # Receives the type of model for the fitting 
    2528        model1  = LineModel() 
     
    4447        self.assertTrue( result1.fitness/len(data.x) < 2 ) 
    4548 
     49        return 
    4650        #fit with park test 
    4751        fitter = Fit('park') 
     
    103107           assert str(msg)=="Scipy can't fit more than a single fit problem at a time." 
    104108        else: raise AssertionError,"No error raised for scipy fitting with more than 2 models" 
    105          
     109 
     110        return 
    106111        #fit with park test 
    107112        fitter = Fit('park') 
     
    121126    def test3(self): 
    122127        """ fit 2 data and 2 model with 1 constrainst""" 
     128        return 
    123129        #load data 
    124130        l = Loader() 
     
    189195         
    190196        result1, = fitter.fit() 
     197        #print(result1) 
    191198        self.assert_(result1) 
    192199 
     
    194201        self.assertTrue( math.fabs(result1.pvec[1]-2.5)/3 <= result1.stderr[1]) 
    195202        self.assertTrue( result1.fitness/len(data1.x) < 2 ) 
    196          
     203 
     204        return 
    197205        #fit with park test 
    198206        fitter = Fit('park') 
     
    213221        self.assertAlmostEquals( result1.stderr[1],result2.stderr[1] ) 
    214222        self.assertTrue( result2.fitness/(len(data2.x)+len(data1.x)) < 2 ) 
    215          
    216          
     223 
     224 
     225if __name__ == "__main__": 
     226    unittest.main() 
    217227     
    218      
  • test/pr_inversion/test/test_output.txt

    r6c00702 r6fe5100  
    33#alpha=0.0007 
    44#chi2=836.797 
    5 #elapsed=0.000999928 
     5#elapsed=0.000168085 
    66#qmin=None 
    77#qmax=None 
  • test/run_one.py

    r6c00702 r6fe5100  
     1#!/usr/bin/env python 
     2 
    13import os 
    24import sys 
     
    1214#print "\n".join(sys.path) 
    1315test_path,test_file = splitpath(sys.argv[1]) 
    14 print "test file",sys.argv[1] 
     16print "=== testing:",sys.argv[1] 
    1517#print test_path, test_file 
    1618sys.argv = [sys.argv[0]] 
     
    1921test = imp.load_source('tests',test_file) 
    2022unittest.main(test, testRunner=xmlrunner.XMLTestRunner(output='logs')) 
    21  
  • test/utest_sansview.py

    r6c00702 r6fe5100  
     1#!/usr/bin/env python 
    12import os 
    23import subprocess 
Note: See TracChangeset for help on using the changeset viewer.