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

686 statements  

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 

9import astropy 

10 

11from spectractor import parameters 

12from spectractor.config import set_logger, load_config, apply_rebinning_to_parameters 

13from spectractor.extractor.dispersers import Hologram 

14from spectractor.extractor.targets import load_target 

15from spectractor.tools import (ensure_dir, load_fits, plot_image_simple, 

16 find_nearest, plot_spectrum_simple, fit_poly1d_legendre, gauss, 

17 rescale_x_for_legendre, fit_multigauss_and_bgd, multigauss_and_bgd) 

18from spectractor.extractor.psf import load_PSF 

19from spectractor.extractor.chromaticpsf import ChromaticPSF 

20from spectractor.simulation.adr import adr_calib, flip_and_rotate_adr_to_image_xy_coordinates 

21from spectractor.simulation.throughput import TelescopeTransmission 

22 

23 

24fits_mappings = {'date_obs': 'DATE-OBS', 

25 'expo': 'EXPTIME', 

26 'airmass': 'AIRMASS', 

27 'disperser_label': 'GRATING', 

28 'units': 'UNIT2', 

29 'rotation_angle': 'ROTANGLE', 

30 'dec': 'DEC', 

31 'hour_angle': 'HA', 

32 'temperature': 'OUTTEMP', 

33 'pressure': 'OUTPRESS', 

34 'humidity': 'OUTHUM', 

35 'lambda_ref': 'LBDA_REF', 

36 'parallactic_angle': 'PARANGLE', 

37 } 

38 

39 

40class Spectrum: 

41 """ Class used to store information and methods relative to spectra and their extraction. 

42 

43 Attributes 

44 ---------- 

45 my_logger: logging 

46 Logging object 

47 fast_load: bool 

48 If True, only load the spectrum but not the spectrogram. 

49 units: str 

50 Units of the spectrum. 

51 lambdas: array 

52 Spectrum wavelengths in nm. 

53 data: array 

54 Spectrum amplitude array in self.units units. 

55 err: array 

56 Spectrum amplitude uncertainties in self.units units. 

57 cov_matrix: array 

58 Spectrum amplitude covariance matrix between wavelengths in self.units units. 

59 lambdas_binwidths: array 

60 Bin widths of the wavelength array in nm. 

61 lambdas_order2: array 

62 Spectrum wavelengths for order 2 contamination in nm. 

63 data_order2: array 

64 Spectrum amplitude array for order 2 contamination in self.units units. 

65 err_order2: array 

66 Spectrum amplitude uncertainties for order 2 contamination in self.units units. 

67 lambda_ref: float 

68 Reference wavelength for ADR computations in nm. 

69 order: int 

70 Index of the diffraction order. 

71 x0: array 

72 Target position [x,y] in the image in pixels. 

73 psf: PSF 

74 PSF instance to model the spectrum PSF. 

75 chromatic_psf: ChromaticPSF 

76 ChromaticPSF object that contains data on the PSF shape and evolution in wavelength. 

77 date_obs: str 

78 Date of the observation. 

79 airmass: float 

80 Airmass of the current target. 

81 expo: float 

82 Exposure time in seconds. 

83 disperser_label: str 

84 Label of the disperser. 

85 filter_label: str: 

86 Label of the filter. 

87 rotation_angle: float 

88 Dispersion axis angle in the image in degrees, positive if anticlockwise. 

89 parallactic_angle: float 

90 Parallactic angle in degrees. 

91 lines: Lines 

92 Lines instance that contains data on the emission or absorption lines to be searched and fitted in the spectrum. 

93 header: Fits.Header 

94 FITS file header. 

95 disperser: Disperser 

96 Disperser instance that describes the disperser. 

97 target: Target 

98 Target instance that describes the current exposure. 

99 dec: float 

100 Declination coordinate of the current exposure. 

101 hour_angle float 

102 Hour angle coordinate of the current exposure. 

103 temperature: float 

104 Outside temperature in Celsius degrees. 

105 pressure: float 

106 Outside pressure in hPa. 

107 humidity: float 

108 Outside relative humidity in fraction of one. 

109 spectrogram: array 

110 Spectrogram 2D image in image units. 

111 spectrogram_bgd: array 

112 Estimated 2D background fitted below the spectrogram in image units. 

113 spectrogram_bgd_rms: array 

114 Estimated 2D background RMS fitted below the spectrogram in image units. 

115 spectrogram_err: array 

116 Estimated 2D background uncertainty fitted below the spectrogram in image units. 

117 spectrogram_fit: array 

118 Best fitting model of the spectrogram in image units. 

119 spectrogram_residuals: array 

120 Residuals between the spectrogram data and the best fitting model of the spectrogram in image units. 

121 spectrogram_x0: float 

122 Relative position of the target in the spectrogram array along the x axis. 

123 spectrogram_y0: float 

124 Relative position of the target in the spectrogram array along the y axis. 

125 spectrogram_xmin: int 

126 Left index of the spectrogram crop in the image. 

127 spectrogram_xmax: int 

128 Right index of the spectrogram crop in the image. 

129 spectrogram_ymin: int 

130 Bottom index of the spectrogram crop in the image. 

131 spectrogram_ymax: int 

132 Top index of the spectrogram crop in the image. 

133 spectrogram_deg: int 

134 Degree of the polynomial functions to model wavelength evolutions of the PSF parameters. 

135 spectrogram_saturation: float 

136 Level of saturation in the spectrogram in image units. 

137 spectrogram_Nx: int 

138 Size of the spectrogram along the x axis. 

139 spectrogram_Ny: int 

140 Size of the spectrogram along the y axis. 

141 """ 

142 

143 def __init__(self, file_name="", image=None, order=1, target=None, config="", fast_load=False, 

144 spectrogram_file_name_override=None, 

145 psf_file_name_override=None,): 

146 """ Class used to store information and methods relative to spectra and their extraction. 

147 

148 Parameters 

149 ---------- 

150 file_name: str, optional 

151 Path to the spectrum file (default: ""). 

152 image: Image, optional 

153 Image object from which to create the Spectrum object: 

154 copy the information from the Image header (default: None). 

155 order: int 

156 Order of the spectrum (default: 1) 

157 target: Target, optional 

158 Target object if provided (default: None) 

159 config: str, optional 

160 A config file name to load some parameter values for a given instrument (default: ""). 

161 fast_load: bool, optional 

162 If True, only the spectrum is loaded (not the PSF nor the spectrogram data) (default: False). 

163 

164 Examples 

165 -------- 

166 Load a spectrum from a fits file 

167 >>> s = Spectrum(file_name='tests/data/reduc_20170605_028_spectrum.fits') 

168 >>> print(s.order) 

169 1 

170 >>> print(s.target.label) 

171 PNG321.0+3.9 

172 >>> print(s.disperser_label) 

173 HoloPhAg 

174 

175 Load a spectrum from a fits image file 

176 >>> from spectractor.extractor.images import Image 

177 >>> image = Image('tests/data/reduc_20170605_028.fits', target_label='PNG321.0+3.9') 

178 >>> s = Spectrum(image=image) 

179 >>> print(s.target.label) 

180 PNG321.0+3.9 

181 """ 

182 self.fast_load = fast_load 

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

184 if config != "": 

185 load_config(config) 

186 self.target = target 

187 self.data = None 

188 self.err = None 

189 self.cov_matrix = None 

190 self.x0 = None 

191 self.pixels = None 

192 self.lambdas = None 

193 self.lambdas_binwidths = None 

194 self.lambdas_indices = None 

195 self.lambda_ref = None 

196 self.order = order 

197 self.chromatic_psf = None 

198 self.filter_label = "" 

199 self.filters = None 

200 self.units = 'ADU/s' 

201 self.gain = parameters.CCD_GAIN 

202 self.psf = load_PSF(psf_type="Moffat", target=self.target) 

203 self.chromatic_psf = ChromaticPSF(self.psf, Nx=1, Ny=1, deg=1, saturation=1) 

204 self.rotation_angle = 0 

205 self.parallactic_angle = None 

206 self.spectrogram = None 

207 self.spectrogram_bgd = None 

208 self.spectrogram_bgd_rms = None 

209 self.spectrogram_err = None 

210 self.spectrogram_residuals = None 

211 self.spectrogram_fit = None 

212 self.spectrogram_x0 = None 

213 self.spectrogram_y0 = None 

214 self.spectrogram_xmin = None 

215 self.spectrogram_xmax = None 

216 self.spectrogram_ymin = None 

217 self.spectrogram_ymax = None 

218 self.spectrogram_deg = None 

219 self.spectrogram_saturation = None 

220 self.spectrogram_Nx = None 

221 self.spectrogram_Ny = None 

222 self.lambdas_order2 = None 

223 self.data_order2 = None 

