Coverage for tests/test_getTemplate.py: 96%

695 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-19 01:38 -0800

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 collections 

23import itertools 

24import unittest 

25import unittest.mock 

26 

27import astropy.units as u 

28from astropy.stats import gaussian_sigma_to_fwhm 

29import astshim 

30import numpy as np 

31 

32import lsst.afw.cameraGeom.testUtils 

33import lsst.afw.detection 

34import lsst.afw.geom 

35import lsst.afw.image 

36import lsst.afw.math 

37import lsst.afw.table 

38from lsst.daf.base import DateTime 

39from lsst.daf.butler import DataCoordinate, DatasetRef, DatasetType, DimensionUniverse 

40import lsst.geom 

41import lsst.images 

42import lsst.images.psfs 

43from lsst.images.tests import compare_masked_image_to_legacy 

44import lsst.ip.diffim 

45import lsst.meas.algorithms 

46import lsst.meas.base.tests 

47import lsst.pex.exceptions 

48import lsst.pipe.base as pipeBase 

49import lsst.pipe.base.testUtils 

50import lsst.skymap 

51import lsst.utils.tests 

52 

53from utils import generate_data_id, makeTestExposureRecord 

54 

55# Change this to True, `setup display_ds9`, and open ds9 (or use another afw 

56# display backend) to show the tract/patch layouts on the image. 

57debug = False 

58if debug: 58 ↛ 59line 58 didn't jump to line 59 because the condition on line 58 was never true

59 import lsst.afw.display 

60 display = lsst.afw.display.Display() 

61 display.frame = 1 

62 

63# Sum of squared warping kernel values along one axis, with the kernel 

64# normalized to unit sum at each sub-pixel phase, averaged over phase. 

65KERNEL_SUM_SQ_1D = { 

66 "bilinear": 2/3, 

67 "lanczos3": 0.8933699084, 

68 "lanczos4": 0.9141249535, 

69 "lanczos5": 0.9342245513, 

70} 

71 

72 

73def _showTemplate(box, template): 

74 """Show the corners of the template we made in this test.""" 

75 for point in box.getCorners(): 

76 display.dot("+", point.x, point.y, ctype="orange", size=40) 

77 display.frame = 2 

78 display.image(template, "warped template") 

79 display.frame = 3 

80 display.image(template.variance, "warped variance") 

81 

82 

83class GetTemplateTaskTestCase(lsst.utils.tests.TestCase): 

84 """Test that GetTemplateTask works on both one tract and multiple tract 

85 input coadd exposures. 

86 

87 Makes a synthetic exposure large enough to fit four small tracts with 2x2 

88 (300x300 pixel) patches each, extracts pixels for those patches by warping, 

89 and tests GetTemplateTask's output against boxes that overlap various 

90 combinations of one or multiple tracts. 

91 """ 

92 scale = 0.2 # arcsec/pixel 

93 # Use 5th order to minimize artifacts on the templates. 

94 coaddWarpKernel = "lanczos5" 

95 

96 @classmethod 

97 def setUpClass(cls): 

98 # Warping the patches is the slowest part of every test, so it is done 

99 # once. Tests must not modify the exposure; the patch handles return 

100 # copies, and setUp gives each test its own lists of them. 

101 cls.skymap = cls._makeSkymap() 

102 cls.patches = collections.defaultdict(list) 

103 cls.dataIds = collections.defaultdict(list) 

104 cls.exposure = cls._makeExposure() 

105 

106 if debug: 106 ↛ 107line 106 didn't jump to line 107 because the condition on line 106 was never true

107 display.image(cls.exposure, "base exposure") 

108 

109 for tract_id in range(4): 

110 tract = cls.skymap.generateTract(tract_id) 

111 cls._makePatches(tract) 

112 

113 @classmethod 

114 def tearDownClass(cls): 

115 del cls.skymap, cls.patches, cls.dataIds, cls.exposure 

116 

117 def setUp(self): 

118 cls = type(self) 

119 self.patches = collections.defaultdict(list, {k: list(v) for k, v in cls.patches.items()}) 

120 self.dataIds = collections.defaultdict(list, {k: list(v) for k, v in cls.dataIds.items()}) 

121 self.coaddRefs = {} 

122 self.varianceBox = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(180, 180)) 

123 

124 @classmethod 

125 def _makeSkymap(cls): 

126 """Make a Skymap with 4 tracts with 4 patches each. 

127 """ 

128 tractScale = 0.02 # degrees 

129 # On-sky coordinates of the tract centers. 

130 coords = [(0, 0), 

131 (0, tractScale), 

132 (tractScale, 0), 

133 (tractScale, tractScale), 

134 ] 

135 config = lsst.skymap.DiscreteSkyMap.ConfigClass() 

136 config.raList = [c[0] for c in coords] 

137 config.decList = [c[1] for c in coords] 

138 # Half the tract center step size, to keep the tract overlap small. 

139 config.radiusList = [tractScale/2 for c in coords] 

140 config.projection = "TAN" 

141 config.pixelScale = cls.scale 

142 config.tractOverlap = 0.0005 

143 config.tractBuilder = "legacy" 

144 config.tractBuilder["legacy"].patchInnerDimensions = (300, 300) 

145 config.tractBuilder["legacy"].patchBorder = 10 

146 return lsst.skymap.DiscreteSkyMap(config=config) 

147 

148 @classmethod 

149 def _makeExposure(cls): 

150 """Create a large image to break up into tracts and patches. 

151 

152 The image will have a source every 100 pixels in x and y, and a WCS 

153 that results in the tracts all fitting in the image, with tract=0 

154 in the lower left, tract=1 to the right, tract=2 above, and tract=3 

155 to the upper right. 

156 """ 

157 box = lsst.geom.Box2I(lsst.geom.Point2I(-200, -200), lsst.geom.Point2I(800, 800)) 

158 # This WCS was constructed so that tract 0 mostly fills the lower left 

159 # quadrant of the image, and the other tracts fill the rest; slight 

160 # extra rotation as a check on the final warp layout, scaled by 5% 

161 # from the patch pixel scale. 

162 cd_matrix = lsst.afw.geom.makeCdMatrix(1.05*cls.scale*lsst.geom.arcseconds, 93*lsst.geom.degrees) 

163 wcs = lsst.afw.geom.makeSkyWcs(lsst.geom.Point2D(120, 150), 

164 lsst.geom.SpherePoint(0, 0, lsst.geom.radians), 

165 cd_matrix) 

166 dataset = lsst.meas.base.tests.TestDataset(box, wcs=wcs) 

167 for x, y in itertools.product(np.arange(0, 500, 100), np.arange(0, 500, 100)): 

168 dataset.addSource(1e5, lsst.geom.Point2D(x, y)) 

169 exposure, _ = dataset.realize(2, dataset.makeMinimalSchema()) 

170 exposure.setFilter(lsst.afw.image.FilterLabel("a", "a_test")) 

171 return exposure 

172 

173 @classmethod 

174 def _makePatches(cls, tract): 

175 """Populate the patches and dataId dicts, keyed on tract id, with the 

176 warps of the main exposure and minimal dataIds, respectively. 

177 """ 

178 if debug: 178 ↛ 179line 178 didn't jump to line 179 because the condition on line 178 was never true

179 color = ['red', 'green', 'cyan', 'yellow'][tract.tract_id] 

180 point = cls.exposure.wcs.skyToPixel(tract.ctr_coord) 

181 # Show the tract center, colored by tract id. 

182 display.dot("x", point.x, point.y, ctype=color, size=30) 

183 

184 config = lsst.afw.math.Warper.ConfigClass() 

185 config.warpingKernelName = cls.coaddWarpKernel 

186 warper = lsst.afw.math.Warper.fromConfig(config) 

187 for patchId in range(tract.num_patches.x*tract.num_patches.y): 

188 patch = tract.getPatchInfo(patchId) 

189 box = patch.getOuterBBox() 

190 

191 if debug: 191 ↛ 193line 191 didn't jump to line 193 because the condition on line 191 was never true

192 # Show the patch corners as patch ids, colored by tract id. 

193 points = cls.exposure.wcs.skyToPixel(patch.wcs.pixelToSky([lsst.geom.Point2D(x) 

194 for x in box.getCorners()])) 

195 for p in points: 

196 display.dot(patchId, p.x, p.y, ctype=color) 

197 

198 # This is mostly taken from drp_tasks makePsfMatchedWarp, but 

199 # ip_diffim cannot depend on drp_tasks. 

200 xyTransform = lsst.afw.geom.makeWcsPairTransform(cls.exposure.wcs, patch.wcs) 

201 warpedPsf = lsst.meas.algorithms.WarpedPsf(cls.exposure.psf, xyTransform) 

202 warped = warper.warpExposure(patch.wcs, cls.exposure, destBBox=box) 

203 warped.setPsf(warpedPsf) 

204 

205 warped.getInfo().setCoaddInputs( 

206 cls._makeCoaddInputs([(cls.exposure.wcs, cls.exposure.getBBox())])) 

207 dataRef = pipeBase.InMemoryDatasetHandle( 

208 warped, 

209 storageClass="ExposureF", 

210 copy=True, 

211 dataId=generate_data_id( 

212 tract=tract, 

213 patch=patch, 

214 ) 

215 ) 

216 cls.patches[tract.tract_id].append(dataRef) 

217 dataCoordinate = DataCoordinate.standardize({"tract": tract.tract_id, 

218 "patch": patchId, 

219 "band": "a", 

220 "skymap": "skymap"}, 

221 universe=DimensionUniverse()) 

222 cls.dataIds[tract.tract_id].append(dataCoordinate) 

223 

224 def _checkMetadata(self, template, config, box, wcs, nPsfs): 

225 """Check that the various metadata components were set correctly. 

226 """ 

227 expectedBox = lsst.geom.Box2I(box) 

228 expectedBox.grow(config.templateBorderSize) 

