Coverage for tests/test_cell_coadd.py: 79%

398 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 

14import copy 

15import dataclasses 

16import json 

17import os 

18import pickle 

19from pathlib import Path 

20from typing import Any 

21 

22import numpy as np 

23import pytest 

24 

25from lsst.images import YX, BoundsError, Box, Interval, MaskPlane, get_legacy_deep_coadd_mask_planes 

26from lsst.images.cells import ( 

27 CellCoadd, 

28 CellField, 

29 CellGrid, 

30 CellGridBounds, 

31 CellIJ, 

32 CellPointSpreadFunctionSerializationModel, 

33 CoaddProvenance, 

34 PatchDefinition, 

35) 

36from lsst.images.describe import DescribeOptions, Report 

37from lsst.images.fields import ChebyshevField 

38from lsst.images.fits import FitsCompressionOptions 

39from lsst.images.serialization import ( 

40 JsonRef, 

41 class_for_schema, 

42 parameterize_tree, 

43 read_archive, 

44) 

45from lsst.images.tests import ( 

46 DP2_COADD_DATA_ID, 

47 DP2_COADD_MISSING_CELL, 

48 RoundtripFits, 

49 RoundtripJson, 

50 RoundtripNdf, 

51 assert_cell_coadds_equal, 

52 assert_images_equal, 

53 assert_masked_images_equal, 

54 assert_psfs_equal, 

55 check_bounds_contains_broadcasting, 

56 compare_cell_coadd_to_legacy, 

57 compare_masked_image_to_legacy, 

58 compare_psf_to_legacy, 

59 compare_sky_projection_to_legacy_wcs, 

60 current_fixture_path, 

61 reset_afw_mask_planes, # noqa: F401 

62) 

63 

64try: 

65 import h5py # noqa: F401 

66 

67 HAVE_H5PY = True 

68except ImportError: 

69 HAVE_H5PY = False 

70 

71try: 

72 import lsst.afw.image # noqa: F401 

73 from lsst.cell_coadds import MultipleCellCoadd as LegacyMultipleCellCoadd 

74 

75 HAVE_LEGACY = True 

76except ImportError: 

77 HAVE_LEGACY = False 

78 type LegacyMultipleCellCoadd = Any # type: ignore[no-redef] 

79 

80EXTERNAL_DATA_DIR = os.environ.get("TESTDATA_IMAGES_DIR", None) 

81FIXTURE_DIR = Path(__file__).parent / "data" / "schemas" 

82 

83skip_no_h5py = pytest.mark.skipif(not HAVE_H5PY, reason="h5py is not installed") 

84skip_no_legacy = pytest.mark.skipif(not HAVE_LEGACY, reason="lsst.afw (etc) could not be imported.") 

85 

86 

87@dataclasses.dataclass 

88class _LegacyTestData: 

89 """A struct holding test data loaded from EXTERNAL_DATA_DIR.""" 

90 

91 filename: str 

92 tract_bbox: Box 

93 legacy_cell_coadd: LegacyMultipleCellCoadd 

94 cell_coadd: CellCoadd 

95 plane_map: dict[str, MaskPlane] = dataclasses.field(default_factory=get_legacy_deep_coadd_mask_planes) 

96 

97 def make_psf_points(self, bbox: Box | None = None) -> YX[np.ndarray]: 

98 """Create random PSF sample points within the given bbox.""" 

99 if bbox is None: 

100 bbox = self.cell_coadd.bbox 

101 rng = np.random.default_rng(44) 

102 xc, yc = np.meshgrid( 

103 np.arange( 

104 bbox.x.start + self.cell_coadd.grid.cell_shape.x * 0.5, 

105 bbox.x.stop, 

106 self.cell_coadd.grid.cell_shape.x, 

107 ), 

108 np.arange( 

109 bbox.y.start + self.cell_coadd.grid.cell_shape.y * 0.5, 

110 bbox.y.stop, 

111 self.cell_coadd.grid.cell_shape.y, 

112 ), 

113 ) 

114 return YX( 

115 y=yc.ravel() + rng.uniform(-0.4, 0.4, size=yc.size), 

116 x=xc.ravel() + rng.uniform(-0.4, 0.4, size=xc.size), 

117 ) 

118 

119 

120@pytest.fixture 

121def legacy_test_data(reset_afw_mask_planes: None) -> _LegacyTestData: # noqa: F811 

122 """Return a struct of CellCoadd loaded from legacy test data. 

123 

124 Skips if ``TESTDATA_IMAGES_DIR`` is not set or if ``lsst.cell_coadds`` 

125 cannot be imported. 

126 """ 

127 if EXTERNAL_DATA_DIR is None: 127 ↛ 129line 127 didn't jump to line 129 because the condition on line 127 was always true

128 pytest.skip("TESTDATA_IMAGES_DIR is not in the environment.") 

129 try: 

130 from lsst.cell_coadds import MultipleCellCoadd 

131 except ImportError: 

132 pytest.skip("lsst.cell_coadds could not be imported.") 

133 filename = os.path.join(EXTERNAL_DATA_DIR, "dp2", "legacy", "deep_coadd_cell_predetection.fits") 

134 plane_map = get_legacy_deep_coadd_mask_planes() 

135 legacy_cell_coadd = MultipleCellCoadd.read_fits(filename) 

136 with open(os.path.join(EXTERNAL_DATA_DIR, "dp2", "legacy", "skyMap.pickle"), "rb") as stream: 

