Coverage for spectractor/extractor/targets.py: 14%

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

171 statements  

1from astropy.coordinates import SkyCoord, Distance 

2import astropy.units as u 

3from astropy.time import Time 

4 

5import matplotlib.pyplot as plt 

6from scipy.interpolate import interp1d 

7import os 

8import numpy as np 

9 

10from spectractor import parameters 

11from spectractor.config import set_logger 

12from spectractor.extractor.spectroscopy import (Lines, HGAR_LINES, HYDROGEN_LINES, ATMOSPHERIC_LINES, 

13 ISM_LINES, STELLAR_LINES) 

14 

15if os.getenv("PYSYN_CDBS"): 15 ↛ 16line 15 didn't jump to line 16, because the condition on line 15 was never true

16 import pysynphot as S 

17 

18 

19def load_target(label, verbose=False): 

20 """Load the target properties according to the type set by parameters.OBS_OBJECT_TYPE. 

21 

22 Currently, the type can be either "STAR", "HG-AR" or "MONOCHROMATOR". The label parameter gives the 

23 name of the source and allows to load its specific properties. 

24 

25 Parameters 

26 ---------- 

27 label: str 

28 The label of the target. 

29 verbose: bool, optional 

30 If True, more verbosity (default: False). 

31 

32 Examples 

33 -------- 

34 >>> parameters.OBS_OBJECT_TYPE = "STAR" 

35 >>> t = load_target("HD111980", verbose=False) 

36 >>> print(t.label) 

37 HD111980 

38 >>> print(t.radec_position.dec) 

39 -18d31m20.009s 

40 >>> parameters.OBS_OBJECT_TYPE = "MONOCHROMATOR" 

41 >>> t = load_target("XX", verbose=False) 

42 >>> print(t.label) 

43 XX 

44 >>> parameters.OBS_OBJECT_TYPE = "HG-AR" 

45 >>> t = load_target("XX", verbose=False) 

46 >>> print([line.wavelength for line in t.lines.lines][:5]) 

47 [253.652, 296.728, 302.15, 313.155, 334.148] 

48 """ 

49 if parameters.OBS_OBJECT_TYPE == 'STAR': 

50 return Star(label, verbose) 

51 elif parameters.OBS_OBJECT_TYPE == 'HG-AR': 

52 return ArcLamp(label, verbose) 

53 elif parameters.OBS_OBJECT_TYPE == 'MONOCHROMATOR': 

54 return Monochromator(label, verbose) 

55 else: 

56 raise ValueError(f'Unknown parameters.OBS_OBJECT_TYPE: {parameters.OBS_OBJECT_TYPE}') 

57 

58 

59class Target: 

60 

61 def __init__(self, label, verbose=False): 

62 """Initialize Target class. 

63 

64 Parameters 

65 ---------- 

66 label: str 

67 String label to name the target 

68 verbose: bool, optional 

69 Set True to increase verbosity (default: False) 

70 

71 """ 

72 self.my_logger = set_logger(self.__class__.__name__) 

73 self.label = label 

74 self.type = None 

75 self.wavelengths = [] 

76 self.spectra = [] 

77 self.verbose = verbose 

78 self.emission_spectrum = False 

79 self.hydrogen_only = False 

80 self.sed = None 

81 self.lines = None 

82 self.radec_position = None 

83 self.radec_position_after_pm = None 

84 self.redshift = 0 

85 self.image = None 

86 self.image_x0 = None 

87 self.image_y0 = None 

88 

89 

90class ArcLamp(Target): 

91 

92 def __init__(self, label, verbose=False): 

93 """Initialize ArcLamp class. 

94 

95 Parameters 

96 ---------- 

97 label: str 

98 String label to name the lamp. 

99 verbose: bool, optional 

100 Set True to increase verbosity (default: False) 

101 

102 Examples 

103 -------- 

104 

105 Mercury-Argon lamp: 

106 

107 >>> t = ArcLamp("HG-AR", verbose=False) 

108 >>> print([line.wavelength for line in t.lines.lines][:5]) 

109 [253.652, 296.728, 302.15, 313.155, 334.148] 

110 >>> print(t.emission_spectrum) 

111 True 

112 

113 """ 

114 Target.__init__(self, label, verbose=verbose) 

