22 from __future__
import annotations
27 "GroupExposuresConfig",
29 "VisitDefinitionData",
32 from abc
import ABCMeta, abstractmethod
33 from collections
import defaultdict
36 from typing
import Any, Dict, Iterable, List, Optional, Tuple
37 from multiprocessing
import Pool
39 from lsst.daf.butler
import (
49 from lsst.geom
import Box2D
50 from lsst.pex.config
import Config, Field, makeRegistry, registerConfigurable
51 from lsst.afw.cameraGeom
import FOCAL_PLANE, PIXELS
52 from lsst.pipe.base
import Task
53 from lsst.sphgeom
import ConvexPolygon, Region, UnitVector3d
54 from ._instrument
import loadCamera, Instrument
57 @dataclasses.dataclass
59 """Struct representing a group of exposures that will be used to define a
64 """Name of the instrument this visit will be associated with.
68 """Integer ID of the visit.
70 This must be unique across all visit systems for the instrument.
74 """String name for the visit.
76 This must be unique across all visit systems for the instrument.
79 exposures: List[DimensionRecord] = dataclasses.field(default_factory=list)
80 """Dimension records for the exposures that are part of this visit.
84 @dataclasses.dataclass
86 """Struct containing the dimension records associated with a visit.
89 visit: DimensionRecord
90 """Record for the 'visit' dimension itself.
93 visit_definition: List[DimensionRecord]
94 """Records for 'visit_definition', which relates 'visit' to 'exposure'.
97 visit_detector_region: List[DimensionRecord]
98 """Records for 'visit_detector_region', which associates the combination
99 of a 'visit' and a 'detector' with a region on the sky.
107 class GroupExposuresTask(Task, metaclass=ABCMeta):
108 """Abstract base class for the subtask of `DefineVisitsTask` that is
109 responsible for grouping exposures into visits.
111 Subclasses should be registered with `GroupExposuresTask.registry` to
112 enable use by `DefineVisitsTask`, and should generally correspond to a
113 particular 'visit_system' dimension value. They are also responsible for
114 defining visit IDs and names that are unique across all visit systems in
115 use by an instrument.
119 config : `GroupExposuresConfig`
120 Configuration information.
122 Additional keyword arguments forwarded to the `Task` constructor.
124 def __init__(self, config: GroupExposuresConfig, **kwargs: Any):
125 Task.__init__(self, config=config, **kwargs)
127 ConfigClass = GroupExposuresConfig
129 _DefaultName =
"groupExposures"
131 registry = makeRegistry(
132 doc=
"Registry of algorithms for grouping exposures into visits.",
133 configBaseType=GroupExposuresConfig,
137 def group(self, exposures: List[DimensionRecord]) -> Iterable[VisitDefinitionData]:
138 """Group the given exposures into visits.
142 exposures : `list` [ `DimensionRecord` ]
143 DimensionRecords (for the 'exposure' dimension) describing the
148 visits : `Iterable` [ `VisitDefinitionData` ]
149 Structs identifying the visits and the exposures associated with
150 them. This may be an iterator or a container.
152 raise NotImplementedError()
156 """Return identifiers for the 'visit_system' dimension this
157 algorithm implements.
162 Integer ID for the visit system (given an instrument).
164 Unique string identifier for the visit system (given an
167 raise NotImplementedError()
174 doc=(
"Pad raw image bounding boxes with specified number of pixels "
175 "when calculating their (conservatively large) region on the "
181 """Abstract base class for the subtask of `DefineVisitsTask` that is
182 responsible for extracting spatial regions for visits and visit+detector
185 Subclasses should be registered with `ComputeVisitRegionsTask.registry` to
186 enable use by `DefineVisitsTask`.
190 config : `ComputeVisitRegionsConfig`
191 Configuration information.
192 butler : `lsst.daf.butler.Butler`
195 Additional keyword arguments forwarded to the `Task` constructor.
197 def __init__(self, config: ComputeVisitRegionsConfig, *, butler: Butler, **kwargs: Any):
198 Task.__init__(self, config=config, **kwargs)
202 ConfigClass = ComputeVisitRegionsConfig
204 _DefaultName =
"computeVisitRegions"
206 registry = makeRegistry(
207 doc=(
"Registry of algorithms for computing on-sky regions for visits "
208 "and visit+detector combinations."),
209 configBaseType=ComputeVisitRegionsConfig,
213 """Retrieve an `~lsst.obs.base.Instrument` associated with this
218 instrumentName : `str`
219 The name of the instrument.
223 instrument : `~lsst.obs.base.Instrument`
224 The associated instrument object.
228 The result is cached.
231 if instrument
is None:
232 instrument = Instrument.fromName(instrumentName, self.
butler.registry)
237 def compute(self, visit: VisitDefinitionData, *, collections: Any =
None
238 ) -> Tuple[Region, Dict[int, Region]]:
239 """Compute regions for the given visit and all detectors in that visit.
243 visit : `VisitDefinitionData`
244 Struct describing the visit and the exposures associated with it.
245 collections : Any, optional
246 Collections to be searched for raws and camera geometry, overriding
247 ``self.butler.collections``.
248 Can be any of the types supported by the ``collections`` argument
249 to butler construction.
253 visitRegion : `lsst.sphgeom.Region`
254 Region for the full visit.
255 visitDetectorRegions : `dict` [ `int`, `lsst.sphgeom.Region` ]
256 Dictionary mapping detector ID to the region for that detector.
257 Should include all detectors in the visit.
259 raise NotImplementedError()
263 groupExposures = GroupExposuresTask.registry.makeField(
264 doc=
"Algorithm for grouping exposures into visits.",
265 default=
"one-to-one",
267 computeVisitRegions = ComputeVisitRegionsTask.registry.makeField(
268 doc=
"Algorithm from computing visit and visit+detector regions.",
269 default=
"single-raw-wcs",
271 ignoreNonScienceExposures = Field(
272 doc=(
"If True, silently ignore input exposures that do not have "
273 "observation_type=SCIENCE. If False, raise an exception if one "
282 """Driver Task for defining visits (and their spatial regions) in Gen3
287 config : `DefineVisitsConfig`
288 Configuration for the task.
289 butler : `~lsst.daf.butler.Butler`
290 Writeable butler instance. Will be used to read `raw.wcs` and `camera`
291 datasets and insert/sync dimension data.
293 Additional keyword arguments are forwarded to the `lsst.pipe.base.Task`
298 Each instance of `DefineVisitsTask` reads from / writes to the same Butler.
299 Each invocation of `DefineVisitsTask.run` processes an independent group of
300 exposures into one or more new vists, all belonging to the same visit
301 system and instrument.
303 The actual work of grouping exposures and computing regions is delegated
304 to pluggable subtasks (`GroupExposuresTask` and `ComputeVisitRegionsTask`),
305 respectively. The defaults are to create one visit for every exposure,
306 and to use exactly one (arbitrary) detector-level raw dataset's WCS along
307 with camera geometry to compute regions for all detectors. Other
308 implementations can be created and configured for instruments for which
309 these choices are unsuitable (e.g. because visits and exposures are not
310 one-to-one, or because ``raw.wcs`` datasets for different detectors may not
311 be consistent with camera geomery).
313 It is not necessary in general to ingest all raws for an exposure before
314 defining a visit that includes the exposure; this depends entirely on the
315 `ComputeVisitRegionTask` subclass used. For the default configuration,
316 a single raw for each exposure is sufficient.
318 def __init__(self, config: Optional[DefineVisitsConfig] =
None, *, butler: Butler, **kwargs: Any):
323 self.makeSubtask(
"groupExposures")
324 self.makeSubtask(
"computeVisitRegions", butler=self.
butler)
326 def _reduce_kwargs(self):
328 return dict(**super()._reduce_kwargs(), butler=self.
butler)
330 ConfigClass = DefineVisitsConfig
332 _DefaultName =
"defineVisits"
334 def _buildVisitRecords(self, definition: VisitDefinitionData, *,
335 collections: Any =
None) -> _VisitRecords:
336 """Build the DimensionRecords associated with a visit.
340 definition : `VisitDefinition`
341 Struct with identifiers for the visit and records for its
342 constituent exposures.
343 collections : Any, optional
344 Collections to be searched for raws and camera geometry, overriding
345 ``self.butler.collections``.
346 Can be any of the types supported by the ``collections`` argument
347 to butler construction.
351 records : `_VisitRecords`
352 Struct containing DimensionRecords for the visit, including
353 associated dimension elements.
356 visitRegion, visitDetectorRegions = self.computeVisitRegions.compute(definition,
357 collections=collections)
360 begin=_reduceOrNone(min, (e.timespan.begin
for e
in definition.exposures)),
361 end=_reduceOrNone(max, (e.timespan.end
for e
in definition.exposures)),
363 exposure_time = _reduceOrNone(sum, (e.exposure_time
for e
in definition.exposures))
364 physical_filter = _reduceOrNone(
lambda a, b: a
if a == b
else None,
365 (e.physical_filter
for e
in definition.exposures))
366 target_name = _reduceOrNone(
lambda a, b: a
if a == b
else None,
367 (e.target_name
for e
in definition.exposures))
368 science_program = _reduceOrNone(
lambda a, b: a
if a == b
else None,
369 (e.science_program
for e
in definition.exposures))
370 observation_reason = _reduceOrNone(
lambda a, b: a
if a == b
else None,
371 (e.observation_reason
for e
in definition.exposures))
372 if observation_reason
is None:
374 observation_reason =
"various"
377 zenith_angle = _reduceOrNone(sum, (e.zenith_angle
for e
in definition.exposures))
378 if zenith_angle
is not None:
379 zenith_angle /= len(definition.exposures)
383 visit=self.
universe[
"visit"].RecordClass(
384 instrument=definition.instrument,
386 name=definition.name,
387 physical_filter=physical_filter,
388 target_name=target_name,
389 science_program=science_program,
390 observation_reason=observation_reason,
391 zenith_angle=zenith_angle,
392 visit_system=self.groupExposures.getVisitSystem()[0],
393 exposure_time=exposure_time,
401 self.
universe[
"visit_definition"].RecordClass(
402 instrument=definition.instrument,
404 exposure=exposure.id,
405 visit_system=self.groupExposures.getVisitSystem()[0],
407 for exposure
in definition.exposures
409 visit_detector_region=[
410 self.
universe[
"visit_detector_region"].RecordClass(
411 instrument=definition.instrument,
414 region=detectorRegion,
416 for detectorId, detectorRegion
in visitDetectorRegions.items()
420 def _expandExposureId(self, dataId: DataId) -> DataCoordinate:
421 """Return the expanded version of an exposure ID.
423 A private method to allow ID expansion in a pool without resorting
428 dataId : `dict` or `DataCoordinate`
429 Exposure-level data ID.
433 expanded : `DataCoordinate`
434 A data ID that includes full metadata for all exposure dimensions.
436 dimensions = DimensionGraph(self.
universe, names=[
"exposure"])
437 return self.
butler.registry.expandDataId(dataId, graph=dimensions)
439 def _buildVisitRecordsSingle(self, args) -> _VisitRecords:
440 """Build the DimensionRecords associated with a visit and collection.
442 A wrapper for `_buildVisitRecords` to allow it to be run as part of
443 a pool without resorting to local callables.
447 args : `tuple` [`VisitDefinition`, any]
448 A tuple consisting of the ``definition`` and ``collections``
449 arguments to `_buildVisitRecords`, in that order.
453 records : `_VisitRecords`
454 Struct containing DimensionRecords for the visit, including
455 associated dimension elements.
459 def run(self, dataIds: Iterable[DataId], *,
460 pool: Optional[Pool] =
None,
462 collections: Optional[str] =
None):
463 """Add visit definitions to the registry for the given exposures.
467 dataIds : `Iterable` [ `dict` or `DataCoordinate` ]
468 Exposure-level data IDs. These must all correspond to the same
469 instrument, and are expected to be on-sky science exposures.
470 pool : `multiprocessing.Pool`, optional
471 If not `None`, a process pool with which to parallelize some
473 processes : `int`, optional
474 The number of processes to use. Ignored if ``pool`` is not `None`.
475 collections : Any, optional
476 Collections to be searched for raws and camera geometry, overriding
477 ``self.butler.collections``.
478 Can be any of the types supported by the ``collections`` argument
479 to butler construction.
482 if pool
is None and processes > 1:
483 pool = Pool(processes)
484 mapFunc = map
if pool
is None else pool.imap_unordered
486 self.log.info(
"Preprocessing data IDs.")
489 raise RuntimeError(
"No exposures given.")
494 for dataId
in dataIds:
495 record = dataId.records[
"exposure"]
496 if record.observation_type !=
"science":
497 if self.config.ignoreNonScienceExposures:
500 raise RuntimeError(f
"Input exposure {dataId} has observation_type "
501 f
"{record.observation_type}, not 'science'.")
502 instruments.add(dataId[
"instrument"])
503 exposures.append(record)
505 self.log.info(
"No science exposures found after filtering.")
507 if len(instruments) > 1:
509 f
"All data IDs passed to DefineVisitsTask.run must be "
510 f
"from the same instrument; got {instruments}."
512 instrument, = instruments
515 visitSystemId, visitSystemName = self.groupExposures.getVisitSystem()
516 self.log.info(
"Registering visit_system %d: %s.", visitSystemId, visitSystemName)
517 self.
butler.registry.syncDimensionData(
519 {
"instrument": instrument,
"id": visitSystemId,
"name": visitSystemName}
522 self.log.info(
"Grouping %d exposure(s) into visits.", len(exposures))
523 definitions = list(self.groupExposures.group(exposures))
527 self.log.info(
"Computing regions and other metadata for %d visit(s).", len(definitions))
529 zip(definitions, itertools.repeat(collections)))
532 for visitRecords
in allRecords:
533 with self.
butler.registry.transaction():
534 self.
butler.registry.insertDimensionData(
"visit", visitRecords.visit)
535 self.
butler.registry.insertDimensionData(
"visit_definition",
536 *visitRecords.visit_definition)
537 self.
butler.registry.insertDimensionData(
"visit_detector_region",
538 *visitRecords.visit_detector_region)
541 def _reduceOrNone(func, iterable):
542 """Apply a binary function to pairs of elements in an iterable until a
543 single value is returned, but return `None` if any element is `None` or
544 there are no elements.
558 visitSystemId = Field(
559 doc=(
"Integer ID of the visit_system implemented by this grouping "
564 visitSystemName = Field(
565 doc=(
"String name of the visit_system implemented by this grouping "
568 default=
"one-to-one",
572 @registerConfigurable(
"one-to-one", GroupExposuresTask.registry)
574 """An exposure grouping algorithm that simply defines one visit for each
575 exposure, reusing the exposures identifiers for the visit.
578 ConfigClass = _GroupExposuresOneToOneConfig
580 def group(self, exposures: List[DimensionRecord]) -> Iterable[VisitDefinitionData]:
582 for exposure
in exposures:
584 instrument=exposure.instrument,
587 exposures=[exposure],
592 return (self.config.visitSystemId, self.config.visitSystemName)
596 visitSystemId = Field(
597 doc=(
"Integer ID of the visit_system implemented by this grouping "
602 visitSystemName = Field(
603 doc=(
"String name of the visit_system implemented by this grouping "
606 default=
"by-group-metadata",
610 @registerConfigurable(
"by-group-metadata", GroupExposuresTask.registry)
612 """An exposure grouping algorithm that uses exposure.group_name and
615 This algorithm _assumes_ exposure.group_id (generally populated from
616 `astro_metadata_translator.ObservationInfo.visit_id`) is not just unique,
617 but disjoint from all `ObservationInfo.exposure_id` values - if it isn't,
618 it will be impossible to ever use both this grouping algorithm and the
619 one-to-one algorithm for a particular camera in the same data repository.
622 ConfigClass = _GroupExposuresByGroupMetadataConfig
624 def group(self, exposures: List[DimensionRecord]) -> Iterable[VisitDefinitionData]:
626 groups = defaultdict(list)
627 for exposure
in exposures:
628 groups[exposure.group_name].append(exposure)
629 for visitName, exposuresInGroup
in groups.items():
630 instrument = exposuresInGroup[0].instrument
631 visitId = exposuresInGroup[0].group_id
632 assert all(e.group_id == visitId
for e
in exposuresInGroup), \
633 "Grouping by exposure.group_name does not yield consistent group IDs"
635 exposures=exposuresInGroup)
639 return (self.config.visitSystemId, self.config.visitSystemName)
643 mergeExposures = Field(
644 doc=(
"If True, merge per-detector regions over all exposures in a "
645 "visit (via convex hull) instead of using the first exposure and "
646 "assuming its regions are valid for all others."),
651 doc=(
"Load the WCS for the detector with this ID. If None, use an "
652 "arbitrary detector (the first found in a query of the data "
653 "repository for each exposure (or all exposures, if "
654 "mergeExposures is True)."),
659 requireVersionedCamera = Field(
660 doc=(
"If True, raise LookupError if version camera geometry cannot be "
661 "loaded for an exposure. If False, use the nominal camera from "
662 "the Instrument class instead."),
669 @registerConfigurable(
"single-raw-wcs", ComputeVisitRegionsTask.registry)
671 """A visit region calculator that uses a single raw WCS and a camera to
672 project the bounding boxes of all detectors onto the sky, relating
673 different detectors by their positions in focal plane coordinates.
677 Most instruments should have their raw WCSs determined from a combination
678 of boresight angle, rotator angle, and camera geometry, and hence this
679 algorithm should produce stable results regardless of which detector the
680 raw corresponds to. If this is not the case (e.g. because a per-file FITS
681 WCS is used instead), either the ID of the detector should be fixed (see
682 the ``detectorId`` config parameter) or a different algorithm used.
685 ConfigClass = _ComputeVisitRegionsFromSingleRawWcsConfig
688 ) -> Dict[int, List[UnitVector3d]]:
689 """Compute the lists of unit vectors on the sphere that correspond to
690 the sky positions of detector corners.
694 exposure : `DimensionRecord`
695 Dimension record for the exposure.
696 collections : Any, optional
697 Collections to be searched for raws and camera geometry, overriding
698 ``self.butler.collections``.
699 Can be any of the types supported by the ``collections`` argument
700 to butler construction.
705 Dictionary mapping detector ID to a list of unit vectors on the
706 sphere representing that detector's corners projected onto the sky.
708 if collections
is None:
709 collections = self.
butler.collections
710 camera, versioned =
loadCamera(self.
butler, exposure.dataId, collections=collections)
711 if not versioned
and self.config.requireVersionedCamera:
712 raise LookupError(f
"No versioned camera found for exposure {exposure.dataId}.")
717 orientation = lsst.geom.Angle(exposure.sky_angle, lsst.geom.degrees)
718 radec = lsst.geom.SpherePoint(lsst.geom.Angle(exposure.tracking_ra, lsst.geom.degrees),
719 lsst.geom.Angle(exposure.tracking_dec, lsst.geom.degrees))
720 except AttributeError:
724 if self.config.detectorId
is None:
725 detectorId = next(camera.getIdIter())
727 detectorId = self.config.detectorId
728 wcsDetector = camera[detectorId]
733 rawFormatter = instrument.getRawFormatter({
"detector": detectorId})
734 wcs = rawFormatter.makeRawSkyWcsFromBoresight(radec, orientation, wcsDetector)
737 if self.config.detectorId
is None:
738 wcsRefsIter = self.
butler.registry.queryDatasets(
"raw.wcs", dataId=exposure.dataId,
739 collections=collections)
741 raise LookupError(f
"No raw.wcs datasets found for data ID {exposure.dataId} "
742 f
"in collections {collections}.")
743 wcsRef = next(iter(wcsRefsIter))
744 wcsDetector = camera[wcsRef.dataId[
"detector"]]
745 wcs = self.
butler.getDirect(wcsRef)
747 wcsDetector = camera[self.config.detectorId]
748 wcs = self.
butler.get(
"raw.wcs", dataId=exposure.dataId, detector=self.config.detectorId,
749 collections=collections)
750 fpToSky = wcsDetector.getTransform(FOCAL_PLANE, PIXELS).then(wcs.getTransform())
752 for detector
in camera:
753 pixelsToSky = detector.getTransform(PIXELS, FOCAL_PLANE).then(fpToSky)
754 pixCorners = Box2D(detector.getBBox().dilatedBy(self.config.padding)).getCorners()
755 bounds[detector.getId()] = [
756 skyCorner.getVector()
for skyCorner
in pixelsToSky.applyForward(pixCorners)
760 def compute(self, visit: VisitDefinitionData, *, collections: Any =
None
761 ) -> Tuple[Region, Dict[int, Region]]:
763 if self.config.mergeExposures:
764 detectorBounds = defaultdict(list)
765 for exposure
in visit.exposures:
767 for detectorId, bounds
in exposureDetectorBounds.items():
768 detectorBounds[detectorId].extend(bounds)
773 for detectorId, bounds
in detectorBounds.items():
774 detectorRegions[detectorId] = ConvexPolygon.convexHull(bounds)
775 visitBounds.extend(bounds)
776 return ConvexPolygon.convexHull(visitBounds), detectorRegions