| [113] | 1 | import _asap | 
|---|
| [1826] | 2 | from asap.parameters import rcParams | 
|---|
| [1862] | 3 | from asap.logging import asaplog, asaplog_post_dec | 
|---|
| [1826] | 4 | from asap.utils import _n_bools, mask_and | 
|---|
| [2666] | 5 | from numpy import ndarray | 
|---|
| [113] | 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 | 
|---|
| [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 | 
|---|
| [2666] | 28 | self._constraints = [] | 
|---|
| [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 | 
|---|
| [2153] | 33 | indicating valid points. | 
|---|
| [113] | 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 |  | 
|---|
| [1862] | 51 | @asaplog_post_dec | 
|---|
| [113] | 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 | 
|---|
| [1420] | 57 | mask:        a msk retrieved from the scantable | 
|---|
| [113] | 58 | """ | 
|---|
|  | 59 | if not thescan: | 
|---|
| [723] | 60 | msg = "Please give a correct scan" | 
|---|
| [1859] | 61 | raise TypeError(msg) | 
|---|
| [113] | 62 | self.fitted = False | 
|---|
|  | 63 | self.data = thescan | 
|---|
| [1075] | 64 | self.mask = None | 
|---|
| [113] | 65 | if mask is None: | 
|---|
| [1295] | 66 | self.mask = _n_bools(self.data.nchan(), True) | 
|---|
| [113] | 67 | else: | 
|---|
|  | 68 | self.mask = mask | 
|---|
|  | 69 | return | 
|---|
|  | 70 |  | 
|---|
| [1862] | 71 | @asaplog_post_dec | 
|---|
| [113] | 72 | def set_function(self, **kwargs): | 
|---|
|  | 73 | """ | 
|---|
|  | 74 | Set the function to be fit. | 
|---|
|  | 75 | Parameters: | 
|---|
| [2666] | 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 | 
|---|
| [2047] | 80 | gauss:    fit the number of gaussian specified | 
|---|
|  | 81 | lorentz:  fit the number of lorentzian specified | 
|---|
|  | 82 | sinusoid: fit the number of sinusoid specified | 
|---|
| [113] | 83 | Example: | 
|---|
| [2666] | 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 | 
|---|
| [1819] | 88 | fitter.set_function(gauss=2) # will fit two gaussians | 
|---|
|  | 89 | fitter.set_function(lorentz=2) # will fit two lorentzians | 
|---|
| [2047] | 90 | fitter.set_function(sinusoid=3) # will fit three sinusoids | 
|---|
| [113] | 91 | """ | 
|---|
| [723] | 92 | #default poly order 0 | 
|---|
| [515] | 93 | n=0 | 
|---|
| [113] | 94 | if kwargs.has_key('poly'): | 
|---|
|  | 95 | self.fitfunc = 'poly' | 
|---|
| [1938] | 96 | self.fitfuncs = ['poly'] | 
|---|
| [113] | 97 | n = kwargs.get('poly') | 
|---|
| [1938] | 98 | self.components = [n+1] | 
|---|
| [1589] | 99 | self.uselinear = False | 
|---|
| [1391] | 100 | elif kwargs.has_key('lpoly'): | 
|---|
|  | 101 | self.fitfunc = 'poly' | 
|---|
| [1938] | 102 | self.fitfuncs = ['lpoly'] | 
|---|
| [1391] | 103 | n = kwargs.get('lpoly') | 
|---|
| [1938] | 104 | self.components = [n+1] | 
|---|
| [1391] | 105 | self.uselinear = True | 
|---|
| [113] | 106 | elif kwargs.has_key('gauss'): | 
|---|
|  | 107 | n = kwargs.get('gauss') | 
|---|
|  | 108 | self.fitfunc = 'gauss' | 
|---|
| [515] | 109 | self.fitfuncs = [ 'gauss' for i in range(n) ] | 
|---|
|  | 110 | self.components = [ 3 for i in range(n) ] | 
|---|
| [1589] | 111 | self.uselinear = False | 
|---|
| [1819] | 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 | 
|---|
| [2047] | 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 | 
|---|
| [2666] | 124 | elif kwargs.has_key('expression'): | 
|---|
|  | 125 | self.uselinear = False | 
|---|
|  | 126 | raise RuntimeError("Not yet implemented") | 
|---|
| [515] | 127 | else: | 
|---|
| [723] | 128 | msg = "Invalid function type." | 
|---|
| [1859] | 129 | raise TypeError(msg) | 
|---|
| [723] | 130 |  | 
|---|
| [113] | 131 | self.fitter.setexpression(self.fitfunc,n) | 
|---|
| [2666] | 132 | self._constraints = [] | 
|---|
| [1232] | 133 | self.fitted = False | 
|---|
| [113] | 134 | return | 
|---|
| [723] | 135 |  | 
|---|
| [1862] | 136 | @asaplog_post_dec | 
|---|
| [1075] | 137 | def fit(self, row=0, estimate=False): | 
|---|
| [113] | 138 | """ | 
|---|
|  | 139 | Execute the actual fitting process. All the state has to be set. | 
|---|
|  | 140 | Parameters: | 
|---|
| [1075] | 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. | 
|---|
| [113] | 145 | Example: | 
|---|
| [515] | 146 | s = scantable('myscan.asap') | 
|---|
|  | 147 | s.set_cursor(thepol=1)        # select second pol | 
|---|
| [113] | 148 | f = fitter() | 
|---|
|  | 149 | f.set_scan(s) | 
|---|
|  | 150 | f.set_function(poly=0) | 
|---|
| [723] | 151 | f.fit(row=0)                  # fit first row | 
|---|
| [113] | 152 | """ | 
|---|
|  | 153 | if ((self.x is None or self.y is None) and self.data is None) \ | 
|---|
|  | 154 | or self.fitfunc is None: | 
|---|
| [723] | 155 | msg = "Fitter not yet initialised. Please set data & fit function" | 
|---|
| [1859] | 156 | raise RuntimeError(msg) | 
|---|
| [723] | 157 |  | 
|---|
| [2666] | 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 |  | 
|---|
| [515] | 180 | self.fitter.setdata(self.x, self.y, self.mask) | 
|---|
| [1819] | 181 | if self.fitfunc == 'gauss' or self.fitfunc == 'lorentz': | 
|---|
| [113] | 182 | ps = self.fitter.getparameters() | 
|---|
| [1075] | 183 | if len(ps) == 0 or estimate: | 
|---|
| [113] | 184 | self.fitter.estimate() | 
|---|
| [1859] | 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." | 
|---|
| [2666] | 188 | if self._constraints: | 
|---|
|  | 189 | for c in self._constraints: | 
|---|
|  | 190 | self.fitter.addconstraint(c[0]+[c[-1]]) | 
|---|
| [1859] | 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." | 
|---|
| [515] | 197 | self._fittedrow = row | 
|---|
| [113] | 198 | self.fitted = True | 
|---|
|  | 199 | return | 
|---|
|  | 200 |  | 
|---|
| [1232] | 201 | def store_fit(self, filename=None): | 
|---|
| [526] | 202 | """ | 
|---|
| [1232] | 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 | 
|---|
| [526] | 207 | """ | 
|---|
| [515] | 208 | if self.fitted and self.data is not None: | 
|---|
|  | 209 | pars = list(self.fitter.getparameters()) | 
|---|
|  | 210 | fixed = list(self.fitter.getfixedparameters()) | 
|---|
| [975] | 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()) | 
|---|
| [1232] | 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) | 
|---|
| [515] | 226 |  | 
|---|
| [1862] | 227 | @asaplog_post_dec | 
|---|
| [1017] | 228 | def set_parameters(self,*args,**kwargs): | 
|---|
| [526] | 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) | 
|---|
| [2047] | 235 | component: in case of multiple gaussians/lorentzians/sinusoidals, | 
|---|
|  | 236 | the index of the target component | 
|---|
| [1017] | 237 | """ | 
|---|
|  | 238 | component = None | 
|---|
|  | 239 | fixed = None | 
|---|
|  | 240 | params = None | 
|---|
| [1031] | 241 |  | 
|---|
| [1017] | 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] | 
|---|
| [515] | 248 | if self.fitfunc is None: | 
|---|
| [723] | 249 | msg = "Please specify a fitting function first." | 
|---|
| [1859] | 250 | raise RuntimeError(msg) | 
|---|
| [2666] | 251 | if (self.fitfunc == "gauss" or self.fitfunc == "lorentz" | 
|---|
|  | 252 | or self.fitfunc == "sinusoid") and component is not None: | 
|---|
| [1017] | 253 | if not self.fitted and sum(self.fitter.getparameters()) == 0: | 
|---|
| [1295] | 254 | pars = _n_bools(len(self.components)*3, False) | 
|---|
| [2047] | 255 | fxd  = _n_bools(len(pars), False) | 
|---|
| [515] | 256 | else: | 
|---|
| [723] | 257 | pars = list(self.fitter.getparameters()) | 
|---|
| [2047] | 258 | fxd  = list(self.fitter.getfixedparameters()) | 
|---|
| [515] | 259 | i = 3*component | 
|---|
|  | 260 | pars[i:i+3] = params | 
|---|
| [2047] | 261 | fxd[i:i+3]  = fixed | 
|---|
| [515] | 262 | params = pars | 
|---|
| [2047] | 263 | fixed  = fxd | 
|---|
| [113] | 264 | self.fitter.setparameters(params) | 
|---|
|  | 265 | if fixed is not None: | 
|---|
|  | 266 | self.fitter.setfixedparameters(fixed) | 
|---|
|  | 267 | return | 
|---|
| [515] | 268 |  | 
|---|
| [1862] | 269 | @asaplog_post_dec | 
|---|
| [1217] | 270 | def set_gauss_parameters(self, peak, centre, fwhm, | 
|---|
| [1409] | 271 | peakfixed=0, centrefixed=0, | 
|---|
| [1217] | 272 | fwhmfixed=0, | 
|---|
| [515] | 273 | component=0): | 
|---|
| [113] | 274 | """ | 
|---|
| [515] | 275 | Set the Parameters of a 'Gaussian' component, set with set_function. | 
|---|
|  | 276 | Parameters: | 
|---|
| [1232] | 277 | peak, centre, fwhm:  The gaussian parameters | 
|---|
| [515] | 278 | peakfixed, | 
|---|
| [1409] | 279 | centrefixed, | 
|---|
| [1217] | 280 | fwhmfixed:           Optional parameters to indicate if | 
|---|
| [515] | 281 | the paramters should be held fixed during | 
|---|
|  | 282 | the fitting process. The default is to keep | 
|---|
|  | 283 | all parameters flexible. | 
|---|
| [526] | 284 | component:           The number of the component (Default is the | 
|---|
|  | 285 | component 0) | 
|---|
| [515] | 286 | """ | 
|---|
|  | 287 | if self.fitfunc != "gauss": | 
|---|
| [723] | 288 | msg = "Function only operates on Gaussian components." | 
|---|
| [1859] | 289 | raise ValueError(msg) | 
|---|
| [515] | 290 | if 0 <= component < len(self.components): | 
|---|
| [1217] | 291 | d = {'params':[peak, centre, fwhm], | 
|---|
| [1409] | 292 | 'fixed':[peakfixed, centrefixed, fwhmfixed]} | 
|---|
| [1017] | 293 | self.set_parameters(d, component) | 
|---|
| [515] | 294 | else: | 
|---|
| [723] | 295 | msg = "Please select a valid  component." | 
|---|
| [1859] | 296 | raise ValueError(msg) | 
|---|
| [723] | 297 |  | 
|---|
| [1862] | 298 | @asaplog_post_dec | 
|---|
| [1819] | 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: | 
|---|
| [1927] | 306 | peak, centre, fwhm:  The lorentzian parameters | 
|---|
| [1819] | 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." | 
|---|
| [1859] | 318 | raise ValueError(msg) | 
|---|
| [1819] | 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." | 
|---|
| [1859] | 325 | raise ValueError(msg) | 
|---|
| [1819] | 326 |  | 
|---|
| [2047] | 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 |  | 
|---|
| [2666] | 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 | 
|---|
|  | 363 | needs a constraint | 
|---|
|  | 364 |  | 
|---|
|  | 365 | add_constraint([1, 0, 0, -2, 0, 0, 0], 0) | 
|---|
|  | 366 |  | 
|---|
|  | 367 | a velocity difference of v2-v1=17 | 
|---|
|  | 368 |  | 
|---|
|  | 369 | add_constraint([0.,-1.,0.,0.,1.,0.], 17.) | 
|---|
|  | 370 |  | 
|---|
|  | 371 | """ | 
|---|
|  | 372 | self._constraints.append((xpar, y)) | 
|---|
|  | 373 |  | 
|---|
|  | 374 |  | 
|---|
| [975] | 375 | def get_area(self, component=None): | 
|---|
|  | 376 | """ | 
|---|
| [1819] | 377 | Return the area under the fitted gaussian/lorentzian component. | 
|---|
| [975] | 378 | Parameters: | 
|---|
| [1819] | 379 | component:   the gaussian/lorentzian component selection, | 
|---|
| [975] | 380 | default (None) is the sum of all components | 
|---|
|  | 381 | Note: | 
|---|
| [1819] | 382 | This will only work for gaussian/lorentzian fits. | 
|---|
| [975] | 383 | """ | 
|---|
|  | 384 | if not self.fitted: return | 
|---|
| [1819] | 385 | if self.fitfunc == "gauss" or self.fitfunc == "lorentz": | 
|---|
| [975] | 386 | pars = list(self.fitter.getparameters()) | 
|---|
|  | 387 | from math import log,pi,sqrt | 
|---|
| [1819] | 388 | if self.fitfunc == "gauss": | 
|---|
|  | 389 | fac = sqrt(pi/log(16.0)) | 
|---|
|  | 390 | elif self.fitfunc == "lorentz": | 
|---|
|  | 391 | fac = pi/2.0 | 
|---|
| [975] | 392 | areas = [] | 
|---|
|  | 393 | for i in range(len(self.components)): | 
|---|
|  | 394 | j = i*3 | 
|---|
|  | 395 | cpars = pars[j:j+3] | 
|---|
|  | 396 | areas.append(fac * cpars[0] * cpars[2]) | 
|---|
|  | 397 | else: | 
|---|
|  | 398 | return None | 
|---|
|  | 399 | if component is not None: | 
|---|
|  | 400 | return areas[component] | 
|---|
|  | 401 | else: | 
|---|
|  | 402 | return sum(areas) | 
|---|
|  | 403 |  | 
|---|
| [1862] | 404 | @asaplog_post_dec | 
|---|
| [1075] | 405 | def get_errors(self, component=None): | 
|---|
| [515] | 406 | """ | 
|---|
| [1075] | 407 | Return the errors in the parameters. | 
|---|
|  | 408 | Parameters: | 
|---|
|  | 409 | component:    get the errors for the specified component | 
|---|
|  | 410 | only, default is all components | 
|---|
|  | 411 | """ | 
|---|
|  | 412 | if not self.fitted: | 
|---|
|  | 413 | msg = "Not yet fitted." | 
|---|
| [1859] | 414 | raise RuntimeError(msg) | 
|---|
| [1075] | 415 | errs = list(self.fitter.geterrors()) | 
|---|
|  | 416 | cerrs = errs | 
|---|
|  | 417 | if component is not None: | 
|---|
| [2666] | 418 | if self.fitfunc == "gauss" or self.fitfunc == "lorentz" \ | 
|---|
|  | 419 | or self.fitfunc == "sinusoid": | 
|---|
| [1075] | 420 | i = 3*component | 
|---|
|  | 421 | if i < len(errs): | 
|---|
|  | 422 | cerrs = errs[i:i+3] | 
|---|
|  | 423 | return cerrs | 
|---|
|  | 424 |  | 
|---|
| [1859] | 425 |  | 
|---|
| [1862] | 426 | @asaplog_post_dec | 
|---|
| [1075] | 427 | def get_parameters(self, component=None, errors=False): | 
|---|
|  | 428 | """ | 
|---|
| [113] | 429 | Return the fit paramters. | 
|---|
| [526] | 430 | Parameters: | 
|---|
|  | 431 | component:    get the parameters for the specified component | 
|---|
|  | 432 | only, default is all components | 
|---|
| [113] | 433 | """ | 
|---|
|  | 434 | if not self.fitted: | 
|---|
| [723] | 435 | msg = "Not yet fitted." | 
|---|
| [1859] | 436 | raise RuntimeError(msg) | 
|---|
| [113] | 437 | pars = list(self.fitter.getparameters()) | 
|---|
|  | 438 | fixed = list(self.fitter.getfixedparameters()) | 
|---|
| [1075] | 439 | errs = list(self.fitter.geterrors()) | 
|---|
| [1039] | 440 | area = [] | 
|---|
| [723] | 441 | if component is not None: | 
|---|
| [2047] | 442 | if self.fitfunc == "poly" or self.fitfunc == "lpoly": | 
|---|
|  | 443 | cpars = pars | 
|---|
|  | 444 | cfixed = fixed | 
|---|
|  | 445 | cerrs = errs | 
|---|
|  | 446 | else: | 
|---|
| [515] | 447 | i = 3*component | 
|---|
|  | 448 | cpars = pars[i:i+3] | 
|---|
|  | 449 | cfixed = fixed[i:i+3] | 
|---|
| [1075] | 450 | cerrs = errs[i:i+3] | 
|---|
| [2047] | 451 | if self.fitfunc == "gauss" or self.fitfunc == "lorentz": | 
|---|
|  | 452 | a = self.get_area(component) | 
|---|
|  | 453 | area = [a for i in range(3)] | 
|---|
| [515] | 454 | else: | 
|---|
|  | 455 | cpars = pars | 
|---|
|  | 456 | cfixed = fixed | 
|---|
| [1075] | 457 | cerrs = errs | 
|---|
| [1819] | 458 | if self.fitfunc == "gauss" or self.fitfunc == "lorentz": | 
|---|
| [1039] | 459 | for c in range(len(self.components)): | 
|---|
| [2047] | 460 | a = self.get_area(c) | 
|---|
|  | 461 | area += [a for i in range(3)] | 
|---|
| [1088] | 462 | fpars = self._format_pars(cpars, cfixed, errors and cerrs, area) | 
|---|
| [1859] | 463 | asaplog.push(fpars) | 
|---|
| [1075] | 464 | return {'params':cpars, 'fixed':cfixed, 'formatted': fpars, | 
|---|
|  | 465 | 'errors':cerrs} | 
|---|
| [723] | 466 |  | 
|---|
| [1075] | 467 | def _format_pars(self, pars, fixed, errors, area): | 
|---|
| [113] | 468 | out = '' | 
|---|
| [2047] | 469 | if self.fitfunc == "poly" or self.fitfunc == "lpoly": | 
|---|
| [113] | 470 | c = 0 | 
|---|
| [515] | 471 | for i in range(len(pars)): | 
|---|
|  | 472 | fix = "" | 
|---|
| [1232] | 473 | if len(fixed) and fixed[i]: fix = "(fixed)" | 
|---|
| [2047] | 474 | out += "  p%d%s= %3.6f" % (c, fix, pars[i]) | 
|---|
|  | 475 | if errors : out += " (%1.6f)" % errors[i] | 
|---|
|  | 476 | out += "," | 
|---|
| [113] | 477 | c+=1 | 
|---|
| [515] | 478 | out = out[:-1]  # remove trailing ',' | 
|---|
| [2047] | 479 | else: | 
|---|
| [113] | 480 | i = 0 | 
|---|
|  | 481 | c = 0 | 
|---|
| [2047] | 482 | if self.fitfunc == "gauss" or self.fitfunc == "lorentz": | 
|---|
|  | 483 | pnam = ["peak", "centre", "FWHM"] | 
|---|
|  | 484 | elif self.fitfunc == "sinusoid": | 
|---|
|  | 485 | pnam = ["amplitude", "period", "x0"] | 
|---|
|  | 486 | aunit = "" | 
|---|
|  | 487 | ounit = "" | 
|---|
| [113] | 488 | if self.data: | 
|---|
| [515] | 489 | aunit = self.data.get_unit() | 
|---|
|  | 490 | ounit = self.data.get_fluxunit() | 
|---|
| [113] | 491 | while i < len(pars): | 
|---|
| [2047] | 492 | fix0 = fix1 = fix2 = "" | 
|---|
|  | 493 | if i < len(fixed)-2: | 
|---|
|  | 494 | if fixed[i]:   fix0 = "(fixed)" | 
|---|
|  | 495 | if fixed[i+1]: fix1 = "(fixed)" | 
|---|
|  | 496 | if fixed[i+2]: fix2 = "(fixed)" | 
|---|
|  | 497 | out += "  %2d: " % c | 
|---|
|  | 498 | out += "%s%s = %3.3f %s, " % (pnam[0], fix0, pars[i],   ounit) | 
|---|
|  | 499 | out += "%s%s = %3.3f %s, " % (pnam[1], fix1, pars[i+1], aunit) | 
|---|
|  | 500 | out += "%s%s = %3.3f %s\n" % (pnam[2], fix2, pars[i+2], aunit) | 
|---|
| [2666] | 501 | if len(area): out += "      area = %3.3f %s %s\n" % (area[i], | 
|---|
|  | 502 | ounit, | 
|---|
|  | 503 | aunit) | 
|---|
| [113] | 504 | c+=1 | 
|---|
|  | 505 | i+=3 | 
|---|
|  | 506 | return out | 
|---|
| [723] | 507 |  | 
|---|
| [1859] | 508 |  | 
|---|
| [1862] | 509 | @asaplog_post_dec | 
|---|
| [113] | 510 | def get_estimate(self): | 
|---|
|  | 511 | """ | 
|---|
| [515] | 512 | Return the parameter estimates (for non-linear functions). | 
|---|
| [113] | 513 | """ | 
|---|
|  | 514 | pars = self.fitter.getestimate() | 
|---|
| [943] | 515 | fixed = self.fitter.getfixedparameters() | 
|---|
| [1927] | 516 | asaplog.push(self._format_pars(pars,fixed,None,None)) | 
|---|
| [113] | 517 | return pars | 
|---|
|  | 518 |  | 
|---|
| [1862] | 519 | @asaplog_post_dec | 
|---|
| [113] | 520 | def get_residual(self): | 
|---|
|  | 521 | """ | 
|---|
|  | 522 | Return the residual of the fit. | 
|---|
|  | 523 | """ | 
|---|
|  | 524 | if not self.fitted: | 
|---|
| [723] | 525 | msg = "Not yet fitted." | 
|---|
| [1859] | 526 | raise RuntimeError(msg) | 
|---|
| [113] | 527 | return self.fitter.getresidual() | 
|---|
|  | 528 |  | 
|---|
| [1862] | 529 | @asaplog_post_dec | 
|---|
| [113] | 530 | def get_chi2(self): | 
|---|
|  | 531 | """ | 
|---|
|  | 532 | Return chi^2. | 
|---|
|  | 533 | """ | 
|---|
|  | 534 | if not self.fitted: | 
|---|
| [723] | 535 | msg = "Not yet fitted." | 
|---|
| [1859] | 536 | raise RuntimeError(msg) | 
|---|
| [113] | 537 | ch2 = self.fitter.getchi2() | 
|---|
| [1859] | 538 | asaplog.push( 'Chi^2 = %3.3f' % (ch2) ) | 
|---|
| [723] | 539 | return ch2 | 
|---|
| [113] | 540 |  | 
|---|
| [1862] | 541 | @asaplog_post_dec | 
|---|
| [113] | 542 | def get_fit(self): | 
|---|
|  | 543 | """ | 
|---|
|  | 544 | Return the fitted ordinate values. | 
|---|
|  | 545 | """ | 
|---|
|  | 546 | if not self.fitted: | 
|---|
| [723] | 547 | msg = "Not yet fitted." | 
|---|
| [1859] | 548 | raise RuntimeError(msg) | 
|---|
| [113] | 549 | return self.fitter.getfit() | 
|---|
|  | 550 |  | 
|---|
| [1862] | 551 | @asaplog_post_dec | 
|---|
| [113] | 552 | def commit(self): | 
|---|
|  | 553 | """ | 
|---|
| [526] | 554 | Return a new scan where the fits have been commited (subtracted) | 
|---|
| [113] | 555 | """ | 
|---|
|  | 556 | if not self.fitted: | 
|---|
| [723] | 557 | msg = "Not yet fitted." | 
|---|
| [1859] | 558 | raise RuntimeError(msg) | 
|---|
| [975] | 559 | from asap import scantable | 
|---|
|  | 560 | if not isinstance(self.data, scantable): | 
|---|
| [723] | 561 | msg = "Not a scantable" | 
|---|
| [1859] | 562 | raise TypeError(msg) | 
|---|
| [113] | 563 | scan = self.data.copy() | 
|---|
| [259] | 564 | scan._setspectrum(self.fitter.getresidual()) | 
|---|
| [1092] | 565 | return scan | 
|---|
| [113] | 566 |  | 
|---|
| [1862] | 567 | @asaplog_post_dec | 
|---|
| [1689] | 568 | def plot(self, residual=False, components=None, plotparms=False, | 
|---|
|  | 569 | filename=None): | 
|---|
| [113] | 570 | """ | 
|---|
|  | 571 | Plot the last fit. | 
|---|
|  | 572 | Parameters: | 
|---|
|  | 573 | residual:    an optional parameter indicating if the residual | 
|---|
|  | 574 | should be plotted (default 'False') | 
|---|
| [526] | 575 | components:  a list of components to plot, e.g [0,1], | 
|---|
|  | 576 | -1 plots the total fit. Default is to only | 
|---|
|  | 577 | plot the total fit. | 
|---|
|  | 578 | plotparms:   Inidicates if the parameter values should be present | 
|---|
|  | 579 | on the plot | 
|---|
| [113] | 580 | """ | 
|---|
| [2538] | 581 | from matplotlib import rc as rcp | 
|---|
| [113] | 582 | if not self.fitted: | 
|---|
|  | 583 | return | 
|---|
| [2541] | 584 | #if not self._p or self._p.is_dead: | 
|---|
|  | 585 | if not (self._p and self._p._alive()): | 
|---|
| [2150] | 586 | from asap.asapplotter import new_asaplot | 
|---|
| [2451] | 587 | del self._p | 
|---|
| [2150] | 588 | self._p = new_asaplot(rcParams['plotter.gui']) | 
|---|
| [723] | 589 | self._p.hold() | 
|---|
| [113] | 590 | self._p.clear() | 
|---|
| [2535] | 591 | rcp('lines', linewidth=1) | 
|---|
| [515] | 592 | self._p.set_panels() | 
|---|
| [652] | 593 | self._p.palette(0) | 
|---|
| [113] | 594 | tlab = 'Spectrum' | 
|---|
| [723] | 595 | xlab = 'Abcissa' | 
|---|
| [1017] | 596 | ylab = 'Ordinate' | 
|---|
| [1739] | 597 | from numpy import ma,logical_not,logical_and,array | 
|---|
| [1273] | 598 | m = self.mask | 
|---|
| [113] | 599 | if self.data: | 
|---|
| [515] | 600 | tlab = self.data._getsourcename(self._fittedrow) | 
|---|
|  | 601 | xlab = self.data._getabcissalabel(self._fittedrow) | 
|---|
| [2153] | 602 | if self.data._getflagrow(self._fittedrow): | 
|---|
|  | 603 | m = [False] | 
|---|
|  | 604 | else: | 
|---|
|  | 605 | m =  logical_and(self.mask, | 
|---|
|  | 606 | array(self.data._getmask(self._fittedrow), | 
|---|
|  | 607 | copy=False)) | 
|---|
| [1589] | 608 |  | 
|---|
| [626] | 609 | ylab = self.data._get_ordinate_label() | 
|---|
| [515] | 610 |  | 
|---|
| [2666] | 611 | colours = ["#777777","#dddddd","red","orange","purple","green", | 
|---|
|  | 612 | "magenta", "cyan"] | 
|---|
| [1819] | 613 | nomask=True | 
|---|
|  | 614 | for i in range(len(m)): | 
|---|
|  | 615 | nomask = nomask and m[i] | 
|---|
| [2153] | 616 | if len(m) == 1: | 
|---|
|  | 617 | m = m[0] | 
|---|
|  | 618 | invm = (not m) | 
|---|
|  | 619 | else: | 
|---|
|  | 620 | invm = logical_not(m) | 
|---|
| [1819] | 621 | label0='Masked Region' | 
|---|
|  | 622 | label1='Spectrum' | 
|---|
|  | 623 | if ( nomask ): | 
|---|
|  | 624 | label0=label1 | 
|---|
|  | 625 | else: | 
|---|
|  | 626 | y = ma.masked_array( self.y, mask = m ) | 
|---|
|  | 627 | self._p.palette(1,colours) | 
|---|
|  | 628 | self._p.set_line( label = label1 ) | 
|---|
|  | 629 | self._p.plot( self.x, y ) | 
|---|
| [652] | 630 | self._p.palette(0,colours) | 
|---|
| [1819] | 631 | self._p.set_line(label=label0) | 
|---|
| [2153] | 632 | y = ma.masked_array(self.y,mask=invm) | 
|---|
| [1088] | 633 | self._p.plot(self.x, y) | 
|---|
| [113] | 634 | if residual: | 
|---|
| [1819] | 635 | self._p.palette(7) | 
|---|
| [515] | 636 | self._p.set_line(label='Residual') | 
|---|
| [1116] | 637 | y = ma.masked_array(self.get_residual(), | 
|---|
| [2153] | 638 | mask=invm) | 
|---|
| [1088] | 639 | self._p.plot(self.x, y) | 
|---|
| [652] | 640 | self._p.palette(2) | 
|---|
| [515] | 641 | if components is not None: | 
|---|
|  | 642 | cs = components | 
|---|
|  | 643 | if isinstance(components,int): cs = [components] | 
|---|
| [526] | 644 | if plotparms: | 
|---|
| [2666] | 645 | self._p.text(0.15,0.15, | 
|---|
|  | 646 | str(self.get_parameters()['formatted']),size=8) | 
|---|
| [515] | 647 | n = len(self.components) | 
|---|
| [652] | 648 | self._p.palette(3) | 
|---|
| [515] | 649 | for c in cs: | 
|---|
|  | 650 | if 0 <= c < n: | 
|---|
|  | 651 | lab = self.fitfuncs[c]+str(c) | 
|---|
|  | 652 | self._p.set_line(label=lab) | 
|---|
| [2153] | 653 | y = ma.masked_array(self.fitter.evaluate(c), mask=invm) | 
|---|
| [1088] | 654 |  | 
|---|
|  | 655 | self._p.plot(self.x, y) | 
|---|
| [515] | 656 | elif c == -1: | 
|---|
| [652] | 657 | self._p.palette(2) | 
|---|
| [515] | 658 | self._p.set_line(label="Total Fit") | 
|---|
| [1116] | 659 | y = ma.masked_array(self.fitter.getfit(), | 
|---|
| [2153] | 660 | mask=invm) | 
|---|
| [1088] | 661 | self._p.plot(self.x, y) | 
|---|
| [515] | 662 | else: | 
|---|
| [652] | 663 | self._p.palette(2) | 
|---|
| [515] | 664 | self._p.set_line(label='Fit') | 
|---|
| [2153] | 665 | y = ma.masked_array(self.fitter.getfit(),mask=invm) | 
|---|
| [1088] | 666 | self._p.plot(self.x, y) | 
|---|
| [723] | 667 | xlim=[min(self.x),max(self.x)] | 
|---|
|  | 668 | self._p.axes.set_xlim(xlim) | 
|---|
| [113] | 669 | self._p.set_axes('xlabel',xlab) | 
|---|
|  | 670 | self._p.set_axes('ylabel',ylab) | 
|---|
|  | 671 | self._p.set_axes('title',tlab) | 
|---|
|  | 672 | self._p.release() | 
|---|
| [723] | 673 | if (not rcParams['plotter.gui']): | 
|---|
|  | 674 | self._p.save(filename) | 
|---|
| [113] | 675 |  | 
|---|
| [1862] | 676 | @asaplog_post_dec | 
|---|
| [1061] | 677 | def auto_fit(self, insitu=None, plot=False): | 
|---|
| [113] | 678 | """ | 
|---|
| [515] | 679 | Return a scan where the function is applied to all rows for | 
|---|
|  | 680 | all Beams/IFs/Pols. | 
|---|
| [723] | 681 |  | 
|---|
| [113] | 682 | """ | 
|---|
|  | 683 | from asap import scantable | 
|---|
| [515] | 684 | if not isinstance(self.data, scantable) : | 
|---|
| [723] | 685 | msg = "Data is not a scantable" | 
|---|
| [1859] | 686 | raise TypeError(msg) | 
|---|
| [259] | 687 | if insitu is None: insitu = rcParams['insitu'] | 
|---|
|  | 688 | if not insitu: | 
|---|
|  | 689 | scan = self.data.copy() | 
|---|
|  | 690 | else: | 
|---|
|  | 691 | scan = self.data | 
|---|
| [880] | 692 | rows = xrange(scan.nrow()) | 
|---|
| [1826] | 693 | # Save parameters of baseline fits as a class attribute. | 
|---|
| [1819] | 694 | # NOTICE: This does not reflect changes in scantable! | 
|---|
|  | 695 | if len(rows) > 0: self.blpars=[] | 
|---|
| [876] | 696 | asaplog.push("Fitting:") | 
|---|
|  | 697 | for r in rows: | 
|---|
| [2666] | 698 | out = " Scan[%d] Beam[%d] IF[%d] Pol[%d] Cycle[%d]" % ( | 
|---|
|  | 699 | scan.getscan(r), | 
|---|
|  | 700 | scan.getbeam(r), | 
|---|
|  | 701 | scan.getif(r), | 
|---|
|  | 702 | scan.getpol(r), | 
|---|
|  | 703 | scan.getcycle(r) | 
|---|
|  | 704 | ) | 
|---|
| [880] | 705 | asaplog.push(out, False) | 
|---|
| [876] | 706 | self.x = scan._getabcissa(r) | 
|---|
|  | 707 | self.y = scan._getspectrum(r) | 
|---|
| [2409] | 708 | #self.mask = mask_and(self.mask, scan._getmask(r)) | 
|---|
| [2408] | 709 | if len(self.x) == len(self.mask): | 
|---|
|  | 710 | self.mask = mask_and(self.mask, self.data._getmask(row)) | 
|---|
|  | 711 | else: | 
|---|
| [2666] | 712 | asaplog.push('lengths of data and mask are not the same. ' | 
|---|
|  | 713 | 'preset mask will be ignored') | 
|---|
| [2408] | 714 | asaplog.post('WARN','asapfit.fit') | 
|---|
| [2409] | 715 | self.mask=self.data._getmask(row) | 
|---|
| [876] | 716 | self.data = None | 
|---|
|  | 717 | self.fit() | 
|---|
|  | 718 | x = self.get_parameters() | 
|---|
| [1819] | 719 | fpar = self.get_parameters() | 
|---|
| [1061] | 720 | if plot: | 
|---|
|  | 721 | self.plot(residual=True) | 
|---|
|  | 722 | x = raw_input("Accept fit ([y]/n): ") | 
|---|
|  | 723 | if x.upper() == 'N': | 
|---|
| [1819] | 724 | self.blpars.append(None) | 
|---|
| [1061] | 725 | continue | 
|---|
| [880] | 726 | scan._setspectrum(self.fitter.getresidual(), r) | 
|---|
| [1819] | 727 | self.blpars.append(fpar) | 
|---|
| [1061] | 728 | if plot: | 
|---|
| [2151] | 729 | self._p.quit() | 
|---|
|  | 730 | del self._p | 
|---|
| [1061] | 731 | self._p = None | 
|---|
| [876] | 732 | return scan | 
|---|