Coverage for python/lsst/images/tests/_checks.py: 71%

796 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 

14__all__ = ( 

15 "annotate_errors", 

16 "arrays_to_legacy_points", 

17 "assert_cell_coadds_equal", 

18 "assert_images_equal", 

19 "assert_masked_images_equal", 

20 "assert_masks_equal", 

21 "assert_obs_metadata_fields_equal", 

22 "assert_psfs_equal", 

23 "assert_sky_projections_equal", 

24 "assert_values_equal", 

25 "assert_visit_images_equal", 

26 "cell_center_points", 

27 "check_archive_tree_class_invariants", 

28 "check_astropy_wcs_interface", 

29 "check_bounds_contains_broadcasting", 

30 "check_projection", 

31 "check_transform", 

32 "compare_amplifier_to_legacy", 

33 "compare_aperture_corrections_to_legacy", 

34 "compare_cell_coadd_provenance_to_legacy_lazy", 

35 "compare_cell_coadd_to_legacy", 

36 "compare_cell_coadd_to_legacy_lazy", 

37 "compare_detector_to_legacy", 

38 "compare_field_to_legacy", 

39 "compare_image_to_legacy", 

40 "compare_mask_to_legacy", 

41 "compare_masked_image_to_legacy", 

42 "compare_observation_summary_stats_to_legacy", 

43 "compare_photo_calib_to_legacy", 

44 "compare_psf_to_legacy", 

45 "compare_sky_projection_to_legacy_wcs", 

46 "compare_visit_image_to_legacy", 

47 "iter_concrete_archive_tree_subclasses", 

48 "legacy_coords_to_astropy", 

49 "legacy_points_to_xy_array", 

50) 

51 

52import dataclasses 

53import re 

54from abc import ABC, abstractmethod 

55from collections.abc import Generator, Iterator, Mapping 

56from contextlib import contextmanager 

57from typing import TYPE_CHECKING, Any, Literal, NoReturn, Self, cast 

58 

59import astropy.coordinates as coords 

60import astropy.time 

61import astropy.units as u 

62import astropy.wcs.wcsapi 

63import numpy as np 

64import pytest 

65from astropy.coordinates import SkyCoord 

66 

67from .._geom import XY, YX, Bounds, Box 

68from .._image import Image 

69from .._mask import ( 

70 Mask, 

71 MaskPlane, 

72 get_legacy_non_cell_coadd_mask_planes, 

73 get_legacy_visit_image_mask_planes, 

74) 

75from .._masked_image import MaskedImage 

76from .._observation_summary_stats import ObservationSummaryStats 

77from .._transforms import DetectorFrame, Frame, SkyFrame, SkyProjection, TractFrame, Transform 

78from .._visit_image import VisitImage 

79from ..cameras import Amplifier, Detector, DetectorType, ReadoutCorner 

80from ..cells import CellCoadd, CellGridBounds, CellIJ, CoaddProvenance 

81from ..fields import BaseField, ChebyshevField 

82from ..psfs import PointSpreadFunction 

83from ..serialization import ArchiveTree 

84 

85if TYPE_CHECKING: 

86 try: 

87 from lsst.cell_coadds import MultipleCellCoadd 

88 except ImportError: 

89 type MultipleCellCoadd = Any # type: ignore[no-redef] 

90 try: 

91 from lsst.afw.image import PhotoCalib as LegacyPhotoCalib 

92 except ImportError: 

93 type LegacyPhotoCalib = Any # type: ignore[no-redef] 

94 

95 

96# The sky-to-pixel direction of a SkyProjection is a numerical AST inversion 

97# of the celestial projection, so it carries a small error floor (~1e-9 px). 

98# A relative-only tolerance collapses to exact equality at pixel coordinate 

99# zero, so comparisons that can include the origin need a small absolute pixel 

100# tolerance to avoid reporting that numerical noise as a difference. 

101_AST_INV_ATOL = 1e-7 

102 

103# Relative tolerance for comparisons of AST-backed transforms and projections. 

104_AST_RTOL = 1e-9 

105 

106# Default absolute tolerance for great-circle sky-coordinate comparisons, in 

107# the same order of magnitude as _AST_INV_ATOL (which is in pixels). A 

108# nonzero default is important because sky coordinates can be near zero 

109# (e.g. RA/Dec ~ 0), where a relative tolerance provides no error floor. 

110_AST_SKY_ATOL = 1e-7 * u.deg 

111 

112 

113class _BaseCmpArg(ABC): 

114 """A helper base clas for `assert_values_equal` whose subclasses represent 

115 different types of comparisons. 

116 

117 Parameters 

118 ---------- 

119 value 

120 The coerced operand; type is subclass-dependent.. 

121 """ 

122 

123 def __init__(self, value: Any): 

124 self.value = value 

125 

126 @property 

127 @abstractmethod 

128 def unit(self) -> u.UnitBase: 

129 raise NotImplementedError() 

130 

131 def coerce_atol(self, atol: float | u.Quantity | astropy.time.TimeDelta) -> float: 

132 try: 

133 if isinstance(atol, astropy.time.TimeDelta): 

134 return atol.to_value(self.unit) 

135 if atol != 0.0: 

136 return u.Quantity(atol).to_value(self.unit) 

137 return 0.0 

138 except u.UnitConversionError as err: 

139 err.add_note("Invalid atol for these operands.") 

140 raise 

141 

142 def get_nan_mask(self) -> np.ndarray: 

143 return np.isnan(np.asarray(self.value)) 

144 

145 @abstractmethod 

146 def get_separation(self, other: Self) -> np.ndarray: 

147 raise NotImplementedError 

148 

149 @abstractmethod 

150 def find_mismatches( 

151 self, 

152 other: Self, 

153 *, 

154 rtol: float, 

155 atol_value: float, 

156 equal_nan: bool, 

157 ) -> np.ndarray | None: 

158 """Search for element-wise mismatches against ``other``. 

159 

160 Each comparison family implements its own tolerance semantics. 

161 

162 Parameters 

163 ---------- 

164 other 

165 The other comparison argument. 

166 rtol 

167 Relative tolerance. 

168 atol_value 

169 Absolute tolerance, already coerced to this comparison's unit. 

170 equal_nan 

171 If `True`, treat NaN as equal to NaN wherever the operand can 

172 hold NaN. 

173 

174 Returns 

175 ------- 

176 mismatch : `numpy.ndarray` | None 

177 Boolean mask marking differing elements, or `None` if all 

178 elements agree within tolerance. 

179 """ 

180 raise NotImplementedError() 

181 

182 def report_mismatches( 

183 self, 

184 other: Self, 

185 a: Any, 

186 b: Any, 

187 mismatch: np.ndarray, 

188 label: str, 

189 ) -> NoReturn: 

190 """Raise an `AssertionError` reporting a computed mismatch. 

191 

192 Parameters 

193 ---------- 

194 other : _BaseCmpArg 

195 The other comparison argument. 

196 a 

197 First original operand; used for the scalar failure message. 

198 b 

199 Second original operand; used for the scalar failure message. 

200 mismatch 

201 Boolean mask marking differing elements, from `find_mismatches`. 

202 label 

203 Prefix prepended to the failure message. 

204 """ 

205 n_mismatch = int(np.count_nonzero(mismatch)) 

206 prefix = f"{label}: " if label else "" 

207 separation = self.get_separation(other) 

208 if mismatch.shape == (): 

209 raise AssertionError(f"{prefix}{a!r} != {b!r} (differ by {float(separation)}{self.unit})") 

210 nan_mismatch = int(np.count_nonzero(mismatch & (self.get_nan_mask() | other.get_nan_mask()))) 

211 nan_str = f"; {nan_mismatch} NaN mismatches" if nan_mismatch else "" 

212 if np.isnan(separation).all(): 

213 raise AssertionError(f"{prefix}{n_mismatch}/{mismatch.size} values differ{nan_str}") 

214 maxdiff = float(np.nanmax(separation)) 

215 # Convert to plain ints so the index prints as e.g. (2198,) 

216 # rather than (np.int64(2198),). 

217 loc = tuple(int(i) for i in np.unravel_index(np.nanargmax(separation), separation.shape)) 

218 raise AssertionError( 

219 f"{prefix}{n_mismatch}/{mismatch.size} values differ; " 

220 f"max abs diff {maxdiff}{self.unit} at index {loc} {nan_str}" 

221 ) 

222 

223 

224class _QuantityCmpArg(_BaseCmpArg): 

225 """Direct comparison of (possibly dimensionless) 

226 `astropy.units.Quantity` instances, used for all non-separation 

227 floating-point comparisons. 

228 """ 

229 

230 value: u.Quantity 

231 

232 @property 

233 def unit(self) -> u.UnitBase: 

234 return self.value.unit 

235 

236 def get_separation(self, other: Self) -> np.ndarray: 

237 a_vals = self.value.to_value(self.unit) 

238 b_vals = other.value.to_value(self.unit) 

239 return np.abs(a_vals - b_vals) 

240 

241 def find_mismatches( 

242 self, 

243 other: Self, 

244 *, 

245 rtol: float, 

246 atol_value: float, 

247 equal_nan: bool, 

248 ) -> np.ndarray | None: 

249 a_vals = self.value.to_value(self.unit) 

250 b_vals = other.value.to_value(self.unit) 

251 mismatch = ~np.isclose(a_vals, b_vals, rtol=rtol, atol=atol_value, equal_nan=equal_nan) 

252 return mismatch if np.any(mismatch) else None 

253 

254 

255class _SeparationCmpArg(_BaseCmpArg): 

256 """A base class for operands compared through a pairwise separation. 

257 

258 ``rtol`` is meaningless and must be zero for these comparisons. 

259 """ 

260 

261 @property 

262 @abstractmethod 

263 def unit(self) -> u.UnitBase: 

264 raise NotImplementedError 

265 

266 def find_mismatches( 

267 self, 

268 other: Self, 

269 *, 

270 rtol: float, 

271 atol_value: float, 

272 equal_nan: bool, 

273 ) -> np.ndarray | None: 

274 if rtol != 0.0: 

275 raise ValueError(f"rtol is meaningless for separations; use atol (in {self.unit}) instead.") 

276 # A NaN separation (from a NaN operand element) fails the ``<=`` 

277 # test and so counts as a mismatch unless equal_nan clears it. 

278 separation = np.asarray(self.get_separation(other)) 

279 mismatch = np.logical_not(separation <= atol_value) 

280 if equal_nan: 

281 mismatch = mismatch & ~(self.get_nan_mask() & other.get_nan_mask()) 

282 return mismatch if np.any(mismatch) else None 

283 

284 

285class _TimeCmpArg(_SeparationCmpArg): 

286 value: astropy.time.Time 

287 

288 @property 

289 def unit(self) -> u.UnitBase: 

290 return u.s 

291 

292 def get_separation(self, other: Self) -> np.ndarray: 

293 return np.abs((self.value - other.value).sec) 

294 

295 def get_nan_mask(self) -> np.ndarray: 

296 # astropy.time.Time rejects non-finite values at construction. 

297 return np.zeros(self.value.shape, dtype=bool) 

298 

299 

300class _SkyCoordCmpArg(_SeparationCmpArg): 

301 value: SkyCoord 

302 

303 @property 

304 def unit(self) -> u.UnitBase: 

305 return u.arcsec 

306 

307 def get_separation(self, other: Self) -> np.ndarray: 

308 return self.value.separation(other.value).to_value(self.unit) 

309 

310 def get_nan_mask(self) -> np.ndarray: 

311 # A coordinate counts as NaN only when *both* components are NaN; 

312 # a half-NaN coordinate is a difference to report, not a NaN match. 

313 return np.isnan(self.value.ra) & np.isnan(self.value.dec) 

314 

315 

316class _WrappedAngleCmpArg(_SeparationCmpArg): 

317 value: u.Quantity 

318 

319 @property 

320 def unit(self) -> u.UnitBase: 

321 return u.rad 

322 

323 def get_separation(self, other: Self) -> np.ndarray: 

324 a_rad = np.asarray(self.value.to_value(u.rad)) 

325 b_rad = np.asarray(other.value.to_value(u.rad)) 

326 return np.abs((a_rad - b_rad + np.pi) % (2.0 * np.pi) - np.pi) 

327 

328 

329def _classify_operand(arg: Any, *, wrap_angles: bool = False) -> _BaseCmpArg | None: 

330 """Coerce one comparison operand into its comparison-argument wrapper. 

331 

332 Parameters 

333 ---------- 

334 arg 

335 Operand to classify. 

336 wrap_angles 

337 If `True`, ``arg`` must be an angular `~astropy.units.Quantity` and 

338 is classified for wrapped-angle comparison. 

339 

340 Returns 

341 ------- 

342 cmp_arg : _BaseCmpArg | None 

343 Wrapper selecting the comparison space for ``arg``, or `None` for 

344 operands that cannot hold floating-point values (integers, bools, 

345 strings); those are compared exactly by the driver. 

346 """ 

347 if wrap_angles: 

348 return _WrappedAngleCmpArg(u.Quantity(arg).to(u.rad)) 

349 match arg: 

350 case astropy.time.Time(): 

351 return _TimeCmpArg(arg) 

352 case astropy.time.TimeDelta(): 

353 return _QuantityCmpArg(arg.to(u.s)) 

354 case SkyCoord(): 

355 return _SkyCoordCmpArg(arg) 

356 case u.Quantity(): 

357 if arg.dtype.kind not in "fc": 357 ↛ 359line 357 didn't jump to line 359 because the condition on line 357 was never true

358 # Coerce integer Quantities to floating point. 

359 arg = arg.astype(float) 

360 return _QuantityCmpArg(arg) 

361 arg = np.asarray(arg) 

362 if arg.dtype.kind not in "fc": 

363 return None 

364 return _QuantityCmpArg(u.Quantity(arg)) 

365 

366 

367def assert_values_equal( 

368 a: (np.ndarray | u.Quantity | float | astropy.time.Time | astropy.time.TimeDelta | SkyCoord), 

369 b: (np.ndarray | u.Quantity | float | astropy.time.Time | astropy.time.TimeDelta | SkyCoord), 

370 *, 

371 rtol: float = 0.0, 

372 atol: float | u.Quantity | astropy.time.TimeDelta = 0.0, 

373 equal_nan: bool = True, 

374 label: str = "", 

375 wrap_angles: bool = False, 

376) -> None: 