224 self.err_order2 = None 

225 self.dec = None 

226 self.hour_angle = None 

227 self.temperature = None 

228 self.pressure = None 

229 self.humidity = None 

230 self.parallactic_angle = None 

231 self.filename = file_name 

232 if file_name != "": 

233 self.load_spectrum(file_name, 

234 spectrogram_file_name_override=spectrogram_file_name_override, 

235 psf_file_name_override=psf_file_name_override) 

236 if image is not None: 

237 self.header = image.header 

238 self.date_obs = image.date_obs 

239 self.airmass = image.airmass 

240 self.expo = image.expo 

241 self.filters = image.filters 

242 self.filter_label = image.filter_label 

243 self.disperser_label = image.disperser_label 

244 self.disperser = image.disperser 

245 self.target = image.target 

246 self.lines = self.target.lines 

247 self.x0 = image.target_pixcoords 

248 self.target_pixcoords = image.target_pixcoords 

249 self.target_pixcoords_rotated = image.target_pixcoords_rotated 

250 self.units = image.units 

251 self.gain = image.gain 

252 self.rotation_angle = image.rotation_angle 

253 self.my_logger.info('\n\tSpectrum info copied from image') 

254 self.dec = image.dec 

255 self.hour_angle = image.hour_angle 

256 self.temperature = image.temperature 

257 self.pressure = image.pressure 

258 self.humidity = image.humidity 

259 self.parallactic_angle = image.parallactic_angle 

260 self.adr_params = [self.dec, self.hour_angle, self.temperature, self.pressure, 

261 self.humidity, self.airmass] 

262 self.load_filter() 

263 

264 def convert_from_ADUrate_to_flam(self): 

265 """Convert units from ADU/s to erg/s/cm^2/nm. 

266 The SED is supposed to be in flam units ie erg/s/cm^2/nm 

267 

268 Examples 

269 -------- 

270 >>> s = Spectrum(file_name='tests/data/reduc_20170605_028_spectrum.fits') 

271 >>> s.convert_from_ADUrate_to_flam() 

272 

273 .. doctest:: 

274 :hide: 

275 

276 >>> assert np.max(s.data) < 1e-2 

277 >>> assert np.max(s.err) < 1e-2 

278 

279 """ 

280 if self.units == 'erg/s/cm$^2$/nm' or self.units == "flam": 

281 self.my_logger.warning(f"You ask to convert spectrum already in {self.units}" 

282 f" in erg/s/cm^2/nm... check your code ! Skip the instruction.") 

283 return 

284 ldl = parameters.FLAM_TO_ADURATE * self.lambdas * np.abs(self.lambdas_binwidths) 

285 self.data /= ldl 

286 if self.err is not None: 

287 self.err /= ldl 

288 if self.cov_matrix is not None: 

289 ldl_mat = np.outer(ldl, ldl) 

290 self.cov_matrix /= ldl_mat 

291 if self.data_order2 is not None: 

292 ldl_2 = parameters.FLAM_TO_ADURATE * self.lambdas_order2 * np.abs(np.gradient(self.lambdas_order2)) 

293 self.data_order2 /= ldl_2 

294 self.err_order2 /= ldl_2 

295 self.units = 'erg/s/cm$^2$/nm' 

296 

297 def convert_from_flam_to_ADUrate(self): 

298 """Convert units from erg/s/cm^2/nm to ADU/s. 

299 The SED is supposed to be in flam units ie erg/s/cm^2/nm 

300 

301 Examples 

302 -------- 

303 >>> s = Spectrum(file_name='tests/data/reduc_20170605_028_spectrum.fits') 

304 >>> s.convert_from_flam_to_ADUrate() 

305 

306 .. doctest:: 

307 :hide: 

308 

309 >>> assert np.max(s.data) > 1e-2 

310 >>> assert np.max(s.err) > 1e-2 

311 

312 """ 

313 if self.units == "ADU/s": 

314 self.my_logger.warning(f"You ask to convert spectrum already in {self.units} in ADU/s... check your code ! " 

315 f"Skip the instruction") 

316 return 

317 ldl = parameters.FLAM_TO_ADURATE * self.lambdas * np.abs(self.lambdas_binwidths) 

318 self.data *= ldl 

319 if self.err is not None: 

320 self.err *= ldl 

321 if self.cov_matrix is not None: 

322 ldl_mat = np.outer(ldl, ldl) 

323 self.cov_matrix *= ldl_mat 

324 if self.data_order2 is not None: 

325 ldl_2 = parameters.FLAM_TO_ADURATE * self.lambdas_order2 * np.abs(np.gradient(self.lambdas_order2)) 

326 self.data_order2 *= ldl_2 

327 self.err_order2 *= ldl_2 

328 self.units = 'ADU/s' 

329 

330 def load_filter(self): 

331 """Load filter properties and set relevant LAMBDA_MIN and LAMBDA_MAX values. 

332 

333 Examples 

334 -------- 

335 >>> s = Spectrum() 

336 >>> s.filter_label = 'FGB37' 

337 >>> s.load_filter() 

338 

339 .. doctest:: 

340 :hide: 

341 

342 >>> assert np.isclose(parameters.LAMBDA_MIN, 300) 

343 >>> assert np.isclose(parameters.LAMBDA_MAX, 760) 

344 

345 """ 

346 if self.filter_label != "" and "empty" not in self.filter_label.lower(): 

347 t = TelescopeTransmission(filter_label=self.filter_label) 

348 t.reset_lambda_range(transmission_threshold=1e-4) 

349 

350 def plot_spectrum(self, ax=None, xlim=None, live_fit=False, label='', force_lines=False): 

351 """Plot spectrum with emission and absorption lines. 

352 

353 Parameters 

354 ---------- 

355 ax: Axes, optional 

356 Axes instance (default: None). 

357 label: str 

358 Label for the legend (default: ''). 

359 xlim: list, optional 

360 List of minimum and maximum abscisses (default: None) 

361 live_fit: bool, optional 

362 If True the spectrum is plotted in live during the fitting procedures 

363 (default: False). 

364 force_lines: bool 

365 Force the over plot of vertical lines for atomic lines if set to True (default: False). 

366 

367 Examples 

368 -------- 

369 >>> s = Spectrum(file_name='tests/data/reduc_20170530_134_spectrum.fits') 

370 >>> s.plot_spectrum(xlim=[500,900], live_fit=False, force_lines=True) 

371 """ 

372 if ax is None: 

373 plt.figure(figsize=[12, 6]) 

374 ax = plt.gca() 

375 if label == '': 

376 label = f'Order {self.order:d} spectrum\n' \ 

377 r'$D_{\mathrm{CCD}}=' \ 

378 rf'{self.disperser.D:.2f}\,$mm' 

379 if self.x0 is not None: 

380 label += rf', $x_0={self.x0[0]:.2f}\,$pix' 

381 title = self.target.label 

382 if self.lambdas_order2 is not None: 

383 distance = self.disperser.grating_lambda_to_pixel(self.lambdas_order2, self.x0, order=2) 

384 lambdas_order2_contamination = self.disperser.grating_pixel_to_lambda(distance, self.x0, order=1) 

385 data_order2_contamination = self.data_order2 * (self.lambdas_order2 * np.gradient(self.lambdas_order2)) \ 

386 / (lambdas_order2_contamination * np.gradient(lambdas_order2_contamination)) 

387 if np.sum(data_order2_contamination) / np.sum(self.data) > 0.01: 

388 data_interp = interp1d(self.lambdas, self.data, kind="linear", fill_value="0", bounds_error=False) 

389 plot_spectrum_simple(ax, lambdas_order2_contamination, 

390 data_interp(lambdas_order2_contamination) + data_order2_contamination, 

391 data_err=None, xlim=xlim, label='Order 2 contamination', linestyle="--", lw=1) 

392 plot_spectrum_simple(ax, self.lambdas, self.data, data_err=self.err, xlim=xlim, label=label, 

393 title=title, units=self.units) 

394 if len(self.target.spectra) > 0: 

395 for k in range(len(self.target.spectra)): 

396 plot_indices = np.logical_and(self.target.wavelengths[k] > np.min(self.lambdas), 

397 self.target.wavelengths[k] < np.max(self.lambdas)) 

398 s = self.target.spectra[k] / np.max(self.target.spectra[k][plot_indices]) * np.max(self.data) 

399 ax.plot(self.target.wavelengths[k], s, lw=2, label='Tabulated spectra #%d' % k) 

400 if self.lambdas is not None: 

401 self.lines.plot_detected_lines(ax, print_table=parameters.VERBOSE) 

402 if self.lambdas is not None and self.lines is not None: 

403 self.lines.plot_atomic_lines(ax, fontsize=12, force=force_lines) 

