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

27 statements  

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

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

2##################### cd5491adbb52564df09390ab9c67dee0 ############################## 

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_immath import immath as _immath_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 _immath: 

15 """ 

16 immath ---- Perform math operations on images 

17 

18 math on images 

19 

20 --------- parameter descriptions --------------------------------------------- 

21 

22 imagename a list of input images 

23 mode mode for math operation (evalexpr, spix, pola, poli, lpoli, tpoli) 

24 outfile File where the output is saved 

25 expr Mathematical expression using images 

26 varnames a list of variable names to use with the image files 

27 sigma standard deviation of noise for debiasing 

28 polithresh Threshold in linear polarization intensity image below which to mask pixels. 

29 mask Mask to use. Default is none. 

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

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

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

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

34 stretch Stretch the mask if necessary and possible? See help stretch.par 

35 imagemd An image name from which metadata should be copied. The input can be either an image listed under imagename or any other image on disk. Leaving this parameter unset may copy header metadata from any of the input images, which one is not guaranteed. 

36 prec Precision for the output image pixels if mode="evalexpr" or "spix". "float" or "double" (minimum match supported) 

37 RETURNS bool 

38 

39 --------- examples ----------------------------------------------------------- 

40 

41  

42  

43 This task evaluates mathematical expressions involving existing 

44 image files. The results of the calculations are stored in the 

45 designated output file. Options are available to specify mathematical 

46 expression directly or pre-defined expression for calculation of 

47 spectral index image, and polarization intensity and position angle 

48 images are available. The image file names imbedded in the expression or 

49 specified in the imagename parameter for the pre-defined calculations may 

50 be CASA images or FITS images. 

51  

52  

53 NOTE: Index values start at 0 Use the imhead task to see the range of 

54 index values for each axes. 

55  

56  

57 Keyword arguments: 

58 imagename input image name(s) 

59 Default: none; 

60 Examples: mode='evalexpr'; imagename=['image1.im', 'image2.im' ] 

61 The text 'IM0' is replaced by 'image1.im' in the 

62 expression and 'IM1' is repalced with 'image2.im' 

63 mode='spix'; imagename=['image1.im','image2.im'] will calculate 

64 an image of log(S1/S2)/log(f1/f2), where S1 and S2 are fluxes and 

65 f1 and f2 are frequencies 

66 mode='pola'; imagename='multistokes.im' (where that image contains both Q and U 

67 stokes planes) or imagename=['imageQ.im','imageU.im'] will calculate 

68 an image of polarization angle distribution, where imageQ.im and 

69 imageU.im are Stokes Q and U images, respectively. Calculate 0.5*arctan(U/Q). 

70 mode='poli'; imagename=['imageQ.im','imageU.im','imageV.im'] will calculate 

71 total polarization intensity image, where imageQ.im, imageU.im, imageV.im 

72 are Stokes Q, U, and V images, respectively. Alternatively, with 

73 imagename = ['imageQ.im','imageU.im'] the linear polarization intensity 

74 image will be calculated. In the case where imagename is a single multi-stokes 

75 image, the total polarization image will be calculated if all of the Q, U, and 

76 V stokes planes are present, and the linear polarization intensity image will 

77 be calculated if the Q and U (but not V) planes are present. 

78  

79 mode mode for mathematical operation 

80 Default: evalexpr 

81 Options: 'evalexpr' : evalulate a mathematical expression defined in 'expr' 

82 'spix' : spectalindex image 

83 'pola' : polarization position angle image 

84 'poli' : polarization intesity image 

85 >>> mode expandable parameters 

86 sigma (for mode='poli') standard deviation of noise of Stokes images with unit such as 

87 Jy/beam to correct for bias 

88 Default: '0.0Jy/beam' (= no debiasing) 

89 polithresh (for mode='pola') Quantity (eg '30uJy/beam') describing the linear (not total; 

90 the stokes V contribution is not included) polarization threshold. A mask ('mask0') 

91 is written to the output image and is False for all corresponding linear polarization 

92 values below this threshold. This parameter overrides the mask input parameter 

93 (below). Default ('') means use the value given in mask, or no masking if that 

94 value is empty as well. 

95 expr (for mode='evalexpr') A LEL expression with images. 

96 Image file names are specified in the imagenames paramter, and 

97 the variables IM0, IM1, ... (or optionally via the varnames parameter, see below) 

98 are used to represent these files 

99 in the expression. Explicit notations of file names in the 

100 expression are also supported, in which cases the file names must 

101 be enclosed in double quotes (") and imagename is ignored. 

102 Examples: 

103 Make an image that is image1.im - image2.im 

104 expr=' (IM0 - IM1 )' 

105 or with an explicit notation, 

106 expr='("image1.im" - "image2.im")' 

107 Clip an image below a value (0.5 in this case) 

108 expr = ' iif( IM0 >=0.5, IM0, 0.0) ' 

109 Note: iif (a, b, c) a is the boolean expression 

110 b is the value if true 

111 c is the value if false 

112 Take the rms value of two images 

113 expr = ' sqrt(IM0 * IM0 + IM1 * IM1) ' 

114 Build an image pixel by pixel from the minimum of (image2.im, 2*image1.im) 

115 expr='min(IM1,2*max(IM0))' 

116 varnames For mode="evalexpr". Instead of the default variable names IM0, IM1, ..., use 

117 the names in this array to represent the input images. 

118 outfile The output image. Overwriting an existing outfile is not permitted. 

119 Default: immath_results.im; Example: outfile='results.im' 

120 mask Mask to use. Default is none. Also see polithresh. 

121 stretch Stretch the input mask if necessary and possible. See below. 

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

123 box Rectangular region to select in direction plane. Default 

124 is to use the entire direction plane. 

125 Example: box='10,10,50,50' 

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

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

128 Not used in for cases of mode='poli' or mode='pola' 

129 imagemd The image from which metadata should be copied to the output. Default means no guarantee from 

130 which image is used. The image must exist and should conform to the output image spec. 

131  

132 Available functions in the expr and mask parameters: 

133 pi(), e(), sin(), sinh(), asinh(), cos(), cosh(), tan(), tanh(), 

134 atan(), exp(), log(), log10(), pow(), sqrt(), complex(), conj() 

135 real(), imag(), abs(), arg(), phase(), amplitude(), min(), max() 

136 round(), isgn(), floor(), ceil(), rebin(), spectralindex(), pa(), 

137 iif(), indexin(), replace(), ... 

138  

139 If the mask has fewer dimensions than the image and if the shape 

140 of the dimensions the mask and image have in common are the same, 

141 the mask will automatically have the missing dimensions added so 

142 it conforms to the image. 

143  

144 For a full description of the allowed syntax see the 

145 Lattice Expression Language (LEL) documentation on the at: 

146 http://aips2.nrao.edu/docs/notes/223/223.html 

147  

148 NOTE: where indexing and axis numbering are used in the above 

149 functions they are 1-based, ie. numbering starts at 1. 

150  

151 If stretch is true and if the number of mask dimensions is less than 

152 or equal to the number of image dimensions and some axes in the 

153 mask are degenerate while the corresponding axes in the image are not, 

154 the mask will be stetched in the degenerate axis dimensions. For example, 

155 if the input image has shape [100, 200, 10] and the input 

156 mask has shape [100, 200, 1] and stretch is true, the mask will be 

157 stretched along the third dimension to shape [100, 200, 10]. However if 

158 the mask is shape [100, 200, 2], stretching is not possible and an 

159 error will result. 

160  

161 CAUTIONS REGARDING OUTPUT IMAGE METADATA, INCLUDING BRIGHTNESS UNIT 

162  

163 EXCEPT IN THE CASES NOTED BELOW, THIS APPLICATION MAKES NO ATTEMPT TO 

164 DETERMINE WHAT THE CORRECT BRIGHTNESS UNIT OF THE OUTPUT IMAGE SHOULD BE. THIS 

165 RESPONSIBILITY LIES SOLELY WITH THE USER. The brightness unit of the output image 

166 can be modified using tool method ia.setbrightnessunit() or task imhead with 

167 mode='put' and hdkey='bunit'. 

168  

169 Note that when multiple image are used in the expression, there is 

170 no garauntee about which of those images will be used to create the metadata 

171 of the output image, unless imagemd is specified. If imagemd is specified, the following 

172 rules of metadata copying will be followed: 

173  

174 1. The pixel data type of the image specified by imagemd and the output image must 

175 be the same. 

176 2. The metadata copied include the coordinate system (and so of course the dimensionality of 

177 the output image must correspond to the coordinate system to be copied), the image_info record 

178 (which contains things like the beam(s)), the misc_info record (should one exist in the image 

179 specified by imagemd), and the units. 

180 3. If the output image is a spectral image, the brightness units are set to the empty string. 

181 4. If the ouptut image is a polarization angle image, the brightness unit is set to "deg" and 

182 the stokes coordinate is set to have a single plane of type of Pangle. 

183  

184 Examples: 

185 # Double all values in an image. 

186 immath( imagesname='myimage.im', expr='IM0*2', outfile='double.im' ) 

187 # or with an explicit notation, 

188 immath( expr='"myimage.im"*2', outfile='double.im' ) 

189  

190 # Taking the sin of an image and adding it to another 

191 # Note that the images need to be the same size 

192 immath(images=['image1.im', 'image2.im'], expr='sin(IM1)+IM0;',outfile='newImage.im') 

193  

194 # Adding only the plane associated with the 'V' stokes value and 

195 # the 1st channel together in two images 

196 immath(imagename=[image1', 'image2'], expr='IM0+IM1',chans='1',stokes='V') 

197  

198  

199 # Selecting a single plane (5th channel), of the 3-D cube and 

200 # adding it to the original image. In this example the 2-D plane 

201 # gets expanded out and the values are applied to each plane in the 

202 # 3-D cube. 

203 default('immath') 

204 imagename='ngc7538.image' 

205 outfile='chanFive.im' 

206 expr='IM0' 

207 chans='5' 

208 go 

209 default('immath') 

210 imagename=['ngc7538.image', chanFive.im'] 

211 outfile='ngc7538_chanFive.im' 

212 expr='IM0+IM1' 

213 go 

214  

215 # Selecting and saving the inner 3/4 of an image for channels 40,42,44 

216 # as well as channels less than 10 

217 default('immath') 

218 imagename='my_image.im' 

219 expr='IM0' 

220 box='25,25,123,123' 

221 chans='<10;40,42,44' 

222 outfile='my_image_inner.im' ) 

223 go 

224  

225 # Dividing an image by another, making sure we aren't dividing by zero 

226 default('immath') 

227 imagename=['orion.image', 'my.image'] 

228 expr='IM0/iif(IM1==0,1.0,IM1)' 

229 outfile='my_orion.image' 

230 go 

231  

232 # Applying a mask to all of the images in the expression 

233 default('immath') 

234 imagename=['ngc7538.image','ngc7538_clean.image'] 

235 expr='(IM0*10)+IM1' 

236 mask='"ngc7538.mask"' 

237 outfile='really_noisy_ngc7538.image' 

238 go 

239  

240  

241 # Applying a pixel mask contained in the image information 

242 default('immath') 

243 imagename='ngc5921.image' 

244 expr='IM0*10' 

245 mask='mask("ngc5921.mask")' 

246 outfile='ngc5921.masked.image' 

247 go 

248  

249 # Creating a total polarization intensity image from an multi-stokes image 

250 # containing IQUV. 

251 default('immath') 

252 outfile='pol_intensity' 

253 stokes='' 

254 # in imagename, you can also specify a list containing single stokes images 

255 # of Q and U (for linear polarization intensity) and V (for total 

256 # polarization intensity) 

257 imagename='3C138_pcal' 

258 mode='poli' 

259 go 

260  

261 # Creating a polarization position angle image 

262 default('immath') 

263 outfile='pol_angle.im' 

264 mode='pola' 

265 # you can also do imagename=['Q.im','U.im'] for single stokes images, order of 

266 # the two Stokes images does not matter 

267 imagename='3C138_pcal' # multi-stokes image containing at least Q and U stokes 

268 go 

269  

270 # same as before but write a mask with values of False for pixels for which the 

271 # corresponding linear polarization ( sqrt(Q*Q+U*U)) is less than 30 microJy/beam 

272 polithresh='30uJy/beam' 

273 go 

274  

275 # Creating a spectral index image from the images at two different observing frequencies 

276 default('immath') 

277 outfile='mySource_sp.im' 

278 mode='spix' 

279 imagename=['mySource_5GHz.im','mySource_8GHz.im'] 

280 go 

281  

282 TEMPORARY IMAGES 

283  

284 At this time, it is usually necessary for this task to create intermediate, temporary disk images. 

285 The names of these images start with '_immath' and are created in the directory in which the task 

286 is run. The task makes reasonable attempts to remove these images before it exits, but there are 

287 conceivably instances where the temporary images may not be automatically deleted. It is generally 

288 safe to delete them by hand, assuming no immath instance is currently in progress. 

289  

290 The hope and plan is that the necessity of these images will decrease in the future (i.e. the computations 

291 will require only RAM and not temporary persistent storage of intermediate results). 

292  

293  

294 

295 

296 """ 

