Coverage for spectractor/extractor/extractor.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

618 statements  

1import os 

2import copy 

3import numpy as np 

4import matplotlib.pyplot as plt 

5from matplotlib import cm 

6from scipy.interpolate import interp1d 

7from scipy import sparse 

8import time 

9 

10from spectractor import parameters 

11from spectractor.config import set_logger, load_config 

12from spectractor.extractor.images import Image, find_target, turn_image 

13from spectractor.extractor.spectrum import Spectrum, calibrate_spectrum 

14from spectractor.extractor.background import extract_spectrogram_background_sextractor 

15from spectractor.extractor.chromaticpsf import ChromaticPSF 

16from spectractor.extractor.psf import load_PSF 

17from spectractor.tools import ensure_dir, plot_image_simple, from_lambda_to_colormap, plot_spectrum_simple 

18from spectractor.simulation.adr import adr_calib, flip_and_rotate_adr_to_image_xy_coordinates 

19from spectractor.fit.fitter import run_minimisation, run_minimisation_sigma_clipping, RegFitWorkspace, FitWorkspace 

20 

21def dumpParameters(): 

22 for item in dir(parameters): 

23 if not item.startswith("__"): 

24 print(item, getattr(parameters, item)) 

25 

26class FullForwardModelFitWorkspace(FitWorkspace): 

27 

28 def __init__(self, spectrum, amplitude_priors_method="noprior", nwalkers=18, nsteps=1000, burnin=100, nbins=10, 

29 verbose=0, plot=False, live_fit=False, truth=None): 

30 """Class to fit a full forward model on data to extract a spectrum, with ADR prediction and order 2 subtraction. 

31 

32 Parameters 

33 ---------- 

34 spectrum: Spectrum 

35 amplitude_priors_method 

36 nwalkers 

37 nsteps 

38 burnin 

39 nbins 

40 verbose 

41 plot 

42 live_fit 

43 truth 

44 

45 Examples 

46 -------- 

47 >>> spec = Spectrum("./tests/data/sim_20170530_134_spectrum.fits", config="./config/ctio.ini") 

48 >>> w = FullForwardModelFitWorkspace(spectrum=spec, amplitude_priors_method="spectrum") 

49 """ 

50 FitWorkspace.__init__(self, spectrum.filename, nwalkers, nsteps, burnin, nbins, verbose, plot, 

51 live_fit, truth=truth) 

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

53 self.spectrum = spectrum 

54 

55 # check the shapes 

56 self.Ny, self.Nx = spectrum.spectrogram.shape 

57 # if self.Ny != self.spectrum.chromatic_psf.Ny: 

58 # raise AttributeError(f"Data y shape {self.Ny} different from " 

59 # f"ChromaticPSF input Ny {spectrum.chromatic_psf.Ny}.") 

60 # if self.Nx != self.spectrum.chromatic_psf.Nx: 

61 # raise AttributeError(f"Data x shape {self.Nx} different from " 

62 # f"ChromaticPSF input Nx {spectrum.chromatic_psf.Nx}.") 

63 

64 # crop data to fit faster 

65 self.lambdas = self.spectrum.lambdas 

66 self.lambdas_order2 = self.spectrum.lambdas_order2 

67 self.bgd_width = parameters.PIXWIDTH_BACKGROUND + parameters.PIXDIST_BACKGROUND - parameters.PIXWIDTH_SIGNAL 

68 self.data = spectrum.spectrogram[self.bgd_width:-self.bgd_width, :] 

69 self.err = spectrum.spectrogram_err[self.bgd_width:-self.bgd_width, :] 

70 self.bgd = spectrum.spectrogram_bgd[self.bgd_width:-self.bgd_width, :] 

71 self.bgd_flat = self.bgd.flatten() 

72 self.Ny, self.Nx = self.data.shape 

73 yy, xx = np.mgrid[:self.Ny, :self.Nx] 

74 self.pixels = np.asarray([xx, yy]) 

75 

76 # prepare parameters to fit 

77 self.A2 = 1 

78 self.D = np.copy(self.spectrum.header['D2CCD']) 

79 self.shift_x = np.copy(self.spectrum.header['PIXSHIFT']) 

80 self.shift_y = 0. 

81 self.angle = np.copy(self.spectrum.rotation_angle) 

82 self.B = 1 

83 self.rotation = parameters.OBS_CAMERA_ROTATION 

84 self.psf_poly_params = np.copy(self.spectrum.chromatic_psf.from_table_to_poly_params()) 

85 self.psf_profile_params = np.copy(self.spectrum.chromatic_psf.from_table_to_profile_params()) 

86 length = len(self.spectrum.chromatic_psf.table) 

87 self.psf_poly_params = self.psf_poly_params[length:] 

88 self.psf_poly_params_labels = np.copy(self.spectrum.chromatic_psf.poly_params_labels[length:]) 

89 self.psf_poly_params_names = np.copy(self.spectrum.chromatic_psf.poly_params_names[length:]) 

90 self.psf_poly_params_bounds = self.spectrum.chromatic_psf.set_bounds_for_minuit(data=None) 

91 self.spectrum.chromatic_psf.psf.apply_max_width_to_bounds(max_half_width=self.spectrum.spectrogram_Ny) 

92 psf_poly_params_bounds = self.spectrum.chromatic_psf.set_bounds() 

93 self.saturation = self.spectrum.spectrogram_saturation 

94 self.p = np.array([self.A2, self.D, self.shift_x, self.shift_y, self.angle, self.B, self.rotation]) 

95 self.psf_params_start_index = self.p.size 

96 self.p = np.concatenate([self.p, self.psf_poly_params]) 

97 self.input_labels = ["A2", r"D_CCD [mm]", r"shift_x [pix]", r"shift_y [pix]", 

98 r"angle [deg]", "B", "R"] + list(self.psf_poly_params_labels) 

99 self.axis_names = ["$A_2$", r"$D_{CCD}$ [mm]", r"$\Delta_{\mathrm{x}}$ [pix]", r"$\Delta_{\mathrm{y}}$ [pix]", 

100 r"$\theta$ [deg]", "$B$", "R"] + list(self.psf_poly_params_names) 

101 bounds_D = (self.D - 5 * parameters.DISTANCE2CCD_ERR, self.D + 5 * parameters.DISTANCE2CCD_ERR) 

102 self.bounds = np.concatenate([np.array([(0, 2 / parameters.GRATING_ORDER_2OVER1), bounds_D, 

103 (-parameters.PIXSHIFT_PRIOR, parameters.PIXSHIFT_PRIOR), 

104 (-10 * parameters.CCD_PIXEL2ARCSEC, 10 * parameters.PIXSHIFT_PRIOR), 

105 (-90, 90), (0.2, 5), (-360, 360)]), psf_poly_params_bounds]) 

106 self.fixed = [False] * self.p.size 

107 for k, par in enumerate(self.input_labels): 

108 if "x_c" in par or "saturation" in par or "y_c" in par: 

109 self.fixed[k] = True 

110 # This set of fixed parameters was determined so that the reconstructed spectrum has a ZERO bias 

111 # with respect to the true spectrum injected in the simulation 

112 # A2 is free only if spectrogram is a simulation or if the order 2/1 ratio is not known and flat 

113 self.fixed[0] = not self.spectrum.disperser.flat_ratio_order_2over1 

114 self.fixed[1] = True # D2CCD: spectrogram can not tell something on this parameter: rely on calibrate_pectrum 

115 self.fixed[2] = True # delta x: if False, extracted spectrum is biased compared with truth 

116 # self.fixed[3] = True # delta y 

117 # self.fixed[4] = True # angle 

118 self.fixed[5] = True # B: not needed in simulations, to check with data 

119 self.fixed[6] = True # camera rot 

120 self.fixed[-1] = True # saturation 

121 self.nwalkers = max(2 * self.ndim, nwalkers) 

122 

123 # prepare the background, data and errors 

124 self.bgd_std = float(np.std(np.random.poisson(np.abs(self.bgd)))) 

125 

126 # error matrix 

127 # here image uncertainties are assumed to be uncorrelated 

128 # (which is not exactly true in rotated images) 

129 self.W = 1. / (self.err * self.err) 

130 self.W = self.W.flatten() 

131 

132 # flat data for fitworkspace 

133 self.data = self.data.flatten() - self.bgd_flat 

134 self.err = self.err.flatten() 

135 self.data_before_mask = np.copy(self.data) 

136 self.W_before_mask = np.copy(self.W) 

137 

138 # create mask 

139 self.sqrtW = np.sqrt(sparse.diags(self.W)) 

140 self.sparse_indices = None 

141 self.set_mask() 

142 

143 # design matrix 

144 self.M = np.zeros((self.Nx, self.data.size)) 

145 self.M_dot_W_dot_M = np.zeros((self.Nx, self.Nx)) 

146 

147 # prepare results 

148 self.amplitude_params = np.zeros(self.Nx) 

149 self.amplitude_params_err = np.zeros(self.Nx) 

150 self.amplitude_cov_matrix = np.zeros((self.Nx, self.Nx)) 

151 

152 # priors on amplitude parameters 

153 self.amplitude_priors_list = ['noprior', 'positive', 'smooth', 'spectrum', 'fixed'] 

154 self.amplitude_priors_method = amplitude_priors_method 

155 self.fwhm_priors = np.copy(spectrum.chromatic_psf.table['fwhm']) 

156 self.reg = spectrum.chromatic_psf.opt_reg 

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

158 self.reg = float(spectrum.header['PSF_REG']) 

159 if self.reg < 0: 

160 self.reg = parameters.PSF_FIT_REG_PARAM 

161 self.my_logger.info(f"\n\tFull forward model fitting with regularisation parameter r={self.reg}.") 

162 self.Q = np.zeros((self.Nx, self.Nx)) 

163 self.Q_dot_A0 = np.zeros(self.Nx) 

164 if amplitude_priors_method not in self.amplitude_priors_list: 

165 raise ValueError(f"Unknown prior method for the amplitude fitting: {self.amplitude_priors_method}. " 

166 f"Must be either {self.amplitude_priors_list}.") 

167 self.spectrum.convert_from_flam_to_ADUrate() 

168 if self.amplitude_priors_method == "spectrum": 

169 self.amplitude_priors = np.copy(self.spectrum.data) 

170 self.amplitude_priors_cov_matrix = np.copy(self.spectrum.cov_matrix) 

171 if self.amplitude_priors_method == "fixed": 

172 self.amplitude_priors = np.copy(self.spectrum.data) 

173 