404 ax.legend(loc='best') 

405 if self.filters is not None: 

406 ax.get_legend().set_title(self.filters) 

407 if parameters.LSST_SAVEFIGPATH: # pragma: no cover 

408 plt.gcf().savefig(os.path.join(parameters.LSST_SAVEFIGPATH, f'{self.target.label}_spectrum.pdf')) 

409 if parameters.DISPLAY: 

410 if live_fit: 

411 plt.draw() 

412 plt.pause(1e-8) 

413 plt.close() 

414 else: 

415 plt.show() 

416 

417 def plot_spectrogram(self, ax=None, scale="lin", title="", units="Image units", plot_stats=False, 

418 target_pixcoords=None, vmin=None, vmax=None, figsize=[9.3, 8], aspect=None, 

419 cmap=None, cax=None): 

420 """Plot spectrogram. 

421 

422 Parameters 

423 ---------- 

424 ax: Axes, optional 

425 Axes instance (default: None). 

426 scale: str 

427 Scaling of the image (choose between: lin, log or log10) (default: lin) 

428 title: str 

429 Title of the image (default: "") 

430 units: str 

431 Units of the image to be written in the color bar label (default: "Image units") 

432 cmap: colormap 

433 Color map label (default: None) 

434 target_pixcoords: array_like, optional 

435 2D array giving the (x,y) coordinates of the targets on the image: add a scatter plot (default: None) 

436 vmin: float 

437 Minimum value of the image (default: None) 

438 vmax: float 

439 Maximum value of the image (default: None) 

440 aspect: str 

441 Aspect keyword to be passed to imshow (default: None) 

442 cax: Axes, optional 

443 Color bar axes if necessary (default: None). 

444 figsize: tuple 

445 Figure size (default: [9.3, 8]). 

446 plot_stats: bool 

447 If True, plot the uncertainty map instead of the spectrogram (default: False). 

448 

449 Examples 

450 -------- 

451 >>> s = Spectrum(file_name='tests/data/reduc_20170605_028_spectrum.fits') 

452 >>> s.plot_spectrogram() 

453 >>> if parameters.DISPLAY: plt.show() 

454 

455 .. plot:: 

456 

457 from spectractor.extractor.spectrum import Spectrum 

458 s = Spectrum(file_name='tests/data/reduc_20170605_028_spectrum.fits') 

459 s.plot_spectrogram() 

460 

461 """ 

462 if ax is None: 

463 plt.figure(figsize=figsize) 

464 ax = plt.gca() 

465 data = np.copy(self.spectrogram) 

466 if plot_stats: 

467 data = np.copy(self.spectrogram_err) 

468 plot_image_simple(ax, data=data, scale=scale, title=title, units=units, cax=cax, 

469 target_pixcoords=target_pixcoords, aspect=aspect, vmin=vmin, vmax=vmax, cmap=cmap) 

470 if parameters.DISPLAY: 

471 plt.show() 

472 if parameters.PdfPages: 

473 parameters.PdfPages.savefig() 

474 

475 def save_spectrum(self, output_file_name, overwrite=False): 

476 """Save the spectrum into a fits file (data, error and wavelengths). 

477 

478 Parameters 

479 ---------- 

480 output_file_name: str 

481 Path of the output fits file. 

482 overwrite: bool 

483 If True overwrite the output file if needed (default: False). 

484 

485 Examples 

486 -------- 

487 >>> import os 

488 >>> s = Spectrum(file_name='tests/data/reduc_20170530_134_spectrum.fits') 

489 >>> s.save_spectrum('./tests/test.fits') 

490 

491 .. doctest:: 

492 :hide: 

493 

494 >>> assert os.path.isfile('./tests/test.fits') 

495 

496 Overwrite previous file: 

497 >>> s.save_spectrum('./tests/test.fits', overwrite=True) 

498 

499 .. doctest:: 

500 :hide: 

501 

502 >>> assert os.path.isfile('./tests/test.fits') 

503 >>> os.remove('./tests/test.fits') 

504 """ 

505 self.header["REBIN"] = parameters.CCD_REBIN 

506 self.header.comments['REBIN'] = 'original image rebinning factor to get spectrum.' 

507 self.header['UNIT1'] = "nanometer" 

508 self.header['UNIT2'] = self.units 

509 self.header['COMMENTS'] = 'First column gives the wavelength in unit UNIT1, ' \ 

510 'second column gives the spectrum in unit UNIT2, ' \ 

511 'third column the corresponding errors.' 

512 hdu1 = fits.PrimaryHDU() 

513 hdu1.header = self.header 

514 

515 for attribute, header_key in fits_mappings.items(): 

516 try: 

517 value = getattr(self, attribute) 

518 except AttributeError: 

519 print(f"Failed to get {attribute}") 

520 continue 

521 if isinstance(value, astropy.coordinates.angles.Angle): 

522 value = value.degree 

523 hdu1.header[header_key] = value 

524 print(f"Set header key {header_key} to {value} from attr {attribute}") 

525 

526 hdu1.header["EXTNAME"] = "SPECTRUM" 

527 hdu2 = fits.ImageHDU() 

528 hdu2.header["EXTNAME"] = "SPEC_COV" 

529 hdu3 = fits.ImageHDU() 

530 hdu3.header["EXTNAME"] = "ORDER2" 

531 hdu4 = fits.ImageHDU() 

532 hdu4.header["EXTNAME"] = "ORDER0" 

533 hdu1.data = [self.lambdas, self.data, self.err] 

534 hdu2.data = self.cov_matrix 

535 hdu3.data = [self.lambdas_order2, self.data_order2, self.err_order2] 

536 hdu4.data = self.target.image 

537 hdu4.header["IM_X0"] = self.target.image_x0 

538 hdu4.header["IM_Y0"] = self.target.image_y0 

539 hdu = fits.HDUList([hdu1, hdu2, hdu3, hdu4]) 

540 output_directory = '/'.join(output_file_name.split('/')[:-1]) 

541 ensure_dir(output_directory) 

542 hdu.writeto(output_file_name, overwrite=overwrite) 

543 self.my_logger.info(f'\n\tSpectrum saved in {output_file_name}') 

544 

545 def save_spectrogram(self, output_file_name, overwrite=False): 

546 """Save the spectrogram into a fits file (data, error and background). 

547 

548 Parameters 

549 ---------- 

550 output_file_name: str 

551 Path of the output fits file. 

552 overwrite: bool, optional 

553 If True overwrite the output file if needed (default: False). 

554 

555 Examples 

556 -------- 

557 """ 

558 self.header['UNIT1'] = self.units 

559 self.header['COMMENTS'] = 'First HDU gives the data in UNIT1 units, ' \ 

560 'second HDU gives the uncertainties, ' \ 

561 'third HDU the fitted background.' 

562 self.header['S_X0'] = self.spectrogram_x0 

563 self.header['S_Y0'] = self.spectrogram_y0 

564 self.header['S_XMIN'] = self.spectrogram_xmin 

565 self.header['S_XMAX'] = self.spectrogram_xmax 

566 self.header['S_YMIN'] = self.spectrogram_ymin 

567 self.header['S_YMAX'] = self.spectrogram_ymax 

568 self.header['S_DEG'] = self.spectrogram_deg 

569 self.header['S_SAT'] = self.spectrogram_saturation 

570 hdu1 = fits.PrimaryHDU() 

571 hdu1.header["EXTNAME"] = "S_DATA" 

572 hdu2 = fits.ImageHDU() 

573 hdu2.header["EXTNAME"] = "S_ERR" 

574 hdu3 = fits.ImageHDU() 

575 hdu3.header["EXTNAME"] = "S_BGD" 

576 hdu4 = fits.ImageHDU() 

577 hdu4.header["EXTNAME"] = "S_BGD_ER" 

578 hdu5 = fits.ImageHDU() 

579 hdu5.header["EXTNAME"] = "S_FIT" 

580 hdu6 = fits.ImageHDU() 

581 hdu6.header["EXTNAME"] = "S_RES" 

582 hdu1.header = self.header 

583 hdu1.data = self.spectrogram 

584 hdu2.data = self.spectrogram_err 

585 hdu3.data = self.spectrogram_bgd 

586 hdu4.data = self.spectrogram_bgd_rms 

587 hdu5.data = self.spectrogram_fit 

588 hdu6.data = self.spectrogram_residuals 

589 hdu = fits.HDUList([hdu1, hdu2, hdu3, hdu4, hdu5, hdu6]) 

590 output_directory = '/'.join(output_file_name.split('/')[:-1]) 

591 ensure_dir(output_directory) 

592 hdu.writeto(output_file_name, overwrite=overwrite) 

593 self.my_logger.info('\n\tSpectrogram saved in %s' % output_file_name) 

594 

