Coverage for python/lsst/obs/lsst/translators/lsst.py: 25%
368 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-11 03:03 -0700
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-11 03:03 -0700
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.
55CONTROLLERS = "OCHPQ"
57# Number of decimal digits allocated to the sequence number in exposure_ids.
58_SEQNUM_MAXDIGITS = 5
60# Number of decimal digits allocated to the day of observation (and controller
61# code) in exposure_ids.
62_DAYOBS_MAXDIGITS = 8
64# Value added to day_obs for controllers after the default.
65_CONTROLLER_INCREMENT = 1000_00_00
67# Number of decimal digits used by exposure_ids.
68EXPOSURE_ID_MAXDIGITS = _SEQNUM_MAXDIGITS + _DAYOBS_MAXDIGITS
70obs_lsst_packageDir = getPackageDir("obs_lsst")
72log = logging.getLogger(__name__)
75def read_detector_ids(policyFile):
76 """Read a camera policy file and retrieve the mapping from CCD name
77 to ID.
79 Parameters
80 ----------
81 policyFile : `str`
82 Name of YAML policy file to read, relative to the obs_lsst
83 package.
85 Returns
86 -------
87 mapping : `dict` of `str` to (`int`, `str`)
88 A `dict` with keys being the full names of the detectors, and the
89 value is a `tuple` containing the integer detector number and the
90 detector serial number.
92 Notes
93 -----
94 Reads the camera YAML definition file directly and extracts just the
95 IDs and serials. This routine does not use the standard
96 `~lsst.obs.base.yamlCamera.YAMLCamera` infrastructure or
97 `lsst.afw.cameraGeom`. This is because the translators are intended to
98 have minimal dependencies on LSST infrastructure.
99 """
101 file = os.path.join(obs_lsst_packageDir, policyFile)
102 try:
103 with open(file) as fh:
104 # Use the fast parser since these files are large
105 camera = yaml.load(fh, Loader=yaml.CSafeLoader)
106 except OSError as e:
107 raise ValueError(f"Could not load camera policy file {file}") from e
109 mapping = {}
110 for ccd, value in camera["CCDs"].items():
111 mapping[ccd] = (int(value["id"]), value["serial"])
113 return mapping
116def compute_detector_exposure_id_generic(exposure_id, detector_num, max_num):
117 """Compute the detector_exposure_id from the exposure id and the
118 detector number.
120 Parameters
121 ----------
122 exposure_id : `int`
123 The exposure ID.
124 detector_num : `int`
125 The detector number.
126 max_num : `int`
127 Maximum number of detectors to make space for.
129 Returns
130 -------
131 detector_exposure_id : `int`
132 Computed ID.
134 Raises
135 ------
136 ValueError
137 The detector number is out of range.
138 """
140 if detector_num is None:
141 raise ValueError("Detector number must be defined.")
142 if detector_num >= max_num or detector_num < 0:
143 raise ValueError(f"Detector number out of range 0 <= {detector_num} < {max_num}")
145 return max_num*exposure_id + detector_num
148class LsstBaseTranslator(FitsTranslator):
149 """Translation methods useful for all LSST-style headers."""
151 _const_map = {}
152 _trivial_map = {}
154 # Do not specify a name for this translator
155 cameraPolicyFile = None
156 """Path to policy file relative to obs_lsst root."""
158 detectorMapping = None
159 """Mapping of detector name to detector number and serial."""
161 detectorSerials = None
162 """Mapping of detector serial number to raft, number, and name."""
164 DETECTOR_MAX = 1000
165 """Maximum number of detectors to use when calculating the
166 detector_exposure_id.
168 Note that because this is the maximum number *of* detectors, for
169 zero-based ``detector_num`` values this is one greater than the maximum
170 ``detector_num``. It is also often rounded up to the nearest power of
171 10 anyway, to allow ``detector_exposure_id`` values to be easily decoded by
172 humans.
173 """
175 _DEFAULT_LOCATION = SIMONYI_LOCATION
176 """Default telescope location in absence of relevant FITS headers."""
178 _ROLLOVER_TIME = TimeDelta(12*60*60, scale="tai", format="sec")
179 """Time delta for the definition of a Rubin Observatory start of day.
180 Used when the header is missing. See LSE-400 for details."""
182 @classmethod
183 def __init_subclass__(cls, **kwargs):
184 """Ensure that subclasses clear their own detector mapping entries
185 such that subclasses of translators that use detector mappings
186 do not pick up the incorrect values from a parent."""
188 cls.detectorMapping = None
189 cls.detectorSerials = None
191 super().__init_subclass__(**kwargs)
193 def search_paths(self):
194 """Search paths to use for LSST data when looking for header correction
195 files.
197 Returns
198 -------
199 path : `list`
200 List with a single element containing the full path to the
201 ``corrections`` directory within the ``obs_lsst`` package.
202 """
203 return [os.path.join(obs_lsst_packageDir, "corrections")]
205 @classmethod
206 def compute_detector_exposure_id(cls, exposure_id, detector_num):
207 """Compute the detector exposure ID from detector number and
208 exposure ID.
210 This is a helper method to allow code working outside the translator
211 infrastructure to use the same algorithm.
213 Parameters
214 ----------
215 exposure_id : `int`
216 Unique exposure ID.
217 detector_num : `int`
218 Detector number.
220 Returns
221 -------
222 detector_exposure_id : `int`
223 The calculated ID.
224 """
225 from .._packer import RubinDimensionPacker
227 return RubinDimensionPacker.pack_id_pair(exposure_id, detector_num)
229 @classmethod
230 def max_detector_exposure_id(cls):
231 """The maximum detector exposure ID expected to be generated by
232 this instrument.
234 Returns
235 -------
236 max_id : `int`
237 The maximum value.
238 """
239 max_exposure_id = cls.max_exposure_id()
240 # We subtract 1 from DETECTOR_MAX because LSST detector_num values are
241 # zero-based, and detector_max is the maximum number *of* detectors,
242 # while this returns the (inclusive) maximum ID value.
243 return cls.compute_detector_exposure_id(max_exposure_id, cls.DETECTOR_MAX - 1)
245 @classmethod
246 def max_exposure_id(cls):
247 """The maximum exposure ID expected from this instrument.
249 Returns
250 -------
251 max_exposure_id : `int`
252 The maximum value.
253 """
254 max_date = "2050-12-31T23:59.999"
255 max_seqnum = 99_999
256 # This controller triggers the largest numbers
257 max_controller = CONTROLLERS[-1]
258 return cls.compute_exposure_id(max_date, max_seqnum, max_controller)
260 @classmethod
261 def detector_mapping(cls):
262 """Returns the mapping of full name to detector ID and serial.
264 Returns
265 -------
266 mapping : `dict` of `str`:`tuple`
267 Returns the mapping of full detector name (group+detector)
268 to detector number and serial.
270 Raises
271 ------
272 ValueError
273 Raised if no camera policy file has been registered with this
274 translation class.
276 Notes
277 -----
278 Will construct the mapping if none has previously been constructed.
279 """
280 if cls.cameraPolicyFile is not None:
281 if cls.detectorMapping is None:
282 cls.detectorMapping = read_detector_ids(cls.cameraPolicyFile)
283 else:
284 raise ValueError(f"Translation class '{cls.__name__}' has no registered camera policy file")
286 return cls.detectorMapping
288 @classmethod
289 def detector_serials(cls):
290 """Obtain the mapping of detector serial to detector group, name,
291 and number.
293 Returns
294 -------
295 info : `dict` of `tuple` of (`str`, `str`, `int`)
296 A `dict` with the serial numbers as keys and values of detector
297 group, name, and number.
298 """
299 if cls.detectorSerials is None:
300 detector_mapping = cls.detector_mapping()
302 if detector_mapping is not None:
303 # Form mapping to go from serial number to names/numbers
304 serials = {}
305 for fullname, (id, serial) in cls.detectorMapping.items():
306 raft, detector_name = fullname.split("_")
307 if serial in serials:
308 raise RuntimeError(f"Serial {serial} is defined in multiple places")
309 serials[serial] = (raft, detector_name, id)
310 cls.detectorSerials = serials
311 else:
312 raise RuntimeError("Unable to obtain detector mapping information")
314 return cls.detectorSerials
316 @classmethod
317 def compute_detector_num_from_name(cls, detector_group, detector_name):
318 """Helper method to return the detector number from the name.
320 Parameters
321 ----------
322 detector_group : `str`
323 Name of the detector grouping. This is generally the raft name.
324 detector_name : `str`
325 Detector name.
327 Returns
328 -------
329 num : `int`
330 Detector number.
331 """
332 fullname = f"{detector_group}_{detector_name}"
334 num = None
335 detector_mapping = cls.detector_mapping()
336 if detector_mapping is None:
337 raise RuntimeError("Unable to obtain detector mapping information")
339 if fullname in detector_mapping:
340 num = detector_mapping[fullname]
341 else:
342 log.warning(f"Unable to determine detector number from detector name {fullname}")
343 return None
345 return num[0]
347 @classmethod
348 def compute_detector_info_from_serial(cls, detector_serial):
349 """Helper method to return the detector information from the serial.
351 Parameters
352 ----------
353 detector_serial : `str`
354 Detector serial ID.
356 Returns
357 -------
358 info : `tuple` of (`str`, `str`, `int`)
359 Detector group, name, and number.
360 """
361 serial_mapping = cls.detector_serials()
362 if serial_mapping is None:
363 raise RuntimeError("Unable to obtain serial mapping information")
365 if detector_serial in serial_mapping:
366 info = serial_mapping[detector_serial]
367 else:
368 raise RuntimeError("Unable to determine detector information from detector serial"
369 f" {detector_serial}")
371 return info
373 @staticmethod
374 def compute_exposure_id(dayobs, seqnum, controller=None):
375 """Helper method to calculate the exposure_id.
377 Parameters
378 ----------
379 dayobs : `str` or `int`
380 Day of observation in either YYYYMMDD or YYYY-MM-DD format.
381 If the string looks like ISO format it will be truncated before the
382 ``T`` before being handled.
383 seqnum : `int` or `str`
384 Sequence number.
385 controller : `str`, optional
386 Controller to use. If this is "O", no change is made to the
387 exposure ID. If it is "C" a 1000 is added to the year component
388 of the exposure ID. If it is "H" a 2000 is added to the year
389 component. This sequence continues with "P" and "Q" controllers.
390 `None` indicates that the controller is not relevant to the
391 exposure ID calculation (generally this is the case for test
392 stand data).
394 Returns
395 -------
396 exposure_id : `int`
397 Exposure ID in form YYYYMMDDnnnnn form.
398 """
399 # We really want an integer but the checks require a str.
400 if isinstance(dayobs, int):
401 dayobs = str(dayobs)
403 if "T" in dayobs:
404 dayobs = dayobs[:dayobs.find("T")]
406 dayobs = dayobs.replace("-", "")
408 if len(dayobs) != 8:
409 raise ValueError(f"Malformed dayobs: {dayobs}")
411 # Expect no more than 99,999 exposures in a day
412 if seqnum >= 10**_SEQNUM_MAXDIGITS:
413 raise ValueError(f"Sequence number ({seqnum}) exceeds limit")
415 # Camera control changes the exposure ID
416 if controller is not None:
417 index = CONTROLLERS.find(controller)
418 if index == -1:
419 raise ValueError(f"Supplied controller, '{controller}' is not "
420 f"in supported list: {CONTROLLERS}")
421 dayobs = int(dayobs)
422 # Increment a thousand years per controller
423 dayobs += _CONTROLLER_INCREMENT * index
425 # Form the number as a string zero padding the sequence number
426 idstr = f"{dayobs}{seqnum:0{_SEQNUM_MAXDIGITS}d}"
428 # Exposure ID has to be an integer
429 return int(idstr)
431 @staticmethod
432 def unpack_exposure_id(exposure_id):
433 """Unpack an exposure ID into dayobs, seqnum, and controller.
435 Parameters
436 ----------
437 exposure_id : `int`
438 Integer exposure ID produced by `compute_exposure_id`.
440 Returns
441 -------
442 dayobs : `str`
443 Day of observation as a YYYYMMDD string.
444 seqnum : `int`
445 Sequence number.
446 controller : `str`
447 Controller code. Will be `O` (but should be ignored) for IDs
448 produced by calling `compute_exposure_id` with ``controller=None`.
449 """
450 dayobs, seqnum = divmod(exposure_id, 10**_SEQNUM_MAXDIGITS)
451 controller_index = dayobs // _CONTROLLER_INCREMENT - 2
452 dayobs -= controller_index * _CONTROLLER_INCREMENT
453 return (str(dayobs), seqnum, CONTROLLERS[controller_index], )
455 def _is_on_mountain(self):
456 """Indicate whether these data are coming from the instrument
457 installed on the mountain.
459 Returns
460 -------
461 is : `bool`
462 `True` if instrument is on the mountain.
463 """
464 if "TSTAND" in self._header:
465 return False
466 return True
468 def is_on_sky(self):
469 """Determine if this is an on-sky observation.
471 Returns
472 -------
473 is_on_sky : `bool`
474 Returns True if this is a observation on sky on the
475 summit.
476 """
477 # For LSST we think on sky unless tracksys is local
478 if self.is_key_ok("TRACKSYS"):
479 if self._header["TRACKSYS"].lower() == "local":
480 # not on sky
481 return False
483 # These are obviously not on sky
484 if self.to_observation_type() in ("bias", "dark", "flat"):
485 return False
487 return self._is_on_mountain()
489 @cache_translation
490 def to_location(self):
491 # Docstring will be inherited. Property defined in properties.py
492 if not self._is_on_mountain():
493 return None
494 try:
495 # Try standard FITS headers
496 return super().to_location()
497 except KeyError:
498 return self._DEFAULT_LOCATION
500 @cache_translation
501 def to_datetime_begin(self):
502 # Docstring will be inherited. Property defined in properties.py
503 self._used_these_cards("MJD-OBS")
504 return Time(self._header["MJD-OBS"], scale="tai", format="mjd")
506 @cache_translation
507 def to_datetime_end(self):
508 # Docstring will be inherited. Property defined in properties.py
509 if self.is_key_ok("DATE-END"):
510 return super().to_datetime_end()
512 return self.to_datetime_begin() + self.to_exposure_time()
514 @cache_translation
515 def to_detector_num(self):
516 # Docstring will be inherited. Property defined in properties.py
517 raft = self.to_detector_group()
518 detector = self.to_detector_name()
519 return self.compute_detector_num_from_name(raft, detector)
521 @cache_translation
522 def to_detector_exposure_id(self):
523 # Docstring will be inherited. Property defined in properties.py
524 exposure_id = self.to_exposure_id()
525 num = self.to_detector_num()
526 return self.compute_detector_exposure_id(exposure_id, num)
528 @cache_translation
529 def to_observation_type(self):
530 # Docstring will be inherited. Property defined in properties.py
531 obstype = self._header["IMGTYPE"]
532 self._used_these_cards("IMGTYPE")
533 obstype = obstype.lower()
534 if obstype in ("skyexp", "object"):
535 obstype = "science"
536 return obstype
538 @cache_translation
539 def to_observation_reason(self):
540 # Docstring will be inherited. Property defined in properties.py
541 for key in ("REASON", "TESTTYPE"):
542 if self.is_key_ok(key):
543 reason = self._header[key]
544 self._used_these_cards(key)
545 return reason.lower()
546 # no specific header present so use the default translation
547 return super().to_observation_reason()
549 @cache_translation
550 def to_dark_time(self):
551 """Calculate the dark time.
553 If a DARKTIME header is not found, the value is assumed to be
554 identical to the exposure time.
556 Returns
557 -------
558 dark : `astropy.units.Quantity`
559 The dark time in seconds.
560 """
561 if self.is_key_ok("DARKTIME"):
562 darktime = self._header["DARKTIME"]*u.s
563 self._used_these_cards("DARKTIME")
564 else:
565 log.warning("%s: Unable to determine dark time. Setting from exposure time.",
566 self._log_prefix)
567 darktime = self.to_exposure_time()
568 return darktime
570 @cache_translation
571 def to_exposure_id(self):
572 """Generate a unique exposure ID number
574 This is a combination of DAYOBS and SEQNUM, and optionally
575 CONTRLLR.
577 Returns
578 -------
579 exposure_id : `int`
580 Unique exposure number.
581 """
582 if "CALIB_ID" in self._header:
583 self._used_these_cards("CALIB_ID")
584 return None
586 dayobs = self._header["DAYOBS"]
587 seqnum = self._header["SEQNUM"]
588 self._used_these_cards("DAYOBS", "SEQNUM")
590 if self.is_key_ok("CONTRLLR"):
591 controller = self._header["CONTRLLR"]
592 self._used_these_cards("CONTRLLR")
593 else:
594 controller = None
596 return self.compute_exposure_id(dayobs, seqnum, controller=controller)
598 @cache_translation
599 def to_visit_id(self):
600 """Calculate the visit associated with this exposure.
602 Notes
603 -----
604 For LATISS and LSSTCam the default visit is derived from the
605 exposure group. For other instruments we return the exposure_id.
606 """
608 exposure_group = self.to_exposure_group()
609 # If the group is an int we return it
610 try:
611 visit_id = int(exposure_group)
612 return visit_id
613 except ValueError:
614 pass
616 # A Group is defined as ISO date with an extension
617 # The integer must be the same for a given group so we can never
618 # use datetime_begin.
619 # Nominally a GROUPID looks like "ISODATE+N" where the +N is
620 # optional. This can be converted to seconds since epoch with
621 # an adjustment for N.
622 # For early data lacking that form we hash the group and return
623 # the int.
624 matches_date = GROUP_RE.match(exposure_group)
625 if matches_date:
626 iso_str = matches_date.group(1)
627 fraction = matches_date.group(2)
628 n = matches_date.group(3)
629 if n is not None:
630 n = int(n)
631 else:
632 n = 0
633 iso = datetime.datetime.strptime(iso_str, "%Y-%m-%dT%H:%M:%S")
635 tdelta = iso - TZERO_DATETIME
636 epoch = int(tdelta.total_seconds())
638 # Form the integer from EPOCH + 3 DIGIT FRAC + 0-pad N
639 visit_id = int(f"{epoch}{fraction}{n:04d}")
640 else:
641 # Non-standard string so convert to numbers
642 # using a hash function. Use the first N hex digits
643 group_bytes = exposure_group.encode("us-ascii")
644 hasher = hashlib.blake2b(group_bytes)
645 # Need to be big enough it does not possibly clash with the
646 # date-based version above
647 digest = hasher.hexdigest()[:14]
648 visit_id = int(digest, base=16)
650 # To help with hash collision, append the string length
651 visit_id = int(f"{visit_id}{len(exposure_group):02d}")
653 return visit_id
655 @cache_translation
656 def to_physical_filter(self):
657 """Calculate the physical filter name.
659 Returns
660 -------
661 filter : `str`
662 Name of filter. Can be a combination of FILTER, FILTER1 and FILTER2
663 headers joined by a "~". Returns "unknown" if no filter is declared
664 """
665 joined = self._join_keyword_values(["FILTER", "FILTER1", "FILTER2"], delim=FILTER_DELIMITER)
666 if not joined:
667 joined = "unknown"
669 return joined
671 @cache_translation
672 def to_tracking_radec(self):
673 # RA/DEC are *derived* headers and for the case where the DATE-BEG
674 # is 1970 they are garbage and should not be used.
675 try:
676 if self._header["DATE-OBS"] == self._header["DATE"]:
677 # A fixed up date -- use AZEL as source of truth
678 altaz = self.to_altaz_begin()
679 radec = astropy.coordinates.SkyCoord(altaz.transform_to(astropy.coordinates.ICRS()),
680 obstime=altaz.obstime,
681 location=altaz.location)
682 else:
683 radecsys = ("RADESYS",)
684 radecpairs = (("RASTART", "DECSTART"), ("RA", "DEC"))
685 radec = tracking_from_degree_headers(self, radecsys, radecpairs)
686 except Exception:
687 # If this observation was not formally on sky then we are allowed
688 # to return None.
689 if self.is_on_sky():
690 raise
691 radec = None
693 return radec
695 @cache_translation
696 def to_altaz_begin(self):
697 if not self._is_on_mountain():
698 return None
700 # Always attempt to find the alt/az values regardless of observation
701 # type.
702 return altaz_from_degree_headers(self, (("ELSTART", "AZSTART"),),
703 self.to_datetime_begin(), is_zd=False)
705 @cache_translation
706 def to_exposure_group(self):
707 """Calculate the exposure group string.
709 For LSSTCam and LATISS this is read from the ``GROUPID`` header.
710 If that header is missing the exposure_id is returned instead as
711 a string.
712 """
713 if self.is_key_ok("GROUPID"):
714 exposure_group = self._header["GROUPID"]
715 self._used_these_cards("GROUPID")
716 return exposure_group
717 return super().to_exposure_group()
719 @cache_translation
720 def to_focus_z(self):
721 """Return the defocal distance of the camera in units of mm.
722 If there is no ``FOCUSZ`` value in the header it will return
723 the default 0.0mm value.
725 Returns
726 -------
727 focus_z: `astropy.units.Quantity`
728 The defocal distance from header in mm or the 0.0mm default
729 """
730 if self.is_key_ok("FOCUSZ"):
731 focus_z = self._header["FOCUSZ"]
732 return focus_z * u.mm
733 return super().to_focus_z()
735 @staticmethod
736 def _is_filter_empty(filter):
737 """Return true if the supplied filter indicates an empty filter slot
739 Parameters
740 ----------
741 filter : `str`
742 The filter string to check.
744 Returns
745 -------
746 is_empty : `bool`
747 `True` if the filter string looks like it is referring to an
748 empty filter slot. For example this can be if the filter is
749 "empty" or "empty_2".
750 """
751 return bool(re.match(r"empty_?\d*$", filter.lower()))
753 def _determine_primary_filter(self):
754 """Determine the primary filter from the ``FILTER`` header.
756 Returns
757 -------
758 filter : `str`
759 The contents of the ``FILTER`` header with some appropriate
760 defaulting.
761 """
763 if self.is_key_ok("FILTER"):
764 physical_filter = self._header["FILTER"]
765 self._used_these_cards("FILTER")
767 if self._is_filter_empty(physical_filter):
768 physical_filter = "empty"
769 else:
770 # Be explicit about having no knowledge of the filter
771 # by setting it to "unknown". It should always have a value.
772 physical_filter = "unknown"
774 # Warn if the filter being unknown is important
775 obstype = self.to_observation_type()
776 if obstype not in ("bias", "dark"):
777 log.warning("%s: Unable to determine the filter",
778 self._log_prefix)
780 return physical_filter
782 @cache_translation
783 def to_observing_day(self):
784 """Return the day of observation as YYYYMMDD integer.
786 For LSSTCam and other compliant instruments this is the value
787 of the DAYOBS header.
789 Returns
790 -------
791 obs_day : `int`
792 The day of observation.
793 """
794 if self.is_key_ok("DAYOBS"):
795 self._used_these_cards("DAYOBS")
796 return int(self._header["DAYOBS"])
798 # Calculate it ourselves correcting for the Rubin offset
799 date = self.to_datetime_begin().tai
800 date -= self._ROLLOVER_TIME
801 return int(date.strftime("%Y%m%d"))
803 @cache_translation
804 def to_observation_counter(self):
805 """Return the sequence number within the observing day.
807 Returns
808 -------
809 counter : `int`
810 The sequence number for this day.
811 """
812 if self.is_key_ok("SEQNUM"):
813 # Some older LATISS data may not have the header
814 # but this is corrected in fix_header for LATISS.
815 self._used_these_cards("SEQNUM")
816 return int(self._header["SEQNUM"])
818 # This indicates a problem so we warn and return a 0
819 log.warning("%s: Unable to determine the observation counter so returning 0",
820 self._log_prefix)
821 return 0
823 @cache_translation
824 def to_boresight_rotation_coord(self):
825 """Boresight rotation angle.
827 Only relevant for science observations.
828 """
829 unknown = "unknown"
830 if not self.is_on_sky():
831 return unknown
833 self._used_these_cards("ROTCOORD")
834 coord = self._header.get("ROTCOORD", unknown)
835 if coord is None:
836 coord = unknown
837 return coord
839 @cache_translation
840 def to_boresight_airmass(self):
841 """Calculate airmass at boresight at start of observation.
843 Notes
844 -----
845 Early data are missing AMSTART header so we fall back to calculating
846 it from ELSTART.
847 """
848 if not self.is_on_sky():
849 return None
851 # This observation should have AMSTART
852 amkey = "AMSTART"
853 if self.is_key_ok(amkey):
854 self._used_these_cards(amkey)
855 return self._header[amkey]
857 # Instead we need to look at azel
858 altaz = self.to_altaz_begin()
859 if altaz is not None:
860 return altaz.secz.to_value()
862 log.warning("%s: Unable to determine airmass of a science observation, returning 1.",
863 self._log_prefix)
864 return 1.0
866 @cache_translation
867 def to_group_counter_start(self):
868 # Effectively the start of the visit as determined by the headers.
869 counter = self.to_observation_counter()
870 # Older data does not have the CURINDEX header.
871 if self.is_key_ok("CURINDEX"):
872 # CURINDEX is 1-based.
873 seq_start = counter - self._header["CURINDEX"] + 1
874 self._used_these_cards("CURINDEX")
875 return seq_start
876 else:
877 # If the counter is 0 we need to pick something else
878 # that is not going to confuse the visit calculation
879 # (since setting everything to 0 will make one big visit).
880 return counter if counter != 0 else self.to_exposure_id()
882 @cache_translation
883 def to_group_counter_end(self):
884 # Effectively the end of the visit as determined by the headers.
885 counter = self.to_observation_counter()
886 # Older data does not have the CURINDEX or MAXINDEX headers.
887 if self.is_key_ok("CURINDEX") and self.is_key_ok("MAXINDEX"):
888 # CURINDEX is 1-based. CURINDEX == MAXINDEX indicates the
889 # final exposure in the sequence.
890 remaining = self._header["MAXINDEX"] - self._header["CURINDEX"]
891 seq_end = counter + remaining
892 self._used_these_cards("CURINDEX", "MAXINDEX")
893 return seq_end
894 else:
895 # If the counter is 0 we need to pick something else
896 # that is not going to confuse the visit calculation
897 # (since setting everything to 0 will make one big visit).
898 return counter if counter != 0 else self.to_exposure_id()
900 @cache_translation
901 def to_has_simulated_content(self):
902 # Check all the simulation flags.
903 # We do not know all the simulation flags that we may have so
904 # must check every header key. Ideally HIERARCH SIMULATE would
905 # be a hierarchical header so _header["SIMULATE"] would return
906 # everything. The header looks like:
907 #
908 # HIERARCH SIMULATE ATMCS = / ATMCS Simulation Mode
909 # HIERARCH SIMULATE ATHEXAPOD = 0 / ATHexapod Simulation Mode
910 # HIERARCH SIMULATE ATPNEUMATICS = / ATPneumatics Simulation Mode
911 # HIERARCH SIMULATE ATDOME = 1 / ATDome Simulation Mode
912 # HIERARCH SIMULATE ATSPECTROGRAPH = 0 / ATSpectrograph Simulation Mode
913 #
914 # So any header that includes "SIMULATE" in the key name and has a
915 # true value implies that something in the data is simulated.
916 for k, v in self._header.items():
917 if "SIMULATE" in k and v:
918 return True
920 # If the controller is H, P, or Q then the data are simulated.
921 ctrlr_key = "CONTRLLR"
922 if self.is_key_ok(ctrlr_key):
923 controller = self._header[ctrlr_key]
924 self._used_these_cards(ctrlr_key)
925 if controller in "HPQ":
926 return True
928 # No simulation flags set.
929 return False