Coverage for python/lsst/ip/diffim/getTemplate.py: 77%

506 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-26 12:11 -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/>. 

21import collections 

22import dataclasses 

23import functools 

24 

25import astropy.units 

26from astropy.stats import gaussian_sigma_to_fwhm 

27import numpy as np 

28 

29import lsst.afw.detection as afwDetection 

30import lsst.afw.image as afwImage 

31import lsst.geom as geom 

32import lsst.afw.geom as afwGeom 

33from lsst.afw.image import VisitInfo 

34import lsst.afw.table as afwTable 

35from lsst.afw.math._warper import computeWarpedBBox 

36import lsst.afw.math as afwMath 

37from lsst.daf.base import DateTime 

38import lsst.pex.config as pexConfig 

39import lsst.pex.exceptions 

40import lsst.pipe.base as pipeBase 

41 

42from lsst.images import ( 

43 Box, 

44 DifferenceImage, 

45 DifferenceImageTemplateInfo, 

46 DifferenceImageTemplateInput, 

47 GeneralFrame, 

48 NoOverlapError, 

49 Polygon, 

50 Transform, 

51 get_legacy_optional_mask_planes, 

52 get_legacy_template_mask_planes, 

53) 

54from lsst.skymap import BaseSkyMap 

55from lsst.ip.diffim.dcrModel import DcrModel 

56from lsst.ip.diffim.utils import ( 

57 checkTemplateIsSufficient, 

58 evaluateMeanPsfFwhm, 

59 getPsfFwhm, 

60 record_from_obs_info, 

61) 

62from lsst.meas.algorithms import CoaddPsf, CoaddPsfConfig, SubtractBackgroundTask, ScaleVarianceTask 

63from lsst.utils.timer import timeMethod 

64 

65__all__ = [ 

66 "GetTemplateTask", 

67 "GetTemplateConfig", 

68 "GetDcrTemplateTask", 

69 "GetDcrTemplateConfig", 

70] 

71 

72_PSF_STAMP_SIGMAS = 5 

73"""Width, in N sigma, of the Gaussian approximation to the CoaddPsf.""" 

74 

75_UNKNOWN_INSTRUMENT = "UNKNOWN" 

76"""Instrument recorded for a coadd or template made from observations of an 

77unknown instrument. 

78""" 

79 

80_FOOTPRINT_MARGIN = 32.0 

81"""Distance, in coadd pixels, by which the science image's footprint in a 

82coadd is grown before a coadd input is clipped to it. It must exceed twice 

83the distance by which a distorted science image edge departs from a straight 

84line between its corners, and limits how far outside the science image its 

85WCS is evaluated. 

86""" 

87 

88 

89def _pixelTransform(fromWcs, toWcs): 

90 """Return a chainable transformation between two pixel frames. 

91 

92 Parameters 

93 ---------- 

94 fromWcs, toWcs : `lsst.afw.geom.SkyWcs` 

95 WCSs of the input and output pixels. 

96 

97 Returns 

98 ------- 

99 transform : `lsst.images.Transform` 

100 Transform from ``fromWcs`` pixels to ``toWcs`` pixels. 

101 """ 

102 return Transform.from_legacy(afwGeom.makeWcsPairTransform(fromWcs, toWcs), 

103 GeneralFrame(unit=astropy.units.pix), 

104 GeneralFrame(unit=astropy.units.pix) 

105 ) 

106 

107 

108def _getImageOverlap(record, coaddWcs, scienceFootprint, coaddToScienceTransform, scienceBox, border): 

109 """Return the region enclosing the overlap of the science image and one 

110 input image of the coadd. 

111 

112 Note that there are three different WCS's involved here: the WCS of the 

113 original image that was warped to contribute to the coadd, the coadd WCS, 

114 and the current science image WCS that we are building a template for. 

115 

116 Parameters 

117 ---------- 

118 record : `lsst.afw.table.ExposureRecord` 

119 Input record of a coadd, with the input's WCS, bounding box and 

120 optional valid polygon. 

121 coaddWcs : `lsst.afw.geom.SkyWcs` 

122 WCS of the coadd. 

123 scienceFootprint : `lsst.images.Region` 

124 ``scienceBox`` in coadd pixels, grown by ``_FOOTPRINT_MARGIN``. 

125 coaddToScienceTransform : `lsst.images.Transform` 

126 Transform from coadd pixels to science image pixels. 

127 scienceBox : `lsst.images.Box` 

128 Bounding box of the science image. 

129 border : `float` 

130 Width, in input pixels, of the border of the input that warping left 

131 out of the coadd. 

132 

133 Returns 

134 ------- 

135 footprint : `lsst.images.Polygon` or `None` 

136 The part of ``scienceBox`` the input's warp covers, in science image 

137 pixels, or `None` if it covers none of it. 

138 """ 

139 inputBox = geom.Box2D(record.getBBox()) 

140 inputBox.grow(-border) 

141 inputBounds = Polygon.from_legacy(afwGeom.Polygon(inputBox)) 

142 polygon = record.getValidPolygon() 

143 inputToCoadd = _pixelTransform(record.getWcs(), coaddWcs) 

144 try: 

145 if polygon is not None: 145 ↛ 146line 145 didn't jump to line 146 because the condition on line 145 was never true

146 inputBounds = inputBounds.intersection(Polygon.from_legacy(polygon)) 

147 # Only vertices are transformed, so the edges of the input stay 

148 # straight. 

149 footprint = ( 

150 inputBounds.transform(inputToCoadd) 

151 .intersection(scienceFootprint) 

152 .transform(coaddToScienceTransform) 

153 ) 

154 # The convex hull keeps the footprint in one piece when it is clipped. 

155 footprint = footprint.convex_hull().intersection(scienceBox) 

156 except NoOverlapError: 

157 return None 

158 return Polygon.from_box(footprint) if isinstance(footprint, Box) else footprint 

159 

160 

161def _warpBorder(kernelName): 

162 """Return the width of the border of an image that warping leaves out. 

163 

164 A warped pixel is computed only where the whole kernel lies on the image. 

165 

166 Parameters 

167 ---------- 

168 kernelName : `str` 

169 Name of the warping kernel, as `lsst.afw.math.Warper` takes it. 

170 

171 Returns 

172 ------- 

173 border : `float` 

174 Width of the border on each side, in pixels from the edge of the 

175 image's bounding box; 2.5 for ``lanczos3``. 

176 """ 

177 kernel = afwMath.WarpingControl(kernelName).getWarpingKernel() 

178 return kernel.getCtr().getX() + 0.5 

179 

180 

181@functools.cache 

182def _warpKernelSumSq(kernelName, nPhase=100): 

183 """Compute the phase-averaged sum of squared values of a warping kernel. 

184 

185 Warping with a kernel normalized to unit sum multiplies the variance by 

186 this sum, which is less than one. The power the warp took off the 

187 diagonal became covariance between neighboring pixels, which a variance 

188 plane cannot represent, so dividing by it restores the noise power: the 

189 variance of a flux measured over a region and not a single pixel. 

190 

191 Parameters 

192 ---------- 

193 kernelName : `str` 

194 Name of the warping kernel, as `lsst.afw.math.Warper` takes it. 

195 nPhase : `int`, optional 

196 Number of sub-pixel phases to average over. 

197 

198 Returns 

199 ------- 

200 sumSq : `float` 

201 Sum of the squared 2-D kernel values, averaged over sub-pixel 

202 phase. Converges with large ``nPhase`` to 0.798 for ``lanczos3``, 

203 4/9 for ``bilinear``, and 1 for no interpolation. 

204 

205 Notes 

206 ----- 

207 The kernels are separable and the phases of the two axes independent, 

208 so this is the square of the 1-D average. The warper normalizes the 

209 kernel to unit sum at each phase, which the analytic Lanczos integral 

210 does not include, so the average is computed from the kernel itself. 

211 """ 

212 # Disable the cache since we are evaluating fewer phase points than the 

213 # default cache size. 

214 kernel = afwMath.Warper(kernelName, cacheSize=0).getWarpingKernel() 

215 image = afwImage.ImageD(kernel.getDimensions()) 

216 total = 0.0 

217 for phase in (np.arange(nPhase) + 0.5)/nPhase: 

218 kernel.setKernelParameters((float(phase), 0.0)) 

219 kernel.computeImage(image, doNormalize=True) 

220 total += float((image.array.sum(axis=0)**2).sum()) 

221 return (total/nPhase)**2 

222 

223 

224class GetTemplateConnections( 

225 pipeBase.PipelineTaskConnections, 

226 dimensions=("instrument", "visit", "detector"), 

227 defaultTemplates={"coaddName": "goodSeeing", "warpTypeSuffix": "", "fakesType": ""}, 

228): 

229 bbox = pipeBase.connectionTypes.Input( 

230 doc="Bounding box of exposure to determine the geometry of the output template.", 

231 name="{fakesType}calexp.bbox", 

232 storageClass="Box2I", 

233 dimensions=("instrument", "visit", "detector"), 

234 deprecated="Replaced by the `detector` connection. Will be removed after v31.", 

235 ) 

