Coverage for python/lsst/daf/butler/transfers/_yaml.py: 14%

199 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-10-12 09:44 +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/>. 

27 

28from __future__ import annotations 

29 

30__all__ = ["YamlRepoExportBackend", "YamlRepoImportBackend"] 

31 

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 

38 

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 

45 

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, Registry 

55from ..registry.interfaces import ChainedCollectionRecord, CollectionRecord, RunRecord, VersionTuple 

56from ..registry.versions import IncompatibleVersionError 

57from ._interfaces import RepoExportBackend, RepoImportBackend 

58 

59if TYPE_CHECKING: 

60 from lsst.resources import ResourcePathExpression 

61 

62EXPORT_FORMAT_VERSION = VersionTuple(1, 0, 2) 

63"""Export format version. 

64 

65Files with a different major version or a newer minor version cannot be read by 

66this version of the code. 

67""" 

68 

69 

70class _RefMapper(UserDict[int, uuid.UUID]): 

71 """Create a local dict subclass which creates new deterministic UUID for 

72 missing keys. 

73 """ 

74 

75 _namespace = uuid.UUID("4d4851f4-2890-4d41-8779-5f38a3f5062b") 

76 

77 def __missing__(self, key: int) -> uuid.UUID: 

78 newUUID = uuid.uuid3(namespace=self._namespace, name=str(key)) 

79 self[key] = newUUID 

80 return newUUID 

81 

82 

83_refIntId2UUID = _RefMapper() 

84 

85 

86def _uuid_representer(dumper: yaml.Dumper, data: uuid.UUID) -> yaml.Node: 

87 """Generate YAML representation for UUID. 

88 

89 This produces a scalar node with a tag "!uuid" and value being a regular 

90 string representation of UUID. 

91 """ 

92 return dumper.represent_scalar("!uuid", str(data)) 

93 

94 

95def _uuid_constructor(loader: yaml.Loader, node: yaml.Node) -> uuid.UUID | None: 

96 if node.value is not None: 

97 return uuid.UUID(hex=node.value) 

98 return None 

99 

100 

101yaml.Dumper.add_representer(uuid.UUID, _uuid_representer) 

102yaml.SafeLoader.add_constructor("!uuid", _uuid_constructor) 

103 

104 

105class YamlRepoExportBackend(RepoExportBackend): 

106 """A repository export implementation that saves to a YAML file. 

107 

108 Parameters 

109 ---------- 

110 stream 

111 A writeable file-like object. 

112 """ 

113 

114 def __init__(self, stream: IO, universe: DimensionUniverse): 

115 self.stream = stream 

116 self.universe = universe 

117 self.data: list[dict[str, Any]] = [] 

118 

119 def saveDimensionData(self, element: DimensionElement, *data: DimensionRecord) -> None: 

120 # Docstring inherited from RepoExportBackend.saveDimensionData. 

121 data_dicts = [record.toDict(splitTimespan=True) for record in data] 

122 self.data.append( 

123 { 

124 "type": "dimension", 

125 "element": element.name, 

126 "records": data_dicts, 

127 } 

128 ) 

129 

130 def saveCollection(self, record: CollectionRecord, doc: str | None) -> None: 

131 # Docstring inherited from RepoExportBackend.saveCollections. 

132 data: dict[str, Any] = { 

133 "type": "collection", 

134 "collection_type": record.type.name, 

135 "name": record.name, 

136 } 

137 if doc is not None: 

138 data["doc"] = doc 

139 if isinstance(record, RunRecord): 

140 data["host"] = record.host 

141 data["timespan_begin"] = record.timespan.begin 

142 data["timespan_end"] = record.timespan.end 

143 elif isinstance(record, ChainedCollectionRecord): 

144 data["children"] = list(record.children) 

145 self.data.append(data) 

146 

147 def saveDatasets(self, datasetType: DatasetType, run: str, *datasets: FileDataset) -> None: 

148 # Docstring inherited from RepoExportBackend.saveDatasets. 

149 self.data.append( 

150 { 

151 "type": "dataset_type", 

152 "name": datasetType.name, 

153 "dimensions": [d.name for d in datasetType.dimensions], 

154 "storage_class": datasetType.storageClass_name, 

155 "is_calibration": datasetType.isCalibration(), 

156 } 

157 ) 

158 self.data.append( 

159 { 

160 "type": "dataset", 

161 "dataset_type": datasetType.name, 

162 "run": run, 

163 "records": [ 

164 { 

165 "dataset_id": [ref.id for ref in sorted(dataset.refs)], 

166 "data_id": [ref.dataId.byName() for ref in sorted(dataset.refs)], 

167 "path": dataset.path, 

168 "formatter": dataset.formatter, 

169 # TODO: look up and save other collections 

170 } 

171 for dataset in datasets 

172 ], 

173 } 

174 ) 