174 # regularisation matrices 

175 if amplitude_priors_method == "spectrum": 

176 # U = np.diag([1 / np.sqrt(np.sum(self.err[:, x]**2)) for x in range(self.Nx)]) 

177 self.U = np.diag([1 / np.sqrt(self.amplitude_priors_cov_matrix[x, x]) for x in range(self.Nx)]) 

178 L = np.diag(-2 * np.ones(self.Nx)) + np.diag(np.ones(self.Nx), -1)[:-1, :-1] \ 

179 + np.diag(np.ones(self.Nx), 1)[:-1, :-1] 

180 L.astype(float) 

181 L[0, 0] = -1 

182 L[-1, -1] = -1 

183 self.L = L 

184 self.Q = L.T @ np.linalg.inv(self.amplitude_priors_cov_matrix) @ L 

185 # self.Q = L.T @ U.T @ U @ L 

186 self.Q_dot_A0 = self.Q @ self.amplitude_priors 

187 

188 def set_mask(self, psf_poly_params=None): 

189 if psf_poly_params is None: 

190 psf_poly_params = self.psf_poly_params 

191 psf_profile_params = self.spectrum.chromatic_psf.from_poly_params_to_profile_params(psf_poly_params, 

192 apply_bounds=True) 

193 self.spectrum.chromatic_psf.from_profile_params_to_shape_params(psf_profile_params) 

194 psf_profile_params[:, 2] -= self.bgd_width 

195 psf_cube = self.spectrum.chromatic_psf.build_psf_cube(self.pixels, psf_profile_params, 

196 fwhmx_clip=3 * parameters.PSF_FWHM_CLIP, 

197 fwhmy_clip=parameters.PSF_FWHM_CLIP, dtype="float32") 

198 flat_spectrogram = np.sum(psf_cube.reshape(len(psf_profile_params), self.pixels[0].size), axis=0) 

199 mask = flat_spectrogram / np.max(flat_spectrogram) == 0 

200 self.data[mask] = 0 

201 self.W[mask] = 0 

202 self.sqrtW = np.sqrt(sparse.diags(self.W)) 

203 self.sparse_indices = None 

204 self.mask = list(np.where(mask)[0]) 

205 

206 def simulate(self, *params): 

207 r""" 

208 Compute a ChromaticPSF2D model given PSF shape parameters and minimizing 

209 amplitude parameters using a spectrogram data array. 

210 

211 The ChromaticPSF2D model :math:`\vec{m}(\vec{x},\vec{p})` can be written as 

212 

213 .. math :: 

214 :label: chromaticpsf2d 

215 

216 \vec{m}(\vec{x},\vec{p}) = \sum_{i=0}^{N_x} A_i \phi\left(\vec{x},\vec{p}_i\right) 

217 

218 with :math:`\vec{x}` the 2D array of the pixel coordinates, :math:`\vec{A}` the amplitude parameter array 

219 along the x axis of the spectrogram, :math:`\phi\left(\vec{x},\vec{p}_i\right)` the 2D PSF kernel whose integral 

220 is normalised to one parametrized with the :math:`\vec{p}_i` non-linear parameter array. If the :math:`\vec{x}` 

221 2D array is flatten in 1D, equation :eq:`chromaticpsf2d` is 

222 

223 .. math :: 

224 :label: chromaticpsf2d_matrix 

225 :nowrap: 

226 

227 \begin{align} 

228 \vec{m}(\vec{x},\vec{p}) & = \mathbf{M}\left(\vec{x},\vec{p}\right) \mathbf{A} \\ 

229 

230 \mathbf{M}\left(\vec{x},\vec{p}\right) & = \left(\begin{array}{cccc} 

231 \phi\left(\vec{x}_1,\vec{p}_1\right) & \phi\left(\vec{x}_2,\vec{p}_1\right) & ... 

232 & \phi\left(\vec{x}_{N_x},\vec{p}_1\right) \\ 

233 ... & ... & ... & ...\\ 

234 \phi\left(\vec{x}_1,\vec{p}_{N_x}\right) & \phi\left(\vec{x}_2,\vec{p}_{N_x}\right) & ... 

235 & \phi\left(\vec{x}_{N_x},\vec{p}_{N_x}\right) \\ 

236 \end{array}\right) 

237 \end{align} 

238 

239 

240 with :math:`\mathbf{M}` the design matrix. 

241 

242 The goal of this function is to perform a minimisation of the amplitude vector :math:`\mathbf{A}` given 

243 a set of non-linear parameters :math:`\mathbf{p}` and a spectrogram data array :math:`mathbf{y}` modelise as 

244 

245 .. math:: \mathbf{y} = \mathbf{m}(\vec{x},\vec{p}) + \vec{\epsilon} 

246 

247 with :math:`\vec{\epsilon}` a random noise vector. The :math:`\chi^2` function to minimise is 

248 

249 .. math:: 

250 :label: chromaticspsf2d_chi2 

251 

252 \chi^2(\mathbf{A})= \left(\mathbf{y} - \mathbf{M}\left(\vec{x},\vec{p}\right) \mathbf{A}\right)^T \mathbf{W} 

253 \left(\mathbf{y} - \mathbf{M}\left(\vec{x},\vec{p}\right) \mathbf{A} \right) 

254 

255 

256 with :math:`\mathbf{W}` the weight matrix, inverse of the covariance matrix. In our case this matrix is diagonal 

257 as the pixels are considered all independent. The minimum of equation :eq:`chromaticspsf2d_chi2` is reached for 

258 a the set of amplitude parameters :math:`\hat{\mathbf{A}}` given by 

259 

260 .. math:: 

261 

262 \hat{\mathbf{A}} = (\mathbf{M}^T \mathbf{W} \mathbf{M})^{-1} \mathbf{M}^T \mathbf{W} \mathbf{y} 

263 

264 The error matrix on the :math:`\hat{\mathbf{A}}` coefficient is simply 

265 :math:`(\mathbf{M}^T \mathbf{W} \mathbf{M})^{-1}`. 

266 

267 See Also 

268 -------- 

269 ChromaticPSF2DFitWorkspace.simulate 

270 

271 Parameters 

272 ---------- 

273 params: array_like 

274 Full forward model parameter array. 

275 

276 Examples 

277 -------- 

278 

279 Load data: 

280 

281 >>> spec = Spectrum("./tests/data/sim_20170530_134_spectrum.fits", config="./config/ctio.ini") 

282 

283 Simulate the data with fixed amplitude priors: 

284 

285 .. doctest:: 

286 

287 >>> w = FullForwardModelFitWorkspace(spectrum=spec, amplitude_priors_method="fixed", verbose=True) 

288 >>> y, mod, mod_err = w.simulate(*w.p) 

289 >>> w.plot_fit() 

290 

291 .. doctest:: 

292 :hide: 

293 

294 >>> assert mod is not None 

295 

296 Simulate the data with a Tikhonov prior on amplitude parameters: 

297 

298 .. doctest:: 

299 

300 >>> spec = Spectrum("./tests/data/sim_20170530_134_spectrum.fits", config="./config/ctio.ini") 

301 >>> w = FullForwardModelFitWorkspace(spectrum=spec, amplitude_priors_method="spectrum", verbose=True) 

302 >>> y, mod, mod_err = w.simulate(*w.p) 

303 >>> w.plot_fit() 

304 

305 """ 

306 # linear regression for the amplitude parameters 

307 # prepare the vectors 

308 A2, D2CCD, dx0, dy0, angle, B, rot, *poly_params = params 

309 parameters.OBS_CAMERA_ROTATION = rot 

310 self.p = np.asarray(params) 

311 W_dot_data = self.W * (self.data + (1 - B) * self.bgd_flat) 

312 profile_params = self.spectrum.chromatic_psf.from_poly_params_to_profile_params(poly_params, apply_bounds=True) 

313 profile_params[:, 0] = 1 

314 profile_params[:, 1] = np.arange(self.Nx) 

315 self.spectrum.chromatic_psf.fill_table_with_profile_params(profile_params) 

316 

317 # Distance in x and y with respect to the true order 0 position at lambda_ref 

318 Dx = np.arange(self.Nx) - self.spectrum.spectrogram_x0 - dx0 # distance in (x,y) spectrogram frame for column x 

319 Dy_disp_axis = np.tan(angle * np.pi / 180) * Dx # disp axis height in spectrogram frame for x 

320 distance = np.sign(Dx) * np.sqrt(Dx * Dx + Dy_disp_axis * Dy_disp_axis) # algebraic distance along dispersion axis 

321 self.spectrum.chromatic_psf.table["Dy_disp_axis"] = Dy_disp_axis 

322 self.spectrum.chromatic_psf.table["Dx"] = Dx 

323 

324 # First guess of wavelengths 

325 self.spectrum.disperser.D = np.copy(D2CCD) 

326 self.lambdas = self.spectrum.disperser.grating_pixel_to_lambda(distance, 

327 self.spectrum.x0 + np.asarray([dx0, dy0]), 

328 order=self.spectrum.order) 

329 self.lambdas_order2 = self.spectrum.disperser.grating_pixel_to_lambda(distance, 

330 self.spectrum.x0 + np.asarray([dx0, dy0]), 

331 order=self.spectrum.order+np.sign(self.spectrum.order)) 

332 

333 # Evaluate ADR 

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

335 lambda_ref=self.spectrum.lambda_ref) 

336 adr_x, adr_y = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec, dispersion_axis_angle=0) 

337 adr_u, adr_v = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec, dispersion_axis_angle=angle) 

338 # Compute lambdas at pixel column x 

339 # self.lambdas = self.spectrum.disperser.grating_pixel_to_lambda(distance - adr_u, 

340 # self.spectrum.x0 + np.asarray([dx0, dy0]), 

341 # order=1) 

342 

343 # Evaluate ADR for order 2 

344 adr_ra, adr_dec = adr_calib(self.lambdas_order2, self.spectrum.adr_params, parameters.OBS_LATITUDE, 

345 lambda_ref=self.spectrum.lambda_ref) 

346 adr_x_2, adr_y_2 = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec, dispersion_axis_angle=0) 

347 # adr_u_2, adr_v_2 = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec, dispersion_axis_angle=angle) 

348 # Compute lambdas at pixel column x for order 2 

349 # self.lambdas_order2 = self.spectrum.disperser.grating_pixel_to_lambda(distance - adr_u_2, 

350 # self.spectrum.x0 + np.asarray([dx0, dy0]), 

351 # order=2) 

352 

353 # Fill spectrogram trace as a function of the pixel column x 

