Coverage for python/lsst/images/cells/_coadd.py: 66%

294 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__ = ("CellCoadd", "CellCoaddSerializationModel") 

15 

16import functools 

17from collections.abc import Mapping, Sequence 

18from types import EllipsisType 

19from typing import TYPE_CHECKING, Any, ClassVar, cast 

20 

21import astropy.io.fits 

22import astropy.units 

23import astropy.wcs 

24import numpy as np 

25import pydantic 

26 

27from .._backgrounds import BackgroundMap, BackgroundMapSerializationModel 

28from .._cell_grid import CellGrid, CellGridBounds, PatchDefinition 

29from .._geom import YX, Box 

30from .._image import Image, ImageSerializationModel 

31from .._mask import ( 

32 Mask, 

33 MaskPlane, 

34 MaskSchema, 

35 MaskSerializationModel, 

36 get_legacy_deep_coadd_mask_planes, 

37 get_legacy_non_cell_coadd_mask_planes, 

38) 

39from .._masked_image import MaskedImage, MaskedImageSerializationModel 

40from .._transforms import SkyProjection, SkyProjectionSerializationModel, TractFrame 

41from ..describe import DescribeOptions, FieldRole, Report, ReportField 

42from ..fields import BaseField, field_from_legacy_photo_calib 

43from ..serialization import InputArchive, InvalidParameterError, OutputArchive 

44from ._aperture_corrections import ( 

45 CellApertureCorrectionMapSerializationModel, 

46 CellField, 

47 approximate_aperture_corrections_from_legacy, 

48) 

49from ._provenance import CoaddProvenance, CoaddProvenanceSerializationModel 

50from ._psf import CellPointSpreadFunction, CellPointSpreadFunctionSerializationModel 

51 

52if TYPE_CHECKING: 

53 try: 

54 from lsst.afw.image import Exposure as LegacyExposure 

55 from lsst.cell_coadds import MultipleCellCoadd as LegacyMultipleCellCoadd 

56 from lsst.skymap import TractInfo 

57 except ImportError: 

58 type LegacyExposure = Any # type: ignore[no-redef] 

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

60 type TractInfo = Any # type: ignore[no-redef] 

61 

62 

63class CellCoadd(MaskedImage): 

64 """A coadd comprised of cells on a regular grid. 

65 

66 Parameters 

67 ---------- 

68 image 

69 The main image plane. If this has a `.SkyProjection`, it will be used 

70 for all planes unless a ``sky_projection`` is passed separately. 

71 mask 

72 A bitmask image that annotates the main image plane. Must have the 

73 same bounding box as ``image`` if provided. Any attached 

74 ``sky_projection`` is replaced (possibly by `None`). 

75 variance 

76 The per-pixel uncertainty of the main image as an image of variance 

77 values. Must have the same bounding box as ``image`` if provided, and 

78 its units must be the square of ``image.unit`` or `None`. 

79 Values default to ``1.0``. Any attached ``sky_projection`` is replaced 

80 (possibly by `None`). 

81 mask_fractions 

82 A mapping from an input-image mask plane name to an image of the 

83 weights sums of that plane. 

84 noise_realizations 

85 A sequence of images with Monte Carlo realizations of the noise in 

86 the coadd. 

87 mask_schema 

88 Schema for the mask plane. Must be provided if and only if ``mask`` is 

89 not provided. 

90 sky_projection 

91 Projection that maps the pixel grid to the sky. Can only be `None` if 

92 a projection is already attached to ``image``. 

93 band 

94 Name of the band. 

95 psf 

96 Effective point-spread function for the coadd. The missing cells 

97 reported by ``psf.bounds`` are assumed to apply to all image data for 

98 that cell as well (i.e. there is a PSF for a cell if and only if 

99 there is image data for that cell). 

100 aperture_corrections 

101 Aperture corrections for different photometry algorithms. A name that 

102 maps to `None` has no usable value in any cell. 

103 patch 

104 Identifiers and geometry of the full patch, if the image is confined 

105 to a single patch. When present, the cell grid of the PSF and 

106 provenance (if provideD) must be the full patch grid, even if its 

107 bounds select a subset of that area. 

108 provenance 

109 Information about the images that went into the coadd. 

110 backgrounds 

111 Background models associated with this image. 

112 """ 

113 

114 def __init__( 

115 self, 

116 image: Image, 

117 *, 

118 mask: Mask | None = None, 

119 variance: Image | None = None, 

120 mask_fractions: Mapping[str, Image] | None = None, 

121 noise_realizations: Sequence[Image] = (), 

122 mask_schema: MaskSchema | None = None, 

123 sky_projection: SkyProjection[TractFrame] | None = None, 

124 band: str | None = None, 

125 psf: CellPointSpreadFunction, 

126 aperture_corrections: Mapping[str, CellField | None] | None = None, 

127 patch: PatchDefinition | None = None, 

128 provenance: CoaddProvenance | None = None, 

129 backgrounds: BackgroundMap | None = None, 

130 ) -> None: 

131 super().__init__( 

132 image, 

133 mask=mask, 

134 variance=variance, 

135 mask_schema=mask_schema, 

136 sky_projection=sky_projection, 

137 ) 

