Coverage for spectractor/tools.py: 11%

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

531 statements  

1import os 

2 

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 

9 

10import matplotlib.pyplot as plt 

11import matplotlib.colors 

12from matplotlib.ticker import MaxNLocator 

13 

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 

20 

21from skimage.feature import hessian_matrix 

22from spectractor.config import set_logger 

23from spectractor import parameters 

24from math import floor 

25 

26 

27def gauss(x, A, x0, sigma): 

28 """Evaluate the Gaussian function. 

29 

30 Parameters 

31 ---------- 

32 x: array_like 

33 Abscisse array to evaluate the function of size Nx. 

34 A: float 

35 Amplitude of the Gaussian function. 

36 x0: float 

37 Mean of the Gaussian function. 

38 sigma: float 

39 Standard deviation of the Gaussian function. 

40 

41 Returns 

42 ------- 

43 m: array_like 

44 The Gaussian function evaluated on the x array. 

45 

46 Examples 

47 -------- 

48 

49 >>> x = np.arange(50) 

50 >>> y = gauss(x, 10, 25, 3) 

51 >>> print(y.shape) 

52 (50,) 

53 >>> y[25] 

54 10.0 

55 """ 

56 return A * np.exp(-(x - x0) * (x - x0) / (2 * sigma * sigma)) 

57 

58 

59def gauss_jacobian(x, A, x0, sigma): 

60 """Compute the Jacobian matrix of the Gaussian function. 

61 

62 Parameters 

63 ---------- 

64 x: array_like 

65 Abscisse array to evaluate the function of size Nx. 

66 A: float 

67 Amplitude of the Gaussian function. 

68 x0: float 

69 Mean of the Gaussian function. 

70 sigma: float 

71 Standard deviation of the Gaussian function. 

72 

73 Returns 

74 ------- 

75 m: array_like 

76 The Jacobian matrix of size 3 x Nx. 

77 

78 Examples 

79 -------- 

80 

81 >>> x = np.arange(50) 

82 >>> jac = gauss_jacobian(x, 10, 25, 3) 

83 >>> print(jac.shape) 

84 (50, 3) 

85 """ 

86 dA = gauss(x, A, x0, sigma) / A 

87 dx0 = A * (x - x0) / (sigma * sigma) * dA 

88 dsigma = A * (x - x0) * (x - x0) / (sigma ** 3) * dA 

89 return np.array([dA, dx0, dsigma]).T 

90 

91 

92def line(x, a, b): 

93 return a * x + b 

94 

95 

96# noinspection PyTypeChecker 

97def fit_gauss(x, y, guess=[10, 1000, 1], bounds=(-np.inf, np.inf), sigma=None): 

98 """Fit a Gaussian profile to data, using curve_fit. The mean guess value of the Gaussian 

99 must not be far from the truth values. Boundaries helps a lot also. 

100 

101 Parameters 

102 ---------- 

103 x: np.array 

104 The x data values. 

105 y: np.array 

106 The y data values. 

107 guess: list, [amplitude, mean, sigma], optional 

108 List of first guessed values for the Gaussian fit (default: [10, 1000, 1]). 

109 bounds: list, optional 

110 List of boundaries for the parameters [[minima],[maxima]] (default: (-np.inf, np.inf)). 

111 sigma: np.array, optional 

112 The y data uncertainties. 

113 

114 Returns 

115 ------- 

116 popt: list 

117 Best fitting parameters of curve_fit. 

118 pcov: list 

119 Best fitting parameters covariance matrix from curve_fit. 

120 

121 Examples 

122 -------- 

123 

124 >>> import numpy as np 

125 >>> import matplotlib.pyplot as plt 

126 >>> x = np.arange(600.,700.,2) 

127 >>> p = [10, 650, 10] 

128 >>> y = gauss(x, *p) 

129 >>> y_err = np.ones_like(y) 

130 >>> print(y[25]) 

131 10.0 

132 >>> guess = (2,630,2) 

133 >>> popt, pcov = fit_gauss(x, y, guess=guess, bounds=((1,600,1),(100,700,100)), sigma=y_err) 

134 

135 .. doctest:: 

136 :hide: 

137 

138 >>> assert np.all(np.isclose(p,popt)) 

139 """ 

140 popt, pcov = curve_fit(gauss, x, y, p0=guess, bounds=bounds, tr_solver='exact', jac=gauss_jacobian, 

141 sigma=sigma, method='dogbox', verbose=0, xtol=1e-20, ftol=1e-20) 

142 return popt, pcov 

143 

144 

145def multigauss_and_line(x, *params): 

146 """Multiple Gaussian profile plus a straight line to data. 

147 The order of the parameters is line slope, line intercept, 

148 and then block of 3 parameters for the Gaussian profiles like amplitude, mean and standard 

149 deviation. 

150 

151 Parameters 

152 ---------- 

153 x: array 

154 The x data values. 

155 *params: list of float parameters as described above. 

156 

157 Returns 

158 ------- 

159 y: array 

160 The y profile values. 

161 

162 Examples 

163 -------- 

164 

165 >>> x = np.arange(600.,800.,1) 

166 >>> y = multigauss_and_line(x, 1, 10, 20, 650, 3, 40, 750, 10) 

167 >>> print(y[0]) 

168 610.0 

169 """ 

170 out = line(x, params[0], params[1]) 