595 def load_spectrum(self, input_file_name, spectrogram_file_name_override=None, 

596 psf_file_name_override=None): 

597 """Load the spectrum from a fits file (data, error and wavelengths). 

598 

599 Parameters 

600 ---------- 

601 input_file_name: str 

602 Path to the input fits file 

603 

604 spectrogram_file_name_override : str 

605 Manually specify a path to the spectrogram file. 

606 

607 psf_file_name_override : str 

608 Manually specify a path to the psf file. 

609 

610 Examples 

611 -------- 

612 >>> s = Spectrum() 

613 >>> s.load_spectrum('tests/data/reduc_20170605_028_spectrum.fits') 

614 >>> print(s.units) 

615 erg/s/cm$^2$/nm 

616 """ 

617 if os.path.isfile(input_file_name): 

618 self.header, raw_data = load_fits(input_file_name) 

619 self.lambdas = raw_data[0] 

620 self.lambdas_binwidths = np.gradient(self.lambdas) 

621 self.data = raw_data[1] 

622 if len(raw_data) > 2: 

623 self.err = raw_data[2] 

624 

625 # set the simple items from the mappings. More complex items, i.e. 

626 # those needing function calls, follow 

627 for attribute, header_key in fits_mappings.items(): 

628 if (item := self.header.get(header_key)) is not None: 

629 setattr(self, attribute, item) 

630 print(f'set {attribute} to {item}') 

631 else: 

632 print(f'Failed to set spectrum attribute {attribute} using header {header_key}') 

633 

634 # set the more complex items by hand here 

635 if target := self.header.get('TARGET'): 

636 self.target = load_target(target, verbose=parameters.VERBOSE) 

637 self.lines = self.target.lines 

638 if (targetx := self.header.get('TARGETX')) and (targety := self.header.get('TARGETY')): 

639 self.x0 = [targetx, targety] # should be a tuple not a list 

640 if rebin := self.header.get('CCDREBIN'): 

641 if parameters.CCD_REBIN != rebin: 

642 raise ValueError("Different values of rebinning parameters between config file and header. Choose.") 

643 parameters.CCD_REBIN = rebin 

644 if dist := self.header.get('D2CCD'): 

645 parameters.DISTANCE2CCD = float(dist) 

646 

647 self.my_logger.info('\n\tLoading disperser %s...' % self.disperser_label) 

648 self.disperser = Hologram(self.disperser_label, D=parameters.DISTANCE2CCD, 

649 data_dir=parameters.DISPERSER_DIR, verbose=parameters.VERBOSE) 

650 self.my_logger.info('\n\tSpectrum loaded from %s' % input_file_name) 

651 if parameters.OBS_OBJECT_TYPE == "STAR": 

652 self.adr_params = [self.dec, self.hour_angle, self.temperature, 

653 self.pressure, self.humidity, self.airmass] 

654 

655 hdu_list = fits.open(input_file_name) 

656 if len(hdu_list) > 1: 

657 self.cov_matrix = hdu_list["SPEC_COV"].data 

658 if len(hdu_list) > 2: 

659 self.lambdas_order2, self.data_order2, self.err_order2 = hdu_list["ORDER2"].data 

660 if len(hdu_list) > 3: 

661 self.target.image = hdu_list["ORDER0"].data 

662 self.target.image_x0 = float(hdu_list["ORDER0"].header["IM_X0"]) 

663 self.target.image_y0 = float(hdu_list["ORDER0"].header["IM_Y0"]) 

664 else: 

665 self.cov_matrix = np.diag(self.err ** 2) 

666 

667 # original, hard-coded spectrogram/table relative paths 

668 spectrogram_file_name = input_file_name.replace('spectrum', 'spectrogram') 

669 psf_file_name = input_file_name.replace('spectrum.fits', 'table.csv') 

670 

671 # for LSST-DM supplied filenames 

672 if spectrogram_file_name_override and psf_file_name_override: 

673 self.fast_load = False 

674 spectrogram_file_name = spectrogram_file_name_override 

675 psf_file_name = psf_file_name_override 

676 self.my_logger.info(f'Applying spectrogram filename override {spectrogram_file_name}') 

677 self.my_logger.info(f'Applying psf filename override {psf_file_name}') 

678 

679 if not self.fast_load: 

680 self.my_logger.info(f'\n\tLoading spectrogram from {spectrogram_file_name}...') 

681 if os.path.isfile(spectrogram_file_name): 

682 self.load_spectrogram(spectrogram_file_name) 

683 else: 

684 raise FileNotFoundError(f"Spectrogram file {spectrogram_file_name} does not exist.") 

685 self.my_logger.info(f'\n\tLoading PSF from {psf_file_name}...') 

686 if os.path.isfile(psf_file_name): 

687 self.load_chromatic_psf(psf_file_name) 

688 else: 

689 raise FileNotFoundError(f"PSF file {psf_file_name} does not exist.") 

690 else: 

691 raise FileNotFoundError(f'\n\tSpectrum file {input_file_name} not found') 

692 

693 def load_spectrogram(self, input_file_name): 

694 """Load the spectrum from a fits file (data, error and wavelengths). 

695 

696 Parameters 

697 ---------- 

698 input_file_name: str 

699 Path to the input fits file 

700 

701 Examples 

702 -------- 

703 >>> s = Spectrum() 

704 >>> s.load_spectrum('tests/data/reduc_20170605_028_spectrum.fits') 

705 """ 

706 if os.path.isfile(input_file_name): 

707 hdu_list = fits.open(input_file_name) 

708 header = hdu_list[0].header 

709 self.spectrogram = hdu_list[0].data 

710 self.spectrogram_err = hdu_list[1].data 

711 self.spectrogram_bgd = hdu_list[2].data 

712 if len(hdu_list) > 3: 

713 self.spectrogram_bgd_rms = hdu_list[3].data 

714 self.spectrogram_fit = hdu_list[4].data 

715 self.spectrogram_residuals = hdu_list[5].data 

716 self.spectrogram_x0 = float(header['S_X0']) 

717 self.spectrogram_y0 = float(header['S_Y0']) 

718 self.spectrogram_xmin = int(header['S_XMIN']) 

719 self.spectrogram_xmax = int(header['S_XMAX']) 

720 self.spectrogram_ymin = int(header['S_YMIN']) 

721 self.spectrogram_ymax = int(header['S_YMAX']) 

722 self.spectrogram_deg = int(header['S_DEG']) 

723 self.spectrogram_saturation = float(header['S_SAT']) 

724 self.spectrogram_Nx = self.spectrogram_xmax - self.spectrogram_xmin 

725 self.spectrogram_Ny = self.spectrogram_ymax - self.spectrogram_ymin 

726 hdu_list.close() # need to free allocation for file descripto 

727 self.my_logger.info('\n\tSpectrogram loaded from %s' % input_file_name) 

728 else: 

729 self.my_logger.warning('\n\tSpectrogram file %s not found' % input_file_name) 

730 

731 def load_chromatic_psf(self, input_file_name): 

732 """Load the spectrum from a fits file (data, error and wavelengths). 

733 

734 Parameters 

735 ---------- 

736 input_file_name: str 

737 Path to the input fits file 

738 

739 Examples 

740 -------- 

741 >>> s = Spectrum() 

742 >>> s.load_spectrum('./tests/data/reduc_20170530_134_spectrum.fits') 

743 >>> print(s.chromatic_psf.table) #doctest: +ELLIPSIS 

744 lambdas Dx ... 

745 """ 

746 if os.path.isfile(input_file_name): 

747 self.psf = load_PSF(psf_type=parameters.PSF_TYPE, target=self.target) 

748 self.chromatic_psf = ChromaticPSF(self.psf, self.spectrogram_Nx, self.spectrogram_Ny, 

749 x0=self.spectrogram_x0, y0=self.spectrogram_y0, 

750 deg=self.spectrogram_deg, saturation=self.spectrogram_saturation, 

751 file_name=input_file_name) 

752 if 'PSF_REG' in self.header and float(self.header["PSF_REG"]) > 0: 

753 self.chromatic_psf.opt_reg = float(self.header["PSF_REG"]) 

754 self.my_logger.info(f'\n\tSpectrogram loaded from {input_file_name}') 

755 else: 

756 self.my_logger.warning(f'\n\tSpectrogram file {input_file_name} not found') 

757 

758 

759def detect_lines(lines, lambdas, spec, spec_err=None, cov_matrix=None, fwhm_func=None, snr_minlevel=3, ax=None, 

760 calibration_lines_only=False, 

761 xlim=(parameters.LAMBDA_MIN, parameters.LAMBDA_MAX)): 

