Coverage for python/lsst/daf/butler/dimensions/_skypix.py: 46%
91 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-27 09:44 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-27 09:44 +0000
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://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 software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
28from __future__ import annotations
30__all__ = (
31 "SkyPixDimension",
32 "SkyPixSystem",
33)
35from collections.abc import Mapping, Set
36from types import MappingProxyType
37from typing import TYPE_CHECKING
39import sqlalchemy
40from lsst.sphgeom import PixelizationABC
41from lsst.utils import doImportType
43from .. import ddl
44from .._named import NamedValueAbstractSet, NamedValueSet
45from .._topology import TopologicalFamily, TopologicalRelationshipEndpoint, TopologicalSpace
46from ._elements import Dimension
47from .construction import DimensionConstructionBuilder, DimensionConstructionVisitor
49if TYPE_CHECKING:
50 from ..registry.interfaces import SkyPixDimensionRecordStorage
53class SkyPixSystem(TopologicalFamily):
54 """Class for hierarchical pixelization of the sky.
56 A `TopologicalFamily` that represents a hierarchical pixelization of the
57 sky.
59 Parameters
60 ----------
61 name : `str`
62 Name of the system.
63 maxLevel : `int`
64 Maximum level (inclusive) of the hierarchy.
65 PixelizationClass : `type` (`lsst.sphgeom.PixelizationABC` subclass)
66 Class whose instances represent a particular level of this
67 pixelization.
68 """
70 def __init__(
71 self,
72 name: str,
73 *,
74 maxLevel: int,
75 PixelizationClass: type[PixelizationABC],
76 ):
77 super().__init__(name, TopologicalSpace.SPATIAL)
78 self.maxLevel = maxLevel
79 self.PixelizationClass = PixelizationClass
80 self._members: dict[int, SkyPixDimension] = {}
81 for level in range(maxLevel + 1):
82 self._members[level] = SkyPixDimension(self, level)
84 def choose(self, endpoints: NamedValueAbstractSet[TopologicalRelationshipEndpoint]) -> SkyPixDimension:
85 # Docstring inherited from TopologicalFamily.
86 best: SkyPixDimension | None = None
87 for endpoint in endpoints:
88 if endpoint not in self:
89 continue
90 assert isinstance(endpoint, SkyPixDimension)
91 if best is None or best.level < endpoint.level:
92 best = endpoint
93 if best is None:
94 raise RuntimeError(f"No recognized endpoints for {self.name} in {endpoints}.")
95 return best
97 def __getitem__(self, level: int) -> SkyPixDimension:
98 return self._members[level]
101class SkyPixDimension(Dimension):
102 """Special dimension for sky pixelizations.
104 A special `Dimension` subclass for hierarchical pixelizations of the
105 sky at a particular level.
107 Unlike most other dimensions, skypix dimension records are not stored in
108 the database, as these records only contain an integer pixel ID and a
109 region on the sky, and each of these can be computed directly from the
110 other.
112 Parameters
113 ----------
114 system : `SkyPixSystem`
115 Pixelization system this dimension belongs to.
116 level : `int`
117 Integer level of this pixelization (smaller numbers are coarser grids).
118 """
120 def __init__(self, system: SkyPixSystem, level: int):
121 self.system = system
122 self.level = level
123 self.pixelization = system.PixelizationClass(level)
125 @property
126 def name(self) -> str:
127 return f"{self.system.name}{self.level}"
129 @property
130 def required(self) -> NamedValueAbstractSet[Dimension]:
131 # Docstring inherited from DimensionElement.
132 return NamedValueSet({self}).freeze()
134 @property
135 def implied(self) -> NamedValueAbstractSet[Dimension]:
136 # Docstring inherited from DimensionElement.
137 return NamedValueSet().freeze()
139 @property
140 def topology(self) -> Mapping[TopologicalSpace, TopologicalFamily]:
141 # Docstring inherited from TopologicalRelationshipEndpoint
142 return MappingProxyType({TopologicalSpace.SPATIAL: self.system})
144 @property
145 def metadata(self) -> NamedValueAbstractSet[ddl.FieldSpec]:
146 # Docstring inherited from DimensionElement.
147 return NamedValueSet().freeze()
149 def hasTable(self) -> bool:
150 # Docstring inherited from DimensionElement.hasTable.
151 return False
153 def makeStorage(self) -> SkyPixDimensionRecordStorage:
154 """Make the storage record.
156 Constructs the `DimensionRecordStorage` instance that should
157 be used to back this element in a registry.
159 Returns
160 -------
161 storage : `SkyPixDimensionRecordStorage`
162 Storage object that should back this element in a registry.
163 """
164 from ..registry.dimensions.skypix import BasicSkyPixDimensionRecordStorage
166 return BasicSkyPixDimensionRecordStorage(self)
168 @property
169 def uniqueKeys(self) -> NamedValueAbstractSet[ddl.FieldSpec]:
170 # Docstring inherited from DimensionElement.
171 return NamedValueSet(
172 {
173 ddl.FieldSpec(
174 name="id",
175 dtype=sqlalchemy.BigInteger,
176 primaryKey=True,
177 nullable=False,
178 )
179 }
180 ).freeze()
182 # Class attributes below are shadowed by instance attributes, and are
183 # present just to hold the docstrings for those instance attributes.
185 system: SkyPixSystem
186 """Pixelization system this dimension belongs to (`SkyPixSystem`).
187 """
189 level: int
190 """Integer level of this pixelization (smaller numbers are coarser grids).
191 """
193 pixelization: PixelizationABC
194 """Pixelization instance that can compute regions from IDs and IDs from
195 points (`sphgeom.PixelizationABC`).
196 """
199class SkyPixConstructionVisitor(DimensionConstructionVisitor):
200 """Builder visitor for a single `SkyPixSystem` and its dimensions.
202 Parameters
203 ----------
204 name : `str`
205 Name of the `SkyPixSystem` to be constructed.
206 pixelizationClassName : `str`
207 Fully-qualified name of the class whose instances represent a
208 particular level of this pixelization.
209 maxLevel : `int`, optional
210 Maximum level (inclusive) of the hierarchy. If not provided,
211 an attempt will be made to obtain it from a ``MAX_LEVEL`` attribute
212 of the pixelization class.
214 Notes
215 -----
216 At present, this class adds both a new `SkyPixSystem` instance all possible
217 `SkyPixDimension` to the builder that invokes it. In the future, it may
218 add only the `SkyPixSystem`, with dimension instances created on-the-fly
219 by the `DimensionUniverse`; this depends on `DimensionGraph.encode` going
220 away or otherwise eliminating assumptions about the set of dimensions in a
221 universe being static.
222 """
224 def __init__(self, name: str, pixelizationClassName: str, maxLevel: int | None = None):
225 super().__init__(name)
226 self._pixelizationClassName = pixelizationClassName
227 self._maxLevel = maxLevel
229 def hasDependenciesIn(self, others: Set[str]) -> bool:
230 # Docstring inherited from DimensionConstructionVisitor.
231 return False
233 def visit(self, builder: DimensionConstructionBuilder) -> None:
234 # Docstring inherited from DimensionConstructionVisitor.
235 PixelizationClass = doImportType(self._pixelizationClassName)
236 assert issubclass(PixelizationClass, PixelizationABC)
237 if self._maxLevel is not None:
238 maxLevel = self._maxLevel
239 else:
240 # MyPy does not know the return type of getattr.
241 max_level = getattr(PixelizationClass, "MAX_LEVEL", None)
242 if max_level is None:
243 raise TypeError(
244 f"Skypix pixelization class {self._pixelizationClassName} does"
245 " not have MAX_LEVEL but no max level has been set explicitly."
246 )
247 assert isinstance(max_level, int)
248 maxLevel = max_level
249 system = SkyPixSystem(
250 self.name,
251 maxLevel=maxLevel,
252 PixelizationClass=PixelizationClass,
253 )
254 builder.topology[TopologicalSpace.SPATIAL].add(system)
255 for level in range(maxLevel + 1):
256 dimension = system[level]
257 builder.dimensions.add(dimension)
258 builder.elements.add(dimension)