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 (
42 from lsst.pex.config
import Config, ChoiceField
45 from ._instrument
import Instrument, makeExposureRecordFromObsInfo
46 from .fitsRawFormatterBase
import FitsRawFormatterBase
51 """Structure that holds information about a single dataset within a
55 dataId: DataCoordinate
56 """Data ID for this file (`lsst.daf.butler.DataCoordinate`).
58 This may be a minimal `~lsst.daf.butler.DataCoordinate` base instance, or
59 a complete `~lsst.daf.butler.ExpandedDataCoordinate`.
62 obsInfo: ObservationInfo
63 """Standardized observation metadata extracted directly from the file
64 headers (`astro_metadata_translator.ObservationInfo`).
70 """Structure that holds information about a single raw file, used during
74 datasets: List[RawFileDatasetInfo]
75 """The information describing each dataset within this raw file.
76 (`list` of `RawFileDatasetInfo`)
80 """Name of the file this information was extracted from (`str`).
82 This is the path prior to ingest, not the path after ingest.
85 FormatterClass: Type[FitsRawFormatterBase]
86 """Formatter class that should be used to ingest this file (`type`; as
87 subclass of `FitsRawFormatterBase`).
93 """Structure that holds information about a complete raw exposure, used
97 dataId: DataCoordinate
98 """Data ID for this exposure (`lsst.daf.butler.DataCoordinate`).
100 This may be a minimal `~lsst.daf.butler.DataCoordinate` base instance, or
101 a complete `~lsst.daf.butler.ExpandedDataCoordinate`.
104 files: List[RawFileData]
105 """List of structures containing file-level information.
108 universe: InitVar[DimensionUniverse]
109 """Set of all known dimensions.
112 record: Optional[DimensionRecord] =
None
113 """The exposure `DimensionRecord` that must be inserted into the
114 `~lsst.daf.butler.Registry` prior to file-level ingest (`DimensionRecord`).
124 """Create a Config field with options for how to transfer files between
127 The allowed options for the field are exactly those supported by
128 `lsst.daf.butler.Datastore.ingest`.
133 Documentation for the configuration field.
137 field : `lsst.pex.config.ChoiceField`
143 allowed={
"move":
"move",
145 "auto":
"choice will depend on datastore",
146 "link":
"hard link falling back to symbolic link",
147 "hardlink":
"hard link",
148 "symlink":
"symbolic (soft) link",
149 "relsymlink":
"relative symbolic link",
161 """Driver Task for ingesting raw data into Gen3 Butler repositories.
165 config : `RawIngestConfig`
166 Configuration for the task.
167 butler : `~lsst.daf.butler.Butler`
168 Writeable butler instance, with ``butler.run`` set to the appropriate
169 `~lsst.daf.butler.CollectionType.RUN` collection for these raw
172 Additional keyword arguments are forwarded to the `lsst.pipe.base.Task`
177 Each instance of `RawIngestTask` writes to the same Butler. Each
178 invocation of `RawIngestTask.run` ingests a list of files.
181 ConfigClass = RawIngestConfig
183 _DefaultName =
"ingest"
186 """Return the DatasetType of the datasets ingested by this Task.
188 return DatasetType(
"raw", (
"instrument",
"detector",
"exposure"),
"Exposure",
189 universe=self.
butler.registry.dimensions)
191 def __init__(self, config: Optional[RawIngestConfig] =
None, *, butler: Butler, **kwargs: Any):
200 Instrument.importAll(self.
butler.registry)
203 """Extract and process metadata from a single raw file.
213 A structure containing the metadata extracted from the file,
214 as well as the original filename. All fields will be populated,
215 but the `RawFileData.dataId` attribute will be a minimal
216 (unexpanded) `DataCoordinate` instance.
220 Assumes that there is a single dataset associated with the given
221 file. Instruments using a single file to store multiple datasets
222 must implement their own version of this method.
227 header = merge_headers([phdu,
readMetadata(filename)], mode=
"overwrite")
234 instrument = Instrument.fromName(datasets[0].dataId[
"instrument"], self.
butler.registry)
235 FormatterClass = instrument.getRawFormatter(datasets[0].dataId)
237 return RawFileData(datasets=datasets, filename=filename,
238 FormatterClass=FormatterClass)
240 def _calculate_dataset_info(self, header, filename):
241 """Calculate a RawFileDatasetInfo from the supplied information.
246 Header from the dataset.
248 Filename to use for error messages.
252 dataset : `RawFileDatasetInfo`
253 The dataId, and observation information associated with this
256 obsInfo = ObservationInfo(header)
257 dataId = DataCoordinate.standardize(instrument=obsInfo.instrument,
258 exposure=obsInfo.exposure_id,
259 detector=obsInfo.detector_num,
264 """Group an iterable of `RawFileData` by exposure.
268 files : iterable of `RawFileData`
269 File-level information to group.
273 exposures : `list` of `RawExposureData`
274 A list of structures that group the file-level information by
275 exposure. All fields will be populated. The
276 `RawExposureData.dataId` attributes will be minimal (unexpanded)
277 `DataCoordinate` instances.
279 exposureDimensions = self.
universe[
"exposure"].graph
280 byExposure = defaultdict(list)
283 byExposure[f.datasets[0].dataId.subset(exposureDimensions)].
append(f)
286 for dataId, exposureFiles
in byExposure.items()]
289 """Expand the data IDs associated with a raw exposure to include
290 additional metadata records.
294 exposure : `RawExposureData`
295 A structure containing information about the exposure to be
296 ingested. Must have `RawExposureData.records` populated. Should
297 be considered consumed upon return.
301 exposure : `RawExposureData`
302 An updated version of the input structure, with
303 `RawExposureData.dataId` and nested `RawFileData.dataId` attributes
304 containing `~lsst.daf.butler.ExpandedDataCoordinate` instances.
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
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)
454 for exposure
in exposureData:
455 self.
butler.registry.syncDimensionData(
"exposure", exposure.record)
456 with self.
butler.transaction():