377 """Assert that two arrays, quantities, floats, astropy times, or sky 

378 coordinates are equal or close. 

379 

380 On mismatch this raises an `AssertionError` with a concise report (count, 

381 max absolute difference, location, NaN-mismatch count) rather than dumping 

382 the arrays. Exact (non-floating-point) mismatches instead report through 

383 `numpy.testing.assert_array_equal`. 

384 

385 Both operands must be of the same kind: both floating-point numeric 

386 (bare or as `~astropy.units.Quantity` or `~astropy.time.TimeDelta`), 

387 or both the same astropy type (`~astropy.time.Time` or 

388 `astropy.coordinates.SkyCoord`). 

389 Operands that cannot hold floating-point values (integers, bools, 

390 strings) are compared exactly, with no tolerance or NaN semantics. 

391 Tolerances never have their units guessed: a bare-float ``atol`` is 

392 only valid for dimensionless operands, and for unitful operands only 

393 exactly ``0.0`` (which is unit-independent) is accepted without units. 

394 

395 Parameters 

396 ---------- 

397 a 

398 First value to compare. 

399 b 

400 Second value to compare. 

401 rtol 

402 Relative tolerance, applied to the operand magnitudes. Must be zero 

403 for comparisons of separations. 

404 atol 

405 Absolute tolerance. For dimensionless operands, a bare float. For 

406 unitful operands, a `~astropy.units.Quantity` with units compatible 

407 with ``a``, or exactly ``0.0``. 

408 equal_nan 

409 If `True`, treat NaN as equal to NaN. A `astropy.coordinates.SkyCoord` 

410 element counts as NaN only when both of its coordinates are NaN. 

411 label 

412 Prefix prepended to the failure message. 

413 wrap_angles 

414 If `True`, compare ``a`` and ``b`` (angular quantities) modulo 2 pi. 

415 """ 

416 a_arg = _classify_operand(a, wrap_angles=wrap_angles) 

417 b_arg = _classify_operand(b, wrap_angles=wrap_angles) 

418 if type(a_arg) is not type(b_arg): 

419 raise TypeError(f"cannot compare {type(a).__name__} with {type(b).__name__}") 

420 if a_arg is None or b_arg is None: 

421 # The type check above means both are None: exact comparison of 

422 # operands that cannot hold floating-point values. 

423 if rtol != 0.0 or atol != 0.0: 

424 raise ValueError("rtol and atol are only supported for floating-point operands.") 

425 np.testing.assert_array_equal( 

426 np.asarray(a), 

427 np.asarray(b), 

428 strict=True, 

429 err_msg=f"{label}: arrays are not equal." if label else "", 

430 ) 

431 return 

432 atol_value = a_arg.coerce_atol(atol) 

433 if a_arg.value.shape != b_arg.value.shape: 

434 raise AssertionError(f"{label}: shape {a_arg.value.shape} != {b_arg.value.shape}") 

435 mismatch = a_arg.find_mismatches(b_arg, rtol=rtol, atol_value=atol_value, equal_nan=equal_nan) 

436 if mismatch is not None: 

437 a_arg.report_mismatches(b_arg, a, b, mismatch, label) 

438 

439 

440@contextmanager 

441def annotate_errors(note: str) -> Generator[None]: 

442 """Attach a note to any exception raised in the block. 

443 

444 Parameters 

445 ---------- 

446 note 

447 Note to attach on failure. 

448 """ 

449 try: 

450 yield 

451 except Exception as err: 

452 err.add_note(note) 

453 raise 

454 

455 

456def assert_images_equal( 

457 a: Image, 

458 b: Image, 

459 *, 

460 rtol: float = 0.0, 

461 atol: float = 0.0, 

462 expect_view: bool | Literal["array"] | None = None, 

463) -> None: 

464 """Assert that two images are equal or nearly equal. 

465 

466 Parameters 

467 ---------- 

468 a 

469 First image to compare. 

470 b 

471 Second image to compare. 

472 rtol 

473 Relative tolerance for the pixel comparison. 

474 atol 

475 Absolute tolerance for the pixel comparison. 

476 expect_view 

477 If not `None`, also assert whether ``b`` shares memory with ``a`` 

478 (i.e. is a view); ``"array"`` checks only the pixel arrays. 

479 """ 

480 assert a.bbox == b.bbox 

481 assert a.unit == b.unit 

482 assert_sky_projections_equal(a.sky_projection, b.sky_projection) 

483 if expect_view is not None: 

484 assert np.may_share_memory(a.array, b.array) == bool(expect_view) 

485 if expect_view == "array": 

486 assert a.metadata.native == b.metadata.native 

487 else: 

488 assert (a._metadata is b._metadata) == expect_view 

489 if not expect_view: 

490 assert_values_equal(a.array, b.array, atol=atol, rtol=rtol) 

491 assert a.metadata.native == b.metadata.native 

492 

493 

494def _note_mask_difference( 

495 err: AssertionError, a: Mask, b: Mask, *, label: str, names: Mapping[str, str] | None = None 

496) -> None: 

497 """Embed a plane-by-plane `Mask.compare` summary as a note on ``err``. 

498 

499 Parameters 

500 ---------- 

501 err 

502 Exception to attach the summary to. 

503 a 

504 First mask compared. 

505 b 

506 Second mask compared. 

507 label 

508 Prefix for the failure message. 

509 names 

510 Optional mapping from mask-plane names used by ``a`` and ``b`` to 

511 names to display in the summary (e.g. the legacy names, when 

512 comparing against legacy code). 

513 """ 

514 diff = a.compare(b) 

515 if not diff: 515 ↛ 516line 515 didn't jump to line 516 because the condition on line 515 was never true

516 return 

517 shown = names or {} 

518 summary = "\n".join( 

519 f"{label}[{shown.get(name, name)}]: +{added} -{removed}" for name, (added, removed) in diff.items() 

520 ) 

521 err.add_note(summary) 

522 

523 

524def assert_masks_equal(a: Mask, b: Mask) -> None: 

525 """Assert that two masks are equal or nearly equal. 

526 

527 Parameters 

528 ---------- 

529 a 

530 First mask to compare. 

531 b 

532 Second mask to compare. 

533 """ 

534 assert a.bbox == b.bbox 

535 assert a.schema == b.schema 

536 assert a.metadata.native == b.metadata.native 

537 assert_sky_projections_equal(a.sky_projection, b.sky_projection) 

538 try: 

539 assert_values_equal(a.array, b.array, label="mask") 

540 except AssertionError as err: 

541 _note_mask_difference(err, a, b, label="mask") 

542 raise 

543 

544 

545def assert_masked_images_equal( 

546 a: MaskedImage, 

547 b: MaskedImage, 

548 *, 

549 rtol: float = 0.0, 

550 atol: float = 0.0, 

551 expect_view: bool | None = None, 

552) -> None: 

553 """Assert that two masked images are equal or nearly equal. 

554 

555 Parameters 

556 ---------- 

557 a 

558 First masked image to compare. 

559 b 

560 Second masked image to compare. 

561 rtol 

562 Relative tolerance for the pixel comparison. 

563 atol 

564 Absolute tolerance for the pixel comparison. 

565 expect_view 

566 If not `None`, also assert whether ``b`` shares memory with ``a`` 

567 (i.e. is a view). 

568 """ 

569 assert a.metadata.native == b.metadata.native 

570 assert_sky_projections_equal(a.sky_projection, b.sky_projection) 

571 assert_images_equal(a.image, b.image, rtol=rtol, atol=atol, expect_view=expect_view) 

572 assert_masks_equal(a.mask, b.mask) 

573 assert_images_equal(a.variance, b.variance, rtol=rtol, atol=atol, expect_view=expect_view) 

574 

575 

576def assert_psfs_equal( 

577 psf1: PointSpreadFunction, 

578 psf2: PointSpreadFunction, 

579 points: YX[np.ndarray] | XY[np.ndarray] | None = None, 

580) -> int: 

581 """Compare two PSF objets. 

582 

583 Parameters 

584 ---------- 

585 psf1 

586 Point-spread function to test. 

587 psf2 

588 The other point-spread function to test. 

589 points 

590 Points to evaluate the PSFs at. If not provided, the intersection of 

591 the PSF bounding boxes are used to generate points on a grid. 

592 

593 Returns 

594 ------- 

595 `int` 

596 The number of points actually tested. 

597 """ 

598 if points is None: 598 ↛ 601line 598 didn't jump to line 601 because the condition on line 598 was always true

599 points = psf1.bounds.bbox.intersection(psf2.bounds.bbox).meshgrid(3).map(np.ravel) 

600 

601 assert psf1.kernel_bbox == psf2.kernel_bbox 

602 

603 n_points_tested: int = 0 

604 for x, y in zip(points.x, points.y): 

605 # The two PSFs must agree on which points fall inside their input 

606 # domain. Querying ``.contains`` directly (rather than relying on 

607 # ``compute_kernel_image`` to raise) makes this test tolerant of 

608 # implementations that do not raise on out-of-domain points -- in 

609 # particular ``CellPointSpreadFunction``, where evaluating in a 

610 # missing cell does not always raise ``BoundsError``. 

611 contains1 = psf1.bounds.contains(x=x, y=y) 

612 contains2 = psf2.bounds.contains(x=x, y=y) 

613 assert contains1 == contains2, ( 

614 f"PSFs disagree on whether ({x}, {y}) is in-bounds: psf1={contains1}, psf2={contains2}" 

615 ) 

616 if not contains1: 616 ↛ 617line 616 didn't jump to line 617 because the condition on line 616 was never true

617 continue 

618 assert psf1.compute_kernel_image(x=x, y=y) == psf2.compute_kernel_image(x=x, y=y) 

619 assert psf1.compute_stellar_bbox(x=x, y=y) == psf2.compute_stellar_bbox(x=x, y=y) 

620 assert psf1.compute_stellar_image(x=x, y=y) == psf2.compute_stellar_image(x=x, y=y) 

621 n_points_tested += 1 

622 return n_points_tested 

623 

624 

625def assert_visit_images_equal( 

626 a: VisitImage, 

627 b: VisitImage, 

628 *, 

629 expect_view: bool | None = None, 

630) -> None: 

631 """Assert that two `.VisitImage` instances carry the same persistent state. 

632 

633 Extends `assert_masked_images_equal` with the VisitImage-specific 

634 attributes (PSF, filter, observation info, detector, aperture 

635 corrections, photometric scaling, backgrounds, polygon bounds, 

636 summary stats) so a round-trip check on a `.VisitImage` does not 

637 silently miss differences in any of them. 

638 

639 Parameters 

640 ---------- 

641 a 

642 First visit image to compare. 

643 b 

644 Second visit image to compare. 

645 expect_view 

646 If not `None`, also assert whether ``b`` shares memory with ``a`` 

647 (i.e. is a view). 

648 """ 

649 assert_masked_images_equal(a, b, expect_view=expect_view) 

650 assert a.summary_stats == b.summary_stats 

651 assert a.physical_filter == b.physical_filter 

652 assert a.band == b.band 

653 assert a.obs_info == b.obs_info 

654 assert a.detector == b.detector 

655 assert dict(a.aperture_corrections) == dict(b.aperture_corrections) 

656 assert a.photometric_scaling == b.photometric_scaling 

657 assert dict(a.backgrounds) == dict(b.backgrounds) 

658 assert a.backgrounds.subtracted == b.backgrounds.subtracted 

659 assert a.bounds == b.bounds 

660 assert_psfs_equal(a.psf, b.psf) 

661 

662 

663def assert_cell_coadds_equal( 

664 a: CellCoadd, 

665 b: CellCoadd, 

666 *, 

667 expect_view: bool | None = None, 

668) -> None: 

669 """Assert that two `.CellCoadd` instances carry the same persistent state. 

670 

671 Extends the masked-image-style equality check with the 

672 CellCoadd-specific attributes (PSF, cell grid, missing cells, aperture 

673 corrections, backgrounds, patch/tract, band) so a round-trip check does not 

674 silently miss differences in any of them. 

675 

676 Parameters 

677 ---------- 

678 a 

679 First cell coadd to compare. 

680 b 

681 Second cell coadd to compare. 

682 expect_view 

683 If not `None`, also assert whether ``b`` shares memory with ``a`` 

684 (i.e. is a view). 

685 """ 

686 assert_masked_images_equal(a, b, expect_view=expect_view) 

687 assert a.band == b.band 

688 assert a.patch == b.patch 

689 assert a.tract == b.tract 

690 assert a.grid == b.grid 

691 assert a.bounds.missing == b.bounds.missing 

692 assert dict(a.backgrounds) == dict(b.backgrounds) 

693 assert a.backgrounds.subtracted == b.backgrounds.subtracted 

694 assert a.aperture_corrections.keys() == b.aperture_corrections.keys() 

695 for name, field in a.aperture_corrections.items(): 

696 other_field = b.aperture_corrections[name] 

697 assert (field is None) == (other_field is None), f"Aperture correction {name} is None in only one" 

698 if field is not None and other_field is not None: 

699 assert field.bounds == other_field.bounds, f"Bounds differ for aperture correction {name}" 

700 assert_values_equal(field._array, other_field._array, label=f"aperture_corrections/{name}") 

701 assert_psfs_equal(a.psf, b.psf) 

702 

703 

704def compare_image_to_legacy( 

705 image: Image, 

706 legacy_image: Any, 

707 expect_view: bool | None = None, 

708 *, 

709 label: str = "image", 

710 atol: float = 0.0, 

711) -> None: 

712 """Compare an `.Image` object to a legacy `lsst.afw.image.Image` object. 

713 

714 Parameters 

715 ---------- 

716 image 

717 Image to compare. 

718 legacy_image 

719 Legacy `lsst.afw.image.Image` to compare against. 

720 expect_view 

721 If not `None`, also assert whether ``image`` shares memory with 

722 ``legacy_image`` (i.e. is a view). 

723 label 

724 Prefix for the failure message. 

725 atol 

726 Absolute tolerance for the pixel-value comparison. 

727 """ 

728 assert image.bbox == Box.from_legacy(legacy_image.getBBox()) 

729 if expect_view is not None: 729 ↛ 731line 729 didn't jump to line 731 because the condition on line 729 was always true

