Coverage for spectractor/extractor/psf.py: 15%

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

246 statements  

1import os 

2import numpy as np 

3import matplotlib.pyplot as plt 

4from scipy import special 

5from scipy.interpolate import interp2d 

6 

7from spectractor.tools import plot_image_simple 

8from spectractor import parameters 

9from spectractor.config import set_logger 

10from spectractor.fit.fitter import FitWorkspace, run_minimisation 

11 

12from numba import njit 

13 

14 

15@njit 

16def evaluate_moffat1d_unnormalized(y, amplitude, y_c, gamma, alpha): # pragma: nocover 

17 r"""Compute a 1D Moffat function, whose integral is not normalised to unity. 

18 

19 .. math :: 

20 

21 f(y) \propto \frac{A}{\left[ 1 +\left(\frac{y-y_c}{\gamma}\right)^2 \right]^\alpha} 

22 \quad\text{with}, \alpha > 1/2 

23 

24 Note that this function is defined only for :math:`alpha > 1/2`. The normalisation factor 

25 :math:`\frac{\Gamma(alpha)}{\gamma \sqrt{\pi} \Gamma(alpha -1/2)}` is not included as special functions 

26 are not supported by numba library. 

27 

28 Parameters 

29 ---------- 

30 y: array_like 

31 1D array of pixels :math:`y`, regularly spaced. 

32 amplitude: float 

33 Integral :math:`A` of the function. 

34 y_c: float 

35 Center :math:`y_c` of the function. 

36 gamma: float 

37 Width :math:`\gamma` of the function. 

38 alpha: float 

39 Exponent :math:`\alpha` of the Moffat function. 

40 

41 Returns 

42 ------- 

43 output: array_like 

44 1D array of the function evaluated on the y pixel array. 

45 

46 Examples 

47 -------- 

48 

49 >>> Ny = 50 

50 >>> y = np.arange(Ny) 

51 >>> amplitude = 10 

52 >>> alpha = 2 

53 >>> gamma = 5 

54 >>> a = evaluate_moffat1d_unnormalized(y, amplitude=amplitude, y_c=Ny/2, gamma=gamma, alpha=alpha) 

55 >>> norm = gamma * np.sqrt(np.pi) * special.gamma(alpha - 0.5) / special.gamma(alpha) 

56 >>> a = a / norm 

57 >>> print(f"{np.sum(a):.6f}") 

58 9.967561 

59 

60 .. doctest:: 

61 :hide: 

62 

63 >>> assert np.isclose(np.argmax(a), Ny/2, atol=0.5) 

64 >>> assert np.isclose(np.argmax(a), Ny/2, atol=0.5) 

65 

66 .. plot:: 

67 

68 import numpy as np 

69 import matplotlib.pyplot as plt 

70 from spectractor.extractor.psf import * 

71 Ny = 50 

72 y = np.arange(Ny) 

73 amplitude = 10 

74 a = evaluate_moffat1d(y, amplitude=amplitude, y_c=Ny/2, gamma=5, alpha=2) 

75 plt.plot(a) 

76 plt.grid() 

77 plt.xlabel("y") 

78 plt.ylabel("Moffat") 

79 plt.show() 

80 

81 """ 

82 rr = (y - y_c) * (y - y_c) 

83 rr_gg = rr / (gamma * gamma) 

84 a = (1 + rr_gg) ** -alpha 

85 # dx = y[1] - y[0] 

86 # integral = np.sum(a) * dx 

87 # norm = amplitude 

88 # if integral != 0: 

89 # a /= integral 

90 # a *= amplitude 

91 a *= amplitude 

92 return a 

93 

94 

95@njit 

96def evaluate_moffatgauss1d_unnormalized(y, amplitude, y_c, gamma, alpha, eta_gauss, sigma): # pragma: nocover 

97 r"""Compute a 1D Moffat-Gaussian function, whose integral is not normalised to unity. 

98 

99 .. math :: 

100 

101 f(y) \propto A \left\lbrace 

102 \frac{1}{\left[ 1 +\left(\frac{y-y_c}{\gamma}\right)^2 \right]^\alpha} 

103 - \eta e^{-(y-y_c)^2/(2\sigma^2)}\right\rbrace 

104 \quad\text{ and } \quad \eta < 0, \alpha > 1/2 

105 

106 Note that this function is defined only for :math:`alpha > 1/2`. The normalisation factor for the Moffat 

107 :math:`\frac{\Gamma(alpha)}{\gamma \sqrt{\pi} \Gamma(alpha -1/2)}` is not included as special functions 

108 are not supproted by the numba library. 

109 

110 Parameters 

111 ---------- 

112 y: array_like 

113 1D array of pixels :math:`y`, regularly spaced. 

114 amplitude: float 

115 Integral :math:`A` of the function. 

116 y_c: float 

117 Center :math:`y_c` of the function. 

118 gamma: float 

119 Width :math:`\gamma` of the Moffat function. 

120 alpha: float 

121 Exponent :math:`\alpha` of the Moffat function. 

122 eta_gauss: float 

123 Relative negative amplitude of the Gaussian function. 

124 sigma: float 

125 Width :math:`\sigma` of the Gaussian function. 

126 

127 Returns 

128 ------- 

129 output: array_like 

130 1D array of the function evaluated on the y pixel array. 

131 

132 Examples 

133 -------- 

134 

135 >>> Ny = 50 

136 >>> y = np.arange(Ny) 

137 >>> amplitude = 10 

138 >>> gamma = 5 

139 >>> alpha = 2 

140 >>> eta_gauss = -0.1 

141 >>> sigma = 1 

142 >>> a = evaluate_moffatgauss1d_unnormalized(y, amplitude=amplitude, y_c=Ny/2, gamma=gamma, alpha=alpha, 

143 ... eta_gauss=eta_gauss, sigma=sigma) 

144 >>> norm = gamma*np.sqrt(np.pi)*special.gamma(alpha-0.5)/special.gamma(alpha) + eta_gauss*np.sqrt(2*np.pi)*sigma 

145 >>> a = a / norm 

146 >>> print(f"{np.sum(a):.6f}") 

147 9.966492 

148 

149 .. doctest:: 

150 :hide: 

151 

152 >>> assert np.isclose(np.sum(a), amplitude, atol=0.5) 

153 >>> assert np.isclose(np.argmax(a), Ny/2, atol=0.5) 

154 

155 .. plot:: 

156 

157 import numpy as np 

158 import matplotlib.pyplot as plt 

159 from spectractor.extractor.psf import * 

160 Ny = 50 

161 y = np.arange(Ny) 

162 amplitude = 10 

163 a = evaluate_moffatgauss1d(y, amplitude=amplitude, y_c=Ny/2, gamma=5, alpha=2, eta_gauss=-0.1, sigma=1) 

164 plt.plot(a) 

165 plt.grid() 

166 plt.xlabel("y") 

167 plt.ylabel("Moffat") 

168 plt.show() 

169 

170 """ 

