Coverage for python/lsst/images/cells/_provenance.py: 60%
264 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.
12from __future__ import annotations
14__all__ = ("CoaddProvenance", "CoaddProvenanceSerializationModel")
16from collections.abc import Iterable
17from typing import TYPE_CHECKING, Any, ClassVar
19import astropy.table
20import astropy.units as u
21import numpy as np
22import pydantic
24from .._cell_grid import CellGridBounds, CellIJ
25from .._geom import XY, Box, NoOverlapError
26from .._polygon import Polygon, Region, RegionDomainError
27from .._transforms import GeneralFrame, SkyProjection
28from ..describe import DescribableMixin, DescribeOptions, FieldRole, Report, ReportField
29from ..serialization import ArchiveTree, InputArchive, InvalidParameterError, OutputArchive, TableModel
31if TYPE_CHECKING:
32 try:
33 from lsst.afw.geom import Polygon as LegacyPolygon
34 from lsst.afw.image import CoaddInputs as LegacyCoaddInputs
35 from lsst.cell_coadds import CoaddInputs as LegacyCellCoaddInputs
36 from lsst.cell_coadds import MultipleCellCoadd as LegacyMultipleCellCoadd
37 from lsst.cell_coadds import ObservationIdentifiers as LegacyObservationIdentifiers
38 from lsst.skymap import Index2D as LegacyIndex2D
39 except ImportError:
40 type LegacyIndex2D = Any # type: ignore[no-redef]
41 type LegacyCellCoaddInputs = Any # type: ignore[no-redef]
42 type LegacyCoaddInputs = Any # type: ignore[no-redef]
43 type LegacyPolygon = Any # type: ignore[no-redef]
44 type LegacyMultipleCellCoadd = Any # type: ignore[no-redef]
45 type LegacyObservationIdentifiers = Any # type: ignore[no-redef]
48class CoaddProvenance(DescribableMixin):
49 """A pair of tables that record the inputs to a cell-based coadd.
51 Parameters
52 ----------
53 inputs
54 A table of {visit, detector} combinations that contribute to any cell
55 in the coadd.
56 contributions
57 A table of {visit, detector, cell} combinations that describe how an
58 observation contributed to a cell.
60 Raises
61 ------
62 ValueError
63 Raised if ``inputs`` has no rows; provenance that records no input
64 image is not meaningful.
66 Notes
67 -----
68 This object can represent the provenance of a whole patch, a single cell,
69 or anything in between. In the single-cell case, the ``inputs`` and
70 ``contributions`` tables have the same number of rows (but may not be
71 ordered the same way!).
72 """
74 def __init__(self, inputs: astropy.table.Table, contributions: astropy.table.Table) -> None:
75 if not len(inputs):
76 raise ValueError("Coadd provenance must contain at least one input image.")
77 self._inputs = inputs
78 self._contributions = contributions
80 _INPUT_TABLE_COLUMNS: ClassVar[list[tuple[str, type, str]]] = [
81 ("instrument", np.object_, "Name of the instrument."),
82 ("visit", np.uint64, "ID of the visit."),
83 ("detector", np.uint16, "ID of the detector."),
84 ("physical_filter", np.object_, "Full name of the bandpass filter."),
85 ("day_obs", np.uint32, "Observation night as a YYYYMMDD integer."),
86 (
87 "polygon",
88 np.object_,
89 (
90 "Polygon that approximates the overlap of the observation and the coadd patch, "
91 "in coadd coordinates."
92 ),
93 ),
94 ]
96 _CONTRIBUTION_TABLE_COLUMNS: ClassVar[list[tuple[str, type, str, u.UnitBase | None]]] = [
97 ("cell_i", np.uint16, "Y-axis index of the cell within the patch.", None),
98 ("cell_j", np.uint16, "X-axis index of the cell within the patch.", None),
99 ("instrument", np.object_, "Name of the instrument.", None),
100 ("visit", np.uint64, "ID of the visit.", None),
101 ("detector", np.uint16, "ID of the detector.", None),
102 ("overlaps_center", np.bool_, "Whether a this observation overlaps the center of the cell.", None),
103 ("overlap_fraction", np.float64, "Fraction of the cell that is covered by the overlap region.", None),
104 ("unmasked_fraction", np.float64, "Fraction of the cell propagated to the coadd.", None),
105 ("weight", np.float64, "Weight to be used for this input in this cell.", None),
106 ("psf_shape_xx", np.float64, "Second order moments of the PSF.", u.pix**2),
107 ("psf_shape_yy", np.float64, "Second order moments of the PSF.", u.pix**2),
108 ("psf_shape_xy", np.float64, "Second order moments of the PSF.", u.pix**2),
109 (
110 "psf_shape_flag",
111 np.bool_,
112 "Flag indicating whether the PSF shape measurement was successful.",
113 None,
114 ),
115 ]
117 @classmethod
118 def make_empty_input_table(cls, n_rows: int) -> astropy.table.Table:
119 """Make an empty `inputs` table with a set number of rows.
121 Parameters
122 ----------
123 n_rows
124 Number of rows in the new table.
125 """
126 return astropy.table.Table(
127 [
128 astropy.table.Column(name=name, length=n_rows, dtype=dtype, description=description)
129 for name, dtype, description in cls._INPUT_TABLE_COLUMNS
130 ]
131 )
133 @classmethod
134 def make_empty_contribution_table(cls, n_rows: int) -> astropy.table.Table:
135 """Make an empty `contributions` table with a set number of rows.
137 Parameters
138 ----------
139 n_rows
140 Number of rows in the new table.
141 """
142 return astropy.table.Table(
143 [
144 astropy.table.Column(
145 name=name, length=n_rows, dtype=dtype, description=description, unit=unit
146 )
147 for name, dtype, description, unit in cls._CONTRIBUTION_TABLE_COLUMNS
148 ]
149 )
151 @property
152 def inputs(self) -> astropy.table.Table:
153 """A table of {visit, detector} combinations that contribute to any
154 cell in the coadd.
155 """
156 return self._inputs
158 @property
159 def contributions(self) -> astropy.table.Table:
160 """A table of {visit, detector, cell} combinations that describe how an
161 observation contributed to a cell.
162 """
163 return self._contributions
165 def __getitem__(self, cell: CellIJ) -> CoaddProvenance | None:
166 return self.subset([cell])
168 def subset(self, cells: Iterable[CellIJ]) -> CoaddProvenance | None:
169 """Return a new provenance object with just the given cells.
171 Parameters
172 ----------
173 cells
174 Cells to keep in the returned provenance.
176 Returns
177 -------
178 subset : `CoaddProvenance` or `None`
179 Provenance for ``cells`` only, or `None` if none of them have
180 contributions.
181 """
182 cells_to_keep = astropy.table.Table(
183 rows=[(index.i, index.j) for index in cells],
184 names=["cell_i", "cell_j"],
185 dtype=[np.uint16, np.uint16],
186 )
187 if not len(cells_to_keep): 187 ↛ 189line 187 didn't jump to line 189 because the condition on line 187 was never true
188 # astropy.table.join rejects an empty operand outright.
189 return None
190 contributions = astropy.table.join(self._contributions, cells_to_keep)
191 assert contributions.columns.keys() == {name for name, _, _, _ in self._CONTRIBUTION_TABLE_COLUMNS}
192 if not len(contributions):
193 # No inputs to derive either, and astropy.table.join rejects an
194 # empty operand outright.
195 return None
196 # We need to pass 'keys' below to avoid duplicate outputs coming from
197 # the same observation appearing in multiple cells.
198 inputs = astropy.table.unique(
199 astropy.table.join(contributions["instrument", "visit", "detector"], self._inputs),
200 keys=["instrument", "visit", "detector"],
201 )
202 assert inputs.columns.keys() == {name for name, _, _ in self._INPUT_TABLE_COLUMNS}
203 return CoaddProvenance(inputs=inputs, contributions=contributions)
205 def _describe(
206 self,
207 options: DescribeOptions = DescribeOptions(),
208 /,
209 *,
210 bounds: CellGridBounds | None = None,
211 ) -> Report:
212 """Return a `Report` describing this provenance.
214 Parameters
215 ----------
216 options : `DescribeOptions`, optional
217 Rendering options. `DescribeOptions.brief` reports only the
218 number of input images, which no column scan is needed to count.
219 bounds : `CellGridBounds`, optional
220 Cells the image this provenance belongs to has data for. When
221 given, the number of cells with contributions is reported as a
222 fraction of them.
224 Notes
225 -----
226 The report summarizes the tables rather than rendering them. Rich
227 renders an embedded `astropy.table.Table` as plain text and never
228 consults the table's own ``_repr_html_``, so `inputs` and
229 `contributions` describe themselves better than this report could,
230 and a patch has tens of thousands of contribution rows.
231 """
232 n_inputs = len(self._inputs)
233 summary = f"CoaddProvenance({n_inputs} input image{'s' if n_inputs != 1 else ''})"
234 if options.brief:
235 return Report(type_name="CoaddProvenance", summary=summary)
236 fields: list[ReportField] = []
237 for column in ("instrument", "physical_filter"):
238 fields.append(
239 ReportField(
240 label=column,
241 value=", ".join(sorted({str(value) for value in self._inputs[column]})),
242 role=FieldRole.DERIVED,
243 )
244 )
245 n_visits = len(np.unique(self._inputs["visit"]))
246 input_images = f"{n_inputs} from {n_visits} visit{'s' if n_visits != 1 else ''}"
247 fields.append(ReportField(label="input images", value=input_images, role=FieldRole.DERIVED))
248 first_night = int(self._inputs["day_obs"].min())
249 last_night = int(self._inputs["day_obs"].max())
250 fields.append(
251 ReportField(
252 label="day_obs",
253 value=str(first_night) if first_night == last_night else f"{first_night} - {last_night}",
254 role=FieldRole.DERIVED,
255 )
256 )
257 _, counts = np.unique(
258 np.column_stack([self._contributions["cell_i"], self._contributions["cell_j"]]),
259 axis=0,
260 return_counts=True,
261 )
262 if bounds is not None:
263 n_cells_with_data = bounds.subgrid_size.i * bounds.subgrid_size.j - len(bounds.missing)
264 cells = f"{len(counts)} of {n_cells_with_data} with contributions"
265 else:
266 cells = f"{len(counts)} with contributions" if len(counts) else "none"
267 fields.append(ReportField(label="cells", value=cells, role=FieldRole.DERIVED))
268 if len(counts):
269 low = int(counts.min())
270 high = int(counts.max())
271 per_cell = (
272 f"{low} input image{'s' if low != 1 else ''}"
273 if low == high
274 else f"{low} - {high} input images (median {np.median(counts):g})"
275 )
276 fields.append(ReportField(label="per cell", value=per_cell, role=FieldRole.DERIVED))
277 return Report(type_name="CoaddProvenance", summary=summary, fields=fields)
279 def serialize(self, archive: OutputArchive[Any]) -> CoaddProvenanceSerializationModel:
280 """Serialize the provenance to an output archive.
282 Parameters
283 ----------
284 archive
285 Archive to write to.
286 """
287 # The tables are exposed and mutable, so a caller can empty one after
288 # construction. Catch that here rather than deep in the column
289 # rewriting below, where it surfaces as "max() iterable argument is
290 # empty".
291 assert len(self._inputs), "Coadd provenance must contain at least one input image."
292 inputs = self._inputs.copy(copy_data=False)
293 contributions = self._contributions.copy(copy_data=False)
294 instrument = CoaddProvenanceSerializationModel._fix_str_for_serialization(
295 "instrument", inputs, contributions
296 )
297 physical_filter = CoaddProvenanceSerializationModel._fix_str_for_serialization(
298 "physical_filter", inputs
299 )
300 CoaddProvenanceSerializationModel._fix_polygon_for_serialization(inputs)
301 inputs_model = archive.add_table(inputs, name="inputs")
302 contributions_model = archive.add_table(contributions, name="contributions")
303 return CoaddProvenanceSerializationModel(
304 instrument=instrument,
305 physical_filter=physical_filter,
306 inputs=inputs_model,
307 contributions=contributions_model,
308 )
310 @staticmethod
311 def from_legacy(legacy_cell_coadd: LegacyMultipleCellCoadd) -> CoaddProvenance:
312 """Extract provenance from a legacy
313 `lsst.cell_coadds.MultipleCellCoadd` object.
315 Parameters
316 ----------
317 legacy_cell_coadd
318 Legacy cell coadd to extract provenance from.
319 """
320 inputs = CoaddProvenance.make_empty_input_table(len(legacy_cell_coadd.common.visit_polygons))
321 for n, (legacy_identifiers, legacy_polygon) in enumerate(
322 legacy_cell_coadd.common.visit_polygons.items()
323 ):
324 inputs["instrument"][n] = legacy_identifiers.instrument
325 inputs["visit"][n] = legacy_identifiers.visit
326 inputs["detector"][n] = legacy_identifiers.detector
327 inputs["physical_filter"][n] = legacy_identifiers.physical_filter
328 inputs["day_obs"][n] = legacy_identifiers.day_obs
329 inputs["polygon"][n] = Polygon.from_legacy(legacy_polygon)
330 n_contributions = 0
331 for legacy_cell in legacy_cell_coadd.cells.values():
332 n_contributions += len(legacy_cell.inputs)
333 contributions = CoaddProvenance.make_empty_contribution_table(n_contributions)
334 n = 0
335 for legacy_cell in legacy_cell_coadd.cells.values():
336 for legacy_identifiers, legacy_inputs in legacy_cell.inputs.items():
337 contributions["cell_i"][n] = legacy_cell.identifiers.cell.y
338 contributions["cell_j"][n] = legacy_cell.identifiers.cell.x
339 contributions["instrument"][n] = legacy_identifiers.instrument
340 contributions["visit"][n] = legacy_identifiers.visit
341 contributions["detector"][n] = legacy_identifiers.detector
342 contributions["overlaps_center"][n] = legacy_inputs.overlaps_center
343 contributions["overlap_fraction"][n] = legacy_inputs.overlap_fraction
344 contributions["unmasked_fraction"][n] = legacy_inputs.unmasked_overlap_fraction
345 contributions["weight"][n] = legacy_inputs.weight
346 contributions["psf_shape_xx"][n] = legacy_inputs.psf_shape.getIxx()
347 contributions["psf_shape_yy"][n] = legacy_inputs.psf_shape.getIyy()
348 contributions["psf_shape_xy"][n] = legacy_inputs.psf_shape.getIxy()
349 contributions["psf_shape_flag"][n] = legacy_inputs.psf_shape_flag
350 n += 1
351 return CoaddProvenance(inputs=inputs, contributions=contributions)
353 def to_legacy_polygon_map(self) -> dict[LegacyObservationIdentifiers, LegacyPolygon]:
354 """Construct a legacy mapping from
355 `lsst.cell_coadds.ObservationIdentifiers` to `lsst.afw.geom.Polygon`
356 from the `inputs` table.
357 """
358 from lsst.cell_coadds import ObservationIdentifiers as LegacyObservationIdentifiers
360 return {
361 LegacyObservationIdentifiers(
362 instrument=str(row["instrument"]),
363 physical_filter=str(row["physical_filter"]),
364 visit=int(row["visit"]),
365 day_obs=int(row["day_obs"]),
366 detector=int(row["detector"]),
367 ): row["polygon"].to_legacy()
368 for row in self.inputs
369 }
371 def to_legacy_cell_coadd_inputs(
372 self, observations: Iterable[LegacyObservationIdentifiers] | None
373 ) -> dict[LegacyIndex2D, dict[LegacyObservationIdentifiers, LegacyCellCoaddInputs]]:
374 """Construct a mapping from legacy cell index to the list of legacy
375 input structs for that cell.
377 Parameters
378 ----------
379 observations
380 Observations to include, or `None` to include all observations
381 in the `inputs` table.
382 """
383 from lsst.afw.geom.ellipses import Quadrupole
384 from lsst.cell_coadds import CoaddInputs as LegacyCellCoaddInputs
385 from lsst.skymap import Index2D as LegacyIndex2D
387 if observations is None: 387 ↛ 388line 387 didn't jump to line 388 because the condition on line 387 was never true
388 observations = self.to_legacy_polygon_map().keys()
389 observations_by_key: dict[tuple[str, int, int], LegacyObservationIdentifiers] = {
390 (obs.instrument, obs.visit, obs.detector): obs for obs in observations
391 }
392 result: dict[LegacyIndex2D, dict[LegacyObservationIdentifiers, LegacyCellCoaddInputs]] = {}
393 for row in self.contributions:
394 obs_key = (str(row["instrument"]), int(row["visit"]), int(row["detector"]))
395 obs = observations_by_key[obs_key]
396 cell_inputs = result.setdefault(LegacyIndex2D(x=int(row["cell_j"]), y=int(row["cell_i"])), {})
397 cell_inputs[obs] = LegacyCellCoaddInputs(
398 overlaps_center=bool(row["overlaps_center"]),
399 overlap_fraction=float(row["overlap_fraction"]),
400 unmasked_overlap_fraction=float(row["unmasked_fraction"]),
401 weight=float(row["weight"]),
402 psf_shape=Quadrupole(row["psf_shape_xx"], row["psf_shape_yy"], row["psf_shape_xy"]),
403 psf_shape_flag=bool(row["psf_shape_flag"]),
404 )
405 return result
407 @staticmethod
408 def from_legacy_lazy(
409 legacy_coadd_inputs: LegacyCoaddInputs,
410 bounds: CellGridBounds,
411 sky_projection: SkyProjection,
412 instrument: str,
413 ) -> CoaddProvenance:
414 """Convert provenance from a legacy
415 `lsst.afw.image.CoaddInputs` object.
417 Parameters
418 ----------
419 legacy_coadd_inputs
420 Legacy coadd-input provenance to convert.
421 bounds
422 The cell grid and known-missing cells.
423 sky_projection
424 The projection the coadd pixel grid to the sky.
425 instrument
426 Name of the instrument (for all inputs).
427 """
428 ccd_catalog = legacy_coadd_inputs.ccds
429 inputs = CoaddProvenance.make_empty_input_table(len(ccd_catalog))
430 inputs["instrument"] = instrument
431 contributions = CoaddProvenance.make_empty_contribution_table(bounds.n_cells * len(ccd_catalog))
432 contributions["instrument"] = instrument
433 contributions["unmasked_fraction"] = np.nan
434 m = 0
435 n = 0
436 for ccd_record in ccd_catalog:
437 visit_id = ccd_record.get("visit")
438 detector_id = ccd_record.get("ccd")
439 detector_region: Region = Polygon.from_box(Box.from_legacy(ccd_record.getBBox()))
440 if (legacy_polygon := ccd_record.getValidPolygon()) is not None:
441 detector_region = detector_region.intersection(Polygon.from_legacy(legacy_polygon))
442 detector_proj = SkyProjection.from_legacy(ccd_record.getWcs(), GeneralFrame(unit=u.pix))
443 detector_to_coadd = detector_proj.pixel_to_sky_transform.then(
444 sky_projection.sky_to_pixel_transform
445 )
446 try:
447 detector_coadd_region = detector_region.transform(detector_to_coadd)
448 except RegionDomainError:
449 # This input is outside the domain of the coadd's projection
450 # (e.g. on the far side of the sky from its tangent point),
451 # so it cannot overlap the coadd.
452 continue
453 try:
454 detector_patch_region = detector_coadd_region.intersection(bounds.bbox)
455 except NoOverlapError:
456 # This input does not overlap this coadd's bounds at all, as
457 # happens when converting from a larger (e.g. whole-tract
458 # template) CoaddInputs to a smaller (e.g. postage) coadd.
459 continue
460 inputs["visit"][n] = visit_id
461 inputs["detector"][n] = detector_id
462 inputs["physical_filter"][n] = ccd_record.get("filter")
463 inputs["day_obs"][n] = _extract_day_obs_from_visit(visit_id)
464 inputs["polygon"][n] = detector_patch_region
465 weight = ccd_record.get("weight")
466 for cell in bounds.cell_indices():
467 cell_box = bounds.grid.bbox_of(cell)
468 cell_center = XY(x=cell_box.x.center, y=cell_box.y.center)
469 try:
470 cell_region = detector_patch_region.intersection(cell_box)
471 except NoOverlapError:
472 continue
473 contributions["cell_i"][m] = cell.i
474 contributions["cell_j"][m] = cell.j
475 contributions["visit"][m] = visit_id
476 contributions["detector"][m] = detector_id
477 contributions["overlaps_center"][m] = cell_region.contains(cell_center)
478 contributions["overlap_fraction"][m] = cell_region.area / cell_box.area
479 contributions["weight"][m] = weight
480 # PSFs are expensive to evaluate; not clear if these columns
481 # are useful enough to be worth the cost.
482 contributions["psf_shape_flag"][m] = True
483 contributions["psf_shape_xx"][m] = np.nan
484 contributions["psf_shape_yy"][m] = np.nan
485 contributions["psf_shape_xy"][m] = np.nan
486 m += 1
487 n += 1
488 contributions = contributions[:m].copy()
489 inputs = inputs[:n].copy()
490 return CoaddProvenance(inputs, contributions)
493class CoaddProvenanceSerializationModel(ArchiveTree):
494 """A Pydantic model used to represent a serialized `CoaddProvenance`.
496 Notes
497 -----
498 We can't rewrite the Astropy tables directly into the archive (e.g. as
499 FITS binary tables for a FITS archive), because:
501 - `str` columns are a huge pain in both Numpy and FITS;
502 - the polygon columns need to be rewritten as array-valued columns.
504 To deal with the string columns (``instrument`` and ``physical_filter``)
505 we do dictionary compression: we map each distinct value of those columns
506 to an integer, and then we save that mapping to the model while saving
507 an integer version of that column in the table. But if there is actually
508 only one value in that column (the most common case by far) we just drop
509 the column and store that value directly in the model.
510 """
512 SCHEMA_NAME: ClassVar[str] = "coadd_provenance"
513 SCHEMA_VERSION: ClassVar[str] = "1.0.0"
514 MIN_READ_VERSION: ClassVar[int] = 1
515 PUBLIC_TYPE: ClassVar[type] = CoaddProvenance
517 instrument: str | dict[str, int] = pydantic.Field(
518 description=(
519 "Instrument name for all inputs to this coadd, or a mapping from "
520 "instrument name to the integer used in its place in the tables."
521 )
522 )
523 physical_filter: str | dict[str, int] = pydantic.Field(
524 description="Physical filter name for all inputs to this coadd."
525 )
526 inputs: TableModel = pydantic.Field(description="Table of all inputs to the coadd.")
527 contributions: TableModel = pydantic.Field(description="Table of per-cell contributions to the coadd.")
529 def deserialize(self, archive: InputArchive[Any], **kwargs: Any) -> CoaddProvenance:
530 """Deserialize a provenance from an input archive.
532 Parameters
533 ----------
534 archive
535 Archive to read from.
536 **kwargs
537 Unsupported keyword arguments are accepted only to provide
538 better error messages (raising
539 `.serialization.InvalidParameterError`).
541 Notes
542 -----
543 While `CoaddProvenance.subset` can be used to filter provenance
544 information down to just certain cells, there is no advantage to be
545 had from doing this during deserialization (the table data is not
546 ordered by cell, and hence there's read-slicing we can do).
547 """
548 if kwargs: 548 ↛ 549line 548 didn't jump to line 549 because the condition on line 548 was never true
549 raise InvalidParameterError(f"Unrecognized parameters for CoaddProvenance: {set(kwargs.keys())}.")
550 inputs = archive.get_table(self.inputs)
551 contributions = archive.get_table(self.contributions)
552 CoaddProvenanceSerializationModel._fix_str_for_deserialization(
553 "instrument", self.instrument, inputs, contributions
554 )
555 CoaddProvenanceSerializationModel._fix_str_for_deserialization(
556 "physical_filter", self.physical_filter, inputs
557 )
558 CoaddProvenanceSerializationModel._fix_polygon_for_deserialization(inputs)
559 for name, _, description in CoaddProvenance._INPUT_TABLE_COLUMNS:
560 inputs.columns[name].description = description
561 for name, _, description, unit in CoaddProvenance._CONTRIBUTION_TABLE_COLUMNS:
562 contributions.columns[name].description = description
563 contributions.columns[name].unit = unit
564 return CoaddProvenance(inputs=inputs, contributions=contributions)
566 @staticmethod
567 def _fix_str_for_serialization(column: str, *tables: astropy.table.Table) -> str | dict[str, int]:
568 """Rewrite a string column as an integer column or drop it.
570 Parameters
571 ----------
572 column
573 Name of the column to rewrite.
574 *tables
575 One or more astropy tables to rewrite. The first table is assumed
576 to have all values for this column that might appear in any other
577 tables.
579 Returns
580 -------
581 `str` | `dict` [`str`, `int`]
582 If there is only one unique value for this column in the first
583 table, that value (and the column will have been dropped from
584 all givne tables). If the tables are empty, the column is
585 dropped and an empty `dict` is returned. In all other cases the
586 given column is replaced with an integer column in all given
587 tables and the mapping from strings to integers is returned.
588 """
589 result: str | dict[str, int] = {name: n for n, name in enumerate(sorted(set(tables[0][column])))}
590 match len(result):
591 case 0: 591 ↛ 592line 591 didn't jump to line 592 because the pattern on line 591 never matched
592 pass
593 case 1: 593 ↛ 595line 593 didn't jump to line 595 because the pattern on line 593 always matched
594 (result,) = result.keys() # type: ignore[union-attr]
595 case _:
596 for table in tables:
597 table.columns[column] = astropy.table.Column(
598 data=[result[k] for k in table.columns[column]],
599 name=column,
600 dtype=np.uint8,
601 description=f"Integer mapped to {column} name.",
602 )
603 return result
604 # If we didn't remap to an integer (case 0 and 1 above), delete the
605 # column.
606 for table in tables:
607 del table.columns[column]
608 return result
610 @staticmethod
611 def _fix_str_for_deserialization(
612 column: str, value: str | dict[str, int], *tables: astropy.table.Table
613 ) -> None:
614 """Rewrite an integer column back to a string one.
616 Parameters
617 ----------
618 column
619 Name of the column to rewrite.
620 value
621 Value or mapping of values returned by
622 `_fix_str_for_serialization`.
623 tables
624 Tables to rewrite this column in.
625 """
626 match value:
627 case str(): 627 ↛ 630line 627 didn't jump to line 630 because the pattern on line 627 always matched
628 for table in tables:
629 table.columns[column] = astropy.table.Column([value] * len(table), dtype=object)
630 case dict():
631 mapping = {v: k for k, v in value.items()}
632 for table in tables:
633 table.columns[column] = astropy.table.Column(
634 [mapping[k] for k in table[column]], dtype=object
635 )
637 @staticmethod
638 def _fix_polygon_for_serialization(inputs: astropy.table.Table) -> None:
639 """Rewrite a polygon `object` column as a pair of array-valued columns
640 and an array-size column.
642 Parameters
643 ----------
644 inputs
645 A copy of the in-memory coadd inputs table to modify in-place into
646 its serialization form.
647 """
648 # Region intersections are sometimes represented as boxes rather
649 # than polygons, so normalize to polygons before writing vertex
650 # columns.
651 polygons = [p.to_polygon() if isinstance(p, Box) else p for p in inputs["polygon"]]
652 max_n_vertices = max((p.n_vertices for p in polygons), default=0)
653 inputs["n_vertices"] = astropy.table.Column(
654 [p.n_vertices for p in polygons],
655 name="n_vertices",
656 dtype=np.uint8,
657 description="Number of polygon vertices.",
658 )
659 inputs["x_vertices"] = astropy.table.Column(
660 name="x_vertices",
661 dtype=np.float64,
662 length=len(inputs),
663 shape=(max_n_vertices,),
664 description="X coordinates of polygon vertices, in tract coordinates.",
665 )
666 inputs["x_vertices"][:, :] = np.nan
667 inputs["y_vertices"] = astropy.table.Column(
668 name="y_vertices",
669 dtype=np.float64,
670 length=len(inputs),
671 shape=(max_n_vertices,),
672 description="Y coordinates of polygon vertices, in tract coordinates.",
673 )
674 inputs["y_vertices"][:, :] = np.nan
675 for i, polygon in enumerate(polygons):
676 inputs["n_vertices"][i] = polygon.n_vertices
677 inputs["x_vertices"][i][: polygon.n_vertices] = polygon.x_vertices
678 inputs["y_vertices"][i][: polygon.n_vertices] = polygon.y_vertices
679 del inputs["polygon"]
681 @staticmethod
682 def _fix_polygon_for_deserialization(inputs: astropy.table.Table) -> None:
683 """Rewrite a a pair of array-valued columns and an array-size column
684 into a polygon `object` column.
686 Parameters
687 ----------
688 inputs
689 The serialized version of the coadd inputs table, to be modified
690 in-place into its in-memory form.
691 """
692 polygons = [
693 Polygon(x_vertices=x_vertices[:n_vertices], y_vertices=y_vertices[:n_vertices])
694 for n_vertices, x_vertices, y_vertices in zip(
695 inputs["n_vertices"], inputs["x_vertices"], inputs["y_vertices"]
696 )
697 ]
698 del inputs["n_vertices"]
699 del inputs["x_vertices"]
700 del inputs["y_vertices"]
701 inputs["polygon"] = astropy.table.Column(polygons, name="polygon", dtype=np.object_)
704def _extract_day_obs_from_visit(visit_id: int) -> int:
705 """If the given visit ID looks like an ISO date-as-integer concatenated
706 with a sequence number, extract and return the date part.
708 Raises
709 ------
710 NotImplementedError
711 Raised if the visit ID does not look date-based.
712 """
713 id_str = str(visit_id)
714 if len(id_str) < 8:
715 raise NotImplementedError(f"visit ID {visit_id} does not start with a date.")
716 year = int(id_str[:4])
717 month = int(id_str[4:6])
718 day = int(id_str[6:8])
719 if year >= 1900 and year < 3000 and month <= 12 and day <= 31:
720 return (year * 100 + month) * 100 + day
721 raise NotImplementedError(f"visit ID {visit_id} does not start with a date.")