Coverage for spectractor/extractor/chromaticpsf.py: 6%

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

638 statements  

1import numpy as np 

2import os 

3import matplotlib.pyplot as plt 

4from matplotlib import cm 

5from tqdm import tqdm 

6import copy 

7 

8from scipy.interpolate import interp1d 

9from scipy import sparse 

10 

11from astropy.table import Table 

12 

13from spectractor.tools import (fit_poly1d, plot_image_simple, compute_fwhm) 

14from spectractor.extractor.background import extract_spectrogram_background_sextractor 

15from spectractor.extractor.psf import PSF, PSFFitWorkspace, MoffatGauss, Moffat 

16from spectractor import parameters 

17from spectractor.config import set_logger 

18from spectractor.fit.fitter import FitWorkspace, run_minimisation, run_minimisation_sigma_clipping, RegFitWorkspace 

19 

20 

21class ChromaticPSF: 

22 """Class to store a PSF evolving with wavelength. 

23 

24 The wavelength evolution is stored in an Astropy table instance. Whatever the PSF model, the common keywords are: 

25 

26 * lambdas: the wavelength [nm] 

27 * Dx: the distance along X axis to order 0 position of the PSF model centroid [pixels] 

28 * Dy: the distance along Y axis to order 0 position of the PSF model centroid [pixels] 

29 * Dy_disp_axis: the distance along Y axis to order 0 position of the mean dispersion axis [pixels] 

30 * flux_sum: the transverse sum of the data flux [spectrogram units] 

31 * flux_integral: the integral of the best fitting PSF model to the data (should be equal to the amplitude parameter 

32 of the PSF model if the model is correclty normalized to one) [spectrogram units] 

33 * flux_err: the uncertainty on flux_sum [spectrogram units] 

34 * fwhm: the FWHM of the best fitting PSF model [pixels] 

35 * Dy_fwhm_sup: the distance along Y axis to order 0 position of the upper FWHM edge [pixels] 

36 * Dy_fwhm_inf: the distance along Y axis to order 0 position of the lower FWHM edge [pixels] 

37 

38 Then all the specific parameter of the PSF model are stored in other columns with their wavelength evolution 

39 (read from PSF.param_names attribute). 

40 

41 A saturation level should be specified in data units. 

42 

43 """ 

44 

45 def __init__(self, psf, Nx, Ny, x0=0, y0=None, deg=4, saturation=None, file_name=''): 

46 """Initialize a ChromaticPSF instance. 

47 

48 

49 Parameters 

50 ---------- 

51 psf: PSF 

52 The PSF class model to build the PSF. 

53 Nx: int 

54 The number of pixels along the dispersion axis. 

55 Ny: int 

56 The number of pixels transverse to the dispersion axis. 

57 x0: float 

58 Relative position to pixel (0, 0) of the order 0 position along x (default: 0). 

59 y0: float 

60 Relative position to pixel (0, 0) of the order 0 position along y. 

61 If None, y0 is set at Ny/2 (default: None). 

62 deg: int, optional 

63 The degree of the polynomial functions to model the chromatic evolution 

64 of the PSF shape parameters (default: 4). 

65 saturation: float, optional 

66 The image saturation level (default: None). 

67 file_name: str, optional 

68 A path to a CSV file containing a ChromaticPSF table and load it (default: ""). 

69 """ 

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

71 self.psf = psf 

72 self.deg = -1 

73 self.degrees = {} 

74 self.set_polynomial_degrees(deg) 

75 self.Nx = Nx 

76 self.Ny = Ny 

77 self.x0 = x0 

78 if y0 is None: 

79 y0 = Ny / 2 

80 self.y0 = y0 

81 self.profile_params = np.zeros((Nx, len(self.psf.param_names))) 

82 self.pixels = np.mgrid[:Nx, :Ny] 

83 if file_name == '': 

84 arr = np.zeros((Nx, len(self.psf.param_names) + 10)) 

85 self.table = Table(arr, names=['lambdas', 'Dx', 'Dy', 'Dy_disp_axis', 'flux_sum', 'flux_integral', 

86 'flux_err', 'fwhm', 'Dy_fwhm_sup', 'Dy_fwhm_inf'] + list( 

87 self.psf.param_names)) 

88 else: 

89 self.table = Table.read(file_name) 

90 self.psf_param_start_index = 10 

91 self.n_poly_params = len(self.table) 

92 self.fitted_pixels = np.arange(len(self.table)).astype(int) 

93 self.saturation = saturation 

94 if saturation is None: 

95 self.saturation = 1e20 

96 self.my_logger.warning(f"\n\tSaturation level should be given to instanciate the ChromaticPSF " 

97 f"object. self.saturation is set arbitrarily to 1e20. Good luck.") 

98 for name in self.psf.param_names: 

99 self.n_poly_params += self.degrees[name] + 1 

100 self.poly_params = np.zeros(self.n_poly_params) 

101 self.poly_params_labels = [] # [f"a{k}" for k in range(self.poly_params.size)] 

102 self.poly_params_names = [] # "$a_{" + str(k) + "}$" for k in range(self.poly_params.size)] 

103 for ip, p in enumerate(self.psf.param_names): 

104 if ip == 0: 

105 self.poly_params_labels += [f"{p}^{k}" for k in range(len(self.table))] 

106 self.poly_params_names += \ 

107 ["$" + self.psf.axis_names[ip].replace("$", "") + "{(" + str(k) + ")}$" 

108 for k in range(len(self.table))] 

109 else: 

110 for k in range(self.degrees[p] + 1): 

111 self.poly_params_labels.append(f"{p}_{k}") 

112 self.poly_params_names.append("$" + self.psf.axis_names[ip].replace("$", "") 

113 + "^{(" + str(k) + ")}$") 

114 self.opt_reg = parameters.PSF_FIT_REG_PARAM 

115 self.cov_matrix = np.zeros((Nx, Nx)) 

116 if file_name != "": 

117 self.poly_params = self.from_table_to_poly_params() 

118 

119 def set_polynomial_degrees(self, deg): 

120 self.deg = deg 

121 self.degrees = {key: deg for key in self.psf.param_names} 

122 self.degrees['saturation'] = 0 

123 

124 def generate_test_poly_params(self): 

125 """ 

126 A set of parameters to define a test spectrogram. PSF function must be MoffatGauss 

127 for this test example. 

128 

129 Returns 

130 ------- 

131 profile_params: array 

132 The list of the test parameters 

133 

134 Examples 

135 -------- 

136 

137 >>> psf = MoffatGauss() 

138 >>> s = ChromaticPSF(psf, Nx=5, Ny=4, deg=1, saturation=20000) 

139 >>> params = s.generate_test_poly_params() 

140 

141 .. doctest:: 

142 :hide: 

143 >>> assert(np.all(np.isclose(params,[10, 50, 100, 150, 200, 0, 0, 0, 0, 5, 0, 2, 0, -0.4, -0.4,1,0,20000]))) 

144 

145 """ 

146 if not isinstance(self.psf, MoffatGauss) and not isinstance(self.psf, Moffat): 

147 raise TypeError(f"In this test function, PSF model must be MoffatGauss or Moffat. Gave {type(self.psf)}.") 

148 params = [50 * i for i in range(self.Nx)] 

149 params[0] = 10 

150 # add absorption lines 

151 if self.Nx > 80: 

152 params = list(np.array(params) 

153 - 3000 * np.exp(-((np.arange(self.Nx) - 70) / 2) ** 2) 

154 - 2000 * np.exp(-((np.arange(self.Nx) - 50) / 2) ** 2)) 

155 params += [0.] * (self.degrees['x_c'] - 1) + [0, 0] # x mean 

156 params += [0.] * (self.degrees['y_c'] - 1) + [0, 0] # y mean 

157 params += [0.] * (self.degrees['gamma'] - 1) + [0, 5] # gamma 

158 params += [0.] * (self.degrees['alpha'] - 1) + [0, 2] # alpha 

159 if isinstance(self.psf, MoffatGauss): 

160 params += [0.] * (self.degrees['eta_gauss'] - 1) + [-0.4, -0.4] # eta_gauss 

161 params += [0.] * (self.degrees['stddev'] - 1) + [0, 1] # stddev 

162 params += [self.saturation] # saturation 

163 poly_params = np.zeros_like(params) 

164 poly_params[:self.Nx] = params[:self.Nx] 

165 index = self.Nx - 1 

166 for name in self.psf.param_names: 

167 if name == 'amplitude': 

168 continue 

169 else: 

170 shift = self.degrees[name] + 1 

171 c = np.polynomial.legendre.poly2leg(params[index + shift:index:-1]) 

172 coeffs = np.zeros(shift) 

173 coeffs[:c.size] = c 

174 poly_params[index + 1:index + shift + 1] = coeffs 

175 index = index + shift 

176 return poly_params 

177 

178 def build_spectrogram_image(self, poly_params, mode="1D"): 

179 """Simulate a 2D spectrogram of size Nx times Ny. 

180 

181 Given a set of polynomial parameters defining the chromatic PSF model, a 2D spectrogram 

182 is produced either summing transverse 1D PSF profiles along the dispersion axis, or 

183 full 2D PSF profiles. 

184 

185 Parameters 

186 ---------- 

187 poly_params: array_like 

188 Parameter array of the model, in the form: 

189 - Nx first parameters are amplitudes for the Moffat transverse profiles 

190 - next parameters are polynomial coefficients for all the PSF parameters in the same order 

191 as in PSF definition, except amplitude. 

192 mode: str, optional 

193 Set the evaluation mode: either transverse 1D PSF profile (mode="1D") or full 2D PSF profile (mode="2D"). 

194 

195 Returns 

196 ------- 

197 output: array 

198 A 2D array with the model. 

199 

200 Examples 

201 -------- 

202 

203 >>> psf = MoffatGauss() 

204 >>> s = ChromaticPSF(psf, Nx=100, Ny=20, deg=4, saturation=20000) 

205 >>> poly_params = s.generate_test_poly_params() 

206 

207 1D evaluation: 

208 

209 .. doctest:: 

210 

211 >>> output = s.build_spectrogram_image(poly_params, mode="1D") 

212 >>> im = plt.imshow(output, origin='lower') # doctest: +ELLIPSIS 

213 >>> plt.colorbar(im) # doctest: +ELLIPSIS 

214 <matplotlib.colorbar.Colorbar object at 0x...> 

215 >>> plt.show() 

216 

217 .. plot :: 

218 

219 from spectractor.extractor.chromaticpsf import ChromaticPSF 

220 from spectractor.extractor.psf import MoffatGauss 

221 psf = MoffatGauss() 

222 s = ChromaticPSF(psf, Nx=100, Ny=20, deg=4, saturation=20000) 

223 poly_params = s.generate_test_poly_params() 

224 output = s.build_spectrogram_image(poly_params, mode="1D") 

225 im = plt.imshow(output, origin='lower') 

226 plt.colorbar(im) 

227 plt.show() 

228 

229 2D evaluation: 

230 

231 .. doctest:: 

232 

233 >>> output = s.build_spectrogram_image(poly_params, mode="2D") 

234 >>> im = plt.imshow(output, origin='lower') # doctest: +ELLIPSIS 

235 >>> plt.colorbar(im) # doctest: +ELLIPSIS 

236 <matplotlib.colorbar.Colorbar object at 0x...> 

237 >>> plt.show() 

238 

239 .. plot :: 

240 

241 from spectractor.extractor.chromaticpsf import ChromaticPSF 

242 from spectractor.extractor.psf import MoffatGauss 

243 psf = MoffatGauss() 

244 s = ChromaticPSF(psf, Nx=100, Ny=20, deg=4, saturation=20000) 

245 poly_params = s.generate_test_poly_params() 

246 output = s.build_spectrogram_image(poly_params, mode="2D") 

247 im = plt.imshow(output, origin='lower') 

248 plt.colorbar(im) 

249 plt.show() 

250 

251 """ 

