Coverage for tests/test_detectAndMeasure.py: 9%

797 statements  

« prev     ^ index     » next       coverage.py v7.10.0, created at 2025-07-26 08:37 +0000

1# This file is part of ip_diffim. 

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 numpy as np 

23import os 

24import unittest 

25from unittest import mock 

26import requests 

27 

28import lsst.afw.geom as afwGeom 

29import lsst.afw.image as afwImage 

30import lsst.afw.math as afwMath 

31import lsst.geom 

32from lsst.ip.diffim import detectAndMeasure, subtractImages 

33from lsst.afw.table import IdFactory 

34from lsst.afw.cameraGeom.testUtils import DetectorWrapper 

35import lsst.meas.algorithms as measAlg 

36from lsst.pipe.base import InvalidQuantumError, UpstreamFailureNoWorkFound, AlgorithmError 

37import lsst.utils.tests 

38import lsst.meas.base.tests 

39import lsst.daf.base as dafBase 

40from lsst.afw.coord import Observatory, Weather 

41import lsst.geom as geom 

42import lsst.pex.config as pexConfig 

43 

44from utils import makeTestImage, checkMask 

45 

46 

47class DetectAndMeasureTestBase: 

48 

49 def _check_diaSource(self, refSources, diaSource, refIds=None, 

50 matchDistance=1., scale=1., usePsfFlux=True, 

51 rtol=0.025, atol=None): 

52 """Match a diaSource with a source in a reference catalog 

53 and compare properties. 

54 

55 Parameters 

56 ---------- 

57 refSources : `lsst.afw.table.SourceCatalog` 

58 The reference catalog. 

59 diaSource : `lsst.afw.table.SourceRecord` 

60 The new diaSource to match to the reference catalog. 

61 refIds : `list` of `int`, optional 

62 Source IDs of previously associated diaSources. 

63 matchDistance : `float`, optional 

64 Maximum distance allowed between the detected and reference source 

65 locations, in pixels. 

66 scale : `float`, optional 

67 Optional factor to scale the flux by before performing the test. 

68 usePsfFlux : `bool`, optional 

69 If set, test the PsfInstFlux field, otherwise use ApInstFlux. 

70 rtol : `float`, optional 

71 Relative tolerance of the flux value test. 

72 atol : `float`, optional 

73 Absolute tolerance of the flux value test. 

74 """ 

75 if diaSource["sky_source"]: 

76 return 

77 distance = np.sqrt((diaSource.getX() - refSources.getX())**2 

78 + (diaSource.getY() - refSources.getY())**2) 

79 self.assertLess(min(distance), matchDistance) 

80 src = refSources[np.argmin(distance)] 

81 if refIds is not None: 

82 # Check that the same source was not previously associated 

83 self.assertNotIn(src.getId(), refIds) 

84 refIds.append(src.getId()) 

85 if atol is None: 

86 atol = rtol*src.getPsfInstFlux() if usePsfFlux else rtol*src.getApInstFlux() 

87 if usePsfFlux: 

88 self.assertFloatsAlmostEqual(src.getPsfInstFlux()*scale, diaSource.getPsfInstFlux(), 

89 rtol=rtol, atol=atol) 

90 else: 

91 self.assertFloatsAlmostEqual(src.getApInstFlux()*scale, diaSource.getApInstFlux(), 

92 rtol=rtol, atol=atol) 

93 

94 def _check_values(self, values, minValue=None, maxValue=None): 

95 """Verify that an array has finite values, and optionally that they are 

96 within specified minimum and maximum bounds. 

97 

98 Parameters 

99 ---------- 

100 values : `numpy.ndarray` 

101 Array of values to check. 

102 minValue : `float`, optional 

103 Minimum allowable value. 

104 maxValue : `float`, optional 

105 Maximum allowable value. 

106 """ 

107 self.assertTrue(np.all(np.isfinite(values))) 

108 if minValue is not None: 

109 self.assertTrue(np.all(values >= minValue)) 

110 if maxValue is not None: 

111 self.assertTrue(np.all(values <= maxValue)) 

112 

113 def _setup_detection(self, doSkySources=True, nSkySources=5, 

114 doSubtractBackground=False, run_sattle=False, **kwargs): 

115 """Setup and configure the detection and measurement PipelineTask. 

116 

117 Parameters 

118 ---------- 

119 doSkySources : `bool`, optional 

120 Generate sky sources. 

121 nSkySources : `int`, optional 

122 The number of sky sources to add in isolated background regions. 

123 **kwargs 

124 Any additional config parameters to set. 

125 

126 Returns 

127 ------- 

128 `lsst.pipe.base.PipelineTask` 

129 The configured Task to use for detection and measurement. 

130 """ 

131 config = self.detectionTask.ConfigClass() 

132 config.doSkySources = doSkySources 

133 if doSkySources: 

134 config.skySources.nSources = nSkySources 

135 config.update(**kwargs) 

136 

137 config.run_sattle = run_sattle 

138 

139 # Make a realistic id generator so that output catalog ids are useful. 

140 dataId = lsst.daf.butler.DataCoordinate.standardize( 

141 instrument="I", 

142 visit=42, 

143 detector=12, 

144 universe=lsst.daf.butler.DimensionUniverse(), 

145 ) 

146 config.idGenerator.packer.name = "observation" 

147 config.idGenerator.packer["observation"].n_observations = 10000 

148 config.idGenerator.packer["observation"].n_detectors = 99 

149 config.idGenerator.n_releases = 8 

150 config.idGenerator.release_id = 2 

151 config.doSubtractBackground = doSubtractBackground 

152 self.idGenerator = config.idGenerator.apply(dataId) 

153 

154 return self.detectionTask(config=config) 

155 

156 

157class DetectAndMeasureTest(DetectAndMeasureTestBase, lsst.utils.tests.TestCase): 

158 detectionTask = detectAndMeasure.DetectAndMeasureTask 

159 

160 def test_detection_xy0(self): 

161 """Basic functionality test with non-zero x0 and y0. 

162 """ 

163 # Set up the simulated images 

164 noiseLevel = 1. 

165 staticSeed = 1 

166 fluxLevel = 500 

167 kwargs = {"seed": staticSeed, "psfSize": 2.4, "fluxLevel": fluxLevel, "x0": 12345, "y0": 67890} 

168 science, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6, **kwargs) 

169 science.getInfo().setVisitInfo(makeVisitInfo()) 

170 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=7, **kwargs) 

171 difference = science.clone() 

172 

173 # Configure the detection Task 

174 # Set the subtraction residual metric threshold high, since the template 

175 # is not actually subtracted from the science image. 

176 detectionTask = self._setup_detection(doDeblend=True, badSubtractionRatioThreshold=1., 

177 doSkySources=False) 

178 

179 # Run detection and check the results 

180 output = detectionTask.run(science, matchedTemplate, difference, sources, 

181 idFactory=self.idGenerator.make_table_id_factory()) 

182 subtractedMeasuredExposure = output.subtractedMeasuredExposure 

183 

184 # Catalog ids should be very large from this id generator. 

185 self.assertTrue(all(output.diaSources['id'] > 1000000000)) 

186 self.assertImagesEqual(subtractedMeasuredExposure.image, difference.image) 

187 

188 # all of the sources should have been detected 

189 self.assertEqual(len(output.diaSources), len(sources)) 

190 # no sources should be flagged as negative 

191 self.assertEqual(len(~output.diaSources["is_negative"]), len(output.diaSources)) 

192 refIds = [] 

193 for source in sources: 

194 self._check_diaSource(output.diaSources, source, refIds=refIds) 

195 

196 def test_raise_bad_psf(self): 

197 """Detection should raise if the PSF width is NaN 

198 """ 

199 # Set up the simulated images 

200 noiseLevel = 1. 

201 staticSeed = 1 

202 fluxLevel = 500 

203 kwargs = {"seed": staticSeed, "psfSize": 2.4, "fluxLevel": fluxLevel, "x0": 12345, "y0": 67890} 

204 science, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6, **kwargs) 

205 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=7, **kwargs) 

206 difference = science.clone() 

207 

208 psfShape = difference.getPsf().computeBBox(lsst.geom.Point2D(0, 0)).getDimensions() 

209 psfcI = afwImage.ImageD(lsst.geom.Extent2I(psfShape[1], psfShape[0])) 

210 psfNew = np.zeros(psfShape) 

211 psfNew[0, :] = 1 

212 psfcI.array = psfNew 

213 psfcK = afwMath.FixedKernel(psfcI) 

214 psf = measAlg.KernelPsf(psfcK) 

215 difference.setPsf(psf) 

