Coverage for python/lsst/ip/diffim/subtractImages.py: 21%

368 statements  

« prev     ^ index     » next       coverage.py v7.10.0, created at 2025-07-26 08:37 +0000

1# This file is part of ip_diffim. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (https://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# This program is free software: you can redistribute it and/or modify 

10# it under the terms of the GNU General Public License as published by 

11# the Free Software Foundation, either version 3 of the License, or 

12# (at your option) any later version. 

13# 

14# This program is distributed in the hope that it will be useful, 

15# but WITHOUT ANY WARRANTY; without even the implied warranty of 

16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

17# GNU General Public License for more details. 

18# 

19# You should have received a copy of the GNU General Public License 

20# along with this program. If not, see <https://www.gnu.org/licenses/>. 

21 

22from astropy import units as u 

23import numpy as np 

24 

25import lsst.afw.detection as afwDetection 

26import lsst.afw.image 

27import lsst.afw.math 

28import lsst.geom 

29from lsst.ip.diffim.utils import evaluateMeanPsfFwhm, getPsfFwhm, computeDifferenceImageMetrics 

30from lsst.meas.algorithms import ScaleVarianceTask, ScienceSourceSelectorTask 

31import lsst.pex.config 

32import lsst.pipe.base 

33import lsst.pex.exceptions 

34from lsst.pipe.base import connectionTypes 

35from . import MakeKernelTask, DecorrelateALKernelTask 

36from lsst.utils.timer import timeMethod 

37 

38__all__ = ["AlardLuptonSubtractConfig", "AlardLuptonSubtractTask", 

39 "AlardLuptonPreconvolveSubtractConfig", "AlardLuptonPreconvolveSubtractTask"] 

40 

41_dimensions = ("instrument", "visit", "detector") 

42_defaultTemplates = {"coaddName": "deep", "fakesType": ""} 

43 

44 

45class SubtractInputConnections(lsst.pipe.base.PipelineTaskConnections, 

46 dimensions=_dimensions, 

47 defaultTemplates=_defaultTemplates): 

48 template = connectionTypes.Input( 

49 doc="Input warped template to subtract.", 

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

51 storageClass="ExposureF", 

52 name="{fakesType}{coaddName}Diff_templateExp" 

53 ) 

54 science = connectionTypes.Input( 

55 doc="Input science exposure to subtract from.", 

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

57 storageClass="ExposureF", 

58 name="{fakesType}calexp" 

59 ) 

60 sources = connectionTypes.Input( 

61 doc="Sources measured on the science exposure; " 

62 "used to select sources for making the matching kernel.", 

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

64 storageClass="SourceCatalog", 

65 name="{fakesType}src" 

66 ) 

67 visitSummary = connectionTypes.Input( 

68 doc=("Per-visit catalog with final calibration objects. " 

69 "These catalogs use the detector id for the catalog id, " 

70 "sorted on id for fast lookup."), 

71 dimensions=("instrument", "visit"), 

72 storageClass="ExposureCatalog", 

73 name="finalVisitSummary", 

74 ) 

75 

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

77 super().__init__(config=config) 

78 if not config.doApplyExternalCalibrations: 

79 del self.visitSummary 

80 

81 

82class SubtractImageOutputConnections(lsst.pipe.base.PipelineTaskConnections, 

83 dimensions=_dimensions, 

84 defaultTemplates=_defaultTemplates): 

85 difference = connectionTypes.Output( 

86 doc="Result of subtracting convolved template from science image.", 

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

88 storageClass="ExposureF", 

89 name="{fakesType}{coaddName}Diff_differenceTempExp", 

90 ) 

91 matchedTemplate = connectionTypes.Output( 

92 doc="Warped and PSF-matched template used to create `subtractedExposure`.", 

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

94 storageClass="ExposureF", 

95 name="{fakesType}{coaddName}Diff_matchedExp", 

96 ) 

97 psfMatchingKernel = connectionTypes.Output( 

98 doc="Kernel used to PSF match the science and template images.", 

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

100 storageClass="MatchingKernel", 

101 name="{fakesType}{coaddName}Diff_psfMatchKernel", 

102 ) 

103 kernelSources = connectionTypes.Output( 

104 doc="Final selection of sources used for psf matching.", 

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

106 storageClass="SourceCatalog", 

107 name="{fakesType}{coaddName}Diff_psfMatchSources" 

108 ) 

109 

110 

111class SubtractScoreOutputConnections(lsst.pipe.base.PipelineTaskConnections, 

112 dimensions=_dimensions, 

113 defaultTemplates=_defaultTemplates): 

114 scoreExposure = connectionTypes.Output( 

115 doc="The maximum likelihood image, used for the detection of diaSources.", 

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

117 storageClass="ExposureF", 

118 name="{fakesType}{coaddName}Diff_scoreExp", 

119 ) 

120 psfMatchingKernel = connectionTypes.Output( 

121 doc="Kernel used to PSF match the science and template images.", 

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

123 storageClass="MatchingKernel", 

124 name="{fakesType}{coaddName}Diff_psfScoreMatchKernel", 

125 ) 

126 kernelSources = connectionTypes.Output( 

127 doc="Final selection of sources used for psf matching.", 

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

129 storageClass="SourceCatalog", 

130 name="{fakesType}{coaddName}Diff_psfScoreMatchSources" 

131 ) 

132 

133 

134class AlardLuptonSubtractConnections(SubtractInputConnections, SubtractImageOutputConnections): 

135 pass 

136 

137 

138class AlardLuptonSubtractBaseConfig(lsst.pex.config.Config): 

139 makeKernel = lsst.pex.config.ConfigurableField( 

140 target=MakeKernelTask, 

141 doc="Task to construct a matching kernel for convolution.", 

142 ) 

143 doDecorrelation = lsst.pex.config.Field( 

144 dtype=bool, 

145 default=True, 

146 doc="Perform diffim decorrelation to undo pixel correlation due to A&L " 

147 "kernel convolution? If True, also update the diffim PSF." 

148 ) 

149 decorrelate = lsst.pex.config.ConfigurableField( 

150 target=DecorrelateALKernelTask, 

151 doc="Task to decorrelate the image difference.", 

152 ) 

153 requiredTemplateFraction = lsst.pex.config.Field( 

154 dtype=float, 

155 default=0.1, 

156 doc="Raise NoWorkFound and do not attempt image subtraction if template covers less than this " 

157 " fraction of pixels. Setting to 0 will always attempt image subtraction." 

158 ) 

159 minTemplateFractionForExpectedSuccess = lsst.pex.config.Field( 

160 dtype=float, 

161 default=0.2, 

162 doc="Raise NoWorkFound if PSF-matching fails and template covers less than this fraction of pixels." 

163 " If the fraction of pixels covered by the template is less than this value (and greater than" 

164 " requiredTemplateFraction) this task is attempted but failure is anticipated and tolerated." 

165 ) 

166 doScaleVariance = lsst.pex.config.Field( 

167 dtype=bool, 

168 default=True, 

169 doc="Scale variance of the image difference?" 

170 ) 

171 scaleVariance = lsst.pex.config.ConfigurableField( 

172 target=ScaleVarianceTask, 

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

174 ) 

175 doSubtractBackground = lsst.pex.config.Field( 

176 doc="Subtract the background fit when solving the kernel?", 

177 dtype=bool, 

178 default=False, 

179 ) 