762 """Detect and fit the lines in a spectrum. The method is to look at maxima or minima 

763 around emission or absorption tabulated lines, and to select surrounding pixels 

764 to fit a (positive or negative) gaussian and a polynomial background. If several regions 

765 overlap, a multi-gaussian fit is performed above a common polynomial background. 

766 The mean global shift (in nm) between the detected and tabulated lines is returned, considering 

767 only the lines with a signal-to-noise ratio above a threshold. 

768 The order of the polynomial background is set in parameters.py with CALIB_BGD_ORDER. 

769 

770 Parameters 

771 ---------- 

772 lines: Lines 

773 The Lines object containing the line characteristics 

774 lambdas: float array 

775 The wavelength array (in nm) 

776 spec: float array 

777 The spectrum amplitude array 

778 spec_err: float array, optional 

779 The spectrum amplitude uncertainty array (default: None) 

780 cov_matrix: float array, optional 

781 The spectrum amplitude 2D covariance matrix array (default: None) 

782 fwhm_func: callable, optional 

783 The fwhm of the cross spectrum to reset CALIB_PEAK_WIDTH parameter as a function of lambda (default: None) 

784 snr_minlevel: float 

785 The minimum signal over noise ratio to consider using a fitted line in the computation of the mean 

786 shift output and to print it in the outpur table (default: 3) 

787 ax: Axes, optional 

788 An Axes instance to over plot the result of the fit (default: None). 

789 calibration_lines_only: bool, optional 

790 If True, try to detect only the lines with use_for_calibration attributes set True. 

791 xlim: array, optional 

792 (min, max) list limiting the wavelength interval where to detect spectral lines (default: 

793 (parameters.LAMBDA_MIN, parameters.LAMBDA_MAX)) 

794 

795 Returns 

796 ------- 

797 shift: float 

798 The mean shift (in nm) between the detected and tabulated lines 

799 

800 Examples 

801 -------- 

802 

803 Creation of a mock spectrum with emission and absorption lines: 

804 

805 >>> import numpy as np 

806 >>> from spectractor.extractor.spectroscopy import Lines, HALPHA, HBETA, O2_1 

807 >>> lambdas = np.arange(300,1000,1) 

808 >>> spectrum = 1e4*np.exp(-((lambdas-600)/200)**2) 

809 >>> spectrum += HALPHA.gaussian_model(lambdas, A=5000, sigma=3) 

810 >>> spectrum += HBETA.gaussian_model(lambdas, A=3000, sigma=2) 

811 >>> spectrum += O2_1.gaussian_model(lambdas, A=-3000, sigma=7) 

812 >>> spectrum_err = np.sqrt(spectrum) 

813 >>> cov = np.diag(spectrum_err) 

814 >>> spectrum = np.random.poisson(spectrum) 

815 >>> spec = Spectrum() 

816 >>> spec.lambdas = lambdas 

817 >>> spec.data = spectrum 

818 >>> spec.err = spectrum_err 

819 >>> fwhm_func = interp1d(lambdas, 0.01 * lambdas) 

820 

821 Detect the lines: 

822 

823 >>> lines = Lines([HALPHA, HBETA, O2_1], hydrogen_only=True, 

824 ... atmospheric_lines=True, redshift=0, emission_spectrum=True) 

825 >>> global_chisq = detect_lines(lines, lambdas, spectrum, spectrum_err, cov, fwhm_func=fwhm_func) 

826 

827 .. doctest:: 

828 :hide: 

829 

830 >>> assert(global_chisq < 2) 

831 

832 Plot the result: 

833 

834 >>> import matplotlib.pyplot as plt 

835 >>> spec.lines = lines 

836 >>> fig = plt.figure() 

837 >>> plot_spectrum_simple(plt.gca(), lambdas, spec.data, data_err=spec.err) 

838 >>> lines.plot_detected_lines(plt.gca()) 

839 >>> if parameters.DISPLAY: plt.show() 

840 """ 

841 

842 # main settings 

843 peak_width = parameters.CALIB_PEAK_WIDTH 

844 bgd_width = parameters.CALIB_BGD_WIDTH 

845 # if lines.hydrogen_only: 

846 # peak_width = 7 

847 # bgd_width = 15 

848 fwhm_to_peak_width_factor = 1.5 

849 len_index_to_bgd_npar_factor = 0 * 0.12 / 0.024 * parameters.CCD_PIXEL2MM 

850 baseline_prior = 3 # *sigma gaussian prior on base line fit 

851 # filter the noise 

852 # plt.errorbar(lambdas,spec,yerr=spec_err) 

853 spec = np.copy(spec) 

854 spec_smooth = savgol_filter(spec, parameters.CALIB_SAVGOL_WINDOW, parameters.CALIB_SAVGOL_ORDER) 

855 # plt.plot(lambdas,spec) 

856 # plt.show() 

857 # initialisation 

858 lambda_shifts = [] 

859 snrs = [] 

860 index_list = [] 

861 bgd_npar_list = [] 

862 peak_index_list = [] 

863 guess_list = [] 

864 bounds_list = [] 

865 lines_list = [] 

866 for line in lines.lines: 

867 # reset line fit attributes 

868 line.fitted = False 

869 line.fit_popt = None 

870 line.high_snr = False 

871 if not line.use_for_calibration and calibration_lines_only: 

872 continue 

873 # wavelength of the line: find the nearest pixel index 

874 line_wavelength = line.wavelength 

875 if fwhm_func is not None: 

876 peak_width = max(fwhm_to_peak_width_factor * fwhm_func(line_wavelength), parameters.CALIB_PEAK_WIDTH) 

877 if line_wavelength < xlim[0] or line_wavelength > xlim[1]: 

878 continue 

879 l_index, l_lambdas = find_nearest(lambdas, line_wavelength) 

880 # reject if pixel index is too close to image bounds 

881 if l_index < peak_width or l_index > len(lambdas) - peak_width: 

882 continue 

883 # search for local extrema to detect emission or absorption line 

884 # around pixel index +/- peak_width 

885 line_strategy = np.greater # look for emission line 

886 bgd_strategy = np.less 

887 if not lines.emission_spectrum or line.atmospheric: 

888 line_strategy = np.less # look for absorption line 

889 bgd_strategy = np.greater 

890 index = np.arange(l_index - peak_width, l_index + peak_width, 1).astype(int) 

891 # skip if data is masked with NaN 

892 if np.any(np.isnan(spec_smooth[index])): 

893 continue 

894 extrema = argrelextrema(spec_smooth[index], line_strategy) 

895 if len(extrema[0]) == 0: 

896 continue 

897 peak_index = index[0] + extrema[0][0] 

898 # if several extrema, look for the greatest 

899 if len(extrema[0]) > 1: 

900 if line_strategy == np.greater: 

901 test = -1e20 

902 for m in extrema[0]: 

903 idx = index[0] + m 

904 if spec_smooth[idx] > test: 

905 peak_index = idx 

906 test = spec_smooth[idx] 

907 elif line_strategy == np.less: 

908 test = 1e20 

909 for m in extrema[0]: 

910 idx = index[0] + m 

911 if spec_smooth[idx] < test: 

912 peak_index = idx 

913 test = spec_smooth[idx] 

914 # search for first local minima around the local maximum 

915 # or for first local maxima around the local minimum 

916 # around +/- 3*peak_width 

917 index_inf = peak_index - 1 # extrema on the left 

918 while index_inf > max(0, peak_index - 3 * peak_width): 

919 test_index = np.arange(index_inf, peak_index, 1).astype(int) 

920 minm = argrelextrema(spec_smooth[test_index], bgd_strategy) 

921 if len(minm[0]) > 0: 

922 index_inf = index_inf + minm[0][0] 

923 break 

924 else: 

925 index_inf -= 1 

926 index_sup = peak_index + 1 # extrema on the right 

927 while index_sup < min(len(spec_smooth) - 1, peak_index + 3 * peak_width): 

928 test_index = np.arange(peak_index, index_sup, 1).astype(int) 

929 minm = argrelextrema(spec_smooth[test_index], bgd_strategy) 

930 if len(minm[0]) > 0: 

931 index_sup = peak_index + minm[0][0] 

932 break 

933 else: 

934 index_sup += 1 

935 index_sup = max(index_sup, peak_index + peak_width) 

936 index_inf = min(index_inf, peak_index - peak_width) 

937 # pixel range to consider around the peak, adding bgd_width pixels 

938 # to fit for background around the peak 

939 index = list(np.arange(max(0, index_inf - bgd_width), 

940 min(len(lambdas), index_sup + bgd_width), 1).astype(int)) 

941 # skip if data is masked with NaN 

942 if np.any(np.isnan(spec_smooth[index])): 

943 continue 

944 # first guess and bounds to fit the line properties and 

945 # the background with CALIB_BGD_ORDER order polynom 