236 detector = pipeBase.connectionTypes.Input( 

237 doc="Detector of the exposure that we will construct the template for." 

238 " Its bounding box sets the geometry of the output template.", 

239 name="{fakesType}calexp.detector", 

240 storageClass="Detector", 

241 dimensions=("instrument", "visit", "detector"), 

242 ) 

243 obs_info = pipeBase.connectionTypes.Input( 

244 doc="Observation metadata of the exposure the template is built for." 

245 " Only read with output_image_type='future', which needs this to set" 

246 " the obs_info component of a lsst.images.VisitImage.", 

247 name="{fakesType}calexp.obs_info", 

248 storageClass="ObservationInfo", 

249 dimensions=("instrument", "visit", "detector"), 

250 ) 

251 wcs = pipeBase.connectionTypes.Input( 

252 doc="WCS of the exposure that we will construct the template for.", 

253 name="{fakesType}calexp.wcs", 

254 storageClass="Wcs", 

255 dimensions=("instrument", "visit", "detector"), 

256 ) 

257 skyMap = pipeBase.connectionTypes.Input( 

258 doc="Geometry of the tracts and patches that the coadds are defined on.", 

259 name=BaseSkyMap.SKYMAP_DATASET_TYPE_NAME, 

260 dimensions=("skymap",), 

261 storageClass="SkyMap", 

262 ) 

263 coaddExposures = pipeBase.connectionTypes.Input( 

264 doc="Coadds that may overlap the desired region, as possible inputs to the template." 

265 " Will be restricted to those that directly overlap the projected bounding box.", 

266 dimensions=("tract", "patch", "skymap", "band"), 

267 storageClass="ExposureF", 

268 name="{fakesType}{coaddName}Coadd{warpTypeSuffix}", 

269 multiple=True, 

270 deferLoad=True, 

271 deferGraphConstraint=True, 

272 ) 

273 

274 template = pipeBase.connectionTypes.Output( 

275 doc="Warped template, pixel matched to the bounding box and WCS.", 

276 dimensions=("instrument", "visit", "detector"), 

277 storageClass="ExposureF", 

278 name="{fakesType}{coaddName}Diff_templateExp{warpTypeSuffix}", 

279 ) 

280 

281 def __init__(self, *, config=None): 

282 super().__init__(config=config) 

283 # Kept only so that older config files still load. 

284 del self.bbox 

285 if config.requireCoaddAtGraphBuild: 285 ↛ 286line 285 didn't jump to line 286 because the condition on line 285 was never true

286 self.coaddExposures = dataclasses.replace( 

287 self.coaddExposures, 

288 deferGraphConstraint=False, 

289 ) 

290 if config.output_image_type == "future": 

291 self.template = dataclasses.replace(self.template, storageClass="DifferenceImage") 

292 else: 

293 del self.obs_info 

294 

295 

296class GetTemplateConfig( 

297 pipeBase.PipelineTaskConfig, pipelineConnections=GetTemplateConnections 

298): 

299 templateBorderSize = pexConfig.Field( 

300 dtype=int, 

301 default=20, 

302 doc="Number of pixels to grow the requested template image to account for warping", 

303 ) 

304 warp = pexConfig.ConfigField( 

305 dtype=afwMath.Warper.ConfigClass, 

306 doc="warper configuration", 

307 ) 

308 doCorrectVarianceWarpCorrelation = pexConfig.Field( 

309 dtype=bool, 

310 default=True, 

311 doc="Correct the template variance for the correlation that warping" 

312 " introduced between neighboring pixels? This covers both warps: the" 

313 " one that built the coadds, named by coaddWarpKernel, and the one" 

314 " this task performs, named by warp.warpingKernelName. It is a single" 

315 " scalar factor, fixed entirely by those two kernels and independent" 

316 " of the pixel scales involved.", 

317 ) 

318 coaddWarpKernel = pexConfig.ChoiceField( 

319 dtype=str, 

320 default="lanczos3", 

321 allowed={ 

322 "bilinear": "bilinear interpolation", 

323 "lanczos3": "Lanczos kernel of order 3", 

324 "lanczos4": "Lanczos kernel of order 4", 

325 "lanczos5": "Lanczos kernel of order 5", 

326 }, 

327 doc="Warping kernel that was used to build the input coadds. This" 

328 " cannot be recovered from the coadds themselves. It is used to" 

329 " correct the variance if doCorrectVarianceWarpCorrelation is True," 

330 " and to trim the coadd inputs bboxes to account for the size of the" 

331 " warping kernel.", 

332 ) 

333 coaddPsf = pexConfig.ConfigField( 

334 doc="Configuration for CoaddPsf", 

335 dtype=CoaddPsfConfig, 

336 ) 

337 fwhmExposureGrid = pexConfig.Field( 

338 doc="Grid size to compute the average PSF FWHM in an exposure (pixels)", 

339 dtype=int, 

340 default=10, 

341 ) 

342 fwhmExposureBuffer = pexConfig.Field( 

343 doc="Fractional buffer margin to be left out of all sides of the image during construction" 

344 " of grid to compute average PSF FWHM in an exposure", 

345 dtype=float, 

346 default=0.05, 

347 ) 

348 minTemplateFractionForExpectedSuccess = pexConfig.Field( 

349 doc="Raise NoWorkFound if the template PSF cannot be evaluated and less than this fraction" 

350 " of the template pixels have data. With more coverage, the PSF error is raised.", 

351 dtype=float, 

352 default=0.1, 

353 ) 

354 varianceBackground = pexConfig.ConfigurableField( 

355 target=SubtractBackgroundTask, 

356 doc="Task to estimate the background variance.", 

357 ) 

358 highVarianceThreshold = pexConfig.RangeField( 

359 dtype=float, 

360 default=4, 

361 min=1, 

362 doc="Set the HIGH_VARIANCE mask plane for regions with variance" 

363 " greater than the median by this factor.", 

364 ) 

365 highVarianceMaskFraction = pexConfig.Field( 

366 dtype=float, 

367 default=0.1, 

368 doc="Minimum fraction of unmasked pixels needed to set the" 

369 " HIGH_VARIANCE mask plane.", 

370 ) 

371 doScaleVariance = pexConfig.Field( 

372 dtype=bool, 

373 default=False, 

374 doc="Scale the variance of the template image to match its per-pixel" 

375 " scatter? Warping correlates the noise, so when combined with" 

376 " doCorrectVarianceWarpCorrelation this overcounts the correction.", 

377 ) 

378 scaleVariance = pexConfig.ConfigurableField( 

379 target=ScaleVarianceTask, 

380 doc="Subtask to rescale the variance of the template to the statistically expected level." 

381 ) 

382 requireCoaddAtGraphBuild = pexConfig.Field( 

383 dtype=bool, 

384 default=False, 

385 doc="If True, include the coadd dataset existence in the" 

386 " initial butler query during QuantumGraph generation.", 

387 ) 

388 output_image_type = pexConfig.ChoiceField[str]( 

389 "Which image type to use for the output template.", 

390 allowed={ 

391 "legacy": "Write as a lsst.afw.image.ExposureF.", 

392 "future": "Write as a lsst.images.DifferenceImage.", 

393 }, 

394 optional=False, 

395 default="legacy", 

396 ) 

397 raiseOnUndefinedMaskMap = pexConfig.Field( 

398 dtype=bool, 

399 default=False, 

400 doc="Raise if the template has pixels set in a mask plane that" 

401 " `lsst.images` does not map? If False, log a warning and drop that" 

402 " plane from the output instead." 

403 " Only used with output_image_type='future'.", 

404 ) 

405 

406 def setDefaults(self): 

407 # Use a smaller cache: per SeparableKernel.computeCache, this should 

408 # give a warping error of a fraction of a count (these must match). 

409 self.warp.cacheSize = 100000 

410 self.coaddPsf.cacheSize = self.warp.cacheSize 

411 # The WCS for LSST should be smoothly varying, so we can use a longer 

412 # interpolation length for WCS evaluations. 

413 self.warp.interpLength = 100 

414 self.warp.warpingKernelName = "lanczos3" 

415 self.coaddPsf.warpingKernelName = self.warp.warpingKernelName 

416 

417 # Background subtraction of the variance plane 

418 self.varianceBackground.algorithm = "LINEAR" 

419 self.varianceBackground.binSize = 32 

420 self.varianceBackground.useApprox = False 

421 self.varianceBackground.statisticsProperty = "MEDIAN" 

422 self.varianceBackground.doFilterSuperPixels = True 

423 self.varianceBackground.ignoredPixelMask = ["BAD", 

424 "EDGE", 

425 "DETECTED", 

426 "DETECTED_NEGATIVE", 

427 "NO_DATA", 

428 ] 

429 

430 

431class GetTemplateTask(pipeBase.PipelineTask): 

432 ConfigClass = GetTemplateConfig 

433 _DefaultName = "getTemplate" 

434 

435 def __init__(self, *args, **kwargs): 

436 super().__init__(*args, **kwargs) 

437 if self.config.doScaleVariance: 

438 self.makeSubtask("scaleVariance") 