297 

298 _info_group_ = """analysis""" 

299 _info_desc_ = """Perform math operations on images""" 

300 

301 def __call__( self, imagename='', mode='evalexpr', outfile='immath_results.im', expr='IM0', varnames='', sigma='0.0mJy/beam', polithresh='', mask='', region='', box='', chans='', stokes='', stretch=False, imagemd='', prec='float' ): 

302 schema = {'imagename': {'type': 'cVariant', 'coerce': [_coerce.to_variant]}, 'mode': {'type': 'cStr', 'coerce': _coerce.to_str, 'allowed': [ 'lpoli', 'poli', 'evalexpr', 'spix', 'tpoli', 'pola' ]}, 'outfile': {'type': 'cStr', 'coerce': _coerce.to_str}, 'expr': {'type': 'cStr', 'coerce': _coerce.to_str}, 'varnames': {'type': 'cVariant', 'coerce': [_coerce.to_variant]}, 'sigma': {'type': 'cStr', 'coerce': _coerce.to_str}, 'polithresh': {'type': 'cStr', 'coerce': _coerce.to_str}, 'mask': {'type': 'cStr', 'coerce': _coerce.to_str}, 'region': {'type': 'cStr', 'coerce': _coerce.to_str}, 'box': {'type': 'cStr', 'coerce': _coerce.to_str}, 'chans': {'type': 'cStr', 'coerce': _coerce.to_str}, 'stokes': {'type': 'cStr', 'coerce': _coerce.to_str}, 'stretch': {'type': 'cBool'}, 'imagemd': {'type': 'cStr', 'coerce': _coerce.to_str}, 'prec': {'type': 'cStr', 'coerce': _coerce.to_str}} 

