Coverage for spectractor/simulation/adr.py: 13%

Shortcuts on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

152 statements  

1#! /usr/bin/env python 

2# -*- coding: utf-8 -*- 

3 

4 

5import astropy.coordinates as AC 

6from astropy import units as u 

7import numpy as np 

8from spectractor import parameters 

9from spectractor.tools import flip_and_rotate_radec_to_image_xy_coordinates 

10 

11""" 

12Atmospheric Differential Refraction: Evolution of the spatial position as a function of wavelength. 

13Credit: Y.Copin (y.copin@ipnl.in2p3.fr) 

14Adapted by: M. Rigault 

15Inspiration: SNfactory ToolBox (see also Don Neill's Fork of KPY) 

16Original Source: http://emtoolbox.nist.gov/Wavelength/Documentation.asp 

17""" 

18 

19 

20class ADR: 

21 

22 def __init__(self, airmass, lbdaref, pressure, parangle, relathumidity, temperature): 

23 

24 self.airmass = airmass 

25 self.lbdaref = lbdaref 

26 self.pressure = pressure 

27 self.parangle = parangle 

28 self.relathumidity = relathumidity 

29 self.temperature = temperature 

30 

31 # =================== # 

32 # Methods # 

33 # =================== # 

34 def refract(self, x, y, lbda, backward=False, unit=1.): 

35 """If forward (default), return refracted position(s) at 

36 wavelength(s) *lbda* [Å] from reference position(s) *x*,*y* 

37 (in units of *unit* in arcsec). Return shape is 

38 (2,[nlbda],[npos]), where nlbda and npos are the number of 

39 input wavelengths and reference positions. 

40 If backward, one should have `len(x) == len(y) == 

41 len(lbda)`. Return shape is then (2,npos). 

42 Coordinate *x* is counted westward, and coordinate *y* counted 

43 northward (standard North-up, Est-left orientation). 

44 Anonymous `kwargs` will be propagated to :meth:`set`. 

45 """ 

46 

47 x0 = np.atleast_1d(x) # (npos,) 

48 y0 = np.atleast_1d(y) 

49 if np.shape(x0) != np.shape(y0): 

50 raise TypeError("x and y do not have the same shape") 

51 

52 npos = len(x0) 

53 

54 dz = np.tan(np.arccos(1. / self.airmass)) * self.get_scale(lbda) / unit # [unit] 

55 if backward: 

56 nlbda = len(np.atleast_1d(lbda)) 

57 assert npos == nlbda, "Incompatible x,y and lbda vectors." 

58 x = x0 - dz * np.sin(self.parangle / 180. * np.pi) 

59 y = y0 + dz * np.cos(self.parangle / 180. * np.pi) # (nlbda=npos,) 

60 out = np.vstack((x, y)) # (2,npos) 

61 else: 

62 dz = dz[:, np.newaxis] # (nlbda,1) 

63 x = x0 + dz * np.sin(self.parangle / 180. * np.pi) # (nlbda,npos) 

64 y = y0 - dz * np.cos(self.parangle / 180. * np.pi) # (nlbda,npos) 

65 out = np.dstack((x.T, y.T)).T # (2,nlbda,npos) 

66 return out.squeeze() # (2,[nlbda],[npos]) 

67 

68 # ------- # 

69 # GETTER # 

70 # ------- # 

71 def get_scale(self, lbda): 

72 """ 

73 Return ADR scale [arcsec] for wavelength(s) `lbda` [A]. 

74 Anonymous `kwargs` will be propagated to :meth:`set`. 

75 """ 

76 

77 lbda = np.atleast_1d(lbda) # (nlbda,) 

78 

79 # Approximate ADR to 1st order in (n - 1). The difference 

80 # between exact expression and 1st-order approximation reaches 

81 # 4e-9 at 3200 A. 

82 # dz = self.nref - \ 

83 # refractiveIndex(lbda, P=self.P, T=self.T, RH=self.RH) 

84 

85 # Exact ADR expression 

86 dz = (self.get_refractive_index(lbda) ** -2 - self.get_refractive_index(self.lbdaref) ** -2) * 0.5 

87 

88 return dz * 180. * 3600 / np.pi # (nlbda,) [arcsec] 

89 

