Coverage for python/lsst/images/cells/_aperture_corrections.py: 57%

215 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-26 12:09 -0800

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. 

11 

12from __future__ import annotations 

13 

14__all__ = ( 

15 "CellApertureCorrectionMapSerializationModel", 

16 "CellField", 

17 "approximate_aperture_corrections_from_legacy", 

18) 

19 

20from collections.abc import Mapping 

21from typing import TYPE_CHECKING, Any, ClassVar, final 

22 

23import astropy.table 

24import astropy.units 

25import numpy as np 

26import pydantic 

27 

28from .._cell_grid import CellGridBounds, CellIJ 

29from .._geom import BoundsError, Box 

30from .._image import Image 

31from ..fields import BaseField 

32from ..serialization import ( 

33 ArchiveReadError, 

34 ArchiveTree, 

35 InputArchive, 

36 InvalidParameterError, 

37 OutputArchive, 

38 TableModel, 

39) 

40 

41if TYPE_CHECKING: 

42 try: 

43 from lsst.afw.math import BoundedField as LegacyBoundedField 

44 from lsst.cell_coadds import StitchedApertureCorrection as LegacyStitchedApertureCorrection 

45 except ImportError: 

46 type LegacyBoundedField = Any # type: ignore[no-redef] 

47 type LegacyStitchedApertureCorrection = Any # type: ignore[no-redef] 

48 

49 

50@final 

51class CellField(BaseField): 

52 """A piecewise 2-d function on a cell-coadd grid. 

53 

54 Parameters 

55 ---------- 

56 bounds 

57 Description of the cell grid and any missing cells. Array entries for 

58 missing cells should be NaN. 

59 array 

60 A 2-d array of cell values with shape 

61 ``bounds.subgrid_size.as_tuple()``. 

62 unit 

63 Units of the field values, or `None` if dimensionless. 

64 

65 Notes 

66 ----- 

67 `CellField` is not directly serializable and is not included in the 

68 ``Field`` union type alias as a result. A `~collections.abc.Mapping` of 

69 `CellField` is instead serializable via 

70 `CellApertureCorrectionMapSerializationModel`. 

71 """ 

72 

73 def __init__( 

74 self, bounds: CellGridBounds, array: np.ndarray, unit: astropy.units.UnitBase | None = None 

75 ) -> None: 

76 self._array = array 

77 self._bounds = bounds 

78 self._unit = unit 

79 if self._array.shape != self._bounds.subgrid_size.as_tuple(): 79 ↛ 80line 79 didn't jump to line 80 because the condition on line 79 was never true

80 raise ValueError( 

81 f"Array shape ({self._array.shape}) differs from subgrid size ({self._bounds.subgrid_size})." 

82 ) 

83 

84 __hash__ = None # type: ignore[assignment] 

85 

86 @property 

87 def bounds(self) -> CellGridBounds: 

88 return self._bounds 

89 

90 @property 

91 def unit(self) -> astropy.units.UnitBase | None: 

92 return self._unit 

93 

94 @property 

95 def is_constant(self) -> bool: 

96 indices = iter(self._bounds.cell_indices()) 

97 try: 

98 first = self.value_in_cell(next(indices)) 

99 except StopIteration: 

100 return True 

101 for other_index in indices: 

102 if self.value_in_cell(other_index) != first: 

103 return False 

104 return True 

105 

106 def value_in_cell(self, key: CellIJ) -> float: 

107 """Return the value of the field in the cell with the given index. 

108 

109 Parameters 

110 ---------- 

111 key 

112 Index of the cell to evaluate. 

113 """ 

114 if key in self._bounds.missing: 

115 raise BoundsError(f"Cell {key} is missing for this field.") 

116 if not self._bounds.contains_cell(key): 

117 raise BoundsError(f"Cell {key} is out of bounds for this field.") 

118 index = key - self._bounds.subgrid_start 

119 try: 

120 return self._array[index.i, index.j] 

121 except IndexError: 

122 raise BoundsError(f"Cell {key} is out of bounds for this field.") from None 

123 

124 def quantity_in_cell(self, key: CellIJ) -> astropy.units.Quantity: 