439 self.warper = afwMath.Warper.fromConfig(self.config.warp) 

440 self.schema = afwTable.ExposureTable.makeMinimalSchema() 

441 self.schema.addField( 

442 "tract", type=np.int32, doc="Which tract this exposure came from." 

443 ) 

444 self.schema.addField( 

445 "patch", 

446 type=np.int32, 

447 doc="Which patch in the tract this exposure came from.", 

448 ) 

449 self.schema.addField( 

450 "weight", 

451 type=float, 

452 doc="Weight for each exposure, used to make the CoaddPsf; should always be 1.", 

453 ) 

454 self.schema.addField( 

455 "instrument", 

456 type=str, 

457 size=64, 

458 doc="Instrument whose observations were coadded to make the template, or UNKNOWN.", 

459 ) 

460 self.makeSubtask("varianceBackground") 

461 

462 def runQuantum(self, butlerQC, inputRefs, outputRefs): 

463 inputs = butlerQC.get(inputRefs) 

464 detector = inputs.pop("detector") 

465 bbox = detector.getBBox() 

466 wcs = inputs.pop("wcs") 

467 obsInfo = inputs.pop("obs_info", None) 

468 coaddExposures = inputs.pop("coaddExposures") 

469 skymap = inputs.pop("skyMap") 

470 

471 # This should not happen with a properly configured execution context. 

472 assert not inputs, "runQuantum got more inputs than expected" 

473 

474 results = self.getExposures(coaddExposures, bbox, skymap, wcs) 

475 physical_filter = butlerQC.quantum.dataId["physical_filter"] 

476 outputs = self.run( 

477 coaddExposureHandles=results.coaddExposures, 

478 bbox=bbox, 

479 wcs=wcs, 

480 dataIds=results.dataIds, 

481 physical_filter=physical_filter, 

482 visit=outputRefs.template.dataId["visit"], 

483 instrument=butlerQC.quantum.dataId["instrument"], 

484 ) 

485 if self.config.output_image_type == "future": 

486 dataId = butlerQC.quantum.dataId 

487 exposureRecord = record_from_obs_info(obsInfo, dataId["instrument"], dataId["visit"], 

488 dataId.universe) 

489 outputs.template = self.convert_outputs_to_future(outputs.template, 

490 inputRefs.coaddExposures, 

491 detector=detector, 

492 exposureRecord=exposureRecord, 

493 templateInputs=outputs.templateInputs) 

494 butlerQC.put(outputs, outputRefs) 

495 

496 def convert_outputs_to_future(self, template, coadd_refs, detector, exposureRecord, 

497 templateInputs=None): 

498 """Convert a template image to DifferenceImage format. 

499 

500 This replaces ``template`` with an `lsst.images.DifferenceImage` 

501 instance and records the coadds contributed to it, along with the 

502 instrument they were made from and their input image identifiers. 

503 The Gaussian PSF set by `run` is converted to an 

504 `lsst.images.psfs.GaussianPointSpreadFunction`. 

505 

506 Parameters 

507 ---------- 

508 template : `lsst.afw.image.Exposure` 

509 Template to convert. Its detector is replaced with ``detector`` 

510 and its mask is modified in place. 

511 coadd_refs : `list` [`lsst.daf.butler.DatasetRef`] 

512 References to the coadds that may have gone into the template. 

513 May be a superset of the coadds that were used; supplies the 

514 dataset id and RUN collection recorded for each coadd that was. 

515 detector : `lsst.afw.cameraGeom.Detector` 

516 Detector of the science image that the template was built for. 

517 exposureRecord : `lsst.daf.butler.DimensionRecord` 

518 The ``exposure`` record of the observation the template was built 

519 for, which supplies the observation metadata recorded on the 

520 output. 

521 templateInputs : `dict` [`tuple` [`int`, `int`], \ 

522 `list` [`lsst.images.DifferenceImageTemplateInput`]], optional 

523 Input image records of each coadd, keyed by tract and patch, as 

524 returned by `run`. Coadds not listed record no inputs. 

525 

526 Returns 

527 ------- 

528 convertedTemplate : `lsst.images.DifferenceImage` 

529 The converted image. 

530 

531 Raises 

532 ------ 

533 RuntimeError 

534 Raised if the template has pixels set in a mask plane that 

535 `lsst.images.get_legacy_template_mask_planes` does not map and 

536 ``config.raiseOnUndefinedMaskMap`` is True, or if ``coadd_refs`` 

537 spans more than one skymap. 

538 """ 

539 # The template PSF is a Gaussian, so rebuild the CoaddPsf from the 

540 # template inputs to record which coadds contributed. 

541 catalog = template.getInfo().getCoaddInputs().ccds 

542 coaddPsf = self._makePsf(template, catalog, template.getWcs()) 

543 # `run` records the template's instrument on every input. 

544 instrument = catalog[0]["instrument"] 

545 template.setDetector(detector) 

546 skymaps = {ref.dataId["skymap"] for ref in coadd_refs} 

547 if len(skymaps) != 1: 547 ↛ 548line 547 didn't jump to line 548 because the condition on line 547 was never true

548 raise RuntimeError("Expected the template inputs to come from one skymap;" 

549 f" got {sorted(skymaps)}.") 

550 butler_info = {(ref.dataId["tract"], ref.dataId["patch"]): (ref.id, ref.run) 

551 for ref in coadd_refs} 

552 planeMap = get_legacy_template_mask_planes() 

553 if not self.config.raiseOnUndefinedMaskMap: 

554 self._clearUnmappedMaskPlanes(template.mask, planeMap) 

555 convertedTemplate = DifferenceImage.from_legacy( 

556 template, 

557 exposure_record=exposureRecord, 

558 unit=astropy.units.nJy, 

559 plane_map=planeMap, 

560 ) 

561 del template 

562 convertedTemplate.templates = DifferenceImageTemplateInfo.from_legacy_psf( 

563 convertedTemplate.sky_projection.pixel_frame, 

564 coaddPsf, 

565 skymaps.pop(), 

566 butler_info, 

567 log=self.log, 

568 instrument=instrument, 

569 ) 

570 if templateInputs: 

571 for info in convertedTemplate.templates: 

572 info.inputs = templateInputs.get((info.tract, info.patch), []) 

573 return convertedTemplate 

574 

575 def _clearUnmappedMaskPlanes(self, mask, planeMap): 

576 """Clear the pixels of every mask plane that conversion would reject. 

577 

578 Parameters 

579 ---------- 

580 mask : `lsst.afw.image.Mask` 

581 Template mask to modify in place. 

582 planeMap : `dict` [`str`, `lsst.images.MaskPlane`] 

583 Plane map the template will be converted with. The optional 

584 planes of `lsst.images.get_legacy_optional_mask_planes` are kept 

585 as well, since conversion adds them when they have pixels set. 

586 """ 

587 keep = planeMap.keys() | get_legacy_optional_mask_planes().keys() 

588 for name in mask.getMaskPlaneDict(): 

589 if name in keep: 

590 continue 

591 bitmask = mask.getPlaneBitMask(name) 

592 nSet = np.count_nonzero(mask.array & bitmask) 

593 if nSet: 

594 self.log.warning("Dropping mask plane %s from the template: %d pixels are set, but" 

595 " the template plane map does not include it.", name, nSet) 

596 mask.array &= ~bitmask 

597 

598 def getExposures(self, coaddExposureHandles, bbox, skymap, wcs): 

599 """Return a data structure containing the coadds that overlap the 

600 specified bbox projected onto the sky, and a corresponding data 

601 structure of their dataIds. 

602 These are the appropriate inputs to this task's `run` method. 

603 

604 The spatial index in the butler registry has generous padding and often 

605 supplies patches near, but not directly overlapping the desired region. 

606 This method filters the inputs so that `run` does not have to read in 

607 all possibly-matching coadd exposures. 

608 

609 Parameters 

610 ---------- 

611 coaddExposureHandles : `iterable` \ 

612 [`lsst.daf.butler.DeferredDatasetHandle` of \ 

613 `lsst.afw.image.Exposure`] 

614 Dataset handles to exposures that might overlap the desired 

615 region. 

616 bbox : `lsst.geom.Box2I` 

617 Template bounding box of the pixel geometry onto which the 

618 coaddExposures will be resampled. 

619 skymap : `lsst.skymap.SkyMap` 

620 Geometry of the tracts and patches the coadds are defined on. 

621 wcs : `lsst.afw.geom.SkyWcs` 

622 Template WCS onto which the coadds will be resampled. 

623 

624 Returns 

625 ------- 

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

627 A struct with attributes: 

628 

629 ``coaddExposures`` 

630 Dict of coadd exposures that overlap the projected bbox, 

631 indexed on tract id 

632 (`dict` [`int`, `list` [`lsst.daf.butler.DeferredDatasetHandle` of 

633 `lsst.afw.image.Exposure`] ]). 

634 ``dataIds`` 

635 Dict of data IDs of the coadd exposures that overlap the 

636 projected bbox, indexed on tract id 

637 (`dict` [`int`, `list [`lsst.daf.butler.DataCoordinate`] ]). 

638 

639 Raises 

640 ------ 

641 NoWorkFound 

642 Raised if no patches overlap the input detector bbox, or the input 

643 WCS is None. 

644 """ 

