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

555 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-26 20:30 +0000

1# This file is part of ip_diffim. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

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

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

7# for details of code ownership. 

8# 

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

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

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

12# (at your option) any later version. 

13# 

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

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

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

17# GNU General Public License for more details. 

18# 

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

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

21 

22import dataclasses 

23 

24from astropy import units as u 

25from astropy.stats import gaussian_fwhm_to_sigma 

26import numpy as np 

27 

28import lsst.afw.detection as afwDetection 

29import lsst.afw.image 

30import lsst.afw.math 

31import lsst.geom 

32from lsst.images import DifferenceImage 

33from lsst.images.convolution_kernels import ImageBasisConvolutionKernel 

34from lsst.ip.diffim.utils import (evaluateMeanPsfFwhm, getPsfFwhm, 

35 computeDifferenceImageMetrics, computePSFNoiseEquivalentArea, 

36 checkMask, record_from_obs_info, setSourceFootprints, 

37 get_difference_image_provenance, checkTemplateIsSufficient) 

38from lsst.meas.algorithms import ScaleVarianceTask, ScienceSourceSelectorTask 

39import lsst.pex.config 

40import lsst.pipe.base 

41import lsst.pex.exceptions 

42from lsst.pipe.base import connectionTypes 

43from . import MakeKernelTask, DecorrelateALKernelTask 

44from lsst.utils.timer import timeMethod 

45 

46__all__ = ["AlardLuptonSubtractConfig", "AlardLuptonSubtractTask", 

47 "AlardLuptonPreconvolveSubtractConfig", "AlardLuptonPreconvolveSubtractTask", 

48 "SimplifiedSubtractConfig", "SimplifiedSubtractTask", 

49 "InsufficientKernelSourcesError"] 

50 

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

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

53 

54 

55class InsufficientKernelSourcesError(lsst.pipe.base.AlgorithmError): 

56 """Raised when there are too few sources to calculate the PSF matching 

57 kernel. 

58 """ 

59 def __init__(self, *, nSources, nRequired): 

60 msg = (f"Only {nSources} sources were selected for PSF matching," 

61 f" but {nRequired} are required.") 

62 super().__init__(msg) 

63 self.nSources = nSources 

64 self.nRequired = nRequired 

65 

66 @property 

67 def metadata(self): 

68 return {"nSources": self.nSources, 

69 "nRequired": self.nRequired 

70 } 

71 

72 

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

74 dimensions=_dimensions, 

75 defaultTemplates=_defaultTemplates): 

76 template = connectionTypes.Input( 

77 doc="Input warped template to subtract." 

78 " With image_type='future' this is read as a lsst.images.DifferenceImage, so that the" 

79 " record of the coadds that went into it can be passed on to the outputs.", 

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

81 storageClass="ExposureF", 

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

83 ) 

84 science = connectionTypes.Input( 

85 doc="Input science exposure to subtract from." 

86 " With image_type='future' this is read as a lsst.images.VisitImage, so that its" 

87 " photometric scaling can be passed on to the outputs.", 

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

89 storageClass="ExposureF", 

90 name="{fakesType}calexp" 

91 ) 

92 sources = connectionTypes.Input( 

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

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

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

96 storageClass="SourceCatalog", 

97 name="{fakesType}src" 

98 ) 

99 visitSummary = connectionTypes.Input( 

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

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

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

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

104 storageClass="ExposureCatalog", 

105 name="finalVisitSummary", 

106 ) 

107 

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

109 super().__init__(config=config) 

110 if not config.doApplyExternalCalibrations: 110 ↛ 112line 110 didn't jump to line 112 because the condition on line 110 was always true

111 del self.visitSummary 

112 if config.image_type == "future": 

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

114 self.science = dataclasses.replace(self.science, storageClass="VisitImage") 

115 

116 

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

118 dimensions=_dimensions, 

119 defaultTemplates=_defaultTemplates): 

120 difference = connectionTypes.Output( 

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

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

123 storageClass="ExposureF", 

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

125 ) 

126 matchedTemplate = connectionTypes.Output( 

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

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

129 storageClass="ExposureF", 

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

131 ) 

132 psfMatchingKernel = connectionTypes.Output( 

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

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

135 storageClass="MatchingKernel", 

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

137 ) 

138 kernelSources = connectionTypes.Output( 

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

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

141 storageClass="SourceCatalog", 

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

143 ) 

144 

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

146 super().__init__(config=config) 

147 if config.image_type == "future": 

148 self.difference = dataclasses.replace(self.difference, storageClass="DifferenceImage") 

149 self.matchedTemplate = dataclasses.replace(self.matchedTemplate, 

150 storageClass="DifferenceImage") 

151 self.psfMatchingKernel = dataclasses.replace(self.psfMatchingKernel, 

152 storageClass="ConvolutionKernel") 

153 

154 

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

156 dimensions=_dimensions, 

157 defaultTemplates=_defaultTemplates): 

158 scoreExposure = connectionTypes.Output( 

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

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

161 storageClass="ExposureF", 

162 name="{fakesType}{coaddName}Diff_scoreTempExp", 

163 ) 

164 psfMatchingKernel = connectionTypes.Output( 

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

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

167 storageClass="MatchingKernel", 

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

169 ) 

170 kernelSources = connectionTypes.Output( 

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

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

173 storageClass="SourceCatalog", 

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

175 ) 

176 

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

178 super().__init__(config=config) 

179 if config.image_type == "future": 

180 self.scoreExposure = dataclasses.replace(self.scoreExposure, storageClass="DifferenceImage") 

181 self.psfMatchingKernel = dataclasses.replace(self.psfMatchingKernel, 

182 storageClass="ConvolutionKernel") 

183 

184 

185class AlardLuptonSubtractConnections(SubtractInputConnections, SubtractImageOutputConnections): 

186 pass 

187 

188 

189class SimplifiedSubtractConnections(SubtractInputConnections, SubtractImageOutputConnections): 

190 inputPsfMatchingKernel = connectionTypes.Input( 

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

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

193 storageClass="MatchingKernel", 

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

195 ) 

196 

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

198 super().__init__(config=config) 

199 del self.sources 

200 if config.useExistingKernel: 200 ↛ 207line 200 didn't jump to line 207 because the condition on line 200 was always true

201 del self.psfMatchingKernel 

202 del self.kernelSources 

203 if config.image_type == "future": 

204 self.inputPsfMatchingKernel = dataclasses.replace(self.inputPsfMatchingKernel, 

205 storageClass="ConvolutionKernel") 

206 else: 

207 del self.inputPsfMatchingKernel 

208 

209 

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

211 makeKernel = lsst.pex.config.ConfigurableField( 

212 target=MakeKernelTask, 

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

214 ) 

215 doDecorrelation = lsst.pex.config.Field( 

216 dtype=bool, 

217 default=True, 

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

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

220 ) 

221 decorrelate = lsst.pex.config.ConfigurableField( 

222 target=DecorrelateALKernelTask, 

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

224 ) 

225 requiredTemplateFraction = lsst.pex.config.Field( 

226 dtype=float, 

227 default=0.1, 

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

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

230 ) 

231 minTemplateFractionForExpectedSuccess = lsst.pex.config.Field( 

232 dtype=float, 

233 default=0.2, 

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

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

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

237 ) 

238 doScaleVariance = lsst.pex.config.Field( 

239 dtype=bool, 

240 default=True, 

241 doc="Scale variance of the science image? Note that the template variance is NOT scaled" 

242 " here. The template variance may be scaled independently in ``GetTemplateTask``." 

243 ) 

