Coverage for spectractor/extractor/images.py: 7%
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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
1from astropy.coordinates import Angle, SkyCoord, Latitude
2from astropy.io import fits
3import astropy.units as units
4from scipy import ndimage
5from matplotlib import cm
6import matplotlib.pyplot as plt
7import numpy as np
8import os
9import copy
11from spectractor import parameters
12from spectractor.config import set_logger, load_config
13from spectractor.extractor.targets import load_target
14from spectractor.extractor.dispersers import Hologram
15from spectractor.extractor.psf import Moffat
16from spectractor.simulation.adr import hadec2zdpar
17from spectractor.simulation.throughput import TelescopeTransmission
18from spectractor.tools import (plot_image_simple, save_fits, load_fits, fit_poly1d, plot_compass_simple,
19 fit_poly1d_outlier_removal, weighted_avg_and_std,
20 fit_poly2d_outlier_removal, hessian_and_theta,
21 set_wcs_file_name, load_wcs_from_file, imgslice, rebin)
24class Image(object):
25 """ The image class contains all the features necessary to load an image and extract a spectrum.
27 Attributes
28 ----------
29 my_logger: logging
30 Logging object
31 file_name: str
32 The file name of the exposure.
33 units: str
34 Units of the image.
35 data: array
36 Image 2D array in self.units units.
37 stat_errors: array
38 Image 2D uncertainty array in self.units units.
39 target_pixcoords: array
40 Target position [x,y] in the image in pixels.
41 data_rotated: array
42 Rotated image 2D array in self.units units.
43 stat_errors_rotated: array
44 Rotated image 2D uncertainty array in self.units units.
45 target_pixcoords_rotated: array
46 Target position [x,y] in the rotated image in pixels.
47 date_obs: str
48 Date of the observation.
49 airmass: float
50 Airmass of the current target.
51 expo: float
52 Exposure time in seconds.
53 disperser_label: str
54 Label of the disperser.
55 filter_label: str
56 Label of the filter.
57 target_label: str:
58 Label of the current target.
59 rotation_angle: float
60 Dispersion axis angle in the image in degrees, positive if anticlockwise.
61 parallactic_angle: float
62 Parallactic angle in degrees.
63 header: Fits.Header
64 FITS file header.
65 disperser: Disperser
66 Disperser instance that describes the disperser.
67 target: Target
68 Target instance that describes the current target.
69 ra: float
70 Right ascension coordinate of the current exposure.
71 dec: float
72 Declination coordinate of the current exposure.
73 hour_angle: float
74 Hour angle coordinate of the current exposure.
75 temperature: float
76 Outside temperature in Celsius degrees.
77 pressure: float
78 Outside pressure in hPa.
79 humidity: float
80 Outside relative humidity in fraction of one.
81 saturation: float
82 Level of saturation in the image in image units.
83 target_star2D: PSF
84 PSF instance fitted on the current target.
85 target_bkgd2D: callable
86 Function that models the background behind the current target.
88 """
90 def __init__(self, file_name, *, target_label="", disperser_label="",
91 config="", **kwargs):
92 """
93 The image class contains all the features necessary to load an image and extract a spectrum.
95 Parameters
96 ----------
97 file_name: str
98 The file name where the image is.
99 target_label: str, optional
100 The target name, to be found in data bases.
101 disperser_label: str, optional
102 The disperser label to load its properties
103 config: str, optional
104 A config file name to load some parameter values for a given instrument (default: "").
106 Examples
107 --------
109 .. doctest::
111 >>> im = Image('tests/data/reduc_20170605_028.fits')
113 .. doctest::
114 :hide:
116 >>> assert im.file_name == 'tests/data/reduc_20170605_028.fits'
117 >>> assert im.data is not None and np.mean(im.data) > 0
118 >>> assert im.stat_errors is not None and np.mean(im.stat_errors) > 0
119 >>> assert im.header is not None
120 >>> assert im.gain is not None and np.mean(im.gain) > 0
122 """
123 self.my_logger = set_logger(self.__class__.__name__)
124 if config != "":
125 load_config(config)
126 if not os.path.isfile(file_name) and parameters.CALLING_CODE != 'LSST_DM':
127 raise FileNotFoundError(f"File {file_name} does not exist.")
128 self.file_name = file_name
129 self.units = 'ADU'
130 self.expo = -1
131 self.airmass = -1
132 self.date_obs = None
133 self.disperser = None
134 self.disperser_label = disperser_label
135 self.target_label = target_label
136 self.target_guess = None
137 self.filter_label = ""
138 self.filters = None
139 self.header = None
140 self.data = None
141 self.data_rotated = None
142 self.gain = None # in e-/ADU
143 self.read_out_noise = None
144 self.stat_errors = None
145 self.stat_errors_rotated = None
146 self.rotation_angle = 0
147 self.parallactic_angle = None
148 self.saturation = None
150 self.ra = None
151 self.dec = None
152 self.hour_angle = None
153 self.temperature = 0
154 self.pressure = 0
155 self.humidity = 0
157 if parameters.CALLING_CODE != 'LSST_DM':
158 self.load_image(file_name)
159 else:
160 # data provided by the LSST shim, just instantiate objects
161 # necessary for the following code not to fail
162 self.header = fits.header.Header()
163 self.filter_label = kwargs.get('filter_label', '')
164 # Load the target if given
165 self.target = None
166 self.target_pixcoords = None
167 self.target_pixcoords_rotated = None
168 self.target_bkgd2D = None
169 self.target_star2D = None
170 self.header['TARGET'] = self.target_label
171 self.header.comments['TARGET'] = 'name of the target in the image'
172 self.header['REDSHIFT'] = 0
173 self.header.comments['REDSHIFT'] = 'redshift of the target'
174 self.header["GRATING"] = self.disperser_label
175 self.header.comments["GRATING"] = "name of the disperser"
176 self.header['ROTANGLE'] = self.rotation_angle
177 self.header.comments["ROTANGLE"] = "[deg] angle of the dispersion axis"
178 self.header['D2CCD'] = parameters.DISTANCE2CCD
179 self.header.comments["D2CCD"] = "[mm] distance between disperser and CCD"
181 if self.filter_label != "" and "empty" not in self.filter_label.lower():
182 t = TelescopeTransmission(filter_label=self.filter_label)
183 t.reset_lambda_range(transmission_threshold=1e-4)
185 if self.target_label != "":
186 self.target = load_target(self.target_label, verbose=parameters.VERBOSE)
187 self.header['REDSHIFT'] = str(self.target.redshift)
189 def rebin(self):
190 """Rebin the image and reset some related parameters.
192 Examples
193 --------
194 >>> parameters.CCD_REBIN = 2
195 >>> im = Image('tests/data/reduc_20170605_028.fits')
196 >>> im.target_guess = [810, 590]
197 >>> im.data.shape
198 (2048, 2048)
199 >>> im.rebin()
200 >>> im.data.shape
201 (1024, 1024)
202 >>> im.stat_errors.shape
203 (1024, 1024)
204 >>> im.target_guess
205 array([405., 295.])
206 """
207 new_shape = np.asarray(self.data.shape) // parameters.CCD_REBIN
208 self.data = rebin(self.data, new_shape)
209 self.stat_errors = np.sqrt(rebin(self.stat_errors ** 2, new_shape))
210 if self.target_guess is not None:
211 self.target_guess = np.asarray(self.target_guess) / parameters.CCD_REBIN
213 def load_image(self, file_name):
214 """
215 Load the image and store some information from header in class attributes.
216 Then load the target and disperser properties. Called when an Image instance is created.
218 Parameters
219 ----------
220 file_name: str
221 The fits file name.
223 """
224 if parameters.OBS_NAME == 'CTIO':
225 load_CTIO_image(self)
226 elif parameters.OBS_NAME == 'LPNHE':
227 load_LPNHE_image(self)
228 if parameters.OBS_NAME == "AUXTEL":
229 load_AUXTEL_image(self)
230 # Load the disperser
231 self.my_logger.info(f'\n\tLoading disperser {self.disperser_label}...')
232 self.header["GRATING"] = self.disperser_label
233 self.header["AIRMASS"] = self.airmass
234 self.header["DATE-OBS"] = self.date_obs
235 self.header["EXPTIME"] = self.expo
236 self.header['OUTTEMP'] = self.temperature
237 self.header['OUTPRESS'] = self.pressure
238 self.header['OUTHUM'] = self.humidity
239 self.header['CCDREBIN'] = parameters.CCD_REBIN
241 self.disperser = Hologram(self.disperser_label, D=parameters.DISTANCE2CCD,
242 data_dir=parameters.DISPERSER_DIR, verbose=parameters.VERBOSE)
243 self.compute_statistical_error()
244 self.convert_to_ADU_rate_units()
246 def save_image(self, output_file_name, overwrite=False):
247 """Save the image in a fits file.
249 Parameters
250 ----------
251 output_file_name: str
252 The output file name.
253 overwrite: bool
254 If True, overwrite the file if it exists previously (default: False).
256 Examples
257 --------
258 >>> im = Image('tests/data/reduc_20170605_028.fits')
259 >>> im.save_image('tests/data/reduc_20170605_028_copy.fits', overwrite=True)
260 """
261 save_fits(output_file_name, self.header, self.data, overwrite=overwrite)
262 self.my_logger.info(f'\n\tImage saved in {output_file_name}')
264 def convert_to_ADU_rate_units(self):
265 """Convert Image data from ADU to ADU/s units.
267 Examples
268 --------
269 >>> im = Image('tests/data/reduc_20170605_028.fits')
270 >>> print(im.expo)
271 600.0
272 >>> data_before = np.copy(im.data)
273 >>> im.convert_to_ADU_rate_units()
275 .. doctest::
276 :hide:
278 >>> assert np.all(np.isclose(data_before, im.data * im.expo))
279 """
280 self.data = self.data.astype(np.float64) / self.expo
281 self.stat_errors /= self.expo
282 if self.stat_errors_rotated is not None:
283 self.stat_errors_rotated /= self.expo
284 self.units = 'ADU/s'
286 def convert_to_ADU_units(self):
287 """Convert Image data from ADU/s to ADU units.
289 Examples
290 --------
291 >>> im = Image('tests/data/reduc_20170605_028.fits')
292 >>> print(im.expo)
293 600.0
294 >>> data_before = np.copy(im.data)
295 >>> im.convert_to_ADU_rate_units()
296 >>> data_after = np.copy(im.data)
297 >>> im.convert_to_ADU_units()
299 .. doctest::
300 :hide:
302 >>> assert np.all(np.isclose(data_before, im.data))
303 """
304 self.data *= self.expo
305 self.stat_errors *= self.expo
306 if self.stat_errors_rotated is not None:
307 self.stat_errors_rotated *= self.expo
308 self.units = 'ADU'
310 def compute_statistical_error(self):
311 """Compute the image noise map from Image.data. The latter must be in ADU.
312 The function first converts the image in electron counts units, evaluate the Poisson noise,
313 add in quadrature the read-out noise, takes the square root and returns a map in ADU units.
315 Examples
316 --------
317 .. doctest::
319 >>> im = Image('tests/data/reduc_20170530_134.fits')
320 >>> im.convert_to_ADU_units()
321 >>> im.compute_statistical_error()
322 >>> im.plot_statistical_error()
324 .. plot::
326 from spectractor.extractor.images import Image
327 im = Image('tests/data/reduc_20170530_134.fits')
328 im.convert_to_ADU_units()
329 im.plot_statistical_error()
331 """
332 if self.units != 'ADU':
333 raise AttributeError(f'Noise must be estimated on an image in ADU units. '
334 f'Currently self.units={self.units}.')
335 # removes the zeros and negative pixels first
336 # set to minimum positive value
337 data = np.copy(self.data)
338 # OLD: compute poisson noise in ADU/s without read-out noise
339 # self.stat_errors = np.sqrt(data) / np.sqrt(self.gain * self.expo)
340 # convert in e- counts
341 err2 = data * self.gain
342 if self.read_out_noise is not None:
343 err2 += self.read_out_noise * self.read_out_noise
344 # remove negative values (due to dead columns for instance
345 min_noz = np.min(err2[err2 > 0])
346 err2[err2 <= 0] = min_noz
347 self.stat_errors = np.sqrt(err2)
348 # convert in ADU
349 self.stat_errors /= self.gain
350 # check uncertainty model
351 self.check_statistical_error()
353 def check_statistical_error(self):
354 """Check that statistical uncertainty map follows the input uncertainty model
355 in terms of gain and read-out noise.
357 A linear model is fitted to the squared pixel uncertainty values with respect to the pixel data values.
358 The slop gives the gain value and the intercept gives the read-out noise value.
360 Returns
361 -------
362 fit: tuple
363 The best fit parameter of the linear model.
364 x: array_like
365 The x data used for the fit (data).
366 y: array_like
367 The y data used for the fit (squared uncertainties).
368 model: array_like
369 The linear model values.
371 Examples
372 --------
374 .. doctest::
376 >>> im = Image('tests/data/reduc_20170530_134.fits')
377 >>> im.convert_to_ADU_units()
378 >>> fit, x, y, model = im.check_statistical_error()
380 .. doctest::
381 :hide:
383 >>> assert fit is not None
384 >>> assert len(fit) == 2
385 >>> assert x.shape == y.shape
386 >>> assert y.shape == model.shape
388 """
389 if self.units != "ADU":
390 raise AttributeError(f"Noise map must be in ADU units to be plotted and analyzed. "
391 f"Currently self.units={self.units}.")
392 data = np.copy(self.data)
393 min_noz = np.min(data[data > 0])
394 data[data <= 0] = min_noz
395 y = self.stat_errors.flatten() ** 2
396 x = data.flatten()
397 fit, cov, model = fit_poly1d(x, y, order=1)
398 gain = 1 / fit[0]
399 read_out = np.sqrt(fit[1]) * gain
400 if not np.isclose(gain, np.mean(self.gain), rtol=1e-2):
401 self.my_logger.warning(f"\n\tFitted gain seems to be different than input gain. "
402 f"Fit={gain} but average of self.gain is {np.mean(self.gain)}.")
403 if not np.isclose(read_out, np.mean(self.read_out_noise), rtol=1e-2):
404 self.my_logger.warning(f"\n\tFitted read out noise seems to be different than input readout noise. "
405 f"Fit={read_out} but average of self.read_out_noise is "
406 f"{np.mean(self.read_out_noise)}.")
407 return fit, x, y, model
409 def plot_statistical_error(self):
410 """Plot the statistical uncertainty map and check it is a Poisson noise.
412 The image units must be ADU.
414 Examples
415 --------
417 .. doctest::
419 >>> im = Image('tests/data/reduc_20170530_134.fits')
420 >>> im.convert_to_ADU_units()
421 >>> im.plot_statistical_error()
423 .. plot::
425 from spectractor.extractor.images import Image
426 im = Image('tests/data/reduc_20170530_134.fits')
427 im.convert_to_ADU_units()
428 im.plot_statistical_error()
430 """
431 fig, ax = plt.subplots(1, 2, figsize=(12, 5))
432 fit, x, y, model = self.check_statistical_error()
433 gain = 1 / fit[0]
434 read_out = np.sqrt(fit[1]) * gain
435 ax[0].text(0.05, 0.95, f"fitted gain={gain:.3g} [e-/ADU]\nintercept={fit[1]:.3g} [ADU$^2$]"
436 f"\nfitted read-out={read_out:.3g} [ADU]",
437 horizontalalignment='left', verticalalignment='top', transform=ax[0].transAxes)
438 ax[0].scatter(x, y)
439 ax[0].plot(x, model, "k-")
440 ax[0].grid()
441 ax[0].set_ylabel(r"$\sigma_{\mathrm{ADU}}^2$ [ADU$^2$]")
442 ax[0].set_xlabel(r"Data pixel values [ADU]")
443 plot_image_simple(ax[1], data=self.stat_errors, scale="log10", title="Statistical uncertainty map",
444 units=self.units, target_pixcoords=None, aspect="auto", cmap=None)
445 fig.tight_layout()
446 if parameters.LSST_SAVEFIGPATH: # pragma: no cover
447 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'uncertainty_map.pdf'))
448 if parameters.DISPLAY: # pragma: no cover
449 plt.show()
451 def compute_parallactic_angle(self):
452 """Compute the parallactic angle.
454 Script from A. Guyonnet.
455 """
456 latitude = Latitude(parameters.OBS_LATITUDE, unit=units.deg)
457 ha = self.hour_angle
458 dec = self.dec
459 # parallactic_angle = Angle(np.arctan2(np.sin(ha), (np.cos(dec) * np.tan(latitude) - np.sin(dec) * np.cos(ha))))
460 zenithal_distance, parallactic_angle = hadec2zdpar(ha, dec, latitude, deg=False)
461 self.parallactic_angle = parallactic_angle.value * 180 / np.pi
462 self.header['PARANGLE'] = self.parallactic_angle
463 self.header.comments['PARANGLE'] = 'parallactic angle in degree'
464 return self.parallactic_angle
466 def plot_image(self, ax=None, scale="lin", title="", units="", plot_stats=False,
467 target_pixcoords=None, figsize=(7.3, 6), aspect=None, vmin=None, vmax=None,
468 cmap=None, cax=None):
469 """Plot image.
471 Parameters
472 ----------
473 ax: Axes, optional
474 Axes instance (default: None).
475 scale: str
476 Scaling of the image (choose between: lin, log or log10, symlog) (default: lin)
477 title: str
478 Title of the image (default: "")
479 units: str
480 Units of the image to be written in the color bar label (default: "")
481 cmap: colormap
482 Color map label (default: None)
483 target_pixcoords: array_like, optional
484 2D array giving the (x,y) coordinates of the targets on the image: add a scatter plot (default: None)
485 vmin: float
486 Minimum value of the image (default: None)
487 vmax: float
488 Maximum value of the image (default: None)
489 aspect: str
490 Aspect keyword to be passed to imshow (default: None)
491 cax: Axes, optional
492 Color bar axes if necessary (default: None).
493 figsize: tuple
494 Figure size (default: [9.3, 8]).
495 plot_stats: bool
496 If True, plot the uncertainty map instead of the image (default: False).
498 Examples
499 --------
500 >>> im = Image('tests/data/reduc_20170605_028.fits', config="./config/ctio.ini")
501 >>> im.plot_image(target_pixcoords=[820, 580], scale="symlog")
502 >>> if parameters.DISPLAY: plt.show()
503 """
504 if ax is None:
505 plt.figure(figsize=figsize)
506 ax = plt.gca()
507 data = np.copy(self.data)
508 if plot_stats:
509 data = np.copy(self.stat_errors)
510 if units == "":
511 units = self.units
512 plot_image_simple(ax, data=data, scale=scale, title=title, units=units, cax=cax,
513 target_pixcoords=target_pixcoords, aspect=aspect, vmin=vmin, vmax=vmax, cmap=cmap)
514 if parameters.OBS_OBJECT_TYPE == "STAR":
515 plot_compass_simple(ax, self.parallactic_angle, arrow_size=0.1, origin=[0.15, 0.15])
516 plt.legend()
517 if parameters.LSST_SAVEFIGPATH: # pragma: no cover
518 plt.gcf().savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'image.pdf'))
519 if parameters.DISPLAY: # pragma: no cover
520 plt.show()
521 if parameters.PdfPages:
522 parameters.PdfPages.savefig()
524def load_CTIO_image(image):
525 """Specific routine to load CTIO fits files and load their data and properties for Spectractor.
527 Parameters
528 ----------
529 image: Image
530 The Image instance to fill with file data and header.
531 """
532 image.my_logger.info(f'\n\tLoading CTIO image {image.file_name}...')
533 image.header, image.data = load_fits(image.file_name)
535 image.date_obs = image.header['DATE-OBS']
536 image.airmass = float(image.header['AIRMASS'])
537 image.expo = float(image.header['EXPTIME'])
538 image.filters = image.header['FILTERS']
539 if "dia" not in image.header['FILTER1'].lower():
540 image.filter_label = image.header['FILTER1']
541 image.disperser_label = image.header['FILTER2']
542 image.ra = Angle(image.header['RA'], unit="hourangle")
543 image.dec = Angle(image.header['DEC'], unit="deg")
544 image.hour_angle = Angle(image.header['HA'], unit="hourangle")
545 image.temperature = image.header['OUTTEMP']
546 image.pressure = image.header['OUTPRESS']
547 image.humidity = image.header['OUTHUM']
549 parameters.CCD_IMSIZE = int(image.header['XLENGTH'])
550 parameters.CCD_PIXEL2ARCSEC = float(image.header['XPIXSIZE'])
551 if image.header['YLENGTH'] != parameters.CCD_IMSIZE:
552 image.my_logger.warning(
553 f'\n\tImage rectangular: X={parameters.CCD_IMSIZE:d} pix, Y={image.header["YLENGTH"]:d} pix')
554 image.coord = SkyCoord(image.header['RA'] + ' ' + image.header['DEC'], unit=(units.hourangle, units.deg),
555 obstime=image.header['DATE-OBS'])
556 image.my_logger.info(f'\n\tImage {image.file_name} loaded.')
557 # compute CCD gain map
558 build_CTIO_gain_map(image)
559 build_CTIO_read_out_noise_map(image)
560 image.compute_parallactic_angle()
563def build_CTIO_gain_map(image):
564 """Compute the CTIO gain map according to header GAIN values.
566 Parameters
567 ----------
568 image: Image
569 The Image instance to fill with file data and header.
570 """
571 size = parameters.CCD_IMSIZE
572 image.gain = np.zeros_like(image.data)
573 # ampli 11
574 image.gain[0:size // 2, 0:size // 2] = image.header['GTGAIN11']
575 # ampli 12
576 image.gain[0:size // 2, size // 2:size] = image.header['GTGAIN12']
577 # ampli 21
578 image.gain[size // 2:size, 0:size] = image.header['GTGAIN21']
579 # ampli 22
580 image.gain[size // 2:size, size // 2:size] = image.header['GTGAIN22']
583def build_CTIO_read_out_noise_map(image):
584 """Compute the CTIO gain map according to header GAIN values.
586 Parameters
587 ----------
588 image: Image
589 The Image instance to fill with file data and header.
590 """
591 size = parameters.CCD_IMSIZE
592 image.read_out_noise = np.zeros_like(image.data)
593 # ampli 11
594 image.read_out_noise[0:size // 2, 0:size // 2] = image.header['GTRON11']
595 # ampli 12
596 image.read_out_noise[0:size // 2, size // 2:size] = image.header['GTRON12']
597 # ampli 21
598 image.read_out_noise[size // 2:size, 0:size] = image.header['GTRON21']
599 # ampli 22
600 image.read_out_noise[size // 2:size, size // 2:size] = image.header['GTRON22']
603def load_LPNHE_image(image): # pragma: no cover
604 """Specific routine to load LPNHE fits files and load their data and properties for Spectractor.
606 Parameters
607 ----------
608 image: Image
609 The Image instance to fill with file data and header.
610 """
611 image.my_logger.info(f'\n\tLoading LPNHE image {image.file_name}...')
612 hdus = fits.open(image.file_name)
613 image.header = hdus[0].header
614 hdu1 = hdus["CHAN_14"]
615 hdu2 = hdus["CHAN_06"]
616 data1 = hdu1.data[imgslice(hdu1.header['DATASEC'])].astype(np.float64)
617 bias1 = np.median(hdu1.data[imgslice(hdu1.header['BIASSEC'])].astype(np.float64))
618 data1 -= bias1
619 detsecy, detsecx = imgslice(hdu1.header['DETSEC'])
620 if detsecy.start > detsecy.stop:
621 data1 = data1[:, ::-1]
622 if detsecx.start > detsecx.stop:
623 data1 = data1[::-1, :]
624 data2 = hdu2.data[imgslice(hdu2.header['DATASEC'])].astype(np.float64)
625 bias2 = np.median(hdu2.data[imgslice(hdu2.header['BIASSEC'])].astype(np.float64))
626 data2 -= bias2
627 detsecy, detsecx = imgslice(hdu2.header['DETSEC'])
628 if detsecy.start > detsecy.stop:
629 data2 = data2[:, ::-1]
630 if detsecx.start > detsecx.stop:
631 data2 = data2[::-1, :]
632 data = np.concatenate([data2, data1])
633 image.data = data[::-1, :].T
634 image.date_obs = image.header['DATE-OBS']
635 image.expo = float(image.header['EXPTIME'])
636 image.airmass = -1
637 parameters.DISTANCE2CCD -= float(hdus["XYZ"].header["ZPOS"])
638 if "mm" not in hdus["XYZ"].header.comments["ZPOS"]:
639 raise KeyError(f'mm is absent from ZPOS key in XYZ header. Had {hdus["XYZ"].header.comments["ZPOS"]}'
640 f'Distances along Z axis must be in mm.')
641 image.my_logger.info(f'\n\tDistance to CCD adjusted to {parameters.DISTANCE2CCD} mm '
642 f'considering XYZ platform is set at ZPOS={float(hdus["XYZ"].header["ZPOS"])} mm.')
643 # compute CCD gain map
644 image.gain = float(image.header['CCDGAIN']) * np.ones_like(image.data)
645 image.read_out_noise = float(image.header['CCDNOISE']) * np.ones_like(image.data)
646 parameters.CCD_IMSIZE = image.data.shape[1]
647 # save xys platform position into main header
648 image.header["XPOS"] = hdus["XYZ"].header["XPOS"]
649 image.header.comments["XPOS"] = hdus["XYZ"].header.comments["XPOS"]
650 image.header["YPOS"] = hdus["XYZ"].header["YPOS"]
651 image.header.comments["YPOS"] = hdus["XYZ"].header.comments["YPOS"]
652 image.header["ZPOS"] = hdus["XYZ"].header["ZPOS"]
653 image.header.comments["ZPOS"] = hdus["XYZ"].header.comments["ZPOS"]
654 image.my_logger.info('\n\tImage loaded')
657def load_AUXTEL_image(image): # pragma: no cover
658 """Specific routine to load AUXTEL fits files and load their data and properties for Spectractor.
660 Parameters
661 ----------
662 image: Image
663 The Image instance to fill with file data and header.
664 """
665 image.my_logger.info(f'\n\tLoading AUXTEL image {image.file_name}...')
666 hdu_list = fits.open(image.file_name)
667 image.header = hdu_list[0].header
668 image.data = hdu_list[1].data.astype(np.float64)
669 hdu_list.close() # need to free allocation for file descripto
670 image.date_obs = image.header['DATE']
671 image.expo = float(image.header['EXPTIME'])
672 if "empty" not in image.header['FILTER'].lower():
673 image.filter_label = image.header['FILTER']
674 # transformations so that stars are like in Stellarium up to a rotation
675 # with spectrogram nearly horizontal and on the right of central star
676 image.data = image.data.T[::-1, ::-1]
677 if image.header["AMSTART"] is not None:
678 image.airmass = 0.5 * (float(image.header["AMSTART"]) + float(image.header["AMEND"]))
679 else:
680 image.airmass = float(image.header['AIRMASS'])
681 image.my_logger.info('\n\tImage loaded')
682 # compute CCD gain map
683 image.gain = float(parameters.CCD_GAIN) * np.ones_like(image.data)
684 parameters.CCD_IMSIZE = image.data.shape[1]
685 image.disperser_label = image.header['GRATING']
686 image.ra = Angle(image.header['RA'], unit="deg")
687 image.dec = Angle(image.header['DEC'], unit="deg")
688 if 'HASTART' in image.header and image.header['HASTART'] is not None:
689 image.hour_angle = Angle(image.header['HASTART'], unit="hourangle")
690 else:
691 image.hour_angle = Angle(image.header['HA'], unit="deg")
692 if 'AIRTEMP' in image.header:
693 image.temperature = image.header['AIRTEMP']
694 else:
695 image.temperature = 10
696 if 'PRESSURE' in image.header:
697 image.pressure = image.header['PRESSURE']
698 else:
699 image.pressure = 743
700 if 'HUMIDITY' in image.header:
701 image.humidity = image.header['HUMIDITY']
702 else:
703 image.humidity = 40
704 if 'adu' in image.header['BUNIT']:
705 image.units = 'ADU'
706 parameters.OBS_CAMERA_ROTATION = 90 - float(image.header["ROTPA"])
707 if parameters.OBS_CAMERA_ROTATION > 360:
708 parameters.OBS_CAMERA_ROTATION -= 360
709 if parameters.OBS_CAMERA_ROTATION < -360:
710 parameters.OBS_CAMERA_ROTATION += 360
711 if "CD2_1" in hdu_list[1].header:
712 rotation_wcs = 180 / np.pi * np.arctan2(hdu_list[1].header["CD2_1"], hdu_list[1].header["CD1_1"]) + 90
713 if not np.isclose(rotation_wcs % 360, parameters.OBS_CAMERA_ROTATION % 360, atol=2):
714 image.my_logger.warning(f"\n\tWCS rotation angle is {rotation_wcs} degree while "
715 f"parameters.OBS_CAMERA_ROTATION={parameters.OBS_CAMERA_ROTATION} degree. "
716 f"\nBoth differs by more than 2 degree... bug ?")
717 parameters.OBS_ALTITUDE = float(image.header['OBS-ELEV']) / 1000
718 parameters.OBS_LATITUDE = image.header['OBS-LAT']
719 image.read_out_noise = 8.5 * np.ones_like(image.data)
720 image.target_label = image.header["OBJECT"].replace(" ", "")
721 if "OBJECTX" in image.header:
722 image.target_guess = [parameters.CCD_IMSIZE - float(image.header["OBJECTY"]),
723 parameters.CCD_IMSIZE - float(image.header["OBJECTX"])]
724 image.disperser_label = image.header["GRATING"]
725 parameters.DISTANCE2CCD = 115 + float(image.header["LINSPOS"]) # mm
726 image.compute_parallactic_angle()
729def find_target(image, guess=None, rotated=False, widths=[parameters.XWINDOW, parameters.YWINDOW]):
730 """Find the target in the Image instance.
732 The object is search in a windows of size defined by the XWINDOW and YWINDOW parameters,
733 using two iterative fits of a PSF model.
734 User must give a guess array in the raw image.
736 Parameters
737 ----------
738 image: Image
739 The Image instance.
740 guess: array_like
741 Two parameter array giving the estimated position of the target in the image, optional if WCS is used.
742 rotated: bool
743 If True, the target is searched in the rotated image.
744 widths: (int, int)
745 Two parameter array to define the width of the cropped image (default: [parameters.XWINDOW, parameters.YWINDOW])
747 Returns
748 -------
749 x0: float
750 The x position of the target.
751 y0: float
752 The y position of the target.
754 Examples
755 --------
756 >>> im = Image('tests/data/reduc_20170605_028.fits', target_label="PNG321.0+3.9")
757 >>> im.plot_image()
758 >>> guess = [820, 580]
759 >>> parameters.VERBOSE = True
760 >>> parameters.DEBUG = True
761 >>> parameters.SPECTRACTOR_FIT_TARGET_CENTROID = "fit"
762 >>> find_target(im, guess) #doctest: +ELLIPSIS
763 [816.8... 587.3...]
764 >>> parameters.SPECTRACTOR_FIT_TARGET_CENTROID = "WCS"
765 >>> find_target(im, guess) #doctest: +ELLIPSIS
766 [816.9... 587.1...]
767 >>> parameters.SPECTRACTOR_FIT_TARGET_CENTROID = "guess"
768 >>> find_target(im, guess)
769 [820, 580]
770 """
771 my_logger = set_logger(__name__)
772 target_pixcoords = [-1, -1]
773 theX = -1
774 theY = -1
775 if parameters.SPECTRACTOR_FIT_TARGET_CENTROID == "WCS" and not rotated:
776 wcs_file_name = set_wcs_file_name(image.file_name)
777 if os.path.isfile(wcs_file_name):
778 my_logger.info(f"\n\tUse WCS {wcs_file_name} to find target pixel position.")
779 if rotated:
780 target_pixcoords = find_target_after_rotation(image)
781 theX, theY = target_pixcoords
782 else:
783 wcs = load_wcs_from_file(wcs_file_name)
784 target_coord_after_motion = image.target.get_radec_position_after_pm(image.date_obs)
785 # noinspection PyUnresolvedReferences
786 target_pixcoords = np.array(wcs.all_world2pix(target_coord_after_motion.ra,
787 target_coord_after_motion.dec, 0))
788 theX, theY = target_pixcoords / parameters.CCD_REBIN
789 sub_image_subtracted, x0, y0, Dx, Dy, sub_errors = find_target_init(image=image, guess=[theX, theY],
790 rotated=rotated, widths=widths)
791 sub_image_x0 = theX - x0 + Dx
792 sub_image_y0 = theX - y0 + Dy
793 if parameters.DEBUG:
794 plt.figure(figsize=(5, 5))
795 plot_image_simple(plt.gca(), data=sub_image_subtracted, scale="lin", title="", units=image.units,
796 target_pixcoords=[theX - x0 + Dx, theX - x0 + Dx])
797 plt.show()
798 if parameters.PdfPages:
799 parameters.PdfPages.savefig()
800 else:
801 my_logger.info(f"\n\tNo WCS {wcs_file_name} available, use 2D fit to find target pixel position.")
802 if parameters.SPECTRACTOR_FIT_TARGET_CENTROID == "fit" or rotated:
803 if target_pixcoords[0] == -1 and target_pixcoords[1] == -1:
804 if guess is None:
805 raise ValueError(f"Guess parameter must be set if WCS solution is not found.")
806 Dx, Dy = widths
807 theX, theY = guess
808 if rotated:
809 guess2 = find_target_after_rotation(image)
810 x0 = int(guess2[0])
811 y0 = int(guess2[1])
812 guess = [x0, y0]
813 niter = 2
814 sub_image_subtracted, x0, y0, Dx, Dy, sub_errors = find_target_init(image=image, guess=guess, rotated=rotated,
815 widths=(Dx, Dy))
816 sub_image_x0, sub_image_y0 = x0, y0
817 for i in range(niter):
818 # find the target
819 # try:
820 sub_image_x0, sub_image_y0 = find_target_Moffat2D(image, sub_image_subtracted, sub_errors=sub_errors)
821 # except (Exception, ValueError):
822 # image.target_star2D = None
823 # avX, avY = find_target_2DprofileASTROPY(image, sub_image_subtracted, sub_errors=sub_errors)
824 # compute target position
825 theX = x0 - Dx + sub_image_x0
826 theY = y0 - Dy + sub_image_y0
827 # crop for next iteration
828 if i < niter - 1:
829 Dx = Dx // (i + 2)
830 Dy = Dy // (i + 2)
831 x0 = int(theX)
832 y0 = int(theY)
833 NY, NX = sub_image_subtracted.shape
834 sub_image_subtracted = sub_image_subtracted[
835 max(0, int(sub_image_y0) - Dy):min(NY, int(sub_image_y0) + Dy),
836 max(0, int(sub_image_x0) - Dx):min(NX, int(sub_image_x0) + Dx)]
837 sub_errors = sub_errors[max(0, int(sub_image_y0) - Dy):min(NY, int(sub_image_y0) + Dy),
838 max(0, int(sub_image_x0) - Dx):min(NX, int(sub_image_x0) + Dx)]
839 if int(sub_image_x0) - Dx < 0:
840 Dx = int(sub_image_x0)
841 if int(sub_image_y0) - Dy < 0:
842 Dy = int(sub_image_y0)
843 else:
844 Dx, Dy = widths
845 sub_image_subtracted, x0, y0, Dx, Dy, sub_errors = find_target_init(image=image, guess=target_pixcoords,
846 rotated=rotated, widths=(Dx, Dy))
847 theX, theY = target_pixcoords
848 sub_image_x0 = target_pixcoords[0] - x0 + Dx
849 sub_image_y0 = target_pixcoords[1] - y0 + Dy
850 elif parameters.SPECTRACTOR_FIT_TARGET_CENTROID == "guess":
851 Dx, Dy = widths
852 sub_image_subtracted, x0, y0, Dx, Dy, sub_errors = find_target_init(image=image, guess=target_pixcoords,
853 rotated=rotated, widths=(Dx, Dy))
854 theX, theY = guess
855 sub_image_x0 = theX - x0 + Dx
856 sub_image_y0 = theY - y0 + Dy
857 elif parameters.SPECTRACTOR_FIT_TARGET_CENTROID == "WCS" and not rotated:
858 pass
859 else:
860 raise ValueError(f"For unrotated images, parameters.SPECTRACTOR_FIT_TARGET_CENTROID muste be either: "
861 f"guess, fit or WCS. Got {parameters.SPECTRACTOR_FIT_TARGET_CENTROID}.")
862 image.my_logger.info(f'\n\tX,Y target position in pixels: {theX:.3f},{theY:.3f}')
863 if rotated:
864 image.target_pixcoords_rotated = [theX, theY]
865 else:
866 image.target.image = sub_image_subtracted
867 image.target.image_x0 = sub_image_x0
868 image.target.image_y0 = sub_image_y0
869 image.target_pixcoords = [theX, theY]
870 image.header['TARGETX'] = theX
871 image.header.comments['TARGETX'] = 'target position on X axis'
872 image.header['TARGETY'] = theY
873 image.header.comments['TARGETY'] = 'target position on Y axis'
874 return [theX, theY]
877def find_target_after_rotation(image):
878 angle = image.rotation_angle * np.pi / 180.
879 rotmat = np.array([[np.cos(angle), np.sin(angle)], [-np.sin(angle), np.cos(angle)]])
880 vec = np.array(image.target_pixcoords) - 0.5 * np.array(image.data.shape[::-1])
881 target_pixcoords_after_rotation = rotmat @ vec + 0.5 * np.array(image.data_rotated.shape[::-1])
882 return target_pixcoords_after_rotation
885def find_target_init(image, guess, rotated=False, widths=[parameters.XWINDOW, parameters.YWINDOW]):
886 """Initialize the search of the target: crop the image, set the saturation level,
887 estimate and subtract a 2D polynomial background.
889 Parameters
890 ----------
891 image: Image
892 The Image instance.
893 guess: array_like
894 Two parameter array giving the estimated position of the target in the image.
895 rotated: bool
896 If True, the target is searched in the rotated image.
897 widths: (int, int)
898 Two parameter array to define the width of the cropped image (default: [parameters.XWINDOW, parameters.YWINDOW])
900 Returns
901 -------
902 sub_image: array_like
903 The cropped image data array where the fit has to be performed.
904 x0: float
905 The x position of the target.
906 y0: float
907 The y position of the target.
908 Dx: int
909 The width of the cropped image.
910 Dy: int
911 The height of the cropped image.
912 sub_errors: array_like
913 The cropped image uncertainty array where the fit has to be performed.
914 """
915 x0 = int(guess[0])
916 y0 = int(guess[1])
917 Dx, Dy = widths
918 if rotated:
919 sub_image = np.copy(image.data_rotated[y0 - Dy:y0 + Dy, x0 - Dx:x0 + Dx])
920 sub_errors = np.copy(image.stat_errors[y0 - Dy:y0 + Dy, x0 - Dx:x0 + Dx])
921 else:
922 sub_image = np.copy(image.data[y0 - Dy:y0 + Dy, x0 - Dx:x0 + Dx])
923 sub_errors = np.copy(image.stat_errors[y0 - Dy:y0 + Dy, x0 - Dx:x0 + Dx])
924 image.saturation = parameters.CCD_MAXADU / image.expo
925 NY, NX = sub_image.shape
926 Y, X = np.mgrid[:NY, :NX]
927 bkgd_2D = fit_poly2d_outlier_removal(X, Y, sub_image, order=1, sigma=3)
928 image.target_bkgd2D = bkgd_2D
929 sub_image_subtracted = sub_image - bkgd_2D(X, Y)
930 saturated_pixels = np.where(sub_image >= image.saturation)
931 if len(saturated_pixels[0]) > 0:
932 image.my_logger.debug(
933 f'\n\t{len(saturated_pixels[0])} saturated pixels: set saturation level '
934 f'to {image.saturation} {image.units}.')
935 sub_errors[sub_image >= 0.99 * image.saturation] = 10 * image.saturation # np.min(np.abs(sub_errors))
936 # sub_image = clean_target_spikes(sub_image, image.saturation)
937 return sub_image_subtracted, x0, y0, Dx, Dy, sub_errors
940def find_target_1Dprofile(image, sub_image, guess):
941 """
942 Find precisely the position of the targeted object fitting a PSF model
943 on each projection of the image along x and y, using outlier removal.
945 Parameters
946 ----------
947 image: Image
948 The Image instance.
949 sub_image: array_like
950 The cropped image data array where the fit is performed.
951 guess: array_like
952 Two parameter array giving the estimated position of the target in the image.
954 Examples
955 --------
956 >>> im = Image('tests/data/reduc_20170605_028.fits')
957 >>> guess = [820, 580]
958 >>> parameters.DEBUG = True
959 >>> sub_image, x0, y0, Dx, Dy, sub_errors = find_target_init(im, guess, rotated=False)
960 >>> x1, y1 = find_target_1Dprofile(im, sub_image, guess)
962 .. doctest::
963 :hide:
965 >>> assert np.isclose(x1, np.argmax(np.nansum(sub_image, axis=0)), rtol=1e-2)
966 >>> assert np.isclose(y1, np.argmax(np.nansum(sub_image, axis=1)), rtol=1e-2)
968 """
969 NY, NX = sub_image.shape
970 X = np.arange(NX)
971 Y = np.arange(NY)
972 # Mask aigrette
973 saturated_pixels = np.where(sub_image >= image.saturation)
974 if parameters.DEBUG:
975 image.my_logger.info('\n\t%d saturated pixels: set saturation level to %d %s.' % (
976 len(saturated_pixels[0]), image.saturation, image.units))
977 # sub_image[sub_image >= 0.5*image.saturation] = np.nan
978 # compute profiles
979 profile_X_raw = np.sum(sub_image, axis=0)
980 profile_Y_raw = np.sum(sub_image, axis=1)
981 # fit and subtract smooth polynomial background
982 # with 3sigma rejection of outliers (star peaks)
983 bkgd_X, outliers = fit_poly1d_outlier_removal(X, profile_X_raw, order=2)
984 bkgd_Y, outliers = fit_poly1d_outlier_removal(Y, profile_Y_raw, order=2)
985 profile_X = profile_X_raw - bkgd_X(X) # np.min(profile_X)
986 profile_Y = profile_Y_raw - bkgd_Y(Y) # np.min(profile_Y)
987 avX, sigX = weighted_avg_and_std(X, profile_X ** 4)
988 avY, sigY = weighted_avg_and_std(Y, profile_Y ** 4)
989 if profile_X[int(avX)] < 0.8 * np.max(profile_X):
990 image.my_logger.warning('\n\tX position determination of the target probably wrong')
991 if profile_Y[int(avY)] < 0.8 * np.max(profile_Y):
992 image.my_logger.warning('\n\tY position determination of the target probably wrong')
993 if parameters.DEBUG:
994 f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 4))
995 plot_image_simple(ax1, data=sub_image, scale="log", title="", units=image.units, target_pixcoords=[avX, avY])
996 ax1.legend(loc=1)
997 ax2.plot(X, profile_X_raw, 'r-', lw=2)
998 ax2.plot(X, bkgd_X(X), 'g--', lw=2, label='bkgd')
999 ax2.axvline(avX, color='b', linestyle='-', label='new', lw=2)
1000 ax2.grid(True)
1001 ax2.set_xlabel(parameters.PLOT_XLABEL)
1002 ax2.legend(loc=1)
1003 ax3.plot(Y, profile_Y_raw, 'r-', lw=2)
1004 ax3.plot(Y, bkgd_Y(Y), 'g--', lw=2, label='bkgd')
1005 ax3.axvline(avY, color='b', linestyle='-', label='new', lw=2)
1006 ax3.grid(True)
1007 ax3.set_xlabel(parameters.PLOT_YLABEL)
1008 ax3.legend(loc=1)
1009 f.tight_layout()
1010 if parameters.DISPLAY: # pragma: no cover
1011 plt.show()
1012 if parameters.LSST_SAVEFIGPATH: # pragma: no cover
1013 f.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'namethisplot1.pdf'))
1014 if parameters.PdfPages:
1015 parameters.PdfPages.savefig()
1016 return avX, avY
1019def find_target_Moffat2D(image, sub_image_subtracted, sub_errors=None):
1020 """
1021 Find precisely the position of the targeted object fitting a Moffat PSF model.
1022 A polynomial 2D background is subtracted first. Saturated pixels are masked with np.nan values.
1024 Parameters
1025 ----------
1026 image: Image
1027 The Image instance.
1028 sub_image_subtracted: array_like
1029 The cropped image data array where the fit is performed, background has been subtracted.
1030 sub_errors: array_like
1031 The image data uncertainties.
1033 Examples
1034 --------
1035 >>> im = Image('tests/data/reduc_20170605_028.fits')
1036 >>> guess = [820, 580]
1037 >>> parameters.VERBOSE = True
1038 >>> parameters.DEBUG = True
1039 >>> sub_image_subtracted, x0, y0, Dx, Dy, sub_errors = find_target_init(im, guess, rotated=False) #, widths=[30,30])
1040 >>> xmax = np.argmax(np.sum(sub_image_subtracted, axis=0))
1041 >>> ymax = np.argmax(np.sum(sub_image_subtracted, axis=1))
1042 >>> x1, y1 = find_target_Moffat2D(im, sub_image_subtracted, sub_errors=sub_errors)
1044 .. doctest::
1045 :hide:
1047 >>> assert np.isclose(x1, xmax, rtol=1e-2)
1048 >>> assert np.isclose(y1, ymax, rtol=1e-2)
1050 """
1051 # fit and subtract smooth polynomial background
1052 # with 3sigma rejection of outliers (star peaks)
1053 NY, NX = sub_image_subtracted.shape
1054 XX = np.arange(NX)
1055 YY = np.arange(NY)
1056 # find a first guess of the target position
1057 avX, sigX = weighted_avg_and_std(XX, np.sum(sub_image_subtracted, axis=0) ** 4)
1058 avY, sigY = weighted_avg_and_std(YY, np.sum(sub_image_subtracted, axis=1) ** 4)
1059 # fit a 2D star profile close to this position
1060 # guess = [np.max(sub_image_subtracted),avX,avY,1,1] #for Moffat2Ds
1061 # guess = [np.max(sub_image_subtracted),avX-2,avY-2,2,2,0] #for Gauss2D
1062 psf = Moffat(clip=True)
1063 total_flux = np.sum(sub_image_subtracted)
1064 psf.p[:3] = [total_flux, avX, avY]
1065 psf.p[-1] = image.saturation
1066 if image.target_star2D is not None:
1067 psf.p = image.target_star2D.p
1068 psf.p[1] = avX
1069 psf.p[2] = avY
1070 mean_prior = 10 # in pixels
1071 # bounds = [ [0.5*np.max(sub_image_subtracted),avX-mean_prior,avY-mean_prior,0,-np.inf],
1072 # [2*np.max(sub_image_subtracted),avX+mean_prior,avY+mean_prior,np.inf,np.inf] ] #for Moffat2D
1073 # bounds = [ [0.5*np.max(sub_image_subtracted),avX-mean_prior,avY-mean_prior,0,0,0],
1074 # [100*image.saturation,avX+mean_prior,avY+mean_prior,10,10,np.pi] ] #for Gauss2D
1075 # bounds = [[0.5 * np.max(sub_image_subtracted), avX - mean_prior, avY - mean_prior, 2, 0.9 * image.saturation],
1076 # [10 * image.saturation, avX + mean_prior, avY + mean_prior, 15, 1.1 * image.saturation]]
1077 psf.bounds[:3] = [[0.1 * total_flux, 4 * total_flux],
1078 [avX - mean_prior, avX + mean_prior],
1079 [avY - mean_prior, avY + mean_prior]]
1080 # fit
1081 # star2D = fit_PSF2D(X, Y, sub_image_subtracted, guess=guess, bounds=bounds)
1082 # star2D = fit_PSF2D_minuit(X, Y, sub_image_subtracted, guess=guess, bounds=bounds)
1083 psf.fit_psf(sub_image_subtracted, data_errors=sub_errors, bgd_model_func=image.target_bkgd2D)
1084 new_avX = psf.p[1]
1085 new_avY = psf.p[2]
1086 image.target_star2D = psf
1087 # check target positions
1088 dist = np.sqrt((new_avY - avY) ** 2 + (new_avX - avX) ** 2)
1089 if dist > mean_prior / 2:
1090 image.my_logger.warning(
1091 f'\n\tX={new_avX:.2f}, Y={new_avY:.2f} target position determination probably wrong: '
1092 f'{dist:.1f} pixels from profile detection ({avX:.2f}, {avY:.2f})')
1093 # debugging plots
1094 if parameters.DEBUG:
1095 f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 4))
1096 vmin = 0
1097 vmax = float(np.nanmax(sub_image_subtracted))
1098 Y, X = np.mgrid[:NY, :NX]
1099 star2D = psf.evaluate(pixels=np.array([X, Y]))
1100 plot_image_simple(ax1, data=sub_image_subtracted, scale="lin", title="", units=image.units,
1101 target_pixcoords=[new_avX, new_avY], vmin=vmin, vmax=vmax)
1102 ax1.legend(loc=1)
1104 ax1.text(0.05, 0.05, f'Data', color="white",
1105 horizontalalignment='left', verticalalignment='bottom', transform=ax1.transAxes)
1106 ax2.text(0.05, 0.05, f'Background+Moffat2D model', color="white",
1107 horizontalalignment='left', verticalalignment='bottom', transform=ax2.transAxes)
1108 ax3.text(0.05, 0.05, f'Residuals', color="white",
1109 horizontalalignment='left', verticalalignment='bottom', transform=ax3.transAxes)
1110 plot_image_simple(ax2, data=star2D, scale="lin", title="",
1111 units=f'{image.units}', vmin=vmin, vmax=vmax)
1112 plot_image_simple(ax3, data=sub_image_subtracted - star2D, scale="lin", title="",
1113 units=f'{image.units}', target_pixcoords=[new_avX, new_avY], vmin=vmin, vmax=vmax)
1114 ax3.legend(loc=1)
1116 f.tight_layout()
1117 if parameters.DISPLAY: # pragma: no cover
1118 plt.show()
1119 if parameters.LSST_SAVEFIGPATH: # pragma: no cover
1120 f.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'order0_centroid_fit.pdf'))
1121 return new_avX, new_avY
1124def compute_rotation_angle_hessian(image, angle_range=(-10, 10), width_cut=parameters.YWINDOW,
1125 edges=(0, parameters.CCD_IMSIZE),
1126 margin_cut=12, pixel_fraction=0.01):
1127 """Compute the rotation angle in degree of a spectrogram with the Hessian of the image.
1128 Use the disperser rotation angle map as a prior and the target_pixcoords values to crop the image
1129 around the spectrogram.
1131 Parameters
1132 ----------
1133 image: Image
1134 The Image instance.
1135 angle_range: (float, float)
1136 Don't consider pixel with Hessian angle outside this range (default: (-10,10)).
1137 width_cut: int
1138 Half with of the image to consider in height (default: parameters.YWINDOW).
1139 edges: (int, int)
1140 Minimum and maximum pixel on the right edge (default: (0, parameters.CCD_IMSIZE)).
1141 margin_cut: int
1142 After computing the Hessian, to avoid bad values on the edges the function cut on the
1143 edge of image margin_cut pixels (default: 12).
1144 pixel_fraction: float
1145 Minimum pixel fraction to keep after thresholding the lambda minus map (default: 0.01).
1147 Returns
1148 -------
1149 theta: float
1150 The median value of the histogram of angles deduced with the Hessian of the pixels (in degree).
1152 Examples
1153 --------
1154 >>> im=Image('tests/data/reduc_20170605_028.fits', disperser_label='HoloPhAg')
1156 Create a mock spectrogram:
1158 >>> N = parameters.CCD_IMSIZE
1159 >>> im.data = np.ones((N, N))
1160 >>> slope = -0.1
1161 >>> y = lambda x: slope * (x - 0.5*N) + 0.5*N
1162 >>> for x in np.arange(N):
1163 ... im.data[int(y(x)), x] = 100
1164 ... im.data[int(y(x))+1, x] = 100
1165 >>> im.target_pixcoords=(N//2, N//2)
1166 >>> parameters.DEBUG = True
1167 >>> theta = compute_rotation_angle_hessian(im)
1169 .. doctest::
1170 :hide:
1172 >>> assert np.isclose(theta, np.arctan(slope)*180/np.pi, rtol=1e-1)
1174 """
1175 x0, y0 = np.array(image.target_pixcoords).astype(int)
1176 # extract a region
1177 left_edge, right_edge = edges
1178 data = np.copy(image.data[y0 - width_cut:y0 + width_cut, left_edge:right_edge])
1179 lambda_plus, lambda_minus, theta = hessian_and_theta(data, margin_cut)
1180 # thresholds
1181 lambda_threshold = np.min(lambda_minus)
1182 mask = np.where(lambda_minus > lambda_threshold)
1183 theta_mask = np.copy(theta)
1184 theta_mask[mask] = np.nan
1185 minimum_pixels = pixel_fraction * 2 * width_cut * right_edge
1186 while len(theta_mask[~np.isnan(theta_mask)]) < minimum_pixels:
1187 lambda_threshold /= 2
1188 mask = np.where(lambda_minus > lambda_threshold)
1189 theta_mask = np.copy(theta)
1190 theta_mask[mask] = np.nan
1191 # print len(theta_mask[~np.isnan(theta_mask)]), lambda_threshold
1192 theta_guess = image.disperser.theta(image.target_pixcoords)
1193 mask2 = np.logical_or(angle_range[0] > theta - theta_guess, theta - theta_guess > angle_range[1])
1194 theta_mask[mask2] = np.nan
1195 theta_mask = theta_mask[2:-2, 2:-2]
1196 theta_hist = theta_mask[~np.isnan(theta_mask)].flatten()
1197 if parameters.OBS_OBJECT_TYPE != 'STAR':
1198 pixels = np.where(~np.isnan(theta_mask))
1199 p = np.polyfit(pixels[1], pixels[0], deg=1)
1200 theta_median = np.arctan(p[0]) * 180 / np.pi
1201 else:
1202 theta_median = float(np.median(theta_hist))
1203 # theta_critical = 180. * np.arctan(20. / parameters.CCD_IMSIZE) / np.pi
1204 image.header['THETAFIT'] = theta_median
1205 image.header.comments['THETAFIT'] = '[deg] [USED] rotation angle from the Hessian analysis'
1206 image.header['THETAINT'] = theta_guess
1207 image.header.comments['THETAINT'] = '[deg] rotation angle interp from disperser scan'
1208 # if abs(theta_median - theta_guess) > theta_critical:
1209 # image.my_logger.warning(
1210 # f'\n\tInterpolated angle and fitted angle disagrees with more than 20 pixels '
1211 # f'over {parameters.CCD_IMSIZE:d} pixels: {theta_median:.2f} vs {theta_guess:.2f}')
1212 if parameters.DEBUG:
1213 gs_kw = dict(width_ratios=[3, 1], height_ratios=[1])
1214 f, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(6.5, 3), gridspec_kw=gs_kw)
1215 xindex = np.arange(data.shape[1])
1216 x_new = np.linspace(xindex.min(), xindex.max(), 50)
1217 y_new = width_cut - margin_cut - 3 + (x_new - x0) * np.tan(theta_median * np.pi / 180.)
1218 cmap = copy.copy(cm.get_cmap('bwr'))
1219 cmap.set_bad(color='lightgrey')
1220 im = ax1.imshow(theta_mask, origin='lower', cmap=cmap, aspect='auto', vmin=angle_range[0], vmax=angle_range[1])
1221 cb = plt.colorbar(im, ax=ax1)
1222 cb.set_label(parameters.PLOT_ROT_LABEL, labelpad=-10)
1223 ax1.plot(x_new, y_new, 'k-', label=rf"Mean dispersion axis: $\varphi_d$={theta_median:.2f}°")
1224 ax1.set_ylim(0, theta_mask.shape[0])
1225 ax1.set_xlim(0, theta_mask.shape[1])
1226 ax1.legend()
1227 ax1.set_xlabel(parameters.PLOT_XLABEL)
1228 ax1.set_ylabel(parameters.PLOT_YLABEL)
1229 ax1.grid(True)
1230 ax2.hist(theta_hist, bins=int(np.sqrt(len(theta_hist))))
1231 ax2.axvline(theta_median, color='k')
1232 ax2.set_xlabel(parameters.PLOT_ROT_LABEL)
1233 ax2.grid()
1234 f.tight_layout()
1235 if parameters.DISPLAY: # pragma: no cover
1236 plt.show()
1237 if parameters.LSST_SAVEFIGPATH: # pragma: no cover
1238 f.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'rotation_hessian.pdf'))
1239 if parameters.PdfPages:
1240 parameters.PdfPages.savefig()
1241 return theta_median
1244def turn_image(image):
1245 """Compute the rotation angle using the Hessian algorithm and turn the image.
1247 The results are stored in Image.data_rotated and Image.stat_errors_rotated.
1249 Parameters
1250 ----------
1251 image: Image
1252 The Image instance.
1254 Returns
1255 -------
1256 rotation_angle: float
1257 Rotation angle in degree.
1259 Examples
1260 --------
1262 Create of False spectrogram:
1264 >>> im=Image('tests/data/reduc_20170605_028.fits', disperser_label='HoloPhAg')
1265 >>> N = parameters.CCD_IMSIZE
1266 >>> im.data = np.ones((N, N))
1267 >>> slope = -0.1
1268 >>> y = lambda x: slope * (x - 0.5*N) + 0.5*N
1269 >>> for x in np.arange(N):
1270 ... im.data[int(y(x)), x] = 10
1271 ... im.data[int(y(x))+1, x] = 10
1273 .. plot::
1275 from spectractor.extractor.images import Image
1276 import spectractor.parameters as parameters
1277 im=Image('tests/data/reduc_20170605_028.fits', disperser_label='HoloPhAg')
1278 N = parameters.CCD_IMSIZE
1279 im.data = np.ones((N, N))
1280 slope = -0.1
1281 y = lambda x: slope * (x - 0.5*N) + 0.5*N
1282 for x in np.arange(N):
1283 im.data[int(y(x)), x] = 10
1284 im.data[int(y(x))+1, x] = 10
1285 plt.imshow(im.data, origin='lower')
1286 plt.show()
1288 >>> im.target_pixcoords=(N//2, N//2)
1289 >>> parameters.DEBUG = True
1290 >>> parameters.SPECTRACTOR_COMPUTE_ROTATION_ANGLE = False
1291 >>> turn_image(im)
1292 0
1293 >>> parameters.SPECTRACTOR_COMPUTE_ROTATION_ANGLE = "disperser"
1294 >>> turn_image(im)
1295 -1.915
1296 >>> parameters.SPECTRACTOR_COMPUTE_ROTATION_ANGLE = "hessian"
1297 >>> turn_image(im) #doctest: +ELLIPSIS
1298 -5.90...
1300 .. doctest::
1301 :hide:
1303 >>> assert im.data_rotated is not None
1304 >>> assert np.isclose(im.rotation_angle, np.arctan(slope)*180/np.pi, rtol=5e-2)
1306 .. plot::
1308 from spectractor.extractor.images import Image, turn_image
1309 import spectractor.parameters as parameters
1310 im=Image('tests/data/reduc_20170605_028.fits', disperser_label='HoloPhAg')
1311 N = parameters.CCD_IMSIZE
1312 im.data = np.ones((N, N))
1313 slope = -0.1
1314 y = lambda x: slope * (x - 0.5*N) + 0.5*N
1315 for x in np.arange(N):
1316 im.data[int(y(x)), x] = 10
1317 im.data[int(y(x))+1, x] = 10
1319 im.target_pixcoords=(N//2, N//2)
1320 turn_image(im)
1321 plt.imshow(im.data_rotated, origin='lower')
1322 plt.show()
1323 """
1324 if parameters.SPECTRACTOR_COMPUTE_ROTATION_ANGLE == "hessian":
1325 image.rotation_angle = compute_rotation_angle_hessian(image, width_cut=parameters.YWINDOW,
1326 angle_range=(parameters.ROT_ANGLE_MIN,
1327 parameters.ROT_ANGLE_MAX),
1328 edges=(0, parameters.CCD_IMSIZE))
1329 elif parameters.SPECTRACTOR_COMPUTE_ROTATION_ANGLE == "disperser":
1330 image.rotation_angle = image.disperser.theta_tilt
1331 elif parameters.SPECTRACTOR_COMPUTE_ROTATION_ANGLE is False:
1332 image.rotation_angle = 0
1333 else:
1334 raise ValueError(f"Unknown method for rotation angle computation: choose among False, disperser, hessian. "
1335 f"Got {parameters.SPECTRACTOR_COMPUTE_ROTATION_ANGLE}")
1336 image.header['ROTANGLE'] = image.rotation_angle
1337 image.my_logger.info(f'\n\tRotate the image with angle theta={image.rotation_angle:.2f} degree')
1338 image.data_rotated = np.copy(image.data)
1339 if not np.isnan(image.rotation_angle):
1340 image.data_rotated = ndimage.interpolation.rotate(image.data, image.rotation_angle,
1341 prefilter=parameters.ROT_PREFILTER,
1342 order=parameters.ROT_ORDER)
1343 image.stat_errors_rotated = np.sqrt(
1344 np.abs(ndimage.interpolation.rotate(image.stat_errors ** 2, image.rotation_angle,
1345 prefilter=parameters.ROT_PREFILTER,
1346 order=parameters.ROT_ORDER)))
1347 min_noz = np.min(image.stat_errors_rotated[image.stat_errors_rotated > 0])
1348 image.stat_errors_rotated[image.stat_errors_rotated <= 0] = min_noz
1349 if parameters.DEBUG:
1350 margin = 100 // parameters.CCD_REBIN
1351 y0 = int(image.target_pixcoords[1])
1352 f, (ax1, ax2) = plt.subplots(2, 1, figsize=[8, 8])
1353 plot_image_simple(ax1, data=image.data[max(0, y0 - 2 * parameters.YWINDOW):
1354 min(y0 + 2 * parameters.YWINDOW, image.data.shape[0]),
1355 margin:-margin],
1356 scale="symlog", title='Raw image (log10 scale)', units=image.units,
1357 target_pixcoords=(image.target_pixcoords[0] - margin, 2 * parameters.YWINDOW), aspect='auto')
1358 if parameters.OBS_OBJECT_TYPE == "STAR":
1359 plot_compass_simple(ax1, image.parallactic_angle, arrow_size=0.1, origin=[0.15, 0.15])
1360 ax2.axhline(parameters.YWINDOW, color='k')
1361 plot_image_simple(ax2, data=image.data_rotated[max(0, y0 - 2 * parameters.YWINDOW):
1362 min(y0 + 2 * parameters.YWINDOW, image.data.shape[0]),
1363 margin:-margin],
1364 scale="symlog", title='Turned image (log10 scale)',
1365 units=image.units, target_pixcoords=image.target_pixcoords_rotated, aspect='auto')
1366 ax2.axhline(2 * parameters.YWINDOW, color='k')
1367 f.tight_layout()
1368 if parameters.DISPLAY: # pragma: no cover
1369 plt.show()
1370 if parameters.LSST_SAVEFIGPATH: # pragma: no cover
1371 f.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'rotated_image.pdf'))
1372 return image.rotation_angle
1375if __name__ == "__main__": 1375 ↛ 1376line 1375 didn't jump to line 1376, because the condition on line 1375 was never true
1376 import doctest
1378 doctest.testmod()