22from astropy
import units
as u
23from astropy.stats
import gaussian_fwhm_to_sigma
31 computeDifferenceImageMetrics,
32 checkMask, setSourceFootprints)
33from lsst.meas.algorithms
import ScaleVarianceTask, ScienceSourceSelectorTask
38from .
import MakeKernelTask, DecorrelateALKernelTask
39from lsst.utils.timer
import timeMethod
41__all__ = [
"AlardLuptonSubtractConfig",
"AlardLuptonSubtractTask",
42 "AlardLuptonPreconvolveSubtractConfig",
"AlardLuptonPreconvolveSubtractTask",
43 "SimplifiedSubtractConfig",
"SimplifiedSubtractTask",
44 "InsufficientKernelSourcesError"]
46_dimensions = (
"instrument",
"visit",
"detector")
47_defaultTemplates = {
"coaddName":
"deep",
"fakesType":
""}
51 """Raised when there are too few sources to calculate the PSF matching
55 msg = (f
"Only {nSources} sources were selected for PSF matching,"
56 f
" but {nRequired} are required.")
69 dimensions=_dimensions,
70 defaultTemplates=_defaultTemplates):
71 template = connectionTypes.Input(
72 doc=
"Input warped template to subtract.",
73 dimensions=(
"instrument",
"visit",
"detector"),
74 storageClass=
"ExposureF",
75 name=
"{fakesType}{coaddName}Diff_templateExp"
77 science = connectionTypes.Input(
78 doc=
"Input science exposure to subtract from.",
79 dimensions=(
"instrument",
"visit",
"detector"),
80 storageClass=
"ExposureF",
81 name=
"{fakesType}calexp"
83 sources = connectionTypes.Input(
84 doc=
"Sources measured on the science exposure; "
85 "used to select sources for making the matching kernel.",
86 dimensions=(
"instrument",
"visit",
"detector"),
87 storageClass=
"SourceCatalog",
90 visitSummary = connectionTypes.Input(
91 doc=(
"Per-visit catalog with final calibration objects. "
92 "These catalogs use the detector id for the catalog id, "
93 "sorted on id for fast lookup."),
94 dimensions=(
"instrument",
"visit"),
95 storageClass=
"ExposureCatalog",
96 name=
"finalVisitSummary",
101 if not config.doApplyExternalCalibrations:
106 dimensions=_dimensions,
107 defaultTemplates=_defaultTemplates):
108 difference = connectionTypes.Output(
109 doc=
"Result of subtracting convolved template from science image.",
110 dimensions=(
"instrument",
"visit",
"detector"),
111 storageClass=
"ExposureF",
112 name=
"{fakesType}{coaddName}Diff_differenceTempExp",
114 matchedTemplate = connectionTypes.Output(
115 doc=
"Warped and PSF-matched template used to create `subtractedExposure`.",
116 dimensions=(
"instrument",
"visit",
"detector"),
117 storageClass=
"ExposureF",
118 name=
"{fakesType}{coaddName}Diff_matchedExp",
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_psfMatchKernel",
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_psfMatchSources"
135 dimensions=_dimensions,
136 defaultTemplates=_defaultTemplates):
137 scoreExposure = connectionTypes.Output(
138 doc=
"The maximum likelihood image, used for the detection of diaSources.",
139 dimensions=(
"instrument",
"visit",
"detector"),
140 storageClass=
"ExposureF",
141 name=
"{fakesType}{coaddName}Diff_scoreTempExp",
143 psfMatchingKernel = connectionTypes.Output(
144 doc=
"Kernel used to PSF match the science and template images.",
145 dimensions=(
"instrument",
"visit",
"detector"),
146 storageClass=
"MatchingKernel",
147 name=
"{fakesType}{coaddName}Diff_psfScoreMatchKernel",
149 kernelSources = connectionTypes.Output(
150 doc=
"Final selection of sources used for psf matching.",
151 dimensions=(
"instrument",
"visit",
"detector"),
152 storageClass=
"SourceCatalog",
153 name=
"{fakesType}{coaddName}Diff_psfScoreMatchSources"
161class SimplifiedSubtractConnections(SubtractInputConnections, SubtractImageOutputConnections):
162 inputPsfMatchingKernel = connectionTypes.Input(
163 doc=
"Kernel used to PSF match the science and template images.",
164 dimensions=(
"instrument",
"visit",
"detector"),
165 storageClass=
"MatchingKernel",
166 name=
"{fakesType}{coaddName}Diff_psfMatchKernel",
172 if config.useExistingKernel:
180 makeKernel = lsst.pex.config.ConfigurableField(
181 target=MakeKernelTask,
182 doc=
"Task to construct a matching kernel for convolution.",
184 doDecorrelation = lsst.pex.config.Field(
187 doc=
"Perform diffim decorrelation to undo pixel correlation due to A&L "
188 "kernel convolution? If True, also update the diffim PSF."
190 decorrelate = lsst.pex.config.ConfigurableField(
191 target=DecorrelateALKernelTask,
192 doc=
"Task to decorrelate the image difference.",
194 requiredTemplateFraction = lsst.pex.config.Field(
197 doc=
"Raise NoWorkFound and do not attempt image subtraction if template covers less than this "
198 " fraction of pixels. Setting to 0 will always attempt image subtraction."
200 minTemplateFractionForExpectedSuccess = lsst.pex.config.Field(
203 doc=
"Raise NoWorkFound if PSF-matching fails and template covers less than this fraction of pixels."
204 " If the fraction of pixels covered by the template is less than this value (and greater than"
205 " requiredTemplateFraction) this task is attempted but failure is anticipated and tolerated."
207 doScaleVariance = lsst.pex.config.Field(
210 doc=
"Scale variance of the science image? Note that the template variance is NOT scaled"
211 " here. The template variance may be scaled independently in ``GetTemplateTask``."
213 scaleVariance = lsst.pex.config.ConfigurableField(
214 target=ScaleVarianceTask,
215 doc=
"Subtask to rescale the variance of the template to the statistically expected level."
217 doSubtractBackground = lsst.pex.config.Field(
218 doc=
"Subtract the background fit when solving the kernel? "
219 "It is generally better to instead subtract the background in detectAndMeasure.",
223 doApplyExternalCalibrations = lsst.pex.config.Field(
225 "Replace science Exposure's calibration objects with those"
226 " in visitSummary. Ignored if `doApplyFinalizedPsf is True."
231 sourceSelector = lsst.pex.config.ConfigurableField(
232 target=ScienceSourceSelectorTask,
233 doc=
"Task to select sources to be used for PSF matching.",
235 fallbackSourceSelector = lsst.pex.config.ConfigurableField(
236 target=ScienceSourceSelectorTask,
237 doc=
"Task to select sources to be used for PSF matching."
238 "Used only if the kernel calculation fails and"
239 "`allowKernelSourceDetection` is set. The fallback source detection"
240 " will not include all of the same plugins as the original source "
241 " detection, so not all of the same flags can be used.",
243 detectionThreshold = lsst.pex.config.Field(
246 doc=
"Minimum signal to noise ratio of detected sources "
247 "to use for calculating the PSF matching kernel.",
248 deprecated=
"No longer used. Will be removed after v30"
250 detectionThresholdMax = lsst.pex.config.Field(
253 doc=
"Maximum signal to noise ratio of detected sources "
254 "to use for calculating the PSF matching kernel.",
255 deprecated=
"No longer used. Will be removed after v30"
257 restrictKernelEdgeSources = lsst.pex.config.Field(
260 doc=
"Exclude sources close to the edge from the kernel calculation?"
262 maxKernelSources = lsst.pex.config.Field(
265 doc=
"Maximum number of sources to use for calculating the PSF matching kernel."
266 "Set to -1 to disable."
268 minKernelSources = lsst.pex.config.Field(
271 doc=
"Minimum number of sources needed for calculating the PSF matching kernel."
273 excludeMaskPlanes = lsst.pex.config.ListField(
275 default=(
"NO_DATA",
"BAD",
"SAT",
"EDGE",
"FAKE",
"HIGH_VARIANCE"),
276 doc=
"Template mask planes to exclude when selecting sources for PSF matching.",
278 badMaskPlanes = lsst.pex.config.ListField(
280 default=(
"NO_DATA",
"BAD",
"SAT",
"EDGE"),
281 doc=
"Mask planes to interpolate over."
283 preserveTemplateMask = lsst.pex.config.ListField(
285 default=(
"NO_DATA",
"BAD",
"HIGH_VARIANCE"),
286 doc=
"Mask planes from the template to propagate to the image difference."
288 renameTemplateMask = lsst.pex.config.ListField(
290 default=(
"SAT",
"INJECTED",
"INJECTED_CORE",),
291 doc=
"Mask planes from the template to propagate to the image difference"
292 "with '_TEMPLATE' appended to the name."
294 preserveMaskPlanes = lsst.pex.config.ListField(
296 default=(
"INJECTED",
"INJECTED_CORE",
"INJECTED_TEMPLATE",
"INJECTED_CORE_TEMPLATE"),
297 doc=
"Mask planes to preserve without dilation when convolving the image.",
299 allowKernelSourceDetection = lsst.pex.config.Field(
302 doc=
"Re-run source detection for kernel candidates if an error is"
303 " encountered while calculating the matching kernel."
310 self.
makeKernel.kernel.active.fitForBackground =
True
311 self.
makeKernel.kernel.active.spatialKernelOrder = 1
312 self.
makeKernel.kernel.active.spatialBgOrder = 2
315 doSignalToNoise =
True
317 signalToNoiseMinimum = 10
318 signalToNoiseMaximum = 500
339 pipelineConnections=AlardLuptonSubtractConnections):
340 mode = lsst.pex.config.ChoiceField(
342 default=
"convolveTemplate",
343 allowed={
"auto":
"Choose which image to convolve at runtime.",
344 "convolveScience":
"Only convolve the science image.",
345 "convolveTemplate":
"Only convolve the template image."},
346 doc=
"Choose which image to convolve at runtime, or require that a specific image is convolved."
351 """Compute the image difference of a science and template image using
352 the Alard & Lupton (1998) algorithm.
354 ConfigClass = AlardLuptonSubtractConfig
355 _DefaultName =
"alardLuptonSubtract"
356 usePreconvolution =
False
357 """Whether this task preconvolves the science image with its own PSF
358 before kernel-matching. Subclasses that preconvolve override this to
363 self.makeSubtask(
"decorrelate")
364 self.makeSubtask(
"makeKernel")
365 self.makeSubtask(
"sourceSelector")
366 self.makeSubtask(
"fallbackSourceSelector")
367 if self.config.doScaleVariance:
368 self.makeSubtask(
"scaleVariance")
377 """Replace calibrations (psf, and ApCorrMap) on this exposure with
382 exposure : `lsst.afw.image.exposure.Exposure`
383 Input exposure to adjust calibrations.
384 visitSummary : `lsst.afw.table.ExposureCatalog`
385 Exposure catalog with external calibrations to be applied. Catalog
386 uses the detector id for the catalog id, sorted on id for fast
391 exposure : `lsst.afw.image.exposure.Exposure`
392 Exposure with adjusted calibrations.
394 detectorId = exposure.info.getDetector().getId()
396 row = visitSummary.find(detectorId)
398 self.
log.warning(
"Detector id %s not found in external calibrations catalog; "
399 "Using original calibrations.", detectorId)
402 apCorrMap = row.getApCorrMap()
404 self.
log.warning(
"Detector id %s has None for psf in "
405 "external calibrations catalog; Using original psf and aperture correction.",
407 elif apCorrMap
is None:
408 self.
log.warning(
"Detector id %s has None for apCorrMap in "
409 "external calibrations catalog; Using original psf and aperture correction.",
413 exposure.info.setApCorrMap(apCorrMap)
418 inputs = butlerQC.get(inputRefs)
421 results = self.
run(**inputs)
422 except lsst.pipe.base.AlgorithmError
as e:
423 error = lsst.pipe.base.AnnotatedPartialOutputsError.annotate(e, self, log=self.
log)
427 butlerQC.put(results, outputRefs)
430 def run(self, template, science, sources, visitSummary=None):
431 """PSF match, subtract, and decorrelate two images.
435 template : `lsst.afw.image.ExposureF`
436 Template exposure, warped to match the science exposure.
437 science : `lsst.afw.image.ExposureF`
438 Science exposure to subtract from the template.
439 sources : `lsst.afw.table.SourceCatalog`
440 Identified sources on the science exposure. This catalog is used to
441 select sources in order to perform the AL PSF matching on stamp
443 visitSummary : `lsst.afw.table.ExposureCatalog`, optional
444 Exposure catalog with external calibrations to be applied. Catalog
445 uses the detector id for the catalog id, sorted on id for fast
450 results : `lsst.pipe.base.Struct`
451 ``difference`` : `lsst.afw.image.ExposureF`
452 Result of subtracting template and science.
453 ``matchedTemplate`` : `lsst.afw.image.ExposureF`
454 Warped and PSF-matched template exposure.
455 ``backgroundModel`` : `lsst.afw.math.Function2D`
456 Background model that was fit while solving for the
458 ``psfMatchingKernel`` : `lsst.afw.math.Kernel`
459 Kernel used to PSF-match the convolved image.
460 ``kernelSources` : `lsst.afw.table.SourceCatalog`
461 Sources from the input catalog that were used to construct the
469 kernelResult = self.
runMakeKernel(template, science, sources=sources,
470 convolveTemplate=convolveTemplate,
471 runSourceDetection=
False)
473 if self.config.doSubtractBackground:
474 backgroundModel = kernelResult.backgroundModel
476 backgroundModel =
None
478 subtractResults = self.
runConvolveTemplate(template, science, kernelResult.psfMatchingKernel,
479 backgroundModel=backgroundModel)
481 subtractResults = self.
runConvolveScience(template, science, kernelResult.psfMatchingKernel,
482 backgroundModel=backgroundModel)
483 subtractResults.kernelSources = kernelResult.kernelSources
485 metrics = computeDifferenceImageMetrics(science, subtractResults.difference, sources)
487 self.metadata[
"differenceFootprintRatioMean"] = metrics.differenceFootprintRatioMean
488 self.metadata[
"differenceFootprintRatioStdev"] = metrics.differenceFootprintRatioStdev
489 self.metadata[
"differenceFootprintSkyRatioMean"] = metrics.differenceFootprintSkyRatioMean
490 self.metadata[
"differenceFootprintSkyRatioStdev"] = metrics.differenceFootprintSkyRatioStdev
491 self.
log.info(
"Mean, stdev of ratio of difference to science "
492 "pixels in star footprints: %5.4f, %5.4f",
493 self.metadata[
"differenceFootprintRatioMean"],
494 self.metadata[
"differenceFootprintRatioStdev"])
496 return subtractResults
499 """Determine whether the template should be convolved with the PSF
504 template : `lsst.afw.image.ExposureF`
505 Template exposure, warped to match the science exposure.
506 science : `lsst.afw.image.ExposureF`
507 Science exposure to subtract from the template.
511 convolveTemplate : `bool`
512 Convolve the template to match the two images?
517 If an unsupported convolution mode is supplied.
520 raise RuntimeError(
"Choosing a convolution method is incompatible with preconvolution!")
521 if self.config.mode ==
"auto":
524 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer,
525 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid)
528 self.
log.info(
"Average template PSF size is greater, "
529 "but science PSF greater in one dimension: convolving template image.")
531 self.
log.info(
"Science PSF size is greater: convolving template image.")
533 self.
log.info(
"Template PSF size is greater: convolving science image.")
534 elif self.config.mode ==
"convolveTemplate":
535 self.
log.info(
"`convolveTemplate` is set: convolving template image.")
536 convolveTemplate =
True
537 elif self.config.mode ==
"convolveScience":
538 self.
log.info(
"`convolveScience` is set: convolving science image.")
539 convolveTemplate =
False
541 raise RuntimeError(f
"Cannot handle AlardLuptonSubtract mode: {self.config.mode}")
542 return convolveTemplate
544 def runMakeKernel(self, template, science, sources=None, convolveTemplate=True, runSourceDetection=False):
545 """Construct the PSF-matching kernel. Not used for preconvolution.
549 template : `lsst.afw.image.ExposureF`
550 Template exposure, warped to match the science exposure.
551 science : `lsst.afw.image.ExposureF`
552 Science exposure to subtract from the template.
553 sources : `lsst.afw.table.SourceCatalog`
554 Identified sources on the science exposure. This catalog is used to
555 select sources in order to perform the AL PSF matching on stamp
557 Not used if ``runSourceDetection`` is set.
558 convolveTemplate : `bool`, optional
559 Construct the matching kernel to convolve the template?
560 runSourceDetection : `bool`, optional
561 Run a minimal version of source detection to determine kernel
562 candidates? If False, a source list to select kernel candidates
563 from must be supplied.
567 results : `lsst.pipe.base.Struct`
568 ``backgroundModel`` : `lsst.afw.math.Function2D`
569 Background model that was fit while solving for the
571 ``psfMatchingKernel`` : `lsst.afw.math.Kernel`
572 Kernel used to PSF-match the convolved image.
573 ``kernelSources` : `lsst.afw.table.SourceCatalog`
574 Sources from the input catalog that were used to construct the
578 raise RuntimeError(
"Incorrect matching kernel calculation configured. "
579 "`runMakeKernel` can't be called if `usePreconvolution` is set.")
591 if runSourceDetection:
595 kernelResult = self.makeKernel.
run(reference, target, kernelSources,
597 templateFwhmPix=referenceFwhmPix,
598 scienceFwhmPix=targetFwhmPix)
600 self.
log.warning(
"Failed to match template. Checking coverage")
603 self.config.minTemplateFractionForExpectedSuccess,
604 exceptionMessage=
"Template coverage lower than expected to succeed."
605 f
" Failure is tolerable: {e}")
609 return lsst.pipe.base.Struct(backgroundModel=kernelResult.backgroundModel,
610 psfMatchingKernel=kernelResult.psfMatchingKernel,
611 kernelSources=kernelSources)
614 """Run detection on the science image and use the template mask plane
615 to reject candidate sources.
619 template : `lsst.afw.image.ExposureF`
620 Template exposure, warped to match the science exposure.
621 science : `lsst.afw.image.ExposureF`
622 Science exposure to subtract from the template.
626 kernelSources : `lsst.afw.table.SourceCatalog`
627 Sources from the input catalog to use to construct the
630 kernelSize = self.makeKernel.makeKernelBasisList(
632 sources = self.makeKernel.makeCandidateList(template, science, kernelSize,
638 """Convolve the template image with a PSF-matching kernel and subtract
639 from the science image.
643 template : `lsst.afw.image.ExposureF`
644 Template exposure, warped to match the science exposure.
645 science : `lsst.afw.image.ExposureF`
646 Science exposure to subtract from the template.
647 psfMatchingKernel : `lsst.afw.math.Kernel`
648 Kernel to be used to PSF-match the science image to the template.
649 backgroundModel : `lsst.afw.math.Function2D`, optional
650 Background model that was fit while solving for the PSF-matching
655 results : `lsst.pipe.base.Struct`
657 ``difference`` : `lsst.afw.image.ExposureF`
658 Result of subtracting template and science.
659 ``matchedTemplate`` : `lsst.afw.image.ExposureF`
660 Warped and PSF-matched template exposure.
661 ``backgroundModel`` : `lsst.afw.math.Function2D`
662 Background model that was fit while solving for the PSF-matching kernel
663 ``psfMatchingKernel`` : `lsst.afw.math.Kernel`
664 Kernel used to PSF-match the template to the science image.
666 self.metadata[
"convolvedExposure"] =
"Template"
670 bbox=science.getBBox(),
672 photoCalib=science.photoCalib)
674 difference =
_subtractImages(science, matchedTemplate, backgroundModel=backgroundModel)
675 correctedExposure = self.
finalize(template, science, difference,
677 templateMatched=
True)
679 return lsst.pipe.base.Struct(difference=correctedExposure,
680 matchedTemplate=matchedTemplate,
681 matchedScience=science,
682 backgroundModel=backgroundModel,
683 psfMatchingKernel=psfMatchingKernel)
686 """Convolve the science image with a PSF-matching kernel and subtract
691 template : `lsst.afw.image.ExposureF`
692 Template exposure, warped to match the science exposure.
693 science : `lsst.afw.image.ExposureF`
694 Science exposure to subtract from the template.
695 psfMatchingKernel : `lsst.afw.math.Kernel`
696 Kernel to be used to PSF-match the science image to the template.
697 backgroundModel : `lsst.afw.math.Function2D`, optional
698 Background model that was fit while solving for the PSF-matching
703 results : `lsst.pipe.base.Struct`
705 ``difference`` : `lsst.afw.image.ExposureF`
706 Result of subtracting template and science.
707 ``matchedTemplate`` : `lsst.afw.image.ExposureF`
708 Warped template exposure. Note that in this case, the template
709 is not PSF-matched to the science image.
710 ``backgroundModel`` : `lsst.afw.math.Function2D`
711 Background model that was fit while solving for the PSF-matching kernel
712 ``psfMatchingKernel`` : `lsst.afw.math.Kernel`
713 Kernel used to PSF-match the science image to the template.
715 self.metadata[
"convolvedExposure"] =
"Science"
716 bbox = science.getBBox()
718 kernelImage = lsst.afw.image.ImageD(psfMatchingKernel.getDimensions())
719 xcen, ycen = bbox.getCenter()
720 norm = psfMatchingKernel.computeImage(kernelImage, doNormalize=
False, x=xcen, y=ycen)
727 matchedScience.maskedImage /= norm
728 matchedTemplate = template.clone()[bbox]
729 matchedTemplate.setPhotoCalib(science.photoCalib)
731 if backgroundModel
is not None:
733 invertedBackground = backgroundModel.clone()
734 invertedBackground.setParameters([-p
for p
in backgroundModel.getParameters()])
735 backgroundModel = invertedBackground
737 difference =
_subtractImages(matchedScience, matchedTemplate, backgroundModel=backgroundModel)
739 correctedExposure = self.
finalize(template, science, difference,
741 templateMatched=
False)
743 return lsst.pipe.base.Struct(difference=correctedExposure,
744 matchedTemplate=matchedTemplate,
745 matchedScience=matchedScience,
746 backgroundModel=backgroundModel,
747 psfMatchingKernel=psfMatchingKernel)
749 def finalize(self, template, science, difference, kernel,
750 templateMatched=True,
753 spatiallyVarying=False):
754 """Decorrelate the difference image to undo the noise correlations
755 caused by convolution.
759 template : `lsst.afw.image.ExposureF`
760 Template exposure, warped to match the science exposure.
761 science : `lsst.afw.image.ExposureF`
762 Science exposure to subtract from the template.
763 difference : `lsst.afw.image.ExposureF`
764 Result of subtracting template and science.
765 kernel : `lsst.afw.math.Kernel`
766 An (optionally spatially-varying) PSF matching kernel
767 templateMatched : `bool`, optional
768 Was the template PSF-matched to the science image?
769 preConvMode : `bool`, optional
770 Was the science image preconvolved with its own PSF
771 before PSF matching the template?
772 preConvKernel : `lsst.afw.detection.Psf`, optional
773 If not `None`, then the science image was pre-convolved with
774 (the reflection of) this kernel. Must be normalized to sum to 1.
775 spatiallyVarying : `bool`, optional
776 Compute the decorrelation kernel spatially varying across the image?
780 correctedExposure : `lsst.afw.image.ExposureF`
781 The decorrelated image difference.
783 if self.config.doDecorrelation:
784 self.
log.info(
"Decorrelating image difference.")
788 correctedExposure = self.decorrelate.
run(science, template[science.getBBox()], difference, kernel,
789 templateMatched=templateMatched,
790 preConvMode=preConvMode,
791 preConvKernel=preConvKernel,
792 spatiallyVarying=spatiallyVarying).correctedExposure
794 self.
log.info(
"NOT decorrelating image difference.")
795 correctedExposure = difference
796 return correctedExposure
799 """Calculate an exposure's limiting magnitude.
801 This method uses the photometric zeropoint together with the
802 PSF size from the average position of the exposure.
806 exposure : `lsst.afw.image.Exposure`
807 The target exposure to calculate the limiting magnitude for.
808 nsigma : `float`, optional
809 The detection threshold in sigma.
810 fallbackPsfSize : `float`, optional
811 PSF FWHM to use in the event the exposure PSF cannot be retrieved.
815 maglim : `astropy.units.Quantity`
816 The limiting magnitude of the exposure, or np.nan.
818 if exposure.photoCalib
is None:
821 psf = exposure.getPsf()
822 psf_shape = psf.computeShape(psf.getAveragePosition())
824 afwDetection.InvalidPsfError,
826 if fallbackPsfSize
is None:
827 self.
log.info(
"Unable to evaluate PSF, setting maglim to nan")
829 self.
log.info(
"Unable to evaluate PSF, using fallback FWHM %f", fallbackPsfSize)
830 psf_area = np.pi*(fallbackPsfSize/2)**2
833 psf_area = np.pi*np.sqrt(psf_shape.getIxx()*psf_shape.getIyy())
835 zeropoint = exposure.photoCalib.instFluxToMagnitude(1)
836 return zeropoint - 2.5*np.log10(nsigma*np.sqrt(psf_area))
840 """Check that the WCS of the two Exposures match, the template bbox
841 contains the science bbox, and that the bands match.
845 template : `lsst.afw.image.ExposureF`
846 Template exposure, warped to match the science exposure.
847 science : `lsst.afw.image.ExposureF`
848 Science exposure to subtract from the template.
853 Raised if the WCS of the template is not equal to the science WCS,
854 if the science image is not fully contained in the template
855 bounding box, or if the bands do not match.
857 assert template.wcs == science.wcs, \
858 "Template and science exposure WCS are not identical."
859 templateBBox = template.getBBox()
860 scienceBBox = science.getBBox()
861 assert science.filter.bandLabel == template.filter.bandLabel, \
862 "Science and template exposures have different bands: %s, %s" % \
863 (science.filter, template.filter)
865 assert templateBBox.contains(scienceBBox), \
866 "Template bbox does not contain all of the science image."
872 interpolateBadMaskPlanes=False,
874 """Convolve an exposure with the given kernel.
878 exposure : `lsst.afw.Exposure`
879 exposure to convolve.
880 kernel : `lsst.afw.math.LinearCombinationKernel`
881 PSF matching kernel computed in the ``makeKernel`` subtask.
882 convolutionControl : `lsst.afw.math.ConvolutionControl`
883 Configuration for convolve algorithm.
884 bbox : `lsst.geom.Box2I`, optional
885 Bounding box to trim the convolved exposure to.
886 psf : `lsst.afw.detection.Psf`, optional
887 Point spread function (PSF) to set for the convolved exposure.
888 photoCalib : `lsst.afw.image.PhotoCalib`, optional
889 Photometric calibration of the convolved exposure.
890 interpolateBadMaskPlanes : `bool`, optional
891 If set, interpolate over mask planes specified in
892 ``config.badMaskPlanes`` before convolving the image.
896 convolvedExp : `lsst.afw.Exposure`
899 convolvedExposure = exposure.clone()
901 convolvedExposure.setPsf(psf)
902 if photoCalib
is not None:
903 convolvedExposure.setPhotoCalib(photoCalib)
904 if interpolateBadMaskPlanes
and self.config.badMaskPlanes
is not None:
906 self.config.badMaskPlanes)
907 self.metadata[
"nInterpolated"] = nInterp
911 preservePlanes = [mp
for mp
in self.config.preserveMaskPlanes
912 if mp
in convolvedExposure.mask.getMaskPlaneDict()]
914 mp: (convolvedExposure.mask.array
915 & convolvedExposure.mask.getPlaneBitMask(mp)) > 0
916 for mp
in preservePlanes
919 convolvedImage = lsst.afw.image.MaskedImageF(convolvedExposure.getBBox())
921 convolvedExposure.setMaskedImage(convolvedImage)
926 self.
_clearMask(convolvedExposure.mask, clearMaskPlanes=preservePlanes)
927 for maskPlane, maskSetPixels
in maskResetDict.items():
928 bit = convolvedExposure.mask.getPlaneBitMask(maskPlane)
929 convolvedExposure.mask.array[maskSetPixels] |= bit
932 return convolvedExposure
934 return convolvedExposure[bbox]
937 """Select sources from a catalog that meet the selection criteria.
938 The selection criteria include any configured parameters of the
939 `sourceSelector` subtask, as well as checking the science and template
944 template : `lsst.afw.image.ExposureF`
945 Template exposure, warped to match the science exposure.
946 science : `lsst.afw.image.ExposureF`
947 Science exposure to subtract from the template.
948 sources : `lsst.afw.table.SourceCatalog`
949 Input source catalog to select sources from.
950 fallback : `bool`, optional
951 Switch indicating the source selector is being called after
952 running the fallback source detection subtask, which does not run a
953 full set of measurement plugins and can't use the same settings for
958 kernelSources : `lsst.afw.table.SourceCatalog`
959 The input source catalog, with flagged and low signal-to-noise
960 sources removed and footprints added.
964 InsufficientKernelSourcesError
965 An AlgorithmError that is raised if there are not enough PSF
966 candidates to construct the PSF matching kernel.
969 selected = self.fallbackSourceSelector.selectSources(sources).selected
971 selected = self.sourceSelector.selectSources(sources).selected
976 selectSources = sources[selected].copy(deep=
True)
978 kernelSources = setSourceFootprints(selectSources, kernelSize=kSize)
979 bbox = science.getBBox()
984 if self.config.restrictKernelEdgeSources:
987 scienceSelected = checkMask(science.mask[bbox], kernelSources, self.config.excludeMaskPlanes)
988 templateSelected = checkMask(template.mask[bbox], kernelSources, self.config.excludeMaskPlanes)
989 maskSelected = scienceSelected & templateSelected
990 kernelSources = kernelSources[maskSelected].copy(deep=
True)
993 if (len(kernelSources) > self.config.maxKernelSources) & (self.config.maxKernelSources > 0):
994 signalToNoise = kernelSources.getPsfInstFlux()/kernelSources.getPsfInstFluxErr()
995 indices = np.argsort(signalToNoise)
996 indices = indices[-self.config.maxKernelSources:]
997 selected = np.zeros(len(kernelSources), dtype=bool)
998 selected[indices] =
True
999 kernelSources = kernelSources[selected].copy(deep=
True)
1001 self.
log.info(
"%i/%i=%.1f%% of sources selected for PSF matching from the input catalog",
1002 len(kernelSources), len(sources), 100*len(kernelSources)/len(sources))
1003 if len(kernelSources) < self.config.minKernelSources:
1004 self.
log.error(
"Too few sources to calculate the PSF matching kernel: "
1005 "%i selected but %i needed for the calculation.",
1006 len(kernelSources), self.config.minKernelSources)
1007 if self.config.allowKernelSourceDetection
and not fallback:
1014 nRequired=self.config.minKernelSources)
1016 self.metadata[
"nPsfSources"] = len(kernelSources)
1018 return kernelSources
1021 """Perform preparatory calculations common to all Alard&Lupton Tasks.
1025 template : `lsst.afw.image.ExposureF`
1026 Template exposure, warped to match the science exposure. The
1027 variance plane of the template image is modified in place.
1028 science : `lsst.afw.image.ExposureF`
1029 Science exposure to subtract from the template. The variance plane
1030 of the science image is modified in place.
1031 visitSummary : `lsst.afw.table.ExposureCatalog`, optional
1032 Exposure catalog with external calibrations to be applied. Catalog
1033 uses the detector id for the catalog id, sorted on id for fast
1037 if visitSummary
is not None:
1040 template[science.getBBox()], science, self.
log,
1041 requiredTemplateFraction=self.config.requiredTemplateFraction,
1042 exceptionMessage=
"Not attempting subtraction. To force subtraction,"
1043 " set config requiredTemplateFraction=0"
1045 self.metadata[
"templateCoveragePercent"] = 100*templateCoverageFraction
1047 if self.config.doScaleVariance:
1052 sciVarFactor = self.scaleVariance.
run(science.maskedImage)
1053 self.
log.info(
"Science variance scaling factor: %.2f", sciVarFactor)
1054 self.metadata[
"scaleScienceVarianceFactor"] = sciVarFactor
1080 self.
log.info(
"Unable to evaluate PSF at the average position. "
1081 "Evaluting PSF on a grid of points."
1085 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer,
1086 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid
1090 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer,
1091 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid
1100 if np.isnan(maglim_science):
1101 self.
log.warning(
"Limiting magnitude of the science image is NaN!")
1102 fluxlim_science = (maglim_science*u.ABmag).to_value(u.nJy)
1104 if np.isnan(maglim_template):
1105 self.
log.info(
"Cannot evaluate template limiting mag; adopting science limiting mag for diffim")
1106 maglim_diffim = maglim_science
1108 fluxlim_template = (maglim_template*u.ABmag).to_value(u.nJy)
1109 maglim_diffim = (np.sqrt(fluxlim_science**2 + fluxlim_template**2)*u.nJy).to(u.ABmag).value
1110 self.metadata[
"scienceLimitingMagnitude"] = maglim_science
1111 self.metadata[
"templateLimitingMagnitude"] = maglim_template
1112 self.metadata[
"diffimLimitingMagnitude"] = maglim_diffim
1115 """Update the science and template mask planes before differencing.
1119 template : `lsst.afw.image.Exposure`
1120 Template exposure, warped to match the science exposure.
1121 The template mask planes will be erased, except for a few specified
1123 science : `lsst.afw.image.Exposure`
1124 Science exposure to subtract from the template.
1125 The DETECTED and DETECTED_NEGATIVE mask planes of the science image
1128 self.
_clearMask(science.mask, clearMaskPlanes=[
"DETECTED",
"DETECTED_NEGATIVE"])
1135 clearMaskPlanes = [mp
for mp
in template.mask.getMaskPlaneDict().keys()
1136 if mp
not in self.config.preserveTemplateMask]
1137 renameMaskPlanes = [mp
for mp
in self.config.renameTemplateMask
1138 if mp
in template.mask.getMaskPlaneDict().keys()]
1143 if "FAKE" in science.mask.getMaskPlaneDict().keys():
1144 self.
log.info(
"Adding injected mask plane to science image")
1146 if "FAKE" in template.mask.getMaskPlaneDict().keys():
1147 self.
log.info(
"Adding injected mask plane to template image")
1149 if "INJECTED" in renameMaskPlanes:
1150 renameMaskPlanes.remove(
"INJECTED")
1151 if "INJECTED_TEMPLATE" in clearMaskPlanes:
1152 clearMaskPlanes.remove(
"INJECTED_TEMPLATE")
1154 for maskPlane
in renameMaskPlanes:
1156 self.
_clearMask(template.mask, clearMaskPlanes=clearMaskPlanes)
1160 """Rename a mask plane by adding the new name and copying the data.
1164 mask : `lsst.afw.image.Mask`
1165 The mask image to update in place.
1167 The name of the existing mask plane to copy.
1168 newMaskPlane : `str`
1169 The new name of the mask plane that will be added.
1170 If the mask plane already exists, it will be updated in place.
1172 mask.addMaskPlane(newMaskPlane)
1173 originBitMask = mask.getPlaneBitMask(maskPlane)
1174 destinationBitMask = mask.getPlaneBitMask(newMaskPlane)
1175 mask.array |= ((mask.array & originBitMask) > 0)*destinationBitMask
1178 """Clear the mask plane of an exposure.
1182 mask : `lsst.afw.image.Mask`
1183 The mask plane to erase, which will be modified in place.
1184 clearMaskPlanes : `list` of `str`, optional
1185 Erase the specified mask planes.
1186 If not supplied, the entire mask will be erased.
1188 if clearMaskPlanes
is None:
1189 clearMaskPlanes = list(mask.getMaskPlaneDict().keys())
1191 bitMaskToClear = mask.getPlaneBitMask(clearMaskPlanes)
1192 mask &= ~bitMaskToClear
1196 SubtractScoreOutputConnections):
1201 pipelineConnections=AlardLuptonPreconvolveSubtractConnections):
1206 """Subtract a template from a science image, convolving the science image
1207 before computing the kernel, and also convolving the template before
1210 ConfigClass = AlardLuptonPreconvolveSubtractConfig
1211 _DefaultName =
"alardLuptonPreconvolveSubtract"
1212 usePreconvolution =
True
1214 def run(self, template, science, sources, visitSummary=None):
1215 """Preconvolve the science image with its own PSF,
1216 convolve the template image with a PSF-matching kernel and subtract
1217 from the preconvolved science image.
1221 template : `lsst.afw.image.ExposureF`
1222 The template image, which has previously been warped to the science
1223 image. The template bbox will be padded by a few pixels compared to
1225 science : `lsst.afw.image.ExposureF`
1226 The science exposure.
1227 sources : `lsst.afw.table.SourceCatalog`
1228 Identified sources on the science exposure. This catalog is used to
1229 select sources in order to perform the AL PSF matching on stamp
1231 visitSummary : `lsst.afw.table.ExposureCatalog`, optional
1232 Exposure catalog with complete external calibrations. Catalog uses
1233 the detector id for the catalog id, sorted on id for fast lookup.
1237 results : `lsst.pipe.base.Struct`
1238 ``scoreExposure`` : `lsst.afw.image.ExposureF`
1239 Result of subtracting the convolved template and science
1240 images. Attached PSF is that of the original science image.
1241 ``matchedTemplate`` : `lsst.afw.image.ExposureF`
1242 Warped and PSF-matched template exposure. Attached PSF is that
1243 of the original science image.
1244 ``matchedScience`` : `lsst.afw.image.ExposureF`
1245 The science exposure after convolving with its own PSF.
1246 Attached PSF is that of the original science image.
1247 ``backgroundModel`` : `lsst.afw.math.Function2D`
1248 Background model that was fit while solving for the
1250 ``psfMatchingKernel`` : `lsst.afw.math.Kernel`
1251 Final kernel used to PSF-match the template to the science
1254 self.
_prepareInputs(template, science, visitSummary=visitSummary)
1258 interpolateBadMaskPlanes=
True)
1259 self.metadata[
"convolvedExposure"] =
"Preconvolution"
1263 self.metadata[
"preconvolvedSciencePsfSize"] = self.
matchedPsfSize
1265 kernelSources = self.
_sourceSelector(template, matchedScience, sources)
1266 subtractResults = self.
runPreconvolve(template, science, matchedScience,
1267 kernelSources, convolutionKernel)
1270 self.
log.warning(
"Failed to match template. Checking coverage")
1273 self.config.minTemplateFractionForExpectedSuccess,
1274 exceptionMessage=
"Template coverage lower than expected to succeed."
1275 f
" Failure is tolerable: {e}")
1279 return subtractResults
1283 """Set the EDGE mask bit on pixels outside a known-valid region.
1287 mask : `~lsst.afw.image.Mask`
1288 Exposure mask that will be modified in place. Must have
1289 an ``EDGE`` mask plane.
1290 innerBBox : `~lsst.geom.Box2I`
1291 The valid inner region. Pixels
1292 outside this bbox will have their ``EDGE`` bit set.
1294 bbox = mask.getBBox()
1295 edgeBit = mask.getPlaneBitMask(
"EDGE")
1296 dx0 = innerBBox.getMinX() - bbox.getMinX()
1297 dx1 = bbox.getMaxX() - innerBBox.getMaxX()
1298 dy0 = innerBBox.getMinY() - bbox.getMinY()
1299 dy1 = bbox.getMaxY() - innerBBox.getMaxY()
1301 mask.array[:dy0, :] |= edgeBit
1303 mask.array[-dy1:, :] |= edgeBit
1305 mask.array[:, :dx0] |= edgeBit
1307 mask.array[:, -dx1:] |= edgeBit
1311 """Build a normalized, reflected matched-filter kernel from a PSF.
1313 Convolving an image with this kernel is equivalent to correlating
1314 the image with the PSF, so peaks in the output align with the PSF's
1315 centroid — even for asymmetric PSFs. The kernel is evaluated at the
1316 PSF's average position and returned as a constant
1317 `~lsst.afw.math.Kernel`.
1321 psf : `~lsst.afw.detection.Psf`
1322 The PSF to derive the preconvolution kernel from.
1326 kernel : `~lsst.afw.math.Kernel`
1327 The PSF reflected about both axes, normalized to sum to one.
1332 Raised if the PSF kernel has an even size along either axis.
1333 It's not possible to center an even-sized kernel.
1335 avgPos = psf.getAveragePosition()
1336 localKernel = psf.getLocalKernel(avgPos)
1337 dims = localKernel.getDimensions()
1338 if dims.x % 2 == 0
or dims.y % 2 == 0:
1340 f
"Preconvolution requires an odd-sized PSF kernel, got {dims.x}x{dims.y}. "
1342 kimg = lsst.afw.image.ImageD(dims)
1343 localKernel.computeImage(kimg, doNormalize=
True)
1346 kimg.array[...] = kimg.array[::-1, ::-1]
1349 def runPreconvolve(self, template, science, matchedScience, kernelSources, preConvKernel):
1350 """Convolve the science image with its own PSF, then convolve the
1351 template with a matching kernel and subtract to form the Score
1356 template : `lsst.afw.image.ExposureF`
1357 Template exposure, warped to match the science exposure.
1358 science : `lsst.afw.image.ExposureF`
1359 Science exposure to subtract from the template.
1360 matchedScience : `lsst.afw.image.ExposureF`
1361 The science exposure, convolved with the reflection of its own PSF.
1362 kernelSources : `lsst.afw.table.SourceCatalog`
1363 Identified sources on the science exposure. This catalog is used to
1364 select sources in order to perform the AL PSF matching on stamp
1366 preConvKernel : `lsst.afw.math.Kernel`
1367 The kernel that was used to preconvolve the ``science``
1368 exposure. Must be normalized to sum to 1.
1372 results : `lsst.pipe.base.Struct`
1374 ``scoreExposure`` : `lsst.afw.image.ExposureF`
1375 Result of subtracting the convolved template and science
1376 images. Attached PSF is that of the original science image.
1377 ``matchedTemplate`` : `lsst.afw.image.ExposureF`
1378 Warped and PSF-matched template exposure. Attached PSF is that
1379 of the original science image.
1380 ``matchedScience`` : `lsst.afw.image.ExposureF`
1381 The science exposure after convolving with its own PSF.
1382 Attached PSF is that of the original science image.
1383 ``backgroundModel`` : `lsst.afw.math.Function2D`
1384 Background model that was fit while solving for the
1386 ``psfMatchingKernel`` : `lsst.afw.math.Kernel`
1387 Final kernel used to PSF-match the template to the science
1390 bbox = science.getBBox()
1391 innerBBox = preConvKernel.shrinkBBox(bbox)
1393 kernelResult = self.makeKernel.
run(template[innerBBox], matchedScience[innerBBox], kernelSources,
1398 matchedTemplate = self.
_convolveExposure(template, kernelResult.psfMatchingKernel,
1402 interpolateBadMaskPlanes=
True,
1403 photoCalib=science.photoCalib)
1405 backgroundModel=(kernelResult.backgroundModel
1406 if self.config.doSubtractBackground
else None))
1407 correctedScore = self.
finalize(template[bbox], science, score,
1408 kernelResult.psfMatchingKernel,
1409 templateMatched=
True, preConvMode=
True,
1410 preConvKernel=preConvKernel)
1415 return lsst.pipe.base.Struct(scoreExposure=correctedScore,
1416 matchedTemplate=matchedTemplate,
1417 matchedScience=matchedScience,
1418 backgroundModel=kernelResult.backgroundModel,
1419 psfMatchingKernel=kernelResult.psfMatchingKernel,
1420 kernelSources=kernelSources)
1424 exceptionMessage=""):
1425 """Raise NoWorkFound if template coverage < requiredTemplateFraction
1429 templateExposure : `lsst.afw.image.ExposureF`
1430 The template exposure to check
1431 logger : `logging.Logger`
1432 Logger for printing output.
1433 requiredTemplateFraction : `float`, optional
1434 Fraction of pixels of the science image required to have coverage
1436 exceptionMessage : `str`, optional
1437 Message to include in the exception raised if the template coverage
1442 templateCoverageFraction: `float`
1443 Fraction of pixels in the template with data.
1447 lsst.pipe.base.NoWorkFound
1448 Raised if fraction of good pixels, defined as not having NO_DATA
1449 set, is less than the requiredTemplateFraction
1453 noTemplate = templateExposure.mask.array & templateExposure.mask.getPlaneBitMask(
'NO_DATA')
1456 noScience = scienceExposure.mask.array & scienceExposure.mask.getPlaneBitMask(
'NO_DATA')
1457 pixNoData = np.count_nonzero(noTemplate | noScience)
1458 pixGood = templateExposure.getBBox().getArea() - pixNoData
1459 templateCoverageFraction = pixGood/templateExposure.getBBox().getArea()
1460 logger.info(
"template has %d good pixels (%.1f%%)", pixGood, 100*templateCoverageFraction)
1462 if templateCoverageFraction < requiredTemplateFraction:
1463 message = (
"Insufficient Template Coverage. (%.1f%% < %.1f%%)" % (
1464 100*templateCoverageFraction,
1465 100*requiredTemplateFraction))
1466 raise lsst.pipe.base.NoWorkFound(message +
" " + exceptionMessage)
1467 return templateCoverageFraction
1471 """Subtract template from science, propagating relevant metadata.
1475 science : `lsst.afw.Exposure`
1476 The input science image.
1477 template : `lsst.afw.Exposure`
1478 The template to subtract from the science image.
1479 backgroundModel : `lsst.afw.MaskedImage`, optional
1480 Differential background model
1484 difference : `lsst.afw.Exposure`
1485 The subtracted image.
1487 difference = science.clone()
1488 if backgroundModel
is not None:
1489 difference.maskedImage -= backgroundModel
1490 difference.maskedImage -= template.maskedImage
1495 """Determine that the PSF of ``exp1`` is not wider than that of ``exp2``.
1499 exp1 : `~lsst.afw.image.Exposure`
1500 Exposure with the reference point spread function (PSF) to evaluate.
1501 exp2 : `~lsst.afw.image.Exposure`
1502 Exposure with a candidate point spread function (PSF) to evaluate.
1503 fwhmExposureBuffer : `float`
1504 Fractional buffer margin to be left out of all sides of the image
1505 during the construction of the grid to compute mean PSF FWHM in an
1506 exposure, if the PSF is not available at its average position.
1507 fwhmExposureGrid : `int`
1508 Grid size to compute the mean FWHM in an exposure, if the PSF is not
1509 available at its average position.
1513 True if ``exp1`` has a PSF that is not wider than that of ``exp2`` in
1517 shape1 = getPsfFwhm(exp1.psf, average=
False)
1518 shape2 = getPsfFwhm(exp2.psf, average=
False)
1520 shape1 = evaluateMeanPsfFwhm(exp1,
1521 fwhmExposureBuffer=fwhmExposureBuffer,
1522 fwhmExposureGrid=fwhmExposureGrid
1524 shape2 = evaluateMeanPsfFwhm(exp2,
1525 fwhmExposureBuffer=fwhmExposureBuffer,
1526 fwhmExposureGrid=fwhmExposureGrid
1528 return shape1 <= shape2
1531 xTest = shape1[0] <= shape2[0]
1532 yTest = shape1[1] <= shape2[1]
1533 return xTest | yTest
1537 pipelineConnections=SimplifiedSubtractConnections):
1538 mode = lsst.pex.config.ChoiceField(
1540 default=
"convolveTemplate",
1541 allowed={
"auto":
"Choose which image to convolve at runtime.",
1542 "convolveScience":
"Only convolve the science image.",
1543 "convolveTemplate":
"Only convolve the template image."},
1544 doc=
"Choose which image to convolve at runtime, or require that a specific image is convolved."
1546 useExistingKernel = lsst.pex.config.Field(
1549 doc=
"Use a pre-existing PSF matching kernel?"
1550 "If False, source detection and measurement will be run."
1555 """Compute the image difference of a science and template image using
1556 the Alard & Lupton (1998) algorithm.
1558 ConfigClass = SimplifiedSubtractConfig
1559 _DefaultName =
"simplifiedSubtract"
1562 def run(self, template, science, visitSummary=None, inputPsfMatchingKernel=None):
1563 """PSF match, subtract, and decorrelate two images.
1567 template : `lsst.afw.image.ExposureF`
1568 Template exposure, warped to match the science exposure.
1569 science : `lsst.afw.image.ExposureF`
1570 Science exposure to subtract from the template.
1571 visitSummary : `lsst.afw.table.ExposureCatalog`, optional
1572 Exposure catalog with external calibrations to be applied. Catalog
1573 uses the detector id for the catalog id, sorted on id for fast
1575 inputPsfMatchingKernel : `lsst.afw.math.Kernel`, optional
1576 Pre-existing PSF matching kernel to use for convolution.
1577 Required, and only used, if ``config.useExistingKernel`` is set.
1581 results : `lsst.pipe.base.Struct`
1582 ``difference`` : `lsst.afw.image.ExposureF`
1583 Result of subtracting template and science.
1584 ``matchedTemplate`` : `lsst.afw.image.ExposureF`
1585 Warped and PSF-matched template exposure.
1586 ``backgroundModel`` : `lsst.afw.math.Function2D`
1587 Background model that was fit while solving for the
1589 ``psfMatchingKernel`` : `lsst.afw.math.Kernel`
1590 Kernel used to PSF-match the convolved image.
1591 ``kernelSources` : `lsst.afw.table.SourceCatalog`
1592 Sources detected on the science image that were used to
1593 construct the PSF-matching kernel.
1597 lsst.pipe.base.NoWorkFound
1598 Raised if fraction of good pixels, defined as not having NO_DATA
1599 set, is less then the configured requiredTemplateFraction
1601 self.
_prepareInputs(template, science, visitSummary=visitSummary)
1606 if self.config.useExistingKernel:
1607 psfMatchingKernel = inputPsfMatchingKernel
1608 backgroundModel =
None
1609 kernelSources =
None
1611 kernelResult = self.
runMakeKernel(template, science, convolveTemplate=convolveTemplate,
1612 runSourceDetection=
True)
1613 psfMatchingKernel = kernelResult.psfMatchingKernel
1614 kernelSources = kernelResult.kernelSources
1615 if self.config.doSubtractBackground:
1616 backgroundModel = kernelResult.backgroundModel
1618 backgroundModel =
None
1619 if convolveTemplate:
1621 backgroundModel=backgroundModel)
1624 backgroundModel=backgroundModel)
1625 if kernelSources
is not None:
1626 subtractResults.kernelSources = kernelSources
1627 return subtractResults
1631 """Replace masked image pixels with interpolated values.
1635 maskedImage : `lsst.afw.image.MaskedImage`
1636 Image on which to perform interpolation.
1637 badMaskPlanes : `list` of `str`
1638 List of mask planes to interpolate over.
1639 fallbackValue : `float`, optional
1640 Value to set when interpolation fails.
1645 The number of masked pixels that were replaced.
1647 imgBadMaskPlanes = [
1648 maskPlane
for maskPlane
in badMaskPlanes
if maskPlane
in maskedImage.mask.getMaskPlaneDict()
1651 image = maskedImage.image.array
1652 badPixels = (maskedImage.mask.array & maskedImage.mask.getPlaneBitMask(imgBadMaskPlanes)) > 0
1653 image[badPixels] = np.nan
1654 if fallbackValue
is None:
1655 fallbackValue = np.nanmedian(image)
1658 image[badPixels] = fallbackValue
1659 return np.sum(badPixels)
_flagScoreEdge(mask, innerBBox)
run(self, template, science, sources, visitSummary=None)
runPreconvolve(self, template, science, matchedScience, kernelSources, preConvKernel)
_makePreconvolutionKernel(psf)
_clearMask(self, mask, clearMaskPlanes=None)
_prepareInputs(self, template, science, visitSummary=None)
chooseConvolutionMethod(self, template, science)
runConvolveTemplate(self, template, science, psfMatchingKernel, backgroundModel=None)
runQuantum(self, butlerQC, inputRefs, outputRefs)
run(self, template, science, sources, visitSummary=None)
runConvolveScience(self, template, science, psfMatchingKernel, backgroundModel=None)
_calculateMagLim(self, exposure, nsigma=5.0, fallbackPsfSize=None)
_applyExternalCalibrations(self, exposure, visitSummary)
updateMasks(self, template, science)
runMakeKernel(self, template, science, sources=None, convolveTemplate=True, runSourceDetection=False)
_convolveExposure(self, exposure, kernel, convolutionControl, bbox=None, psf=None, photoCalib=None, interpolateBadMaskPlanes=False)
_sourceSelector(self, template, science, sources, fallback=False)
runKernelSourceDetection(self, template, science)
finalize(self, template, science, difference, kernel, templateMatched=True, preConvMode=False, preConvKernel=None, spatiallyVarying=False)
_validateExposures(template, science)
_renameMaskPlanes(mask, maskPlane, newMaskPlane)
__init__(self, *, nSources, nRequired)
__init__(self, *, config=None)
run(self, template, science, visitSummary=None, inputPsfMatchingKernel=None)
void convolve(OutImageT &convolvedImage, InImageT const &inImage, KernelT const &kernel, ConvolutionControl const &convolutionControl=ConvolutionControl())
_interpolateImage(maskedImage, badMaskPlanes, fallbackValue=None)
_subtractImages(science, template, backgroundModel=None)
checkTemplateIsSufficient(templateExposure, scienceExposure, logger, requiredTemplateFraction=0., exceptionMessage="")
_shapeTest(exp1, exp2, fwhmExposureBuffer, fwhmExposureGrid)