244 scaleVariance = lsst.pex.config.ConfigurableField( 

245 target=ScaleVarianceTask, 

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

247 ) 

248 doSubtractBackground = lsst.pex.config.Field( 

249 doc="Subtract the background fit when solving the kernel? " 

250 "It is generally better to instead subtract the background in detectAndMeasure.", 

251 dtype=bool, 

252 default=False, 

253 deprecated="Subtract the background in detectAndMeasure instead. Will be removed after v31.", 

254 ) 

255 doApplyExternalCalibrations = lsst.pex.config.Field( 

256 doc=( 

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

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

259 ), 

260 dtype=bool, 

261 default=False, 

262 ) 

263 sourceSelector = lsst.pex.config.ConfigurableField( 

264 target=ScienceSourceSelectorTask, 

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

266 ) 

267 fallbackSourceSelector = lsst.pex.config.ConfigurableField( 

268 target=ScienceSourceSelectorTask, 

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

270 "Used only if the kernel calculation fails and" 

271 "`allowKernelSourceDetection` is set. The fallback source detection" 

272 " will not include all of the same plugins as the original source " 

273 " detection, so not all of the same flags can be used.", 

274 ) 

275 detectionThreshold = lsst.pex.config.Field( 

276 dtype=float, 

277 default=10, 

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

279 "to use for calculating the PSF matching kernel.", 

280 deprecated="No longer used. Will be removed after v30" 

281 ) 

282 detectionThresholdMax = lsst.pex.config.Field( 

283 dtype=float, 

284 default=500, 

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

286 "to use for calculating the PSF matching kernel.", 

287 deprecated="No longer used. Will be removed after v30" 

288 ) 

289 restrictKernelEdgeSources = lsst.pex.config.Field( 

290 dtype=bool, 

291 default=True, 

292 doc="Exclude sources close to the edge from the kernel calculation?" 

293 ) 

294 maxKernelSources = lsst.pex.config.Field( 

295 dtype=int, 

296 default=1000, 

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

298 "Set to -1 to disable." 

299 ) 

300 minKernelSources = lsst.pex.config.Field( 

301 dtype=int, 

302 default=3, 

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

304 ) 

305 excludeMaskPlanes = lsst.pex.config.ListField( 

306 dtype=str, 

307 default=("NO_DATA", "BAD", "SAT", "EDGE", "FAKE", "HIGH_VARIANCE"), 

308 doc="Template mask planes to exclude when selecting sources for PSF matching.", 

309 ) 

310 badMaskPlanes = lsst.pex.config.ListField( 

311 dtype=str, 

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

313 doc="Mask planes to interpolate over." 

314 ) 

315 preserveTemplateMask = lsst.pex.config.ListField( 

316 dtype=str, 

317 default=("NO_DATA", "BAD", "HIGH_VARIANCE"), 

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

319 ) 

320 renameTemplateMask = lsst.pex.config.ListField( 

321 dtype=str, 

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

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

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

325 ) 

326 preserveMaskPlanes = lsst.pex.config.ListField( 

327 dtype=str, 

328 default=("INJECTED", "INJECTED_CORE", "INJECTED_TEMPLATE", "INJECTED_CORE_TEMPLATE"), 

329 doc="Mask planes to preserve without dilation when convolving the image.", 

330 ) 

331 allowKernelSourceDetection = lsst.pex.config.Field( 

332 dtype=bool, 

333 default=False, 

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

335 " encountered while calculating the matching kernel." 

336 ) 

337 image_type = lsst.pex.config.ChoiceField[str]( 

338 doc="Image type of the input template, the image outputs of this" 

339 " task (difference and matchedTemplate, or scoreExposure), and the PSF" 

340 " matching kernel.", 

341 allowed={ 

342 "legacy": "Read and write lsst.afw.image.ExposureF and" 

343 " lsst.afw.math.Kernel.", 

344 "future": "Read and write lsst.images.DifferenceImage and" 

345 " lsst.images.convolution_kernels.ConvolutionKernel.", 

346 }, 

347 optional=False, 

348 default="legacy", 

349 ) 

350 

351 def setDefaults(self): 

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

353 # Always include background fitting in the kernel fit, 

354 # even if it is not subtracted 

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

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

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

358 # Shared source selector settings 

359 doSkySources = False # Do not include sky sources 

360 doSignalToNoise = True # apply signal to noise filter 

361 doUnresolved = True # apply star-galaxy separation 

362 signalToNoiseMinimum = 10 

363 signalToNoiseMaximum = 500 

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

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

366 self.sourceSelector.doUnresolved = doUnresolved 

367 self.sourceSelector.doSkySources = doSkySources 

368 self.sourceSelector.doSignalToNoise = doSignalToNoise 

369 self.sourceSelector.signalToNoise.minimum = signalToNoiseMinimum 

370 self.sourceSelector.signalToNoise.maximum = signalToNoiseMaximum 

371 # The following two configs should not be necessary to be turned on for 

372 # PSF-matching, and the fallback kernel source selection will fail if 

373 # they are set since it does not run deblending. 

374 self.fallbackSourceSelector.doIsolated = False # Do not apply isolated star selection 

375 self.fallbackSourceSelector.doRequirePrimary = False # Do not apply primary flag selection 

376 self.fallbackSourceSelector.doUnresolved = doUnresolved 

377 self.fallbackSourceSelector.doSkySources = doSkySources 

378 self.fallbackSourceSelector.doSignalToNoise = doSignalToNoise 

379 self.fallbackSourceSelector.signalToNoise.minimum = signalToNoiseMinimum 

380 self.fallbackSourceSelector.signalToNoise.maximum = signalToNoiseMaximum 

381 

382 def validate(self): 

383 super().validate() 

384 if self.doSubtractBackground and self.image_type == "future": 384 ↛ 385line 384 didn't jump to line 385 because the condition on line 384 was never true

385 raise lsst.pex.config.FieldValidationError( 

386 AlardLuptonSubtractBaseConfig.doSubtractBackground, self, 

387 "The background subtracted when solving the kernel is not recorded on" 

388 " image_type='future' outputs; subtract the background in detectAndMeasure instead." 

389 ) 

390 

391 

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

393 pipelineConnections=AlardLuptonSubtractConnections): 

394 mode = lsst.pex.config.ChoiceField( 

395 dtype=str, 

396 default="convolveTemplate", 

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

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

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

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

401 ) 

402 

403 

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

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

406 the Alard & Lupton (1998) algorithm. 

407 """ 

408 ConfigClass = AlardLuptonSubtractConfig 

409 _DefaultName = "alardLuptonSubtract" 

410 usePreconvolution = False 

411 """Whether this task preconvolves the science image with its own PSF 

412 before kernel-matching. Subclasses that preconvolve override this to 

413 `True`.""" 

414 

415 futureImageOutputs = ("difference", "matchedTemplate") 

416 """Names of the images in the results struct that are converted in future 

417 mode (`tuple` [`str`]). Subclasses with different image outputs override 

418 this.""" 

419 

420 def __init__(self, **kwargs): 

421 super().__init__(**kwargs) 

422 self.makeSubtask("decorrelate") 

423 self.makeSubtask("makeKernel") 

424 self.makeSubtask("sourceSelector") 

425 self.makeSubtask("fallbackSourceSelector") 

426 if self.config.doScaleVariance: 

427 self.makeSubtask("scaleVariance") 

428 

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

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

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

432 self.convolutionControl.setDoNormalize(False) 

433 self.convolutionControl.setDoCopyEdge(True) 

434 

435 def _applyExternalCalibrations(self, exposure, visitSummary): 

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

437 external ones.". 

438 

439 Parameters 

440 ---------- 

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

442 Input exposure to adjust calibrations. 

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

444 Exposure catalog with external calibrations to be applied. Catalog 

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

446 lookup. 

447 

448 Returns 

449 ------- 

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

451 Exposure with adjusted calibrations. 

452 """ 

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