90 def get_refractive_index(self, lbda): 

91 """ relative index for the given wavelength. 

92 Anonymous `kwargs` will be propagated to :meth:`set`. 

93 """ 

94 

95 return refractive_index(lbda, self.pressure, self.temperature, self.relathumidity) 

96 

97 

98############################## 

99# # 

100# General Functions # 

101# # 

102############################## 

103 

104def refractive_index(lbda, pressure=617., temperature=2., relathumidity=0): 

105 """Compute refractive index at vacuum wavelength. 

106 source: NIST/IAPWS via SNfactory ToolBox 

107 http://emtoolbox.nist.gov/Wavelength/Documentation.asp 

108 Parameters: 

109 ----------- 

110 lbda: [float / array of] 

111 wavelength in [Å] 

112 

113 pressure: [float] -optional- 

114 air pressure in mbar 

115 temperature: [float] -optional- 

116 air temperature in Celcius 

117 relathumidity: [float] -optional- 

118 air relative humidity in percent. 

119 [the water vapor pressure will be derived from it, 

120 according to (modified) Edlén Calculation of the Index of 

121 Refraction from NIST 'Refractive Index of Air Calculator'. CO2 

122 concentration is fixed to 450 µmol/mol.] 

123 Returns 

124 ------- 

125 float/array (depending on lbda input) 

126 """ 

127 

128 A = 8342.54 

129 B = 2406147. 

130 C = 15998. 

131 D = 96095.43 

132 E = 0.601 

133 F = 0.00972 

134 G = 0.003661 

135 

136 iml2 = (lbda * 1e-4) ** -2 # 1/(lambda in microns)**2 

137 nsm1e2 = 1e-6 * (A + B / (130. - iml2) + C / (38.9 - iml2)) # (ns - 1)*1e2 

138 # P in mbar = 1e2 Pa 

139 X = (1. + 1e-6 * (E - F * temperature) * pressure) / (1. + G * temperature) 

140 n = 1. + pressure * nsm1e2 * X / D # ref. index corrected for P,T 

141 

142 if relathumidity: # Humidity correction 

143 pv = relathumidity / 100. * saturation_vapor_pressure(temperature) # [Pa] 

144 n -= 1e-10 * (292.75 / (temperature + 273.15)) * (3.7345 - 0.0401 * iml2) * pv 

145 

146 return n 

147 

148 

149def saturation_vapor_pressure(temperature): 

150 """Compute saturation vapor pressure [Pa] for temperature *T* [°C] 

151 according to Edlén Calculation of the Index of Refraction from 

152 NIST 'Refractive Index of Air Calculator'. 

153 Source: http://emtoolbox.nist.gov/Wavelength/Documentation.asp 

154 """ 

155 

156 t = np.atleast_1d(temperature) 

157 psv = np.where(t >= 0, 

158 _saturationVaporPressureOverWater(temperature), 

159 _saturationVaporPressureOverIce(temperature)) 

160 

161 return psv # [Pa] 

162 

163 

164def _saturationVaporPressureOverIce(temperature): 

165 """See :func:`saturation_vapor_pressure`""" 

166 

167 A1 = -13.928169 

168 A2 = 34.7078238 

169 th = (temperature + 273.15) / 273.16 

170 Y = A1 * (1 - th ** -1.5) + A2 * (1 - th ** -1.25) 

171 psv = 611.657 * np.exp(Y) 

172 

173 return psv 

174 

175 

176def _saturationVaporPressureOverWater(temperature): 

177 """See :func:`saturation_vapor_pressure`""" 

178 

179 K1 = 1.16705214528e+03 

180 K2 = -7.24213167032e+05 

181 K3 = -1.70738469401e+01 

182 K4 = 1.20208247025e+04 

183 K5 = -3.23255503223e+06 

184 K6 = 1.49151086135e+01 

185 K7 = -4.82326573616e+03 

186 K8 = 4.05113405421e+05 

187 K9 = -2.38555575678e-01 

188 K10 = 6.50175348448e+02 

189 

190 t = temperature + 273.15 # °C → K 

191 x = t + K9 / (t - K10) 

192 A = x ** 2 + K1 * x + K2 

193 B = K3 * x ** 2 + K4 * x + K5 

