Coverage for tests/test_transformDiaSourceCatalog.py: 19%

118 statements  

« prev     ^ index     » next       coverage.py v7.2.5, created at 2023-05-06 11:14 +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/>. 

21 

22import os 

23import unittest 

24 

25import numpy as np 

26 

27from lsst.ap.association.transformDiaSourceCatalog import (TransformDiaSourceCatalogConfig, 

28 TransformDiaSourceCatalogTask) 

29from lsst.afw.cameraGeom.testUtils import DetectorWrapper 

30import lsst.daf.base as dafBase 

31import lsst.afw.image as afwImage 

32import lsst.geom as geom 

33import lsst.meas.base.tests as measTests 

34from lsst.pipe.base import Struct 

35import lsst.utils.tests 

36 

37from lsst.ap.association.transformDiaSourceCatalog import UnpackApdbFlags 

38 

39TESTDIR = os.path.abspath(os.path.dirname(__file__)) 

40 

41 

42class TestTransformDiaSourceCatalogTask(unittest.TestCase): 

43 def setUp(self): 

44 # The first source will be a sky source. 

45 self.nSources = 10 

46 # Default PSF size (psfDim in makeEmptyExposure) in TestDataset results 

47 # in an 18 pixel wide source box. 

48 self.bboxSize = 18 

49 self.yLoc = 100 

50 self.bbox = geom.Box2I(geom.Point2I(0, 0), 

51 geom.Extent2I(1024, 1153)) 

52 dataset = measTests.TestDataset(self.bbox) 

53 for srcIdx in range(self.nSources-1): 

54 # Place sources at (index, yLoc), so we can distinguish them later. 

55 dataset.addSource(100000.0, geom.Point2D(srcIdx, self.yLoc)) 

56 # Ensure the last source has no peak `significance` field. 

57 dataset.addSource(100000.0, geom.Point2D(srcIdx+1, self.yLoc), setPeakSignificance=False) 

58 schema = dataset.makeMinimalSchema() 

59 schema.addField("base_PixelFlags_flag", type="Flag") 

60 schema.addField("base_PixelFlags_flag_offimage", type="Flag") 

61 schema.addField("sky_source", type="Flag", doc="Sky objects.") 

62 self.exposure, self.inputCatalog = dataset.realize(10.0, schema, randomSeed=1234) 

63 self.inputCatalog[0]['sky_source'] = True 

64 # Create schemas for use in initializing the TransformDiaSourceCatalog task. 

65 self.initInputs = {"diaSourceSchema": Struct(schema=schema)} 

66 self.initInputsBadFlags = {"diaSourceSchema": Struct(schema=dataset.makeMinimalSchema())} 

67 

68 self.expId = 4321 

69 self.date = dafBase.DateTime(nsecs=1400000000 * 10**9) 

70 detector = DetectorWrapper(id=23, bbox=self.exposure.getBBox()).detector 

71 visit = afwImage.VisitInfo( 

72 exposureId=self.expId, 

73 exposureTime=200., 

74 date=self.date) 

75 self.exposure.info.id = self.expId 

76 self.exposure.setDetector(detector) 

77 self.exposure.getInfo().setVisitInfo(visit) 

78 self.filterName = 'g' 

79 self.exposure.setFilter(afwImage.FilterLabel(band=self.filterName, physical='g.MP9401')) 

80 scale = 2 

81 scaleErr = 1 

82 self.photoCalib = afwImage.PhotoCalib(scale, scaleErr) 

83 self.exposure.setPhotoCalib(self.photoCalib) 

84 

85 self.config = TransformDiaSourceCatalogConfig() 

86 self.config.flagMap = os.path.join(TESTDIR, "data", "test-flag-map.yaml") 

87 self.config.functorFile = os.path.join(TESTDIR, 

88 "data", 

89 "testDiaSource.yaml") 

90 

91 def test_run(self): 

92 """Test output dataFrame is created and values are correctly inserted 

93 from the exposure. 

94 """ 

95 transformTask = TransformDiaSourceCatalogTask(initInputs=self.initInputs, 

96 config=self.config) 

97 result = transformTask.run(self.inputCatalog, 

98 self.exposure, 

99 self.filterName, 

100 ccdVisitId=self.expId) 

101 

102 self.assertEqual(len(result.diaSourceTable), len(self.inputCatalog)) 

103 np.testing.assert_array_equal(result.diaSourceTable["bboxSize"], [self.bboxSize]*self.nSources) 

104 np.testing.assert_array_equal(result.diaSourceTable["ccdVisitId"], [self.expId]*self.nSources) 

105 np.testing.assert_array_equal(result.diaSourceTable["filterName"], [self.filterName]*self.nSources) 

106 np.testing.assert_array_equal(result.diaSourceTable["midPointTai"], 

107 [self.date.get(system=dafBase.DateTime.MJD)]*self.nSources) 

108 np.testing.assert_array_equal(result.diaSourceTable["diaObjectId"], [0]*self.nSources) 

109 np.testing.assert_array_equal(result.diaSourceTable["x"], np.arange(self.nSources)) 

110 # The final snr value should be NaN because it doesn't have a peak significance field. 

111 expect_snr = [397.887353515625]*9 

112 expect_snr.append(np.nan) 

113 # Have to use allclose because assert_array_equal doesn't support equal_nan. 