645 if wcs is None: 

646 raise pipeBase.NoWorkFound( 

647 "WCS is None; cannot find overlapping exposures." 

648 ) 

649 

650 # Exposure's validPolygon would be more accurate 

651 detectorPolygon = geom.Box2D(bbox) 

652 detectorCorners = wcs.pixelToSky(detectorPolygon.getCorners()) 

653 overlappingArea = 0 

654 coaddExposures = collections.defaultdict(list) 

655 dataIds = collections.defaultdict(list) 

656 

657 for coaddRef in coaddExposureHandles: 

658 dataId = coaddRef.dataId 

659 patchWcs = skymap[dataId["tract"]].getWcs() 

660 patchBBox = skymap[dataId["tract"]][dataId["patch"]].getOuterBBox() 

661 patchPolygon = afwGeom.Polygon(geom.Box2D(patchBBox)) 

662 # Calculate detector/patch overlap in patch coordinates rather than 

663 # detector coordinates because the skymap's inverse mapping 

664 # (patchWcs.skyToPixel()) is more stable than the detector's for 

665 # arbitrary sky coordinates. 

666 detectorInPatchCoordinates = afwGeom.Polygon(patchWcs.skyToPixel(detectorCorners)) 

667 if patchPolygon.intersection(detectorInPatchCoordinates): 

668 overlappingArea += patchPolygon.intersectionSingle( 

669 detectorInPatchCoordinates 

670 ).calculateArea() 

671 self.log.info( 

672 "Using template input tract=%s, patch=%s", 

673 dataId["tract"], 

674 dataId["patch"], 

675 ) 

676 coaddExposures[dataId["tract"]].append(coaddRef) 

677 dataIds[dataId["tract"]].append(dataId) 

678 

679 if not overlappingArea: 

680 raise pipeBase.NoWorkFound("No patches overlap detector") 

681 

682 return pipeBase.Struct(coaddExposures=coaddExposures, dataIds=dataIds) 

683 

684 @timeMethod 

685 def run(self, *, coaddExposureHandles, bbox, wcs, dataIds, physical_filter, visit=None, instrument=None): 

686 """Warp coadds from multiple tracts and patches to form a template to 

687 subtract from a science image. 

688 

689 Tract and patch overlap regions are combined by a variance-weighted 

690 average, and the variance planes are combined with the same weights, 

691 not added in quadrature; the overlap regions are not statistically 

692 independent, because they're derived from the same original data. 

693 The PSF of the template is a Gaussian with the same width as the 

694 CoaddPsf evaluated at the center of the detector. 

695 

696 The template is built from coadds of one instrument: the science 

697 image's ``instrument`` if any coadd was made from it, and otherwise the 

698 one that most of the coadds were made from. Coadds made from another 

699 instrument are dropped, and so are coadds that record no instrument 

700 unless none of the coadds records one. 

701 

702 Parameters 

703 ---------- 

704 coaddExposureHandles : `dict` [`int`, `list` of \ 

705 [`lsst.daf.butler.DeferredDatasetHandle` of \ 

706 `lsst.afw.image.Exposure`]] 

707 Coadds to be mosaicked, indexed on tract id. 

708 bbox : `lsst.geom.Box2I` 

709 Input Bounding box of the detector geometry onto which to 

710 resample the ``coaddExposureHandles``. The output template bbox 

711 will be grown by ``templateBorderSize``. 

712 wcs : `lsst.afw.geom.SkyWcs` 

713 Template WCS onto which to resample the ``coaddExposureHandles``. 

714 dataIds : `dict` [`int`, `list` [`lsst.daf.butler.DataCoordinate`]] 

715 Record of the tract and patch of each coaddExposure, indexed on 

716 tract id. 

717 physical_filter : `str` 

718 Physical filter of the science image. 

719 visit : `int`, optional 

720 If supplied, over-write the visit ID in the template's visitInfo 

721 so that downstream source injection tasks can link the template and 

722 science image for the visit. 

723 instrument : `str`, optional 

724 Instrument of the science image. Coadds made from it are used in 

725 preference to coadds from any other instrument. 

726 

727 Returns 

728 ------- 

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

730 A struct with attributes: 

731 

732 ``template`` 

733 A template coadd exposure assembled out of patches, with 

734 pixels in nJy. Its PSF is a Gaussian approximation to the 

735 CoaddPsf of its inputs (`lsst.afw.image.ExposureF`). 

736 ``templateInputs`` 

737 Input image records of each coadd that cover part of the 

738 science image, keyed by tract and patch (`dict` 

739 [`tuple` [`int`, `int`], 

740 `list` [`lsst.images.DifferenceImageTemplateInput`]]). Empty 

741 unless ``config.output_image_type`` is ``"future"``. 

742 

743 Raises 

744 ------ 

745 NoWorkFound 

746 If no coadds are found with sufficient un-masked pixels, or if the 

747 template PSF cannot be evaluated and too few of the template pixels 

748 have data. 

749 lsst.afw.detection.InvalidPsfError 

750 If the template PSF cannot be evaluated and the template has 

751 enough coverage that it was expected to succeed. 

752 RuntimeError 

753 If the template is not known to be from the science image's 

754 instrument and no coadd records the plate scale of its input 

755 images, so the template variance cannot be corrected. 

756 """ 

757 band, photoCalib, templateInstrument = self._checkInputs(dataIds, coaddExposureHandles, instrument) 

758 

759 scienceBBox = bbox 

760 bbox = geom.Box2I(bbox) 

761 bbox.grow(self.config.templateBorderSize) 

762 

763 warped = {} 

764 catalogs = [] 

765 inputs = [] 

766 plateScaleFactor = 1.0 if instrument == templateInstrument else None 

767 

768 for tract in coaddExposureHandles: 

769 maskedImages, catalog, totalBox, coaddInputs = self._makeExposureCatalog( 

770 coaddExposureHandles[tract], dataIds[tract], templateInstrument 

771 ) 

772 if len(catalog) == 0: 

773 # Every coadd in this tract was dropped for its instrument. 

774 continue 

775 # Determine the ratio of the original pixel area to the pixel area 

776 # of the science image. This will only be different from 1 if the 

777 # coadd was from a different instrument. A single correction factor 

778 # is calculated from the first usable coadd and applied to all. 

779 if plateScaleFactor is None: 

780 plateScaleFactor = self._plateScaleFactor(coaddInputs[0], wcs, bbox) 

781 warpedBox = computeWarpedBBox(catalog[0].wcs, bbox, wcs) 

782 warpedBox.grow(5) # to ensure we catch all relevant input pixels 

783 # Combine images from individual patches together. 

784 unwarped, count, included = self._merge( 

785 maskedImages, warpedBox, catalog[0].wcs 

786 ) 

787 # Delete `maskedImages` after combining into one large image to reduce peak memory use 

788 del maskedImages 

789 if count == 0: 

790 self.log.info( 

791 "No valid pixels from coadd patches in tract %s; not including in output.", 

792 tract, 

793 ) 

794 continue 

795 warpedBox.clip(totalBox) 

796 potentialInput = self.warper.warpExposure( 

797 wcs, unwarped.subset(warpedBox), destBBox=bbox 

798 ) 

799 # Delete the single large `unwarped` image after warping to reduce peak memory use 

800 del unwarped 

801 if np.all( 

802 potentialInput.mask.array 

803 & potentialInput.mask.getPlaneBitMask("NO_DATA") 

804 ): 

805 self.log.info( 

806 "No overlap from coadd patches in tract %s; not including in output.", 

807 tract, 

808 ) 

809 continue 

810 

811 # Trim the exposure catalog to just the patches that were used. 

812 tempCatalog = afwTable.ExposureCatalog(self.schema) 

813 tempCatalog.reserve(len(included)) 

814 for i in included: 

815 tempCatalog.append(catalog[i]) 

816 inputs.append(coaddInputs[i]) 

817 catalogs.append(tempCatalog) 

818 warped[tract] = potentialInput.maskedImage 

819 

820 if len(warped) == 0: 

821 raise pipeBase.NoWorkFound("No patches found to overlap science exposure.") 

822 

823 # At this point, all entries will be valid, so we can ignore included. 

824 template, count, _ = self._merge(warped, bbox, wcs) 

825 if count == 0: 825 ↛ 826line 825 didn't jump to line 826 because the condition on line 825 was never true

826 raise pipeBase.NoWorkFound("No valid pixels in warped template.") 

827 

828 if self.config.doScaleVariance: 

829 # Scale the variance of the template image before subtraction, if 

830 # needed. Note that the science variance is scaled 

831 # independently in ``AlardLuptonSubtractTask``. 

832 varianceFactor = self.scaleVariance.run(template.maskedImage) 

833 self.log.info("Template variance scaling factor: %.2f", varianceFactor) 

834 self.metadata["scaleTemplateVarianceFactor"] = varianceFactor 

835 

836 self._correctVariance(template, plateScaleFactor) 

