24from astropy
import units
as u
25from astropy.stats
import gaussian_fwhm_to_sigma
32from lsst.images
import DifferenceImage
33from lsst.images.convolution_kernels
import ImageBasisConvolutionKernel
35 computeDifferenceImageMetrics, computePSFNoiseEquivalentArea,
36 checkMask, record_from_obs_info, setSourceFootprints,
37 get_difference_image_provenance, checkTemplateIsSufficient)
38from lsst.meas.algorithms
import ScaleVarianceTask, ScienceSourceSelectorTask
43from .
import MakeKernelTask, DecorrelateALKernelTask
44from lsst.utils.timer
import timeMethod
46__all__ = [
"AlardLuptonSubtractConfig",
"AlardLuptonSubtractTask",
47 "AlardLuptonPreconvolveSubtractConfig",
"AlardLuptonPreconvolveSubtractTask",
48 "SimplifiedSubtractConfig",
"SimplifiedSubtractTask",
49 "InsufficientKernelSourcesError"]
51_dimensions = (
"instrument",
"visit",
"detector")
52_defaultTemplates = {
"coaddName":
"deep",
"fakesType":
""}
56 """Raised when there are too few sources to calculate the PSF matching
60 msg = (f
"Only {nSources} sources were selected for PSF matching,"
61 f
" but {nRequired} are required.")
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"
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"
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",
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",
110 if not config.doApplyExternalCalibrations:
112 if config.image_type ==
"future":
113 self.
template = dataclasses.replace(self.
template, storageClass=
"DifferenceImage")
114 self.
science = dataclasses.replace(self.
science, storageClass=
"VisitImage")
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",
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",
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",
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"
147 if config.image_type ==
"future":
150 storageClass=
"DifferenceImage")
152 storageClass=
"ConvolutionKernel")
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",
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",
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"
179 if config.image_type ==
"future":
182 storageClass=
"ConvolutionKernel")
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",
200 if config.useExistingKernel:
203 if config.image_type ==
"future":
205 storageClass=
"ConvolutionKernel")
211 makeKernel = lsst.pex.config.ConfigurableField(
212 target=MakeKernelTask,
213 doc=
"Task to construct a matching kernel for convolution.",
215 doDecorrelation = lsst.pex.config.Field(
218 doc=
"Perform diffim decorrelation to undo pixel correlation due to A&L "
219 "kernel convolution? If True, also update the diffim PSF."
221 decorrelate = lsst.pex.config.ConfigurableField(
222 target=DecorrelateALKernelTask,
223 doc=
"Task to decorrelate the image difference.",
225 requiredTemplateFraction = lsst.pex.config.Field(
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."
231 minTemplateFractionForExpectedSuccess = lsst.pex.config.Field(
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."
238 doScaleVariance = lsst.pex.config.Field(
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``."
244 scaleVariance = lsst.pex.config.ConfigurableField(
245 target=ScaleVarianceTask,
246 doc=
"Subtask to rescale the variance of the template to the statistically expected level."
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.",
253 deprecated=
"Subtract the background in detectAndMeasure instead. Will be removed after v31.",
255 doApplyExternalCalibrations = lsst.pex.config.Field(
257 "Replace science Exposure's calibration objects with those"
258 " in visitSummary. Ignored if `doApplyFinalizedPsf is True."
263 sourceSelector = lsst.pex.config.ConfigurableField(
264 target=ScienceSourceSelectorTask,
265 doc=
"Task to select sources to be used for PSF matching.",
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.",
275 detectionThreshold = lsst.pex.config.Field(
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"
282 detectionThresholdMax = lsst.pex.config.Field(
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"
289 restrictKernelEdgeSources = lsst.pex.config.Field(
292 doc=
"Exclude sources close to the edge from the kernel calculation?"
294 maxKernelSources = lsst.pex.config.Field(
297 doc=
"Maximum number of sources to use for calculating the PSF matching kernel."
298 "Set to -1 to disable."
300 minKernelSources = lsst.pex.config.Field(
303 doc=
"Minimum number of sources needed for calculating the PSF matching kernel."
305 excludeMaskPlanes = lsst.pex.config.ListField(
307 default=(
"NO_DATA",
"BAD",
"SAT",
"EDGE",
"FAKE",
"HIGH_VARIANCE"),
308 doc=
"Template mask planes to exclude when selecting sources for PSF matching.",
310 badMaskPlanes = lsst.pex.config.ListField(
312 default=(
"NO_DATA",
"BAD",
"SAT",
"EDGE"),
313 doc=
"Mask planes to interpolate over."
315 preserveTemplateMask = lsst.pex.config.ListField(
317 default=(
"NO_DATA",
"BAD",
"HIGH_VARIANCE"),
318 doc=
"Mask planes from the template to propagate to the image difference."
320 renameTemplateMask = lsst.pex.config.ListField(
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."
326 preserveMaskPlanes = lsst.pex.config.ListField(
328 default=(
"INJECTED",
"INJECTED_CORE",
"INJECTED_TEMPLATE",
"INJECTED_CORE_TEMPLATE"),
329 doc=
"Mask planes to preserve without dilation when convolving the image.",
331 allowKernelSourceDetection = lsst.pex.config.Field(
334 doc=
"Re-run source detection for kernel candidates if an error is"
335 " encountered while calculating the matching kernel."
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"
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.",
355 self.
makeKernel.kernel.active.fitForBackground =
True
356 self.
makeKernel.kernel.active.spatialKernelOrder = 1
357 self.
makeKernel.kernel.active.spatialBgOrder = 2
360 doSignalToNoise =
True
362 signalToNoiseMinimum = 10
363 signalToNoiseMaximum = 500
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."
393 pipelineConnections=AlardLuptonSubtractConnections):
394 mode = lsst.pex.config.ChoiceField(
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."
405 """Compute the image difference of a science and template image using
406 the Alard & Lupton (1998) algorithm.
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
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
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")
436 """Replace calibrations (psf, and ApCorrMap) on this exposure with
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
450 exposure : `lsst.afw.image.exposure.Exposure`
451 Exposure with adjusted calibrations.
453 detectorId = exposure.info.getDetector().getId()
455 row = visitSummary.find(detectorId)
457 self.
log.warning(
"Detector id %s not found in external calibrations catalog; "
458 "Using original calibrations.", detectorId)
461 apCorrMap = row.getApCorrMap()
463 self.
log.warning(
"Detector id %s has None for psf in "
464 "external calibrations catalog; Using original psf and aperture correction.",
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.",
472 exposure.info.setApCorrMap(apCorrMap)
477 inputs = butlerQC.get(inputRefs)
479 exposureRecord =
None
480 photometricScaling =
None
481 if self.config.image_type ==
"future":
482 template = inputs[
"template"]
483 dataId = butlerQC.quantum.dataId
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()
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)
502 if self.config.image_type ==
"future":
504 photometricScaling=photometricScaling)
506 butlerQC.put(results, outputRefs)
509 photometricScaling=None):
510 """Convert the image outputs to `lsst.images` types.
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`.
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`], \
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.
535 Raised if the PSF matching kernel cannot be stored on an
536 `lsst.images.DifferenceImage`.
538 Raised if an output has pixels set in a mask plane that
539 `lsst.images.get_legacy_difference_image_mask_planes` does not
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.
551 science = results.matchedScience
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
558 exposure = getattr(results, name,
None)
561 if exposure.getDetector()
is None:
564 exposure.setDetector(science.getDetector())
565 image = DifferenceImage.from_legacy(
568 exposure_record=exposureRecord,
570 if kernel
is not None:
571 image.kernel = kernel
573 image.templates = templateInfo
574 if photometricScaling
is not None:
575 image.photometric_scaling = photometricScaling
576 setattr(results, name, image)
577 results.psfMatchingKernel = kernel
580 def run(self, template, science, sources, visitSummary=None):
581 """PSF match, subtract, and decorrelate two images.
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
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
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
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
619 kernelResult = self.
runMakeKernel(template, science, sources=sources,
620 convolveTemplate=convolveTemplate,
621 runSourceDetection=
False)
623 if self.config.doSubtractBackground:
624 backgroundModel = kernelResult.backgroundModel
626 backgroundModel =
None
628 subtractResults = self.
runConvolveTemplate(template, science, kernelResult.psfMatchingKernel,
629 backgroundModel=backgroundModel)
631 subtractResults = self.
runConvolveScience(template, science, kernelResult.psfMatchingKernel,
632 backgroundModel=backgroundModel)
633 subtractResults.kernelSources = kernelResult.kernelSources
635 metrics = computeDifferenceImageMetrics(science, subtractResults.difference, sources)
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"])
646 return subtractResults
649 """Determine whether the template should be convolved with the PSF
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.
661 convolveTemplate : `bool`
662 Convolve the template to match the two images?
667 If an unsupported convolution mode is supplied.
670 raise RuntimeError(
"Choosing a convolution method is incompatible with preconvolution!")
671 if self.config.mode ==
"auto":
674 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer,
675 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid)
678 self.
log.info(
"Average template PSF size is greater, "
679 "but science PSF greater in one dimension: convolving template image.")
681 self.
log.info(
"Science PSF size is greater: convolving template image.")
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":
688 self.
log.info(
"`convolveScience` is set: convolving science image.")
689 convolveTemplate =
False
691 raise RuntimeError(f
"Cannot handle AlardLuptonSubtract mode: {self.config.mode}")
692 return convolveTemplate
694 def runMakeKernel(self, template, science, sources=None, convolveTemplate=True, runSourceDetection=False):
695 """Construct the PSF-matching kernel. Not used for preconvolution.
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
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.
717 results : `lsst.pipe.base.Struct`
718 ``backgroundModel`` : `lsst.afw.math.Function2D`
719 Background model that was fit while solving for the
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
728 raise RuntimeError(
"Incorrect matching kernel calculation configured. "
729 "`runMakeKernel` can't be called if `usePreconvolution` is set.")
741 if runSourceDetection:
745 kernelResult = self.makeKernel.
run(reference, target, kernelSources,
747 templateFwhmPix=referenceFwhmPix,
748 scienceFwhmPix=targetFwhmPix)
750 self.
log.warning(
"Failed to match template. Checking coverage")
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}"
761 return lsst.pipe.base.Struct(backgroundModel=kernelResult.backgroundModel,
762 psfMatchingKernel=kernelResult.psfMatchingKernel,
763 kernelSources=kernelSources)
766 """Run detection on the science image and use the template mask plane
767 to reject candidate sources.
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.
778 kernelSources : `lsst.afw.table.SourceCatalog`
779 Sources from the input catalog to use to construct the
782 kernelSize = self.makeKernel.makeKernelBasisList(
784 sources = self.makeKernel.makeCandidateList(template, science, kernelSize,
790 """Convolve the template image with a PSF-matching kernel and subtract
791 from the science image.
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
807 results : `lsst.pipe.base.Struct`
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.
818 self.metadata[
"convolvedExposure"] =
"Template"
822 bbox=science.getBBox(),
824 photoCalib=science.photoCalib)
826 difference =
_subtractImages(science, matchedTemplate, backgroundModel=backgroundModel)
827 correctedExposure = self.
finalize(template, science, difference,
829 templateMatched=
True)
831 return lsst.pipe.base.Struct(difference=correctedExposure,
832 matchedTemplate=matchedTemplate,
833 matchedScience=science,
834 backgroundModel=backgroundModel,
835 psfMatchingKernel=psfMatchingKernel)
838 """Convolve the science image with a PSF-matching kernel and subtract
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
855 results : `lsst.pipe.base.Struct`
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.
867 self.metadata[
"convolvedExposure"] =
"Science"
868 bbox = science.getBBox()
870 kernelImage = lsst.afw.image.ImageD(psfMatchingKernel.getDimensions())
871 xcen, ycen = bbox.getCenter()
872 norm = psfMatchingKernel.computeImage(kernelImage, doNormalize=
False, x=xcen, y=ycen)
879 matchedScience.maskedImage /= norm
880 matchedTemplate = template.clone()[bbox]
881 matchedTemplate.setPhotoCalib(science.photoCalib)
883 if backgroundModel
is not None:
885 invertedBackground = backgroundModel.clone()
886 invertedBackground.setParameters([-p
for p
in backgroundModel.getParameters()])
887 backgroundModel = invertedBackground
889 difference =
_subtractImages(matchedScience, matchedTemplate, backgroundModel=backgroundModel)
891 correctedExposure = self.
finalize(template, science, difference,
893 templateMatched=
False)
895 return lsst.pipe.base.Struct(difference=correctedExposure,
896 matchedTemplate=matchedTemplate,
897 matchedScience=matchedScience,
898 backgroundModel=backgroundModel,
899 psfMatchingKernel=psfMatchingKernel)
901 def finalize(self, template, science, difference, kernel,
902 templateMatched=True,
905 spatiallyVarying=False):
906 """Decorrelate the difference image to undo the noise correlations
907 caused by convolution.
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?
932 correctedExposure : `lsst.afw.image.ExposureF`
933 The decorrelated image difference.
935 if self.config.doDecorrelation:
936 self.
log.info(
"Decorrelating image difference.")
940 correctedExposure = self.decorrelate.
run(science, template[science.getBBox()], difference, kernel,
941 templateMatched=templateMatched,
942 preConvMode=preConvMode,
943 preConvKernel=preConvKernel,
944 spatiallyVarying=spatiallyVarying).correctedExposure
946 self.
log.info(
"NOT decorrelating image difference.")
947 correctedExposure = difference
948 return correctedExposure
951 """Calculate the point-source limiting magnitude of an exposure.
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.
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
970 The limiting AB magnitude, or `numpy.nan` if the exposure has no
971 photometric calibration, no usable pixels, or no PSF.
973 if exposure.photoCalib
is None:
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")
983 self.
log.info(
"Unable to evaluate PSF, using fallback FWHM %f", fallbackPsfSize)
985 psfArea = 4*np.pi*(fallbackPsfSize/np.sqrt(8*np.log(2)))**2
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:
992 fluxLim = nsigma*np.sqrt(np.median(variance)*psfArea)
993 return exposure.photoCalib.instFluxToMagnitude(fluxLim)
997 """Check that the WCS of the two Exposures match, the template bbox
998 contains the science bbox, and that the bands match.
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.
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.
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)
1022 assert templateBBox.contains(scienceBBox), \
1023 "Template bbox does not contain all of the science image."
1029 interpolateBadMaskPlanes=False,
1031 """Convolve an exposure with the given kernel.
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.
1053 convolvedExp : `lsst.afw.Exposure`
1054 The convolved image.
1056 convolvedExposure = exposure.clone()
1058 convolvedExposure.setPsf(psf)
1059 if photoCalib
is not None:
1060 convolvedExposure.setPhotoCalib(photoCalib)
1061 if interpolateBadMaskPlanes
and self.config.badMaskPlanes
is not None:
1063 self.config.badMaskPlanes)
1064 self.metadata[
"nInterpolated"] = nInterp
1068 preservePlanes = [mp
for mp
in self.config.preserveMaskPlanes
1069 if mp
in convolvedExposure.mask.getMaskPlaneDict()]
1071 mp: (convolvedExposure.mask.array
1072 & convolvedExposure.mask.getPlaneBitMask(mp)) > 0
1073 for mp
in preservePlanes
1076 convolvedImage = lsst.afw.image.MaskedImageF(convolvedExposure.getBBox())
1078 convolvedExposure.setMaskedImage(convolvedImage)
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
1089 return convolvedExposure
1091 return convolvedExposure[bbox]
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
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.
1115 kernelSources : `lsst.afw.table.SourceCatalog`
1116 The input source catalog, with flagged and low signal-to-noise
1117 sources removed and footprints added.
1121 InsufficientKernelSourcesError
1122 An AlgorithmError that is raised if there are not enough PSF
1123 candidates to construct the PSF matching kernel.
1126 selected = self.fallbackSourceSelector.selectSources(sources).selected
1128 selected = self.sourceSelector.selectSources(sources).selected
1133 selectSources = sources[selected].copy(deep=
True)
1135 kernelSources = setSourceFootprints(selectSources, kernelSize=kSize)
1136 bbox = science.getBBox()
1141 if self.config.restrictKernelEdgeSources:
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)
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)
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:
1171 nRequired=self.config.minKernelSources)
1173 self.metadata[
"nPsfSources"] = len(kernelSources)
1175 return kernelSources
1178 """Perform preparatory calculations common to all Alard&Lupton Tasks.
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
1194 if visitSummary
is not None:
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"
1202 self.metadata[
"templateCoveragePercent"] = 100*templateCoverageFraction
1204 if self.config.doScaleVariance:
1209 sciVarFactor = self.scaleVariance.
run(science.maskedImage)
1210 self.
log.info(
"Science variance scaling factor: %.2f", sciVarFactor)
1211 self.metadata[
"scaleScienceVarianceFactor"] = sciVarFactor
1237 self.
log.info(
"Unable to evaluate PSF at the average position. "
1238 "Evaluting PSF on a grid of points."
1242 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer,
1243 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid
1247 fwhmExposureBuffer=self.config.makeKernel.fwhmExposureBuffer,
1248 fwhmExposureGrid=self.config.makeKernel.fwhmExposureGrid
1257 if np.isnan(maglim_science):
1258 self.
log.warning(
"Limiting magnitude of the science image is NaN!")
1259 fluxlim_science = (maglim_science*u.ABmag).to_value(u.nJy)
1261 if np.isnan(maglim_template):
1262 self.
log.info(
"Cannot evaluate template limiting mag; adopting science limiting mag for diffim")
1263 maglim_diffim = maglim_science
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
1272 """Update the science and template mask planes before differencing.
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
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
1285 self.
_clearMask(science.mask, clearMaskPlanes=[
"DETECTED",
"DETECTED_NEGATIVE"])
1292 renameMaskPlanes = [mp
for mp
in self.config.renameTemplateMask
1293 if mp
in template.mask.getMaskPlaneDict().keys()]
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]
1305 if "FAKE" in science.mask.getMaskPlaneDict().keys():
1306 self.
log.info(
"Adding injected mask plane to science image")
1308 if "FAKE" in template.mask.getMaskPlaneDict().keys():
1309 self.
log.info(
"Adding injected mask plane to template image")
1311 if "INJECTED" in renameMaskPlanes:
1312 renameMaskPlanes.remove(
"INJECTED")
1313 if "INJECTED_TEMPLATE" in clearMaskPlanes:
1314 clearMaskPlanes.remove(
"INJECTED_TEMPLATE")
1316 for maskPlane
in renameMaskPlanes:
1318 self.
_clearMask(template.mask, clearMaskPlanes=clearMaskPlanes)
1322 """Rename a mask plane by adding the new name and copying the data.
1326 mask : `lsst.afw.image.Mask`
1327 The mask image to update in place.
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.
1334 mask.addMaskPlane(newMaskPlane)
1335 originBitMask = mask.getPlaneBitMask(maskPlane)
1336 destinationBitMask = mask.getPlaneBitMask(newMaskPlane)
1337 mask.array |= ((mask.array & originBitMask) > 0)*destinationBitMask
1340 """Clear the mask plane of an exposure.
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.
1350 if clearMaskPlanes
is None:
1351 clearMaskPlanes = list(mask.getMaskPlaneDict().keys())
1353 bitMaskToClear = mask.getPlaneBitMask(clearMaskPlanes)
1354 mask &= ~bitMaskToClear
1358 SubtractScoreOutputConnections):
1363 pipelineConnections=AlardLuptonPreconvolveSubtractConnections):
1368 """Subtract a template from a science image, convolving the science image
1369 before computing the kernel, and also convolving the template before
1372 ConfigClass = AlardLuptonPreconvolveSubtractConfig
1373 _DefaultName =
"alardLuptonPreconvolveSubtract"
1374 usePreconvolution =
True
1377 futureImageOutputs = (
"scoreExposure",)
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.
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
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
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.
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
1415 ``psfMatchingKernel`` : `lsst.afw.math.Kernel`
1416 Final kernel used to PSF-match the template to the science
1419 self.
_prepareInputs(template, science, visitSummary=visitSummary)
1423 interpolateBadMaskPlanes=
True)
1424 self.metadata[
"convolvedExposure"] =
"Preconvolution"
1428 self.metadata[
"preconvolvedSciencePsfSize"] = self.
matchedPsfSize
1430 kernelSources = self.
_sourceSelector(template, matchedScience, sources)
1431 subtractResults = self.
runPreconvolve(template, science, matchedScience,
1432 kernelSources, convolutionKernel)
1435 self.
log.warning(
"Failed to match template. Checking coverage")
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}"
1446 return subtractResults
1450 """Set the EDGE mask bit on pixels outside a known-valid region.
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.
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()
1468 mask.array[:dy0, :] |= edgeBit
1470 mask.array[-dy1:, :] |= edgeBit
1472 mask.array[:, :dx0] |= edgeBit
1474 mask.array[:, -dx1:] |= edgeBit
1478 """Build a normalized, reflected matched-filter kernel from a PSF.
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`.
1488 psf : `~lsst.afw.detection.Psf`
1489 The PSF to derive the preconvolution kernel from.
1493 kernel : `~lsst.afw.math.Kernel`
1494 The PSF reflected about both axes, normalized to sum to one.
1499 Raised if the PSF kernel has an even size along either axis.
1500 It's not possible to center an even-sized kernel.
1502 avgPos = psf.getAveragePosition()
1503 localKernel = psf.getLocalKernel(avgPos)
1504 dims = localKernel.getDimensions()
1505 if dims.x % 2 == 0
or dims.y % 2 == 0:
1507 f
"Preconvolution requires an odd-sized PSF kernel, got {dims.x}x{dims.y}. "
1509 kimg = lsst.afw.image.ImageD(dims)
1510 localKernel.computeImage(kimg, doNormalize=
True)
1513 kimg.array[...] = kimg.array[::-1, ::-1]
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
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
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.
1539 results : `lsst.pipe.base.Struct`
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
1553 ``psfMatchingKernel`` : `lsst.afw.math.Kernel`
1554 Final kernel used to PSF-match the template to the science
1557 bbox = science.getBBox()
1558 innerBBox = preConvKernel.shrinkBBox(bbox)
1560 kernelResult = self.makeKernel.
run(template[innerBBox], matchedScience[innerBBox], kernelSources,
1565 matchedTemplate = self.
_convolveExposure(template, kernelResult.psfMatchingKernel,
1569 interpolateBadMaskPlanes=
True,
1570 photoCalib=science.photoCalib)
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)
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)
1591 """Subtract template from science, propagating relevant metadata.
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
1604 difference : `lsst.afw.Exposure`
1605 The subtracted image.
1607 difference = science.clone()
1608 if backgroundModel
is not None:
1609 difference.maskedImage -= backgroundModel
1610 difference.maskedImage -= template.maskedImage
1615 """Determine that the PSF of ``exp1`` is not wider than that of ``exp2``.
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.
1633 True if ``exp1`` has a PSF that is not wider than that of ``exp2`` in
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
1644 shape2 = evaluateMeanPsfFwhm(exp2,
1645 fwhmExposureBuffer=fwhmExposureBuffer,
1646 fwhmExposureGrid=fwhmExposureGrid
1648 return shape1 <= shape2
1651 xTest = shape1[0] <= shape2[0]
1652 yTest = shape1[1] <= shape2[1]
1653 return xTest | yTest
1657 pipelineConnections=SimplifiedSubtractConnections):
1658 mode = lsst.pex.config.ChoiceField(
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."
1666 useExistingKernel = lsst.pex.config.Field(
1669 doc=
"Use a pre-existing PSF matching kernel?"
1670 "If False, source detection and measurement will be run."
1675 """Compute the image difference of a science and template image using
1676 the Alard & Lupton (1998) algorithm.
1678 ConfigClass = SimplifiedSubtractConfig
1679 _DefaultName =
"simplifiedSubtract"
1682 def run(self, template, science, visitSummary=None, inputPsfMatchingKernel=None):
1683 """PSF match, subtract, and decorrelate two images.
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
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.
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
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.
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
1721 self.
_prepareInputs(template, science, visitSummary=visitSummary)
1726 if self.config.useExistingKernel:
1727 psfMatchingKernel = inputPsfMatchingKernel
1728 backgroundModel =
None
1729 kernelSources =
None
1731 kernelResult = self.
runMakeKernel(template, science, convolveTemplate=convolveTemplate,
1732 runSourceDetection=
True)
1733 psfMatchingKernel = kernelResult.psfMatchingKernel
1734 kernelSources = kernelResult.kernelSources
1735 if self.config.doSubtractBackground:
1736 backgroundModel = kernelResult.backgroundModel
1738 backgroundModel =
None
1739 if convolveTemplate:
1741 backgroundModel=backgroundModel)
1744 backgroundModel=backgroundModel)
1745 if kernelSources
is not None:
1746 subtractResults.kernelSources = kernelSources
1747 return subtractResults
1751 """Replace masked image pixels with interpolated values.
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.
1765 The number of masked pixels that were replaced.
1767 imgBadMaskPlanes = [
1768 maskPlane
for maskPlane
in badMaskPlanes
if maskPlane
in maskedImage.mask.getMaskPlaneDict()
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:
1775 fallbackValue = np.nanmedian(image)
1778 image[badPixels] = fallbackValue
1779 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)
convert_outputs_to_future(self, results, exposureRecord, templateInfo=None, photometricScaling=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)
__init__(self, *, config=None)
__init__(self, *, config=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)
_shapeTest(exp1, exp2, fwhmExposureBuffer, fwhmExposureGrid)