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 self.output_directory = set_wcs_output_directory(file_name, output_directory=output_directory) 

246 ensure_dir(self.output_directory) 

247 self.tag = set_wcs_tag(file_name) 

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

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

250 self.wcs_file_name = wcs_file_name 

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

252 self.wcs = None 

253 if self.wcs_file_name != "": 

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

255 self.wcs = load_wcs_from_file(self.wcs_file_name) 

256 else: 

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

258 else: 

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

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

261 self.wcs = load_wcs_from_file(self.wcs_file_name) 

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

263 self.gaia_catalog = None 

264 self.gaia_index = None 

265 self.gaia_matches = None 

266 self.gaia_residuals = None 

267 self.gaia_radec_positions_after_pm = None 

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

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

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

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

272 self.sources = None 

273 self.sources_radec_positions = None 

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

275 self.sources = self.load_sources_from_file() 

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

277 self.dist_2d = None 

278 self.quad_stars_pixel_positions = None 

279 self.dist_ra = 0 * u.arcsec 

280 self.dist_dec = 0 * u.arcsec 

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

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

283 self.quad_stars_pixel_positions = self.get_quad_stars_pixel_positions() 

284 

285 def get_target_pixel_position(self): 

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

287 The object proper motion is taken into account. 

288 

289 Returns 

290 ------- 

291 target_x: float 

292 The target position along the x axis. 

293 target_y: float 

294 The target position along the y axis. 

295 

296 Examples 

297 -------- 

298 

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

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

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

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

303 743... 683... 

304 

305 """ 

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

307 self.target_radec_position_after_pm.dec, 0) 

308 return target_x, target_y 

309 

310 def get_gaia_pixel_positions(self, gaia_index=None): 

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

312 The star proper motions are taken into account. 

313 

314 Parameters 

315 ---------- 

316 gaia_index: array_like, optional 

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

318 

319 Returns 

320 ------- 

321 gaia_x: array_like 

322 The Gaia star positions along the x axis. 

323 gaia_y: array_like 

324 The Gaia star positions along the y axis. 

325 

326 Examples 

327 -------- 

328 

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

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

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

332 

333 or with selected Gaia index: 

334 

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

336 

337 .. doctest: 

338 :hide: 

339 

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

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

342 

343 """ 

344 if gaia_index is None: 

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

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

347 else: 

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

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

350 return gaia_x, gaia_y 

351 

352 def get_quad_stars_pixel_positions(self): 

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

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

355 At least 4 stars should be present. 

356 

357 Returns 

358 ------- 

359 quad_star_positions: array_like 

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

361 

362 Examples 

363 -------- 

364 

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

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

367 >>> quad_stars = a.get_quad_stars_pixel_positions() 

368 

369 .. doctest: 

370 :hide: 

371 

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

373 

374 """ 

375 coords = [] 

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

377 for line in f: 

378 if 'field_xy' in line: 

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

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

381 f.close() 

382 if len(coords) < 4: 

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

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

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

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

387 self.quad_stars_pixel_positions = np.array(coords) 

388 return self.quad_stars_pixel_positions 

389 

390 def load_sources_from_file(self): 

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

392 

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

394 source file if it exists. 

395 

396 Returns 

397 ------- 

398 sources: Table 

399 The table of detected sources. 

400 

401 Examples 

402 -------- 

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

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

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

406 <Table length=... 

407 

408 """ 

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

410 sources = Table.read(self.sources_file_name) 

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

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

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

414 self.sources = sources 

415 return sources 

416 

417 def load_gaia_catalog_around_target(self): 

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

419 

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

421 

422 Returns 

423 ------- 

424 gaia_catalog: Table 

425 The table of Gaia stars around the target position. 

426 

427 Examples 

428 -------- 

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

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

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

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

433 INFO: Query finished... 

434 

435 """ 

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

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

438 radius *= parameters.CCD_PIXEL2ARCSEC * u.arcsec 

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

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

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

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

443 return self.gaia_catalog 

444 

445 def write_sources(self): 

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

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

448 

449 """ 

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

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

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

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

454 hdu = fits.BinTableHDU.from_columns(coldefs) 

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

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

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

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

459 

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

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

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

463 

464 Parameters 

465 ---------- 

