Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions python/lsst/ip/diffim/detectAndMeasure.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,9 +511,11 @@ def setDefaults(self):

# Keep track of which footprints contain streaks
self.measurement.plugins["base_PixelFlags"].masksFpAnywhere = [
"STREAK", "INJECTED", "INJECTED_TEMPLATE", "HIGH_VARIANCE", "SAT_TEMPLATE", "SPIKE"]
"STREAK", "INJECTED", "INJECTED_TEMPLATE", "HIGH_VARIANCE", "SAT_TEMPLATE", "SPIKE",
"REJECTED_TEMPLATE"]
self.measurement.plugins["base_PixelFlags"].masksFpCenter = [
"STREAK", "INJECTED", "INJECTED_TEMPLATE", "HIGH_VARIANCE", "SAT_TEMPLATE", "SPIKE"]
"STREAK", "INJECTED", "INJECTED_TEMPLATE", "HIGH_VARIANCE", "SAT_TEMPLATE", "SPIKE",
"REJECTED_TEMPLATE"]
self.skySources.avoidMask = ["DETECTED", "DETECTED_NEGATIVE", "BAD", "NO_DATA", "EDGE"]

def validate(self):
Expand Down
275 changes: 273 additions & 2 deletions python/lsst/ip/diffim/getTemplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,12 @@
checkTemplateIsSufficient,
evaluateMeanPsfFwhm,
getPsfFwhm,
psfShapeDeviation,
record_from_obs_info,
sampleCoaddPsfMoments,
)
from lsst.meas.algorithms import CoaddPsf, CoaddPsfConfig, SubtractBackgroundTask, ScaleVarianceTask
from lsst.meas.algorithms import (CoaddPsf, CoaddPsfConfig, ScaleVarianceTask, SourceDetectionTask,
SubtractBackgroundTask)
from lsst.utils.timer import timeMethod

__all__ = [
Expand Down Expand Up @@ -402,6 +405,56 @@ class GetTemplateConfig(
" plane from the output instead."
" Only used with output_image_type='future'.",
)
doMaskPsfDiscontinuities = pexConfig.Field(
dtype=bool,
default=True,
doc="Check the template PSF for discontinuities that the PSF-matching"
" kernel can't fit, and mask DETECTED regions in those locations?"
" These regions will have the mask REJECTED_TEMPLATE set, which will"
" prevent sources landing in them from being used to compute the"
" matching kernel and allows affected diaSources to be filtered."
" A simplified form of source detection is run to set the mask plane.",
)
detection = pexConfig.ConfigurableField(
target=SourceDetectionTask,
doc="Detect sources on the template to set its DETECTED mask plane."
" Only used if doMaskPsfDiscontinuities is set.",
)
psfDiscontinuityGridStep = pexConfig.RangeField(
dtype=int,
default=300,
min=1,
doc="Spacing in pixels to sample the template PSF, to build the"
" spatial model.",
)
psfDiscontinuityPeakRadius = pexConfig.RangeField(
dtype=float,
default=2.0,
min=0.0,
inclusiveMin=False,
doc="Radius around each detected peak of the template, in units of"
" the template PSF FWHM, that has REJECTED_TEMPLATE set if the PSF at"
" the peak can't be fit by the spatial model. Only the pixels of the"
" peak's footprint are set.",
)
psfDiscontinuityPolyOrder = pexConfig.RangeField(
dtype=int,
default=1,
min=0,
doc="Total order of the 2D polynomial fit to each second moment of the"
" template PSF across the template, excluding outliers. Should match"
" the spatialKernelOrder of the downstream AL PSF matching task"
" (1 by default), so that the fit follows the PSF variation that"
" PSF matching can absorb.",
)
psfDiscontinuityMaxDeviation = pexConfig.RangeField(
dtype=float,
default=0.05,
min=0.0,
inclusiveMin=False,
doc="Largest fractional difference in PSF width allowed between the"
" template PSF at a detected peak and the spatial fit.",
)

def setDefaults(self):
# Use a smaller cache: per SeparableKernel.computeCache, this should
Expand All @@ -427,6 +480,15 @@ def setDefaults(self):
"NO_DATA",
]

# Configure a simplified source detection task for the PSF
# discontinuity check.
self.detection.thresholdPolarity = "positive"
self.detection.reEstimateBackground = False
self.detection.doTempLocalBackground = False
# Mask only a narrow region around significant sources.
self.detection.thresholdValue = 10.0
self.detection.nSigmaToGrow = 1.0


