Coverage for tests/test_subtractTask.py: 7%

755 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 unittest 

23 

24from astropy import units as u 

25 

26import lsst.afw.math as afwMath 

27import lsst.afw.table as afwTable 

28import lsst.geom 

29import lsst.meas.algorithms as measAlg 

30from lsst.ip.diffim import subtractImages 

31from lsst.pex.config import FieldValidationError 

32from lsst.pipe.base import NoWorkFound 

33import lsst.utils.tests 

34import numpy as np 

35from lsst.ip.diffim.utils import (computeRobustStatistics, computePSFNoiseEquivalentArea, 

36 evaluateMeanPsfFwhm, getPsfFwhm) 

37from lsst.pex.exceptions import InvalidParameterError 

38 

39from utils import makeStats, makeTestImage, CustomCoaddPsf 

40 

41 

42class AlardLuptonSubtractTestBase: 

43 def _setup_subtraction(self, **kwargs): 

44 """Setup and configure the image subtraction PipelineTask. 

45 

46 Parameters 

47 ---------- 

48 **kwargs 

49 Any additional config parameters to set. 

50 

51 Returns 

52 ------- 

53 `lsst.pipe.base.PipelineTask` 

54 The configured Task to use for detection and measurement. 

55 """ 

56 config = self.subtractTask.ConfigClass() 

57 config.doSubtractBackground = False 

58 config.sourceSelector.signalToNoise.fluxField = "truth_instFlux" 

59 config.sourceSelector.signalToNoise.errField = "truth_instFluxErr" 

60 config.sourceSelector.doUnresolved = True 

61 config.sourceSelector.doIsolated = True 

62 config.sourceSelector.doRequirePrimary = True 

63 config.sourceSelector.doFlags = True 

64 config.sourceSelector.doSignalToNoise = True 

65 config.sourceSelector.flags.bad = ["base_PsfFlux_flag", ] 

66 config.update(**kwargs) 

67 

68 return self.subtractTask(config=config) 

69 

70 

71class AlardLuptonSubtractTest(AlardLuptonSubtractTestBase, lsst.utils.tests.TestCase): 

72 subtractTask = subtractImages.AlardLuptonSubtractTask 

73 

74 def test_allowed_config_modes(self): 

75 """Verify the allowable modes for convolution. 

76 """ 

77 config = subtractImages.AlardLuptonSubtractTask.ConfigClass() 

78 config.mode = 'auto' 

79 config.mode = 'convolveScience' 

80 config.mode = 'convolveTemplate' 

81 

82 with self.assertRaises(FieldValidationError): 

83 config.mode = 'aotu' 

84 

85 def test_mismatched_template(self): 

86 """Test that an error is raised if the template 

87 does not fully contain the science image. 

88 """ 

89 xSize = 200 

90 ySize = 200 

91 science, sources = makeTestImage(psfSize=2.4, xSize=xSize + 20, ySize=ySize + 20) 

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

93 task = self._setup_subtraction() 

94 with self.assertRaises(AssertionError): 

95 task.run(template, science, sources) 

96 

97 def test_mismatched_filter(self): 

98 """Test that an error is raised if the science and template have 

99 different bands. 

100 """ 

101 xSize = 200 

102 ySize = 200 

103 science, sources = makeTestImage(psfSize=2.4, xSize=xSize + 20, ySize=ySize + 20, 

104 band="g", physicalFilter="g noCamera") 

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

106 band="not-g", physicalFilter="not-g noCamera") 

107 task = self._setup_subtraction() 

108 with self.assertRaises(AssertionError): 

109 task.run(template, science, sources) 

110 

111 def test_incomplete_template_coverage(self): 

112 noiseLevel = 1. 

113 border = 20 

114 xSize = 400 

115 ySize = 400 

116 science, sources = makeTestImage(psfSize=3.0, noiseLevel=noiseLevel, noiseSeed=6, nSrc=50, 

117 xSize=xSize, ySize=ySize) 

118 template, _ = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=7, nSrc=50, 

119 templateBorderSize=border, doApplyCalibration=True, 

120 xSize=xSize, ySize=ySize) 

121 

122 science_height = science.getBBox().getDimensions().getY() 

123 

124 def _run_and_check_coverage(template_coverage, 

125 requiredTemplateFraction=0.1, 

126 minTemplateFractionForExpectedSuccess=0.2): 

127 template_cut = template.clone() 

128 template_height = int(science_height*template_coverage + border) 

129 template_cut.image.array[:, template_height:] = 0 

130 template_cut.mask.array[:, template_height:] = template_cut.mask.getPlaneBitMask('NO_DATA') 

131 task = self._setup_subtraction( 

132 requiredTemplateFraction=requiredTemplateFraction, 

133 minTemplateFractionForExpectedSuccess=minTemplateFractionForExpectedSuccess 

134 ) 

135 if template_coverage < requiredTemplateFraction: 

136 doRaise = True 

137 elif template_coverage < minTemplateFractionForExpectedSuccess: 

138 doRaise = True 

139 else: 

140 doRaise = False 

141 if doRaise: 

142 with self.assertRaises(NoWorkFound): 

143 task.run(template_cut, science.clone(), sources.copy(deep=True)) 

144 else: 

145 task.run(template_cut, science.clone(), sources.copy(deep=True)) 

146 _run_and_check_coverage(template_coverage=0.09) 

147 _run_and_check_coverage(template_coverage=0.19) 

148 _run_and_check_coverage(template_coverage=0.7) 

149 

150 def test_clear_template_mask(self): 

151 noiseLevel = 1. 

152 science, sources = makeTestImage(psfSize=3.0, noiseLevel=noiseLevel, noiseSeed=6) 

153 template, _ = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=7, 

154 templateBorderSize=20, doApplyCalibration=True) 

155 diffimEmptyMaskPlanes = ["DETECTED", "DETECTED_NEGATIVE"] 

156 task = self._setup_subtraction(mode="convolveTemplate") 

157 # Ensure that each each mask plane is set for some pixels 

158 mask = template.mask 

159 x0 = 50 

160 x1 = 75 

161 y0 = 150 

162 y1 = 175 

163 scienceMaskCheck = {} 

164 for maskPlane in mask.getMaskPlaneDict().keys(): 

165 scienceMaskCheck[maskPlane] = np.sum(science.mask.array & mask.getPlaneBitMask(maskPlane) > 0) 

166 mask.array[x0: x1, y0: y1] |= mask.getPlaneBitMask(maskPlane) 

167 self.assertTrue(np.sum(mask.array & mask.getPlaneBitMask(maskPlane) > 0)) 

168 

169 output = task.run(template, science, sources) 

170 # Verify that the template mask has been modified in place 

171 for maskPlane in mask.getMaskPlaneDict().keys(): 

172 if maskPlane in diffimEmptyMaskPlanes: 

173 self.assertTrue(np.sum(mask.array & mask.getPlaneBitMask(maskPlane) == 0)) 

174 elif maskPlane in task.config.preserveTemplateMask: 

175 self.assertTrue(np.sum(mask.array & mask.getPlaneBitMask(maskPlane) > 0)) 

176 else: 

177 self.assertTrue(np.sum(mask.array & mask.getPlaneBitMask(maskPlane) == 0)) 

178 # Mask planes set in the science image should also be set in the difference 

179 # Except the "DETECTED" planes should have been cleared 

180 diffimMask = output.difference.mask 

181 for maskPlane, scienceSum in scienceMaskCheck.items(): 

182 diffimSum = np.sum(diffimMask.array & mask.getPlaneBitMask(maskPlane) > 0) 

183 if maskPlane in diffimEmptyMaskPlanes: 

184 self.assertEqual(diffimSum, 0) 

185 else: 

186 self.assertTrue(diffimSum >= scienceSum) 

187 

188 def test_equal_images(self): 

189 """Test that running with enough sources produces reasonable output, 

190 with the same size psf in the template and science. 

191 """ 

192 noiseLevel = 1. 

193 science, sources = makeTestImage(psfSize=2.4, noiseLevel=noiseLevel, noiseSeed=6) 

194 template, _ = makeTestImage(psfSize=2.4, noiseLevel=noiseLevel, noiseSeed=7, 

195 templateBorderSize=20, doApplyCalibration=True) 

196 task = self._setup_subtraction() 

197 output = task.run(template, science, sources) 

198 # There shoud be no NaN values in the difference image 

199 self.assertTrue(np.all(np.isfinite(output.difference.image.array))) 

200 # Mean of difference image should be close to zero. 

201 meanError = noiseLevel/np.sqrt(output.difference.image.array.size) 

202 # Make sure to include pixels with the DETECTED mask bit set. 

203 statsCtrl = makeStats(badMaskPlanes=("EDGE", "BAD", "NO_DATA", "DETECTED", "DETECTED_NEGATIVE")) 

204 differenceMean = computeRobustStatistics(output.difference.image, output.difference.mask, statsCtrl) 

205 self.assertFloatsAlmostEqual(differenceMean, 0, atol=5*meanError) 