229 self.assertEqual(template.getBBox(), expectedBox) 

230 # WCS should match our exposure, not any of the coadd tracts. 

231 for tract in self.patches: 

232 self.assertNotEqual(template.wcs, self.patches[tract][0].get().wcs) 

233 self.assertEqual(template.wcs, self.exposure.wcs) 

234 # The template pixels are calibrated to nJy. 

235 self.assertEqual(template.photoCalib, lsst.afw.image.PhotoCalib(1.0)) 

236 self.assertEqual(template.getXY0(), expectedBox.getMin()) 

237 self.assertEqual(template.filter.bandLabel, "a") 

238 self.assertEqual(template.filter.physicalLabel, "a_test") 

239 # The template PSF is a Gaussian with the width of the CoaddPsf of 

240 # its inputs. 

241 self.assertIsInstance(template.psf, lsst.afw.detection.GaussianPsf) 

242 coaddPsf = self._makeCoaddPsf(template, config) 

243 self.assertEqual(coaddPsf.getComponentCount(), nPsfs) 

244 position = coaddPsf.getAveragePosition() 

245 self.assertFloatsAlmostEqual(template.psf.getSigma(), 

246 coaddPsf.computeShape(position).getTraceRadius()) 

247 self.assertTrue(template.getInfo().hasCoaddInputs()) 

248 self.assertEqual(len(template.getInfo().getCoaddInputs().ccds), nPsfs) 

249 

250 def _makeConfig(self): 

251 """Make a GetTemplateTask config whose coaddWarpKernel is the kernel 

252 the test patches were made with. 

253 """ 

254 config = lsst.ip.diffim.GetTemplateTask.ConfigClass() 

255 config.coaddWarpKernel = self.coaddWarpKernel 

256 return config 

257 

258 def _makeCoaddPsf(self, template, config): 

259 """Return the CoaddPsf that ``run`` approximated with a Gaussian, 

260 rebuilt from the coadd inputs recorded on the template. 

261 """ 

262 task = lsst.ip.diffim.GetTemplateTask(config=config) 

263 return task._makePsf(template, template.getInfo().getCoaddInputs().ccds, template.wcs) 

264 

265 def _checkPixels(self, template, config, box): 

266 """Check that the pixel values in the template are close to the 

267 original image, calibrated to nJy. 

268 """ 

269 # All pixels should have real values! 

270 expectedBox = lsst.geom.Box2I(box) 

271 expectedBox.grow(config.templateBorderSize) 

272 calibration = self.exposure.photoCalib.getCalibrationMean() 

273 expected = self.exposure.photoCalib.calibrateImage(self.exposure[expectedBox].maskedImage) 

274 

275 if debug: 275 ↛ 276line 275 didn't jump to line 276 because the condition on line 275 was never true

276 _showTemplate(expectedBox, template) 

277 

278 # Check that we fully filled the template from the patches. 

279 self.assertTrue(np.all(np.isfinite(template.image.array))) 

280 # Because of the scale changes, there will be some ringing in the 

281 # difference between the template and the original image; pick 

282 # tolerances large enough to account for that. 

283 self.assertImagesAlmostEqual(template.image, expected.image, rtol=.1, atol=4*calibration) 

284 # Variance plane ==4 in the original image (realize() takes a noise 

285 # sigma). Warping sets the level from the pixel areas and the two 

286 # warping kernels, which `_correctVariance` corrects. A per-pixel 

287 # ripple that no scalar correction can remove remains on top of that, 

288 # so check the level tightly and allow for the ripple around it. 

289 variance = template.variance.array[np.isfinite(template.variance.array)] 

290 median = np.median(variance) 

291 self.assertFloatsAlmostEqual(median, np.median(expected.variance.array), 

292 rtol=0.02, msg="variance level differs") 

293 self.assertLess(np.percentile(variance, 99)/median, 1.6, msg="variance ripple too large") 

294 self.assertGreater(np.percentile(variance, 1)/median, 0.6, msg="variance ripple too large") 

295 # Not checking the mask, as warping changes the sizes of the masks. 

296 

297 def testRunOneTractInput(self): 

298 """Test a bounding box that fully fits inside one tract, with only 

299 that tract passed as input. This checks that the code handles a single 

300 tract input correctly. 

301 """ 

302 box = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(180, 180)) 

303 task = lsst.ip.diffim.GetTemplateTask(config=self._makeConfig()) 

304 # Restrict to tract 0, since the box fits in just that tract. 

305 result = task.run(coaddExposureHandles={0: self.patches[0]}, 

306 bbox=box, 

307 wcs=self.exposure.wcs, 

308 dataIds={0: self.dataIds[0]}, 

309 physical_filter="a_test") 

310 

311 # All 4 patches from tract 0 are included in this template. 

312 self._checkMetadata(result.template, task.config, box, self.exposure.wcs, 4) 

313 self._checkPixels(result.template, task.config, box) 

314 

315 def testRunOneTractMultipleInputs(self): 

316 """Test a bounding box that fully fits inside one tract but where 

317 multiple tracts were passed in. This checks that patches that are 

318 mostly NaN after warping are merged correctly in the output. 

319 """ 

320 box = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(180, 180)) 

321 task = lsst.ip.diffim.GetTemplateTask(config=self._makeConfig()) 

322 result = task.run(coaddExposureHandles=self.patches, 

323 bbox=box, 

324 wcs=self.exposure.wcs, 

325 dataIds=self.dataIds, 

326 physical_filter="a_test") 

327 

328 # All 4 patches from two tracts are included in this template. 

329 self._checkMetadata(result.template, task.config, box, self.exposure.wcs, 6) 

330 self._checkPixels(result.template, task.config, box) 

331 

332 def testRunTwoTracts(self): 

333 """Test a bounding box that crosses tract boundaries. 

334 """ 

335 box = lsst.geom.Box2I(lsst.geom.Point2I(200, 200), lsst.geom.Point2I(600, 600)) 

336 task = lsst.ip.diffim.GetTemplateTask(config=self._makeConfig()) 

337 result = task.run(coaddExposureHandles=self.patches, 

338 bbox=box, 

339 wcs=self.exposure.wcs, 

340 dataIds=self.dataIds, 

341 physical_filter="a_test") 

342 

343 # All 4 patches from all 4 tracts are included in this template 

344 self._checkMetadata(result.template, task.config, box, self.exposure.wcs, 9) 

345 self._checkPixels(result.template, task.config, box) 

346 

347 def testRunCalibratesToNanojansky(self): 

348 """Test that the template is in nJy whatever the calibration of the 

349 coadds, and that coadds already in nJy are not rescaled. 

350 """ 

351 box = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(180, 180)) 

352 calibration = self.exposure.photoCalib.getCalibrationMean() 

353 self.assertNotEqual(calibration, 1.0) 

354 # The same coadd pixels, labelled as already in nJy. 

355 uncalibrated = [] 

356 for handle in self.patches[0]: 

357 coadd = handle.get() 

358 coadd.setPhotoCalib(lsst.afw.image.PhotoCalib(1.0)) 

359 uncalibrated.append(pipeBase.InMemoryDatasetHandle(coadd, storageClass="ExposureF", copy=True, 

360 dataId=handle.dataId)) 

361 task = lsst.ip.diffim.GetTemplateTask(config=self._makeConfig()) 

362 templates = {} 

363 for key, handles in ((calibration, self.patches[0]), (1.0, uncalibrated)): 

364 result = task.run(coaddExposureHandles={0: handles}, 

365 bbox=box, 

366 wcs=self.exposure.wcs, 

367 dataIds={0: self.dataIds[0]}, 

368 physical_filter="a_test") 

369 self.assertEqual(result.template.photoCalib, lsst.afw.image.PhotoCalib(1.0)) 

370 templates[key] = result.template 

371 

372 self.assertFloatsAlmostEqual(templates[calibration].image.array, 

373 calibration*templates[1.0].image.array, rtol=1e-6) 

374 self.assertFloatsAlmostEqual(templates[calibration].variance.array, 

375 calibration**2*templates[1.0].variance.array, rtol=1e-6) 

376 

377 def testGaussianPsfGridFallback(self): 

378 """If the CoaddPsf cannot be evaluated at its average position, the 

379 Gaussian width is averaged over a grid of positions instead. 

380 """ 

381 box = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(180, 180)) 

382 task = lsst.ip.diffim.GetTemplateTask(config=self._makeConfig()) 

383 result = task.run(coaddExposureHandles={0: self.patches[0]}, 

384 bbox=box, 

385 wcs=self.exposure.wcs, 

386 dataIds={0: self.dataIds[0]}, 

387 physical_filter="a_test") 

388 template = result.template 

389 template.setPsf(self._makeCoaddPsf(template, task.config)) 

390 expected = lsst.ip.diffim.utils.evaluateMeanPsfFwhm( 

391 template, 

392 fwhmExposureBuffer=task.config.fwhmExposureBuffer, 

393 fwhmExposureGrid=task.config.fwhmExposureGrid, 

394 )/gaussian_sigma_to_fwhm 

395 

396 error = lsst.pex.exceptions.InvalidParameterError("No inputs at the average position.") 

397 with unittest.mock.patch("lsst.ip.diffim.getTemplate.getPsfFwhm", side_effect=error): 

398 with self.assertLogs(task.log.name, level="INFO") as cm: 

399 psf = task._makeGaussianPsf(template) 

400 

401 self.assertIn("grid of points", "\n".join(cm.output)) 

402 self.assertIsInstance(psf, lsst.afw.detection.GaussianPsf) 

403 self.assertFloatsAlmostEqual(psf.getSigma(), expected) 

404 self.assertFloatsAlmostEqual(task.metadata["templatePsfSigma"], expected) 

405 

406 @lsst.utils.tests.methodParameters( 

407 minFraction=[0.1, 0.9], 

408 expected=[lsst.afw.detection.InvalidPsfError, pipeBase.NoWorkFound], 

409 ) 