180 doApplyExternalCalibrations = lsst.pex.config.Field( 

181 doc=( 

182 "Replace science Exposure's calibration objects with those" 

183 " in visitSummary. Ignored if `doApplyFinalizedPsf is True." 

184 ), 

185 dtype=bool, 

186 default=False, 

187 ) 

188 sourceSelector = lsst.pex.config.ConfigurableField( 

189 target=ScienceSourceSelectorTask, 

190 doc="Task to select sources to be used for PSF matching.", 

191 ) 

192 detectionThreshold = lsst.pex.config.Field( 

193 dtype=float, 

194 default=10, 

195 doc="Minimum signal to noise ratio of detected sources " 

196 "to use for calculating the PSF matching kernel." 

197 ) 

198 detectionThresholdMax = lsst.pex.config.Field( 

199 dtype=float, 

200 default=500, 

201 doc="Maximum signal to noise ratio of detected sources " 

202 "to use for calculating the PSF matching kernel." 

203 ) 

204 maxKernelSources = lsst.pex.config.Field( 

205 dtype=int, 

206 default=1000, 

207 doc="Maximum number of sources to use for calculating the PSF matching kernel." 

208 "Set to -1 to disable." 

209 ) 

210 minKernelSources = lsst.pex.config.Field( 

211 dtype=int, 

212 default=3, 

213 doc="Minimum number of sources needed for calculating the PSF matching kernel." 

214 ) 

215 excludeMaskPlanes = lsst.pex.config.ListField( 

216 dtype=str, 

217 default=("NO_DATA", "BAD", "SAT", "EDGE", "FAKE"), 

218 doc="Mask planes to exclude when selecting sources for PSF matching." 

219 ) 

220 badMaskPlanes = lsst.pex.config.ListField( 

221 dtype=str, 

222 default=("NO_DATA", "BAD", "SAT", "EDGE"), 

223 doc="Mask planes to interpolate over." 

224 ) 

225 preserveTemplateMask = lsst.pex.config.ListField( 

226 dtype=str, 

227 default=("NO_DATA", "BAD",), 

228 doc="Mask planes from the template to propagate to the image difference." 

229 ) 

230 renameTemplateMask = lsst.pex.config.ListField( 

231 dtype=str, 

232 default=("SAT", "INJECTED", "INJECTED_CORE",), 

233 doc="Mask planes from the template to propagate to the image difference" 

234 "with '_TEMPLATE' appended to the name." 

235 ) 

236 allowKernelSourceDetection = lsst.pex.config.Field( 

237 dtype=bool, 

238 default=False, 

239 doc="Re-run source detection for kernel candidates if an error is" 

240 " encountered while calculating the matching kernel." 

241 ) 

242 

243 def setDefaults(self): 

244 self.makeKernel.kernel.name = "AL" 

245 # Always include background fitting in the kernel fit, 

246 # even if it is not subtracted 

247 self.makeKernel.kernel.active.fitForBackground = True 

248 self.makeKernel.kernel.active.spatialKernelOrder = 1 

249 self.makeKernel.kernel.active.spatialBgOrder = 2 

250 self.sourceSelector.doUnresolved = True # apply star-galaxy separation 

251 self.sourceSelector.doIsolated = True # apply isolated star selection 

252 self.sourceSelector.doRequirePrimary = True # apply primary flag selection 

253 self.sourceSelector.doSkySources = False # Do not include sky sources 

254 self.sourceSelector.doSignalToNoise = True # apply signal to noise filter 

255 self.sourceSelector.signalToNoise.minimum = 10 

256 self.sourceSelector.signalToNoise.maximum = 500 

257 

258 

259class AlardLuptonSubtractConfig(AlardLuptonSubtractBaseConfig, lsst.pipe.base.PipelineTaskConfig, 

260 pipelineConnections=AlardLuptonSubtractConnections): 

261 mode = lsst.pex.config.ChoiceField( 

262 dtype=str, 

263 default="convolveTemplate", 

264 allowed={"auto": "Choose which image to convolve at runtime.", 

265 "convolveScience": "Only convolve the science image.", 

266 "convolveTemplate": "Only convolve the template image."}, 

267 doc="Choose which image to convolve at runtime, or require that a specific image is convolved." 

268 ) 

269 

270 

271class AlardLuptonSubtractTask(lsst.pipe.base.PipelineTask): 

272 """Compute the image difference of a science and template image using 

273 the Alard & Lupton (1998) algorithm. 

274 """ 

275 ConfigClass = AlardLuptonSubtractConfig 

276 _DefaultName = "alardLuptonSubtract" 

277 

278 def __init__(self, **kwargs): 

279 super().__init__(**kwargs) 

280 self.makeSubtask("decorrelate") 

281 self.makeSubtask("makeKernel") 

282 self.makeSubtask("sourceSelector") 

283 if self.config.doScaleVariance: 

284 self.makeSubtask("scaleVariance") 

285 

286 self.convolutionControl = lsst.afw.math.ConvolutionControl() 

287 # Normalization is an extra, unnecessary, calculation and will result 

288 # in mis-subtraction of the images if there are calibration errors. 

289 self.convolutionControl.setDoNormalize(False) 

290 self.convolutionControl.setDoCopyEdge(True) 

291 

292 def _applyExternalCalibrations(self, exposure, visitSummary): 

293 """Replace calibrations (psf, and ApCorrMap) on this exposure with 

294 external ones.". 

295 

296 Parameters 

297 ---------- 

298 exposure : `lsst.afw.image.exposure.Exposure` 

299 Input exposure to adjust calibrations. 

300 visitSummary : `lsst.afw.table.ExposureCatalog` 

301 Exposure catalog with external calibrations to be applied. Catalog 

302 uses the detector id for the catalog id, sorted on id for fast 

303 lookup. 

304 

305 Returns 

306 ------- 

307 exposure : `lsst.afw.image.exposure.Exposure` 

308 Exposure with adjusted calibrations. 

309 """ 

310 detectorId = exposure.info.getDetector().getId() 

311 

312 row = visitSummary.find(detectorId) 

313 if row is None: 

314 self.log.warning("Detector id %s not found in external calibrations catalog; " 

315 "Using original calibrations.", detectorId) 

316 else: 

317 psf = row.getPsf() 

318 apCorrMap = row.getApCorrMap() 

319 if psf is None: 

320 self.log.warning("Detector id %s has None for psf in " 

321 "external calibrations catalog; Using original psf and aperture correction.", 

322 detectorId) 

323 elif apCorrMap is None: 

324 self.log.warning("Detector id %s has None for apCorrMap in " 

325 "external calibrations catalog; Using original psf and aperture correction.", 

326 detectorId) 

327 else: 

328 exposure.setPsf(psf) 

329 exposure.info.setApCorrMap(apCorrMap) 

330 

331 return exposure 

332 

333 @timeMethod 

334 def run(self, template, science, sources, visitSummary=None): 