138 if self.image.unit is None: 138 ↛ 139line 138 didn't jump to line 139 because the condition on line 138 was never true

139 raise TypeError("The image component of a CellCoadd must have units.") 

140 if self.image.sky_projection is None: 140 ↛ 141line 140 didn't jump to line 141 because the condition on line 140 was never true

141 raise TypeError("The sky_projection component of a CellCoadd cannot be None.") 

142 if not isinstance(self.image.sky_projection.pixel_frame, TractFrame): 142 ↛ 143line 142 didn't jump to line 143 because the condition on line 142 was never true

143 raise TypeError("The sky_projection's pixel frame must be a TractFrame for CellCoadd.") 

144 self._mask_fractions = dict(mask_fractions) if mask_fractions is not None else {} 

145 self._noise_realizations = list(noise_realizations) 

146 self._band = band 

147 if psf.bounds.bbox != self.bbox: 

148 psf = psf[self.bbox.intersection(psf.bounds.bbox)] 

149 self._psf = psf 

150 self._aperture_corrections = dict(aperture_corrections) if aperture_corrections is not None else {} 

151 for ap_corr_name, ap_corr_field in self._aperture_corrections.items(): 

152 if ap_corr_field is not None and ap_corr_field.bounds.grid != self.grid: 152 ↛ 153line 152 didn't jump to line 153 because the condition on line 152 was never true

153 raise ValueError( 

154 f"Grids for cell PSF and {ap_corr_name} aperture corrections are not consistent." 

155 ) 

156 self._patch = patch 

157 self._provenance = provenance 

158 if self._provenance and not self._patch: 158 ↛ 159line 158 didn't jump to line 159 because the condition on line 158 was never true

159 raise TypeError("A CellCoadd cannot carry provenance without a patch definition.") 

160 self._backgrounds = backgrounds if backgrounds is not None else BackgroundMap() 

161 

162 @property 

163 def skymap(self) -> str: 

164 """Name of the skymap (`str`).""" 

165 return self.sky_projection.pixel_frame.skymap 

166 

167 @property 

168 def tract(self) -> int: 

169 """ID of the tract (`int`).""" 

170 return self.sky_projection.pixel_frame.tract 

171 

172 @property 

173 def patch(self) -> PatchDefinition: 

174 """Identifiers and geometry of the full patch, if the image is confined 

175 to a single patch (`PatchDefinition`). 

176 """ 

177 if self._patch is None: 

178 raise AttributeError("Coadd has no patch information.") 

179 return self._patch 

180 

181 @property 

182 def band(self) -> str | None: 

183 """Name of the band (`str` or `None`).""" 

184 return self._band 

185 

186 @property 

187 def mask_fractions(self) -> Mapping[str, Image]: 

188 """A mapping from an input-image mask plane name to an image of the 

189 weights sums of that plane 

190 (`~collections.abc.Mapping` [`str`, `.Image`]). 

191 """ 

192 return self._mask_fractions 

193 

194 @property 

195 def noise_realizations(self) -> Sequence[Image]: 

196 """A sequence of images with Monte Carlo realizations of the noise in 

197 the coadd (`~collections.abc.Sequence` [`.Image`]). 

198 """ 

199 return self._noise_realizations 

200 

201 @property 

202 def unit(self) -> astropy.units.UnitBase: 

203 """The units of the image plane (`astropy.units.Unit`).""" 

204 return cast(astropy.units.UnitBase, super().unit) 

205 

206 @property 

207 def sky_projection(self) -> SkyProjection[TractFrame]: 

208 """The projection that maps the pixel grid to the sky 

209 (`.SkyProjection` [`.TractFrame`]). 

210 """ 

211 return cast(SkyProjection[TractFrame], super().sky_projection) 

212 

213 @property 

214 def psf(self) -> CellPointSpreadFunction: 

215 """Effective point-spread function for the coadd 

216 (`CellPointSpreadFunction`). 

217 """ 

218 return self._psf 

219 

220 @property 

221 def aperture_corrections(self) -> Mapping[str, CellField | None]: 

222 """Aperture corrections for different photometry algorithms 

223 (`dict` [`str`, `CellField` | `None`]). A name that maps to `None` 

224 has no usable value in any cell. 

225 """ 

226 return self._aperture_corrections 

227 

228 @property 

229 def bounds(self) -> CellGridBounds: 

230 """The grid of cells that overlap this coadd and a set of missing 

231 cells (`CellGridBounds`). 

232 """ 

233 return self._psf.bounds 

234 

235 @property 

236 def grid(self) -> CellGrid: 

237 """The grid of cells that overlap this coadd (`CellGrid`).""" 

238 return self._psf.bounds.grid 

239 

240 @property 

241 def provenance(self) -> CoaddProvenance: 

242 """Information about the images that went into the coadd 

243 (`CoaddProvenance` or `None`). 

244 """ 

245 if self._provenance is None: 

246 raise AttributeError("Coadd has no provenance information.") 

247 return self._provenance 

248 

249 @property 

250 def backgrounds(self) -> BackgroundMap: 

251 """A mapping of backgrounds associated with this image 

252 (`.BackgroundMap`). 

253 """ 

