Coverage for python/lsst/images/_cell_grid.py: 65%
117 statements
« prev ^ index » next coverage.py v7.14.1, created at 2026-06-21 02:10 -0700
« prev ^ index » next coverage.py v7.14.1, created at 2026-06-21 02:10 -0700
1# This file is part of lsst-images.
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# Use of this source code is governed by a 3-clause BSD-style
10# license that can be found in the LICENSE file.
12from __future__ import annotations
14# This module is conceptually part of the 'cells' subpackage, but we don't
15# want the stuff in '_concrete_bounds' to depend on all of that. So the
16# basic CellGrid and CellGridBounds objects are defined here, used in both
17# places, and exported from 'cells'.
19__all__ = (
20 "CellGrid",
21 "CellGridBounds",
22 "CellIJ",
23 "PatchDefinition",
24)
26import dataclasses
27import math
28from collections.abc import Iterator
29from functools import cached_property
30from typing import TYPE_CHECKING, Any, overload
32import numpy as np
33import pydantic
35from ._geom import YX, Bounds, Box
37if TYPE_CHECKING:
38 try:
39 from lsst.cell_coadds import UniformGrid as LegacyUniformGrid
40 from lsst.skymap import Index2D as LegacyIndex2D
41 except ImportError:
42 type LegacyUniformGrid = Any # type: ignore[no-redef]
43 type LegacyIndex2D = Any # type: ignore[no-redef]
46@dataclasses.dataclass(frozen=True, order=True)
47class CellIJ:
48 """An index in a grid of cells.
50 Notes
51 -----
52 This is deliberately not a `tuple` or other `~collections.abc.Sequence` in
53 order to make it typing-incompatible with sequence-based pixel coordinate
54 pairs (e.g. `.YX`). This also allows it to have addition and subtraction
55 operators.
56 """
58 i: int
59 """The y / row object."""
61 j: int
62 """The x / column object."""
64 def __add__(self, other: CellIJ) -> CellIJ:
65 return CellIJ(i=self.i + other.i, j=self.j + other.j)
67 def __sub__(self, other: CellIJ) -> CellIJ:
68 return CellIJ(i=self.i - other.i, j=self.j - other.j)
70 @staticmethod
71 def from_legacy(legacy_index: LegacyIndex2D) -> CellIJ:
72 """Convert from a legacy `lsst.skymap.Index2D` instance.
74 Notes
75 -----
76 `lsst.skymap.Index2D` is ordered ``(x, y)``, i.e. ``(j, i)``.
77 """
78 return CellIJ(i=legacy_index.y, j=legacy_index.x)
80 def to_legacy(self) -> LegacyIndex2D:
81 """Convert to a legacy `lsst.skymap.Index2D` instance.
83 Notes
84 -----
85 `lsst.skymap.Index2D` is ordered ``(x, y)``, i.e. ``(j, i)``.
86 """
87 from lsst.skymap import Index2D as LegacyIndex2D
89 return LegacyIndex2D(x=self.j, y=self.i)
91 def as_tuple(self) -> tuple[int, int]:
92 """Convert to an (i, j) `tuple`."""
93 return (self.i, self.j)
96class CellGrid(pydantic.BaseModel, frozen=True):
97 """A grid of rectangular cells with no overlaps or space between cells.
99 Notes
100 -----
101 A cell grid usually corresponds to a full patch, but we do not explicitly
102 encode this in the type to permit full-tract grids, which would have to
103 drop the cells in patch overlap regions and re-label all cells.
105 Subsets of grids are usually represented via `CellGridBounds`.
106 """
108 bbox: Box = pydantic.Field(
109 description=(
110 "Bounding box of the grid of cells (snapped to cell boundaries. "
111 "The cell with index (i=0, j=0) always has a corner at ``(y=bbox.y.min, x=bbox.x.min)`` "
112 "but there is no expectation that ``(y=bbox.y.min, x=bbox.x.min)`` be ``(y=0, x=0)``."
113 )
114 )
115 cell_shape: YX[int] = pydantic.Field(description="Shape of each cell in pixels.")
117 @property
118 def grid_size(self) -> CellIJ:
119 """The number of cells in each dimension (`CellIJ`)."""
120 return CellIJ(i=self.bbox.y.size // self.cell_shape.y, j=self.bbox.x.size // self.cell_shape.x)
122 def index_of(self, *, y: int, x: int) -> CellIJ:
123 """Return the 2-d index of the cell that contains the given pixel.
125 Parameters
126 ----------
127 y
128 Y cell index.
129 x
130 X cell index.
131 """
132 return CellIJ(
133 i=(y - self.bbox.y.start) // self.cell_shape.y,
134 j=(x - self.bbox.x.start) // self.cell_shape.x,
135 )
137 def bbox_of(self, cell: CellIJ) -> Box:
138 """Return the bounding box of the given cell."""
139 return Box.from_shape(
140 self.cell_shape,
141 start=YX(
142 y=cell.i * self.cell_shape.y + self.bbox.y.start,
143 x=cell.j * self.cell_shape.x + self.bbox.x.start,
144 ),
145 )
147 @staticmethod
148 def from_legacy(legacy: LegacyUniformGrid) -> CellGrid:
149 """Construct from a legacy `lsst.cell_coadds.UniformGrid` object.
151 Parameters
152 ----------
153 legacy
154 Legacy grid to convert.
155 """
156 if legacy.padding:
157 raise ValueError("Only cell grids with no padding are supported.")
158 bbox = Box.from_legacy(legacy.bbox)
159 cell_shape = YX(y=legacy.cell_size.y, x=legacy.cell_size.x)
160 return CellGrid(bbox=bbox, cell_shape=cell_shape)
162 def to_legacy(self) -> LegacyUniformGrid:
163 """Convert to a legacy `lsst.cell_coadds.UniformGrid` object."""
164 from lsst.cell_coadds import UniformGrid as LegacyUniformGrid
166 return LegacyUniformGrid(
167 self.cell_shape.to_legacy_extent(),
168 self.grid_size.to_legacy(),
169 min=self.bbox.min.to_legacy_point(),
170 )
173class CellGridBounds(pydantic.BaseModel, frozen=True):
174 """A region of pixels defined by a set of cells within a grid.
176 Notes
177 -----
178 This data structure is optimized for the case where a continguous
179 rectangular region of the grid (the `bbox` attribute) is populated with
180 only a few exceptions (the `missing` set).
182 Slicing a `CellGridBounds` with a `.Box` returns a new `CellGridBounds`
183 with just the cells that overlap that box. As always,
184 `CellGridBounds.bbox` will be snapped to the outer boundaries of those
185 cells, so it will contain (and not generally equal) the given box.
186 """
188 grid: CellGrid = pydantic.Field(description="Definition of the grid that defines the cells.")
189 bbox: Box = pydantic.Field(description="Pixel bounding box of the region (snapped to cell boundaries).")
190 missing: frozenset[CellIJ] = pydantic.Field(
191 default=frozenset(),
192 description=(
193 "Indices of cells that are missing, where (i=0, j=0) is the cell that starts at grid.bbox.start."
194 ),
195 )
197 @cached_property
198 def subgrid_start(self) -> CellIJ:
199 """The index of the first cell in this bounds' bounding box within
200 its grid.
201 """
202 return self.grid.index_of(y=self.bbox.y.start, x=self.bbox.x.start)
204 @cached_property
205 def subgrid_stop(self) -> CellIJ:
206 """One-past-the-last indices for the cells in these bounds, within
207 its grid.
208 """
209 return self.grid.index_of(y=self.bbox.y.stop, x=self.bbox.x.stop)
211 @cached_property
212 def subgrid_size(self) -> CellIJ:
213 """Number of cells within these bounds in both dimensions, not
214 accounting for `missing`.
215 """
216 return self.subgrid_stop - self.subgrid_start
218 @overload
219 def contains(self, *, x: int, y: int) -> bool: ... 219 ↛ exitline 219 didn't return from function 'contains' because
221 @overload
222 def contains(self, *, x: np.ndarray, y: np.ndarray) -> np.ndarray: ... 222 ↛ exitline 222 didn't return from function 'contains' because
224 def contains(self, *, x: Any, y: Any) -> Any:
225 """Test whether these bounds contain one or more points.
227 Parameters
228 ----------
229 x
230 One or more integer X coordinates to test for containment.
231 If an array, an array of results will be returned.
232 y
233 One or more integer Y coordinates to test for containment.
234 If an array, an array of results will be returned.
236 Returns
237 -------
238 `bool` | `numpy.ndarray`
239 If ``x`` and ``y`` are both scalars, a single `bool` value. If
240 ``x`` and ``y`` are arrays, a boolean array with their broadcasted
241 shape.
242 """
243 result = self.bbox.contains(x=x, y=y)
244 if not self.missing:
245 return result
246 match result:
247 case False:
248 return False
249 case True:
250 return self.grid.index_of(x=x, y=y) not in self.missing
251 case np.ndarray():
252 for box in self.missing_boxes():
253 result = np.logical_and(result, np.logical_not(box.contains(x=x, y=y)))
254 return result
256 def intersection(self, other: Bounds) -> Bounds:
257 """Compute the intersection of this bounds object with another."""
258 from ._concrete_bounds import _intersect_cgb
260 return _intersect_cgb(self, other)
262 def contains_cell(self, index: CellIJ) -> bool:
263 """Test whether the given cell is in the bounds."""
264 return (
265 (index.i >= self.subgrid_start.i and index.i < self.subgrid_stop.i)
266 and (index.j >= self.subgrid_start.j and index.j < self.subgrid_stop.j)
267 and index not in self.missing
268 )
270 def missing_boxes(self) -> Iterator[Box]:
271 """Iterate over the bounding boxes of the missing cells."""
272 for index in sorted(self.missing):
273 yield self.grid.bbox_of(index)
275 def cell_indices(self) -> Iterator[CellIJ]:
276 """Iterate over the indices of the cells in these bounds."""
277 for i in range(self.subgrid_start.i, self.subgrid_stop.i):
278 for j in range(self.subgrid_start.j, self.subgrid_stop.j):
279 index = CellIJ(i=i, j=j)
280 if index not in self.missing:
281 yield index
283 def __getitem__(self, bbox: Box) -> CellGridBounds:
284 if not self.bbox.contains(bbox): 284 ↛ 285line 284 didn't jump to line 285 because the condition on line 284 was never true
285 raise ValueError(
286 f"Original grid bounding box {self.bbox} does not contain the subset bounding box {bbox}."
287 )
288 c = self.grid.cell_shape
289 s = self.grid.bbox.start
290 i1 = (bbox.y.start - s.y) // c.y
291 j1 = (bbox.x.start - s.x) // c.x
292 i2 = math.ceil((bbox.y.stop - s.y) / c.y)
293 j2 = math.ceil((bbox.x.stop - s.x) / c.x)
294 subset_bbox = Box.factory[i1 * c.y + s.y : i2 * c.y + s.y, j1 * c.x + s.x : j2 * c.x + s.x]
295 grid_as_box = Box.factory[i1:i2, j1:j2]
296 subset_missing = {index for index in self.missing if grid_as_box.contains(y=index.i, x=index.j)}
297 return CellGridBounds(grid=self.grid, bbox=subset_bbox, missing=frozenset(subset_missing))
299 def serialize(self) -> CellGridBounds:
300 """Convert a bounds instance into a serializable object."""
301 return self
303 def deserialize(self) -> CellGridBounds:
304 """Deserialize a bounds object on the assumption it is a
305 `CellGridBounds`.
307 This method just returns the `CellGridBounds` itself, since that
308 already provides Pydantic serialization hooks. It exists for
309 compatibility with the `.Bounds` protocol.
310 """
311 return self
314class PatchDefinition(pydantic.BaseModel, frozen=True):
315 """Identifiers and geometry for a full patch."""
317 id: int = pydantic.Field(description="ID for the patch.")
318 index: YX[int] = pydantic.Field(description="2-d index of this patch within the tract.")
319 inner_bbox: Box = pydantic.Field(description="Inner bounding box of this patch.")
320 cells: CellGrid = pydantic.Field(description="Cell grid for the full patch.")
322 @property
323 def outer_bbox(self) -> Box:
324 """The outer bounding box of this patch (`.Box`)."""
325 return self.cells.bbox