216 

217 # Configure the detection Task 

218 detectionTask = self._setup_detection() 

219 

220 # Run detection and check the results 

221 with self.assertRaises(UpstreamFailureNoWorkFound): 

222 detectionTask.run(science, matchedTemplate, difference, sources) 

223 

224 def test_measurements_finite(self): 

225 """Measured fluxes and centroids should always be finite. 

226 """ 

227 columnNames = ["coord_ra", "coord_dec", "ip_diffim_forced_PsfFlux_instFlux"] 

228 

229 # Set up the simulated images 

230 noiseLevel = 1. 

231 staticSeed = 1 

232 transientSeed = 6 

233 xSize = 256 

234 ySize = 256 

235 kwargs = {"psfSize": 2.4, "x0": 0, "y0": 0, 

236 "xSize": xSize, "ySize": ySize} 

237 science, sources = makeTestImage(seed=staticSeed, noiseLevel=noiseLevel, noiseSeed=6, 

238 nSrc=1, **kwargs) 

239 science.getInfo().setVisitInfo(makeVisitInfo()) 

240 matchedTemplate, _ = makeTestImage(seed=staticSeed, noiseLevel=noiseLevel/4, noiseSeed=7, 

241 nSrc=1, **kwargs) 

242 rng = np.random.RandomState(3) 

243 xLoc = np.arange(-5, xSize+5, 10) 

244 rng.shuffle(xLoc) 

245 yLoc = np.arange(-5, ySize+5, 10) 

246 rng.shuffle(yLoc) 

247 transients, transientSources = makeTestImage(seed=transientSeed, 

248 nSrc=len(xLoc), fluxLevel=1000., 

249 noiseLevel=noiseLevel, noiseSeed=8, 

250 xLoc=xLoc, yLoc=yLoc, 

251 **kwargs) 

252 difference = science.clone() 

253 difference.maskedImage -= matchedTemplate.maskedImage 

254 difference.maskedImage += transients.maskedImage 

255 

256 # Configure the detection Task 

257 detectionTask = self._setup_detection(doForcedMeasurement=True) 

258 

259 # Run detection and check the results 

260 output = detectionTask.run(science, matchedTemplate, difference, sources) 

261 

262 for column in columnNames: 

263 self._check_values(output.diaSources[column]) 

264 self._check_values(output.diaSources.getX(), minValue=0, maxValue=xSize) 

265 self._check_values(output.diaSources.getY(), minValue=0, maxValue=ySize) 

266 self._check_values(output.diaSources.getPsfInstFlux()) 

267 

268 def test_raise_config_schema_mismatch(self): 

269 """Check that sources with specified flags are removed from the catalog. 

270 """ 

271 # Configure the detection Task, and and set a config that is not in the schema 

272 with self.assertRaises(InvalidQuantumError): 

273 self._setup_detection(badSourceFlags=["Bogus_flag_42"]) 

274 

275 def test_remove_unphysical(self): 

276 """Check that sources with specified flags are removed from the catalog. 

277 """ 

278 # Set up the simulated images 

279 noiseLevel = 1. 

280 staticSeed = 1 

281 xSize = 256 

282 ySize = 256 

283 kwargs = {"psfSize": 2.4, "xSize": xSize, "ySize": ySize} 

284 science, sources = makeTestImage(seed=staticSeed, noiseLevel=noiseLevel, noiseSeed=6, 

285 nSrc=1, **kwargs) 

286 science.getInfo().setVisitInfo(makeVisitInfo()) 

287 matchedTemplate, _ = makeTestImage(seed=staticSeed, noiseLevel=noiseLevel/4, noiseSeed=7, 

288 nSrc=1, **kwargs) 

289 transients, transientSources = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=8, nSrc=1, **kwargs) 

290 science.maskedImage += transients.maskedImage 

291 difference = science.clone() 

292 bbox = difference.getBBox() 

293 difference.maskedImage -= matchedTemplate.maskedImage 

294 

295 # Configure the detection Task, and remove unphysical sources 

296 detectionTask = self._setup_detection(doForcedMeasurement=False, doSkySources=True, nSkySources=20, 

297 badSourceFlags=["base_PixelFlags_flag_offimage", ]) 

298 

299 # Run detection and check the results 

300 diaSources = detectionTask.run(science, matchedTemplate, difference, sources).diaSources 

301 badDiaSrcDoRemove = ~bbox.contains(diaSources.getX(), diaSources.getY()) 

302 nBadDoRemove = np.count_nonzero(badDiaSrcDoRemove) 

303 # Verify that all sources are physical 

304 self.assertEqual(nBadDoRemove, 0) 

305 # Set a few centroids outside the image bounding box 

306 nSetBad = 5 

307 for src in diaSources[0: nSetBad]: 

308 src["slot_Centroid_x"] += xSize 

309 src["slot_Centroid_y"] += ySize 

310 src["base_PixelFlags_flag_offimage"] = True 

311 # Verify that these sources are outside the image 

312 badDiaSrc = ~bbox.contains(diaSources.getX(), diaSources.getY()) 

313 nBad = np.count_nonzero(badDiaSrc) 

314 self.assertEqual(nBad, nSetBad) 

315 diaSourcesNoBad = detectionTask._removeBadSources(diaSources) 

316 badDiaSrcNoBad = ~bbox.contains(diaSourcesNoBad.getX(), diaSourcesNoBad.getY()) 

317 

318 # Verify that no sources outside the image bounding box remain 

319 self.assertEqual(np.count_nonzero(badDiaSrcNoBad), 0) 

320 self.assertEqual(len(diaSourcesNoBad), len(diaSources) - nSetBad) 

321 

322 def test_detect_transients(self): 

323 """Run detection on a difference image containing transients. 

324 """ 

325 # Set up the simulated images 

326 noiseLevel = 1. 

327 staticSeed = 1 

328 transientSeed = 6 

329 fluxLevel = 500 

330 kwargs = {"seed": staticSeed, "psfSize": 2.4, "fluxLevel": fluxLevel} 

331 scienceBase, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6, **kwargs) 

332 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=7, **kwargs) 

333 

334 # Configure the detection Task 

335 detectionTask = self._setup_detection(doMerge=False, doSkySources=True) 

336 kwargs["seed"] = transientSeed 

337 kwargs["nSrc"] = 10 

338 kwargs["fluxLevel"] = 1000 

339 

340 # Run detection and check the results 

341 def _detection_wrapper(positive=True): 

342 transients, transientSources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=8, **kwargs) 

343 science = scienceBase.clone() 

344 if positive: 

345 science.maskedImage += transients.maskedImage 

346 else: 

347 science.maskedImage -= transients.maskedImage 

348 difference = science.clone() 

349 difference.maskedImage -= matchedTemplate.maskedImage 

350 # NOTE: NoiseReplacer (run by forcedMeasurement) can modify the 

351 # science image if we've e.g. removed parents post-deblending. 

352 # Pass a clone of the science image, so that it doesn't disrupt 

353 # later tests. 

354 output = detectionTask.run(science, matchedTemplate, difference, sources) 

355 refIds = [] 

356 scale = 1. if positive else -1. 

357 for diaSource in output.diaSources: 

358 self._check_diaSource(transientSources, diaSource, refIds=refIds, scale=scale) 

359 _detection_wrapper(positive=True) 

360 _detection_wrapper(positive=False) 

361 

362 def test_detect_transients_with_background(self): 

363 """Run detection on a difference image containing transients and a background. 

364 """ 

365 # Set up the simulated images 

366 noiseLevel = 1. 

367 staticSeed = 1 

368 transientSeed = 6 

369 fluxLevel = 500 

370 xSize = 512 

371 ySize = 512 

372 x0 = 123 

373 y0 = 456 

374 kwargs = {"seed": staticSeed, "psfSize": 2.4, "fluxLevel": fluxLevel, 

375 "xSize": xSize, "ySize": ySize, "x0": x0, "y0": y0} 

376 params = [2.2, 2.1, 2.0, 1.2, 1.1, 1.0] 

377 

378 bbox2D = lsst.geom.Box2D(lsst.geom.Point2D(x0, y0), lsst.geom.Extent2D(xSize, ySize)) 

379 background_model = afwMath.Chebyshev1Function2D(params, bbox2D) 

380 scienceBase, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6, 

381 background=background_model, **kwargs) 

382 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=7, **kwargs) 

383 

384 # Configure the detection Task 

385 detectionTask = self._setup_detection(doMerge=False, doSubtractBackground=True) 

386 kwargs["seed"] = transientSeed 

387 kwargs["nSrc"] = 10 

