source: sasview/park_integration/ScipyFitting.py @ 3617aa2

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 3617aa2 was eef2e0ed, checked in by Gervaise Alina <gervyh@…>, 16 years ago

remove comments

  • Property mode set to 100644
File size: 3.9 KB
RevLine 
[792db7d5]1"""
2    @organization: ScipyFitting module contains FitArrange , ScipyFit,
3    Parameter classes.All listed classes work together to perform a
4    simple fit with scipy optimizer.
5"""
[48882d1]6#import scipy.linalg
7import numpy 
[61cb28d]8
[7705306]9from Loader import Load
10from scipy import optimize
11
[48882d1]12from AbstractFitEngine import FitEngine, sansAssembly
[61cb28d]13
[48882d1]14class fitresult:
15    """
16        Storing fit result
17    """
18    calls     = None
19    fitness   = None
20    chisqr    = None
21    pvec      = None
22    cov       = None
23    info      = None
24    mesg      = None
25    success   = None
26    stderr    = None
27    parameters= None
28   
[4c718654]29class ScipyFit(FitEngine):
[7705306]30    """
[792db7d5]31        ScipyFit performs the Fit.This class can be used as follow:
32        #Do the fit SCIPY
33        create an engine: engine = ScipyFit()
34        Use data must be of type plottable
35        Use a sans model
36       
[ca6d914]37        Add data with a dictionnary of FitArrangeDict where Uid is a key and data
[792db7d5]38        is saved in FitArrange object.
39        engine.set_data(data,Uid)
40       
41        Set model parameter "M1"= model.name add {model.parameter.name:value}.
42        @note: Set_param() if used must always preceded set_model()
43             for the fit to be performed.In case of Scipyfit set_param is called in
44             fit () automatically.
45        engine.set_param( model,"M1", {'A':2,'B':4})
46       
[ca6d914]47        Add model with a dictionnary of FitArrangeDict{} where Uid is a key and model
[792db7d5]48        is save in FitArrange object.
49        engine.set_model(model,Uid)
50       
51        engine.fit return chisqr,[model.parameter 1,2,..],[[err1....][..err2...]]
52        chisqr1, out1, cov1=engine.fit({model.parameter.name:value},qmin,qmax)
[7705306]53    """
[792db7d5]54    def __init__(self):
55        """
[ca6d914]56            Creates a dictionary (self.fitArrangeDict={})of FitArrange elements
[792db7d5]57            with Uid as keys
58        """
[ca6d914]59        self.fitArrangeDict={}
[ee5b04c]60        self.paramList=[]
[9c648c7]61    #def fit(self, *args, **kw):
62    #    return profile(self._fit, *args, **kw)
63
[a320904]64    def fit(self ,handler=None):
[681f0dc]65       
[a9e04aa]66        fitproblem=[]
67        for id ,fproblem in self.fitArrangeDict.iteritems():
68            if fproblem.get_to_fit()==1:
69                fitproblem.append(fproblem)
70        if len(fitproblem)>1 : 
71            raise RuntimeError, "Scipy can't fit more than a single fit problem at a time."
72            return
73        elif len(fitproblem)==0 : 
74            raise RuntimeError, "No Assembly scheduled for Scipy fitting."
75            return
76   
[7705306]77        listdata=[]
[a9e04aa]78        model = fitproblem[0].get_model()
79        listdata = fitproblem[0].get_data()
[792db7d5]80        # Concatenate dList set (contains one or more data)before fitting
[7d0c1a8]81        #data=self._concatenateData( listdata)
82        data=listdata
[e71440c]83        functor= sansAssembly(self.paramList,model,data)
[9c648c7]84       
[48882d1]85        out, cov_x, info, mesg, success = optimize.leastsq(functor,model.getParams(self.paramList), full_output=1, warning=True)
86        chisqr = functor.chisq(out)
[e71440c]87       
[ca6d914]88        if cov_x is not None and numpy.isfinite(cov_x).all():
89            stderr = numpy.sqrt(numpy.diag(cov_x))
[e71440c]90        else:
91            stderr=None
[ca6d914]92        if not (numpy.isnan(out).any()) or ( cov_x !=None) :
[48882d1]93                result = fitresult()
94                result.fitness = chisqr
[ca6d914]95                result.stderr  = stderr
[48882d1]96                result.pvec = out
97                result.success =success
98               
99                return result
100        else: 
[ca6d914]101            raise ValueError, "SVD did not converge"+str(success)
[7705306]102       
[48882d1]103       
[9c648c7]104def profile(fn, *args, **kw):
105    import cProfile, pstats, os
106    global call_result
107    def call():
108        global call_result
109        call_result = fn(*args, **kw)
110    cProfile.runctx('call()', dict(call=call), {}, 'profile.out')
111    stats = pstats.Stats('profile.out')
112    #stats.sort_stats('time')
113    stats.sort_stats('calls')
114    stats.print_stats()
115    os.unlink('profile.out')
116    return call_result
117
[48882d1]118     
Note: See TracBrowser for help on using the repository browser.