Coverage for spectractor/extractor/images.py: 7%

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

472 statements  

1from astropy.coordinates import Angle, SkyCoord, Latitude 

2from astropy.io import fits 

3import astropy.units as units 

4from scipy import ndimage 

5from matplotlib import cm 

6import matplotlib.pyplot as plt 

7import numpy as np 

8import os 

9import copy 

10 

11from spectractor import parameters 

12from spectractor.config import set_logger, load_config 

13from spectractor.extractor.targets import load_target 

14from spectractor.extractor.dispersers import Hologram 

15from spectractor.extractor.psf import Moffat 

16from spectractor.simulation.adr import hadec2zdpar 

17from spectractor.simulation.throughput import TelescopeTransmission 

18from spectractor.tools import (plot_image_simple, save_fits, load_fits, fit_poly1d, plot_compass_simple, 

19 fit_poly1d_outlier_removal, weighted_avg_and_std, 

20 fit_poly2d_outlier_removal, hessian_and_theta, 

21 set_wcs_file_name, load_wcs_from_file, imgslice) 

22 

23 

24class Image(object): 

25 """ The image class contains all the features necessary to load an image and extract a spectrum. 

26 

27 Attributes 

28 ---------- 

29 my_logger: logging 

30 Logging object 

31 file_name: str 

32 The file name of the exposure. 

33 units: str 

34 Units of the image. 

35 data: array 

36 Image 2D array in self.units units. 

37 stat_errors: array 

38 Image 2D uncertainty array in self.units units. 

39 target_pixcoords: array 

40 Target position [x,y] in the image in pixels. 

41 data_rotated: array 

42 Rotated image 2D array in self.units units. 

43 stat_errors_rotated: array 

44 Rotated image 2D uncertainty array in self.units units. 

45 target_pixcoords_rotated: array 

46 Target position [x,y] in the rotated image in pixels. 

47 date_obs: str 

48 Date of the observation. 

49 airmass: float 

50 Airmass of the current target. 

51 expo: float 

52 Exposure time in seconds. 

53 disperser_label: str 

54 Label of the disperser. 

55 filter_label: str: 

56 Label of the filter. 

57 target_label: str: 

58 Label of the current target. 

59 rotation_angle: float 

60 Dispersion axis angle in the image in degrees, positive if anticlockwise. 

61 parallactic_angle: float 

62 Parallactic angle in degrees. 

63 header: Fits.Header 

64 FITS file header. 

65 disperser: Disperser 

66 Disperser instance that describes the disperser. 

67 target: Target 

68 Target instance that describes the current target. 

69 ra: float 

70 Right ascension coordinate of the current exposure. 

71 dec: float 

72 Declination coordinate of the current exposure. 

73 hour_angle float 

74 Hour angle coordinate of the current exposure. 

75 temperature: float 

76 Outside temperature in Celsius degrees. 

77 pressure: float 

78 Outside pressure in hPa. 

79 humidity: float 

80 Outside relative humidity in fraction of one. 

81 saturation: float 

82 Level of saturation in the image in image units. 

83 target_star2D: PSF 

84 PSF instance fitted on the current target. 

85 target_bkgd2D: callable 

86 Function that models the background behind the current target. 

87 

88 """ 

89 

90 def __init__(self, file_name, *, target_label="", disperser_label="", 

91 config="", **kwargs): 

92 """ 

93 The image class contains all the features necessary to load an image and extract a spectrum. 

94 

95 Parameters 

96 ---------- 

97 file_name: str 

98 The file name where the image is. 

99 target_label: str, optional 

100 The target name, to be found in data bases. 

101 disperser_label: str, optional 

102 The disperser label to load its properties 

103 config: str, optional 

104 A config file name to load some parameter values for a given instrument (default: ""). 

105 

106 Examples 

107 -------- 

108 

109 .. doctest:: 

110 

111 >>> im = Image('tests/data/reduc_20170605_028.fits') 

112 

113 .. doctest:: 

114 :hide: 

115 

116 >>> assert im.file_name == 'tests/data/reduc_20170605_028.fits' 

117 >>> assert im.data is not None and np.mean(im.data) > 0 

118 >>> assert im.stat_errors is not None and np.mean(im.stat_errors) > 0 

119 >>> assert im.header is not None 

120 >>> assert im.gain is not None and np.mean(im.gain) > 0 

121 

122 """ 

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

124 if config != "": 

125 load_config(config) 

126 if not os.path.isfile(file_name) and parameters.CALLING_CODE != 'LSST_DM': 

127 raise FileNotFoundError(f"File {file_name} does not exist.") 

128 self.file_name = file_name 

129 self.units = 'ADU' 

130 self.expo = -1 

131 self.airmass = -1 

132 self.date_obs = None 

133 self.disperser = None 

134 self.disperser_label = disperser_label 

135 self.target_label = target_label 

136 self.target_guess = None 

137 self.filter_label = "" 

138 self.filters = None 

139 self.header = None 

140 self.data = None 

141 self.data_rotated = None 

142 self.gain = None # in e-/ADU 

143 self.read_out_noise = None 

144 self.stat_errors = None 

145 self.stat_errors_rotated = None 

146 self.rotation_angle = 0 

147 self.parallactic_angle = None 

148 self.saturation = None 

149 

150 self.ra = None 

151 self.dec = None 

152 self.hour_angle = None 

153 self.temperature = 0 

154 self.pressure = 0 

155 self.humidity = 0 

156 

157 if parameters.CALLING_CODE != 'LSST_DM': 

158 self.load_image(file_name) 

159 else: 

160 # data provided by the LSST shim, just instantiate objects 

161 # necessary for the following code not to fail 

162 self.header = fits.header.Header() 

163 self.filter_label = kwargs.get('filter_label', '') 

164 # Load the target if given 

165 self.target = None 

166 self.target_pixcoords = None 

167 self.target_pixcoords_rotated = None 

168 self.target_bkgd2D = None 

169 self.target_star2D = None 

170 self.header['TARGET'] = self.target_label 

171 self.header.comments['TARGET'] = 'name of the target in the image' 

172 self.header['REDSHIFT'] = 0 

173 self.header.comments['REDSHIFT'] = 'redshift of the target' 

174 self.header["GRATING"] = self.disperser_label 

175 self.header.comments["GRATING"] = "name of the disperser" 

176 self.header['ROTANGLE'] = self.rotation_angle 

177 self.header.comments["ROTANGLE"] = "[deg] angle of the dispersion axis" 

178 self.header['D2CCD'] = parameters.DISTANCE2CCD 

179 self.header.comments["D2CCD"] = "[mm] distance between disperser and CCD" 

180 

181 if self.filter_label != "" and "empty" not in self.filter_label.lower(): 

182 t = TelescopeTransmission(filter_label=self.filter_label) 

183 t.reset_lambda_range(transmission_threshold=1e-4) 

184 

185 if self.target_label != "": 

186 self.target = load_target(self.target_label, verbose=parameters.VERBOSE) 

187 self.header['REDSHIFT'] = str(self.target.redshift) 

188 

189 def load_image(self, file_name): 

190 """ 

191 Load the image and store some information from header in class attributes. 

192 Then load the target and disperser properties. Called when an Image instance is created. 

193 

194 Parameters 

195 ---------- 

196 file_name: str 

197 The fits file name. 

198 

199 """ 

200 if parameters.OBS_NAME == 'CTIO': 

201 load_CTIO_image(self) 

202 elif parameters.OBS_NAME == 'LPNHE': 

203 load_LPNHE_image(self) 

204 if parameters.OBS_NAME == "AUXTEL": 

205 load_AUXTEL_image(self) 

206 # Load the disperser 

207 self.my_logger.info(f'\n\tLoading disperser {self.disperser_label}...') 

208 self.header["GRATING"] = self.disperser_label 

209 self.header["AIRMASS"] = self.airmass 

210 self.header["DATE-OBS"] = self.date_obs 

211 self.header["EXPTIME"] = self.expo 

212 self.header['OUTTEMP'] = self.temperature 

213 self.header['OUTPRESS'] = self.pressure 

214 self.header['OUTHUM'] = self.humidity 

