source: sasview/park_integration/ScipyFitting.py @ d67fc8d

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 d67fc8d was fd6b789, checked in by Gervaise Alina <gervyh@…>, 15 years ago

refactor fit engine set_model can receive sans.model or park.model has a parameter;set_del has a new parameters constraints

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