388 kwargs["fluxLevel"] = 1000 

389 

390 # Run detection and check the results 

391 def _detection_wrapper(positive=True): 

392 transients, transientSources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=8, **kwargs) 

393 science = scienceBase.clone() 

394 if positive: 

395 science.maskedImage += transients.maskedImage 

396 else: 

397 science.maskedImage -= transients.maskedImage 

398 difference = science.clone() 

399 difference.maskedImage -= matchedTemplate.maskedImage 

400 # NOTE: NoiseReplacer (run by forcedMeasurement) can modify the 

401 # science image if we've e.g. removed parents post-deblending. 

402 # Pass a clone of the science image, so that it doesn't disrupt 

403 # later tests. 

404 output = detectionTask.run(science, matchedTemplate, difference, sources) 

405 refIds = [] 

406 scale = 1. if positive else -1. 

407 for transient in transientSources: 

408 self._check_diaSource(output.diaSources, transient, refIds=refIds, scale=scale) 

409 _detection_wrapper(positive=True) 

410 _detection_wrapper(positive=False) 

411 

412 def test_missing_mask_planes(self): 

413 """Check that detection runs with missing mask planes. 

414 """ 

415 # Set up the simulated images 

416 noiseLevel = 1. 

417 fluxLevel = 500 

418 kwargs = {"psfSize": 2.4, "fluxLevel": fluxLevel, "addMaskPlanes": []} 

419 # Use different seeds for the science and template so every source is a diaSource 

420 science, sources = makeTestImage(seed=5, noiseLevel=noiseLevel, noiseSeed=6, **kwargs) 

421 science.getInfo().setVisitInfo(makeVisitInfo()) 

422 matchedTemplate, _ = makeTestImage(seed=6, noiseLevel=noiseLevel/4, noiseSeed=7, **kwargs) 

423 

424 difference = science.clone() 

425 difference.maskedImage -= matchedTemplate.maskedImage 

426 detectionTask = self._setup_detection(raiseOnBadSubtractionRatio=False, raiseOnNoDiaSources=False) 

427 

428 # Verify that detection runs without errors 

429 detectionTask.run(science, matchedTemplate, difference, sources) 

430 

431 def test_detect_dipoles(self): 

432 """Run detection on a difference image containing dipoles. 

433 """ 

434 # Set up the simulated images 

435 noiseLevel = 1. 

436 staticSeed = 1 

437 fluxLevel = 1000 

438 fluxRange = 1.5 

439 nSources = 10 

440 offset = 1 

441 xSize = 300 

442 ySize = 300 

443 kernelSize = 32 

444 # Avoid placing sources near the edge for this test, so that we can 

445 # easily check that the correct number of sources are detected. 

446 templateBorderSize = kernelSize//2 

447 dipoleFlag = "ip_diffim_DipoleFit_classification" 

448 kwargs = {"seed": staticSeed, "psfSize": 2.4, "fluxLevel": fluxLevel, "fluxRange": fluxRange, 

449 "nSrc": nSources, "templateBorderSize": templateBorderSize, "kernelSize": kernelSize, 

450 "xSize": xSize, "ySize": ySize} 

451 dipoleFlag = "ip_diffim_DipoleFit_classification" 

452 science, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6, **kwargs) 

453 science.getInfo().setVisitInfo(makeVisitInfo()) 

454 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=7, **kwargs) 

455 difference = science.clone() 

456 matchedTemplate.image.array[...] = np.roll(matchedTemplate.image.array[...], offset, axis=0) 

457 matchedTemplate.variance.array[...] = np.roll(matchedTemplate.variance.array[...], offset, axis=0) 

458 matchedTemplate.mask.array[...] = np.roll(matchedTemplate.mask.array[...], offset, axis=0) 

459 difference.maskedImage -= matchedTemplate.maskedImage[science.getBBox()] 

460 

461 # Need a higher residual metric threshold, since we are purposely 

462 # creating poor subtractions. 

463 detectionTask = self._setup_detection(doMerge=True, badSubtractionRatioThreshold=0.3) 

464 output = detectionTask.run(science, matchedTemplate, difference, sources) 

465 diaSources = output.diaSources[~output.diaSources["sky_source"]].copy(deep=True) 

466 self.assertEqual(len(diaSources), len(sources)) 

467 # no sources should be flagged as negative 

468 self.assertEqual(len(~diaSources["is_negative"]), len(diaSources)) 

469 refIds = [] 

470 for diaSource in diaSources: 

471 if diaSource[dipoleFlag]: 

472 self._check_diaSource(sources, diaSource, refIds=refIds, scale=0, 

473 rtol=0.05, atol=None, usePsfFlux=False) 

474 self.assertFloatsAlmostEqual(diaSource["ip_diffim_DipoleFit_orientation"], 

475 -np.pi / 2, atol=2.) 

476 self.assertFloatsAlmostEqual(diaSource["ip_diffim_DipoleFit_separation"], offset, rtol=0.1) 

477 else: 

478 raise ValueError("DiaSource with ID %s is not a dipole!", diaSource.getId()) 

479 

480 def test_sky_sources(self): 

481 """Add sky sources and check that they are sufficiently far from other 

482 sources and have negligible flux. 

483 """ 

484 # Set up the simulated images 

485 noiseLevel = 1. 

486 staticSeed = 1 

487 transientSeed = 6 

488 transientFluxLevel = 1000. 

489 transientFluxRange = 1.5 

490 fluxLevel = 500 

491 kwargs = {"seed": staticSeed, "psfSize": 2.4, "fluxLevel": fluxLevel} 

492 science, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6, **kwargs) 

493 science.getInfo().setVisitInfo(makeVisitInfo()) 

494 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=7, **kwargs) 

495 transients, transientSources = makeTestImage(seed=transientSeed, psfSize=2.4, 

496 nSrc=10, fluxLevel=transientFluxLevel, 

497 fluxRange=transientFluxRange, 

498 noiseLevel=noiseLevel, noiseSeed=8) 

499 difference = science.clone() 

500 difference.maskedImage -= matchedTemplate.maskedImage 

501 difference.maskedImage += transients.maskedImage 

502 kernelWidth = np.max(science.psf.getKernel().getDimensions())//2 

503 

504 # Configure the detection Task 

505 detectionTask = self._setup_detection(doSkySources=True) 

506 

507 # Run detection and check the results 

508 output = detectionTask.run(science, matchedTemplate, difference, sources, 

509 idFactory=self.idGenerator.make_table_id_factory()) 

510 skySources = output.diaSources[output.diaSources["sky_source"]] 

511 self.assertEqual(len(skySources), detectionTask.config.skySources.nSources) 

512 for skySource in skySources: 

513 # Disable the sky_source flag to enable checks. 

514 skySource["sky_source"] = False 

515 # The sky sources should not be close to any other source 

516 with self.assertRaises(AssertionError): 

517 self._check_diaSource(transientSources, skySource, matchDistance=kernelWidth) 

518 with self.assertRaises(AssertionError): 

519 self._check_diaSource(sources, skySource, matchDistance=kernelWidth) 

520 # The sky sources should have low flux levels. 

521 self._check_diaSource(transientSources, skySource, matchDistance=1000, scale=0., 

522 atol=np.sqrt(transientFluxRange*transientFluxLevel)) 

523 

524 # Catalog ids should be very large from this id generator. 

525 self.assertTrue(all(output.diaSources['id'] > 1000000000)) 

526 

527 def test_exclude_mask_detections(self): 

528 """Sources with certain bad mask planes set should not be detected. 

529 """ 

530 # Set up the simulated images 

531 noiseLevel = 1. 

532 staticSeed = 1 

533 transientSeed = 6 

534 fluxLevel = 500 

535 radius = 2 

536 kwargs = {"seed": staticSeed, "psfSize": 2.4, "fluxLevel": fluxLevel} 

537 science, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6, **kwargs) 

538 science.getInfo().setVisitInfo(makeVisitInfo()) 

539 detector = DetectorWrapper(numAmps=1).detector 

540 science.setDetector(detector) 

541 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=7, **kwargs) 

542 

543 # Configure the detection Task 

544 detectionTask = self._setup_detection() 

545 excludeMaskPlanes = detectionTask.config.detection.excludeMaskPlanes 

546 nBad = len(excludeMaskPlanes) 

547 self.assertGreater(nBad, 0) 

548 kwargs["seed"] = transientSeed 

549 kwargs["nSrc"] = nBad 

550 kwargs["fluxLevel"] = 1000 

551 

552 # Run detection and check the results 

553 def _detection_wrapper(setFlags=True): 

554 transients, transientSources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=8, **kwargs) 

