Coverage for tests/test_subtractTask.py: 7%

787 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 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, InsufficientKernelSourcesError 

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, fluxField="truth_instFlux", errField="truth_instFluxErr", **kwargs): 

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

45 

46 Parameters 

47 ---------- 

48 fluxField : `str`, optional 

49 Name of the flux field in the source catalog. 

50 errField : `str`, optional 

51 Name of the flux error field in the source catalog. 

52 **kwargs 

53 Any additional config parameters to set. 

54 

55 Returns 

56 ------- 

57 `lsst.pipe.base.PipelineTask` 

58 The configured Task to use for detection and measurement. 

59 """ 

60 config = self.subtractTask.ConfigClass() 

61 config.doSubtractBackground = False 

62 config.sourceSelector.signalToNoise.fluxField = fluxField 

63 config.sourceSelector.signalToNoise.errField = errField 

64 config.sourceSelector.doUnresolved = True 

65 config.sourceSelector.doIsolated = True 

66 config.sourceSelector.doRequirePrimary = True 

67 config.sourceSelector.doFlags = True 

68 config.sourceSelector.doSignalToNoise = True 

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

70 config.update(**kwargs) 

71 

72 return self.subtractTask(config=config) 

73 

74 

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

76 subtractTask = subtractImages.AlardLuptonSubtractTask 

77 

78 def test_allowed_config_modes(self): 

79 """Verify the allowable modes for convolution. 

80 """ 

81 config = subtractImages.AlardLuptonSubtractTask.ConfigClass() 

82 config.mode = 'auto' 

83 config.mode = 'convolveScience' 

84 config.mode = 'convolveTemplate' 

85 

86 with self.assertRaises(FieldValidationError): 

87 config.mode = 'aotu' 

88 

89 def test_mismatched_template(self): 

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

91 does not fully contain the science image. 

92 """ 

93 xSize = 200 

94 ySize = 200 

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

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

97 task = self._setup_subtraction() 

98 with self.assertRaises(AssertionError): 

99 task.run(template, science, sources) 

100 

101 def test_mismatched_filter(self): 

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

103 different bands. 

104 """ 

105 xSize = 200 

106 ySize = 200 

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

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

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

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

111 task = self._setup_subtraction() 

112 with self.assertRaises(AssertionError): 

113 task.run(template, science, sources) 

114 

115 def test_incomplete_template_coverage(self): 

116 noiseLevel = 1. 

117 border = 20 

118 xSize = 400 

119 ySize = 400 

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

121 xSize=xSize, ySize=ySize) 

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

123 templateBorderSize=border, doApplyCalibration=True, 

124 xSize=xSize, ySize=ySize) 

125 

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

127 

128 def _run_and_check_coverage(template_coverage, 

129 requiredTemplateFraction=0.1, 

130 minTemplateFractionForExpectedSuccess=0.2): 

131 template_cut = template.clone() 

132 template_height = int(science_height*template_coverage + border) 

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

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

135 task = self._setup_subtraction( 

136 requiredTemplateFraction=requiredTemplateFraction, 

137 minTemplateFractionForExpectedSuccess=minTemplateFractionForExpectedSuccess 

138 ) 

139 if template_coverage < requiredTemplateFraction: 

140 doRaise = True 

141 elif template_coverage < minTemplateFractionForExpectedSuccess: 

142 doRaise = True 

143 else: 

144 doRaise = False 

145 if doRaise: 

146 with self.assertRaises(NoWorkFound): 

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

148 else: 

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

150 _run_and_check_coverage(template_coverage=0.09) 

151 _run_and_check_coverage(template_coverage=0.19) 

152 _run_and_check_coverage(template_coverage=0.7) 

153 

154 def test_clear_template_mask(self): 

155 noiseLevel = 1. 

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

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

158 templateBorderSize=20, doApplyCalibration=True) 

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

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

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

162 mask = template.mask 

163 x0 = 50 

164 x1 = 75 

165 y0 = 150 

166 y1 = 175 

167 scienceMaskCheck = {} 

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

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

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

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

172 

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

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

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

176 if maskPlane in diffimEmptyMaskPlanes: 

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

178 elif maskPlane in task.config.preserveTemplateMask: 

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

180 else: 

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

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

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

184 diffimMask = output.difference.mask 

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

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

187 if maskPlane in diffimEmptyMaskPlanes: 

188 self.assertEqual(diffimSum, 0) 

189 else: 

190 self.assertTrue(diffimSum >= scienceSum) 

191 

192 def test_equal_images(self): 

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

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

195 """ 

196 noiseLevel = 1. 

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

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

