Coverage for tests/test_detectAndMeasure.py: 9%

797 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-05 09:10 +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 "ip_diffim_forced_template_PsfFlux_instFlux"] 

229 

230 # Set up the simulated images 

231 noiseLevel = 1. 

232 staticSeed = 1 

233 transientSeed = 6 

234 xSize = 256 

235 ySize = 256 

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

237 "xSize": xSize, "ySize": ySize} 

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

239 nSrc=1, **kwargs) 

240 science.getInfo().setVisitInfo(makeVisitInfo()) 

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

242 nSrc=1, **kwargs) 

243 rng = np.random.RandomState(3) 

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

245 rng.shuffle(xLoc) 

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

247 rng.shuffle(yLoc) 

248 transients, transientSources = makeTestImage(seed=transientSeed, 

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

250 noiseLevel=noiseLevel, noiseSeed=8, 

251 xLoc=xLoc, yLoc=yLoc, 

252 **kwargs) 

253 difference = science.clone() 

254 difference.maskedImage -= matchedTemplate.maskedImage 

255 difference.maskedImage += transients.maskedImage 

256 

257 # Configure the detection Task 

258 detectionTask = self._setup_detection(doForcedMeasurement=True) 

259 

260 # Run detection and check the results 

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

262 

263 for column in columnNames: 

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

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

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

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

268 

269 def test_raise_config_schema_mismatch(self): 

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

271 """ 

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

273 with self.assertRaises(InvalidQuantumError): 

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

275 

276 def test_remove_unphysical(self): 

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

278 """ 

279 # Set up the simulated images 

280 noiseLevel = 1. 

281 staticSeed = 1 

282 xSize = 256 

283 ySize = 256 

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

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

286 nSrc=1, **kwargs) 

287 science.getInfo().setVisitInfo(makeVisitInfo()) 

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

289 nSrc=1, **kwargs) 

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

291 science.maskedImage += transients.maskedImage 

292 difference = science.clone() 

293 bbox = difference.getBBox() 

294 difference.maskedImage -= matchedTemplate.maskedImage 

295 

296 # Configure the detection Task, and remove unphysical sources 

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

298 badSourceFlags=["base_PixelFlags_flag_offimage", ]) 

299 

300 # Run detection and check the results 

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

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

303 nBadDoRemove = np.count_nonzero(badDiaSrcDoRemove) 

304 # Verify that all sources are physical 

305 self.assertEqual(nBadDoRemove, 0) 

306 # Set a few centroids outside the image bounding box 

307 nSetBad = 5 

308 for src in diaSources[0: nSetBad]: 

309 src["slot_Centroid_x"] += xSize 

310 src["slot_Centroid_y"] += ySize 

311 src["base_PixelFlags_flag_offimage"] = True 

312 # Verify that these sources are outside the image 

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

314 nBad = np.count_nonzero(badDiaSrc) 

315 self.assertEqual(nBad, nSetBad) 

316 diaSourcesNoBad = detectionTask._removeBadSources(diaSources) 

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

318 

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

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

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

322 

323 def test_detect_transients(self): 

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

325 """ 

326 # Set up the simulated images 

327 noiseLevel = 1. 

328 staticSeed = 1 

329 transientSeed = 6 

330 fluxLevel = 500 

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

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

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

334 

335 # Configure the detection Task 

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

337 kwargs["seed"] = transientSeed 

338 kwargs["nSrc"] = 10 

339 kwargs["fluxLevel"] = 1000 

340 

341 # Run detection and check the results 

342 def _detection_wrapper(positive=True): 

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

344 science = scienceBase.clone() 

345 if positive: 

346 science.maskedImage += transients.maskedImage 

347 else: 

348 science.maskedImage -= transients.maskedImage 

349 difference = science.clone() 

350 difference.maskedImage -= matchedTemplate.maskedImage 

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

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

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

354 # later tests. 

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

356 refIds = [] 

357 scale = 1. if positive else -1. 

358 for diaSource in output.diaSources: 

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

360 _detection_wrapper(positive=True) 

361 _detection_wrapper(positive=False) 

362 

363 def test_detect_transients_with_background(self): 

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

365 """ 