206 # stddev of difference image should be close to expected value. 

207 differenceStd = computeRobustStatistics(output.difference.image, output.difference.mask, 

208 makeStats(), statistic=afwMath.STDEV) 

209 self.assertFloatsAlmostEqual(differenceStd, np.sqrt(2)*noiseLevel, rtol=0.1) 

210 

211 def test_equal_images_missing_mask_planes(self): 

212 """Test that running with enough sources produces reasonable output, 

213 with the same size psf in the template and science and with missing 

214 mask planes. 

215 """ 

216 noiseLevel = 1. 

217 science, sources = makeTestImage(psfSize=2.4, noiseLevel=noiseLevel, noiseSeed=6, addMaskPlanes=[]) 

218 template, _ = makeTestImage(psfSize=2.4, noiseLevel=noiseLevel, noiseSeed=7, 

219 templateBorderSize=20, doApplyCalibration=True, addMaskPlanes=[]) 

220 task = self._setup_subtraction() 

221 output = task.run(template, science, sources) 

222 # There shoud be no NaN values in the difference image 

223 self.assertTrue(np.all(np.isfinite(output.difference.image.array))) 

224 # Mean of difference image should be close to zero. 

225 meanError = noiseLevel/np.sqrt(output.difference.image.array.size) 

226 # Make sure to include pixels with the DETECTED mask bit set. 

227 statsCtrl = makeStats(badMaskPlanes=("EDGE", "BAD", "NO_DATA", "DETECTED", "DETECTED_NEGATIVE")) 

228 differenceMean = computeRobustStatistics(output.difference.image, output.difference.mask, statsCtrl) 

229 self.assertFloatsAlmostEqual(differenceMean, 0, atol=5*meanError) 

230 # stddev of difference image should be close to expected value. 

231 differenceStd = computeRobustStatistics(output.difference.image, output.difference.mask, 

232 makeStats(), statistic=afwMath.STDEV) 

233 self.assertFloatsAlmostEqual(differenceStd, np.sqrt(2)*noiseLevel, rtol=0.1) 

234 

235 def test_psf_size(self): 

236 """Test that the image subtract task runs without failing, if 

237 fwhmExposureBuffer and fwhmExposureGrid parameters are set. 

238 """ 

239 noiseLevel = 1. 

240 science, sources = makeTestImage(psfSize=2.4, noiseLevel=noiseLevel, noiseSeed=6) 

241 template, _ = makeTestImage(psfSize=2.4, noiseLevel=noiseLevel, noiseSeed=7, 

242 templateBorderSize=20, doApplyCalibration=True) 

243 

244 schema = afwTable.ExposureTable.makeMinimalSchema() 

245 weightKey = schema.addField("weight", type="D", doc="Coadd weight") 

246 exposureCatalog = afwTable.ExposureCatalog(schema) 

247 kernel = measAlg.DoubleGaussianPsf(7, 7, 2.0).getKernel() 

248 psf = measAlg.KernelPsf(kernel, template.getBBox().getCenter()) 

249 

250 record = exposureCatalog.addNew() 

251 record.setPsf(psf) 

252 record.setWcs(template.wcs) 

253 record.setD(weightKey, 1.0) 

254 record.setBBox(template.getBBox()) 

255 

256 customPsf = CustomCoaddPsf(exposureCatalog, template.wcs) 

257 template.setPsf(customPsf) 

258 

259 # Test that we get an exception if we simply get the FWHM at center. 

260 with self.assertRaises(InvalidParameterError): 

261 getPsfFwhm(template.psf, True) 

262 

263 with self.assertRaises(InvalidParameterError): 

264 getPsfFwhm(template.psf, False) 

265 

266 # Test that evaluateMeanPsfFwhm runs successfully on the template. 

267 evaluateMeanPsfFwhm(template, fwhmExposureBuffer=0.05, fwhmExposureGrid=10) 

268 

269 # Since the PSF is spatially invariant, the FWHM should be the same at 

270 # all points in the science image. 

271 fwhm1 = getPsfFwhm(science.psf, False) 

272 fwhm2 = evaluateMeanPsfFwhm(science, fwhmExposureBuffer=0.05, fwhmExposureGrid=10) 

273 self.assertAlmostEqual(fwhm1[0], fwhm2, places=13) 

274 self.assertAlmostEqual(fwhm1[1], fwhm2, places=13) 

275 

276 self.assertAlmostEqual(evaluateMeanPsfFwhm(science, fwhmExposureBuffer=0.05, 

277 fwhmExposureGrid=10), 

278 getPsfFwhm(science.psf, True), places=7 

279 ) 

280 

281 # Test that the image subtraction task runs successfully. 

282 task = self._setup_subtraction() 

283 

284 # Test that the task runs if we take the mean FWHM on a grid. 

285 with self.assertLogs(level="INFO") as cm: 

286 task.run(template, science, sources) 

287 

288 # Check that evaluateMeanPsfFwhm was called. 

289 # This tests that getPsfFwhm failed raising InvalidParameterError, 

290 # that is caught and handled appropriately. 

291 logMessage = ("INFO:lsst.alardLuptonSubtract:Unable to evaluate PSF at the average position. " 

292 "Evaluting PSF on a grid of points." 

293 ) 

294 self.assertIn(logMessage, cm.output) 

295 

296 def test_auto_convolveTemplate(self): 

297 """Test that auto mode gives the same result as convolveTemplate when 

298 the template psf is the smaller. 

299 """ 

300 noiseLevel = 1. 

301 science, sources = makeTestImage(psfSize=3.0, noiseLevel=noiseLevel, noiseSeed=6) 

302 template, _ = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=7, 

303 templateBorderSize=20, doApplyCalibration=True) 

304 task = self._setup_subtraction(mode="convolveTemplate") 

305 output = task.run(template.clone(), science.clone(), sources) 

306 

307 task = self._setup_subtraction(mode="auto") 

308 outputAuto = task.run(template, science, sources) 

309 self.assertMaskedImagesEqual(output.difference.maskedImage, outputAuto.difference.maskedImage) 

310 

311 def test_auto_convolveScience(self): 

312 """Test that auto mode gives the same result as convolveScience when 

313 the science psf is the smaller. 

314 """ 

315 noiseLevel = 1. 

316 science, sources = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=6) 

317 template, _ = makeTestImage(psfSize=3.0, noiseLevel=noiseLevel, noiseSeed=7, 

318 templateBorderSize=20, doApplyCalibration=True) 

319 task = self._setup_subtraction(mode="convolveScience") 

320 output = task.run(template.clone(), science.clone(), sources) 

321 

322 task = self._setup_subtraction(mode="auto") 

323 outputAuto = task.run(template, science, sources) 

324 self.assertMaskedImagesEqual(output.difference.maskedImage, outputAuto.difference.maskedImage) 

325 

326 def test_science_better(self): 

327 """Test that running with enough sources produces reasonable output, 

328 with the science psf being smaller than the template. 

329 """ 

330 statsCtrl = makeStats() 

331 statsCtrlDetect = makeStats(badMaskPlanes=("EDGE", "BAD", "NO_DATA")) 

332 

333 def _run_and_check_images(statsCtrl, statsCtrlDetect, scienceNoiseLevel, templateNoiseLevel): 

334 science, sources = makeTestImage(psfSize=2.0, noiseLevel=scienceNoiseLevel, noiseSeed=6) 

335 template, _ = makeTestImage(psfSize=3.0, noiseLevel=templateNoiseLevel, noiseSeed=7, 

336 templateBorderSize=20, doApplyCalibration=True) 

337 task = self._setup_subtraction(mode="convolveScience") 

338 output = task.run(template, science, sources) 

339 self.assertFloatsAlmostEqual(task.metadata["scaleTemplateVarianceFactor"], 1., atol=.05) 

340 self.assertFloatsAlmostEqual(task.metadata["scaleScienceVarianceFactor"], 1., atol=.05) 

341 # Mean of difference image should be close to zero. 

342 nGoodPix = np.sum(np.isfinite(output.difference.image.array)) 

343 meanError = (scienceNoiseLevel + templateNoiseLevel)/np.sqrt(nGoodPix) 

344 diffimMean = computeRobustStatistics(output.difference.image, output.difference.mask, 

345 statsCtrlDetect) 

346 

347 self.assertFloatsAlmostEqual(diffimMean, 0, atol=5*meanError) 

348 # stddev of difference image should be close to expected value. 

349 noiseLevel = np.sqrt(scienceNoiseLevel**2 + templateNoiseLevel**2) 

350 varianceMean = computeRobustStatistics(output.difference.variance, output.difference.mask, 

351 statsCtrl) 

352 diffimStd = computeRobustStatistics(output.difference.image, output.difference.mask, 

353 statsCtrl, statistic=afwMath.STDEV) 

354 self.assertFloatsAlmostEqual(varianceMean, noiseLevel**2, rtol=0.1) 

355 self.assertFloatsAlmostEqual(diffimStd, noiseLevel, rtol=0.1) 

356 

