Coverage for tests/test_approximate_from_legacy.py: 26%
271 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-26 12:09 -0800
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-26 12:09 -0800
1# This file is part of lsst-images.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# Use of this source code is governed by a 3-clause BSD-style
10# license that can be found in the LICENSE file.
12"""Unit tests for the missing/partial-cell sampling rules of conversions
13from legacy (non-cell) coadd components.
14"""
16from __future__ import annotations
18import dataclasses
19import os
20import pickle
21import types
22from collections.abc import Iterable
23from typing import Any
25import numpy as np
26import pytest
28from lsst.images import XY, YX, BoundsError, Box, Image, SkyProjection, TractFrame
29from lsst.images.cells import (
30 CellField,
31 CellGridBounds,
32 CellIJ,
33 CellPointSpreadFunction,
34 CoaddProvenance,
35 PatchDefinition,
36 approximate_aperture_corrections_from_legacy,
37)
38from lsst.images.tests import (
39 DP2_COADD_DATA_ID,
40 assert_values_equal,
41 cell_center_points,
42 compare_cell_coadd_provenance_to_legacy_lazy,
43 compare_psf_to_legacy,
44 reset_afw_mask_planes, # noqa: F401
45)
47try:
48 from lsst.afw.detection import InvalidPsfError
49 from lsst.afw.geom import makeCdMatrix, makeSkyWcs
50 from lsst.afw.image import Exposure as LegacyExposure
51 from lsst.afw.image import ExposureFitsReader
52 from lsst.afw.math import ChebyshevBoundedField as LegacyChebyshevBoundedField
53 from lsst.afw.table import ExposureCatalog as LegacyExposureCatalog
54 from lsst.geom import Box2D as LegacyBox2D
55 from lsst.geom import Box2I as LegacyBox2I
56 from lsst.geom import Point2I as LegacyPoint2I
57 from lsst.meas.algorithms import CoaddBoundedField as LegacyCoaddBoundedField
58 from lsst.meas.algorithms import CoaddBoundedFieldElement as LegacyCoaddBoundedFieldElement
59 from lsst.meas.algorithms import CoaddPsf as LegacyCoaddPsf
60 from lsst.pex.exceptions import DomainError
61 from lsst.skymap import TractInfo as LegacyTractInfo
63 HAVE_LEGACY = True
64except ImportError:
65 type LegacyChebyshevBoundedField = Any # type: ignore[no-redef]
66 type LegacyExposure = Any # type: ignore[no-redef]
67 type LegacyExposureCatalog = Any # type: ignore[no-redef]
68 type LegacyBox2I = Any # type: ignore[no-redef]
69 type LegacyPoint2I = Any # type: ignore[no-redef]
70 type LegacyCoaddBoundedFieldElement = Any # type: ignore[no-redef]
71 type LegacyCoaddBoundedField = Any # type: ignore[no-redef]
72 type LegacyCoaddPsf = Any # type: ignore[no-redef]
73 type LegacyTractInfo = Any # type: ignore[no-redef]
74 HAVE_LEGACY = False
77EXTERNAL_DATA_DIR = os.environ.get("TESTDATA_IMAGES_DIR", None)
79# Index into the sparse cell's ``Box.boundary()`` corners whose overlapping
80# inputs are also (in addition to the center's inputs).
81PARTIAL_CORNER_INDEX = 0
82# Number of the sparse cell's corners that stay valid under ``trim_partial`` (4
83# corners minus the dropped one).
84PARTIAL_N_VALID_CORNERS = 3
87@dataclasses.dataclass(frozen=True)
88class _TrimmedLegacyCoaddComponents:
89 """Legacy coadd components rebuilt without the inputs covering a point."""
91 ccds: LegacyExposureCatalog
92 psf: LegacyCoaddPsf
93 ap_corrections: dict[str, LegacyCoaddBoundedField]
94 dropped: frozenset[tuple[int, int]] # dropped (visit, detector) pairs
97@dataclasses.dataclass(frozen=True)
98class _LegacyTestCoadd:
99 """Test data loaded from EXTERNAL_DATA_DIR."""
101 coadd: LegacyExposure
102 tract_info: LegacyTractInfo
103 patch: PatchDefinition
104 bounds: CellGridBounds
106 @property
107 def sky_projection(self) -> SkyProjection[TractFrame]:
108 """The coadd's sky projection in its tract frame."""
109 tract_bbox = Box.from_legacy(self.tract_info.getBBox())
110 return SkyProjection.from_legacy(
111 self.coadd.getWcs(),
112 TractFrame(
113 skymap=DP2_COADD_DATA_ID["skymap"],
114 tract=DP2_COADD_DATA_ID["tract"],
115 bbox=tract_bbox,
116 ),
117 pixel_bounds=tract_bbox,
118 )
120 @property
121 def sparse_cell_index(self) -> CellIJ:
122 """Index of the sparse cell that has an invalid corner or center,
123 depending on the test.
124 """
125 return next(iter(self.bounds.cell_indices()))
127 @property
128 def sparse_cell_box(self) -> Box:
129 """Pixel bounding box of the sparse cell."""
130 return self.patch.cells.bbox_of(self.sparse_cell_index)
132 @property
133 def control_cell_index(self) -> CellIJ:
134 """Index of a control cell: a regular cell fully covered by inputs."""
135 return self.sparse_cell_index + CellIJ(i=0, j=1)
137 @property
138 def control_cell_box(self) -> Box:
139 """Pixel bounding box of the control cell."""
140 return self.patch.cells.bbox_of(self.control_cell_index)
142 def trim(
143 self,
144 *points: XY[float] | YX[int],
145 ap_corr_names: Iterable[str] = (
146 "base_PsfFlux_instFlux",
147 "base_PsfFlux_instFluxErr",
148 "base_GaussianFlux_instFluxErr",
149 "ext_convolved_ConvolvedFlux_0_3_3_instFlux",
150 ),
151 ) -> _TrimmedLegacyCoaddComponents:
152 """Trim the original coadd's inputs to leave some of the sparse
153 cell uncovered.
155 Parameters
156 ----------
157 *points
158 Points that should be left uncovered by inputs.
159 ap_corr_names
160 Aperture correction fields to propagate (we don't need them all
161 for testing).
162 """
163 coadd_wcs = self.coadd.getWcs()
165 def _element_covers(element: LegacyCoaddBoundedFieldElement, point: XY[float] | YX[int]) -> bool:
166 """Test whether one visit-level ApCorr covers a coadd point."""
167 projected = element.wcs.skyToPixel(coadd_wcs.pixelToSky(point.to_legacy_float_point()))
168 # Box2D.contains rejects NaN projections (distant elements outside
169 # the TAN domain project here as NaN).
170 return LegacyBox2D(element.field.getBBox()).contains(projected) and element.validPolygon.contains(
171 projected
172 )
174 ccds = self.coadd.info.getCoaddInputs().ccds
175 dropped: set[tuple[int, int]] = set()
176 for point in points:
177 for record in ccds.subsetContaining(
178 point.to_legacy_float_point(), coadd_wcs, includeValidPolygon=True
179 ):
180 dropped.add((record.get("visit"), record.get("ccd")))
181 trimmed = ccds.copy()
182 # 'del catalog[i]' only supports one row at a time; drop from the back.
183 drop_rows = sorted(
184 i for i, record in enumerate(ccds) if (record.get("visit"), record.get("ccd")) in dropped
185 )
186 for i in reversed(drop_rows):
187 del trimmed[i]
188 psf = LegacyCoaddPsf(trimmed, coadd_wcs)
189 fields: dict[str, Any] = {}
190 for name in ap_corr_names:
191 stored = self.coadd.info.getApCorrMap()[name]
192 keep = [
193 element
194 for element in stored.getElements()
195 if not any(_element_covers(element, point) for point in points)
196 ]
197 assert keep, f"every element of {name} covers the trimmed points"
198 field = LegacyCoaddBoundedField(stored.getBBox(), coadd_wcs, keep)
199 # Check that the default throw behavior is what other tests expect
200 # so we don't miss out on coverage of both modes.
201 assert field.getThrowOnMissing(), f"{name} does not throw at uncovered points"
202 fields[name] = field
203 return _TrimmedLegacyCoaddComponents(
204 ccds=trimmed, psf=psf, ap_corrections=fields, dropped=frozenset(dropped)
205 )
208@pytest.fixture
209def legacy_test_coadd(reset_afw_mask_planes: None) -> _LegacyTestCoadd: # noqa: F811
210 """Return the DP2 template_coadd and its derived cell bounds."""
211 if not HAVE_LEGACY: 211 ↛ 212line 211 didn't jump to line 212 because the condition on line 211 was never true
212 pytest.skip("Legacy packages (lsst.afw, etc) could not be imported.")
213 if EXTERNAL_DATA_DIR is None: 213 ↛ 215line 213 didn't jump to line 215 because the condition on line 213 was always true
214 pytest.skip("TESTDATA_IMAGES_DIR is not in the environment.")
215 filename = os.path.join(EXTERNAL_DATA_DIR, "dp2", "legacy", "template_coadd.fits")
216 coadd = ExposureFitsReader(filename).read()
217 filename = os.path.join(EXTERNAL_DATA_DIR, "dp2", "legacy", "skyMap.pickle")
218 with open(filename, "rb") as stream:
219 skymap = pickle.load(stream)
220 tract_info = skymap[DP2_COADD_DATA_ID["tract"]]
221 patch = PatchDefinition.from_legacy_patch_info(tract_info[DP2_COADD_DATA_ID["patch"]])
222 # Cell bounds over the four sparsest cells of the patch (2x2 region).
223 # Tract-frame origin of the sparsest cell of patch 43: its center is
224 # covered by only 20 of the fixture's 103 inputs, while all four outermost
225 # pixel centers keep coverage from at least one other input.
226 region = Box.from_shape(patch.cells.cell_shape.map(lambda s: 2 * s), start=YX(y=12450, x=9600))
227 bounds = CellGridBounds(grid=patch.cells, bbox=patch.cells.bbox)[region]
228 return _LegacyTestCoadd(coadd=coadd, tract_info=tract_info, patch=patch, bounds=bounds)
231@pytest.fixture
232def trim_missing(legacy_test_coadd: _LegacyTestCoadd) -> _TrimmedLegacyCoaddComponents:
233 """Components with all inputs covering the sparse cell dropped."""
234 return legacy_test_coadd.trim(
235 legacy_test_coadd.sparse_cell_box.center, *legacy_test_coadd.sparse_cell_box.boundary()
236 )
239@pytest.fixture
240def trim_partial(legacy_test_coadd: _LegacyTestCoadd) -> _TrimmedLegacyCoaddComponents:
241 """Components with the inputs covering the sparse cell's center and one
242 corner dropped, leaving the other three corners valid.
243 """
244 return legacy_test_coadd.trim(
245 legacy_test_coadd.sparse_cell_box.center,
246 list(legacy_test_coadd.sparse_cell_box.boundary())[PARTIAL_CORNER_INDEX],
247 )
250def test_trim_missing_fixture(
251 legacy_test_coadd: _LegacyTestCoadd, trim_missing: _TrimmedLegacyCoaddComponents
252) -> None:
253 """Test that the `trim_missing` test fixture does what it claims."""
254 sparse_box = legacy_test_coadd.sparse_cell_box
255 center = sparse_box.center.to_legacy_float_point()
256 corners = [corner.to_legacy_float_point() for corner in sparse_box.boundary()]
257 for point in (center, *corners):
258 with pytest.raises(InvalidPsfError):
259 trim_missing.psf.computeKernelImage(point)
260 for field in trim_missing.ap_corrections.values():
261 with pytest.raises(DomainError):
262 field.evaluate(point)
263 other_center = legacy_test_coadd.control_cell_box.center.to_legacy_float_point()
264 trim_missing.psf.computeKernelImage(other_center) # must not raise
265 for field in trim_missing.ap_corrections.values():
266 assert np.isfinite(field.evaluate(other_center))
269def test_trim_partial_fixture(
270 legacy_test_coadd: _LegacyTestCoadd, trim_partial: _TrimmedLegacyCoaddComponents
271) -> None:
272 """Test that the `trim_partial` fixture does what it claims."""
273 sparse_box = legacy_test_coadd.sparse_cell_box
274 corners = [corner.to_legacy_float_point() for corner in sparse_box.boundary()]
275 for point in (sparse_box.center.to_legacy_float_point(), corners[PARTIAL_CORNER_INDEX]):
276 with pytest.raises(InvalidPsfError):
277 trim_partial.psf.computeKernelImage(point)
278 for field in trim_partial.ap_corrections.values():
279 with pytest.raises(DomainError):
280 field.evaluate(point)
281 valid_others = []
282 for k, corner in enumerate(corners):
283 if k == PARTIAL_CORNER_INDEX:
284 continue
285 try:
286 trim_partial.psf.computeKernelImage(corner)
287 finite = all(
288 np.isfinite(field.evaluate(corner)) for field in trim_partial.ap_corrections.values()
289 )
290 except (InvalidPsfError, DomainError):
291 finite = False
292 if finite:
293 valid_others.append(k)
294 # Exact count and identity: exactly the three corners other than the
295 # dropped one stay valid (the partial-corner regime the averaging tests
296 # below rely on).
297 assert valid_others == [k for k in range(len(corners)) if k != PARTIAL_CORNER_INDEX]
298 assert len(valid_others) == PARTIAL_N_VALID_CORNERS
299 other_center = legacy_test_coadd.control_cell_box.center.to_legacy_float_point()
300 trim_partial.psf.computeKernelImage(other_center) # must not raise
301 for field in trim_partial.ap_corrections.values():
302 assert np.isfinite(field.evaluate(other_center))
305def test_psf_valid_cells_store_center_stamps(
306 legacy_test_coadd: _LegacyTestCoadd, trim_missing: _TrimmedLegacyCoaddComponents
307) -> None:
308 """Test that where the center is valid, the stored stamp is exactly the
309 legacy kernel image at the center (zero-padded into the shared kernel
310 bbox).
311 """
312 psf = CellPointSpreadFunction.approximate_from_legacy(trim_missing.psf, legacy_test_coadd.bounds)
313 stamp = Image.from_legacy(
314 trim_missing.psf.computeKernelImage(legacy_test_coadd.control_cell_box.center.to_legacy_float_point())
315 )
316 expected = np.zeros(psf.kernel_bbox.shape, dtype=np.float64)
317 slices = stamp.bbox.slice_within(psf.kernel_bbox)
318 expected[slices.y, slices.x] = stamp.array
319 assert psf[legacy_test_coadd.control_cell_index] == Image(expected, bbox=psf.kernel_bbox)
322def test_psf_partial_corner_fallback_averages_valid_corners(
323 legacy_test_coadd: _LegacyTestCoadd, trim_partial: _TrimmedLegacyCoaddComponents
324) -> None:
325 """Test that the cell whose center and one corner are invalid stores the
326 mean of only the valid corner stamps.
327 """
328 psf = CellPointSpreadFunction.approximate_from_legacy(trim_partial.psf, legacy_test_coadd.bounds)
329 assert legacy_test_coadd.sparse_cell_index not in psf.bounds.missing
330 corners = [corner.to_legacy_float_point() for corner in legacy_test_coadd.sparse_cell_box.boundary()]
331 total = np.zeros(psf.kernel_bbox.shape, dtype=np.float64)
332 n_valid = 0
333 for k, corner in enumerate(corners):
334 if k == PARTIAL_CORNER_INDEX:
335 continue
336 stamp = Image.from_legacy(trim_partial.psf.computeKernelImage(corner))
337 slices = stamp.bbox.slice_within(psf.kernel_bbox)
338 total[slices.y, slices.x] += stamp.array
339 n_valid += 1
340 assert n_valid == PARTIAL_N_VALID_CORNERS
341 expected = total / n_valid
342 stored = psf[legacy_test_coadd.sparse_cell_index]
343 assert stored.bbox == psf.kernel_bbox
344 # Bitwise: the conversion sums the same valid stamps in the same
345 # boundary() order, then divides in place by the number of valid stamps.
346 assert np.array_equal(stored.array, expected)
349def test_psf_missing_cells_marked_and_nan(
350 legacy_test_coadd: _LegacyTestCoadd, trim_missing: _TrimmedLegacyCoaddComponents
351) -> None:
352 """Test that a fully-invalid cell is added to bounds.missing and its
353 array slice is NaN (the documented convention), and that pre-existing
354 missing cells survive the bounds reconstruction.
355 """
356 pre_existing = CellGridBounds(
357 grid=legacy_test_coadd.bounds.grid,
358 bbox=legacy_test_coadd.bounds.bbox,
359 missing=frozenset({legacy_test_coadd.control_cell_index}),
360 )
361 psf = CellPointSpreadFunction.approximate_from_legacy(trim_missing.psf, pre_existing)
362 assert legacy_test_coadd.sparse_cell_index in psf.bounds.missing
363 assert legacy_test_coadd.control_cell_index in psf.bounds.missing
364 # We have to access the private array to see that it's NaN (public
365 # interface
366 # raises).
367 index = legacy_test_coadd.sparse_cell_index - psf.bounds.subgrid_start
368 assert np.isnan(psf._array[index.i, index.j]).all()
371def test_psf_raises_when_no_cell_is_valid(
372 legacy_test_coadd: _LegacyTestCoadd, trim_missing: _TrimmedLegacyCoaddComponents
373) -> None:
374 """Test that conversion of a region with no valid sample anywhere is an
375 error, not an all-missing result.
376 """
377 single = legacy_test_coadd.bounds[
378 legacy_test_coadd.bounds.grid.bbox_of(legacy_test_coadd.sparse_cell_index)
379 ]
380 with pytest.raises(ValueError, match="could not be evaluated"):
381 CellPointSpreadFunction.approximate_from_legacy(trim_missing.psf, single)
384def test_field_valid_cells_store_center_values(
385 legacy_test_coadd: _LegacyTestCoadd, trim_missing: _TrimmedLegacyCoaddComponents
386) -> None:
387 """Test that where the center is valid, the stored value is exactly the
388 legacy evaluation at the center.
389 """
390 for name, legacy_field in trim_missing.ap_corrections.items():
391 field = CellField.approximate_from_legacy(legacy_field, legacy_test_coadd.bounds)
392 assert field.value_in_cell(legacy_test_coadd.control_cell_index) == legacy_field.evaluate(
393 legacy_test_coadd.control_cell_box.center.to_legacy_float_point()
394 ), name
397def test_field_partial_corner_fallback_averages_valid_only(
398 legacy_test_coadd: _LegacyTestCoadd, trim_partial: _TrimmedLegacyCoaddComponents
399) -> None:
400 """Test that the cell whose center and one corner are invalid stores the
401 mean of only the valid corner evaluations. A mean over the valid samples
402 differs from a sum over them divided by four, so this pins the divisor
403 against a regression to the corner count.
404 """
405 cell_a = legacy_test_coadd.sparse_cell_index
406 corners = [corner.to_legacy_float_point() for corner in legacy_test_coadd.sparse_cell_box.boundary()]
407 for name, legacy_field in trim_partial.ap_corrections.items():
408 field = CellField.approximate_from_legacy(legacy_field, legacy_test_coadd.bounds)
409 assert cell_a not in field.bounds.missing, name
410 values = [
411 legacy_field.evaluate(corner) for k, corner in enumerate(corners) if k != PARTIAL_CORNER_INDEX
412 ]
413 assert len(values) == PARTIAL_N_VALID_CORNERS
414 assert all(np.isfinite(values)), name
415 assert_values_equal(
416 field.value_in_cell(cell_a),
417 float(np.mean(values)),
418 rtol=1e-13,
419 label=f"partial fallback cell value [{name}]",
420 )
423def test_field_missing_cells_marked_and_nan(
424 legacy_test_coadd: _LegacyTestCoadd, trim_missing: _TrimmedLegacyCoaddComponents
425) -> None:
426 """Test that a cell where center and all corners raise is marked missing,
427 its array entry is NaN (the documented convention), and the accessor
428 refuses missing cells.
429 """
430 for name, legacy_field in trim_missing.ap_corrections.items():
431 field = CellField.approximate_from_legacy(legacy_field, legacy_test_coadd.bounds)
432 assert legacy_test_coadd.sparse_cell_index in field.bounds.missing, name
433 # We have to access the private array to see that it's NaN (public
434 # interface raises).
435 index = legacy_test_coadd.sparse_cell_index - field.bounds.subgrid_start
436 assert np.isnan(field._array[index.i, index.j]), name
437 with pytest.raises(BoundsError):
438 field.value_in_cell(legacy_test_coadd.sparse_cell_index)
441def test_approximate_from_legacy_returns_none_without_usable_values(
442 legacy_test_coadd: _LegacyTestCoadd,
443) -> None:
444 """A legacy field that cannot be sampled in any cell converts to `None`."""
445 unusable = LegacyChebyshevBoundedField(
446 legacy_test_coadd.bounds.bbox.to_legacy(),
447 np.full(legacy_test_coadd.bounds.subgrid_size.as_tuple(), np.nan),
448 )
449 assert CellField.approximate_from_legacy(unusable, legacy_test_coadd.bounds) is None
452def test_aperture_corrections_err_without_usable_flux_is_none(
453 legacy_test_coadd: _LegacyTestCoadd,
454) -> None:
455 """An ``*_instFluxErr`` field converts to `None` when its ``*_instFlux``
456 partner does, even though the legacy default of zero would otherwise be
457 a usable error value.
458 """
459 no_inputs = LegacyCoaddBoundedField(
460 legacy_test_coadd.bounds.bbox.to_legacy(), legacy_test_coadd.coadd.getWcs(), [], 0.0
461 )
462 converted = approximate_aperture_corrections_from_legacy(
463 {"a_instFlux": no_inputs, "a_instFluxErr": no_inputs}, legacy_test_coadd.bounds
464 )
465 assert converted == {"a_instFlux": None, "a_instFluxErr": None}
468def test_provenance_skips_missing_cells_and_matches_trimmed_inputs(
469 legacy_test_coadd: _LegacyTestCoadd,
470 trim_missing: _TrimmedLegacyCoaddComponents,
471) -> None:
472 """Test that provenance built from the trimmed catalog contributes
473 nothing to the missing cell and is consistent with the trimmed catalog's
474 own geometry.
475 """
476 psf = CellPointSpreadFunction.approximate_from_legacy(trim_missing.psf, legacy_test_coadd.bounds)
477 bounds = psf.bounds
478 cell_a = legacy_test_coadd.sparse_cell_index
479 assert cell_a in bounds.missing
481 provenance = CoaddProvenance.from_legacy_lazy(
482 # from_legacy_lazy takes a CoaddInputs-like object and reads only
483 # its .ccds attribute (lsst/images/cells/_provenance.py).
484 types.SimpleNamespace(ccds=trim_missing.ccds),
485 bounds=bounds,
486 sky_projection=legacy_test_coadd.sky_projection,
487 instrument="LSSTCam",
488 )
490 contribution_cells = {
491 CellIJ(i=int(row["cell_i"]), j=int(row["cell_j"])) for row in provenance.contributions
492 }
493 assert cell_a not in contribution_cells
494 # Every remaining cell here is covered by surviving inputs, so
495 # contributions cover exactly the non-missing cells of the region.
496 assert contribution_cells == set(bounds.cell_indices())
497 # The provenance inputs table carries (visit, detector) identities;
498 # from_legacy_lazy legitimately skips inputs that do not overlap the
499 # region bounds (the NoOverlapError path in _provenance.py), so the
500 # shipped helper asserts the identities are a subset of the trimmed
501 # catalog rather than equal to it.
503 trimmed_legacy = types.SimpleNamespace(
504 info=types.SimpleNamespace(getCoaddInputs=lambda: types.SimpleNamespace(ccds=trim_missing.ccds)),
505 getWcs=lambda: legacy_test_coadd.coadd.getWcs(),
506 )
507 compare_cell_coadd_provenance_to_legacy_lazy(provenance, trimmed_legacy, bounds)
510def _move_record_far_away(record: Any, coadd_wcs: Any) -> None:
511 """Give a coadd-input record a WCS centered on the far side of the sky
512 from the coadd's tangent point, outside the coadd projection's domain.
513 """
514 from lsst.geom import Point2D, SpherePoint, degrees
516 origin = coadd_wcs.getSkyOrigin()
517 antipode = SpherePoint(origin.getLongitude() + 180.0 * degrees, -origin.getLatitude())
518 cd_matrix = makeCdMatrix(scale=record.getWcs().getPixelScale())
519 record.setWcs(makeSkyWcs(crpix=Point2D(0.0, 0.0), crval=antipode, cdMatrix=cd_matrix))
522def _provenance_keys(provenance: CoaddProvenance) -> set[tuple[int, int]]:
523 return {(int(row["visit"]), int(row["detector"])) for row in provenance.inputs}
526def test_provenance_skips_inputs_outside_projection_domain(legacy_test_coadd: _LegacyTestCoadd) -> None:
527 """Test that an input whose footprint cannot be projected onto the coadd
528 is dropped rather than aborting the conversion.
529 """
530 ccds = legacy_test_coadd.coadd.info.getCoaddInputs().ccds
531 expected = CoaddProvenance.from_legacy_lazy(
532 types.SimpleNamespace(ccds=ccds),
533 bounds=legacy_test_coadd.bounds,
534 sky_projection=legacy_test_coadd.sky_projection,
535 instrument="LSSTCam",
536 )
537 moved = ccds.copy(deep=True)
538 # Move an input that does overlap the test region, so the drop is visible.
539 moved_key = next(iter(sorted(_provenance_keys(expected))))
540 for record in moved:
541 if (int(record.get("visit")), int(record.get("ccd"))) == moved_key:
542 _move_record_far_away(record, legacy_test_coadd.coadd.getWcs())
543 provenance = CoaddProvenance.from_legacy_lazy(
544 types.SimpleNamespace(ccds=moved),
545 bounds=legacy_test_coadd.bounds,
546 sky_projection=legacy_test_coadd.sky_projection,
547 instrument="LSSTCam",
548 )
549 assert _provenance_keys(provenance) == _provenance_keys(expected) - {moved_key}
552def test_compare_psf_to_legacy_approximate_kernel_bbox(legacy_test_coadd: _LegacyTestCoadd) -> None:
553 """Test that the approximate PSF comparison accepts a stored kernel bbox
554 larger than the legacy kernel bbox at a point (as the shared bbox of a
555 converted cell PSF generally is), while the exact comparison does not.
556 """
557 legacy_psf = legacy_test_coadd.coadd.getPsf()
558 psf = CellPointSpreadFunction.approximate_from_legacy(legacy_psf, legacy_test_coadd.bounds)
559 padded = CellPointSpreadFunction(np.pad(psf._array, [(0, 0), (0, 0), (1, 1), (1, 1)]), bounds=psf.bounds)
560 assert padded.kernel_bbox != psf.kernel_bbox
561 points = cell_center_points(psf.bounds)
562 assert compare_psf_to_legacy(padded, legacy_psf, points=points, rtol=1e-5) == psf.bounds.n_cells
563 with pytest.raises(AssertionError):
564 compare_psf_to_legacy(padded, legacy_psf, points=points)
565 # A stamp with flux outside the legacy kernel bbox is still rejected.
566 corrupted_array = padded._array.copy()
567 corrupted_array[:, :, 0, 0] = 1.0
568 corrupted = CellPointSpreadFunction(corrupted_array, bounds=psf.bounds)
569 with pytest.raises(AssertionError):
570 compare_psf_to_legacy(corrupted, legacy_psf, points=points, rtol=1e-5)
573def test_compare_psf_to_legacy_exact_mode_propagates_invalid_psf(
574 legacy_test_coadd: _LegacyTestCoadd, trim_missing: _TrimmedLegacyCoaddComponents
575) -> None:
576 """Test that a legacy PSF that cannot be evaluated at a comparison point
577 fails an exact comparison, and is only skipped by an approximate one.
578 """
579 psf = CellPointSpreadFunction.approximate_from_legacy(
580 legacy_test_coadd.coadd.getPsf(), legacy_test_coadd.bounds
581 )
582 center = legacy_test_coadd.sparse_cell_box.center
583 points = XY(x=np.array([center.x]), y=np.array([center.y]))
584 with pytest.raises(InvalidPsfError):
585 compare_psf_to_legacy(psf, trim_missing.psf, points=points)
586 assert compare_psf_to_legacy(psf, trim_missing.psf, points=points, rtol=1e-5) == 0