Coverage for spectractor/extractor/extractor.py: 4%
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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 matplotlib import cm
6from scipy.interpolate import interp1d
7import time
9from spectractor import parameters
10from spectractor.config import set_logger, load_config
11from spectractor.extractor.images import Image, find_target, turn_image
12from spectractor.extractor.spectrum import Spectrum, calibrate_spectrum
13from spectractor.extractor.background import extract_spectrogram_background_sextractor
14from spectractor.extractor.chromaticpsf import ChromaticPSF
15from spectractor.extractor.psf import load_PSF
16from spectractor.tools import ensure_dir, plot_image_simple, from_lambda_to_colormap, plot_spectrum_simple, rebin
17from spectractor.simulation.adr import adr_calib, flip_and_rotate_adr_to_image_xy_coordinates
18from spectractor.fit.fitter import run_minimisation, run_minimisation_sigma_clipping, RegFitWorkspace, FitWorkspace
21def dumpParameters():
22 for item in dir(parameters):
23 if not item.startswith("__"):
24 print(item, getattr(parameters, item))
26class FullForwardModelFitWorkspace(FitWorkspace):
28 def __init__(self, spectrum, amplitude_priors_method="noprior", nwalkers=18, nsteps=1000, burnin=100, nbins=10,
29 verbose=0, plot=False, live_fit=False, truth=None):
30 """Class to fit a full forward model on data to extract a spectrum, with ADR prediction and order 2 subtraction.
32 Parameters
33 ----------
34 spectrum: Spectrum
35 amplitude_priors_method
36 nwalkers
37 nsteps
38 burnin
39 nbins
40 verbose
41 plot
42 live_fit
43 truth
45 Examples
46 --------
47 >>> spec = Spectrum("./tests/data/sim_20170530_134_spectrum.fits", config="./config/ctio.ini")
48 >>> w = FullForwardModelFitWorkspace(spectrum=spec, amplitude_priors_method="spectrum")
49 """
50 FitWorkspace.__init__(self, spectrum.filename, nwalkers, nsteps, burnin, nbins, verbose, plot,
51 live_fit, truth=truth)
52 self.my_logger = set_logger(self.__class__.__name__)
53 self.spectrum = spectrum
55 # check the shapes
56 self.Ny, self.Nx = spectrum.spectrogram.shape
57 if self.Ny != self.spectrum.chromatic_psf.Ny:
58 raise AttributeError(f"Data y shape {self.Ny} different from "
59 f"ChromaticPSF input Ny {spectrum.chromatic_psf.Ny}.")
60 if self.Nx != self.spectrum.chromatic_psf.Nx:
61 raise AttributeError(f"Data x shape {self.Nx} different from "
62 f"ChromaticPSF input Nx {spectrum.chromatic_psf.Nx}.")
64 # crop data to fit faster
65 self.lambdas = self.spectrum.lambdas
66 self.lambdas_order2 = self.spectrum.lambdas_order2
67 self.bgd_width = parameters.PIXWIDTH_BACKGROUND + parameters.PIXDIST_BACKGROUND - parameters.PIXWIDTH_SIGNAL
68 self.data = spectrum.spectrogram[self.bgd_width:-self.bgd_width, :]
69 self.err = spectrum.spectrogram_err[self.bgd_width:-self.bgd_width, :]
70 self.bgd = spectrum.spectrogram_bgd[self.bgd_width:-self.bgd_width, :]
71 self.bgd_flat = self.bgd.flatten()
72 self.Ny, self.Nx = self.data.shape
73 yy, xx = np.mgrid[:self.Ny, :self.Nx]
74 self.pixels = np.asarray([xx, yy])
76 # prepare parameters to fit
77 self.A2 = 1
78 self.D = np.copy(self.spectrum.header['D2CCD'])
79 self.shift_x = np.copy(self.spectrum.header['PIXSHIFT'])
80 self.shift_y = 0.
81 self.angle = np.copy(self.spectrum.rotation_angle)
82 self.B = 1
83 self.rotation = parameters.OBS_CAMERA_ROTATION
84 self.psf_poly_params = np.copy(self.spectrum.chromatic_psf.from_table_to_poly_params())
85 self.psf_profile_params = np.copy(self.spectrum.chromatic_psf.from_table_to_profile_params())
86 length = len(self.spectrum.chromatic_psf.table)
87 self.psf_poly_params = self.psf_poly_params[length:]
88 self.psf_poly_params_labels = np.copy(self.spectrum.chromatic_psf.poly_params_labels[length:])
89 self.psf_poly_params_names = np.copy(self.spectrum.chromatic_psf.poly_params_names[length:])
90 self.psf_poly_params_bounds = self.spectrum.chromatic_psf.set_bounds_for_minuit(data=None)
91 self.spectrum.chromatic_psf.psf.apply_max_width_to_bounds(max_half_width=self.spectrum.spectrogram_Ny)
92 psf_poly_params_bounds = self.spectrum.chromatic_psf.set_bounds()
93 self.saturation = self.spectrum.spectrogram_saturation
94 self.p = np.array([self.A2, self.D, self.shift_x, self.shift_y, self.angle, self.B, self.rotation])
95 self.psf_params_start_index = self.p.size
96 self.p = np.concatenate([self.p, self.psf_poly_params])
97 self.input_labels = ["A2", r"D_CCD [mm]", r"shift_x [pix]", r"shift_y [pix]",
98 r"angle [deg]", "B", "R"] + list(self.psf_poly_params_labels)
99 self.axis_names = ["$A_2$", r"$D_{CCD}$ [mm]", r"$\Delta_{\mathrm{x}}$ [pix]", r"$\Delta_{\mathrm{y}}$ [pix]",
100 r"$\theta$ [deg]", "$B$", "R"] + list(self.psf_poly_params_names)
101 bounds_D = (self.D - 5 * parameters.DISTANCE2CCD_ERR, self.D + 5 * parameters.DISTANCE2CCD_ERR)
102 self.bounds = np.concatenate([np.array([(0, 2 / parameters.GRATING_ORDER_2OVER1), bounds_D,
103 (-parameters.PIXSHIFT_PRIOR, parameters.PIXSHIFT_PRIOR),
104 (-10 * parameters.CCD_PIXEL2ARCSEC, 10 * parameters.PIXSHIFT_PRIOR),
105 (-90, 90), (0.2, 5), (-360, 360)]), psf_poly_params_bounds])
106 self.fixed = [False] * self.p.size
107 for k, par in enumerate(self.input_labels):
108 if "x_c" in par or "saturation" in par or "y_c" in par:
109 self.fixed[k] = True
110 # This set of fixed parameters was determined so that the reconstructed spectrum has a ZERO bias
111 # with respect to the true spectrum injected in the simulation
112 # A2 is free only if spectrogram is a simulation or if the order 2/1 ratio is not known and flat
113 self.fixed[0] = not self.spectrum.disperser.flat_ratio_order_2over1
114 self.fixed[1] = True # D2CCD: spectrogram can not tell something on this parameter: rely on calibrate_pectrum
115 self.fixed[2] = True # delta x: if False, extracted spectrum is biased compared with truth
116 # self.fixed[3] = True # delta y
117 # self.fixed[4] = True # angle
118 self.fixed[5] = True # B: not needed in simulations, to check with data
119 self.fixed[6] = True # camera rot
120 self.fixed[-1] = True # saturation
121 self.nwalkers = max(2 * self.ndim, nwalkers)
123 # prepare the background, data and errors
124 self.bgd_std = float(np.std(np.random.poisson(np.abs(self.bgd))))
126 # error matrix
127 # here image uncertainties are assumed to be uncorrelated
128 # (which is not exactly true in rotated images)
129 self.W = 1. / (self.err * self.err)
130 self.W = self.W.flatten()
132 # flat data for fitworkspace
133 self.data = self.data.flatten() - self.bgd_flat
134 self.err = self.err.flatten()
136 # design matrix
137 self.M = np.zeros((self.Nx, self.data.size))
138 self.M_dot_W_dot_M = np.zeros((self.Nx, self.Nx))
140 # prepare results
141 self.amplitude_params = np.zeros(self.Nx)
142 self.amplitude_params_err = np.zeros(self.Nx)
143 self.amplitude_cov_matrix = np.zeros((self.Nx, self.Nx))
145 # priors on amplitude parameters
146 self.amplitude_priors_list = ['noprior', 'positive', 'smooth', 'spectrum', 'fixed']
147 self.amplitude_priors_method = amplitude_priors_method
148 self.fwhm_priors = np.copy(spectrum.chromatic_psf.table['fwhm'])
149 self.reg = spectrum.chromatic_psf.opt_reg
150 if 'PSF_REG' in spectrum.header and float(spectrum.header["PSF_REG"]) > 0:
151 self.reg = float(spectrum.header['PSF_REG'])
152 if self.reg < 0:
153 self.reg = parameters.PSF_FIT_REG_PARAM
154 self.my_logger.info(f"\n\tFull forward model fitting with regularisation parameter r={self.reg}.")
155 self.Q = np.zeros((self.Nx, self.Nx))
156 self.Q_dot_A0 = np.zeros(self.Nx)
157 if amplitude_priors_method not in self.amplitude_priors_list:
158 raise ValueError(f"Unknown prior method for the amplitude fitting: {self.amplitude_priors_method}. "
159 f"Must be either {self.amplitude_priors_list}.")
160 self.spectrum.convert_from_flam_to_ADUrate()
161 if self.amplitude_priors_method == "spectrum":
162 self.amplitude_priors = np.copy(self.spectrum.data)
163 self.amplitude_priors_cov_matrix = np.copy(self.spectrum.cov_matrix)
164 if self.amplitude_priors_method == "fixed":
165 self.amplitude_priors = np.copy(self.spectrum.data)
167 # regularisation matrices
168 if amplitude_priors_method == "spectrum":
169 # U = np.diag([1 / np.sqrt(np.sum(self.err[:, x]**2)) for x in range(self.Nx)])
170 self.U = np.diag([1 / np.sqrt(self.amplitude_priors_cov_matrix[x, x]) for x in range(self.Nx)])
171 L = np.diag(-2 * np.ones(self.Nx)) + np.diag(np.ones(self.Nx), -1)[:-1, :-1] \
172 + np.diag(np.ones(self.Nx), 1)[:-1, :-1]
173 L.astype(float)
174 L[0, 0] = -1
175 L[-1, -1] = -1
176 self.L = L
177 self.Q = L.T @ np.linalg.inv(self.amplitude_priors_cov_matrix) @ L
178 # self.Q = L.T @ U.T @ U @ L
179 self.Q_dot_A0 = self.Q @ self.amplitude_priors
181 def simulate(self, *params):
182 r"""
183 Compute a ChromaticPSF2D model given PSF shape parameters and minimizing
184 amplitude parameters using a spectrogram data array.
186 The ChromaticPSF2D model :math:`\vec{m}(\vec{x},\vec{p})` can be written as
188 .. math ::
189 :label: chromaticpsf2d
191 \vec{m}(\vec{x},\vec{p}) = \sum_{i=0}^{N_x} A_i \phi\left(\vec{x},\vec{p}_i\right)
193 with :math:`\vec{x}` the 2D array of the pixel coordinates, :math:`\vec{A}` the amplitude parameter array
194 along the x axis of the spectrogram, :math:`\phi\left(\vec{x},\vec{p}_i\right)` the 2D PSF kernel whose integral
195 is normalised to one parametrized with the :math:`\vec{p}_i` non-linear parameter array. If the :math:`\vec{x}`
196 2D array is flatten in 1D, equation :eq:`chromaticpsf2d` is
198 .. math ::
199 :label: chromaticpsf2d_matrix
200 :nowrap:
202 \begin{align}
203 \vec{m}(\vec{x},\vec{p}) & = \mathbf{M}\left(\vec{x},\vec{p}\right) \mathbf{A} \\
205 \mathbf{M}\left(\vec{x},\vec{p}\right) & = \left(\begin{array}{cccc}
206 \phi\left(\vec{x}_1,\vec{p}_1\right) & \phi\left(\vec{x}_2,\vec{p}_1\right) & ...
207 & \phi\left(\vec{x}_{N_x},\vec{p}_1\right) \\
208 ... & ... & ... & ...\\
209 \phi\left(\vec{x}_1,\vec{p}_{N_x}\right) & \phi\left(\vec{x}_2,\vec{p}_{N_x}\right) & ...
210 & \phi\left(\vec{x}_{N_x},\vec{p}_{N_x}\right) \\
211 \end{array}\right)
212 \end{align}
215 with :math:`\mathbf{M}` the design matrix.
217 The goal of this function is to perform a minimisation of the amplitude vector :math:`\mathbf{A}` given
218 a set of non-linear parameters :math:`\mathbf{p}` and a spectrogram data array :math:`mathbf{y}` modelise as
220 .. math:: \mathbf{y} = \mathbf{m}(\vec{x},\vec{p}) + \vec{\epsilon}
222 with :math:`\vec{\epsilon}` a random noise vector. The :math:`\chi^2` function to minimise is
224 .. math::
225 :label: chromaticspsf2d_chi2
227 \chi^2(\mathbf{A})= \left(\mathbf{y} - \mathbf{M}\left(\vec{x},\vec{p}\right) \mathbf{A}\right)^T \mathbf{W}
228 \left(\mathbf{y} - \mathbf{M}\left(\vec{x},\vec{p}\right) \mathbf{A} \right)
231 with :math:`\mathbf{W}` the weight matrix, inverse of the covariance matrix. In our case this matrix is diagonal
232 as the pixels are considered all independent. The minimum of equation :eq:`chromaticspsf2d_chi2` is reached for
233 a the set of amplitude parameters :math:`\hat{\mathbf{A}}` given by
235 .. math::
237 \hat{\mathbf{A}} = (\mathbf{M}^T \mathbf{W} \mathbf{M})^{-1} \mathbf{M}^T \mathbf{W} \mathbf{y}
239 The error matrix on the :math:`\hat{\mathbf{A}}` coefficient is simply
240 :math:`(\mathbf{M}^T \mathbf{W} \mathbf{M})^{-1}`.
242 See Also
243 --------
244 ChromaticPSF2DFitWorkspace.simulate
246 Parameters
247 ----------
248 params: array_like
249 Full forward model parameter array.
251 Examples
252 --------
254 Load data:
256 >>> spec = Spectrum("./tests/data/sim_20170530_134_spectrum.fits", config="./config/ctio.ini")
258 Simulate the data with fixed amplitude priors:
260 .. doctest::
262 >>> w = FullForwardModelFitWorkspace(spectrum=spec, amplitude_priors_method="fixed", verbose=True)
263 >>> y, mod, mod_err = w.simulate(*w.p)
264 >>> w.plot_fit()
266 .. doctest::
267 :hide:
269 >>> assert mod is not None
271 Simulate the data with a Tikhonov prior on amplitude parameters:
273 .. doctest::
275 >>> spec = Spectrum("./tests/data/sim_20170530_134_spectrum.fits", config="./config/ctio.ini")
276 >>> w = FullForwardModelFitWorkspace(spectrum=spec, amplitude_priors_method="spectrum", verbose=True)
277 >>> y, mod, mod_err = w.simulate(*w.p)
278 >>> w.plot_fit()
280 """
281 # linear regression for the amplitude parameters
282 # prepare the vectors
283 A2, D2CCD, dx0, dy0, angle, B, rot, *poly_params = params
284 parameters.OBS_CAMERA_ROTATION = rot
285 self.p = np.asarray(params)
286 W_dot_data = self.W * (self.data + (1 - B) * self.bgd_flat)
287 profile_params = self.spectrum.chromatic_psf.from_poly_params_to_profile_params(poly_params, apply_bounds=True)
288 profile_params[:, 0] = 1
289 profile_params[:, 1] = np.arange(self.Nx)
290 self.spectrum.chromatic_psf.fill_table_with_profile_params(profile_params)
292 # Distance in x and y with respect to the true order 0 position at lambda_ref
293 Dx = np.arange(self.Nx) - self.spectrum.spectrogram_x0 - dx0 # distance in (x,y) spectrogram frame for column x
294 Dy_disp_axis = np.tan(angle * np.pi / 180) * Dx # disp axis height in spectrogram frame for x
295 distance = np.sign(Dx)*np.sqrt(Dx * Dx + Dy_disp_axis * Dy_disp_axis) # algebraic distance along dispersion axis
296 self.spectrum.chromatic_psf.table["Dy_disp_axis"] = Dy_disp_axis
297 self.spectrum.chromatic_psf.table["Dx"] = Dx
299 # First guess of wavelengths
300 self.spectrum.disperser.D = np.copy(D2CCD)
301 self.lambdas = self.spectrum.disperser.grating_pixel_to_lambda(distance,
302 self.spectrum.x0 + np.asarray([dx0, dy0]),
303 order=self.spectrum.order)
304 self.lambdas_order2 = self.spectrum.disperser.grating_pixel_to_lambda(distance,
305 self.spectrum.x0 + np.asarray([dx0, dy0]),
306 order=self.spectrum.order+np.sign(self.spectrum.order))
308 # Evaluate ADR
309 adr_ra, adr_dec = adr_calib(self.lambdas, self.spectrum.adr_params, parameters.OBS_LATITUDE,
310 lambda_ref=self.spectrum.lambda_ref)
311 adr_x, adr_y = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec, dispersion_axis_angle=0)
312 adr_u, adr_v = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec, dispersion_axis_angle=angle)
313 # Compute lambdas at pixel column x
314 # self.lambdas = self.spectrum.disperser.grating_pixel_to_lambda(distance - adr_u,
315 # self.spectrum.x0 + np.asarray([dx0, dy0]),
316 # order=1)
318 # Evaluate ADR for order 2
319 adr_ra, adr_dec = adr_calib(self.lambdas_order2, self.spectrum.adr_params, parameters.OBS_LATITUDE,
320 lambda_ref=self.spectrum.lambda_ref)
321 adr_x_2, adr_y_2 = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec, dispersion_axis_angle=0)
322 # adr_u_2, adr_v_2 = flip_and_rotate_adr_to_image_xy_coordinates(adr_ra, adr_dec, dispersion_axis_angle=angle)
323 # Compute lambdas at pixel column x for order 2
324 # self.lambdas_order2 = self.spectrum.disperser.grating_pixel_to_lambda(distance - adr_u_2,
325 # self.spectrum.x0 + np.asarray([dx0, dy0]),
326 # order=2)
328 # Fill spectrogram trace as a function of the pixel column x
329 profile_params[:, 1] = Dx + self.spectrum.spectrogram_x0 + adr_x + dx0
330 profile_params[:, 2] = Dy_disp_axis + (self.spectrum.spectrogram_y0 + adr_y + dy0) - self.bgd_width
331 # Dy_disp_axis = np.copy(profile_params[:, 2])
332 # profile_params[:, 2] += adr_y + dy0 - self.bgd_width
334 # Prepare order 2 profile params indexed by the pixel column x
335 profile_params_order2 = np.copy(profile_params)
336 profile_params_order2[:, 0] = self.spectrum.disperser.ratio_order_2over1(self.lambdas)
337 profile_params_order2[:, 1] = np.arange(self.Nx) + adr_x_2 + dx0
338 profile_params_order2[:, 2] = Dy_disp_axis + (self.spectrum.spectrogram_y0 + adr_y_2 + dy0) - self.bgd_width
339 # profile_params_order2[:, 2] = Dy_disp_axis + adr_y_2 + dy0 - self.bgd_width
341 # For each A(lambda)=A_x, affect an order 2 PSF with correct position and
342 # same PSF as for the order 1 but at the same position
343 distance_order2 = self.spectrum.disperser.grating_lambda_to_pixel(self.lambdas - adr_u,
344 self.spectrum.x0 + np.asarray([dx0, dy0]),
345 order=self.spectrum.order+np.sign(self.spectrum.order))
346 for k in range(1, profile_params.shape[1]):
347 # profile_params_order2[:, k] = interp1d(self.lambdas_order2, profile_params_order2[:, k],
348 # kind="cubic", fill_value="extrapolate")(self.lambdas)
349 profile_params_order2[:, k] = interp1d(distance, profile_params_order2[:, k],
350 kind="cubic", fill_value="extrapolate")(distance_order2)
352 # if parameters.DEBUG:
353 # plt.imshow(self.data.reshape((self.Ny, self.Nx)), origin="lower")
354 # plt.scatter(profile_params[:, 1], profile_params[:, 2], label="profile",
355 # cmap=from_lambda_to_colormap(self.lambdas), c=self.lambdas)
356 # plt.scatter(profile_params_order2[:, 1], profile_params_order2[:, 2], label="order 2",
357 # cmap=from_lambda_to_colormap(self.lambdas), c=self.lambdas)
358 # plt.plot(profile_params[:, 1], profile_params[:, 2], label="profile")
359 # plt.plot(profile_params[:, 1], Dy_disp_axis + self.spectrum.spectrogram_y0 + dy0 - self.bgd_width, 'k-',
360 # label="disp_axis")
361 # plt.plot(self.spectrum.chromatic_psf.table['Dx'] + self.spectrum.spectrogram_x0 + dx0,
362 # self.spectrum.chromatic_psf.table['Dy'] + self.spectrum.spectrogram_y0 + dy0 - self.bgd_width,
363 # label="y_c")
364 # plt.legend()
365 # plt.title(f"D_CCD={D2CCD:.2f}, dx0={dx0:.2g}, dy0={dy0:.2g}")
366 # plt.xlim((0, self.Nx))
367 # plt.ylim((0, self.Ny))
368 # plt.grid()
369 # plt.gca().set_aspect("auto")
370 # plt.show()
372 # Matrix filling
373 M = np.array([self.spectrum.chromatic_psf.psf.evaluate(self.pixels, p=profile_params[x, :]).flatten()
374 for x in range(self.Nx)]).T
375 if A2 > 0:
376 for x in range(self.Nx):
377 M[:, x] += A2 * self.spectrum.chromatic_psf.psf.evaluate(self.pixels,
378 p=profile_params_order2[x, :]).flatten()
379 if profile_params_order2[x, 1] > 1.2 * self.Nx:
380 break
382 # Algebra to compute amplitude parameters
383 if self.amplitude_priors_method != "fixed":
384 W_dot_M = np.array([M[:, x] * self.W for x in range(self.Nx)]).T
385 M_dot_W_dot_M = M.T @ W_dot_M
386 if self.amplitude_priors_method != "spectrum":
387 try:
388 L = np.linalg.inv(np.linalg.cholesky(M_dot_W_dot_M))
389 cov_matrix = L.T @ L
390 except np.linalg.LinAlgError:
391 cov_matrix = np.linalg.inv(M_dot_W_dot_M)
392 amplitude_params = cov_matrix @ (M.T @ W_dot_data)
393 if self.amplitude_priors_method == "positive":
394 amplitude_params[amplitude_params < 0] = 0
395 elif self.amplitude_priors_method == "smooth":
396 null_indices = np.where(amplitude_params < 0)[0]
397 for index in null_indices:
398 right = amplitude_params[index]
399 for i in range(index, min(index + 10, self.Nx)):
400 right = amplitude_params[i]
401 if i not in null_indices:
402 break
403 left = amplitude_params[index]
404 for i in range(index, max(0, index - 10), -1):
405 left = amplitude_params[i]
406 if i not in null_indices:
407 break
408 amplitude_params[index] = 0.5 * (right + left)
409 elif self.amplitude_priors_method == "noprior":
410 pass
411 else:
412 M_dot_W_dot_M_plus_Q = M_dot_W_dot_M + self.reg * self.Q
413 try:
414 L = np.linalg.inv(np.linalg.cholesky(M_dot_W_dot_M_plus_Q))
415 cov_matrix = L.T @ L
416 except np.linalg.LinAlgError:
417 cov_matrix = np.linalg.inv(M_dot_W_dot_M_plus_Q)
418 amplitude_params = cov_matrix @ (M.T @ W_dot_data + self.reg * self.Q_dot_A0)
419 self.M_dot_W_dot_M = M_dot_W_dot_M
420 else:
421 amplitude_params = np.copy(self.amplitude_priors)
422 err2 = np.copy(amplitude_params)
423 err2[err2 <= 0] = np.min(np.abs(err2[err2 > 0]))
424 cov_matrix = np.diag(err2)
426 # Save results
427 self.M = M
428 self.psf_profile_params = np.copy(profile_params)
429 self.psf_poly_params = np.copy(poly_params)
430 self.amplitude_params = np.copy(amplitude_params)
431 self.amplitude_params_err = np.array([np.sqrt(cov_matrix[x, x]) for x in range(self.Nx)])
432 self.amplitude_cov_matrix = np.copy(cov_matrix)
434 # Compute the model
435 self.model = (M @ amplitude_params) # .reshape((self.Ny, self.Nx))
436 self.model_err = np.zeros_like(self.model)
438 return self.pixels, self.model, self.model_err
440 def plot_spectrogram_comparison_simple(self, ax, title='', extent=None, dispersion=False):
441 """Method to plot a spectrogram issued from data and compare it with simulations.
443 Parameters
444 ----------
445 ax: Axes
446 Axes instance of shape (4, 2).
447 title: str, optional
448 Title for the simulation plot (default: '').
449 extent: array_like, optional
450 Extent argument for imshow to crop plots (default: None).
451 dispersion: bool, optional
452 If True, plot a colored bar to see the associated wavelength color along the x axis (default: False).
453 """
454 cmap_bwr = copy.copy(cm.get_cmap('bwr'))
455 cmap_bwr.set_bad(color='lightgrey')
456 cmap_viridis = copy.copy(cm.get_cmap('viridis'))
457 cmap_viridis.set_bad(color='lightgrey')
459 data = np.copy(self.data)
460 if len(self.outliers) > 0:
461 bad_indices = self.get_bad_indices()
462 data[bad_indices] = np.nan
464 lambdas = self.spectrum.lambdas
465 sub = np.where((lambdas > parameters.LAMBDA_MIN) & (lambdas < parameters.LAMBDA_MAX))[0]
466 sub = np.where(sub < self.spectrum.spectrogram.shape[1])[0]
467 data = (data + self.bgd_flat).reshape((self.Ny, self.Nx))
468 err = self.err.reshape((self.Ny, self.Nx))
469 model = (self.model + self.p[5] * self.bgd_flat).reshape((self.Ny, self.Nx))
470 if extent is not None:
471 sub = np.where((lambdas > extent[0]) & (lambdas < extent[1]))[0]
472 if len(sub) > 0:
473 norm = np.nanmax(data[:, sub])
474 plot_image_simple(ax[0, 0], data=data[:, sub] / norm, title='Data', aspect='auto',
475 cax=ax[0, 1], vmin=0, vmax=1, units='1/max(data)', cmap=cmap_viridis)
476 ax[0, 0].set_title('Data', fontsize=10, loc='center', color='white', y=0.8)
477 plot_image_simple(ax[1, 0], data=model[:, sub] / norm, aspect='auto', cax=ax[1, 1], vmin=0, vmax=1,
478 units='1/max(data)', cmap=cmap_viridis)
479 if dispersion:
480 x = self.spectrum.chromatic_psf.table['Dx'][sub[5:-5]] + self.spectrum.spectrogram_x0 - sub[0]
481 y = np.ones_like(x)
482 ax[1, 0].scatter(x, y, cmap=from_lambda_to_colormap(self.lambdas[sub[5:-5]]), edgecolors='None',
483 c=self.lambdas[sub[5:-5]],
484 label='', marker='o', s=10)
485 ax[1, 0].set_xlim(0, model[:, sub].shape[1])
486 ax[1, 0].set_ylim(0, model[:, sub].shape[0])
487 # p0 = ax.plot(lambdas, self.model(lambdas), label='model')
488 # # ax.plot(self.lambdas, self.model_noconv, label='before conv')
489 if title != '':
490 ax[1, 0].set_title(title, fontsize=10, loc='center', color='white', y=0.8)
491 residuals = (data - model)
492 # residuals_err = self.spectrum.spectrogram_err / self.model
493 norm = err
494 residuals /= norm
495 std = float(np.nanstd(residuals[:, sub]))
496 plot_image_simple(ax[2, 0], data=residuals[:, sub], vmin=-5 * std, vmax=5 * std, title='(Data-Model)/Err',
497 aspect='auto', cax=ax[2, 1], units='', cmap=cmap_bwr)
498 ax[2, 0].set_title('(Data-Model)/Err', fontsize=10, loc='center', color='black', y=0.8)
499 ax[2, 0].text(0.05, 0.05,
500 f'mean={np.nanmean(residuals[:, sub]):.3f}\nstd={np.nanstd(residuals[:, sub]):.3f}',
501 horizontalalignment='left', verticalalignment='bottom',
502 color='black', transform=ax[2, 0].transAxes)
503 ax[0, 0].set_xticks(ax[2, 0].get_xticks()[1:-1])
504 ax[0, 1].get_yaxis().set_label_coords(3.5, 0.5)
505 ax[1, 1].get_yaxis().set_label_coords(3.5, 0.5)
506 ax[2, 1].get_yaxis().set_label_coords(3.5, 0.5)
507 ax[3, 1].remove()
508 ax[3, 0].plot(self.lambdas[sub], np.nansum(data, axis=0)[sub], label='Data')
509 ax[3, 0].plot(self.lambdas[sub], np.nansum(model, axis=0)[sub], label='Model')
510 ax[3, 0].set_ylabel('Cross spectrum')
511 ax[3, 0].set_xlabel(r'$\lambda$ [nm]')
512 ax[3, 0].legend(fontsize=7)
513 ax[3, 0].grid(True)
515 def plot_fit(self):
516 """Plot the fit result.
518 Examples
519 --------
521 >>> spec = Spectrum('tests/data/sim_20170530_134_spectrum.fits', config="config/ctio.ini")
522 >>> w = FullForwardModelFitWorkspace(spec, verbose=1, plot=True, live_fit=False)
523 >>> lambdas, model, model_err = w.simulate(*w.p)
524 >>> w.plot_fit()
526 .. plot::
527 :include-source:
529 from spectractor.fit.fit_spectrogram import SpectrogramFitWorkspace
530 file_name = 'tests/data/reduc_20170530_134_spectrum.fits'
531 atmgrid_file_name = file_name.replace('spectrum', 'atmsim')
532 fit_workspace = SpectrogramFitWorkspace(file_name, atmgrid_file_name=atmgrid_file_name, verbose=True)
533 A1, A2, ozone, pwv, aerosols, D, shift_x, shift_y, angle, *psf = fit_workspace.p
534 lambdas, model, model_err = fit_workspace.simulation.simulate(A1, A2, ozone, pwv, aerosols, D, shift_x,
535 shift_y, angle, psf)
536 fit_workspace.lambdas = lambdas
537 fit_workspace.model = model
538 fit_workspace.model_err = model_err
539 fit_workspace.plot_fit()
541 """
542 gs_kw = dict(width_ratios=[3, 0.01, 1, 0.01, 1, 0.15], height_ratios=[1, 1, 1, 1])
543 fig, ax = plt.subplots(nrows=4, ncols=6, figsize=(10, 8), gridspec_kw=gs_kw)
545 A2, D2CCD, dx0, dy0, angle, B, rot, *poly_params = self.p
546 plt.suptitle(f'A2={A2:.3f}, D={D2CCD:.2f}mm, shift_x={dx0:.3f}pix, shift_y={dy0:.3f}pix, '
547 f'angle={angle:.2f}pix, B={B:.3f}', y=1)
548 # main plot
549 self.plot_spectrogram_comparison_simple(ax[:, 0:2], title='Spectrogram model', dispersion=True)
550 # zoom O2
551 self.plot_spectrogram_comparison_simple(ax[:, 2:4], extent=[730, 800], title='Zoom $O_2$', dispersion=True)
552 # zoom H2O
553 self.plot_spectrogram_comparison_simple(ax[:, 4:6], extent=[870, 1000], title='Zoom $H_2 O$', dispersion=True)
554 for i in range(3): # clear middle colorbars
555 for j in range(2):
556 plt.delaxes(ax[i, 2 * j + 1])
557 for i in range(4): # clear middle y axis labels
558 for j in range(1, 3):
559 ax[i, 2 * j].set_ylabel("")
560 fig.tight_layout()
561 if self.live_fit: # pragma: no cover
562 plt.draw()
563 plt.pause(1e-8)
564 plt.close()
565 else:
566 if parameters.DISPLAY and self.verbose:
567 plt.show()
568 if parameters.SAVE: # pragma: no cover
569 figname = os.path.splitext(self.filename)[0] + "_bestfit.pdf"
570 self.my_logger.info(f"\n\tSave figure {figname}.")
571 fig.savefig(figname, dpi=100, bbox_inches='tight')
574def run_ffm_minimisation(w, method="newton"):
575 """Interface function to fit spectrogram simulation parameters to data.
577 Parameters
578 ----------
579 w: FullForwardModelFitWorkspace
580 An instance of the SpectrogramFitWorkspace class.
581 method: str, optional
582 Fitting method (default: 'newton').
584 Returns
585 -------
586 spectrum: Spectrum
587 The extracted spectrum.
589 Examples
590 --------
592 >>> spec = Spectrum("./tests/data/reduc_20170530_134_spectrum.fits", config="./config/ctio.ini")
593 >>> parameters.VERBOSE = True
594 >>> w = FullForwardModelFitWorkspace(spec, verbose=1, plot=True, live_fit=True, amplitude_priors_method="spectrum")
595 >>> spec = run_ffm_minimisation(w, method="newton") # doctest: +ELLIPSIS
596 >>> if 'LBDAS_T' in spec.header: plot_comparison_truth(spec, w)
597 Line Tabulated Detected ...
599 .. doctest:
600 :hide:
602 >>> assert w.costs[-1] / w.data.size < 1.22 # reduced chisq
603 >>> assert np.isclose(w.p[4], -1.56, rtol=0.05) # angle
604 >>> assert np.isclose(w.p[5], 1, rtol=0.05) # B
606 """
607 my_logger = set_logger(__name__)
608 guess = np.asarray(w.p)
609 w.simulate(*guess)
610 w.plot_fit()
611 if method != "newton":
612 run_minimisation(w, method=method)
613 else:
614 costs = np.array([w.chisq(guess)])
615 if parameters.DISPLAY and (parameters.DEBUG or w.live_fit):
616 w.plot_fit()
617 start = time.time()
618 my_logger.info(f"\n\tStart guess: {guess}\n\twith {w.input_labels}")
619 epsilon = 1e-4 * guess
620 epsilon[epsilon == 0] = 1e-4
621 fixed = np.copy(w.fixed)
623 w.fixed = np.copy(fixed)
624 run_minimisation_sigma_clipping(w, "newton", epsilon, fixed, xtol=1e-5,
625 ftol=1 / w.data.size, sigma_clip=10, niter_clip=3)
627 my_logger.info(f"\n\tNewton: total computation time: {time.time() - start}s")
628 if w.filename != "":
629 parameters.SAVE = True
630 ipar = np.array(np.where(np.array(w.fixed).astype(int) == 0)[0])
631 w.plot_correlation_matrix(ipar)
632 w.save_parameters_summary(ipar, header=f"{w.spectrum.date_obs}\n"
633 f"chi2: {costs[-1] / w.data.size}")
634 w.plot_fit()
635 parameters.SAVE = False
637 # Optimize the regularisation parameter only if it was not done before
638 if w.amplitude_priors_method == "spectrum" and w.reg == parameters.PSF_FIT_REG_PARAM: # pragma: no cover
639 w_reg = RegFitWorkspace(w, opt_reg=parameters.PSF_FIT_REG_PARAM, verbose=1)
640 run_minimisation(w_reg, method="minimize", ftol=1e-4, xtol=1e-2, verbose=1, epsilon=[1e-1],
641 minimizer_method="Nelder-Mead")
642 w_reg.opt_reg = 10 ** w_reg.p[0]
643 w.my_logger.info(f"\n\tOptimal regularisation parameter: {w_reg.opt_reg}")
644 w.reg = np.copy(w_reg.opt_reg)
645 w.simulate(*w.p)
646 w.opt_reg = w_reg.opt_reg
647 if np.trace(w.amplitude_cov_matrix) < np.trace(w.amplitude_priors_cov_matrix):
648 w.my_logger.warning(
649 f"\n\tTrace of final covariance matrix ({np.trace(w.amplitude_cov_matrix)}) is "
650 f"below the trace of the prior covariance matrix "
651 f"({np.trace(w.amplitude_priors_cov_matrix)}). This is probably due to a very "
652 f"high regularisation parameter in case of a bad fit. Therefore the final "
653 f"covariance matrix is mulitiplied by the ratio of the traces and "
654 f"the amplitude parameters are very close the amplitude priors.")
655 r = np.trace(w.amplitude_priors_cov_matrix) / np.trace(w.amplitude_cov_matrix)
656 w.amplitude_cov_matrix *= r
657 w.amplitude_params_err = np.array(
658 [np.sqrt(w.amplitude_cov_matrix[x, x]) for x in range(w.Nx)])
660 # Save results
661 x, model, model_err = w.simulate(*w.p)
663 # Propagate uncertainties
664 # from spectractor.tools import plot_correlation_matrix_simple, compute_correlation_matrix
665 # M = np.copy(w.M)
666 # amplitude_params = np.copy(w.amplitude_params)
667 # ipar = np.array(np.where(np.array(w.fixed).astype(int) == 0)[0])
668 # w.amplitude_priors_method = "fixed"
669 # jac = w.jacobian(w.p, epsilon=epsilon, fixed_params=w.fixed, model_input=[x, model, model_err])
670 # jac = jac[ipar]
671 # start = jac.shape[0]
672 # J = np.hstack([jac.T, M])
673 # H = (J.T * w.W) @ J
674 # H[start:, start:] += w.reg*w.Q
675 # full_cov_matrix = np.linalg.inv(H)
676 # amplitude_params_err = np.array([np.sqrt(full_cov_matrix[start+x, start+x]) for x in range(w.Nx)])
677 # plt.errorbar(w.lambdas, amplitude_params, yerr=amplitude_params_err)
678 # plt.grid()
679 # plt.show()
680 # plt.figure()
681 # plot_correlation_matrix_simple(ax=plt.gca(), rho=compute_correlation_matrix(full_cov_matrix))
682 # plt.show()
683 # w.amplitude_params = amplitude_params
684 # w.amplitude_params_err = amplitude_params_err
685 # w.amplitude_cov_matrix = full_cov_matrix[start:, start:]
687 if parameters.DEBUG:
688 w.plot_fit()
689 w.spectrum.lambdas = np.copy(w.lambdas)
690 w.spectrum.data = np.copy(w.amplitude_params)
691 w.spectrum.err = np.copy(w.amplitude_params_err)
692 w.spectrum.cov_matrix = np.copy(w.amplitude_cov_matrix)
693 w.spectrum.chromatic_psf.fill_table_with_profile_params(w.psf_profile_params)
694 w.spectrum.chromatic_psf.from_profile_params_to_shape_params(w.psf_profile_params)
695 w.spectrum.spectrogram_fit = w.model
696 w.spectrum.spectrogram_residuals = (w.data - w.spectrum.spectrogram_fit) / w.err
697 w.spectrum.header['CHI2_FIT'] = w.costs[-1] / w.data.size
698 w.spectrum.header['PIXSHIFT'] = w.p[2]
699 w.spectrum.header['D2CCD'] = w.p[1]
700 w.spectrum.header['A2_FIT'] = w.p[0]
701 w.spectrum.header["ROTANGLE"] = w.p[4]
703 return w.spectrum
706def Spectractor(file_name, output_directory, target_label, guess=None, disperser_label="", config="",
707 atmospheric_lines=True):
708 """ Spectractor
709 Main function to extract a spectrum from an image
711 Parameters
712 ----------
713 file_name: str
714 Input file nam of the image to analyse.
715 output_directory: str
716 Output directory.
717 target_label: str
718 The name of the targeted object.
719 guess: [int,int], optional
720 [x0,y0] list of the guessed pixel positions of the target in the image (must be integers). Mandatory if
721 WCS solution is absent (default: None).
722 disperser_label: str, optional
723 The name of the disperser (default: "").
724 config: str
725 The config file name (default: "./config/ctio.ini").
726 atmospheric_lines: bool, optional
727 If True atmospheric lines are used in the calibration fit.
729 Returns
730 -------
731 spectrum: Spectrum
732 The extracted spectrum object.
734 Examples
735 --------
737 Extract the spectrogram and its characteristics from the image:
739 .. doctest::
741 >>> import os
742 >>> from spectractor.logbook import LogBook
743 >>> logbook = LogBook(logbook='./ctiofulllogbook_jun2017_v5.csv')
744 >>> file_names = ['./tests/data/reduc_20170530_134.fits']
745 >>> for file_name in file_names:
746 ... tag = file_name.split('/')[-1]
747 ... disperser_label, target_label, xpos, ypos = logbook.search_for_image(tag)
748 ... if target_label is None or xpos is None or ypos is None:
749 ... continue
750 ... spectrum = Spectractor(file_name, './tests/data/', guess=[xpos, ypos], target_label=target_label,
751 ... disperser_label=disperser_label, config='./config/ctio.ini')
753 .. doctest::
754 :hide:
756 >>> assert spectrum is not None
757 >>> assert os.path.isfile('tests/data/reduc_20170530_134_spectrum.fits')
759 """
761 my_logger = set_logger(__name__)
762 my_logger.info('\n\tStart SPECTRACTOR')
763 # Load config file
764 if config != "":
765 load_config(config)
766 if parameters.LSST_SAVEFIGPATH: # pragma: no cover
767 ensure_dir(parameters.LSST_SAVEFIGPATH)
769 # Load reduced image
770 image = Image(file_name, target_label=target_label, disperser_label=disperser_label)
771 if guess is not None and image.target_guess is None:
772 image.target_guess = np.asarray(guess)
773 if image.target_guess is None:
774 from scipy.signal import medfilt2d
775 data = medfilt2d(image.data.T, kernel_size=9)
776 image.target_guess = np.unravel_index(np.argmax(data), data.shape)
777 my_logger.info(f"\n\tNo guess position of order 0 has been given. Assuming the spectrum to extract comes "
778 f"from the brightest object, guess position is set as {image.target_guess}.")
779 if parameters.DEBUG:
780 image.plot_image(scale='symlog', target_pixcoords=image.target_guess)
782 # Use fast mode
783 if parameters.CCD_REBIN > 1:
784 image = set_fast_mode(image)
785 if parameters.DEBUG:
786 image.plot_image(scale='symlog', target_pixcoords=image.target_guess)
788 # Set output path
789 ensure_dir(output_directory)
790 output_filename = file_name.split('/')[-1]
791 output_filename = output_filename.replace('.fits', '_spectrum.fits')
792 output_filename = output_filename.replace('.fz', '_spectrum.fits')
793 output_filename = os.path.join(output_directory, output_filename)
794 output_filename_spectrogram = output_filename.replace('spectrum', 'spectrogram')
795 output_filename_psf = output_filename.replace('spectrum.fits', 'table.csv')
796 # Find the exact target position in the raw cut image: several methods
797 my_logger.info(f'\n\tSearch for the target in the image with guess={image.target_guess}...')
798 find_target(image, image.target_guess, use_wcs=True, widths=(parameters.XWINDOW, parameters.YWINDOW))
799 # Rotate the image
800 turn_image(image)
801 # Find the exact target position in the rotated image: several methods
802 my_logger.info('\n\tSearch for the target in the rotated image...')
803 find_target(image, image.target_guess, rotated=True, use_wcs=False,
804 widths=(parameters.XWINDOW_ROT, parameters.YWINDOW_ROT))
805 # Create Spectrum object
806 spectrum = Spectrum(image=image, order=parameters.SPEC_ORDER)
807 # Subtract background and bad pixels
808 extract_spectrum_from_image(image, spectrum, signal_width=parameters.PIXWIDTH_SIGNAL,
809 ws=(parameters.PIXDIST_BACKGROUND,
810 parameters.PIXDIST_BACKGROUND + parameters.PIXWIDTH_BACKGROUND),
811 right_edge=parameters.CCD_IMSIZE)
812 spectrum.atmospheric_lines = atmospheric_lines
814 # Calibrate the spectrum
815 my_logger.info(f'\n\tCalibrating order {spectrum.order:d} spectrum...')
816 with_adr = True
817 if parameters.OBS_OBJECT_TYPE != "STAR":
818 with_adr = False
819 calibrate_spectrum(spectrum, with_adr=with_adr)
820 spectrum.data_order2 = np.zeros_like(spectrum.lambdas_order2)
821 spectrum.err_order2 = np.zeros_like(spectrum.lambdas_order2)
823 # Full forward model extraction: add transverse ADR and order 2 subtraction
824 if parameters.PSF_EXTRACTION_MODE == "PSF_2D" and parameters.OBS_OBJECT_TYPE == "STAR":
825 w = FullForwardModelFitWorkspace(spectrum, verbose=1, plot=True, live_fit=False,
826 amplitude_priors_method="spectrum")
827 for i in range(2):
828 spectrum.convert_from_flam_to_ADUrate()
829 spectrum = run_ffm_minimisation(w, method="newton")
831 # Calibrate the spectrum
832 calibrate_spectrum(spectrum, with_adr=False)
833 w.p[1] = spectrum.disperser.D
834 w.p[2] = spectrum.header['PIXSHIFT']
836 # Recompute and save params in class attributes
837 w.simulate(*w.p)
839 # Propagate parameters
840 A2, D2CCD, dx0, dy0, angle, B, *poly_params = w.p
841 w.spectrum.rotation_angle = angle
842 w.spectrum.spectrogram_bgd *= B
843 w.spectrum.spectrogram_bgd_rms *= B
844 w.spectrum.spectrogram_x0 += dx0
845 w.spectrum.spectrogram_y0 += dy0
846 w.spectrum.x0[0] += dx0
847 w.spectrum.x0[1] += dy0
848 w.spectrum.header["TARGETX"] = w.spectrum.x0[0]
849 w.spectrum.header["TARGETY"] = w.spectrum.x0[1]
851 # Compute order 2 contamination
852 w.spectrum.lambdas_order2 = w.lambdas
853 w.spectrum.data_order2 = A2 * w.amplitude_params * w.spectrum.disperser.ratio_order_2over1(w.lambdas)
854 w.spectrum.err_order2 = A2 * w.amplitude_params_err * w.spectrum.disperser.ratio_order_2over1(w.lambdas)
856 # Compare with truth if available
857 if parameters.PSF_EXTRACTION_MODE == "PSF_2D" and 'LBDAS_T' in spectrum.header and parameters.DEBUG:
858 plot_comparison_truth(spectrum, w)
860 # Save the spectrum
861 spectrum.save_spectrum(output_filename, overwrite=True)
862 spectrum.save_spectrogram(output_filename_spectrogram, overwrite=True)
863 spectrum.lines.print_detected_lines(output_file_name=output_filename.replace('_spectrum.fits', '_lines.csv'),
864 overwrite=True, amplitude_units=spectrum.units)
866 # Plot the spectrum
867 if parameters.VERBOSE and parameters.DISPLAY:
868 spectrum.plot_spectrum(xlim=None)
869 spectrum.chromatic_psf.table['lambdas'] = spectrum.lambdas
870 spectrum.chromatic_psf.table.write(output_filename_psf, overwrite=True)
872 return spectrum
875def extract_spectrum_from_image(image, spectrum, signal_width=10, ws=(20, 30), right_edge=parameters.CCD_IMSIZE):
876 """Extract the 1D spectrum from the image.
878 Method : remove a uniform background estimated from the rectangular lateral bands
880 The spectrum amplitude is the sum of the pixels in the 2*w rectangular window
881 centered on the order 0 y position.
882 The up and down backgrounds are estimated as the median in rectangular regions
883 above and below the spectrum, in the ws-defined rectangular regions; stars are filtered
884 as nan values using an hessian analysis of the image to remove structures.
885 The subtracted background is the mean of the two up and down backgrounds.
886 Stars are filtered.
888 Prerequisites: the target position must have been found before, and the
889 image turned to have an horizontal dispersion line
891 Parameters
892 ----------
893 image: Image
894 Image object from which to extract the spectrum
895 spectrum: Spectrum
896 Spectrum object to store new wavelengths, data and error arrays
897 signal_width: int
898 Half width of central region where the spectrum is extracted and summed (default: 10)
899 ws: list
900 up/down region extension where the sky background is estimated with format [int, int] (default: [20,30])
901 right_edge: int
902 Right-hand pixel position above which no pixel should be used (default: parameters.CCD_IMSIZE)
903 """
905 if parameters.PSF_EXTRACTION_MODE != "PSF_1D" and parameters.PSF_EXTRACTION_MODE != "PSF_2D":
906 raise NotImplementedError(f"PSF_EXTRACTION_MODE must PSF_1D or PSF_2D. Found {parameters.PSF_EXTRACTION_MODE}.")
908 my_logger = set_logger(__name__)
909 if ws is None:
910 ws = [signal_width + 20, signal_width + 30]
911 my_logger.info(
912 f'\n\tExtracting spectrum from image: spectrum with width 2*{signal_width:d} pixels '
913 f'and background from {ws[0]:d} to {ws[1]:d} pixels')
915 # Make a data copy
916 data = np.copy(image.data_rotated)[:, 0:right_edge]
917 err = np.copy(image.stat_errors_rotated)[:, 0:right_edge]
919 # Lateral bands to remove sky background
920 Ny, Nx = data.shape
921 y0 = int(image.target_pixcoords_rotated[1])
922 ymax = min(Ny, y0 + ws[1])
923 ymin = max(0, y0 - ws[1])
925 # Roughly estimates the wavelengths and set start 0 nm before parameters.LAMBDA_MIN
926 # and end 0 nm after parameters.LAMBDA_MAX
927 if spectrum.order < 0:
928 distance = np.sign(spectrum.order)*(np.arange(Nx) - image.target_pixcoords_rotated[0])
929 lambdas = image.disperser.grating_pixel_to_lambda(distance, x0=image.target_pixcoords, order=spectrum.order)
930 lambda_min_index = int(np.argmin(np.abs(lambdas[::np.sign(spectrum.order)] - parameters.LAMBDA_MIN)))
931 lambda_max_index = int(np.argmin(np.abs(lambdas[::np.sign(spectrum.order)] - parameters.LAMBDA_MAX)))
932 xmin = max(0, int(distance[lambda_min_index]))
933 xmax = min(right_edge, int(distance[lambda_max_index]) + 1) # +1 to include edges
934 else:
935 lambdas = image.disperser.grating_pixel_to_lambda(np.arange(Nx) - image.target_pixcoords_rotated[0], x0=image.target_pixcoords,
936 order=spectrum.order)
937 xmin = int(np.argmin(np.abs(lambdas - parameters.LAMBDA_MIN)))
938 xmax = int(np.argmin(np.abs(lambdas - parameters.LAMBDA_MAX)))
940 # Create spectrogram
941 data = data[ymin:ymax, xmin:xmax]
942 err = err[ymin:ymax, xmin:xmax]
943 Ny, Nx = data.shape
944 my_logger.info(f'\n\tExtract spectrogram: crop rotated image [{xmin}:{xmax},{ymin}:{ymax}] (size ({Nx}, {Ny}))')
946 # Position of the order 0 in the spectrogram coordinates
947 target_pixcoords_spectrogram = [image.target_pixcoords_rotated[0] - xmin, image.target_pixcoords_rotated[1] - ymin]
949 # Extract the background on the rotated image
950 bgd_model_func, bgd_res, bgd_rms = extract_spectrogram_background_sextractor(data, err, ws=ws)
951 # while np.nanmean(bgd_res)/np.nanstd(bgd_res) < -0.2 and parameters.PIXWIDTH_BOXSIZE >= 5:
952 while (np.abs(np.nanmean(bgd_res)) > 0.5 or np.nanstd(bgd_res) > 1.3) and parameters.PIXWIDTH_BOXSIZE > 5:
953 parameters.PIXWIDTH_BOXSIZE = max(5, parameters.PIXWIDTH_BOXSIZE // 2)
954 my_logger.debug(f"\n\tPull distribution of background residuals differs too much from mean=0 and std=1. "
955 f"\n\t\tmean={np.nanmean(bgd_res):.3g}; std={np.nanstd(bgd_res):.3g}"
956 f"\n\tThese value should be smaller in absolute value than 0.5 and 1.3. "
957 f"\n\tTo do so, parameters.PIXWIDTH_BOXSIZE is divided "
958 f"by 2 from {parameters.PIXWIDTH_BOXSIZE * 2} -> {parameters.PIXWIDTH_BOXSIZE}.")
959 bgd_model_func, bgd_res, bgd_rms = extract_spectrogram_background_sextractor(data, err, ws=ws)
961 # Propagate background uncertainties
962 err = np.sqrt(err * err + bgd_rms * bgd_rms)
964 # Fit the transverse profile
965 my_logger.info(f'\n\tStart PSF1D transverse fit...')
966 psf = load_PSF(psf_type=parameters.PSF_TYPE, target=image.target)
967 s = ChromaticPSF(psf, Nx=Nx, Ny=Ny, x0=target_pixcoords_spectrogram[0], y0=target_pixcoords_spectrogram[1],
968 deg=parameters.PSF_POLY_ORDER, saturation=image.saturation)
969 verbose = copy.copy(parameters.VERBOSE)
970 debug = copy.copy(parameters.DEBUG)
971 parameters.VERBOSE = False
972 parameters.DEBUG = False
973 s.fit_transverse_PSF1D_profile(data, err, signal_width, ws, pixel_step=parameters.PSF_PIXEL_STEP_TRANSVERSE_FIT,
974 sigma_clip=5, bgd_model_func=bgd_model_func, saturation=image.saturation,
975 live_fit=False)
976 parameters.VERBOSE = verbose
977 parameters.DEBUG = debug
979 # Fill spectrum object
980 spectrum.pixels = np.arange(xmin, xmax, 1).astype(int)
981 spectrum.data = np.copy(s.table['amplitude'])
982 spectrum.err = np.copy(s.table['flux_err'])
983 my_logger.debug(f'\n\tTransverse fit table:\n{s.table}')
984 if parameters.DEBUG:
985 s.plot_summary()
987 # Fit the data:
988 method = "noprior"
989 mode = "1D"
990 my_logger.info(f'\n\tStart ChromaticPSF polynomial fit with '
991 f'mode={mode} and amplitude_priors_method={method}...')
992 w = s.fit_chromatic_psf(data, bgd_model_func=bgd_model_func, data_errors=err,
993 amplitude_priors_method=method, mode=mode, verbose=parameters.VERBOSE)
994 spectrum.data = np.copy(w.amplitude_params)
995 spectrum.err = np.copy(w.amplitude_params_err)
996 spectrum.cov_matrix = np.copy(w.amplitude_cov_matrix)
997 spectrum.chromatic_psf = s
999 Dx_rot = spectrum.pixels.astype(float) - image.target_pixcoords_rotated[0]
1000 s.table['Dx'] = np.copy(Dx_rot)
1001 s.table['Dy'] = s.table['y_c'] - (image.target_pixcoords_rotated[1] - ymin)
1002 s.table['Dy_disp_axis'] = 0
1003 s.table['Dy_fwhm_inf'] = s.table['Dy'] - 0.5 * s.table['fwhm']
1004 s.table['Dy_fwhm_sup'] = s.table['Dy'] + 0.5 * s.table['fwhm']
1005 my_logger.debug(f"\n\tTransverse fit table before derotation:"
1006 f"\n{s.table[['amplitude', 'x_c', 'y_c', 'Dx', 'Dy', 'Dy_disp_axis']]}")
1008 # Rotate and save the table
1009 s.rotate_table(-image.rotation_angle)
1010 flux = np.copy(s.table["amplitude"])
1011 flux_err = np.copy(s.table["flux_err"])
1013 # Extract the spectrogram edges
1014 data = np.copy(image.data)[:, 0:right_edge]
1015 err = np.copy(image.stat_errors)[:, 0:right_edge]
1016 Ny, Nx = data.shape
1017 x0 = int(image.target_pixcoords[0])
1018 y0 = int(image.target_pixcoords[1])
1019 ymax = min(Ny, y0 + int(s.table['Dy_disp_axis'].max()) + ws[1] + 1) # +1 to include edges
1020 ymin = max(0, y0 + int(s.table['Dy_disp_axis'].min()) - ws[1])
1021 distance = s.get_algebraic_distance_along_dispersion_axis()
1022 lambdas = image.disperser.grating_pixel_to_lambda(distance, x0=image.target_pixcoords, order=spectrum.order)
1023 lambda_min_index = int(np.argmin(np.abs(lambdas[::np.sign(spectrum.order)] - parameters.LAMBDA_MIN)))
1024 lambda_max_index = int(np.argmin(np.abs(lambdas[::np.sign(spectrum.order)] - parameters.LAMBDA_MAX)))
1025 xmin = max(0, int(s.table['Dx'][lambda_min_index] + x0))
1026 xmax = min(right_edge, int(s.table['Dx'][lambda_max_index] + x0) + 1) # +1 to include edges
1028 # Position of the order 0 in the spectrogram coordinates
1029 target_pixcoords_spectrogram = [image.target_pixcoords[0] - xmin, image.target_pixcoords[1] - ymin]
1030 s.y0 = target_pixcoords_spectrogram[1]
1031 s.x0 = target_pixcoords_spectrogram[0]
1033 # Update y_c and x_c after rotation
1034 s.table['y_c'] = s.table['Dy'] + target_pixcoords_spectrogram[1]
1035 s.table['x_c'] = s.table['Dx'] + target_pixcoords_spectrogram[0]
1036 my_logger.debug(f"\n\tTransverse fit table after derotation:"
1037 f"\n{s.table[['amplitude', 'x_c', 'y_c', 'Dx', 'Dy', 'Dy_disp_axis']]}")
1039 # Create spectrogram
1040 data = data[ymin:ymax, xmin:xmax]
1041 err = err[ymin:ymax, xmin:xmax]
1042 Ny, Nx = data.shape
1043 my_logger.info(f'\n\tExtract spectrogram: crop raw image [{xmin}:{xmax},{ymin}:{ymax}] (size ({Nx}, {Ny}))')
1045 # Extract the non rotated background
1046 bgd_model_func, bgd_res, bgd_rms = extract_spectrogram_background_sextractor(data, err, ws=ws)
1047 bgd = bgd_model_func(np.arange(Nx), np.arange(Ny))
1048 my_logger.info(f"\n\tBackground statistics: mean={np.nanmean(bgd):.3f} {image.units}, "
1049 f"RMS={np.nanmean(bgd_rms):.3f} {image.units}.")
1051 # Propagate background uncertainties
1052 err = np.sqrt(err * err + bgd_rms * bgd_rms)
1054 # 2D extraction
1055 opt_reg = -1
1056 if parameters.PSF_EXTRACTION_MODE == "PSF_2D":
1057 # build 1D priors
1058 psf_poly_priors = s.from_table_to_poly_params()[s.Nx:]
1059 Dy_disp_axis = np.copy(s.table["Dy_disp_axis"])
1060 # initialize a new ChromaticPSF
1061 s = ChromaticPSF(psf, Nx=Nx, Ny=Ny, x0=target_pixcoords_spectrogram[0], y0=target_pixcoords_spectrogram[1],
1062 deg=parameters.PSF_POLY_ORDER, saturation=image.saturation)
1063 # fill a first table with first guess
1064 s.table['Dx'] = (np.arange(xmin, xmax, 1) - image.target_pixcoords[0])[:len(s.table['Dx'])]
1065 s.table["amplitude"] = np.interp(s.table['Dx'], Dx_rot, flux)
1066 s.table["flux_sum"] = np.interp(s.table['Dx'], Dx_rot, flux)
1067 s.table["flux_err"] = np.interp(s.table['Dx'], Dx_rot, flux_err)
1068 s.table['Dy_disp_axis'] = np.interp(s.table['Dx'], Dx_rot, Dy_disp_axis)
1069 s.poly_params = np.concatenate((s.table["amplitude"], psf_poly_priors))
1070 s.cov_matrix = np.copy(w.amplitude_cov_matrix)
1071 s.profile_params = s.from_poly_params_to_profile_params(s.poly_params, apply_bounds=True)
1072 s.fill_table_with_profile_params(s.profile_params)
1073 s.table['Dy'] = s.table['y_c'] - target_pixcoords_spectrogram[1]
1074 # deconvolve and regularize with 1D priors
1075 method = "psf1d"
1076 mode = "2D"
1077 my_logger.debug(f"\n\tTransverse fit table before PSF_2D fit:"
1078 f"\n{s.table[['amplitude', 'x_c', 'y_c', 'Dx', 'Dy', 'Dy_disp_axis']]}")
1079 my_logger.info(f'\n\tStart ChromaticPSF polynomial fit with '
1080 f'mode={mode} and amplitude_priors_method={method}...')
1081 w = s.fit_chromatic_psf(data, bgd_model_func=bgd_model_func, data_errors=err, live_fit=False,
1082 amplitude_priors_method=method, mode=mode, verbose=parameters.VERBOSE)
1083 # save results
1084 spectrum.spectrogram_fit = s.evaluate(s.poly_params, mode=mode)
1085 spectrum.spectrogram_residuals = (data - spectrum.spectrogram_fit - bgd_model_func(np.arange(Nx),
1086 np.arange(Ny))) / err
1087 spectrum.data = np.copy(w.amplitude_params)
1088 spectrum.err = np.copy(w.amplitude_params_err)
1089 spectrum.cov_matrix = np.copy(w.amplitude_cov_matrix)
1090 spectrum.pixels = np.copy(s.table['Dx'])
1091 s.table['Dy'] = s.table['y_c'] - target_pixcoords_spectrogram[1]
1092 s.table['Dy_fwhm_inf'] = s.table['Dy'] - 0.5 * s.table['fwhm']
1093 s.table['Dy_fwhm_sup'] = s.table['Dy'] + 0.5 * s.table['fwhm']
1094 spectrum.chromatic_psf = s
1095 opt_reg = s.opt_reg
1096 spectrum.header['PSF_REG'] = opt_reg
1098 # First guess for lambdas
1099 first_guess_lambdas = image.disperser.grating_pixel_to_lambda(s.get_algebraic_distance_along_dispersion_axis(),
1100 x0=image.target_pixcoords, order=spectrum.order)
1101 s.table['lambdas'] = first_guess_lambdas
1102 spectrum.lambdas = np.array(first_guess_lambdas)
1104 # Position of the order 0 in the spectrogram coordinates
1105 my_logger.info(f'\n\tExtract spectrogram: crop image [{xmin}:{xmax},{ymin}:{ymax}] (size ({Nx}, {Ny}))'
1106 f'\n\tNew target position in spectrogram frame: {target_pixcoords_spectrogram}')
1108 # Save results
1109 spectrum.spectrogram = data
1110 spectrum.spectrogram_err = err
1111 spectrum.spectrogram_bgd = bgd
1112 spectrum.spectrogram_bgd_rms = bgd_rms
1113 spectrum.spectrogram_x0 = target_pixcoords_spectrogram[0]
1114 spectrum.spectrogram_y0 = target_pixcoords_spectrogram[1]
1115 spectrum.spectrogram_xmin = xmin
1116 spectrum.spectrogram_xmax = xmax
1117 spectrum.spectrogram_ymin = ymin
1118 spectrum.spectrogram_ymax = ymax
1119 spectrum.spectrogram_deg = spectrum.chromatic_psf.deg
1120 spectrum.spectrogram_saturation = spectrum.chromatic_psf.saturation
1122 # Plot FHWM(lambda)
1123 if parameters.DEBUG:
1124 fig, ax = plt.subplots(2, 1, figsize=(10, 8), sharex="all")
1125 ax[0].plot(spectrum.lambdas, np.array(s.table['fwhm']))
1126 ax[0].set_xlabel(r"$\lambda$ [nm]")
1127 ax[0].set_ylabel("Transverse FWHM [pixels]")
1128 ax[0].set_ylim((0.8 * np.min(s.table['fwhm']), 1.2 * np.max(s.table['fwhm']))) # [-10:])))
1129 ax[0].grid()
1130 ax[1].plot(spectrum.lambdas, np.array(s.table['y_c']))
1131 ax[1].set_xlabel(r"$\lambda$ [nm]")
1132 ax[1].set_ylabel("Distance from mean dispersion axis [pixels]")
1133 # ax[1].set_ylim((0.8*np.min(s.table['Dy']), 1.2*np.max(s.table['fwhm'][-10:])))
1134 ax[1].grid()
1135 if parameters.DISPLAY:
1136 plt.show()
1137 if parameters.LSST_SAVEFIGPATH:
1138 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'fwhm.pdf'))
1140 # Summary plot
1141 if parameters.DEBUG or parameters.LSST_SAVEFIGPATH:
1142 gs_kw = dict(width_ratios=[3, 0.08], height_ratios=[1, 1, 1])
1143 fig, ax = plt.subplots(3, 2, sharex='none', figsize=(12, 6), gridspec_kw=gs_kw)
1144 xx = np.arange(s.table['Dx'].size)
1145 plot_image_simple(ax[2, 0], data=data, scale="symlog", title='', units=image.units, aspect='auto', cax=ax[2, 1])
1146 ax[2, 0].plot(xx, target_pixcoords_spectrogram[1] + s.table['Dy_disp_axis'], label='Dispersion axis', color="r")
1147 ax[2, 0].scatter(xx, target_pixcoords_spectrogram[1] + s.table['Dy'],
1148 c=s.table['lambdas'], edgecolors='None', cmap=from_lambda_to_colormap(s.table['lambdas']),
1149 label='Fitted spectrum centers', marker='o', s=10)
1150 ax[2, 0].plot(xx, target_pixcoords_spectrogram[1] + s.table['Dy_fwhm_inf'], 'k-', label='Fitted FWHM')
1151 ax[2, 0].plot(xx, target_pixcoords_spectrogram[1] + s.table['Dy_fwhm_sup'], 'k-', label='')
1152 ax[2, 0].set_ylim(0.5 * Ny - signal_width, 0.5 * Ny + signal_width)
1153 ax[2, 0].set_xlim(0, xx.size)
1154 ax[2, 0].legend(loc='best')
1155 plot_spectrum_simple(ax[0, 0], spectrum.lambdas, spectrum.data, data_err=spectrum.err,
1156 units=image.units, label='Fitted spectrum')
1157 ax[0, 0].plot(spectrum.lambdas, s.table['flux_sum'], 'k-', label='Cross spectrum')
1158 ax[1, 0].set_xlabel(r"$\lambda$ [nm]")
1159 ax[0, 0].legend(loc='best')
1160 ax[1, 0].plot(spectrum.lambdas, (s.table['flux_sum'] - s.table['flux_integral']) / s.table['flux_sum'],
1161 label='(model_integral-cross_sum)/cross_sum')
1162 ax[1, 0].legend()
1163 ax[1, 0].grid(True)
1164 ax[1, 0].set_xlim(ax[0, 0].get_xlim())
1165 ax[1, 0].set_ylim(-1, 1)
1166 ax[1, 0].set_ylabel('Relative difference')
1167 fig.tight_layout()
1168 # fig.subplots_adjust(hspace=0)
1169 pos0 = ax[0, 0].get_position()
1170 pos1 = ax[1, 0].get_position()
1171 pos2 = ax[2, 0].get_position()
1172 ax[0, 0].set_position([pos2.x0, pos0.y0, pos2.width, pos0.height])
1173 ax[1, 0].set_position([pos2.x0, pos1.y0, pos2.width, pos1.height])
1174 ax[0, 1].remove()
1175 ax[1, 1].remove()
1176 if parameters.DISPLAY:
1177 plt.show()
1178 if parameters.LSST_SAVEFIGPATH:
1179 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'intermediate_spectrum.pdf'))
1181 return w
1184def plot_comparison_truth(spectrum, w): # pragma: no cover
1185 s = spectrum.chromatic_psf
1186 lambdas_truth = np.fromstring(spectrum.header['LBDAS_T'][1:-1], sep=' ')
1187 psf_poly_truth = np.fromstring(spectrum.header['PSF_P_T'][1:-1], sep=' ', dtype=float)
1188 deg_truth = int(spectrum.header["PSF_DEG"])
1189 psf_poly_truth[-1] = spectrum.spectrogram_saturation
1190 amplitude_truth = np.fromstring(spectrum.header['AMPLIS_T'][1:-1], sep=' ', dtype=float)
1191 amplitude_truth *= parameters.FLAM_TO_ADURATE * lambdas_truth * np.gradient(lambdas_truth)
1192 s0 = ChromaticPSF(s.psf, lambdas_truth.size, s.Ny, deg=deg_truth,
1193 saturation=spectrum.spectrogram_saturation)
1194 s0.poly_params = np.asarray(list(amplitude_truth) + list(psf_poly_truth))
1195 s0.deg = (len(s0.poly_params[s0.Nx:]) - 1) // (len(s0.psf.param_names) - 2) - 1
1196 s0.set_polynomial_degrees(s0.deg)
1197 s0.profile_params = s0.from_poly_params_to_profile_params(s0.poly_params)
1198 s0.from_profile_params_to_shape_params(s0.profile_params)
1199 gs_kw = dict(width_ratios=[2, 1], height_ratios=[2, 1])
1200 fig, ax = plt.subplots(2, 2, figsize=(9, 5), sharex="all", gridspec_kw=gs_kw)
1201 ax[0, 0].plot(lambdas_truth, amplitude_truth, label="truth")
1202 amplitude_priors_err = [np.sqrt(w.amplitude_priors_cov_matrix[x, x]) for x in range(w.Nx)]
1203 ax[0, 0].errorbar(spectrum.lambdas, w.amplitude_priors, yerr=amplitude_priors_err, label="prior")
1204 ax[0, 0].errorbar(spectrum.lambdas, w.amplitude_params, yerr=w.amplitude_params_err, label="2D")
1205 ax[0, 0].grid()
1206 ax[0, 0].legend()
1207 ax[0, 0].set_xlabel(r"$\lambda$ [nm]")
1208 ax[0, 0].set_ylabel(f"Amplitude $A$ [ADU/s]")
1209 ax[1, 0].plot(lambdas_truth, np.zeros_like(lambdas_truth), label="truth")
1210 amplitude_truth_interp = np.interp(spectrum.lambdas, lambdas_truth, amplitude_truth)
1211 res = (w.amplitude_priors - amplitude_truth_interp) / amplitude_priors_err
1212 ax[1, 0].errorbar(spectrum.lambdas, res, yerr=np.ones_like(res),
1213 label=f"prior: mean={np.mean(res):.2f}, std={np.std(res):.2f}")
1214 res = (w.amplitude_params - amplitude_truth_interp) / w.amplitude_params_err
1215 ax[1, 0].errorbar(spectrum.lambdas, res, yerr=np.ones_like(res),
1216 label=f"2D: mean={np.mean(res):.2f}, std={np.std(res):.2f}")
1217 ax[1, 0].grid()
1218 ax[1, 0].legend()
1219 ax[1, 0].set_xlabel(r"$\lambda$ [nm]")
1220 ax[1, 0].set_ylim(-5, 5)
1221 ax[1, 0].set_ylabel(r"$(A - A_{\rm truth})/\sigma_A$")
1223 fwhm_truth = np.interp(spectrum.lambdas, lambdas_truth, s0.table["fwhm"])
1224 # fwhm_prior = np.interp(spectrum.lambdas, np.arange(w.amplitude_priors.size), w.fwhm_priors)
1225 # fwhm_1d = np.interp(np.arange(len(s.table)), np.arange(w.fwhm_1d.size), w.fwhm_1d)
1226 # fwhm_2d = np.interp(np.arange(len(s.table)), np.arange(s.Nx), fwhm_1d)
1227 ax[0, 1].plot(lambdas_truth, s0.table["fwhm"], label="truth")
1228 ax[0, 1].plot(spectrum.lambdas, w.fwhm_priors, label="prior")
1229 ax[0, 1].plot(spectrum.lambdas, s.table["fwhm"], label="fit")
1230 ax[0, 1].grid()
1231 ax[0, 1].set_ylim(0, 10)
1232 ax[0, 1].legend()
1233 ax[0, 1].set_xlabel(r"$\lambda$ [nm]")
1234 ax[1, 1].set_xlabel(r"$\lambda$ [nm]")
1235 ax[0, 1].set_ylabel(f"FWHM [pix]")
1236 ax[1, 1].set_ylabel(r"FWHM - FWHM$_{\rm truth}$ [pix]")
1237 ax[1, 1].plot(lambdas_truth, np.zeros_like(lambdas_truth), label="truth")
1238 ax[1, 1].plot(spectrum.lambdas, w.fwhm_priors - fwhm_truth, label="prior")
1239 ax[1, 1].plot(spectrum.lambdas, s.table["fwhm"] - fwhm_truth, label="2D")
1240 ax[1, 1].grid()
1241 ax[1, 1].set_ylim(-0.5, 0.5)
1242 ax[1, 1].legend()
1243 plt.subplots_adjust(hspace=0)
1244 fig.tight_layout()
1245 if parameters.DISPLAY:
1246 plt.show()
1247 if parameters.LSST_SAVEFIGPATH:
1248 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'deconvolution_truth.pdf'))
1249 plt.show()
1252def set_fast_mode(image):
1253 """Set the parameters for a fast mode run of Spectractor.
1255 Parameters
1256 ----------
1257 image: Image
1259 Returns
1260 -------
1261 image: Image
1263 """
1264 new_shape = np.asarray(image.data.shape) // parameters.CCD_REBIN
1265 image.data = rebin(image.data, new_shape)
1266 image.stat_errors = np.sqrt(rebin(image.stat_errors ** 2, new_shape))
1267 image.target_guess = np.asarray(image.target_guess) / parameters.CCD_REBIN
1268 parameters.PIXDIST_BACKGROUND //= parameters.CCD_REBIN
1269 parameters.PIXWIDTH_BOXSIZE = max(10, parameters.PIXWIDTH_BOXSIZE // parameters.CCD_REBIN)
1270 parameters.PIXWIDTH_BACKGROUND //= parameters.CCD_REBIN
1271 parameters.PIXWIDTH_SIGNAL //= parameters.CCD_REBIN
1272 parameters.CCD_IMSIZE //= parameters.CCD_REBIN
1273 parameters.CCD_PIXEL2MM *= parameters.CCD_REBIN
1274 parameters.CCD_PIXEL2ARCSEC *= parameters.CCD_REBIN
1275 parameters.XWINDOW //= parameters.CCD_REBIN
1276 parameters.YWINDOW //= parameters.CCD_REBIN
1277 parameters.XWINDOW_ROT //= parameters.CCD_REBIN
1278 parameters.YWINDOW_ROT //= parameters.CCD_REBIN
1279 parameters.PSF_PIXEL_STEP_TRANSVERSE_FIT //= parameters.CCD_REBIN
1280 return image