354 profile_params[:, 1] = Dx + self.spectrum.spectrogram_x0 + adr_x + dx0 

355 profile_params[:, 2] = Dy_disp_axis + (self.spectrum.spectrogram_y0 + adr_y + dy0) - self.bgd_width 

356 # Dy_disp_axis = np.copy(profile_params[:, 2]) 

357 # profile_params[:, 2] += adr_y + dy0 - self.bgd_width 

358 

359 # Prepare order 2 profile params indexed by the pixel column x 

360 profile_params_order2 = np.copy(profile_params) 

361 profile_params_order2[:, 0] = self.spectrum.disperser.ratio_order_2over1(self.lambdas) 

362 profile_params_order2[:, 1] = np.arange(self.Nx) + adr_x_2 + dx0 

363 profile_params_order2[:, 2] = Dy_disp_axis + (self.spectrum.spectrogram_y0 + adr_y_2 + dy0) - self.bgd_width 

364 # profile_params_order2[:, 2] = Dy_disp_axis + adr_y_2 + dy0 - self.bgd_width 

365 

366 # For each A(lambda)=A_x, affect an order 2 PSF with correct position and 

367 # same PSF as for the order 1 but at the same position 

368 distance_order2 = self.spectrum.disperser.grating_lambda_to_pixel(self.lambdas - adr_u, 

369 self.spectrum.x0 + np.asarray([dx0, dy0]), 

370 order=self.spectrum.order+np.sign(self.spectrum.order)) 

371 for k in range(1, profile_params.shape[1]): 

372 # profile_params_order2[:, k] = interp1d(self.lambdas_order2, profile_params_order2[:, k], 

373 # kind="cubic", fill_value="extrapolate")(self.lambdas) 

374 profile_params_order2[:, k] = interp1d(distance, profile_params_order2[:, k], 

375 kind="cubic", fill_value="extrapolate")(distance_order2) 

376 

377 # if parameters.DEBUG: 

378 # plt.imshow(self.data.reshape((self.Ny, self.Nx)), origin="lower") 

379 # plt.scatter(profile_params[:, 1], profile_params[:, 2], label="profile", 

380 # cmap=from_lambda_to_colormap(self.lambdas), c=self.lambdas) 

381 # plt.scatter(profile_params_order2[:, 1], profile_params_order2[:, 2], label="order 2", 

382 # cmap=from_lambda_to_colormap(self.lambdas), c=self.lambdas) 

383 # plt.plot(profile_params[:, 1], profile_params[:, 2], label="profile") 

384 # plt.plot(profile_params[:, 1], Dy_disp_axis + self.spectrum.spectrogram_y0 + dy0 - self.bgd_width, 'k-', 

385 # label="disp_axis") 

386 # plt.plot(self.spectrum.chromatic_psf.table['Dx'] + self.spectrum.spectrogram_x0 + dx0, 

387 # self.spectrum.chromatic_psf.table['Dy'] + self.spectrum.spectrogram_y0 + dy0 - self.bgd_width, 

388 # label="y_c") 

389 # plt.legend() 

390 # plt.title(f"D_CCD={D2CCD:.2f}, dx0={dx0:.2g}, dy0={dy0:.2g}") 

391 # plt.xlim((0, self.Nx)) 

392 # plt.ylim((0, self.Ny)) 

393 # plt.grid() 

394 # plt.gca().set_aspect("auto") 

395 # plt.show() 

396 

397 # Matrix filling 

398 psf_cube = self.spectrum.chromatic_psf.build_psf_cube(self.pixels, profile_params, 

399 fwhmx_clip=3 * parameters.PSF_FWHM_CLIP, 

400 fwhmy_clip=parameters.PSF_FWHM_CLIP, dtype="float32") 

401 if A2 > 0: 

402 # for x in range(self.Nx): 

403 # M[:, x] += A2 * self.spectrum.chromatic_psf.psf.evaluate(self.pixels, 

404 # p=profile_params_order2[x, :]).flatten() 

405 # if profile_params_order2[x, 1] > 1.2 * self.Nx: 

406 # break 

407 psf_cube2 = A2 * self.spectrum.chromatic_psf.build_psf_cube(self.pixels, profile_params_order2, 

408 fwhmx_clip=3 * parameters.PSF_FWHM_CLIP, 

409 fwhmy_clip=parameters.PSF_FWHM_CLIP, 

410 dtype="float32") 

411 psf_cube += psf_cube2 

412 M = psf_cube.reshape(len(profile_params), self.pixels[0].size).T # flattening 

413 if self.sparse_indices is None: 

414 self.sparse_indices = np.where(M > 0) 

415 M = sparse.csr_matrix((M[self.sparse_indices].ravel(), self.sparse_indices), shape=M.shape, dtype="float32") 

416 # Algebra to compute amplitude parameters 

417 if self.amplitude_priors_method != "fixed": 

418 M_dot_W = M.T * self.sqrtW 

419 M_dot_W_dot_M = M_dot_W @ M_dot_W.T 

420 if self.amplitude_priors_method != "spectrum": 

421 # try: # slower 

422 # L = np.linalg.inv(np.linalg.cholesky(M_dot_W_dot_M)) 

423 # cov_matrix = L.T @ L 

424 # except np.linalg.LinAlgError: 

425 cov_matrix = np.linalg.inv(M_dot_W_dot_M) 

426 amplitude_params = cov_matrix @ (M.T @ W_dot_data) 

427 if self.amplitude_priors_method == "positive": 

428 amplitude_params[amplitude_params < 0] = 0 

429 elif self.amplitude_priors_method == "smooth": 

430 null_indices = np.where(amplitude_params < 0)[0] 

431 for index in null_indices: 

432 right = amplitude_params[index] 

433 for i in range(index, min(index + 10, self.Nx)): 

434 right = amplitude_params[i] 

435 if i not in null_indices: 

436 break 

437 left = amplitude_params[index] 

438 for i in range(index, max(0, index - 10), -1): 

439 left = amplitude_params[i] 

440 if i not in null_indices: 

441 break 

442 amplitude_params[index] = 0.5 * (right + left) 

443 elif self.amplitude_priors_method == "noprior": 

444 pass 

445 else: 

446 M_dot_W_dot_M_plus_Q = M_dot_W_dot_M + self.reg * self.Q 

447 # try: # slower 

448 # L = np.linalg.inv(np.linalg.cholesky(M_dot_W_dot_M_plus_Q)) 

449 # cov_matrix = L.T @ L 

450 # except np.linalg.LinAlgError: 

451 cov_matrix = np.linalg.inv(M_dot_W_dot_M_plus_Q) 

452 amplitude_params = cov_matrix @ (M.T @ W_dot_data + self.reg * self.Q_dot_A0) 

453 self.M_dot_W_dot_M = M_dot_W_dot_M 

454 amplitude_params = np.asarray(amplitude_params).reshape(-1) 

455 else: 

456 amplitude_params = np.copy(self.amplitude_priors) 

457 err2 = np.copy(amplitude_params) 

458 err2[err2 <= 0] = np.min(np.abs(err2[err2 > 0])) 

459 cov_matrix = np.diag(err2) 

460 

461 # Save results 

462 self.M = M 

463 self.psf_profile_params = np.copy(profile_params) 

464 self.psf_poly_params = np.copy(poly_params) 

465 self.amplitude_params = np.copy(amplitude_params) 

466 self.amplitude_params_err = np.array([np.sqrt(cov_matrix[x, x]) for x in range(self.Nx)]) 

467 self.amplitude_cov_matrix = np.copy(cov_matrix) 

468 

469 # Compute the model 

470 self.model = M @ amplitude_params 

471 self.model_err = np.zeros_like(self.model) 

472 

473 return self.pixels, self.model, self.model_err 

474 

475 def plot_spectrogram_comparison_simple(self, ax, title='', extent=None, dispersion=False): 

476 """Method to plot a spectrogram issued from data and compare it with simulations. 

477 

478 Parameters 

479 ---------- 

480 ax: Axes 

481 Axes instance of shape (4, 2). 

482 title: str, optional 

483 Title for the simulation plot (default: ''). 

484 extent: array_like, optional 

485 Extent argument for imshow to crop plots (default: None). 

486 dispersion: bool, optional 

487 If True, plot a colored bar to see the associated wavelength color along the x axis (default: False). 

488 """ 

489 cmap_bwr = copy.copy(cm.get_cmap('bwr')) 

490 cmap_bwr.set_bad(color='lightgrey') 

491 cmap_viridis = copy.copy(cm.get_cmap('viridis')) 

492 cmap_viridis.set_bad(color='lightgrey') 

493 

494 data = np.copy(self.data_before_mask) 

495 if len(self.outliers) > 0 or len(self.mask) > 0: 

496 bad_indices = np.array(list(self.get_bad_indices()) + list(self.mask)).astype(int) 

497 data[bad_indices] = np.nan 

498 

499 lambdas = self.spectrum.lambdas 

500 sub = np.where((lambdas > parameters.LAMBDA_MIN) & (lambdas < parameters.LAMBDA_MAX))[0] 

501 sub = np.where(sub < self.spectrum.spectrogram.shape[1])[0] 

502 data = (data + self.bgd_flat).reshape((self.Ny, self.Nx)) 

503 err = self.err.reshape((self.Ny, self.Nx)) 

504 model = (self.model + self.p[5] * self.bgd_flat).reshape((self.Ny, self.Nx)) 

505 if extent is not None: 

506 sub = np.where((lambdas > extent[0]) & (lambdas < extent[1]))[0] 

507 if len(sub) > 0: 

508 norm = np.nanmax(data[:, sub]) 

509 plot_image_simple(ax[0, 0], data=data[:, sub] / norm, title='Data', aspect='auto', 

510 cax=ax[0, 1], vmin=0, vmax=1, units='1/max(data)', cmap=cmap_viridis) 

511 ax[0, 0].set_title('Data', fontsize=10, loc='center', color='white', y=0.8) 

512 plot_image_simple(ax[1, 0], data=model[:, sub] / norm, aspect='auto', cax=ax[1, 1], vmin=0, vmax=1, 

513 units='1/max(data)', cmap=cmap_viridis) 

514 if dispersion: 

515 x = self.spectrum.chromatic_psf.table['Dx'][sub[5:-5]] + self.spectrum.spectrogram_x0 - sub[0] 

516 y = np.ones_like(x) 

517 ax[1, 0].scatter(x, y, cmap=from_lambda_to_colormap(self.lambdas[sub[5:-5]]), edgecolors='None', 

518 c=self.lambdas[sub[5:-5]], 

519 label='', marker='o', s=10) 

