Coverage for /wheeldirectory/casa-6.7.0-12-py3.10.el8/lib/py/lib/python3.10/site-packages/casatasks/specfit.py: 56%

27 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-10-31 17:39 +0000

1##################### generated by xml-casa (v2) from specfit.xml ################### 

2##################### a81d50501849096b05583002a039cc1e ############################## 

3from __future__ import absolute_import 

4import numpy 

5from casatools.typecheck import CasaValidator as _val_ctor 

6_pc = _val_ctor( ) 

7from casatools.coercetype import coerce as _coerce 

8from casatools.errors import create_error_string 

9from .private.task_specfit import specfit as _specfit_t 

10from casatasks.private.task_logging import start_log as _start_log 

11from casatasks.private.task_logging import end_log as _end_log 

12from casatasks.private.task_logging import except_log as _except_log 

13 

14class _specfit: 

15 """ 

16 specfit ---- Fit 1-dimensional gaussians and/or polynomial models to an image or image region 

17 

18 --------- parameter descriptions --------------------------------------------- 

19 

20 imagename Name of the input image 

21 box Rectangular region to select in direction plane. Default is to use the entire direction plane. 

22 region Region selection. Default is to use the full image. 

23 chans Channels to use. Default is to use all channels. 

24 stokes Stokes planes to use. Default is to use all Stokes planes. 

25 axis The profile axis. Default: use the spectral axis if one exists, axis 0 otherwise (<0). 

26 mask Mask to use. Default is none.. 

27 ngauss Number of Gaussian elements. Default: 1. 

28 poly Order of polynomial element. Default: do not fit a polynomial (<0). 

29 estimates Name of file containing initial estimates. Default: No initial estimates (""). 

30 minpts Minimum number of unmasked points necessary to attempt fit. 

31 multifit If true, fit a profile along the desired axis at each pixel in the specified region. If false, average the non-fit axis pixels and do a single fit to that average profile. Default False. 

32 model Name of model image. Default: do not write the model image (""). 

33 residual Name of residual image. Default: do not write the residual image (""). 

34 amp Name of amplitude solution image. Default: do not write the image (""). 

35 amperr Name of amplitude solution error image. Default: do not write the image (""). 

36 center Name of center solution image. Default: do not write the image (""). 

37 centererr Name of center solution error image. Default: do not write the image (""). 

38 fwhm Name of fwhm solution image. Default: do not write the image (""). 

39 fwhmerr Name of fwhm solution error image. Default: do not write the image (""). 

40 integral Prefix of ame of integral solution image. Name of image will have gaussian component number appended. Default: do not write the image (""). 

41 integralerr Prefix of name of integral error solution image. Name of image will have gaussian component number appended. Default: do not write the image (""). 

42 wantreturn Should a record summarizing the results be returned? 

43 stretch Stretch the mask if necessary and possible? 

44 logresults Output results to logger? 

45 pampest Initial estimate of PCF profile (gaussian or lorentzian) amplitudes. 

46 pcenterest Initial estimate PCF profile centers, in pixels. 

47 pfwhmest Initial estimate PCF profile FWHMs, in pixels. 

48 pfix PCF profile parameters to fix during fit. 

49 gmncomps Number of components in each gaussian multiplet to fit 

50 gmampcon The amplitude ratio constraints for non-reference components to reference component in gaussian multiplets. 

51 gmcentercon The center offset constraints (in pixels) for non-reference components to reference component in gaussian multiplets. 

52 gmfwhmcon The FWHM ratio constraints for non-reference components to reference component in gaussian multiplets. 

53 gmampest Initial estimate of individual gaussian amplitudes in gaussian multiplets. 

54 gmcenterest Initial estimate of individual gaussian centers in gaussian multiplets, in pixels. 

55 gmfwhmest Initial estimate of individual gaussian FWHMss in gaussian multiplets, in pixels. 

56 gmfix Parameters of individual gaussians in gaussian multiplets to fix during fit. 

57 logfile File in which to log results. Default is not to write a logfile. 

58 append Append results to logfile? Logfile must be specified. Default is to append. False means overwrite existing file if it exists. 

59 pfunc PCF singlet functions to fit. "gaussian" or "lorentzian" (minimal match supported). Unspecified means all gaussians. 

60 goodamprange Acceptable amplitude solution range. [0.0] => all amplitude solutions are acceptable. 

61 goodcenterrange Acceptable center solution range in pixels relative to region start. [0.0] => all center solutions are acceptable. 

62 goodfwhmrange Acceptable FWHM solution range in pixels. [0.0] => all FWHM solutions are acceptable. 

63 sigma Standard deviation array or image name. 

64 outsigma Name of output image used for standard deviation. Ignored if sigma is empty. 

65 RETURNS record 

66 

67 --------- examples ----------------------------------------------------------- 

68 

69  

70  

71 This task simultaneously fits one or more gaussian singlets lorentzian singlets, gaussian multiplets, and/or a polynomial to one dimensional profiles. 

72  

73 PARAMETER SUMMARY 

74 imagename Name of the input (CASA, FITS, MIRIAD) image 

75 box Rectangular region to select in direction plane. 

76 for details. Default is to use the entire direction plane. 

77 region Region selection. Default is to use the 

78 full image. 

79 chans Channels to use. Default is to use 

80 all channels. 

81 stokes Stokes planes to use. Default is 

82 to use all Stokes planes. 

83 axis Axis along which to do the fit(s). <0 means use the spectral axis or the 

84 zeroth axis if a spectral axis is not present. 

85 mask Mask to use. Default is none. 

86 stretch Stretch the input mask if necessary and possible? Only used if a mask is specified. 

87  

88 ngauss Maximum number of gaussians to fit. 

89 poly Order of polynomial to fit. <0 means do not fit a polynomial. 

90 estimates Name of file containing initial gaussian estimates. 

91 minpts Minimum number of points necessary to attempt a fit. 

92 multifit Fit models at each pixel in region (true) or average profiles and fit a single model (false). 

93 model Name of model image to write. 

94 residual Name of residual image to write. 

95 amp Name of amplitude solution image. Default: do not write the image ("") 

96 amperr Name of amplitude solution error image. Default: do not write the image ("") 

97 center Name of center solution image. Default: do not write the image ("") 

98 centererr Name of center solution error image. Default: do not write the image ("") 

99 fwhm Name of fwhm solution image. Default: do not write the image ("") 

100 fwhmerr Name of fwhm solution error image. Default: do not write the image ("") 

101 integral Name of integral solution image. Default: do not write the image ("") 

102 integralerr Name of integral solution error image. Default: do not write the image ("") 

103 wantreturn If true, return a record summarizing the fit results, if false, return false. 

104 stretch Stretch the mask if necessary and possible? 

105 logresults Output results to logger? 

106 pampest Initial estimate of PCF profile (gaussian or lorentzian) amplitudes. 

107 pcenterest Initial estimate PCF profile centers, in pixels. 

108 pfwhmest Initial estimate PCF profile FWHMs, in pixels. 

109 pfix PCF profile parameters to fix during fit. 

110 pfunc PCF singlet functions to fit. "gaussian" or "lorentzian" (minimal match supported). Unspecified means all gaussians. 

111 gmncomps Number of components in each Gaussian multiplet to fit. 

112 gmampcon The amplitude ratio constraints for non-reference components to reference component in gaussian multiplets. 

113 gmcentercon The center offset constraints (in pixels) for non-reference components to reference component in gaussian multiplets. 

114 gmfwhmcon The FWHM ratio constraints for non-reference components to reference component in gaussian multiplets. 

115 gmampest Initial estimate of individual gaussian amplitudes in gaussian multiplets. 

116 gmcenterest Initial estimate of individual gaussian centers in gaussian multiplets, in pixels. 

117 gmfwhmest Initial estimate of individual gaussian FWHMss in gaussian multiplets, in pixels. 

118 gmfix Parameters of individual gaussians in gaussian multiplets to fix during fit. 

119 logfile File in which to log results. Default is not to write a logfile. 

120 append Append results to logfile? Logfile must be specified. Default is to append. False means overwrite existing file if it exists. 

121 goodamprange Acceptable amplitude solution range. 0 => all amplitude solutions are acceptable. [0.0] => All amplitude solutions are acceptable. 

122 goodcenterrange Acceptable center solution range in pixels relative to region start. [0.0] => all center solutions are acceptable. 

123 goodfwhmrange Acceptable FWHM solution range in pixels. [0.0] => all FWHM solutions are acceptable. 

124 sigma Standard deviation array or image name. 

125 outsigma Name of output image used for standard deviation. Ignored if sigma is empty. 

126  

127 This task simultaneously performs a non-linear, least squares fit using the Levenberg-Marquardt algorithm of one or more gaussian singlets, 

128 one or more lorentzian singlets, one or more gaussian multiplets, and/or a polynomial to one dimensional profiles. A description of the 

129 fitting algorithm may be found in AIPS++ Note 224 (http://www.astron.nl/casacore/trunk/casacore/doc/notes/224.html) and in Numerical Recipes 

130 by W.H. Press et al., Cambridge University Press. A gaussian/lorentzian singlet is a gaussian/lorentzian whose parameters (amplitude, 

131 center position, and width) are all independent from any other feature that may be simultaneously fit. A gaussian multiplet is a set of two or 

132 more gaussian lines in which at least one (and possibly two or three) parameter of each line is dependent on the parameter of another, 

133 single (reference) profile in the multiplet. For example, one can specify a doublet in which the amplitude of the first line is 0.6 times the 

134 amplitude of the zeroth line and/or the center of the first line is 20 pixels from the center of the zeroth line, and/or the fwhm of the first 

135 line is identical (in pixels) to that of the zeroth line. There is no limit to the number of components one can specify in a multiplet 

136 (except of course that the number of parameters to be fit should be significantly less than the number of data points), but there can be only 

137 a single reference profile in a multiplet to which to tie constraints of parameters of the other profiles in the set. 

138  

139 AXIS 

140 The axis parameter indicates on which axis profiles should be fit; a value <0 indicates the spectral axis should be used, or if one does not exist, 

141 that the zeroth axis should be used. 

142  

143 MINIMUM NUMBER OF PIXELS 

144 The minpts parameter indicates the minimum number of unmasked pixels that must be present in order for a fit 

145 to be attempted. When multifit=T, positions with too few good points will be masked in any output images. 

146  

147 ONE FIT OF REGION AVERAGE OR PIXEL BY PIXEL FIT 

148 The multifit parameter indicates if profiles should be fit at each pixel in the selected region (true), or if the profiles in that region should be 

149 averaged and the fit done to that average profile (false). 

150  

151 POLYNOMIAL FITTING 

152 The order of the polynomial to fit is specified only via the poly parameter. If poly<0, no polynomial will be fit. No initial estimates of 

153 coefficients can be specified; these are determined automatically. 

154  

155 GAUSSIAN SINGLET FITTING 

156 In the absence of an estimates file and no estimates being specified by the p*est parameters, and gmncomps=0 or is empty, the ngauss parameter 

157 indicates the maximum number of gaussian singlets that should be fit. The initial estimates of the parameters for these gaussians will be attempted 

158 automatically in this case. If it deems appropriate, the fitter will fit fewer than this number. In the case where an estimates file is supplied, 

159 ngauss is ignored (see below). ngauss is also ignored if the p*est parameters are specified or if gmncomps is not an empty array or, if an integer, 

160 is greater than zero. If estimates is not specified or the p*est parameters are not specified and ngauss=0, gmncomps is empty or 0, and poly<0, 

161 an error will occur as this indicates there is nothing to fit. 

162  

163 One can specify initial estimates of gaussian singlet parameters via an estimates file or the pampest, pcenterest, pfwhmest, and optionally, the 

164 pfix parameters. The latter is the recommended way to specify these estimates as support for estimates files may be deprecated in the future. No matter 

165 which option is used, an amplitude initial estimate must always be nonzero. A negative fwhm estimate will be silently changed to positve. 

166  

167 SPECIFYING INITIAL ESTIMATES FOR GAUSSIAN AND LORENTZIAN SINGLETS (RECOMMENDED METHOD) 

168 One may specify initial estimates via the pampest, pcenterest, and pfwhmest parameters. In the case of a single gaussian or lorentzian singlet, 

169 these parameters can be numbers. pampest must be specified in image brightness units, pcenterest must be given in the number of pixels from the 

170 zeroth pixel, and pfwhmest must be given in pixels. Optionally pfix can be specified and in the case of a single gaussian or lorentzian singlet 

171 can be a string. In it is coded which parameters should be held constant during the fix. Any combination of "p" (amplitude), "c" (center), or "f" 

172 (fwhm) is allowed; eg pfix="pc" means fix both the amplitude and center during the fit. In the case of more than one gaussian and/or lorentzian 

173 singlets, these parameters must be specified as arrays of numbers. The length of the arrays indicates the number of singlets to fit and must be 

174 the same for all the p*est parameters. 

175  

176 If no parameters are to be fixed for any of the singlets, pfix can be set to the empty string. However, if at least one parameter of one singlet 

177 is to be fixed, pfix must be an array of strings and have a length equal to the p*est arrays. Singlets which are not to have any parameters fixed 

178 should be represented as an empty string in the pfix array. So, for example, if one desires to fit three singlets and fix the fwhm of the middle 

179 one, one must specify pfix=["", "f", ""], the empty strings indicating no parameters of the zeroth and second singlet should be held constant. 

180  

181 In the case of multifit=True, the initial estimates, whether from the p*est parameters or from a file (see below), will be applied to the location 

182 of the first fit. This is normally the bottom left corner of the region selected. If masked, not enough good points to perform a fit, or the 

183 attempted fit fails, the fitting proceeds to the next pixel with the pixel value of the lowest numbered axis changing the fastest. Once a 

184 successful fit has been performed, subsequent fits will use the results of a fit for a nearest pixel for which a previous fit was successful as the 

185 initial estimate for the parameters at the current location. The fixed parameter string will be honored for every fit performed when multifit=True. 

186  

187 One specifies what type of PCF profile to fit via the pfunc parameter. A PCF function is one that can be parameterized by a peak, center, and FWHM, 

188 as both gaussian and lorentzian singlets can. If all singlets to be fit are gaussians, one can set pfunc equal to the empty string and all snglets 

189 will be assumed to be gaussians. If at least one lorentzian is to be fit, pfunc must be specified as a string (in the case of a single singlet) or 

190 an array of strings (in the case of multiple singlets). The position of each string corresponds to the positions of the initial estimates in the 

191 p*est and pfix arrays. Minimal match ("g", "G", "l", or "L") is supported. So, if one wanted to simultaneously fit two gaussian and two lorentzian 

192 singlets, the zeroth and last of which were lorentzians, one would specify pfunc=["L", "G", "G", "L"]. 

193  

194 ESTIMATES FILE FOR GAUSSIAN SINGLETS (NONRECOMMENDED METHOD) 

195 Initial estimates for gaussian singlets can be specified in an estimates file. Estimates files may be deprecated in the future in favor of the 

196 p*est parameters, so it is recommended users use those parameters instead. If an estimates file is desired to be used, the p*est parameters 

197 must be 0 or empty and mgncomps must be 0 or empty. Only gaussian singlets can be specified in an estimates file. If one desires to fit one or 

198 more gaussian multiplets and/or one or more lorentzian singlets simultaneously, the p*est parameters must be used to specify the initial parameters 

199 of all gaussian singlets to fit; one cannot use an estimates file in this case. If an estimates file is specified, a polynomial 

200 can be fit simultaneously by specifying the poly parameter. The estimates file must contain initial estimates of parameters 

201 for all gaussian singlets to be fit. The number of gaussian singlets to fit is gotten from the number of estimates in the file. The file can contain 

202 comments which are indicated by a "#" at the beginning of a line. All non-comment lines will be interpreted as initial estimates. The 

203 format of such a line is 

204  

205 [peak intensity], [center], [fwhm], [optional fixed parameter string] 

206  

207 The first three values are required and must be numerical values. The peak intensity must be expressed in image brightness units, while the 

208 center must be specified in pixels offset from the zeroth pixel, and fwhm must be specified in pixels. The fourth value is optional and if present, 

209 represents the parameter(s) that should be held constant during the fit. Any combination of the characters 'p' (peak), 'c' (center), and 'f' (fwhm) are 

210 permitted, eg "fc" means hold the fwhm and the center constant during the fit. Fixed parameters will have no error associated with them. Here is an 

211 example file: 

212  

213 # estimates file indicating that two gaussians should be fit 

214 # first guassian estimate, peak=40, center at pixel number 10.5, fwhm = 5.8 pixels, all parameters allowed to vary during 

215 # fit 

216 40, 10.5, 5.8 

217 # second gaussian, peak = 4, center at pixel number 90.2, fwhm = 7.2 pixels, hold fwhm constant 

218 4, 90.2, 7.2, f 

219 # end file 

220  

221 GAUSSIAN MULTIPLET FITTING 

222 Any number of gaussian multiplets, each containing any number of two or more components, can be simultaneously fit, optionally with a 

223 polynomial and/or any number of gaussian and/or lorentzian singlets, the only caveat being that the number of parameters to be fit should be 

224 significantly less than the number of data points. The gmncomps parameter indicates the number of multiplets to fit and the number of 

225 components in each multiplet. In the case of a single multiplet, an integer (>1) can be specified. For example, mgncomps=4 means fit a 

226 single quadruplet of gaussians. In the case of 2 or more multiplets, and array of integers (all >1) must be specified. For example, 

227 gmncomps=[2, 4, 3] means 3 seperate multiples are to be fit, the zeroth being a doublet, the first being a quadruplet, and the second 

228 being a triplet. 

229  

230 Initial estimates of all gaussians in all multiplets are specified via the gm*est parameters which must be arrays of numbers. The order 

231 starts with the zeroth component of the zeroth multiplet to the last component of the zeroth multiplet, then the zeroth component of 

232 the first multiplet to the last compoenent of the first multiplet, etc to the zeroth component of the last multiplet to the last 

233 element of the last multiplet. The zeroth element of a multiplet is defined as the reference component of that multiplet and has the special 

234 significance that it is the profile to which all constraints of all other profiles in that multiplet are referenced (see below). So, 

235 in our example of gmncomps=[2, 4, 3], gmampest, gmcenterest, and gmfwhmest must each be nine (the total number of individual gaussian 

236 profiles summed over all multiplets) element arrays. The zeroth, second, and sixth elements represent parameters of the reference profiles 

237 in the zeroth, first, and second multiplet, respectively. 

238  

239 The fixed relationships between the non-reference profile(s) and the reference profile of a multiplet are specified via the gmampcon, 

240 gmcentercon, and gmfwhmcon parameters. At least one, and any combination, of constraints can be specified for any non-reference 

241 component of a multiplet. The amplitude ratio of a non-reference line to that of the reference line is set in gmampcon. The ratio of 

242 the fwhm of a non-reference line to that of the reference line is set in gmfwhmcon. The offset in pixels of the center position of 

243 a non-reference line to that of the reference line is set in gmcentercon. In the case where a parameter is not constrained for any 

244 non-reference line of any multiplet, the value of the associated parameter must be 0. In the case of 

245 a single doublet, a constraint may be specified as a number or an array of a single number. For example, mgncomps=2 and gmampcon=0.65 

246 and gmcentercon=[32.4] means there is a single doublet to fit where the amplitude ratio of the first to the zeroth line is constained 

247 to be 0.65 and the center of the first line is constrained to be offset by 32.4 pixels from the center of the zeroth line. In cases 

248 of a total of three or more gaussians, the constraints parameters must be specified as arrays with lengths equal to the total number 

249 of gaussians summed over all multiplets minus the number of reference lines (one per multiplet, or just number of multiplets, since 

250 reference lines cannot be constrained by themselves). In the cases where an array must be specified but a component in that array 

251 does not have that constraint, 0 should be specified. Here's an example 

252  

253 gmncomps=[2, 4, 3] 

254 gmampcon= [ 0 , 0.2, 0 , 0.1, 4.5, 0 ] 

255 gcentercon=[24.2, 45.6, 92.7, 0 , -22.8, -33.5] 

256 gfwhmcon="" 

257  

258 In this case we have our previous example of one doublet, one quadruplet, and one triplet. The first component of the doublet has the constraint 

259 that its center is offset by 24.2 pixels from the zeroth (reference) component. The first component of the quadruplet is constrained to have 

260 an amplitude of 0.2 times that of the quadruplet's zeroth component and its center is constrained to be offset by 45.6 pixels from the 

261 reference component. The second component of the quadruplet is constained to have its center offset by 92.7 pixels from the associated 

262 reference component and the third component is constrained to have an amplitude of 0.1 times that of the associated reference component. 

263 The first component of the triplet is constrained to have an amplitude of 4.5 times that of its associated reference component and its center 

264 is constrained to be offset by -22.8 pixels from the reference component's center. The second component of the triplet is constrained to have 

265 its center offset by -33.5 pixels from the center of the reference component. No lines have FWHM constraints, so the empty string can be given 

266 for that parameter. Note that using 0 to indicate no constraint for line center means that one cannot specify a line centered at the same 

267 position as the reference component but having a different FWHM from the reference component. If you must specify this very unusual case, 

268 try using a very small positive (or even negative) value for the center constraint. 

269  

270 Note that when a parameter for a line is constrained, the corresponding value for that component in the corresponding gm*est array is 

271 ignored and the value of the constrained parameter is automatically used instead. So let's say, for our example above, we had specified 

272 the following estimates: 

273  

274 gmampest = [ 1, .2, 2, .1, .1, .5, 3, 2, 5] 

275 gmcenterest = [20, 10 , 30, 45.2, 609 , -233, 30, -859, 1] 

276  

277 Before any fitting is done, the constraints would be taken into account and these arrays would be implicitly rewritten as: 

278  

279 gmampest = [ 1, .2, 2, .4, .1, .2, 3, 13.5, 5 ] 

280 gmcenterest = [20, 44.2, 30, 75.6, 127.7, -233, 30, 7.2, -3.5] 

281  

282 The value of gmfwhmest would be unchanged since there are no FWHM constraints in this example. 

283  

284 In addition to be constrained by values of the reference component, parameters of individual components can be fixed. Fixed parameters 

285 are specified via the gmfix parameter. If no parameters are to be fixed, gmfix can be specified as the empty string or a zero element 

286 array. In the case where any parameter is to be fixed, gmfix must be specified as an array of strings with length equal to the total number of 

287 components summed over all multiplets. These strings encode which parameters to be fixed for the corresponding components. If 

288 a component is to have no parameters fixed, an empty string is used. In other cases one or more of any combination of parameters can 

289 be fixed using "p", "c", and/or "f" described above for fixing singlet parameters. There are a couople of special cases 

290 to be aware of. In the case where a non-reference component parameter is constrained and the corresponding reference component parameter is 

291 set as fixed, that parameter in the non-reference parameter will automatically be fixed even if it was specified not to be fixed in 

292 the gmfix array. This is the only way the constraint can be honored afterall. In the converse case of when a constrained parameter of a 

293 non-reference component is specified as fixed, but the corresponding parameter in the reference component is not specified to be fixed, 

294 an error will occur. Fixing an unconstrained parameter in a non-reference component is always legal as is fixing any combination of 

295 parameters in a reference component (with the above caveat that corresponding constrained parameters in non-reference components will 

296 be silently held fixed as well). 

297  

298 The same rules that apply to singlets when multifit=True apply to multiplets. 

299  

300 LIMITING RANGES FOR SOLUTION PARAMETERS 

301 In cases of low (or no) signal to noise spectra, it is still possible for the fit to converge, but often to a 

302 nonsensical solution. The astronomer can use her knowledge of the source to filter out obviously bogus solutions. 

303 Any solution which contains a NaN value as a value or error in any one of its parameters is automatically marked as 

304 invalid. 

305  

306 One can also limit the ranges of solution parameters to known "good" values via the goodamprange, goodcenterrange, and goodfwhmrange 

307 parameters. Any combination can be specified and the limit constraints will be ANDed together. The ranges apply to all PCF components 

308 that might be fit; choosing ranges on a component by component basis is not supported. If specified, 

309 an array of exactly two numerical values must be given to indicate the range of acceptable solution values for 

310 that parameter. goodamprange is expressed in terms of image brightness units. goodcenterrange is expressed in terms of pixels 

311 from the zeroth pixel in the specified region. goodfwhmrange is expressed in terms of pixels (only non-negative values should be 

312 given for FWHM range endpoints). In the case of a multiple-PCF fit, if any of the corresponding solutions are outside the specified 

313 ranges, the entire solution is considered to be invalid. 

314  

315 In addition, solutions for which the absolute value of the ratio of the amplitude error to the amplitude exceeds 100 or the 

316 ratio of the FWHM error to the FWHM exceeds 100 are automatically marked as invalid. 

317  

318 INCLUDING STANDARD DEVIATIONS OF PIXEL VALUES 

319 If the standard deviations of the pixel values in the input image are known and they vary in the image (eg they are higher for pixels 

320 near the edge of the band), they can be included in the sigma parameter. This parameter takes either an array or an image name. The 

321 array or image must have one of three shapes: 1. the shape of the input image, 2. the same dimensions as the input image with the lengths 

322 of all axes being one except for the fit axis which must have length corresponding to its length in the input image, or 3. be one 

323 dimensional with lenght equal the the length of the fit axis in the input image. In cases 2 and 3, the array or pixels in sigma will 

324 be replicated such that the image that is ultimately used is the same shape as the input image. The values of sigma must be non-negative. 

325 It is only the relative values that are important. A value of 0 means that pixel should not be used in the fit. Other than that, if pixel 

326 A has a higher standard deviation than pixel B, then pixel A is noisier than pixel B and will receive a lower weight when the fit is done. 

327 The weight of a pixel is the usual 

328  

329 weight = 1/(sigma*sigma) 

330  

331 In the case of multifit=F, the sigma values at each pixel along the fit axis in the hyperplane perpendicular to the fit axis which includes 

332 that pixel are averaged and the resultant averaged standard deviation spectrum is the one used in the fit. Internally, sigma values are normalized 

333 such that the maximum value is 1. This mitigates a known overflow issue. 

334  

335 One can write the normalized standard deviation image used in the fit but specifying its name in outsigma. This image can then be 

336 used as sigma for subsequent runs. 

337  

338 RETURNED DICTIONARY STRUCTURE 

339 The dictionary returned (if wantreturn=True) has a (necessarily) complex structure. First, there are keys "xUnit" and "yUnit" whose values are 

340 the abscissa unit and the ordinate unit described by simple strings. Next there are arrays giving a broad overview of the 

341 fit quality. These arrays have the shape of the specified region collapsed along the fit axis with the axis corresponding to the fit 

342 axis having length of 1: 

343  

344 attempted: a boolean array indicating which fits were attempted (eg if too few unmasked points, a fit will not be attempted). 

345 converged: a boolean array indicating which fits converged. False if the fit was not attempted. 

346 valid: a boolean array indicating which solutions fall within the specified valid ranges of parameter space (see 

347 section LIMITING RANGES FOR SOLUTION PARAMETERS for details). 

348 niter: an int array indicating the number of iterations for each profile, <0 if the fit did not converge 

349 ncomps: the number of components (gaussian singlets + lorentzian singlets + gaussian multiplets + polynomial) fit for the profile, 

350 <0 if the fit did not converge 

351 direction: a string array containing the world direction coordinate for each profile 

352  

353 There is a "type" array having number of dimensions equal to the number of dimensions in the above arrays plus one. The shape of 

354 the first n-1 dimensions is the same as the shape of the above arrays. The length of the last dimension is equal to the number of 

355 components fit. The values of this array are strings describing the components that were fit at each possition ("POLYNOMIAL", 

356 "GAUSSIAN" in the case of gaussian singlets, "LORENTZIAN" in the case of lorentzian singlets, and ""GAUSSIAN MULTPLET"). 

357  

358 If any gaussian singlets were fit, there will be a subdictionary accessible via the "gs" key which will have subkeys "amp", "ampErr", "center", 

359 "centerErr", "fwhm", "fwhmErr, "integral", and "integralErr". Each of these arrays will have one more dimension than the overview arrays described 

360 above. The shape of the first n-1 dimensions will be the same as the shape of the arrays described above, while the final dimension will 

361 have length equal to the maximum number of gaussian singlets that were fit. Along this axis will be the 

362 corresponding fit result or associated error (depending on the array's associated key) of the fit for that singlet component number. In cases where 

363 the fit did not converge, or that particular component was excluded from the fit, a value of NAN will be present. 

364  

365 If any lorentzian singlets were fit, their solutions will be accessible via the "ls" key. These arrays follow the same rules 

366 as the "gs" arrays described above. 

367  

368 If any gaussian multiplets were fit, there will be subdictionaries accessible by keys "gm0", "gm1", ..., "gm{n-1}" where n is the number of gaussian 

369 muliplets that were fit. Each of these dictionaries will have the same arrays described above for gaussian singlets. The last dimension 

370 will have length equal to the number of components in that particular multiplet. Each pixel along the last axis will be the parameter solution 

371 value or error for that component number in the multiplet, eg the zeroth pixel along that axis contains 

372 the parameter solution or error for the reference component of the multiplet. 

373  

374 The polynomial coefficient solutions and errors are not returned, although they are logged. 

375  

376 OUTPUT IMAGES 

377 In addition to the returned dictionary, optionally one or more of any combination of output images can be written. 

378 The model and residual parameters indicate the names of the model and residual images to be written; blank values inidcate that these images 

379 should not be written. 

380  

381 One can also write none, any or all of the solution and error images for Gaussian singlet, Lorentzian singlet, and Gaussian multiplet fits 

382 via the parameters amp, amperr, center, centererr, fwhm, fwhmerr, integral, and integralerr when doing multi-pixel fits. These images simply 

383 contain the arrays described for the associated parameter solutions or errors described in previous sections. In the case of Lorentzian 

384 singlets, "_ls" is appended to the image names, in the case of Gaussian multiplets, "_gm" is appended. Pixels for which fits were not attempted or did not converge will be masked as bad. The last axis of these images 

385 is a linear axis and repesents component number (and is named accordingly). In the case where multiple Gaussian singlets and/or 

386 Lorentzians are fitted, the image names are further appended with an underscore and the relevant component number ("_0", "_1", etc). 

387 In the case of Gaussian multiplets, the image names are appended with an underscore, followed by the number of the relevant 

388 multiplet group, followed by an underscore, followed by the number of the component in that group (eg, "image_gm_3_4" represents 

389 component number 4 of multiplet group number 3). Pixels for which fits were not attempted, did not converge, or converged but 

390 have values of NaN (not a number) or INF (infinity) will be masked as bad. 

391  

392 Writing analogous images for polynomial coefficients is not supported. 

393  

394 EXAMPLE 

395 res = specif(imagename="myspectrum.im", ngauss=2, box="3,3,4,5", poly=2, multifit=true, wantreturn=True) 

396 

397 

398 """ 

