Coverage for python / lsst / obs / base / ingest.py: 14%
509 statements
« prev ^ index » next coverage.py v7.13.2, created at 2026-02-11 01:17 -0800
« prev ^ index » next coverage.py v7.13.2, created at 2026-02-11 01:17 -0800
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/>.
22from __future__ import annotations
24__all__ = (
25 "RawExposureData",
26 "RawFileData",
27 "RawFileDatasetInfo",
28 "RawIngestConfig",
29 "RawIngestTask",
30 "makeTransferChoiceField",
31)
33import concurrent.futures
34import contextlib
35import json
36import logging
37import re
38import warnings
39import zipfile
40from collections import defaultdict
41from collections.abc import Callable, Iterable, Iterator, MutableMapping, Sequence, Sized
42from contextlib import contextmanager
43from dataclasses import InitVar, dataclass
44from typing import Any, ClassVar, cast
46from astro_metadata_translator import MetadataTranslator, ObservationInfo, merge_headers
47from astro_metadata_translator.indexing import process_index_data, process_sidecar_data
48from pydantic import BaseModel
50from lsst.afw.fits import readMetadata
51from lsst.daf.butler import (
52 Butler,
53 CollectionType,
54 DataCoordinate,
55 DatasetIdGenEnum,
56 DatasetRef,
57 DatasetType,
58 DimensionRecord,
59 DimensionUniverse,
60 FileDataset,
61 Formatter,
62 FormatterV2,
63 Progress,
64 Timespan,
65)
66from lsst.daf.butler.datastores.file_datastore.retrieve_artifacts import ZipIndex
67from lsst.pex.config import ChoiceField, Config, Field
68from lsst.pipe.base import Instrument, Task
69from lsst.resources import ResourcePath, ResourcePathExpression
70from lsst.utils.logging import LsstLoggers
71from lsst.utils.timer import time_this, timeMethod
73from ._instrument import makeExposureRecordFromObsInfo
76def _do_nothing(*args: Any, **kwargs: Any) -> None:
77 """Do nothing.
79 This is a function that accepts anything and does nothing.
80 For use as a default in callback arguments.
81 """
82 pass
85def _log_msg_counter(noun: int | Sized) -> tuple[int, str]:
86 """Count the iterable and return the count and plural modifier.
88 Parameters
89 ----------
90 noun : `Sized` or `int`
91 Thing to count. If given an integer it is assumed to be the count
92 to use to calculate modifier.
94 Returns
95 -------
96 num : `int`
97 Number of items found in ``noun``.
98 modifier : `str`
99 Character to add to the end of a string referring to these items
100 to indicate whether it was a single item or not. Returns empty
101 string if there is one item or "s" otherwise.
103 Examples
104 --------
105 .. code-block:: python
107 log.warning("Found %d file%s", *_log_msg_counter(nfiles))
108 """
109 if isinstance(noun, int):
110 num = noun
111 else:
112 num = len(noun)
113 return num, "" if num == 1 else "s"
116class IngestMetrics(BaseModel):
117 """Metrics collected during raw ingest."""
119 time_for_metadata: float = 0.0
120 """Wall-clock time, in seconds, spent gathering file metadata."""
122 time_for_records: float = 0.0
123 """Wall-clock time, in seconds, spent writing dimension records."""
125 time_for_ingest: float = 0.0
126 """Wall-clock time, in seconds, spent calling butler ingest."""
128 time_for_callbacks: float = 0.0
129 """Wall-clock time, in seconds, processing user-supplied callbacks."""
131 def reset(self) -> None:
132 """Reset all metrics to initial values."""
133 self.time_for_ingest = 0.0
134 self.time_for_records = 0.0
135 self.time_for_metadata = 0.0
136 self.time_for_callbacks = 0.0
138 @contextmanager
139 def collect_metric(
140 self,
141 property: str,
142 log: LsstLoggers | None = None,
143 msg: str | None = None,
144 args: tuple[Any, ...] = (),
145 ) -> Iterator[None]:
146 with time_this(log=log, msg=msg, args=args, level=logging.INFO) as timer:
147 yield
148 setattr(self, property, getattr(self, property) + timer.duration)
151@dataclass
152class RawFileDatasetInfo:
153 """Information about a single dataset within a raw file."""
155 dataId: DataCoordinate
156 """Data ID for this file (`lsst.daf.butler.DataCoordinate`)."""
158 obsInfo: ObservationInfo
159 """Standardized observation metadata extracted directly from the file
160 headers (`astro_metadata_translator.ObservationInfo`).
161 """
164@dataclass
165class RawFileData:
166 """Information about a single raw file, used during ingest."""
168 datasets: list[RawFileDatasetInfo]
169 """The information describing each dataset within this raw file.
170 (`list` of `RawFileDatasetInfo`)
171 """
173 filename: ResourcePath
174 """URI of the file this information was extracted from (`str`).
176 This is the path prior to ingest, not the path after ingest.
177 """
179 FormatterClass: type[Formatter]
180 """Formatter class that should be used to ingest this file (`type`; as
181 subclass of `~lsst.daf.butler.Formatter`).
182 """
184 instrument: Instrument | None
185 """The `Instrument` instance associated with this file. Can be `None`
186 if ``datasets`` is an empty list."""
189@dataclass
190class RawExposureData:
191 """Information about a complete raw exposure, used during ingest."""
193 dataId: DataCoordinate
194 """Data ID for this exposure (`lsst.daf.butler.DataCoordinate`).
195 """
197 files: list[RawFileData]
198 """List of structures containing file-level information.
199 """
201 universe: InitVar[DimensionUniverse]
202 """Set of all known dimensions.
203 """
205 record: DimensionRecord
206 """The exposure `~lsst.daf.butler.DimensionRecord` that must be inserted
207 into the `~lsst.daf.butler.Registry` prior to file-level ingest
208 (`~lsst.daf.butler.DimensionRecord`).
209 """
211 dependencyRecords: dict[str, DimensionRecord]
212 """Additional records that must be inserted into the
213 `~lsst.daf.butler.Registry` prior to ingesting the exposure ``record``
214 (e.g., to satisfy foreign key constraints), indexed by the dimension name.
215 """
218def makeTransferChoiceField(
219 doc: str = "How to transfer files (None for no transfer).", default: str = "auto"
220) -> ChoiceField:
221 """Create a Config field with options for transferring data between repos.
223 The allowed options for the field are exactly those supported by
224 `lsst.daf.butler.Datastore.ingest`.
226 Parameters
227 ----------
228 doc : `str`
229 Documentation for the configuration field.
230 default : `str`, optional
231 Default transfer mode for the field.
233 Returns
234 -------
235 field : `lsst.pex.config.ChoiceField`
236 Configuration field.
237 """
238 return ChoiceField(
239 doc=doc,
240 dtype=str,
241 allowed={
242 "move": "move",
243 "copy": "copy",
244 "auto": "choice will depend on datastore",
245 "direct": "use URI to ingested file directly in datastore",
246 "link": "hard link falling back to symbolic link",
247 "hardlink": "hard link",
248 "symlink": "symbolic (soft) link",
249 "relsymlink": "relative symbolic link",
250 },
251 optional=True,
252 default=default,
253 )
256class RawIngestConfig(Config):
257 """Configuration class for RawIngestTask."""
259 transfer = makeTransferChoiceField()
260 failFast: Field[bool] = Field(
261 dtype=bool,
262 default=False,
263 doc="If True, stop ingest as soon as any problem is encountered with any file. "
264 "Otherwise problem files will be skipped and logged and a report issued at completion.",
265 )
268class RawIngestTask(Task):
269 """Driver Task for ingesting raw data into Gen3 Butler repositories.
271 Parameters
272 ----------
273 config : `RawIngestConfig`
274 Configuration for the task.
275 butler : `~lsst.daf.butler.Butler`
276 Writeable butler instance, with ``butler.run`` set to the appropriate
277 `~lsst.daf.butler.CollectionType.RUN` collection for these raw
278 datasets.
279 on_success : `collections.abc.Callable`, optional
280 A callback invoked when all of the raws associated with an exposure
281 are ingested. Will be passed a list of `~lsst.daf.butler.FileDataset`
282 objects, each containing one or more resolved
283 `~lsst.daf.butler.DatasetRef` objects. If this callback raises it will
284 interrupt the entire ingest process, even if `RawIngestConfig.failFast`
285 is `False`.
286 on_metadata_failure : `collections.abc.Callable`, optional
287 A callback invoked when a failure occurs trying to translate the
288 metadata for a file. Will be passed the URI and the exception, in
289 that order, as positional arguments. Guaranteed to be called in an
290 ``except`` block, allowing the callback to re-raise or replace (with
291 ``raise ... from``) to override the task's usual error handling (before
292 `RawIngestConfig.failFast` logic occurs). This callback can be called
293 from within a worker thread if multiple workers have been requested.
294 Ensure that any code within the call back is thread-safe.
295 on_ingest_failure : `collections.abc.Callable`, optional
296 A callback invoked when dimension record or dataset insertion into the
297 database fails for an exposure. Will be passed a `RawExposureData`
298 instance and the exception, in that order, as positional arguments.
299 Guaranteed to be called in an ``except`` block, allowing the callback
300 to re-raise or replace (with ``raise ... from``) to override the task's
301 usual error handling (before `RawIngestConfig.failFast` logic occurs).
302 on_exposure_record : `collections.abc.Callable`, optional
303 A callback invoked when an exposure dimension record has been created
304 or modified. Will not be called if the record already existed. Will
305 be called with the exposure record.
306 **kwargs
307 Additional keyword arguments are forwarded to the `lsst.pipe.base.Task`
308 constructor.
310 Notes
311 -----
312 Each instance of `RawIngestTask` writes to the same Butler. Each
313 invocation of `RawIngestTask.run` ingests a list of files.
314 """
316 ConfigClass: ClassVar[type[Config]] = RawIngestConfig
318 _DefaultName: ClassVar[str] = "ingest"
320 def getDatasetType(self) -> DatasetType:
321 """Return the default DatasetType of the datasets ingested by this
322 Task.
324 Returns
325 -------
326 datasetType : `lsst.daf.butler.DatasetType`
327 The default dataset type to use for the data being ingested. This
328 is only used if the relevant `~lsst.pipe.base.Instrument` does not
329 define an override.
330 """
331 return DatasetType(
332 "raw",
333 ("instrument", "detector", "exposure"),
334 "Exposure",
335 universe=self.butler.dimensions,
336 )
338 # Mypy can not determine that the config passed to super() is this type.
339 config: RawIngestConfig
341 def __init__(
342 self,
343 config: RawIngestConfig,
344 *,
345 butler: Butler,
346 on_success: Callable[[list[FileDataset]], Any] = _do_nothing,
347 on_metadata_failure: Callable[[ResourcePath, Exception], Any] = _do_nothing,
348 on_ingest_failure: Callable[[RawExposureData, Exception], Any] = _do_nothing,
349 on_exposure_record: Callable[[DimensionRecord], Any] = _do_nothing,
350 **kwargs: Any,
351 ):
352 config.validate() # Not a CmdlineTask nor PipelineTask, so have to validate the config here.
353 super().__init__(config, **kwargs)
354 self.butler = butler
355 self.universe = self.butler.dimensions
356 self.datasetType = self.getDatasetType()
357 self._on_success = on_success
358 self._on_exposure_record = on_exposure_record
359 self._on_metadata_failure = on_metadata_failure
360 self._on_ingest_failure = on_ingest_failure
361 self.progress = Progress("obs.base.RawIngestTask")
363 # Import all the instrument classes so that we ensure that we
364 # have all the relevant metadata translators loaded.
365 self.instruments = Instrument.importAll(self.butler.registry)
367 # Read all the instrument records into a cache since they will be
368 # needed later to calculate day_obs timespans, if appropriate.
369 self._instrument_records = {
370 rec.name: rec for rec in butler.registry.queryDimensionRecords("instrument")
371 }
372 # Create empty metrics.
373 self.metrics = IngestMetrics()
375 def _reduce_kwargs(self) -> dict[str, Any]:
376 # Add extra parameters to pickle.
377 return dict(
378 **super()._reduce_kwargs(),
379 butler=self.butler,
380 on_success=self._on_success,
381 on_metadata_failure=self._on_metadata_failure,
382 on_ingest_failure=self._on_ingest_failure,
383 on_exposure_record=self._on_exposure_record,
384 )
386 def _determine_instrument_formatter(
387 self, dataId: DataCoordinate, filename: ResourcePath
388 ) -> tuple[Instrument | None, type[Formatter | FormatterV2]]:
389 """Determine the instrument and formatter class.
391 Parameters
392 ----------
393 dataId : `lsst.daf.butler.DataCoordinate`
394 The dataId associated with this dataset.
395 filename : `lsst.resources.ResourcePath`
396 URI of file used for error reporting.
398 Returns
399 -------
400 instrument : `Instrument` or `None`
401 Instance of the `Instrument` associated with this dataset. `None`
402 indicates that the instrument could not be determined.
403 formatterClass : `type`
404 Class to be used as the formatter for this dataset.
406 Notes
407 -----
408 Does not access butler registry since it may be called from threads.
409 """
410 # The data model currently assumes that whilst multiple datasets
411 # can be associated with a single file, they must all share the
412 # same formatter.
413 FormatterClass: type[Formatter | FormatterV2] = Formatter
414 try:
415 instrument_name = cast(str, dataId["instrument"])
416 instrument = self.instruments[instrument_name]()
417 except LookupError as e:
418 self._on_metadata_failure(filename, e)
419 self.log.warning(
420 "Instrument %s for file %s not known to registry", dataId["instrument"], filename
421 )
422 if self.config.failFast:
423 raise RuntimeError(
424 f"Instrument {dataId['instrument']} for file {filename} not known to registry"
425 ) from e
426 # Indicate that we could not work out the instrument.
427 instrument = None
428 else:
429 assert instrument is not None, "Should be guaranted by fromName succeeding."
430 FormatterClass = instrument.getRawFormatter(dataId)
431 return instrument, FormatterClass
433 def get_raw_datasetType(
434 self, instrument: Instrument, cache: dict[str, DatasetType] | None = None
435 ) -> DatasetType:
436 """Get the raw dataset type associated with this ingest.
438 Parameters
439 ----------
440 instrument : `Instrument`
441 Class that might specify an override of the default raw dataset
442 type. If no override is specified the task default will be used.
443 cache : `dict` [`str`, `lsst.daf.butler.DatasetType`] \
444 or `None`, optional
445 An optional cache that can be used to return a pre-existing
446 dataset type. Is not updated.
448 Returns
449 -------
450 lsst.daf.butler.DatasetType
451 The dataset type to use for raw ingest of this instrument.
452 """
453 if cache is None:
454 cache = {}
455 if raw_definition := getattr(instrument, "raw_definition", None):
456 datasetTypeName, dimensions, storageClass = raw_definition
457 if not (datasetType := cache.get(datasetTypeName)):
458 datasetType = DatasetType(
459 datasetTypeName, dimensions, storageClass, universe=self.butler.dimensions
460 )
461 else:
462 datasetType = self.datasetType
463 return datasetType
465 def extractMetadata(self, filename: ResourcePath) -> RawFileData:
466 """Extract and process metadata from a single raw file.
468 Parameters
469 ----------
470 filename : `lsst.resources.ResourcePath`
471 URI to the file.
473 Returns
474 -------
475 data : `RawFileData`
476 A structure containing the metadata extracted from the file,
477 as well as the original filename. All fields will be populated,
478 but the `RawFileDatasetInfo.dataId` attribute will be a minimal
479 (unexpanded) `~lsst.daf.butler.DataCoordinate` instance. The
480 ``instrument`` field will be `None` if there is a problem
481 with metadata extraction.
483 Notes
484 -----
485 Assumes that there is a single dataset associated with the given
486 file. Instruments using a single file to store multiple datasets
487 must implement their own version of this method.
489 By default the method will catch all exceptions unless the
490 `RawIngestConfig.failFast` configuration item is `True`. If an error
491 is encountered the supplied ``on_metadata_failure()``
492 method will be called. If no exceptions result and an error was
493 encountered the returned object will have a null-instrument class and
494 no datasets.
496 This method supports sidecar JSON files which can be used to
497 extract metadata without having to read the data file itself.
498 The sidecar file is always used if found.
499 """
500 formatterClass: type[Formatter | FormatterV2]
501 sidecar_fail_msg = "" # Requires prepended space when set.
502 try:
503 sidecar_file = filename.updatedExtension(".json")
504 headers = []
505 with contextlib.suppress(Exception):
506 # Try to read directly, bypassing existence check.
507 content = json.loads(sidecar_file.read())
508 headers = [process_sidecar_data(content)]
509 sidecar_fail_msg = " (via sidecar)"
510 if not headers:
511 # Read the metadata from the data file itself.
513 # For remote files download the entire file to get the
514 # header. This is very inefficient and it would be better
515 # to have some way of knowing where in the file the headers
516 # are and to only download those parts of the file.
517 with filename.as_local() as local_file:
518 # Read the primary. This might be sufficient.
519 header = readMetadata(local_file.ospath, 0)
520 translator_class = None
522 try:
523 # Try to work out a translator class early.
524 translator_class = MetadataTranslator.determine_translator(
525 header, filename=str(filename)
526 )
527 except ValueError:
528 # Primary header was not sufficient (maybe this file
529 # has been compressed or is a MEF with minimal
530 # primary). Read second header and merge with primary.
531 header = merge_headers([header, readMetadata(local_file.ospath, 1)], mode="overwrite")
533 # Try again to work out a translator class, letting this
534 # fail.
535 if translator_class is None:
536 translator_class = MetadataTranslator.determine_translator(
537 header, filename=str(filename)
538 )
540 # Request the headers to use for ingest
541 headers = list(translator_class.determine_translatable_headers(local_file.ospath, header))
543 # Add each header to the dataset list
544 datasets = [self._calculate_dataset_info(h, filename) for h in headers]
546 except Exception as e:
547 self.log.debug("Problem extracting metadata from %s%s: %s", filename, sidecar_fail_msg, e)
548 # Indicate to the caller that we failed to read.
549 datasets = []
550 formatterClass = Formatter
551 instrument = None
552 self._on_metadata_failure(filename, e)
553 if self.config.failFast:
554 raise RuntimeError(
555 f"Problem extracting metadata for file {filename}{sidecar_fail_msg}"
556 ) from e
557 else:
558 self.log.debug("Extracted metadata for file %s%s", filename, sidecar_fail_msg)
559 # The data model currently assumes that whilst multiple datasets
560 # can be associated with a single file, they must all share the
561 # same formatter.
562 instrument, formatterClass = self._determine_instrument_formatter(datasets[0].dataId, filename)
563 if instrument is None:
564 datasets = []
566 return RawFileData(
567 datasets=datasets,
568 filename=filename,
569 # MyPy wants this to be a non-abstract class, which is not true
570 # for the error case where instrument is None and datasets=[].
571 FormatterClass=formatterClass, # type: ignore
572 instrument=instrument,
573 )
575 @classmethod
576 def getObservationInfoSubsets(cls) -> tuple[set, set]:
577 """Return subsets of fields in the
578 `~astro_metadata_translator.ObservationInfo` that we care about.
580 These fields will be used in constructing an exposure record.
582 Returns
583 -------
584 required : `set`
585 Set of `~astro_metadata_translator.ObservationInfo` field names
586 that are required.
587 optional : `set`
588 Set of `~astro_metadata_translator.ObservationInfo` field names
589 we will use if they are available.
590 """
591 # Marking the new properties "group_counter_*" and
592 # "has_simulated_content" as required, assumes that we either
593 # recreate any existing index/sidecar files that include translated
594 # values, or else allow astro_metadata_translator to fill in
595 # defaults.
596 required = {
597 "datetime_begin",
598 "datetime_end",
599 "detector_num",
600 "exposure_group",
601 "exposure_id",
602 "exposure_time_requested",
603 "group_counter_end",
604 "group_counter_start",
605 "has_simulated_content",
606 "instrument",
607 "observation_id",
608 "observation_type",
609 "observing_day",
610 "physical_filter",
611 }
612 optional = {
613 "altaz_begin",
614 "boresight_rotation_coord",
615 "boresight_rotation_angle",
616 "dark_time",
617 "tracking_radec",
618 "object",
619 "observation_counter",
620 "observation_reason",
621 "observing_day_offset",
622 "science_program",
623 "visit_id",
624 "can_see_sky",
625 }
626 return required, optional
628 def _calculate_dataset_info(
629 self, header: MutableMapping[str, Any] | ObservationInfo, filename: ResourcePath
630 ) -> RawFileDatasetInfo:
631 """Calculate a RawFileDatasetInfo from the supplied information.
633 Parameters
634 ----------
635 header : Mapping or `astro_metadata_translator.ObservationInfo`
636 Header from the dataset or previously-translated content.
637 filename : `lsst.resources.ResourcePath`
638 Filename to use for error messages.
640 Returns
641 -------
642 dataset : `RawFileDatasetInfo`
643 The dataId, and observation information associated with this
644 dataset.
645 """
646 required, optional = self.getObservationInfoSubsets()
647 if isinstance(header, ObservationInfo):
648 obsInfo = header
649 missing = []
650 # Need to check the required properties are present.
651 for property in required:
652 # getattr does not need to be protected because it is using
653 # the defined list above containing properties that must exist.
654 value = getattr(obsInfo, property)
655 if value is None:
656 missing.append(property)
657 if missing:
658 raise ValueError(
659 f"Requested required properties are missing from file {filename}: {missing} (via JSON)"
660 )
662 else:
663 obsInfo = ObservationInfo(
664 header,
665 pedantic=False,
666 filename=str(filename),
667 required=required,
668 subset=required | optional,
669 )
671 dataId = DataCoordinate.standardize(
672 instrument=obsInfo.instrument,
673 exposure=obsInfo.exposure_id,
674 detector=obsInfo.detector_num,
675 universe=self.universe,
676 )
677 return RawFileDatasetInfo(obsInfo=obsInfo, dataId=dataId)
679 def readZipIndexFiles(
680 self, files: Iterable[ResourcePath]
681 ) -> tuple[list[RawFileData], list[ResourcePath], set[ResourcePath], set[ResourcePath]]:
682 """Given a list of files, filter out zip files and look for index files
683 inside.
685 Parameters
686 ----------
687 files : `~collections.abc.Iterable` [ `lsst.resources.ResourcePath` ]
688 URIs to the files to be ingested.
690 Returns
691 -------
692 index : `dict` [ `lsst.resources.ResourcePath`, `typing.Any` ]
693 Merged contents of all relevant index files found in zip files.
694 The keys include the path to the data file within the zip using
695 the butler fragment convention of ``zip-path=PATH``.
696 updated_files : `list` [ `lsst.resources.ResourcePath` ]
697 Updated list of the input files with zip entries removed.
698 good_index_files: `set` [ `lsst.resources.ResourcePath` ]
699 Zip files that contained index information.
700 bad_zip_files: `set` [ `lsst.resources.ResourcePath` ]
701 Zip files that contained no index information.
702 """
703 zip_metadata_index = "_metadata_index.json"
705 # Files that weren't zip files.
706 updated_files: list[ResourcePath] = []
708 # Index files we failed to read.
709 bad_index_files: set[ResourcePath] = set()
711 # Any good index files that were found and used.
712 good_index_files: set[ResourcePath] = set()
714 # Processed content from any zip files.
715 indexFileData: list[RawFileData] = []
717 for file in files:
718 if file.getExtension() != ".zip":
719 updated_files.append(file)
720 continue
722 zip_info: dict[str, zipfile.ZipInfo] = {}
723 try:
724 with file.open("rb") as fd, zipfile.ZipFile(fd) as zf:
725 zip_info = {info.filename: info for info in zf.infolist()}
726 content = json.loads(zf.read(zip_metadata_index))
727 index = process_index_data(content, force_dict=True)
728 assert isinstance(index, MutableMapping)
730 # Try to read the ZipIndex.
731 zip_index = ZipIndex.from_open_zip(zf)
732 except Exception as e:
733 if self.config.failFast:
734 raise RuntimeError(f"Problem reading index file from zip file at {file}") from e
735 bad_index_files.add(file)
736 continue
737 self.log.debug("Extracted index metadata from zip file %s", str(file))
739 # All the metadata read from this index file with keys of full
740 # path.
741 index_entries: dict[ResourcePath, Any] = {}
743 # In theory we could scan for JSON sidecar files associated with
744 # any files not found in the metadata index, but that is not meant
745 # to be possible. Guider data is another issue not handled by
746 # this code.
747 for path_in_zip in index:
748 if path_in_zip not in zip_info:
749 # Index entry exists but no file for it.
750 self.log.info("File {path_in_zip} is in zip index but not in zip file {file}. Ignoring.")
751 continue
752 file_to_ingest = file.replace(fragment=f"zip-path={path_in_zip}")
753 index_entries[file_to_ingest] = index[path_in_zip]
755 file_data = self.processIndexEntries(index_entries)
757 # Validate that the index entries we have read match the
758 # values in the butler zip index.
759 data_ids_from_index: dict[str, tuple[DataCoordinate, ...]] = {}
760 for f in file_data:
761 _, path_in_zip = f.filename.fragment.split("=")
762 data_ids_from_index[path_in_zip] = tuple(d.dataId for d in f.datasets)
764 data_ids_from_butler_index: dict[str, tuple[DataCoordinate, ...]] = {}
765 # Refs indexed by UUID.
766 refs = zip_index.refs.to_refs(universe=self.universe)
767 id_to_ref = {ref.id: ref for ref in refs}
768 for path_in_zip, index_info in zip_index.artifact_map.items():
769 data_ids_from_butler_index[path_in_zip] = tuple(
770 id_to_ref[id_].dataId for id_ in index_info.ids
771 )
773 if data_ids_from_butler_index != data_ids_from_index:
774 self.log.warning(
775 "Recalculating the Data IDs for zip file %s (which may include new metadata corrections) "
776 "results in a difference to the Data IDs recorded in the butler index in that zip. "
777 "Consider remaking the zipped raws.",
778 file,
779 )
781 indexFileData.extend(file_data)
783 return indexFileData, updated_files, good_index_files, bad_index_files
785 def locateAndReadIndexFiles(
786 self, files: Iterable[ResourcePath]
787 ) -> tuple[dict[ResourcePath, Any], list[ResourcePath], set[ResourcePath], set[ResourcePath]]:
788 """Given a list of files, look for index files and read them.
790 Index files can either be explicitly in the list of files to
791 ingest, or else located in the same directory as a file to ingest.
792 Index entries are always used if present.
794 Parameters
795 ----------
796 files : `~collections.abc.Iterable` [ `lsst.resources.ResourcePath` ]
797 URIs to the files to be ingested.
799 Returns
800 -------
801 index : `dict` [ `lsst.resources.ResourcePath`, `typing.Any` ]
802 Merged contents of all relevant index files found. These can
803 be explicitly specified index files or ones found in the
804 directory alongside a data file to be ingested.
805 updated_files : `list` [ `lsst.resources.ResourcePath` ]
806 Updated list of the input files with entries removed that were
807 found listed in an index file. Order is not guaranteed to
808 match the order of the files given to this routine.
809 good_index_files: `set` [ `lsst.resources.ResourcePath` ]
810 Index files that were successfully read.
811 bad_index_files: `set` [ `lsst.resources.ResourcePath` ]
812 Files that looked like index files but failed to read properly.
813 """
814 # Convert the paths to absolute for easy comparison with index content.
815 # Do not convert to real paths since we have to assume that index
816 # files are in this location and not the location which it links to.
817 files = tuple(f.abspath() for f in files)
819 # Index files must be named this.
820 index_root_file = "_index.json"
822 # Group the files by directory.
823 files_by_directory: dict[ResourcePath, set[str]] = defaultdict(set)
825 for path in files:
826 directory, file_in_dir = path.split()
827 files_by_directory[directory].add(file_in_dir)
829 # All the metadata read from index files with keys of full path.
830 index_entries: dict[ResourcePath, Any] = {}
832 # Index files we failed to read.
833 bad_index_files: set[ResourcePath] = set()
835 # Any good index files that were found and used.
836 good_index_files: set[ResourcePath] = set()
838 # Look for index files in those directories.
839 for directory, files_in_directory in files_by_directory.items():
840 possible_index_file = directory.join(index_root_file)
841 if possible_index_file.exists():
842 # If we are explicitly requesting an index file the
843 # messages should be different.
844 index_msg = "inferred"
845 is_implied = True
846 if index_root_file in files_in_directory:
847 index_msg = "explicit"
848 is_implied = False
850 # Try to read the index file and catch and report any
851 # problems.
852 try:
853 content = json.loads(possible_index_file.read())
854 index = process_index_data(content, force_dict=True)
855 # mypy should in theory know that this is a mapping
856 # from the overload type annotation of process_index_data.
857 assert isinstance(index, MutableMapping)
858 except Exception as e:
859 # Only trigger the callback if the index file
860 # was asked for explicitly. Triggering on implied file
861 # might be surprising.
862 if not is_implied:
863 self._on_metadata_failure(possible_index_file, e)
864 if self.config.failFast:
865 raise RuntimeError(
866 f"Problem reading index file from {index_msg} location {possible_index_file}"
867 ) from e
868 bad_index_files.add(possible_index_file)
869 continue
871 self.log.debug("Extracted index metadata from %s file %s", index_msg, possible_index_file)
872 good_index_files.add(possible_index_file)
874 # Go through the index adding entries for files.
875 # If we have non-index files in this directory marked for
876 # ingest we should only get index information for those.
877 # If the index file was explicit we use all entries.
878 if is_implied:
879 files_to_ingest = files_in_directory
880 else:
881 files_to_ingest = set(index)
883 # Copy relevant metadata into a single dict for all index
884 # entries.
885 for file_in_dir in files_to_ingest:
886 # Skip an explicitly specified index file.
887 # This should never happen because an explicit index
888 # file will force ingest of all files in the index
889 # and not use the explicit file list. If somehow
890 # this is not true we continue. Raising an exception
891 # seems like the wrong thing to do since this is harmless.
892 if file_in_dir == index_root_file:
893 self.log.info(
894 "Logic error found scanning directory %s. Please file ticket.", directory
895 )
896 continue
897 if file_in_dir in index:
898 file = directory.join(file_in_dir)
899 if file in index_entries:
900 # ObservationInfo overrides raw metadata
901 if isinstance(index[file_in_dir], ObservationInfo) and not isinstance(
902 index_entries[file], ObservationInfo
903 ):
904 self.log.warning(
905 "File %s already specified in an index file but overriding"
906 " with ObservationInfo content from %s",
907 file,
908 possible_index_file,
909 )
910 else:
911 self.log.warning(
912 "File %s already specified in an index file, ignoring content from %s",
913 file,
914 possible_index_file,
915 )
916 # Do nothing in this case
917 continue
919 index_entries[file] = index[file_in_dir]
921 # Remove files from list that have index entries and also
922 # any files that we determined to be explicit index files
923 # or any index files that we failed to read.
924 filtered = set(files) - set(index_entries) - good_index_files - bad_index_files
926 # The filtered list loses the initial order. Retaining the order
927 # is good for testing but does have a cost if there are many
928 # files when copying the good values out. A dict would have faster
929 # lookups (using the files as keys) but use more memory.
930 ordered = [f for f in filtered if f in files]
932 return index_entries, ordered, good_index_files, bad_index_files
934 def processIndexEntries(self, index_entries: dict[ResourcePath, Any]) -> list[RawFileData]:
935 """Convert index entries to RawFileData.
937 Parameters
938 ----------
939 index_entries : `dict` [`lsst.resources.ResourcePath`, `typing.Any`]
940 Dict indexed by name of file to ingest and with keys either
941 raw metadata or translated
942 `~astro_metadata_translator.ObservationInfo`.
944 Returns
945 -------
946 data : `list` [ `RawFileData` ]
947 Structures containing the metadata extracted from the file,
948 as well as the original filename. All fields will be populated,
949 but the `RawFileDatasetInfo.dataId` attributes will be minimal
950 (unexpanded) `~lsst.daf.butler.DataCoordinate` instances.
951 """
952 formatterClass: type[Formatter | FormatterV2]
953 fileData = []
954 for filename, metadata in index_entries.items():
955 try:
956 datasets = [self._calculate_dataset_info(metadata, filename)]
957 except Exception as e:
958 self.log.debug("Problem extracting metadata for file %s found in index file: %s", filename, e)
959 datasets = []
960 formatterClass = Formatter
961 instrument = None
962 self._on_metadata_failure(filename, e)
963 if self.config.failFast:
964 raise RuntimeError(
965 f"Problem extracting metadata for file {filename} found in index file"
966 ) from e
967 else:
968 instrument, formatterClass = self._determine_instrument_formatter(
969 datasets[0].dataId, filename
970 )
971 if instrument is None:
972 datasets = []
973 fileData.append(
974 RawFileData(
975 datasets=datasets,
976 filename=filename,
977 # MyPy wants this to be a non-abstract class, which is not
978 # true for the error case where instrument is None and
979 # datasets=[].
980 FormatterClass=formatterClass, # type: ignore
981 instrument=instrument,
982 )
983 )
984 return fileData
986 def groupByExposure(self, files: Iterable[RawFileData]) -> list[RawExposureData]:
987 """Group an iterable of `RawFileData` by exposure.
989 Parameters
990 ----------
991 files : iterable of `RawFileData`
992 File-level information to group.
994 Returns
995 -------
996 exposures : `list` of `RawExposureData`
997 A list of structures that group the file-level information by
998 exposure. All fields will be populated. The
999 `RawExposureData.dataId` attributes will be minimal (unexpanded)
1000 `~lsst.daf.butler.DataCoordinate` instances.
1001 """
1002 exposureDimensions = self.universe["exposure"].minimal_group
1003 byExposure = defaultdict(list)
1004 for f in files:
1005 # Assume that the first dataset is representative for the file.
1006 byExposure[f.datasets[0].dataId.subset(exposureDimensions)].append(f)
1008 return [
1009 RawExposureData(
1010 dataId=dataId,
1011 files=exposureFiles,
1012 universe=self.universe,
1013 record=self.makeExposureRecord(exposureFiles[0].datasets[0].obsInfo, self.universe),
1014 dependencyRecords=self.makeDependencyRecords(
1015 exposureFiles[0].datasets[0].obsInfo, self.universe
1016 ),
1017 )
1018 for dataId, exposureFiles in byExposure.items()
1019 ]
1021 def makeExposureRecord(
1022 self, obsInfo: ObservationInfo, universe: DimensionUniverse, **kwargs: Any
1023 ) -> DimensionRecord:
1024 """Construct a registry record for an exposure.
1026 This is a method that subclasses will often want to customize. This can
1027 often be done by calling this base class implementation with additional
1028 ``kwargs``.
1030 Parameters
1031 ----------
1032 obsInfo : `~astro_metadata_translator.ObservationInfo`
1033 Observation details for (one of the components of) the exposure.
1034 universe : `lsst.daf.butler.DimensionUniverse`
1035 Set of all known dimensions.
1036 **kwargs
1037 Additional field values for this record.
1039 Returns
1040 -------
1041 record : `lsst.daf.butler.DimensionRecord`
1042 The exposure record that must be inserted into the
1043 `~lsst.daf.butler.Registry` prior to file-level ingest.
1044 """
1045 return makeExposureRecordFromObsInfo(obsInfo, universe, **kwargs)
1047 def makeDependencyRecords(
1048 self, obsInfo: ObservationInfo, universe: DimensionUniverse
1049 ) -> dict[str, DimensionRecord]:
1050 """Construct dependency records.
1052 These dependency records will be inserted into the
1053 `~lsst.daf.butler.Registry` before the exposure records, because they
1054 are dependencies of the exposure. This allows an opportunity to satisfy
1055 foreign key constraints that exist because of dimensions related to the
1056 exposure.
1058 This is a method that subclasses may want to customize, if they've
1059 added dimensions that relate to an exposure.
1061 Parameters
1062 ----------
1063 obsInfo : `~astro_metadata_translator.ObservationInfo`
1064 Observation details for (one of the components of) the exposure.
1065 universe : `lsst.daf.butler.DimensionUniverse`
1066 Set of all known dimensions.
1068 Returns
1069 -------
1070 records : `dict` [`str`, `lsst.daf.butler.DimensionRecord`]
1071 The records to insert, indexed by dimension name.
1072 """
1073 records: dict[str, DimensionRecord] = {}
1074 if "exposure" not in universe:
1075 return records
1076 exposure = universe["exposure"]
1077 if "group" in exposure.implied:
1078 records["group"] = universe["group"].RecordClass(
1079 name=obsInfo.exposure_group,
1080 instrument=obsInfo.instrument,
1081 )
1082 if "day_obs" in exposure.implied:
1083 if (offset := getattr(obsInfo, "observing_day_offset")) is not None:
1084 offset_int = round(offset.to_value("s"))
1085 timespan = Timespan.from_day_obs(obsInfo.observing_day, offset_int)
1086 else:
1087 timespan = None
1088 records["day_obs"] = universe["day_obs"].RecordClass(
1089 instrument=obsInfo.instrument,
1090 id=obsInfo.observing_day,
1091 timespan=timespan,
1092 )
1093 return records
1095 def expandDataIds(self, data: RawExposureData) -> RawExposureData:
1096 """Expand the data IDs associated with a raw exposure.
1098 This adds the metadata records.
1100 Parameters
1101 ----------
1102 data : `RawExposureData`
1103 A structure containing information about the exposure to be
1104 ingested. Must have `RawExposureData.record` populated. Should
1105 be considered consumed upon return.
1107 Returns
1108 -------
1109 exposure : `RawExposureData`
1110 An updated version of the input structure, with
1111 `RawExposureData.dataId` and nested `RawFileDatasetInfo.dataId`
1112 attributes updated to data IDs for which
1113 `~lsst.daf.butler.DataCoordinate.hasRecords` returns `True`.
1114 """
1115 # We start by expanded the exposure-level data ID; we won't use that
1116 # directly in file ingest, but this lets us do some database lookups
1117 # once per exposure instead of once per file later.
1118 data.dataId = self.butler.registry.expandDataId(
1119 data.dataId,
1120 # We pass in the records we'll be inserting shortly so they aren't
1121 # looked up from the database. We do expect instrument and filter
1122 # records to be retrieved from the database here (though the
1123 # Registry may cache them so there isn't a lookup every time).
1124 records={"exposure": data.record, **data.dependencyRecords},
1125 )
1126 # Now we expand the per-file (exposure+detector) data IDs. This time
1127 # we pass in the records we just retrieved from the exposure data ID
1128 # expansion.
1129 for file in data.files:
1130 for dataset in file.datasets:
1131 dataset.dataId = self.butler.registry.expandDataId(
1132 dataset.dataId,
1133 records={k: data.dataId.records[k] for k in data.dataId.dimensions.elements},
1134 )
1135 return data
1137 def prep(
1138 self,
1139 files: Iterable[ResourcePath],
1140 *,
1141 pool: concurrent.futures.ThreadPoolExecutor | None = None,
1142 search_indexes: bool = True,
1143 ) -> tuple[Iterator[RawExposureData], list[ResourcePath]]:
1144 """Perform all non-database-updating ingest preprocessing steps.
1146 Parameters
1147 ----------
1148 files : iterable over `str` or path-like objects
1149 Paths to the files to be ingested. Will be made absolute
1150 if they are not already.
1151 pool : `concurrent.futures.ThreadPoolExecutor`, optional
1152 If not `None`, a thread pool with which to parallelize some
1153 operations.
1154 search_indexes : `bool`, optional
1155 If `True` the code will search for index JSON files in given
1156 directories. If you know for a fact that index files do not exist
1157 set this to `False` for a slight speed up in metadata gathering.
1159 Returns
1160 -------
1161 exposures : `~collections.abc.Iterator` [ `RawExposureData` ]
1162 Data structures containing dimension records, filenames, and data
1163 IDs to be ingested (one structure for each exposure).
1164 bad_files : `list` of `str`
1165 List of all the files that could not have metadata extracted.
1166 """
1168 def _partition_good_bad(
1169 file_data: Iterable[RawFileData],
1170 ) -> tuple[list[RawFileData], list[ResourcePath]]:
1171 """Filter out bad files and return good with list of bad."""
1172 good_files = []
1173 bad_files = []
1174 for fileDatum in self.progress.wrap(file_data, desc="Reading image metadata"):
1175 if not fileDatum.datasets:
1176 bad_files.append(fileDatum.filename)
1177 else:
1178 good_files.append(fileDatum)
1179 return good_files, bad_files
1181 # Look for zip files.
1182 zip_file_data, files, good_zip_files, bad_zip_files = self.readZipIndexFiles(files)
1183 if bad_zip_files:
1184 self.log.info("Failed to extract index metadata from the following zip files:")
1185 for bad in sorted(bad_zip_files):
1186 self.log.info("- %s", bad)
1188 # Look for index files and read them.
1189 # There should be far fewer index files than data files.
1190 index_entries: dict[ResourcePath, Any] = {}
1191 if search_indexes:
1192 index_entries, files, good_index_files, bad_index_files = self.locateAndReadIndexFiles(files)
1193 if bad_index_files:
1194 self.log.info("Failed to read the following explicitly requested index files:")
1195 for bad in sorted(bad_index_files):
1196 self.log.info("- %s", bad)
1197 else:
1198 # We have been told explicitly there are no indexes.
1199 index_entries = {}
1200 good_index_files = set()
1201 bad_index_files = set()
1203 # Merge information from zips and standalone index files.
1204 good_index_files.update(good_zip_files)
1205 bad_index_files.update(bad_index_files)
1207 # Now convert all the index file entries to standard form for ingest.
1208 processed_bad_index_files: list[ResourcePath] = []
1209 indexFileData = self.processIndexEntries(index_entries)
1210 indexFileData.extend(zip_file_data)
1211 if indexFileData:
1212 indexFileData, processed_bad_index_files = _partition_good_bad(indexFileData)
1213 self.log.info(
1214 "Successfully extracted metadata for %d file%s found in %d index file%s with %d failure%s",
1215 *_log_msg_counter(indexFileData),
1216 *_log_msg_counter(good_index_files),
1217 *_log_msg_counter(processed_bad_index_files),
1218 )
1220 # Extract metadata and build per-detector regions.
1221 # This could run in threads or a subprocess so collect all output
1222 # before looking at failures.
1223 fileData: Iterator[RawFileData]
1224 if pool is None:
1225 fileData = map(self.extractMetadata, files)
1226 else:
1227 fileData = pool.map(self.extractMetadata, files)
1229 # Filter out all the failed reads and store them for later
1230 # reporting.
1231 good_file_data, bad_files = _partition_good_bad(fileData)
1232 # Only report if we looked at any standalone files at all.
1233 if files:
1234 self.log.info(
1235 "Successfully extracted metadata from %d file%s with %d failure%s",
1236 *_log_msg_counter(good_file_data),
1237 *_log_msg_counter(bad_files),
1238 )
1240 # Combine with data from index files.
1241 good_file_data.extend(indexFileData)
1242 bad_files.extend(processed_bad_index_files)
1243 bad_files.extend(bad_index_files)
1245 # Use that metadata to group files (and extracted metadata) by
1246 # exposure. Never parallelized because it's intrinsically a gather
1247 # step.
1248 exposureData: list[RawExposureData] = self.groupByExposure(good_file_data)
1250 # The next operation operates on RawExposureData instances (one at
1251 # a time) in-place and then returns the modified instance. We call it
1252 # as a pass-through instead of relying on the arguments we pass in to
1253 # have been modified because in the parallel case those arguments are
1254 # going to be pickled and unpickled, and I'm not certain
1255 # multiprocessing is careful enough with that for output arguments to
1256 # work.
1258 # Expand the data IDs to include all dimension metadata; we need this
1259 # because we may need to generate path templates that rely on that
1260 # metadata.
1261 # This is the first step that involves actual database calls (but just
1262 # SELECTs), so if there's going to be a problem with connections vs.
1263 # multiple processes, or lock contention (in SQLite) slowing things
1264 # down, it'll happen here.
1265 return map(self.expandDataIds, exposureData), bad_files
1267 def ingestExposureDatasets(
1268 self,
1269 exposure: RawExposureData,
1270 datasetType: DatasetType,
1271 *,
1272 run: str,
1273 skip_existing_exposures: bool = False,
1274 track_file_attrs: bool = True,
1275 ) -> list[FileDataset]:
1276 """Ingest all raw files in one exposure.
1278 Parameters
1279 ----------
1280 exposure : `RawExposureData`
1281 A structure containing information about the exposure to be
1282 ingested. Must have `RawExposureData.record` populated and all
1283 data ID attributes expanded.
1284 datasetType : `lsst.daf.butler.DatasetType`
1285 The dataset type associated with this exposure.
1286 run : `str`
1287 Name of a RUN-type collection to write to.
1288 skip_existing_exposures : `bool`, optional
1289 If `True` (`False` is default), skip raws that have already been
1290 ingested (i.e. raws for which we already have a dataset with the
1291 same data ID in the target collection, even if from another file).
1292 Note that this is much slower than just not passing
1293 already-ingested files as inputs, because we still need to read and
1294 process metadata to identify which exposures to search for.
1295 track_file_attrs : `bool`, optional
1296 Control whether file attributes such as the size or checksum should
1297 be tracked by the datastore. Whether this parameter is honored
1298 depends on the specific datastore implementation.
1300 Returns
1301 -------
1302 datasets : `list` of `lsst.daf.butler.FileDataset`
1303 Per-file structures identifying the files ingested and their
1304 dataset representation in the data repository.
1305 """
1306 # Raw files are preferentially ingested using a UUID derived from
1307 # the collection name and dataId.
1308 if self.butler.registry.supportsIdGenerationMode(DatasetIdGenEnum.DATAID_TYPE_RUN):
1309 mode = DatasetIdGenEnum.DATAID_TYPE_RUN
1310 else:
1311 mode = DatasetIdGenEnum.UNIQUE
1313 # The datasets for this exposure could all be from a single zip
1314 # or be distinct files. Need to pull out the zip files.
1315 zips: dict[ResourcePath, list[RawFileData]] = defaultdict(list)
1316 datasets: list[FileDataset] = []
1317 for file in exposure.files:
1318 if file.filename.getExtension() == ".zip":
1319 zips[file.filename.replace(fragment="")].append(file)
1320 continue
1322 refs = [
1323 DatasetRef(datasetType, d.dataId, run=run, id_generation_mode=mode) for d in file.datasets
1324 ]
1325 if refs:
1326 datasets.append(
1327 FileDataset(path=file.filename.abspath(), refs=refs, formatter=file.FormatterClass)
1328 )
1330 if datasets:
1331 with self.butler.record_metrics() as butler_metrics:
1332 self.butler.ingest(
1333 *datasets,
1334 transfer=self.config.transfer,
1335 record_validation_info=track_file_attrs,
1336 skip_existing=skip_existing_exposures,
1337 )
1338 self.metrics.time_for_ingest += butler_metrics.time_in_ingest
1340 # In theory it is possible for the new Data IDs to differ from the Data
1341 # IDs stored in the Zip index. That could happen if there is a metadata
1342 # correction that changes the exposure or detector numbers. We have to
1343 # assume that by the time the zip has been made that this correction
1344 # has been applied. If we don't assume that then we have to
1345 # regenerate the index but we cannot change the contents of the zip.
1346 # We would also need the ability for butler.ingest_zip to take an
1347 # override ZipIndex object.
1348 # The Dataset ref IDs will only change if the data IDs change.
1349 for zip, files in zips.items():
1350 zip_datasets: list[FileDataset] = [] # Needed for return value.
1351 for file in files:
1352 refs = [
1353 DatasetRef(datasetType, d.dataId, run=run, id_generation_mode=mode) for d in file.datasets
1354 ]
1355 if refs:
1356 # Assumes the guiders are not included in the metadata
1357 # index.
1358 zip_datasets.append(
1359 FileDataset(path=file.filename.abspath(), refs=refs, formatter=file.FormatterClass)
1360 )
1361 with self.butler.record_metrics() as butler_metrics:
1362 self.butler.ingest_zip(
1363 zip, transfer=self.config.transfer, skip_existing=skip_existing_exposures
1364 )
1365 datasets.extend(zip_datasets)
1366 self.metrics.time_for_ingest += butler_metrics.time_in_ingest
1368 return datasets
1370 def ingestFiles(
1371 self,
1372 files: Sequence[ResourcePath],
1373 *,
1374 pool: concurrent.futures.ThreadPoolExecutor | None = None,
1375 num_workers: int = 1,
1376 run: str | None = None,
1377 skip_existing_exposures: bool = False,
1378 update_exposure_records: bool = False,
1379 track_file_attrs: bool = True,
1380 search_indexes: bool = True,
1381 skip_ingest: bool = False,
1382 ) -> tuple[list[DatasetRef], list[ResourcePath], int, int, int]:
1383 """Ingest files into a Butler data repository.
1385 This creates any new exposure or visit Dimension entries needed to
1386 identify the ingested files, creates new Dataset entries in the
1387 Registry and finally ingests the files themselves into the Datastore.
1388 Any needed instrument, detector, and physical_filter Dimension entries
1389 must exist in the Registry before `run` is called.
1391 Parameters
1392 ----------
1393 files : iterable over `lsst.resources.ResourcePath`
1394 URIs to the files to be ingested.
1395 pool : `concurrent.futures.ThreadPoolExecutor`, optional
1396 If not `None`, a thread pool with which to parallelize some
1397 operations.
1398 num_workers : `int`, optional
1399 The number of workers to use. Ignored if ``pool`` is not `None`.
1400 run : `str`, optional
1401 Name of a RUN-type collection to write to, overriding
1402 the default derived from the instrument name.
1403 skip_existing_exposures : `bool`, optional
1404 If `True` (`False` is default), skip raws that have already been
1405 ingested (i.e. raws for which we already have a dataset with the
1406 same data ID in the target collection, even if from another file).
1407 Note that this is much slower than just not passing
1408 already-ingested files as inputs, because we still need to read and
1409 process metadata to identify which exposures to search for. It
1410 also will not work reliably if multiple processes are attempting to
1411 ingest raws from the same exposure concurrently, in that different
1412 processes may still attempt to ingest the same raw and conflict,
1413 causing a failure that prevents other raws from the same exposure
1414 from being ingested.
1415 update_exposure_records : `bool`, optional
1416 If `True` (`False` is default), update existing exposure records
1417 that conflict with the new ones instead of rejecting them. THIS IS
1418 AN ADVANCED OPTION THAT SHOULD ONLY BE USED TO FIX METADATA THAT IS
1419 KNOWN TO BE BAD. This should usually be combined with
1420 ``skip_existing_exposures=True``.
1421 track_file_attrs : `bool`, optional
1422 Control whether file attributes such as the size or checksum should
1423 be tracked by the datastore. Whether this parameter is honored
1424 depends on the specific datastore implementation.
1425 search_indexes : `bool`, optional
1426 If `True` the code will search for index JSON files in given
1427 directories. If you know for a fact that index files do not exist
1428 set this to `False` for a slight speed up in metadata gathering.
1429 skip_ingest : `bool`, optional
1430 Set this to `True` to do metadata extraction and dimension record
1431 updates without attempting to re-ingest. This can be useful if
1432 there has been a metadata correction associated with an exposure.
1434 Returns
1435 -------
1436 refs : `list` of `lsst.daf.butler.DatasetRef`
1437 Dataset references for ingested raws.
1438 bad_files : `list` of `lsst.resources.ResourcePath`
1439 Given paths that could not be ingested.
1440 n_exposures : `int`
1441 Number of exposures successfully ingested.
1442 n_exposures_failed : `int`
1443 Number of exposures that failed when inserting dimension data.
1444 n_ingests_failed : `int`
1445 Number of exposures that failed when ingesting raw datasets.
1446 """
1447 created_pool = False
1448 if pool is None and num_workers > 1:
1449 pool = concurrent.futures.ThreadPoolExecutor(max_workers=num_workers)
1450 created_pool = True
1452 try:
1453 with self.metrics.collect_metric(
1454 "time_for_metadata",
1455 self.log,
1456 msg="Reading metadata from %d file%s",
1457 args=(*_log_msg_counter(files),),
1458 ):
1459 exposureData, bad_files = self.prep(files, pool=pool, search_indexes=search_indexes)
1460 finally:
1461 if created_pool and pool:
1462 # The pool is not needed any more so close it if we created
1463 # it to ensure we clean up resources.
1464 pool.shutdown(wait=True)
1466 # Up to this point, we haven't modified the data repository at all.
1467 # Now we finally do that, with one transaction per exposure. This is
1468 # not parallelized at present because the performance of this step is
1469 # limited by the database server. That may or may not change in the
1470 # future once we increase our usage of bulk inserts and reduce our
1471 # usage of savepoints; we've tried to get everything but the database
1472 # operations done in advance to reduce the time spent inside
1473 # transactions.
1474 refs = []
1475 runs = set()
1476 datasetTypes: dict[str, DatasetType] = {}
1477 n_exposures = 0
1478 n_exposures_failed = 0
1479 n_ingests_failed = 0
1480 for exposure in self.progress.wrap(exposureData, desc="Ingesting raw exposures"):
1481 assert exposure.record is not None, "Should be guaranteed by prep()"
1482 self.log.debug(
1483 "Attempting to ingest %d file%s from exposure %s:%s",
1484 *_log_msg_counter(exposure.files),
1485 exposure.record.instrument,
1486 exposure.record.obs_id,
1487 )
1489 try:
1490 with self.metrics.collect_metric(
1491 "time_for_records",
1492 self.log,
1493 msg="Creating dimension records for instrument %s, exposure %s",
1494 args=(
1495 str(exposure.record.instrument),
1496 str(exposure.record.id),
1497 ),
1498 ):
1499 for name, record in exposure.dependencyRecords.items():
1500 self.butler.registry.syncDimensionData(name, record, update=update_exposure_records)
1501 inserted_or_updated = self.butler.registry.syncDimensionData(
1502 "exposure",
1503 exposure.record,
1504 update=update_exposure_records,
1505 )
1506 if inserted_or_updated is not False:
1507 with self.metrics.collect_metric(
1508 "time_for_callbacks", log=self.log, msg="Exposure record updated. Calling handler"
1509 ):
1510 self._on_exposure_record(exposure.record)
1511 except Exception as e:
1512 self._on_ingest_failure(exposure, e)
1513 n_exposures_failed += 1
1514 self.log.warning(
1515 "Exposure %s:%s could not be registered: %s",
1516 exposure.record.instrument,
1517 exposure.record.obs_id,
1518 e,
1519 )
1520 if self.config.failFast:
1521 raise e
1522 continue
1524 if isinstance(inserted_or_updated, dict):
1525 # Exposure is in the registry and we updated it, so
1526 # syncDimensionData returned a dict.
1527 columns_updated = list(inserted_or_updated.keys())
1528 s_col = "s" if len(columns_updated) != 1 else ""
1529 w_col = "were" if len(columns_updated) != 1 else "was"
1530 self.log.info(
1531 "Exposure %s:%s was already present, but column%s %s %s updated.",
1532 exposure.record.instrument,
1533 exposure.record.obs_id,
1534 s_col,
1535 ", ".join(repr(c) for c in columns_updated),
1536 w_col,
1537 )
1539 if skip_ingest:
1540 continue
1542 # Determine the instrument so we can work out the dataset type.
1543 instrument = exposure.files[0].instrument
1544 assert instrument is not None, (
1545 "file should have been removed from this list by prep if instrument could not be found"
1546 )
1548 datasetType = self.get_raw_datasetType(instrument, datasetTypes)
1549 if datasetType.name not in datasetTypes:
1550 self.butler.registry.registerDatasetType(datasetType)
1551 datasetTypes[datasetType.name] = datasetType
1553 # Override default run if nothing specified explicitly.
1554 if run is None:
1555 this_run = instrument.makeDefaultRawIngestRunName()
1556 else:
1557 this_run = run
1558 if this_run not in runs:
1559 self.butler.registry.registerCollection(this_run, type=CollectionType.RUN)
1560 runs.add(this_run)
1561 try:
1562 datasets_for_exposure = self.ingestExposureDatasets(
1563 exposure,
1564 datasetType=datasetType,
1565 run=this_run,
1566 skip_existing_exposures=skip_existing_exposures,
1567 track_file_attrs=track_file_attrs,
1568 )
1569 except Exception as e:
1570 self._on_ingest_failure(exposure, e)
1571 n_ingests_failed += 1
1572 self.log.warning("Failed to ingest the following for reason: %s", e)
1573 for f in exposure.files:
1574 self.log.warning("- %s", f.filename)
1575 if self.config.failFast:
1576 raise e
1577 continue
1578 else:
1579 with self.metrics.collect_metric("time_for_callbacks", self.log, msg="Calling on_success"):
1580 self._on_success(datasets_for_exposure)
1581 for dataset in datasets_for_exposure:
1582 refs.extend(dataset.refs)
1584 # Success for this exposure.
1585 n_exposures += 1
1586 self.log.info(
1587 "Exposure %s:%s ingested successfully", exposure.record.instrument, exposure.record.obs_id
1588 )
1590 return refs, bad_files, n_exposures, n_exposures_failed, n_ingests_failed
1592 @timeMethod
1593 def run(
1594 self,
1595 files: Iterable[ResourcePathExpression],
1596 *,
1597 pool: concurrent.futures.ThreadPoolExecutor | None = None,
1598 processes: int | None = None, # Deprecated. Use num_workers.
1599 run: str | None = None,
1600 file_filter: str | re.Pattern = r"\.fit[s]?\b",
1601 group_files: bool = True,
1602 skip_existing_exposures: bool = False,
1603 update_exposure_records: bool = False,
1604 track_file_attrs: bool = True,
1605 search_indexes: bool = True,
1606 num_workers: int = 1,
1607 skip_ingest: bool = False,
1608 ) -> list[DatasetRef]:
1609 """Ingest files into a Butler data repository.
1611 This creates any new exposure or visit Dimension entries needed to
1612 identify the ingested files, creates new Dataset entries in the
1613 Registry and finally ingests the files themselves into the Datastore.
1614 Any needed instrument, detector, and physical_filter Dimension entries
1615 must exist in the Registry before `run` is called.
1617 Parameters
1618 ----------
1619 files : iterable `lsst.resources.ResourcePath`, `str` or path-like
1620 Paths to the files to be ingested. Can refer to directories.
1621 Will be made absolute if they are not already.
1622 pool : `concurrent.futures.ThreadPoolExecutor`, optional
1623 If not `None`, a process pool with which to parallelize some
1624 operations. This parameter was previously a `multiprocessing.Pool`
1625 but that option is no longer supported since it is slow compared
1626 to futures.
1627 processes : `int`, optional
1628 The number of processes to use. Ignored if ``pool`` is not `None`.
1629 Deprecated. Please use ``num_workers`` parameter instead.
1630 run : `str`, optional
1631 Name of a RUN-type collection to write to, overriding
1632 the default derived from the instrument name.
1633 file_filter : `str` or `re.Pattern`, optional
1634 Pattern to use to discover files to ingest within directories.
1635 The default is to search for FITS files. The regex applies to
1636 files within the directory.
1637 group_files : `bool`, optional
1638 Group files by directory if they have been discovered in
1639 directories. Will not affect files explicitly provided.
1640 skip_existing_exposures : `bool`, optional
1641 If `True` (`False` is default), skip raws that have already been
1642 ingested (i.e. raws for which we already have a dataset with the
1643 same data ID in the target collection, even if from another file).
1644 Note that this is much slower than just not passing
1645 already-ingested files as inputs, because we still need to read and
1646 process metadata to identify which exposures to search for. It
1647 also will not work reliably if multiple processes are attempting to
1648 ingest raws from the same exposure concurrently, in that different
1649 processes may still attempt to ingest the same raw and conflict,
1650 causing a failure that prevents other raws from the same exposure
1651 from being ingested.
1652 update_exposure_records : `bool`, optional
1653 If `True` (`False` is default), update existing exposure records
1654 that conflict with the new ones instead of rejecting them. THIS IS
1655 AN ADVANCED OPTION THAT SHOULD ONLY BE USED TO FIX METADATA THAT IS
1656 KNOWN TO BE BAD. This should usually be combined with
1657 ``skip_existing_exposures=True``.
1658 track_file_attrs : `bool`, optional
1659 Control whether file attributes such as the size or checksum should
1660 be tracked by the datastore. Whether this parameter is honored
1661 depends on the specific datastore implementation.
1662 search_indexes : `bool`, optional
1663 If `True` the code will search for index JSON files in given
1664 directories. If you know for a fact that index files do not exist
1665 set this to `False` for a slight speed up in metadata gathering.
1666 num_workers : `int`, optional
1667 The number of workers to use. Ignored if ``pool`` parameter is
1668 given.
1669 skip_ingest : `bool`, optional
1670 Set this to `True` to do metadata extraction and dimension record
1671 updates without attempting to re-ingest. This can be useful if
1672 there has been a metadata correction associated with an exposure.
1674 Returns
1675 -------
1676 refs : `list` of `lsst.daf.butler.DatasetRef`
1677 Dataset references for ingested raws.
1679 Notes
1680 -----
1681 This method inserts all datasets for an exposure within a transaction,
1682 guaranteeing that partial exposures are never ingested. The exposure
1683 dimension record is inserted with
1684 `lsst.daf.butler.Registry.syncDimensionData` first (in its own
1685 transaction), which inserts only if a record with the same
1686 primary key does not already exist. This allows different files within
1687 the same exposure to be ingested in different runs.
1688 """
1689 if pool and not isinstance(pool, concurrent.futures.ThreadPoolExecutor):
1690 raise ValueError(f"This parameter must now be a ThreadPoolExecutor but was given {pool}.")
1692 if processes is not None:
1693 warnings.warn(
1694 "Processes parameter is deprecated. Please use num_workers parameter.",
1695 FutureWarning,
1696 stacklevel=3, # Jump above the timeMethod wrapper.
1697 )
1698 num_workers = processes
1700 refs = []
1701 bad_files = []
1702 n_exposures = 0
1703 n_exposures_failed = 0
1704 n_ingests_failed = 0
1705 self.metrics.reset() # Clear previous metrics.
1706 ingest_duration = 0.0
1707 if group_files:
1708 with time_this(log=self.log, msg="Processing ingest groups") as timer:
1709 for group in ResourcePath.findFileResources(files, file_filter, group_files):
1710 new_refs, bad, n_exp, n_exp_fail, n_ingest_fail = self.ingestFiles(
1711 tuple(group),
1712 pool=pool,
1713 num_workers=num_workers,
1714 run=run,
1715 skip_existing_exposures=skip_existing_exposures,
1716 update_exposure_records=update_exposure_records,
1717 track_file_attrs=track_file_attrs,
1718 search_indexes=search_indexes,
1719 skip_ingest=skip_ingest,
1720 )
1721 refs.extend(new_refs)
1722 bad_files.extend(bad)
1723 n_exposures += n_exp
1724 n_exposures_failed += n_exp_fail
1725 n_ingests_failed += n_ingest_fail
1726 ingest_duration = timer.duration
1727 else:
1728 with time_this(log=self.log, msg="Ingesting all files in one batch") as timer:
1729 refs, bad_files, n_exposures, n_exposures_failed, n_ingests_failed = self.ingestFiles(
1730 tuple(ResourcePath.findFileResources(files, file_filter, group_files)),
1731 pool=pool,
1732 num_workers=num_workers,
1733 run=run,
1734 skip_existing_exposures=skip_existing_exposures,
1735 update_exposure_records=update_exposure_records,
1736 track_file_attrs=track_file_attrs,
1737 search_indexes=search_indexes,
1738 skip_ingest=skip_ingest,
1739 )
1740 ingest_duration = timer.duration
1742 had_failure = False
1744 if bad_files:
1745 had_failure = True
1746 self.log.warning("Could not extract observation metadata from the following:")
1747 for f in bad_files:
1748 self.log.warning("- %s", f)
1750 if skip_ingest:
1751 ingest_text = ""
1752 else:
1753 ingest_text = f" - time in butler ingest: {self.metrics.time_for_ingest} s\n"
1755 self.log.info(
1756 "Successfully processed data from %d exposure%s with %d failure%s from exposure"
1757 " registration and %d failure%s from file ingest.\n"
1758 "Timing breakdown:\n"
1759 " - time in metadata gathering: %f s\n"
1760 " - time in dimension record writing: %f s\n"
1761 "%s"
1762 " - time in user-supplied callbacks: %f s\n",
1763 *_log_msg_counter(n_exposures),
1764 *_log_msg_counter(n_exposures_failed),
1765 *_log_msg_counter(n_ingests_failed),
1766 self.metrics.time_for_metadata,
1767 self.metrics.time_for_records,
1768 ingest_text,
1769 self.metrics.time_for_callbacks,
1770 )
1771 if n_exposures_failed > 0 or n_ingests_failed > 0:
1772 had_failure = True
1773 if not skip_ingest:
1774 self.log.info(
1775 "Ingested %d distinct Butler dataset%s in %f sec", *_log_msg_counter(refs), ingest_duration
1776 )
1778 if had_failure:
1779 raise RuntimeError("Some failures encountered during ingestion")
1781 return refs