LSST Applications  22.0.1,22.0.1+01bcf6a671,22.0.1+046ee49490,22.0.1+05c7de27da,22.0.1+0c6914dbf6,22.0.1+1220d50b50,22.0.1+12fd109e95,22.0.1+1a1dd69893,22.0.1+1c910dc348,22.0.1+1ef34551f5,22.0.1+30170c3d08,22.0.1+39153823fd,22.0.1+611137eacc,22.0.1+771eb1e3e8,22.0.1+94e66cc9ed,22.0.1+9a075d06e2,22.0.1+a5ff6e246e,22.0.1+a7db719c1a,22.0.1+ba0d97e778,22.0.1+bfe1ee9056,22.0.1+c4e1e0358a,22.0.1+cc34b8281e,22.0.1+d640e2c0fa,22.0.1+d72a2e677a,22.0.1+d9a6b571bd,22.0.1+e485e9761b,22.0.1+ebe8d3385e
LSST Data Management Base Package
Public Member Functions | Public Attributes | List of all members
lsst.pipe.base.connections.PipelineTaskConnections Class Reference
Inheritance diagram for lsst.pipe.base.connections.PipelineTaskConnections:
lsst.pipe.base.connections.PipelineTaskConnectionsMetaclass lsst.meas.base.forcedPhotCcd.ForcedPhotCcdConnections lsst.pipe.tasks.deblendCoaddSourcesPipeline.DeblendCoaddSourceSingleConnections lsst.pipe.tasks.deblendCoaddSourcesPipeline.DeblendCoaddSourcesMultiConnections lsst.pipe.tasks.insertFakes.InsertFakesConnections lsst.pipe.tasks.mergeDetections.MergeDetectionsConnections lsst.pipe.tasks.mergeMeasurements.MergeMeasurementsConnections lsst.pipe.tasks.multiBand.DetectCoaddSourcesConnections lsst.pipe.tasks.processCcdWithFakes.ProcessCcdWithFakesConnections

Public Member Functions

def __init__ (self, *'PipelineTaskConfig' config=None)
 