837 

838 # Make a single catalog containing all the inputs that were accepted. 

839 catalog = afwTable.ExposureCatalog(self.schema) 

840 catalog.reserve(sum([len(c) for c in catalogs])) 

841 for c in catalogs: 

842 catalog.extend(c) 

843 # Only the future output type records the inputs. 

844 if self.config.output_image_type == "future": 

845 templateInputs = self._collectTemplateInputs(catalog, inputs, wcs, scienceBBox) 

846 else: 

847 templateInputs = {} 

848 

849 # Set a mask plane for any regions with exceptionally high variance. 

850 self.checkHighVariance(template) 

851 if visit is not None: 

852 template.getInfo().setVisitInfo(VisitInfo(id=visit)) 

853 template.setFilter(afwImage.FilterLabel(band, physical_filter)) 

854 identity = afwImage.PhotoCalib(1.0) 

855 if photoCalib is not None and photoCalib != identity: 

856 template.maskedImage = photoCalib.calibrateImage(template.maskedImage) 

857 photoCalib = identity 

858 template.setPhotoCalib(photoCalib) 

859 template.setPsf(self._makePsf(template, catalog, wcs)) 

860 try: 

861 template.setPsf(self._makeGaussianPsf(template)) 

862 except afwDetection.InvalidPsfError as e: 

863 # Raise NoWorkFound if the template coverage is insufficient. 

864 checkTemplateIsSufficient( 

865 template, self.log, 

866 requiredTemplateFraction=self.config.minTemplateFractionForExpectedSuccess, 

867 exceptionMessage="Template coverage lower than expected to succeed." 

868 f" Failure is tolerable: {e}" 

869 ) 

870 # checkTemplateIsSufficient did not raise NoWorkFound, so raise 

871 # the original exception. 

872 raise 

873 

874 # Record the input coadd patches as the template's coadd inputs. 

875 coaddInputs = afwImage.CoaddInputs(afwTable.ExposureTable.makeMinimalSchema(), self.schema) 

876 coaddInputs.ccds.extend(catalog, deep=True) 

877 template.getInfo().setCoaddInputs(coaddInputs) 

878 return pipeBase.Struct(template=template, templateInputs=templateInputs) 

879 

880 def _correctVariance(self, template, plateScaleFactor): 

881 """Correct the template variance plane for the effects of warping. 

882 

883 Warping introduces a covariance between neighboring pixels, while the 

884 input variance plane captures only the diagonal term. Compute a 

885 multiplicative correction factor to apply to the final variance so that 

886 the detection significance on the convolved difference image is correct 

887 on average. 

888 

889 Separately, also apply a scalar multiplicative correction factor to the 

890 template variance if the plate scale of the coadd's constituent images 

891 is different than the science image the template is being constructed 

892 for. This should only be necessary if the coadd images were from a 

893 different instrument than the science image, since the scale change 

894 otherwise cancels between the two warps. If the plate scale of the 

895 science instrument is smaller than the plate scale of the coadd 

896 instrument, then the template pixels will be correlated and the true 

897 variance will be higher than the image pixel noise level would suggest. 

898 

899 Parameters 

900 ---------- 

901 template : `lsst.afw.image.Exposure` 

902 Assembled template; its variance plane is modified in place. 

903 plateScaleFactor : `float` or `None` 

904 Correction for the change in pixel area, from `_plateScaleFactor`. 

905 

906 Raises 

907 ------ 

908 RuntimeError 

909 Raised if ``plateScaleFactor`` is `None`. 

910 """ 

911 if plateScaleFactor is None: 

912 raise RuntimeError( 

913 "Could not determine the plate scale of the images the template coadds were made from," 

914 " so the template variance cannot be corrected for the change in pixel area." 

915 ) 

916 self.metadata["variancePlateScaleFactor"] = plateScaleFactor 

917 correlationFactor = 1.0 

918 if self.config.doCorrectVarianceWarpCorrelation: 

919 # Both warps correlate the noise: the one that built the coadds, 

920 # and the one this task just performed. 

921 correlationFactor = 1/(_warpKernelSumSq(self.config.coaddWarpKernel) 

922 * _warpKernelSumSq(self.config.warp.warpingKernelName)) 

923 self.metadata["varianceWarpCorrelationFactor"] = correlationFactor 

924 scale = correlationFactor*plateScaleFactor 

925 if scale == 1.0: 

926 return 

927 template.variance.array *= scale 

928 self.metadata["templateVarianceCorrectionFactor"] = scale 

929 self.log.info( 

930 "Variance correction factor due to plate scale changes: %.4f", 

931 plateScaleFactor, 

932 ) 

933 self.log.info( 

934 "Variance correction factor due to warping correlations: %.4f", 

935 correlationFactor, 

936 ) 

937 self.log.info( 

938 "Overall template variance correction factor: %.4f", 

939 scale, 

940 ) 

941 

942 def _plateScaleFactor(self, coaddInputs, wcs, bbox): 

943 """Compute the variance correction for the total change in pixel area 

944 between the coadd's constituent images and the science image. 

945 

946 Parameters 

947 ---------- 

948 coaddInputs : `lsst.afw.image.CoaddInputs` or `None` 

949 Input records of one of the coadd patches. 

950 wcs : `lsst.afw.geom.SkyWcs` 

951 WCS of the science image the template is being built for. 

952 bbox : `lsst.geom.Box2I` 

953 Bounding box of the template, used only to choose where to 

954 evaluate the science image pixel scale. 

955 

956 Returns 

957 ------- 

958 factor : `float` or `None` 

959 The correction factor equivalent to the ratio of the area of a pixel 

960 from the coadd's instrument to the science instrument, or `None` if 

961 this patch carries no input record from which it could be computed. 

962 """ 

963 if coaddInputs is None: 963 ↛ 964line 963 didn't jump to line 964 because the condition on line 963 was never true

964 return None 

965 scienceScale = wcs.getPixelScale(geom.Box2D(bbox).getCenter()).asArcseconds() 

966 

967 for record in coaddInputs.ccds: 

968 # Iterate through the records, and use the first one with a WCS 

969 # that gives a usable pixel area. 

970 originalWcs = record.getWcs() 

971 if originalWcs is None: 

972 continue 

973 center = geom.Box2D(record.getBBox()).getCenter() 

974 pviScale = originalWcs.getPixelScale(center).asArcseconds() 

975 # The area of one original pixel, expressed in science pixels. 

976 factor = (pviScale/scienceScale)**2 

977 if np.isfinite(factor) and factor > 0: 977 ↛ 967line 977 didn't jump to line 967 because the condition on line 977 was always true

978 return factor 

979 return None 

980 

981 def _collectTemplateInputs(self, catalog, coaddInputs, wcs, bbox): 

982 """Find the input images and epochs of each coadd in the template. 

983 

984 Parameters 

985 ---------- 

986 catalog : `lsst.afw.table.ExposureCatalog` 

987 Coadds the template was built from, with their tract, patch and 

988 WCS. 

989 coaddInputs : `list` [`lsst.afw.image.CoaddInputs` or `None`] 

990 Input records of each coadd in ``catalog``, in the same order. 

991 wcs : `lsst.afw.geom.SkyWcs` 

992 WCS of the science image. 

993 bbox : `lsst.geom.Box2I` 

994 Bounding box of the science image. 

995 

996 Returns 

997 ------- 

998 templateInputs : `dict` [`tuple` [`int`, `int`], \ 

999 `list` [`lsst.images.DifferenceImageTemplateInput`]] 

1000 Inputs of each coadd that cover part of the science image, keyed 

1001 by tract and patch, with the part their warps cover in science 

1002 image pixels. 

1003 """ 

1004 scienceBox = Box.from_legacy(bbox) 

1005 border = _warpBorder(self.config.coaddWarpKernel) 

1006 regions = {} 

1007 templateInputs = {} 

1008 for coadd, coaddInput in zip(catalog, coaddInputs, strict=True): 

1009 coaddList = templateInputs.setdefault((coadd["tract"], coadd["patch"]), []) 

1010 if coaddInput is None: 1010 ↛ 1011line 1010 didn't jump to line 1011 because the condition on line 1010 was never true

1011 continue 

1012 scienceToCoadd = _pixelTransform(wcs, coadd.getWcs()) 

1013 scienceFootprint = scienceBox.transform(scienceToCoadd).dilated_by(_FOOTPRINT_MARGIN) 

1014 coaddToScience = scienceToCoadd.inverted() 

1015 for record in coaddInput.ccds: 

1016 visitInfo = record.getVisitInfo() 

1017 weight = record["weight"] 

1018 if visitInfo is None or not visitInfo.getDate().isValid() or not weight > 0: 

1019 continue 

1020 key = (record["visit"], record["ccd"]) 

1021 # Record a single region for a ccd in overlapping patches. 

1022 if key not in regions: 

1023 regions[key] = _getImageOverlap(record, coadd.getWcs(), scienceFootprint, coaddToScience, 

1024 scienceBox, border) 

1025 region = regions[key] 

1026 if region is None: 

1027 continue 

