Coverage for tests/test_sourceSelector.py: 14%

301 statements  

« 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-2017 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# 

23 

24import unittest 

25import numpy as np 

26import astropy.units as u 

27import warnings 

28 

29import lsst.afw.table 

30import lsst.meas.algorithms 

31import lsst.meas.base.tests 

32import lsst.pipe.base 

33import lsst.utils.tests 

34 

35from lsst.meas.algorithms import ColorLimit 

36 

37 

38class SourceSelectorTester: 

39 """Mixin for testing 

40 

41 This provides a base class for doing tests common to the 

42 ScienceSourceSelectorTask and ReferenceSourceSelectorTask. 

43 """ 

44 Task = None 

45 

46 def setUp(self): 

47 schema = lsst.afw.table.SourceTable.makeMinimalSchema() 

48 schema.addField("flux", float, "Flux value") 

49 schema.addField("flux_flag", "Flag", "Bad flux?") 

50 schema.addField("other_flux", float, "Flux value 2") 

51 schema.addField("other_flux_flag", "Flag", "Bad flux 2?") 

52 schema.addField("other_fluxErr", float, "Flux error 2") 

53 schema.addField("goodFlag", "Flag", "Flagged if good") 

54 schema.addField("badFlag", "Flag", "Flagged if bad") 

55 schema.addField("starGalaxy", float, "0=star, 1=galaxy") 

56 schema.addField("nChild", np.int32, "Number of children") 

57 schema.addField("detect_isPrimary", "Flag", "Is primary detection?") 

58 schema.addField("sky_source", "Flag", "Empty sky region.") 

59 self.catalog = lsst.afw.table.SourceCatalog(schema) 

60 self.catalog.reserve(10) 

61 self.config = self.Task.ConfigClass() 

62 

63 def tearDown(self): 

64 del self.catalog 

65 

66 def check(self, expected): 

67 task = self.Task(config=self.config) 

68 results = task.run(self.catalog) 

69 self.assertListEqual(results.selected.tolist(), expected) 

70 self.assertListEqual([src.getId() for src in results.sourceCat], 

71 [src.getId() for src, ok in zip(self.catalog, expected) if ok]) 

72 

73 # Check with pandas.DataFrame version of catalog 

74 results = task.run(self.catalog.asAstropy().to_pandas()) 

75 self.assertListEqual(results.selected.tolist(), expected) 

76 self.assertListEqual(list(results.sourceCat['id']), 

77 [src.getId() for src, ok in zip(self.catalog, expected) if ok]) 

78 

79 # Check with astropy.table.Table version of catalog 

80 results = task.run(self.catalog.asAstropy()) 

81 self.assertListEqual(results.selected.tolist(), expected) 

82 self.assertListEqual(list(results.sourceCat['id']), 

83 [src.getId() for src, ok in zip(self.catalog, expected) if ok]) 

84 

85 def testFlags(self): 

86 bad1 = self.catalog.addNew() 

87 bad1.set("goodFlag", False) 

88 bad1.set("badFlag", False) 

89 bad2 = self.catalog.addNew() 

90 bad2.set("goodFlag", True) 

91 bad2.set("badFlag", True) 

92 bad3 = self.catalog.addNew() 

93 bad3.set("goodFlag", False) 

94 bad3.set("badFlag", True) 

95 good = self.catalog.addNew() 

96 good.set("goodFlag", True) 

97 good.set("badFlag", False) 

98 self.catalog["flux"] = 1.0 

99 self.catalog["other_flux"] = 1.0 

100 self.config.flags.good = ["goodFlag"] 

101 self.config.flags.bad = ["badFlag"] 

102 self.check([False, False, False, True]) 

103 

104 def testSignalToNoise(self): 

105 low = self.catalog.addNew() 

106 low.set("other_flux", 1.0) 

107 low.set("other_fluxErr", 1.0) 

108 good = self.catalog.addNew() 

109 good.set("other_flux", 1.0) 

110 good.set("other_fluxErr", 0.1) 

111 high = self.catalog.addNew() 

112 high.set("other_flux", 1.0) 

113 high.set("other_fluxErr", 0.001) 

114 self.config.doSignalToNoise = True 

115 self.config.signalToNoise.fluxField = "other_flux" 

116 self.config.signalToNoise.errField = "other_fluxErr" 

117 self.config.signalToNoise.minimum = 5.0 

118 self.config.signalToNoise.maximum = 100.0 

119 self.check([False, True, False]) 