466 ax: Axes, optional 

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

468 sources: Table, optional 

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

470 gaia_coord: SkyCoord, optional 

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

472 quad: array_like, optional 

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

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

475 center: array_like, optional 

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

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

478 label: str, optional 

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

480 margin: int, optional 

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

482 scale: str, optional 

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

484 vmax: float, optional 

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

486 

487 Examples 

488 -------- 

489 

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

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

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

493 ... quad=a.quad_stars_pixel_positions, 

494 ... label=a.target.label) 

495 

496 .. plot: 

497 :hide: 

498 

499 from spectractor.astrometry import Astrometry 

500 

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

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

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

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

505 label=a.target.label) 

506 

507 """ 

508 no_plot = False 

509 if ax is None: 

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

511 if self.wcs is not None: 

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

513 ax = plt.gca() 

514 else: 

515 no_plot = True 

516 

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

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

519 ax.set_xlabel('RA') 

520 ax.set_ylabel('Dec') 

521 if sources is not None: 

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

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

524 if gaia_coord is not None: 

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

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

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

528 if center is None: 

529 target_x, target_y = self.get_target_pixel_position() 

530 else: 

531 target_x, target_y = center 

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

533 if quad is not None: 

534 if len(quad) > 3: 

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

536 hull = ConvexHull(points) 

537 for simplex in hull.simplices: 

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

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

540 else: 

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

542 ax.legend() 

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

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

545 if not no_plot and parameters.DISPLAY: 

546 # fig.tight_layout() 

547 plt.show() 

548 if parameters.PdfPages: 

549 parameters.PdfPages.savefig() 

550 else: 

551 plt.close("all") 

552 

553 def get_sources_radec_positions(self): 

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

555 

556 Returns 

557 ------- 

558 coords: SkyCoord 

559 The RA,DEC positions 

560 

561 Examples 

562 -------- 

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

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

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

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

567 

568 """ 

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

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

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

572 return self.sources_radec_positions 

573 

574 def match_sources_to_gaia_catalog(self, gaia_coord=None): 

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

576 

577 Parameters 

578 ---------- 

579 gaia_coord: SkyCoord, optional 

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

581 

582 Returns 

583 ------- 

584 gaia_index: array_like 

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

586 dist_2d: Angle 

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

588 dist_ra: Angle 

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

590 dist_ra: Angle 

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

592 

593 Examples 

594 -------- 

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

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

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

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

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

600 ... gaia_coord=a.gaia_radec_positions_after_pm) 

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

602 [0d00... 0d00m00... 0d00m00...] 

603 

604 """ 

605 if gaia_coord is None: 

606 gaia_coord = self.gaia_radec_positions_after_pm 

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

608 matches = gaia_coord[self.gaia_index] 

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

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

611 

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

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

614 

615 Parameters 

616 ---------- 

617 vmax: float, optional 

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

619 margin: int, optional 

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

621 

622 Examples 

623 -------- 

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

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

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

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

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

629 ... gaia_coord=a.gaia_radec_positions_after_pm) 

630 >>> a.plot_astrometry_shifts() 

631 

632 .. plot: 

633 :hide: 

634 

635 from spectractor.astrometry import Astrometry 

636 

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

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

639 a.load_gaia_catalog_around_target() # doctest: +ELLIPSIS 

640 a.load_sources_from_file() # doctest: +ELLIPSIS 

641 a.get_sources_radec_positions() # doctest: +ELLIPSIS 

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

643 gaia_coord=a.gaia_radec_positions_after_pm) 

644 a.plot_astrometry_shifts() 

645 """ 

646 target_x, target_y = self.get_target_pixel_position() 

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

648 

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

650 

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

652 

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

654 plt.xlabel('RA') 

655 plt.ylabel('Dec') 

656 if self.sources is not None: 

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

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

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

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

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

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

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

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

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

666 plt.legend() 

667 

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

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

670 plt.xlabel('RA') 

671 plt.ylabel('Dec') 

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

673 if self.sources is not None: 

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

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

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

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

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

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

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

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

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

683 plt.legend() 

684 if parameters.DISPLAY: 

685 # fig.tight_layout() 

686 plt.show() 

687 if parameters.PdfPages: 