555 difference = science.clone() 

556 difference.maskedImage -= matchedTemplate.maskedImage 

557 difference.maskedImage += transients.maskedImage 

558 if setFlags: 

559 for src, badMask in zip(transientSources, excludeMaskPlanes): 

560 srcX = int(src.getX()) 

561 srcY = int(src.getY()) 

562 srcBbox = lsst.geom.Box2I(lsst.geom.Point2I(srcX - radius, srcY - radius), 

563 lsst.geom.Extent2I(2*radius + 1, 2*radius + 1)) 

564 difference[srcBbox].mask.array |= lsst.afw.image.Mask.getPlaneBitMask(badMask) 

565 if setFlags: 

566 with self.assertRaises(AlgorithmError): 

567 output = detectionTask.run(science, matchedTemplate, difference, sources) 

568 return 

569 else: 

570 output = detectionTask.run(science, matchedTemplate, difference, sources) 

571 refIds = [] 

572 goodSrcFlags = checkMask(difference.mask, transientSources, excludeMaskPlanes) 

573 self.assertEqual(np.sum(~goodSrcFlags), 0) 

574 for diaSource, goodSrcFlag in zip(output.diaSources, goodSrcFlags): 

575 if ~goodSrcFlag: 

576 with self.assertRaises(AssertionError): 

577 self._check_diaSource(transientSources, diaSource, refIds=refIds) 

578 else: 

579 self._check_diaSource(transientSources, diaSource, refIds=refIds) 

580 _detection_wrapper(setFlags=False) 

581 _detection_wrapper(setFlags=True) 

582 

583 def test_fake_mask_plane_propagation(self): 

584 """Test that we have the mask planes related to fakes in diffim images. 

585 This is testing method called updateMasks 

586 """ 

587 xSize = 256 

588 ySize = 256 

589 science, sources = makeTestImage(psfSize=2.4, xSize=xSize, ySize=ySize, doApplyCalibration=True) 

590 science_fake_img, science_fake_sources = makeTestImage( 

591 psfSize=2.4, xSize=xSize, ySize=ySize, seed=5, nSrc=3, noiseLevel=0.25, fluxRange=1 

592 ) 

593 template, _ = makeTestImage(psfSize=2.4, xSize=xSize, ySize=ySize, doApplyCalibration=True) 

594 tmplt_fake_img, tmplt_fake_sources = makeTestImage( 

595 psfSize=2.4, xSize=xSize, ySize=ySize, seed=9, nSrc=3, noiseLevel=0.25, fluxRange=1 

596 ) 

597 # created fakes and added them to the images 

598 science.image += science_fake_img.image 

599 template.image += tmplt_fake_img.image 

600 

601 # TODO: DM-40796 update to INJECTED names when source injection gets refactored 

602 # adding mask planes to both science and template images 

603 science.mask.addMaskPlane("FAKE") 

604 science_fake_bitmask = science.mask.getPlaneBitMask("FAKE") 

605 template.mask.addMaskPlane("FAKE") 

606 template_fake_bitmask = template.mask.getPlaneBitMask("FAKE") 

607 

608 # makeTestImage sets the DETECTED plane on the sources; we can use 

609 # that to set the FAKE plane on the science and template images. 

610 detected = science_fake_img.mask.getPlaneBitMask("DETECTED") 

611 fake_pixels = (science_fake_img.mask.array & detected).nonzero() 

612 science.mask.array[fake_pixels] |= science_fake_bitmask 

613 detected = tmplt_fake_img.mask.getPlaneBitMask("DETECTED") 

614 fake_pixels = (tmplt_fake_img.mask.array & detected).nonzero() 

615 template.mask.array[fake_pixels] |= science_fake_bitmask 

616 

617 science_fake_masked = (science.mask.array & science_fake_bitmask) > 0 

618 template_fake_masked = (template.mask.array & template_fake_bitmask) > 0 

619 

620 subtractConfig = subtractImages.AlardLuptonSubtractTask.ConfigClass() 

621 subtractConfig.sourceSelector.signalToNoise.fluxField = "truth_instFlux" 

622 subtractConfig.sourceSelector.signalToNoise.errField = "truth_instFluxErr" 

623 subtractTask = subtractImages.AlardLuptonSubtractTask(config=subtractConfig) 

624 subtraction = subtractTask.run(template, science, sources) 

625 

626 # check subtraction mask plane is set where we set the previous masks 

627 diff_mask = subtraction.difference.mask 

628 

629 # science mask should be now in INJECTED 

630 inj_masked = (diff_mask.array & diff_mask.getPlaneBitMask("INJECTED")) > 0 

631 

632 # template mask should be now in INJECTED_TEMPLATE 

633 injTmplt_masked = (diff_mask.array & diff_mask.getPlaneBitMask("INJECTED_TEMPLATE")) > 0 

634 

635 self.assertFloatsEqual(inj_masked.astype(int), science_fake_masked.astype(int)) 

636 # The template is convolved, so the INJECTED_TEMPLATE mask plane may 

637 # include more pixels than the FAKE mask plane 

638 injTmplt_masked &= template_fake_masked 

639 self.assertFloatsEqual(injTmplt_masked.astype(int), template_fake_masked.astype(int)) 

640 

641 # Now check that detection of fakes have the correct flag for injections 

642 detectionTask = self._setup_detection() 

643 

644 output = detectionTask.run(subtraction.matchedScience, 

645 subtraction.matchedTemplate, 

646 subtraction.difference, 

647 subtraction.kernelSources) 

648 diaSources = output.diaSources[~output.diaSources["sky_source"]].copy(deep=True) 

649 

650 sci_refIds = [] 

651 tmpl_refIds = [] 

652 for diaSrc in diaSources: 

653 if diaSrc['base_PsfFlux_instFlux'] > 0: 

654 self._check_diaSource(science_fake_sources, diaSrc, scale=1, refIds=sci_refIds) 

655 self.assertTrue(diaSrc['base_PixelFlags_flag_injected']) 

656 self.assertTrue(diaSrc['base_PixelFlags_flag_injectedCenter']) 

657 self.assertFalse(diaSrc['base_PixelFlags_flag_injected_template']) 

658 self.assertFalse(diaSrc['base_PixelFlags_flag_injected_templateCenter']) 

659 else: 

660 self._check_diaSource(tmplt_fake_sources, diaSrc, scale=-1, refIds=tmpl_refIds) 

661 self.assertTrue(diaSrc['base_PixelFlags_flag_injected_template']) 

662 self.assertTrue(diaSrc['base_PixelFlags_flag_injected_templateCenter']) 

663 self.assertFalse(diaSrc['base_PixelFlags_flag_injected']) 

664 self.assertFalse(diaSrc['base_PixelFlags_flag_injectedCenter']) 

665 

666 def test_mask_streaks(self): 

667 """Run detection on a difference image containing a streak. 

668 """ 

669 # Set up the simulated images 

670 noiseLevel = 1. 

671 staticSeed = 1 

672 fluxLevel = 500 

673 xSize = 400 

674 ySize = 400 

675 kwargs = {"seed": staticSeed, "psfSize": 2.4, "fluxLevel": fluxLevel, "xSize": xSize, "ySize": ySize} 

676 science, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6, **kwargs) 

677 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=7, **kwargs) 

678 

679 # Configure the detection Task 

680 detectionTask = self._setup_detection(doMerge=False, doMaskStreaks=True, 

681 raiseOnNoDiaSources=False, raiseOnBadSubtractionRatio=False) 

682 

683 # Test that no streaks are detected 

684 difference = science.clone() 

685 difference.maskedImage -= matchedTemplate.maskedImage 

686 output = detectionTask.run(science, matchedTemplate, difference, sources) 

687 outMask = output.subtractedMeasuredExposure.mask.array 

688 streakMask = output.subtractedMeasuredExposure.mask.getPlaneBitMask("STREAK") 

689 streakMaskSet = (outMask & streakMask) > 0 

690 self.assertTrue(np.all(streakMaskSet == 0)) 

691 

692 # Add streak-like shape and check that streak is detected 

693 difference.image.array[20:23, 40:200] += 50 

694 output = detectionTask.run(science, matchedTemplate, difference, sources) 

695 outMask = output.subtractedMeasuredExposure.mask.array 

696 streakMask = output.subtractedMeasuredExposure.mask.getPlaneBitMask("STREAK") 

697 streakMaskSet = (outMask & streakMask) > 0 

698 self.assertTrue(np.all(streakMaskSet[20:23, 40:200])) 

699 

700 # Add a more trapezoid shaped streak across an image that is 

701 # fainter and check that it is also detected 