335 """PSF match, subtract, and decorrelate two images. 

336 

337 Parameters 

338 ---------- 

339 template : `lsst.afw.image.ExposureF` 

340 Template exposure, warped to match the science exposure. 

341 science : `lsst.afw.image.ExposureF` 

342 Science exposure to subtract from the template. 

343 sources : `lsst.afw.table.SourceCatalog` 

344 Identified sources on the science exposure. This catalog is used to 

345 select sources in order to perform the AL PSF matching on stamp 

346 images around them. 

347 visitSummary : `lsst.afw.table.ExposureCatalog`, optional 

348 Exposure catalog with external calibrations to be applied. Catalog 

349 uses the detector id for the catalog id, sorted on id for fast 

350 lookup. 

351 

352 Returns 

353 ------- 

354 results : `lsst.pipe.base.Struct` 

355 ``difference`` : `lsst.afw.image.ExposureF` 

356 Result of subtracting template and science. 

357 ``matchedTemplate`` : `lsst.afw.image.ExposureF` 

358 Warped and PSF-matched template exposure. 

359 ``backgroundModel`` : `lsst.afw.math.Function2D` 

360 Background model that was fit while solving for the 

361 PSF-matching kernel 

362 ``psfMatchingKernel`` : `lsst.afw.math.Kernel` 

363 Kernel used to PSF-match the convolved image. 

364 

365 Raises 

366 ------ 

367 RuntimeError 

368 If an unsupported convolution mode is supplied. 

369 RuntimeError 

370 If there are too few sources to calculate the PSF matching kernel. 

371 lsst.pipe.base.NoWorkFound 

372 Raised if fraction of good pixels, defined as not having NO_DATA 

373 set, is less then the configured requiredTemplateFraction 

374 """ 

375 self._prepareInputs(template, science, visitSummary=visitSummary) 

376 

377 # Calculate estimated image depths, i.e., limiting magnitudes 

378 maglim_science = self._calculateMagLim(science, fallbackPsfSize=self.sciencePsfSize) 

379 if np.isnan(maglim_science): 

380 self.log.warning("Limiting magnitude of the science image is NaN!") 

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

382 maglim_template = self._calculateMagLim(template, fallbackPsfSize=self.templatePsfSize) 

383 if np.isnan(maglim_template): 

384 self.log.info("Cannot evaluate template limiting mag; adopting science limiting mag for diffim") 

385 maglim_diffim = maglim_science 

386 else: 

387 fluxlim_template = (maglim_template*u.ABmag).to_value(u.nJy) 

388 maglim_diffim = (np.sqrt(fluxlim_science**2 + fluxlim_template**2)*u.nJy).to(u.ABmag).value 

389 self.metadata["scienceLimitingMagnitude"] = maglim_science 

390 self.metadata["templateLimitingMagnitude"] = maglim_template 

391 self.metadata["diffimLimitingMagnitude"] = maglim_diffim 

392 

393 if self.config.mode == "auto": 

394 convolveTemplate = _shapeTest(template, 

395 science, 

396 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer, 

397 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid) 

398 if convolveTemplate: 

399 if self.sciencePsfSize < self.templatePsfSize: 

400 self.log.info("Average template PSF size is greater, " 

401 "but science PSF greater in one dimension: convolving template image.") 

402 else: 

403 self.log.info("Science PSF size is greater: convolving template image.") 

404 else: 

405 self.log.info("Template PSF size is greater: convolving science image.") 

406 elif self.config.mode == "convolveTemplate": 

407 self.log.info("`convolveTemplate` is set: convolving template image.") 

408 convolveTemplate = True 

409 elif self.config.mode == "convolveScience": 

410 self.log.info("`convolveScience` is set: convolving science image.") 

411 convolveTemplate = False 

412 else: 

413 raise RuntimeError("Cannot handle AlardLuptonSubtract mode: %s", self.config.mode) 

414 

415 try: 

416 sourceMask = science.mask.clone() 

417 sourceMask.array |= template[science.getBBox()].mask.array 

418 selectSources = self._sourceSelector(sources, sourceMask) 

419 if convolveTemplate: 

420 self.metadata["convolvedExposure"] = "Template" 

421 subtractResults = self.runConvolveTemplate(template, science, selectSources) 

422 else: 

423 self.metadata["convolvedExposure"] = "Science" 

424 subtractResults = self.runConvolveScience(template, science, selectSources) 

425 

426 except (RuntimeError, lsst.pex.exceptions.Exception) as e: 

427 self.log.warning("Failed to match template. Checking coverage") 

428 # Raise NoWorkFound if template fraction is insufficient 

429 checkTemplateIsSufficient(template[science.getBBox()], science, self.log, 

430 self.config.minTemplateFractionForExpectedSuccess, 

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

432 f" Failure is tolerable: {e}") 

433 # checkTemplateIsSufficient did not raise NoWorkFound, so raise original exception 

434 raise e 

435 

436 metrics = computeDifferenceImageMetrics(science, subtractResults.difference, sources) 

437 

438 self.metadata["differenceFootprintRatioMean"] = metrics.differenceFootprintRatioMean 

439 self.metadata["differenceFootprintRatioStdev"] = metrics.differenceFootprintRatioStdev 

440 self.metadata["differenceFootprintSkyRatioMean"] = metrics.differenceFootprintSkyRatioMean 

441 self.metadata["differenceFootprintSkyRatioStdev"] = metrics.differenceFootprintSkyRatioStdev 

442 self.log.info("Mean, stdev of ratio of difference to science " 

443 "pixels in star footprints: %5.4f, %5.4f", 

444 self.metadata["differenceFootprintRatioMean"], 

445 self.metadata["differenceFootprintRatioStdev"]) 

446 

447 return subtractResults 

448 

449 def runConvolveTemplate(self, template, science, selectSources): 

450 """Convolve the template image with a PSF-matching kernel and subtract 

451 from the science image. 

452 

453 Parameters 

454 ---------- 

455 template : `lsst.afw.image.ExposureF` 

456 Template exposure, warped to match the science exposure. 

457 science : `lsst.afw.image.ExposureF` 

458 Science exposure to subtract from the template. 

459 selectSources : `lsst.afw.table.SourceCatalog` 

460 Identified sources on the science exposure. This catalog is used to 

461 select sources in order to perform the AL PSF matching on stamp 

462 images around them. 

463 

464 Returns 

465 ------- 

466 results : `lsst.pipe.base.Struct` 

467 

468 ``difference`` : `lsst.afw.image.ExposureF` 

469 Result of subtracting template and science. 

470 ``matchedTemplate`` : `lsst.afw.image.ExposureF` 

471 Warped and PSF-matched template exposure. 

472 ``backgroundModel`` : `lsst.afw.math.Function2D` 

473 Background model that was fit while solving for the PSF-matching kernel 

474 ``psfMatchingKernel`` : `lsst.afw.math.Kernel` 

475 Kernel used to PSF-match the template to the science image. 

476 """ 

477 try: 

478 kernelSources = self.makeKernel.selectKernelSources(template, science, 

479 candidateList=selectSources, 

480 preconvolved=False, 

481 templateFwhmPix=self.templatePsfSize, 

482 scienceFwhmPix=self.sciencePsfSize) 

483 kernelResult = self.makeKernel.run(template, science, kernelSources, 

484 preconvolved=False, 

485 templateFwhmPix=self.templatePsfSize, 

486 scienceFwhmPix=self.sciencePsfSize) 

487 except Exception as e: 

488 if self.config.allowKernelSourceDetection: 

489 self.log.warning("Error encountered trying to construct the matching kernel" 

490 f" Running source detection and retrying. {e}") 

491 kernelSize = self.makeKernel.makeKernelBasisList( 

492 self.templatePsfSize, self.sciencePsfSize)[0].getWidth() 

493 sigmaToFwhm = 2*np.log(2*np.sqrt(2)) 