399 

400 _info_group_ = """analysis""" 

401 _info_desc_ = """Fit 1-dimensional gaussians and/or polynomial models to an image or image region""" 

402 

403 def __call__( self, imagename='', box='', region='', chans='', stokes='', axis=int(-1), mask='', ngauss=int(1), poly=int(-1), estimates='', minpts=int(1), multifit=False, model='', residual='', amp='', amperr='', center='', centererr='', fwhm='', fwhmerr='', integral='', integralerr='', wantreturn=True, stretch=False, logresults=True, pampest=[ ], pcenterest=[ ], pfwhmest=[ ], pfix=[ ], gmncomps=int(0), gmampcon=[ ], gmcentercon=[ ], gmfwhmcon=[ ], gmampest=[ float(0.0) ], gmcenterest=[ float(0.0) ], gmfwhmest=[ float(0.0) ], gmfix='', logfile='', append=True, pfunc='', goodamprange=[ float(0.0) ], goodcenterrange=[ float(0.0) ], goodfwhmrange=[ float(0.0) ], sigma='', outsigma='' ): 

404 schema = {'imagename': {'type': 'cReqPath', 'coerce': _coerce.expand_path}, 'box': {'type': 'cStr', 'coerce': _coerce.to_str}, 'region': {'anyof': [{'type': 'cPath', 'coerce': _coerce.expand_path}, {'type': 'cStr', 'coerce': _coerce.to_str}, {'type': 'cDict'}]}, 'chans': {'type': 'cStr', 'coerce': _coerce.to_str}, 'stokes': {'type': 'cStr', 'coerce': _coerce.to_str}, 'axis': {'type': 'cInt'}, 'mask': {'anyof': [{'type': 'cStr', 'coerce': _coerce.to_str}, {'type': 'cStrVec', 'coerce': [_coerce.to_list,_coerce.to_strvec]}]}, 'ngauss': {'type': 'cInt'}, 'poly': {'type': 'cInt'}, 'estimates': {'type': 'cPath', 'coerce': _coerce.expand_path}, 'minpts': {'type': 'cInt'}, 'multifit': {'type': 'cBool'}, 'model': {'type': 'cStr', 'coerce': _coerce.to_str}, 'residual': {'type': 'cStr', 'coerce': _coerce.to_str}, 'amp': {'type': 'cStr', 'coerce': _coerce.to_str}, 'amperr': {'type': 'cStr', 'coerce': _coerce.to_str}, 'center': {'type': 'cStr', 'coerce': _coerce.to_str}, 'centererr': {'type': 'cStr', 'coerce': _coerce.to_str}, 'fwhm': {'type': 'cStr', 'coerce': _coerce.to_str}, 'fwhmerr': {'type': 'cStr', 'coerce': _coerce.to_str}, 'integral': {'type': 'cStr', 'coerce': _coerce.to_str}, 'integralerr': {'type': 'cStr', 'coerce': _coerce.to_str}, 'wantreturn': {'type': 'cBool'}, 'stretch': {'type': 'cBool'}, 'logresults': {'type': 'cBool'}, 'pampest': {'anyof': [{'type': 'cFloat', 'coerce': _coerce.to_float}, {'type': 'cFloatVec', 'coerce': [_coerce.to_list,_coerce.to_floatvec]}]}, 'pcenterest': {'anyof': [{'type': 'cFloat', 'coerce': _coerce.to_float}, {'type': 'cFloatVec', 'coerce': [_coerce.to_list,_coerce.to_floatvec]}]}, 'pfwhmest': {'anyof': [{'type': 'cFloat', 'coerce': _coerce.to_float}, {'type': 'cFloatVec', 'coerce': [_coerce.to_list,_coerce.to_floatvec]}]}, 'pfix': {'anyof': [{'type': 'cFloat', 'coerce': _coerce.to_float}, {'type': 'cFloatVec', 'coerce': [_coerce.to_list,_coerce.to_floatvec]}]}, 'gmncomps': {'anyof': [{'type': 'cInt'}, {'type': 'cIntVec', 'coerce': [_coerce.to_list,_coerce.to_intvec]}]}, 'gmampcon': {'anyof': [{'type': 'cFloat', 'coerce': _coerce.to_float}, {'type': 'cFloatVec', 'coerce': [_coerce.to_list,_coerce.to_floatvec]}]}, 'gmcentercon': {'anyof': [{'type': 'cFloat', 'coerce': _coerce.to_float}, {'type': 'cFloatVec', 'coerce': [_coerce.to_list,_coerce.to_floatvec]}]}, 'gmfwhmcon': {'anyof': [{'type': 'cFloat', 'coerce': _coerce.to_float}, {'type': 'cFloatVec', 'coerce': [_coerce.to_list,_coerce.to_floatvec]}]}, 'gmampest': {'type': 'cFloatVec', 'coerce': [_coerce.to_list,_coerce.to_floatvec]}, 'gmcenterest': {'type': 'cFloatVec', 'coerce': [_coerce.to_list,_coerce.to_floatvec]}, 'gmfwhmest': {'type': 'cFloatVec', 'coerce': [_coerce.to_list,_coerce.to_floatvec]}, 'gmfix': {'anyof': [{'type': 'cStr', 'coerce': _coerce.to_str}, {'type': 'cStrVec', 'coerce': [_coerce.to_list,_coerce.to_strvec]}]}, 'logfile': {'type': 'cStr', 'coerce': _coerce.to_str}, 'append': {'type': 'cBool'}, 'pfunc': {'anyof': [{'type': 'cStr', 'coerce': _coerce.to_str}, {'type': 'cStrVec', 'coerce': [_coerce.to_list,_coerce.to_strvec]}]}, 'goodamprange': {'type': 'cFloatVec', 'coerce': [_coerce.to_list,_coerce.to_floatvec]}, 'goodcenterrange': {'type': 'cFloatVec', 'coerce': [_coerce.to_list,_coerce.to_floatvec]}, 'goodfwhmrange': {'type': 'cFloatVec', 'coerce': [_coerce.to_list,_coerce.to_floatvec]}, 'sigma': {'anyof': [{'type': 'cIntVec', 'coerce': [_coerce.to_list,_coerce.to_intvec]}, {'type': 'cStr', 'coerce': _coerce.to_str}, {'type': 'cIntArray', 'coerce': [_coerce.to_intarray]}, {'type': 'cFloatArray', 'coerce': [_coerce.to_floatarray]}, {'type': 'cFloatVec', 'coerce': [_coerce.to_list,_coerce.to_floatvec]}]}, 'outsigma': {'type': 'cStr', 'coerce': _coerce.to_str}} 

