lsst.obs.base  19.0.0-28-g99824a6
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(self.task.config.rawDatasetType,
118  visit=visit) for visit in self.subset.visits
119  )
120  else:
121  dataRefs = self.butler2.subset(self.task.config.rawDatasetType)
122  dataPaths = getDataPaths(dataRefs)
123  self.task.log.debug("Prepping files: %s", dataPaths)
124  self._exposureData.extend(self.task.raws.prep(dataPaths))
125  # Gather information about reference catalogs.
126  if self.task.isDatasetTypeIncluded("ref_cat") and len(self.task.config.refCats) != 0:
127  from lsst.meas.algorithms import DatasetConfig as RefCatDatasetConfig
128  for refCat in os.listdir(os.path.join(self.root, "ref_cats")):
129  path = os.path.join(self.root, "ref_cats", refCat)
130  configFile = os.path.join(path, "config.py")
131  if not os.path.exists(configFile):
132  continue
133  if refCat not in self.task.config.refCats:
134  continue
135  self.task.log.info(f"Preparing ref_cat {refCat} from root {self.root}.")
136  onDiskConfig = RefCatDatasetConfig()
137  onDiskConfig.load(configFile)
138  if onDiskConfig.indexer.name != "HTM":
139  raise ValueError(f"Reference catalog '{refCat}' uses unsupported "
140  f"pixelization '{onDiskConfig.indexer.name}'.")
141  level = onDiskConfig.indexer["HTM"].depth
142  try:
143  dimension = self.task.universe[f"htm{level}"]
144  except KeyError as err:
145  raise ValueError(f"Reference catalog {refCat} uses HTM level {level}, but no htm{level} "
146  f"skypix dimension is configured for this registry.") from err
147  self.task.useSkyPix(dimension)
148  self._refCats.append((refCat, dimension))
149  if self.task.isDatasetTypeIncluded("brightObjectMask") and self.task.config.rootSkyMapName:
150  self.task.useSkyMap(self._rootSkyMap, self.task.config.rootSkyMapName)
151  super().prep()
152 
154  # Docstring inherited from RepoConverter.
155  self.task.log.info(f"Inserting observation dimension records from {self.root}.")
156  records = {"visit": [], "exposure": [], "visit_detector_region": []}
157  for exposure in self._exposureData:
158  for dimension, recordsForDimension in exposure.records.items():
159  records[dimension].extend(recordsForDimension)
160  self.task.raws.insertDimensionData(records)
161 
162  def iterDatasets(self) -> Iterator[FileDataset]:
163  # Docstring inherited from RepoConverter.
164  # Iterate over reference catalog files.
165  for refCat, dimension in self._refCats:
166  datasetType = DatasetType(refCat, dimensions=[dimension], universe=self.task.universe,
167  storageClass="SimpleCatalog")
168  if self.subset is None:
169  regex = re.compile(r"(\d+)\.fits")
170  for fileName in os.listdir(os.path.join(self.root, "ref_cats", refCat)):
171  m = regex.match(fileName)
172  if m is not None:
173  htmId = int(m.group(1))
174  dataId = self.task.registry.expandDataId({dimension: htmId})
175  yield FileDataset(path=os.path.join(self.root, "ref_cats", refCat, fileName),
176  refs=DatasetRef(datasetType, dataId))
177  else:
178  for begin, end in self.subset.skypix[dimension]:
179  for htmId in range(begin, end):
180  dataId = self.task.registry.expandDataId({dimension: htmId})
181  yield FileDataset(path=os.path.join(self.root, "ref_cats", refCat, f"{htmId}.fits"),
182  refs=DatasetRef(datasetType, dataId))
183  yield from super().iterDatasets()
184 
185  def ingest(self):
186  # Docstring inherited from RepoConverter.
187  if self.task.raws is not None:
188  self.task.log.info(f"Ingesting raws from root {self.root}.")
189  self.task.registry.registerDatasetType(self.task.raws.datasetType)
190  # We need te delegate to RawIngestTask to actually ingest raws,
191  # rather than just including those datasets in iterDatasets for
192  # the base class to handle, because we don't want to assume we
193  # can use the Datastore-configured Formatter for raw data.
194  refs = []
195  collections = self.getCollections("raw")
196  for exposure in self._exposureData:
197  refs.extend(self.task.raws.ingestExposureDatasets(exposure))
198  for collection in collections[1:]:
199  self.task.registry.associate(collection, refs)
200  super().ingest()
201 
202  def getCollections(self, datasetTypeName: str) -> List[str]:
203  # override to put reference catalogs in the right collection
204  if datasetTypeName in self.task.config.refCats:
205  return ['refcats']
206  else:
207  return super().getCollections(datasetTypeName)