494 candidateList = self.makeKernel.makeCandidateList(template, science, kernelSize, 

495 candidateList=None, 

496 sigma=self.sciencePsfSize/sigmaToFwhm) 

497 kernelSources = self.makeKernel.selectKernelSources(template, science, 

498 candidateList=candidateList, 

499 preconvolved=False, 

500 templateFwhmPix=self.templatePsfSize, 

501 scienceFwhmPix=self.sciencePsfSize) 

502 kernelResult = self.makeKernel.run(template, science, kernelSources, 

503 preconvolved=False, 

504 templateFwhmPix=self.templatePsfSize, 

505 scienceFwhmPix=self.sciencePsfSize) 

506 else: 

507 raise e 

508 

509 matchedTemplate = self._convolveExposure(template, kernelResult.psfMatchingKernel, 

510 self.convolutionControl, 

511 bbox=science.getBBox(), 

512 psf=science.psf, 

513 photoCalib=science.photoCalib) 

514 

515 difference = _subtractImages(science, matchedTemplate, 

516 backgroundModel=(kernelResult.backgroundModel 

517 if self.config.doSubtractBackground else None)) 

518 correctedExposure = self.finalize(template, science, difference, 

519 kernelResult.psfMatchingKernel, 

520 templateMatched=True) 

521 

522 return lsst.pipe.base.Struct(difference=correctedExposure, 

523 matchedTemplate=matchedTemplate, 

524 matchedScience=science, 

525 backgroundModel=kernelResult.backgroundModel, 

526 psfMatchingKernel=kernelResult.psfMatchingKernel, 

527 kernelSources=kernelSources) 

528 

529 def runConvolveScience(self, template, science, selectSources): 

530 """Convolve the science image with a PSF-matching kernel and subtract 

531 the template image. 

532 

533 Parameters 

534 ---------- 

535 template : `lsst.afw.image.ExposureF` 

536 Template exposure, warped to match the science exposure. 

537 science : `lsst.afw.image.ExposureF` 

538 Science exposure to subtract from the template. 

539 selectSources : `lsst.afw.table.SourceCatalog` 

540 Identified sources on the science exposure. This catalog is used to 

541 select sources in order to perform the AL PSF matching on stamp 

542 images around them. 

543 

544 Returns 

545 ------- 

546 results : `lsst.pipe.base.Struct` 

547 

548 ``difference`` : `lsst.afw.image.ExposureF` 

549 Result of subtracting template and science. 

550 ``matchedTemplate`` : `lsst.afw.image.ExposureF` 

551 Warped template exposure. Note that in this case, the template 

552 is not PSF-matched to the science image. 

553 ``backgroundModel`` : `lsst.afw.math.Function2D` 

554 Background model that was fit while solving for the PSF-matching kernel 

555 ``psfMatchingKernel`` : `lsst.afw.math.Kernel` 

556 Kernel used to PSF-match the science image to the template. 

557 """ 

558 bbox = science.getBBox() 

559 kernelSources = self.makeKernel.selectKernelSources(science, template, 

560 candidateList=selectSources, 

561 preconvolved=False, 

562 templateFwhmPix=self.templatePsfSize, 

563 scienceFwhmPix=self.sciencePsfSize) 

564 kernelResult = self.makeKernel.run(science, template, kernelSources, 

565 preconvolved=False, 

566 templateFwhmPix=self.templatePsfSize, 

567 scienceFwhmPix=self.sciencePsfSize) 

568 modelParams = kernelResult.backgroundModel.getParameters() 

569 # We must invert the background model if the matching kernel is solved for the science image. 

570 kernelResult.backgroundModel.setParameters([-p for p in modelParams]) 

571 

572 kernelImage = lsst.afw.image.ImageD(kernelResult.psfMatchingKernel.getDimensions()) 

573 norm = kernelResult.psfMatchingKernel.computeImage(kernelImage, doNormalize=False) 

574 

575 matchedScience = self._convolveExposure(science, kernelResult.psfMatchingKernel, 

576 self.convolutionControl, 

577 psf=template.psf) 

578 

579 # Place back on native photometric scale 

580 matchedScience.maskedImage /= norm 

581 matchedTemplate = template.clone()[bbox] 

582 matchedTemplate.maskedImage /= norm 

583 matchedTemplate.setPhotoCalib(science.photoCalib) 

584 

585 difference = _subtractImages(matchedScience, matchedTemplate, 

586 backgroundModel=(kernelResult.backgroundModel 

587 if self.config.doSubtractBackground else None)) 

588 

589 correctedExposure = self.finalize(template, science, difference, 

590 kernelResult.psfMatchingKernel, 

591 templateMatched=False) 

592 

593 return lsst.pipe.base.Struct(difference=correctedExposure, 

594 matchedTemplate=matchedTemplate, 

595 matchedScience=matchedScience, 

596 backgroundModel=kernelResult.backgroundModel, 

597 psfMatchingKernel=kernelResult.psfMatchingKernel, 

598 kernelSources=kernelSources) 

599 

600 def finalize(self, template, science, difference, kernel, 

601 templateMatched=True, 

602 preConvMode=False, 

603 preConvKernel=None, 

604 spatiallyVarying=False): 

605 """Decorrelate the difference image to undo the noise correlations 

606 caused by convolution. 

607 

608 Parameters 

609 ---------- 

610 template : `lsst.afw.image.ExposureF` 

611 Template exposure, warped to match the science exposure. 

612 science : `lsst.afw.image.ExposureF` 

613 Science exposure to subtract from the template. 

614 difference : `lsst.afw.image.ExposureF` 

615 Result of subtracting template and science. 

616 kernel : `lsst.afw.math.Kernel` 

617 An (optionally spatially-varying) PSF matching kernel 

618 templateMatched : `bool`, optional 

619 Was the template PSF-matched to the science image? 

620 preConvMode : `bool`, optional 

621 Was the science image preconvolved with its own PSF 

622 before PSF matching the template? 

623 preConvKernel : `lsst.afw.detection.Psf`, optional 

624 If not `None`, then the science image was pre-convolved with 

625 (the reflection of) this kernel. Must be normalized to sum to 1. 

626 spatiallyVarying : `bool`, optional 

627 Compute the decorrelation kernel spatially varying across the image? 

628 

629 Returns 

630 ------- 

631 correctedExposure : `lsst.afw.image.ExposureF` 

632 The decorrelated image difference. 

633 """ 

634 if self.config.doDecorrelation: 

635 self.log.info("Decorrelating image difference.") 

636 # We have cleared the template mask plane, so copy the mask plane of 

637 # the image difference so that we can calculate correct statistics 

638 # during decorrelation 

639 correctedExposure = self.decorrelate.run(science, template[science.getBBox()], difference, kernel, 

640 templateMatched=templateMatched, 

641 preConvMode=preConvMode, 

642 preConvKernel=preConvKernel, 

643 spatiallyVarying=spatiallyVarying).correctedExposure 

644 else: 

645 self.log.info("NOT decorrelating image difference.") 

646 correctedExposure = difference 

647 return correctedExposure 

648 

649 def _calculateMagLim(self, exposure, nsigma=5.0, fallbackPsfSize=None): 