702 bbox = science.getBBox() 

703 difference = science.clone() 

704 difference.maskedImage -= matchedTemplate.maskedImage 

705 width = 100 

706 amplitude = 5 

707 x0 = -100 + bbox.getBeginX() 

708 y0 = -100 + bbox.getBeginY() 

709 x1 = xSize + x0 + 100 

710 y1 = ySize/2 

711 corner_coords = [lsst.geom.Point2D(x0, y0), 

712 lsst.geom.Point2D(x0, y0 + width), 

713 lsst.geom.Point2D(x1, y1), 

714 lsst.geom.Point2D(x1 + width, y1)] 

715 streak_trapezoid = afwGeom.Polygon(corner_coords) 

716 streak_image = streak_trapezoid.createImage(bbox) 

717 streak_image *= amplitude 

718 difference.image.array += streak_image.array 

719 output = detectionTask.run(science, matchedTemplate, difference, sources) 

720 outMask = output.subtractedMeasuredExposure.mask.array 

721 streakMask = output.subtractedMeasuredExposure.mask.getPlaneBitMask("STREAK") 

722 streakMaskSet = (outMask & streakMask) > 0 

723 # Check that pixel values in streak_image equal the streak amplitude 

724 streak_check = np.where(streak_image.array == amplitude) 

725 self.assertTrue(np.all(streakMaskSet[streak_check])) 

726 # Check that the entire image was not masked STREAK 

727 self.assertFalse(np.all(streakMaskSet)) 

728 

729 def _setup_sattle_tests(self): 

730 noiseLevel = 1. 

731 staticSeed = 1 

732 fluxLevel = 500 

733 shared_kwargs = {"seed": staticSeed, "psfSize": 2.4, "fluxLevel": fluxLevel, 

734 "x0": 12345, "y0": 67890} 

735 science, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6, 

736 **shared_kwargs) 

737 science.getInfo().setVisitInfo(makeVisitInfo(id=2)) 

738 detector = DetectorWrapper(numAmps=1).detector 

739 science.setDetector(detector) 

740 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel / 4, 

741 noiseSeed=7, **shared_kwargs) 

742 difference = science.clone() 

743 

744 detectionTask = self._setup_detection(doDeblend=True, 

745 badSubtractionRatioThreshold=1., 

746 doSkySources=False, run_sattle=True) 

747 

748 return science, matchedTemplate, difference, sources, detectionTask 

749 

750 @mock.patch.dict(os.environ, {"SATTLE_URI_BASE": "fake_host:1234"}) 

751 def test_sattle_not_available(self): 

752 science, matchedTemplate, difference, sources, detectionTask = self._setup_sattle_tests() 

753 

754 response = MockResponse({"allow_list": []}, 500, "sattle internal error") 

755 with mock.patch('requests.put', return_value=response): 

756 with self.assertRaises(requests.exceptions.HTTPError): 

757 detectionTask.run(science, matchedTemplate, difference, sources, 

758 idFactory=IdFactory.makeSimple()) 

759 

760 @mock.patch.dict(os.environ, {"SATTLE_URI_BASE": "fake_host:1234"}) 

761 def test_visit_id_not_in_sattle(self): 

762 science, matchedTemplate, difference, sources, detectionTask = self._setup_sattle_tests() 

763 

764 response = MockResponse({"allow_list": []}, 404, "missing visit cache") 

765 # visit id not in sattle raises 

766 with self.assertRaises(requests.exceptions.HTTPError): 

767 with mock.patch('lsst.ip.diffim.detectAndMeasure.requests.put', 

768 return_value=response): 

769 with mock.patch('lsst.ip.diffim.utils.populate_sattle_visit_cache'): 

770 detectionTask.run(science, matchedTemplate, difference, sources, 

771 idFactory=IdFactory.makeSimple()) 

772 

773 @mock.patch.dict(os.environ, {"SATTLE_URI_BASE": "fake_host:1234"}) 

774 def test_filter_satellites_some_allowed(self): 

775 science, matchedTemplate, difference, sources, detectionTask = self._setup_sattle_tests() 

776 

777 allowed_ids = [1, 5] 

778 response = MockResponse({"allow_list": allowed_ids}, 200, "some allowed") 

779 with mock.patch('requests.put', return_value=response): 

780 output = detectionTask.run(science, matchedTemplate, difference, sources, 

781 idFactory=IdFactory.makeSimple()) 

782 

783 self.assertEqual(len(output.diaSources), 2) 

784 

785 # Output should be sources 1 and 5 allowed out of 20 

786 self.assertEqual(set(output.diaSources['id']), set(allowed_ids)) 

787 

788 @mock.patch.dict(os.environ, {"SATTLE_URI_BASE": "fake_host:1234"}) 

789 def test_filter_satellites_all_allowed(self): 

790 science, matchedTemplate, difference, sources, detectionTask = self._setup_sattle_tests() 

791 

792 allowed_ids = list(range(1, 21)) 

793 response = MockResponse({"allow_list": allowed_ids}, 200, "all allowed") 

794 # Run detection and check the results 

795 with mock.patch('requests.put', return_value=response): 

796 output = detectionTask.run(science, matchedTemplate, difference, sources, 

797 idFactory=IdFactory.makeSimple()) 

798 

799 # Output should be all sources that went in. 20 go in, 20 should come out 

800 self.assertEqual(len(output.diaSources), 20) 

801 

802 self.assertEqual(set(output.diaSources['id']), set(allowed_ids)) 

803 

804 @mock.patch.dict(os.environ, {"SATTLE_URI_BASE": "fake_host:1234"}) 

805 def test_filter_satellites_none_allowed(self): 

806 science, matchedTemplate, difference, sources, detectionTask = self._setup_sattle_tests() 

807 

808 response = MockResponse({"allow_list": []}, 200, "none allowed") 

809 # Run detection and confirm it raises for no diasources 

810 with self.assertRaises(detectAndMeasure.NoDiaSourcesError): 

811 with mock.patch('requests.put', return_value=response): 

812 detectionTask.run(science, matchedTemplate, difference, sources, 

813 idFactory=IdFactory.makeSimple()) 

814 

815 @mock.patch.dict(os.environ, {"SATTLE_URI_BASE": ""}) 

816 def test_fail_on_sattle_misconfiguration(self): 

817 with self.assertRaises(pexConfig.FieldValidationError): 

818 self._setup_detection(run_sattle=True) 

819 

820 def test_trailed_glints(self): 

821 """Test that the glint_trail column works, and that 

822 the trailed_glints output contains the expected information. 

823 """ 

824 noiseLevel = 1. 

825 staticSeed = 1 

826 diffim, diaSources = makeTestImage(seed=staticSeed, noiseLevel=noiseLevel, noiseSeed=6) 

827 self._check_values(diaSources['glint_trail']) 

828 

829 # Run detection and return the output Struct so we can check it 

830 def _detection_wrapper(diffim, diaSources): 

831 detectionTask = self._setup_detection() 

832 scienceBase, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6) 

833 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=7) 

834 science = scienceBase.clone() 

835 science.maskedImage -= diffim.maskedImage 

836 difference = science.clone() 

837 difference.maskedImage -= matchedTemplate.maskedImage 

838 output = detectionTask.run(science, matchedTemplate, difference, sources) 

839 return output 

840 

841 output = _detection_wrapper(diffim, diaSources) 

842 self.assertTrue('slopes' in output.glintTrailInfo) 

843 self.assertTrue('intercepts' in output.glintTrailInfo) 

844 self.assertTrue('stderrs' in output.glintTrailInfo) 

845 self.assertTrue('lengths' in output.glintTrailInfo) 

846 self.assertTrue('angles' in output.glintTrailInfo) 

847 

848 

849class DetectAndMeasureScoreTest(DetectAndMeasureTestBase, lsst.utils.tests.TestCase): 

850 detectionTask = detectAndMeasure.DetectAndMeasureScoreTask 

851 

852 def test_detection_xy0(self): 

853 """Basic functionality test with non-zero x0 and y0. 

854 """ 

855 # Set up the simulated images 

856 noiseLevel = 1. 

857 staticSeed = 1 

858 fluxLevel = 500 

859 kwargs = {"seed": staticSeed, "psfSize": 2.4, "fluxLevel": fluxLevel, "x0": 12345, "y0": 67890} 

860 science, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6, **kwargs) 

861 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=7, **kwargs) 

862 difference = science.clone() 

863 subtractTask = subtractImages.AlardLuptonPreconvolveSubtractTask() 

864 scienceKernel = science.psf.getKernel() 

