Coverage for spectractor/simulation/simulator.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 os
2import copy
3import numpy as np
4import matplotlib.pyplot as plt
5from astropy.io import fits
7from scipy.interpolate import interp1d
9from spectractor.extractor.spectrum import Spectrum
10from spectractor.extractor.dispersers import Grating, Hologram
11from spectractor.extractor.targets import Target
12from spectractor.extractor.psf import load_PSF
13from spectractor.tools import fftconvolve_gaussian, ensure_dir
14from spectractor.config import set_logger
15from spectractor.simulation.throughput import TelescopeTransmission
16from spectractor.simulation.atmosphere import Atmosphere, AtmosphereGrid
17import spectractor.parameters as parameters
18from spectractor.simulation.adr import adr_calib, flip_and_rotate_adr_to_image_xy_coordinates
21class SpectrumSimulation(Spectrum):
23 def __init__(self, spectrum, atmosphere, telescope, disperser, fast_sim=True):
24 """Class to simulate cross spectrum.
26 Parameters
27 ----------
28 spectrum: Spectrum
29 Spectrum instance to load main properties before simulation.
30 atmosphere: Atmosphere
31 Atmosphere or AtmosphereGrid instance to make the atmospheric simulation.
32 telescope: TelescopeTransmission
33 Telescope transmission.
34 disperser: Grating
35 Disperser instance.
36 fast_sim: bool, optional
37 If True, do a fast simulation without integrating within the wavelength bins (default: True).
39 Examples
40 --------
41 >>> spectrum, telescope, disperser, target = SimulatorInit("./tests/data/reduc_20170530_134_spectrum.fits")
42 >>> atmosphere = Atmosphere(airmass=1.2, pressure=800, temperature=10)
43 >>> sim = SpectrumSimulation(spectrum, atmosphere, telescope, disperser, fast_sim=True)
45 """
46 Spectrum.__init__(self)
47 for k, v in list(spectrum.__dict__.items()):
48 self.__dict__[k] = copy.copy(v)
49 self.my_logger = set_logger(self.__class__.__name__)
50 self.disperser = disperser
51 self.telescope = telescope
52 self.atmosphere = atmosphere
53 self.fast_sim = fast_sim
54 # save original pixel distances to zero order
55 # self.disperser.grating_lambda_to_pixel(self.lambdas, x0=self.x0, order=1)
56 # now reset data
57 self.lambdas = None
58 self.lambdas_order2 = None
59 self.err = None
60 self.model = lambda x: np.zeros_like(x)
61 self.model_err = lambda x: np.zeros_like(x)
62 lbdas_sed = self.target.wavelengths[0]
63 sub = np.where((lbdas_sed > parameters.LAMBDA_MIN) & (lbdas_sed < parameters.LAMBDA_MAX))
64 self.lambdas_step = min(parameters.LAMBDA_STEP, np.min(lbdas_sed[sub]))
66 def simulate_without_atmosphere(self, lambdas):
67 """Compute the spectrum of an object and its uncertainties
68 after its transmission throught the instrument except the atmosphere.
69 The units remains the ones of the Target instance.
71 Parameters
72 ----------
73 lambdas: array_like
74 The wavelength array in nm
76 Returns
77 -------
78 spectrum: array_like
79 The spectrum in Target units.
80 spectrum_err: array_like
81 The spectrum uncertainties in Target units.
82 """
83 self.lambdas = lambdas
84 self.lambdas_binwidths = np.gradient(lambdas)
85 self.data = self.disperser.transmission(lambdas)
86 self.data *= self.telescope.transmission(lambdas)
87 self.data *= self.target.sed(lambdas)
88 self.err = np.zeros_like(self.data)
89 idx = np.where(self.telescope.transmission(lambdas) > 0)[0]
90 self.err[idx] = self.telescope.transmission_err(lambdas)[idx] / self.telescope.transmission(lambdas)[idx]
91 self.err[idx] *= self.data[idx]
92 idx = np.where(self.telescope.transmission(lambdas) <= 0)[0]
93 self.err[idx] = 1e6 * np.max(self.err)
94 return self.data, self.err
96 def simulate(self, A1=1.0, A2=0., ozone=300, pwv=5, aerosols=0.05, reso=0.,
97 D=parameters.DISTANCE2CCD, shift_x=0., B=0.):
98 """Simulate the cross spectrum of an object and its uncertainties
99 after its transmission throught the instrument and the atmosphere.
101 Parameters
102 ----------
103 A1: float
104 Global amplitude of the spectrum (default: 1).
105 A2: float
106 Relative amplitude of the order 2 spectrum contamination (default: 0).
107 ozone: float
108 Ozone quantity in Dobson
109 pwv: float
110 Precipitable Water Vapor quantity in mm
111 aerosols: float
112 VAOD Vertical Aerosols Optical Depth
113 reso: float
114 Gaussian kernel size for the convolution (default: 0).
115 D: float
116 Distance between the CCD and the disperser in mm (default: parameters.DISTANCE2CCD)
117 shift_x: float
118 Shift in pixels of the order 0 position estimate (default: 0).
119 B: float
120 Amplitude level for the background (default: 0).
122 Returns
123 -------
124 lambdas: array_like
125 The wavelength array in nm used for the interpolation.
126 spectrum: array_like
127 The spectrum interpolated function in Target units.
128 spectrum_err: array_like
129 The spectrum uncertainties interpolated function in Target units.
131 Examples
132 --------
133 >>> spectrum, telescope, disperser, target = SimulatorInit("./tests/data/reduc_20170530_134_spectrum.fits")
134 >>> atmosphere = AtmosphereGrid(filename="./tests/data/reduc_20170530_134_atmsim.fits")
135 >>> sim = SpectrumSimulation(spectrum, atmosphere, telescope, disperser, fast_sim=True)
136 >>> lambdas, model, model_err = sim.simulate(A1=1, A2=1, ozone=300, pwv=5, aerosols=0.05, reso=0.,
137 ... D=parameters.DISTANCE2CCD, shift_x=0., B=0.)
138 >>> sim.plot_spectrum()
140 .. doctest::
141 :hide:
143 >>> assert np.sum(lambdas) > 0
144 >>> assert np.sum(model) > 0
145 >>> assert np.sum(model) < 1e-10
146 >>> assert np.sum(sim.data_order2) > 0
147 >>> assert np.sum(sim.data_order2) < 1e-11
149 """
150 # find lambdas including ADR effect
151 new_x0 = [self.x0[0] - shift_x, self.x0[1]]
152 self.disperser.D = D
153 distance = self.chromatic_psf.get_algebraic_distance_along_dispersion_axis(shift_x=shift_x)
154 lambdas = self.disperser.grating_pixel_to_lambda(distance, x0=new_x0, order=1)
155 lambdas_order2 = self.disperser.grating_pixel_to_lambda(distance, x0=new_x0, order=2)
156 # lambda_ref = self.lambda_ref
157 # adr_ra, adr_dec = adr_calib(lambdas, self.adr_params, parameters.OBS_LATITUDE, lambda_ref=lambda_ref)
158 # adr_u, _ = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec,
159 # dispersion_axis_angle=self.rotation_angle)
160 # distance_order1 = distance - adr_u
161 # adr_ra, adr_dec = adr_calib(lambdas_order2, self.adr_params, parameters.OBS_LATITUDE, lambda_ref=lambda_ref)
162 # adr_u, _ = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec,
163 # dispersion_axis_angle=self.rotation_angle)
164 # distance_order2 = distance - adr_u
165 # lambdas = self.disperser.grating_pixel_to_lambda(distance_order1, x0=new_x0, order=1)
166 # lambdas_order2 = self.disperser.grating_pixel_to_lambda(distance_order2, x0=new_x0, order=2)
167 self.lambdas = lambdas
168 self.lambdas_order2 = lambdas_order2
169 atmospheric_transmission = self.atmosphere.simulate(ozone, pwv, aerosols)
170 if self.fast_sim:
171 self.data, self.err = self.simulate_without_atmosphere(lambdas)
172 self.data *= A1 * atmospheric_transmission(lambdas)
173 self.err *= A1 * atmospheric_transmission(lambdas)
174 else:
175 def integrand(lbda):
176 return self.target.sed(lbda) * self.telescope.transmission(lbda) \
177 * self.disperser.transmission(lbda) * atmospheric_transmission(lbda)
179 self.data = np.zeros_like(lambdas)
180 self.err = np.zeros_like(lambdas)
181 for i in range(len(lambdas) - 1):
182 lbdas = np.arange(lambdas[i], lambdas[i + 1], self.lambdas_step)
183 self.data[i] = A1 * np.mean(integrand(lbdas))
184 # self.data[i] = A1 * quad(integrand, lambdas[i], lambdas[i + 1])[0]
185 self.data[-1] = self.data[-2]
186 # self.data /= np.gradient(lambdas)
187 telescope_transmission = self.telescope.transmission(lambdas)
188 idx = telescope_transmission > 0
189 self.err[idx] = self.data[idx] * self.telescope.transmission_err(lambdas)[idx] / telescope_transmission[idx]
190 idx = telescope_transmission <= 0
191 self.err[idx] = 1e6 * np.max(self.err)
192 # Now add the systematics
193 if reso > 0.1:
194 self.data = fftconvolve_gaussian(self.data, reso)
195 # self.err = np.sqrt(np.abs(fftconvolve_gaussian(self.err ** 2, reso)))
196 if A2 > 0:
197 lambdas_binwidths_order2 = np.gradient(lambdas_order2)
198 sim_conv = interp1d(lambdas, self.data * lambdas, kind="linear", bounds_error=False, fill_value=(0, 0))
199 err_conv = interp1d(lambdas, self.err * lambdas, kind="linear", bounds_error=False, fill_value=(0, 0))
200 spectrum_order2 = self.disperser.ratio_order_2over1(lambdas_order2) * sim_conv(lambdas_order2) \
201 * lambdas_binwidths_order2 / self.lambdas_binwidths
202 err_order2 = err_conv(lambdas_order2) * lambdas_binwidths_order2 / self.lambdas_binwidths
203 self.data = (sim_conv(lambdas) + A2 * spectrum_order2) / lambdas
204 self.data_order2 = A2 * spectrum_order2 / lambdas
205 self.err = (err_conv(lambdas) + A2 * err_order2) / lambdas
206 if B != 0:
207 self.data += B / (lambdas * np.gradient(lambdas))
208 if np.any(self.err <= 0):
209 min_positive = np.min(self.err[self.err > 0])
210 self.err[np.isclose(self.err, 0., atol=0.01 * min_positive)] = min_positive
211 return self.lambdas, self.data, self.err
214class SpectrogramModel(Spectrum):
216 def __init__(self, spectrum, atmosphere, telescope, disperser, with_background=True, fast_sim=True,
217 full_image=False):
218 """Class to simulate a spectrogram.
220 Parameters
221 ----------
222 spectrum: Spectrum
223 Spectrum instance to load main properties before simulation.
224 atmosphere: Atmosphere
225 Atmosphere or AtmosphereGrid instance to make the atmospheric simulation.
226 telescope: TelescopeTransmission
227 Telescope transmission.
228 disperser: Grating
229 Disperser instance.
230 with_background: bool, optional
231 If True, add the background model to the simulated spectrogram (default: True).
232 fast_sim: bool, optional
233 If True, perform a fast simulation of the spectrum without integrated the spectrum
234 in pixel bins (default: True).
235 full_image: bool, optional
236 If True, simulate the spectrogram on the full CCD size,
237 otherwise only the cropped spectrogram (default: False).
239 Examples
240 --------
241 >>> spectrum, telescope, disperser, target = SimulatorInit("./tests/data/reduc_20170530_134_spectrum.fits")
242 >>> atmosphere = Atmosphere(airmass=1.2, pressure=800, temperature=10)
243 >>> sim = SpectrogramModel(spectrum, atmosphere, telescope, disperser, with_background=True, fast_sim=True)
244 """
245 Spectrum.__init__(self)
246 for k, v in list(spectrum.__dict__.items()):
247 self.__dict__[k] = copy.copy(v)
248 self.disperser = disperser
249 self.telescope = telescope
250 self.atmosphere = atmosphere
251 self.true_lambdas = None
252 self.true_spectrum = None
253 self.lambdas = None
254 self.err = None
255 self.model = lambda x, y: np.zeros((x.size, y.size))
256 self.psf = load_PSF(psf_type=parameters.PSF_TYPE)
257 self.profile_params = None
258 self.psf_cube = None
259 self.psf_cube_order2 = None
260 self.fix_psf_cube = False
261 self.fix_atm_sim = False
262 self.atmosphere_sim = None
263 self.fast_sim = fast_sim
264 self.with_background = with_background
265 self.full_image = full_image
266 if self.full_image:
267 self.Nx = parameters.CCD_IMSIZE
268 self.Ny = self.spectrogram_Ny # too long if =parameters.CCD_IMSIZE
269 self.r0 = self.x0[0] + 1j * self.spectrogram_y0
270 else:
271 self.Nx = self.spectrogram_Nx
272 self.Ny = self.spectrogram_Ny
273 self.r0 = self.spectrogram_x0 + 1j * self.spectrogram_y0
274 lbdas_sed = self.target.wavelengths[0]
275 sub = np.where((lbdas_sed > parameters.LAMBDA_MIN) & (lbdas_sed < parameters.LAMBDA_MAX))
276 self.lambdas_step = min(parameters.LAMBDA_STEP, np.min(lbdas_sed[sub]))
277 self.yy, self.xx = np.mgrid[:self.Ny, :self.Nx]
278 self.pixels = np.asarray([self.xx, self.yy])
280 def set_true_spectrum(self, lambdas, ozone, pwv, aerosols, shift_t=0.):
281 atmosphere = self.atmosphere.simulate(ozone, pwv, aerosols)
282 spectrum = self.target.sed(lambdas)
283 spectrum *= self.disperser.transmission(lambdas - shift_t)
284 spectrum *= self.telescope.transmission(lambdas - shift_t)
285 spectrum *= atmosphere(lambdas)
286 self.true_spectrum = spectrum
287 self.true_lambdas = lambdas
288 return spectrum
290 def simulate_spectrum(self, lambdas, atmosphere, shift_t=0.):
291 """
292 Simulate the spectrum of the object and return the result in Target units.
294 Parameters
295 ----------
296 lambdas: array_like
297 The wavelength array in nm.
298 atmosphere: callable
299 A callable function of the atmospheric transmission.
300 shift_t: float
301 Shift of the transmission in nm (default: 0).
303 Returns
304 -------
305 spectrum: array_like
306 The spectrum array in ADU/s units.
307 spectrum_err: array_like
308 The spectrum uncertainty array in ADU/s units.
310 """
311 spectrum = np.zeros_like(lambdas)
312 telescope_transmission = self.telescope.transmission(lambdas - shift_t)
313 if self.fast_sim:
314 spectrum = self.target.sed(lambdas)
315 spectrum *= self.disperser.transmission(lambdas - shift_t)
316 spectrum *= telescope_transmission
317 spectrum *= atmosphere(lambdas)
318 spectrum *= parameters.FLAM_TO_ADURATE * lambdas * np.gradient(lambdas)
319 else:
320 def integrand(lbda):
321 return lbda * self.target.sed(lbda) * self.telescope.transmission(lbda - shift_t) \
322 * self.disperser.transmission(lbda - shift_t) * atmosphere(lbda)
324 for i in range(len(lambdas) - 1):
325 # spectrum[i] = parameters.FLAM_TO_ADURATE * quad(integrand, lambdas[i], lambdas[i + 1])[0]
326 lbdas = np.arange(lambdas[i], lambdas[i + 1], self.lambdas_step)
327 spectrum[i] = parameters.FLAM_TO_ADURATE * np.mean(integrand(lbdas)) * (lambdas[i + 1] - lambdas[i])
328 spectrum[-1] = spectrum[-2]
329 spectrum_err = np.zeros_like(spectrum)
330 idx = telescope_transmission > 0
331 spectrum_err[idx] = self.telescope.transmission_err(lambdas)[idx] / telescope_transmission[idx] * spectrum[idx]
332 # idx = telescope_transmission <= 0: not ready yet to be implemented
333 # spectrum_err[idx] = 1e6 * np.max(spectrum_err)
334 return spectrum, spectrum_err
336 def simulate_psf(self, psf_poly_params):
337 profile_params = self.chromatic_psf.from_poly_params_to_profile_params(psf_poly_params, apply_bounds=True)
338 self.chromatic_psf.fill_table_with_profile_params(profile_params)
339 self.chromatic_psf.table['Dy_disp_axis'] = \
340 np.tan(self.rotation_angle * np.pi / 180) * self.chromatic_psf.table['Dx']
341 self.chromatic_psf.table['Dy'] = np.copy(self.chromatic_psf.table['y_c']) - self.r0.imag
342 self.chromatic_psf.profile_params = self.chromatic_psf.from_table_to_profile_params()
343 if False:
344 self.chromatic_psf.plot_summary()
345 return self.chromatic_psf.profile_params
347 def simulate_dispersion(self, D, shift_x, shift_y):
348 # Distance in x and y with respect to the true order 0 position at lambda_ref
349 Dx = np.arange(self.spectrogram_Nx) - self.spectrogram_x0 - shift_x # distance in (x,y) spectrogram frame for column x
350 Dy_disp_axis = np.tan(self.rotation_angle * np.pi / 180) * Dx # disp axis height in spectrogram frame for x
351 distance = np.sqrt(Dx**2 + Dy_disp_axis**2)
353 # Wavelengths using the order 0 shifts (ADR has no impact as it shifts order 0 and order p equally)
354 new_x0 = [self.x0[0] + shift_x, self.x0[1] + shift_y]
355 self.disperser.D = D
356 self.lambdas = self.disperser.grating_pixel_to_lambda(distance, x0=new_x0, order=1)
357 distance_order2 = self.disperser.grating_lambda_to_pixel(self.lambdas, x0=new_x0, order=2)
358 distance_order2 = distance_order2[distance_order2 + self.r0.real < self.Nx + 100] # little margin of 100 pixels
359 Dx_order2 = distance_order2 * np.cos(self.rotation_angle * np.pi / 180)
360 Dy_disp_axis_order2 = distance_order2 * np.sin(self.rotation_angle * np.pi / 180)
361 self.lambdas_order2 = self.disperser.grating_pixel_to_lambda(distance_order2, x0=new_x0, order=2)
362 self.lambdas_binwidths = np.gradient(self.lambdas)
364 # ADR for order 1
365 adr_ra, adr_dec = adr_calib(self.lambdas, self.adr_params, parameters.OBS_LATITUDE, lambda_ref=self.lambda_ref)
366 adr_x, adr_y = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec, dispersion_axis_angle=0)
367 # adr_u, adr_v = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec,
368 # dispersion_axis_angle=self.rotation_angle)
370 # Compute lambdas at pixel column x
371 # lambdas = self.disperser.grating_pixel_to_lambda(distance - 0*adr_u, new_x0, order=1)
372 # Position (not distance) in pixel of wavelength lambda order 1 centroid in the (x,y) spectrogram frame
373 dispersion_law = self.r0 + (Dx + shift_x + adr_x) + 1j * (Dy_disp_axis + adr_y + shift_y)
375 # ADR for order 2
376 adr_ra, adr_dec = adr_calib(self.lambdas_order2, self.adr_params, parameters.OBS_LATITUDE,
377 lambda_ref=self.lambda_ref)
378 adr_x, adr_y = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec, dispersion_axis_angle=0)
379 # adr_u, adr_v = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec,
380 # dispersion_axis_angle=self.rotation_angle)
382 # Compute lambdas at pixel column x
383 # lambdas_order2 = self.disperser.grating_pixel_to_lambda(distance - 0*adr_u, new_x0, order=2)
384 # Position (not distance) in pixel of wavelength lambda order 2 centroid in the (x,y) spectrogram frame
385 dispersion_law_order2 = self.r0 + (Dx_order2 + shift_x + adr_x) + 1j * (Dy_disp_axis_order2 + adr_y + shift_y)
387 # Dx_func = interp1d(lambdas / 2, self.chromatic_psf.table['Dx'], bounds_error=False, fill_value=(0, 0))
388 # Dy_mean_func=interp1d(lambdas/2,self.chromatic_psf.table['Dy_disp_axis'],bounds_error=False,fill_value=(0,0))
389 # dy_func = interp1d(lambdas / 2, self.chromatic_psf.table['Dy'] - self.chromatic_psf.table['Dy_disp_axis'],
390 # bounds_error=False, fill_value=(0, 0))
391 # dispersion_law = r0 + (self.chromatic_psf.table['Dx'] - shift_x) + 1j * (
392 # self.chromatic_psf.table['Dy'] - shift_y)
393 # dispersion_law_order2 = r0 + (Dx_func(lambdas_order2) - shift_x) + 1j * (
394 # Dy_mean_func(lambdas_order2) + dy_func(lambdas_order2) - shift_y)
395 # Dx_func = interp1d(lambdas, self.chromatic_psf.table['Dx'], bounds_error=False, fill_value=(0, 0))
396 # Dy_mean_func=interp1d(lambdas,self.chromatic_psf.table['Dy_dips_axis'],bounds_error=False, fill_value=(0, 0))
398 # dispersion laws from the PSF table
399 # dy_func = interp1d(lambdas, self.chromatic_psf.table['Dy'] - self.chromatic_psf.table['Dy_disp_axis'],
400 # bounds_error=False, fill_value="extrapolate")
401 # dispersion_law = r0 + (self.chromatic_psf.table['Dx'] - shift_x) \
402 # + 1j * (self.chromatic_psf.table['Dy'] - shift_y)
403 # dispersion_law_order2 = dispersion_law + 1j * (dy_func(lambdas_order2) - self.chromatic_psf.table['Dy']
404 # + self.chromatic_psf.table['Dy_disp_axis'])
406 if False:
407 from spectractor.tools import from_lambda_to_colormap
408 plt.plot(self.chromatic_psf.table['Dx'], self.chromatic_psf.table['Dy_disp_axis'], 'k-', label="mean")
409 plt.scatter(dispersion_law.real-self.r0.real, -self.r0.imag + dispersion_law.imag, label="dispersion_law",
410 cmap=from_lambda_to_colormap(self.lambdas), c=self.lambdas)
411 plt.scatter(dispersion_law_order2.real-self.r0.real, -self.r0.imag + dispersion_law_order2.imag,
412 label="dispersion_law_order2",
413 cmap=from_lambda_to_colormap(self.lambdas_order2), c=self.lambdas_order2)
414 plt.title(f"x0={new_x0}")
415 plt.legend()
416 plt.show()
417 if parameters.PdfPages:
418 parameters.PdfPages.savefig()
420 return self.lambdas, self.lambdas_order2, dispersion_law, dispersion_law_order2
422 # @profile
423 def simulate(self, A1=1.0, A2=0., ozone=300, pwv=5, aerosols=0.05, D=parameters.DISTANCE2CCD,
424 shift_x=0., shift_y=0., angle=0., B=1., psf_poly_params=None):
425 """
427 Parameters
428 ----------
429 A1: float
430 Global amplitude of the spectrum (default: 1).
431 A2: float
432 Relative amplitude of the order 2 spectrum contamination (default: 0).
433 ozone: float
434 Ozone quantity in Dobson.
435 pwv: float
436 Precipitable Water Vapor quantity in mm.
437 aerosols: float
438 VAOD Vertical Aerosols Optical Depth.
439 D: float
440 Distance between the CCD and the disperser in mm (default: parameters.DISTANCE2CCD)
441 shift_x: float
442 Shift in pixels along x axis of the order 0 position estimate (default: 0).
443 shift_y: float
444 Shift in pixels along y axis of the order 0 position estimate (default: 0).
445 angle: float
446 Angle of the dispersion axis in degree (default: 0).
447 B: float
448 Amplitude level for the background (default: 0).
449 psf_poly_params: array_like
450 Polynomial parameters describing the PSF dependence in wavelength (default: None).
452 Returns
453 -------
454 lambdas: array_like
455 The wavelength array in nm used for the interpolation.
456 spectrogram: array_like
457 The spectrogram array in ADU/s units.
458 spectrogram_err: array_like
459 The spectrogram uncertainty array in ADU/s units.
461 Example
462 -------
464 >>> spectrum, telescope, disperser, target = SimulatorInit('./tests/data/reduc_20170530_134_spectrum.fits')
465 >>> atmosphere = AtmosphereGrid(filename="./tests/data/reduc_20170530_134_atmsim.fits")
466 >>> psf_poly_params = spectrum.chromatic_psf.from_table_to_poly_params()
467 >>> sim = SpectrogramModel(spectrum, atmosphere, telescope, disperser, with_background=True, fast_sim=True)
468 >>> lambdas, model, model_err = sim.simulate(A2=1, angle=-1.5, psf_poly_params=psf_poly_params)
469 >>> sim.plot_spectrogram()
471 .. doctest::
472 :hide:
474 >>> assert np.sum(lambdas) > 0
475 >>> assert np.sum(model) > 20
476 """
477 import time
478 start = time.time()
479 self.rotation_angle = angle
480 if self.profile_params is None or not self.fix_psf_cube:
481 self.profile_params = self.simulate_psf(psf_poly_params)
482 self.my_logger.debug(f'\n\tAfter psf params: {time.time() - start}')
483 start = time.time()
484 lambdas, lambdas_order2, dispersion_law, dispersion_law_order2 = self.simulate_dispersion(D, shift_x, shift_y)
485 self.chromatic_psf.table["Dx"] = dispersion_law.real - self.r0.real
486 self.chromatic_psf.table["Dy"] = dispersion_law.imag - self.r0.imag
487 self.my_logger.debug(f'\n\tAfter dispersion: {time.time() - start}')
488 start = time.time()
489 if self.atmosphere_sim is None or not self.fix_atm_sim:
490 self.atmosphere_sim = self.atmosphere.simulate(ozone, pwv, aerosols)
491 spectrum, spectrum_err = self.simulate_spectrum(lambdas, self.atmosphere_sim)
492 self.my_logger.debug(f'\n\tAfter spectrum: {time.time() - start}')
493 # Fill the order 1 cube
494 nlbda = dispersion_law.size
495 if self.psf_cube is None or not self.fix_psf_cube:
496 start = time.time()
497 self.psf_cube = np.zeros((nlbda, self.Ny, self.Nx))
498 for i in range(0, nlbda, 1):
499 p = np.array([1, dispersion_law[i].real, dispersion_law[i].imag] + list(self.profile_params[i, 3:]))
500 self.psf_cube[i] = self.psf.evaluate(self.pixels, p=p)
501 self.my_logger.debug(f'\n\tAfter psf cube: {time.time() - start}')
502 start = time.time()
503 ima1 = np.zeros((self.Ny, self.Nx))
504 ima1_err2 = np.zeros((self.Ny, self.Nx))
505 for i in range(0, nlbda, 1):
506 # here spectrum[i] is in ADU/s
507 ima1 += spectrum[i] * self.psf_cube[i]
508 ima1_err2 += (spectrum_err[i] * self.psf_cube[i]) ** 2
509 self.my_logger.debug(f'\n\tAfter build ima1: {time.time() - start}')
511 # Add order 2
512 if A2 > 0.:
513 spectrum_order2, spectrum_order2_err = self.disperser.ratio_order_2over1(lambdas_order2) * \
514 self.simulate_spectrum(lambdas_order2, self.atmosphere_sim)
515 if np.any(np.isnan(spectrum_order2)):
516 spectrum_order2[np.isnan(spectrum_order2)] = 0.
517 nlbda2 = dispersion_law_order2.size
518 if self.psf_cube_order2 is None or not self.fix_psf_cube:
519 start = time.time()
520 self.psf_cube_order2 = np.zeros((nlbda2, self.Ny, self.Nx))
521 # For each A(lambda)=A_x, affect an order 2 PSF with correct position and
522 # same PSF as for the order 1 but at the same position
523 profile_params_order2 = np.copy(self.profile_params)
524 profile_params_order2[:, 0] = 1
525 profile_params_order2[:nlbda2, 1] = dispersion_law_order2.real
526 profile_params_order2[:nlbda2, 2] = dispersion_law_order2.imag
527 distance = np.abs(dispersion_law)
528 distance_order2 = np.abs(dispersion_law_order2)
529 for k in range(3, self.profile_params.shape[1]):
530 profile_params_order2[:nlbda2, k] = interp1d(distance, profile_params_order2[:, k], kind="cubic",
531 fill_value="extrapolate")(distance_order2)
532 for i in range(0, nlbda2, 1):
533 self.psf_cube_order2[i] = self.psf.evaluate(self.pixels, p=profile_params_order2[i, :])
534 self.my_logger.debug(f'\n\tAfter psf cube order 2: {time.time() - start}')
535 start = time.time()
536 ima2 = np.zeros_like(ima1)
537 ima2_err2 = np.zeros_like(ima1)
538 for i in range(0, nlbda2, 1):
539 # here spectrum[i] is in ADU/s
540 ima2 += spectrum_order2[i] * self.psf_cube_order2[i]
541 ima2_err2 += (spectrum_order2_err[i] * self.psf_cube_order2[i]) ** 2
542 # self.data is in ADU/s units here
543 self.data = A1 * (ima1 + A2 * ima2)
544 self.err = np.sqrt(A1*A1*(ima1_err2 + A2*A2*ima2_err2))
545 self.my_logger.debug(f'\n\tAfter build ima2: {time.time() - start}')
546 else:
547 self.data = A1 * ima1
548 self.err = A1 * np.sqrt(ima1_err2)
549 start = time.time()
550 if self.with_background:
551 self.data += B * self.spectrogram_bgd
552 self.my_logger.debug(f'\n\tAfter bgd: {time.time() - start}')
553 if False:
554 fig, ax = plt.subplots(2, 1, sharex="all", figsize=(12, 9))
555 im = ax[0].imshow(self.data, origin='lower')
556 plt.colorbar(im, ax=ax[0], label=self.units)
557 ax[0].set_title('Model')
558 im = ax[1].imshow(self.err, origin='lower')
559 plt.colorbar(im, ax=ax[1], label=self.units)
560 ax[1].set_title('Err')
561 ax[1].set_xlabel('X [pixels]')
562 ax[0].set_ylabel('Y [pixels]')
563 ax[1].set_ylabel('Y [pixels]')
564 ax[0].grid()
565 ax[1].grid()
566 # if self.with_background:
567 # ax[2].plot(np.sum(self.data, axis=0), label="model")
568 # else:
569 # ax[2].plot(np.sum(self.data + self.spectrogram_bgd, axis=0), label="model")
570 # ax[2].plot(np.sum(self.spectrogram, axis=0), label="data")
571 # ax[2].grid()
572 # ax[2].legend()
573 fig.tight_layout()
574 plt.show()
575 if parameters.PdfPages:
576 parameters.PdfPages.savefig()
578 return self.lambdas, self.data, self.err
581class SpectrumSimGrid:
582 """ SpectrumSim class used to store information and methods
583 relative to spectrum simulation.
584 NEED TO ADAPT THIS CLASS TO THE FULL SIMULATION WITH SYSTEMATICS.
585 """
587 # ---------------------------------------------------------------------------
588 def __init__(self, spectrum, atmgrid, telescope, disperser, target, filename=""):
589 """
590 Args:
591 filename (:obj:`str`): path to the image
592 """
593 self.my_logger = set_logger(self.__class__.__name__)
595 self.spectrum = spectrum
596 self.header = spectrum.header
597 self.disperser = disperser
598 self.target = target
599 self.telescope = telescope
601 self.atmgrid = atmgrid
602 self.lambdas = self.atmgrid.atmgrid[0, self.atmgrid.index_atm_data:]
603 self.lambdas_binwidths = np.gradient(self.lambdas)
604 self.spectragrid = None
606 self.filename = ""
607 if filename != "":
608 self.filename = filename
609 self.spectrum.load_spectrum(filename)
611 def compute(self):
612 sim = SpectrumSimulation(self.spectrum, self.atmgrid.atmgrid, self.telescope, self.disperser)
613 # product of all sed and transmissions except atmosphere
614 all_transm, all_transm_err = sim.simulate_without_atmosphere(self.lambdas)
615 # copy atmospheric grid parameters into spectra grid
616 self.spectragrid = np.zeros_like(self.atmgrid.atmgrid)
617 self.spectragrid[0, self.atmgrid.index_atm_data:] = self.lambdas
618 self.spectragrid[:, self.atmgrid.index_atm_count:self.atmgrid.index_atm_data] = \
619 self.atmgrid.atmgrid[:, self.atmgrid.index_atm_count:self.atmgrid.index_atm_data]
620 # Is broadcasting working OK ?
621 self.spectragrid[1:, self.atmgrid.index_atm_data:] = self.atmgrid.atmgrid[1:, self.atmgrid.index_atm_data:]
622 self.spectragrid[1:, self.atmgrid.index_atm_data:] *= all_transm
623 return self.spectragrid
625 def plot_spectra(self):
626 plt.figure()
627 counts = self.spectragrid[1:, self.atmgrid.index_atm_count]
628 for count in counts:
629 plt.plot(self.lambdas, self.spectragrid[int(count), self.atmgrid.index_atm_data:])
630 plt.grid()
631 plt.xlabel(r"$\lambda$ [nm]")
632 plt.ylabel("Flux [ADU/s]")
633 plt.title("Spectra for Atmospheric variations")
634 if parameters.DISPLAY:
635 plt.show()
636 else:
637 plt.close('all')
639 def plot_spectra_img(self):
640 plt.figure()
641 img = plt.imshow(self.spectragrid[1:, self.atmgrid.index_atm_data:], origin='lower', cmap='jet')
642 plt.xlabel(r"$\lambda$ [nm]")
643 plt.ylabel("Simulation number")
644 plt.title("Spectra for atmospheric variations")
645 cbar = plt.colorbar(img)
646 cbar.set_label("Flux [ADU/s]")
647 plt.grid(True)
648 if parameters.DISPLAY:
649 plt.show()
650 else:
651 plt.close('all')
653 def save_spectra(self, filename):
655 if filename != "":
656 self.filename = filename
658 if self.filename == "":
659 return
660 else:
662 hdu = fits.PrimaryHDU(self.spectragrid, header=self.header)
663 hdu.writeto(self.filename, overwrite=True)
664 if parameters.VERBOSE or parameters.DEBUG:
665 self.my_logger.info(f'\n\tSPECTRA.save atm-file={self.filename}')
668def SimulatorInit(filename, fast_load=False):
669 """ SimulatorInit
670 Main function to evaluate several spectra
671 A grid of spectra will be produced for a given target, airmass and pressure
672 """
673 my_logger = set_logger(__name__)
674 my_logger.info('\n\tStart SIMULATOR initialisation')
675 # Load data spectrum
676 spectrum = Spectrum(filename, fast_load=fast_load)
678 # TELESCOPE TRANSMISSION
679 # ------------------------
680 telescope = TelescopeTransmission(spectrum.filter_label)
682 # DISPERSER TRANSMISSION
683 # ------------------------
684 if not isinstance(spectrum.disperser, str):
685 disperser = spectrum.disperser
686 else:
687 disperser = Hologram(spectrum.disperser)
689 # STAR SPECTRUM
690 # ------------------------
691 if not isinstance(spectrum.target, str):
692 target = spectrum.target
693 else:
694 target = Target(spectrum.target)
696 return spectrum, telescope, disperser, target
699def SpectrumSimulatorCore(spectrum, telescope, disperser, airmass=1.0, pressure=800, temperature=10,
700 pwv=5, ozone=300, aerosols=0.05, A1=1.0, A2=0., reso=0, D=parameters.DISTANCE2CCD, shift=0.):
701 """ SimulatorCore
702 Main function to evaluate several spectra
703 A grid of spectra will be produced for a given target, airmass and pressure
704 """
705 my_logger = set_logger(__name__)
706 my_logger.info('\n\tStart SPECTRUMSIMULATOR core program')
707 # SIMULATE ATMOSPHERE
708 # -------------------
709 atmosphere = Atmosphere(airmass, pressure, temperature)
711 # SPECTRUM SIMULATION
712 # --------------------
713 spectrum_simulation = SpectrumSimulation(spectrum, atmosphere, telescope, disperser)
714 spectrum_simulation.simulate(A1, A2, ozone, pwv, aerosols, reso, D, shift)
715 if parameters.DEBUG:
716 spectrum_simulation.plot_spectrum(force_lines=True)
717 return spectrum_simulation
720def SpectrogramSimulatorCore(spectrum, telescope, disperser, airmass=1.0, pressure=800, temperature=10,
721 pwv=5, ozone=300, aerosols=0.05, A1=1.0, A2=0.,
722 D=parameters.DISTANCE2CCD, shift_x=0., shift_y=0., shift_t=0., angle=0.,
723 B=1., psf_poly_params=None, with_background=True, fast_sim=False, full_image=False):
724 """ SimulatorCore
725 Main function to evaluate several spectra
726 A grid of spectra will be produced for a given target, airmass and pressure
727 """
728 my_logger = set_logger(__name__)
729 my_logger.info('\n\tStart SPECTROGRAMSIMULATOR core program')
730 # SIMULATE ATMOSPHERE
731 # -------------------
733 atmosphere = Atmosphere(airmass, pressure, temperature)
734 spectrum.rotation_angle = angle
736 # SPECTRUM SIMULATION
737 # --------------------
738 spectrogram_simulation = SpectrogramModel(spectrum, atmosphere, telescope, disperser,
739 with_background=with_background, fast_sim=fast_sim, full_image=full_image)
740 spectrogram_simulation.simulate(A1, A2, ozone, pwv, aerosols, D, shift_x, shift_y, angle, B, psf_poly_params)
741 return spectrogram_simulation
744def SpectrumSimulatorSimGrid(filename, outputdir, pwv_grid=[0, 10, 5], ozone_grid=[100, 700, 7],
745 aerosol_grid=[0, 0.1, 5]):
746 """ SimulatorSimGrid
747 Main function to evaluate several spectra
748 A grid of spectra will be produced for a given target, airmass and pressure
750 """
751 my_logger = set_logger(__name__)
752 my_logger.info('\n\tStart SIMULATORGRID')
753 # Initialisation
754 spectrum, telescope, disperser, target = SimulatorInit(filename)
755 # Set output path
756 ensure_dir(outputdir)
757 # extract the basename : simimar as os.path.basename(file)
758 base_filename = filename.split('/')[-1]
759 output_filename = os.path.join(outputdir, base_filename.replace('spectrum', 'spectrasim'))
760 output_atmfilename = os.path.join(outputdir, base_filename.replace('spectrum', 'atmsim'))
762 # SIMULATE ATMOSPHERE GRID
763 # ------------------------
764 airmass = spectrum.header['AIRMASS']
765 pressure = spectrum.header['OUTPRESS']
766 temperature = spectrum.header['OUTTEMP']
767 atm = AtmosphereGrid(filename, airmass=airmass, pressure=pressure, temperature=temperature)
768 atm.set_grid(pwv_grid, ozone_grid, aerosol_grid)
770 # test if file already exists
771 if os.path.exists(output_atmfilename) and os.path.getsize(output_atmfilename) > 20000:
772 filesize = os.path.getsize(output_atmfilename)
773 infostring = " atmospheric simulation file %s of size %d already exists, thus load_image it ..." % (
774 output_atmfilename, filesize)
775 my_logger.info(infostring)
776 atm.load_file(output_atmfilename)
777 else:
778 my_logger.info(f"\n\tFile {output_atmfilename} does not exist yet. Compute it...")
779 atm.compute()
780 atm.save_file(filename=output_atmfilename)
781 # libradtran.clean_simulation_directory()
782 if parameters.DEBUG:
783 infostring = '\n\t ========= Atmospheric simulation : ==============='
784 my_logger.info(infostring)
785 atm.plot_transmission() # plot all atm transp profiles
786 atm.plot_transmission_image() # plot 2D image summary of atm simulations
788 # SPECTRA-GRID
789 # -------------
790 # in any case we re-calculate the spectra in case of change of spectrum function
791 spectra = SpectrumSimGrid(spectrum, atm, telescope, disperser, target)
792 spectra.compute()
793 spectra.save_spectra(output_filename)
794 if parameters.DEBUG:
795 spectra.plot_spectra()
796 spectra.plot_spectra_img()
797 # ---------------------------------------------------------------------------
800def SpectrumSimulator(filename, outputdir="", pwv=5, ozone=300, aerosols=0.05, A1=1., A2=0.,
801 reso=None, D=parameters.DISTANCE2CCD, shift=0.):
802 """ Simulator
803 Main function to evaluate several spectra
804 A grid of spectra will be produced for a given target, airmass and pressure
805 """
806 my_logger = set_logger(__name__)
807 my_logger.info('\n\tStart SPECTRACTORSIM')
808 # Initialisation
809 spectrum, telescope, disperser, target = SimulatorInit(filename)
811 # SIMULATE SPECTRUM
812 # -------------------
813 airmass = spectrum.header['AIRMASS']
814 pressure = spectrum.header['OUTPRESS']
815 temperature = spectrum.header['OUTTEMP']
817 spectrum_simulation = SpectrumSimulatorCore(spectrum, telescope, disperser, airmass, pressure,
818 temperature, pwv, ozone, aerosols, A1=A1, A2=A2, reso=reso, D=D,
819 shift=shift)
821 # Save the spectrum
822 spectrum_simulation.header['OZONE_T'] = ozone
823 spectrum_simulation.header['PWV_T'] = pwv
824 spectrum_simulation.header['VAOD_T'] = aerosols
825 spectrum_simulation.header['A1_T'] = A1
826 spectrum_simulation.header['A2_T'] = A2
827 spectrum_simulation.header['RESO_T'] = reso
828 spectrum_simulation.header['D2CCD_T'] = D
829 spectrum_simulation.header['X0_T'] = shift
830 output_filename = filename.replace('spectrum', 'sim')
831 if outputdir != "":
832 base_filename = filename.split('/')[-1]
833 output_filename = os.path.join(outputdir, base_filename.replace('spectrum', 'sim'))
834 spectrum_simulation.save_spectrum(output_filename, overwrite=True)
836 return spectrum_simulation
839def SpectrogramSimulator(filename, outputdir="", pwv=5, ozone=300, aerosols=0.05, A1=1., A2=0.,
840 D=parameters.DISTANCE2CCD, shift_x=0., shift_y=0., shift_t=0., angle=0., B=1.,
841 psf_poly_params=None):
842 """ Simulator
843 Main function to evaluate several spectra
844 A grid of spectra will be produced for a given target, airmass and pressure
845 """
846 my_logger = set_logger(__name__)
847 my_logger.info('\n\tStart SPECTRACTORSIM')
848 # Initialisation
849 spectrum, telescope, disperser, target = SimulatorInit(filename)
851 if psf_poly_params is None:
852 my_logger.info('\n\tUse PSF parameters from _table.csv file.')
853 psf_poly_params = spectrum.chromatic_psf.from_table_to_poly_params()
855 # SIMULATE SPECTRUM
856 # -------------------
857 airmass = spectrum.header['AIRMASS']
858 pressure = spectrum.header['OUTPRESS']
859 temperature = spectrum.header['OUTTEMP']
861 spectrogram_simulation = SpectrogramSimulatorCore(spectrum, telescope, disperser, airmass, pressure,
862 temperature, pwv, ozone, aerosols,
863 D=D, shift_x=shift_x,
864 shift_y=shift_y, shift_t=shift_t, angle=angle, B=B,
865 psf_poly_params=psf_poly_params)
867 # Save the spectrum
868 spectrogram_simulation.header['OZONE_T'] = ozone
869 spectrogram_simulation.header['PWV_T'] = pwv
870 spectrogram_simulation.header['VAOD_T'] = aerosols
871 spectrogram_simulation.header['A1_T'] = A1
872 spectrogram_simulation.header['A2_T'] = A2
873 spectrogram_simulation.header['D2CCD_T'] = D
874 spectrogram_simulation.header['X0_T'] = shift_x
875 spectrogram_simulation.header['Y0_T'] = shift_y
876 spectrogram_simulation.header['TSHIFT_T'] = shift_t
877 spectrogram_simulation.header['ROTANGLE'] = angle
878 output_filename = filename.replace('spectrum', 'sim')
879 if outputdir != "":
880 base_filename = filename.split('/')[-1]
881 output_filename = os.path.join(outputdir, base_filename.replace('spectrum', 'sim'))
882 # spectrogram_simulation.save_spectrum(output_filename, overwrite=True)
884 return spectrogram_simulation
887if __name__ == "__main__": 887 ↛ 888line 887 didn't jump to line 888, because the condition on line 887 was never true
888 import doctest
890 doctest.testmod()