366 # Set up the simulated images 

367 noiseLevel = 1. 

368 staticSeed = 1 

369 transientSeed = 6 

370 fluxLevel = 500 

371 xSize = 512 

372 ySize = 512 

373 x0 = 123 

374 y0 = 456 

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

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

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

378 

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

380 background_model = afwMath.Chebyshev1Function2D(params, bbox2D) 

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

382 background=background_model, **kwargs) 

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

384 

385 # Configure the detection Task 

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

387 kwargs["seed"] = transientSeed 

388 kwargs["nSrc"] = 10 

389 kwargs["fluxLevel"] = 1000 

390 

391 # Run detection and check the results 

392 def _detection_wrapper(positive=True): 

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

394 science = scienceBase.clone() 

395 if positive: 

396 science.maskedImage += transients.maskedImage 

397 else: 

398 science.maskedImage -= transients.maskedImage 

399 difference = science.clone() 

400 difference.maskedImage -= matchedTemplate.maskedImage 

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

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

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

404 # later tests. 

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

406 refIds = [] 

407 scale = 1. if positive else -1. 

408 for transient in transientSources: 

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

410 _detection_wrapper(positive=True) 

411 _detection_wrapper(positive=False) 

412 

413 def test_missing_mask_planes(self): 

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

415 """ 

416 # Set up the simulated images 

417 noiseLevel = 1. 

418 fluxLevel = 500 

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

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

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

422 science.getInfo().setVisitInfo(makeVisitInfo()) 

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

424 

425 difference = science.clone() 

426 difference.maskedImage -= matchedTemplate.maskedImage 

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

428 

429 # Verify that detection runs without errors 

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

431 

432 def test_detect_dipoles(self): 

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

434 """ 

435 # Set up the simulated images 

436 noiseLevel = 1. 

437 staticSeed = 1 

438 fluxLevel = 1000 

439 fluxRange = 1.5 

440 nSources = 10 

441 offset = 1 

442 xSize = 300 

443 ySize = 300 

444 kernelSize = 32 

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

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

447 templateBorderSize = kernelSize//2 

448 dipoleFlag = "ip_diffim_DipoleFit_classification" 

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

450 "nSrc": nSources, "templateBorderSize": templateBorderSize, "kernelSize": kernelSize, 

451 "xSize": xSize, "ySize": ySize} 

452 dipoleFlag = "ip_diffim_DipoleFit_classification" 

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

454 science.getInfo().setVisitInfo(makeVisitInfo()) 

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

456 difference = science.clone() 

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

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

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

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

461 

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

463 # creating poor subtractions. 

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

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

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

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

468 # no sources should be flagged as negative 

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

470 refIds = [] 

471 for diaSource in diaSources: 

472 if diaSource[dipoleFlag]: 

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

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

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

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

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

478 else: 

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

480 

481 def test_sky_sources(self): 

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

483 sources and have negligible flux. 

484 """ 

485 # Set up the simulated images 

486 noiseLevel = 1. 

487 staticSeed = 1 

488 transientSeed = 6 

489 transientFluxLevel = 1000. 

490 transientFluxRange = 1.5 

491 fluxLevel = 500 

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

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

494 science.getInfo().setVisitInfo(makeVisitInfo()) 

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

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

497 nSrc=10, fluxLevel=transientFluxLevel, 

498 fluxRange=transientFluxRange, 

499 noiseLevel=noiseLevel, noiseSeed=8) 

500 difference = science.clone() 

501 difference.maskedImage -= matchedTemplate.maskedImage 

502 difference.maskedImage += transients.maskedImage 

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

504 

505 # Configure the detection Task 

506 detectionTask = self._setup_detection(doSkySources=True) 

507 

508 # Run detection and check the results 

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

510 idFactory=self.idGenerator.make_table_id_factory()) 

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

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

513 for skySource in skySources: 

514 # Disable the sky_source flag to enable checks. 

515 skySource["sky_source"] = False 

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

517 with self.assertRaises(AssertionError): 

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

519 with self.assertRaises(AssertionError): 

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

521 # The sky sources should have low flux levels. 

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

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

524 

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

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

527 

528 def test_exclude_mask_detections(self): 

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

530 """ 