199 templateBorderSize=20, doApplyCalibration=True) 

200 task = self._setup_subtraction() 

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

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

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

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

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

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

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

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

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

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

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

212 makeStats(), statistic=afwMath.STDEV) 

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

214 

215 def test_equal_images_missing_mask_planes(self): 

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

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

218 mask planes. 

219 """ 

220 noiseLevel = 1. 

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

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

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

224 task = self._setup_subtraction() 

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

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

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

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

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

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

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

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

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

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

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

236 makeStats(), statistic=afwMath.STDEV) 

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

238 

239 def test_psf_size(self): 

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

241 fwhmExposureBuffer and fwhmExposureGrid parameters are set. 

242 """ 

243 noiseLevel = 1. 

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

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

246 templateBorderSize=20, doApplyCalibration=True) 

247 

248 schema = afwTable.ExposureTable.makeMinimalSchema() 

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

250 exposureCatalog = afwTable.ExposureCatalog(schema) 

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

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

253 

254 record = exposureCatalog.addNew() 

255 record.setPsf(psf) 

256 record.setWcs(template.wcs) 

257 record.setD(weightKey, 1.0) 

258 record.setBBox(template.getBBox()) 

259 

260 customPsf = CustomCoaddPsf(exposureCatalog, template.wcs) 

261 template.setPsf(customPsf) 

262 

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

264 with self.assertRaises(InvalidParameterError): 

265 getPsfFwhm(template.psf, True) 

266 

267 with self.assertRaises(InvalidParameterError): 

268 getPsfFwhm(template.psf, False) 

269 

270 # Test that evaluateMeanPsfFwhm runs successfully on the template. 

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

272 

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

274 # all points in the science image. 

275 fwhm1 = getPsfFwhm(science.psf, False) 

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

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

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

279 

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

281 fwhmExposureGrid=10), 

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

283 ) 

284 

285 # Test that the image subtraction task runs successfully. 

286 task = self._setup_subtraction() 

287 

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

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

290 task.run(template, science, sources) 

291 

292 # Check that evaluateMeanPsfFwhm was called. 

293 # This tests that getPsfFwhm failed raising InvalidParameterError, 

294 # that is caught and handled appropriately. 

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

296 "Evaluting PSF on a grid of points." 

297 ) 

298 self.assertIn(logMessage, cm.output) 

299 

300 def test_auto_convolveTemplate(self): 

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

302 the template psf is the smaller. 

303 """ 

304 noiseLevel = 1. 

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

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

307 templateBorderSize=20, doApplyCalibration=True) 

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

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

310 

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

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

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

314 

315 def test_auto_convolveScience(self): 

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

317 the science psf is the smaller. 

318 """ 

319 noiseLevel = 1. 

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

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

322 templateBorderSize=20, doApplyCalibration=True) 

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

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

325 

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

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

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

329 

330 def test_science_better(self): 

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

332 with the science psf being smaller than the template. 

333 """ 

334 statsCtrl = makeStats() 

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

336 

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

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

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

340 templateBorderSize=20, doApplyCalibration=True) 

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

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

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

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

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

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

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

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

349 statsCtrlDetect) 

350 

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

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

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

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

355 statsCtrl) 

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

357 statsCtrl, statistic=afwMath.STDEV) 

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

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

360 

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

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

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

364 

365 def test_template_better(self): 

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

367 with the template psf being smaller than the science. 

368 """ 

369 statsCtrl = makeStats() 

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

371 

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

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

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

375 templateBorderSize=20, doApplyCalibration=True) 

376 task = self._setup_subtraction() 

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

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

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

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

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

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

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

384 

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

386 statsCtrlDetect) 

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

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

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

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

391 statsCtrl) 

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

393 statsCtrl, statistic=afwMath.STDEV) 

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

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

396 

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

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

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

400 

401 def test_symmetry(self): 

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

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

404 should be nearly the same. 

405 """ 

406 noiseLevel = 1. 

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

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

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

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

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

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

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

414 

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

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

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

418 

419 delta = template_better.difference.clone() 

420 delta.image -= science_better.difference.image 

421 delta.variance -= science_better.difference.variance 

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

423 

424 statsCtrl = makeStats() 

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

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

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

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

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

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

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

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

433 

434 def test_few_sources(self): 

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

436 """ 

437 xSize = 256 

438 ySize = 256 

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

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

441 task = self._setup_subtraction() 

442 sources = sources[0:1] 

443 with self.assertRaises(InsufficientKernelSourcesError): 

444 task.run(template, science, sources) 

445 

446 def test_kernel_source_selector(self): 

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