125 """Return the quantity (value with units) of the field in the cell 

126 with the given index. 

127 

128 Parameters 

129 ---------- 

130 key 

131 Index of the cell to evaluate. 

132 """ 

133 return astropy.units.Quantity(self.value_in_cell(key), self._unit) 

134 

135 def _evaluate( 

136 self, *, x: np.ndarray, y: np.ndarray, quantity: bool 

137 ) -> np.ndarray | astropy.units.Quantity: 

138 # This implementation is optimized for the case where there are many 

139 # more evaluation points than cells. We could switch to an 

140 # implementation that zip-broadcast-iterates over x and y when that is 

141 # not the case, but that feels like a premature optimization right now. 

142 result = np.full(np.broadcast_shapes(y.shape, x.shape), np.nan, dtype=np.float64) 

143 for cell_index in self._bounds.cell_indices(): 

144 cell_bbox = self._bounds.grid.bbox_of(cell_index) 

145 result[cell_bbox.contains(x=x, y=y)] = self.value_in_cell(cell_index) 

146 if quantity: 146 ↛ 147line 146 didn't jump to line 147 because the condition on line 146 was never true

147 return astropy.units.Quantity(result, self._unit) 

148 return result 

149 

150 def render(self, bbox: Box | None = None, *, dtype: np.typing.DTypeLike | None = None) -> Image: 

151 if bbox is None: 

152 bbox = self._bounds.bbox 

153 bounds = self._bounds 

154 else: 

155 bounds = self._bounds[bbox] 

156 result = Image(np.nan, bbox=bbox, dtype=dtype, unit=self._unit) 

157 for cell_index in bounds.cell_indices(): 

158 cell_bbox = self._bounds.grid.bbox_of(cell_index).intersection(bbox) 

159 result[cell_bbox].array = self.value_in_cell(cell_index) 

160 return result 

161 

162 def _multiply_constant( 

163 self, factor: float | astropy.units.Quantity | astropy.units.UnitBase 

164 ) -> CellField: 

165 factor, unit = self._handle_factor_units(factor) 

166 return CellField(self._bounds, self._array * factor, unit=unit) 

167 

168 @staticmethod 

169 def from_legacy_aperture_correction( 

170 legacy: LegacyStitchedApertureCorrection, bounds: CellGridBounds 

171 ) -> CellField | None: 

172 """Convert from a legacy `lsst.cell_coadds.StitchedApertureCorrection`. 

173 

174 Parameters 

175 ---------- 

176 legacy 

177 Legacy field to convert. 

178 bounds 

179 The grid and bounds of the returned field. 

180 

181 Returns 

182 ------- 

183 field : `CellField` or `None` 

184 The converted field, or `None` if no cell has a usable value. 

185 """ 

186 array = np.full(bounds.subgrid_size.as_tuple(), np.nan, dtype=np.float64) 

187 new_missing: set[CellIJ] = set() 

188 for cell_index in bounds.cell_indices(): 

189 array_index = cell_index - bounds.subgrid_start 

190 try: 

191 value = legacy.gc[cell_index.to_legacy()] 

192 except KeyError: 

193 value = np.nan 

194 new_missing.add(cell_index) 

195 else: 

196 if not np.isfinite(value): 

197 value = np.nan 

198 new_missing.add(cell_index) 

199 array[array_index.i, array_index.j] = value 

200 if not set(bounds.cell_indices()) - new_missing: 

201 return None 

202 if new_missing: 

203 bounds = CellGridBounds( 

204 grid=bounds.grid, missing=frozenset(bounds.missing | new_missing), bbox=bounds.bbox 

205 ) 

206 return CellField(bounds, array) 

207 

208 def to_legacy_aperture_correction(self) -> LegacyStitchedApertureCorrection: 

209 """Convert to a legacy 

210 `lsst.cell_coadds.StitchedApertureCorrection`. 

211 """ 

212 from lsst.cell_coadds import GridContainer, StitchedApertureCorrection 

213 

214 grid = self.bounds.grid.to_legacy() 

215 gc = GridContainer[float](grid.shape) 

216 for cell_index in self.bounds.cell_indices(): 

217 gc[cell_index.to_legacy()] = self.value_in_cell(cell_index) 