531 # Set up the simulated images 

532 noiseLevel = 1. 

533 staticSeed = 1 

534 transientSeed = 6 

535 fluxLevel = 500 

536 radius = 2 

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

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

539 science.getInfo().setVisitInfo(makeVisitInfo()) 

540 detector = DetectorWrapper(numAmps=1).detector 

541 science.setDetector(detector) 

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

543 

544 # Configure the detection Task 

545 detectionTask = self._setup_detection() 

546 excludeMaskPlanes = detectionTask.config.detection.excludeMaskPlanes 

547 nBad = len(excludeMaskPlanes) 

548 self.assertGreater(nBad, 0) 

549 kwargs["seed"] = transientSeed 

550 kwargs["nSrc"] = nBad 

551 kwargs["fluxLevel"] = 1000 

552 

553 # Run detection and check the results 

554 def _detection_wrapper(setFlags=True): 

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

556 difference = science.clone() 

557 difference.maskedImage -= matchedTemplate.maskedImage 

558 difference.maskedImage += transients.maskedImage 

559 if setFlags: 

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

561 srcX = int(src.getX()) 

562 srcY = int(src.getY()) 

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

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

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

566 if setFlags: 

567 with self.assertRaises(AlgorithmError): 

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

569 return 

570 else: 

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

572 refIds = [] 

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

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

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

576 if ~goodSrcFlag: 

577 with self.assertRaises(AssertionError): 

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

579 else: 

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

581 _detection_wrapper(setFlags=False) 

582 _detection_wrapper(setFlags=True) 

583 

584 def test_fake_mask_plane_propagation(self): 

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

586 This is testing method called updateMasks 

587 """ 

588 xSize = 256 

589 ySize = 256 

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

591 science_fake_img, science_fake_sources = makeTestImage( 

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

593 ) 

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

595 tmplt_fake_img, tmplt_fake_sources = makeTestImage( 

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

597 ) 

598 # created fakes and added them to the images 

599 science.image += science_fake_img.image 

600 template.image += tmplt_fake_img.image 

601 

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

603 # adding mask planes to both science and template images 

604 science.mask.addMaskPlane("FAKE") 

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

606 template.mask.addMaskPlane("FAKE") 

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

608 

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

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

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

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

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

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

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

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

617 

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

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

620 

621 subtractConfig = subtractImages.AlardLuptonSubtractTask.ConfigClass() 

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

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

624 subtractTask = subtractImages.AlardLuptonSubtractTask(config=subtractConfig) 

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

626 

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

628 diff_mask = subtraction.difference.mask 

629 

630 # science mask should be now in INJECTED 

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

632 

633 # template mask should be now in INJECTED_TEMPLATE 

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

635 

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

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

638 # include more pixels than the FAKE mask plane 

639 injTmplt_masked &= template_fake_masked 

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

641 

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

643 detectionTask = self._setup_detection() 

644 

645 output = detectionTask.run(subtraction.matchedScience, 

646 subtraction.matchedTemplate, 

647 subtraction.difference, 

648 subtraction.kernelSources) 

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

650 

651 sci_refIds = [] 

652 tmpl_refIds = [] 

653 for diaSrc in diaSources: 

654 if diaSrc['base_PsfFlux_instFlux'] > 0: 

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

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

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

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

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

660 else: 

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

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

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

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

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

666 

667 def test_mask_streaks(self): 

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

669 """ 

670 # Set up the simulated images 

671 noiseLevel = 1. 

672 staticSeed = 1 

673 fluxLevel = 500 

674 xSize = 400 

