Coverage for python/lsst/daf/butler/transfers/_yaml.py: 12%
184 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-08 05:05 -0700
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-08 05:05 -0700
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 program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
22from __future__ import annotations
24__all__ = ["YamlRepoExportBackend", "YamlRepoImportBackend"]
26import uuid
27import warnings
28from collections import defaultdict
29from datetime import datetime
30from typing import IO, TYPE_CHECKING, Any, Dict, Iterable, List, Mapping, Optional, Set, Tuple, Type
32import astropy.time
33import yaml
34from lsst.resources import ResourcePath
35from lsst.utils import doImportType
36from lsst.utils.iteration import ensure_iterable
38from ..core import (
39 DatasetAssociation,
40 DatasetId,
41 DatasetRef,
42 DatasetType,
43 Datastore,
44 DimensionElement,
45 DimensionRecord,
46 DimensionUniverse,
47 FileDataset,
48 Timespan,
49)
50from ..core.named import NamedValueSet
51from ..registry import CollectionType, Registry
52from ..registry.interfaces import ChainedCollectionRecord, CollectionRecord, RunRecord, VersionTuple
53from ..registry.versions import IncompatibleVersionError
54from ._interfaces import RepoExportBackend, RepoImportBackend
56if TYPE_CHECKING:
57 from lsst.resources import ResourcePathExpression
59EXPORT_FORMAT_VERSION = VersionTuple(1, 0, 2)
60"""Export format version.
62Files with a different major version or a newer minor version cannot be read by
63this version of the code.
64"""
67def _uuid_representer(dumper: yaml.Dumper, data: uuid.UUID) -> yaml.Node:
68 """Generate YAML representation for UUID.
70 This produces a scalar node with a tag "!uuid" and value being a regular
71 string representation of UUID.
72 """
73 return dumper.represent_scalar("!uuid", str(data))
76def _uuid_constructor(loader: yaml.Loader, node: yaml.Node) -> Optional[uuid.UUID]:
77 if node.value is not None:
78 return uuid.UUID(hex=node.value)
79 return None
82yaml.Dumper.add_representer(uuid.UUID, _uuid_representer)
83yaml.SafeLoader.add_constructor("!uuid", _uuid_constructor)
86class YamlRepoExportBackend(RepoExportBackend):
87 """A repository export implementation that saves to a YAML file.
89 Parameters
90 ----------
91 stream
92 A writeable file-like object.
93 """
95 def __init__(self, stream: IO, universe: DimensionUniverse):
96 self.stream = stream
97 self.universe = universe
98 self.data: List[Dict[str, Any]] = []
100 def saveDimensionData(self, element: DimensionElement, *data: DimensionRecord) -> None:
101 # Docstring inherited from RepoExportBackend.saveDimensionData.
102 data_dicts = [record.toDict(splitTimespan=True) for record in data]
103 self.data.append(
104 {
105 "type": "dimension",
106 "element": element.name,
107 "records": data_dicts,
108 }
109 )
111 def saveCollection(self, record: CollectionRecord, doc: Optional[str]) -> None:
112 # Docstring inherited from RepoExportBackend.saveCollections.
113 data: Dict[str, Any] = {
114 "type": "collection",
115 "collection_type": record.type.name,
116 "name": record.name,
117 }
118 if doc is not None:
119 data["doc"] = doc
120 if isinstance(record, RunRecord):
121 data["host"] = record.host
122 data["timespan_begin"] = record.timespan.begin
123 data["timespan_end"] = record.timespan.end
124 elif isinstance(record, ChainedCollectionRecord):
125 data["children"] = list(record.children)
126 self.data.append(data)
128 def saveDatasets(self, datasetType: DatasetType, run: str, *datasets: FileDataset) -> None:
129 # Docstring inherited from RepoExportBackend.saveDatasets.
130 self.data.append(
131 {
132 "type": "dataset_type",
133 "name": datasetType.name,
134 "dimensions": [d.name for d in datasetType.dimensions],
135 "storage_class": datasetType.storageClass_name,
136 "is_calibration": datasetType.isCalibration(),
137 }
138 )
139 self.data.append(
140 {
141 "type": "dataset",
142 "dataset_type": datasetType.name,
143 "run": run,
144 "records": [
145 {
146 "dataset_id": [ref.id for ref in sorted(dataset.refs)],
147 "data_id": [ref.dataId.byName() for ref in sorted(dataset.refs)],
148 "path": dataset.path,
149 "formatter": dataset.formatter,
150 # TODO: look up and save other collections
151 }
152 for dataset in datasets
153 ],
154 }
155 )
157 def saveDatasetAssociations(
158 self, collection: str, collectionType: CollectionType, associations: Iterable[DatasetAssociation]
159 ) -> None:
160 # Docstring inherited from RepoExportBackend.saveDatasetAssociations.
161 if collectionType is CollectionType.TAGGED:
162 self.data.append(
163 {
164 "type": "associations",
165 "collection": collection,
166 "collection_type": collectionType.name,
167 "dataset_ids": [assoc.ref.id for assoc in associations],
168 }
169 )
170 elif collectionType is CollectionType.CALIBRATION:
171 idsByTimespan: Dict[Timespan, List[DatasetId]] = defaultdict(list)
172 for association in associations:
173 assert association.timespan is not None
174 idsByTimespan[association.timespan].append(association.ref.id)
175 self.data.append(
176 {
177 "type": "associations",
178 "collection": collection,
179 "collection_type": collectionType.name,
180 "validity_ranges": [
181 {
182 "timespan": timespan,
183 "dataset_ids": dataset_ids,
184 }
185 for timespan, dataset_ids in idsByTimespan.items()
186 ],
187 }
188 )
190 def finish(self) -> None:
191 # Docstring inherited from RepoExportBackend.
192 yaml.dump(
193 {
194 "description": "Butler Data Repository Export",
195 "version": str(EXPORT_FORMAT_VERSION),
196 "universe_version": self.universe.version,
197 "universe_namespace": self.universe.namespace,
198 "data": self.data,
199 },
200 stream=self.stream,
201 sort_keys=False,
202 )
205class YamlRepoImportBackend(RepoImportBackend):
206 """A repository import implementation that reads from a YAML file.
208 Parameters
209 ----------
210 stream
211 A readable file-like object.
212 registry : `Registry`
213 The registry datasets will be imported into. Only used to retreive
214 dataset types during construction; all write happen in `register`
215 and `load`.
216 """
218 def __init__(self, stream: IO, registry: Registry):
219 # We read the file fully and convert its contents to Python objects
220 # instead of loading incrementally so we can spot some problems early;
221 # because `register` can't be put inside a transaction, we'd rather not
222 # run that at all if there's going to be problem later in `load`.
223 wrapper = yaml.safe_load(stream)
224 if wrapper["version"] == 0:
225 # Grandfather-in 'version: 0' -> 1.0.0, which is what we wrote
226 # before we really tried to do versioning here.
227 fileVersion = VersionTuple(1, 0, 0)
228 else:
229 fileVersion = VersionTuple.fromString(wrapper["version"])
230 if fileVersion.major != EXPORT_FORMAT_VERSION.major:
231 raise IncompatibleVersionError(
232 f"Cannot read repository export file with version={fileVersion} "
233 f"({EXPORT_FORMAT_VERSION.major}.x.x required)."
234 )
235 if fileVersion.minor > EXPORT_FORMAT_VERSION.minor:
236 raise IncompatibleVersionError(
237 f"Cannot read repository export file with version={fileVersion} "
238 f"< {EXPORT_FORMAT_VERSION.major}.{EXPORT_FORMAT_VERSION.minor}.x required."
239 )
240 self.runs: Dict[str, Tuple[Optional[str], Timespan]] = {}
241 self.chains: Dict[str, List[str]] = {}
242 self.collections: Dict[str, CollectionType] = {}
243 self.collectionDocs: Dict[str, str] = {}
244 self.datasetTypes: NamedValueSet[DatasetType] = NamedValueSet()
245 self.dimensions: Mapping[DimensionElement, List[DimensionRecord]] = defaultdict(list)
246 self.tagAssociations: Dict[str, List[DatasetId]] = defaultdict(list)
247 self.calibAssociations: Dict[str, Dict[Timespan, List[DatasetId]]] = defaultdict(dict)
248 self.refsByFileId: Dict[DatasetId, DatasetRef] = {}
249 self.registry: Registry = registry
251 universe_version = wrapper.get("universe_version", 0)
252 universe_namespace = wrapper.get("universe_namespace", "daf_butler")
254 # If this is data exported before the reorganization of visits
255 # and visit systems and that new schema is in use, some filtering
256 # will be needed. The entry in the visit dimension record will be
257 # silently dropped when visit is created but the
258 # visit_system_membership must be constructed.
259 migrate_visit_system = False
260 if (
261 universe_version < 2
262 and universe_namespace == "daf_butler"
263 and "visit_system_membership" in self.registry.dimensions
264 ):
265 migrate_visit_system = True
267 datasetData = []
268 for data in wrapper["data"]:
269 if data["type"] == "dimension":
270 # convert all datetime values to astropy
271 for record in data["records"]:
272 for key in record:
273 # Some older YAML files were produced with native
274 # YAML support for datetime, we support reading that
275 # data back. Newer conversion uses _AstropyTimeToYAML
276 # class with special YAML tag.
277 if isinstance(record[key], datetime):
278 record[key] = astropy.time.Time(record[key], scale="utc")
279 element = self.registry.dimensions[data["element"]]
280 RecordClass: Type[DimensionRecord] = element.RecordClass
281 self.dimensions[element].extend(RecordClass(**r) for r in data["records"])
283 if data["element"] == "visit" and migrate_visit_system:
284 # Must create the visit_system_membership records.
285 element = self.registry.dimensions["visit_system_membership"]
286 RecordClass = element.RecordClass
287 self.dimensions[element].extend(
288 RecordClass(instrument=r["instrument"], visit_system=r["visit_system"], visit=r["id"])
289 for r in data["records"]
290 )
292 elif data["type"] == "collection":
293 collectionType = CollectionType.from_name(data["collection_type"])
294 if collectionType is CollectionType.RUN:
295 self.runs[data["name"]] = (
296 data["host"],
297 Timespan(begin=data["timespan_begin"], end=data["timespan_end"]),
298 )
299 elif collectionType is CollectionType.CHAINED:
300 children = []
301 for child in data["children"]:
302 if not isinstance(child, str):
303 warnings.warn(
304 f"CHAINED collection {data['name']} includes restrictions on child "
305 "collection searches, which are no longer suppored and will be ignored."
306 )
307 # Old form with dataset type restrictions only,
308 # supported for backwards compatibility.
309 child, _ = child
310 children.append(child)
311 self.chains[data["name"]] = children
312 else:
313 self.collections[data["name"]] = collectionType
314 doc = data.get("doc")
315 if doc is not None:
316 self.collectionDocs[data["name"]] = doc
317 elif data["type"] == "run":
318 # Also support old form of saving a run with no extra info.
319 self.runs[data["name"]] = (None, Timespan(None, None))
320 elif data["type"] == "dataset_type":
321 dimensions = data["dimensions"]
322 if migrate_visit_system and "visit" in dimensions and "visit_system" in dimensions:
323 dimensions.remove("visit_system")
324 self.datasetTypes.add(
325 DatasetType(
326 data["name"],
327 dimensions=dimensions,
328 storageClass=data["storage_class"],
329 universe=self.registry.dimensions,
330 isCalibration=data.get("is_calibration", False),
331 )
332 )
333 elif data["type"] == "dataset":
334 # Save raw dataset data for a second loop, so we can ensure we
335 # know about all dataset types first.
336 datasetData.append(data)
337 elif data["type"] == "associations":
338 collectionType = CollectionType.from_name(data["collection_type"])
339 if collectionType is CollectionType.TAGGED:
340 self.tagAssociations[data["collection"]].extend(data["dataset_ids"])
341 elif collectionType is CollectionType.CALIBRATION:
342 assocsByTimespan = self.calibAssociations[data["collection"]]
343 for d in data["validity_ranges"]:
344 if "timespan" in d:
345 assocsByTimespan[d["timespan"]] = d["dataset_ids"]
346 else:
347 # TODO: this is for backward compatibility, should
348 # be removed at some point.
349 assocsByTimespan[Timespan(begin=d["begin"], end=d["end"])] = d["dataset_ids"]
350 else:
351 raise ValueError(f"Unexpected calibration type for association: {collectionType.name}.")
352 else:
353 raise ValueError(f"Unexpected dictionary type: {data['type']}.")
354 # key is (dataset type name, run)
355 self.datasets: Mapping[Tuple[str, str], List[FileDataset]] = defaultdict(list)
356 for data in datasetData:
357 datasetType = self.datasetTypes.get(data["dataset_type"])
358 if datasetType is None:
359 datasetType = self.registry.getDatasetType(data["dataset_type"])
360 self.datasets[data["dataset_type"], data["run"]].extend(
361 FileDataset(
362 d.get("path"),
363 [
364 DatasetRef(datasetType, dataId, run=data["run"], id=refid)
365 for dataId, refid in zip(
366 ensure_iterable(d["data_id"]), ensure_iterable(d["dataset_id"])
367 )
368 ],
369 formatter=doImportType(d.get("formatter")) if "formatter" in d else None,
370 )
371 for d in data["records"]
372 )
374 def register(self) -> None:
375 # Docstring inherited from RepoImportBackend.register.
376 for datasetType in self.datasetTypes:
377 self.registry.registerDatasetType(datasetType)
378 for run in self.runs:
379 self.registry.registerRun(run, doc=self.collectionDocs.get(run))
380 # No way to add extra run info to registry yet.
381 for collection, collection_type in self.collections.items():
382 self.registry.registerCollection(
383 collection, collection_type, doc=self.collectionDocs.get(collection)
384 )
385 for chain, children in self.chains.items():
386 self.registry.registerCollection(
387 chain, CollectionType.CHAINED, doc=self.collectionDocs.get(chain)
388 )
389 self.registry.setCollectionChain(chain, children)
391 def load(
392 self,
393 datastore: Optional[Datastore],
394 *,
395 directory: ResourcePathExpression | None = None,
396 transfer: Optional[str] = None,
397 skip_dimensions: Optional[Set] = None,
398 ) -> None:
399 # Docstring inherited from RepoImportBackend.load.
400 for element, dimensionRecords in self.dimensions.items():
401 if skip_dimensions and element in skip_dimensions:
402 continue
403 # Using skip_existing=True here assumes that the records in the
404 # database are either equivalent or at least preferable to the ones
405 # being imported. It'd be ideal to check that, but that would mean
406 # using syncDimensionData, which is not vectorized and is hence
407 # unacceptably slo.
408 self.registry.insertDimensionData(element, *dimensionRecords, skip_existing=True)
409 # FileDatasets to ingest into the datastore (in bulk):
410 fileDatasets = []
411 for (datasetTypeName, run), records in self.datasets.items():
412 # Make a big flattened list of all data IDs and dataset_ids, while
413 # remembering slices that associate them with the FileDataset
414 # instances they came from.
415 datasets: List[DatasetRef] = []
416 dataset_ids: List[DatasetId] = []
417 slices = []
418 for fileDataset in records:
419 start = len(datasets)
420 datasets.extend(fileDataset.refs)
421 dataset_ids.extend(ref.id for ref in fileDataset.refs)
422 stop = len(datasets)
423 slices.append(slice(start, stop))
424 # Insert all of those DatasetRefs at once.
425 # For now, we ignore the dataset_id we pulled from the file
426 # and just insert without one to get a new autoincrement value.
427 # Eventually (once we have origin in IDs) we'll preserve them.
428 resolvedRefs = self.registry._importDatasets(datasets)
429 # Populate our dictionary that maps int dataset_id values from the
430 # export file to the new DatasetRefs
431 for fileId, ref in zip(dataset_ids, resolvedRefs):
432 self.refsByFileId[fileId] = ref
433 # Now iterate over the original records, and install the new
434 # resolved DatasetRefs to replace the unresolved ones as we
435 # reorganize the collection information.
436 for sliceForFileDataset, fileDataset in zip(slices, records):
437 fileDataset.refs = resolvedRefs[sliceForFileDataset]
438 if directory is not None:
439 fileDataset.path = ResourcePath(directory, forceDirectory=True).join(fileDataset.path)
440 fileDatasets.append(fileDataset)
441 # Ingest everything into the datastore at once.
442 if datastore is not None and fileDatasets:
443 datastore.ingest(*fileDatasets, transfer=transfer)
444 # Associate datasets with tagged collections.
445 for collection, dataset_ids in self.tagAssociations.items():
446 self.registry.associate(collection, [self.refsByFileId[i] for i in dataset_ids])
447 # Associate datasets with calibration collections.
448 for collection, idsByTimespan in self.calibAssociations.items():
449 for timespan, dataset_ids in idsByTimespan.items():
450 self.registry.certify(collection, [self.refsByFileId[i] for i in dataset_ids], timespan)