410 def testGaussianPsfFailure(self, minFraction=None, expected=None): 

411 """A template PSF that cannot be evaluated raises NoWorkFound if the 

412 template coverage is below the configured minimum, and the PSF error 

413 otherwise. 

414 """ 

415 # Drop a patch so that only about half of the template has data. 

416 self.patches[0].pop(1) 

417 box = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(180, 180)) 

418 config = self._makeConfig() 

419 config.minTemplateFractionForExpectedSuccess = minFraction 

420 task = lsst.ip.diffim.GetTemplateTask(config=config) 

421 error = lsst.afw.detection.InvalidPsfError("Unable to compute PSF FWHM.") 

422 with unittest.mock.patch.object(task, "_makeGaussianPsf", side_effect=error): 

423 with self.assertRaisesRegex(expected, "Unable to compute PSF FWHM"): 

424 task.run(coaddExposureHandles=self.patches, 

425 bbox=box, 

426 wcs=self.exposure.wcs, 

427 dataIds=self.dataIds, 

428 physical_filter="a_test") 

429 

430 def testRunNoTemplate(self): 

431 """A bounding box that doesn't overlap the patches will raise. 

432 """ 

433 box = lsst.geom.Box2I(lsst.geom.Point2I(1200, 1200), lsst.geom.Point2I(1600, 1600)) 

434 task = lsst.ip.diffim.GetTemplateTask(config=self._makeConfig()) 

435 with self.assertRaisesRegex(lsst.pipe.base.NoWorkFound, "No patches found"): 

436 task.run(coaddExposureHandles=self.patches, 

437 bbox=box, 

438 wcs=self.exposure.wcs, 

439 dataIds=self.dataIds, 

440 physical_filter="a_test") 

441 

442 def testMissingPatches(self): 

443 """Test that a missing patch results in an appropriate mask. 

444 

445 This fixes the bug reported on DM-44997 (image and variance were NaN 

446 but the mask was not set to NO_DATA for those pixels). 

447 """ 

448 # tract=0, patch=1 is the lower-left corner, as displayed in DS9. 

449 self.patches[0].pop(1) 

450 box = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(180, 180)) 

451 task = lsst.ip.diffim.GetTemplateTask(config=self._makeConfig()) 

452 result = task.run(coaddExposureHandles=self.patches, 

453 bbox=box, 

454 wcs=self.exposure.wcs, 

455 dataIds=self.dataIds, 

456 physical_filter="a_test") 

457 no_data = (result.template.mask.array & result.template.mask.getPlaneBitMask("NO_DATA")) != 0 

458 self.assertTrue(np.isfinite(result.template.image.array).all()) 

459 self.assertTrue(np.isfinite(result.template.variance.array).all()) 

460 self.assertEqual(no_data.sum(), 20990) 

461 

462 @lsst.utils.tests.methodParameters( 

463 box=[ 

464 lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(180, 180)), 

465 lsst.geom.Box2I(lsst.geom.Point2I(200, 200), lsst.geom.Point2I(600, 600)), 

466 ], 

467 nInput=[8, 16], 

468 ) 

469 def testNanInputs(self, box=None, nInput=None): 

470 """Test that the template has finite values when some of the input 

471 pixels have NaN as variance. 

472 """ 

473 for tract, patchRefs in self.patches.items(): 

474 for patchRef in patchRefs: 

475 patchCoadd = patchRef.get() 

476 bbox = lsst.geom.Box2I() 

477 bbox.include(lsst.geom.Point2I(patchCoadd.getBBox().getCenter())) 

478 bbox.grow(3) 

479 patchCoadd.variance[bbox].array *= np.nan 

480 

481 box = lsst.geom.Box2I(lsst.geom.Point2I(200, 200), lsst.geom.Point2I(600, 600)) 

482 task = lsst.ip.diffim.GetTemplateTask(config=self._makeConfig()) 

483 result = task.run(coaddExposureHandles=self.patches, 

484 bbox=box, 

485 wcs=self.exposure.wcs, 

486 dataIds=self.dataIds, 

487 physical_filter="a_test") 

488 if debug: 488 ↛ 489line 488 didn't jump to line 489 because the condition on line 488 was never true

489 _showTemplate(box, result.template) 

490 self._checkMetadata(result.template, task.config, box, self.exposure.wcs, 9) 

491 # We just check that the pixel values are all finite. We cannot check that pixel values 

492 # in the template are closer to the original anymore. 

493 self.assertTrue(np.isfinite(result.template.image.array).all()) 

494 

495 def _runCorrection(self, doCorrectVarianceWarpCorrelation=False, doScaleVariance=False, 

496 handles=None, instrument="SciCam", coaddWarpKernel=None, 

497 templateWarpKernel="lanczos3"): 

498 """Run the task on tract 0, with a science image from ``instrument``. 

499 

500 The plate scale correction is applied only when ``instrument`` is not 

501 the instrument of the template coadds, which is ``"TestCam"`` unless 

502 ``handles`` says otherwise. ``coaddWarpKernel`` defaults to the kernel 

503 the patches were made with, so the reconstructed factors are exact. 

504 """ 

505 config = self._makeConfig() 

506 config.doCorrectVarianceWarpCorrelation = doCorrectVarianceWarpCorrelation 

507 config.doScaleVariance = doScaleVariance 

508 if coaddWarpKernel is not None: 

509 config.coaddWarpKernel = coaddWarpKernel 

510 config.warp.warpingKernelName = templateWarpKernel 

511 task = lsst.ip.diffim.GetTemplateTask(config=config) 

512 result = task.run(coaddExposureHandles={0: handles or self.patches[0]}, 

513 bbox=lsst.geom.Box2I(self.varianceBox), 

514 wcs=self.exposure.wcs, 

515 dataIds={0: self.dataIds[0]}, 

516 physical_filter="a_test", 

517 instrument=instrument) 

518 return task, result.template 

519 

520 def _makeScaledWcs(self, factor): 

521 """Make a WCS like the base exposure's, but with its pixel scale 

522 multiplied by ``factor``. 

523 """ 

524 cdMatrix = lsst.afw.geom.makeCdMatrix(factor*1.05*self.scale*lsst.geom.arcseconds, 

525 93*lsst.geom.degrees) 

526 return lsst.afw.geom.makeSkyWcs(lsst.geom.Point2D(120, 150), 

527 lsst.geom.SpherePoint(0, 0, lsst.geom.radians), 

528 cdMatrix) 

529 

530 @staticmethod 

531 def _makeCoaddInputs(records, instrument="TestCam", epochs=None): 

532 """Make a CoaddInputs holding the given input records. 

533 

534 Parameters 

535 ---------- 

536 records : `list` [`tuple` [`lsst.afw.geom.SkyWcs` or `None`, \ 

537 `lsst.geom.Box2I`]] 

538 The WCS and bbox to record for each input. A `None` WCS makes a 

539 record that `_plateScaleFactor` has to skip. May be empty, to 

540 simulate a coadd whose plate scale cannot be reconstructed. 

541 instrument : `str` or `None`, optional 

542 Instrument label to record for every input. `None` leaves the 

543 inputs without a visit info, and an empty string gives them a 

544 visit info with no label; either way the instrument is unknown. 

545 epochs : `list` [`tuple` [`int`, `float`, `float`]], optional 

546 Visit, mid-exposure MJD (TAI) and coadd weight of each input. By 

547 default every input is visit 0 with weight 1 and no observation 

548 time. The time is not recorded if ``instrument`` is `None`. 

549 """ 

550 ccdSchema = lsst.afw.table.ExposureTable.makeMinimalSchema() 

551 weightKey = ccdSchema.addField("weight", type=float, doc="Coadd weight") 

552 visitKey = ccdSchema.addField("visit", type=np.int64, doc="Visit of the input") 

553 ccdSchema.addField("ccd", type=np.int32, doc="Detector of the input") 

554 coaddInputs = lsst.afw.image.CoaddInputs( 

555 lsst.afw.table.ExposureTable.makeMinimalSchema(), ccdSchema) 

556 if epochs is None: 

557 epochs = [(0, None, 1.0)]*len(records) 

558 for (wcs, bbox), (visit, mjd, weight) in zip(records, epochs, strict=True): 

559 record = coaddInputs.ccds.addNew() 

560 record.setWcs(wcs) 

561 record.setBBox(bbox) 

562 record.set(visitKey, visit) 

563 record.set(weightKey, weight) 

564 if instrument is not None: 

565 date = DateTime(mjd, DateTime.MJD, DateTime.TAI) if mjd is not None else DateTime() 

566 record.setVisitInfo(lsst.afw.image.VisitInfo(instrumentLabel=instrument, date=date)) 

567 return coaddInputs 

568 

569 def _patchHandles(self, tract, records, instrument="TestCam", epochs=None): 

570 """Return handles for a tract's patches, with their CoaddInputs 

571 replaced by ``records`` from ``instrument``, observed at ``epochs``. 

572 """ 

573 handles = [] 

574 for ref in self.patches[tract]: 

575 coadd = ref.get() 

576 coadd.getInfo().setCoaddInputs(self._makeCoaddInputs(records, instrument=instrument, 

577 epochs=epochs)) 

578 handles.append(pipeBase.InMemoryDatasetHandle( 

579 coadd, storageClass="ExposureF", copy=True, dataId=ref.dataId)) 

580 return handles 

581 

582 def testCorrectVarianceWarpCorrelation(self): 

583 """The correlation correction covers both warps: the one that built 

584 the coadds and the one this task performs. 

585 """ 

586 _, off = self._runCorrection(instrument="TestCam") 

587 for coaddKernel, templateKernel in (("lanczos3", "lanczos3"), 

588 ("lanczos5", "lanczos3"), 

589 ("lanczos5", "lanczos5"), 

590 ("bilinear", "lanczos3")): 