218 return StitchedApertureCorrection(grid, gc) 

219 

220 @staticmethod 

221 def approximate_from_legacy( 

222 legacy: LegacyBoundedField, bounds: CellGridBounds, default_is_missing: bool = True 

223 ) -> CellField | None: 

224 """Convert from a legacy bounded field by evaluating it at cell 

225 centers and assuming variation within a cell is approximately 

226 constant. 

227 

228 When the center sample is unusable (e.g. the center falls outside 

229 the field's bounding box), the field is instead sampled at the 

230 cell's four corners and the usable samples are averaged. Cells 

231 with no usable sample at all are marked missing. 

232 

233 Parameters 

234 ---------- 

235 legacy 

236 Legacy bounded field to approximate. 

237 bounds 

238 Cell grid and known-missing cells. 

239 default_is_missing 

240 If `True` and ``legacy.getThrowOnMissing()`` returns `False`, 

241 treat values that are identical to ``legacy.getDefault()`` as 

242 missing. This covers some confusing 

243 `lsst.meas.algorithms.CoaddBoundedField` behavior for backwards 

244 compatibility. 

245 

246 Returns 

247 ------- 

248 field : `CellField` or `None` 

249 The converted field, or `None` if no cell has a usable value. 

250 """ 

251 from lsst.pex.exceptions import DomainError 

252 

253 get_throw_on_missing = getattr(legacy, "getThrowOnMissing", None) 

254 get_default = getattr(legacy, "getDefault", None) 

255 default = ( 

256 get_default() 

257 if default_is_missing 

258 and get_throw_on_missing is not None 

259 and get_default is not None 

260 and not get_throw_on_missing() 

261 else None 

262 ) 

263 

264 def usable(value: float) -> bool: 

265 return np.isfinite(value) and (default is None or value != default) 

266 

267 array = np.full(bounds.subgrid_size.as_tuple(), np.nan, dtype=np.float64) 

268 missing: set[CellIJ] = set() 

269 for cell_index in bounds.cell_indices(): 

270 cell_bbox = bounds.grid.bbox_of(cell_index) 

271 try: 

272 value = legacy.evaluate(cell_bbox.center.to_legacy_float_point()) 

273 except DomainError: 

274 value = np.nan 

275 if not usable(value): 

276 corner_values: list[float] = [] 

277 for corner in cell_bbox.boundary(): 

278 try: 

279 corner_value = legacy.evaluate(corner.to_legacy_float_point()) 

280 except DomainError: 

281 continue 

282 if not usable(corner_value): 

283 continue 

284 corner_values.append(corner_value) 

285 if not corner_values: 

286 missing.add(cell_index) 

287 continue 

288 else: 

289 value = np.mean(corner_values) 

290 array_index = cell_index - bounds.subgrid_start 

291 array[array_index.i, array_index.j] = value 

292 if not set(bounds.cell_indices()) - missing: 

293 return None 

294 if missing: 

295 bounds = CellGridBounds( 

296 grid=bounds.grid, missing=frozenset(bounds.missing | missing), bbox=bounds.bbox 

297 ) 

298 return CellField(bounds, array) 

299 

300 

301def approximate_aperture_corrections_from_legacy( 

302 legacy_map: Mapping[str, LegacyBoundedField], 

303 bounds: CellGridBounds, 

304 flux_suffix: str = "_instFlux", 

305 err_suffix: str = "_instFluxErr", 

306) -> dict[str, CellField | None]: 

307 """Convert a mapping of legacy aperture-correction bounded fields to 

308 `CellField` instances by approximating them on a cell grid. 

309 

310 Parameters 

311 ---------- 

312 legacy_map 

313 Mapping of aperture-correction names to legacy bounded fields, as 

314 returned by a legacy `lsst.afw.image.Exposure`'s ``getApCorrMap()``. 

315 bounds 

316 Cell grid and known-missing cells to convert onto. 

317 flux_suffix 

318 Suffix of the flux member of an aperture-correction name pair. 

319 err_suffix 

320 Suffix of the error member of an aperture-correction name pair. 

321 

322 Returns 

323 ------- 

324 `dict` [`str`, `CellField` | `None`] 

325 Mapping with the same keys, holding the converted fields. A name whose 

326 legacy field has no usable value in any cell maps to `None`. 

327 

328 Notes 

329 ----- 

330 This routine relies on the fact that aperture correction fields come in 

331 ``*_instFlux`` + ``*_instFluxErr`` pairs to resolve the fact that zero is 

332 a possible valid (albeit suspicious) value for the latter *and* the 

333 sentinel used for missing data. We assume a zero ``*_instFlux`` 

334 evaluation represents bad data, but a zero ``*_instFluxErr`` is bad data 

335 only if the corresponding ``*_instFlux`` evaluation is also bad data. 

336 """ 

