Coverage for python/lsst/images/tests/_minify_for_fixtures.py: 20%

197 statements  

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

1# This file is part of lsst-images. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (https://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# Use of this source code is governed by a 3-clause BSD-style 

10# license that can be found in the LICENSE file. 

11 

12"""Minify a real on-disk archive into a small JSON test fixture. 

13 

14Reads a FITS or NDF file via the appropriate input archive, takes a 

15small subset of the in-memory object, and writes JSON via 

16``JsonOutputArchive``. Used to populate the ``dp1`` / ``dp2`` fixture 

17variants under ``tests/data/schemas/`` with derived-from-real test data 

18that exercises the full read path. The ``cell_coadd`` ``as_shipped`` 

19fixture was also written by this helper, but it preserves the bytes of a 

20shipped file and is never regenerated. 

21 

22Per top-level type the subset rule is: 

23 

24 VisitImage Crop the image/mask/variance planes to a small (~16x16) 

25 corner, keeping the real single-instance structures (PSF 

26 such as Piff, detector frames) that synthetic fixtures 

27 cannot reproduce -- the whole point of deriving a fixture 

28 from real data. Homogeneous repeated collections (detector 

29 amplifiers, aperture-correction entries) are trimmed to a 

30 representative few, since one entry exercises the schema as 

31 well as sixteen. The projection's pixel->sky mapping is 

32 replaced by its linear (affine) approximation over the kept 

33 box: a real TAN-SIP WCS serializes as a ~100 KB AST 

34 polynomial dump, but over a 16x16 box it is linear to far 

35 below a pixel, so the affine form is schema-identical and 

36 orders of magnitude smaller. A Piff PSF's field 

37 interpolation is truncated to a low order (the order-4 

38 solution table is ~225 KB; order 0, the field-averaged PSF, 

39 is schema-identical and ~13x smaller). 

40 

41 CellCoadd Crop to a small block of cells (preferring a block that 

42 includes a missing cell so the sparse-grid path is 

43 exercised) and then *morph* that block onto a tiny cell 

44 grid: each cell's planes are decimated from the native 

45 cell size down to a few pixels and re-stitched, and the 

46 PSF kernels are cropped to a small odd window. The grid 

47 topology (number of cells, the missing-cell set, band, 

48 mask schema and provenance shape) is preserved; the pixel 

49 values and WCS are *not* physically meaningful. This is 

50 the "morph cells in place" fallback: it sidesteps the 

51 outer-ring problem (inputs/PSFs that overlap kept cells) 

52 by rebuilding a self-consistent miniature coadd rather 

53 than trying to carve an accurate subset out of the real 

54 one. An accurate per-cell subset would inline several 

55 150x150 planes per cell and produce multi-megabyte JSON, 

56 which defeats the purpose of a fixture. 

57 

58Run interactively; the input must be a native ``lsst.images`` archive, so 

59legacy files under ``$TESTDATA_IMAGES_DIR`` are must be converted first:: 

60 

61 lsst-images-admin convert \ 

62 "$TESTDATA_IMAGES_DIR/dp2/legacy/deep_coadd_cell_predetection.fits" \ 

63 native_cell_coadd.fits --type cell_coadd \ 

64 --skymap "$TESTDATA_IMAGES_DIR/dp2/legacy/skyMap.pickle" 

65 python -c " 

66 from lsst.images.tests._minify_for_fixtures import minify 

67 schemas = 'tests/data/schemas' 

68 minify( 

69 'native_cell_coadd.fits', 

70 f'{schemas}/cell_coadd/cell_coadd-1.0.0-dp2.json', 

71 ) 

72 minify('dp1.fits', f'{schemas}/visit_image/visit_image-1.0.0.dev-dp1.json') 

73 minify('dp2.fits', f'{schemas}/visit_image/visit_image-1.0.0.dev-dp2.json') 

74 " 

75 

76Fixtures must then be put in canonical form. ``lsst-images-admin fixtures 

77refresh`` does that for a fixture at a development version, but refuses to 

78rewrite one at a finalized version such as ``cell_coadd`` 1.0.0, which has 

79to be canonicalized directly:: 

80 

81 python -c " 

82 from pathlib import Path 

83 from lsst.images.tests import ( 

84 canonical_fixture_text, iter_schema_fixtures, read_fixture_tree, 

85 ) 

86 for fixture in iter_schema_fixtures(Path('tests/data/schemas')): 

87 if (fixture.name, fixture.variant) == ('cell_coadd', 'dp2'): 

88 fixture.path.write_text(canonical_fixture_text(read_fixture_tree(fixture))) 

89 " 

90 

91The helper is invoked manually by developers when they have a real 

92on-disk file to derive from; it is not exercised by CI. 

93""" 

