21 from __future__
import annotations
23 """Module defining GraphBuilder class and related methods. 26 __all__ = [
'GraphBuilder']
33 from collections
import ChainMap
34 from dataclasses
import dataclass
35 from typing
import Set, List, Dict, Optional, Iterable
41 from .pipeline
import PipelineDatasetTypes, TaskDatasetTypes, Pipeline, TaskDef
42 from .graph
import QuantumGraph, QuantumGraphTaskNodes
43 from lsst.daf.butler
import Quantum, DatasetRef, DimensionGraph, DataId, DimensionUniverse, DatasetType
44 from lsst.daf.butler.core.utils
import NamedKeyDict
45 from lsst.daf.butler.sql
import DataIdQueryBuilder, SingleDatasetQueryBuilder
51 _LOG = logging.getLogger(__name__.partition(
".")[2])
56 """Helper class aggregating information about a `DatasetType`, used when 57 constructing a `QuantumGraph`. 59 `_DatasetScaffolding` does not hold the `DatasetType` instance itself 60 because it is usually used as the value type in `_DatasetScaffoldingDict`, 61 which uses `DatasetType` instances as keys. 63 See `_PipelineScaffolding` for a top-down description of the full 64 scaffolding data structure. 68 dimensions : `DimensionGraph` 69 Dimensions of the `DatasetType`, expanded to include implied 72 def __init__(self, dimensions: DimensionGraph):
79 __slots__ = (
"dimensions",
"producer",
"consumers",
"dataIds",
"refs")
81 dimensions: DimensionGraph
82 """The dimensions of the dataset type, expanded to included implied 85 Set during `_PipelineScaffolding` construction. 88 producer: Optional[_TaskScaffolding]
89 """The scaffolding objects for the Task that produces this dataset. 91 Set during `_PipelineScaffolding` construction. 94 consumers: Dict[str, _TaskScaffolding]
95 """The scaffolding objects for the Tasks that consume this dataset, 96 keyed by their label in the `Pipeline`. 98 Set during `_PipelineScaffolding` construction. 102 """Data IDs for all instances of this dataset type in the graph. 104 These data IDs cover the full set of implied-expanded dimensions (i.e. 105 the `dimensions` attribute of this instance), which is a supserset of the 106 dimensions used in `DatasetRef` instances (e.g. in ``refs``). 108 Populated after construction by `_PipelineScaffolding.fillDataIds`. 111 refs: List[DatasetRef]
112 """References for all instances of this dataset type in the graph. 114 Populated after construction by `_PipelineScaffolding.fillDatasetRefs`. 119 """Custom dictionary that maps `DatasetType` to `_DatasetScaffolding`. 121 See `_PipelineScaffolding` for a top-down description of the full 122 scaffolding data structure. 127 Positional arguments are forwarded to the `dict` constructor. 128 universe : `DimensionUniverse` 129 Universe of all possible dimensions. 131 def __init__(self, *args, universe: DimensionGraph):
137 universe: DimensionUniverse) -> _DatasetScaffoldingDict:
138 """Construct a a dictionary from a flat iterable of `DatasetType` keys. 142 datasetTypes : `iterable` of `DatasetType` 143 DatasetTypes to use as keys for the dict. Values will be 144 constructed from the dimensions of the keys. 145 universe : `DimensionUniverse` 146 Universe of all possible dimensions. 150 dictionary : `_DatasetScaffoldingDict` 151 A new dictionary instance. 154 for datasetType
in datasetTypes),
158 def fromSubset(cls, datasetTypes: Iterable[DatasetType], first: _DatasetScaffoldingDict,
159 *rest) -> _DatasetScaffoldingDict:
160 """Return a new dictionary by extracting items corresponding to the 161 given keys from one or more existing dictionaries. 165 datasetTypes : `iterable` of `DatasetType` 166 DatasetTypes to use as keys for the dict. Values will be obtained 167 by lookups against ``first`` and ``rest``. 168 first : `_DatasetScaffoldingDict` 169 Another dictionary from which to extract values. 171 Additional dictionaries from which to extract values. 175 dictionary : `_DatasetScaffoldingDict` 176 A new dictionary instance. 178 combined = ChainMap(first, *rest)
179 return cls(((datasetType, combined[datasetType])
for datasetType
in datasetTypes),
180 universe=first.universe)
184 """The union of all dimensions used by all dataset types in this 185 dictionary, including implied dependencies (`DimensionGraph`). 190 return base.union(*(scaffolding.dimensions
for scaffolding
in self.values()), implied=
True)
193 """Unpack nested single-element `DatasetRef` lists into a new 196 This method assumes that each `_DatasetScaffolding.refs` list contains 197 exactly one `DatasetRef`, as is the case for all "init" datasets. 201 dictionary : `NamedKeyDict` 202 Dictionary mapping `DatasetType` to `DatasetRef`, with both 203 `DatasetType` instances and string names usable as keys. 205 return NamedKeyDict((datasetType, scaffolding.refs[0])
for datasetType, scaffolding
in self.items())
210 """Helper class aggregating information about a `PipelineTask`, used when 211 constructing a `QuantumGraph`. 213 See `_PipelineScaffolding` for a top-down description of the full 214 scaffolding data structure. 219 Data structure that identifies the task class and its config. 220 parent : `_PipelineScaffolding` 221 The parent data structure that will hold the instance being 223 datasetTypes : `TaskDatasetTypes` 224 Data structure that categorizes the dataset types used by this task. 229 Raised if the task's dimensions are not a subset of the union of the 230 pipeline's dataset dimensions. 232 def __init__(self, taskDef: TaskDef, parent: _PipelineScaffolding, datasetTypes: TaskDatasetTypes):
233 universe = parent.dimensions.universe
235 self.
dimensions = universe.extract(taskDef.connections.dimensions, implied=
True)
236 if not self.
dimensions.issubset(parent.dimensions):
238 f
"{self.dimensions.toSet()} that are not a subset of " 239 f
"the pipeline dimensions {parent.dimensions.toSet()}.")
242 self.
initInputs = _DatasetScaffoldingDict.fromSubset(datasetTypes.initInputs,
243 parent.initInputs, parent.initIntermediates)
244 self.
initOutputs = _DatasetScaffoldingDict.fromSubset(datasetTypes.initOutputs,
245 parent.initIntermediates, parent.initOutputs)
246 self.
inputs = _DatasetScaffoldingDict.fromSubset(datasetTypes.inputs,
247 parent.inputs, parent.intermediates)
248 self.
outputs = _DatasetScaffoldingDict.fromSubset(datasetTypes.outputs,
249 parent.intermediates, parent.outputs)
250 self.
prerequisites = _DatasetScaffoldingDict.fromSubset(datasetTypes.prerequisites,
251 parent.prerequisites)
254 for dataset
in itertools.chain(self.
initInputs.values(), self.
inputs.values(),
256 dataset.consumers[self.
taskDef.label] = self
258 assert dataset.producer
is None 259 dataset.producer = self
264 """Data structure that identifies the task class and its config 268 dimensions: DimensionGraph
269 """The dimensions of a single `Quantum` of this task, expanded to include 270 implied dependencies (`DimensionGraph`). 273 initInputs: _DatasetScaffoldingDict
274 """Dictionary containing information about datasets used to construct this 275 task (`_DatasetScaffoldingDict`). 278 initOutputs: _DatasetScaffoldingDict
279 """Dictionary containing information about datasets produced as a 280 side-effect of constructing this task (`_DatasetScaffoldingDict`). 283 inputs: _DatasetScaffoldingDict
284 """Dictionary containing information about datasets used as regular, 285 graph-constraining inputs to this task (`_DatasetScaffoldingDict`). 288 outputs: _DatasetScaffoldingDict
289 """Dictionary containing information about datasets produced by this task 290 (`_DatasetScaffoldingDict`). 293 prerequisites: _DatasetScaffoldingDict
294 """Dictionary containing information about input datasets that must be 295 present in the repository before any Pipeline containing this task is run 296 (`_DatasetScaffoldingDict`). 300 """Data IDs for all quanta for this task in the graph (`set` of `DataId`). 302 Populated after construction by `_PipelineScaffolding.fillDataIds`. 305 quanta: List[Quantum]
306 """All quanta for this task in the graph (`list` of `Quantum`). 308 Populated after construction by `_PipelineScaffolding.fillQuanta`. 313 connectionClass = config.connections.ConnectionsClass
314 connectionInstance = connectionClass(config=config)
317 result = connectionInstance.adjustQuantum(quantum.predictedInputs)
318 quantum._predictedInputs = NamedKeyDict(result)
321 self.
quanta.append(quantum)
324 """Create a `QuantumGraphTaskNodes` instance from the information in 329 nodes : `QuantumGraphTaskNodes` 330 The `QuantumGraph` elements corresponding to this task. 342 """A helper data structure that organizes the information involved in 343 constructing a `QuantumGraph` for a `Pipeline`. 347 pipeline : `Pipeline` 348 Sequence of tasks from which a graph is to be constructed. Must 349 have nested task classes already imported. 350 universe : `DimensionUniverse` 351 Universe of all possible dimensions. 356 Raised if the task's dimensions are not a subset of the union of the 357 pipeline's dataset dimensions. 361 The scaffolding data structure contains nested data structures for both 362 tasks (`_TaskScaffolding`) and datasets (`_DatasetScaffolding`), with the 363 latter held by `_DatasetScaffoldingDict`. The dataset data structures are 364 shared between the pipeline-level structure (which aggregates all datasets 365 and categorizes them from the perspective of the complete pipeline) and the 366 individual tasks that use them as inputs and outputs. 368 `QuantumGraph` construction proceeds in five steps, with each corresponding 369 to a different `_PipelineScaffolding` method: 371 1. When `_PipelineScaffolding` is constructed, we extract and categorize 372 the DatasetTypes used by the pipeline (delegating to 373 `PipelineDatasetTypes.fromPipeline`), then use these to construct the 374 nested `_TaskScaffolding` and `_DatasetScaffolding` objects. 376 2. In `fillDataIds`, we construct and run the "Big Join Query", which 377 returns related tuples of all dimensions used to identify any regular 378 input, output, and intermediate datasets (not prerequisites). We then 379 iterate over these tuples of related dimensions, identifying the subsets 380 that correspond to distinct data IDs for each task and dataset type. 382 3. In `fillDatasetRefs`, we run follow-up queries against all of the 383 dataset data IDs previously identified, populating the 384 `_DatasetScaffolding.refs` lists - except for those for prerequisite 385 datasets, which cannot be resolved until distinct quanta are 388 4. In `fillQuanta`, we extract subsets from the lists of `DatasetRef` into 389 the inputs and outputs for each `Quantum` and search for prerequisite 390 datasets, populating `_TaskScaffolding.quanta`. 392 5. In `makeQuantumGraph`, we construct a `QuantumGraph` from the lists of 393 per-task quanta identified in the previous step. 398 datasetTypes = PipelineDatasetTypes.fromPipeline(pipeline, universe=universe)
401 for attr
in (
"initInputs",
"initIntermediates",
"initOutputs",
402 "inputs",
"intermediates",
"outputs",
"prerequisites"):
403 setattr(self, attr, _DatasetScaffoldingDict.fromDatasetTypes(getattr(datasetTypes, attr),
407 self.
dimensions = self.inputs.dimensions.union(self.inputs.dimensions,
408 self.intermediates.dimensions,
409 self.outputs.dimensions, implied=
True)
415 for taskDef, taskDatasetTypes
in zip(pipeline, datasetTypes.byTask.values())]
417 tasks: List[_TaskScaffolding]
418 """Scaffolding data structures for each task in the pipeline 419 (`list` of `_TaskScaffolding`). 422 initInputs: _DatasetScaffoldingDict
423 """Datasets consumed but not produced when constructing the tasks in this 424 pipeline (`_DatasetScaffoldingDict`). 427 initIntermediates: _DatasetScaffoldingDict
428 """Datasets that are both consumed and produced when constructing the tasks 429 in this pipeline (`_DatasetScaffoldingDict`). 432 initOutputs: _DatasetScaffoldingDict
433 """Datasets produced but not consumed when constructing the tasks in this 434 pipeline (`_DatasetScaffoldingDict`). 437 inputs: _DatasetScaffoldingDict
438 """Datasets that are consumed but not produced when running this pipeline 439 (`_DatasetScaffoldingDict`). 442 intermediates: _DatasetScaffoldingDict
443 """Datasets that are both produced and consumed when running this pipeline 444 (`_DatasetScaffoldingDict`). 447 outputs: _DatasetScaffoldingDict
448 """Datasets produced but not consumed when when running this pipeline 449 (`_DatasetScaffoldingDict`). 452 prerequisites: _DatasetScaffoldingDict
453 """Datasets that are consumed when running this pipeline and looked up 454 per-Quantum when generating the graph (`_DatasetScaffoldingDict`). 457 dimensions: DimensionGraph
458 """All dimensions used by any regular input, intermediate, or output 459 (not prerequisite) dataset; the set of dimension used in the "Big Join 460 Query" (`DimensionGraph`). 462 This is required to be a superset of all task quantum dimensions. 466 """Query for the data IDs that connect nodes in the `QuantumGraph`. 468 This method populates `_TaskScaffolding.dataIds` and 469 `_DatasetScaffolding.dataIds` (except for those in `prerequisites`). 473 registry : `lsst.daf.butler.Registry` 474 Registry for the data repository; used for all data ID queries. 475 originInfo : `lsst.daf.butler.DatasetOriginInfo` 476 Object holding the input and output collections for each 478 userQuery : `str`, optional 479 User-provided expression to limit the data IDs processed. 482 emptyDataId = DataId(dimensions=registry.dimensions.empty)
483 for scaffolding
in itertools.chain(self.initInputs.values(),
484 self.initIntermediates.values(),
485 self.initOutputs.values()):
486 scaffolding.dataIds.add(emptyDataId)
489 query = DataIdQueryBuilder.fromDimensions(registry, self.
dimensions)
492 for datasetType
in self.inputs:
493 query.requireDataset(datasetType, originInfo.getInputCollections(datasetType.name))
496 query.whereParsedExpression(userQuery)
510 for commonDataId
in query.execute():
511 for taskScaffolding
in self.
tasks:
512 dataId = DataId(commonDataId, dimensions=taskScaffolding.dimensions)
513 taskScaffolding.dataIds.add(dataId)
514 for datasetType, scaffolding
in itertools.chain(self.inputs.items(),
515 self.intermediates.items(),
516 self.outputs.items()):
517 dataId = DataId(commonDataId, dimensions=scaffolding.dimensions)
518 scaffolding.dataIds.add(dataId)
520 def fillDatasetRefs(self, registry, originInfo, *, skipExisting=True, clobberExisting=False):
521 """Perform follow up queries for each dataset data ID produced in 524 This method populates `_DatasetScaffolding.refs` (except for those in 529 registry : `lsst.daf.butler.Registry` 530 Registry for the data repository; used for all data ID queries. 531 originInfo : `lsst.daf.butler.DatasetOriginInfo` 532 Object holding the input and output collections for each 534 skipExisting : `bool`, optional 535 If `True` (default), a Quantum is not created if all its outputs 537 clobberExisting : `bool`, optional 538 If `True`, overwrite any outputs that already exist. Cannot be 539 `True` if ``skipExisting`` is. 544 Raised if both `skipExisting` and `clobberExisting` are `True`. 546 Raised if an output dataset already exists in the output collection 547 and both ``skipExisting`` and ``clobberExisting`` are `False`. The 548 case where some but not all of a quantum's outputs are present and 549 ``skipExisting`` is `True` cannot be identified at this stage, and 550 is handled by `fillQuanta` instead. 552 if clobberExisting
and skipExisting:
553 raise ValueError(
"clobberExisting and skipExisting cannot both be true.")
555 for datasetType, scaffolding
in itertools.chain(self.initInputs.items(), self.inputs.items()):
556 for dataId
in scaffolding.dataIds:
562 builder = SingleDatasetQueryBuilder.fromCollections(
563 registry, datasetType,
564 collections=originInfo.getInputCollections(datasetType.name)
566 builder.whereDataId(dataId)
567 ref = builder.executeOne(expandDataId=
True)
572 ref = DatasetRef(datasetType, DataId(dataId, dimensions=datasetType.dimensions))
573 scaffolding.refs.append(ref)
577 for datasetType, scaffolding
in itertools.chain(self.initIntermediates.items(),
578 self.initOutputs.items(),
579 self.intermediates.items(),
580 self.outputs.items()):
581 collection = originInfo.getOutputCollection(datasetType.name)
582 for dataId
in scaffolding.dataIds:
591 ref = registry.find(collection=collection, datasetType=datasetType, dataId=dataId)
595 ref = DatasetRef(datasetType, DataId(dataId, dimensions=datasetType.dimensions))
596 elif not skipExisting:
598 f
"output collection {collection} with data ID {dataId}.")
599 scaffolding.refs.append(ref)
602 def fillQuanta(self, registry, originInfo, *, skipExisting=True):
603 """Define quanta for each task by splitting up the datasets associated 604 with each task data ID. 606 This method populates `_TaskScaffolding.quanta`. 610 registry : `lsst.daf.butler.Registry` 611 Registry for the data repository; used for all data ID queries. 612 originInfo : `lsst.daf.butler.DatasetOriginInfo` 613 Object holding the input and output collections for each 615 skipExisting : `bool`, optional 616 If `True` (default), a Quantum is not created if all its outputs 619 for task
in self.
tasks:
620 for quantumDataId
in task.dataIds:
627 inputs = NamedKeyDict()
628 for datasetType, scaffolding
in task.inputs.items():
629 inputs[datasetType] = [ref
for ref, dataId
in zip(scaffolding.refs, scaffolding.dataIds)
630 if quantumDataId.matches(dataId)]
632 outputs = NamedKeyDict()
633 allOutputsPresent =
True 634 for datasetType, scaffolding
in task.outputs.items():
635 outputs[datasetType] = []
636 for ref, dataId
in zip(scaffolding.refs, scaffolding.dataIds):
637 if quantumDataId.matches(dataId):
639 allOutputsPresent =
False 641 assert skipExisting,
"Existing outputs should have already been identified." 642 if not allOutputsPresent:
644 f
"{dataId} already exists, but other outputs " 645 f
"for task with label {task.taskDef.label} " 646 f
"and data ID {quantumDataId} do not.")
647 outputs[datasetType].append(ref)
648 if allOutputsPresent
and skipExisting:
659 for datasetType, scaffolding
in task.prerequisites.items():
660 builder = SingleDatasetQueryBuilder.fromCollections(
661 registry, datasetType,
662 collections=originInfo.getInputCollections(datasetType.name)
664 if not datasetType.dimensions.issubset(quantumDataId.dimensions()):
665 builder.relateDimensions(quantumDataId.dimensions(), addResultColumns=
False)
666 builder.whereDataId(quantumDataId)
667 refs = list(builder.execute(expandDataId=
True))
670 f
"No instances of prerequisite dataset {datasetType.name} found for task " 671 f
"with label {task.taskDef.label} and quantum data ID {quantumDataId}." 673 inputs[datasetType] = refs
676 taskName=task.taskDef.taskName,
677 taskClass=task.taskDef.taskClass,
678 dataId=quantumDataId,
679 initInputs=task.initInputs.unpackRefs(),
680 predictedInputs=inputs,
686 """Create a `QuantumGraph` from the quanta already present in 687 the scaffolding data structure. 690 graph.initInputs = self.initInputs.unpackRefs()
691 graph.initOutputs = self.initOutputs.unpackRefs()
692 graph.initIntermediates = self.initIntermediates.unpackRefs()
702 """Base class for exceptions generated by graph builder. 707 class OutputExistsError(GraphBuilderError):
708 """Exception generated when output datasets already exist. 714 """Exception generated when a prerequisite dataset does not exist. 720 """GraphBuilder class is responsible for building task execution graph from 725 taskFactory : `TaskFactory` 726 Factory object used to load/instantiate PipelineTasks 727 registry : `~lsst.daf.butler.Registry` 728 Data butler instance. 729 skipExisting : `bool`, optional 730 If `True` (default), a Quantum is not created if all its outputs 732 clobberExisting : `bool`, optional 733 If `True`, overwrite any outputs that already exist. Cannot be 734 `True` if ``skipExisting`` is. 737 def __init__(self, taskFactory, registry, skipExisting=True, clobberExisting=False):
744 def _loadTaskClass(self, taskDef):
745 """Make sure task class is loaded. 747 Load task class, update task name to make sure it is fully-qualified, 748 do not update original taskDef in a Pipeline though. 756 `TaskDef` instance, may be the same as parameter if task class is 759 if taskDef.taskClass
is None:
760 tClass, tName = self.
taskFactory.loadTaskClass(taskDef.taskName)
761 taskDef = copy.copy(taskDef)
762 taskDef.taskClass = tClass
763 taskDef.taskName = tName
767 """Create execution graph for a pipeline. 771 pipeline : `Pipeline` 772 Pipeline definition, task names/classes and their configs. 773 originInfo : `~lsst.daf.butler.DatasetOriginInfo` 774 Object which provides names of the input/output collections. 776 String which defunes user-defined selection for registry, should be 777 empty or `None` if there is no restrictions on data selection. 781 graph : `QuantumGraph` 786 Raised when user expression cannot be parsed. 788 Raised when output datasets already exist. 790 Other exceptions types may be raised by underlying registry 802 scaffolding.fillDataIds(self.
registry, originInfo, userQuery)
803 scaffolding.fillDatasetRefs(self.
registry, originInfo,
806 scaffolding.fillQuanta(self.
registry, originInfo,
809 return scaffolding.makeQuantumGraph()
def makeGraph(self, pipeline, originInfo, userQuery)
def makeQuantumGraph(self)
def _loadTaskClass(self, taskDef)
def makeQuantumGraphTaskNodes(self)
def fillDataIds(self, registry, originInfo, userQuery)
def __init__(self, taskFactory, registry, skipExisting=True, clobberExisting=False)
def __init__(self, pipeline, universe)
def fillQuanta(self, registry, originInfo, skipExisting=True)
def fillDatasetRefs(self, registry, originInfo, skipExisting=True, clobberExisting=False)