source: sasview/park_integration/ScipyFitting.py @ b2c6d23

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 b2c6d23 was 681f0dc, checked in by Gervaise Alina <gervyh@…>, 16 years ago

added flexibility on handler choice for fit (park). allow to print some update on the sansview

  • Property mode set to 100644
File size: 4.2 KB
Line 
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"""
6#import scipy.linalg
7import numpy 
8
9from Loader import Load
10from scipy import optimize
11
12from AbstractFitEngine import FitEngine, sansAssembly
13
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   
29class ScipyFit(FitEngine):
30    """
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       
37        Add data with a dictionnary of FitArrangeDict where Uid is a key and data
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       
47        Add model with a dictionnary of FitArrangeDict{} where Uid is a key and model
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)
53    """
54    def __init__(self):
55        """
56            Creates a dictionary (self.fitArrangeDict={})of FitArrange elements
57            with Uid as keys
58        """
59        self.fitArrangeDict={}
60        self.paramList=[]
61    def fit(self ,handler=None, qmin=None, qmax=None):
62        # Protect against simultanous fitting attempts
63        #if len(self.fitArrangeDict)>1:
64        #    raise RuntimeError, "Scipy can't fit more than a single fit problem at a time."
65        # fitproblem contains first fitArrange object(one model and a list of data)
66        #list of fitproblem
67       
68        fitproblem=[]
69        for id ,fproblem in self.fitArrangeDict.iteritems():
70            print "ScipyFitting:fproblem.get_to_fit() ",fproblem.get_to_fit()
71            if fproblem.get_to_fit()==1:
72                fitproblem.append(fproblem)
73        if len(fitproblem)>1 : 
74            raise RuntimeError, "Scipy can't fit more than a single fit problem at a time."
75            return
76        elif len(fitproblem)==0 : 
77            raise RuntimeError, "No Assembly scheduled for Scipy fitting."
78            return
79   
80        listdata=[]
81        model = fitproblem[0].get_model()
82        listdata = fitproblem[0].get_data()
83        # Concatenate dList set (contains one or more data)before fitting
84        #data=self._concatenateData( listdata)
85        data=listdata
86        #Assign a fit range is not boundaries were given
87        if not hasattr(data, 'image'):
88            if qmin==None:
89                qmin= min(data.x)
90            if qmax==None:
91                qmax= max(data.x) 
92        else:
93            if qmin==None:
94                qmin= numpy.min(data.image)
95            if qmax==None:
96                qmax= numpy.max(data.image) 
97        functor= sansAssembly(self.paramList,model,data)
98        out, cov_x, info, mesg, success = optimize.leastsq(functor,model.getParams(self.paramList), full_output=1, warning=True)
99        chisqr = functor.chisq(out)
100       
101        if cov_x is not None and numpy.isfinite(cov_x).all():
102            stderr = numpy.sqrt(numpy.diag(cov_x))
103        else:
104            stderr=None
105        if not (numpy.isnan(out).any()) or ( cov_x !=None) :
106                result = fitresult()
107                result.fitness = chisqr
108                result.stderr  = stderr
109                result.pvec = out
110                result.success =success
111               
112                return result
113        else: 
114            raise ValueError, "SVD did not converge"+str(success)
115       
116       
117             
118           
119     
Note: See TracBrowser for help on using the repository browser.