175 

176 def saveDatasetAssociations( 

177 self, collection: str, collectionType: CollectionType, associations: Iterable[DatasetAssociation] 

178 ) -> None: 

179 # Docstring inherited from RepoExportBackend.saveDatasetAssociations. 

180 if collectionType is CollectionType.TAGGED: 

181 self.data.append( 

182 { 

183 "type": "associations", 

184 "collection": collection, 

185 "collection_type": collectionType.name, 

186 "dataset_ids": [assoc.ref.id for assoc in associations], 

187 } 

188 ) 

189 elif collectionType is CollectionType.CALIBRATION: 

190 idsByTimespan: dict[Timespan, list[DatasetId]] = defaultdict(list) 

191 for association in associations: 

192 assert association.timespan is not None 

193 idsByTimespan[association.timespan].append(association.ref.id) 

194 self.data.append( 

195 { 

196 "type": "associations", 

197 "collection": collection, 

198 "collection_type": collectionType.name, 

199 "validity_ranges": [ 

200 { 

201 "timespan": timespan, 

202 "dataset_ids": dataset_ids, 

203 } 

204 for timespan, dataset_ids in idsByTimespan.items() 

205 ], 

206 } 

207 ) 

208 

209 def finish(self) -> None: 

210 # Docstring inherited from RepoExportBackend. 

211 yaml.dump( 

212 { 

213 "description": "Butler Data Repository Export", 

214 "version": str(EXPORT_FORMAT_VERSION), 

215 "universe_version": self.universe.version, 

216 "universe_namespace": self.universe.namespace, 

217 "data": self.data, 

218 }, 

219 stream=self.stream, 

220 sort_keys=False, 

221 ) 

222 

223 

224class YamlRepoImportBackend(RepoImportBackend): 

225 """A repository import implementation that reads from a YAML file. 

226 

227 Parameters 

228 ---------- 

229 stream 

230 A readable file-like object. 

231 registry : `Registry` 

232 The registry datasets will be imported into. Only used to retreive 

233 dataset types during construction; all write happen in `register` 

234 and `load`. 

235 """ 

236 

237 def __init__(self, stream: IO, registry: Registry): 

238 # We read the file fully and convert its contents to Python objects 

239 # instead of loading incrementally so we can spot some problems early; 

240 # because `register` can't be put inside a transaction, we'd rather not 

241 # run that at all if there's going to be problem later in `load`. 

242 wrapper = yaml.safe_load(stream) 

243 if wrapper["version"] == 0: 

244 # Grandfather-in 'version: 0' -> 1.0.0, which is what we wrote 

245 # before we really tried to do versioning here. 

246 fileVersion = VersionTuple(1, 0, 0) 

247 else: 

248 fileVersion = VersionTuple.fromString(wrapper["version"]) 

249 if fileVersion.major != EXPORT_FORMAT_VERSION.major: 

250 raise IncompatibleVersionError( 

251 f"Cannot read repository export file with version={fileVersion} " 

252 f"({EXPORT_FORMAT_VERSION.major}.x.x required)." 

253 ) 

254 if fileVersion.minor > EXPORT_FORMAT_VERSION.minor: 

255 raise IncompatibleVersionError( 

256 f"Cannot read repository export file with version={fileVersion} " 

257 f"< {EXPORT_FORMAT_VERSION.major}.{EXPORT_FORMAT_VERSION.minor}.x required." 

258 ) 

259 self.runs: dict[str, tuple[str | None, Timespan]] = {} 

260 self.chains: dict[str, list[str]] = {} 

261 self.collections: dict[str, CollectionType] = {} 

262 self.collectionDocs: dict[str, str] = {} 

263 self.datasetTypes: NamedValueSet[DatasetType] = NamedValueSet() 

264 self.dimensions: Mapping[DimensionElement, list[DimensionRecord]] = defaultdict(list) 

265 self.tagAssociations: dict[str, list[DatasetId]] = defaultdict(list) 

266 self.calibAssociations: dict[str, dict[Timespan, list[DatasetId]]] = defaultdict(dict) 

267 self.refsByFileId: dict[DatasetId, DatasetRef] = {} 

268 self.registry: Registry = registry 

269 

270 universe_version = wrapper.get("universe_version", 0) 

271 universe_namespace = wrapper.get("universe_namespace", "daf_butler") 

272 

273 # If this is data exported before the reorganization of visits 

274 # and visit systems and that new schema is in use, some filtering 

275 # will be needed. The entry in the visit dimension record will be 

276 # silently dropped when visit is created but the 

277 # visit_system_membership must be constructed. 

278 migrate_visit_system = False 

