Coverage for python/lsst/obs/base/ingest.py : 45%

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 obs_base.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://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/>.
23__all__ = ("RawIngestTask", "RawIngestConfig", "makeTransferChoiceField")
25import os.path
26from dataclasses import dataclass, InitVar
27from typing import List, Iterator, Iterable, Type, Optional, Any
28from collections import defaultdict
29from multiprocessing import Pool
31from astro_metadata_translator import ObservationInfo, fix_header, merge_headers
32from lsst.afw.fits import readMetadata
33from lsst.daf.butler import (
34 Butler,
35 DataCoordinate,
36 DatasetRef,
37 DatasetType,
38 DimensionRecord,
39 DimensionUniverse,
40 FileDataset,
41)
42from lsst.pex.config import Config, ChoiceField
43from lsst.pipe.base import Task
45from ._instrument import Instrument, makeExposureRecordFromObsInfo
46from ._fitsRawFormatterBase import FitsRawFormatterBase
49@dataclass
50class RawFileDatasetInfo:
51 """Structure that holds information about a single dataset within a
52 raw file.
53 """
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`.
60 """
62 obsInfo: ObservationInfo
63 """Standardized observation metadata extracted directly from the file
64 headers (`astro_metadata_translator.ObservationInfo`).
65 """
68@dataclass
69class RawFileData:
70 """Structure that holds information about a single raw file, used during
71 ingest.
72 """
74 datasets: List[RawFileDatasetInfo]
75 """The information describing each dataset within this raw file.
76 (`list` of `RawFileDatasetInfo`)
77 """
79 filename: str
80 """Name of the file this information was extracted from (`str`).
82 This is the path prior to ingest, not the path after ingest.
83 """
85 FormatterClass: Type[FitsRawFormatterBase]
86 """Formatter class that should be used to ingest this file (`type`; as
87 subclass of `FitsRawFormatterBase`).
88 """
91@dataclass
92class RawExposureData:
93 """Structure that holds information about a complete raw exposure, used
94 during ingest.
95 """
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`.
102 """
104 files: List[RawFileData]
105 """List of structures containing file-level information.
106 """
108 universe: InitVar[DimensionUniverse]
109 """Set of all known dimensions.
110 """
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`).
115 """
117 def __post_init__(self, universe: DimensionUniverse):
118 # We don't care which file or dataset we read metadata from, because
119 # we're assuming they'll all be the same; just use the first ones.
120 self.record = makeExposureRecordFromObsInfo(self.files[0].datasets[0].obsInfo, universe)
123def makeTransferChoiceField(doc="How to transfer files (None for no transfer).", default=None):
124 """Create a Config field with options for how to transfer files between
125 data repositories.
127 The allowed options for the field are exactly those supported by
128 `lsst.daf.butler.Datastore.ingest`.
130 Parameters
131 ----------
132 doc : `str`
133 Documentation for the configuration field.
135 Returns
136 -------
137 field : `lsst.pex.config.ChoiceField`
138 Configuration field.
139 """
140 return ChoiceField(
141 doc=doc,
142 dtype=str,
143 allowed={"move": "move",
144 "copy": "copy",
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",
150 },
151 optional=True,
152 default=default
153 )
156class RawIngestConfig(Config):
157 transfer = makeTransferChoiceField()
160class RawIngestTask(Task):
161 """Driver Task for ingesting raw data into Gen3 Butler repositories.
163 Parameters
164 ----------
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
170 datasets.
171 **kwargs
172 Additional keyword arguments are forwarded to the `lsst.pipe.base.Task`
173 constructor.
175 Notes
176 -----
177 Each instance of `RawIngestTask` writes to the same Butler. Each
178 invocation of `RawIngestTask.run` ingests a list of files.
179 """
181 ConfigClass = RawIngestConfig
183 _DefaultName = "ingest"
185 def getDatasetType(self):
186 """Return the DatasetType of the datasets ingested by this Task.
187 """
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):
192 config.validate() # Not a CmdlineTask nor PipelineTask, so have to validate the config here.
193 super().__init__(config, **kwargs)
194 self.butler = butler
195 self.universe = self.butler.registry.dimensions
196 self.datasetType = self.getDatasetType()
198 # Import all the instrument classes so that we ensure that we
199 # have all the relevant metadata translators loaded.
200 Instrument.importAll(self.butler.registry)
202 def extractMetadata(self, filename: str) -> RawFileData:
203 """Extract and process metadata from a single raw file.
205 Parameters
206 ----------
207 filename : `str`
208 Path to the file.
210 Returns
211 -------
212 data : `RawFileData`
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.
218 Notes
219 -----
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.
223 """
224 # Manually merge the primary and "first data" headers here because we
225 # do not know in general if an input file has set INHERIT=T.
226 phdu = readMetadata(filename, 0)
227 header = merge_headers([phdu, readMetadata(filename)], mode="overwrite")
228 fix_header(header)
229 datasets = [self._calculate_dataset_info(header, filename)]
231 # The data model currently assumes that whilst multiple datasets
232 # can be associated with a single file, they must all share the
233 # same formatter.
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.
243 Parameters
244 ----------
245 header : `Mapping`
246 Header from the dataset.
247 filename : `str`
248 Filename to use for error messages.
250 Returns
251 -------
252 dataset : `RawFileDatasetInfo`
253 The dataId, and observation information associated with this
254 dataset.
255 """
256 obsInfo = ObservationInfo(header)
257 dataId = DataCoordinate.standardize(instrument=obsInfo.instrument,
258 exposure=obsInfo.exposure_id,
259 detector=obsInfo.detector_num,
260 universe=self.universe)
261 return RawFileDatasetInfo(obsInfo=obsInfo, dataId=dataId)
263 def groupByExposure(self, files: Iterable[RawFileData]) -> List[RawExposureData]:
264 """Group an iterable of `RawFileData` by exposure.
266 Parameters
267 ----------
268 files : iterable of `RawFileData`
269 File-level information to group.
271 Returns
272 -------
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.
278 """
279 exposureDimensions = self.universe["exposure"].graph
280 byExposure = defaultdict(list)
281 for f in files:
282 # Assume that the first dataset is representative for the file
283 byExposure[f.datasets[0].dataId.subset(exposureDimensions)].append(f)
285 return [RawExposureData(dataId=dataId, files=exposureFiles, universe=self.universe)
286 for dataId, exposureFiles in byExposure.items()]
288 def expandDataIds(self, data: RawExposureData) -> RawExposureData:
289 """Expand the data IDs associated with a raw exposure to include
290 additional metadata records.
292 Parameters
293 ----------
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.
299 Returns
300 -------
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.
305 """
306 # We start by expanded the exposure-level data ID; we won't use that
307 # directly in file ingest, but this lets us do some database lookups
308 # once per exposure instead of once per file later.
309 data.dataId = self.butler.registry.expandDataId(
310 data.dataId,
311 # We pass in the records we'll be inserting shortly so they aren't
312 # looked up from the database. We do expect instrument and filter
313 # records to be retrieved from the database here (though the
314 # Registry may cache them so there isn't a lookup every time).
315 records={
316 self.butler.registry.dimensions["exposure"]: data.record,
317 }
318 )
319 # Now we expand the per-file (exposure+detector) data IDs. This time
320 # we pass in the records we just retrieved from the exposure data ID
321 # expansion.
322 for file in data.files:
323 for dataset in file.datasets:
324 dataset.dataId = self.butler.registry.expandDataId(
325 dataset.dataId,
326 records=dict(data.dataId.records)
327 )
328 return data
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.
334 Parameters
335 ----------
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
341 operations.
342 processes : `int`, optional
343 The number of processes to use. Ignored if ``pool`` is not `None`.
345 Yields
346 ------
347 exposure : `RawExposureData`
348 Data structures containing dimension records, filenames, and data
349 IDs to be ingested (one structure for each exposure).
350 """
351 if pool is None and processes > 1:
352 pool = Pool(processes)
353 mapFunc = map if pool is None else pool.imap_unordered
355 # Extract metadata and build per-detector regions.
356 fileData: Iterator[RawFileData] = mapFunc(self.extractMetadata, files)
358 # Use that metadata to group files (and extracted metadata) by
359 # exposure. Never parallelized because it's intrinsically a gather
360 # step.
361 exposureData: List[RawExposureData] = self.groupByExposure(fileData)
363 # The next operation operates on RawExposureData instances (one at
364 # a time) in-place and then returns the modified instance. We call it
365 # as a pass-through instead of relying on the arguments we pass in to
366 # have been modified because in the parallel case those arguments are
367 # going to be pickled and unpickled, and I'm not certain
368 # multiprocessing is careful enough with that for output arguments to
369 # work.
371 # Expand the data IDs to include all dimension metadata; we need this
372 # because we may need to generate path templates that rely on that
373 # metadata.
374 # This is the first step that involves actual database calls (but just
375 # SELECTs), so if there's going to be a problem with connections vs.
376 # multiple processes, or lock contention (in SQLite) slowing things
377 # down, it'll happen here.
378 return mapFunc(self.expandDataIds, exposureData)
380 def ingestExposureDatasets(self, exposure: RawExposureData, *, run: Optional[str] = None
381 ) -> List[DatasetRef]:
382 """Ingest all raw files in one exposure.
384 Parameters
385 ----------
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
392 ``self.butler.run``.
394 Returns
395 -------
396 refs : `list` of `lsst.daf.butler.DatasetRef`
397 Dataset references for ingested raws.
398 """
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.
415 Parameters
416 ----------
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
422 operations.
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 ``self.butler.run``.
429 Returns
430 -------
431 refs : `list` of `lsst.daf.butler.DatasetRef`
432 Dataset references for ingested raws.
434 Notes
435 -----
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.
442 """
443 exposureData = self.prep(files, pool=pool, processes=processes)
444 # Up to this point, we haven't modified the data repository at all.
445 # Now we finally do that, with one transaction per exposure. This is
446 # not parallelized at present because the performance of this step is
447 # limited by the database server. That may or may not change in the
448 # future once we increase our usage of bulk inserts and reduce our
449 # usage of savepoints; we've tried to get everything but the database
450 # operations done in advance to reduce the time spent inside
451 # transactions.
452 self.butler.registry.registerDatasetType(self.datasetType)
453 refs = []
454 for exposure in exposureData:
455 self.butler.registry.syncDimensionData("exposure", exposure.record)
456 with self.butler.transaction():
457 refs.extend(self.ingestExposureDatasets(exposure, run=run))
458 return refs