137 skymap = pickle.load(stream) 

138 cell_coadd = CellCoadd.from_legacy_cell_coadd( 

139 legacy_cell_coadd, 

140 plane_map=plane_map, 

141 tract_info=skymap[DP2_COADD_DATA_ID["tract"]], 

142 ) 

143 return _LegacyTestData( 

144 filename=filename, 

145 tract_bbox=Box.from_legacy(skymap[DP2_COADD_DATA_ID["tract"]].getBBox()), 

146 legacy_cell_coadd=legacy_cell_coadd, 

147 cell_coadd=cell_coadd, 

148 ) 

149 

150 

151@pytest.fixture 

152def minified_cell_coadd() -> CellCoadd: 

153 """Return a tiny CellCoadd from JSON data stored in this package.""" 

154 path = current_fixture_path(FIXTURE_DIR, "cell_coadd", variant="dp2") 

155 return read_archive(path, CellCoadd) 

156 

157 

158def make_subbox(full_bbox: Box) -> Box: 

159 """Make a box that's useful for nontrivial subimage tests. 

160 

161 This box only overlaps (but does not fully cover) the middle 2 (of 4) 

162 cells in y, while covering exactly the last column of cells in x. It does 

163 not cover the missing cell. 

164 """ 

165 return Box.factory[ 

166 full_bbox.y.start + 252 : full_bbox.y.stop - 175, 

167 full_bbox.x.stop - 150 : full_bbox.x.stop, 

168 ] 

169 

170 

171def test_cell_coadd_repr_str_pinned(minified_cell_coadd: CellCoadd) -> None: 

172 """Pin the exact str and repr output of a CellCoadd. 

173 

174 A coadd takes component types no string can express, so repr is the 

175 descriptive form rather than a constructor call. Both come from the 

176 report, as they do for the sibling `VisitImage`. 

177 """ 

178 assert str(minified_cell_coadd) == "CellCoadd([y=48:60, x=36:48], tract=9813)" 

179 assert repr(minified_cell_coadd) == "<CellCoadd([y=48:60, x=36:48], tract=9813)>" 

180 

181 

182def report_fields(report: Report) -> dict[str, Any]: 

183 """Return a mapping from report field label to field value.""" 

184 return {field.label: field.value for field in report.fields} 

185 

186 

187def make_test_provenance() -> CoaddProvenance: 

188 """Return a provenance with three input images taken over two nights, 

189 whose contributions cover three cells unevenly. 

190 """ 

191 inputs = CoaddProvenance.make_empty_input_table(3) 

192 inputs["instrument"] = "LSSTCam" 

193 inputs["physical_filter"] = "r_57" 

194 inputs["visit"] = [101, 102, 103] 

195 inputs["detector"] = [1, 2, 3] 

196 inputs["day_obs"] = [20250520, 20250520, 20250521] 

197 contributions = CoaddProvenance.make_empty_contribution_table(6) 

198 contributions["cell_i"] = [0, 0, 0, 1, 1, 2] 

199 contributions["cell_j"] = 0 

200 return CoaddProvenance(inputs=inputs, contributions=contributions) 

201 

202 

203def test_coadd_provenance_repr_str_pinned(minified_cell_coadd: CellCoadd) -> None: 

204 """Pin the str and repr of a CoaddProvenance. 

205 

206 Neither table can be expressed in an eval-able string, so repr is the 

207 descriptive form, and both report only what len() can answer. 

208 """ 

209 provenance = minified_cell_coadd.provenance 

210 assert str(provenance) == "CoaddProvenance(6 input images)" 

211 assert repr(provenance) == "<CoaddProvenance(6 input images)>" 

212 

213 

214def test_coadd_provenance_brief_report_skips_column_scans(minified_cell_coadd: CellCoadd) -> None: 

215 """The brief report carries no fields, so repr and str never scan a 

216 column of either table. 

217 """ 

218 report = minified_cell_coadd.provenance._describe(DescribeOptions(brief=True)) 

219 assert not report.fields 

220 assert report.to_repr() == "<CoaddProvenance(6 input images)>" 

221 

222 

223def test_coadd_provenance_report_summarizes_its_tables(minified_cell_coadd: CellCoadd) -> None: 

224 """The expanded report summarizes both tables instead of rendering them.""" 

225 report = minified_cell_coadd.provenance.describe() 

226 assert report.type_name == "CoaddProvenance" 

227 assert report_fields(report) == { 

228 "instrument": "LSSTCam", 

229 "physical_filter": "r_57", 

230 "input images": "6 from 6 visits", 

231 "day_obs": "20250520", 

232 "cells": "3 with contributions", 

233 "per cell": "6 input images", 

234 } 

235 assert list(report_fields(report)) == [ 

236 "instrument", 

237 "physical_filter", 

238 "input images", 

239 "day_obs", 

240 "cells", 

241 "per cell", 

242 ] 

243 # Rich renders an astropy table as plain text and never consults its 

244 # _repr_html_, so the report tabulates nothing. 

245 assert not report.tables 

246 assert "input images" in report._repr_html_() 

247 

248 

249def test_coadd_provenance_report_counts_cells_against_bounds(minified_cell_coadd: CellCoadd) -> None: 

250 """Given the image's cells, the report states coverage as a fraction.""" 

251 report = minified_cell_coadd.provenance._describe(bounds=minified_cell_coadd.bounds) 

252 assert report_fields(report)["cells"] == "3 of 3 with contributions" 

253 

254 