class GetTemplateTask(pipeBase.PipelineTask):
ConfigClass = GetTemplateConfig
Expand Down Expand Up @@ -458,6 +520,8 @@ def __init__(self, *args, **kwargs):
doc="Instrument whose observations were coadded to make the template, or UNKNOWN.",
)
self.makeSubtask("varianceBackground")
if self.config.doMaskPsfDiscontinuities:
self.makeSubtask("detection")

def runQuantum(self, butlerQC, inputRefs, outputRefs):
inputs = butlerQC.get(inputRefs)
Expand Down Expand Up @@ -856,7 +920,8 @@ def run(self, *, coaddExposureHandles, bbox, wcs, dataIds, physical_filter, visi
template.maskedImage = photoCalib.calibrateImage(template.maskedImage)
photoCalib = identity
template.setPhotoCalib(photoCalib)
template.setPsf(self._makePsf(template, catalog, wcs))
coaddPsf = self._makePsf(template, catalog, wcs)
template.setPsf(coaddPsf)
try:
template.setPsf(self._makeGaussianPsf(template))
except afwDetection.InvalidPsfError as e:
Expand All @@ -871,6 +936,12 @@ def run(self, *, coaddExposureHandles, bbox, wcs, dataIds, physical_filter, visi
# the original exception.
raise

# Check the template for regions likely to generate false diaSource
# detections, based on the PSF.
if self.config.doMaskPsfDiscontinuities:
footprints = self.detectSources(template)
self.maskPsfDiscontinuities(template, coaddPsf, footprints)

# Record the input coadd patches as the template's coadd inputs.
coaddInputs = afwImage.CoaddInputs(afwTable.ExposureTable.makeMinimalSchema(), self.schema)
coaddInputs.ccds.extend(catalog, deep=True)
Expand Down Expand Up @@ -1055,6 +1126,206 @@ def checkHighVariance(self, template):
highVariancePix = varianceBackground > threshold
template.mask.array[highVariancePix] |= 2**highVarianceMaskPlaneBit

def detectSources(self, template):
"""Clear any existing detection mask planes and re-run source
detection.

Note that only footprints are detected and masked here; sources are not
measured.

Parameters
----------
template : `lsst.afw.image.Exposure`
Template whose mask is modified in place. Its PSF sets the
detection smoothing.

Returns
-------
footprints : `list` [`lsst.afw.detection.Footprint`]
Footprints of the detected sources, with their peaks. Together
they cover the DETECTED pixels of the template.
"""
mask = template.mask
# Pixels that no input covers have zero image and variance. Detection
# would find every one of them significant and a peak, so give them a
# typical variance while detecting.
variance = template.variance.array
noData = ~(variance > 0)
if noData.all():
mask.array &= ~mask.getPlaneBitMask(["DETECTED", "DETECTED_NEGATIVE"])
self.metadata["nTemplateDetections"] = 0
return []
saved = variance[noData]
if noData.any():
variance[noData] = np.median(variance[~noData])
try:
result = self.detection.detectFootprints(template, clearMask=True)
finally:
variance[noData] = saved
# Clear the EDGE mask plane that was set by detection.
mask.array &= ~mask.getPlaneBitMask("EDGE")
self.metadata["nTemplateDetections"] = result.numPos
return list(result.positive.getFootprints())

def maskPsfDiscontinuities(self, template, psf, footprints):
"""Mask the sources where the template PSF differs from a smooth model
of the PSF.

PSF matching fits a matching kernel that varies across the image as a
polynomial of order ``config.psfDiscontinuityPolyOrder``. In regions
where the template PSF changes discontinuously the PSF matching
kernel may not be able to fit the change and the image subtraction
quality may be poor. Check the PSF at each detected peak of the
template to see whether it is well fit by the overall spatial model,
and mask the pixels around any peak that fails as REJECTED_TEMPLATE.
Only check sources, since empty regions of the template will not cause
subtraction artifacts and a transient can still be safely detected.

Parameters
----------
template : `lsst.afw.image.Exposure`
Template whose mask is modified in place. Its PSF FWHM sets the
radius masked around each peak.
psf : `lsst.meas.algorithms.CoaddPsf`
PSF of the template, built from its inputs. Its coadd WCS is the
template WCS.
footprints : `list` [`lsst.afw.detection.Footprint`]
Footprints of the sources detected on the template, with their
peaks.
"""
bbox = template.getBBox()
coaddWcs = psf.getCoaddWcs()
order = self.config.psfDiscontinuityPolyOrder
maxDeviation = self.config.psfDiscontinuityMaxDeviation

def measureLocalPsfMoments(x, y):
"""Return the (N, 3) PSF moments ixx, iyy, ixy at the given
positions.
"""
ra, dec = coaddWcs.pixelToSkyArray(x, y)
return np.stack(sampleCoaddPsfMoments(psf, ra, dec, coaddWcs), axis=-1)

def extractPolynomialTermsFromModel(x, y):
"""Return the (N, nCoeffs) polynomial terms of the spatial model
at the given positions.
"""
# Coordinates scaled to [-1, 1] for a well-conditioned fit.
xn = 2*(x - bbox.minX)/bbox.width - 1
yn = 2*(y - bbox.minY)/bbox.height - 1
return np.stack([xn**p*yn**q for p in range(order + 1) for q in range(order + 1 - p)], axis=-1)

def deviationFromFit(x, y, moments, coeffs):
"""Return the fractional shape deviation of the PSF moments from the
spatial model at the given positions.
"""
fit = extractPolynomialTermsFromModel(x, y) @ coeffs
# A fit that is not a valid PSF shape cannot match the PSF there.
deviation = np.full(len(x), np.inf)
valid = (fit[:, 0] > 0) & (fit[:, 0]*fit[:, 1] > fit[:, 2]**2)
deviation[valid] = psfShapeDeviation(moments[valid], fit[valid])
return deviation

# Fit the smooth model to the PSF at the center of each block.
step = self.config.psfDiscontinuityGridStep
xc = np.minimum(bbox.minX + step*(np.arange(-(-bbox.width//step)) + 0.5), bbox.maxX)
yc = np.minimum(bbox.minY + step*(np.arange(-(-bbox.height//step)) + 0.5), bbox.maxY)
xb, yb = (grid.ravel() for grid in np.meshgrid(xc, yc))
blockMoments = measureLocalPsfMoments(xb, yb)
good = np.isfinite(blockMoments[:, 0])
nCoeffs = (order + 1)*(order + 2)//2
# Blocks that no input covers have no PSF, so only the covered blocks
# count toward the minimums.
minBlocks = 3*nCoeffs
self.metadata["psfDiscontinuityCheckSkipped"] = bool(good.sum() < minBlocks)
if good.sum() < minBlocks:
self.log.info("Not masking template PSF discontinuities: only %d of %d blocks have a PSF"
" (need at least %d).", good.sum(), good.size, minBlocks)
return
xb = xb[good]
yb = yb[good]
blockMoments = blockMoments[good]
terms = extractPolynomialTermsFromModel(xb, yb)
minGood = max(2*nCoeffs, len(blockMoments)//2)

def refit(inliers):
"""Iteratively refit the spatial model, dropping outliers until the
model stops changing, from a starting set of blocks.
"""
# This is fast, but cap at a reasonable number of iterations.
for _ in range(10):
coeffs, *_ = np.linalg.lstsq(terms[inliers], blockMoments[inliers], rcond=None)
modelDeviation = deviationFromFit(xb, yb, blockMoments, coeffs)
newInliers = modelDeviation <= maxDeviation
if np.array_equal(newInliers, inliers) or newInliers.sum() < minGood:
break
inliers = newInliers
return coeffs, modelDeviation, inliers

# First fit starting from all the usable blocks.
coeffs, modelDeviation, inliers = refit(np.ones(len(blockMoments), dtype=bool))

# If the PSF has significant discontinuities, a large region with an
# outlier PSF shape may pull the fit towards it. Refit using the median
# PSF shape as the starting point, but only use it if it results in
# more of the image being usable.
median = np.median(blockMoments, axis=0)
medianIxx, medianIyy, medianIxy = median
# First check that the PSF second moments are positve definite,
# otherwise the fit will fail.
if medianIxx > 0 and medianIxx*medianIyy > medianIxy**2:
medianMoments = np.tile(median, (len(blockMoments), 1))
nearMedian = psfShapeDeviation(blockMoments, medianMoments) <= maxDeviation
if nearMedian.sum() >= minGood:
medianCoeffs, medianDeviation, medianInliers = refit(nearMedian)
# Keep the median fit only if more blocks agree with it.
if (np.count_nonzero(medianDeviation <= maxDeviation)
> np.count_nonzero(modelDeviation <= maxDeviation)):
coeffs, modelDeviation, inliers = medianCoeffs, medianDeviation, medianInliers

# Compare the PSF at each detected peak to the model.
peaks = [(peak.getFx(), peak.getFy(), i) for i, footprint in enumerate(footprints)
for peak in footprint.getPeaks()]
peakX, peakY, owner = (np.array(column) for column in zip(*peaks)) if peaks else (np.zeros(0),)*3
rejected = np.zeros(len(peakX), dtype=bool)
deviation = np.zeros(0)
if len(peakX) > 0:
moments = measureLocalPsfMoments(peakX, peakY)
# Peaks that no input covers have no PSF to compare.
covered = np.isfinite(moments[:, 0])
deviation = deviationFromFit(peakX[covered], peakY[covered], moments[covered], coeffs)
rejected[covered] = deviation > maxDeviation

# Mask the pixels of each footprint that are within the radius of any
# of its rejected peaks. Only the part of the footprint in a box
# around each peak is read, so that memory does not grow with the
# size of the footprint.
mask = template.mask
mask.addMaskPlane("REJECTED_TEMPLATE")
rejectedBit = mask.getPlaneBitMask("REJECTED_TEMPLATE")
fwhm = template.psf.computeShape(bbox.getCenter()).getDeterminantRadius()*gaussian_sigma_to_fwhm
radius = self.config.psfDiscontinuityPeakRadius*fwhm
nMasked = 0
for k in np.flatnonzero(rejected):
box = geom.Box2I(geom.Point2I(int(np.floor(peakX[k] - radius)), int(np.floor(peakY[k] - radius))),
geom.Point2I(int(np.ceil(peakX[k] + radius)), int(np.ceil(peakY[k] + radius))))
ys, xs = footprints[owner[k]].spans.clippedTo(box).indices()
hit = np.hypot(xs - peakX[k], ys - peakY[k]) <= radius
ys, xs = ys[hit] - bbox.minY, xs[hit] - bbox.minX
# Count each pixel once where the disks of two peaks overlap.
nMasked += int(np.count_nonzero((mask.array[ys, xs] & rejectedBit) == 0))
mask.array[ys, xs] |= rejectedBit

maxFound = float(deviation.max()) if deviation.size > 0 else 0.0
self.metadata["WorstSurvivingSpatialModelFit"] = float(modelDeviation[inliers].max())
self.metadata["WorstPeakSpatialModelFit"] = maxFound
self.metadata["nCheckedPeaks"] = len(peakX)
self.metadata["nRejectedPeaks"] = int(rejected.sum())
self.metadata["nRejectedMaskedPixels"] = nMasked
self.log.info("The PSF at %d detected peaks of the template differs from its polynomial fit by up"
" to %.1f%% in width; %d pixels around the %d that differ by more than %.1f%% were"
" set REJECTED_TEMPLATE.", len(peakX), 100*maxFound, nMasked, rejected.sum(),
100*maxDeviation)

@staticmethod
def _checkInputs(dataIds, coaddExposures, scienceInstrument=None):
"""Check that the all the dataIds are from the same band and that
Expand Down
7 changes: 4 additions & 3 deletions python/lsst/ip/diffim/subtractImages.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ class AlardLuptonSubtractBaseConfig(lsst.pex.config.Config):
)
excludeMaskPlanes = lsst.pex.config.ListField(
dtype=str,
default=("NO_DATA", "BAD", "SAT", "EDGE", "FAKE", "HIGH_VARIANCE"),
default=("NO_DATA", "BAD", "SAT", "EDGE", "FAKE", "HIGH_VARIANCE", "REJECTED_TEMPLATE"),
doc="Template mask planes to exclude when selecting sources for PSF matching.",
)
badMaskPlanes = lsst.pex.config.ListField(
Expand All @@ -314,7 +314,7 @@ class AlardLuptonSubtractBaseConfig(lsst.pex.config.Config):
)
preserveTemplateMask = lsst.pex.config.ListField(
dtype=str,
default=("NO_DATA", "BAD", "HIGH_VARIANCE"),
default=("NO_DATA", "BAD", "HIGH_VARIANCE", "REJECTED_TEMPLATE"),
doc="Mask planes from the template to propagate to the image difference."
)
renameTemplateMask = lsst.pex.config.ListField(
Expand All @@ -325,7 +325,8 @@ class AlardLuptonSubtractBaseConfig(lsst.pex.config.Config):
)
preserveMaskPlanes = lsst.pex.config.ListField(
dtype=str,
default=("INJECTED", "INJECTED_CORE", "INJECTED_TEMPLATE", "INJECTED_CORE_TEMPLATE"),
default=("INJECTED", "INJECTED_CORE", "INJECTED_TEMPLATE", "INJECTED_CORE_TEMPLATE",
"REJECTED_TEMPLATE"),
doc="Mask planes to preserve without dilation when convolving the image.",
)
allowKernelSourceDetection = lsst.pex.config.Field(
Expand Down
Loading
Loading