254 return self._backgrounds 

255 

256 def __getitem__(self, bbox: Box | EllipsisType) -> CellCoadd: 

257 bbox, _ = self._handle_getitem_args(bbox) 

258 psf = self.psf[bbox] 

259 return self._transfer_metadata( 

260 CellCoadd( 

261 self.image[bbox], 

262 mask=self.mask[bbox], 

263 variance=self.variance[bbox], 

264 sky_projection=self.sky_projection, 

265 mask_fractions={k: v[bbox] for k, v in self._mask_fractions.items()}, 

266 noise_realizations=[v[bbox] for v in self._noise_realizations], 

267 band=self.band, 

268 psf=psf, 

269 patch=self._patch, 

270 provenance=( 

271 self._provenance.subset(psf.bounds.cell_indices()) 

272 if self._provenance is not None 

273 else None 

274 ), 

275 backgrounds=self._backgrounds, 

276 aperture_corrections=self._aperture_corrections.copy(), 

277 ), 

278 bbox=bbox, 

279 ) 

280 

281 def _describe(self, options: DescribeOptions = DescribeOptions(), /) -> Report: 

282 """Return a `Report` describing this cell coadd. 

283 

284 Parameters 

285 ---------- 

286 options : `DescribeOptions`, optional 

287 Rendering options; forwarded to all children. 

288 """ 

289 fields = [ 

290 ReportField(label="skymap", value=self.skymap, role=FieldRole.DERIVED), 

291 ReportField(label="tract", value=self.tract, role=FieldRole.DERIVED), 

292 ReportField(label="patch", value=self._patch, role=FieldRole.DERIVED), 

293 ReportField(label="band", value=self.band, role=FieldRole.DERIVED), 

294 ReportField(label="bbox", value=self.bbox, repr_value=repr(self.bbox), role=FieldRole.DERIVED), 

295 ] 

296 summary = f"CellCoadd({self.bbox!s}, tract={self.tract})" 

297 if options.brief: 

298 return Report(type_name="CellCoadd", summary=summary, fields=fields) 

299 # Components with no report of their own get a line each, so that 

300 # nothing the coadd carries is absent from its description. 

301 if self._mask_fractions: 

302 fields.append( 

303 ReportField( 

304 label="mask_fractions", value=", ".join(self._mask_fractions), role=FieldRole.DERIVED 

305 ) 

306 ) 

307 if self._noise_realizations: 

308 n_noise = len(self._noise_realizations) 

309 fields.append( 

310 ReportField( 

311 label="noise_realizations", 

312 value=( 

313 f"{n_noise} image{'s' if n_noise != 1 else ''} " 

314 f"(dtype {self._noise_realizations[0].array.dtype})" 

315 ), 

316 role=FieldRole.DERIVED, 

317 ) 

318 ) 

319 if self._aperture_corrections: 

320 n_ap_corr = len(self._aperture_corrections) 

321 # Never print all the keys even in detailed mode since there 

322 # are usually many of them and they swamp the report. 

323 ap_corr = f"{n_ap_corr} field{'s' if n_ap_corr != 1 else ''}" 

324 fields.append(ReportField(label="aperture_corrections", value=ap_corr, role=FieldRole.DERIVED)) 

325 if self._provenance is None: 

326 # A coadd without provenance is a meaningful state: it is what 

327 # reading with provenance=False gives, and it is what makes 

328 # to_legacy_cell_coadd fail. 

329 fields.append(ReportField(label="provenance", value="none", role=FieldRole.DERIVED)) 

330 child = options.for_child() 

331 plane = options.for_child("sky_projection", "bbox") 

332 children: dict[str, Report] = { 

333 "image": self.image._describe(plane), 

334 "mask": self.mask._describe(plane), 

335 "variance": self.variance._describe(plane), 

336 "sky_projection": self.sky_projection._describe(child, bbox=self.bbox), 

337 "psf": self.psf._describe(child), 

338 } 

339 if self._provenance is not None: 

340 # The provenance property raises when there is none. Its cells 

341 # come from this coadd, so pass them down for the coverage ratio. 

342 children["provenance"] = self._provenance._describe(child, bounds=self.bounds) 

343 children["backgrounds"] = self.backgrounds._describe(child) 

344 return Report( 

345 type_name="CellCoadd", 

346 summary=summary, 

347 fields=fields, 

348 children=children, 

349 ) 

350 

351 def copy(self) -> CellCoadd: 

352 """Deep-copy the coadd.""" 

353 return self._transfer_metadata( 

354 CellCoadd( 

355 image=self._image.copy(), 

356 mask=self._mask.copy(), 

357 variance=self._variance.copy(), 

358 sky_projection=self.sky_projection, 

359 mask_fractions={k: v.copy() for k, v in self._mask_fractions.items()}, 

360 noise_realizations=[v.copy() for v in self._noise_realizations], 

361 band=self.band, 

362 psf=self.psf, 

363 patch=self._patch, 

364 provenance=self._provenance, 

365 backgrounds=self._backgrounds.copy(), 

366 aperture_corrections=self._aperture_corrections.copy(), 

367 ), 

368 copy=True, 

369 ) 

