Coverage for spectractor/astrometry.py: 8%

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

468 statements  

1import os 

2from copy import deepcopy 

3import subprocess 

4import numpy as np 

5import matplotlib.pyplot as plt 

6from astropy.stats import sigma_clipped_stats 

7from astropy.io import fits, ascii 

8import astropy.units as u 

9from astropy.table import Table 

10from astropy.time import Time 

11from astropy.coordinates import SkyCoord, Distance 

12 

13from photutils import IRAFStarFinder 

14 

15from scipy.spatial import ConvexHull 

16 

17from spectractor import parameters 

18from spectractor.tools import (plot_image_simple, set_wcs_file_name, set_wcs_tag, set_wcs_output_directory, 

19 set_sources_file_name, set_gaia_catalog_file_name, load_wcs_from_file, ensure_dir) 

20from spectractor.config import set_logger 

21from spectractor.extractor.images import Image 

22from spectractor.extractor.background import remove_image_background_sextractor 

23 

24 

25def source_detection(data_wo_bkg, sigma=3.0, fwhm=3.0, threshold_std_factor=5, mask=None): 

26 """Function to detect point-like sources in a data array. 

27 

28 This function use the photutils IRAFStarFinder module to search for sources in an image. This finder 

29 is better than DAOStarFinder for the astrometry of isolated sources but less good for photometry. 

30 

31 Parameters 

32 ---------- 

33 data_wo_bkg: array_like 

34 The image data array. It works better if the background was subtracted before. 

35 sigma: float 

36 Standard deviation value for sigma clipping function before finding sources (default: 3.0). 

37 fwhm: float 

38 Full width half maximum for the source detection algorithm (default: 3.0). 

39 threshold_std_factor: float 

40 Only sources with a flux above this value times the RMS of the images are kept (default: 5). 

41 mask: array_like, optional 

42 Boolean array to mask image pixels (default: None). 

43 

44 Returns 

45 ------- 

46 sources: Table 

47 Astropy table containing the source centroids and fluxes, ordered by decreasing magnitudes. 

48 

49 Examples 

50 -------- 

51 

52 >>> N = 100 

53 >>> data = np.ones((N, N)) 

54 >>> yy, xx = np.mgrid[:N, :N] 

55 >>> x_center, y_center = 20, 30 

56 >>> data += 10*np.exp(-((x_center-xx)**2+(y_center-yy)**2)/10) 

57 >>> sources = source_detection(data) 

58 >>> print(float(sources["xcentroid"]), float(sources["ycentroid"])) 

59 20.0 30.0 

60 

61 .. doctest: 

62 :hide: 

63 

64 >>> assert len(sources) == 1 

65 >>> assert sources["xcentroid"] == x_center 

66 >>> assert sources["ycentroid"] == y_center 

67 

68 .. plot: 

69 

70 from spectractor.tools import plot_image_simple 

71 from spectractor.astrometry import source_detection 

72 import numpy as np 

73 import matplotlib.pyplot as plt 

74 

75 N = 100 

76 data = np.ones((N, N)) 

77 yy, xx = np.mgrid[:N, :N] 

78 x_center, y_center = 20, 30 

79 data += 10*np.exp(-((x_center-xx)**2+(y_center-yy)**2)/10) 

80 sources = source_detection(data) 

81 fig = plt.figure(figsize=(6,5)) 

82 plot_image_simple(plt.gca(), data, target_pixcoords=(sources["xcentroid"], sources["ycentroid"])) 

83 fig.tight_layout() 

84 plt.show() 

85 

86 """ 

87 mean, median, std = sigma_clipped_stats(data_wo_bkg, sigma=sigma) 

88 if mask is None: 

89 mask = np.zeros(data_wo_bkg.shape, dtype=bool) 

90 # daofind = DAOStarFinder(fwhm=fwhm, threshold=threshold_std_factor * std, exclude_border=True) 

91 # sources = daofind(data_wo_bkg - median, mask=mask) 

92 iraffind = IRAFStarFinder(fwhm=fwhm, threshold=threshold_std_factor * std, exclude_border=True) 

93 sources = iraffind(data_wo_bkg - median, mask=mask) 

94 for col in sources.colnames: 

95 sources[col].info.format = '%.8g' # for consistent table output 

96 sources.sort('mag') 

97 if parameters.DEBUG: 

98 positions = np.array((sources['xcentroid'], sources['ycentroid'])) 

99 plot_image_simple(plt.gca(), data_wo_bkg, scale="symlog", target_pixcoords=positions) 

100 if parameters.DISPLAY: 

101 # fig.tight_layout() 

102 plt.show() 

103 if parameters.PdfPages: 

104 parameters.PdfPages.savefig() 

105 

106 return sources 

107 

108 

109def load_gaia_catalog(coord, radius=5 * u.arcmin): 

110 """Load the Gaia catalog of stars around a given RA,DEC position within a given radius. 

111 

112 Parameters 

113 ---------- 

114 coord: SkyCoord 

115 Central coordinates for the Gaia cone search. 

116 radius: float 

117 Radius size for the cone search, with angle units (default: 5u.arcmin). 

118 

119 Returns 

120 ------- 

121 gaia_catalog: Table 

122 The Gaia catalog. 

123 

124 Examples 

125 -------- 

126 

127 >>> from astropy.coordinates import SkyCoord 

128 >>> c = SkyCoord(ra=0*u.deg, dec=0*u.deg) 

129 >>> gaia_catalog = load_gaia_catalog(c, radius=1*u.arcmin) # doctest: +ELLIPSIS 

130 INFO: Query finished... 

131 >>> print(gaia_catalog) # doctest: +SKIP 

132 dist ... 

133 

134 .. doctest: 

135 :hide: 

136 

137 >>> assert len(gaia_catalog) > 0 

138 

139 """ 

140 from astroquery.gaia import Gaia 

141 my_logger = set_logger("load_gaia_catalog") 

142 Gaia.ROW_LIMIT = -1 

143 job = Gaia.cone_search_async(coord, radius=radius, verbose=False) 

144 my_logger.debug(f"\n\t{job}") 

145 gaia_catalog = job.get_results() 

146 my_logger.debug(f"\n\t{gaia_catalog}") 

147 gaia_catalog.fill_value = 0 

148 gaia_catalog['parallax'].fill_value = np.min(gaia_catalog['parallax']) 

149 return gaia_catalog 

150 

151 

152def get_gaia_coords_after_proper_motion(gaia_catalog, date_obs): 

153 """Use proper motion data to shift the Gaia catalog coordinates at J2000 

154 to current date of observation. 

155 

156 Parameters 

157 ---------- 

158 gaia_catalog: Table 

159 The Gaia catalog. 

160 date_obs: Time 

161 The time of observation. 

162 

163 Returns 

164 ------- 

165 gaia_coordinates_after_proper_motion: SkyCoord 

166 Array of RA,DEC coordinates of the Gaia stars at the observation date. 

167 

168 Examples 

169 -------- 

170 

171 >>> from astropy.coordinates import SkyCoord 

172 >>> from astropy.time import Time 

173 >>> c = SkyCoord(ra=0*u.deg, dec=0*u.deg) 

174 >>> gaia_catalog = load_gaia_catalog(c, radius=1*u.arcmin) # doctest: +ELLIPSIS 

175 INFO: Query finished... 

176 >>> t = Time("2017-01-01T00:00:00.000") 

177 >>> gaia_coords = get_gaia_coords_after_proper_motion(gaia_catalog, t) 

178 >>> print(gaia_coords) # doctest: +ELLIPSIS 

179 <SkyCoord (ICRS): (ra, dec, distance) in (deg, deg, pc)... 

180 

181 .. doctest: 

182 :hide: 

183 

184 >>> assert len(gaia_catalog) == len(gaia_coords) 

185 

186 """ 

187 parallax = np.array(gaia_catalog['parallax'].filled(np.nanmin(np.abs(gaia_catalog['parallax'])))) 

188 parallax[parallax < 0] = np.min(parallax[parallax > 0]) 

189 gaia_stars = SkyCoord(ra=gaia_catalog['ra'], dec=gaia_catalog['dec'], frame='icrs', equinox="J2000", 

190 obstime=Time(np.array(gaia_catalog['ref_epoch']), format='decimalyear'), 

191 pm_ra_cosdec=gaia_catalog['pmra'].filled(0) * np.cos( 

192 np.array(gaia_catalog['dec']) * np.pi / 180), 

193 pm_dec=gaia_catalog['pmdec'].filled(0), 

194 distance=Distance(parallax=parallax * u.mas, allow_negative=True)) 