946 # guess = [0] * bgd_npar + [0.5 * np.max(spec_smooth[index]), lambdas[peak_index], 

947 # 0.5 * (line.width_bounds[0] + line.width_bounds[1])] 

948 bgd_npar = max(parameters.CALIB_BGD_NPARAMS, int(len_index_to_bgd_npar_factor * (index[-1] - index[0]))) 

949 bgd_npar_list.append(bgd_npar) 

950 guess = [0] * bgd_npar + [0.5 * np.max(spec_smooth[index]), line_wavelength, 

951 0.5 * (line.width_bounds[0] + line.width_bounds[1])] 

952 if line_strategy == np.less: 

953 # noinspection PyTypeChecker 

954 guess[bgd_npar] = -0.5 * np.max(spec_smooth[index]) # look for abosrption under bgd 

955 # bounds = [[-np.inf] * bgd_npar + [-abs(np.max(spec[index])), lambdas[index_inf], line.width_bounds[0]], 

956 # [np.inf] * bgd_npar + [abs(np.max(spec[index])), lambdas[index_sup], line.width_bounds[1]]] 

957 bounds = [[-np.inf] * bgd_npar + [-abs(np.max(spec[index])), line_wavelength - peak_width / 2, 

958 line.width_bounds[0]], 

959 [np.inf] * bgd_npar + [abs(np.max(spec[index])), line_wavelength + peak_width / 2, 

960 line.width_bounds[1]]] 

961 # gaussian amplitude bounds depend if line is emission/absorption 

962 if line_strategy == np.less: 

963 bounds[1][bgd_npar] = 0 # look for absorption under bgd 

964 else: 

965 bounds[0][bgd_npar] = 0 # look for emission above bgd 

966 peak_index_list.append(peak_index) 

967 index_list.append(index) 

968 lines_list.append(line) 

969 guess_list.append(guess) 

970 bounds_list.append(bounds) 

971 # now gather lines together if pixel index ranges overlap 

972 idx = 0 

973 merges = [[0]] 

974 while idx < len(index_list) - 1: 

975 idx = merges[-1][-1] 

976 if idx == len(index_list) - 1: 

977 break 

978 if index_list[idx + 1][0] > index_list[idx][0]: # increasing order 

979 if index_list[idx][-1] > index_list[idx + 1][0]: 

980 merges[-1].append(idx + 1) 

981 else: 

982 merges.append([idx + 1]) 

983 idx += 1 

984 else: # decreasing order 

985 if index_list[idx][0] < index_list[idx + 1][-1]: 

986 merges[-1].append(idx + 1) 

987 else: 

988 merges.append([idx + 1]) 

989 idx += 1 

990 # reorder merge list with respect to lambdas in guess list 

991 new_merges = [] 

992 for merge in merges: 

993 if len(guess_list) == 0: 

994 continue 

995 tmp_guess = [guess_list[i][-2] for i in merge] 

996 new_merges.append([x for _, x in sorted(zip(tmp_guess, merge))]) 

997 # reorder lists with merges 

998 new_peak_index_list = [] 

999 new_index_list = [] 

1000 new_guess_list = [] 

1001 new_bounds_list = [] 

1002 new_lines_list = [] 

1003 for merge in new_merges: 

1004 new_peak_index_list.append([]) 

1005 new_index_list.append([]) 

1006 new_guess_list.append([]) 

1007 new_bounds_list.append([[], []]) 

1008 new_lines_list.append([]) 

1009 for i in merge: 

1010 # add the bgd parameters 

1011 bgd_npar = bgd_npar_list[i] 

1012 # if i == merge[0]: 

1013 # new_guess_list[-1] += guess_list[i][:bgd_npar] 

1014 # new_bounds_list[-1][0] += bounds_list[i][0][:bgd_npar] 

1015 # new_bounds_list[-1][1] += bounds_list[i][1][:bgd_npar] 

1016 # add the gauss parameters 

1017 new_peak_index_list[-1].append(peak_index_list[i]) 

1018 new_index_list[-1] += index_list[i] 

1019 new_guess_list[-1] += guess_list[i][bgd_npar:] 

1020 new_bounds_list[-1][0] += bounds_list[i][0][bgd_npar:] 

1021 new_bounds_list[-1][1] += bounds_list[i][1][bgd_npar:] 

1022 new_lines_list[-1].append(lines_list[i]) 

1023 # set central peak bounds exactly between two close lines 

1024 for k in range(len(merge) - 1): 

1025 new_bounds_list[-1][0][3 * (k + 1) + 1] = 0.5 * ( 

1026 new_guess_list[-1][3 * k + 1] + new_guess_list[-1][3 * (k + 1) + 1]) 

1027 new_bounds_list[-1][1][3 * k + 1] = 0.5 * ( 

1028 new_guess_list[-1][3 * k + 1] + new_guess_list[-1][3 * (k + 1) + 1]) + 1e-3 

1029 # last term is to avoid equalities 

1030 # between bounds in some pathological case 

1031 # sort pixel indices and remove doublons 

1032 new_index_list[-1] = sorted(list(set(new_index_list[-1]))) 

1033 # fit the line subsets and background 

1034 global_chisq = 0 

1035 for k in range(len(new_index_list)): 

1036 # first guess for the base line with the lateral bands 

1037 peak_index = new_peak_index_list[k] 

1038 index = new_index_list[k] 

1039 guess = new_guess_list[k] 

1040 bounds = new_bounds_list[k] 

1041 bgd_index = [] 

1042 if fwhm_func is not None: 

1043 peak_width = fwhm_to_peak_width_factor * np.mean(fwhm_func(lambdas[index])) 

1044 for i in index: 

1045 is_close_to_peak = False 

1046 for j in peak_index: 

1047 if abs(i - j) < peak_width: 

1048 is_close_to_peak = True 

1049 break 

1050 if not is_close_to_peak: 

1051 bgd_index.append(i) 

1052 # add background guess and bounds 

1053 bgd_npar = max(parameters.CALIB_BGD_ORDER + 1, int(len_index_to_bgd_npar_factor * len(bgd_index))) 

1054 parameters.CALIB_BGD_NPARAMS = bgd_npar 

1055 guess = [0] * bgd_npar + guess 

1056 bounds[0] = [-np.inf] * bgd_npar + bounds[0] 

1057 bounds[1] = [np.inf] * bgd_npar + bounds[1] 

1058 if len(bgd_index) > 0: 

1059 try: 

1060 if spec_err is not None: 

1061 w = 1. / spec_err[bgd_index] 

1062 else: 

1063 w = np.ones_like(lambdas[bgd_index]) 

1064 fit, cov, model = fit_poly1d_legendre(lambdas[bgd_index], spec[bgd_index], order=bgd_npar - 1, w=w) 

1065 except: 

1066 if spec_err is not None: 

1067 w = 1. / spec_err[index] 

1068 else: 

1069 w = np.ones_like(lambdas[index]) 

1070 fit, cov, model = fit_poly1d_legendre(lambdas[index], spec[index], order=bgd_npar - 1, w=w) 

1071 else: 

1072 if spec_err is not None: 

1073 w = 1. / spec_err[index] 

1074 else: 

1075 w = np.ones_like(lambdas[index]) 

1076 fit, cov, model = fit_poly1d_legendre(lambdas[index], spec[index], order=bgd_npar - 1, w=w) 

1077 # lines.my_logger.warning(f'{bgd_npar} {fit}') 

1078 # fig = plt.figure() 

1079 # plt.plot(lambdas[index], spec[index]) 

1080 # plt.plot(lambdas[bgd_index], spec[bgd_index], 'ro') 

1081 # x_norm = rescale_x_for_legendre(lambdas[index]) 

1082 # lines.my_logger.warning(f'tototot {x_norm}') 

1083 # plt.plot(lambdas[index], np.polynomial.legendre.legval(x_norm, fit), 'b-') 

1084 # plt.plot(lambdas[bgd_index], model, 'b--') 

1085 # plt.title(f"{fit}") 

1086 # plt.show() 

1087 for n in range(bgd_npar): 

1088 # guess[n] = getattr(bgd, bgd.param_names[parameters.CALIB_BGD_ORDER - n]).value 

1089 guess[n] = fit[n] 

1090 b = abs(baseline_prior * guess[n]) 

1091 if np.isclose(b, 0, rtol=1e-2 * float(np.mean(spec_smooth[bgd_index]))): 

1092 b = baseline_prior * np.std(spec_smooth[bgd_index]) 

1093 if np.isclose(b, 0, rtol=1e-2 * float(np.mean(spec_smooth[bgd_index]))): 

1094 b = np.inf 

1095 bounds[0][n] = guess[n] - b 

1096 bounds[1][n] = guess[n] + b 

1097 for j in range(len(new_lines_list[k])): 

