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

371 statements  

« prev     ^ index     » next       coverage.py v7.2.6, created at 2023-05-24 09:52 +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. 

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

393 

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) 

402 

403 if "T" in dayobs: 

404 dayobs = dayobs[:dayobs.find("T")] 

405 

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

407 

408 if len(dayobs) != 8: 

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

410 

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

414 

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 

424 

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

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

427 

428 # Exposure ID has to be an integer 

429 return int(idstr) 

430 

431 @staticmethod 

432 def unpack_exposure_id(exposure_id): 

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

434 

435 Parameters 

436 ---------- 

437 exposure_id : `int` 

438 Integer exposure ID produced by `compute_exposure_id`. 

439 

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

454 

455 def _is_on_mountain(self): 

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

457 installed on the mountain. 

458 

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 

467 

468 def is_on_sky(self): 

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

470 

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 

482 

483 # These are obviously not on sky 

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

485 return False 

486 

487 return self._is_on_mountain() 

488 

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 

499 

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

505 

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

511 

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

513 

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) 

520 

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) 

527 

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 

537 

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

548 

549 @cache_translation 

550 def to_dark_time(self): 

551 """Calculate the dark time. 

552 

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

554 identical to the exposure time. 

555 

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 

569 

570 @cache_translation 

571 def to_exposure_id(self): 

572 """Generate a unique exposure ID number 

573 

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

575 CONTRLLR. 

576 

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 

585 

586 dayobs = self._header["DAYOBS"] 

587 seqnum = self._header["SEQNUM"] 

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

589 

590 if self.is_key_ok("CONTRLLR"): 

591 controller = self._header["CONTRLLR"] 

592 self._used_these_cards("CONTRLLR") 

593 else: 

594 controller = None 

595 

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

597 

598 @cache_translation 

599 def to_visit_id(self): 

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

601 

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

607 

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 

615 

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

634 

635 tdelta = iso - TZERO_DATETIME 

636 epoch = int(tdelta.total_seconds()) 

637 

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) 

649 

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

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

652 

653 return visit_id 

654 

655 @cache_translation 

656 def to_physical_filter(self): 

657 """Calculate the physical filter name. 

658 

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" 

668 

669 # Remove blank and "empty" fields. 

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

671 if _ and _ != "empty") 

672 

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

674 if not joined: 

675 joined = "empty" 

676 

677 return joined 

678 

679 @cache_translation 

680 def to_tracking_radec(self): 

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

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

683 try: 

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

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

686 altaz = self.to_altaz_begin() 

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

688 obstime=altaz.obstime, 

689 location=altaz.location) 

690 else: 

691 radecsys = ("RADESYS",) 

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

693 radec = tracking_from_degree_headers(self, radecsys, radecpairs) 

694 except Exception: 

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

696 # to return None. 

697 if self.is_on_sky(): 

698 raise 

699 radec = None 

700 

701 return radec 

702 

703 @cache_translation 

704 def to_altaz_begin(self): 

705 if not self._is_on_mountain(): 

706 return None 

707 

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

709 # type. 

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

711 self.to_datetime_begin(), is_zd=False) 

712 

713 @cache_translation 

714 def to_exposure_group(self): 

715 """Calculate the exposure group string. 

716 

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

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

719 a string. 

720 """ 

721 if self.is_key_ok("GROUPID"): 

722 exposure_group = self._header["GROUPID"] 

723 self._used_these_cards("GROUPID") 

724 return exposure_group 

725 return super().to_exposure_group() 

726 

727 @cache_translation 

728 def to_focus_z(self): 

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

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

731 the default 0.0mm value. 

732 

733 Returns 

734 ------- 

735 focus_z: `astropy.units.Quantity` 

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

737 """ 

738 if self.is_key_ok("FOCUSZ"): 

739 focus_z = self._header["FOCUSZ"] 

740 return focus_z * u.mm 

741 return super().to_focus_z() 

742 

743 @staticmethod 

744 def _is_filter_empty(filter): 

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

746 

747 Parameters 

748 ---------- 

749 filter : `str` 

750 The filter string to check. 

751 

752 Returns 

753 ------- 

754 is_empty : `bool` 

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

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

757 "empty" or "empty_2". 

758 """ 

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

760 

761 def _determine_primary_filter(self): 

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

763 

764 Returns 

765 ------- 

766 filter : `str` 

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

768 defaulting. 

769 """ 

770 

771 if self.is_key_ok("FILTER"): 

