Coverage for python/lsst/pipe/base/butlerQuantumContext.py : 11%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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/>.
22"""Module defining a butler like object specialized to a specific quantum.
23"""
25__all__ = ("ButlerQuantumContext",)
27from .connections import InputQuantizedConnection, OutputQuantizedConnection, DeferredDatasetRef
28from .struct import Struct
29from lsst.daf.butler import DatasetRef, Butler, Quantum
31from typing import Any, Union, List, Sequence
34class ButlerQuantumContext:
35 """A Butler-like class specialized for a single quantum
37 A ButlerQuantumContext class wraps a standard butler interface and
38 specializes it to the context of a given quantum. What this means
39 in practice is that the only gets and puts that this class allows
40 are DatasetRefs that are contained in the quantum.
42 In the future this class will also be used to record provenance on
43 what was actually get and put. This is in contrast to what the
44 preflight expects to be get and put by looking at the graph before
45 execution.
47 Parameters
48 ----------
49 butler : `lsst.daf.butler.Butler`
50 Butler object from/to which datasets will be get/put
51 quantum : `lsst.daf.butler.core.Quantum`
52 Quantum object that describes the datasets which will be get/put by a
53 single execution of this node in the pipeline graph. All input
54 dataset references must be resolved (i.e. satisfy
55 ``DatasetRef.id is not None``) prior to constructing the
56 `ButlerQuantumContext`.
58 Notes
59 -----
60 Most quanta in any non-trivial graph will not start with resolved dataset
61 references, because they represent processing steps that can only run
62 after some other quanta have produced their inputs. At present, it is the
63 responsibility of ``lsst.ctrl.mpexec.SingleQuantumExecutor`` to resolve all
64 datasets prior to constructing `ButlerQuantumContext` and calling
65 `runQuantum`, and the fact that this precondition is satisfied by code in
66 a downstream package is considered a problem with the
67 ``pipe_base/ctrl_mpexec`` separation of concerns that will be addressed in
68 the future.
69 """
70 def __init__(self, butler: Butler, quantum: Quantum):
71 self.quantum = quantum
72 self.registry = butler.registry
73 self.allInputs = set()
74 self.allOutputs = set()
75 for refs in quantum.inputs.values():
76 for ref in refs:
77 self.allInputs.add((ref.datasetType, ref.dataId))
78 for refs in quantum.outputs.values():
79 for ref in refs:
80 self.allOutputs.add((ref.datasetType, ref.dataId))
81 self.__butler = butler
83 def _get(self, ref: DatasetRef) -> Any:
84 # Butler methods below will check for unresolved DatasetRefs and
85 # raise appropriately, so no need for us to do that here.
86 if isinstance(ref, DeferredDatasetRef):
87 self._checkMembership(ref.datasetRef, self.allInputs)
88 return self.__butler.getDirectDeferred(ref.datasetRef)
90 else:
91 self._checkMembership(ref, self.allInputs)
92 return self.__butler.getDirect(ref)
94 def _put(self, value: Any, ref: DatasetRef):
95 self._checkMembership(ref, self.allOutputs)
96 self.__butler.put(value, ref)
98 def get(self, dataset: Union[InputQuantizedConnection, List[DatasetRef], DatasetRef]) -> Any:
99 """Fetches data from the butler
101 Parameters
102 ----------
103 dataset
104 This argument may either be an `InputQuantizedConnection` which
105 describes all the inputs of a quantum, a list of
106 `~lsst.daf.butler.DatasetRef`, or a single
107 `~lsst.daf.butler.DatasetRef`. The function will get and return
108 the corresponding datasets from the butler.
110 Returns
111 -------
112 return : `object`
113 This function returns arbitrary objects fetched from the bulter.
114 The structure these objects are returned in depends on the type of
115 the input argument. If the input dataset argument is a
116 `InputQuantizedConnection`, then the return type will be a
117 dictionary with keys corresponding to the attributes of the
118 `InputQuantizedConnection` (which in turn are the attribute
119 identifiers of the connections). If the input argument is of type
120 `list` of `~lsst.daf.butler.DatasetRef` then the return type will
121 be a list of objects. If the input argument is a single
122 `~lsst.daf.butler.DatasetRef` then a single object will be
123 returned.
125 Raises
126 ------
127 ValueError
128 Raised if a `DatasetRef` is passed to get that is not defined in
129 the quantum object
130 """
131 if isinstance(dataset, InputQuantizedConnection):
132 retVal = {}
133 for name, ref in dataset:
134 if isinstance(ref, list):
135 val = [self._get(r) for r in ref]
136 else:
137 val = self._get(ref)
138 retVal[name] = val
139 return retVal
140 elif isinstance(dataset, list):
141 return [self._get(x) for x in dataset]
142 elif isinstance(dataset, DatasetRef) or isinstance(dataset, DeferredDatasetRef):
143 return self._get(dataset)
144 else:
145 raise TypeError("Dataset argument is not a type that can be used to get")
147 def put(self, values: Union[Struct, List[Any], Any],
148 dataset: Union[OutputQuantizedConnection, List[DatasetRef], DatasetRef]):
149 """Puts data into the butler
151 Parameters
152 ----------
153 values : `Struct` or `list` of `object` or `object`
154 The data that should be put with the butler. If the type of the
155 dataset is `OutputQuantizedConnection` then this argument should be
156 a `Struct` with corresponding attribute names. Each attribute
157 should then correspond to either a list of object or a single
158 object depending of the type of the corresponding attribute on
159 dataset. I.e. if ``dataset.calexp`` is
160 ``[datasetRef1, datasetRef2]`` then ``values.calexp`` should be
161 ``[calexp1, calexp2]``. Like wise if there is a single ref, then
162 only a single object need be passed. The same restriction applies
163 if dataset is directly a `list` of `DatasetRef` or a single
164 `DatasetRef`.
165 dataset
166 This argument may either be an `InputQuantizedConnection` which
167 describes all the inputs of a quantum, a list of
168 `lsst.daf.butler.DatasetRef`, or a single
169 `lsst.daf.butler.DatasetRef`. The function will get and return
170 the corresponding datasets from the butler.
172 Raises
173 ------
174 ValueError
175 Raised if a `DatasetRef` is passed to put that is not defined in
176 the quantum object, or the type of values does not match what is
177 expected from the type of dataset.
178 """
179 if isinstance(dataset, OutputQuantizedConnection):
180 if not isinstance(values, Struct):
181 raise ValueError("dataset is a OutputQuantizedConnection, a Struct with corresponding"
182 " attributes must be passed as the values to put")
183 for name, refs in dataset:
184 valuesAttribute = getattr(values, name)
185 if isinstance(refs, list):
186 if len(refs) != len(valuesAttribute):
187 raise ValueError(f"There must be a object to put for every Dataset ref in {name}")
188 for i, ref in enumerate(refs):
189 self._put(valuesAttribute[i], ref)
190 else:
191 self._put(valuesAttribute, refs)
192 elif isinstance(dataset, list):
193 if not isinstance(values, Sequence):
194 raise ValueError("Values to put must be a sequence")
195 if len(dataset) != len(values):
196 raise ValueError("There must be a common number of references and values to put")
197 for i, ref in enumerate(dataset):
198 self._put(values[i], ref)
199 elif isinstance(dataset, DatasetRef):
200 self._put(values, dataset)
201 else:
202 raise TypeError("Dataset argument is not a type that can be used to put")
204 def _checkMembership(self, ref: Union[List[DatasetRef], DatasetRef], inout: set):
205 """Internal function used to check if a DatasetRef is part of the input
206 quantum
208 This function will raise an exception if the ButlerQuantumContext is
209 used to get/put a DatasetRef which is not defined in the quantum.
211 Parameters
212 ----------
213 ref : `list` of `DatasetRef` or `DatasetRef`
214 Either a list or a single `DatasetRef` to check
215 inout : `set`
216 The connection type to check, e.g. either an input or an output.
217 This prevents both types needing to be checked for every operation,
218 which may be important for Quanta with lots of `DatasetRef`.
219 """
220 if not isinstance(ref, list):
221 ref = [ref]
222 for r in ref:
223 if (r.datasetType, r.dataId) not in inout:
224 raise ValueError("DatasetRef is not part of the Quantum being processed")