448 """ 

449 xSize = 256 

450 ySize = 256 

451 nSourcesSimulated = 20 

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

453 xSize=xSize, ySize=ySize) 

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

455 xSize=xSize, ySize=ySize, doApplyCalibration=True) 

456 

457 def _run_and_check_sources(sourcesIn, maxKernelSources=1000, minKernelSources=3, 

458 restrictKernelEdgeSources=False): 

459 sources = sourcesIn.copy(deep=True) 

460 

461 task = self._setup_subtraction(maxKernelSources=maxKernelSources, 

462 minKernelSources=minKernelSources, 

463 restrictKernelEdgeSources=restrictKernelEdgeSources, 

464 ) 

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

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

467 # the test. 

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

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

470 nSources = len(sources) 

471 # Flag a third of the sources 

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

473 if restrictKernelEdgeSources: 

474 rejectRadius = 2*task.config.makeKernel.kernel.active.kernelSize 

475 bbox = science.getBBox() 

476 bbox.grow(-rejectRadius) 

477 edgeSources = ~bbox.contains(sources.getX(), sources.getY()) 

478 sources[edgeSources][badSourceFlag] = True 

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

480 if maxKernelSources > 0: 

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

482 else: 

483 nGoodSources = nSources - nBadSources 

484 

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

486 signalToNoise = signalToNoise[~sources[badSourceFlag]] 

487 signalToNoise.sort() 

488 selectSources = task._sourceSelector(sources, science.getBBox()) 

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

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

491 signalToNoiseOut.sort() 

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

493 

494 _run_and_check_sources(sources) 

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

496 _run_and_check_sources(sources, restrictKernelEdgeSources=True) 

497 _run_and_check_sources(sources, maxKernelSources=len(sources)//3, restrictKernelEdgeSources=True) 

498 _run_and_check_sources(sources, maxKernelSources=-1) 

499 with self.assertRaises(RuntimeError): 

500 _run_and_check_sources(sources, minKernelSources=1000) 

501 

502 def test_order_equal_images(self): 

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

504 if the images are equivalent. 

505 """ 

506 noiseLevel = .1 

507 seed1 = 6 

508 seed2 = 7 

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

510 clearEdgeMask=True) 

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

512 templateBorderSize=0, doApplyCalibration=True, 

513 clearEdgeMask=True) 

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

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

516 

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

518 clearEdgeMask=True) 

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

520 templateBorderSize=0, doApplyCalibration=True, 

521 clearEdgeMask=True) 

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

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

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

525 results_convolveScience.difference.getBBox()) 

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

527 diff1 -= template1.maskedImage[bbox] 

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

529 diff2 -= template2.maskedImage[bbox] 

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

531 diff1.image.array, 

532 atol=noiseLevel*5.) 

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

534 diff2.image.array, 

535 atol=noiseLevel*5.) 

536 diffErr = noiseLevel*2 

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

538 results_convolveScience.difference[bbox].maskedImage, 

539 atol=diffErr*5.) 

540 

541 def test_background_subtraction(self): 

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

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

544 

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

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

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

548 stay to make sure it continues functioning as intended. 

549 """ 

550 noiseLevel = 1. 

551 xSize = 512 

552 ySize = 512 

553 x0 = 123 

554 y0 = 456 

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

556 templateBorderSize=20, 

557 xSize=xSize, ySize=ySize, x0=x0, y0=y0, 

558 doApplyCalibration=True) 

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

560 

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

562 background_model = afwMath.Chebyshev1Function2D(params, bbox2D) 

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

564 background=background_model, 

565 xSize=xSize, ySize=ySize, x0=x0, y0=y0) 

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

567 # Modifying the config of a subtask is messy. 

568 config = subtractImages.AlardLuptonSubtractTask.ConfigClass() 

569 

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

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

572 config.doSubtractBackground = True 

573 

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

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

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

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

578 statsCtrl = makeStats() 

579 

580 def _run_and_check_images(config, statsCtrl, mode): 

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

582 """ 

583 config.mode = mode 

584 task = subtractImages.AlardLuptonSubtractTask(config=config) 

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

586 

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

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

589 

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

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

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

593 

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

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

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

597 statsCtrl, statistic=afwMath.STDEV) 

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

599 

600 _run_and_check_images(config, statsCtrl, "convolveTemplate") 

601 _run_and_check_images(config, statsCtrl, "convolveScience") 

602 

603 def test_scale_variance_convolve_template(self): 

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

605 """ 

606 scienceNoiseLevel = 4. 

607 templateNoiseLevel = 2. 

608 scaleFactor = 1.345 

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

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

611 

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

613 doDecorrelation, doScaleVariance, scaleFactor=1.): 

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

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

616 """ 