688 parameters.PdfPages.savefig() 

689 else: 

690 plt.close("all") 

691 

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

693 max_sep=1 * u.arcsec): 

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

695 

696 Parameters 

697 ---------- 

698 min_stars: int 

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

700 flux_log10_threshold: 

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

702 min_range: 

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

704 max_range 

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

706 max_sep 

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

708 

709 Returns 

710 ------- 

711 indices: array_like 

712 Boolean array of selected sources. 

713 

714 """ 

715 sep = self.dist_2d < max_sep 

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

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

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

719 if np.sum(sep) > min_stars: 

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

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

722 < r * u.arcmin 

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

724 break 

725 else: 

726 sep *= range_constraint 

727 return sep 

728 

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

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

731 The median of the distances is overplotted. 

732 

733 Parameters 

734 ---------- 

735 matches: SkyCoord 

736 Array of sky coordinates of the detected sources. 

737 dra: Angle 

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

739 ddec 

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

741 

742 Examples 

743 -------- 

744 

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

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

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

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

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

750 ... gaia_coord=a.gaia_radec_positions_after_pm) 

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

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

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

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

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

756 

757 .. plot: 

758 :hide: 

759 

760 from spectractor.astrometry import Astrometry 

761 

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

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

764 a.load_gaia_catalog_around_target() 

765 a.load_sources_from_file() 

766 a.get_sources_radec_positions() 

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

768 gaia_coord=a.gaia_radec_positions_after_pm) 

769 sep_constraints = a.set_constraints(flux_log10_threshold=0.1) 

770 sources_selection = a.sources_radec_positions[sep_constraints] 

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

772 dra, ddec = sources_selection.spherical_offsets_to(gaia_matches) 

773 a.plot_shifts_profiles(gaia_matches, dra, ddec) 

774 

775 

776 """ 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

796 ax[0].grid() 

797 ax[1].grid() 

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

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

800 ax[0].legend() 

801 ax[1].legend() 

802 if parameters.DISPLAY: 

803 plt.show() 

804 if parameters.PdfPages: 

805 parameters.PdfPages.savefig() 

806 

807 def merge_wcs_with_new_exposure(self, log_file=None): 

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

809 

810 Parameters 

811 ---------- 

812 log_file: file, optional 

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

814 

815 """ 

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

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

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

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

820 if log_file is not None: 

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

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

823 

824 def compute_gaia_pixel_residuals(self): 

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

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

827 

828 Returns 

829 ------- 

830 gaia_residuals: array_like 

831 2D array of the pixel residuals. 

832 

833 Examples 

834 -------- 

835 

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

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

838 >>> residuals = a.compute_gaia_pixel_residuals() 

839 

840 .. doctest: 

841 :hide: 

842 

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

844 

845 """ 

846 coords = self.quad_stars_pixel_positions.T 

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

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

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

850 matches = self.gaia_radec_positions_after_pm[gaia_index] 

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

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

853 return self.gaia_residuals 

854 

855 def find_quad_star_index_in_sources(self, quad_star): 

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

857 

858 Parameters 

859 ---------- 

860 quad_star: array_like 

861 (x, y) positions of a quad star 

862 

863 Returns 

864 ------- 

865 index: int 

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

867 

868 Examples 

869 -------- 

870 

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

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

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

874 <Table length=... 

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

876 

877 """ 

878 eps = 1e-1 

879 k = -1 

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

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

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

883 break 

884 return k 

885 

886 def remove_worst_quad_star_from_sources(self): 

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

888 and the associated Gaia star position. 

889 

890 Examples 

891 -------- 

892 

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

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

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

896 <Table length=... 

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

898 >>> a.remove_worst_quad_star_from_sources() 

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

900 

901 """ 

902 gaia_pixel_residuals = self.compute_gaia_pixel_residuals() 

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

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

905 worst_source_index = \ 

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

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

908 self.sources.remove_row(worst_source_index) 

909 

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

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

912 

913 Parameters 

914 ---------- 

915 margin: int, optional 

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

917 scale: str, optional 

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

919 

920 Examples 

921 -------- 

922 

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

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

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

926 <Table length=... 

927 >>> a.plot_quad_stars() 

928 