94 

95from __future__ import annotations 

96 

97__all__ = ("minify",) 

98 

99import os 

100from collections.abc import Callable 

101from typing import Any, cast 

102 

103import numpy as np 

104 

105from .. import DifferenceImage, VisitImage 

106from .._cell_grid import CellGrid, CellGridBounds, CellIJ, PatchDefinition 

107from .._geom import YX, Box 

108from .._image import Image 

109from .._mask import Mask 

110from .._transforms import SkyProjection, TractFrame, Transform 

111from .._transforms._ast import PolyMap 

112from ..cells import CellCoadd, CellField, CellPointSpreadFunction, CoaddProvenance 

113from ..convolution_kernels import ImageBasisConvolutionKernel 

114from ..psfs import PiffWrapper 

115from ..serialization import read_archive 

116from ._creation import make_random_sky_projection 

117 

118# Default morph parameters for CellCoadd. ``CELL_SIZE`` should divide the 

119# native cell size evenly; ``KERNEL_SIZE`` must be odd. ``MAX_INPUTS`` caps 

120# the provenance ``inputs`` table (a real coadd has hundreds of visits); the 

121# full provenance schema is already exercised by the ``coadd_provenance`` 

122# fixture, so here we keep just enough rows to be representative. 

123_CELL_SIZE = 6 

124_KERNEL_SIZE = 5 

125_MAX_INPUTS = 6 

126 

127# A real coadd's aperture-correction map is dozens of schema-identical names; 

128# a couple of usable ones plus a single unusable (all-NaN column) name cover 

129# the schema as well as the full map. 

130_MAX_USABLE_APERTURE_CORRECTIONS = 2 

131_MAX_UNUSABLE_APERTURE_CORRECTIONS = 1 

132 

133# Default trim parameters for VisitImage. Amplifiers and aperture-correction 

134# entries are homogeneous collections, so a couple of each cover the schema 

135# just as well as the full set (a real detector has 16 amplifiers and dozens 

136# of aperture corrections). 

137_MAX_AMPLIFIERS = 2 

138_MAX_APERTURE_CORRECTIONS = 2 

139 

140# Field-interpolation order to truncate a Piff PSF to (the solution table of a 

141# real order-4 PixelGrid PSF dominates the fixture at ~225 KB). Order 0 is the 

142# field-averaged PSF; set to `None` to leave the PSF untouched. 

143_PSF_INTERP_ORDER = 0 

144 

145# Maximum permitted deviation (radians) when approximating a projection's 

146# pixel->sky mapping with an affine one. Over a fixture's tiny box the real 

147# mapping is linear well below this, so the fit always succeeds. 

148_PROJECTION_LINEAR_APPROX_TOL = 1e-8 

149 

150 

151def minify(in_path: str, out_path: str) -> None: 

152 """Read a real archive at ``in_path``, take a small subset, and write JSON. 

153 

154 Parameters 

155 ---------- 

156 in_path 

157 Path to a FITS (``.fits`` / ``.fits.gz``) or NDF (``.sdf`` / ``.ndf``) 

158 file to read. 

159 out_path 

160 Path to the output file to write. The parent directory is 

161 created if it does not exist. Can be any supported file format. 

162 File extension controls the output format. 

163 

164 Raises 

165 ------ 

166 ValueError 

167 If the file extension is not recognised. 

168 NotImplementedError 

169 If the top-level type is not one this helper knows how to subset. 

170 """ 

171 obj = read_archive(in_path) 

172 subsetter = _dispatch(obj) 

173 subset = subsetter(obj) 

174 

175 os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True) 

176 subset.write(out_path) 

177 

178 

179def _dispatch(image: Any) -> Callable[[Any], Any]: 

180 """Return the relevant subsetter for this image object.""" 

181 match image: 

182 case DifferenceImage(): # this branch needs to go first, as DifferenceImage subclasses VisitImage 182 ↛ 183line 182 didn't jump to line 183 because the pattern on line 182 never matched