194 C = K6 * x ** 2 + K7 * x + K8 

195 X = -B + np.sqrt(B ** 2 - 4 * A * C) 

196 psv = 1e6 * (2 * C / X) ** 4 

197 

198 return psv 

199 

200 

201######################## 

202# 

203# Conversions # 

204# 

205######################## 

206RAD2DEG = 180. / np.pi 

207 

208 

209def hadec2zdpar(ha, dec, lat, deg=True): 

210 """ 

211 Conversion of equatorial coordinates *(ha, dec)* (in degrees if *deg*) to 

212 zenithal distance and parallactic angle *(zd, par)* (in degrees if *deg*), 

213 for a given geodetic latitude *lat* (in degrees if *deg*). 

214 .. Author: Y. Copin (y.copin@ipnl.in2p3.fr) 

215 """ 

216 if deg: # Convert to radians 

217 ha = ha / RAD2DEG 

218 dec = dec / RAD2DEG 

219 lat = lat / RAD2DEG 

220 

221 cha, sha = np.cos(ha), np.sin(ha) 

222 cdec, sdec = np.cos(dec), np.sin(dec) 

223 clat, slat = np.cos(lat), np.sin(lat) 

224 

225 sz_sp = clat * sha 

226 sz_cp = slat * cdec - clat * cha * sdec 

227 cz = slat * sdec + clat * cha * cdec 

228 

229 sz, p = rec2pol(sz_cp, sz_sp) 

230 r, z = rec2pol(cz, sz) 

231 

232 assert np.allclose(r, 1), "Precision error" 

233 

234 if deg: 

235 z *= RAD2DEG 

236 p *= RAD2DEG 

237 

238 return z, p 

239 

240 

241def rec2pol(x, y, deg=False): 

242 """ 

243 Conversion of rectangular *(x, y)* to polar *(r, theta)* coordinates. 

244 .. Author: Y. Copin (y.copin@ipnl.in2p3.fr) 

245 """ 

246 r = np.hypot(x, y) 

247 t = np.arctan2(y, x) 

248 if deg: # Convert to radians 

249 t *= RAD2DEG 

250 

251 return r, t 

252 

253 

254""" 

255Functions to: 

256 - get adr object from fits file 

257 - get list of shift due to adr corresponding to a list of lambdas 

258 - get maximum shift due to adr between (in th range of lambdas given) 

259 - plot the adr along both axis and the biggest one against the wavelength 

260Example to get shift in pixels: 

261 instanciation_adr(fitsfile, latitude, lbda_ref) 

262 xs, ys = get_adr_shift_for_lbdas(adr_object, lbdas) 

263 xs_pix, ys_pix = in_pixel(xs, fitsfile), adru.in_pixel(ys, fitsfile) 

264""" 

265 

266 

267# ================================= # 

268# Main functions # 

269# ================================= # 

270 

271 

272def adr_calib(lambdas, params, lat, lambda_ref=550): 

273 if isinstance(lat, str) or isinstance(lat, float): 

274 lat = AC.Latitude(lat, unit=u.deg) 

275 elif isinstance(lat, AC.Latitude): 

276 lat = lat 

277 else: 

278 raise TypeError('Latitude type is neither a str, float nor an astropy.coordinates') 

279 

280 meadr = instanciation_adr(params, lat, lambda_ref * 10) 

281 

282 disp_axis, trans_axis = get_adr_shift_for_lbdas(meadr, lambdas * 10) 

283 disp_axis_pix = in_pixel(disp_axis) 

284 trans_axis_pix = in_pixel(trans_axis) 

285 

286 return disp_axis_pix, trans_axis_pix 

287 

288 

289def instanciation_adr(params, latitude, lbda_ref): 

290 dec, hour_angle = params[:2] 

291 

292 if (isinstance(dec, str) and isinstance(hour_angle, str)) \ 

293 or (isinstance(dec, float) and isinstance(hour_angle, float)): 

294 dec = AC.Angle(params[0], unit=u.deg) 

295 hour_angle = AC.Angle(params[1], unit=u.hourangle) 

296 elif isinstance(dec, AC.Angle) and isinstance(hour_angle, AC.Angle): 

297 dec = dec 

298 hour_angle = hour_angle 

299 else: 

