22from astropy
import units
as u
30from lsst.meas.algorithms
import ScaleVarianceTask, ScienceSourceSelectorTask
35from .
import MakeKernelTask, DecorrelateALKernelTask
36from lsst.utils.timer
import timeMethod
38__all__ = [
"AlardLuptonSubtractConfig",
"AlardLuptonSubtractTask",
39 "AlardLuptonPreconvolveSubtractConfig",
"AlardLuptonPreconvolveSubtractTask"]
41_dimensions = (
"instrument",
"visit",
"detector")
42_defaultTemplates = {
"coaddName":
"deep",
"fakesType":
""}
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"
54 science = connectionTypes.Input(
55 doc=
"Input science exposure to subtract from.",
56 dimensions=(
"instrument",
"visit",
"detector"),
57 storageClass=
"ExposureF",
58 name=
"{fakesType}calexp"
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",
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",
78 if not config.doApplyExternalCalibrations:
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",
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",
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",
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"
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",
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",
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"
139 makeKernel = lsst.pex.config.ConfigurableField(
140 target=MakeKernelTask,
141 doc=
"Task to construct a matching kernel for convolution.",
143 doDecorrelation = lsst.pex.config.Field(
146 doc=
"Perform diffim decorrelation to undo pixel correlation due to A&L "
147 "kernel convolution? If True, also update the diffim PSF."
149 decorrelate = lsst.pex.config.ConfigurableField(
150 target=DecorrelateALKernelTask,
151 doc=
"Task to decorrelate the image difference.",
153 requiredTemplateFraction = lsst.pex.config.Field(
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."
159 minTemplateFractionForExpectedSuccess = lsst.pex.config.Field(
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."
166 doScaleVariance = lsst.pex.config.Field(
169 doc=
"Scale variance of the image difference?"
171 scaleVariance = lsst.pex.config.ConfigurableField(
172 target=ScaleVarianceTask,
173 doc=
"Subtask to rescale the variance of the template to the statistically expected level."
175 doSubtractBackground = lsst.pex.config.Field(
176 doc=
"Subtract the background fit when solving the kernel?",
180 doApplyExternalCalibrations = lsst.pex.config.Field(
182 "Replace science Exposure's calibration objects with those"
183 " in visitSummary. Ignored if `doApplyFinalizedPsf is True."
188 sourceSelector = lsst.pex.config.ConfigurableField(
189 target=ScienceSourceSelectorTask,
190 doc=
"Task to select sources to be used for PSF matching.",
192 detectionThreshold = lsst.pex.config.Field(
195 doc=
"Minimum signal to noise ratio of detected sources "
196 "to use for calculating the PSF matching kernel."
198 detectionThresholdMax = lsst.pex.config.Field(
201 doc=
"Maximum signal to noise ratio of detected sources "
202 "to use for calculating the PSF matching kernel."
204 maxKernelSources = lsst.pex.config.Field(
207 doc=
"Maximum number of sources to use for calculating the PSF matching kernel."
208 "Set to -1 to disable."
210 minKernelSources = lsst.pex.config.Field(
213 doc=
"Minimum number of sources needed for calculating the PSF matching kernel."
215 excludeMaskPlanes = lsst.pex.config.ListField(
217 default=(
"NO_DATA",
"BAD",
"SAT",
"EDGE",
"FAKE"),
218 doc=
"Mask planes to exclude when selecting sources for PSF matching."
220 badMaskPlanes = lsst.pex.config.ListField(
222 default=(
"NO_DATA",
"BAD",
"SAT",
"EDGE"),
223 doc=
"Mask planes to interpolate over."
225 preserveTemplateMask = lsst.pex.config.ListField(
227 default=(
"NO_DATA",
"BAD",),
228 doc=
"Mask planes from the template to propagate to the image difference."
230 renameTemplateMask = lsst.pex.config.ListField(
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."
236 allowKernelSourceDetection = lsst.pex.config.Field(
239 doc=
"Re-run source detection for kernel candidates if an error is"
240 " encountered while calculating the matching kernel."
247 self.
makeKernel.kernel.active.fitForBackground =
True
248 self.
makeKernel.kernel.active.spatialKernelOrder = 1
249 self.
makeKernel.kernel.active.spatialBgOrder = 2
260 pipelineConnections=AlardLuptonSubtractConnections):
261 mode = lsst.pex.config.ChoiceField(
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."
272 """Compute the image difference of a science and template image using
273 the Alard & Lupton (1998) algorithm.
275 ConfigClass = AlardLuptonSubtractConfig
276 _DefaultName =
"alardLuptonSubtract"
280 self.makeSubtask(
"decorrelate")
281 self.makeSubtask(
"makeKernel")
282 self.makeSubtask(
"sourceSelector")
283 if self.config.doScaleVariance:
284 self.makeSubtask(
"scaleVariance")
293 """Replace calibrations (psf, and ApCorrMap) on this exposure with
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
307 exposure : `lsst.afw.image.exposure.Exposure`
308 Exposure with adjusted calibrations.
310 detectorId = exposure.info.getDetector().getId()
312 row = visitSummary.find(detectorId)
314 self.
log.warning(
"Detector id %s not found in external calibrations catalog; "
315 "Using original calibrations.", detectorId)
318 apCorrMap = row.getApCorrMap()
320 self.
log.warning(
"Detector id %s has None for psf in "
321 "external calibrations catalog; Using original psf and aperture correction.",
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.",
329 exposure.info.setApCorrMap(apCorrMap)
334 def run(self, template, science, sources, visitSummary=None):
335 """PSF match, subtract, and decorrelate two images.
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
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
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
362 ``psfMatchingKernel`` : `lsst.afw.math.Kernel`
363 Kernel used to PSF-match the convolved image.
368 If an unsupported convolution mode is supplied.
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
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)
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
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
393 if self.config.mode ==
"auto":
396 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer,
397 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid)
400 self.
log.info(
"Average template PSF size is greater, "
401 "but science PSF greater in one dimension: convolving template image.")
403 self.
log.info(
"Science PSF size is greater: convolving template image.")
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
413 raise RuntimeError(
"Cannot handle AlardLuptonSubtract mode: %s", self.config.mode)
416 sourceMask = science.mask.clone()
417 sourceMask.array |= template[science.getBBox()].mask.array
420 self.metadata[
"convolvedExposure"] =
"Template"
423 self.metadata[
"convolvedExposure"] =
"Science"
427 self.
log.warning(
"Failed to match template. Checking coverage")
430 self.config.minTemplateFractionForExpectedSuccess,
431 exceptionMessage=
"Template coverage lower than expected to succeed."
432 f
" Failure is tolerable: {e}")
436 metrics = computeDifferenceImageMetrics(science, subtractResults.difference, sources)
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"])
447 return subtractResults
450 """Convolve the template image with a PSF-matching kernel and subtract
451 from the science image.
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
466 results : `lsst.pipe.base.Struct`
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.
478 kernelSources = self.makeKernel.selectKernelSources(template, science,
479 candidateList=selectSources,
483 kernelResult = self.makeKernel.
run(template, science, kernelSources,
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(
493 sigmaToFwhm = 2*np.log(2*np.sqrt(2))
494 candidateList = self.makeKernel.makeCandidateList(template, science, kernelSize,
497 kernelSources = self.makeKernel.selectKernelSources(template, science,
498 candidateList=candidateList,
502 kernelResult = self.makeKernel.
run(template, science, kernelSources,
509 matchedTemplate = self.
_convolveExposure(template, kernelResult.psfMatchingKernel,
511 bbox=science.getBBox(),
513 photoCalib=science.photoCalib)
516 backgroundModel=(kernelResult.backgroundModel
517 if self.config.doSubtractBackground
else None))
518 correctedExposure = self.
finalize(template, science, difference,
519 kernelResult.psfMatchingKernel,
520 templateMatched=
True)
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)
530 """Convolve the science image with a PSF-matching kernel and subtract
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
546 results : `lsst.pipe.base.Struct`
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.
558 bbox = science.getBBox()
559 kernelSources = self.makeKernel.selectKernelSources(science, template,
560 candidateList=selectSources,
564 kernelResult = self.makeKernel.
run(science, template, kernelSources,
568 modelParams = kernelResult.backgroundModel.getParameters()
570 kernelResult.backgroundModel.setParameters([-p
for p
in modelParams])
572 kernelImage = lsst.afw.image.ImageD(kernelResult.psfMatchingKernel.getDimensions())
573 norm = kernelResult.psfMatchingKernel.computeImage(kernelImage, doNormalize=
False)
580 matchedScience.maskedImage /= norm
581 matchedTemplate = template.clone()[bbox]
582 matchedTemplate.maskedImage /= norm
583 matchedTemplate.setPhotoCalib(science.photoCalib)
586 backgroundModel=(kernelResult.backgroundModel
587 if self.config.doSubtractBackground
else None))
589 correctedExposure = self.
finalize(template, science, difference,
590 kernelResult.psfMatchingKernel,
591 templateMatched=
False)
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)
600 def finalize(self, template, science, difference, kernel,
601 templateMatched=True,
604 spatiallyVarying=False):
605 """Decorrelate the difference image to undo the noise correlations
606 caused by convolution.
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?
631 correctedExposure : `lsst.afw.image.ExposureF`
632 The decorrelated image difference.
634 if self.config.doDecorrelation:
635 self.
log.info(
"Decorrelating image difference.")
639 correctedExposure = self.decorrelate.
run(science, template[science.getBBox()], difference, kernel,
640 templateMatched=templateMatched,
641 preConvMode=preConvMode,
642 preConvKernel=preConvKernel,
643 spatiallyVarying=spatiallyVarying).correctedExposure
645 self.
log.info(
"NOT decorrelating image difference.")
646 correctedExposure = difference
647 return correctedExposure
650 """Calculate an exposure's limiting magnitude.
652 This method uses the photometric zeropoint together with the
653 PSF size from the average position of the exposure.
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.
666 maglim : `astropy.units.Quantity`
667 The limiting magnitude of the exposure, or np.nan.
669 if exposure.photoCalib
is None:
674 psf = exposure.getPsf()
675 psf_shape = psf.computeShape(psf.getAveragePosition())
677 afwDetection.InvalidPsfError,
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))
685 self.
log.info(
"Unable to evaluate PSF, setting maglim to nan")
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))
697 """Check that the WCS of the two Exposures match, the template bbox
698 contains the science bbox, and that the bands match.
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.
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.
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)
722 assert templateBBox.contains(scienceBBox), \
723 "Template bbox does not contain all of the science image."
729 interpolateBadMaskPlanes=False,
731 """Convolve an exposure with the given kernel.
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.
750 convolvedExp : `lsst.afw.Exposure`
753 convolvedExposure = exposure.clone()
755 convolvedExposure.setPsf(psf)
756 if photoCalib
is not None:
757 convolvedExposure.setPhotoCalib(photoCalib)
758 if interpolateBadMaskPlanes
and self.config.badMaskPlanes
is not None:
760 self.config.badMaskPlanes)
761 self.metadata[
"nInterpolated"] = nInterp
762 convolvedImage = lsst.afw.image.MaskedImageF(convolvedExposure.getBBox())
764 convolvedExposure.setMaskedImage(convolvedImage)
766 return convolvedExposure
768 return convolvedExposure[bbox]
771 """Select sources from a catalog that meet the selection criteria.
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.
783 selectSources : `lsst.afw.table.SourceCatalog`
784 The input source catalog, with flagged and low signal-to-noise
790 If there are too few sources to compute the PSF matching kernel
791 remaining after source selection.
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)
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)
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)
823 """Perform preparatory calculations common to all Alard&Lupton Tasks.
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
839 if visitSummary
is not None:
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"
847 self.metadata[
"templateCoveragePercent"] = 100*templateCoverageFraction
849 if self.config.doScaleVariance:
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
884 self.
log.info(
"Unable to evaluate PSF at the average position. "
885 "Evaluting PSF on a grid of points."
889 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer,
890 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid
894 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer,
895 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid
903 """Update the science and template mask planes before differencing.
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
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
916 self.
_clearMask(science.mask, clearMaskPlanes=[
"DETECTED",
"DETECTED_NEGATIVE"])
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()]
931 if "FAKE" in science.mask.getMaskPlaneDict().keys():
932 self.
log.info(
"Adding injected mask plane to science image")
934 if "FAKE" in template.mask.getMaskPlaneDict().keys():
935 self.
log.info(
"Adding injected mask plane to template image")
937 if "INJECTED" in renameMaskPlanes:
938 renameMaskPlanes.remove(
"INJECTED")
939 if "INJECTED_TEMPLATE" in clearMaskPlanes:
940 clearMaskPlanes.remove(
"INJECTED_TEMPLATE")
942 for maskPlane
in renameMaskPlanes:
944 self.
_clearMask(template.mask, clearMaskPlanes=clearMaskPlanes)
948 """Rename a mask plane by adding the new name and copying the data.
952 mask : `lsst.afw.image.Mask`
953 The mask image to update in place.
955 The name of the existing mask plane to copy.
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.
960 mask.addMaskPlane(newMaskPlane)
961 originBitMask = mask.getPlaneBitMask(maskPlane)
962 destinationBitMask = mask.getPlaneBitMask(newMaskPlane)
963 mask.array |= ((mask.array & originBitMask) > 0)*destinationBitMask
966 """Clear the mask plane of an exposure.
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.
976 if clearMaskPlanes
is None:
977 clearMaskPlanes = list(mask.getMaskPlaneDict().keys())
979 bitMaskToClear = mask.getPlaneBitMask(clearMaskPlanes)
980 mask &= ~bitMaskToClear
984 SubtractScoreOutputConnections):
989 pipelineConnections=AlardLuptonPreconvolveSubtractConnections):
994 """Subtract a template from a science image, convolving the science image
995 before computing the kernel, and also convolving the template before
998 ConfigClass = AlardLuptonPreconvolveSubtractConfig
999 _DefaultName =
"alardLuptonPreconvolveSubtract"
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.
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
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
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.
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
1037 ``psfMatchingKernel`` : `lsst.afw.math.Kernel`
1038 Final kernel used to PSF-match the template to the science
1041 self.
_prepareInputs(template, science, visitSummary=visitSummary)
1044 scienceKernel = science.psf.getKernel()
1046 interpolateBadMaskPlanes=
True)
1047 self.metadata[
"convolvedExposure"] =
"Preconvolution"
1050 subtractResults = self.
runPreconvolve(template, science, matchedScience,
1051 selectSources, scienceKernel)
1054 self.
log.warning(
"Failed to match template. Checking coverage")
1057 self.config.minTemplateFractionForExpectedSuccess,
1058 exceptionMessage=
"Template coverage lower than expected to succeed."
1059 f
" Failure is tolerable: {e}")
1063 return subtractResults
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
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
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.
1088 results : `lsst.pipe.base.Struct`
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
1102 ``psfMatchingKernel`` : `lsst.afw.math.Kernel`
1103 Final kernel used to PSF-match the template to the science
1106 bbox = science.getBBox()
1107 innerBBox = preConvKernel.shrinkBBox(bbox)
1109 kernelSources = self.makeKernel.selectKernelSources(template[innerBBox], matchedScience[innerBBox],
1110 candidateList=selectSources,
1114 kernelResult = self.makeKernel.
run(template[innerBBox], matchedScience[innerBBox], kernelSources,
1119 matchedTemplate = self.
_convolveExposure(template, kernelResult.psfMatchingKernel,
1123 interpolateBadMaskPlanes=
True,
1124 photoCalib=science.photoCalib)
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)
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)
1142 exceptionMessage=""):
1143 """Raise NoWorkFound if template coverage < requiredTemplateFraction
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
1154 exceptionMessage : `str`, optional
1155 Message to include in the exception raised if the template coverage
1160 templateCoverageFraction: `float`
1161 Fraction of pixels in the template with data.
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
1171 noTemplate = templateExposure.mask.array & templateExposure.mask.getPlaneBitMask(
'NO_DATA')
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)
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
1189 """Subtract template from science, propagating relevant metadata.
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
1202 difference : `lsst.afw.Exposure`
1203 The subtracted image.
1205 difference = science.clone()
1206 if backgroundModel
is not None:
1207 difference.maskedImage -= backgroundModel
1208 difference.maskedImage -= template.maskedImage
1213 """Determine that the PSF of ``exp1`` is not wider than that of ``exp2``.
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.
1231 True if ``exp1`` has a PSF that is not wider than that of ``exp2`` in
1235 shape1 = getPsfFwhm(exp1.psf, average=
False)
1236 shape2 = getPsfFwhm(exp2.psf, average=
False)
1238 shape1 = evaluateMeanPsfFwhm(exp1,
1239 fwhmExposureBuffer=fwhmExposureBuffer,
1240 fwhmExposureGrid=fwhmExposureGrid
1242 shape2 = evaluateMeanPsfFwhm(exp2,
1243 fwhmExposureBuffer=fwhmExposureBuffer,
1244 fwhmExposureGrid=fwhmExposureGrid
1246 return shape1 <= shape2
1249 xTest = shape1[0] <= shape2[0]
1250 yTest = shape1[1] <= shape2[1]
1251 return xTest | yTest
1255 """Replace masked image pixels with interpolated values.
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.
1269 The number of masked pixels that were replaced.
1271 imgBadMaskPlanes = [
1272 maskPlane
for maskPlane
in badMaskPlanes
if maskPlane
in maskedImage.mask.getMaskPlaneDict()
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)
1282 image[badPixels] = fallbackValue
1283 return np.sum(badPixels)
runPreconvolve(self, template, science, matchedScience, selectSources, preConvKernel)
run(self, template, science, sources, visitSummary=None)
_clearMask(self, mask, clearMaskPlanes=None)
_prepareInputs(self, template, science, visitSummary=None)
run(self, template, science, sources, visitSummary=None)
_calculateMagLim(self, exposure, nsigma=5.0, fallbackPsfSize=None)
runConvolveTemplate(self, template, science, selectSources)
_applyExternalCalibrations(self, exposure, visitSummary)
updateMasks(self, template, science)
_sourceSelector(self, sources, mask)
_convolveExposure(self, exposure, kernel, convolutionControl, bbox=None, psf=None, photoCalib=None, interpolateBadMaskPlanes=False)
runConvolveScience(self, template, science, selectSources)
finalize(self, template, science, difference, kernel, templateMatched=True, preConvMode=False, preConvKernel=None, spatiallyVarying=False)
_validateExposures(template, science)
_renameMaskPlanes(mask, maskPlane, newMaskPlane)
void convolve(OutImageT &convolvedImage, InImageT const &inImage, KernelT const &kernel, ConvolutionControl const &convolutionControl=ConvolutionControl())
_subtractImages(science, template, backgroundModel=None)
checkTemplateIsSufficient(templateExposure, scienceExposure, logger, requiredTemplateFraction=0., exceptionMessage="")
_interpolateImage(maskedImage, badMaskPlanes, fallbackValue=None)
_shapeTest(exp1, exp2, fwhmExposureBuffer, fwhmExposureGrid)