675 ySize = 400 

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

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

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

679 

680 # Configure the detection Task 

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

682 raiseOnNoDiaSources=False, raiseOnBadSubtractionRatio=False) 

683 

684 # Test that no streaks are detected 

685 difference = science.clone() 

686 difference.maskedImage -= matchedTemplate.maskedImage 

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

688 outMask = output.subtractedMeasuredExposure.mask.array 

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

690 streakMaskSet = (outMask & streakMask) > 0 

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

692 

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

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

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

696 outMask = output.subtractedMeasuredExposure.mask.array 

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

698 streakMaskSet = (outMask & streakMask) > 0 

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

700 

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

702 # fainter and check that it is also detected 

703 bbox = science.getBBox() 

704 difference = science.clone() 

705 difference.maskedImage -= matchedTemplate.maskedImage 

706 width = 100 

707 amplitude = 5 

708 x0 = -100 + bbox.getBeginX() 

709 y0 = -100 + bbox.getBeginY() 

710 x1 = xSize + x0 + 100 

711 y1 = ySize/2 

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

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

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

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

716 streak_trapezoid = afwGeom.Polygon(corner_coords) 

717 streak_image = streak_trapezoid.createImage(bbox) 

718 streak_image *= amplitude 

719 difference.image.array += streak_image.array 

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

721 outMask = output.subtractedMeasuredExposure.mask.array 

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

723 streakMaskSet = (outMask & streakMask) > 0 

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

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

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

727 # Check that the entire image was not masked STREAK 

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

729 

730 def _setup_sattle_tests(self): 

731 noiseLevel = 1. 

732 staticSeed = 1 

733 fluxLevel = 500 

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

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

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

737 **shared_kwargs) 

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

739 detector = DetectorWrapper(numAmps=1).detector 

740 science.setDetector(detector) 

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

742 noiseSeed=7, **shared_kwargs) 

743 difference = science.clone() 

744 

745 detectionTask = self._setup_detection(doDeblend=True, 

746 badSubtractionRatioThreshold=1., 

747 doSkySources=False, run_sattle=True) 

748 

749 return science, matchedTemplate, difference, sources, detectionTask 

750 

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

752 def test_sattle_not_available(self): 

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

754 

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

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

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

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

759 idFactory=IdFactory.makeSimple()) 

760 

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

762 def test_visit_id_not_in_sattle(self): 

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

764 

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

766 # visit id not in sattle raises 

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

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

769 return_value=response): 

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

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

772 idFactory=IdFactory.makeSimple()) 

773 

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

775 def test_filter_satellites_some_allowed(self): 

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

777 

778 allowed_ids = [1, 5] 

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

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

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

782 idFactory=IdFactory.makeSimple()) 

783 

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

785 

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

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

788 

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

790 def test_filter_satellites_all_allowed(self): 

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

792 

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

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

795 # Run detection and check the results 

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

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

798 idFactory=IdFactory.makeSimple()) 

799 

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

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

802 

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

804 

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

806 def test_filter_satellites_none_allowed(self): 

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

808 

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

810 # Run detection and confirm it raises for no diasources 

811 with self.assertRaises(detectAndMeasure.NoDiaSourcesError): 

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

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

814 idFactory=IdFactory.makeSimple()) 

815 

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

817 def test_fail_on_sattle_misconfiguration(self): 

818 with self.assertRaises(pexConfig.FieldValidationError): 

819 self._setup_detection(run_sattle=True) 

820 

821 def test_trailed_glints(self): 

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

823 the trailed_glints output contains the expected information. 

824 """ 

825 noiseLevel = 1. 

826 staticSeed = 1 

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

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

829 

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

831 def _detection_wrapper(diffim, diaSources): 

832 detectionTask = self._setup_detection() 

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

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

835 science = scienceBase.clone() 

836 science.maskedImage -= diffim.maskedImage 

837 difference = science.clone() 

838 difference.maskedImage -= matchedTemplate.maskedImage 

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

840 return output 

841 

842 output = _detection_wrapper(diffim, diaSources) 

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

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

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

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

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

848 

849 

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

851 detectionTask = detectAndMeasure.DetectAndMeasureScoreTask 

852 

853 def test_detection_xy0(self): 

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

855 """ 