730 assert np.may_share_memory(image.array, legacy_image.array) == expect_view 

731 if not expect_view: 731 ↛ exitline 731 didn't return from function 'compare_image_to_legacy' because the condition on line 731 was always true

732 assert_values_equal(image.array, legacy_image.array, atol=atol, label=label) 

733 

734 

735def compare_mask_to_legacy( 

736 mask: Mask, 

737 legacy_mask: Any, 

738 plane_map: Mapping[str, MaskPlane] | None = None, 

739 *, 

740 label: str = "mask", 

741) -> None: 

742 """Compare a `.Mask` object to a legacy `lsst.afw.image.Mask` object. 

743 

744 Parameters 

745 ---------- 

746 mask 

747 Mask to compare. 

748 legacy_mask 

749 Legacy `lsst.afw.image.Mask` to compare against. 

750 plane_map 

751 Mapping from legacy plane name to the new mask plane; defaults to 

752 the planes in ``mask.schema``. Schema planes the map does not name 

753 are compared under their own names. A plane the legacy mask does 

754 not define must have no pixels set in ``mask``. 

755 label 

756 Prefix for the failure message; each plane is reported as 

757 ``"{label}[<plane>]"``. 

758 """ 

759 assert mask.bbox == Box.from_legacy(legacy_mask.getBBox()) 

760 if plane_map is None: 

761 plane_map = {plane.name: plane for plane in mask.schema if plane is not None} 

762 legacy_planes = legacy_mask.getMaskPlaneDict() 

763 # Compare schema planes the map does not name (e.g. the planes of 

764 # `get_legacy_optional_mask_planes`) under their own names. 

765 plane_map = dict(plane_map) 

766 mapped = {plane.name for plane in plane_map.values()} 

767 plane_map.update( 

768 {plane.name: plane for plane in mask.schema if plane is not None and plane.name not in mapped} 

769 ) 

770 try: 

771 for old_name, new_plane in plane_map.items(): 

772 pixels = mask.get(new_plane.name) 

773 if old_name not in legacy_planes: 

774 # A plane the legacy mask does not define must be empty. 

775 assert_values_equal(np.zeros_like(pixels), pixels, label=f"{label}[{old_name}]") 

776 continue 

777 assert_values_equal( 

778 (legacy_mask.array & legacy_mask.getPlaneBitMask(old_name)).astype(bool), 

779 pixels, 

780 label=f"{label}[{old_name}]", 

781 ) 

782 except AssertionError as err: 

783 names = {new_plane.name: old_name for old_name, new_plane in plane_map.items()} 

784 _note_mask_difference(err, mask, Mask.from_legacy(legacy_mask, plane_map), label=label, names=names) 

785 raise 

786 

787 

788def compare_masked_image_to_legacy( 

789 masked_image: MaskedImage, 

790 legacy_masked_image: Any, 

791 *, 

792 plane_map: Mapping[str, MaskPlane] | None = None, 

793 expect_view: bool | None = None, 

794 alternates: Mapping[str, Any] | None = None, 

795 image_atol: float = 0.0, 

796 variance_atol: float = 0.0, 

797) -> None: 

798 """Compare a `.MaskedImage` object to a legacy `lsst.afw.image.MaskedImage` 

799 object. 

800 

801 Parameters 

802 ---------- 

803 masked_image 

804 New image to test. 

805 legacy_masked_image 

806 Legacy image to test against. 

807 plane_map 

808 Mapping between new and legacy mask planes. 

809 expect_view 

810 Whether to test that the image and variance arrays do or do not share 

811 memory. 

812 alternates 

813 A mapping of other versions of one or more (new) components to also 

814 check against the legacy versions of those components. 

815 image_atol 

816 Absolute tolerance for the image pixel comparison. 

817 variance_atol 

818 Absolute tolerance for the variance pixel comparison. Separate from 

819 ``image_atol`` because the two have different units. The mask 

820 comparison is always exact. 

821 """ 

822 compare_image_to_legacy( 

823 masked_image.image, 

824 legacy_masked_image.getImage(), 

825 expect_view=expect_view, 

826 label="image", 

827 atol=image_atol, 

828 ) 

829 compare_mask_to_legacy( 

830 masked_image.mask, legacy_masked_image.getMask(), plane_map=plane_map, label="mask" 

831 ) 

832 compare_image_to_legacy( 

833 masked_image.variance, 

834 legacy_masked_image.getVariance(), 

835 expect_view=expect_view, 

836 label="variance", 

837 atol=variance_atol, 

838 ) 

839 if alternates: 839 ↛ 840line 839 didn't jump to line 840 because the condition on line 839 was never true

840 if image := alternates.get("image"): 

841 compare_image_to_legacy( 

842 image, 

843 legacy_masked_image.getImage(), 

844 expect_view=expect_view, 

845 label="image", 

846 atol=image_atol, 

847 ) 

848 if mask := alternates.get("mask"): 

849 compare_mask_to_legacy(mask, legacy_masked_image.getMask(), plane_map=plane_map, label="mask") 

850 if variance := alternates.get("variance"): 

851 compare_image_to_legacy( 

852 variance, 

853 legacy_masked_image.getVariance(), 

854 expect_view=expect_view, 

855 label="variance", 

856 atol=variance_atol, 

857 ) 

858 

859 

860def compare_visit_image_to_legacy( 

861 visit_image: VisitImage, 

862 legacy_exposure: Any, 

863 *, 

864 plane_map: Mapping[str, MaskPlane] | None = None, 

865 expect_view: bool | None = None, 

866 instrument: str, 

867 visit: int, 

868 detector: int, 

869 applied_legacy_photo_calib: LegacyPhotoCalib | None = None, 

870 alternates: Mapping[str, Any] | None = None, 

871 check_photometric_scaling: bool = True, 

872) -> None: 

873 """Compare a `.VisitImage` object to a legacy `lsst.afw.image.Exposure` 

874 object. 

875 

876 Parameters 

877 ---------- 

878 visit_image 

879 New image to test. 

880 legacy_exposure 

881 Legacy image to test against. 

882 plane_map 

883 Mapping between new and legacy mask planes; defaults to the planes 

884 used by the legacy (`lsst.afw.image.Exposure`) visit image. 

885 expect_view 

886 Whether to test that the image and variance arrays do or do not share 

887 memory. 

888 instrument 

889 Expected instrument name. 

890 visit 

891 Expected visit ID. 

892 detector 

893 Expected detector ID. 

894 applied_legacy_photo_calib 

895 Legacy `lsst.afw.image.PhotoCalib` already applied to 

896 ``legacy_exposure``, used when comparing photometric scaling. 

897 alternates 

898 A mapping of other versions of one or more (new) components to also 

899 check against the legacy versions of those components. 

900 check_photometric_scaling 

901 If `False`, skip the photometric-scaling comparison. 

902 """ 

903 if plane_map is None: 

904 plane_map = get_legacy_visit_image_mask_planes() 

905 compare_masked_image_to_legacy( 

906 visit_image, 

907 legacy_exposure.getMaskedImage(), 

908 plane_map=plane_map, 

909 expect_view=expect_view, 

910 alternates=alternates, 

911 ) 

912 detector_bbox = Box.from_legacy(legacy_exposure.getDetector().getBBox()) 

913 with annotate_errors("sky_projection"): 

914 compare_sky_projection_to_legacy_wcs( 

915 visit_image.sky_projection, 

916 legacy_exposure.getWcs(), 

917 DetectorFrame(instrument=instrument, visit=visit, detector=detector, bbox=detector_bbox), 

918 visit_image.bbox, 

919 ) 

920 assert visit_image.sky_projection is visit_image.mask.sky_projection 

921 assert visit_image.sky_projection is visit_image.variance.sky_projection 

922 with annotate_errors("psf"): 

923 compare_psf_to_legacy(visit_image.psf, legacy_exposure.getPsf()) 

924 with annotate_errors("summary_stats"): 

925 compare_observation_summary_stats_to_legacy( 

926 visit_image.summary_stats, legacy_exposure.info.getSummaryStats() 

927 ) 

928 with annotate_errors("detector"): 

929 compare_detector_to_legacy(visit_image.detector, legacy_exposure.getDetector(), is_raw_assembled=True) 

930 # Make a tiny box for Field comparisons that need to make arrays; that can 

931 # get expensive otherwise. 

932 tiny_bbox = detector_bbox.local[2:4, 3:6] 

933 with annotate_errors("aperture_corrections"): 

934 compare_aperture_corrections_to_legacy( 

935 visit_image.aperture_corrections, legacy_exposure.info.getApCorrMap(), tiny_bbox 

936 ) 

937 if check_photometric_scaling: 

938 with annotate_errors("photometric_scaling"): 

939 compare_photo_calib_to_legacy( 

940 visit_image.photometric_scaling, 

941 legacy_exposure.info.getPhotoCalib(), 

942 applied_legacy_photo_calib=applied_legacy_photo_calib, 

943 subimage_bbox=tiny_bbox, 

944 ) 

945 if alternates: 

946 if (bbox := alternates.get("bbox")) is not None: 

947 assert bbox == visit_image.bbox 

948 if sky_projection := alternates.get("sky_projection"): 

949 with annotate_errors("sky_projection"): 

950 compare_sky_projection_to_legacy_wcs( 

951 sky_projection, 

952 legacy_exposure.getWcs(), 

953 DetectorFrame(instrument=instrument, visit=visit, detector=detector, bbox=detector_bbox), 

954 visit_image.bbox, 

955 ) 

956 if psf := alternates.get("psf"): 

957 with annotate_errors("psf"): 

958 compare_psf_to_legacy(psf, legacy_exposure.getPsf()) 

959 if summary_stats := alternates.get("summary_stats"): 

960 with annotate_errors("summary_stats"): 

961 compare_observation_summary_stats_to_legacy( 

962 summary_stats, legacy_exposure.info.getSummaryStats() 

963 ) 

964 if detector_obj := alternates.get("detector"): 

965 with annotate_errors("detector"): 

966 compare_detector_to_legacy(detector_obj, legacy_exposure.getDetector(), is_raw_assembled=True) 

967 if obs_info := alternates.get("obs_info"): 

968 visitInfo = legacy_exposure.visitInfo 

969 assert obs_info.instrument == visitInfo.getInstrumentLabel() 

970 if aperture_corrections := alternates.get("aperture_corrections"): 

971 with annotate_errors("aperture_corrections"): 

972 compare_aperture_corrections_to_legacy( 

973 aperture_corrections, legacy_exposure.info.getApCorrMap(), tiny_bbox 

974 ) 

975 if check_photometric_scaling: 

976 if (photometric_scaling := alternates.get("photometric_scaling", ...)) is not ...: 

977 with annotate_errors("photometric_scaling"): 

978 compare_photo_calib_to_legacy( 

979 photometric_scaling, 

980 legacy_exposure.info.getPhotoCalib(), 

981 applied_legacy_photo_calib=applied_legacy_photo_calib, 

982 subimage_bbox=tiny_bbox, 

983 ) 

984 

985 

986def compare_photo_calib_to_legacy( 

987 photometric_scaling: BaseField | None, 

988 legacy_photo_calib: LegacyPhotoCalib, 

989 *, 

990 applied_legacy_photo_calib: LegacyPhotoCalib | None = None, 

991 subimage_bbox: Box, 

992) -> None: 

993 if legacy_photo_calib._isConstant: 

994 if legacy_photo_calib.getCalibrationMean() == 1.0: 

995 if applied_legacy_photo_calib is None: 

996 assert photometric_scaling is None 

997 return 

998 else: 

999 legacy_photo_calib = applied_legacy_photo_calib 

1000 if legacy_photo_calib._isConstant: 

1001 assert isinstance(photometric_scaling, ChebyshevField) 

1002 assert_values_equal( 

1003 photometric_scaling.coefficients, 

1004 np.array([[legacy_photo_calib.getCalibrationMean()]]), 

1005 # The coefficients come from a numerical fit, so this can be 

1006 # bigger than just round-off error epislon. 

1007 rtol=1e-5, 

1008 ) 

1009 else: 

1010 assert photometric_scaling is not None 

1011 compare_field_to_legacy( 

1012 photometric_scaling / legacy_photo_calib.getCalibrationMean(), 

1013 legacy_photo_calib.computeScaledCalibration(), 

1014 subimage_bbox, 

1015 ) 

1016 

1017 

1018def _check_cell_coadd_geometry(cell_coadd: CellCoadd, tract_bbox: Box) -> None: 

1019 """Check the geometric self-consistency of a cell coadd's patch, 

1020 bounds, grid, and bounding box. 

1021 

1022 Parameters 

1023 ---------- 

1024 cell_coadd 

1025 Coadd to test. 

1026 tract_bbox 

1027 Bounding box of the full tract. 

1028 """ 

1029 assert tract_bbox.contains(cell_coadd.patch.outer_bbox) 

1030 assert cell_coadd.patch.outer_bbox.contains(cell_coadd.patch.inner_bbox) 

1031 assert cell_coadd.patch.outer_bbox.contains(cell_coadd.bbox) 

1032 # bounds.bbox is snapped to cell boundaries while cell_coadd.bbox is not, 

1033 # but bounds.bbox can also shrink if one or more rows or columns of cells 

1034 # are missing around the outside. So the only guaranteed relationship is 

1035 # that they overlap (i.e. intersection does not raise). 

1036 cell_coadd.bounds.bbox.intersection(cell_coadd.bbox) 

1037 assert cell_coadd.grid.bbox.contains(cell_coadd.bbox) 

1038 

1039 

1040def cell_center_points(bounds: CellGridBounds) -> YX[np.ndarray]: 

1041 """Return the centers of the non-missing cells of cell grid bounds. 

1042 

1043 These are the points at which approximations made by conversions from 

1044 legacy (non-cell) coadds are expected to be accurate. 

1045 

1046 Parameters 

1047 ---------- 

1048 bounds 

1049 Cell grid bounds whose cells' centers are returned. 

1050 

1051 Returns 

1052 ------- 

1053 `.YX` [ `numpy.ndarray` ] 

1054 Centers of the non-missing cells within ``bounds``. 

1055 """ 

1056 xs: list[float] = [] 

1057 ys: list[float] = [] 

