1 | |
---|
2 | |
---|
3 | """ |
---|
4 | ScipyFitting module contains FitArrange , ScipyFit, |
---|
5 | Parameter classes.All listed classes work together to perform a |
---|
6 | simple fit with scipy optimizer. |
---|
7 | """ |
---|
8 | |
---|
9 | import numpy |
---|
10 | import sys |
---|
11 | from scipy import optimize |
---|
12 | |
---|
13 | from sans.fit.AbstractFitEngine import FitEngine |
---|
14 | from sans.fit.AbstractFitEngine import SansAssembly |
---|
15 | from sans.fit.AbstractFitEngine import FitAbort |
---|
16 | |
---|
17 | |
---|
18 | class fitresult(object): |
---|
19 | """ |
---|
20 | Storing fit result |
---|
21 | """ |
---|
22 | def __init__(self, model=None, param_list=None): |
---|
23 | self.calls = None |
---|
24 | self.fitness = None |
---|
25 | self.chisqr = None |
---|
26 | self.pvec = None |
---|
27 | self.cov = None |
---|
28 | self.info = None |
---|
29 | self.mesg = None |
---|
30 | self.success = None |
---|
31 | self.stderr = None |
---|
32 | self.parameters = None |
---|
33 | self.model = model |
---|
34 | self.param_list = param_list |
---|
35 | self.iterations = 0 |
---|
36 | |
---|
37 | def set_model(self, model): |
---|
38 | """ |
---|
39 | """ |
---|
40 | self.model = model |
---|
41 | |
---|
42 | def set_fitness(self, fitness): |
---|
43 | """ |
---|
44 | """ |
---|
45 | self.fitness = fitness |
---|
46 | |
---|
47 | def __str__(self): |
---|
48 | """ |
---|
49 | """ |
---|
50 | if self.pvec == None and self.model is None and self.param_list is None: |
---|
51 | return "No results" |
---|
52 | n = len(self.model.parameterset) |
---|
53 | self.iterations += 1 |
---|
54 | result_param = zip(xrange(n), self.model.parameterset) |
---|
55 | msg = [" [Iteration #: %s] | P%-3d %s......|.....%s" % \ |
---|
56 | (self.iterations, p[0], p[1], p[1].value)\ |
---|
57 | for p in result_param if p[1].name in self.param_list] |
---|
58 | msg.append("=== goodness of fit: %s" % (str(self.fitness))) |
---|
59 | return "\n".join(msg) |
---|
60 | |
---|
61 | def print_summary(self): |
---|
62 | """ |
---|
63 | """ |
---|
64 | print self |
---|
65 | |
---|
66 | class ScipyFit(FitEngine): |
---|
67 | """ |
---|
68 | ScipyFit performs the Fit.This class can be used as follow: |
---|
69 | #Do the fit SCIPY |
---|
70 | create an engine: engine = ScipyFit() |
---|
71 | Use data must be of type plottable |
---|
72 | Use a sans model |
---|
73 | |
---|
74 | Add data with a dictionnary of FitArrangeDict where Uid is a key and data |
---|
75 | is saved in FitArrange object. |
---|
76 | engine.set_data(data,Uid) |
---|
77 | |
---|
78 | Set model parameter "M1"= model.name add {model.parameter.name:value}. |
---|
79 | |
---|
80 | :note: Set_param() if used must always preceded set_model() |
---|
81 | for the fit to be performed.In case of Scipyfit set_param is called in |
---|
82 | fit () automatically. |
---|
83 | |
---|
84 | engine.set_param( model,"M1", {'A':2,'B':4}) |
---|
85 | |
---|
86 | Add model with a dictionnary of FitArrangeDict{} where Uid is a key and model |
---|
87 | is save in FitArrange object. |
---|
88 | engine.set_model(model,Uid) |
---|
89 | |
---|
90 | engine.fit return chisqr,[model.parameter 1,2,..],[[err1....][..err2...]] |
---|
91 | chisqr1, out1, cov1=engine.fit({model.parameter.name:value},qmin,qmax) |
---|
92 | """ |
---|
93 | def __init__(self): |
---|
94 | """ |
---|
95 | Creates a dictionary (self.fit_arrange_dict={})of FitArrange elements |
---|
96 | with Uid as keys |
---|
97 | """ |
---|
98 | FitEngine.__init__(self) |
---|
99 | self.fit_arrange_dict = {} |
---|
100 | self.param_list = [] |
---|
101 | self.curr_thread = None |
---|
102 | self.result = None |
---|
103 | #def fit(self, *args, **kw): |
---|
104 | # return profile(self._fit, *args, **kw) |
---|
105 | |
---|
106 | def fit(self, q=None, handler=None, curr_thread=None): |
---|
107 | """ |
---|
108 | """ |
---|
109 | fitproblem = [] |
---|
110 | for fproblem in self.fit_arrange_dict.itervalues(): |
---|
111 | if fproblem.get_to_fit() == 1: |
---|
112 | fitproblem.append(fproblem) |
---|
113 | if len(fitproblem) > 1 : |
---|
114 | msg = "Scipy can't fit more than a single fit problem at a time." |
---|
115 | raise RuntimeError, msg |
---|
116 | return |
---|
117 | elif len(fitproblem) == 0 : |
---|
118 | raise RuntimeError, "No Assembly scheduled for Scipy fitting." |
---|
119 | return |
---|
120 | |
---|
121 | listdata = [] |
---|
122 | model = fitproblem[0].get_model() |
---|
123 | listdata = fitproblem[0].get_data() |
---|
124 | # Concatenate dList set (contains one or more data)before fitting |
---|
125 | data = listdata |
---|
126 | self.curr_thread = curr_thread |
---|
127 | self.result = fitresult(model=model, param_list=self.param_list) |
---|
128 | self.handler = handler |
---|
129 | if self.handler is not None: |
---|
130 | self.handler.set_result(result=self.result) |
---|
131 | #try: |
---|
132 | functor = SansAssembly(self.param_list, model, data, handler=self.handler, |
---|
133 | fitresult=self.result, curr_thread= self.curr_thread) |
---|
134 | |
---|
135 | try: |
---|
136 | out, cov_x, _, mesg, success = optimize.leastsq(functor, |
---|
137 | model.get_params(self.param_list), |
---|
138 | ftol = 0.001, |
---|
139 | full_output=1, |
---|
140 | warning=True) |
---|
141 | except: |
---|
142 | if hasattr(sys, 'last_type') and sys.last_type == FitAbort: |
---|
143 | if self.handler is not None: |
---|
144 | msg = "Fit Stop!" |
---|
145 | #self.handler.error(msg) |
---|
146 | self.result = self.handler.get_result() |
---|
147 | return self.result |
---|
148 | else: |
---|
149 | raise |
---|
150 | |
---|
151 | chisqr = functor.chisq() |
---|
152 | if cov_x is not None and numpy.isfinite(cov_x).all(): |
---|
153 | stderr = numpy.sqrt(numpy.diag(cov_x)) |
---|
154 | else: |
---|
155 | stderr = None |
---|
156 | |
---|
157 | if (out is not None) and not (numpy.isnan(out).any()) \ |
---|
158 | and (cov_x != None): |
---|
159 | self.result.fitness = chisqr |
---|
160 | self.result.stderr = stderr |
---|
161 | self.result.pvec = out |
---|
162 | self.result.success = success |
---|
163 | else: |
---|
164 | msg = "SVD did not converge " + str(mesg) |
---|
165 | #handler.error(msg) |
---|
166 | return self.result |
---|
167 | |
---|
168 | |
---|
169 | |
---|
170 | |
---|
171 | |
---|
172 | #def profile(fn, *args, **kw): |
---|
173 | # import cProfile, pstats, os |
---|
174 | # global call_result |
---|
175 | # def call(): |
---|
176 | # global call_result |
---|
177 | # call_result = fn(*args, **kw) |
---|
178 | # cProfile.runctx('call()', dict(call=call), {}, 'profile.out') |
---|
179 | # stats = pstats.Stats('profile.out') |
---|
180 | # stats.sort_stats('time') |
---|
181 | # stats.sort_stats('calls') |
---|
182 | # stats.print_stats() |
---|
183 | # os.unlink('profile.out') |
---|
184 | # return call_result |
---|
185 | |
---|
186 | |
---|