Coverage for tests/test_measureApCorr.py: 16%
176 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-12 10:22 +0000
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-12 10:22 +0000
1#
2# LSST Data Management System
3#
4# Copyright 2008-2016 AURA/LSST.
5#
6# This product includes software developed by the
7# LSST Project (http://www.lsst.org/).
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 LSST License Statement and
20# the GNU General Public License along with this program. If not,
21# see <https://www.lsstcorp.org/LegalNotices/>.
22#
23import unittest
24import numpy as np
25import logging
27import lsst.geom
28import lsst.afw.image as afwImage
29import lsst.afw.table as afwTable
30from lsst.afw.math import ChebyshevBoundedField
31import lsst.pex.config
32import lsst.meas.algorithms.measureApCorr as measureApCorr
33from lsst.meas.base.apCorrRegistry import addApCorrName
34import lsst.meas.base.tests
35import lsst.utils.tests
38def apCorrDefaultMap(value=None, bbox=None):
39 default_coefficients = np.ones((1, 1), dtype=float)
40 default_coefficients /= value
41 default_apCorrMap = ChebyshevBoundedField(bbox, default_coefficients)
42 default_fill = afwImage.ImageF(bbox)
43 default_apCorrMap.fillImage(default_fill)
44 return default_fill
47class MeasureApCorrTestCase(lsst.meas.base.tests.AlgorithmTestCase, lsst.utils.tests.TestCase):
49 def makeCatalog(self, apCorrScale=1.0, numSources=5):
50 sourceCat = afwTable.SourceCatalog(self.schema)
52 centroidKey = afwTable.Point2DKey(self.schema["slot_Centroid"])
53 x = self.rng.random(numSources)*self.exposure.getWidth() + self.exposure.getX0()
54 y = self.rng.random(numSources)*self.exposure.getHeight() + self.exposure.getY0()
55 for _i in range(numSources):
56 source_test_centroid = lsst.geom.Point2D(x[_i], y[_i])
57 source = sourceCat.addNew()
58 source.set(centroidKey, source_test_centroid)
59 # All sources are unresolved.
60 source[self.unresolvedName] = 0.0
62 source_test_instFlux = 5.1
63 source_test_instFluxErr = 1e-3
65 for name in self.names:
66 sourceCat[name + "_instFlux"] = source_test_instFlux
67 sourceCat[name + "_instFluxErr"] = source_test_instFluxErr
68 sourceCat[name + "_flag"] = np.zeros(len(sourceCat), dtype=bool)
69 sourceCat[name + self.apNameStr + "_instFlux"] = source_test_instFlux * apCorrScale
70 sourceCat[name + self.apNameStr + "_instFluxErr"] = source_test_instFluxErr * apCorrScale
71 sourceCat[name + self.apNameStr + "_flag"] = np.zeros(len(sourceCat), dtype=bool)
73 return sourceCat
75 def setUp(self):
76 self.rng = np.random.Generator(np.random.MT19937(1))
77 schema = afwTable.SourceTable.makeMinimalSchema()
78 apNameStr = "Ap"
79 config = measureApCorr.MeasureApCorrTask.ConfigClass()
80 unresolvedName = config.sourceSelector.active.unresolved.name
81 # Add fields in anti-sorted order to try to impose a need for sorting
82 # in the addition of the apCorr fields (may happen by fluke, but this
83 # is the best we can do to test this here.
84 names = ["test2", "test1"]
85 for name in names:
86 apName = name + apNameStr
87 addApCorrName(apName)
88 schema.addField(name + "_instFlux", type=float)
89 schema.addField(name + "_instFluxErr", type=float)
90 schema.addField(name + "_flag", type="Flag")
91 schema.addField(apName + "_instFlux", type=float)
92 schema.addField(apName + "_instFluxErr", type=float)
93 schema.addField(apName + "_flag", type="Flag")
94 schema.addField(names[0] + "_Centroid_x", type=float)
95 schema.addField(names[0] + "_Centroid_y", type=float)
96 schema.getAliasMap().set("slot_Centroid", names[0] + "_Centroid")
97 schema.addField(unresolvedName, type=float)
98 schema.addField("deblend_nChild", type=np.int32)
99 for flag in [
100 "base_PixelFlags_flag_edge",
101 "base_PixelFlags_flag_interpolatedCenter",
102 "base_PixelFlags_flag_saturatedCenter",
103 "base_PixelFlags_flag_crCenter",
104 "base_PixelFlags_flag_bad",
105 "base_PixelFlags_flag_interpolated",
106 "base_PixelFlags_flag_saturated",
107 ]:
108 schema.addField(flag, type="Flag")
109 config.refFluxName = names[0]
110 config.sourceSelector["science"].signalToNoise.fluxField = names[0] + "_instFlux"
111 config.sourceSelector["science"].signalToNoise.errField = names[0] + "_instFluxErr"
112 self.meas_apCorr_task = measureApCorr.MeasureApCorrTask(schema=schema, config=config)
113 self.names = names
114 self.apNameStr = apNameStr
115 self.schema = schema
116 self.exposure = lsst.afw.image.ExposureF(10, 10)
117 self.unresolvedName = unresolvedName
119 def tearDown(self):
120 del self.schema
121 del self.meas_apCorr_task
122 del self.exposure
124 def testAddFields(self):
125 """Instantiating the task should add one field to the schema."""
126 for name in self.names:
127 self.assertIn("apcorr_" + name + self.apNameStr + "_used", self.schema.getNames())
128 sortedNames = sorted(self.names)
129 key0 = self.schema.find("apcorr_" + sortedNames[0] + self.apNameStr + "_used").key
130 key1 = self.schema.find("apcorr_" + sortedNames[1] + self.apNameStr + "_used").key
131 # Check that the apCorr fields were added in a sorted order (not
132 # foolproof as this could have happened by fluke, but it's the best
133 # we can do to test this here (having added the two fields in an anti-
134 # sorted order).
135 self.assertLess(key0.getOffset() + key0.getBit(), key1.getOffset() + key1.getBit())
137 def testReturnApCorrMap(self):
138 """The measureApCorr task should return a structure with a single key 'apCorrMap'."""
139 struct = self.meas_apCorr_task.run(catalog=self.makeCatalog(), exposure=self.exposure)
140 self.assertEqual(list(struct.getDict().keys()), ['apCorrMap'])
142 def testApCorrMapKeys(self):
143 """An apCorrMap structure should have two keys per name supplied to addApCorrName()."""
144 key_names = []
145 for name in self.names:
146 apFluxName = name + self.apNameStr + "_instFlux"
147 apFluxErrName = name + self.apNameStr + "_instFluxErr"
148 struct = self.meas_apCorr_task.run(catalog=self.makeCatalog(), exposure=self.exposure)
149 key_names.append(apFluxName)
150 key_names.append(apFluxErrName)
151 self.assertEqual(set(struct.apCorrMap.keys()), set(key_names))
153 def testTooFewSources(self):
154 """ If there are too few sources, check that an exception is raised."""
155 # Create an empty catalog with no sources to process.
156 catalog = afwTable.SourceCatalog(self.schema)
157 with self.assertRaisesRegex(measureApCorr.MeasureApCorrError,
158 "Unable to measure aperture correction for 'test1Ap'"):
159 self.meas_apCorr_task.run(catalog=catalog, exposure=self.exposure)
161 # We now try again after declaring that the aperture correction is
162 # allowed to fail. This should run without raising an exception, but
163 # will log a warning.
164 for name in self.names:
165 self.meas_apCorr_task.config.allowFailure.append(name + self.apNameStr)
166 with self.assertLogs(level=logging.WARNING) as cm:
167 self.meas_apCorr_task.run(catalog=catalog, exposure=self.exposure)
168 self.assertIn("Unable to measure aperture correction for 'test1Ap'", cm.output[0])
170 def testSourceNotUsed(self):
171 """ Check that a source outside the bounding box is flagged as not used (False)."""
172 sourceCat = self.makeCatalog()
173 source = sourceCat.addNew()
174 nameAp = self.names[0] + "Ap"
175 source[nameAp + "_instFlux"] = 5.1
176 source[nameAp + "_instFluxErr"] = 1e-3
177 source[self.meas_apCorr_task.config.refFluxName + "_instFlux"] = 5.1
178 source[self.meas_apCorr_task.config.refFluxName + "_instFluxErr"] = 1e-3
179 centroidKey = afwTable.Point2DKey(self.schema["slot_Centroid"])
180 source.set(centroidKey, lsst.geom.Point2D(15, 7.1))
181 apCorrFlagName = "apcorr_" + nameAp + "_used"
183 self.meas_apCorr_task.run(catalog=sourceCat, exposure=self.exposure)
184 # Check that all but the final source are used.
185 self.assertTrue(sourceCat[apCorrFlagName][0: -1].all())
186 # Check that the final source is not used.
187 self.assertFalse(sourceCat[apCorrFlagName][-1])
189 def testSourceUsed(self):
190 """Check that valid sources inside the bounding box that are used have their flags set to True."""
191 sourceCat = self.makeCatalog()
192 self.meas_apCorr_task.run(catalog=sourceCat, exposure=self.exposure)
193 for name in self.names:
194 self.assertTrue(sourceCat["apcorr_" + name + self.apNameStr + "_used"].all())
196 def testApertureMeasOnes(self):
197 """ Check that sources with aperture fluxes exactly the same as their catalog fluxes
198 returns an aperture correction map of 1s"""
199 apFluxName = self.names[0] + self.apNameStr + "_instFlux"
200 sourceCat = self.makeCatalog()
201 struct = self.meas_apCorr_task.run(catalog=sourceCat, exposure=self.exposure)
202 default_fill = apCorrDefaultMap(value=1.0, bbox=self.exposure.getBBox())
203 test_fill = afwImage.ImageF(self.exposure.getBBox())
204 struct.apCorrMap[apFluxName].fillImage(test_fill)
205 np.testing.assert_allclose(test_fill.getArray(), default_fill.getArray())
207 def testApertureMeasTens(self):
208 """Check that aperture correction scales source fluxes in the correct direction."""
209 apCorr_factor = 10.
210 sourceCat = self.makeCatalog(apCorrScale=apCorr_factor)
211 apFluxName = self.names[0] + self.apNameStr + "_instFlux"
212 struct = self.meas_apCorr_task.run(catalog=sourceCat, exposure=self.exposure)
213 default_fill = apCorrDefaultMap(value=apCorr_factor, bbox=self.exposure.getBBox())
214 test_fill = afwImage.ImageF(self.exposure.getBBox())
215 struct.apCorrMap[apFluxName].fillImage(test_fill)
216 np.testing.assert_allclose(test_fill.getArray(), default_fill.getArray())
218 def testFilterBadValue(self):
219 """Check that the aperture correction filters a bad value."""
220 sourceCat = self.makeCatalog()
221 source = sourceCat.addNew()
222 nameAp = self.names[0] + self.apNameStr
223 source[nameAp + "_instFlux"] = 100.0
224 source[nameAp + "_instFluxErr"] = 1e-3
225 source[self.meas_apCorr_task.config.refFluxName + "_instFlux"] = 5.1
226 source[self.meas_apCorr_task.config.refFluxName + "_instFluxErr"] = 1e-3
227 source[self.unresolvedName] = 0.0
228 centroidKey = afwTable.Point2DKey(self.schema["slot_Centroid"])
229 x = self.exposure.getX0() + 1
230 y = self.exposure.getY0() + 1
231 source.set(centroidKey, lsst.geom.Point2D(x, y))
233 self.meas_apCorr_task.run(catalog=sourceCat, exposure=self.exposure)
235 # Check that both Ap fluxes are removed as outliers; one is due
236 # to being unfilled (nan), the other is a large outlier.
237 for name in self.names:
238 apCorrFlagName = "apcorr_" + name + self.apNameStr + "_used"
239 # Check that all but the final source are used.
240 self.assertTrue(sourceCat[apCorrFlagName][0: -1].all())
241 # Check that the final source is not used.
242 self.assertFalse(sourceCat[apCorrFlagName][-1])
244 def testTooFewSourcesAfterFiltering(self):
245 """Check that the aperture correction fails when too many are filtered."""
246 sourceCat = self.makeCatalog()
247 self.meas_apCorr_task.config.minDegreesOfFreedom = 4
249 for name in self.names:
250 nameAp = name + self.apNameStr
251 sourceCat[nameAp + "_instFlux"][0] = 100.0
253 with self.assertRaisesRegex(measureApCorr.MeasureApCorrError,
254 f"Unable to measure aperture correction for '{nameAp}'"):
255 self.meas_apCorr_task.run(catalog=sourceCat, exposure=self.exposure)
257 # We now try again after declaring that the aperture correction is
258 # allowed to fail. This should run cleanly without raising an exception.
259 for name in self.names:
260 self.meas_apCorr_task.config.allowFailure.append(name + self.apNameStr)
261 self.meas_apCorr_task.run(catalog=sourceCat, exposure=self.exposure)
264class TestMemory(lsst.utils.tests.MemoryTestCase):
265 pass
268def setup_module(module):
269 lsst.utils.tests.init()
272if __name__ == "__main__": 272 ↛ 273line 272 didn't jump to line 273 because the condition on line 272 was never true
273 lsst.utils.tests.init()
274 unittest.main()