120 

121 def testSignalToNoiseNoWarn(self): 

122 low = self.catalog.addNew() 

123 low.set("other_flux", np.nan) 

124 low.set("other_fluxErr", np.nan) 

125 self.config.doSignalToNoise = True 

126 self.config.signalToNoise.fluxField = "other_flux" 

127 self.config.signalToNoise.errField = "other_fluxErr" 

128 # Ensure no warnings are raised. 

129 with warnings.catch_warnings(): 

130 warnings.simplefilter("error") 

131 self.check([False]) 

132 

133 

134class ScienceSourceSelectorTaskTest(SourceSelectorTester, lsst.utils.tests.TestCase): 

135 Task = lsst.meas.algorithms.ScienceSourceSelectorTask 

136 

137 def setUp(self): 

138 SourceSelectorTester.setUp(self) 

139 self.config.fluxLimit.fluxField = "flux" 

140 self.config.flags.bad = [] 

141 self.config.doFluxLimit = True 

142 self.config.doFlags = True 

143 self.config.doUnresolved = False 

144 self.config.doIsolated = False 

145 

146 def testFluxLimit(self): 

147 tooBright = self.catalog.addNew() 

148 tooBright.set("flux", 1.0e10) 

149 tooBright.set("flux_flag", False) 

150 good = self.catalog.addNew() 

151 good.set("flux", 1000.0) 

152 good.set("flux_flag", False) 

153 bad = self.catalog.addNew() 

154 bad.set("flux", good.get("flux")) 

155 bad.set("flux_flag", True) 

156 tooFaint = self.catalog.addNew() 

157 tooFaint.set("flux", 1.0) 

158 tooFaint.set("flux_flag", False) 

159 self.config.fluxLimit.minimum = 10.0 

160 self.config.fluxLimit.maximum = 1.0e6 

161 self.config.fluxLimit.fluxField = "flux" 

162 self.check([False, True, False, False]) 

163 

164 # Works with no maximum set? 

165 self.config.fluxLimit.maximum = None 

166 self.check([True, True, False, False]) 

167 

168 # Works with no minimum set? 

169 self.config.fluxLimit.minimum = None 

170 self.check([True, True, False, True]) 

171 

172 def testUnresolved(self): 

173 num = 5 

174 for _ in range(num): 

175 self.catalog.addNew() 

176 self.catalog["flux"] = 1.0 

177 starGalaxy = np.linspace(0.0, 1.0, num, False) 

178 self.catalog["starGalaxy"] = starGalaxy 

179 self.config.doUnresolved = True 

180 self.config.unresolved.name = "starGalaxy" 

181 minimum, maximum = 0.3, 0.7 

182 self.config.unresolved.minimum = minimum 

183 self.config.unresolved.maximum = maximum 

184 self.check(((starGalaxy > minimum) & (starGalaxy < maximum)).tolist()) 

185 

186 # Works with no minimum set? 

187 self.config.unresolved.minimum = None 

188 self.check((starGalaxy < maximum).tolist()) 

189 

190 # Works with no maximum set? 

191 self.config.unresolved.minimum = minimum 

192 self.config.unresolved.maximum = None 

193 self.check((starGalaxy > minimum).tolist()) 

194 

195 def testIsolated(self): 

196 num = 5 

197 for _ in range(num): 

198 self.catalog.addNew() 

199 self.catalog["flux"] = 1.0 

200 parent = np.array([0, 0, 10, 0, 0], dtype=int) 

201 nChild = np.array([2, 0, 0, 0, 0], dtype=int) 

202 self.catalog["parent"] = parent 

203 self.catalog["nChild"] = nChild 

204 self.config.doIsolated = True 

205 self.config.isolated.parentName = "parent" 

206 self.config.isolated.nChildName = "nChild" 

207 self.check(((parent == 0) & (nChild == 0)).tolist()) 

208 

209 def testRequireFiniteRaDec(self): 

210 num = 5 

211 for _ in range(num): 

212 self.catalog.addNew() 

213 ra = np.array([np.nan, np.nan, 0, 0, 0], dtype=float) 

214 dec = np.array([2, np.nan, 0, 0, np.nan], dtype=float) 

215 self.catalog["coord_ra"] = ra 

216 self.catalog["coord_dec"] = dec 

217 self.config.doRequireFiniteRaDec = True 

218 self.config.requireFiniteRaDec.raColName = "coord_ra" 

