Coverage for python/lsst/cell_coadds/_multiple_cell_coadd.py: 49%

88 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-04-04 03:56 -0700

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/>. 

21 

22from __future__ import annotations 

23 

24__all__ = ("MultipleCellCoadd",) 

25 

26from collections.abc import Iterable, Set 

27from typing import TYPE_CHECKING 

28 

29from lsst.geom import Box2I 

30 

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 

37 

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 

41 

42 

43class MultipleCellCoadd(CommonComponentsProperties): 

44 """A data structure for coadds built from many overlapping cells. 

45 

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). 

54 

55 Indexing with `Box2I` yields a `MultipleCellCoadd` view containing just the 

56 cells that overlap that region. 

57 """ 

58 

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 

76 for cell in cells: 

77 index = cell.identifiers.cell 

78 cells_builder[index] = cell 

79 if cell.inner.bbox != self._grid.bbox_of(index): 

80 raise ValueError( 

81 f"Cell at index {index} has inner bbox {cell.inner.bbox}, " 

82 f"but grid expects {self._grid.bbox_of(index)}." 

83 ) 

84 if cell.outer.bbox.getDimensions() != self._outer_cell_size: 

85 raise ValueError( 

86 f"Cell at index {index} has outer dimensions {cell.outer.bbox.getDimensions()}, " 

87 f"but coadd expects {self._outer_cell_size}." 

88 ) 

89 if cell.psf_image.getDimensions() != self._psf_image_size: 

90 raise ValueError( 

91 f"Cell at index {index} has PSF image with dimensions {cell.psf_image.getDimensions()}, " 

92 f"but coadd expects {self._psf_image_size}." 

93 ) 

94 

95 self._cells = cells_builder 

96 n_noise_realizations = {len(cell.outer.noise_realizations) for cell in self._cells.values()} 

97 self._n_noise_realizations = n_noise_realizations.pop() 

98 if n_noise_realizations: 

99 n_noise_realizations.add(self._n_noise_realizations) 

100 raise ValueError( 

101 f"Inconsistent number of noise realizations ({n_noise_realizations}) between cells." 

102 ) 

103 

104 # Finish the construction without relying on the first and last of 

105 # self._cells so we can construct an instance with partial list. 

106 indices = list(cells_builder.indices()) 

107 max_inner_bbox = Box2I( 

108 grid.bbox_of(indices[0]).getMin(), 

109 grid.bbox_of(indices[-1]).getMax(), 

110 ) 

111 

112 if inner_bbox is None: 

113 inner_bbox = max_inner_bbox 

114 elif not max_inner_bbox.contains(inner_bbox): 

115 raise ValueError( 

116 f"Requested inner bounding box {inner_bbox} is not fully covered by these " 

117 f"cells (bbox is {max_inner_bbox})." 

118 ) 

119 self._inner_bbox = inner_bbox 

120 

121 @property 

122 def cells(self) -> GridContainer[SingleCellCoadd]: 

123 """The grid of single-cell coadds, indexed by (y, x).""" 

124 return self._cells 

125 

126 @property 

127 def n_noise_realizations(self) -> int: 

128 """The number of noise realizations cells are guaranteed to have.""" 

129 return self._n_noise_realizations 

130 

131 @property 

132 def mask_fraction_names(self) -> Set[str]: 

133 """The names of all mask planes whose fractions were propagated in any 

134 cell. 

135 

136 Cells that do not have a mask fraction for a particular name may be 

137 assumed to have the fraction for that mask plane uniformly zero. 

138 """ 

139 return self._mask_fraction_names 

140 

141 @property 

142 def grid(self) -> UniformGrid: 

143 """Object that defines the inner geometry for all cells.""" 

144 return self._grid 

145 

146 @property 

147 def outer_cell_size(self) -> Extent2I: 

148 """Dimensions of the outer region of each cell.""" 

149 return self._outer_cell_size 

150 

151 @property 

152 def psf_image_size(self) -> Extent2I: 

153 """Dimensions of PSF model images.""" 

154 return self._psf_image_size 

155 

156 @property 

157 def outer_bbox(self) -> Box2I: 

158 """The rectangular region fully covered by all cell outer bounding 

159 boxes. 

160 """ 

161 return Box2I(self.cells.first.outer.bbox.getMin(), self.cells.last.outer.bbox.getMax()) 

162 

163 @property 

