23 __all__ = (
"RawIngestTask",
"RawIngestConfig",
"makeTransferChoiceField")
26 from dataclasses
import dataclass, InitVar
27 from typing
import List, Iterator, Iterable, Type, Optional, Any
28 from collections
import defaultdict
29 from multiprocessing
import Pool
31 from astro_metadata_translator
import ObservationInfo, fix_header, merge_headers
33 from lsst.daf.butler
import (
43 from lsst.pex.config
import Config, ChoiceField
46 from ._instrument
import Instrument, makeExposureRecordFromObsInfo
47 from ._fitsRawFormatterBase
import FitsRawFormatterBase
52 """Structure that holds information about a single dataset within a
56 dataId: DataCoordinate
57 """Data ID for this file (`lsst.daf.butler.DataCoordinate`).
60 obsInfo: ObservationInfo
61 """Standardized observation metadata extracted directly from the file
62 headers (`astro_metadata_translator.ObservationInfo`).
68 """Structure that holds information about a single raw file, used during
72 datasets: List[RawFileDatasetInfo]
73 """The information describing each dataset within this raw file.
74 (`list` of `RawFileDatasetInfo`)
78 """Name of the file this information was extracted from (`str`).
80 This is the path prior to ingest, not the path after ingest.
83 FormatterClass: Type[FitsRawFormatterBase]
84 """Formatter class that should be used to ingest this file (`type`; as
85 subclass of `FitsRawFormatterBase`).
88 instrumentClass: Type[Instrument]
89 """The `Instrument` class associated with this file."""
94 """Structure that holds information about a complete raw exposure, used
98 dataId: DataCoordinate
99 """Data ID for this exposure (`lsst.daf.butler.DataCoordinate`).
102 files: List[RawFileData]
103 """List of structures containing file-level information.
106 universe: InitVar[DimensionUniverse]
107 """Set of all known dimensions.
110 record: Optional[DimensionRecord] =
None
111 """The exposure `DimensionRecord` that must be inserted into the
112 `~lsst.daf.butler.Registry` prior to file-level ingest (`DimensionRecord`).
122 """Create a Config field with options for how to transfer files between
125 The allowed options for the field are exactly those supported by
126 `lsst.daf.butler.Datastore.ingest`.
131 Documentation for the configuration field.
135 field : `lsst.pex.config.ChoiceField`
141 allowed={
"move":
"move",
143 "auto":
"choice will depend on datastore",
144 "link":
"hard link falling back to symbolic link",
145 "hardlink":
"hard link",
146 "symlink":
"symbolic (soft) link",
147 "relsymlink":
"relative symbolic link",
159 """Driver Task for ingesting raw data into Gen3 Butler repositories.
163 config : `RawIngestConfig`
164 Configuration for the task.
165 butler : `~lsst.daf.butler.Butler`
166 Writeable butler instance, with ``butler.run`` set to the appropriate
167 `~lsst.daf.butler.CollectionType.RUN` collection for these raw
170 Additional keyword arguments are forwarded to the `lsst.pipe.base.Task`
175 Each instance of `RawIngestTask` writes to the same Butler. Each
176 invocation of `RawIngestTask.run` ingests a list of files.
179 ConfigClass = RawIngestConfig
181 _DefaultName =
"ingest"
184 """Return the DatasetType of the datasets ingested by this Task.
186 return DatasetType(
"raw", (
"instrument",
"detector",
"exposure"),
"Exposure",
187 universe=self.
butler.registry.dimensions)
189 def __init__(self, config: Optional[RawIngestConfig] =
None, *, butler: Butler, **kwargs: Any):
198 Instrument.importAll(self.
butler.registry)
201 """Extract and process metadata from a single raw file.
211 A structure containing the metadata extracted from the file,
212 as well as the original filename. All fields will be populated,
213 but the `RawFileData.dataId` attribute will be a minimal
214 (unexpanded) `DataCoordinate` instance.
218 Assumes that there is a single dataset associated with the given
219 file. Instruments using a single file to store multiple datasets
220 must implement their own version of this method.
225 header = merge_headers([phdu,
readMetadata(filename)], mode=
"overwrite")
232 instrument = Instrument.fromName(datasets[0].dataId[
"instrument"], self.
butler.registry)
233 FormatterClass = instrument.getRawFormatter(datasets[0].dataId)
235 return RawFileData(datasets=datasets, filename=filename,
236 FormatterClass=FormatterClass,
237 instrumentClass=instrument)
239 def _calculate_dataset_info(self, header, filename):
240 """Calculate a RawFileDatasetInfo from the supplied information.
245 Header from the dataset.
247 Filename to use for error messages.
251 dataset : `RawFileDatasetInfo`
252 The dataId, and observation information associated with this
255 obsInfo = ObservationInfo(header)
256 dataId = DataCoordinate.standardize(instrument=obsInfo.instrument,
257 exposure=obsInfo.exposure_id,
258 detector=obsInfo.detector_num,
263 """Group an iterable of `RawFileData` by exposure.
267 files : iterable of `RawFileData`
268 File-level information to group.
272 exposures : `list` of `RawExposureData`
273 A list of structures that group the file-level information by
274 exposure. All fields will be populated. The
275 `RawExposureData.dataId` attributes will be minimal (unexpanded)
276 `DataCoordinate` instances.
278 exposureDimensions = self.
universe[
"exposure"].graph
279 byExposure = defaultdict(list)
282 byExposure[f.datasets[0].dataId.subset(exposureDimensions)].
append(f)
285 for dataId, exposureFiles
in byExposure.items()]
288 """Expand the data IDs associated with a raw exposure to include
289 additional metadata records.
293 exposure : `RawExposureData`
294 A structure containing information about the exposure to be
295 ingested. Must have `RawExposureData.records` populated. Should
296 be considered consumed upon return.
300 exposure : `RawExposureData`
301 An updated version of the input structure, with
302 `RawExposureData.dataId` and nested `RawFileData.dataId` attributes
303 updated to data IDs for which `DataCoordinate.hasRecords` returns
309 data.dataId = self.
butler.registry.expandDataId(
316 self.
butler.registry.dimensions[
"exposure"]: data.record,
322 for file
in data.files:
323 for dataset
in file.datasets:
324 dataset.dataId = self.
butler.registry.expandDataId(
326 records=dict(data.dataId.records)
330 def prep(self, files, *, pool: Optional[Pool] =
None, processes: int = 1) -> Iterator[RawExposureData]:
331 """Perform all ingest preprocessing steps that do not involve actually
332 modifying the database.
336 files : iterable over `str` or path-like objects
337 Paths to the files to be ingested. Will be made absolute
338 if they are not already.
339 pool : `multiprocessing.Pool`, optional
340 If not `None`, a process pool with which to parallelize some
342 processes : `int`, optional
343 The number of processes to use. Ignored if ``pool`` is not `None`.
347 exposure : `RawExposureData`
348 Data structures containing dimension records, filenames, and data
349 IDs to be ingested (one structure for each exposure).
351 if pool
is None and processes > 1:
352 pool = Pool(processes)
353 mapFunc = map
if pool
is None else pool.imap_unordered
381 ) -> List[DatasetRef]:
382 """Ingest all raw files in one exposure.
386 exposure : `RawExposureData`
387 A structure containing information about the exposure to be
388 ingested. Must have `RawExposureData.records` populated and all
389 data ID attributes expanded.
390 run : `str`, optional
391 Name of a RUN-type collection to write to, overriding
396 refs : `list` of `lsst.daf.butler.DatasetRef`
397 Dataset references for ingested raws.
399 datasets = [FileDataset(path=os.path.abspath(file.filename),
400 refs=[DatasetRef(self.
datasetType, d.dataId)
for d
in file.datasets],
401 formatter=file.FormatterClass)
402 for file
in exposure.files]
403 self.
butler.ingest(*datasets, transfer=self.
config.transfer, run=run)
404 return [ref
for dataset
in datasets
for ref
in dataset.refs]
406 def run(self, files, *, pool: Optional[Pool] =
None, processes: int = 1, run: Optional[str] =
None):
407 """Ingest files into a Butler data repository.
409 This creates any new exposure or visit Dimension entries needed to
410 identify the ingested files, creates new Dataset entries in the
411 Registry and finally ingests the files themselves into the Datastore.
412 Any needed instrument, detector, and physical_filter Dimension entries
413 must exist in the Registry before `run` is called.
417 files : iterable over `str` or path-like objects
418 Paths to the files to be ingested. Will be made absolute
419 if they are not already.
420 pool : `multiprocessing.Pool`, optional
421 If not `None`, a process pool with which to parallelize some
423 processes : `int`, optional
424 The number of processes to use. Ignored if ``pool`` is not `None`.
425 run : `str`, optional
426 Name of a RUN-type collection to write to, overriding
427 the default derived from the instrument name.
431 refs : `list` of `lsst.daf.butler.DatasetRef`
432 Dataset references for ingested raws.
436 This method inserts all datasets for an exposure within a transaction,
437 guaranteeing that partial exposures are never ingested. The exposure
438 dimension record is inserted with `Registry.syncDimensionData` first
439 (in its own transaction), which inserts only if a record with the same
440 primary key does not already exist. This allows different files within
441 the same exposure to be incremented in different runs.
443 exposureData = self.
prep(files, pool=pool, processes=processes)
455 for exposure
in exposureData:
456 self.
butler.registry.syncDimensionData(
"exposure", exposure.record)
459 instrumentClass = exposure.files[0].instrumentClass
460 this_run = instrumentClass.makeDefaultRawIngestRunName()
463 if this_run
not in runs:
464 self.
butler.registry.registerCollection(this_run, type=CollectionType.RUN)
466 with self.
butler.transaction():