171 rr = (y - y_c) * (y - y_c) 

172 rr_gg = rr / (gamma * gamma) 

173 a = (1 + rr_gg) ** -alpha + eta_gauss * np.exp(-(rr / (2. * sigma * sigma))) 

174 # dx = y[1] - y[0] 

175 # integral = np.sum(a) * dx 

176 # norm = amplitude 

177 # if integral != 0: 

178 # norm /= integral 

179 # a *= norm 

180 a *= amplitude 

181 return a 

182 

183 

184@njit 

185def evaluate_moffat2d(x, y, amplitude, x_c, y_c, gamma, alpha): # pragma: nocover 

186 r"""Compute a 2D Moffat function, whose integral is normalised to unity. 

187 

188 .. math :: 

189 

190 f(x, y) = \frac{A (\alpha - 1)}{\pi \gamma^2} \frac{1}{ 

191 \left[ 1 +\frac{\left(x-x_c\right)^2+\left(y-y_c\right)^2}{\gamma^2} \right]^\alpha} 

192 \quad\text{with}\quad 

193 \int_{-\infty}^{\infty}\int_{-\infty}^{\infty}f(x, y) \mathrm{d}x \mathrm{d}y = A 

194 

195 Note that this function is defined only for :math:`alpha > 1`. 

196 

197 Note that the normalisation of a 2D Moffat function is analytical so it is not expected that 

198 the sum of the output array is equal to :math:`A`, but lower. 

199 

200 Parameters 

201 ---------- 

202 x: array_like 

203 2D array of pixels :math:`x`, regularly spaced. 

204 y: array_like 

205 2D array of pixels :math:`y`, regularly spaced. 

206 amplitude: float 

207 Integral :math:`A` of the function. 

208 x_c: float 

209 X axis center :math:`x_c` of the function. 

210 y_c: float 

211 Y axis center :math:`y_c` of the function. 

212 gamma: float 

213 Width :math:`\gamma` of the function. 

214 alpha: float 

215 Exponent :math:`\alpha` of the Moffat function. 

216 

217 Returns 

218 ------- 

219 output: array_like 

220 2D array of the function evaluated on the y pixel array. 

221 

222 Examples 

223 -------- 

224 

225 >>> Nx = 50 

226 >>> Ny = 50 

227 >>> yy, xx = np.mgrid[:Ny, :Nx] 

228 >>> amplitude = 10 

229 >>> a = evaluate_moffat2d(xx, yy, amplitude=amplitude, x_c=Nx/2, y_c=Ny/2, gamma=5, alpha=2) 

230 >>> print(f"{np.sum(a):.6f}") 

231 9.683129 

232 

233 .. doctest:: 

234 :hide: 

235 

236 >>> assert not np.isclose(np.sum(a), amplitude) 

237 

238 .. plot:: 

239 

240 import numpy as np 

241 import matplotlib.pyplot as plt 

242 from spectractor.extractor.psf import * 

243 Nx = 50 

244 Ny = 50 

245 yy, xx = np.mgrid[:Nx, :Ny] 

246 amplitude = 10 

247 a = evaluate_moffat2d(xx, yy, amplitude=amplitude, y_c=Ny/2, x_c=Nx/2, gamma=5, alpha=2) 

248 im = plt.pcolor(xx, yy, a) 

249 plt.grid() 

250 plt.xlabel("x") 

251 plt.ylabel("y") 

252 plt.colorbar(im, label="Moffat 2D") 

253 plt.show() 

254 

255 """ 

256 rr_gg = ((x - x_c) * (x - x_c) / (gamma * gamma) + (y - y_c) * (y - y_c) / (gamma * gamma)) 

257 a = (1 + rr_gg) ** -alpha 

258 norm = (np.pi * gamma * gamma) / (alpha - 1) 

259 a *= amplitude / norm 

260 return a 

261 

262 

263@njit 

264def evaluate_moffatgauss2d(x, y, amplitude, x_c, y_c, gamma, alpha, eta_gauss, sigma): # pragma: nocover 