929 """ 

930 nquads = self.quad_stars_pixel_positions.shape[0] 

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

932 for k in range(nquads): 

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

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

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

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

937 margin=margin, scale=scale, sources=self.sources, 

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

939 quad=self.quad_stars_pixel_positions) 

940 ax[k].set_title( 

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

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

943 if parameters.DISPLAY: 

944 fig.tight_layout() 

945 plt.show() 

946 if parameters.PdfPages: 

947 parameters.PdfPages.savefig() 

948 

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

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

951 

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

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

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

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

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

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

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

959 

960 Parameters 

961 ---------- 

962 extent: 2-tuple 

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

964 sources: Table 

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

966 

967 Notes 

968 ----- 

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

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

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

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

973 

974 See Also 

975 -------- 

976 

977 source_detection() 

978 

979 Examples 

980 -------- 

981 

982 >>> import os 

983 >>> from spectractor.logbook import LogBook 

984 >>> from spectractor.astrometry import Astrometry 

985 >>> from spectractor import parameters 

986 >>> parameters.VERBOSE = True 

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

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

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

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

991 >>> for file_name in file_names: 

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

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

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

995 ... continue 

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

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

998 WCS ... 

999 

1000 .. doctest: 

1001 :hide: 

1002 

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

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

1005 

1006 """ 

1007 # crop data 

1008 if extent is not None: 

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

1010 else: 

1011 data = np.copy(self.data) 

1012 if sources is None: 

1013 # remove background 

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

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

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

1017 # extract source positions and fluxes 

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

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

1020 if extent is not None: 

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

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

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

1024 else: 

1025 self.sources = sources 

1026 # write results in fits file 

1027 self.write_sources() 

1028 # run astrometry.net 

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

1030 f"--scale-low {0.999 * parameters.CCD_PIXEL2ARCSEC} " \ 

1031 f"--scale-high {1.001 * parameters.CCD_PIXEL2ARCSEC} " \ 

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

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

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

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

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

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

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

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

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

1041 # save new WCS in original fits file 

1042 # self.merge_wcs_with_new_exposure(log_file=log_file) 

1043 log_file.close() 

1044 

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

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

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

1048 hdu = fits.open(self.wcs_file_name) 

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

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

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

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

1053 

1054 # load quad stars 

1055 self.quad_stars_pixel_positions = self.get_quad_stars_pixel_positions() 

1056 

1057 # load WCS 

1058 self.wcs = load_wcs_from_file(self.wcs_file_name) 

1059 return self.wcs 

1060 

1061 # noinspection PyUnresolvedReferences 

1062 def run_gaia_astrometry(self): 

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

1064 

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

1066 

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

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

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

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

1071 

1072 Examples 

1073 -------- 

1074 

1075 >>> import os 

1076 >>> from spectractor.logbook import LogBook 

1077 >>> from spectractor import parameters 

1078 >>> parameters.VERBOSE = True 

1079 >>> parameters.DEBUG = True 

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

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

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

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

1084 >>> for file_name in file_names: 

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

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

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

1088 ... continue 

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

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

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

1092 WCS ... 

1093 

1094 .. doctest: 

1095 :hide: 

1096 

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

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

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

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

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

1102 

