lsst.obs.base  19.0.0-25-g78ff95b
rootRepoConverter.py
Go to the documentation of this file.
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/>.
21 from __future__ import annotations
22 
23 __all__ = ["RootRepoConverter"]
24 
25 import os
26 import re
27 import itertools
28 from typing import TYPE_CHECKING, Iterator, Optional, Tuple, List
29 
30 from lsst.skymap import BaseSkyMap
31 from lsst.daf.butler import DatasetType, DatasetRef, FileDataset
32 from .standardRepoConverter import StandardRepoConverter
33 
34 SKYMAP_DATASET_TYPES = {
35  coaddName: f"{coaddName}Coadd_skyMap" for coaddName in ("deep", "goodSeeing", "dcr")
36 }
37 
38 if TYPE_CHECKING:
39  from lsst.daf.butler import SkyPixDimension
40  from ..ingest import RawExposureData
41 
42 
43 def getDataPaths(dataRefs):
44  """Strip HDU identifiers from paths and return a unique set of paths.
45 
46  Parameters
47  ----------
48  dataRefs : `lsst.daf.persistence.ButlerDataRef`
49  The gen2 datarefs to strip "[HDU]" values from.
50 
51  Returns
52  -------
53  paths : `set` [`str`]
54  The unique file paths without appended "[HDU]".
55  """
56  paths = set()
57  for dataRef in dataRefs:
58  path = dataRef.getUri()
59  # handle with FITS files with multiple HDUs (e.g. decam raw)
60  paths.add(path.split('[')[0])
61  return paths
62 
63 
65  """A specialization of `RepoConverter` for root data repositories.
66 
67  `RootRepoConverter` adds support for raw images (mostly delegated to the
68  parent task's `RawIngestTask` subtask) and reference catalogs.
69 
70  Parameters
71  ----------
72  kwds
73  Keyword arguments are forwarded to (and required by) `RepoConverter`.
74  """
75 
76  def __init__(self, **kwds):
77  super().__init__(**kwds)
78  self._exposureData: List[RawExposureData] = []
79  self._refCats: List[Tuple[str, SkyPixDimension]] = []
80  if self.task.config.rootSkyMapName is not None:
81  self._rootSkyMap = self.task.config.skyMaps[self.task.config.rootSkyMapName].skyMap.apply()
82  else:
83  self._rootSkyMap = None
84 
85  def isDatasetTypeSpecial(self, datasetTypeName: str) -> bool:
86  # Docstring inherited from RepoConverter.
87  return (
88  super().isDatasetTypeSpecial(datasetTypeName)
89  or datasetTypeName in ("raw", "ref_cat", "ref_cat_config")
90  # in Gen2, some of these are in the root repo, not a calib repo
91  or datasetTypeName in self.task.config.curatedCalibrations
92  )
93 
94  def getSpecialDirectories(self) -> List[str]:
95  # Docstring inherited from RepoConverter.
96  return super().getSpecialDirectories() + ["CALIB", "ref_cats", "rerun"]
97 
98  def findMatchingSkyMap(self, datasetTypeName: str) -> Tuple[Optional[BaseSkyMap], Optional[str]]:
99  # Docstring inherited from StandardRepoConverter.findMatchingSkyMap.
100  skyMap, name = super().findMatchingSkyMap(datasetTypeName)
101  if skyMap is None and self.task.config.rootSkyMapName is not None:
102  self.task.log.debug(
103  ("Assuming configured root skymap with name '%s' for dataset %s."),
104  self.task.config.rootSkyMapName, datasetTypeName
105  )
106  skyMap = self._rootSkyMap
107  name = self.task.config.rootSkyMapName
108  return skyMap, name
109 
110  def prep(self):
111  # Docstring inherited from RepoConverter.
112  # Gather information about raws.
113  if self.task.raws is not None:
114  self.task.log.info(f"Preparing raws from root {self.root}.")
115  if self.subset is not None:
116  dataRefs = itertools.chain.from_iterable(
117  self.butler2.subset("raw", visit=visit) for visit in self.subset.visits
118  )
119  else:
120  dataRefs = self.butler2.subset("raw")
121  dataPaths = getDataPaths(dataRefs)
122  self.task.log.debug("Prepping files: %s", dataPaths)
123  self._exposureData.extend(self.task.raws.prep(dataPaths))
124  # Gather information about reference catalogs.
125  if self.task.isDatasetTypeIncluded("ref_cat") and len(self.task.config.refCats) != 0:
126  from lsst.meas.algorithms import DatasetConfig as RefCatDatasetConfig
127  for refCat in os.listdir(os.path.join(self.root, "ref_cats")):
128  path = os.path.join(self.root, "ref_cats", refCat)
129  configFile = os.path.join(path, "config.py")
130  if not os.path.exists(configFile):
131  continue
132  if refCat not in self.task.config.refCats:
133  continue
134  self.task.log.info(f"Preparing ref_cat {refCat} from root {self.root}.")
135  onDiskConfig = RefCatDatasetConfig()
136  onDiskConfig.load(configFile)
137  if onDiskConfig.indexer.name != "HTM":
138  raise ValueError(f"Reference catalog '{refCat}' uses unsupported "
139  f"pixelization '{onDiskConfig.indexer.name}'.")
140  level = onDiskConfig.indexer["HTM"].depth
141  try:
142  dimension = self.task.universe[f"htm{level}"]
143  except KeyError as err:
144  raise ValueError(f"Reference catalog {refCat} uses HTM level {level}, but no htm{level} "
145  f"skypix dimension is configured for this registry.") from err
146  self.task.useSkyPix(dimension)
147  self._refCats.append((refCat, dimension))
148  if self.task.isDatasetTypeIncluded("brightObjectMask") and self.task.config.rootSkyMapName:
149  self.task.useSkyMap(self._rootSkyMap, self.task.config.rootSkyMapName)
150  super().prep()
151 
153  # Docstring inherited from RepoConverter.
154  self.task.log.info(f"Inserting observation dimension records from {self.root}.")
155  records = {"visit": [], "exposure": [], "visit_detector_region": []}
156  for exposure in self._exposureData:
157  for dimension, recordsForDimension in exposure.records.items():
158  records[dimension].extend(recordsForDimension)
159  self.task.raws.insertDimensionData(records)
160 
161  def iterDatasets(self) -> Iterator[FileDataset]:
162  # Docstring inherited from RepoConverter.
163  # Iterate over reference catalog files.
164  for refCat, dimension in self._refCats:
165  datasetType = DatasetType(refCat, dimensions=[dimension], universe=self.task.universe,
166  storageClass="SimpleCatalog")
167  if self.subset is None:
168  regex = re.compile(r"(\d+)\.fits")
169  for fileName in os.listdir(os.path.join(self.root, "ref_cats", refCat)):
170  m = regex.match(fileName)
171  if m is not None:
172  htmId = int(m.group(1))
173  dataId = self.task.registry.expandDataId({dimension: htmId})
174  yield FileDataset(path=os.path.join(self.root, "ref_cats", refCat, fileName),
175  refs=DatasetRef(datasetType, dataId))
176  else:
177  for begin, end in self.subset.skypix[dimension]:
178  for htmId in range(begin, end):
179  dataId = self.task.registry.expandDataId({dimension: htmId})
180  yield FileDataset(path=os.path.join(self.root, "ref_cats", refCat, f"{htmId}.fits"),
181  refs=DatasetRef(datasetType, dataId))
182  yield from super().iterDatasets()
183 
184  def ingest(self):
185  # Docstring inherited from RepoConverter.
186  if self.task.raws is not None:
187  self.task.log.info(f"Ingesting raws from root {self.root}.")
188  self.task.registry.registerDatasetType(self.task.raws.datasetType)
189  # We need te delegate to RawIngestTask to actually ingest raws,
190  # rather than just including those datasets in iterDatasets for
191  # the base class to handle, because we don't want to assume we
192  # can use the Datastore-configured Formatter for raw data.
193  refs = []
194  collections = self.getCollections("raw")
195  for exposure in self._exposureData:
196  refs.extend(self.task.raws.ingestExposureDatasets(exposure))
197  for collection in collections[1:]:
198  self.task.registry.associate(collection, refs)
199  super().ingest()
200 
201  def getCollections(self, datasetTypeName: str) -> List[str]:
202  # override to put reference catalogs in the right collection
203  if datasetTypeName in self.task.config.refCats:
204  return ['refcats']
205  else:
206  return super().getCollections(datasetTypeName)