219 self.config.requireFiniteRaDec.decColName = "coord_dec" 

220 self.check((np.isfinite(ra) & np.isfinite(dec)).tolist()) 

221 

222 def testRequirePrimary(self): 

223 num = 5 

224 for _ in range(num): 

225 self.catalog.addNew() 

226 primary = np.array([True, True, False, True, False], dtype=bool) 

227 self.catalog["detect_isPrimary"] = primary 

228 self.config.doRequirePrimary = True 

229 self.config.requirePrimary.primaryColName = "detect_isPrimary" 

230 self.check(primary.tolist()) 

231 

232 def testSkySource(self): 

233 num = 5 

234 for _ in range(num): 

235 self.catalog.addNew() 

236 sky = np.array([True, True, False, True, False], dtype=bool) 

237 self.catalog["sky_source"] = sky 

238 # This is a union, not an intersection, so include another selection 

239 # that would otherwise reject everything. 

240 self.config.doRequirePrimary = True 

241 self.config.doSkySources = True 

242 self.check(sky.tolist()) 

243 

244 

245class ReferenceSourceSelectorTaskTest(SourceSelectorTester, lsst.utils.tests.TestCase): 

246 Task = lsst.meas.algorithms.ReferenceSourceSelectorTask 

247 

248 def setUp(self): 

249 SourceSelectorTester.setUp(self) 

250 self.config.magLimit.fluxField = "flux" 

251 self.config.doMagLimit = True 

252 self.config.doFlags = True 

253 self.config.doUnresolved = False 

254 self.config.doRequireFiniteRaDec = False 

255 

256 def testMagnitudeLimit(self): 

257 tooBright = self.catalog.addNew() 

258 tooBright.set("flux", 1.0e10) 

259 tooBright.set("flux_flag", False) 

260 good = self.catalog.addNew() 

261 good.set("flux", 1000.0) 

262 good.set("flux_flag", False) 

263 bad = self.catalog.addNew() 

264 bad.set("flux", good.get("flux")) 

265 bad.set("flux_flag", True) 

266 tooFaint = self.catalog.addNew() 

267 tooFaint.set("flux", 1.0) 

268 tooFaint.set("flux_flag", False) 

269 # Note: magnitudes are backwards, so the minimum flux is the maximum magnitude 

270 self.config.magLimit.minimum = (1.0e6*u.nJy).to_value(u.ABmag) 

271 self.config.magLimit.maximum = (10.0*u.nJy).to_value(u.ABmag) 

272 self.config.magLimit.fluxField = "flux" 

273 self.check([False, True, False, False]) 

274 

275 # Works with no minimum set? 

276 self.config.magLimit.minimum = None 

277 self.check([True, True, False, False]) 

278 

279 # Works with no maximum set? 

280 self.config.magLimit.maximum = None 

281 self.check([True, True, False, True]) 

282 

283 def testMagErrorLimit(self): 

284 # Using an arbitrary field as if it was a magnitude error to save adding a new field 

285 field = "other_fluxErr" 

286 tooFaint = self.catalog.addNew() 

287 tooFaint.set(field, 0.5) 

288 tooBright = self.catalog.addNew() 

289 tooBright.set(field, 0.00001) 

290 good = self.catalog.addNew() 

291 good.set(field, 0.2) 

292 

293 self.config.doMagError = True 

294 self.config.magError.minimum = 0.01 

295 self.config.magError.maximum = 0.3 

296 self.config.magError.magErrField = field 

297 self.check([False, False, True]) 

298 

299 def testColorLimits(self): 

300 num = 10 

301 for _ in range(num): 

302 self.catalog.addNew() 

303 color = np.linspace(-0.5, 0.5, num, True) 

304 flux = 1000.0*u.nJy 

305 # Definition: color = mag(flux) - mag(otherFlux) 

306 otherFlux = (flux.to(u.ABmag) - color*u.mag).to_value(u.nJy) 

307 self.catalog["flux"] = flux.value 

308 self.catalog["other_flux"] = otherFlux 

309 minimum, maximum = -0.1, 0.2 

310 self.config.colorLimits = {"test": ColorLimit(primary="flux", secondary="other_flux", 

311 minimum=minimum, maximum=maximum)} 

312 self.check(((color > minimum) & (color < maximum)).tolist()) 

313 

314 # Works with no minimum set? 

315 self.config.colorLimits["test"].minimum = None 

316 self.check((color < maximum).tolist()) 

317 

318 # Works with no maximum set? 