617 

618 task = self._setup_subtraction(doDecorrelation=doDecorrelation, 

619 doScaleVariance=doScaleVariance, 

620 ) 

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

622 if doScaleVariance: 

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

624 scaleFactor, atol=0.05) 

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

626 scaleFactor, atol=0.05) 

627 

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

629 if doDecorrelation: 

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

631 else: 

632 templateNoise = computeRobustStatistics(output.matchedTemplate.variance, 

633 output.matchedTemplate.mask, 

634 statsCtrl) 

635 

636 if doScaleVariance: 

637 templateNoise *= scaleFactor 

638 scienceNoise *= scaleFactor 

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

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

641 

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

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

644 templateBorderSize=20, doApplyCalibration=True) 

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

646 # when the template and science variance planes are correct 

647 _run_and_check_images(science, template, sources, statsCtrl, 

648 doDecorrelation=True, doScaleVariance=True) 

649 _run_and_check_images(science, template, sources, statsCtrl, 

650 doDecorrelation=True, doScaleVariance=False) 

651 _run_and_check_images(science, template, sources, statsCtrl, 

652 doDecorrelation=False, doScaleVariance=True) 

653 _run_and_check_images(science, template, sources, statsCtrl, 

654 doDecorrelation=False, doScaleVariance=False) 

655 

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

657 # when the template variance plane is incorrect 

658 template.variance.array /= scaleFactor 

659 science.variance.array /= scaleFactor 

660 _run_and_check_images(science, template, sources, statsCtrl, 

661 doDecorrelation=True, doScaleVariance=True, scaleFactor=scaleFactor) 

662 _run_and_check_images(science, template, sources, statsCtrl, 

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

664 _run_and_check_images(science, template, sources, statsCtrl, 

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

666 _run_and_check_images(science, template, sources, statsCtrl, 

667 doDecorrelation=False, doScaleVariance=False, scaleFactor=scaleFactor) 

668 

669 def test_scale_variance_convolve_science(self): 

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

671 """ 

672 scienceNoiseLevel = 4. 

673 templateNoiseLevel = 2. 

674 scaleFactor = 1.345 

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

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

677 

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

679 doDecorrelation, doScaleVariance, scaleFactor=1.): 

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

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

682 """ 

683 

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

685 doDecorrelation=doDecorrelation, 

686 doScaleVariance=doScaleVariance, 

687 restrictKernelEdgeSources=False, 

688 ) 

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

690 if doScaleVariance: 

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

692 scaleFactor, atol=0.05) 

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

694 scaleFactor, atol=0.05) 

695 

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

697 if doDecorrelation: 

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

699 else: 

700 scienceNoise = computeRobustStatistics(output.matchedScience.variance, 

701 output.matchedScience.mask, 

702 statsCtrl) 

703 

704 if doScaleVariance: 

705 templateNoise *= scaleFactor 

706 scienceNoise *= scaleFactor 

707 

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

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

710 

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

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

713 templateBorderSize=20, doApplyCalibration=True) 

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

715 # when the template and science variance planes are correct 

716 _run_and_check_images(science, template, sources, statsCtrl, 

717 doDecorrelation=True, doScaleVariance=True) 

718 _run_and_check_images(science, template, sources, statsCtrl, 

719 doDecorrelation=True, doScaleVariance=False) 

720 _run_and_check_images(science, template, sources, statsCtrl, 

721 doDecorrelation=False, doScaleVariance=True) 

722 _run_and_check_images(science, template, sources, statsCtrl, 

723 doDecorrelation=False, doScaleVariance=False) 

724 

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

726 # when the template and science variance planes are incorrect 

727 science.variance.array /= scaleFactor 

728 template.variance.array /= scaleFactor 

729 _run_and_check_images(science, template, sources, statsCtrl, 

730 doDecorrelation=True, doScaleVariance=True, scaleFactor=scaleFactor) 