337 converted: dict[str, CellField | None] = {} 

338 for name, legacy_field in legacy_map.items(): 

339 if name.endswith(err_suffix): 

340 continue 

341 converted[name] = CellField.approximate_from_legacy(legacy_field, bounds) 

342 for name, legacy_field in legacy_map.items(): 

343 if not name.endswith(err_suffix): 

344 continue 

345 flux_name = name[: -len(err_suffix)] + flux_suffix 

346 err_bounds = bounds 

347 if flux_name in converted: 

348 partner = converted[flux_name] 

349 if partner is None: 

350 # No usable flux anywhere, so every error value is bad data. 

351 converted[name] = None 

352 continue 

353 err_bounds = partner.bounds 

354 converted[name] = CellField.approximate_from_legacy( 

355 legacy_field, err_bounds, default_is_missing=False 

356 ) 

357 return converted 

358 

359 

360class CellApertureCorrectionMapSerializationModel(ArchiveTree): 

361 """A serialization model for a `~collections.abc.Mapping` of `CellField`, 

362 which is used to represent aperture corrections for cell-based coadds. 

363 """ 

364 

365 SCHEMA_NAME: ClassVar[str] = "cell_aperture_correction_map" 

366 SCHEMA_VERSION: ClassVar[str] = "1.0.0" 

367 MIN_READ_VERSION: ClassVar[int] = 1 

368 PUBLIC_TYPE: ClassVar[type] = dict 

369 

370 table: TableModel = pydantic.Field( 

371 description="Table with one row for each cell and different photometry algorithms in columns." 

372 ) 

373 bounds: CellGridBounds = pydantic.Field( 

374 description=( 

375 "Description of the cell grid and any missing cells. Array entries for " 

376 "missing cells should be NaN." 

377 ), 

378 ) 

379 

380 @staticmethod 

381 def serialize( 

382 aperture_correction_map: Mapping[str, CellField | None], archive: OutputArchive[Any] 

383 ) -> CellApertureCorrectionMapSerializationModel | None: 

384 """Serialize an aperture-correction map, one table column per name. 

385 

386 Names that map to `None` are written as columns that are entirely NaN. 

387 A map whose every name is `None` is written as no aperture 

388 corrections (top-level `None`). 

389 

390 Parameters 

391 ---------- 

392 aperture_correction_map 

393 Aperture corrections to write, keyed by name. A name with no 

394 usable value in any cell maps to `None`. 

395 archive 

396 Archive to add the cell-value table to. 

397 

398 Returns 

399 ------- 

400 model : `CellApertureCorrectionMapSerializationModel` or `None` 

401 The serialized model, or `None` if no name has a usable value. 

402 """ 

403 usable = {name: field for name, field in aperture_correction_map.items() if field is not None} 

404 if not usable: 

405 return None 

406 bounds = next(iter(usable.values())).bounds 

407 for field in usable.values(): 

408 if field.bounds.grid != bounds.grid: 

409 raise ValueError("Cell aperture corrections do not have a consistent grid.") 

410 if field.bounds.bbox != bounds.bbox: 

411 raise ValueError("Cell aperture corrections do not have a consistent bounding box.") 

412 if not all(field.bounds == bounds for field in usable.values()): 

413 # In rare cases some field can have more missing cells from the 

414 # others. This isn't worth a full denormalization into full 

415 # per-field bounds (especially since that's a schema change). 

416 # Instead, the shared, serialized 'bounds' only marks a cell as 

417 # missing if it's absent from all fields (as is the case when 

418 # there's no data), and we restore the per-field missing cells in 