215 self.header['CCDREBIN'] = parameters.CCD_REBIN 

216 

217 self.disperser = Hologram(self.disperser_label, D=parameters.DISTANCE2CCD, 

218 data_dir=parameters.DISPERSER_DIR, verbose=parameters.VERBOSE) 

219 self.compute_statistical_error() 

220 self.convert_to_ADU_rate_units() 

221 

222 def save_image(self, output_file_name, overwrite=False): 

223 """Save the image in a fits file. 

224 

225 Parameters 

226 ---------- 

227 output_file_name: str 

228 The output file name. 

229 overwrite: bool 

230 If True, overwrite the file if it exists previously (default: False). 

231 

232 Examples 

233 -------- 

234 >>> im = Image('tests/data/reduc_20170605_028.fits') 

235 >>> im.save_image('tests/data/reduc_20170605_028_copy.fits', overwrite=True) 

236 """ 

237 save_fits(output_file_name, self.header, self.data, overwrite=overwrite) 

238 self.my_logger.info(f'\n\tImage saved in {output_file_name}') 

239 

240 def convert_to_ADU_rate_units(self): 

241 """Convert Image data from ADU to ADU/s units. 

242 

243 Examples 

244 -------- 

245 >>> im = Image('tests/data/reduc_20170605_028.fits') 

246 >>> print(im.expo) 

247 600.0 

248 >>> data_before = np.copy(im.data) 

249 >>> im.convert_to_ADU_rate_units() 

250 

251 .. doctest:: 

252 :hide: 

253 

254 >>> assert np.all(np.isclose(data_before, im.data * im.expo)) 

255 """ 

256 self.data = self.data.astype(np.float64) / self.expo 

257 self.stat_errors /= self.expo 

258 if self.stat_errors_rotated is not None: 

259 self.stat_errors_rotated /= self.expo 

260 self.units = 'ADU/s' 

261 

262 def convert_to_ADU_units(self): 

263 """Convert Image data from ADU/s to ADU units. 

264 

265 Examples 

266 -------- 

267 >>> im = Image('tests/data/reduc_20170605_028.fits') 

268 >>> print(im.expo) 

269 600.0 

270 >>> data_before = np.copy(im.data) 

271 >>> im.convert_to_ADU_rate_units() 

272 >>> data_after = np.copy(im.data) 

273 >>> im.convert_to_ADU_units() 

274 

275 .. doctest:: 

276 :hide: 

277 

278 >>> assert np.all(np.isclose(data_before, im.data)) 

279 """ 

280 self.data *= self.expo 

281 self.stat_errors *= self.expo 

282 if self.stat_errors_rotated is not None: 

283 self.stat_errors_rotated *= self.expo 

284 self.units = 'ADU' 

285 

286 def compute_statistical_error(self): 

287 """Compute the image noise map from Image.data. The latter must be in ADU. 

288 The function first converts the image in electron counts units, evaluate the Poisson noise, 

289 add in quadrature the read-out noise, takes the square root and returns a map in ADU units. 

290 

291 Examples 

292 -------- 

293 .. doctest:: 

294 

295 >>> im = Image('tests/data/reduc_20170530_134.fits') 

296 >>> im.convert_to_ADU_units() 

297 >>> im.compute_statistical_error() 

298 >>> im.plot_statistical_error() 

299 

300 .. plot:: 

301 

302 from spectractor.extractor.images import Image 

303 im = Image('tests/data/reduc_20170530_134.fits') 

304 im.convert_to_ADU_units() 

305 im.plot_statistical_error() 

306 

307 """ 

308 if self.units != 'ADU': 

309 raise AttributeError(f'Noise must be estimated on an image in ADU units. ' 

310 f'Currently self.units={self.units}.') 

311 # removes the zeros and negative pixels first 

312 # set to minimum positive value 

313 data = np.copy(self.data) 

314 # OLD: compute poisson noise in ADU/s without read-out noise 

315 # self.stat_errors = np.sqrt(data) / np.sqrt(self.gain * self.expo) 

316 # convert in e- counts 

317 err2 = data * self.gain 

318 if self.read_out_noise is not None: 

319 err2 += self.read_out_noise * self.read_out_noise 

320 # remove negative values (due to dead columns for instance 

321 min_noz = np.min(err2[err2 > 0]) 

322 err2[err2 <= 0] = min_noz 

323 self.stat_errors = np.sqrt(err2) 

324 # convert in ADU 

325 self.stat_errors /= self.gain 

326 # check uncertainty model 

327 self.check_statistical_error() 

328 

329 def check_statistical_error(self): 

330 """Check that statistical uncertainty map follows the input uncertainty model 

331 in terms of gain and read-out noise. 

332 

333 A linear model is fitted to the squared pixel uncertainty values with respect to the pixel data values. 

334 The slop gives the gain value and the intercept gives the read-out noise value. 

335 

336 Returns 

337 ------- 

338 fit: tuple 

339 The best fit parameter of the linear model. 

340 x: array_like 

341 The x data used for the fit (data). 

342 y: array_like 

343 The y data used for the fit (squared uncertainties). 

344 model: array_like 

345 The linear model values. 

346 

347 Examples 

348 -------- 

349 

350 .. doctest:: 

351 

352 >>> im = Image('tests/data/reduc_20170530_134.fits') 

353 >>> im.convert_to_ADU_units() 

354 >>> fit, x, y, model = im.check_statistical_error() 

355 

356 .. doctest:: 

357 :hide: 

358 

359 >>> assert fit is not None 

360 >>> assert len(fit) == 2 

361 >>> assert x.shape == y.shape 

362 >>> assert y.shape == model.shape 

363 

364 """ 

365 if self.units != "ADU": 

366 raise AttributeError(f"Noise map must be in ADU units to be plotted and analyzed. " 

367 f"Currently self.units={self.units}.") 

368 data = np.copy(self.data) 

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

370 data[data <= 0] = min_noz 

371 y = self.stat_errors.flatten() ** 2 

372 x = data.flatten() 

373 fit, cov, model = fit_poly1d(x, y, order=1) 

374 gain = 1 / fit[0] 

375 read_out = np.sqrt(fit[1]) * gain 

376 if not np.isclose(gain, np.mean(self.gain), rtol=1e-2): 

377 self.my_logger.warning(f"\n\tFitted gain seems to be different than input gain. " 

378 f"Fit={gain} but average of self.gain is {np.mean(self.gain)}.") 

379 if not np.isclose(read_out, np.mean(self.read_out_noise), rtol=1e-2): 

380 self.my_logger.warning(f"\n\tFitted read out noise seems to be different than input readout noise. " 

381 f"Fit={read_out} but average of self.read_out_noise is " 

382 f"{np.mean(self.read_out_noise)}.") 

383 return fit, x, y, model 

384 

385 def plot_statistical_error(self): 

386 """Plot the statistical uncertainty map and check it is a Poisson noise. 

387 

388 The image units must be ADU. 

389 

390 Examples 

391 -------- 

392 

393 .. doctest:: 

394 

395 >>> im = Image('tests/data/reduc_20170530_134.fits') 

396 >>> im.convert_to_ADU_units() 

397 >>> im.plot_statistical_error() 

398 

399 .. plot:: 

400 

401 from spectractor.extractor.images import Image 

402 im = Image('tests/data/reduc_20170530_134.fits') 

403 im.convert_to_ADU_units() 

404 im.plot_statistical_error() 

405 

406 """ 

407 fig, ax = plt.subplots(1, 2, figsize=(12, 5)) 

408 fit, x, y, model = self.check_statistical_error() 

409 gain = 1 / fit[0] 

410 read_out = np.sqrt(fit[1]) * gain 

411 ax[0].text(0.05, 0.95, f"fitted gain={gain:.3g} [e-/ADU]\nintercept={fit[1]:.3g} [ADU$^2$]" 

412 f"\nfitted read-out={read_out:.3g} [ADU]", 

413 horizontalalignment='left', verticalalignment='top', transform=ax[0].transAxes) 

414 ax[0].scatter(x, y) 

415 ax[0].plot(x, model, "k-") 

416 ax[0].grid() 