370 

371 def apply_background(self, name: str | None) -> None: 

372 """Subtract the background with the given name, modifying the image 

373 in place. 

374 

375 If ``name`` is `None`, restore the original background. 

376 

377 Parameters 

378 ---------- 

379 name 

380 Name of the background to subtract, or `None` to restore the 

381 original background. 

382 """ 

383 current_bg = self.backgrounds.subtracted 

384 if current_bg is not None and name == current_bg.name: 384 ↛ 385line 384 didn't jump to line 385 because the condition on line 384 was never true

385 return 

386 

387 adjustment: astropy.units.Quantity | None = None 

388 if current_bg is not None: 

389 adjustment = current_bg.field.render(self.bbox, dtype=self.image.array.dtype).quantity 

390 if name is not None: 

391 new_bg = self.backgrounds[name] 

392 new_values = new_bg.field.render(self.bbox, dtype=self.image.array.dtype).quantity 

393 adjustment = -new_values if adjustment is None else adjustment - new_values 

394 

395 # Resolve and render every model before changing either pixels or 

396 # state. Computing one combined adjustment also ensures a failed unit 

397 # conversion cannot leave a previously subtracted background restored 

398 # while the map still says it is subtracted. 

399 if adjustment is not None: 399 ↛ 401line 399 didn't jump to line 401 because the condition on line 399 was always true

400 self.image.quantity += adjustment 

401 self._backgrounds._subtracted = name 

402 

403 def serialize(self, archive: OutputArchive[Any]) -> CellCoaddSerializationModel: 

404 """Serialize the image to an output archive. 

405 

406 Parameters 

407 ---------- 

408 archive 

409 Archive to write to. 

410 """ 

411 serialized_image = archive.serialize_direct( 

412 "image", 

413 functools.partial(self.image.serialize, save_projection=False, tile_shape=self.grid.cell_shape), 

414 ) 

415 serialized_mask = archive.serialize_direct( 

416 "mask", 

417 functools.partial(self.mask.serialize, save_projection=False, tile_shape=self.grid.cell_shape), 

418 ) 

419 serialized_variance = archive.serialize_direct( 

420 "variance", 

421 functools.partial( 

422 self.variance.serialize, save_projection=False, tile_shape=self.grid.cell_shape 

423 ), 

424 ) 

425 serialized_projection = archive.serialize_direct("sky_projection", self.sky_projection.serialize) 

426 serialized_mask_fractions = { 

427 k: archive.serialize_direct( 

428 f"mask_fractions/{k}", 

429 functools.partial( 

430 v.serialize, 

431 save_projection=False, 

432 tile_shape=self.grid.cell_shape, 

433 options_name="mask_fractions", 

434 ), 

435 ) 

436 for k, v in self.mask_fractions.items() 

437 } 

438 serialized_noise_realizations = [ 

439 archive.serialize_direct( 

440 f"noise_realizations/{n}", 

441 functools.partial( 

442 v.serialize, save_projection=False, tile_shape=self.grid.cell_shape, options_name="image" 

443 ), 

444 ) 

445 for n, v in enumerate(self.noise_realizations) 

446 ] 

447 serialized_psf = archive.serialize_direct("psf", self.psf.serialize) 

448 serialized_aperture_corrections = archive.serialize_direct( 

449 "aperture_corrections", 

450 functools.partial( 

451 CellApertureCorrectionMapSerializationModel.serialize, self.aperture_corrections 

452 ), 

453 ) 

454 serialized_provenance = ( 

455 archive.serialize_direct("provenance", self._provenance.serialize) 

456 if self._provenance is not None 

457 else None 

458 ) 

459 serialized_backgrounds = archive.serialize_direct("background", self._backgrounds.serialize) 

460 return CellCoaddSerializationModel( 

461 image=serialized_image, 

462 mask=serialized_mask, 

463 variance=serialized_variance, 

464 sky_projection=serialized_projection, 

465 mask_fractions=serialized_mask_fractions, 

466 noise_realizations=serialized_noise_realizations, 

467 band=self._band, 

468 psf=serialized_psf, 

469 aperture_corrections=serialized_aperture_corrections, 

470 patch=self._patch, 

471 provenance=serialized_provenance, 

472 backgrounds=serialized_backgrounds, 

473 metadata=self._metadata, 

474 ) 

475 

476 @staticmethod 

477 def _get_archive_tree_type[P: pydantic.BaseModel]( 

478 pointer_type: type[P], 

479 ) -> type[CellCoaddSerializationModel[P]]: 

480 """Return the serialization model type for this object for an archive 

481 type that uses the given pointer type. 

482 """ 

483 return CellCoaddSerializationModel[pointer_type] # type: ignore 

484 

485 @staticmethod 

486 def from_legacy_cell_coadd( 

487 legacy: LegacyMultipleCellCoadd, 

488 *, 

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

490 tract_info: TractInfo, 

491 bbox: Box | None = None, 

492 ) -> CellCoadd: 