357 _run_and_check_images(statsCtrl, statsCtrlDetect, scienceNoiseLevel=1., templateNoiseLevel=1.) 

358 _run_and_check_images(statsCtrl, statsCtrlDetect, scienceNoiseLevel=1., templateNoiseLevel=.1) 

359 _run_and_check_images(statsCtrl, statsCtrlDetect, scienceNoiseLevel=.1, templateNoiseLevel=.1) 

360 

361 def test_template_better(self): 

362 """Test that running with enough sources produces reasonable output, 

363 with the template psf being smaller than the science. 

364 """ 

365 statsCtrl = makeStats() 

366 statsCtrlDetect = makeStats(badMaskPlanes=("EDGE", "BAD", "NO_DATA")) 

367 

368 def _run_and_check_images(statsCtrl, statsCtrlDetect, scienceNoiseLevel, templateNoiseLevel): 

369 science, sources = makeTestImage(psfSize=3.0, noiseLevel=scienceNoiseLevel, noiseSeed=6) 

370 template, _ = makeTestImage(psfSize=2.0, noiseLevel=templateNoiseLevel, noiseSeed=7, 

371 templateBorderSize=20, doApplyCalibration=True) 

372 task = self._setup_subtraction() 

373 output = task.run(template, science, sources) 

374 self.assertFloatsAlmostEqual(task.metadata["scaleTemplateVarianceFactor"], 1., atol=.05) 

375 self.assertFloatsAlmostEqual(task.metadata["scaleScienceVarianceFactor"], 1., atol=.05) 

376 # There should be no NaNs in the image if we convolve the template with a buffer 

377 self.assertTrue(np.all(np.isfinite(output.difference.image.array))) 

378 # Mean of difference image should be close to zero. 

379 meanError = (scienceNoiseLevel + templateNoiseLevel)/np.sqrt(output.difference.image.array.size) 

380 

381 diffimMean = computeRobustStatistics(output.difference.image, output.difference.mask, 

382 statsCtrlDetect) 

383 self.assertFloatsAlmostEqual(diffimMean, 0, atol=5*meanError) 

384 # stddev of difference image should be close to expected value. 

385 noiseLevel = np.sqrt(scienceNoiseLevel**2 + templateNoiseLevel**2) 

386 varianceMean = computeRobustStatistics(output.difference.variance, output.difference.mask, 

387 statsCtrl) 

388 diffimStd = computeRobustStatistics(output.difference.image, output.difference.mask, 

389 statsCtrl, statistic=afwMath.STDEV) 

390 self.assertFloatsAlmostEqual(varianceMean, noiseLevel**2, rtol=0.1) 

391 self.assertFloatsAlmostEqual(diffimStd, noiseLevel, rtol=0.1) 

392 

393 _run_and_check_images(statsCtrl, statsCtrlDetect, scienceNoiseLevel=1., templateNoiseLevel=1.) 

394 _run_and_check_images(statsCtrl, statsCtrlDetect, scienceNoiseLevel=1., templateNoiseLevel=.1) 

395 _run_and_check_images(statsCtrl, statsCtrlDetect, scienceNoiseLevel=.1, templateNoiseLevel=.1) 

396 

397 def test_symmetry(self): 

398 """Test that convolving the science and convolving the template are 

399 symmetric: if the psfs are switched between them, the difference image 

400 should be nearly the same. 

401 """ 

402 noiseLevel = 1. 

403 # Don't include a border for the template, in order to make the results 

404 # comparable when we swap which image is treated as the "science" image. 

405 science, sources = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, 

406 noiseSeed=6, templateBorderSize=0, doApplyCalibration=True) 

407 template, _ = makeTestImage(psfSize=3.0, noiseLevel=noiseLevel, 

408 noiseSeed=7, templateBorderSize=0, doApplyCalibration=True) 

409 task = self._setup_subtraction(mode='auto') 

410 

411 # The science image will be modified in place, so use a copy for the second run. 

412 science_better = task.run(template.clone(), science.clone(), sources) 

413 template_better = task.run(science, template, sources) 

414 

415 delta = template_better.difference.clone() 

416 delta.image -= science_better.difference.image 

417 delta.variance -= science_better.difference.variance 

418 delta.mask.array -= science_better.difference.mask.array 

419 

420 statsCtrl = makeStats() 

421 # Mean of delta should be very close to zero. 

422 nGoodPix = np.sum(np.isfinite(delta.image.array)) 

423 meanError = 2*noiseLevel/np.sqrt(nGoodPix) 

424 deltaMean = computeRobustStatistics(delta.image, delta.mask, statsCtrl) 

425 deltaStd = computeRobustStatistics(delta.image, delta.mask, statsCtrl, statistic=afwMath.STDEV) 

426 self.assertFloatsAlmostEqual(deltaMean, 0, atol=5*meanError) 

427 # stddev of difference image should be close to expected value 

428 self.assertFloatsAlmostEqual(deltaStd, 2*np.sqrt(2)*noiseLevel, rtol=.1) 

429 

430 def test_few_sources(self): 

431 """Test with only 1 source, to check that we get a useful error. 

432 """ 

433 xSize = 256 

434 ySize = 256 

435 science, sources = makeTestImage(psfSize=2.4, nSrc=10, xSize=xSize, ySize=ySize) 

436 template, _ = makeTestImage(psfSize=2.0, nSrc=10, xSize=xSize, ySize=ySize, doApplyCalibration=True) 

437 task = self._setup_subtraction() 

438 sources = sources[0:1] 

439 with self.assertRaisesRegex(RuntimeError, 

440 "Cannot compute PSF matching kernel: too few sources selected."): 

441 task.run(template, science, sources) 

442 

443 def test_kernel_source_selector(self): 

444 """Check that kernel source selection behaves as expected. 

445 """ 

446 xSize = 256 

447 ySize = 256 

448 nSourcesSimulated = 20 

449 science, sources = makeTestImage(psfSize=2.4, nSrc=nSourcesSimulated, 

450 xSize=xSize, ySize=ySize) 

451 template, _ = makeTestImage(psfSize=2.0, nSrc=nSourcesSimulated, 

452 xSize=xSize, ySize=ySize, doApplyCalibration=True) 

453 

454 def _run_and_check_sources(sourcesIn, maxKernelSources=1000, minKernelSources=3): 

455 sources = sourcesIn.copy(deep=True) 

456 

457 task = self._setup_subtraction(maxKernelSources=maxKernelSources, 

458 minKernelSources=minKernelSources, 

459 ) 

460 # Verify that source flags are not set in the input catalog 

461 # Note that this will use the last flag in the list for the rest of 

462 # the test. 

463 for badSourceFlag in task.sourceSelector.config.flags.bad: 

464 self.assertEqual(np.sum(sources[badSourceFlag]), 0) 

465 nSources = len(sources) 

466 # Flag a third of the sources 

467 sources[0:: 3][badSourceFlag] = True 

468 nBadSources = np.sum(sources[badSourceFlag]) 

469 if maxKernelSources > 0: 

470 nGoodSources = np.minimum(nSources - nBadSources, maxKernelSources) 

471 else: 

472 nGoodSources = nSources - nBadSources 

473 

474 signalToNoise = sources.getPsfInstFlux()/sources.getPsfInstFluxErr() 

475 signalToNoise = signalToNoise[~sources[badSourceFlag]] 

476 signalToNoise.sort() 

477 selectSources = task._sourceSelector(sources, science.mask) 

478 self.assertEqual(nGoodSources, len(selectSources)) 

479 signalToNoiseOut = selectSources.getPsfInstFlux()/selectSources.getPsfInstFluxErr() 

480 signalToNoiseOut.sort() 

481 self.assertFloatsAlmostEqual(signalToNoise[-nGoodSources:], signalToNoiseOut) 

482 

483 _run_and_check_sources(sources) 

484 _run_and_check_sources(sources, maxKernelSources=len(sources)//3) 

485 _run_and_check_sources(sources, maxKernelSources=-1) 

486 with self.assertRaises(RuntimeError): 

487 _run_and_check_sources(sources, minKernelSources=1000) 

488 

489 def test_order_equal_images(self): 

490 """Verify that the result is the same regardless of convolution mode 

491 if the images are equivalent. 

492 """ 

493 noiseLevel = .1 

494 seed1 = 6 

495 seed2 = 7 

496 science1, sources1 = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=seed1, 

497 clearEdgeMask=True) 

498 template1, _ = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=seed2, 

499 templateBorderSize=0, doApplyCalibration=True, 

500 clearEdgeMask=True) 

501 task1 = self._setup_subtraction(mode="convolveTemplate") 

502 results_convolveTemplate = task1.run(template1, science1, sources1) 

503 

504 science2, sources2 = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=seed1, 

505 clearEdgeMask=True) 

506 template2, _ = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=seed2, 

507 templateBorderSize=0, doApplyCalibration=True, 

508 clearEdgeMask=True) 

509 task2 = self._setup_subtraction(mode="convolveScience") 

510 results_convolveScience = task2.run(template2, science2, sources2) 