303 doc = {'imagename': imagename, 'mode': mode, 'outfile': outfile, 'expr': expr, 'varnames': varnames, 'sigma': sigma, 'polithresh': polithresh, 'mask': mask, 'region': region, 'box': box, 'chans': chans, 'stokes': stokes, 'stretch': stretch, 'imagemd': imagemd, 'prec': prec} 

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

305 _logging_state_ = _start_log( 'immath', [ 'imagename=' + repr(_pc.document['imagename']), 'mode=' + repr(_pc.document['mode']), 'outfile=' + repr(_pc.document['outfile']), 'expr=' + repr(_pc.document['expr']), 'varnames=' + repr(_pc.document['varnames']), 'sigma=' + repr(_pc.document['sigma']), 'polithresh=' + repr(_pc.document['polithresh']), 'mask=' + repr(_pc.document['mask']), 'region=' + repr(_pc.document['region']), 'box=' + repr(_pc.document['box']), 'chans=' + repr(_pc.document['chans']), 'stokes=' + repr(_pc.document['stokes']), 'stretch=' + repr(_pc.document['stretch']), 'imagemd=' + repr(_pc.document['imagemd']), 'prec=' + repr(_pc.document['prec']) ] ) 

306 task_result = None 

307 try: 

308 task_result = _immath_t( _pc.document['imagename'], _pc.document['mode'], _pc.document['outfile'], _pc.document['expr'], _pc.document['varnames'], _pc.document['sigma'], _pc.document['polithresh'], _pc.document['mask'], _pc.document['region'], _pc.document['box'], _pc.document['chans'], _pc.document['stokes'], _pc.document['stretch'], _pc.document['imagemd'], _pc.document['prec'] ) 

309 except Exception as exc: 

310 _except_log('immath', exc) 

311 raise 

312 finally: 

313 task_result = _end_log( _logging_state_, 'immath', task_result ) 

314 return task_result 

315 

316immath = _immath( ) 

317