Coverage for spectractor/fit/fit_spectrogram.py: 7%

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

269 statements  

1import time 

2import os 

3import matplotlib.pyplot as plt 

4from matplotlib import cm 

5import numpy as np 

6import copy 

7 

8from spectractor import parameters 

9from spectractor.config import set_logger, load_config 

10from spectractor.tools import plot_image_simple, from_lambda_to_colormap 

11from spectractor.simulation.simulator import SimulatorInit, SpectrogramModel 

12from spectractor.simulation.atmosphere import Atmosphere, AtmosphereGrid 

13from spectractor.fit.fitter import FitWorkspace, run_minimisation, run_gradient_descent, run_minimisation_sigma_clipping 

14 

15plot_counter = 0 

16 

17 

18class SpectrogramFitWorkspace(FitWorkspace): 

19 

20 def __init__(self, file_name, atmgrid_file_name="", nwalkers=18, nsteps=1000, burnin=100, nbins=10, 

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

22 """Class to fit a spectrogram extracted with Spectractor. 

23 

24 First the spectrogram is cropped using the parameters.PIXWIDTH_SIGNAL parameter to increase speedness. 

25 The truth parameters are loaded from the file header if provided. 

26 If provided, the atmospheric grid is used for the atmospheric transmission simulations and interpolated 

27 with splines, otherwise Libradtran is called at each step (slower). 

28 

29 Parameters 

30 ---------- 

31 file_name: str 

32 Spectrum file name. 

33 atmgrid_file_name: str, optional 

34 Atmospheric grid file name (default: ""). 

35 nwalkers: int, optional 

36 Number of walkers for MCMC fitting. 

37 nsteps: int, optional 

38 Number of steps for MCMC fitting. 

39 burnin: int, optional 

40 Number of burn-in steps for MCMC fitting. 

41 nbins: int, optional 

42 Number of bins for MCMC chains analysis. 

43 verbose: int, optional 

44 Verbosity level (default: 0). 

45 plot: bool, optional 

46 If True, many plots are produced (default: False). 

47 live_fit: bool, optional 

48 If True, many plots along the fitting procedure are produced to see convergence in live (default: False). 

49 truth: array_like, optional 

50 Array of truth parameters to compare with the best fit result (default: None). 

51 

52 Examples 

53 -------- 

54 

55 >>> filename = 'tests/data/reduc_20170530_134_spectrum.fits' 

56 >>> atmgrid_filename = filename.replace('spectrum', 'atmsim') 

57 >>> load_config("config/ctio.ini") 

58 >>> w = SpectrogramFitWorkspace(filename, atmgrid_file_name=atmgrid_filename, nsteps=1000, 

59 ... burnin=2, nbins=10, verbose=1, plot=True, live_fit=False) 

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

61 >>> w.plot_fit() 

62 

63 """ 

64 FitWorkspace.__init__(self, file_name, nwalkers, nsteps, burnin, nbins, verbose, plot, 

65 live_fit, truth=truth) 

66 if "spectrum" not in file_name: 

67 raise ValueError("file_name argument must contain spectrum keyword and be an output from Spectractor.") 

68 self.filename = self.filename.replace("spectrum", "spectrogram") 

69 self.spectrum, self.telescope, self.disperser, self.target = SimulatorInit(file_name) 

70 self.airmass = self.spectrum.header['AIRMASS'] 

71 self.pressure = self.spectrum.header['OUTPRESS'] 

72 self.temperature = self.spectrum.header['OUTTEMP'] 

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

74 if atmgrid_file_name == "": 

75 self.atmosphere = Atmosphere(self.airmass, self.pressure, self.temperature) 

76 else: 

77 self.use_grid = True 

78 self.atmosphere = AtmosphereGrid(file_name, atmgrid_file_name) 

79 if parameters.VERBOSE: 

80 self.my_logger.info(f'\n\tUse atmospheric grid models from file {atmgrid_file_name}. ') 

81 self.crop_spectrogram() 

82 self.lambdas = self.spectrum.lambdas 

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

84 self.data = self.spectrum.spectrogram.flatten() 

85 self.err = self.spectrum.spectrogram_err.flatten() 

86 self.A1 = 1.0 

87 self.A2 = 1.0 

88 self.ozone = 400. 

89 self.pwv = 3 

90 self.aerosols = 0.05 

91 self.D = self.spectrum.header['D2CCD'] 

92 self.psf_poly_params = self.spectrum.chromatic_psf.from_table_to_poly_params() 

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

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

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

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

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

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

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

100 self.shift_x = self.spectrum.header['PIXSHIFT'] 

101 self.shift_y = 0. 

102 self.angle = self.spectrum.rotation_angle 

103 self.B = 1 

104 self.saturation = self.spectrum.spectrogram_saturation 

105 self.p = np.array([self.A1, self.A2, self.ozone, self.pwv, self.aerosols, 

106 self.D, self.shift_x, self.shift_y, self.angle, self.B]) 

107 self.fixed_psf_params = np.array([0, 1, 2, 3, 4, 9]) 

108 self.atm_params_indices = np.array([2, 3, 4]) 

109 self.psf_params_start_index = self.p.size 

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

111 self.input_labels = ["A1", "A2", "ozone [db]", "PWV [mm]", "VAOD", r"D_CCD [mm]", 

112 r"shift_x [pix]", r"shift_y [pix]", r"angle [deg]", "B"] + list(self.psf_poly_params_labels) 

113 self.axis_names = ["$A_1$", "$A_2$", "ozone [db]", "PWV [mm]", "VAOD", r"$D_{CCD}$ [mm]", 

114 r"$\Delta_{\mathrm{x}}$ [pix]", r"$\Delta_{\mathrm{y}}$ [pix]", 

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

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

117 self.bounds = np.concatenate([np.array([(0, 2), (0, 2/parameters.GRATING_ORDER_2OVER1), (100, 700), (0, 10), 

118 (0, 0.1), bounds_D, (-2, 2), (-10, 10), (-90, 90), (0.8, 1.2)]), 

119 psf_poly_params_bounds]) 

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

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

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

123 self.fixed[k] = True 

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

125 self.fixed[1] = "A2_T" not in self.spectrum.header # not self.spectrum.disperser.flat_ratio_order_2over1 

126 # self.fixed[5:7] = [True, True] # DCCD, x0 

127 self.fixed[6] = True # Delta x 

128 # self.fixed[7] = True # Delta y 

129 # self.fixed[8] = True # angle 

130 self.fixed[9] = True # B 

131 if atmgrid_file_name != "": 

132 self.bounds[2] = (min(self.atmosphere.OZ_Points), max(self.atmosphere.OZ_Points)) 

133 self.bounds[3] = (min(self.atmosphere.PWV_Points), max(self.atmosphere.PWV_Points)) 

134 self.bounds[4] = (min(self.atmosphere.AER_Points), max(self.atmosphere.AER_Points)) 

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

136 self.simulation = SpectrogramModel(self.spectrum, self.atmosphere, self.telescope, self.disperser, 

137 with_background=True, fast_sim=False) 

138 self.lambdas_truth = None 

139 self.amplitude_truth = None 

140 self.get_spectrogram_truth() 

141 

142 def crop_spectrogram(self): 

143 """Crop the spectrogram in the middle, keeping a vertical width of 2*parameters.PIXWIDTH_SIGNAL around 

144 the signal region. 

145 

146 """ 

147 bgd_width = parameters.PIXWIDTH_BACKGROUND + parameters.PIXDIST_BACKGROUND - parameters.PIXWIDTH_SIGNAL 

148 self.spectrum.spectrogram_ymax = self.spectrum.spectrogram_ymax - bgd_width 

149 self.spectrum.spectrogram_ymin += bgd_width 

150 self.spectrum.spectrogram_bgd = self.spectrum.spectrogram_bgd[bgd_width:-bgd_width, :] 

151 self.spectrum.spectrogram = self.spectrum.spectrogram[bgd_width:-bgd_width, :] 

152 self.spectrum.spectrogram_err = self.spectrum.spectrogram_err[bgd_width:-bgd_width, :] 

153 self.spectrum.spectrogram_y0 -= bgd_width 

154 self.spectrum.chromatic_psf.y0 -= bgd_width 

155 self.spectrum.spectrogram_Ny, self.spectrum.spectrogram_Nx = self.spectrum.spectrogram.shape 

156 self.spectrum.chromatic_psf.table["y_c"] -= bgd_width 

157 self.my_logger.debug(f'\n\tSize of the spectrogram region after cropping: ' 

158 f'({self.spectrum.spectrogram_Nx},{self.spectrum.spectrogram_Ny})') 

159 

160 def get_spectrogram_truth(self): 

161 """Load the truth parameters (if provided) from the file header. 

162 

163 """ 

164 if 'A1_T' in list(self.spectrum.header.keys()): 

165 A1_truth = self.spectrum.header['A1_T'] 

166 A2_truth = self.spectrum.header['A2_T'] 

167 ozone_truth = self.spectrum.header['OZONE_T'] 

168 pwv_truth = self.spectrum.header['PWV_T'] 

169 aerosols_truth = self.spectrum.header['VAOD_T'] 

170 D_truth = self.spectrum.header['D2CCD_T'] 

171 shiftx_truth = 0 

172 shifty_truth = 0 

173 rotation_angle = self.spectrum.header['ROT_T'] 

174 B = 1 

175 poly_truth = np.fromstring(self.spectrum.header['PSF_P_T'][1:-1], sep=' ', dtype=float) 

176 self.truth = (A1_truth, A2_truth, ozone_truth, pwv_truth, aerosols_truth, 

177 D_truth, shiftx_truth, shifty_truth, rotation_angle, B, *poly_truth) 

178 self.lambdas_truth = np.fromstring(self.spectrum.header['LBDAS_T'][1:-1], sep=' ', dtype=float) 

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

180 else: 

181 self.truth = None 

182 

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

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

185 

186 Parameters 

187 ---------- 

188 ax: Axes 

189 Axes instance of shape (4, 2). 

190 title: str, optional 

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

192 extent: array_like, optional 

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

194 dispersion: bool, optional 

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

196 """ 

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

198 cmap_bwr.set_bad(color='lightgrey') 

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

200 cmap_viridis.set_bad(color='lightgrey') 

201 

202 data = np.copy(self.data) 

203 if len(self.outliers) > 0: 

204 bad_indices = self.get_bad_indices() 

205 data[bad_indices] = np.nan 

206 

207 lambdas = self.spectrum.lambdas 

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

209 sub = np.where(sub < self.spectrum.spectrogram_Nx)[0] 

210 data = data.reshape((self.Ny, self.Nx)) 

211 model = self.model.reshape((self.Ny, self.Nx)) 

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

213 if extent is not None: 

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

215 if len(sub) > 0: 

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

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

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

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

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

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

222 if dispersion: 

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

224 y = np.ones_like(x) 

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

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

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

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

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

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

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

232 if title != '': 

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

234 residuals = (data - model) 

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

236 norm = err 

237 residuals /= norm 

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

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

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

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

242 ax[2, 0].text(0.05, 0.05, f'mean={np.mean(residuals[:, sub]):.3f}\nstd={np.std(residuals[:, sub]):.3f}', 

243 horizontalalignment='left', verticalalignment='bottom', 

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

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

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

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

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

249 ax[3, 1].remove() 

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

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

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

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

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

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

256 

257 def simulate(self, A1, A2, ozone, pwv, aerosols, D, shift_x, shift_y, angle, B, *psf_poly_params): 

258 """Interface method to simulate a spectrogram. 

259 

260 Parameters 

261 ---------- 

262 A1: float 

263 Main amplitude parameter. 

264 A2: float 

265 Relative amplitude of the order 2 spectrogram. 

266 ozone: float 

267 Ozone parameter for Libradtran (in db). 

268 pwv: float 

269 Precipitable Water Vapor quantity for Libradtran (in mm). 

270 aerosols: float 

271 Vertical Aerosols Optical Depth quantity for Libradtran (no units). 

272 D: float 

273 Distance between the CCD and the disperser (in mm). 

274 shift_x: float 

275 Shift of the order 0 position along the X axis (in pixels). 

276 shift_y: float 

277 Shift of the order 0 position along the Y axis (in pixels). 

278 angle: float 

279 Angle of the dispersion axis with respect to the X axis (in degrees). 

280 B: float 

281 Amplitude of the simulated background. 

282 psf_poly_params: array_like 

283 PSF polynomial parameters formatted with the ChromaticPSF class. 

284 

285 Returns 

286 ------- 

287 lambdas: array_like 

288 Array of wavelengths (1D). 

289 model: array_like 

290 Flat 1D array of the spectrogram simulation. 

291 model_err: array_like 

292 Flat 1D array of the spectrogram simulation uncertainty. 

293 

294 Examples 

295 -------- 

296 

297 >>> filename = 'tests/data/sim_20170530_134_spectrum.fits' 

298 >>> atmgrid_filename = filename.replace('spectrum', 'atmsim') 

299 >>> load_config("config/ctio.ini") 

300 >>> w = SpectrogramFitWorkspace(filename, atmgrid_filename, verbose=1, plot=True, live_fit=False) 

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

302 >>> w.plot_fit() 

303 

304 """ 

305 global plot_counter 

306 lambdas, model, model_err = \ 

307 self.simulation.simulate(A1, A2, ozone, pwv, aerosols, D, shift_x, shift_y, angle, B, psf_poly_params) 

308 self.p = np.array([A1, A2, ozone, pwv, aerosols, D, shift_x, shift_y, angle, B] + list(psf_poly_params)) 

309 self.lambdas = lambdas 

310 self.model = model.flatten() 

311 self.model_err = model_err.flatten() 

312 if self.live_fit and (plot_counter % 30) == 0: # pragma: no cover 

313 self.plot_fit() 

314 plot_counter += 1 

315 return self.lambdas, self.model, self.model_err 

316 

317 def jacobian(self, params, epsilon, fixed_params=None, model_input=None): 

318 start = time.time() 

319 if model_input is not None: 

320 lambdas, model, model_err = model_input 

321 else: 

322 lambdas, model, model_err = self.simulate(*params) 

323 model = model.flatten() 

324 J = np.zeros((params.size, model.size)) 

325 strategy = copy.copy(self.simulation.fix_psf_cube) 

326 atmosphere = copy.copy(self.simulation.atmosphere_sim) 

327 for ip, p in enumerate(params): 

328 if fixed_params[ip]: 

329 continue 

330 if ip in self.fixed_psf_params: 

331 self.simulation.fix_psf_cube = True 

332 else: 

333 self.simulation.fix_psf_cube = False 

334 if ip in self.atm_params_indices: 

335 self.simulation.fix_atm_sim = False 

336 else: 

337 self.simulation.fix_atm_sim = True 

338 tmp_p = np.copy(params) 

339 if tmp_p[ip] + epsilon[ip] < self.bounds[ip][0] or tmp_p[ip] + epsilon[ip] > self.bounds[ip][1]: 

340 epsilon[ip] = - epsilon[ip] 

341 tmp_p[ip] += epsilon[ip] 

342 tmp_lambdas, tmp_model, tmp_model_err = self.simulate(*tmp_p) 

343 if self.simulation.fix_atm_sim is False: 

344 self.simulation.atmosphere_sim = atmosphere 

345 J[ip] = (tmp_model.flatten() - model) / epsilon[ip] 

346 self.simulation.fix_psf_cube = strategy 

347 self.simulation.fix_atm_sim = False 

348 self.my_logger.debug(f"\n\tJacobian time computation = {time.time() - start:.1f}s") 

349 return J 

350 

351 def plot_fit(self): 

352 """Plot the fit result. 

353 

354 Examples 

355 -------- 

356 

357 >>> filename = 'tests/data/reduc_20170530_134_spectrum.fits' 

358 >>> atmgrid_filename = filename.replace('spectrum', 'atmsim') 

359 >>> load_config("config/ctio.ini") 

360 >>> w = SpectrogramFitWorkspace(filename, atmgrid_filename, verbose=1, plot=True, live_fit=False) 

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

362 >>> w.plot_fit() 

363 

364 .. plot:: 

365 :include-source: 

366 

367 from spectractor.fit.fit_spectrogram import SpectrogramFitWorkspace 

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

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

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

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

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

373 shift_y, angle, psf) 

374 fit_workspace.lambdas = lambdas 

375 fit_workspace.model = model 

376 fit_workspace.model_err = model_err 

377 fit_workspace.plot_fit() 

378 

379 """ 

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

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

382 

383 A1, A2, ozone, pwv, aerosols, D, shift_x, shift_y, shift_t, B, *psf = self.p 

384 plt.suptitle(f'A1={A1:.3f}, A2={A2:.3f}, PWV={pwv:.3f}, OZ={ozone:.3g}, VAOD={aerosols:.3f}, ' 

385 f'D={D:.2f}mm, shift_y={shift_y:.2f}pix, B={B:.3f}', y=1) 

386 # main plot 

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

388 # zoom O2 

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

390 # zoom H2O 

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

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

393 for j in range(2): 

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

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

396 for j in range(1, 3): 

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

398 fig.tight_layout() 

399 if self.live_fit: # pragma: no cover 

400 plt.draw() 

401 plt.pause(1e-8) 

402 plt.close() 

403 else: 

404 if parameters.DISPLAY and self.verbose: 

405 plt.show() 

406 if parameters.PdfPages: 

407 parameters.PdfPages.savefig() 

408 if parameters.SAVE: 

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

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

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

412 

413 

414def lnprob_spectrogram(p): # pragma: no cover 

415 """Logarithmic likelihood function to maximize in MCMC exploration. 

416 

417 Parameters 

418 ---------- 

419 p: array_like 

420 Array of SpectrogramFitWorkspace parameters. 

421 

422 Returns 

423 ------- 

424 lp: float 

425 Log of the likelihood function. 

426 

427 """ 

428 global fit_workspace 

429 lp = fit_workspace.lnprior(p) 

430 if not np.isfinite(lp): 

431 return -1e20 

432 return lp + fit_workspace.lnlike_spectrogram(p) 

433 

434 

435def run_spectrogram_minimisation(fit_workspace, method="newton"): 

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

437 

438 Parameters 

439 ---------- 

440 fit_workspace: SpectrogramFitWorkspace 

441 An instance of the SpectrogramFitWorkspace class. 

442 method: str, optional 

443 Fitting method (default: 'newton'). 

444 

445 Examples 

446 -------- 

447 

448 >>> filename = 'tests/data/sim_20170530_134_spectrum.fits' 

449 >>> atmgrid_filename = filename.replace('sim', 'reduc').replace('spectrum', 'atmsim') 

450 >>> load_config("config/ctio.ini") 

451 >>> w = SpectrogramFitWorkspace(filename, atmgrid_file_name=atmgrid_filename, verbose=1, plot=True, live_fit=False) 

452 >>> parameters.VERBOSE = True 

453 >>> run_spectrogram_minimisation(w, method="newton") 

454 

455 """ 

456 my_logger = set_logger(__name__) 

457 guess = np.asarray(fit_workspace.p) 

458 fit_workspace.simulate(*guess) 

459 fit_workspace.plot_fit() 

460 if method != "newton": 

461 run_minimisation(fit_workspace, method=method) 

462 else: 

463 # costs = np.array([fit_workspace.chisq(guess)]) 

464 # if parameters.DISPLAY and (parameters.DEBUG or fit_workspace.live_fit): 

465 # fit_workspace.plot_fit() 

466 # params_table = np.array([guess]) 

467 start = time.time() 

468 my_logger.info(f"\n\tStart guess: {guess}\n\twith {fit_workspace.input_labels}") 

469 epsilon = 1e-4 * guess 

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

471 fixed = np.copy(fit_workspace.fixed) 

472 

473 # fit_workspace.simulation.fast_sim = True 

474 # fit_workspace.simulation.fix_psf_cube = False 

475 # fit_workspace.fixed = np.copy(fixed) 

476 # fit_workspace.fixed[:fit_workspace.psf_params_start_index] = True 

477 # params_table, costs = run_gradient_descent(fit_workspace, guess, epsilon, params_table, costs, 

478 # fix=fit_workspace.fixed, xtol=1e-3, ftol=1e-2, niter=10) 

479 

480 # fit_workspace.simulation.fast_sim = True 

481 # fit_workspace.simulation.fix_psf_cube = False 

482 # fit_workspace.fixed = np.copy(fixed) 

483 # guess = fit_workspace.p 

484 # params_table, costs = run_gradient_descent(fit_workspace, guess, epsilon, params_table, costs, 

485 # fix=fit_workspace.fixed, xtol=1e-5, ftol=1e-3, niter=10) 

486 

487 fit_workspace.simulation.fast_sim = False 

488 fit_workspace.simulation.fix_psf_cube = False 

489 fit_workspace.fixed = np.copy(fixed) 

490 # guess = fit_workspace.p 

491 # params_table, costs = run_gradient_descent(fit_workspace, guess, epsilon, params_table, costs, 

492 # fix=fit_workspace.fixed, xtol=1e-6, ftol=1 / fit_workspace.data.size, 

493 # niter=40) 

494 run_minimisation_sigma_clipping(fit_workspace, method="newton", epsilon=epsilon, fix=fit_workspace.fixed, 

495 xtol=1e-6, ftol=1 / fit_workspace.data.size, sigma_clip=20, niter_clip=3, 

496 verbose=False) 

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

498 if fit_workspace.filename != "": 

499 parameters.SAVE = True 

500 ipar = np.array(np.where(np.array(fit_workspace.fixed).astype(int) == 0)[0]) 

501 fit_workspace.plot_correlation_matrix(ipar) 

502 fit_workspace.save_parameters_summary(ipar, header=f"{fit_workspace.spectrum.date_obs}\n" 

503 f"chi2: " 

504 f"{fit_workspace.costs[-1] / fit_workspace.data.size}") 

505 # save_gradient_descent(fit_workspace, costs, params_table) 

506 fit_workspace.plot_fit() 

507 parameters.SAVE = False 

508 

509 

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

511 from argparse import ArgumentParser 

512 from spectractor.config import load_config 

513 

514 parser = ArgumentParser() 

515 parser.add_argument(dest="input", metavar='path', default=["tests/data/reduc_20170530_134_spectrum.fits"], 

516 help="Input fits file name. It can be a list separated by spaces, or it can use * as wildcard.", 

517 nargs='*') 

518 parser.add_argument("-d", "--debug", dest="debug", action="store_true", 

519 help="Enter debug mode (more verbose and plots).", default=False) 

520 parser.add_argument("-v", "--verbose", dest="verbose", action="store_true", 

521 help="Enter verbose (print more stuff).", default=False) 

522 parser.add_argument("-o", "--output_directory", dest="output_directory", default="outputs/", 

523 help="Write results in given output directory (default: ./outputs/).") 

524 parser.add_argument("-l", "--logbook", dest="logbook", default="ctiofulllogbook_jun2017_v5.csv", 

525 help="CSV logbook file. (default: ctiofulllogbook_jun2017_v5.csv).") 

526 parser.add_argument("-c", "--config", dest="config", default="config/ctio.ini", 

527 help="INI config file. (default: config/ctio.ini).") 

528 args = parser.parse_args() 

529 

530 parameters.VERBOSE = args.verbose 

531 if args.debug: 

532 parameters.DEBUG = True 

533 parameters.VERBOSE = True 

534 

535 file_names = args.input 

536 

537 load_config(args.config) 

538 

539 # filename = 'outputs/reduc_20170530_130_spectrum.fits' 

540 filename = 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_134_spectrum.fits' 

541 # filename = 'outputs/sim_20170530_134_spectrum.fits' 

542 filenames = [ 

543 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_104_spectrum.fits', 

544 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_109_spectrum.fits', 

545 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_114_spectrum.fits', 

546 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_119_spectrum.fits', 

547 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_124_spectrum.fits', 

548 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_129_spectrum.fits', 

549 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_134_spectrum.fits', 

550 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_139_spectrum.fits', 

551 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_144_spectrum.fits', 

552 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_149_spectrum.fits', 

553 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_154_spectrum.fits', 

554 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_159_spectrum.fits', 

555 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_164_spectrum.fits', 

556 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_169_spectrum.fits', 

557 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_174_spectrum.fits', 

558 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_179_spectrum.fits', 

559 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_184_spectrum.fits', 

560 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_189_spectrum.fits', 

561 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_194_spectrum.fits', 

562 'outputs/data_30may17_HoloAmAg_prod7.1/sim_20170530_199_spectrum.fits'] 

563 params = [] 

564 chisqs = [] 

565 filenames = ['outputs/sim_20170530_134_spectrum.fits'] 

566 for filename in filenames: 

567 atmgrid_filename = filename.replace('sim', 'reduc').replace('spectrum', 'atmsim') 

568 

569 w = SpectrogramFitWorkspace(filename, atmgrid_file_name=atmgrid_filename, nsteps=1000, 

570 burnin=2, nbins=10, verbose=1, plot=True, live_fit=False) 

571 # w.simulate(*w.truth) 

572 # w.plot_fit() 

573 run_spectrogram_minimisation(w, method="newton") 

574 # run_emcee(w, ln=lnprob_spectrogram) 

575 # w.analyze_chains() 

576 params.append(w.p) 

577 chisqs.append(w.costs[-1]) 

578 # params = np.asarray(params).T 

579 # 

580 # fig, ax = plt.subplots(1, len(params)) 

581 # for ip, p in enumerate(params): 

582 # print(f"{w.input_labels[ip]}:", np.mean(p), np.std(p)) 

583 # ax[ip].plot(p, label=f"{w.input_labels[ip]}") 

584 # ax[ip].grid() 

585 # ax[ip].legend() 

586 # plt.show()