265 r"""Compute a 2D Moffat-Gaussian function, whose integral is normalised to unity. 

266 

267 .. math :: 

268 

269 f(x, y) = \frac{A}{\frac{\pi \gamma^2}{\alpha-1} + 2 \pi \eta \sigma^2}\left\lbrace \frac{1}{ 

270 \left[ 1 +\frac{\left(x-x_c\right)^2+\left(y-y_c\right)^2}{\gamma^2} \right]^\alpha} 

271 + \eta e^{-\left[ \left(x-x_c\right)^2+\left(y-y_c\right)^2\right]/(2 \sigma^2)} 

272 \right\rbrace 

273 

274 .. math :: 

275 \quad\text{with}\quad 

276 \int_{-\infty}^{\infty}\int_{-\infty}^{\infty}f(x, y) \mathrm{d}x \mathrm{d}y = A 

277 \quad\text{and} \quad \eta < 0 

278 

279 Note that this function is defined only for :math:`alpha > 1`. 

280 

281 Parameters 

282 ---------- 

283 x: array_like 

284 2D array of pixels :math:`x`, regularly spaced. 

285 y: array_like 

286 2D array of pixels :math:`y`, regularly spaced. 

287 amplitude: float 

288 Integral :math:`A` of the function. 

289 x_c: float 

290 X axis center :math:`x_c` of the function. 

291 y_c: float 

292 Y axis center :math:`y_c` of the function. 

293 gamma: float 

294 Width :math:`\gamma` of the function. 

295 alpha: float 

296 Exponent :math:`\alpha` of the Moffat function. 

297 eta_gauss: float 

298 Relative negative amplitude of the Gaussian function. 

299 sigma: float 

300 Width :math:`\sigma` of the Gaussian function. 

301 

302 Returns 

303 ------- 

304 output: array_like 

305 2D array of the function evaluated on the y pixel array. 

306 

307 Examples 

308 -------- 

309 

310 >>> Nx = 50 

311 >>> Ny = 50 

312 >>> yy, xx = np.mgrid[:Ny, :Nx] 

313 >>> amplitude = 10 

314 >>> a = evaluate_moffatgauss2d(xx, yy, amplitude=amplitude, x_c=Nx/2, y_c=Ny/2, gamma=5, alpha=2, 

315 ... eta_gauss=-0.1, sigma=1) 

316 >>> print(f"{np.sum(a):.6f}") 

317 9.680573 

318 

319 .. doctest:: 

320 :hide: 

321 

322 >>> assert not np.isclose(np.sum(a), amplitude) 

323 

324 .. plot:: 

325 

326 import numpy as np 

327 import matplotlib.pyplot as plt 

328 from spectractor.extractor.psf import * 

329 Nx = 50 

330 Ny = 50 

331 yy, xx = np.mgrid[:Nx, :Ny] 

332 amplitude = 10 

333 a = evaluate_moffatgauss2d(xx, yy, amplitude, Nx/2, Ny/2, gamma=5, alpha=2, eta_gauss=-0.1, sigma=1) 

334 im = plt.pcolor(xx, yy, a) 

335 plt.grid() 

336 plt.xlabel("x") 

337 plt.ylabel("y") 

338 plt.colorbar(im, label="Moffat 2D") 

339 plt.show() 

340 

341 """ 

342 rr = ((x - x_c) * (x - x_c) + (y - y_c) * (y - y_c)) 

343 rr_gg = rr / (gamma * gamma) 

344 a = (1 + rr_gg) ** -alpha + eta_gauss * np.exp(-(rr / (2. * sigma * sigma))) 

345 norm = (np.pi * gamma * gamma) / (alpha - 1) + eta_gauss * 2 * np.pi * sigma * sigma 

346 a *= amplitude / norm 

347 return a 

348 

349 

350class PSF: 

351 """Generic PSF model class. 

352 

353 The PSF models must contain at least the "amplitude", "x_c" and "y_c" parameters as the first three parameters 

354 (in this order) and "saturation" parameter as the last parameter. "amplitude", "x_c" and "y_c" 

355 stands respectively for the general amplitude of the model, the position along the dispersion axis and the 

356 transverse position with respect to the dispersion axis (assumed to be the X axis). 

357 Last "saturation" parameter must be express in the same units as the signal to model and as the "amplitude" 

358 parameter. The PSF models must be normalized to one in total flux divided by the first parameter (amplitude). 

359 Then the PSF model integral is equal to the "amplitude" parameter. 

360 

361 """ 

362 

363 def __init__(self): 

364 self.my_logger = set_logger(self.__class__.__name__) 

365 self.p = np.array([]) 

366 self.param_names = ["amplitude", "x_c", "y_c", "saturation"] 

367 self.axis_names = ["$A$", r"$x_c$", r"$y_c$", "saturation"] 

368 self.bounds = [[]] 

369 self.p_default = np.array([1, 0, 0, 1]) 

370 self.max_half_width = np.inf 

371 

372 def evaluate(self, pixels, p=None): # pragma: no cover 

373 if p is not None: 

374 self.p = np.asarray(p).astype(float) 

375 if pixels.ndim == 3 and pixels.shape[0] == 2: 

376 return np.zeros_like(pixels) 

377 elif pixels.ndim == 1: 

378 return np.zeros_like(pixels) 

379 else: 

380 raise ValueError(f"Pixels array must have dimension 1 or shape=(2,Nx,Ny). Here pixels.ndim={pixels.shape}.") 

381 

382 def apply_max_width_to_bounds(self, max_half_width=None): # pragma: no cover 

383 pass 

384 

385 def fit_psf(self, data, data_errors=None, bgd_model_func=None): 

386 """ 

387 Fit a PSF model on 1D or 2D data. 

388 

389 Parameters 

390 ---------- 

391 data: array_like 

392 1D or 2D array containing the data. 

393 data_errors: np.array, optional 

394 The 1D or 2D array of uncertainties. 

395 bgd_model_func: callable, optional 

396 A 1D or 2D function to model the extracted background (default: None -> null background). 

397 

398 Returns 

399 ------- 

400 fit_workspace: PSFFitWorkspace 

401 The PSFFitWorkspace instance to get info about the fitting. 

402 

403 Examples 

404 -------- 

405 

406 Build a mock PSF2D without background and with random Poisson noise: 

407 

408 >>> p0 = np.array([200000, 20, 30, 5, 2, -0.1, 2, 400000]) 

409 >>> psf0 = MoffatGauss(p0) 

410 >>> yy, xx = np.mgrid[:50, :60] 

411 >>> data = psf0.evaluate(np.array([xx, yy]), p0) 

412 >>> data = np.random.poisson(data) 

413 >>> data_errors = np.sqrt(data+1) 

414 

415 Fit the data in 2D: 

416 

417 >>> p = np.array([150000, 19, 31, 4.5, 2.5, -0.1, 3, 400000]) 

418 >>> psf = MoffatGauss(p) 

419 >>> w = psf.fit_psf(data, data_errors=data_errors, bgd_model_func=None) 

420 >>> w.plot_fit() 

421 

422 .. doctest:: 

423 :hide: 

424 

425 >>> assert w.model is not None 

426 >>> residuals = (w.data-w.model)/w.err 

427 >>> assert w.costs[-1] / w.pixels.size < 1.3 

428 >>> assert np.abs(np.mean(residuals)) < 0.4 

429 >>> assert np.std(residuals) < 1.2 

430 >>> assert np.all(np.isclose(psf.p[1:3], p0[1:3], atol=1e-1)) 

431 

432 Fit the data in 1D: 

433 

434 >>> data1d = data[:,int(p0[1])] 

435 >>> data1d_err = data_errors[:,int(p0[1])] 

436 >>> p = np.array([10000, 20, 32, 4, 3, -0.1, 2, 400000]) 

437 >>> psf1d = MoffatGauss(p) 

438 >>> w = psf1d.fit_psf(data1d, data_errors=data1d_err, bgd_model_func=None) 

439 >>> w.plot_fit() 

440 

441 .. doctest:: 

442 :hide: 

443 

444 >>> assert w.model is not None 

445 >>> residuals = (w.data-w.model)/w.err 

446 >>> assert w.costs[-1] / w.pixels.size < 1.2 

447 >>> assert np.abs(np.mean(residuals)) < 0.2 

448 >>> assert np.std(residuals) < 1.2 

449 >>> assert np.all(np.isclose(w.p[2], p0[2], atol=1e-1)) 

450 

451 .. plot:: 

452 

453 import numpy as np 

454 import matplotlib.pyplot as plt 

455 from spectractor.extractor.psf import * 

456 p = np.array([200000, 20, 30, 5, 2, -0.1, 2, 400000]) 

457 psf = MoffatGauss(p) 

458 yy, xx = np.mgrid[:50, :60] 

459 data = psf.evaluate(np.array([xx, yy]), p) 

460 data = np.random.poisson(data) 

461 data_errors = np.sqrt(data+1) 

462 data = np.random.poisson(data) 

463 data_errors = np.sqrt(data+1) 

464 psf = MoffatGauss(p) 

465 w = psf.fit_psf(data, data_errors=data_errors, bgd_model_func=None) 

466 w.plot_fit() 

467 

468 """ 