856 # Set up the simulated images 

857 noiseLevel = 1. 

858 staticSeed = 1 

859 fluxLevel = 500 

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

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

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

863 difference = science.clone() 

864 subtractTask = subtractImages.AlardLuptonPreconvolveSubtractTask() 

865 scienceKernel = science.psf.getKernel() 

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

867 

868 # Configure the detection Task 

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

870 # is not actually subtracted from the science image. 

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

872 doSkySources=False) 

873 

874 # Run detection and check the results 

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

876 idFactory=self.idGenerator.make_table_id_factory()) 

877 

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

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

880 subtractedMeasuredExposure = output.subtractedMeasuredExposure 

881 

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

883 

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

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

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

887 # no sources should be flagged as negative 

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

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

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

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

892 # refIds = [] 

893 # for source in sources: 

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

895 

896 def test_measurements_finite(self): 

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

898 """ 

899 columnNames = ["coord_ra", "coord_dec", "ip_diffim_forced_PsfFlux_instFlux", 

900 "ip_diffim_forced_template_PsfFlux_instFlux"] 

901 

902 # Set up the simulated images 

903 noiseLevel = 1. 

904 staticSeed = 1 

905 transientSeed = 6 

906 xSize = 256 

907 ySize = 256 

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

909 "xSize": xSize, "ySize": ySize} 

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

911 nSrc=1, **kwargs) 

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

913 nSrc=1, **kwargs) 

914 rng = np.random.RandomState(3) 

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

916 rng.shuffle(xLoc) 

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

918 rng.shuffle(yLoc) 

919 transients, transientSources = makeTestImage(seed=transientSeed, 

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

921 noiseLevel=noiseLevel, noiseSeed=8, 

922 xLoc=xLoc, yLoc=yLoc, 

923 **kwargs) 

924 difference = science.clone() 

925 difference.maskedImage -= matchedTemplate.maskedImage 

926 difference.maskedImage += transients.maskedImage 

927 subtractTask = subtractImages.AlardLuptonPreconvolveSubtractTask() 

928 scienceKernel = science.psf.getKernel() 

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

930 

931 # Configure the detection Task 

932 detectionTask = self._setup_detection(doForcedMeasurement=True) 

933 

934 # Run detection and check the results 

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

936 

937 for column in columnNames: 

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

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

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

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

942 

943 def test_detect_transients(self): 

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

945 """ 

946 # Set up the simulated images 

947 noiseLevel = 1. 

948 staticSeed = 1 

949 transientSeed = 6 

950 fluxLevel = 500 

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

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

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

954 scienceKernel = scienceBase.psf.getKernel() 

955 subtractTask = subtractImages.AlardLuptonPreconvolveSubtractTask() 

956 

957 # Configure the detection Task 

958 detectionTask = self._setup_detection(doMerge=False) 

959 kwargs["seed"] = transientSeed 

960 kwargs["nSrc"] = 10 

961 kwargs["fluxLevel"] = 1000 

962 

963 # Run detection and check the results 

964 def _detection_wrapper(positive=True): 

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

966 

967 Parameters 

968 ---------- 

969 positive : `bool`, optional 

970 If set, use positive transient sources. 

971 """ 

972 

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

974 science = scienceBase.clone() 

975 if positive: 

976 science.maskedImage += transients.maskedImage 

977 else: 

978 science.maskedImage -= transients.maskedImage 

979 difference = science.clone() 

980 difference.maskedImage -= matchedTemplate.maskedImage 

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

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

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

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

985 # later tests. 

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

987 refIds = [] 

988 scale = 1. if positive else -1. 

989 # sources near the edge may have untrustworthy centroids 

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

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

992 if goodSrcFlag: 

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

994 _detection_wrapper(positive=True) 

995 _detection_wrapper(positive=False) 

996 

997 def test_detect_dipoles(self): 

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

999 """ 