1058 for cell in bounds.cell_indices(): 

1059 bbox = bounds.grid.bbox_of(cell) 

1060 xs.append(bbox.x.center) 

1061 ys.append(bbox.y.center) 

1062 return YX(y=np.array(ys), x=np.array(xs)) 

1063 

1064 

1065def compare_cell_coadd_to_legacy( 

1066 cell_coadd: CellCoadd, 

1067 legacy_cell_coadd: MultipleCellCoadd, 

1068 *, 

1069 tract_bbox: Box, 

1070 plane_map: Mapping[str, MaskPlane] | None = None, 

1071 alternates: Mapping[str, Any] | None = None, 

1072 psf_points: XY[np.ndarray] | YX[np.ndarray] | None = None, 

1073) -> None: 

1074 """Compare a `.cells.CellCoadd` object to a legacy 

1075 `lsst.cell_coadds.MultipleCellCoadd` object. 

1076 

1077 Parameters 

1078 ---------- 

1079 cell_coadd 

1080 New coadd to test. 

1081 legacy_cell_coadd 

1082 Legacy coadd to test against. 

1083 tract_bbox 

1084 Bounding box of the full tract. 

1085 plane_map 

1086 Mapping between new and legacy mask planes. 

1087 alternates 

1088 A mapping of other versions of one or more (new) components to also 

1089 check against the legacy versions of those components. 

1090 psf_points 

1091 Points to use to compare the PSFs. 

1092 """ 

1093 legacy_stitched = legacy_cell_coadd.stitch(cell_coadd.bbox.to_legacy()) 

1094 compare_image_to_legacy(cell_coadd.image, legacy_stitched.image, expect_view=False) 

1095 compare_mask_to_legacy(cell_coadd.mask, legacy_stitched.mask, plane_map=plane_map) 

1096 compare_image_to_legacy(cell_coadd.variance, legacy_stitched.variance, expect_view=False) 

1097 if legacy_stitched.mask_fractions is not None: 1097 ↛ 1101line 1097 didn't jump to line 1101 because the condition on line 1097 was always true

1098 compare_image_to_legacy( 

1099 cell_coadd.mask_fractions["rejected"], legacy_stitched.mask_fractions, expect_view=False 

1100 ) 

1101 for n in range(legacy_stitched.n_noise_realizations): 

1102 compare_image_to_legacy( 

1103 cell_coadd.noise_realizations[n], legacy_stitched.noise_realizations[n], expect_view=False 

1104 ) 

1105 assert cell_coadd.skymap == legacy_stitched.identifiers.skymap 

1106 assert cell_coadd.tract == legacy_stitched.identifiers.tract 

1107 assert cell_coadd.patch.index.x == legacy_stitched.identifiers.patch.x 

1108 assert cell_coadd.patch.index.y == legacy_stitched.identifiers.patch.y 

1109 assert cell_coadd.band == legacy_stitched.identifiers.band 

1110 _check_cell_coadd_geometry(cell_coadd, tract_bbox) 

1111 assert cell_coadd.unit == u.Unit(legacy_cell_coadd.common.units.value) 

1112 compare_sky_projection_to_legacy_wcs( 

1113 cell_coadd.sky_projection, 

1114 legacy_cell_coadd.wcs, 

1115 TractFrame( 

1116 skymap=legacy_cell_coadd.identifiers.skymap, 

1117 tract=legacy_cell_coadd.identifiers.tract, 

1118 bbox=tract_bbox, 

1119 ), 

1120 cell_coadd.bbox, 

1121 is_fits=True, 

1122 ) 

1123 assert cell_coadd.sky_projection is cell_coadd.mask.sky_projection 

1124 assert cell_coadd.sky_projection is cell_coadd.variance.sky_projection 

1125 compare_psf_to_legacy( 

1126 cell_coadd.psf, legacy_stitched.psf, expect_legacy_raise_on_out_of_bounds=True, points=psf_points 

1127 ) 

1128 compare_aperture_corrections_to_legacy( 

1129 cell_coadd.aperture_corrections, legacy_stitched.ap_corr_map, cell_coadd.bbox 

1130 ) 

1131 compare_cell_coadd_provenance_to_legacy(cell_coadd.provenance, legacy_cell_coadd) 

1132 if alternates: 1132 ↛ 1133line 1132 didn't jump to line 1133 because the condition on line 1132 was never true

1133 if sky_projection := alternates.get("sky_projection"): 

1134 compare_sky_projection_to_legacy_wcs( 

1135 sky_projection, 

1136 legacy_stitched.wcs, 

1137 TractFrame( 

1138 skymap=legacy_cell_coadd.identifiers.skymap, 

1139 tract=legacy_cell_coadd.identifiers.tract, 

1140 bbox=tract_bbox, 

1141 ), 

1142 cell_coadd.bbox, 

1143 is_fits=True, 

1144 ) 

1145 if psf := alternates.get("psf"): 

1146 compare_psf_to_legacy(psf, legacy_stitched.psf, points=psf_points) 

1147 if aperture_corrections := alternates.get("aperture_corrections"): 

1148 compare_aperture_corrections_to_legacy( 

1149 aperture_corrections, legacy_stitched.ap_corr_map, cell_coadd.bbox 

1150 ) 

1151 if provenance := alternates.get("provenance"): 

1152 compare_cell_coadd_provenance_to_legacy(provenance, legacy_cell_coadd) 

1153 

1154 

1155def compare_cell_coadd_provenance_to_legacy( 

1156 provenance: CoaddProvenance, legacy_cell_coadd: MultipleCellCoadd 

1157) -> None: 

1158 """Compare a `.cells.CoaddProvenance` object to a legacy 

1159 `lsst.cell_coadds.MultipleCellCoadd` object. 

1160 

1161 Parameters 

1162 ---------- 

1163 provenance 

1164 New provenance object to test. 

1165 legacy_cell_coadd 

1166 Legacy coadd to test against. 

1167 """ 

1168 from lsst.cell_coadds import ObservationIdentifiers 

1169 

1170 for legacy_cell in legacy_cell_coadd.cells.values(): 

1171 cell_index = CellIJ.from_legacy(legacy_cell.identifiers.cell) 

1172 prov = provenance[cell_index] 

1173 assert prov is not None, f"Legacy cell {cell_index} has inputs, so its provenance is not empty." 

1174 legacy_table = astropy.table.Table( 

1175 rows=[ 

1176 [ 

1177 ids.instrument, 

1178 ids.visit, 

1179 ids.detector, 

1180 ids.day_obs, 

1181 ids.physical_filter, 

1182 legacy_input.overlaps_center, 

1183 legacy_input.overlap_fraction, 

1184 legacy_input.weight, 

1185 legacy_input.psf_shape.getIxx(), 

1186 legacy_input.psf_shape.getIyy(), 

1187 legacy_input.psf_shape.getIxy(), 

1188 legacy_input.psf_shape_flag, 

1189 ] 

1190 for ids, legacy_input in legacy_cell.inputs.items() 

1191 ], 

1192 dtype=[ 

1193 np.object_, 

1194 np.uint64, 

1195 np.uint16, 

1196 np.uint32, 

1197 np.object_, 

1198 np.bool_, 

1199 np.float64, 

1200 np.float64, 

1201 np.float64, 

1202 np.float64, 

1203 np.float64, 

1204 np.bool_, 

1205 ], 

1206 names=[ 

1207 "instrument", 

1208 "visit", 

1209 "detector", 

1210 "day_obs", 

1211 "physical_filter", 

1212 "overlaps_center", 

1213 "overlap_fraction", 

1214 "weight", 

1215 "psf_shape_xx", 

1216 "psf_shape_yy", 

1217 "psf_shape_xy", 

1218 "psf_shape_flag", 

1219 ], 

1220 ) 

1221 # For a single cell all 'inputs' are also 'contributions'. 

1222 assert len(legacy_cell.inputs) == len(prov.inputs) 

1223 assert len(legacy_cell.inputs) == len(prov.contributions) 

1224 prov.inputs.sort(["instrument", "visit", "detector"]) 

1225 prov.contributions.sort(["instrument", "visit", "detector"]) 

1226 legacy_table.sort(["instrument", "visit", "detector"]) 

1227 assert_values_equal(prov.inputs["instrument"], prov.contributions["instrument"], label="inputs") 

1228 assert_values_equal(prov.inputs["visit"], prov.contributions["visit"], label="inputs") 

1229 assert_values_equal(prov.inputs["detector"], prov.contributions["detector"], label="inputs") 

1230 assert_values_equal(prov.inputs["instrument"], legacy_table["instrument"], label="inputs") 

1231 assert_values_equal(prov.inputs["visit"], legacy_table["visit"], label="inputs") 

1232 assert_values_equal(prov.inputs["detector"], legacy_table["detector"], label="inputs") 

1233 assert_values_equal(prov.inputs["physical_filter"], legacy_table["physical_filter"], label="inputs") 

1234 assert_values_equal(prov.inputs["day_obs"], legacy_table["day_obs"], label="inputs") 

1235 assert_values_equal( 

1236 prov.contributions["overlaps_center"], legacy_table["overlaps_center"], label="inputs" 

1237 ) 

1238 assert_values_equal( 

1239 prov.contributions["overlap_fraction"], legacy_table["overlap_fraction"], label="inputs" 

1240 ) 

1241 assert_values_equal(prov.contributions["weight"], legacy_table["weight"], label="inputs") 

1242 assert_values_equal(prov.contributions["psf_shape_xx"], legacy_table["psf_shape_xx"], label="inputs") 

1243 assert_values_equal(prov.contributions["psf_shape_yy"], legacy_table["psf_shape_yy"], label="inputs") 

1244 assert_values_equal(prov.contributions["psf_shape_xy"], legacy_table["psf_shape_xy"], label="inputs") 

1245 assert_values_equal( 

1246 prov.contributions["psf_shape_flag"], legacy_table["psf_shape_flag"], label="inputs" 

1247 ) 

1248 for row in prov.inputs: 

1249 polygon_key = ObservationIdentifiers(**{k: row[k] for k in row.keys() if k != "polygon"}) 

1250 legacy_polygon = legacy_cell_coadd.common.visit_polygons[polygon_key] 

1251 assert legacy_polygon == row["polygon"].to_legacy() 

1252 

1253 

1254def compare_cell_coadd_to_legacy_lazy( 

1255 cell_coadd: CellCoadd, 

1256 legacy_exposure: Any, 

1257 *, 

1258 skymap: str, 

1259 tract: int, 

1260 patch: int, 

1261 band: str, 

1262 tract_bbox: Box, 

1263 plane_map: Mapping[str, MaskPlane] | None = None, 

1264 unit: u.UnitBase = u.nJy, 

1265 expect_view: bool | None = None, 

1266 alternates: Mapping[str, Any] | None = None, 

1267 psf_points: XY[np.ndarray] | YX[np.ndarray] | None = None, 

1268 image_atol: float = 0.0, 

1269 variance_atol: float = 0.0, 

1270) -> None: 

1271 """Compare a `.cells.CellCoadd` object to the legacy 

1272 `lsst.afw.image.Exposure` instance it was converted from 

1273 by ``CellCoadd.from_legacy_lazy_coadd``. 

1274 

1275 Parameters 

1276 ---------- 

1277 cell_coadd 

1278 New coadd to test. 

1279 legacy_exposure 

1280 Legacy `lsst.afw.image.Exposure` to test against. 

1281 skymap 

1282 Expected skymap name, which the legacy exposure does not carry. 

1283 tract 

1284 Expected tract ID. 

1285 patch 

1286 Expected patch sequential ID. 

1287 band 

1288 Expected band name. 

1289 tract_bbox 

1290 Bounding box of the full tract. 

1291 plane_map 

1292 Mapping between new and legacy mask planes; defaults to the planes 

1293 used by legacy (non-cell) coadds like DP2's ``template_coadd``. 

1294 unit 

1295 Expected pixel unit of the coadd. 

1296 expect_view 

1297 Whether to test that the image and variance arrays do or do not 

1298 share memory with ``legacy_exposure``. 

1299 alternates 

1300 A mapping of other versions of one or more (new) components to also 

1301 check against the legacy versions of those components. 

1302 psf_points 

1303 Points to use to compare the PSFs. Defaults to the centers of the 

1304 coadd's non-missing cells. 

1305 image_atol 

1306 Absolute tolerance for the image pixel comparison. 

1307 variance_atol 

1308 Absolute tolerance for the variance pixel comparison. 

1309 """ 

1310 if plane_map is None: 

1311 plane_map = get_legacy_non_cell_coadd_mask_planes() 

1312 compare_masked_image_to_legacy( 

1313 cell_coadd, 

1314 legacy_exposure.getMaskedImage(), 

1315 plane_map=plane_map, 

1316 expect_view=expect_view, 

1317 image_atol=image_atol, 

1318 variance_atol=variance_atol, 

1319 ) 

1320 # A legacy (non-cell) coadd has no place for any of these components, 

1321 # so a faithful conversion must not invent them. 

1322 assert cell_coadd.mask_fractions == {} 

1323 assert cell_coadd.noise_realizations == [] 

1324 assert cell_coadd.backgrounds.keys() == set() 

1325 assert cell_coadd.backgrounds.subtracted is None 

1326 assert cell_coadd.skymap == skymap 

1327 assert cell_coadd.tract == tract 

1328 assert cell_coadd.patch.id == patch 

1329 assert cell_coadd.band == band 

1330 assert cell_coadd.unit == unit 

1331 _check_cell_coadd_geometry(cell_coadd, tract_bbox) 

1332 assert cell_coadd.sky_projection is cell_coadd.mask.sky_projection 

1333 assert cell_coadd.sky_projection is cell_coadd.variance.sky_projection 

1334 compare_sky_projection_to_legacy_wcs( 

1335 cell_coadd.sky_projection, 

1336 legacy_exposure.getWcs(), 

1337 TractFrame(skymap=skymap, tract=tract, bbox=tract_bbox), 

1338 cell_coadd.bbox, 

1339 is_fits=True, 

1340 ) 

1341 if psf_points is None: 

1342 psf_points = cell_center_points(cell_coadd.bounds) 

1343 n_psf_points = compare_psf_to_legacy( 

1344 cell_coadd.psf, legacy_exposure.getPsf(), points=psf_points, rtol=1e-5 

1345 ) 

