Coverage for tests/test_cell_aperture_corrections.py: 96%

104 statements  

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

11 

12from __future__ import annotations 

13 

14from collections.abc import Mapping 

15from typing import Any 

16 

17import numpy as np 

18import pytest 

19 

20from lsst.images import YX, BoundsError, Box 

21from lsst.images.cells import ( 

22 CellApertureCorrectionMapSerializationModel, 

23 CellField, 

24 CellGrid, 

25 CellGridBounds, 

26 CellIJ, 

27) 

28from lsst.images.json import JsonInputArchive, JsonOutputArchive 

29 

30try: 

31 from lsst.cell_coadds import StitchedApertureCorrection as LegacyStitchedApertureCorrection 

32 from lsst.cell_coadds import UniformGrid as LegacyUniformGrid 

33 from lsst.skymap import Index2D as LegacyIndex2D 

34 

35 HAVE_LEGACY = True 

36except ImportError: 

37 HAVE_LEGACY = False 

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

39 type LegacyUniformGrid = Any # type: ignore[no-redef] 

40 type LegacyIndex2D = Any # type: ignore[no-redef] 

41 

42skip_no_legacy = pytest.mark.skipif(not HAVE_LEGACY, reason="lsst.cell_coadds could not be imported.") 

43 

44# A 3x3 grid with 10x10-pixel cells. 

45GRID = CellGrid(bbox=Box.from_shape((30, 30)), cell_shape=YX(10, 10)) 

46BASE_BOUNDS = CellGridBounds(grid=GRID, bbox=Box.factory[0:30, 0:30]) 

47CELL_X = CellIJ(i=0, j=0) 

48CELL_Y = CellIJ(i=1, j=1) 

49 

50 

51def _make_field(missing: frozenset[CellIJ]) -> CellField: 

52 """Build a CellField over the shared 3x3 grid with ``missing`` cells set 

53 to NaN and all other cells set to 0.5. 

54 """ 

55 bounds = CellGridBounds(grid=GRID, bbox=Box.factory[0:30, 0:30], missing=missing) 

56 array = np.full((3, 3), 0.5) 

57 for cell in missing: 

58 index = cell - bounds.subgrid_start 

59 array[index.i, index.j] = np.nan 

60 return CellField(bounds, array) 

61 

62 

63def _make_legacy(gc: dict[LegacyIndex2D, float]) -> LegacyStitchedApertureCorrection: 

64 """Construct a legacy `StitchedApertureCorrection` on the shared 3x3 grid 

65 from the given per-cell values. 

66 """ 

67 ugrid = LegacyUniformGrid(cell_size=YX(10, 10).to_legacy_int_extent(), shape=LegacyIndex2D(x=3, y=3)) 

68 return LegacyStitchedApertureCorrection(ugrid, gc) 

69 

70 

71def _roundtrip( 

72 aperture_corrections: Mapping[str, CellField | None], 

73) -> tuple[CellApertureCorrectionMapSerializationModel, dict[str, CellField | None]]: 

74 """Serialize a CellField map, persist it to JSON, and read it back. 

75 

76 Returns the serialized model and the deserialized map, so tests can assert 

77 both the shared serialized bounds and the per-field result. 

78 

79 We can't use RoundtripJson for this because the in-memory type is just 

80 `dict` and hence doesn't have a ``serialize`` method. 

81 """ 

82 output_archive = JsonOutputArchive() 

83 model = CellApertureCorrectionMapSerializationModel.serialize(aperture_corrections, output_archive) 

84 output_tree = output_archive.finish(model) 

85 input_tree = CellApertureCorrectionMapSerializationModel.model_validate_json( 

86 output_tree.model_dump_json() 

87 ) 

88 input_archive = JsonInputArchive() 

89 return input_tree, input_tree.deserialize(input_archive) 

90 

91 

92@skip_no_legacy 

93def test_from_legacy_records_missing_cells() -> None: 

94 """Test that cells the legacy map has no entry for, and cells whose entry 

95 is non-finite, are both recorded as missing. 

96 """ 

97 missing = {CELL_X, CELL_Y} 

98 present = [c for c in BASE_BOUNDS.cell_indices() if c not in missing] 

99 gc = {c.to_legacy(): 0.5 + 0.1 * c.i + 0.01 * c.j for c in present} 

100 gc[CELL_Y.to_legacy()] = np.nan 

101 legacy = _make_legacy(gc) 

102 field = CellField.from_legacy_aperture_correction(legacy, BASE_BOUNDS) 

103 assert field is not None 

104 assert field.bounds.missing == missing 

105 for cell in present: 

106 np.testing.assert_allclose(field.value_in_cell(cell), gc[cell.to_legacy()]) 

107 for cell in missing: 

108 with pytest.raises(BoundsError): 

109 field.value_in_cell(cell) 

110 

111 

112@skip_no_legacy 

113def test_from_legacy_all_cells_present() -> None: 