650 """Calculate an exposure's limiting magnitude. 

651 

652 This method uses the photometric zeropoint together with the 

653 PSF size from the average position of the exposure. 

654 

655 Parameters 

656 ---------- 

657 exposure : `lsst.afw.image.Exposure` 

658 The target exposure to calculate the limiting magnitude for. 

659 nsigma : `float`, optional 

660 The detection threshold in sigma. 

661 fallbackPsfSize : `float`, optional 

662 PSF FWHM to use in the event the exposure PSF cannot be retrieved. 

663 

664 Returns 

665 ------- 

666 maglim : `astropy.units.Quantity` 

667 The limiting magnitude of the exposure, or np.nan. 

668 """ 

669 if exposure.photoCalib is None: 

670 return np.nan 

671 # Set maglim to nan upfront in case on an unexpected RuntimeError 

672 maglim = np.nan 

673 try: 

674 psf = exposure.getPsf() 

675 psf_shape = psf.computeShape(psf.getAveragePosition()) 

676 except (lsst.pex.exceptions.InvalidParameterError, 

677 afwDetection.InvalidPsfError, 

678 lsst.pex.exceptions.RangeError): 

679 if fallbackPsfSize is not None: 

680 self.log.info("Unable to evaluate PSF, using fallback FWHM %f", fallbackPsfSize) 

681 psf_area = np.pi*(fallbackPsfSize/2)**2 

682 zeropoint = exposure.photoCalib.instFluxToMagnitude(1) 

683 maglim = zeropoint - 2.5*np.log10(nsigma*np.sqrt(psf_area)) 

684 else: 

685 self.log.info("Unable to evaluate PSF, setting maglim to nan") 

686 maglim = np.nan 

687 else: 

688 # Get a more accurate area than `psf_shape.getArea()` via moments 

689 psf_area = np.pi*np.sqrt(psf_shape.getIxx()*psf_shape.getIyy()) 

690 zeropoint = exposure.photoCalib.instFluxToMagnitude(1) 

691 maglim = zeropoint - 2.5*np.log10(nsigma*np.sqrt(psf_area)) 

692 finally: 

693 return maglim 

694 

695 @staticmethod 

696 def _validateExposures(template, science): 

697 """Check that the WCS of the two Exposures match, the template bbox 

698 contains the science bbox, and that the bands match. 

699 

700 Parameters 

701 ---------- 

702 template : `lsst.afw.image.ExposureF` 

703 Template exposure, warped to match the science exposure. 

704 science : `lsst.afw.image.ExposureF` 

705 Science exposure to subtract from the template. 

706 

707 Raises 

708 ------ 

709 AssertionError 

710 Raised if the WCS of the template is not equal to the science WCS, 

711 if the science image is not fully contained in the template 

712 bounding box, or if the bands do not match. 

713 """ 

714 assert template.wcs == science.wcs, \ 

715 "Template and science exposure WCS are not identical." 

716 templateBBox = template.getBBox() 

717 scienceBBox = science.getBBox() 

718 assert science.filter.bandLabel == template.filter.bandLabel, \ 

719 "Science and template exposures have different bands: %s, %s" % \ 

720 (science.filter, template.filter) 

721 

722 assert templateBBox.contains(scienceBBox), \ 

723 "Template bbox does not contain all of the science image." 

724 

725 def _convolveExposure(self, exposure, kernel, convolutionControl, 

726 bbox=None, 

727 psf=None, 

728 photoCalib=None, 

729 interpolateBadMaskPlanes=False, 

730 ): 

731 """Convolve an exposure with the given kernel. 

732 

733 Parameters 

734 ---------- 

735 exposure : `lsst.afw.Exposure` 

736 exposure to convolve. 

737 kernel : `lsst.afw.math.LinearCombinationKernel` 

738 PSF matching kernel computed in the ``makeKernel`` subtask. 

739 convolutionControl : `lsst.afw.math.ConvolutionControl` 

740 Configuration for convolve algorithm. 

741 bbox : `lsst.geom.Box2I`, optional 

742 Bounding box to trim the convolved exposure to. 

743 psf : `lsst.afw.detection.Psf`, optional 

744 Point spread function (PSF) to set for the convolved exposure. 

745 photoCalib : `lsst.afw.image.PhotoCalib`, optional 

746 Photometric calibration of the convolved exposure. 

747 

748 Returns 

749 ------- 

750 convolvedExp : `lsst.afw.Exposure` 

751 The convolved image. 

752 """ 

753 convolvedExposure = exposure.clone() 

754 if psf is not None: 

755 convolvedExposure.setPsf(psf) 

756 if photoCalib is not None: 

757 convolvedExposure.setPhotoCalib(photoCalib) 

758 if interpolateBadMaskPlanes and self.config.badMaskPlanes is not None: 

759 nInterp = _interpolateImage(convolvedExposure.maskedImage, 

760 self.config.badMaskPlanes) 

761 self.metadata["nInterpolated"] = nInterp 

762 convolvedImage = lsst.afw.image.MaskedImageF(convolvedExposure.getBBox()) 

763 lsst.afw.math.convolve(convolvedImage, convolvedExposure.maskedImage, kernel, convolutionControl) 

764 convolvedExposure.setMaskedImage(convolvedImage) 

765 if bbox is None: 

766 return convolvedExposure 

767 else: 

768 return convolvedExposure[bbox] 

769 

770 def _sourceSelector(self, sources, mask): 

771 """Select sources from a catalog that meet the selection criteria. 

772 

773 Parameters 

774 ---------- 

775 sources : `lsst.afw.table.SourceCatalog` 

776 Input source catalog to select sources from. 

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

778 The image mask plane to use to reject sources 

779 based on their location on the ccd. 

780 

781 Returns 

782 ------- 

783 selectSources : `lsst.afw.table.SourceCatalog` 

784 The input source catalog, with flagged and low signal-to-noise 

785 sources removed. 

786 

787 Raises 

788 ------ 

789 RuntimeError 

790 If there are too few sources to compute the PSF matching kernel 

791 remaining after source selection. 

792 """ 

793 

794 selected = self.sourceSelector.selectSources(sources).selected 

795 nInitialSelected = np.count_nonzero(selected) 

796 nSelected = np.count_nonzero(selected) 

797 self.log.info("Rejecting %i candidate sources: an excluded template mask plane is set.", 

798 nInitialSelected - nSelected) 

799 selectSources = sources[selected].copy(deep=True) 

800 # Trim selectSources if they exceed ``maxKernelSources``. 

801 # Keep the highest signal-to-noise sources of those selected. 

802 if (len(selectSources) > self.config.maxKernelSources) & (self.config.maxKernelSources > 0): 

803 signalToNoise = selectSources.getPsfInstFlux()/selectSources.getPsfInstFluxErr() 

804 indices = np.argsort(signalToNoise) 

805 indices = indices[-self.config.maxKernelSources:] 

806 selected = np.zeros(len(selectSources), dtype=bool) 

807 selected[indices] = True 

808 selectSources = selectSources[selected].copy(deep=True) 

809 

810 self.log.info("%i/%i=%.1f%% of sources selected for PSF matching from the input catalog", 

811 len(selectSources), len(sources), 100*len(selectSources)/len(sources)) 

812 if len(selectSources) < self.config.minKernelSources: 

813 self.log.error("Too few sources to calculate the PSF matching kernel: " 

814 "%i selected but %i needed for the calculation.", 

815 len(selectSources), self.config.minKernelSources) 

816 if not self.config.allowKernelSourceDetection: 

817 raise RuntimeError("Cannot compute PSF matching kernel: too few sources selected.") 

818 self.metadata["nPsfSources"] = len(selectSources) 