1346 assert n_psf_points > 0, "The legacy PSF could not be evaluated at any of the PSF comparison points." 

1347 compare_aperture_corrections_to_legacy( 

1348 cell_coadd.aperture_corrections, 

1349 legacy_exposure.info.getApCorrMap(), 

1350 cell_coadd.bbox, 

1351 eval_points=psf_points, 

1352 expect_subset_bounds=True, 

1353 ) 

1354 compare_cell_coadd_provenance_to_legacy_lazy(cell_coadd.provenance, legacy_exposure, cell_coadd.bounds) 

1355 if alternates: 

1356 if sky_projection := alternates.get("sky_projection"): 

1357 compare_sky_projection_to_legacy_wcs( 

1358 sky_projection, 

1359 legacy_exposure.getWcs(), 

1360 TractFrame(skymap=skymap, tract=tract, bbox=tract_bbox), 

1361 cell_coadd.bbox, 

1362 is_fits=True, 

1363 ) 

1364 if psf := alternates.get("psf"): 

1365 assert compare_psf_to_legacy(psf, legacy_exposure.getPsf(), points=psf_points, rtol=1e-5) > 0 

1366 if aperture_corrections := alternates.get("aperture_corrections"): 

1367 compare_aperture_corrections_to_legacy( 

1368 aperture_corrections, 

1369 legacy_exposure.info.getApCorrMap(), 

1370 cell_coadd.bbox, 

1371 eval_points=psf_points, 

1372 expect_subset_bounds=True, 

1373 ) 

1374 if provenance := alternates.get("provenance"): 

1375 compare_cell_coadd_provenance_to_legacy_lazy(provenance, legacy_exposure, cell_coadd.bounds) 

1376 

1377 

1378def compare_cell_coadd_provenance_to_legacy_lazy( 

1379 provenance: CoaddProvenance, 

1380 legacy_exposure: Any, 

1381 bounds: CellGridBounds, 

1382) -> None: 

1383 """Compare a `.cells.CoaddProvenance` object to the 

1384 `lsst.afw.image.CoaddInputs` of the legacy (non-cell) coadd it was 

1385 converted from. 

1386 

1387 Parameters 

1388 ---------- 

1389 provenance 

1390 New provenance object to test. 

1391 legacy_exposure 

1392 Legacy `lsst.afw.image.Exposure` whose ``info.getCoaddInputs()`` 

1393 the provenance should be consistent with. 

1394 bounds 

1395 The cell bounds of the coadd this provenance belongs to. 

1396 """ 

1397 coadd_inputs = legacy_exposure.info.getCoaddInputs() 

1398 assert coadd_inputs is not None 

1399 wcs = legacy_exposure.getWcs() 

1400 legacy_by_key: dict[tuple[int, int], Any] = {(row["visit"], row["ccd"]): row for row in coadd_inputs.ccds} 

1401 inputs = provenance.inputs 

1402 prov_keys = {(row["visit"], row["detector"]) for row in inputs} 

1403 # A coadd converted from a larger CoaddInputs (e.g. a postage stamp cut 

1404 # from a whole-tract template) legitimately drops inputs that intersect 

1405 # its bounds nowhere, so this is subset, not equality. 

1406 assert prov_keys <= set(legacy_by_key), "Provenance inputs must be a subset of CoaddInputs ccds." 

1407 instruments = {row["instrument"] for row in inputs} 

1408 assert len(instruments) == 1, "A coadd's inputs must all share one instrument." 

1409 for row in inputs: 

1410 legacy_row = legacy_by_key[(row["visit"], row["detector"])] 

1411 assert row["physical_filter"] == legacy_row["filter"] 

1412 assert row["polygon"].area > 0 

1413 # Group contribution rows by input, checking weights are carried over 

1414 # exactly, and then group them by cell for the geometric checks below. 

1415 contributions_by_input: dict[tuple[int, int], list[Any]] = {} 

1416 contributions_by_cell: dict[CellIJ, list[Any]] = {} 

1417 for row in provenance.contributions: 

1418 key = (row["visit"], row["detector"]) 

1419 assert key in prov_keys 

1420 contributions_by_input.setdefault(key, []).append(row) 

1421 contributions_by_cell.setdefault(CellIJ(i=row["cell_i"], j=row["cell_j"]), []).append(row) 

1422 for key, rows in contributions_by_input.items(): 

1423 assert rows, f"Input (visit={key[0]}, detector={key[1]}) must contribute somewhere." 

1424 assert_values_equal( 

1425 np.array([row["weight"] for row in rows]), 

1426 np.full(len(rows), legacy_by_key[key]["weight"]), 

1427 rtol=1e-12, 

1428 label="contributions[weight]", 

1429 ) 

1430 overlap = np.asarray(provenance.contributions["overlap_fraction"], dtype=np.float64) 

1431 assert np.all((overlap > 0.0) & (overlap <= 1.0)), "Overlap fractions must be valid cell fractions." 

1432 assert set(contributions_by_cell) <= set(bounds.cell_indices()), ( 

1433 "Contributions must be on non-missing cells." 

1434 ) 

1435 for cell, rows in contributions_by_cell.items(): 

1436 bbox = bounds.grid.bbox_of(cell) 

1437 overlapping = { 

1438 (row["visit"], row["ccd"]) 

1439 for row in coadd_inputs.ccds.subsetContaining( 

1440 bbox.center.to_legacy_float_point(), wcs, includeValidPolygon=True 

1441 ) 

1442 } 

1443 keys = {(row["visit"], row["detector"]) for row in rows} 

1444 assert overlapping <= keys, "Inputs overlapping a cell center must contribute to that cell." 

1445 centered = {(row["visit"], row["detector"]) for row in rows if row["overlaps_center"]} 

1446 assert centered == overlapping, "overlaps_center must match which inputs cover the cell center." 

1447 

1448 

1449def compare_psf_to_legacy( 

1450 psf: PointSpreadFunction, 

1451 legacy_psf: Any, 

1452 points: YX[np.ndarray] | XY[np.ndarray] | None = None, 

1453 expect_legacy_raise_on_out_of_bounds: bool = False, 

1454 *, 

1455 rtol: float = 0.0, 

1456 atol: float = 0.0, 

1457) -> int: 

1458 """Compare a PSF model object to its legacy interface. 

1459 

1460 Parameters 

1461 ---------- 

1462 psf 

1463 Point-spread function to test. 

1464 legacy_psf 

1465 Legacy `lsst.afw.detection.Psf` instance to compare with. 

1466 points 

1467 Points to evaluate the PSFs at. If not provided, the intersection of 

1468 the PSF bounding boxes are used to generate points on a grid. 

1469 expect_legacy_raise_on_out_of_bounds 

1470 If `True`, expect ``legacy_psf`` to raise 

1471 `lsst.afw.detection.InvalidPsfError` when evaluated at a position 

1472 considered out-of-bounds by ``psf``. 

1473 rtol 

1474 Relative tolerance for kernel and stellar image pixel values. 

1475 The default of zero (with ``atol`` also zero) requires exact 

1476 equality, appropriate when both PSFs were converted from the same 

1477 representation. Nonzero values are for comparing approximations, 

1478 such as cell-based evaluations of a spatially varying legacy PSF. 

1479 atol 

1480 Absolute tolerance for kernel and stellar image pixel values. 

1481 

1482 Returns 

1483 ------- 

1484 `int` 

1485 The number of points actually tested. 

1486 """ 

1487 from lsst.afw.detection import InvalidPsfError 

1488 

1489 approximate = rtol != 0.0 or atol != 0.0 

1490 if points is None: 1490 ↛ 1492line 1490 didn't jump to line 1492 because the condition on line 1490 was always true

1491 points = psf.bounds.bbox.meshgrid(n=3).map(np.ravel) 

1492 legacy_points = arrays_to_legacy_points(points.x, points.y) 

1493 n_points_tested: int = 0 

1494 for p in legacy_points: 

1495 if not psf.bounds.contains(x=p.x, y=p.y): 1495 ↛ 1496line 1495 didn't jump to line 1496 because the condition on line 1495 was never true

1496 if expect_legacy_raise_on_out_of_bounds: 

1497 with pytest.raises(InvalidPsfError): 

1498 legacy_psf.computeKernelImage(p) 

1499 continue 

1500 try: 

1501 legacy_kernel = Image.from_legacy(legacy_psf.computeKernelImage(p)) 

1502 except InvalidPsfError: 

1503 if not approximate: 

1504 raise 

1505 # An approximate conversion samples a cell's corners when the 

1506 # legacy PSF cannot be evaluated at its center, so there is 

1507 # nothing to compare at this point. 

1508 continue 

1509 legacy_kernel_bbox = Box.from_legacy(legacy_psf.computeKernelBBox(p)) 

1510 legacy_stellar_bbox = Box.from_legacy(legacy_psf.computeImageBBox(p)) 

1511 legacy_stellar = Image.from_legacy(legacy_psf.computeImage(p)) 

1512 kernel = psf.compute_kernel_image(x=p.x, y=p.y) 

1513 stellar_bbox = psf.compute_stellar_bbox(x=p.x, y=p.y) 

1514 stellar = psf.compute_stellar_image(x=p.x, y=p.y) 

1515 if approximate: 1515 ↛ 1522line 1515 didn't jump to line 1522 because the condition on line 1515 was never true

1516 # An approximate conversion stores every cell's stamp in one 

1517 # kernel bbox large enough for the legacy kernel at every sampled 

1518 # point, so the legacy kernel must match the stamp's sub-box and 

1519 # the rest of the stamp must be empty. Resampling the stamp into 

1520 # the stellar image spreads flux into that padding, so only the 

1521 # sub-box is comparable there. 

1522 assert psf.kernel_bbox.contains(legacy_kernel_bbox) 

1523 expected_kernel = Image(0.0, bbox=kernel.bbox, dtype=np.float64) 

1524 expected_kernel[legacy_kernel.bbox] = legacy_kernel 

1525 with annotate_errors("psf kernel image"): 

1526 assert_images_equal(kernel, expected_kernel, rtol=rtol, atol=atol) 

1527 assert stellar_bbox.contains(legacy_stellar_bbox) 

1528 with annotate_errors("psf stellar image"): 

1529 assert_images_equal(stellar[legacy_stellar.bbox], legacy_stellar, rtol=rtol, atol=atol) 

1530 else: 

1531 assert psf.kernel_bbox == legacy_kernel_bbox 

1532 assert kernel == legacy_kernel 

1533 assert stellar_bbox == legacy_stellar_bbox 

1534 assert stellar == legacy_stellar 

1535 n_points_tested += 1 

1536 return n_points_tested 

1537 

1538 

1539def compare_field_to_legacy( 

1540 field: BaseField, 

1541 legacy_field: Any, 

1542 subimage_bbox: Box, 

1543 eval_points: XY[np.ndarray] | YX[np.ndarray] | None = None, 

1544 expect_subset_bounds: bool = False, 

1545 *, 

1546 rtol: float = 1e-5, 

1547) -> None: 

1548 """Test a Field object by comparing it to an equivalent 

1549 `lsst.afw.math.BoundedField`. 

1550 

1551 Parameters 

1552 ---------- 

1553 field 

1554 Field to test. 

1555 legacy_field : ``lsst.afw.math.BoundedField`` 

1556 Equivalent legacy bounded field. 

1557 subimage_bbox 

1558 Bounding box for full-image tests. 

1559 eval_points 

1560 Points at which to compare field values, instead of testing over a 

1561 grid covering ``field.bounds``. This also disables image-rendering 

1562 comparison checks. 

1563 expect_subset_bounds 

1564 If `True`, expect ``field.bounds`` to be contained by 

1565 ``legacy_field.getBBox()``, not equal to it. 

1566 rtol 

1567 Relative tolerance for the evaluation-point field-value comparison. 

1568 """ 

1569 from lsst.afw.math import BoundedField as LegacyBoundedField 

1570 

1571 if expect_subset_bounds: 1571 ↛ 1572line 1571 didn't jump to line 1572 because the condition on line 1571 was never true

1572 assert Box.from_legacy(legacy_field.getBBox()).contains(field.bounds.bbox) 

1573 else: 

1574 assert field.bounds.bbox == Box.from_legacy(legacy_field.getBBox()) 

1575 if eval_points is not None: 1575 ↛ 1576line 1575 didn't jump to line 1576 because the condition on line 1575 was never true

1576 pixel_xy = eval_points.map(np.ravel) 

1577 else: 

1578 pixel_xy = field.bounds.bbox.meshgrid(n=5).map(np.ravel) 

1579 if not isinstance(field.bounds, Box): 

1580 mask = field.bounds.contains(x=pixel_xy.x, y=pixel_xy.y) 

1581 pixel_xy = pixel_xy.map(lambda v: v[mask]) 

1582 try: 

1583 assert_values_equal( 

1584 field(x=pixel_xy.x, y=pixel_xy.y), 

1585 legacy_field.evaluate(pixel_xy.x, pixel_xy.y), 

1586 # The field coefficients come from a numerical fit, so this can 

1587 # be bigger than just round-off error epsilon. 

1588 rtol=rtol, 

1589 ) 

1590 except AssertionError as err: 

1591 err.add_note(f"evaluated at {pixel_xy}") 

1592 raise 

1593 if not isinstance(legacy_field, LegacyBoundedField): 

1594 # Legacy StitchedApertureCorrection objects are not true BoundedFields 

1595 # and don't have addToImage. 

1596 return 

1597 if eval_points is not None: 1597 ↛ 1598line 1597 didn't jump to line 1598 because the condition on line 1597 was never true

1598 return 

1599 legacy_image_1 = Image(0, bbox=subimage_bbox, dtype=np.float64).to_legacy() 

1600 legacy_field.addToImage(legacy_image_1, overlapOnly=True) 

1601 assert_images_equal( 

1602 field.render(subimage_bbox), Image.from_legacy(legacy_image_1, unit=field.unit), rtol=1e-13 

1603 ) 

1604 

1605 

1606def compare_aperture_corrections_to_legacy( 

1607 aperture_corrections: Mapping[str, BaseField | None], 

1608 legacy_ap_corr_map: Any, 

1609 subimage_bbox: Box, 

1610 *, 

1611 eval_points: XY[np.ndarray] | YX[np.ndarray] | None = None, 

1612 expect_subset_bounds: bool = False, 

1613 rtol: float = 1e-5, 

1614) -> None: 