279 if ( 

280 universe_version < 2 

281 and universe_namespace == "daf_butler" 

282 and "visit_system_membership" in self.registry.dimensions 

283 ): 

284 migrate_visit_system = True 

285 

286 datasetData = [] 

287 for data in wrapper["data"]: 

288 if data["type"] == "dimension": 

289 # convert all datetime values to astropy 

290 for record in data["records"]: 

291 for key in record: 

292 # Some older YAML files were produced with native 

293 # YAML support for datetime, we support reading that 

294 # data back. Newer conversion uses _AstropyTimeToYAML 

295 # class with special YAML tag. 

296 if isinstance(record[key], datetime): 

297 record[key] = astropy.time.Time(record[key], scale="utc") 

298 element = self.registry.dimensions[data["element"]] 

299 RecordClass: type[DimensionRecord] = element.RecordClass 

300 self.dimensions[element].extend(RecordClass(**r) for r in data["records"]) 

301 

302 if data["element"] == "visit" and migrate_visit_system: 

303 # Must create the visit_system_membership records. 

304 element = self.registry.dimensions["visit_system_membership"] 

305 RecordClass = element.RecordClass 

306 self.dimensions[element].extend( 

307 RecordClass(instrument=r["instrument"], visit_system=r["visit_system"], visit=r["id"]) 

308 for r in data["records"] 

309 ) 

310 

311 elif data["type"] == "collection": 

312 collectionType = CollectionType.from_name(data["collection_type"]) 

313 if collectionType is CollectionType.RUN: 

314 self.runs[data["name"]] = ( 

315 data["host"], 

316 Timespan(begin=data["timespan_begin"], end=data["timespan_end"]), 

317 ) 

318 elif collectionType is CollectionType.CHAINED: 

319 children = [] 

320 for child in data["children"]: 

321 if not isinstance(child, str): 

322 warnings.warn( 

323 f"CHAINED collection {data['name']} includes restrictions on child " 

324 "collection searches, which are no longer suppored and will be ignored.", 

325 stacklevel=find_outside_stacklevel("lsst.daf.butler"), 

326 ) 

327 # Old form with dataset type restrictions only, 

328 # supported for backwards compatibility. 

329 child, _ = child 

330 children.append(child) 

331 self.chains[data["name"]] = children 

332 else: 

333 self.collections[data["name"]] = collectionType 

334 doc = data.get("doc") 

335 if doc is not None: 

336 self.collectionDocs[data["name"]] = doc 

337 elif data["type"] == "run": 

338 # Also support old form of saving a run with no extra info. 

339 self.runs[data["name"]] = (None, Timespan(None, None)) 

340 elif data["type"] == "dataset_type": 

341 dimensions = data["dimensions"] 

342 if migrate_visit_system and "visit" in dimensions and "visit_system" in dimensions: 

343 dimensions.remove("visit_system") 

344 self.datasetTypes.add( 

345 DatasetType( 

346 data["name"], 

347 dimensions=dimensions, 

348 storageClass=data["storage_class"], 

349 universe=self.registry.dimensions, 

350 isCalibration=data.get("is_calibration", False), 

351 ) 

352 ) 

353 elif data["type"] == "dataset": 

354 # Save raw dataset data for a second loop, so we can ensure we 

355 # know about all dataset types first. 

356 datasetData.append(data) 

357 elif data["type"] == "associations": 

358 collectionType = CollectionType.from_name(data["collection_type"]) 

359 if collectionType is CollectionType.TAGGED: 

360 self.tagAssociations[data["collection"]].extend( 

361 [x if not isinstance(x, int) else _refIntId2UUID[x] for x in data["dataset_ids"]] 

362 ) 

363 elif collectionType is CollectionType.CALIBRATION: 

364 assocsByTimespan = self.calibAssociations[data["collection"]] 

365 for d in data["validity_ranges"]: 

366 if "timespan" in d: 

367 assocsByTimespan[d["timespan"]] = [ 

368 x if not isinstance(x, int) else _refIntId2UUID[x] for x in d["dataset_ids"] 

369 ] 

370 else: 

371 # TODO: this is for backward compatibility, should 

372 # be removed at some point. 

373 assocsByTimespan[Timespan(begin=d["begin"], end=d["end"])] = [ 

374 x if not isinstance(x, int) else _refIntId2UUID[x] for x in d["dataset_ids"] 

375 ] 

376 else: 

377 raise ValueError(f"Unexpected calibration type for association: {collectionType.name}.") 

378 else: 

379 raise ValueError(f"Unexpected dictionary type: {data['type']}.") 

380 # key is (dataset type name, run) 

381 self.datasets: Mapping[tuple[str, str], list[FileDataset]] = defaultdict(list) 

382 for data in datasetData: 

383 datasetType = self.datasetTypes.get(data["dataset_type"]) 