319 self.config.colorLimits["test"].maximum = None 

320 self.config.colorLimits["test"].minimum = minimum 

321 self.check((color > minimum).tolist()) 

322 

323 # Multiple limits 

324 self.config.colorLimits = {"test": ColorLimit(primary="flux", secondary="other_flux", 

325 minimum=minimum), 

326 "other": ColorLimit(primary="flux", secondary="other_flux", 

327 maximum=maximum)} 

328 assert maximum > minimum # To be non-mutually-exclusive 

329 self.check(((color > minimum) & (color < maximum)).tolist()) 

330 

331 # Multiple mutually-exclusive limits 

332 self.config.colorLimits["test"] = ColorLimit(primary="flux", secondary="other_flux", maximum=-0.1) 

333 self.config.colorLimits["other"] = ColorLimit(primary="flux", secondary="other_flux", minimum=0.1) 

334 self.check([False]*num) 

335 

336 def testUnresolved(self): 

337 num = 5 

338 for _ in range(num): 

339 self.catalog.addNew() 

340 self.catalog["flux"] = 1.0 

341 starGalaxy = np.linspace(0.0, 1.0, num, False) 

342 self.catalog["starGalaxy"] = starGalaxy 

343 self.config.doUnresolved = True 

344 self.config.unresolved.name = "starGalaxy" 

345 minimum, maximum = 0.3, 0.7 

346 self.config.unresolved.minimum = minimum 

347 self.config.unresolved.maximum = maximum 

348 self.check(((starGalaxy > minimum) & (starGalaxy < maximum)).tolist()) 

349 

350 # Works with no minimum set? 

351 self.config.unresolved.minimum = None 

352 self.check((starGalaxy < maximum).tolist()) 

353 

354 # Works with no maximum set? 

355 self.config.unresolved.minimum = minimum 

356 self.config.unresolved.maximum = None 

357 self.check((starGalaxy > minimum).tolist()) 

358 

359 def testFiniteRaDec(self): 

360 "Test that non-finite RA and Dec values are caught." 

361 num = 5 

362 for _ in range(num): 

363 self.catalog.addNew() 

364 self.catalog["coord_ra"][:] = 1.0 

365 self.catalog["coord_dec"][:] = 1.0 

366 self.catalog["coord_ra"][0] = np.nan 

367 self.catalog["coord_dec"][1] = np.inf 

368 self.config.doRequireFiniteRaDec = True 

369 

370 self.check([False, False, True, True, True]) 

371 

372 

373class TestBaseSourceSelector(lsst.utils.tests.TestCase): 

374 """Test the API of the Abstract Base Class with a trivial example.""" 

375 def setUp(self): 

376 schema = lsst.meas.base.tests.TestDataset.makeMinimalSchema() 

377 self.selectedKeyName = "is_selected" 

378 schema.addField(self.selectedKeyName, type="Flag") 

379 self.catalog = lsst.afw.table.SourceCatalog(schema) 

380 for i in range(4): 

381 self.catalog.addNew() 

382 

383 self.sourceSelector = lsst.meas.algorithms.NullSourceSelectorTask() 

384 

385 def testRun(self): 

386 """Test that run() returns a catalog and boolean selected array.""" 

387 result = self.sourceSelector.run(self.catalog) 

388 for i, x in enumerate(self.catalog['id']): 

389 self.assertIn(x, result.sourceCat['id']) 

390 self.assertTrue(result.selected[i]) 

391 

392 def testRunSourceSelectedField(self): 

393 """Test that the selected flag is set in the original catalog.""" 

394 self.sourceSelector.run(self.catalog, sourceSelectedField=self.selectedKeyName) 

395 np.testing.assert_array_equal(self.catalog[self.selectedKeyName], True) 

396 

397 def testRunNonContiguousRaises(self): 

398 """Cannot do source selection on non-contiguous catalogs.""" 

399 del self.catalog[1] # take one out of the middle to make it non-contiguous. 

400 self.assertFalse(self.catalog.isContiguous(), "Catalog is contiguous: the test won't work.") 

401 

402 with self.assertRaises(RuntimeError): 

403 self.sourceSelector.run(self.catalog) 

404 

405 

406class TestMemory(lsst.utils.tests.MemoryTestCase): 

407 pass 

408 

409 

410def setup_module(module): 

411 lsst.utils.tests.init() 

412 

413 

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

415 import sys 

416 setup_module(sys.modules[__name__]) 

417 unittest.main()