520 ax[1, 0].set_xlim(0, model[:, sub].shape[1]) 

521 ax[1, 0].set_ylim(0, model[:, sub].shape[0]) 

522 # p0 = ax.plot(lambdas, self.model(lambdas), label='model') 

523 # # ax.plot(self.lambdas, self.model_noconv, label='before conv') 

524 if title != '': 

525 ax[1, 0].set_title(title, fontsize=10, loc='center', color='white', y=0.8) 

526 residuals = (data - model) 

527 # residuals_err = self.spectrum.spectrogram_err / self.model 

528 norm = err 

529 residuals /= norm 

530 std = float(np.nanstd(residuals[:, sub])) 

531 plot_image_simple(ax[2, 0], data=residuals[:, sub], vmin=-5 * std, vmax=5 * std, title='(Data-Model)/Err', 

532 aspect='auto', cax=ax[2, 1], units='', cmap=cmap_bwr) 

533 ax[2, 0].set_title('(Data-Model)/Err', fontsize=10, loc='center', color='black', y=0.8) 

534 ax[2, 0].text(0.05, 0.05, 

535 f'mean={np.nanmean(residuals[:, sub]):.3f}\nstd={np.nanstd(residuals[:, sub]):.3f}', 

536 horizontalalignment='left', verticalalignment='bottom', 

537 color='black', transform=ax[2, 0].transAxes) 

538 ax[0, 0].set_xticks(ax[2, 0].get_xticks()[1:-1]) 

539 ax[0, 1].get_yaxis().set_label_coords(3.5, 0.5) 

540 ax[1, 1].get_yaxis().set_label_coords(3.5, 0.5) 

541 ax[2, 1].get_yaxis().set_label_coords(3.5, 0.5) 

542 ax[3, 1].remove() 

543 ax[3, 0].plot(self.lambdas[sub], np.nansum(data, axis=0)[sub], label='Data') 

544 model[np.isnan(data)] = np.nan # mask background values outside fitted region 

545 ax[3, 0].plot(self.lambdas[sub], np.nansum(model, axis=0)[sub], label='Model') 

546 ax[3, 0].set_ylabel('Cross spectrum') 

547 ax[3, 0].set_xlabel(r'$\lambda$ [nm]') 

548 ax[3, 0].legend(fontsize=7) 

549 ax[3, 0].grid(True) 

550 

551 def plot_fit(self): 

552 """Plot the fit result. 

553 

554 Examples 

555 -------- 

556 

557 >>> spec = Spectrum('tests/data/sim_20170530_134_spectrum.fits', config="config/ctio.ini") 

558 >>> w = FullForwardModelFitWorkspace(spec, verbose=1, plot=True, live_fit=False) 

559 >>> lambdas, model, model_err = w.simulate(*w.p) 

560 >>> w.plot_fit() 

561 

562 .. plot:: 

563 :include-source: 

564 

565 from spectractor.fit.fit_spectrogram import SpectrogramFitWorkspace 

566 file_name = 'tests/data/reduc_20170530_134_spectrum.fits' 

567 atmgrid_file_name = file_name.replace('spectrum', 'atmsim') 

568 fit_workspace = SpectrogramFitWorkspace(file_name, atmgrid_file_name=atmgrid_file_name, verbose=True) 

569 A1, A2, ozone, pwv, aerosols, D, shift_x, shift_y, angle, *psf = fit_workspace.p 

570 lambdas, model, model_err = fit_workspace.simulation.simulate(A1, A2, ozone, pwv, aerosols, D, shift_x, 

571 shift_y, angle, psf) 

572 fit_workspace.lambdas = lambdas 

573 fit_workspace.model = model 

574 fit_workspace.model_err = model_err 

575 fit_workspace.plot_fit() 

576 

577 """ 

578 gs_kw = dict(width_ratios=[3, 0.01, 1, 0.01, 1, 0.15], height_ratios=[1, 1, 1, 1]) 

579 fig, ax = plt.subplots(nrows=4, ncols=6, figsize=(10, 8), gridspec_kw=gs_kw) 

580 

581 A2, D2CCD, dx0, dy0, angle, B, rot, *poly_params = self.p 

582 plt.suptitle(f'A2={A2:.3f}, D={D2CCD:.2f}mm, shift_x={dx0:.3f}pix, shift_y={dy0:.3f}pix, ' 

583 f'angle={angle:.2f}pix, B={B:.3f}', y=1) 

584 # main plot 

585 self.plot_spectrogram_comparison_simple(ax[:, 0:2], title='Spectrogram model', dispersion=True) 

586 # zoom O2 

587 self.plot_spectrogram_comparison_simple(ax[:, 2:4], extent=[730, 800], title='Zoom $O_2$', dispersion=True) 

588 # zoom H2O 

589 self.plot_spectrogram_comparison_simple(ax[:, 4:6], extent=[870, 1000], title='Zoom $H_2 O$', dispersion=True) 

590 for i in range(3): # clear middle colorbars 

591 for j in range(2): 

592 plt.delaxes(ax[i, 2 * j + 1]) 

593 for i in range(4): # clear middle y axis labels 

594 for j in range(1, 3): 

595 ax[i, 2 * j].set_ylabel("") 

596 fig.tight_layout() 

597 if self.live_fit: # pragma: no cover 

598 plt.draw() 

599 plt.pause(1e-8) 

600 plt.close() 

601 else: 

602 if parameters.DISPLAY and self.verbose: 

603 plt.show() 

604 if parameters.SAVE: # pragma: no cover 

605 figname = os.path.splitext(self.filename)[0] + "_bestfit.pdf" 

606 self.my_logger.info(f"\n\tSave figure {figname}.") 

607 fig.savefig(figname, dpi=100, bbox_inches='tight') 

608 

609 def adjust_spectrogram_position_parameters(self): 

610 # fit the spectrogram trace 

611 epsilon = 1e-4 * self.p 

612 epsilon[epsilon == 0] = 1e-4 

613 fixed = [True] * len(self.p) 

614 fixed[3:5] = [False, False] # shift_y and angle 

615 self.sparse_indices = None 

616 run_minimisation(self, "newton", epsilon, fixed, xtol=1e-4, ftol=100 / self.data.size) 

617 self.sparse_indices = None 

618 

619 

620def run_ffm_minimisation(w, method="newton", niter=2): 

621 """Interface function to fit spectrogram simulation parameters to data. 

622 

623 Parameters 

624 ---------- 

625 w: FullForwardModelFitWorkspace 

626 An instance of the SpectrogramFitWorkspace class. 

627 method: str, optional 

628 Fitting method (default: 'newton'). 

629 niter: int, optional 

630 Number of FFM iterations to final result (default: 2). 

631 

632 Returns 

633 ------- 

634 spectrum: Spectrum 

635 The extracted spectrum. 

636 

637 Examples 

638 -------- 

639 

640 >>> spec = Spectrum("./tests/data/reduc_20170530_134_spectrum.fits", config="./config/ctio.ini") 

641 >>> parameters.VERBOSE = True 

642 >>> w = FullForwardModelFitWorkspace(spec, verbose=1, plot=True, live_fit=True, amplitude_priors_method="spectrum") 

643 >>> spec = run_ffm_minimisation(w, method="newton") # doctest: +ELLIPSIS 

644 >>> if 'LBDAS_T' in spec.header: plot_comparison_truth(spec, w) 

645 Line Tabulated Detected ... 

646 

647 .. doctest: 

648 :hide: 

649 

650 >>> assert w.costs[-1] / w.data.size < 1.22 # reduced chisq 

651 >>> assert np.isclose(w.p[4], -1.56, rtol=0.05) # angle 

652 >>> assert np.isclose(w.p[5], 1, rtol=0.05) # B 

653 

654 """ 

655 my_logger = set_logger(__name__) 

656 w.adjust_spectrogram_position_parameters() 

657 

658 if method != "newton": 

659 run_minimisation(w, method=method) 

660 else: 

661 costs = np.array([w.chisq(w.p)]) 

662 if parameters.DISPLAY and (parameters.DEBUG or w.live_fit): 

663 w.plot_fit() 

664 start = time.time() 

665 my_logger.info(f"\n\tStart guess: {w.p}\n\twith {w.input_labels}") 

666 epsilon = 1e-4 * w.p 

667 epsilon[epsilon == 0] = 1e-4 

668 

669 run_minimisation(w, method=method, fix=w.fixed, xtol=1e-4, ftol=10 / w.data.size) 

670 # Optimize the regularisation parameter only if it was not done before 

671 if w.amplitude_priors_method == "spectrum" and w.reg == parameters.PSF_FIT_REG_PARAM: # pragma: no cover 

672 w_reg = RegFitWorkspace(w, opt_reg=parameters.PSF_FIT_REG_PARAM, verbose=True) 

673 w_reg.run_regularisation() 

674 w.opt_reg = w_reg.opt_reg 

675 w.reg = np.copy(w_reg.opt_reg) 

676 w.simulate(*w.p) 

677 if np.trace(w.amplitude_cov_matrix) < np.trace(w.amplitude_priors_cov_matrix): 

678 w.my_logger.warning( 

679 f"\n\tTrace of final covariance matrix ({np.trace(w.amplitude_cov_matrix)}) is " 

680 f"below the trace of the prior covariance matrix " 

681 f"({np.trace(w.amplitude_priors_cov_matrix)}). This is probably due to a very " 

682 f"high regularisation parameter in case of a bad fit. Therefore the final " 

683 f"covariance matrix is mulitiplied by the ratio of the traces and " 

684 f"the amplitude parameters are very close the amplitude priors.") 

685 r = np.trace(w.amplitude_priors_cov_matrix) / np.trace(w.amplitude_cov_matrix) 

686 w.amplitude_cov_matrix *= r 

687 w.amplitude_params_err = np.array( 

688 [np.sqrt(w.amplitude_cov_matrix[x, x]) for x in range(w.Nx)]) 

689 

690 for i in range(niter): 

691 w.set_mask(psf_poly_params=w.p[w.psf_params_start_index:]) 

692 run_minimisation_sigma_clipping(w, "newton", epsilon, w.fixed, xtol=1e-5, 

693 ftol=1 / w.data.size, sigma_clip=20, niter_clip=3) 

694 my_logger.info(f"\n\tNewton: total computation time: {time.time() - start}s") 

695 

696 if parameters.DEBUG: 

697 w.plot_fit() 