731 _run_and_check_images(science, template, sources, statsCtrl, 

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

733 _run_and_check_images(science, template, sources, statsCtrl, 

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

735 _run_and_check_images(science, template, sources, statsCtrl, 

736 doDecorrelation=False, doScaleVariance=False, scaleFactor=scaleFactor) 

737 

738 def test_exposure_properties_convolve_template(self): 

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

740 when the template is convolved. 

741 """ 

742 noiseLevel = 1. 

743 seed = 37 

744 rng = np.random.RandomState(seed) 

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

746 psf = science.psf 

747 psfAvgPos = psf.getAveragePosition() 

748 psfSize = getPsfFwhm(science.psf) 

749 psfImg = psf.computeKernelImage(psfAvgPos) 

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

751 templateBorderSize=20, doApplyCalibration=True) 

752 

753 # Generate a random aperture correction map 

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

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

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

757 science.info.setApCorrMap(apCorrMap) 

758 

759 def _run_and_check_images(doDecorrelation): 

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

761 """ 

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

763 doDecorrelation=doDecorrelation, 

764 ) 

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

766 psfOut = output.difference.psf 

767 psfAvgPos = psfOut.getAveragePosition() 

768 if doDecorrelation: 

769 # Decorrelation requires recalculating the PSF, 

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

771 psfOutSize = getPsfFwhm(science.psf) 

772 self.assertFloatsAlmostEqual(psfSize, psfOutSize) 

773 else: 

774 psfOutImg = psfOut.computeKernelImage(psfAvgPos) 

775 self.assertImagesAlmostEqual(psfImg, psfOutImg) 

776 

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

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

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

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

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

782 _run_and_check_images(doDecorrelation=True) 

783 _run_and_check_images(doDecorrelation=False) 

784 

785 def test_exposure_properties_convolve_science(self): 

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

787 when the science image is convolved. 

788 """ 

789 noiseLevel = 1. 

790 seed = 37 

791 rng = np.random.RandomState(seed) 

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

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

794 templateBorderSize=20, doApplyCalibration=True) 

795 psf = template.psf 

796 psfAvgPos = psf.getAveragePosition() 

797 psfSize = getPsfFwhm(template.psf) 

798 psfImg = psf.computeKernelImage(psfAvgPos) 

799 

800 # Generate a random aperture correction map 

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

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

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

804 science.info.setApCorrMap(apCorrMap) 

805 

806 def _run_and_check_images(doDecorrelation): 

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

808 """ 

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

810 doDecorrelation=doDecorrelation, 

811 ) 

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

813 if doDecorrelation: 

814 # Decorrelation requires recalculating the PSF, 

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

816 psfOutSize = getPsfFwhm(template.psf) 

817 self.assertFloatsAlmostEqual(psfSize, psfOutSize) 

818 else: 

819 psfOut = output.difference.psf 

820 psfAvgPos = psfOut.getAveragePosition() 

821 psfOutImg = psfOut.computeKernelImage(psfAvgPos) 

822 self.assertImagesAlmostEqual(psfImg, psfOutImg) 

823 

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

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

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

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

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

829 

830 _run_and_check_images(doDecorrelation=True) 

831 _run_and_check_images(doDecorrelation=False) 

832 

833 def _compare_apCorrMaps(self, a, b): 

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

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

836 

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

838 

839 Parameters 

840 ---------- 

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

842 The two aperture correction maps to compare. 

843 """ 

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

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

846 value2 = b.get(name) 

847 self.assertIsNotNone(value2) 

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

849 self.assertFloatsAlmostEqual( 

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

851 

852 def test_fake_mask_plane_propagation(self): 

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

854 This is testing method called updateMasks 

855 """ 

856 xSize = 200 

857 ySize = 200 

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

859 science_fake_img, science_fake_sources = makeTestImage( 

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

861 ) 

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

863 tmplt_fake_img, tmplt_fake_sources = makeTestImage( 

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

865 ) 

866 # created fakes and added them to the images 

867 science.image.array += science_fake_img.image.array 

868 template.image.array += tmplt_fake_img.image.array 

869 

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

871 # adding mask planes to both science and template images 

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

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

874 

875 for a_science_source in science_fake_sources: 

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

877 bbox = lsst.geom.Box2I( 

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

879 ) 

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

881 

882 for a_template_source in tmplt_fake_sources: 

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

884 bbox = lsst.geom.Box2I( 

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

886 lsst.geom.Extent2I(3, 3) 

887 ) 

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

889 

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

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

892 

893 task = self._setup_subtraction() 

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

895 

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

897 diff_mask = subtraction.difference.mask 

898 

899 # science mask should be now in INJECTED 

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

901 

902 # template mask should be now in INJECTED_TEMPLATE 

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

904 

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

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

907 

908 def test_metadata_metrics(self): 

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

910 that the difference image limiting magnitude is calculated correctly, 

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

