[113] | 1 | import _asap |
---|
[1826] | 2 | from asap.parameters import rcParams |
---|
| 3 | from asap.logging import asaplog, print_log, print_log_dec |
---|
| 4 | from asap.utils import _n_bools, mask_and |
---|
[113] | 5 | |
---|
[1826] | 6 | |
---|
[113] | 7 | class fitter: |
---|
| 8 | """ |
---|
| 9 | The fitting class for ASAP. |
---|
| 10 | """ |
---|
[723] | 11 | |
---|
[113] | 12 | def __init__(self): |
---|
| 13 | """ |
---|
| 14 | Create a fitter object. No state is set. |
---|
| 15 | """ |
---|
| 16 | self.fitter = _asap.fitter() |
---|
| 17 | self.x = None |
---|
| 18 | self.y = None |
---|
| 19 | self.mask = None |
---|
| 20 | self.fitfunc = None |
---|
[515] | 21 | self.fitfuncs = None |
---|
[113] | 22 | self.fitted = False |
---|
| 23 | self.data = None |
---|
[515] | 24 | self.components = 0 |
---|
| 25 | self._fittedrow = 0 |
---|
[113] | 26 | self._p = None |
---|
[515] | 27 | self._selection = None |
---|
[1391] | 28 | self.uselinear = False |
---|
[113] | 29 | |
---|
| 30 | def set_data(self, xdat, ydat, mask=None): |
---|
| 31 | """ |
---|
[158] | 32 | Set the absissa and ordinate for the fit. Also set the mask |
---|
[113] | 33 | indicationg 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: |
---|
[158] | 37 | xdat: the abcissa values |
---|
[113] | 38 | ydat: the ordinate values |
---|
| 39 | mask: an optional mask |
---|
[723] | 40 | |
---|
[113] | 41 | """ |
---|
| 42 | self.fitted = False |
---|
| 43 | self.x = xdat |
---|
| 44 | self.y = ydat |
---|
| 45 | if mask == None: |
---|
[1295] | 46 | self.mask = _n_bools(len(xdat), True) |
---|
[113] | 47 | else: |
---|
| 48 | self.mask = mask |
---|
| 49 | return |
---|
| 50 | |
---|
| 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" |
---|
| 60 | if rcParams['verbose']: |
---|
[1819] | 61 | #print msg |
---|
| 62 | asaplog.push(msg) |
---|
| 63 | print_log('ERROR') |
---|
[723] | 64 | return |
---|
| 65 | else: |
---|
| 66 | raise TypeError(msg) |
---|
[113] | 67 | self.fitted = False |
---|
| 68 | self.data = thescan |
---|
[1075] | 69 | self.mask = None |
---|
[113] | 70 | if mask is None: |
---|
[1295] | 71 | self.mask = _n_bools(self.data.nchan(), True) |
---|
[113] | 72 | else: |
---|
| 73 | self.mask = mask |
---|
| 74 | return |
---|
| 75 | |
---|
| 76 | def set_function(self, **kwargs): |
---|
| 77 | """ |
---|
| 78 | Set the function to be fit. |
---|
| 79 | Parameters: |
---|
[1589] | 80 | poly: use a polynomial of the order given with nonlinear least squares fit |
---|
[1391] | 81 | lpoly: use polynomial of the order given with linear least squares fit |
---|
[113] | 82 | gauss: fit the number of gaussian specified |
---|
[1819] | 83 | lorentz: fit the number of lorentzian specified |
---|
[113] | 84 | Example: |
---|
[1391] | 85 | fitter.set_function(poly=3) # will fit a 3rd order polynomial via nonlinear method |
---|
| 86 | fitter.set_function(lpoly=3) # will fit a 3rd order polynomial via linear method |
---|
[1819] | 87 | fitter.set_function(gauss=2) # will fit two gaussians |
---|
| 88 | fitter.set_function(lorentz=2) # will fit two lorentzians |
---|
[113] | 89 | """ |
---|
[723] | 90 | #default poly order 0 |
---|
[515] | 91 | n=0 |
---|
[113] | 92 | if kwargs.has_key('poly'): |
---|
| 93 | self.fitfunc = 'poly' |
---|
| 94 | n = kwargs.get('poly') |
---|
[515] | 95 | self.components = [n] |
---|
[1589] | 96 | self.uselinear = False |
---|
[1391] | 97 | elif kwargs.has_key('lpoly'): |
---|
| 98 | self.fitfunc = 'poly' |
---|
| 99 | n = kwargs.get('lpoly') |
---|
| 100 | self.components = [n] |
---|
| 101 | self.uselinear = True |
---|
[113] | 102 | elif kwargs.has_key('gauss'): |
---|
| 103 | n = kwargs.get('gauss') |
---|
| 104 | self.fitfunc = 'gauss' |
---|
[515] | 105 | self.fitfuncs = [ 'gauss' for i in range(n) ] |
---|
| 106 | self.components = [ 3 for i in range(n) ] |
---|
[1589] | 107 | self.uselinear = False |
---|
[1819] | 108 | elif kwargs.has_key('lorentz'): |
---|
| 109 | n = kwargs.get('lorentz') |
---|
| 110 | self.fitfunc = 'lorentz' |
---|
| 111 | self.fitfuncs = [ 'lorentz' for i in range(n) ] |
---|
| 112 | self.components = [ 3 for i in range(n) ] |
---|
| 113 | self.uselinear = False |
---|
[515] | 114 | else: |
---|
[723] | 115 | msg = "Invalid function type." |
---|
| 116 | if rcParams['verbose']: |
---|
[1819] | 117 | #print msg |
---|
| 118 | asaplog.push(msg) |
---|
| 119 | print_log('ERROR') |
---|
[723] | 120 | return |
---|
| 121 | else: |
---|
| 122 | raise TypeError(msg) |
---|
| 123 | |
---|
[113] | 124 | self.fitter.setexpression(self.fitfunc,n) |
---|
[1232] | 125 | self.fitted = False |
---|
[113] | 126 | return |
---|
[723] | 127 | |
---|
[1589] | 128 | @print_log_dec |
---|
[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']: |
---|
[1819] | 149 | #print msg |
---|
| 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) |
---|
[1536] | 160 | self.mask = mask_and(self.mask, self.data._getmask(row)) |
---|
[723] | 161 | asaplog.push("Fitting:") |
---|
[943] | 162 | i = row |
---|
[1536] | 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), |
---|
[1589] | 166 | self.data.getpol(i), |
---|
[1536] | 167 | self.data.getcycle(i)) |
---|
[1075] | 168 | asaplog.push(out,False) |
---|
[515] | 169 | self.fitter.setdata(self.x, self.y, self.mask) |
---|
[1819] | 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() |
---|
[626] | 174 | try: |
---|
[1232] | 175 | fxdpar = list(self.fitter.getfixedparameters()) |
---|
| 176 | if len(fxdpar) and fxdpar.count(0) == 0: |
---|
| 177 | raise RuntimeError,"No point fitting, if all parameters are fixed." |
---|
[1391] | 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']: |
---|
[1819] | 186 | #print msg |
---|
| 187 | print_log() |
---|
| 188 | asaplog.push(str(msg)) |
---|
| 189 | print_log('ERROR') |
---|
[723] | 190 | else: |
---|
| 191 | raise |
---|
[515] | 192 | self._fittedrow = row |
---|
[113] | 193 | self.fitted = True |
---|
[1819] | 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 | |
---|
[1589] | 223 | @print_log_dec |
---|
[1017] | 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']: |
---|
[1819] | 247 | #print msg |
---|
| 248 | asaplog.push(msg) |
---|
| 249 | print_log('ERROR') |
---|
[723] | 250 | return |
---|
| 251 | else: |
---|
| 252 | raise RuntimeError(msg) |
---|
[1819] | 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) |
---|
[1819] | 268 | print_log() |
---|
[113] | 269 | return |
---|
[515] | 270 | |
---|
[1217] | 271 | def set_gauss_parameters(self, peak, centre, fwhm, |
---|
[1409] | 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, |
---|
[1409] | 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']: |
---|
[1819] | 291 | #print msg |
---|
| 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], |
---|
[1409] | 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']: |
---|
[1819] | 304 | #print msg |
---|
| 305 | asaplog.push(msg) |
---|
| 306 | print_log('ERROR') |
---|
[723] | 307 | return |
---|
| 308 | else: |
---|
| 309 | raise ValueError(msg) |
---|
| 310 | |
---|
[1819] | 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 | """ |
---|
[1819] | 353 | Return the area under the fitted gaussian/lorentzian component. |
---|
[975] | 354 | Parameters: |
---|
[1819] | 355 | component: the gaussian/lorentzian component selection, |
---|
[975] | 356 | default (None) is the sum of all components |
---|
| 357 | Note: |
---|
[1819] | 358 | This will only work for gaussian/lorentzian fits. |
---|
[975] | 359 | """ |
---|
| 360 | if not self.fitted: return |
---|
[1819] | 361 | if self.fitfunc == "gauss" or self.fitfunc == "lorentz": |
---|
[975] | 362 | pars = list(self.fitter.getparameters()) |
---|
| 363 | from math import log,pi,sqrt |
---|
[1819] | 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']: |
---|
[1819] | 390 | #print msg |
---|
| 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: |
---|
[1819] | 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']: |
---|
[1819] | 415 | #print msg |
---|
| 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: |
---|
[1819] | 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 |
---|
[1819] | 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']: |
---|
[1819] | 447 | #print fpars |
---|
| 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 ',' |
---|
[1819] | 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']: |
---|
[1819] | 490 | #print self._format_pars(pars,fixed,None) |
---|
| 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']: |
---|
[1819] | 502 | #print msg |
---|
| 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']: |
---|
[1819] | 517 | #print msg |
---|
| 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']: |
---|
[1819] | 525 | #print 'Chi^2 = %3.3f' % (ch2) |
---|
| 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']: |
---|
[1819] | 537 | #print msg |
---|
| 538 | asaplog.push(msg) |
---|
| 539 | print_log('ERROR') |
---|
[723] | 540 | return |
---|
| 541 | else: |
---|
| 542 | raise RuntimeError(msg) |
---|
[113] | 543 | return self.fitter.getfit() |
---|
| 544 | |
---|
[1589] | 545 | @print_log_dec |
---|
[113] | 546 | def commit(self): |
---|
| 547 | """ |
---|
[526] | 548 | Return a new scan where the fits have been commited (subtracted) |
---|
[113] | 549 | """ |
---|
| 550 | if not self.fitted: |
---|
[723] | 551 | msg = "Not yet fitted." |
---|
| 552 | if rcParams['verbose']: |
---|
[1819] | 553 | #print msg |
---|
| 554 | asaplog.push(msg) |
---|
| 555 | print_log('ERROR') |
---|
[723] | 556 | return |
---|
| 557 | else: |
---|
| 558 | raise RuntimeError(msg) |
---|
[975] | 559 | from asap import scantable |
---|
| 560 | if not isinstance(self.data, scantable): |
---|
[723] | 561 | msg = "Not a scantable" |
---|
| 562 | if rcParams['verbose']: |
---|
[1819] | 563 | #print msg |
---|
| 564 | asaplog.push(msg) |
---|
| 565 | print_log('ERROR') |
---|
[723] | 566 | return |
---|
| 567 | else: |
---|
| 568 | raise TypeError(msg) |
---|
[113] | 569 | scan = self.data.copy() |
---|
[259] | 570 | scan._setspectrum(self.fitter.getresidual()) |
---|
[1819] | 571 | print_log() |
---|
[1092] | 572 | return scan |
---|
[113] | 573 | |
---|
[1589] | 574 | @print_log_dec |
---|
[1689] | 575 | def plot(self, residual=False, components=None, plotparms=False, |
---|
| 576 | filename=None): |
---|
[113] | 577 | """ |
---|
| 578 | Plot the last fit. |
---|
| 579 | Parameters: |
---|
| 580 | residual: an optional parameter indicating if the residual |
---|
| 581 | should be plotted (default 'False') |
---|
[526] | 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 |
---|
[113] | 587 | """ |
---|
| 588 | if not self.fitted: |
---|
| 589 | return |
---|
[723] | 590 | if not self._p or self._p.is_dead: |
---|
| 591 | if rcParams['plotter.gui']: |
---|
| 592 | from asap.asaplotgui import asaplotgui as asaplot |
---|
| 593 | else: |
---|
| 594 | from asap.asaplot import asaplot |
---|
| 595 | self._p = asaplot() |
---|
| 596 | self._p.hold() |
---|
[113] | 597 | self._p.clear() |
---|
[515] | 598 | self._p.set_panels() |
---|
[652] | 599 | self._p.palette(0) |
---|
[113] | 600 | tlab = 'Spectrum' |
---|
[723] | 601 | xlab = 'Abcissa' |
---|
[1017] | 602 | ylab = 'Ordinate' |
---|
[1739] | 603 | from numpy import ma,logical_not,logical_and,array |
---|
[1273] | 604 | m = self.mask |
---|
[113] | 605 | if self.data: |
---|
[515] | 606 | tlab = self.data._getsourcename(self._fittedrow) |
---|
| 607 | xlab = self.data._getabcissalabel(self._fittedrow) |
---|
[1273] | 608 | m = logical_and(self.mask, |
---|
[1306] | 609 | array(self.data._getmask(self._fittedrow), |
---|
| 610 | copy=False)) |
---|
[1589] | 611 | |
---|
[626] | 612 | ylab = self.data._get_ordinate_label() |
---|
[515] | 613 | |
---|
[1075] | 614 | colours = ["#777777","#dddddd","red","orange","purple","green","magenta", "cyan"] |
---|
[1819] | 615 | nomask=True |
---|
| 616 | for i in range(len(m)): |
---|
| 617 | nomask = nomask and m[i] |
---|
| 618 | label0='Masked Region' |
---|
| 619 | label1='Spectrum' |
---|
| 620 | if ( nomask ): |
---|
| 621 | label0=label1 |
---|
| 622 | else: |
---|
| 623 | y = ma.masked_array( self.y, mask = m ) |
---|
| 624 | self._p.palette(1,colours) |
---|
| 625 | self._p.set_line( label = label1 ) |
---|
| 626 | self._p.plot( self.x, y ) |
---|
[652] | 627 | self._p.palette(0,colours) |
---|
[1819] | 628 | self._p.set_line(label=label0) |
---|
[1273] | 629 | y = ma.masked_array(self.y,mask=logical_not(m)) |
---|
[1088] | 630 | self._p.plot(self.x, y) |
---|
[113] | 631 | if residual: |
---|
[1819] | 632 | self._p.palette(7) |
---|
[515] | 633 | self._p.set_line(label='Residual') |
---|
[1116] | 634 | y = ma.masked_array(self.get_residual(), |
---|
[1273] | 635 | mask=logical_not(m)) |
---|
[1088] | 636 | self._p.plot(self.x, y) |
---|
[652] | 637 | self._p.palette(2) |
---|
[515] | 638 | if components is not None: |
---|
| 639 | cs = components |
---|
| 640 | if isinstance(components,int): cs = [components] |
---|
[526] | 641 | if plotparms: |
---|
[1031] | 642 | self._p.text(0.15,0.15,str(self.get_parameters()['formatted']),size=8) |
---|
[515] | 643 | n = len(self.components) |
---|
[652] | 644 | self._p.palette(3) |
---|
[515] | 645 | for c in cs: |
---|
| 646 | if 0 <= c < n: |
---|
| 647 | lab = self.fitfuncs[c]+str(c) |
---|
| 648 | self._p.set_line(label=lab) |
---|
[1116] | 649 | y = ma.masked_array(self.fitter.evaluate(c), |
---|
[1273] | 650 | mask=logical_not(m)) |
---|
[1088] | 651 | |
---|
| 652 | self._p.plot(self.x, y) |
---|
[515] | 653 | elif c == -1: |
---|
[652] | 654 | self._p.palette(2) |
---|
[515] | 655 | self._p.set_line(label="Total Fit") |
---|
[1116] | 656 | y = ma.masked_array(self.fitter.getfit(), |
---|
[1273] | 657 | mask=logical_not(m)) |
---|
[1088] | 658 | self._p.plot(self.x, y) |
---|
[515] | 659 | else: |
---|
[652] | 660 | self._p.palette(2) |
---|
[515] | 661 | self._p.set_line(label='Fit') |
---|
[1116] | 662 | y = ma.masked_array(self.fitter.getfit(), |
---|
[1273] | 663 | mask=logical_not(m)) |
---|
[1088] | 664 | self._p.plot(self.x, y) |
---|
[723] | 665 | xlim=[min(self.x),max(self.x)] |
---|
| 666 | self._p.axes.set_xlim(xlim) |
---|
[113] | 667 | self._p.set_axes('xlabel',xlab) |
---|
| 668 | self._p.set_axes('ylabel',ylab) |
---|
| 669 | self._p.set_axes('title',tlab) |
---|
| 670 | self._p.release() |
---|
[723] | 671 | if (not rcParams['plotter.gui']): |
---|
| 672 | self._p.save(filename) |
---|
[1819] | 673 | print_log() |
---|
[113] | 674 | |
---|
[1589] | 675 | @print_log_dec |
---|
[1061] | 676 | def auto_fit(self, insitu=None, plot=False): |
---|
[113] | 677 | """ |
---|
[515] | 678 | Return a scan where the function is applied to all rows for |
---|
| 679 | all Beams/IFs/Pols. |
---|
[723] | 680 | |
---|
[113] | 681 | """ |
---|
| 682 | from asap import scantable |
---|
[515] | 683 | if not isinstance(self.data, scantable) : |
---|
[723] | 684 | msg = "Data is not a scantable" |
---|
| 685 | if rcParams['verbose']: |
---|
[1819] | 686 | #print msg |
---|
| 687 | asaplog.push(msg) |
---|
| 688 | print_log('ERROR') |
---|
[723] | 689 | return |
---|
| 690 | else: |
---|
| 691 | raise TypeError(msg) |
---|
[259] | 692 | if insitu is None: insitu = rcParams['insitu'] |
---|
| 693 | if not insitu: |
---|
| 694 | scan = self.data.copy() |
---|
| 695 | else: |
---|
| 696 | scan = self.data |
---|
[880] | 697 | rows = xrange(scan.nrow()) |
---|
[1826] | 698 | # Save parameters of baseline fits as a class attribute. |
---|
[1819] | 699 | # NOTICE: This does not reflect changes in scantable! |
---|
| 700 | if len(rows) > 0: self.blpars=[] |
---|
[876] | 701 | asaplog.push("Fitting:") |
---|
| 702 | for r in rows: |
---|
[1536] | 703 | out = " Scan[%d] Beam[%d] IF[%d] Pol[%d] Cycle[%d]" % (scan.getscan(r), |
---|
| 704 | scan.getbeam(r), |
---|
| 705 | scan.getif(r), |
---|
[1589] | 706 | scan.getpol(r), |
---|
[1536] | 707 | scan.getcycle(r)) |
---|
[880] | 708 | asaplog.push(out, False) |
---|
[876] | 709 | self.x = scan._getabcissa(r) |
---|
| 710 | self.y = scan._getspectrum(r) |
---|
[1536] | 711 | self.mask = mask_and(self.mask, scan._getmask(r)) |
---|
[876] | 712 | self.data = None |
---|
| 713 | self.fit() |
---|
| 714 | x = self.get_parameters() |
---|
[1819] | 715 | fpar = self.get_parameters() |
---|
[1061] | 716 | if plot: |
---|
| 717 | self.plot(residual=True) |
---|
| 718 | x = raw_input("Accept fit ([y]/n): ") |
---|
| 719 | if x.upper() == 'N': |
---|
[1819] | 720 | self.blpars.append(None) |
---|
[1061] | 721 | continue |
---|
[880] | 722 | scan._setspectrum(self.fitter.getresidual(), r) |
---|
[1819] | 723 | self.blpars.append(fpar) |
---|
[1061] | 724 | if plot: |
---|
| 725 | self._p.unmap() |
---|
| 726 | self._p = None |
---|
[1819] | 727 | print_log() |
---|
[876] | 728 | return scan |
---|