195 gaia_coords_after_proper_motion = gaia_stars.apply_space_motion(new_obstime=Time(date_obs)) 

196 return gaia_coords_after_proper_motion 

197 

198 

199def plot_shifts_histograms(dra, ddec): 

200 dra_median = np.median(dra.to(u.arcsec).value) 

201 ddec_median = np.median(ddec.to(u.arcsec).value) 

202 dra_rms = np.std(dra.to(u.arcsec).value) 

203 ddec_rms = np.std(ddec.to(u.arcsec).value) 

204 fig, ax = plt.subplots(1, 2, figsize=(8, 4)) 

205 ax[0].hist(dra.to(u.arcsec).value, bins=50) 

206 ax[1].hist(ddec.to(u.arcsec).value, bins=50) 

207 ax[0].axvline(dra_median, color='k', label="median", lw=2) 

208 ax[1].axvline(ddec_median, color='k', label="median", lw=2) 

209 ax[0].set_xlabel('Shift in RA [arcsec]') 

210 ax[1].set_xlabel('Shift in DEC [arcsec]') 

211 ax[0].text(0.05, 0.96, f"Median: {dra_median:.3g}arcsec\nRMS: {dra_rms:.3g} arcsec", 

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

213 ax[1].text(0.05, 0.96, f"Median: {ddec_median:.3g}arcsec\nRMS: {ddec_rms:.3g} arcsec", 

214 verticalalignment='top', horizontalalignment='left', transform=ax[1].transAxes) 

215 ax[0].grid() 

216 ax[1].grid() 

217 # ax[0].legend() 

218 # ax[1].legend() 

219 if parameters.DISPLAY: 

220 plt.show() 

221 if parameters.PdfPages: 

222 parameters.PdfPages.savefig() 

223 

224 

225class Astrometry(Image): 

226 

227 def __init__(self, file_name, target_label="", disperser_label="", wcs_file_name="", output_directory=""): 

228 """Class to handle astrometric computations. 

229 

230 Parameters 

231 ---------- 

232 file_name: str 

233 Input file name of the image to analyse. 

234 target_label: str, optional 

235 The name of the targeted object (default: ""). 

236 disperser_label: str, optional 

237 The name of the disperser (default: ""). 

238 wcs_file_name: str, optional 

239 The path to a WCS fits file. WCS content will be loaded (default: ""). 

240 output_directory: str, optional 

241 The output directory path. If empty, a directory *_wcs is created next to the analyzed image (default: ""). 

242 """ 

243 Image.__init__(self, file_name, target_label=target_label, disperser_label=disperser_label) 

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

245 # Use fast mode 

246 if parameters.CCD_REBIN > 1: 

247 self.rebin() 

248 if parameters.DEBUG: 

249 self.plot_image(scale='symlog', target_pixcoords=self.target_guess) 

250 

251 self.output_directory = set_wcs_output_directory(file_name, output_directory=output_directory) 

252 ensure_dir(self.output_directory) 

253 self.tag = set_wcs_tag(file_name) 

254 self.new_file_name = self.file_name.replace('.fits', '_new.fits') 

255 self.sources_file_name = set_sources_file_name(file_name, output_directory=output_directory) 

256 self.wcs_file_name = wcs_file_name 

257 self.log_file_name = os.path.join(self.output_directory, self.tag) + ".log" 

258 self.wcs = None 

259 if self.wcs_file_name != "": 

260 if os.path.isfile(self.wcs_file_name): 

261 self.wcs = load_wcs_from_file(self.wcs_file_name) 

262 else: 

263 self.my_logger.warning(f"WCS file {wcs_file_name} does not exist. Skip it.") 

264 else: 

265 self.wcs_file_name = set_wcs_file_name(file_name, output_directory=output_directory) 

266 if os.path.isfile(self.wcs_file_name): 

267 self.wcs = load_wcs_from_file(self.wcs_file_name) 

268 self.gaia_file_name = set_gaia_catalog_file_name(file_name, output_directory=output_directory) 

269 self.gaia_catalog = None 

270 self.gaia_index = None 

271 self.gaia_matches = None 

272 self.gaia_residuals = None 

273 self.gaia_radec_positions_after_pm = None 

274 if os.path.isfile(self.gaia_file_name): 

275 self.my_logger.info(f"\n\tLoad Gaia catalog from {self.gaia_file_name}.") 

276 self.gaia_catalog = ascii.read(self.gaia_file_name, format="ecsv") 

277 self.gaia_radec_positions_after_pm = get_gaia_coords_after_proper_motion(self.gaia_catalog, self.date_obs) 

278 self.sources = None 

279 self.sources_radec_positions = None 

280 if os.path.isfile(self.sources_file_name): 

281 self.sources = self.load_sources_from_file() 

282 self.my_logger.info(f"\n\tIntermediate outputs will be stored in {self.output_directory}") 

283 self.dist_2d = None 

284 self.quad_stars_pixel_positions = None 

285 self.dist_ra = 0 * u.arcsec 

286 self.dist_dec = 0 * u.arcsec 

287 self.target_radec_position_after_pm = self.target.get_radec_position_after_pm(date_obs=self.date_obs) 

288 if os.path.isfile(self.log_file_name): 

289 self.quad_stars_pixel_positions = self.get_quad_stars_pixel_positions() 

290 

291 def get_target_pixel_position(self): 

292 """Gives the principal targetted object position in pixels in the image given the WCS. 

293 The object proper motion is taken into account. 

294 

295 Returns 

296 ------- 

297 target_x: float 

298 The target position along the x axis. 

299 target_y: float 

300 The target position along the y axis. 

301 

302 Examples 

303 -------- 

304 

305 >>> a = Astrometry("./tests/data/reduc_20170530_134.fits", target_label="HD111980", 

306 ... wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

307 >>> target_x, target_y = a.get_target_pixel_position() 

308 >>> print(target_x, target_y) # doctest: +ELLIPSIS 

309 743... 683... 

310 

311 """ 

312 target_x, target_y = self.wcs.all_world2pix(self.target_radec_position_after_pm.ra, 

313 self.target_radec_position_after_pm.dec, 0) 

314 return target_x, target_y 

315 

316 def get_gaia_pixel_positions(self, gaia_index=None): 

317 """Gives the Gaia star positions in pixels in the image given the WCS. 

318 The star proper motions are taken into account. 

319 

320 Parameters 

321 ---------- 

322 gaia_index: array_like, optional 

323 List of indices from the Gaia catalog for which to compute the pixel positions (default: None). 

324 

325 Returns 

326 ------- 

327 gaia_x: array_like 

328 The Gaia star positions along the x axis. 

329 gaia_y: array_like 

330 The Gaia star positions along the y axis. 

331 

332 Examples 

333 -------- 

334 

335 >>> a = Astrometry("./tests/data/reduc_20170530_134.fits", target_label="HD111980", 

336 ... wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

337 >>> gaia_x, gaia_y = a.get_gaia_pixel_positions() 

338 

339 or with selected Gaia index: 

340 

341 >>> gaia_x, gaia_y = a.get_gaia_pixel_positions(gaia_index=[1, 2]) 

342 

343 .. doctest: 

344 :hide: 

345 

346 >>> assert np.isclose(gaia_x[0], 744, atol=0.5) 

347 >>> assert np.isclose(gaia_y[0], 683, atol=0.5) 

348 

349 """ 

350 if gaia_index is None: 

351 gaia_x, gaia_y = self.wcs.all_world2pix(self.gaia_radec_positions_after_pm.ra, 

352 self.gaia_radec_positions_after_pm.dec, 0, quiet=True) 

353 else: 

354 gaia_x, gaia_y = self.wcs.all_world2pix(self.gaia_radec_positions_after_pm[gaia_index].ra, 

355 self.gaia_radec_positions_after_pm[gaia_index].dec, 0, quiet=True) 

356 return gaia_x, gaia_y 

357 

358 def get_quad_stars_pixel_positions(self): 

359 """Gives the star positions in pixels in the image that were used as a quad by the astrometry.net 

360 to compute the WCS. The positions are recovered from the *.log file generated by the solve-field command. 

361 At least 4 stars should be present. 

362 

363 Returns 

364 ------- 

365 quad_star_positions: array_like 

366 The array of quad star (x, y) positions. 

367 

368 Examples 

369 -------- 

370 

371 >>> a = Astrometry("./tests/data/reduc_20170530_134.fits", target_label="HD111980", 

372 ... wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

373 >>> quad_stars = a.get_quad_stars_pixel_positions() 

374 

375 .. doctest: 

376 :hide: 

377 

378 >>> assert quad_stars.shape == (4, 2) 

379 

380 """ 

381 coords = [] 

382 f = open(self.log_file_name, 'r') 

383 for line in f: 

384 if 'field_xy' in line: 

385 coord = line.split(' ')[5].split(',') 

386 coords.append([float(coord[0]), float(coord[1])]) 

387 f.close() 

388 if len(coords) < 4: 

389 self.my_logger.warning(f"\n\tOnly {len(coords)} calibration stars has been extracted from " 

390 f"{self.log_file_name}, with positions {coords}. " 

391 f"A quad of at least 4 stars is expected. " 

392 f"Please check {self.log_file_name}.") 

393 self.quad_stars_pixel_positions = np.array(coords) 

394 return self.quad_stars_pixel_positions 

395 

396 def load_sources_from_file(self): 

397 """Load the sources from the class associated self.sources_file_name file. 

398 

399 By default, the creation of an Astrometry class instance try to load the default 

400 source file if it exists. 

401 

402 Returns 

403 ------- 

404 sources: Table 

405 The table of detected sources. 

406 

407 Examples 

408 -------- 

409 >>> a = Astrometry("./tests/data/reduc_20170530_134.fits", target_label="HD111980", 

410 ... wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

411 >>> a.load_sources_from_file() # doctest: +ELLIPSIS 

412 <Table length=... 

413 

414 """ 

415 self.my_logger.info(f"\n\tLoad source positions and flux from {self.sources_file_name}") 

416 sources = Table.read(self.sources_file_name) 

417 sources['X'].name = "xcentroid" 

418 sources['Y'].name = "ycentroid" 

419 sources['FLUX'].name = "flux" 

420 self.sources = sources 

421 return sources 

422 

423 def load_gaia_catalog_around_target(self): 

424 """Load the Gaia stars catalog around the target position. 

425 

426 The radius of the search is set accordingly to the maximum range of detected sources. 

427 

428 Returns 

429 ------- 

430 gaia_catalog: Table 

431 The table of Gaia stars around the target position. 

432 

433 Examples 

434 -------- 

435 >>> a = Astrometry("./tests/data/reduc_20170530_134.fits", target_label="HD111980", 

436 ... wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

437 >>> a.load_gaia_catalog_around_target() #doctest: +ELLIPSIS 

438 Created TAP+ (v1.2.1) - Connection:... 

439 INFO: Query finished... 

440 

441 """ 

442 radius = 0.5*np.sqrt(2) * max(np.max(self.sources["xcentroid"]) - np.min(self.sources["xcentroid"]), 

443 np.max(self.sources["ycentroid"]) - np.min(self.sources["ycentroid"])) 

444 radius *= parameters.CCD_PIXEL2ARCSEC * u.arcsec 

445 self.my_logger.info(f"\n\tLoading Gaia catalog within radius < {radius.value} " 

446 f"arcsec from {self.target.label} {self.target.radec_position}...") 

447 self.gaia_catalog = load_gaia_catalog(self.target.radec_position, radius=radius) 

448 ascii.write(self.gaia_catalog, self.gaia_file_name, format='ecsv', overwrite=True) 

449 return self.gaia_catalog 

450 

451 def write_sources(self): 

452 """Write a fits file containing the source positions and fluxes. 

453 The name of the file is set accordingly to the name of the WCS file. 

454 

455 """ 

456 colx = fits.Column(name='X', format='D', array=self.sources['xcentroid']) 

457 coly = fits.Column(name='Y', format='D', array=self.sources['ycentroid']) 

458 colflux = fits.Column(name='FLUX', format='D', array=self.sources['flux']) 

459 coldefs = fits.ColDefs([colx, coly, colflux]) 

460 hdu = fits.BinTableHDU.from_columns(coldefs) 

461 hdu.header['IMAGEW'] = self.data.shape[1] 

462 hdu.header['IMAGEH'] = self.data.shape[0] 

463 hdu.writeto(self.sources_file_name, overwrite=True) 

464 self.my_logger.info(f'\n\tSources positions saved in {self.sources_file_name}') 

465 

466 def plot_sources_and_gaia_catalog(self, ax=None, sources=None, gaia_coord=None, quad=None, label="", 

467 vmax=None, margin=parameters.CCD_IMSIZE, center=None, scale="log10"): 

468 """Plot the data image with different overlays: detected sources, Gaia stars, quad stars. 

469 

470 Parameters 

471 ---------- 

472 ax: Axes, optional 

473 Axes instance. If not given, open a new figure. (default: None). 

474 sources: Table, optional 

475 Sources. If not given use the current class instance (default: None). 

476 gaia_coord: SkyCoord, optional 

477 List of Gaia stars RA,DEC coordinates. If not given, does nothing (default: None). 

478 quad: array_like, optional 

479 List of quad stars (x,y) coordinates in pixel to plot the quad that was used by astrometry.net to 

480 compute the WCS solution. If not given, does nothing (default: None). 

481 center: array_like, optional 

482 (x,y) position of the center of the image. 

483 If not given, center the image on the main target (default: None). 

484 label: str, optional 

485 Name of the center if particular (default: ''). 

486 margin: int, optional 

487 Size of the image to plot in pixels from the center (default: parameters.CCD_IMSIZE). 

488 scale: str, optional 

489 Scaling of the image (choose between: lin, log or log10) (default: log10). 

490 vmax: float, optional 

491 Maximum z-scale value (default: None). 

492 

493 Examples 

494 -------- 

495 

496 >>> a = Astrometry("./tests/data/reduc_20170530_134.fits", target_label="HD111980", 

497 ... wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

498 >>> a.plot_sources_and_gaia_catalog(sources=a.sources, gaia_coord=a.gaia_radec_positions_after_pm, 

499 ... quad=a.quad_stars_pixel_positions, 

500 ... label=a.target.label) 

501 

502 .. plot: 

503 :hide: 

504 

505 from spectractor.astrometry import Astrometry 

506 

507 a = Astrometry("./tests/data/reduc_20170530_134.fits", target="HD111980", 

508 wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

509 a.plot_sources_and_gaia_catalog(sources=a.sources, gaia_coord=a.gaia_radec_positions_after_pm, 

510 quad=np.array(a.quad_stars_pixel_positions).T, 

511 label=a.target.label) 

512 

513 """ 

514 no_plot = False 

515 if ax is None: 

516 fig = plt.figure(figsize=(8, 6)) 

517 if self.wcs is not None: 

518 fig.add_subplot(111, projection=self.wcs) 

519 ax = plt.gca() 

520 else: 

521 no_plot = True 

522 

523 plot_image_simple(ax, self.data, scale=scale, vmax=vmax) 

524 if self.wcs is not None and not no_plot: 

525 ax.set_xlabel('RA') 

526 ax.set_ylabel('Dec') 

527 if sources is not None: 

528 ax.scatter(sources['xcentroid'], sources['ycentroid'], s=300, lw=2, 

529 edgecolor='black', facecolor='none', label="Detected sources") 

530 if gaia_coord is not None: 

531 gaia_x, gaia_y = self.wcs.all_world2pix(self.gaia_radec_positions_after_pm.ra, 

532 self.gaia_radec_positions_after_pm.dec, 0, quiet=True) 

533 ax.scatter(gaia_x, gaia_y, s=300, marker="+", facecolor='blue', label=f"Gaia stars", lw=2) 

534 if center is None: 

535 target_x, target_y = self.get_target_pixel_position() 

536 else: 

537 target_x, target_y = center 

538 ax.scatter(target_x, target_y, s=300, marker="x", facecolor='cyan', label=f"{label}", lw=2) 

539 if quad is not None: 

540 if len(quad) > 3: 

541 points = np.concatenate([quad, [quad[-1]]]) 

542 hull = ConvexHull(points) 

543 for simplex in hull.simplices: 

544 ax.plot(points[simplex, 0], points[simplex, 1], 'r-') 

545 ax.plot(points.T[0], points.T[1], 'rx', lw=2, label="Quad stars") 

546 else: 

547 self.my_logger.warning(f"\n\tNumber of quad stars is {len(quad)}: the quad can't be plotted. Skip it.") 

548 ax.legend() 

549 ax.set_xlim(max(0, target_x - margin), min(target_x + margin, self.data.shape[1])) 

550 ax.set_ylim(max(0, target_y - margin), min(target_y + margin, self.data.shape[0])) 

551 if not no_plot and parameters.DISPLAY: 

552 # fig.tight_layout() 

553 plt.show() 

554 else: 

555 plt.close("all") 

556 

557 def get_sources_radec_positions(self): 

558 """Gives the RA,DEC position of the detected sources. 

559 

560 Returns 

561 ------- 

562 coords: SkyCoord 

563 The RA,DEC positions 

564 

565 Examples 

566 -------- 

567 >>> a = Astrometry("./tests/data/reduc_20170530_134.fits", target_label="HD111980", 

568 ... wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

569 >>> a.get_sources_radec_positions() # doctest: +ELLIPSIS 

570 <SkyCoord (ICRS): (ra, dec) in deg... 

571 

572 """ 

573 sources_coord = self.wcs.all_pix2world(self.sources['xcentroid'], self.sources['ycentroid'], 0) 

574 self.sources_radec_positions = SkyCoord(ra=sources_coord[0] * u.deg, dec=sources_coord[1] * u.deg, 

575 frame="icrs", obstime=self.date_obs, equinox="J2000") 

576 return self.sources_radec_positions 

577 

578 def match_sources_to_gaia_catalog(self, gaia_coord=None): 

579 """Make the matching between the detected sources and the Gaia star catalog. 

580 

581 Parameters 

582 ---------- 

583 gaia_coord: SkyCoord, optional 

584 The Gaia stars RA,DEC positions. If None, the self.gaia_radec_positions_after_pm instance is used. 

585 

586 Returns 

587 ------- 

588 gaia_index: array_like 

589 The index in the Gaia catalog that matches best the sources. 

590 dist_2d: Angle 

591 The array of angular distances between the sources and the Gaia matches. 

592 dist_ra: Angle 

593 The array of distances in RA between the sources and the Gaia matches. 

594 dist_ra: Angle 

595 The array of distances in DEC between the sources and the Gaia matches. 

596 

597 Examples 

598 -------- 

599 >>> a = Astrometry("./tests/data/reduc_20170530_134.fits", target_label="HD111980", 

600 ... wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

601 >>> a.get_sources_radec_positions() # doctest: +ELLIPSIS 

602 <SkyCoord (ICRS): (ra, dec) in deg... 

603 >>> gaia_index, dist_2d, dist_ra, dist_dec = a.match_sources_to_gaia_catalog( 

604 ... gaia_coord=a.gaia_radec_positions_after_pm) 

605 >>> print(dist_2d[0: 3]) # doctest: +ELLIPSIS 

606 [0d00... 0d00m00... 0d00m00...] 

607 

608 """ 

609 if gaia_coord is None: 

610 gaia_coord = self.gaia_radec_positions_after_pm 

611 self.gaia_index, self.dist_2d, dist_3d = self.sources_radec_positions.match_to_catalog_sky(gaia_coord) 

612 matches = gaia_coord[self.gaia_index] 

613 self.dist_ra, self.dist_dec = self.sources_radec_positions.spherical_offsets_to(matches) 

614 return self.gaia_index, self.dist_2d, self.dist_ra, self.dist_dec 

615 

616 def plot_astrometry_shifts(self, vmax=3, margin=parameters.CCD_IMSIZE): 

617 """Plot the RA,DEC distances between the detected sources and the Gaia star that match the sources. 

618 

619 Parameters 

620 ---------- 

621 vmax: float, optional 

622 Maximum z-scale value in arcsec (default: 3). 

623 margin: int, optional 

624 Size of the image to plot in pixels from the center (default: parameters.CCD_IMSIZE). 

625 

626 Examples 

627 -------- 

628 >>> a = Astrometry("./tests/data/reduc_20170530_134.fits", target_label="HD111980", 

629 ... wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

630 >>> a.get_sources_radec_positions() # doctest: +ELLIPSIS 

631 <SkyCoord (ICRS): (ra, dec) in deg... 

632 >>> a.gaia_index, a.dist_2d, a.dist_ra, a.dist_dec = a.match_sources_to_gaia_catalog( 

633 ... gaia_coord=a.gaia_radec_positions_after_pm) 

634 >>> a.plot_astrometry_shifts() 

635 

636 .. plot: 

637 :hide: 

638 

639 from spectractor.astrometry import Astrometry 

640 

641 a = Astrometry("./tests/data/reduc_20170530_134.fits", target="HD111980", 

642 wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

643 a.load_gaia_catalog_around_target() # doctest: +ELLIPSIS 

644 a.load_sources_from_file() # doctest: +ELLIPSIS 

645 a.get_sources_radec_positions() # doctest: +ELLIPSIS 

646 a.gaia_index, a.dist_2d, a.dist_ra, a.dist_dec = a.match_sources_to_gaia_catalog( 

647 gaia_coord=a.gaia_radec_positions_after_pm) 

648 a.plot_astrometry_shifts() 

649 """ 

650 target_x, target_y = self.get_target_pixel_position() 

651 gaia_x, gaia_y = self.get_gaia_pixel_positions(gaia_index=self.gaia_index) 

652 

653 fig = plt.figure(figsize=(6, 8)) 

654 

655 fig.add_subplot(211, projection=self.wcs) 

656 

657 plot_image_simple(plt.gca(), self.data, scale="log10") 

658 plt.xlabel('RA') 

659 plt.ylabel('Dec') 

660 if self.sources is not None: 

661 plt.scatter(self.sources['xcentroid'], self.sources['ycentroid'], s=100, lw=2, 

662 edgecolor='black', facecolor='none', label="Detected sources") 

663 vmax_2 = min(vmax, np.max(np.abs(self.dist_ra.to(u.arcsec).value))) 

664 sc = plt.scatter(gaia_x, gaia_y, s=100, c=self.dist_ra.to(u.arcsec).value, 

665 cmap="bwr", vmin=-vmax_2, vmax=vmax_2, 

666 label=f"Gaia stars", lw=1) 

667 plt.xlim(max(0, int(target_x - margin)), min(int(target_x + margin), self.data.shape[1])) 

668 plt.ylim(max(0, int(target_y - margin)), min(int(target_y + margin), self.data.shape[0])) 

669 plt.colorbar(sc, label="Shift in RA [arcsec]") 

670 plt.legend() 

671 

672 fig.add_subplot(212, projection=self.wcs) 

673 plot_image_simple(plt.gca(), self.data, scale="log10") 

674 plt.xlabel('RA') 

675 plt.ylabel('Dec') 

676 plt.grid(color='white', ls='solid') 

677 if self.sources is not None: 

678 plt.scatter(self.sources['xcentroid'], self.sources['ycentroid'], s=100, lw=2, 

679 edgecolor='black', facecolor='none', label="all sources") 

680 vmax_2 = min(vmax, np.max(np.abs(self.dist_dec.to(u.arcsec).value))) 

681 sc = plt.scatter(gaia_x, gaia_y, s=100, c=self.dist_dec.to(u.arcsec).value, 

682 cmap="bwr", vmin=-vmax_2, vmax=vmax_2, 

683 label=f"Gaia Stars", lw=1) 

684 plt.xlim(max(0, int(target_x - margin)), min(int(target_x + margin), self.data.shape[1])) 

685 plt.ylim(max(0, int(target_y - margin)), min(int(target_y + margin), self.data.shape[0])) 

686 plt.colorbar(sc, label="Shift in DEC [arcsec]") 

687 plt.legend() 

688 if parameters.DISPLAY: 

689 # fig.tight_layout() 

690 plt.show() 

691 else: 

692 plt.close("all") 

693 

694 def set_constraints(self, min_stars=100, flux_log10_threshold=0.1, min_range=3 * u.arcsec, max_range=5 * u.arcmin, 

695 max_sep=1 * u.arcsec): 

696 """Gives a boolean array for sources that respect certain criterai (see below). 

697 

698 Parameters 

699 ---------- 

700 min_stars: int 

701 Minimum number of stars that have to be kept in the selection (default: 100). 

702 flux_log10_threshold: 

703 Lower cut on the log10 of the star fluxes (default: 0.1). 

704 min_range: 

705 Minimum distance for sources from image principal target in arcsec (default: 3*u.arcsec). 

706 max_range 

707 Maximum distance for sources from image principal target in arcsec (default: 3*u.arcsec). 

708 max_sep 

709 Maximum separation between the detected sources and the Gaia stars in arcsec (default: 1*u.arcsec). 

710 

711 Returns 

712 ------- 

713 indices: array_like 

714 Boolean array of selected sources. 

715 

716 """ 

717 sep = self.dist_2d < max_sep 

718 sep *= self.sources_radec_positions.separation(self.target_radec_position_after_pm) < max_range 

719 sep *= self.sources_radec_positions.separation(self.target_radec_position_after_pm) > min_range 

720 sep *= np.log10(self.sources['flux']) > flux_log10_threshold 

721 if np.sum(sep) > min_stars: 

722 for r in np.arange(0, max_range.value, 0.1)[::-1]: 

723 range_constraint = self.sources_radec_positions.separation(self.target.radec_position_after_pm) \ 

724 < r * u.arcmin 

725 if np.sum(sep * range_constraint) < min_stars: 

726 break 

727 else: 

728 sep *= range_constraint 

729 return sep 

730 

731 def plot_shifts_profiles(self, matches, dra, ddec): 

732 """Plot the distances between Gaia stars and detected sources with respect to RA and DEC. 

733 The median of the distances is overplotted. 

734 

735 Parameters 

736 ---------- 

737 matches: SkyCoord 

738 Array of sky coordinates of the detected sources. 

739 dra: Angle 

740 Array of distances between sources and Gaia stars along the RA direction. 

741 ddec 

742 Array of distances between sources and Gaia stars along the DEC direction. 

743 

744 Examples 

745 -------- 

746 

747 >>> a = Astrometry("./tests/data/reduc_20170530_134.fits", target_label="HD111980", 

748 ... wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

749 >>> a.get_sources_radec_positions() # doctest: +ELLIPSIS 

750 <SkyCoord (ICRS): (ra, dec) in deg... 

751 >>> a.gaia_index, a.dist_2d, a.dist_ra, a.dist_dec = a.match_sources_to_gaia_catalog( 

752 ... gaia_coord=a.gaia_radec_positions_after_pm) 

753 >>> sep_constraints = a.set_constraints(flux_log10_threshold=0.1) 

754 >>> sources_selection = a.sources_radec_positions[sep_constraints] 

755 >>> gaia_matches = a.gaia_radec_positions_after_pm[a.gaia_index[sep_constraints]] 

756 >>> dra, ddec = sources_selection.spherical_offsets_to(gaia_matches) 

757 >>> a.plot_shifts_profiles(gaia_matches, dra, ddec) 

758 

759 .. plot: 

760 :hide: 

761 

762 from spectractor.astrometry import Astrometry 

763 

764 a = Astrometry("./tests/data/reduc_20170530_134.fits", target="HD111980", 

765 wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

766 a.load_gaia_catalog_around_target() 

767 a.load_sources_from_file() 

768 a.get_sources_radec_positions() 

769 a.gaia_index, a.dist_2d, a.dist_ra, a.dist_dec = a.match_sources_to_gaia_catalog( 

770 gaia_coord=a.gaia_radec_positions_after_pm) 

771 sep_constraints = a.set_constraints(flux_log10_threshold=0.1) 

772 sources_selection = a.sources_radec_positions[sep_constraints] 

773 gaia_matches = a.gaia_radec_positions_after_pm[a.gaia_index[sep_constraints]] 

774 dra, ddec = sources_selection.spherical_offsets_to(gaia_matches) 

775 a.plot_shifts_profiles(gaia_matches, dra, ddec) 

776 

777 

778 """ 

779 dra_median = np.median(dra.to(u.arcsec).value) 

780 ddec_median = np.median(ddec.to(u.arcsec).value) 

781 fig, ax = plt.subplots(1, 2, figsize=(11, 4)) 

782 c_ra = ax[0].scatter(matches.ra, dra.to(u.arcsec).value, label="Shift in RA [arcsec]") 

783 c_dec = ax[0].scatter(matches.ra, ddec.to(u.arcsec).value, label="Shift in DEC [arcsec]") 

784 ax[1].scatter(matches.dec, dra.to(u.arcsec).value, label="Shift in RA [arcsec]") 

785 ax[1].scatter(matches.dec, ddec.to(u.arcsec).value, label="Shift in DEC [arcsec]") 

786 ax[0].axhline(dra_median, color=c_ra.get_facecolor()[0], label="median", lw=2) 

787 ax[0].axhline(ddec_median, color=c_dec.get_facecolor()[0], label="median", lw=2) 

788 ax[1].axhline(dra_median, color=c_ra.get_facecolor()[0], label="median", lw=2) 

789 ax[1].axhline(ddec_median, color=c_dec.get_facecolor()[0], label="median", lw=2) 

790 ax[0].axvline(self.target_radec_position_after_pm.ra.value, color='k', linestyle="--", 

791 label=f"{self.target.label} RA") 

792 ax[1].axvline(self.target_radec_position_after_pm.dec.value, color='k', linestyle="--", 

793 label=f"{self.target.label} DEC") 

794 ax[0].set_xlabel('Gaia RA [deg]') 

795 ax[1].set_xlabel('Gaia DEC [deg]') 

796 ax[0].set_ylabel('Astrometric shifts [arcsec]') 

797 ax[1].set_ylabel('Astrometric shifts [arcsec]') 

798 ax[0].grid() 

799 ax[1].grid() 

800 ax[0].set_ylim(-2, 2) 

801 ax[1].set_ylim(-2, 2) 

802 ax[0].legend() 

803 ax[1].legend() 

804 if parameters.DISPLAY: 

805 plt.show() 

806 if parameters.PdfPages: 

807 parameters.PdfPages.savefig() 

808 

809 def merge_wcs_with_new_exposure(self, log_file=None): 

810 """Merge the WCS solution with the current FITS file image. 

811 

812 Parameters 

813 ---------- 

814 log_file: file, optional 

815 Log file to write the output of the merge command. 

816 

817 """ 

818 command = f"{os.path.join(parameters.ASTROMETRYNET_DIR, 'bin/new-wcs')} -v -d -i {self.file_name} " \ 

819 f"-w {self.wcs_file_name} -o {self.new_file_name}\n" 

820 self.my_logger.info(f'\n\tSave WCS in original file:\n\t{command}') 

821 log = subprocess.check_output(command, shell=True) 

822 if log_file is not None: 

823 log_file.write(command + "\n") 

824 log_file.write(log.decode("utf-8") + "\n") 

825 

826 def compute_gaia_pixel_residuals(self): 

827 """Compute the residuals in pixels between the detected sources and the associated Gaia stars. 

828 A selection in proximity, range and flux is performed to keep the best matches. 

829 

830 Returns 

831 ------- 

832 gaia_residuals: array_like 

833 2D array of the pixel residuals. 

834 

835 Examples 

836 -------- 

837 

838 >>> a = Astrometry("./tests/data/reduc_20170530_134.fits", target_label="HD111980", 

839 ... wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

840 >>> residuals = a.compute_gaia_pixel_residuals() 

841 

842 .. doctest: 

843 :hide: 

844 

845 >>> assert residuals.shape == (4, 2) 

846 

847 """ 

848 coords = self.quad_stars_pixel_positions.T 

849 ra, dec = self.wcs.all_pix2world(coords[0], coords[1], 0) 

850 coords_radec = SkyCoord(ra * u.deg, dec * u.deg, frame='icrs', equinox="J2000") 

851 gaia_index, dist_2d, dist_3d = coords_radec.match_to_catalog_sky(self.gaia_radec_positions_after_pm) 

852 matches = self.gaia_radec_positions_after_pm[gaia_index] 

853 gaia_coords = np.array(self.wcs.all_world2pix(matches.ra, matches.dec, 0)) 

854 self.gaia_residuals = (gaia_coords - coords).T 

855 return self.gaia_residuals 

856 

857 def find_quad_star_index_in_sources(self, quad_star): 

858 """Associate a quad star with a detected source. 

859 

860 Parameters 

861 ---------- 

862 quad_star: array_like 

863 (x, y) positions of a quad star 

864 

865 Returns 

866 ------- 

867 index: int 

868 The index of the source that match the input quad star. 

869 

870 Examples 

871 -------- 

872 

873 >>> a = Astrometry("./tests/data/reduc_20170530_134.fits", target_label="HD111980", 

874 ... wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

875 >>> a.load_sources_from_file() # doctest: +ELLIPSIS 

876 <Table length=... 

877 >>> index = a.find_quad_star_index_in_sources(a.quad_stars_pixel_positions[0]) 

878 

879 """ 

880 eps = 1e-1 

881 k = -1 

882 for k in range(len(self.sources)): 

883 if abs(self.sources['xcentroid'][k] - quad_star[0]) < eps \ 

884 and abs(self.sources['ycentroid'][k] - quad_star[1]): 

885 break 

886 return k 

887 

888 def remove_worst_quad_star_from_sources(self): 

889 """Remove the quad star from the source table with the largest distance between the source centroid 

890 and the associated Gaia star position. 

891 

892 Examples 

893 -------- 

894 

895 >>> a = Astrometry("./tests/data/reduc_20170530_134.fits", target_label="HD111980", 

896 ... wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

897 >>> a.load_sources_from_file() # doctest: +ELLIPSIS 

898 <Table length=... 

899 >>> length = len(a.sources) 

900 >>> a.remove_worst_quad_star_from_sources() 

901 >>> assert len(a.sources) == length - 1 

902 

903 """ 

904 gaia_pixel_residuals = self.compute_gaia_pixel_residuals() 

905 distances = np.sqrt(np.sum(gaia_pixel_residuals ** 2, axis=1)) 

906 max_residual_index = int(np.argmax(distances)) 

907 worst_source_index = \ 

908 self.find_quad_star_index_in_sources(self.quad_stars_pixel_positions[max_residual_index]) 

909 self.my_logger.debug(f"\n\tRemove source #{worst_source_index}\n{self.sources[max_residual_index]}") 

910 self.sources.remove_row(worst_source_index) 

911 

912 def plot_quad_stars(self, margin=10, scale="log10"): 

913 """Make a set of plots centered on the quad stars to check their astrometry. 

914 

915 Parameters 

916 ---------- 

917 margin: int, optional 

918 Size of the image to plot in pixels from the center (default: parameters.CCD_IMSIZE). 

919 scale: str, optional 

920 Scaling of the image (choose between: lin, log or log10) (default: log10). 

921 

922 Examples 

923 -------- 

924 

925 >>> a = Astrometry("./tests/data/reduc_20170530_134.fits", target_label="HD111980", 

926 ... wcs_file_name="./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs") 

927 >>> a.load_sources_from_file() # doctest: +ELLIPSIS 

928 <Table length=... 

929 >>> a.plot_quad_stars() 

930 

931 """ 

932 nquads = self.quad_stars_pixel_positions.shape[0] 

933 fig, ax = plt.subplots(1, nquads, figsize=(4 * nquads, 3)) 

934 for k in range(nquads): 

935 row = self.sources[self.find_quad_star_index_in_sources((self.quad_stars_pixel_positions[k][0], 

936 self.quad_stars_pixel_positions[k][1]))] 

937 self.plot_sources_and_gaia_catalog(ax=ax[k], center=(self.quad_stars_pixel_positions[k][0], 

938 self.quad_stars_pixel_positions[k][1]), 

939 margin=margin, scale=scale, sources=self.sources, 

940 gaia_coord=self.gaia_matches, label=f"Quad star #{k}", 

941 quad=self.quad_stars_pixel_positions) 

942 ax[k].set_title( 

943 f"x={self.quad_stars_pixel_positions[k][0]:.2f}, y={self.quad_stars_pixel_positions[k][1]:.2f}, " 

944 f"flux={row['flux']:.2f}") 

945 if parameters.DISPLAY: 

946 fig.tight_layout() 

947 plt.show() 

948 if parameters.PdfPages: 

949 parameters.PdfPages.savefig() 

950 

951 def run_simple_astrometry(self, extent=None, sources=None): 

952 """Build a World Coordinate System (WCS) using astrometry.net library given an exposure as a FITS file. 

953 

954 The name of the target must be given to get its RA,DEC coordinates via a Simbad query. 

955 First the background of the exposure is removed using the astropy SExtractorBackground() method. 

956 Then photutils source_detection() is used to get the positions in pixels en flux of the objects in the field. 

957 The results are saved in the {file_name}_sources.fits file and used by the solve_field command from the 

958 astrometry.net library. The solve_field path must be set using the spectractor.parameters.ASTROMETRYNET_BINDIR 

959 variable. A new WCS is created and saved as a new FITS file. The WCS file and the intermediate results 

960 are saved in a new directory named as the FITS file name with a _wcs suffix. 

961 

962 Parameters 

963 ---------- 

964 extent: 2-tuple 

965 ((xmin,xmax),(ymin,ymax)) 2 dimensional tuple to crop the exposure before any operation (default: None). 

966 sources: Table 

967 List of sources. If None, then source detection is run on the image (default: None). 

968 

969 Notes 

970 ----- 

971 The source file given to solve-field is understood as a FITS file with pixel origin value at 1, 

972 whereas pixel coordinates comes from photutils using a numpy convention with pixel origin value at 0. 

973 To correct for this we shift the CRPIX center of 1 pixel at the end of the function. It can be that solve-field 

974 using the source list or the raw FITS image then give the same WCS values. 

975 

976 See Also 

977 -------- 

978 

979 source_detection() 

980 

981 Examples 

982 -------- 

983 

984 >>> import os 

985 >>> from spectractor.logbook import LogBook 

986 >>> from spectractor.astrometry import Astrometry 

987 >>> from spectractor import parameters 

988 >>> parameters.VERBOSE = True 

989 >>> logbook = LogBook(logbook='./ctiofulllogbook_jun2017_v5.csv') 

990 >>> file_names = ['./tests/data/reduc_20170530_134.fits'] 

991 >>> if os.path.isfile('./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs'): 

992 ... os.remove('./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs') 

993 >>> for file_name in file_names: 

994 ... tag = file_name.split('/')[-1] 

995 ... disperser_label, target, xpos, ypos = logbook.search_for_image(tag) 

996 ... if target is None or xpos is None or ypos is None: 

997 ... continue 

998 ... a = Astrometry(file_name, target, disperser_label) 

999 ... a.run_simple_astrometry(extent=((300,1400),(300,1400))) # doctest: +ELLIPSIS 

1000 WCS ... 

1001 

1002 .. doctest: 

1003 :hide: 

1004 

1005 >>> assert os.path.isdir('./tests/data/reduc_20170530_134_wcs') 

1006 >>> assert os.path.isfile('./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs') 

1007 

1008 """ 

1009 # crop data 

1010 if extent is not None: 

1011 data = self.data[extent[1][0]:extent[1][1], extent[0][0]:extent[0][1]] 

1012 else: 

1013 data = np.copy(self.data) 

1014 if sources is None: 

1015 # remove background 

1016 self.my_logger.info('\n\tRemove background using astropy SExtractorBackground()...') 

1017 data_wo_bkg = remove_image_background_sextractor(data, sigma=3.0, box_size=(50, 50), 

1018 filter_size=(10, 10), positive=True) 

1019 # extract source positions and fluxes 

1020 self.my_logger.info('\n\tDetect sources using photutils source_detection()...') 

1021 self.sources = source_detection(data_wo_bkg, sigma=3.0, fwhm=3.0, threshold_std_factor=5, mask=None) 

1022 if extent is not None: 

1023 self.sources['xcentroid'] += extent[0][0] 

1024 self.sources['ycentroid'] += extent[1][0] 

1025 self.my_logger.info(f'\n\t{self.sources}') 

1026 else: 

1027 self.sources = sources 

1028 # write results in fits file 

1029 self.write_sources() 

1030 # run astrometry.net 

1031 command = f"{os.path.join(parameters.ASTROMETRYNET_DIR, 'bin/solve-field')} --scale-unit arcsecperpix " \ 

1032 f"--scale-low {0.95 * parameters.CCD_PIXEL2ARCSEC} " \ 

1033 f"--scale-high {1.05 * parameters.CCD_PIXEL2ARCSEC} " \ 

1034 f"--ra {self.target.radec_position.ra.value} --dec {self.target.radec_position.dec.value} " \ 

1035 f"--radius {parameters.CCD_IMSIZE * parameters.CCD_PIXEL2ARCSEC / 3600.} " \ 

1036 f"--dir {self.output_directory} --out {self.tag} " \ 

1037 f"--overwrite --x-column X --y-column Y {self.sources_file_name}" 

1038 self.my_logger.info(f'\n\tRun astrometry.net solve_field command:\n\t{command}') 

1039 log = subprocess.check_output(command, shell=True) 

1040 log_file = open(self.log_file_name, "w+") 

1041 log_file.write(command + "\n") 

1042 log_file.write(log.decode("utf-8") + "\n") 

1043 # save new WCS in original fits file 

1044 # self.merge_wcs_with_new_exposure(log_file=log_file) 

1045 log_file.close() 

1046 

1047 # The source file given to solve-field is understood as a FITS file with pixel origin value at 1, 

1048 # whereas pixel coordinates comes from photutils using a numpy convention with pixel origin value at 0 

1049 # To correct for this we shift the CRPIX center of 1 pixel 

1050 hdu = fits.open(self.wcs_file_name) 

1051 hdu[0].header['CRPIX1'] = float(hdu[0].header['CRPIX1']) + 1 

1052 hdu[0].header['CRPIX2'] = float(hdu[0].header['CRPIX2']) + 1 

1053 self.my_logger.info(f"\n\tWrite astrometry.net WCS solution in {self.wcs_file_name}...") 

1054 hdu.writeto(self.wcs_file_name, overwrite=True) 

1055 

1056 # load quad stars 

1057 self.quad_stars_pixel_positions = self.get_quad_stars_pixel_positions() 

1058 

1059 # load WCS 

1060 self.wcs = load_wcs_from_file(self.wcs_file_name) 

1061 return self.wcs 

1062 

1063 # noinspection PyUnresolvedReferences 

1064 def run_gaia_astrometry(self): 

1065 """Refine a World Coordinate System (WCS) using Gaia satellite astrometry catalog. 

1066 

1067 A WCS must be already present in the exposure FITS file. 

1068 

1069 The name of the target must be given to get its RA,DEC coordinates via a Simbad query. 

1070 A matching is performed between the detected sources and the Gaia catalog obtained for the region of the target. 

1071 Then the closest and brightest sources are selected and the WCS is shifted by the median of the distance between 

1072 these stars and the detected sources. The original WCS FITS file is updated. 

1073 

1074 Examples 

1075 -------- 

1076 

1077 >>> import os 

1078 >>> from spectractor.logbook import LogBook 

1079 >>> from spectractor import parameters 

1080 >>> parameters.VERBOSE = True 

1081 >>> parameters.DEBUG = True 

1082 >>> logbook = LogBook(logbook='./ctiofulllogbook_jun2017_v5.csv') 

1083 >>> file_names = ['./tests/data/reduc_20170530_134.fits'] 

1084 >>> if os.path.isfile('./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs'): 

1085 ... os.remove('./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs') 

1086 >>> for file_name in file_names: 

1087 ... tag = file_name.split('/')[-1] 

1088 ... disperser_label, target, xpos, ypos = logbook.search_for_image(tag) 

1089 ... if target is None or xpos is None or ypos is None: 

1090 ... continue 

1091 ... a = Astrometry(file_name, target, disperser_label) 

1092 ... a.run_simple_astrometry(extent=((300,1400),(300,1400))) 

1093 ... dra, ddec = a.run_gaia_astrometry() # doctest: +ELLIPSIS 

1094 WCS ... 

1095 

1096 .. doctest: 

1097 :hide: 

1098 

1099 >>> dra_median = np.median(dra.to(u.arcsec).value) 

1100 >>> ddec_median = np.median(ddec.to(u.arcsec).value) 

1101 >>> assert os.path.isdir('./tests/data/reduc_20170530_134_wcs') 

1102 >>> assert os.path.isfile('./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs') 

1103 >>> assert np.all(np.abs([dra_median, ddec_median]) < 1e-3) 

1104 

1105 """ 

1106 # load detected sources 

1107 if self.sources is None: 

1108 self.sources = self.load_sources_from_file() 

1109 # load WCS if absent 

1110 if self.wcs is None: 

1111 self.wcs = load_wcs_from_file(self.wcs_file_name) 

1112 self.sources_radec_positions = self.get_sources_radec_positions() 

1113 

1114 # load the Gaia catalog 

1115 if self.gaia_catalog is None: 

1116 if os.path.isfile(self.gaia_file_name): 

1117 self.my_logger.info(f"\n\tLoad Gaia catalog from {self.gaia_file_name}.") 

1118 self.gaia_catalog = ascii.read(self.gaia_file_name, format="ecsv") 

1119 else: 

1120 radius = 2 * max(np.max(self.sources["xcentroid"]) - np.min(self.sources["xcentroid"]), 

1121 np.max(self.sources["ycentroid"]) - np.min(self.sources["ycentroid"])) 

1122 radius *= parameters.CCD_PIXEL2ARCSEC * u.arcsec 

1123 self.my_logger.info(f"\n\tLoading Gaia catalog within radius < {radius.value} " 

1124 f"arcsec from {self.target.label} {self.target.radec_position}...") 

1125 self.gaia_catalog = load_gaia_catalog(self.target.radec_position, radius=radius) 

1126 ascii.write(self.gaia_catalog, self.gaia_file_name, format='ecsv', overwrite=True) 

1127 self.my_logger.info(f"\n\tGaia catalog loaded.") 

1128 

1129 # update coordinates with proper motion data 

1130 self.my_logger.info(f"\n\tUpdate object coordinates with proper motion at time={self.date_obs}.") 

1131 self.target_radec_position_after_pm = self.target.get_radec_position_after_pm(self.date_obs) 

1132 self.gaia_radec_positions_after_pm = get_gaia_coords_after_proper_motion(self.gaia_catalog, self.date_obs) 

1133 if parameters.DEBUG: 

1134 self.plot_sources_and_gaia_catalog(sources=self.sources, gaia_coord=self.gaia_radec_positions_after_pm, 

1135 quad=self.quad_stars_pixel_positions, margin=1000, 

1136 label=self.target.label) 

1137 

1138 # compute shifts 

1139 self.my_logger.info(f"\n\tCompute distances between Gaia catalog and detected sources.") 

1140 self.gaia_index, self.dist_2d, self.dist_ra, self.dist_dec = \ 

1141 self.match_sources_to_gaia_catalog(self.gaia_radec_positions_after_pm) 

1142 if parameters.DEBUG: 

1143 self.plot_astrometry_shifts(vmax=3) 

1144 

1145 # select the brightest and closest stars with minimal shift 

1146 if len(self.sources) > 50: 

1147 flux_log10_threshold = np.log10(self.sources['flux'][int(0.5 * len(self.sources))]) 

1148 else: 

1149 flux_log10_threshold = np.log10(self.sources['flux'][int(0.8 * len(self.sources))]) 

1150 sep_constraints = self.set_constraints(flux_log10_threshold=flux_log10_threshold) 

1151 sources_selection = self.sources_radec_positions[sep_constraints] 

1152 gaia_matches = self.gaia_radec_positions_after_pm[self.gaia_index[sep_constraints]] 

1153 dra, ddec = sources_selection.spherical_offsets_to(gaia_matches) 

1154 

1155 # compute statistics 

1156 dra_median = np.median(dra.to(u.arcsec).value) 

1157 ddec_median = np.median(ddec.to(u.arcsec).value) 

1158 self.my_logger.info(f"\n\tMedian DeltaRA={dra_median:.3f} arcsec, median DeltaDEC={ddec_median:.3f} arcsec") 

1159 if parameters.DEBUG: 

1160 plot_shifts_histograms(dra, ddec) 

1161 self.plot_shifts_profiles(gaia_matches, dra, ddec) 

1162 

1163 # update WCS 

1164 # tested with high latitude 20170530_120.fits exposure: dra shift must be divided by cos(dec) 

1165 # to set new WCS system because spherical_offsets_to gives shifts angle at equator 

1166 # (see https://docs.astropy.org/en/stable/api/astropy.coordinates.SkyCoord.html 

1167 # #astropy.coordinates.SkyCoord.spherical_offsets_to) 

1168 # after the shift the histograms must be centered on zero 

1169 total_shift = np.array( 

1170 [dra_median / np.cos(self.target_radec_position_after_pm.dec.radian), ddec_median]) * u.arcsec 

1171 self.my_logger.info(f"\n\tShift original CRVAL value {self.wcs.wcs.crval * u.deg} of {total_shift}.") 

1172 self.wcs.wcs.crval = self.wcs.wcs.crval * u.deg + total_shift 

1173 # if parameters.DEBUG: 

1174 # self.plot_sources_and_gaia_catalog(sources=self.sources, gaia_coord=self.gaia_radec_positions_after_pm, 

1175 # quad=np.array(self.quad_stars_pixel_positions).T, 

1176 # margin=10, label=self.target.label) 

1177 

1178 # Now, write out the WCS object as a FITS header 

1179 dra_median = np.median(dra.to(u.arcsec).value) 

1180 ddec_median = np.median(ddec.to(u.arcsec).value) 

1181 dra_rms = np.std(dra.to(u.arcsec).value) 

1182 ddec_rms = np.std(ddec.to(u.arcsec).value) 

1183 hdu = fits.open(self.wcs_file_name) 

1184 hdu[0].header['CRVAL1'] = self.wcs.wcs.crval[0] 

1185 hdu[0].header['CRVAL2'] = self.wcs.wcs.crval[1] 

1186 hdu[0].header['CRV1_MED'] = dra_median 

1187 hdu[0].header['CRV2_MED'] = ddec_median 

1188 hdu[0].header['CRV1_RMS'] = dra_rms 

1189 hdu[0].header['CRV2_RMS'] = ddec_rms 

1190 hdu.writeto(self.wcs_file_name, overwrite=True) 

1191 

1192 # check histogram medians 

1193 self.wcs = load_wcs_from_file(self.wcs_file_name) 

1194 self.get_sources_radec_positions() 

1195 self.gaia_index, self.dist_2d, self.dist_ra, self.dist_dec = \ 

1196 self.match_sources_to_gaia_catalog(self.gaia_radec_positions_after_pm) 

1197 sep_constraints = self.set_constraints(flux_log10_threshold=flux_log10_threshold) 

1198 sources_selection = self.sources_radec_positions[sep_constraints] 

1199 self.gaia_matches = self.gaia_radec_positions_after_pm[self.gaia_index[sep_constraints]] 

1200 dra, ddec = sources_selection.spherical_offsets_to(self.gaia_matches) 

1201 

1202 # update values 

1203 self.my_logger.info(f"\n\tUpdate WCS solution from {self.wcs_file_name} with Gaia solution.") 

1204 dra_median = np.median(dra.to(u.arcsec).value) 

1205 ddec_median = np.median(ddec.to(u.arcsec).value) 

1206 dra_rms = np.std(dra.to(u.arcsec).value) 

1207 ddec_rms = np.std(ddec.to(u.arcsec).value) 

1208 hdu = fits.open(self.wcs_file_name) 

1209 hdu[0].header['CRV1_MED'] = dra_median 

1210 hdu[0].header['CRV2_MED'] = ddec_median 

1211 hdu[0].header['CRV1_RMS'] = dra_rms 

1212 hdu[0].header['CRV2_RMS'] = ddec_rms 

1213 hdu.writeto(self.wcs_file_name, overwrite=True) 

1214 

1215 # if parameters.DEBUG: 

1216 # plot_shifts_histograms(dra, ddec) 

1217 # self.plot_sources_and_gaia_catalog(sources=self.sources, gaia_coord=self.gaia_radec_positions_after_pm, 

1218 # quad=np.array(self.quad_stars_pixel_positions).T, 

1219 # margin=10, label=self.target.label) 

1220 return dra, ddec 

1221 

1222 def run_full_astrometry(self, extent=None, maxiter=20): 

1223 """Iterative method to get a precise World Coordinate System (WCS) using Gaia satellite astrometry catalog and 

1224 astrometry.net fitter. 

1225 

1226 This function runs alternatively the run_simple_astrometry and the run_gaia_astrometry. 

1227 After an iteration, the distances between the quad stars and the associated Gaia stars are 

1228 computed. The quad star with the largest distance is removed from the list of detected sources. 

1229 Then the function iterates again until it reaches the maxiter maximum number of iterations 

1230 or when astrometry.net fails because too few sources are left. 

1231 At each iteration, the total quadratic sum of the distances between the quad stars and the 

1232 Gaia stars is computed. The iteration with the smallest total distance (ie the smallest centroid 

1233 distances in the pixel space) is kept as the best iteration and gives the final WCS. 

1234 

1235 A new WCS is created and saved as a new FITS file. The WCS file and the intermediate results 

1236 are saved in a new directory named as the FITS file name with a _wcs suffix. 

1237 

1238 Parameters 

1239 ---------- 

1240 extent: array_like, optional 

1241 A ((xmin,xmax),(ymin,ymax)) to crop the image before any analysis (default: None). 

1242 maxiter: int, optional 

1243 The maximum number of iterations (default: 20). 

1244 

1245 Returns 

1246 ------- 

1247 min_gaia_residuals_quad_sum: float 

1248 The minimum total quadratic distance between Gaia stars and the quad stars (in pixels). 

1249 

1250 Examples 

1251 -------- 

1252 

1253 >>> import os 

1254 >>> from spectractor.logbook import LogBook 

1255 >>> from spectractor import parameters 

1256 >>> parameters.VERBOSE = True 

1257 >>> parameters.DEBUG = True 

1258 >>> radius = 100 

1259 >>> maxiter = 10 

1260 >>> logbook = LogBook(logbook='./ctiofulllogbook_jun2017_v5.csv') 

1261 >>> file_names = ['./tests/data/reduc_20170530_134.fits'] 

1262 >>> if os.path.isfile('./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs'): 

1263 ... os.remove('./tests/data/reduc_20170530_134_wcs/reduc_20170530_134.wcs') 

1264 >>> for file_name in file_names: 

1265 ... tag = file_name.split('/')[-1] 

1266 ... disperser_label, target, xpos, ypos = logbook.search_for_image(tag) 

1267 ... if target is None or xpos is None or ypos is None: 

1268 ... continue 

1269 ... a = Astrometry(file_name, target, disperser_label) 

1270 ... extent = ((max(0, xpos - radius), min(xpos + radius, parameters.CCD_IMSIZE)), 

1271 ... (max(0, ypos - radius), min(ypos + radius, parameters.CCD_IMSIZE))) 

1272 ... gaia_min_residuals = a.run_full_astrometry(extent=extent, maxiter=maxiter) #doctest: +ELLIPSIS 

1273 iter target_x ... 

1274 

1275 .. doctest: 

1276 :hide: 

1277 

1278 >>> assert os.path.isdir(a.output_directory) 

1279 >>> assert os.path.isfile(set_wcs_file_name(file_name)) 

1280 >>> assert a.data is not None 

1281 >>> assert np.sum(a.data) > 1e-10 

1282 >>> assert gaia_min_residuals < 0.8 

1283 

1284 """ 

1285 

1286 t = Table(names=["iter", "target_x", "target_y", "gaia_residuals_abs_sum_x", 

1287 "gaia_residuals_abs_sum_y", "gaia_residuals_quad_sum"]) 

1288 t["iter"].format = "%d" 

1289 for c in t.columns[1:]: 

1290 t[c].format = "%.2f" 

1291 sources_list = [] 

1292 for k in range(maxiter): 

1293 self.my_logger.info(f'\n\tIteration #{k}') 

1294 try: 

1295 # find a simple astrometric solution using astrometry.net 

1296 self.run_simple_astrometry(extent=extent, sources=self.sources) 

1297 # refine with Gaia catalog 

1298 for i in range(maxiter): 

1299 dra, ddec = self.run_gaia_astrometry() 

1300 dra_median = np.median(dra.to(u.mas).value) 

1301 ddec_median = np.median(ddec.to(u.mas).value) 

1302 if np.abs(dra_median) < 1 and np.abs(ddec_median) < 1: 

1303 break 

1304 sources_list.append(deepcopy(self.sources)) 

1305 # check the positions of quad stars with their WCS position from Gaia catalog 

1306 gaia_residuals = self.compute_gaia_pixel_residuals() 

1307 gaia_residuals_sum_x, gaia_residuals_sum_y = np.sum(np.abs(gaia_residuals), axis=0) 

1308 gaia_residuals_quad_sum = np.sum(np.sqrt(np.sum(gaia_residuals ** 2, axis=1))) 

1309 if parameters.DEBUG: 

1310 self.plot_sources_and_gaia_catalog(sources=self.sources, gaia_coord=self.gaia_matches, margin=20, 

1311 quad=self.quad_stars_pixel_positions, 

1312 label=self.target.label) 

1313 self.plot_astrometry_shifts(vmax=3) 

1314 self.plot_quad_stars() 

1315 target_x, target_y = self.get_target_pixel_position() 

1316 t.add_row([k, target_x, target_y, gaia_residuals_sum_x, gaia_residuals_sum_y, gaia_residuals_quad_sum]) 

1317 self.remove_worst_quad_star_from_sources() 

1318 except FileNotFoundError or TimeoutError: 

1319 self.my_logger.warning(f"\n\tAstrometry.net failed at iteration {k}. " 

1320 f"Stop the loop here and look for best solution.") 

1321 k -= 1 

1322 break 

1323 t.pprint_all() 

1324 best_iter = int(np.argmin(t["gaia_residuals_quad_sum"])) 

1325 self.my_logger.info(f'\n\tBest run: iteration #{best_iter}') 

1326 self.run_simple_astrometry(extent=extent, sources=sources_list[best_iter]) 

1327 self.run_gaia_astrometry() 

1328 self.my_logger.info(f'\n\tFinal target position: {self.get_target_pixel_position()}') 

1329 if parameters.DEBUG: 

1330 self.plot_sources_and_gaia_catalog(sources=self.sources, gaia_coord=self.gaia_matches, margin=20, 

1331 quad=self.quad_stars_pixel_positions, label="FINALLLL") 

1332 self.plot_quad_stars() 

1333 return np.min(t["gaia_residuals_quad_sum"]) 

1334 

1335 

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

1337 import doctest 

1338 

1339 doctest.testmod()