1000 # Set up the simulated images 

1001 noiseLevel = 1. 

1002 staticSeed = 1 

1003 fluxLevel = 1000 

1004 fluxRange = 1.5 

1005 nSources = 10 

1006 offset = 1 

1007 xSize = 300 

1008 ySize = 300 

1009 kernelSize = 32 

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

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

1012 templateBorderSize = kernelSize//2 

1013 dipoleFlag = "ip_diffim_DipoleFit_classification" 

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

1015 "nSrc": nSources, "templateBorderSize": templateBorderSize, "kernelSize": kernelSize, 

1016 "xSize": xSize, "ySize": ySize} 

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

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

1019 difference = science.clone() 

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

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

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

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

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

1025 subtractTask = subtractImages.AlardLuptonPreconvolveSubtractTask() 

1026 scienceKernel = science.psf.getKernel() 

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

1028 

1029 detectionTask = self._setup_detection(badSubtractionRatioThreshold=0.3) 

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

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

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

1033 refIds = [] 

1034 for diaSource in diaSources: 

1035 if diaSource[dipoleFlag]: 

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

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

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

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

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

1041 else: 

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

1043 

1044 def test_sky_sources(self): 

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

1046 sources and have negligible flux. 

1047 """ 

1048 # Set up the simulated images 

1049 noiseLevel = 1. 

1050 staticSeed = 1 

1051 transientSeed = 6 

1052 transientFluxLevel = 1000. 

1053 transientFluxRange = 1.5 

1054 fluxLevel = 500 

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

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

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

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

1059 nSrc=10, fluxLevel=transientFluxLevel, 

1060 fluxRange=transientFluxRange, 

1061 noiseLevel=noiseLevel, noiseSeed=8) 

1062 difference = science.clone() 

1063 difference.maskedImage -= matchedTemplate.maskedImage 

1064 difference.maskedImage += transients.maskedImage 

1065 subtractTask = subtractImages.AlardLuptonPreconvolveSubtractTask() 

1066 scienceKernel = science.psf.getKernel() 

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

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

1069 

1070 # Configure the detection Task 

1071 detectionTask = self._setup_detection(doSkySources=True) 

1072 

1073 # Run detection and check the results 

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

1075 idFactory=self.idGenerator.make_table_id_factory()) 

1076 nSkySourcesGenerated = detectionTask.metadata["n_skySources"] 

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

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

1079 for skySource in skySources: 

1080 # Disable the sky_source flag to enable checks. 

1081 skySource["sky_source"] = False 

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

1083 with self.assertRaises(AssertionError): 

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

1085 with self.assertRaises(AssertionError): 

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

1087 # The sky sources should have low flux levels. 

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

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

1090 

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

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

1093 

1094 def test_exclude_mask_detections(self): 

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

1096 """ 

1097 # Set up the simulated images 

1098 noiseLevel = 1. 

1099 staticSeed = 1 

1100 transientSeed = 6 

1101 fluxLevel = 500 

1102 radius = 2 

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

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

1105 science.getInfo().setVisitInfo(makeVisitInfo()) 

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

1107 

1108 subtractTask = subtractImages.AlardLuptonPreconvolveSubtractTask() 

1109 scienceKernel = science.psf.getKernel() 

1110 # Configure the detection Task 

1111 detectionTask = self._setup_detection() 

1112 excludeMaskPlanes = detectionTask.config.detection.excludeMaskPlanes 

1113 nBad = len(excludeMaskPlanes) 

1114 self.assertGreater(nBad, 0) 

1115 kwargs["seed"] = transientSeed 

1116 kwargs["nSrc"] = nBad 

1117 kwargs["fluxLevel"] = 1000 

1118 

1119 # Run detection and check the results 

1120 def _detection_wrapper(setFlags=True): 

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

1122 difference = science.clone() 