405 doc = {'imagename': imagename, 'box': box, 'region': region, 'chans': chans, 'stokes': stokes, 'axis': axis, 'mask': mask, 'ngauss': ngauss, 'poly': poly, 'estimates': estimates, 'minpts': minpts, 'multifit': multifit, 'model': model, 'residual': residual, 'amp': amp, 'amperr': amperr, 'center': center, 'centererr': centererr, 'fwhm': fwhm, 'fwhmerr': fwhmerr, 'integral': integral, 'integralerr': integralerr, 'wantreturn': wantreturn, 'stretch': stretch, 'logresults': logresults, 'pampest': pampest, 'pcenterest': pcenterest, 'pfwhmest': pfwhmest, 'pfix': pfix, 'gmncomps': gmncomps, 'gmampcon': gmampcon, 'gmcentercon': gmcentercon, 'gmfwhmcon': gmfwhmcon, 'gmampest': gmampest, 'gmcenterest': gmcenterest, 'gmfwhmest': gmfwhmest, 'gmfix': gmfix, 'logfile': logfile, 'append': append, 'pfunc': pfunc, 'goodamprange': goodamprange, 'goodcenterrange': goodcenterrange, 'goodfwhmrange': goodfwhmrange, 'sigma': sigma, 'outsigma': outsigma} 

