Coverage for spectractor/simulation/image_simulation.py: 14%

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

274 statements  

1from spectractor import parameters 

2from spectractor.config import set_logger 

3from spectractor.tools import (pixel_rotation, set_wcs_file_name, set_sources_file_name, 

4 set_gaia_catalog_file_name, load_wcs_from_file, ensure_dir, 

5 plot_image_simple) 

6from spectractor.extractor.images import Image, find_target 

7from spectractor.astrometry import get_gaia_coords_after_proper_motion, source_detection 

8from spectractor.extractor.background import remove_image_background_sextractor 

9from spectractor.simulation.throughput import TelescopeTransmission 

10from spectractor.simulation.simulator import SpectrogramSimulatorCore, SimulatorInit 

11from spectractor.extractor.psf import PSF 

12 

13from astropy.io import fits, ascii 

14import astropy.units as units 

15from astropy.coordinates import SkyCoord 

16from astropy.table import Table 

17from scipy.signal import fftconvolve, gaussian 

18import matplotlib.pyplot as plt 

19from matplotlib.ticker import MaxNLocator 

20import numpy as np 

21import copy 

22import os 

23 

24 

25class StarModel: 

26 """Class to model a star in the image simulation process. 

27 

28 Attributes 

29 ---------- 

30 x0: float 

31 X position of the star centroid in pixels. 

32 y0: float 

33 Y position of the star centroid in pixels. 

34 amplitude: amplitude 

35 The amplitude of the star in image units. 

36 """ 

37 

38 def __init__(self, centroid_coords, psf, amplitude): 

39 """Create a StarModel instance. 

40 

41 The model is based on an Astropy Fittable2DModel. The centroid and amplitude 

42 parameters of the given model are updated by the dedicated arguments. 

43 

44 Parameters 

45 ---------- 

46 centroid_coords: array_like 

47 Tuple of (x,y) coordinates of the desired star centroid in pixels. 

48 psf: PSF 

49 PSF model 

50 amplitude: float 

51 The desired amplitude of the star in image units. 

52 

53 Examples 

54 -------- 

55 >>> from spectractor.extractor.psf import Moffat 

56 >>> p = (100, 50, 50, 5, 2, 200) 

57 >>> psf = Moffat(p) 

58 >>> s = StarModel((20, 10), psf, 200) 

59 >>> s.plot_model() 

60 >>> s.x0 

61 20 

62 >>> s.y0 

63 10 

64 >>> s.amplitude 

65 200 

66 """ 

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

68 self.x0 = centroid_coords[0] 

69 self.y0 = centroid_coords[1] 

70 self.amplitude = amplitude 

71 # self.target = target 

72 self.psf = copy.deepcopy(psf) 

73 self.psf.p[1] = self.x0 

74 self.psf.p[2] = self.y0 

75 self.psf.p[0] = amplitude 

76 # to be realistic, usually fitted fwhm is too big, divide gamma by 2 

77 self.fwhm = self.psf.p[3] 

78 # self.sigma = self.model.stddev / 2 

79 

80 def plot_model(self): 

81 """ 

82 Plot the star model. 

83 """ 

84 x = np.arange(self.x0 - 5 * self.fwhm, self.x0 + 5 * self.fwhm) 

85 y = np.arange(self.y0 - 5 * self.fwhm, self.y0 + 5 * self.fwhm) 

86 xx, yy = np.meshgrid(x, y) 

87 star = self.psf.evaluate(np.array([xx, yy])) 

88 fig, ax = plt.subplots(1, 1) 

89 plot_image_simple(ax, star, title=f'Star model: A={self.amplitude:.2f}, fwhm={self.fwhm:.2f}', 

90 units='Arbitrary units') 

91 if parameters.DISPLAY: 

92 plt.show() 

93 if parameters.PdfPages: 

94 parameters.PdfPages.savefig() 

95 

96 

97class StarFieldModel: 

98 

99 def __init__(self, base_image, flux_factor=1): 