1615 """Test an aperture correction `dict` by comparing it to an equivalent 

1616 `lsst.afw.image.ApCorrMap`. 

1617 

1618 Parameters 

1619 ---------- 

1620 aperture_corrections 

1621 Dictionary to test. A name that maps to `None` is expected to have no 

1622 usable value anywhere in the equivalent legacy field. 

1623 legacy_ap_corr_map : ``lsst.afw.image.ApCorrMap`` 

1624 Equivalent legacy aperture correction map. 

1625 subimage_bbox 

1626 Bounding box for full-image tests. 

1627 eval_points 

1628 Points at which to compare field values, forwarded to 

1629 `compare_field_to_legacy`. This also disables image-rendering 

1630 comparison checks. 

1631 expect_subset_bounds 

1632 If `True`, expect ``field.bounds`` to be contained by 

1633 ``legacy_field.getBBox()``, not equal to it. 

1634 rtol 

1635 Relative tolerance for the evaluation-point field-value comparison, 

1636 forwarded to `compare_field_to_legacy`. 

1637 """ 

1638 from lsst.pex.exceptions import DomainError 

1639 

1640 assert aperture_corrections.keys() == set(legacy_ap_corr_map.keys()) 

1641 for name, field in aperture_corrections.items(): 

1642 legacy_field = legacy_ap_corr_map[name] 

1643 if field is None: 

1644 points = Box.from_legacy(legacy_field.getBBox()).meshgrid(n=3).map(np.ravel) 

1645 for p in arrays_to_legacy_points(points.x, points.y): 

1646 try: 

1647 value = legacy_field.evaluate(p) 

1648 except DomainError: 

1649 continue 

1650 assert not np.isfinite(value), f"Aperture correction {name} is unusable but not in legacy" 

1651 continue 

1652 compare_field_to_legacy( 

1653 field, 

1654 legacy_field, 

1655 subimage_bbox, 

1656 eval_points=eval_points, 

1657 expect_subset_bounds=expect_subset_bounds, 

1658 rtol=rtol, 

1659 ) 

1660 

1661 

1662def compare_observation_summary_stats_to_legacy( 

1663 summary_stats: ObservationSummaryStats, 

1664 legacy_summary_stats: Any, 

1665) -> None: 

1666 """Test an ObservationSummaryStats object by comparing it to an equivalent 

1667 `lsst.afw.image.ExposureSummaryStats`. 

1668 

1669 Parameters 

1670 ---------- 

1671 summary_stats 

1672 Struct to test. 

1673 legacy_summary_stats : ``lsst.afw.image.ExposureSummaryStats`` 

1674 Equivalent legacy struct. 

1675 """ 

1676 for field in dataclasses.fields(legacy_summary_stats): 

1677 # Always skip version since that field has no meaning in the new 

1678 # type. 

1679 if field.name == "version": 

1680 continue 

1681 a = getattr(legacy_summary_stats, field.name) 

1682 b = getattr(summary_stats, field.name) 

1683 assert_values_equal(a, b, label=field.name) 

1684 

1685 

1686def compare_sky_projection_to_legacy_wcs[F: Frame]( 

1687 sky_projection: SkyProjection[F], 

1688 legacy_wcs: Any, 

1689 pixel_frame: F, 

1690 subimage_bbox: Box, 

1691 is_fits: bool = False, 

1692) -> None: 

1693 """Test a Projection object by comparing it to an equivalent 

1694 `lsst.afw.geom.SkyWcs`. 

1695 

1696 Parameters 

1697 ---------- 

1698 sky_projection 

1699 Projection to test. 

1700 legacy_wcs : ``lsst.afw.geom.SkyWcs`` 

1701 Equivalent legacy WCS. 

1702 pixel_frame 

1703 Expected pixel frame for the sky_projection. 

1704 subimage_bbox 

1705 Bounding box of points to generate for tests. 

1706 is_fits 

1707 Whether this sky_projection is expected to be exactly representable as 

1708 a FITS WCS. If `False` it is assumed to have a FITS approximation 

1709 attached instead. 

1710 """ 

1711 # Pixel coordinates to test on over the subimage region of interest: 

1712 pixel_xy = subimage_bbox.meshgrid(step=50).map(np.ravel) 

1713 # Array indices of those pixel values (subtract off bbox starts): 

1714 subimage_array_xy = XY(x=pixel_xy.x - subimage_bbox.x.start, y=pixel_xy.y - subimage_bbox.y.start) 

1715 sky_coords = legacy_coords_to_astropy( 

1716 legacy_wcs.pixelToSky(arrays_to_legacy_points(pixel_xy.x, pixel_xy.y)) 

1717 ) 

1718 # Test transforming with the Projection itself, which also tests its 

1719 # nested Transform and an Astropy High-Level WCS view with no origin 

1720 # change. 

1721 check_projection(sky_projection, pixel_xy, sky_coords, pixel_frame, pixel_atol=_AST_INV_ATOL) 

1722 # Also test the Astropy High-Level WCS view with an origin change to 

1723 # array indices. 

1724 check_astropy_wcs_interface( 

1725 sky_projection.as_astropy(subimage_bbox), subimage_array_xy, sky_coords, pixel_atol=1e-5 

1726 ) 

1727 if is_fits: 1727 ↛ 1746line 1727 didn't jump to line 1746 because the condition on line 1727 was always true

1728 fits_wcs = sky_projection.as_fits_wcs(subimage_bbox, allow_approximation=True) 

1729 assert fits_wcs is not None 

1730 check_astropy_wcs_interface(fits_wcs, subimage_array_xy, sky_coords, pixel_atol=1e-5) 

1731 # Use that FITS approximation to check that we can make a 

1732 # Projection from a FITS WCS, too. 

1733 fits_projection = SkyProjection.from_fits_wcs(fits_wcs, pixel_frame) 

1734 check_projection( 

1735 fits_projection, 

1736 subimage_array_xy, 

1737 sky_coords, 

1738 pixel_frame, 

1739 pixel_atol=1e-5, 

1740 ) 

1741 # We want Projections we create from a FITS WCS to be backed by an 

1742 # AST FrameSet so we can convert them into legacy 

1743 # `lsst.afw.geom.SkyWcs` objects if desired. 

1744 assert "Begin FrameSet" in fits_projection.show() 

1745 else: 

1746 assert sky_projection.as_fits_wcs(subimage_bbox, allow_approximation=False) is None 

1747 # The legacy SkyWcs should instead have a FITS approximation 

1748 # attached; run the same tests on that. 

1749 assert sky_projection.fits_approximation is not None 

1750 compare_sky_projection_to_legacy_wcs( 

1751 sky_projection.fits_approximation, 

1752 legacy_wcs.getFitsApproximation(), 

1753 pixel_frame, 

1754 subimage_bbox, 

1755 is_fits=True, 

1756 ) 

1757 

1758 

1759def check_transform[I: Frame, O: Frame]( 

1760 transform: Transform[I, O], 

1761 input_xy: XY[np.ndarray], 

1762 output_xy: XY[np.ndarray], 

1763 in_frame: Frame, 

1764 out_frame: Frame, 

1765 *, 

1766 check_inverted: bool = True, 

1767 in_atol: u.Quantity | float | None = None, 

1768 out_atol: u.Quantity | float | None = None, 

1769 angle_wrapped: bool = False, 

1770) -> None: 

1771 """Test Transform against known arrays of input and output points. 

1772 

1773 Parameters 

1774 ---------- 

1775 transform 

1776 Transform to test. 

1777 input_xy 

1778 Arrays of input points. 

1779 output_xy 

1780 Arrays of output points. 

1781 in_frame 

1782 Expected input frame. 

1783 out_frame 

1784 Expected output frame. 

1785 check_inverted 

1786 If `True`, recurse (once) to test the inverse transform. 

1787 in_atol 

1788 Expected absolute precision of input points. 

1789 out_atol 

1790 Expected absolute precision of output points. 

1791 angle_wrapped 

1792 If `True`, treat comparisons on sky-coordinate axes (as determined 

1793 by the frames) as angles modulo 2 pi, so differences that cross 

1794 zero or 360 degrees compare correctly. 

1795 """ 

1796 assert transform.in_frame == in_frame 

1797 assert transform.out_frame == out_frame 

1798 in_atol = 0.0 if in_atol is None else in_atol 

1799 out_atol = 0.0 if out_atol is None else out_atol 

1800 in_atol_v = in_atol.to_value(in_frame.unit) if isinstance(in_atol, u.Quantity) else float(in_atol) 

1801 out_atol_v = out_atol.to_value(out_frame.unit) if isinstance(out_atol, u.Quantity) else float(out_atol) 

1802 out_wrapped = angle_wrapped and out_frame == SkyFrame.ICRS 

1803 in_wrapped = angle_wrapped and in_frame == SkyFrame.ICRS 

1804 

1805 def assert_close( 

1806 test: np.ndarray | float | u.Quantity, 

1807 expected: np.ndarray | float | u.Quantity, 

1808 atol: float | u.Quantity, 

1809 *, 

1810 wrapped: bool, 

1811 ) -> None: 

1812 """Compare one axis, wrap-aware if that axis is a sky angle. 

1813 

1814 Parameters 

1815 ---------- 

1816 test 

1817 Values to test. 

1818 expected 

1819 Expected values. 

1820 atol 

1821 Absolute tolerance, in the units the values are expressed in. 

1822 wrapped 

1823 If `True`, treat the values as angles modulo 2 pi (radians). 

1824 """ 

1825 if not wrapped: 

1826 assert_values_equal(test, expected, atol=atol, rtol=_AST_RTOL) 

1827 return 

1828 test_values = np.asarray(getattr(test, "value", test)) 

1829 expected_values = np.asarray(getattr(expected, "value", expected)) 

1830 atol_rad = atol.to_value(u.rad) if isinstance(atol, u.Quantity) else float(atol) 

1831 assert_values_equal( 

1832 test_values * u.rad, 

1833 expected_values * u.rad, 

1834 atol=atol_rad * u.rad, 

1835 equal_nan=False, 

1836 wrap_angles=True, 

1837 ) 

1838 

1839 # Test array interfaces. 

1840 test_output_xy = transform.apply_forward(x=input_xy.x, y=input_xy.y) 

1841 assert_close(test_output_xy.x, output_xy.x, out_atol_v, wrapped=out_wrapped) 

1842 assert_close(test_output_xy.y, output_xy.y, out_atol_v, wrapped=out_wrapped) 

1843 test_input_xy = transform.apply_inverse(x=output_xy.x, y=output_xy.y) 

1844 assert_close(test_input_xy.x, input_xy.x, in_atol_v, wrapped=in_wrapped) 

1845 assert_close(test_input_xy.y, input_xy.y, in_atol_v, wrapped=in_wrapped) 

1846 # Test scalar interfaces with numpy scalars. 

1847 for input_x, input_y, output_x, output_y in zip(input_xy.x, input_xy.y, output_xy.x, output_xy.y): 

1848 forward_xy = transform.apply_forward(x=input_x, y=input_y) 

1849 assert_close(forward_xy.x, output_x, out_atol_v, wrapped=out_wrapped) 

1850 assert_close(forward_xy.y, output_y, out_atol_v, wrapped=out_wrapped) 

1851 inverse_xy = transform.apply_inverse(x=output_x, y=output_y) 

1852 assert_close(inverse_xy.x, input_x, in_atol_v, wrapped=in_wrapped) 

1853 assert_close(inverse_xy.y, input_y, in_atol_v, wrapped=in_wrapped) 

1854 # Test quantity array interfaces. 

1855 input_q_xy = XY(x=input_xy.x * transform.in_frame.unit, y=input_xy.y * transform.in_frame.unit) 

1856 output_q_xy = XY(x=output_xy.x * transform.out_frame.unit, y=output_xy.y * transform.out_frame.unit) 

1857 test_output_q_xy = transform.apply_forward_q(x=input_q_xy.x, y=input_q_xy.y) 

1858 assert_close(test_output_q_xy.x, output_q_xy.x, out_atol, wrapped=out_wrapped) 

1859 assert_close(test_output_q_xy.y, output_q_xy.y, out_atol, wrapped=out_wrapped) 

1860 test_input_q_xy = transform.apply_inverse_q(x=output_q_xy.x, y=output_q_xy.y) 

1861 assert_close(test_input_q_xy.x, input_q_xy.x, in_atol, wrapped=in_wrapped) 

1862 assert_close(test_input_q_xy.y, input_q_xy.y, in_atol, wrapped=in_wrapped) 

1863 # Test quantity scalar interfaces. 

1864 for input_q_x, input_q_y, output_q_x, output_q_y in zip( 

1865 input_q_xy.x, input_q_xy.y, output_q_xy.x, output_q_xy.y 

1866 ): 

1867 forward_q_xy = transform.apply_forward_q(x=input_q_x, y=input_q_y) 

1868 assert_close(forward_q_xy.x, output_q_x, out_atol, wrapped=out_wrapped) 

1869 assert_close(forward_q_xy.y, output_q_y, out_atol, wrapped=out_wrapped) 

1870 inverse_q_xy = transform.apply_inverse_q(x=output_q_x, y=output_q_y) 

1871 assert_close(inverse_q_xy.x, input_q_x, in_atol, wrapped=in_wrapped) 

1872 assert_close(inverse_q_xy.y, input_q_y, in_atol, wrapped=in_wrapped) 

1873 if check_inverted: 

1874 # Test the inverse transform. 

1875 check_transform( 

1876 transform.inverted(), 

1877 output_xy, 

1878 input_xy, 

1879 out_frame, 

1880 in_frame, 

1881 check_inverted=False, 

1882 out_atol=in_atol, 

1883 in_atol=out_atol, 

1884 angle_wrapped=angle_wrapped, 

1885 ) 

1886 

1887 

1888def check_projection[P: Frame]( 

1889 sky_projection: SkyProjection[P], 

1890 pixel_xy: XY[np.ndarray], 

1891 sky_coords: SkyCoord, 

1892 pixel_frame: Frame, 

1893 *, 

1894 pixel_atol: float | None = None, 

1895 sky_atol: u.Quantity | None = None, 

1896) -> None: 