1103 """ 

1104 # load detected sources 

1105 if self.sources is None: 

1106 self.sources = self.load_sources_from_file() 

1107 # load WCS if absent 

1108 if self.wcs is None: 

1109 self.wcs = load_wcs_from_file(self.wcs_file_name) 

1110 self.sources_radec_positions = self.get_sources_radec_positions() 

1111 

1112 # load the Gaia catalog 

1113 if self.gaia_catalog is None: 

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

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

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

1117 else: 

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

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

1120 radius *= parameters.CCD_PIXEL2ARCSEC * u.arcsec 

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

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

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

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

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

1126 

1127 # update coordinates with proper motion data 

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

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

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

1131 if parameters.DEBUG: 

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

1133 quad=self.quad_stars_pixel_positions, margin=1000, 

1134 label=self.target.label) 

1135 

1136 # compute shifts 

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

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

1139 self.match_sources_to_gaia_catalog(self.gaia_radec_positions_after_pm) 

1140 if parameters.DEBUG: 

1141 self.plot_astrometry_shifts(vmax=3) 

1142 

1143 # select the brightest and closest stars with minimal shift 

1144 if len(self.sources) > 50: 

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

1146 else: 

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

1148 sep_constraints = self.set_constraints(flux_log10_threshold=flux_log10_threshold) 

1149 sources_selection = self.sources_radec_positions[sep_constraints] 

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

1151 dra, ddec = sources_selection.spherical_offsets_to(gaia_matches) 

1152 

1153 # compute statistics 

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

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

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

1157 if parameters.DEBUG: 

1158 plot_shifts_histograms(dra, ddec) 

1159 self.plot_shifts_profiles(gaia_matches, dra, ddec) 

1160 

1161 # update WCS 

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

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

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

1165 # #astropy.coordinates.SkyCoord.spherical_offsets_to) 

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

1167 total_shift = np.array( 

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

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

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

1171 # if parameters.DEBUG: 

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

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

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

1175 

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

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

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

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

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

1181 hdu = fits.open(self.wcs_file_name) 

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

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

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

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

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

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

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

1189 

1190 # check histogram medians 

1191 self.wcs = load_wcs_from_file(self.wcs_file_name) 

1192 self.get_sources_radec_positions() 

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

1194 self.match_sources_to_gaia_catalog(self.gaia_radec_positions_after_pm) 

1195 sep_constraints = self.set_constraints(flux_log10_threshold=flux_log10_threshold) 

1196 sources_selection = self.sources_radec_positions[sep_constraints] 

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

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

1199 

1200 # update values 

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

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

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

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

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

1206 hdu = fits.open(self.wcs_file_name) 

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

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

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

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

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

1212 

1213 # if parameters.DEBUG: 

1214 # plot_shifts_histograms(dra, ddec) 

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

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

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

1218 return dra, ddec 

1219 

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

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

1222 astrometry.net fitter. 

1223 

1224 This function runs alternatively the run_simple_astrometry and the run_gaia_astrometry. 

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

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

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

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

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

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

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

1232 

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

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

1235 

1236 Parameters 

1237 ---------- 

1238 extent: array_like, optional 

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

1240 maxiter: int, optional 

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

1242 

1243 Returns 

1244 ------- 

1245 min_gaia_residuals_quad_sum: float 

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

1247 

1248 Examples 

1249 -------- 

1250 

1251 >>> import os 

1252 >>> from spectractor.logbook import LogBook 

1253 >>> from spectractor import parameters 

1254 >>> parameters.VERBOSE = True 

1255 >>> parameters.DEBUG = True 

1256 >>> radius = 100 

1257 >>> maxiter = 10 

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

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

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

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

1262 >>> for file_name in file_names: 

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

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

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

1266 ... continue 

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

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

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

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

1271 iter target_x ... 

1272 

1273 .. doctest: 

1274 :hide: 

1275 

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

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

1278 >>> assert a.data is not None 

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

1280 >>> assert gaia_min_residuals < 0.8 

1281 

1282 """ 

1283 

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

1285 "gaia_residuals_abs_sum_y", "gaia_residuals_quad_sum"]) 

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

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

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

1289 sources_list = [] 

1290 for k in range(maxiter): 

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

1292 try: 

1293 # find a simple astrometric solution using astrometry.net 

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

1295 # refine with Gaia catalog 

1296 for i in range(maxiter): 

1297 dra, ddec = self.run_gaia_astrometry() 

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

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

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

1301 break 

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

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

1304 gaia_residuals = self.compute_gaia_pixel_residuals() 

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

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

1307 if parameters.DEBUG: 

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

1309 quad=self.quad_stars_pixel_positions, 

1310 label=self.target.label) 

1311 self.plot_astrometry_shifts(vmax=3) 

1312 self.plot_quad_stars() 

1313 target_x, target_y = self.get_target_pixel_position() 

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

1315 self.remove_worst_quad_star_from_sources() 

1316 except FileNotFoundError or TimeoutError: 

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

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

1319 k -= 1 

1320 break 

1321 t.pprint_all() 

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

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

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

1325 self.run_gaia_astrometry() 

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

1327 if parameters.DEBUG: 

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

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

1330 self.plot_quad_stars() 

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

1332 

1333 

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

1335 import doctest 

1336 

1337 doctest.testmod()