source: branches/alma/python/asapfitter.py@ 1628

Last change on this file since 1628 was 1628, checked in by Takeshi Nakazato, 15 years ago

New Development: No

JIRA Issue: No

Ready to Release: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: No

Module(s): Module Names change impacts.

Description: Describe your changes here...

Bug fix.


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