114 np.testing.assert_allclose(result.diaSourceTable["snr"], expect_snr, equal_nan=True, rtol=0) 

115 

116 def test_run_doSkySources(self): 

117 """Test that we get the correct output with doSkySources=True; the one 

118 sky source should be missing, but the other records should be the same. 

119 

120 We only test the fields here that could be different, not the ones that 

121 are the same for all sources. 

122 """ 

123 # Make the sky source have a different significance value, to distinguish it. 

124 self.inputCatalog[0].getFootprint().updatePeakSignificance(5.0) 

125 

126 self.config.doRemoveSkySources = True 

127 task = TransformDiaSourceCatalogTask(initInputs=self.initInputs, config=self.config) 

128 result = task.run(self.inputCatalog, self.exposure, self.filterName, ccdVisitId=self.expId) 

129 

130 self.assertEqual(len(result.diaSourceTable), self.nSources-1) 

131 # 0th source was removed, so x positions of the remaining sources are at x=1,2,3... 

132 np.testing.assert_array_equal(result.diaSourceTable["x"], np.arange(self.nSources-1)+1) 

133 # The final snr value should be NaN because it doesn't have a peak significance field. 

134 expect_snr = [397.887353515625]*8 

135 expect_snr.append(np.nan) 

136 # Have to use allclose because assert_array_equal doesn't support equal_nan. 

137 np.testing.assert_allclose(result.diaSourceTable["snr"], expect_snr, equal_nan=True, rtol=0) 

138 

139 def test_run_dia_source_wrong_flags(self): 

140 """Test that the proper errors are thrown when requesting flag columns 

141 that are not in the input schema. 

142 """ 

143 with self.assertRaises(KeyError): 

144 TransformDiaSourceCatalogTask(initInputs=self.initInputsBadFlags) 

145 

146 def test_computeBBoxSize(self): 

147 transform = TransformDiaSourceCatalogTask(initInputs=self.initInputs, 

148 config=self.config) 

149 boxSizes = transform.computeBBoxSizes(self.inputCatalog) 

150 

151 for size in boxSizes: 

152 self.assertEqual(size, self.bboxSize) 

153 self.assertEqual(len(boxSizes), self.nSources) 

154 

155 def test_bit_unpacker(self): 

156 """Test that the integer bit packer is functioning correctly. 

157 """ 

158 transform = TransformDiaSourceCatalogTask(initInputs=self.initInputs, 

159 config=self.config) 

160 for idx, obj in enumerate(self.inputCatalog): 

161 if idx in [1, 3, 5]: 

162 obj.set("base_PixelFlags_flag", 1) 

163 if idx in [1, 4, 6]: 

164 obj.set("base_PixelFlags_flag_offimage", 1) 

165 outputCatalog = transform.run(self.inputCatalog, 

166 self.exposure, 

167 self.filterName, 

168 ccdVisitId=self.expId).diaSourceTable 

169 

170 unpacker = UnpackApdbFlags(self.config.flagMap, "DiaSource") 

171 flag_values = unpacker.unpack(outputCatalog["flags"], "flags") 

172 

173 for idx, flag in enumerate(flag_values): 

174 if idx in [1, 3, 5]: 

175 self.assertTrue(flag['base_PixelFlags_flag']) 

176 else: 

177 self.assertFalse(flag['base_PixelFlags_flag']) 

178 

179 if idx in [1, 4, 6]: 

180 self.assertTrue(flag['base_PixelFlags_flag_offimage']) 

181 else: 

182 self.assertFalse(flag['base_PixelFlags_flag_offimage']) 

183 

184 def test_flag_existence_check(self): 

185 unpacker = UnpackApdbFlags(self.config.flagMap, "DiaSource") 

186 

187 self.assertTrue(unpacker.flagExists('base_PixelFlags_flag')) 

188 self.assertFalse(unpacker.flagExists('')) 

189 with self.assertRaisesRegex(ValueError, 'column doesNotExist not in flag map'): 

190 unpacker.flagExists('base_PixelFlags_flag', columnName='doesNotExist') 

191 

192 def test_flag_bitmask(self): 

193 """Test that we get the expected bitmask back from supplied flag names. 

194 """ 

195 unpacker = UnpackApdbFlags(self.config.flagMap, "DiaSource") 

196 

197 with self.assertRaisesRegex(ValueError, "flag '' not included"): 

198 unpacker.makeFlagBitMask(['']) 

199 with self.assertRaisesRegex(ValueError, 'column doesNotExist not in flag map'): 

200 unpacker.makeFlagBitMask(['base_PixelFlags_flag'], columnName='doesNotExist') 

201 self.assertEqual(unpacker.makeFlagBitMask(['base_PixelFlags_flag']), np.uint64(1)) 

202 self.assertEqual(unpacker.makeFlagBitMask(['base_PixelFlags_flag_offimage']), np.uint64(2)) 

203 self.assertEqual(unpacker.makeFlagBitMask(['base_PixelFlags_flag', 

204 'base_PixelFlags_flag_offimage']), 

205 np.uint64(3)) 

206 

207 

208class MemoryTester(lsst.utils.tests.MemoryTestCase): 

209 pass 

210 

211 

212def setup_module(module): 

213 lsst.utils.tests.init() 

214 

215 

216if __name__ == "__main__": 216 ↛ 217line 216 didn't jump to line 217, because the condition on line 216 was never true

217 lsst.utils.tests.init() 

218 unittest.main()