typing.Tuple[InputQuantizedConnection, OutputQuantizedConnectionbuildDatasetRefs (self, Quantum quantum)
 
NamedKeyDict[DatasetType, typing.Set[DatasetRef]] adjustQuantum (self, NamedKeyDict[DatasetType, typing.Set[DatasetRef]] datasetRefMap)
 
def __prepare__ (name, bases, **kwargs)
 
def __new__ (cls, name, bases, dct, **kwargs)
 

Public Attributes

 inputs
 
 prerequisiteInputs
 
 outputs
 
 initInputs
 
 initOutputs
 
 allConnections
 
 config
 

Detailed Description

PipelineTaskConnections is a class used to declare desired IO when a
PipelineTask is run by an activator

Parameters
----------
config : `PipelineTaskConfig`
    A `PipelineTaskConfig` class instance whose class has been configured
    to use this `PipelineTaskConnectionsClass`

Notes
-----
``PipelineTaskConnection`` classes are created by declaring class
attributes of types defined in `lsst.pipe.base.connectionTypes` and are
listed as follows:

* ``InitInput`` - Defines connections in a quantum graph which are used as
  inputs to the ``__init__`` function of the `PipelineTask` corresponding
  to this class
* ``InitOuput`` - Defines connections in a quantum graph which are to be
  persisted using a butler at the end of the ``__init__`` function of the
  `PipelineTask` corresponding to this class. The variable name used to
  define this connection should be the same as an attribute name on the
  `PipelineTask` instance. E.g. if an ``InitOutput`` is declared with
  the name ``outputSchema`` in a ``PipelineTaskConnections`` class, then
  a `PipelineTask` instance should have an attribute
  ``self.outputSchema`` defined. Its value is what will be saved by the
  activator framework.
* ``PrerequisiteInput`` - An input connection type that defines a
  `lsst.daf.butler.DatasetType` that must be present at execution time,
  but that will not be used during the course of creating the quantum
  graph to be executed. These most often are things produced outside the
  processing pipeline, such as reference catalogs.
* ``Input`` - Input `lsst.daf.butler.DatasetType` objects that will be used
  in the ``run`` method of a `PipelineTask`.  The name used to declare
  class attribute must match a function argument name in the ``run``
  method of a `PipelineTask`. E.g. If the ``PipelineTaskConnections``
  defines an ``Input`` with the name ``calexp``, then the corresponding
  signature should be ``PipelineTask.run(calexp, ...)``
* ``Output`` - A `lsst.daf.butler.DatasetType` that will be produced by an
  execution of a `PipelineTask`. The name used to declare the connection
  must correspond to an attribute of a `Struct` that is returned by a
  `PipelineTask` ``run`` method.  E.g. if an output connection is
  defined with the name ``measCat``, then the corresponding
  ``PipelineTask.run`` method must return ``Struct(measCat=X,..)`` where
  X matches the ``storageClass`` type defined on the output connection.

The process of declaring a ``PipelineTaskConnection`` class involves
parameters passed in the declaration statement.

The first parameter is ``dimensions`` which is an iterable of strings which
defines the unit of processing the run method of a corresponding
`PipelineTask` will operate on. These dimensions must match dimensions that
exist in the butler registry which will be used in executing the
corresponding `PipelineTask`.

The second parameter is labeled ``defaultTemplates`` and is conditionally
optional. The name attributes of connections can be specified as python
format strings, with named format arguments. If any of the name parameters
on connections defined in a `PipelineTaskConnections` class contain a
template, then a default template value must be specified in the
``defaultTemplates`` argument. This is done by passing a dictionary with
keys corresponding to a template identifier, and values corresponding to
the value to use as a default when formatting the string. For example if
``ConnectionClass.calexp.name = '{input}Coadd_calexp'`` then
``defaultTemplates`` = {'input': 'deep'}.

Once a `PipelineTaskConnections` class is created, it is used in the
creation of a `PipelineTaskConfig`. This is further documented in the
documentation of `PipelineTaskConfig`. For the purposes of this
documentation, the relevant information is that the config class allows
configuration of connection names by users when running a pipeline.

Instances of a `PipelineTaskConnections` class are used by the pipeline
task execution framework to introspect what a corresponding `PipelineTask`
will require, and what it will produce.

Examples
--------
>>> from lsst.pipe.base import connectionTypes as cT
>>> from lsst.pipe.base import PipelineTaskConnections
>>> from lsst.pipe.base import PipelineTaskConfig
>>> class ExampleConnections(PipelineTaskConnections,
...                          dimensions=("A", "B"),
...                          defaultTemplates={"foo": "Example"}):
...     inputConnection = cT.Input(doc="Example input",
...                                dimensions=("A", "B"),
...                                storageClass=Exposure,
...                                name="{foo}Dataset")
...     outputConnection = cT.Output(doc="Example output",
...                                  dimensions=("A", "B"),
...                                  storageClass=Exposure,
...                                  name="{foo}output")
>>> class ExampleConfig(PipelineTaskConfig,
...                     pipelineConnections=ExampleConnections):
...    pass
>>> config = ExampleConfig()
>>> config.connections.foo = Modified
>>> config.connections.outputConnection = "TotallyDifferent"
>>> connections = ExampleConnections(config=config)
>>> assert(connections.inputConnection.name == "ModifiedDataset")
>>> assert(connections.outputConnection.name == "TotallyDifferent")

Definition at line 260 of file connections.py.

Constructor & Destructor Documentation

◆ __init__()

def lsst.pipe.base.connections.PipelineTaskConnections.__init__ (   self,
*'PipelineTaskConfig'   config = None 
)

Definition at line 364 of file connections.py.

364  def __init__(self, *, config: 'PipelineTaskConfig' = None):
365  self.inputs = set(self.inputs)
366  self.prerequisiteInputs = set(self.prerequisiteInputs)
367  self.outputs = set(self.outputs)
368  self.initInputs = set(self.initInputs)
369  self.initOutputs = set(self.initOutputs)
370  self.allConnections = dict(self.allConnections)
371 
372  if config is None or not isinstance(config, configMod.PipelineTaskConfig):
373  raise ValueError("PipelineTaskConnections must be instantiated with"
374  " a PipelineTaskConfig instance")
375  self.config = config
376  # Extract the template names that were defined in the config instance
377  # by looping over the keys of the defaultTemplates dict specified at
378  # class declaration time
379  templateValues = {name: getattr(config.connections, name) for name in getattr(self,
380  'defaultTemplates').keys()}
381  # Extract the configured value corresponding to each connection
382  # variable. I.e. for each connection identifier, populate a override
383  # for the connection.name attribute
384  self._nameOverrides = {name: getattr(config.connections, name).format(**templateValues)
385  for name in self.allConnections.keys()}
386 
387  # connections.name corresponds to a dataset type name, create a reverse
388  # mapping that goes from dataset type name to attribute identifier name
389  # (variable name) on the connection class
390  self._typeNameToVarName = {v: k for k, v in self._nameOverrides.items()}
391 
std::vector< SchemaItem< Flag > > * items
daf::base::PropertySet * set
Definition: fits.cc:912
def format(config, name=None, writeSourceLine=True, prefix="", verbose=False)
Definition: history.py:174

Member Function Documentation

◆ __new__()

def lsst.pipe.base.connections.PipelineTaskConnectionsMetaclass.__new__ (   cls,
  name,
  bases,
  dct,
**  kwargs 
)
inherited

Definition at line 110 of file connections.py.

110  def __new__(cls, name, bases, dct, **kwargs):
111  dimensionsValueError = TypeError("PipelineTaskConnections class must be created with a dimensions "
112  "attribute which is an iterable of dimension names")
113 
114  if name != 'PipelineTaskConnections':
115  # Verify that dimensions are passed as a keyword in class
116  # declaration
117  if 'dimensions' not in kwargs:
118  for base in bases:
119  if hasattr(base, 'dimensions'):
120  kwargs['dimensions'] = base.dimensions
121  break
122  if 'dimensions' not in kwargs:
123  raise dimensionsValueError
124  try:
125  if isinstance(kwargs['dimensions'], str):
126  raise TypeError("Dimensions must be iterable of dimensions, got str,"
127  "possibly omitted trailing comma")
128  if not isinstance(kwargs['dimensions'], typing.Iterable):
129  raise TypeError("Dimensions must be iterable of dimensions")
130  dct['dimensions'] = set(kwargs['dimensions'])
131  except TypeError as exc:
132  raise dimensionsValueError from exc
133  # Lookup any python string templates that may have been used in the
134  # declaration of the name field of a class connection attribute
135  allTemplates = set()
136  stringFormatter = string.Formatter()
137  # Loop over all connections
138  for obj in dct['allConnections'].values():
139  nameValue = obj.name
140  # add all the parameters to the set of templates
141  for param in stringFormatter.parse(nameValue):
142  if param[1] is not None:
143  allTemplates.add(param[1])
144 
145  # look up any template from base classes and merge them all
146  # together
147  mergeDict = {}
148  for base in bases[::-1]:
149  if hasattr(base, 'defaultTemplates'):
150  mergeDict.update(base.defaultTemplates)
151  if 'defaultTemplates' in kwargs:
152  mergeDict.update(kwargs['defaultTemplates'])
153 
154  if len(mergeDict) > 0:
155  kwargs['defaultTemplates'] = mergeDict
156 
157  # Verify that if templated strings were used, defaults were
158  # supplied as an argument in the declaration of the connection
159  # class
160  if len(allTemplates) > 0 and 'defaultTemplates' not in kwargs:
161  raise TypeError("PipelineTaskConnection class contains templated attribute names, but no "
162  "defaut templates were provided, add a dictionary attribute named "
163  "defaultTemplates which contains the mapping between template key and value")
164  if len(allTemplates) > 0:
165  # Verify all templates have a default, and throw if they do not
166  defaultTemplateKeys = set(kwargs['defaultTemplates'].keys())
167  templateDifference = allTemplates.difference(defaultTemplateKeys)
168  if templateDifference:
169  raise TypeError(f"Default template keys were not provided for {templateDifference}")
170  # Verify that templates do not share names with variable names
171  # used for a connection, this is needed because of how
172  # templates are specified in an associated config class.
173  nameTemplateIntersection = allTemplates.intersection(set(dct['allConnections'].keys()))
174  if len(nameTemplateIntersection) > 0:
175  raise TypeError(f"Template parameters cannot share names with Class attributes"
176  f" (conflicts are {nameTemplateIntersection}).")
177  dct['defaultTemplates'] = kwargs.get('defaultTemplates', {})
178 
179  # Convert all the connection containers into frozensets so they cannot
180  # be modified at the class scope
181  for connectionName in ("inputs", "prerequisiteInputs", "outputs", "initInputs", "initOutputs"):
182  dct[connectionName] = frozenset(dct[connectionName])
183  # our custom dict type must be turned into an actual dict to be used in
184  # type.__new__
185  return super().__new__(cls, name, bases, dict(dct))
186 

◆ __prepare__()

def lsst.pipe.base.connections.PipelineTaskConnectionsMetaclass.__prepare__ (   name,
  bases,
**  kwargs 
)
inherited

Definition at line 99 of file connections.py.

99  def __prepare__(name, bases, **kwargs): # noqa: 805
100  # Create an instance of our special dict to catch and track all
101  # variables that are instances of connectionTypes.BaseConnection
102  # Copy any existing connections from a parent class
103  dct = PipelineTaskConnectionDict()
104  for base in bases:
105  if isinstance(base, PipelineTaskConnectionsMetaclass):
106  for name, value in base.allConnections.items():
107  dct[name] = value
108  return dct
109 

◆ adjustQuantum()

NamedKeyDict[DatasetType, typing.Set[DatasetRef]] lsst.pipe.base.connections.PipelineTaskConnections.adjustQuantum (   self,
NamedKeyDict[DatasetType, typing.Set[DatasetRef]]   datasetRefMap 
)
Override to make adjustments to `lsst.daf.butler.DatasetRef` objects
in the `lsst.daf.butler.core.Quantum` during the graph generation stage
of the activator.

The base class implementation simply checks that input connections with
``multiple`` set to `False` have no more than one dataset.

Parameters
----------
datasetRefMap : `NamedKeyDict`
    Mapping from dataset type to a `set` of
    `lsst.daf.butler.DatasetRef` objects

Returns
-------
datasetRefMap : `NamedKeyDict`
    Modified mapping of input with possibly adjusted
    `lsst.daf.butler.DatasetRef` objects.

Raises
------
ScalarError
    Raised if any `Input` or `PrerequisiteInput` connection has
    ``multiple`` set to `False`, but multiple datasets.
Exception
    Overrides of this function have the option of raising an Exception
    if a field in the input does not satisfy a need for a corresponding
    pipelineTask, i.e. no reference catalogs are found.

Definition at line 459 of file connections.py.

460  ) -> NamedKeyDict[DatasetType, typing.Set[DatasetRef]]:
461  """Override to make adjustments to `lsst.daf.butler.DatasetRef` objects
462  in the `lsst.daf.butler.core.Quantum` during the graph generation stage
463  of the activator.
464 
465  The base class implementation simply checks that input connections with
466  ``multiple`` set to `False` have no more than one dataset.
467 
468  Parameters
469  ----------
470  datasetRefMap : `NamedKeyDict`
471  Mapping from dataset type to a `set` of
472  `lsst.daf.butler.DatasetRef` objects
473 
474  Returns
475  -------
476  datasetRefMap : `NamedKeyDict`
477  Modified mapping of input with possibly adjusted
478  `lsst.daf.butler.DatasetRef` objects.
479 
480  Raises
481  ------
482  ScalarError
483  Raised if any `Input` or `PrerequisiteInput` connection has
484  ``multiple`` set to `False`, but multiple datasets.
485  Exception
486  Overrides of this function have the option of raising an Exception
487  if a field in the input does not satisfy a need for a corresponding
488  pipelineTask, i.e. no reference catalogs are found.
489  """
490  for connection in itertools.chain(iterConnections(self, "inputs"),
491  iterConnections(self, "prerequisiteInputs")):
492  refs = datasetRefMap[connection.name]
493  if not connection.multiple and len(refs) > 1:
494  raise ScalarError(
495  f"Found multiple datasets {', '.join(str(r.dataId) for r in refs)} "
496  f"for scalar connection {connection.name} ({refs[0].datasetType.name})."
497  )
498  return datasetRefMap
499 
500 
typing.Generator[BaseConnection, None, None] iterConnections(PipelineTaskConnections connections, Union[str, Iterable[str]] connectionType)
Definition: connections.py:503