406 assert _pc.validate(doc,schema), create_error_string(_pc.errors) 

407 _logging_state_ = _start_log( 'specfit', [ 'imagename=' + repr(_pc.document['imagename']), 'box=' + repr(_pc.document['box']), 'region=' + repr(_pc.document['region']), 'chans=' + repr(_pc.document['chans']), 'stokes=' + repr(_pc.document['stokes']), 'axis=' + repr(_pc.document['axis']), 'mask=' + repr(_pc.document['mask']), 'ngauss=' + repr(_pc.document['ngauss']), 'poly=' + repr(_pc.document['poly']), 'estimates=' + repr(_pc.document['estimates']), 'minpts=' + repr(_pc.document['minpts']), 'multifit=' + repr(_pc.document['multifit']), 'model=' + repr(_pc.document['model']), 'residual=' + repr(_pc.document['residual']), 'amp=' + repr(_pc.document['amp']), 'amperr=' + repr(_pc.document['amperr']), 'center=' + repr(_pc.document['center']), 'centererr=' + repr(_pc.document['centererr']), 'fwhm=' + repr(_pc.document['fwhm']), 'fwhmerr=' + repr(_pc.document['fwhmerr']), 'integral=' + repr(_pc.document['integral']), 'integralerr=' + repr(_pc.document['integralerr']), 'wantreturn=' + repr(_pc.document['wantreturn']), 'stretch=' + repr(_pc.document['stretch']), 'logresults=' + repr(_pc.document['logresults']), 'pampest=' + repr(_pc.document['pampest']), 'pcenterest=' + repr(_pc.document['pcenterest']), 'pfwhmest=' + repr(_pc.document['pfwhmest']), 'pfix=' + repr(_pc.document['pfix']), 'gmncomps=' + repr(_pc.document['gmncomps']), 'gmampcon=' + repr(_pc.document['gmampcon']), 'gmcentercon=' + repr(_pc.document['gmcentercon']), 'gmfwhmcon=' + repr(_pc.document['gmfwhmcon']), 'gmampest=' + repr(_pc.document['gmampest']), 'gmcenterest=' + repr(_pc.document['gmcenterest']), 'gmfwhmest=' + repr(_pc.document['gmfwhmest']), 'gmfix=' + repr(_pc.document['gmfix']), 'logfile=' + repr(_pc.document['logfile']), 'append=' + repr(_pc.document['append']), 'pfunc=' + repr(_pc.document['pfunc']), 'goodamprange=' + repr(_pc.document['goodamprange']), 'goodcenterrange=' + repr(_pc.document['goodcenterrange']), 'goodfwhmrange=' + repr(_pc.document['goodfwhmrange']), 'sigma=' + repr(_pc.document['sigma']), 'outsigma=' + repr(_pc.document['outsigma']) ] ) 