865 score = subtractTask._convolveExposure(difference, scienceKernel, subtractTask.convolutionControl) 

866 

867 # Configure the detection Task 

868 # Set the subtraction residual metric threshold high, since the template 

869 # is not actually subtracted from the science image. 

870 detectionTask = self._setup_detection(doDeblend=True, badSubtractionRatioThreshold=1., 

871 doSkySources=False) 

872 

873 # Run detection and check the results 

874 output = detectionTask.run(science, matchedTemplate, difference, score, sources, 

875 idFactory=self.idGenerator.make_table_id_factory()) 

876 

877 # Catalog ids should be very large from this id generator. 

878 self.assertTrue(all(output.diaSources['id'] > 1000000000)) 

879 subtractedMeasuredExposure = output.subtractedMeasuredExposure 

880 

881 self.assertImagesEqual(subtractedMeasuredExposure.image, difference.image) 

882 

883 # Not all of the sources will be detected: preconvolution results in 

884 # a larger edge mask, so we miss an edge source. 

885 self.assertEqual(len(output.diaSources), len(sources)-1) 

886 # no sources should be flagged as negative 

887 self.assertEqual(len(~output.diaSources["is_negative"]), len(output.diaSources)) 

888 # TODO DM-41496: restore this block once we handle detections on edge 

889 # pixels better; at least one of these sources currently has a bad 

890 # centroid because most of the source is rejected as EDGE. 

891 # refIds = [] 

892 # for source in sources: 

893 # self._check_diaSource(output.diaSources, source, refIds=refIds) 

894 

895 def test_measurements_finite(self): 

896 """Measured fluxes and centroids should always be finite. 

897 """ 

898 columnNames = ["coord_ra", "coord_dec", "ip_diffim_forced_PsfFlux_instFlux"] 

899 

900 # Set up the simulated images 

901 noiseLevel = 1. 

902 staticSeed = 1 

903 transientSeed = 6 

904 xSize = 256 

905 ySize = 256 

906 kwargs = {"psfSize": 2.4, "x0": 0, "y0": 0, 

907 "xSize": xSize, "ySize": ySize} 

908 science, sources = makeTestImage(seed=staticSeed, noiseLevel=noiseLevel, noiseSeed=6, 

909 nSrc=1, **kwargs) 

910 matchedTemplate, _ = makeTestImage(seed=staticSeed, noiseLevel=noiseLevel/4, noiseSeed=7, 

911 nSrc=1, **kwargs) 

912 rng = np.random.RandomState(3) 

913 xLoc = np.arange(-5, xSize+5, 10) 

914 rng.shuffle(xLoc) 

915 yLoc = np.arange(-5, ySize+5, 10) 

916 rng.shuffle(yLoc) 

917 transients, transientSources = makeTestImage(seed=transientSeed, 

918 nSrc=len(xLoc), fluxLevel=1000., 

919 noiseLevel=noiseLevel, noiseSeed=8, 

920 xLoc=xLoc, yLoc=yLoc, 

921 **kwargs) 

922 difference = science.clone() 

923 difference.maskedImage -= matchedTemplate.maskedImage 

924 difference.maskedImage += transients.maskedImage 

925 subtractTask = subtractImages.AlardLuptonPreconvolveSubtractTask() 

926 scienceKernel = science.psf.getKernel() 

927 score = subtractTask._convolveExposure(difference, scienceKernel, subtractTask.convolutionControl) 

928 

929 # Configure the detection Task 

930 detectionTask = self._setup_detection(doForcedMeasurement=True) 

931 

932 # Run detection and check the results 

933 output = detectionTask.run(science, matchedTemplate, difference, score, sources) 

934 

935 for column in columnNames: 

936 self._check_values(output.diaSources[column]) 

937 self._check_values(output.diaSources.getX(), minValue=0, maxValue=xSize) 

938 self._check_values(output.diaSources.getY(), minValue=0, maxValue=ySize) 

939 self._check_values(output.diaSources.getPsfInstFlux()) 

940 

941 def test_detect_transients(self): 

942 """Run detection on a difference image containing transients. 

943 """ 

944 # Set up the simulated images 

945 noiseLevel = 1. 

946 staticSeed = 1 

947 transientSeed = 6 

948 fluxLevel = 500 

949 kwargs = {"seed": staticSeed, "psfSize": 2.4, "fluxLevel": fluxLevel} 

950 scienceBase, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6, **kwargs) 

951 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=7, **kwargs) 

952 scienceKernel = scienceBase.psf.getKernel() 

953 subtractTask = subtractImages.AlardLuptonPreconvolveSubtractTask() 

954 

955 # Configure the detection Task 

956 detectionTask = self._setup_detection(doMerge=False) 

957 kwargs["seed"] = transientSeed 

958 kwargs["nSrc"] = 10 

959 kwargs["fluxLevel"] = 1000 

960 

961 # Run detection and check the results 

962 def _detection_wrapper(positive=True): 

963 """Simulate positive or negative transients and run detection. 

964 

965 Parameters 

966 ---------- 

967 positive : `bool`, optional 

968 If set, use positive transient sources. 

969 """ 

970 

971 transients, transientSources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=8, **kwargs) 

972 science = scienceBase.clone() 

973 if positive: 

974 science.maskedImage += transients.maskedImage 

975 else: 

976 science.maskedImage -= transients.maskedImage 

977 difference = science.clone() 

978 difference.maskedImage -= matchedTemplate.maskedImage 

979 score = subtractTask._convolveExposure(difference, scienceKernel, subtractTask.convolutionControl) 

980 # NOTE: NoiseReplacer (run by forcedMeasurement) can modify the 

981 # science image if we've e.g. removed parents post-deblending. 

982 # Pass a clone of the science image, so that it doesn't disrupt 

983 # later tests. 

984 output = detectionTask.run(science, matchedTemplate, difference, score, sources) 

985 refIds = [] 

986 scale = 1. if positive else -1. 

987 # sources near the edge may have untrustworthy centroids 

988 goodSrcFlags = ~output.diaSources['base_PixelFlags_flag_edge'] 

989 for diaSource, goodSrcFlag in zip(output.diaSources, goodSrcFlags): 

990 if goodSrcFlag: 

991 self._check_diaSource(transientSources, diaSource, refIds=refIds, scale=scale) 

992 _detection_wrapper(positive=True) 

993 _detection_wrapper(positive=False) 

994 

995 def test_detect_dipoles(self): 

996 """Run detection on a difference image containing dipoles. 

997 """ 

998 # Set up the simulated images 

999 noiseLevel = 1. 

1000 staticSeed = 1 

1001 fluxLevel = 1000 

1002 fluxRange = 1.5 

1003 nSources = 10 

1004 offset = 1 

1005 xSize = 300 

1006 ySize = 300 

1007 kernelSize = 32 

1008 # Avoid placing sources near the edge for this test, so that we can 

1009 # easily check that the correct number of sources are detected. 

1010 templateBorderSize = kernelSize//2 

1011 dipoleFlag = "ip_diffim_DipoleFit_classification" 

1012 kwargs = {"seed": staticSeed, "psfSize": 2.4, "fluxLevel": fluxLevel, "fluxRange": fluxRange, 

1013 "nSrc": nSources, "templateBorderSize": templateBorderSize, "kernelSize": kernelSize, 

1014 "xSize": xSize, "ySize": ySize} 

1015 science, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6, **kwargs) 

1016 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=7, **kwargs) 

1017 difference = science.clone() 

1018 # Shift the template by a pixel in order to make dipoles in the difference image. 

1019 matchedTemplate.image.array[...] = np.roll(matchedTemplate.image.array[...], offset, axis=0) 

1020 matchedTemplate.variance.array[...] = np.roll(matchedTemplate.variance.array[...], offset, axis=0) 

1021 matchedTemplate.mask.array[...] = np.roll(matchedTemplate.mask.array[...], offset, axis=0) 

1022 difference.maskedImage -= matchedTemplate.maskedImage[science.getBBox()] 

1023 subtractTask = subtractImages.AlardLuptonPreconvolveSubtractTask() 

1024 scienceKernel = science.psf.getKernel() 

1025 score = subtractTask._convolveExposure(difference, scienceKernel, subtractTask.convolutionControl) 

1026 

1027 detectionTask = self._setup_detection(badSubtractionRatioThreshold=0.3) 

1028 output = detectionTask.run(science, matchedTemplate, difference, score, sources) 

1029 diaSources = output.diaSources[~output.diaSources["sky_source"]].copy(deep=True) 

1030 self.assertEqual(len(diaSources), len(sources)) 

1031 refIds = [] 

1032 for diaSource in diaSources: 

