[113] | 1 | import _asap |
---|
[259] | 2 | from asap import rcParams |
---|
[723] | 3 | from asap import print_log |
---|
[113] | 4 | |
---|
| 5 | class fitter: |
---|
| 6 | """ |
---|
| 7 | The fitting class for ASAP. |
---|
| 8 | """ |
---|
[723] | 9 | |
---|
[113] | 10 | def __init__(self): |
---|
| 11 | """ |
---|
| 12 | Create a fitter object. No state is set. |
---|
| 13 | """ |
---|
| 14 | self.fitter = _asap.fitter() |
---|
| 15 | self.x = None |
---|
| 16 | self.y = None |
---|
| 17 | self.mask = None |
---|
| 18 | self.fitfunc = None |
---|
[515] | 19 | self.fitfuncs = None |
---|
[113] | 20 | self.fitted = False |
---|
| 21 | self.data = None |
---|
[515] | 22 | self.components = 0 |
---|
| 23 | self._fittedrow = 0 |
---|
[113] | 24 | self._p = None |
---|
[515] | 25 | self._selection = None |
---|
[113] | 26 | |
---|
| 27 | def set_data(self, xdat, ydat, mask=None): |
---|
| 28 | """ |
---|
[158] | 29 | Set the absissa and ordinate for the fit. Also set the mask |
---|
[113] | 30 | indicationg valid points. |
---|
| 31 | This can be used for data vectors retrieved from a scantable. |
---|
| 32 | For scantable fitting use 'fitter.set_scan(scan, mask)'. |
---|
| 33 | Parameters: |
---|
[158] | 34 | xdat: the abcissa values |
---|
[113] | 35 | ydat: the ordinate values |
---|
| 36 | mask: an optional mask |
---|
[723] | 37 | |
---|
[113] | 38 | """ |
---|
| 39 | self.fitted = False |
---|
| 40 | self.x = xdat |
---|
| 41 | self.y = ydat |
---|
| 42 | if mask == None: |
---|
| 43 | from numarray import ones |
---|
| 44 | self.mask = ones(len(xdat)) |
---|
| 45 | else: |
---|
| 46 | self.mask = mask |
---|
| 47 | return |
---|
| 48 | |
---|
| 49 | def set_scan(self, thescan=None, mask=None): |
---|
| 50 | """ |
---|
| 51 | Set the 'data' (a scantable) of the fitter. |
---|
| 52 | Parameters: |
---|
| 53 | thescan: a scantable |
---|
| 54 | mask: a msk retireved from the scantable |
---|
| 55 | """ |
---|
| 56 | if not thescan: |
---|
[723] | 57 | msg = "Please give a correct scan" |
---|
| 58 | if rcParams['verbose']: |
---|
| 59 | print msg |
---|
| 60 | return |
---|
| 61 | else: |
---|
| 62 | raise TypeError(msg) |
---|
[113] | 63 | self.fitted = False |
---|
| 64 | self.data = thescan |
---|
| 65 | if mask is None: |
---|
| 66 | from numarray import ones |
---|
| 67 | self.mask = ones(self.data.nchan()) |
---|
| 68 | else: |
---|
| 69 | self.mask = mask |
---|
| 70 | return |
---|
| 71 | |
---|
| 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 |
---|
| 77 | gauss: fit the number of gaussian specified |
---|
| 78 | Example: |
---|
| 79 | fitter.set_function(gauss=2) # will fit two gaussians |
---|
| 80 | fitter.set_function(poly=3) # will fit a 3rd order polynomial |
---|
| 81 | """ |
---|
[723] | 82 | #default poly order 0 |
---|
[515] | 83 | n=0 |
---|
[113] | 84 | if kwargs.has_key('poly'): |
---|
| 85 | self.fitfunc = 'poly' |
---|
| 86 | n = kwargs.get('poly') |
---|
[515] | 87 | self.components = [n] |
---|
[113] | 88 | elif kwargs.has_key('gauss'): |
---|
| 89 | n = kwargs.get('gauss') |
---|
| 90 | self.fitfunc = 'gauss' |
---|
[515] | 91 | self.fitfuncs = [ 'gauss' for i in range(n) ] |
---|
| 92 | self.components = [ 3 for i in range(n) ] |
---|
| 93 | else: |
---|
[723] | 94 | msg = "Invalid function type." |
---|
| 95 | if rcParams['verbose']: |
---|
| 96 | print msg |
---|
| 97 | return |
---|
| 98 | else: |
---|
| 99 | raise TypeError(msg) |
---|
| 100 | |
---|
[113] | 101 | self.fitter.setexpression(self.fitfunc,n) |
---|
| 102 | return |
---|
[723] | 103 | |
---|
[515] | 104 | def fit(self, row=0): |
---|
[113] | 105 | """ |
---|
| 106 | Execute the actual fitting process. All the state has to be set. |
---|
| 107 | Parameters: |
---|
[526] | 108 | row: specify the row in the scantable |
---|
[113] | 109 | Example: |
---|
[515] | 110 | s = scantable('myscan.asap') |
---|
| 111 | s.set_cursor(thepol=1) # select second pol |
---|
[113] | 112 | f = fitter() |
---|
| 113 | f.set_scan(s) |
---|
| 114 | f.set_function(poly=0) |
---|
[723] | 115 | f.fit(row=0) # fit first row |
---|
[113] | 116 | """ |
---|
| 117 | if ((self.x is None or self.y is None) and self.data is None) \ |
---|
| 118 | or self.fitfunc is None: |
---|
[723] | 119 | msg = "Fitter not yet initialised. Please set data & fit function" |
---|
| 120 | if rcParams['verbose']: |
---|
| 121 | print msg |
---|
| 122 | return |
---|
| 123 | else: |
---|
| 124 | raise RuntimeError(msg) |
---|
| 125 | |
---|
[113] | 126 | else: |
---|
| 127 | if self.data is not None: |
---|
[515] | 128 | self.x = self.data._getabcissa(row) |
---|
| 129 | self.y = self.data._getspectrum(row) |
---|
[723] | 130 | from asap import asaplog |
---|
| 131 | asaplog.push("Fitting:") |
---|
[515] | 132 | self.selection = self.data.get_cursor() |
---|
| 133 | self.fitter.setdata(self.x, self.y, self.mask) |
---|
[113] | 134 | if self.fitfunc == 'gauss': |
---|
| 135 | ps = self.fitter.getparameters() |
---|
| 136 | if len(ps) == 0: |
---|
| 137 | self.fitter.estimate() |
---|
[626] | 138 | try: |
---|
| 139 | self.fitter.fit() |
---|
| 140 | except RuntimeError, msg: |
---|
[723] | 141 | if rcParams['verbose']: |
---|
| 142 | print msg |
---|
| 143 | else: |
---|
| 144 | raise |
---|
[515] | 145 | self._fittedrow = row |
---|
[113] | 146 | self.fitted = True |
---|
[723] | 147 | print_log() |
---|
[113] | 148 | return |
---|
| 149 | |
---|
[515] | 150 | def store_fit(self): |
---|
[526] | 151 | """ |
---|
| 152 | Store the fit parameters in the scantable. |
---|
| 153 | """ |
---|
[515] | 154 | if self.fitted and self.data is not None: |
---|
| 155 | pars = list(self.fitter.getparameters()) |
---|
| 156 | fixed = list(self.fitter.getfixedparameters()) |
---|
| 157 | self.data._addfit(self._fittedrow, pars, fixed, |
---|
| 158 | self.fitfuncs, self.components) |
---|
| 159 | |
---|
| 160 | def set_parameters(self, params, fixed=None, component=None): |
---|
[526] | 161 | """ |
---|
| 162 | Set the parameters to be fitted. |
---|
| 163 | Parameters: |
---|
| 164 | params: a vector of parameters |
---|
| 165 | fixed: a vector of which parameters are to be held fixed |
---|
| 166 | (default is none) |
---|
| 167 | component: in case of multiple gaussians, the index of the |
---|
| 168 | component |
---|
| 169 | """ |
---|
[515] | 170 | if self.fitfunc is None: |
---|
[723] | 171 | msg = "Please specify a fitting function first." |
---|
| 172 | if rcParams['verbose']: |
---|
| 173 | print msg |
---|
| 174 | return |
---|
| 175 | else: |
---|
| 176 | raise RuntimeError(msg) |
---|
[515] | 177 | if self.fitfunc == "gauss" and component is not None: |
---|
| 178 | if not self.fitted: |
---|
| 179 | from numarray import zeros |
---|
| 180 | pars = list(zeros(len(self.components)*3)) |
---|
| 181 | fxd = list(zeros(len(pars))) |
---|
| 182 | else: |
---|
[723] | 183 | pars = list(self.fitter.getparameters()) |
---|
[515] | 184 | fxd = list(self.fitter.getfixedparameters()) |
---|
| 185 | i = 3*component |
---|
| 186 | pars[i:i+3] = params |
---|
| 187 | fxd[i:i+3] = fixed |
---|
| 188 | params = pars |
---|
[723] | 189 | fixed = fxd |
---|
[113] | 190 | self.fitter.setparameters(params) |
---|
| 191 | if fixed is not None: |
---|
| 192 | self.fitter.setfixedparameters(fixed) |
---|
[723] | 193 | print_log() |
---|
[113] | 194 | return |
---|
[515] | 195 | |
---|
| 196 | def set_gauss_parameters(self, peak, centre, fhwm, |
---|
| 197 | peakfixed=False, centerfixed=False, |
---|
| 198 | fhwmfixed=False, |
---|
| 199 | component=0): |
---|
[113] | 200 | """ |
---|
[515] | 201 | Set the Parameters of a 'Gaussian' component, set with set_function. |
---|
| 202 | Parameters: |
---|
| 203 | peak, centre, fhwm: The gaussian parameters |
---|
| 204 | peakfixed, |
---|
| 205 | centerfixed, |
---|
| 206 | fhwmfixed: Optional parameters to indicate if |
---|
| 207 | the paramters should be held fixed during |
---|
| 208 | the fitting process. The default is to keep |
---|
| 209 | all parameters flexible. |
---|
[526] | 210 | component: The number of the component (Default is the |
---|
| 211 | component 0) |
---|
[515] | 212 | """ |
---|
| 213 | if self.fitfunc != "gauss": |
---|
[723] | 214 | msg = "Function only operates on Gaussian components." |
---|
| 215 | if rcParams['verbose']: |
---|
| 216 | print msg |
---|
| 217 | return |
---|
| 218 | else: |
---|
| 219 | raise ValueError(msg) |
---|
[515] | 220 | if 0 <= component < len(self.components): |
---|
| 221 | self.set_parameters([peak, centre, fhwm], |
---|
| 222 | [peakfixed, centerfixed, fhwmfixed], |
---|
| 223 | component) |
---|
| 224 | else: |
---|
[723] | 225 | msg = "Please select a valid component." |
---|
| 226 | if rcParams['verbose']: |
---|
| 227 | print msg |
---|
| 228 | return |
---|
| 229 | else: |
---|
| 230 | raise ValueError(msg) |
---|
| 231 | |
---|
[515] | 232 | def get_parameters(self, component=None): |
---|
| 233 | """ |
---|
[113] | 234 | Return the fit paramters. |
---|
[526] | 235 | Parameters: |
---|
| 236 | component: get the parameters for the specified component |
---|
| 237 | only, default is all components |
---|
[113] | 238 | """ |
---|
| 239 | if not self.fitted: |
---|
[723] | 240 | msg = "Not yet fitted." |
---|
| 241 | if rcParams['verbose']: |
---|
| 242 | print msg |
---|
| 243 | return |
---|
| 244 | else: |
---|
| 245 | raise RuntimeError(msg) |
---|
[113] | 246 | pars = list(self.fitter.getparameters()) |
---|
| 247 | fixed = list(self.fitter.getfixedparameters()) |
---|
[723] | 248 | if component is not None: |
---|
[515] | 249 | if self.fitfunc == "gauss": |
---|
| 250 | i = 3*component |
---|
| 251 | cpars = pars[i:i+3] |
---|
| 252 | cfixed = fixed[i:i+3] |
---|
| 253 | else: |
---|
| 254 | cpars = pars |
---|
[723] | 255 | cfixed = fixed |
---|
[515] | 256 | else: |
---|
| 257 | cpars = pars |
---|
| 258 | cfixed = fixed |
---|
| 259 | fpars = self._format_pars(cpars, cfixed) |
---|
[723] | 260 | if rcParams['verbose']: |
---|
[515] | 261 | print fpars |
---|
| 262 | return cpars, cfixed, fpars |
---|
[723] | 263 | |
---|
[515] | 264 | def _format_pars(self, pars, fixed): |
---|
[113] | 265 | out = '' |
---|
| 266 | if self.fitfunc == 'poly': |
---|
| 267 | c = 0 |
---|
[515] | 268 | for i in range(len(pars)): |
---|
| 269 | fix = "" |
---|
| 270 | if fixed[i]: fix = "(fixed)" |
---|
| 271 | out += ' p%d%s= %3.3f,' % (c,fix,pars[i]) |
---|
[113] | 272 | c+=1 |
---|
[515] | 273 | out = out[:-1] # remove trailing ',' |
---|
[113] | 274 | elif self.fitfunc == 'gauss': |
---|
| 275 | i = 0 |
---|
| 276 | c = 0 |
---|
[515] | 277 | aunit = '' |
---|
| 278 | ounit = '' |
---|
[113] | 279 | if self.data: |
---|
[515] | 280 | aunit = self.data.get_unit() |
---|
| 281 | ounit = self.data.get_fluxunit() |
---|
[113] | 282 | while i < len(pars): |
---|
[515] | 283 | out += ' %d: 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) |
---|
[113] | 284 | c+=1 |
---|
| 285 | i+=3 |
---|
| 286 | return out |
---|
[723] | 287 | |
---|
[113] | 288 | def get_estimate(self): |
---|
| 289 | """ |
---|
[515] | 290 | Return the parameter estimates (for non-linear functions). |
---|
[113] | 291 | """ |
---|
| 292 | pars = self.fitter.getestimate() |
---|
[723] | 293 | if rcParams['verbose']: |
---|
[113] | 294 | print self._format_pars(pars) |
---|
| 295 | return pars |
---|
| 296 | |
---|
| 297 | def get_residual(self): |
---|
| 298 | """ |
---|
| 299 | Return the residual of the fit. |
---|
| 300 | """ |
---|
| 301 | if not self.fitted: |
---|
[723] | 302 | msg = "Not yet fitted." |
---|
| 303 | if rcParams['verbose']: |
---|
| 304 | print msg |
---|
| 305 | return |
---|
| 306 | else: |
---|
| 307 | raise RuntimeError(msg) |
---|
[113] | 308 | return self.fitter.getresidual() |
---|
| 309 | |
---|
| 310 | def get_chi2(self): |
---|
| 311 | """ |
---|
| 312 | Return chi^2. |
---|
| 313 | """ |
---|
| 314 | if not self.fitted: |
---|
[723] | 315 | msg = "Not yet fitted." |
---|
| 316 | if rcParams['verbose']: |
---|
| 317 | print msg |
---|
| 318 | return |
---|
| 319 | else: |
---|
| 320 | raise RuntimeError(msg) |
---|
[113] | 321 | ch2 = self.fitter.getchi2() |
---|
[723] | 322 | if rcParams['verbose']: |
---|
[113] | 323 | print 'Chi^2 = %3.3f' % (ch2) |
---|
[723] | 324 | return ch2 |
---|
[113] | 325 | |
---|
| 326 | def get_fit(self): |
---|
| 327 | """ |
---|
| 328 | Return the fitted ordinate values. |
---|
| 329 | """ |
---|
| 330 | if not self.fitted: |
---|
[723] | 331 | msg = "Not yet fitted." |
---|
| 332 | if rcParams['verbose']: |
---|
| 333 | print msg |
---|
| 334 | return |
---|
| 335 | else: |
---|
| 336 | raise RuntimeError(msg) |
---|
[113] | 337 | return self.fitter.getfit() |
---|
| 338 | |
---|
| 339 | def commit(self): |
---|
| 340 | """ |
---|
[526] | 341 | Return a new scan where the fits have been commited (subtracted) |
---|
[113] | 342 | """ |
---|
| 343 | if not self.fitted: |
---|
| 344 | print "Not yet fitted." |
---|
[723] | 345 | msg = "Not yet fitted." |
---|
| 346 | if rcParams['verbose']: |
---|
| 347 | print msg |
---|
| 348 | return |
---|
| 349 | else: |
---|
| 350 | raise RuntimeError(msg) |
---|
[113] | 351 | if self.data is not scantable: |
---|
[723] | 352 | msg = "Not a scantable" |
---|
| 353 | if rcParams['verbose']: |
---|
| 354 | print msg |
---|
| 355 | return |
---|
| 356 | else: |
---|
| 357 | raise TypeError(msg) |
---|
[113] | 358 | scan = self.data.copy() |
---|
[259] | 359 | scan._setspectrum(self.fitter.getresidual()) |
---|
[723] | 360 | print_log() |
---|
[113] | 361 | |
---|
[723] | 362 | def plot(self, residual=False, components=None, plotparms=False, filename=None): |
---|
[113] | 363 | """ |
---|
| 364 | Plot the last fit. |
---|
| 365 | Parameters: |
---|
| 366 | residual: an optional parameter indicating if the residual |
---|
| 367 | should be plotted (default 'False') |
---|
[526] | 368 | components: a list of components to plot, e.g [0,1], |
---|
| 369 | -1 plots the total fit. Default is to only |
---|
| 370 | plot the total fit. |
---|
| 371 | plotparms: Inidicates if the parameter values should be present |
---|
| 372 | on the plot |
---|
[113] | 373 | """ |
---|
| 374 | if not self.fitted: |
---|
| 375 | return |
---|
[723] | 376 | if not self._p or self._p.is_dead: |
---|
| 377 | if rcParams['plotter.gui']: |
---|
| 378 | from asap.asaplotgui import asaplotgui as asaplot |
---|
| 379 | else: |
---|
| 380 | from asap.asaplot import asaplot |
---|
| 381 | self._p = asaplot() |
---|
| 382 | self._p.hold() |
---|
[113] | 383 | self._p.clear() |
---|
[515] | 384 | self._p.set_panels() |
---|
[652] | 385 | self._p.palette(0) |
---|
[113] | 386 | tlab = 'Spectrum' |
---|
[723] | 387 | xlab = 'Abcissa' |
---|
[515] | 388 | m = () |
---|
[113] | 389 | if self.data: |
---|
[515] | 390 | tlab = self.data._getsourcename(self._fittedrow) |
---|
| 391 | xlab = self.data._getabcissalabel(self._fittedrow) |
---|
| 392 | m = self.data._getmask(self._fittedrow) |
---|
[626] | 393 | ylab = self.data._get_ordinate_label() |
---|
[515] | 394 | |
---|
[668] | 395 | colours = ["#777777","#bbbbbb","red","orange","purple","green","magenta", "cyan"] |
---|
[652] | 396 | self._p.palette(0,colours) |
---|
[515] | 397 | self._p.set_line(label='Spectrum') |
---|
[113] | 398 | self._p.plot(self.x, self.y, m) |
---|
| 399 | if residual: |
---|
[652] | 400 | self._p.palette(1) |
---|
[515] | 401 | self._p.set_line(label='Residual') |
---|
[113] | 402 | self._p.plot(self.x, self.get_residual(), m) |
---|
[652] | 403 | self._p.palette(2) |
---|
[515] | 404 | if components is not None: |
---|
| 405 | cs = components |
---|
| 406 | if isinstance(components,int): cs = [components] |
---|
[526] | 407 | if plotparms: |
---|
| 408 | self._p.text(0.15,0.15,str(self.get_parameters()[2]),size=8) |
---|
[515] | 409 | n = len(self.components) |
---|
[652] | 410 | self._p.palette(3) |
---|
[515] | 411 | for c in cs: |
---|
| 412 | if 0 <= c < n: |
---|
| 413 | lab = self.fitfuncs[c]+str(c) |
---|
| 414 | self._p.set_line(label=lab) |
---|
| 415 | self._p.plot(self.x, self.fitter.evaluate(c), m) |
---|
| 416 | elif c == -1: |
---|
[652] | 417 | self._p.palette(2) |
---|
[515] | 418 | self._p.set_line(label="Total Fit") |
---|
[723] | 419 | self._p.plot(self.x, self.get_fit(), m) |
---|
[515] | 420 | else: |
---|
[652] | 421 | self._p.palette(2) |
---|
[515] | 422 | self._p.set_line(label='Fit') |
---|
| 423 | self._p.plot(self.x, self.get_fit(), m) |
---|
[723] | 424 | xlim=[min(self.x),max(self.x)] |
---|
| 425 | self._p.axes.set_xlim(xlim) |
---|
[113] | 426 | self._p.set_axes('xlabel',xlab) |
---|
| 427 | self._p.set_axes('ylabel',ylab) |
---|
| 428 | self._p.set_axes('title',tlab) |
---|
| 429 | self._p.release() |
---|
[723] | 430 | if (not rcParams['plotter.gui']): |
---|
| 431 | self._p.save(filename) |
---|
| 432 | print_log() |
---|
[113] | 433 | |
---|
[794] | 434 | def auto_fit(self, insitu=None, allaxes=True): |
---|
[113] | 435 | """ |
---|
[515] | 436 | Return a scan where the function is applied to all rows for |
---|
| 437 | all Beams/IFs/Pols. |
---|
[723] | 438 | |
---|
[113] | 439 | """ |
---|
| 440 | from asap import scantable |
---|
[515] | 441 | if not isinstance(self.data, scantable) : |
---|
[723] | 442 | msg = "Data is not a scantable" |
---|
| 443 | if rcParams['verbose']: |
---|
| 444 | print msg |
---|
| 445 | return |
---|
| 446 | else: |
---|
| 447 | raise TypeError(msg) |
---|
[259] | 448 | if insitu is None: insitu = rcParams['insitu'] |
---|
| 449 | if not insitu: |
---|
| 450 | scan = self.data.copy() |
---|
| 451 | else: |
---|
| 452 | scan = self.data |
---|
| 453 | sel = scan.get_cursor() |
---|
[159] | 454 | rows = range(scan.nrow()) |
---|
[723] | 455 | from asap import asaplog |
---|
[794] | 456 | if allaxes: |
---|
| 457 | for i in range(scan.nbeam()): |
---|
| 458 | scan.setbeam(i) |
---|
| 459 | for j in range(scan.nif()): |
---|
| 460 | scan.setif(j) |
---|
| 461 | for k in range(scan.npol()): |
---|
| 462 | scan.setpol(k) |
---|
| 463 | asaplog.push("Fitting:") |
---|
| 464 | out = 'Beam[%d], IF[%d], Pol[%d]' % (i,j,k) |
---|
| 465 | asaplog.push(out) |
---|
| 466 | for iRow in rows: |
---|
| 467 | self.x = scan._getabcissa(iRow) |
---|
| 468 | self.y = scan._getspectrum(iRow) |
---|
| 469 | self.data = None |
---|
| 470 | self.fit() |
---|
| 471 | x = self.get_parameters() |
---|
| 472 | scan._setspectrum(self.fitter.getresidual(),iRow) |
---|
| 473 | else: |
---|
| 474 | asaplog.push("Fitting:") |
---|
| 475 | out = 'Beam[%d], IF[%d], Pol[%d]' % sel |
---|
| 476 | asaplog.push(out) |
---|
| 477 | for iRow in rows: |
---|
| 478 | self.x = scan._getabcissa(iRow) |
---|
| 479 | self.y = scan._getspectrum(iRow) |
---|
| 480 | self.data = None |
---|
| 481 | self.fit() |
---|
| 482 | x = self.get_parameters() |
---|
| 483 | scan._setspectrum(self.fitter.getresidual(),iRow) |
---|
| 484 | |
---|
[259] | 485 | scan.set_cursor(sel[0],sel[1],sel[2]) |
---|
[723] | 486 | print_log() |
---|
[259] | 487 | if not insitu: |
---|
| 488 | return scan |
---|