493 """Convert from a `lsst.cell_coadds.MultipleCellCoadd` instance. 

494 

495 Parameters 

496 ---------- 

497 legacy 

498 A `lsst.cell_coadds.MultipleCellCoadd` instance to convert. 

499 plane_map 

500 A mapping from legacy mask plane name to the new plane name and 

501 description. 

502 tract_info 

503 Information about the full tract. 

504 bbox 

505 Bounding box of the image. The default is to include just the 

506 bounding box of the valid cells, which may not cover a full patch. 

507 """ 

508 from lsst.geom import Box2I 

509 

510 if plane_map is None: 

511 plane_map = get_legacy_deep_coadd_mask_planes() 

512 if bbox is None: 

513 legacy_bbox = Box2I() 

514 for single_cell in legacy.cells.values(): 

515 legacy_bbox.include(single_cell.inner.bbox) 

516 else: 

517 legacy_bbox = bbox.to_legacy() 

518 legacy_stitched = legacy.stitch(legacy_bbox) 

519 unit = astropy.units.Unit(legacy.units.value) 

520 tract_bbox = Box.from_legacy(tract_info.getBBox()) 

521 sky_projection = SkyProjection.from_legacy( 

522 legacy.wcs, 

523 TractFrame( 

524 skymap=legacy.identifiers.skymap, 

525 tract=legacy.identifiers.tract, 

526 bbox=tract_bbox, 

527 ), 

528 pixel_bounds=tract_bbox, 

529 ) 

530 band = legacy.identifiers.band 

531 image = Image.from_legacy(legacy_stitched.image, unit=unit) 

532 mask = Mask.from_legacy(legacy_stitched.mask, plane_map=plane_map) 

533 variance = Image.from_legacy(legacy_stitched.variance, unit=unit**2) 

534 noise_realizations = [ 

535 Image.from_legacy(noise_image) for noise_image in legacy_stitched.noise_realizations 

536 ] 

537 mask_fractions = ( 

538 {"rejected": Image.from_legacy(legacy_stitched.mask_fractions)} 

539 if legacy_stitched.mask_fractions is not None 

540 else {} 

541 ) 

542 psf = CellPointSpreadFunction.from_legacy(legacy_stitched.psf, image.bbox) 

543 aperture_corrections = { 

544 ap_corr_name: CellField.from_legacy_aperture_correction(legacy_ap_corr, psf.bounds) 

545 for ap_corr_name, legacy_ap_corr in legacy_stitched.ap_corr_map.items() 

546 } 

547 patch_info = tract_info[legacy.identifiers.patch] 

548 patch = PatchDefinition( 

549 id=patch_info.getSequentialIndex(), 

550 index=YX(y=legacy.identifiers.patch.y, x=legacy.identifiers.patch.x), 

551 inner_bbox=Box.from_legacy(patch_info.getInnerBBox()), 

552 cells=CellGrid.from_legacy(legacy.grid), 

553 ) 

554 provenance = CoaddProvenance.from_legacy(legacy) 

555 return CellCoadd( 

556 image=image, 

557 mask=mask, 

558 variance=variance, 

559 mask_fractions=mask_fractions, 

560 noise_realizations=noise_realizations, 

561 sky_projection=sky_projection, 

562 band=band, 

563 psf=psf, 

564 aperture_corrections=aperture_corrections, 

565 patch=patch, 

566 provenance=provenance, 

567 ) 

568 

569 def to_legacy_cell_coadd( 

570 self, copy: bool | None = None, plane_map: Mapping[str, MaskPlane] | None = None 

571 ) -> LegacyMultipleCellCoadd: 

572 """Convert to a `lsst.cell_coadds.MultipleCellCoadd` instance. 

573 

574 Parameters 

575 ---------- 

576 copy 

577 If `True`, always copy the image and variance pixel data. 

578 If `False`, return a view, and raise `TypeError` if the pixel data 

579 is read-only (this is not supported by afw). If `None`, only copy 

580 if the pixel data is read-only. Mask pixel data is always copied. 

581 plane_map 

582 A mapping from legacy mask plane name to the new plane name and 

583 description. 

584 """ 

585 from frozendict import frozendict 

586 

587 from lsst.cell_coadds import CellIdentifiers as LegacyCellIdentifiers 

588 from lsst.cell_coadds import CoaddUnits as LegacyCoaddUnits 

589 from lsst.cell_coadds import CommonComponents as LegacyCommonComponents 

590 from lsst.cell_coadds import MultipleCellCoadd as LegacyMultipleCellCoadd 

591 from lsst.cell_coadds import OwnedImagePlanes as LegacyOwnedImagePlanes 

592 from lsst.cell_coadds import PatchIdentifiers as LegacyPatchIdentifiers 

593 from lsst.cell_coadds import SingleCellCoadd as LegacySingleCellCoadd 

594 from lsst.skymap import Index2D as LegacyIndex2D 

595 

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

597 plane_map = get_legacy_deep_coadd_mask_planes() 

598 if self.unit != astropy.units.nJy: 598 ↛ 599line 598 didn't jump to line 599 because the condition on line 598 was never true

599 raise ValueError("CellCoadd.to_legacy requires nJy pixel units.") 

600 legacy_grid = self.grid.to_legacy() 

601 visit_polygons = self.provenance.to_legacy_polygon_map() 