591 with self.subTest(coaddWarpKernel=coaddKernel, templateWarpKernel=templateKernel): 

592 task, on = self._runCorrection(doCorrectVarianceWarpCorrelation=True, 

593 instrument="TestCam", 

594 coaddWarpKernel=coaddKernel, 

595 templateWarpKernel=templateKernel) 

596 factor = task.metadata["varianceWarpCorrelationFactor"] 

597 # A kernel spreads power, so this always makes the plane 

598 # larger. 

599 self.assertGreater(factor, 1.0) 

600 # The phase average converges slowly for bilinear, because 

601 # its sum of squares has a kink where the phase wraps. 

602 rtol = 1e-4 if "bilinear" in (coaddKernel, templateKernel) else 1e-5 

603 self.assertFloatsAlmostEqual( 

604 factor, 

605 1/(KERNEL_SUM_SQ_1D[coaddKernel]*KERNEL_SUM_SQ_1D[templateKernel])**2, 

606 rtol=rtol) 

607 self.assertEqual(task.metadata["variancePlateScaleFactor"], 1.0) 

608 if templateKernel == "lanczos3": 

609 # A pure scalar, with no per-pixel structure of its own; 

610 # only comparable when `off` used the same template warp. 

611 self.assertFloatsAlmostEqual(on.variance.array, off.variance.array*factor, 

612 rtol=1e-5, ignoreNaNs=True) 

613 

614 def testCorrectVariancePlateScale(self): 

615 """The plate scale correction is the total pixel area change from the 

616 images the coadds were built from to the science image. 

617 """ 

618 # The science image and the coadds are from the same instrument, so 

619 # the factor is 1 without reading any coadd inputs. 

620 task, off = self._runCorrection(instrument="TestCam") 

621 self.assertEqual(task.metadata["variancePlateScaleFactor"], 1.0) 

622 self.assertNotIn("templateVarianceCorrectionFactor", task.metadata) 

623 

624 # The fixture's records are the science image itself, so there is no 

625 # net change in pixel area even when the instruments differ. 

626 task, on = self._runCorrection() 

627 self.assertFloatsAlmostEqual(task.metadata["variancePlateScaleFactor"], 1.0, rtol=1e-6) 

628 self.assertNotIn("varianceWarpCorrelationFactor", task.metadata) 

629 

630 # Coarser original pixels than science pixels, the DECam-template 

631 # case: the correction is the ratio of their areas. 

632 for scaleFactor in (1.315, 0.5): 

633 with self.subTest(scaleFactor=scaleFactor): 

634 handles = self._patchHandles( 

635 0, [(self._makeScaledWcs(scaleFactor), self.exposure.getBBox())]) 

636 task, on = self._runCorrection(handles=handles) 

637 factor = task.metadata["variancePlateScaleFactor"] 

638 self.assertFloatsAlmostEqual(factor, scaleFactor**2, rtol=1e-6) 

639 self.assertFloatsAlmostEqual(on.variance.array, off.variance.array*factor, 

640 rtol=1e-5, ignoreNaNs=True) 

641 

642 def testVarianceCorrectionsCompose(self): 

643 """The two corrections are independent and multiply together. 

644 

645 The patches are warped from the exposure and the template is warped 

646 back to its pixel grid, so the two warps cancel geometrically, leaving 

647 only the two kernels' correlation to undo. The substituted coadd 

648 inputs claim coarser original pixels than the exposure really has, so 

649 with both corrections applied the variance must come back to its 

650 original value times the claimed change in pixel area. 

651 """ 

652 plateScale = 1.315 

653 handles = self._patchHandles(0, [(self._makeScaledWcs(plateScale), self.exposure.getBBox())]) 

654 # A science image from the coadds' instrument applies no correction 

655 # at all; one from another instrument applies both. 

656 _, off = self._runCorrection(handles=handles, instrument="TestCam") 

657 task, on = self._runCorrection(doCorrectVarianceWarpCorrelation=True, handles=handles) 

658 

659 # Both together is exactly the product of the two factors. 

660 self.assertFloatsAlmostEqual(task.metadata["variancePlateScaleFactor"], plateScale**2, rtol=1e-6) 

661 scale = (task.metadata["varianceWarpCorrelationFactor"] 

662 * task.metadata["variancePlateScaleFactor"]) 

663 self.assertFloatsAlmostEqual(task.metadata["templateVarianceCorrectionFactor"], 

664 scale, rtol=1e-12) 

665 self.assertFloatsAlmostEqual(on.variance.array, off.variance.array*scale, 

666 rtol=1e-5, ignoreNaNs=True) 

667 

668 # Only the variance plane is touched. Nothing about the correction 

669 # feeds back into how the patches are combined. 

670 self.assertImagesEqual(on.image, off.image) 

671 self.assertMasksEqual(on.mask, off.mask) 

672 

673 # realize() takes a noise sigma, so the original variance is 4, not 2, 

674 # before calibrating to nJy. 

675 calibration = self.exposure.photoCalib.getCalibrationMean() 

676 original = calibration**2*np.median(self.exposure.variance.array) 

677 self.assertFloatsAlmostEqual(np.median(on.variance.array), original*plateScale**2, rtol=0.02) 

678 

679 # Which is a real correction: uncorrected, the plane is too small by 

680 # the two warping kernels' phase-averaged sums of squares. 

681 self.assertFloatsAlmostEqual( 

682 np.median(off.variance.array)/original, 

683 (KERNEL_SUM_SQ_1D[self.coaddWarpKernel]*KERNEL_SUM_SQ_1D["lanczos3"])**2, rtol=0.02) 

684 

685 def testCorrectVariancePlateScaleUsesOneRecord(self): 

686 """Only the first usable coadd input is read. 

687 

688 The spread between records is just the local pixel scale, a few 

689 tenths of a percent across a real focal plane, so one stands for all 

690 of them. 

691 """ 

692 handles = self._patchHandles( 

693 0, [(None, self.exposure.getBBox()), 

694 (self._makeScaledWcs(2.0), self.exposure.getBBox()), 

695 (self.exposure.wcs, self.exposure.getBBox())]) 

696 task, _ = self._runCorrection(handles=handles) 

697 

698 # The first record with a WCS: the one without is skipped, and the 

699 # last (which would give 1.0) is never reached. 

700 self.assertFloatsAlmostEqual(task.metadata["variancePlateScaleFactor"], 4.0, rtol=1e-6) 

701 

702 def testCorrectVariancePlateScaleSkipsDroppedCoadd(self): 

703 """The plate scale comes from the first coadd that is used, not from 

704 one dropped for its instrument. 

705 """ 

706 bbox = self.exposure.getBBox() 

707 handles = (self._patchHandles(0, [(self._makeScaledWcs(2.0), bbox)], instrument="OtherCam")[:1] 

708 + self._patchHandles(0, [(self._makeScaledWcs(1.315), bbox)])[1:]) 

709 task, _ = self._runCorrection(handles=handles) 

710 self.assertFloatsAlmostEqual(task.metadata["variancePlateScaleFactor"], 1.315**2, rtol=1e-6) 

711 

712 def testCorrectVariancePlateScaleNextTract(self): 

713 """If the first coadd kept in a tract cannot give the plate scale, the 

714 first coadd kept in the next tract is used. 

715 """ 

716 task = lsst.ip.diffim.GetTemplateTask(config=self._makeConfig()) 

717 handles = {0: self._patchHandles(0, []), 

718 1: self._patchHandles(1, [(self._makeScaledWcs(1.315), self.exposure.getBBox())])} 

719 task.run(coaddExposureHandles=handles, 

720 bbox=lsst.geom.Box2I(self.varianceBox), 

721 wcs=self.exposure.wcs, 

722 dataIds={0: self.dataIds[0], 1: self.dataIds[1]}, 

723 physical_filter="a_test", 

724 instrument="SciCam") 

725 self.assertFloatsAlmostEqual(task.metadata["variancePlateScaleFactor"], 1.315**2, rtol=1e-6) 

726 

727 def testCorrectVariancePlateScaleNeedsCoaddInputs(self): 

728 """Without usable coadd inputs the plate scale cannot be 

729 reconstructed, so the template cannot be built. 

730 """ 

731 handles = self._patchHandles(0, []) 

732 with self.assertRaisesRegex(RuntimeError, "cannot be corrected for the change in pixel area"): 

733 self._runCorrection(handles=handles) 

734 

735 def testRunReturnsTemplateInputs(self): 

736 """`run` returns the inputs of each coadd that overlap the science 

737 image, with the part of the science image each one covers. Inputs 

738 with no weight or no observation time are left out, as are inputs 

739 that cover only the template border. 

740 """ 

741 wcs = self.exposure.wcs 

742 whole = (wcs, self.exposure.getBBox()) 

743 right = (wcs, lsst.geom.Box2I(lsst.geom.Point2I(90, -200), lsst.geom.Point2I(800, 800))) 

744 outside = (wcs, lsst.geom.Box2I(lsst.geom.Point2I(600, 600), lsst.geom.Point2I(800, 800))) 

745 border = (wcs, lsst.geom.Box2I(lsst.geom.Point2I(185, 0), lsst.geom.Point2I(195, 180))) 

746 handles = (self._patchHandles(0, [whole, right, outside, whole, whole, border], 

747 epochs=[(1, 60000.25, 1.0), (2, 60010.5, 3.0), (3, 60100.0, 1.0), 

748 (4, 60200.0, 0.0), (5, None, 1.0), (6, 60300.0, 1.0)])[:1] 

749 + self._patchHandles(0, [whole], epochs=[(1, 60000.25, 2.0)])[1:]) 

750 result = self._runTract0(handles, outputImageType="future") 

751 

752 templateInputs = result.templateInputs 

753 self.assertEqual(set(templateInputs), {(0, patch) for patch in range(4)}) 

754 first = templateInputs[0, 0] 

