Coverage for spectractor/extractor/psf.py: 14%
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 numpy as np
3import matplotlib.pyplot as plt
4from scipy import special
5from scipy.interpolate import interp2d
7from spectractor.tools import plot_image_simple
8from spectractor import parameters
9from spectractor.config import set_logger
10from spectractor.fit.fitter import FitWorkspace, run_minimisation
12from numba import njit
15@njit(fastmath=True, cache=True)
16def evaluate_moffat1d_unnormalized(y, amplitude, y_c, gamma, alpha): # pragma: nocover
17 r"""Compute a 1D Moffat function, whose integral is not normalised to unity.
19 .. math ::
21 f(y) \propto \frac{A}{\left[ 1 +\left(\frac{y-y_c}{\gamma}\right)^2 \right]^\alpha}
22 \quad\text{with}, \alpha > 1/2
24 Note that this function is defined only for :math:`alpha > 1/2`. The normalisation factor
25 :math:`\frac{\Gamma(alpha)}{\gamma \sqrt{\pi} \Gamma(alpha -1/2)}` is not included as special functions
26 are not supported by numba library.
28 Parameters
29 ----------
30 y: array_like
31 1D array of pixels :math:`y`, regularly spaced.
32 amplitude: float
33 Integral :math:`A` of the function.
34 y_c: float
35 Center :math:`y_c` of the function.
36 gamma: float
37 Width :math:`\gamma` of the function.
38 alpha: float
39 Exponent :math:`\alpha` of the Moffat function.
41 Returns
42 -------
43 output: array_like
44 1D array of the function evaluated on the y pixel array.
46 Examples
47 --------
49 >>> Ny = 50
50 >>> y = np.arange(Ny)
51 >>> amplitude = 10
52 >>> alpha = 2
53 >>> gamma = 5
54 >>> a = evaluate_moffat1d_unnormalized(y, amplitude=amplitude, y_c=Ny/2, gamma=gamma, alpha=alpha)
55 >>> norm = gamma * np.sqrt(np.pi) * special.gamma(alpha - 0.5) / special.gamma(alpha)
56 >>> a = a / norm
57 >>> print(f"{np.sum(a):.6f}")
58 9.967561
60 .. doctest::
61 :hide:
63 >>> assert np.isclose(np.argmax(a), Ny/2, atol=0.5)
64 >>> assert np.isclose(np.argmax(a), Ny/2, atol=0.5)
66 .. plot::
68 import numpy as np
69 import matplotlib.pyplot as plt
70 from spectractor.extractor.psf import *
71 Ny = 50
72 y = np.arange(Ny)
73 amplitude = 10
74 a = evaluate_moffat1d(y, amplitude=amplitude, y_c=Ny/2, gamma=5, alpha=2)
75 plt.plot(a)
76 plt.grid()
77 plt.xlabel("y")
78 plt.ylabel("Moffat")
79 plt.show()
81 """
82 rr = (y - y_c) * (y - y_c)
83 rr_gg = rr / (gamma * gamma)
84 a = (1 + rr_gg) ** -alpha
85 # dx = y[1] - y[0]
86 # integral = np.sum(a) * dx
87 # norm = amplitude
88 # if integral != 0:
89 # a /= integral
90 # a *= amplitude
91 a *= amplitude
92 return a
95@njit(fastmath=True, cache=True)
96def evaluate_moffatgauss1d_unnormalized(y, amplitude, y_c, gamma, alpha, eta_gauss, sigma): # pragma: nocover
97 r"""Compute a 1D Moffat-Gaussian function, whose integral is not normalised to unity.
99 .. math ::
101 f(y) \propto A \left\lbrace
102 \frac{1}{\left[ 1 +\left(\frac{y-y_c}{\gamma}\right)^2 \right]^\alpha}
103 - \eta e^{-(y-y_c)^2/(2\sigma^2)}\right\rbrace
104 \quad\text{ and } \quad \eta < 0, \alpha > 1/2
106 Note that this function is defined only for :math:`alpha > 1/2`. The normalisation factor for the Moffat
107 :math:`\frac{\Gamma(alpha)}{\gamma \sqrt{\pi} \Gamma(alpha -1/2)}` is not included as special functions
108 are not supproted by the numba library.
110 Parameters
111 ----------
112 y: array_like
113 1D array of pixels :math:`y`, regularly spaced.
114 amplitude: float
115 Integral :math:`A` of the function.
116 y_c: float
117 Center :math:`y_c` of the function.
118 gamma: float
119 Width :math:`\gamma` of the Moffat function.
120 alpha: float
121 Exponent :math:`\alpha` of the Moffat function.
122 eta_gauss: float
123 Relative negative amplitude of the Gaussian function.
124 sigma: float
125 Width :math:`\sigma` of the Gaussian function.
127 Returns
128 -------
129 output: array_like
130 1D array of the function evaluated on the y pixel array.
132 Examples
133 --------
135 >>> Ny = 50
136 >>> y = np.arange(Ny)
137 >>> amplitude = 10
138 >>> gamma = 5
139 >>> alpha = 2
140 >>> eta_gauss = -0.1
141 >>> sigma = 1
142 >>> a = evaluate_moffatgauss1d_unnormalized(y, amplitude=amplitude, y_c=Ny/2, gamma=gamma, alpha=alpha,
143 ... eta_gauss=eta_gauss, sigma=sigma)
144 >>> norm = gamma*np.sqrt(np.pi)*special.gamma(alpha-0.5)/special.gamma(alpha) + eta_gauss*np.sqrt(2*np.pi)*sigma
145 >>> a = a / norm
146 >>> print(f"{np.sum(a):.6f}")
147 9.966492
149 .. doctest::
150 :hide:
152 >>> assert np.isclose(np.sum(a), amplitude, atol=0.5)
153 >>> assert np.isclose(np.argmax(a), Ny/2, atol=0.5)
155 .. plot::
157 import numpy as np
158 import matplotlib.pyplot as plt
159 from spectractor.extractor.psf import *
160 Ny = 50
161 y = np.arange(Ny)
162 amplitude = 10
163 a = evaluate_moffatgauss1d(y, amplitude=amplitude, y_c=Ny/2, gamma=5, alpha=2, eta_gauss=-0.1, sigma=1)
164 plt.plot(a)
165 plt.grid()
166 plt.xlabel("y")
167 plt.ylabel("Moffat")
168 plt.show()
170 """
171 rr = (y - y_c) * (y - y_c)
172 rr_gg = rr / (gamma * gamma)
173 a = (1 + rr_gg) ** -alpha + eta_gauss * np.exp(-(rr / (2. * sigma * sigma)))
174 # dx = y[1] - y[0]
175 # integral = np.sum(a) * dx
176 # norm = amplitude
177 # if integral != 0:
178 # norm /= integral
179 # a *= norm
180 a *= amplitude
181 return a
184@njit(fastmath=True, cache=True)
185def evaluate_moffat2d(x, y, amplitude, x_c, y_c, gamma, alpha): # pragma: nocover
186 r"""Compute a 2D Moffat function, whose integral is normalised to unity.
188 .. math ::
190 f(x, y) = \frac{A (\alpha - 1)}{\pi \gamma^2} \frac{1}{
191 \left[ 1 +\frac{\left(x-x_c\right)^2+\left(y-y_c\right)^2}{\gamma^2} \right]^\alpha}
192 \quad\text{with}\quad
193 \int_{-\infty}^{\infty}\int_{-\infty}^{\infty}f(x, y) \mathrm{d}x \mathrm{d}y = A
195 Note that this function is defined only for :math:`alpha > 1`.
197 Note that the normalisation of a 2D Moffat function is analytical so it is not expected that
198 the sum of the output array is equal to :math:`A`, but lower.
200 Parameters
201 ----------
202 x: array_like
203 2D array of pixels :math:`x`, regularly spaced.
204 y: array_like
205 2D array of pixels :math:`y`, regularly spaced.
206 amplitude: float
207 Integral :math:`A` of the function.
208 x_c: float
209 X axis center :math:`x_c` of the function.
210 y_c: float
211 Y axis center :math:`y_c` of the function.
212 gamma: float
213 Width :math:`\gamma` of the function.
214 alpha: float
215 Exponent :math:`\alpha` of the Moffat function.
217 Returns
218 -------
219 output: array_like
220 2D array of the function evaluated on the y pixel array.
222 Examples
223 --------
225 >>> Nx = 50
226 >>> Ny = 50
227 >>> yy, xx = np.mgrid[:Ny, :Nx]
228 >>> amplitude = 10
229 >>> a = evaluate_moffat2d(xx, yy, amplitude=amplitude, x_c=Nx/2, y_c=Ny/2, gamma=5, alpha=2)
230 >>> print(f"{np.sum(a):.6f}")
231 9.683129
233 .. doctest::
234 :hide:
236 >>> assert not np.isclose(np.sum(a), amplitude)
238 .. plot::
240 import numpy as np
241 import matplotlib.pyplot as plt
242 from spectractor.extractor.psf import *
243 Nx = 50
244 Ny = 50
245 yy, xx = np.mgrid[:Nx, :Ny]
246 amplitude = 10
247 a = evaluate_moffat2d(xx, yy, amplitude=amplitude, y_c=Ny/2, x_c=Nx/2, gamma=5, alpha=2)
248 im = plt.pcolor(xx, yy, a)
249 plt.grid()
250 plt.xlabel("x")
251 plt.ylabel("y")
252 plt.colorbar(im, label="Moffat 2D")
253 plt.show()
255 """
256 rr_gg = ((x - x_c) * (x - x_c) / (gamma * gamma) + (y - y_c) * (y - y_c) / (gamma * gamma))
257 a = (1 + rr_gg) ** -alpha
258 norm = (np.pi * gamma * gamma) / (alpha - 1)
259 a *= amplitude / norm
260 return a
263@njit(fastmath=True, cache=True)
264def evaluate_moffatgauss2d(x, y, amplitude, x_c, y_c, gamma, alpha, eta_gauss, sigma): # pragma: nocover
265 r"""Compute a 2D Moffat-Gaussian function, whose integral is normalised to unity.
267 .. math ::
269 f(x, y) = \frac{A}{\frac{\pi \gamma^2}{\alpha-1} + 2 \pi \eta \sigma^2}\left\lbrace \frac{1}{
270 \left[ 1 +\frac{\left(x-x_c\right)^2+\left(y-y_c\right)^2}{\gamma^2} \right]^\alpha}
271 + \eta e^{-\left[ \left(x-x_c\right)^2+\left(y-y_c\right)^2\right]/(2 \sigma^2)}
272 \right\rbrace
274 .. math ::
275 \quad\text{with}\quad
276 \int_{-\infty}^{\infty}\int_{-\infty}^{\infty}f(x, y) \mathrm{d}x \mathrm{d}y = A
277 \quad\text{and} \quad \eta < 0
279 Note that this function is defined only for :math:`alpha > 1`.
281 Parameters
282 ----------
283 x: array_like
284 2D array of pixels :math:`x`, regularly spaced.
285 y: array_like
286 2D array of pixels :math:`y`, regularly spaced.
287 amplitude: float
288 Integral :math:`A` of the function.
289 x_c: float
290 X axis center :math:`x_c` of the function.
291 y_c: float
292 Y axis center :math:`y_c` of the function.
293 gamma: float
294 Width :math:`\gamma` of the function.
295 alpha: float
296 Exponent :math:`\alpha` of the Moffat function.
297 eta_gauss: float
298 Relative negative amplitude of the Gaussian function.
299 sigma: float
300 Width :math:`\sigma` of the Gaussian function.
302 Returns
303 -------
304 output: array_like
305 2D array of the function evaluated on the y pixel array.
307 Examples
308 --------
310 >>> Nx = 50
311 >>> Ny = 50
312 >>> yy, xx = np.mgrid[:Ny, :Nx]
313 >>> amplitude = 10
314 >>> a = evaluate_moffatgauss2d(xx, yy, amplitude=amplitude, x_c=Nx/2, y_c=Ny/2, gamma=5, alpha=2,
315 ... eta_gauss=-0.1, sigma=1)
316 >>> print(f"{np.sum(a):.6f}")
317 9.680573
319 .. doctest::
320 :hide:
322 >>> assert not np.isclose(np.sum(a), amplitude)
324 .. plot::
326 import numpy as np
327 import matplotlib.pyplot as plt
328 from spectractor.extractor.psf import *
329 Nx = 50
330 Ny = 50
331 yy, xx = np.mgrid[:Nx, :Ny]
332 amplitude = 10
333 a = evaluate_moffatgauss2d(xx, yy, amplitude, Nx/2, Ny/2, gamma=5, alpha=2, eta_gauss=-0.1, sigma=1)
334 im = plt.pcolor(xx, yy, a)
335 plt.grid()
336 plt.xlabel("x")
337 plt.ylabel("y")
338 plt.colorbar(im, label="Moffat 2D")
339 plt.show()
341 """
342 rr = ((x - x_c) * (x - x_c) + (y - y_c) * (y - y_c))
343 rr_gg = rr / (gamma * gamma)
344 a = (1 + rr_gg) ** -alpha + eta_gauss * np.exp(-(rr / (2. * sigma * sigma)))
345 norm = (np.pi * gamma * gamma) / (alpha - 1) + eta_gauss * 2 * np.pi * sigma * sigma
346 a *= amplitude / norm
347 return a
350class PSF:
351 """Generic PSF model class.
353 The PSF models must contain at least the "amplitude", "x_c" and "y_c" parameters as the first three parameters
354 (in this order) and "saturation" parameter as the last parameter. "amplitude", "x_c" and "y_c"
355 stands respectively for the general amplitude of the model, the position along the dispersion axis and the
356 transverse position with respect to the dispersion axis (assumed to be the X axis).
357 Last "saturation" parameter must be express in the same units as the signal to model and as the "amplitude"
358 parameter. The PSF models must be normalized to one in total flux divided by the first parameter (amplitude).
359 Then the PSF model integral is equal to the "amplitude" parameter.
361 """
363 def __init__(self, clip=False):
364 """
365 Parameters
366 ----------
367 clip: bool, optional
368 If True, PSF evaluation is clipped between 0 and saturation level (slower) (default: False)
370 """
371 self.my_logger = set_logger(self.__class__.__name__)
372 self.p = np.array([])
373 self.param_names = ["amplitude", "x_c", "y_c", "saturation"]
374 self.axis_names = ["$A$", r"$x_c$", r"$y_c$", "saturation"]
375 self.bounds = [[]]
376 self.p_default = np.array([1, 0, 0, 1])
377 self.max_half_width = np.inf
378 self.clip = clip
380 def evaluate(self, pixels, p=None): # pragma: no cover
381 if p is not None:
382 self.p = np.asarray(p).astype(float)
383 if pixels.ndim == 3 and pixels.shape[0] == 2:
384 return np.zeros_like(pixels)
385 elif pixels.ndim == 1:
386 return np.zeros_like(pixels)
387 else:
388 raise ValueError(f"Pixels array must have dimension 1 or shape=(2,Nx,Ny). Here pixels.ndim={pixels.shape}.")
390 def apply_max_width_to_bounds(self, max_half_width=None): # pragma: no cover
391 pass
393 def fit_psf(self, data, data_errors=None, bgd_model_func=None):
394 """
395 Fit a PSF model on 1D or 2D data.
397 Parameters
398 ----------
399 data: array_like
400 1D or 2D array containing the data.
401 data_errors: np.array, optional
402 The 1D or 2D array of uncertainties.
403 bgd_model_func: callable, optional
404 A 1D or 2D function to model the extracted background (default: None -> null background).
406 Returns
407 -------
408 fit_workspace: PSFFitWorkspace
409 The PSFFitWorkspace instance to get info about the fitting.
411 Examples
412 --------
414 Build a mock PSF2D without background and with random Poisson noise:
416 >>> p0 = np.array([200000, 20, 30, 5, 2, -0.1, 2, 400000])
417 >>> psf0 = MoffatGauss(p0)
418 >>> yy, xx = np.mgrid[:50, :60]
419 >>> data = psf0.evaluate(np.array([xx, yy]), p0)
420 >>> data = np.random.poisson(data)
421 >>> data_errors = np.sqrt(data+1)
423 Fit the data in 2D:
425 >>> p = np.array([150000, 19, 31, 4.5, 2.5, -0.1, 3, 400000])
426 >>> psf = MoffatGauss(p)
427 >>> w = psf.fit_psf(data, data_errors=data_errors, bgd_model_func=None)
428 >>> w.plot_fit()
430 .. doctest::
431 :hide:
433 >>> assert w.model is not None
434 >>> residuals = (w.data-w.model)/w.err
435 >>> assert w.costs[-1] / w.pixels.size < 1.3
436 >>> assert np.abs(np.mean(residuals)) < 0.4
437 >>> assert np.std(residuals) < 1.2
438 >>> assert np.all(np.isclose(psf.p[1:3], p0[1:3], atol=1e-1))
440 Fit the data in 1D:
442 >>> data1d = data[:,int(p0[1])]
443 >>> data1d_err = data_errors[:,int(p0[1])]
444 >>> p = np.array([10000, 20, 32, 4, 3, -0.1, 2, 400000])
445 >>> psf1d = MoffatGauss(p)
446 >>> w = psf1d.fit_psf(data1d, data_errors=data1d_err, bgd_model_func=None)
447 >>> w.plot_fit()
449 .. doctest::
450 :hide:
452 >>> assert w.model is not None
453 >>> residuals = (w.data-w.model)/w.err
454 >>> assert w.costs[-1] / w.pixels.size < 1.2
455 >>> assert np.abs(np.mean(residuals)) < 0.2
456 >>> assert np.std(residuals) < 1.2
457 >>> assert np.all(np.isclose(w.p[2], p0[2], atol=1e-1))
459 .. plot::
461 import numpy as np
462 import matplotlib.pyplot as plt
463 from spectractor.extractor.psf import *
464 p = np.array([200000, 20, 30, 5, 2, -0.1, 2, 400000])
465 psf = MoffatGauss(p)
466 yy, xx = np.mgrid[:50, :60]
467 data = psf.evaluate(np.array([xx, yy]), p)
468 data = np.random.poisson(data)
469 data_errors = np.sqrt(data+1)
470 data = np.random.poisson(data)
471 data_errors = np.sqrt(data+1)
472 psf = MoffatGauss(p)
473 w = psf.fit_psf(data, data_errors=data_errors, bgd_model_func=None)
474 w.plot_fit()
476 """
477 w = PSFFitWorkspace(self, data, data_errors, bgd_model_func=bgd_model_func,
478 verbose=False, live_fit=False)
479 run_minimisation(w, method="newton", ftol=1 / w.pixels.size, xtol=1e-6, niter=50, fix=w.fixed)
480 self.p = np.copy(w.p)
481 return w
484class Moffat(PSF):
486 def __init__(self, p=None, clip=False):
487 PSF.__init__(self, clip=clip)
488 self.p_default = np.array([1, 0, 0, 3, 2, 1]).astype(float)
489 if p is not None:
490 self.p = np.asarray(p).astype(float)
491 else:
492 self.p = np.copy(self.p_default)
493 self.param_names = ["amplitude", "x_c", "y_c", "gamma", "alpha", "saturation"]
494 self.axis_names = ["$A$", r"$x_c$", r"$y_c$", r"$\gamma$", r"$\alpha$", "saturation"]
495 self.bounds = np.array([(0, np.inf), (-np.inf, np.inf), (-np.inf, np.inf), (0.1, np.inf),
496 (1.1, 100), (0, np.inf)])
498 def apply_max_width_to_bounds(self, max_half_width=None):
499 if max_half_width is not None:
500 self.max_half_width = max_half_width
501 self.bounds = np.array([(0, np.inf), (-np.inf, np.inf), (0, 2 * self.max_half_width),
502 (0.1, self.max_half_width), (1.1, 100), (0, np.inf)])
504 def evaluate(self, pixels, p=None):
505 r"""Evaluate the Moffat function.
507 The function is normalized to have an integral equal to amplitude parameter, with normalisation factor:
509 .. math::
511 f(y) \propto \frac{A \Gamma(alpha)}{\gamma \sqrt{\pi} \Gamma(alpha -1/2)},
512 \quad \int_{y_{\text{min}}}^{y_{\text{max}}} f(y) \mathrm{d}y = A
514 Parameters
515 ----------
516 pixels: list
517 List containing the X abscisse 2D array and the Y abscisse 2D array.
518 p: array_like
519 The parameter array. If None, the array used to instanciate the class is taken.
520 If given, the class instance parameter array is updated.
522 Returns
523 -------
524 output: array_like
525 The PSF function evaluated.
527 Examples
528 --------
529 >>> p = [2,20,30,4,2,10]
530 >>> psf = Moffat(p, clip=True)
531 >>> yy, xx = np.mgrid[:50, :60]
532 >>> out = psf.evaluate(pixels=np.array([xx, yy]))
534 .. plot::
536 import matplotlib.pyplot as plt
537 import numpy as np
538 from spectractor.extractor.psf import Moffat
539 p = [2,20,30,4,2,10]
540 psf = Moffat(p)
541 yy, xx = np.mgrid[:50, :60]
542 out = psf.evaluate(pixels=np.array([xx, yy]))
543 fig = plt.figure(figsize=(5,5))
544 plt.imshow(out, origin="lower")
545 plt.xlabel("X [pixels]")
546 plt.ylabel("Y [pixels]")
547 plt.show()
548 if parameters.PdfPages:
549 parameters.PdfPages.savefig()
551 """
552 if p is not None:
553 self.p = np.asarray(p).astype(float)
554 amplitude, x_c, y_c, gamma, alpha, saturation = self.p
555 if pixels.ndim == 3 and pixels.shape[0] == 2:
556 x, y = pixels # .astype(np.float32) # float32 to increase rapidity
557 out = evaluate_moffat2d(x, y, amplitude, x_c, y_c, gamma, alpha)
558 if self.clip:
559 out = np.clip(out, 0, saturation)
560 return out
561 elif pixels.ndim == 1:
562 y = np.array(pixels)
563 norm = gamma * np.sqrt(np.pi) * special.gamma(alpha - 0.5) / special.gamma(alpha)
564 out = evaluate_moffat1d_unnormalized(y, amplitude, y_c, gamma, alpha) / norm
565 if self.clip:
566 out = np.clip(out, 0, saturation)
567 return out
568 else: # pragma: no cover
569 raise ValueError(f"Pixels array must have dimension 1 or shape=(2,Nx,Ny). Here pixels.ndim={pixels.shape}.")
572class MoffatGauss(PSF):
574 def __init__(self, p=None, clip=False):
575 PSF.__init__(self, clip=clip)
576 self.p_default = np.array([1, 0, 0, 3, 2, 0, 1, 1]).astype(float)
577 if p is not None:
578 self.p = np.asarray(p).astype(float)
579 else:
580 self.p = np.copy(self.p_default)
581 self.param_names = ["amplitude", "x_c", "y_c", "gamma", "alpha", "eta_gauss", "stddev",
582 "saturation"]
583 self.axis_names = ["$A$", r"$x_c$", r"$y_c$", r"$\gamma$", r"$\alpha$", r"$\eta$", r"$\sigma$", "saturation"]
584 self.bounds = np.array([(0, np.inf), (-np.inf, np.inf), (-np.inf, np.inf), (0.1, np.inf), (1.1, 100),
585 (-1, 0), (0.1, np.inf), (0, np.inf)])
587 def apply_max_width_to_bounds(self, max_half_width=None):
588 if max_half_width is not None:
589 self.max_half_width = max_half_width
590 self.bounds = np.array([(0, np.inf), (-np.inf, np.inf), (0, 2 * self.max_half_width),
591 (0.1, self.max_half_width), (1.1, 100), (-1, 0), (0.1, self.max_half_width),
592 (0, np.inf)])
594 def evaluate(self, pixels, p=None):
595 r"""Evaluate the MoffatGauss function.
597 The function is normalized to have an integral equal to amplitude parameter, with normalisation factor:
599 .. math::
601 f(y) \propto \frac{A}{ \frac{\Gamma(alpha)}{\gamma \sqrt{\pi} \Gamma(alpha -1/2)}+\eta\sqrt{2\pi}\sigma},
602 \quad \int_{y_{\text{min}}}^{y_{\text{max}}} f(y) \mathrm{d}y = A
604 Parameters
605 ----------
606 pixels: list
607 List containing the X abscisse 2D array and the Y abscisse 2D array.
608 p: array_like
609 The parameter array. If None, the array used to instanciate the class is taken.
610 If given, the class instance parameter array is updated.
612 Returns
613 -------
614 output: array_like
615 The PSF function evaluated.
617 Examples
618 --------
619 >>> p = [2,20,30,4,2,-0.5,1,10]
620 >>> psf = MoffatGauss(p)
621 >>> yy, xx = np.mgrid[:50, :60]
622 >>> out = psf.evaluate(pixels=np.array([xx, yy]))
624 .. plot::
626 import matplotlib.pyplot as plt
627 import numpy as np
628 from spectractor.extractor.psf import MoffatGauss
629 p = [2,20,30,4,2,-0.5,1,10]
630 psf = MoffatGauss(p)
631 yy, xx = np.mgrid[:50, :60]
632 out = psf.evaluate(pixels=np.array([xx, yy]))
633 fig = plt.figure(figsize=(5,5))
634 plt.imshow(out, origin="lower")
635 plt.xlabel("X [pixels]")
636 plt.ylabel("Y [pixels]")
637 plt.show()
639 """
640 if p is not None:
641 self.p = np.asarray(p).astype(float)
642 amplitude, x_c, y_c, gamma, alpha, eta_gauss, stddev, saturation = self.p
643 if pixels.ndim == 3 and pixels.shape[0] == 2:
644 x, y = pixels # .astype(np.float32) # float32 to increase rapidity
645 out = evaluate_moffatgauss2d(x, y, amplitude, x_c, y_c, gamma, alpha, eta_gauss, stddev)
646 if self.clip:
647 out = np.clip(out, 0, saturation)
648 return out
649 elif pixels.ndim == 1:
650 y = np.array(pixels)
651 norm = gamma * np.sqrt(np.pi) * special.gamma(alpha - 0.5) / special.gamma(alpha) + eta_gauss * np.sqrt(
652 2 * np.pi) * stddev
653 out = evaluate_moffatgauss1d_unnormalized(y, amplitude, y_c, gamma, alpha, eta_gauss, stddev) / norm
654 if self.clip:
655 out = np.clip(out, 0, saturation)
656 return out
657 else: # pragma: no cover
658 raise ValueError(f"Pixels array must have dimension 1 or shape=(2,Nx,Ny). Here pixels.ndim={pixels.shape}.")
661class Order0(PSF):
663 def __init__(self, target, p=None, clip=False):
664 PSF.__init__(self, clip=clip)
665 self.p_default = np.array([1, 0, 0, 1, 1]).astype(float)
666 if p is not None:
667 self.p = np.asarray(p).astype(float)
668 else:
669 self.p = np.copy(self.p_default)
670 self.param_names = ["amplitude", "x_c", "y_c", "gamma", "saturation"]
671 self.axis_names = ["$A$", r"$x_c$", r"$y_c$", r"$\gamma$", "saturation"]
672 self.bounds = np.array([(0, np.inf), (-np.inf, np.inf), (-np.inf, np.inf), (0.5, 5), (0, np.inf)])
673 self.psf_func = self.build_interpolated_functions(target=target)
675 def build_interpolated_functions(self, target):
676 """Interpolate the order 0 image and make 1D and 2D functions centered on its centroid, with varying width
677 and normalized to get an integral equal to unity.
679 Parameters
680 ----------
681 target: Target
682 The target with a target.image attribute to interpolate.
684 Returns
685 -------
686 func: Callable
687 The 2D interpolated function centered in (target.image_x0, target.image_y0).
688 """
689 xx = np.arange(0, target.image.shape[1]) - target.image_x0
690 yy = np.arange(0, target.image.shape[0]) - target.image_y0
691 data = target.image / np.sum(target.image)
692 tmp_func = interp2d(xx, yy, data, bounds_error=False, fill_value=None)
694 def func(x, y, amplitude, x_c, y_c, gamma):
695 return amplitude * tmp_func((x - x_c)/gamma, (y - y_c)/gamma)
697 return func
699 def apply_max_width_to_bounds(self, max_half_width=None):
700 if max_half_width is not None:
701 self.max_half_width = max_half_width
702 self.bounds = np.array([(0, np.inf), (-np.inf, np.inf), (0, 2 * self.max_half_width), (0.5, 5), (0, np.inf)])
704 def evaluate(self, pixels, p=None):
705 r"""Evaluate the Order 0 interpolated function.
707 The function is normalized to have an integral equal to amplitude parameter.
709 Parameters
710 ----------
711 pixels: list
712 List containing the X abscisse 2D array and the Y abscisse 2D array.
713 p: array_like
714 The parameter array. If None, the array used to instanciate the class is taken.
715 If given, the class instance parameter array is updated.
717 Returns
718 -------
719 output: array_like
720 The PSF function evaluated.
722 Examples
723 --------
724 >>> from spectractor.extractor.images import Image, find_target
725 >>> im = Image('tests/data/reduc_20170605_028.fits', target_label="PNG321.0+3.9")
726 >>> im.plot_image()
727 >>> guess = [820, 580]
728 >>> parameters.VERBOSE = True
729 >>> parameters.DEBUG = True
730 >>> x0, y0 = find_target(im, guess)
732 >>> p = [1,40,50,1,1e20]
733 >>> psf = Order0(target=im.target, p=p)
735 2D evaluation:
737 >>> yy, xx = np.mgrid[:80, :100]
738 >>> out = psf.evaluate(pixels=np.array([xx, yy]))
740 1D evaluation:
742 >>> out = psf.evaluate(pixels=np.arange(100))
744 .. plot::
746 import matplotlib.pyplot as plt
747 import numpy as np
748 from spectractor.extractor.psf import Moffat, Order0
749 from spectractor.extractor.images import Image, find_target
750 im = Image('tests/data/reduc_20170605_028.fits', target_label="PNG321.0+3.9")
751 im.plot_image()
752 guess = [820, 580]
753 parameters.VERBOSE = True
754 parameters.DEBUG = True
755 x0, y0 = find_target(im, guess)
756 p = [1,40,50,1,1e20]
757 psf = Order0(target=im.target, p=p)
758 yy, xx = np.mgrid[:80, :100]
759 out = psf.evaluate(pixels=np.array([xx, yy]))
760 fig = plt.figure(figsize=(5,5))
761 plt.imshow(out, origin="lower")
762 plt.xlabel("X [pixels]")
763 plt.ylabel("Y [pixels]")
764 plt.grid()
765 plt.show()
767 """
768 if p is not None:
769 self.p = np.asarray(p).astype(float)
770 amplitude, x_c, y_c, gamma, saturation = self.p
771 if pixels.ndim == 3 and pixels.shape[0] == 2:
772 x, y = pixels # .astype(np.float32) # float32 to increase rapidity
773 out = self.psf_func(x[0], y[:, 0], amplitude, x_c, y_c, gamma)
774 if self.clip:
775 out = np.clip(out, 0, saturation)
776 return out
777 elif pixels.ndim == 1:
778 y = np.array(pixels)
779 out = self.psf_func(x_c, y, amplitude, x_c, y_c, gamma).T[0]
780 out *= amplitude / np.sum(out)
781 if self.clip:
782 out = np.clip(out, 0, saturation)
783 return out
784 else: # pragma: no cover
785 raise ValueError(f"Pixels array must have dimension 1 or shape=(2,Nx,Ny). Here pixels.ndim={pixels.shape}.")
788class PSFFitWorkspace(FitWorkspace):
789 """Generic PSF fitting workspace.
791 """
793 def __init__(self, psf, data, data_errors, bgd_model_func=None, file_name="",
794 nwalkers=18, nsteps=1000, burnin=100, nbins=10,
795 verbose=0, plot=False, live_fit=False, truth=None):
796 """
798 Parameters
799 ----------
800 psf
801 data: array_like
802 The data array (background subtracted) of dimension 1 or 2.
803 data_errors
804 bgd_model_func
805 file_name
806 nwalkers
807 nsteps
808 burnin
809 nbins
810 verbose
811 plot
812 live_fit
813 truth
815 Examples
816 --------
818 Build a mock spectrogram with random Poisson noise:
820 >>> p = np.array([100, 50, 50, 3, 2, -0.1, 2, 200])
821 >>> psf = MoffatGauss(p)
822 >>> data = psf.evaluate(p)
823 >>> data_errors = np.sqrt(data+1)
825 Fit the data:
827 >>> w = PSFFitWorkspace(psf, data, data_errors, bgd_model_func=None, verbose=True)
829 """
830 FitWorkspace.__init__(self, file_name, nwalkers, nsteps, burnin, nbins, verbose=verbose, plot=plot,
831 live_fit=live_fit, truth=truth)
832 self.my_logger = set_logger(self.__class__.__name__)
833 if data.shape != data_errors.shape:
834 raise ValueError(f"Data and uncertainty arrays must have the same shapes. "
835 f"Here data.shape={data.shape} and data_errors.shape={data_errors.shape}.")
836 self.psf = psf
837 self.data = data
838 self.err = data_errors
839 self.bgd_model_func = bgd_model_func
840 self.p = np.copy(self.psf.p) # [1:])
841 self.guess = np.copy(self.psf.p)
842 self.saturation = self.psf.p[-1]
843 self.fixed = [False] * len(self.p)
844 self.fixed[-1] = True # fix saturation parameter
845 self.input_labels = list(np.copy(self.psf.param_names)) # [1:]))
846 self.axis_names = list(np.copy(self.psf.axis_names)) # [1:]))
847 self.bounds = self.psf.bounds # [1:]
848 self.nwalkers = max(2 * self.ndim, nwalkers)
850 # prepare the fit
851 if data.ndim == 2:
852 self.Ny, self.Nx = self.data.shape
853 self.psf.apply_max_width_to_bounds(self.Ny)
854 yy, xx = np.mgrid[:self.Ny, :self.Nx]
855 self.pixels = np.asarray([xx, yy])
856 # flat data for fitworkspace
857 self.data = self.data.flatten()
858 self.err = self.err.flatten()
859 elif data.ndim == 1:
860 self.Ny = self.data.size
861 self.Nx = 1
862 self.psf.apply_max_width_to_bounds(self.Ny)
863 self.pixels = np.arange(self.Ny)
864 self.fixed[1] = True
865 else:
866 raise ValueError(f"Data array must have dimension 1 or 2. Here pixels.ndim={data.ndim}.")
868 # update bounds
869 self.bounds = self.psf.bounds # [1:]
870 total_flux = np.sum(data)
871 self.bounds[0] = (0.1 * total_flux, 2 * total_flux)
873 # error matrix
874 # here image uncertainties are assumed to be uncorrelated
875 # (which is not exactly true in rotated images)
876 self.W = 1. / (self.err * self.err)
878 def simulate(self, *psf_params):
879 """
880 Compute a PSF model given PSF parameters and minimizing
881 amplitude parameter given a data array.
883 Parameters
884 ----------
885 psf_params: array_like
886 PSF shape parameter array (all parameters except amplitude).
888 Examples
889 --------
891 Build a mock PSF2D without background and with random Poisson noise:
893 >>> p = np.array([200000, 20, 30, 5, 2, -0.1, 2, 400000])
894 >>> psf = MoffatGauss(p)
895 >>> yy, xx = np.mgrid[:50, :60]
896 >>> data = psf.evaluate(np.array([xx, yy]), p)
897 >>> data = np.random.poisson(data)
898 >>> data_errors = np.sqrt(data+1)
900 Fit the data in 2D:
902 >>> w = PSFFitWorkspace(psf, data, data_errors, bgd_model_func=None, verbose=True)
903 >>> x, mod, mod_err = w.simulate(*p)
904 >>> w.plot_fit()
906 .. doctest::
907 :hide:
909 >>> assert mod is not None
910 >>> assert np.mean(np.abs(mod.reshape(data.shape)-data)/data_errors) < 1
912 Fit the data in 1D:
914 >>> data1d = data[:,int(p[1])]
915 >>> data1d_err = data_errors[:,int(p[1])]
916 >>> psf.p[0] = p[0] / 10.5
917 >>> w = PSFFitWorkspace(psf, data1d, data1d_err, bgd_model_func=None, verbose=True)
918 >>> x, mod, mod_err = w.simulate(*psf.p)
919 >>> w.plot_fit()
921 .. doctest::
922 :hide:
924 >>> assert mod is not None
925 >>> assert np.mean(np.abs(mod-data1d)/data1d_err) < 1
927 .. plot::
929 import numpy as np
930 import matplotlib.pyplot as plt
931 from spectractor.extractor.psf import *
932 p = np.array([2000, 20, 30, 5, 2, -0.1, 2, 400])
933 psf = MoffatGauss(p)
934 yy, xx = np.mgrid[:50, :60]
935 data = psf.evaluate(np.array([xx, yy]), p)
936 data = np.random.poisson(data)
937 data_errors = np.sqrt(data+1)
938 data = np.random.poisson(data)
939 data_errors = np.sqrt(data+1)
940 w = PSFFitWorkspace(psf, data, data_errors, bgd_model_func=bgd_model_func, verbose=True)
941 x, mod, mod_err = w.simulate(*p[:-1])
942 w.plot_fit()
944 """
945 # Initialization of the regression
946 self.p = np.copy(psf_params)
947 # if not self.fixed_amplitude:
948 # # Matrix filling
949 # M = self.psf.evaluate(self.pixels, p=np.array([1] + list(self.p))).flatten()
950 # M_dot_W_dot_M = M.T @ self.W @ M
951 # # Regression
952 # amplitude = M.T @ (self.W * self.data) / M_dot_W_dot_M
953 # self.p[0] = amplitude
954 # Save results
955 self.model = self.psf.evaluate(self.pixels, p=self.p).flatten()
956 self.model_err = np.zeros_like(self.model)
957 return self.pixels, self.model, self.model_err
959 def plot_fit(self):
960 if self.Nx == 1:
961 fig, ax = plt.subplots(2, 1, figsize=(6, 6), sharex='all', gridspec_kw={'height_ratios': [5, 1]})
962 data = np.copy(self.data)
963 if self.bgd_model_func is not None:
964 data = data + self.bgd_model_func(self.pixels)
965 ax[0].errorbar(self.pixels, data, yerr=self.err, fmt='ro', label="Data")
966 if len(self.outliers) > 0:
967 ax[0].errorbar(self.outliers, data[self.outliers], yerr=self.err[self.outliers], fmt='go',
968 label=rf"Outliers ({self.sigma_clip}$\sigma$)")
969 if self.bgd_model_func is not None:
970 ax[0].plot(self.pixels, self.bgd_model_func(self.pixels), 'b--', label="fitted bgd")
971 if self.guess is not None:
972 if self.bgd_model_func is not None:
973 ax[0].plot(self.pixels, self.psf.evaluate(self.pixels, p=self.guess)
974 + self.bgd_model_func(self.pixels), 'k--', label="Guess")
975 else:
976 ax[0].plot(self.pixels, self.psf.evaluate(self.pixels, p=self.guess),
977 'k--', label="Guess")
978 self.psf.p = np.copy(self.p)
979 model = np.copy(self.model)
980 # if self.bgd_model_func is not None:
981 # model = self.model + self.bgd_model_func(self.pixels)
982 ax[0].plot(self.pixels, model, 'b-', label="Model")
983 ylim = list(ax[0].get_ylim())
984 ylim[1] = 1.2 * np.max(self.model)
985 ax[0].set_ylim(ylim)
986 ax[0].set_ylabel('Transverse profile')
987 ax[0].legend(loc=2, numpoints=1)
988 ax[0].grid(True)
989 txt = ""
990 for ip, p in enumerate(self.input_labels):
991 txt += f'{p}: {self.p[ip]:.4g}\n'
992 ax[0].text(0.95, 0.95, txt, horizontalalignment='right', verticalalignment='top', transform=ax[0].transAxes)
993 # residuals
994 residuals = (data - model) / self.err
995 residuals_err = np.ones_like(self.err)
996 ax[1].errorbar(self.pixels, residuals, yerr=residuals_err, fmt='ro')
997 if len(self.outliers) > 0:
998 residuals_outliers = (data[self.outliers] - model[self.outliers]) / self.err[self.outliers]
999 residuals_outliers_err = np.ones_like(residuals_outliers)
1000 ax[1].errorbar(self.outliers, residuals_outliers, yerr=residuals_outliers_err, fmt='go')
1001 ax[1].axhline(0, color='b')
1002 ax[1].grid(True)
1003 std = np.std(residuals)
1004 ax[1].set_ylim([-3. * std, 3. * std])
1005 ax[1].set_xlabel(ax[0].get_xlabel())
1006 ax[1].set_ylabel('(data-fit)/err')
1007 ax[0].set_xticks(ax[1].get_xticks()[1:-1])
1008 ax[0].get_yaxis().set_label_coords(-0.1, 0.5)
1009 ax[1].get_yaxis().set_label_coords(-0.1, 0.5)
1010 # fig.tight_layout()
1011 # fig.subplots_adjust(wspace=0, hspace=0)
1012 else:
1013 data = np.copy(self.data).reshape((self.Ny, self.Nx))
1014 model = np.copy(self.model).reshape((self.Ny, self.Nx))
1015 err = np.copy(self.err).reshape((self.Ny, self.Nx))
1016 gs_kw = dict(width_ratios=[3, 0.15], height_ratios=[1, 1, 1, 1])
1017 fig, ax = plt.subplots(nrows=4, ncols=2, figsize=(5, 7), gridspec_kw=gs_kw)
1018 norm = np.nanmax(self.data)
1019 plot_image_simple(ax[0, 0], data=model / norm, aspect='auto', cax=ax[0, 1], vmin=0, vmax=1,
1020 units='1/max(data)')
1021 ax[0, 0].set_title("Model", fontsize=10, loc='center', color='white', y=0.8)
1022 plot_image_simple(ax[1, 0], data=data / norm, title='Data', aspect='auto',
1023 cax=ax[1, 1], vmin=0, vmax=1, units='1/max(data)')
1024 ax[1, 0].set_title('Data', fontsize=10, loc='center', color='white', y=0.8)
1025 residuals = (data - model)
1026 # residuals_err = self.spectrum.spectrogram_err / self.model
1027 norm = err
1028 residuals /= norm
1029 std = float(np.std(residuals))
1030 plot_image_simple(ax[2, 0], data=residuals, vmin=-5 * std, vmax=5 * std, title='(Data-Model)/Err',
1031 aspect='auto', cax=ax[2, 1], units='', cmap="bwr")
1032 ax[2, 0].set_title('(Data-Model)/Err', fontsize=10, loc='center', color='black', y=0.8)
1033 ax[2, 0].text(0.05, 0.05, f'mean={np.mean(residuals):.3f}\nstd={np.std(residuals):.3f}',
1034 horizontalalignment='left', verticalalignment='bottom',
1035 color='black', transform=ax[2, 0].transAxes)
1036 ax[0, 0].set_xticks(ax[2, 0].get_xticks()[1:-1])
1037 ax[0, 1].get_yaxis().set_label_coords(3.5, 0.5)
1038 ax[1, 1].get_yaxis().set_label_coords(3.5, 0.5)
1039 ax[2, 1].get_yaxis().set_label_coords(3.5, 0.5)
1040 ax[3, 1].remove()
1041 ax[3, 0].plot(np.arange(self.Nx), data.sum(axis=0), label='Data')
1042 ax[3, 0].plot(np.arange(self.Nx), model.sum(axis=0), label='Model')
1043 ax[3, 0].set_ylabel('Transverse sum')
1044 ax[3, 0].set_xlabel(r'X [pixels]')
1045 ax[3, 0].legend(fontsize=7)
1046 ax[3, 0].grid(True)
1047 if self.live_fit: # pragma: no cover
1048 plt.draw()
1049 plt.pause(1e-8)
1050 plt.close()
1051 else:
1052 if parameters.DISPLAY:
1053 plt.show()
1054 else:
1055 plt.close(fig)
1056 if parameters.SAVE: # pragma: no cover
1057 figname = os.path.splitext(self.filename)[0] + "_bestfit.pdf"
1058 self.my_logger.info(f"\n\tSave figure {figname}.")
1059 fig.savefig(figname, dpi=100, bbox_inches='tight')
1060 if parameters.PdfPages:
1061 parameters.PdfPages.savefig()
1064def load_PSF(psf_type=parameters.PSF_TYPE, target=None, clip=False):
1065 """Load the PSF model with a keyword.
1067 Parameters
1068 ----------
1069 psf_type: str
1070 PSF model keyword (default: parameters.PSF_TYPE).
1071 target: Target, optional
1072 The Target instance to make Order0 PSF model (default: None).
1073 clip: bool, optional
1074 If True, PSF evaluation is clipped between 0 and saturation level (slower) (default: False)
1076 Returns
1077 -------
1078 psf: PSF
1079 An instance of the selected PSF model.
1081 Examples
1082 --------
1084 >>> load_PSF(psf_type="Moffat", clip=True) # doctest: +ELLIPSIS
1085 <....Moffat object at ...>
1086 >>> load_PSF(psf_type="MoffatGauss", clip=False) # doctest: +ELLIPSIS
1087 <....MoffatGauss object at ...>
1089 """
1090 if psf_type == "Moffat":
1091 psf = Moffat(clip=clip)
1092 elif psf_type == "MoffatGauss":
1093 psf = MoffatGauss(clip=clip)
1094 elif psf_type == "Order0":
1095 if target is None:
1096 raise ValueError(f"A Target instance must be given when PSF_TYPE='Order0'. I got target={target}.")
1097 psf = Order0(target=target, clip=clip)
1098 else:
1099 raise ValueError(f"Unknown PSF_TYPE={psf_type}. Must be either Moffat or MoffatGauss.")
1100 return psf
1103if __name__ == "__main__": 1103 ↛ 1104line 1103 didn't jump to line 1104, because the condition on line 1103 was never true
1104 import doctest
1106 doctest.testmod()