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
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')) # MFL: Where did that .gcf come from?
382 if parameters.PdfPages:
383 parameters.PdfPages.savefig()
384 if parameters.DISPLAY:
385 if live_fit:
386 plt.draw()
387 plt.pause(1e-8)
388 plt.close()
389 else:
390 plt.show()
392 def plot_spectrogram(self, ax=None, scale="lin", title="", units="Image units", plot_stats=False,
393 target_pixcoords=None, vmin=None, vmax=None, figsize=[9.3, 8], aspect=None,
394 cmap=None, cax=None):
395 """Plot spectrogram.
397 Parameters
398 ----------
399 ax: Axes, optional
400 Axes instance (default: None).
401 scale: str
402 Scaling of the image (choose between: lin, log or log10) (default: lin)
403 title: str
404 Title of the image (default: "")
405 units: str
406 Units of the image to be written in the color bar label (default: "Image units")
407 cmap: colormap
408 Color map label (default: None)
409 target_pixcoords: array_like, optional
410 2D array giving the (x,y) coordinates of the targets on the image: add a scatter plot (default: None)
411 vmin: float
412 Minimum value of the image (default: None)
413 vmax: float
414 Maximum value of the image (default: None)
415 aspect: str
416 Aspect keyword to be passed to imshow (default: None)
417 cax: Axes, optional
418 Color bar axes if necessary (default: None).
419 figsize: tuple
420 Figure size (default: [9.3, 8]).
421 plot_stats: bool
422 If True, plot the uncertainty map instead of the spectrogram (default: False).
424 Examples
425 --------
426 >>> s = Spectrum(file_name='tests/data/reduc_20170605_028_spectrum.fits')
427 >>> s.plot_spectrogram()
428 >>> if parameters.DISPLAY: plt.show()
430 .. plot::
432 from spectractor.extractor.spectrum import Spectrum
433 s = Spectrum(file_name='tests/data/reduc_20170605_028_spectrum.fits')
434 s.plot_spectrogram()
436 """
437 if ax is None:
438 plt.figure(figsize=figsize)
439 ax = plt.gca()
440 data = np.copy(self.spectrogram)
441 if plot_stats:
442 data = np.copy(self.spectrogram_err)
443 plot_image_simple(ax, data=data, scale=scale, title=title, units=units, cax=cax,
444 target_pixcoords=target_pixcoords, aspect=aspect, vmin=vmin, vmax=vmax, cmap=cmap)
445 if parameters.DISPLAY:
446 plt.show()
447 if parameters.PdfPages:
448 parameters.PdfPages.savefig()
450 def save_spectrum(self, output_file_name, overwrite=False):
451 """Save the spectrum into a fits file (data, error and wavelengths).
453 Parameters
454 ----------
455 output_file_name: str
456 Path of the output fits file.
457 overwrite: bool
458 If True overwrite the output file if needed (default: False).
460 Examples
461 --------
462 >>> import os
463 >>> s = Spectrum(file_name='tests/data/reduc_20170530_134_spectrum.fits')
464 >>> s.save_spectrum('./tests/test.fits')
466 .. doctest::
467 :hide:
469 >>> assert os.path.isfile('./tests/test.fits')
471 Overwrite previous file:
472 >>> s.save_spectrum('./tests/test.fits', overwrite=True)
474 .. doctest::
475 :hide:
477 >>> assert os.path.isfile('./tests/test.fits')
478 >>> os.remove('./tests/test.fits')
479 """
480 self.header["REBIN"] = parameters.CCD_REBIN
481 self.header.comments['REBIN'] = 'original image rebinning factor to get spectrum.'
482 self.header['UNIT1'] = "nanometer"
483 self.header['UNIT2'] = self.units
484 self.header['COMMENTS'] = 'First column gives the wavelength in unit UNIT1, ' \
485 'second column gives the spectrum in unit UNIT2, ' \
486 'third column the corresponding errors.'
487 hdu1 = fits.PrimaryHDU()
488 hdu1.header = self.header
489 hdu1.header["EXTNAME"] = "SPECTRUM"
490 hdu2 = fits.ImageHDU()
491 hdu2.header["EXTNAME"] = "SPEC_COV"
492 hdu3 = fits.ImageHDU()
493 hdu3.header["EXTNAME"] = "ORDER2"
494 hdu4 = fits.ImageHDU()
495 hdu4.header["EXTNAME"] = "ORDER0"
496 hdu1.data = [self.lambdas, self.data, self.err]
497 hdu2.data = self.cov_matrix
498 hdu3.data = [self.lambdas_order2, self.data_order2, self.err_order2]
499 hdu4.data = self.target.image
500 hdu4.header["IM_X0"] = self.target.image_x0
501 hdu4.header["IM_Y0"] = self.target.image_y0
502 hdu = fits.HDUList([hdu1, hdu2, hdu3, hdu4])
503 output_directory = '/'.join(output_file_name.split('/')[:-1])
504 ensure_dir(output_directory)
505 hdu.writeto(output_file_name, overwrite=overwrite)
506 self.my_logger.info(f'\n\tSpectrum saved in {output_file_name}')
508 def save_spectrogram(self, output_file_name, overwrite=False):
509 """Save the spectrogram into a fits file (data, error and background).
511 Parameters
512 ----------
513 output_file_name: str
514 Path of the output fits file.
515 overwrite: bool, optional
516 If True overwrite the output file if needed (default: False).
518 Examples
519 --------
520 """
521 self.header['UNIT1'] = self.units
522 self.header['COMMENTS'] = 'First HDU gives the data in UNIT1 units, ' \
523 'second HDU gives the uncertainties, ' \
524 'third HDU the fitted background.'
525 self.header['S_X0'] = self.spectrogram_x0
526 self.header['S_Y0'] = self.spectrogram_y0
527 self.header['S_XMIN'] = self.spectrogram_xmin
528 self.header['S_XMAX'] = self.spectrogram_xmax
529 self.header['S_YMIN'] = self.spectrogram_ymin
530 self.header['S_YMAX'] = self.spectrogram_ymax
531 self.header['S_DEG'] = self.spectrogram_deg
532 self.header['S_SAT'] = self.spectrogram_saturation
533 hdu1 = fits.PrimaryHDU()
534 hdu1.header["EXTNAME"] = "S_DATA"
535 hdu2 = fits.ImageHDU()
536 hdu2.header["EXTNAME"] = "S_ERR"
537 hdu3 = fits.ImageHDU()
538 hdu3.header["EXTNAME"] = "S_BGD"
539 hdu4 = fits.ImageHDU()
540 hdu4.header["EXTNAME"] = "S_BGD_ER"
541 hdu5 = fits.ImageHDU()
542 hdu5.header["EXTNAME"] = "S_FIT"
543 hdu6 = fits.ImageHDU()
544 hdu6.header["EXTNAME"] = "S_RES"
545 hdu1.header = self.header
546 hdu1.data = self.spectrogram
547 hdu2.data = self.spectrogram_err
548 hdu3.data = self.spectrogram_bgd
549 hdu4.data = self.spectrogram_bgd_rms
550 hdu5.data = self.spectrogram_fit
551 hdu6.data = self.spectrogram_residuals
552 hdu = fits.HDUList([hdu1, hdu2, hdu3, hdu4, hdu5, hdu6])
553 output_directory = '/'.join(output_file_name.split('/')[:-1])
554 ensure_dir(output_directory)
555 hdu.writeto(output_file_name, overwrite=overwrite)
556 self.my_logger.info('\n\tSpectrogram saved in %s' % output_file_name)
558 def load_spectrum(self, input_file_name):
559 """Load the spectrum from a fits file (data, error and wavelengths).
561 Parameters
562 ----------
563 input_file_name: str
564 Path to the input fits file
566 Examples
567 --------
568 >>> s = Spectrum()
569 >>> s.load_spectrum('tests/data/reduc_20170605_028_spectrum.fits')
570 >>> print(s.units)
571 erg/s/cm$^2$/nm
572 """
573 if os.path.isfile(input_file_name):
574 self.header, raw_data = load_fits(input_file_name)
575 self.lambdas = raw_data[0]
576 self.lambdas_binwidths = np.gradient(self.lambdas)
577 self.data = raw_data[1]
578 if len(raw_data) > 2:
579 self.err = raw_data[2]
580 if self.header['DATE-OBS'] != "":
581 self.date_obs = self.header['DATE-OBS']
582 if self.header['EXPTIME'] != "":
583 self.expo = self.header['EXPTIME']
584 if self.header['AIRMASS'] != "":
585 self.airmass = self.header['AIRMASS']
586 if self.header['GRATING'] != "":
587 self.disperser_label = self.header['GRATING']
588 if self.header['TARGET'] != "":
589 self.target = load_target(self.header['TARGET'], verbose=parameters.VERBOSE)
590 self.lines = self.target.lines
591 if self.header['UNIT2'] != "":
592 self.units = self.header['UNIT2']
593 if self.header['ROTANGLE'] != "":
594 self.rotation_angle = self.header['ROTANGLE']
595 if self.header['TARGETX'] != "" and self.header['TARGETY'] != "":
596 self.x0 = [self.header['TARGETX'], self.header['TARGETY']]
597 if self.header['D2CCD'] != "":
598 parameters.DISTANCE2CCD = float(self.header["D2CCD"])
599 if 'DEC' in self.header and self.header['DEC'] != "":
600 self.dec = self.header['DEC']
601 if 'RA' in self.header and self.header['HA'] != "":
602 self.hour_angle = self.header['HA']
603 if 'OUTTEMP' in self.header and self.header['OUTTEMP'] != "":
604 self.temperature = self.header['OUTTEMP']
605 if 'OUTPRESS' in self.header and self.header['OUTPRESS'] != "":
606 self.pressure = self.header['OUTPRESS']
607 if 'OUTHUM' in self.header and self.header['OUTHUM'] != "":
608 self.humidity = self.header['OUTHUM']
609 if self.header['LBDA_REF'] != "":
610 self.lambda_ref = self.header['LBDA_REF']
611 if 'PARANGLE' in self.header and self.header['PARANGLE'] != "":
612 self.parallactic_angle = self.header['PARANGLE']
613 if 'CCDREBIN' in self.header and self.header['CCDREBIN'] != "":
614 parameters.CCD_REBIN = self.header['CCDREBIN']
616 self.my_logger.info('\n\tLoading disperser %s...' % self.disperser_label)
617 self.disperser = Hologram(self.disperser_label, D=parameters.DISTANCE2CCD,
618 data_dir=parameters.DISPERSER_DIR, verbose=parameters.VERBOSE)
619 self.my_logger.info('\n\tSpectrum loaded from %s' % input_file_name)
620 spectrogram_file_name = input_file_name.replace('spectrum', 'spectrogram')
621 if parameters.OBS_OBJECT_TYPE == "STAR":
622 self.adr_params = [self.dec, self.hour_angle, self.temperature,
623 self.pressure, self.humidity, self.airmass]
625 hdu_list = fits.open(input_file_name)
626 if len(hdu_list) > 1:
627 self.cov_matrix = hdu_list["SPEC_COV"].data
628 if len(hdu_list) > 2:
629 self.lambdas_order2, self.data_order2, self.err_order2 = hdu_list["ORDER2"].data
630 if len(hdu_list) > 3:
631 self.target.image = hdu_list["ORDER0"].data
632 self.target.image_x0 = float(hdu_list["ORDER0"].header["IM_X0"])
633 self.target.image_y0 = float(hdu_list["ORDER0"].header["IM_Y0"])
634 else:
635 self.cov_matrix = np.diag(self.err ** 2)
636 if not self.fast_load:
637 self.my_logger.info(f'\n\tLoading spectrogram from {spectrogram_file_name}...')
638 if os.path.isfile(spectrogram_file_name):
639 self.load_spectrogram(spectrogram_file_name)
640 else:
641 raise FileNotFoundError(f"Spectrogram file {spectrogram_file_name} does not exist.")
642 psf_file_name = input_file_name.replace('spectrum.fits', 'table.csv')
643 self.my_logger.info(f'\n\tLoading PSF from {psf_file_name}...')
644 if os.path.isfile(psf_file_name):
645 self.load_chromatic_psf(psf_file_name)
646 else:
647 raise FileNotFoundError(f"PSF file {psf_file_name} does not exist.")
648 else:
649 raise FileNotFoundError(f'\n\tSpectrum file {input_file_name} not found')
651 def load_spectrogram(self, input_file_name):
652 """Load the spectrum from a fits file (data, error and wavelengths).
654 Parameters
655 ----------
656 input_file_name: str
657 Path to the input fits file
659 Examples
660 --------
661 >>> s = Spectrum()
662 >>> s.load_spectrum('tests/data/reduc_20170605_028_spectrum.fits')
663 """
664 if os.path.isfile(input_file_name):
665 hdu_list = fits.open(input_file_name)
666 header = hdu_list[0].header
667 self.spectrogram = hdu_list[0].data
668 self.spectrogram_err = hdu_list[1].data
669 self.spectrogram_bgd = hdu_list[2].data
670 if len(hdu_list) > 3:
671 self.spectrogram_bgd_rms = hdu_list[3].data
672 self.spectrogram_fit = hdu_list[4].data
673 self.spectrogram_residuals = hdu_list[5].data
674 self.spectrogram_x0 = float(header['S_X0'])
675 self.spectrogram_y0 = float(header['S_Y0'])
676 self.spectrogram_xmin = int(header['S_XMIN'])
677 self.spectrogram_xmax = int(header['S_XMAX'])
678 self.spectrogram_ymin = int(header['S_YMIN'])
679 self.spectrogram_ymax = int(header['S_YMAX'])
680 self.spectrogram_deg = int(header['S_DEG'])
681 self.spectrogram_saturation = float(header['S_SAT'])
682 self.spectrogram_Nx = self.spectrogram_xmax - self.spectrogram_xmin
683 self.spectrogram_Ny = self.spectrogram_ymax - self.spectrogram_ymin
684 hdu_list.close() # need to free allocation for file descripto
685 self.my_logger.info('\n\tSpectrogram loaded from %s' % input_file_name)
686 else:
687 self.my_logger.warning('\n\tSpectrogram file %s not found' % input_file_name)
689 def load_chromatic_psf(self, input_file_name):
690 """Load the spectrum from a fits file (data, error and wavelengths).
692 Parameters
693 ----------
694 input_file_name: str
695 Path to the input fits file
697 Examples
698 --------
699 >>> s = Spectrum()
700 >>> s.load_spectrum('./tests/data/reduc_20170530_134_spectrum.fits')
701 >>> print(s.chromatic_psf.table) #doctest: +ELLIPSIS
702 lambdas Dx ...
703 """
704 if os.path.isfile(input_file_name):
705 self.psf = load_PSF(psf_type=parameters.PSF_TYPE, target=self.target)
706 self.chromatic_psf = ChromaticPSF(self.psf, self.spectrogram_Nx, self.spectrogram_Ny,
707 x0=self.spectrogram_x0, y0=self.spectrogram_y0,
708 deg=self.spectrogram_deg, saturation=self.spectrogram_saturation,
709 file_name=input_file_name)
710 if 'PSF_REG' in self.header and float(self.header["PSF_REG"]) > 0:
711 self.chromatic_psf.opt_reg = float(self.header["PSF_REG"])
712 self.my_logger.info(f'\n\tSpectrogram loaded from {input_file_name}')
713 else:
714 self.my_logger.warning(f'\n\tSpectrogram file {input_file_name} not found')
717def detect_lines(lines, lambdas, spec, spec_err=None, cov_matrix=None, fwhm_func=None, snr_minlevel=3, ax=None,
718 calibration_lines_only=False,
719 xlim=(parameters.LAMBDA_MIN, parameters.LAMBDA_MAX)):
720 """Detect and fit the lines in a spectrum. The method is to look at maxima or minima
721 around emission or absorption tabulated lines, and to select surrounding pixels
722 to fit a (positive or negative) gaussian and a polynomial background. If several regions
723 overlap, a multi-gaussian fit is performed above a common polynomial background.
724 The mean global shift (in nm) between the detected and tabulated lines is returned, considering
725 only the lines with a signal-to-noise ratio above a threshold.
726 The order of the polynomial background is set in parameters.py with CALIB_BGD_ORDER.
728 Parameters
729 ----------
730 lines: Lines
731 The Lines object containing the line characteristics
732 lambdas: float array
733 The wavelength array (in nm)
734 spec: float array
735 The spectrum amplitude array
736 spec_err: float array, optional
737 The spectrum amplitude uncertainty array (default: None)
738 cov_matrix: float array, optional
739 The spectrum amplitude 2D covariance matrix array (default: None)
740 fwhm_func: callable, optional
741 The fwhm of the cross spectrum to reset CALIB_PEAK_WIDTH parameter as a function of lambda (default: None)
742 snr_minlevel: float
743 The minimum signal over noise ratio to consider using a fitted line in the computation of the mean
744 shift output and to print it in the outpur table (default: 3)
745 ax: Axes, optional
746 An Axes instance to over plot the result of the fit (default: None).
747 calibration_lines_only: bool, optional
748 If True, try to detect only the lines with use_for_calibration attributes set True.
749 xlim: array, optional
750 (min, max) list limiting the wavelength interval where to detect spectral lines (default:
751 (parameters.LAMBDA_MIN, parameters.LAMBDA_MAX))
753 Returns
754 -------
755 shift: float
756 The mean shift (in nm) between the detected and tabulated lines
758 Examples
759 --------
761 Creation of a mock spectrum with emission and absorption lines:
763 >>> import numpy as np
764 >>> from spectractor.extractor.spectroscopy import Lines, HALPHA, HBETA, O2_1
765 >>> lambdas = np.arange(300,1000,1)
766 >>> spectrum = 1e4*np.exp(-((lambdas-600)/200)**2)
767 >>> spectrum += HALPHA.gaussian_model(lambdas, A=5000, sigma=3)
768 >>> spectrum += HBETA.gaussian_model(lambdas, A=3000, sigma=2)
769 >>> spectrum += O2_1.gaussian_model(lambdas, A=-3000, sigma=7)
770 >>> spectrum_err = np.sqrt(spectrum)
771 >>> cov = np.diag(spectrum_err)
772 >>> spectrum = np.random.poisson(spectrum)
773 >>> spec = Spectrum()
774 >>> spec.lambdas = lambdas
775 >>> spec.data = spectrum
776 >>> spec.err = spectrum_err
777 >>> fwhm_func = interp1d(lambdas, 0.01 * lambdas)
779 Detect the lines:
781 >>> lines = Lines([HALPHA, HBETA, O2_1], hydrogen_only=True,
782 ... atmospheric_lines=True, redshift=0, emission_spectrum=True)
783 >>> global_chisq = detect_lines(lines, lambdas, spectrum, spectrum_err, cov, fwhm_func=fwhm_func)
785 .. doctest::
786 :hide:
788 >>> assert(global_chisq < 2)
790 Plot the result:
792 >>> import matplotlib.pyplot as plt
793 >>> spec.lines = lines
794 >>> fig = plt.figure()
795 >>> plot_spectrum_simple(plt.gca(), lambdas, spec.data, data_err=spec.err)
796 >>> lines.plot_detected_lines(plt.gca())
797 >>> if parameters.DISPLAY: plt.show()
798 """
800 # main settings
801 peak_width = parameters.CALIB_PEAK_WIDTH
802 bgd_width = parameters.CALIB_BGD_WIDTH
803 # if lines.hydrogen_only:
804 # peak_width = 7
805 # bgd_width = 15
806 fwhm_to_peak_width_factor = 1.5
807 len_index_to_bgd_npar_factor = 0 * 0.12 / 0.024 * parameters.CCD_PIXEL2MM
808 baseline_prior = 3 # *sigma gaussian prior on base line fit
809 # filter the noise
810 # plt.errorbar(lambdas,spec,yerr=spec_err)
811 spec = np.copy(spec)
812 spec_smooth = savgol_filter(spec, parameters.CALIB_SAVGOL_WINDOW, parameters.CALIB_SAVGOL_ORDER)
813 # plt.plot(lambdas,spec)
814 # plt.show()
815 # initialisation
816 lambda_shifts = []
817 snrs = []
818 index_list = []
819 bgd_npar_list = []
820 peak_index_list = []
821 guess_list = []
822 bounds_list = []
823 lines_list = []
824 for line in lines.lines:
825 # reset line fit attributes
826 line.fitted = False
827 line.fit_popt = None
828 line.high_snr = False
829 if not line.use_for_calibration and calibration_lines_only:
830 continue
831 # wavelength of the line: find the nearest pixel index
832 line_wavelength = line.wavelength
833 if fwhm_func is not None:
834 peak_width = max(fwhm_to_peak_width_factor * fwhm_func(line_wavelength), parameters.CALIB_PEAK_WIDTH)
835 if line_wavelength < xlim[0] or line_wavelength > xlim[1]:
836 continue
837 l_index, l_lambdas = find_nearest(lambdas, line_wavelength)
838 # reject if pixel index is too close to image bounds
839 if l_index < peak_width or l_index > len(lambdas) - peak_width:
840 continue
841 # search for local extrema to detect emission or absorption line
842 # around pixel index +/- peak_width
843 line_strategy = np.greater # look for emission line
844 bgd_strategy = np.less
845 if not lines.emission_spectrum or line.atmospheric:
846 line_strategy = np.less # look for absorption line
847 bgd_strategy = np.greater
848 index = np.arange(l_index - peak_width, l_index + peak_width, 1).astype(int)
849 # skip if data is masked with NaN
850 if np.any(np.isnan(spec_smooth[index])):
851 continue
852 extrema = argrelextrema(spec_smooth[index], line_strategy)
853 if len(extrema[0]) == 0:
854 continue
855 peak_index = index[0] + extrema[0][0]
856 # if several extrema, look for the greatest
857 if len(extrema[0]) > 1:
858 if line_strategy == np.greater:
859 test = -1e20
860 for m in extrema[0]:
861 idx = index[0] + m
862 if spec_smooth[idx] > test:
863 peak_index = idx
864 test = spec_smooth[idx]
865 elif line_strategy == np.less:
866 test = 1e20
867 for m in extrema[0]:
868 idx = index[0] + m
869 if spec_smooth[idx] < test:
870 peak_index = idx
871 test = spec_smooth[idx]
872 # search for first local minima around the local maximum
873 # or for first local maxima around the local minimum
874 # around +/- 3*peak_width
875 index_inf = peak_index - 1 # extrema on the left
876 while index_inf > max(0, peak_index - 3 * peak_width):
877 test_index = np.arange(index_inf, peak_index, 1).astype(int)
878 minm = argrelextrema(spec_smooth[test_index], bgd_strategy)
879 if len(minm[0]) > 0:
880 index_inf = index_inf + minm[0][0]
881 break
882 else:
883 index_inf -= 1
884 index_sup = peak_index + 1 # extrema on the right
885 while index_sup < min(len(spec_smooth) - 1, peak_index + 3 * peak_width):
886 test_index = np.arange(peak_index, index_sup, 1).astype(int)
887 minm = argrelextrema(spec_smooth[test_index], bgd_strategy)
888 if len(minm[0]) > 0:
889 index_sup = peak_index + minm[0][0]
890 break
891 else:
892 index_sup += 1
893 index_sup = max(index_sup, peak_index + peak_width)
894 index_inf = min(index_inf, peak_index - peak_width)
895 # pixel range to consider around the peak, adding bgd_width pixels
896 # to fit for background around the peak
897 index = list(np.arange(max(0, index_inf - bgd_width),
898 min(len(lambdas), index_sup + bgd_width), 1).astype(int))
899 # skip if data is masked with NaN
900 if np.any(np.isnan(spec_smooth[index])):
901 continue
902 # first guess and bounds to fit the line properties and
903 # the background with CALIB_BGD_ORDER order polynom
904 # guess = [0] * bgd_npar + [0.5 * np.max(spec_smooth[index]), lambdas[peak_index],
905 # 0.5 * (line.width_bounds[0] + line.width_bounds[1])]
906 bgd_npar = max(parameters.CALIB_BGD_NPARAMS, int(len_index_to_bgd_npar_factor * (index[-1] - index[0])))
907 bgd_npar_list.append(bgd_npar)
908 guess = [0] * bgd_npar + [0.5 * np.max(spec_smooth[index]), line_wavelength,
909 0.5 * (line.width_bounds[0] + line.width_bounds[1])]
910 if line_strategy == np.less:
911 # noinspection PyTypeChecker
912 guess[bgd_npar] = -0.5 * np.max(spec_smooth[index]) # look for abosrption under bgd
913 # bounds = [[-np.inf] * bgd_npar + [-abs(np.max(spec[index])), lambdas[index_inf], line.width_bounds[0]],
914 # [np.inf] * bgd_npar + [abs(np.max(spec[index])), lambdas[index_sup], line.width_bounds[1]]]
915 bounds = [[-np.inf] * bgd_npar + [-abs(np.max(spec[index])), line_wavelength - peak_width / 2,
916 line.width_bounds[0]],
917 [np.inf] * bgd_npar + [abs(np.max(spec[index])), line_wavelength + peak_width / 2,
918 line.width_bounds[1]]]
919 # gaussian amplitude bounds depend if line is emission/absorption
920 if line_strategy == np.less:
921 bounds[1][bgd_npar] = 0 # look for absorption under bgd
922 else:
923 bounds[0][bgd_npar] = 0 # look for emission above bgd
924 peak_index_list.append(peak_index)
925 index_list.append(index)
926 lines_list.append(line)
927 guess_list.append(guess)
928 bounds_list.append(bounds)
929 # now gather lines together if pixel index ranges overlap
930 idx = 0
931 merges = [[0]]
932 while idx < len(index_list) - 1:
933 idx = merges[-1][-1]
934 if idx == len(index_list) - 1:
935 break
936 if index_list[idx + 1][0] > index_list[idx][0]: # increasing order
937 if index_list[idx][-1] > index_list[idx + 1][0]:
938 merges[-1].append(idx + 1)
939 else:
940 merges.append([idx + 1])
941 idx += 1
942 else: # decreasing order
943 if index_list[idx][0] < index_list[idx + 1][-1]:
944 merges[-1].append(idx + 1)
945 else:
946 merges.append([idx + 1])
947 idx += 1
948 # reorder merge list with respect to lambdas in guess list
949 new_merges = []
950 for merge in merges:
951 if len(guess_list) == 0:
952 continue
953 tmp_guess = [guess_list[i][-2] for i in merge]
954 new_merges.append([x for _, x in sorted(zip(tmp_guess, merge))])
955 # reorder lists with merges
956 new_peak_index_list = []
957 new_index_list = []
958 new_guess_list = []
959 new_bounds_list = []
960 new_lines_list = []
961 for merge in new_merges:
962 new_peak_index_list.append([])
963 new_index_list.append([])
964 new_guess_list.append([])
965 new_bounds_list.append([[], []])
966 new_lines_list.append([])
967 for i in merge:
968 # add the bgd parameters
969 bgd_npar = bgd_npar_list[i]
970 # if i == merge[0]:
971 # new_guess_list[-1] += guess_list[i][:bgd_npar]
972 # new_bounds_list[-1][0] += bounds_list[i][0][:bgd_npar]
973 # new_bounds_list[-1][1] += bounds_list[i][1][:bgd_npar]
974 # add the gauss parameters
975 new_peak_index_list[-1].append(peak_index_list[i])
976 new_index_list[-1] += index_list[i]
977 new_guess_list[-1] += guess_list[i][bgd_npar:]
978 new_bounds_list[-1][0] += bounds_list[i][0][bgd_npar:]
979 new_bounds_list[-1][1] += bounds_list[i][1][bgd_npar:]
980 new_lines_list[-1].append(lines_list[i])
981 # set central peak bounds exactly between two close lines
982 for k in range(len(merge) - 1):
983 new_bounds_list[-1][0][3 * (k + 1) + 1] = 0.5 * (
984 new_guess_list[-1][3 * k + 1] + new_guess_list[-1][3 * (k + 1) + 1])
985 new_bounds_list[-1][1][3 * k + 1] = 0.5 * (
986 new_guess_list[-1][3 * k + 1] + new_guess_list[-1][3 * (k + 1) + 1]) + 1e-3
987 # last term is to avoid equalities
988 # between bounds in some pathological case
989 # sort pixel indices and remove doublons
990 new_index_list[-1] = sorted(list(set(new_index_list[-1])))
991 # fit the line subsets and background
992 global_chisq = 0
993 for k in range(len(new_index_list)):
994 # first guess for the base line with the lateral bands
995 peak_index = new_peak_index_list[k]
996 index = new_index_list[k]
997 guess = new_guess_list[k]
998 bounds = new_bounds_list[k]
999 bgd_index = []
1000 if fwhm_func is not None:
1001 peak_width = fwhm_to_peak_width_factor * np.mean(fwhm_func(lambdas[index]))
1002 for i in index:
1003 is_close_to_peak = False
1004 for j in peak_index:
1005 if abs(i - j) < peak_width:
1006 is_close_to_peak = True
1007 break
1008 if not is_close_to_peak:
1009 bgd_index.append(i)
1010 # add background guess and bounds
1011 bgd_npar = max(parameters.CALIB_BGD_ORDER + 1, int(len_index_to_bgd_npar_factor * len(bgd_index)))
1012 parameters.CALIB_BGD_NPARAMS = bgd_npar
1013 guess = [0] * bgd_npar + guess
1014 bounds[0] = [-np.inf] * bgd_npar + bounds[0]
1015 bounds[1] = [np.inf] * bgd_npar + bounds[1]
1016 if len(bgd_index) > 0:
1017 try:
1018 if spec_err is not None:
1019 w = 1. / spec_err[bgd_index]
1020 else:
1021 w = np.ones_like(lambdas[bgd_index])
1022 fit, cov, model = fit_poly1d_legendre(lambdas[bgd_index], spec[bgd_index], order=bgd_npar - 1, w=w)
1023 except:
1024 if spec_err is not None:
1025 w = 1. / spec_err[index]
1026 else:
1027 w = np.ones_like(lambdas[index])
1028 fit, cov, model = fit_poly1d_legendre(lambdas[index], spec[index], order=bgd_npar - 1, w=w)
1029 else:
1030 if spec_err is not None:
1031 w = 1. / spec_err[index]
1032 else:
1033 w = np.ones_like(lambdas[index])
1034 fit, cov, model = fit_poly1d_legendre(lambdas[index], spec[index], order=bgd_npar - 1, w=w)
1035 # lines.my_logger.warning(f'{bgd_npar} {fit}')
1036 # fig = plt.figure()
1037 # plt.plot(lambdas[index], spec[index])
1038 # plt.plot(lambdas[bgd_index], spec[bgd_index], 'ro')
1039 # x_norm = rescale_x_for_legendre(lambdas[index])
1040 # lines.my_logger.warning(f'tototot {x_norm}')
1041 # plt.plot(lambdas[index], np.polynomial.legendre.legval(x_norm, fit), 'b-')
1042 # plt.plot(lambdas[bgd_index], model, 'b--')
1043 # plt.title(f"{fit}")
1044 # plt.show()
1045 for n in range(bgd_npar):
1046 # guess[n] = getattr(bgd, bgd.param_names[parameters.CALIB_BGD_ORDER - n]).value
1047 guess[n] = fit[n]
1048 b = abs(baseline_prior * guess[n])
1049 if np.isclose(b, 0, rtol=1e-2 * float(np.mean(spec_smooth[bgd_index]))):
1050 b = baseline_prior * np.std(spec_smooth[bgd_index])
1051 if np.isclose(b, 0, rtol=1e-2 * float(np.mean(spec_smooth[bgd_index]))):
1052 b = np.inf
1053 bounds[0][n] = guess[n] - b
1054 bounds[1][n] = guess[n] + b
1055 for j in range(len(new_lines_list[k])):
1056 idx = new_peak_index_list[k][j]
1057 x_norm = rescale_x_for_legendre(lambdas[idx])
1058 guess[bgd_npar + 3 * j] = np.sign(guess[bgd_npar + 3 * j]) * abs(
1059 spec_smooth[idx] - np.polynomial.legendre.legval(x_norm, guess[:bgd_npar]))
1060 if np.sign(guess[bgd_npar + 3 * j]) < 0: # absorption
1061 bounds[0][bgd_npar + 3 * j] = 2 * guess[bgd_npar + 3 * j]
1062 else: # emission
1063 bounds[1][bgd_npar + 3 * j] = 2 * guess[bgd_npar + 3 * j]
1064 # fit local extrema with a multigaussian + CALIB_BGD_ORDER polynom
1065 # account for the spectrum uncertainties if provided
1066 sigma = None
1067 if spec_err is not None:
1068 sigma = spec_err[index]
1069 if cov_matrix is not None:
1070 sigma = cov_matrix[index, index]
1071 # my_logger.warning(f'\n{guess} {np.mean(spec[bgd_index])} {np.std(spec[bgd_index])}')
1072 popt, pcov = fit_multigauss_and_bgd(lambdas[index], spec[index], guess=guess, bounds=bounds, sigma=sigma)
1073 # noise level defined as the std of the residuals if no error
1074 noise_level = np.std(spec[index] - multigauss_and_bgd(lambdas[index], *popt))
1075 # otherwise mean of error bars of bgd lateral bands
1076 if sigma is not None:
1077 chisq = np.sum((multigauss_and_bgd(lambdas[index], *popt) - spec[index]) ** 2 / (sigma * sigma))
1078 else:
1079 chisq = np.sum((multigauss_and_bgd(lambdas[index], *popt) - spec[index]) ** 2)
1080 chisq /= len(index)
1081 global_chisq += chisq
1082 if spec_err is not None:
1083 noise_level = np.sqrt(np.mean(spec_err[index] ** 2))
1085 for j in range(len(new_lines_list[k])):
1086 line = new_lines_list[k][j]
1087 peak_pos = popt[bgd_npar + 3 * j + 1]
1088 # FWHM
1089 FWHM = np.abs(popt[bgd_npar + 3 * j + 2]) * 2.355
1090 # SNR computation
1091 # signal_level = popt[bgd_npar+3*j]
1092 signal_level = popt[
1093 bgd_npar + 3 * j] # multigauss_and_bgd(peak_pos, *popt) - np.polyval(popt[:bgd_npar], peak_pos)
1094 snr = np.abs(signal_level / noise_level)
1095 # save fit results
1096 line.fitted = True
1097 line.fit_index = index
1098 line.fit_lambdas = lambdas[index]
1100 x_norm = rescale_x_for_legendre(lambdas[index])
1102 x_step = 0.1 # nm
1103 x_int = np.arange(max(np.min(lambdas), peak_pos - 5 * np.abs(popt[bgd_npar + 3 * j + 2])),
1104 min(np.max(lambdas), peak_pos + 5 * np.abs(popt[bgd_npar + 3 * j + 2])), x_step)
1105 middle = 0.5 * (np.max(lambdas[index]) + np.min(lambdas[index]))
1106 x_int_norm = x_int - middle
1107 if np.max(lambdas[index] - middle) != 0:
1108 x_int_norm = x_int_norm / np.max(lambdas[index] - middle)
1110 # jmin and jmax a bit larger than x_int to avoid extrapolation
1111 jmin = max(0, int(np.argmin(np.abs(lambdas - (x_int[0] - x_step))) - 2))
1112 jmax = min(len(lambdas), int(np.argmin(np.abs(lambdas - (x_int[-1] + x_step))) + 2))
1113 if jmax-2 < jmin+2: # decreasing order
1114 jmin, jmax = max(0, jmax-4), min(len(lambdas), jmin+4)
1115 spectr_data = interp1d(lambdas[jmin:jmax], spec[jmin:jmax],
1116 bounds_error=False, fill_value="extrapolate")(x_int)
1118 Continuum = np.polynomial.legendre.legval(x_int_norm, popt[:bgd_npar])
1119 Gauss = gauss(x_int, *popt[bgd_npar + 3 * j:bgd_npar + 3 * j + 3])
1121 Y = -Gauss / Continuum
1122 Ydata = 1 - spectr_data / Continuum
1124 line.fit_eqwidth_mod = integrate.simps(Y, x_int) # sol1
1125 line.fit_eqwidth_data = integrate.simps(Ydata, x_int) # sol2
1127 line.fit_popt = popt
1128 line.fit_popt_gaussian = popt[bgd_npar + 3 * j:bgd_npar + 3 * j + 3]
1129 line.fit_gauss = gauss(lambdas[index], *popt[bgd_npar + 3 * j:bgd_npar + 3 * j + 3])
1131 line.fit_bgd = np.polynomial.legendre.legval(x_norm, popt[:bgd_npar])
1132 line.fit_snr = snr
1133 line.fit_chisq = chisq
1134 line.fit_fwhm = FWHM
1135 line.fit_bgd_npar = bgd_npar
1136 if snr < snr_minlevel:
1137 continue
1138 line.high_snr = True
1139 if line.use_for_calibration:
1140 # wavelength shift between tabulate and observed lines
1141 lambda_shifts.append(peak_pos - line.wavelength)
1142 snrs.append(snr)
1143 if ax is not None:
1144 lines.plot_detected_lines(ax, print_table=parameters.DEBUG)
1145 if len(lambda_shifts) > 0:
1146 global_chisq /= len(lambda_shifts)
1147 shift = np.average(np.abs(lambda_shifts) ** 2, weights=np.array(snrs) ** 2)
1148 # if guess values on tabulated lines have not moved: penalize the chisq
1149 global_chisq += shift
1150 # lines.my_logger.debug(f'\n\tNumber of calibration lines detected {len(lambda_shifts):d}'
1151 # f'\n\tTotal chisq: {global_chisq:.3f} with shift {shift:.3f}pix')
1152 else:
1153 global_chisq = 2 * len(parameters.LAMBDAS)
1154 # lines.my_logger.debug(
1155 # f'\n\tNumber of calibration lines detected {len(lambda_shifts):d}\n\tTotal chisq: {global_chisq:.3f}')
1156 return global_chisq
1159def calibrate_spectrum(spectrum, with_adr=False):
1160 """Convert pixels into wavelengths given the position of the order 0,
1161 the data for the spectrum, the properties of the disperser. Fit the absorption
1162 (and eventually the emission) lines to perform a second calibration of the
1163 distance between the CCD and the disperser. The number of fitting steps is
1164 limited to 30.
1166 Finally convert the spectrum amplitude from ADU rate to erg/s/cm2/nm.
1168 Parameters
1169 ----------
1170 spectrum: Spectrum
1171 Spectrum object to calibrate
1172 with_adr: bool, optional
1173 If True, the ADR longitudinal shift is subtracted to distances.
1174 Must be False if the spectrum has already been decontaminated from ADR (default: False).
1176 Returns
1177 -------
1178 lambdas: array_like
1179 The new wavelength array in nm.
1181 Examples
1182 --------
1183 >>> spectrum = Spectrum('tests/data/reduc_20170605_028_spectrum.fits')
1184 >>> parameters.LAMBDA_MIN = 550
1185 >>> parameters.LAMBDA_MAX = 800
1186 >>> lambdas = calibrate_spectrum(spectrum, with_adr=False)
1187 >>> spectrum.plot_spectrum()
1188 """
1189 with_adr = int(with_adr)
1190 distance = spectrum.chromatic_psf.get_algebraic_distance_along_dispersion_axis()
1191 spectrum.lambdas = spectrum.disperser.grating_pixel_to_lambda(distance, spectrum.x0, order=spectrum.order)
1192 if spectrum.lambda_ref is None:
1193 lambda_ref = np.sum(spectrum.lambdas * spectrum.data) / np.sum(spectrum.data)
1194 spectrum.lambda_ref = lambda_ref
1195 spectrum.header['LBDA_REF'] = lambda_ref
1196 # ADR is x>0 westward and y>0 northward while CTIO images are x>0 westward and y>0 southward
1197 # Must project ADR along dispersion axis
1198 if with_adr > 0:
1199 adr_ra, adr_dec = adr_calib(spectrum.lambdas, spectrum.adr_params, parameters.OBS_LATITUDE,
1200 lambda_ref=spectrum.lambda_ref)
1201 adr_u, _ = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec,
1202 dispersion_axis_angle=spectrum.rotation_angle)
1203 else:
1204 adr_u = np.zeros_like(distance)
1205 x0 = spectrum.x0
1206 if x0 is None:
1207 x0 = spectrum.target_pixcoords
1208 spectrum.x0 = x0
1210 # Detect emission/absorption lines and calibrate pixel/lambda
1211 fwhm_func = interp1d(spectrum.chromatic_psf.table['lambdas'],
1212 spectrum.chromatic_psf.table['fwhm'],
1213 fill_value=(parameters.CALIB_PEAK_WIDTH, parameters.CALIB_PEAK_WIDTH), bounds_error=False)
1215 def shift_minimizer(params):
1216 spectrum.disperser.D, shift = params
1217 dist = spectrum.chromatic_psf.get_algebraic_distance_along_dispersion_axis(shift_x=shift)
1218 spectrum.lambdas = spectrum.disperser.grating_pixel_to_lambda(dist - with_adr * adr_u,
1219 x0=[x0[0] + shift, x0[1]], order=spectrum.order)
1220 spectrum.lambdas_binwidths = np.gradient(spectrum.lambdas)
1221 spectrum.convert_from_ADUrate_to_flam()
1222 chisq = detect_lines(spectrum.lines, spectrum.lambdas, spectrum.data, spec_err=spectrum.err,
1223 fwhm_func=fwhm_func, ax=None, calibration_lines_only=True)
1224 chisq += ((shift) / parameters.PIXSHIFT_PRIOR) ** 2
1225 if parameters.DEBUG and parameters.DISPLAY:
1226 if parameters.LIVE_FIT:
1227 spectrum.plot_spectrum(live_fit=True, label=f'Order {spectrum.order:d} spectrum\n'
1228 r'$D_\mathrm{CCD}'
1229 rf'={D:.2f}\,$mm, $\delta u_0={shift:.2f}\,$pix')
1230 spectrum.convert_from_flam_to_ADUrate()
1231 return chisq
1233 # grid exploration of the parameters
1234 # necessary because of the the line detection algo
1235 D = parameters.DISTANCE2CCD
1236 if spectrum.header['D2CCD'] != '':
1237 D = spectrum.header['D2CCD']
1238 D_err = parameters.DISTANCE2CCD_ERR
1239 D_step = D_err / 2
1240 pixel_shift_step = parameters.PIXSHIFT_PRIOR / 5
1241 pixel_shift_prior = parameters.PIXSHIFT_PRIOR
1242 Ds = np.arange(D - 5 * D_err, D + 6 * D_err, D_step)
1243 pixel_shifts = np.arange(-pixel_shift_prior, pixel_shift_prior + pixel_shift_step, pixel_shift_step)
1244 # pixel_shifts = np.array([0])
1245 chisq_grid = np.zeros((len(Ds), len(pixel_shifts)))
1246 for i, D in enumerate(Ds):
1247 for j, pixel_shift in enumerate(pixel_shifts):
1248 chisq_grid[i, j] = shift_minimizer([D, pixel_shift])
1249 imin, jmin = np.unravel_index(chisq_grid.argmin(), chisq_grid.shape)
1250 D = Ds[imin]
1251 pixel_shift = pixel_shifts[jmin]
1252 start = np.array([D, pixel_shift])
1253 if imin == 0 or imin == Ds.size or jmin == 0 or jmin == pixel_shifts.size:
1254 spectrum.my_logger.warning('\n\tMinimum chisq is on the edge of the exploration grid.')
1255 if parameters.DEBUG:
1256 fig = plt.figure(figsize=(7, 4))
1257 im = plt.imshow(np.log10(chisq_grid), origin='lower', aspect='auto',
1258 extent=(
1259 np.min(pixel_shifts) - pixel_shift_step / 2, np.max(pixel_shifts) + pixel_shift_step / 2,
1260 np.min(Ds) - D_step / 2, np.max(Ds) + D_step / 2))
1261 plt.gca().scatter(pixel_shift, D, marker='o', s=100, edgecolors='k', facecolors='none',
1262 label='Minimum', linewidth=2)
1263 c = plt.colorbar(im)
1264 c.set_label('Log10(chisq)')
1265 plt.xlabel(r'Pixel shift $\delta u_0$ [pix]')
1266 plt.ylabel(r'$D_\mathrm{CCD}$ [mm]')
1267 plt.legend()
1268 if parameters.DISPLAY: # pragma: no cover
1269 plt.show()
1270 if parameters.LSST_SAVEFIGPATH: # pragma: no cover
1271 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'D2CCD_x0_fit.pdf'))
1272 plt.show()
1273 if parameters.PdfPages:
1274 parameters.PdfPages.savefig()
1276 # now minimize around the global minimum found previously
1277 # res = opt.minimize(shift_minimizer, start, args=(), method='L-BFGS-B',
1278 # options={'maxiter': 200, 'ftol': 1e-3},
1279 # bounds=((D - 5 * parameters.DISTANCE2CCD_ERR, D + 5 * parameters.DISTANCE2CCD_ERR), (-2, 2)))
1280 error = [parameters.DISTANCE2CCD_ERR, pixel_shift_step]
1281 fix = [False, False]
1282 m = Minuit(shift_minimizer, start)
1283 m.errors = error
1284 m.errordef = 1
1285 m.fixed = fix
1286 m.print_level = 0
1287 m.limits = ((D - 5 * parameters.DISTANCE2CCD_ERR, D + 5 * parameters.DISTANCE2CCD_ERR), (-2, 2))
1288 m.migrad()
1289 # if parameters.DEBUG:
1290 # print(m.prin)
1291 # if not res.success:
1292 # spectrum.my_logger.warning('\n\tMinimizer failed.')
1293 # print(res)
1294 D, pixel_shift = np.array(m.values[:])
1295 spectrum.disperser.D = D
1296 x0 = [x0[0] + pixel_shift, x0[1]]
1297 spectrum.x0 = x0
1298 # check success, xO or D on the edge of their priors
1299 distance = spectrum.chromatic_psf.get_algebraic_distance_along_dispersion_axis(shift_x=pixel_shift)
1300 lambdas = spectrum.disperser.grating_pixel_to_lambda(distance - with_adr * adr_u, x0=x0, order=spectrum.order)
1301 spectrum.lambdas = lambdas
1302 spectrum.lambdas_order2 = spectrum.disperser.grating_pixel_to_lambda(distance - with_adr * adr_u, x0=x0,
1303 order=spectrum.order + 1)
1304 spectrum.lambdas_binwidths = np.gradient(lambdas)
1305 spectrum.convert_from_ADUrate_to_flam()
1306 spectrum.chromatic_psf.table['Dx'] -= pixel_shift
1307 spectrum.chromatic_psf.table['Dy_disp_axis'] = distance * np.sin(spectrum.rotation_angle * np.pi / 180)
1308 spectrum.pixels = np.copy(spectrum.chromatic_psf.table['Dx'])
1309 detect_lines(spectrum.lines, spectrum.lambdas, spectrum.data, spec_err=spectrum.err,
1310 fwhm_func=fwhm_func, ax=None, calibration_lines_only=False)
1311 # Convert back to flam units
1312 # spectrum.convert_from_ADUrate_to_flam()
1313 spectrum.my_logger.info(
1314 f"\n\tOrder0 total shift: {pixel_shift:.3f}pix"
1315 f"\n\tD = {D:.3f} mm (default: DISTANCE2CCD = {parameters.DISTANCE2CCD:.2f} "
1316 f"+/- {parameters.DISTANCE2CCD_ERR:.2f} mm, "
1317 f"{(D - parameters.DISTANCE2CCD) / parameters.DISTANCE2CCD_ERR:.1f} sigma shift)")
1318 spectrum.header['PIXSHIFT'] = pixel_shift
1319 spectrum.header['D2CCD'] = D
1320 return lambdas
1323if __name__ == "__main__": 1323 ↛ 1324line 1323 didn't jump to line 1324, because the condition on line 1323 was never true
1324 import doctest
1326 doctest.testmod()