1028 mjd = visitInfo.getDate().get(DateTime.MJD, DateTime.TAI) 

1029 coaddList.append(DifferenceImageTemplateInput(visit=key[0], detector=key[1], 

1030 mid_mjd_tai=mjd, weight=weight, 

1031 bounds=region)) 

1032 return templateInputs 

1033 

1034 def checkHighVariance(self, template): 

1035 """Set a mask plane for regions with unusually high variance. 

1036 

1037 Parameters 

1038 ---------- 

1039 template : `lsst.afw.image.Exposure` 

1040 The warped template exposure, which will be modified in place. 

1041 """ 

1042 highVarianceMaskPlaneBit = template.mask.addMaskPlane("HIGH_VARIANCE") 

1043 ignoredPixelBits = template.mask.getPlaneBitMask(self.varianceBackground.config.ignoredPixelMask) 

1044 goodMask = (template.mask.array & ignoredPixelBits) == 0 

1045 goodFraction = np.count_nonzero(goodMask)/template.mask.array.size 

1046 if goodFraction < self.config.highVarianceMaskFraction: 

1047 self.log.info("Not setting HIGH_VARIANCE mask plane, only %2.1f%% of" 

1048 " pixels were unmasked for background estimation, but" 

1049 " %2.1f%% are required", 100*goodFraction, 100*self.config.highVarianceMaskFraction) 

1050 else: 

1051 varianceExposure = template.clone() 

1052 varianceExposure.image.array = varianceExposure.variance.array 

1053 varianceBackground = self.varianceBackground.run(varianceExposure).background.getImage().array 

1054 threshold = self.config.highVarianceThreshold*np.nanmedian(varianceBackground) 

1055 highVariancePix = varianceBackground > threshold 

1056 template.mask.array[highVariancePix] |= 2**highVarianceMaskPlaneBit 

1057 

1058 @staticmethod 

1059 def _checkInputs(dataIds, coaddExposures, scienceInstrument=None): 

1060 """Check that the all the dataIds are from the same band and that 

1061 the exposures all have the same photometric calibration, and choose 

1062 the instrument of the template. 

1063 

1064 Parameters 

1065 ---------- 

1066 dataIds : `dict` [`int`, `list` [`lsst.daf.butler.DataCoordinate`]] 

1067 Record of the tract and patch of each coaddExposure. 

1068 coaddExposures : `dict` [`int`, `list` of \ 

1069 [`lsst.daf.butler.DeferredDatasetHandle` of \ 

1070 `lsst.afw.image.Exposure` or 

1071 `lsst.afw.image.Exposure`]] 

1072 Coadds to be mosaicked. 

1073 scienceInstrument : `str`, optional 

1074 Instrument of the science image. 

1075 

1076 Returns 

1077 ------- 

1078 band : `str` 

1079 Filter band of all the input exposures. 

1080 photoCalib : `lsst.afw.image.PhotoCalib` 

1081 Photometric calibration of all of the input exposures. 

1082 instrument : `str` 

1083 ``scienceInstrument`` if any coadd was made from it, otherwise the 

1084 instrument that the most coadds were made from, or ``"UNKNOWN"`` if 

1085 no coadd records one. A tie goes to the instrument whose name sorts 

1086 first. 

1087 

1088 Raises 

1089 ------ 

1090 RuntimeError 

1091 Raised if the bands or calibrations of the input exposures are not 

1092 all the same. 

1093 """ 

1094 bands = set(dataId["band"] for tract in dataIds for dataId in dataIds[tract]) 

1095 if len(bands) > 1: 1095 ↛ 1096line 1095 didn't jump to line 1096 because the condition on line 1095 was never true

1096 raise RuntimeError(f"GetTemplateTask called with multiple bands: {bands}") 

1097 band = bands.pop() 

1098 photoCalibs = [] 

1099 instrumentCounts = collections.Counter() 

1100 for exposures in coaddExposures.values(): 

1101 for exposure in exposures: 

1102 # Read both components of a coadd in turn, so a butler cache 

1103 # can serve the second read from the first download. 

1104 photoCalibs.append(exposure.get(component="photoCalib")) 

1105 instrumentCounts[GetTemplateTask._getInstrument(exposure.get(component="coaddInputs"))] += 1 

1106 if not all([photoCalibs[0] == x for x in photoCalibs]): 1106 ↛ 1107line 1106 didn't jump to line 1107 because the condition on line 1106 was never true

1107 msg = f"GetTemplateTask called with exposures with different photoCalibs: {photoCalibs}" 

1108 raise RuntimeError(msg) 

1109 photoCalib = photoCalibs[0] 

1110 # Coadds that record no instrument do not count toward the choice. 

1111 del instrumentCounts[_UNKNOWN_INSTRUMENT] 

1112 if scienceInstrument in instrumentCounts: 

1113 return band, photoCalib, scienceInstrument 

1114 if not instrumentCounts: 

1115 return band, photoCalib, _UNKNOWN_INSTRUMENT 

1116 instrument = max(sorted(instrumentCounts), key=instrumentCounts.get) 

1117 return band, photoCalib, instrument 

1118 

1119 @staticmethod 

1120 def _getInstrument(coaddInputs): 

1121 """Return the instrument whose observations were coadded to make a 

1122 coadd. 

1123 

1124 Parameters 

1125 ---------- 

1126 coaddInputs : `lsst.afw.image.CoaddInputs` or `None` 

1127 Input records of the coadd. 

1128 

1129 Returns 

1130 ------- 

1131 instrument : `str` 

1132 Instrument label of the coadd, or ``"UNKNOWN"`` if it records none. 

1133 

1134 Notes 

1135 ----- 

1136 Every input of a coadd comes from the same instrument, so the first 

1137 input record stands for all of them. 

1138 """ 

1139 if coaddInputs is None or len(coaddInputs.ccds) == 0: 

1140 return _UNKNOWN_INSTRUMENT 

1141 visitInfo = coaddInputs.ccds[0].getVisitInfo() 

1142 label = visitInfo.getInstrumentLabel() if visitInfo is not None else "" 

1143 return label or _UNKNOWN_INSTRUMENT 

1144 

1145 def _makeExposureCatalog(self, exposureRefs, dataIds, instrument=_UNKNOWN_INSTRUMENT): 

1146 """Make an exposure catalog for one tract. 

1147 

1148 Parameters 

1149 ---------- 

1150 exposureRefs : `list` of [`lsst.daf.butler.DeferredDatasetHandle` of \ 

1151 `lsst.afw.image.Exposure`] 

1152 Exposures to include in the catalog. 

1153 dataIds : `list` [`lsst.daf.butler.DataCoordinate`] 

1154 Data ids of each of the included exposures; must have "tract" and 

1155 "patch" entries. 

1156 instrument : `str`, optional 

1157 Instrument of the template, recorded in the catalog. Exposures 

1158 made from another instrument are dropped, as are exposures that 

1159 record no instrument unless ``instrument`` is ``"UNKNOWN"``. 

1160 

1161 Returns 

1162 ------- 

1163 images : `dict` [`lsst.afw.image.MaskedImage`] 

1164 MaskedImages of each of the input exposures, for warping. 

1165 catalog : `lsst.afw.table.ExposureCatalog` 

1166 Catalog of metadata for each exposure 

1167 totalBox : `lsst.geom.Box2I` 

1168 The union of the bounding boxes of all the input exposures. 

1169 coaddInputs : `list` [`lsst.afw.image.CoaddInputs` or `None`] 

1170 Input records of each exposure in ``catalog``, in the same order. 

1171 """ 

1172 catalog = afwTable.ExposureCatalog(self.schema) 

1173 catalog.reserve(len(exposureRefs)) 

1174 exposures = (exposureRef.get() for exposureRef in exposureRefs) 

1175 images = {} 

1176 totalBox = geom.Box2I() 

1177 keptCoaddInputs = [] 

1178 

1179 for coadd, dataId in zip(exposures, dataIds): 

1180 coaddInputs = coadd.getInfo().getCoaddInputs() 

1181 coaddInstrument = self._getInstrument(coaddInputs) 

1182 if coaddInstrument != instrument: 

1183 self.log.info( 

1184 "Dropping template coadd %s: it was made from %s, but the template is made from %s.", 

1185 dataId, 

1186 coaddInstrument, 

1187 instrument, 

1188 ) 

1189 continue 

1190 keptCoaddInputs.append(coaddInputs) 

1191 images[dataId] = coadd.maskedImage 

1192 bbox = coadd.getBBox() 

1193 totalBox = totalBox.expandedTo(bbox) 

1194 record = catalog.addNew() 

1195 record.setPsf(coadd.psf) 

1196 record.setWcs(coadd.wcs) 

1197 record.setPhotoCalib(coadd.photoCalib) 

1198 record.setBBox(bbox) 

1199 record.setValidPolygon(afwGeom.Polygon(geom.Box2D(bbox).getCorners())) 

1200 record.set("tract", dataId["tract"]) 

1201 record.set("patch", dataId["patch"]) 

1202 record.set("instrument", instrument) 

1203 # Weight is used by CoaddPsf, but the PSFs from overlapping patches 