◆ buildDatasetRefs()

typing.Tuple[InputQuantizedConnection, OutputQuantizedConnection] lsst.pipe.base.connections.PipelineTaskConnections.buildDatasetRefs (   self,
Quantum  quantum 
)
Builds QuantizedConnections corresponding to input Quantum

Parameters
----------
quantum : `lsst.daf.butler.Quantum`
    Quantum object which defines the inputs and outputs for a given
    unit of processing

Returns
-------
retVal : `tuple` of (`InputQuantizedConnection`,
    `OutputQuantizedConnection`) Namespaces mapping attribute names
    (identifiers of connections) to butler references defined in the
    input `lsst.daf.butler.Quantum`

Definition at line 392 of file connections.py.

393  OutputQuantizedConnection]:
394  """Builds QuantizedConnections corresponding to input Quantum
395 
396  Parameters
397  ----------
398  quantum : `lsst.daf.butler.Quantum`
399  Quantum object which defines the inputs and outputs for a given
400  unit of processing
401 
402  Returns
403  -------
404  retVal : `tuple` of (`InputQuantizedConnection`,
405  `OutputQuantizedConnection`) Namespaces mapping attribute names
406  (identifiers of connections) to butler references defined in the
407  input `lsst.daf.butler.Quantum`
408  """
409  inputDatasetRefs = InputQuantizedConnection()
410  outputDatasetRefs = OutputQuantizedConnection()
411  # operate on a reference object and an interable of names of class
412  # connection attributes
413  for refs, names in zip((inputDatasetRefs, outputDatasetRefs),
414  (itertools.chain(self.inputs, self.prerequisiteInputs), self.outputs)):
415  # get a name of a class connection attribute
416  for attributeName in names:
417  # get the attribute identified by name
418  attribute = getattr(self, attributeName)
419  # Branch if the attribute dataset type is an input
420  if attribute.name in quantum.inputs:
421  # Get the DatasetRefs
422  quantumInputRefs = quantum.inputs[attribute.name]
423  # if the dataset is marked to load deferred, wrap it in a
424  # DeferredDatasetRef
425  if attribute.deferLoad:
426  quantumInputRefs = [DeferredDatasetRef(datasetRef=ref) for ref in quantumInputRefs]
427  # Unpack arguments that are not marked multiples (list of
428  # length one)
429  if not attribute.multiple:
430  if len(quantumInputRefs) > 1:
431  raise ScalarError(
432  f"Received multiple datasets "
433  f"{', '.join(str(r.dataId) for r in quantumInputRefs)} "
434  f"for scalar connection {attributeName} "
435  f"({quantumInputRefs[0].datasetType.name}) "
436  f"of quantum for {quantum.taskName} with data ID {quantum.dataId}."
437  )
438  if len(quantumInputRefs) == 0:
439  continue
440  quantumInputRefs = quantumInputRefs[0]
441  # Add to the QuantizedConnection identifier
442  setattr(refs, attributeName, quantumInputRefs)
443  # Branch if the attribute dataset type is an output
444  elif attribute.name in quantum.outputs:
445  value = quantum.outputs[attribute.name]
446  # Unpack arguments that are not marked multiples (list of
447  # length one)
448  if not attribute.multiple:
449  value = value[0]
450  # Add to the QuantizedConnection identifier
451  setattr(refs, attributeName, value)
452  # Specified attribute is not in inputs or outputs dont know how
453  # to handle, throw
454  else:
455  raise ValueError(f"Attribute with name {attributeName} has no counterpoint "
456  "in input quantum")
457  return inputDatasetRefs, outputDatasetRefs
458 

Member Data Documentation

◆ allConnections

lsst.pipe.base.connections.PipelineTaskConnections.allConnections

Definition at line 370 of file connections.py.

◆ config

lsst.pipe.base.connections.PipelineTaskConnections.config

Definition at line 375 of file connections.py.

◆ initInputs

lsst.pipe.base.connections.PipelineTaskConnections.initInputs

Definition at line 368 of file connections.py.

◆ initOutputs

lsst.pipe.base.connections.PipelineTaskConnections.initOutputs

Definition at line 369 of file connections.py.

◆ inputs

lsst.pipe.base.connections.PipelineTaskConnections.inputs

Definition at line 365 of file connections.py.

◆ outputs

lsst.pipe.base.connections.PipelineTaskConnections.outputs

Definition at line 367 of file connections.py.

◆ prerequisiteInputs

lsst.pipe.base.connections.PipelineTaskConnections.prerequisiteInputs

Definition at line 366 of file connections.py.


The documentation for this class was generated from the following file: