Coverage for python/lsst/obs/lsst/translators/lsst.py: 24%

369 statements  

« prev     ^ index     » next       coverage.py v7.2.5, created at 2023-05-23 04:18 -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. 

10 

11"""Metadata translation support code for LSST headers""" 

12 

13__all__ = ("TZERO", "SIMONYI_LOCATION", "read_detector_ids", 

14 "compute_detector_exposure_id_generic", "LsstBaseTranslator", 

15 "SIMONYI_TELESCOPE") 

16 

17import os.path 

18import yaml 

19import logging 

20import re 

21import datetime 

22import hashlib 

23 

24import astropy.coordinates 

25import astropy.units as u 

26from astropy.time import Time, TimeDelta 

27from astropy.coordinates import EarthLocation 

28 

29from lsst.utils import getPackageDir 

30 

31from astro_metadata_translator import cache_translation, FitsTranslator 

32from astro_metadata_translator.translators.helpers import tracking_from_degree_headers, \ 

33 altaz_from_degree_headers 

34 

35 

36TZERO = Time("2015-01-01T00:00", format="isot", scale="utc") 

37TZERO_DATETIME = TZERO.to_datetime() 

38 

39# Delimiter to use for multiple filters/gratings 

40FILTER_DELIMITER = "~" 

41 

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+))?$") 

44 

45# LSST Default location in the absence of headers 

46SIMONYI_LOCATION = EarthLocation.from_geodetic(-70.749417, -30.244639, 2663.0) 

47 

48# Name of the main survey telescope 

49SIMONYI_TELESCOPE = "Simonyi Survey Telescope" 

50 

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" 

56 

57# Number of decimal digits allocated to the sequence number in exposure_ids. 

58_SEQNUM_MAXDIGITS = 5 

59 

60# Number of decimal digits allocated to the day of observation (and controller 

61# code) in exposure_ids. 

62_DAYOBS_MAXDIGITS = 8 

63 

64# Value added to day_obs for controllers after the default. 

65_CONTROLLER_INCREMENT = 1000_00_00 

66 

67# Number of decimal digits used by exposure_ids. 

68EXPOSURE_ID_MAXDIGITS = _SEQNUM_MAXDIGITS + _DAYOBS_MAXDIGITS 

69 

70obs_lsst_packageDir = getPackageDir("obs_lsst") 

71 

72log = logging.getLogger(__name__) 

73 

74 

75def read_detector_ids(policyFile): 

76 """Read a camera policy file and retrieve the mapping from CCD name 

77 to ID. 

78 

79 Parameters 

80 ---------- 

81 policyFile : `str` 

82 Name of YAML policy file to read, relative to the obs_lsst 

83 package. 

84 

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. 

91 

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 """ 

100 

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 

108 

109 mapping = {} 

110 for ccd, value in camera["CCDs"].items(): 

111 mapping[ccd] = (int(value["id"]), value["serial"]) 

112 

113 return mapping 

114 

115 

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. 

119 

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. 

128 

129 Returns 

130 ------- 

131 detector_exposure_id : `int` 

132 Computed ID. 

133 

134 Raises 

135 ------ 

136 ValueError 

137 The detector number is out of range. 

138 """ 

139 

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}") 

144 

145 return max_num*exposure_id + detector_num 

146 

147 

148class LsstBaseTranslator(FitsTranslator): 

149 """Translation methods useful for all LSST-style headers.""" 

150 

151 _const_map = {} 

152 _trivial_map = {} 

153 

154 # Do not specify a name for this translator 

155 cameraPolicyFile = None 

156 """Path to policy file relative to obs_lsst root.""" 

157 

158 detectorMapping = None 

159 """Mapping of detector name to detector number and serial.""" 

160 

161 detectorSerials = None 

162 """Mapping of detector serial number to raft, number, and name.""" 

163 

164 DETECTOR_MAX = 1000 

165 """Maximum number of detectors to use when calculating the 

166 detector_exposure_id. 

