source: sasview/park_integration/ScipyFitting.py @ 94b44293

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 94b44293 was d4b0687, checked in by Gervaise Alina <gervyh@…>, 16 years ago

changed done on AbstractFit? engine scipyfit parkfit

  • Property mode set to 100644
File size: 4.7 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        # fitproblem contains first fitArrange object(one model and a list of data)
58        fitproblem=self.fitArrangeList.values()[0]
59        listdata=[]
60        model = fitproblem.get_model()
61        listdata = fitproblem.get_data()
62       
63       
64        # Concatenate dList set (contains one or more data)before fitting
65        xtemp,ytemp,dytemp=self._concatenateData( listdata)
66       
67        #print "dytemp",dytemp
68        #Assign a fit range is not boundaries were given
69        if qmin==None:
70            qmin= min(xtemp)
71        if qmax==None:
72            qmax= max(xtemp) 
73       
74        #perform the fit
75        chisqr, out, cov = fitHelper(model,self.parameters, xtemp,ytemp, dytemp ,qmin,qmax)
76       
77        return chisqr, out, cov
78   
79
80def fitHelper(model, pars, x, y, err_y ,qmin=None, qmax=None):
81    """
82        Fit function
83        @param model: sans model object
84        @param pars: list of parameters
85        @param x: vector of x data
86        @param y: vector of y data
87        @param err_y: vector of y errors
88        @return chisqr: Value of the goodness of fit metric
89        @return out: list of parameter with the best value found during fitting
90        @return cov: Covariance matrix
91    """
92    def f(params):
93        """
94            Calculates the vector of residuals for each point
95            in y for a given set of input parameters.
96            @param params: list of parameter values
97            @return: vector of residuals
98        """
99        i = 0
100        for p in pars:
101            p.set(params[i])
102            i += 1
103       
104        residuals = []
105        for j in range(len(x)):
106            if x[j]>qmin and x[j]<qmax:
107                residuals.append( ( y[j] - model.runXY(x[j]) ) / err_y[j] )
108           
109        return residuals
110       
111    def chi2(params):
112        """
113            Calculates chi^2
114            @param params: list of parameter values
115            @return: chi^2
116        """
117        sum = 0
118        res = f(params)
119        for item in res:
120            sum += item*item
121        return sum
122       
123    p = [param() for param in pars]
124    out, cov_x, info, mesg, success = optimize.leastsq(f, p, full_output=1, warning=True)
125    print info, mesg, success
126    # Calculate chi squared
127    if len(pars)>1:
128        chisqr = chi2(out)
129    elif len(pars)==1:
130        chisqr = chi2([out])
131       
132    return chisqr, out, cov_x   
133
Note: See TracBrowser for help on using the repository browser.