Coverage for python/lsst/cell_coadds/_multiple_cell_coadd.py: 50%
87 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-12 14:15 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-12 14:15 +0000
1# This file is part of cell_coadds.
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 <https://www.gnu.org/licenses/>.
22from __future__ import annotations
24__all__ = ("MultipleCellCoadd",)
26from collections.abc import Iterable, Set
27from typing import TYPE_CHECKING
29from lsst.geom import Box2I
31from ._common_components import CommonComponents, CommonComponentsProperties
32from ._exploded_coadd import ExplodedCoadd
33from ._grid_container import GridContainer
34from ._single_cell_coadd import SingleCellCoadd
35from ._stitched_coadd import StitchedCoadd
36from ._uniform_grid import UniformGrid
38if TYPE_CHECKING: 38 ↛ 39line 38 didn't jump to line 39, because the condition on line 38 was never true
39 from lsst.daf.base import PropertySet
40 from lsst.geom import Extent2I
43class MultipleCellCoadd(CommonComponentsProperties):
44 """A data structure for coadds built from many overlapping cells.
46 Notes
47 -----
48 `MultipleCellCoadd` is designed to be used both by measurement algorithms
49 that are able to take advantage of cell boundaries and overlap regions
50 (which can use the ``.cells`` attribute to access `SingleCellCoadd` objects
51 directly) and measurement algorithms that just want one image and don't
52 care (or don't care much) about discontinuities (which can use `stitch` to
53 obtain such an image).
55 Indexing with `Box2I` yields a `MultipleCellCoadd` view containing just the
56 cells that overlap that region.
57 """
59 def __init__(
60 self,
61 cells: Iterable[SingleCellCoadd],
62 grid: UniformGrid,
63 outer_cell_size: Extent2I,
64 psf_image_size: Extent2I,
65 *,
66 common: CommonComponents,
67 inner_bbox: Box2I | None = None,
68 ):
69 self._grid = grid
70 self._outer_cell_size = outer_cell_size
71 self._psf_image_size = psf_image_size
72 self._common = common
73 cells_builder = GridContainer[SingleCellCoadd](self._grid.shape)
74 self._mask_fraction_names: set[str] = set()
75 for cell in cells:
76 index = cell.identifiers.cell
77 cells_builder[index] = cell
78 if cell.inner.bbox != self._grid.bbox_of(index):
79 raise ValueError(
80 f"Cell at index {index} has inner bbox {cell.inner.bbox}, "
81 f"but grid expects {self._grid.bbox_of(index)}."
82 )
83 if cell.outer.bbox.getDimensions() != self._outer_cell_size:
84 raise ValueError(
85 f"Cell at index {index} has outer dimensions {cell.outer.bbox.getDimensions()}, "
86 f"but coadd expects {self._outer_cell_size}."
87 )
88 if cell.psf_image.getDimensions() != self._psf_image_size:
89 raise ValueError(
90 f"Cell at index {index} has PSF image with dimensions {cell.psf_image.getDimensions()}, "
91 f"but coadd expects {self._psf_image_size}."
92 )
94 self._cells = cells_builder
95 n_noise_realizations = {len(cell.outer.noise_realizations) for cell in self._cells.values()}
96 self._n_noise_realizations = n_noise_realizations.pop()
97 if n_noise_realizations:
98 n_noise_realizations.add(self._n_noise_realizations)
99 raise ValueError(
100 f"Inconsistent number of noise realizations ({n_noise_realizations}) betwen cells."
101 )
102 max_inner_bbox = Box2I(self._cells.first.inner.bbox.getMin(), self._cells.last.inner.bbox.getMax())
103 if inner_bbox is None:
104 inner_bbox = max_inner_bbox
105 elif not max_inner_bbox.contains(inner_bbox):
106 raise ValueError(
107 f"Requested inner bounding box {inner_bbox} is not fully covered by these "
108 f"cells (bbox is {max_inner_bbox})."
109 )
110 self._inner_bbox = inner_bbox
112 @property
113 def cells(self) -> GridContainer[SingleCellCoadd]:
114 """The grid of single-cell coadds, indexed by (y, x)."""
115 return self._cells
117 @property
118 def n_noise_realizations(self) -> int:
119 """The number of noise realizations cells are guaranteed to have."""
120 return self._n_noise_realizations
122 @property
123 def mask_fraction_names(self) -> Set[str]:
124 """The names of all mask planes whose fractions were propagated in any
125 cell.
127 Cells that do not have a mask fraction for a particular name may be
128 assumed to have the fraction for that mask plane uniformly zero.
129 """
130 return self._mask_fraction_names
132 @property
133 def grid(self) -> UniformGrid:
134 """Object that defines the inner geometry for all cells."""
135 return self._grid
137 @property
138 def outer_cell_size(self) -> Extent2I:
139 """Dimensions of the outer region of each cell."""
140 return self._outer_cell_size
142 @property
143 def psf_image_size(self) -> Extent2I:
144 """Dimensions of PSF model images."""
145 return self._psf_image_size
147 @property
148 def outer_bbox(self) -> Box2I:
149 """The rectangular region fully covered by all cell outer bounding
150 boxes.
151 """
152 return Box2I(self.cells.first.outer.bbox.getMin(), self.cells.last.outer.bbox.getMax())
154 @property
155 def inner_bbox(self) -> Box2I:
156 """The rectangular region fully covered by all cell inner bounding
157 boxes.
158 """
159 return self._inner_bbox
161 @property
162 def common(self) -> CommonComponents:
163 # Docstring inherited.
164 return self._common
166 def stitch(self, bbox: Box2I | None = None) -> StitchedCoadd:
167 """Return a contiguous (but in general discontinuous) coadd by
168 stitching together inner cells.
170 Parameters
171 ----------
172 bbox : `Box2I`, optional
173 Region for the returned coadd; default is ``self.inner_bbox``.
175 Returns
176 -------
177 stitched : `StitchedCellCoadd`
178 Contiguous coadd covering the given area. Each image plane is
179 actually constructed when first accessed, not when this method
180 is called.
181 """
182 # In the future, stitching algorithms that apply ramps to smooth
183 # discontinuities may also be provided; we'd implement that by having
184 # this return different types (from a common ABC), perhaps dispatched
185 # by an enum.
186 return StitchedCoadd(self, bbox=bbox)
188 def explode(self, pad_psfs_with: float | None = None) -> ExplodedCoadd:
189 """Return a coadd whose image planes stitch together the outer regions
190 of each cell, duplicating pixels in the overlap regions.
192 Parameters
193 ----------
194 pad_psfs_with : `float` or None, optional
195 A floating-point value to pad PSF images with so each PSF-image
196 cell has the same dimensions as the image (outer) cell it
197 corresponds to. If `None`, PSF images will not be padded and the
198 full PSF image will generally be smaller than the exploded image it
199 corresponds to.
201 Returns
202 -------
203 exploded : `ExplodedCoadd`
204 Exploded version of the coadd.
205 """
206 return ExplodedCoadd(self, pad_psfs_with=pad_psfs_with)
208 @classmethod
209 def read_fits(cls, filename: str) -> MultipleCellCoadd:
210 """Read a MultipleCellCoadd from a FITS file.
212 Parameters
213 ----------
214 filename : `str`
215 The path to the FITS file to read.
217 Returns
218 -------
219 cell_coadd : `MultipleCellCoadd`
220 The MultipleCellCoadd object read from the FITS file.
221 """
222 from ._fits import CellCoaddFitsReader # Avoid circular import.
224 reader = CellCoaddFitsReader(filename)
225 return reader.readAsMultipleCellCoadd()
227 @classmethod
228 def readFits(cls, *args, **kwargs) -> MultipleCellCoadd: # type: ignore[no-untyped-def]
229 """Alias to `read_fits` method.
231 Notes
232 -----
233 This method exists for compatability with the rest of the codebase.
234 The presence of this method allows for reading in via
235 `lsst.obs.base.formatters.FitsGenericFormatter`.
236 Whenever possible, use `read_fits` instead, since this method may be
237 deprecated in the near future.
238 """
239 return cls.read_fits(*args, **kwargs)
241 def write_fits(self, filename: str, overwrite: bool = False, metadata: PropertySet | None = None) -> None:
242 """Write the coadd as a FITS file.
244 Parameters
245 ----------
246 filename : `str`
247 The path to the FITS file to write.
248 overwrite : `bool`, optional
249 Whether to overwrite an existing file?
250 metadata : `~lsst.daf.base.PropertySet`, optional
251 Additional metadata to write to the FITS header.
252 """
253 from ._fits import writeMultipleCellCoaddAsFits # Avoid circular import.
255 writeMultipleCellCoaddAsFits(self, filename, overwrite=overwrite, metadata=metadata)
257 def writeFits(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
258 """Alias to `write_fits` method.
260 Notes
261 -----
262 This method exists for compatability with the rest of the codebase.
263 The presence of this method allows for persistence via
264 `lsst.obs.base.formatters.FitsGenericFormatter`.
265 Whenever possible, use `write_fits` instead, since this method may be
266 deprecated in the near future.
267 """
268 self.write_fits(*args, **kwargs)