454 

455 row = visitSummary.find(detectorId) 

456 if row is None: 

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

458 "Using original calibrations.", detectorId) 

459 else: 

460 psf = row.getPsf() 

461 apCorrMap = row.getApCorrMap() 

462 if psf is None: 

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

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

465 detectorId) 

466 elif apCorrMap is None: 

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

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

469 detectorId) 

470 else: 

471 exposure.setPsf(psf) 

472 exposure.info.setApCorrMap(apCorrMap) 

473 

474 return exposure 

475 

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

477 inputs = butlerQC.get(inputRefs) 

478 templateInfo = None 

479 exposureRecord = None 

480 photometricScaling = None 

481 if self.config.image_type == "future": 

482 template = inputs["template"] 

483 dataId = butlerQC.quantum.dataId 

484 # Read the `TemplateInfo` and the observation metadata from the 

485 # template while it is still in the `DifferenceImage` format. 

486 templateInfo = get_difference_image_provenance(template, "templates", "template", dataId) 

487 exposureRecord = record_from_obs_info(template.obs_info, dataId["instrument"], 

488 dataId["visit"], dataId.universe) 

489 inputs["template"] = template.to_legacy() 

490 photometricScaling = inputs["science"].photometric_scaling 

491 inputs["science"] = inputs["science"].to_legacy() 

492 if "inputPsfMatchingKernel" in inputs: 

493 inputs["inputPsfMatchingKernel"] = inputs["inputPsfMatchingKernel"].to_legacy() 

494 

495 try: 

496 results = self.run(**inputs) 

497 except lsst.pipe.base.AlgorithmError as e: 

498 error = lsst.pipe.base.AnnotatedPartialOutputsError.annotate(e, self, log=self.log) 

499 # No partial outputs for butler to put, so nothing to convert. 

500 raise error from e 

501 

502 if self.config.image_type == "future": 

503 self.convert_outputs_to_future(results, exposureRecord, templateInfo=templateInfo, 

504 photometricScaling=photometricScaling) 

505 

506 butlerQC.put(results, outputRefs) 

507 

508 def convert_outputs_to_future(self, results, exposureRecord, templateInfo=None, 

509 photometricScaling=None): 

510 """Convert the image outputs to `lsst.images` types. 

511 

512 Each image named in `futureImageOutputs` that is present on 

513 ``results`` is replaced by an `lsst.images.DifferenceImage`, with the 

514 PSF matching kernel attached to it. ``psfMatchingKernel`` is replaced 

515 by the same kernel as an 

516 `lsst.images.convolution_kernels.ImageBasisConvolutionKernel`. 

517 

518 Parameters 

519 ---------- 

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

521 Output struct to read and modify in place. 

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

523 The ``exposure`` record of the observation, which supplies the 

524 observation metadata recorded on each converted output. 

525 templateInfo : `list` [`lsst.images.DifferenceImageTemplateInfo`], \ 

526 optional 

527 Record of the coadds that went into the template, taken from the 

528 template this task subtracted. 

529 photometricScaling : `lsst.images.fields.BaseField`, optional 

530 Photometric scaling of the science image. 

531 

532 Raises 

533 ------ 

534 TypeError 

535 Raised if the PSF matching kernel cannot be stored on an 

536 `lsst.images.DifferenceImage`. 

537 RuntimeError 

538 Raised if an output has pixels set in a mask plane that 

539 `lsst.images.get_legacy_difference_image_mask_planes` does not 

540 map. 

541 

542 Notes 

543 ----- 

544 This uses the default legacy mask plane map of 

545 `lsst.images.get_legacy_difference_image_mask_planes` and adds any 

546 planes from `~lsst.images.get_legacy_optional_mask_planes` that are set 

547 for any pixels in the image. 

548 """ 

549 # The science image and every output built from it share the science 

550 # pixel grid, so its detector applies to all of them. 

551 science = results.matchedScience 

552 try: 

553 kernel = ImageBasisConvolutionKernel.from_legacy(results.psfMatchingKernel) 

554 except (TypeError, ValueError, AttributeError) as e: 

555 raise TypeError("The supplied PSF matching kernel cannot be attached to an" 

556 f" lsst.images.DifferenceImage: {e}") from e 

557 for name in self.futureImageOutputs: 

558 exposure = getattr(results, name, None) 

559 if exposure is None: 

560 continue 

561 if exposure.getDetector() is None: 

562 # Fall back on the science detector for images without a 

563 # detector of their own (e.g. matchedTemplate) 

564 exposure.setDetector(science.getDetector()) 

565 image = DifferenceImage.from_legacy( 

566 exposure, 

567 unit=u.nJy, 

568 exposure_record=exposureRecord, 

569 ) 

570 if kernel is not None: 570 ↛ 572line 570 didn't jump to line 572 because the condition on line 570 was always true

571 image.kernel = kernel 

572 if templateInfo: 

573 image.templates = templateInfo 

574 if photometricScaling is not None: 

575 image.photometric_scaling = photometricScaling 

576 setattr(results, name, image) 

577 results.psfMatchingKernel = kernel 

578 

579 @timeMethod 

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

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

582 

583 Parameters 

584 ---------- 

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

586 Template exposure, warped to match the science exposure. 

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

588 Science exposure to subtract from the template. 

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

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

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

592 images around them. 

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

594 Exposure catalog with external calibrations to be applied. Catalog 

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

596 lookup. 

597 

598 Returns 

599 ------- 

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

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

602 Result of subtracting template and science. 

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

604 Warped and PSF-matched template exposure. 

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

606 Background model that was fit while solving for the 

607 PSF-matching kernel 

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

609 Kernel used to PSF-match the convolved image. 

