Coverage for spectractor/tools.py: 12%
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
3from scipy.optimize import curve_fit
4import numpy as np
5from astropy.modeling import models, fitting
6from astropy.stats import sigma_clip
7from astropy.io import fits
8from astropy import wcs as WCS
10import matplotlib.pyplot as plt
11import matplotlib.colors
12from matplotlib.ticker import MaxNLocator
14import warnings
15from scipy.signal import fftconvolve, gaussian
16from scipy.ndimage.filters import maximum_filter
17from scipy.ndimage.morphology import generate_binary_structure, binary_erosion
18from scipy.interpolate import interp1d
19from scipy.integrate import quad
21from skimage.feature import hessian_matrix
22from spectractor.config import set_logger
23from spectractor import parameters
24from math import floor
26from numba import njit
29@njit(fastmath=True, cache=True)
30def gauss(x, A, x0, sigma):
31 """Evaluate the Gaussian function.
33 Parameters
34 ----------
35 x: array_like
36 Abscisse array to evaluate the function of size Nx.
37 A: float
38 Amplitude of the Gaussian function.
39 x0: float
40 Mean of the Gaussian function.
41 sigma: float
42 Standard deviation of the Gaussian function.
44 Returns
45 -------
46 m: array_like
47 The Gaussian function evaluated on the x array.
49 Examples
50 --------
52 >>> x = np.arange(50)
53 >>> y = gauss(x, 10, 25, 3)
54 >>> print(y.shape)
55 (50,)
56 >>> y[25]
57 10.0
58 """
59 return A * np.exp(-(x - x0) * (x - x0) / (2 * sigma * sigma))
62@njit(fastmath=True, cache=True)
63def gauss_jacobian(x, A, x0, sigma):
64 """Compute the Jacobian matrix of the Gaussian function.
66 Parameters
67 ----------
68 x: array_like
69 Abscisse array to evaluate the function of size Nx.
70 A: float
71 Amplitude of the Gaussian function.
72 x0: float
73 Mean of the Gaussian function.
74 sigma: float
75 Standard deviation of the Gaussian function.
77 Returns
78 -------
79 m: array_like
80 The Jacobian matrix of size 3 x Nx.
82 Examples
83 --------
85 >>> x = np.arange(50)
86 >>> jac = gauss_jacobian(x, 10, 25, 3)
87 >>> print(np.array(jac).T.shape)
88 (50, 3)
89 """
90 dA = gauss(x, A, x0, sigma) / A
91 dx0 = A * (x - x0) / (sigma * sigma) * dA
92 dsigma = A * (x - x0) * (x - x0) / (sigma ** 3) * dA
93 # return np.array([dA, dx0, dsigma]).T
94 return dA, dx0, dsigma
97@njit(fastmath=True, cache=True)
98def line(x, a, b):
99 return a * x + b
102# noinspection PyTypeChecker
103def fit_gauss(x, y, guess=[10, 1000, 1], bounds=(-np.inf, np.inf), sigma=None):
104 """Fit a Gaussian profile to data, using curve_fit. The mean guess value of the Gaussian
105 must not be far from the truth values. Boundaries helps a lot also.
107 Parameters
108 ----------
109 x: np.array
110 The x data values.
111 y: np.array
112 The y data values.
113 guess: list, [amplitude, mean, sigma], optional
114 List of first guessed values for the Gaussian fit (default: [10, 1000, 1]).
115 bounds: list, optional
116 List of boundaries for the parameters [[minima],[maxima]] (default: (-np.inf, np.inf)).
117 sigma: np.array, optional
118 The y data uncertainties.
120 Returns
121 -------
122 popt: list
123 Best fitting parameters of curve_fit.
124 pcov: list
125 Best fitting parameters covariance matrix from curve_fit.
127 Examples
128 --------
130 >>> import numpy as np
131 >>> import matplotlib.pyplot as plt
132 >>> x = np.arange(600.,700.,2)
133 >>> p = [10, 650, 10]
134 >>> y = gauss(x, *p)
135 >>> y_err = np.ones_like(y)
136 >>> print(y[25])
137 10.0
138 >>> guess = (2,630,2)
139 >>> popt, pcov = fit_gauss(x, y, guess=guess, bounds=((1,600,1),(100,700,100)), sigma=y_err)
141 .. doctest::
142 :hide:
144 >>> assert np.all(np.isclose(p,popt))
145 """
146 def gauss_jacobian_wrapper(*params):
147 return np.array(gauss_jacobian(*params)).T
148 popt, pcov = curve_fit(gauss, x, y, p0=guess, bounds=bounds, tr_solver='exact', jac=gauss_jacobian_wrapper,
149 sigma=sigma, method='dogbox', verbose=0, xtol=1e-20, ftol=1e-20)
150 return popt, pcov
153def multigauss_and_line(x, *params):
154 """Multiple Gaussian profile plus a straight line to data.
155 The order of the parameters is line slope, line intercept,
156 and then block of 3 parameters for the Gaussian profiles like amplitude, mean and standard
157 deviation.
159 Parameters
160 ----------
161 x: array
162 The x data values.
163 *params: list of float parameters as described above.
165 Returns
166 -------
167 y: array
168 The y profile values.
170 Examples
171 --------
173 >>> x = np.arange(600.,800.,1)
174 >>> y = multigauss_and_line(x, 1, 10, 20, 650, 3, 40, 750, 10)
175 >>> print(y[0])
176 610.0
177 """
178 out = line(x, params[0], params[1])
179 for k in range((len(params) - 2) // 3):
180 out += gauss(x, *params[2 + 3 * k:2 + 3 * k + 3])
181 return out
184# noinspection PyTypeChecker
185def fit_multigauss_and_line(x, y, guess=[0, 1, 10, 1000, 1, 0], bounds=(-np.inf, np.inf)):
186 """Fit a multiple Gaussian profile plus a straight line to data, using curve_fit.
187 The mean guess value of the Gaussian must not be far from the truth values.
188 Boundaries helps a lot also. The order of the parameters is line slope, line intercept,
189 and then block of 3 parameters for the Gaussian profiles like amplitude, mean and standard
190 deviation.
192 Parameters
193 ----------
194 x: array
195 The x data values.
196 y: array
197 The y data values.
198 guess: list, [slope, intercept, amplitude, mean, sigma]
199 List of first guessed values for the Gaussian fit (default: [0, 1, 10, 1000, 1]).
200 bounds: 2D-list
201 List of boundaries for the parameters [[minima],[maxima]] (default: (-np.inf, np.inf)).
203 Returns
204 -------
205 popt: list
206 Best fitting parameters of curve_fit.
207 pcov: 2D-list
208 Best fitting parameters covariance matrix from curve_fit.
210 Examples
211 --------
213 >>> x = np.arange(600.,800.,1)
214 >>> y = multigauss_and_line(x, 1, 10, 20, 650, 3, 40, 750, 10)
215 >>> print(y[0])
216 610.0
217 >>> bounds = ((-np.inf,-np.inf,1,600,1,1,600,1),(np.inf,np.inf,100,800,100,100,800,100))
218 >>> popt, pcov = fit_multigauss_and_line(x, y, guess=(0,1,3,630,3,3,770,3), bounds=bounds)
219 >>> print(popt)
220 [ 1. 10. 20. 650. 3. 40. 750. 10.]
221 """
222 maxfev = 1000
223 popt, pcov = curve_fit(multigauss_and_line, x, y, p0=guess, bounds=bounds, maxfev=maxfev, absolute_sigma=True)
224 return popt, pcov
227def rescale_x_for_legendre(x):
228 middle = 0.5 * (np.max(x) + np.min(x))
229 x_norm = x - middle
230 if np.max(x_norm) != 0:
231 return x_norm / np.max(x_norm)
232 else:
233 return x_norm
236# noinspection PyTypeChecker
237def multigauss_and_bgd(x, *params):
238 """Multiple Gaussian profile plus a polynomial background to data.
239 Polynomial function is based on the orthogonal Legendre polynomial basis.
240 The degree of the polynomial background is fixed by parameters.CALIB_BGD_NPARAMS.
241 The order of the parameters is a first block CALIB_BGD_NPARAMS parameters (from low to high Legendre polynome degree,
242 contrary to np.polyval), and then block of 3 parameters for the Gaussian profiles like amplitude, mean and standard
243 deviation.
245 Parameters
246 ----------
247 x: array
248 The x data values.
249 *params: list of float parameters as described above.
251 Returns
252 -------
253 y: array
254 The y profile values.
256 Examples
257 --------
258 >>> parameters.CALIB_BGD_NPARAMS = 4
259 >>> x = np.arange(600., 800., 1)
260 >>> p = [20, 1, -1, -1, 20, 650, 3, 40, 750, 5]
261 >>> y = multigauss_and_bgd(x, *p)
262 >>> print(f'{y[0]:.2f}')
263 19.00
265 .. plot::
267 from spectractor import parameters
268 from spectractor.tools import multigauss_and_bgd
269 import numpy as np
270 parameters.CALIB_BGD_NPARAMS = 4
271 x = np.arange(600., 800., 1)
272 p = [20, 1, -1, -1, 20, 650, 3, 40, 750, 5]
273 y = multigauss_and_bgd(x, *p)
274 plt.plot(x,y,'r-')
275 plt.show()
277 """
278 bgd_nparams = parameters.CALIB_BGD_NPARAMS
279 # out = np.polyval(params[0:bgd_nparams], x)
280 x_norm = rescale_x_for_legendre(x)
281 out = np.polynomial.legendre.legval(x_norm, params[0:bgd_nparams])
282 for k in range((len(params) - bgd_nparams) // 3):
283 out += gauss(x, *params[bgd_nparams + 3 * k:bgd_nparams + 3 * k + 3])
284 return out
287# noinspection PyTypeChecker
288def multigauss_and_bgd_jacobian(x, *params):
289 """Jacobien of the multiple Gaussian profile plus a polynomial background to data.
290 The degree of the polynomial background is fixed by parameters.CALIB_BGD_NPARAMS.
291 The order of the parameters is a first block CALIB_BGD_NPARAMS parameters (from low to high Legendre polynome degree,
292 contrary to np.polyval), and then block of 3 parameters for the Gaussian profiles like amplitude, mean and standard
293 deviation. x values are renormalised on the [-1, 1] interval for the background.
295 Parameters
296 ----------
297 x: array
298 The x data values.
299 *params: list of float parameters as described above.
301 Returns
302 -------
303 y: array
304 The jacobian values.
306 Examples
307 --------
309 >>> import spectractor.parameters as parameters
310 >>> parameters.CALIB_BGD_NPARAMS = 4
311 >>> x = np.arange(600.,800.,1)
312 >>> p = [20, 1, -1, -1, 20, 650, 3, 40, 750, 5]
313 >>> y = multigauss_and_bgd_jacobian(x, *p)
314 >>> assert(np.all(np.isclose(y.T[0],np.ones_like(x))))
315 >>> print(y.shape)
316 (200, 10)
317 """
318 bgd_nparams = parameters.CALIB_BGD_NPARAMS
319 out = []
320 x_norm = rescale_x_for_legendre(x)
321 for k in range(bgd_nparams):
322 # out.append(params[k]*(parameters.CALIB_BGD_ORDER-k)*x**(parameters.CALIB_BGD_ORDER-(k+1)))
323 # out.append(x ** (bgd_nparams - 1 - k))
324 c = np.zeros(bgd_nparams)
325 c[k] = 1
326 out.append(np.polynomial.legendre.legval(x_norm, c))
327 for k in range((len(params) - bgd_nparams) // 3):
328 jac = np.array(gauss_jacobian(x, *params[bgd_nparams + 3 * k:bgd_nparams + 3 * k + 3]))
329 for j in jac:
330 out.append(list(j))
331 return np.array(out).T
334# noinspection PyTypeChecker
335def fit_multigauss_and_bgd(x, y, guess=[0, 1, 10, 1000, 1, 0], bounds=(-np.inf, np.inf), sigma=None,
336 fix_centroids=False):
337 """Fit a multiple Gaussian profile plus a polynomial background to data, using iminuit.
338 The mean guess value of the Gaussian must not be far from the truth values.
339 Boundaries helps a lot also. The degree of the polynomial background is fixed by parameters.CALIB_BGD_NPARAMS.
340 The order of the parameters is a first block CALIB_BGD_NPARAMS parameters (from high to low monomial terms,
341 same as np.polyval), and then block of 3 parameters for the Gaussian profiles like amplitude, mean and standard
342 deviation. x values are renormalised on the [-1, 1] interval for the background.
344 Parameters
345 ----------
346 x: array
347 The x data values.
348 y: array
349 The y data values.
350 guess: list, [CALIB_BGD_ORDER+1 parameters, 3*number of Gaussian parameters]
351 List of first guessed values for the Gaussian fit (default: [0, 1, 10, 1000, 1]).
352 bounds: array
353 List of boundaries for the parameters [[minima],[maxima]] (default: (-np.inf, np.inf)).
354 sigma: array, optional
355 The uncertainties on the y values (default: None).
357 Returns
358 -------
359 popt: array
360 Best fitting parameters of curve_fit.
361 pcov: array
362 Best fitting parameters covariance matrix from curve_fit.
364 Examples
365 --------
367 >>> x = np.arange(600.,800.,1)
368 >>> p = [20, 1, -1, -1, 20, 650, 3, 40, 750, 5]
369 >>> y = multigauss_and_bgd(x, *p)
370 >>> print(f'{y[0]:.2f}')
371 19.00
372 >>> err = 0.1 * np.sqrt(y)
373 >>> guess = (15,0,0,0,10,640,2,20,750,7)
374 >>> bounds = ((-np.inf,-np.inf,-np.inf,-np.inf,1,600,1,1,600,1),(np.inf,np.inf,np.inf,np.inf,100,800,100,100,800,100))
375 >>> popt, pcov = fit_multigauss_and_bgd(x, y, guess=guess, bounds=bounds, sigma=err)
376 >>> assert np.all(np.isclose(p,popt,rtol=1e-4))
377 >>> fit = multigauss_and_bgd(x, *popt)
379 .. plot::
381 import matplotlib.pyplot as plt
382 import numpy as np
383 from spectractor.tools import multigauss_and_bgd, fit_multigauss_and_bgd
384 x = np.arange(600.,800.,1)
385 p = [20, 1, -1, -1, 20, 650, 3, 40, 750, 5]
386 y = multigauss_and_bgd(x, *p)
387 err = 0.1 * np.sqrt(y)
388 guess = (15,0,0,0,10,640,2,20,750,7)
389 bounds = ((-np.inf,-np.inf,-np.inf,-np.inf,1,600,1,1,600,1),(np.inf,np.inf,np.inf,np.inf,100,800,100,100,800,100))
390 popt, pcov = fit_multigauss_and_bgd(x, y, guess=guess, bounds=bounds, sigma=err)
391 fit = multigauss_and_bgd(x, *popt)
392 fig = plt.figure()
393 plt.errorbar(x,y,yerr=err,linestyle='None')
394 plt.plot(x,fit,'r-')
395 plt.plot(x,multigauss_and_bgd(x, *guess),'k--')
396 plt.show()
397 """
398 maxfev = 10000
399 popt, pcov = curve_fit(multigauss_and_bgd, x, y, p0=guess, bounds=bounds, maxfev=maxfev, sigma=sigma,
400 absolute_sigma=True, method='trf', xtol=1e-4, ftol=1e-4, verbose=0,
401 jac=multigauss_and_bgd_jacobian, x_scale='jac')
402 # error = 0.1 * np.abs(guess) * np.ones_like(guess)
403 # z = np.where(np.isclose(error,0.0,1e-6))
404 # error[z] = 0.01
405 # bounds = np.array(bounds)
406 # if bounds.shape[0] == 2 and bounds.shape[1] > 2:
407 # bounds = bounds.T
408 # guess = np.array(guess)
409 #
410 # def chisq_multigauss_and_bgd(params):
411 # if sigma is None:
412 # return np.nansum((multigauss_and_bgd(x, *params) - y)**2)
413 # else:
414 # return np.nansum(((multigauss_and_bgd(x, *params) - y)/sigma)**2)
415 #
416 # def chisq_multigauss_and_bgd_jac(params):
417 # diff = multigauss_and_bgd(x, *params) - y
418 # jac = multigauss_and_bgd_jacobian(x, *params)
419 # if sigma is None:
420 # return np.array([np.nansum(2 * jac[p] * diff) for p in range(len(params))])
421 # else:
422 # return np.array([np.nansum(2 * jac[p] * diff / (sigma*sigma)) for p in range(len(params))])
423 #
424 # fix = [False] * error.size
425 # if fix_centroids:
426 # for k in range(parameters.CALIB_BGD_NPARAMS, len(fix), 3):
427 # fix[k+1] = True
428 # # noinspection PyArgumentList
429 # m = Minuit.from_array_func(fcn=chisq_multigauss_and_bgd, start=guess, error=error, errordef=1,
430 # fix=fix, print_level=0, limit=bounds, grad=chisq_multigauss_and_bgd_jac)
431 #
432 # m.tol = 0.001
433 # m.migrad()
434 # try:
435 # pcov = m.np_covariance()
436 # except:
437 # pcov = None
438 # popt = m.np_values()
439 return popt, pcov
442# noinspection PyTupleAssignmentBalance
443def fit_poly1d(x, y, order, w=None):
444 """Fit a 1D polynomial function to data. Use np.polyfit.
446 Parameters
447 ----------
448 x: array
449 The x data values.
450 y: array
451 The y data values.
452 order: int
453 The degree of the polynomial function.
454 w: array, optional
455 Weights on the y data (default: None).
457 Returns
458 -------
459 fit: array
460 The best fitting parameter values.
461 cov: 2D-array
462 The covariance matrix
463 model: array
464 The best fitting profile
466 Examples
467 --------
469 >>> x = np.arange(500., 1000., 1)
470 >>> p = [3, 2, 1, 1]
471 >>> y = np.polyval(p, x)
472 >>> err = np.ones_like(y)
473 >>> fit, cov, model = fit_poly1d(x, y, order=3)
475 .. doctest::
476 :hide:
478 >>> assert np.all(np.isclose(p, fit, 1e-5))
479 >>> assert np.all(np.isclose(model, y))
480 >>> assert cov.shape == (4, 4)
482 With uncertainties:
484 >>> fit, cov2, model2 = fit_poly1d(x, y, order=3, w=err)
486 .. doctest::
487 :hide:
489 >>> assert np.all(np.isclose(p, fit, 1e-5))
491 >>> fit, cov3, model3 = fit_poly1d([0, 1], [1, 1], order=3, w=err)
492 >>> print(fit)
493 [0 0 0 0]
494 """
495 cov = np.array([])
496 if len(x) > order:
497 if w is None:
498 fit, cov = np.polyfit(x, y, order, cov=True)
499 else:
500 fit, cov = np.polyfit(x, y, order, cov=True, w=w)
501 model = np.polyval(fit, x)
502 else:
503 fit = np.array([0] * (order + 1))
504 model = y
505 return fit, cov, model
508# noinspection PyTupleAssignmentBalance
509def fit_poly1d_legendre(x, y, order, w=None):
510 """Fit a 1D polynomial function to data using Legendre polynomial orthogonal basis.
512 Parameters
513 ----------
514 x: array
515 The x data values.
516 y: array
517 The y data values.
518 order: int
519 The degree of the polynomial function.
520 w: array, optional
521 Weights on the y data (default: None).
523 Returns
524 -------
525 fit: array
526 The best fitting parameter values.
527 cov: 2D-array
528 The covariance matrix
529 model: array
530 The best fitting profile
532 Examples
533 --------
535 >>> x = np.arange(500., 1000., 1)
536 >>> p = [-1e-6, -1e-4, 1, 1]
537 >>> y = np.polyval(p, x)
538 >>> err = np.ones_like(y)
539 >>> fit, cov, model = fit_poly1d_legendre(x,y,order=3)
540 >>> assert np.all(np.isclose(p,fit,3))
541 >>> fit, cov2, model2 = fit_poly1d_legendre(x,y,order=3,w=err)
542 >>> assert np.all(np.isclose(p,fit,3))
543 >>> fit, cov3, model3 = fit_poly1d([0, 1], [1, 1], order=3, w=err)
544 >>> print(fit)
545 [0 0 0 0]
547 .. plot::
549 import matplotlib.pyplot as plt
550 import numpy as np
551 from spectractor.tools import fit_poly1d_legendre
552 p = [-1e-6, -1e-4, 1, 1]
553 x = np.arange(500., 1000., 1)
554 y = np.polyval(p, x)
555 err = np.ones_like(y)
556 fit, cov2, model2 = fit_poly1d_legendre(x,y,order=3,w=err)
557 plt.errorbar(x,y,yerr=err,fmt='ro')
558 plt.plot(x,model2)
559 plt.show()
560 """
561 cov = -1
562 x_norm = rescale_x_for_legendre(x)
563 if len(x) > order:
564 fit, cov = np.polynomial.legendre.legfit(x_norm, y, deg=order, full=True, w=w)
565 model = np.polynomial.legendre.legval(x_norm, fit)
566 else:
567 fit = np.array([0] * (order + 1))
568 model = y
569 return fit, cov, model
572# noinspection PyTypeChecker,PyUnresolvedReferences
573def fit_poly2d(x, y, z, order):
574 """Fit a 2D polynomial function to data. Use astropy.modeling.
576 Parameters
577 ----------
578 x: array
579 The x data values.
580 y: array
581 The y data values.
582 z: array
583 The z data values.
584 order: int
585 The degree of the polynomial function.
587 Returns
588 -------
589 model: Astropy model
590 The best fitting astropy polynomial model
592 Examples
593 --------
595 >>> x, y = np.mgrid[:50,:50]
596 >>> z = x**2 + y**2 - 2*x*y
597 >>> fit = fit_poly2d(x, y, z, order=2)
599 .. doctest::
600 :hide:
602 >>> assert np.isclose(fit.c0_0.value, 0)
603 >>> assert np.isclose(fit.c1_0.value, 0)
604 >>> assert np.isclose(fit.c2_0.value, 1)
605 >>> assert np.isclose(fit.c0_1.value, 0)
606 >>> assert np.isclose(fit.c0_2.value, 1)
607 >>> assert np.isclose(fit.c1_1.value, -2)
608 """
609 p_init = models.Polynomial2D(degree=order)
610 fit_p = fitting.LevMarLSQFitter()
611 with warnings.catch_warnings():
612 # Ignore model linearity warning from the fitter
613 warnings.simplefilter('ignore')
614 p = fit_p(p_init, x, y, z)
615 return p
618def fit_poly1d_outlier_removal(x, y, order=2, sigma=3.0, niter=3):
619 """Fit a 1D polynomial function to data. Use astropy.modeling.
621 Parameters
622 ----------
623 x: array
624 The x data values.
625 y: array
626 The y data values.
627 order: int
628 The degree of the polynomial function (default: 2).
629 sigma: float
630 Value of the sigma-clipping (default: 3.0).
631 niter: int
632 The number of iterations to converge (default: 3).
634 Returns
635 -------
636 model: Astropy model
637 The best fitting astropy model.
638 outliers: array_like
639 List of the outlier points.
641 Examples
642 --------
644 >>> x = np.arange(500., 1000., 1)
645 >>> p = [3,2,1,0]
646 >>> y = np.polyval(p, x)
647 >>> y[::10] = 0.
648 >>> model, outliers = fit_poly1d_outlier_removal(x,y,order=3,sigma=3)
649 >>> print('{:.2f}'.format(model.c0.value))
650 0.00
651 >>> print('{:.2f}'.format(model.c1.value))
652 1.00
653 >>> print('{:.2f}'.format(model.c2.value))
654 2.00
655 >>> print('{:.2f}'.format(model.c3.value))
656 3.00
658 """
659 gg_init = models.Polynomial1D(order)
660 gg_init.c1 = 0
661 gg_init.c2 = 0
662 fit = fitting.LinearLSQFitter()
663 or_fit = fitting.FittingWithOutlierRemoval(fit, sigma_clip, niter=niter, sigma=sigma)
664 # get fitted model and filtered data
665 or_fitted_model, filtered_data = or_fit(gg_init, x, y)
666 outliers = [] # not working
667 """
668 import matplotlib.pyplot as plt
669 plt.figure(figsize=(8,5))
670 plt.plot(x, y, 'gx', label="original data")
671 plt.plot(x, gg_init(x), 'k.', label="guess")
672 plt.plot(x, filtered_data, 'r+', label="filtered data")
673 plt.plot(x, or_fitted_model(x), 'r--',
674 label="model fitted w/ filtered data")
675 plt.legend(loc=2, numpoints=1)
676 if parameters.DISPLAY: plt.show()
677 """
678 return or_fitted_model, outliers
681def fit_poly2d_outlier_removal(x, y, z, order=2, sigma=3.0, niter=30):
682 """Fit a 2D polynomial function to data. Use astropy.modeling.
684 Parameters
685 ----------
686 x: array
687 The x data values.
688 y: array
689 The y data values.
690 z: array
691 The z data values.
692 order: int
693 The degree of the polynomial function (default: 2).
694 sigma: float
695 Value of the sigma-clipping (default: 3.0).
696 niter: int
697 The number of iterations to converge (default: 30).
699 Returns
700 -------
701 model: Astropy model
702 The best fitting astropy model.
704 Examples
705 --------
707 >>> x, y = np.mgrid[:50,:50]
708 >>> z = x**2 + y**2 - 2*x*y
709 >>> z[::10,::10] = 0.
710 >>> fit = fit_poly2d_outlier_removal(x,y,z,order=2,sigma=3)
712 .. doctest::
713 :hide:
715 >>> assert np.isclose(fit.c0_0.value, 0)
716 >>> assert np.isclose(fit.c1_0.value, 0)
717 >>> assert np.isclose(fit.c2_0.value, 1)
718 >>> assert np.isclose(fit.c0_1.value, 0)
719 >>> assert np.isclose(fit.c0_2.value, 1)
720 >>> assert np.isclose(fit.c1_1.value, -2)
722 """
723 my_logger = set_logger(__name__)
724 gg_init = models.Polynomial2D(order)
725 fit = fitting.LinearLSQFitter()
726 or_fit = fitting.FittingWithOutlierRemoval(fit, sigma_clip, niter=niter, sigma=sigma)
727 # get fitted model and filtered data
728 or_fitted_model, filtered_data = or_fit(gg_init, x, y, z)
729 my_logger.info(f'\n\t{or_fitted_model}')
730 # my_logger.debug(f'\n\t{fit.fit_info}')
731 return or_fitted_model
734def tied_circular_gauss2d(g1):
735 std = g1.x_stddev
736 return std
739def fit_gauss2d_outlier_removal(x, y, z, sigma=3.0, niter=3, guess=None, bounds=None, circular=False):
740 """
741 Fit an astropy Gaussian 2D model with parameters : amplitude, x_mean, y_mean, x_stddev, y_stddev, theta
742 using outlier removal methods.
744 Parameters
745 ----------
746 x: np.array
747 2D array of the x coordinates from meshgrid.
748 y: np.array
749 2D array of the y coordinates from meshgrid.
750 z: np.array
751 the 2D array image.
752 sigma: float
753 value of sigma for the sigma rejection of outliers (default: 3)
754 niter: int
755 maximum number of iterations for the outlier detection (default: 3)
756 guess: list, optional
757 List containing a first guess for the PSF parameters (default: None).
758 bounds: list, optional
759 2D list containing bounds for the PSF parameters with format ((min,...), (max...)) (default: None)
760 circular: bool, optional
761 If True, force the Gaussian shape to be circular (default: False)
763 Returns
764 -------
765 fitted_model: Fittable
766 Astropy Gaussian2D model
768 Examples
769 --------
771 >>> import numpy as np
772 >>> import matplotlib.pyplot as plt
773 >>> from astropy.modeling import models
774 >>> X, Y = np.mgrid[:50,:50]
775 >>> PSF = models.Gaussian2D()
776 >>> p = (50, 25, 25, 5, 5, 0)
777 >>> Z = PSF.evaluate(X, Y, *p)
779 .. plot::
781 import numpy as np
782 import matplotlib.pyplot as plt
783 from astropy.modeling import models
784 X, Y = np.mgrid[:50,:50]
785 PSF = models.Gaussian2D()
786 p = (50, 25, 25, 5, 5, 0)
787 Z = PSF.evaluate(X, Y, *p)
788 plt.imshow(Z, origin='lower')
789 plt.show()
791 >>> guess = (45, 20, 20, 7, 7, 0)
792 >>> bounds = ((1, 10, 10, 1, 1, -90), (100, 40, 40, 10, 10, 90))
793 >>> fit = fit_gauss2d_outlier_removal(X, Y, Z, guess=guess, bounds=bounds, circular=True)
794 >>> res = [getattr(fit, p).value for p in fit.param_names]
795 >>> print(res)
796 [50.0, 25.0, 25.0, 5.0, 5.0, 0.0]
798 .. plot::
800 import numpy as np
801 import matplotlib.pyplot as plt
802 from astropy.modeling import models
803 from spectractor.tools import fit_gauss2d_outlier_removal
804 X, Y = np.mgrid[:50,:50]
805 PSF = models.Gaussian2D()
806 p = (50, 25, 25, 5, 5, 0)
807 Z = PSF.evaluate(X, Y, *p)
808 guess = (45, 20, 20, 7, 7, 0)
809 bounds = ((1, 10, 10, 1, 1, -90), (100, 40, 40, 10, 10, 90))
810 fit = fit_gauss2d_outlier_removal(X, Y, Z, guess=guess, bounds=bounds, circular=True)
811 plt.imshow(Z-fit(X, Y), origin='lower')
812 plt.show()
814 """
815 my_logger = set_logger(__name__)
816 gg_init = models.Gaussian2D()
817 if guess is not None:
818 for ip, p in enumerate(gg_init.param_names):
819 getattr(gg_init, p).value = guess[ip]
820 if bounds is not None:
821 for ip, p in enumerate(gg_init.param_names):
822 getattr(gg_init, p).min = bounds[0][ip]
823 getattr(gg_init, p).max = bounds[1][ip]
824 if circular:
825 gg_init.y_stddev.tied = tied_circular_gauss2d
826 gg_init.theta.fixed = True
827 with warnings.catch_warnings():
828 # Ignore model linearity warning from the fitter
829 warnings.simplefilter('ignore')
830 fit = fitting.LevMarLSQFitter()
831 or_fit = fitting.FittingWithOutlierRemoval(fit, sigma_clip, niter=niter, sigma=sigma)
832 # get fitted model and filtered data
833 or_fitted_model, filtered_data = or_fit(gg_init, x, y, z)
834 my_logger.info(f'\n\t{or_fitted_model}')
835 # my_logger.debug(f'\n\t{fit.fit_info}')
836 return or_fitted_model
839def fit_moffat2d_outlier_removal(x, y, z, sigma=3.0, niter=3, guess=None, bounds=None):
840 """
841 Fit an astropy Moffat 2D model with parameters: amplitude, x_mean, y_mean, gamma, alpha
842 using outlier removal methods.
844 Parameters
845 ----------
846 x: np.array
847 2D array of the x coordinates from meshgrid.
848 y: np.array
849 2D array of the y coordinates from meshgrid.
850 z: np.array
851 the 2D array image.
852 sigma: float
853 value of sigma for the sigma rejection of outliers (default: 3)
854 niter: int
855 maximum number of iterations for the outlier detection (default: 3)
856 guess: list, optional
857 List containing a first guess for the PSF parameters (default: None).
858 bounds: list, optional
859 2D list containing bounds for the PSF parameters with format ((min,...), (max...)) (default: None)
861 Returns
862 -------
863 fitted_model: Fittable
864 Astropy Moffat2D model
866 Examples
867 --------
869 >>> import numpy as np
870 >>> import matplotlib.pyplot as plt
871 >>> from astropy.modeling import models
872 >>> X, Y = np.mgrid[:100,:100]
873 >>> PSF = models.Moffat2D()
874 >>> p = (50, 50, 50, 5, 2)
875 >>> Z = PSF.evaluate(X, Y, *p)
877 .. plot::
879 import numpy as np
880 import matplotlib.pyplot as plt
881 from astropy.modeling import models
882 X, Y = np.mgrid[:100,:100]
883 PSF = models.Moffat2D()
884 p = (50, 50, 50, 5, 2)
885 Z = PSF.evaluate(X, Y, *p)
886 plt.imshow(Z, origin='loxer')
887 plt.show()
889 >>> guess = (45, 48, 52, 4, 2)
890 >>> bounds = ((1, 10, 10, 1, 1), (100, 90, 90, 10, 10))
891 >>> fit = fit_moffat2d_outlier_removal(X, Y, Z, guess=guess, bounds=bounds, niter=3)
892 >>> res = [getattr(fit, p).value for p in fit.param_names]
894 .. doctest::
895 :hide:
897 >>> assert(np.all(np.isclose(p, res, 1e-1)))
899 .. plot::
901 import numpy as np
902 import matplotlib.pyplot as plt
903 from astropy.modeling import models
904 from spectractor.tools import fit_moffat2d_outlier_removal
905 X, Y = np.mgrid[:100,:100]
906 PSF = models.Moffat2D()
907 p = (50, 50, 50, 5, 2)
908 Z = PSF.evaluate(X, Y, *p)
909 guess = (45, 48, 52, 4, 2)
910 bounds = ((1, 10, 10, 1, 1), (100, 90, 90, 10, 10))
911 fit = fit_moffat2d_outlier_removal(X, Y, Z, guess=guess, bounds=bounds, niter=3)
912 plt.imshow(Z-fit(X, Y), origin='loxer')
913 plt.show()
914 """
915 my_logger = set_logger(__name__)
916 gg_init = models.Moffat2D()
917 if guess is not None:
918 for ip, p in enumerate(gg_init.param_names):
919 getattr(gg_init, p).value = guess[ip]
920 if bounds is not None:
921 for ip, p in enumerate(gg_init.param_names):
922 getattr(gg_init, p).min = bounds[0][ip]
923 getattr(gg_init, p).max = bounds[1][ip]
924 with warnings.catch_warnings():
925 # Ignore model linearity warning from the fitter
926 warnings.simplefilter('ignore')
927 fit = fitting.LevMarLSQFitter()
928 or_fit = fitting.FittingWithOutlierRemoval(fit, sigma_clip, niter=niter, sigma=sigma)
929 # get fitted model and filtered data
930 or_fitted_model, filtered_data = or_fit(gg_init, x, y, z)
931 my_logger.info(f'\n\t{or_fitted_model}')
932 # my_logger.debug(f'\n\t{fit.fit_info}')
933 return or_fitted_model
936def fit_moffat1d_outlier_removal(x, y, sigma=3.0, niter=3, guess=None, bounds=None):
937 """
938 Fit an astropy Moffat 1D model with parameters: amplitude, x_mean, gamma, alpha
939 using outlier removal methods.
941 Parameters
942 ----------
943 x: np.array
944 1D array of the x coordinates from meshgrid.
945 y: np.array
946 the 1D array amplitudes.
947 sigma: float
948 value of sigma for the sigma rejection of outliers (default: 3)
949 niter: int
950 maximum number of iterations for the outlier detection (default: 3)
951 guess: list, optional
952 List containing a first guess for the PSF parameters (default: None).
953 bounds: list, optional
954 2D list containing bounds for the PSF parameters with format ((min,...), (max...)) (default: None)
956 Returns
957 -------
958 fitted_model: Fittable
959 Astropy Moffat1D model
961 Examples
962 --------
964 >>> import numpy as np
965 >>> import matplotlib.pyplot as plt
966 >>> from astropy.modeling import models
967 >>> X = np.arange(100)
968 >>> PSF = models.Moffat1D()
969 >>> p = (50, 50, 5, 2)
970 >>> Y = PSF.evaluate(X, *p)
972 .. plot::
974 import numpy as np
975 import matplotlib.pyplot as plt
976 from astropy.modeling import models
977 X = np.arange(100)
978 PSF = models.Moffat1D()
979 p = (50, 50, 5, 2)
980 Y = PSF.evaluate(X, *p)
981 plt.plot(X, Y)
982 plt.show()
984 >>> guess = (45, 48, 4, 2)
985 >>> bounds = ((1, 10, 1, 1), (100, 90, 10, 10))
986 >>> fit = fit_moffat1d_outlier_removal(X, Y, guess=guess, bounds=bounds, niter=3)
987 >>> res = [getattr(fit, p).value for p in fit.param_names]
989 .. doctest::
990 :hide:
992 >>> assert(np.all(np.isclose(p, res, 1e-6)))
994 .. plot::
996 import numpy as np
997 import matplotlib.pyplot as plt
998 from astropy.modeling import models
999 from spectractor.tools import fit_moffat1d_outlier_removal
1000 X = np.arange(100)
1001 PSF = models.Moffat1D()
1002 p = (50, 50, 5, 2)
1003 Y = PSF.evaluate(X, *p)
1004 guess = (45, 48, 4, 2)
1005 bounds = ((1, 10, 1, 1), (100, 90, 10, 10))
1006 fit = fit_moffat1d_outlier_removal(X, Y, guess=guess, bounds=bounds, niter=3)
1007 plt.plot(X, Y-fit(X))
1008 plt.show()
1009 """
1010 my_logger = set_logger(__name__)
1011 gg_init = models.Moffat1D()
1012 if guess is not None:
1013 for ip, p in enumerate(gg_init.param_names):
1014 getattr(gg_init, p).value = guess[ip]
1015 if bounds is not None:
1016 for ip, p in enumerate(gg_init.param_names):
1017 getattr(gg_init, p).min = bounds[0][ip]
1018 getattr(gg_init, p).max = bounds[1][ip]
1019 with warnings.catch_warnings():
1020 # Ignore model linearity warning from the fitter
1021 warnings.simplefilter('ignore')
1022 fit = fitting.LevMarLSQFitter()
1023 or_fit = fitting.FittingWithOutlierRemoval(fit, sigma_clip, niter=niter, sigma=sigma)
1024 # get fitted model and filtered data
1025 or_fitted_model, filtered_data = or_fit(gg_init, x, y)
1026 my_logger.debug(f'\n\t{or_fitted_model}')
1027 # my_logger.debug(f'\n\t{fit.fit_info}')
1028 return or_fitted_model
1031def fit_moffat1d(x, y, guess=None, bounds=None):
1032 """Fit an astropy Moffat 1D model with parameters :
1033 amplitude, x_mean, gamma, alpha
1035 Parameters
1036 ----------
1037 x: np.array
1038 1D array of the x coordinates from meshgrid.
1039 y: np.array
1040 the 1D array amplitudes.
1041 guess: list, optional
1042 List containing a first guess for the PSF parameters (default: None).
1043 bounds: list, optional
1044 2D list containing bounds for the PSF parameters with format ((min,...), (max...)) (default: None)
1046 Returns
1047 -------
1048 fitted_model: Fittable
1049 Astropy Moffat1D model
1051 Examples
1052 --------
1054 >>> import numpy as np
1055 >>> import matplotlib.pyplot as plt
1056 >>> from astropy.modeling import models
1057 >>> X = np.arange(100)
1058 >>> PSF = models.Moffat1D()
1059 >>> p = (50, 50, 5, 2)
1060 >>> Y = PSF.evaluate(X, *p)
1062 .. plot::
1064 import numpy as np
1065 import matplotlib.pyplot as plt
1066 from astropy.modeling import models
1067 X = np.arange(100)
1068 PSF = models.Moffat1D()
1069 p = (50, 50, 5, 2)
1070 Y = PSF.evaluate(X, *p)
1071 plt.plot(X, Y)
1072 plt.show()
1074 >>> guess = (45, 48, 4, 2)
1075 >>> bounds = ((1, 10, 1, 1), (100, 90, 10, 10))
1076 >>> fit = fit_moffat1d(X, Y, guess=guess, bounds=bounds)
1077 >>> res = [getattr(fit, p).value for p in fit.param_names]
1078 >>> assert(np.all(np.isclose(p, res, 1e-6)))
1080 .. plot::
1082 import numpy as np
1083 import matplotlib.pyplot as plt
1084 from astropy.modeling import models
1085 from spectractor.tools import fit_moffat1d
1086 X = np.arange(100)
1087 PSF = models.Moffat1D()
1088 p = (50, 50, 5, 2)
1089 Y = PSF.evaluate(X, *p)
1090 guess = (45, 48, 4, 2)
1091 bounds = ((1, 10, 1, 1), (100, 90, 10, 10))
1092 fit = fit_moffat1d(X, Y, guess=guess, bounds=bounds)
1093 plt.plot(X, Y-fit(X))
1094 plt.show()
1095 """
1096 my_logger = set_logger(__name__)
1097 gg_init = models.Moffat1D()
1098 if guess is not None:
1099 for ip, p in enumerate(gg_init.param_names):
1100 getattr(gg_init, p).value = guess[ip]
1101 if bounds is not None:
1102 for ip, p in enumerate(gg_init.param_names):
1103 getattr(gg_init, p).min = bounds[0][ip]
1104 getattr(gg_init, p).max = bounds[1][ip]
1105 with warnings.catch_warnings():
1106 # Ignore model linearity warning from the fitter
1107 warnings.simplefilter('ignore')
1108 fit = fitting.LevMarLSQFitter()
1109 fitted_model = fit(gg_init, x, y)
1110 my_logger.info(f'\n\t{fitted_model}')
1111 # my_logger.debug(f'\n\t{fit.fit_info}')
1112 return fitted_model
1115class LevMarLSQFitterWithNan(fitting.LevMarLSQFitter):
1117 def objective_function(self, fps, *args):
1118 """
1119 Function to minimize.
1121 Parameters
1122 ----------
1123 fps : list
1124 parameters returned by the fitter
1125 args : list
1126 [model, [weights], [input coordinates]]
1127 """
1129 model = args[0]
1130 weights = args[1]
1131 fitting._fitter_to_model_params(model, fps)
1132 meas = args[-1]
1133 if weights is None:
1134 a = np.ravel(model(*args[2: -1]) - meas)
1135 a[np.isfinite(a)] = 0
1136 return a
1137 else:
1138 a = np.ravel(weights * (model(*args[2: -1]) - meas))
1139 a[~np.isfinite(a)] = 0
1140 return a
1143def compute_fwhm(x, y, minimum=0, center=None, full_output=False):
1144 """
1145 Compute the full width half maximum of y(x) curve,
1146 using an interpolation of the data points and dichotomie method.
1148 Parameters
1149 ----------
1150 x: array_like
1151 The abscisse array.
1152 y: array_like
1153 The function array.
1154 minimum: float, optional
1155 The minimum reference from which to compyte half the height (default: 0).
1156 center: float, optional
1157 The center of the curve. If None, the weighted averageof the y(x) distribution is computed (default: None).
1158 full_output: bool, optional
1159 If True, half maximum, the edges of the curve and the curve center are given in output (default: False).
1161 Returns
1162 -------
1163 FWHM: float
1164 The full width half maximum of the curve.
1165 half: float, optional
1166 The half maximum value. Only if full_output=True.
1167 center: float, optional
1168 The y(x) center value. Only if full_output=True.
1169 left_edge: float, optional
1170 The left_edge value at half maximum. Only if full_output=True.
1171 right_edge: float, optional
1172 The right_edge value at half maximum. Only if full_output=True.
1174 Examples
1175 --------
1177 Gaussian example
1179 >>> x = np.arange(0, 100, 1)
1180 >>> stddev = 4
1181 >>> middle = 40
1182 >>> psf = gauss(x, 1, middle, stddev)
1183 >>> fwhm, half, center, a, b = compute_fwhm(x, psf, full_output=True)
1184 >>> print(f"{fwhm:.4f} {2.355*stddev:.4f} {center:.4f}")
1185 9.4329 9.4200 40.0000
1187 .. doctest::
1188 :hide:
1190 >>> assert np.isclose(fwhm, 2.355*stddev, atol=2e-1)
1191 >>> assert np.isclose(center, middle, atol=1e-3)
1193 .. plot ::
1195 import matplotlib.pyplot as plt
1196 import numpy as np
1197 from spectractor.tools import gauss, compute_fwhm
1198 x = np.arange(0, 100, 1)
1199 stddev = 4
1200 middle = 40
1201 psf = gauss(x, 1, middle, stddev)
1202 fwhm, half, center, a, b = compute_fwhm(x, psf, full_output=True)
1203 plt.figure()
1204 plt.plot(x, psf, label="function")
1205 plt.axvline(center, color="gray", label="center")
1206 plt.axvline(a, color="k", label="edges at half max")
1207 plt.axvline(b, color="k", label="edges at half max")
1208 plt.axhline(half, color="r", label="half max")
1209 plt.legend()
1210 plt.title(f"FWHM={fwhm:.3f}")
1211 plt.xlabel("x")
1212 plt.ylabel("y")
1213 plt.show()
1215 Defocused PSF example
1217 >>> from spectractor.extractor.psf import MoffatGauss
1218 >>> p = [2,40,40,4,2,-0.4,1,10]
1219 >>> psf = MoffatGauss(p)
1220 >>> fwhm, half, center, a, b = compute_fwhm(x, psf.evaluate(x), full_output=True)
1222 .. doctest::
1223 :hide:
1225 >>> assert np.isclose(fwhm, 7.05, atol=1e-2)
1226 >>> assert np.isclose(center, p[1], atol=1e-2)
1228 .. plot ::
1230 import matplotlib.pyplot as plt
1231 import numpy as np
1232 from spectractor.tools import gauss, compute_fwhm
1233 from spectractor.extractor.psf import MoffatGauss
1234 x = np.arange(0, 100, 1)
1235 p = [2,40,40,4,2,-0.4,1,10]
1236 psf = MoffatGauss(p)
1237 fwhm, half, center, a, b = compute_fwhm(x, psf.evaluate(x), full_output=True)
1238 plt.figure()
1239 plt.plot(x, psf.evaluate(x, p), label="function")
1240 plt.axvline(center, color="gray", label="center")
1241 plt.axvline(a, color="k", label="edges at half max")
1242 plt.axvline(b, color="k", label="edges at half max")
1243 plt.axhline(half, color="r", label="half max")
1244 plt.legend()
1245 plt.title(f"FWHM={fwhm:.3f}")
1246 plt.xlabel("x")
1247 plt.ylabel("y")
1248 plt.show()
1249 """
1250 if y.ndim > 1:
1251 # TODO: implement fwhm for 2D curves
1252 return -1
1253 interp = interp1d(x, y, kind="linear", bounds_error=False, fill_value="extrapolate")
1254 maximum = np.max(y) - minimum
1255 imax = np.argmax(y)
1256 a = x[imax + np.argmin(np.abs(y[imax:] - 0.9 * maximum))]
1257 b = x[imax + np.argmin(np.abs(y[imax:] - 0.1 * maximum))]
1259 def eq(xx):
1260 return interp(xx) - 0.5 * maximum
1262 res = dichotomie(eq, a, b, 1e-3)
1263 if center is None:
1264 center = np.average(x, weights=y)
1265 fwhm = abs(2 * (res - center))
1266 if not full_output:
1267 return fwhm
1268 else:
1269 return fwhm, 0.5 * maximum, center, res, center - abs(res - center)
1272def compute_integral(x, y, bounds=None):
1273 """
1274 Compute the integral of an y(x) curve. The curve is interpolated and extrapolated with cubic splines.
1275 If not provided, bounds are set to the x array edges.
1277 Parameters
1278 ----------
1279 x: array_like
1280 The abscisse array.
1281 y: array_like
1282 The function array.
1283 bounds: array_like, optional
1284 The bounds of the integral. If None, the edges of thex array are taken (default bounds=None).
1286 Returns
1287 -------
1288 result: float
1289 The integral of the PSF model.
1291 Examples
1292 --------
1294 Gaussian example
1296 .. doctest::
1298 >>> x = np.arange(0, 100, 0.5)
1299 >>> stddev = 4
1300 >>> middle = 40
1301 >>> psf = gauss(x, 1/(stddev*np.sqrt(2*np.pi)), middle, stddev)
1302 >>> integral = compute_integral(x, psf)
1303 >>> print(f"{integral:.6f}")
1304 1.000000
1306 Defocused PSF example
1308 .. doctest::
1310 >>> from spectractor.extractor.psf import MoffatGauss
1311 >>> p = [2,30,30,4,2,-0.5,1,10]
1312 >>> psf = MoffatGauss(p)
1313 >>> integral = compute_integral(x, psf.evaluate(x))
1314 >>> assert np.isclose(integral, p[0], atol=1e-2)
1316 """
1317 if bounds is None:
1318 bounds = (np.min(x), np.max(x))
1319 interp = interp1d(x, y, kind="cubic", bounds_error=False, fill_value="extrapolate")
1320 integral = quad(interp, bounds[0], bounds[1], limit=200)
1321 return integral[0]
1324def find_nearest(array, value):
1325 """Find the nearest index and value in an array.
1327 Parameters
1328 ----------
1329 array: array
1330 The array to inspect.
1331 value: float
1332 The value to look for.
1334 Returns
1335 -------
1336 index: int
1337 The array index of the nearest value close to *value*
1338 val: float
1339 The value fo the array at index.
1341 Examples
1342 --------
1343 >>> x = np.arange(0.,10.)
1344 >>> idx, val = find_nearest(x, 3.3)
1345 >>> print(idx, val)
1346 3 3.0
1347 """
1348 idx = (np.abs(array - value)).argmin()
1349 return idx, array[idx]
1352def ensure_dir(directory_name):
1353 """Ensure that *directory_name* directory exists. If not, create it.
1355 Parameters
1356 ----------
1357 directory_name: str
1358 The directory name.
1360 Examples
1361 --------
1362 >>> ensure_dir('tests')
1363 >>> os.path.exists('tests')
1364 True
1365 >>> ensure_dir('tests/mytest')
1366 >>> os.path.exists('tests/mytest')
1367 True
1368 >>> os.rmdir('./tests/mytest')
1369 """
1370 if not os.path.exists(directory_name):
1371 os.makedirs(directory_name)
1374def weighted_avg_and_std(values, weights):
1375 """
1376 Return the weighted average and standard deviation.
1378 values, weights -- Numpy ndarrays with the same shape.
1380 For example for the PSF
1382 x=pixel number
1383 y=Intensity in pixel
1385 values-x
1386 weights=y=f(x)
1388 """
1389 average = np.average(values, weights=weights)
1390 variance = np.average((values - average) ** 2, weights=weights) # Fast and numerically precise
1391 return average, np.sqrt(variance)
1394def hessian_and_theta(data, margin_cut=1):
1395 # compute hessian matrices on the image
1396 Hxx, Hxy, Hyy = hessian_matrix(data, sigma=3, order='rc')
1397 lambda_plus = 0.5 * ((Hxx + Hyy) + np.sqrt((Hxx - Hyy) ** 2 + 4 * Hxy * Hxy))
1398 lambda_minus = 0.5 * ((Hxx + Hyy) - np.sqrt((Hxx - Hyy) ** 2 + 4 * Hxy * Hxy))
1399 theta = 0.5 * np.arctan2(2 * Hxy, Hxx - Hyy) * 180 / np.pi
1400 # remove the margins
1401 lambda_minus = lambda_minus[margin_cut:-margin_cut, margin_cut:-margin_cut]
1402 lambda_plus = lambda_plus[margin_cut:-margin_cut, margin_cut:-margin_cut]
1403 theta = theta[margin_cut:-margin_cut, margin_cut:-margin_cut]
1404 return lambda_plus, lambda_minus, theta
1407def filter_stars_from_bgd(data, margin_cut=1):
1408 lambda_plus, lambda_minus, theta = hessian_and_theta(np.copy(data), margin_cut=margin_cut)
1409 # thresholds
1410 lambda_threshold = np.median(lambda_minus) - 2 * np.std(lambda_minus)
1411 mask = np.where(lambda_minus < lambda_threshold)
1412 data[mask] = np.nan
1413 return data
1416def fftconvolve_gaussian(array, reso):
1417 """Convolve an 1D or 2D array with a Gaussian profile of given standard deviation.
1419 Parameters
1420 ----------
1421 array: array
1422 The array to convolve.
1423 reso: float
1424 The standard deviation of the Gaussian profile.
1426 Returns
1427 -------
1428 convolved: array
1429 The convolved array, same size and shape as input.
1431 Examples
1432 --------
1433 >>> array = np.ones(100)
1434 >>> output = fftconvolve_gaussian(array, 3)
1435 >>> print(output[:3])
1436 [0.5 0.63114657 0.74850168]
1437 >>> array = np.ones((100, 100))
1438 >>> output = fftconvolve_gaussian(array, 3)
1439 >>> print(output[0][:3])
1440 [0.5 0.63114657 0.74850168]
1441 >>> array = np.ones((100, 100, 100))
1442 >>> output = fftconvolve_gaussian(array, 3)
1443 """
1444 my_logger = set_logger(__name__)
1445 if array.ndim == 2:
1446 kernel = gaussian(array.shape[1], reso)
1447 kernel /= np.sum(kernel)
1448 for i in range(array.shape[0]):
1449 array[i] = fftconvolve(array[i], kernel, mode='same')
1450 elif array.ndim == 1:
1451 kernel = gaussian(array.size, reso)
1452 kernel /= np.sum(kernel)
1453 array = fftconvolve(array, kernel, mode='same')
1454 else:
1455 my_logger.error(f'\n\tArray dimension must be 1 or 2. Here I have array.ndim={array.ndim}.')
1456 return array
1459def formatting_numbers(value, error_high, error_low, std=None, label=None):
1460 """Format a physical value and its uncertainties. Round the uncertainties
1461 to the first significant digit, and do the same for the physical value.
1463 Parameters
1464 ----------
1465 value: float
1466 The physical value.
1467 error_high: float
1468 Upper uncertainty.
1469 error_low: float
1470 Lower uncertainty
1471 std: float, optional
1472 The RMS of the physical parameter (default: None).
1473 label: str, optional
1474 The name of the physical parameter to output (default: None).
1476 Returns
1477 -------
1478 text: tuple
1479 The formatted output strings inside a tuple.
1481 Examples
1482 --------
1483 >>> formatting_numbers(3., 0.789, 0.500, std=0.45, label='test')
1484 ('test', '3.0', '0.8', '0.5', '0.5')
1485 >>> formatting_numbers(3., 0.07, 0.008, std=0.03, label='test')
1486 ('test', '3.000', '0.07', '0.008', '0.03')
1487 >>> formatting_numbers(3240., 0.2, 0.4, std=0.3)
1488 ('3240.0', '0.2', '0.4', '0.3')
1489 >>> formatting_numbers(3240., 230, 420, std=330)
1490 ('3240', '230', '420', '330')
1491 >>> formatting_numbers(0, 0.008, 0.04, std=0.03)
1492 ('0.000', '0.008', '0.040', '0.030')
1493 >>> formatting_numbers(-55, 0.008, 0.04, std=0.03)
1494 ('-55.000', '0.008', '0.04', '0.03')
1495 """
1496 str_std = ""
1497 out = []
1498 if label is not None:
1499 out.append(label)
1500 power10 = min(int(floor(np.log10(np.abs(error_high)))), int(floor(np.log10(np.abs(error_low)))))
1501 if np.isclose(0.0, float("%.*f" % (abs(power10), value))):
1502 str_value = "%.*f" % (abs(power10), 0)
1503 str_error_high = "%.*f" % (abs(power10), error_high)
1504 str_error_low = "%.*f" % (abs(power10), error_low)
1505 if std is not None:
1506 str_std = "%.*f" % (abs(power10), std)
1507 elif power10 > 0:
1508 str_value = f"{value:.0f}"
1509 str_error_high = f"{error_high:.0f}"
1510 str_error_low = f"{error_low:.0f}"
1511 if std is not None:
1512 str_std = f"{std:.0f}"
1513 else:
1514 if int(floor(np.log10(np.abs(error_high)))) == int(floor(np.log10(np.abs(error_low)))):
1515 str_value = "%.*f" % (abs(power10), value)
1516 str_error_high = f"{error_high:.1g}"
1517 str_error_low = f"{error_low:.1g}"
1518 if std is not None:
1519 str_std = f"{std:.1g}"
1520 elif int(floor(np.log10(np.abs(error_high)))) > int(floor(np.log10(np.abs(error_low)))):
1521 str_value = "%.*f" % (abs(power10), value)
1522 str_error_high = f"{error_high:.2g}"
1523 str_error_low = f"{error_low:.1g}"
1524 if std is not None:
1525 str_std = f"{std:.2g}"
1526 else:
1527 str_value = "%.*f" % (abs(power10), value)
1528 str_error_high = f"{error_high:.1g}"
1529 str_error_low = f"{error_low:.2g}"
1530 if std is not None:
1531 str_std = f"{std:.2g}"
1532 out += [str_value, str_error_high]
1533 # if not np.isclose(error_high, error_low):
1534 out += [str_error_low]
1535 if std is not None:
1536 out += [str_std]
1537 out = tuple(out)
1538 return out
1541def pixel_rotation(x, y, theta, x0=0, y0=0):
1542 """Rotate a 2D vector (x,y) of an angle theta clockwise.
1544 Parameters
1545 ----------
1546 x: float
1547 x coordinate
1548 y: float
1549 y coordinate
1550 theta: float
1551 angle in radians
1552 x0: float, optional
1553 x position of the center of rotation (default: 0)
1554 y0: float, optional
1555 y position of the center of rotation (default: 0)
1557 Returns
1558 -------
1559 u: float
1560 rotated x coordinate
1561 v: float
1562 rotated y coordinate
1564 Examples
1565 --------
1566 >>> pixel_rotation(0, 0, 45)
1567 (0.0, 0.0)
1568 >>> u, v = pixel_rotation(1, 0, np.pi/4)
1570 .. doctest::
1571 :hide:
1573 >>> assert np.isclose(u, 1/np.sqrt(2))
1574 >>> assert np.isclose(v, -1/np.sqrt(2))
1575 >>> u, v = pixel_rotation(1, 2, -np.pi/2, x0=1, y0=0)
1576 >>> assert np.isclose(u, -2)
1577 >>> assert np.isclose(v, 0)
1578 """
1579 u = np.cos(theta) * (x - x0) + np.sin(theta) * (y - y0)
1580 v = -np.sin(theta) * (x - x0) + np.cos(theta) * (y - y0)
1581 return u, v
1584def detect_peaks(image):
1585 """
1586 Takes an image and detect the peaks using the local maximum filter.
1587 Returns a boolean mask of the peaks (i.e. 1 when
1588 the pixel's value is the neighborhood maximum, 0 otherwise).
1589 Only positive peaks are detected (take absolute value or negative value of the
1590 image to detect the negative ones).
1592 Parameters
1593 ----------
1594 image: array_like
1595 The image 2D array.
1597 Returns
1598 -------
1599 detected_peaks: array_like
1600 Boolean maskof the peaks.
1602 Examples
1603 --------
1604 >>> im = np.zeros((50,50))
1605 >>> im[4,6] = 2
1606 >>> im[10,20] = -3
1607 >>> im[49,49] = 1
1608 >>> detected_peaks = detect_peaks(im)
1610 .. doctest::
1611 :hide:
1613 >>> assert detected_peaks[4,6]
1614 >>> assert not detected_peaks[10,20]
1615 >>> assert detected_peaks[49,49]
1616 """
1618 # define an 8-connected neighborhood
1619 neighborhood = generate_binary_structure(2, 2)
1621 # apply the local maximum filter; all pixel of maximal value
1622 # in their neighborhood are set to 1
1623 local_max = maximum_filter(image, footprint=neighborhood) == image
1624 # local_max is a mask that contains the peaks we are
1625 # looking for, but also the background.
1626 # In order to isolate the peaks we must remove the background from the mask.
1628 # we create the mask of the background
1629 background = (image == 0)
1631 # a little technicality: we must erode the background in order to
1632 # successfully subtract it form local_max, otherwise a line will
1633 # appear along the background border (artifact of the local maximum filter)
1634 eroded_background = binary_erosion(background, structure=neighborhood, border_value=50)
1636 # we obtain the final mask, containing only peaks,
1637 # by removing the background from the local_max mask (xor operation)
1638 detected_peaks = local_max ^ eroded_background
1640 return detected_peaks
1643def clean_target_spikes(data, saturation):
1644 saturated_pixels = np.where(data > saturation)
1645 data[saturated_pixels] = saturation
1646 NY, NX = data.shape
1647 delta = len(saturated_pixels[0])
1648 while delta > 0:
1649 delta = len(saturated_pixels[0])
1650 grady, gradx = np.gradient(data)
1651 for iy in range(1, NY - 1):
1652 for ix in range(1, NX - 1):
1653 # if grady[iy,ix] > 0.8*np.max(grady) :
1654 # data[iy,ix] = data[iy-1,ix]
1655 # if grady[iy,ix] < 0.8*np.min(grady) :
1656 # data[iy,ix] = data[iy+1,ix]
1657 if gradx[iy, ix] > 0.8 * np.max(gradx):
1658 data[iy, ix] = data[iy, ix - 1]
1659 if gradx[iy, ix] < 0.8 * np.min(gradx):
1660 data[iy, ix] = data[iy, ix + 1]
1661 saturated_pixels = np.where(data >= saturation)
1662 delta = delta - len(saturated_pixels[0])
1663 return data
1666def plot_image_simple(ax, data, scale="lin", title="", units="Image units", cmap=None,
1667 target_pixcoords=None, vmin=None, vmax=None, aspect=None, cax=None):
1668 """Simple function to plot a spectrum with error bars and labels.
1670 Parameters
1671 ----------
1672 ax: Axes
1673 Axes instance to make the plot
1674 data: array_like
1675 The image data 2D array.
1676 scale: str
1677 Scaling of the image (choose between: lin, log or log10, symlog) (default: lin)
1678 title: str
1679 Title of the image (default: "")
1680 units: str
1681 Units of the image to be written in the color bar label (default: "Image units")
1682 cmap: colormap
1683 Color map label (default: None)
1684 target_pixcoords: array_like, optional
1685 2D array giving the (x,y) coordinates of the targets on the image: add a scatter plot (default: None)
1686 vmin: float
1687 Minimum value of the image (default: None)
1688 vmax: float
1689 Maximum value of the image (default: None)
1690 aspect: str
1691 Aspect keyword to be passed to imshow (default: None)
1692 cax: Axes, optional
1693 Color bar axes if necessary (default: None).
1695 Examples
1696 --------
1698 .. plot::
1699 :include-source:
1701 >>> import matplotlib.pyplot as plt
1702 >>> from spectractor.extractor.images import Image
1703 >>> from spectractor import parameters
1704 >>> from spectractor.tools import plot_image_simple
1705 >>> f, ax = plt.subplots(1,1)
1706 >>> im = Image('tests/data/reduc_20170605_028.fits', config="./config/ctio.ini")
1707 >>> plot_image_simple(ax, im.data, scale="symlog", units="ADU", target_pixcoords=(815,580),
1708 ... title="tests/data/reduc_20170605_028.fits")
1709 >>> if parameters.DISPLAY: plt.show()
1710 """
1711 if scale == "log" or scale == "log10":
1712 # removes the zeros and negative pixels first
1713 zeros = np.where(data <= 0)
1714 min_noz = np.min(data[np.where(data > 0)])
1715 data[zeros] = min_noz
1716 # apply log
1717 # data = np.log10(data)
1718 if scale == "log10" or scale == "log":
1719 norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax)
1720 elif scale == "symlog":
1721 norm = matplotlib.colors.SymLogNorm(vmin=vmin, vmax=vmax, linthresh=10, base=10)
1722 else:
1723 norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
1724 im = ax.imshow(data, origin='lower', cmap=cmap, norm=norm, aspect=aspect)
1725 ax.grid(color='silver', ls='solid')
1726 ax.grid(True)
1727 ax.set_xlabel(parameters.PLOT_XLABEL)
1728 ax.set_ylabel(parameters.PLOT_YLABEL)
1729 cb = plt.colorbar(im, ax=ax, cax=cax)
1730 if scale == "lin":
1731 cb.formatter.set_powerlimits((0, 0))
1732 cb.locator = MaxNLocator(7, prune=None)
1733 cb.update_ticks()
1734 cb.set_label('%s (%s scale)' % (units, scale)) # ,fontsize=16)
1735 if title != "":
1736 ax.set_title(title)
1737 if target_pixcoords is not None:
1738 ax.scatter(target_pixcoords[0], target_pixcoords[1], marker='o', s=100, edgecolors='k', facecolors='none',
1739 label='Target', linewidth=2)
1742def plot_spectrum_simple(ax, lambdas, data, data_err=None, xlim=None, color='r', linestyle='none', lw=2, label='',
1743 title='', units=''):
1744 """Simple function to plot a spectrum with error bars and labels.
1746 Parameters
1747 ----------
1748 ax: Axes
1749 Axes instance to make the plot.
1750 lambdas: array
1751 The wavelengths array.
1752 data: array
1753 The spectrum data array.
1754 data_err: array, optional
1755 The spectrum uncertainty array (default: None).
1756 xlim: list, optional
1757 List of minimum and maximum abscisses (default: None).
1758 color: str, optional
1759 String for the color of the spectrum (default: 'r').
1760 linestyle: str, optional
1761 String for the linestyle of the spectrum (default: 'none').
1762 lw: int, optional
1763 Integer for line width (default: 2).
1764 label: str, optional
1765 String label for the plot legend (default: '').
1766 title: str, optional
1767 String label for the plot title (default: '').
1768 units: str, optional
1769 String label for the plot units (default: '').
1772 Examples
1773 --------
1775 .. plot::
1776 :include-source:
1778 >>> import matplotlib.pyplot as plt
1779 >>> from spectractor.extractor.spectrum import Spectrum
1780 >>> from spectractor import parameters
1781 >>> from spectractor.tools import plot_spectrum_simple
1782 >>> f, ax = plt.subplots(1,1)
1783 >>> s = Spectrum(file_name='tests/data/reduc_20170530_134_spectrum.fits')
1784 >>> plot_spectrum_simple(ax, s.lambdas, s.data, data_err=s.err, xlim=None, color='r', label='test')
1785 >>> if parameters.DISPLAY: plt.show()
1786 """
1787 xs = lambdas
1788 if xs is None:
1789 xs = np.arange(data.size)
1790 if data_err is not None:
1791 ax.errorbar(xs, data, yerr=data_err, fmt=f'{color}o', lw=lw, label=label,
1792 zorder=0, markersize=2, linestyle=linestyle)
1793 else:
1794 ax.plot(xs, data, color=color, lw=lw, label=label, linestyle=linestyle)
1795 ax.grid(True)
1796 if xlim is None and lambdas is not None:
1797 xlim = [parameters.LAMBDA_MIN, parameters.LAMBDA_MAX]
1798 ax.set_xlim(xlim)
1799 try:
1800 ax.set_ylim(0., np.nanmax(data[np.logical_and(xs > xlim[0], xs < xlim[1])]) * 1.2)
1801 except ValueError:
1802 pass
1803 if lambdas is not None:
1804 ax.set_xlabel(r'$\lambda$ [nm]')
1805 else:
1806 ax.set_xlabel('X [pixels]')
1807 if units != '':
1808 ax.set_ylabel(f'Flux [{units}]')
1809 else:
1810 ax.set_ylabel(f'Flux')
1811 if title != '':
1812 ax.set_title(title)
1815def plot_compass_simple(ax, parallactic_angle=None, arrow_size=0.1, origin=[0.15, 0.15]):
1816 """Plot small (N,W) compass, and optionally zenith direction.
1818 Parameters
1819 ----------
1820 ax: Axes
1821 Axes instance to make the plot.
1822 parallactic_angle: float, optional
1823 Value is the parallactic angle with respect to North eastward and plot the zenith direction (default: None).
1824 arrow_size: float, optional
1825 Length of the arrow as a fraction of axe sizes (default: 0.1)
1826 origin: array_like, optional
1827 (x0, y0) position of the compass as axes fraction (default: [0.15, 0.15]).
1829 Examples
1830 --------
1832 >>> from spectractor.extractor.images import Image
1833 >>> from spectractor import parameters
1834 >>> from spectractor.tools import plot_image_simple, plot_compass_simple
1835 >>> f, ax = plt.subplots(1,1)
1836 >>> im = Image('tests/data/reduc_20170605_028.fits', config="./config/ctio.ini")
1837 >>> plot_image_simple(ax, im.data, scale="symlog", units="ADU", target_pixcoords=(750,700),
1838 ... title='tests/data/reduc_20170530_134.fits')
1839 >>> plot_compass_simple(ax, im.parallactic_angle)
1840 >>> if parameters.DISPLAY: plt.show()
1842 """
1843 # North arrow
1844 N_arrow = [0, arrow_size]
1845 N_xy = np.asarray(flip_and_rotate_radec_to_image_xy_coordinates(N_arrow[0], N_arrow[1],
1846 camera_angle=parameters.OBS_CAMERA_ROTATION,
1847 flip_ra_sign=parameters.OBS_CAMERA_RA_FLIP_SIGN,
1848 flip_dec_sign=parameters.OBS_CAMERA_DEC_FLIP_SIGN))
1849 ax.annotate("N", xy=origin, xycoords='axes fraction', xytext=N_xy + origin, textcoords='axes fraction',
1850 arrowprops=dict(arrowstyle="<|-", fc="yellow", ec="yellow"), color="yellow",
1851 horizontalalignment='center', verticalalignment='center')
1852 # West arrow
1853 W_arrow = [arrow_size, 0]
1854 W_xy = np.asarray(flip_and_rotate_radec_to_image_xy_coordinates(W_arrow[0], W_arrow[1],
1855 camera_angle=parameters.OBS_CAMERA_ROTATION,
1856 flip_ra_sign=parameters.OBS_CAMERA_RA_FLIP_SIGN,
1857 flip_dec_sign=parameters.OBS_CAMERA_DEC_FLIP_SIGN))
1858 ax.annotate("W", xy=origin, xycoords='axes fraction', xytext=W_xy + origin, textcoords='axes fraction',
1859 arrowprops=dict(arrowstyle="<|-", fc="yellow", ec="yellow"), color="yellow",
1860 horizontalalignment='center', verticalalignment='center')
1861 # Central dot
1862 xmin, xmax = ax.get_xlim()
1863 ymin, ymax = ax.get_ylim()
1864 ax.scatter(origin[0] * xmax, origin[1] * ymax, color="yellow", s=20)
1865 # Zenith direction
1866 if parallactic_angle is not None:
1867 p_arrow = [0, arrow_size] # angle with respect to North in RADEC counterclockwise
1868 angle = parameters.OBS_CAMERA_ROTATION + parameters.OBS_CAMERA_RA_FLIP_SIGN * parallactic_angle
1869 p_xy = np.asarray(flip_and_rotate_radec_to_image_xy_coordinates(p_arrow[0], p_arrow[1],
1870 camera_angle=angle,
1871 flip_ra_sign=parameters.OBS_CAMERA_RA_FLIP_SIGN,
1872 flip_dec_sign=parameters.OBS_CAMERA_DEC_FLIP_SIGN))
1873 ax.annotate("Z", xy=origin, xycoords='axes fraction', xytext=p_xy + origin, textcoords='axes fraction',
1874 arrowprops=dict(arrowstyle="<|-", fc="lightgreen", ec="lightgreen"), color="lightgreen",
1875 horizontalalignment='center', verticalalignment='center')
1878def load_fits(file_name, hdu_index=0):
1879 """Generic function to load a FITS file.
1881 Parameters
1882 ----------
1883 file_name: str
1884 The FITS file name.
1885 hdu_index: int, optional
1886 The HDU index in the file (default: 0).
1888 Returns
1889 -------
1890 header: fits.Header
1891 Header of the FITS file.
1892 data: np.array
1893 The data array.
1895 Examples
1896 --------
1897 >>> header, data = load_fits("./tests/data/reduc_20170530_134.fits")
1898 >>> header["DATE-OBS"]
1899 '2017-05-31T02:53:52.356'
1900 >>> data.shape
1901 (2048, 2048)
1903 """
1904 hdu_list = fits.open(file_name)
1905 header = hdu_list[0].header
1906 data = hdu_list[hdu_index].data
1907 hdu_list.close() # need to free allocation for file description
1908 return header, data
1911def save_fits(file_name, header, data, overwrite=False):
1912 """Generic function to save a FITS file.
1914 Parameters
1915 ----------
1916 file_name: str
1917 The FITS file name.
1918 header: fits.Header
1919 Header of the FITS file.
1920 data: np.array
1921 The data array.
1922 overwrite: bool, optional
1923 If True and the file already exists, it is overwritten (default: False).
1925 Examples
1926 --------
1928 >>> header, data = load_fits("./tests/data/reduc_20170530_134.fits")
1929 >>> save_fits("./outputs/save_fits_test.fits", header, data, overwrite=True)
1930 >>> assert os.path.isfile("./outputs/save_fits_test.fits")
1932 .. doctest:
1933 :hide:
1935 >>> os.remove("./outputs/save_fits_test.fits")
1937 """
1938 hdu = fits.PrimaryHDU()
1939 hdu.header = header
1940 hdu.data = data
1941 output_directory = '/'.join(file_name.split('/')[:-1])
1942 ensure_dir(output_directory)
1943 hdu.writeto(file_name, overwrite=overwrite)
1946def dichotomie(f, a, b, epsilon):
1947 """
1948 Dichotomie method to find a function root.
1950 Parameters
1951 ----------
1952 f: callable
1953 The function
1954 a: float
1955 Left bound to the expected root
1956 b: float
1957 Right bound to the expected root
1958 epsilon: float
1959 Precision
1961 Returns
1962 -------
1963 root: float
1964 The root of the function.
1966 Examples
1967 --------
1969 Search for the Gaussian FWHM:
1971 >>> p = [1,0,1]
1972 >>> xx = np.arange(-10,10,0.1)
1973 >>> PSF = gauss(xx, *p)
1974 >>> def eq(x):
1975 ... return np.interp(x, xx, PSF) - 0.5
1976 >>> root = dichotomie(eq, 0, 10, 1e-6)
1977 >>> assert np.isclose(2*root, 2.355*p[2], 1e-3)
1978 """
1979 x = 0.5 * (a + b)
1980 N = 1
1981 while b - a > epsilon and N < 100:
1982 x = 0.5 * (a + b)
1983 if f(x) * f(a) > 0:
1984 a = x
1985 else:
1986 b = x
1987 N += 1
1988 return x
1991def wavelength_to_rgb(wavelength, gamma=0.8):
1992 """ taken from http://www.noah.org/wiki/Wavelength_to_RGB_in_Python
1993 This converts a given wavelength of light to an
1994 approximate RGB color value. The wavelength must be given
1995 in nanometers in the range from 380 nm through 750 nm
1996 (789 THz through 400 THz).
1998 Based on code by Dan Bruton
1999 http://www.physics.sfasu.edu/astro/color/spectra.html
2000 Additionally alpha value set to 0.5 outside range
2001 """
2002 wavelength = float(wavelength)
2003 if 380 <= wavelength <= 750:
2004 A = 1.
2005 else:
2006 A = 0.5
2007 if wavelength < 380:
2008 wavelength = 380.
2009 if wavelength > 750:
2010 wavelength = 750.
2011 if 380 <= wavelength <= 440:
2012 attenuation = 0.3 + 0.7 * (wavelength - 380) / (440 - 380)
2013 R = ((-(wavelength - 440) / (440 - 380)) * attenuation) ** gamma
2014 G = 0.0
2015 B = (1.0 * attenuation) ** gamma
2016 elif 440 <= wavelength <= 490:
2017 R = 0.0
2018 G = ((wavelength - 440) / (490 - 440)) ** gamma
2019 B = 1.0
2020 elif 490 <= wavelength <= 510:
2021 R = 0.0
2022 G = 1.0
2023 B = (-(wavelength - 510) / (510 - 490)) ** gamma
2024 elif 510 <= wavelength <= 580:
2025 R = ((wavelength - 510) / (580 - 510)) ** gamma
2026 G = 1.0
2027 B = 0.0
2028 elif 580 <= wavelength <= 645:
2029 R = 1.0
2030 G = (-(wavelength - 645) / (645 - 580)) ** gamma
2031 B = 0.0
2032 elif 645 <= wavelength <= 750:
2033 attenuation = 0.3 + 0.7 * (750 - wavelength) / (750 - 645)
2034 R = (1.0 * attenuation) ** gamma
2035 G = 0.0
2036 B = 0.0
2037 else:
2038 R = 0.0
2039 G = 0.0
2040 B = 0.0
2041 return R, G, B, A
2044def from_lambda_to_colormap(lambdas):
2045 """Convert an array of wavelength in nm into a color map.
2047 Parameters
2048 ----------
2049 lambdas: array_like
2050 Wavelength array in nm.
2052 Returns
2053 -------
2054 spectral_map: matplotlib.colors.LinearSegmentedColormap
2055 Color map.
2057 Examples
2058 --------
2059 >>> lambdas = np.arange(300, 1000, 10)
2060 >>> spec = from_lambda_to_colormap(lambdas)
2061 >>> plt.scatter(lambdas, np.zeros(lambdas.size), cmap=spec, c=lambdas) #doctest: +ELLIPSIS
2062 <matplotlib.collections.PathCollection object at ...>
2063 >>> plt.grid()
2064 >>> plt.xlabel("Wavelength [nm]") #doctest: +ELLIPSIS
2065 Text(..., 'Wavelength [nm]')
2066 >>> plt.show()
2068 ..plot::
2070 import numpy as np
2071 import matplotlib.pyplot as plt
2072 from spectractor.tools import from_lambda_to_colormap
2073 lambdas = np.arange(300, 1000, 10)
2074 spec = from_lambda_to_colormap(lambdas)
2075 plt.scatter(lambdas, np.zeros(lambdas.size), cmap=spec, c=lambdas)
2076 plt.xlabel("Wavelength [nm]")
2077 plt.grid()
2078 plt.show()
2080 """
2081 colorlist = [wavelength_to_rgb(lbda) for lbda in lambdas]
2082 spectralmap = matplotlib.colors.LinearSegmentedColormap.from_list("spectrum", colorlist)
2083 return spectralmap
2086def rebin(arr, new_shape):
2087 """Rebin and reshape a numpy array.
2089 Parameters
2090 ----------
2091 arr: np.array
2092 Numpy array to be reshaped.
2093 new_shape: array_like
2094 New shape of the array.
2096 Returns
2097 -------
2098 arr_rebinned: np.array
2099 Rebinned array.
2101 Examples
2102 --------
2103 >>> a = 4 * np.ones((10, 10))
2104 >>> b = rebin(a, (5, 5))
2105 >>> b
2106 array([[4., 4., 4., 4., 4.],
2107 [4., 4., 4., 4., 4.],
2108 [4., 4., 4., 4., 4.],
2109 [4., 4., 4., 4., 4.],
2110 [4., 4., 4., 4., 4.]])
2111 """
2112 if np.any(new_shape * parameters.CCD_REBIN != arr.shape):
2113 shape_cropped = new_shape * parameters.CCD_REBIN
2114 margins = np.asarray(arr.shape) - shape_cropped
2115 arr = arr[:-margins[0], :-margins[1]]
2116 shape = (new_shape[0], arr.shape[0] // new_shape[0],
2117 new_shape[1], arr.shape[1] // new_shape[1])
2118 return arr.reshape(shape).mean(-1).mean(1)
2121def set_wcs_output_directory(file_name, output_directory=""):
2122 """Returns the WCS output directory corresponding to the analyzed image. The name of the directory is
2123 the anme of the image with the suffix _wcs.
2125 Parameters
2126 ----------
2127 file_name: str
2128 File name of the image.
2129 output_directory: str, optional
2130 If not set, the main output directory is the one the image,
2131 otherwise the specified directory is taken (default: "").
2133 Returns
2134 -------
2135 output: str
2136 The name of the output directory
2138 Examples
2139 --------
2140 >>> set_wcs_output_directory("image.fits", output_directory="")
2141 'image_wcs'
2142 >>> set_wcs_output_directory("image.png", output_directory="outputs")
2143 'outputs/image_wcs'
2145 """
2146 outdir = os.path.dirname(file_name)
2147 if output_directory != "":
2148 outdir = output_directory
2149 output_directory = os.path.join(outdir, os.path.splitext(os.path.basename(file_name))[0]) + "_wcs"
2150 return output_directory
2153def set_wcs_tag(file_name):
2154 """Returns the WCS tag name associated to the analyzed image: the file name without the extension.
2156 Parameters
2157 ----------
2158 file_name: str
2159 File name of the image.
2161 Returns
2162 -------
2163 tag: str
2164 The tag.
2166 Examples
2167 --------
2168 >>> set_wcs_tag("image.fits")
2169 'image'
2171 """
2172 tag = os.path.splitext(os.path.basename(file_name))[0]
2173 return tag
2176def set_wcs_file_name(file_name, output_directory=""):
2177 """Returns the WCS file name associated to the analyzed image, placed in the output directory.
2178 The extension is .wcs.
2180 Parameters
2181 ----------
2182 file_name: str
2183 File name of the image.
2184 output_directory: str, optional
2185 If not set, the main output directory is the one the image,
2186 otherwise the specified directory is taken (default: "").
2188 Returns
2189 -------
2190 wcs_file_name: str
2191 The WCS file name.
2193 Examples
2194 --------
2195 >>> set_wcs_file_name("image.fits", output_directory="")
2196 'image_wcs/image.wcs'
2197 >>> set_wcs_file_name("image.png", output_directory="outputs")
2198 'outputs/image_wcs/image.wcs'
2200 """
2201 output_directory = set_wcs_output_directory(file_name, output_directory=output_directory)
2202 tag = set_wcs_tag(file_name)
2203 return os.path.join(output_directory, tag + '.wcs')
2206def set_sources_file_name(file_name, output_directory=""):
2207 """Returns the file name containing the deteted sources associated to the analyzed image,
2208 placed in the output directory. The suffix is _source.fits.
2210 Parameters
2211 ----------
2212 file_name: str
2213 File name of the image.
2214 output_directory: str, optional
2215 If not set, the main output directory is the one the image,
2216 otherwise the specified directory is taken (default: "").
2218 Returns
2219 -------
2220 sources_file_name: str
2221 The detected sources file name.
2223 Examples
2224 --------
2225 >>> set_sources_file_name("image.fits", output_directory="")
2226 'image_wcs/image_sources.fits'
2227 >>> set_sources_file_name("image.png", output_directory="outputs")
2228 'outputs/image_wcs/image_sources.fits'
2230 """
2231 output_directory = set_wcs_output_directory(file_name, output_directory=output_directory)
2232 tag = set_wcs_tag(file_name)
2233 return os.path.join(output_directory, f"{tag}_sources.fits")
2236def set_gaia_catalog_file_name(file_name, output_directory=""):
2237 """Returns the file name containing the Gaia catalog associated to the analyzed image,
2238 placed in the output directory. The suffix is _gaia.ecsv.
2240 Parameters
2241 ----------
2242 file_name: str
2243 File name of the image.
2244 output_directory: str, optional
2245 If not set, the main output directory is the one the image,
2246 otherwise the specified directory is taken (default: "").
2248 Returns
2249 -------
2250 sources_file_name: str
2251 The Gaia catalog file name.
2253 Examples
2254 --------
2255 >>> set_gaia_catalog_file_name("image.fits", output_directory="")
2256 'image_wcs/image_gaia.ecsv'
2257 >>> set_gaia_catalog_file_name("image.png", output_directory="outputs")
2258 'outputs/image_wcs/image_gaia.ecsv'
2260 """
2261 output_directory = set_wcs_output_directory(file_name, output_directory=output_directory)
2262 tag = set_wcs_tag(file_name)
2263 return os.path.join(output_directory, f"{tag}_gaia.ecsv")
2266def load_wcs_from_file(file_name):
2267 """Open the WCS FITS file and returns a WCS astropy object.
2269 Parameters
2270 ----------
2271 file_name: str
2272 File name of the WCS FITS file.
2274 Returns
2275 -------
2276 wcs: WCS
2277 WCS Astropy object.
2279 """
2280 # Load the FITS hdulist using astropy.io.fits
2281 hdulist = fits.open(file_name)
2282 # Parse the WCS keywords in the primary HDU
2283 with warnings.catch_warnings():
2284 warnings.filterwarnings("ignore")
2285 wcs = WCS.WCS(hdulist[0].header, fix=False)
2286 return wcs
2289def imgslice(slicespec):
2290 """
2291 Utility function: convert a FITS slice specification (1-based)
2292 into the corresponding numpy array slice spec (0-based as python does, xy swapped).
2294 Parameters
2295 ----------
2296 slicespec: str
2297 FITS slice specification with the format [xmin:xmax,ymin:ymax]
2299 Returns
2300 -------
2301 slice: slice
2302 Slice object to be injected in a np.array for instance.
2304 Examples
2305 --------
2306 >>> imgslice('[11:522,1:2002]')
2307 (slice(0, 2002, None), slice(10, 522, None))
2308 """
2310 parts = slicespec.replace('[', '').replace(']', '').split(',')
2311 xbegin, xend = [int(i) for i in parts[0].split(':')]
2312 ybegin, yend = [int(i) for i in parts[1].split(':')]
2313 xbegin -= 1
2314 ybegin -= 1
2315 return np.s_[ybegin:yend, xbegin:xend]
2318def compute_correlation_matrix(cov):
2319 rho = np.zeros_like(cov)
2320 for i in range(cov.shape[0]):
2321 for j in range(cov.shape[1]):
2322 rho[i, j] = cov[i, j] / np.sqrt(cov[i, i] * cov[j, j])
2323 return rho
2326def plot_correlation_matrix_simple(ax, rho, axis_names=None, ipar=None):
2327 if ipar is None:
2328 ipar = np.arange(rho.shape[0]).astype(int)
2329 im = plt.imshow(rho[ipar[:, None], ipar], interpolation="nearest", cmap='bwr', vmin=-1, vmax=1)
2330 ax.set_title("Correlation matrix")
2331 if axis_names is not None:
2332 names = [axis_names[ip] for ip in ipar]
2333 plt.xticks(np.arange(ipar.size), names, rotation='vertical', fontsize=11)
2334 plt.yticks(np.arange(ipar.size), names, fontsize=11)
2335 cbar = plt.colorbar(im)
2336 cbar.ax.tick_params(labelsize=9)
2337 plt.gcf().tight_layout()
2340def resolution_operator(cov, Q, reg):
2341 N = cov.shape[0]
2342 return np.eye(N) - reg * cov @ Q
2345def flip_and_rotate_radec_to_image_xy_coordinates(ra, dec, camera_angle=0, flip_ra_sign=1, flip_dec_sign=1):
2346 """Flip and rotate the vectors in pixels along (RA,DEC) directions to (x, y) image coordinates.
2347 The parity transformations are applied first, then rotation.
2349 Parameters
2350 ----------
2351 ra: array_like
2352 Vector coordinates along RA direction.
2353 dec: array_like
2354 Vector coordinates along DEC direction.
2355 camera_angle: float
2356 Angle of the camera between y axis and the North Celestial Pole counterclockwise, or equivalently between
2357 the x axis and the West direction counterclokwise. Units are degrees. (default: 0).
2358 flip_ra_sign: -1, 1, optional
2359 Flip RA axis is value is -1 (default: 1).
2360 flip_dec_sign: -1, 1, optional
2361 Flip DEC axis is value is -1 (default: 1).
2363 Returns
2364 -------
2365 x: array_like
2366 Vector coordinates along the x direction.
2367 y: array_like
2368 Vector coordinates along the y direction.
2370 Examples
2371 --------
2373 >>> from spectractor import parameters
2374 >>> parameters.OBS_CAMERA_ROTATION = 180
2375 >>> parameters.OBS_CAMERA_DEC_FLIP_SIGN = 1
2376 >>> parameters.OBS_CAMERA_RA_FLIP_SIGN = 1
2378 North vector
2380 >>> N_ra, N_dec = [0, 1]
2382 Compute North direction in (x, y) frame
2384 >>> flip_and_rotate_radec_to_image_xy_coordinates(N_ra, N_dec, 0, flip_ra_sign=1, flip_dec_sign=1)
2385 (0.0, 1.0)
2386 >>> "%.1f, %.1f" % flip_and_rotate_radec_to_image_xy_coordinates(N_ra, N_dec, 180, flip_ra_sign=1, flip_dec_sign=1)
2387 '-0.0, -1.0'
2388 >>> "%.1f, %.1f" % flip_and_rotate_radec_to_image_xy_coordinates(N_ra, N_dec, 90, flip_ra_sign=1, flip_dec_sign=1)
2389 '-1.0, 0.0'
2390 >>> "%.1f, %.1f" % flip_and_rotate_radec_to_image_xy_coordinates(N_ra, N_dec, 90, flip_ra_sign=1, flip_dec_sign=-1)
2391 '1.0, -0.0'
2392 >>> "%.1f, %.1f" % flip_and_rotate_radec_to_image_xy_coordinates(N_ra, N_dec, 90, flip_ra_sign=-1, flip_dec_sign=-1)
2393 '1.0, -0.0'
2394 >>> "%.1f, %.1f" % flip_and_rotate_radec_to_image_xy_coordinates(N_ra, N_dec, 0, flip_ra_sign=1, flip_dec_sign=-1)
2395 '0.0, -1.0'
2396 >>> "%.1f, %.1f" % flip_and_rotate_radec_to_image_xy_coordinates(N_ra, N_dec, 0, flip_ra_sign=-1, flip_dec_sign=1)
2397 '0.0, 1.0'
2399 """
2400 flip = np.array([[flip_ra_sign, 0], [0, flip_dec_sign]], dtype=float)
2401 a = - camera_angle * np.pi / 180
2402 # minus sign as rotation matrix is apply on the right on the adr vector
2403 rotation = np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]], dtype=float)
2404 transformation = flip @ rotation
2405 x, y = (np.asarray([ra, dec]).T @ transformation).T
2406 return x, y
2409if __name__ == "__main__": 2409 ↛ 2410line 2409 didn't jump to line 2410, because the condition on line 2409 was never true
2410 import doctest
2412 doctest.testmod()