417 ax[0].set_ylabel(r"$\sigma_{\mathrm{ADU}}^2$ [ADU$^2$]") 

418 ax[0].set_xlabel(r"Data pixel values [ADU]") 

419 plot_image_simple(ax[1], data=self.stat_errors, scale="log10", title="Statistical uncertainty map", 

420 units=self.units, target_pixcoords=None, aspect="auto", cmap=None) 

421 fig.tight_layout() 

422 if parameters.LSST_SAVEFIGPATH: # pragma: no cover 

423 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'uncertainty_map.pdf')) 

424 if parameters.DISPLAY: # pragma: no cover 

425 plt.show() 

426 

427 def compute_parallactic_angle(self): 

428 """Compute the parallactic angle. 

429 

430 Script from A. Guyonnet. 

431 """ 

432 latitude = Latitude(parameters.OBS_LATITUDE, unit=units.deg) 

433 ha = self.hour_angle 

434 dec = self.dec 

435 # parallactic_angle = Angle(np.arctan2(np.sin(ha), (np.cos(dec) * np.tan(latitude) - np.sin(dec) * np.cos(ha)))) 

436 zenithal_distance, parallactic_angle = hadec2zdpar(ha, dec, latitude, deg=False) 

437 self.parallactic_angle = parallactic_angle.value * 180 / np.pi 

438 self.header['PARANGLE'] = self.parallactic_angle 

439 self.header.comments['PARANGLE'] = 'parallactic angle in degree' 

440 return self.parallactic_angle 

441 

442 def plot_image(self, ax=None, scale="lin", title="", units="", plot_stats=False, 

443 target_pixcoords=None, figsize=(7.3, 6), aspect=None, vmin=None, vmax=None, 

444 cmap=None, cax=None): 

445 """Plot image. 

446 

447 Parameters 

448 ---------- 

449 ax: Axes, optional 

450 Axes instance (default: None). 

451 scale: str 

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

453 title: str 

454 Title of the image (default: "") 

455 units: str 

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

457 cmap: colormap 

458 Color map label (default: None) 

459 target_pixcoords: array_like, optional 

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

461 vmin: float 

462 Minimum value of the image (default: None) 

463 vmax: float 

464 Maximum value of the image (default: None) 

465 aspect: str 

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

467 cax: Axes, optional 

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

469 figsize: tuple 

470 Figure size (default: [9.3, 8]). 

471 plot_stats: bool 

472 If True, plot the uncertainty map instead of the image (default: False). 

473 

474 Examples 

475 -------- 

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

477 >>> im.plot_image(target_pixcoords=[820, 580], scale="symlog") 

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

479 """ 

480 if ax is None: 

481 plt.figure(figsize=figsize) 

482 ax = plt.gca() 

483 data = np.copy(self.data) 

484 if plot_stats: 

485 data = np.copy(self.stat_errors) 

486 if units == "": 

487 units = self.units 

488 plot_image_simple(ax, data=data, scale=scale, title=title, units=units, cax=cax, 

489 target_pixcoords=target_pixcoords, aspect=aspect, vmin=vmin, vmax=vmax, cmap=cmap) 

490 if parameters.OBS_OBJECT_TYPE == "STAR": 

491 plot_compass_simple(ax, self.parallactic_angle, arrow_size=0.1, origin=[0.15, 0.15]) 

492 plt.legend() 

493 if parameters.LSST_SAVEFIGPATH: # pragma: no cover 

494 plt.gcf().savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'image.pdf')) 

495 if parameters.DISPLAY: # pragma: no cover 

496 plt.show() 

497 if parameters.PdfPages: 

498 parameters.PdfPages.savefig() 

499 

500def load_CTIO_image(image): 

501 """Specific routine to load CTIO fits files and load their data and properties for Spectractor. 

502 

503 Parameters 

504 ---------- 

505 image: Image 

506 The Image instance to fill with file data and header. 

507 """ 

508 image.my_logger.info(f'\n\tLoading CTIO image {image.file_name}...') 

509 image.header, image.data = load_fits(image.file_name) 

510 

511 image.date_obs = image.header['DATE-OBS'] 

512 image.airmass = float(image.header['AIRMASS']) 

513 image.expo = float(image.header['EXPTIME']) 

514 image.filters = image.header['FILTERS'] 

515 if "dia" not in image.header['FILTER1'].lower(): 

516 image.filter_label = image.header['FILTER1'] 

517 image.disperser_label = image.header['FILTER2'] 

518 image.ra = Angle(image.header['RA'], unit="hourangle") 

519 image.dec = Angle(image.header['DEC'], unit="deg") 

520 image.hour_angle = Angle(image.header['HA'], unit="hourangle") 

521 image.temperature = image.header['OUTTEMP'] 

522 image.pressure = image.header['OUTPRESS'] 

523 image.humidity = image.header['OUTHUM'] 

524 

525 parameters.CCD_IMSIZE = int(image.header['XLENGTH']) 

526 parameters.CCD_PIXEL2ARCSEC = float(image.header['XPIXSIZE']) 

527 if image.header['YLENGTH'] != parameters.CCD_IMSIZE: 

528 image.my_logger.warning( 

529 f'\n\tImage rectangular: X={parameters.CCD_IMSIZE:d} pix, Y={image.header["YLENGTH"]:d} pix') 

530 image.coord = SkyCoord(image.header['RA'] + ' ' + image.header['DEC'], unit=(units.hourangle, units.deg), 

531 obstime=image.header['DATE-OBS']) 

532 image.my_logger.info(f'\n\tImage {image.file_name} loaded.') 

533 # compute CCD gain map 

534 build_CTIO_gain_map(image) 

535 build_CTIO_read_out_noise_map(image) 

536 image.compute_parallactic_angle() 

537 

538 

539def build_CTIO_gain_map(image): 

540 """Compute the CTIO gain map according to header GAIN values. 

541 

542 Parameters 

543 ---------- 

544 image: Image 

545 The Image instance to fill with file data and header. 

546 """ 

547 size = parameters.CCD_IMSIZE 

548 image.gain = np.zeros_like(image.data) 

549 # ampli 11 