755 self.assertEqual([(i.visit, i.detector, i.weight) for i in first], [(1, 0, 1.0), (2, 0, 3.0)]) 

756 self.assertFloatsAlmostEqual(np.array([i.mid_mjd_tai for i in first]), np.array([60000.25, 60010.5]), 

757 rtol=0, atol=1e-6) 

758 # The box that _runTract0 requests. 

759 scienceBox = lsst.geom.Box2D(lsst.geom.Point2D(-0.5, -0.5), lsst.geom.Point2D(180.5, 180.5)) 

760 self.assertFloatsAlmostEqual(first[0].bounds.area, scienceBox.getArea(), rtol=1e-6) 

761 # Warping with lanczos5 left the 4.5 pixels along the input's edges 

762 # out of the coadd. 

763 rightArea = (scienceBox.getMaxX() - 94.0)*scienceBox.getHeight() 

764 self.assertFloatsAlmostEqual(first[1].bounds.area, rightArea, rtol=1e-6) 

765 self.assertFloatsAlmostEqual(first[1].bounds.x_vertices.min(), 94.0, rtol=0, atol=1e-6) 

766 # Each coadd lists its own record of an input shared with another. 

767 for patch in range(1, 4): 

768 self.assertEqual([(i.visit, i.weight) for i in templateInputs[0, patch]], [(1, 2.0)]) 

769 

770 def testRunTemplateInputsOnlyForFuture(self): 

771 """`run` records no template inputs for the legacy output type. 

772 """ 

773 records = [(self.exposure.wcs, self.exposure.getBBox())] 

774 result = self._runTract0(self._patchHandles(0, records, epochs=[(1, 60000.25, 1.0)])) 

775 self.assertEqual(result.templateInputs, {}) 

776 

777 def testRunTemplateInputsSkipDroppedCoadd(self): 

778 """A coadd dropped for its instrument has no template inputs. 

779 """ 

780 records = [(self.exposure.wcs, self.exposure.getBBox())] 

781 handles = (self._patchHandles(0, records, epochs=[(1, 60000.25, 1.0)])[:3] 

782 + self._patchHandles(0, records, instrument="OtherCam", 

783 epochs=[(2, 60100.0, 1.0)])[3:]) 

784 result = self._runTract0(handles, outputImageType="future") 

785 self.assertEqual(set(result.templateInputs), {(0, 0), (0, 1), (0, 2)}) 

786 

787 def testRunTemplateInputsLeaveOutWarpBorder(self): 

788 """An input's footprint leaves out the border along its edges that 

789 the coadd's warping kernel left out. 

790 """ 

791 right = (self.exposure.wcs, lsst.geom.Box2I(lsst.geom.Point2I(90, -200), lsst.geom.Point2I(800, 800))) 

792 for kernel, border in (("bilinear", 0.5), ("lanczos3", 2.5)): 

793 with self.subTest(coaddWarpKernel=kernel): 

794 result = self._runTract0(self._patchHandles(0, [right], epochs=[(1, 60000.25, 1.0)]), 

795 outputImageType="future", coaddWarpKernel=kernel) 

796 bounds = result.templateInputs[0, 0][0].bounds 

797 self.assertFloatsAlmostEqual(bounds.x_vertices.min(), 89.5 + border, rtol=0, atol=1e-6) 

798 

799 def testRunTemplateInputsCoverScienceEdges(self): 

800 """An input's footprint reaches the edges of a distorted science image 

801 wherever the input covers them. 

802 """ 

803 # Science pixel (x, y) lands on input pixel (x, y + a*(x - xc)**2), 

804 # which distorts the top and bottom edges of the science image by about 

805 # 2 pixels between its corners. 

806 xc = 90.0 

807 left = (self.exposure.wcs, lsst.geom.Box2I(lsst.geom.Point2I(-200, -200), lsst.geom.Point2I(89, 800))) 

808 # The centers of the edge pixels that the input's warp covers; warping 

809 # with lanczos5 left the 4.5 pixels along the input's edges out. 

810 x = np.arange(0.0, 85.0) 

811 y = np.arange(0.0, 181.0) 

812 edgeX = np.concatenate([x, x, np.zeros_like(y)]) 

813 edgeY = np.concatenate([np.zeros_like(x), np.full_like(x, 180.0), y]) 

814 for a in (-2.5e-4, 2.5e-4): 

815 with self.subTest(a=a): 

816 forward = np.array([[1.0, 1, 1, 0], [1.0, 2, 0, 1], [a, 2, 2, 0], [-2*a*xc, 2, 1, 0], 

817 [a*xc**2, 2, 0, 0]]) 

818 inverse = np.array([[1.0, 1, 1, 0], [1.0, 2, 0, 1], [-a, 2, 2, 0], [2*a*xc, 2, 1, 0], 

819 [-a*xc**2, 2, 0, 0]]) 

820 distortion = lsst.afw.geom.TransformPoint2ToPoint2(astshim.PolyMap(forward, inverse)) 

821 wcs = lsst.afw.geom.makeModifiedWcs(distortion, self.exposure.wcs, False) 

822 result = self._runTract0(self._patchHandles(0, [left], epochs=[(1, 60000.25, 1.0)]), 

823 outputImageType="future", wcs=wcs) 

824 bounds = result.templateInputs[0, 0][0].bounds 

825 self.assertTrue(np.all(bounds.contains(x=edgeX, y=edgeY))) 

826 

827 def _runTract0(self, handles, outputImageType="legacy", wcs=None, coaddWarpKernel=None): 

828 """Build a template from the given tract 0 patch handles, with a task 

829 configured for ``outputImageType`` and ``coaddWarpKernel``, for a 

830 science image with ``wcs``, by default that of the test exposure. 

831 """ 

832 box = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(180, 180)) 

833 config = self._makeConfig() 

834 config.output_image_type = outputImageType 

835 if coaddWarpKernel is not None: 

836 config.coaddWarpKernel = coaddWarpKernel 

837 task = lsst.ip.diffim.GetTemplateTask(config=config) 

838 return task.run(coaddExposureHandles={0: handles}, 

839 bbox=box, 

840 wcs=self.exposure.wcs if wcs is None else wcs, 

841 dataIds={0: self.dataIds[0]}, 

842 physical_filter="a_test") 

843 

844 def testRunRecordsInstrument(self): 

845 """The instrument of each coadd is recorded with the template's coadd 

846 inputs. 

847 """ 

848 result = self._runTract0(self.patches[0]) 

849 ccds = result.template.getInfo().getCoaddInputs().ccds 

850 self.assertEqual(len(ccds), 4) 

851 self.assertEqual({record["instrument"] for record in ccds}, {"TestCam"}) 

852 

853 def testRunUnknownInstrument(self): 

854 """A coadd whose inputs record no instrument is dropped when the 

855 other coadds record one, and kept, with the template's instrument 

856 ``"UNKNOWN"``, when none of them records one. 

857 """ 

858 records = [(self.exposure.wcs, self.exposure.getBBox())] 

859 # Inputs with no visit info, and with a visit info but no label. 

860 for unknown in (None, ""): 

861 with self.subTest(label=unknown): 

862 handles = (self._patchHandles(0, records, instrument=unknown)[:1] 

863 + self._patchHandles(0, records)[1:]) 

864 ccds, dropped = self._runLogged({0: handles}) 

865 self.assertEqual(len(ccds), 3) 

866 self.assertEqual({record["instrument"] for record in ccds}, {"TestCam"}) 

867 self.assertEqual(len(dropped), 1) 

868 self.assertIn("made from UNKNOWN", dropped[0]) 

869 

870 # No coadd records an instrument. 

871 result = self._runTract0(self._patchHandles(0, records, instrument=unknown)) 

872 ccds = result.template.getInfo().getCoaddInputs().ccds 

873 self.assertEqual(len(ccds), 4) 

874 self.assertEqual({record["instrument"] for record in ccds}, {"UNKNOWN"}) 

875 

876 def _runLogged(self, handles, dataIds=None, box=None, instrument=None): 

877 """Build a template, capturing the messages about dropped coadds. 

878 

879 Parameters 

880 ---------- 

881 handles : `dict` [`int`, `list`] 

882 Patch handles, keyed by tract. 

883 dataIds : `dict` [`int`, `list`], optional 

884 Data ids matching ``handles``; defaults to the fixture's. 

885 box : `lsst.geom.Box2I`, optional 

886 Box to build the template on; defaults to one in tract 0. 

887 instrument : `str`, optional 

888 Instrument of the science image. 

889 

890 Returns 

891 ------- 

892 ccds : `lsst.afw.table.ExposureCatalog` 

893 The coadd inputs recorded on the template. 

894 dropped : `list` [`str`] 

895 The info messages about dropped coadds. 

896 """ 

897 if dataIds is None: 

898 dataIds = {tract: self.dataIds[tract] for tract in handles} 

899 if box is None: 

900 box = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(180, 180)) 

901 task = lsst.ip.diffim.GetTemplateTask(config=self._makeConfig()) 

902 with self.assertLogs(task.log.name, level="INFO") as cm: 

903 result = task.run(coaddExposureHandles=handles, 

904 bbox=box, 

905 wcs=self.exposure.wcs, 

906 dataIds=dataIds, 

907 physical_filter="a_test", 

908 instrument=instrument) 

909 dropped = [record for record in cm.records 

910 if record.getMessage().startswith("Dropping template coadd")] 

911 self.assertEqual({record.levelname for record in dropped}, {"INFO"} if dropped else set()) 

912 return result.template.getInfo().getCoaddInputs().ccds, [record.getMessage() for record in dropped] 

913 

914 def testRunDropsMinorityInstrument(self): 

915 """Coadds made from an instrument other than the one most coadds were 

916 made from are dropped. 

917 """ 

918 records = [(self.exposure.wcs, self.exposure.getBBox())] 

