source: sasview/park_integration/ScipyFitting.py @ 0eb801a

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 0eb801a was 0eb801a, checked in by Mathieu Doucet <doucetm@…>, 16 years ago

protect scipy against simultaneous fitting

  • Property mode set to 100644
File size: 4.9 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"""
6from sans.guitools.plottables import Data1D
7from Loader import Load
8from scipy import optimize
9from AbstractFitEngine import FitEngine, Parameter
10from AbstractFitEngine import FitArrange
11
12class ScipyFit(FitEngine):
13    """
14        ScipyFit performs the Fit.This class can be used as follow:
15        #Do the fit SCIPY
16        create an engine: engine = ScipyFit()
17        Use data must be of type plottable
18        Use a sans model
19       
20        Add data with a dictionnary of FitArrangeList where Uid is a key and data
21        is saved in FitArrange object.
22        engine.set_data(data,Uid)
23       
24        Set model parameter "M1"= model.name add {model.parameter.name:value}.
25        @note: Set_param() if used must always preceded set_model()
26             for the fit to be performed.In case of Scipyfit set_param is called in
27             fit () automatically.
28        engine.set_param( model,"M1", {'A':2,'B':4})
29       
30        Add model with a dictionnary of FitArrangeList{} where Uid is a key and model
31        is save in FitArrange object.
32        engine.set_model(model,Uid)
33       
34        engine.fit return chisqr,[model.parameter 1,2,..],[[err1....][..err2...]]
35        chisqr1, out1, cov1=engine.fit({model.parameter.name:value},qmin,qmax)
36    """
37    def __init__(self):
38        """
39            Creates a dictionary (self.fitArrangeList={})of FitArrange elements
40            with Uid as keys
41        """
42        self.fitArrangeList={}
43       
44    def fit(self,qmin=None, qmax=None):
45        """
46            Performs fit with scipy optimizer.It can only perform fit with one model
47            and a set of data.
48            @note: Cannot perform more than one fit at the time.
49           
50            @param pars: Dictionary of parameter names for the model and their values
51            @param qmin: The minimum value of data's range to be fit
52            @param qmax: The maximum value of data's range to be fit
53            @return chisqr: Value of the goodness of fit metric
54            @return out: list of parameter with the best value found during fitting
55            @return cov: Covariance matrix
56        """
57        # Protect against simultanous fitting attempts
58        if len(self.fitArrangeList)>1: 
59            raise RuntimeError, "Scipy can't fit more than a single fit problem at a time."
60       
61        # fitproblem contains first fitArrange object(one model and a list of data)
62        fitproblem=self.fitArrangeList.values()[0]
63        listdata=[]
64        model = fitproblem.get_model()
65        listdata = fitproblem.get_data()
66       
67       
68        # Concatenate dList set (contains one or more data)before fitting
69        xtemp,ytemp,dytemp=self._concatenateData( listdata)
70       
71        #print "dytemp",dytemp
72        #Assign a fit range is not boundaries were given
73        if qmin==None:
74            qmin= min(xtemp)
75        if qmax==None:
76            qmax= max(xtemp) 
77       
78        #perform the fit
79        chisqr, out, cov = fitHelper(model,self.parameters, xtemp,ytemp, dytemp ,qmin,qmax)
80       
81        return chisqr, out, cov
82   
83
84def fitHelper(model, pars, x, y, err_y ,qmin=None, qmax=None):
85    """
86        Fit function
87        @param model: sans model object
88        @param pars: list of parameters
89        @param x: vector of x data
90        @param y: vector of y data
91        @param err_y: vector of y errors
92        @return chisqr: Value of the goodness of fit metric
93        @return out: list of parameter with the best value found during fitting
94        @return cov: Covariance matrix
95    """
96    def f(params):
97        """
98            Calculates the vector of residuals for each point
99            in y for a given set of input parameters.
100            @param params: list of parameter values
101            @return: vector of residuals
102        """
103        i = 0
104        for p in pars:
105            p.set(params[i])
106            i += 1
107       
108        residuals = []
109        for j in range(len(x)):
110            if x[j]>qmin and x[j]<qmax:
111                residuals.append( ( y[j] - model.runXY(x[j]) ) / err_y[j] )
112           
113        return residuals
114       
115    def chi2(params):
116        """
117            Calculates chi^2
118            @param params: list of parameter values
119            @return: chi^2
120        """
121        sum = 0
122        res = f(params)
123        for item in res:
124            sum += item*item
125        return sum
126       
127    p = [param() for param in pars]
128    out, cov_x, info, mesg, success = optimize.leastsq(f, p, full_output=1, warning=True)
129    #print info, mesg, success
130    # Calculate chi squared
131    if len(pars)>1:
132        chisqr = chi2(out)
133    elif len(pars)==1:
134        chisqr = chi2([out])
135       
136    return chisqr, out, cov_x   
137
Note: See TracBrowser for help on using the repository browser.