602 legacy_common = LegacyCommonComponents( 

603 units=LegacyCoaddUnits.nJy, 

604 wcs=self.sky_projection.to_legacy(), 

605 band=self.band, 

606 identifiers=LegacyPatchIdentifiers( 

607 self.skymap, 

608 self.tract, 

609 LegacyIndex2D(x=self.patch.index.x, y=self.patch.index.y), 

610 band=self.band, 

611 ), 

612 visit_polygons=visit_polygons, 

613 ) 

614 legacy_inputs = self.provenance.to_legacy_cell_coadd_inputs(visit_polygons.keys()) 

615 cells: list[LegacySingleCellCoadd] = [] 

616 for cell_index in self.bounds.cell_indices(): 

617 cell_bbox = self.grid.bbox_of(cell_index) 

618 if not self.bbox.contains(cell_bbox): 618 ↛ 619line 618 didn't jump to line 619 because the condition on line 618 was never true

619 raise ValueError( 

620 f"MultipleCellCoadd requires full cells; cell {cell_index} " 

621 f"with bbox {cell_bbox} is not within {self.bbox}." 

622 ) 

623 # Legacy type only has room for one mask_fractions plane. 

624 legacy_mask_fractions = ( 

625 next(iter(self.mask_fractions.values()))[cell_bbox].to_legacy(copy=copy) 

626 if self.mask_fractions 

627 else None 

628 ) 

629 legacy_planes = LegacyOwnedImagePlanes( 

630 image=self.image[cell_bbox].to_legacy(copy=copy), 

631 mask=self.mask[cell_bbox].to_legacy(plane_map), 

632 variance=self.variance[cell_bbox].to_legacy(copy=copy), 

633 mask_fractions=legacy_mask_fractions, 

634 noise_realizations=[n[cell_bbox].to_legacy(copy=copy) for n in self.noise_realizations], 

635 ) 

636 legacy_aperture_correction_map = frozendict( 

637 { 

638 name: field.value_in_cell(cell_index) 

639 if field is not None and cell_index not in field.bounds.missing 

640 else np.nan 

641 for name, field in self.aperture_corrections.items() 

642 } 

643 ) 

644 cells.append( 

645 LegacySingleCellCoadd( 

646 legacy_planes, 

647 psf=self.psf[cell_index].to_legacy(copy=copy), 

648 inner_bbox=cell_bbox.to_legacy(), 

649 common=legacy_common, 

650 inputs=legacy_inputs[cell_index.to_legacy()], 

651 identifiers=LegacyCellIdentifiers( 

652 self.skymap, 

653 self.tract, 

654 legacy_common.identifiers.patch, 

655 band=self.band, 

656 cell=cell_index.to_legacy(), 

657 ), 

658 aperture_correction_map=legacy_aperture_correction_map, 

659 ) 

660 ) 

661 return LegacyMultipleCellCoadd( 

662 cells, 

663 legacy_grid, 

664 outer_cell_size=self.grid.cell_shape.to_legacy_int_extent(), 

665 psf_image_size=self.psf.kernel_bbox.shape.to_legacy_int_extent(), 

666 common=legacy_common, 

667 inner_bbox=self.bbox.to_legacy(), 

668 ) 

669 

670 @staticmethod 

671 def from_legacy_lazy_coadd( 

672 legacy: LegacyExposure, 

673 *, 

674 instrument: str, 

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

676 tract_info: TractInfo, 

677 skymap: str | None = None, 

678 patch: int | None = None, 

679 band: str | None = None, 

680 ) -> CellCoadd: 

681 """Convert from a `lsst.afw.image.Exposure` instance with a lazy 

682 PSF and/or aperture corrections. 

683 

684 This approximates the given image's PSF and aperture corrections by 

685 evaluating them at cell centers and assuming they are valid for the 

686 entirety of the cell. 

687 

688 Parameters 

689 ---------- 

690 legacy 

691 A `lsst.afw.image.Exposure` instance to convert. 

692 instrument 

693 Name of the instrument that produced all inputs to this coadd. 

694 plane_map 

695 A mapping from legacy mask plane name to the new plane name and 

696 description. 

697 tract_info 

698 Information about the full tract. 

699 skymap 

700 Name of the skymap. 

701 patch 

702 ID of the patch this coadd belongs to. 

703 band 

704 Name of the bandpass filter. 

705 """ 

706 if plane_map is None: 

707 plane_map = get_legacy_non_cell_coadd_mask_planes() 

708 legacy_md = legacy.getMetadata() 

709 if skymap is None: 

710 skymap = legacy_md.get("LSST BUTLER DATAID SKYMAP") 

711 if skymap is None: 

712 raise ValueError("No skymap name provided and no skymap name found in header.") 

713 if patch is None: 

714 patch = legacy_md.get("LSST BUTLER DATAID PATCH") 

715 if patch is None: 

716 raise ValueError("No patch ID provided and no patch ID found in header.") 

717 if band is None: 

718 band = legacy_md.get("LSST BUTLER DATAID BAND") 

719 if band is None: 

720 raise ValueError("No band name provided and no band name found in header.") 

721 tract_bbox = Box.from_legacy(tract_info.getBBox()) 