1033 if diaSource[dipoleFlag]: 

1034 self._check_diaSource(sources, diaSource, refIds=refIds, scale=0, 

1035 rtol=0.05, atol=None, usePsfFlux=False) 

1036 self.assertFloatsAlmostEqual(diaSource["ip_diffim_DipoleFit_orientation"], 

1037 -np.pi / 2, atol=2.) 

1038 self.assertFloatsAlmostEqual(diaSource["ip_diffim_DipoleFit_separation"], offset, rtol=0.1) 

1039 else: 

1040 raise ValueError("DiaSource with ID %s is not a dipole!", diaSource.getId()) 

1041 

1042 def test_sky_sources(self): 

1043 """Add sky sources and check that they are sufficiently far from other 

1044 sources and have negligible flux. 

1045 """ 

1046 # Set up the simulated images 

1047 noiseLevel = 1. 

1048 staticSeed = 1 

1049 transientSeed = 6 

1050 transientFluxLevel = 1000. 

1051 transientFluxRange = 1.5 

1052 fluxLevel = 500 

1053 kwargs = {"seed": staticSeed, "psfSize": 2.4, "fluxLevel": fluxLevel} 

1054 science, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6, **kwargs) 

1055 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=7, **kwargs) 

1056 transients, transientSources = makeTestImage(seed=transientSeed, psfSize=2.4, 

1057 nSrc=10, fluxLevel=transientFluxLevel, 

1058 fluxRange=transientFluxRange, 

1059 noiseLevel=noiseLevel, noiseSeed=8) 

1060 difference = science.clone() 

1061 difference.maskedImage -= matchedTemplate.maskedImage 

1062 difference.maskedImage += transients.maskedImage 

1063 subtractTask = subtractImages.AlardLuptonPreconvolveSubtractTask() 

1064 scienceKernel = science.psf.getKernel() 

1065 kernelWidth = np.max(scienceKernel.getDimensions())//2 

1066 score = subtractTask._convolveExposure(difference, scienceKernel, subtractTask.convolutionControl) 

1067 

1068 # Configure the detection Task 

1069 detectionTask = self._setup_detection(doSkySources=True) 

1070 

1071 # Run detection and check the results 

1072 output = detectionTask.run(science, matchedTemplate, difference, score, sources, 

1073 idFactory=self.idGenerator.make_table_id_factory()) 

1074 nSkySourcesGenerated = detectionTask.metadata["n_skySources"] 

1075 skySources = output.diaSources[output.diaSources["sky_source"]] 

1076 self.assertEqual(len(skySources), nSkySourcesGenerated) 

1077 for skySource in skySources: 

1078 # Disable the sky_source flag to enable checks. 

1079 skySource["sky_source"] = False 

1080 # The sky sources should not be close to any other source 

1081 with self.assertRaises(AssertionError): 

1082 self._check_diaSource(transientSources, skySource, matchDistance=kernelWidth) 

1083 with self.assertRaises(AssertionError): 

1084 self._check_diaSource(sources, skySource, matchDistance=kernelWidth) 

1085 # The sky sources should have low flux levels. 

1086 self._check_diaSource(transientSources, skySource, matchDistance=1000, scale=0., 

1087 atol=np.sqrt(transientFluxRange*transientFluxLevel)) 

1088 

1089 # Catalog ids should be very large from this id generator. 

1090 self.assertTrue(all(output.diaSources['id'] > 1000000000)) 

1091 

1092 def test_exclude_mask_detections(self): 

1093 """Sources with certain bad mask planes set should not be detected. 

1094 """ 

1095 # Set up the simulated images 

1096 noiseLevel = 1. 

1097 staticSeed = 1 

1098 transientSeed = 6 

1099 fluxLevel = 500 

1100 radius = 2 

1101 kwargs = {"seed": staticSeed, "psfSize": 2.4, "fluxLevel": fluxLevel} 

1102 science, sources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=6, **kwargs) 

1103 science.getInfo().setVisitInfo(makeVisitInfo()) 

1104 matchedTemplate, _ = makeTestImage(noiseLevel=noiseLevel/4, noiseSeed=7, **kwargs) 

1105 

1106 subtractTask = subtractImages.AlardLuptonPreconvolveSubtractTask() 

1107 scienceKernel = science.psf.getKernel() 

1108 # Configure the detection Task 

1109 detectionTask = self._setup_detection() 

1110 excludeMaskPlanes = detectionTask.config.detection.excludeMaskPlanes 

1111 nBad = len(excludeMaskPlanes) 

1112 self.assertGreater(nBad, 0) 

1113 kwargs["seed"] = transientSeed 

1114 kwargs["nSrc"] = nBad 

1115 kwargs["fluxLevel"] = 1000 

1116 

1117 # Run detection and check the results 

1118 def _detection_wrapper(setFlags=True): 

1119 transients, transientSources = makeTestImage(noiseLevel=noiseLevel, noiseSeed=8, **kwargs) 

1120 difference = science.clone() 

1121 difference.maskedImage -= matchedTemplate.maskedImage 

1122 difference.maskedImage += transients.maskedImage 

1123 if setFlags: 

1124 for src, badMask in zip(transientSources, excludeMaskPlanes): 

1125 srcX = int(src.getX()) 

1126 srcY = int(src.getY()) 

1127 srcBbox = lsst.geom.Box2I(lsst.geom.Point2I(srcX - radius, srcY - radius), 

1128 lsst.geom.Extent2I(2*radius + 1, 2*radius + 1)) 

1129 difference[srcBbox].mask.array |= lsst.afw.image.Mask.getPlaneBitMask(badMask) 

1130 score = subtractTask._convolveExposure(difference, scienceKernel, subtractTask.convolutionControl) 

1131 if setFlags: 

1132 with self.assertRaises(AlgorithmError): 

1133 output = detectionTask.run(science, matchedTemplate, difference, score, sources) 

1134 return 

1135 else: 

1136 output = detectionTask.run(science, matchedTemplate, difference, score, sources) 

1137 refIds = [] 

1138 goodSrcFlags = checkMask(difference.mask, transientSources, excludeMaskPlanes) 

1139 self.assertEqual(np.sum(~goodSrcFlags), 0) 

1140 for diaSource, goodSrcFlag in zip(output.diaSources, goodSrcFlags): 

1141 if ~goodSrcFlag: 

1142 with self.assertRaises(AssertionError): 

1143 self._check_diaSource(transientSources, diaSource, refIds=refIds) 

1144 else: 

1145 self._check_diaSource(transientSources, diaSource, refIds=refIds) 

1146 _detection_wrapper(setFlags=False) 

1147 _detection_wrapper(setFlags=True) 

1148 

1149 

1150class TestNegativePeaks(lsst.utils.tests.TestCase): 

1151 """Tests of deblending and merging negative peaks, to test fixes for the 

1152 various problems found on DM-48596. 

1153 """ 

1154 

1155 def testDeblendNegatives(self): 

1156 """Test that negative peaks get deblended and not destroyed: DM-48704. 

1157 This is only a test of deblending, not of merging. 

1158 """ 

1159 # Make a science image with one blend of two positive sources, to 

1160 # subtract from an empty template, resulting in a negative diffim. 

1161 bbox = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(100, 100)) 

1162 dataset = lsst.meas.base.tests.TestDataset(bbox) 

1163 delta = 10 

1164 with dataset.addBlend() as family: 

1165 family.addChild(instFlux=2E5, centroid=lsst.geom.Point2D(50, 72)) 

1166 family.addChild(instFlux=2.5E5, centroid=lsst.geom.Point2D(50+delta, 74)) 