115 self.my_logger = set_logger(self.__class__.__name__) 

116 self.emission_spectrum = True 

117 self.lines = Lines(HGAR_LINES, emission_spectrum=True, orders=[1, 2]) 

118 

119 def load(self): # pragma: no cover 

120 pass 

121 

122 

123class Monochromator(Target): 

124 

125 def __init__(self, label, verbose=False): 

126 """Initialize Monochromator class. 

127 

128 Parameters 

129 ---------- 

130 label: str 

131 String label to name the monochromator. 

132 verbose: bool, optional 

133 Set True to increase verbosity (default: False) 

134 

135 Examples 

136 -------- 

137 

138 >>> t = Monochromator("XX", verbose=False) 

139 >>> print(t.label) 

140 XX 

141 >>> print(t.emission_spectrum) 

142 True 

143 

144 """ 

145 Target.__init__(self, label, verbose=verbose) 

146 self.my_logger = set_logger(self.__class__.__name__) 

147 self.emission_spectrum = True 

148 self.lines = Lines([], emission_spectrum=True, orders=[1, 2]) 

149 

150 def load(self): # pragma: no cover 

151 pass 

152 

153 

154class Star(Target): 

155 

156 def __init__(self, label, verbose=False): 

157 """Initialize Star class. 

158 

159 Parameters 

160 ---------- 

161 label: str 

162 String label to name the target 

163 verbose: bool, optional 

164 Set True to increase verbosity (default: False) 

165 

166 Examples 

167 -------- 

168 

169 Emission line object: 

170 

171 >>> s = Star('3C273') 

172 >>> print(s.label) 

173 3C273 

174 >>> print(s.radec_position.dec) 

175 2d03m08.598s 

176 >>> print(s.emission_spectrum) 

177 True 

178 

179 Standard star: 

180 

181 >>> s = Star('HD111980') 

182 >>> print(s.label) 

183 HD111980 

184 >>> print(s.radec_position.dec) 

185 -18d31m20.009s 

186 >>> print(s.emission_spectrum) 

187 False 

188 

189 """ 

190 Target.__init__(self, label, verbose=verbose) 

191 self.my_logger = set_logger(self.__class__.__name__) 

192 self.simbad = None 

193 self.load() 

194 

195 def load(self): 

196 """Load the coordinates of the target. 

197 

198 Examples 

199 -------- 

200 >>> s = Star('3C273') 

201 >>> print(s.radec_position.dec) 

202 2d03m08.598s 

203 

204 """ 

205 # currently (pending a new release) astroquery has a race 

206 # condition at import time, so putting here rather than at the 

207 # module level so that multiple test runners don't run the race 

208 from astroquery.simbad import Simbad 

209 Simbad.add_votable_fields('flux(U)', 'flux(B)', 'flux(V)', 'flux(R)', 'flux(I)', 'flux(J)', 'sptype', 

210 'parallax', 'pm', 'z_value') 

211 simbad = Simbad.query_object(self.label) 

212 self.simbad = simbad 

213 if simbad is not None: 

214 if self.verbose or True: 

215 self.my_logger.info(f'\n\tSimbad:\n{simbad}') 

216 self.radec_position = SkyCoord(simbad['RA'][0] + ' ' + simbad['DEC'][0], unit=(u.hourangle, u.deg)) 

217 else: 

218 self.my_logger.warning('Target {} not found in Simbad'.format(self.label)) 

219 self.get_radec_position_after_pm(date_obs="J2000") 

220 if not np.ma.is_masked(simbad['Z_VALUE']): 

221 self.redshift = float(simbad['Z_VALUE']) 

222 else: 

223 self.redshift = 0 

224 self.load_spectra() 

225 

226 def load_spectra(self): 