1897 """Test a `.SkyProjection` instance against known arrays of pixel and sky 

1898 coordinates. 

1899 

1900 Parameters 

1901 ---------- 

1902 sky_projection 

1903 Projection to test. 

1904 pixel_xy 

1905 Arrays of pixel coordinates. 

1906 sky_coords 

1907 Corresponding sky coordinates. 

1908 pixel_frame 

1909 Expected pixel frame. 

1910 pixel_atol 

1911 Expected absolute precision of pixel points. 

1912 sky_atol 

1913 Expected absolute precision of sky coordinates, as a maximum 

1914 great-circle separation. 

1915 """ 

1916 assert sky_projection.pixel_frame == pixel_frame 

1917 assert sky_projection.sky_frame == SkyFrame.ICRS 

1918 sky_atol = _AST_SKY_ATOL if sky_atol is None else u.Quantity(sky_atol) 

1919 pixel_atol = 0.0 if pixel_atol is None else pixel_atol 

1920 pixel_atol_q = pixel_atol * u.pix 

1921 # Test array interfaces. 

1922 test_pixel_xy = cast(XY[np.ndarray], sky_projection.sky_to_pixel(sky_coords)) 

1923 assert_values_equal(test_pixel_xy.x, pixel_xy.x, atol=pixel_atol, rtol=_AST_RTOL) 

1924 assert_values_equal(test_pixel_xy.y, pixel_xy.y, atol=pixel_atol, rtol=_AST_RTOL) 

1925 test_sky_astropy = sky_projection.pixel_to_sky(x=pixel_xy.x, y=pixel_xy.y) 

1926 assert_values_equal(test_sky_astropy, sky_coords, atol=sky_atol, label="pixel_to_sky") 

1927 # Test scalar interfaces. 

1928 for pixel_x, pixel_y, sky_single in zip(pixel_xy.x, pixel_xy.y, sky_coords): 

1929 assert_values_equal( 

1930 sky_projection.sky_to_pixel(sky_single).x, pixel_x, atol=pixel_atol, rtol=_AST_RTOL 

1931 ) 

1932 assert_values_equal( 

1933 sky_projection.sky_to_pixel(sky_single).y, pixel_y, atol=pixel_atol, rtol=_AST_RTOL 

1934 ) 

1935 test_sky_single = sky_projection.pixel_to_sky(x=pixel_x, y=pixel_y) 

1936 assert_values_equal(test_sky_single, sky_single, atol=sky_atol, label="pixel_to_sky") 

1937 # Test the underlying Transform object. 

1938 sky_xy = XY(x=sky_coords.ra.to_value(u.rad), y=sky_coords.dec.to_value(u.rad)) 

1939 check_transform( 

1940 sky_projection.pixel_to_sky_transform, 

1941 pixel_xy, 

1942 sky_xy, 

1943 pixel_frame, 

1944 SkyFrame.ICRS, 

1945 check_inverted=False, 

1946 in_atol=pixel_atol_q, 

1947 out_atol=sky_atol, 

1948 angle_wrapped=True, 

1949 ) 

1950 check_transform( 

1951 sky_projection.sky_to_pixel_transform, 

1952 sky_xy, 

1953 pixel_xy, 

1954 SkyFrame.ICRS, 

1955 pixel_frame, 

1956 check_inverted=False, 

1957 in_atol=sky_atol, 

1958 out_atol=pixel_atol_q, 

1959 angle_wrapped=True, 

1960 ) 

1961 # Test the Astropy interface adapter. 

1962 check_astropy_wcs_interface( 

1963 sky_projection.as_astropy(), pixel_xy, sky_coords, pixel_atol=pixel_atol, sky_atol=sky_atol 

1964 ) 

1965 

1966 

1967def assert_sky_projections_equal( 

1968 a: SkyProjection[Any] | None, 

1969 b: SkyProjection[Any] | None, 

1970 expect_identity: bool | None = None, 

1971) -> None: 

1972 """Test that two `.SkyProjection` instances are equivalent. 

1973 

1974 Parameters 

1975 ---------- 

1976 a 

1977 First sky projection to compare. 

1978 b 

1979 Second sky projection to compare. 

1980 expect_identity 

1981 If not `None`, assert whether ``a`` and ``b`` are the same object. 

1982 """ 

1983 if a is None and b is None: 

1984 return 

1985 assert a is not None 

1986 assert b is not None 

1987 match expect_identity: 

1988 case True: 1988 ↛ 1989line 1988 didn't jump to line 1989 because the pattern on line 1988 never matched

1989 assert a is b 

1990 return 

1991 case False: 

1992 assert a is not b 

1993 case None if a is b: 

1994 return 

1995 assert a == b 

1996 

1997 

1998def check_astropy_wcs_interface( 

1999 wcs: astropy.wcs.wcsapi.BaseHighLevelWCS, 

2000 pixel_xy: XY[np.ndarray], 

2001 sky_coords: SkyCoord, 

2002 *, 

2003 pixel_atol: float | None = None, 

2004 sky_atol: u.Quantity | None = None, 

2005) -> None: 

2006 """Test an Astropy WCS instance against known arrays of pixel and 

2007 sky coordinates. 

2008 

2009 Parameters 

2010 ---------- 

2011 wcs 

2012 Astropy WCS object to test. 

2013 pixel_xy 

2014 Arrays of pixel coordinates. 

2015 sky_coords 

2016 Corresponding sky coordinates. 

2017 pixel_atol 

2018 Expected absolute precision of pixel points. 

2019 sky_atol 

2020 Expected absolute precision of sky coordinates, as a maximum 

2021 great-circle separation. 

2022 """ 

2023 pixel_atol = 0.0 if pixel_atol is None else pixel_atol 

2024 sky_atol = _AST_SKY_ATOL if sky_atol is None else u.Quantity(sky_atol) 

2025 test_x, test_y = wcs.world_to_pixel(sky_coords) 

2026 assert_values_equal(test_x, pixel_xy.x, atol=pixel_atol, rtol=_AST_RTOL) 

2027 assert_values_equal(test_y, pixel_xy.y, atol=pixel_atol, rtol=_AST_RTOL) 

2028 test_sky_coords = wcs.pixel_to_world(pixel_xy.x, pixel_xy.y) 

2029 assert_values_equal(test_sky_coords, sky_coords, atol=sky_atol, label="pixel_to_world") 

2030 

2031 

2032def legacy_points_to_xy_array(legacy_points: list[Any]) -> XY[np.ndarray]: 

2033 """Convert a list of ``lsst.geom.Point2D`` objects to an `.XY` array. 

2034 

2035 Parameters 

2036 ---------- 

2037 legacy_points 

2038 Legacy ``lsst.geom.Point2D`` objects to convert. 

2039 """ 

2040 return XY(x=np.array([p.x for p in legacy_points]), y=np.array([p.y for p in legacy_points])) 

2041 

2042 

2043def legacy_coords_to_astropy(legacy_coords: list[Any]) -> SkyCoord: 

2044 """Convert a list of ``lsst.geom.SpherePoint`` objects to an Astropy 

2045 coordinate object. 

2046 

2047 Parameters 

2048 ---------- 

2049 legacy_coords 

2050 Legacy ``lsst.geom.SpherePoint`` objects to convert. 

2051 """ 

2052 return SkyCoord( 

2053 ra=np.array([p.getRa().asRadians() for p in legacy_coords]) * u.rad, 

2054 dec=np.array([p.getDec().asRadians() for p in legacy_coords]) * u.rad, 

2055 ) 

2056 

2057 

2058def arrays_to_legacy_points(x: np.ndarray, y: np.ndarray) -> list[Any]: 

2059 """Convert arrays of ``x`` and ``y`` to a list of ``lsst.geom.Point2D``. 

2060 

2061 Parameters 

2062 ---------- 

2063 x 

2064 X coordinates of the points. 

2065 y 

2066 Y coordinates of the points. 

2067 """ 

2068 from lsst.geom import Point2D 

2069 

2070 return [Point2D(x=xv, y=yv) for xv, yv in zip(x, y)] 

2071 

2072 

2073def compare_amplifier_to_legacy( 

2074 amplifier: Amplifier, 

2075 legacy_amplifier: Any, 

2076 *, 

2077 is_raw_assembled: bool, 

2078 expect_nominal_calibrations: bool = True, 

2079) -> None: 

2080 """Compare an `~.cameras.Amplifier` to a legacy 

2081 `lsst.afw.cameraGeom.Amplifier`. 

2082 

2083 Parameters 

2084 ---------- 

2085 amplifier 

2086 Amplifier to compare. 

2087 legacy_amplifier 

2088 Legacy `lsst.afw.cameraGeom.Amplifier` to compare against. 

2089 is_raw_assembled 

2090 Whether the raw geometry is expected to be the assembled-raw 

2091 geometry (`True`) or the unassembled-raw geometry (`False`). 

2092 expect_nominal_calibrations 

2093 Whether the amplifier is expected to carry nominal calibrations. 

2094 """ 

2095 assert legacy_amplifier.getName() == amplifier.name 

2096 assert Box.from_legacy(legacy_amplifier.getBBox()) == amplifier.bbox 

2097 if is_raw_assembled: 2097 ↛ 2100line 2097 didn't jump to line 2100 because the condition on line 2097 was always true

2098 raw_geom = amplifier.assembled_raw_geometry 

2099 else: 

2100 raw_geom = amplifier.unassembled_raw_geometry 

2101 assert raw_geom is not None 

2102 assert ReadoutCorner.from_legacy(legacy_amplifier.getReadoutCorner()) == raw_geom.readout_corner 

2103 assert Box.from_legacy(legacy_amplifier.getRawBBox()) == raw_geom.bbox 

2104 assert Box.from_legacy(legacy_amplifier.getRawDataBBox()) == raw_geom.data_bbox 

2105 assert legacy_amplifier.getRawFlipX() == raw_geom.flip_x 

2106 assert legacy_amplifier.getRawFlipY() == raw_geom.flip_y 

2107 assert legacy_amplifier.getRawXYOffset().getX() == raw_geom.x_offset 

2108 assert legacy_amplifier.getRawXYOffset().getY() == raw_geom.y_offset 

2109 assert ( 

2110 Box.from_legacy(legacy_amplifier.getRawHorizontalOverscanBBox()) == raw_geom.horizontal_overscan_bbox 

2111 ) 

2112 assert Box.from_legacy(legacy_amplifier.getRawVerticalOverscanBBox()) == raw_geom.vertical_overscan_bbox 

2113 if raw_geom.horizontal_prescan_bbox is None: 

2114 # `Box` requires a positive size, so an amplifier with no prescan 

2115 # region carries `None` here. 

2116 assert legacy_amplifier.getRawPrescanBBox().isEmpty() 

2117 else: 

2118 assert Box.from_legacy(legacy_amplifier.getRawPrescanBBox()) == raw_geom.horizontal_prescan_bbox 

2119 if expect_nominal_calibrations: 2119 ↛ exitline 2119 didn't return from function 'compare_amplifier_to_legacy' because the condition on line 2119 was always true

2120 assert amplifier.nominal_calibrations is not None 

2121 assert_values_equal( 

2122 legacy_amplifier.getGain(), 

2123 amplifier.nominal_calibrations.gain, 

2124 equal_nan=True, 

2125 label="gain", 

2126 ) 

2127 assert_values_equal( 

2128 legacy_amplifier.getReadNoise(), 

2129 amplifier.nominal_calibrations.read_noise, 

2130 equal_nan=True, 

2131 label="read_noise", 

2132 ) 

2133 assert_values_equal( 

2134 legacy_amplifier.getSaturation(), 

2135 amplifier.nominal_calibrations.saturation, 

2136 equal_nan=True, 

2137 label="saturation", 

2138 ) 

2139 assert_values_equal( 

2140 legacy_amplifier.getSuspectLevel(), 

2141 amplifier.nominal_calibrations.suspect_level, 

2142 equal_nan=True, 

2143 label="suspect_level", 

2144 ) 

2145 assert_values_equal( 

2146 legacy_amplifier.getLinearityCoeffs(), 

2147 amplifier.nominal_calibrations.linearity_coefficients, 

2148 label="linearity_coefficients", 

2149 ) 

2150 assert legacy_amplifier.getLinearityType() == amplifier.nominal_calibrations.linearity_type 

2151 

2152 

2153def compare_detector_to_legacy( 

2154 detector: Detector, 

2155 legacy_detector: Any, 

2156 *, 

2157 is_raw_assembled: bool, 

2158 expect_nominal_calibrations: bool = True, 

2159) -> None: 

2160 """Compare a `~.cameras.Detector` to a `lsst.afw.cameraGeom.Detector`. 

2161 

2162 Parameters 

2163 ---------- 

2164 detector 

2165 Detector to compare. 

2166 legacy_detector 

2167 Legacy `lsst.afw.cameraGeom.Detector` to compare against. 

2168 is_raw_assembled 

2169 Whether the raw geometry is expected to be the assembled-raw 

2170 geometry (`True`) or the unassembled-raw geometry (`False`). 

2171 expect_nominal_calibrations 

2172 Whether the detector's amplifiers are expected to carry nominal 

2173 calibrations. 

2174 """ 

2175 from lsst.afw.cameraGeom import FIELD_ANGLE, FOCAL_PLANE, PIXELS 

2176 

2177 assert legacy_detector.getName() == detector.name 

2178 assert legacy_detector.getId() == detector.id 

2179 assert DetectorType.from_legacy(legacy_detector.getType()) == detector.type 

2180 assert Box.from_legacy(legacy_detector.getBBox()) == detector.bbox 

2181 assert legacy_detector.getSerial() == detector.serial 

2182 legacy_orientation = legacy_detector.getOrientation() 

2183 assert legacy_orientation.getFpPosition3().getX() == detector.orientation.focal_plane_x 

2184 assert legacy_orientation.getFpPosition3().getY() == detector.orientation.focal_plane_y 

2185 assert legacy_orientation.getFpPosition3().getZ() == detector.orientation.focal_plane_z 

2186 assert legacy_orientation.getReferencePoint().getX() == detector.orientation.pixel_reference_x 

2187 assert legacy_orientation.getReferencePoint().getY() == detector.orientation.pixel_reference_y 

