Coverage for python/lsst/pipe/base/butlerQuantumContext.py: 14%
106 statements
« prev ^ index » next coverage.py v7.2.5, created at 2023-05-06 02:42 -0700
« prev ^ index » next coverage.py v7.2.5, created at 2023-05-06 02:42 -0700
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/>.
22from __future__ import annotations
24"""Module defining a butler like object specialized to a specific quantum.
25"""
27__all__ = ("ButlerQuantumContext",)
29from typing import Any, List, Optional, Sequence, Union
31from lsst.daf.butler import Butler, DatasetRef, DimensionUniverse, LimitedButler, Quantum
32from lsst.utils.introspection import get_full_type_name
33from lsst.utils.logging import PeriodicLogger, getLogger
35from .connections import DeferredDatasetRef, InputQuantizedConnection, OutputQuantizedConnection
36from .struct import Struct
38_LOG = getLogger(__name__)
41class ButlerQuantumContext:
42 """A Butler-like class specialized for a single quantum.
44 A ButlerQuantumContext class wraps a standard butler interface and
45 specializes it to the context of a given quantum. What this means
46 in practice is that the only gets and puts that this class allows
47 are DatasetRefs that are contained in the quantum.
49 In the future this class will also be used to record provenance on
50 what was actually get and put. This is in contrast to what the
51 preflight expects to be get and put by looking at the graph before
52 execution.
54 Do not use constructor directly, instead use `from_full` or `from_limited`
55 factory methods.
57 Notes
58 -----
59 `ButlerQuantumContext` instances are backed by either
60 `lsst.daf.butler.Butler` or `lsst.daf.butler.LimitedButler`. When a
61 limited butler is used then quantum has to contain dataset references
62 that are completely resolved (usually when graph is constructed by
63 GraphBuilder).
65 When instances are backed by full butler, the quantum graph does not have
66 to resolve output or intermediate references, but input references of each
67 quantum have to be resolved before they can be used by this class. When
68 executing such graphs, intermediate references used as input to some
69 Quantum are resolved by ``lsst.ctrl.mpexec.SingleQuantumExecutor``. If
70 output references of a quanta are resolved, they will be unresolved when
71 full butler is used.
72 """
74 def __init__(self, *, limited: LimitedButler, quantum: Quantum, butler: Butler | None = None):
75 self.quantum = quantum
76 self.allInputs = set()
77 self.allOutputs = set()
78 for refs in quantum.inputs.values():
79 for ref in refs:
80 self.allInputs.add((ref.datasetType, ref.dataId))
81 for refs in quantum.outputs.values():
82 for ref in refs:
83 self.allOutputs.add((ref.datasetType, ref.dataId))
84 self.__full_butler = butler
85 self.__butler = limited
87 @classmethod
88 def from_full(cls, butler: Butler, quantum: Quantum) -> ButlerQuantumContext:
89 """Make ButlerQuantumContext backed by `lsst.daf.butler.Butler`.
91 Parameters
92 ----------
93 butler : `lsst.daf.butler.Butler`
94 Butler object from/to which datasets will be get/put.
95 quantum : `lsst.daf.butler.core.Quantum`
96 Quantum object that describes the datasets which will be get/put by
97 a single execution of this node in the pipeline graph. All input
98 dataset references must be resolved in this Quantum. Output
99 references can be resolved, but they will be unresolved.
101 Returns
102 -------
103 butlerQC : `ButlerQuantumContext`
104 Instance of butler wrapper.
105 """
106 return ButlerQuantumContext(limited=butler, butler=butler, quantum=quantum)
108 @classmethod
109 def from_limited(cls, butler: LimitedButler, quantum: Quantum) -> ButlerQuantumContext:
110 """Make ButlerQuantumContext backed by `lsst.daf.butler.LimitedButler`.
112 Parameters
113 ----------
114 butler : `lsst.daf.butler.LimitedButler`
115 Butler object from/to which datasets will be get/put.
116 quantum : `lsst.daf.butler.core.Quantum`
117 Quantum object that describes the datasets which will be get/put by
118 a single execution of this node in the pipeline graph. Both input
119 and output dataset references must be resolved in this Quantum.
121 Returns
122 -------
123 butlerQC : `ButlerQuantumContext`
124 Instance of butler wrapper.
125 """
126 return ButlerQuantumContext(limited=butler, quantum=quantum)
128 def _get(self, ref: Optional[Union[DeferredDatasetRef, DatasetRef]]) -> Any:
129 # Butler methods below will check for unresolved DatasetRefs and
130 # raise appropriately, so no need for us to do that here.
131 if isinstance(ref, DeferredDatasetRef):
132 self._checkMembership(ref.datasetRef, self.allInputs)
133 return self.__butler.getDeferred(ref.datasetRef)
134 elif ref is None:
135 return None
136 else:
137 self._checkMembership(ref, self.allInputs)
138 return self.__butler.get(ref)
140 def _put(self, value: Any, ref: DatasetRef) -> None:
141 """Store data in butler"""
142 self._checkMembership(ref, self.allOutputs)
143 if self.__full_butler is not None:
144 self.__full_butler.put(value, ref)
145 else:
146 self.__butler.put(value, ref)
148 def get(
149 self,
150 dataset: Union[
151 InputQuantizedConnection,
152 List[Optional[DatasetRef]],
153 List[Optional[DeferredDatasetRef]],
154 DatasetRef,
155 DeferredDatasetRef,
156 None,
157 ],
158 ) -> Any:
159 """Fetches data from the butler
161 Parameters
162 ----------
163 dataset
164 This argument may either be an `InputQuantizedConnection` which
165 describes all the inputs of a quantum, a list of
166 `~lsst.daf.butler.DatasetRef`, or a single
167 `~lsst.daf.butler.DatasetRef`. The function will get and return
168 the corresponding datasets from the butler. If `None` is passed in
169 place of a `~lsst.daf.butler.DatasetRef` then the corresponding
170 returned object will be `None`.
172 Returns
173 -------
174 return : `object`
175 This function returns arbitrary objects fetched from the bulter.
176 The structure these objects are returned in depends on the type of
177 the input argument. If the input dataset argument is a
178 `InputQuantizedConnection`, then the return type will be a
179 dictionary with keys corresponding to the attributes of the
180 `InputQuantizedConnection` (which in turn are the attribute
181 identifiers of the connections). If the input argument is of type
182 `list` of `~lsst.daf.butler.DatasetRef` then the return type will
183 be a list of objects. If the input argument is a single
184 `~lsst.daf.butler.DatasetRef` then a single object will be
185 returned.
187 Raises
188 ------
189 ValueError
190 Raised if a `DatasetRef` is passed to get that is not defined in
191 the quantum object
192 """
193 # Set up a periodic logger so log messages can be issued if things
194 # are taking too long.
195 periodic = PeriodicLogger(_LOG)
197 if isinstance(dataset, InputQuantizedConnection):
198 retVal = {}
199 n_connections = len(dataset)
200 n_retrieved = 0
201 for i, (name, ref) in enumerate(dataset):
202 if isinstance(ref, list):
203 val = []
204 n_refs = len(ref)
205 for j, r in enumerate(ref):
206 val.append(self._get(r))
207 n_retrieved += 1
208 periodic.log(
209 "Retrieved %d out of %d datasets for connection '%s' (%d out of %d)",
210 j + 1,
211 n_refs,
212 name,
213 i + 1,
214 n_connections,
215 )
216 else:
217 val = self._get(ref)
218 periodic.log(
219 "Retrieved dataset for connection '%s' (%d out of %d)",
220 name,
221 i + 1,
222 n_connections,
223 )
224 n_retrieved += 1
225 retVal[name] = val
226 if periodic.num_issued > 0:
227 # This took long enough that we issued some periodic log
228 # messages, so issue a final confirmation message as well.
229 _LOG.verbose(
230 "Completed retrieval of %d datasets from %d connections", n_retrieved, n_connections
231 )
232 return retVal
233 elif isinstance(dataset, list):
234 n_datasets = len(dataset)
235 retrieved = []
236 for i, x in enumerate(dataset):
237 # Mypy is not sure of the type of x because of the union
238 # of lists so complains. Ignoring it is more efficient
239 # than adding an isinstance assert.
240 retrieved.append(self._get(x))
241 periodic.log("Retrieved %d out of %d datasets", i + 1, n_datasets)
242 if periodic.num_issued > 0:
243 _LOG.verbose("Completed retrieval of %d datasets", n_datasets)
244 return retrieved
245 elif isinstance(dataset, DatasetRef) or isinstance(dataset, DeferredDatasetRef) or dataset is None:
246 return self._get(dataset)
247 else:
248 raise TypeError(
249 f"Dataset argument ({get_full_type_name(dataset)}) is not a type that can be used to get"
250 )
252 def put(
253 self,
254 values: Union[Struct, List[Any], Any],
255 dataset: Union[OutputQuantizedConnection, List[DatasetRef], DatasetRef],
256 ) -> None:
257 """Puts data into the butler
259 Parameters
260 ----------
261 values : `Struct` or `list` of `object` or `object`
262 The data that should be put with the butler. If the type of the
263 dataset is `OutputQuantizedConnection` then this argument should be
264 a `Struct` with corresponding attribute names. Each attribute
265 should then correspond to either a list of object or a single
266 object depending of the type of the corresponding attribute on
267 dataset. I.e. if ``dataset.calexp`` is
268 ``[datasetRef1, datasetRef2]`` then ``values.calexp`` should be
269 ``[calexp1, calexp2]``. Like wise if there is a single ref, then
270 only a single object need be passed. The same restriction applies
271 if dataset is directly a `list` of `DatasetRef` or a single
272 `DatasetRef`.
273 dataset
274 This argument may either be an `InputQuantizedConnection` which
275 describes all the inputs of a quantum, a list of
276 `lsst.daf.butler.DatasetRef`, or a single
277 `lsst.daf.butler.DatasetRef`. The function will get and return
278 the corresponding datasets from the butler.
280 Raises
281 ------
282 ValueError
283 Raised if a `DatasetRef` is passed to put that is not defined in
284 the quantum object, or the type of values does not match what is
285 expected from the type of dataset.
286 """
287 if isinstance(dataset, OutputQuantizedConnection):
288 if not isinstance(values, Struct):
289 raise ValueError(
290 "dataset is a OutputQuantizedConnection, a Struct with corresponding"
291 " attributes must be passed as the values to put"
292 )
293 for name, refs in dataset:
294 valuesAttribute = getattr(values, name)
295 if isinstance(refs, list):
296 if len(refs) != len(valuesAttribute):
297 raise ValueError(f"There must be a object to put for every Dataset ref in {name}")
298 for i, ref in enumerate(refs):
299 self._put(valuesAttribute[i], ref)
300 else:
301 self._put(valuesAttribute, refs)
302 elif isinstance(dataset, list):
303 if not isinstance(values, Sequence):
304 raise ValueError("Values to put must be a sequence")
305 if len(dataset) != len(values):
306 raise ValueError("There must be a common number of references and values to put")
307 for i, ref in enumerate(dataset):
308 self._put(values[i], ref)
309 elif isinstance(dataset, DatasetRef):
310 self._put(values, dataset)
311 else:
312 raise TypeError("Dataset argument is not a type that can be used to put")
314 def _checkMembership(self, ref: Union[List[DatasetRef], DatasetRef], inout: set) -> None:
315 """Internal function used to check if a DatasetRef is part of the input
316 quantum
318 This function will raise an exception if the ButlerQuantumContext is
319 used to get/put a DatasetRef which is not defined in the quantum.
321 Parameters
322 ----------
323 ref : `list` of `DatasetRef` or `DatasetRef`
324 Either a list or a single `DatasetRef` to check
325 inout : `set`
326 The connection type to check, e.g. either an input or an output.
327 This prevents both types needing to be checked for every operation,
328 which may be important for Quanta with lots of `DatasetRef`.
329 """
330 if not isinstance(ref, list):
331 ref = [ref]
332 for r in ref:
333 if (r.datasetType, r.dataId) not in inout:
334 raise ValueError("DatasetRef is not part of the Quantum being processed")
336 @property
337 def dimensions(self) -> DimensionUniverse:
338 """Structure managing all dimensions recognized by this data
339 repository (`DimensionUniverse`).
340 """
341 return self.__butler.dimensions