550 image.gain[0:size // 2, 0:size // 2] = image.header['GTGAIN11'] 

551 # ampli 12 

552 image.gain[0:size // 2, size // 2:size] = image.header['GTGAIN12'] 

553 # ampli 21 

554 image.gain[size // 2:size, 0:size] = image.header['GTGAIN21'] 

555 # ampli 22 

556 image.gain[size // 2:size, size // 2:size] = image.header['GTGAIN22'] 

557 

558 

559def build_CTIO_read_out_noise_map(image): 

560 """Compute the CTIO gain map according to header GAIN values. 

561 

562 Parameters 

563 ---------- 

564 image: Image 

565 The Image instance to fill with file data and header. 

566 """ 

567 size = parameters.CCD_IMSIZE 

568 image.read_out_noise = np.zeros_like(image.data) 

569 # ampli 11 

570 image.read_out_noise[0:size // 2, 0:size // 2] = image.header['GTRON11'] 

571 # ampli 12 

572 image.read_out_noise[0:size // 2, size // 2:size] = image.header['GTRON12'] 

573 # ampli 21 

574 image.read_out_noise[size // 2:size, 0:size] = image.header['GTRON21'] 

575 # ampli 22 

576 image.read_out_noise[size // 2:size, size // 2:size] = image.header['GTRON22'] 

577 

578 

579def load_LPNHE_image(image): # pragma: no cover 

580 """Specific routine to load LPNHE fits files and load their data and properties for Spectractor. 

581 

582 Parameters 

583 ---------- 

584 image: Image 

585 The Image instance to fill with file data and header. 

586 """ 

587 image.my_logger.info(f'\n\tLoading LPNHE image {image.file_name}...') 

588 hdus = fits.open(image.file_name) 

589 image.header = hdus[0].header 

590 hdu1 = hdus["CHAN_14"] 

591 hdu2 = hdus["CHAN_06"] 

592 data1 = hdu1.data[imgslice(hdu1.header['DATASEC'])].astype(np.float64) 

593 bias1 = np.median(hdu1.data[imgslice(hdu1.header['BIASSEC'])].astype(np.float64)) 

594 data1 -= bias1 

595 detsecy, detsecx = imgslice(hdu1.header['DETSEC']) 

596 if detsecy.start > detsecy.stop: 

597 data1 = data1[:, ::-1] 

598 if detsecx.start > detsecx.stop: 

599 data1 = data1[::-1, :] 

600 data2 = hdu2.data[imgslice(hdu2.header['DATASEC'])].astype(np.float64) 

601 bias2 = np.median(hdu2.data[imgslice(hdu2.header['BIASSEC'])].astype(np.float64)) 

602 data2 -= bias2 

603 detsecy, detsecx = imgslice(hdu2.header['DETSEC']) 

604 if detsecy.start > detsecy.stop: 

605 data2 = data2[:, ::-1] 

606 if detsecx.start > detsecx.stop: 

607 data2 = data2[::-1, :] 

608 data = np.concatenate([data2, data1]) 

609 image.data = data[::-1, :].T 

610 image.date_obs = image.header['DATE-OBS'] 

611 image.expo = float(image.header['EXPTIME']) 

612 image.airmass = -1 

613 parameters.DISTANCE2CCD -= float(hdus["XYZ"].header["ZPOS"]) 

614 if "mm" not in hdus["XYZ"].header.comments["ZPOS"]: 

615 raise KeyError(f'mm is absent from ZPOS key in XYZ header. Had {hdus["XYZ"].header.comments["ZPOS"]}' 

616 f'Distances along Z axis must be in mm.') 

617 image.my_logger.info(f'\n\tDistance to CCD adjusted to {parameters.DISTANCE2CCD} mm ' 

618 f'considering XYZ platform is set at ZPOS={float(hdus["XYZ"].header["ZPOS"])} mm.') 

619 # compute CCD gain map 

620 image.gain = float(image.header['CCDGAIN']) * np.ones_like(image.data) 

621 image.read_out_noise = float(image.header['CCDNOISE']) * np.ones_like(image.data) 

622 parameters.CCD_IMSIZE = image.data.shape[1] 

623 # save xys platform position into main header 

624 image.header["XPOS"] = hdus["XYZ"].header["XPOS"] 

625 image.header.comments["XPOS"] = hdus["XYZ"].header.comments["XPOS"] 

626 image.header["YPOS"] = hdus["XYZ"].header["YPOS"] 

627 image.header.comments["YPOS"] = hdus["XYZ"].header.comments["YPOS"] 

628 image.header["ZPOS"] = hdus["XYZ"].header["ZPOS"] 

629 image.header.comments["ZPOS"] = hdus["XYZ"].header.comments["ZPOS"] 

630 image.my_logger.info('\n\tImage loaded') 

631 

632 

633def load_AUXTEL_image(image): # pragma: no cover 

634 """Specific routine to load AUXTEL fits files and load their data and properties for Spectractor. 

635 

636 Parameters 

637 ---------- 

638 image: Image 

639 The Image instance to fill with file data and header. 

640 """ 

641 image.my_logger.info(f'\n\tLoading AUXTEL image {image.file_name}...') 

642 hdu_list = fits.open(image.file_name) 

643 image.header = hdu_list[0].header 

644 image.data = hdu_list[1].data.astype(np.float64) 

645 hdu_list.close() # need to free allocation for file descripto 

646 image.date_obs = image.header['DATE'] 

647 image.expo = float(image.header['EXPTIME']) 

648 if "empty" not in image.header['FILTER'].lower(): 

649 image.filter_label = image.header['FILTER'] 

650 # transformations so that stars are like in Stellarium up to a rotation 

651 # with spectrogram nearly horizontal and on the right of central star 

652 image.data = image.data.T[::-1, ::-1] 

653 if image.header["AMSTART"] is not None: 

654 image.airmass = 0.5 * (float(image.header["AMSTART"]) + float(image.header["AMEND"])) 

655 else: 

656 image.airmass = float(image.header['AIRMASS']) 

657 image.my_logger.info('\n\tImage loaded') 

658 # compute CCD gain map 

659 image.gain = float(parameters.CCD_GAIN) * np.ones_like(image.data) 

660 parameters.CCD_IMSIZE = image.data.shape[1] 

661 image.disperser_label = image.header['GRATING'] 

662 image.ra = Angle(image.header['RA'], unit="deg") 

663 image.dec = Angle(image.header['DEC'], unit="deg") 

664 if 'HASTART' in image.header and image.header['HASTART'] is not None: 

665 image.hour_angle = Angle(image.header['HASTART'], unit="hourangle") 

666 else: 

667 image.hour_angle = Angle(image.header['HA'], unit="deg") 

668 if 'AIRTEMP' in image.header: 

669 image.temperature = image.header['AIRTEMP'] 

670 else: 

671 image.temperature = 10 

672 if 'PRESSURE' in image.header: 

673 image.pressure = image.header['PRESSURE'] 

674 else: 

675 image.pressure = 743 

676 if 'HUMIDITY' in image.header: 

677 image.humidity = image.header['HUMIDITY'] 

678 else: 

679 image.humidity = 40 

680 if 'adu' in image.header['BUNIT']: 

681 image.units = 'ADU' 

682 parameters.OBS_CAMERA_ROTATION = 90 - float(image.header["ROTPA"]) 

683 if parameters.OBS_CAMERA_ROTATION > 360: 

684 parameters.OBS_CAMERA_ROTATION -= 360 

685 if parameters.OBS_CAMERA_ROTATION < -360: 

686 parameters.OBS_CAMERA_ROTATION += 360 

687 if "CD2_1" in hdu_list[1].header: 

688 rotation_wcs = 180 / np.pi * np.arctan2(hdu_list[1].header["CD2_1"], hdu_list[1].header["CD1_1"]) + 90 

689 if not np.isclose(rotation_wcs % 360, parameters.OBS_CAMERA_ROTATION % 360, atol=2): 

690 image.my_logger.warning(f"\n\tWCS rotation angle is {rotation_wcs} degree while " 

691 f"parameters.OBS_CAMERA_ROTATION={parameters.OBS_CAMERA_ROTATION} degree. " 

692 f"\nBoth differs by more than 2 degree... bug ?") 

693 parameters.OBS_ALTITUDE = float(image.header['OBS-ELEV']) / 1000 

694 parameters.OBS_LATITUDE = image.header['OBS-LAT'] 

695 image.read_out_noise = 8.5 * np.ones_like(image.data) 

696 image.target_label = image.header["OBJECT"].replace(" ", "") 

697 if "OBJECTX" in image.header: 

698 image.target_guess = [parameters.CCD_IMSIZE - float(image.header["OBJECTY"]), 

699 parameters.CCD_IMSIZE - float(image.header["OBJECTX"])] 

700 image.disperser_label = image.header["GRATING"] 

701 parameters.DISTANCE2CCD = 115 + float(image.header["LINSPOS"]) # mm 

702 image.compute_parallactic_angle() 

703 

704 

705def find_target(image, guess=None, rotated=False, use_wcs=True, widths=[parameters.XWINDOW, parameters.YWINDOW]): 

706 """Find the target in the Image instance. 

707 

708 The object is search in a windows of size defined by the XWINDOW and YWINDOW parameters, 

709 using two iterative fits of a PSF model. 

710 User must give a guess array in the raw image. 

711 

712 Parameters 

713 ---------- 

714 image: Image 

715 The Image instance. 

716 guess: array_like 

717 Two parameter array giving the estimated position of the target in the image, optional if WCS is used. 

718 rotated: bool 

719 If True, the target is searched in the rotated image. 

720 use_wcs: bool 

721 If True, the WCS file (if found) is used to set the target position in pixels, 

722 guess parameter is then unnecessary. 

723 widths: (int, int) 

724 Two parameter array to define the width of the cropped image (default: [parameters.XWINDOW, parameters.YWINDOW]) 

725 

726 Returns 

727 ------- 

728 x0: float 

729 The x position of the target. 

730 y0: float 

731 The y position of the target. 

732 

733 Examples 

734 -------- 

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

736 >>> im.plot_image() 

737 >>> guess = [820, 580] 

738 >>> parameters.VERBOSE = True 

739 >>> parameters.DEBUG = True 

740 >>> x1, y1 = find_target(im, guess) 

741 """ 

742 my_logger = set_logger(__name__) 

743 target_pixcoords = [-1, -1] 

744 theX = -1 

745 theY = -1 

746 if use_wcs: 

747 wcs_file_name = set_wcs_file_name(image.file_name) 

748 if os.path.isfile(wcs_file_name): 

749 my_logger.info(f"\n\tUse WCS {wcs_file_name} to find target pixel position.") 

750 if rotated: 

751 target_pixcoords = find_target_after_rotation(image) 

752 theX, theY = target_pixcoords 

753 else: 

754 wcs = load_wcs_from_file(wcs_file_name) 

755 target_coord_after_motion = image.target.get_radec_position_after_pm(image.date_obs) 

756 # noinspection PyUnresolvedReferences 

757 target_pixcoords = np.array(wcs.all_world2pix(target_coord_after_motion.ra, 

758 target_coord_after_motion.dec, 0)) 

759 theX, theY = target_pixcoords / parameters.CCD_REBIN 

760 sub_image_subtracted, x0, y0, Dx, Dy, sub_errors = find_target_init(image=image, guess=[theX, theY], 

761 rotated=rotated, widths=widths) 

762 sub_image_x0 = theX - x0 + Dx 

763 sub_image_y0 = theX - y0 + Dy 

764 if parameters.DEBUG: 

765 plt.figure(figsize=(5, 5)) 

766 plot_image_simple(plt.gca(), data=sub_image_subtracted, scale="lin", title="", units=image.units, 

767 target_pixcoords=[theX - x0 + Dx, theX - x0 + Dx]) 

768 plt.show() 

769 if parameters.PdfPages: 

770 parameters.PdfPages.savefig() 

771 else: 

772 my_logger.info(f"\n\tNo WCS {wcs_file_name} available, use 2D fit to find target pixel position.") 

773 if target_pixcoords[0] == -1 and target_pixcoords[1] == -1: 

774 if guess is None: 

775 raise ValueError(f"Guess parameter must be set if WCS solution is not found.") 

776 Dx, Dy = widths 

777 theX, theY = guess 

778 if rotated: 

779 guess2 = find_target_after_rotation(image) 

780 x0 = int(guess2[0]) 

781 y0 = int(guess2[1]) 

782 guess = [x0, y0] 

783 niter = 2 

784 sub_image_subtracted, x0, y0, Dx, Dy, sub_errors = find_target_init(image=image, guess=guess, rotated=rotated, 

785 widths=(Dx, Dy)) 

786 sub_image_x0, sub_image_y0 = x0, y0 

787 for i in range(niter): 

788 # find the target 

789 # try: 

790 sub_image_x0, sub_image_y0 = find_target_Moffat2D(image, sub_image_subtracted, sub_errors=sub_errors) 

791 # except (Exception, ValueError): 

792 # image.target_star2D = None 

793 # avX, avY = find_target_2DprofileASTROPY(image, sub_image_subtracted, sub_errors=sub_errors) 

794 # compute target position 

795 theX = x0 - Dx + sub_image_x0 

796 theY = y0 - Dy + sub_image_y0 

797 # crop for next iteration 

798 if i < niter - 1: 

799 Dx = Dx // (i + 2) 

800 Dy = Dy // (i + 2) 

801 x0 = int(theX) 

802 y0 = int(theY) 

803 NY, NX = sub_image_subtracted.shape 

804 sub_image_subtracted = sub_image_subtracted[ 

805 max(0, int(sub_image_y0) - Dy):min(NY, int(sub_image_y0) + Dy), 

806 max(0, int(sub_image_x0) - Dx):min(NX, int(sub_image_x0) + Dx)] 

807 sub_errors = sub_errors[max(0, int(sub_image_y0) - Dy):min(NY, int(sub_image_y0) + Dy), 

808 max(0, int(sub_image_x0) - Dx):min(NX, int(sub_image_x0) + Dx)] 

809 if int(sub_image_x0) - Dx < 0: 

810 Dx = int(sub_image_x0) 

811 if int(sub_image_y0) - Dy < 0: 

812 Dy = int(sub_image_y0) 

813 else: 

814 Dx, Dy = widths 

815 sub_image_subtracted, x0, y0, Dx, Dy, sub_errors = find_target_init(image=image, guess=target_pixcoords, 

816 rotated=rotated, widths=(Dx, Dy)) 

817 sub_image_x0 = target_pixcoords[0] - x0 + Dx 

818 sub_image_y0 = target_pixcoords[1] - y0 + Dy 

819 image.my_logger.info(f'\n\tX,Y target position in pixels: {theX:.3f},{theY:.3f}') 

820 if rotated: 

821 image.target_pixcoords_rotated = [theX, theY] 

822 else: 

823 image.target.image = sub_image_subtracted 

824 image.target.image_x0 = sub_image_x0 

825 image.target.image_y0 = sub_image_y0 

826 image.target_pixcoords = [theX, theY] 

827 image.header['TARGETX'] = theX 

828 image.header.comments['TARGETX'] = 'target position on X axis' 

829 image.header['TARGETY'] = theY 

830 image.header.comments['TARGETY'] = 'target position on Y axis' 

831 return [theX, theY] 

832 

833 

834def find_target_after_rotation(image): 

835 angle = image.rotation_angle * np.pi / 180. 

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

837 vec = np.array(image.target_pixcoords) - 0.5 * np.array(image.data.shape[::-1]) 

838 target_pixcoords_after_rotation = rotmat @ vec + 0.5 * np.array(image.data_rotated.shape[::-1]) 

839 return target_pixcoords_after_rotation 

840 

841 

842def find_target_init(image, guess, rotated=False, widths=[parameters.XWINDOW, parameters.YWINDOW]): 

843 """Initialize the search of the target: crop the image, set the saturation level, 

844 estimate and subtract a 2D polynomial background. 

845 

846 Parameters 

847 ---------- 

848 image: Image 

849 The Image instance. 

850 guess: array_like 

851 Two parameter array giving the estimated position of the target in the image. 

852 rotated: bool 

853 If True, the target is searched in the rotated image. 

854 widths: (int, int) 

855 Two parameter array to define the width of the cropped image (default: [parameters.XWINDOW, parameters.YWINDOW]) 

856 

857 Returns 

858 ------- 

859 sub_image: array_like 

860 The cropped image data array where the fit has to be performed. 

861 x0: float 

862 The x position of the target. 

863 y0: float 

864 The y position of the target. 

865 Dx: int 

866 The width of the cropped image. 

867 Dy: int 

868 The height of the cropped image. 

869 sub_errors: array_like 

870 The cropped image uncertainty array where the fit has to be performed. 

871 """ 

872 x0 = int(guess[0]) 

873 y0 = int(guess[1]) 

874 Dx, Dy = widths 

875 if rotated: 

876 sub_image = np.copy(image.data_rotated[y0 - Dy:y0 + Dy, x0 - Dx:x0 + Dx]) 

877 sub_errors = np.copy(image.stat_errors[y0 - Dy:y0 + Dy, x0 - Dx:x0 + Dx]) 

878 else: 

879 sub_image = np.copy(image.data[y0 - Dy:y0 + Dy, x0 - Dx:x0 + Dx]) 

880 sub_errors = np.copy(image.stat_errors[y0 - Dy:y0 + Dy, x0 - Dx:x0 + Dx]) 

881 image.saturation = parameters.CCD_MAXADU / image.expo 

882 NY, NX = sub_image.shape 

883 Y, X = np.mgrid[:NY, :NX] 

884 bkgd_2D = fit_poly2d_outlier_removal(X, Y, sub_image, order=1, sigma=3) 

885 image.target_bkgd2D = bkgd_2D 

886 sub_image_subtracted = sub_image - bkgd_2D(X, Y) 

887 saturated_pixels = np.where(sub_image >= image.saturation) 

888 if len(saturated_pixels[0]) > 0: 

889 image.my_logger.debug( 

890 f'\n\t{len(saturated_pixels[0])} saturated pixels: set saturation level ' 

891 f'to {image.saturation} {image.units}.') 

892 sub_errors[sub_image >= 0.99 * image.saturation] = 10 * image.saturation # np.min(np.abs(sub_errors)) 

893 # sub_image = clean_target_spikes(sub_image, image.saturation) 

894 return sub_image_subtracted, x0, y0, Dx, Dy, sub_errors 

895 

896 

897def find_target_1Dprofile(image, sub_image, guess): 

898 """ 

899 Find precisely the position of the targeted object fitting a PSF model 

900 on each projection of the image along x and y, using outlier removal. 

901 

902 Parameters 

903 ---------- 

904 image: Image 

905 The Image instance. 

906 sub_image: array_like 

907 The cropped image data array where the fit is performed. 

908 guess: array_like 

909 Two parameter array giving the estimated position of the target in the image. 

910 

911 Examples 

912 -------- 

913 >>> im = Image('tests/data/reduc_20170605_028.fits') 

914 >>> guess = [820, 580] 

915 >>> parameters.DEBUG = True 

916 >>> sub_image, x0, y0, Dx, Dy, sub_errors = find_target_init(im, guess, rotated=False) 

917 >>> x1, y1 = find_target_1Dprofile(im, sub_image, guess) 

918 

919 .. doctest:: 

920 :hide: 

921 

922 >>> assert np.isclose(x1, np.argmax(np.nansum(sub_image, axis=0)), rtol=1e-2) 

923 >>> assert np.isclose(y1, np.argmax(np.nansum(sub_image, axis=1)), rtol=1e-2) 

924 

925 """ 

926 NY, NX = sub_image.shape 

927 X = np.arange(NX) 

928 Y = np.arange(NY) 

929 # Mask aigrette 

930 saturated_pixels = np.where(sub_image >= image.saturation) 

931 if parameters.DEBUG: 

932 image.my_logger.info('\n\t%d saturated pixels: set saturation level to %d %s.' % ( 

933 len(saturated_pixels[0]), image.saturation, image.units)) 

934 # sub_image[sub_image >= 0.5*image.saturation] = np.nan 

935 # compute profiles 

936 profile_X_raw = np.sum(sub_image, axis=0) 

937 profile_Y_raw = np.sum(sub_image, axis=1) 

938 # fit and subtract smooth polynomial background 

939 # with 3sigma rejection of outliers (star peaks) 

940 bkgd_X, outliers = fit_poly1d_outlier_removal(X, profile_X_raw, order=2) 

941 bkgd_Y, outliers = fit_poly1d_outlier_removal(Y, profile_Y_raw, order=2) 

942 profile_X = profile_X_raw - bkgd_X(X) # np.min(profile_X) 

943 profile_Y = profile_Y_raw - bkgd_Y(Y) # np.min(profile_Y) 

944 avX, sigX = weighted_avg_and_std(X, profile_X ** 4) 

945 avY, sigY = weighted_avg_and_std(Y, profile_Y ** 4) 

946 if profile_X[int(avX)] < 0.8 * np.max(profile_X): 

947 image.my_logger.warning('\n\tX position determination of the target probably wrong') 

948 if profile_Y[int(avY)] < 0.8 * np.max(profile_Y): 

949 image.my_logger.warning('\n\tY position determination of the target probably wrong') 

950 if parameters.DEBUG: 

951 f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 4)) 

952 plot_image_simple(ax1, data=sub_image, scale="log", title="", units=image.units, target_pixcoords=[avX, avY]) 

953 ax1.legend(loc=1) 

954 ax2.plot(X, profile_X_raw, 'r-', lw=2) 

955 ax2.plot(X, bkgd_X(X), 'g--', lw=2, label='bkgd') 

956 ax2.axvline(avX, color='b', linestyle='-', label='new', lw=2) 

957 ax2.grid(True) 

958 ax2.set_xlabel(parameters.PLOT_XLABEL) 

959 ax2.legend(loc=1) 

960 ax3.plot(Y, profile_Y_raw, 'r-', lw=2) 

961 ax3.plot(Y, bkgd_Y(Y), 'g--', lw=2, label='bkgd') 

962 ax3.axvline(avY, color='b', linestyle='-', label='new', lw=2) 

963 ax3.grid(True) 

964 ax3.set_xlabel(parameters.PLOT_YLABEL) 

965 ax3.legend(loc=1) 

966 f.tight_layout() 

967 if parameters.DISPLAY: # pragma: no cover 

968 plt.show() 

969 if parameters.LSST_SAVEFIGPATH: # pragma: no cover 

970 f.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'namethisplot1.pdf')) 

971 if parameters.PdfPages: 

972 parameters.PdfPages.savefig() 

973 return avX, avY 

974 

975 

976def find_target_Moffat2D(image, sub_image_subtracted, sub_errors=None): 

977 """ 

978 Find precisely the position of the targeted object fitting a Moffat PSF model. 

979 A polynomial 2D background is subtracted first. Saturated pixels are masked with np.nan values. 

980 

981 Parameters 

982 ---------- 

983 image: Image 

984 The Image instance. 

985 sub_image_subtracted: array_like 

986 The cropped image data array where the fit is performed, background has been subtracted. 

987 sub_errors: array_like 

988 The image data uncertainties. 

989 

990 Examples 

991 -------- 

992 >>> im = Image('tests/data/reduc_20170605_028.fits') 

993 >>> guess = [820, 580] 

994 >>> parameters.VERBOSE = True 

995 >>> parameters.DEBUG = True 

996 >>> sub_image_subtracted, x0, y0, Dx, Dy, sub_errors = find_target_init(im, guess, rotated=False) #, widths=[30,30]) 

997 >>> xmax = np.argmax(np.sum(sub_image_subtracted, axis=0)) 

998 >>> ymax = np.argmax(np.sum(sub_image_subtracted, axis=1)) 

999 >>> x1, y1 = find_target_Moffat2D(im, sub_image_subtracted, sub_errors=sub_errors) 

1000 

1001 .. doctest:: 

1002 :hide: 

1003 

1004 >>> assert np.isclose(x1, xmax, rtol=1e-2) 

1005 >>> assert np.isclose(y1, ymax, rtol=1e-2) 

1006 

1007 """ 

1008 # fit and subtract smooth polynomial background 

1009 # with 3sigma rejection of outliers (star peaks) 

1010 NY, NX = sub_image_subtracted.shape 

1011 XX = np.arange(NX) 

1012 YY = np.arange(NY) 

1013 # find a first guess of the target position 

1014 avX, sigX = weighted_avg_and_std(XX, np.sum(sub_image_subtracted, axis=0) ** 4) 

1015 avY, sigY = weighted_avg_and_std(YY, np.sum(sub_image_subtracted, axis=1) ** 4) 

1016 # fit a 2D star profile close to this position 

1017 # guess = [np.max(sub_image_subtracted),avX,avY,1,1] #for Moffat2Ds 

1018 # guess = [np.max(sub_image_subtracted),avX-2,avY-2,2,2,0] #for Gauss2D 

1019 psf = Moffat() 

1020 total_flux = np.sum(sub_image_subtracted) 

1021 psf.p[:3] = [total_flux, avX, avY] 

1022 psf.p[-1] = image.saturation 

1023 if image.target_star2D is not None: 

1024 psf.p = image.target_star2D.p 

1025 psf.p[1] = avX 

1026 psf.p[2] = avY 

1027 mean_prior = 10 # in pixels 

1028 # bounds = [ [0.5*np.max(sub_image_subtracted),avX-mean_prior,avY-mean_prior,0,-np.inf], 

1029 # [2*np.max(sub_image_subtracted),avX+mean_prior,avY+mean_prior,np.inf,np.inf] ] #for Moffat2D 

1030 # bounds = [ [0.5*np.max(sub_image_subtracted),avX-mean_prior,avY-mean_prior,0,0,0], 

1031 # [100*image.saturation,avX+mean_prior,avY+mean_prior,10,10,np.pi] ] #for Gauss2D 

1032 # bounds = [[0.5 * np.max(sub_image_subtracted), avX - mean_prior, avY - mean_prior, 2, 0.9 * image.saturation], 

1033 # [10 * image.saturation, avX + mean_prior, avY + mean_prior, 15, 1.1 * image.saturation]] 

1034 psf.bounds[:3] = [[0.1 * total_flux, 4 * total_flux], 

1035 [avX - mean_prior, avX + mean_prior], 

1036 [avY - mean_prior, avY + mean_prior]] 

1037 # fit 

1038 # star2D = fit_PSF2D(X, Y, sub_image_subtracted, guess=guess, bounds=bounds) 

1039 # star2D = fit_PSF2D_minuit(X, Y, sub_image_subtracted, guess=guess, bounds=bounds) 

1040 psf.fit_psf(sub_image_subtracted, data_errors=sub_errors, bgd_model_func=image.target_bkgd2D) 

1041 new_avX = psf.p[1] 

1042 new_avY = psf.p[2] 

1043 image.target_star2D = psf 

1044 # check target positions 

1045 dist = np.sqrt((new_avY - avY) ** 2 + (new_avX - avX) ** 2) 

1046 if dist > mean_prior / 2: 

1047 image.my_logger.warning( 

1048 f'\n\tX={new_avX:.2f}, Y={new_avY:.2f} target position determination probably wrong: ' 

1049 f'{dist:.1f} pixels from profile detection ({avX:.2f}, {avY:.2f})') 

1050 # debugging plots 

1051 if parameters.DEBUG: 

1052 f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 4)) 

1053 vmin = 0 

1054 vmax = float(np.nanmax(sub_image_subtracted)) 

1055 Y, X = np.mgrid[:NY, :NX] 

1056 star2D = psf.evaluate(pixels=np.array([X, Y])) 

1057 plot_image_simple(ax1, data=sub_image_subtracted, scale="lin", title="", units=image.units, 

1058 target_pixcoords=[new_avX, new_avY], vmin=vmin, vmax=vmax) 

1059 ax1.legend(loc=1) 

1060 

1061 ax1.text(0.05, 0.05, f'Data', color="white", 

1062 horizontalalignment='left', verticalalignment='bottom', transform=ax1.transAxes) 

1063 ax2.text(0.05, 0.05, f'Background+Moffat2D model', color="white", 

1064 horizontalalignment='left', verticalalignment='bottom', transform=ax2.transAxes) 

1065 ax3.text(0.05, 0.05, f'Residuals', color="white", 

1066 horizontalalignment='left', verticalalignment='bottom', transform=ax3.transAxes) 

1067 plot_image_simple(ax2, data=star2D, scale="lin", title="", 

1068 units=f'{image.units}', vmin=vmin, vmax=vmax) 

1069 plot_image_simple(ax3, data=sub_image_subtracted - star2D, scale="lin", title="", 

1070 units=f'{image.units}', target_pixcoords=[new_avX, new_avY], vmin=vmin, vmax=vmax) 

1071 ax3.legend(loc=1) 

1072 

1073 f.tight_layout() 

1074 if parameters.DISPLAY: # pragma: no cover 

1075 plt.show() 

1076 if parameters.LSST_SAVEFIGPATH: # pragma: no cover 

1077 f.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'order0_centroid_fit.pdf')) 