1123 difference.maskedImage -= matchedTemplate.maskedImage 

1124 difference.maskedImage += transients.maskedImage 

1125 if setFlags: 

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

1127 srcX = int(src.getX()) 

1128 srcY = int(src.getY()) 

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

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

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

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

1133 if setFlags: 

1134 with self.assertRaises(AlgorithmError): 

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

1136 return 

1137 else: 

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

1139 refIds = [] 

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

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

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

1143 if ~goodSrcFlag: 

1144 with self.assertRaises(AssertionError): 

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

1146 else: 

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

1148 _detection_wrapper(setFlags=False) 

1149 _detection_wrapper(setFlags=True) 

1150 

1151 

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

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

1154 various problems found on DM-48596. 

1155 """ 

1156 

1157 def testDeblendNegatives(self): 

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

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

1160 """ 

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

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

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

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

1165 delta = 10 

1166 with dataset.addBlend() as family: 

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

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

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

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

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

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

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

1174 difference = template.clone() 

1175 difference.image -= science.image 

1176 

1177 config = detectAndMeasure.DetectAndMeasureTask.ConfigClass() 

1178 config.doDeblend = True 

1179 task = detectAndMeasure.DetectAndMeasureTask(config=config) 

1180 # prelude steps taken from `detectAndMeasure.run` 

1181 task._prepareInputs(difference) 

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

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

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

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

1186 

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

1188 # the spans were empty. 

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

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

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

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

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

1194 # pixel values in those are correct (though DetectAndMeasureTask 

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

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

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

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

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

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

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

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

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

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

1205 

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

1207 

1208 def testMergeFootprints(self): 

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

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

1211 

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

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

1214 """ 

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

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

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

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

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

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

1221 # `template.image.subset` below. 

1222 # positive isolated source on diffim 

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

1224 # negative isolated source on diffim 

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

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

1227 delta = 10 

1228 # negative blended pair on diffim 

1229 with dataset.addBlend() as family: 

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

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

1232 # positive blended pair on diffim 

1233 with dataset.addBlend() as family: 

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

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

1236 # negative blended pair on diffim 

1237 with dataset.addBlend() as family: 

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

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

1240 # negative isolated source on diffim 

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

1242 # negative isolated source on diffim 

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

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

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

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

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

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

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

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

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

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

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

1254 difference = science.clone() 

1255 difference.image -= template.image 

1256 

1257 config = detectAndMeasure.DetectAndMeasureTask.ConfigClass() 

1258 config.doDeblend = True 

1259 config.raiseOnBadSubtractionRatio = False 

1260 config.raiseOnNoDiaSources = False 

1261 task = detectAndMeasure.DetectAndMeasureTask(config=config) 

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

1263 

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

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

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

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

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

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

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

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

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

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

1274 

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

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

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

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

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

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

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

1282 

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

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

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

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

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

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

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

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

1291 

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

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

1294 # handled. 

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

1296 

1297 

1298def makeVisitInfo(id=1): 

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

1300 return afwImage.VisitInfo(id=id, 

1301 exposureTime=10.01, 

1302 darkTime=11.02, 

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

1304 ut1=12345.1, 

1305 era=45.1*geom.degrees, 

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

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

1308 boresightAirmass=1.73, 

1309 boresightRotAngle=73.2*geom.degrees, 

1310 rotType=afwImage.RotType.SKY, 

1311 observatory=Observatory( 

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

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

1314 ) 

1315 

1316 

1317class MockResponse: 

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

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

1320 self.json_data = json_data 

1321 self.status_code = status_code 

1322 self.text = text 

1323 

1324 def json(self): 

1325 return self.json_data 

1326 

1327 def raise_for_status(self): 

1328 if self.status_code != 200: 

1329 raise requests.exceptions.HTTPError 

1330 

1331 

1332def setup_module(module): 

1333 lsst.utils.tests.init() 

1334 

1335 

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

1337 pass 

1338 

1339 

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

1341 lsst.utils.tests.init() 

1342 unittest.main()