183 return _subset_difference_image 

184 case VisitImage(): 184 ↛ 185line 184 didn't jump to line 185 because the pattern on line 184 never matched

185 return _subset_visit_image 

186 case CellCoadd(): 

187 return _subset_cell_coadd 

188 case _: 

189 raise NotImplementedError(f"No minify rule for image of type {type(image)}.") 

190 

191 

192# -- VisitImage ------------------------------------------------------------ 

193 

194 

195def _subset_visit_image[T: VisitImage]( 

196 visit_like_image: T, 

197 *, 

198 size: int = 16, 

199 max_amplifiers: int = _MAX_AMPLIFIERS, 

200 max_aperture_corrections: int = _MAX_APERTURE_CORRECTIONS, 

201 linearize_projection: bool = True, 

202 projection_tol: float = _PROJECTION_LINEAR_APPROX_TOL, 

203 psf_interp_order: int | None = _PSF_INTERP_ORDER, 

204) -> T: 

205 """Crop a VisitImage's pixel planes to a small corner and trim its 

206 homogeneous collections. 

207 

208 The detector frames are a single structure carried through unchanged by 

209 ``__getitem__``. The detector's amplifiers and the aperture-correction map 

210 are repeated, schema-identical entries, so they are trimmed to a 

211 representative few. The projection's pixel->sky mapping is replaced by its 

212 affine approximation over the kept box (see ``_linear_approx_projection``) 

213 unless ``linearize_projection`` is false. A Piff PSF's field interpolation 

214 is truncated to ``psf_interp_order`` (see ``_simplify_piff_psf``) unless 

215 that is `None`. 

216 """ 

217 bbox = visit_like_image.bbox 

218 y0 = bbox.y.start 

219 x0 = bbox.x.start 

220 y1 = min(y0 + size, bbox.y.stop) 

221 x1 = min(x0 + size, bbox.x.stop) 

222 subset = cast(T, visit_like_image[Box.factory[y0:y1, x0:x1]]) 

223 

224 # ``subset`` is a fresh throwaway object whose detector amplifier list, 

225 # aperture-correction map and PSF are live, mutable components. Trim them 

226 # in place through the public accessors rather than reaching for private 

227 # attributes. 

228 del subset.detector.amplifiers[max_amplifiers:] 

229 aperture_corrections = subset.aperture_corrections 

230 for key in list(aperture_corrections)[max_aperture_corrections:]: 

231 del aperture_corrections[key] 

232 if psf_interp_order is not None and isinstance(subset.psf, PiffWrapper): 

233 _simplify_piff_psf(subset.psf, order=psf_interp_order) 

234 

235 if not linearize_projection or subset.sky_projection is None: 

236 return subset 

237 

238 # The pixel planes carry the projection immutably (there is no public 

239 # setter for it), so install the affine approximation by rebuilding the 

240 # VisitImage from its public components with re-viewed planes. Only the 

241 # image plane's projection is actually serialized, but keeping all three 

242 # consistent avoids surprises. 

243 linear = _linear_approx_projection(subset.sky_projection, subset.image.bbox, tol=projection_tol) 

244 return type(visit_like_image)( 

245 subset.image.view(sky_projection=linear), 

246 mask=subset.mask.view(sky_projection=linear), 

247 variance=subset.variance.view(sky_projection=linear), 

248 sky_projection=linear, 

249 psf=subset.psf, 

250 obs_info=subset.obs_info, 

251 bounds=subset.bounds, 

252 summary_stats=subset.summary_stats, 

253 detector=subset.detector, 

254 photometric_scaling=subset.photometric_scaling, 

255 aperture_corrections=subset.aperture_corrections, 

256 backgrounds=subset.backgrounds, 

257 band=subset.band, 

258 metadata=subset._metadata, 

259 ) 

260 

261 

262def _linear_approx_projection(sky_projection: SkyProjection, bbox: Box, *, tol: float) -> SkyProjection: 

