Coverage for spectractor/extractor/chromaticpsf.py: 5%
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 numpy as np
2import os
3import matplotlib.pyplot as plt
4from tqdm import tqdm
6from scipy.interpolate import interp1d
8from astropy.table import Table
10from spectractor.tools import (fit_poly1d, plot_image_simple, compute_fwhm)
11from spectractor.extractor.background import extract_spectrogram_background_sextractor
12from spectractor.extractor.psf import PSF, PSFFitWorkspace, MoffatGauss, Moffat
13from spectractor import parameters
14from spectractor.config import set_logger
15from spectractor.fit.fitter import FitWorkspace, run_minimisation, run_minimisation_sigma_clipping, RegFitWorkspace
18class ChromaticPSF:
19 """Class to store a PSF evolving with wavelength.
21 The wavelength evolution is stored in an Astropy table instance. Whatever the PSF model, the common keywords are:
23 * lambdas: the wavelength [nm]
24 * Dx: the distance along X axis to order 0 position of the PSF model centroid [pixels]
25 * Dy: the distance along Y axis to order 0 position of the PSF model centroid [pixels]
26 * Dy_disp_axis: the distance along Y axis to order 0 position of the mean dispersion axis [pixels]
27 * flux_sum: the transverse sum of the data flux [spectrogram units]
28 * flux_integral: the integral of the best fitting PSF model to the data (should be equal to the amplitude parameter
29 of the PSF model if the model is correclty normalized to one) [spectrogram units]
30 * flux_err: the uncertainty on flux_sum [spectrogram units]
31 * fwhm: the FWHM of the best fitting PSF model [pixels]
32 * Dy_fwhm_sup: the distance along Y axis to order 0 position of the upper FWHM edge [pixels]
33 * Dy_fwhm_inf: the distance along Y axis to order 0 position of the lower FWHM edge [pixels]
35 Then all the specific parameter of the PSF model are stored in other columns with their wavelength evolution
36 (read from PSF.param_names attribute).
38 A saturation level should be specified in data units.
40 """
42 def __init__(self, psf, Nx, Ny, x0=0, y0=None, deg=4, saturation=None, file_name=''):
43 """Initialize a ChromaticPSF instance.
46 Parameters
47 ----------
48 psf: PSF
49 The PSF class model to build the PSF.
50 Nx: int
51 The number of pixels along the dispersion axis.
52 Ny: int
53 The number of pixels transverse to the dispersion axis.
54 x0: float
55 Relative position to pixel (0, 0) of the order 0 position along x (default: 0).
56 y0: float
57 Relative position to pixel (0, 0) of the order 0 position along y.
58 If None, y0 is set at Ny/2 (default: None).
59 deg: int, optional
60 The degree of the polynomial functions to model the chromatic evolution
61 of the PSF shape parameters (default: 4).
62 saturation: float, optional
63 The image saturation level (default: None).
64 file_name: str, optional
65 A path to a CSV file containing a ChromaticPSF table and load it (default: "").
66 """
67 self.my_logger = set_logger(self.__class__.__name__)
68 self.psf = psf
69 self.deg = -1
70 self.degrees = {}
71 self.set_polynomial_degrees(deg)
72 self.Nx = Nx
73 self.Ny = Ny
74 self.x0 = x0
75 if y0 is None:
76 y0 = Ny / 2
77 self.y0 = y0
78 self.profile_params = np.zeros((Nx, len(self.psf.param_names)))
79 self.pixels = np.mgrid[:Nx, :Ny]
80 if file_name == '':
81 arr = np.zeros((Nx, len(self.psf.param_names) + 10))
82 self.table = Table(arr, names=['lambdas', 'Dx', 'Dy', 'Dy_disp_axis', 'flux_sum', 'flux_integral',
83 'flux_err', 'fwhm', 'Dy_fwhm_sup', 'Dy_fwhm_inf'] + list(
84 self.psf.param_names))
85 else:
86 self.table = Table.read(file_name)
87 self.psf_param_start_index = 10
88 self.n_poly_params = len(self.table)
89 self.fitted_pixels = np.arange(len(self.table)).astype(int)
90 self.saturation = saturation
91 if saturation is None:
92 self.saturation = 1e20
93 self.my_logger.warning(f"\n\tSaturation level should be given to instanciate the ChromaticPSF "
94 f"object. self.saturation is set arbitrarily to 1e20. Good luck.")
95 for name in self.psf.param_names:
96 self.n_poly_params += self.degrees[name] + 1
97 self.poly_params = np.zeros(self.n_poly_params)
98 self.poly_params_labels = [] # [f"a{k}" for k in range(self.poly_params.size)]
99 self.poly_params_names = [] # "$a_{" + str(k) + "}$" for k in range(self.poly_params.size)]
100 for ip, p in enumerate(self.psf.param_names):
101 if ip == 0:
102 self.poly_params_labels += [f"{p}^{k}" for k in range(len(self.table))]
103 self.poly_params_names += \
104 ["$" + self.psf.axis_names[ip].replace("$", "") + "{(" + str(k) + ")}$"
105 for k in range(len(self.table))]
106 else:
107 for k in range(self.degrees[p] + 1):
108 self.poly_params_labels.append(f"{p}_{k}")
109 self.poly_params_names.append("$" + self.psf.axis_names[ip].replace("$", "")
110 + "^{(" + str(k) + ")}$")
111 self.opt_reg = parameters.PSF_FIT_REG_PARAM
112 self.cov_matrix = np.zeros((Nx, Nx))
113 if file_name != "":
114 self.poly_params = self.from_table_to_poly_params()
116 def set_polynomial_degrees(self, deg):
117 self.deg = deg
118 self.degrees = {key: deg for key in self.psf.param_names}
119 self.degrees['saturation'] = 0
121 def generate_test_poly_params(self):
122 """
123 A set of parameters to define a test spectrogram. PSF function must be MoffatGauss
124 for this test example.
126 Returns
127 -------
128 profile_params: array
129 The list of the test parameters
131 Examples
132 --------
134 >>> psf = MoffatGauss()
135 >>> s = ChromaticPSF(psf, Nx=5, Ny=4, deg=1, saturation=20000)
136 >>> params = s.generate_test_poly_params()
138 .. doctest::
139 :hide:
140 >>> assert(np.all(np.isclose(params,[10, 50, 100, 150, 200, 0, 0, 0, 0, 5, 0, 2, 0, -0.4, -0.4,1,0,20000])))
142 """
143 if not isinstance(self.psf, MoffatGauss) and not isinstance(self.psf, Moffat):
144 raise TypeError(f"In this test function, PSF model must be MoffatGauss or Moffat. Gave {type(self.psf)}.")
145 params = [50 * i for i in range(self.Nx)]
146 params[0] = 10
147 # add absorption lines
148 if self.Nx > 80:
149 params = list(np.array(params)
150 - 3000 * np.exp(-((np.arange(self.Nx) - 70) / 2) ** 2)
151 - 2000 * np.exp(-((np.arange(self.Nx) - 50) / 2) ** 2))
152 params += [0.] * (self.degrees['x_c'] - 1) + [0, 0] # x mean
153 params += [0.] * (self.degrees['y_c'] - 1) + [0, 0] # y mean
154 params += [0.] * (self.degrees['gamma'] - 1) + [0, 5] # gamma
155 params += [0.] * (self.degrees['alpha'] - 1) + [0, 2] # alpha
156 if isinstance(self.psf, MoffatGauss):
157 params += [0.] * (self.degrees['eta_gauss'] - 1) + [-0.4, -0.4] # eta_gauss
158 params += [0.] * (self.degrees['stddev'] - 1) + [0, 1] # stddev
159 params += [self.saturation] # saturation
160 poly_params = np.zeros_like(params)
161 poly_params[:self.Nx] = params[:self.Nx]
162 index = self.Nx - 1
163 for name in self.psf.param_names:
164 if name == 'amplitude':
165 continue
166 else:
167 shift = self.degrees[name] + 1
168 c = np.polynomial.legendre.poly2leg(params[index + shift:index:-1])
169 coeffs = np.zeros(shift)
170 coeffs[:c.size] = c
171 poly_params[index + 1:index + shift + 1] = coeffs
172 index = index + shift
173 return poly_params
175 def evaluate(self, poly_params, mode="1D"):
176 """Simulate a 2D spectrogram of size Nx times Ny.
178 Given a set of polynomial parameters defining the chromatic PSF model, a 2D spectrogram
179 is produced either summing transverse 1D PSF profiles along the dispersion axis, or
180 full 2D PSF profiles.
182 Parameters
183 ----------
184 poly_params: array_like
185 Parameter array of the model, in the form:
186 - Nx first parameters are amplitudes for the Moffat transverse profiles
187 - next parameters are polynomial coefficients for all the PSF parameters in the same order
188 as in PSF definition, except amplitude.
189 mode: str, optional
190 Set the evaluation mode: either transverse 1D PSF profile (mode="1D") or full 2D PSF profile (mode="2D").
192 Returns
193 -------
194 output: array
195 A 2D array with the model.
197 Examples
198 --------
200 >>> psf = MoffatGauss()
201 >>> s = ChromaticPSF(psf, Nx=100, Ny=20, deg=4, saturation=20000)
202 >>> poly_params = s.generate_test_poly_params()
204 1D evaluation:
206 .. doctest::
208 >>> output = s.evaluate(poly_params, mode="1D")
209 >>> im = plt.imshow(output, origin='lower') # doctest: +ELLIPSIS
210 >>> plt.colorbar(im) # doctest: +ELLIPSIS
211 <matplotlib.colorbar.Colorbar object at 0x...>
212 >>> plt.show()
214 .. plot ::
216 from spectractor.extractor.chromaticpsf import ChromaticPSF
217 from spectractor.extractor.psf import MoffatGauss
218 psf = MoffatGauss()
219 s = ChromaticPSF(psf, Nx=100, Ny=20, deg=4, saturation=20000)
220 poly_params = s.generate_test_poly_params()
221 output = s.evaluate(poly_params, mode="1D")
222 im = plt.imshow(output, origin='lower')
223 plt.colorbar(im)
224 plt.show()
226 2D evaluation:
228 .. doctest::
230 >>> output = s.evaluate(poly_params, mode="2D")
231 >>> im = plt.imshow(output, origin='lower') # doctest: +ELLIPSIS
232 >>> plt.colorbar(im) # doctest: +ELLIPSIS
233 <matplotlib.colorbar.Colorbar object at 0x...>
234 >>> plt.show()
236 .. plot ::
238 from spectractor.extractor.chromaticpsf import ChromaticPSF
239 from spectractor.extractor.psf import MoffatGauss
240 psf = MoffatGauss()
241 s = ChromaticPSF(psf, Nx=100, Ny=20, deg=4, saturation=20000)
242 poly_params = s.generate_test_poly_params()
243 output = s.evaluate(poly_params, mode="2D")
244 im = plt.imshow(output, origin='lower')
245 plt.colorbar(im)
246 plt.show()
248 """
249 if mode == "2D":
250 yy, xx = np.mgrid[:self.Ny, :self.Nx]
251 pixels = np.asarray([xx, yy])
252 elif mode == "1D":
253 pixels = np.arange(self.Ny)
254 else:
255 raise ValueError(f"Unknown evaluation mode={mode}. Must be '1D' or '2D'.")
256 self.psf.apply_max_width_to_bounds(max_half_width=self.Ny)
257 profile_params = self.from_poly_params_to_profile_params(poly_params, apply_bounds=True)
258 profile_params[:, 1] = np.arange(self.Nx) # replace x_c
259 output = np.zeros((self.Ny, self.Nx))
260 if mode == "1D":
261 for x in range(self.Nx):
262 output[:, x] = self.psf.evaluate(pixels, p=profile_params[x, :])
263 elif mode == "2D":
264 for x in range(self.Nx):
265 output += self.psf.evaluate(pixels, p=profile_params[x, :])
266 return np.clip(output, 0, self.saturation)
268 def fill_table_with_profile_params(self, profile_params):
269 """
270 Fill the table with the profile parameters.
272 Parameters
273 ----------
274 profile_params: array
275 a Nx * len(self.psf.param_names) numpy array containing the PSF parameters as a function of pixels.
277 Examples
278 --------
280 >>> psf = MoffatGauss()
281 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=4, saturation=8000)
282 >>> poly_params_test = s.generate_test_poly_params()
283 >>> profile_params = s.from_poly_params_to_profile_params(poly_params_test)
284 >>> s.fill_table_with_profile_params(profile_params)
286 .. doctest::
287 :hide:
289 >>> assert(np.all(np.isclose(s.table['stddev'], 1*np.ones(100))))
291 """
292 for k, name in enumerate(self.psf.param_names):
293 self.table[name] = profile_params[:, k]
295 def rotate_table(self, angle_degree):
296 """
297 In self.table, rotate the columns Dx, Dy, Dy_fwhm_inf and Dy_fwhm_sup by an angle
298 given in degree. The results overwrite the previous columns in self.table.
300 Parameters
301 ----------
302 angle_degree: float
303 Rotation angle in degree
305 Examples
306 --------
308 >>> psf = MoffatGauss()
309 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=4, saturation=8000)
310 >>> s.table['Dx'] = np.arange(100)
311 >>> s.rotate_table(45)
313 .. doctest::
314 :hide:
316 >>> assert(np.all(np.isclose(s.table['Dy'], -np.arange(100)/np.sqrt(2))))
317 >>> assert(np.all(np.isclose(s.table['Dx'], np.arange(100)/np.sqrt(2))))
318 >>> assert(np.all(np.isclose(s.table['Dy_fwhm_inf'], -np.arange(100)/np.sqrt(2))))
319 >>> assert(np.all(np.isclose(s.table['Dy_fwhm_sup'], -np.arange(100)/np.sqrt(2))))
320 """
321 angle = angle_degree * np.pi / 180.
322 rotmat = np.array([[np.cos(angle), np.sin(angle)], [-np.sin(angle), np.cos(angle)]])
323 # finish with Dy_c to get correct Dx
324 for name in ['Dy', 'Dy_fwhm_inf', 'Dy_fwhm_sup', 'Dy_disp_axis']:
325 vec = list(np.array([self.table['Dx'], self.table[name]]).T)
326 rot_vec = np.array([np.dot(rotmat, v) for v in vec])
327 self.table[name] = rot_vec.T[1]
328 self.table['Dx'] = rot_vec.T[0]
330 def from_profile_params_to_poly_params(self, profile_params):
331 """
332 Transform the profile_params array into a set of parameters for the chromatic PSF parameterisation.
333 Fit Legendre polynomial functions across the pixels for each PSF parameters.
334 The order of the polynomial functions is given by the self.degrees array.
336 Parameters
337 ----------
338 profile_params: array
339 a Nx * len(self.psf.param_names) numpy array containing the PSF parameters as a function of pixels.
341 Returns
342 -------
343 profile_params: array_like
344 A set of parameters that can be evaluated by the chromatic PSF class evaluate function.
346 Examples
347 --------
349 Build a mock spectrogram with random Poisson noise:
351 >>> psf = MoffatGauss()
352 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=4, saturation=8000)
353 >>> poly_params_test = s.generate_test_poly_params()
354 >>> data = s.evaluate(poly_params_test, mode="1D")
355 >>> data = np.random.poisson(data)
356 >>> data_errors = np.sqrt(data+1)
358 From the polynomial parameters to the profile parameters:
360 >>> profile_params = s.from_poly_params_to_profile_params(poly_params_test)
362 .. doctest::
363 :hide:
365 >>> assert(np.all(np.isclose(profile_params[0], [10, 0, 50, 5, 2, 0, 1, 8e3])))
367 From the profile parameters to the polynomial parameters:
369 >>> profile_params = s.from_profile_params_to_poly_params(profile_params)
371 .. doctest::
372 :hide:
374 >>> assert(np.all(np.isclose(profile_params, poly_params_test)))
375 """
376 pixels = np.linspace(-1, 1, len(self.table))
377 poly_params = np.array([])
378 amplitude = None
379 for k, name in enumerate(self.psf.param_names):
380 if name == 'amplitude':
381 amplitude = profile_params[:, k]
382 poly_params = np.concatenate([poly_params, amplitude])
383 if amplitude is None:
384 self.my_logger.warning('\n\tAmplitude array not initialized. '
385 'Polynomial fit for shape parameters will be unweighted.')
386 for k, name in enumerate(self.psf.param_names):
387 delta = 0
388 if name != 'amplitude':
389 weights = np.copy(amplitude)
390 if name == 'x_c':
391 delta = self.x0
392 if name == 'y_c':
393 delta = self.y0
394 fit = np.polynomial.legendre.legfit(pixels, profile_params[:, k] - delta,
395 deg=self.degrees[name], w=weights)
396 poly_params = np.concatenate([poly_params, fit])
397 return poly_params
399 def from_table_to_profile_params(self): # pragma: nocover
400 """
401 Extract the profile parameters from self.table and fill an array of profile parameters.
403 Parameters
404 ----------
406 Returns
407 -------
408 profile_params: array
409 Nx * len(self.psf.param_names) numpy array containing the PSF parameters as a function of pixels.
411 Examples
412 --------
414 >>> from spectractor.extractor.spectrum import Spectrum
415 >>> s = Spectrum('./tests/data/reduc_20170530_134_spectrum.fits')
416 >>> profile_params = s.chromatic_psf.from_table_to_profile_params()
418 .. doctest::
419 :hide:
421 >>> assert(profile_params.shape == (s.chromatic_psf.Nx, len(s.chromatic_psf.psf.param_names)))
422 >>> assert not np.all(np.isclose(profile_params, np.zeros_like(profile_params)))
423 """
424 profile_params = np.zeros((len(self.table), len(self.psf.param_names)))
425 for k, name in enumerate(self.psf.param_names):
426 profile_params[:, k] = self.table[name]
427 return profile_params
429 def from_table_to_poly_params(self): # pragma: nocover
430 """
431 Extract the polynomial parameters from self.table and fill an array with polynomial parameters.
433 Parameters
434 ----------
436 Returns
437 -------
438 poly_params: array_like
439 A set of polynomial parameters that can be evaluated by the chromatic PSF class evaluate function.
441 Examples
442 --------
444 >>> from spectractor.extractor.spectrum import Spectrum
445 >>> s = Spectrum('./tests/data/reduc_20170530_134_spectrum.fits')
446 >>> poly_params = s.chromatic_psf.from_table_to_poly_params()
448 .. doctest::
449 :hide:
451 >>> assert(poly_params.size > s.chromatic_psf.Nx)
452 >>> assert(len(poly_params.shape)==1)
453 >>> assert not np.all(np.isclose(poly_params, np.zeros_like(poly_params)))
454 """
455 profile_params = self.from_table_to_profile_params()
456 poly_params = self.from_profile_params_to_poly_params(profile_params)
457 return poly_params
459 def from_poly_params_to_profile_params(self, poly_params, apply_bounds=False):
460 """
461 Evaluate the PSF profile parameters from the polynomial coefficients. If poly_params length is smaller
462 than self.Nx, it is assumed that the amplitude parameters are not included and set to arbitrarily to 1.
464 Parameters
465 ----------
466 poly_params: array_like
467 Parameter array of the model, in the form:
468 - Nx first parameters are amplitudes for the Moffat transverse profiles
469 - next parameters are polynomial coefficients for all the PSF parameters in the same order
470 as in PSF definition, except amplitude
472 apply_bounds: bool, optional
473 Force profile parameters to respect their boundary conditions if they lie outside (default: False)
475 Returns
476 -------
477 profile_params: array
478 Nx * len(self.psf.param_names) numpy array containing the PSF parameters as a function of pixels.
480 Examples
481 --------
483 Build a mock spectrogram with random Poisson noise:
485 >>> psf = MoffatGauss()
486 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=1, saturation=8000)
487 >>> poly_params_test = s.generate_test_poly_params()
488 >>> data = s.evaluate(poly_params_test, mode="1D")
489 >>> data = np.random.poisson(data)
490 >>> data_errors = np.sqrt(data+1)
492 From the polynomial parameters to the profile parameters:
494 >>> profile_params = s.from_poly_params_to_profile_params(poly_params_test, apply_bounds=True)
496 .. doctest::
497 :hide:
499 >>> assert(np.all(np.isclose(profile_params[0], [10, 0, 50, 5, 2, 0, 1, 8e3])))
501 From the profile parameters to the polynomial parameters:
503 >>> profile_params = s.from_profile_params_to_poly_params(profile_params)
505 .. doctest::
506 :hide:
508 >>> assert(np.all(np.isclose(profile_params, poly_params_test)))
510 From the polynomial parameters to the profile parameters without Moffat amplitudes:
512 >>> profile_params = s.from_poly_params_to_profile_params(poly_params_test[100:])
514 .. doctest::
515 :hide:
517 >>> assert(np.all(np.isclose(profile_params[0], [1, 0, 50, 5, 2, 0, 1, 8e3])))
519 """
520 length = len(self.table)
521 pixels = np.linspace(-1, 1, length)
522 profile_params = np.zeros((length, len(self.psf.param_names)))
523 shift = 0
524 for k, name in enumerate(self.psf.param_names):
525 if name == 'amplitude':
526 if len(poly_params) > length:
527 profile_params[:, k] = poly_params[:length]
528 else:
529 profile_params[:, k] = np.ones(length)
530 else:
531 if len(poly_params) > length:
532 profile_params[:, k] = \
533 np.polynomial.legendre.legval(pixels,
534 poly_params[
535 length + shift:length + shift + self.degrees[name] + 1])
536 else:
537 p = poly_params[shift:shift + self.degrees[name] + 1]
538 if len(p) > 0: # to avoid saturation parameters in case not set
539 profile_params[:, k] = np.polynomial.legendre.legval(pixels, p)
540 shift += self.degrees[name] + 1
541 if name == 'x_c':
542 profile_params[:, k] += self.x0
543 if name == 'y_c':
544 profile_params[:, k] += self.y0
545 if apply_bounds:
546 for k, name in enumerate(self.psf.param_names):
547 profile_params[profile_params[:, k] <= self.psf.bounds[k][0], k] = self.psf.bounds[k][0]
548 profile_params[profile_params[:, k] > self.psf.bounds[k][1], k] = self.psf.bounds[k][1]
549 return profile_params
551 def from_profile_params_to_shape_params(self, profile_params):
552 """
553 Compute the PSF integrals and FWHMS given the profile_params array and fill the table.
555 Parameters
556 ----------
557 profile_params: array
558 a Nx * len(self.psf.param_names) numpy array containing the PSF parameters as a function of pixels.
560 Examples
561 --------
563 >>> psf = MoffatGauss()
564 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=4, saturation=8000)
565 >>> poly_params_test = s.generate_test_poly_params()
566 >>> profile_params = s.from_poly_params_to_profile_params(poly_params_test)
567 >>> s.from_profile_params_to_shape_params(profile_params)
569 .. doctest::
570 :hide:
572 >>> assert s.table['fwhm'][-1] > 0
574 """
575 self.fill_table_with_profile_params(profile_params)
576 pixel_x = np.arange(self.Nx).astype(int)
577 # oversampling for precise computation of the PSF
578 # pixels.shape = (2, Nx, Ny): self.pixels[1<-y, 0<-first pixel value column, :]
579 # TODO: account for rotation ad projection effects is PSF is not round
580 pixel_eval = np.arange(self.pixels[1, 0, 0], self.pixels[1, 0, -1], 0.1)
581 for x in pixel_x:
582 p = profile_params[x, :]
583 # compute FWHM transverse to dispersion axis (assuming revolution symmetry of the PSF)
584 out = self.psf.evaluate(pixel_eval, p=p)
585 fwhm = compute_fwhm(pixel_eval, out, center=p[2], minimum=0)
586 self.table['flux_integral'][x] = p[0] # if MoffatGauss1D normalized
587 self.table['fwhm'][x] = fwhm
589 def set_bounds(self):
590 """
591 This function returns an array of bounds for iminuit. It is very touchy, change the values with caution !
593 Returns
594 -------
595 bounds: array_like
596 2D array containing the pair of bounds for each polynomial parameters.
598 """
599 bounds = [[], []]
600 for k, name in enumerate(self.psf.param_names):
601 tmp_bounds = [[-np.inf] * (1 + self.degrees[name]), [np.inf] * (1 + self.degrees[name])]
602 if name == "saturation":
603 tmp_bounds = [[0], [2 * self.saturation]]
604 elif name == "amplitude":
605 continue
606 bounds[0] += tmp_bounds[0]
607 bounds[1] += tmp_bounds[1]
608 return np.array(bounds).T
610 def set_bounds_for_minuit(self, data=None): # pragma: nocover
611 """
612 This function returns an array of bounds for iminuit. It is very touchy, change the values with caution !
614 Parameters
615 ----------
616 data: array_like, optional
617 The data array, to set the bounds for the amplitude using its maximum.
618 If None is provided, no bounds are provided for the amplitude parameters.
620 Returns
621 -------
622 bounds: array_like
623 2D array containing the pair of bounds for each polynomial parameters.
625 """
626 if self.saturation is None:
627 self.saturation = 2 * np.max(data)
628 if data is not None:
629 Ny, Nx = data.shape
630 bounds = [[0.1 * np.max(data[:, x]) for x in range(Nx)], [100.0 * np.max(data[:, x]) for x in range(Nx)]]
631 else:
632 bounds = [[], []]
633 for k, name in enumerate(self.psf.param_names):
634 tmp_bounds = [[-np.inf] * (1 + self.degrees[name]), [np.inf] * (1 + self.degrees[name])]
635 if name == "saturation":
636 if data is not None:
637 tmp_bounds = [[0.1 * np.max(data)], [2 * self.saturation]]
638 else:
639 tmp_bounds = [[0], [2 * self.saturation]]
640 elif name == "amplitude":
641 continue
642 bounds[0] += tmp_bounds[0]
643 bounds[1] += tmp_bounds[1]
644 return np.array(bounds).T
646 def check_bounds(self, poly_params, noise_level=0): # pragma: nocover
647 """
648 Evaluate the PSF profile parameters from the polynomial coefficients and check if they are within priors.
650 Parameters
651 ----------
652 poly_params: array_like
653 Parameter array of the model, in the form:
654 - Nx first parameters are amplitudes for the Moffat transverse profiles
655 - next parameters are polynomial coefficients for all the PSF parameters
656 in the same order as in PSF definition, except amplitude
657 noise_level: float, optional
658 Noise level to set minimal boundary for amplitudes (negatively).
660 Returns
661 -------
662 in_bounds: bool
663 True if all parameters respect the model parameter priors.
664 penalty: float
665 Float value to add to chi square evaluating the degree of departure of a parameter from its boundaries.
666 outbound_parameter_name: str
667 Names of the parameters that are out of their boundaries.
669 Examples
670 --------
672 Build a mock spectrogram with random Poisson noise:
674 >>> psf = MoffatGauss()
675 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=1, saturation=8000)
676 >>> poly_params_test = s.generate_test_poly_params()
678 Check bounds:
680 >>> in_bounds, penalty, outbound_parameter_name = s.check_bounds(poly_params_test)
682 .. doctest::
683 :hide:
685 >>> assert in_bounds is True
686 >>> assert np.isclose(penalty, 0, atol=1e-16)
687 >>> assert outbound_parameter_name is not None
689 """
690 in_bounds = True
691 penalty = 0
692 outbound_parameter_name = ""
693 profile_params = self.from_poly_params_to_profile_params(poly_params)
694 for k, name in enumerate(self.psf.param_names):
695 p = profile_params[:, k]
696 if name == 'amplitude':
697 if np.any(p < -noise_level):
698 in_bounds = False
699 penalty += np.abs(np.sum(profile_params[p < -noise_level, k])) # / np.mean(np.abs(p))
700 outbound_parameter_name += name + ' '
701 elif name == "saturation":
702 continue
703 else:
704 if np.any(p > self.psf.bounds[k][1]):
705 penalty += np.sum(profile_params[p > self.psf.bounds[k][1], k] - self.psf.bounds[k][1])
706 if not np.isclose(np.mean(p), 0):
707 penalty /= np.abs(np.mean(p))
708 in_bounds = False
709 outbound_parameter_name += name + ' '
710 if np.any(p < self.psf.bounds[k][0]):
711 penalty += np.sum(self.psf.bounds[k][0] - profile_params[p < self.psf.bounds[k][0], k])
712 if not np.isclose(np.mean(p), 0):
713 penalty /= np.abs(np.mean(p))
714 in_bounds = False
715 outbound_parameter_name += name + ' '
716 # elif name is "stddev":
717 # if np.any(p < 0) or np.any(p > self.Ny):
718 # in_bounds = False
719 # penalty = 1
720 # break
721 # else:
722 # raise ValueError(f'Unknown parameter name {name} in set_bounds_for_minuit.')
723 penalty *= self.Nx * self.Ny
724 return in_bounds, penalty, outbound_parameter_name
726 def get_algebraic_distance_along_dispersion_axis(self, shift_x=0, shift_y=0):
727 return np.asarray(np.sign(self.table['Dx']) *
728 np.sqrt((self.table['Dx'] - shift_x) ** 2 + (self.table['Dy_disp_axis'] - shift_y) ** 2))
730 def plot_summary(self, truth=None):
731 fig, ax = plt.subplots(2, 1, sharex='all', figsize=(12, 6))
732 PSF_models = []
733 PSF_truth = []
734 if truth is not None:
735 PSF_truth = truth.from_poly_params_to_profile_params(truth.poly_params, apply_bounds=True)
736 all_pixels = np.arange(self.profile_params.shape[0])
737 for i, name in enumerate(self.psf.param_names):
738 fit, cov, model = fit_poly1d(all_pixels, self.profile_params[:, i], order=self.degrees[name])
739 PSF_models.append(np.polyval(fit, all_pixels))
740 for i, name in enumerate(self.psf.param_names):
741 p = ax[0].plot(all_pixels, self.profile_params[:, i], marker='+', linestyle='none')
742 ax[0].plot(self.fitted_pixels, self.profile_params[self.fitted_pixels, i], label=name,
743 marker='o', linestyle='none', color=p[0].get_color())
744 if i > 0:
745 ax[0].plot(all_pixels, PSF_models[i], color=p[0].get_color())
746 if truth is not None:
747 ax[0].plot(all_pixels, PSF_truth[:, i], color=p[0].get_color(), linestyle='--')
748 img = np.zeros((self.Ny, self.Nx)).astype(float)
749 yy, xx = np.mgrid[:self.Ny, :self.Nx]
750 for x in all_pixels[::self.Nx // 10]:
751 params = [PSF_models[p][x] for p in range(len(self.psf.param_names))]
752 params[:3] = [1, x, self.Ny // 2]
753 out = self.psf.evaluate(np.asarray([xx, yy]), p=params)
754 if np.max(out) <= 0:
755 continue
756 out /= np.max(out)
757 img += out
758 ax[1].imshow(img, origin='lower') # , extent=[0, self.Nx,
759 # self.Ny//2-parameters.PIXWIDTH_SIGNAL,
760 # self.Ny//2+parameters.PIXWIDTH_SIGNAL])
761 ax[1].set_xlabel('X [pixels]')
762 ax[1].set_ylabel('Y [pixels]')
763 ax[0].set_ylabel('PSF parameters')
764 ax[0].grid()
765 ax[1].grid(color='white', ls='solid')
766 ax[1].grid(True)
767 ax[0].set_yscale('symlog', linthresh=10)
768 ax[1].legend(title='PSF(x)')
769 ax[0].legend()
770 fig.tight_layout()
771 # fig.subplots_adjust(hspace=0)
772 if parameters.DISPLAY: # pragma: no cover
773 plt.show()
775 def fit_transverse_PSF1D_profile(self, data, err, w, ws, pixel_step=1, bgd_model_func=None, saturation=None,
776 live_fit=False, sigma_clip=5):
777 """
778 Fit the transverse profile of a 2D data image with a PSF profile.
779 Loop is done on the x-axis direction.
780 An order 1 polynomial function is fitted to subtract the background for each pixel
781 with a 3*sigma outlier removal procedure to remove background stars.
783 Parameters
784 ----------
785 data: array
786 The 2D array image. The transverse profile is fitted on the y direction
787 for all pixels along the x direction.
788 err: array
789 The uncertainties related to the data array.
790 w: int
791 Half width of central region where the spectrum is extracted and summed (default: 10)
792 ws: list
793 up/down region extension where the sky background is estimated with format [int, int] (default: [20,30])
794 pixel_step: int, optional
795 The step in pixels between the slices to be fitted (default: 1).
796 The values for the skipped pixels are interpolated with splines from the fitted parameters.
797 bgd_model_func: callable, optional
798 A 2D function to model the extracted background (default: None -> null background)
799 saturation: float, optional
800 The saturation level of the image. Default is set to twice the maximum of the data array and has no effect.
801 live_fit: bool, optional
802 If True, the transverse profile fit is plotted in live accross the loop (default: False).
803 sigma_clip: int
804 Sigma for outlier rejection (default: 5).
806 Examples
807 --------
809 Build a mock spectrogram with random Poisson noise:
811 >>> psf = MoffatGauss()
812 >>> s0 = ChromaticPSF(psf, Nx=100, Ny=100, saturation=1000)
813 >>> params = s0.generate_test_poly_params()
814 >>> saturation = params[-1]
815 >>> data = s0.evaluate(params, mode="1D")
816 >>> bgd = 10*np.ones_like(data)
817 >>> xx, yy = np.meshgrid(np.arange(s0.Nx), np.arange(s0.Ny))
818 >>> bgd += 1000*np.exp(-((xx-20)**2+(yy-10)**2)/(2*2))
819 >>> data += bgd
820 >>> data = np.random.poisson(data)
821 >>> data_errors = np.sqrt(data+1)
823 Extract the background:
825 >>> bgd_model_func, _, _ = extract_spectrogram_background_sextractor(data, data_errors, ws=[30,50])
827 Fit the transverse profile:
829 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=4, saturation=saturation)
830 >>> s.fit_transverse_PSF1D_profile(data, data_errors, w=20, ws=[30,50], pixel_step=10,
831 ... bgd_model_func=bgd_model_func, saturation=saturation, live_fit=False, sigma_clip=5)
832 >>> s.plot_summary(truth=s0)
834 .. doctest::
835 :hide:
837 >>> assert(not np.any(np.isclose(s.table['flux_sum'][3:6], np.zeros(s.Nx)[3:6], rtol=1e-3)))
838 >>> assert(np.all(np.isclose(s.table['Dy'][-10:-1], np.zeros(s.Nx)[-10:-1], rtol=1e-2)))
840 """
841 if saturation is None:
842 saturation = 2 * np.max(data)
843 Ny, Nx = data.shape
844 middle = Ny // 2
845 index = np.arange(Ny)
846 # Prepare the fit: start with the maximum of the spectrum
847 xmax_index = int(np.unravel_index(np.argmax(data[middle - w:middle + w, :]), data.shape)[1])
848 bgd_index = np.concatenate((np.arange(0, middle - ws[0]), np.arange(middle + ws[0], Ny))).astype(int)
849 y = data[:, xmax_index]
850 # first fit with moffat only to initialize the guess
851 # hypothesis that max of spectrum if well describe by a focused PSF
852 if bgd_model_func is not None:
853 signal = y - bgd_model_func(xmax_index, index)[:, 0]
854 else:
855 signal = y
856 # fwhm = compute_fwhm(index, signal, minimum=0)
857 # Initialize PSF
858 psf = self.psf
859 guess = np.copy(psf.p_default).astype(float)
860 # guess = [2 * np.nanmax(signal), middle, 0.5 * fwhm, 2, 0, 0.1 * fwhm, saturation]
861 signal_sum = np.nanmax(signal)
862 guess[0] = signal_sum
863 guess[1] = xmax_index
864 guess[2] = middle
865 guess[-1] = saturation
866 # bounds = [(0.1 * maxi, 10 * maxi), (middle - w, middle + w), (0.1, min(fwhm, Ny // 2)), (0.1, self.alpha_max),
867 # (-1, 0),
868 # (0.1, min(Ny // 2, fwhm)),
869 # (0, 2 * saturation)]
870 psf.apply_max_width_to_bounds(max_half_width=Ny)
871 bounds = np.copy(psf.bounds)
872 bounds[0] = (0.1 * signal_sum, 2 * signal_sum)
873 bounds[2] = (middle - w, middle + w)
874 bounds[-1] = (0, 2 * saturation)
875 # moffat_guess = [2 * np.nanmax(signal), middle, 0.5 * fwhm, 2]
876 # moffat_bounds = [(0.1 * maxi, 10 * maxi), (middle - w, middle + w), (0.1, min(fwhm, Ny // 2)), (0.1, 10)]
877 # fit = fit_moffat1d_outlier_removal(index, signal, sigma=sigma, niter=2,
878 # guess=moffat_guess, bounds=np.array(moffat_bounds).T)
879 # moffat_guess = [getattr(fit, p).value for p in fit.param_names]
880 # signal_width_guess = moffat_guess[2]
881 # bounds[2] = (0.1, min(Ny // 2, 5 * signal_width_guess))
882 # bounds[5] = (0.1, min(Ny // 2, 5 * signal_width_guess))
883 # guess[:4] = moffat_guess
884 init_guess = np.copy(guess)
885 # Go from max to right, then from max to left
886 # includes the boundaries to avoid Runge phenomenum in chromatic_fit
887 pixel_range = list(np.arange(xmax_index, Nx, pixel_step).astype(int))
888 if Nx - 1 not in pixel_range:
889 pixel_range.append(Nx - 1)
890 pixel_range += list(np.arange(xmax_index, -1, -pixel_step).astype(int))
891 if 0 not in pixel_range:
892 pixel_range.append(0)
893 pixel_range = np.array(pixel_range)
894 for x in tqdm(pixel_range, disable=not parameters.VERBOSE):
895 guess = np.copy(guess)
896 if x == xmax_index:
897 guess = np.copy(init_guess)
898 # fit the background with a polynomial function
899 y = data[:, x]
900 if bgd_model_func is not None:
901 # x_array = [x] * index.size
902 signal = y - bgd_model_func(x, index)[:, 0]
903 else:
904 signal = y
905 if np.mean(signal[bgd_index]) < 0:
906 signal -= np.mean(signal[bgd_index])
907 # in case guess amplitude is too low
908 # pdf = np.abs(signal)
909 signal_sum = np.nansum(signal[middle - ws[0]:middle + ws[0]])
910 if signal_sum < 3 * np.nanstd(signal[bgd_index]):
911 continue
912 # if signal_sum > 0:
913 # pdf /= signal_sum
914 # mean = np.nansum(pdf * index)
915 # bounds[0] = (0.1 * np.nanstd(bgd), 2 * np.nanmax(y[middle - ws[0]:middle + ws[0]]))
916 bounds[0] = (0.1 * signal_sum, 1.5 * signal_sum)
917 guess[0] = signal_sum
918 guess[1] = x
919 # if guess[4] > -1:
920 # guess[0] = np.max(signal) / (1 + guess[4])
921 # std = np.sqrt(np.nansum(pdf * (index - mean) ** 2))
922 # if guess[0] < 3 * np.nanstd(bgd):
923 # guess[0] = float(0.9 * np.abs(np.nanmax(signal)))
924 # if guess[0] * (1 + 0*guess[4]) > 1.2 * maxi:
925 # guess[0] = 0.9 * maxi
926 psf.p = guess
927 psf.bounds = bounds
928 w = PSFFitWorkspace(psf, signal, data_errors=err[:, x], bgd_model_func=None,
929 live_fit=False, verbose=False)
930 try:
931 run_minimisation_sigma_clipping(w, method="newton", sigma_clip=sigma_clip, niter_clip=2, verbose=False,
932 fix=w.fixed)
933 except:
934 pass
935 best_fit = w.psf.p
936 # It is better not to propagate the guess to further pixel columns
937 # otherwise fit_chromatic_psf1D is more likely to get trapped in a local minimum
938 # Randomness of the slice fit is better :
939 # guess = best_fit
940 self.profile_params[x, :] = best_fit
941 # TODO: propagate amplitude uncertainties from Newton fit
942 self.table['flux_err'][x] = np.sqrt(np.sum(err[:, x] ** 2))
943 self.table['flux_sum'][x] = np.sum(signal)
944 if live_fit and parameters.DISPLAY: # pragma: no cover
945 if not np.any(np.isnan(best_fit[0])):
946 w.live_fit = True
947 w.plot_fit()
948 # interpolate the skipped pixels with splines
949 all_pixels = np.arange(Nx)
950 xp = np.array(sorted(set(list(pixel_range))))
951 self.fitted_pixels = xp
952 for i in range(len(self.psf.param_names)):
953 yp = self.profile_params[xp, i]
954 self.profile_params[:, i] = interp1d(xp, yp, kind='cubic')(all_pixels)
955 for x in all_pixels:
956 y = data[:, x]
957 if bgd_model_func is not None:
958 signal = y - bgd_model_func(x, index)[:, 0]
959 else:
960 signal = y
961 if np.mean(signal[bgd_index]) < 0:
962 signal -= np.mean(signal[bgd_index])
963 self.table['flux_err'][x] = np.sqrt(np.sum(err[:, x] ** 2))
964 self.table['flux_sum'][x] = np.sum(signal)
965 self.poly_params = self.from_profile_params_to_poly_params(self.profile_params)
966 self.from_profile_params_to_shape_params(self.profile_params)
968 def fit_chromatic_psf(self, data, bgd_model_func=None, data_errors=None, mode="1D",
969 amplitude_priors_method="noprior", verbose=False, live_fit=False):
970 """
971 Fit a chromatic PSF model on 2D data.
973 Parameters
974 ----------
975 data: array_like
976 2D array containing the image data.
977 bgd_model_func: callable, optional
978 A 2D function to model the extracted background (default: None -> null background)
979 data_errors: np.array
980 the 2D array uncertainties.
981 mode: str, optional
982 Set the fitting mode: either transverse 1D PSF profile (mode="1D") or full 2D PSF profile (mode="2D").
983 amplitude_priors_method: str, optional
984 Prior method to use to constrain the amplitude parameters of the PSF (default: "noprior").
985 verbose: bool, optional
986 Set the verbosity of the fitting process (default: False).
988 Returns
989 -------
990 w: ChromaticPSFFitWorkspace
991 The ChromaticPSFFitWorkspace containing info abut the fitting process.
993 Examples
994 --------
996 Set the parameters:
998 >>> parameters.PIXDIST_BACKGROUND = 40
999 >>> parameters.PIXWIDTH_BACKGROUND = 10
1000 >>> parameters.PIXWIDTH_SIGNAL = 30
1001 >>> parameters.DEBUG = True
1003 Build a mock spectrogram with random Poisson noise using the full 2D PSF model:
1005 >>> psf = Moffat()
1006 >>> s0 = ChromaticPSF(psf, Nx=120, Ny=100, deg=2, saturation=10000000)
1007 >>> params = s0.generate_test_poly_params()
1008 >>> params[:s0.Nx] *= 1
1009 >>> s0.poly_params = params
1010 >>> saturation = params[-1]
1011 >>> data = s0.evaluate(params, mode="2D")
1012 >>> bgd = 10*np.ones_like(data)
1013 >>> data += bgd
1014 >>> data = np.random.poisson(data)
1015 >>> data_errors = np.sqrt(data)
1017 Extract the background:
1019 >>> bgd_model_func, _, _ = extract_spectrogram_background_sextractor(data, data_errors, ws=[30,50])
1021 Propagate background uncertainties:
1023 >>> data_errors = np.sqrt(data_errors**2 + bgd_model_func(np.arange(s0.Nx), np.arange(s0.Ny)))
1025 Estimate the first guess values:
1027 >>> s = ChromaticPSF(psf, Nx=120, Ny=100, deg=2, saturation=saturation)
1028 >>> s.fit_transverse_PSF1D_profile(data, data_errors, w=20, ws=[30,50],
1029 ... pixel_step=1, bgd_model_func=bgd_model_func, saturation=saturation, live_fit=False)
1030 >>> s.plot_summary(truth=s0)
1031 >>> amplitude_residuals = [ [s0.poly_params[:s0.Nx], np.array(s.table["amplitude"])-s0.poly_params[:s0.Nx],
1032 ... np.array(s.table['amplitude'] * s.table['flux_err'] / s.table['flux_sum'])] ]
1034 Fit the data using the transverse 1D PSF model only:
1036 >>> w = s.fit_chromatic_psf(data, mode="1D", data_errors=data_errors, bgd_model_func=bgd_model_func,
1037 ... amplitude_priors_method="noprior", verbose=True)
1038 >>> s.plot_summary(truth=s0)
1039 >>> amplitude_residuals.append([s0.poly_params[:s0.Nx], w.amplitude_params-s0.poly_params[:s0.Nx],
1040 ... w.amplitude_params_err])
1042 .. doctest::
1043 :hide:
1045 >>> residuals = [(w.data[x]-w.model[x])/w.err[x] for x in range(w.Nx)]
1046 >>> assert w.costs[-1] /(w.Nx*w.Ny) < 1.5
1047 >>> assert np.abs(np.mean(residuals)) < 0.15
1048 >>> assert np.std(residuals) < 1.2
1050 Fit the data using the full 2D PSF model
1052 >>> parameters.PSF_FIT_REG_PARAM = 0.002
1053 >>> w = s.fit_chromatic_psf(data, mode="2D", data_errors=data_errors, bgd_model_func=bgd_model_func,
1054 ... amplitude_priors_method="psf1d", verbose=True)
1055 >>> s.plot_summary(truth=s0)
1056 >>> amplitude_residuals.append([s0.poly_params[:s0.Nx], w.amplitude_params-s0.poly_params[:s0.Nx],
1057 ... w.amplitude_params_err])
1058 >>> for k, label in enumerate(["Transverse", "PSF1D", "PSF2D"]):
1059 ... plt.errorbar(np.arange(s0.Nx), amplitude_residuals[k][1]/amplitude_residuals[k][2],
1060 ... yerr=amplitude_residuals[k][2]/amplitude_residuals[k][2],
1061 ... fmt="+", label=label) # doctest: +ELLIPSIS
1062 <ErrorbarContainer ...>
1063 >>> plt.grid()
1064 >>> plt.legend() # doctest: +ELLIPSIS
1065 <matplotlib.legend.Legend object at ...>
1066 >>> plt.show()
1068 .. doctest::
1069 :hide:
1071 >>> residuals = (w.data.flatten()-w.model.flatten())/w.err.flatten()
1072 >>> assert w.costs[-1] /(w.Nx*w.Ny) < 1.2
1073 >>> assert np.abs(np.mean(residuals)) < 0.15
1074 >>> assert np.std(residuals) < 1.2
1075 >>> assert np.abs(np.mean((w.amplitude_params - s0.poly_params[:s0.Nx])/w.amplitude_params_err)) < 0.5
1077 """
1078 if mode == "1D":
1079 w = ChromaticPSF1DFitWorkspace(self, data, data_errors=data_errors, bgd_model_func=bgd_model_func,
1080 amplitude_priors_method=amplitude_priors_method, verbose=verbose,
1081 live_fit=live_fit)
1082 run_minimisation(w, method="newton", ftol=1 / (w.Nx * w.Ny), xtol=1e-6, niter=50, fix=w.fixed)
1083 elif mode == "2D":
1084 w = ChromaticPSF2DFitWorkspace(self, data, data_errors=data_errors, bgd_model_func=bgd_model_func,
1085 amplitude_priors_method=amplitude_priors_method, verbose=verbose,
1086 live_fit=live_fit)
1087 # run_minimisation(w, method="newton", ftol=1 / (w.Nx * w.Ny), xtol=1e-6, niter=50, fix=w.fixed)
1088 run_minimisation_sigma_clipping(w, method="newton", ftol=1 / (w.Nx * w.Ny), xtol=1e-6, niter=50,
1089 fix=w.fixed, sigma_clip=10, niter_clip=3, verbose=verbose)
1090 else:
1091 raise ValueError(f"Unknown fitting mode={mode}. Must be '1D' or '2D'.")
1093 # recompute and save params in class attributes
1094 w.simulate(*w.p)
1096 # regularisation
1097 if w.amplitude_priors_method == "psf1d" and mode == "2D":
1098 w_reg = RegFitWorkspace(w, opt_reg=parameters.PSF_FIT_REG_PARAM, verbose=verbose)
1099 run_minimisation(w_reg, method="minimize", ftol=1e-4, xtol=1e-2, verbose=verbose, epsilon=[1e-1],
1100 minimizer_method="Nelder-Mead")
1101 w_reg.opt_reg = 10 ** w_reg.p[0]
1102 self.my_logger.info(f"\n\tOptimal regularisation parameter: {w_reg.opt_reg}")
1103 w.reg = np.copy(w_reg.opt_reg)
1104 w.simulate(*w.p)
1105 self.opt_reg = w_reg.opt_reg
1106 if np.trace(w.amplitude_cov_matrix) < np.trace(w.amplitude_priors_cov_matrix):
1107 self.my_logger.warning(f"\n\tTrace of final covariance matrix ({np.trace(w.amplitude_cov_matrix)}) is "
1108 f"below the trace of the prior covariance matrix "
1109 f"({np.trace(w.amplitude_priors_cov_matrix)}). This is probably due to a very "
1110 f"high regularisation parameter in case of a bad fit. Therefore the final "
1111 f"covariance matrix is mulitiplied by the ratio of the traces and "
1112 f"the amplitude parameters are very close the amplitude priors.")
1113 r = np.trace(w.amplitude_priors_cov_matrix) / np.trace(w.amplitude_cov_matrix)
1114 w.amplitude_cov_matrix *= r
1115 w.amplitude_params_err = np.array([np.sqrt(w.amplitude_cov_matrix[x, x]) for x in range(self.Nx)])
1117 self.poly_params = w.poly_params
1118 self.cov_matrix = np.copy(w.amplitude_cov_matrix)
1120 # add background crop to y_c
1121 self.poly_params[w.Nx + w.y_c_0_index] += w.bgd_width
1123 # fill results
1124 self.psf.apply_max_width_to_bounds(max_half_width=w.Ny + 2 * w.bgd_width)
1125 self.set_bounds()
1126 self.profile_params = self.from_poly_params_to_profile_params(self.poly_params, apply_bounds=True)
1127 self.profile_params[:self.Nx, 0] = w.amplitude_params
1128 self.profile_params[:self.Nx, 1] = np.arange(self.Nx)
1129 self.fill_table_with_profile_params(self.profile_params)
1130 self.from_profile_params_to_shape_params(self.profile_params)
1132 # save plots
1133 if parameters.LSST_SAVEFIGPATH: # pragma: no cover
1134 w.plot_fit()
1135 return w
1138class ChromaticPSFFitWorkspace(FitWorkspace):
1140 def __init__(self, chromatic_psf, data, data_errors, bgd_model_func=None, file_name="",
1141 amplitude_priors_method="noprior",
1142 nwalkers=18, nsteps=1000, burnin=100, nbins=10,
1143 verbose=0, plot=False, live_fit=False, truth=None):
1144 FitWorkspace.__init__(self, file_name, nwalkers, nsteps, burnin, nbins, verbose, plot,
1145 live_fit, truth=truth)
1146 self.my_logger = set_logger(self.__class__.__name__)
1147 self.chromatic_psf = chromatic_psf
1148 self.data = data
1149 self.err = data_errors
1150 self.bgd_model_func = bgd_model_func
1151 length = len(self.chromatic_psf.table)
1152 self.p = np.copy(self.chromatic_psf.poly_params[length:]) # remove saturation (fixed parameter))
1153 self.poly_params = np.copy(self.chromatic_psf.poly_params)
1154 self.input_labels = list(np.copy(self.chromatic_psf.poly_params_labels[length:]))
1155 self.axis_names = list(np.copy(self.chromatic_psf.poly_params_names[length:]))
1156 self.fixed = [False] * self.p.size
1157 for k, par in enumerate(self.input_labels):
1158 if "x_c" in par or "saturation" in par:
1159 self.fixed[k] = True
1160 self.y_c_0_index = -1
1161 for k, par in enumerate(self.input_labels):
1162 if par == "y_c_0":
1163 self.y_c_0_index = k
1164 break
1165 self.nwalkers = max(2 * self.ndim, nwalkers)
1167 # prepare the fit
1168 self.Ny, self.Nx = self.data.shape
1169 if self.Ny != self.chromatic_psf.Ny:
1170 raise AttributeError(f"Data y shape {self.Ny} different from "
1171 f"ChromaticPSF input Ny {self.chromatic_psf.Ny}.")
1172 if self.Nx != self.chromatic_psf.Nx:
1173 raise AttributeError(f"Data x shape {self.Nx} different from "
1174 f"ChromaticPSF input Nx {self.chromatic_psf.Nx}.")
1175 self.pixels = np.arange(self.Ny)
1177 # prepare the background, data and errors
1178 self.bgd = np.zeros_like(self.data)
1179 if self.bgd_model_func is not None:
1180 self.bgd = self.bgd_model_func(np.arange(self.Nx), self.pixels)
1181 self.data = self.data - self.bgd
1182 self.bgd_std = float(np.std(np.random.poisson(np.abs(self.bgd))))
1184 # crop spectrogram to fit faster
1185 self.bgd_width = parameters.PIXWIDTH_BACKGROUND + parameters.PIXDIST_BACKGROUND - parameters.PIXWIDTH_SIGNAL
1186 self.data = self.data[self.bgd_width:-self.bgd_width, :]
1187 self.pixels = np.arange(self.data.shape[0])
1188 self.err = np.copy(self.err[self.bgd_width:-self.bgd_width, :])
1189 self.Ny, self.Nx = self.data.shape
1191 # update the bounds
1192 self.chromatic_psf.psf.apply_max_width_to_bounds(max_half_width=self.Ny)
1193 self.bounds = self.chromatic_psf.set_bounds()
1195 # error matrix
1196 # here image uncertainties are assumed to be uncorrelated
1197 # (which is not exactly true in rotated images)
1198 self.data_cov = (self.err * self.err).flatten()
1199 self.W = 1. / (self.err * self.err)
1200 self.W = self.W.flatten()
1202 # design matrix
1203 self.M = np.zeros((self.Nx, self.data.size))
1204 self.M_dot_W_dot_M = np.zeros((self.Nx, self.Nx))
1206 # prepare results
1207 self.amplitude_params = np.zeros(self.Nx)
1208 self.amplitude_params_err = np.zeros(self.Nx)
1209 self.amplitude_cov_matrix = np.zeros((self.Nx, self.Nx))
1211 # priors on amplitude parameters
1212 self.amplitude_priors_list = ['noprior', 'positive', 'smooth', 'psf1d', 'fixed']
1213 self.amplitude_priors_method = amplitude_priors_method
1214 self.fwhm_priors = np.copy(self.chromatic_psf.table['fwhm'])
1215 self.reg = parameters.PSF_FIT_REG_PARAM
1216 self.Q = np.zeros((self.Nx, self.Nx))
1217 self.Q_dot_A0 = np.zeros(self.Nx)
1218 if amplitude_priors_method not in self.amplitude_priors_list:
1219 raise ValueError(f"Unknown prior method for the amplitude fitting: {self.amplitude_priors_method}. "
1220 f"Must be either {self.amplitude_priors_list}.")
1221 if self.amplitude_priors_method == "psf1d":
1222 self.amplitude_priors = np.copy(self.chromatic_psf.poly_params[:self.Nx])
1223 self.amplitude_priors_cov_matrix = np.copy(self.chromatic_psf.cov_matrix)
1224 # self.amplitude_priors_err = np.copy(self.chromatic_psf.table["flux_err"])
1225 self.Q = np.diag([1 / np.sum(self.err[:, x] ** 2) for x in range(self.Nx)])
1226 self.Q_dot_A0 = self.Q @ self.amplitude_priors
1227 if self.amplitude_priors_method == "fixed":
1228 self.amplitude_priors = np.copy(self.chromatic_psf.poly_params[:self.Nx])
1230 def plot_fit(self):
1231 data = np.copy(self.data)
1232 model = np.copy(self.model)
1233 err = np.copy(self.err)
1234 if isinstance(self, ChromaticPSF1DFitWorkspace):
1235 data = np.array([data[x] for x in range(self.Nx)], dtype=float).T
1236 model = np.array([model[x] for x in range(self.Nx)], dtype=float).T
1237 err = np.array([err[x] for x in range(self.Nx)], dtype=float).T
1238 if isinstance(self, ChromaticPSF2DFitWorkspace):
1239 data = data.reshape((self.Ny, self.Nx))
1240 model = model.reshape((self.Ny, self.Nx))
1241 err = err.reshape((self.Ny, self.Nx))
1242 gs_kw = dict(width_ratios=[3, 0.15], height_ratios=[1, 1, 1, 1])
1243 fig, ax = plt.subplots(nrows=4, ncols=2, figsize=(7, 7), gridspec_kw=gs_kw)
1244 norm = np.max(data)
1245 plot_image_simple(ax[1, 0], data=model / norm, aspect='auto', cax=ax[1, 1], vmin=0, vmax=1,
1246 units='1/max(data)')
1247 ax[1, 0].set_title("Model", fontsize=10, loc='center', color='white', y=0.8)
1248 plot_image_simple(ax[0, 0], data=data / norm, title='Data', aspect='auto',
1249 cax=ax[0, 1], vmin=0, vmax=1, units='1/max(data)')
1250 ax[0, 0].set_title('Data', fontsize=10, loc='center', color='white', y=0.8)
1251 residuals = (data - model)
1252 # residuals_err = self.spectrum.spectrogram_err / self.model
1253 norm = err
1254 residuals /= norm
1255 std = float(np.std(residuals))
1256 plot_image_simple(ax[2, 0], data=residuals, vmin=-5 * std, vmax=5 * std, title='(Data-Model)/Err',
1257 aspect='auto', cax=ax[2, 1], units='', cmap="bwr")
1258 ax[2, 0].set_title('(Data-Model)/Err', fontsize=10, loc='center', color='black', y=0.8)
1259 ax[2, 0].text(0.05, 0.05, f'mean={np.mean(residuals):.3f}\nstd={np.std(residuals):.3f}',
1260 horizontalalignment='left', verticalalignment='bottom',
1261 color='black', transform=ax[2, 0].transAxes)
1262 ax[0, 0].set_xticks(ax[2, 0].get_xticks()[1:-1])
1263 ax[0, 1].get_yaxis().set_label_coords(3.5, 0.5)
1264 ax[1, 1].get_yaxis().set_label_coords(3.5, 0.5)
1265 ax[2, 1].get_yaxis().set_label_coords(3.5, 0.5)
1266 ax[3, 1].remove()
1267 ax[3, 0].errorbar(np.arange(self.Nx), data.sum(axis=0), yerr=np.sqrt(np.sum(err ** 2, axis=0)),
1268 label='Data', fmt='k.', markersize=0.1)
1269 ax[3, 0].plot(np.arange(self.Nx), model.sum(axis=0), label='Model')
1270 ax[3, 0].set_ylabel('Transverse sum')
1271 ax[3, 0].set_xlabel(parameters.PLOT_XLABEL)
1272 ax[3, 0].legend(fontsize=7)
1273 ax[3, 0].set_xlim((0, data.shape[1]))
1274 ax[3, 0].grid(True)
1275 if self.live_fit: # pragma: no cover
1276 plt.draw()
1277 plt.pause(1e-8)
1278 plt.close()
1279 else: # pragma: no cover
1280 if parameters.DISPLAY and self.verbose:
1281 plt.show()
1282 if parameters.LSST_SAVEFIGPATH: # pragma: no cover
1283 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH,
1284 f'fit_chromatic_psf_best_fit_{self.amplitude_priors_method}.pdf'),
1285 dpi=100, bbox_inches='tight')
1288class ChromaticPSF1DFitWorkspace(ChromaticPSFFitWorkspace):
1290 def __init__(self, chromatic_psf, data, data_errors, bgd_model_func=None, file_name="",
1291 amplitude_priors_method="noprior",
1292 nwalkers=18, nsteps=1000, burnin=100, nbins=10,
1293 verbose=0, plot=False, live_fit=False, truth=None):
1294 ChromaticPSFFitWorkspace.__init__(self, chromatic_psf, data, data_errors, bgd_model_func,
1295 file_name, amplitude_priors_method, nwalkers, nsteps, burnin, nbins, verbose,
1296 plot, live_fit, truth=truth)
1297 self.my_logger = set_logger(self.__class__.__name__)
1298 self.pixels = np.arange(self.Ny)
1300 # error matrix
1301 # here image uncertainties are assumed to be uncorrelated
1302 # (which is not exactly true in rotated images)
1303 self.data_cov = self.err * self.err
1304 W = 1. / (self.err * self.err)
1305 # these lines make the code thinks that W is block diagonal
1306 self.W = np.empty(self.Nx, dtype=np.object)
1307 for x in range(self.Nx):
1308 self.W[x] = W[:, x]
1310 # data: ordered by pixel columns
1311 data = np.empty(self.Nx, dtype=np.object)
1312 err = np.empty(self.Nx, dtype=np.object)
1313 for x in range(self.Nx):
1314 data[x] = self.data[:, x]
1315 err[x] = self.err[:, x]
1316 self.data = data
1317 self.err = err
1318 self.pixels = self.pixels.T
1320 def simulate(self, *shape_params):
1321 """
1322 Compute a ChromaticPSF model given PSF shape parameters and minimizing
1323 amplitude parameters given a spectrogram data array.
1325 Parameters
1326 ----------
1327 shape_params: array_like
1328 PSF shape polynomial parameter array.
1330 Examples
1331 --------
1333 Set the parameters:
1335 >>> parameters.PIXDIST_BACKGROUND = 40
1336 >>> parameters.PIXWIDTH_BACKGROUND = 10
1337 >>> parameters.PIXWIDTH_SIGNAL = 30
1339 Build a mock spectrogram with random Poisson noise:
1341 >>> psf = MoffatGauss()
1342 >>> s0 = ChromaticPSF(psf, Nx=100, Ny=100, deg=4, saturation=1000)
1343 >>> params = s0.generate_test_poly_params()
1344 >>> s0.poly_params = params
1345 >>> saturation = params[-1]
1346 >>> data = s0.evaluate(params, mode="1D")
1347 >>> bgd = 10*np.ones_like(data)
1348 >>> data += bgd
1349 >>> data = np.random.poisson(data)
1350 >>> data_errors = np.sqrt(data+1)
1352 Extract the background:
1354 >>> bgd_model_func, _, _ = extract_spectrogram_background_sextractor(data, data_errors, ws=[30,50])
1356 Estimate the first guess values:
1358 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=4, saturation=saturation)
1359 >>> s.fit_transverse_PSF1D_profile(data, data_errors, w=20, ws=[30,50],
1360 ... pixel_step=1, bgd_model_func=bgd_model_func, saturation=saturation, live_fit=False)
1361 >>> guess = np.copy(s.table["amplitude"])
1363 Fit the amplitude of data without any prior:
1365 >>> w = ChromaticPSF1DFitWorkspace(s, data, data_errors, bgd_model_func=bgd_model_func, verbose=True,
1366 ... amplitude_priors_method="noprior")
1367 >>> y, mod, mod_err = w.simulate(*s.poly_params[s.Nx:])
1368 >>> w.plot_fit()
1370 .. doctest::
1371 :hide:
1373 >>> assert mod is not None
1374 >>> assert np.mean(np.abs(mod.flatten()-np.concatenate(w.data).ravel())/np.concatenate(w.err).ravel()) < 1
1376 Fit the amplitude of data smoothing the result with a window of size 10 pixels:
1378 >>> w = ChromaticPSF1DFitWorkspace(s, data, data_errors, bgd_model_func=bgd_model_func, verbose=True,
1379 ... amplitude_priors_method="smooth")
1380 >>> y, mod, mod_err = w.simulate(*s.poly_params[s.Nx:])
1381 >>> w.plot_fit()
1383 .. doctest::
1384 :hide:
1386 >>> assert mod is not None
1387 >>> assert np.mean(np.abs(mod.flatten()-np.concatenate(w.data).ravel())/np.concatenate(w.err).ravel()) < 1
1389 Fit the amplitude of data using the transverse PSF1D fit as a prior and with a
1390 Tikhonov regularisation parameter set by parameters.PSF_FIT_REG_PARAM:
1392 >>> w = ChromaticPSF1DFitWorkspace(s, data, data_errors, bgd_model_func=bgd_model_func, verbose=True,
1393 ... amplitude_priors_method="psf1d")
1394 >>> y, mod, mod_err = w.simulate(*s.poly_params[s.Nx:])
1395 >>> w.plot_fit()
1397 .. doctest::
1398 :hide:
1400 >>> assert mod is not None
1401 >>> assert np.mean(np.abs(mod.flatten()-np.concatenate(w.data).ravel())/np.concatenate(w.err).ravel()) < 1
1403 Set the amplitude parameters fixing the transverse PSF1D fit amplitudes:
1405 >>> w = ChromaticPSF1DFitWorkspace(s, data, data_errors, bgd_model_func=bgd_model_func, verbose=True,
1406 ... amplitude_priors_method="fixed")
1407 >>> y, mod, mod_err = w.simulate(*s.poly_params[s.Nx:])
1408 >>> w.plot_fit()
1410 .. doctest::
1411 :hide:
1413 >>> assert mod is not None
1414 >>> assert np.mean(np.abs(mod.flatten()-np.concatenate(w.data).ravel())/np.concatenate(w.err).ravel()) < 1
1416 """
1417 # linear regression for the amplitude parameters
1418 poly_params = np.copy(self.poly_params)
1419 poly_params[self.Nx:] = np.copy(shape_params)
1420 poly_params[self.Nx + self.y_c_0_index] -= self.bgd_width
1421 profile_params = self.chromatic_psf.from_poly_params_to_profile_params(poly_params, apply_bounds=True)
1422 profile_params[:self.Nx, 0] = 1
1423 profile_params[:self.Nx, 1] = np.arange(self.Nx)
1424 # profile_params[:self.Nx, 2] -= self.bgd_width
1425 if self.amplitude_priors_method != "fixed":
1426 # Matrix filling
1427 M = np.array([self.chromatic_psf.psf.evaluate(self.pixels, p=profile_params[x, :]) for x in range(self.Nx)])
1428 M_dot_W_dot_M = np.array([M[x].T @ (self.W[x] * M[x]) for x in range(self.Nx)])
1429 if self.amplitude_priors_method != "psf1d":
1430 cov_matrix = np.diag([1 / M_dot_W_dot_M[x] if M_dot_W_dot_M[x] > 0 else 0.1 * self.bgd_std
1431 for x in range(self.Nx)])
1432 amplitude_params = np.array([
1433 M[x].T @ (self.W[x] * self.data[x]) / (M_dot_W_dot_M[x]) if M_dot_W_dot_M[x] > 0 else 0.1 * self.bgd_std
1434 for x in range(self.Nx)])
1435 if self.amplitude_priors_method == "positive":
1436 amplitude_params[amplitude_params < 0] = 0
1437 elif self.amplitude_priors_method == "smooth":
1438 null_indices = np.where(amplitude_params < 0)[0]
1439 for index in null_indices:
1440 right = amplitude_params[index]
1441 for i in range(index, min(index + 10, self.Nx)):
1442 right = amplitude_params[i]
1443 if i not in null_indices:
1444 break
1445 left = amplitude_params[index]
1446 for i in range(index, max(0, index - 10), -1):
1447 left = amplitude_params[i]
1448 if i not in null_indices:
1449 break
1450 amplitude_params[index] = 0.5 * (right + left)
1451 elif self.amplitude_priors_method == "noprior":
1452 pass
1453 else:
1454 M_dot_W_dot_M_plus_Q = [M_dot_W_dot_M[x] + self.reg * self.Q[x, x] for x in range(self.Nx)]
1455 cov_matrix = np.diag([1 / M_dot_W_dot_M_plus_Q[x] if M_dot_W_dot_M_plus_Q[x] > 0 else 0.1 * self.bgd_std
1456 for x in range(self.Nx)])
1457 amplitude_params = [cov_matrix[x, x] * (M[x].T @ (self.W[x] * self.data[x]) + self.reg * self.Q_dot_A0[x])
1458 for x in range(self.Nx)]
1459 self.M = M
1460 self.M_dot_W_dot_M = M_dot_W_dot_M
1461 self.model = np.zeros((self.Nx, self.Ny), dtype=float)
1462 for x in range(self.Nx):
1463 self.model[x] = M[x] * amplitude_params[x]
1465 else:
1466 amplitude_params = np.copy(self.amplitude_priors)
1467 err2 = np.copy(amplitude_params)
1468 err2[err2 <= 0] = np.min(np.abs(err2[err2 > 0]))
1469 cov_matrix = np.diag(err2)
1470 self.amplitude_params = np.copy(amplitude_params)
1471 self.amplitude_params_err = np.array([np.sqrt(cov_matrix[x, x])
1472 if cov_matrix[x, x] > 0 else 0 for x in range(self.Nx)])
1473 self.amplitude_cov_matrix = np.copy(cov_matrix)
1474 poly_params[:self.Nx] = amplitude_params
1475 self.poly_params = np.copy(poly_params)
1476 poly_params[self.Nx + self.y_c_0_index] += self.bgd_width
1477 if self.amplitude_priors_method == "fixed":
1478 self.model = self.chromatic_psf.evaluate(poly_params, mode="1D")[self.bgd_width:-self.bgd_width, :].T
1479 self.model_err = np.zeros_like(self.model)
1480 return self.pixels, self.model, self.model_err
1483class ChromaticPSF2DFitWorkspace(ChromaticPSFFitWorkspace):
1485 def __init__(self, chromatic_psf, data, data_errors, bgd_model_func=None, amplitude_priors_method="noprior",
1486 file_name="", nwalkers=18, nsteps=1000, burnin=100, nbins=10,
1487 verbose=0, plot=False, live_fit=False, truth=None):
1488 ChromaticPSFFitWorkspace.__init__(self, chromatic_psf, data, data_errors, bgd_model_func,
1489 file_name, amplitude_priors_method, nwalkers, nsteps, burnin, nbins, verbose,
1490 plot,
1491 live_fit, truth=truth)
1492 self.my_logger = set_logger(self.__class__.__name__)
1493 yy, xx = np.mgrid[:self.Ny, :self.Nx]
1494 self.pixels = np.asarray([xx, yy])
1496 # error matrix
1497 # here image uncertainties are assumed to be uncorrelated
1498 # (which is not exactly true in rotated images)
1499 self.W = 1. / (self.err * self.err)
1500 self.W = self.W.flatten()
1501 self.data = self.data.flatten()
1502 self.err = self.err.flatten()
1504 # regularisation matrices
1505 self.reg = parameters.PSF_FIT_REG_PARAM
1506 if amplitude_priors_method == "psf1d":
1507 # U = np.diag([1 / np.sqrt(np.sum(self.err[:, x]**2)) for x in range(self.Nx)])
1508 self.U = np.diag([1 / np.sqrt(self.amplitude_priors_cov_matrix[x, x]) for x in range(self.Nx)])
1509 L = np.diag(-2 * np.ones(self.Nx)) + np.diag(np.ones(self.Nx), -1)[:-1, :-1] \
1510 + np.diag(np.ones(self.Nx), 1)[:-1, :-1]
1511 L.astype(float)
1512 L[0, 0] = -1
1513 L[-1, -1] = -1
1514 self.L = L
1515 self.Q = L.T @ self.U.T @ self.U @ L
1516 self.Q_dot_A0 = self.Q @ self.amplitude_priors
1518 def simulate(self, *shape_params):
1519 r"""
1520 Compute a ChromaticPSF2D model given PSF shape parameters and minimizing
1521 amplitude parameters using a spectrogram data array.
1523 The ChromaticPSF2D model :math:`\vec{m}(\vec{x},\vec{p})` can be written as
1525 .. math ::
1526 :label: chromaticpsf2d
1528 \vec{m}(\vec{x},\vec{p}) = \sum_{i=0}^{N_x} A_i \phi\left(\vec{x},\vec{p}_i\right)
1530 with :math:`\vec{x}` the 2D array of the pixel coordinates, :math:`\vec{A}` the amplitude parameter array
1531 along the x axis of the spectrogram, :math:`\phi\left(\vec{x},\vec{p}_i\right)` the 2D PSF kernel whose integral
1532 is normalised to one parametrized with the :math:`\vec{p}_i` non-linear parameter array. If the :math:`\vec{x}`
1533 2D array is flatten in 1D, equation :eq:`chromaticpsf2d` is
1535 .. math ::
1536 :label: chromaticpsf2d_matrix
1537 :nowrap:
1539 \begin{align}
1540 \vec{m}(\vec{x},\vec{p}) & = \mathbf{M}\left(\vec{x},\vec{p}\right) \mathbf{A} \\
1542 \mathbf{M}\left(\vec{x},\vec{p}\right) & = \left(\begin{array}{cccc}
1543 \phi\left(\vec{x}_1,\vec{p}_1\right) & \phi\left(\vec{x}_2,\vec{p}_1\right) & ...
1544 & \phi\left(\vec{x}_{N_x},\vec{p}_1\right) \\
1545 ... & ... & ... & ...\\
1546 \phi\left(\vec{x}_1,\vec{p}_{N_x}\right) & \phi\left(\vec{x}_2,\vec{p}_{N_x}\right) & ...
1547 & \phi\left(\vec{x}_{N_x},\vec{p}_{N_x}\right) \\
1548 \end{array}\right)
1549 \end{align}
1552 with :math:`\mathbf{M}` the design matrix.
1554 The goal of this function is to perform a minimisation of the amplitude vector :math:`\mathbf{A}` given
1555 a set of non-linear parameters :math:`\mathbf{p}` and a spectrogram data array :math:`mathbf{y}` modelise as
1557 .. math:: \mathbf{y} = \mathbf{m}(\vec{x},\vec{p}) + \vec{\epsilon}
1559 with :math:`\vec{\epsilon}` a random noise vector. The :math:`\chi^2` function to minimise is
1561 .. math::
1562 :label: chromaticspsf2d_chi2
1564 \chi^2(\mathbf{A})= \left(\mathbf{y} - \mathbf{M}\left(\vec{x},\vec{p}\right) \mathbf{A}\right)^T \mathbf{W}
1565 \left(\mathbf{y} - \mathbf{M}\left(\vec{x},\vec{p}\right) \mathbf{A} \right)
1568 with :math:`\mathbf{W}` the weight matrix, inverse of the covariance matrix. In our case this matrix is diagonal
1569 as the pixels are considered all independent. The minimum of equation :eq:`chromaticspsf2d_chi2` is reached for
1570 a the set of amplitude parameters :math:`\hat{\mathbf{A}}` given by
1572 .. math::
1574 \hat{\mathbf{A}} = (\mathbf{M}^T \mathbf{W} \mathbf{M})^{-1} \mathbf{M}^T \mathbf{W} \mathbf{y}
1576 The error matrix on the :math:`\hat{\mathbf{A}}` coefficient is simply
1577 :math:`(\mathbf{M}^T \mathbf{W} \mathbf{M})^{-1}`.
1579 See Also
1580 --------
1581 ChromaticPSF1DFitWorkspace.simulate
1583 Parameters
1584 ----------
1585 shape_params: array_like
1586 PSF shape polynomial parameter array.
1588 Examples
1589 --------
1591 Set the parameters:
1593 .. doctest::
1595 >>> parameters.PIXDIST_BACKGROUND = 40
1596 >>> parameters.PIXWIDTH_BACKGROUND = 10
1597 >>> parameters.PIXWIDTH_SIGNAL = 30
1599 Build a mock spectrogram with random Poisson noise:
1601 .. doctest::
1603 >>> psf = Moffat()
1604 >>> s0 = ChromaticPSF(psf, Nx=120, Ny=100, deg=2, saturation=100000)
1605 >>> params = s0.generate_test_poly_params()
1606 >>> params[:s0.Nx] *= 10
1607 >>> s0.poly_params = params
1608 >>> saturation = params[-1]
1609 >>> data = s0.evaluate(params, mode="2D")
1610 >>> bgd = 10*np.ones_like(data)
1611 >>> data += bgd
1612 >>> data = np.random.poisson(data)
1613 >>> data_errors = np.sqrt(data+1)
1615 Extract the background:
1617 .. doctest::
1619 >>> bgd_model_func, _, _ = extract_spectrogram_background_sextractor(data, data_errors, ws=[30,50])
1621 Estimate the first guess values:
1623 .. doctest::
1625 >>> s = ChromaticPSF(psf, Nx=120, Ny=100, deg=2, saturation=saturation)
1626 >>> s.fit_transverse_PSF1D_profile(data, data_errors, w=20, ws=[30,50],
1627 ... pixel_step=1, bgd_model_func=bgd_model_func, saturation=saturation, live_fit=False)
1628 >>> s.plot_summary(truth=s0)
1630 Simulate the data with fixed amplitude priors:
1632 .. doctest::
1634 >>> w = ChromaticPSF2DFitWorkspace(s, data, data_errors, bgd_model_func=bgd_model_func,
1635 ... amplitude_priors_method="fixed", verbose=True)
1636 >>> y, mod, mod_err = w.simulate(s.poly_params[s.Nx:])
1637 >>> w.plot_fit()
1639 .. doctest::
1640 :hide:
1642 >>> assert mod is not None
1644 Simulate the data with a Tikhonov prior on amplitude parameters:
1646 .. doctest::
1648 >>> parameters.PSF_FIT_REG_PARAM = 0.002
1649 >>> s.poly_params = s.from_table_to_poly_params()
1650 >>> w = ChromaticPSF2DFitWorkspace(s, data, data_errors, bgd_model_func=bgd_model_func,
1651 ... amplitude_priors_method="psf1d", verbose=True)
1652 >>> y, mod, mod_err = w.simulate(s.poly_params[s.Nx:])
1653 >>> w.plot_fit()
1655 .. doctest::
1656 :hide:
1658 >>> assert mod is not None
1659 >>> w = ChromaticPSF2DFitWorkspace(s0, data, data_errors, bgd_model_func=bgd_model_func,
1660 ... amplitude_priors_method="fixed", verbose=True)
1661 >>> y, mod, mod_err = w.simulate(s0.poly_params[s0.Nx:])
1662 >>> w.plot_fit()
1663 >>> assert np.abs(np.mean((w.amplitude_params-s0.poly_params[:s0.Nx])/w.amplitude_params_err)) < 0.05
1665 """
1666 # linear regression for the amplitude parameters
1667 # prepare the vectors
1668 poly_params = np.copy(self.poly_params)
1669 poly_params[self.Nx:] = np.copy(shape_params)
1670 poly_params[self.Nx + self.y_c_0_index] -= self.bgd_width
1671 profile_params = self.chromatic_psf.from_poly_params_to_profile_params(poly_params, apply_bounds=True)
1672 profile_params[:self.Nx, 0] = 1
1673 profile_params[:self.Nx, 1] = np.arange(self.Nx)
1674 # profile_params[:self.Nx, 2] -= self.bgd_width
1675 if self.amplitude_priors_method != "fixed":
1676 # Matrix filling
1677 M = np.array([self.chromatic_psf.psf.evaluate(self.pixels, p=profile_params[x, :]).flatten()
1678 for x in range(self.Nx)]).T
1679 W_dot_M = np.array([M[:, x] * self.W for x in range(self.Nx)]).T
1680 # Compute the minimizing amplitudes
1681 M_dot_W_dot_M = M.T @ W_dot_M
1682 if self.amplitude_priors_method != "psf1d":
1683 try:
1684 L = np.linalg.inv(np.linalg.cholesky(M_dot_W_dot_M))
1685 cov_matrix = L.T @ L
1686 except np.linalg.LinAlgError:
1687 cov_matrix = np.linalg.inv(M_dot_W_dot_M)
1688 amplitude_params = cov_matrix @ (M.T @ (self.W * self.data))
1689 if self.amplitude_priors_method == "positive":
1690 amplitude_params[amplitude_params < 0] = 0
1691 elif self.amplitude_priors_method == "smooth":
1692 null_indices = np.where(amplitude_params < 0)[0]
1693 for index in null_indices:
1694 right = amplitude_params[index]
1695 for i in range(index, min(index + 10, self.Nx)):
1696 right = amplitude_params[i]
1697 if i not in null_indices:
1698 break
1699 left = amplitude_params[index]
1700 for i in range(index, max(0, index - 10), -1):
1701 left = amplitude_params[i]
1702 if i not in null_indices:
1703 break
1704 amplitude_params[index] = 0.5 * (right + left)
1705 elif self.amplitude_priors_method == "noprior":
1706 pass
1707 else:
1708 M_dot_W_dot_M_plus_Q = M_dot_W_dot_M + self.reg * self.Q
1709 try:
1710 L = np.linalg.inv(np.linalg.cholesky(M_dot_W_dot_M_plus_Q))
1711 cov_matrix = L.T @ L
1712 except np.linalg.LinAlgError:
1713 cov_matrix = np.linalg.inv(M_dot_W_dot_M_plus_Q)
1714 amplitude_params = cov_matrix @ (M.T @ (self.W * self.data) + self.reg * self.Q_dot_A0)
1715 self.M = M
1716 self.M_dot_W_dot_M = M_dot_W_dot_M
1717 self.model = (M @ amplitude_params) #.reshape((self.Ny, self.Nx))
1718 else:
1719 amplitude_params = np.copy(self.amplitude_priors)
1720 err2 = np.copy(amplitude_params)
1721 err2[err2 <= 0] = np.min(np.abs(err2[err2 > 0]))
1722 cov_matrix = np.diag(err2)
1723 poly_params[:self.Nx] = amplitude_params
1724 self.poly_params = np.copy(poly_params)
1725 poly_params[self.Nx + self.y_c_0_index] += self.bgd_width
1726 self.amplitude_params = np.copy(amplitude_params)
1727 # TODO: propagate and marginalize over the shape parameter uncertainties ?
1728 self.amplitude_params_err = np.array([np.sqrt(cov_matrix[x, x]) for x in range(self.Nx)])
1729 self.amplitude_cov_matrix = np.copy(cov_matrix)
1730 # in_bounds, penalty, name = self.chromatic_psf.check_bounds(poly_params, noise_level=self.bgd_std)
1731 if self.amplitude_priors_method == "fixed":
1732 self.model = self.chromatic_psf.evaluate(poly_params, mode="2D")[self.bgd_width:-self.bgd_width, :]
1733 self.model_err = np.zeros_like(self.model)
1734 return self.pixels, self.model, self.model_err
1737if __name__ == "__main__": 1737 ↛ 1738line 1737 didn't jump to line 1738, because the condition on line 1737 was never true
1738 import doctest
1740 doctest.testmod()