610 ``kernelSources` : `lsst.afw.table.SourceCatalog` 

611 Sources from the input catalog that were used to construct the 

612 PSF-matching kernel. 

613 """ 

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

615 

616 convolveTemplate = self.chooseConvolutionMethod(template, science) 

617 self.matchedPsfSize = self.sciencePsfSize if convolveTemplate else self.templatePsfSize 

618 

619 kernelResult = self.runMakeKernel(template, science, sources=sources, 

620 convolveTemplate=convolveTemplate, 

621 runSourceDetection=False) 

622 

623 if self.config.doSubtractBackground: 

624 backgroundModel = kernelResult.backgroundModel 

625 else: 

626 backgroundModel = None 

627 if convolveTemplate: 

628 subtractResults = self.runConvolveTemplate(template, science, kernelResult.psfMatchingKernel, 

629 backgroundModel=backgroundModel) 

630 else: 

631 subtractResults = self.runConvolveScience(template, science, kernelResult.psfMatchingKernel, 

632 backgroundModel=backgroundModel) 

633 subtractResults.kernelSources = kernelResult.kernelSources 

634 

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

636 

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

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

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

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

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

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

643 self.metadata["differenceFootprintRatioMean"], 

644 self.metadata["differenceFootprintRatioStdev"]) 

645 

646 return subtractResults 

647 

648 def chooseConvolutionMethod(self, template, science): 

649 """Determine whether the template should be convolved with the PSF 

650 matching kernel. 

651 

652 Parameters 

653 ---------- 

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

655 Template exposure, warped to match the science exposure. 

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

657 Science exposure to subtract from the template. 

658 

659 Returns 

660 ------- 

661 convolveTemplate : `bool` 

662 Convolve the template to match the two images? 

663 

664 Raises 

665 ------ 

666 RuntimeError 

667 If an unsupported convolution mode is supplied. 

668 """ 

669 if self.usePreconvolution: 669 ↛ 670line 669 didn't jump to line 670 because the condition on line 669 was never true

670 raise RuntimeError("Choosing a convolution method is incompatible with preconvolution!") 

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

672 convolveTemplate = _shapeTest(template, 

673 science, 

674 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer, 

675 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid) 

676 if convolveTemplate: 

677 if self.sciencePsfSize < self.templatePsfSize: 677 ↛ 678line 677 didn't jump to line 678 because the condition on line 677 was never true

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

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

680 else: 

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

682 else: 

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

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

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

686 convolveTemplate = True 

687 elif self.config.mode == "convolveScience": 687 ↛ 691line 687 didn't jump to line 691 because the condition on line 687 was always true

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

689 convolveTemplate = False 

690 else: 

691 raise RuntimeError(f"Cannot handle AlardLuptonSubtract mode: {self.config.mode}") 

692 return convolveTemplate 

693 

694 def runMakeKernel(self, template, science, sources=None, convolveTemplate=True, runSourceDetection=False): 

695 """Construct the PSF-matching kernel. Not used for preconvolution. 

696 

697 Parameters 

698 ---------- 

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

700 Template exposure, warped to match the science exposure. 

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

702 Science exposure to subtract from the template. 

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

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

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

706 images around them. 

707 Not used if ``runSourceDetection`` is set. 

708 convolveTemplate : `bool`, optional 

709 Construct the matching kernel to convolve the template? 

710 runSourceDetection : `bool`, optional 

711 Run a minimal version of source detection to determine kernel 

712 candidates? If False, a source list to select kernel candidates 

713 from must be supplied. 

714 

715 Returns 

716 ------- 

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

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

719 Background model that was fit while solving for the 

720 PSF-matching kernel 

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

722 Kernel used to PSF-match the convolved image. 

723 ``kernelSources` : `lsst.afw.table.SourceCatalog` 

724 Sources from the input catalog that were used to construct the 

725 PSF-matching kernel. 

726 """ 

727 if self.usePreconvolution: 727 ↛ 728line 727 didn't jump to line 728 because the condition on line 727 was never true

728 raise RuntimeError("Incorrect matching kernel calculation configured. " 

729 "`runMakeKernel` can't be called if `usePreconvolution` is set.") 

730 if convolveTemplate: 

731 reference = template 

732 target = science 

733 referenceFwhmPix = self.templatePsfSize 

734 targetFwhmPix = self.sciencePsfSize 

735 else: 

736 reference = science 

737 target = template 

738 referenceFwhmPix = self.sciencePsfSize 

739 targetFwhmPix = self.templatePsfSize 

740 try: 

741 if runSourceDetection: 

742 kernelSources = self.runKernelSourceDetection(template, science) 

743 else: 

744 kernelSources = self._sourceSelector(template, science, sources) 

745 kernelResult = self.makeKernel.run(reference, target, kernelSources, 

746 preconvolved=False, 

747 templateFwhmPix=referenceFwhmPix, 

748 scienceFwhmPix=targetFwhmPix) 

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

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

751 # Raise NoWorkFound if template fraction is insufficient 

752 checkTemplateIsSufficient( 

753 template[science.getBBox()], self.log, scienceExposure=science, 

754 requiredTemplateFraction=self.config.minTemplateFractionForExpectedSuccess, 

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

756 f" Failure is tolerable: {e}" 

757 ) 

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

759 raise e 

760 

761 return lsst.pipe.base.Struct(backgroundModel=kernelResult.backgroundModel, 

762 psfMatchingKernel=kernelResult.psfMatchingKernel, 

763 kernelSources=kernelSources) 

764 

765 def runKernelSourceDetection(self, template, science): 

766 """Run detection on the science image and use the template mask plane 

767 to reject candidate sources. 

768 

769 Parameters 

770 ---------- 

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

772 Template exposure, warped to match the science exposure. 

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

774 Science exposure to subtract from the template. 

775 

776 Returns 

777 ------- 

778 kernelSources : `lsst.afw.table.SourceCatalog` 

779 Sources from the input catalog to use to construct the 

780 PSF-matching kernel. 

781 """ 

782 kernelSize = self.makeKernel.makeKernelBasisList( 

783 self.templatePsfSize, self.matchedPsfSize)[0].getWidth() 

784 sources = self.makeKernel.makeCandidateList(template, science, kernelSize, 

785 candidateList=None, 

786 sigma=gaussian_fwhm_to_sigma*self.sciencePsfSize) 

787 return self._sourceSelector(template, science, sources, fallback=True) 

788 

789 def runConvolveTemplate(self, template, science, psfMatchingKernel, backgroundModel=None): 

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

791 from the science image. 

792 

793 Parameters 

794 ---------- 

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

796 Template exposure, warped to match the science exposure. 

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

798 Science exposure to subtract from the template. 

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

800 Kernel to be used to PSF-match the science image to the template. 

801 backgroundModel : `lsst.afw.math.Function2D`, optional 

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

803 kernel. 

804 

805 Returns 

806 ------- 

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

808 

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

810 Result of subtracting template and science. 

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

812 Warped and PSF-matched template exposure. 

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

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

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

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

817 """ 

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

819 

820 matchedTemplate = self._convolveExposure(template, psfMatchingKernel, 

821 self.convolutionControl, 

822 bbox=science.getBBox(), 

823 psf=science.psf, 

824 photoCalib=science.photoCalib) 

825 

826 difference = _subtractImages(science, matchedTemplate, backgroundModel=backgroundModel) 

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

828 psfMatchingKernel, 

829 templateMatched=True) 

830 

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

832 matchedTemplate=matchedTemplate, 

833 matchedScience=science, 

834 backgroundModel=backgroundModel, 

835 psfMatchingKernel=psfMatchingKernel) 

836 

837 def runConvolveScience(self, template, science, psfMatchingKernel, backgroundModel=None): 

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

839 the template image. 

840 

841 Parameters 

842 ---------- 

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

844 Template exposure, warped to match the science exposure. 

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

846 Science exposure to subtract from the template. 

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

848 Kernel to be used to PSF-match the science image to the template. 

849 backgroundModel : `lsst.afw.math.Function2D`, optional 

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

851 kernel. 

852 

853 Returns 

854 ------- 

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

856 

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

858 Result of subtracting template and science. 

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

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

861 is not PSF-matched to the science image. 

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

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

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

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

866 """ 

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

868 bbox = science.getBBox() 

869 

870 kernelImage = lsst.afw.image.ImageD(psfMatchingKernel.getDimensions()) 

871 xcen, ycen = bbox.getCenter() 

872 norm = psfMatchingKernel.computeImage(kernelImage, doNormalize=False, x=xcen, y=ycen) 

873 

874 matchedScience = self._convolveExposure(science, psfMatchingKernel, 

875 self.convolutionControl, 

876 psf=template.psf) 

877 

878 # Place back on native photometric scale 

879 matchedScience.maskedImage /= norm 

880 matchedTemplate = template.clone()[bbox] 

881 matchedTemplate.setPhotoCalib(science.photoCalib) 

882 

883 if backgroundModel is not None: 

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

885 invertedBackground = backgroundModel.clone() 

886 invertedBackground.setParameters([-p for p in backgroundModel.getParameters()]) 

887 backgroundModel = invertedBackground 

888 

889 difference = _subtractImages(matchedScience, matchedTemplate, backgroundModel=backgroundModel) 

890 

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

892 psfMatchingKernel, 

893 templateMatched=False) 

894 

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

896 matchedTemplate=matchedTemplate, 

897 matchedScience=matchedScience, 

898 backgroundModel=backgroundModel, 

899 psfMatchingKernel=psfMatchingKernel) 

900 

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

902 templateMatched=True, 

903 preConvMode=False, 

904 preConvKernel=None, 

905 spatiallyVarying=False): 

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

907 caused by convolution. 

908 

909 Parameters 

910 ---------- 

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

912 Template exposure, warped to match the science exposure. 

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

914 Science exposure to subtract from the template. 

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

916 Result of subtracting template and science. 

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

918 An (optionally spatially-varying) PSF matching kernel 

919 templateMatched : `bool`, optional 

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

921 preConvMode : `bool`, optional 

922 Was the science image preconvolved with its own PSF 

923 before PSF matching the template? 

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

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

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

927 spatiallyVarying : `bool`, optional 

928 Compute the decorrelation kernel spatially varying across the image? 

929 

930 Returns 

931 ------- 

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

933 The decorrelated image difference. 

934 """ 

