Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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/>. 

21 

22from __future__ import annotations 

23 

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

25 

26import os 

27from datetime import datetime 

28from typing import ( 

29 Any, 

30 Dict, 

31 IO, 

32 Iterable, 

33 List, 

34 Mapping, 

35 Optional, 

36 Set, 

37 Tuple, 

38 Type, 

39) 

40import warnings 

41from collections import defaultdict 

42 

43import yaml 

44import astropy.time 

45 

46from lsst.utils import doImport 

47from ..core import ( 

48 DatasetAssociation, 

49 DatasetRef, 

50 DatasetType, 

51 DataCoordinate, 

52 Datastore, 

53 DimensionElement, 

54 DimensionRecord, 

55 FileDataset, 

56 Timespan, 

57) 

58from ..core.utils import iterable 

59from ..core.named import NamedValueSet 

60from ..registry import CollectionType, Registry 

61from ..registry.interfaces import ( 

62 ChainedCollectionRecord, 

63 CollectionRecord, 

64 RunRecord, 

65 VersionTuple, 

66) 

67from ..registry.versions import IncompatibleVersionError 

68from ._interfaces import RepoExportBackend, RepoImportBackend 

69 

70 

71EXPORT_FORMAT_VERSION = VersionTuple(1, 0, 0) 

72"""Export format version. 

73 

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

75this version of the code. 

76""" 

77 

78 

79class YamlRepoExportBackend(RepoExportBackend): 

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

81 

82 Parameters 

83 ---------- 

84 stream 

85 A writeable file-like object. 

86 """ 

87 

88 def __init__(self, stream: IO): 

89 self.stream = stream 

90 self.data: List[Dict[str, Any]] = [] 

91 

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

93 # Docstring inherited from RepoExportBackend.saveDimensionData. 

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

95 self.data.append({ 

96 "type": "dimension", 

97 "element": element.name, 

98 "records": data_dicts, 

99 }) 

100 

101 def saveCollection(self, record: CollectionRecord) -> None: 

102 # Docstring inherited from RepoExportBackend.saveCollections. 

103 data: Dict[str, Any] = { 

104 "type": "collection", 

105 "collection_type": record.type.name, 

106 "name": record.name, 

107 } 

108 if isinstance(record, RunRecord): 

109 data["host"] = record.host 

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

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

112 elif isinstance(record, ChainedCollectionRecord): 

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

114 self.data.append(data) 

115 

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

117 # Docstring inherited from RepoExportBackend.saveDatasets. 

118 self.data.append({ 

119 "type": "dataset_type", 

120 "name": datasetType.name, 

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

122 "storage_class": datasetType.storageClass.name, 

123 "is_calibration": datasetType.isCalibration(), 

124 }) 

125 self.data.append({ 

126 "type": "dataset", 

127 "dataset_type": datasetType.name, 

128 "run": run, 

129 "records": [ 

130 { 

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

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

133 "path": dataset.path, 

134 "formatter": dataset.formatter, 

135 # TODO: look up and save other collections 

136 } 

137 for dataset in datasets 

138 ] 

139 }) 

140 

141 def saveDatasetAssociations(self, collection: str, collectionType: CollectionType, 

142 associations: Iterable[DatasetAssociation]) -> None: 

143 # Docstring inherited from RepoExportBackend.saveDatasetAssociations. 

144 if collectionType is CollectionType.TAGGED: 

145 self.data.append({ 

146 "type": "associations", 

147 "collection": collection, 

148 "collection_type": collectionType.name, 

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

150 }) 

151 elif collectionType is CollectionType.CALIBRATION: 

152 idsByTimespan: Dict[Timespan, List[int]] = defaultdict(list) 

153 for association in associations: 

154 assert association.timespan is not None 

155 assert association.ref.id is not None 

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

157 self.data.append({ 

158 "type": "associations", 

159 "collection": collection, 

160 "collection_type": collectionType.name, 

161 "validity_ranges": [ 

162 { 

163 "begin": timespan.begin, 

164 "end": timespan.end, 

165 "dataset_ids": dataset_ids, 

166 } 

167 for timespan, dataset_ids in idsByTimespan.items() 

168 ] 

169 }) 

170 

171 def finish(self) -> None: 

172 # Docstring inherited from RepoExportBackend. 

173 yaml.dump( 

174 { 

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

176 "version": str(EXPORT_FORMAT_VERSION), 

177 "data": self.data, 

178 }, 

179 stream=self.stream, 

180 sort_keys=False, 

181 ) 

182 

183 

184class YamlRepoImportBackend(RepoImportBackend): 

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

186 

187 Parameters 

188 ---------- 

189 stream 

190 A readable file-like object. 

191 registry : `Registry` 

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

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

194 and `load`. 

195 """ 

196 

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

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

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

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

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

202 wrapper = yaml.safe_load(stream) 

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

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

205 # before we really tried to do versioning here. 

206 fileVersion = VersionTuple(1, 0, 0) 

207 else: 

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

209 if fileVersion.major != EXPORT_FORMAT_VERSION.major: 

210 raise IncompatibleVersionError( 

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

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

213 ) 

214 if fileVersion.minor > EXPORT_FORMAT_VERSION.minor: 

215 raise IncompatibleVersionError( 

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

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

218 ) 

219 self.runs: Dict[str, Tuple[Optional[str], Timespan]] = {} 