511 bbox = results_convolveTemplate.difference.getBBox().clippedTo( 

512 results_convolveScience.difference.getBBox()) 

513 diff1 = science1.maskedImage.clone()[bbox] 

514 diff1 -= template1.maskedImage[bbox] 

515 diff2 = science2.maskedImage.clone()[bbox] 

516 diff2 -= template2.maskedImage[bbox] 

517 self.assertFloatsAlmostEqual(results_convolveTemplate.difference[bbox].image.array, 

518 diff1.image.array, 

519 atol=noiseLevel*5.) 

520 self.assertFloatsAlmostEqual(results_convolveScience.difference[bbox].image.array, 

521 diff2.image.array, 

522 atol=noiseLevel*5.) 

523 diffErr = noiseLevel*2 

524 self.assertMaskedImagesAlmostEqual(results_convolveTemplate.difference[bbox].maskedImage, 

525 results_convolveScience.difference[bbox].maskedImage, 

526 atol=diffErr*5.) 

527 

528 def test_background_subtraction(self): 

529 """Check that we can recover the background, 

530 and that it is subtracted correctly in the difference image. 

531 

532 NOTE: Background subtraction is now turned off by default in 

533 subtractImages. It is now run in detectAndMeasure instead, but since the 

534 code to run background subtraction is not being removed this test should 

535 stay to make sure it continues functioning as intended. 

536 """ 

537 noiseLevel = 1. 

538 xSize = 512 

539 ySize = 512 

540 x0 = 123 

541 y0 = 456 

542 template, _ = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=7, 

543 templateBorderSize=20, 

544 xSize=xSize, ySize=ySize, x0=x0, y0=y0, 

545 doApplyCalibration=True) 

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

547 

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

549 background_model = afwMath.Chebyshev1Function2D(params, bbox2D) 

550 science, sources = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=6, 

551 background=background_model, 

552 xSize=xSize, ySize=ySize, x0=x0, y0=y0) 

553 # Don't use ``self._setup_subtraction()`` here. 

554 # Modifying the config of a subtask is messy. 

555 config = subtractImages.AlardLuptonSubtractTask.ConfigClass() 

556 

557 config.sourceSelector.signalToNoise.fluxField = "truth_instFlux" 

558 config.sourceSelector.signalToNoise.errField = "truth_instFluxErr" 

559 config.doSubtractBackground = True 

560 

561 config.makeKernel.kernel.name = "AL" 

562 config.makeKernel.kernel.active.fitForBackground = True 

563 config.makeKernel.kernel.active.spatialKernelOrder = 1 

564 config.makeKernel.kernel.active.spatialBgOrder = 2 

565 statsCtrl = makeStats() 

566 

567 def _run_and_check_images(config, statsCtrl, mode): 

568 """Check that the fit background matches the input model. 

569 """ 

570 config.mode = mode 

571 task = subtractImages.AlardLuptonSubtractTask(config=config) 

572 output = task.run(template.clone(), science.clone(), sources) 

573 

574 # We should be fitting the same number of parameters as were in the input model 

575 self.assertEqual(output.backgroundModel.getNParameters(), background_model.getNParameters()) 

576 

577 # The parameters of the background fit should be close to the input model 

578 self.assertFloatsAlmostEqual(np.array(output.backgroundModel.getParameters()), 

579 np.array(params), rtol=0.3) 

580 

581 # stddev of difference image should be close to expected value. 

582 # This will fail if we have mis-subtracted the background. 

583 stdVal = computeRobustStatistics(output.difference.image, output.difference.mask, 

584 statsCtrl, statistic=afwMath.STDEV) 

585 self.assertFloatsAlmostEqual(stdVal, np.sqrt(2)*noiseLevel, rtol=0.1) 

586 

587 _run_and_check_images(config, statsCtrl, "convolveTemplate") 

588 _run_and_check_images(config, statsCtrl, "convolveScience") 

589 

590 def test_scale_variance_convolve_template(self): 

591 """Check variance scaling of the image difference. 

592 """ 

593 scienceNoiseLevel = 4. 

594 templateNoiseLevel = 2. 

595 scaleFactor = 1.345 

596 # Make sure to include pixels with the DETECTED mask bit set. 

597 statsCtrl = makeStats(badMaskPlanes=("EDGE", "BAD", "NO_DATA")) 

598 

599 def _run_and_check_images(science, template, sources, statsCtrl, 

600 doDecorrelation, doScaleVariance, scaleFactor=1.): 

601 """Check that the variance plane matches the expected value for 

602 different configurations of ``doDecorrelation`` and ``doScaleVariance``. 

603 """ 

604 

605 task = self._setup_subtraction(doDecorrelation=doDecorrelation, 

606 doScaleVariance=doScaleVariance, 

607 ) 

608 output = task.run(template.clone(), science.clone(), sources) 

609 if doScaleVariance: 

610 self.assertFloatsAlmostEqual(task.metadata["scaleTemplateVarianceFactor"], 

611 scaleFactor, atol=0.05) 

612 self.assertFloatsAlmostEqual(task.metadata["scaleScienceVarianceFactor"], 

613 scaleFactor, atol=0.05) 

614 

615 scienceNoise = computeRobustStatistics(science.variance, science.mask, statsCtrl) 

616 if doDecorrelation: 

617 templateNoise = computeRobustStatistics(template.variance, template.mask, statsCtrl) 

618 else: 

619 templateNoise = computeRobustStatistics(output.matchedTemplate.variance, 

620 output.matchedTemplate.mask, 

621 statsCtrl) 

622 

623 if doScaleVariance: 

624 templateNoise *= scaleFactor 

625 scienceNoise *= scaleFactor 

626 varMean = computeRobustStatistics(output.difference.variance, output.difference.mask, statsCtrl) 

627 self.assertFloatsAlmostEqual(varMean, scienceNoise + templateNoise, rtol=0.1) 

628 

629 science, sources = makeTestImage(psfSize=3.0, noiseLevel=scienceNoiseLevel, noiseSeed=6) 

630 template, _ = makeTestImage(psfSize=2.0, noiseLevel=templateNoiseLevel, noiseSeed=7, 

631 templateBorderSize=20, doApplyCalibration=True) 

632 # Verify that the variance plane of the difference image is correct 

633 # when the template and science variance planes are correct 

634 _run_and_check_images(science, template, sources, statsCtrl, 

635 doDecorrelation=True, doScaleVariance=True) 

636 _run_and_check_images(science, template, sources, statsCtrl, 

637 doDecorrelation=True, doScaleVariance=False) 

638 _run_and_check_images(science, template, sources, statsCtrl, 

639 doDecorrelation=False, doScaleVariance=True) 

640 _run_and_check_images(science, template, sources, statsCtrl, 

641 doDecorrelation=False, doScaleVariance=False) 

642 

643 # Verify that the variance plane of the difference image is correct 

644 # when the template variance plane is incorrect 

645 template.variance.array /= scaleFactor 

646 science.variance.array /= scaleFactor 

647 _run_and_check_images(science, template, sources, statsCtrl, 

648 doDecorrelation=True, doScaleVariance=True, scaleFactor=scaleFactor) 

649 _run_and_check_images(science, template, sources, statsCtrl, 

650 doDecorrelation=True, doScaleVariance=False, scaleFactor=scaleFactor) 

651 _run_and_check_images(science, template, sources, statsCtrl, 

652 doDecorrelation=False, doScaleVariance=True, scaleFactor=scaleFactor) 

653 _run_and_check_images(science, template, sources, statsCtrl, 

654 doDecorrelation=False, doScaleVariance=False, scaleFactor=scaleFactor) 

655 

656 def test_scale_variance_convolve_science(self): 

657 """Check variance scaling of the image difference. 

658 """ 

659 scienceNoiseLevel = 4. 

660 templateNoiseLevel = 2. 

661 scaleFactor = 1.345 

662 # Make sure to include pixels with the DETECTED mask bit set. 

663 statsCtrl = makeStats(badMaskPlanes=("EDGE", "BAD", "NO_DATA")) 

664 

665 def _run_and_check_images(science, template, sources, statsCtrl, 

666 doDecorrelation, doScaleVariance, scaleFactor=1.): 

667 """Check that the variance plane matches the expected value for 

668 different configurations of ``doDecorrelation`` and ``doScaleVariance``. 

669 """ 

670 

671 task = self._setup_subtraction(mode="convolveScience", 

672 doDecorrelation=doDecorrelation, 

673 doScaleVariance=doScaleVariance, 

674 ) 

675 output = task.run(template.clone(), science.clone(), sources) 

676 if doScaleVariance: 

677 self.assertFloatsAlmostEqual(task.metadata["scaleTemplateVarianceFactor"], 

678 scaleFactor, atol=0.05) 

679 self.assertFloatsAlmostEqual(task.metadata["scaleScienceVarianceFactor"], 

680 scaleFactor, atol=0.05) 

681 

682 templateNoise = computeRobustStatistics(template.variance, template.mask, statsCtrl) 