1078 if parameters.PdfPages: 

1079 parameters.PdfPages.savefig() 

1080 return new_avX, new_avY 

1081 

1082 

1083def compute_rotation_angle_hessian(image, angle_range=(-10, 10), width_cut=parameters.YWINDOW, 

1084 edges=(0, parameters.CCD_IMSIZE), 

1085 margin_cut=12, pixel_fraction=0.01): 

1086 """Compute the rotation angle in degree of a spectrogram with the Hessian of the image. 

1087 Use the disperser rotation angle map as a prior and the target_pixcoords values to crop the image 

1088 around the spectrogram. 

1089 

1090 Parameters 

1091 ---------- 

1092 image: Image 

1093 The Image instance. 

1094 angle_range: (float, float) 

1095 Don't consider pixel with Hessian angle outside this range (default: (-10,10)). 

1096 width_cut: int 

1097 Half with of the image to consider in height (default: parameters.YWINDOW). 

1098 edges: (int, int) 

1099 Minimum and maximum pixel on the right edge (default: (0, parameters.CCD_IMSIZE)). 

1100 margin_cut: int 

1101 After computing the Hessian, to avoid bad values on the edges the function cut on the 

1102 edge of image margin_cut pixels (default: 12). 

1103 pixel_fraction: float 

1104 Minimum pixel fraction to keep after thresholding the lambda minus map (default: 0.01). 

1105 

1106 Returns 

1107 ------- 

1108 theta: float 

1109 The median value of the histogram of angles deduced with the Hessian of the pixels (in degree). 

1110 

1111 Examples 

1112 -------- 

1113 >>> im=Image('tests/data/reduc_20170605_028.fits', disperser_label='HoloPhAg') 

1114 

1115 Create a mock spectrogram: 

1116 

1117 >>> N = parameters.CCD_IMSIZE 

1118 >>> im.data = np.ones((N, N)) 

1119 >>> slope = -0.1 

1120 >>> y = lambda x: slope * (x - 0.5*N) + 0.5*N 

1121 >>> for x in np.arange(N): 

1122 ... im.data[int(y(x)), x] = 100 

1123 ... im.data[int(y(x))+1, x] = 100 

1124 >>> im.target_pixcoords=(N//2, N//2) 

1125 >>> parameters.DEBUG = True 

1126 >>> theta = compute_rotation_angle_hessian(im) 

1127 

1128 .. doctest:: 

1129 :hide: 

1130 

1131 >>> assert np.isclose(theta, np.arctan(slope)*180/np.pi, rtol=1e-1) 

1132 

1133 """ 