698 w.spectrum.lambdas = np.copy(w.lambdas) 

699 w.spectrum.data = np.copy(w.amplitude_params) 

700 w.spectrum.err = np.copy(w.amplitude_params_err) 

701 w.spectrum.cov_matrix = np.copy(w.amplitude_cov_matrix) 

702 w.spectrum.chromatic_psf.fill_table_with_profile_params(w.psf_profile_params) 

703 w.spectrum.chromatic_psf.table["amplitude"] = np.copy(w.amplitude_params) 

704 w.spectrum.chromatic_psf.from_profile_params_to_shape_params(w.psf_profile_params) 

705 w.spectrum.chromatic_psf.poly_params = w.spectrum.chromatic_psf.from_table_to_poly_params() 

706 w.spectrum.spectrogram_fit = w.model 

707 w.spectrum.spectrogram_residuals = (w.data - w.spectrum.spectrogram_fit) / w.err 

708 w.spectrum.header['CHI2_FIT'] = w.costs[-1] / (w.data.size - len(w.mask)) 

709 w.spectrum.header['PIXSHIFT'] = w.p[2] 

710 w.spectrum.header['D2CCD'] = w.p[1] 

711 w.spectrum.header['A2_FIT'] = w.p[0] 

712 w.spectrum.header["ROTANGLE"] = w.p[4] 

713 

714 # Calibrate the spectrum 

715 calibrate_spectrum(w.spectrum, with_adr=False) 

716 w.p[1] = w.spectrum.disperser.D 

717 w.p[2] = w.spectrum.header['PIXSHIFT'] 

718 w.spectrum.convert_from_flam_to_ADUrate() 

719 

720 if w.filename != "": 

721 parameters.SAVE = True 

722 ipar = np.array(np.where(np.array(w.fixed).astype(int) == 0)[0]) 

723 w.plot_correlation_matrix(ipar) 

724 w.save_parameters_summary(ipar, header=f"{w.spectrum.date_obs}\n" 

725 f"chi2: {costs[-1] / w.data.size}") 

726 w.plot_fit() 

727 parameters.SAVE = False 

728 

729 # Save results 

730 w.spectrum.convert_from_ADUrate_to_flam() 

731 x, model, model_err = w.simulate(*w.p) 

732 

733 # Propagate uncertainties 

734 # from spectractor.tools import plot_correlation_matrix_simple, compute_correlation_matrix 

735 # M = np.copy(w.M) 

736 # amplitude_params = np.copy(w.amplitude_params) 

737 # ipar = np.array(np.where(np.array(w.fixed).astype(int) == 0)[0]) 

738 # w.amplitude_priors_method = "fixed" 

739 # jac = w.jacobian(w.p, epsilon=epsilon, fixed_params=w.fixed, model_input=[x, model, model_err]) 

740 # jac = jac[ipar] 

741 # start = jac.shape[0] 

742 # J = np.hstack([jac.T, M]) 

743 # H = (J.T * w.W) @ J 

744 # H[start:, start:] += w.reg*w.Q 

745 # full_cov_matrix = np.linalg.inv(H) 

746 # amplitude_params_err = np.array([np.sqrt(full_cov_matrix[start+x, start+x]) for x in range(w.Nx)]) 

747 # plt.errorbar(w.lambdas, amplitude_params, yerr=amplitude_params_err) 

748 # plt.grid() 

749 # plt.show() 

750 # plt.figure() 

751 # plot_correlation_matrix_simple(ax=plt.gca(), rho=compute_correlation_matrix(full_cov_matrix)) 

752 # plt.show() 

753 # w.amplitude_params = amplitude_params 

754 # w.amplitude_params_err = amplitude_params_err 

755 # w.amplitude_cov_matrix = full_cov_matrix[start:, start:] 

756 

757 # Propagate parameters 

758 A2, D2CCD, dx0, dy0, angle, B, *poly_params = w.p 

759 w.spectrum.rotation_angle = angle 

760 w.spectrum.spectrogram_bgd *= B 

761 w.spectrum.spectrogram_bgd_rms *= B 

762 w.spectrum.spectrogram_x0 += dx0 

763 w.spectrum.spectrogram_y0 += dy0 

764 w.spectrum.x0[0] += dx0 

765 w.spectrum.x0[1] += dy0 

766 w.spectrum.header["TARGETX"] = w.spectrum.x0[0] 

767 w.spectrum.header["TARGETY"] = w.spectrum.x0[1] 

768 

769 # Compute order 2 contamination 

770 w.spectrum.lambdas_order2 = w.lambdas 

771 w.spectrum.data_order2 = A2 * w.amplitude_params * w.spectrum.disperser.ratio_order_2over1(w.lambdas) 

772 w.spectrum.err_order2 = A2 * w.amplitude_params_err * w.spectrum.disperser.ratio_order_2over1(w.lambdas) 

773 

774 # Convert to flam 

775 w.spectrum.convert_from_ADUrate_to_flam() 

776 

777 # Compare with truth if available 

778 if 'LBDAS_T' in w.spectrum.header and parameters.DEBUG: 

779 plot_comparison_truth(w.spectrum, w) 

780 

781 return w.spectrum 

782 

783def Spectractor(file_name, output_directory, target_label, guess=None, disperser_label="", config='./config/ctio.ini', 

784 atmospheric_lines=True, line_detection=True): 

785 """ Spectractor 

786 Main function to extract a spectrum from an image 

787 

788 Parameters 

789 ---------- 

790 file_name: str 

791 Input file nam of the image to analyse. 

792 output_directory: str 

793 Output directory. 

794 target_label: str 

795 The name of the targeted object. 

796 guess: [int,int], optional 

797 [x0,y0] list of the guessed pixel positions of the target in the image (must be integers). Mandatory if 

798 WCS solution is absent (default: None). 

799 disperser_label: str, optional 

800 The name of the disperser (default: ""). 

801 config: str 

802 The config file name (default: "./config/ctio.ini"). 

803 atmospheric_lines: bool, optional 

804 If True atmospheric lines are used in the calibration fit. 

805 

806 Returns 

807 ------- 

808 spectrum: Spectrum 

809 The extracted spectrum object. 

810 

811 Examples 

812 -------- 

813 

814 Extract the spectrogram and its characteristics from the image: 

815 

816 .. doctest:: 

817 

818 >>> import os 

819 >>> from spectractor.logbook import LogBook 

820 >>> logbook = LogBook(logbook='./ctiofulllogbook_jun2017_v5.csv') 

821 >>> file_names = ['./tests/data/reduc_20170530_134.fits'] 

822 >>> for file_name in file_names: 

823 ... tag = file_name.split('/')[-1] 

824 ... disperser_label, target_label, xpos, ypos = logbook.search_for_image(tag) 

825 ... if target_label is None or xpos is None or ypos is None: 

826 ... continue 

827 ... spectrum = Spectractor(file_name, './tests/data/', guess=[xpos, ypos], target_label=target_label, 

828 ... disperser_label=disperser_label, config='./config/ctio.ini') 

829 

830 .. doctest:: 

831 :hide: 

832 

833 >>> assert spectrum is not None 

834 >>> assert os.path.isfile('tests/data/reduc_20170530_134_spectrum.fits') 

835 

836 """ 

837 

838 my_logger = set_logger(__name__) 

839 my_logger.info('\n\tStart SPECTRACTOR') 

840 # Load config file 

841 if config != "": 

842 load_config(config) 

843 if parameters.LSST_SAVEFIGPATH: # pragma: no cover 

844 ensure_dir(parameters.LSST_SAVEFIGPATH) 

845 

846 # Load reduced image 

847 image = Image(file_name, target_label=target_label, disperser_label=disperser_label) 

848 if guess is not None and image.target_guess is None: 

849 image.target_guess = np.asarray(guess) 

850 if image.target_guess is None: 

851 from scipy.signal import medfilt2d 

852 data = medfilt2d(image.data.T, kernel_size=9) 

853 image.target_guess = np.unravel_index(np.argmax(data), data.shape) 

854 my_logger.info(f"\n\tNo guess position of order 0 has been given. Assuming the spectrum to extract comes " 

855 f"from the brightest object, guess position is set as {image.target_guess}.") 

856 if parameters.DEBUG: 

857 image.plot_image(scale='symlog', target_pixcoords=image.target_guess) 

858 

859 # Use fast mode 

860 if parameters.CCD_REBIN > 1: 

861 image.rebin() 

862 if parameters.DEBUG: 

863 image.plot_image(scale='symlog', target_pixcoords=image.target_guess) 

864 

865 # Set output path 

866 ensure_dir(output_directory) 

867 output_filename = file_name.split('/')[-1] 

868 output_filename = output_filename.replace('.fits', '_spectrum.fits') 

869 output_filename = output_filename.replace('.fz', '_spectrum.fits') 

870 output_filename = os.path.join(output_directory, output_filename) 

871 output_filename_spectrogram = output_filename.replace('spectrum', 'spectrogram') 

872 output_filename_psf = output_filename.replace('spectrum.fits', 'table.csv') 

873 # Find the exact target position in the raw cut image: several methods 

874 my_logger.info(f'\n\tSearch for the target in the image with guess={image.target_guess}...') 

875 find_target(image, image.target_guess, widths=(parameters.XWINDOW, parameters.YWINDOW)) 

876 # Rotate the image 

877 turn_image(image) 

878 # Find the exact target position in the rotated image: several methods 

879 my_logger.info('\n\tSearch for the target in the rotated image...') 

880 find_target(image, image.target_guess, rotated=True, widths=(parameters.XWINDOW_ROT, parameters.YWINDOW_ROT)) 

881 # Create Spectrum object 

882 spectrum = Spectrum(image=image, order=parameters.SPEC_ORDER) 

883 # First 1D spectrum extraction and background extraction 

884 w_psf1d, bgd_model_func = extract_spectrum_from_image(image, spectrum, signal_width=parameters.PIXWIDTH_SIGNAL, 

885 ws=(parameters.PIXDIST_BACKGROUND, 

886 parameters.PIXDIST_BACKGROUND 

887 + parameters.PIXWIDTH_BACKGROUND), 

888 right_edge=parameters.CCD_IMSIZE) 

889 spectrum.atmospheric_lines = atmospheric_lines 

890 

891 # PSF2D deconvolution 

892 if parameters.SPECTRACTOR_DECONVOLUTION_PSF2D: 

893 run_spectrogram_deconvolution_psf2d(spectrum, bgd_model_func=bgd_model_func) 

894 

895 # Calibrate the spectrum 

