Coverage for tests/test_catalogMatch.py: 24%
89 statements
« prev ^ index » next coverage.py v7.2.3, created at 2023-04-28 10:27 +0000
« prev ^ index » next coverage.py v7.2.3, created at 2023-04-28 10:27 +0000
1# This file is part of analysis_tools.
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/>.
22import unittest
24import astropy.units as u
25import lsst.afw.table as afwTable
26import lsst.geom
27import lsst.skymap
28import numpy as np
29import pandas as pd
30from lsst.analysis.tools.tasks import CatalogMatchConfig, CatalogMatchTask
31from lsst.daf.base import PropertyList
32from lsst.meas.algorithms import ReferenceObjectLoader
33from lsst.meas.algorithms.testUtils import MockRefcatDataId
34from lsst.pipe.base import InMemoryDatasetHandle
37class TestCatalogMatch(unittest.TestCase):
38 """Test CatalogMatchTask"""
40 def setUp(self):
41 config = CatalogMatchConfig()
42 config.bands = ["g", "r", "i", "z", "y"]
43 self.task = CatalogMatchTask(config=config)
44 self.task.config.extraColumns.append("sourceId")
46 self.rng = np.random.default_rng(12345)
48 self.skymap = self._make_skymap()
49 self.tract = 9813
51 tract = self.skymap.generateTract(self.tract)
52 self.tractPoly = tract.getOuterSkyPolygon()
53 self.tractBbox = self.tractPoly.getBoundingBox()
55 self.nStars = 1000
56 starIds = np.arange(self.nStars)
57 starRas = (
58 self.rng.random(self.nStars) * self.tractBbox.getWidth().asDegrees()
59 + self.tractBbox.getLon().getA().asDegrees()
60 )
61 starDecs = (
62 self.rng.random(self.nStars) * self.tractBbox.getHeight().asDegrees()
63 + self.tractBbox.getLat().getA().asDegrees()
64 )
66 refDataId, deferredRefCat = self._make_refCat(starIds, starRas, starDecs, self.tractPoly)
68 self.task.refObjLoader = ReferenceObjectLoader(
69 dataIds=[refDataId], refCats=[deferredRefCat], name="gaia_dr2_20200414"
70 )
71 self.task.refObjLoader.config.anyFilterMapsToThis = "phot_g_mean"
72 self.task.setRefCat(self.skymap, self.tract)
74 self.objectTable = self._make_objectCat(starIds, starRas, starDecs)
76 def _make_skymap(self):
77 """Make a testing skymap.
79 Returns
80 -------
81 `lsst.skymap.ringsSkyMap.RingsSkyMap`
82 Skymap that mimics the "hsc_rings_v1" skymap
83 """
84 skymap_config = lsst.skymap.ringsSkyMap.RingsSkyMapConfig()
85 skymap_config.numRings = 120
86 skymap_config.projection = "TAN"
87 skymap_config.tractOverlap = 1.0 / 60
88 skymap_config.pixelScale = 0.168
89 return lsst.skymap.ringsSkyMap.RingsSkyMap(skymap_config)
91 def _make_refCat(self, starIds, starRas, starDecs, poly):
92 """Make a mock `deferredDatasetReference` and
93 `DeferredDatasetHandle.dataId for a reference catalog.
95 Parameters
96 ----------
97 starIds : `np.ndarray` of `int`
98 Source ids for the simulated stars
99 starRas : `np.ndarray` of `float`
100 RAs of the simulated stars
101 starDecs : `np.ndarray` of `float`
102 Decs of the simulated stars
103 poly : `lsst.sphgeom._sphgeom.ConvexPolygon`
104 Bounding polygon containing the simulated stars
106 Returns
107 -------
108 refDataId : `lsst.meas.algorithms.testUtils.MockRefcatDataId`
109 Object that replicates the functionality of a dataId
110 deferredRefCat : InMemoryDatasetHandle
111 Object that replicates the functionality of a `DeferredDatasetRef`
112 """
113 refSchema = afwTable.SimpleTable.makeMinimalSchema()
114 idKey = refSchema.addField("sourceId", type="I")
115 fluxKey = refSchema.addField("phot_g_mean_flux", units="nJy", type=np.float64)
116 refCat = afwTable.SimpleCatalog(refSchema)
117 ref_md = PropertyList()
118 ref_md.set("REFCAT_FORMAT_VERSION", 1)
119 refCat.table.setMetadata(ref_md)
120 for i in range(len(starIds)):
121 record = refCat.addNew()
122 record.set(idKey, starIds[i])
123 record.setRa(lsst.geom.Angle(starRas[i], lsst.geom.degrees))
124 record.setDec(lsst.geom.Angle(starDecs[i], lsst.geom.degrees))
125 record.set(fluxKey, 1)
126 refDataId = MockRefcatDataId(poly)
127 deferredRefCat = InMemoryDatasetHandle(refCat, storageClass="SimpleCatalog", htm7="mockRefCat")
128 return refDataId, deferredRefCat
130 def _make_objectCat(self, starIds, starRas, starDecs):
131 """Make a `pd.DataFrame` catalog with the columns needed for the
132 object selector.
134 Parameters
135 ----------
136 starIds : `np.ndarray` of `int`
137 Source ids for the simulated stars
138 starRas : `np.ndarray` of `float`
139 RAs of the simulated stars
140 starDecs : `np.ndarray` of `float`
141 Decs of the simulated stars
142 poly : `lsst.sphgeom._sphgeom.ConvexPolygon`
143 Bounding polygon containing the simulated stars
145 Returns
146 -------
147 sourceCat : `pd.DataFrame`
148 Catalog containing the simulated stars
149 """
150 x = self.rng.random(self.nStars) * 4000
151 y = self.rng.random(self.nStars) * 4000
152 radecErr = 1.0 / (3600 * 10) # Let random scatter be about 1/10 arcsecond
153 sourceDict = {
154 "sourceId": starIds,
155 "coord_ra": starRas + self.rng.standard_normal(self.nStars) * radecErr,
156 "coord_dec": starDecs + self.rng.standard_normal(self.nStars) * radecErr,
157 "x": x,
158 "y": y,
159 }
161 for key in [
162 "r_psfFlux_flag",
163 "y_extendedness_flag",
164 "i_pixelFlags_saturatedCenter",
165 "r_extendedness_flag",
166 "y_extendedness",
167 "g_extendedness_flag",
168 "z_extendedness",
169 "i_extendedness",
170 "z_pixelFlags_saturatedCenter",
171 "i_psfFlux_flag",
172 "r_pixelFlags_saturatedCenter",
173 "xy_flag",
174 "r_extendedness",
175 "y_pixelFlags_saturatedCenter",
176 "i_extendedness_flag",
177 "patch",
178 "g_psfFlux_flag",
179 "y_psfFlux_flag",
180 "z_psfFlux_flag",
181 "g_pixelFlags_saturatedCenter",
182 "z_extendedness_flag",
183 "g_extendedness",
184 ]:
185 sourceDict[key] = 0
186 for key in ["detect_isPatchInner", "detect_isDeblendedSource"]:
187 sourceDict[key] = 1
188 for key in ["i_psfFlux", "g_psfFlux", "r_psfFlux", "y_psfFlux", "z_psfFlux"]:
189 sourceDict[key] = 1000
190 for key in ["z_psfFluxErr", "i_psfFluxErr", "r_psfFluxErr", "g_psfFluxErr", "y_psfFluxErr"]:
191 sourceDict[key] = 1
192 sourceCat = pd.DataFrame(sourceDict)
193 return sourceCat
195 def test_setRefCat(self):
196 """Test whether the objects in the reference catalog are in the
197 expected footprint and that we get as many as expected
198 """
199 coord_ra = (self.task.refCat["coord_ra"].to_numpy() * u.degree).to(u.radian).value
200 coord_dec = (self.task.refCat["coord_dec"].to_numpy() * u.degree).to(u.radian).value
201 inFootprint = self.tractBbox.contains(coord_ra, coord_dec)
202 self.assertTrue(inFootprint.all())
203 self.assertEqual(len(self.task.refCat), self.nStars)
205 def test_run(self):
206 """Test whether `CatalogMatchTask` correctly associates the target and
207 reference catalog.
208 """
209 output = self.task.run(self.objectTable)
211 self.assertEqual(len(output.matchedCatalog), self.nStars)
212 self.assertListEqual(
213 output.matchedCatalog["sourceId_target"].to_list(),
214 output.matchedCatalog["sourceId_ref"].to_list(),
215 )
218class MyMemoryTestCase(lsst.utils.tests.MemoryTestCase):
219 pass
222def setup_module(module):
223 lsst.utils.tests.init()
226if __name__ == "__main__": 226 ↛ 227line 226 didn't jump to line 227, because the condition on line 226 was never true
227 lsst.utils.tests.init()
228 unittest.main()