1134 x0, y0 = np.array(image.target_pixcoords).astype(int) 

1135 # extract a region 

1136 left_edge, right_edge = edges 

1137 data = np.copy(image.data[y0 - width_cut:y0 + width_cut, left_edge:right_edge]) 

1138 lambda_plus, lambda_minus, theta = hessian_and_theta(data, margin_cut) 

1139 # thresholds 

1140 lambda_threshold = np.min(lambda_minus) 

1141 mask = np.where(lambda_minus > lambda_threshold) 

1142 theta_mask = np.copy(theta) 

1143 theta_mask[mask] = np.nan 

1144 minimum_pixels = pixel_fraction * 2 * width_cut * right_edge 

1145 while len(theta_mask[~np.isnan(theta_mask)]) < minimum_pixels: 

1146 lambda_threshold /= 2 

1147 mask = np.where(lambda_minus > lambda_threshold) 

1148 theta_mask = np.copy(theta) 

1149 theta_mask[mask] = np.nan 

1150 # print len(theta_mask[~np.isnan(theta_mask)]), lambda_threshold 

1151 theta_guess = image.disperser.theta(image.target_pixcoords) 

1152 mask2 = np.logical_or(angle_range[0] > theta - theta_guess, theta - theta_guess > angle_range[1]) 

