source: trunk/python/asapfitter.py@ 2639

Last change on this file since 2639 was 2541, checked in by Kana Sugimoto, 13 years ago

New Development: No

JIRA Issue: Yes (related to CAS-3749)

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: Interactive tests

Test I. run sdbaseline with blfunc='poly', verify=True and masklist=[]

on CASA,
or run scantable.auto_poly_baseline and scantable.poly_baseline
with plot=True and mask=None.
--> Verification plots should properly be loaded.

Test II.
(1) run asapfitter.plot, by for example

scan = asap.scantable(infile,False)
f=asap.fitter()
f.set_function(lpoly=2)
f.x = scan._getabcissa(0)
f.y = scan._getspectrum(0)
f.mask=(scan._getmask(0))
f.data=None
f.fit()
f.plot(residual=True)

(2) plot something with sdplot (on CASA) or asapplotter.plot
(3) run asapfitter.plot again

f.plot(residual=True)
--> (3) should work without an error

Put in Release Notes: No

Module(s):

Description:

[I] Fixed bugs which caused scantable.poly_baseline and
scantable.auto_poly_baseline crash when mask=None (default)
and plot=True.
[II] Fixed a bug which caused an error in asapfitter.plot when the
other plotting operation is invoked between multiple run of asapfitter.plot.


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