Coverage for tests/test_fullchain.py: 23%
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from numpy.testing import run_module_suite
2from scipy.interpolate import interp1d
4from spectractor import parameters
5from spectractor.extractor.images import Image
6from spectractor.extractor.spectrum import Spectrum
7from spectractor.extractor.extractor import Spectractor
8from spectractor.logbook import LogBook
9from spectractor.config import load_config
10from spectractor.simulation.image_simulation import ImageSim
11from spectractor.tools import plot_spectrum_simple
12from spectractor.fit.fit_spectrum import SpectrumFitWorkspace, run_spectrum_minimisation
13from spectractor.fit.fit_spectrogram import SpectrogramFitWorkspace, run_spectrogram_minimisation
14import os
15import numpy as np
16import matplotlib.pyplot as plt
17import unittest
19PSF_POLY_ORDER = 2
20PSF_POLY_PARAMS_TRUTH = [1, 0, 0,
21 0, 0, 0,
22 3, 2, 0,
23 2, 0, 0,
24 1e6]
25A1_T = 1
26A2_T = 1
29def plot_residuals(spectrum, lambdas_truth, amplitude_truth):
30 """
32 Parameters
33 ----------
34 spectrum
35 lambdas_truth
36 amplitude_truth
38 Examples
39 --------
41 >>> from spectractor.extractor.spectrum import Spectrum
42 >>> image = Image("./tests/data/sim_20170530_134.fits")
43 >>> spectrum = Spectrum("./tests/data/sim_20170530_134_spectrum.fits")
44 >>> lambdas_truth = np.fromstring(image.header['LBDAS_T'][1:-1], sep=' ')
45 >>> amplitude_truth = np.fromstring(image.header['AMPLIS_T'][1:-1], sep=' ', dtype=float)[:lambdas_truth.size]
46 >>> plot_residuals(spectrum, lambdas_truth, amplitude_truth) #doctest: +ELLIPSIS
47 array([...
48 """
49 fig, ax = plt.subplots(2, 1, figsize=(8, 6), sharex="all", gridspec_kw={'height_ratios': [3, 1]})
50 plot_spectrum_simple(ax[0], spectrum.lambdas, spectrum.data, data_err=spectrum.err, label="Fit",
51 units=spectrum.units)
52 # spectrum.lines.plot_atomic_lines(ax[0], fontsize=12, force=True)
53 ax[0].plot(lambdas_truth, amplitude_truth, label="Truth")
54 # transverse_sum = np.mean((spectrum.spectrogram-spectrum.spectrogram_bgd)*spectrum.expo
55 # /(parameters.FLAM_TO_ADURATE*spectrum.lambdas*spectrum.lambdas_binwidths), axis=0)
56 # transverse_sum *= np.max(spectrum.data)/np.max(transverse_sum)
57 # ax[0].plot(spectrum.lambdas, transverse_sum, label="Transverse sum")
58 ax[0].set_ylabel(f"Spectrum [{spectrum.units}]")
59 ax[0].legend()
60 amplitude_truth_interp = interp1d(lambdas_truth, amplitude_truth, kind='cubic',
61 fill_value=0, bounds_error=False)(spectrum.lambdas)
62 residuals = (spectrum.data - amplitude_truth_interp) / spectrum.err
63 ax[1].errorbar(spectrum.lambdas, residuals, yerr=np.ones_like(spectrum.data), label="Fit", fmt="r.")
64 ax[1].set_ylabel(f"Residuals")
65 ax[1].set_xlabel(r"$\lambda$ [nm]")
66 ax[1].grid()
67 ax[1].legend()
68 ax[1].text(0.05, 0.05, f'mean={np.mean(residuals):.3g}\nstd={np.std(residuals):.3g}',
69 horizontalalignment='left', verticalalignment='bottom',
70 color='black', transform=ax[1].transAxes)
71 fig.tight_layout()
72 fig.subplots_adjust(wspace=0, hspace=0)
73 plt.show()
74 return residuals
77def make_image():
78 spectrum_filename = "./tests/data/reduc_20170530_134_spectrum.fits"
79 image_filename = "./tests/data/reduc_20170530_134.fits"
80 # spectrum_filename = "../CTIODataJune2017_reduced_RG715_v2_prod7.4/data_30may17_A2=0.1/reduc_20170530_176_spectrum.fits"
81 # image_filename = "../CTIODataJune2017_reduced_RG715_v2_prod7.3/data_30may17_A2=0.1/reduc_20170530_176.fits"
82 ImageSim(image_filename, spectrum_filename, "./tests/data/", A1=A1_T, A2=A2_T,
83 psf_poly_params=PSF_POLY_PARAMS_TRUTH, with_stars=True, with_rotation=True)
86def fullchain_run(sim_image="./tests/data/sim_20170530_134.fits"):
87 # load test and make image simulation
88 load_config("./config/ctio.ini")
89 if not os.path.isfile(sim_image):
90 make_image()
91 image = Image(sim_image)
92 lambdas_truth = np.fromstring(image.header['LBDAS_T'][1:-1], sep=' ')
93 amplitude_truth = np.fromstring(image.header['AMPLIS_T'][1:-1], sep=' ', dtype=float)
94 parameters.AMPLITUDE_TRUTH = np.copy(amplitude_truth)
95 parameters.LAMBDA_TRUTH = np.copy(lambdas_truth)
97 # extractor
98 tag = sim_image.split('/')[-1]
99 tag = tag.replace('sim_', 'reduc_')
100 logbook = LogBook(logbook="./ctiofulllogbook_jun2017_v5.csv")
101 disperser_label, target, xpos, ypos = logbook.search_for_image(tag)
102 parameters.PSF_POLY_ORDER = PSF_POLY_ORDER
103 spectrum = Spectractor(sim_image, "./tests/data", guess=[xpos, ypos], target_label=target,
104 disperser_label=disperser_label)
105 # spectrum = Spectrum("./tests/data/sim_20170530_134_spectrum.fits")
106 # spectrum = Spectrum("./tests/data/sim_20170530_176_spectrum.fits")
108 # tests
109 residuals = plot_residuals(spectrum, lambdas_truth, amplitude_truth)
111 spectrum.my_logger.warning(f"\n\tQuantities to test:"
112 f"\n\t\tspectrum.header['X0_T']={spectrum.header['X0_T']:.5g} vs {spectrum.x0[0]:.5g}"
113 f"\n\t\tspectrum.header['Y0_T']={spectrum.header['Y0_T']:.5g} vs {spectrum.x0[1]:.5g}"
114 f"\n\t\tspectrum.header['ROT_T']={spectrum.header['ROT_T']:.5g} "
115 f"vs {spectrum.rotation_angle:.5g}"
116 f"\n\t\tspectrum.header['BKGD_LEV']={spectrum.header['BKGD_LEV']:.5g} "
117 f"vs {np.mean(spectrum.spectrogram_bgd):.5g}"
118 f"\n\t\tspectrum.header['D2CCD_T']={spectrum.header['D2CCD_T']:.5g} "
119 f"vs {spectrum.disperser.D:.5g}"
120 f"\n\t\tspectrum.header['A2_FIT']={spectrum.header['A2_FIT']:.5g} vs {A2_T:.5g}"
121 f"\n\t\tspectrum.header['CHI2_FIT']={spectrum.header['CHI2_FIT']:.4g}"
122 f"\n\t\tspectrum.chromatic_psf.poly_params="
123 f"{spectrum.chromatic_psf.poly_params[spectrum.chromatic_psf.Nx + 2 * (PSF_POLY_ORDER + 1):-1]}"
124 f" vs {PSF_POLY_PARAMS_TRUTH[2 * (PSF_POLY_ORDER + 1):-1]}"
125 f"\n\t\tresiduals wrt truth: mean={np.mean(residuals[100:-100]):.5g}, "
126 f"std={np.std(residuals[100:-100]):.5g}")
127 assert np.isclose(float(spectrum.header['X0_T']), spectrum.x0[0], atol=0.2)
128 assert np.isclose(float(spectrum.header['Y0_T']), spectrum.x0[1], atol=0.5)
129 assert np.isclose(float(spectrum.header['ROT_T']), spectrum.rotation_angle,
130 atol=180 / np.pi * 1 / parameters.CCD_IMSIZE)
131 assert np.isclose(float(spectrum.header['BKGD_LEV']), np.mean(spectrum.spectrogram_bgd), rtol=1e-2)
132 assert np.isclose(float(spectrum.header['D2CCD_T']), spectrum.disperser.D, atol=0.1)
133 assert float(spectrum.header['CHI2_FIT']) < 0.65
134 assert np.all(
135 np.isclose(spectrum.chromatic_psf.poly_params[spectrum.chromatic_psf.Nx + 2 * (PSF_POLY_ORDER + 1):-1],
136 np.array(PSF_POLY_PARAMS_TRUTH)[2 * (PSF_POLY_ORDER + 1):-1], rtol=0.1, atol=0.1))
137 assert np.abs(np.mean(residuals[100:-100])) < 0.25
138 assert np.std(residuals[100:-100]) < 2
139 spectrum_file_name = "./tests/data/sim_20170530_134_spectrum.fits"
140 # spectrum_file_name = "./tests/data/sim_20170530_176_spectrum.fits"
141 assert os.path.isfile(spectrum_file_name)
142 spectrum = Spectrum(spectrum_file_name)
143 atmgrid_filename = sim_image.replace('sim', 'reduc').replace('.fits', '_atmsim.fits')
144 assert os.path.isfile(atmgrid_filename)
146 w = SpectrumFitWorkspace(spectrum_file_name, atmgrid_file_name=atmgrid_filename, nsteps=1000,
147 burnin=200, nbins=10, verbose=1, plot=True, live_fit=False)
148 run_spectrum_minimisation(w, method="newton")
149 nsigma = 5
150 labels = ["OZONE_T", "PWV_T", "VAOD_T"]
151 indices = [2, 3, 4]
152 assert w.costs[-1] / w.data.size < 0.9
153 for i, l in zip(indices, labels):
154 spectrum.my_logger.info(f"Test {l} best-fit {w.p[i]:.3f}+/-{np.sqrt(w.cov[i, i]):.3f} "
155 f"vs {spectrum.header[l]:.3f} at {nsigma}sigma level: "
156 f"{np.abs(w.p[i] - spectrum.header[l]) / np.sqrt(w.cov[i, i]) < nsigma}")
157 assert np.abs(w.p[i] - spectrum.header[l]) / np.sqrt(w.cov[i, i]) < nsigma
158 assert np.abs(w.p[1]) / np.sqrt(w.cov[1, 1]) < nsigma # A2
159 assert np.isclose(w.p[6], spectrum.header["D2CCD_T"], atol=parameters.DISTANCE2CCD_ERR) # D2CCD
160 assert np.isclose(np.abs(w.p[7]), 0, atol=parameters.PIXSHIFT_PRIOR) # pixshift
161 assert np.isclose(np.abs(w.p[8]), 0, atol=1e-3) # B
163 parameters.DEBUG = False
164 w = SpectrogramFitWorkspace(spectrum_file_name, atmgrid_file_name=atmgrid_filename, nsteps=1000,
165 burnin=2, nbins=10, verbose=1, plot=True, live_fit=False)
166 run_spectrogram_minimisation(w, method="newton")
167 nsigma = 5
168 labels = ["A1_T", "A2_T", "OZONE_T", "PWV_T", "VAOD_T"]
169 indices = [0, 1, 2, 3, 4, 5]
170 A1, A2, ozone, pwv, aerosols, D, shift_x, shift_y, shift_t, B, *psf_poly_params = w.p
171 assert w.costs[-1] / w.data.size < 0.65
172 for i, l in zip(indices, labels):
173 spectrum.my_logger.info(f"Test {l} best-fit {w.p[i]:.3f}+/-{np.sqrt(w.cov[i, i]):.3f} "
174 f"vs {spectrum.header[l]:.3f} at {nsigma}sigma level: "
175 f"{np.abs(w.p[i] - spectrum.header[l]) / np.sqrt(w.cov[i, i]) < nsigma}")
176 assert np.abs(w.p[i] - spectrum.header[l]) / np.sqrt(w.cov[i, i]) < nsigma
177 assert np.isclose(shift_y, 0, atol=parameters.PIXSHIFT_PRIOR) # shift_y
178 assert np.isclose(B, 1, atol=1e-3) # B
179 assert np.all(np.isclose(psf_poly_params[2 * (PSF_POLY_ORDER + 1):-1],
180 np.array(PSF_POLY_PARAMS_TRUTH)[2 * (PSF_POLY_ORDER + 1):-1], rtol=0.1, atol=0.1))
183# TODO: DM-33441 Fix broken spectractor tests
184@unittest.skip('Skipping due to broken test (index out of range error)')
185def test_fullchain():
186 parameters.VERBOSE = True
187 parameters.DEBUG = True
188 sim_image = "./tests/data/sim_20170530_134.fits"
189 fullchain_run(sim_image=sim_image)
192if __name__ == "__main__": 192 ↛ 193line 192 didn't jump to line 193, because the condition on line 192 was never true
193 run_module_suite()