683 if doDecorrelation: 

684 scienceNoise = computeRobustStatistics(science.variance, science.mask, statsCtrl) 

685 else: 

686 scienceNoise = computeRobustStatistics(output.matchedScience.variance, 

687 output.matchedScience.mask, 

688 statsCtrl) 

689 

690 if doScaleVariance: 

691 templateNoise *= scaleFactor 

692 scienceNoise *= scaleFactor 

693 

694 varMean = computeRobustStatistics(output.difference.variance, output.difference.mask, statsCtrl) 

695 self.assertFloatsAlmostEqual(varMean, scienceNoise + templateNoise, rtol=0.1) 

696 

697 science, sources = makeTestImage(psfSize=2.0, noiseLevel=scienceNoiseLevel, noiseSeed=6) 

698 template, _ = makeTestImage(psfSize=3.0, noiseLevel=templateNoiseLevel, noiseSeed=7, 

699 templateBorderSize=20, doApplyCalibration=True) 

700 # Verify that the variance plane of the difference image is correct 

701 # when the template and science variance planes are correct 

702 _run_and_check_images(science, template, sources, statsCtrl, 

703 doDecorrelation=True, doScaleVariance=True) 

704 _run_and_check_images(science, template, sources, statsCtrl, 

705 doDecorrelation=True, doScaleVariance=False) 

706 _run_and_check_images(science, template, sources, statsCtrl, 

707 doDecorrelation=False, doScaleVariance=True) 

708 _run_and_check_images(science, template, sources, statsCtrl, 

709 doDecorrelation=False, doScaleVariance=False) 

710 

711 # Verify that the variance plane of the difference image is correct 

712 # when the template and science variance planes are incorrect 

713 science.variance.array /= scaleFactor 

714 template.variance.array /= scaleFactor 

715 _run_and_check_images(science, template, sources, statsCtrl, 

716 doDecorrelation=True, doScaleVariance=True, scaleFactor=scaleFactor) 

717 _run_and_check_images(science, template, sources, statsCtrl, 

718 doDecorrelation=True, doScaleVariance=False, scaleFactor=scaleFactor) 

719 _run_and_check_images(science, template, sources, statsCtrl, 

720 doDecorrelation=False, doScaleVariance=True, scaleFactor=scaleFactor) 

721 _run_and_check_images(science, template, sources, statsCtrl, 

722 doDecorrelation=False, doScaleVariance=False, scaleFactor=scaleFactor) 

723 

724 def test_exposure_properties_convolve_template(self): 

725 """Check that all necessary exposure metadata is included 

726 when the template is convolved. 

727 """ 

728 noiseLevel = 1. 

729 seed = 37 

730 rng = np.random.RandomState(seed) 

731 science, sources = makeTestImage(psfSize=3.0, noiseLevel=noiseLevel, noiseSeed=6) 

732 psf = science.psf 

733 psfAvgPos = psf.getAveragePosition() 

734 psfSize = getPsfFwhm(science.psf) 

735 psfImg = psf.computeKernelImage(psfAvgPos) 

736 template, _ = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=7, 

737 templateBorderSize=20, doApplyCalibration=True) 

738 

739 # Generate a random aperture correction map 

740 apCorrMap = lsst.afw.image.ApCorrMap() 

741 for name in ("a", "b", "c"): 

742 apCorrMap.set(name, lsst.afw.math.ChebyshevBoundedField(science.getBBox(), rng.randn(3, 3))) 

743 science.info.setApCorrMap(apCorrMap) 

744 

745 def _run_and_check_images(doDecorrelation): 

746 """Check that the metadata is correct with or without decorrelation. 

747 """ 

748 task = self._setup_subtraction(mode="convolveTemplate", 

749 doDecorrelation=doDecorrelation, 

750 ) 

751 output = task.run(template.clone(), science.clone(), sources) 

752 psfOut = output.difference.psf 

753 psfAvgPos = psfOut.getAveragePosition() 

754 if doDecorrelation: 

755 # Decorrelation requires recalculating the PSF, 

756 # so it will not be the same as the input 

757 psfOutSize = getPsfFwhm(science.psf) 

758 self.assertFloatsAlmostEqual(psfSize, psfOutSize) 

759 else: 

760 psfOutImg = psfOut.computeKernelImage(psfAvgPos) 

761 self.assertImagesAlmostEqual(psfImg, psfOutImg) 

762 

763 # check PSF, WCS, bbox, filterLabel, photoCalib, aperture correction 

764 self._compare_apCorrMaps(apCorrMap, output.difference.info.getApCorrMap()) 

765 self.assertWcsAlmostEqualOverBBox(science.wcs, output.difference.wcs, science.getBBox()) 

766 self.assertEqual(science.filter, output.difference.filter) 

767 self.assertEqual(science.photoCalib, output.difference.photoCalib) 

768 _run_and_check_images(doDecorrelation=True) 

769 _run_and_check_images(doDecorrelation=False) 

770 

771 def test_exposure_properties_convolve_science(self): 

772 """Check that all necessary exposure metadata is included 

773 when the science image is convolved. 

774 """ 

775 noiseLevel = 1. 

776 seed = 37 

777 rng = np.random.RandomState(seed) 

778 science, sources = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=6) 

779 template, _ = makeTestImage(psfSize=3.0, noiseLevel=noiseLevel, noiseSeed=7, 

780 templateBorderSize=20, doApplyCalibration=True) 

781 psf = template.psf 

782 psfAvgPos = psf.getAveragePosition() 

783 psfSize = getPsfFwhm(template.psf) 

784 psfImg = psf.computeKernelImage(psfAvgPos) 

785 

786 # Generate a random aperture correction map 

787 apCorrMap = lsst.afw.image.ApCorrMap() 

788 for name in ("a", "b", "c"): 

789 apCorrMap.set(name, lsst.afw.math.ChebyshevBoundedField(science.getBBox(), rng.randn(3, 3))) 

790 science.info.setApCorrMap(apCorrMap) 

791 

792 def _run_and_check_images(doDecorrelation): 

793 """Check that the metadata is correct with or without decorrelation. 

794 """ 

795 task = self._setup_subtraction(mode="convolveScience", 

796 doDecorrelation=doDecorrelation, 

797 ) 

798 output = task.run(template.clone(), science.clone(), sources) 

799 if doDecorrelation: 

800 # Decorrelation requires recalculating the PSF, 

801 # so it will not be the same as the input 

802 psfOutSize = getPsfFwhm(template.psf) 

803 self.assertFloatsAlmostEqual(psfSize, psfOutSize) 

804 else: 

805 psfOut = output.difference.psf 

806 psfAvgPos = psfOut.getAveragePosition() 

807 psfOutImg = psfOut.computeKernelImage(psfAvgPos) 

808 self.assertImagesAlmostEqual(psfImg, psfOutImg) 

809 

810 # check PSF, WCS, bbox, filterLabel, photoCalib, aperture correction 

811 self._compare_apCorrMaps(apCorrMap, output.difference.info.getApCorrMap()) 

812 self.assertWcsAlmostEqualOverBBox(science.wcs, output.difference.wcs, science.getBBox()) 

813 self.assertEqual(science.filter, output.difference.filter) 

814 self.assertEqual(science.photoCalib, output.difference.photoCalib) 

815 

816 _run_and_check_images(doDecorrelation=True) 

817 _run_and_check_images(doDecorrelation=False) 

818 

819 def _compare_apCorrMaps(self, a, b): 

820 """Compare two ApCorrMaps for equality, without assuming that their BoundedFields have the 

821 same addresses (i.e. so we can compare after serialization). 

822 

823 This function is taken from ``ApCorrMapTestCase`` in afw/tests/. 

824 

825 Parameters 

826 ---------- 

827 a, b : `lsst.afw.image.ApCorrMap` 

828 The two aperture correction maps to compare. 

829 """ 

830 self.assertEqual(len(a), len(b)) 

831 for name, value in list(a.items()): 

832 value2 = b.get(name) 

833 self.assertIsNotNone(value2) 

834 self.assertEqual(value.getBBox(), value2.getBBox()) 

835 self.assertFloatsAlmostEqual( 

836 value.getCoefficients(), value2.getCoefficients(), rtol=0.0) 

837 

838 def test_fake_mask_plane_propagation(self): 

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

840 This is testing method called updateMasks 