912 """ 

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

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

915 templateBorderSize=20) 

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

917 templateBorderSize=20) 

918 

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

920 config = measAlg.SkyObjectsTask.ConfigClass() 

921 config.nSources = 3 

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

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

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

925 sources = sources.copy(deep=True) 

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

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

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

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

930 

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

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

933 

934 subtractTask_good = self._setup_subtraction() 

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

936 subtractTask_bad = self._setup_subtraction() 

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

938 

939 # Test that the diffim limiting magnitudes are computed correctly 

940 maglim_science = subtractTask_good._calculateMagLim(science) 

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

942 maglim_template_good = subtractTask_good._calculateMagLim(template_good) 

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

944 maglim_template_bad = subtractTask_bad._calculateMagLim(template_bad) 

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

946 

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

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

949 

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

951 maglim_good, atol=1e-6) 

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

953 maglim_bad, atol=1e-6) 

954 

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

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

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

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

959 template_offimage, _ = makeTestImage() 

960 schema = afwTable.ExposureTable.makeMinimalSchema() 

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

962 exposureCatalog = afwTable.ExposureCatalog(schema) 

963 record = exposureCatalog.addNew() 

964 record.setD(weightKey, 1.0) 

965 record.setBBox(template_offimage.getBBox()) 

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

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

968 record.setPsf(psf) 

969 record.setWcs(template_offimage.wcs) 

970 custom_offimage_psf = CustomCoaddPsf(exposureCatalog, template_offimage.wcs) 

971 template_offimage.setPsf(custom_offimage_psf) 

972 

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

974 subtractTask_offimage = self._setup_subtraction() 

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

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

977 # limiting magnitude. 

978 maglim_template_offimage = subtractTask_offimage._calculateMagLim(template_offimage) 

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

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

981 # magnitude is calculated correctly. 

982 maglim_template_offimage = 28.3173123103493 

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

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

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

986 

987 # Test that several other expected metadata metrics exist 

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

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

990 

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

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

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

994 

995 

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

997 subtractTask = subtractImages.AlardLuptonPreconvolveSubtractTask 

998 

999 def test_mismatched_template(self): 

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

1001 does not fully contain the science image. 

1002 """ 

1003 xSize = 200 

1004 ySize = 200 

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

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

1007 task = self._setup_subtraction() 

1008 with self.assertRaises(AssertionError): 

1009 task.run(template, science, sources) 

1010 

1011 def test_equal_images(self): 

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

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

1014 """ 

1015 noiseLevel = 1. 

1016 xSize = 400 

1017 ySize = 400 

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

1019 xSize=xSize, ySize=ySize) 

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

1021 templateBorderSize=20, doApplyCalibration=True, 

1022 xSize=xSize, ySize=ySize) 

1023 task = self._setup_subtraction() 

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

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

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

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

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

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

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

1031 scoreMean = computeRobustStatistics(output.scoreExposure.image, 

1032 output.scoreExposure.mask, 

1033 statsCtrl) 

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

1035 nea = computePSFNoiseEquivalentArea(science.psf) 

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

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

1038 statsCtrl=statsCtrl, statistic=afwMath.STDEV) 

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

1040 

1041 def test_incomplete_template_coverage(self): 

1042 noiseLevel = 1. 

1043 border = 20 

1044 xSize = 400 

1045 ySize = 400 

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

1047 xSize=xSize, ySize=ySize) 

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

1049 templateBorderSize=border, doApplyCalibration=True, 

1050 xSize=xSize, ySize=ySize) 

1051 

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

1053 

1054 def _run_and_check_coverage(template_coverage): 

1055 template_cut = template.clone() 

1056 template_height = int(science_height*template_coverage + border) 

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

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

1059 task = self._setup_subtraction() 

1060 if template_coverage < task.config.requiredTemplateFraction: 

1061 doRaise = True 

1062 elif template_coverage < task.config.minTemplateFractionForExpectedSuccess: 

1063 doRaise = True 

1064 else: 

1065 doRaise = False 

1066 if doRaise: 

1067 with self.assertRaises(NoWorkFound): 

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

1069 else: 

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

1071 _run_and_check_coverage(template_coverage=0.09) 

1072 _run_and_check_coverage(template_coverage=0.19) 

1073 _run_and_check_coverage(template_coverage=.7) 

1074 

1075 def test_clear_template_mask(self): 

1076 noiseLevel = 1. 

1077 xSize = 400 

1078 ySize = 400 

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

1080 xSize=xSize, ySize=ySize) 

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

1082 templateBorderSize=20, doApplyCalibration=True, 

1083 xSize=xSize, ySize=ySize) 

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

1085 task = self._setup_subtraction() 

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

1087 mask = template.mask 

1088 x0 = 50 

1089 x1 = 75 

1090 y0 = 150 

1091 y1 = 175 

1092 scienceMaskCheck = {} 

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

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

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

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

1097 

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

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

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

1101 if maskPlane in diffimEmptyMaskPlanes: 

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

1103 elif maskPlane in task.config.preserveTemplateMask: 

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

1105 else: 

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

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

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

1109 diffimMask = output.scoreExposure.mask 

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

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

1112 if maskPlane in diffimEmptyMaskPlanes: 

1113 self.assertEqual(diffimSum, 0) 

1114 else: 

1115 self.assertTrue(diffimSum >= scienceSum) 

1116 

1117 def test_agnostic_template_psf(self): 

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

1119 larger or smaller than the science image PSF. 

1120 """ 