171 for k in range((len(params) - 2) // 3): 

172 out += gauss(x, *params[2 + 3 * k:2 + 3 * k + 3]) 

173 return out 

174 

175 

176# noinspection PyTypeChecker 

177def fit_multigauss_and_line(x, y, guess=[0, 1, 10, 1000, 1, 0], bounds=(-np.inf, np.inf)): 

178 """Fit a multiple Gaussian profile plus a straight line to data, using curve_fit. 

179 The mean guess value of the Gaussian must not be far from the truth values. 

180 Boundaries helps a lot also. The order of the parameters is line slope, line intercept, 

181 and then block of 3 parameters for the Gaussian profiles like amplitude, mean and standard 

182 deviation. 

183 

184 Parameters 

185 ---------- 

186 x: array 

187 The x data values. 

188 y: array 

189 The y data values. 

190 guess: list, [slope, intercept, amplitude, mean, sigma] 

191 List of first guessed values for the Gaussian fit (default: [0, 1, 10, 1000, 1]). 

192 bounds: 2D-list 

193 List of boundaries for the parameters [[minima],[maxima]] (default: (-np.inf, np.inf)). 

194 

195 Returns 

196 ------- 

197 popt: list 

198 Best fitting parameters of curve_fit. 

199 pcov: 2D-list 

200 Best fitting parameters covariance matrix from curve_fit. 

201 

202 Examples 

203 -------- 

204 

205 >>> x = np.arange(600.,800.,1) 

206 >>> y = multigauss_and_line(x, 1, 10, 20, 650, 3, 40, 750, 10) 

207 >>> print(y[0]) 

208 610.0 

209 >>> bounds = ((-np.inf,-np.inf,1,600,1,1,600,1),(np.inf,np.inf,100,800,100,100,800,100)) 

210 >>> popt, pcov = fit_multigauss_and_line(x, y, guess=(0,1,3,630,3,3,770,3), bounds=bounds) 

211 >>> print(popt) 

212 [ 1. 10. 20. 650. 3. 40. 750. 10.] 

213 """ 

214 maxfev = 1000 

215 popt, pcov = curve_fit(multigauss_and_line, x, y, p0=guess, bounds=bounds, maxfev=maxfev, absolute_sigma=True) 

216 return popt, pcov 

217 

218 

219def rescale_x_for_legendre(x): 

220 middle = 0.5 * (np.max(x) + np.min(x)) 

221 x_norm = x - middle 

222 if np.max(x_norm) != 0: 

223 return x_norm / np.max(x_norm) 

224 else: 

225 return x_norm 

226 

227 

228# noinspection PyTypeChecker 

229def multigauss_and_bgd(x, *params): 

230 """Multiple Gaussian profile plus a polynomial background to data. 

231 Polynomial function is based on the orthogonal Legendre polynomial basis. 

232 The degree of the polynomial background is fixed by parameters.CALIB_BGD_NPARAMS. 

233 The order of the parameters is a first block CALIB_BGD_NPARAMS parameters (from low to high Legendre polynome degree, 

234 contrary to np.polyval), and then block of 3 parameters for the Gaussian profiles like amplitude, mean and standard 

235 deviation. 

236 

237 Parameters 

238 ---------- 

239 x: array 

240 The x data values. 

241 *params: list of float parameters as described above. 

242 

243 Returns 

244 ------- 

245 y: array 

246 The y profile values. 

247 

248 Examples 

249 -------- 

250 >>> parameters.CALIB_BGD_NPARAMS = 4 

251 >>> x = np.arange(600., 800., 1) 

252 >>> p = [20, 1, -1, -1, 20, 650, 3, 40, 750, 5] 

253 >>> y = multigauss_and_bgd(x, *p) 

254 >>> print(f'{y[0]:.2f}') 

255 19.00 

256 

257 .. plot:: 

258 

259 from spectractor import parameters 

260 from spectractor.tools import multigauss_and_bgd 

261 import numpy as np 

262 parameters.CALIB_BGD_NPARAMS = 4 

263 x = np.arange(600., 800., 1) 

264 p = [20, 1, -1, -1, 20, 650, 3, 40, 750, 5] 

265 y = multigauss_and_bgd(x, *p) 

266 plt.plot(x,y,'r-') 

267 plt.show() 

268 

269 """ 

270 bgd_nparams = parameters.CALIB_BGD_NPARAMS 

271 # out = np.polyval(params[0:bgd_nparams], x) 

272 x_norm = rescale_x_for_legendre(x) 

273 out = np.polynomial.legendre.legval(x_norm, params[0:bgd_nparams]) 

274 for k in range((len(params) - bgd_nparams) // 3): 

275 out += gauss(x, *params[bgd_nparams + 3 * k:bgd_nparams + 3 * k + 3]) 

276 return out 

277 

278 

279# noinspection PyTypeChecker 

280def multigauss_and_bgd_jacobian(x, *params): 

281 """Jacobien of the multiple Gaussian profile plus a polynomial background to data. 

282 The degree of the polynomial background is fixed by parameters.CALIB_BGD_NPARAMS. 

283 The order of the parameters is a first block CALIB_BGD_NPARAMS parameters (from low to high Legendre polynome degree, 

284 contrary to np.polyval), and then block of 3 parameters for the Gaussian profiles like amplitude, mean and standard 

285 deviation. x values are renormalised on the [-1, 1] interval for the background. 

286 

287 Parameters 

288 ---------- 

289 x: array 

290 The x data values. 

291 *params: list of float parameters as described above. 

292 

293 Returns 

294 ------- 

295 y: array 

296 The jacobian values. 

297 

298 Examples 

299 -------- 

300 

301 >>> import spectractor.parameters as parameters 

302 >>> parameters.CALIB_BGD_NPARAMS = 4 

303 >>> x = np.arange(600.,800.,1) 

304 >>> p = [20, 1, -1, -1, 20, 650, 3, 40, 750, 5] 

305 >>> y = multigauss_and_bgd_jacobian(x, *p) 

306 >>> assert(np.all(np.isclose(y.T[0],np.ones_like(x)))) 

307 >>> print(y.shape) 

308 (200, 10) 

309 """ 

310 bgd_nparams = parameters.CALIB_BGD_NPARAMS 

311 out = [] 

312 x_norm = rescale_x_for_legendre(x) 

313 for k in range(bgd_nparams): 

314 # out.append(params[k]*(parameters.CALIB_BGD_ORDER-k)*x**(parameters.CALIB_BGD_ORDER-(k+1))) 

315 # out.append(x ** (bgd_nparams - 1 - k)) 

316 c = np.zeros(bgd_nparams) 

317 c[k] = 1 

318 out.append(np.polynomial.legendre.legval(x_norm, c)) 

319 for k in range((len(params) - bgd_nparams) // 3): 

320 jac = gauss_jacobian(x, *params[bgd_nparams + 3 * k:bgd_nparams + 3 * k + 3]).T 

321 for j in jac: 

322 out.append(list(j)) 

323 return np.array(out).T 

324 

325 

326# noinspection PyTypeChecker 

327def fit_multigauss_and_bgd(x, y, guess=[0, 1, 10, 1000, 1, 0], bounds=(-np.inf, np.inf), sigma=None, 

328 fix_centroids=False): 

329 """Fit a multiple Gaussian profile plus a polynomial background to data, using iminuit. 

330 The mean guess value of the Gaussian must not be far from the truth values. 

331 Boundaries helps a lot also. The degree of the polynomial background is fixed by parameters.CALIB_BGD_NPARAMS. 

332 The order of the parameters is a first block CALIB_BGD_NPARAMS parameters (from high to low monomial terms, 

333 same as np.polyval), and then block of 3 parameters for the Gaussian profiles like amplitude, mean and standard 

334 deviation. x values are renormalised on the [-1, 1] interval for the background. 

335 

336 Parameters 

337 ---------- 

338 x: array 

339 The x data values. 

340 y: array 

341 The y data values. 

342 guess: list, [CALIB_BGD_ORDER+1 parameters, 3*number of Gaussian parameters] 

343 List of first guessed values for the Gaussian fit (default: [0, 1, 10, 1000, 1]). 

344 bounds: array 

345 List of boundaries for the parameters [[minima],[maxima]] (default: (-np.inf, np.inf)). 

346 sigma: array, optional 

347 The uncertainties on the y values (default: None). 

348 

349 Returns 

350 ------- 

351 popt: array 

352 Best fitting parameters of curve_fit. 

353 pcov: array 

354 Best fitting parameters covariance matrix from curve_fit. 

355 

356 Examples 

357 -------- 

358 

359 >>> x = np.arange(600.,800.,1) 

360 >>> p = [20, 1, -1, -1, 20, 650, 3, 40, 750, 5] 

361 >>> y = multigauss_and_bgd(x, *p) 

362 >>> print(f'{y[0]:.2f}') 

363 19.00 

364 >>> err = 0.1 * np.sqrt(y) 

365 >>> guess = (15,0,0,0,10,640,2,20,750,7) 

366 >>> 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)) 

367 >>> popt, pcov = fit_multigauss_and_bgd(x, y, guess=guess, bounds=bounds, sigma=err) 

368 >>> assert np.all(np.isclose(p,popt,rtol=1e-4)) 

369 >>> fit = multigauss_and_bgd(x, *popt) 

370 

371 .. plot:: 

372 

373 import matplotlib.pyplot as plt 

374 import numpy as np 

375 from spectractor.tools import multigauss_and_bgd, fit_multigauss_and_bgd 

376 x = np.arange(600.,800.,1) 

377 p = [20, 1, -1, -1, 20, 650, 3, 40, 750, 5] 

378 y = multigauss_and_bgd(x, *p) 

379 err = 0.1 * np.sqrt(y) 

380 guess = (15,0,0,0,10,640,2,20,750,7) 

381 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)) 

382 popt, pcov = fit_multigauss_and_bgd(x, y, guess=guess, bounds=bounds, sigma=err) 

383 fit = multigauss_and_bgd(x, *popt) 

384 fig = plt.figure() 

385 plt.errorbar(x,y,yerr=err,linestyle='None') 

386 plt.plot(x,fit,'r-') 

387 plt.plot(x,multigauss_and_bgd(x, *guess),'k--') 

388 plt.show() 

389 """ 

390 maxfev = 10000 

391 popt, pcov = curve_fit(multigauss_and_bgd, x, y, p0=guess, bounds=bounds, maxfev=maxfev, sigma=sigma, 

392 absolute_sigma=True, method='trf', xtol=1e-4, ftol=1e-4, verbose=0, 

393 jac=multigauss_and_bgd_jacobian, x_scale='jac') 

394 # error = 0.1 * np.abs(guess) * np.ones_like(guess) 

395 # z = np.where(np.isclose(error,0.0,1e-6)) 

396 # error[z] = 0.01 

397 # bounds = np.array(bounds) 

398 # if bounds.shape[0] == 2 and bounds.shape[1] > 2: 

399 # bounds = bounds.T 

400 # guess = np.array(guess) 

401 # 

402 # def chisq_multigauss_and_bgd(params): 

403 # if sigma is None: 

404 # return np.nansum((multigauss_and_bgd(x, *params) - y)**2) 

405 # else: 

406 # return np.nansum(((multigauss_and_bgd(x, *params) - y)/sigma)**2) 

407 # 

408 # def chisq_multigauss_and_bgd_jac(params): 

409 # diff = multigauss_and_bgd(x, *params) - y 

410 # jac = multigauss_and_bgd_jacobian(x, *params) 

411 # if sigma is None: 

412 # return np.array([np.nansum(2 * jac[p] * diff) for p in range(len(params))]) 

413 # else: 

414 # return np.array([np.nansum(2 * jac[p] * diff / (sigma*sigma)) for p in range(len(params))]) 

415 # 

416 # fix = [False] * error.size 

417 # if fix_centroids: 

418 # for k in range(parameters.CALIB_BGD_NPARAMS, len(fix), 3): 

419 # fix[k+1] = True 

420 # # noinspection PyArgumentList 

421 # m = Minuit.from_array_func(fcn=chisq_multigauss_and_bgd, start=guess, error=error, errordef=1, 

422 # fix=fix, print_level=0, limit=bounds, grad=chisq_multigauss_and_bgd_jac) 

423 # 

424 # m.tol = 0.001 

425 # m.migrad() 

426 # try: 

427 # pcov = m.np_covariance() 

428 # except: 

429 # pcov = None 

430 # popt = m.np_values() 

431 return popt, pcov 

432 

433 

434# noinspection PyTupleAssignmentBalance 

435def fit_poly1d(x, y, order, w=None): 

436 """Fit a 1D polynomial function to data. Use np.polyfit. 

437 

438 Parameters 

439 ---------- 

440 x: array 

441 The x data values. 

442 y: array 

443 The y data values. 

444 order: int 

445 The degree of the polynomial function. 

446 w: array, optional 

447 Weights on the y data (default: None). 

448 

449 Returns 

450 ------- 

451 fit: array 

452 The best fitting parameter values. 

453 cov: 2D-array 

454 The covariance matrix 

455 model: array 

456 The best fitting profile 

457 

458 Examples 

459 -------- 

460 

461 >>> x = np.arange(500., 1000., 1) 

462 >>> p = [3, 2, 1, 1] 

463 >>> y = np.polyval(p, x) 

464 >>> err = np.ones_like(y) 

465 >>> fit, cov, model = fit_poly1d(x, y, order=3) 

466 

467 .. doctest:: 

468 :hide: 

469 

470 >>> assert np.all(np.isclose(p, fit, 1e-5)) 

471 >>> assert np.all(np.isclose(model, y)) 

472 >>> assert cov.shape == (4, 4) 

473 

474 With uncertainties: 

475 

476 >>> fit, cov2, model2 = fit_poly1d(x, y, order=3, w=err) 

477 

478 .. doctest:: 

479 :hide: 

480 

481 >>> assert np.all(np.isclose(p, fit, 1e-5)) 

482 

483 >>> fit, cov3, model3 = fit_poly1d([0, 1], [1, 1], order=3, w=err) 

484 >>> print(fit) 

485 [0 0 0 0] 

486 """ 

487 cov = np.array([]) 

488 if len(x) > order: 

489 if w is None: 

490 fit, cov = np.polyfit(x, y, order, cov=True) 

491 else: 

492 fit, cov = np.polyfit(x, y, order, cov=True, w=w) 

493 model = np.polyval(fit, x) 

494 else: 

495 fit = np.array([0] * (order + 1)) 

496 model = y 

497 return fit, cov, model 

498 

499 

500# noinspection PyTupleAssignmentBalance 

501def fit_poly1d_legendre(x, y, order, w=None): 

502 """Fit a 1D polynomial function to data using Legendre polynomial orthogonal basis. 

503 

504 Parameters 

505 ---------- 

506 x: array 

507 The x data values. 

508 y: array 

509 The y data values. 

510 order: int 

511 The degree of the polynomial function. 

512 w: array, optional 

513 Weights on the y data (default: None). 

514 

515 Returns 

516 ------- 

517 fit: array 

518 The best fitting parameter values. 

519 cov: 2D-array 

520 The covariance matrix 

521 model: array 

522 The best fitting profile 

523 

524 Examples 

525 -------- 

526 

527 >>> x = np.arange(500., 1000., 1) 

528 >>> p = [-1e-6, -1e-4, 1, 1] 

529 >>> y = np.polyval(p, x) 

530 >>> err = np.ones_like(y) 

531 >>> fit, cov, model = fit_poly1d_legendre(x,y,order=3) 

532 >>> assert np.all(np.isclose(p,fit,3)) 

533 >>> fit, cov2, model2 = fit_poly1d_legendre(x,y,order=3,w=err) 

534 >>> assert np.all(np.isclose(p,fit,3)) 

535 >>> fit, cov3, model3 = fit_poly1d([0, 1], [1, 1], order=3, w=err) 

536 >>> print(fit) 

537 [0 0 0 0] 

538 

539 .. plot:: 

540 

541 import matplotlib.pyplot as plt 

542 import numpy as np 

543 from spectractor.tools import fit_poly1d_legendre 

544 p = [-1e-6, -1e-4, 1, 1] 

545 x = np.arange(500., 1000., 1) 

546 y = np.polyval(p, x) 

547 err = np.ones_like(y) 

548 fit, cov2, model2 = fit_poly1d_legendre(x,y,order=3,w=err) 

549 plt.errorbar(x,y,yerr=err,fmt='ro') 

550 plt.plot(x,model2) 

551 plt.show() 

552 """ 

553 cov = -1 

554 x_norm = rescale_x_for_legendre(x) 

555 if len(x) > order: 

556 fit, cov = np.polynomial.legendre.legfit(x_norm, y, deg=order, full=True, w=w) 

557 model = np.polynomial.legendre.legval(x_norm, fit) 

558 else: 

559 fit = np.array([0] * (order + 1)) 

560 model = y 

561 return fit, cov, model 

562 

563 

564# noinspection PyTypeChecker,PyUnresolvedReferences 

565def fit_poly2d(x, y, z, order): 

566 """Fit a 2D polynomial function to data. Use astropy.modeling. 

567 

568 Parameters 

569 ---------- 

570 x: array 

571 The x data values. 

572 y: array 

573 The y data values. 

574 z: array 

575 The z data values. 

576 order: int 

577 The degree of the polynomial function. 

578 

579 Returns 

580 ------- 

581 model: Astropy model 

582 The best fitting astropy polynomial model 

583 

584 Examples 

585 -------- 

586 

587 >>> x, y = np.mgrid[:50,:50] 

588 >>> z = x**2 + y**2 - 2*x*y 

589 >>> fit = fit_poly2d(x, y, z, order=2) 

590 

591 .. doctest:: 

592 :hide: 

593 

594 >>> assert np.isclose(fit.c0_0.value, 0) 

595 >>> assert np.isclose(fit.c1_0.value, 0) 

596 >>> assert np.isclose(fit.c2_0.value, 1) 

597 >>> assert np.isclose(fit.c0_1.value, 0) 

598 >>> assert np.isclose(fit.c0_2.value, 1) 

599 >>> assert np.isclose(fit.c1_1.value, -2) 

600 """ 

601 p_init = models.Polynomial2D(degree=order) 

602 fit_p = fitting.LevMarLSQFitter() 

603 with warnings.catch_warnings(): 

604 # Ignore model linearity warning from the fitter 

605 warnings.simplefilter('ignore') 

606 p = fit_p(p_init, x, y, z) 

607 return p 

608 

609 

610def fit_poly1d_outlier_removal(x, y, order=2, sigma=3.0, niter=3): 

611 """Fit a 1D polynomial function to data. Use astropy.modeling. 

612 

613 Parameters 

614 ---------- 

615 x: array 

616 The x data values. 

617 y: array 

618 The y data values. 

619 order: int 

620 The degree of the polynomial function (default: 2). 

621 sigma: float 

622 Value of the sigma-clipping (default: 3.0). 

623 niter: int 

624 The number of iterations to converge (default: 3). 

625 

626 Returns 

627 ------- 

628 model: Astropy model 

629 The best fitting astropy model. 

630 outliers: array_like 

631 List of the outlier points. 

632 

633 Examples 

634 -------- 

635 

636 >>> x = np.arange(500., 1000., 1) 

637 >>> p = [3,2,1,0] 

638 >>> y = np.polyval(p, x) 

639 >>> y[::10] = 0. 

640 >>> model, outliers = fit_poly1d_outlier_removal(x,y,order=3,sigma=3) 

641 >>> print('{:.2f}'.format(model.c0.value)) 

642 0.00 

643 >>> print('{:.2f}'.format(model.c1.value)) 

644 1.00 

645 >>> print('{:.2f}'.format(model.c2.value)) 

646 2.00 

647 >>> print('{:.2f}'.format(model.c3.value)) 

648 3.00 

649 

650 """ 

651 gg_init = models.Polynomial1D(order) 

652 gg_init.c1 = 0 

653 gg_init.c2 = 0 

654 fit = fitting.LinearLSQFitter() 

655 or_fit = fitting.FittingWithOutlierRemoval(fit, sigma_clip, niter=niter, sigma=sigma) 

656 # get fitted model and filtered data 

657 or_fitted_model, filtered_data = or_fit(gg_init, x, y) 

658 outliers = [] # not working 

659 """ 

660 import matplotlib.pyplot as plt 

661 plt.figure(figsize=(8,5)) 

662 plt.plot(x, y, 'gx', label="original data") 

663 plt.plot(x, gg_init(x), 'k.', label="guess") 

664 plt.plot(x, filtered_data, 'r+', label="filtered data") 

665 plt.plot(x, or_fitted_model(x), 'r--', 

666 label="model fitted w/ filtered data") 

667 plt.legend(loc=2, numpoints=1) 

668 if parameters.DISPLAY: plt.show() 

669 """ 

670 return or_fitted_model, outliers 

671 

672 

673def fit_poly2d_outlier_removal(x, y, z, order=2, sigma=3.0, niter=30): 

674 """Fit a 2D polynomial function to data. Use astropy.modeling. 

675 

676 Parameters 

677 ---------- 

678 x: array 

679 The x data values. 

680 y: array 

681 The y data values. 

682 z: array 

683 The z data values. 

684 order: int 

685 The degree of the polynomial function (default: 2). 

686 sigma: float 

687 Value of the sigma-clipping (default: 3.0). 

688 niter: int 

689 The number of iterations to converge (default: 30). 

690 

691 Returns 

692 ------- 

693 model: Astropy model 

694 The best fitting astropy model. 

695 

696 Examples 

697 -------- 

698 

699 >>> x, y = np.mgrid[:50,:50] 

700 >>> z = x**2 + y**2 - 2*x*y 

701 >>> z[::10,::10] = 0. 

702 >>> fit = fit_poly2d_outlier_removal(x,y,z,order=2,sigma=3) 

703 

704 .. doctest:: 

705 :hide: 

706 

707 >>> assert np.isclose(fit.c0_0.value, 0) 

708 >>> assert np.isclose(fit.c1_0.value, 0) 

709 >>> assert np.isclose(fit.c2_0.value, 1) 

710 >>> assert np.isclose(fit.c0_1.value, 0) 

711 >>> assert np.isclose(fit.c0_2.value, 1) 

712 >>> assert np.isclose(fit.c1_1.value, -2) 

713 

714 """ 

715 my_logger = set_logger(__name__) 

716 gg_init = models.Polynomial2D(order) 

717 fit = fitting.LinearLSQFitter() 

718 or_fit = fitting.FittingWithOutlierRemoval(fit, sigma_clip, niter=niter, sigma=sigma) 

719 # get fitted model and filtered data 

720 or_fitted_model, filtered_data = or_fit(gg_init, x, y, z) 

721 my_logger.info(f'\n\t{or_fitted_model}') 

722 # my_logger.debug(f'\n\t{fit.fit_info}') 

723 return or_fitted_model 

724 

725 

726def tied_circular_gauss2d(g1): 

727 std = g1.x_stddev 

728 return std 

729 

730 

731def fit_gauss2d_outlier_removal(x, y, z, sigma=3.0, niter=3, guess=None, bounds=None, circular=False): 

732 """ 

733 Fit an astropy Gaussian 2D model with parameters : amplitude, x_mean, y_mean, x_stddev, y_stddev, theta 

734 using outlier removal methods. 

735 

736 Parameters 

737 ---------- 

738 x: np.array 

739 2D array of the x coordinates from meshgrid. 

740 y: np.array 

741 2D array of the y coordinates from meshgrid. 

742 z: np.array 

743 the 2D array image. 

744 sigma: float 

745 value of sigma for the sigma rejection of outliers (default: 3) 

746 niter: int 

747 maximum number of iterations for the outlier detection (default: 3) 

748 guess: list, optional 

749 List containing a first guess for the PSF parameters (default: None). 

750 bounds: list, optional 

751 2D list containing bounds for the PSF parameters with format ((min,...), (max...)) (default: None) 

752 circular: bool, optional 

753 If True, force the Gaussian shape to be circular (default: False) 

754 

755 Returns 

756 ------- 

757 fitted_model: Fittable 

758 Astropy Gaussian2D model 

759 

760 Examples 

761 -------- 

762 

763 >>> import numpy as np 

764 >>> import matplotlib.pyplot as plt 

765 >>> from astropy.modeling import models 

766 >>> X, Y = np.mgrid[:50,:50] 

767 >>> PSF = models.Gaussian2D() 

768 >>> p = (50, 25, 25, 5, 5, 0) 

769 >>> Z = PSF.evaluate(X, Y, *p) 

770 

771 .. plot:: 

772 

773 import numpy as np 

774 import matplotlib.pyplot as plt 

775 from astropy.modeling import models 

776 X, Y = np.mgrid[:50,:50] 

777 PSF = models.Gaussian2D() 

778 p = (50, 25, 25, 5, 5, 0) 

779 Z = PSF.evaluate(X, Y, *p) 

780 plt.imshow(Z, origin='lower') 

781 plt.show() 

782 

783 >>> guess = (45, 20, 20, 7, 7, 0) 

784 >>> bounds = ((1, 10, 10, 1, 1, -90), (100, 40, 40, 10, 10, 90)) 

785 >>> fit = fit_gauss2d_outlier_removal(X, Y, Z, guess=guess, bounds=bounds, circular=True) 

786 >>> res = [getattr(fit, p).value for p in fit.param_names] 

787 >>> print(res) 

788 [50.0, 25.0, 25.0, 5.0, 5.0, 0.0] 

789 

790 .. plot:: 

791 

792 import numpy as np 

793 import matplotlib.pyplot as plt 

794 from astropy.modeling import models 

795 from spectractor.tools import fit_gauss2d_outlier_removal 

796 X, Y = np.mgrid[:50,:50] 

797 PSF = models.Gaussian2D() 

798 p = (50, 25, 25, 5, 5, 0) 

799 Z = PSF.evaluate(X, Y, *p) 

800 guess = (45, 20, 20, 7, 7, 0) 

801 bounds = ((1, 10, 10, 1, 1, -90), (100, 40, 40, 10, 10, 90)) 

802 fit = fit_gauss2d_outlier_removal(X, Y, Z, guess=guess, bounds=bounds, circular=True) 

803 plt.imshow(Z-fit(X, Y), origin='lower') 

804 plt.show() 

805 

806 """ 

807 my_logger = set_logger(__name__) 

808 gg_init = models.Gaussian2D() 

809 if guess is not None: 

810 for ip, p in enumerate(gg_init.param_names): 

811 getattr(gg_init, p).value = guess[ip] 

812 if bounds is not None: 

813 for ip, p in enumerate(gg_init.param_names): 

814 getattr(gg_init, p).min = bounds[0][ip] 

815 getattr(gg_init, p).max = bounds[1][ip] 

816 if circular: 

817 gg_init.y_stddev.tied = tied_circular_gauss2d 

818 gg_init.theta.fixed = True 

819 with warnings.catch_warnings(): 

820 # Ignore model linearity warning from the fitter 

821 warnings.simplefilter('ignore') 

822 fit = fitting.LevMarLSQFitter() 

823 or_fit = fitting.FittingWithOutlierRemoval(fit, sigma_clip, niter=niter, sigma=sigma) 

824 # get fitted model and filtered data 

825 or_fitted_model, filtered_data = or_fit(gg_init, x, y, z) 

826 my_logger.info(f'\n\t{or_fitted_model}') 

827 # my_logger.debug(f'\n\t{fit.fit_info}') 

828 return or_fitted_model 

829 

830 

831def fit_moffat2d_outlier_removal(x, y, z, sigma=3.0, niter=3, guess=None, bounds=None): 

832 """ 

833 Fit an astropy Moffat 2D model with parameters: amplitude, x_mean, y_mean, gamma, alpha 

834 using outlier removal methods. 

835 

836 Parameters 

837 ---------- 

838 x: np.array 

839 2D array of the x coordinates from meshgrid. 

840 y: np.array 

841 2D array of the y coordinates from meshgrid. 

842 z: np.array 

843 the 2D array image. 

844 sigma: float 

845 value of sigma for the sigma rejection of outliers (default: 3) 

846 niter: int 

847 maximum number of iterations for the outlier detection (default: 3) 

848 guess: list, optional 

849 List containing a first guess for the PSF parameters (default: None). 

850 bounds: list, optional 

851 2D list containing bounds for the PSF parameters with format ((min,...), (max...)) (default: None) 

852 

853 Returns 

854 ------- 

855 fitted_model: Fittable 

856 Astropy Moffat2D model 

857 

858 Examples 

859 -------- 

860 

861 >>> import numpy as np 

862 >>> import matplotlib.pyplot as plt 

863 >>> from astropy.modeling import models 

864 >>> X, Y = np.mgrid[:100,:100] 

865 >>> PSF = models.Moffat2D() 

866 >>> p = (50, 50, 50, 5, 2) 

867 >>> Z = PSF.evaluate(X, Y, *p) 

868 

869 .. plot:: 

870 

871 import numpy as np 

872 import matplotlib.pyplot as plt 

873 from astropy.modeling import models 

874 X, Y = np.mgrid[:100,:100] 

875 PSF = models.Moffat2D() 

876 p = (50, 50, 50, 5, 2) 

877 Z = PSF.evaluate(X, Y, *p) 

878 plt.imshow(Z, origin='loxer') 

879 plt.show() 

880 

881 >>> guess = (45, 48, 52, 4, 2) 

882 >>> bounds = ((1, 10, 10, 1, 1), (100, 90, 90, 10, 10)) 

883 >>> fit = fit_moffat2d_outlier_removal(X, Y, Z, guess=guess, bounds=bounds, niter=3) 

884 >>> res = [getattr(fit, p).value for p in fit.param_names] 

885 

886 .. doctest:: 

887 :hide: 

888 

889 >>> assert(np.all(np.isclose(p, res, 1e-1))) 

890 

891 .. plot:: 

892 

893 import numpy as np 

894 import matplotlib.pyplot as plt 

895 from astropy.modeling import models 

896 from spectractor.tools import fit_moffat2d_outlier_removal 

897 X, Y = np.mgrid[:100,:100] 

898 PSF = models.Moffat2D() 

899 p = (50, 50, 50, 5, 2) 

900 Z = PSF.evaluate(X, Y, *p) 

901 guess = (45, 48, 52, 4, 2) 

902 bounds = ((1, 10, 10, 1, 1), (100, 90, 90, 10, 10)) 

903 fit = fit_moffat2d_outlier_removal(X, Y, Z, guess=guess, bounds=bounds, niter=3) 

904 plt.imshow(Z-fit(X, Y), origin='loxer') 

905 plt.show() 

906 """ 

907 my_logger = set_logger(__name__) 

908 gg_init = models.Moffat2D() 

909 if guess is not None: 

910 for ip, p in enumerate(gg_init.param_names): 

911 getattr(gg_init, p).value = guess[ip] 

912 if bounds is not None: 

913 for ip, p in enumerate(gg_init.param_names): 

914 getattr(gg_init, p).min = bounds[0][ip] 

915 getattr(gg_init, p).max = bounds[1][ip] 

916 with warnings.catch_warnings(): 

917 # Ignore model linearity warning from the fitter 

918 warnings.simplefilter('ignore') 

919 fit = fitting.LevMarLSQFitter() 

920 or_fit = fitting.FittingWithOutlierRemoval(fit, sigma_clip, niter=niter, sigma=sigma) 

921 # get fitted model and filtered data 

922 or_fitted_model, filtered_data = or_fit(gg_init, x, y, z) 

923 my_logger.info(f'\n\t{or_fitted_model}') 

924 # my_logger.debug(f'\n\t{fit.fit_info}') 

925 return or_fitted_model 

926 

927 

928def fit_moffat1d_outlier_removal(x, y, sigma=3.0, niter=3, guess=None, bounds=None): 

929 """ 

930 Fit an astropy Moffat 1D model with parameters: amplitude, x_mean, gamma, alpha 

931 using outlier removal methods. 

932 

933 Parameters 

934 ---------- 

935 x: np.array 

936 1D array of the x coordinates from meshgrid. 

937 y: np.array 

938 the 1D array amplitudes. 

939 sigma: float 

940 value of sigma for the sigma rejection of outliers (default: 3) 

941 niter: int 

942 maximum number of iterations for the outlier detection (default: 3) 

943 guess: list, optional 

944 List containing a first guess for the PSF parameters (default: None). 

945 bounds: list, optional 

946 2D list containing bounds for the PSF parameters with format ((min,...), (max...)) (default: None) 

947 

948 Returns 

949 ------- 

950 fitted_model: Fittable 

951 Astropy Moffat1D model 

952 

953 Examples 

954 -------- 

955 

956 >>> import numpy as np 

957 >>> import matplotlib.pyplot as plt 

958 >>> from astropy.modeling import models 

959 >>> X = np.arange(100) 

960 >>> PSF = models.Moffat1D() 

961 >>> p = (50, 50, 5, 2) 

962 >>> Y = PSF.evaluate(X, *p) 

963 

964 .. plot:: 

965 

966 import numpy as np 

967 import matplotlib.pyplot as plt 

968 from astropy.modeling import models 

969 X = np.arange(100) 

970 PSF = models.Moffat1D() 

971 p = (50, 50, 5, 2) 

972 Y = PSF.evaluate(X, *p) 

973 plt.plot(X, Y) 

974 plt.show() 

975 

976 >>> guess = (45, 48, 4, 2) 

977 >>> bounds = ((1, 10, 1, 1), (100, 90, 10, 10)) 

978 >>> fit = fit_moffat1d_outlier_removal(X, Y, guess=guess, bounds=bounds, niter=3) 

979 >>> res = [getattr(fit, p).value for p in fit.param_names] 

980 

981 .. doctest:: 

982 :hide: 

983 

984 >>> assert(np.all(np.isclose(p, res, 1e-6))) 

985 

986 .. plot:: 

987 

988 import numpy as np 

989 import matplotlib.pyplot as plt 

990 from astropy.modeling import models 

991 from spectractor.tools import fit_moffat1d_outlier_removal 

992 X = np.arange(100) 

993 PSF = models.Moffat1D() 

994 p = (50, 50, 5, 2) 

995 Y = PSF.evaluate(X, *p) 

996 guess = (45, 48, 4, 2) 

997 bounds = ((1, 10, 1, 1), (100, 90, 10, 10)) 

998 fit = fit_moffat1d_outlier_removal(X, Y, guess=guess, bounds=bounds, niter=3) 

999 plt.plot(X, Y-fit(X)) 

1000 plt.show() 

1001 """ 

1002 my_logger = set_logger(__name__) 

1003 gg_init = models.Moffat1D() 

1004 if guess is not None: 

1005 for ip, p in enumerate(gg_init.param_names): 

1006 getattr(gg_init, p).value = guess[ip] 

1007 if bounds is not None: 

1008 for ip, p in enumerate(gg_init.param_names): 

1009 getattr(gg_init, p).min = bounds[0][ip] 

1010 getattr(gg_init, p).max = bounds[1][ip] 

1011 with warnings.catch_warnings(): 

1012 # Ignore model linearity warning from the fitter 

1013 warnings.simplefilter('ignore') 

1014 fit = fitting.LevMarLSQFitter() 

1015 or_fit = fitting.FittingWithOutlierRemoval(fit, sigma_clip, niter=niter, sigma=sigma) 

1016 # get fitted model and filtered data 

1017 or_fitted_model, filtered_data = or_fit(gg_init, x, y) 

1018 my_logger.debug(f'\n\t{or_fitted_model}') 

1019 # my_logger.debug(f'\n\t{fit.fit_info}') 

1020 return or_fitted_model 

1021 

1022 

1023def fit_moffat1d(x, y, guess=None, bounds=None): 

1024 """Fit an astropy Moffat 1D model with parameters : 

1025 amplitude, x_mean, gamma, alpha 

1026 

1027 Parameters 

1028 ---------- 

1029 x: np.array 

1030 1D array of the x coordinates from meshgrid. 

1031 y: np.array 

1032 the 1D array amplitudes. 

1033 guess: list, optional 

1034 List containing a first guess for the PSF parameters (default: None). 

1035 bounds: list, optional 

1036 2D list containing bounds for the PSF parameters with format ((min,...), (max...)) (default: None) 

1037 

1038 Returns 

1039 ------- 

1040 fitted_model: Fittable 

1041 Astropy Moffat1D model 

1042 

1043 Examples 

1044 -------- 

1045 

1046 >>> import numpy as np 

1047 >>> import matplotlib.pyplot as plt 

1048 >>> from astropy.modeling import models 

1049 >>> X = np.arange(100) 

1050 >>> PSF = models.Moffat1D() 

1051 >>> p = (50, 50, 5, 2) 

1052 >>> Y = PSF.evaluate(X, *p) 

1053 

1054 .. plot:: 

1055 

1056 import numpy as np 

1057 import matplotlib.pyplot as plt 

1058 from astropy.modeling import models 

1059 X = np.arange(100) 

1060 PSF = models.Moffat1D() 

1061 p = (50, 50, 5, 2) 

1062 Y = PSF.evaluate(X, *p) 

1063 plt.plot(X, Y) 

1064 plt.show() 

1065 

1066 >>> guess = (45, 48, 4, 2) 

1067 >>> bounds = ((1, 10, 1, 1), (100, 90, 10, 10)) 

1068 >>> fit = fit_moffat1d(X, Y, guess=guess, bounds=bounds) 

1069 >>> res = [getattr(fit, p).value for p in fit.param_names] 

1070 >>> assert(np.all(np.isclose(p, res, 1e-6))) 

1071 

1072 .. plot:: 

1073 

1074 import numpy as np 

1075 import matplotlib.pyplot as plt 

1076 from astropy.modeling import models 

1077 from spectractor.tools import fit_moffat1d 

1078 X = np.arange(100) 

1079 PSF = models.Moffat1D() 

1080 p = (50, 50, 5, 2) 

1081 Y = PSF.evaluate(X, *p) 

1082 guess = (45, 48, 4, 2) 

1083 bounds = ((1, 10, 1, 1), (100, 90, 10, 10)) 

1084 fit = fit_moffat1d(X, Y, guess=guess, bounds=bounds) 

1085 plt.plot(X, Y-fit(X)) 

1086 plt.show() 

1087 """ 

1088 my_logger = set_logger(__name__) 

1089 gg_init = models.Moffat1D() 

1090 if guess is not None: 

1091 for ip, p in enumerate(gg_init.param_names): 

1092 getattr(gg_init, p).value = guess[ip] 

1093 if bounds is not None: 

1094 for ip, p in enumerate(gg_init.param_names): 

1095 getattr(gg_init, p).min = bounds[0][ip] 

1096 getattr(gg_init, p).max = bounds[1][ip] 

1097 with warnings.catch_warnings(): 

1098 # Ignore model linearity warning from the fitter 

1099 warnings.simplefilter('ignore') 

1100 fit = fitting.LevMarLSQFitter() 

1101 fitted_model = fit(gg_init, x, y) 

1102 my_logger.info(f'\n\t{fitted_model}') 

1103 # my_logger.debug(f'\n\t{fit.fit_info}') 

1104 return fitted_model 

1105 

1106 

1107class LevMarLSQFitterWithNan(fitting.LevMarLSQFitter): 

1108 

1109 def objective_function(self, fps, *args): 

1110 """ 

1111 Function to minimize. 

1112 

1113 Parameters 

1114 ---------- 

1115 fps : list 

1116 parameters returned by the fitter 

1117 args : list 

1118 [model, [weights], [input coordinates]] 

1119 """ 

1120 

1121 model = args[0] 

1122 weights = args[1] 

1123 fitting._fitter_to_model_params(model, fps) 

1124 meas = args[-1] 

1125 if weights is None: 

1126 a = np.ravel(model(*args[2: -1]) - meas) 

1127 a[np.isfinite(a)] = 0 

1128 return a 

1129 else: 

1130 a = np.ravel(weights * (model(*args[2: -1]) - meas)) 

1131 a[~np.isfinite(a)] = 0 

1132 return a 

1133 

1134 

1135def compute_fwhm(x, y, minimum=0, center=None, full_output=False): 

1136 """ 

1137 Compute the full width half maximum of y(x) curve, 

1138 using an interpolation of the data points and dichotomie method. 

1139 

1140 Parameters 

1141 ---------- 

1142 x: array_like 

1143 The abscisse array. 

1144 y: array_like 

1145 The function array. 

1146 minimum: float, optional 

1147 The minimum reference from which to compyte half the height (default: 0). 

1148 center: float, optional 

1149 The center of the curve. If None, the weighted averageof the y(x) distribution is computed (default: None). 

1150 full_output: bool, optional 

1151 If True, half maximum, the edges of the curve and the curve center are given in output (default: False). 

1152 

1153 Returns 

1154 ------- 

1155 FWHM: float 

1156 The full width half maximum of the curve. 

1157 half: float, optional 

1158 The half maximum value. Only if full_output=True. 

1159 center: float, optional 

1160 The y(x) center value. Only if full_output=True. 

1161 left_edge: float, optional 

1162 The left_edge value at half maximum. Only if full_output=True. 

1163 right_edge: float, optional 

1164 The right_edge value at half maximum. Only if full_output=True. 

1165 

1166 Examples 

1167 -------- 

1168 

1169 Gaussian example 

1170 

1171 >>> x = np.arange(0, 100, 1) 

1172 >>> stddev = 4 

1173 >>> middle = 40 

1174 >>> psf = gauss(x, 1, middle, stddev) 

1175 >>> fwhm, half, center, a, b = compute_fwhm(x, psf, full_output=True) 

1176 >>> print(f"{fwhm:.4f} {2.355*stddev:.4f} {center:.4f}") 

1177 9.4329 9.4200 40.0000 

1178 

1179 .. doctest:: 

1180 :hide: 

1181 

1182 >>> assert np.isclose(fwhm, 2.355*stddev, atol=2e-1) 

1183 >>> assert np.isclose(center, middle, atol=1e-3) 

1184 

1185 .. plot :: 

1186 

1187 import matplotlib.pyplot as plt 

1188 import numpy as np 

1189 from spectractor.tools import gauss, compute_fwhm 

1190 x = np.arange(0, 100, 1) 

1191 stddev = 4 

1192 middle = 40 

1193 psf = gauss(x, 1, middle, stddev) 

1194 fwhm, half, center, a, b = compute_fwhm(x, psf, full_output=True) 

1195 plt.figure() 

1196 plt.plot(x, psf, label="function") 

1197 plt.axvline(center, color="gray", label="center") 

1198 plt.axvline(a, color="k", label="edges at half max") 

1199 plt.axvline(b, color="k", label="edges at half max") 

1200 plt.axhline(half, color="r", label="half max") 

1201 plt.legend() 

1202 plt.title(f"FWHM={fwhm:.3f}") 

1203 plt.xlabel("x") 

1204 plt.ylabel("y") 

1205 plt.show() 

1206 

1207 Defocused PSF example 

1208 

1209 >>> from spectractor.extractor.psf import MoffatGauss 

1210 >>> p = [2,40,40,4,2,-0.4,1,10] 

1211 >>> psf = MoffatGauss(p) 

1212 >>> fwhm, half, center, a, b = compute_fwhm(x, psf.evaluate(x), full_output=True) 

1213 

1214 .. doctest:: 

1215 :hide: 

1216 

1217 >>> assert np.isclose(fwhm, 7.05, atol=1e-2) 

1218 >>> assert np.isclose(center, p[1], atol=1e-2) 

1219 

1220 .. plot :: 

1221 

1222 import matplotlib.pyplot as plt 

1223 import numpy as np 

1224 from spectractor.tools import gauss, compute_fwhm 

1225 from spectractor.extractor.psf import MoffatGauss 

1226 x = np.arange(0, 100, 1) 

1227 p = [2,40,40,4,2,-0.4,1,10] 

1228 psf = MoffatGauss(p) 

1229 fwhm, half, center, a, b = compute_fwhm(x, psf.evaluate(x), full_output=True) 

1230 plt.figure() 

1231 plt.plot(x, psf.evaluate(x, p), label="function") 

1232 plt.axvline(center, color="gray", label="center") 

1233 plt.axvline(a, color="k", label="edges at half max") 

1234 plt.axvline(b, color="k", label="edges at half max") 

1235 plt.axhline(half, color="r", label="half max") 

1236 plt.legend() 

1237 plt.title(f"FWHM={fwhm:.3f}") 

1238 plt.xlabel("x") 

1239 plt.ylabel("y") 

1240 plt.show() 

1241 """ 

1242 if y.ndim > 1: 

1243 # TODO: implement fwhm for 2D curves 

1244 return -1 

1245 interp = interp1d(x, y, kind="linear", bounds_error=False, fill_value="extrapolate") 

1246 maximum = np.max(y) - minimum 

1247 imax = np.argmax(y) 

1248 a = x[imax + np.argmin(np.abs(y[imax:] - 0.9 * maximum))] 

1249 b = x[imax + np.argmin(np.abs(y[imax:] - 0.1 * maximum))] 

1250 

1251 def eq(xx): 

1252 return interp(xx) - 0.5 * maximum 

1253 

1254 res = dichotomie(eq, a, b, 1e-3) 

1255 if center is None: 

1256 center = np.average(x, weights=y) 

1257 fwhm = abs(2 * (res - center)) 

1258 if not full_output: 

1259 return fwhm 

1260 else: 

1261 return fwhm, 0.5 * maximum, center, res, center - abs(res - center) 

1262 

1263 

1264def compute_integral(x, y, bounds=None): 

1265 """ 

1266 Compute the integral of an y(x) curve. The curve is interpolated and extrapolated with cubic splines. 

1267 If not provided, bounds are set to the x array edges. 

1268 

1269 Parameters 

1270 ---------- 

1271 x: array_like 

1272 The abscisse array. 

1273 y: array_like 

1274 The function array. 

1275 bounds: array_like, optional 

1276 The bounds of the integral. If None, the edges of thex array are taken (default bounds=None). 

1277 

1278 Returns 

1279 ------- 

1280 result: float 

1281 The integral of the PSF model. 

1282 

1283 Examples 

1284 -------- 

1285 

1286 Gaussian example 

1287 

1288 .. doctest:: 

1289 

1290 >>> x = np.arange(0, 100, 0.5) 

1291 >>> stddev = 4 

1292 >>> middle = 40 

1293 >>> psf = gauss(x, 1/(stddev*np.sqrt(2*np.pi)), middle, stddev) 

1294 >>> integral = compute_integral(x, psf) 

1295 >>> print(f"{integral:.6f}") 

1296 1.000000 

1297 

1298 Defocused PSF example 

1299 

1300 .. doctest:: 

1301 

1302 >>> from spectractor.extractor.psf import MoffatGauss 

1303 >>> p = [2,30,30,4,2,-0.5,1,10] 

1304 >>> psf = MoffatGauss(p) 

1305 >>> integral = compute_integral(x, psf.evaluate(x)) 

1306 >>> assert np.isclose(integral, p[0], atol=1e-2) 

1307 

1308 """ 

1309 if bounds is None: 

1310 bounds = (np.min(x), np.max(x)) 

1311 interp = interp1d(x, y, kind="cubic", bounds_error=False, fill_value="extrapolate") 

1312 integral = quad(interp, bounds[0], bounds[1], limit=200) 

1313 return integral[0] 

1314 

1315 

1316def find_nearest(array, value): 

1317 """Find the nearest index and value in an array. 

1318 

1319 Parameters 

1320 ---------- 

1321 array: array 

1322 The array to inspect. 

1323 value: float 

1324 The value to look for. 

1325 

1326 Returns 

1327 ------- 

1328 index: int 

1329 The array index of the nearest value close to *value* 

1330 val: float 

1331 The value fo the array at index. 

1332 

1333 Examples 

1334 -------- 

1335 >>> x = np.arange(0.,10.) 

1336 >>> idx, val = find_nearest(x, 3.3) 

1337 >>> print(idx, val) 

1338 3 3.0 

1339 """ 

1340 idx = (np.abs(array - value)).argmin() 

1341 return idx, array[idx] 

1342 

1343 

1344def ensure_dir(directory_name): 

1345 """Ensure that *directory_name* directory exists. If not, create it. 

1346 

1347 Parameters 

1348 ---------- 

1349 directory_name: str 

1350 The directory name. 

1351 

1352 Examples 

1353 -------- 

1354 >>> ensure_dir('tests') 

1355 >>> os.path.exists('tests') 

1356 True 

1357 >>> ensure_dir('tests/mytest') 

1358 >>> os.path.exists('tests/mytest') 

1359 True 

1360 >>> os.rmdir('./tests/mytest') 

1361 """ 

1362 if not os.path.exists(directory_name): 

1363 os.makedirs(directory_name) 

1364 

1365 

1366def weighted_avg_and_std(values, weights): 

1367 """ 

1368 Return the weighted average and standard deviation. 

1369 

1370 values, weights -- Numpy ndarrays with the same shape. 

1371  

1372 For example for the PSF 

1373  

1374 x=pixel number 

1375 y=Intensity in pixel 

1376  

1377 values-x 

1378 weights=y=f(x) 

1379  

1380 """ 

1381 average = np.average(values, weights=weights) 

1382 variance = np.average((values - average) ** 2, weights=weights) # Fast and numerically precise 

1383 return average, np.sqrt(variance) 

1384 

1385 

1386def hessian_and_theta(data, margin_cut=1): 

1387 # compute hessian matrices on the image 

1388 Hxx, Hxy, Hyy = hessian_matrix(data, sigma=3, order='rc') 

1389 lambda_plus = 0.5 * ((Hxx + Hyy) + np.sqrt((Hxx - Hyy) ** 2 + 4 * Hxy * Hxy)) 

1390 lambda_minus = 0.5 * ((Hxx + Hyy) - np.sqrt((Hxx - Hyy) ** 2 + 4 * Hxy * Hxy)) 

1391 theta = 0.5 * np.arctan2(2 * Hxy, Hxx - Hyy) * 180 / np.pi 

1392 # remove the margins 

1393 lambda_minus = lambda_minus[margin_cut:-margin_cut, margin_cut:-margin_cut] 

1394 lambda_plus = lambda_plus[margin_cut:-margin_cut, margin_cut:-margin_cut] 

1395 theta = theta[margin_cut:-margin_cut, margin_cut:-margin_cut] 

1396 return lambda_plus, lambda_minus, theta 

1397 

1398 

1399def filter_stars_from_bgd(data, margin_cut=1): 

1400 lambda_plus, lambda_minus, theta = hessian_and_theta(np.copy(data), margin_cut=margin_cut) 

1401 # thresholds 

1402 lambda_threshold = np.median(lambda_minus) - 2 * np.std(lambda_minus) 

1403 mask = np.where(lambda_minus < lambda_threshold) 

1404 data[mask] = np.nan 

1405 return data 

1406 

1407 

1408def fftconvolve_gaussian(array, reso): 

1409 """Convolve an 1D or 2D array with a Gaussian profile of given standard deviation. 

1410 

1411 Parameters 

1412 ---------- 

1413 array: array 

1414 The array to convolve. 

1415 reso: float 

1416 The standard deviation of the Gaussian profile. 

1417 

1418 Returns 

1419 ------- 

1420 convolved: array 

1421 The convolved array, same size and shape as input. 

1422 

1423 Examples 

1424 -------- 

1425 >>> array = np.ones(100) 

1426 >>> output = fftconvolve_gaussian(array, 3) 

1427 >>> print(output[:3]) 

1428 [0.5 0.63114657 0.74850168] 

1429 >>> array = np.ones((100, 100)) 

1430 >>> output = fftconvolve_gaussian(array, 3) 

1431 >>> print(output[0][:3]) 

1432 [0.5 0.63114657 0.74850168] 

1433 >>> array = np.ones((100, 100, 100)) 

1434 >>> output = fftconvolve_gaussian(array, 3) 

1435 """ 

1436 my_logger = set_logger(__name__) 

1437 if array.ndim == 2: 

1438 kernel = gaussian(array.shape[1], reso) 

1439 kernel /= np.sum(kernel) 

1440 for i in range(array.shape[0]): 

1441 array[i] = fftconvolve(array[i], kernel, mode='same') 

1442 elif array.ndim == 1: 

1443 kernel = gaussian(array.size, reso) 

1444 kernel /= np.sum(kernel) 

1445 array = fftconvolve(array, kernel, mode='same') 

1446 else: 

1447 my_logger.error(f'\n\tArray dimension must be 1 or 2. Here I have array.ndim={array.ndim}.') 

1448 return array 

1449 

1450 

1451def formatting_numbers(value, error_high, error_low, std=None, label=None): 

1452 """Format a physical value and its uncertainties. Round the uncertainties 

1453 to the first significant digit, and do the same for the physical value. 

1454 

1455 Parameters 

1456 ---------- 

1457 value: float 

1458 The physical value. 

1459 error_high: float 

1460 Upper uncertainty. 

1461 error_low: float 

1462 Lower uncertainty 

1463 std: float, optional 

1464 The RMS of the physical parameter (default: None). 

1465 label: str, optional 

1466 The name of the physical parameter to output (default: None). 

1467 

1468 Returns 

1469 ------- 

1470 text: tuple 

1471 The formatted output strings inside a tuple. 

1472 

1473 Examples 

1474 -------- 

1475 >>> formatting_numbers(3., 0.789, 0.500, std=0.45, label='test') 

1476 ('test', '3.0', '0.8', '0.5', '0.5') 

1477 >>> formatting_numbers(3., 0.07, 0.008, std=0.03, label='test') 

1478 ('test', '3.000', '0.07', '0.008', '0.03') 

1479 >>> formatting_numbers(3240., 0.2, 0.4, std=0.3) 

1480 ('3240.0', '0.2', '0.4', '0.3') 

1481 >>> formatting_numbers(3240., 230, 420, std=330) 

1482 ('3240', '230', '420', '330') 

1483 >>> formatting_numbers(0, 0.008, 0.04, std=0.03) 

1484 ('0.000', '0.008', '0.040', '0.030') 

1485 >>> formatting_numbers(-55, 0.008, 0.04, std=0.03) 

1486 ('-55.000', '0.008', '0.04', '0.03') 

1487 """ 

1488 str_std = "" 

1489 out = [] 

1490 if label is not None: 

1491 out.append(label) 

1492 power10 = min(int(floor(np.log10(np.abs(error_high)))), int(floor(np.log10(np.abs(error_low))))) 

1493 if np.isclose(0.0, float("%.*f" % (abs(power10), value))): 

1494 str_value = "%.*f" % (abs(power10), 0) 

1495 str_error_high = "%.*f" % (abs(power10), error_high) 

1496 str_error_low = "%.*f" % (abs(power10), error_low) 

1497 if std is not None: 

1498 str_std = "%.*f" % (abs(power10), std) 

1499 elif power10 > 0: 

1500 str_value = f"{value:.0f}" 

1501 str_error_high = f"{error_high:.0f}" 

1502 str_error_low = f"{error_low:.0f}" 

1503 if std is not None: 

1504 str_std = f"{std:.0f}" 

1505 else: 

1506 if int(floor(np.log10(np.abs(error_high)))) == int(floor(np.log10(np.abs(error_low)))): 

1507 str_value = "%.*f" % (abs(power10), value) 

1508 str_error_high = f"{error_high:.1g}" 

1509 str_error_low = f"{error_low:.1g}" 

1510 if std is not None: 

1511 str_std = f"{std:.1g}" 

1512 elif int(floor(np.log10(np.abs(error_high)))) > int(floor(np.log10(np.abs(error_low)))): 

1513 str_value = "%.*f" % (abs(power10), value) 

1514 str_error_high = f"{error_high:.2g}" 

1515 str_error_low = f"{error_low:.1g}" 

1516 if std is not None: 

1517 str_std = f"{std:.2g}" 

1518 else: 

1519 str_value = "%.*f" % (abs(power10), value) 

1520 str_error_high = f"{error_high:.1g}" 

1521 str_error_low = f"{error_low:.2g}" 

1522 if std is not None: 

1523 str_std = f"{std:.2g}" 

1524 out += [str_value, str_error_high] 

1525 # if not np.isclose(error_high, error_low): 

1526 out += [str_error_low] 

1527 if std is not None: 

1528 out += [str_std] 

1529 out = tuple(out) 

1530 return out 

1531 

1532 

1533def pixel_rotation(x, y, theta, x0=0, y0=0): 

1534 """Rotate a 2D vector (x,y) of an angle theta clockwise. 

1535 

1536 Parameters 

1537 ---------- 

1538 x: float 

1539 x coordinate 

1540 y: float 

1541 y coordinate 

1542 theta: float 

1543 angle in radians 

1544 x0: float, optional 

1545 x position of the center of rotation (default: 0) 

1546 y0: float, optional 

1547 y position of the center of rotation (default: 0) 

1548 

1549 Returns 

1550 ------- 

1551 u: float 

1552 rotated x coordinate 

1553 v: float 

1554 rotated y coordinate 

1555 

1556 Examples 

1557 -------- 

1558 >>> pixel_rotation(0, 0, 45) 

1559 (0.0, 0.0) 

1560 >>> u, v = pixel_rotation(1, 0, np.pi/4) 

1561 

1562 .. doctest:: 

1563 :hide: 

1564 

1565 >>> assert np.isclose(u, 1/np.sqrt(2)) 

1566 >>> assert np.isclose(v, -1/np.sqrt(2)) 

1567 >>> u, v = pixel_rotation(1, 2, -np.pi/2, x0=1, y0=0) 

1568 >>> assert np.isclose(u, -2) 

1569 >>> assert np.isclose(v, 0) 

1570 """ 

1571 u = np.cos(theta) * (x - x0) + np.sin(theta) * (y - y0) 

1572 v = -np.sin(theta) * (x - x0) + np.cos(theta) * (y - y0) 

1573 return u, v 

1574 

1575 

1576def detect_peaks(image): 

1577 """ 

1578 Takes an image and detect the peaks using the local maximum filter. 

1579 Returns a boolean mask of the peaks (i.e. 1 when 

1580 the pixel's value is the neighborhood maximum, 0 otherwise). 

1581 Only positive peaks are detected (take absolute value or negative value of the 

1582 image to detect the negative ones). 

1583 

1584 Parameters 

1585 ---------- 

1586 image: array_like 

1587 The image 2D array. 

1588 

1589 Returns 

1590 ------- 

1591 detected_peaks: array_like 

1592 Boolean maskof the peaks. 

1593 

1594 Examples 

1595 -------- 

1596 >>> im = np.zeros((50,50)) 

1597 >>> im[4,6] = 2 

1598 >>> im[10,20] = -3 

1599 >>> im[49,49] = 1 

1600 >>> detected_peaks = detect_peaks(im) 

1601 

1602 .. doctest:: 

1603 :hide: 

1604 

1605 >>> assert detected_peaks[4,6] 

1606 >>> assert not detected_peaks[10,20] 

1607 >>> assert detected_peaks[49,49] 

1608 """ 

1609 

1610 # define an 8-connected neighborhood 

1611 neighborhood = generate_binary_structure(2, 2) 

1612 

1613 # apply the local maximum filter; all pixel of maximal value 

1614 # in their neighborhood are set to 1 

1615 local_max = maximum_filter(image, footprint=neighborhood) == image 

1616 # local_max is a mask that contains the peaks we are 

1617 # looking for, but also the background. 

1618 # In order to isolate the peaks we must remove the background from the mask. 

1619 

1620 # we create the mask of the background 

1621 background = (image == 0) 

1622 

1623 # a little technicality: we must erode the background in order to 

1624 # successfully subtract it form local_max, otherwise a line will 

1625 # appear along the background border (artifact of the local maximum filter) 

1626 eroded_background = binary_erosion(background, structure=neighborhood, border_value=50) 

1627 

1628 # we obtain the final mask, containing only peaks, 

1629 # by removing the background from the local_max mask (xor operation) 

1630 detected_peaks = local_max ^ eroded_background 

1631 

1632 return detected_peaks 

1633 

1634 

1635def clean_target_spikes(data, saturation): 

1636 saturated_pixels = np.where(data > saturation) 

1637 data[saturated_pixels] = saturation 

1638 NY, NX = data.shape 

1639 delta = len(saturated_pixels[0]) 

1640 while delta > 0: 

1641 delta = len(saturated_pixels[0]) 

1642 grady, gradx = np.gradient(data) 

1643 for iy in range(1, NY - 1): 

1644 for ix in range(1, NX - 1): 

1645 # if grady[iy,ix] > 0.8*np.max(grady) : 

1646 # data[iy,ix] = data[iy-1,ix] 

1647 # if grady[iy,ix] < 0.8*np.min(grady) : 

1648 # data[iy,ix] = data[iy+1,ix] 

1649 if gradx[iy, ix] > 0.8 * np.max(gradx): 

1650 data[iy, ix] = data[iy, ix - 1] 

1651 if gradx[iy, ix] < 0.8 * np.min(gradx): 

1652 data[iy, ix] = data[iy, ix + 1] 

1653 saturated_pixels = np.where(data >= saturation) 

1654 delta = delta - len(saturated_pixels[0]) 

1655 return data 

1656 

1657 

1658def plot_image_simple(ax, data, scale="lin", title="", units="Image units", cmap=None, 

1659 target_pixcoords=None, vmin=None, vmax=None, aspect=None, cax=None): 

1660 """Simple function to plot a spectrum with error bars and labels. 

1661 

1662 Parameters 

1663 ---------- 

1664 ax: Axes 

1665 Axes instance to make the plot 

1666 data: array_like 

1667 The image data 2D array. 

1668 scale: str 

1669 Scaling of the image (choose between: lin, log or log10, symlog) (default: lin) 

1670 title: str 

1671 Title of the image (default: "") 

1672 units: str 

1673 Units of the image to be written in the color bar label (default: "Image units") 

1674 cmap: colormap 

1675 Color map label (default: None) 

1676 target_pixcoords: array_like, optional 

1677 2D array giving the (x,y) coordinates of the targets on the image: add a scatter plot (default: None) 

1678 vmin: float 

1679 Minimum value of the image (default: None) 

1680 vmax: float 

1681 Maximum value of the image (default: None) 

1682 aspect: str 

1683 Aspect keyword to be passed to imshow (default: None) 

1684 cax: Axes, optional 

1685 Color bar axes if necessary (default: None). 

1686 

1687 Examples 

1688 -------- 

1689 

1690 .. plot:: 

1691 :include-source: 

1692 

1693 >>> import matplotlib.pyplot as plt 

1694 >>> from spectractor.extractor.images import Image 

1695 >>> from spectractor import parameters 

1696 >>> from spectractor.tools import plot_image_simple 

1697 >>> f, ax = plt.subplots(1,1) 

1698 >>> im = Image('tests/data/reduc_20170605_028.fits', config="./config/ctio.ini") 

1699 >>> plot_image_simple(ax, im.data, scale="symlog", units="ADU", target_pixcoords=(815,580), 

1700 ... title="tests/data/reduc_20170605_028.fits") 

1701 >>> if parameters.DISPLAY: plt.show() 

1702 """ 

1703 if scale == "log" or scale == "log10": 

1704 # removes the zeros and negative pixels first 

1705 zeros = np.where(data <= 0) 

1706 min_noz = np.min(data[np.where(data > 0)]) 

1707 data[zeros] = min_noz 

1708 # apply log 

1709 # data = np.log10(data) 

1710 if scale == "log10" or scale == "log": 

1711 norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax) 

1712 elif scale == "symlog": 

1713 norm = matplotlib.colors.SymLogNorm(vmin=vmin, vmax=vmax, linthresh=10, base=10) 

1714 else: 

1715 norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) 

1716 im = ax.imshow(data, origin='lower', cmap=cmap, norm=norm, aspect=aspect) 

1717 ax.grid(color='silver', ls='solid') 

1718 ax.grid(True) 

1719 ax.set_xlabel(parameters.PLOT_XLABEL) 

1720 ax.set_ylabel(parameters.PLOT_YLABEL) 

1721 cb = plt.colorbar(im, ax=ax, cax=cax) 

1722 if scale == "lin": 

1723 cb.formatter.set_powerlimits((0, 0)) 

1724 cb.locator = MaxNLocator(7, prune=None) 

1725 cb.update_ticks() 

1726 cb.set_label('%s (%s scale)' % (units, scale)) # ,fontsize=16) 

1727 if title != "": 

1728 ax.set_title(title) 

1729 if target_pixcoords is not None: 

1730 ax.scatter(target_pixcoords[0], target_pixcoords[1], marker='o', s=100, edgecolors='k', facecolors='none', 

1731 label='Target', linewidth=2) 

1732 

1733 

1734def plot_spectrum_simple(ax, lambdas, data, data_err=None, xlim=None, color='r', linestyle='none', lw=2, label='', 

1735 title='', units=''): 

1736 """Simple function to plot a spectrum with error bars and labels. 

1737 

1738 Parameters 

1739 ---------- 

1740 ax: Axes 

1741 Axes instance to make the plot. 

1742 lambdas: array 

1743 The wavelengths array. 

1744 data: array 

1745 The spectrum data array. 

1746 data_err: array, optional 

1747 The spectrum uncertainty array (default: None). 

1748 xlim: list, optional 

1749 List of minimum and maximum abscisses (default: None). 

1750 color: str, optional 

1751 String for the color of the spectrum (default: 'r'). 

1752 linestyle: str, optional 

1753 String for the linestyle of the spectrum (default: 'none'). 

1754 lw: int, optional 

1755 Integer for line width (default: 2). 

1756 label: str, optional 

1757 String label for the plot legend (default: ''). 

1758 title: str, optional 

1759 String label for the plot title (default: ''). 

1760 units: str, optional 

1761 String label for the plot units (default: ''). 

1762 

1763 

1764 Examples 

1765 -------- 

1766 

1767 .. plot:: 

1768 :include-source: 

1769 

1770 >>> import matplotlib.pyplot as plt 

1771 >>> from spectractor.extractor.spectrum import Spectrum 

1772 >>> from spectractor import parameters 

1773 >>> from spectractor.tools import plot_spectrum_simple 

1774 >>> f, ax = plt.subplots(1,1) 

1775 >>> s = Spectrum(file_name='tests/data/reduc_20170530_134_spectrum.fits') 

1776 >>> plot_spectrum_simple(ax, s.lambdas, s.data, data_err=s.err, xlim=None, color='r', label='test') 

1777 >>> if parameters.DISPLAY: plt.show() 

1778 """ 

1779 xs = lambdas 

1780 if xs is None: 

1781 xs = np.arange(data.size) 

1782 if data_err is not None: 

1783 ax.errorbar(xs, data, yerr=data_err, fmt=f'{color}o', lw=lw, label=label, 

1784 zorder=0, markersize=2, linestyle=linestyle) 

1785 else: 

1786 ax.plot(xs, data, f'{color}-', lw=lw, label=label, linestyle=linestyle) 

1787 ax.grid(True) 

1788 if xlim is None and lambdas is not None: 

1789 xlim = [parameters.LAMBDA_MIN, parameters.LAMBDA_MAX] 

1790 ax.set_xlim(xlim) 

1791 try: 

1792 ax.set_ylim(0., np.nanmax(data[np.logical_and(xs > xlim[0], xs < xlim[1])]) * 1.2) 

1793 except ValueError: 

1794 pass 

1795 if lambdas is not None: 

1796 ax.set_xlabel(r'$\lambda$ [nm]') 

1797 else: 

1798 ax.set_xlabel('X [pixels]') 

1799 if units != '': 

1800 ax.set_ylabel(f'Flux [{units}]') 

1801 else: 

1802 ax.set_ylabel(f'Flux') 

1803 if title != '': 

1804 ax.set_title(title) 

1805 

1806 

1807def plot_compass_simple(ax, parallactic_angle=None, arrow_size=0.1, origin=[0.15, 0.15]): 

1808 """Plot small (N,W) compass, and optionally zenith direction. 

1809 

1810 Parameters 

1811 ---------- 

1812 ax: Axes 

1813 Axes instance to make the plot. 

1814 parallactic_angle: float, optional 

1815 Value is the parallactic angle with respect to North eastward and plot the zenith direction (default: None). 

1816 arrow_size: float, optional 

1817 Length of the arrow as a fraction of axe sizes (default: 0.1) 

1818 origin: array_like, optional 

1819 (x0, y0) position of the compass as axes fraction (default: [0.15, 0.15]). 

1820 

1821 Examples 

1822 -------- 

1823 

1824 >>> from spectractor.extractor.images import Image 

1825 >>> from spectractor import parameters 

1826 >>> from spectractor.tools import plot_image_simple, plot_compass_simple 

1827 >>> f, ax = plt.subplots(1,1) 

1828 >>> im = Image('tests/data/reduc_20170605_028.fits', config="./config/ctio.ini") 

1829 >>> plot_image_simple(ax, im.data, scale="symlog", units="ADU", target_pixcoords=(750,700), 

1830 ... title='tests/data/reduc_20170530_134.fits') 

1831 >>> plot_compass_simple(ax, im.parallactic_angle) 

1832 >>> if parameters.DISPLAY: plt.show() 

1833 

1834 """ 

1835 # North arrow 

1836 N_arrow = [0, arrow_size] 

1837 N_xy = np.asarray(flip_and_rotate_radec_to_image_xy_coordinates(N_arrow[0], N_arrow[1], 

1838 camera_angle=parameters.OBS_CAMERA_ROTATION, 

1839 flip_ra_sign=parameters.OBS_CAMERA_RA_FLIP_SIGN, 

1840 flip_dec_sign=parameters.OBS_CAMERA_DEC_FLIP_SIGN)) 

1841 ax.annotate("N", xy=origin, xycoords='axes fraction', xytext=N_xy + origin, textcoords='axes fraction', 

1842 arrowprops=dict(arrowstyle="<|-", fc="yellow", ec="yellow"), color="yellow", 

1843 horizontalalignment='center', verticalalignment='center') 

1844 # West arrow 

1845 W_arrow = [arrow_size, 0] 

1846 W_xy = np.asarray(flip_and_rotate_radec_to_image_xy_coordinates(W_arrow[0], W_arrow[1], 

1847 camera_angle=parameters.OBS_CAMERA_ROTATION, 

1848 flip_ra_sign=parameters.OBS_CAMERA_RA_FLIP_SIGN, 

1849 flip_dec_sign=parameters.OBS_CAMERA_DEC_FLIP_SIGN)) 

1850 ax.annotate("W", xy=origin, xycoords='axes fraction', xytext=W_xy + origin, textcoords='axes fraction', 

1851 arrowprops=dict(arrowstyle="<|-", fc="yellow", ec="yellow"), color="yellow", 

1852 horizontalalignment='center', verticalalignment='center') 

1853 # Central dot 

1854 xmin, xmax = ax.get_xlim() 

1855 ymin, ymax = ax.get_ylim() 

1856 ax.scatter(origin[0] * xmax, origin[1] * ymax, color="yellow", s=20) 

1857 # Zenith direction 

1858 if parallactic_angle is not None: 

1859 p_arrow = [0, arrow_size] # angle with respect to North in RADEC counterclockwise 

1860 angle = parameters.OBS_CAMERA_ROTATION + parameters.OBS_CAMERA_RA_FLIP_SIGN * parallactic_angle 

1861 p_xy = np.asarray(flip_and_rotate_radec_to_image_xy_coordinates(p_arrow[0], p_arrow[1], 

1862 camera_angle=angle, 

1863 flip_ra_sign=parameters.OBS_CAMERA_RA_FLIP_SIGN, 

1864 flip_dec_sign=parameters.OBS_CAMERA_DEC_FLIP_SIGN)) 

1865 ax.annotate("Z", xy=origin, xycoords='axes fraction', xytext=p_xy + origin, textcoords='axes fraction', 

1866 arrowprops=dict(arrowstyle="<|-", fc="lightgreen", ec="lightgreen"), color="lightgreen", 

1867 horizontalalignment='center', verticalalignment='center') 

1868 

1869 

1870def load_fits(file_name, hdu_index=0): 

1871 """Generic function to load a FITS file. 

1872 

1873 Parameters 

1874 ---------- 

1875 file_name: str 

1876 The FITS file name. 

1877 hdu_index: int, optional 

1878 The HDU index in the file (default: 0). 

1879 

1880 Returns 

1881 ------- 

1882 header: fits.Header 

1883 Header of the FITS file. 

1884 data: np.array 

1885 The data array. 

1886 

1887 Examples 

1888 -------- 

1889 >>> header, data = load_fits("./tests/data/reduc_20170530_134.fits") 

1890 >>> header["DATE-OBS"] 

1891 '2017-05-31T02:53:52.356' 

1892 >>> data.shape 

1893 (2048, 2048) 

1894 

1895 """ 

1896 hdu_list = fits.open(file_name) 

1897 header = hdu_list[0].header 

1898 data = hdu_list[hdu_index].data 

1899 hdu_list.close() # need to free allocation for file description 

1900 return header, data 

1901 

1902 

1903def save_fits(file_name, header, data, overwrite=False): 

1904 """Generic function to save a FITS file. 

1905 

1906 Parameters 

1907 ---------- 

1908 file_name: str 

1909 The FITS file name. 

1910 header: fits.Header 

1911 Header of the FITS file. 

1912 data: np.array 

1913 The data array. 

1914 overwrite: bool, optional 

1915 If True and the file already exists, it is overwritten (default: False). 

1916 

1917 Examples 

1918 -------- 

1919 

1920 >>> header, data = load_fits("./tests/data/reduc_20170530_134.fits") 

1921 >>> save_fits("./outputs/save_fits_test.fits", header, data, overwrite=True) 

1922 >>> assert os.path.isfile("./outputs/save_fits_test.fits") 

1923 

1924 .. doctest: 

1925 :hide: 

1926 

1927 >>> os.remove("./outputs/save_fits_test.fits") 

1928 

1929 """ 

1930 hdu = fits.PrimaryHDU() 

1931 hdu.header = header 

1932 hdu.data = data 

1933 output_directory = '/'.join(file_name.split('/')[:-1]) 

1934 ensure_dir(output_directory) 

1935 hdu.writeto(file_name, overwrite=overwrite) 

1936 

1937 

1938def dichotomie(f, a, b, epsilon): 

1939 """ 

1940 Dichotomie method to find a function root. 

1941 

1942 Parameters 

1943 ---------- 

1944 f: callable 

1945 The function 

1946 a: float 

1947 Left bound to the expected root 

1948 b: float 

1949 Right bound to the expected root 

1950 epsilon: float 

1951 Precision 

1952 

1953 Returns 

1954 ------- 

1955 root: float 

1956 The root of the function. 

1957 

1958 Examples 

1959 -------- 

1960 

1961 Search for the Gaussian FWHM: 

1962 

1963 >>> p = [1,0,1] 

1964 >>> xx = np.arange(-10,10,0.1) 

1965 >>> PSF = gauss(xx, *p) 

1966 >>> def eq(x): 

1967 ... return np.interp(x, xx, PSF) - 0.5 

1968 >>> root = dichotomie(eq, 0, 10, 1e-6) 

1969 >>> assert np.isclose(2*root, 2.355*p[2], 1e-3) 

1970 """ 

1971 x = 0.5 * (a + b) 

1972 N = 1 

1973 while b - a > epsilon and N < 100: 

1974 x = 0.5 * (a + b) 

1975 if f(x) * f(a) > 0: 

1976 a = x 

1977 else: 

1978 b = x 

1979 N += 1 

1980 return x 

1981 

1982 

1983def wavelength_to_rgb(wavelength, gamma=0.8): 

1984 """ taken from http://www.noah.org/wiki/Wavelength_to_RGB_in_Python 

1985 This converts a given wavelength of light to an 

1986 approximate RGB color value. The wavelength must be given 

1987 in nanometers in the range from 380 nm through 750 nm 

1988 (789 THz through 400 THz). 

1989 

1990 Based on code by Dan Bruton 

1991 http://www.physics.sfasu.edu/astro/color/spectra.html 

1992 Additionally alpha value set to 0.5 outside range 

1993 """ 

1994 wavelength = float(wavelength) 

1995 if 380 <= wavelength <= 750: 

1996 A = 1. 

1997 else: 

1998 A = 0.5 

1999 if wavelength < 380: 

2000 wavelength = 380. 

2001 if wavelength > 750: 

2002 wavelength = 750. 

2003 if 380 <= wavelength <= 440: 

2004 attenuation = 0.3 + 0.7 * (wavelength - 380) / (440 - 380) 

2005 R = ((-(wavelength - 440) / (440 - 380)) * attenuation) ** gamma 

2006 G = 0.0 

2007 B = (1.0 * attenuation) ** gamma 

2008 elif 440 <= wavelength <= 490: 

2009 R = 0.0 

2010 G = ((wavelength - 440) / (490 - 440)) ** gamma 

2011 B = 1.0 

2012 elif 490 <= wavelength <= 510: 

2013 R = 0.0 

2014 G = 1.0 

2015 B = (-(wavelength - 510) / (510 - 490)) ** gamma 

2016 elif 510 <= wavelength <= 580: 

2017 R = ((wavelength - 510) / (580 - 510)) ** gamma 

2018 G = 1.0 

2019 B = 0.0 

2020 elif 580 <= wavelength <= 645: 

2021 R = 1.0 

2022 G = (-(wavelength - 645) / (645 - 580)) ** gamma 

2023 B = 0.0 

2024 elif 645 <= wavelength <= 750: 

2025 attenuation = 0.3 + 0.7 * (750 - wavelength) / (750 - 645) 

2026 R = (1.0 * attenuation) ** gamma 

2027 G = 0.0 

2028 B = 0.0 

2029 else: 

2030 R = 0.0 

2031 G = 0.0 

2032 B = 0.0 

2033 return R, G, B, A 

2034 

2035 

2036def from_lambda_to_colormap(lambdas): 

2037 """Convert an array of wavelength in nm into a color map. 

2038 

2039 Parameters 

2040 ---------- 

2041 lambdas: array_like 

2042 Wavelength array in nm. 

2043 

2044 Returns 

2045 ------- 

2046 spectral_map: matplotlib.colors.LinearSegmentedColormap 

2047 Color map. 

2048 

2049 Examples 

2050 -------- 

2051 >>> lambdas = np.arange(300, 1000, 10) 

2052 >>> spec = from_lambda_to_colormap(lambdas) 

2053 >>> plt.scatter(lambdas, np.zeros(lambdas.size), cmap=spec, c=lambdas) #doctest: +ELLIPSIS 

2054 <matplotlib.collections.PathCollection object at ...> 

2055 >>> plt.grid() 

2056 >>> plt.xlabel("Wavelength [nm]") #doctest: +ELLIPSIS 

2057 Text(..., 'Wavelength [nm]') 

2058 >>> plt.show() 

2059 

2060 ..plot:: 

2061 

2062 import numpy as np 

2063 import matplotlib.pyplot as plt 

2064 from spectractor.tools import from_lambda_to_colormap 

2065 lambdas = np.arange(300, 1000, 10) 

2066 spec = from_lambda_to_colormap(lambdas) 

2067 plt.scatter(lambdas, np.zeros(lambdas.size), cmap=spec, c=lambdas) 

2068 plt.xlabel("Wavelength [nm]") 

2069 plt.grid() 

2070 plt.show() 

2071 

2072 """ 

2073 colorlist = [wavelength_to_rgb(lbda) for lbda in lambdas] 

2074 spectralmap = matplotlib.colors.LinearSegmentedColormap.from_list("spectrum", colorlist) 

2075 return spectralmap 

2076 

2077 

2078def rebin(arr, new_shape): 

2079 """Rebin and reshape a numpy array. 

2080 

2081 Parameters 

2082 ---------- 

2083 arr: np.array 

2084 Numpy array to be reshaped. 

2085 new_shape: array_like 

2086 New shape of the array. 

2087 

2088 Returns 

2089 ------- 

2090 arr_rebinned: np.array 

2091 Rebinned array. 

2092 

2093 Examples 

2094 -------- 

2095 >>> a = 4 * np.ones((10, 10)) 

2096 >>> b = rebin(a, (5, 5)) 

2097 >>> b 

2098 array([[4., 4., 4., 4., 4.], 

2099 [4., 4., 4., 4., 4.], 

2100 [4., 4., 4., 4., 4.], 

2101 [4., 4., 4., 4., 4.], 

2102 [4., 4., 4., 4., 4.]]) 

2103 """ 

2104 if np.any(new_shape * parameters.CCD_REBIN != arr.shape): 

2105 shape_cropped = new_shape * parameters.CCD_REBIN 

2106 margins = np.asarray(arr.shape) - shape_cropped 

2107 arr = arr[:-margins[0], :-margins[1]] 

2108 shape = (new_shape[0], arr.shape[0] // new_shape[0], 

2109 new_shape[1], arr.shape[1] // new_shape[1]) 

2110 return arr.reshape(shape).mean(-1).mean(1) 

2111 

2112 

2113def set_wcs_output_directory(file_name, output_directory=""): 

2114 """Returns the WCS output directory corresponding to the analyzed image. The name of the directory is 

2115 the anme of the image with the suffix _wcs. 

2116 

2117 Parameters 

2118 ---------- 

2119 file_name: str 

2120 File name of the image. 

2121 output_directory: str, optional 

2122 If not set, the main output directory is the one the image, 

2123 otherwise the specified directory is taken (default: ""). 

2124 

2125 Returns 

2126 ------- 

2127 output: str 

2128 The name of the output directory 

2129 

2130 Examples 

2131 -------- 

2132 >>> set_wcs_output_directory("image.fits", output_directory="") 

2133 'image_wcs' 

2134 >>> set_wcs_output_directory("image.png", output_directory="outputs") 

2135 'outputs/image_wcs' 

2136 

2137 """ 

2138 outdir = os.path.dirname(file_name) 

2139 if output_directory != "": 

2140 outdir = output_directory 

2141 output_directory = os.path.join(outdir, os.path.splitext(os.path.basename(file_name))[0]) + "_wcs" 

2142 return output_directory 

2143 

2144 

2145def set_wcs_tag(file_name): 

2146 """Returns the WCS tag name associated to the analyzed image: the file name without the extension. 

2147 

2148 Parameters 

2149 ---------- 

2150 file_name: str 

2151 File name of the image. 

2152 

2153 Returns 

2154 ------- 

2155 tag: str 

2156 The tag. 

2157 

2158 Examples 

2159 -------- 

2160 >>> set_wcs_tag("image.fits") 

2161 'image' 

2162 

2163 """ 

2164 tag = os.path.splitext(os.path.basename(file_name))[0] 

2165 return tag 

2166 

2167 

2168def set_wcs_file_name(file_name, output_directory=""): 

2169 """Returns the WCS file name associated to the analyzed image, placed in the output directory. 

2170 The extension is .wcs. 

2171 

2172 Parameters 

2173 ---------- 

2174 file_name: str 

2175 File name of the image. 

2176 output_directory: str, optional 

2177 If not set, the main output directory is the one the image, 

2178 otherwise the specified directory is taken (default: ""). 

2179 

2180 Returns 

2181 ------- 

2182 wcs_file_name: str 

2183 The WCS file name. 

2184 

2185 Examples 

2186 -------- 

2187 >>> set_wcs_file_name("image.fits", output_directory="") 

2188 'image_wcs/image.wcs' 

2189 >>> set_wcs_file_name("image.png", output_directory="outputs") 

2190 'outputs/image_wcs/image.wcs' 

2191 

2192 """ 

2193 output_directory = set_wcs_output_directory(file_name, output_directory=output_directory) 

2194 tag = set_wcs_tag(file_name) 

2195 return os.path.join(output_directory, tag + '.wcs') 

2196 

2197 

2198def set_sources_file_name(file_name, output_directory=""): 

2199 """Returns the file name containing the deteted sources associated to the analyzed image, 

2200 placed in the output directory. The suffix is _source.fits. 

2201 

2202 Parameters 

2203 ---------- 

2204 file_name: str 

2205 File name of the image. 

2206 output_directory: str, optional 

2207 If not set, the main output directory is the one the image, 

2208 otherwise the specified directory is taken (default: ""). 

2209 

2210 Returns 

2211 ------- 

2212 sources_file_name: str 

2213 The detected sources file name. 

2214 

2215 Examples 

2216 -------- 

2217 >>> set_sources_file_name("image.fits", output_directory="") 

2218 'image_wcs/image_sources.fits' 

2219 >>> set_sources_file_name("image.png", output_directory="outputs") 

2220 'outputs/image_wcs/image_sources.fits' 

2221 

2222 """ 

2223 output_directory = set_wcs_output_directory(file_name, output_directory=output_directory) 

2224 tag = set_wcs_tag(file_name) 

2225 return os.path.join(output_directory, f"{tag}_sources.fits") 

2226 

2227 

2228def set_gaia_catalog_file_name(file_name, output_directory=""): 

2229 """Returns the file name containing the Gaia catalog associated to the analyzed image, 

2230 placed in the output directory. The suffix is _gaia.ecsv. 

2231 

2232 Parameters 

2233 ---------- 

2234 file_name: str 

2235 File name of the image. 

2236 output_directory: str, optional 

2237 If not set, the main output directory is the one the image, 

2238 otherwise the specified directory is taken (default: ""). 

2239 

2240 Returns 

2241 ------- 

2242 sources_file_name: str 

2243 The Gaia catalog file name. 

2244 

2245 Examples 

2246 -------- 

2247 >>> set_gaia_catalog_file_name("image.fits", output_directory="") 

2248 'image_wcs/image_gaia.ecsv' 

2249 >>> set_gaia_catalog_file_name("image.png", output_directory="outputs") 

2250 'outputs/image_wcs/image_gaia.ecsv' 

2251 

2252 """ 

2253 output_directory = set_wcs_output_directory(file_name, output_directory=output_directory) 

2254 tag = set_wcs_tag(file_name) 

2255 return os.path.join(output_directory, f"{tag}_gaia.ecsv") 

2256 

2257 

2258def load_wcs_from_file(file_name): 

2259 """Open the WCS FITS file and returns a WCS astropy object. 

2260 

2261 Parameters 

2262 ---------- 

2263 file_name: str 

2264 File name of the WCS FITS file. 

2265 

2266 Returns 

2267 ------- 

2268 wcs: WCS 

2269 WCS Astropy object. 

2270 

2271 """ 

2272 # Load the FITS hdulist using astropy.io.fits 

2273 hdulist = fits.open(file_name) 

2274 # Parse the WCS keywords in the primary HDU 

2275 with warnings.catch_warnings(): 

2276 warnings.filterwarnings("ignore") 

2277 wcs = WCS.WCS(hdulist[0].header, fix=False) 

2278 return wcs 

2279 

2280 

2281def imgslice(slicespec): 

2282 """ 

2283 Utility function: convert a FITS slice specification (1-based) 

2284 into the corresponding numpy array slice spec (0-based as python does, xy swapped). 

2285 

2286 Parameters 

2287 ---------- 

2288 slicespec: str 

2289 FITS slice specification with the format [xmin:xmax,ymin:ymax] 

2290 

2291 Returns 

2292 ------- 

2293 slice: slice 

2294 Slice object to be injected in a np.array for instance. 

2295 

2296 Examples 

2297 -------- 

2298 >>> imgslice('[11:522,1:2002]') 

2299 (slice(0, 2002, None), slice(10, 522, None)) 

2300 """ 

2301 

2302 parts = slicespec.replace('[', '').replace(']', '').split(',') 

2303 xbegin, xend = [int(i) for i in parts[0].split(':')] 

2304 ybegin, yend = [int(i) for i in parts[1].split(':')] 

2305 xbegin -= 1 

2306 ybegin -= 1 

2307 return np.s_[ybegin:yend, xbegin:xend] 

2308 

2309 

2310def compute_correlation_matrix(cov): 

2311 rho = np.zeros_like(cov) 

2312 for i in range(cov.shape[0]): 

2313 for j in range(cov.shape[1]): 

2314 rho[i, j] = cov[i, j] / np.sqrt(cov[i, i] * cov[j, j]) 

2315 return rho 

2316 

2317 

2318def plot_correlation_matrix_simple(ax, rho, axis_names=None, ipar=None): 

2319 if ipar is None: 

2320 ipar = np.arange(rho.shape[0]).astype(int) 

2321 im = plt.imshow(rho[ipar[:, None], ipar], interpolation="nearest", cmap='bwr', vmin=-1, vmax=1) 

2322 ax.set_title("Correlation matrix") 

2323 if axis_names is not None: 

2324 names = [axis_names[ip] for ip in ipar] 

2325 plt.xticks(np.arange(ipar.size), names, rotation='vertical', fontsize=11) 

2326 plt.yticks(np.arange(ipar.size), names, fontsize=11) 

2327 cbar = plt.colorbar(im) 

2328 cbar.ax.tick_params(labelsize=9) 

2329 plt.gcf().tight_layout() 

2330 

2331 

2332def resolution_operator(cov, Q, reg): 

2333 N = cov.shape[0] 

2334 return np.eye(N) - reg * cov @ Q 

2335 

2336 

2337def flip_and_rotate_radec_to_image_xy_coordinates(ra, dec, camera_angle=0, flip_ra_sign=1, flip_dec_sign=1): 

2338 """Flip and rotate the vectors in pixels along (RA,DEC) directions to (x, y) image coordinates. 

2339 The parity transformations are applied first, then rotation. 

2340 

2341 Parameters 

2342 ---------- 

2343 ra: array_like 

2344 Vector coordinates along RA direction. 

2345 dec: array_like 

2346 Vector coordinates along DEC direction. 

2347 camera_angle: float 

2348 Angle of the camera between y axis and the North Celestial Pole counterclockwise, or equivalently between 

2349 the x axis and the West direction counterclokwise. Units are degrees. (default: 0). 

2350 flip_ra_sign: -1, 1, optional 

2351 Flip RA axis is value is -1 (default: 1). 

2352 flip_dec_sign: -1, 1, optional 

2353 Flip DEC axis is value is -1 (default: 1). 

2354 

2355 Returns 

2356 ------- 

2357 x: array_like 

2358 Vector coordinates along the x direction. 

2359 y: array_like 

2360 Vector coordinates along the y direction. 

2361 

2362 Examples 

2363 -------- 

2364 

2365 >>> from spectractor import parameters 

2366 >>> parameters.OBS_CAMERA_ROTATION = 180 

2367 >>> parameters.OBS_CAMERA_DEC_FLIP_SIGN = 1 

2368 >>> parameters.OBS_CAMERA_RA_FLIP_SIGN = 1 

2369 

2370 North vector 

2371 

2372 >>> N_ra, N_dec = [0, 1] 

2373 

2374 Compute North direction in (x, y) frame 

2375 

2376 >>> flip_and_rotate_radec_to_image_xy_coordinates(N_ra, N_dec, 0, flip_ra_sign=1, flip_dec_sign=1) 

2377 (0.0, 1.0) 

2378 >>> "%.1f, %.1f" % flip_and_rotate_radec_to_image_xy_coordinates(N_ra, N_dec, 180, flip_ra_sign=1, flip_dec_sign=1) 

2379 '-0.0, -1.0' 

2380 >>> "%.1f, %.1f" % flip_and_rotate_radec_to_image_xy_coordinates(N_ra, N_dec, 90, flip_ra_sign=1, flip_dec_sign=1) 

2381 '-1.0, 0.0' 

2382 >>> "%.1f, %.1f" % flip_and_rotate_radec_to_image_xy_coordinates(N_ra, N_dec, 90, flip_ra_sign=1, flip_dec_sign=-1) 

2383 '1.0, -0.0' 

2384 >>> "%.1f, %.1f" % flip_and_rotate_radec_to_image_xy_coordinates(N_ra, N_dec, 90, flip_ra_sign=-1, flip_dec_sign=-1) 

2385 '1.0, -0.0' 

2386 >>> "%.1f, %.1f" % flip_and_rotate_radec_to_image_xy_coordinates(N_ra, N_dec, 0, 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, 0, flip_ra_sign=-1, flip_dec_sign=1) 

2389 '0.0, 1.0' 

2390 

2391 """ 

2392 flip = np.array([[flip_ra_sign, 0], [0, flip_dec_sign]], dtype=float) 

2393 a = - camera_angle * np.pi / 180 

2394 # minus sign as rotation matrix is apply on the right on the adr vector 

2395 rotation = np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]], dtype=float) 

2396 transformation = flip @ rotation 

2397 x, y = (np.asarray([ra, dec]).T @ transformation).T 

2398 return x, y 

2399 

2400 

2401if __name__ == "__main__": 2401 ↛ 2402line 2401 didn't jump to line 2402, because the condition on line 2401 was never true

2402 import doctest 

2403 

2404 doctest.testmod()