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