255def test_coadd_provenance_report_shows_partial_cell_coverage() -> None: 

256 """Cells with image data but no contribution rows show up in the ratio.""" 

257 grid = CellGrid(bbox=Box.from_shape((30, 30)), cell_shape=YX(10, 10)) 

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

259 report = make_test_provenance()._describe(bounds=bounds) 

260 assert report_fields(report)["cells"] == "3 of 9 with contributions" 

261 

262 

263def test_coadd_provenance_report_ranges_over_nights_and_cells() -> None: 

264 """Several visits, several nights and uneven cell coverage give the 

265 ranged forms of each field. 

266 """ 

267 fields = report_fields(make_test_provenance().describe()) 

268 assert fields["input images"] == "3 from 3 visits" 

269 assert fields["day_obs"] == "20250520 - 20250521" 

270 assert fields["cells"] == "3 with contributions" 

271 assert fields["per cell"] == "1 - 3 input images (median 2)" 

272 

273 

274def test_empty_coadd_provenance_cannot_be_constructed() -> None: 

275 """Provenance is only meaningful when it records an input image.""" 

276 with pytest.raises(ValueError, match="at least one input"): 

277 CoaddProvenance( 

278 inputs=CoaddProvenance.make_empty_input_table(0), 

279 contributions=CoaddProvenance.make_empty_contribution_table(0), 

280 ) 

281 

282 

283def test_coadd_provenance_subset_without_contributions_is_none() -> None: 

284 """Subsetting to cells that no image contributed to yields no provenance 

285 rather than an empty one. 

286 """ 

287 inputs = CoaddProvenance.make_empty_input_table(1) 

288 inputs["instrument"] = "LSSTCam" 

289 inputs["physical_filter"] = "r_57" 

290 inputs["visit"] = [101] 

291 inputs["detector"] = [1] 

292 inputs["day_obs"] = [20250520] 

293 contributions = CoaddProvenance.make_empty_contribution_table(1) 

294 contributions["cell_i"] = [0] 

295 contributions["cell_j"] = [0] 

296 contributions["instrument"] = "LSSTCam" 

297 contributions["visit"] = [101] 

298 contributions["detector"] = [1] 

299 provenance = CoaddProvenance(inputs=inputs, contributions=contributions) 

300 

301 populated = provenance[CellIJ(0, 0)] 

302 assert populated is not None 

303 assert len(populated.inputs) == 1 

304 assert len(populated.contributions) == 1 

305 

306 assert provenance[CellIJ(1, 1)] is None 

307 

308 

309def test_coadd_provenance_subset_inputs_are_unique() -> None: 

310 """Test that CoaddProvenance.subset doesn't generate duplicates from the 

311 same observation appearing in multiple cells. 

312 """ 

313 inputs = CoaddProvenance.make_empty_input_table(2) 

314 inputs["instrument"] = "LSSTCam" 

315 inputs["physical_filter"] = "r_57" 

316 inputs["visit"] = [101, 102] 

317 inputs["detector"] = [1, 2] 

318 inputs["day_obs"] = [20250520, 20250520] 

319 contributions = CoaddProvenance.make_empty_contribution_table(4) 

320 contributions["instrument"] = "LSSTCam" 

321 # Each observation contributes to both cells. 

322 contributions["visit"] = [101, 102, 101, 102] 

323 contributions["detector"] = [1, 2, 1, 2] 

324 contributions["cell_i"] = 0 

325 contributions["cell_j"] = [0, 0, 1, 1] 

326 provenance = CoaddProvenance(inputs=inputs, contributions=contributions) 

327 

328 subset = provenance.subset([CellIJ(0, 0), CellIJ(0, 1)]) 

329 

330 assert len(subset.contributions) == 4 

331 assert len(subset.inputs) == 2 

332 assert set(zip(subset.inputs["visit"], subset.inputs["detector"])) == {(101, 1), (102, 2)} 

333 

334 

335def test_coadd_provenance_report_counts_one_input_image_in_the_singular() -> None: 

336 """Pin the singular forms of the counted phrases. 

337 

338 One input image is what the standalone ``coadd_provenance`` file holds, 

339 and what a single-cell subset of a coadd holds, so this is the case the 

340 ``describe`` command line subcommand shows most often. 

341 """ 

342 inputs = CoaddProvenance.make_empty_input_table(1) 

343 inputs["instrument"] = "LSSTCam" 

344 inputs["physical_filter"] = "r_57" 

345 inputs["visit"] = [101] 

346 inputs["detector"] = [1] 

347 inputs["day_obs"] = [20250520] 

348 provenance = CoaddProvenance( 

349 inputs=inputs, contributions=CoaddProvenance.make_empty_contribution_table(1) 

350 ) 

351 assert str(provenance) == "CoaddProvenance(1 input image)" 

352 assert repr(provenance) == "<CoaddProvenance(1 input image)>" 

353 fields = report_fields(provenance.describe()) 

354 assert fields["input images"] == "1 from 1 visit" 

355 assert fields["per cell"] == "1 input image" 

356 

357 

358def test_cell_coadd_report_accounts_for_every_component(minified_cell_coadd: CellCoadd) -> None: 

359 """Nothing the coadd carries is absent from its report.""" 

360 report = minified_cell_coadd.describe() 

361 fields = report_fields(report) 

362 assert fields["mask_fractions"] == "rejected" 

363 assert fields["noise_realizations"] == "1 image (dtype float32)" 

364 assert fields["aperture_corrections"] == "3 fields" 

