Coverage for spectractor/fit/fit_spectrum.py: 9%
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import matplotlib.pyplot as plt
2from mpl_toolkits.axes_grid1 import make_axes_locatable
3import numpy as np
4from scipy.interpolate import interp1d
6from spectractor import parameters
7from spectractor.config import set_logger
8from spectractor.simulation.simulator import SimulatorInit, SpectrumSimulation
9from spectractor.simulation.atmosphere import Atmosphere, AtmosphereGrid
10from spectractor.fit.fitter import FitWorkspace, run_minimisation_sigma_clipping
11from spectractor.tools import plot_spectrum_simple
14class SpectrumFitWorkspace(FitWorkspace):
16 def __init__(self, file_name, atmgrid_file_name="", nwalkers=18, nsteps=1000, burnin=100, nbins=10,
17 verbose=0, plot=False, live_fit=False, truth=None):
18 """Class to fit a spectrum extracted with Spectractor.
20 The spectrum is supposed to be the product of the star SED, the instrument throughput and the atmospheric
21 transmission, contaminated eventually by a second order diffraction.
22 The truth parameters are loaded from the file header if provided.
23 If provided, the atmospheric grid is used for the atmospheric transmission simulations and interpolated
24 with splines, otherwise Libradtran is called at each step (slower).
26 Parameters
27 ----------
28 file_name: str
29 Spectrum file name.
30 atmgrid_file_name: str, optional
31 Atmospheric grid file name (default: "").
32 nwalkers: int, optional
33 Number of walkers for MCMC fitting.
34 nsteps: int, optional
35 Number of steps for MCMC fitting.
36 burnin: int, optional
37 Number of burn-in steps for MCMC fitting.
38 nbins: int, optional
39 Number of bins for MCMC chains analysis.
40 verbose: int, optional
41 Verbosity level (default: 0).
42 plot: bool, optional
43 If True, many plots are produced (default: False).
44 live_fit: bool, optional
45 If True, many plots along the fitting procedure are produced to see convergence in live (default: False).
46 truth: array_like, optional
47 Array of truth parameters to compare with the best fit result (default: None).
49 Examples
50 --------
52 >>> filename = 'tests/data/reduc_20170530_134_spectrum.fits'
53 >>> atmgrid_filename = filename.replace('spectrum', 'atmsim')
54 >>> load_config("config/ctio.ini")
55 >>> w = SpectrumFitWorkspace(filename, atmgrid_file_name=atmgrid_filename, nsteps=1000,
56 ... burnin=2, nbins=10, verbose=1, plot=True, live_fit=False)
57 >>> lambdas, model, model_err = w.simulate(*w.p)
58 >>> w.plot_fit()
60 """
61 FitWorkspace.__init__(self, file_name, nwalkers, nsteps, burnin, nbins, verbose, plot, live_fit, truth=truth)
62 if "spectrum" not in file_name:
63 raise ValueError("file_name argument must contain spectrum keyword and be an output from Spectractor.")
64 self.my_logger = set_logger(self.__class__.__name__)
65 self.spectrum, self.telescope, self.disperser, self.target = SimulatorInit(file_name)
66 self.airmass = self.spectrum.header['AIRMASS']
67 self.pressure = self.spectrum.header['OUTPRESS']
68 self.temperature = self.spectrum.header['OUTTEMP']
69 if atmgrid_file_name == "":
70 self.atmosphere = Atmosphere(self.airmass, self.pressure, self.temperature)
71 else:
72 self.use_grid = True
73 self.atmosphere = AtmosphereGrid(file_name, atmgrid_file_name)
74 if parameters.VERBOSE:
75 self.my_logger.info(f'\n\tUse atmospheric grid models from file {atmgrid_file_name}. ')
76 self.lambdas = self.spectrum.lambdas
77 self.data = self.spectrum.data
78 self.err = self.spectrum.err
79 self.data_cov = self.spectrum.cov_matrix
80 self.A1 = 1.0
81 self.A2 = 0
82 self.ozone = 400.
83 self.pwv = 3
84 self.aerosols = 0.05
85 self.reso = -1
86 self.D = self.spectrum.header['D2CCD']
87 self.shift_x = self.spectrum.header['PIXSHIFT']
88 self.B = 0
89 self.p = np.array([self.A1, self.A2, self.ozone, self.pwv, self.aerosols, self.reso, self.D,
90 self.shift_x, self.B])
91 self.fixed = [False] * self.p.size
92 # self.fixed[0] = True
93 self.fixed[1] = "A2_T" not in self.spectrum.header # fit A2 only on sims to evaluate extraction biases
94 self.fixed[5] = True
95 # self.fixed[6:8] = [True, True]
96 self.fixed[7] = True
97 self.fixed[8] = True
98 # self.fixed[-1] = True
99 self.input_labels = ["A1", "A2", "ozone", "PWV", "VAOD", "reso [pix]", r"D_CCD [mm]",
100 r"alpha_pix [pix]", "B"]
101 self.axis_names = ["$A_1$", "$A_2$", "ozone", "PWV", "VAOD", "reso [pix]", r"$D_{CCD}$ [mm]",
102 r"$\alpha_{\mathrm{pix}}$ [pix]", "$B$"]
103 bounds_D = (self.D - 5 * parameters.DISTANCE2CCD_ERR, self.D + 5 * parameters.DISTANCE2CCD_ERR)
104 self.bounds = [(0, 2), (0, 2/parameters.GRATING_ORDER_2OVER1), (100, 700), (0, 10), (0, 0.1),
105 (0.1, 10), bounds_D, (-2, 2), (-np.inf, np.inf)]
106 if atmgrid_file_name != "":
107 self.bounds[2] = (min(self.atmosphere.OZ_Points), max(self.atmosphere.OZ_Points))
108 self.bounds[3] = (min(self.atmosphere.PWV_Points), max(self.atmosphere.PWV_Points))
109 self.bounds[4] = (min(self.atmosphere.AER_Points), max(self.atmosphere.AER_Points))
110 self.nwalkers = max(2 * self.ndim, nwalkers)
111 self.simulation = SpectrumSimulation(self.spectrum, self.atmosphere, self.telescope, self.disperser)
112 self.amplitude_truth = None
113 self.lambdas_truth = None
114 self.output_file_name = file_name.replace('_spectrum', '_spectrum_A2=0')
115 self.get_truth()
117 def get_truth(self):
118 """Load the truth parameters (if provided) from the file header.
120 """
121 if 'A1_T' in list(self.spectrum.header.keys()):
122 A1_truth = self.spectrum.header['A1_T']
123 A2_truth = 0 * self.spectrum.header['A2_T']
124 ozone_truth = self.spectrum.header['OZONE_T']
125 pwv_truth = self.spectrum.header['PWV_T']
126 aerosols_truth = self.spectrum.header['VAOD_T']
127 reso_truth = -1
128 D_truth = self.spectrum.header['D2CCD_T']
129 shift_truth = 0
130 B_truth = 0
131 self.truth = (A1_truth, A2_truth, ozone_truth, pwv_truth, aerosols_truth,
132 reso_truth, D_truth, shift_truth, B_truth)
133 self.lambdas_truth = np.fromstring(self.spectrum.header['LBDAS_T'][1:-1], sep=' ', dtype=float)
134 self.amplitude_truth = np.fromstring(self.spectrum.header['AMPLIS_T'][1:-1], sep=' ', dtype=float)
135 else:
136 self.truth = None
138 def plot_spectrum_comparison_simple(self, ax, title='', extent=None, size=0.4):
139 """Method to plot a spectrum issued from data and compare it with simulations.
141 Parameters
142 ----------
143 ax: Axes
144 Axes instance of shape (4, 2).
145 title: str, optional
146 Title for the simulation plot (default: '').
147 extent: array_like, optional
148 Extent argument for imshow to crop plots (default: None).
149 size: float, optional
150 Relative size of the residual pad (default: 0.4).
151 """
152 lambdas = self.spectrum.lambdas
153 sub = np.where((lambdas > parameters.LAMBDA_MIN) & (lambdas < parameters.LAMBDA_MAX))
154 if extent is not None:
155 sub = np.where((lambdas > extent[0]) & (lambdas < extent[1]))
156 plot_spectrum_simple(ax, lambdas=lambdas, data=self.data, data_err=self.err,
157 units=self.spectrum.units)
158 p0 = ax.plot(lambdas, self.model, label='model')
159 ax.fill_between(lambdas, self.model - self.model_err,
160 self.model + self.model_err, alpha=0.3, color=p0[0].get_color())
161 if self.amplitude_truth is not None:
162 ax.plot(self.lambdas_truth, self.amplitude_truth, 'g', label="truth")
163 # ax.plot(self.lambdas, self.model_noconv, label='before conv')
164 if title != '':
165 ax.set_title(title, fontsize=10)
166 ax.legend()
167 divider = make_axes_locatable(ax)
168 ax2 = divider.append_axes("bottom", size=size, pad=0, sharex=ax)
169 ax.figure.add_axes(ax2)
170 min_positive = np.min(self.model[self.model > 0])
171 idx = np.logical_not(np.isclose(self.model[sub], 0, atol=0.01 * min_positive))
172 residuals = (self.spectrum.data[sub][idx] - self.model[sub][idx]) / self.err[sub][idx]
173 residuals_err = self.spectrum.err[sub][idx] / self.err[sub][idx]
174 ax2.errorbar(lambdas[sub][idx], residuals, yerr=residuals_err, fmt='ro', markersize=2, label='(Data-Model)/Err')
175 ax2.axhline(0, color=p0[0].get_color())
176 ax2.grid(True)
177 ylim = ax2.get_ylim()
178 residuals_model = self.model_err[sub][idx] / self.err[sub][idx]
179 ax2.fill_between(lambdas[sub][idx], -residuals_model, residuals_model, alpha=0.3, color=p0[0].get_color())
180 # std = np.std(residuals)
181 ax2.set_ylim(ylim)
182 ax2.set_xlabel(ax.get_xlabel())
183 # ax2.set_ylabel('(Data-Model)/Err', fontsize=10)
184 ax2.legend()
185 ax2.set_xlim((lambdas[sub][0], lambdas[sub][-1]))
186 ax.set_xlim((lambdas[sub][0], lambdas[sub][-1]))
187 ax.set_ylim((0.9 * np.min(self.spectrum.data[sub]), 1.1 * np.max(self.spectrum.data[sub])))
188 ax.set_xticks(ax2.get_xticks()[1:-1])
189 ax.get_yaxis().set_label_coords(-0.08, 0.6)
190 # ax2.get_yaxis().set_label_coords(-0.11, 0.5)
192 def simulate(self, A1, A2, ozone, pwv, aerosols, reso, D, shift_x, B):
193 """Interface method to simulate a spectrogram.
195 Parameters
196 ----------
197 A1: float
198 Main amplitude parameter.
199 A2: float
200 Relative amplitude of the order 2 spectrogram.
201 ozone: float
202 Ozone parameter for Libradtran (in db).
203 pwv: float
204 Precipitable Water Vapor quantity for Libradtran (in mm).
205 aerosols: float
206 Vertical Aerosols Optical Depth quantity for Libradtran (no units).
207 reso: float
208 Width of the Gaussian kernel to convolve the spectrum.
209 D: float
210 Distance between the CCD and the disperser (in mm).
211 shift_x: float
212 Shift of the order 0 position along the X axis (in pixels).
213 B: float
214 Amplitude of the simulated background (considered flat in ADUs).
216 Returns
217 -------
218 lambdas: array_like
219 Array of wavelengths (1D).
220 model: array_like
221 2D array of the spectrogram simulation.
222 model_err: array_like
223 2D array of the spectrogram simulation uncertainty.
225 Examples
226 --------
228 >>> filename = 'tests/data/sim_20170530_134_spectrum.fits'
229 >>> atmgrid_filename = filename.replace('spectrum', 'atmsim')
230 >>> load_config("config/ctio.ini")
231 >>> w = SpectrumFitWorkspace(filename, atmgrid_filename, verbose=1, plot=True, live_fit=False)
232 >>> lambdas, model, model_err = w.simulate(*w.p)
233 >>> w.plot_fit()
235 """
236 lambdas, model, model_err = self.simulation.simulate(A1, A2, ozone, pwv, aerosols, reso, D, shift_x, B)
237 self.model = model
238 self.model_err = model_err
239 return lambdas, model, model_err
241 def plot_fit(self):
242 """Plot the fit result.
244 Examples
245 --------
247 >>> filename = 'tests/data/reduc_20170530_134_spectrum.fits'
248 >>> atmgrid_filename = filename.replace('spectrum', 'atmsim')
249 >>> load_config("config/ctio.ini")
250 >>> w = SpectrumFitWorkspace(filename, atmgrid_filename, verbose=1, plot=True, live_fit=False)
251 >>> lambdas, model, model_err = w.simulate(*w.p)
252 >>> w.plot_fit()
254 .. plot::
255 :include-source:
257 from spectractor.fit.fit_spectrum import SpectrumFitWorkspace
258 file_name = 'tests/data/reduc_20170530_134_spectrum.fits'
259 atmgrid_file_name = file_name.replace('spectrum', 'atmsim')
260 fit_workspace = SpectrumFitWorkspace(file_name, atmgrid_file_name=atmgrid_file_name, verbose=True)
261 A1, A2, ozone, pwv, aerosols, reso, D, shift_x = fit_workspace.p
262 lambdas, model, model_err = fit_workspace.simulation.simulate(A1,A2,ozone, pwv, aerosols, reso, D, shift_x)
263 fit_workspace.lambdas = lambdas
264 fit_workspace.model = model
265 fit_workspace.model_err = model_err
266 fit_workspace.plot_fit()
268 """
269 fig = plt.figure(figsize=(12, 6))
270 ax1 = plt.subplot(222)
271 ax2 = plt.subplot(224)
272 ax3 = plt.subplot(121)
273 A1, A2, ozone, pwv, aerosols, reso, D, shift, B = self.p
274 self.title = f'A1={A1:.3f}, A2={A2:.3f}, PWV={pwv:.3f}, OZ={ozone:.3g}, VAOD={aerosols:.3f},\n ' \
275 f'reso={reso:.2f}pix, D={D:.2f}mm, shift={shift:.2f}pix, B={B:.2g}'
276 # main plot
277 self.plot_spectrum_comparison_simple(ax3, title=self.title, size=0.8)
278 # zoom O2
279 self.plot_spectrum_comparison_simple(ax2, extent=[730, 800], title='Zoom $O_2$', size=0.8)
280 # zoom H2O
281 self.plot_spectrum_comparison_simple(ax1, extent=[870, 1000], title='Zoom $H_2 O$', size=0.8)
282 fig.tight_layout()
283 if self.live_fit: # pragma: no cover
284 plt.draw()
285 plt.pause(1e-8)
286 plt.close()
287 else:
288 if parameters.DISPLAY and parameters.VERBOSE:
289 plt.show()
290 if parameters.PdfPages:
291 parameters.PdfPages.savefig()
292 if parameters.SAVE:
293 figname = self.filename.replace('.fits', '_bestfit.pdf')
294 self.my_logger.info(f'Save figure {figname}.')
295 fig.savefig(figname, dpi=100, bbox_inches='tight')
297 def decontaminate_order2(self): # pragma: no cover
298 lambdas = self.spectrum.lambdas
299 lambdas_order2 = self.simulation.lambdas_order2
300 A1, A2, ozone, pwv, aerosols, reso, D, shift, B = self.p
301 lambdas_binwidths_order2 = np.gradient(lambdas_order2)
302 lambdas_binwidths = np.gradient(lambdas)
303 sim_conv = interp1d(lambdas, self.model * lambdas, kind="linear", bounds_error=False, fill_value=(0, 0))
304 err_conv = interp1d(lambdas, self.model_err * lambdas, kind="linear", bounds_error=False, fill_value=(0, 0))
305 spectrum_order2 = sim_conv(lambdas_order2) * lambdas_binwidths_order2 / lambdas_binwidths
306 err_order2 = err_conv(lambdas_order2) * lambdas_binwidths_order2 / lambdas_binwidths
307 self.model = (sim_conv(lambdas) - A2 * spectrum_order2) / lambdas
308 self.model_err = (err_conv(lambdas) - A2 * err_order2) / lambdas
310 def get_truth_without_order2(self): # pragma: no cover
311 lambdas, model, model_err = self.simulation.simulate(1., 0., self.ozone, self.pwv, self.aerosols, self.reso,
312 self.D, self.shift_x)
313 self.lambdas_truth = lambdas
314 self.amplitude_truth = model
317def lnprob_spectrum(p): # pragma: no cover
318 """Logarithmic likelihood function to maximize in MCMC exploration.
320 Parameters
321 ----------
322 p: array_like
323 Array of SpectrumFitWorkspace parameters.
325 Returns
326 -------
327 lp: float
328 Log of the likelihood function.
330 """
331 global w
332 lp = w.lnprior(p)
333 if not np.isfinite(lp):
334 return -1e20
335 return lp + w.lnlike(p)
338def run_spectrum_minimisation(fit_workspace, method="newton"):
339 """Interface function to fit spectrum simulation parameters to data.
341 Parameters
342 ----------
343 fit_workspace: SpectrumFitWorkspace
344 An instance of the SpectrogramFitWorkspace class.
345 method: str, optional
346 Fitting method (default: 'newton').
348 Examples
349 --------
351 >>> filename = 'tests/data/sim_20170530_134_spectrum.fits'
352 >>> atmgrid_filename = filename.replace('sim', 'reduc').replace('spectrum', 'atmsim')
353 >>> load_config("config/ctio.ini")
354 >>> w = SpectrumFitWorkspace(filename, atmgrid_file_name=atmgrid_filename, verbose=1, plot=True, live_fit=False)
355 >>> parameters.VERBOSE = True
356 >>> run_spectrum_minimisation(w, method="newton")
358 """
359 my_logger = set_logger(__name__)
360 guess = np.asarray(fit_workspace.p)
361 if method != "newton":
362 run_minimisation(fit_workspace, method=method)
363 else:
364 # fit_workspace.simulation.fast_sim = True
365 # costs = np.array([fit_workspace.chisq(guess)])
366 # if parameters.DISPLAY and (parameters.DEBUG or fit_workspace.live_fit):
367 # fit_workspace.plot_fit()
368 # params_table = np.array([guess])
369 my_logger.info(f"\n\tStart guess: {guess}\n\twith {fit_workspace.input_labels}")
370 epsilon = 1e-4 * guess
371 epsilon[epsilon == 0] = 1e-4
372 epsilon[-1] = 0.001 * np.max(fit_workspace.data)
374 # fit_workspace.simulation.fast_sim = True
375 # fit_workspace.simulation.fix_psf_cube = False
376 # run_minimisation_sigma_clipping(fit_workspace, method="newton", epsilon=epsilon, fix=fit_workspace.fixed,
377 # xtol=1e-4, ftol=1 / fit_workspace.data.size, sigma_clip=10, niter_clip=3,
378 # verbose=False)
380 fit_workspace.simulation.fast_sim = False
381 fit_workspace.fixed[0] = True
382 run_minimisation_sigma_clipping(fit_workspace, method="newton", epsilon=epsilon, fix=fit_workspace.fixed,
383 xtol=1e-6, ftol=1 / fit_workspace.data.size, sigma_clip=20, niter_clip=3,
384 verbose=False)
385 fit_workspace.fixed[0] = False
386 run_minimisation_sigma_clipping(fit_workspace, method="newton", epsilon=epsilon, fix=fit_workspace.fixed,
387 xtol=1e-6, ftol=1 / fit_workspace.data.size, sigma_clip=20, niter_clip=3,
388 verbose=False)
390 parameters.SAVE = True
391 ipar = np.array(np.where(np.array(fit_workspace.fixed).astype(int) == 0)[0])
392 fit_workspace.plot_correlation_matrix(ipar)
393 fit_workspace.plot_fit()
394 if fit_workspace.filename != "":
395 header = f"{fit_workspace.spectrum.date_obs}\nchi2: {fit_workspace.costs[-1] / fit_workspace.data.size}"
396 fit_workspace.save_parameters_summary(ipar, header=header)
397 # save_gradient_descent(fit_workspace, costs, params_table)
398 parameters.SAVE = False
401if __name__ == "__main__": 401 ↛ 402line 401 didn't jump to line 402, because the condition on line 401 was never true
402 from argparse import ArgumentParser
403 from spectractor.config import load_config
404 from spectractor.fit.fitter import run_minimisation
406 parser = ArgumentParser()
407 parser.add_argument(dest="input", metavar='path', default=["tests/data/reduc_20170530_134_spectrum.fits"],
408 help="Input fits file name. It can be a list separated by spaces, or it can use * as wildcard.",
409 nargs='*')
410 parser.add_argument("-d", "--debug", dest="debug", action="store_true",
411 help="Enter debug mode (more verbose and plots).", default=True)
412 parser.add_argument("-v", "--verbose", dest="verbose", action="store_true",
413 help="Enter verbose (print more stuff).", default=False)
414 parser.add_argument("-o", "--output_directory", dest="output_directory", default="outputs/",
415 help="Write results in given output directory (default: ./outputs/).")
416 parser.add_argument("-l", "--logbook", dest="logbook", default="ctiofulllogbook_jun2017_v5.csv",
417 help="CSV logbook file. (default: ctiofulllogbook_jun2017_v5.csv).")
418 parser.add_argument("-c", "--config", dest="config", default="config/ctio.ini",
419 help="INI config file. (default: config.ctio.ini).")
420 args = parser.parse_args()
422 parameters.VERBOSE = args.verbose
423 if args.debug:
424 parameters.DEBUG = True
425 parameters.VERBOSE = True
427 file_names = args.input
429 load_config(args.config)
431 filenames = ['outputs/sim_20170530_134_spectrum.fits']
432 filenames = [
433 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_104_spectrum.fits',
434 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_109_spectrum.fits',
435 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_114_spectrum.fits',
436 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_119_spectrum.fits',
437 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_124_spectrum.fits',
438 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_129_spectrum.fits',
439 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_134_spectrum.fits',
440 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_139_spectrum.fits',
441 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_144_spectrum.fits',
442 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_149_spectrum.fits',
443 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_154_spectrum.fits',
444 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_159_spectrum.fits',
445 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_164_spectrum.fits',
446 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_169_spectrum.fits',
447 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_174_spectrum.fits',
448 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_179_spectrum.fits',
449 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_184_spectrum.fits',
450 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_189_spectrum.fits',
451 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_194_spectrum.fits',
452 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_199_spectrum.fits']
453 params = []
454 chisqs = []
455 filenames = ['outputs/reduc_20170530_176_spectrum.fits']
456 # filenames = ['../test_176_Moffat4/reduc_20170530_176_spectrum.fits']
457 # filenames = ['../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_176_spectrum.fits']
458 # filenames = ['../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_061_spectrum.fits',
459 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_066_spectrum.fits',
460 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_071_spectrum.fits',
461 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_076_spectrum.fits',
462 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_081_spectrum.fits',
463 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_086_spectrum.fits',
464 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_091_spectrum.fits',
465 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_096_spectrum.fits',
466 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_101_spectrum.fits',
467 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_106_spectrum.fits',
468 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_111_spectrum.fits',
469 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_116_spectrum.fits',
470 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_121_spectrum.fits',
471 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_126_spectrum.fits',
472 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_131_spectrum.fits',
473 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_136_spectrum.fits',
474 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_141_spectrum.fits',
475 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_146_spectrum.fits',
476 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_151_spectrum.fits',
477 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_156_spectrum.fits',
478 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_161_spectrum.fits',
479 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_166_spectrum.fits',
480 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_171_spectrum.fits',
481 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_176_spectrum.fits',
482 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_181_spectrum.fits',
483 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_186_spectrum.fits',
484 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_191_spectrum.fits',
485 # '../CTIODataJune2017_reduced_RG715_v2_prod7.2/data_30may17_A2=0.1/reduc_20170530_196_spectrum.fits']
488 for filename in filenames:
489 atmgrid_filename = filename.replace('sim', 'reduc').replace('spectrum', 'atmsim')
491 w = SpectrumFitWorkspace(filename, atmgrid_file_name=atmgrid_filename, nsteps=1000,
492 burnin=200, nbins=10, verbose=1, plot=True, live_fit=False)
493 run_spectrum_minimisation(w, method="newton")
494 params.append(w.p)
495 chisqs.append(w.costs[-1])
496 params = np.asarray(params).T
498 # fig, ax = plt.subplots(1, len(params))
499 # for ip, p in enumerate(params):
500 # print(f"{w.input_labels[ip]}:", np.mean(p), np.std(p))
501 # ax[ip].plot(p, label=f"{w.input_labels[ip]}")
502 # ax[ip].grid()
503 # ax[ip].legend()
504 # plt.show()
506 # w.decontaminate_order2()
507 # fit_workspace.simulate(*fit_workspace.p)
508 # fit_workspace.plot_fit()
509 # run_emcee(fit_workspace, ln=lnprob_spectrum)
510 # fit_workspace.analyze_chains()