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
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
1from astropy.coordinates import SkyCoord, Distance
2import astropy.units as u
3from astropy.time import Time
5import matplotlib.pyplot as plt
6from scipy.interpolate import interp1d
7import os
8import numpy as np
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)
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
19def load_target(label, verbose=False):
20 """Load the target properties according to the type set by parameters.OBS_OBJECT_TYPE.
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.
25 Parameters
26 ----------
27 label: str
28 The label of the target.
29 verbose: bool, optional
30 If True, more verbosity (default: False).
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}')
59class Target:
61 def __init__(self, label, verbose=False):
62 """Initialize Target class.
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)
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
90class ArcLamp(Target):
92 def __init__(self, label, verbose=False):
93 """Initialize ArcLamp class.
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)
102 Examples
103 --------
105 Mercury-Argon lamp:
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
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])
119 def load(self): # pragma: no cover
120 pass
123class Monochromator(Target):
125 def __init__(self, label, verbose=False):
126 """Initialize Monochromator class.
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)
135 Examples
136 --------
138 >>> t = Monochromator("XX", verbose=False)
139 >>> print(t.label)
140 XX
141 >>> print(t.emission_spectrum)
142 True
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])
150 def load(self): # pragma: no cover
151 pass
154class Star(Target):
156 def __init__(self, label, verbose=False):
157 """Initialize Star class.
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)
166 Examples
167 --------
169 Emission line object:
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
179 Standard star:
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
189 """
190 Target.__init__(self, label, verbose=verbose)
191 self.my_logger = set_logger(self.__class__.__name__)
192 self.simbad = None
193 self.load()
195 def load(self):
196 """Load the coordinates of the target.
198 Examples
199 --------
200 >>> s = Star('3C273')
201 >>> print(s.radec_position.dec)
202 2d03m08.598s
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()
226 def load_spectra(self):
227 """Load reference spectra from Pysynphot database or NED database.
229 If the object redshift is >0.2, the LAMBDA_MIN and LAMBDA_MAX parameters
230 are redshifted accordingly.
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 elif 'HD' in self.label or self.label in parameters.STAR_NAMES: # it is a star
279 self.emission_spectrum = False
280 self.hydrogen_only = False
281 self.lines = Lines(ATMOSPHERIC_LINES + HYDROGEN_LINES + STELLAR_LINES,
282 redshift=self.redshift, emission_spectrum=self.emission_spectrum,
283 hydrogen_only=self.hydrogen_only)
284 else:
285 if 'PNG' not in self.label:
286 # Try with NED query
287 # print 'Loading target %s from NED...' % self.label
289 # currently (pending a new release) astroquery has a race
290 # condition at import time, so putting here rather than at the
291 # module level so that multiple test runners don't run the race
292 from astroquery.ned import Ned
293 ned = Ned.query_object(self.label)
294 hdulists = Ned.get_spectra(self.label, show_progress=False)
295 self.redshift = ned['Redshift'][0]
296 self.emission_spectrum = True
297 self.hydrogen_only = False
298 if self.redshift > 0.2:
299 self.hydrogen_only = True
300 parameters.LAMBDA_MIN *= 1 + self.redshift
301 parameters.LAMBDA_MAX *= 1 + self.redshift
302 self.lines = Lines(ATMOSPHERIC_LINES+ISM_LINES+HYDROGEN_LINES,
303 redshift=self.redshift, emission_spectrum=self.emission_spectrum,
304 hydrogen_only=self.hydrogen_only)
305 for k, h in enumerate(hdulists):
306 if h[0].header['NAXIS'] == 1:
307 self.spectra.append(h[0].data)
308 else:
309 for d in h[0].data:
310 self.spectra.append(d)
311 wave_n = len(h[0].data)
312 if h[0].header['NAXIS'] == 2:
313 wave_n = len(h[0].data.T)
314 wave_step = h[0].header['CDELT1']
315 wave_start = h[0].header['CRVAL1'] - (h[0].header['CRPIX1'] - 1) * wave_step
316 wave_end = wave_start + wave_n * wave_step
317 waves = np.linspace(wave_start, wave_end, wave_n)
318 is_angstrom = False
319 for key in list(h[0].header.keys()):
320 if 'angstrom' in str(h[0].header[key]).lower():
321 is_angstrom = True
322 if is_angstrom:
323 waves *= 0.1
324 if h[0].header['NAXIS'] > 1:
325 for i in range(h[0].header['NAXIS'] + 1):
326 self.wavelengths.append(waves)
327 else:
328 self.wavelengths.append(waves)
329 else:
330 self.emission_spectrum = True
331 self.lines = Lines(ATMOSPHERIC_LINES+ISM_LINES+HYDROGEN_LINES,
332 redshift=self.redshift, emission_spectrum=self.emission_spectrum,
333 hydrogen_only=self.hydrogen_only)
334 self.build_sed()
335 self.my_logger.debug(f"\n\tTarget label: {self.label}"
336 f"\n\tCalspec? {is_calspec}"
337 f"\n\tNumber of spectra: {len(self.spectra)}"
338 f"\n\tRedshift: {self.redshift}"
339 f"\n\tEmission spectrum ? {self.emission_spectrum}"
340 f"\n\tLines: {[l.label for l in self.lines.lines]}")
342 def get_radec_position_after_pm(self, date_obs):
343 target_pmra = self.simbad[0]['PMRA'] * u.mas / u.yr
344 if np.isnan(target_pmra):
345 target_pmra = 0 * u.mas / u.yr
346 target_pmdec = self.simbad[0]['PMDEC'] * u.mas / u.yr
347 if np.isnan(target_pmdec):
348 target_pmdec = 0 * u.mas / u.yr
349 target_parallax = self.simbad[0]['PLX_VALUE'] * u.mas
350 if target_parallax == 0 * u.mas:
351 target_parallax = 1e-4 * u.mas
352 target_coord = SkyCoord(ra=self.radec_position.ra, dec=self.radec_position.dec,
353 distance=Distance(parallax=target_parallax),
354 pm_ra_cosdec=target_pmra, pm_dec=target_pmdec, frame='icrs', equinox="J2000",
355 obstime="J2000")
356 self.radec_position_after_pm = target_coord.apply_space_motion(new_obstime=Time(date_obs))
357 return self.radec_position_after_pm
359 def build_sed(self, index=0):
360 """Interpolate the database reference spectra and return self.sed as a function of the wavelength.
362 Parameters
363 ----------
364 index: int
365 Index of the spectrum stored in the self.spectra list
367 Examples
368 --------
369 >>> s = Star('HD111980')
370 >>> s.build_sed(index=0)
371 >>> s.sed(550)
372 array(1.67605113e-11)
373 """
374 if len(self.spectra) == 0:
375 self.sed = lambda x: np.zeros_like(x)
376 else:
377 self.sed = interp1d(self.wavelengths[index], self.spectra[index], kind='linear', bounds_error=False,
378 fill_value=0.)
380 def plot_spectra(self):
381 """ Plot the spectra stored in the self.spectra list.
383 Examples
384 --------
385 >>> s = Star('HD111980')
386 >>> s.plot_spectra()
387 """
388 # target.load_spectra() ## No global target object available here (SDC)
389 plt.figure() # necessary to create a new plot (SDC)
390 for isp, sp in enumerate(self.spectra):
391 plt.plot(self.wavelengths[isp], sp, label='Spectrum %d' % isp)
392 plt.xlim((300, 1100))
393 plt.xlabel(r'$\lambda$ [nm]')
394 plt.ylabel('Flux')
395 plt.title(self.label)
396 plt.legend()
397 if parameters.DISPLAY: # pragma: no cover
398 plt.show()
399 if parameters.PdfPages:
400 parameters.PdfPages.savefig()
403if __name__ == "__main__": 403 ↛ 404line 403 didn't jump to line 404, because the condition on line 403 was never true
404 import doctest
406 doctest.testmod()