Coverage for python/lsst/ap/association/utils.py: 89%
45 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 11:42 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 11:42 +0000
1# This file is part of ap_association.
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# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
22"""Utilities for working with the APDB.
23"""
24__all__ = ("getMidpointFromTimespan", "makeEmptyForcedSourceTable", "getRegion", "paddedRegion",
25 "readSchemaFromApdb", "readMpcOrbitsSchema")
28import math
30import felis.datamodel
31import pandas as pd
33from lsst.daf.butler import Timespan
34from lsst.dax.apdb import Apdb, ApdbTables, schema_model
35import lsst.geom
36import lsst.sphgeom
38from lsst.pipe.tasks.schemaUtils import convertDataFrameToSdmSchema, readSdmSchemaFile
41def readSchemaFromApdb(apdb: Apdb) -> dict[str, schema_model.Table | None]:
42 """Extract the schema from an APDB instance.
44 Parameters
45 ----------
46 apdb : `lsst.dax.apdb.Apdb`
47 AP database connection object.
49 Returns
50 -------
51 schemaTable : dict[str, schema_model.Table | None]
52 A dict of the schemas in the given table defined in the specified file.
53 """
54 return {table.table_name(): apdb.tableDef(table) for table in ApdbTables}
57def readMpcOrbitsSchema(apdb: Apdb) -> felis.datamodel.Table | None:
58 """Read the ``mpc_orbits`` table schema from the schema file of an APDB.
60 This needs a special read function, since the APDB does not store
61 ``mpc_orbits`` and `readSchemaFromApdb` can't return it.
63 Parameters
64 ----------
65 apdb : `lsst.dax.apdb.Apdb`
66 AP database connection object.
68 Returns
69 -------
70 table : `felis.datamodel.Table` or `None`
71 Schema of the ``mpc_orbits`` table, or `None` if the APDB schema file
72 does not define it.
73 """
74 return readSdmSchemaFile(apdb.getConfig().schema_file).get("mpc_orbits")
77def getMidpointFromTimespan(timespan, allowUnbounded=True):
78 """Safely retrieve the midpoint in TAI from a Timespan.
80 Parameters
81 ----------
82 timespan : `lsst.daf.butler.Timespan` of `astropy.time.Time`
83 A Timespan centered on the midpoint of a visit.
84 allowUnbounded : `bool`, optional
85 If set, return the start or end of an unbounded timespan.
87 Returns
88 -------
89 midpoint : `astropy.time.Time`
90 The midpoint of the timespan.
92 Raises
93 ------
94 ValueError
95 Raised if either the start or end of the timespan is None, and
96 ``allowUnbounded`` is not set.
97 ValueError
98 Raised if the timespan is empty.
99 """
100 if (timespan.begin == Timespan.EMPTY) or (timespan.begin == Timespan.EMPTY):
101 raise ValueError("Cannot compute midpoint: EMPTY Timespan.")
103 try:
104 interval = timespan.end - timespan.begin
105 return (timespan.begin + interval/2).tai
106 except TypeError as e:
107 if allowUnbounded:
108 if timespan.end is not None:
109 return timespan.end.tai
110 elif timespan.begin is not None:
111 return timespan.begin.tai
112 else:
113 raise ValueError("Cannot compute midpoint: unbounded timespan.") from e
114 else:
115 raise ValueError("Cannot compute midpoint: unbounded timespan.") from e
118def makeEmptyForcedSourceTable(schema):
119 """Return a dataframe with the correct columns for diaForcedSources table.
121 Returns
122 -------
123 diaForcedSources : `pandas.DataFrame`
124 Empty dataframe.
125 """
126 diaForcedSources = convertDataFrameToSdmSchema(schema, pd.DataFrame(), tableName="DiaForcedSource")
127 return diaForcedSources
130def getRegion(exposure):
131 """Calculate an enveloping region for an exposure.
133 Parameters
134 ----------
135 exposure : `lsst.afw.image.Exposure`
136 Exposure object with calibrated WCS.
138 Returns
139 -------
140 region : `lsst.sphgeom.Region`
141 Region enveloping an exposure.
142 """
143 # Bounding box needs to be a `Box2D` not a `Box2I` for `wcs.pixelToSky()`
144 bbox = lsst.geom.Box2D(exposure.getBBox())
145 wcs = exposure.getWcs()
147 region = lsst.sphgeom.ConvexPolygon([pp.getVector() for pp in wcs.pixelToSky(bbox.getCorners())])
149 return region
152def paddedRegion(region, margin):
153 """Return a region that has been expanded by a buffer.
155 Parameters
156 ----------
157 region : `lsst.sphgeom.Region`
158 The region to pad.
159 margin : `lsst.sphgeom.Angle`
160 The amount by which to increase the region.
162 Returns
163 -------
164 padded : `lsst.sphgeom.Region`
165 An enlarged copy of ``region``.
166 """
167 # region is almost certainly a (padded) detector bounding box.
168 if isinstance(region, lsst.sphgeom.ConvexPolygon): 168 ↛ 178line 168 didn't jump to line 178 because the condition on line 168 was always true
169 # This is an ad-hoc, approximate implementation. It should be good
170 # enough for catalog loading, but is not a general-purpose solution.
171 center = lsst.geom.SpherePoint(region.getCentroid())
172 corners = [lsst.geom.SpherePoint(c) for c in region.getVertices()]
173 # Approximate the region as a Euclidian square
174 # geom.Angle(sphgeom.Angle) converter not pybind-wrapped???
175 diagonal_margin = lsst.geom.Angle(margin.asRadians() * math.sqrt(2.0))
176 padded = [c.offset(center.bearingTo(c), diagonal_margin) for c in corners]
177 return lsst.sphgeom.ConvexPolygon.convexHull([c.getVector() for c in padded])
178 elif hasattr(region, "dilatedBy"):
179 return region.dilatedBy(margin)
180 else:
181 return region.getBoundingCircle().dilatedBy(margin)