source: sasview/park_integration/ScipyFitting.py @ ee5b04c

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

comment added

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