1204 # should be very similar, so this value mostly shouldn't matter. 

1205 record.set("weight", 1) 

1206 

1207 return images, catalog, totalBox, keptCoaddInputs 

1208 

1209 def _merge(self, maskedImages, bbox, wcs): 

1210 """Merge the images that came from one tract into one larger image, 

1211 ignoring NaN pixels and non-finite variance pixels from individual 

1212 exposures. 

1213 

1214 Parameters 

1215 ---------- 

1216 maskedImages : `dict` [`lsst.afw.image.MaskedImage` or 

1217 `lsst.afw.image.Exposure`] 

1218 Images to be merged into one larger bounding box. 

1219 bbox : `lsst.geom.Box2I` 

1220 Bounding box defining the image to merge into. 

1221 wcs : `lsst.afw.geom.SkyWcs` 

1222 WCS of all of the input images to set on the output image. 

1223 

1224 Returns 

1225 ------- 

1226 merged : `lsst.afw.image.MaskedImage` 

1227 Merged image with all of the inputs at their respective bbox 

1228 positions. 

1229 count : `int` 

1230 Count of the number of good pixels (those with positive weights) 

1231 in the merged image. 

1232 included : `list` [`int`] 

1233 List of indexes of patches that were included in the merged 

1234 result, to be used to trim the exposure catalog. 

1235 """ 

1236 merged = afwImage.ExposureF(bbox, wcs) 

1237 weights = afwImage.ImageF(bbox) 

1238 included = [] # which patches were included in the result 

1239 for i, (dataId, maskedImage) in enumerate(maskedImages.items()): 

1240 # Only merge into the trimmed box, to save memory 

1241 clippedBox = geom.Box2I(maskedImage.getBBox()) 

1242 clippedBox.clip(bbox) 

1243 if clippedBox.area == 0: 

1244 self.log.debug("%s does not overlap template region.", dataId) 

1245 continue # nothing in this image overlaps the output 

1246 maskedImage = maskedImage.subset(clippedBox) 

1247 # Catch both zero-value and NaN variance plane pixels 

1248 good = (maskedImage.variance.array > 0) & ( 

1249 np.isfinite(maskedImage.variance.array) 

1250 ) 

1251 weight = maskedImage.variance.array[good] ** (-0.5) 

1252 bad = np.isnan(maskedImage.image.array) | ~good 

1253 # Note that modifying the patch MaskedImage in place is fine; 

1254 # we're throwing it away at the end anyway. 

1255 maskedImage.image.array[bad] = 0.0 

1256 maskedImage.variance.array[bad] = 0.0 

1257 # Reset mask, too, since these pixels don't contribute to sum. 

1258 maskedImage.mask.array[bad] = 0 

1259 # Cannot use `merged.maskedImage *= weight` because that operator 

1260 # multiplies the variance by the weight twice; in this case 

1261 # `weight` are the exact values we want to scale by. 

1262 maskedImage.image.array[good] *= weight 

1263 maskedImage.variance.array[good] *= weight 

1264 weights[clippedBox].array[good] += weight 

1265 # Free memory before creating new large arrays 

1266 del weight 

1267 merged.maskedImage[clippedBox] += maskedImage 

1268 included.append(i) 

1269 

1270 good = weights.array > 0 

1271 

1272 # Cannot use `merged.maskedImage /= weights` because that 

1273 # operator divides the variance by the weight twice; in this case 

1274 # `weights` are the exact values we want to scale by. 

1275 weights = weights.array[good] 

1276 merged.image.array[good] /= weights 

1277 merged.variance.array[good] /= weights 

1278 

1279 merged.mask.array[~good] |= merged.mask.getPlaneBitMask("NO_DATA") 

1280 

1281 return merged, good.sum(), included 

1282 

1283 def _makePsf(self, template, catalog, wcs): 

1284 """Return a PSF containing the PSF at each of the input regions. 

1285 

1286 Note that although this includes all the exposures from the catalog, 

1287 the PSF knows which part of the template the inputs came from, so when 

1288 evaluated at a given position it will not include inputs that never 

1289 went in to those pixels. 

1290 

1291 Parameters 

1292 ---------- 

1293 template : `lsst.afw.image.Exposure` 

1294 Generated template the PSF is for. 

1295 catalog : `lsst.afw.table.ExposureCatalog` 

1296 Catalog of exposures that went into the template that contains all 

1297 of the input PSFs. 

1298 wcs : `lsst.afw.geom.SkyWcs` 

1299 WCS of the template, to warp the PSFs to. 

1300 

1301 Returns 

1302 ------- 

1303 coaddPsf : `lsst.meas.algorithms.CoaddPsf` 

1304 The meta-psf constructed from all of the input catalogs. 

1305 """ 

1306 # CoaddPsf centroid not only must overlap image, but must overlap the 

1307 # part of image with data. Use centroid of region with data. 

1308 boolmask = template.mask.array & template.mask.getPlaneBitMask("NO_DATA") == 0 

1309 maskx = afwImage.makeMaskFromArray(boolmask.astype(afwImage.MaskPixel)) 

1310 centerCoord = afwGeom.SpanSet.fromMask(maskx, 1).computeCentroid() 

1311 

1312 ctrl = self.config.coaddPsf.makeControl() 

1313 coaddPsf = CoaddPsf( 

1314 catalog, wcs, centerCoord, ctrl.warpingKernelName, ctrl.cacheSize 

1315 ) 

1316 return coaddPsf 

1317 

1318 def _makeGaussianPsf(self, template): 

1319 """Return a Gaussian PSF with the width of the template CoaddPsf. 

1320 

1321 Parameters 

1322 ---------- 

1323 template : `lsst.afw.image.Exposure` 

1324 Template with the CoaddPsf to approximate. The width is measured 

1325 at the average position of the PSF, or averaged over a grid of 

1326 positions if the PSF cannot be evaluated there. 

1327 

1328 Returns 

1329 ------- 

1330 psf : `lsst.afw.detection.GaussianPsf` 

1331 Gaussian with the width of the template PSF. 

1332 

1333 Raises 

1334 ------ 

1335 lsst.afw.detection.InvalidPsfError 

1336 Raised if the PSF cannot be evaluated at any grid position. 

1337 """ 

1338 # The CoaddPsf is not defined where the template has no inputs, which 

1339 # can include its average position. 

1340 try: 

1341 fwhm = getPsfFwhm(template.psf) 

1342 except lsst.pex.exceptions.Exception: 

1343 # Catch a broad range of exceptions, since some are C++ only 

1344 # Catching: 

1345 # - lsst::geom::SingularTransformException 

1346 # - lsst.pex.exceptions.InvalidParameterError 

1347 # - lsst.pex.exceptions.RangeError 

1348 self.log.info("Unable to evaluate PSF at the average position. " 

1349 "Evaluating PSF on a grid of points.") 

1350 fwhm = evaluateMeanPsfFwhm(template, 

1351 fwhmExposureBuffer=self.config.fwhmExposureBuffer, 

1352 fwhmExposureGrid=self.config.fwhmExposureGrid) 

1353 sigma = fwhm/gaussian_sigma_to_fwhm 

1354 size = 2*int(np.ceil(_PSF_STAMP_SIGMAS*sigma)) + 1 

1355 self.metadata["templatePsfSigma"] = float(sigma) 

1356 self.log.info("Approximated the template PSF with a Gaussian of sigma %.3f pixels.", sigma) 

1357 return afwDetection.GaussianPsf(size, size, sigma) 

1358 

1359 

1360class GetDcrTemplateConnections( 

1361 GetTemplateConnections, 

1362 dimensions=("instrument", "visit", "detector"), 

1363 defaultTemplates={"coaddName": "dcr", "warpTypeSuffix": "", "fakesType": ""}, 

1364): 

1365 visitInfo = pipeBase.connectionTypes.Input( 

1366 doc="VisitInfo of calexp used to determine observing conditions.", 

1367 name="{fakesType}calexp.visitInfo", 

1368 storageClass="VisitInfo", 

1369 dimensions=("instrument", "visit", "detector"), 

1370 ) 

1371 dcrCoadds = pipeBase.connectionTypes.Input( 

1372 doc="Input DCR template to match and subtract from the exposure", 

1373 name="{fakesType}dcrCoadd{warpTypeSuffix}", 

1374 storageClass="ExposureF", 

1375 dimensions=("tract", "patch", "skymap", "band", "subfilter"), 

1376 multiple=True, 

1377 deferLoad=True, 

1378 ) 

1379 

1380 def __init__(self, *, config=None): 

1381 super().__init__(config=config) 

1382 self.inputs.remove("coaddExposures") 

1383 

1384 

1385class GetDcrTemplateConfig( 

1386 GetTemplateConfig, pipelineConnections=GetDcrTemplateConnections 

1387): 

1388 """Config for GetDcrTemplateTask. 

1389 

1390 Only ``output_image_type="legacy"`` is supported: the task always writes 

1391 an `lsst.afw.image.ExposureF`. 

1392 """ 

1393 

