Coverage for python/lsst/images/_cell_grid.py: 45%
153 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 20:37 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 20:37 +0000
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, assert_type, overload
32import numpy as np
33import numpy.typing as npt
34import pydantic
36from ._geom import XY, YX, Bounds, Box, SerializableYX
38if TYPE_CHECKING:
39 try:
40 from lsst.cell_coadds import UniformGrid as LegacyUniformGrid
41 from lsst.skymap import Index2D as LegacyIndex2D
42 from lsst.skymap import PatchInfo as LegacyPatchInfo
43 except ImportError:
44 type LegacyUniformGrid = Any # type: ignore[no-redef]
45 type LegacyIndex2D = Any # type: ignore[no-redef]
46 type LegacyPatchInfo = Any # type: ignore[no-redef]
49@dataclasses.dataclass(frozen=True, order=True)
50class CellIJ:
51 """An index in a grid of cells.
53 Notes
54 -----
55 This is deliberately not a `tuple` or other `~collections.abc.Sequence` in
56 order to make it typing-incompatible with sequence-based pixel coordinate
57 pairs (e.g. `.YX`). This also allows it to have addition and subtraction
58 operators.
59 """
61 i: int
62 """The y / row object."""
64 j: int
65 """The x / column object."""
67 def __add__(self, other: CellIJ) -> CellIJ:
68 return CellIJ(i=self.i + other.i, j=self.j + other.j)
70 def __sub__(self, other: CellIJ) -> CellIJ:
71 return CellIJ(i=self.i - other.i, j=self.j - other.j)
73 @staticmethod
74 def from_legacy(legacy_index: LegacyIndex2D) -> CellIJ:
75 """Convert from a legacy `lsst.skymap.Index2D` instance.
77 Parameters
78 ----------
79 legacy_index
80 Legacy `lsst.skymap.Index2D` to convert.
82 Notes
83 -----
84 `lsst.skymap.Index2D` is ordered ``(x, y)``, i.e. ``(j, i)``.
85 """
86 return CellIJ(i=legacy_index.y, j=legacy_index.x)
88 def to_legacy(self) -> LegacyIndex2D:
89 """Convert to a legacy `lsst.skymap.Index2D` instance.
91 Notes
92 -----
93 `lsst.skymap.Index2D` is ordered ``(x, y)``, i.e. ``(j, i)``.
94 """
95 from lsst.skymap import Index2D as LegacyIndex2D
97 return LegacyIndex2D(x=self.j, y=self.i)
99 def as_tuple(self) -> tuple[int, int]:
100 """Convert to an (i, j) `tuple`."""
101 return (self.i, self.j)
103 def within_subgrid_array(self, bounds: CellGridBounds) -> tuple[int, int]:
104 """Return the indices of this cell within an array sized to a
105 `CellGridBounds`.
107 Parameters
108 ----------
109 bounds
110 Bounds whose subgrid corresponds to the array being indexes.
111 """
112 return (self - bounds.subgrid_start).as_tuple()
115class CellGrid(pydantic.BaseModel, frozen=True):
116 """A grid of rectangular cells with no overlaps or space between cells.
118 Notes
119 -----
120 A cell grid usually corresponds to a full patch, but we do not explicitly
121 encode this in the type to permit full-tract grids, which would have to
122 drop the cells in patch overlap regions and re-label all cells.
124 Subsets of grids are usually represented via `CellGridBounds`.
125 """
127 bbox: Box = pydantic.Field(
128 description=(
129 "Bounding box of the grid of cells (snapped to cell boundaries. "
130 "The cell with index (i=0, j=0) always has a corner at ``(y=bbox.y.min, x=bbox.x.min)`` "
131 "but there is no expectation that ``(y=bbox.y.min, x=bbox.x.min)`` be ``(y=0, x=0)``."
132 )
133 )
134 cell_shape: SerializableYX[int] = pydantic.Field(description="Shape of each cell in pixels.")
136 def __str__(self) -> str:
137 return f"{self.bbox}, cell_shape=(y={self.cell_shape.y}, x={self.cell_shape.x})"
139 @property
140 def grid_size(self) -> CellIJ:
141 """The number of cells in each dimension (`CellIJ`)."""
142 return CellIJ(i=self.bbox.y.size // self.cell_shape.y, j=self.bbox.x.size // self.cell_shape.x)
144 def index_of(self, *, y: int, x: int) -> CellIJ:
145 """Return the 2-d index of the cell that contains the given pixel.
147 Parameters
148 ----------
149 y
150 Y cell index.
151 x
152 X cell index.
153 """
154 return CellIJ(
155 i=(y - self.bbox.y.start) // self.cell_shape.y,
156 j=(x - self.bbox.x.start) // self.cell_shape.x,
157 )
159 def bbox_of(self, cell: CellIJ) -> Box:
160 """Return the bounding box of the given cell.
162 Parameters
163 ----------
164 cell
165 Index of the cell whose bounding box is returned.
166 """
167 return Box.from_shape(
168 self.cell_shape,
169 start=YX(
170 y=cell.i * self.cell_shape.y + self.bbox.y.start,
171 x=cell.j * self.cell_shape.x + self.bbox.x.start,
172 ),
173 )
175 @staticmethod
176 def from_legacy(legacy: LegacyUniformGrid) -> CellGrid:
177 """Construct from a legacy `lsst.cell_coadds.UniformGrid` object.
179 Parameters
180 ----------
181 legacy
182 Legacy grid to convert.
183 """
184 if legacy.padding:
185 raise ValueError("Only cell grids with no padding are supported.")
186 bbox = Box.from_legacy(legacy.bbox)
187 cell_shape = YX(y=legacy.cell_size.y, x=legacy.cell_size.x)
188 return CellGrid(bbox=bbox, cell_shape=cell_shape)
190 def to_legacy(self) -> LegacyUniformGrid:
191 """Convert to a legacy `lsst.cell_coadds.UniformGrid` object."""
192 from lsst.cell_coadds import UniformGrid as LegacyUniformGrid
194 return LegacyUniformGrid(
195 self.cell_shape.to_legacy_int_extent(),
196 self.grid_size.to_legacy(),
197 min=self.bbox.min.to_legacy_int_point(),
198 )
201class CellGridBounds(pydantic.BaseModel, frozen=True):
202 """A region of pixels defined by a set of cells within a grid.
204 Notes
205 -----
206 This data structure is optimized for the case where a continguous
207 rectangular region of the grid (the `bbox` attribute) is populated with
208 only a few exceptions (the `missing` set).
210 Slicing a `CellGridBounds` with a `.Box` returns a new `CellGridBounds`
211 with just the cells that overlap that box. As always,
212 `CellGridBounds.bbox` will be snapped to the outer boundaries of those
213 cells, so it will contain (and not generally equal) the given box.
214 """
216 grid: CellGrid = pydantic.Field(description="Definition of the grid that defines the cells.")
217 bbox: Box = pydantic.Field(description="Pixel bounding box of the region (snapped to cell boundaries).")
218 missing: frozenset[CellIJ] = pydantic.Field(
219 default=frozenset(),
220 description=(
221 "Indices of cells that are missing, where (i=0, j=0) is the cell that starts at grid.bbox.start."
222 ),
223 )
225 def __str__(self) -> str:
226 text = f"{self.bbox} in grid ({self.grid})"
227 if self.missing:
228 missing = ", ".join(f"(i={c.i}, j={c.j})" for c in sorted(self.missing))
229 text = f"{text}, missing={{{missing}}}"
230 return text
232 @cached_property
233 def subgrid_start(self) -> CellIJ:
234 """The index of the first cell in this bounds' bounding box within
235 its grid.
236 """
237 return self.grid.index_of(y=self.bbox.y.start, x=self.bbox.x.start)
239 @cached_property
240 def subgrid_stop(self) -> CellIJ:
241 """One-past-the-last indices for the cells in these bounds, within
242 its grid.
243 """
244 return self.grid.index_of(y=self.bbox.y.stop, x=self.bbox.x.stop)
246 @cached_property
247 def subgrid_size(self) -> CellIJ:
248 """Number of cells within these bounds in both dimensions, not
249 accounting for `missing`.
250 """
251 return self.subgrid_stop - self.subgrid_start
253 @property
254 def n_cells(self) -> int:
255 """Return the number of cells within this bounds, accounting for
256 `missing`.
257 """
258 return self.subgrid_size.i * self.subgrid_size.j - len(self.missing)
260 @overload
261 def contains(self, point: XY[int | float] | YX[int | float], /) -> bool: ...
263 @overload
264 def contains(self, point: XY[npt.ArrayLike] | YX[npt.ArrayLike], /) -> np.ndarray: ...
266 @overload
267 def contains(self, *, x: int | float, y: int | float) -> bool: ...
269 @overload
270 def contains(self, *, x: npt.ArrayLike, y: npt.ArrayLike) -> np.ndarray: ...
272 def contains(self, point: XY[Any] | YX[Any] | None = None, /, *, x: Any = None, y: Any = None) -> Any: # type: ignore[misc]
273 """Test whether these bounds contain one or more points.
275 Parameters
276 ----------
277 point
278 An `.XY` or `.YX` coordinate pair to test for containment.
279 Mutually exclusive with ``x`` and ``y``.
280 x
281 One or more X coordinates to test for containment, as a scalar or
282 any array-like. Results are broadcast against ``y``.
283 Mutually exclusive with ``point``.
284 y
285 One or more Y coordinates to test for containment, as a scalar or
286 any array-like. Results are broadcast against ``x``.
287 Mutually exclusive with ``point``.
289 Returns
290 -------
291 `bool` | `numpy.ndarray`
292 If ``x`` and ``y`` are both scalars, a single `bool` value. If
293 ``x`` and ``y`` are array-like, a boolean array with their
294 broadcasted shape.
295 """
296 match point:
297 case None:
298 if x is None or y is None: 298 ↛ 299line 298 didn't jump to line 299 because the condition on line 298 was never true
299 raise TypeError("Pass either a point or both x= and y= to 'CellGridBounds.contains'.")
300 case XY() | YX(): 300 ↛ 306line 300 didn't jump to line 306 because the pattern on line 300 always matched
301 if x is not None or y is not None: 301 ↛ 302line 301 didn't jump to line 302 because the condition on line 301 was never true
302 raise TypeError(
303 "'CellGridBounds.contains' point argument is mutually exclusive with x= and y=."
304 )
305 x, y = point.x, point.y
306 case _:
307 raise TypeError(f"Unexpected positional argument type: {type(point)!r}.")
308 result = self.bbox.contains(x=x, y=y)
309 if not self.missing:
310 return result
311 match result:
312 case False:
313 return False
314 case True:
315 return self.grid.index_of(x=x, y=y) not in self.missing
316 case np.ndarray(): 316 ↛ 319line 316 didn't jump to line 319 because the pattern on line 316 always matched
317 for box in self.missing_boxes():
318 result = np.logical_and(result, np.logical_not(box.contains(x=x, y=y)))
319 return result
321 def intersection(self, other: Bounds) -> Bounds:
322 """Compute the intersection of this bounds object with another.
324 Parameters
325 ----------
326 other
327 Bounds to intersect with this one.
328 """
329 from ._concrete_bounds import _intersect_cgb
331 return _intersect_cgb(self, other)
333 def contains_cell(self, index: CellIJ) -> bool:
334 """Test whether the given cell is in the bounds.
336 Parameters
337 ----------
338 index
339 Index of the cell to test.
340 """
341 return (
342 (index.i >= self.subgrid_start.i and index.i < self.subgrid_stop.i)
343 and (index.j >= self.subgrid_start.j and index.j < self.subgrid_stop.j)
344 and index not in self.missing
345 )
347 def missing_boxes(self) -> Iterator[Box]:
348 """Iterate over the bounding boxes of the missing cells."""
349 for index in sorted(self.missing):
350 yield self.grid.bbox_of(index)
352 def cell_indices(self) -> Iterator[CellIJ]:
353 """Iterate over the indices of the cells in these bounds."""
354 for i in range(self.subgrid_start.i, self.subgrid_stop.i):
355 for j in range(self.subgrid_start.j, self.subgrid_stop.j):
356 index = CellIJ(i=i, j=j)
357 if index not in self.missing:
358 yield index
360 def __getitem__(self, bbox: Box) -> CellGridBounds:
361 if not self.bbox.contains(bbox): 361 ↛ 362line 361 didn't jump to line 362 because the condition on line 361 was never true
362 raise ValueError(
363 f"Original grid bounding box {self.bbox} does not contain the subset bounding box {bbox}."
364 )
365 c = self.grid.cell_shape
366 s = self.grid.bbox.start
367 i1 = (bbox.y.start - s.y) // c.y
368 j1 = (bbox.x.start - s.x) // c.x
369 i2 = math.ceil((bbox.y.stop - s.y) / c.y)
370 j2 = math.ceil((bbox.x.stop - s.x) / c.x)
371 subset_bbox = Box.factory[i1 * c.y + s.y : i2 * c.y + s.y, j1 * c.x + s.x : j2 * c.x + s.x]
372 grid_as_box = Box.factory[i1:i2, j1:j2]
373 subset_missing = {index for index in self.missing if grid_as_box.contains(y=index.i, x=index.j)}
374 return CellGridBounds(grid=self.grid, bbox=subset_bbox, missing=frozenset(subset_missing))
376 def serialize(self) -> CellGridBounds:
377 """Convert a bounds instance into a serializable object."""
378 return self
380 def deserialize(self) -> CellGridBounds:
381 """Deserialize a bounds object on the assumption it is a
382 `CellGridBounds`.
384 This method just returns the `CellGridBounds` itself, since that
385 already provides Pydantic serialization hooks. It exists for
386 compatibility with the `.Bounds` protocol.
387 """
388 return self
391class PatchDefinition(pydantic.BaseModel, frozen=True):
392 """Identifiers and geometry for a full patch."""
394 id: int = pydantic.Field(description="ID for the patch.")
395 index: SerializableYX[int] = pydantic.Field(description="2-d index of this patch within the tract.")
396 inner_bbox: Box = pydantic.Field(description="Inner bounding box of this patch.")
397 cells: CellGrid = pydantic.Field(description="Cell grid for the full patch.")
399 def __str__(self) -> str:
400 return (
401 f"id={self.id}, index=(y={self.index.y}, x={self.index.x}), "
402 f"inner_bbox={self.inner_bbox}, cells=({self.cells})"
403 )
405 @property
406 def outer_bbox(self) -> Box:
407 """The outer bounding box of this patch (`.Box`)."""
408 return self.cells.bbox
410 @staticmethod
411 def from_legacy_patch_info(patch_info: LegacyPatchInfo) -> PatchDefinition:
412 """Convert from a legacy `lsst.skymap.PatchInfo` object.
414 Parameters
415 ----------
416 patch_info
417 Legacy patch definition to convert.
418 """
419 index = patch_info.getIndex()
420 cell_extent = patch_info.getCellInnerDimensions()
421 cell_grid = CellGrid(
422 bbox=Box.from_legacy(patch_info.getOuterBBox()),
423 cell_shape=YX(y=cell_extent.y, x=cell_extent.x),
424 )
425 return PatchDefinition(
426 id=patch_info.getSequentialIndex(),
427 index=YX(y=index.y, x=index.x),
428 inner_bbox=Box.from_legacy(patch_info.getInnerBBox()),
429 cells=cell_grid,
430 )
433if TYPE_CHECKING:
435 def _test_types() -> None:
436 arr = np.zeros(3)
437 bbox = Box.from_shape((100, 200))
438 grid = CellGrid(bbox=bbox, cell_shape=YX(10, 20))
439 cgb = CellGridBounds(grid=grid, bbox=bbox)
441 # CellGridBounds satisfies the Bounds Protocol.
442 bounds: Bounds = cgb
444 # CellGridBounds.contains: XY/YX, scalar, array-like
445 assert_type(cgb.contains(x=1, y=2), bool)
446 assert_type(cgb.contains(x=1.0, y=2.0), bool)
447 assert_type(cgb.contains(x=arr, y=arr), np.ndarray)
448 assert_type(cgb.contains(XY(1, 2)), bool)
449 assert_type(cgb.contains(YX(2, 1)), bool)
450 assert_type(cgb.contains(XY(arr, arr)), np.ndarray)
451 assert_type(cgb.contains(YX(arr, arr)), np.ndarray)
453 # Via the Bounds Protocol view, same signatures hold.
454 assert_type(bounds.contains(x=1, y=1), bool)
455 assert_type(bounds.contains(x=1.0, y=1.0), bool)
456 assert_type(bounds.contains(x=arr, y=arr), np.ndarray)
457 assert_type(bounds.contains(XY(1, 1)), bool)
458 assert_type(bounds.contains(YX(1, 1)), bool)
459 assert_type(bounds.contains(XY(arr, arr)), np.ndarray)
460 assert_type(bounds.contains(YX(arr, arr)), np.ndarray)