469 w = PSFFitWorkspace(self, data, data_errors, bgd_model_func=bgd_model_func, 

470 verbose=False, live_fit=False) 

471 run_minimisation(w, method="newton", ftol=1 / w.pixels.size, xtol=1e-6, niter=50, fix=w.fixed) 

472 self.p = np.copy(w.p) 

473 return w 

474 

475 

476class Moffat(PSF): 

477 

478 def __init__(self, p=None): 

479 PSF.__init__(self) 

480 self.p_default = np.array([1, 0, 0, 3, 2, 1]).astype(float) 

481 if p is not None: 

482 self.p = np.asarray(p).astype(float) 

483 else: 

484 self.p = np.copy(self.p_default) 

485 self.param_names = ["amplitude", "x_c", "y_c", "gamma", "alpha", "saturation"] 

486 self.axis_names = ["$A$", r"$x_c$", r"$y_c$", r"$\gamma$", r"$\alpha$", "saturation"] 

487 self.bounds = np.array([(0, np.inf), (-np.inf, np.inf), (-np.inf, np.inf), (0.1, np.inf), 

488 (1.1, 100), (0, np.inf)]) 

489 

490 def apply_max_width_to_bounds(self, max_half_width=None): 

491 if max_half_width is not None: 

492 self.max_half_width = max_half_width 

493 self.bounds = np.array([(0, np.inf), (-np.inf, np.inf), (0, 2 * self.max_half_width), 

494 (0.1, self.max_half_width), (1.1, 100), (0, np.inf)]) 

495 

496 def evaluate(self, pixels, p=None): 

497 r"""Evaluate the Moffat function. 

498 

499 The function is normalized to have an integral equal to amplitude parameter, with normalisation factor: 

500 

501 .. math:: 

502 

503 f(y) \propto \frac{A \Gamma(alpha)}{\gamma \sqrt{\pi} \Gamma(alpha -1/2)}, 

504 \quad \int_{y_{\text{min}}}^{y_{\text{max}}} f(y) \mathrm{d}y = A 

505 

506 Parameters 

507 ---------- 

508 pixels: list 

509 List containing the X abscisse 2D array and the Y abscisse 2D array. 

510 p: array_like 

511 The parameter array. If None, the array used to instanciate the class is taken. 

512 If given, the class instance parameter array is updated. 

513 

514 Returns 

515 ------- 

516 output: array_like 

517 The PSF function evaluated. 

518 

519 Examples 

520 -------- 

521 >>> p = [2,20,30,4,2,10] 

522 >>> psf = Moffat(p) 

523 >>> yy, xx = np.mgrid[:50, :60] 

524 >>> out = psf.evaluate(pixels=np.array([xx, yy])) 

525 

526 .. plot:: 

527 

528 import matplotlib.pyplot as plt 

529 import numpy as np 

530 from spectractor.extractor.psf import Moffat 

531 p = [2,20,30,4,2,10] 

532 psf = Moffat(p) 

533 yy, xx = np.mgrid[:50, :60] 

534 out = psf.evaluate(pixels=np.array([xx, yy])) 

535 fig = plt.figure(figsize=(5,5)) 

536 plt.imshow(out, origin="lower") 

537 plt.xlabel("X [pixels]") 

538 plt.ylabel("Y [pixels]") 

539 plt.show() 

540 

541 """ 

542 if p is not None: 

543 self.p = np.asarray(p).astype(float) 

544 amplitude, x_c, y_c, gamma, alpha, saturation = self.p 

545 if pixels.ndim == 3 and pixels.shape[0] == 2: 

546 x, y = pixels # .astype(np.float32) # float32 to increase rapidity 

547 return np.clip(evaluate_moffat2d(x, y, amplitude, x_c, y_c, gamma, alpha), 0, saturation) 

548 elif pixels.ndim == 1: 

549 y = np.array(pixels) 

550 norm = gamma * np.sqrt(np.pi) * special.gamma(alpha - 0.5) / special.gamma(alpha) 

551 return np.clip(evaluate_moffat1d_unnormalized(y, amplitude, y_c, gamma, alpha) / norm, 0, saturation) 

552 else: # pragma: no cover 

553 raise ValueError(f"Pixels array must have dimension 1 or shape=(2,Nx,Ny). Here pixels.ndim={pixels.shape}.") 

554 

555 

556class MoffatGauss(PSF): 

557 

558 def __init__(self, p=None): 

559 PSF.__init__(self) 

560 self.p_default = np.array([1, 0, 0, 3, 2, 0, 1, 1]).astype(float) 

561 if p is not None: 

562 self.p = np.asarray(p).astype(float) 

563 else: 

564 self.p = np.copy(self.p_default) 

565 self.param_names = ["amplitude", "x_c", "y_c", "gamma", "alpha", "eta_gauss", "stddev", 

566 "saturation"] 