722 sky_projection = SkyProjection.from_legacy( 

723 legacy.wcs, 

724 TractFrame( 

725 skymap=skymap, 

726 tract=tract_info.getId(), 

727 bbox=tract_bbox, 

728 ), 

729 pixel_bounds=tract_bbox, 

730 ) 

731 image = Image.from_legacy(legacy.image, unit=astropy.units.nJy) 

732 if (legacy_photo_calib := legacy.getPhotoCalib()) is not None and ( 

733 field_from_legacy_photo_calib(legacy_photo_calib, image.bbox) is not None 

734 ): 

735 raise ValueError( 

736 "Legacy coadd pixels must already be calibrated to nJy (an identity PhotoCalib)." 

737 ) 

738 mask = Mask.from_legacy(legacy.mask, plane_map=plane_map) 

739 variance = Image.from_legacy(legacy.variance, unit=astropy.units.nJy**2) 

740 patch_definition = PatchDefinition.from_legacy_patch_info(tract_info[patch]) 

741 psf_bounds = CellGridBounds(grid=patch_definition.cells, bbox=patch_definition.cells.bbox)[ 

742 Box.from_legacy(legacy.getBBox()) 

743 ] 

744 psf = CellPointSpreadFunction.approximate_from_legacy(legacy.psf, psf_bounds) 

745 aperture_corrections = approximate_aperture_corrections_from_legacy( 

746 legacy.info.getApCorrMap(), psf.bounds 

747 ) 

748 provenance = CoaddProvenance.from_legacy_lazy( 

749 legacy.info.getCoaddInputs(), 

750 bounds=psf.bounds, 

751 sky_projection=sky_projection, 

752 instrument=instrument, 

753 ) 

754 return CellCoadd( 

755 image=image, 

756 mask=mask, 

757 variance=variance, 

758 mask_fractions={}, 

759 noise_realizations=[], 

760 sky_projection=sky_projection, 

761 band=band, 

762 psf=psf, 

763 aperture_corrections=aperture_corrections, 

764 patch=patch_definition, 

765 provenance=provenance, 

766 ) 

767 

768 def to_legacy( 

769 self, copy: bool | None = None, plane_map: Mapping[str, MaskPlane] | None = None 

770 ) -> LegacyExposure: 

771 """Convert to a `lsst.afw.image.Exposure` instance. 

772 

773 Parameters 

774 ---------- 

775 copy 

776 If `True`, always copy the image and variance pixel data. 

777 If `False`, return a view, and raise `TypeError` if the pixel data 

778 is read-only (this is not supported by afw). If `None`, only copy 

779 if the pixel data is read-only. Mask pixel data is always copied. 

780 plane_map 

781 A mapping from legacy mask plane name to the new plane name and 

782 description. 

783 

784 Returns 

785 ------- 

786 `lsst.afw.image.Exposure` 

787 A legacy representation of the coadd. This will have its ``wcs``, 

788 ``psf``, ``filter``, ``photoCalib``, and ``metadata`` components 

789 set. The ``apCorrMap`` component is not set, because there is no 

790 true `lsst.afw.math.BoundedField` representation for cell-coadd 

791 aperture corrections, and the ``coaddInputs`` component is not set 

792 because that data structure cannot fully capture cell-coadd 

793 provenance. 

794 

795 Notes 

796 ----- 

797 This method requires the `provenance` attribute to have been populated 

798 at construction. 

799 """ 

800 from lsst.afw.image import Exposure as LegacyExposure 

801 from lsst.afw.image import FilterLabel as LegacyFilterLabel 

802 

803 if plane_map is None: 

804 plane_map = get_legacy_deep_coadd_mask_planes() 

805 legacy_masked_image = super().to_legacy(copy=copy, plane_map=plane_map) 

806 result = LegacyExposure(legacy_masked_image, dtype=self.image.array.dtype) 

807 result_info = result.info 

808 result_info.setWcs(self.sky_projection.to_legacy()) 

809 result_info.setPsf(self.psf.to_legacy()) 

810 result_info.setFilter(LegacyFilterLabel.fromBand(self.band)) 

811 result_info.setPhotoCalib(BaseField.make_legacy_photo_calib(self.unit)) 

812 # We don't do setCoaddInputs because that data structure can't really 

813 # represent cell-coadd provenance accurately, and it's not clear 

814 # anything would use it. 

815 self._fill_legacy_metadata(result_info.getMetadata()) 

816 # We can't do setApCorrMap because the legacy 

817 # StitchedApertureCorrection is not a real C++ BoundedField, just a 

818 # Python duck-alike. 

819 return result 

820 

821 

822class CellCoaddSerializationModel[P: pydantic.BaseModel](MaskedImageSerializationModel[P]): 

823 """A Pydantic model used to represent a serialized `CellCoadd`.""" 

824 

825 SCHEMA_NAME: ClassVar[str] = "cell_coadd" 

826 SCHEMA_VERSION: ClassVar[str] = "1.0.0" 

827 MIN_READ_VERSION: ClassVar[int] = 1 

828 PUBLIC_TYPE: ClassVar[type] = CellCoadd 

829 

830 # Inherited attributes are duplicated because that improves the docs 