1167 science, catalog = dataset.realize(noise=1.0, 

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

1169 dataset = lsst.meas.base.tests.TestDataset(bbox) 

1170 template, _ = dataset.realize(noise=1.0, 

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

1172 difference = template.clone() 

1173 difference.image -= science.image 

1174 

1175 config = detectAndMeasure.DetectAndMeasureTask.ConfigClass() 

1176 config.doDeblend = True 

1177 task = detectAndMeasure.DetectAndMeasureTask(config=config) 

1178 # prelude steps taken from `detectAndMeasure.run` 

1179 task._prepareInputs(difference) 

1180 table = lsst.afw.table.SourceTable.make(task.schema) 

1181 results = task.detection.run(table=table, exposure=difference, doSmooth=True) 

1182 # Just run the deblend step so we can check the footprints independently. 

1183 sources, positives, negatives = task._deblend(difference, results.positive, results.negative) 

1184 

1185 # DM-48704 fixed a problem where the peaks were in the footprints, but 

1186 # the spans were empty. 

1187 self.assertEqual(len(negatives), 2) 

1188 self.assertEqual(len(positives), 0) 

1189 self.assertGreater(negatives[0].getFootprint().getSpans().getArea(), 0) 

1190 self.assertGreater(negatives[1].getFootprint().getSpans().getArea(), 0) 

1191 # Deblended children are HeavyFootprints; we have to make sure the 

1192 # pixel values in those are correct (though DetectAndMeasureTask 

1193 # doesn't use the fact that they're Heavy). 

1194 # The sources are positive in the science image, and negative in the 

1195 # diffim, so the minimum value in the deblended negative footprint is 

1196 # the maximum value in the science catalog footprint (ignoring the 

1197 # noise in the science and template, hence rtol). 

1198 # (catalog[0] is the parent; we want the children) 

1199 self.assertFloatsAlmostEqual(negatives[0].getFootprint().getImageArray().min(), 

1200 -catalog[1].getFootprint().getImageArray().max(), rtol=1e-4) 

1201 self.assertFloatsAlmostEqual(negatives[1].getFootprint().getImageArray().min(), 

1202 -catalog[2].getFootprint().getImageArray().max(), rtol=1e-4) 

1203 

1204 self.assertEqual(sources["is_negative"].sum(), 2) 

1205 

1206 def testMergeFootprints(self): 

1207 """Test that merging footprints does not cause negative ones to 

1208 disappear (e.g. get merged into non-connected footprints). 

1209 

1210 As implemented, the diffim will have three positive sources (one a 

1211 blended pair), and 7 negative sources (two a blended pair). 

1212 """ 

1213 # Make a template image with multiple blends, designed to trigger the 

1214 # negative-footprint-related bug in `FootprintSet.merge`. 

1215 bbox = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(400, 200)) 

1216 dataset = lsst.meas.base.tests.TestDataset(bbox) 

1217 # Because these sources are on the template, they will be negative on 

1218 # the diffim, unless the pixels are explicitly made negative via 

1219 # `template.image.subset` below. 

1220 # positive isolated source on diffim 

1221 dataset.addSource(instFlux=.5E5, centroid=lsst.geom.Point2D(25, 26)) 

1222 # negative isolated source on diffim 

1223 dataset.addSource(instFlux=.7E5, centroid=lsst.geom.Point2D(75, 24), 

1224 shape=lsst.afw.geom.Quadrupole(12, 7, 2)) 

1225 delta = 10 

1226 # negative blended pair on diffim 

1227 with dataset.addBlend() as family: 

1228 family.addChild(instFlux=1E5, centroid=lsst.geom.Point2D(150, 72)) 

1229 family.addChild(instFlux=1.5E5, centroid=lsst.geom.Point2D(150+delta, 74)) 

1230 # positive blended pair on diffim 

1231 with dataset.addBlend() as family: 

1232 family.addChild(instFlux=2E5, centroid=lsst.geom.Point2D(250, 72)) 

1233 family.addChild(instFlux=2.5E5, centroid=lsst.geom.Point2D(250+delta, 74)) 

1234 # negative blended pair on diffim 

1235 with dataset.addBlend() as family: 

1236 family.addChild(instFlux=3E5, centroid=lsst.geom.Point2D(350, 72)) 

1237 family.addChild(instFlux=3.5E5, centroid=lsst.geom.Point2D(350+delta, 74)) 

1238 # negative isolated source on diffim 

1239 dataset.addSource(instFlux=4E5, centroid=lsst.geom.Point2D(75, 124)) 

1240 # negative isolated source on diffim 

1241 dataset.addSource(instFlux=5E5, centroid=lsst.geom.Point2D(175, 124)) 

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

1243 schema.addField("sky_source", "Flag", "Sky source.") 

1244 template, catalog = dataset.realize(noise=100.0, schema=schema) 

1245 # These will be positive sources on the diffim (as noted above). 

1246 template.image.subset(lsst.geom.Box2I(lsst.geom.Point2I(15, 15), 

1247 lsst.geom.Point2I(35, 35))).array *= -1 

1248 template.image.subset(lsst.geom.Box2I(lsst.geom.Point2I(230, 60), 

1249 lsst.geom.Point2I(270, 85))).array *= -1 

1250 dataset = lsst.meas.base.tests.TestDataset(bbox) 

1251 science, _ = dataset.realize(noise=100.0, schema=schema) 

1252 difference = science.clone() 

1253 difference.image -= template.image 

1254 

1255 config = detectAndMeasure.DetectAndMeasureTask.ConfigClass() 

1256 config.doDeblend = True 

1257 config.raiseOnBadSubtractionRatio = False 

1258 config.raiseOnNoDiaSources = False 

1259 task = detectAndMeasure.DetectAndMeasureTask(config=config) 

1260 result = task.run(science, template, difference, catalog) 

1261 

1262 # The original bug manifested as the (175,124) source disappaering in 

1263 # the merge step, and being included in the peaks of a duplicated 

1264 # (75,124) source, even though their footprints are not connected. 

1265 mask = np.isclose(result.diaSources["slot_Centroid_x"], 75) & \ 

1266 np.isclose(result.diaSources["slot_Centroid_y"], 124) 

1267 self.assertEqual(mask.sum(), 1) 

1268 peaks = result.diaSources[mask][0].getFootprint().peaks 

1269 self.assertEqual(len(peaks), 1) 

1270 self.assertEqual(peaks[0].getIx(), 75) 

1271 self.assertEqual(peaks[0].getIy(), 124) 

1272 

1273 mask = np.isclose(result.diaSources["slot_Centroid_x"], 175) & \ 

1274 np.isclose(result.diaSources["slot_Centroid_y"], 124) 

1275 self.assertEqual(mask.sum(), 1) 

1276 peaks = result.diaSources[mask][0].getFootprint().peaks 

1277 self.assertEqual(len(peaks), 1) 

1278 self.assertEqual(peaks[0].getIx(), 175) 

1279 self.assertEqual(peaks[0].getIy(), 124) 

1280 

1281 # This checks that all the returned footprints have exactly one peak; 

1282 # it's a more general test than the above, but I'm keeping that for 

1283 # the more explicit test of the original bugged sources. 

1284 peak_x = np.array([peak['f_x'] for src in result.diaSources for peak in src.getFootprint().peaks]) 

1285 peak_y = np.array([peak['f_y'] for src in result.diaSources for peak in src.getFootprint().peaks]) 

1286 peaks = np.column_stack((peak_x, peak_y)) 

1287 unique_peaks, counts = np.unique(peaks, axis=0, return_counts=True) 

1288 self.assertEqual(np.sum(counts > 1), 0) 

1289 

1290 # There are three positive sources that should not have `is_negative` 

1291 # set, independent of how deblending/merging of negative sources is 

1292 # handled. 

1293 self.assertEqual((~result.diaSources["is_negative"]).sum(), 3) 

1294 

1295 

1296def makeVisitInfo(id=1): 

1297 """Return a non-NaN visitInfo.""" 

1298 return afwImage.VisitInfo(id=id, 

1299 exposureTime=10.01, 

1300 darkTime=11.02, 

1301 date=dafBase.DateTime(65321.1, dafBase.DateTime.MJD, dafBase.DateTime.TAI), 

1302 ut1=12345.1, 

1303 era=45.1*geom.degrees, 

1304 boresightRaDec=geom.SpherePoint(23.1, 73.2, geom.degrees), 

1305 boresightAzAlt=geom.SpherePoint(134.5, 33.3, geom.degrees), 

1306 boresightAirmass=1.73, 

1307 boresightRotAngle=73.2*geom.degrees, 

1308 rotType=afwImage.RotType.SKY, 

1309 observatory=Observatory( 

1310 11.1*geom.degrees, 22.2*geom.degrees, 0.333), 

1311 weather=Weather(1.1, 2.2, 34.5), 

1312 ) 

1313 

1314 

1315class MockResponse: 

1316 """Provide a mock for requests.put calls""" 

1317 def __init__(self, json_data, status_code, text): 

1318 self.json_data = json_data 

1319 self.status_code = status_code 

1320 self.text = text 

1321 

1322 def json(self): 

1323 return self.json_data 

1324 

1325 def raise_for_status(self): 

1326 if self.status_code != 200: 

1327 raise requests.exceptions.HTTPError 

1328 

1329 

1330def setup_module(module): 

1331 lsst.utils.tests.init() 

1332 

1333 

1334class MemoryTestCase(lsst.utils.tests.MemoryTestCase): 

1335 pass 

1336 

1337 

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

1339 lsst.utils.tests.init() 

1340 unittest.main()