567 self.axis_names = ["$A$", r"$x_c$", r"$y_c$", r"$\gamma$", r"$\alpha$", r"$\eta$", r"$\sigma$", "saturation"] 

568 self.bounds = np.array([(0, np.inf), (-np.inf, np.inf), (-np.inf, np.inf), (0.1, np.inf), (1.1, 100), 

569 (-1, 0), (0.1, np.inf), (0, np.inf)]) 

570 

571 def apply_max_width_to_bounds(self, max_half_width=None): 

572 if max_half_width is not None: 

573 self.max_half_width = max_half_width 

574 self.bounds = np.array([(0, np.inf), (-np.inf, np.inf), (0, 2 * self.max_half_width), 

575 (0.1, self.max_half_width), (1.1, 100), (-1, 0), (0.1, self.max_half_width), 

576 (0, np.inf)]) 

577 

578 def evaluate(self, pixels, p=None): 

579 r"""Evaluate the MoffatGauss function. 

580 

581 The function is normalized to have an integral equal to amplitude parameter, with normalisation factor: 

582 

583 .. math:: 

584 

585 f(y) \propto \frac{A}{ \frac{\Gamma(alpha)}{\gamma \sqrt{\pi} \Gamma(alpha -1/2)}+\eta\sqrt{2\pi}\sigma}, 

586 \quad \int_{y_{\text{min}}}^{y_{\text{max}}} f(y) \mathrm{d}y = A 

587 

588 Parameters 

589 ---------- 

590 pixels: list 

591 List containing the X abscisse 2D array and the Y abscisse 2D array. 

592 p: array_like 

593 The parameter array. If None, the array used to instanciate the class is taken. 

594 If given, the class instance parameter array is updated. 

595 

596 Returns 

597 ------- 

598 output: array_like 

599 The PSF function evaluated. 

600 

601 Examples 

602 -------- 

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

604 >>> psf = MoffatGauss(p) 

605 >>> yy, xx = np.mgrid[:50, :60] 

606 >>> out = psf.evaluate(pixels=np.array([xx, yy])) 

607 

608 .. plot:: 

609 

610 import matplotlib.pyplot as plt 

611 import numpy as np 

612 from spectractor.extractor.psf import MoffatGauss 

613 p = [2,20,30,4,2,-0.5,1,10] 

614 psf = MoffatGauss(p) 

615 yy, xx = np.mgrid[:50, :60] 

616 out = psf.evaluate(pixels=np.array([xx, yy])) 

617 fig = plt.figure(figsize=(5,5)) 

618 plt.imshow(out, origin="lower") 

619 plt.xlabel("X [pixels]") 

620 plt.ylabel("Y [pixels]") 

621 plt.show() 

622 

623 """ 

624 if p is not None: 

625 self.p = np.asarray(p).astype(float) 

626 amplitude, x_c, y_c, gamma, alpha, eta_gauss, stddev, saturation = self.p 

627 if pixels.ndim == 3 and pixels.shape[0] == 2: 

628 x, y = pixels # .astype(np.float32) # float32 to increase rapidity 

629 return np.clip(evaluate_moffatgauss2d(x, y, amplitude, x_c, y_c, 

630 gamma, alpha, eta_gauss, stddev), 0, saturation) 

631 elif pixels.ndim == 1: 

632 y = np.array(pixels) 

633 norm = gamma * np.sqrt(np.pi) * special.gamma(alpha - 0.5) / special.gamma(alpha) + eta_gauss * np.sqrt( 

634 2 * np.pi) * stddev 

635 return np.clip( 

636 evaluate_moffatgauss1d_unnormalized(y, amplitude, y_c, gamma, alpha, eta_gauss, stddev) / norm, 0, 

637 saturation) 

638 else: # pragma: no cover 

639 raise ValueError(f"Pixels array must have dimension 1 or shape=(2,Nx,Ny). Here pixels.ndim={pixels.shape}.") 

640 

641 

642class Order0(PSF): 

643 

644 def __init__(self, target, p=None): 

645 PSF.__init__(self) 

646 self.p_default = np.array([1, 0, 0, 1, 1]).astype(float) 

647 if p is not None: 

648 self.p = np.asarray(p).astype(float) 

649 else: 

650 self.p = np.copy(self.p_default) 

651 self.param_names = ["amplitude", "x_c", "y_c", "gamma", "saturation"] 

652 self.axis_names = ["$A$", r"$x_c$", r"$y_c$", r"$\gamma$", "saturation"] 

653 self.bounds = np.array([(0, np.inf), (-np.inf, np.inf), (-np.inf, np.inf), (0.5, 5), (0, np.inf)]) 

654 self.psf_func = self.build_interpolated_functions(target=target) 

655 

656 def build_interpolated_functions(self, target): 

657 """Interpolate the order 0 image and make 1D and 2D functions centered on its centroid, with varying width 

658 and normalized to get an integral equal to unity. 

659 

660 Parameters 

661 ---------- 

662 target: Target 

663 The target with a target.image attribute to interpolate. 

664 

665 Returns 

666 ------- 

667 func: Callable 

668 The 2D interpolated function centered in (target.image_x0, target.image_y0). 

669 """ 

670 xx = np.arange(0, target.image.shape[1]) - target.image_x0 

671 yy = np.arange(0, target.image.shape[0]) - target.image_y0 

672 data = target.image / np.sum(target.image) 

673 tmp_func = interp2d(xx, yy, data, bounds_error=False, fill_value=None) 

674 

675 def func(x, y, amplitude, x_c, y_c, gamma): 

676 return amplitude * tmp_func((x - x_c)/gamma, (y - y_c)/gamma) 

677 

678 return func 

679 

680 def apply_max_width_to_bounds(self, max_half_width=None): 

681 if max_half_width is not None: 

682 self.max_half_width = max_half_width 

683 self.bounds = np.array([(0, np.inf), (-np.inf, np.inf), (0, 2 * self.max_half_width), (0.5, 5), (0, np.inf)]) 

684 

685 def evaluate(self, pixels, p=None): 