819 

820 return selectSources 

821 

822 def _prepareInputs(self, template, science, visitSummary=None): 

823 """Perform preparatory calculations common to all Alard&Lupton Tasks. 

824 

825 Parameters 

826 ---------- 

827 template : `lsst.afw.image.ExposureF` 

828 Template exposure, warped to match the science exposure. The 

829 variance plane of the template image is modified in place. 

830 science : `lsst.afw.image.ExposureF` 

831 Science exposure to subtract from the template. The variance plane 

832 of the science image is modified in place. 

833 visitSummary : `lsst.afw.table.ExposureCatalog`, optional 

834 Exposure catalog with external calibrations to be applied. Catalog 

835 uses the detector id for the catalog id, sorted on id for fast 

836 lookup. 

837 """ 

838 self._validateExposures(template, science) 

839 if visitSummary is not None: 

840 self._applyExternalCalibrations(science, visitSummary=visitSummary) 

841 templateCoverageFraction = checkTemplateIsSufficient( 

842 template[science.getBBox()], science, self.log, 

843 requiredTemplateFraction=self.config.requiredTemplateFraction, 

844 exceptionMessage="Not attempting subtraction. To force subtraction," 

845 " set config requiredTemplateFraction=0" 

846 ) 

847 self.metadata["templateCoveragePercent"] = 100*templateCoverageFraction 

848 

849 if self.config.doScaleVariance: 

850 # Scale the variance of the template and science images before 

851 # convolution, subtraction, or decorrelation so that they have the 

852 # correct ratio. 

853 templateVarFactor = self.scaleVariance.run(template.maskedImage) 

854 sciVarFactor = self.scaleVariance.run(science.maskedImage) 

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

856 self.metadata["scaleTemplateVarianceFactor"] = templateVarFactor 

857 self.log.info("Science variance scaling factor: %.2f", sciVarFactor) 

858 self.metadata["scaleScienceVarianceFactor"] = sciVarFactor 

859 

860 # Erase existing detection mask planes. 

861 # We don't want the detection mask from the science image 

862 self.updateMasks(template, science) 

863 

864 # Calling getPsfFwhm on template.psf fails on some rare occasions when 

865 # the template has no input exposures at the average position of the 

866 # stars. So we try getPsfFwhm first on template, and if that fails we 

867 # evaluate the PSF on a grid specified by fwhmExposure* fields. 

868 # To keep consistent definitions for PSF size on the template and 

869 # science images, we use the same method for both. 

870 # In the try block below, we catch two exceptions: 

871 # 1. InvalidParameterError, in case the point where we are evaluating 

872 # the PSF lands in a gap in the template. 

873 # 2. RangeError, in case the template coverage is so poor that we end 

874 # up near a region with no data. 

875 try: 

876 self.templatePsfSize = getPsfFwhm(template.psf) 

877 self.sciencePsfSize = getPsfFwhm(science.psf) 

878 except lsst.pex.exceptions.Exception: 

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

880 # Catching: 

881 # - lsst::geom::SingularTransformException 

882 # - lsst.pex.exceptions.InvalidParameterError 

883 # - lsst.pex.exceptions.RangeError 

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

885 "Evaluting PSF on a grid of points." 

886 ) 

887 self.templatePsfSize = evaluateMeanPsfFwhm( 

888 template, 

889 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer, 

890 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid 

891 ) 

892 self.sciencePsfSize = evaluateMeanPsfFwhm( 

893 science, 

894 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer, 

895 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid 

896 ) 

897 self.log.info("Science PSF FWHM: %f pixels", self.sciencePsfSize) 

898 self.log.info("Template PSF FWHM: %f pixels", self.templatePsfSize) 

899 self.metadata["sciencePsfSize"] = self.sciencePsfSize 

900 self.metadata["templatePsfSize"] = self.templatePsfSize 

901 

902 def updateMasks(self, template, science): 

903 """Update the science and template mask planes before differencing. 

904 

905 Parameters 

906 ---------- 

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

908 Template exposure, warped to match the science exposure. 

909 The template mask planes will be erased, except for a few specified 

910 in the task config. 

911 science : `lsst.afw.image.Exposure` 

912 Science exposure to subtract from the template. 

913 The DETECTED and DETECTED_NEGATIVE mask planes of the science image 

914 will be erased. 

915 """ 

916 self._clearMask(science.mask, clearMaskPlanes=["DETECTED", "DETECTED_NEGATIVE"]) 

917 

918 # We will clear ALL template mask planes, except for those specified 

919 # via the `preserveTemplateMask` config. Mask planes specified via 

920 # the `renameTemplateMask` config will be copied to new planes with 

921 # "_TEMPLATE" appended to their names, and the original mask plane will 

922 # be cleared. 

923 clearMaskPlanes = [mp for mp in template.mask.getMaskPlaneDict().keys() 

924 if mp not in self.config.preserveTemplateMask] 

925 renameMaskPlanes = [mp for mp in self.config.renameTemplateMask 

926 if mp in template.mask.getMaskPlaneDict().keys()] 

927 

928 # propagate the mask plane related to Fake source injection 

929 # NOTE: the fake source injection sets FAKE plane, but it should be INJECTED 

930 # NOTE: This can be removed in DM-40796 

931 if "FAKE" in science.mask.getMaskPlaneDict().keys(): 

932 self.log.info("Adding injected mask plane to science image") 

933 self._renameMaskPlanes(science.mask, "FAKE", "INJECTED") 

934 if "FAKE" in template.mask.getMaskPlaneDict().keys(): 

935 self.log.info("Adding injected mask plane to template image") 

936 self._renameMaskPlanes(template.mask, "FAKE", "INJECTED_TEMPLATE") 

937 if "INJECTED" in renameMaskPlanes: 

938 renameMaskPlanes.remove("INJECTED") 

939 if "INJECTED_TEMPLATE" in clearMaskPlanes: 

940 clearMaskPlanes.remove("INJECTED_TEMPLATE") 

941 

942 for maskPlane in renameMaskPlanes: 

943 self._renameMaskPlanes(template.mask, maskPlane, maskPlane + "_TEMPLATE") 

944 self._clearMask(template.mask, clearMaskPlanes=clearMaskPlanes) 

945 

946 @staticmethod 

947 def _renameMaskPlanes(mask, maskPlane, newMaskPlane): 

948 """Rename a mask plane by adding the new name and copying the data. 

949 

950 Parameters 

951 ---------- 

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

953 The mask image to update in place. 

954 maskPlane : `str` 

955 The name of the existing mask plane to copy. 

956 newMaskPlane : `str` 

957 The new name of the mask plane that will be added. 

958 If the mask plane already exists, it will be updated in place. 

959 """ 

960 mask.addMaskPlane(newMaskPlane) 

961 originBitMask = mask.getPlaneBitMask(maskPlane) 

962 destinationBitMask = mask.getPlaneBitMask(newMaskPlane) 

963 mask.array |= ((mask.array & originBitMask) > 0)*destinationBitMask 

964 

965 def _clearMask(self, mask, clearMaskPlanes=None): 

966 """Clear the mask plane of an exposure. 

967 

968 Parameters 

969 ---------- 

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

971 The mask plane to erase, which will be modified in place. 

972 clearMaskPlanes : `list` of `str`, optional 

973 Erase the specified mask planes. 

974 If not supplied, the entire mask will be erased. 

975 """ 