252 if mode == "2D": 

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

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

255 elif mode == "1D": 

256 pixels = np.arange(self.Ny) 

257 else: 

258 raise ValueError(f"Unknown evaluation mode={mode}. Must be '1D' or '2D'.") 

259 self.psf.apply_max_width_to_bounds(max_half_width=self.Ny) 

260 profile_params = self.from_poly_params_to_profile_params(poly_params, apply_bounds=True) 

261 profile_params[:, 1] = np.arange(self.Nx) # replace x_c 

262 output = np.zeros((self.Ny, self.Nx)) 

263 if mode == "1D": 

264 for x in range(self.Nx): 

265 output[:, x] = self.psf.evaluate(pixels, p=profile_params[x, :]) 

266 elif mode == "2D": 

267 for x in range(self.Nx): 

268 output += self.psf.evaluate(pixels, p=profile_params[x, :]) 

269 return np.clip(output, 0, self.saturation) 

270 

271 def build_psf_cube(self, pixels, profile_params, fwhmx_clip=parameters.PSF_FWHM_CLIP, 

272 fwhmy_clip=parameters.PSF_FWHM_CLIP, dtype="float64"): 

273 Ny_pix, Nx_pix = pixels[0].shape 

274 psf_cube = np.zeros((len(profile_params), Ny_pix, Nx_pix), dtype=dtype) 

275 fwhms = self.table["fwhm"] 

276 for x in range(len(profile_params)): 

277 xc, yc = profile_params[x, 1:3] 

278 if xc < - fwhmx_clip * fwhms[x]: 

279 continue 

280 if xc > Nx_pix + fwhmx_clip * fwhms[x]: 

281 break 

282 xmin = max(0, int(xc - max(fwhmx_clip * fwhms[x], parameters.PIXWIDTH_SIGNAL))) 

283 xmax = min(Nx_pix, int(xc + max(parameters.PIXWIDTH_SIGNAL, fwhmx_clip * fwhms[x]))) 

284 ymin = max(0, int(yc - max(parameters.PIXWIDTH_SIGNAL, fwhmy_clip * fwhms[x]))) 

285 ymax = min(Ny_pix, int(yc + max(parameters.PIXWIDTH_SIGNAL, fwhmy_clip * fwhms[x]))) 

286 # print(x, xc, yc, xmin, xmax, ymin, ymax, fwhms[x]) 

287 psf_cube[x, ymin:ymax, xmin:xmax] = self.psf.evaluate(pixels[:, ymin:ymax, xmin:xmax], 

288 p=profile_params[x, :]) 

289 return psf_cube 

290 

291 def fill_table_with_profile_params(self, profile_params): 

292 """ 

293 Fill the table with the profile parameters. 

294 

295 Parameters 

296 ---------- 

297 profile_params: array 

298 a Nx * len(self.psf.param_names) numpy array containing the PSF parameters as a function of pixels. 

299 

300 Examples 

301 -------- 

302 

303 >>> psf = MoffatGauss() 

304 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=4, saturation=8000) 

305 >>> poly_params_test = s.generate_test_poly_params() 

306 >>> profile_params = s.from_poly_params_to_profile_params(poly_params_test) 

307 >>> s.fill_table_with_profile_params(profile_params) 

308 

309 .. doctest:: 

310 :hide: 

311 

312 >>> assert(np.all(np.isclose(s.table['stddev'], 1*np.ones(100)))) 

313 

314 """ 

315 for k, name in enumerate(self.psf.param_names): 

316 self.table[name] = profile_params[:, k] 

317 

318 def rotate_table(self, angle_degree): 

319 """ 

320 In self.table, rotate the columns Dx, Dy, Dy_fwhm_inf and Dy_fwhm_sup by an angle 

321 given in degree. The results overwrite the previous columns in self.table. 

322 

323 Parameters 

324 ---------- 

325 angle_degree: float 

326 Rotation angle in degree 

327 

328 Examples 

329 -------- 

330 

331 >>> psf = MoffatGauss() 

332 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=4, saturation=8000) 

333 >>> s.table['Dx'] = np.arange(100) 

334 >>> s.rotate_table(45) 

335 

336 .. doctest:: 

337 :hide: 

338 

339 >>> assert(np.all(np.isclose(s.table['Dy'], -np.arange(100)/np.sqrt(2)))) 

340 >>> assert(np.all(np.isclose(s.table['Dx'], np.arange(100)/np.sqrt(2)))) 

341 >>> assert(np.all(np.isclose(s.table['Dy_fwhm_inf'], -np.arange(100)/np.sqrt(2)))) 

342 >>> assert(np.all(np.isclose(s.table['Dy_fwhm_sup'], -np.arange(100)/np.sqrt(2)))) 

343 """ 

344 angle = angle_degree * np.pi / 180. 

345 rotmat = np.array([[np.cos(angle), np.sin(angle)], [-np.sin(angle), np.cos(angle)]]) 

346 # finish with Dy_c to get correct Dx 

347 for name in ['Dy', 'Dy_fwhm_inf', 'Dy_fwhm_sup', 'Dy_disp_axis']: 

348 vec = list(np.array([self.table['Dx'], self.table[name]]).T) 

349 rot_vec = np.array([np.dot(rotmat, v) for v in vec]) 

350 self.table[name] = rot_vec.T[1] 

351 self.table['Dx'] = rot_vec.T[0] 

352 

353 def from_profile_params_to_poly_params(self, profile_params): 

354 """ 

355 Transform the profile_params array into a set of parameters for the chromatic PSF parameterisation. 

356 Fit Legendre polynomial functions across the pixels for each PSF parameters. 

357 The order of the polynomial functions is given by the self.degrees array. 

358 

359 Parameters 

360 ---------- 

361 profile_params: array 

362 a Nx * len(self.psf.param_names) numpy array containing the PSF parameters as a function of pixels. 

363 

364 Returns 

365 ------- 

366 profile_params: array_like 

367 A set of parameters that can be evaluated by the chromatic PSF class evaluate function. 

368 

369 Examples 

370 -------- 

371 

372 Build a mock spectrogram with random Poisson noise: 

373 

374 >>> psf = MoffatGauss() 

375 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=4, saturation=8000) 

376 >>> poly_params_test = s.generate_test_poly_params() 

377 >>> data = s.build_spectrogram_image(poly_params_test, mode="1D") 

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

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

380 

381 From the polynomial parameters to the profile parameters: 

382 

383 >>> profile_params = s.from_poly_params_to_profile_params(poly_params_test) 

384 

385 .. doctest:: 

386 :hide: 

387 

388 >>> assert(np.all(np.isclose(profile_params[0], [10, 0, 50, 5, 2, 0, 1, 8e3]))) 

389 

390 From the profile parameters to the polynomial parameters: 

391 

392 >>> profile_params = s.from_profile_params_to_poly_params(profile_params) 

393 

394 .. doctest:: 

395 :hide: 

396 

397 >>> assert(np.all(np.isclose(profile_params, poly_params_test))) 

398 """ 

399 pixels = np.linspace(-1, 1, len(self.table)) 

400 poly_params = np.array([]) 

401 amplitude = None 

402 for k, name in enumerate(self.psf.param_names): 

403 if name == 'amplitude': 

404 amplitude = profile_params[:, k] 

405 poly_params = np.concatenate([poly_params, amplitude]) 

406 if amplitude is None: 

407 self.my_logger.warning('\n\tAmplitude array not initialized. ' 

408 'Polynomial fit for shape parameters will be unweighted.') 

409 for k, name in enumerate(self.psf.param_names): 

410 delta = 0 

411 if name != 'amplitude': 

412 weights = np.copy(amplitude) 

413 if name == 'x_c': 

414 delta = self.x0 

415 if name == 'y_c': 

416 delta = self.y0 

417 fit = np.polynomial.legendre.legfit(pixels, profile_params[:, k] - delta, 

418 deg=self.degrees[name], w=weights) 

419 poly_params = np.concatenate([poly_params, fit]) 

420 return poly_params 

421 

422 def from_table_to_profile_params(self): # pragma: nocover 

423 """ 

424 Extract the profile parameters from self.table and fill an array of profile parameters. 

425 

426 Parameters 

427 ---------- 

428 

429 Returns 

430 ------- 

431 profile_params: array 

432 Nx * len(self.psf.param_names) numpy array containing the PSF parameters as a function of pixels. 

433 

434 Examples 

435 -------- 

436 

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

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

439 >>> profile_params = s.chromatic_psf.from_table_to_profile_params() 

440 

441 .. doctest:: 

442 :hide: 

443 

444 >>> assert(profile_params.shape == (s.chromatic_psf.Nx, len(s.chromatic_psf.psf.param_names))) 

445 >>> assert not np.all(np.isclose(profile_params, np.zeros_like(profile_params))) 

446 """ 

447 profile_params = np.zeros((len(self.table), len(self.psf.param_names))) 

448 for k, name in enumerate(self.psf.param_names): 

449 profile_params[:, k] = self.table[name] 

450 return profile_params 

451 

452 def from_table_to_poly_params(self): # pragma: nocover 

453 """ 

454 Extract the polynomial parameters from self.table and fill an array with polynomial parameters. 

455 

456 Parameters 

457 ---------- 

458 

459 Returns 

460 ------- 

461 poly_params: array_like 

462 A set of polynomial parameters that can be evaluated by the chromatic PSF class evaluate function. 

463 

464 Examples 

465 -------- 

466 

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

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

469 >>> poly_params = s.chromatic_psf.from_table_to_poly_params() 

470 

471 .. doctest:: 

472 :hide: 

473 

474 >>> assert(poly_params.size > s.chromatic_psf.Nx) 

475 >>> assert(len(poly_params.shape)==1) 

476 >>> assert not np.all(np.isclose(poly_params, np.zeros_like(poly_params))) 

477 """ 

478 profile_params = self.from_table_to_profile_params() 

479 poly_params = self.from_profile_params_to_poly_params(profile_params) 

480 return poly_params 

481 

482 def from_poly_params_to_profile_params(self, poly_params, apply_bounds=False): 