167 

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 """ 

174 

175 _DEFAULT_LOCATION = SIMONYI_LOCATION 

176 """Default telescope location in absence of relevant FITS headers.""" 

177 

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.""" 

181 

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.""" 

187 

188 cls.detectorMapping = None 

189 cls.detectorSerials = None 

190 

191 super().__init_subclass__(**kwargs) 

192 

193 def search_paths(self): 

194 """Search paths to use for LSST data when looking for header correction 

195 files. 

196 

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")] 

204 

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. 

209 

210 This is a helper method to allow code working outside the translator 

211 infrastructure to use the same algorithm. 

212 

213 Parameters 

214 ---------- 

215 exposure_id : `int` 

216 Unique exposure ID. 

217 detector_num : `int` 

218 Detector number. 

219 

220 Returns 

221 ------- 

222 detector_exposure_id : `int` 

223 The calculated ID. 

224 """ 

225 from .._packer import RubinDimensionPacker 

226 

227 return RubinDimensionPacker.pack_id_pair(exposure_id, detector_num) 

228 

229 @classmethod 

230 def max_detector_exposure_id(cls): 

231 """The maximum detector exposure ID expected to be generated by 

232 this instrument. 

233 

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) 

244 

245 @classmethod 

246 def max_exposure_id(cls): 

247 """The maximum exposure ID expected from this instrument. 

248 

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) 

259 

260 @classmethod 

261 def detector_mapping(cls): 

262 """Returns the mapping of full name to detector ID and serial. 

263 

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. 

269 

270 Raises 

271 ------ 

272 ValueError 

273 Raised if no camera policy file has been registered with this 

274 translation class. 

275 

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") 

285 

286 return cls.detectorMapping 

287 

288 @classmethod 

289 def detector_serials(cls): 

290 """Obtain the mapping of detector serial to detector group, name, 

291 and number. 

292 

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() 

301 

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") 

313 

314 return cls.detectorSerials 

315 

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. 

319 

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. 

326 

327 Returns 

328 ------- 

329 num : `int` 

330 Detector number. 

331 """ 

332 fullname = f"{detector_group}_{detector_name}" 

333 

334 num = None 

335 detector_mapping = cls.detector_mapping() 

336 if detector_mapping is None: 

337 raise RuntimeError("Unable to obtain detector mapping information") 

338 

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 

344 

345 return num[0] 

346 

347 @classmethod 

348 def compute_detector_info_from_serial(cls, detector_serial): 

349 """Helper method to return the detector information from the serial. 

350 

351 Parameters 

352 ---------- 

353 detector_serial : `str` 

354 Detector serial ID. 

355 

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") 

364 

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}") 

370 

371 return info 

372 

373 @staticmethod 

374 def compute_exposure_id(dayobs, seqnum, controller=None): 

375 """Helper method to calculate the exposure_id. 

376 

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). 

393 

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")] 

401 

402 dayobs = dayobs.replace("-", "") 

403 

404 if len(dayobs) != 8: 

405 raise ValueError(f"Malformed dayobs: {dayobs}") 

406 

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") 

410 

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 

420 

421 # Form the number as a string zero padding the sequence number 

422 idstr = f"{dayobs}{seqnum:0{_SEQNUM_MAXDIGITS}d}" 

423 

424 # Exposure ID has to be an integer 

425 return int(idstr) 

426 

427 @staticmethod 

428 def unpack_exposure_id(exposure_id): 

429 """Unpack an exposure ID into dayobs, seqnum, and controller. 

430 

431 Parameters 

432 ---------- 

433 exposure_id : `int` 

434 Integer exposure ID produced by `compute_exposure_id`. 

435 

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], ) 

450 

451 def _is_on_mountain(self): 

452 """Indicate whether these data are coming from the instrument 

453 installed on the mountain. 

454 

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 

463 

464 def is_on_sky(self): 