976 if clearMaskPlanes is None: 

977 clearMaskPlanes = list(mask.getMaskPlaneDict().keys()) 

978 

979 bitMaskToClear = mask.getPlaneBitMask(clearMaskPlanes) 

980 mask &= ~bitMaskToClear 

981 

982 

983class AlardLuptonPreconvolveSubtractConnections(SubtractInputConnections, 

984 SubtractScoreOutputConnections): 

985 pass 

986 

987 

988class AlardLuptonPreconvolveSubtractConfig(AlardLuptonSubtractBaseConfig, lsst.pipe.base.PipelineTaskConfig, 

989 pipelineConnections=AlardLuptonPreconvolveSubtractConnections): 

990 pass 

991 

992 

993class AlardLuptonPreconvolveSubtractTask(AlardLuptonSubtractTask): 

994 """Subtract a template from a science image, convolving the science image 

995 before computing the kernel, and also convolving the template before 

996 subtraction. 

997 """ 

998 ConfigClass = AlardLuptonPreconvolveSubtractConfig 

999 _DefaultName = "alardLuptonPreconvolveSubtract" 

1000 

1001 def run(self, template, science, sources, visitSummary=None): 

1002 """Preconvolve the science image with its own PSF, 

1003 convolve the template image with a PSF-matching kernel and subtract 

1004 from the preconvolved science image. 

1005 

1006 Parameters 

1007 ---------- 

1008 template : `lsst.afw.image.ExposureF` 

1009 The template image, which has previously been warped to the science 

1010 image. The template bbox will be padded by a few pixels compared to 

1011 the science bbox. 

1012 science : `lsst.afw.image.ExposureF` 

1013 The science exposure. 

1014 sources : `lsst.afw.table.SourceCatalog` 

1015 Identified sources on the science exposure. This catalog is used to 

1016 select sources in order to perform the AL PSF matching on stamp 

1017 images around them. 

1018 visitSummary : `lsst.afw.table.ExposureCatalog`, optional 

1019 Exposure catalog with complete external calibrations. Catalog uses 

1020 the detector id for the catalog id, sorted on id for fast lookup. 

1021 

1022 Returns 

1023 ------- 

1024 results : `lsst.pipe.base.Struct` 

1025 ``scoreExposure`` : `lsst.afw.image.ExposureF` 

1026 Result of subtracting the convolved template and science 

1027 images. Attached PSF is that of the original science image. 

1028 ``matchedTemplate`` : `lsst.afw.image.ExposureF` 

1029 Warped and PSF-matched template exposure. Attached PSF is that 

1030 of the original science image. 

1031 ``matchedScience`` : `lsst.afw.image.ExposureF` 

1032 The science exposure after convolving with its own PSF. 

1033 Attached PSF is that of the original science image. 

1034 ``backgroundModel`` : `lsst.afw.math.Function2D` 

1035 Background model that was fit while solving for the 

1036 PSF-matching kernel 

1037 ``psfMatchingKernel`` : `lsst.afw.math.Kernel` 

1038 Final kernel used to PSF-match the template to the science 

1039 image. 

1040 """ 

1041 self._prepareInputs(template, science, visitSummary=visitSummary) 

1042 

1043 # TODO: DM-37212 we need to mirror the kernel in order to get correct cross correlation 

1044 scienceKernel = science.psf.getKernel() 

1045 matchedScience = self._convolveExposure(science, scienceKernel, self.convolutionControl, 

1046 interpolateBadMaskPlanes=True) 

1047 self.metadata["convolvedExposure"] = "Preconvolution" 

1048 try: 

1049 selectSources = self._sourceSelector(sources, matchedScience.mask) 

1050 subtractResults = self.runPreconvolve(template, science, matchedScience, 

1051 selectSources, scienceKernel) 

1052 

1053 except (RuntimeError, lsst.pex.exceptions.Exception) as e: 

1054 self.log.warning("Failed to match template. Checking coverage") 

1055 # Raise NoWorkFound if template fraction is insufficient 

1056 checkTemplateIsSufficient(template[science.getBBox()], science, self.log, 

1057 self.config.minTemplateFractionForExpectedSuccess, 

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

1059 f" Failure is tolerable: {e}") 

1060 # checkTemplateIsSufficient did not raise NoWorkFound, so raise original exception 

1061 raise e 

1062 

1063 return subtractResults 

1064 

1065 def runPreconvolve(self, template, science, matchedScience, selectSources, preConvKernel): 

1066 """Convolve the science image with its own PSF, then convolve the 

1067 template with a matching kernel and subtract to form the Score 

1068 exposure. 

1069 

1070 Parameters 

1071 ---------- 

1072 template : `lsst.afw.image.ExposureF` 

1073 Template exposure, warped to match the science exposure. 

1074 science : `lsst.afw.image.ExposureF` 

1075 Science exposure to subtract from the template. 

1076 matchedScience : `lsst.afw.image.ExposureF` 

1077 The science exposure, convolved with the reflection of its own PSF. 

1078 selectSources : `lsst.afw.table.SourceCatalog` 

1079 Identified sources on the science exposure. This catalog is used to 

1080 select sources in order to perform the AL PSF matching on stamp 

1081 images around them. 

1082 preConvKernel : `lsst.afw.math.Kernel` 

1083 The reflection of the kernel that was used to preconvolve the 

1084 `science` exposure. Must be normalized to sum to 1. 

1085 

1086 Returns 

1087 ------- 

1088 results : `lsst.pipe.base.Struct` 

1089 

1090 ``scoreExposure`` : `lsst.afw.image.ExposureF` 

1091 Result of subtracting the convolved template and science 

1092 images. Attached PSF is that of the original science image. 

1093 ``matchedTemplate`` : `lsst.afw.image.ExposureF` 

1094 Warped and PSF-matched template exposure. Attached PSF is that 

1095 of the original science image. 

1096 ``matchedScience`` : `lsst.afw.image.ExposureF` 

1097 The science exposure after convolving with its own PSF. 

1098 Attached PSF is that of the original science image. 

1099 ``backgroundModel`` : `lsst.afw.math.Function2D` 

1100 Background model that was fit while solving for the 

1101 PSF-matching kernel 

1102 ``psfMatchingKernel`` : `lsst.afw.math.Kernel` 

1103 Final kernel used to PSF-match the template to the science 

1104 image. 

1105 """ 

1106 bbox = science.getBBox() 

1107 innerBBox = preConvKernel.shrinkBBox(bbox) 

1108 

1109 kernelSources = self.makeKernel.selectKernelSources(template[innerBBox], matchedScience[innerBBox], 

1110 candidateList=selectSources, 

1111 preconvolved=True, 

1112 templateFwhmPix=self.templatePsfSize, 

1113 scienceFwhmPix=self.sciencePsfSize) 

1114 kernelResult = self.makeKernel.run(template[innerBBox], matchedScience[innerBBox], kernelSources, 

1115 preconvolved=True, 

1116 templateFwhmPix=self.templatePsfSize, 

1117 scienceFwhmPix=self.sciencePsfSize) 

1118 

1119 matchedTemplate = self._convolveExposure(template, kernelResult.psfMatchingKernel, 

1120 self.convolutionControl, 

1121 bbox=bbox, 

1122 psf=science.psf, 

1123 interpolateBadMaskPlanes=True, 

1124 photoCalib=science.photoCalib) 