164 def inner_bbox(self) -> Box2I: 

165 """The rectangular region fully covered by all cell inner bounding 

166 boxes. 

167 """ 

168 return self._inner_bbox 

169 

170 @property 

171 def common(self) -> CommonComponents: 

172 # Docstring inherited. 

173 return self._common 

174 

175 def stitch(self, bbox: Box2I | None = None) -> StitchedCoadd: 

176 """Return a contiguous (but in general discontinuous) coadd by 

177 stitching together inner cells. 

178 

179 Parameters 

180 ---------- 

181 bbox : `Box2I`, optional 

182 Region for the returned coadd; default is ``self.inner_bbox``. 

183 

184 Returns 

185 ------- 

186 stitched : `StitchedCellCoadd` 

187 Contiguous coadd covering the given area. Each image plane is 

188 actually constructed when first accessed, not when this method 

189 is called. 

190 """ 

191 # In the future, stitching algorithms that apply ramps to smooth 

192 # discontinuities may also be provided; we'd implement that by having 

193 # this return different types (from a common ABC), perhaps dispatched 

194 # by an enum. 

195 return StitchedCoadd(self, bbox=bbox) 

196 

197 def explode(self, pad_psfs_with: float | None = None) -> ExplodedCoadd: 

198 """Return a coadd whose image planes stitch together the outer regions 

199 of each cell, duplicating pixels in the overlap regions. 

200 

201 Parameters 

202 ---------- 

203 pad_psfs_with : `float` or None, optional 

204 A floating-point value to pad PSF images with so each PSF-image 

205 cell has the same dimensions as the image (outer) cell it 

206 corresponds to. If `None`, PSF images will not be padded and the 

207 full PSF image will generally be smaller than the exploded image it 

208 corresponds to. 

209 

210 Returns 

211 ------- 

212 exploded : `ExplodedCoadd` 

213 Exploded version of the coadd. 

214 """ 

215 return ExplodedCoadd(self, pad_psfs_with=pad_psfs_with) 

216 

217 @classmethod 

218 def read_fits(cls, filename: str) -> MultipleCellCoadd: 

219 """Read a MultipleCellCoadd from a FITS file. 

220 

221 Parameters 

222 ---------- 

223 filename : `str` 

224 The path to the FITS file to read. 

225 

226 Returns 

227 ------- 

228 cell_coadd : `MultipleCellCoadd` 

229 The MultipleCellCoadd object read from the FITS file. 

230 """ 

231 from ._fits import CellCoaddFitsReader # Avoid circular import. 

232 

233 reader = CellCoaddFitsReader(filename) 

234 return reader.readAsMultipleCellCoadd() 

235 

236 @classmethod 

237 def readFits(cls, *args, **kwargs) -> MultipleCellCoadd: # type: ignore[no-untyped-def] 

238 """Alias to `read_fits` method. 

239 

240 Notes 

241 ----- 

242 This method exists for compatability with the rest of the codebase. 

243 The presence of this method allows for reading in via 

244 `lsst.obs.base.formatters.FitsGenericFormatter`. 

245 Whenever possible, use `read_fits` instead, since this method may be 

246 deprecated in the near future. 

247 """ 

248 return cls.read_fits(*args, **kwargs) 

249 

250 def write_fits(self, filename: str, overwrite: bool = False, metadata: PropertySet | None = None) -> None: 

251 """Write the coadd as a FITS file. 

252 

253 Parameters 

254 ---------- 

255 filename : `str` 

256 The path to the FITS file to write. 

257 overwrite : `bool`, optional 

258 Whether to overwrite an existing file? 

259 metadata : `~lsst.daf.base.PropertySet`, optional 

260 Additional metadata to write to the FITS header. 

261 """ 

262 from ._fits import writeMultipleCellCoaddAsFits # Avoid circular import. 

263 

264 writeMultipleCellCoaddAsFits(self, filename, overwrite=overwrite, metadata=metadata) 

265 

266 def writeFits(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def] 

267 """Alias to `write_fits` method. 

268 

269 Notes 

270 ----- 

271 This method exists for compatability with the rest of the codebase. 

272 The presence of this method allows for persistence via 

273 `lsst.obs.base.formatters.FitsGenericFormatter`. 

274 Whenever possible, use `write_fits` instead, since this method may be 

275 deprecated in the near future. 

276 """ 

277 self.write_fits(*args, **kwargs)