227 """Load reference spectra from Pysynphot database or NED database. 

228 

229 If the object redshift is >0.2, the LAMBDA_MIN and LAMBDA_MAX parameters 

230 are redshifted accordingly. 

231 

232 Examples 

233 -------- 

234 >>> s = Star('3C273') 

235 >>> print(s.spectra[0][:4]) 

236 [0.0000000e+00 2.5048577e-14 2.4238061e-14 2.4088789e-14] 

237 >>> s = Star('HD111980') 

238 >>> print(s.spectra[0][:4]) 

239 [2.16890002e-13 2.66480010e-13 2.03540011e-13 2.38780004e-13] 

240 >>> s = Star('PKS1510-089') 

241 >>> print(s.redshift) 

242 0.36 

243 >>> print(f'{parameters.LAMBDA_MIN:.1f}, {parameters.LAMBDA_MAX:.1f}') 

244 408.0, 1496.0 

245 >>> print(s.spectra[0][:4]) 

246 [117.34012 139.27621 87.38032 143.0816 ] 

247 """ 

248 self.wavelengths = [] # in nm 

249 self.spectra = [] 

250 # first try with pysynphot 

251 file_names = [] 

252 is_calspec = False 

253 if os.getenv("PYSYN_CDBS") is not None: 

254 dirname = os.path.expandvars('$PYSYN_CDBS/calspec/') 

255 for fname in os.listdir(dirname): 

256 if os.path.isfile(dirname + fname): 

257 if self.label.lower() in fname.lower(): 

258 file_names.append(dirname + fname) 

259 if len(file_names) > 0: 

260 is_calspec = True 

261 self.emission_spectrum = False 

262 self.hydrogen_only = False 

263 self.lines = Lines(HYDROGEN_LINES + ATMOSPHERIC_LINES + STELLAR_LINES, 

264 redshift=self.redshift, emission_spectrum=self.emission_spectrum, 

265 hydrogen_only=self.hydrogen_only) 

266 for k, f in enumerate(file_names): 

267 if '_mod_' in f: 

268 continue 

269 if self.verbose: 

270 self.my_logger.info('\n\tLoading %s' % f) 

271 data = S.FileSpectrum(f, keepneg=True) 

272 if isinstance(data.waveunits, S.units.Angstrom): 

273 self.wavelengths.append(data.wave / 10.) 

274 self.spectra.append(data.flux * 10.) 

275 else: 

276 self.wavelengths.append(data.wave) 

277 self.spectra.append(data.flux) 

278 # TODO DM-33731: the use of self.label in parameters.STAR_NAMES: 

279 # below works for running but breaks a test so needs fixing for DM 

280 elif 'HD' in self.label: # or self.label in parameters.STAR_NAMES: # it is a star 

281 self.emission_spectrum = False 

282 self.hydrogen_only = False 

283 self.lines = Lines(ATMOSPHERIC_LINES + HYDROGEN_LINES + STELLAR_LINES, 

284 redshift=self.redshift, emission_spectrum=self.emission_spectrum, 

285 hydrogen_only=self.hydrogen_only) 

286 else: 

287 if 'PNG' not in self.label: 

288 # Try with NED query 

289 # print 'Loading target %s from NED...' % self.label 

290 

291 # currently (pending a new release) astroquery has a race 

292 # condition at import time, so putting here rather than at the 

293 # module level so that multiple test runners don't run the race 

294 from astroquery.ned import Ned 

295 ned = Ned.query_object(self.label) 

296 hdulists = Ned.get_spectra(self.label, show_progress=False) 

297 self.redshift = ned['Redshift'][0] 

298 self.emission_spectrum = True 

299 self.hydrogen_only = False 

300 if self.redshift > 0.2: 

301 self.hydrogen_only = True 

302 parameters.LAMBDA_MIN *= 1 + self.redshift 

303 parameters.LAMBDA_MAX *= 1 + self.redshift 

304 self.lines = Lines(ATMOSPHERIC_LINES+ISM_LINES+HYDROGEN_LINES, 

305 redshift=self.redshift, emission_spectrum=self.emission_spectrum, 

306 hydrogen_only=self.hydrogen_only) 

307 for k, h in enumerate(hdulists): 

308 if h[0].header['NAXIS'] == 1: 

309 self.spectra.append(h[0].data) 

310 else: 

311 for d in h[0].data: 

312 self.spectra.append(d) 

313 wave_n = len(h[0].data) 

314 if h[0].header['NAXIS'] == 2: 

315 wave_n = len(h[0].data.T) 

316 wave_step = h[0].header['CDELT1'] 

317 wave_start = h[0].header['CRVAL1'] - (h[0].header['CRPIX1'] - 1) * wave_step 

318 wave_end = wave_start + wave_n * wave_step 