919 handles = (self._patchHandles(0, records)[:3] 

920 + self._patchHandles(0, records, instrument="OtherCam")[3:]) 

921 

922 ccds, dropped = self._runLogged({0: handles}) 

923 self.assertEqual({record["patch"] for record in ccds}, {0, 1, 2}) 

924 self.assertEqual({record["instrument"] for record in ccds}, {"TestCam"}) 

925 self.assertEqual(len(dropped), 1) 

926 self.assertIn(str(self.dataIds[0][3]), dropped[0]) 

927 self.assertIn("made from OtherCam", dropped[0]) 

928 

929 def testRunPrefersScienceInstrument(self): 

930 """Coadds made from the science image's instrument are used even when 

931 they are in the minority; otherwise the majority instrument is used. 

932 """ 

933 records = [(self.exposure.wcs, self.exposure.getBBox())] 

934 handles = (self._patchHandles(0, records, instrument="OtherCam")[:3] 

935 + self._patchHandles(0, records)[3:]) 

936 

937 ccds, dropped = self._runLogged({0: handles}, instrument="TestCam") 

938 self.assertEqual({record["patch"] for record in ccds}, {3}) 

939 self.assertEqual({record["instrument"] for record in ccds}, {"TestCam"}) 

940 self.assertEqual(len(dropped), 3) 

941 self.assertTrue(all("made from OtherCam" in message for message in dropped)) 

942 

943 # No coadd was made from the science image's instrument. 

944 ccds, dropped = self._runLogged({0: handles}, instrument="SciCam") 

945 self.assertEqual({record["patch"] for record in ccds}, {0, 1, 2}) 

946 self.assertEqual({record["instrument"] for record in ccds}, {"OtherCam"}) 

947 self.assertEqual(len(dropped), 1) 

948 

949 def testRunInstrumentTie(self): 

950 """A tie goes to the instrument whose name sorts first. 

951 """ 

952 records = [(self.exposure.wcs, self.exposure.getBBox())] 

953 handles = (self._patchHandles(0, records)[:2] 

954 + self._patchHandles(0, records, instrument="OtherCam")[2:]) 

955 

956 ccds, dropped = self._runLogged({0: handles}) 

957 self.assertEqual({record["patch"] for record in ccds}, {2, 3}) 

958 self.assertEqual({record["instrument"] for record in ccds}, {"OtherCam"}) 

959 self.assertEqual(len(dropped), 2) 

960 

961 def testRunDropsNonOverlappingCoadd(self): 

962 """A coadd from another instrument is dropped even if it does not 

963 overlap the template. 

964 """ 

965 records = [(self.exposure.wcs, self.exposure.getBBox())] 

966 # Tract 3 does not overlap a box in the lower left of tract 0. 

967 box = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(50, 50)) 

968 handles = {0: self.patches[0], 3: self._patchHandles(3, records, instrument="OtherCam")[:1]} 

969 dataIds = {0: self.dataIds[0], 3: self.dataIds[3][:1]} 

970 

971 ccds, dropped = self._runLogged(handles, dataIds=dataIds, box=box) 

972 self.assertEqual({record["tract"] for record in ccds}, {0}) 

973 self.assertEqual({record["instrument"] for record in ccds}, {"TestCam"}) 

974 self.assertEqual(len(dropped), 1) 

975 self.assertIn(str(self.dataIds[3][0]), dropped[0]) 

976 

977 def _scaleInputVariance(self, tract, factor): 

978 """Return fresh handles for one tract's patches, with their variance 

979 planes multiplied by ``factor``. 

980 

981 Parameters 

982 ---------- 

983 tract : `int` 

984 Id of the tract whose patches should be copied. 

985 factor : `float` 

986 Factor to multiply the input variance planes by. 

987 

988 Returns 

989 ------- 

990 handles : `list` [`lsst.pipe.base.InMemoryDatasetHandle`] 

991 Handles to the modified patches. 

992 """ 

993 handles = [] 

994 for handle in self.patches[tract]: 

995 # ``copy=True`` on the original handles means this is a copy, so 

996 # the patches shared with the other tests are left untouched. 

997 patch = handle.get() 

998 patch.variance.array *= factor 

999 handles.append(pipeBase.InMemoryDatasetHandle(patch, 

1000 storageClass="ExposureF", 

1001 copy=True, 

1002 dataId=handle.dataId)) 

1003 return handles 

1004 

1005 def testScaleVariance(self): 

1006 """Test that the template variance plane is rescaled to match the 

1007 empirical pixel noise, and that the factor used is recorded in the 

1008 task metadata. 

1009 """ 

1010 scaleFactor = 1.345 

1011 box = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(180, 180)) 

1012 

1013 def _configureAndRunTask(doScaleVariance, varianceScale=1.): 

1014 """Build a template from tract 0, optionally rescaling the input 

1015 variance planes by ``varianceScale`` first. 

1016 """ 

1017 config = self._makeConfig() 

1018 config.doScaleVariance = doScaleVariance 

1019 task = lsst.ip.diffim.GetTemplateTask(config=config) 

1020 result = task.run(coaddExposureHandles={0: self._scaleInputVariance(0, varianceScale)}, 

1021 bbox=box, 

1022 wcs=self.exposure.wcs, 

1023 dataIds={0: self.dataIds[0]}, 

1024 physical_filter="a_test") 

1025 return task, result.template 

1026 

1027 # With scaling disabled the subtask is never constructed, and nothing 

1028 # is recorded in the metadata. 

1029 taskOff, templateOff = _configureAndRunTask(doScaleVariance=False) 

1030 self.assertFalse(hasattr(taskOff, "scaleVariance")) 

1031 self.assertNotIn("scaleTemplateVarianceFactor", taskOff.metadata) 

1032 

1033 # The image is correlated after warping, so ``doScaleVariance`` will 

1034 # apply a correction. The value here is empirical from a warped image 

1035 # with white noise and no sources. 

1036 taskOn, templateOn = _configureAndRunTask(doScaleVariance=True) 

1037 factor = taskOn.metadata["scaleTemplateVarianceFactor"] 

1038 self.assertFloatsAlmostEqual(factor, 1.145, atol=0.01, 

1039 msg="Measured template variance scaling changed; check the" 

1040 " warping kernels used by _makePatches and the task," 

1041 " and the order of the variance corrections.") 

1042 # The only difference from the unscaled template is the constant 

1043 # factor applied to the variance plane. 

1044 self.assertFloatsAlmostEqual(templateOn.variance.array, 

1045 templateOff.variance.array*factor, rtol=1e-5) 

1046 # Tolerance here is float32 round-off: repeated runs of the task are 

1047 # not bitwise identical. 

1048 self.assertImagesAlmostEqual(templateOn.image, templateOff.image, rtol=1e-5, atol=1e-5) 

1049 

1050 # If the input variance planes under-estimate the noise by a known 

1051 # factor, the measured factor grows by that amount and the same 

1052 # output variance plane is recovered. 

1053 taskLow, templateLow = _configureAndRunTask(doScaleVariance=True, varianceScale=1/scaleFactor) 

1054 self.assertFloatsAlmostEqual(taskLow.metadata["scaleTemplateVarianceFactor"], 

1055 factor*scaleFactor, rtol=1e-5) 

1056 self.assertImagesAlmostEqual(templateLow.variance, templateOn.variance, rtol=1e-5) 

1057 

1058 def _runLegacyForFuture(self, raiseOnUndefinedMaskMap=True, handles=None): 

1059 """Build a template from tract 0 with a task configured for the 

1060 future output type, without converting it. 

1061 

1062 The task is kept as ``self.futureTask``. 

1063 

1064 Parameters 

1065 ---------- 

1066 raiseOnUndefinedMaskMap : `bool`, optional 

1067 Value of the task config field of the same name. 

1068 handles : `list` [`lsst.pipe.base.InMemoryDatasetHandle`], optional 

1069 Handles to the tract 0 patches to use instead of the fixture's. 

1070 

1071 Returns 

1072 ------- 

1073 result : `lsst.pipe.base.Struct` 

1074 The legacy output struct. 

1075 box : `lsst.geom.Box2I` 

1076 The bounding box the template was requested on, before the task 

1077 grew it by the template border. 

1078 """ 

1079 config = self._makeConfig() 

1080 config.output_image_type = "future" 

1081 config.raiseOnUndefinedMaskMap = raiseOnUndefinedMaskMap 

1082 task = lsst.ip.diffim.GetTemplateTask(config=config) 

1083 self.visit = 9876 

1084 box = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Point2I(180, 180)) 

1085 result = task.run(coaddExposureHandles={0: self.patches[0] if handles is None else handles}, 

1086 bbox=box, 

1087 wcs=self.exposure.wcs, 

1088 dataIds={0: self.dataIds[0]}, 

1089 physical_filter="a_test", 

1090 visit=self.visit) 

1091 # run() always produces legacy types, whatever output_image_type is. 

1092 self.assertIsInstance(result.template, lsst.afw.image.ExposureF) 

1093 self.futureTask = task 

1094 return result, box 

1095 

1096 def _runFuture(self, handles=None): 

1097 """Build a template and convert it, the way ``runQuantum`` does. 

1098 

1099 Parameters 

1100 ---------- 

1101 handles : `list` [`lsst.pipe.base.InMemoryDatasetHandle`], optional 

1102 Handles to the tract 0 patches to use instead of the fixture's. 

1103 

1104 Returns 

1105 ------- 

1106 result : `lsst.pipe.base.Struct` 

1107 The converted output struct. 

1108 box : `lsst.geom.Box2I` 

1109 The bounding box the template was requested on, before the task 

1110 grew it by the template border. 

1111 """ 

1112 # lsst.images needs per-amplifier raw geometry and a field angle 

1113 # transform, which the trivial test detectors do not have. 

1114 detector = list(lsst.afw.cameraGeom.testUtils.CameraWrapper().camera)[0] 