772 physical_filter = self._header["FILTER"] 

773 self._used_these_cards("FILTER") 

774 

775 if self._is_filter_empty(physical_filter): 

776 physical_filter = "empty" 

777 else: 

778 # Be explicit about having no knowledge of the filter 

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

780 physical_filter = "unknown" 

781 

782 # Warn if the filter being unknown is important 

783 obstype = self.to_observation_type() 

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

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

786 self._log_prefix) 

787 

788 return physical_filter 

789 

790 @cache_translation 

791 def to_observing_day(self): 

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

793 

794 For LSSTCam and other compliant instruments this is the value 

795 of the DAYOBS header. 

796 

797 Returns 

798 ------- 

799 obs_day : `int` 

800 The day of observation. 

801 """ 

802 if self.is_key_ok("DAYOBS"): 

803 self._used_these_cards("DAYOBS") 

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

805 

806 # Calculate it ourselves correcting for the Rubin offset 

807 date = self.to_datetime_begin().tai 

808 date -= self._ROLLOVER_TIME 

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

810 

811 @cache_translation 

812 def to_observation_counter(self): 

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

814 

815 Returns 

816 ------- 

817 counter : `int` 

818 The sequence number for this day. 

819 """ 

820 if self.is_key_ok("SEQNUM"): 

821 # Some older LATISS data may not have the header 

822 # but this is corrected in fix_header for LATISS. 

823 self._used_these_cards("SEQNUM") 

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

825 

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

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

828 self._log_prefix) 

829 return 0 

830 

831 @cache_translation 

832 def to_boresight_rotation_coord(self): 

833 """Boresight rotation angle. 

834 

835 Only relevant for science observations. 

836 """ 

837 unknown = "unknown" 

838 if not self.is_on_sky(): 

839 return unknown 

840 

841 self._used_these_cards("ROTCOORD") 

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

843 if coord is None: 

844 coord = unknown 

845 return coord 

846 

847 @cache_translation 

848 def to_boresight_airmass(self): 

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

850 

851 Notes 

852 ----- 

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

854 it from ELSTART. 

855 """ 

856 if not self.is_on_sky(): 

857 return None 

858 

859 # This observation should have AMSTART 

860 amkey = "AMSTART" 

861 if self.is_key_ok(amkey): 

862 self._used_these_cards(amkey) 

863 return self._header[amkey] 

864 

865 # Instead we need to look at azel 

866 altaz = self.to_altaz_begin() 

867 if altaz is not None: 

868 return altaz.secz.to_value() 

869 

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

871 self._log_prefix) 

872 return 1.0 

873 

874 @cache_translation 

875 def to_group_counter_start(self): 

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

877 counter = self.to_observation_counter() 

878 # Older data does not have the CURINDEX header. 

879 if self.is_key_ok("CURINDEX"): 

880 # CURINDEX is 1-based. 

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

882 self._used_these_cards("CURINDEX") 

883 return seq_start 

884 else: 

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

886 # that is not going to confuse the visit calculation 

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

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

889 

890 @cache_translation 

891 def to_group_counter_end(self): 

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

893 counter = self.to_observation_counter() 

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

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

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

897 # final exposure in the sequence. 

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

899 seq_end = counter + remaining 

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

901 return seq_end 

902 else: 

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

904 # that is not going to confuse the visit calculation 

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

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

907 

908 @cache_translation 

909 def to_has_simulated_content(self): 

910 # Check all the simulation flags. 

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

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

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

914 # everything. The header looks like: 

915 # 

916 # HIERARCH SIMULATE ATMCS = / ATMCS Simulation Mode 

917 # HIERARCH SIMULATE ATHEXAPOD = 0 / ATHexapod Simulation Mode 

918 # HIERARCH SIMULATE ATPNEUMATICS = / ATPneumatics Simulation Mode 

919 # HIERARCH SIMULATE ATDOME = 1 / ATDome Simulation Mode 

920 # HIERARCH SIMULATE ATSPECTROGRAPH = 0 / ATSpectrograph Simulation Mode 

921 # 

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

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

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

925 if "SIMULATE" in k and v: 

926 return True 

927 

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

929 ctrlr_key = "CONTRLLR" 

930 if self.is_key_ok(ctrlr_key): 

931 controller = self._header[ctrlr_key] 

932 self._used_these_cards(ctrlr_key) 

933 if controller in "HPQ": 

934 return True 

935 

936 # No simulation flags set. 

937 return False