419 # deserialized. 

420 always_missing: set[CellIJ] = set(bounds.missing) 

421 for field in usable.values(): 

422 always_missing &= field.bounds.missing 

423 bounds = CellGridBounds(grid=bounds.grid, missing=frozenset(always_missing), bbox=bounds.bbox) 

424 if any(field.unit is not None for field in usable.values()): 424 ↛ 425line 424 didn't jump to line 425 because the condition on line 424 was never true

425 raise ValueError("Aperture corrections should be dimensionless.") 

426 table = astropy.table.Table( 

427 rows=[cell_index.as_tuple() for cell_index in bounds.cell_indices()], names=["cell_i", "cell_j"] 

428 ) 

429 good_cell_mask = np.ones(bounds.subgrid_size.as_tuple(), dtype=bool) 

430 for cell_index in bounds.missing: 

431 array_index = cell_index - bounds.subgrid_start 

432 good_cell_mask[array_index.i, array_index.j] = False 

433 for name, ap_corr in aperture_correction_map.items(): 

434 column = ( 

435 ap_corr._array[good_cell_mask] 

436 if ap_corr is not None 

437 else np.full(good_cell_mask.sum(), np.nan) 

438 ) 

439 table.add_column(column, name=name, copy=False) 

440 return CellApertureCorrectionMapSerializationModel( 

441 table=archive.add_table(table, name="table"), bounds=bounds 

442 ) 

443 

444 def deserialize(self, archive: InputArchive[Any], **kwargs: Any) -> dict[str, CellField | None]: 

445 """Read an aperture-correction map from a table with one column per 

446 name. 

447 

448 A column that is entirely NaN denotes a name with no usable value in 

449 any cell, which becomes `None`. Cells that are missing for just one 

450 name (recorded as NaN) become missing cells of that field's bounds. 

451 

452 Parameters 

453 ---------- 

454 archive 

455 Archive to read the cell-value table from. 

456 **kwargs 

457 Must be empty. 

458 

459 Returns 

460 ------- 

461 aperture_corrections : `dict` [`str`, `CellField` | `None`] 

462 Aperture corrections, keyed by name. 

463 """ 

464 if kwargs: 464 ↛ 465line 464 didn't jump to line 465 because the condition on line 464 was never true

465 raise InvalidParameterError( 

466 f"Unrecognized parameters for cell aperture correction map: {set(kwargs.keys())}." 

467 ) 

468 good_cell_mask = np.zeros(self.bounds.subgrid_size.as_tuple(), dtype=bool) 

469 table = archive.get_table(self.table) 

470 for tbl_ij, cell_index in zip( 

471 table["cell_i", "cell_j"].iterrows(), self.bounds.cell_indices(), strict=True 

472 ): 

473 if cell_index.as_tuple() != tbl_ij: 473 ↛ 474line 473 didn't jump to line 474 because the condition on line 473 was never true

474 raise ArchiveReadError( 

475 "Inconsistency between serialized aperture correction bounds and table." 

476 ) 

477 array_index = cell_index - self.bounds.subgrid_start 

478 good_cell_mask[array_index.i, array_index.j] = True 

479 result: dict[str, CellField | None] = {} 

480 for name, column in table.columns.items(): 

481 if name in ("cell_i", "cell_j"): 

482 continue 

483 extra_missing_mask = np.isnan(column) 

484 if extra_missing_mask.all(): 

485 result[name] = None 

486 continue 

487 # If there are any NaN entries in this column, make a custom 

488 # CellGridBounds with additional missing cells for this field. 

489 bounds = self.bounds 

490 if extra_missing_mask.any(): 

491 extra_missing = frozenset( 

492 {CellIJ(i=i, j=j) for i, j in table["cell_i", "cell_j"][extra_missing_mask].iterrows()} 

493 ) 

494 bounds = CellGridBounds( 

495 grid=self.bounds.grid, missing=self.bounds.missing | extra_missing, bbox=self.bounds.bbox 

496 ) 

497 array = np.full(self.bounds.subgrid_size.as_tuple(), np.nan, dtype=np.float64) 

498 array[good_cell_mask] = column 

499 result[name] = CellField(bounds, array) 

500 return result