841 """ 

842 xSize = 200 

843 ySize = 200 

844 science, sources = makeTestImage(psfSize=2.4, xSize=xSize, ySize=ySize) 

845 science_fake_img, science_fake_sources = makeTestImage( 

846 psfSize=2.4, xSize=xSize, ySize=ySize, seed=7, nSrc=2, noiseLevel=0.25, fluxRange=1 

847 ) 

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

849 tmplt_fake_img, tmplt_fake_sources = makeTestImage( 

850 psfSize=2.4, xSize=xSize, ySize=ySize, seed=9, nSrc=2, noiseLevel=0.25, fluxRange=1 

851 ) 

852 # created fakes and added them to the images 

853 science.image.array += science_fake_img.image.array 

854 template.image.array += tmplt_fake_img.image.array 

855 

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

857 # adding mask planes to both science and template images 

858 science_mask_planes = science.mask.addMaskPlane("FAKE") 

859 template_mask_planes = template.mask.addMaskPlane("FAKE") 

860 

861 for a_science_source in science_fake_sources: 

862 # 3 x 3 masking of the source locations is fine 

863 bbox = lsst.geom.Box2I( 

864 lsst.geom.Point2I(a_science_source.getX(), a_science_source.getY()), lsst.geom.Extent2I(3, 3) 

865 ) 

866 science[bbox].mask.array |= science_mask_planes 

867 

868 for a_template_source in tmplt_fake_sources: 

869 # 3 x 3 masking of the source locations is fine 

870 bbox = lsst.geom.Box2I( 

871 lsst.geom.Point2I(a_template_source.getX(), a_template_source.getY()), 

872 lsst.geom.Extent2I(3, 3) 

873 ) 

874 template[bbox].mask.array |= template_mask_planes 

875 

876 science_fake_masked = (science.mask.array & science.mask.getPlaneBitMask("FAKE")) > 0 

877 template_fake_masked = (template.mask.array & template.mask.getPlaneBitMask("FAKE")) > 0 

878 

879 task = self._setup_subtraction() 

880 subtraction = task.run(template, science, sources) 

881 

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

883 diff_mask = subtraction.difference.mask 

884 

885 # science mask should be now in INJECTED 

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

887 

888 # template mask should be now in INJECTED_TEMPLATE 

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

890 

891 self.assertEqual(np.sum(inj_masked.astype(int)-science_fake_masked.astype(int)), 0) 

892 self.assertEqual(np.sum(injTmplt_masked.astype(int)-template_fake_masked.astype(int)), 0) 

893 

894 def test_metadata_metrics(self): 

895 """Verify fields are added to metadata when subtraction is run, and 

896 that the difference image limiting magnitude is calculated correctly, 

897 both with a "good" and "bad" seeing template. 

898 """ 

899 science, sources = makeTestImage(psfSize=2.8, noiseLevel=1) 

900 template_good, _ = makeTestImage(psfSize=2.4, doApplyCalibration=True, noiseLevel=0.25, 

901 templateBorderSize=20) 

902 template_bad, _ = makeTestImage(psfSize=9.5, doApplyCalibration=True, noiseLevel=0.25, 

903 templateBorderSize=20) 

904 

905 # Add a few sky objects; sky footprints are needed for some metrics. 

906 config = measAlg.SkyObjectsTask.ConfigClass() 

907 config.nSources = 3 

908 skyTask = measAlg.SkyObjectsTask(config=config, name="skySources") 

909 skyTask.skySourceKey = sources.schema["sky_source"].asKey() 

910 skyTask.run(science.mask, 10, catalog=sources) 

911 sources = sources.copy(deep=True) 

912 # Add centroids, since these sources were added post-measurement. 

913 for record in sources[sources["sky_source"]]: 

914 record["truth_x"] = record.getFootprint().getPeaks()[0].getFx() 

915 record["truth_y"] = record.getFootprint().getPeaks()[0].getFy() 

916 

917 # The metadata fields are attached to the subtractTask, so we do 

918 # need to run that; run it for both "good" and "bad" seeing templates 

919 

920 subtractTask_good = self._setup_subtraction() 

921 _ = subtractTask_good.run(template_good.clone(), science.clone(), sources) 

922 subtractTask_bad = self._setup_subtraction() 

923 _ = subtractTask_bad.run(template_bad.clone(), science.clone(), sources) 

924 

925 # Test that the diffim limiting magnitudes are computed correctly 

926 maglim_science = subtractTask_good._calculateMagLim(science) 

927 fluxlim_science = (maglim_science*u.ABmag).to_value(u.nJy) 

928 maglim_template_good = subtractTask_good._calculateMagLim(template_good) 

929 fluxlim_template_good = (maglim_template_good*u.ABmag).to_value(u.nJy) 

930 maglim_template_bad = subtractTask_bad._calculateMagLim(template_bad) 

931 fluxlim_template_bad = (maglim_template_bad*u.ABmag).to_value(u.nJy) 

932 

933 maglim_good = (np.sqrt(fluxlim_science**2 + fluxlim_template_good**2)*u.nJy).to(u.ABmag).value 

934 maglim_bad = (np.sqrt(fluxlim_science**2 + fluxlim_template_bad**2)*u.nJy).to(u.ABmag).value 

935 

936 self.assertFloatsAlmostEqual(subtractTask_good.metadata['diffimLimitingMagnitude'], 

937 maglim_good, atol=1e-6) 

938 self.assertFloatsAlmostEqual(subtractTask_bad.metadata['diffimLimitingMagnitude'], 

939 maglim_bad, atol=1e-6) 

940 

941 # Create a template with a PSF that is not defined at the image center. 

942 # First, make an exposure catalog so we can force the template to have 

943 # a bad (off-image) PSF. It must have a record with a weight field 

944 # and a BBox in order to let us set the PSF manually. 

945 template_offimage, _ = makeTestImage() 

946 schema = afwTable.ExposureTable.makeMinimalSchema() 

947 weightKey = schema.addField("weight", type="D", doc="Coadd weight") 

948 exposureCatalog = afwTable.ExposureCatalog(schema) 

949 record = exposureCatalog.addNew() 

950 record.setD(weightKey, 1.0) 

951 record.setBBox(template_offimage.getBBox()) 

952 kernel = measAlg.DoubleGaussianPsf(7, 7, 2.0).getKernel() 

953 psf = measAlg.KernelPsf(kernel, template_offimage.getBBox().getCenter()) 

954 record.setPsf(psf) 

955 record.setWcs(template_offimage.wcs) 

956 custom_offimage_psf = CustomCoaddPsf(exposureCatalog, template_offimage.wcs) 

957 template_offimage.setPsf(custom_offimage_psf) 

958 

959 # Test that template PSF size edge cases are handled correctly. 

960 subtractTask_offimage = self._setup_subtraction() 

961 _ = subtractTask_offimage.run(template_offimage.clone(), science.clone(), sources) 

962 # Test that providing no fallbackPsfSize results in a nan template 

963 # limiting magnitude. 

964 maglim_template_offimage = subtractTask_offimage._calculateMagLim(template_offimage) 

965 self.assertTrue(np.isnan(maglim_template_offimage)) 

966 # Test that given the provided fallbackPsfSize, the diffim limiting 

967 # magnitude is calculated correctly. 

968 maglim_template_offimage = 28.3173123103493 

969 fluxlim_template_offimage = (maglim_template_offimage*u.ABmag).to_value(u.nJy) 

970 maglim_offimage = (np.sqrt(fluxlim_science**2 + fluxlim_template_offimage**2)*u.nJy).to(u.ABmag).value 

971 self.assertEqual(subtractTask_offimage.metadata['diffimLimitingMagnitude'], maglim_offimage) 

972 

973 # Test that several other expected metadata metrics exist 

974 self.assertIn('scienceLimitingMagnitude', subtractTask_good.metadata) 

975 self.assertIn('templateLimitingMagnitude', subtractTask_good.metadata) 

976 

977 # The mean ratio metric should be much worse on the "bad" subtraction. 

978 self.assertLess(subtractTask_good.metadata['differenceFootprintRatioMean'], 0.02) 

979 self.assertGreater(subtractTask_bad.metadata['differenceFootprintRatioMean'], 0.12) 

980 

981 

982class AlardLuptonPreconvolveSubtractTest(AlardLuptonSubtractTestBase, lsst.utils.tests.TestCase): 

983 subtractTask = subtractImages.AlardLuptonPreconvolveSubtractTask 

984 

985 def test_mismatched_template(self): 

986 """Test that an error is raised if the template 

987 does not fully contain the science image. 

988 """ 

989 xSize = 200 

990 ySize = 200 

991 science, sources = makeTestImage(psfSize=2.4, xSize=xSize + 20, ySize=ySize + 20) 

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

993 task = self._setup_subtraction() 

994 with self.assertRaises(AssertionError): 

995 task.run(template, science, sources) 

996 

997 def test_equal_images(self): 

998 """Test that running with enough sources produces reasonable output, 

999 with the same size psf in the template and science. 