220 self.chains: Dict[str, List[str]] = {} 

221 self.collections: Dict[str, CollectionType] = {} 

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

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

224 self.tagAssociations: Dict[str, List[int]] = defaultdict(list) 

225 self.calibAssociations: Dict[str, Dict[Timespan, List[int]]] = defaultdict(dict) 

226 self.refsByFileId: Dict[int, DatasetRef] = {} 

227 self.registry: Registry = registry 

228 datasetData = [] 

229 for data in wrapper["data"]: 

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

231 # convert all datetime values to astropy 

232 for record in data["records"]: 

233 for key in record: 

234 # Some older YAML files were produced with native 

235 # YAML support for datetime, we support reading that 

236 # data back. Newer conversion uses _AstropyTimeToYAML 

237 # class with special YAML tag. 

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

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

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

241 RecordClass: Type[DimensionRecord] = element.RecordClass 

242 self.dimensions[element].extend( 

243 RecordClass(**r) for r in data["records"] 

244 ) 

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

246 collectionType = CollectionType.__members__[data["collection_type"].upper()] 

247 if collectionType is CollectionType.RUN: 

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

249 data["host"], 

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

251 ) 

252 elif collectionType is CollectionType.CHAINED: 

253 children = [] 

254 for child in data["children"]: 

255 if not isinstance(child, str): 

256 warnings.warn( 

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

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

259 ) 

260 # Old form with dataset type restrictions only, 

261 # supported for backwards compatibility. 

262 child, _ = child 

263 children.append(child) 

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

265 else: 

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

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

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

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

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

271 self.datasetTypes.add( 

272 DatasetType(data["name"], dimensions=data["dimensions"], 

273 storageClass=data["storage_class"], universe=self.registry.dimensions, 

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

275 ) 

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

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

278 # know about all dataset types first. 

279 datasetData.append(data) 

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

281 collectionType = CollectionType.__members__[data["collection_type"].upper()] 

282 if collectionType is CollectionType.TAGGED: 

283 self.tagAssociations[data["collection"]].extend(data["dataset_ids"]) 

284 elif collectionType is CollectionType.CALIBRATION: 

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

286 for d in data["validity_ranges"]: 

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

288 else: 

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

290 else: 

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

292 # key is (dataset type name, run) 

293 self.datasets: Mapping[Tuple[str, str], List[FileDataset]] = defaultdict(list) 

294 for data in datasetData: 

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

296 if datasetType is None: 

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

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

299 FileDataset( 

300 d.get("path"), 

301 [DatasetRef(datasetType, dataId, run=data["run"], id=refid) 

302 for dataId, refid in zip(iterable(d["data_id"]), iterable(d["dataset_id"]))], 

303 formatter=doImport(d.get("formatter")) if "formatter" in d else None 

304 ) 

305 for d in data["records"] 

306 ) 

307 

308 def register(self) -> None: 

309 # Docstring inherited from RepoImportBackend.register. 

310 for datasetType in self.datasetTypes: 

311 self.registry.registerDatasetType(datasetType) 

312 for run in self.runs: 

313 self.registry.registerRun(run) 

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

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

316 self.registry.registerCollection(collection, collection_type) 

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

318 self.registry.registerCollection(chain, CollectionType.CHAINED) 

319 self.registry.setCollectionChain(chain, children) 

320 

321 def load(self, datastore: Optional[Datastore], *, 

322 directory: Optional[str] = None, transfer: Optional[str] = None, 

323 skip_dimensions: Optional[Set] = None) -> None: 

324 # Docstring inherited from RepoImportBackend.load. 

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

326 if skip_dimensions and element in skip_dimensions: 

327 continue 

328 self.registry.insertDimensionData(element, *dimensionRecords) 

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

330 fileDatasets = [] 

331 for (datasetTypeName, run), records in self.datasets.items(): 

332 datasetType = self.registry.getDatasetType(datasetTypeName) 

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

334 # remembering slices that associate them with the FileDataset 

335 # instances they came from. 

336 dataIds: List[DataCoordinate] = [] 

337 dataset_ids: List[int] = [] 

338 slices = [] 

339 for fileDataset in records: 

340 start = len(dataIds) 

341 dataIds.extend(ref.dataId for ref in fileDataset.refs) 

342 dataset_ids.extend(ref.id for ref in fileDataset.refs) # type: ignore 

343 stop = len(dataIds) 

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

345 # Insert all of those DatasetRefs at once. 

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

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

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

349 resolvedRefs = self.registry.insertDatasets( 

350 datasetType, 

351 dataIds=dataIds, 

352 run=run, 

353 ) 

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

355 # export file to the new DatasetRefs 

356 for fileId, ref in zip(dataset_ids, resolvedRefs): 

357 self.refsByFileId[fileId] = ref 

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

359 # resolved DatasetRefs to replace the unresolved ones as we 

360 # reorganize the collection information. 

361 for sliceForFileDataset, fileDataset in zip(slices, records): 

362 fileDataset.refs = resolvedRefs[sliceForFileDataset] 

363 if directory is not None: 

364 fileDataset.path = os.path.join(directory, fileDataset.path) 

365 fileDatasets.append(fileDataset) 

366 # Ingest everything into the datastore at once. 

367 if datastore is not None and fileDatasets: 

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

369 # Associate datasets with tagged collections. 

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

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

372 # Associate datasets with calibration collections. 

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

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

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