365 # Provenance is a child, so it needs no field line of its own. 

366 assert "provenance" not in fields 

367 assert list(report.children) == [ 

368 "image", 

369 "mask", 

370 "variance", 

371 "sky_projection", 

372 "psf", 

373 "provenance", 

374 "backgrounds", 

375 ] 

376 provenance = report.children["provenance"] 

377 assert provenance.type_name == "CoaddProvenance" 

378 # The coadd passed its cells down, so coverage is stated as a fraction. 

379 assert report_fields(provenance)["cells"] == "3 of 3 with contributions" 

380 

381 

382def test_cell_coadd_report_counts_aperture_corrections_only(minified_cell_coadd: CellCoadd) -> None: 

383 """A coadd can carry dozens of aperture corrections with long names, so 

384 the report counts them and never names them, detail or not. 

385 """ 

386 plain = report_fields(minified_cell_coadd.describe())["aperture_corrections"] 

387 assert plain == "3 fields" 

388 detailed = report_fields(minified_cell_coadd.describe(detail=True))["aperture_corrections"] 

389 assert detailed == "3 fields" # No additional detail 

390 

391 

392def test_cell_coadd_report_states_absent_provenance(minified_cell_coadd: CellCoadd) -> None: 

393 """A coadd with no provenance says so, while components that are merely 

394 empty stay out of the report. 

395 """ 

396 bare = CellCoadd( 

397 minified_cell_coadd.image, 

398 mask=minified_cell_coadd.mask, 

399 variance=minified_cell_coadd.variance, 

400 sky_projection=minified_cell_coadd.sky_projection, 

401 band=minified_cell_coadd.band, 

402 psf=minified_cell_coadd.psf, 

403 patch=minified_cell_coadd.patch, 

404 ) 

405 report = bare.describe() 

406 fields = report_fields(report) 

407 assert fields["provenance"] == "none" 

408 assert "provenance" not in report.children 

409 assert "mask_fractions" not in fields 

410 assert "noise_realizations" not in fields 

411 assert "aperture_corrections" not in fields 

412 

413 

414def test_cell_coadd_copy_preserves_absent_optional_state(minified_cell_coadd: CellCoadd) -> None: 

415 """Copying must support coadds without patch or provenance records.""" 

416 minified_cell_coadd._patch = None 

417 minified_cell_coadd._provenance = None 

418 

419 copied = minified_cell_coadd.copy() 

420 

421 assert copied._patch is None 

422 assert copied._provenance is None 

423 assert_masked_images_equal(copied, minified_cell_coadd) 

424 with pytest.raises(AttributeError, match="no patch"): 

425 copied.patch 

426 with pytest.raises(AttributeError, match="no provenance"): 

427 copied.provenance 

428 

429 

430def test_cell_grid_patch_str_uses_clean_geometry() -> None: 

431 """CellGrid, PatchDefinition and CellGridBounds str drop the 

432 Interval/YX/Box/CellIJ wrappers. 

433 

434 The report renders field values with str, so these must use the compact 

435 geometry forms rather than pydantic's default field-by-field repr. 

436 """ 

437 grid = CellGrid(bbox=Box.from_shape((100, 200)), cell_shape=YX(10, 20)) 

438 assert str(grid) == "[y=0:100, x=0:200], cell_shape=(y=10, x=20)" 

439 

440 patch = PatchDefinition(id=73, index=YX(7, 3), inner_bbox=Box.factory[1:3, 2:4], cells=grid) 

441 assert str(patch) == ( 

442 "id=73, index=(y=7, x=3), inner_bbox=[y=1:3, x=2:4], " 

443 "cells=([y=0:100, x=0:200], cell_shape=(y=10, x=20))" 

444 ) 

445 # repr stays as the pydantic default so it remains eval-ish and distinct. 

446 assert "Interval(" in repr(patch) 

447 assert "YX(" in repr(patch) 

448 

449 bounds = CellGridBounds(grid=grid, bbox=Box.factory[0:40, 0:60]) 

450 assert str(bounds) == "[y=0:40, x=0:60] in grid ([y=0:100, x=0:200], cell_shape=(y=10, x=20))" 

451 bounds_missing = CellGridBounds( 

452 grid=grid, bbox=Box.factory[0:40, 0:60], missing=frozenset({CellIJ(i=1, j=1), CellIJ(i=0, j=2)}) 

453 ) 

454 assert str(bounds_missing) == ( 

455 "[y=0:40, x=0:60] in grid ([y=0:100, x=0:200], cell_shape=(y=10, x=20)), " 

456 "missing={(i=0, j=2), (i=1, j=1)}" 

457 ) 

458 assert "Interval(" in repr(bounds_missing) 

459 

460 

461def test_cell_shape_accepts_both_spellings() -> None: 

462 """Verify both on-disk spellings of an XY pair still validate. 

463 

464 Shipped cell_coadd 1.0.0 files carry the array spelling, so this stays 

465 readable until a major bump retires the as_shipped fixture. A focused 

466 check here gives a two-line failure instead of a 52 KB fixture failing 

467 to read. 

468 """ 

469 tree_cls = class_for_schema("cell_psf") 

470 assert tree_cls is not None 

471 model = parameterize_tree(tree_cls, JsonRef) 

472 fixture = json.loads(current_fixture_path(FIXTURE_DIR, "cell_psf").read_text()) 

473 assert fixture["bounds"]["grid"]["cell_shape"] == {"y": 4, "x": 4} 

