Coverage for python / lsst / daf / butler / direct_butler / _direct_butler.py: 10%
928 statements
« prev ^ index » next coverage.py v7.12.0, created at 2025-12-17 16:22 -0800
« prev ^ index » next coverage.py v7.12.0, created at 2025-12-17 16:22 -0800
1# This file is part of daf_butler.
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 software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
28"""Butler top level classes."""
30from __future__ import annotations
32__all__ = (
33 "ButlerValidationError",
34 "DirectButler",
35)
37import collections.abc
38import contextlib
39import io
40import itertools
41import math
42import numbers
43import os
44import uuid
45import warnings
46from collections import Counter, defaultdict
47from collections.abc import Collection, Iterable, Iterator, MutableMapping, Sequence
48from functools import partial
49from types import EllipsisType
50from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, TextIO, cast
52from deprecated.sphinx import deprecated
53from sqlalchemy.exc import IntegrityError
55from lsst.resources import ResourcePath, ResourcePathExpression
56from lsst.utils.introspection import find_outside_stacklevel, get_class_of
57from lsst.utils.iteration import chunk_iterable
58from lsst.utils.logging import VERBOSE, getLogger
59from lsst.utils.timer import time_this
61from .._butler import Butler, _DeprecatedDefault
62from .._butler_config import ButlerConfig
63from .._butler_instance_options import ButlerInstanceOptions
64from .._butler_metrics import ButlerMetrics
65from .._collection_type import CollectionType
66from .._dataset_existence import DatasetExistence
67from .._dataset_ref import DatasetRef
68from .._dataset_type import DatasetType
69from .._deferredDatasetHandle import DeferredDatasetHandle
70from .._exceptions import DatasetNotFoundError, DimensionValueError, EmptyQueryResultError, ValidationError
71from .._file_dataset import FileDataset
72from .._limited_butler import LimitedButler
73from .._query_all_datasets import QueryAllDatasetsParameters, query_all_datasets
74from .._registry_shim import RegistryShim
75from .._storage_class import StorageClass, StorageClassFactory
76from .._timespan import Timespan
77from ..datastore import Datastore, NullDatastore
78from ..datastores.file_datastore.retrieve_artifacts import ZipIndex, retrieve_and_zip
79from ..datastores.file_datastore.transfer import retrieve_file_transfer_records
80from ..dimensions import DataCoordinate, Dimension, DimensionGroup
81from ..direct_query_driver import DirectQueryDriver
82from ..progress import Progress
83from ..queries import Query
84from ..registry import (
85 ConflictingDefinitionError,
86 DataIdError,
87 MissingDatasetTypeError,
88 RegistryDefaults,
89 _RegistryFactory,
90)
91from ..registry.sql_registry import SqlRegistry
92from ..transfers import RepoExportContext
93from ..utils import transactional
94from ._direct_butler_collections import DirectButlerCollections
96if TYPE_CHECKING:
97 from lsst.resources import ResourceHandleProtocol
99 from .._dataset_provenance import DatasetProvenance
100 from .._dataset_ref import DatasetId
101 from ..datastore import DatasetRefURIs
102 from ..dimensions import DataId, DataIdValue, DimensionElement, DimensionRecord, DimensionUniverse
103 from ..registry import CollectionArgType, Registry
104 from ..transfers import RepoImportBackend
106_LOG = getLogger(__name__)
109class ButlerValidationError(ValidationError):
110 """There is a problem with the Butler configuration."""
112 pass
115class DirectButler(Butler): # numpydoc ignore=PR02
116 """Main entry point for the data access system.
118 Parameters
119 ----------
120 config : `ButlerConfig`
121 The configuration for this Butler instance.
122 registry : `SqlRegistry`
123 The object that manages dataset metadata and relationships.
124 datastore : Datastore
125 The object that manages actual dataset storage.
126 storageClasses : StorageClassFactory
127 An object that maps known storage class names to objects that fully
128 describe them.
130 Notes
131 -----
132 Most users should call the top-level `Butler`.``from_config`` instead of
133 using this constructor directly.
134 """
136 # This is __new__ instead of __init__ because we have to support
137 # instantiation via the legacy constructor Butler.__new__(), which
138 # reads the configuration and selects which subclass to instantiate. The
139 # interaction between __new__ and __init__ is kind of wacky in Python. If
140 # we were using __init__ here, __init__ would be called twice (once when
141 # the DirectButler instance is constructed inside Butler.from_config(), and
142 # a second time with the original arguments to Butler() when the instance
143 # is returned from Butler.__new__()
144 def __new__(
145 cls,
146 *,
147 config: ButlerConfig,
148 registry: SqlRegistry,
149 datastore: Datastore,
150 storageClasses: StorageClassFactory,
151 metrics: ButlerMetrics | None = None,
152 ) -> DirectButler:
153 self = cast(DirectButler, super().__new__(cls))
154 self._config = config
155 self._registry = registry
156 self._datastore = datastore
157 self.storageClasses = storageClasses
158 self._metrics = metrics if metrics is not None else ButlerMetrics()
160 # For execution butler the datastore needs a special
161 # dependency-inversion trick. This is not used by regular butler,
162 # but we do not have a way to distinguish regular butler from execution
163 # butler.
164 self._datastore.set_retrieve_dataset_type_method(partial(_retrieve_dataset_type, registry))
166 self._closed = False
168 return self
170 @classmethod
171 def create_from_config(
172 cls,
173 config: ButlerConfig,
174 *,
175 options: ButlerInstanceOptions,
176 without_datastore: bool = False,
177 ) -> DirectButler:
178 """Construct a Butler instance from a configuration file.
180 Parameters
181 ----------
182 config : `ButlerConfig`
183 The configuration for this Butler instance.
184 options : `ButlerInstanceOptions`
185 Default values and other settings for the Butler instance.
186 without_datastore : `bool`, optional
187 If `True` do not attach a datastore to this butler. Any attempts
188 to use a datastore will fail.
190 Notes
191 -----
192 Most users should call the top-level `Butler`.``from_config``
193 instead of using this function directly.
194 """
195 if "run" in config or "collection" in config:
196 raise ValueError("Passing a run or collection via configuration is no longer supported.")
198 defaults = RegistryDefaults.from_butler_instance_options(options)
199 try:
200 butlerRoot = config.get("root", config.configDir)
201 writeable = options.writeable
202 if writeable is None:
203 writeable = options.run is not None
204 registry = _RegistryFactory(config).from_config(
205 butlerRoot=butlerRoot, writeable=writeable, defaults=defaults
206 )
207 if without_datastore:
208 datastore: Datastore = NullDatastore(None, None)
209 else:
210 datastore = Datastore.fromConfig(
211 config, registry.getDatastoreBridgeManager(), butlerRoot=butlerRoot
212 )
213 # TODO: Once datastore drops dependency on registry we can
214 # construct datastore first and pass opaque tables to registry
215 # constructor.
216 registry.make_datastore_tables(datastore.get_opaque_table_definitions())
217 storageClasses = StorageClassFactory()
218 storageClasses.addFromConfig(config)
220 return DirectButler(
221 config=config,
222 registry=registry,
223 datastore=datastore,
224 storageClasses=storageClasses,
225 metrics=options.metrics,
226 )
227 except Exception:
228 # Failures here usually mean that configuration is incomplete,
229 # just issue an error message which includes config file URI.
230 _LOG.error(f"Failed to instantiate Butler from config {config.configFile}.")
231 raise
233 def clone(
234 self,
235 *,
236 collections: CollectionArgType | None | EllipsisType = ...,
237 run: str | None | EllipsisType = ...,
238 inferDefaults: bool | EllipsisType = ...,
239 dataId: dict[str, str] | EllipsisType = ...,
240 metrics: ButlerMetrics | None = None,
241 ) -> DirectButler:
242 # Docstring inherited
243 defaults = self._registry.defaults.clone(collections, run, inferDefaults, dataId)
244 registry = self._registry.copy(defaults)
246 return DirectButler(
247 registry=registry,
248 config=self._config,
249 datastore=self._datastore.clone(registry.getDatastoreBridgeManager()),
250 storageClasses=self.storageClasses,
251 metrics=metrics,
252 )
254 def close(self) -> None:
255 if not self._closed:
256 self._closed = True
257 self._registry.close()
258 # Cause exceptions to be raised if a user attempts to use the
259 # instance after closing it. Without this, Butler would still
260 # work after being closed because of implementation details
261 # of SqlAlchemy, but this may not continue to be the case in the
262 # future and we don't want users to get in the habit of doing this.
263 self._registry = _BUTLER_CLOSED_INSTANCE
264 self._datastore = _BUTLER_CLOSED_INSTANCE
266 GENERATION: ClassVar[int] = 3
267 """This is a Generation 3 Butler.
269 This attribute may be removed in the future, once the Generation 2 Butler
270 interface has been fully retired; it should only be used in transitional
271 code.
272 """
274 @classmethod
275 def _unpickle(
276 cls,
277 config: ButlerConfig,
278 collections: tuple[str, ...] | None,
279 run: str | None,
280 defaultDataId: dict[str, str],
281 writeable: bool,
282 ) -> DirectButler:
283 """Callable used to unpickle a Butler.
285 We prefer not to use ``Butler.__init__`` directly so we can force some
286 of its many arguments to be keyword-only (note that ``__reduce__``
287 can only invoke callables with positional arguments).
289 Parameters
290 ----------
291 config : `ButlerConfig`
292 Butler configuration, already coerced into a true `ButlerConfig`
293 instance (and hence after any search paths for overrides have been
294 utilized).
295 collections : `tuple` [ `str` ]
296 Names of the default collections to read from.
297 run : `str`, optional
298 Name of the default `~CollectionType.RUN` collection to write to.
299 defaultDataId : `dict` [ `str`, `str` ]
300 Default data ID values.
301 writeable : `bool`
302 Whether the Butler should support write operations.
304 Returns
305 -------
306 butler : `Butler`
307 A new `Butler` instance.
308 """
309 return cls.create_from_config(
310 config=config,
311 options=ButlerInstanceOptions(
312 collections=collections, run=run, writeable=writeable, kwargs=defaultDataId
313 ),
314 )
316 def __reduce__(self) -> tuple:
317 """Support pickling."""
318 return (
319 DirectButler._unpickle,
320 (
321 self._config,
322 self.collections.defaults,
323 self.run,
324 dict(self._registry.defaults.dataId.required),
325 self._registry.isWriteable(),
326 ),
327 )
329 def __str__(self) -> str:
330 return (
331 f"Butler(collections={self.collections}, run={self.run}, "
332 f"datastore='{self._datastore}', registry='{self._registry}')"
333 )
335 def isWriteable(self) -> bool:
336 # Docstring inherited.
337 return self._registry.isWriteable()
339 def _caching_context(self) -> contextlib.AbstractContextManager[None]:
340 """Context manager that enables caching."""
341 return self._registry.caching_context()
343 @contextlib.contextmanager
344 def transaction(self) -> Iterator[None]:
345 """Context manager supporting `Butler` transactions.
347 Transactions can be nested.
348 """
349 with self._registry.transaction(), self._datastore.transaction():
350 yield
352 def _standardizeArgs(
353 self,
354 datasetRefOrType: DatasetRef | DatasetType | str,
355 dataId: DataId | None = None,
356 for_put: bool = True,
357 **kwargs: Any,
358 ) -> tuple[DatasetType, DataId | None]:
359 """Standardize the arguments passed to several Butler APIs.
361 Parameters
362 ----------
363 datasetRefOrType : `DatasetRef`, `DatasetType`, or `str`
364 When `DatasetRef` the `dataId` should be `None`.
365 Otherwise the `DatasetType` or name thereof.
366 dataId : `dict` or `DataCoordinate`
367 A `dict` of `Dimension` link name, value pairs that label the
368 `DatasetRef` within a Collection. When `None`, a `DatasetRef`
369 should be provided as the second argument.
370 for_put : `bool`, optional
371 If `True` this call is invoked as part of a `Butler.put()`.
372 Otherwise it is assumed to be part of a `Butler.get()`. This
373 parameter is only relevant if there is dataset type
374 inconsistency.
375 **kwargs
376 Additional keyword arguments used to augment or construct a
377 `DataCoordinate`. See `DataCoordinate.standardize`
378 parameters.
380 Returns
381 -------
382 datasetType : `DatasetType`
383 A `DatasetType` instance extracted from ``datasetRefOrType``.
384 dataId : `dict` or `DataId`, optional
385 Argument that can be used (along with ``kwargs``) to construct a
386 `DataId`.
388 Notes
389 -----
390 Butler APIs that conceptually need a DatasetRef also allow passing a
391 `DatasetType` (or the name of one) and a `DataId` (or a dict and
392 keyword arguments that can be used to construct one) separately. This
393 method accepts those arguments and always returns a true `DatasetType`
394 and a `DataId` or `dict`.
396 Standardization of `dict` vs `DataId` is best handled by passing the
397 returned ``dataId`` (and ``kwargs``) to `Registry` APIs, which are
398 generally similarly flexible.
399 """
400 externalDatasetType: DatasetType | None = None
401 internalDatasetType: DatasetType | None = None
402 if isinstance(datasetRefOrType, DatasetRef):
403 if dataId is not None or kwargs:
404 raise ValueError("DatasetRef given, cannot use dataId as well")
405 externalDatasetType = datasetRefOrType.datasetType
406 dataId = datasetRefOrType.dataId
407 else:
408 # Don't check whether DataId is provided, because Registry APIs
409 # can usually construct a better error message when it wasn't.
410 if isinstance(datasetRefOrType, DatasetType):
411 externalDatasetType = datasetRefOrType
412 else:
413 internalDatasetType = self.get_dataset_type(datasetRefOrType)
415 # Check that they are self-consistent
416 if externalDatasetType is not None:
417 internalDatasetType = self.get_dataset_type(externalDatasetType.name)
418 if externalDatasetType != internalDatasetType:
419 # We can allow differences if they are compatible, depending
420 # on whether this is a get or a put. A get requires that
421 # the python type associated with the datastore can be
422 # converted to the user type. A put requires that the user
423 # supplied python type can be converted to the internal
424 # type expected by registry.
425 relevantDatasetType = internalDatasetType
426 if for_put:
427 is_compatible = internalDatasetType.is_compatible_with(externalDatasetType)
428 else:
429 is_compatible = externalDatasetType.is_compatible_with(internalDatasetType)
430 relevantDatasetType = externalDatasetType
431 if not is_compatible:
432 raise ValueError(
433 f"Supplied dataset type ({externalDatasetType}) inconsistent with "
434 f"registry definition ({internalDatasetType})"
435 )
436 # Override the internal definition.
437 internalDatasetType = relevantDatasetType
439 assert internalDatasetType is not None
440 return internalDatasetType, dataId
442 def _rewrite_data_id(
443 self, dataId: DataId | None, datasetType: DatasetType, **kwargs: Any
444 ) -> tuple[DataId | None, dict[str, Any]]:
445 """Rewrite a data ID taking into account dimension records.
447 Take a Data ID and keyword args and rewrite it if necessary to
448 allow the user to specify dimension records rather than dimension
449 primary values.
451 This allows a user to include a dataId dict with keys of
452 ``exposure.day_obs`` and ``exposure.seq_num`` instead of giving
453 the integer exposure ID. It also allows a string to be given
454 for a dimension value rather than the integer ID if that is more
455 convenient. For example, rather than having to specifying the
456 detector with ``detector.full_name``, a string given for ``detector``
457 will be interpreted as the full name and converted to the integer
458 value.
460 Keyword arguments can also use strings for dimensions like detector
461 and exposure but python does not allow them to include ``.`` and
462 so the ``exposure.day_obs`` syntax can not be used in a keyword
463 argument.
465 Parameters
466 ----------
467 dataId : `dict` or `DataCoordinate`
468 A `dict` of `Dimension` link name, value pairs that will label the
469 `DatasetRef` within a Collection.
470 datasetType : `DatasetType`
471 The dataset type associated with this dataId. Required to
472 determine the relevant dimensions.
473 **kwargs
474 Additional keyword arguments used to augment or construct a
475 `DataId`. See `DataId` parameters.
477 Returns
478 -------
479 dataId : `dict` or `DataCoordinate`
480 The, possibly rewritten, dataId. If given a `DataCoordinate` and
481 no keyword arguments, the original dataId will be returned
482 unchanged.
483 **kwargs : `dict`
484 Any unused keyword arguments (would normally be empty dict).
485 """
486 # Process dimension records that are using record information
487 # rather than ids
488 newDataId: dict[str, DataIdValue] = {}
489 byRecord: dict[str, dict[str, Any]] = defaultdict(dict)
491 if isinstance(dataId, DataCoordinate):
492 # Do nothing if we have a DataCoordinate and no kwargs.
493 if not kwargs:
494 return dataId, kwargs
495 # If we have a DataCoordinate with kwargs, we know the
496 # DataCoordinate only has values for real dimensions.
497 newDataId.update(dataId.mapping)
498 elif dataId:
499 # The data is mapping, which means it might have keys like
500 # "exposure.obs_id" (unlike kwargs, because a "." is not allowed in
501 # a keyword parameter).
502 for k, v in dataId.items():
503 if isinstance(k, str) and "." in k:
504 # Someone is using a more human-readable dataId
505 dimensionName, record = k.split(".", 1)
506 byRecord[dimensionName][record] = v
507 else:
508 newDataId[k] = v
510 # Go through the updated dataId and check the type in case someone is
511 # using an alternate key. We have already filtered out the compound
512 # keys dimensions.record format.
513 not_dimensions = {}
515 # Will need to look in the dataId and the keyword arguments
516 # and will remove them if they need to be fixed or are unrecognized.
517 for dataIdDict in (newDataId, kwargs):
518 # Use a list so we can adjust the dict safely in the loop
519 for dimensionName in list(dataIdDict):
520 value = dataIdDict[dimensionName]
521 try:
522 dimension = self.dimensions.dimensions[dimensionName]
523 except KeyError:
524 # This is not a real dimension
525 not_dimensions[dimensionName] = value
526 del dataIdDict[dimensionName]
527 continue
529 # Convert an integral type to an explicit int to simplify
530 # comparisons here
531 if isinstance(value, numbers.Integral):
532 value = int(value)
534 if not isinstance(value, dimension.primaryKey.getPythonType()):
535 for alternate in dimension.alternateKeys:
536 if isinstance(value, alternate.getPythonType()):
537 byRecord[dimensionName][alternate.name] = value
538 del dataIdDict[dimensionName]
539 _LOG.debug(
540 "Converting dimension %s to %s.%s=%s",
541 dimensionName,
542 dimensionName,
543 alternate.name,
544 value,
545 )
546 break
547 else:
548 _LOG.warning(
549 "Type mismatch found for value '%r' provided for dimension %s. "
550 "Could not find matching alternative (primary key has type %s) "
551 "so attempting to use as-is.",
552 value,
553 dimensionName,
554 dimension.primaryKey.getPythonType(),
555 )
557 # By this point kwargs and newDataId should only include valid
558 # dimensions. Merge kwargs in to the new dataId and log if there
559 # are dimensions in both (rather than calling update).
560 for k, v in kwargs.items():
561 if k in newDataId and newDataId[k] != v:
562 _LOG.debug(
563 "Keyword arg %s overriding explicit value in dataId of %s with %s", k, newDataId[k], v
564 )
565 newDataId[k] = v
566 # No need to retain any values in kwargs now.
567 kwargs = {}
569 # If we have some unrecognized dimensions we have to try to connect
570 # them to records in other dimensions. This is made more complicated
571 # by some dimensions having records with clashing names. A mitigation
572 # is that we can tell by this point which dimensions are missing
573 # for the DatasetType but this does not work for calibrations
574 # where additional dimensions can be used to constrain the temporal
575 # axis.
576 if not_dimensions:
577 # Search for all dimensions even if we have been given a value
578 # explicitly. In some cases records are given as well as the
579 # actually dimension and this should not be an error if they
580 # match.
581 mandatoryDimensions = datasetType.dimensions.names # - provided
583 candidateDimensions: set[str] = set()
584 candidateDimensions.update(mandatoryDimensions)
586 # For calibrations we may well be needing temporal dimensions
587 # so rather than always including all dimensions in the scan
588 # restrict things a little. It is still possible for there
589 # to be confusion over day_obs in visit vs exposure for example.
590 # If we are not searching calibration collections things may
591 # fail but they are going to fail anyway because of the
592 # ambiguousness of the dataId...
593 if datasetType.isCalibration():
594 for dim in self.dimensions.dimensions:
595 if dim.temporal:
596 candidateDimensions.add(str(dim))
598 # Look up table for the first association with a dimension
599 guessedAssociation: dict[str, dict[str, Any]] = defaultdict(dict)
601 # Keep track of whether an item is associated with multiple
602 # dimensions.
603 counter: Counter[str] = Counter()
604 assigned: dict[str, set[str]] = defaultdict(set)
606 # Go through the missing dimensions and associate the
607 # given names with records within those dimensions
608 matched_dims = set()
609 for dimensionName in candidateDimensions:
610 dimension = self.dimensions.dimensions[dimensionName]
611 fields = dimension.metadata.names | dimension.uniqueKeys.names
612 for field in not_dimensions:
613 if field in fields:
614 guessedAssociation[dimensionName][field] = not_dimensions[field]
615 counter[dimensionName] += 1
616 assigned[field].add(dimensionName)
617 matched_dims.add(field)
619 # Calculate the fields that matched nothing.
620 never_found = set(not_dimensions) - matched_dims
622 if never_found:
623 raise DimensionValueError(f"Unrecognized keyword args given: {never_found}")
625 # There is a chance we have allocated a single dataId item
626 # to multiple dimensions. Need to decide which should be retained.
627 # For now assume that the most popular alternative wins.
628 # This means that day_obs with seq_num will result in
629 # exposure.day_obs and not visit.day_obs
630 # Also prefer an explicitly missing dimension over an inferred
631 # temporal dimension.
632 for fieldName, assignedDimensions in assigned.items():
633 if len(assignedDimensions) > 1:
634 # Pick the most popular (preferring mandatory dimensions)
635 requiredButMissing = assignedDimensions.intersection(mandatoryDimensions)
636 if requiredButMissing:
637 candidateDimensions = requiredButMissing
638 else:
639 candidateDimensions = assignedDimensions
641 # If this is a choice between visit and exposure and
642 # neither was a required part of the dataset type,
643 # (hence in this branch) always prefer exposure over
644 # visit since exposures are always defined and visits
645 # are defined from exposures.
646 if candidateDimensions == {"exposure", "visit"}:
647 candidateDimensions = {"exposure"}
649 # Select the relevant items and get a new restricted
650 # counter.
651 theseCounts = {k: v for k, v in counter.items() if k in candidateDimensions}
652 duplicatesCounter: Counter[str] = Counter()
653 duplicatesCounter.update(theseCounts)
655 # Choose the most common. If they are equally common
656 # we will pick the one that was found first.
657 # Returns a list of tuples
658 selected = duplicatesCounter.most_common(1)[0][0]
660 _LOG.debug(
661 "Ambiguous dataId entry '%s' associated with multiple dimensions: %s."
662 " Removed ambiguity by choosing dimension %s.",
663 fieldName,
664 ", ".join(assignedDimensions),
665 selected,
666 )
668 for candidateDimension in assignedDimensions:
669 if candidateDimension != selected:
670 del guessedAssociation[candidateDimension][fieldName]
672 # Update the record look up dict with the new associations
673 for dimensionName, values in guessedAssociation.items():
674 if values: # A dict might now be empty
675 _LOG.debug(
676 "Assigned non-dimension dataId keys to dimension %s: %s", dimensionName, values
677 )
678 byRecord[dimensionName].update(values)
680 if byRecord:
681 # Some record specifiers were found so we need to convert
682 # them to the Id form
683 for dimensionName, values in byRecord.items():
684 if dimensionName in newDataId:
685 _LOG.debug(
686 "DataId specified explicit %s dimension value of %s in addition to"
687 " general record specifiers for it of %s. Checking for self-consistency.",
688 dimensionName,
689 newDataId[dimensionName],
690 str(values),
691 )
692 # Get the actual record and compare with these values.
693 # Only query with relevant data ID values.
694 filtered_data_id = {
695 k: v for k, v in newDataId.items() if k in self.dimensions[dimensionName].required
696 }
697 try:
698 recs = self.query_dimension_records(
699 dimensionName,
700 data_id=filtered_data_id,
701 )
702 except (DataIdError, EmptyQueryResultError):
703 raise DimensionValueError(
704 f"Could not find dimension '{dimensionName}'"
705 f" with dataId {filtered_data_id} as part of comparing with"
706 f" record values {byRecord[dimensionName]}"
707 ) from None
708 if len(recs) == 1:
709 errmsg: list[str] = []
710 for k, v in values.items():
711 if (recval := getattr(recs[0], k)) != v:
712 errmsg.append(f"{k} ({recval} != {v})")
713 if errmsg:
714 raise DimensionValueError(
715 f"Dimension {dimensionName} in dataId has explicit value"
716 f" {newDataId[dimensionName]} inconsistent with"
717 f" {dimensionName} dimension record: " + ", ".join(errmsg)
718 )
719 else:
720 # Multiple matches for an explicit dimension
721 # should never happen but let downstream complain.
722 pass
723 continue
725 # Do not use data ID keys in query that aren't relevant.
726 # Otherwise we can have detector queries being constrained
727 # by an exposure ID that doesn't exist and return no matches
728 # for a detector even though it's a good detector name.
729 filtered_data_id = {
730 k: v
731 for k, v in newDataId.items()
732 if k in self.dimensions[dimensionName].minimal_group.names
733 }
735 def _get_attr(obj: Any, attr: str) -> Any:
736 # Used to implement x.exposure.seq_num when given
737 # x and "exposure.seq_num".
738 for component in attr.split("."):
739 obj = getattr(obj, component)
740 return obj
742 with self.query() as q:
743 x = q.expression_factory
744 # Build up a WHERE expression.
745 predicates = tuple(_get_attr(x, f"{dimensionName}.{k}") == v for k, v in values.items())
746 extra_args: dict[str, Any] = {} # For mypy.
747 extra_args.update(filtered_data_id)
748 extra_args.update(kwargs)
749 q = q.where(x.all(*predicates), **extra_args)
750 records = set(q.dimension_records(dimensionName))
752 if len(records) != 1:
753 if len(records) > 1:
754 # visit can have an ambiguous answer without involving
755 # visit_system. The default visit_system is defined
756 # by the instrument.
757 if (
758 dimensionName == "visit"
759 and "visit_system_membership" in self.dimensions
760 and "visit_system" in self.dimensions["instrument"].metadata
761 ):
762 instrument_records = self.query_dimension_records(
763 "instrument",
764 data_id=newDataId,
765 explain=False,
766 **kwargs,
767 )
768 if len(instrument_records) == 1:
769 visit_system = instrument_records[0].visit_system
770 if visit_system is None:
771 # Set to a value that will never match.
772 visit_system = -1
774 # Look up each visit in the
775 # visit_system_membership records.
776 for rec in records:
777 membership = self.query_dimension_records(
778 # Use bind to allow zero results.
779 # This is a fully-specified query.
780 "visit_system_membership",
781 instrument=instrument_records[0].name,
782 visit_system=visit_system,
783 visit=rec.id,
784 explain=False,
785 )
786 if membership:
787 # This record is the right answer.
788 records = {rec}
789 break
791 # The ambiguity may have been resolved so check again.
792 if len(records) > 1:
793 _LOG.debug(
794 "Received %d records from constraints of %s", len(records), str(values)
795 )
796 for r in records:
797 _LOG.debug("- %s", str(r))
798 raise DimensionValueError(
799 f"DataId specification for dimension {dimensionName} is not"
800 f" uniquely constrained to a single dataset by {values}."
801 f" Got {len(records)} results."
802 )
803 else:
804 raise DimensionValueError(
805 f"DataId specification for dimension {dimensionName} matched no"
806 f" records when constrained by {values}"
807 )
809 # Get the primary key from the real dimension object
810 dimension = self.dimensions.dimensions[dimensionName]
811 if not isinstance(dimension, Dimension):
812 raise RuntimeError(
813 f"{dimension.name} is not a true dimension, and cannot be used in data IDs."
814 )
815 newDataId[dimensionName] = getattr(records.pop(), dimension.primaryKey.name)
817 return newDataId, kwargs
819 def _findDatasetRef(
820 self,
821 datasetRefOrType: DatasetRef | DatasetType | str,
822 dataId: DataId | None = None,
823 *,
824 collections: Any = None,
825 predict: bool = False,
826 run: str | None = None,
827 datastore_records: bool = False,
828 timespan: Timespan | None = None,
829 **kwargs: Any,
830 ) -> DatasetRef:
831 """Shared logic for methods that start with a search for a dataset in
832 the registry.
834 Parameters
835 ----------
836 datasetRefOrType : `DatasetRef`, `DatasetType`, or `str`
837 When `DatasetRef` the `dataId` should be `None`.
838 Otherwise the `DatasetType` or name thereof.
839 dataId : `dict` or `DataCoordinate`, optional
840 A `dict` of `Dimension` link name, value pairs that label the
841 `DatasetRef` within a Collection. When `None`, a `DatasetRef`
842 should be provided as the first argument.
843 collections : Any, optional
844 Collections to be searched, overriding ``self.collections``.
845 Can be any of the types supported by the ``collections`` argument
846 to butler construction.
847 predict : `bool`, optional
848 If `True`, return a newly created `DatasetRef` with a unique
849 dataset ID if finding a reference in the `Registry` fails.
850 Defaults to `False`.
851 run : `str`, optional
852 Run collection name to use for creating `DatasetRef` for predicted
853 datasets. Only used if ``predict`` is `True`.
854 datastore_records : `bool`, optional
855 If `True` add datastore records to returned `DatasetRef`.
856 timespan : `Timespan` or `None`, optional
857 A timespan that the validity range of the dataset must overlap.
858 If not provided and this is a calibration dataset type, an attempt
859 will be made to find the timespan from any temporal coordinate
860 in the data ID.
861 **kwargs
862 Additional keyword arguments used to augment or construct a
863 `DataId`. See `DataId` parameters.
865 Returns
866 -------
867 ref : `DatasetRef`
868 A reference to the dataset identified by the given arguments.
869 This can be the same dataset reference as given if it was
870 resolved.
872 Raises
873 ------
874 LookupError
875 Raised if no matching dataset exists in the `Registry` (and
876 ``predict`` is `False`).
877 ValueError
878 Raised if a resolved `DatasetRef` was passed as an input, but it
879 differs from the one found in the registry.
880 TypeError
881 Raised if no collections were provided.
882 """
883 datasetType, dataId = self._standardizeArgs(datasetRefOrType, dataId, for_put=False, **kwargs)
884 if isinstance(datasetRefOrType, DatasetRef):
885 if collections is not None:
886 warnings.warn("Collections should not be specified with DatasetRef", stacklevel=3)
887 # May need to retrieve datastore records if requested.
888 if datastore_records and datasetRefOrType._datastore_records is None:
889 datasetRefOrType = self._registry.get_datastore_records(datasetRefOrType)
890 return datasetRefOrType
892 dataId, kwargs = self._rewrite_data_id(dataId, datasetType, **kwargs)
894 if datasetType.isCalibration():
895 # Because this is a calibration dataset, first try to make a
896 # standardize the data ID without restricting the dimensions to
897 # those of the dataset type requested, because there may be extra
898 # dimensions that provide temporal information for a validity-range
899 # lookup.
900 dataId = DataCoordinate.standardize(
901 dataId, universe=self.dimensions, defaults=self._registry.defaults.dataId, **kwargs
902 )
903 if timespan is None:
904 if dataId.dimensions.temporal:
905 dataId = self._registry.expandDataId(dataId)
906 # Use the timespan from the data ID to constrain the
907 # calibration lookup, but only if the caller has not
908 # specified an explicit timespan.
909 timespan = dataId.timespan
910 else:
911 # Try an arbitrary timespan. Downstream will fail if this
912 # results in more than one matching dataset.
913 timespan = Timespan(None, None)
914 else:
915 # Standardize the data ID to just the dimensions of the dataset
916 # type instead of letting registry.findDataset do it, so we get the
917 # result even if no dataset is found.
918 dataId = DataCoordinate.standardize(
919 dataId,
920 dimensions=datasetType.dimensions,
921 defaults=self._registry.defaults.dataId,
922 **kwargs,
923 )
924 # Always lookup the DatasetRef, even if one is given, to ensure it is
925 # present in the current collection.
926 ref = self.find_dataset(
927 datasetType,
928 dataId,
929 collections=collections,
930 timespan=timespan,
931 datastore_records=datastore_records,
932 )
933 if ref is None:
934 if predict:
935 if run is None:
936 run = self.run
937 if run is None:
938 raise TypeError("Cannot predict dataset ID/location with run=None.")
939 return DatasetRef(datasetType, dataId, run=run)
940 else:
941 if collections is None:
942 collections = self._registry.defaults.collections
943 raise DatasetNotFoundError(
944 f"Dataset {datasetType.name} with data ID {dataId} "
945 f"could not be found in collections {collections}."
946 )
947 if datasetType != ref.datasetType:
948 # If they differ it is because the user explicitly specified
949 # a compatible dataset type to this call rather than using the
950 # registry definition. The DatasetRef must therefore be recreated
951 # using the user definition such that the expected type is
952 # returned.
953 ref = DatasetRef(
954 datasetType, ref.dataId, run=ref.run, id=ref.id, datastore_records=ref._datastore_records
955 )
957 return ref
959 @transactional
960 def put(
961 self,
962 obj: Any,
963 datasetRefOrType: DatasetRef | DatasetType | str,
964 /,
965 dataId: DataId | None = None,
966 *,
967 run: str | None = None,
968 provenance: DatasetProvenance | None = None,
969 **kwargs: Any,
970 ) -> DatasetRef:
971 """Store and register a dataset.
973 Parameters
974 ----------
975 obj : `object`
976 The dataset.
977 datasetRefOrType : `DatasetRef`, `DatasetType`, or `str`
978 When `DatasetRef` is provided, ``dataId`` should be `None`.
979 Otherwise the `DatasetType` or name thereof. If a fully resolved
980 `DatasetRef` is given the run and ID are used directly.
981 dataId : `dict` or `DataCoordinate`
982 A `dict` of `Dimension` link name, value pairs that label the
983 `DatasetRef` within a Collection. When `None`, a `DatasetRef`
984 should be provided as the second argument.
985 run : `str`, optional
986 The name of the run the dataset should be added to, overriding
987 ``self.run``. Not used if a resolved `DatasetRef` is provided.
988 provenance : `DatasetProvenance` or `None`, optional
989 Any provenance that should be attached to the serialized dataset.
990 Not supported by all serialization mechanisms.
991 **kwargs
992 Additional keyword arguments used to augment or construct a
993 `DataCoordinate`. See `DataCoordinate.standardize`
994 parameters. Not used if a resolve `DatasetRef` is provided.
996 Returns
997 -------
998 ref : `DatasetRef`
999 A reference to the stored dataset, updated with the correct id if
1000 given.
1002 Raises
1003 ------
1004 TypeError
1005 Raised if the butler is read-only or if no run has been provided.
1006 """
1007 if isinstance(datasetRefOrType, DatasetRef):
1008 # This is a direct put of predefined DatasetRef.
1009 _LOG.debug("Butler put direct: %s", datasetRefOrType)
1010 if run is not None:
1011 warnings.warn("Run collection is not used for DatasetRef", stacklevel=3)
1013 with self._metrics.instrument_put(_LOG, msg="Dataset put direct"):
1014 # If registry already has a dataset with the same dataset ID,
1015 # dataset type and DataId, then _importDatasets will do
1016 # nothing and just return an original ref. We have to raise in
1017 # this case, there is a datastore check below for that.
1018 self._registry._importDatasets([datasetRefOrType], expand=True)
1019 # Before trying to write to the datastore check that it does
1020 # not know this dataset. This is prone to races, of course.
1021 if self._datastore.knows(datasetRefOrType):
1022 raise ConflictingDefinitionError(
1023 f"Datastore already contains dataset: {datasetRefOrType}"
1024 )
1025 # Try to write dataset to the datastore, if it fails due to a
1026 # race with another write, the content of stored data may be
1027 # unpredictable.
1028 try:
1029 self._datastore.put(obj, datasetRefOrType, provenance=provenance)
1030 except IntegrityError as e:
1031 raise ConflictingDefinitionError(f"Datastore already contains dataset: {e}") from e
1033 return datasetRefOrType
1035 _LOG.debug("Butler put: %s, dataId=%s, run=%s", datasetRefOrType, dataId, run)
1036 if not self.isWriteable():
1037 raise TypeError("Butler is read-only.")
1039 with self._metrics.instrument_put(_LOG, msg="Dataset put with dataID"):
1040 datasetType, dataId = self._standardizeArgs(datasetRefOrType, dataId, **kwargs)
1042 # Handle dimension records in dataId
1043 dataId, kwargs = self._rewrite_data_id(dataId, datasetType, **kwargs)
1045 # Add Registry Dataset entry.
1046 dataId = self._registry.expandDataId(dataId, dimensions=datasetType.dimensions, **kwargs)
1047 (ref,) = self._registry.insertDatasets(datasetType, run=run, dataIds=[dataId])
1048 self._datastore.put(obj, ref, provenance=provenance)
1050 return ref
1052 def getDeferred(
1053 self,
1054 datasetRefOrType: DatasetRef | DatasetType | str,
1055 /,
1056 dataId: DataId | None = None,
1057 *,
1058 parameters: dict | None = None,
1059 collections: Any = None,
1060 storageClass: str | StorageClass | None = None,
1061 timespan: Timespan | None = None,
1062 **kwargs: Any,
1063 ) -> DeferredDatasetHandle:
1064 """Create a `DeferredDatasetHandle` which can later retrieve a dataset,
1065 after an immediate registry lookup.
1067 Parameters
1068 ----------
1069 datasetRefOrType : `DatasetRef`, `DatasetType`, or `str`
1070 When `DatasetRef` the `dataId` should be `None`.
1071 Otherwise the `DatasetType` or name thereof.
1072 dataId : `dict` or `DataCoordinate`, optional
1073 A `dict` of `Dimension` link name, value pairs that label the
1074 `DatasetRef` within a Collection. When `None`, a `DatasetRef`
1075 should be provided as the first argument.
1076 parameters : `dict`
1077 Additional StorageClass-defined options to control reading,
1078 typically used to efficiently read only a subset of the dataset.
1079 collections : Any, optional
1080 Collections to be searched, overriding ``self.collections``.
1081 Can be any of the types supported by the ``collections`` argument
1082 to butler construction.
1083 storageClass : `StorageClass` or `str`, optional
1084 The storage class to be used to override the Python type
1085 returned by this method. By default the returned type matches
1086 the dataset type definition for this dataset. Specifying a
1087 read `StorageClass` can force a different type to be returned.
1088 This type must be compatible with the original type.
1089 timespan : `Timespan` or `None`, optional
1090 A timespan that the validity range of the dataset must overlap.
1091 If not provided and this is a calibration dataset type, an attempt
1092 will be made to find the timespan from any temporal coordinate
1093 in the data ID.
1094 **kwargs
1095 Additional keyword arguments used to augment or construct a
1096 `DataId`. See `DataId` parameters.
1098 Returns
1099 -------
1100 obj : `DeferredDatasetHandle`
1101 A handle which can be used to retrieve a dataset at a later time.
1103 Raises
1104 ------
1105 LookupError
1106 Raised if no matching dataset exists in the `Registry` or
1107 datastore.
1108 ValueError
1109 Raised if a resolved `DatasetRef` was passed as an input, but it
1110 differs from the one found in the registry.
1111 TypeError
1112 Raised if no collections were provided.
1113 """
1114 if isinstance(datasetRefOrType, DatasetRef):
1115 # Do the quick check first and if that fails, check for artifact
1116 # existence. This is necessary for datastores that are configured
1117 # in trust mode where there won't be a record but there will be
1118 # a file.
1119 if self._datastore.knows(datasetRefOrType) or self._datastore.exists(datasetRefOrType):
1120 ref = datasetRefOrType
1121 else:
1122 raise LookupError(f"Dataset reference {datasetRefOrType} does not exist.")
1123 else:
1124 ref = self._findDatasetRef(
1125 datasetRefOrType, dataId, collections=collections, timespan=timespan, **kwargs
1126 )
1127 return DeferredDatasetHandle(butler=self, ref=ref, parameters=parameters, storageClass=storageClass)
1129 def get(
1130 self,
1131 datasetRefOrType: DatasetRef | DatasetType | str,
1132 /,
1133 dataId: DataId | None = None,
1134 *,
1135 parameters: dict[str, Any] | None = None,
1136 collections: Any = None,
1137 storageClass: StorageClass | str | None = None,
1138 timespan: Timespan | None = None,
1139 **kwargs: Any,
1140 ) -> Any:
1141 """Retrieve a stored dataset.
1143 Parameters
1144 ----------
1145 datasetRefOrType : `DatasetRef`, `DatasetType`, or `str`
1146 When `DatasetRef` the `dataId` should be `None`.
1147 Otherwise the `DatasetType` or name thereof.
1148 If a resolved `DatasetRef`, the associated dataset
1149 is returned directly without additional querying.
1150 dataId : `dict` or `DataCoordinate`
1151 A `dict` of `Dimension` link name, value pairs that label the
1152 `DatasetRef` within a Collection. When `None`, a `DatasetRef`
1153 should be provided as the first argument.
1154 parameters : `dict`
1155 Additional StorageClass-defined options to control reading,
1156 typically used to efficiently read only a subset of the dataset.
1157 collections : Any, optional
1158 Collections to be searched, overriding ``self.collections``.
1159 Can be any of the types supported by the ``collections`` argument
1160 to butler construction.
1161 storageClass : `StorageClass` or `str`, optional
1162 The storage class to be used to override the Python type
1163 returned by this method. By default the returned type matches
1164 the dataset type definition for this dataset. Specifying a
1165 read `StorageClass` can force a different type to be returned.
1166 This type must be compatible with the original type.
1167 timespan : `Timespan` or `None`, optional
1168 A timespan that the validity range of the dataset must overlap.
1169 If not provided and this is a calibration dataset type, an attempt
1170 will be made to find the timespan from any temporal coordinate
1171 in the data ID.
1172 **kwargs
1173 Additional keyword arguments used to augment or construct a
1174 `DataCoordinate`. See `DataCoordinate.standardize`
1175 parameters.
1177 Returns
1178 -------
1179 obj : `object`
1180 The dataset.
1182 Raises
1183 ------
1184 LookupError
1185 Raised if no matching dataset exists in the `Registry`.
1186 TypeError
1187 Raised if no collections were provided.
1189 Notes
1190 -----
1191 When looking up datasets in a `~CollectionType.CALIBRATION` collection,
1192 this method requires that the given data ID include temporal dimensions
1193 beyond the dimensions of the dataset type itself, in order to find the
1194 dataset with the appropriate validity range. For example, a "bias"
1195 dataset with native dimensions ``{instrument, detector}`` could be
1196 fetched with a ``{instrument, detector, exposure}`` data ID, because
1197 ``exposure`` is a temporal dimension.
1198 """
1199 _LOG.debug("Butler get: %s, dataId=%s, parameters=%s", datasetRefOrType, dataId, parameters)
1200 with self._metrics.instrument_get(_LOG, msg="Retrieved dataset"):
1201 ref = self._findDatasetRef(
1202 datasetRefOrType,
1203 dataId,
1204 collections=collections,
1205 datastore_records=True,
1206 timespan=timespan,
1207 **kwargs,
1208 )
1209 return self._datastore.get(ref, parameters=parameters, storageClass=storageClass)
1211 def getURIs(
1212 self,
1213 datasetRefOrType: DatasetRef | DatasetType | str,
1214 /,
1215 dataId: DataId | None = None,
1216 *,
1217 predict: bool = False,
1218 collections: Any = None,
1219 run: str | None = None,
1220 **kwargs: Any,
1221 ) -> DatasetRefURIs:
1222 """Return the URIs associated with the dataset.
1224 Parameters
1225 ----------
1226 datasetRefOrType : `DatasetRef`, `DatasetType`, or `str`
1227 When `DatasetRef` the `dataId` should be `None`.
1228 Otherwise the `DatasetType` or name thereof.
1229 dataId : `dict` or `DataCoordinate`
1230 A `dict` of `Dimension` link name, value pairs that label the
1231 `DatasetRef` within a Collection. When `None`, a `DatasetRef`
1232 should be provided as the first argument.
1233 predict : `bool`
1234 If `True`, allow URIs to be returned of datasets that have not
1235 been written.
1236 collections : Any, optional
1237 Collections to be searched, overriding ``self.collections``.
1238 Can be any of the types supported by the ``collections`` argument
1239 to butler construction.
1240 run : `str`, optional
1241 Run to use for predictions, overriding ``self.run``.
1242 **kwargs
1243 Additional keyword arguments used to augment or construct a
1244 `DataCoordinate`. See `DataCoordinate.standardize`
1245 parameters.
1247 Returns
1248 -------
1249 uris : `DatasetRefURIs`
1250 The URI to the primary artifact associated with this dataset (if
1251 the dataset was disassembled within the datastore this may be
1252 `None`), and the URIs to any components associated with the dataset
1253 artifact. (can be empty if there are no components).
1254 """
1255 ref = self._findDatasetRef(
1256 datasetRefOrType, dataId, predict=predict, run=run, collections=collections, **kwargs
1257 )
1258 return self._datastore.getURIs(ref, predict)
1260 def get_dataset_type(self, name: str) -> DatasetType:
1261 return self._registry.getDatasetType(name)
1263 def get_dataset(
1264 self,
1265 id: DatasetId | str,
1266 *,
1267 storage_class: str | StorageClass | None = None,
1268 dimension_records: bool = False,
1269 datastore_records: bool = False,
1270 ) -> DatasetRef | None:
1271 id = _to_uuid(id)
1272 ref = self._registry.getDataset(id)
1273 if ref is not None:
1274 if dimension_records:
1275 ref = ref.expanded(
1276 self._registry.expandDataId(ref.dataId, dimensions=ref.datasetType.dimensions)
1277 )
1278 if storage_class:
1279 ref = ref.overrideStorageClass(storage_class)
1280 if datastore_records:
1281 ref = self._registry.get_datastore_records(ref)
1282 return ref
1284 def get_many_datasets(self, ids: Iterable[DatasetId | str]) -> list[DatasetRef]:
1285 uuids = [_to_uuid(id) for id in ids]
1286 return self._registry._managers.datasets.get_dataset_refs(uuids)
1288 def find_dataset(
1289 self,
1290 dataset_type: DatasetType | str,
1291 data_id: DataId | None = None,
1292 *,
1293 collections: str | Sequence[str] | None = None,
1294 timespan: Timespan | None = None,
1295 storage_class: str | StorageClass | None = None,
1296 dimension_records: bool = False,
1297 datastore_records: bool = False,
1298 **kwargs: Any,
1299 ) -> DatasetRef | None:
1300 # Handle any parts of the dataID that are not using primary dimension
1301 # keys.
1302 if isinstance(dataset_type, str):
1303 actual_type = self.get_dataset_type(dataset_type)
1304 else:
1305 actual_type = dataset_type
1307 # Store the component for later.
1308 component_name = actual_type.component()
1309 if actual_type.isComponent():
1310 parent_type = actual_type.makeCompositeDatasetType()
1311 else:
1312 parent_type = actual_type
1314 data_id, kwargs = self._rewrite_data_id(data_id, parent_type, **kwargs)
1316 ref = self.registry.findDataset(
1317 parent_type,
1318 data_id,
1319 collections=collections,
1320 timespan=timespan,
1321 datastore_records=datastore_records,
1322 **kwargs,
1323 )
1324 if ref is not None and dimension_records:
1325 ref = ref.expanded(self._registry.expandDataId(ref.dataId, dimensions=ref.datasetType.dimensions))
1326 if ref is not None and component_name:
1327 ref = ref.makeComponentRef(component_name)
1328 if ref is not None and storage_class is not None:
1329 ref = ref.overrideStorageClass(storage_class)
1331 return ref
1333 def retrieve_artifacts_zip(
1334 self,
1335 refs: Iterable[DatasetRef],
1336 destination: ResourcePathExpression,
1337 overwrite: bool = True,
1338 ) -> ResourcePath:
1339 return retrieve_and_zip(refs, destination, self._datastore.retrieveArtifacts, overwrite)
1341 def retrieveArtifacts(
1342 self,
1343 refs: Iterable[DatasetRef],
1344 destination: ResourcePathExpression,
1345 transfer: str = "auto",
1346 preserve_path: bool = True,
1347 overwrite: bool = False,
1348 ) -> list[ResourcePath]:
1349 # Docstring inherited.
1350 outdir = ResourcePath(destination)
1351 artifact_map = self._datastore.retrieveArtifacts(
1352 refs,
1353 outdir,
1354 transfer=transfer,
1355 preserve_path=preserve_path,
1356 overwrite=overwrite,
1357 write_index=True,
1358 )
1359 return list(artifact_map)
1361 def exists(
1362 self,
1363 dataset_ref_or_type: DatasetRef | DatasetType | str,
1364 /,
1365 data_id: DataId | None = None,
1366 *,
1367 full_check: bool = True,
1368 collections: Any = None,
1369 **kwargs: Any,
1370 ) -> DatasetExistence:
1371 # Docstring inherited.
1372 existence = DatasetExistence.UNRECOGNIZED
1374 if isinstance(dataset_ref_or_type, DatasetRef):
1375 if collections is not None:
1376 warnings.warn("Collections should not be specified with DatasetRef", stacklevel=2)
1377 if data_id is not None:
1378 warnings.warn("A DataID should not be specified with DatasetRef", stacklevel=2)
1379 ref = dataset_ref_or_type
1380 registry_ref = self._registry.getDataset(dataset_ref_or_type.id)
1381 if registry_ref is not None:
1382 existence |= DatasetExistence.RECORDED
1384 if dataset_ref_or_type != registry_ref:
1385 # This could mean that storage classes differ, so we should
1386 # check for that but use the registry ref for the rest of
1387 # the method.
1388 if registry_ref.is_compatible_with(dataset_ref_or_type):
1389 # Use the registry version from now on.
1390 ref = registry_ref
1391 else:
1392 raise ValueError(
1393 f"The ref given to exists() ({ref}) has the same dataset ID as one "
1394 f"in registry but has different incompatible values ({registry_ref})."
1395 )
1396 else:
1397 try:
1398 ref = self._findDatasetRef(dataset_ref_or_type, data_id, collections=collections, **kwargs)
1399 except (LookupError, TypeError):
1400 return existence
1401 existence |= DatasetExistence.RECORDED
1403 if self._datastore.knows(ref):
1404 existence |= DatasetExistence.DATASTORE
1406 if full_check:
1407 if self._datastore.exists(ref):
1408 existence |= DatasetExistence._ARTIFACT
1409 elif existence.value != DatasetExistence.UNRECOGNIZED.value:
1410 # Do not add this flag if we have no other idea about a dataset.
1411 existence |= DatasetExistence(DatasetExistence._ASSUMED)
1413 return existence
1415 def _exists_many(
1416 self,
1417 refs: Iterable[DatasetRef],
1418 /,
1419 *,
1420 full_check: bool = True,
1421 ) -> dict[DatasetRef, DatasetExistence]:
1422 # Docstring inherited.
1423 existence = {ref: DatasetExistence.UNRECOGNIZED for ref in refs}
1425 # Check which refs exist in the registry.
1426 id_map = {ref.id: ref for ref in existence.keys()}
1427 for registry_ref in self.get_many_datasets(id_map.keys()):
1428 # Consistency between the given DatasetRef and the information
1429 # recorded in the registry is not verified.
1430 existence[id_map[registry_ref.id]] |= DatasetExistence.RECORDED
1432 # Ask datastore if it knows about these refs.
1433 knows = self._datastore.knows_these(refs)
1434 for ref, known in knows.items():
1435 if known:
1436 existence[ref] |= DatasetExistence.DATASTORE
1438 if full_check:
1439 mexists = self._datastore.mexists(refs)
1440 for ref, exists in mexists.items():
1441 if exists:
1442 existence[ref] |= DatasetExistence._ARTIFACT
1443 else:
1444 # Do not set this flag if nothing is known about the dataset.
1445 for ref in existence:
1446 if existence[ref] != DatasetExistence.UNRECOGNIZED:
1447 existence[ref] |= DatasetExistence._ASSUMED
1449 return existence
1451 def removeRuns(
1452 self,
1453 names: Iterable[str],
1454 unstore: bool | type[_DeprecatedDefault] = _DeprecatedDefault,
1455 *,
1456 unlink_from_chains: bool = False,
1457 ) -> None:
1458 # Docstring inherited.
1459 if not self.isWriteable():
1460 raise TypeError("Butler is read-only.")
1462 if unstore is not _DeprecatedDefault:
1463 # The value was passed in by a user. Must report it is now
1464 # ignored.
1465 if unstore is True:
1466 msg = "The unstore parameter is deprecated and is now always treated as True. "
1467 else:
1468 msg = "The unstore parameter for removeRuns can no longer be False and is now ignored. "
1469 warnings.warn(
1470 msg + " The parameter will be removed after v30.",
1471 category=FutureWarning,
1472 stacklevel=find_outside_stacklevel("lsst.daf.butler"),
1473 )
1475 names = list(names)
1476 refs: list[DatasetRef] = []
1477 # Map of the chained collections to the RUN children.
1478 parents_to_children: dict[str, set[str]] = defaultdict(set)
1480 with self._caching_context():
1481 # Get information about these RUNs.
1482 collections_info = self.collections.query_info(names, include_parents=unlink_from_chains)
1483 for info in collections_info:
1484 if info.type is not CollectionType.RUN:
1485 raise TypeError(f"The collection type of '{info.name}' is {info.type.name}, not RUN.")
1486 if unlink_from_chains:
1487 if info.parents is None: # For mypy.
1488 raise AssertionError("Internal error: Collection parents required but not received")
1489 for parent in info.parents:
1490 parents_to_children[parent].add(info.name)
1492 # Update the names in case the query unexpectedly had a wildcard.
1493 names = [info.name for info in collections_info]
1495 # Get all the datasets from these runs.
1496 refs = self.query_all_datasets(names, find_first=False, limit=None)
1498 # Call pruneDatasets since we are deliberately removing
1499 # datasets in chunks from the RUN collections rather than
1500 # attempting to remove everything at once.
1501 with time_this(
1502 _LOG,
1503 msg="Removing %d dataset%s from %s",
1504 args=(len(refs), "s" if len(refs) != 1 else "", ", ".join(names)),
1505 ):
1506 self.pruneDatasets(refs, unstore=True, purge=True, disassociate=True)
1508 # Now can remove the actual RUN collection and unlink from chains.
1509 with self._registry.transaction():
1510 # This will fail if caller is not unlinking from chains but the
1511 # RUN is in a chain -- but we have already deleted all the datasets
1512 # by this point.
1513 if unlink_from_chains:
1514 # Use deterministic order for deletions to attempt to minimize
1515 # risk of deadlocks for parallel deletes.
1516 for parent in sorted(parents_to_children):
1517 self.collections.remove_from_chain(parent, sorted(parents_to_children[parent]))
1518 # Sort to avoid potential deadlocks.
1519 for name in sorted(names):
1520 # This should be fast since the collection should be empty.
1521 with time_this(_LOG, msg="Removing RUN collection %s", args=(name,)):
1522 self._registry.removeCollection(name)
1523 _LOG.info("Completely removed the following RUN collections: %s", ", ".join(names))
1525 def pruneDatasets(
1526 self,
1527 refs: Iterable[DatasetRef],
1528 *,
1529 disassociate: bool = True,
1530 unstore: bool = False,
1531 tags: Iterable[str] = (),
1532 purge: bool = False,
1533 ) -> None:
1534 # docstring inherited from LimitedButler
1536 if not self.isWriteable():
1537 raise TypeError("Butler is read-only.")
1538 if purge:
1539 if not disassociate:
1540 raise TypeError("Cannot pass purge=True without disassociate=True.")
1541 if not unstore:
1542 raise TypeError("Cannot pass purge=True without unstore=True.")
1543 elif disassociate:
1544 tags = tuple(tags)
1545 if not tags:
1546 raise TypeError("No tags provided but disassociate=True.")
1547 for tag in tags:
1548 collectionType = self._registry.getCollectionType(tag)
1549 if collectionType is not CollectionType.TAGGED:
1550 raise TypeError(
1551 f"Cannot disassociate from collection '{tag}' "
1552 f"of non-TAGGED type {collectionType.name}."
1553 )
1554 # Transform possibly-single-pass iterable into something we can iterate
1555 # over multiple times.
1556 refs = list(refs)
1557 # Pruning a component of a DatasetRef makes no sense since registry
1558 # doesn't know about components and datastore might not store
1559 # components in a separate file
1560 for ref in refs:
1561 if ref.datasetType.component():
1562 raise ValueError(f"Can not prune a component of a dataset (ref={ref})")
1564 # Chunk the deletions using a size that is reasonably efficient whilst
1565 # also giving reasonable feedback to the user. Chunking also minimizes
1566 # what needs to rollback if there is a failure and should allow
1567 # incremental re-running of the pruning (assuming the query is
1568 # repeated). The only issue will be if the Ctrl-C comes during
1569 # emptyTrash since an admin command would need to run to finish the
1570 # emptying of that chunk.
1571 progress = Progress("lsst.daf.butler.Butler.pruneDatasets", level=_LOG.INFO)
1572 chunk_size = 50_000
1573 n_chunks = math.ceil(len(refs) / chunk_size)
1574 if n_chunks > 1:
1575 _LOG.verbose("Pruning a total of %d datasets", len(refs))
1576 chunk_num = 0
1577 for chunked_refs in progress.wrap(
1578 chunk_iterable(refs, chunk_size=chunk_size), desc="Deleting datasets", total=n_chunks
1579 ):
1580 chunk_num += 1
1581 _LOG.verbose(
1582 "Pruning %d dataset%s in chunk %d/%d",
1583 len(chunked_refs),
1584 "s" if len(chunked_refs) != 1 else "",
1585 chunk_num,
1586 n_chunks,
1587 )
1588 with time_this(
1589 _LOG,
1590 msg="Removing %d datasets for chunk %d/%d",
1591 args=(len(chunked_refs), chunk_num, n_chunks),
1592 ):
1593 self._prune_datasets(
1594 chunked_refs, tags=tags, unstore=unstore, purge=purge, disassociate=disassociate
1595 )
1597 def _prune_datasets(
1598 self,
1599 refs: Collection[DatasetRef],
1600 *,
1601 disassociate: bool = True,
1602 unstore: bool = False,
1603 tags: Iterable[str] = (),
1604 purge: bool = False,
1605 ) -> None:
1606 # We don't need an unreliable Datastore transaction for this, because
1607 # we've been extra careful to ensure that Datastore.trash only involves
1608 # mutating the Registry (it can _look_ at Datastore-specific things,
1609 # but shouldn't change them), and hence all operations here are
1610 # Registry operations.
1611 with self.transaction():
1612 plural = "s" if len(refs) != 1 else ""
1613 if unstore:
1614 with time_this(
1615 _LOG,
1616 msg="Marking %d dataset%s for removal during pruneDatasets",
1617 args=(len(refs), plural),
1618 ):
1619 self._datastore.trash(refs)
1620 if purge:
1621 with time_this(
1622 _LOG, msg="Removing %d pruned dataset%s from registry", args=(len(refs), plural)
1623 ):
1624 self._registry.removeDatasets(refs)
1625 elif disassociate:
1626 assert tags, "Guaranteed by earlier logic in this function."
1627 with time_this(
1628 _LOG, msg="Disassociating %d dataset%ss from tagged collections", args=(len(refs), plural)
1629 ):
1630 for tag in tags:
1631 self._registry.disassociate(tag, refs)
1632 # We've exited the Registry transaction, and apparently committed.
1633 # (if there was an exception, everything rolled back, and it's as if
1634 # nothing happened - and we never get here).
1635 # Datastore artifacts are not yet gone, but they're clearly marked
1636 # as trash, so if we fail to delete now because of (e.g.) filesystem
1637 # problems we can try again later, and if manual administrative
1638 # intervention is required, it's pretty clear what that should entail:
1639 # deleting everything on disk and in private Datastore tables that is
1640 # in the dataset_location_trash table.
1641 if unstore:
1642 # Point of no return for removing artifacts. Restrict the trash
1643 # emptying to the refs that this call trashed.
1644 with time_this(
1645 _LOG,
1646 msg="Attempting to remove artifacts for %d dataset%s associated with pruning",
1647 args=(len(refs), plural),
1648 ):
1649 self._datastore.emptyTrash(refs=refs)
1651 def ingest_zip(
1652 self,
1653 zip_file: ResourcePathExpression,
1654 transfer: str = "auto",
1655 *,
1656 transfer_dimensions: bool = False,
1657 dry_run: bool = False,
1658 ) -> None:
1659 """Ingest a Zip file into this butler.
1661 The Zip file must have been created by `retrieve_artifacts_zip`.
1663 Parameters
1664 ----------
1665 zip_file : `lsst.resources.ResourcePathExpression`
1666 Path to the Zip file.
1667 transfer : `str`, optional
1668 Method to use to transfer the Zip into the datastore.
1669 transfer_dimensions : `bool`, optional
1670 If `True`, dimension record data associated with the new datasets
1671 will be transferred from the Zip, if present.
1672 dry_run : `bool`, optional
1673 If `True` the ingest will be processed without any modifications
1674 made to the target butler and as if the target butler did not
1675 have any of the datasets.
1677 Notes
1678 -----
1679 Run collections and dataset types are created as needed.
1680 """
1681 if not self.isWriteable():
1682 raise TypeError("Butler is read-only.")
1684 zip_path = ResourcePath(zip_file)
1685 index = ZipIndex.from_zip_file(zip_path)
1686 _LOG.verbose(
1687 "Ingesting %s containing %d datasets and %d files.", zip_path, len(index.refs), len(index)
1688 )
1690 # Need to ingest the refs into registry. Re-use the standard ingest
1691 # code by reconstructing FileDataset from the index.
1692 refs = index.refs.to_refs(universe=self.dimensions)
1693 id_to_ref = {ref.id: ref for ref in refs}
1694 datasets: list[FileDataset] = []
1695 processed_ids: set[uuid.UUID] = set()
1696 for path_in_zip, index_info in index.artifact_map.items():
1697 # Disassembled composites need to check this ref isn't already
1698 # included.
1699 unprocessed = {id_ for id_ in index_info.ids if id_ not in processed_ids}
1700 if not unprocessed:
1701 continue
1702 dataset = FileDataset(refs=[id_to_ref[id_] for id_ in unprocessed], path=path_in_zip)
1703 datasets.append(dataset)
1704 processed_ids.update(unprocessed)
1706 # Ingest doesn't create the RUN collections so we have to do that
1707 # here.
1708 #
1709 # Sort by run collection name to ensure Postgres takes locks in the
1710 # same order between different processes, to mitigate an issue
1711 # where Postgres can deadlock due to the unique index on collection
1712 # name. (See DM-47543).
1713 runs = {ref.run for ref in refs}
1714 for run in sorted(runs):
1715 registered = self.collections.register(run)
1716 if registered:
1717 _LOG.verbose("Created RUN collection %s as part of zip ingest", run)
1719 progress = Progress("lsst.daf.butler.Butler.ingest", level=VERBOSE)
1720 import_info = self._prepare_ingest_file_datasets(
1721 datasets, progress, dry_run=dry_run, transfer_dimensions=transfer_dimensions
1722 )
1724 with self.transaction():
1725 # Do not need expanded dataset refs so can ignore the return value.
1726 self._ingest_file_datasets(datasets, import_info, progress, dry_run=dry_run)
1728 try:
1729 self._datastore.ingest_zip(zip_path, transfer=transfer, dry_run=dry_run)
1730 except IntegrityError as e:
1731 raise ConflictingDefinitionError(
1732 f"Datastore already contains one or more datasets: {e}"
1733 ) from e
1735 def _prepare_ingest_file_datasets(
1736 self,
1737 datasets: Sequence[FileDataset],
1738 progress: Progress,
1739 *,
1740 transfer_dimensions: bool = False,
1741 dry_run: bool = False,
1742 ) -> _ImportDatasetsInfo:
1743 # Track DataIDs that are being ingested so we can spot issues early
1744 # with duplication. Retain previous FileDataset so we can report it.
1745 groupedDataIds: MutableMapping[tuple[DatasetType, str], dict[DataCoordinate, FileDataset]] = (
1746 defaultdict(dict)
1747 )
1749 # All the refs we need to import.
1750 refs: list[DatasetRef] = []
1752 for dataset in progress.wrap(datasets, desc="Validating dataIDs"):
1753 for ref in dataset.refs:
1754 group_key = (ref.datasetType, ref.run)
1756 if ref.dataId in groupedDataIds[group_key]:
1757 raise ConflictingDefinitionError(
1758 f"Ingest conflict. Dataset {dataset.path} has same"
1759 " DataId as other ingest dataset"
1760 f" {groupedDataIds[group_key][ref.dataId].path} "
1761 f" ({ref.dataId})"
1762 )
1764 groupedDataIds[group_key][ref.dataId] = dataset
1765 refs.extend(dataset.refs)
1767 # Ensure that dataset types are created and all ref information
1768 # extracted.
1769 import_info = self._prepare_for_import_refs(
1770 self,
1771 refs,
1772 register_dataset_types=True,
1773 dry_run=dry_run,
1774 transfer_dimensions=transfer_dimensions,
1775 )
1776 return import_info
1778 def _ingest_file_datasets(
1779 self,
1780 datasets: Sequence[FileDataset],
1781 import_info: _ImportDatasetsInfo,
1782 progress: Progress,
1783 *,
1784 dry_run: bool = False,
1785 ) -> None:
1786 self._import_dimension_records(import_info.dimension_records, dry_run=dry_run)
1787 imported_refs = self._import_grouped_refs(
1788 import_info.grouped_refs, None, progress, dry_run=dry_run, expand_refs=True
1789 )
1791 # The expanded refs need to be attached back to the original
1792 # FileDatasets for datastore to use.
1793 id_to_ref = {ref.id: ref for ref in imported_refs}
1795 for dataset in progress.wrap(datasets, desc="Re-attaching expanded refs"):
1796 dataset.refs = [id_to_ref[ref.id] for ref in dataset.refs]
1798 def ingest(
1799 self,
1800 *datasets: FileDataset,
1801 transfer: str | None = "auto",
1802 record_validation_info: bool = True,
1803 skip_existing: bool = False,
1804 ) -> None:
1805 # Docstring inherited.
1806 if not datasets:
1807 return
1808 if not self.isWriteable():
1809 raise TypeError("Butler is read-only.")
1810 _LOG.verbose("Ingesting %d file dataset%s.", len(datasets), "" if len(datasets) == 1 else "s")
1811 progress = Progress("lsst.daf.butler.Butler.ingest", level=VERBOSE)
1813 new_datasets, existing_datasets = self._partition_datasets_by_known(datasets)
1814 if existing_datasets:
1815 if skip_existing:
1816 _LOG.info(
1817 "Skipping %d datasets which already exist in the repository.", len(existing_datasets)
1818 )
1819 else:
1820 raise ConflictingDefinitionError(
1821 f"Datastore already contains {len(existing_datasets)} of the given datasets."
1822 f" Example: {existing_datasets[0]}"
1823 )
1825 # We use `datasets` rather `new_datasets` for the Registry
1826 # portion of this, to let it confirm that everything matches the
1827 # existing datasets.
1828 import_info = self._prepare_ingest_file_datasets(datasets, progress)
1830 with self.transaction():
1831 self._ingest_file_datasets(datasets, import_info, progress)
1833 # Bulk-insert everything into Datastore.
1834 # We do not know if any of the registry entries already existed
1835 # (_importDatasets only complains if they exist but differ).
1836 # The _partition_datasets_by_known logic above should catch most
1837 # instances where we attempt to re-ingest files that were already
1838 # ingested, but a concurrent writer could cause a unique constraint
1839 # violation here.
1840 try:
1841 self._datastore.ingest(
1842 *new_datasets, transfer=transfer, record_validation_info=record_validation_info
1843 )
1844 except IntegrityError as e:
1845 raise ConflictingDefinitionError(
1846 f"Datastore already contains one or more datasets: {e}"
1847 ) from e
1849 def _partition_datasets_by_known(
1850 self, datasets: Iterable[FileDataset]
1851 ) -> tuple[list[FileDataset], list[FileDataset]]:
1852 """Divides the given `FileDataset` objects into two groups: those for
1853 which the Datastore already has an entry, and those for which it does
1854 not.
1855 """
1856 new_datasets = []
1857 existing_datasets = []
1859 refs = itertools.chain.from_iterable(dataset.refs for dataset in datasets)
1860 known_refs = self._datastore.knows_these(refs)
1862 for dataset in datasets:
1863 if any(known_refs[ref] for ref in dataset.refs):
1864 existing_datasets.append(dataset)
1865 else:
1866 new_datasets.append(dataset)
1868 return new_datasets, existing_datasets
1870 @contextlib.contextmanager
1871 def export(
1872 self,
1873 *,
1874 directory: str | None = None,
1875 filename: str | None = None,
1876 format: str | None = None,
1877 transfer: str | None = None,
1878 ) -> Iterator[RepoExportContext]:
1879 # Docstring inherited.
1880 if directory is None and transfer is not None:
1881 raise TypeError("Cannot transfer without providing a directory.")
1882 if transfer == "move":
1883 raise TypeError("Transfer may not be 'move': export is read-only")
1884 if format is None:
1885 if filename is None:
1886 raise TypeError("At least one of 'filename' or 'format' must be provided.")
1887 else:
1888 _, format = os.path.splitext(filename)
1889 if not format:
1890 raise ValueError("Please specify a file extension to determine export format.")
1891 format = format[1:] # Strip leading ".""
1892 elif filename is None:
1893 filename = f"export.{format}"
1894 if directory is not None:
1895 filename = os.path.join(directory, filename)
1896 formats = self._config["repo_transfer_formats"]
1897 if format not in formats:
1898 raise ValueError(f"Unknown export format {format!r}, allowed: {','.join(formats.keys())}")
1899 BackendClass = get_class_of(formats[format, "export"])
1900 with open(filename, "w") as stream:
1901 backend = BackendClass(stream, universe=self.dimensions)
1902 try:
1903 helper = RepoExportContext(self, backend=backend, directory=directory, transfer=transfer)
1904 with self._caching_context():
1905 yield helper
1906 except BaseException:
1907 raise
1908 else:
1909 helper._finish()
1911 def import_(
1912 self,
1913 *,
1914 directory: ResourcePathExpression | None = None,
1915 filename: ResourcePathExpression | TextIO | None = None,
1916 format: str | None = None,
1917 transfer: str | None = None,
1918 skip_dimensions: set | None = None,
1919 record_validation_info: bool = True,
1920 without_datastore: bool = False,
1921 ) -> None:
1922 # Docstring inherited.
1923 if not self.isWriteable():
1924 raise TypeError("Butler is read-only.")
1925 if filename is None and format is not None:
1926 filename = ResourcePath(f"export.{format}", forceAbsolute=False)
1927 if directory is not None:
1928 directory = ResourcePath(directory, forceDirectory=True)
1929 # mypy doesn't think this will work but it does in python >= 3.10.
1930 if isinstance(filename, ResourcePathExpression): # type: ignore
1931 filename = ResourcePath(filename, forceAbsolute=False) # type: ignore
1932 if format is None:
1933 format = filename.getExtension()
1934 if not filename.isabs() and directory is not None:
1935 potential = directory.join(filename)
1936 exists_in_cwd = filename.exists()
1937 exists_in_dir = potential.exists()
1938 if exists_in_cwd and exists_in_dir:
1939 _LOG.warning(
1940 "A relative path for filename was specified (%s) which exists relative to cwd. "
1941 "Additionally, the file exists relative to the given search directory (%s). "
1942 "Using the export file in the given directory.",
1943 filename,
1944 potential,
1945 )
1946 # Given they specified an explicit directory and that
1947 # directory has the export file in it, assume that that
1948 # is what was meant despite the file in cwd.
1949 filename = potential
1950 elif exists_in_dir:
1951 filename = potential
1952 elif not exists_in_cwd and not exists_in_dir:
1953 # Raise early.
1954 raise FileNotFoundError(
1955 f"Export file could not be found in {filename.abspath()} or {potential.abspath()}."
1956 )
1957 elif format is None:
1958 format = ".yaml"
1959 BackendClass: type[RepoImportBackend] = get_class_of(
1960 self._config["repo_transfer_formats"][format]["import"]
1961 )
1963 def doImport(importStream: TextIO | ResourceHandleProtocol) -> None:
1964 with self._caching_context():
1965 backend = BackendClass(importStream, self) # type: ignore[call-arg]
1966 backend.register()
1967 with self.transaction():
1968 backend.load(
1969 datastore=self._datastore if not without_datastore else None,
1970 directory=directory,
1971 transfer=transfer,
1972 skip_dimensions=skip_dimensions,
1973 record_validation_info=record_validation_info,
1974 )
1976 if isinstance(filename, ResourcePath):
1977 # We can not use open() here at the moment because of
1978 # DM-38589 since yaml does stream.read(8192) in a loop.
1979 stream = io.StringIO(filename.read().decode())
1980 doImport(stream)
1981 else:
1982 doImport(filename) # type: ignore
1984 def transfer_dimension_records_from(
1985 self, source_butler: LimitedButler | Butler, source_refs: Iterable[DatasetRef]
1986 ) -> None:
1987 # Allowed dimensions in the target butler.
1988 elements = frozenset(element for element in self.dimensions.elements if element.has_own_table)
1990 data_ids = {ref.dataId for ref in source_refs}
1992 dimension_records = self._extract_all_dimension_records_from_data_ids(
1993 source_butler, data_ids, elements
1994 )
1996 # Insert order is important.
1997 for element in self.dimensions.sorted(dimension_records.keys()):
1998 records = [r for r in dimension_records[element].values()]
1999 # Assume that if the record is already present that we can
2000 # use it without having to check that the record metadata
2001 # is consistent.
2002 self._registry.insertDimensionData(element, *records, skip_existing=True)
2003 _LOG.debug("Dimension '%s' -- number of records transferred: %d", element.name, len(records))
2005 def _extract_all_dimension_records_from_data_ids(
2006 self,
2007 source_butler: LimitedButler | Butler,
2008 data_ids: set[DataCoordinate],
2009 allowed_elements: frozenset[DimensionElement],
2010 ) -> dict[DimensionElement, dict[DataCoordinate, DimensionRecord]]:
2011 primary_records = self._extract_dimension_records_from_data_ids(
2012 source_butler, data_ids, allowed_elements
2013 )
2015 can_query = True if isinstance(source_butler, Butler) else False
2017 additional_records: dict[DimensionElement, dict[DataCoordinate, DimensionRecord]] = defaultdict(dict)
2018 for original_element, record_mapping in primary_records.items():
2019 # Get dimensions that depend on this dimension.
2020 populated_by = self.dimensions.get_elements_populated_by(
2021 self.dimensions[original_element.name] # type: ignore
2022 )
2024 for data_id in record_mapping.keys():
2025 for element in populated_by:
2026 if element not in allowed_elements:
2027 continue
2028 if element.name == original_element.name:
2029 continue
2031 if element.name in primary_records:
2032 # If this element has already been stored avoid
2033 # re-finding records since that may lead to additional
2034 # spurious records. e.g. visit is populated_by
2035 # visit_detector_region but querying
2036 # visit_detector_region by visit will return all the
2037 # detectors for this visit -- the visit dataId does not
2038 # constrain this.
2039 # To constrain the query the original dataIds would
2040 # have to be scanned.
2041 continue
2043 if not can_query:
2044 raise RuntimeError(
2045 f"Transferring populated_by records like {element.name} requires a full Butler."
2046 )
2048 records = source_butler.query_dimension_records( # type: ignore
2049 element.name,
2050 explain=False,
2051 **data_id.mapping, # type: ignore
2052 )
2053 for record in records:
2054 additional_records[record.definition].setdefault(record.dataId, record)
2056 # The next step is to walk back through the additional records to
2057 # pick up any missing content (such as visit_definition needing to
2058 # know the exposure). Want to ensure we do not request records we
2059 # already have.
2060 missing_data_ids = set()
2061 for name, record_mapping in additional_records.items():
2062 for data_id in record_mapping.keys():
2063 if data_id not in primary_records[name]:
2064 missing_data_ids.add(data_id)
2066 # Fill out the new records. Assume that these new records do not
2067 # also need to carry over additional populated_by records.
2068 secondary_records = self._extract_dimension_records_from_data_ids(
2069 source_butler, missing_data_ids, allowed_elements
2070 )
2072 # Merge the extra sets of records in with the original.
2073 for name, record_mapping in itertools.chain(additional_records.items(), secondary_records.items()):
2074 primary_records[name].update(record_mapping)
2076 return primary_records
2078 def _extract_dimension_records_from_data_ids(
2079 self,
2080 source_butler: LimitedButler | Butler,
2081 data_ids: set[DataCoordinate],
2082 allowed_elements: frozenset[DimensionElement],
2083 ) -> dict[DimensionElement, dict[DataCoordinate, DimensionRecord]]:
2084 dimension_records: dict[DimensionElement, dict[DataCoordinate, DimensionRecord]] = defaultdict(dict)
2086 for data_id in data_ids:
2087 # Need an expanded record, if not expanded that we need a full
2088 # butler with registry (allow mocks with registry too).
2089 if not data_id.hasRecords():
2090 if registry := getattr(source_butler, "registry", None):
2091 data_id = registry.expandDataId(data_id)
2092 else:
2093 raise TypeError("Input butler needs to be a full butler to expand DataId.")
2094 # If this butler doesn't know about a dimension in the source
2095 # butler things will break later.
2096 for element_name in data_id.dimensions.elements:
2097 record = data_id.records[element_name]
2098 if record is not None and record.definition in allowed_elements:
2099 dimension_records[record.definition].setdefault(record.dataId, record)
2101 return dimension_records
2103 def _prepare_for_import_refs(
2104 self,
2105 source_butler: LimitedButler,
2106 source_refs: Iterable[DatasetRef],
2107 *,
2108 register_dataset_types: bool = False,
2109 transfer_dimensions: bool = False,
2110 dry_run: bool = False,
2111 ) -> _ImportDatasetsInfo:
2112 # Docstring inherited.
2113 if not self.isWriteable() and not dry_run:
2114 raise TypeError("Butler is read-only.")
2116 # Will iterate through the refs multiple times so need to convert
2117 # to a list if this isn't a collection.
2118 if not isinstance(source_refs, collections.abc.Collection):
2119 source_refs = list(source_refs)
2121 original_count = len(source_refs)
2122 log_level = _LOG.INFO if original_count > 1 else _LOG.VERBOSE
2123 _LOG.log(
2124 log_level,
2125 "Importing %d dataset%s into %s",
2126 original_count,
2127 "s" if original_count != 1 else "",
2128 str(self),
2129 )
2131 # Importing requires that we group the refs by dimension group and run
2132 # before doing the import.
2133 source_dataset_types = set()
2134 grouped_refs: defaultdict[_RefGroup, list[DatasetRef]] = defaultdict(list)
2135 for ref in source_refs:
2136 grouped_refs[_RefGroup(ref.datasetType.dimensions, ref.run)].append(ref)
2137 source_dataset_types.add(ref.datasetType)
2139 # Check to see if the dataset type in the source butler has
2140 # the same definition in the target butler and register missing
2141 # ones if requested. Registration must happen outside a transaction.
2142 newly_registered_dataset_types = set()
2143 for datasetType in source_dataset_types:
2144 if register_dataset_types:
2145 # Let this raise immediately if inconsistent. Continuing
2146 # on to find additional inconsistent dataset types
2147 # might result in additional unwanted dataset types being
2148 # registered.
2149 try:
2150 if not dry_run and self._registry.registerDatasetType(datasetType):
2151 newly_registered_dataset_types.add(datasetType)
2152 except ConflictingDefinitionError as e:
2153 # Be safe and require that conversions be bidirectional
2154 # when there are storage class mismatches. This is because
2155 # get() will have to support conversion from source to
2156 # target python type (the source formatter will be
2157 # returning source python type) but there also is an
2158 # expectation that people will want to be able to get() in
2159 # the target using the source python type, which will not
2160 # require conversion for transferred datasets but might
2161 # for target-native types. Additionally, butler.get does
2162 # not know that the formatter will return the wrong
2163 # python type and so will always check that the conversion
2164 # works even though it won't need it.
2165 target_dataset_type = self.get_dataset_type(datasetType.name)
2166 target_compatible_with_source = target_dataset_type.is_compatible_with(datasetType)
2167 source_compatible_with_target = datasetType.is_compatible_with(target_dataset_type)
2168 if not (target_compatible_with_source and source_compatible_with_target):
2169 if target_compatible_with_source:
2170 e.add_note(
2171 "Target dataset type storage class is compatible with source "
2172 "but the reverse is not true."
2173 )
2174 elif source_compatible_with_target:
2175 e.add_note(
2176 "Source dataset type storage class is compatible with target "
2177 "but the reverse is not true."
2178 )
2179 else:
2180 e.add_note("If storage classes differ, please register converters.")
2181 raise
2182 else:
2183 # If the dataset type is missing, let it fail immediately.
2184 target_dataset_type = self.get_dataset_type(datasetType.name)
2185 if target_dataset_type != datasetType:
2186 target_compatible_with_source = target_dataset_type.is_compatible_with(datasetType)
2187 source_compatible_with_target = datasetType.is_compatible_with(target_dataset_type)
2188 # Both conversion directions are currently required.
2189 if not (target_compatible_with_source and source_compatible_with_target):
2190 msg = ""
2191 if target_compatible_with_source:
2192 msg = (
2193 "Target storage class is compatible with the source storage class "
2194 "but the reverse is not true."
2195 )
2196 elif source_compatible_with_target:
2197 msg = (
2198 "Source storage class is compatible with the target storage class"
2199 " but the reverse is not true."
2200 )
2201 else:
2202 msg = "If storage classes differ register converters."
2203 if msg:
2204 msg = f"({msg})"
2205 raise ConflictingDefinitionError(
2206 "Source butler dataset type differs from definition"
2207 f" in target butler: {datasetType} !="
2208 f" {target_dataset_type} {msg}"
2209 )
2210 if newly_registered_dataset_types:
2211 # We may have registered some even if there were inconsistencies
2212 # but should let people know (or else remove them again).
2213 _LOG.verbose(
2214 "Registered the following dataset types in the target Butler: %s",
2215 ", ".join(d.name for d in newly_registered_dataset_types),
2216 )
2217 else:
2218 _LOG.verbose("All required dataset types are known to the target Butler")
2220 dimension_records: dict[DimensionElement, dict[DataCoordinate, DimensionRecord]] = defaultdict(dict)
2221 if transfer_dimensions:
2222 # Collect all the dimension records for these refs.
2223 # All dimensions are to be copied but the list of valid dimensions
2224 # come from this butler's universe.
2225 elements = frozenset(element for element in self.dimensions.elements if element.has_own_table)
2226 dataIds = {ref.dataId for ref in source_refs}
2227 dimension_records = self._extract_all_dimension_records_from_data_ids(
2228 source_butler, dataIds, elements
2229 )
2230 return _ImportDatasetsInfo(grouped_refs, dimension_records)
2232 def _import_dimension_records(
2233 self,
2234 dimension_records: dict[DimensionElement, dict[DataCoordinate, DimensionRecord]],
2235 *,
2236 dry_run: bool,
2237 ) -> None:
2238 """Import dimension records collected during import pre-process."""
2239 if dimension_records and not dry_run:
2240 _LOG.verbose("Ensuring that dimension records exist for transferred datasets.")
2241 # Order matters.
2242 for element in self.dimensions.sorted(dimension_records.keys()):
2243 records = list(dimension_records[element].values())
2244 # Assume that if the record is already present that we can
2245 # use it without having to check that the record metadata
2246 # is consistent.
2247 self._registry.insertDimensionData(element, *records, skip_existing=True)
2249 def _import_grouped_refs(
2250 self,
2251 grouped_refs: defaultdict[_RefGroup, list[DatasetRef]],
2252 source_butler: LimitedButler | None,
2253 progress: Progress,
2254 *,
2255 dry_run: bool = False,
2256 expand_refs: bool = False,
2257 ) -> list[DatasetRef]:
2258 handled_collections: set[str] = set()
2259 n_to_import = 0
2260 all_imported_refs: list[DatasetRef] = []
2261 # Sort by run collection name to ensure Postgres takes locks in the
2262 # same order between different processes, to mitigate an issue
2263 # where Postgres can deadlock due to the unique index on collection
2264 # name. (See DM-47543).
2265 groups = sorted(grouped_refs.items(), key=lambda item: item[0].run)
2266 for (dimension_group, run), refs_to_import in progress.iter_item_chunks(
2267 groups, desc="Importing to registry by run and dataset type"
2268 ):
2269 if run not in handled_collections:
2270 # May need to create output collection. If source butler
2271 # has a registry, ask for documentation string.
2272 run_doc = None
2273 if source_butler is not None and (registry := getattr(source_butler, "registry", None)):
2274 run_doc = registry.getCollectionDocumentation(run)
2275 if not dry_run:
2276 registered = self.collections.register(run, doc=run_doc)
2277 else:
2278 registered = True
2279 handled_collections.add(run)
2280 if registered:
2281 _LOG.verbose("Creating output run %s", run)
2283 n_refs = len(refs_to_import)
2284 n_to_import += n_refs
2285 _LOG.verbose(
2286 "Importing %d ref%s with dimensions %s into run %s",
2287 n_refs,
2288 "" if n_refs == 1 else "s",
2289 dimension_group.names,
2290 run,
2291 )
2293 # Assume we are using UUIDs and the source refs will match
2294 # those imported.
2295 if not dry_run:
2296 imported_refs = self._registry._importDatasets(refs_to_import, expand=expand_refs)
2297 else:
2298 imported_refs = refs_to_import
2300 all_imported_refs.extend(imported_refs)
2302 assert n_to_import == len(all_imported_refs)
2303 _LOG.verbose("Imported %d datasets into destination butler", n_to_import)
2304 return all_imported_refs
2306 def transfer_from(
2307 self,
2308 source_butler: LimitedButler,
2309 source_refs: Iterable[DatasetRef],
2310 transfer: str = "auto",
2311 skip_missing: bool = True,
2312 register_dataset_types: bool = False,
2313 transfer_dimensions: bool = False,
2314 dry_run: bool = False,
2315 ) -> collections.abc.Collection[DatasetRef]:
2316 # Docstring inherited.
2317 source_refs = list(source_refs)
2318 if not self.isWriteable() and not dry_run:
2319 raise TypeError("Butler is read-only.")
2321 progress = Progress("lsst.daf.butler.Butler.transfer_from", level=VERBOSE)
2323 artifact_existence: dict[ResourcePath, bool] = {}
2324 file_transfer_source = source_butler._file_transfer_source
2325 transfer_records = retrieve_file_transfer_records(
2326 file_transfer_source, source_refs, artifact_existence
2327 )
2328 # In some situations the datastore artifact may be missing and we do
2329 # not want that registry entry to be imported. For example, this can
2330 # happen if a file was removed but the dataset was left in the registry
2331 # for provenance, or if a pipeline task didn't create all of the
2332 # possible files in a QuantumBackedButler.
2333 if skip_missing:
2334 original_ids = {ref.id for ref in source_refs}
2335 missing_ids = original_ids - transfer_records.keys()
2336 if missing_ids:
2337 original_count = len(source_refs)
2338 source_refs = [ref for ref in source_refs if ref.id not in missing_ids]
2339 filtered_count = len(source_refs)
2340 n_missing = original_count - filtered_count
2341 _LOG.verbose(
2342 "%d dataset%s removed because the artifact does not exist. Now have %d.",
2343 n_missing,
2344 "" if n_missing == 1 else "s",
2345 filtered_count,
2346 )
2348 import_info = self._prepare_for_import_refs(
2349 source_butler,
2350 source_refs,
2351 register_dataset_types=register_dataset_types,
2352 dry_run=dry_run,
2353 transfer_dimensions=transfer_dimensions,
2354 )
2356 # Do all the importing in a single transaction.
2357 with self.transaction():
2358 self._import_dimension_records(import_info.dimension_records, dry_run=dry_run)
2359 imported_refs = self._import_grouped_refs(
2360 import_info.grouped_refs, source_butler, progress, dry_run=dry_run
2361 )
2363 # Ask the datastore to transfer. The datastore has to check that
2364 # the source datastore is compatible with the target datastore.
2365 _LOG.verbose("Transferring %d datasets from %s", len(transfer_records), file_transfer_source.name)
2366 accepted, rejected = self._datastore.transfer_from(
2367 transfer_records,
2368 imported_refs,
2369 transfer=transfer,
2370 artifact_existence=artifact_existence,
2371 dry_run=dry_run,
2372 )
2373 if rejected:
2374 # For now, accept the registry entries but not the files.
2375 _LOG.warning(
2376 "%d datasets were rejected and %d accepted for transfer.",
2377 len(rejected),
2378 len(accepted),
2379 )
2381 return imported_refs
2383 def validateConfiguration(
2384 self,
2385 logFailures: bool = False,
2386 datasetTypeNames: Iterable[str] | None = None,
2387 ignore: Iterable[str] | None = None,
2388 ) -> None:
2389 # Docstring inherited.
2390 if datasetTypeNames:
2391 datasetTypes = [self.get_dataset_type(name) for name in datasetTypeNames]
2392 else:
2393 datasetTypes = list(self._registry.queryDatasetTypes())
2395 # filter out anything from the ignore list
2396 if ignore:
2397 ignore = set(ignore)
2398 datasetTypes = [
2399 e for e in datasetTypes if e.name not in ignore and e.nameAndComponent()[0] not in ignore
2400 ]
2401 else:
2402 ignore = set()
2404 # For each datasetType that has an instrument dimension, create
2405 # a DatasetRef for each defined instrument
2406 datasetRefs = []
2408 # Find all the registered instruments (if "instrument" is in the
2409 # universe).
2410 instruments: set[str] = set()
2411 if "instrument" in self.dimensions:
2412 instruments = {rec.name for rec in self.query_dimension_records("instrument", explain=False)}
2414 for datasetType in datasetTypes:
2415 if "instrument" in datasetType.dimensions:
2416 # In order to create a conforming dataset ref, create
2417 # fake DataCoordinate values for the non-instrument
2418 # dimensions. The type of the value does not matter here.
2419 dataId = {dim: 1 for dim in datasetType.dimensions.names if dim != "instrument"}
2421 for instrument in instruments:
2422 datasetRef = DatasetRef(
2423 datasetType,
2424 DataCoordinate.standardize(
2425 dataId, instrument=instrument, dimensions=datasetType.dimensions
2426 ),
2427 run="validate",
2428 )
2429 datasetRefs.append(datasetRef)
2431 entities: list[DatasetType | DatasetRef] = []
2432 entities.extend(datasetTypes)
2433 entities.extend(datasetRefs)
2435 datastoreErrorStr = None
2436 try:
2437 self._datastore.validateConfiguration(entities, logFailures=logFailures)
2438 except ValidationError as e:
2439 datastoreErrorStr = str(e)
2441 # Also check that the LookupKeys used by the datastores match
2442 # registry and storage class definitions
2443 keys = self._datastore.getLookupKeys()
2445 failedNames = set()
2446 failedDataId = set()
2447 for key in keys:
2448 if key.name is not None:
2449 if key.name in ignore:
2450 continue
2452 # skip if specific datasetType names were requested and this
2453 # name does not match
2454 if datasetTypeNames and key.name not in datasetTypeNames:
2455 continue
2457 # See if it is a StorageClass or a DatasetType
2458 if key.name in self.storageClasses:
2459 pass
2460 else:
2461 try:
2462 self.get_dataset_type(key.name)
2463 except KeyError:
2464 if logFailures:
2465 _LOG.critical(
2466 "Key '%s' does not correspond to a DatasetType or StorageClass", key
2467 )
2468 failedNames.add(key)
2469 else:
2470 # Dimensions are checked for consistency when the Butler
2471 # is created and rendezvoused with a universe.
2472 pass
2474 # Check that the instrument is a valid instrument
2475 # Currently only support instrument so check for that
2476 if key.dataId:
2477 dataIdKeys = set(key.dataId)
2478 if {"instrument"} != dataIdKeys:
2479 if logFailures:
2480 _LOG.critical("Key '%s' has unsupported DataId override", key)
2481 failedDataId.add(key)
2482 elif key.dataId["instrument"] not in instruments:
2483 if logFailures:
2484 _LOG.critical("Key '%s' has unknown instrument", key)
2485 failedDataId.add(key)
2487 messages = []
2489 if datastoreErrorStr:
2490 messages.append(datastoreErrorStr)
2492 for failed, msg in (
2493 (failedNames, "Keys without corresponding DatasetType or StorageClass entry: "),
2494 (failedDataId, "Keys with bad DataId entries: "),
2495 ):
2496 if failed:
2497 msg += ", ".join(str(k) for k in failed)
2498 messages.append(msg)
2500 if messages:
2501 raise ValidationError(";\n".join(messages))
2503 @property
2504 @deprecated(
2505 "Please use 'collections' instead. collection_chains will be removed after v28.",
2506 version="v28",
2507 category=FutureWarning,
2508 )
2509 def collection_chains(self) -> DirectButlerCollections:
2510 """Object with methods for modifying collection chains."""
2511 return DirectButlerCollections(self._registry)
2513 @property
2514 def collections(self) -> DirectButlerCollections:
2515 """Object with methods for modifying and inspecting collections."""
2516 return DirectButlerCollections(self._registry)
2518 @property
2519 def run(self) -> str | None:
2520 """Name of the run this butler writes outputs to by default (`str` or
2521 `None`).
2523 This is an alias for ``self.registry.defaults.run``. It cannot be set
2524 directly in isolation, but all defaults may be changed together by
2525 assigning a new `RegistryDefaults` instance to
2526 ``self.registry.defaults``.
2527 """
2528 return self._registry.defaults.run
2530 @property
2531 def registry(self) -> Registry:
2532 """The object that manages dataset metadata and relationships
2533 (`Registry`).
2535 Many operations that don't involve reading or writing butler datasets
2536 are accessible only via `Registry` methods. Eventually these methods
2537 will be replaced by equivalent `Butler` methods.
2538 """
2539 return RegistryShim(self)
2541 @property
2542 def dimensions(self) -> DimensionUniverse:
2543 # Docstring inherited.
2544 return self._registry.dimensions
2546 def query(self) -> contextlib.AbstractContextManager[Query]:
2547 # Docstring inherited.
2548 return self._registry._query()
2550 def _query_driver(
2551 self,
2552 default_collections: Iterable[str],
2553 default_data_id: DataCoordinate,
2554 ) -> contextlib.AbstractContextManager[DirectQueryDriver]:
2555 """Set up a QueryDriver instance for use with this Butler. Although
2556 this is marked as a private method, it is also used by Butler server.
2557 """
2558 return self._registry._query_driver(default_collections, default_data_id)
2560 @contextlib.contextmanager
2561 def _query_all_datasets_by_page(
2562 self, args: QueryAllDatasetsParameters
2563 ) -> Iterator[Iterator[list[DatasetRef]]]:
2564 with self.query() as query:
2565 pages = query_all_datasets(self, query, args)
2566 yield iter(page.data for page in pages)
2568 def _preload_cache(self, *, load_dimension_record_cache: bool = True) -> None:
2569 """Immediately load caches that are used for common operations."""
2570 self._registry.preload_cache(load_dimension_record_cache=load_dimension_record_cache)
2572 _config: ButlerConfig
2573 """Configuration for this Butler instance."""
2575 _registry: SqlRegistry
2576 """The object that manages dataset metadata and relationships
2577 (`SqlRegistry`).
2579 Most operations that don't involve reading or writing butler datasets are
2580 accessible only via `SqlRegistry` methods.
2581 """
2583 storageClasses: StorageClassFactory
2584 """An object that maps known storage class names to objects that fully
2585 describe them (`StorageClassFactory`).
2586 """
2588 _closed: bool
2589 """`True` if close() has already been called on this instance; `False`
2590 otherwise.
2591 """
2594class _RefGroup(NamedTuple):
2595 """Key identifying a batch of DatasetRefs to be inserted in
2596 `Butler.transfer_from`.
2597 """
2599 dimensions: DimensionGroup
2600 run: str
2603class _ImportDatasetsInfo(NamedTuple):
2604 """Information extracted from datasets to be imported."""
2606 grouped_refs: defaultdict[_RefGroup, list[DatasetRef]]
2607 dimension_records: dict[DimensionElement, dict[DataCoordinate, DimensionRecord]]
2610def _to_uuid(id: DatasetId | str) -> uuid.UUID:
2611 if isinstance(id, uuid.UUID):
2612 return id
2613 else:
2614 return uuid.UUID(id)
2617class _ButlerClosed:
2618 def __getattr__(self, name: str) -> Any:
2619 raise RuntimeError("Attempted to use a Butler instance which has been closed.")
2622_BUTLER_CLOSED_INSTANCE: Any = _ButlerClosed()
2625def _retrieve_dataset_type(registry: SqlRegistry, name: str) -> DatasetType | None:
2626 """Return DatasetType defined in registry given dataset type name."""
2627 try:
2628 return registry.getDatasetType(name)
2629 except MissingDatasetTypeError:
2630 return None