1000 """ 

1001 noiseLevel = 1. 

1002 xSize = 400 

1003 ySize = 400 

1004 science, sources = makeTestImage(psfSize=2.4, noiseLevel=noiseLevel, noiseSeed=6, 

1005 xSize=xSize, ySize=ySize) 

1006 template, _ = makeTestImage(psfSize=2.4, noiseLevel=noiseLevel, noiseSeed=7, 

1007 templateBorderSize=20, doApplyCalibration=True, 

1008 xSize=xSize, ySize=ySize) 

1009 task = self._setup_subtraction() 

1010 output = task.run(template, science, sources) 

1011 # There shoud be no NaN values in the Score image 

1012 self.assertTrue(np.all(np.isfinite(output.scoreExposure.image.array))) 

1013 # Mean of Score image should be close to zero. 

1014 meanError = noiseLevel/np.sqrt(output.scoreExposure.image.array.size) 

1015 # Make sure to include pixels with the DETECTED mask bit set. 

1016 statsCtrl = makeStats(badMaskPlanes=("EDGE", "BAD", "NO_DATA")) 

1017 scoreMean = computeRobustStatistics(output.scoreExposure.image, 

1018 output.scoreExposure.mask, 

1019 statsCtrl) 

1020 self.assertFloatsAlmostEqual(scoreMean, 0, atol=5*meanError) 

1021 nea = computePSFNoiseEquivalentArea(science.psf) 

1022 # stddev of Score image should be close to expected value. 

1023 scoreStd = computeRobustStatistics(output.scoreExposure.image, output.scoreExposure.mask, 

1024 statsCtrl=statsCtrl, statistic=afwMath.STDEV) 

1025 self.assertFloatsAlmostEqual(scoreStd, np.sqrt(2)*noiseLevel/np.sqrt(nea), rtol=0.1) 

1026 

1027 def test_incomplete_template_coverage(self): 

1028 noiseLevel = 1. 

1029 border = 20 

1030 xSize = 400 

1031 ySize = 400 

1032 science, sources = makeTestImage(psfSize=3.0, noiseLevel=noiseLevel, noiseSeed=6, 

1033 xSize=xSize, ySize=ySize) 

1034 template, _ = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=7, 

1035 templateBorderSize=border, doApplyCalibration=True, 

1036 xSize=xSize, ySize=ySize) 

1037 

1038 science_height = science.getBBox().getDimensions().getY() 

1039 

1040 def _run_and_check_coverage(template_coverage): 

1041 template_cut = template.clone() 

1042 template_height = int(science_height*template_coverage + border) 

1043 template_cut.image.array[:, template_height:] = 0 

1044 template_cut.mask.array[:, template_height:] = template_cut.mask.getPlaneBitMask('NO_DATA') 

1045 task = self._setup_subtraction() 

1046 if template_coverage < task.config.requiredTemplateFraction: 

1047 doRaise = True 

1048 elif template_coverage < task.config.minTemplateFractionForExpectedSuccess: 

1049 doRaise = True 

1050 else: 

1051 doRaise = False 

1052 if doRaise: 

1053 with self.assertRaises(NoWorkFound): 

1054 task.run(template_cut, science.clone(), sources.copy(deep=True)) 

1055 else: 

1056 task.run(template_cut, science.clone(), sources.copy(deep=True)) 

1057 _run_and_check_coverage(template_coverage=0.09) 

1058 _run_and_check_coverage(template_coverage=0.19) 

1059 _run_and_check_coverage(template_coverage=.7) 

1060 

1061 def test_clear_template_mask(self): 

1062 noiseLevel = 1. 

1063 xSize = 400 

1064 ySize = 400 

1065 science, sources = makeTestImage(psfSize=3.0, noiseLevel=noiseLevel, noiseSeed=6, 

1066 xSize=xSize, ySize=ySize) 

1067 template, _ = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=7, 

1068 templateBorderSize=20, doApplyCalibration=True, 

1069 xSize=xSize, ySize=ySize) 

1070 diffimEmptyMaskPlanes = ["DETECTED", "DETECTED_NEGATIVE"] 

1071 task = self._setup_subtraction() 

1072 # Ensure that each each mask plane is set for some pixels 

1073 mask = template.mask 

1074 x0 = 50 

1075 x1 = 75 

1076 y0 = 150 

1077 y1 = 175 

1078 scienceMaskCheck = {} 

1079 for maskPlane in mask.getMaskPlaneDict().keys(): 

1080 scienceMaskCheck[maskPlane] = np.sum(science.mask.array & mask.getPlaneBitMask(maskPlane) > 0) 

1081 mask.array[x0: x1, y0: y1] |= mask.getPlaneBitMask(maskPlane) 

1082 self.assertTrue(np.sum(mask.array & mask.getPlaneBitMask(maskPlane) > 0)) 

1083 

1084 output = task.run(template, science, sources) 

1085 # Verify that the template mask has been modified in place 

1086 for maskPlane in mask.getMaskPlaneDict().keys(): 

1087 if maskPlane in diffimEmptyMaskPlanes: 

1088 self.assertTrue(np.sum(mask.array & mask.getPlaneBitMask(maskPlane) == 0)) 

1089 elif maskPlane in task.config.preserveTemplateMask: 

1090 self.assertTrue(np.sum(mask.array & mask.getPlaneBitMask(maskPlane) > 0)) 

1091 else: 

1092 self.assertTrue(np.sum(mask.array & mask.getPlaneBitMask(maskPlane) == 0)) 

1093 # Mask planes set in the science image should also be set in the difference 

1094 # Except the "DETECTED" planes should have been cleared 

1095 diffimMask = output.scoreExposure.mask 

1096 for maskPlane, scienceSum in scienceMaskCheck.items(): 

1097 diffimSum = np.sum(diffimMask.array & mask.getPlaneBitMask(maskPlane) > 0) 

1098 if maskPlane in diffimEmptyMaskPlanes: 

1099 self.assertEqual(diffimSum, 0) 

1100 else: 

1101 self.assertTrue(diffimSum >= scienceSum) 

1102 

1103 def test_agnostic_template_psf(self): 

1104 """Test that the Score image is the same whether the template PSF is 

1105 larger or smaller than the science image PSF. 

1106 """ 

1107 noiseLevel = .3 

1108 xSize = 400 

1109 ySize = 400 

1110 science, sources = makeTestImage(psfSize=2.4, noiseLevel=noiseLevel, 

1111 noiseSeed=6, templateBorderSize=0, 

1112 xSize=xSize, ySize=ySize) 

1113 template1, _ = makeTestImage(psfSize=3.0, noiseLevel=noiseLevel, 

1114 noiseSeed=7, doApplyCalibration=True, 

1115 xSize=xSize, ySize=ySize) 

1116 template2, _ = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, 

1117 noiseSeed=8, doApplyCalibration=True, 

1118 xSize=xSize, ySize=ySize) 

1119 task = self._setup_subtraction() 

1120 

1121 science_better = task.run(template1, science.clone(), sources) 

1122 template_better = task.run(template2, science, sources) 

1123 bbox = science_better.scoreExposure.getBBox().clippedTo(template_better.scoreExposure.getBBox()) 

1124 

1125 delta = template_better.scoreExposure[bbox].clone() 

1126 delta.image -= science_better.scoreExposure[bbox].image 

1127 delta.variance -= science_better.scoreExposure[bbox].variance 

1128 delta.mask.array &= science_better.scoreExposure[bbox].mask.array 

1129 

1130 statsCtrl = makeStats(badMaskPlanes=("EDGE", "BAD", "NO_DATA")) 

1131 # Mean of delta should be very close to zero. 

1132 nGoodPix = np.sum(np.isfinite(delta.image.array)) 

1133 meanError = 2*noiseLevel/np.sqrt(nGoodPix) 

1134 deltaMean = computeRobustStatistics(delta.image, delta.mask, statsCtrl) 

1135 deltaStd = computeRobustStatistics(delta.image, delta.mask, statsCtrl, 

1136 statistic=afwMath.STDEV) 

1137 self.assertFloatsAlmostEqual(deltaMean, 0, atol=5*meanError) 

1138 nea = computePSFNoiseEquivalentArea(science.psf) 

1139 # stddev of Score image should be close to expected value 

1140 self.assertFloatsAlmostEqual(deltaStd, np.sqrt(2)*noiseLevel/np.sqrt(nea), rtol=.1) 

1141 

1142 def test_few_sources(self): 

1143 """Test with only 1 source, to check that we get a useful error. 

1144 """ 

1145 xSize = 256 

1146 ySize = 256 

1147 science, sources = makeTestImage(psfSize=2.4, nSrc=10, xSize=xSize, ySize=ySize) 

1148 template, _ = makeTestImage(psfSize=2.0, nSrc=10, xSize=xSize, ySize=ySize, doApplyCalibration=True) 

1149 task = self._setup_subtraction() 

1150 sources = sources[0:1] 

1151 with self.assertRaisesRegex(RuntimeError, 

1152 "Cannot compute PSF matching kernel: too few sources selected."): 

1153 task.run(template, science, sources) 

1154 

1155 def test_background_subtraction(self): 

1156 """Check that we can recover the background, 

1157 and that it is subtracted correctly in the Score image. 