474 

475 legacy = copy.deepcopy(fixture) 

476 legacy["bounds"]["grid"]["cell_shape"] = [4, 4] 

477 tree = model.model_validate(legacy) 

478 assert isinstance(tree, CellPointSpreadFunctionSerializationModel) 

479 assert tree.bounds.grid.cell_shape.y == 4 

480 assert tree.bounds.grid.cell_shape.x == 4 

481 

482 

483def test_cell_psf_rejects_index_below_bounds(minified_cell_coadd: CellCoadd) -> None: 

484 """An index below the PSF bounds must not wrap around its array.""" 

485 start = minified_cell_coadd.psf.bounds.subgrid_start 

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

487 minified_cell_coadd.psf[CellIJ(i=start.i - 1, j=start.j)] 

488 

489 

490def test_from_legacy(legacy_test_data: _LegacyTestData) -> None: 

491 """Test constructing a CellCoadd by converting a legacy 

492 ``MultipleCellCoadd``. 

493 """ 

494 assert legacy_test_data.cell_coadd.bounds.missing == {CellIJ(**DP2_COADD_MISSING_CELL)} 

495 assert legacy_test_data.cell_coadd.bbox == Box.factory[12900:13500, 9600:10050] 

496 compare_cell_coadd_to_legacy( 

497 legacy_test_data.cell_coadd, 

498 legacy_test_data.legacy_cell_coadd, 

499 tract_bbox=legacy_test_data.tract_bbox, 

500 plane_map=legacy_test_data.plane_map, 

501 psf_points=legacy_test_data.make_psf_points(), 

502 ) 

503 

504 

505def test_roundtrip(legacy_test_data: _LegacyTestData) -> None: 

506 """Test that a CellCoadd roundtrips through FITS.""" 

507 with RoundtripFits(legacy_test_data.cell_coadd, "CellCoadd") as roundtrip: 

508 # Check a subimage read (no component arg — does not trigger a skip). 

509 subbox = Box.factory[ 

510 legacy_test_data.cell_coadd.bbox.y.start + 252 : legacy_test_data.cell_coadd.bbox.y.stop - 175, 

511 legacy_test_data.cell_coadd.bbox.x.stop - 150 : legacy_test_data.cell_coadd.bbox.x.stop, 

512 ] 

513 subimage = roundtrip.get(bbox=subbox) 

514 assert_masked_images_equal(subimage, legacy_test_data.cell_coadd[subbox], expect_view=False) 

515 with roundtrip.inspect() as fits: 

516 for extname in ["IMAGE", "MASK", "VARIANCE", "MASK_FRACTIONS/REJECTED"] + [ 

517 f"NOISE_REALIZATIONS/{n}" for n in range(len(legacy_test_data.cell_coadd.noise_realizations)) 

518 ]: 

519 assert fits[extname].header["ZTILE1"] == legacy_test_data.cell_coadd.grid.cell_shape.x 

520 assert fits[extname].header["ZTILE2"] == legacy_test_data.cell_coadd.grid.cell_shape.y 

521 # Fixture self-consistency: bbox and missing-cell set are as expected. 

522 assert legacy_test_data.cell_coadd.bounds.missing == {CellIJ(**DP2_COADD_MISSING_CELL)} 

523 assert legacy_test_data.cell_coadd.bbox == Box.factory[12900:13500, 9600:10050] 

524 # Full round-trip fidelity. 

525 assert_cell_coadds_equal(roundtrip.result, legacy_test_data.cell_coadd, expect_view=False) 

526 compare_cell_coadd_to_legacy( 

527 roundtrip.result, 

528 legacy_test_data.legacy_cell_coadd, 

529 tract_bbox=legacy_test_data.tract_bbox, 

530 plane_map=legacy_test_data.plane_map, 

531 psf_points=legacy_test_data.make_psf_points(), 

532 ) 

533 

534 

535def test_roundtrip_components(legacy_test_data: _LegacyTestData) -> None: 

536 """Test component and subimage reads. 

537 

538 This test will be skipped if `lsst.daf.butler` is not available instead of 

539 falling back to non-butler I/O, which is why we don't want to merge it 

540 with `test_roundtrip`. 

541 """ 

542 with RoundtripFits(legacy_test_data.cell_coadd, "CellCoadd") as roundtrip: 

543 subbox = make_subbox(legacy_test_data.cell_coadd.bbox) 

544 subpsf = roundtrip.get("psf", bbox=subbox) 

545 assert subpsf.bounds.bbox == Box( 

546 y=Interval.factory[ 

547 legacy_test_data.cell_coadd.bbox.y.start + 150 : legacy_test_data.cell_coadd.bbox.y.stop - 150 

548 ], 

549 x=subbox.x, 

550 ) 

551 assert_psfs_equal( 

552 subpsf, 

553 legacy_test_data.cell_coadd.psf, 

554 points=legacy_test_data.make_psf_points(subbox), 

555 ) 

556 assert roundtrip.get("bbox") == legacy_test_data.cell_coadd.bbox 

557 alternates = { 

558 k: roundtrip.get(k) 

559 for k in [ 

560 "sky_projection", 

561 "image", 

562 "mask", 

563 "variance", 

564 "masked_image", 

565 "psf", 

566 "aperture_corrections", 

567 "provenance", 

568 "backgrounds", 

569 "bbox", 

570 "unit", 

571 ] 

572 } 

573 # Read all the components at once. 

574 all_components = roundtrip.get("components") 