935 if self.config.doDecorrelation: 

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

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

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

939 # during decorrelation 

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

941 templateMatched=templateMatched, 

942 preConvMode=preConvMode, 

943 preConvKernel=preConvKernel, 

944 spatiallyVarying=spatiallyVarying).correctedExposure 

945 else: 

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

947 correctedExposure = difference 

948 return correctedExposure 

949 

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

951 """Calculate the point-source limiting magnitude of an exposure. 

952 

953 The limit is the flux of a point source detected at ``nsigma`` in 

954 the median pixel noise, integrated over the effective area of the 

955 PSF, so it does not depend on the units of the pixels. 

956 

957 Parameters 

958 ---------- 

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

960 The exposure to calculate the limiting magnitude for. 

961 nsigma : `float`, optional 

962 The detection threshold in sigma. 

963 fallbackPsfSize : `float`, optional 

964 PSF FWHM in pixels to use if the exposure PSF cannot be 

965 evaluated. 

966 

967 Returns 

968 ------- 

969 maglim : `float` 

970 The limiting AB magnitude, or `numpy.nan` if the exposure has no 

971 photometric calibration, no usable pixels, or no PSF. 

972 """ 

973 if exposure.photoCalib is None: 973 ↛ 974line 973 didn't jump to line 974 because the condition on line 973 was never true

974 return np.nan 

975 try: 

976 psfArea = computePSFNoiseEquivalentArea(exposure.getPsf()) 

977 except (lsst.pex.exceptions.InvalidParameterError, 

978 afwDetection.InvalidPsfError, 

979 lsst.pex.exceptions.RangeError): 

980 if fallbackPsfSize is None: 

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

982 return np.nan 

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

984 # Effective area of a Gaussian PSF with this FWHM. 

985 psfArea = 4*np.pi*(fallbackPsfSize/np.sqrt(8*np.log(2)))**2 

986 mask = exposure.mask 

987 good = (mask.array & mask.getPlaneBitMask(self.config.badMaskPlanes)) == 0 

988 variance = exposure.variance.array[good] 

989 variance = variance[np.isfinite(variance) & (variance > 0)] 

990 if variance.size == 0: 

991 return np.nan 

992 fluxLim = nsigma*np.sqrt(np.median(variance)*psfArea) 

993 return exposure.photoCalib.instFluxToMagnitude(fluxLim) 

994 

995 @staticmethod 

996 def _validateExposures(template, science): 

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

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

999 

1000 Parameters 

1001 ---------- 

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

1003 Template exposure, warped to match the science exposure. 

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

1005 Science exposure to subtract from the template. 

1006 

1007 Raises 

1008 ------ 

1009 AssertionError 

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

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

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

1013 """ 

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

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

1016 templateBBox = template.getBBox() 

1017 scienceBBox = science.getBBox() 

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

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

1020 (science.filter, template.filter) 

1021 

1022 assert templateBBox.contains(scienceBBox), \ 

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

1024 

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

1026 bbox=None, 

1027 psf=None, 

1028 photoCalib=None, 

1029 interpolateBadMaskPlanes=False, 

1030 ): 

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

1032 

1033 Parameters 

1034 ---------- 

1035 exposure : `lsst.afw.Exposure` 

1036 exposure to convolve. 

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

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

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

1040 Configuration for convolve algorithm. 

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

1042 Bounding box to trim the convolved exposure to. 

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

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

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

1046 Photometric calibration of the convolved exposure. 

1047 interpolateBadMaskPlanes : `bool`, optional 

1048 If set, interpolate over mask planes specified in 

1049 ``config.badMaskPlanes`` before convolving the image. 

1050 

1051 Returns 

1052 ------- 

1053 convolvedExp : `lsst.afw.Exposure` 

1054 The convolved image. 

1055 """ 

1056 convolvedExposure = exposure.clone() 

1057 if psf is not None: 

1058 convolvedExposure.setPsf(psf) 

1059 if photoCalib is not None: 

1060 convolvedExposure.setPhotoCalib(photoCalib) 

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

1062 nInterp = _interpolateImage(convolvedExposure.maskedImage, 

1063 self.config.badMaskPlanes) 

1064 self.metadata["nInterpolated"] = nInterp 

1065 

1066 # Snapshot the footprints of mask planes that must not be dilated by 

1067 # the convolution. 

1068 preservePlanes = [mp for mp in self.config.preserveMaskPlanes 

1069 if mp in convolvedExposure.mask.getMaskPlaneDict()] 

1070 maskResetDict = { 

1071 mp: (convolvedExposure.mask.array 

1072 & convolvedExposure.mask.getPlaneBitMask(mp)) > 0 

1073 for mp in preservePlanes 

1074 } 

1075 

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

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

1078 convolvedExposure.setMaskedImage(convolvedImage) 

1079 

1080 # Undo the convolution's dilation of the preserved planes: clear the 

1081 # dilated bits, then restore each mask plane for the pixels that were 

1082 # previously set. 

1083 self._clearMask(convolvedExposure.mask, clearMaskPlanes=preservePlanes) 

1084 for maskPlane, maskSetPixels in maskResetDict.items(): 

1085 bit = convolvedExposure.mask.getPlaneBitMask(maskPlane) 

1086 convolvedExposure.mask.array[maskSetPixels] |= bit 

1087 

1088 if bbox is None: 

1089 return convolvedExposure 

1090 else: 

1091 return convolvedExposure[bbox] 

1092 

1093 def _sourceSelector(self, template, science, sources, fallback=False): 

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

1095 The selection criteria include any configured parameters of the 

1096 `sourceSelector` subtask, as well as checking the science and template 

1097 mask planes. 

1098 

1099 Parameters 

1100 ---------- 

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

1102 Template exposure, warped to match the science exposure. 

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

1104 Science exposure to subtract from the template. 

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

1106 Input source catalog to select sources from. 

1107 fallback : `bool`, optional 

1108 Switch indicating the source selector is being called after 

1109 running the fallback source detection subtask, which does not run a 

1110 full set of measurement plugins and can't use the same settings for 

1111 the source selector. 

1112 

1113 Returns 

1114 ------- 

1115 kernelSources : `lsst.afw.table.SourceCatalog` 

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

1117 sources removed and footprints added. 

1118 

1119 Raises 

1120 ------ 

1121 InsufficientKernelSourcesError 

1122 An AlgorithmError that is raised if there are not enough PSF 

1123 candidates to construct the PSF matching kernel. 