1158 """ 

1159 noiseLevel = 1. 

1160 xSize = 512 

1161 ySize = 512 

1162 x0 = 123 

1163 y0 = 456 

1164 template, _ = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=7, 

1165 templateBorderSize=20, 

1166 xSize=xSize, ySize=ySize, x0=x0, y0=y0, 

1167 doApplyCalibration=True) 

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

1169 

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

1171 background_model = afwMath.Chebyshev1Function2D(params, bbox2D) 

1172 science, sources = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=6, 

1173 background=background_model, 

1174 xSize=xSize, ySize=ySize, x0=x0, y0=y0) 

1175 # Don't use ``self._setup_subtraction()`` here. 

1176 # Modifying the config of a subtask is messy. 

1177 config = subtractImages.AlardLuptonPreconvolveSubtractTask.ConfigClass() 

1178 

1179 config.sourceSelector.signalToNoise.fluxField = "truth_instFlux" 

1180 config.sourceSelector.signalToNoise.errField = "truth_instFluxErr" 

1181 config.doSubtractBackground = True 

1182 

1183 config.makeKernel.kernel.name = "AL" 

1184 config.makeKernel.kernel.active.fitForBackground = True 

1185 config.makeKernel.kernel.active.spatialKernelOrder = 1 

1186 config.makeKernel.kernel.active.spatialBgOrder = 2 

1187 statsCtrl = makeStats(badMaskPlanes=("EDGE", "BAD", "NO_DATA")) 

1188 

1189 task = subtractImages.AlardLuptonPreconvolveSubtractTask(config=config) 

1190 output = task.run(template.clone(), science.clone(), sources) 

1191 

1192 # We should be fitting the same number of parameters as were in the input model 

1193 self.assertEqual(output.backgroundModel.getNParameters(), background_model.getNParameters()) 

1194 

1195 # The parameters of the background fit should be close to the input model 

1196 self.assertFloatsAlmostEqual(np.array(output.backgroundModel.getParameters()), 

1197 np.array(params), rtol=0.2) 

1198 

1199 # stddev of Score image should be close to expected value. 

1200 # This will fail if we have mis-subtracted the background. 

1201 stdVal = computeRobustStatistics(output.scoreExposure.image, output.scoreExposure.mask, 

1202 statsCtrl, statistic=afwMath.STDEV) 

1203 # get the img psf Noise Equivalent Area value 

1204 nea = computePSFNoiseEquivalentArea(science.psf) 

1205 self.assertFloatsAlmostEqual(stdVal, np.sqrt(2)*noiseLevel/np.sqrt(nea), rtol=0.1) 

1206 

1207 def test_scale_variance(self): 

1208 """Check variance scaling of the Score image. 

1209 """ 

1210 scienceNoiseLevel = 4. 

1211 templateNoiseLevel = 2. 

1212 scaleFactor = 1.345 

1213 xSize = 400 

1214 ySize = 400 

1215 # Make sure to include pixels with the DETECTED mask bit set. 

1216 statsCtrl = makeStats(badMaskPlanes=("EDGE", "BAD", "NO_DATA")) 

1217 

1218 def _run_and_check_images(science, template, sources, statsCtrl, 

1219 doDecorrelation, doScaleVariance, scaleFactor=1.): 

1220 """Check that the variance plane matches the expected value for 

1221 different configurations of ``doDecorrelation`` and ``doScaleVariance``. 

1222 """ 

1223 

1224 task = self._setup_subtraction(doDecorrelation=doDecorrelation, 

1225 doScaleVariance=doScaleVariance, 

1226 ) 

1227 output = task.run(template.clone(), science.clone(), sources) 

1228 if doScaleVariance: 

1229 self.assertFloatsAlmostEqual(task.metadata["scaleTemplateVarianceFactor"], 

1230 scaleFactor, atol=0.05) 

1231 self.assertFloatsAlmostEqual(task.metadata["scaleScienceVarianceFactor"], 

1232 scaleFactor, atol=0.05) 

1233 

1234 scienceNoise = computeRobustStatistics(science.variance, science.mask, statsCtrl) 

1235 # get the img psf Noise Equivalent Area value 

1236 nea = computePSFNoiseEquivalentArea(science.psf) 

1237 scienceNoise /= nea 

1238 if doDecorrelation: 

1239 templateNoise = computeRobustStatistics(template.variance, template.mask, statsCtrl) 

1240 templateNoise /= nea 

1241 else: 

1242 # Don't divide by NEA in this case, since the template is convolved 

1243 # and in the same units as the Score exposure. 

1244 templateNoise = computeRobustStatistics(output.matchedTemplate.variance, 

1245 output.matchedTemplate.mask, 

1246 statsCtrl) 

1247 if doScaleVariance: 

1248 templateNoise *= scaleFactor 

1249 scienceNoise *= scaleFactor 

1250 varMean = computeRobustStatistics(output.scoreExposure.variance, 

1251 output.scoreExposure.mask, 

1252 statsCtrl) 

1253 self.assertFloatsAlmostEqual(varMean, scienceNoise + templateNoise, rtol=0.1) 

1254 

1255 science, sources = makeTestImage(psfSize=3.0, noiseLevel=scienceNoiseLevel, noiseSeed=6, 

1256 xSize=xSize, ySize=ySize) 

1257 template, _ = makeTestImage(psfSize=2.0, noiseLevel=templateNoiseLevel, noiseSeed=7, 

1258 templateBorderSize=20, doApplyCalibration=True, 

1259 xSize=xSize, ySize=ySize) 

1260 # Verify that the variance plane of the Score image is correct 

1261 # when the template and science variance planes are correct 

1262 _run_and_check_images(science, template, sources, statsCtrl, 

1263 doDecorrelation=True, doScaleVariance=True) 

1264 _run_and_check_images(science, template, sources, statsCtrl, 

1265 doDecorrelation=True, doScaleVariance=False) 

1266 _run_and_check_images(science, template, sources, statsCtrl, 

1267 doDecorrelation=False, doScaleVariance=True) 

1268 _run_and_check_images(science, template, sources, statsCtrl, 

1269 doDecorrelation=False, doScaleVariance=False) 

1270 

1271 # Verify that the variance plane of the Score image is correct 

1272 # when the template variance plane is incorrect 

1273 template.variance.array /= scaleFactor 

1274 science.variance.array /= scaleFactor 

1275 _run_and_check_images(science, template, sources, statsCtrl, 

1276 doDecorrelation=True, doScaleVariance=True, scaleFactor=scaleFactor) 

1277 _run_and_check_images(science, template, sources, statsCtrl, 

1278 doDecorrelation=True, doScaleVariance=False, scaleFactor=scaleFactor) 

1279 _run_and_check_images(science, template, sources, statsCtrl, 

1280 doDecorrelation=False, doScaleVariance=True, scaleFactor=scaleFactor) 

1281 _run_and_check_images(science, template, sources, statsCtrl, 

1282 doDecorrelation=False, doScaleVariance=False, scaleFactor=scaleFactor) 

1283 

1284 def test_exposure_properties(self): 

1285 """Check that all necessary exposure metadata is included 

1286 with the Score image. 

1287 """ 

1288 noiseLevel = 1. 

1289 xSize = 400 

1290 ySize = 400 

1291 science, sources = makeTestImage(psfSize=3.0, noiseLevel=noiseLevel, noiseSeed=6, 

1292 xSize=xSize, ySize=ySize) 

1293 psf = science.psf 

1294 psfAvgPos = psf.getAveragePosition() 

1295 psfSize = getPsfFwhm(science.psf) 

1296 psfImg = psf.computeKernelImage(psfAvgPos) 

1297 template, _ = makeTestImage(psfSize=2.0, noiseLevel=noiseLevel, noiseSeed=7, 

1298 templateBorderSize=20, doApplyCalibration=True, 

1299 xSize=xSize, ySize=ySize) 

1300 

1301 def _run_and_check_images(doDecorrelation): 

1302 """Check that the metadata is correct with or without decorrelation. 

1303 """ 

1304 task = self._setup_subtraction(doDecorrelation=doDecorrelation) 

1305 output = task.run(template.clone(), science.clone(), sources) 

1306 psfOut = output.scoreExposure.psf 

1307 psfAvgPos = psfOut.getAveragePosition() 

1308 if doDecorrelation: 

1309 # Decorrelation requires recalculating the PSF, 

1310 # so it will not be the same as the input 

1311 psfOutSize = getPsfFwhm(science.psf) 

1312 self.assertFloatsAlmostEqual(psfSize, psfOutSize) 

1313 else: 

1314 psfOutImg = psfOut.computeKernelImage(psfAvgPos) 

1315 self.assertImagesAlmostEqual(psfImg, psfOutImg) 

1316 

1317 # check PSF, WCS, bbox, filterLabel, photoCalib 

1318 self.assertWcsAlmostEqualOverBBox(science.wcs, output.scoreExposure.wcs, science.getBBox()) 

1319 self.assertEqual(science.filter, output.scoreExposure.filter) 

1320 self.assertEqual(science.photoCalib, output.scoreExposure.photoCalib) 

1321 _run_and_check_images(doDecorrelation=True) 

1322 _run_and_check_images(doDecorrelation=False) 

1323 

1324 

1325def setup_module(module): 

1326 lsst.utils.tests.init() 

1327 

1328 

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

1330 pass 

1331 

1332 

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

1334 lsst.utils.tests.init() 

1335 unittest.main()