896 my_logger.info(f'\n\tCalibrating order {spectrum.order:d} spectrum...') 

897 with_adr = True 

898 if parameters.OBS_OBJECT_TYPE != "STAR": 

899 with_adr = False 

900 calibrate_spectrum(spectrum, with_adr=with_adr) 

901 spectrum.data_order2 = np.zeros_like(spectrum.lambdas_order2) 

902 spectrum.err_order2 = np.zeros_like(spectrum.lambdas_order2) 

903 

904 # Full forward model extraction: add transverse ADR and order 2 subtraction 

905 if parameters.SPECTRACTOR_DECONVOLUTION_FFM: 

906 w = FullForwardModelFitWorkspace(spectrum, verbose=parameters.VERBOSE, plot=True, live_fit=False, 

907 amplitude_priors_method="spectrum") 

908 spectrum = run_ffm_minimisation(w, method="newton", niter=2) 

909 

910 # Save the spectrum 

911 spectrum.save_spectrum(output_filename, overwrite=True) 

912 spectrum.save_spectrogram(output_filename_spectrogram, overwrite=True) 

913 spectrum.lines.print_detected_lines(output_file_name=output_filename.replace('_spectrum.fits', '_lines.csv'), 

914 overwrite=True, amplitude_units=spectrum.units) 

915 

916 # Plot the spectrum 

917 if parameters.VERBOSE and parameters.DISPLAY: 

918 spectrum.plot_spectrum(xlim=None) 

919 spectrum.chromatic_psf.table['lambdas'] = spectrum.lambdas 

920 spectrum.chromatic_psf.table.write(output_filename_psf, overwrite=True) 

921 

922 return spectrum 

923 

924 

925def extract_spectrum_from_image(image, spectrum, signal_width=10, ws=(20, 30), right_edge=parameters.CCD_IMSIZE): 

926 """Extract the 1D spectrum from the image. 

927 

928 Method : remove a uniform background estimated from the rectangular lateral bands 

929 

930 The spectrum amplitude is the sum of the pixels in the 2*w rectangular window 

931 centered on the order 0 y position. 

932 The up and down backgrounds are estimated as the median in rectangular regions 

933 above and below the spectrum, in the ws-defined rectangular regions; stars are filtered 

934 as nan values using an hessian analysis of the image to remove structures. 

935 The subtracted background is the mean of the two up and down backgrounds. 

936 Stars are filtered. 

937 

938 Prerequisites: the target position must have been found before, and the 

939 image turned to have an horizontal dispersion line 

940 

941 Parameters 

942 ---------- 

943 image: Image 

944 Image object from which to extract the spectrum 

945 spectrum: Spectrum 

946 Spectrum object to store new wavelengths, data and error arrays 

947 signal_width: int 

948 Half width of central region where the spectrum is extracted and summed (default: 10) 

949 ws: list 

950 up/down region extension where the sky background is estimated with format [int, int] (default: [20,30]) 

951 right_edge: int 

952 Right-hand pixel position above which no pixel should be used (default: parameters.CCD_IMSIZE) 

953 """ 

954 

955 my_logger = set_logger(__name__) 

956 if ws is None: 

957 ws = [signal_width + 20, signal_width + 30] 

958 my_logger.info( 

959 f'\n\tExtracting spectrum from image: spectrum with width 2*{signal_width:d} pixels ' 

960 f'and background from {ws[0]:d} to {ws[1]:d} pixels') 

961 

962 # Make a data copy 

963 data = np.copy(image.data_rotated)[:, 0:right_edge] 

964 err = np.copy(image.stat_errors_rotated)[:, 0:right_edge] 

965 

966 # Lateral bands to remove sky background 

967 Ny, Nx = data.shape 

968 y0 = int(image.target_pixcoords_rotated[1]) 

969 ymax = min(Ny, y0 + ws[1]) 

970 ymin = max(0, y0 - ws[1]) 

971 

972 # Roughly estimates the wavelengths and set start 0 nm before parameters.LAMBDA_MIN 

973 # and end 0 nm after parameters.LAMBDA_MAX 

974 if spectrum.order < 0: 

975 distance = np.sign(spectrum.order) * (np.arange(Nx) - image.target_pixcoords_rotated[0]) 

976 lambdas = image.disperser.grating_pixel_to_lambda(distance, x0=image.target_pixcoords, order=spectrum.order) 

977 lambda_min_index = int(np.argmin(np.abs(lambdas[::np.sign(spectrum.order)] - parameters.LAMBDA_MIN))) 

978 lambda_max_index = int(np.argmin(np.abs(lambdas[::np.sign(spectrum.order)] - parameters.LAMBDA_MAX))) 

979 xmin = max(0, int(distance[lambda_min_index])) 

980 xmax = min(right_edge, int(distance[lambda_max_index]) + 1) # +1 to include edges 

981 else: 

982 lambdas = image.disperser.grating_pixel_to_lambda(np.arange(Nx) - image.target_pixcoords_rotated[0], 

983 x0=image.target_pixcoords, 

984 order=spectrum.order) 

985 xmin = int(np.argmin(np.abs(lambdas - parameters.LAMBDA_MIN))) 

986 xmax = int(np.argmin(np.abs(lambdas - parameters.LAMBDA_MAX))) 

987 

988 # Create spectrogram 

989 data = data[ymin:ymax, xmin:xmax] 

990 err = err[ymin:ymax, xmin:xmax] 

991 Ny, Nx = data.shape 

992 my_logger.info(f'\n\tExtract spectrogram: crop rotated image [{xmin}:{xmax},{ymin}:{ymax}] (size ({Nx}, {Ny}))') 

993 

994 # Position of the order 0 in the spectrogram coordinates 

995 target_pixcoords_spectrogram = [image.target_pixcoords_rotated[0] - xmin, image.target_pixcoords_rotated[1] - ymin] 

996 

997 # Extract the background on the rotated image 

998 bgd_model_func, bgd_res, bgd_rms = extract_spectrogram_background_sextractor(data, err, ws=ws) 

999 # while np.nanmean(bgd_res)/np.nanstd(bgd_res) < -0.2 and parameters.PIXWIDTH_BOXSIZE >= 5: 

1000 while (np.abs(np.nanmean(bgd_res)) > 0.5 or np.nanstd(bgd_res) > 1.3) and parameters.PIXWIDTH_BOXSIZE > 5: 