100 """ 

101 Examples 

102 -------- 

103 

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

105 >>> im = Image('tests/data/reduc_20170530_134.fits', target_label="HD111980") 

106 >>> x0, y0 = find_target(im, guess=(740, 680), use_wcs=False) 

107 >>> s = StarFieldModel(im) 

108 >>> s.plot_model() 

109 

110 """ 

111 self.image = base_image 

112 self.target = base_image.target 

113 self.field = None 

114 self.stars = [] 

115 self.pixcoords = [] 

116 self.fwhm = base_image.target_star2D.p[3] 

117 self.flux_factor = flux_factor 

118 self.set_star_list() 

119 

120 # noinspection PyUnresolvedReferences 

121 def set_star_list(self): 

122 x0, y0 = self.image.target_pixcoords 

123 sources_file_name = set_sources_file_name(self.image.file_name) 

124 if os.path.isfile(sources_file_name): 

125 # load sources positions and flux 

126 sources = Table.read(sources_file_name) 

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

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

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

130 # test presence of WCS and gaia catalog files 

131 wcs_file_name = set_wcs_file_name(self.image.file_name) 

132 gaia_catalog_file_name = set_gaia_catalog_file_name(self.image.file_name) 

133 if os.path.isfile(wcs_file_name) and os.path.isfile(gaia_catalog_file_name): 

134 # load gaia catalog 

135 gaia_catalog = ascii.read(gaia_catalog_file_name, format="ecsv") 

136 gaia_coord_after_motion = get_gaia_coords_after_proper_motion(gaia_catalog, self.image.date_obs) 

137 # load WCS 

138 wcs = load_wcs_from_file(wcs_file_name) 

139 # catalog matching to set star positions using Gaia 

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