114 """Test that when every legacy cell has an entry, bounds are unchanged.""" 

115 gc = {c.to_legacy(): 0.5 for c in BASE_BOUNDS.cell_indices()} 

116 legacy = _make_legacy(gc) 

117 field = CellField.from_legacy_aperture_correction(legacy, BASE_BOUNDS) 

118 assert field.bounds.missing == frozenset() 

119 

120 

121def test_value_in_cell_rejects_index_below_bounds() -> None: 

122 """An index below the bounds must not wrap around the NumPy array.""" 

123 field = _make_field(frozenset()) 

124 with pytest.raises(BoundsError, match="out of bounds"): 

125 field.value_in_cell(CellIJ(i=-1, j=0)) 

126 

127 

128def test_serialize_deserialize_differing_missing_cells() -> None: 

129 """Test that a map whose fields differ in missing cells round-trips, 

130 restoring each field's per-cell missing set. 

131 """ 

132 ap = {"A": _make_field(frozenset({CELL_X})), "B": _make_field(frozenset({CELL_X, CELL_Y}))} 

133 model, result = _roundtrip(ap) 

134 # Shared serialized bounds keep only cells missing from every field. 

135 assert model.bounds.missing == frozenset({CELL_X}) 

136 assert result["A"].bounds.missing == frozenset({CELL_X}) 

137 assert result["B"].bounds.missing == frozenset({CELL_X, CELL_Y}) 

138 for name, field in ap.items(): 

139 for cell in BASE_BOUNDS.cell_indices(): 

140 if cell not in field.bounds.missing: 

141 np.testing.assert_allclose(result[name].value_in_cell(cell), field.value_in_cell(cell)) 

142 else: 

143 with pytest.raises(BoundsError): 

144 result[name].value_in_cell(cell) 

145 

146 

147def test_serialize_raises_on_inconsistent_grid() -> None: 

148 """Test that fields on different grids cannot be serialized together.""" 

149 other_grid = CellGrid(bbox=Box.from_shape((40, 40)), cell_shape=YX(10, 10)) 

150 other_bounds = CellGridBounds(grid=other_grid, bbox=Box.factory[0:30, 0:30]) 

151 other_field = CellField(other_bounds, np.full((3, 3), 0.25)) 

152 with pytest.raises(ValueError, match="do not have a consistent grid"): 

153 CellApertureCorrectionMapSerializationModel.serialize( 

154 {"A": _make_field(frozenset()), "B": other_field}, JsonOutputArchive() 

155 ) 

156 

157 

158def test_serialize_raises_on_inconsistent_bbox() -> None: 

159 """Test that fields covering different parts of one grid are rejected.""" 

160 other_bounds = CellGridBounds(grid=GRID, bbox=Box.factory[0:20, 10:30]) 

161 other_field = CellField(other_bounds, np.full((2, 2), 0.25)) 

162 with pytest.raises(ValueError, match="do not have a consistent bounding box"): 

163 CellApertureCorrectionMapSerializationModel.serialize( 

164 {"A": _make_field(frozenset()), "B": other_field}, JsonOutputArchive() 

165 ) 

166 

167 

168def test_deserialize_nan_column_becomes_missing() -> None: 

169 """Test that a NaN in one field column makes that cell missing for that 

170 field. 

171 """ 

172 ap = {"A": _make_field(frozenset()), "B": _make_field(frozenset({CELL_Y}))} 

173 _, result = _roundtrip(ap) 

174 assert result["A"].bounds.missing == frozenset() 

175 assert result["B"].bounds.missing == frozenset({CELL_Y}) 

176 np.testing.assert_allclose(result["A"].value_in_cell(CELL_Y), ap["A"].value_in_cell(CELL_Y)) 

177 with pytest.raises(BoundsError): 

178 result["B"].value_in_cell(CELL_Y) 

179 

180 

181@skip_no_legacy 

182def test_from_legacy_returns_none_without_usable_values() -> None: 

183 """A name with no usable value in any cell converts to `None` instead of a 

184 field with no cells. 

185 """ 

186 all_nan = {c.to_legacy(): np.nan for c in BASE_BOUNDS.cell_indices()} 

187 assert CellField.from_legacy_aperture_correction(_make_legacy(all_nan), BASE_BOUNDS) is None 

188 # Cells the legacy container has no entry for are unusable in the same way. 

189 assert CellField.from_legacy_aperture_correction(_make_legacy({}), BASE_BOUNDS) is None 

190 

191 

192def test_serialize_without_any_usable_name_is_none() -> None: 

193 """A map with no usable name — empty, or with only `None`-valued names — 

194 records no aperture corrections at all, since there is nothing left to 

195 define the shared bounds. 

196 """ 

197 assert CellApertureCorrectionMapSerializationModel.serialize({}, JsonOutputArchive()) is None 

198 assert CellApertureCorrectionMapSerializationModel.serialize({"A": None}, JsonOutputArchive()) is None