1124 """ 

1125 if fallback: 

1126 selected = self.fallbackSourceSelector.selectSources(sources).selected 

1127 else: 

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

1129 # It is OK to use just self.matchedPsfSize for the science PSF here, 

1130 # since we are just using it to calculate the size of the matching 

1131 # kernel. 

1132 kSize = self.makeKernel.makeKernelBasisList(self.templatePsfSize, self.matchedPsfSize)[0].getWidth() 

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

1134 # Set the footprints, to be used in `makeKernel` and `checkMask`. 

1135 kernelSources = setSourceFootprints(selectSources, kernelSize=kSize) 

1136 bbox = science.getBBox() 

1137 if self.usePreconvolution: 

1138 # Exclude a wider buffer around the edge of the image to 

1139 # account for an extra convolution. 

1140 bbox.grow(-kSize) 

1141 if self.config.restrictKernelEdgeSources: 

1142 bbox.grow(-kSize) 

1143 # Remove sources that land on masked pixels 

1144 scienceSelected = checkMask(science.mask[bbox], kernelSources, self.config.excludeMaskPlanes) 

1145 templateSelected = checkMask(template.mask[bbox], kernelSources, self.config.excludeMaskPlanes) 

1146 maskSelected = scienceSelected & templateSelected 

1147 kernelSources = kernelSources[maskSelected].copy(deep=True) 

1148 # Trim kernelSources if they exceed ``maxKernelSources``. 

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

1150 if (len(kernelSources) > self.config.maxKernelSources) & (self.config.maxKernelSources > 0): 

1151 signalToNoise = kernelSources.getPsfInstFlux()/kernelSources.getPsfInstFluxErr() 

1152 indices = np.argsort(signalToNoise) 

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

1154 selected = np.zeros(len(kernelSources), dtype=bool) 

1155 selected[indices] = True 

1156 kernelSources = kernelSources[selected].copy(deep=True) 

1157 

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

1159 len(kernelSources), len(sources), 100*len(kernelSources)/len(sources)) 

1160 if len(kernelSources) < self.config.minKernelSources: 

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

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

1163 len(kernelSources), self.config.minKernelSources) 

1164 if self.config.allowKernelSourceDetection and not fallback: 1164 ↛ 1168line 1164 didn't jump to line 1168 because the condition on line 1164 was never true

1165 # The fallback source detection pipeline calls this method, so 

1166 # allowing source detection in that case would create an endless 

1167 # loop 

1168 kernelSources = self.runKernelSourceDetection(template, science) 

1169 else: 

1170 raise InsufficientKernelSourcesError(nSources=len(kernelSources), 

1171 nRequired=self.config.minKernelSources) 

1172 

1173 self.metadata["nPsfSources"] = len(kernelSources) 

1174 

1175 return kernelSources 

1176 

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

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

1179 

1180 Parameters 

1181 ---------- 

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

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

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

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

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

1187 of the science image is modified in place. 

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

1189 Exposure catalog with external calibrations to be applied. Catalog 

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

1191 lookup. 

1192 """ 

1193 self._validateExposures(template, science) 

1194 if visitSummary is not None: 1194 ↛ 1195line 1194 didn't jump to line 1195 because the condition on line 1194 was never true

1195 self._applyExternalCalibrations(science, visitSummary=visitSummary) 

1196 templateCoverageFraction = checkTemplateIsSufficient( 

1197 template[science.getBBox()], self.log, scienceExposure=science, 

1198 requiredTemplateFraction=self.config.requiredTemplateFraction, 

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

1200 " set config requiredTemplateFraction=0" 

1201 ) 

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

1203 

1204 if self.config.doScaleVariance: 

1205 # Scale the variance of the science image before 

1206 # convolution, subtraction, or decorrelation so that it has the 

1207 # correct ratio. Note that the template variance is scaled 

1208 # independently in ``GetTemplateTask``. 

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

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

1211 self.metadata["scaleScienceVarianceFactor"] = sciVarFactor 

1212 

1213 # Erase existing detection mask planes. 

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

1215 self.updateMasks(template, science) 

1216 

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

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

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

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

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

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

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

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

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

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

1227 # up near a region with no data. 

1228 try: 

1229 self.templatePsfSize = getPsfFwhm(template.psf) 

1230 self.sciencePsfSize = getPsfFwhm(science.psf) 

1231 except lsst.pex.exceptions.Exception: 

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

1233 # Catching: 

1234 # - lsst::geom::SingularTransformException 

1235 # - lsst.pex.exceptions.InvalidParameterError 

1236 # - lsst.pex.exceptions.RangeError 

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

1238 "Evaluting PSF on a grid of points." 

1239 ) 

1240 self.templatePsfSize = evaluateMeanPsfFwhm( 

1241 template, 

1242 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer, 

1243 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid 

1244 ) 

1245 self.sciencePsfSize = evaluateMeanPsfFwhm( 

1246 science, 

1247 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer, 

1248 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid 

1249 ) 

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

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

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

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

1254 

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

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

1257 if np.isnan(maglim_science): 1257 ↛ 1258line 1257 didn't jump to line 1258 because the condition on line 1257 was never true

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

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

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

1261 if np.isnan(maglim_template): 1261 ↛ 1262line 1261 didn't jump to line 1262 because the condition on line 1261 was never true

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

1263 maglim_diffim = maglim_science 

1264 else: 

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

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

1267 self.metadata["scienceLimitingMagnitude"] = maglim_science 

1268 self.metadata["templateLimitingMagnitude"] = maglim_template 

1269 self.metadata["diffimLimitingMagnitude"] = maglim_diffim 

1270 

1271 def updateMasks(self, template, science): 

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

1273 

1274 Parameters 

1275 ---------- 

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

1277 Template exposure, warped to match the science exposure. 

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

1279 in the task config. 

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

1281 Science exposure to subtract from the template. 

1282 The DETECTED and DETECTED_NEGATIVE mask planes of the science image 

1283 will be erased. 

1284 """ 

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

1286 

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

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

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

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

1291 # be cleared. 

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

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

1294 # afw's mask planes are global, so if the "*_TEMPLATE" mask planes were 

1295 # defined anywhere previously they would now also be cleared unless we 

1296 # exclude them. 

1297 renamedMaskPlanes = {maskPlane + "_TEMPLATE" for maskPlane in renameMaskPlanes} 

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

1299 if mp not in self.config.preserveTemplateMask 

1300 and mp not in renamedMaskPlanes] 

1301 

1302 # propagate the mask plane related to Fake source injection 

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

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

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

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

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

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

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

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

1311 if "INJECTED" in renameMaskPlanes: 1311 ↛ 1313line 1311 didn't jump to line 1313 because the condition on line 1311 was always true

1312 renameMaskPlanes.remove("INJECTED") 

1313 if "INJECTED_TEMPLATE" in clearMaskPlanes: 1313 ↛ 1314line 1313 didn't jump to line 1314 because the condition on line 1313 was never true

1314 clearMaskPlanes.remove("INJECTED_TEMPLATE") 

1315 

1316 for maskPlane in renameMaskPlanes: 

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

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

1319 

1320 @staticmethod 

1321 def _renameMaskPlanes(mask, maskPlane, newMaskPlane): 

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

1323 

1324 Parameters 

1325 ---------- 

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

1327 The mask image to update in place. 

1328 maskPlane : `str` 

1329 The name of the existing mask plane to copy. 

1330 newMaskPlane : `str` 

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

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

1333 """ 

1334 mask.addMaskPlane(newMaskPlane) 

1335 originBitMask = mask.getPlaneBitMask(maskPlane) 

1336 destinationBitMask = mask.getPlaneBitMask(newMaskPlane) 

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

1338 

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

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

1341 