1121 noiseLevel = .3 

1122 xSize = 400 

1123 ySize = 400 

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

1125 noiseSeed=6, templateBorderSize=0, 

1126 xSize=xSize, ySize=ySize) 

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

1128 noiseSeed=7, doApplyCalibration=True, 

1129 xSize=xSize, ySize=ySize) 

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

1131 noiseSeed=8, doApplyCalibration=True, 

1132 xSize=xSize, ySize=ySize) 

1133 task = self._setup_subtraction() 

1134 

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

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

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

1138 

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

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

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

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

1143 

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

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

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

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

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

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

1150 statistic=afwMath.STDEV) 

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

1152 nea = computePSFNoiseEquivalentArea(science.psf) 

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

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

1155 

1156 def test_few_sources(self): 

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

1158 """ 

1159 xSize = 256 

1160 ySize = 256 

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

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

1163 task = self._setup_subtraction() 

1164 sources = sources[0:1] 

1165 with self.assertRaises(InsufficientKernelSourcesError): 

1166 task.run(template, science, sources) 

1167 

1168 def test_background_subtraction(self): 

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

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

1171 """ 

1172 noiseLevel = 1. 

1173 xSize = 512 

1174 ySize = 512 

1175 x0 = 123 

1176 y0 = 456 

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

1178 templateBorderSize=20, 

1179 xSize=xSize, ySize=ySize, x0=x0, y0=y0, 

1180 doApplyCalibration=True) 

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

1182 

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

1184 background_model = afwMath.Chebyshev1Function2D(params, bbox2D) 

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

1186 background=background_model, 

1187 xSize=xSize, ySize=ySize, x0=x0, y0=y0) 

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

1189 # Modifying the config of a subtask is messy. 

1190 config = subtractImages.AlardLuptonPreconvolveSubtractTask.ConfigClass() 

1191 

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

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

1194 config.doSubtractBackground = True 

1195 

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

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

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

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

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

1201 

1202 task = subtractImages.AlardLuptonPreconvolveSubtractTask(config=config) 

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

1204 

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

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

1207 

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

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

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

1211 

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

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

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

1215 statsCtrl, statistic=afwMath.STDEV) 

1216 # get the img psf Noise Equivalent Area value 

1217 nea = computePSFNoiseEquivalentArea(science.psf) 

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

1219 

1220 def test_scale_variance(self): 

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

1222 """ 

1223 scienceNoiseLevel = 4. 

1224 templateNoiseLevel = 2. 

1225 scaleFactor = 1.345 

1226 xSize = 400 

1227 ySize = 400 

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

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

1230 

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

1232 doDecorrelation, doScaleVariance, scaleFactor=1.): 

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

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

1235 """ 

1236 

1237 task = self._setup_subtraction(doDecorrelation=doDecorrelation, 

1238 doScaleVariance=doScaleVariance, 

1239 ) 

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

1241 if doScaleVariance: 

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

1243 scaleFactor, atol=0.05) 

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

1245 scaleFactor, atol=0.05) 

1246 

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

1248 # get the img psf Noise Equivalent Area value 

1249 nea = computePSFNoiseEquivalentArea(science.psf) 

1250 scienceNoise /= nea 

1251 if doDecorrelation: 

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

1253 templateNoise /= nea 

1254 else: 

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

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

1257 templateNoise = computeRobustStatistics(output.matchedTemplate.variance, 

1258 output.matchedTemplate.mask, 

1259 statsCtrl) 

1260 if doScaleVariance: 

1261 templateNoise *= scaleFactor 

1262 scienceNoise *= scaleFactor 

1263 varMean = computeRobustStatistics(output.scoreExposure.variance, 

1264 output.scoreExposure.mask, 

1265 statsCtrl) 

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

1267 

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

1269 xSize=xSize, ySize=ySize) 

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

1271 templateBorderSize=20, doApplyCalibration=True, 

1272 xSize=xSize, ySize=ySize) 

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

1274 # when the template and science variance planes are correct 