319 waves = np.linspace(wave_start, wave_end, wave_n) 

320 is_angstrom = False 

321 for key in list(h[0].header.keys()): 

322 if 'angstrom' in str(h[0].header[key]).lower(): 

323 is_angstrom = True 

324 if is_angstrom: 

325 waves *= 0.1 

326 if h[0].header['NAXIS'] > 1: 

327 for i in range(h[0].header['NAXIS'] + 1): 

328 self.wavelengths.append(waves) 

329 else: 

330 self.wavelengths.append(waves) 

331 else: 

332 self.emission_spectrum = True 

333 self.lines = Lines(ATMOSPHERIC_LINES+ISM_LINES+HYDROGEN_LINES, 

334 redshift=self.redshift, emission_spectrum=self.emission_spectrum, 

335 hydrogen_only=self.hydrogen_only) 

336 self.build_sed() 

337 self.my_logger.debug(f"\n\tTarget label: {self.label}" 

338 f"\n\tCalspec? {is_calspec}" 

339 f"\n\tNumber of spectra: {len(self.spectra)}" 

340 f"\n\tRedshift: {self.redshift}" 

341 f"\n\tEmission spectrum ? {self.emission_spectrum}" 

342 f"\n\tLines: {[l.label for l in self.lines.lines]}") 

343 

344 def get_radec_position_after_pm(self, date_obs): 

345 target_pmra = self.simbad[0]['PMRA'] * u.mas / u.yr 

346 if np.isnan(target_pmra): 

347 target_pmra = 0 * u.mas / u.yr 

348 target_pmdec = self.simbad[0]['PMDEC'] * u.mas / u.yr 

349 if np.isnan(target_pmdec): 

350 target_pmdec = 0 * u.mas / u.yr 

351 target_parallax = self.simbad[0]['PLX_VALUE'] * u.mas 

352 if target_parallax == 0 * u.mas: 

353 target_parallax = 1e-4 * u.mas 

354 target_coord = SkyCoord(ra=self.radec_position.ra, dec=self.radec_position.dec, 

355 distance=Distance(parallax=target_parallax), 

356 pm_ra_cosdec=target_pmra, pm_dec=target_pmdec, frame='icrs', equinox="J2000", 

357 obstime="J2000") 

358 self.radec_position_after_pm = target_coord.apply_space_motion(new_obstime=Time(date_obs)) 

359 return self.radec_position_after_pm 

360 

361 def build_sed(self, index=0): 

362 """Interpolate the database reference spectra and return self.sed as a function of the wavelength. 

363 

364 Parameters 

365 ---------- 

366 index: int 

367 Index of the spectrum stored in the self.spectra list 

368 

369 Examples 

370 -------- 

371 >>> s = Star('HD111980') 

372 >>> s.build_sed(index=0) 

373 >>> s.sed(550) 

374 array(1.67605113e-11) 

375 """ 

376 if len(self.spectra) == 0: 

377 self.sed = lambda x: np.zeros_like(x) 

378 else: 

379 self.sed = interp1d(self.wavelengths[index], self.spectra[index], kind='linear', bounds_error=False, 

380 fill_value=0.) 

381 

382 def plot_spectra(self): 

383 """ Plot the spectra stored in the self.spectra list. 

384 

385 Examples 

386 -------- 

387 >>> s = Star('HD111980') 

388 >>> s.plot_spectra() 

389 """ 

390 # target.load_spectra() ## No global target object available here (SDC) 

391 plt.figure() # necessary to create a new plot (SDC) 

392 for isp, sp in enumerate(self.spectra): 

393 plt.plot(self.wavelengths[isp], sp, label='Spectrum %d' % isp) 

394 plt.xlim((300, 1100)) 

395 plt.xlabel(r'$\lambda$ [nm]') 

396 plt.ylabel('Flux') 

397 plt.title(self.label) 

398 plt.legend() 

399 if parameters.DISPLAY: # pragma: no cover 

400 plt.show() 

401 if parameters.PdfPages: 

402 parameters.PdfPages.savefig() 

403 

404 

405if __name__ == "__main__": 405 ↛ 406line 405 didn't jump to line 406, because the condition on line 405 was never true

406 import doctest 

407 

408 doctest.testmod()