1342 Parameters 

1343 ---------- 

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

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

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

1347 Erase the specified mask planes. 

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

1349 """ 

1350 if clearMaskPlanes is None: 1350 ↛ 1351line 1350 didn't jump to line 1351 because the condition on line 1350 was never true

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

1352 

1353 bitMaskToClear = mask.getPlaneBitMask(clearMaskPlanes) 

1354 mask &= ~bitMaskToClear 

1355 

1356 

1357class AlardLuptonPreconvolveSubtractConnections(SubtractInputConnections, 

1358 SubtractScoreOutputConnections): 

1359 pass 

1360 

1361 

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

1363 pipelineConnections=AlardLuptonPreconvolveSubtractConnections): 

1364 pass 

1365 

1366 

1367class AlardLuptonPreconvolveSubtractTask(AlardLuptonSubtractTask): 

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

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

1370 subtraction. 

1371 """ 

1372 ConfigClass = AlardLuptonPreconvolveSubtractConfig 

1373 _DefaultName = "alardLuptonPreconvolveSubtract" 

1374 usePreconvolution = True 

1375 # This task just writes the score image instead of the difference image and 

1376 # matchedTemplate 

1377 futureImageOutputs = ("scoreExposure",) 

1378 

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

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

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

1382 from the preconvolved science image. 

1383 

1384 Parameters 

1385 ---------- 

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

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

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

1389 the science bbox. 

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

1391 The science exposure. 

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

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

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

1395 images around them. 

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

1397 Exposure catalog with complete external calibrations. Catalog uses 

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

1399 

1400 Returns 

1401 ------- 

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

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

1404 Result of subtracting the convolved template and science 

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

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

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

1408 of the original science image. 

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

1410 The science exposure after convolving with its own PSF. 

1411 Attached PSF is that of the original science image. 

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

1413 Background model that was fit while solving for the 

1414 PSF-matching kernel 

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

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

1417 image. 

1418 """ 

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

1420 

1421 convolutionKernel = self._makePreconvolutionKernel(science.psf) 

1422 matchedScience = self._convolveExposure(science, convolutionKernel, self.convolutionControl, 

1423 interpolateBadMaskPlanes=True) 

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

1425 

1426 self.matchedPsfSize = self.sciencePsfSize*np.sqrt(2) 

1427 self.log.info("Preconvolved science PSF FWHM: %f pixels", self.matchedPsfSize) 

1428 self.metadata["preconvolvedSciencePsfSize"] = self.matchedPsfSize 

1429 try: 

1430 kernelSources = self._sourceSelector(template, matchedScience, sources) 

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

1432 kernelSources, convolutionKernel) 

1433 

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

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

1436 # Raise NoWorkFound if template fraction is insufficient 

1437 checkTemplateIsSufficient( 

1438 template[science.getBBox()], self.log, scienceExposure=science, 

1439 requiredTemplateFraction=self.config.minTemplateFractionForExpectedSuccess, 

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

1441 f" Failure is tolerable: {e}" 

1442 ) 

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

1444 raise e 

1445 

1446 return subtractResults 

1447 

1448 @staticmethod 

1449 def _flagScoreEdge(mask, innerBBox): 

1450 """Set the EDGE mask bit on pixels outside a known-valid region. 

1451 

1452 Parameters 

1453 ---------- 

1454 mask : `~lsst.afw.image.Mask` 

1455 Exposure mask that will be modified in place. Must have 

1456 an ``EDGE`` mask plane. 

1457 innerBBox : `~lsst.geom.Box2I` 

1458 The valid inner region. Pixels 

1459 outside this bbox will have their ``EDGE`` bit set. 

1460 """ 

1461 bbox = mask.getBBox() 

1462 edgeBit = mask.getPlaneBitMask("EDGE") 

1463 dx0 = innerBBox.getMinX() - bbox.getMinX() 

1464 dx1 = bbox.getMaxX() - innerBBox.getMaxX() 

1465 dy0 = innerBBox.getMinY() - bbox.getMinY() 

1466 dy1 = bbox.getMaxY() - innerBBox.getMaxY() 

1467 if dy0 > 0: 1467 ↛ 1469line 1467 didn't jump to line 1469 because the condition on line 1467 was always true

1468 mask.array[:dy0, :] |= edgeBit 

1469 if dy1 > 0: 1469 ↛ 1471line 1469 didn't jump to line 1471 because the condition on line 1469 was always true

1470 mask.array[-dy1:, :] |= edgeBit 

1471 if dx0 > 0: 1471 ↛ 1473line 1471 didn't jump to line 1473 because the condition on line 1471 was always true

1472 mask.array[:, :dx0] |= edgeBit 

1473 if dx1 > 0: 1473 ↛ exitline 1473 didn't return from function '_flagScoreEdge' because the condition on line 1473 was always true

1474 mask.array[:, -dx1:] |= edgeBit 

1475 

1476 @staticmethod 

1477 def _makePreconvolutionKernel(psf): 

1478 """Build a normalized, reflected matched-filter kernel from a PSF. 

1479 

1480 Convolving an image with this kernel is equivalent to correlating 

1481 the image with the PSF, so peaks in the output align with the PSF's 

1482 centroid — even for asymmetric PSFs. The kernel is evaluated at the 

1483 PSF's average position and returned as a constant 

1484 `~lsst.afw.math.Kernel`. 

1485 

1486 Parameters 

1487 ---------- 

1488 psf : `~lsst.afw.detection.Psf` 

1489 The PSF to derive the preconvolution kernel from. 

1490 

1491 Returns 

1492 ------- 

1493 kernel : `~lsst.afw.math.Kernel` 

1494 The PSF reflected about both axes, normalized to sum to one. 

1495 

1496 Raises 

1497 ------ 

1498 ValueError 

1499 Raised if the PSF kernel has an even size along either axis. 

1500 It's not possible to center an even-sized kernel. 

1501 """ 

1502 avgPos = psf.getAveragePosition() 

1503 localKernel = psf.getLocalKernel(avgPos) 

1504 dims = localKernel.getDimensions() 

1505 if dims.x % 2 == 0 or dims.y % 2 == 0: 1505 ↛ 1506line 1505 didn't jump to line 1506 because the condition on line 1505 was never true

1506 raise ValueError( 

1507 f"Preconvolution requires an odd-sized PSF kernel, got {dims.x}x{dims.y}. " 

1508 ) 

1509 kimg = lsst.afw.image.ImageD(dims) 

1510 localKernel.computeImage(kimg, doNormalize=True) # normalize to unit sum 

1511 # Reflect about the kernel center. PSF kernels are odd-sized, 

1512 # so ``[::-1, ::-1]`` places the peak at the same pixel. 

1513 kimg.array[...] = kimg.array[::-1, ::-1] 

1514 return lsst.afw.math.FixedKernel(kimg) 

1515 

1516 def runPreconvolve(self, template, science, matchedScience, kernelSources, preConvKernel): 

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

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

1519 exposure. 

1520 

1521 Parameters 

1522 ---------- 

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

1524 Template exposure, warped to match the science exposure. 

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

1526 Science exposure to subtract from the template. 

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

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

1529 kernelSources : `lsst.afw.table.SourceCatalog` 

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

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

1532 images around them. 

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

1534 The kernel that was used to preconvolve the ``science`` 

1535 exposure. Must be normalized to sum to 1. 

1536 

1537 Returns 

1538 ------- 

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

1540 

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

1542 Result of subtracting the convolved template and science 

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

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

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

1546 of the original science image. 

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

1548 The science exposure after convolving with its own PSF. 

1549 Attached PSF is that of the original science image. 

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

1551 Background model that was fit while solving for the 

1552 PSF-matching kernel 

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

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

1555 image. 

1556 """ 