483 """ 

484 Evaluate the PSF profile parameters from the polynomial coefficients. If poly_params length is smaller 

485 than self.Nx, it is assumed that the amplitude parameters are not included and set to arbitrarily to 1. 

486 

487 Parameters 

488 ---------- 

489 poly_params: array_like 

490 Parameter array of the model, in the form: 

491 - Nx first parameters are amplitudes for the Moffat transverse profiles 

492 - next parameters are polynomial coefficients for all the PSF parameters in the same order 

493 as in PSF definition, except amplitude 

494 

495 apply_bounds: bool, optional 

496 Force profile parameters to respect their boundary conditions if they lie outside (default: False) 

497 

498 Returns 

499 ------- 

500 profile_params: array 

501 Nx * len(self.psf.param_names) numpy array containing the PSF parameters as a function of pixels. 

502 

503 Examples 

504 -------- 

505 

506 Build a mock spectrogram with random Poisson noise: 

507 

508 >>> psf = MoffatGauss() 

509 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=1, saturation=8000) 

510 >>> poly_params_test = s.generate_test_poly_params() 

511 >>> data = s.build_spectrogram_image(poly_params_test, mode="1D") 

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

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

514 

515 From the polynomial parameters to the profile parameters: 

516 

517 >>> profile_params = s.from_poly_params_to_profile_params(poly_params_test, apply_bounds=True) 

518 

519 .. doctest:: 

520 :hide: 

521 

522 >>> assert(np.all(np.isclose(profile_params[0], [10, 0, 50, 5, 2, 0, 1, 8e3]))) 

523 

524 From the profile parameters to the polynomial parameters: 

525 

526 >>> profile_params = s.from_profile_params_to_poly_params(profile_params) 

527 

528 .. doctest:: 

529 :hide: 

530 

531 >>> assert(np.all(np.isclose(profile_params, poly_params_test))) 

532 

533 From the polynomial parameters to the profile parameters without Moffat amplitudes: 

534 

535 >>> profile_params = s.from_poly_params_to_profile_params(poly_params_test[100:]) 

536 

537 .. doctest:: 

538 :hide: 

539 

540 >>> assert(np.all(np.isclose(profile_params[0], [1, 0, 50, 5, 2, 0, 1, 8e3]))) 

541 

542 """ 

543 length = len(self.table) 

544 pixels = np.linspace(-1, 1, length) 

545 profile_params = np.zeros((length, len(self.psf.param_names))) 

546 shift = 0 

547 for k, name in enumerate(self.psf.param_names): 

548 if name == 'amplitude': 

549 if len(poly_params) > length: 

550 profile_params[:, k] = poly_params[:length] 

551 else: 

552 profile_params[:, k] = np.ones(length) 

553 else: 

554 if len(poly_params) > length: 

555 profile_params[:, k] = \ 

556 np.polynomial.legendre.legval(pixels, 

557 poly_params[ 

558 length + shift:length + shift + self.degrees[name] + 1]) 

559 else: 

560 p = poly_params[shift:shift + self.degrees[name] + 1] 

561 if len(p) > 0: # to avoid saturation parameters in case not set 

562 profile_params[:, k] = np.polynomial.legendre.legval(pixels, p) 

563 shift += self.degrees[name] + 1 

564 if name == 'x_c': 

565 profile_params[:, k] += self.x0 

566 if name == 'y_c': 

567 profile_params[:, k] += self.y0 

568 if apply_bounds: 

569 for k, name in enumerate(self.psf.param_names): 

570 profile_params[profile_params[:, k] <= self.psf.bounds[k][0], k] = self.psf.bounds[k][0] 

571 profile_params[profile_params[:, k] > self.psf.bounds[k][1], k] = self.psf.bounds[k][1] 

572 return profile_params 

573 

574 def from_profile_params_to_shape_params(self, profile_params): 

575 """ 

576 Compute the PSF integrals and FWHMS given the profile_params array and fill the table. 

577 

578 Parameters 

579 ---------- 

580 profile_params: array 

581 a Nx * len(self.psf.param_names) numpy array containing the PSF parameters as a function of pixels. 

582 

583 Examples 

584 -------- 

585 

586 >>> psf = MoffatGauss() 

587 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=4, saturation=8000) 

588 >>> poly_params_test = s.generate_test_poly_params() 

589 >>> profile_params = s.from_poly_params_to_profile_params(poly_params_test) 

590 >>> s.from_profile_params_to_shape_params(profile_params) 

591 

592 .. doctest:: 

593 :hide: 

594 

595 >>> assert s.table['fwhm'][-1] > 0 

596 

597 """ 

598 self.fill_table_with_profile_params(profile_params) 

599 pixel_x = np.arange(self.Nx).astype(int) 

600 # oversampling for precise computation of the PSF 

601 # pixels.shape = (2, Nx, Ny): self.pixels[1<-y, 0<-first pixel value column, :] 

602 # TODO: account for rotation ad projection effects is PSF is not round 

603 pixel_eval = np.arange(self.pixels[1, 0, 0], self.pixels[1, 0, -1], 0.1) 

604 for x in pixel_x: 

605 p = profile_params[x, :] 

606 # compute FWHM transverse to dispersion axis (assuming revolution symmetry of the PSF) 

607 out = self.psf.evaluate(pixel_eval, p=p) 

608 fwhm = compute_fwhm(pixel_eval, out, center=p[2], minimum=0) 

609 self.table['flux_integral'][x] = p[0] # if MoffatGauss1D normalized 

610 self.table['fwhm'][x] = fwhm 

611 # clean fwhm bad points 

612 fwhms = self.table['fwhm'] 