686 r"""Evaluate the Order 0 interpolated function. 

687 

688 The function is normalized to have an integral equal to amplitude parameter. 

689 

690 Parameters 

691 ---------- 

692 pixels: list 

693 List containing the X abscisse 2D array and the Y abscisse 2D array. 

694 p: array_like 

695 The parameter array. If None, the array used to instanciate the class is taken. 

696 If given, the class instance parameter array is updated. 

697 

698 Returns 

699 ------- 

700 output: array_like 

701 The PSF function evaluated. 

702 

703 Examples 

704 -------- 

705 >>> from spectractor.extractor.images import Image, find_target 

706 >>> im = Image('tests/data/reduc_20170605_028.fits', target_label="PNG321.0+3.9") 

707 >>> im.plot_image() 

708 >>> guess = [820, 580] 

709 >>> parameters.VERBOSE = True 

710 >>> parameters.DEBUG = True 

711 >>> x0, y0 = find_target(im, guess) 

712 

713 >>> p = [1,40,50,1,1e20] 

714 >>> psf = Order0(target=im.target, p=p) 

715 

716 2D evaluation: 

717 

718 >>> yy, xx = np.mgrid[:80, :100] 

719 >>> out = psf.evaluate(pixels=np.array([xx, yy])) 

720 

721 1D evaluation: 

722 

723 >>> out = psf.evaluate(pixels=np.arange(100)) 

724 

725 .. plot:: 

726 

727 import matplotlib.pyplot as plt 

728 import numpy as np 

729 from spectractor.extractor.psf import Moffat, Order0 

730 from spectractor.extractor.images import Image, find_target 

731 im = Image('tests/data/reduc_20170605_028.fits', target_label="PNG321.0+3.9") 

732 im.plot_image() 

733 guess = [820, 580] 

734 parameters.VERBOSE = True 

735 parameters.DEBUG = True 

736 x0, y0 = find_target(im, guess) 

737 p = [1,40,50,1,1e20] 

738 psf = Order0(target=im.target, p=p) 

739 yy, xx = np.mgrid[:80, :100] 

740 out = psf.evaluate(pixels=np.array([xx, yy])) 

741 fig = plt.figure(figsize=(5,5)) 

742 plt.imshow(out, origin="lower") 

743 plt.xlabel("X [pixels]") 

744 plt.ylabel("Y [pixels]") 

745 plt.grid() 

746 plt.show() 

747 

748 """ 

749 if p is not None: 

750 self.p = np.asarray(p).astype(float) 

751 amplitude, x_c, y_c, gamma, saturation = self.p 

752 if pixels.ndim == 3 and pixels.shape[0] == 2: 

753 x, y = pixels # .astype(np.float32) # float32 to increase rapidity 

754 return np.clip(self.psf_func(x[0], y[:, 0], amplitude, x_c, y_c, gamma), 0, saturation) 

755 elif pixels.ndim == 1: 

756 y = np.array(pixels) 

757 out = self.psf_func(x_c, y, amplitude, x_c, y_c, gamma).T[0] 

758 out *= amplitude / np.sum(out) 

759 return np.clip(out, 0, saturation) 

760 else: # pragma: no cover 

761 raise ValueError(f"Pixels array must have dimension 1 or shape=(2,Nx,Ny). Here pixels.ndim={pixels.shape}.") 

762 

763 

764class PSFFitWorkspace(FitWorkspace): 

765 """Generic PSF fitting workspace. 

766 

767 """ 

768 

769 def __init__(self, psf, data, data_errors, bgd_model_func=None, file_name="", 

770 nwalkers=18, nsteps=1000, burnin=100, nbins=10, 

771 verbose=0, plot=False, live_fit=False, truth=None): 

772 """ 

773 

774 Parameters 

775 ---------- 

776 psf 

777 data: array_like 

778 The data array (background subtracted) of dimension 1 or 2. 

779 data_errors 

780 bgd_model_func 

781 file_name 

782 nwalkers 

783 nsteps 

784 burnin 

785 nbins 

786 verbose 

787 plot 

788 live_fit 

789 truth 

790 

791 Examples 

792 -------- 

793 

794 Build a mock spectrogram with random Poisson noise: 

795 

796 >>> p = np.array([100, 50, 50, 3, 2, -0.1, 2, 200]) 

797 >>> psf = MoffatGauss(p) 

798 >>> data = psf.evaluate(p) 

799 >>> data_errors = np.sqrt(data+1) 

800 

801 Fit the data: 

802 

803 >>> w = PSFFitWorkspace(psf, data, data_errors, bgd_model_func=None, verbose=True) 

804 

805 """ 

806 FitWorkspace.__init__(self, file_name, nwalkers, nsteps, burnin, nbins, verbose=verbose, plot=plot, 

807 live_fit=live_fit, truth=truth) 

808 self.my_logger = set_logger(self.__class__.__name__) 

809 if data.shape != data_errors.shape: 

810 raise ValueError(f"Data and uncertainty arrays must have the same shapes. " 

811 f"Here data.shape={data.shape} and data_errors.shape={data_errors.shape}.") 

812 self.psf = psf 

813 self.data = data 

814 self.err = data_errors 

815 self.bgd_model_func = bgd_model_func 

816 self.p = np.copy(self.psf.p) # [1:]) 

817 self.guess = np.copy(self.psf.p) 

818 self.saturation = self.psf.p[-1] 

819 self.fixed = [False] * len(self.p) 

820 self.fixed[-1] = True # fix saturation parameter 

821 self.input_labels = list(np.copy(self.psf.param_names)) # [1:])) 

822 self.axis_names = list(np.copy(self.psf.axis_names)) # [1:])) 

823 self.bounds = self.psf.bounds # [1:] 

824 self.nwalkers = max(2 * self.ndim, nwalkers) 

825 

826 # prepare the fit 

827 if data.ndim == 2: 

828 self.Ny, self.Nx = self.data.shape 

829 self.psf.apply_max_width_to_bounds(self.Ny) 

830 yy, xx = np.mgrid[:self.Ny, :self.Nx] 

831 self.pixels = np.asarray([xx, yy]) 

832 # flat data for fitworkspace 

833 self.data = self.data.flatten() 

834 self.err = self.err.flatten() 

835 elif data.ndim == 1: 

836 self.Ny = self.data.size 

837 self.Nx = 1 

838 self.psf.apply_max_width_to_bounds(self.Ny) 

839 self.pixels = np.arange(self.Ny) 

840 self.fixed[1] = True 

841 else: 

842 raise ValueError(f"Data array must have dimension 1 or 2. Here pixels.ndim={data.ndim}.") 

843 

844 # update bounds 

845 self.bounds = self.psf.bounds # [1:] 

846 total_flux = np.sum(data) 

847 self.bounds[0] = (0.1 * total_flux, 2 * total_flux) 

848 

849 # error matrix 

850 # here image uncertainties are assumed to be uncorrelated 

851 # (which is not exactly true in rotated images) 

852 self.W = 1. / (self.err * self.err) 

853 

854 def simulate(self, *psf_params): 

855 """ 

856 Compute a PSF model given PSF parameters and minimizing 

857 amplitude parameter given a data array. 

858 

859 Parameters 

860 ---------- 

861 psf_params: array_like 

862 PSF shape parameter array (all parameters except amplitude). 

863 

864 Examples 

865 -------- 

866 

867 Build a mock PSF2D without background and with random Poisson noise: 

868 

869 >>> p = np.array([200000, 20, 30, 5, 2, -0.1, 2, 400000]) 

870 >>> psf = MoffatGauss(p) 

871 >>> yy, xx = np.mgrid[:50, :60] 

872 >>> data = psf.evaluate(np.array([xx, yy]), p) 

873 >>> data = np.random.poisson(data) 

874 >>> data_errors = np.sqrt(data+1) 

875 

876 Fit the data in 2D: 

877 

878 >>> w = PSFFitWorkspace(psf, data, data_errors, bgd_model_func=None, verbose=True) 

879 >>> x, mod, mod_err = w.simulate(*p) 

880 >>> w.plot_fit() 

881 

882 .. doctest:: 

883 :hide: 

884 

885 >>> assert mod is not None 

886 >>> assert np.mean(np.abs(mod.reshape(data.shape)-data)/data_errors) < 1 

887 

888 Fit the data in 1D: 

889 

890 >>> data1d = data[:,int(p[1])] 

891 >>> data1d_err = data_errors[:,int(p[1])] 

892 >>> psf.p[0] = p[0] / 10.5 

893 >>> w = PSFFitWorkspace(psf, data1d, data1d_err, bgd_model_func=None, verbose=True) 

894 >>> x, mod, mod_err = w.simulate(*psf.p) 

895 >>> w.plot_fit() 

896 

897 .. doctest:: 

898 :hide: 

899 

900 >>> assert mod is not None 

901 >>> assert np.mean(np.abs(mod-data1d)/data1d_err) < 1 

902 

903 .. plot:: 

904 

905 import numpy as np 

906 import matplotlib.pyplot as plt 

907 from spectractor.extractor.psf import * 

908 p = np.array([2000, 20, 30, 5, 2, -0.1, 2, 400]) 

909 psf = MoffatGauss(p) 

910 yy, xx = np.mgrid[:50, :60] 

911 data = psf.evaluate(np.array([xx, yy]), p) 

912 data = np.random.poisson(data) 

913 data_errors = np.sqrt(data+1) 

914 data = np.random.poisson(data) 

915 data_errors = np.sqrt(data+1) 

916 w = PSFFitWorkspace(psf, data, data_errors, bgd_model_func=bgd_model_func, verbose=True) 

917 x, mod, mod_err = w.simulate(*p[:-1]) 

918 w.plot_fit() 

919 

920 """ 

921 # Initialization of the regression 

922 self.p = np.copy(psf_params) 

923 # if not self.fixed_amplitude: 

924 # # Matrix filling 

925 # M = self.psf.evaluate(self.pixels, p=np.array([1] + list(self.p))).flatten() 

926 # M_dot_W_dot_M = M.T @ self.W @ M 

927 # # Regression 

928 # amplitude = M.T @ (self.W * self.data) / M_dot_W_dot_M 

929 # self.p[0] = amplitude 

930 # Save results 

931 self.model = self.psf.evaluate(self.pixels, p=self.p).flatten() 

932 self.model_err = np.zeros_like(self.model) 

933 return self.pixels, self.model, self.model_err 

934 

935 def plot_fit(self): 

936 if self.Nx == 1: 

937 fig, ax = plt.subplots(2, 1, figsize=(6, 6), sharex='all', gridspec_kw={'height_ratios': [5, 1]}) 

938 data = np.copy(self.data) 

939 if self.bgd_model_func is not None: 

940 data = data + self.bgd_model_func(self.pixels) 

941 ax[0].errorbar(self.pixels, data, yerr=self.err, fmt='ro', label="Data") 

942 if len(self.outliers) > 0: 

943 ax[0].errorbar(self.outliers, data[self.outliers], yerr=self.err[self.outliers], fmt='go', 

944 label=rf"Outliers ({self.sigma_clip}$\sigma$)") 

945 if self.bgd_model_func is not None: 

946 ax[0].plot(self.pixels, self.bgd_model_func(self.pixels), 'b--', label="fitted bgd") 

947 if self.guess is not None: 

948 if self.bgd_model_func is not None: 

949 ax[0].plot(self.pixels, self.psf.evaluate(self.pixels, p=self.guess) 

950 + self.bgd_model_func(self.pixels), 'k--', label="Guess") 

951 else: 

952 ax[0].plot(self.pixels, self.psf.evaluate(self.pixels, p=self.guess), 

953 'k--', label="Guess") 

954 self.psf.p = np.copy(self.p) 

955 model = np.copy(self.model) 

956 # if self.bgd_model_func is not None: 

957 # model = self.model + self.bgd_model_func(self.pixels) 

958 ax[0].plot(self.pixels, model, 'b-', label="Model") 

959 ylim = list(ax[0].get_ylim()) 

960 ylim[1] = 1.2 * np.max(self.model) 

961 ax[0].set_ylim(ylim) 

962 ax[0].set_ylabel('Transverse profile') 

963 ax[0].legend(loc=2, numpoints=1) 

964 ax[0].grid(True) 

965 txt = "" 

966 for ip, p in enumerate(self.input_labels): 

967 txt += f'{p}: {self.p[ip]:.4g}\n' 

968 ax[0].text(0.95, 0.95, txt, horizontalalignment='right', verticalalignment='top', transform=ax[0].transAxes) 