1557 bbox = science.getBBox() 

1558 innerBBox = preConvKernel.shrinkBBox(bbox) 

1559 

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

1561 preconvolved=True, 

1562 templateFwhmPix=self.templatePsfSize, 

1563 scienceFwhmPix=self.matchedPsfSize) 

1564 

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

1566 self.convolutionControl, 

1567 bbox=bbox, 

1568 psf=science.psf, 

1569 interpolateBadMaskPlanes=True, 

1570 photoCalib=science.photoCalib) 

1571 score = _subtractImages(matchedScience, matchedTemplate, 

1572 backgroundModel=(kernelResult.backgroundModel 

1573 if self.config.doSubtractBackground else None)) 

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

1575 kernelResult.psfMatchingKernel, 

1576 templateMatched=True, preConvMode=True, 

1577 preConvKernel=preConvKernel) 

1578 

1579 # Flag the outer ``preConvKernel/2``-wide border as EDGE. 

1580 self._flagScoreEdge(correctedScore.mask, innerBBox) 

1581 

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

1583 matchedTemplate=matchedTemplate, 

1584 matchedScience=matchedScience, 

1585 backgroundModel=kernelResult.backgroundModel, 

1586 psfMatchingKernel=kernelResult.psfMatchingKernel, 

1587 kernelSources=kernelSources) 

1588 

1589 

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

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

1592 

1593 Parameters 

1594 ---------- 

1595 science : `lsst.afw.Exposure` 

1596 The input science image. 

1597 template : `lsst.afw.Exposure` 

1598 The template to subtract from the science image. 

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

1600 Differential background model 

1601 

1602 Returns 

1603 ------- 

1604 difference : `lsst.afw.Exposure` 

1605 The subtracted image. 

1606 """ 

1607 difference = science.clone() 

1608 if backgroundModel is not None: 

1609 difference.maskedImage -= backgroundModel 

1610 difference.maskedImage -= template.maskedImage 

1611 return difference 

1612 

1613 

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

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

1616 

1617 Parameters 

1618 ---------- 

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

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

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

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

1623 fwhmExposureBuffer : `float` 

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

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

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

1627 fwhmExposureGrid : `int` 

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

1629 available at its average position. 

1630 Returns 

1631 ------- 

1632 result : `bool` 

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

1634 either dimension. 

1635 """ 

1636 try: 

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

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

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

1640 shape1 = evaluateMeanPsfFwhm(exp1, 

1641 fwhmExposureBuffer=fwhmExposureBuffer, 

1642 fwhmExposureGrid=fwhmExposureGrid 

1643 ) 

1644 shape2 = evaluateMeanPsfFwhm(exp2, 

1645 fwhmExposureBuffer=fwhmExposureBuffer, 

1646 fwhmExposureGrid=fwhmExposureGrid 

1647 ) 

1648 return shape1 <= shape2 

1649 

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

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

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

1653 return xTest | yTest 

1654 

1655 

1656class SimplifiedSubtractConfig(AlardLuptonSubtractBaseConfig, lsst.pipe.base.PipelineTaskConfig, 

1657 pipelineConnections=SimplifiedSubtractConnections): 

1658 mode = lsst.pex.config.ChoiceField( 

1659 dtype=str, 

1660 default="convolveTemplate", 

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

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

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

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

1665 ) 

1666 useExistingKernel = lsst.pex.config.Field( 

1667 dtype=bool, 

1668 default=True, 

1669 doc="Use a pre-existing PSF matching kernel?" 

1670 "If False, source detection and measurement will be run." 

1671 ) 

1672 

1673 

1674class SimplifiedSubtractTask(AlardLuptonSubtractTask): 

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

1676 the Alard & Lupton (1998) algorithm. 

1677 """ 

1678 ConfigClass = SimplifiedSubtractConfig 

1679 _DefaultName = "simplifiedSubtract" 

1680 

1681 @timeMethod 

1682 def run(self, template, science, visitSummary=None, inputPsfMatchingKernel=None): 

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

1684 

1685 Parameters 

1686 ---------- 

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

1688 Template exposure, warped to match the science exposure. 

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

1690 Science exposure to subtract from the template. 

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

1692 Exposure catalog with external calibrations to be applied. Catalog 

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

1694 lookup. 

1695 inputPsfMatchingKernel : `lsst.afw.math.Kernel`, optional 

1696 Pre-existing PSF matching kernel to use for convolution. 

1697 Required, and only used, if ``config.useExistingKernel`` is set. 

1698 

1699 Returns 

1700 ------- 

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

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

1703 Result of subtracting template and science. 

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

1705 Warped and PSF-matched template exposure. 

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

1707 Background model that was fit while solving for the 

1708 PSF-matching kernel 

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

1710 Kernel used to PSF-match the convolved image. 

1711 ``kernelSources` : `lsst.afw.table.SourceCatalog` 

1712 Sources detected on the science image that were used to 

1713 construct the PSF-matching kernel. 

1714 

1715 Raises 

1716 ------ 

1717 lsst.pipe.base.NoWorkFound 

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

1719 set, is less then the configured requiredTemplateFraction 

1720 """ 

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

1722 

1723 convolveTemplate = self.chooseConvolutionMethod(template, science) 

1724 self.matchedPsfSize = self.sciencePsfSize if convolveTemplate else self.templatePsfSize 

1725 

1726 if self.config.useExistingKernel: 

1727 psfMatchingKernel = inputPsfMatchingKernel 

1728 backgroundModel = None 

1729 kernelSources = None 

1730 else: 

1731 kernelResult = self.runMakeKernel(template, science, convolveTemplate=convolveTemplate, 

1732 runSourceDetection=True) 

1733 psfMatchingKernel = kernelResult.psfMatchingKernel 

1734 kernelSources = kernelResult.kernelSources 

1735 if self.config.doSubtractBackground: 1735 ↛ 1736line 1735 didn't jump to line 1736 because the condition on line 1735 was never true

1736 backgroundModel = kernelResult.backgroundModel 

1737 else: 

1738 backgroundModel = None 

1739 if convolveTemplate: 1739 ↛ 1743line 1739 didn't jump to line 1743 because the condition on line 1739 was always true

1740 subtractResults = self.runConvolveTemplate(template, science, psfMatchingKernel, 

1741 backgroundModel=backgroundModel) 

1742 else: 

1743 subtractResults = self.runConvolveScience(template, science, psfMatchingKernel, 

1744 backgroundModel=backgroundModel) 

1745 if kernelSources is not None: 

1746 subtractResults.kernelSources = kernelSources 

1747 return subtractResults 

1748 

1749 

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

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

1752 

1753 Parameters 

1754 ---------- 

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

1756 Image on which to perform interpolation. 

1757 badMaskPlanes : `list` of `str` 

1758 List of mask planes to interpolate over. 

1759 fallbackValue : `float`, optional 

1760 Value to set when interpolation fails. 

1761 

1762 Returns 

1763 ------- 

1764 result: `float` 

1765 The number of masked pixels that were replaced. 

1766 """ 

1767 imgBadMaskPlanes = [ 

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

1769 ] 

1770 

1771 image = maskedImage.image.array 

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

1773 image[badPixels] = np.nan 

1774 if fallbackValue is None: 1774 ↛ 1778line 1774 didn't jump to line 1778 because the condition on line 1774 was always true

1775 fallbackValue = np.nanmedian(image) 

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

1777 # the median value. 

1778 image[badPixels] = fallbackValue 

1779 return np.sum(badPixels)