1275 _run_and_check_images(science, template, sources, statsCtrl, 

1276 doDecorrelation=True, doScaleVariance=True) 

1277 _run_and_check_images(science, template, sources, statsCtrl, 

1278 doDecorrelation=True, doScaleVariance=False) 

1279 _run_and_check_images(science, template, sources, statsCtrl, 

1280 doDecorrelation=False, doScaleVariance=True) 

1281 _run_and_check_images(science, template, sources, statsCtrl, 

1282 doDecorrelation=False, doScaleVariance=False) 

1283 

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

1285 # when the template variance plane is incorrect 

1286 template.variance.array /= scaleFactor 

1287 science.variance.array /= scaleFactor 

1288 _run_and_check_images(science, template, sources, statsCtrl, 

1289 doDecorrelation=True, doScaleVariance=True, scaleFactor=scaleFactor) 

1290 _run_and_check_images(science, template, sources, statsCtrl, 

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

1292 _run_and_check_images(science, template, sources, statsCtrl, 

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

1294 _run_and_check_images(science, template, sources, statsCtrl, 

1295 doDecorrelation=False, doScaleVariance=False, scaleFactor=scaleFactor) 

1296 

1297 def test_exposure_properties(self): 

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

1299 with the Score image. 

1300 """ 

1301 noiseLevel = 1. 

1302 xSize = 400 

1303 ySize = 400 

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

1305 xSize=xSize, ySize=ySize) 

1306 psf = science.psf 

1307 psfAvgPos = psf.getAveragePosition() 

1308 psfSize = getPsfFwhm(science.psf) 

1309 psfImg = psf.computeKernelImage(psfAvgPos) 

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

1311 templateBorderSize=20, doApplyCalibration=True, 

1312 xSize=xSize, ySize=ySize) 

1313 

1314 def _run_and_check_images(doDecorrelation): 

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

1316 """ 

1317 task = self._setup_subtraction(doDecorrelation=doDecorrelation) 

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

1319 psfOut = output.scoreExposure.psf 

1320 psfAvgPos = psfOut.getAveragePosition() 

1321 if doDecorrelation: 

1322 # Decorrelation requires recalculating the PSF, 

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

1324 psfOutSize = getPsfFwhm(science.psf) 

1325 self.assertFloatsAlmostEqual(psfSize, psfOutSize) 

1326 else: 

1327 psfOutImg = psfOut.computeKernelImage(psfAvgPos) 

1328 self.assertImagesAlmostEqual(psfImg, psfOutImg) 

1329 

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

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

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

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

1334 _run_and_check_images(doDecorrelation=True) 

1335 _run_and_check_images(doDecorrelation=False) 

1336 

1337 

1338class SimplifiedSubtractTest(AlardLuptonSubtractTestBase, lsst.utils.tests.TestCase): 

1339 subtractTask = subtractImages.SimplifiedSubtractTask 

1340 

1341 def test_runSimplifiedTaskWithExistingKernel(self): 

1342 """Test that the simplified task produces the same output as 

1343 `AlardLuptonSubtractTask` if it uses the AL kernel. 

1344 """ 

1345 noiseLevel = 1. 

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

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

1348 templateBorderSize=20, doApplyCalibration=True) 

1349 alTask = AlardLuptonSubtractTest._setup_subtraction(AlardLuptonSubtractTest()) 

1350 task = self._setup_subtraction(useExistingKernel=True) 

1351 

1352 alResults = alTask.run(template.clone(), science.clone(), sources) 

1353 results = task.run(template.clone(), science.clone(), 

1354 inputPsfMatchingKernel=alResults.psfMatchingKernel) 

1355 

1356 self.assertMaskedImagesEqual(alResults.difference, results.difference) 

1357 

1358 def test_runSimplifiedTaskWithSourceDetection(self): 

1359 """Test that the simplified task with source detection produces 

1360 reasonable output. 

1361 """ 

1362 noiseLevel = 1. 

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

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

1365 templateBorderSize=20, doApplyCalibration=True) 

1366 task = self._setup_subtraction(useExistingKernel=False, 

1367 fluxField="base_PsfFlux_instFlux", 

1368 errField="base_PsfFlux_instFluxErr", 

1369 ) 

1370 

1371 output = task.run(template, science) 

1372 

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

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

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

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

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

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

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

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

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

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

1383 makeStats(), statistic=afwMath.STDEV) 

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

1385 

1386 

1387def setup_module(module): 

1388 lsst.utils.tests.init() 

1389 

1390 

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

1392 pass 

1393 

1394 

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

1396 lsst.utils.tests.init() 

1397 unittest.main()