408 task_result = None 

409 try: 

410 task_result = _specfit_t( _pc.document['imagename'], _pc.document['box'], _pc.document['region'], _pc.document['chans'], _pc.document['stokes'], _pc.document['axis'], _pc.document['mask'], _pc.document['ngauss'], _pc.document['poly'], _pc.document['estimates'], _pc.document['minpts'], _pc.document['multifit'], _pc.document['model'], _pc.document['residual'], _pc.document['amp'], _pc.document['amperr'], _pc.document['center'], _pc.document['centererr'], _pc.document['fwhm'], _pc.document['fwhmerr'], _pc.document['integral'], _pc.document['integralerr'], _pc.document['wantreturn'], _pc.document['stretch'], _pc.document['logresults'], _pc.document['pampest'], _pc.document['pcenterest'], _pc.document['pfwhmest'], _pc.document['pfix'], _pc.document['gmncomps'], _pc.document['gmampcon'], _pc.document['gmcentercon'], _pc.document['gmfwhmcon'], _pc.document['gmampest'], _pc.document['gmcenterest'], _pc.document['gmfwhmest'], _pc.document['gmfix'], _pc.document['logfile'], _pc.document['append'], _pc.document['pfunc'], _pc.document['goodamprange'], _pc.document['goodcenterrange'], _pc.document['goodfwhmrange'], _pc.document['sigma'], _pc.document['outsigma'] ) 

411 except Exception as exc: 

412 _except_log('specfit', exc) 

413 raise 

414 finally: 

415 task_result = _end_log( _logging_state_, 'specfit', task_result ) 

416 return task_result 

417 

418specfit = _specfit( ) 

419