465 """Determine if this is an on-sky observation. 

466 

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 

478 

479 # These are obviously not on sky 

480 if self.to_observation_type() in ("bias", "dark", "flat"): 

481 return False 

482 

483 return self._is_on_mountain() 

484 

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 

495 

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") 

501 

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() 

507 

508 return self.to_datetime_begin() + self.to_exposure_time() 

509 

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) 

516 

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) 

523 

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 

533 

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() 

544 

545 @cache_translation 

546 def to_dark_time(self): 

547 """Calculate the dark time. 

548 

549 If a DARKTIME header is not found, the value is assumed to be 

550 identical to the exposure time. 

551 

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 

565 

566 @cache_translation 

567 def to_exposure_id(self): 

568 """Generate a unique exposure ID number 

569 

570 This is a combination of DAYOBS and SEQNUM, and optionally 

571 CONTRLLR. 

572 

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 

581 

582 dayobs = self._header["DAYOBS"] 

583 seqnum = self._header["SEQNUM"] 

584 self._used_these_cards("DAYOBS", "SEQNUM") 

585 

586 if self.is_key_ok("CONTRLLR"): 

587 controller = self._header["CONTRLLR"] 

588 self._used_these_cards("CONTRLLR") 

589 else: 

590 controller = None 

591 

592 return self.compute_exposure_id(dayobs, seqnum, controller=controller) 

593 

594 @cache_translation 

595 def to_visit_id(self): 

596 """Calculate the visit associated with this exposure. 

597 

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 """ 

603 

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 

611 

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") 

630 

631 tdelta = iso - TZERO_DATETIME 

632 epoch = int(tdelta.total_seconds()) 

633 

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) 

645 

646 # To help with hash collision, append the string length 

647 visit_id = int(f"{visit_id}{len(exposure_group):02d}") 

648 

649 return visit_id 

650 

651 @cache_translation 

652 def to_physical_filter(self): 

653 """Calculate the physical filter name. 

654 

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" 

664 

665 # Remove blank and "empty" fields. 

666 joined = FILTER_DELIMITER.join(_ for _ in joined.split(FILTER_DELIMITER) 

667 if _ and _ != "empty") 

668 

669 # Return "empty" if joined is blank at this point. 

670 if not joined: 

671 joined = "empty" 

672 

673 return joined 

674 

675 @cache_translation 

676 def to_tracking_radec(self): 

677 # RA/DEC are *derived* headers and for the case where the DATE-BEG 

678 # is 1970 they are garbage and should not be used. 

679 try: 

680 if self._header["DATE-OBS"] == self._header["DATE"]: 

681 # A fixed up date -- use AZEL as source of truth 

682 altaz = self.to_altaz_begin() 

683 radec = astropy.coordinates.SkyCoord(altaz.transform_to(astropy.coordinates.ICRS()), 

684 obstime=altaz.obstime, 

685 location=altaz.location) 

686 else: 

687 radecsys = ("RADESYS",) 

688 radecpairs = (("RASTART", "DECSTART"), ("RA", "DEC")) 

689 radec = tracking_from_degree_headers(self, radecsys, radecpairs) 

690 except Exception: 

691 # If this observation was not formally on sky then we are allowed 

692 # to return None. 

693 if self.is_on_sky(): 

694 raise 

695 radec = None 

696 

697 return radec 

698 

699 @cache_translation 

700 def to_altaz_begin(self): 

701 if not self._is_on_mountain(): 

702 return None 

703 

704 # Always attempt to find the alt/az values regardless of observation 

705 # type. 

706 return altaz_from_degree_headers(self, (("ELSTART", "AZSTART"),), 

707 self.to_datetime_begin(), is_zd=False) 

708 

709 @cache_translation 

710 def to_exposure_group(self): 

711 """Calculate the exposure group string. 

712 

713 For LSSTCam and LATISS this is read from the ``GROUPID`` header. 

714 If that header is missing the exposure_id is returned instead as 

715 a string. 

716 """ 

717 if self.is_key_ok("GROUPID"): 

718 exposure_group = self._header["GROUPID"] 

719 self._used_these_cards("GROUPID") 