1115 result, box = self._runLegacyForFuture(handles=handles) 

1116 result.template = self.futureTask.convert_outputs_to_future( 

1117 result.template, self._coaddRefs(0), detector=detector, 

1118 exposureRecord=self._exposureRecord(), templateInputs=result.templateInputs) 

1119 return result, box, detector 

1120 

1121 def _exposureRecord(self): 

1122 """Return the exposure record that ``runQuantum`` rebuilds from the 

1123 observation metadata of the science image. 

1124 """ 

1125 return makeTestExposureRecord(DimensionUniverse(), visit=self.visit) 

1126 

1127 def _coaddRefs(self, tract): 

1128 """Return butler references for the coadds of one tract, like the 

1129 ones ``runQuantum`` passes on from its ``coaddExposures`` input. 

1130 

1131 Parameters 

1132 ---------- 

1133 tract : `int` 

1134 Id of the tract whose coadds to make references for. 

1135 

1136 Returns 

1137 ------- 

1138 refs : `list` [`lsst.daf.butler.DatasetRef`] 

1139 One reference per patch of that tract. The same references are 

1140 returned on every call, because each new one would get a new 

1141 dataset id. 

1142 """ 

1143 if tract not in self.coaddRefs: 

1144 datasetType = DatasetType("template_coadd", ("tract", "patch", "band", "skymap"), 

1145 "ExposureF", universe=DimensionUniverse()) 

1146 self.coaddRefs[tract] = [DatasetRef(datasetType, dataId, run="test_run") 

1147 for dataId in self.dataIds[tract]] 

1148 return self.coaddRefs[tract] 

1149 

1150 def testConvertOutputsToFuture(self): 

1151 """Test that the output template is converted to a DifferenceImage 

1152 that keeps the pixels and the detector it was built on. 

1153 """ 

1154 detector = list(lsst.afw.cameraGeom.testUtils.CameraWrapper().camera)[0] 

1155 result, box = self._runLegacyForFuture() 

1156 legacy = result.template.clone() 

1157 result.template = self.futureTask.convert_outputs_to_future( 

1158 result.template, self._coaddRefs(0), detector=detector, 

1159 exposureRecord=self._exposureRecord()) 

1160 

1161 self.assertIsInstance(result.template, lsst.images.DifferenceImage) 

1162 compare_masked_image_to_legacy(result.template, legacy.maskedImage, 

1163 plane_map=lsst.images.get_legacy_template_mask_planes()) 

1164 self.assertEqual(result.template.unit, u.nJy) 

1165 self.assertIsNotNone(result.template.detector) 

1166 self.assertEqual(result.template.detector.name, detector.getName()) 

1167 # The template is grown by the border, so it is larger than both the 

1168 # requested box and the detector. 

1169 expectedBox = lsst.geom.Box2I(box) 

1170 expectedBox.grow(lsst.ip.diffim.GetTemplateTask.ConfigClass().templateBorderSize) 

1171 self.assertEqual(result.template.bbox.to_legacy(), expectedBox) 

1172 self.assertEqual(result.template.obs_info.visit_id, self.visit) 

1173 

1174 def testConvertOutputsToFutureCoaddMaskPlanes(self): 

1175 """Test that the coadd mask planes a warped template carries are 

1176 converted, and come back when the image is converted to legacy. 

1177 

1178 The template is converted with the template plane map, so the coadd 

1179 planes are named there; the source injection planes are optional, and 

1180 are added because this template has pixels set in them. 

1181 """ 

1182 detector = list(lsst.afw.cameraGeom.testUtils.CameraWrapper().camera)[0] 

1183 planes = ("CLIPPED", "REJECTED", "INEXACT_PSF", "SENSOR_EDGE", "HIGH_VARIANCE", 

1184 "INJECTED", "INJECTED_CORE") 

1185 result, _ = self._runLegacyForFuture() 

1186 mask = result.template.mask 

1187 for n, plane in enumerate(planes): 

1188 mask.addMaskPlane(plane) 

1189 mask.array[0, n] |= mask.getPlaneBitMask(plane) 

1190 legacyTemplate = result.template.clone() 

1191 

1192 result.template = self.futureTask.convert_outputs_to_future( 

1193 result.template, self._coaddRefs(0), detector=detector, 

1194 exposureRecord=self._exposureRecord()) 

1195 

1196 template = result.template 

1197 self.assertIsInstance(template, lsst.images.DifferenceImage) 

1198 # Name the optional planes that have pixels set in the map, so that 

1199 # dropping one fails the comparison instead of skipping it. The others 

1200 # are left out because they may be registered by unrelated tests. 

1201 optional = lsst.images.get_legacy_optional_mask_planes() 

1202 planeMap = lsst.images.get_legacy_template_mask_planes() 

1203 planeMap.update({plane: optional[plane] for plane in planes if plane in optional}) 

1204 compare_masked_image_to_legacy(template, legacyTemplate.maskedImage, plane_map=planeMap) 

1205 # The butler converts a DifferenceImage to an ExposureF with the 

1206 # difference image plane map, which does not name the coadd planes; 

1207 # they keep their own names instead of being dropped. 

1208 legacy = template.to_legacy() 

1209 for n, plane in enumerate(planes): 

1210 with self.subTest(plane=plane): 

1211 self.assertIn(plane, legacy.mask.getMaskPlaneDict()) 

1212 self.assertEqual( 

1213 np.count_nonzero(legacy.mask.array & legacy.mask.getPlaneBitMask(plane)), 1) 

1214 

1215 def _addUnmappedMaskPlane(self, template): 

1216 """Set one pixel in the template's BRIGHT_OBJECT plane, which the 

1217 template plane map does not include, and one in its CLIPPED plane, 

1218 which it does. 

1219 """ 

1220 mask = template.mask 

1221 for n, plane in enumerate(("BRIGHT_OBJECT", "CLIPPED")): 

1222 mask.addMaskPlane(plane) 

1223 mask.array[0, n] |= mask.getPlaneBitMask(plane) 

1224 

1225 def testConvertOutputsToFutureUnmappedMaskPlaneRaises(self): 

1226 """With raiseOnUndefinedMaskMap=True, a template with pixels set in 

1227 an unmapped mask plane cannot be converted. 

1228 """ 

1229 detector = list(lsst.afw.cameraGeom.testUtils.CameraWrapper().camera)[0] 

1230 result, _ = self._runLegacyForFuture() 

1231 self._addUnmappedMaskPlane(result.template) 

1232 with self.assertRaisesRegex(RuntimeError, "BRIGHT_OBJECT"): 

1233 self.futureTask.convert_outputs_to_future( 

1234 result.template, self._coaddRefs(0), detector=detector, 

1235 exposureRecord=self._exposureRecord()) 

1236 

1237 def testConvertOutputsToFutureUnmappedMaskPlaneWarns(self): 

1238 """With raiseOnUndefinedMaskMap=False, an unmapped mask plane is 

1239 dropped with a warning and the mapped planes are kept. 

1240 """ 

1241 detector = list(lsst.afw.cameraGeom.testUtils.CameraWrapper().camera)[0] 

1242 result, _ = self._runLegacyForFuture(raiseOnUndefinedMaskMap=False) 

1243 self._addUnmappedMaskPlane(result.template) 

1244 with self.assertLogs(self.futureTask.log.name, level="WARNING") as cm: 

1245 template = self.futureTask.convert_outputs_to_future( 

1246 result.template, self._coaddRefs(0), detector=detector, 

1247 exposureRecord=self._exposureRecord()) 

1248 self.assertIn("BRIGHT_OBJECT", "\n".join(cm.output)) 

1249 self.assertIsInstance(template, lsst.images.DifferenceImage) 

1250 self.assertNotIn("BRIGHT_OBJECT", template.mask.schema.names) 

1251 self.assertEqual(np.count_nonzero(template.mask.get("CLIPPED")), 1) 

1252 

1253 def testConvertOutputsToFutureLosesProvenance(self): 

1254 """The coadd inputs that `run` attaches are not carried by 

1255 `lsst.images.DifferenceImage`. 

1256 """ 

1257 legacy, _ = self._runLegacyForFuture() 

1258 self.assertTrue(legacy.template.getInfo().hasCoaddInputs()) 

1259 result, _, _ = self._runFuture() 

1260 self.assertFalse(result.template.to_legacy().getInfo().hasCoaddInputs()) 

1261 

1262 def testConvertOutputsToFutureTemplates(self): 

1263 """The coadds that went into the template are recorded on the 

1264 converted image. 

1265 """ 

1266 result, _, _ = self._runFuture() 

1267 refs = {(ref.dataId["tract"], ref.dataId["patch"]): ref for ref in self._coaddRefs(0)} 

1268 

1269 templates = result.template.templates 

1270 self.assertGreater(len(templates), 0) 

1271 for template in templates: 

1272 with self.subTest(tract=template.tract, patch=template.patch): 

1273 ref = refs[template.tract, template.patch] 

1274 self.assertEqual(template.skymap, "skymap") 

1275 self.assertEqual(template.dataset_id, ref.id) 

1276 self.assertEqual(template.dataset_run, ref.run) 

1277 self.assertEqual(template.instrument, "TestCam") 

1278 self.assertFalse(template.psf_shape_flag) 

1279 self.assertGreater(template.psf_shape_xx, 0) 

1280 self.assertGreater(template.bounds.area, 0) 

1281 

1282 def testConvertOutputsToFutureInstrument(self): 

1283 """The template instrument is the one recorded by the coadds that 

1284 know it, or ``"UNKNOWN"`` if none of them do. 

1285 """ 

1286 records = [(self.exposure.wcs, self.exposure.getBBox())] 

1287 handles = (self._patchHandles(0, records, instrument=None)[:1] 

1288 + self._patchHandles(0, records)[1:]) 

1289 result, _, _ = self._runFuture(handles=handles) 

1290 self.assertEqual({template.instrument for template in result.template.templates}, {"TestCam"}) 

