lsst.pipe.base  20.0.0-19-gcdd82e7+6f5ab6e0f6
butlerQuantumContext.py
Go to the documentation of this file.
1 # This file is part of pipe_base.
2 #
3 # Developed for the LSST Data Management System.
4 # This product includes software developed by the LSST Project
5 # (http://www.lsst.org).
6 # See the COPYRIGHT file at the top-level directory of this distribution
7 # for details of code ownership.
8 #
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 
22 """Module defining a butler like object specialized to a specific quantum.
23 """
24 
25 __all__ = ("ButlerQuantumContext",)
26 
27 import types
28 import typing
29 
30 from .connections import InputQuantizedConnection, OutputQuantizedConnection, DeferredDatasetRef
31 from .struct import Struct
32 from lsst.daf.butler import DatasetRef, Butler, Quantum
33 
34 
36  """A Butler-like class specialized for a single quantum
37 
38  A ButlerQuantumContext class wraps a standard butler interface and
39  specializes it to the context of a given quantum. What this means
40  in practice is that the only gets and puts that this class allows
41  are DatasetRefs that are contained in the quantum.
42 
43  In the future this class will also be used to record provenance on
44  what was actually get and put. This is in contrast to what the
45  preflight expects to be get and put by looking at the graph before
46  execution.
47 
48  Parameters
49  ----------
50  butler : `lsst.daf.butler.Butler`
51  Butler object from/to which datasets will be get/put
52  quantum : `lsst.daf.butler.core.Quantum`
53  Quantum object that describes the datasets which will be get/put by a
54  single execution of this node in the pipeline graph. All input
55  dataset references must be resolved (i.e. satisfy
56  ``DatasetRef.id is not None``) prior to constructing the
57  `ButlerQuantumContext`.
58 
59  Notes
60  -----
61  Most quanta in any non-trivial graph will not start with resolved dataset
62  references, because they represent processing steps that can only run
63  after some other quanta have produced their inputs. At present, it is the
64  responsibility of ``lsst.ctrl.mpexec.SingleQuantumExecutor`` to resolve all
65  datasets prior to constructing `ButlerQuantumContext` and calling
66  `runQuantum`, and the fact that this precondition is satisfied by code in
67  a downstream package is considered a problem with the
68  ``pipe_base/ctrl_mpexec`` separation of concerns that will be addressed in
69  the future.
70  """
71  def __init__(self, butler: Butler, quantum: Quantum):
72  self.quantum = quantum
73  self.registry = butler.registry
74  self.allInputs = set()
75  self.allOutputs = set()
76  for refs in quantum.inputs.values():
77  for ref in refs:
78  self.allInputs.add((ref.datasetType, ref.dataId))
79  for refs in quantum.outputs.values():
80  for ref in refs:
81  self.allOutputs.add((ref.datasetType, ref.dataId))
82 
83  # Create closures over butler to discourage anyone from directly
84  # using a butler reference
85  def _get(self, ref):
86  # Butler methods below will check for unresolved DatasetRefs and
87  # raise appropriately, so no need for us to do that here.
88  if isinstance(ref, DeferredDatasetRef):
89  self._checkMembership(ref.datasetRef, self.allInputs)
90  return butler.getDirectDeferred(ref.datasetRef)
91 
92  else:
93  self._checkMembership(ref, self.allInputs)
94  return butler.getDirect(ref)
95 
96  def _put(self, value, ref):
97  self._checkMembership(ref, self.allOutputs)
98  butler.put(value, ref)
99 
100  self._get = types.MethodType(_get, self)
101  self._put = types.MethodType(_put, self)
102 
103  def get(self, dataset: typing.Union[InputQuantizedConnection,
104  typing.List[DatasetRef],
105  DatasetRef]) -> object:
106  """Fetches data from the butler
107 
108  Parameters
109  ----------
110  dataset
111  This argument may either be an `InputQuantizedConnection` which describes
112  all the inputs of a quantum, a list of `~lsst.daf.butler.DatasetRef`, or
113  a single `~lsst.daf.butler.DatasetRef`. The function will get and return
114  the corresponding datasets from the butler.
115 
116  Returns
117  -------
118  return : `object`
119  This function returns arbitrary objects fetched from the bulter. The
120  structure these objects are returned in depends on the type of the input
121  argument. If the input dataset argument is a InputQuantizedConnection, then
122  the return type will be a dictionary with keys corresponding to the attributes
123  of the `InputQuantizedConnection` (which in turn are the attribute identifiers
124  of the connections). If the input argument is of type `list` of
125  `~lsst.daf.butler.DatasetRef` then the return type will be a list of objects.
126  If the input argument is a single `~lsst.daf.butler.DatasetRef` then a single
127  object will be returned.
128 
129  Raises
130  ------
131  ValueError
132  If a `DatasetRef` is passed to get that is not defined in the quantum object
133  """
134  if isinstance(dataset, InputQuantizedConnection):
135  retVal = {}
136  for name, ref in dataset:
137  if isinstance(ref, list):
138  val = [self._get(r) for r in ref]
139  else:
140  val = self._get(ref)
141  retVal[name] = val
142  return retVal
143  elif isinstance(dataset, list):
144  return [self._get(x) for x in dataset]
145  elif isinstance(dataset, DatasetRef) or isinstance(dataset, DeferredDatasetRef):
146  return self._get(dataset)
147  else:
148  raise TypeError("Dataset argument is not a type that can be used to get")
149 
150  def put(self, values: typing.Union[Struct, typing.List[typing.Any], object],
151  dataset: typing.Union[OutputQuantizedConnection, typing.List[DatasetRef], DatasetRef]):
152  """Puts data into the butler
153 
154  Parameters
155  ----------
156  values : `Struct` or `list` of `object` or `object`
157  The data that should be put with the butler. If the type of the dataset
158  is `OutputQuantizedConnection` then this argument should be a `Struct`
159  with corresponding attribute names. Each attribute should then correspond
160  to either a list of object or a single object depending of the type of the
161  corresponding attribute on dataset. I.e. if dataset.calexp is [datasetRef1,
162  datasetRef2] then values.calexp should be [calexp1, calexp2]. Like wise
163  if there is a single ref, then only a single object need be passed. The same
164  restriction applies if dataset is directly a `list` of `DatasetRef` or a
165  single `DatasetRef`.
166  dataset
167  This argument may either be an `InputQuantizedConnection` which describes
168  all the inputs of a quantum, a list of `lsst.daf.butler.DatasetRef`, or
169  a single `lsst.daf.butler.DatasetRef`. The function will get and return
170  the corresponding datasets from the butler.
171 
172  Raises
173  ------
174  ValueError
175  If a `DatasetRef` is passed to put that is not defined in the quantum object, or
176  the type of values does not match what is expected from the type of dataset.
177  """
178  if isinstance(dataset, OutputQuantizedConnection):
179  if not isinstance(values, Struct):
180  raise ValueError("dataset is a OutputQuantizedConnection, a Struct with corresponding"
181  " attributes must be passed as the values to put")
182  for name, refs in dataset:
183  valuesAttribute = getattr(values, name)
184  if isinstance(refs, list):
185  if len(refs) != len(valuesAttribute):
186  raise ValueError(f"There must be a object to put for every Dataset ref in {name}")
187  for i, ref in enumerate(refs):
188  self._put(valuesAttribute[i], ref)
189  else:
190  self._put(valuesAttribute, refs)
191  elif isinstance(dataset, list):
192  if len(dataset) != len(values):
193  raise ValueError("There must be a common number of references and values to put")
194  for i, ref in enumerate(dataset):
195  self._put(values[i], ref)
196  elif isinstance(dataset, DatasetRef):
197  self._put(values, dataset)
198  else:
199  raise TypeError("Dataset argument is not a type that can be used to put")
200 
201  def _checkMembership(self, ref: typing.Union[typing.List[DatasetRef], DatasetRef], inout: set):
202  """Internal function used to check if a DatasetRef is part of the input quantum
203 
204  This function will raise an exception if the ButlerQuantumContext is used to
205  get/put a DatasetRef which is not defined in the quantum.
206 
207  Parameters
208  ----------
209  ref : `list` of `DatasetRef` or `DatasetRef`
210  Either a list or a single `DatasetRef` to check
211  inout : `set`
212  The connection type to check, e.g. either an input or an output. This prevents
213  both types needing to be checked for every operation, which may be important
214  for Quanta with lots of `DatasetRef`s.
215  """
216  if not isinstance(ref, list):
217  ref = [ref]
218  for r in ref:
219  if (r.datasetType, r.dataId) not in inout:
220  raise ValueError("DatasetRef is not part of the Quantum being processed")
lsst::pipe::base.butlerQuantumContext.ButlerQuantumContext.registry
registry
Definition: butlerQuantumContext.py:73
lsst::pipe::base.butlerQuantumContext.ButlerQuantumContext
Definition: butlerQuantumContext.py:35
lsst::pipe::base.butlerQuantumContext.ButlerQuantumContext.__init__
def __init__(self, Butler butler, Quantum quantum)
Definition: butlerQuantumContext.py:71
lsst::pipe::base.butlerQuantumContext.ButlerQuantumContext._put
_put
Definition: butlerQuantumContext.py:101
lsst::pipe::base.butlerQuantumContext.ButlerQuantumContext.allInputs
allInputs
Definition: butlerQuantumContext.py:74
lsst::pipe::base.butlerQuantumContext.ButlerQuantumContext.put
def put(self, typing.Union[Struct, typing.List[typing.Any], object] values, typing.Union[OutputQuantizedConnection, typing.List[DatasetRef], DatasetRef] dataset)
Definition: butlerQuantumContext.py:150
lsst::pipe::base.butlerQuantumContext.ButlerQuantumContext._checkMembership
def _checkMembership(self, typing.Union[typing.List[DatasetRef], DatasetRef] ref, set inout)
Definition: butlerQuantumContext.py:201
lsst::pipe::base.butlerQuantumContext.ButlerQuantumContext.get
object get(self, typing.Union[InputQuantizedConnection, typing.List[DatasetRef], DatasetRef] dataset)
Definition: butlerQuantumContext.py:103
lsst::pipe::base.butlerQuantumContext.ButlerQuantumContext._get
_get
Definition: butlerQuantumContext.py:100
lsst::pipe::base.butlerQuantumContext.ButlerQuantumContext.quantum
quantum
Definition: butlerQuantumContext.py:72
lsst::pipe::base.butlerQuantumContext.ButlerQuantumContext.allOutputs
allOutputs
Definition: butlerQuantumContext.py:75