613 mask = np.logical_and(fwhms > 1, fwhms < self.Ny // 2) # more than 1 pixel or less than window 

614 self.table['fwhm'] = interp1d(pixel_x[mask], fwhms[mask], kind="linear", 

615 bounds_error=False, fill_value="extrapolate")(pixel_x) 

616 

617 def set_bounds(self): 

618 """ 

619 This function returns an array of bounds for iminuit. It is very touchy, change the values with caution ! 

620 

621 Returns 

622 ------- 

623 bounds: array_like 

624 2D array containing the pair of bounds for each polynomial parameters. 

625 

626 """ 

627 bounds = [[], []] 

628 for k, name in enumerate(self.psf.param_names): 

629 tmp_bounds = [[-np.inf] * (1 + self.degrees[name]), [np.inf] * (1 + self.degrees[name])] 

630 if name == "saturation": 

631 tmp_bounds = [[0], [2 * self.saturation]] 

632 elif name == "amplitude": 

633 continue 

634 bounds[0] += tmp_bounds[0] 

635 bounds[1] += tmp_bounds[1] 

636 return np.array(bounds).T 

637 

638 def set_bounds_for_minuit(self, data=None): # pragma: nocover 

639 """ 

640 This function returns an array of bounds for iminuit. It is very touchy, change the values with caution ! 

641 

642 Parameters 

643 ---------- 

644 data: array_like, optional 

645 The data array, to set the bounds for the amplitude using its maximum. 

646 If None is provided, no bounds are provided for the amplitude parameters. 

647 

648 Returns 

649 ------- 

650 bounds: array_like 

651 2D array containing the pair of bounds for each polynomial parameters. 

652 

653 """ 

654 if self.saturation is None: 

655 self.saturation = 2 * np.max(data) 

656 if data is not None: 

657 Ny, Nx = data.shape 

658 bounds = [[0.1 * np.max(data[:, x]) for x in range(Nx)], [100.0 * np.max(data[:, x]) for x in range(Nx)]] 

659 else: 

660 bounds = [[], []] 

661 for k, name in enumerate(self.psf.param_names): 

662 tmp_bounds = [[-np.inf] * (1 + self.degrees[name]), [np.inf] * (1 + self.degrees[name])] 

663 if name == "saturation": 

664 if data is not None: 

665 tmp_bounds = [[0.1 * np.max(data)], [2 * self.saturation]] 

666 else: 

667 tmp_bounds = [[0], [2 * self.saturation]] 

668 elif name == "amplitude": 

669 continue 

670 bounds[0] += tmp_bounds[0] 

671 bounds[1] += tmp_bounds[1] 

672 return np.array(bounds).T 

673 

674 def check_bounds(self, poly_params, noise_level=0): # pragma: nocover 

675 """ 

676 Evaluate the PSF profile parameters from the polynomial coefficients and check if they are within priors. 

677 

678 Parameters 

679 ---------- 

680 poly_params: array_like 

681 Parameter array of the model, in the form: 

682 - Nx first parameters are amplitudes for the Moffat transverse profiles 

683 - next parameters are polynomial coefficients for all the PSF parameters 

684 in the same order as in PSF definition, except amplitude 

685 noise_level: float, optional 

686 Noise level to set minimal boundary for amplitudes (negatively). 

687 

688 Returns 

689 ------- 

690 in_bounds: bool 

691 True if all parameters respect the model parameter priors. 

692 penalty: float 

693 Float value to add to chi square evaluating the degree of departure of a parameter from its boundaries. 

694 outbound_parameter_name: str 

695 Names of the parameters that are out of their boundaries. 

696 

697 Examples 

698 -------- 

699 

700 Build a mock spectrogram with random Poisson noise: 

701 

702 >>> psf = MoffatGauss() 

703 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=1, saturation=8000) 

704 >>> poly_params_test = s.generate_test_poly_params() 

705 

706 Check bounds: 

707 

708 >>> in_bounds, penalty, outbound_parameter_name = s.check_bounds(poly_params_test) 

709 

710 .. doctest:: 

711 :hide: 

712 

713 >>> assert in_bounds is True 

714 >>> assert np.isclose(penalty, 0, atol=1e-16) 

715 >>> assert outbound_parameter_name is not None 

716 

717 """ 

718 in_bounds = True 

719 penalty = 0 

720 outbound_parameter_name = "" 

721 profile_params = self.from_poly_params_to_profile_params(poly_params) 

722 for k, name in enumerate(self.psf.param_names): 

723 p = profile_params[:, k] 

724 if name == 'amplitude': 

725 if np.any(p < -noise_level): 

726 in_bounds = False 

727 penalty += np.abs(np.sum(profile_params[p < -noise_level, k])) # / np.mean(np.abs(p)) 

728 outbound_parameter_name += name + ' ' 

729 elif name == "saturation": 

730 continue 

731 else: 

732 if np.any(p > self.psf.bounds[k][1]): 

733 penalty += np.sum(profile_params[p > self.psf.bounds[k][1], k] - self.psf.bounds[k][1]) 

734 if not np.isclose(np.mean(p), 0): 

735 penalty /= np.abs(np.mean(p)) 

736 in_bounds = False 

737 outbound_parameter_name += name + ' ' 

738 if np.any(p < self.psf.bounds[k][0]): 

739 penalty += np.sum(self.psf.bounds[k][0] - profile_params[p < self.psf.bounds[k][0], k]) 

740 if not np.isclose(np.mean(p), 0): 

741 penalty /= np.abs(np.mean(p)) 

742 in_bounds = False 

743 outbound_parameter_name += name + ' ' 

744 # elif name is "stddev": 

745 # if np.any(p < 0) or np.any(p > self.Ny): 

746 # in_bounds = False 

747 # penalty = 1 

748 # break 

749 # else: 

750 # raise ValueError(f'Unknown parameter name {name} in set_bounds_for_minuit.') 

751 penalty *= self.Nx * self.Ny 

752 return in_bounds, penalty, outbound_parameter_name 

753 

754 def get_algebraic_distance_along_dispersion_axis(self, shift_x=0, shift_y=0): 

755 return np.asarray(np.sign(self.table['Dx']) * 

756 np.sqrt((self.table['Dx'] - shift_x) ** 2 + (self.table['Dy_disp_axis'] - shift_y) ** 2)) 

757 

758 def plot_summary(self, truth=None): 

759 fig, ax = plt.subplots(2, 1, sharex='all', figsize=(12, 6)) 

760 PSF_models = [] 

761 PSF_truth = [] 

762 if truth is not None: 

763 PSF_truth = truth.from_poly_params_to_profile_params(truth.poly_params, apply_bounds=True) 

764 all_pixels = np.arange(self.profile_params.shape[0]) 

765 for i, name in enumerate(self.psf.param_names): 

766 fit, cov, model = fit_poly1d(all_pixels, self.profile_params[:, i], order=self.degrees[name]) 

767 PSF_models.append(np.polyval(fit, all_pixels)) 

768 for i, name in enumerate(self.psf.param_names): 

769 p = ax[0].plot(all_pixels, self.profile_params[:, i], marker='+', linestyle='none') 

770 ax[0].plot(self.fitted_pixels, self.profile_params[self.fitted_pixels, i], label=name, 

771 marker='o', linestyle='none', color=p[0].get_color()) 

772 if i > 0: 

773 ax[0].plot(all_pixels, PSF_models[i], color=p[0].get_color()) 

774 if truth is not None: 

775 ax[0].plot(all_pixels, PSF_truth[:, i], color=p[0].get_color(), linestyle='--') 

776 img = np.zeros((self.Ny, self.Nx)).astype(float) 

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

778 for x in all_pixels[::self.Nx // 10]: 

779 params = [PSF_models[p][x] for p in range(len(self.psf.param_names))] 

780 params[:3] = [1, x, self.Ny // 2] 

781 out = self.psf.evaluate(np.asarray([xx, yy]), p=params) 

782 if np.max(out) <= 0: 

783 continue 

784 out /= np.max(out) 

785 img += out 

786 ax[1].imshow(img, origin='lower') # , extent=[0, self.Nx, 

787 # self.Ny//2-parameters.PIXWIDTH_SIGNAL, 

788 # self.Ny//2+parameters.PIXWIDTH_SIGNAL]) 

789 ax[1].set_xlabel('X [pixels]') 

790 ax[1].set_ylabel('Y [pixels]') 

791 ax[0].set_ylabel('PSF parameters') 

792 ax[0].grid() 

793 ax[1].grid(color='white', ls='solid') 

794 ax[1].grid(True) 

795 ax[0].set_yscale('symlog', linthresh=10) 

796 ax[1].legend(title='PSF(x)') 

797 ax[0].legend() 

798 fig.tight_layout() 

799 # fig.subplots_adjust(hspace=0) 

800 if parameters.DISPLAY: # pragma: no cover 

801 plt.show() 

802 

803 def fit_transverse_PSF1D_profile(self, data, err, w, ws, pixel_step=1, bgd_model_func=None, saturation=None, 

804 live_fit=False, sigma_clip=5): 

805 """ 

806 Fit the transverse profile of a 2D data image with a PSF profile. 

807 Loop is done on the x-axis direction. 

808 An order 1 polynomial function is fitted to subtract the background for each pixel 

809 with a 3*sigma outlier removal procedure to remove background stars. 

810 

811 Parameters 

812 ---------- 

813 data: array 

814 The 2D array image. The transverse profile is fitted on the y direction 

815 for all pixels along the x direction. 

816 err: array 

817 The uncertainties related to the data array. 

818 w: int 

819 Half width of central region where the spectrum is extracted and summed (default: 10) 

820 ws: list 

821 up/down region extension where the sky background is estimated with format [int, int] (default: [20,30]) 

822 pixel_step: int, optional 

823 The step in pixels between the slices to be fitted (default: 1). 

824 The values for the skipped pixels are interpolated with splines from the fitted parameters. 

825 bgd_model_func: callable, optional 

826 A 2D function to model the extracted background (default: None -> null background) 

827 saturation: float, optional 

828 The saturation level of the image. Default is set to twice the maximum of the data array and has no effect. 

829 live_fit: bool, optional 

830 If True, the transverse profile fit is plotted in live accross the loop (default: False). 

831 sigma_clip: int 

832 Sigma for outlier rejection (default: 5). 

833 

834 Examples 

835 -------- 

836 

837 Build a mock spectrogram with random Poisson noise: 

838 

839 >>> psf = MoffatGauss() 

840 >>> s0 = ChromaticPSF(psf, Nx=100, Ny=100, saturation=1000) 

841 >>> params = s0.generate_test_poly_params() 

842 >>> saturation = params[-1] 

843 >>> data = s0.build_spectrogram_image(params, mode="1D") 

844 >>> bgd = 10*np.ones_like(data) 

845 >>> xx, yy = np.meshgrid(np.arange(s0.Nx), np.arange(s0.Ny)) 

846 >>> bgd += 1000*np.exp(-((xx-20)**2+(yy-10)**2)/(2*2)) 

847 >>> data += bgd 

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

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

850 

851 Extract the background: 

852 

853 >>> bgd_model_func, _, _ = extract_spectrogram_background_sextractor(data, data_errors, ws=[30,50]) 

854 

855 Fit the transverse profile: 

856 

857 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=4, saturation=saturation) 

858 >>> s.fit_transverse_PSF1D_profile(data, data_errors, w=20, ws=[30,50], pixel_step=10, 

859 ... bgd_model_func=bgd_model_func, saturation=saturation, live_fit=False, sigma_clip=5) 

860 >>> s.plot_summary(truth=s0) 

861 

862 .. doctest:: 

863 :hide: 

864 

865 >>> assert(not np.any(np.isclose(s.table['flux_sum'][3:6], np.zeros(s.Nx)[3:6], rtol=1e-3))) 

866 >>> assert(np.all(np.isclose(s.table['Dy'][-10:-1], np.zeros(s.Nx)[-10:-1], rtol=1e-2))) 

867 

868 """ 

869 if saturation is None: 

870 saturation = 2 * np.max(data) 

871 Ny, Nx = data.shape 

872 middle = Ny // 2 

873 index = np.arange(Ny) 

874 # Prepare the fit: start with the maximum of the spectrum 

875 xmax_index = int(np.unravel_index(np.argmax(data[middle - w:middle + w, :]), data.shape)[1]) 

876 bgd_index = np.concatenate((np.arange(0, middle - ws[0]), np.arange(middle + ws[0], Ny))).astype(int) 

877 y = data[:, xmax_index] 

878 # first fit with moffat only to initialize the guess 

879 # hypothesis that max of spectrum if well describe by a focused PSF 

880 if bgd_model_func is not None: 

881 signal = y - bgd_model_func(xmax_index, index)[:, 0] 

882 else: 

883 signal = y 

884 # fwhm = compute_fwhm(index, signal, minimum=0) 

885 # Initialize PSF 

886 psf = self.psf 

887 guess = np.copy(psf.p_default).astype(float) 

888 # guess = [2 * np.nanmax(signal), middle, 0.5 * fwhm, 2, 0, 0.1 * fwhm, saturation] 

889 signal_sum = np.nanmax(signal) 

890 guess[0] = signal_sum 

891 guess[1] = xmax_index 

892 guess[2] = middle 

893 guess[-1] = saturation 

894 # bounds = [(0.1 * maxi, 10 * maxi), (middle - w, middle + w), (0.1, min(fwhm, Ny // 2)), (0.1, self.alpha_max), 

895 # (-1, 0), 

896 # (0.1, min(Ny // 2, fwhm)), 

897 # (0, 2 * saturation)] 

898 psf.apply_max_width_to_bounds(max_half_width=Ny) 

899 bounds = np.copy(psf.bounds) 

900 bounds[0] = (0.1 * signal_sum, 2 * signal_sum) 

901 bounds[2] = (middle - w, middle + w) 

902 bounds[-1] = (0, 2 * saturation) 

903 # moffat_guess = [2 * np.nanmax(signal), middle, 0.5 * fwhm, 2] 

904 # moffat_bounds = [(0.1 * maxi, 10 * maxi), (middle - w, middle + w), (0.1, min(fwhm, Ny // 2)), (0.1, 10)] 

905 # fit = fit_moffat1d_outlier_removal(index, signal, sigma=sigma, niter=2, 

906 # guess=moffat_guess, bounds=np.array(moffat_bounds).T) 

907 # moffat_guess = [getattr(fit, p).value for p in fit.param_names] 

908 # signal_width_guess = moffat_guess[2] 

909 # bounds[2] = (0.1, min(Ny // 2, 5 * signal_width_guess)) 

910 # bounds[5] = (0.1, min(Ny // 2, 5 * signal_width_guess)) 

911 # guess[:4] = moffat_guess 

912 init_guess = np.copy(guess) 

913 # Go from max to right, then from max to left 

914 # includes the boundaries to avoid Runge phenomenum in chromatic_fit 

915 pixel_range = list(np.arange(xmax_index, Nx, pixel_step).astype(int)) 

916 if Nx - 1 not in pixel_range: 

917 pixel_range.append(Nx - 1) 

918 pixel_range += list(np.arange(xmax_index, -1, -pixel_step).astype(int)) 

919 if 0 not in pixel_range: 

920 pixel_range.append(0) 

921 pixel_range = np.array(pixel_range) 

922 for x in tqdm(pixel_range, disable=not parameters.VERBOSE): 

923 guess = np.copy(guess) 

924 if x == xmax_index: 

925 guess = np.copy(init_guess) 

926 # fit the background with a polynomial function 

927 y = data[:, x] 

928 if bgd_model_func is not None: 

929 # x_array = [x] * index.size 

930 signal = y - bgd_model_func(x, index)[:, 0] 

931 else: 

932 signal = y 

933 if np.mean(signal[bgd_index]) < 0: 

934 signal -= np.mean(signal[bgd_index]) 

935 # in case guess amplitude is too low 

936 # pdf = np.abs(signal) 

937 signal_sum = np.nansum(signal[middle - ws[0]:middle + ws[0]]) 

938 if signal_sum < 3 * np.nanstd(signal[bgd_index]): 

939 continue 

940 # if signal_sum > 0: 

941 # pdf /= signal_sum 

942 # mean = np.nansum(pdf * index) 

943 # bounds[0] = (0.1 * np.nanstd(bgd), 2 * np.nanmax(y[middle - ws[0]:middle + ws[0]])) 

944 bounds[0] = (0.1 * signal_sum, 1.5 * signal_sum) 

945 guess[0] = signal_sum 

946 guess[1] = x 

947 # if guess[4] > -1: 

948 # guess[0] = np.max(signal) / (1 + guess[4]) 

949 # std = np.sqrt(np.nansum(pdf * (index - mean) ** 2)) 

950 # if guess[0] < 3 * np.nanstd(bgd): 

951 # guess[0] = float(0.9 * np.abs(np.nanmax(signal))) 

952 # if guess[0] * (1 + 0*guess[4]) > 1.2 * maxi: 

953 # guess[0] = 0.9 * maxi 

954 psf.p = guess 

955 psf.bounds = bounds 

956 w = PSFFitWorkspace(psf, signal, data_errors=err[:, x], bgd_model_func=None, 

957 live_fit=False, verbose=False) 

958 try: 

959 run_minimisation_sigma_clipping(w, method="newton", sigma_clip=sigma_clip, niter_clip=1, verbose=False, 

960 fix=w.fixed) 

961 except: 

962 pass 

963 best_fit = w.psf.p 

964 # It is better not to propagate the guess to further pixel columns 

965 # otherwise fit_chromatic_psf1D is more likely to get trapped in a local minimum 

966 # Randomness of the slice fit is better : 

967 # guess = best_fit 

968 self.profile_params[x, :] = best_fit 

969 # TODO: propagate amplitude uncertainties from Newton fit 

970 self.table['flux_err'][x] = np.sqrt(np.sum(err[:, x] ** 2)) 

971 self.table['flux_sum'][x] = np.sum(signal) 

972 if live_fit and parameters.DISPLAY: # pragma: no cover 

973 if not np.any(np.isnan(best_fit[0])): 

974 w.live_fit = True 

975 w.plot_fit() 

976 # interpolate the skipped pixels with splines 

977 all_pixels = np.arange(Nx) 

978 xp = np.array(sorted(set(list(pixel_range)))) 

979 self.fitted_pixels = xp 

980 for i in range(len(self.psf.param_names)): 

981 yp = self.profile_params[xp, i] 

982 self.profile_params[:, i] = interp1d(xp, yp, kind='cubic')(all_pixels) 

983 for x in all_pixels: 

984 y = data[:, x] 

985 if bgd_model_func is not None: 

986 signal = y - bgd_model_func(x, index)[:, 0] 

987 else: 

988 signal = y 

989 if np.mean(signal[bgd_index]) < 0: 

990 signal -= np.mean(signal[bgd_index]) 

991 self.table['flux_err'][x] = np.sqrt(np.sum(err[:, x] ** 2)) 

992 self.table['flux_sum'][x] = np.sum(signal) 

993 self.poly_params = self.from_profile_params_to_poly_params(self.profile_params) 

994 self.from_profile_params_to_shape_params(self.profile_params) 

995 self.cov_matrix = np.diag(1 / np.array(self.table['flux_err']) ** 2) 

996 

997 def fit_chromatic_psf(self, data, bgd_model_func=None, data_errors=None, mode="1D", 

998 amplitude_priors_method="noprior", verbose=False, live_fit=False): 

999 """ 

1000 Fit a chromatic PSF model on 2D data. 

1001 

1002 Parameters 

1003 ---------- 

1004 data: array_like 

1005 2D array containing the image data. 

1006 bgd_model_func: callable, optional 

1007 A 2D function to model the extracted background (default: None -> null background) 

1008 data_errors: np.array 

1009 the 2D array uncertainties. 

1010 mode: str, optional 

1011 Set the fitting mode: either transverse 1D PSF profile (mode="1D") or full 2D PSF profile (mode="2D"). 

1012 amplitude_priors_method: str, optional 

1013 Prior method to use to constrain the amplitude parameters of the PSF (default: "noprior"). 

1014 verbose: bool, optional 

1015 Set the verbosity of the fitting process (default: False). 

1016 

1017 Returns 

1018 ------- 

1019 w: ChromaticPSFFitWorkspace 

1020 The ChromaticPSFFitWorkspace containing info abut the fitting process. 

1021 

1022 Examples 

1023 -------- 

1024 

1025 Set the parameters: 

1026 

1027 >>> parameters.PIXDIST_BACKGROUND = 40 

1028 >>> parameters.PIXWIDTH_BACKGROUND = 10 

1029 >>> parameters.PIXWIDTH_SIGNAL = 30 

1030 >>> parameters.DEBUG = True 

1031 

1032 Build a mock spectrogram with random Poisson noise using the full 2D PSF model: 

1033 

1034 >>> psf = Moffat(clip=False) 

1035 >>> s0 = ChromaticPSF(psf, Nx=120, Ny=100, deg=2, saturation=10000000) 

1036 >>> params = s0.generate_test_poly_params() 

1037 >>> params[:s0.Nx] *= 1 

1038 >>> s0.poly_params = params 

1039 >>> saturation = params[-1] 

1040 >>> data = s0.build_spectrogram_image(params, mode="2D") 

1041 >>> bgd = 10*np.ones_like(data) 

1042 >>> data += bgd 

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

1044 >>> data_errors = np.sqrt(data) 

1045 

1046 Extract the background: 

1047 

1048 >>> bgd_model_func, _, _ = extract_spectrogram_background_sextractor(data, data_errors, ws=[30,50]) 

1049 

1050 Propagate background uncertainties: 

1051 

1052 >>> data_errors = np.sqrt(data_errors**2 + bgd_model_func(np.arange(s0.Nx), np.arange(s0.Ny))) 

1053 

1054 Estimate the first guess values: 

1055 

1056 >>> s = ChromaticPSF(psf, Nx=120, Ny=100, deg=2, saturation=saturation) 

1057 >>> s.fit_transverse_PSF1D_profile(data, data_errors, w=20, ws=[30,50], 

1058 ... pixel_step=1, bgd_model_func=bgd_model_func, saturation=saturation, live_fit=False) 

1059 >>> s.plot_summary(truth=s0) 

1060 >>> amplitude_residuals = [ [s0.poly_params[:s0.Nx], np.array(s.table["amplitude"])-s0.poly_params[:s0.Nx], 

1061 ... np.array(s.table['amplitude'] * s.table['flux_err'] / s.table['flux_sum'])] ] 

1062 

1063 Fit the data using the transverse 1D PSF model only: 

1064 

1065 >>> w = s.fit_chromatic_psf(data, mode="1D", data_errors=data_errors, bgd_model_func=bgd_model_func, 

1066 ... amplitude_priors_method="noprior", verbose=True) 

1067 >>> s.plot_summary(truth=s0) 

1068 >>> amplitude_residuals.append([s0.poly_params[:s0.Nx], w.amplitude_params-s0.poly_params[:s0.Nx], 

1069 ... w.amplitude_params_err]) 

1070 

1071 .. doctest:: 

1072 :hide: 

1073 

1074 >>> residuals = [(w.data[x]-w.model[x])/w.err[x] for x in range(w.Nx)] 

1075 >>> assert w.costs[-1] /(w.Nx*w.Ny) < 1.5 

1076 >>> assert np.abs(np.mean(residuals)) < 0.15 

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

1078 

1079 Fit the data using the full 2D PSF model 

1080 

1081 >>> parameters.PSF_FIT_REG_PARAM = 0.002 

1082 >>> w = s.fit_chromatic_psf(data, mode="2D", data_errors=data_errors, bgd_model_func=bgd_model_func, 

1083 ... amplitude_priors_method="psf1d", verbose=True) 

1084 >>> s.plot_summary(truth=s0) 

1085 >>> amplitude_residuals.append([s0.poly_params[:s0.Nx], w.amplitude_params-s0.poly_params[:s0.Nx], 

1086 ... w.amplitude_params_err]) 

1087 >>> for k, label in enumerate(["Transverse", "PSF1D", "PSF2D"]): 

1088 ... plt.errorbar(np.arange(s0.Nx), amplitude_residuals[k][1]/amplitude_residuals[k][2], 

1089 ... yerr=amplitude_residuals[k][2]/amplitude_residuals[k][2], 

1090 ... fmt="+", label=label) # doctest: +ELLIPSIS 

1091 <ErrorbarContainer ...> 

1092 >>> plt.grid() 

1093 >>> plt.legend() # doctest: +ELLIPSIS 

1094 <matplotlib.legend.Legend object at ...> 

1095 >>> plt.show() 

1096 

1097 .. doctest:: 

1098 :hide: 

1099 

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

1101 >>> assert w.costs[-1] /(w.Nx*w.Ny) < 1.2 

1102 >>> assert np.abs(np.mean(residuals)) < 0.15 

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

1104 >>> assert np.abs(np.mean((w.amplitude_params - s0.poly_params[:s0.Nx])/w.amplitude_params_err)) < 0.5 

1105 

1106 """ 

1107 if mode == "1D": 

1108 w = ChromaticPSF1DFitWorkspace(self, data, data_errors=data_errors, bgd_model_func=bgd_model_func, 

1109 amplitude_priors_method=amplitude_priors_method, verbose=verbose, 

1110 live_fit=live_fit) 

1111 run_minimisation(w, method="newton", ftol=1 / (w.Nx * w.Ny), xtol=1e-6, niter=50, fix=w.fixed) 

1112 elif mode == "2D": 

1113 # first shot to set the mask 

1114 w = ChromaticPSF2DFitWorkspace(self, data, data_errors=data_errors, bgd_model_func=bgd_model_func, 

1115 amplitude_priors_method=amplitude_priors_method, verbose=verbose, 

1116 live_fit=live_fit) 

1117 run_minimisation(w, method="newton", ftol=10 / (w.Nx * w.Ny), xtol=1e-4, niter=50, fix=w.fixed, 

1118 verbose=verbose) 

1119 if amplitude_priors_method == "psf1d": 

1120 w_reg = RegFitWorkspace(w, opt_reg=parameters.PSF_FIT_REG_PARAM, verbose=verbose) 

1121 w_reg.run_regularisation() 

1122 w.reg = np.copy(w_reg.opt_reg) 

1123 self.opt_reg = w_reg.opt_reg 

1124 w.simulate(*w.p) 

1125 if np.trace(w.amplitude_cov_matrix) < np.trace(w.amplitude_priors_cov_matrix): 

1126 self.my_logger.warning( 

1127 f"\n\tTrace of final covariance matrix ({np.trace(w.amplitude_cov_matrix)}) is " 

1128 f"below the trace of the prior covariance matrix " 

1129 f"({np.trace(w.amplitude_priors_cov_matrix)}). This is probably due to a very " 

1130 f"high regularisation parameter in case of a bad fit. Therefore the final " 

1131 f"covariance matrix is mulitiplied by the ratio of the traces and " 

1132 f"the amplitude parameters are very close the amplitude priors.") 

1133 r = np.trace(w.amplitude_priors_cov_matrix) / np.trace(w.amplitude_cov_matrix) 

1134 w.amplitude_cov_matrix *= r 

1135 w.amplitude_params_err = np.array([np.sqrt(w.amplitude_cov_matrix[x, x]) for x in range(self.Nx)]) 

1136 

1137 w.set_mask(poly_params=w.poly_params) 

1138 # precise fit with sigma clipping 

1139 run_minimisation_sigma_clipping(w, method="newton", ftol=1 / (w.Nx * w.Ny), xtol=1e-6, niter=50, 

1140 fix=w.fixed, sigma_clip=20, niter_clip=3, verbose=verbose) 

1141 else: 

1142 raise ValueError(f"Unknown fitting mode={mode}. Must be '1D' or '2D'.") 

1143 

1144 # recompute and save params in class attributes 

1145 w.simulate(*w.p) 

1146 self.poly_params = w.poly_params 

1147 self.cov_matrix = np.copy(w.amplitude_cov_matrix) 

1148 

1149 # add background crop to y_c 

1150 self.poly_params[w.Nx + w.y_c_0_index] += w.bgd_width 

1151 

1152 # fill results 

1153 self.psf.apply_max_width_to_bounds(max_half_width=w.Ny + 2 * w.bgd_width) 

1154 self.set_bounds() 

1155 self.profile_params = self.from_poly_params_to_profile_params(self.poly_params, apply_bounds=True) 

1156 self.fill_table_with_profile_params(self.profile_params) 

1157 self.profile_params[:self.Nx, 0] = w.amplitude_params 

1158 self.profile_params[:self.Nx, 1] = np.arange(self.Nx) 

1159 self.from_profile_params_to_shape_params(self.profile_params) 

1160 

1161 # save plots 

1162 if parameters.LSST_SAVEFIGPATH: # pragma: no cover 

1163 w.plot_fit() 

1164 return w 

1165 

1166 

1167class ChromaticPSFFitWorkspace(FitWorkspace): 

1168 

1169 def __init__(self, chromatic_psf, data, data_errors, bgd_model_func=None, file_name="", 

1170 amplitude_priors_method="noprior", 

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

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

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

1174 live_fit, truth=truth) 

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

1176 self.chromatic_psf = chromatic_psf 

1177 self.data = data 

1178 self.err = data_errors 

1179 self.bgd_model_func = bgd_model_func 

1180 length = len(self.chromatic_psf.table) 

1181 self.p = np.copy(self.chromatic_psf.poly_params[length:]) # remove saturation (fixed parameter)) 

1182 self.poly_params = np.copy(self.chromatic_psf.poly_params) 

1183 self.input_labels = list(np.copy(self.chromatic_psf.poly_params_labels[length:])) 

1184 self.axis_names = list(np.copy(self.chromatic_psf.poly_params_names[length:])) 

1185 self.fixed = [False] * self.p.size 

1186 for k, par in enumerate(self.input_labels): 

1187 if "x_c" in par or "saturation" in par: 

1188 self.fixed[k] = True 

1189 self.y_c_0_index = -1 

1190 for k, par in enumerate(self.input_labels): 

1191 if par == "y_c_0": 

1192 self.y_c_0_index = k 

1193 break 

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

1195 

1196 # prepare the fit 

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

1198 if self.Ny != self.chromatic_psf.Ny: 

1199 raise AttributeError(f"Data y shape {self.Ny} different from " 

1200 f"ChromaticPSF input Ny {self.chromatic_psf.Ny}.") 

1201 if self.Nx != self.chromatic_psf.Nx: 

1202 raise AttributeError(f"Data x shape {self.Nx} different from " 

1203 f"ChromaticPSF input Nx {self.chromatic_psf.Nx}.") 

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

1205 

1206 # prepare the background, data and errors 

1207 self.bgd = np.zeros_like(self.data) 

1208 if self.bgd_model_func is not None: 

1209 self.bgd = self.bgd_model_func(np.arange(self.Nx), self.pixels) 

1210 self.data = self.data - self.bgd 

1211 self.bgd_std = float(np.std(np.random.poisson(np.abs(self.bgd)))) 

1212 

1213 # crop spectrogram to fit faster 

1214 self.bgd_width = parameters.PIXWIDTH_BACKGROUND + parameters.PIXDIST_BACKGROUND - parameters.PIXWIDTH_SIGNAL 

1215 self.data = self.data[self.bgd_width:-self.bgd_width, :] 

1216 self.pixels = np.arange(self.data.shape[0]) 

1217 self.err = np.copy(self.err[self.bgd_width:-self.bgd_width, :]) 

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

1219 self.poly_params[self.Nx + self.y_c_0_index] -= self.bgd_width 

1220 self.data_before_mask = np.copy(self.data) 

1221 

1222 # update the bounds 

1223 self.chromatic_psf.psf.apply_max_width_to_bounds(max_half_width=self.Ny) 

1224 self.bounds = self.chromatic_psf.set_bounds() 

1225 

1226 # error matrix 

1227 # here image uncertainties are assumed to be uncorrelated 

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

1229 self.data_cov = (self.err * self.err).flatten() 

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

1231 self.W = self.W.flatten() 

1232 

1233 # design matrix 

1234 self.M = np.zeros((self.Nx, self.data.size)) 

1235 self.M_dot_W_dot_M = np.zeros((self.Nx, self.Nx)) 

1236 

1237 # prepare results 

1238 self.amplitude_params = np.zeros(self.Nx) 

1239 self.amplitude_params_err = np.zeros(self.Nx) 

1240 self.amplitude_cov_matrix = np.zeros((self.Nx, self.Nx)) 

1241 

1242 # priors on amplitude parameters 

1243 self.amplitude_priors_list = ['noprior', 'positive', 'smooth', 'psf1d', 'fixed'] 

1244 self.amplitude_priors_method = amplitude_priors_method 

1245 self.fwhm_priors = np.copy(self.chromatic_psf.table['fwhm']) 

1246 self.reg = parameters.PSF_FIT_REG_PARAM 

1247 self.Q = np.zeros((self.Nx, self.Nx)) 

1248 self.Q_dot_A0 = np.zeros(self.Nx) 

1249 if amplitude_priors_method not in self.amplitude_priors_list: 

1250 raise ValueError(f"Unknown prior method for the amplitude fitting: {self.amplitude_priors_method}. " 

1251 f"Must be either {self.amplitude_priors_list}.") 

1252 if self.amplitude_priors_method == "psf1d": 

1253 self.amplitude_priors = np.copy(self.chromatic_psf.poly_params[:self.Nx]) 

1254 self.amplitude_priors_cov_matrix = np.copy(self.chromatic_psf.cov_matrix) 

1255 # self.amplitude_priors_err = np.copy(self.chromatic_psf.table["flux_err"]) 

1256 self.Q = np.diag([1 / np.sum(self.err[:, x] ** 2) for x in range(self.Nx)]) 

1257 self.Q_dot_A0 = self.Q @ self.amplitude_priors 

1258 if self.amplitude_priors_method == "fixed": 

1259 self.amplitude_priors = np.copy(self.chromatic_psf.poly_params[:self.Nx]) 

1260 

1261 def plot_fit(self): 

1262 cmap_bwr = copy.copy(cm.get_cmap('bwr')) 

1263 cmap_bwr.set_bad(color='lightgrey') 

1264 cmap_viridis = copy.copy(cm.get_cmap('viridis')) 

1265 cmap_viridis.set_bad(color='lightgrey') 

1266 

1267 data = np.copy(self.data_before_mask) 

1268 model = np.copy(self.model) 

1269 err = np.copy(self.err) 

1270 if isinstance(self, ChromaticPSF1DFitWorkspace): 

1271 data = np.array([data[x] for x in range(self.Nx)], dtype=float).T 

1272 model = np.array([model[x] for x in range(self.Nx)], dtype=float).T 

1273 err = np.array([err[x] for x in range(self.Nx)], dtype=float).T 

1274 if isinstance(self, ChromaticPSF2DFitWorkspace): 

1275 if len(self.outliers) > 0 or len(self.mask) > 0: 

1276 bad_indices = np.array(list(self.get_bad_indices()) + list(self.mask)).astype(int) 

1277 data[bad_indices] = np.nan 

1278 data = data.reshape((self.Ny, self.Nx)) 

1279 model = model.reshape((self.Ny, self.Nx)) 

1280 err = err.reshape((self.Ny, self.Nx)) 

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

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

1283 norm = np.nanmax(data) 

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

1285 units='1/max(data)', cmap=cmap_viridis) 

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

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

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

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

1290 residuals = (data - model) 

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

1292 norm = err 

1293 residuals /= norm 

1294 std = float(np.nanstd(residuals)) 

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

1296 aspect='auto', cax=ax[2, 1], units='', cmap=cmap_bwr) 

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

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

1299 horizontalalignment='left', verticalalignment='bottom', 

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

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

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

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

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

1305 ax[3, 1].remove() 

1306 ax[3, 0].errorbar(np.arange(self.Nx), np.nansum(data, axis=0), yerr=np.sqrt(np.nansum(err ** 2, axis=0)), 

1307 label='Data', fmt='k.', markersize=0.1) 

1308 model[np.isnan(data)] = np.nan # mask background values outside fitted region 

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

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

1311 ax[3, 0].set_xlabel(parameters.PLOT_XLABEL) 

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

1313 ax[3, 0].set_xlim((0, data.shape[1])) 

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

1315 if self.live_fit: # pragma: no cover 

1316 plt.draw() 

1317 plt.pause(1e-8) 

1318 plt.close() 

1319 else: # pragma: no cover 

1320 if parameters.DISPLAY and self.verbose: 

1321 plt.show() 

1322 if parameters.LSST_SAVEFIGPATH: # pragma: no cover 

1323 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 

1324 f'fit_chromatic_psf_best_fit_{self.amplitude_priors_method}.pdf'), 