1001 parameters.PIXWIDTH_BOXSIZE = max(5, parameters.PIXWIDTH_BOXSIZE // 2) 

1002 my_logger.debug(f"\n\tPull distribution of background residuals differs too much from mean=0 and std=1. " 

1003 f"\n\t\tmean={np.nanmean(bgd_res):.3g}; std={np.nanstd(bgd_res):.3g}" 

1004 f"\n\tThese value should be smaller in absolute value than 0.5 and 1.3. " 

1005 f"\n\tTo do so, parameters.PIXWIDTH_BOXSIZE is divided " 

1006 f"by 2 from {parameters.PIXWIDTH_BOXSIZE * 2} -> {parameters.PIXWIDTH_BOXSIZE}.") 

1007 bgd_model_func, bgd_res, bgd_rms = extract_spectrogram_background_sextractor(data, err, ws=ws) 

1008 

1009 # Propagate background uncertainties 

1010 err = np.sqrt(err * err + bgd_rms * bgd_rms) 

1011 

1012 # Fit the transverse profile 

1013 my_logger.info(f'\n\tStart PSF1D transverse fit...') 

1014 psf = load_PSF(psf_type=parameters.PSF_TYPE, target=image.target, clip=False) 

1015 s = ChromaticPSF(psf, Nx=Nx, Ny=Ny, x0=target_pixcoords_spectrogram[0], y0=target_pixcoords_spectrogram[1], 

1016 deg=parameters.PSF_POLY_ORDER, saturation=image.saturation) 

1017 verbose = copy.copy(parameters.VERBOSE) 

1018 debug = copy.copy(parameters.DEBUG) 

1019 parameters.VERBOSE = False 

1020 parameters.DEBUG = False 

1021 s.fit_transverse_PSF1D_profile(data, err, signal_width, ws, pixel_step=parameters.PSF_PIXEL_STEP_TRANSVERSE_FIT, 

1022 sigma_clip=5, bgd_model_func=bgd_model_func, saturation=image.saturation, 

1023 live_fit=False) 

1024 parameters.VERBOSE = verbose 

1025 parameters.DEBUG = debug 

1026 

1027 # Fill spectrum object 

1028 spectrum.pixels = np.arange(xmin, xmax, 1).astype(int) 

1029 spectrum.data = np.copy(s.table['amplitude']) 

1030 spectrum.err = np.copy(s.table['flux_err']) 

1031 my_logger.debug(f'\n\tTransverse fit table:\n{s.table}') 

1032 if parameters.DEBUG: 

1033 s.plot_summary() 

1034 

1035 # Fit the data: 

1036 method = "noprior" 

1037 mode = "1D" 

1038 my_logger.info(f'\n\tStart ChromaticPSF polynomial fit with ' 

1039 f'mode={mode} and amplitude_priors_method={method}...') 

1040 w = s.fit_chromatic_psf(data, bgd_model_func=bgd_model_func, data_errors=err, 

1041 amplitude_priors_method=method, mode=mode, verbose=parameters.VERBOSE) 

1042 spectrum.data = np.copy(w.amplitude_params) 

1043 spectrum.err = np.copy(w.amplitude_params_err) 

1044 spectrum.cov_matrix = np.copy(w.amplitude_cov_matrix) 

1045 spectrum.chromatic_psf = s 

1046 

1047 Dx_rot = spectrum.pixels.astype(float) - image.target_pixcoords_rotated[0] 

1048 s.table['Dx'] = np.copy(Dx_rot) 

1049 s.table['Dy'] = s.table['y_c'] - (image.target_pixcoords_rotated[1] - ymin) 

1050 s.table['Dy_disp_axis'] = 0 

1051 s.table['Dy_fwhm_inf'] = s.table['Dy'] - 0.5 * s.table['fwhm'] 

1052 s.table['Dy_fwhm_sup'] = s.table['Dy'] + 0.5 * s.table['fwhm'] 

1053 my_logger.debug(f"\n\tTransverse fit table before derotation:" 

1054 f"\n{s.table[['amplitude', 'x_c', 'y_c', 'Dx', 'Dy', 'Dy_disp_axis']]}") 

1055 

1056 # Rotate and save the table 

1057 s.rotate_table(-image.rotation_angle) 

1058 

1059 # Extract the spectrogram edges 

1060 data = np.copy(image.data)[:, 0:right_edge] 

1061 err = np.copy(image.stat_errors)[:, 0:right_edge] 

1062 Ny, Nx = data.shape 

1063 x0 = int(image.target_pixcoords[0]) 

1064 y0 = int(image.target_pixcoords[1]) 

1065 ymax = min(Ny, y0 + int(s.table['Dy_disp_axis'].max()) + ws[1] + 1) # +1 to include edges 

1066 ymin = max(0, y0 + int(s.table['Dy_disp_axis'].min()) - ws[1]) 

1067 distance = s.get_algebraic_distance_along_dispersion_axis() 

1068 lambdas = image.disperser.grating_pixel_to_lambda(distance, x0=image.target_pixcoords, order=spectrum.order) 

1069 lambda_min_index = int(np.argmin(np.abs(lambdas[::np.sign(spectrum.order)] - parameters.LAMBDA_MIN))) 

1070 lambda_max_index = int(np.argmin(np.abs(lambdas[::np.sign(spectrum.order)] - parameters.LAMBDA_MAX))) 

1071 xmin = max(0, int(s.table['Dx'][lambda_min_index] + x0)) 

1072 xmax = min(right_edge, int(s.table['Dx'][lambda_max_index] + x0) + 1) # +1 to include edges 

1073 

1074 # Position of the order 0 in the spectrogram coordinates 

1075 target_pixcoords_spectrogram = [image.target_pixcoords[0] - xmin, image.target_pixcoords[1] - ymin] 

1076 s.y0 = target_pixcoords_spectrogram[1] 

1077 s.x0 = target_pixcoords_spectrogram[0] 

1078 

1079 # Update y_c and x_c after rotation 

1080 s.table['y_c'] = s.table['Dy'] + target_pixcoords_spectrogram[1] 

1081 s.table['x_c'] = s.table['Dx'] + target_pixcoords_spectrogram[0] 

1082 my_logger.debug(f"\n\tTransverse fit table after derotation:" 

1083 f"\n{s.table[['amplitude', 'x_c', 'y_c', 'Dx', 'Dy', 'Dy_disp_axis']]}") 

1084 

1085 # Create spectrogram 

1086 data = data[ymin:ymax, xmin:xmax] 

1087 err = err[ymin:ymax, xmin:xmax] 

1088 Ny, Nx = data.shape 

1089 my_logger.info(f'\n\tExtract spectrogram: crop raw image [{xmin}:{xmax},{ymin}:{ymax}] (size ({Nx}, {Ny}))') 

1090 

1091 # Extract the non rotated background 

1092 bgd_model_func, bgd_res, bgd_rms = extract_spectrogram_background_sextractor(data, err, ws=ws) 

1093 bgd = bgd_model_func(np.arange(Nx), np.arange(Ny)) 

1094 my_logger.info(f"\n\tBackground statistics: mean={np.nanmean(bgd):.3f} {image.units}, " 

1095 f"RMS={np.nanmean(bgd_rms):.3f} {image.units}.") 

1096 

1097 # Propagate background uncertainties 

1098 err = np.sqrt(err * err + bgd_rms * bgd_rms) 

1099 

1100 # First guess for lambdas 

1101 first_guess_lambdas = image.disperser.grating_pixel_to_lambda(s.get_algebraic_distance_along_dispersion_axis(), 

1102 x0=image.target_pixcoords, order=spectrum.order) 

1103 s.table['lambdas'] = first_guess_lambdas 

1104 spectrum.lambdas = np.array(first_guess_lambdas) 

1105 

1106 # Position of the order 0 in the spectrogram coordinates 

1107 my_logger.info(f'\n\tExtract spectrogram: crop image [{xmin}:{xmax},{ymin}:{ymax}] (size ({Nx}, {Ny}))' 

1108 f'\n\tNew target position in spectrogram frame: {target_pixcoords_spectrogram}') 

1109 

1110 # Save results 

1111 spectrum.spectrogram = data 

1112 spectrum.spectrogram_err = err 

1113 spectrum.spectrogram_bgd = bgd 

1114 spectrum.spectrogram_bgd_rms = bgd_rms 

1115 spectrum.spectrogram_x0 = target_pixcoords_spectrogram[0] 

1116 spectrum.spectrogram_y0 = target_pixcoords_spectrogram[1] 

1117 spectrum.spectrogram_xmin = xmin 

1118 spectrum.spectrogram_xmax = xmax 

1119 spectrum.spectrogram_ymin = ymin 

1120 spectrum.spectrogram_ymax = ymax 

1121 spectrum.spectrogram_deg = spectrum.chromatic_psf.deg 

1122 spectrum.spectrogram_saturation = spectrum.chromatic_psf.saturation 

1123 

1124 # Plot FHWM(lambda) 

1125 if parameters.DEBUG: 

1126 fig, ax = plt.subplots(2, 1, figsize=(10, 8), sharex="all") 

1127 ax[0].plot(spectrum.lambdas, np.array(s.table['fwhm'])) 

1128 ax[0].set_xlabel(r"$\lambda$ [nm]") 

1129 ax[0].set_ylabel("Transverse FWHM [pixels]") 

1130 ax[0].set_ylim((0.8 * np.min(s.table['fwhm']), 1.2 * np.max(s.table['fwhm']))) # [-10:]))) 

1131 ax[0].grid() 

1132 ax[1].plot(spectrum.lambdas, np.array(s.table['y_c'])) 

1133 ax[1].set_xlabel(r"$\lambda$ [nm]") 

1134 ax[1].set_ylabel("Distance from mean dispersion axis [pixels]") 

1135 # ax[1].set_ylim((0.8*np.min(s.table['Dy']), 1.2*np.max(s.table['fwhm'][-10:]))) 

1136 ax[1].grid() 

1137 if parameters.DISPLAY: 

1138 plt.show() 

1139 if parameters.LSST_SAVEFIGPATH: 

1140 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'fwhm.pdf')) 

1141 

1142 # Summary plot 

1143 if parameters.DEBUG or parameters.LSST_SAVEFIGPATH: 

1144 gs_kw = dict(width_ratios=[3, 0.08], height_ratios=[1, 1, 1]) 

1145 fig, ax = plt.subplots(3, 2, sharex='none', figsize=(12, 6), gridspec_kw=gs_kw) 

1146 xx = np.arange(s.table['Dx'].size) 

1147 plot_image_simple(ax[2, 0], data=data, scale="symlog", title='', units=image.units, aspect='auto', cax=ax[2, 1]) 

1148 ax[2, 0].plot(xx, target_pixcoords_spectrogram[1] + s.table['Dy_disp_axis'], label='Dispersion axis', color="r") 

1149 ax[2, 0].scatter(xx, target_pixcoords_spectrogram[1] + s.table['Dy'], 

1150 c=s.table['lambdas'], edgecolors='None', cmap=from_lambda_to_colormap(s.table['lambdas']), 

1151 label='Fitted spectrum centers', marker='o', s=10) 

1152 ax[2, 0].plot(xx, target_pixcoords_spectrogram[1] + s.table['Dy_fwhm_inf'], 'k-', label='Fitted FWHM') 

1153 ax[2, 0].plot(xx, target_pixcoords_spectrogram[1] + s.table['Dy_fwhm_sup'], 'k-', label='') 

1154 ax[2, 0].set_ylim(0.5 * Ny - signal_width, 0.5 * Ny + signal_width) 

1155 ax[2, 0].set_xlim(0, xx.size) 

1156 ax[2, 0].legend(loc='best') 

1157 plot_spectrum_simple(ax[0, 0], spectrum.lambdas, spectrum.data, data_err=spectrum.err, 

1158 units=image.units, label='Fitted spectrum') 

1159 ax[0, 0].plot(spectrum.lambdas, s.table['flux_sum'], 'k-', label='Cross spectrum') 

1160 ax[1, 0].set_xlabel(r"$\lambda$ [nm]") 

1161 ax[0, 0].legend(loc='best') 

1162 ax[1, 0].plot(spectrum.lambdas, (s.table['flux_sum'] - s.table['flux_integral']) / s.table['flux_sum'], 

1163 label='(model_integral-cross_sum)/cross_sum') 

1164 ax[1, 0].legend() 

1165 ax[1, 0].grid(True) 

1166 ax[1, 0].set_xlim(ax[0, 0].get_xlim()) 

1167 ax[1, 0].set_ylim(-1, 1) 

1168 ax[1, 0].set_ylabel('Relative difference') 

1169 fig.tight_layout() 

1170 # fig.subplots_adjust(hspace=0) 

1171 pos0 = ax[0, 0].get_position() 

1172 pos1 = ax[1, 0].get_position() 

1173 pos2 = ax[2, 0].get_position() 

1174 ax[0, 0].set_position([pos2.x0, pos0.y0, pos2.width, pos0.height]) 

1175 ax[1, 0].set_position([pos2.x0, pos1.y0, pos2.width, pos1.height]) 

1176 ax[0, 1].remove() 

1177 ax[1, 1].remove() 

1178 if parameters.DISPLAY: 

1179 plt.show() 

1180 if parameters.LSST_SAVEFIGPATH: 

1181 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'intermediate_spectrum.pdf')) 

1182 

1183 return w, bgd_model_func 

1184 

1185 

1186def run_spectrogram_deconvolution_psf2d(spectrum, bgd_model_func): 

1187 """Get the spectrum from a 2D PSF deconvolution of the spectrogram. 

1188 

1189 Parameters 

1190 ---------- 

1191 spectrum: Spectrum 

1192 bgd_model_func: callable 

1193 

1194 Returns 

1195 ------- 

1196 w: ChromaticPSFFitWorkspace 

1197 

1198 """ 

1199 my_logger = set_logger(__name__) 

1200 s = spectrum.chromatic_psf 

1201 Ny, Nx = spectrum.spectrogram.shape 

1202 

1203 # build 1D priors 

1204 Dx_rot = np.copy(s.table['Dx']) 

1205 amplitude_priors = np.copy(s.table['amplitude']) 

1206 amplitude_priors_err = np.copy(s.table['flux_err']) 

1207 psf_poly_priors = s.from_table_to_poly_params()[s.Nx:] 

1208 Dy_disp_axis = np.copy(s.table["Dy_disp_axis"]) 

1209 

1210 # initialize a new ChromaticPSF 

1211 s = ChromaticPSF(s.psf, Nx=Nx, Ny=Ny, x0=spectrum.spectrogram_x0, y0=spectrum.spectrogram_y0, 

1212 deg=s.deg, saturation=s.saturation) 

