1 | import _asap
|
---|
2 | from asap.parameters import rcParams
|
---|
3 | from asap.logging import asaplog, asaplog_post_dec
|
---|
4 | from asap.utils import _n_bools, mask_and
|
---|
5 | from numpy import ndarray
|
---|
6 |
|
---|
7 | class fitter:
|
---|
8 | """
|
---|
9 | The fitting class for ASAP.
|
---|
10 | """
|
---|
11 | def __init__(self):
|
---|
12 | """
|
---|
13 | Create a fitter object. No state is set.
|
---|
14 | """
|
---|
15 | self.fitter = _asap.fitter()
|
---|
16 | self.x = None
|
---|
17 | self.y = None
|
---|
18 | self.mask = None
|
---|
19 | self.fitfunc = None
|
---|
20 | self.fitfuncs = None
|
---|
21 | self.fitted = False
|
---|
22 | self.data = None
|
---|
23 | self.components = 0
|
---|
24 | self._fittedrow = 0
|
---|
25 | self._p = None
|
---|
26 | self._selection = None
|
---|
27 | self.uselinear = False
|
---|
28 | self._constraints = []
|
---|
29 |
|
---|
30 | def set_data(self, xdat, ydat, mask=None):
|
---|
31 | """
|
---|
32 | Set the absissa and ordinate for the fit. Also set the mask
|
---|
33 | indicating valid points.
|
---|
34 | This can be used for data vectors retrieved from a scantable.
|
---|
35 | For scantable fitting use 'fitter.set_scan(scan, mask)'.
|
---|
36 | Parameters:
|
---|
37 | xdat: the abcissa values
|
---|
38 | ydat: the ordinate values
|
---|
39 | mask: an optional mask
|
---|
40 |
|
---|
41 | """
|
---|
42 | self.fitted = False
|
---|
43 | self.x = xdat
|
---|
44 | self.y = ydat
|
---|
45 | if mask == None:
|
---|
46 | self.mask = _n_bools(len(xdat), True)
|
---|
47 | else:
|
---|
48 | self.mask = mask
|
---|
49 | return
|
---|
50 |
|
---|
51 | @asaplog_post_dec
|
---|
52 | def set_scan(self, thescan=None, mask=None):
|
---|
53 | """
|
---|
54 | Set the 'data' (a scantable) of the fitter.
|
---|
55 | Parameters:
|
---|
56 | thescan: a scantable
|
---|
57 | mask: a msk retrieved from the scantable
|
---|
58 | """
|
---|
59 | if not thescan:
|
---|
60 | msg = "Please give a correct scan"
|
---|
61 | raise TypeError(msg)
|
---|
62 | self.fitted = False
|
---|
63 | self.data = thescan
|
---|
64 | self.mask = None
|
---|
65 | if mask is None:
|
---|
66 | self.mask = _n_bools(self.data.nchan(), True)
|
---|
67 | else:
|
---|
68 | self.mask = mask
|
---|
69 | return
|
---|
70 |
|
---|
71 | @asaplog_post_dec
|
---|
72 | def set_function(self, **kwargs):
|
---|
73 | """
|
---|
74 | Set the function to be fit.
|
---|
75 | Parameters:
|
---|
76 | poly: use a polynomial of the order given with nonlinear
|
---|
77 | least squares fit
|
---|
78 | lpoly: use polynomial of the order given with linear least
|
---|
79 | squares fit
|
---|
80 | gauss: fit the number of gaussian specified
|
---|
81 | lorentz: fit the number of lorentzian specified
|
---|
82 | sinusoid: fit the number of sinusoid specified
|
---|
83 | Example:
|
---|
84 | fitter.set_function(poly=3) # will fit a 3rd order polynomial
|
---|
85 | # via nonlinear method
|
---|
86 | fitter.set_function(lpoly=3) # will fit a 3rd order polynomial
|
---|
87 | # via linear method
|
---|
88 | fitter.set_function(gauss=2) # will fit two gaussians
|
---|
89 | fitter.set_function(lorentz=2) # will fit two lorentzians
|
---|
90 | fitter.set_function(sinusoid=3) # will fit three sinusoids
|
---|
91 | """
|
---|
92 | #default poly order 0
|
---|
93 | n=0
|
---|
94 | if kwargs.has_key('poly'):
|
---|
95 | self.fitfunc = 'poly'
|
---|
96 | self.fitfuncs = ['poly']
|
---|
97 | n = kwargs.get('poly')
|
---|
98 | self.components = [n+1]
|
---|
99 | self.uselinear = False
|
---|
100 | elif kwargs.has_key('lpoly'):
|
---|
101 | self.fitfunc = 'poly'
|
---|
102 | self.fitfuncs = ['lpoly']
|
---|
103 | n = kwargs.get('lpoly')
|
---|
104 | self.components = [n+1]
|
---|
105 | self.uselinear = True
|
---|
106 | elif kwargs.has_key('gauss'):
|
---|
107 | n = kwargs.get('gauss')
|
---|
108 | self.fitfunc = 'gauss'
|
---|
109 | self.fitfuncs = [ 'gauss' for i in range(n) ]
|
---|
110 | self.components = [ 3 for i in range(n) ]
|
---|
111 | self.uselinear = False
|
---|
112 | elif kwargs.has_key('lorentz'):
|
---|
113 | n = kwargs.get('lorentz')
|
---|
114 | self.fitfunc = 'lorentz'
|
---|
115 | self.fitfuncs = [ 'lorentz' for i in range(n) ]
|
---|
116 | self.components = [ 3 for i in range(n) ]
|
---|
117 | self.uselinear = False
|
---|
118 | elif kwargs.has_key('sinusoid'):
|
---|
119 | n = kwargs.get('sinusoid')
|
---|
120 | self.fitfunc = 'sinusoid'
|
---|
121 | self.fitfuncs = [ 'sinusoid' for i in range(n) ]
|
---|
122 | self.components = [ 3 for i in range(n) ]
|
---|
123 | self.uselinear = False
|
---|
124 | elif kwargs.has_key('expression'):
|
---|
125 | self.uselinear = False
|
---|
126 | raise RuntimeError("Not yet implemented")
|
---|
127 | else:
|
---|
128 | msg = "Invalid function type."
|
---|
129 | raise TypeError(msg)
|
---|
130 |
|
---|
131 | self.fitter.setexpression(self.fitfunc,n)
|
---|
132 | self._constraints = []
|
---|
133 | self.fitted = False
|
---|
134 | return
|
---|
135 |
|
---|
136 | @asaplog_post_dec
|
---|
137 | def fit(self, row=0, estimate=False):
|
---|
138 | """
|
---|
139 | Execute the actual fitting process. All the state has to be set.
|
---|
140 | Parameters:
|
---|
141 | row: specify the row in the scantable
|
---|
142 | estimate: auto-compute an initial parameter set (default False)
|
---|
143 | This can be used to compute estimates even if fit was
|
---|
144 | called before.
|
---|
145 | Example:
|
---|
146 | s = scantable('myscan.asap')
|
---|
147 | s.set_cursor(thepol=1) # select second pol
|
---|
148 | f = fitter()
|
---|
149 | f.set_scan(s)
|
---|
150 | f.set_function(poly=0)
|
---|
151 | f.fit(row=0) # fit first row
|
---|
152 | """
|
---|
153 | if ((self.x is None or self.y is None) and self.data is None) \
|
---|
154 | or self.fitfunc is None:
|
---|
155 | msg = "Fitter not yet initialised. Please set data & fit function"
|
---|
156 | raise RuntimeError(msg)
|
---|
157 |
|
---|
158 | if self.data is not None:
|
---|
159 | if self.data._getflagrow(row):
|
---|
160 | raise RuntimeError,"Can not fit flagged row."
|
---|
161 | self.x = self.data._getabcissa(row)
|
---|
162 | self.y = self.data._getspectrum(row)
|
---|
163 | #self.mask = mask_and(self.mask, self.data._getmask(row))
|
---|
164 | if len(self.x) == len(self.mask):
|
---|
165 | self.mask = mask_and(self.mask, self.data._getmask(row))
|
---|
166 | else:
|
---|
167 | asaplog.push('lengths of data and mask are not the same. '
|
---|
168 | 'preset mask will be ignored')
|
---|
169 | asaplog.post('WARN','asapfit.fit')
|
---|
170 | self.mask=self.data._getmask(row)
|
---|
171 | asaplog.push("Fitting:")
|
---|
172 | i = row
|
---|
173 | out = "Scan[%d] Beam[%d] IF[%d] Pol[%d] Cycle[%d]" % (
|
---|
174 | self.data.getscan(i),
|
---|
175 | self.data.getbeam(i),
|
---|
176 | self.data.getif(i),
|
---|
177 | self.data.getpol(i),
|
---|
178 | self.data.getcycle(i))
|
---|
179 |
|
---|
180 | asaplog.push(out, False)
|
---|
181 |
|
---|
182 | self.fitter.setdata(self.x, self.y, self.mask)
|
---|
183 | if self.fitfunc == 'gauss' or self.fitfunc == 'lorentz':
|
---|
184 | ps = self.fitter.getparameters()
|
---|
185 | if len(ps) == 0 or estimate:
|
---|
186 | self.fitter.estimate()
|
---|
187 | fxdpar = list(self.fitter.getfixedparameters())
|
---|
188 | if len(fxdpar) and fxdpar.count(0) == 0:
|
---|
189 | raise RuntimeError,"No point fitting, if all parameters are fixed."
|
---|
190 | if self._constraints:
|
---|
191 | for c in self._constraints:
|
---|
192 | self.fitter.addconstraint(c[0]+[c[-1]])
|
---|
193 | if self.uselinear:
|
---|
194 | converged = self.fitter.lfit()
|
---|
195 | else:
|
---|
196 | converged = self.fitter.fit()
|
---|
197 | if not converged:
|
---|
198 | raise RuntimeError,"Fit didn't converge."
|
---|
199 | self._fittedrow = row
|
---|
200 | self.fitted = True
|
---|
201 | return
|
---|
202 |
|
---|
203 | def store_fit(self, filename=None):
|
---|
204 | """
|
---|
205 | Save the fit parameters.
|
---|
206 | Parameters:
|
---|
207 | filename: if specified save as an ASCII file, if None (default)
|
---|
208 | store it in the scnatable
|
---|
209 | """
|
---|
210 | if self.fitted and self.data is not None:
|
---|
211 | pars = list(self.fitter.getparameters())
|
---|
212 | fixed = list(self.fitter.getfixedparameters())
|
---|
213 | from asap.asapfit import asapfit
|
---|
214 | fit = asapfit()
|
---|
215 | fit.setparameters(pars)
|
---|
216 | fit.setfixedparameters(fixed)
|
---|
217 | fit.setfunctions(self.fitfuncs)
|
---|
218 | fit.setcomponents(self.components)
|
---|
219 | fit.setframeinfo(self.data._getcoordinfo())
|
---|
220 | if filename is not None:
|
---|
221 | import os
|
---|
222 | filename = os.path.expandvars(os.path.expanduser(filename))
|
---|
223 | if os.path.exists(filename):
|
---|
224 | raise IOError("File '%s' exists." % filename)
|
---|
225 | fit.save(filename)
|
---|
226 | else:
|
---|
227 | self.data._addfit(fit,self._fittedrow)
|
---|
228 |
|
---|
229 | @asaplog_post_dec
|
---|
230 | def set_parameters(self,*args,**kwargs):
|
---|
231 | """
|
---|
232 | Set the parameters to be fitted.
|
---|
233 | Parameters:
|
---|
234 | params: a vector of parameters
|
---|
235 | fixed: a vector of which parameters are to be held fixed
|
---|
236 | (default is none)
|
---|
237 | component: in case of multiple gaussians/lorentzians/sinusoidals,
|
---|
238 | the index of the target component
|
---|
239 | """
|
---|
240 | component = None
|
---|
241 | fixed = None
|
---|
242 | params = None
|
---|
243 |
|
---|
244 | if len(args) and isinstance(args[0],dict):
|
---|
245 | kwargs = args[0]
|
---|
246 | if kwargs.has_key("fixed"): fixed = kwargs["fixed"]
|
---|
247 | if kwargs.has_key("params"): params = kwargs["params"]
|
---|
248 | if len(args) == 2 and isinstance(args[1], int):
|
---|
249 | component = args[1]
|
---|
250 | if self.fitfunc is None:
|
---|
251 | msg = "Please specify a fitting function first."
|
---|
252 | raise RuntimeError(msg)
|
---|
253 | if (self.fitfunc == "gauss" or self.fitfunc == "lorentz"
|
---|
254 | or self.fitfunc == "sinusoid") and component is not None:
|
---|
255 | if not self.fitted and sum(self.fitter.getparameters()) == 0:
|
---|
256 | pars = _n_bools(len(self.components)*3, False)
|
---|
257 | fxd = _n_bools(len(pars), False)
|
---|
258 | else:
|
---|
259 | pars = list(self.fitter.getparameters())
|
---|
260 | fxd = list(self.fitter.getfixedparameters())
|
---|
261 | i = 3*component
|
---|
262 | pars[i:i+3] = params
|
---|
263 | fxd[i:i+3] = fixed
|
---|
264 | params = pars
|
---|
265 | fixed = fxd
|
---|
266 | self.fitter.setparameters(params)
|
---|
267 | if fixed is not None:
|
---|
268 | self.fitter.setfixedparameters(fixed)
|
---|
269 | return
|
---|
270 |
|
---|
271 | @asaplog_post_dec
|
---|
272 | def set_gauss_parameters(self, peak, centre, fwhm,
|
---|
273 | peakfixed=0, centrefixed=0,
|
---|
274 | fwhmfixed=0,
|
---|
275 | component=0):
|
---|
276 | """
|
---|
277 | Set the Parameters of a 'Gaussian' component, set with set_function.
|
---|
278 | Parameters:
|
---|
279 | peak, centre, fwhm: The gaussian parameters
|
---|
280 | peakfixed,
|
---|
281 | centrefixed,
|
---|
282 | fwhmfixed: Optional parameters to indicate if
|
---|
283 | the paramters should be held fixed during
|
---|
284 | the fitting process. The default is to keep
|
---|
285 | all parameters flexible.
|
---|
286 | component: The number of the component (Default is the
|
---|
287 | component 0)
|
---|
288 | """
|
---|
289 | if self.fitfunc != "gauss":
|
---|
290 | msg = "Function only operates on Gaussian components."
|
---|
291 | raise ValueError(msg)
|
---|
292 | if 0 <= component < len(self.components):
|
---|
293 | d = {'params':[peak, centre, fwhm],
|
---|
294 | 'fixed':[peakfixed, centrefixed, fwhmfixed]}
|
---|
295 | self.set_parameters(d, component)
|
---|
296 | else:
|
---|
297 | msg = "Please select a valid component."
|
---|
298 | raise ValueError(msg)
|
---|
299 |
|
---|
300 | @asaplog_post_dec
|
---|
301 | def set_lorentz_parameters(self, peak, centre, fwhm,
|
---|
302 | peakfixed=0, centrefixed=0,
|
---|
303 | fwhmfixed=0,
|
---|
304 | component=0):
|
---|
305 | """
|
---|
306 | Set the Parameters of a 'Lorentzian' component, set with set_function.
|
---|
307 | Parameters:
|
---|
308 | peak, centre, fwhm: The lorentzian parameters
|
---|
309 | peakfixed,
|
---|
310 | centrefixed,
|
---|
311 | fwhmfixed: Optional parameters to indicate if
|
---|
312 | the paramters should be held fixed during
|
---|
313 | the fitting process. The default is to keep
|
---|
314 | all parameters flexible.
|
---|
315 | component: The number of the component (Default is the
|
---|
316 | component 0)
|
---|
317 | """
|
---|
318 | if self.fitfunc != "lorentz":
|
---|
319 | msg = "Function only operates on Lorentzian components."
|
---|
320 | raise ValueError(msg)
|
---|
321 | if 0 <= component < len(self.components):
|
---|
322 | d = {'params':[peak, centre, fwhm],
|
---|
323 | 'fixed':[peakfixed, centrefixed, fwhmfixed]}
|
---|
324 | self.set_parameters(d, component)
|
---|
325 | else:
|
---|
326 | msg = "Please select a valid component."
|
---|
327 | raise ValueError(msg)
|
---|
328 |
|
---|
329 | @asaplog_post_dec
|
---|
330 | def set_sinusoid_parameters(self, ampl, period, x0,
|
---|
331 | amplfixed=0, periodfixed=0,
|
---|
332 | x0fixed=0,
|
---|
333 | component=0):
|
---|
334 | """
|
---|
335 | Set the Parameters of a 'Sinusoidal' component, set with set_function.
|
---|
336 | Parameters:
|
---|
337 | ampl, period, x0: The sinusoidal parameters
|
---|
338 | amplfixed,
|
---|
339 | periodfixed,
|
---|
340 | x0fixed: Optional parameters to indicate if
|
---|
341 | the paramters should be held fixed during
|
---|
342 | the fitting process. The default is to keep
|
---|
343 | all parameters flexible.
|
---|
344 | component: The number of the component (Default is the
|
---|
345 | component 0)
|
---|
346 | """
|
---|
347 | if self.fitfunc != "sinusoid":
|
---|
348 | msg = "Function only operates on Sinusoidal components."
|
---|
349 | raise ValueError(msg)
|
---|
350 | if 0 <= component < len(self.components):
|
---|
351 | d = {'params':[ampl, period, x0],
|
---|
352 | 'fixed': [amplfixed, periodfixed, x0fixed]}
|
---|
353 | self.set_parameters(d, component)
|
---|
354 | else:
|
---|
355 | msg = "Please select a valid component."
|
---|
356 | raise ValueError(msg)
|
---|
357 |
|
---|
358 |
|
---|
359 | def add_constraint(self, xpar, y):
|
---|
360 | """Add parameter constraints to the fit. This is done by setting up
|
---|
361 | linear equations for the related parameters.
|
---|
362 |
|
---|
363 | For example a two component gaussian fit where the amplitudes are
|
---|
364 | constraint by amp1 = 2*amp2 and paramaters for the two components
|
---|
365 | in the order [amp1,peakv1,sigma1,amp2,peakv2,sigma2]
|
---|
366 | needs a constraint
|
---|
367 |
|
---|
368 | add_constraint([1, 0, 0, -2, 0, 0], 0)
|
---|
369 |
|
---|
370 | as the linear equation is
|
---|
371 |
|
---|
372 | 1*amp1 + 0*peakv1 + 0*sigma1 -2*amp2 + 0*peakv2 + 0*sigma2 = 0
|
---|
373 |
|
---|
374 | and similarly for a velocity difference of v2-v1=17
|
---|
375 |
|
---|
376 | add_constraint([0.,-1.,0.,0.,1.,0.], 17.)
|
---|
377 |
|
---|
378 | """
|
---|
379 | self._constraints.append((xpar, y))
|
---|
380 |
|
---|
381 |
|
---|
382 | def get_area(self, component=None):
|
---|
383 | """
|
---|
384 | Return the area under the fitted gaussian/lorentzian component.
|
---|
385 | Parameters:
|
---|
386 | component: the gaussian/lorentzian component selection,
|
---|
387 | default (None) is the sum of all components
|
---|
388 | Note:
|
---|
389 | This will only work for gaussian/lorentzian fits.
|
---|
390 | """
|
---|
391 | if not self.fitted: return
|
---|
392 | if self.fitfunc == "gauss" or self.fitfunc == "lorentz":
|
---|
393 | pars = list(self.fitter.getparameters())
|
---|
394 | from math import log,pi,sqrt
|
---|
395 | if self.fitfunc == "gauss":
|
---|
396 | fac = sqrt(pi/log(16.0))
|
---|
397 | elif self.fitfunc == "lorentz":
|
---|
398 | fac = pi/2.0
|
---|
399 | areas = []
|
---|
400 | for i in range(len(self.components)):
|
---|
401 | j = i*3
|
---|
402 | cpars = pars[j:j+3]
|
---|
403 | areas.append(fac * cpars[0] * cpars[2])
|
---|
404 | else:
|
---|
405 | return None
|
---|
406 | if component is not None:
|
---|
407 | return areas[component]
|
---|
408 | else:
|
---|
409 | return sum(areas)
|
---|
410 |
|
---|
411 | @asaplog_post_dec
|
---|
412 | def get_errors(self, component=None):
|
---|
413 | """
|
---|
414 | Return the errors in the parameters.
|
---|
415 | Parameters:
|
---|
416 | component: get the errors for the specified component
|
---|
417 | only, default is all components
|
---|
418 | """
|
---|
419 | if not self.fitted:
|
---|
420 | msg = "Not yet fitted."
|
---|
421 | raise RuntimeError(msg)
|
---|
422 | errs = list(self.fitter.geterrors())
|
---|
423 | cerrs = errs
|
---|
424 | if component is not None:
|
---|
425 | if self.fitfunc == "gauss" or self.fitfunc == "lorentz" \
|
---|
426 | or self.fitfunc == "sinusoid":
|
---|
427 | i = 3*component
|
---|
428 | if i < len(errs):
|
---|
429 | cerrs = errs[i:i+3]
|
---|
430 | return cerrs
|
---|
431 |
|
---|
432 |
|
---|
433 | @asaplog_post_dec
|
---|
434 | def get_parameters(self, component=None, errors=False):
|
---|
435 | """
|
---|
436 | Return the fit paramters.
|
---|
437 | Parameters:
|
---|
438 | component: get the parameters for the specified component
|
---|
439 | only, default is all components
|
---|
440 | """
|
---|
441 | if not self.fitted:
|
---|
442 | msg = "Not yet fitted."
|
---|
443 | raise RuntimeError(msg)
|
---|
444 | pars = list(self.fitter.getparameters())
|
---|
445 | fixed = list(self.fitter.getfixedparameters())
|
---|
446 | errs = list(self.fitter.geterrors())
|
---|
447 | area = []
|
---|
448 | if component is not None:
|
---|
449 | if self.fitfunc == "poly" or self.fitfunc == "lpoly":
|
---|
450 | cpars = pars
|
---|
451 | cfixed = fixed
|
---|
452 | cerrs = errs
|
---|
453 | else:
|
---|
454 | i = 3*component
|
---|
455 | cpars = pars[i:i+3]
|
---|
456 | cfixed = fixed[i:i+3]
|
---|
457 | cerrs = errs[i:i+3]
|
---|
458 | if self.fitfunc == "gauss" or self.fitfunc == "lorentz":
|
---|
459 | a = self.get_area(component)
|
---|
460 | area = [a for i in range(3)]
|
---|
461 | else:
|
---|
462 | cpars = pars
|
---|
463 | cfixed = fixed
|
---|
464 | cerrs = errs
|
---|
465 | if self.fitfunc == "gauss" or self.fitfunc == "lorentz":
|
---|
466 | for c in range(len(self.components)):
|
---|
467 | a = self.get_area(c)
|
---|
468 | area += [a for i in range(3)]
|
---|
469 | fpars = self._format_pars(cpars, cfixed, errors and cerrs, area)
|
---|
470 | asaplog.push(fpars)
|
---|
471 | return {'params':cpars, 'fixed':cfixed, 'formatted': fpars,
|
---|
472 | 'errors':cerrs}
|
---|
473 |
|
---|
474 | def _format_pars(self, pars, fixed, errors, area):
|
---|
475 | out = ''
|
---|
476 | if self.fitfunc == "poly" or self.fitfunc == "lpoly":
|
---|
477 | c = 0
|
---|
478 | for i in range(len(pars)):
|
---|
479 | fix = ""
|
---|
480 | if len(fixed) and fixed[i]: fix = "(fixed)"
|
---|
481 | out += " p%d%s= %3.6f" % (c, fix, pars[i])
|
---|
482 | if errors : out += " (%1.6f)" % errors[i]
|
---|
483 | out += ","
|
---|
484 | c+=1
|
---|
485 | out = out[:-1] # remove trailing ','
|
---|
486 | else:
|
---|
487 | i = 0
|
---|
488 | c = 0
|
---|
489 | if self.fitfunc == "gauss" or self.fitfunc == "lorentz":
|
---|
490 | pnam = ["peak", "centre", "FWHM"]
|
---|
491 | elif self.fitfunc == "sinusoid":
|
---|
492 | pnam = ["amplitude", "period", "x0"]
|
---|
493 | aunit = ""
|
---|
494 | ounit = ""
|
---|
495 | if self.data:
|
---|
496 | aunit = self.data.get_unit()
|
---|
497 | ounit = self.data.get_fluxunit()
|
---|
498 | while i < len(pars):
|
---|
499 | fix0 = fix1 = fix2 = ""
|
---|
500 | if i < len(fixed)-2:
|
---|
501 | if fixed[i]: fix0 = "(fixed)"
|
---|
502 | if fixed[i+1]: fix1 = "(fixed)"
|
---|
503 | if fixed[i+2]: fix2 = "(fixed)"
|
---|
504 | out += " %2d: " % c
|
---|
505 | out += "%s%s = %3.3f %s, " % (pnam[0], fix0, pars[i], ounit)
|
---|
506 | out += "%s%s = %3.3f %s, " % (pnam[1], fix1, pars[i+1], aunit)
|
---|
507 | out += "%s%s = %3.3f %s\n" % (pnam[2], fix2, pars[i+2], aunit)
|
---|
508 | if len(area): out += " area = %3.3f %s %s\n" % (area[i],
|
---|
509 | ounit,
|
---|
510 | aunit)
|
---|
511 | c+=1
|
---|
512 | i+=3
|
---|
513 | return out
|
---|
514 |
|
---|
515 |
|
---|
516 | @asaplog_post_dec
|
---|
517 | def get_estimate(self):
|
---|
518 | """
|
---|
519 | Return the parameter estimates (for non-linear functions).
|
---|
520 | """
|
---|
521 | pars = self.fitter.getestimate()
|
---|
522 | fixed = self.fitter.getfixedparameters()
|
---|
523 | asaplog.push(self._format_pars(pars,fixed,None,None))
|
---|
524 | return pars
|
---|
525 |
|
---|
526 | @asaplog_post_dec
|
---|
527 | def get_residual(self):
|
---|
528 | """
|
---|
529 | Return the residual of the fit.
|
---|
530 | """
|
---|
531 | if not self.fitted:
|
---|
532 | msg = "Not yet fitted."
|
---|
533 | raise RuntimeError(msg)
|
---|
534 | return self.fitter.getresidual()
|
---|
535 |
|
---|
536 | @asaplog_post_dec
|
---|
537 | def get_chi2(self):
|
---|
538 | """
|
---|
539 | Return chi^2.
|
---|
540 | """
|
---|
541 | if not self.fitted:
|
---|
542 | msg = "Not yet fitted."
|
---|
543 | raise RuntimeError(msg)
|
---|
544 | ch2 = self.fitter.getchi2()
|
---|
545 | asaplog.push( 'Chi^2 = %3.3f' % (ch2) )
|
---|
546 | return ch2
|
---|
547 |
|
---|
548 | @asaplog_post_dec
|
---|
549 | def get_fit(self):
|
---|
550 | """
|
---|
551 | Return the fitted ordinate values.
|
---|
552 | """
|
---|
553 | if not self.fitted:
|
---|
554 | msg = "Not yet fitted."
|
---|
555 | raise RuntimeError(msg)
|
---|
556 | return self.fitter.getfit()
|
---|
557 |
|
---|
558 | @asaplog_post_dec
|
---|
559 | def commit(self):
|
---|
560 | """
|
---|
561 | Return a new scan where the fits have been commited (subtracted)
|
---|
562 | """
|
---|
563 | if not self.fitted:
|
---|
564 | msg = "Not yet fitted."
|
---|
565 | raise RuntimeError(msg)
|
---|
566 | from asap import scantable
|
---|
567 | if not isinstance(self.data, scantable):
|
---|
568 | msg = "Not a scantable"
|
---|
569 | raise TypeError(msg)
|
---|
570 | scan = self.data.copy()
|
---|
571 | scan._setspectrum(self.fitter.getresidual())
|
---|
572 | return scan
|
---|
573 |
|
---|
574 | @asaplog_post_dec
|
---|
575 | def plot(self, residual=False, components=None, plotparms=False,
|
---|
576 | filename=None):
|
---|
577 | """
|
---|
578 | Plot the last fit.
|
---|
579 | Parameters:
|
---|
580 | residual: an optional parameter indicating if the residual
|
---|
581 | should be plotted (default 'False')
|
---|
582 | components: a list of components to plot, e.g [0,1],
|
---|
583 | -1 plots the total fit. Default is to only
|
---|
584 | plot the total fit.
|
---|
585 | plotparms: Inidicates if the parameter values should be present
|
---|
586 | on the plot
|
---|
587 | """
|
---|
588 | from matplotlib import rc as rcp
|
---|
589 | if not self.fitted:
|
---|
590 | return
|
---|
591 | #if not self._p or self._p.is_dead:
|
---|
592 | if not (self._p and self._p._alive()):
|
---|
593 | from asap.asapplotter import new_asaplot
|
---|
594 | del self._p
|
---|
595 | self._p = new_asaplot(rcParams['plotter.gui'])
|
---|
596 | self._p.hold()
|
---|
597 | self._p.clear()
|
---|
598 | rcp('lines', linewidth=1)
|
---|
599 | self._p.set_panels()
|
---|
600 | self._p.palette(0)
|
---|
601 | tlab = 'Spectrum'
|
---|
602 | xlab = 'Abcissa'
|
---|
603 | ylab = 'Ordinate'
|
---|
604 | from numpy import ma,logical_not,logical_and,array
|
---|
605 | m = self.mask
|
---|
606 | if self.data:
|
---|
607 | tlab = self.data._getsourcename(self._fittedrow)
|
---|
608 | xlab = self.data._getabcissalabel(self._fittedrow)
|
---|
609 | if self.data._getflagrow(self._fittedrow):
|
---|
610 | m = [False]
|
---|
611 | else:
|
---|
612 | m = logical_and(self.mask,
|
---|
613 | array(self.data._getmask(self._fittedrow),
|
---|
614 | copy=False))
|
---|
615 |
|
---|
616 | ylab = self.data._get_ordinate_label()
|
---|
617 |
|
---|
618 | colours = ["#777777","#dddddd","red","orange","purple","green",
|
---|
619 | "magenta", "cyan"]
|
---|
620 | nomask=True
|
---|
621 | for i in range(len(m)):
|
---|
622 | nomask = nomask and m[i]
|
---|
623 | if len(m) == 1:
|
---|
624 | m = m[0]
|
---|
625 | invm = (not m)
|
---|
626 | else:
|
---|
627 | invm = logical_not(m)
|
---|
628 | label0='Masked Region'
|
---|
629 | label1='Spectrum'
|
---|
630 | if ( nomask ):
|
---|
631 | label0=label1
|
---|
632 | else:
|
---|
633 | y = ma.masked_array( self.y, mask = m )
|
---|
634 | self._p.palette(1,colours)
|
---|
635 | self._p.set_line( label = label1 )
|
---|
636 | self._p.plot( self.x, y )
|
---|
637 | self._p.palette(0,colours)
|
---|
638 | self._p.set_line(label=label0)
|
---|
639 | y = ma.masked_array(self.y,mask=invm)
|
---|
640 | self._p.plot(self.x, y)
|
---|
641 | if residual:
|
---|
642 | self._p.palette(7)
|
---|
643 | self._p.set_line(label='Residual')
|
---|
644 | y = ma.masked_array(self.get_residual(),
|
---|
645 | mask=invm)
|
---|
646 | self._p.plot(self.x, y)
|
---|
647 | self._p.palette(2)
|
---|
648 | if components is not None:
|
---|
649 | cs = components
|
---|
650 | if isinstance(components,int): cs = [components]
|
---|
651 | if plotparms:
|
---|
652 | self._p.text(0.15,0.15,
|
---|
653 | str(self.get_parameters()['formatted']),size=8)
|
---|
654 | n = len(self.components)
|
---|
655 | self._p.palette(3)
|
---|
656 | for c in cs:
|
---|
657 | if 0 <= c < n:
|
---|
658 | lab = self.fitfuncs[c]+str(c)
|
---|
659 | self._p.set_line(label=lab)
|
---|
660 | y = ma.masked_array(self.fitter.evaluate(c), mask=invm)
|
---|
661 |
|
---|
662 | self._p.plot(self.x, y)
|
---|
663 | elif c == -1:
|
---|
664 | self._p.palette(2)
|
---|
665 | self._p.set_line(label="Total Fit")
|
---|
666 | y = ma.masked_array(self.fitter.getfit(),
|
---|
667 | mask=invm)
|
---|
668 | self._p.plot(self.x, y)
|
---|
669 | else:
|
---|
670 | self._p.palette(2)
|
---|
671 | self._p.set_line(label='Fit')
|
---|
672 | y = ma.masked_array(self.fitter.getfit(),mask=invm)
|
---|
673 | self._p.plot(self.x, y)
|
---|
674 | xlim=[min(self.x),max(self.x)]
|
---|
675 | self._p.axes.set_xlim(xlim)
|
---|
676 | self._p.set_axes('xlabel',xlab)
|
---|
677 | self._p.set_axes('ylabel',ylab)
|
---|
678 | self._p.set_axes('title',tlab)
|
---|
679 | self._p.release()
|
---|
680 | if (not rcParams['plotter.gui']):
|
---|
681 | self._p.save(filename)
|
---|
682 |
|
---|
683 | @asaplog_post_dec
|
---|
684 | def auto_fit(self, insitu=None, plot=False):
|
---|
685 | """
|
---|
686 | Return a scan where the function is applied to all rows for
|
---|
687 | all Beams/IFs/Pols.
|
---|
688 |
|
---|
689 | """
|
---|
690 | from asap import scantable
|
---|
691 | if not isinstance(self.data, scantable) :
|
---|
692 | msg = "Data is not a scantable"
|
---|
693 | raise TypeError(msg)
|
---|
694 | if insitu is None: insitu = rcParams['insitu']
|
---|
695 | if not insitu:
|
---|
696 | scan = self.data.copy()
|
---|
697 | else:
|
---|
698 | scan = self.data
|
---|
699 | rows = xrange(scan.nrow())
|
---|
700 | # Save parameters of baseline fits as a class attribute.
|
---|
701 | # NOTICE: This does not reflect changes in scantable!
|
---|
702 | if len(rows) > 0: self.blpars=[]
|
---|
703 | asaplog.push("Fitting:")
|
---|
704 | for r in rows:
|
---|
705 | out = " Scan[%d] Beam[%d] IF[%d] Pol[%d] Cycle[%d]" % (
|
---|
706 | scan.getscan(r),
|
---|
707 | scan.getbeam(r),
|
---|
708 | scan.getif(r),
|
---|
709 | scan.getpol(r),
|
---|
710 | scan.getcycle(r)
|
---|
711 | )
|
---|
712 | asaplog.push(out, False)
|
---|
713 | self.x = scan._getabcissa(r)
|
---|
714 | self.y = scan._getspectrum(r)
|
---|
715 | #self.mask = mask_and(self.mask, scan._getmask(r))
|
---|
716 | if len(self.x) == len(self.mask):
|
---|
717 | self.mask = mask_and(self.mask, self.data._getmask(row))
|
---|
718 | else:
|
---|
719 | asaplog.push('lengths of data and mask are not the same. '
|
---|
720 | 'preset mask will be ignored')
|
---|
721 | asaplog.post('WARN','asapfit.fit')
|
---|
722 | self.mask=self.data._getmask(row)
|
---|
723 | self.data = None
|
---|
724 | self.fit()
|
---|
725 | x = self.get_parameters()
|
---|
726 | fpar = self.get_parameters()
|
---|
727 | if plot:
|
---|
728 | self.plot(residual=True)
|
---|
729 | x = raw_input("Accept fit ([y]/n): ")
|
---|
730 | if x.upper() == 'N':
|
---|
731 | self.blpars.append(None)
|
---|
732 | continue
|
---|
733 | scan._setspectrum(self.fitter.getresidual(), r)
|
---|
734 | self.blpars.append(fpar)
|
---|
735 | if plot:
|
---|
736 | self._p.quit()
|
---|
737 | del self._p
|
---|
738 | self._p = None
|
---|
739 | return scan
|
---|