575 assert set(all_components) == set(alternates) - {"masked_image"} 

576 assert all_components["bbox"] == alternates["bbox"] 

577 assert all_components["unit"] == legacy_test_data.cell_coadd.unit 

578 assert_psfs_equal(all_components["psf"], alternates["psf"]) 

579 assert_images_equal(all_components["image"], alternates["image"]) 

580 

581 backgrounds = roundtrip.get("backgrounds") 

582 assert backgrounds.keys() == set() 

583 assert backgrounds.subtracted is None 

584 

585 compare_cell_coadd_to_legacy( 

586 roundtrip.result, 

587 legacy_test_data.legacy_cell_coadd, 

588 tract_bbox=legacy_test_data.tract_bbox, 

589 plane_map=legacy_test_data.plane_map, 

590 alternates=alternates, 

591 psf_points=legacy_test_data.make_psf_points(), 

592 ) 

593 

594 

595def test_fits_compression(legacy_test_data: _LegacyTestData) -> None: 

596 """Test lossy FITS compression produces the expected headers.""" 

597 with RoundtripFits( 

598 legacy_test_data.cell_coadd, 

599 storage_class="CellCoadd", 

600 recipe="lossy16", 

601 compression_options={ 

602 "image": FitsCompressionOptions.LOSSY, 

603 "variance": FitsCompressionOptions.LOSSY, 

604 }, 

605 ) as roundtrip: 

606 with roundtrip.inspect() as fits: 

607 for extname in ["IMAGE", "MASK", "VARIANCE", "MASK_FRACTIONS/REJECTED"] + [ 

608 f"NOISE_REALIZATIONS/{n}" for n in range(len(legacy_test_data.cell_coadd.noise_realizations)) 

609 ]: 

610 assert fits[extname].header["ZTILE1"] == legacy_test_data.cell_coadd.grid.cell_shape.x 

611 assert fits[extname].header["ZTILE2"] == legacy_test_data.cell_coadd.grid.cell_shape.y 

612 if extname == "MASK" or extname.startswith("MASK_FRACTIONS"): 

613 assert fits[extname].header["ZCMPTYPE"] == "GZIP_2" 

614 else: 

615 assert fits[extname].header["ZCMPTYPE"] == "RICE_1" 

616 assert fits[extname].header["ZQUANTIZ"] == "SUBTRACTIVE_DITHER_2" 

617 

618 

619def test_json_roundtrip(legacy_test_data: _LegacyTestData) -> None: 

620 """Verify a CellCoadd round-trips correctly through the JSON archive.""" 

621 with RoundtripJson(legacy_test_data.cell_coadd) as roundtrip: 

622 pass 

623 assert_cell_coadds_equal(roundtrip.result, legacy_test_data.cell_coadd, expect_view=False) 

624 

625 

626def test_to_legacy_cell_coadd(legacy_test_data: _LegacyTestData) -> None: 

627 """Verify converting a CellCoadd back into a legacy MultipleCellCoadd.""" 

628 legacy_cell_coadd = legacy_test_data.cell_coadd.to_legacy_cell_coadd() 

629 compare_cell_coadd_to_legacy( 

630 legacy_test_data.cell_coadd, 

631 legacy_cell_coadd, 

632 tract_bbox=legacy_test_data.tract_bbox, 

633 plane_map=legacy_test_data.plane_map, 

634 psf_points=legacy_test_data.make_psf_points(), 

635 ) 

636 with pytest.raises(ValueError, match="MultipleCellCoadd requires"): 

637 legacy_test_data.cell_coadd[make_subbox(legacy_test_data.cell_coadd.bbox)].to_legacy_cell_coadd() 

638 

639 

640def make_coadd_missing_last_column(coadd: CellCoadd) -> CellCoadd: 

641 """Return a copy of a coadd whose last column of cells is missing.""" 

642 last_column = max(cell.j for cell in coadd.bounds.cell_indices()) 

643 survivors = [cell for cell in coadd.bounds.cell_indices() if cell.j < last_column] 

644 cell_boxes = [coadd.grid.bbox_of(cell) for cell in survivors] 

645 result_bbox = Box( 

646 Interval(min(b.y.start for b in cell_boxes), max(b.y.stop for b in cell_boxes)), 

647 Interval(min(b.x.start for b in cell_boxes), max(b.x.stop for b in cell_boxes)), 

648 ) 

649 result_bounds = CellGridBounds( 

650 grid=coadd.grid, bbox=result_bbox, missing=coadd.bounds[result_bbox].missing 

651 ) 

652 tmp = coadd.copy() 

653 holes = Box(coadd.bbox.y, Interval(coadd.bbox.x.stop - coadd.grid.cell_shape.x, coadd.bbox.x.stop)) 

654 where = holes.slice_within(coadd.bbox) 

655 tmp.image.array[where.y, where.x] = 0.0 

656 tmp.variance.array[where.y, where.x] = np.inf 

657 column = np.zeros(tmp.mask.array.shape[:2], dtype=bool) 

658 column[where.y, where.x] = True 

659 tmp.mask.clear(None, column) 

660 tmp.mask.set("NO_DATA", column) 

661 for fraction in tmp.mask_fractions.values(): 

662 fraction.array[where.y, where.x] = 0.0 

663 for noise in tmp.noise_realizations: 

664 noise.array[where.y, where.x] = 0.0 

665 

666 def adjust_ap_corr(field: CellField | None) -> CellField | None: 

667 if field is None: 