2188 assert legacy_orientation.getYaw().asRadians() == detector.orientation.yaw.to_value(u.rad) 

2189 assert legacy_orientation.getPitch().asRadians() == detector.orientation.pitch.to_value(u.rad) 

2190 assert legacy_orientation.getRoll().asRadians() == detector.orientation.roll.to_value(u.rad) 

2191 assert legacy_detector.getPixelSize().getX() == detector.pixel_size 

2192 assert legacy_detector.getPhysicalType() == detector.physical_type 

2193 for amplifier, legacy_amplifier in zip(detector.amplifiers, legacy_detector.getAmplifiers(), strict=True): 

2194 compare_amplifier_to_legacy( 

2195 amplifier, 

2196 legacy_amplifier, 

2197 is_raw_assembled=is_raw_assembled, 

2198 expect_nominal_calibrations=expect_nominal_calibrations, 

2199 ) 

2200 pixel_xy = detector.bbox.meshgrid(n=3).map(lambda z: z.ravel().astype(np.float64)) 

2201 pixel_legacy_points = arrays_to_legacy_points(y=pixel_xy.y, x=pixel_xy.x) 

2202 fp_legacy_points = legacy_detector.transform(pixel_legacy_points, PIXELS, FOCAL_PLANE) 

2203 check_transform( 

2204 detector.to_focal_plane, 

2205 pixel_xy, 

2206 legacy_points_to_xy_array(fp_legacy_points), 

2207 detector.frame, 

2208 detector.to_focal_plane.out_frame, 

2209 in_atol=1e-9 * u.pix, 

2210 out_atol=1e-7 * detector.to_focal_plane.out_frame.unit, 

2211 ) 

2212 fa_legacy_points = legacy_detector.transform(pixel_legacy_points, PIXELS, FIELD_ANGLE) 

2213 check_transform( 

2214 detector.to_field_angle, 

2215 pixel_xy, 

2216 legacy_points_to_xy_array(fa_legacy_points), 

2217 detector.frame, 

2218 detector.to_field_angle.out_frame, 

2219 in_atol=1e-9 * u.pix, 

2220 out_atol=1e-7 * u.arcsec, 

2221 ) 

2222 

2223 

2224def iter_concrete_archive_tree_subclasses() -> Iterator[type[ArchiveTree]]: 

2225 """Yield every importable concrete `.serialization.ArchiveTree` subclass. 

2226 

2227 Walks the ``ArchiveTree.__subclasses__()`` tree, skipping abstract 

2228 classes. Importing this module already imports every ``lsst.images`` 

2229 module that defines a subclass, so the tree is fully populated by the time 

2230 this is called. 

2231 

2232 This discovery is deliberately separate from 

2233 `check_archive_tree_class_invariants` so that the per-class check stays 

2234 usable on a single class even if this metaprogramming is removed later. 

2235 """ 

2236 seen: set[type] = set() 

2237 stack: list[type] = [ArchiveTree] 

2238 while stack: 

2239 kls = stack.pop() 

2240 sub: type 

2241 for sub in kls.__subclasses__(): 

2242 if sub in seen: 2242 ↛ 2243line 2242 didn't jump to line 2243 because the condition on line 2242 was never true

2243 continue 

2244 seen.add(sub) 

2245 stack.append(sub) 

2246 if not getattr(sub, "__abstractmethods__", None): 2246 ↛ 2241line 2246 didn't jump to line 2241 because the condition on line 2246 was always true

2247 yield sub 

2248 

2249 

2250def check_bounds_contains_broadcasting(bounds: Bounds) -> None: 

2251 """Verify that `~lsst.images.Bounds.contains` accepts array-like inputs. 

2252 

2253 Uses the scalar overload as the reference and checks that 1-D arrays, 

2254 list inputs, mixed scalar-plus-array inputs, 2-D broadcast inputs, and 

2255 `.XY` / `.YX` positional-argument forms all produce results consistent 

2256 with calling the scalar overload on each ``(x, y)`` pair individually. 

2257 

2258 Parameters 

2259 ---------- 

2260 bounds 

2261 The `~lsst.images.Bounds` implementation to exercise. 

2262 """ 

2263 bbox = bounds.bbox 

2264 # One point outside each boundary, one on each boundary, one in the 

2265 # interior. The boundary points (start and stop) straddle inside/outside 

2266 # (start is inside, stop is outside) so we are guaranteed a mix of True 

2267 # and False results without hard-coding expected values. 

2268 ys = np.array( 

2269 [ 

2270 bbox.y.start - 1, 

2271 bbox.y.start, 

2272 (bbox.y.start + bbox.y.stop) // 2, 

2273 bbox.y.stop, 

2274 ] 

2275 ) 

2276 xs = np.array( 

2277 [ 

2278 bbox.x.start - 1, 

2279 bbox.x.start, 

2280 (bbox.x.start + bbox.x.stop) // 2, 

2281 bbox.x.stop, 

2282 ] 

2283 ) 

2284 # 2-D reference: expected[i, j] == contains(x=xs[j], y=ys[i]). 

2285 expected = np.array( 

2286 [[bounds.contains(x=int(xi), y=int(yi)) for xi in xs] for yi in ys], 

2287 dtype=bool, 

2288 ) 

2289 # 1-D ndarray (diagonal pairs). 

2290 assert_values_equal( 

2291 bounds.contains(x=xs, y=ys), 

2292 np.diagonal(expected), 

2293 label="bounds.contains", 

2294 ) 

2295 # list inputs (array-like). 

2296 assert_values_equal( 

2297 bounds.contains(x=xs.tolist(), y=ys.tolist()), 

2298 np.diagonal(expected), 

2299 label="bounds.contains", 

2300 ) 

2301 # Mixed: scalar y, 1-D array x — produces a 1-D result. 

2302 fixed_yi = 1 # index into ys; ys[1] == bbox.y.start (on the boundary) 

2303 assert_values_equal( 

2304 bounds.contains(x=xs, y=int(ys[fixed_yi])), 

2305 expected[fixed_yi, :], 

2306 label="bounds.contains", 

2307 ) 

2308 # Mixed: 1-D array y, scalar x. 

2309 fixed_xi = 1 # index into xs; xs[1] == bbox.x.start (on the boundary) 

2310 assert_values_equal( 

2311 bounds.contains(x=int(xs[fixed_xi]), y=ys), 

2312 expected[:, fixed_xi], 

2313 label="bounds.contains", 

2314 ) 

2315 # Float scalars: results must match the int-scalar reference. 

2316 assert bounds.contains(x=float(xs[fixed_xi]), y=float(ys[fixed_yi])) == expected[fixed_yi, fixed_xi] 

2317 # XY / YX scalar: results must match the keyword-scalar reference. 

2318 assert bounds.contains(XY(x=int(xs[fixed_xi]), y=int(ys[fixed_yi]))) == expected[fixed_yi, fixed_xi] 

2319 assert bounds.contains(YX(y=int(ys[fixed_yi]), x=int(xs[fixed_xi]))) == expected[fixed_yi, fixed_xi] 

2320 # XY / YX array: results must match the 1-D ndarray reference. 

2321 assert_values_equal(bounds.contains(XY(x=xs, y=ys)), np.diagonal(expected), label="bounds.contains") 

2322 assert_values_equal(bounds.contains(YX(y=ys, x=xs)), np.diagonal(expected), label="bounds.contains") 

2323 # 2-D broadcast: y shape (N, 1) × x shape (1, M) → (N, M). 

2324 assert_values_equal( 

2325 bounds.contains(x=xs.reshape(1, -1), y=ys.reshape(-1, 1)), 

2326 expected, 

2327 label="bounds.contains", 

2328 ) 

2329 

2330 

2331def check_archive_tree_class_invariants(tree_type: type[ArchiveTree]) -> None: 

2332 """Assert that one concrete `.serialization.ArchiveTree` subclass declares 

2333 well-formed schema-version constants and an in-memory type. 

2334 

2335 Checks that ``SCHEMA_NAME``, ``SCHEMA_VERSION``, ``MIN_READ_VERSION`` and 

2336 ``PUBLIC_TYPE`` are present and well-typed, that the version is 

2337 ``major.minor.patch``, and that ``MIN_READ_VERSION`` does not exceed the 

2338 schema major. 

2339 

2340 Parameters 

2341 ---------- 

2342 tree_type 

2343 The concrete `.serialization.ArchiveTree` subclass to check. 

2344 """ 

2345 assert hasattr(tree_type, "SCHEMA_NAME"), f"{tree_type.__name__} lacks SCHEMA_NAME" 

2346 assert hasattr(tree_type, "SCHEMA_VERSION"), f"{tree_type.__name__} lacks SCHEMA_VERSION" 

2347 assert hasattr(tree_type, "MIN_READ_VERSION"), f"{tree_type.__name__} lacks MIN_READ_VERSION" 

2348 assert hasattr(tree_type, "PUBLIC_TYPE"), f"{tree_type.__name__} lacks PUBLIC_TYPE" 

2349 assert isinstance(tree_type.SCHEMA_NAME, str) 

2350 assert len(tree_type.SCHEMA_NAME) > 0 

2351 # Allow an optional PEP 440 development-release suffix (e.g. 1.0.0.dev0) 

2352 # for schemas still in development. 

2353 assert re.fullmatch(r"^\d+\.\d+\.\d+(\.dev\d+)?$", tree_type.SCHEMA_VERSION) 

2354 assert isinstance(tree_type.MIN_READ_VERSION, int) 

2355 assert tree_type.MIN_READ_VERSION >= 1 

2356 assert isinstance(tree_type.PUBLIC_TYPE, type) 

2357 major = int(tree_type.SCHEMA_VERSION.split(".")[0]) 

2358 assert tree_type.MIN_READ_VERSION <= major 

2359 

2360 

2361def _angle_to_astropy(angle: Any) -> u.Quantity: 

2362 """Convert an `lsst.geom.Angle` to an Astropy angular quantity.""" 

2363 return u.Quantity(angle.asRadians(), u.rad) 

2364 

2365 

2366def _observatory_to_location(observatory: Any) -> coords.EarthLocation: 

2367 """Convert an `lsst.afw.coord.Observatory` to an Astropy 

2368 `~astropy.coordinates.EarthLocation`. 

2369 """ 

2370 return coords.EarthLocation.from_geodetic( 

2371 lon=observatory.getLongitude().asRadians() * u.rad, 

2372 lat=observatory.getLatitude().asRadians() * u.rad, 

2373 height=observatory.getElevation() * u.m, 

2374 ) 

2375 

2376 

2377def assert_obs_metadata_fields_equal(actual: Any, expected: Any, *, label: str = "") -> None: 

2378 """Assert that two ObservationInfo or VisitInfo field values are equal. 

2379 

2380 Dispatches on the type of ``expected`` so that values affected by afw's 

2381 float64 date storage, unit conversions, and angle wrapping are compared 

2382 with appropriate tolerances; anything else is compared with ``==``. 

2383 

2384 Parameters 

2385 ---------- 

2386 actual : `object` 

2387 The field value to check. 

2388 expected : `object` 

2389 The field value to check it against. 

2390 label : `str`, optional 

2391 Prefix for the failure message. 

2392 """ 

2393 from lsst.afw.coord import Observatory, Weather 

2394 from lsst.daf.base import DateTime 

2395 from lsst.geom import Angle 

2396 

2397 if isinstance(expected, DateTime): 

2398 assert_obs_metadata_fields_equal(actual.toAstropy(), expected.toAstropy(), label=label) 

2399 elif isinstance(expected, astropy.time.Time): 

2400 # afw stores VisitInfo dates as float64 MJDs, which limits precision. 

2401 assert_values_equal(actual, expected, atol=1e-9 * u.s, label=label) 

2402 elif isinstance(expected, coords.AltAz): 

2403 assert_values_equal(actual.az, expected.az, wrap_angles=True, label=f"{label}.az") 

2404 assert_values_equal(actual.alt, expected.alt, atol=1e-3 * u.arcsec, label=f"{label}.alt") 

2405 elif isinstance(expected, coords.SkyCoord): 

2406 assert_values_equal(actual, expected, atol=1e-3 * u.arcsec, label=label) 

2407 elif isinstance(expected, coords.EarthLocation): 

2408 assert_values_equal( 

2409 u.Quantity([actual.x, actual.y, actual.z]), 

2410 u.Quantity([expected.x, expected.y, expected.z]), 

2411 rtol=1e-9, 

2412 label=label, 

2413 ) 

2414 elif isinstance(expected, Observatory): 

2415 assert_obs_metadata_fields_equal( 

2416 _observatory_to_location(actual), _observatory_to_location(expected), label=label 

2417 ) 

2418 elif isinstance(expected, Weather): 

2419 assert_obs_metadata_fields_equal( 

2420 u.Quantity(actual.getAirTemperature(), u.deg_C), 

2421 u.Quantity(expected.getAirTemperature(), u.deg_C), 

2422 label=f"{label}.temperature", 

2423 ) 

2424 assert_obs_metadata_fields_equal( 

2425 actual.getAirPressure(), expected.getAirPressure(), label=f"{label}.pressure" 

2426 ) 

2427 assert_obs_metadata_fields_equal( 

2428 actual.getHumidity(), expected.getHumidity(), label=f"{label}.humidity" 

2429 ) 

2430 elif isinstance(expected, Angle): 

2431 assert_values_equal( 

2432 _angle_to_astropy(actual), 

2433 _angle_to_astropy(expected), 

2434 atol=1e-12 * u.rad, 

2435 wrap_angles=True, 

2436 label=label, 

2437 ) 

2438 elif ( 

2439 isinstance(expected, u.Quantity) 

2440 and isinstance(actual, u.Quantity) 

2441 and expected.unit.physical_type == "temperature" 

2442 and actual.unit.physical_type == "temperature" 

2443 ): 

2444 assert_values_equal( 

2445 actual.to(u.K, equivalencies=u.temperature()), 

2446 expected.to(u.K, equivalencies=u.temperature()), 

2447 atol=1e-6 * u.K, 

2448 label=label, 

2449 ) 

2450 elif isinstance(expected, u.Quantity | float): 

2451 assert_values_equal(actual, expected, rtol=1e-9, label=label) 

2452 elif actual != expected: 

2453 raise AssertionError(f"{label}: {actual!r} != {expected!r}")