384 if datasetType is None: 

385 datasetType = self.registry.getDatasetType(data["dataset_type"]) 

386 self.datasets[data["dataset_type"], data["run"]].extend( 

387 FileDataset( 

388 d.get("path"), 

389 [ 

390 DatasetRef( 

391 datasetType, 

392 dataId, 

393 run=data["run"], 

394 id=refid if not isinstance(refid, int) else _refIntId2UUID[refid], 

395 ) 

396 for dataId, refid in zip( 

397 ensure_iterable(d["data_id"]), ensure_iterable(d["dataset_id"]), strict=True 

398 ) 

399 ], 

400 formatter=doImportType(d.get("formatter")) if "formatter" in d else None, 

401 ) 

402 for d in data["records"] 

403 ) 

404 

405 def register(self) -> None: 

406 # Docstring inherited from RepoImportBackend.register. 

407 for datasetType in self.datasetTypes: 

408 self.registry.registerDatasetType(datasetType) 

409 for run in self.runs: 

410 self.registry.registerRun(run, doc=self.collectionDocs.get(run)) 

411 # No way to add extra run info to registry yet. 

412 for collection, collection_type in self.collections.items(): 

413 self.registry.registerCollection( 

414 collection, collection_type, doc=self.collectionDocs.get(collection) 

415 ) 

416 for chain, children in self.chains.items(): 

417 self.registry.registerCollection( 

418 chain, CollectionType.CHAINED, doc=self.collectionDocs.get(chain) 

419 ) 

420 self.registry.setCollectionChain(chain, children) 

421 

422 def load( 

423 self, 

424 datastore: Datastore | None, 

425 *, 

426 directory: ResourcePathExpression | None = None, 

427 transfer: str | None = None, 

428 skip_dimensions: set | None = None, 

429 ) -> None: 

430 # Docstring inherited from RepoImportBackend.load. 

431 for element, dimensionRecords in self.dimensions.items(): 

432 if skip_dimensions and element in skip_dimensions: 

433 continue 

434 # Using skip_existing=True here assumes that the records in the 

435 # database are either equivalent or at least preferable to the ones 

436 # being imported. It'd be ideal to check that, but that would mean 

437 # using syncDimensionData, which is not vectorized and is hence 

438 # unacceptably slo. 

439 self.registry.insertDimensionData(element, *dimensionRecords, skip_existing=True) 

440 # FileDatasets to ingest into the datastore (in bulk): 

441 fileDatasets = [] 

442 for records in self.datasets.values(): 

443 # Make a big flattened list of all data IDs and dataset_ids, while 

444 # remembering slices that associate them with the FileDataset 

445 # instances they came from. 

446 datasets: list[DatasetRef] = [] 

447 dataset_ids: list[DatasetId] = [] 

448 slices = [] 

449 for fileDataset in records: 

450 start = len(datasets) 

451 datasets.extend(fileDataset.refs) 

452 dataset_ids.extend(ref.id for ref in fileDataset.refs) 

453 stop = len(datasets) 

454 slices.append(slice(start, stop)) 

455 # Insert all of those DatasetRefs at once. 

456 # For now, we ignore the dataset_id we pulled from the file 

457 # and just insert without one to get a new autoincrement value. 

458 # Eventually (once we have origin in IDs) we'll preserve them. 

459 resolvedRefs = self.registry._importDatasets(datasets) 

460 # Populate our dictionary that maps int dataset_id values from the 

461 # export file to the new DatasetRefs 

462 for fileId, ref in zip(dataset_ids, resolvedRefs, strict=True): 

463 self.refsByFileId[fileId] = ref 

464 # Now iterate over the original records, and install the new 

465 # resolved DatasetRefs to replace the unresolved ones as we 

466 # reorganize the collection information. 

467 for sliceForFileDataset, fileDataset in zip(slices, records, strict=True): 

468 fileDataset.refs = resolvedRefs[sliceForFileDataset] 

469 if directory is not None: 

470 fileDataset.path = ResourcePath(directory, forceDirectory=True).join(fileDataset.path) 

471 fileDatasets.append(fileDataset) 

472 # Ingest everything into the datastore at once. 

473 if datastore is not None and fileDatasets: 

474 datastore.ingest(*fileDatasets, transfer=transfer) 

475 # Associate datasets with tagged collections. 

476 for collection, dataset_ids in self.tagAssociations.items(): 

477 self.registry.associate(collection, [self.refsByFileId[i] for i in dataset_ids]) 

478 # Associate datasets with calibration collections. 

479 for collection, idsByTimespan in self.calibAssociations.items(): 

480 for timespan, dataset_ids in idsByTimespan.items(): 

481 self.registry.certify(collection, [self.refsByFileId[i] for i in dataset_ids], timespan)