1153 theta_mask[mask2] = np.nan 

1154 theta_mask = theta_mask[2:-2, 2:-2] 

1155 theta_hist = theta_mask[~np.isnan(theta_mask)].flatten() 

1156 if parameters.OBS_OBJECT_TYPE != 'STAR': 

1157 pixels = np.where(~np.isnan(theta_mask)) 

1158 p = np.polyfit(pixels[1], pixels[0], deg=1) 

1159 theta_median = np.arctan(p[0]) * 180 / np.pi 

1160 else: 

1161 theta_median = float(np.median(theta_hist)) 

1162 # theta_critical = 180. * np.arctan(20. / parameters.CCD_IMSIZE) / np.pi 

1163 image.header['THETAFIT'] = theta_median 

1164 image.header.comments['THETAFIT'] = '[deg] [USED] rotation angle from the Hessian analysis' 

1165 image.header['THETAINT'] = theta_guess 

1166 image.header.comments['THETAINT'] = '[deg] rotation angle interp from disperser scan' 

1167 # if abs(theta_median - theta_guess) > theta_critical: 

1168 # image.my_logger.warning( 

1169 # f'\n\tInterpolated angle and fitted angle disagrees with more than 20 pixels ' 

1170 # f'over {parameters.CCD_IMSIZE:d} pixels: {theta_median:.2f} vs {theta_guess:.2f}') 

