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

Last change on this file since 1726 was 1701, checked in by WataruKawasaki, 15 years ago

New Development: Yes

JIRA Issue: Yes (CAS-1800 + CAS-1807)

Ready to Release: Yes

Interface Changes: Yes

What Interface Changed: added new methods to scantable and fitter.

Test Programs:

Put in Release Notes: No

Module(s): sdfit, sdflag

Description: added new methods 'scantable.clip' and 'fitter.set_lorentz_parameters'.


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