141 sources_coord = SkyCoord(ra=sources_coord[0] * units.deg, dec=sources_coord[1] * units.deg, 

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

143 gaia_index, dist_2d, dist_3d = sources_coord.match_to_catalog_sky(gaia_coord_after_motion) 

144 for k, gaia_i in enumerate(gaia_index): 

145 x, y = wcs.all_world2pix(gaia_coord_after_motion[gaia_i].ra, gaia_coord_after_motion[gaia_i].dec, 0) 

146 A = sources['flux'][k] * self.flux_factor 

147 self.stars.append(StarModel([x, y], self.image.target_star2D, A)) 

148 self.pixcoords.append([x, y]) 

149 else: 

150 for k, source in enumerate(sources): 

151 x, y = sources['xcentroid'][k], sources['ycentroid'][k] 

152 A = sources['flux'][k] * self.flux_factor 

153 self.stars.append(StarModel([x, y], self.image.target_star2D, A)) 

154 self.pixcoords.append([x, y]) 

155 else: 

156 # mask background, faint stars, and saturated pixels 

157 data = np.copy(self.image.data) 

158 # self.saturation = 0.99 * parameters.CCD_MAXADU / base_image.expo 

159 # self.saturated_pixels = np.where(image_thresholded > self.saturation) 

160 # image_thresholded[self.saturated_pixels] = 0. 

161 # image_thresholded -= threshold 

162 # image_thresholded[np.where(image_thresholded < 0)] = 0. 

163 # mask order0 and spectrum 

164 margin = 30 

165 mask = np.zeros(data.shape, dtype=bool) 

166 for y in range(int(y0) - 100, int(y0) + 100): 

167 for x in range(parameters.CCD_IMSIZE): 

168 u, v = pixel_rotation(x, y, self.image.disperser.theta([x0, y0]) * np.pi / 180., x0, y0) 

169 if margin > v > -margin: 

170 mask[y, x] = True 

171 # remove background and detect sources 

172 data_wo_bkg = remove_image_background_sextractor(data) 

173 sources = source_detection(data_wo_bkg, mask=mask) 

174 for k, source in enumerate(sources): 

175 x, y = sources['xcentroid'][k], sources['ycentroid'][k] 

176 A = sources['flux'][k] * self.flux_factor 

177 self.stars.append(StarModel([x, y], self.image.target_star2D, A)) 

178 self.pixcoords.append([x, y]) 

179 self.pixcoords = np.array(self.pixcoords).T 

180 

181 def model(self, x, y): 

182 if self.field is None: 

183 window = int(20 * self.fwhm) 

184 self.field = self.stars[0].psf.evaluate(np.array([x, y])) 

185 for k in range(1, len(self.stars)): 

186 left = max(0, int(self.pixcoords[0][k]) - window) 

187 right = min(parameters.CCD_IMSIZE, int(self.pixcoords[0][k]) + window) 

188 low = max(0, int(self.pixcoords[1][k]) - window) 

189 up = min(parameters.CCD_IMSIZE, int(self.pixcoords[1][k]) + window) 

190 yy, xx = np.mgrid[low:up, left:right] 

191 self.field[low:up, left:right] += self.stars[k].psf.evaluate(np.array([xx, yy])) 

192 return self.field 

193 

194 def plot_model(self): 

195 xx, yy = np.mgrid[0:parameters.CCD_IMSIZE:1, 0:parameters.CCD_IMSIZE:1] 

196 starfield = self.model(xx, yy) 

197 fig, ax = plt.subplots(1, 1) 

198 plot_image_simple(ax, starfield, scale="log10", target_pixcoords=self.pixcoords) 

199 # im = plt.imshow(starfield, origin='lower', cmap='jet') 

200 # ax.grid(color='white', ls='solid') 

201 # ax.grid(True) 

202 # ax.set_xlabel('X [pixels]') 

203 # ax.set_ylabel('Y [pixels]') 

204 # ax.set_title(f'Star field model: fwhm={self.fwhm.value:.2f}') 

205 # cb = plt.colorbar(im, ax=ax) 

206 # cb.formatter.set_powerlimits((0, 0)) 

207 # cb.locator = MaxNLocator(7, prune=None) 

208 # cb.update_ticks() 

209 # cb.set_label('Arbitrary units') # ,fontsize=16) 

210 if parameters.DISPLAY: 

211 plt.show() 

212 if parameters.PdfPages: 

213 parameters.PdfPages.savefig() 

214 

215 

216class BackgroundModel: 

217 """Class to model the background of the simulated image. 

218 

219 The background model size is set with the parameters.CCD_IMSIZE global keyword. 

220 

221 Attributes 

222 ---------- 

223 level: float 

224 The mean level of the background in image units. 

225 frame: array_like 

226 (x, y, smooth) right and upper limits in pixels of a vignetting frame, 

227 and the smoothing gaussian width (default: None). 

228 """ 

229 

230 def __init__(self, level, frame=None): 

231 """Create a BackgroundModel instance. 

232 

233 The background model size is set with the parameters.CCD_IMSIZE global keyword. 

234 

235 Parameters 

236 ---------- 

237 level: float 

238 The mean level of the background in image units. 

239 frame: array_like, None 

240 (x, y, smooth) right and upper limits in pixels of a vignetting frame, 

241 and the smoothing gaussian width (default: None). 

242 

243 Examples 

244 -------- 

245 >>> from spectractor import parameters 

246 >>> parameters.CCD_IMSIZE = 200 

247 >>> bgd = BackgroundModel(10) 

248 >>> model = bgd.model() 

249 >>> np.all(model==10) 

250 True 

251 >>> model.shape 

252 (200, 200) 

253 >>> bgd = BackgroundModel(10, frame=(160, 180, 3)) 

254 >>> bgd.plot_model() 

255 """ 

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

257 self.level = level 

258 if self.level <= 0: 

259 self.my_logger.warning('\n\tBackground level must be strictly positive.') 

260 else: 

261 self.my_logger.info(f'\n\tBackground set to {level:.3f} ADU/s.') 

262 self.frame = frame 

263 

264 def model(self): 

265 """Compute the background model for the image simulation in image units. 

266 

267 A shadowing vignetting frame is roughly simulated if self.frame is set. 

268 The background model size is set with the parameters.CCD_IMSIZE global keyword. 

269 

270 Returns 

271 ------- 

272 bkgd: array_like 

273 The array of the background model. 

274 

275 """ 

276 yy, xx = np.mgrid[0:parameters.CCD_IMSIZE:1, 0:parameters.CCD_IMSIZE:1] 

277 bkgd = self.level * np.ones_like(xx) 

278 if self.frame is None: 

279 return bkgd 

280 else: 

281 xlim, ylim, width = self.frame 

282 bkgd[ylim:, :] = self.level / 100 

283 bkgd[:, xlim:] = self.level / 100 

284 kernel = np.outer(gaussian(parameters.CCD_IMSIZE, width), gaussian(parameters.CCD_IMSIZE, width)) 

285 bkgd = fftconvolve(bkgd, kernel, mode='same') 

286 bkgd *= self.level / bkgd[parameters.CCD_IMSIZE // 2, parameters.CCD_IMSIZE // 2] 

287 return bkgd 

288 

289 def plot_model(self): 

290 """Plot the background model. 

291 

292 """ 

293 bkgd = self.model() 

294 fig, ax = plt.subplots(1, 1) 

295 im = plt.imshow(bkgd, origin='lower', cmap='jet') 

296 ax.grid(color='white', ls='solid') 

297 ax.grid(True) 

298 ax.set_xlabel('X [pixels]') 

299 ax.set_ylabel('Y [pixels]') 

300 ax.set_title('Background model') 

301 cb = plt.colorbar(im, ax=ax) 

302 cb.formatter.set_powerlimits((0, 0)) 

303 cb.locator = MaxNLocator(7, prune=None) 

304 cb.update_ticks() 

305 cb.set_label('Arbitrary units') # ,fontsize=16) 

306 if parameters.DISPLAY: 

307 plt.show() 

308 if parameters.PdfPages: 

309 parameters.PdfPages.savefig() 

310 

311 

312class ImageModel(Image): 

313 

314 def __init__(self, filename, target_label=None): 

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

316 Image.__init__(self, filename, target_label=target_label) 

317 self.true_lambdas = None 

318 self.true_spectrum = None 

319 

320 def compute(self, star, background, spectrogram, starfield=None): 

321 yy, xx = np.mgrid[0:parameters.CCD_IMSIZE:1, 0:parameters.CCD_IMSIZE:1] 

322 self.data = star.psf.evaluate(np.array([xx, yy])) + background.model() 

323 if spectrogram.full_image: 

324 self.data[spectrogram.spectrogram_ymin:spectrogram.spectrogram_ymax, :] += spectrogram.data 

325 else: 

326 self.data[spectrogram.spectrogram_ymin:spectrogram.spectrogram_ymax, 

327 spectrogram.spectrogram_xmin:spectrogram.spectrogram_xmax] += spectrogram.data 

328 # - spectrogram.spectrogram_bgd) 

329 if starfield is not None: 

330 self.data += starfield.model(xx, yy) 

331 

332 def add_poisson_and_read_out_noise(self): 

333 if self.units != 'ADU': 

334 raise AttributeError('Poisson noise procedure has to be applied on map in ADU units') 

335 d = np.copy(self.data).astype(float) 

336 # convert to electron counts 

337 d *= self.gain 

338 # Poisson noise 

339 noisy = np.random.poisson(d).astype(float) 

340 # Add read-out noise is available 

341 if self.read_out_noise is not None: 

342 noisy += np.random.normal(scale=self.read_out_noise) 

343 # reconvert to ADU 

344 self.data = noisy / self.gain 

345 # removes zeros 

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

347 self.data[self.data <= 0] = min_noz 

348 

349 def save_image(self, output_filename, overwrite=False): 

350 hdu0 = fits.PrimaryHDU() 

351 hdu0.data = self.data 

352 hdu0.header = self.header 

353 hdu1 = fits.ImageHDU() 

354 # hdu1.data = [self.true_lambdas, self.true_spectrum] 

355 hdulist = fits.HDUList([hdu0, hdu1]) 

356 hdulist.writeto(output_filename, overwrite=overwrite) 

357 self.my_logger.info('\n\tImage saved in %s' % output_filename) 

358 

359 def load_image(self, filename): 

360 super(ImageModel, self).load_image(filename) 

361 # hdu_list = fits.open(filename) 

362 # self.true_lambdas, self.true_spectrum = hdu_list[1].data 

363 

364 

365def ImageSim(image_filename, spectrum_filename, outputdir, pwv=5, ozone=300, aerosols=0.03, A1=1, A2=1, 

366 psf_poly_params=None, 

367 with_rotation=True, 

368 with_stars=True): 

369 """ The basic use of the extractor consists first to define: 

370 - the path to the fits image from which to extract the image, 

371 - the path of the output directory to save the extracted spectrum (created automatically if does not exist yet), 

372 - the rough position of the object in the image, 

373 - the name of the target (to search for the extra-atmospheric spectrum if available). 

374 Then different parameters and systematics can be set: 

375 - pwv: the pressure water vapor (in mm) 

376 - ozone: the ozone quantity (in XX) 

377 - aerosols: the vertical aerosol optical depth 

378 - A1: a global grey absorption parameter for the spectrum 

379 - A2: the relative amplitude of second order compared with first order 

380 - with_rotation: rotate the spectrum according to the disperser characteristics (True by default) 

381 - with_stars: include stars in the image field (True by default) 

382 """ 

383 my_logger = set_logger(__name__) 

384 my_logger.info(f'\n\tStart IMAGE SIMULATOR') 

385 # Load reduced image 

386 spectrum, telescope, disperser, target = SimulatorInit(spectrum_filename) 

387 image = ImageModel(image_filename, target_label=target.label) 

388 guess = np.array([spectrum.header['TARGETX'], spectrum.header['TARGETY']]) 

389 if "CCDREBIN" in spectrum.header: 

390 guess *= spectrum.header["CCDREBIN"] 

391 if parameters.DEBUG: 

392 image.plot_image(scale='symlog', target_pixcoords=guess) 

393 # Fit the star 2D profile 

394 my_logger.info('\n\tSearch for the target in the image...') 

395 target_pixcoords = find_target(image, guess, use_wcs=False) 

396 # Find the exact target position using WCS if available 

397 wcs_file_name = set_wcs_file_name(image.file_name) 

398 if os.path.isfile(wcs_file_name): 

399 target_pixcoords = find_target(image, guess, use_wcs=True) 

400 # Background model 

401 my_logger.info('\n\tBackground model...') 

402 bgd_level = float(np.mean(spectrum.spectrogram_bgd)) 

403 background = BackgroundModel(level=bgd_level, frame=None) # (1600, 1650, 100)) 

404 if parameters.DEBUG: 

405 background.plot_model() 

406 

407 # Target model 

408 my_logger.info('\n\tStar model...') 

409 # Spectrogram is simulated with spectrum.x0 target position: must be this position to simualte the target. 

410 star = StarModel(image.target_pixcoords, image.target_star2D, image.target_star2D.p[0]) 

411 # reso = star.fwhm 

412 if parameters.DEBUG: 

413 star.plot_model() 

414 # Star field model 

415 starfield = None 

416 if with_stars: 

417 my_logger.info('\n\tStar field model...') 

418 starfield = StarFieldModel(image) 

419 if parameters.DEBUG: 

420 image.plot_image(scale='symlog', target_pixcoords=starfield.pixcoords) 

421 starfield.plot_model() 

422 

423 # Spectrum model 

424 my_logger.info('\n\tSpectrum model...') 

425 airmass = image.header['AIRMASS'] 

426 pressure = image.header['OUTPRESS'] 

427 temperature = image.header['OUTTEMP'] 

428 telescope = TelescopeTransmission(image.filter_label) 

429 

430 # Rotation: useful only to fill the Dy_disp_axis column in PSF table 

431 if not with_rotation: 

432 rotation_angle = 0 

433 else: 

434 rotation_angle = spectrum.rotation_angle 

435 

436 # Load PSF 

437 if psf_poly_params is None: 

438 my_logger.info('\n\tUse PSF parameters from _table.csv file.') 

439 psf_poly_params = spectrum.chromatic_psf.from_table_to_poly_params() 

440 else: 

441 spectrum.chromatic_psf.deg = (len(psf_poly_params) - 1) // (len(spectrum.chromatic_psf.psf.param_names) - 2) - 1 

442 spectrum.chromatic_psf.set_polynomial_degrees(spectrum.chromatic_psf.deg) 

443 my_logger.info(f'\n\tUse PSF parameters {psf_poly_params} as polynoms of ' 

444 f'degree {spectrum.chromatic_psf.degrees}') 

445 

446 # Simulate spectrogram 

447 spectrogram = SpectrogramSimulatorCore(spectrum, telescope, disperser, airmass, pressure, 

448 temperature, pwv=pwv, ozone=ozone, aerosols=aerosols, A1=A1, A2=A2, 

449 D=spectrum.disperser.D, shift_x=0., shift_y=0., shift_t=0., B=1., 

450 psf_poly_params=psf_poly_params, angle=rotation_angle, with_background=False, 

451 fast_sim=False, full_image=True) 

452 

453 # now we include effects related to the wrong extraction of the spectrum: 

454 # wrong estimation of the order 0 position and wrong DISTANCE2CCD 

455 # distance = spectrum.chromatic_psf.get_algebraic_distance_along_dispersion_axis() 

456 # spectrum.disperser.D = parameters.DISTANCE2CCD 

457 # spectrum.lambdas = spectrum.disperser.grating_pixel_to_lambda(distance, spectrum.x0, order=1) 

458 

459 # Image model 

460 my_logger.info('\n\tImage model...') 

461 image.compute(star, background, spectrogram, starfield=starfield) 

462 

463 # Recover true spectrum 

464 spectrogram.set_true_spectrum(spectrogram.lambdas, ozone, pwv, aerosols, shift_t=0) 

465 true_lambdas = np.copy(spectrogram.true_lambdas) 

466 true_spectrum = np.copy(spectrogram.true_spectrum) 

467 

468 # Saturation effects 

469 saturated_pixels = np.where(spectrogram.data > image.saturation)[0] 

470 if len(saturated_pixels) > 0: 

471 my_logger.warning(f"\n\t{len(saturated_pixels)} saturated pixels detected above saturation " 

472 f"level at {image.saturation} ADU/s in the spectrogram." 

473 f"\n\tSpectrogram maximum is at {np.max(spectrogram.data)} ADU/s.") 

474 image.data[image.data > image.saturation] = image.saturation 

475 

476 # Convert data from ADU/s in ADU 

477 image.convert_to_ADU_units() 

478 

479 # Add Poisson and read-out noise 

480 image.add_poisson_and_read_out_noise() 

481 

482 # Round float ADU into closest integers 

483 # image.data = np.around(image.data) 

484 

485 # Plot 

486 if parameters.VERBOSE and parameters.DISPLAY: # pragma: no cover 

487 image.convert_to_ADU_rate_units() 

488 image.plot_image(scale="symlog", title="Image simulation", target_pixcoords=target_pixcoords, units=image.units) 

489 image.convert_to_ADU_units() 

490 

491 # Set output path 

492 ensure_dir(outputdir) 

493 output_filename = image_filename.split('/')[-1] 

494 output_filename = (output_filename.replace('reduc', 'sim')).replace('trim', 'sim') 

495 output_filename = os.path.join(outputdir, output_filename) 

496 

497 # Save images and parameters 

498 image.header['A1_T'] = A1 

499 image.header['A2_T'] = A2 

500 image.header['X0_T'] = spectrum.x0[0] 

501 image.header['Y0_T'] = spectrum.x0[1] 

502 image.header['D2CCD_T'] = spectrum.disperser.D 

503 image.header['OZONE_T'] = ozone 

504 image.header['PWV_T'] = pwv 

505 image.header['VAOD_T'] = aerosols 

506 image.header['ROT_T'] = rotation_angle 

507 image.header['ROTATION'] = int(with_rotation) 

508 image.header['STARS'] = int(with_stars) 

509 image.header['BKGD_LEV'] = background.level 

510 image.header['PSF_DEG'] = spectrum.spectrogram_deg 

511 image.header['PSF_TYPE'] = parameters.PSF_TYPE 

512 psf_poly_params_truth = np.array(psf_poly_params) 

513 if psf_poly_params_truth.size > spectrum.spectrogram_Nx: 

514 psf_poly_params_truth = psf_poly_params_truth[spectrum.spectrogram_Nx:] 

515 image.header['LBDAS_T'] = np.array_str(true_lambdas, max_line_width=1000000, precision=2) 

516 image.header['AMPLIS_T'] = np.array_str(true_spectrum, max_line_width=1000000, precision=2) 

517 image.header['PSF_P_T'] = np.array_str(psf_poly_params_truth, max_line_width=1000000, precision=4) 

518 image.save_image(output_filename, overwrite=True) 

519 return image 

520 

521 

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

523 import doctest 

524 

525 doctest.testmod() 

526 

527# 

528# if __name__ == "__main__": 

529# from spectractor.logbook import LogBook 

530# from argparse import ArgumentParser 

531# 

532# parser = ArgumentParser() 

533# parser.add_argument("-d", "--debug", dest="debug", action="store_true", 

534# help="Enter debug mode (more verbose and plots).", default=False) 

535# parser.add_argument("-v", "--verbose", dest="verbose", action="store_true", 

536# help="Enter verbose (print more stuff).", default=False) 

537# parser.add_argument("-o", "--output_directory", dest="output_directory", default="outputs/", 

538# help="Write results in given output directory (default: ./outputs/).") 

539# parser.add_argument("-l", "--logbook", dest="logbook", default="ctiofulllogbook_jun2017_v5.csv", 

540# help="CSV logbook file. (default: ctiofulllogbook_jun2017_v5.csv).") 

541# args = parser.parse_args() 

542# 

543# parameters.VERBOSE = args.verbose 

544# if args.debug: 

545# parameters.DEBUG = True 

546# parameters.VERBOSE = True 

547# 

548# file_names = ['tests/data/reduc_20170530_134.fits'] 

549# spectrum_file_name = 'outputs/reduc_20170530_134_spectrum.fits' 

550# # guess = [720, 670] 

551# # hologramme HoloAmAg 

552# psf_poly_params = [0.11298966008548948, -0.396825836448203, 0.2060387678061209, 2.0649268678546955, 

553# -1.3753936625491252, 0.9242067418613167, 1.6950153822467129, -0.6942452135351901, 

554# 0.3644178350759512, -0.0028059253333737044, -0.003111527339787137, -0.00347648933169673, 

555# 528.3594585697788, 628.4966480821147, 12.438043546369354, 499.99999999999835] 

556# # psf_poly_params = [0.11298966008548948, -0.396825836448203, 10.60387678061209, 2.0649268678546955, 

557# # -1.3753936625491252, 0.9242067418613167, 1.6950153822467129, -0.6942452135351901, 

558# # 0.3644178350759512, -0.0028059253333737044, -0.003111527339787137, -0.00347648933169673, 

559# # 528.3594585697788, 628.4966480821147, 12.438043546369354, 499.99999999999835] 

560# # file_name="../CTIOAnaJun2017/ana_31may17/OverScanRemove/trim_images/trim_20170531_150.fits" 

561# # guess = [840, 530] 

562# # target = "HD205905" 

563# # x = np.linspace(-1, 1, 100) 

564# # plt.plot(x, np.polynomial.legendre.legval(x, psf_poly_params[0:3])) 

565# # plt.show() 

566# logbook = LogBook(logbook=args.logbook) 

567# for file_name in file_names: 

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

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

570# if target is None or xpos is None or ypos is None: 

571# continue 

572# 

573# image = ImageSim(file_name, spectrum_file_name, args.output_directory, A1=1, A2=0.05, 

574# psf_poly_params=psf_poly_params, with_stars=False)