1394 numSubfilters = pexConfig.Field( 

1395 doc="Number of subfilters in the DcrCoadd.", 

1396 dtype=int, 

1397 default=3, 

1398 ) 

1399 effectiveWavelength = pexConfig.Field( 

1400 doc="Effective wavelength of the filter in nm.", 

1401 optional=False, 

1402 dtype=float, 

1403 ) 

1404 bandwidth = pexConfig.Field( 

1405 doc="Bandwidth of the physical filter.", 

1406 optional=False, 

1407 dtype=float, 

1408 ) 

1409 

1410 def validate(self): 

1411 if self.effectiveWavelength is None or self.bandwidth is None: 

1412 raise ValueError( 

1413 "The effective wavelength and bandwidth of the physical filter " 

1414 "must be set in the getTemplate config for DCR coadds. " 

1415 "Required until transmission curves are used in DM-13668." 

1416 ) 

1417 

1418 

1419class GetDcrTemplateTask(GetTemplateTask): 

1420 ConfigClass = GetDcrTemplateConfig 

1421 _DefaultName = "getDcrTemplate" 

1422 

1423 def runQuantum(self, butlerQC, inputRefs, outputRefs): 

1424 inputs = butlerQC.get(inputRefs) 

1425 detector = inputs.pop("detector") 

1426 bbox = detector.getBBox() 

1427 wcs = inputs.pop("wcs") 

1428 dcrCoaddExposureHandles = inputs.pop("dcrCoadds") 

1429 skymap = inputs.pop("skyMap") 

1430 visitInfo = inputs.pop("visitInfo") 

1431 # This task never converts its output, so the observation metadata 

1432 # that the conversion needs is dropped here. 

1433 inputs.pop("obs_info", None) 

1434 

1435 # This should not happen with a properly configured execution context. 

1436 assert not inputs, "runQuantum got more inputs than expected" 

1437 

1438 results = self.getExposures( 

1439 dcrCoaddExposureHandles, bbox, skymap, wcs, visitInfo 

1440 ) 

1441 physical_filter = butlerQC.quantum.dataId["physical_filter"] 

1442 outputs = self.run( 

1443 coaddExposureHandles=results.coaddExposures, 

1444 bbox=bbox, 

1445 wcs=wcs, 

1446 dataIds=results.dataIds, 

1447 physical_filter=physical_filter, 

1448 visit=outputRefs.template.dataId["visit"], 

1449 instrument=butlerQC.quantum.dataId["instrument"], 

1450 ) 

1451 butlerQC.put(outputs, outputRefs) 

1452 

1453 def getExposures(self, dcrCoaddExposureHandles, bbox, skymap, wcs, visitInfo): 

1454 """Return lists of coadds and their corresponding dataIds that overlap 

1455 the detector. 

1456 

1457 The spatial index in the registry has generous padding and often 

1458 supplies patches near, but not directly overlapping the detector. 

1459 Filters inputs so that we don't have to read in all input coadds. 

1460 

1461 Parameters 

1462 ---------- 

1463 dcrCoaddExposureHandles : `list` \ 

1464 [`lsst.daf.butler.DeferredDatasetHandle` of \ 

1465 `lsst.afw.image.Exposure`] 

1466 Data references to exposures that might overlap the detector. 

1467 bbox : `lsst.geom.Box2I` 

1468 Template Bounding box of the detector geometry onto which to 

1469 resample the coaddExposures. 

1470 skymap : `lsst.skymap.SkyMap` 

1471 Input definition of geometry/bbox and projection/wcs for 

1472 template exposures. 

1473 wcs : `lsst.afw.geom.SkyWcs` 

1474 Template WCS onto which to resample the coaddExposures. 

1475 visitInfo : `lsst.afw.image.VisitInfo` 

1476 Metadata for the science image. 

1477 

1478 Returns 

1479 ------- 

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

1481 A struct with attibutes: 

1482 

1483 ``coaddExposures`` 

1484 Dict of coadd exposures that overlap the projected bbox, 

1485 indexed on tract id 

1486 (`dict` [`int`, `list` [`lsst.afw.image.Exposure`] ]). 

1487 ``dataIds`` 

1488 Dict of data IDs of the coadd exposures that overlap the 

1489 projected bbox, indexed on tract id 

1490 (`dict` [`int`, `list [`lsst.daf.butler.DataCoordinate`] ]). 

1491 

1492 Raises 

1493 ------ 

1494 pipeBase.NoWorkFound 

1495 Raised if no patches overlatp the input detector bbox. 

1496 """ 

1497 # Check that the patches actually overlap the detector 

1498 # Exposure's validPolygon would be more accurate 

1499 if wcs is None: 

1500 raise pipeBase.NoWorkFound("Exposure has no WCS; cannot create a template.") 

1501 

1502 detectorPolygon = geom.Box2D(bbox) 

1503 overlappingArea = 0 

1504 dataIds = collections.defaultdict(list) 

1505 patchList = dict() 

1506 for coaddRef in dcrCoaddExposureHandles: 

1507 dataId = coaddRef.dataId 

1508 subfilter = dataId["subfilter"] 

1509 patchWcs = skymap[dataId["tract"]].getWcs() 

1510 patchBBox = skymap[dataId["tract"]][dataId["patch"]].getOuterBBox() 

1511 patchCorners = patchWcs.pixelToSky(geom.Box2D(patchBBox).getCorners()) 

1512 patchPolygon = afwGeom.Polygon(wcs.skyToPixel(patchCorners)) 

1513 if patchPolygon.intersection(detectorPolygon): 

1514 overlappingArea += patchPolygon.intersectionSingle( 

1515 detectorPolygon 

1516 ).calculateArea() 

1517 self.log.info( 

1518 "Using template input tract=%s, patch=%s, subfilter=%s" 

1519 % (dataId["tract"], dataId["patch"], dataId["subfilter"]) 

1520 ) 

1521 if dataId["tract"] in patchList: 

1522 patchList[dataId["tract"]].append(dataId["patch"]) 

1523 else: 

1524 patchList[dataId["tract"]] = [ 

1525 dataId["patch"], 

1526 ] 

1527 if subfilter == 0: 

1528 dataIds[dataId["tract"]].append(dataId) 

1529 

1530 if not overlappingArea: 

1531 raise pipeBase.NoWorkFound("No patches overlap detector") 

1532 

1533 self.checkPatchList(patchList) 

1534 

1535 coaddExposures = self.getDcrModel(patchList, dcrCoaddExposureHandles, visitInfo) 

1536 return pipeBase.Struct(coaddExposures=coaddExposures, dataIds=dataIds) 

1537 

1538 def checkPatchList(self, patchList): 

1539 """Check that all of the DcrModel subfilters are present for each 

1540 patch. 

1541 

1542 Parameters 

1543 ---------- 

1544 patchList : `dict` 

1545 Dict of the patches containing valid data for each tract. 

1546 

1547 Raises 

1548 ------ 

1549 RuntimeError 

1550 If the number of exposures found for a patch does not match the 

1551 number of subfilters. 

1552 """ 

1553 for tract in patchList: 

1554 for patch in set(patchList[tract]): 

1555 if patchList[tract].count(patch) != self.config.numSubfilters: 

1556 raise RuntimeError( 

1557 "Invalid number of DcrModel subfilters found: %d vs %d expected", 

1558 patchList[tract].count(patch), 

1559 self.config.numSubfilters, 

1560 ) 

1561 

1562 def getDcrModel(self, patchList, coaddRefs, visitInfo): 

1563 """Build DCR-matched coadds from a list of exposure references. 

1564 

1565 Parameters 

1566 ---------- 

1567 patchList : `dict` 

1568 Dict of the patches containing valid data for each tract. 

1569 coaddRefs : `list` [`lsst.daf.butler.DeferredDatasetHandle`] 

1570 Data references to `~lsst.afw.image.Exposure` representing 

1571 DcrModels that overlap the detector. 

1572 visitInfo : `lsst.afw.image.VisitInfo` 

1573 Metadata for the science image. 

1574 

1575 Returns 

1576 ------- 

1577 coaddExposures : `list` [`lsst.afw.image.Exposure`] 

1578 Coadd exposures that overlap the detector. 

1579 """ 

1580 coaddExposures = collections.defaultdict(list) 

1581 for tract in patchList: 

1582 for patch in set(patchList[tract]): 

1583 coaddRefList = [ 

1584 coaddRef 

1585 for coaddRef in coaddRefs 

1586 if _selectDataRef(coaddRef, tract, patch) 

1587 ] 

1588 

1589 dcrModel = DcrModel.fromQuantum( 

1590 coaddRefList, 

1591 self.config.effectiveWavelength, 

1592 self.config.bandwidth, 

1593 self.config.numSubfilters, 

1594 ) 

1595 coaddExposures[tract].append(dcrModel.buildMatchedExposureHandle(visitInfo=visitInfo)) 

1596 return coaddExposures 

1597 

1598 

1599def _selectDataRef(coaddRef, tract, patch): 

1600 condition = (coaddRef.dataId["tract"] == tract) & ( 

1601 coaddRef.dataId["patch"] == patch 

1602 ) 

1603 return condition