1098 idx = new_peak_index_list[k][j] 

1099 x_norm = rescale_x_for_legendre(lambdas[idx]) 

1100 guess[bgd_npar + 3 * j] = np.sign(guess[bgd_npar + 3 * j]) * abs( 

1101 spec_smooth[idx] - np.polynomial.legendre.legval(x_norm, guess[:bgd_npar])) 

1102 if np.sign(guess[bgd_npar + 3 * j]) < 0: # absorption 

1103 bounds[0][bgd_npar + 3 * j] = 2 * guess[bgd_npar + 3 * j] 

1104 else: # emission 

1105 bounds[1][bgd_npar + 3 * j] = 2 * guess[bgd_npar + 3 * j] 

1106 # fit local extrema with a multigaussian + CALIB_BGD_ORDER polynom 

1107 # account for the spectrum uncertainties if provided 

1108 sigma = None 

1109 if spec_err is not None: 

1110 sigma = spec_err[index] 

1111 if cov_matrix is not None: 

1112 sigma = cov_matrix[index, index] 

1113 # my_logger.warning(f'\n{guess} {np.mean(spec[bgd_index])} {np.std(spec[bgd_index])}') 

1114 popt, pcov = fit_multigauss_and_bgd(lambdas[index], spec[index], guess=guess, bounds=bounds, sigma=sigma) 

1115 # noise level defined as the std of the residuals if no error 

1116 noise_level = np.std(spec[index] - multigauss_and_bgd(lambdas[index], *popt)) 

1117 # otherwise mean of error bars of bgd lateral bands 

1118 if sigma is not None: 

1119 chisq = np.sum((multigauss_and_bgd(lambdas[index], *popt) - spec[index]) ** 2 / (sigma * sigma)) 

1120 else: 

1121 chisq = np.sum((multigauss_and_bgd(lambdas[index], *popt) - spec[index]) ** 2) 

1122 chisq /= len(index) 

1123 global_chisq += chisq 

1124 if spec_err is not None: 

1125 noise_level = np.sqrt(np.mean(spec_err[index] ** 2)) 

1126 

1127 for j in range(len(new_lines_list[k])): 

1128 line = new_lines_list[k][j] 

1129 peak_pos = popt[bgd_npar + 3 * j + 1] 

1130 # FWHM 

1131 FWHM = np.abs(popt[bgd_npar + 3 * j + 2]) * 2.355 

1132 # SNR computation 

1133 # signal_level = popt[bgd_npar+3*j] 

1134 signal_level = popt[ 

1135 bgd_npar + 3 * j] # multigauss_and_bgd(peak_pos, *popt) - np.polyval(popt[:bgd_npar], peak_pos) 

1136 snr = np.abs(signal_level / noise_level) 

1137 # save fit results 

1138 line.fitted = True 

1139 line.fit_index = index 

1140 line.fit_lambdas = lambdas[index] 

1141 

1142 x_norm = rescale_x_for_legendre(lambdas[index]) 

1143 

1144 x_step = 0.1 # nm 

1145 x_int = np.arange(max(np.min(lambdas), peak_pos - 5 * np.abs(popt[bgd_npar + 3 * j + 2])), 

1146 min(np.max(lambdas), peak_pos + 5 * np.abs(popt[bgd_npar + 3 * j + 2])), x_step) 

1147 middle = 0.5 * (np.max(lambdas[index]) + np.min(lambdas[index])) 

1148 x_int_norm = x_int - middle 

1149 if np.max(lambdas[index] - middle) != 0: 

1150 x_int_norm = x_int_norm / np.max(lambdas[index] - middle) 

1151 

1152 # jmin and jmax a bit larger than x_int to avoid extrapolation 

1153 jmin = max(0, int(np.argmin(np.abs(lambdas - (x_int[0] - x_step))) - 2)) 

1154 jmax = min(len(lambdas), int(np.argmin(np.abs(lambdas - (x_int[-1] + x_step))) + 2)) 

1155 if jmax-2 < jmin+2: # decreasing order 

1156 jmin, jmax = max(0, jmax-4), min(len(lambdas), jmin+4) 

1157 spectr_data = interp1d(lambdas[jmin:jmax], spec[jmin:jmax], 

1158 bounds_error=False, fill_value="extrapolate")(x_int) 

1159 

1160 Continuum = np.polynomial.legendre.legval(x_int_norm, popt[:bgd_npar]) 

1161 Gauss = gauss(x_int, *popt[bgd_npar + 3 * j:bgd_npar + 3 * j + 3]) 

1162 

1163 Y = -Gauss / Continuum 

1164 Ydata = 1 - spectr_data / Continuum 

1165 

1166 line.fit_eqwidth_mod = integrate.simps(Y, x_int) # sol1 

1167 line.fit_eqwidth_data = integrate.simps(Ydata, x_int) # sol2 

1168 

1169 line.fit_popt = popt 

1170 line.fit_popt_gaussian = popt[bgd_npar + 3 * j:bgd_npar + 3 * j + 3] 

1171 line.fit_gauss = gauss(lambdas[index], *popt[bgd_npar + 3 * j:bgd_npar + 3 * j + 3]) 

1172 

1173 line.fit_bgd = np.polynomial.legendre.legval(x_norm, popt[:bgd_npar]) 

1174 line.fit_snr = snr 

1175 line.fit_chisq = chisq 

1176 line.fit_fwhm = FWHM 

1177 line.fit_bgd_npar = bgd_npar 

1178 if snr < snr_minlevel: 

1179 continue 

1180 line.high_snr = True 

1181 if line.use_for_calibration: 

1182 # wavelength shift between tabulate and observed lines 

1183 lambda_shifts.append(peak_pos - line.wavelength) 

1184 snrs.append(snr) 

1185 if ax is not None: 

1186 lines.plot_detected_lines(ax, print_table=parameters.DEBUG) 

1187 if len(lambda_shifts) > 0: 

1188 global_chisq /= len(lambda_shifts) 

1189 shift = np.average(np.abs(lambda_shifts) ** 2, weights=np.array(snrs) ** 2) 

1190 # if guess values on tabulated lines have not moved: penalize the chisq 

1191 global_chisq += shift 

1192 # lines.my_logger.debug(f'\n\tNumber of calibration lines detected {len(lambda_shifts):d}' 

1193 # f'\n\tTotal chisq: {global_chisq:.3f} with shift {shift:.3f}pix') 

1194 else: 

1195 global_chisq = 2 * len(parameters.LAMBDAS) 

1196 # lines.my_logger.debug( 

1197 # f'\n\tNumber of calibration lines detected {len(lambda_shifts):d}\n\tTotal chisq: {global_chisq:.3f}') 

1198 return global_chisq 

1199 

1200 

1201def calibrate_spectrum(spectrum, with_adr=False): 

1202 """Convert pixels into wavelengths given the position of the order 0, 

1203 the data for the spectrum, the properties of the disperser. Fit the absorption 

1204 (and eventually the emission) lines to perform a second calibration of the 

1205 distance between the CCD and the disperser. The number of fitting steps is 

1206 limited to 30. 

1207 

1208 Finally convert the spectrum amplitude from ADU rate to erg/s/cm2/nm. 

1209 

1210 Parameters 

1211 ---------- 

1212 spectrum: Spectrum 

1213 Spectrum object to calibrate 

1214 with_adr: bool, optional 

1215 If True, the ADR longitudinal shift is subtracted to distances. 

1216 Must be False if the spectrum has already been decontaminated from ADR (default: False). 

1217 

1218 Returns 

1219 ------- 

1220 lambdas: array_like 

1221 The new wavelength array in nm. 

1222 

1223 Examples 

1224 -------- 

1225 >>> spectrum = Spectrum('tests/data/reduc_20170605_028_spectrum.fits') 

1226 >>> parameters.LAMBDA_MIN = 550 

1227 >>> parameters.LAMBDA_MAX = 800 

1228 >>> lambdas = calibrate_spectrum(spectrum, with_adr=False) 

1229 >>> spectrum.plot_spectrum() 

1230 """ 

1231 with_adr = int(with_adr) 

1232 distance = spectrum.chromatic_psf.get_algebraic_distance_along_dispersion_axis() 

1233 spectrum.lambdas = spectrum.disperser.grating_pixel_to_lambda(distance, spectrum.x0, order=spectrum.order) 

1234 if spectrum.lambda_ref is None: 

1235 lambda_ref = np.sum(spectrum.lambdas * spectrum.data) / np.sum(spectrum.data) 

1236 spectrum.lambda_ref = lambda_ref 

1237 spectrum.header['LBDA_REF'] = lambda_ref 

1238 # ADR is x>0 westward and y>0 northward while CTIO images are x>0 westward and y>0 southward 

1239 # Must project ADR along dispersion axis 