263 """Return a copy of ``sky_projection`` whose pixel->sky mapping is replaced 

264 by its best linear (affine) approximation over ``bbox``. 

265 

266 Real WCS mappings (e.g. TAN-SIP) serialize as large AST polynomial dumps. 

267 Over the small box of a fixture they are linear to far below a pixel, so 

268 an affine approximation is schema-identical but orders of magnitude 

269 smaller. The result carries no FITS approximation (the affine is itself 

270 trivially FITS-representable). 

271 

272 This is written as a self-contained ``sky_projection -> sky_projection`` 

273 transform so it can be promoted to a public 

274 ``SkyProjection.linear_approx(bbox, tol)`` method later with essentially 

275 no change. It assumes a 2-D pixel->sky 

276 mapping. 

277 

278 Parameters 

279 ---------- 

280 sky_projection 

281 The projection to approximate. 

282 bbox 

283 Box (in pixel coordinates) over which the approximation must hold. 

284 tol 

285 Maximum permitted deviation from linearity, as a Cartesian 

286 displacement in the output (sky, radians) coordinates. AST raises 

287 ``RuntimeError`` if no fit within ``tol`` exists. 

288 """ 

289 transform = sky_projection.pixel_to_sky_transform 

290 mapping = transform._ast_mapping 

291 lbnd = [bbox.x.start, bbox.y.start] 

292 ubnd = [bbox.x.stop, bbox.y.stop] 

293 # linearApprox yields [offsets; Jacobian] as a (1 + n_out, n_in) array on 

294 # both AST backends (astshim returns the flat buffer in the same order, so 

295 # the reshape recovers the same layout the starlink-pyast bridge returns). 

296 fit = np.asarray(mapping.linearApprox(lbnd, ubnd, tol), dtype=float).reshape(3, 2) 

297 offset = fit[0] # (lon0, lat0), radians 

298 jacobian = fit[1:] # jacobian[i, j] = d(out_i) / d(in_j), in = (x, y) 

299 jacobian_inv = np.linalg.inv(jacobian) 

300 forward = _affine_polymap_coeffs(jacobian, offset) 

301 inverse = _affine_polymap_coeffs(jacobian_inv, -jacobian_inv @ offset) 

302 affine = Transform( 

303 transform.in_frame, 

304 transform.out_frame, 

305 PolyMap(forward, inverse), 

306 in_bounds=sky_projection.pixel_bounds, 

307 ) 

308 return SkyProjection(affine) 

309 

310 

311def _affine_polymap_coeffs(matrix: np.ndarray, offset: np.ndarray) -> np.ndarray: 

312 """Build AST ``PolyMap`` coefficients for ``out = matrix @ in + offset``. 

313 

314 Each row is ``[coefficient, output_axis (1-based), power_of_in_1, ...]``; 

315 one constant row plus one row per input per output axis. Returned as a 

316 float array, which is the form both AST backends require. 

317 """ 

318 n = len(offset) 

319 coeffs: list[list[float]] = [] 

320 for i in range(n): 

321 coeffs.append([float(offset[i]), i + 1, *([0] * n)]) 

322 for j in range(n): 

323 powers = [1 if k == j else 0 for k in range(n)] 

324 coeffs.append([float(matrix[i][j]), i + 1, *powers]) 

325 return np.array(coeffs, dtype=float) 

326 

327 

328def _simplify_piff_psf(psf: PiffWrapper, *, order: int) -> None: 

329 """Truncate a Piff PSF's field interpolation to ``order``, in place. 

330 

331 A real Piff PSF interpolates a per-pixel model across the focal plane with 

332 a high-order 2-D polynomial; that solution table dominates the serialized 

333 size (a 25x25 PixelGrid x order-4 polynomial is ~225 KB). Truncating to 

334 ``order`` keeps only the lowest-order field terms -- order 0 is the 

335 field-averaged PSF -- which is schema-identical but far smaller, and needs 

336 no stars or refit (the fitted ``stars`` are already dropped on serialize). 

337 

338 Only ``BasisPolynomial``-interpolated PSFs are handled; anything else (a 

339 higher-order model already at/under ``order``, a non-polynomial interp) is 

340 left untouched. 

341 

342 ``piff`` is imported lazily because it is an optional dependency; this is 

343 only ever reached when the PSF being simplified is itself a Piff PSF. 

344 """ 

345 interp = getattr(psf.piff_psf, "interp", None) 

346 if interp is None or type(interp).__name__ != "BasisPolynomial" or interp.q is None: 

347 return 

348 if order >= max(interp._orders): 

349 return 

350 

351 from piff import BasisPolynomial 

352 

353 # ``q`` has one column per active basis term; the terms are the True cells 

354 # of ``_mask`` in row-major (i, j) order (see BasisPolynomial.basis). Make 