1325 dpi=100, bbox_inches='tight') 

1326 

1327 

1328class ChromaticPSF1DFitWorkspace(ChromaticPSFFitWorkspace): 

1329 

1330 def __init__(self, chromatic_psf, data, data_errors, bgd_model_func=None, file_name="", 

1331 amplitude_priors_method="noprior", 

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

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

1334 ChromaticPSFFitWorkspace.__init__(self, chromatic_psf, data, data_errors, bgd_model_func, 

1335 file_name, amplitude_priors_method, nwalkers, nsteps, burnin, nbins, verbose, 

1336 plot, live_fit, truth=truth) 

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

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

1339 

1340 # error matrix 

1341 # here image uncertainties are assumed to be uncorrelated 

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

1343 self.data_cov = self.err * self.err 

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

1345 # these lines make the code thinks that W is block diagonal 

1346 self.W = np.empty(self.Nx, dtype=object) 

1347 for x in range(self.Nx): 

1348 self.W[x] = W[:, x] 

1349 

1350 # data: ordered by pixel columns 

1351 data = np.empty(self.Nx, dtype=object) 

1352 err = np.empty(self.Nx, dtype=object) 

1353 for x in range(self.Nx): 

1354 data[x] = self.data[:, x] 

1355 err[x] = self.err[:, x] 

1356 self.data = data 

1357 self.data_before_mask = np.copy(data) 

1358 self.err = err 

1359 self.pixels = self.pixels.T 

1360 

1361 def simulate(self, *shape_params): 

1362 """ 

1363 Compute a ChromaticPSF model given PSF shape parameters and minimizing 

1364 amplitude parameters given a spectrogram data array. 

1365 

1366 Parameters 

1367 ---------- 

1368 shape_params: array_like 

1369 PSF shape polynomial parameter array. 

1370 

1371 Examples 

1372 -------- 

1373 

1374 Set the parameters: 

1375 

1376 >>> parameters.PIXDIST_BACKGROUND = 40 

1377 >>> parameters.PIXWIDTH_BACKGROUND = 10 

1378 >>> parameters.PIXWIDTH_SIGNAL = 30 

1379 

1380 Build a mock spectrogram with random Poisson noise: 

1381 

1382 >>> psf = MoffatGauss() 

1383 >>> s0 = ChromaticPSF(psf, Nx=100, Ny=100, deg=4, saturation=1000) 

1384 >>> params = s0.generate_test_poly_params() 

1385 >>> s0.poly_params = params 

1386 >>> saturation = params[-1] 

1387 >>> data = s0.build_spectrogram_image(params, mode="1D") 

1388 >>> bgd = 10*np.ones_like(data) 

1389 >>> data += bgd 

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

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

1392 

1393 Extract the background: 

1394 

1395 >>> bgd_model_func, _, _ = extract_spectrogram_background_sextractor(data, data_errors, ws=[30,50]) 

1396 

1397 Estimate the first guess values: 

1398 

1399 >>> s = ChromaticPSF(psf, Nx=100, Ny=100, deg=4, saturation=saturation) 

1400 >>> s.fit_transverse_PSF1D_profile(data, data_errors, w=20, ws=[30,50], 

1401 ... pixel_step=1, bgd_model_func=bgd_model_func, saturation=saturation, live_fit=False) 

1402 >>> guess = np.copy(s.table["amplitude"]) 

1403 

1404 Fit the amplitude of data without any prior: 

1405 

1406 >>> w = ChromaticPSF1DFitWorkspace(s, data, data_errors, bgd_model_func=bgd_model_func, verbose=True, 

1407 ... amplitude_priors_method="noprior") 

1408 >>> y, mod, mod_err = w.simulate(*s.poly_params[s.Nx:]) 

1409 >>> w.plot_fit() 

1410 

1411 .. doctest:: 

1412 :hide: 

1413 

1414 >>> assert mod is not None 

1415 >>> assert np.mean(np.abs(mod.flatten()-np.concatenate(w.data).ravel())/np.concatenate(w.err).ravel()) < 1 

1416 

1417 Fit the amplitude of data smoothing the result with a window of size 10 pixels: 

1418 

1419 >>> w = ChromaticPSF1DFitWorkspace(s, data, data_errors, bgd_model_func=bgd_model_func, verbose=True, 

1420 ... amplitude_priors_method="smooth") 

1421 >>> y, mod, mod_err = w.simulate(*s.poly_params[s.Nx:]) 

1422 >>> w.plot_fit() 

1423 

1424 .. doctest:: 

1425 :hide: 

1426 

1427 >>> assert mod is not None 

1428 >>> assert np.mean(np.abs(mod.flatten()-np.concatenate(w.data).ravel())/np.concatenate(w.err).ravel()) < 1 

1429 

1430 Fit the amplitude of data using the transverse PSF1D fit as a prior and with a 

1431 Tikhonov regularisation parameter set by parameters.PSF_FIT_REG_PARAM: 

1432 

1433 >>> w = ChromaticPSF1DFitWorkspace(s, data, data_errors, bgd_model_func=bgd_model_func, verbose=True, 

1434 ... amplitude_priors_method="psf1d") 

1435 >>> y, mod, mod_err = w.simulate(*s.poly_params[s.Nx:]) 

1436 >>> w.plot_fit() 

1437 

1438 .. doctest:: 

1439 :hide: 

1440 

1441 >>> assert mod is not None 

1442 >>> assert np.mean(np.abs(mod.flatten()-np.concatenate(w.data).ravel())/np.concatenate(w.err).ravel()) < 1 

1443 

1444 Set the amplitude parameters fixing the transverse PSF1D fit amplitudes: 

1445 

1446 >>> w = ChromaticPSF1DFitWorkspace(s, data, data_errors, bgd_model_func=bgd_model_func, verbose=True, 

1447 ... amplitude_priors_method="fixed") 

1448 >>> y, mod, mod_err = w.simulate(*s.poly_params[s.Nx:]) 

1449 >>> w.plot_fit() 

1450 

1451 .. doctest:: 

1452 :hide: 

1453 

1454 >>> assert mod is not None 

1455 >>> assert np.mean(np.abs(mod.flatten()-np.concatenate(w.data).ravel())/np.concatenate(w.err).ravel()) < 1 

1456 

1457 """ 

1458 # linear regression for the amplitude parameters 

1459 poly_params = np.copy(self.poly_params) 

1460 poly_params[self.Nx:] = np.copy(shape_params) 

1461 poly_params[self.Nx + self.y_c_0_index] -= self.bgd_width 

1462 profile_params = self.chromatic_psf.from_poly_params_to_profile_params(poly_params, apply_bounds=True) 

1463 profile_params[:self.Nx, 0] = 1 

1464 profile_params[:self.Nx, 1] = np.arange(self.Nx) 

1465 # profile_params[:self.Nx, 2] -= self.bgd_width 

1466 if self.amplitude_priors_method != "fixed": 

1467 # Matrix filling 

1468 M = np.array([self.chromatic_psf.psf.evaluate(self.pixels, p=profile_params[x, :]) for x in range(self.Nx)]) 

1469 M_dot_W_dot_M = np.array([M[x].T @ (self.W[x] * M[x]) for x in range(self.Nx)]) 

1470 if self.amplitude_priors_method != "psf1d": 

1471 cov_matrix = np.diag([1 / M_dot_W_dot_M[x] if M_dot_W_dot_M[x] > 0 else 0.1 * self.bgd_std 

1472 for x in range(self.Nx)]) 

1473 amplitude_params = np.array([ 

1474 M[x].T @ (self.W[x] * self.data[x]) / (M_dot_W_dot_M[x]) if M_dot_W_dot_M[ 

1475 x] > 0 else 0.1 * self.bgd_std 

1476 for x in range(self.Nx)]) 

1477 if self.amplitude_priors_method == "positive": 

1478 amplitude_params[amplitude_params < 0] = 0 

1479 elif self.amplitude_priors_method == "smooth": 

1480 null_indices = np.where(amplitude_params < 0)[0] 

1481 for index in null_indices: 

1482 right = amplitude_params[index] 

1483 for i in range(index, min(index + 10, self.Nx)): 

1484 right = amplitude_params[i] 

1485 if i not in null_indices: 

1486 break 

1487 left = amplitude_params[index] 

1488 for i in range(index, max(0, index - 10), -1): 

1489 left = amplitude_params[i] 

1490 if i not in null_indices: 

1491 break 

1492 amplitude_params[index] = 0.5 * (right + left) 

1493 elif self.amplitude_priors_method == "noprior": 

1494 pass 

1495 else: 

1496 M_dot_W_dot_M_plus_Q = [M_dot_W_dot_M[x] + self.reg * self.Q[x, x] for x in range(self.Nx)] 

1497 cov_matrix = np.diag([1 / M_dot_W_dot_M_plus_Q[x] if M_dot_W_dot_M_plus_Q[x] > 0 else 0.1 * self.bgd_std 

1498 for x in range(self.Nx)]) 

1499 amplitude_params = [ 

1500 cov_matrix[x, x] * (M[x].T @ (self.W[x] * self.data[x]) + self.reg * self.Q_dot_A0[x]) 

1501 for x in range(self.Nx)] 

1502 self.M = M 

1503 self.M_dot_W_dot_M = M_dot_W_dot_M 

1504 self.model = np.zeros((self.Nx, self.Ny), dtype=float) 

1505 for x in range(self.Nx): 

1506 self.model[x] = M[x] * amplitude_params[x] 

1507 

1508 else: 

1509 amplitude_params = np.copy(self.amplitude_priors) 

1510 err2 = np.copy(amplitude_params) 

1511 err2[err2 <= 0] = np.min(np.abs(err2[err2 > 0])) 

1512 cov_matrix = np.diag(err2) 

1513 self.amplitude_params = np.copy(amplitude_params) 

1514 self.amplitude_params_err = np.array([np.sqrt(cov_matrix[x, x]) 

1515 if cov_matrix[x, x] > 0 else 0 for x in range(self.Nx)]) 

1516 self.amplitude_cov_matrix = np.copy(cov_matrix) 

1517 poly_params[:self.Nx] = amplitude_params 

1518 self.poly_params = np.copy(poly_params) 

1519 poly_params[self.Nx + self.y_c_0_index] += self.bgd_width 

1520 if self.amplitude_priors_method == "fixed": 

1521 self.model = self.chromatic_psf.build_spectrogram_image(poly_params, mode="1D")[ 

1522 self.bgd_width:-self.bgd_width, :].T 

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

1524 return self.pixels, self.model, self.model_err 

1525 

1526 

1527class ChromaticPSF2DFitWorkspace(ChromaticPSFFitWorkspace): 

1528 

1529 def __init__(self, chromatic_psf, data, data_errors, bgd_model_func=None, amplitude_priors_method="noprior", 

1530 file_name="", nwalkers=18, nsteps=1000, burnin=100, nbins=10, 

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

1532 ChromaticPSFFitWorkspace.__init__(self, chromatic_psf, data, data_errors, bgd_model_func, 

1533 file_name, amplitude_priors_method, nwalkers, nsteps, burnin, nbins, verbose, 

1534 plot, 

1535 live_fit, truth=truth) 

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

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

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

1539 

1540 # error matrix 

1541 # here image uncertainties are assumed to be uncorrelated 

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

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

1544 self.W = self.W.flatten() 

1545 self.data = self.data.flatten() 

1546 self.err = self.err.flatten() 

1547 self.sparse_indices = None 

1548 

1549 # create a mask 

1550 self.data_before_mask = np.copy(self.data) 

1551 self.W_before_mask = np.copy(self.W) 

1552 self.sqrtW = np.sqrt(sparse.diags(self.W)) 

1553 self.set_mask() 

1554 

1555 # regularisation matrices 

1556 self.reg = parameters.PSF_FIT_REG_PARAM 

1557 if amplitude_priors_method == "psf1d": 

1558 # U = np.diag([1 / np.sqrt(np.sum(self.err[:, x]**2)) for x in range(self.Nx)]) 

1559 self.U = np.diag([1 / np.sqrt(self.amplitude_priors_cov_matrix[x, x]) for x in range(self.Nx)]) 

1560 L = np.diag(-2 * np.ones(self.Nx)) + np.diag(np.ones(self.Nx), -1)[:-1, :-1] \ 

1561 + np.diag(np.ones(self.Nx), 1)[:-1, :-1] 

1562 L.astype(float) 

1563 L[0, 0] = -1 

1564 L[-1, -1] = -1 

1565 self.L = L 

1566 self.Q = L.T @ self.U.T @ self.U @ L 

1567 self.Q_dot_A0 = self.Q @ self.amplitude_priors 

1568 

1569 def set_mask(self, poly_params=None): 

1570 if poly_params is None: 

1571 poly_params = self.poly_params 

1572 profile_params = self.chromatic_psf.from_poly_params_to_profile_params(poly_params, apply_bounds=True) 

1573 if np.sum(self.chromatic_psf.table["fwhm"]) == 0: 

1574 self.chromatic_psf.from_profile_params_to_shape_params(profile_params) 

1575 psf_cube = self.chromatic_psf.build_psf_cube(self.pixels, profile_params, 

1576 fwhmx_clip=3 * parameters.PSF_FWHM_CLIP, 

1577 fwhmy_clip=parameters.PSF_FWHM_CLIP, dtype="float32") 

1578 flat_spectrogram = np.sum(psf_cube.reshape(len(profile_params), self.pixels[0].size), axis=0) 

1579 mask = flat_spectrogram / np.max(flat_spectrogram) == 0 

1580 self.data = np.copy(self.data_before_mask) 

1581 self.W = np.copy(self.W_before_mask) 

1582 self.data[mask] = 0 

1583 self.W[mask] = 0 

1584 self.sqrtW = np.sqrt(sparse.diags(self.W)) 

1585 self.sparse_indices = None 

1586 self.mask = list(np.where(mask)[0]) 

1587 

1588 def simulate(self, *shape_params): 

1589 r""" 

1590 Compute a ChromaticPSF2D model given PSF shape parameters and minimizing 

1591 amplitude parameters using a spectrogram data array. 

1592 

1593 The ChromaticPSF2D model :math:`\vec{m}(\vec{x},\vec{p})` can be written as 

1594 

1595 .. math :: 

1596 :label: chromaticpsf2d 

1597 

1598 \vec{m}(\vec{x},\vec{p}) = \sum_{i=0}^{N_x} A_i \phi\left(\vec{x},\vec{p}_i\right) 

1599 

1600 with :math:`\vec{x}` the 2D array of the pixel coordinates, :math:`\vec{A}` the amplitude parameter array 

1601 along the x axis of the spectrogram, :math:`\phi\left(\vec{x},\vec{p}_i\right)` the 2D PSF kernel whose integral 

1602 is normalised to one parametrized with the :math:`\vec{p}_i` non-linear parameter array. If the :math:`\vec{x}` 

1603 2D array is flatten in 1D, equation :eq:`chromaticpsf2d` is 

1604 

1605 .. math :: 

1606 :label: chromaticpsf2d_matrix 

1607 :nowrap: 

1608 

1609 \begin{align} 

1610 \vec{m}(\vec{x},\vec{p}) & = \mathbf{M}\left(\vec{x},\vec{p}\right) \mathbf{A} \\ 

1611 

1612 \mathbf{M}\left(\vec{x},\vec{p}\right) & = \left(\begin{array}{cccc} 

1613 \phi\left(\vec{x}_1,\vec{p}_1\right) & \phi\left(\vec{x}_2,\vec{p}_1\right) & ... 

1614 & \phi\left(\vec{x}_{N_x},\vec{p}_1\right) \\ 

1615 ... & ... & ... & ...\\ 

1616 \phi\left(\vec{x}_1,\vec{p}_{N_x}\right) & \phi\left(\vec{x}_2,\vec{p}_{N_x}\right) & ... 

1617 & \phi\left(\vec{x}_{N_x},\vec{p}_{N_x}\right) \\ 

1618 \end{array}\right) 

1619 \end{align} 

1620 

1621 

1622 with :math:`\mathbf{M}` the design matrix. 

1623 

1624 The goal of this function is to perform a minimisation of the amplitude vector :math:`\mathbf{A}` given 

1625 a set of non-linear parameters :math:`\mathbf{p}` and a spectrogram data array :math:`mathbf{y}` modelise as 

1626 

1627 .. math:: \mathbf{y} = \mathbf{m}(\vec{x},\vec{p}) + \vec{\epsilon} 

1628 

1629 with :math:`\vec{\epsilon}` a random noise vector. The :math:`\chi^2` function to minimise is 

1630 

1631 .. math:: 

1632 :label: chromaticspsf2d_chi2 

1633 

1634 \chi^2(\mathbf{A})= \left(\mathbf{y} - \mathbf{M}\left(\vec{x},\vec{p}\right) \mathbf{A}\right)^T \mathbf{W} 

1635 \left(\mathbf{y} - \mathbf{M}\left(\vec{x},\vec{p}\right) \mathbf{A} \right) 

1636 

1637 

1638 with :math:`\mathbf{W}` the weight matrix, inverse of the covariance matrix. In our case this matrix is diagonal 

1639 as the pixels are considered all independent. The minimum of equation :eq:`chromaticspsf2d_chi2` is reached for 

1640 a the set of amplitude parameters :math:`\hat{\mathbf{A}}` given by 

1641 

1642 .. math:: 

1643 

1644 \hat{\mathbf{A}} = (\mathbf{M}^T \mathbf{W} \mathbf{M})^{-1} \mathbf{M}^T \mathbf{W} \mathbf{y} 

1645 

1646 The error matrix on the :math:`\hat{\mathbf{A}}` coefficient is simply 

1647 :math:`(\mathbf{M}^T \mathbf{W} \mathbf{M})^{-1}`. 

1648 

1649 See Also 

1650 -------- 

1651 ChromaticPSF1DFitWorkspace.simulate 

1652 

1653 Parameters 

1654 ---------- 

1655 shape_params: array_like 

1656 PSF shape polynomial parameter array. 

1657 

1658 Examples 

1659 -------- 

1660 

1661 Set the parameters: 

1662 

1663 .. doctest:: 

1664 

1665 >>> parameters.PIXDIST_BACKGROUND = 40 

1666 >>> parameters.PIXWIDTH_BACKGROUND = 10 

1667 >>> parameters.PIXWIDTH_SIGNAL = 30 

1668 

1669 Build a mock spectrogram with random Poisson noise: 

1670 

1671 .. doctest:: 

1672 

1673 >>> psf = Moffat(clip=False) 

1674 >>> s0 = ChromaticPSF(psf, Nx=120, Ny=100, deg=2, saturation=100000) 

1675 >>> params = s0.generate_test_poly_params() 

1676 >>> params[:s0.Nx] *= 10 

1677 >>> s0.poly_params = params 

1678 >>> saturation = params[-1] 

1679 >>> data = s0.build_spectrogram_image(params, mode="2D") 

1680 >>> bgd = 10*np.ones_like(data) 

1681 >>> data += bgd 

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

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

1684 

1685 Extract the background: 

1686 

1687 .. doctest:: 

1688 

1689 >>> bgd_model_func, _, _ = extract_spectrogram_background_sextractor(data, data_errors, ws=[30,50]) 

1690 

1691 Estimate the first guess values: 

1692 

1693 .. doctest:: 

1694 

1695 >>> s = ChromaticPSF(psf, Nx=120, Ny=100, deg=2, saturation=saturation) 

1696 >>> s.fit_transverse_PSF1D_profile(data, data_errors, w=20, ws=[30,50], 

1697 ... pixel_step=1, bgd_model_func=bgd_model_func, saturation=saturation, live_fit=False) 

1698 >>> s.plot_summary(truth=s0) 

1699 

1700 Simulate the data with fixed amplitude priors: 

1701 

1702 .. doctest:: 

1703 

1704 >>> w = ChromaticPSF2DFitWorkspace(s, data, data_errors, bgd_model_func=bgd_model_func, 

1705 ... amplitude_priors_method="fixed", verbose=True) 

1706 >>> y, mod, mod_err = w.simulate(s.poly_params[s.Nx:]) 

1707 >>> w.plot_fit() 

1708 

1709 .. doctest:: 

1710 :hide: 

1711 

1712 >>> assert mod is not None 

1713 

1714 Simulate the data with a Tikhonov prior on amplitude parameters: 

1715 

1716 .. doctest:: 

1717 

1718 >>> parameters.PSF_FIT_REG_PARAM = 0.002 

1719 >>> s.poly_params = s.from_table_to_poly_params() 

1720 >>> w = ChromaticPSF2DFitWorkspace(s, data, data_errors, bgd_model_func=bgd_model_func, 

1721 ... amplitude_priors_method="psf1d", verbose=True) 

1722 >>> y, mod, mod_err = w.simulate(s.poly_params[s.Nx:]) 

1723 >>> w.plot_fit() 

1724 

1725 .. doctest:: 

1726 :hide: 

1727 

1728 >>> assert mod is not None 

1729 

1730 """ 

1731 # linear regression for the amplitude parameters 

1732 # prepare the vectors 

1733 poly_params = np.copy(self.poly_params) 

1734 poly_params[self.Nx:] = np.copy(shape_params) 

1735 poly_params[self.Nx + self.y_c_0_index] -= self.bgd_width 

1736 profile_params = self.chromatic_psf.from_poly_params_to_profile_params(poly_params, apply_bounds=True) 

1737 profile_params[:self.Nx, 0] = 1 

1738 profile_params[:self.Nx, 1] = np.arange(self.Nx) 

1739 # profile_params[:self.Nx, 2] -= self.bgd_width 

1740 if self.amplitude_priors_method != "fixed": 

1741 # Matrix filling 

1742 psf_cube = self.chromatic_psf.build_psf_cube(self.pixels, profile_params, 

1743 fwhmx_clip=3 * parameters.PSF_FWHM_CLIP, 

1744 fwhmy_clip=parameters.PSF_FWHM_CLIP, dtype="float32") 

1745 M = psf_cube.reshape(len(profile_params), self.pixels[0].size).T # flattening 

1746 self.sparse_indices = np.where(M > 0) 

1747 M = sparse.csr_matrix((M[self.sparse_indices].ravel(), self.sparse_indices), shape=M.shape, dtype="float32") 

1748 M_dot_W = M.T * self.sqrtW 

1749 # Compute the minimizing amplitudes 

1750 M_dot_W_dot_M = M_dot_W @ M_dot_W.T 

1751 if self.amplitude_priors_method != "psf1d": 

1752 # try: 

1753 # L = np.linalg.inv(np.linalg.cholesky(M_dot_W_dot_M)) 

1754 # cov_matrix = L.T @ L 

1755 # except np.linalg.LinAlgError: 

1756 cov_matrix = np.linalg.inv(M_dot_W_dot_M) 

1757 amplitude_params = cov_matrix @ (M.T @ (self.W * self.data)) 

1758 if self.amplitude_priors_method == "positive": 

1759 amplitude_params[amplitude_params < 0] = 0 

1760 elif self.amplitude_priors_method == "smooth": 

1761 null_indices = np.where(amplitude_params < 0)[0] 

1762 for index in null_indices: 

1763 right = amplitude_params[index] 

1764 for i in range(index, min(index + 10, self.Nx)): 

1765 right = amplitude_params[i] 

1766 if i not in null_indices: 

1767 break 

1768 left = amplitude_params[index] 

1769 for i in range(index, max(0, index - 10), -1): 

1770 left = amplitude_params[i] 

1771 if i not in null_indices: 

1772 break 

1773 amplitude_params[index] = 0.5 * (right + left) 

1774 elif self.amplitude_priors_method == "noprior": 

1775 pass 

1776 else: 

1777 M_dot_W_dot_M_plus_Q = M_dot_W_dot_M + self.reg * self.Q 

1778 # try: 

1779 # L = np.linalg.inv(np.linalg.cholesky(M_dot_W_dot_M_plus_Q)) 

1780 # cov_matrix = L.T @ L 

1781 # except np.linalg.LinAlgError: 

1782 cov_matrix = np.linalg.inv(M_dot_W_dot_M_plus_Q) 

1783 amplitude_params = cov_matrix @ (M.T @ (self.W * self.data) + self.reg * self.Q_dot_A0) 

1784 amplitude_params = np.asarray(amplitude_params).reshape(-1) 

1785 self.M = M 

1786 self.M_dot_W_dot_M = M_dot_W_dot_M 

1787 self.model = M @ amplitude_params 

1788 else: 

1789 amplitude_params = np.copy(self.amplitude_priors) 

1790 err2 = np.copy(amplitude_params) 

1791 err2[err2 <= 0] = np.min(np.abs(err2[err2 > 0])) 

1792 cov_matrix = np.diag(err2) 

1793 poly_params[:self.Nx] = amplitude_params 

1794 self.poly_params = np.copy(poly_params) 

1795 self.amplitude_params = np.copy(amplitude_params) 

1796 # TODO: propagate and marginalize over the shape parameter uncertainties ? 

1797 self.amplitude_params_err = np.array([np.sqrt(cov_matrix[x, x]) for x in range(self.Nx)]) 

1798 self.amplitude_cov_matrix = np.copy(cov_matrix) 

1799 # in_bounds, penalty, name = self.chromatic_psf.check_bounds(poly_params, noise_level=self.bgd_std) 

1800 if self.amplitude_priors_method == "fixed": 

1801 poly_params[self.Nx + self.y_c_0_index] += self.bgd_width 

1802 self.model = self.chromatic_psf.build_spectrogram_image(poly_params, mode="2D")[ 

1803 self.bgd_width:-self.bgd_width, :] 

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

1805 return self.pixels, self.model, self.model_err 

1806 

1807 

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

1809 import doctest 

1810 

1811 doctest.testmod()