720 return exposure_group 

721 return super().to_exposure_group() 

722 

723 @cache_translation 

724 def to_focus_z(self): 

725 """Return the defocal distance of the camera in units of mm. 

726 If there is no ``FOCUSZ`` value in the header it will return 

727 the default 0.0mm value. 

728 

729 Returns 

730 ------- 

731 focus_z: `astropy.units.Quantity` 

732 The defocal distance from header in mm or the 0.0mm default 

733 """ 

734 if self.is_key_ok("FOCUSZ"): 

735 focus_z = self._header["FOCUSZ"] 

736 return focus_z * u.mm 

737 return super().to_focus_z() 

738 

739 @staticmethod 

740 def _is_filter_empty(filter): 

741 """Return true if the supplied filter indicates an empty filter slot 

742 

743 Parameters 

744 ---------- 

745 filter : `str` 

746 The filter string to check. 

747 

748 Returns 

749 ------- 

750 is_empty : `bool` 

751 `True` if the filter string looks like it is referring to an 

752 empty filter slot. For example this can be if the filter is 

753 "empty" or "empty_2". 

754 """ 

755 return bool(re.match(r"empty_?\d*$", filter.lower())) 

756 

757 def _determine_primary_filter(self): 

758 """Determine the primary filter from the ``FILTER`` header. 

759 

760 Returns 

761 ------- 

762 filter : `str` 

763 The contents of the ``FILTER`` header with some appropriate 

764 defaulting. 

765 """ 

766 

767 if self.is_key_ok("FILTER"): 

768 physical_filter = self._header["FILTER"] 

769 self._used_these_cards("FILTER") 

770 

771 if self._is_filter_empty(physical_filter): 

772 physical_filter = "empty" 

773 else: 

774 # Be explicit about having no knowledge of the filter 

775 # by setting it to "unknown". It should always have a value. 

776 physical_filter = "unknown" 

777 

778 # Warn if the filter being unknown is important 

779 obstype = self.to_observation_type() 

780 if obstype not in ("bias", "dark"): 

781 log.warning("%s: Unable to determine the filter", 

782 self._log_prefix) 

783 

784 return physical_filter 

785 

786 @cache_translation 

787 def to_observing_day(self): 

788 """Return the day of observation as YYYYMMDD integer. 

789 

790 For LSSTCam and other compliant instruments this is the value 

791 of the DAYOBS header. 

792 

793 Returns 

794 ------- 

795 obs_day : `int` 

796 The day of observation. 

797 """ 

798 if self.is_key_ok("DAYOBS"): 

799 self._used_these_cards("DAYOBS") 

800 return int(self._header["DAYOBS"]) 

801 

802 # Calculate it ourselves correcting for the Rubin offset 

803 date = self.to_datetime_begin().tai 

804 date -= self._ROLLOVER_TIME 

805 return int(date.strftime("%Y%m%d")) 

806 

807 @cache_translation 

808 def to_observation_counter(self): 

809 """Return the sequence number within the observing day. 

810 

811 Returns 

812 ------- 

813 counter : `int` 

814 The sequence number for this day. 

815 """ 

816 if self.is_key_ok("SEQNUM"): 

817 # Some older LATISS data may not have the header 

818 # but this is corrected in fix_header for LATISS. 

819 self._used_these_cards("SEQNUM") 

820 return int(self._header["SEQNUM"]) 

821 

822 # This indicates a problem so we warn and return a 0 

823 log.warning("%s: Unable to determine the observation counter so returning 0", 

824 self._log_prefix) 

825 return 0 

826 

827 @cache_translation 

828 def to_boresight_rotation_coord(self): 

829 """Boresight rotation angle. 

830 

831 Only relevant for science observations. 

832 """ 

833 unknown = "unknown" 

834 if not self.is_on_sky(): 

835 return unknown 

836 

837 self._used_these_cards("ROTCOORD") 

838 coord = self._header.get("ROTCOORD", unknown) 

839 if coord is None: 

840 coord = unknown 