355 # the same ordering for a lower-order interp and copy the shared columns. 

356 def _terms(orders: tuple[int, ...], mask: np.ndarray) -> list[tuple[int, ...]]: 

357 grids = np.meshgrid(*[np.arange(o + 1) for o in orders], indexing="ij") 

358 return list(zip(*(grid[mask].tolist() for grid in grids))) 

359 

360 old_terms = _terms(interp._orders, interp._mask) 

361 truncated = BasisPolynomial(order, keys=list(interp._keys)) 

362 new_terms = _terms(truncated._orders, truncated._mask) 

363 column_of = {term: index for index, term in enumerate(old_terms)} 

364 truncated.q = np.ascontiguousarray(interp.q[:, [column_of[term] for term in new_terms]]) 

365 psf.piff_psf.interp = truncated 

366 

367 

368# -- DifferenceImage ------------------------------------------------------- 

369 

370 

371def _subset_difference_image( 

372 difference_image: DifferenceImage, 

373 *, 

374 size: int = 16, 

375 max_amplifiers: int = _MAX_AMPLIFIERS, 

376 max_aperture_corrections: int = _MAX_APERTURE_CORRECTIONS, 

377 linearize_projection: bool = True, 

378 projection_tol: float = _PROJECTION_LINEAR_APPROX_TOL, 

379 psf_interp_order: int | None = _PSF_INTERP_ORDER, 

380) -> DifferenceImage: 

381 """Shrink a difference image. 

382 

383 Most of the shrinking is delegated to `_subset_visit_image`. 

384 

385 Template provenance is shrunk to the first few entries. 

386 

387 Difference kernel basis images are sliced to the innermost pixels and the 

388 number of basis functions is shrunk to the first few. 

389 """ 

390 result = _subset_visit_image( 

391 difference_image, 

392 size=size, 

393 max_amplifiers=max_amplifiers, 

394 max_aperture_corrections=max_aperture_corrections, 

395 linearize_projection=linearize_projection, 

396 projection_tol=projection_tol, 

397 psf_interp_order=psf_interp_order, 

398 ) 

399 if difference_image._kernel is not None: 

400 result.kernel = _subset_difference_kernel(cast(ImageBasisConvolutionKernel, difference_image._kernel)) 

401 result.templates = difference_image.templates[:2] if difference_image.templates is not None else None 

402 return result 

403 

404 

405def _subset_difference_kernel( 

406 kernel: ImageBasisConvolutionKernel, 

407 *, 

408 n_basis_images: int = 2, 

409 basis_radius: int = 1, 

410) -> ImageBasisConvolutionKernel: 

411 kernel_bbox = kernel.kernel_bbox.absolute[ 

412 -basis_radius : basis_radius + 1, -basis_radius : basis_radius + 1 

413 ] 

414 slices = kernel_bbox.slice_within(kernel.kernel_bbox) 

415 return ImageBasisConvolutionKernel( 

416 kernel.basis[:n_basis_images, *slices], 

417 kernel.spatial[:n_basis_images], 

418 ) 

419 

420 

421# -- CellCoadd ------------------------------------------------------------- 

422 

423 

424def _subset_cell_coadd( 

425 cell_coadd: CellCoadd, 

426 *, 

427 cell_size: int = _CELL_SIZE, 

428 kernel_size: int = _KERNEL_SIZE, 

429 max_inputs: int = _MAX_INPUTS, 

430) -> CellCoadd: 

431 """Crop a CellCoadd to a small block of cells and morph it onto a tiny 

432 grid (see the module docstring for the rationale). 

433 """ 

434 if kernel_size % 2 == 0: 

435 raise ValueError(f"kernel_size must be odd, got {kernel_size}.") 

436 

437 # 1. Pick a block of (up to) 2x2 cells, preferring one that contains a 

438 # missing cell so the sparse-grid path is exercised. Falls back to the 

439 # first available block when the coadd is fully dense. 

440 block = cell_coadd[_choose_block_bbox(cell_coadd)] 

441 

442 grid = block.grid 

443 cs = grid.cell_shape 

444 start = block.bounds.subgrid_start 

445 stop = block.bounds.subgrid_stop 

446 n_i = stop.i - start.i 

447 n_j = stop.j - start.j 

448 

449 # 2. Build a tiny full-patch grid with the same cell *count* as the 

