Coverage for spectractor/extractor/spectrum.py: 4%
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 scipy.signal import argrelextrema, savgol_filter
2from scipy.interpolate import interp1d
3from astropy.io import fits
4from scipy import integrate
5from iminuit import Minuit
6import matplotlib.pyplot as plt
7import numpy as np
8import os
10from spectractor import parameters
11from spectractor.config import set_logger, load_config, apply_rebinning_to_parameters
12from spectractor.extractor.dispersers import Hologram
13from spectractor.extractor.targets import load_target
14from spectractor.tools import (ensure_dir, load_fits, plot_image_simple,
15 find_nearest, plot_spectrum_simple, fit_poly1d_legendre, gauss,
16 rescale_x_for_legendre, fit_multigauss_and_bgd, multigauss_and_bgd)
17from spectractor.extractor.psf import load_PSF
18from spectractor.extractor.chromaticpsf import ChromaticPSF
19from spectractor.simulation.adr import adr_calib, flip_and_rotate_adr_to_image_xy_coordinates
20from spectractor.simulation.throughput import TelescopeTransmission
23class Spectrum:
24 """ Class used to store information and methods relative to spectra and their extraction.
26 Attributes
27 ----------
28 my_logger: logging
29 Logging object
30 fast_load: bool
31 If True, only load the spectrum but not the spectrogram.
32 units: str
33 Units of the spectrum.
34 lambdas: array
35 Spectrum wavelengths in nm.
36 data: array
37 Spectrum amplitude array in self.units units.
38 err: array
39 Spectrum amplitude uncertainties in self.units units.
40 cov_matrix: array
41 Spectrum amplitude covariance matrix between wavelengths in self.units units.
42 lambdas_binwidths: array
43 Bin widths of the wavelength array in nm.
44 lambdas_order2: array
45 Spectrum wavelengths for order 2 contamination in nm.
46 data_order2: array
47 Spectrum amplitude array for order 2 contamination in self.units units.
48 err_order2: array
49 Spectrum amplitude uncertainties for order 2 contamination in self.units units.
50 lambda_ref: float
51 Reference wavelength for ADR computations in nm.
52 order: int
53 Index of the diffraction order.
54 x0: array
55 Target position [x,y] in the image in pixels.
56 psf: PSF
57 PSF instance to model the spectrum PSF.
58 chromatic_psf: ChromaticPSF
59 ChromaticPSF object that contains data on the PSF shape and evolution in wavelength.
60 date_obs: str
61 Date of the observation.
62 airmass: float
63 Airmass of the current target.
64 expo: float
65 Exposure time in seconds.
66 disperser_label: str
67 Label of the disperser.
68 filter_label: str:
69 Label of the filter.
70 rotation_angle: float
71 Dispersion axis angle in the image in degrees, positive if anticlockwise.
72 parallactic_angle: float
73 Parallactic angle in degrees.
74 lines: Lines
75 Lines instance that contains data on the emission or absorption lines to be searched and fitted in the spectrum.
76 header: Fits.Header
77 FITS file header.
78 disperser: Disperser
79 Disperser instance that describes the disperser.
80 target: Target
81 Target instance that describes the current exposure.
82 dec: float
83 Declination coordinate of the current exposure.
84 hour_angle float
85 Hour angle coordinate of the current exposure.
86 temperature: float
87 Outside temperature in Celsius degrees.
88 pressure: float
89 Outside pressure in hPa.
90 humidity: float
91 Outside relative humidity in fraction of one.
92 spectrogram: array
93 Spectrogram 2D image in image units.
94 spectrogram_bgd: array
95 Estimated 2D background fitted below the spectrogram in image units.
96 spectrogram_bgd_rms: array
97 Estimated 2D background RMS fitted below the spectrogram in image units.
98 spectrogram_err: array
99 Estimated 2D background uncertainty fitted below the spectrogram in image units.
100 spectrogram_fit: array
101 Best fitting model of the spectrogram in image units.
102 spectrogram_residuals: array
103 Residuals between the spectrogram data and the best fitting model of the spectrogram in image units.
104 spectrogram_x0: float
105 Relative position of the target in the spectrogram array along the x axis.
106 spectrogram_y0: float
107 Relative position of the target in the spectrogram array along the y axis.
108 spectrogram_xmin: int
109 Left index of the spectrogram crop in the image.
110 spectrogram_xmax: int
111 Right index of the spectrogram crop in the image.
112 spectrogram_ymin: int
113 Bottom index of the spectrogram crop in the image.
114 spectrogram_ymax: int
115 Top index of the spectrogram crop in the image.
116 spectrogram_deg: int
117 Degree of the polynomial functions to model wavelength evolutions of the PSF parameters.
118 spectrogram_saturation: float
119 Level of saturation in the spectrogram in image units.
120 spectrogram_Nx: int
121 Size of the spectrogram along the x axis.
122 spectrogram_Ny: int
123 Size of the spectrogram along the y axis.
124 """
126 def __init__(self, file_name="", image=None, order=1, target=None, config="", fast_load=False):
127 """ Class used to store information and methods relative to spectra and their extraction.
129 Parameters
130 ----------
131 file_name: str, optional
132 Path to the spectrum file (default: "").
133 image: Image, optional
134 Image object from which to create the Spectrum object:
135 copy the information from the Image header (default: None).
136 order: int
137 Order of the spectrum (default: 1)
138 target: Target, optional
139 Target object if provided (default: None)
140 config: str, optional
141 A config file name to load some parameter values for a given instrument (default: "").
142 fast_load: bool, optional
143 If True, only the spectrum is loaded (not the PSF nor the spectrogram data) (default: False).
145 Examples
146 --------
147 Load a spectrum from a fits file
148 >>> s = Spectrum(file_name='tests/data/reduc_20170605_028_spectrum.fits')
149 >>> print(s.order)
150 1
151 >>> print(s.target.label)
152 PNG321.0+3.9
153 >>> print(s.disperser_label)
154 HoloPhAg
156 Load a spectrum from a fits image file
157 >>> from spectractor.extractor.images import Image
158 >>> image = Image('tests/data/reduc_20170605_028.fits', target_label='PNG321.0+3.9')
159 >>> s = Spectrum(image=image)
160 >>> print(s.target.label)
161 PNG321.0+3.9
162 """
163 self.fast_load = fast_load
164 self.my_logger = set_logger(self.__class__.__name__)
165 if config != "":
166 load_config(config)
167 self.target = target
168 self.data = None
169 self.err = None
170 self.cov_matrix = None
171 self.x0 = None
172 self.pixels = None
173 self.lambdas = None
174 self.lambdas_binwidths = None
175 self.lambdas_indices = None
176 self.lambda_ref = None
177 self.order = order
178 self.chromatic_psf = None
179 self.filter_label = ""
180 self.filters = None
181 self.units = 'ADU/s'
182 self.gain = parameters.CCD_GAIN
183 self.psf = load_PSF(psf_type="Moffat", target=self.target)
184 self.chromatic_psf = ChromaticPSF(self.psf, Nx=1, Ny=1, deg=1, saturation=1)
185 self.rotation_angle = 0
186 self.parallactic_angle = None
187 self.spectrogram = None
188 self.spectrogram_bgd = None
189 self.spectrogram_bgd_rms = None
190 self.spectrogram_err = None
191 self.spectrogram_residuals = None
192 self.spectrogram_fit = None
193 self.spectrogram_x0 = None
194 self.spectrogram_y0 = None
195 self.spectrogram_xmin = None
196 self.spectrogram_xmax = None
197 self.spectrogram_ymin = None
198 self.spectrogram_ymax = None
199 self.spectrogram_deg = None
200 self.spectrogram_saturation = None
201 self.spectrogram_Nx = None
202 self.spectrogram_Ny = None
203 self.lambdas_order2 = None
204 self.data_order2 = None
205 self.err_order2 = None
206 self.filename = file_name
207 if file_name != "":
208 self.load_spectrum(file_name)
209 if image is not None:
210 self.header = image.header
211 self.date_obs = image.date_obs
212 self.airmass = image.airmass
213 self.expo = image.expo
214 self.filters = image.filters
215 self.filter_label = image.filter_label
216 self.disperser_label = image.disperser_label
217 self.disperser = image.disperser
218 self.target = image.target
219 self.lines = self.target.lines
220 self.x0 = image.target_pixcoords
221 self.target_pixcoords = image.target_pixcoords
222 self.target_pixcoords_rotated = image.target_pixcoords_rotated
223 self.units = image.units
224 self.gain = image.gain
225 self.rotation_angle = image.rotation_angle
226 self.my_logger.info('\n\tSpectrum info copied from image')
227 self.dec = image.dec
228 self.hour_angle = image.hour_angle
229 self.temperature = image.temperature
230 self.pressure = image.pressure
231 self.humidity = image.humidity
232 self.parallactic_angle = image.parallactic_angle
233 self.adr_params = [self.dec, self.hour_angle, self.temperature, self.pressure,
234 self.humidity, self.airmass]
235 self.load_filter()
237 def convert_from_ADUrate_to_flam(self):
238 """Convert units from ADU/s to erg/s/cm^2/nm.
239 The SED is supposed to be in flam units ie erg/s/cm^2/nm
241 Examples
242 --------
243 >>> s = Spectrum(file_name='tests/data/reduc_20170605_028_spectrum.fits')
244 >>> s.convert_from_ADUrate_to_flam()
246 .. doctest::
247 :hide:
249 >>> assert np.max(s.data) < 1e-2
250 >>> assert np.max(s.err) < 1e-2
252 """
253 if self.units == 'erg/s/cm$^2$/nm' or self.units == "flam":
254 self.my_logger.warning(f"You ask to convert spectrum already in {self.units}"
255 f" in erg/s/cm^2/nm... check your code ! Skip the instruction.")
256 return
257 ldl = parameters.FLAM_TO_ADURATE * self.lambdas * np.abs(self.lambdas_binwidths)
258 self.data /= ldl
259 if self.err is not None:
260 self.err /= ldl
261 if self.cov_matrix is not None:
262 ldl_mat = np.outer(ldl, ldl)
263 self.cov_matrix /= ldl_mat
264 if self.data_order2 is not None:
265 ldl_2 = parameters.FLAM_TO_ADURATE * self.lambdas_order2 * np.abs(np.gradient(self.lambdas_order2))
266 self.data_order2 /= ldl_2
267 self.err_order2 /= ldl_2
268 self.units = 'erg/s/cm$^2$/nm'
270 def convert_from_flam_to_ADUrate(self):
271 """Convert units from erg/s/cm^2/nm to ADU/s.
272 The SED is supposed to be in flam units ie erg/s/cm^2/nm
274 Examples
275 --------
276 >>> s = Spectrum(file_name='tests/data/reduc_20170605_028_spectrum.fits')
277 >>> s.convert_from_flam_to_ADUrate()
279 .. doctest::
280 :hide:
282 >>> assert np.max(s.data) > 1e-2
283 >>> assert np.max(s.err) > 1e-2
285 """
286 if self.units == "ADU/s":
287 self.my_logger.warning(f"You ask to convert spectrum already in {self.units} in ADU/s... check your code ! "
288 f"Skip the instruction")
289 return
290 ldl = parameters.FLAM_TO_ADURATE * self.lambdas * np.abs(self.lambdas_binwidths)
291 self.data *= ldl
292 if self.err is not None:
293 self.err *= ldl
294 if self.cov_matrix is not None:
295 ldl_mat = np.outer(ldl, ldl)
296 self.cov_matrix *= ldl_mat
297 if self.data_order2 is not None:
298 ldl_2 = parameters.FLAM_TO_ADURATE * self.lambdas_order2 * np.abs(np.gradient(self.lambdas_order2))
299 self.data_order2 *= ldl_2
300 self.err_order2 *= ldl_2
301 self.units = 'ADU/s'
303 def load_filter(self):
304 """Load filter properties and set relevant LAMBDA_MIN and LAMBDA_MAX values.
306 Examples
307 --------
308 >>> s = Spectrum()
309 >>> s.filter_label = 'FGB37'
310 >>> s.load_filter()
312 .. doctest::
313 :hide:
315 >>> assert np.isclose(parameters.LAMBDA_MIN, 300)
316 >>> assert np.isclose(parameters.LAMBDA_MAX, 760)
318 """
319 if self.filter_label != "" and "empty" not in self.filter_label.lower():
320 t = TelescopeTransmission(filter_label=self.filter_label)
321 t.reset_lambda_range(transmission_threshold=1e-4)
323 def plot_spectrum(self, ax=None, xlim=None, live_fit=False, label='', force_lines=False):
324 """Plot spectrum with emission and absorption lines.
326 Parameters
327 ----------
328 ax: Axes, optional
329 Axes instance (default: None).
330 label: str
331 Label for the legend (default: '').
332 xlim: list, optional
333 List of minimum and maximum abscisses (default: None)
334 live_fit: bool, optional
335 If True the spectrum is plotted in live during the fitting procedures
336 (default: False).
337 force_lines: bool
338 Force the over plot of vertical lines for atomic lines if set to True (default: False).
340 Examples
341 --------
342 >>> s = Spectrum(file_name='tests/data/reduc_20170530_134_spectrum.fits')
343 >>> s.plot_spectrum(xlim=[500,900], live_fit=False, force_lines=True)
344 """
345 if ax is None:
346 plt.figure(figsize=[12, 6])
347 ax = plt.gca()
348 if label == '':
349 label = f'Order {self.order:d} spectrum\n' \
350 r'$D_{\mathrm{CCD}}=' \
351 rf'{self.disperser.D:.2f}\,$mm'
352 if self.x0 is not None:
353 label += rf', $x_0={self.x0[0]:.2f}\,$pix'
354 title = self.target.label
355 if self.lambdas_order2 is not None:
356 distance = self.disperser.grating_lambda_to_pixel(self.lambdas_order2, self.x0, order=2)
357 lambdas_order2_contamination = self.disperser.grating_pixel_to_lambda(distance, self.x0, order=1)
358 data_order2_contamination = self.data_order2 * (self.lambdas_order2 * np.gradient(self.lambdas_order2)) \
359 / (lambdas_order2_contamination * np.gradient(lambdas_order2_contamination))
360 if np.sum(data_order2_contamination) / np.sum(self.data) > 0.01:
361 data_interp = interp1d(self.lambdas, self.data, kind="linear", fill_value="0", bounds_error=False)
362 plot_spectrum_simple(ax, lambdas_order2_contamination,
363 data_interp(lambdas_order2_contamination) + data_order2_contamination,
364 data_err=None, xlim=xlim, label='Order 2 contamination', linestyle="--", lw=1)
365 plot_spectrum_simple(ax, self.lambdas, self.data, data_err=self.err, xlim=xlim, label=label,
366 title=title, units=self.units)
367 if len(self.target.spectra) > 0:
368 for k in range(len(self.target.spectra)):
369 plot_indices = np.logical_and(self.target.wavelengths[k] > np.min(self.lambdas),
370 self.target.wavelengths[k] < np.max(self.lambdas))
371 s = self.target.spectra[k] / np.max(self.target.spectra[k][plot_indices]) * np.max(self.data)
372 ax.plot(self.target.wavelengths[k], s, lw=2, label='Tabulated spectra #%d' % k)
373 if self.lambdas is not None:
374 self.lines.plot_detected_lines(ax, print_table=parameters.VERBOSE)
375 if self.lambdas is not None and self.lines is not None:
376 self.lines.plot_atomic_lines(ax, fontsize=12, force=force_lines)
377 ax.legend(loc='best')
378 if self.filters is not None:
379 ax.get_legend().set_title(self.filters)
380 if parameters.LSST_SAVEFIGPATH: # pragma: no cover
381 plt.gcf().savefig(os.path.join(parameters.LSST_SAVEFIGPATH, f'{self.target.label}_spectrum.pdf'))
382 if parameters.DISPLAY:
383 if live_fit:
384 plt.draw()
385 plt.pause(1e-8)
386 plt.close()
387 else:
388 plt.show()
390 def plot_spectrogram(self, ax=None, scale="lin", title="", units="Image units", plot_stats=False,
391 target_pixcoords=None, vmin=None, vmax=None, figsize=[9.3, 8], aspect=None,
392 cmap=None, cax=None):
393 """Plot spectrogram.
395 Parameters
396 ----------
397 ax: Axes, optional
398 Axes instance (default: None).
399 scale: str
400 Scaling of the image (choose between: lin, log or log10) (default: lin)
401 title: str
402 Title of the image (default: "")
403 units: str
404 Units of the image to be written in the color bar label (default: "Image units")
405 cmap: colormap
406 Color map label (default: None)
407 target_pixcoords: array_like, optional
408 2D array giving the (x,y) coordinates of the targets on the image: add a scatter plot (default: None)
409 vmin: float
410 Minimum value of the image (default: None)
411 vmax: float
412 Maximum value of the image (default: None)
413 aspect: str
414 Aspect keyword to be passed to imshow (default: None)
415 cax: Axes, optional
416 Color bar axes if necessary (default: None).
417 figsize: tuple
418 Figure size (default: [9.3, 8]).
419 plot_stats: bool
420 If True, plot the uncertainty map instead of the spectrogram (default: False).
422 Examples
423 --------
424 >>> s = Spectrum(file_name='tests/data/reduc_20170605_028_spectrum.fits')
425 >>> s.plot_spectrogram()
426 >>> if parameters.DISPLAY: plt.show()
428 .. plot::
430 from spectractor.extractor.spectrum import Spectrum
431 s = Spectrum(file_name='tests/data/reduc_20170605_028_spectrum.fits')
432 s.plot_spectrogram()
434 """
435 if ax is None:
436 plt.figure(figsize=figsize)
437 ax = plt.gca()
438 data = np.copy(self.spectrogram)
439 if plot_stats:
440 data = np.copy(self.spectrogram_err)
441 plot_image_simple(ax, data=data, scale=scale, title=title, units=units, cax=cax,
442 target_pixcoords=target_pixcoords, aspect=aspect, vmin=vmin, vmax=vmax, cmap=cmap)
443 if parameters.DISPLAY:
444 plt.show()
445 if parameters.PdfPages:
446 parameters.PdfPages.savefig()
448 def save_spectrum(self, output_file_name, overwrite=False):
449 """Save the spectrum into a fits file (data, error and wavelengths).
451 Parameters
452 ----------
453 output_file_name: str
454 Path of the output fits file.
455 overwrite: bool
456 If True overwrite the output file if needed (default: False).
458 Examples
459 --------
460 >>> import os
461 >>> s = Spectrum(file_name='tests/data/reduc_20170530_134_spectrum.fits')
462 >>> s.save_spectrum('./tests/test.fits')
464 .. doctest::
465 :hide:
467 >>> assert os.path.isfile('./tests/test.fits')
469 Overwrite previous file:
470 >>> s.save_spectrum('./tests/test.fits', overwrite=True)
472 .. doctest::
473 :hide:
475 >>> assert os.path.isfile('./tests/test.fits')
476 >>> os.remove('./tests/test.fits')
477 """
478 self.header["REBIN"] = parameters.CCD_REBIN
479 self.header.comments['REBIN'] = 'original image rebinning factor to get spectrum.'
480 self.header['UNIT1'] = "nanometer"
481 self.header['UNIT2'] = self.units
482 self.header['COMMENTS'] = 'First column gives the wavelength in unit UNIT1, ' \
483 'second column gives the spectrum in unit UNIT2, ' \
484 'third column the corresponding errors.'
485 hdu1 = fits.PrimaryHDU()
486 hdu1.header = self.header
487 hdu1.header["EXTNAME"] = "SPECTRUM"
488 hdu2 = fits.ImageHDU()
489 hdu2.header["EXTNAME"] = "SPEC_COV"
490 hdu3 = fits.ImageHDU()
491 hdu3.header["EXTNAME"] = "ORDER2"
492 hdu4 = fits.ImageHDU()
493 hdu4.header["EXTNAME"] = "ORDER0"
494 hdu1.data = [self.lambdas, self.data, self.err]
495 hdu2.data = self.cov_matrix
496 hdu3.data = [self.lambdas_order2, self.data_order2, self.err_order2]
497 hdu4.data = self.target.image
498 hdu4.header["IM_X0"] = self.target.image_x0
499 hdu4.header["IM_Y0"] = self.target.image_y0
500 hdu = fits.HDUList([hdu1, hdu2, hdu3, hdu4])
501 output_directory = '/'.join(output_file_name.split('/')[:-1])
502 ensure_dir(output_directory)
503 hdu.writeto(output_file_name, overwrite=overwrite)
504 self.my_logger.info(f'\n\tSpectrum saved in {output_file_name}')
506 def save_spectrogram(self, output_file_name, overwrite=False):
507 """Save the spectrogram into a fits file (data, error and background).
509 Parameters
510 ----------
511 output_file_name: str
512 Path of the output fits file.
513 overwrite: bool, optional
514 If True overwrite the output file if needed (default: False).
516 Examples
517 --------
518 """
519 self.header['UNIT1'] = self.units
520 self.header['COMMENTS'] = 'First HDU gives the data in UNIT1 units, ' \
521 'second HDU gives the uncertainties, ' \
522 'third HDU the fitted background.'
523 self.header['S_X0'] = self.spectrogram_x0
524 self.header['S_Y0'] = self.spectrogram_y0
525 self.header['S_XMIN'] = self.spectrogram_xmin
526 self.header['S_XMAX'] = self.spectrogram_xmax
527 self.header['S_YMIN'] = self.spectrogram_ymin
528 self.header['S_YMAX'] = self.spectrogram_ymax
529 self.header['S_DEG'] = self.spectrogram_deg
530 self.header['S_SAT'] = self.spectrogram_saturation
531 hdu1 = fits.PrimaryHDU()
532 hdu1.header["EXTNAME"] = "S_DATA"
533 hdu2 = fits.ImageHDU()
534 hdu2.header["EXTNAME"] = "S_ERR"
535 hdu3 = fits.ImageHDU()
536 hdu3.header["EXTNAME"] = "S_BGD"
537 hdu4 = fits.ImageHDU()
538 hdu4.header["EXTNAME"] = "S_BGD_ER"
539 hdu5 = fits.ImageHDU()
540 hdu5.header["EXTNAME"] = "S_FIT"
541 hdu6 = fits.ImageHDU()
542 hdu6.header["EXTNAME"] = "S_RES"
543 hdu1.header = self.header
544 hdu1.data = self.spectrogram
545 hdu2.data = self.spectrogram_err
546 hdu3.data = self.spectrogram_bgd
547 hdu4.data = self.spectrogram_bgd_rms
548 hdu5.data = self.spectrogram_fit
549 hdu6.data = self.spectrogram_residuals
550 hdu = fits.HDUList([hdu1, hdu2, hdu3, hdu4, hdu5, hdu6])
551 output_directory = '/'.join(output_file_name.split('/')[:-1])
552 ensure_dir(output_directory)
553 hdu.writeto(output_file_name, overwrite=overwrite)
554 self.my_logger.info('\n\tSpectrogram saved in %s' % output_file_name)
556 def load_spectrum(self, input_file_name):
557 """Load the spectrum from a fits file (data, error and wavelengths).
559 Parameters
560 ----------
561 input_file_name: str
562 Path to the input fits file
564 Examples
565 --------
566 >>> s = Spectrum()
567 >>> s.load_spectrum('tests/data/reduc_20170605_028_spectrum.fits')
568 >>> print(s.units)
569 erg/s/cm$^2$/nm
570 """
571 if os.path.isfile(input_file_name):
572 self.header, raw_data = load_fits(input_file_name)
573 self.lambdas = raw_data[0]
574 self.lambdas_binwidths = np.gradient(self.lambdas)
575 self.data = raw_data[1]
576 if len(raw_data) > 2:
577 self.err = raw_data[2]
578 if self.header['DATE-OBS'] != "":
579 self.date_obs = self.header['DATE-OBS']
580 if self.header['EXPTIME'] != "":
581 self.expo = self.header['EXPTIME']
582 if self.header['AIRMASS'] != "":
583 self.airmass = self.header['AIRMASS']
584 if self.header['GRATING'] != "":
585 self.disperser_label = self.header['GRATING']
586 if self.header['TARGET'] != "":
587 self.target = load_target(self.header['TARGET'], verbose=parameters.VERBOSE)
588 self.lines = self.target.lines
589 if self.header['UNIT2'] != "":
590 self.units = self.header['UNIT2']
591 if self.header['ROTANGLE'] != "":
592 self.rotation_angle = self.header['ROTANGLE']
593 if self.header['TARGETX'] != "" and self.header['TARGETY'] != "":
594 self.x0 = [self.header['TARGETX'], self.header['TARGETY']]
595 if self.header['D2CCD'] != "":
596 parameters.DISTANCE2CCD = float(self.header["D2CCD"])
597 if 'DEC' in self.header and self.header['DEC'] != "":
598 self.dec = self.header['DEC']
599 if 'RA' in self.header and self.header['HA'] != "":
600 self.hour_angle = self.header['HA']
601 if 'OUTTEMP' in self.header and self.header['OUTTEMP'] != "":
602 self.temperature = self.header['OUTTEMP']
603 if 'OUTPRESS' in self.header and self.header['OUTPRESS'] != "":
604 self.pressure = self.header['OUTPRESS']
605 if 'OUTHUM' in self.header and self.header['OUTHUM'] != "":
606 self.humidity = self.header['OUTHUM']
607 if self.header['LBDA_REF'] != "":
608 self.lambda_ref = self.header['LBDA_REF']
609 if 'PARANGLE' in self.header and self.header['PARANGLE'] != "":
610 self.parallactic_angle = self.header['PARANGLE']
611 if 'CCDREBIN' in self.header and self.header['CCDREBIN'] != "":
612 if parameters.CCD_REBIN != self.header['CCDREBIN']:
613 raise ValueError("Different values of rebinning parameters between config file and header. Choose.")
615 self.my_logger.info('\n\tLoading disperser %s...' % self.disperser_label)
616 self.disperser = Hologram(self.disperser_label, D=parameters.DISTANCE2CCD,
617 data_dir=parameters.DISPERSER_DIR, verbose=parameters.VERBOSE)
618 self.my_logger.info('\n\tSpectrum loaded from %s' % input_file_name)
619 spectrogram_file_name = input_file_name.replace('spectrum', 'spectrogram')
620 if parameters.OBS_OBJECT_TYPE == "STAR":
621 self.adr_params = [self.dec, self.hour_angle, self.temperature,
622 self.pressure, self.humidity, self.airmass]
624 hdu_list = fits.open(input_file_name)
625 if len(hdu_list) > 1:
626 self.cov_matrix = hdu_list["SPEC_COV"].data
627 if len(hdu_list) > 2:
628 self.lambdas_order2, self.data_order2, self.err_order2 = hdu_list["ORDER2"].data
629 if len(hdu_list) > 3:
630 self.target.image = hdu_list["ORDER0"].data
631 self.target.image_x0 = float(hdu_list["ORDER0"].header["IM_X0"])
632 self.target.image_y0 = float(hdu_list["ORDER0"].header["IM_Y0"])
633 else:
634 self.cov_matrix = np.diag(self.err ** 2)
635 if not self.fast_load:
636 self.my_logger.info(f'\n\tLoading spectrogram from {spectrogram_file_name}...')
637 if os.path.isfile(spectrogram_file_name):
638 self.load_spectrogram(spectrogram_file_name)
639 else:
640 raise FileNotFoundError(f"Spectrogram file {spectrogram_file_name} does not exist.")
641 psf_file_name = input_file_name.replace('spectrum.fits', 'table.csv')
642 self.my_logger.info(f'\n\tLoading PSF from {psf_file_name}...')
643 if os.path.isfile(psf_file_name):
644 self.load_chromatic_psf(psf_file_name)
645 else:
646 raise FileNotFoundError(f"PSF file {psf_file_name} does not exist.")
647 else:
648 raise FileNotFoundError(f'\n\tSpectrum file {input_file_name} not found')
650 def load_spectrogram(self, input_file_name):
651 """Load the spectrum from a fits file (data, error and wavelengths).
653 Parameters
654 ----------
655 input_file_name: str
656 Path to the input fits file
658 Examples
659 --------
660 >>> s = Spectrum()
661 >>> s.load_spectrum('tests/data/reduc_20170605_028_spectrum.fits')
662 """
663 if os.path.isfile(input_file_name):
664 hdu_list = fits.open(input_file_name)
665 header = hdu_list[0].header
666 self.spectrogram = hdu_list[0].data
667 self.spectrogram_err = hdu_list[1].data
668 self.spectrogram_bgd = hdu_list[2].data
669 if len(hdu_list) > 3:
670 self.spectrogram_bgd_rms = hdu_list[3].data
671 self.spectrogram_fit = hdu_list[4].data
672 self.spectrogram_residuals = hdu_list[5].data
673 self.spectrogram_x0 = float(header['S_X0'])
674 self.spectrogram_y0 = float(header['S_Y0'])
675 self.spectrogram_xmin = int(header['S_XMIN'])
676 self.spectrogram_xmax = int(header['S_XMAX'])
677 self.spectrogram_ymin = int(header['S_YMIN'])
678 self.spectrogram_ymax = int(header['S_YMAX'])
679 self.spectrogram_deg = int(header['S_DEG'])
680 self.spectrogram_saturation = float(header['S_SAT'])
681 self.spectrogram_Nx = self.spectrogram_xmax - self.spectrogram_xmin
682 self.spectrogram_Ny = self.spectrogram_ymax - self.spectrogram_ymin
683 hdu_list.close() # need to free allocation for file descripto
684 self.my_logger.info('\n\tSpectrogram loaded from %s' % input_file_name)
685 else:
686 self.my_logger.warning('\n\tSpectrogram file %s not found' % input_file_name)
688 def load_chromatic_psf(self, input_file_name):
689 """Load the spectrum from a fits file (data, error and wavelengths).
691 Parameters
692 ----------
693 input_file_name: str
694 Path to the input fits file
696 Examples
697 --------
698 >>> s = Spectrum()
699 >>> s.load_spectrum('./tests/data/reduc_20170530_134_spectrum.fits')
700 >>> print(s.chromatic_psf.table) #doctest: +ELLIPSIS
701 lambdas Dx ...
702 """
703 if os.path.isfile(input_file_name):
704 self.psf = load_PSF(psf_type=parameters.PSF_TYPE, target=self.target)
705 self.chromatic_psf = ChromaticPSF(self.psf, self.spectrogram_Nx, self.spectrogram_Ny,
706 x0=self.spectrogram_x0, y0=self.spectrogram_y0,
707 deg=self.spectrogram_deg, saturation=self.spectrogram_saturation,
708 file_name=input_file_name)
709 if 'PSF_REG' in self.header and float(self.header["PSF_REG"]) > 0:
710 self.chromatic_psf.opt_reg = float(self.header["PSF_REG"])
711 self.my_logger.info(f'\n\tSpectrogram loaded from {input_file_name}')
712 else:
713 self.my_logger.warning(f'\n\tSpectrogram file {input_file_name} not found')
716def detect_lines(lines, lambdas, spec, spec_err=None, cov_matrix=None, fwhm_func=None, snr_minlevel=3, ax=None,
717 calibration_lines_only=False,
718 xlim=(parameters.LAMBDA_MIN, parameters.LAMBDA_MAX)):
719 """Detect and fit the lines in a spectrum. The method is to look at maxima or minima
720 around emission or absorption tabulated lines, and to select surrounding pixels
721 to fit a (positive or negative) gaussian and a polynomial background. If several regions
722 overlap, a multi-gaussian fit is performed above a common polynomial background.
723 The mean global shift (in nm) between the detected and tabulated lines is returned, considering
724 only the lines with a signal-to-noise ratio above a threshold.
725 The order of the polynomial background is set in parameters.py with CALIB_BGD_ORDER.
727 Parameters
728 ----------
729 lines: Lines
730 The Lines object containing the line characteristics
731 lambdas: float array
732 The wavelength array (in nm)
733 spec: float array
734 The spectrum amplitude array
735 spec_err: float array, optional
736 The spectrum amplitude uncertainty array (default: None)
737 cov_matrix: float array, optional
738 The spectrum amplitude 2D covariance matrix array (default: None)
739 fwhm_func: callable, optional
740 The fwhm of the cross spectrum to reset CALIB_PEAK_WIDTH parameter as a function of lambda (default: None)
741 snr_minlevel: float
742 The minimum signal over noise ratio to consider using a fitted line in the computation of the mean
743 shift output and to print it in the outpur table (default: 3)
744 ax: Axes, optional
745 An Axes instance to over plot the result of the fit (default: None).
746 calibration_lines_only: bool, optional
747 If True, try to detect only the lines with use_for_calibration attributes set True.
748 xlim: array, optional
749 (min, max) list limiting the wavelength interval where to detect spectral lines (default:
750 (parameters.LAMBDA_MIN, parameters.LAMBDA_MAX))
752 Returns
753 -------
754 shift: float
755 The mean shift (in nm) between the detected and tabulated lines
757 Examples
758 --------
760 Creation of a mock spectrum with emission and absorption lines:
762 >>> import numpy as np
763 >>> from spectractor.extractor.spectroscopy import Lines, HALPHA, HBETA, O2_1
764 >>> lambdas = np.arange(300,1000,1)
765 >>> spectrum = 1e4*np.exp(-((lambdas-600)/200)**2)
766 >>> spectrum += HALPHA.gaussian_model(lambdas, A=5000, sigma=3)
767 >>> spectrum += HBETA.gaussian_model(lambdas, A=3000, sigma=2)
768 >>> spectrum += O2_1.gaussian_model(lambdas, A=-3000, sigma=7)
769 >>> spectrum_err = np.sqrt(spectrum)
770 >>> cov = np.diag(spectrum_err)
771 >>> spectrum = np.random.poisson(spectrum)
772 >>> spec = Spectrum()
773 >>> spec.lambdas = lambdas
774 >>> spec.data = spectrum
775 >>> spec.err = spectrum_err
776 >>> fwhm_func = interp1d(lambdas, 0.01 * lambdas)
778 Detect the lines:
780 >>> lines = Lines([HALPHA, HBETA, O2_1], hydrogen_only=True,
781 ... atmospheric_lines=True, redshift=0, emission_spectrum=True)
782 >>> global_chisq = detect_lines(lines, lambdas, spectrum, spectrum_err, cov, fwhm_func=fwhm_func)
784 .. doctest::
785 :hide:
787 >>> assert(global_chisq < 2)
789 Plot the result:
791 >>> import matplotlib.pyplot as plt
792 >>> spec.lines = lines
793 >>> fig = plt.figure()
794 >>> plot_spectrum_simple(plt.gca(), lambdas, spec.data, data_err=spec.err)
795 >>> lines.plot_detected_lines(plt.gca())
796 >>> if parameters.DISPLAY: plt.show()
797 """
799 # main settings
800 peak_width = parameters.CALIB_PEAK_WIDTH
801 bgd_width = parameters.CALIB_BGD_WIDTH
802 # if lines.hydrogen_only:
803 # peak_width = 7
804 # bgd_width = 15
805 fwhm_to_peak_width_factor = 1.5
806 len_index_to_bgd_npar_factor = 0 * 0.12 / 0.024 * parameters.CCD_PIXEL2MM
807 baseline_prior = 3 # *sigma gaussian prior on base line fit
808 # filter the noise
809 # plt.errorbar(lambdas,spec,yerr=spec_err)
810 spec = np.copy(spec)
811 spec_smooth = savgol_filter(spec, parameters.CALIB_SAVGOL_WINDOW, parameters.CALIB_SAVGOL_ORDER)
812 # plt.plot(lambdas,spec)
813 # plt.show()
814 # initialisation
815 lambda_shifts = []
816 snrs = []
817 index_list = []
818 bgd_npar_list = []
819 peak_index_list = []
820 guess_list = []
821 bounds_list = []
822 lines_list = []
823 for line in lines.lines:
824 # reset line fit attributes
825 line.fitted = False
826 line.fit_popt = None
827 line.high_snr = False
828 if not line.use_for_calibration and calibration_lines_only:
829 continue
830 # wavelength of the line: find the nearest pixel index
831 line_wavelength = line.wavelength
832 if fwhm_func is not None:
833 peak_width = max(fwhm_to_peak_width_factor * fwhm_func(line_wavelength), parameters.CALIB_PEAK_WIDTH)
834 if line_wavelength < xlim[0] or line_wavelength > xlim[1]:
835 continue
836 l_index, l_lambdas = find_nearest(lambdas, line_wavelength)
837 # reject if pixel index is too close to image bounds
838 if l_index < peak_width or l_index > len(lambdas) - peak_width:
839 continue
840 # search for local extrema to detect emission or absorption line
841 # around pixel index +/- peak_width
842 line_strategy = np.greater # look for emission line
843 bgd_strategy = np.less
844 if not lines.emission_spectrum or line.atmospheric:
845 line_strategy = np.less # look for absorption line
846 bgd_strategy = np.greater
847 index = np.arange(l_index - peak_width, l_index + peak_width, 1).astype(int)
848 # skip if data is masked with NaN
849 if np.any(np.isnan(spec_smooth[index])):
850 continue
851 extrema = argrelextrema(spec_smooth[index], line_strategy)
852 if len(extrema[0]) == 0:
853 continue
854 peak_index = index[0] + extrema[0][0]
855 # if several extrema, look for the greatest
856 if len(extrema[0]) > 1:
857 if line_strategy == np.greater:
858 test = -1e20
859 for m in extrema[0]:
860 idx = index[0] + m
861 if spec_smooth[idx] > test:
862 peak_index = idx
863 test = spec_smooth[idx]
864 elif line_strategy == np.less:
865 test = 1e20
866 for m in extrema[0]:
867 idx = index[0] + m
868 if spec_smooth[idx] < test:
869 peak_index = idx
870 test = spec_smooth[idx]
871 # search for first local minima around the local maximum
872 # or for first local maxima around the local minimum
873 # around +/- 3*peak_width
874 index_inf = peak_index - 1 # extrema on the left
875 while index_inf > max(0, peak_index - 3 * peak_width):
876 test_index = np.arange(index_inf, peak_index, 1).astype(int)
877 minm = argrelextrema(spec_smooth[test_index], bgd_strategy)
878 if len(minm[0]) > 0:
879 index_inf = index_inf + minm[0][0]
880 break
881 else:
882 index_inf -= 1
883 index_sup = peak_index + 1 # extrema on the right
884 while index_sup < min(len(spec_smooth) - 1, peak_index + 3 * peak_width):
885 test_index = np.arange(peak_index, index_sup, 1).astype(int)
886 minm = argrelextrema(spec_smooth[test_index], bgd_strategy)
887 if len(minm[0]) > 0:
888 index_sup = peak_index + minm[0][0]
889 break
890 else:
891 index_sup += 1
892 index_sup = max(index_sup, peak_index + peak_width)
893 index_inf = min(index_inf, peak_index - peak_width)
894 # pixel range to consider around the peak, adding bgd_width pixels
895 # to fit for background around the peak
896 index = list(np.arange(max(0, index_inf - bgd_width),
897 min(len(lambdas), index_sup + bgd_width), 1).astype(int))
898 # skip if data is masked with NaN
899 if np.any(np.isnan(spec_smooth[index])):
900 continue
901 # first guess and bounds to fit the line properties and
902 # the background with CALIB_BGD_ORDER order polynom
903 # guess = [0] * bgd_npar + [0.5 * np.max(spec_smooth[index]), lambdas[peak_index],
904 # 0.5 * (line.width_bounds[0] + line.width_bounds[1])]
905 bgd_npar = max(parameters.CALIB_BGD_NPARAMS, int(len_index_to_bgd_npar_factor * (index[-1] - index[0])))
906 bgd_npar_list.append(bgd_npar)
907 guess = [0] * bgd_npar + [0.5 * np.max(spec_smooth[index]), line_wavelength,
908 0.5 * (line.width_bounds[0] + line.width_bounds[1])]
909 if line_strategy == np.less:
910 # noinspection PyTypeChecker
911 guess[bgd_npar] = -0.5 * np.max(spec_smooth[index]) # look for abosrption under bgd
912 # bounds = [[-np.inf] * bgd_npar + [-abs(np.max(spec[index])), lambdas[index_inf], line.width_bounds[0]],
913 # [np.inf] * bgd_npar + [abs(np.max(spec[index])), lambdas[index_sup], line.width_bounds[1]]]
914 bounds = [[-np.inf] * bgd_npar + [-abs(np.max(spec[index])), line_wavelength - peak_width / 2,
915 line.width_bounds[0]],
916 [np.inf] * bgd_npar + [abs(np.max(spec[index])), line_wavelength + peak_width / 2,
917 line.width_bounds[1]]]
918 # gaussian amplitude bounds depend if line is emission/absorption
919 if line_strategy == np.less:
920 bounds[1][bgd_npar] = 0 # look for absorption under bgd
921 else:
922 bounds[0][bgd_npar] = 0 # look for emission above bgd
923 peak_index_list.append(peak_index)
924 index_list.append(index)
925 lines_list.append(line)
926 guess_list.append(guess)
927 bounds_list.append(bounds)
928 # now gather lines together if pixel index ranges overlap
929 idx = 0
930 merges = [[0]]
931 while idx < len(index_list) - 1:
932 idx = merges[-1][-1]
933 if idx == len(index_list) - 1:
934 break
935 if index_list[idx + 1][0] > index_list[idx][0]: # increasing order
936 if index_list[idx][-1] > index_list[idx + 1][0]:
937 merges[-1].append(idx + 1)
938 else:
939 merges.append([idx + 1])
940 idx += 1
941 else: # decreasing order
942 if index_list[idx][0] < index_list[idx + 1][-1]:
943 merges[-1].append(idx + 1)
944 else:
945 merges.append([idx + 1])
946 idx += 1
947 # reorder merge list with respect to lambdas in guess list
948 new_merges = []
949 for merge in merges:
950 if len(guess_list) == 0:
951 continue
952 tmp_guess = [guess_list[i][-2] for i in merge]
953 new_merges.append([x for _, x in sorted(zip(tmp_guess, merge))])
954 # reorder lists with merges
955 new_peak_index_list = []
956 new_index_list = []
957 new_guess_list = []
958 new_bounds_list = []
959 new_lines_list = []
960 for merge in new_merges:
961 new_peak_index_list.append([])
962 new_index_list.append([])
963 new_guess_list.append([])
964 new_bounds_list.append([[], []])
965 new_lines_list.append([])
966 for i in merge:
967 # add the bgd parameters
968 bgd_npar = bgd_npar_list[i]
969 # if i == merge[0]:
970 # new_guess_list[-1] += guess_list[i][:bgd_npar]
971 # new_bounds_list[-1][0] += bounds_list[i][0][:bgd_npar]
972 # new_bounds_list[-1][1] += bounds_list[i][1][:bgd_npar]
973 # add the gauss parameters
974 new_peak_index_list[-1].append(peak_index_list[i])
975 new_index_list[-1] += index_list[i]
976 new_guess_list[-1] += guess_list[i][bgd_npar:]
977 new_bounds_list[-1][0] += bounds_list[i][0][bgd_npar:]
978 new_bounds_list[-1][1] += bounds_list[i][1][bgd_npar:]
979 new_lines_list[-1].append(lines_list[i])
980 # set central peak bounds exactly between two close lines
981 for k in range(len(merge) - 1):
982 new_bounds_list[-1][0][3 * (k + 1) + 1] = 0.5 * (
983 new_guess_list[-1][3 * k + 1] + new_guess_list[-1][3 * (k + 1) + 1])
984 new_bounds_list[-1][1][3 * k + 1] = 0.5 * (
985 new_guess_list[-1][3 * k + 1] + new_guess_list[-1][3 * (k + 1) + 1]) + 1e-3
986 # last term is to avoid equalities
987 # between bounds in some pathological case
988 # sort pixel indices and remove doublons
989 new_index_list[-1] = sorted(list(set(new_index_list[-1])))
990 # fit the line subsets and background
991 global_chisq = 0
992 for k in range(len(new_index_list)):
993 # first guess for the base line with the lateral bands
994 peak_index = new_peak_index_list[k]
995 index = new_index_list[k]
996 guess = new_guess_list[k]
997 bounds = new_bounds_list[k]
998 bgd_index = []
999 if fwhm_func is not None:
1000 peak_width = fwhm_to_peak_width_factor * np.mean(fwhm_func(lambdas[index]))
1001 for i in index:
1002 is_close_to_peak = False
1003 for j in peak_index:
1004 if abs(i - j) < peak_width:
1005 is_close_to_peak = True
1006 break
1007 if not is_close_to_peak:
1008 bgd_index.append(i)
1009 # add background guess and bounds
1010 bgd_npar = max(parameters.CALIB_BGD_ORDER + 1, int(len_index_to_bgd_npar_factor * len(bgd_index)))
1011 parameters.CALIB_BGD_NPARAMS = bgd_npar
1012 guess = [0] * bgd_npar + guess
1013 bounds[0] = [-np.inf] * bgd_npar + bounds[0]
1014 bounds[1] = [np.inf] * bgd_npar + bounds[1]
1015 if len(bgd_index) > 0:
1016 try:
1017 if spec_err is not None:
1018 w = 1. / spec_err[bgd_index]
1019 else:
1020 w = np.ones_like(lambdas[bgd_index])
1021 fit, cov, model = fit_poly1d_legendre(lambdas[bgd_index], spec[bgd_index], order=bgd_npar - 1, w=w)
1022 except:
1023 if spec_err is not None:
1024 w = 1. / spec_err[index]
1025 else:
1026 w = np.ones_like(lambdas[index])
1027 fit, cov, model = fit_poly1d_legendre(lambdas[index], spec[index], order=bgd_npar - 1, w=w)
1028 else:
1029 if spec_err is not None:
1030 w = 1. / spec_err[index]
1031 else:
1032 w = np.ones_like(lambdas[index])
1033 fit, cov, model = fit_poly1d_legendre(lambdas[index], spec[index], order=bgd_npar - 1, w=w)
1034 # lines.my_logger.warning(f'{bgd_npar} {fit}')
1035 # fig = plt.figure()
1036 # plt.plot(lambdas[index], spec[index])
1037 # plt.plot(lambdas[bgd_index], spec[bgd_index], 'ro')
1038 # x_norm = rescale_x_for_legendre(lambdas[index])
1039 # lines.my_logger.warning(f'tototot {x_norm}')
1040 # plt.plot(lambdas[index], np.polynomial.legendre.legval(x_norm, fit), 'b-')
1041 # plt.plot(lambdas[bgd_index], model, 'b--')
1042 # plt.title(f"{fit}")
1043 # plt.show()
1044 for n in range(bgd_npar):
1045 # guess[n] = getattr(bgd, bgd.param_names[parameters.CALIB_BGD_ORDER - n]).value
1046 guess[n] = fit[n]
1047 b = abs(baseline_prior * guess[n])
1048 if np.isclose(b, 0, rtol=1e-2 * float(np.mean(spec_smooth[bgd_index]))):
1049 b = baseline_prior * np.std(spec_smooth[bgd_index])
1050 if np.isclose(b, 0, rtol=1e-2 * float(np.mean(spec_smooth[bgd_index]))):
1051 b = np.inf
1052 bounds[0][n] = guess[n] - b
1053 bounds[1][n] = guess[n] + b
1054 for j in range(len(new_lines_list[k])):
1055 idx = new_peak_index_list[k][j]
1056 x_norm = rescale_x_for_legendre(lambdas[idx])
1057 guess[bgd_npar + 3 * j] = np.sign(guess[bgd_npar + 3 * j]) * abs(
1058 spec_smooth[idx] - np.polynomial.legendre.legval(x_norm, guess[:bgd_npar]))
1059 if np.sign(guess[bgd_npar + 3 * j]) < 0: # absorption
1060 bounds[0][bgd_npar + 3 * j] = 2 * guess[bgd_npar + 3 * j]
1061 else: # emission
1062 bounds[1][bgd_npar + 3 * j] = 2 * guess[bgd_npar + 3 * j]
1063 # fit local extrema with a multigaussian + CALIB_BGD_ORDER polynom
1064 # account for the spectrum uncertainties if provided
1065 sigma = None
1066 if spec_err is not None:
1067 sigma = spec_err[index]
1068 if cov_matrix is not None:
1069 sigma = cov_matrix[index, index]
1070 # my_logger.warning(f'\n{guess} {np.mean(spec[bgd_index])} {np.std(spec[bgd_index])}')
1071 popt, pcov = fit_multigauss_and_bgd(lambdas[index], spec[index], guess=guess, bounds=bounds, sigma=sigma)
1072 # noise level defined as the std of the residuals if no error
1073 noise_level = np.std(spec[index] - multigauss_and_bgd(lambdas[index], *popt))
1074 # otherwise mean of error bars of bgd lateral bands
1075 if sigma is not None:
1076 chisq = np.sum((multigauss_and_bgd(lambdas[index], *popt) - spec[index]) ** 2 / (sigma * sigma))
1077 else:
1078 chisq = np.sum((multigauss_and_bgd(lambdas[index], *popt) - spec[index]) ** 2)
1079 chisq /= len(index)
1080 global_chisq += chisq
1081 if spec_err is not None:
1082 noise_level = np.sqrt(np.mean(spec_err[index] ** 2))
1084 for j in range(len(new_lines_list[k])):
1085 line = new_lines_list[k][j]
1086 peak_pos = popt[bgd_npar + 3 * j + 1]
1087 # FWHM
1088 FWHM = np.abs(popt[bgd_npar + 3 * j + 2]) * 2.355
1089 # SNR computation
1090 # signal_level = popt[bgd_npar+3*j]
1091 signal_level = popt[
1092 bgd_npar + 3 * j] # multigauss_and_bgd(peak_pos, *popt) - np.polyval(popt[:bgd_npar], peak_pos)
1093 snr = np.abs(signal_level / noise_level)
1094 # save fit results
1095 line.fitted = True
1096 line.fit_index = index
1097 line.fit_lambdas = lambdas[index]
1099 x_norm = rescale_x_for_legendre(lambdas[index])
1101 x_step = 0.1 # nm
1102 x_int = np.arange(max(np.min(lambdas), peak_pos - 5 * np.abs(popt[bgd_npar + 3 * j + 2])),
1103 min(np.max(lambdas), peak_pos + 5 * np.abs(popt[bgd_npar + 3 * j + 2])), x_step)
1104 middle = 0.5 * (np.max(lambdas[index]) + np.min(lambdas[index]))
1105 x_int_norm = x_int - middle
1106 if np.max(lambdas[index] - middle) != 0:
1107 x_int_norm = x_int_norm / np.max(lambdas[index] - middle)
1109 # jmin and jmax a bit larger than x_int to avoid extrapolation
1110 jmin = max(0, int(np.argmin(np.abs(lambdas - (x_int[0] - x_step))) - 2))
1111 jmax = min(len(lambdas), int(np.argmin(np.abs(lambdas - (x_int[-1] + x_step))) + 2))
1112 if jmax-2 < jmin+2: # decreasing order
1113 jmin, jmax = max(0, jmax-4), min(len(lambdas), jmin+4)
1114 spectr_data = interp1d(lambdas[jmin:jmax], spec[jmin:jmax],
1115 bounds_error=False, fill_value="extrapolate")(x_int)
1117 Continuum = np.polynomial.legendre.legval(x_int_norm, popt[:bgd_npar])
1118 Gauss = gauss(x_int, *popt[bgd_npar + 3 * j:bgd_npar + 3 * j + 3])
1120 Y = -Gauss / Continuum
1121 Ydata = 1 - spectr_data / Continuum
1123 line.fit_eqwidth_mod = integrate.simps(Y, x_int) # sol1
1124 line.fit_eqwidth_data = integrate.simps(Ydata, x_int) # sol2
1126 line.fit_popt = popt
1127 line.fit_popt_gaussian = popt[bgd_npar + 3 * j:bgd_npar + 3 * j + 3]
1128 line.fit_gauss = gauss(lambdas[index], *popt[bgd_npar + 3 * j:bgd_npar + 3 * j + 3])
1130 line.fit_bgd = np.polynomial.legendre.legval(x_norm, popt[:bgd_npar])
1131 line.fit_snr = snr
1132 line.fit_chisq = chisq
1133 line.fit_fwhm = FWHM
1134 line.fit_bgd_npar = bgd_npar
1135 if snr < snr_minlevel:
1136 continue
1137 line.high_snr = True
1138 if line.use_for_calibration:
1139 # wavelength shift between tabulate and observed lines
1140 lambda_shifts.append(peak_pos - line.wavelength)
1141 snrs.append(snr)
1142 if ax is not None:
1143 lines.plot_detected_lines(ax, print_table=parameters.DEBUG)
1144 if len(lambda_shifts) > 0:
1145 global_chisq /= len(lambda_shifts)
1146 shift = np.average(np.abs(lambda_shifts) ** 2, weights=np.array(snrs) ** 2)
1147 # if guess values on tabulated lines have not moved: penalize the chisq
1148 global_chisq += shift
1149 # lines.my_logger.debug(f'\n\tNumber of calibration lines detected {len(lambda_shifts):d}'
1150 # f'\n\tTotal chisq: {global_chisq:.3f} with shift {shift:.3f}pix')
1151 else:
1152 global_chisq = 2 * len(parameters.LAMBDAS)
1153 # lines.my_logger.debug(
1154 # f'\n\tNumber of calibration lines detected {len(lambda_shifts):d}\n\tTotal chisq: {global_chisq:.3f}')
1155 return global_chisq
1158def calibrate_spectrum(spectrum, with_adr=False):
1159 """Convert pixels into wavelengths given the position of the order 0,
1160 the data for the spectrum, the properties of the disperser. Fit the absorption
1161 (and eventually the emission) lines to perform a second calibration of the
1162 distance between the CCD and the disperser. The number of fitting steps is
1163 limited to 30.
1165 Finally convert the spectrum amplitude from ADU rate to erg/s/cm2/nm.
1167 Parameters
1168 ----------
1169 spectrum: Spectrum
1170 Spectrum object to calibrate
1171 with_adr: bool, optional
1172 If True, the ADR longitudinal shift is subtracted to distances.
1173 Must be False if the spectrum has already been decontaminated from ADR (default: False).
1175 Returns
1176 -------
1177 lambdas: array_like
1178 The new wavelength array in nm.
1180 Examples
1181 --------
1182 >>> spectrum = Spectrum('tests/data/reduc_20170605_028_spectrum.fits')
1183 >>> parameters.LAMBDA_MIN = 550
1184 >>> parameters.LAMBDA_MAX = 800
1185 >>> lambdas = calibrate_spectrum(spectrum, with_adr=False)
1186 >>> spectrum.plot_spectrum()
1187 """
1188 with_adr = int(with_adr)
1189 distance = spectrum.chromatic_psf.get_algebraic_distance_along_dispersion_axis()
1190 spectrum.lambdas = spectrum.disperser.grating_pixel_to_lambda(distance, spectrum.x0, order=spectrum.order)
1191 if spectrum.lambda_ref is None:
1192 lambda_ref = np.sum(spectrum.lambdas * spectrum.data) / np.sum(spectrum.data)
1193 spectrum.lambda_ref = lambda_ref
1194 spectrum.header['LBDA_REF'] = lambda_ref
1195 # ADR is x>0 westward and y>0 northward while CTIO images are x>0 westward and y>0 southward
1196 # Must project ADR along dispersion axis
1197 if with_adr > 0:
1198 adr_ra, adr_dec = adr_calib(spectrum.lambdas, spectrum.adr_params, parameters.OBS_LATITUDE,
1199 lambda_ref=spectrum.lambda_ref)
1200 adr_u, _ = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec,
1201 dispersion_axis_angle=spectrum.rotation_angle)
1202 else:
1203 adr_u = np.zeros_like(distance)
1204 x0 = spectrum.x0
1205 if x0 is None:
1206 x0 = spectrum.target_pixcoords
1207 spectrum.x0 = x0
1209 # Detect emission/absorption lines and calibrate pixel/lambda
1210 fwhm_func = interp1d(spectrum.chromatic_psf.table['lambdas'],
1211 spectrum.chromatic_psf.table['fwhm'],
1212 fill_value=(parameters.CALIB_PEAK_WIDTH, parameters.CALIB_PEAK_WIDTH), bounds_error=False)
1214 def shift_minimizer(params):
1215 spectrum.disperser.D, shift = params
1216 if np.isnan(spectrum.disperser.D): # reset the value in case of bad gradient descent
1217 spectrum.disperser.D = parameters.DISTANCE2CCD
1218 if np.isnan(shift): # reset the value in case of bad gradient descent
1219 shift = 0
1220 dist = spectrum.chromatic_psf.get_algebraic_distance_along_dispersion_axis(shift_x=shift)
1221 spectrum.lambdas = spectrum.disperser.grating_pixel_to_lambda(dist - with_adr * adr_u,
1222 x0=[x0[0] + shift, x0[1]], order=spectrum.order)
1223 spectrum.lambdas_binwidths = np.gradient(spectrum.lambdas)
1224 spectrum.convert_from_ADUrate_to_flam()
1225 chisq = detect_lines(spectrum.lines, spectrum.lambdas, spectrum.data, spec_err=spectrum.err,
1226 fwhm_func=fwhm_func, ax=None, calibration_lines_only=True)
1227 chisq += ((shift) / parameters.PIXSHIFT_PRIOR) ** 2
1228 if parameters.DEBUG and parameters.DISPLAY:
1229 if parameters.LIVE_FIT:
1230 spectrum.plot_spectrum(live_fit=True, label=f'Order {spectrum.order:d} spectrum\n'
1231 r'$D_\mathrm{CCD}'
1232 rf'={D:.2f}\,$mm, $\delta u_0={shift:.2f}\,$pix')
1233 spectrum.convert_from_flam_to_ADUrate()
1234 return chisq
1236 # grid exploration of the parameters
1237 # necessary because of the the line detection algo
1238 D = parameters.DISTANCE2CCD
1239 if spectrum.header['D2CCD'] != '':
1240 D = spectrum.header['D2CCD']
1241 D_err = parameters.DISTANCE2CCD_ERR
1242 D_step = D_err / 2
1243 pixel_shift_step = parameters.PIXSHIFT_PRIOR / 5
1244 pixel_shift_prior = parameters.PIXSHIFT_PRIOR
1245 Ds = np.arange(D - 5 * D_err, D + 6 * D_err, D_step)
1246 pixel_shifts = np.arange(-pixel_shift_prior, pixel_shift_prior + pixel_shift_step, pixel_shift_step)
1247 # pixel_shifts = np.array([0])
1248 chisq_grid = np.zeros((len(Ds), len(pixel_shifts)))
1249 for i, D in enumerate(Ds):
1250 for j, pixel_shift in enumerate(pixel_shifts):
1251 chisq_grid[i, j] = shift_minimizer([D, pixel_shift])
1252 imin, jmin = np.unravel_index(chisq_grid.argmin(), chisq_grid.shape)
1253 D = Ds[imin]
1254 pixel_shift = pixel_shifts[jmin]
1255 start = np.array([D, pixel_shift])
1256 if imin == 0 or imin == Ds.size or jmin == 0 or jmin == pixel_shifts.size:
1257 spectrum.my_logger.warning('\n\tMinimum chisq is on the edge of the exploration grid.')
1258 if parameters.DEBUG:
1259 fig = plt.figure(figsize=(7, 4))
1260 im = plt.imshow(np.log10(chisq_grid), origin='lower', aspect='auto',
1261 extent=(
1262 np.min(pixel_shifts) - pixel_shift_step / 2, np.max(pixel_shifts) + pixel_shift_step / 2,
1263 np.min(Ds) - D_step / 2, np.max(Ds) + D_step / 2))
1264 plt.gca().scatter(pixel_shift, D, marker='o', s=100, edgecolors='k', facecolors='none',
1265 label='Minimum', linewidth=2)
1266 c = plt.colorbar(im)
1267 c.set_label('Log10(chisq)')
1268 plt.xlabel(r'Pixel shift $\delta u_0$ [pix]')
1269 plt.ylabel(r'$D_\mathrm{CCD}$ [mm]')
1270 plt.legend()
1271 if parameters.DISPLAY: # pragma: no cover
1272 plt.show()
1273 if parameters.LSST_SAVEFIGPATH: # pragma: no cover
1274 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'D2CCD_x0_fit.pdf'))
1275 # now minimize around the global minimum found previously
1276 # res = opt.minimize(shift_minimizer, start, args=(), method='L-BFGS-B',
1277 # options={'maxiter': 200, 'ftol': 1e-3},
1278 # bounds=((D - 5 * parameters.DISTANCE2CCD_ERR, D + 5 * parameters.DISTANCE2CCD_ERR), (-2, 2)))
1279 error = [parameters.DISTANCE2CCD_ERR, pixel_shift_step]
1280 fix = [False, False]
1281 m = Minuit(shift_minimizer, start)
1282 m.errors = error
1283 m.errordef = 1
1284 m.fixed = fix
1285 m.print_level = 0
1286 m.limits = ((D - 5 * parameters.DISTANCE2CCD_ERR, D + 5 * parameters.DISTANCE2CCD_ERR), (-2, 2))
1287 m.migrad()
1288 # if parameters.DEBUG:
1289 # print(m.prin)
1290 # if not res.success:
1291 # spectrum.my_logger.warning('\n\tMinimizer failed.')
1292 # print(res)
1293 D, pixel_shift = np.array(m.values[:])
1294 spectrum.disperser.D = D
1295 x0 = [x0[0] + pixel_shift, x0[1]]
1296 spectrum.x0 = x0
1297 # check success, xO or D on the edge of their priors
1298 distance = spectrum.chromatic_psf.get_algebraic_distance_along_dispersion_axis(shift_x=pixel_shift)
1299 lambdas = spectrum.disperser.grating_pixel_to_lambda(distance - with_adr * adr_u, x0=x0, order=spectrum.order)
1300 spectrum.lambdas = lambdas
1301 spectrum.lambdas_order2 = spectrum.disperser.grating_pixel_to_lambda(distance - with_adr * adr_u, x0=x0,
1302 order=spectrum.order + 1)
1303 spectrum.lambdas_binwidths = np.gradient(lambdas)
1304 spectrum.convert_from_ADUrate_to_flam()
1305 spectrum.chromatic_psf.table['Dx'] -= pixel_shift
1306 spectrum.chromatic_psf.table['Dy_disp_axis'] = distance * np.sin(spectrum.rotation_angle * np.pi / 180)
1307 spectrum.pixels = np.copy(spectrum.chromatic_psf.table['Dx'])
1308 detect_lines(spectrum.lines, spectrum.lambdas, spectrum.data, spec_err=spectrum.err,
1309 fwhm_func=fwhm_func, ax=None, calibration_lines_only=False)
1310 # Convert back to flam units
1311 # spectrum.convert_from_ADUrate_to_flam()
1312 spectrum.my_logger.info(
1313 f"\n\tOrder0 total shift: {pixel_shift:.3f}pix"
1314 f"\n\tD = {D:.3f} mm (default: DISTANCE2CCD = {parameters.DISTANCE2CCD:.2f} "
1315 f"+/- {parameters.DISTANCE2CCD_ERR:.2f} mm, "
1316 f"{(D - parameters.DISTANCE2CCD) / parameters.DISTANCE2CCD_ERR:.1f} sigma shift)")
1317 spectrum.header['PIXSHIFT'] = pixel_shift
1318 spectrum.header['D2CCD'] = D
1319 return lambdas
1322if __name__ == "__main__": 1322 ↛ 1323line 1322 didn't jump to line 1323, because the condition on line 1322 was never true
1323 import doctest
1325 doctest.testmod()