Coverage for python/lsst/obs/lsst/translators/lsst.py: 25%
366 statements
« prev ^ index » next coverage.py v7.2.3, created at 2023-04-28 05:12 -0700
« prev ^ index » next coverage.py v7.2.3, created at 2023-04-28 05:12 -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`
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 if "T" in dayobs:
400 dayobs = dayobs[:dayobs.find("T")]
402 dayobs = dayobs.replace("-", "")
404 if len(dayobs) != 8:
405 raise ValueError(f"Malformed dayobs: {dayobs}")
407 # Expect no more than 99,999 exposures in a day
408 if seqnum >= 10**_SEQNUM_MAXDIGITS:
409 raise ValueError(f"Sequence number ({seqnum}) exceeds limit")
411 # Camera control changes the exposure ID
412 if controller is not None:
413 index = CONTROLLERS.find(controller)
414 if index == -1:
415 raise ValueError(f"Supplied controller, '{controller}' is not "
416 f"in supported list: {CONTROLLERS}")
417 dayobs = int(dayobs)
418 # Increment a thousand years per controller
419 dayobs += _CONTROLLER_INCREMENT * index
421 # Form the number as a string zero padding the sequence number
422 idstr = f"{dayobs}{seqnum:0{_SEQNUM_MAXDIGITS}d}"
424 # Exposure ID has to be an integer
425 return int(idstr)
427 @staticmethod
428 def unpack_exposure_id(exposure_id):
429 """Unpack an exposure ID into dayobs, seqnum, and controller.
431 Parameters
432 ----------
433 exposure_id : `int`
434 Integer exposure ID produced by `compute_exposure_id`.
436 Returns
437 -------
438 dayobs : `str`
439 Day of observation as a YYYYMMDD string.
440 seqnum : `int`
441 Sequence number.
442 controller : `str`
443 Controller code. Will be `O` (but should be ignored) for IDs
444 produced by calling `compute_exposure_id` with ``controller=None`.
445 """
446 dayobs, seqnum = divmod(exposure_id, 10**_SEQNUM_MAXDIGITS)
447 controller_index = dayobs // _CONTROLLER_INCREMENT - 2
448 dayobs -= controller_index * _CONTROLLER_INCREMENT
449 return (str(dayobs), seqnum, CONTROLLERS[controller_index], )
451 def _is_on_mountain(self):
452 """Indicate whether these data are coming from the instrument
453 installed on the mountain.
455 Returns
456 -------
457 is : `bool`
458 `True` if instrument is on the mountain.
459 """
460 if "TSTAND" in self._header:
461 return False
462 return True
464 def is_on_sky(self):
465 """Determine if this is an on-sky observation.
467 Returns
468 -------
469 is_on_sky : `bool`
470 Returns True if this is a observation on sky on the
471 summit.
472 """
473 # For LSST we think on sky unless tracksys is local
474 if self.is_key_ok("TRACKSYS"):
475 if self._header["TRACKSYS"].lower() == "local":
476 # not on sky
477 return False
479 # These are obviously not on sky
480 if self.to_observation_type() in ("bias", "dark", "flat"):
481 return False
483 return self._is_on_mountain()
485 @cache_translation
486 def to_location(self):
487 # Docstring will be inherited. Property defined in properties.py
488 if not self._is_on_mountain():
489 return None
490 try:
491 # Try standard FITS headers
492 return super().to_location()
493 except KeyError:
494 return self._DEFAULT_LOCATION
496 @cache_translation
497 def to_datetime_begin(self):
498 # Docstring will be inherited. Property defined in properties.py
499 self._used_these_cards("MJD-OBS")
500 return Time(self._header["MJD-OBS"], scale="tai", format="mjd")
502 @cache_translation
503 def to_datetime_end(self):
504 # Docstring will be inherited. Property defined in properties.py
505 if self.is_key_ok("DATE-END"):
506 return super().to_datetime_end()
508 return self.to_datetime_begin() + self.to_exposure_time()
510 @cache_translation
511 def to_detector_num(self):
512 # Docstring will be inherited. Property defined in properties.py
513 raft = self.to_detector_group()
514 detector = self.to_detector_name()
515 return self.compute_detector_num_from_name(raft, detector)
517 @cache_translation
518 def to_detector_exposure_id(self):
519 # Docstring will be inherited. Property defined in properties.py
520 exposure_id = self.to_exposure_id()
521 num = self.to_detector_num()
522 return self.compute_detector_exposure_id(exposure_id, num)
524 @cache_translation
525 def to_observation_type(self):
526 # Docstring will be inherited. Property defined in properties.py
527 obstype = self._header["IMGTYPE"]
528 self._used_these_cards("IMGTYPE")
529 obstype = obstype.lower()
530 if obstype in ("skyexp", "object"):
531 obstype = "science"
532 return obstype
534 @cache_translation
535 def to_observation_reason(self):
536 # Docstring will be inherited. Property defined in properties.py
537 for key in ("REASON", "TESTTYPE"):
538 if self.is_key_ok(key):
539 reason = self._header[key]
540 self._used_these_cards(key)
541 return reason.lower()
542 # no specific header present so use the default translation
543 return super().to_observation_reason()
545 @cache_translation
546 def to_dark_time(self):
547 """Calculate the dark time.
549 If a DARKTIME header is not found, the value is assumed to be
550 identical to the exposure time.
552 Returns
553 -------
554 dark : `astropy.units.Quantity`
555 The dark time in seconds.
556 """
557 if self.is_key_ok("DARKTIME"):
558 darktime = self._header["DARKTIME"]*u.s
559 self._used_these_cards("DARKTIME")
560 else:
561 log.warning("%s: Unable to determine dark time. Setting from exposure time.",
562 self._log_prefix)
563 darktime = self.to_exposure_time()
564 return darktime
566 @cache_translation
567 def to_exposure_id(self):
568 """Generate a unique exposure ID number
570 This is a combination of DAYOBS and SEQNUM, and optionally
571 CONTRLLR.
573 Returns
574 -------
575 exposure_id : `int`
576 Unique exposure number.
577 """
578 if "CALIB_ID" in self._header:
579 self._used_these_cards("CALIB_ID")
580 return None
582 dayobs = self._header["DAYOBS"]
583 seqnum = self._header["SEQNUM"]
584 self._used_these_cards("DAYOBS", "SEQNUM")
586 if self.is_key_ok("CONTRLLR"):
587 controller = self._header["CONTRLLR"]
588 self._used_these_cards("CONTRLLR")
589 else:
590 controller = None
592 return self.compute_exposure_id(dayobs, seqnum, controller=controller)
594 @cache_translation
595 def to_visit_id(self):
596 """Calculate the visit associated with this exposure.
598 Notes
599 -----
600 For LATISS and LSSTCam the default visit is derived from the
601 exposure group. For other instruments we return the exposure_id.
602 """
604 exposure_group = self.to_exposure_group()
605 # If the group is an int we return it
606 try:
607 visit_id = int(exposure_group)
608 return visit_id
609 except ValueError:
610 pass
612 # A Group is defined as ISO date with an extension
613 # The integer must be the same for a given group so we can never
614 # use datetime_begin.
615 # Nominally a GROUPID looks like "ISODATE+N" where the +N is
616 # optional. This can be converted to seconds since epoch with
617 # an adjustment for N.
618 # For early data lacking that form we hash the group and return
619 # the int.
620 matches_date = GROUP_RE.match(exposure_group)
621 if matches_date:
622 iso_str = matches_date.group(1)
623 fraction = matches_date.group(2)
624 n = matches_date.group(3)
625 if n is not None:
626 n = int(n)
627 else:
628 n = 0
629 iso = datetime.datetime.strptime(iso_str, "%Y-%m-%dT%H:%M:%S")
631 tdelta = iso - TZERO_DATETIME
632 epoch = int(tdelta.total_seconds())
634 # Form the integer from EPOCH + 3 DIGIT FRAC + 0-pad N
635 visit_id = int(f"{epoch}{fraction}{n:04d}")
636 else:
637 # Non-standard string so convert to numbers
638 # using a hash function. Use the first N hex digits
639 group_bytes = exposure_group.encode("us-ascii")
640 hasher = hashlib.blake2b(group_bytes)
641 # Need to be big enough it does not possibly clash with the
642 # date-based version above
643 digest = hasher.hexdigest()[:14]
644 visit_id = int(digest, base=16)
646 # To help with hash collision, append the string length
647 visit_id = int(f"{visit_id}{len(exposure_group):02d}")
649 return visit_id
651 @cache_translation
652 def to_physical_filter(self):
653 """Calculate the physical filter name.
655 Returns
656 -------
657 filter : `str`
658 Name of filter. Can be a combination of FILTER, FILTER1 and FILTER2
659 headers joined by a "~". Returns "unknown" if no filter is declared
660 """
661 joined = self._join_keyword_values(["FILTER", "FILTER1", "FILTER2"], delim=FILTER_DELIMITER)
662 if not joined:
663 joined = "unknown"
665 return joined
667 @cache_translation
668 def to_tracking_radec(self):
669 # RA/DEC are *derived* headers and for the case where the DATE-BEG
670 # is 1970 they are garbage and should not be used.
671 try:
672 if self._header["DATE-OBS"] == self._header["DATE"]:
673 # A fixed up date -- use AZEL as source of truth
674 altaz = self.to_altaz_begin()
675 radec = astropy.coordinates.SkyCoord(altaz.transform_to(astropy.coordinates.ICRS()),
676 obstime=altaz.obstime,
677 location=altaz.location)
678 else:
679 radecsys = ("RADESYS",)
680 radecpairs = (("RASTART", "DECSTART"), ("RA", "DEC"))
681 radec = tracking_from_degree_headers(self, radecsys, radecpairs)
682 except Exception:
683 # If this observation was not formally on sky then we are allowed
684 # to return None.
685 if self.is_on_sky():
686 raise
687 radec = None
689 return radec
691 @cache_translation
692 def to_altaz_begin(self):
693 if not self._is_on_mountain():
694 return None
696 # Always attempt to find the alt/az values regardless of observation
697 # type.
698 return altaz_from_degree_headers(self, (("ELSTART", "AZSTART"),),
699 self.to_datetime_begin(), is_zd=False)
701 @cache_translation
702 def to_exposure_group(self):
703 """Calculate the exposure group string.
705 For LSSTCam and LATISS this is read from the ``GROUPID`` header.
706 If that header is missing the exposure_id is returned instead as
707 a string.
708 """
709 if self.is_key_ok("GROUPID"):
710 exposure_group = self._header["GROUPID"]
711 self._used_these_cards("GROUPID")
712 return exposure_group
713 return super().to_exposure_group()
715 @cache_translation
716 def to_focus_z(self):
717 """Return the defocal distance of the camera in units of mm.
718 If there is no ``FOCUSZ`` value in the header it will return
719 the default 0.0mm value.
721 Returns
722 -------
723 focus_z: `astropy.units.Quantity`
724 The defocal distance from header in mm or the 0.0mm default
725 """
726 if self.is_key_ok("FOCUSZ"):
727 focus_z = self._header["FOCUSZ"]
728 return focus_z * u.mm
729 return super().to_focus_z()
731 @staticmethod
732 def _is_filter_empty(filter):
733 """Return true if the supplied filter indicates an empty filter slot
735 Parameters
736 ----------
737 filter : `str`
738 The filter string to check.
740 Returns
741 -------
742 is_empty : `bool`
743 `True` if the filter string looks like it is referring to an
744 empty filter slot. For example this can be if the filter is
745 "empty" or "empty_2".
746 """
747 return bool(re.match(r"empty_?\d*$", filter.lower()))
749 def _determine_primary_filter(self):
750 """Determine the primary filter from the ``FILTER`` header.
752 Returns
753 -------
754 filter : `str`
755 The contents of the ``FILTER`` header with some appropriate
756 defaulting.
757 """
759 if self.is_key_ok("FILTER"):
760 physical_filter = self._header["FILTER"]
761 self._used_these_cards("FILTER")
763 if self._is_filter_empty(physical_filter):
764 physical_filter = "empty"
765 else:
766 # Be explicit about having no knowledge of the filter
767 # by setting it to "unknown". It should always have a value.
768 physical_filter = "unknown"
770 # Warn if the filter being unknown is important
771 obstype = self.to_observation_type()
772 if obstype not in ("bias", "dark"):
773 log.warning("%s: Unable to determine the filter",
774 self._log_prefix)
776 return physical_filter
778 @cache_translation
779 def to_observing_day(self):
780 """Return the day of observation as YYYYMMDD integer.
782 For LSSTCam and other compliant instruments this is the value
783 of the DAYOBS header.
785 Returns
786 -------
787 obs_day : `int`
788 The day of observation.
789 """
790 if self.is_key_ok("DAYOBS"):
791 self._used_these_cards("DAYOBS")
792 return int(self._header["DAYOBS"])
794 # Calculate it ourselves correcting for the Rubin offset
795 date = self.to_datetime_begin().tai
796 date -= self._ROLLOVER_TIME
797 return int(date.strftime("%Y%m%d"))
799 @cache_translation
800 def to_observation_counter(self):
801 """Return the sequence number within the observing day.
803 Returns
804 -------
805 counter : `int`
806 The sequence number for this day.
807 """
808 if self.is_key_ok("SEQNUM"):
809 # Some older LATISS data may not have the header
810 # but this is corrected in fix_header for LATISS.
811 self._used_these_cards("SEQNUM")
812 return int(self._header["SEQNUM"])
814 # This indicates a problem so we warn and return a 0
815 log.warning("%s: Unable to determine the observation counter so returning 0",
816 self._log_prefix)
817 return 0
819 @cache_translation
820 def to_boresight_rotation_coord(self):
821 """Boresight rotation angle.
823 Only relevant for science observations.
824 """
825 unknown = "unknown"
826 if not self.is_on_sky():
827 return unknown
829 self._used_these_cards("ROTCOORD")
830 coord = self._header.get("ROTCOORD", unknown)
831 if coord is None:
832 coord = unknown
833 return coord
835 @cache_translation
836 def to_boresight_airmass(self):
837 """Calculate airmass at boresight at start of observation.
839 Notes
840 -----
841 Early data are missing AMSTART header so we fall back to calculating
842 it from ELSTART.
843 """
844 if not self.is_on_sky():
845 return None
847 # This observation should have AMSTART
848 amkey = "AMSTART"
849 if self.is_key_ok(amkey):
850 self._used_these_cards(amkey)
851 return self._header[amkey]
853 # Instead we need to look at azel
854 altaz = self.to_altaz_begin()
855 if altaz is not None:
856 return altaz.secz.to_value()
858 log.warning("%s: Unable to determine airmass of a science observation, returning 1.",
859 self._log_prefix)
860 return 1.0
862 @cache_translation
863 def to_group_counter_start(self):
864 # Effectively the start of the visit as determined by the headers.
865 counter = self.to_observation_counter()
866 # Older data does not have the CURINDEX header.
867 if self.is_key_ok("CURINDEX"):
868 # CURINDEX is 1-based.
869 seq_start = counter - self._header["CURINDEX"] + 1
870 self._used_these_cards("CURINDEX")
871 return seq_start
872 else:
873 # If the counter is 0 we need to pick something else
874 # that is not going to confuse the visit calculation
875 # (since setting everything to 0 will make one big visit).
876 return counter if counter != 0 else self.to_exposure_id()
878 @cache_translation
879 def to_group_counter_end(self):
880 # Effectively the end of the visit as determined by the headers.
881 counter = self.to_observation_counter()
882 # Older data does not have the CURINDEX or MAXINDEX headers.
883 if self.is_key_ok("CURINDEX") and self.is_key_ok("MAXINDEX"):
884 # CURINDEX is 1-based. CURINDEX == MAXINDEX indicates the
885 # final exposure in the sequence.
886 remaining = self._header["MAXINDEX"] - self._header["CURINDEX"]
887 seq_end = counter + remaining
888 self._used_these_cards("CURINDEX", "MAXINDEX")
889 return seq_end
890 else:
891 # If the counter is 0 we need to pick something else
892 # that is not going to confuse the visit calculation
893 # (since setting everything to 0 will make one big visit).
894 return counter if counter != 0 else self.to_exposure_id()
896 @cache_translation
897 def to_has_simulated_content(self):
898 # Check all the simulation flags.
899 # We do not know all the simulation flags that we may have so
900 # must check every header key. Ideally HIERARCH SIMULATE would
901 # be a hierarchical header so _header["SIMULATE"] would return
902 # everything. The header looks like:
903 #
904 # HIERARCH SIMULATE ATMCS = / ATMCS Simulation Mode
905 # HIERARCH SIMULATE ATHEXAPOD = 0 / ATHexapod Simulation Mode
906 # HIERARCH SIMULATE ATPNEUMATICS = / ATPneumatics Simulation Mode
907 # HIERARCH SIMULATE ATDOME = 1 / ATDome Simulation Mode
908 # HIERARCH SIMULATE ATSPECTROGRAPH = 0 / ATSpectrograph Simulation Mode
909 #
910 # So any header that includes "SIMULATE" in the key name and has a
911 # true value implies that something in the data is simulated.
912 for k, v in self._header.items():
913 if "SIMULATE" in k and v:
914 return True
916 # If the controller is H, P, or Q then the data are simulated.
917 ctrlr_key = "CONTRLLR"
918 if self.is_key_ok(ctrlr_key):
919 controller = self._header[ctrlr_key]
920 self._used_these_cards(ctrlr_key)
921 if controller in "HPQ":
922 return True
924 # No simulation flags set.
925 return False