1291 

1292 result, _, _ = self._runFuture(handles=self._patchHandles(0, records, instrument=None)) 

1293 self.assertEqual({template.instrument for template in result.template.templates}, {"UNKNOWN"}) 

1294 

1295 def testConvertOutputsToFutureTemplateInputs(self): 

1296 """Each coadd recorded on the converted template lists its inputs. 

1297 """ 

1298 records = [(self.exposure.wcs, self.exposure.getBBox())] 

1299 handles = self._patchHandles(0, records, epochs=[(1, 60000.25, 1.0)]) 

1300 result, _, _ = self._runFuture(handles=handles) 

1301 templates = result.template.templates 

1302 self.assertGreater(len(templates), 0) 

1303 for template in templates: 

1304 with self.subTest(tract=template.tract, patch=template.patch): 

1305 self.assertEqual([(i.visit, i.detector, i.weight) for i in template.inputs], [(1, 0, 1.0)]) 

1306 self.assertFloatsAlmostEqual(template.inputs[0].mid_mjd_tai, 60000.25, rtol=0, atol=1e-6) 

1307 

1308 def testConvertOutputsToFuturePsf(self): 

1309 """The Gaussian PSF set by `run` is kept, defined over the detector. 

1310 """ 

1311 result, _ = self._runLegacyForFuture() 

1312 detector = list(lsst.afw.cameraGeom.testUtils.CameraWrapper().camera)[0] 

1313 legacyPsf = result.template.getPsf() 

1314 

1315 result.template = self.futureTask.convert_outputs_to_future( 

1316 result.template, self._coaddRefs(0), detector=detector, 

1317 exposureRecord=self._exposureRecord()) 

1318 

1319 psf = result.template.psf 

1320 self.assertIsInstance(psf, lsst.images.psfs.GaussianPointSpreadFunction) 

1321 self.assertFloatsAlmostEqual(psf.sigma, legacyPsf.getSigma()) 

1322 self.assertEqual(psf.bounds.to_legacy(), detector.getBBox()) 

1323 self.assertEqual(psf.kernel_bbox.to_legacy().getDimensions(), legacyPsf.getDimensions()) 

1324 

1325 def testConvertOutputsToFuturePsfToLegacy(self): 

1326 """The Gaussian survives conversion back to an Exposure, which is how 

1327 a task that has not been converted reads the template. 

1328 """ 

1329 result, _, _ = self._runFuture() 

1330 

1331 psf = result.template.to_legacy().getPsf() 

1332 self.assertIsInstance(psf, lsst.afw.detection.GaussianPsf) 

1333 self.assertFloatsAlmostEqual(psf.getSigma(), result.template.psf.sigma) 

1334 

1335 

1336class WarpCorrelationFactorTestCase(lsst.utils.tests.TestCase): 

1337 """Test the warping correlation correction on pure noise, with no other 

1338 variance correction. 

1339 """ 

1340 

1341 def setUp(self): 

1342 self.size = 1024 

1343 self.bbox = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Extent2I(self.size, self.size)) 

1344 

1345 def _makeWcs(self, angle, offset): 

1346 """Make a WCS with a fixed plate scale, rotated by ``angle`` degrees 

1347 and with its reference pixel moved by ``offset`` pixels. 

1348 """ 

1349 center = lsst.geom.Point2D(self.size/2 + offset[0], self.size/2 + offset[1]) 

1350 cdMatrix = lsst.afw.geom.makeCdMatrix(0.2*lsst.geom.arcseconds, angle*lsst.geom.degrees) 

1351 return lsst.afw.geom.makeSkyWcs(center, lsst.geom.SpherePoint(45, 30, lsst.geom.degrees), 

1352 cdMatrix) 

1353 

1354 def testCorrelationFactorRestoresNoisePower(self): 

1355 """Warp pure noise to a rotated, offset frame with the coadd kernel, 

1356 then to a third frame with the task's own warper. 

1357 

1358 Warping leaves the variance of a flux summed over a region (the noise 

1359 power) unchanged, but lowers the per-pixel scatter and the variance 

1360 plane. The variance plane is lowered by a larger factor because the 

1361 input to the second warp is already correlated. The correction must 

1362 bring the variance plane back to the noise power of the original image. 

1363 """ 

1364 sigma = 2.0 

1365 rng = np.random.default_rng(42) 

1366 original = lsst.afw.image.ExposureF(self.bbox, self._makeWcs(0, (0, 0))) 

1367 original.image.array[:] = rng.normal(0, sigma, original.image.array.shape) 

1368 original.variance.array[:] = sigma**2 

1369 

1370 config = lsst.ip.diffim.GetTemplateTask.ConfigClass() 

1371 config.doScaleVariance = False 

1372 config.coaddWarpKernel = "lanczos3" 

1373 task = lsst.ip.diffim.GetTemplateTask(config=config) 

1374 coadd = lsst.afw.math.Warper(config.coaddWarpKernel).warpExposure( 

1375 self._makeWcs(37, (0.31, 0.72)), original, destBBox=self.bbox) 

1376 template = task.warper.warpExposure(self._makeWcs(-21, (0.58, 0.23)), coadd, destBBox=self.bbox) 

1377 

1378 # The central quarter is covered in every frame. 

1379 inner = lsst.geom.Box2I(lsst.geom.Point2I(self.size//4, self.size//4), 

1380 lsst.geom.Extent2I(self.size//2, self.size//2)) 

1381 originalStd = original.image[inner].array.std() 

1382 image = template.image[inner].array.astype(float) 

1383 pixelStd = image.std() 

1384 # Each warp moves flux between neighboring pixels but doesn't create 

1385 # or destroy any, so the noise in a flux summed over a region is the 

1386 # same before and after. Summing the image over blocks and measuring 

1387 # how much those sums scatter gives that quantity directly, without 

1388 # depending on the variance plane. Every placement of the block is 

1389 # used, from a summed-area table, to reduce the noise. 

1390 blockSize = 8 

1391 table = np.pad(image.cumsum(axis=0).cumsum(axis=1), ((1, 0), (1, 0))) 

1392 sums = (table[blockSize:, blockSize:] - table[:-blockSize, blockSize:] 

1393 - table[blockSize:, :-blockSize] + table[:-blockSize, :-blockSize]) 

1394 blockStd = sums.std()/blockSize 

1395 planeStdBefore = np.sqrt(template.variance[inner].array.mean()) 

1396 task._correctVariance(template, plateScaleFactor=1.0) 

1397 planeStdAfter = np.sqrt(template.variance[inner].array.mean()) 

1398 factor = task.metadata["varianceWarpCorrelationFactor"] 

1399 

1400 # afw propagates the variance as if each warp's input pixels were 

1401 # independent, so the plane drops by exactly the factor's reciprocal. 

1402 self.assertFloatsAlmostEqual(planeStdBefore, sigma/np.sqrt(factor), rtol=1e-5) 

1403 self.assertFloatsAlmostEqual(planeStdAfter, sigma, rtol=1e-5) 

1404 

1405 # The warps conserve the noise power, which the corrected plane 

1406 # matches. 

1407 self.assertFloatsAlmostEqual(blockStd, originalStd, rtol=0.03) 

1408 self.assertFloatsAlmostEqual(blockStd, planeStdAfter, rtol=0.03) 

1409 

1410 # The per-pixel scatter drops, though by less than the uncorrected 

1411 # plane, because the second warp receives correlated input. The 

1412 # corrected plane deliberately exceeds it. 

1413 self.assertLess(pixelStd, 0.9*originalStd) 

1414 self.assertGreater(pixelStd, planeStdBefore) 

1415 self.assertLess(pixelStd, planeStdAfter) 

1416 

1417 

1418class GetTemplateConnectionsTestCase(lsst.utils.tests.TestCase): 

1419 """Test the connections that ``output_image_type`` switches on. 

1420 

1421 These only need the config classes, not a built template. 

1422 """ 

1423 

1424 def testOutputImageType(self): 

1425 """Test that the future output type changes the template storage 

1426 class, and leaves the input connections alone. 

1427 """ 

1428 Connections = lsst.ip.diffim.GetTemplateTask.ConfigClass.ConnectionsClass 

1429 config = lsst.ip.diffim.GetTemplateTask.ConfigClass() 

1430 

1431 connections = Connections(config=config) 

1432 self.assertEqual(connections.template.storageClass, "ExposureF") 

1433 self.assertNotIn("obs_info", connections.inputs) 

1434 

1435 config.output_image_type = "future" 

1436 connections = Connections(config=config) 

1437 self.assertEqual(connections.template.storageClass, "DifferenceImage") 

1438 # The dataset name is unchanged; only its storage class differs. 

1439 self.assertEqual(connections.template.name, "goodSeeingDiff_templateExp") 

1440 # The detector the conversion needs comes from the science image. 

1441 self.assertEqual(connections.detector.name, "calexp.detector") 

1442 self.assertEqual(connections.detector.storageClass, "Detector") 

1443 # The observation metadata is only read in future mode, where it is 

1444 # the one input the conversion adds. 

1445 self.assertEqual(connections.obs_info.name, "calexp.obs_info") 

1446 self.assertEqual(connections.obs_info.storageClass, "ObservationInfo") 

1447 

1448 def testLintConnections(self): 

1449 """Check that the connections are self-consistent in both modes. 

1450 """ 

1451 for task in (lsst.ip.diffim.GetTemplateTask, lsst.ip.diffim.GetDcrTemplateTask): 

1452 with self.subTest(task=task.__name__): 

1453 lsst.pipe.base.testUtils.lintConnections(task.ConfigClass.ConnectionsClass) 

1454 

1455 

1456def setup_module(module): 

1457 lsst.utils.tests.init() 

1458 

1459 

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

1461 pass 

1462 

1463 

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

1465 lsst.utils.tests.init() 

1466 unittest.main()