1171 if parameters.DEBUG: 

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

1173 f, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(6.5, 3), gridspec_kw=gs_kw) 

1174 xindex = np.arange(data.shape[1]) 

1175 x_new = np.linspace(xindex.min(), xindex.max(), 50) 

1176 y_new = width_cut - margin_cut - 3 + (x_new - x0) * np.tan(theta_median * np.pi / 180.) 

1177 cmap = copy.copy(cm.get_cmap('bwr')) 

1178 cmap.set_bad(color='lightgrey') 

1179 im = ax1.imshow(theta_mask, origin='lower', cmap=cmap, aspect='auto', vmin=angle_range[0], vmax=angle_range[1]) 

1180 cb = plt.colorbar(im, ax=ax1) 

1181 cb.set_label(parameters.PLOT_ROT_LABEL, labelpad=-10) 

1182 ax1.plot(x_new, y_new, 'k-', label=rf"Mean dispersion axis: $\varphi_d$={theta_median:.2f}°") 

1183 ax1.set_ylim(0, theta_mask.shape[0]) 

1184 ax1.set_xlim(0, theta_mask.shape[1]) 

1185 ax1.legend() 

1186 ax1.set_xlabel(parameters.PLOT_XLABEL) 

1187 ax1.set_ylabel(parameters.PLOT_YLABEL) 

1188 ax1.grid(True) 

1189 ax2.hist(theta_hist, bins=int(np.sqrt(len(theta_hist)))) 

1190 ax2.axvline(theta_median, color='k') 

1191 ax2.set_xlabel(parameters.PLOT_ROT_LABEL) 

1192 ax2.grid() 

1193 f.tight_layout() 

1194 if parameters.DISPLAY: # pragma: no cover 

1195 plt.show() 

1196 if parameters.LSST_SAVEFIGPATH: # pragma: no cover 

1197 f.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'rotation_hessian.pdf')) 

1198 if parameters.PdfPages: 

1199 parameters.PdfPages.savefig() 

1200 return theta_median 

1201 

1202 

1203def turn_image(image): 

1204 """Compute the rotation angle using the Hessian algorithm and turn the image. 

1205 

1206 The results are stored in Image.data_rotated and Image.stat_errors_rotated. 

1207 

1208 Parameters 

1209 ---------- 

1210 image: Image 

1211 The Image instance. 

1212 

1213 Examples 

1214 -------- 

1215 

1216 Create of False spectrogram: 

1217 

1218 >>> im=Image('tests/data/reduc_20170605_028.fits', disperser_label='HoloPhAg') 

1219 >>> N = parameters.CCD_IMSIZE 

1220 >>> im.data = np.ones((N, N)) 

1221 >>> slope = -0.1 

1222 >>> y = lambda x: slope * (x - 0.5*N) + 0.5*N 

1223 >>> for x in np.arange(N): 

1224 ... im.data[int(y(x)), x] = 10 

1225 ... im.data[int(y(x))+1, x] = 10 

1226 

1227 .. plot:: 

1228 

1229 from spectractor.extractor.images import Image 

1230 import spectractor.parameters as parameters 

1231 im=Image('tests/data/reduc_20170605_028.fits', disperser_label='HoloPhAg') 

1232 N = parameters.CCD_IMSIZE 

1233 im.data = np.ones((N, N)) 

1234 slope = -0.1 

1235 y = lambda x: slope * (x - 0.5*N) + 0.5*N 

1236 for x in np.arange(N): 

1237 im.data[int(y(x)), x] = 10 

1238 im.data[int(y(x))+1, x] = 10 

1239 plt.imshow(im.data, origin='lower') 

1240 plt.show() 

1241 

1242 >>> im.target_pixcoords=(N//2, N//2) 

1243 >>> parameters.DEBUG = True 

1244 >>> turn_image(im) 

1245 

1246 .. doctest:: 

1247 :hide: 

1248 

1249 >>> assert im.data_rotated is not None 

1250 >>> assert np.isclose(im.rotation_angle, np.arctan(slope)*180/np.pi, rtol=5e-2) 

1251 

1252 .. plot:: 

1253 

1254 from spectractor.extractor.images import Image, turn_image 

1255 import spectractor.parameters as parameters 

1256 im=Image('tests/data/reduc_20170605_028.fits', disperser_label='HoloPhAg') 

1257 N = parameters.CCD_IMSIZE 

1258 im.data = np.ones((N, N)) 

1259 slope = -0.1 

1260 y = lambda x: slope * (x - 0.5*N) + 0.5*N 

1261 for x in np.arange(N): 

1262 im.data[int(y(x)), x] = 10 

1263 im.data[int(y(x))+1, x] = 10 

1264 

1265 im.target_pixcoords=(N//2, N//2) 

1266 turn_image(im) 

1267 plt.imshow(im.data_rotated, origin='lower') 

1268 plt.show() 

1269 """ 

1270 image.rotation_angle = compute_rotation_angle_hessian(image, width_cut=parameters.YWINDOW, 

1271 angle_range=(parameters.ROT_ANGLE_MIN, 

1272 parameters.ROT_ANGLE_MAX), 

1273 edges=(0, parameters.CCD_IMSIZE)) 

1274 image.header['ROTANGLE'] = image.rotation_angle 

1275 image.my_logger.info(f'\n\tRotate the image with angle theta={image.rotation_angle:.2f} degree') 

1276 image.data_rotated = np.copy(image.data) 

1277 if not np.isnan(image.rotation_angle): 

1278 image.data_rotated = ndimage.interpolation.rotate(image.data, image.rotation_angle, 

1279 prefilter=parameters.ROT_PREFILTER, 

1280 order=parameters.ROT_ORDER) 

1281 image.stat_errors_rotated = np.sqrt( 

1282 np.abs(ndimage.interpolation.rotate(image.stat_errors ** 2, image.rotation_angle, 

1283 prefilter=parameters.ROT_PREFILTER, 

1284 order=parameters.ROT_ORDER))) 

1285 min_noz = np.min(image.stat_errors_rotated[image.stat_errors_rotated > 0]) 

1286 image.stat_errors_rotated[image.stat_errors_rotated <= 0] = min_noz 

1287 if parameters.DEBUG: 

1288 margin = 100 // parameters.CCD_REBIN 

1289 y0 = int(image.target_pixcoords[1]) 

1290 f, (ax1, ax2) = plt.subplots(2, 1, figsize=[8, 8]) 

1291 plot_image_simple(ax1, data=image.data[max(0, y0 - 2 * parameters.YWINDOW): 

1292 min(y0 + 2 * parameters.YWINDOW, image.data.shape[0]), 

1293 margin:-margin], 

1294 scale="symlog", title='Raw image (log10 scale)', units=image.units, 

1295 target_pixcoords=(image.target_pixcoords[0] - margin, 2 * parameters.YWINDOW), aspect='auto') 

1296 if parameters.OBS_OBJECT_TYPE == "STAR": 

1297 plot_compass_simple(ax1, image.parallactic_angle, arrow_size=0.1, origin=[0.15, 0.15]) 

1298 ax2.axhline(parameters.YWINDOW, color='k') 

1299 plot_image_simple(ax2, data=image.data_rotated[max(0, y0 - 2 * parameters.YWINDOW): 

1300 min(y0 + 2 * parameters.YWINDOW, image.data.shape[0]), 

1301 margin:-margin], 

1302 scale="symlog", title='Turned image (log10 scale)', 

1303 units=image.units, target_pixcoords=image.target_pixcoords_rotated, aspect='auto') 

1304 ax2.axhline(2 * parameters.YWINDOW, color='k') 

1305 f.tight_layout() 

1306 if parameters.DISPLAY: # pragma: no cover 

1307 plt.show() 

1308 if parameters.LSST_SAVEFIGPATH: # pragma: no cover 

1309 f.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'rotated_image.pdf')) 

1310 if parameters.PdfPages: 

1311 parameters.PdfPages.savefig() 

1312 

1313 

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

1315 import doctest 

1316 

1317 doctest.testmod()