1125 score = _subtractImages(matchedScience, matchedTemplate, 

1126 backgroundModel=(kernelResult.backgroundModel 

1127 if self.config.doSubtractBackground else None)) 

1128 correctedScore = self.finalize(template[bbox], science, score, 

1129 kernelResult.psfMatchingKernel, 

1130 templateMatched=True, preConvMode=True, 

1131 preConvKernel=preConvKernel) 

1132 

1133 return lsst.pipe.base.Struct(scoreExposure=correctedScore, 

1134 matchedTemplate=matchedTemplate, 

1135 matchedScience=matchedScience, 

1136 backgroundModel=kernelResult.backgroundModel, 

1137 psfMatchingKernel=kernelResult.psfMatchingKernel, 

1138 kernelSources=kernelSources) 

1139 

1140 

1141def checkTemplateIsSufficient(templateExposure, scienceExposure, logger, requiredTemplateFraction=0., 

1142 exceptionMessage=""): 

1143 """Raise NoWorkFound if template coverage < requiredTemplateFraction 

1144 

1145 Parameters 

1146 ---------- 

1147 templateExposure : `lsst.afw.image.ExposureF` 

1148 The template exposure to check 

1149 logger : `logging.Logger` 

1150 Logger for printing output. 

1151 requiredTemplateFraction : `float`, optional 

1152 Fraction of pixels of the science image required to have coverage 

1153 in the template. 

1154 exceptionMessage : `str`, optional 

1155 Message to include in the exception raised if the template coverage 

1156 is insufficient. 

1157 

1158 Returns 

1159 ------- 

1160 templateCoverageFraction: `float` 

1161 Fraction of pixels in the template with data. 

1162 

1163 Raises 

1164 ------ 

1165 lsst.pipe.base.NoWorkFound 

1166 Raised if fraction of good pixels, defined as not having NO_DATA 

1167 set, is less than the requiredTemplateFraction 

1168 """ 

1169 # Count the number of pixels with the NO_DATA mask bit set 

1170 # counting NaN pixels is insufficient because pixels without data are often intepolated over) 

1171 noTemplate = templateExposure.mask.array & templateExposure.mask.getPlaneBitMask('NO_DATA') 

1172 # Also need to account for missing data in the science image, 

1173 # because template coverage there doesn't help 

1174 noScience = scienceExposure.mask.array & scienceExposure.mask.getPlaneBitMask('NO_DATA') 

1175 pixNoData = np.count_nonzero(noTemplate | noScience) 

1176 pixGood = templateExposure.getBBox().getArea() - pixNoData 

1177 templateCoverageFraction = pixGood/templateExposure.getBBox().getArea() 

1178 logger.info("template has %d good pixels (%.1f%%)", pixGood, 100*templateCoverageFraction) 

1179 

1180 if templateCoverageFraction < requiredTemplateFraction: 

1181 message = ("Insufficient Template Coverage. (%.1f%% < %.1f%%)" % ( 

1182 100*templateCoverageFraction, 

1183 100*requiredTemplateFraction)) 

1184 raise lsst.pipe.base.NoWorkFound(message + " " + exceptionMessage) 

1185 return templateCoverageFraction 

1186 

1187 

1188def _subtractImages(science, template, backgroundModel=None): 

1189 """Subtract template from science, propagating relevant metadata. 

1190 

1191 Parameters 

1192 ---------- 

1193 science : `lsst.afw.Exposure` 

1194 The input science image. 

1195 template : `lsst.afw.Exposure` 

1196 The template to subtract from the science image. 

1197 backgroundModel : `lsst.afw.MaskedImage`, optional 

1198 Differential background model 

1199 

1200 Returns 

1201 ------- 

1202 difference : `lsst.afw.Exposure` 

1203 The subtracted image. 

1204 """ 

1205 difference = science.clone() 

1206 if backgroundModel is not None: 

1207 difference.maskedImage -= backgroundModel 

1208 difference.maskedImage -= template.maskedImage 

1209 return difference 

1210 

1211 

1212def _shapeTest(exp1, exp2, fwhmExposureBuffer, fwhmExposureGrid): 

1213 """Determine that the PSF of ``exp1`` is not wider than that of ``exp2``. 

1214 

1215 Parameters 

1216 ---------- 

1217 exp1 : `~lsst.afw.image.Exposure` 

1218 Exposure with the reference point spread function (PSF) to evaluate. 

1219 exp2 : `~lsst.afw.image.Exposure` 

1220 Exposure with a candidate point spread function (PSF) to evaluate. 

1221 fwhmExposureBuffer : `float` 

1222 Fractional buffer margin to be left out of all sides of the image 

1223 during the construction of the grid to compute mean PSF FWHM in an 

1224 exposure, if the PSF is not available at its average position. 

1225 fwhmExposureGrid : `int` 

1226 Grid size to compute the mean FWHM in an exposure, if the PSF is not 

1227 available at its average position. 

1228 Returns 

1229 ------- 

1230 result : `bool` 

1231 True if ``exp1`` has a PSF that is not wider than that of ``exp2`` in 

1232 either dimension. 

1233 """ 

1234 try: 

1235 shape1 = getPsfFwhm(exp1.psf, average=False) 

1236 shape2 = getPsfFwhm(exp2.psf, average=False) 

1237 except (lsst.pex.exceptions.InvalidParameterError, lsst.pex.exceptions.RangeError): 

1238 shape1 = evaluateMeanPsfFwhm(exp1, 

1239 fwhmExposureBuffer=fwhmExposureBuffer, 

1240 fwhmExposureGrid=fwhmExposureGrid 

1241 ) 

1242 shape2 = evaluateMeanPsfFwhm(exp2, 

1243 fwhmExposureBuffer=fwhmExposureBuffer, 

1244 fwhmExposureGrid=fwhmExposureGrid 

1245 ) 

1246 return shape1 <= shape2 

1247 

1248 # Results from getPsfFwhm is a tuple of two values, one for each dimension. 

1249 xTest = shape1[0] <= shape2[0] 

1250 yTest = shape1[1] <= shape2[1] 

1251 return xTest | yTest 

1252 

1253 

1254def _interpolateImage(maskedImage, badMaskPlanes, fallbackValue=None): 

1255 """Replace masked image pixels with interpolated values. 

1256 

1257 Parameters 

1258 ---------- 

1259 maskedImage : `lsst.afw.image.MaskedImage` 

1260 Image on which to perform interpolation. 

1261 badMaskPlanes : `list` of `str` 

1262 List of mask planes to interpolate over. 

1263 fallbackValue : `float`, optional 

1264 Value to set when interpolation fails. 

1265 

1266 Returns 

1267 ------- 

1268 result: `float` 

1269 The number of masked pixels that were replaced. 

1270 """ 

1271 imgBadMaskPlanes = [ 

1272 maskPlane for maskPlane in badMaskPlanes if maskPlane in maskedImage.mask.getMaskPlaneDict() 

1273 ] 

1274 

1275 image = maskedImage.image.array 

1276 badPixels = (maskedImage.mask.array & maskedImage.mask.getPlaneBitMask(imgBadMaskPlanes)) > 0 

1277 image[badPixels] = np.nan 

1278 if fallbackValue is None: 

1279 fallbackValue = np.nanmedian(image) 

1280 # For this initial implementation, skip the interpolation and just fill with 

1281 # the median value. 

1282 image[badPixels] = fallbackValue 

1283 return np.sum(badPixels)