Coverage for python/lsst/daf/butler/transfers/_yaml.py: 14%
208 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-01 11:00 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-01 11:00 +0000
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/>.
28from __future__ import annotations
30__all__ = ["YamlRepoExportBackend", "YamlRepoImportBackend"]
32import uuid
33import warnings
34from collections import UserDict, defaultdict
35from collections.abc import Iterable, Mapping
36from datetime import datetime
37from typing import IO, TYPE_CHECKING, Any
39import astropy.time
40import yaml
41from lsst.resources import ResourcePath
42from lsst.utils import doImportType
43from lsst.utils.introspection import find_outside_stacklevel
44from lsst.utils.iteration import ensure_iterable
46from .._dataset_association import DatasetAssociation
47from .._dataset_ref import DatasetId, DatasetRef
48from .._dataset_type import DatasetType
49from .._file_dataset import FileDataset
50from .._named import NamedValueSet
51from .._timespan import Timespan
52from ..datastore import Datastore
53from ..dimensions import DimensionElement, DimensionRecord, DimensionUniverse
54from ..registry import CollectionType
55from ..registry.interfaces import ChainedCollectionRecord, CollectionRecord, RunRecord, VersionTuple
56from ..registry.sql_registry import SqlRegistry
57from ..registry.versions import IncompatibleVersionError
58from ._interfaces import RepoExportBackend, RepoImportBackend
60if TYPE_CHECKING:
61 from lsst.resources import ResourcePathExpression
63EXPORT_FORMAT_VERSION = VersionTuple(1, 0, 2)
64"""Export format version.
66Files with a different major version or a newer minor version cannot be read by
67this version of the code.
68"""
71class _RefMapper(UserDict[int, uuid.UUID]):
72 """Create a local dict subclass which creates new deterministic UUID for
73 missing keys.
74 """
76 _namespace = uuid.UUID("4d4851f4-2890-4d41-8779-5f38a3f5062b")
78 def __missing__(self, key: int) -> uuid.UUID:
79 newUUID = uuid.uuid3(namespace=self._namespace, name=str(key))
80 self[key] = newUUID
81 return newUUID
84_refIntId2UUID = _RefMapper()
87def _uuid_representer(dumper: yaml.Dumper, data: uuid.UUID) -> yaml.Node:
88 """Generate YAML representation for UUID.
90 This produces a scalar node with a tag "!uuid" and value being a regular
91 string representation of UUID.
92 """
93 return dumper.represent_scalar("!uuid", str(data))
96def _uuid_constructor(loader: yaml.Loader, node: yaml.Node) -> uuid.UUID | None:
97 if node.value is not None:
98 return uuid.UUID(hex=node.value)
99 return None
102yaml.Dumper.add_representer(uuid.UUID, _uuid_representer)
103yaml.SafeLoader.add_constructor("!uuid", _uuid_constructor)
106class YamlRepoExportBackend(RepoExportBackend):
107 """A repository export implementation that saves to a YAML file.
109 Parameters
110 ----------
111 stream
112 A writeable file-like object.
113 """
115 def __init__(self, stream: IO, universe: DimensionUniverse):
116 self.stream = stream
117 self.universe = universe
118 self.data: list[dict[str, Any]] = []
120 def saveDimensionData(self, element: DimensionElement, *data: DimensionRecord) -> None:
121 # Docstring inherited from RepoExportBackend.saveDimensionData.
122 data_dicts = [record.toDict(splitTimespan=True) for record in data]
123 self.data.append(
124 {
125 "type": "dimension",
126 "element": element.name,
127 "records": data_dicts,
128 }
129 )
131 def saveCollection(self, record: CollectionRecord, doc: str | None) -> None:
132 # Docstring inherited from RepoExportBackend.saveCollections.
133 data: dict[str, Any] = {
134 "type": "collection",
135 "collection_type": record.type.name,
136 "name": record.name,
137 }
138 if doc is not None:
139 data["doc"] = doc
140 if isinstance(record, RunRecord):
141 data["host"] = record.host
142 data["timespan_begin"] = record.timespan.begin
143 data["timespan_end"] = record.timespan.end
144 elif isinstance(record, ChainedCollectionRecord):
145 data["children"] = list(record.children)
146 self.data.append(data)
148 def saveDatasets(self, datasetType: DatasetType, run: str, *datasets: FileDataset) -> None:
149 # Docstring inherited from RepoExportBackend.saveDatasets.
150 self.data.append(
151 {
152 "type": "dataset_type",
153 "name": datasetType.name,
154 "dimensions": list(datasetType.dimensions.names),
155 "storage_class": datasetType.storageClass_name,
156 "is_calibration": datasetType.isCalibration(),
157 }
158 )
159 self.data.append(
160 {
161 "type": "dataset",
162 "dataset_type": datasetType.name,
163 "run": run,
164 "records": [
165 {
166 "dataset_id": [ref.id for ref in sorted(dataset.refs)],
167 "data_id": [dict(ref.dataId.required) for ref in sorted(dataset.refs)],
168 "path": dataset.path,
169 "formatter": dataset.formatter,
170 # TODO: look up and save other collections
171 }
172 for dataset in datasets
173 ],
174 }
175 )
177 def saveDatasetAssociations(
178 self, collection: str, collectionType: CollectionType, associations: Iterable[DatasetAssociation]
179 ) -> None:
180 # Docstring inherited from RepoExportBackend.saveDatasetAssociations.
181 if collectionType is CollectionType.TAGGED:
182 self.data.append(
183 {
184 "type": "associations",
185 "collection": collection,
186 "collection_type": collectionType.name,
187 "dataset_ids": [assoc.ref.id for assoc in associations],
188 }
189 )
190 elif collectionType is CollectionType.CALIBRATION:
191 idsByTimespan: dict[Timespan, list[DatasetId]] = defaultdict(list)
192 for association in associations:
193 assert association.timespan is not None
194 idsByTimespan[association.timespan].append(association.ref.id)
195 self.data.append(
196 {
197 "type": "associations",
198 "collection": collection,
199 "collection_type": collectionType.name,
200 "validity_ranges": [
201 {
202 "timespan": timespan,
203 "dataset_ids": dataset_ids,
204 }
205 for timespan, dataset_ids in idsByTimespan.items()
206 ],
207 }
208 )
210 def finish(self) -> None:
211 # Docstring inherited from RepoExportBackend.
212 yaml.dump(
213 {
214 "description": "Butler Data Repository Export",
215 "version": str(EXPORT_FORMAT_VERSION),
216 "universe_version": self.universe.version,
217 "universe_namespace": self.universe.namespace,
218 "data": self.data,
219 },
220 stream=self.stream,
221 sort_keys=False,
222 )
225class YamlRepoImportBackend(RepoImportBackend):
226 """A repository import implementation that reads from a YAML file.
228 Parameters
229 ----------
230 stream
231 A readable file-like object.
232 registry : `SqlRegistry`
233 The registry datasets will be imported into. Only used to retreive
234 dataset types during construction; all write happen in `register`
235 and `load`.
236 """
238 def __init__(self, stream: IO, registry: SqlRegistry):
239 # We read the file fully and convert its contents to Python objects
240 # instead of loading incrementally so we can spot some problems early;
241 # because `register` can't be put inside a transaction, we'd rather not
242 # run that at all if there's going to be problem later in `load`.
243 wrapper = yaml.safe_load(stream)
244 if wrapper["version"] == 0:
245 # Grandfather-in 'version: 0' -> 1.0.0, which is what we wrote
246 # before we really tried to do versioning here.
247 fileVersion = VersionTuple(1, 0, 0)
248 else:
249 fileVersion = VersionTuple.fromString(wrapper["version"])
250 if fileVersion.major != EXPORT_FORMAT_VERSION.major:
251 raise IncompatibleVersionError(
252 f"Cannot read repository export file with version={fileVersion} "
253 f"({EXPORT_FORMAT_VERSION.major}.x.x required)."
254 )
255 if fileVersion.minor > EXPORT_FORMAT_VERSION.minor:
256 raise IncompatibleVersionError(
257 f"Cannot read repository export file with version={fileVersion} "
258 f"< {EXPORT_FORMAT_VERSION.major}.{EXPORT_FORMAT_VERSION.minor}.x required."
259 )
260 self.runs: dict[str, tuple[str | None, Timespan]] = {}
261 self.chains: dict[str, list[str]] = {}
262 self.collections: dict[str, CollectionType] = {}
263 self.collectionDocs: dict[str, str] = {}
264 self.datasetTypes: NamedValueSet[DatasetType] = NamedValueSet()
265 self.dimensions: Mapping[DimensionElement, list[DimensionRecord]] = defaultdict(list)
266 self.tagAssociations: dict[str, list[DatasetId]] = defaultdict(list)
267 self.calibAssociations: dict[str, dict[Timespan, list[DatasetId]]] = defaultdict(dict)
268 self.refsByFileId: dict[DatasetId, DatasetRef] = {}
269 self.registry: SqlRegistry = registry
271 universe_version = wrapper.get("universe_version", 0)
272 universe_namespace = wrapper.get("universe_namespace", "daf_butler")
274 # If this is data exported before the reorganization of visits
275 # and visit systems and that new schema is in use, some filtering
276 # will be needed. The entry in the visit dimension record will be
277 # silently dropped when visit is created but the
278 # visit_system_membership must be constructed.
279 migrate_visit_system = False
280 if (
281 universe_version < 2
282 and universe_namespace == "daf_butler"
283 and "visit_system_membership" in self.registry.dimensions
284 ):
285 migrate_visit_system = True
287 # Drop "seeing" from visits in files older than version 1.
288 migrate_visit_seeing = False
289 if (
290 universe_version < 1
291 and universe_namespace == "daf_butler"
292 and "visit" in self.registry.dimensions
293 and "seeing" not in self.registry.dimensions["visit"].metadata
294 ):
295 migrate_visit_seeing = True
297 datasetData = []
298 RecordClass: type[DimensionRecord]
299 for data in wrapper["data"]:
300 if data["type"] == "dimension":
301 # convert all datetime values to astropy
302 for record in data["records"]:
303 for key in record:
304 # Some older YAML files were produced with native
305 # YAML support for datetime, we support reading that
306 # data back. Newer conversion uses _AstropyTimeToYAML
307 # class with special YAML tag.
308 if isinstance(record[key], datetime):
309 record[key] = astropy.time.Time(record[key], scale="utc")
311 if data["element"] == "visit":
312 if migrate_visit_system:
313 # Must create the visit_system_membership records.
314 # But first create empty list for visits since other
315 # logic in this file depends on self.dimensions being
316 # populated in an order consisteny with primary keys.
317 self.dimensions[self.registry.dimensions["visit"]] = []
318 element = self.registry.dimensions["visit_system_membership"]
319 RecordClass = element.RecordClass
320 self.dimensions[element].extend(
321 RecordClass(
322 instrument=r["instrument"], visit_system=r.pop("visit_system"), visit=r["id"]
323 )
324 for r in data["records"]
325 )
326 if migrate_visit_seeing:
327 for record in data["records"]:
328 record.pop("seeing", None)
330 element = self.registry.dimensions[data["element"]]
331 RecordClass = element.RecordClass
332 self.dimensions[element].extend(RecordClass(**r) for r in data["records"])
334 elif data["type"] == "collection":
335 collectionType = CollectionType.from_name(data["collection_type"])
336 if collectionType is CollectionType.RUN:
337 self.runs[data["name"]] = (
338 data["host"],
339 Timespan(begin=data["timespan_begin"], end=data["timespan_end"]),
340 )
341 elif collectionType is CollectionType.CHAINED:
342 children = []
343 for child in data["children"]:
344 if not isinstance(child, str):
345 warnings.warn(
346 f"CHAINED collection {data['name']} includes restrictions on child "
347 "collection searches, which are no longer suppored and will be ignored.",
348 stacklevel=find_outside_stacklevel("lsst.daf.butler"),
349 )
350 # Old form with dataset type restrictions only,
351 # supported for backwards compatibility.
352 child, _ = child
353 children.append(child)
354 self.chains[data["name"]] = children
355 else:
356 self.collections[data["name"]] = collectionType
357 doc = data.get("doc")
358 if doc is not None:
359 self.collectionDocs[data["name"]] = doc
360 elif data["type"] == "run":
361 # Also support old form of saving a run with no extra info.
362 self.runs[data["name"]] = (None, Timespan(None, None))
363 elif data["type"] == "dataset_type":
364 dimensions = data["dimensions"]
365 if migrate_visit_system and "visit" in dimensions and "visit_system" in dimensions:
366 dimensions.remove("visit_system")
367 self.datasetTypes.add(
368 DatasetType(
369 data["name"],
370 dimensions=dimensions,
371 storageClass=data["storage_class"],
372 universe=self.registry.dimensions,
373 isCalibration=data.get("is_calibration", False),
374 )
375 )
376 elif data["type"] == "dataset":
377 # Save raw dataset data for a second loop, so we can ensure we
378 # know about all dataset types first.
379 datasetData.append(data)
380 elif data["type"] == "associations":
381 collectionType = CollectionType.from_name(data["collection_type"])
382 if collectionType is CollectionType.TAGGED:
383 self.tagAssociations[data["collection"]].extend(
384 [x if not isinstance(x, int) else _refIntId2UUID[x] for x in data["dataset_ids"]]
385 )
386 elif collectionType is CollectionType.CALIBRATION:
387 assocsByTimespan = self.calibAssociations[data["collection"]]
388 for d in data["validity_ranges"]:
389 if "timespan" in d:
390 assocsByTimespan[d["timespan"]] = [
391 x if not isinstance(x, int) else _refIntId2UUID[x] for x in d["dataset_ids"]
392 ]
393 else:
394 # TODO: this is for backward compatibility, should
395 # be removed at some point.
396 assocsByTimespan[Timespan(begin=d["begin"], end=d["end"])] = [
397 x if not isinstance(x, int) else _refIntId2UUID[x] for x in d["dataset_ids"]
398 ]
399 else:
400 raise ValueError(f"Unexpected calibration type for association: {collectionType.name}.")
401 else:
402 raise ValueError(f"Unexpected dictionary type: {data['type']}.")
403 # key is (dataset type name, run)
404 self.datasets: Mapping[tuple[str, str], list[FileDataset]] = defaultdict(list)
405 for data in datasetData:
406 datasetType = self.datasetTypes.get(data["dataset_type"])
407 if datasetType is None:
408 datasetType = self.registry.getDatasetType(data["dataset_type"])
409 self.datasets[data["dataset_type"], data["run"]].extend(
410 FileDataset(
411 d.get("path"),
412 [
413 DatasetRef(
414 datasetType,
415 dataId,
416 run=data["run"],
417 id=refid if not isinstance(refid, int) else _refIntId2UUID[refid],
418 )
419 for dataId, refid in zip(
420 ensure_iterable(d["data_id"]), ensure_iterable(d["dataset_id"]), strict=True
421 )
422 ],
423 formatter=doImportType(d.get("formatter")) if "formatter" in d else None,
424 )
425 for d in data["records"]
426 )
428 def register(self) -> None:
429 # Docstring inherited from RepoImportBackend.register.
430 for datasetType in self.datasetTypes:
431 self.registry.registerDatasetType(datasetType)
432 for run in self.runs:
433 self.registry.registerRun(run, doc=self.collectionDocs.get(run))
434 # No way to add extra run info to registry yet.
435 for collection, collection_type in self.collections.items():
436 self.registry.registerCollection(
437 collection, collection_type, doc=self.collectionDocs.get(collection)
438 )
439 for chain, children in self.chains.items():
440 self.registry.registerCollection(
441 chain, CollectionType.CHAINED, doc=self.collectionDocs.get(chain)
442 )
443 self.registry.setCollectionChain(chain, children)
445 def load(
446 self,
447 datastore: Datastore | None,
448 *,
449 directory: ResourcePathExpression | None = None,
450 transfer: str | None = None,
451 skip_dimensions: set | None = None,
452 ) -> None:
453 # Docstring inherited from RepoImportBackend.load.
454 for element, dimensionRecords in self.dimensions.items():
455 if skip_dimensions and element in skip_dimensions:
456 continue
457 # Using skip_existing=True here assumes that the records in the
458 # database are either equivalent or at least preferable to the ones
459 # being imported. It'd be ideal to check that, but that would mean
460 # using syncDimensionData, which is not vectorized and is hence
461 # unacceptably slo.
462 self.registry.insertDimensionData(element, *dimensionRecords, skip_existing=True)
463 # FileDatasets to ingest into the datastore (in bulk):
464 fileDatasets = []
465 for records in self.datasets.values():
466 # Make a big flattened list of all data IDs and dataset_ids, while
467 # remembering slices that associate them with the FileDataset
468 # instances they came from.
469 datasets: list[DatasetRef] = []
470 dataset_ids: list[DatasetId] = []
471 slices = []
472 for fileDataset in records:
473 start = len(datasets)
474 datasets.extend(fileDataset.refs)
475 dataset_ids.extend(ref.id for ref in fileDataset.refs)
476 stop = len(datasets)
477 slices.append(slice(start, stop))
478 # Insert all of those DatasetRefs at once.
479 # For now, we ignore the dataset_id we pulled from the file
480 # and just insert without one to get a new autoincrement value.
481 # Eventually (once we have origin in IDs) we'll preserve them.
482 resolvedRefs = self.registry._importDatasets(datasets)
483 # Populate our dictionary that maps int dataset_id values from the
484 # export file to the new DatasetRefs
485 for fileId, ref in zip(dataset_ids, resolvedRefs, strict=True):
486 self.refsByFileId[fileId] = ref
487 # Now iterate over the original records, and install the new
488 # resolved DatasetRefs to replace the unresolved ones as we
489 # reorganize the collection information.
490 for sliceForFileDataset, fileDataset in zip(slices, records, strict=True):
491 fileDataset.refs = resolvedRefs[sliceForFileDataset]
492 if directory is not None:
493 fileDataset.path = ResourcePath(directory, forceDirectory=True).join(fileDataset.path)
494 fileDatasets.append(fileDataset)
495 # Ingest everything into the datastore at once.
496 if datastore is not None and fileDatasets:
497 datastore.ingest(*fileDatasets, transfer=transfer)
498 # Associate datasets with tagged collections.
499 for collection, dataset_ids in self.tagAssociations.items():
500 self.registry.associate(collection, [self.refsByFileId[i] for i in dataset_ids])
501 # Associate datasets with calibration collections.
502 for collection, idsByTimespan in self.calibAssociations.items():
503 for timespan, dataset_ids in idsByTimespan.items():
504 self.registry.certify(collection, [self.refsByFileId[i] for i in dataset_ids], timespan)