300 raise TypeError('dec/hour_angle type is neither a str nor an astropy.coordinates') 

301 

302 temperature, pressure, humidity, airmass = params[2:] 

303 

304 _, parangle = hadec2zdpar(hour_angle.degree, dec.degree, latitude.degree, deg=True) 

305 adr = ADR(airmass=airmass, parangle=parangle, temperature=temperature, 

306 pressure=pressure, lbdaref=lbda_ref, relathumidity=humidity) 

307 

308 return adr 

309 

310 

311def get_adr_shift_for_lbdas(adr_object, lbdas): 

312 """ 

313 Returns shift in x and y due to adr as arrays in arcsec. 

314 """ 

315 

316 arcsecshift = adr_object.refract(0, 0, lbdas) 

317 

318 x_shift = (arcsecshift[0]) 

319 y_shift = (arcsecshift[1]) 

320 

321 return x_shift, y_shift 

322 

323 

324# ================================= # 

325# Utilitary functions # 

326# ================================= # 

327 

328 

329def in_pixel(thing_in_arcsec): 

330 """ 

331 Transform something in arcsec in pixels 

332 """ 

333 

334 xpixsize = parameters.CCD_PIXEL2ARCSEC 

335 ypixsize = parameters.CCD_PIXEL2ARCSEC 

336 

337 if xpixsize != ypixsize: 

338 raise ValueError('Pixels in X and Y do not have the same length, too complicated, did not work') 

339 

340 thing_in_pix = thing_in_arcsec / xpixsize 

341 

342 return thing_in_pix 

343 

344 

345def flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec, dispersion_axis_angle=0): 

346 """Flip and rotate the ADR shifts in pixels along (RA,DEC) directions to (x, y) image coordinates. 

347 

348 Parameters 

349 ---------- 

350 adr_ra: array_like 

351 ADR shift in pixel along the RA direction. 

352 adr_dec: array_like 

353 ADR shift in pixel along the DEC direction. 

354 dispersion_axis_angle: float, optional 

355 Optional additional angle of the dispersion axis in the (x,y) frame (default: 0). 

356 

357 Returns 

358 ------- 

359 adr_x: array_like 

360 ADR shift in pixel along the x direction. 

361 adr_y: array_like 

362 ADR shift in pixel along the y direction. 

363 

364 Examples 

365 -------- 

366 

367 >>> from spectractor.extractor.spectrum import Spectrum 

368 >>> spec = Spectrum("./tests/data/reduc_20170530_134_spectrum.fits", config="./config/ctio.ini") 

369 

370 Compute ADR in (RA, DEC) frame 

371 

372 >>> adr_ra, adr_dec = adr_calib(spec.lambdas, spec.adr_params, lat=parameters.OBS_LATITUDE, lambda_ref=550) 

373 

374 Compute ADR in (x, y) frame 

375 

376 >>> adr_x, adr_y = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec, dispersion_axis_angle=0) 

377 >>> assert np.all(np.isclose(adr_x, adr_ra)) 

378 >>> assert np.all(np.isclose(adr_y, -adr_dec)) 

379 

380 Compute ADR in (u, v) spectrogram frame 

381 

382 >>> adr_u, adr_v = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec, dispersion_axis_angle=-1.54) 

383 >>> assert adr_x[0] < adr_u[0] 

384 >>> assert adr_y[0] < adr_v[0] 

385 

386 """ 

387 adr_x, adr_y = flip_and_rotate_radec_to_image_xy_coordinates(adr_ra, adr_dec, 

388 camera_angle=parameters.OBS_CAMERA_ROTATION, 

389 flip_ra_sign=parameters.OBS_CAMERA_RA_FLIP_SIGN, 

390 flip_dec_sign=parameters.OBS_CAMERA_DEC_FLIP_SIGN) 

391 if not np.isclose(dispersion_axis_angle, 0, atol=0.001): 

392 # minus sign as rotation matrix is apply on the right on the adr vector 

393 a = - dispersion_axis_angle * np.pi / 180 

394 rotation = np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]], dtype=float) 

395 adr_u, adr_v = (np.asarray([adr_x, adr_y]).T @ rotation).T 

396 return adr_u, adr_v 

397 else: 

398 return adr_x, adr_y