Coverage for python/lsst/obs/lsst/translators/lsst.py: 33%
394 statements
« prev ^ index » next coverage.py v7.4.3, created at 2024-02-25 09:36 +0000
« prev ^ index » next coverage.py v7.4.3, created at 2024-02-25 09:36 +0000
1# This file is currently part of obs_lsst but is written to allow it
2# to be migrated to the astro_metadata_translator package at a later date.
3#
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the LICENSE file in this directory for details of code ownership.
7#
8# Use of this source code is governed by a 3-clause BSD-style
9# license that can be found in the LICENSE file.
11"""Metadata translation support code for LSST headers"""
13__all__ = ("TZERO", "SIMONYI_LOCATION", "read_detector_ids",
14 "compute_detector_exposure_id_generic", "LsstBaseTranslator",
15 "SIMONYI_TELESCOPE")
17import os.path
18import yaml
19import logging
20import re
21import datetime
22import hashlib
24import astropy.coordinates
25import astropy.units as u
26from astropy.time import Time, TimeDelta
27from astropy.coordinates import EarthLocation
29from lsst.utils import getPackageDir
31from astro_metadata_translator import cache_translation, FitsTranslator
32from astro_metadata_translator.translators.helpers import tracking_from_degree_headers, \
33 altaz_from_degree_headers
36TZERO = Time("2015-01-01T00:00", format="isot", scale="utc")
37TZERO_DATETIME = TZERO.to_datetime()
39# Delimiter to use for multiple filters/gratings
40FILTER_DELIMITER = "~"
42# Regex to use for parsing a GROUPID string
43GROUP_RE = re.compile(r"^(\d\d\d\d\-\d\d\-\d\dT\d\d:\d\d:\d\d)\.(\d\d\d)(?:[\+#](\d+))?$")
45# LSST Default location in the absence of headers
46SIMONYI_LOCATION = EarthLocation.from_geodetic(-70.749417, -30.244639, 2663.0)
48# Name of the main survey telescope
49SIMONYI_TELESCOPE = "Simonyi Survey Telescope"
51# Supported controller codes.
52# The order here directly relates to the resulting exposure ID
53# calculation. Do not reorder. Add new ones to the end.
54# OCS, CCS, pHosim, P for simulated OCS, Q for simulated CCS, S for
55# simulated images.
56CONTROLLERS = "OCHPQS"
58# Number of decimal digits allocated to the sequence number in exposure_ids.
59_SEQNUM_MAXDIGITS = 5
61# Number of decimal digits allocated to the day of observation (and controller
62# code) in exposure_ids.
63_DAYOBS_MAXDIGITS = 8
65# Value added to day_obs for controllers after the default.
66_CONTROLLER_INCREMENT = 1000_00_00
68# Number of decimal digits used by exposure_ids.
69EXPOSURE_ID_MAXDIGITS = _SEQNUM_MAXDIGITS + _DAYOBS_MAXDIGITS
71obs_lsst_packageDir = getPackageDir("obs_lsst")
73log = logging.getLogger(__name__)
76def read_detector_ids(policyFile):
77 """Read a camera policy file and retrieve the mapping from CCD name
78 to ID.
80 Parameters
81 ----------
82 policyFile : `str`
83 Name of YAML policy file to read, relative to the obs_lsst
84 package.
86 Returns
87 -------
88 mapping : `dict` of `str` to (`int`, `str`)
89 A `dict` with keys being the full names of the detectors, and the
90 value is a `tuple` containing the integer detector number and the
91 detector serial number.
93 Notes
94 -----
95 Reads the camera YAML definition file directly and extracts just the
96 IDs and serials. This routine does not use the standard
97 `~lsst.obs.base.yamlCamera.YAMLCamera` infrastructure or
98 `lsst.afw.cameraGeom`. This is because the translators are intended to
99 have minimal dependencies on LSST infrastructure.
100 """
102 file = os.path.join(obs_lsst_packageDir, policyFile)
103 try:
104 with open(file) as fh:
105 # Use the fast parser since these files are large
106 camera = yaml.load(fh, Loader=yaml.CSafeLoader)
107 except OSError as e:
108 raise ValueError(f"Could not load camera policy file {file}") from e
110 mapping = {}
111 for ccd, value in camera["CCDs"].items():
112 mapping[ccd] = (int(value["id"]), value["serial"])
114 return mapping
117def compute_detector_exposure_id_generic(exposure_id, detector_num, max_num):
118 """Compute the detector_exposure_id from the exposure id and the
119 detector number.
121 Parameters
122 ----------
123 exposure_id : `int`
124 The exposure ID.
125 detector_num : `int`
126 The detector number.
127 max_num : `int`
128 Maximum number of detectors to make space for.
130 Returns
131 -------
132 detector_exposure_id : `int`
133 Computed ID.
135 Raises
136 ------
137 ValueError
138 The detector number is out of range.
139 """
141 if detector_num is None:
142 raise ValueError("Detector number must be defined.")
143 if detector_num >= max_num or detector_num < 0:
144 raise ValueError(f"Detector number out of range 0 <= {detector_num} < {max_num}")
146 return max_num*exposure_id + detector_num
149class LsstBaseTranslator(FitsTranslator):
150 """Translation methods useful for all LSST-style headers."""
152 _const_map = {}
153 _trivial_map = {}
155 # Do not specify a name for this translator
156 cameraPolicyFile = None
157 """Path to policy file relative to obs_lsst root."""
159 detectorMapping = None
160 """Mapping of detector name to detector number and serial."""
162 detectorSerials = None
163 """Mapping of detector serial number to raft, number, and name."""
165 DETECTOR_MAX = 1000
166 """Maximum number of detectors to use when calculating the
167 detector_exposure_id.
169 Note that because this is the maximum number *of* detectors, for
170 zero-based ``detector_num`` values this is one greater than the maximum
171 ``detector_num``. It is also often rounded up to the nearest power of
172 10 anyway, to allow ``detector_exposure_id`` values to be easily decoded by
173 humans.
174 """
176 _DEFAULT_LOCATION = SIMONYI_LOCATION
177 """Default telescope location in absence of relevant FITS headers."""
179 _ROLLOVER_TIME = TimeDelta(12*60*60, scale="tai", format="sec")
180 """Time delta for the definition of a Rubin Observatory start of day.
181 Used when the header is missing. See LSE-400 for details."""
183 @classmethod
184 def __init_subclass__(cls, **kwargs):
185 """Ensure that subclasses clear their own detector mapping entries
186 such that subclasses of translators that use detector mappings
187 do not pick up the incorrect values from a parent."""
189 cls.detectorMapping = None
190 cls.detectorSerials = None
192 super().__init_subclass__(**kwargs)
194 def search_paths(self):
195 """Search paths to use for LSST data when looking for header correction
196 files.
198 Returns
199 -------
200 path : `list`
201 List with a single element containing the full path to the
202 ``corrections`` directory within the ``obs_lsst`` package.
203 """
204 return [os.path.join(obs_lsst_packageDir, "corrections")]
206 @classmethod
207 def compute_detector_exposure_id(cls, exposure_id, detector_num):
208 """Compute the detector exposure ID from detector number and
209 exposure ID.
211 This is a helper method to allow code working outside the translator
212 infrastructure to use the same algorithm.
214 Parameters
215 ----------
216 exposure_id : `int`
217 Unique exposure ID.
218 detector_num : `int`
219 Detector number.
221 Returns
222 -------
223 detector_exposure_id : `int`
224 The calculated ID.
225 """
226 from .._packer import RubinDimensionPacker
228 return RubinDimensionPacker.pack_id_pair(exposure_id, detector_num)
230 @classmethod
231 def max_detector_exposure_id(cls):
232 """The maximum detector exposure ID expected to be generated by
233 this instrument.
235 Returns
236 -------
237 max_id : `int`
238 The maximum value.
239 """
240 max_exposure_id = cls.max_exposure_id()
241 # We subtract 1 from DETECTOR_MAX because LSST detector_num values are
242 # zero-based, and detector_max is the maximum number *of* detectors,
243 # while this returns the (inclusive) maximum ID value.
244 return cls.compute_detector_exposure_id(max_exposure_id, cls.DETECTOR_MAX - 1)
246 @classmethod
247 def max_exposure_id(cls):
248 """The maximum exposure ID expected from this instrument.
250 Returns
251 -------
252 max_exposure_id : `int`
253 The maximum value.
254 """
255 max_date = "2050-12-31T23:59.999"
256 max_seqnum = 99_999
257 # This controller triggers the largest numbers
258 max_controller = CONTROLLERS[-1]
259 return cls.compute_exposure_id(max_date, max_seqnum, max_controller)
261 @classmethod
262 def detector_mapping(cls):
263 """Returns the mapping of full name to detector ID and serial.
265 Returns
266 -------
267 mapping : `dict` of `str`:`tuple`
268 Returns the mapping of full detector name (group+detector)
269 to detector number and serial.
271 Raises
272 ------
273 ValueError
274 Raised if no camera policy file has been registered with this
275 translation class.
277 Notes
278 -----
279 Will construct the mapping if none has previously been constructed.
280 """
281 if cls.cameraPolicyFile is not None:
282 if cls.detectorMapping is None:
283 cls.detectorMapping = read_detector_ids(cls.cameraPolicyFile)
284 else:
285 raise ValueError(f"Translation class '{cls.__name__}' has no registered camera policy file")
287 return cls.detectorMapping
289 @classmethod
290 def detector_serials(cls):
291 """Obtain the mapping of detector serial to detector group, name,
292 and number.
294 Returns
295 -------
296 info : `dict` of `tuple` of (`str`, `str`, `int`)
297 A `dict` with the serial numbers as keys and values of detector
298 group, name, and number.
299 """
300 if cls.detectorSerials is None:
301 detector_mapping = cls.detector_mapping()
303 if detector_mapping is not None:
304 # Form mapping to go from serial number to names/numbers
305 serials = {}
306 for fullname, (id, serial) in cls.detectorMapping.items():
307 raft, detector_name = fullname.split("_")
308 if serial in serials:
309 raise RuntimeError(f"Serial {serial} is defined in multiple places")
310 serials[serial] = (raft, detector_name, id)
311 cls.detectorSerials = serials
312 else:
313 raise RuntimeError("Unable to obtain detector mapping information")
315 return cls.detectorSerials
317 @classmethod
318 def compute_detector_num_from_name(cls, detector_group, detector_name):
319 """Helper method to return the detector number from the name.
321 Parameters
322 ----------
323 detector_group : `str`
324 Name of the detector grouping. This is generally the raft name.
325 detector_name : `str`
326 Detector name.
328 Returns
329 -------
330 num : `int`
331 Detector number.
332 """
333 fullname = f"{detector_group}_{detector_name}"
335 num = None
336 detector_mapping = cls.detector_mapping()
337 if detector_mapping is None:
338 raise RuntimeError("Unable to obtain detector mapping information")
340 if fullname in detector_mapping:
341 num = detector_mapping[fullname]
342 else:
343 log.warning(f"Unable to determine detector number from detector name {fullname}")
344 return None
346 return num[0]
348 @classmethod
349 def compute_detector_info_from_serial(cls, detector_serial):
350 """Helper method to return the detector information from the serial.
352 Parameters
353 ----------
354 detector_serial : `str`
355 Detector serial ID.
357 Returns
358 -------
359 info : `tuple` of (`str`, `str`, `int`)
360 Detector group, name, and number.
361 """
362 serial_mapping = cls.detector_serials()
363 if serial_mapping is None:
364 raise RuntimeError("Unable to obtain serial mapping information")
366 if detector_serial in serial_mapping:
367 info = serial_mapping[detector_serial]
368 else:
369 raise RuntimeError("Unable to determine detector information from detector serial"
370 f" {detector_serial}")
372 return info
374 @staticmethod
375 def compute_exposure_id(dayobs, seqnum, controller=None):
376 """Helper method to calculate the exposure_id.
378 Parameters
379 ----------
380 dayobs : `str` or `int`
381 Day of observation in either YYYYMMDD or YYYY-MM-DD format.
382 If the string looks like ISO format it will be truncated before the
383 ``T`` before being handled.
384 seqnum : `int` or `str`
385 Sequence number.
386 controller : `str`, optional
387 Controller to use. If this is "O", no change is made to the
388 exposure ID. If it is "C" a 1000 is added to the year component
389 of the exposure ID. If it is "H" a 2000 is added to the year
390 component. This sequence continues with "P" and "Q" controllers.
391 `None` indicates that the controller is not relevant to the
392 exposure ID calculation (generally this is the case for test
393 stand data).
395 Returns
396 -------
397 exposure_id : `int`
398 Exposure ID in form YYYYMMDDnnnnn form.
399 """
400 # We really want an integer but the checks require a str.
401 if isinstance(dayobs, int):
402 dayobs = str(dayobs)
404 if "T" in dayobs:
405 dayobs = dayobs[:dayobs.find("T")]
407 dayobs = dayobs.replace("-", "")
409 if len(dayobs) != 8:
410 raise ValueError(f"Malformed dayobs: {dayobs}")
412 # Expect no more than 99,999 exposures in a day
413 if seqnum >= 10**_SEQNUM_MAXDIGITS:
414 raise ValueError(f"Sequence number ({seqnum}) exceeds limit")
416 dayobs = int(dayobs)
417 if dayobs > 20231004 and controller == "C":
418 # As of this date the CCS controller has a unified counter
419 # with the OCS, so there is no need to adjust the dayobs
420 # to make unique exposure IDs.
421 controller = None
423 # Camera control changes the exposure ID
424 if controller is not None:
425 index = CONTROLLERS.find(controller)
426 if index == -1:
427 raise ValueError(f"Supplied controller, '{controller}' is not "
428 f"in supported list: {CONTROLLERS}")
430 # Increment a thousand years per controller
431 dayobs += _CONTROLLER_INCREMENT * index
433 # Form the number as a string zero padding the sequence number
434 idstr = f"{dayobs}{seqnum:0{_SEQNUM_MAXDIGITS}d}"
436 # Exposure ID has to be an integer
437 return int(idstr)
439 @staticmethod
440 def unpack_exposure_id(exposure_id):
441 """Unpack an exposure ID into dayobs, seqnum, and controller.
443 Parameters
444 ----------
445 exposure_id : `int`
446 Integer exposure ID produced by `compute_exposure_id`.
448 Returns
449 -------
450 dayobs : `str`
451 Day of observation as a YYYYMMDD string.
452 seqnum : `int`
453 Sequence number.
454 controller : `str`
455 Controller code. Will be ``O`` (but should be ignored) for IDs
456 produced by calling `compute_exposure_id` with ``controller=None``.
457 """
458 dayobs, seqnum = divmod(exposure_id, 10**_SEQNUM_MAXDIGITS)
459 controller_index = dayobs // _CONTROLLER_INCREMENT - 2
460 dayobs -= controller_index * _CONTROLLER_INCREMENT
461 return (str(dayobs), seqnum, CONTROLLERS[controller_index], )
463 def _is_on_mountain(self):
464 """Indicate whether these data are coming from the instrument
465 installed on the mountain.
467 Returns
468 -------
469 is : `bool`
470 `True` if instrument is on the mountain.
471 """
472 if "TSTAND" in self._header:
473 return False
474 return True
476 def is_on_sky(self):
477 """Determine if this is an on-sky observation.
479 Returns
480 -------
481 is_on_sky : `bool`
482 Returns True if this is a observation on sky on the
483 summit.
484 """
485 # For LSST we think on sky unless tracksys is local
486 if self.is_key_ok("TRACKSYS"):
487 if self._header["TRACKSYS"].lower() == "local":
488 # not on sky
489 return False
491 # These are obviously not on sky
492 if self.to_observation_type() in ("bias", "dark", "flat"):
493 return False
495 return self._is_on_mountain()
497 @cache_translation
498 def to_location(self):
499 # Docstring will be inherited. Property defined in properties.py
500 if not self._is_on_mountain():
501 return None
502 try:
503 # Try standard FITS headers
504 return super().to_location()
505 except KeyError:
506 return self._DEFAULT_LOCATION
508 @cache_translation
509 def to_datetime_begin(self):
510 # Docstring will be inherited. Property defined in properties.py
511 self._used_these_cards("MJD-OBS")
512 return Time(self._header["MJD-OBS"], scale="tai", format="mjd")
514 @cache_translation
515 def to_datetime_end(self):
516 # Docstring will be inherited. Property defined in properties.py
517 if self.is_key_ok("DATE-END"):
518 return super().to_datetime_end()
520 return self.to_datetime_begin() + self.to_exposure_time()
522 @cache_translation
523 def to_detector_num(self):
524 # Docstring will be inherited. Property defined in properties.py
525 raft = self.to_detector_group()
526 detector = self.to_detector_name()
527 return self.compute_detector_num_from_name(raft, detector)
529 @cache_translation
530 def to_detector_exposure_id(self):
531 # Docstring will be inherited. Property defined in properties.py
532 exposure_id = self.to_exposure_id()
533 num = self.to_detector_num()
534 return self.compute_detector_exposure_id(exposure_id, num)
536 @cache_translation
537 def to_observation_type(self):
538 # Docstring will be inherited. Property defined in properties.py
539 obstype = self._header["IMGTYPE"]
540 self._used_these_cards("IMGTYPE")
541 obstype = obstype.lower()
542 if obstype in ("skyexp", "object"):
543 obstype = "science"
544 return obstype
546 @cache_translation
547 def to_observation_reason(self):
548 # Docstring will be inherited. Property defined in properties.py
549 for key in ("REASON", "TESTTYPE"):
550 if self.is_key_ok(key):
551 reason = self._header[key]
552 self._used_these_cards(key)
553 return reason.lower()
554 # no specific header present so use the default translation
555 return super().to_observation_reason()
557 @cache_translation
558 def to_dark_time(self):
559 """Calculate the dark time.
561 If a DARKTIME header is not found, the value is assumed to be
562 identical to the exposure time.
564 Returns
565 -------
566 dark : `astropy.units.Quantity`
567 The dark time in seconds.
568 """
569 if self.is_key_ok("DARKTIME"):
570 darktime = self._header["DARKTIME"]*u.s
571 self._used_these_cards("DARKTIME")
572 else:
573 log.warning("%s: Unable to determine dark time. Setting from exposure time.",
574 self._log_prefix)
575 darktime = self.to_exposure_time()
576 return darktime
578 @cache_translation
579 def to_exposure_id(self):
580 """Generate a unique exposure ID number
582 This is a combination of DAYOBS and SEQNUM, and optionally
583 CONTRLLR.
585 Returns
586 -------
587 exposure_id : `int`
588 Unique exposure number.
589 """
590 if "CALIB_ID" in self._header:
591 self._used_these_cards("CALIB_ID")
592 return None
594 dayobs = self._header["DAYOBS"]
595 seqnum = self._header["SEQNUM"]
596 self._used_these_cards("DAYOBS", "SEQNUM")
598 if self.is_key_ok("CONTRLLR"):
599 controller = self._header["CONTRLLR"]
600 self._used_these_cards("CONTRLLR")
601 else:
602 controller = None
604 return self.compute_exposure_id(dayobs, seqnum, controller=controller)
606 @cache_translation
607 def to_visit_id(self):
608 """Calculate the visit associated with this exposure.
610 Notes
611 -----
612 For LATISS and LSSTCam the default visit is derived from the
613 exposure group. For other instruments we return the exposure_id.
614 """
616 exposure_group = self.to_exposure_group()
617 # If the group is an int we return it
618 try:
619 visit_id = int(exposure_group)
620 return visit_id
621 except ValueError:
622 pass
624 # A Group is defined as ISO date with an extension
625 # The integer must be the same for a given group so we can never
626 # use datetime_begin.
627 # Nominally a GROUPID looks like "ISODATE+N" where the +N is
628 # optional. This can be converted to seconds since epoch with
629 # an adjustment for N.
630 # For early data lacking that form we hash the group and return
631 # the int.
632 matches_date = GROUP_RE.match(exposure_group)
633 if matches_date:
634 iso_str = matches_date.group(1)
635 fraction = matches_date.group(2)
636 n = matches_date.group(3)
637 if n is not None:
638 n = int(n)
639 else:
640 n = 0
641 iso = datetime.datetime.strptime(iso_str, "%Y-%m-%dT%H:%M:%S")
643 tdelta = iso - TZERO_DATETIME
644 epoch = int(tdelta.total_seconds())
646 # Form the integer from EPOCH + 3 DIGIT FRAC + 0-pad N
647 visit_id = int(f"{epoch}{fraction}{n:04d}")
648 else:
649 # Non-standard string so convert to numbers
650 # using a hash function. Use the first N hex digits
651 group_bytes = exposure_group.encode("us-ascii")
652 hasher = hashlib.blake2b(group_bytes)
653 # Need to be big enough it does not possibly clash with the
654 # date-based version above
655 digest = hasher.hexdigest()[:14]
656 visit_id = int(digest, base=16)
658 # To help with hash collision, append the string length
659 visit_id = int(f"{visit_id}{len(exposure_group):02d}")
661 return visit_id
663 @cache_translation
664 def to_physical_filter(self):
665 """Calculate the physical filter name.
667 Returns
668 -------
669 filter : `str`
670 Name of filter. Can be a combination of FILTER, FILTER1 and FILTER2
671 headers joined by a "~". Returns "unknown" if no filter is declared
672 """
673 joined = self._join_keyword_values(["FILTER", "FILTER1", "FILTER2"], delim=FILTER_DELIMITER)
674 if not joined:
675 joined = "unknown"
677 # Replace instances of "NONE" with "none".
678 joined = joined.replace("NONE", "none")
680 return joined
682 @cache_translation
683 def to_tracking_radec(self):
684 # RA/DEC are *derived* headers and for the case where the DATE-BEG
685 # is 1970 they are garbage and should not be used.
686 try:
687 if self._header["DATE-OBS"] == self._header["DATE"]:
688 # A fixed up date -- use AZEL as source of truth
689 altaz = self.to_altaz_begin()
690 radec = astropy.coordinates.SkyCoord(altaz.transform_to(astropy.coordinates.ICRS()),
691 obstime=altaz.obstime,
692 location=altaz.location)
693 else:
694 radecsys = ("RADESYS",)
695 radecpairs = (("RASTART", "DECSTART"), ("RA", "DEC"))
696 radec = tracking_from_degree_headers(self, radecsys, radecpairs)
697 except Exception:
698 # If this observation was not formally on sky then we are allowed
699 # to return None.
700 if self.is_on_sky():
701 raise
702 radec = None
704 return radec
706 @cache_translation
707 def to_altaz_begin(self):
708 if not self._is_on_mountain():
709 return None
711 # Always attempt to find the alt/az values regardless of observation
712 # type.
713 return altaz_from_degree_headers(self, (("ELSTART", "AZSTART"),),
714 self.to_datetime_begin(), is_zd=False)
716 @cache_translation
717 def to_exposure_group(self):
718 """Calculate the exposure group string.
720 For LSSTCam and LATISS this is read from the ``GROUPID`` header.
721 If that header is missing the exposure_id is returned instead as
722 a string.
723 """
724 if self.is_key_ok("GROUPID"):
725 exposure_group = self._header["GROUPID"]
726 self._used_these_cards("GROUPID")
727 return exposure_group
728 return super().to_exposure_group()
730 @cache_translation
731 def to_focus_z(self):
732 """Return the defocal distance of the camera in units of mm.
733 If there is no ``FOCUSZ`` value in the header it will return
734 the default 0.0mm value.
736 Returns
737 -------
738 focus_z: `astropy.units.Quantity`
739 The defocal distance from header in mm or the 0.0mm default
740 """
741 if self.is_key_ok("FOCUSZ"):
742 focus_z = self._header["FOCUSZ"]
743 return focus_z * u.mm
744 return super().to_focus_z()
746 @staticmethod
747 def _is_filter_empty(filter):
748 """Return true if the supplied filter indicates an empty filter slot
750 Parameters
751 ----------
752 filter : `str`
753 The filter string to check.
755 Returns
756 -------
757 is_empty : `bool`
758 `True` if the filter string looks like it is referring to an
759 empty filter slot. For example this can be if the filter is
760 "empty" or "empty_2".
761 """
762 return bool(re.match(r"empty_?\d*$", filter.lower()))
764 def _determine_primary_filter(self):
765 """Determine the primary filter from the ``FILTER`` header.
767 Returns
768 -------
769 filter : `str`
770 The contents of the ``FILTER`` header with some appropriate
771 defaulting.
772 """
774 if self.is_key_ok("FILTER"):
775 physical_filter = self._header["FILTER"]
776 self._used_these_cards("FILTER")
778 if self._is_filter_empty(physical_filter):
779 physical_filter = "empty"
780 else:
781 # Be explicit about having no knowledge of the filter
782 # by setting it to "unknown". It should always have a value.
783 physical_filter = "unknown"
785 # Warn if the filter being unknown is important
786 obstype = self.to_observation_type()
787 if obstype not in ("bias", "dark"):
788 log.warning("%s: Unable to determine the filter",
789 self._log_prefix)
791 return physical_filter
793 @cache_translation
794 def to_observing_day(self):
795 """Return the day of observation as YYYYMMDD integer.
797 For LSSTCam and other compliant instruments this is the value
798 of the DAYOBS header.
800 Returns
801 -------
802 obs_day : `int`
803 The day of observation.
804 """
805 if self.is_key_ok("DAYOBS"):
806 self._used_these_cards("DAYOBS")
807 return int(self._header["DAYOBS"])
809 # Calculate it ourselves correcting for the Rubin offset
810 date = self.to_datetime_begin().tai
811 date -= self._ROLLOVER_TIME
812 return int(date.strftime("%Y%m%d"))
814 @cache_translation
815 def to_observation_counter(self):
816 """Return the sequence number within the observing day.
818 Returns
819 -------
820 counter : `int`
821 The sequence number for this day.
822 """
823 if self.is_key_ok("SEQNUM"):
824 # Some older LATISS data may not have the header
825 # but this is corrected in fix_header for LATISS.
826 self._used_these_cards("SEQNUM")
827 return int(self._header["SEQNUM"])
829 # This indicates a problem so we warn and return a 0
830 log.warning("%s: Unable to determine the observation counter so returning 0",
831 self._log_prefix)
832 return 0
834 @cache_translation
835 def to_boresight_rotation_coord(self):
836 """Boresight rotation angle.
838 Only relevant for science observations.
839 """
840 unknown = "unknown"
841 if not self.is_on_sky():
842 return unknown
844 self._used_these_cards("ROTCOORD")
845 coord = self._header.get("ROTCOORD", unknown)
846 if coord is None:
847 coord = unknown
848 return coord
850 @cache_translation
851 def to_boresight_airmass(self):
852 """Calculate airmass at boresight at start of observation.
854 Notes
855 -----
856 Early data are missing AMSTART header so we fall back to calculating
857 it from ELSTART.
858 """
859 if not self.is_on_sky():
860 return None
862 # This observation should have AMSTART
863 amkey = "AMSTART"
864 if self.is_key_ok(amkey):
865 self._used_these_cards(amkey)
866 return self._header[amkey]
868 # Instead we need to look at azel
869 altaz = self.to_altaz_begin()
870 if altaz is not None:
871 return altaz.secz.to_value()
873 log.warning("%s: Unable to determine airmass of a science observation, returning 1.",
874 self._log_prefix)
875 return 1.0
877 @cache_translation
878 def to_group_counter_start(self):
879 # Effectively the start of the visit as determined by the headers.
880 counter = self.to_observation_counter()
881 # Older data does not have the CURINDEX header.
882 if self.is_key_ok("CURINDEX"):
883 # CURINDEX is 1-based.
884 seq_start = counter - self._header["CURINDEX"] + 1
885 self._used_these_cards("CURINDEX")
886 return seq_start
887 else:
888 # If the counter is 0 we need to pick something else
889 # that is not going to confuse the visit calculation
890 # (since setting everything to 0 will make one big visit).
891 return counter if counter != 0 else self.to_exposure_id()
893 @cache_translation
894 def to_group_counter_end(self):
895 # Effectively the end of the visit as determined by the headers.
896 counter = self.to_observation_counter()
897 # Older data does not have the CURINDEX or MAXINDEX headers.
898 if self.is_key_ok("CURINDEX") and self.is_key_ok("MAXINDEX"):
899 # CURINDEX is 1-based. CURINDEX == MAXINDEX indicates the
900 # final exposure in the sequence.
901 remaining = self._header["MAXINDEX"] - self._header["CURINDEX"]
902 seq_end = counter + remaining
903 self._used_these_cards("CURINDEX", "MAXINDEX")
904 return seq_end
905 else:
906 # If the counter is 0 we need to pick something else
907 # that is not going to confuse the visit calculation
908 # (since setting everything to 0 will make one big visit).
909 return counter if counter != 0 else self.to_exposure_id()
911 @cache_translation
912 def to_has_simulated_content(self):
913 # Check all the simulation flags.
914 # We do not know all the simulation flags that we may have so
915 # must check every header key. Ideally HIERARCH SIMULATE would
916 # be a hierarchical header so _header["SIMULATE"] would return
917 # everything. The header looks like:
918 #
919 # HIERARCH SIMULATE ATMCS = / ATMCS Simulation Mode
920 # HIERARCH SIMULATE ATHEXAPOD = 0 / ATHexapod Simulation Mode
921 # HIERARCH SIMULATE ATPNEUMATICS = / ATPneumatics Simulation Mode
922 # HIERARCH SIMULATE ATDOME = 1 / ATDome Simulation Mode
923 # HIERARCH SIMULATE ATSPECTROGRAPH = 0 / ATSpectrograph Simulation Mode
924 #
925 # So any header that includes "SIMULATE" in the key name and has a
926 # true value implies that something in the data is simulated.
927 for k, v in self._header.items():
928 if "SIMULATE" in k and v:
929 return True
931 # If the controller is H, P, or Q then the data are simulated.
932 ctrlr_key = "CONTRLLR"
933 if self.is_key_ok(ctrlr_key):
934 controller = self._header[ctrlr_key]
935 self._used_these_cards(ctrlr_key)
936 if controller in "HPQ":
937 return True
939 # No simulation flags set.
940 return False
942 @cache_translation
943 def to_relative_humidity(self) -> float | None:
944 key = "HUMIDITY"
945 if self.is_key_ok(key):
946 self._used_these_cards(key)
947 return self._header[key]
949 return None
951 @cache_translation
952 def to_pressure(self):
953 key = "PRESSURE"
954 if self.is_key_ok(key):
955 value = self._header[key]
956 # There has been an inconsistency in units for the pressure reading
957 # so we need to adjust for this.
958 if value > 10_000:
959 unit = u.Pa
960 else:
961 unit = u.hPa
962 return value * unit
964 return None
966 @cache_translation
967 def to_temperature(self):
968 key = "AIRTEMP"
969 if self.is_key_ok(key):
970 return self._header[key] * u.deg_C
971 return None