668 return None 

669 bounds: CellGridBounds = result_bounds.intersection(field.bounds) 

670 array = np.full(bounds.subgrid_size.as_tuple(), np.nan, dtype=float) 

671 for cell_index in bounds.cell_indices(): 

672 array[cell_index.within_subgrid_array(bounds)] = field.value_in_cell(cell_index) 

673 return CellField(bounds, array, unit=field.unit) 

674 

675 result = CellCoadd( 

676 tmp.image, 

677 mask=tmp.mask, 

678 variance=tmp.variance, 

679 mask_fractions=tmp.mask_fractions, 

680 noise_realizations=tmp.noise_realizations, 

681 band=tmp.band, 

682 psf=coadd.psf[result_bbox], 

683 aperture_corrections={ 

684 name: adjust_ap_corr(field) for name, field in coadd.aperture_corrections.items() 

685 }, 

686 patch=tmp.patch, 

687 provenance=coadd.provenance.subset(survivors), 

688 backgrounds=tmp.backgrounds, 

689 ) 

690 assert result_bounds == result.bounds 

691 return result 

692 

693 

694@skip_no_legacy 

695def test_to_legacy_cell_coadd_missing_last_column(minified_cell_coadd: CellCoadd) -> None: 

696 """Verify converting a coadd whose cells stop short of its bounding box. 

697 

698 Legacy ``MultipleCellCoadd`` accepts an ``inner_bbox`` that spans cells it 

699 does not have, so a bounding box that is aligned with the cell grid while 

700 its outermost cells are missing is convertible. 

701 """ 

702 coadd = make_coadd_missing_last_column(minified_cell_coadd) 

703 assert coadd.bbox != coadd.bounds.bbox 

704 legacy_cell_coadd = coadd.to_legacy_cell_coadd() 

705 assert Box.from_legacy(legacy_cell_coadd.inner_bbox) == coadd.bbox 

706 assert set(legacy_cell_coadd.cells.keys()) == {cell.to_legacy() for cell in coadd.bounds.cell_indices()} 

707 compare_cell_coadd_to_legacy( 

708 coadd, 

709 legacy_cell_coadd, 

710 tract_bbox=coadd.sky_projection.pixel_frame.bbox, 

711 ) 

712 

713 

714@skip_no_legacy 

715def test_to_legacy(legacy_test_data: _LegacyTestData) -> None: 

716 """Test converting a CellCoadd back into a legacy Exposure.""" 

717 legacy_exposure = legacy_test_data.cell_coadd.to_legacy() 

718 assert legacy_exposure.getFilter().bandLabel == legacy_test_data.cell_coadd.band 

719 assert Box.from_legacy(legacy_exposure.getBBox()) == legacy_test_data.cell_coadd.bbox 

720 compare_masked_image_to_legacy( 

721 legacy_test_data.cell_coadd, 

722 legacy_exposure.maskedImage, 

723 plane_map=legacy_test_data.plane_map, 

724 expect_view=True, 

725 ) 

726 compare_psf_to_legacy( 

727 legacy_test_data.cell_coadd.psf, 

728 legacy_exposure.getPsf(), 

729 points=legacy_test_data.make_psf_points(), 

730 expect_legacy_raise_on_out_of_bounds=True, 

731 ) 

732 compare_sky_projection_to_legacy_wcs( 

733 legacy_test_data.cell_coadd.sky_projection, 

734 legacy_exposure.getWcs(), 

735 legacy_test_data.cell_coadd.sky_projection.pixel_frame, 

736 subimage_bbox=legacy_test_data.cell_coadd.bbox, 

737 is_fits=True, 

738 ) 

739 subbox = make_subbox(legacy_test_data.cell_coadd.bbox) 

740 compare_masked_image_to_legacy( 

741 legacy_test_data.cell_coadd[subbox], 

742 legacy_test_data.cell_coadd[subbox].to_legacy().maskedImage, 

743 plane_map=legacy_test_data.plane_map, 

744 expect_view=True, 

745 ) 

746 

747 

748@skip_no_h5py 

749def test_ndf_roundtrip(legacy_test_data: _LegacyTestData) -> None: 

750 """Test that CellCoadd round-trips through NDF.""" 

751 with RoundtripNdf(legacy_test_data.cell_coadd, "CellCoadd") as roundtrip: 

752 assert_cell_coadds_equal(roundtrip.result, legacy_test_data.cell_coadd, expect_view=False) 

753 

754 

755# The float32 image pixels are of order 10 nJy, as is the test background 

756# below, so background arithmetic is only reproducible to a few ULPs at that 

757# scale. 

758BACKGROUND_ATOL = 1e-5 

759 

760 

761def _add_gradient_background(coadd: CellCoadd, name: str = "pretty") -> ChebyshevField: 

762 """Add a non-constant background over the coadd's full bbox and return the 

763 field that was added. 

764 """ 

765 field = ChebyshevField( 

766 coadd.bbox, 

767 np.array([[10.0, 2.0, 0.5], [1.0, 0.75, 0.0], [0.25, 0.0, 0.0]]), 

768 unit=coadd.unit, 

769 ) 

770 coadd.backgrounds.add(name, field, description="Gradient background for tests.") 

771 return field 

772 

773 

774def _make_background_subbox(coadd: CellCoadd) -> Box: 

775 """Make a box that trims a different number of pixels from each side of the 

776 coadd, so a background rendered over the wrong box cannot match by chance. 

777 """ 