831 # (some limitation in the sphinx/pydantic integration), and these are 

832 # important docs. 

833 

834 image: ImageSerializationModel[P] = pydantic.Field(description="The main data image.") 

835 mask: MaskSerializationModel[P] = pydantic.Field( 

836 description="Bitmask that annotates the main image's pixels." 

837 ) 

838 variance: ImageSerializationModel[P] = pydantic.Field( 

839 description="Per-pixel variance estimates for the main image." 

840 ) 

841 sky_projection: SkyProjectionSerializationModel[P] = pydantic.Field( 

842 description="Projection that maps the pixel grid to the sky.", 

843 ) 

844 mask_fractions: dict[str, ImageSerializationModel[P]] = pydantic.Field( 

845 description=( 

846 "A mapping from an input-image mask plane name to an image of the weights sums of that plane." 

847 ) 

848 ) 

849 noise_realizations: list[ImageSerializationModel[P]] = pydantic.Field( 

850 description=( 

851 "A mapping from an input-image mask plane name to an image of the weights sums of that plane." 

852 ) 

853 ) 

854 band: str | None = pydantic.Field(description="Name of the band.") 

855 psf: CellPointSpreadFunctionSerializationModel = pydantic.Field( 

856 description="Effective point-spread function model for the coadd." 

857 ) 

858 aperture_corrections: CellApertureCorrectionMapSerializationModel | None = pydantic.Field( 

859 None, description="Coadded aperture corrections for different photometry algorithms." 

860 ) 

861 patch: PatchDefinition | None = pydantic.Field(description="Identifiers and geometry for the patch.") 

862 provenance: CoaddProvenanceSerializationModel | None = pydantic.Field( 

863 description="Information about the images that went into the coadd." 

864 ) 

865 backgrounds: BackgroundMapSerializationModel = pydantic.Field( 

866 default_factory=BackgroundMapSerializationModel, 

867 description="Background models associated with this image.", 

868 ) 

869 

870 def deserialize( 

871 self, 

872 archive: InputArchive[Any], 

873 *, 

874 bbox: Box | None = None, 

875 provenance: bool = True, 

876 **kwargs: Any, 

877 ) -> CellCoadd: 

878 """Deserialize an image from an input archive. 

879 

880 Parameters 

881 ---------- 

882 archive 

883 Archive to read from. 

884 bbox 

885 Bounding box of a subimage to read instead. 

886 provenance 

887 Whether to read and attach provenance information. 

888 **kwargs 

889 Unsupported keyword arguments are accepted only to provide better 

890 error messages (raising `.serialization.InvalidParameterError`). 

891 """ 

892 if kwargs: 892 ↛ 893line 892 didn't jump to line 893 because the condition on line 892 was never true

893 raise InvalidParameterError(f"Unrecognized parameters for CellCoadd: {set(kwargs.keys())}.") 

894 masked_image = super().deserialize(archive, bbox=bbox) 

895 mask_fractions = { 

896 k.removeprefix("mask_fractions/"): v.deserialize(archive, bbox=bbox) 

897 for k, v in self.mask_fractions.items() 

898 } 

899 noise_realizations = [v.deserialize(archive, bbox=bbox) for v in self.noise_realizations] 

900 sky_projection = self.sky_projection.deserialize(archive) 

901 psf = self.psf.deserialize(archive, bbox=bbox) 

902 aperture_corrections = ( 

903 self.aperture_corrections.deserialize(archive) if self.aperture_corrections is not None else {} 

904 ) 

905 coadd_provenance: CoaddProvenance | None = None 

906 if self.provenance is not None and provenance: 906 ↛ 910line 906 didn't jump to line 910 because the condition on line 906 was always true

907 coadd_provenance = self.provenance.deserialize(archive) 

908 if bbox is not None: 

909 coadd_provenance = coadd_provenance.subset(psf.bounds.cell_indices()) 

910 backgrounds = self.backgrounds.deserialize(archive) 

911 return CellCoadd( 

912 masked_image.image, 

913 mask=masked_image.mask, 

914 variance=masked_image.variance, 

915 mask_fractions=mask_fractions, 

916 noise_realizations=noise_realizations, 

917 sky_projection=sky_projection, 

918 band=self.band, 

919 psf=psf, 

920 aperture_corrections=aperture_corrections, 

921 patch=self.patch, 

922 provenance=coadd_provenance, 

923 backgrounds=backgrounds, 

924 )._finish_deserialize(self) 

925 

926 def deserialize_component(self, component: str, archive: InputArchive[Any], **kwargs: Any) -> Any: 

927 match component: 

928 case "mask_fractions": 

929 return { 

930 name: image_model.deserialize(archive, **kwargs) 

931 for name, image_model in self.mask_fractions.items() 

932 } 

933 case "noise_realizations": 

934 return [image_model.deserialize(archive, **kwargs) for image_model in self.noise_realizations] 

935 case "aperture_corrections" if self.aperture_corrections is None: 

936 # super() delegation handles the not-None case. 

937 return {} 

938 case "masked_image": 

939 return super().deserialize(archive, **kwargs) 

940 return super().deserialize_component(component, archive, **kwargs)