1240 if with_adr > 0: 

1241 adr_ra, adr_dec = adr_calib(spectrum.lambdas, spectrum.adr_params, parameters.OBS_LATITUDE, 

1242 lambda_ref=spectrum.lambda_ref) 

1243 adr_u, _ = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec, 

1244 dispersion_axis_angle=spectrum.rotation_angle) 

1245 else: 

1246 adr_u = np.zeros_like(distance) 

1247 x0 = spectrum.x0 

1248 if x0 is None: 

1249 x0 = spectrum.target_pixcoords 

1250 spectrum.x0 = x0 

1251 

1252 # Detect emission/absorption lines and calibrate pixel/lambda 

1253 fwhm_func = interp1d(spectrum.chromatic_psf.table['lambdas'], 

1254 spectrum.chromatic_psf.table['fwhm'], 

1255 fill_value=(parameters.CALIB_PEAK_WIDTH, parameters.CALIB_PEAK_WIDTH), bounds_error=False) 

1256 

1257 def shift_minimizer(params): 

1258 spectrum.disperser.D, shift = params 

1259 if np.isnan(spectrum.disperser.D): # reset the value in case of bad gradient descent 

1260 spectrum.disperser.D = parameters.DISTANCE2CCD 

1261 if np.isnan(shift): # reset the value in case of bad gradient descent 

1262 shift = 0 

1263 dist = spectrum.chromatic_psf.get_algebraic_distance_along_dispersion_axis(shift_x=shift) 

1264 spectrum.lambdas = spectrum.disperser.grating_pixel_to_lambda(dist - with_adr * adr_u, 

1265 x0=[x0[0] + shift, x0[1]], order=spectrum.order) 

1266 spectrum.lambdas_binwidths = np.gradient(spectrum.lambdas) 

1267 spectrum.convert_from_ADUrate_to_flam() 

1268 chisq = detect_lines(spectrum.lines, spectrum.lambdas, spectrum.data, spec_err=spectrum.err, 

1269 fwhm_func=fwhm_func, ax=None, calibration_lines_only=True) 

1270 chisq += ((shift) / parameters.PIXSHIFT_PRIOR) ** 2 

1271 if parameters.DEBUG and parameters.DISPLAY: 

1272 if parameters.LIVE_FIT: 

1273 spectrum.plot_spectrum(live_fit=True, label=f'Order {spectrum.order:d} spectrum\n' 

1274 r'$D_\mathrm{CCD}' 

1275 rf'={D:.2f}\,$mm, $\delta u_0={shift:.2f}\,$pix') 

1276 spectrum.convert_from_flam_to_ADUrate() 

1277 return chisq 

1278 

1279 # grid exploration of the parameters 

1280 # necessary because of the the line detection algo 

1281 D = parameters.DISTANCE2CCD 

1282 if spectrum.header['D2CCD'] != '': 

1283 D = spectrum.header['D2CCD'] 

1284 D_err = parameters.DISTANCE2CCD_ERR 

1285 D_step = D_err / 2 

1286 pixel_shift_step = parameters.PIXSHIFT_PRIOR / 5 

1287 pixel_shift_prior = parameters.PIXSHIFT_PRIOR 

1288 Ds = np.arange(D - 5 * D_err, D + 6 * D_err, D_step) 

1289 pixel_shifts = np.arange(-pixel_shift_prior, pixel_shift_prior + pixel_shift_step, pixel_shift_step) 

1290 # pixel_shifts = np.array([0]) 

1291 chisq_grid = np.zeros((len(Ds), len(pixel_shifts))) 

1292 for i, D in enumerate(Ds): 

1293 for j, pixel_shift in enumerate(pixel_shifts): 

1294 chisq_grid[i, j] = shift_minimizer([D, pixel_shift]) 

1295 imin, jmin = np.unravel_index(chisq_grid.argmin(), chisq_grid.shape) 

1296 D = Ds[imin] 

1297 pixel_shift = pixel_shifts[jmin] 

1298 start = np.array([D, pixel_shift]) 

1299 if imin == 0 or imin == Ds.size or jmin == 0 or jmin == pixel_shifts.size: 

1300 spectrum.my_logger.warning('\n\tMinimum chisq is on the edge of the exploration grid.') 

1301 if parameters.DEBUG: 

1302 fig = plt.figure(figsize=(7, 4)) 

1303 im = plt.imshow(np.log10(chisq_grid), origin='lower', aspect='auto', 

1304 extent=( 

1305 np.min(pixel_shifts) - pixel_shift_step / 2, np.max(pixel_shifts) + pixel_shift_step / 2, 

1306 np.min(Ds) - D_step / 2, np.max(Ds) + D_step / 2)) 

1307 plt.gca().scatter(pixel_shift, D, marker='o', s=100, edgecolors='k', facecolors='none', 

1308 label='Minimum', linewidth=2) 

1309 c = plt.colorbar(im) 

1310 c.set_label('Log10(chisq)') 

1311 plt.xlabel(r'Pixel shift $\delta u_0$ [pix]') 

1312 plt.ylabel(r'$D_\mathrm{CCD}$ [mm]') 

1313 plt.legend() 

1314 if parameters.DISPLAY: # pragma: no cover 

1315 plt.show() 

1316 if parameters.LSST_SAVEFIGPATH: # pragma: no cover 

1317 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'D2CCD_x0_fit.pdf')) 

1318 # now minimize around the global minimum found previously 

1319 # res = opt.minimize(shift_minimizer, start, args=(), method='L-BFGS-B', 

1320 # options={'maxiter': 200, 'ftol': 1e-3}, 

1321 # bounds=((D - 5 * parameters.DISTANCE2CCD_ERR, D + 5 * parameters.DISTANCE2CCD_ERR), (-2, 2))) 

1322 error = [parameters.DISTANCE2CCD_ERR, pixel_shift_step] 

1323 fix = [False, False] 

1324 m = Minuit(shift_minimizer, start) 

1325 m.errors = error 

1326 m.errordef = 1 

1327 m.fixed = fix 

1328 m.print_level = 0 

1329 m.limits = ((D - 5 * parameters.DISTANCE2CCD_ERR, D + 5 * parameters.DISTANCE2CCD_ERR), (-2, 2)) 

1330 m.migrad() 

1331 # if parameters.DEBUG: 

1332 # print(m.prin) 

1333 # if not res.success: 

1334 # spectrum.my_logger.warning('\n\tMinimizer failed.') 

1335 # print(res) 

1336 D, pixel_shift = np.array(m.values[:]) 

1337 spectrum.disperser.D = D 

1338 x0 = [x0[0] + pixel_shift, x0[1]] 

1339 spectrum.x0 = x0 

1340 # check success, xO or D on the edge of their priors 

1341 distance = spectrum.chromatic_psf.get_algebraic_distance_along_dispersion_axis(shift_x=pixel_shift) 

1342 lambdas = spectrum.disperser.grating_pixel_to_lambda(distance - with_adr * adr_u, x0=x0, order=spectrum.order) 

1343 spectrum.lambdas = lambdas 

1344 spectrum.lambdas_order2 = spectrum.disperser.grating_pixel_to_lambda(distance - with_adr * adr_u, x0=x0, 

1345 order=spectrum.order + 1) 

1346 spectrum.lambdas_binwidths = np.gradient(lambdas) 

1347 spectrum.convert_from_ADUrate_to_flam() 

1348 spectrum.chromatic_psf.table['Dx'] -= pixel_shift 

1349 spectrum.chromatic_psf.table['Dy_disp_axis'] = distance * np.sin(spectrum.rotation_angle * np.pi / 180) 

1350 spectrum.pixels = np.copy(spectrum.chromatic_psf.table['Dx']) 

1351 detect_lines(spectrum.lines, spectrum.lambdas, spectrum.data, spec_err=spectrum.err, 

1352 fwhm_func=fwhm_func, ax=None, calibration_lines_only=False) 

1353 # Convert back to flam units 

1354 # spectrum.convert_from_ADUrate_to_flam() 

1355 spectrum.my_logger.info( 

1356 f"\n\tOrder0 total shift: {pixel_shift:.3f}pix" 

1357 f"\n\tD = {D:.3f} mm (default: DISTANCE2CCD = {parameters.DISTANCE2CCD:.2f} " 

1358 f"+/- {parameters.DISTANCE2CCD_ERR:.2f} mm, " 

1359 f"{(D - parameters.DISTANCE2CCD) / parameters.DISTANCE2CCD_ERR:.1f} sigma shift)") 

1360 spectrum.header['PIXSHIFT'] = pixel_shift 

1361 spectrum.header['D2CCD'] = D 

1362 return lambdas 

1363 

1364 

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

1366 import doctest 

1367 

1368 doctest.testmod()