969 # residuals 

970 residuals = (data - model) / self.err 

971 residuals_err = np.ones_like(self.err) 

972 ax[1].errorbar(self.pixels, residuals, yerr=residuals_err, fmt='ro') 

973 if len(self.outliers) > 0: 

974 residuals_outliers = (data[self.outliers] - model[self.outliers]) / self.err[self.outliers] 

975 residuals_outliers_err = np.ones_like(residuals_outliers) 

976 ax[1].errorbar(self.outliers, residuals_outliers, yerr=residuals_outliers_err, fmt='go') 

977 ax[1].axhline(0, color='b') 

978 ax[1].grid(True) 

979 std = np.std(residuals) 

980 ax[1].set_ylim([-3. * std, 3. * std]) 

981 ax[1].set_xlabel(ax[0].get_xlabel()) 

982 ax[1].set_ylabel('(data-fit)/err') 

983 ax[0].set_xticks(ax[1].get_xticks()[1:-1]) 

984 ax[0].get_yaxis().set_label_coords(-0.1, 0.5) 

985 ax[1].get_yaxis().set_label_coords(-0.1, 0.5) 

986 # fig.tight_layout() 

987 # fig.subplots_adjust(wspace=0, hspace=0) 

988 else: 

989 data = np.copy(self.data).reshape((self.Ny, self.Nx)) 

990 model = np.copy(self.model).reshape((self.Ny, self.Nx)) 

991 err = np.copy(self.err).reshape((self.Ny, self.Nx)) 

992 gs_kw = dict(width_ratios=[3, 0.15], height_ratios=[1, 1, 1, 1]) 

993 fig, ax = plt.subplots(nrows=4, ncols=2, figsize=(5, 7), gridspec_kw=gs_kw) 

994 norm = np.nanmax(self.data) 

995 plot_image_simple(ax[0, 0], data=model / norm, aspect='auto', cax=ax[0, 1], vmin=0, vmax=1, 

996 units='1/max(data)') 

997 ax[0, 0].set_title("Model", fontsize=10, loc='center', color='white', y=0.8) 

998 plot_image_simple(ax[1, 0], data=data / norm, title='Data', aspect='auto', 

999 cax=ax[1, 1], vmin=0, vmax=1, units='1/max(data)') 

1000 ax[1, 0].set_title('Data', fontsize=10, loc='center', color='white', y=0.8) 

1001 residuals = (data - model) 

1002 # residuals_err = self.spectrum.spectrogram_err / self.model 

1003 norm = err 

1004 residuals /= norm 

1005 std = float(np.std(residuals)) 

1006 plot_image_simple(ax[2, 0], data=residuals, vmin=-5 * std, vmax=5 * std, title='(Data-Model)/Err', 

1007 aspect='auto', cax=ax[2, 1], units='', cmap="bwr") 

1008 ax[2, 0].set_title('(Data-Model)/Err', fontsize=10, loc='center', color='black', y=0.8) 

1009 ax[2, 0].text(0.05, 0.05, f'mean={np.mean(residuals):.3f}\nstd={np.std(residuals):.3f}', 

1010 horizontalalignment='left', verticalalignment='bottom', 

1011 color='black', transform=ax[2, 0].transAxes) 

1012 ax[0, 0].set_xticks(ax[2, 0].get_xticks()[1:-1]) 

1013 ax[0, 1].get_yaxis().set_label_coords(3.5, 0.5) 

1014 ax[1, 1].get_yaxis().set_label_coords(3.5, 0.5) 

1015 ax[2, 1].get_yaxis().set_label_coords(3.5, 0.5) 

1016 ax[3, 1].remove() 

1017 ax[3, 0].plot(np.arange(self.Nx), data.sum(axis=0), label='Data') 

1018 ax[3, 0].plot(np.arange(self.Nx), model.sum(axis=0), label='Model') 

1019 ax[3, 0].set_ylabel('Transverse sum') 

1020 ax[3, 0].set_xlabel(r'X [pixels]') 

1021 ax[3, 0].legend(fontsize=7) 

1022 ax[3, 0].grid(True) 

1023 if self.live_fit: # pragma: no cover 

1024 plt.draw() 

1025 plt.pause(1e-8) 

1026 plt.close() 

1027 else: 

1028 if parameters.DISPLAY: 

1029 plt.show() 

1030 else: 

1031 plt.close(fig) 

1032 if parameters.SAVE: # pragma: no cover 

1033 figname = os.path.splitext(self.filename)[0] + "_bestfit.pdf" 

1034 self.my_logger.info(f"\n\tSave figure {figname}.") 

1035 fig.savefig(figname, dpi=100, bbox_inches='tight') 

1036 if parameters.PdfPages: 

1037 parameters.PdfPages.savefig() 

1038 

1039 

1040def load_PSF(psf_type=parameters.PSF_TYPE, target=None): 

1041 """Load the PSF model with a keyword. 

1042 

1043 Parameters 

1044 ---------- 

1045 psf_type: str 

1046 PSF model keyword (default: parameters.PSF_TYPE). 

1047 target: Target, optional 

1048 The Target instance to make Order0 PSF model (default: None). 

1049 

1050 Returns 

1051 ------- 

1052 psf: PSF 

1053 An instance of the selected PSF model. 

1054 

1055 Examples 

1056 -------- 

1057 

1058 >>> load_PSF(psf_type="Moffat") # doctest: +ELLIPSIS 

1059 <....Moffat object at ...> 

1060 >>> load_PSF(psf_type="MoffatGauss") # doctest: +ELLIPSIS 

1061 <....MoffatGauss object at ...> 

1062 

1063 """ 

1064 if psf_type == "Moffat": 

1065 psf = Moffat() 

1066 elif psf_type == "MoffatGauss": 

1067 psf = MoffatGauss() 

1068 elif psf_type == "Order0": 

1069 if target is None: 

1070 raise ValueError(f"A Target instance must be given when PSF_TYPE='Order0'. I got target={target}.") 

1071 psf = Order0(target=target) 

1072 else: 

1073 raise ValueError(f"Unknown PSF_TYPE={psf_type}. Must be either Moffat or MoffatGauss.") 

1074 return psf 

1075 

1076 

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

1078 import doctest 

1079 

1080 doctest.testmod()