450 # original patch but ``cell_size`` pixels per cell, anchored at (0, 0). 

451 full_shape = grid.grid_size 

452 new_grid = CellGrid( 

453 bbox=Box.factory[0 : full_shape.i * cell_size, 0 : full_shape.j * cell_size], 

454 cell_shape=YX(y=cell_size, x=cell_size), 

455 ) 

456 new_block_bbox = _scale_box_to_grid(block.bbox, grid, cell_size) 

457 new_bounds = CellGridBounds(grid=new_grid, bbox=new_block_bbox, missing=block.bounds.missing) 

458 

459 # 3. Decimate each plane. Because the block's planes tile the kept cells 

460 # contiguously, a uniform stride that maps one native cell onto 

461 # ``cell_size`` samples is equivalent to per-cell decimation. 

462 step_y = max(1, cs.y // cell_size) 

463 step_x = max(1, cs.x // cell_size) 

464 ny = n_i * cell_size 

465 nx = n_j * cell_size 

466 

467 def shrink2d(array: np.ndarray) -> np.ndarray: 

468 return np.ascontiguousarray(array[::step_y, ::step_x][:ny, :nx]) 

469 

470 def shrink3d(array: np.ndarray) -> np.ndarray: 

471 return np.ascontiguousarray(array[::step_y, ::step_x, :][:ny, :nx, :]) 

472 

473 # 4. Synthetic-but-valid sky_projection over the tiny tract frame. 

474 rng = np.random.default_rng(0) 

475 tract_frame = TractFrame(skymap=cell_coadd.skymap, tract=cell_coadd.tract, bbox=new_grid.bbox) 

476 sky_projection = make_random_sky_projection(rng, tract_frame, new_block_bbox) 

477 

478 unit = cell_coadd.unit 

479 image = Image(shrink2d(block.image.array), bbox=new_block_bbox, unit=unit, sky_projection=sky_projection) 

480 mask = Mask(shrink3d(block.mask.array), schema=block.mask.schema, bbox=new_block_bbox) 

481 variance = Image(shrink2d(block.variance.array), bbox=new_block_bbox, unit=unit**2) 

482 mask_fractions = { 

483 name: Image(shrink2d(plane.array), bbox=new_block_bbox) 

484 for name, plane in block.mask_fractions.items() 

485 } 

486 noise_realizations = [ 

487 Image(shrink2d(plane.array), bbox=new_block_bbox) for plane in block.noise_realizations 

488 ] 

489 

490 # 5. Crop the PSF kernels to a small odd window about their centre, 

491 # keeping the (n_i, n_j) per-cell structure and NaN-for-missing cells. 

492 psf_array = block.psf._array 

493 ky, kx = psf_array.shape[2:] 

494 half = kernel_size // 2 

495 cy, cx = ky // 2, kx // 2 

496 psf_array = np.ascontiguousarray(psf_array[:, :, cy - half : cy + half + 1, cx - half : cx + half + 1]) 

497 psf = CellPointSpreadFunction(psf_array, bounds=new_bounds) 

498 

499 # 6. Patch geometry scaled onto the tiny grid; provenance and backgrounds 

500 # are reused as-is (provenance is cell-indexed and already subset). 

501 patch = PatchDefinition( 

502 id=block.patch.id, 

503 index=block.patch.index, 

504 inner_bbox=_scale_box_to_grid(block.patch.inner_bbox, grid, cell_size), 

505 cells=new_grid, 

506 ) 

507 

508 provenance = block._provenance 

509 if provenance is not None: 

510 provenance = _trim_provenance(provenance, max_inputs=max_inputs) 

511 

512 # Aperture corrections are not subset when CellCoadd is subset with a 

513 # bounding box, because they're always tiny. But that makes setting 

514 # up a consistent new grid for them tricky. Names that carry no usable 

515 # value anywhere (None, serialized as an all-NaN column) are kept, so the 

516 # fixture exercises more code paths. 

517 aperture_corrections: dict[str, CellField | None] = {} 

518 new_apcorr_bounds = None 

519 n_usable = 0 

520 n_unusable = 0 

521 for name, field in block.aperture_corrections.items(): 

522 if field is None: 

523 if n_unusable < _MAX_UNUSABLE_APERTURE_CORRECTIONS: 

524 aperture_corrections[name] = None 

525 n_unusable += 1 

526 elif n_usable < _MAX_USABLE_APERTURE_CORRECTIONS: 

527 if new_apcorr_bounds is None: 

528 new_apcorr_bounds = CellGridBounds( 

529 grid=new_grid, 

530 bbox=_scale_box_to_grid(field.bounds.bbox, grid, cell_size), 

531 missing=cell_coadd.bounds.missing, 

532 ) 

533 aperture_corrections[name] = CellField(new_apcorr_bounds, field._array) 

534 n_usable += 1 

535 if n_usable >= _MAX_USABLE_APERTURE_CORRECTIONS and ( 

536 n_unusable >= _MAX_UNUSABLE_APERTURE_CORRECTIONS 

537 ): 

538 break 

539 

540 return CellCoadd( 

541 image, 

542 mask=mask, 

543 variance=variance, 

544 mask_fractions=mask_fractions, 

545 noise_realizations=noise_realizations, 

546 sky_projection=sky_projection, 

547 band=block.band, 

548 psf=psf, 

549 patch=patch, 

550 provenance=provenance, 

551 backgrounds=block._backgrounds, 

552 aperture_corrections=aperture_corrections, 

553 ) 

554 

555 

556def _trim_provenance(provenance: CoaddProvenance, *, max_inputs: int) -> CoaddProvenance: 

557 """Cap the provenance ``inputs`` table to ``max_inputs`` rows and drop any 

558 contributions that reference the removed inputs. 

559 

560 The two-table structure, polygon arrays and string dictionary-compression 

561 paths are all preserved; only the number of contributing visits shrinks. 

562 """ 

563 inputs = provenance.inputs 

564 if len(inputs) <= max_inputs: 

565 return provenance 

566 kept_inputs = inputs[:max_inputs] 

567 keys = {(str(row["instrument"]), int(row["visit"]), int(row["detector"])) for row in kept_inputs} 

568 contributions = provenance.contributions 

569 mask = np.array( 

570 [ 

571 (str(instrument), int(visit), int(detector)) in keys 

572 for instrument, visit, detector in zip( 

573 contributions["instrument"], contributions["visit"], contributions["detector"] 

574 ) 

575 ], 

576 dtype=bool, 

577 ) 

578 return CoaddProvenance(inputs=kept_inputs, contributions=contributions[mask]) 

579 

580 

581def _choose_block_bbox(cell_coadd: CellCoadd) -> Box: 

582 """Return the pixel bbox of a (up to) 2x2 block of cells to keep. 

583 

584 Prefers a block containing a missing cell; otherwise the block anchored at 

585 the start of the populated region. Never raises if there is no missing 

586 cell. 

587 """ 

588 bounds = cell_coadd.bounds 

589 grid = bounds.grid 

590 start = bounds.subgrid_start 

591 stop = bounds.subgrid_stop 

592 span_i = min(2, stop.i - start.i) 

593 span_j = min(2, stop.j - start.j) 

594 

595 target = next(iter(sorted(bounds.missing)), None) 

596 if target is not None: 

597 # Anchor the block so it includes the missing cell, clamped to the 

598 # populated index range. 

599 i0 = min(max(target.i, start.i), stop.i - span_i) 

600 j0 = min(max(target.j, start.j), stop.j - span_j) 

601 else: 

602 i0 = start.i 

603 j0 = start.j 

604 

605 lo = grid.bbox_of(CellIJ(i=i0, j=j0)) 

606 hi = grid.bbox_of(CellIJ(i=i0 + span_i - 1, j=j0 + span_j - 1)) 

607 return Box.factory[lo.y.start : hi.y.stop, lo.x.start : hi.x.stop] 

608 

609 

610def _scale_box_to_grid(box: Box, grid: CellGrid, cell_size: int) -> Box: 

611 """Map a grid-aligned box onto a grid with ``cell_size`` pixels per cell, 

612 anchored at the origin. 

613 """ 

614 cs = grid.cell_shape 

615 s = grid.bbox.start 

616 iy0 = (box.y.start - s.y) // cs.y 

617 iy1 = (box.y.stop - s.y) // cs.y 

618 ix0 = (box.x.start - s.x) // cs.x 

619 ix1 = (box.x.stop - s.x) // cs.x 

620 return Box.factory[iy0 * cell_size : iy1 * cell_size, ix0 * cell_size : ix1 * cell_size]