1213 

1214 # fill a first table with first guess 

1215 s.table['Dx'] = (np.arange(spectrum.spectrogram_xmin, spectrum.spectrogram_xmax, 1) 

1216 - spectrum.x0[0])[:len(s.table['Dx'])] 

1217 s.table["amplitude"] = np.interp(s.table['Dx'], Dx_rot, amplitude_priors) 

1218 s.table["flux_sum"] = np.interp(s.table['Dx'], Dx_rot, amplitude_priors) 

1219 s.table["flux_err"] = np.interp(s.table['Dx'], Dx_rot, amplitude_priors_err) 

1220 s.table['Dy_disp_axis'] = np.interp(s.table['Dx'], Dx_rot, Dy_disp_axis) 

1221 s.poly_params = np.concatenate((s.table["amplitude"], psf_poly_priors)) 

1222 s.cov_matrix = np.copy(spectrum.cov_matrix) 

1223 s.profile_params = s.from_poly_params_to_profile_params(s.poly_params, apply_bounds=True) 

1224 s.fill_table_with_profile_params(s.profile_params) 

1225 s.from_profile_params_to_shape_params(s.profile_params) 

1226 s.table['Dy'] = s.table['y_c'] - spectrum.spectrogram_y0 

1227 

1228 # deconvolve and regularize with 1D priors 

1229 method = "psf1d" 

1230 mode = "2D" 

1231 my_logger.debug(f"\n\tTransverse fit table before PSF_2D fit:" 

1232 f"\n{s.table[['amplitude', 'x_c', 'y_c', 'Dx', 'Dy', 'Dy_disp_axis']]}") 

1233 my_logger.info(f'\n\tStart ChromaticPSF polynomial fit with ' 

1234 f'mode={mode} and amplitude_priors_method={method}...') 

1235 data = spectrum.spectrogram 

1236 err = spectrum.spectrogram_err 

1237 w = s.fit_chromatic_psf(data, bgd_model_func=bgd_model_func, data_errors=err, live_fit=False, 

1238 amplitude_priors_method=method, mode=mode, verbose=parameters.VERBOSE) 

1239 

1240 # save results 

1241 spectrum.spectrogram_fit = s.build_spectrogram_image(s.poly_params, mode=mode) 

1242 spectrum.spectrogram_residuals = (data - spectrum.spectrogram_fit - bgd_model_func(np.arange(Nx), 

1243 np.arange(Ny))) / err 

1244 lambdas = spectrum.disperser.grating_pixel_to_lambda(s.get_algebraic_distance_along_dispersion_axis(), 

1245 x0=spectrum.x0, order=spectrum.order) 

1246 s.table['lambdas'] = lambdas 

1247 spectrum.lambdas = np.array(lambdas) 

1248 spectrum.data = np.copy(w.amplitude_params) 

1249 spectrum.err = np.copy(w.amplitude_params_err) 

1250 spectrum.cov_matrix = np.copy(w.amplitude_cov_matrix) 

1251 spectrum.pixels = np.copy(s.table['Dx']) 

1252 s.table['Dy'] = s.table['y_c'] - spectrum.spectrogram_y0 

1253 s.table['Dy_fwhm_inf'] = s.table['Dy'] - 0.5 * s.table['fwhm'] 

1254 s.table['Dy_fwhm_sup'] = s.table['Dy'] + 0.5 * s.table['fwhm'] 

1255 spectrum.chromatic_psf = s 

1256 spectrum.header['PSF_REG'] = s.opt_reg 

1257 

1258 # Plot FHWM(lambda) 

1259 if parameters.DEBUG: 

1260 fig, ax = plt.subplots(2, 1, figsize=(10, 8), sharex="all") 

1261 ax[0].plot(spectrum.lambdas, np.array(s.table['fwhm'])) 

1262 ax[0].set_xlabel(r"$\lambda$ [nm]") 

1263 ax[0].set_ylabel("Transverse FWHM [pixels]") 

1264 ax[0].set_ylim((0.8 * np.min(s.table['fwhm']), 1.2 * np.max(s.table['fwhm']))) # [-10:]))) 

1265 ax[0].grid() 

1266 ax[1].plot(spectrum.lambdas, np.array(s.table['y_c'])) 

1267 ax[1].set_xlabel(r"$\lambda$ [nm]") 

1268 ax[1].set_ylabel("Distance from mean dispersion axis [pixels]") 

1269 # ax[1].set_ylim((0.8*np.min(s.table['Dy']), 1.2*np.max(s.table['fwhm'][-10:]))) 

1270 ax[1].grid() 

1271 if parameters.DISPLAY: 

1272 plt.show() 

1273 if parameters.LSST_SAVEFIGPATH: 

1274 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'fwhm_2.pdf')) 

1275 

1276 return w 

1277 

1278 

1279def plot_comparison_truth(spectrum, w): # pragma: no cover 

1280 s = spectrum.chromatic_psf 

1281 lambdas_truth = np.fromstring(spectrum.header['LBDAS_T'][1:-1], sep=' ') 

1282 psf_poly_truth = np.fromstring(spectrum.header['PSF_P_T'][1:-1], sep=' ', dtype=float) 

1283 deg_truth = int(spectrum.header["PSF_DEG"]) 

1284 psf_poly_truth[-1] = spectrum.spectrogram_saturation 

1285 amplitude_truth = np.fromstring(spectrum.header['AMPLIS_T'][1:-1], sep=' ', dtype=float) 

1286 amplitude_truth *= parameters.FLAM_TO_ADURATE * lambdas_truth * np.gradient(lambdas_truth) 

1287 s0 = ChromaticPSF(s.psf, lambdas_truth.size, s.Ny, deg=deg_truth, 

1288 saturation=spectrum.spectrogram_saturation) 

1289 s0.poly_params = np.asarray(list(amplitude_truth) + list(psf_poly_truth)) 

1290 s0.deg = (len(s0.poly_params[s0.Nx:]) - 1) // (len(s0.psf.param_names) - 2) - 1 

1291 s0.set_polynomial_degrees(s0.deg) 

1292 s0.profile_params = s0.from_poly_params_to_profile_params(s0.poly_params) 

1293 s0.from_profile_params_to_shape_params(s0.profile_params) 

1294 gs_kw = dict(width_ratios=[2, 1], height_ratios=[2, 1]) 

1295 fig, ax = plt.subplots(2, 2, figsize=(9, 5), sharex="all", gridspec_kw=gs_kw) 

1296 ax[0, 0].plot(lambdas_truth, amplitude_truth, label="truth") 

1297 amplitude_priors_err = [np.sqrt(w.amplitude_priors_cov_matrix[x, x]) for x in range(w.Nx)] 

1298 ax[0, 0].errorbar(spectrum.lambdas, w.amplitude_priors, yerr=amplitude_priors_err, label="prior") 

1299 ax[0, 0].errorbar(spectrum.lambdas, w.amplitude_params, yerr=w.amplitude_params_err, label="2D") 

1300 ax[0, 0].grid() 

1301 ax[0, 0].legend() 

1302 ax[0, 0].set_xlabel(r"$\lambda$ [nm]") 

1303 ax[0, 0].set_ylabel(f"Amplitude $A$ [ADU/s]") 

1304 ax[1, 0].plot(lambdas_truth, np.zeros_like(lambdas_truth), label="truth") 

1305 amplitude_truth_interp = np.interp(spectrum.lambdas, lambdas_truth, amplitude_truth) 

1306 res = (w.amplitude_priors - amplitude_truth_interp) / amplitude_priors_err 

1307 ax[1, 0].errorbar(spectrum.lambdas, res, yerr=np.ones_like(res), 

1308 label=f"prior: mean={np.mean(res):.2f}, std={np.std(res):.2f}") 

1309 res = (w.amplitude_params - amplitude_truth_interp) / w.amplitude_params_err 

1310 ax[1, 0].errorbar(spectrum.lambdas, res, yerr=np.ones_like(res), 

1311 label=f"2D: mean={np.mean(res):.2f}, std={np.std(res):.2f}") 

1312 ax[1, 0].grid() 

1313 ax[1, 0].legend() 

1314 ax[1, 0].set_xlabel(r"$\lambda$ [nm]") 

1315 ax[1, 0].set_ylim(-5, 5) 

1316 ax[1, 0].set_ylabel(r"$(A - A_{\rm truth})/\sigma_A$") 

1317 

1318 fwhm_truth = np.interp(spectrum.lambdas, lambdas_truth, s0.table["fwhm"]) 

1319 # fwhm_prior = np.interp(spectrum.lambdas, np.arange(w.amplitude_priors.size), w.fwhm_priors) 

1320 # fwhm_1d = np.interp(np.arange(len(s.table)), np.arange(w.fwhm_1d.size), w.fwhm_1d) 

1321 # fwhm_2d = np.interp(np.arange(len(s.table)), np.arange(s.Nx), fwhm_1d) 

1322 ax[0, 1].plot(lambdas_truth, s0.table["fwhm"], label="truth") 

1323 ax[0, 1].plot(spectrum.lambdas, w.fwhm_priors, label="prior") 

1324 ax[0, 1].plot(spectrum.lambdas, s.table["fwhm"], label="fit") 

1325 ax[0, 1].grid() 

1326 ax[0, 1].set_ylim(0, 10) 

1327 ax[0, 1].legend() 

1328 ax[0, 1].set_xlabel(r"$\lambda$ [nm]") 

1329 ax[1, 1].set_xlabel(r"$\lambda$ [nm]") 

1330 ax[0, 1].set_ylabel(f"FWHM [pix]") 

1331 ax[1, 1].set_ylabel(r"FWHM - FWHM$_{\rm truth}$ [pix]") 

1332 ax[1, 1].plot(lambdas_truth, np.zeros_like(lambdas_truth), label="truth") 

1333 ax[1, 1].plot(spectrum.lambdas, w.fwhm_priors - fwhm_truth, label="prior") 

1334 ax[1, 1].plot(spectrum.lambdas, s.table["fwhm"] - fwhm_truth, label="2D") 

1335 ax[1, 1].grid() 

1336 ax[1, 1].set_ylim(-0.5, 0.5) 

1337 ax[1, 1].legend() 

1338 plt.subplots_adjust(hspace=0) 

1339 fig.tight_layout() 

1340 if parameters.DISPLAY: 

1341 plt.show() 

1342 if parameters.LSST_SAVEFIGPATH: 

1343 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'deconvolution_truth.pdf')) 

1344 plt.show()