841 return coord 

842 

843 @cache_translation 

844 def to_boresight_airmass(self): 

845 """Calculate airmass at boresight at start of observation. 

846 

847 Notes 

848 ----- 

849 Early data are missing AMSTART header so we fall back to calculating 

850 it from ELSTART. 

851 """ 

852 if not self.is_on_sky(): 

853 return None 

854 

855 # This observation should have AMSTART 

856 amkey = "AMSTART" 

857 if self.is_key_ok(amkey): 

858 self._used_these_cards(amkey) 

859 return self._header[amkey] 

860 

861 # Instead we need to look at azel 

862 altaz = self.to_altaz_begin() 

863 if altaz is not None: 

864 return altaz.secz.to_value() 

865 

866 log.warning("%s: Unable to determine airmass of a science observation, returning 1.", 

867 self._log_prefix) 

868 return 1.0 

869 

870 @cache_translation 

871 def to_group_counter_start(self): 

872 # Effectively the start of the visit as determined by the headers. 

873 counter = self.to_observation_counter() 

874 # Older data does not have the CURINDEX header. 

875 if self.is_key_ok("CURINDEX"): 

876 # CURINDEX is 1-based. 

877 seq_start = counter - self._header["CURINDEX"] + 1 

878 self._used_these_cards("CURINDEX") 

879 return seq_start 

880 else: 

881 # If the counter is 0 we need to pick something else 

882 # that is not going to confuse the visit calculation 

883 # (since setting everything to 0 will make one big visit). 

884 return counter if counter != 0 else self.to_exposure_id() 

885 

886 @cache_translation 

887 def to_group_counter_end(self): 

888 # Effectively the end of the visit as determined by the headers. 

889 counter = self.to_observation_counter() 

890 # Older data does not have the CURINDEX or MAXINDEX headers. 

891 if self.is_key_ok("CURINDEX") and self.is_key_ok("MAXINDEX"): 

892 # CURINDEX is 1-based. CURINDEX == MAXINDEX indicates the 

893 # final exposure in the sequence. 

894 remaining = self._header["MAXINDEX"] - self._header["CURINDEX"] 

895 seq_end = counter + remaining 

896 self._used_these_cards("CURINDEX", "MAXINDEX") 

897 return seq_end 

898 else: 

899 # If the counter is 0 we need to pick something else 

900 # that is not going to confuse the visit calculation 

901 # (since setting everything to 0 will make one big visit). 

902 return counter if counter != 0 else self.to_exposure_id() 

903 

904 @cache_translation 

905 def to_has_simulated_content(self): 

906 # Check all the simulation flags. 

907 # We do not know all the simulation flags that we may have so 

908 # must check every header key. Ideally HIERARCH SIMULATE would 

909 # be a hierarchical header so _header["SIMULATE"] would return 

910 # everything. The header looks like: 

911 # 

912 # HIERARCH SIMULATE ATMCS = / ATMCS Simulation Mode 

913 # HIERARCH SIMULATE ATHEXAPOD = 0 / ATHexapod Simulation Mode 

914 # HIERARCH SIMULATE ATPNEUMATICS = / ATPneumatics Simulation Mode 

915 # HIERARCH SIMULATE ATDOME = 1 / ATDome Simulation Mode 

916 # HIERARCH SIMULATE ATSPECTROGRAPH = 0 / ATSpectrograph Simulation Mode 

917 # 

918 # So any header that includes "SIMULATE" in the key name and has a 

919 # true value implies that something in the data is simulated. 

920 for k, v in self._header.items(): 

921 if "SIMULATE" in k and v: 

922 return True 

923 

924 # If the controller is H, P, or Q then the data are simulated. 

925 ctrlr_key = "CONTRLLR" 

926 if self.is_key_ok(ctrlr_key): 

927 controller = self._header[ctrlr_key] 

928 self._used_these_cards(ctrlr_key) 

929 if controller in "HPQ": 

930 return True 

931 

932 # No simulation flags set. 

933 return False