778 return Box.factory[ 

779 coadd.bbox.y.start + 2 : coadd.bbox.y.stop - 3, 

780 coadd.bbox.x.start + 1 : coadd.bbox.x.stop - 2, 

781 ] 

782 

783 

784def test_apply_background_subimage(minified_cell_coadd: CellCoadd) -> None: 

785 """Test that applying a background to a subimage subtracts only the 

786 portion of the background model that overlaps the subimage. 

787 """ 

788 field = _add_gradient_background(minified_cell_coadd) 

789 subbox = _make_background_subbox(minified_cell_coadd) 

790 subimage = minified_cell_coadd[subbox] 

791 original = subimage.image.array.copy() 

792 

793 subimage.apply_background("pretty") 

794 

795 assert subimage.backgrounds.subtracted is not None 

796 assert subimage.backgrounds.subtracted.name == "pretty" 

797 assert subimage.image.bbox == subbox 

798 expected = field.render(subbox, dtype=subimage.image.array.dtype).array 

799 np.testing.assert_allclose(original - subimage.image.array, expected, atol=BACKGROUND_ATOL) 

800 

801 

802def test_restore_background_subimage(minified_cell_coadd: CellCoadd) -> None: 

803 """Test that restoring the original background on a subimage adds back 

804 only the portion of the background model that overlaps the subimage. 

805 """ 

806 _add_gradient_background(minified_cell_coadd) 

807 subbox = _make_background_subbox(minified_cell_coadd) 

808 subimage = minified_cell_coadd[subbox] 

809 original = subimage.image.array.copy() 

810 subimage.apply_background("pretty") 

811 

812 subimage.apply_background(None) 

813 

814 assert subimage.backgrounds.subtracted is None 

815 np.testing.assert_allclose(subimage.image.array, original, atol=BACKGROUND_ATOL) 

816 

817 

818def test_failed_background_switch_preserves_pixels_and_state( 

819 minified_cell_coadd: CellCoadd, 

820) -> None: 

821 """An invalid replacement must not restore the current background.""" 

822 _add_gradient_background(minified_cell_coadd) 

823 minified_cell_coadd.apply_background("pretty") 

824 before = minified_cell_coadd.image.array.copy() 

825 

826 with pytest.raises(KeyError): 

827 minified_cell_coadd.apply_background("missing") 

828 

829 np.testing.assert_array_equal(minified_cell_coadd.image.array, before) 

830 assert minified_cell_coadd.backgrounds.subtracted is not None 

831 assert minified_cell_coadd.backgrounds.subtracted.name == "pretty" 

832 

833 

834def test_switch_background_applies_replacement(minified_cell_coadd: CellCoadd) -> None: 

835 """Switching models restores the old background and subtracts the new.""" 

836 field = _add_gradient_background(minified_cell_coadd) 

837 minified_cell_coadd.backgrounds.add("other", field * 2.0) 

838 original = minified_cell_coadd.image.array.copy() 

839 minified_cell_coadd.apply_background("pretty") 

840 

841 minified_cell_coadd.apply_background("other") 

842 

843 expected = ( 

844 original 

845 - (field * 2.0).render(minified_cell_coadd.bbox, dtype=minified_cell_coadd.image.array.dtype).array 

846 ) 

847 np.testing.assert_allclose(minified_cell_coadd.image.array, expected, atol=BACKGROUND_ATOL) 

848 assert minified_cell_coadd.backgrounds.subtracted is not None 

849 assert minified_cell_coadd.backgrounds.subtracted.name == "other" 

850 

851 

852def test_apply_background_after_bounded_read(minified_cell_coadd: CellCoadd) -> None: 

853 """Test that a background can be applied to a coadd read with a bbox 

854 parameter. 

855 """ 

856 field = _add_gradient_background(minified_cell_coadd) 

857 subbox = _make_background_subbox(minified_cell_coadd) 

858 with RoundtripJson(minified_cell_coadd, "CellCoadd") as roundtrip: 

859 subimage = roundtrip.get(bbox=subbox) 

860 original = subimage.image.array.copy() 

861 

862 subimage.apply_background("pretty") 

863 

864 assert subimage.image.bbox == subbox 

865 expected = field.render(subbox, dtype=subimage.image.array.dtype).array 

866 np.testing.assert_allclose(original - subimage.image.array, expected, atol=BACKGROUND_ATOL) 

867 

868 

869def test_cell_grid_bounds_contains_broadcasting(minified_cell_coadd: CellCoadd) -> None: 

870 """Test that CellGridBounds.contains broadcasts like a numpy ufunc.""" 

871 assert minified_cell_coadd.bounds.missing, "fixture should retain a missing cell" 

872 check_bounds_contains_broadcasting(minified_cell_coadd.bounds) 

873 

874 

875def test_intersection_bounds_contains_broadcasting(minified_cell_coadd: CellCoadd) -> None: 

876 """Test that IntersectionBounds.contains broadcasts like a numpy ufunc.""" 

877 # Clip the CellGridBounds with a Box offset by 1 pixel on each side so it 

878 # does not snap to any cell boundary, forcing a lazy IntersectionBounds. 

879 bounds = minified_cell_coadd.bounds 

880 clip = Box.factory[ 

881 bounds.bbox.y.start + 1 : bounds.bbox.y.stop - 1, 

882 bounds.bbox.x.start + 1 : bounds.bbox.x.stop - 1, 

883 ] 

884 check_bounds_contains_broadcasting(bounds.intersection(clip))