22from contextlib
import contextmanager
27from .
import SubtractBackgroundTask
29__all__ = [
"ScaleVarianceConfig",
"ScaleVarianceTask",
"ExceedsMaxVarianceScaleError"]
33 """Raised if ScaleVariance exceeds a specified threshold.
38 Maximum variance scaling.
40 def __init__(self, scaleVarianceValue, scaleVarianceLimit, **kwargs):
41 msg = (f
"Variance rescaling factor ({scaleVarianceValue}) exceeds configured limit "
42 f
"({scaleVarianceLimit})")
47 self.
_metadata[
"scaleVarianceValue"] = scaleVarianceValue
48 self.
_metadata[
"scaleVarianceLimit"] = scaleVarianceLimit
52 return f
"{self.msg}: {self.metadata}"
57 if not (isinstance(value, int)
or isinstance(value, float)
or isinstance(value, str)):
58 raise TypeError(f
"{key} is of type {type(value)}, but only (int, float, str) are allowed.")
63 background = ConfigurableField(target=SubtractBackgroundTask, doc=
"Background subtraction")
64 maskPlanes = ListField[str](
65 default=[
"DETECTED",
"DETECTED_NEGATIVE",
"BAD",
"SAT",
"NO_DATA",
"INTRP"],
66 doc=
"Mask planes for pixels to ignore when scaling variance",
68 limit = Field[float](default=10.0, doc=
"Maximum variance scaling value to permit")
73 self.
background.undersampleStyle =
"REDUCE_INTERP_ORDER"
74 self.
background.ignoredPixelMask = [
"DETECTED",
"DETECTED_NEGATIVE",
"BAD",
"SAT",
"NO_DATA",
"INTRP"]
78 """Scale the variance in a MaskedImage
80 The variance plane in a convolved or warped image (or a coadd derived
81 from warped images) does not accurately reflect the noise properties of
82 the image because variance has been lost to covariance. This Task
83 attempts to correct for this by scaling the variance plane to match
84 the observed variance in the image. This is not perfect (because we're
85 not tracking the covariance) but it's simple and is often good enough.
87 The task implements a pixel-based and an image-based correction estimator.
89 ConfigClass = ScaleVarianceConfig
90 _DefaultName =
"scaleVariance"
93 Task.__init__(self, *args, **kwargs)
94 self.makeSubtask(
"background")
98 """Context manager for subtracting the background
100 We need to subtract the background so that the entire image
101 (apart from objects, which should be clipped) will have the
102 image/sqrt(variance) distributed about zero.
104 This context manager subtracts the background, and ensures it
109 maskedImage : `lsst.afw.image.MaskedImage`
110 Image+mask+variance to have background subtracted and restored.
114 context : context manager
115 Context manager that ensure the background is restored.
117 bg = self.background.fitBackground(maskedImage)
118 bgImage = bg.getImageF(self.background.config.algorithm, self.background.config.undersampleStyle)
119 maskedImage -= bgImage
123 maskedImage += bgImage
125 def run(self, maskedImage):
126 """Rescale the variance in a maskedImage in place.
130 maskedImage : `lsst.afw.image.MaskedImage`
131 Image for which to determine the variance rescaling factor. The image
132 is modified in place.
137 Variance rescaling factor.
141 ExceedsMaxVarianceScaleError
142 If the estimated variance rescaling factor by both methods exceed the
147 The task calculates and applies the pixel-based correction unless
148 it is over the ``config.limit`` threshold. In this case, the image-based
153 if factor > self.config.limit:
154 self.log.warning(
"Pixel-based variance rescaling factor (%f) exceeds configured limit (%f); "
155 "trying image-based method", factor, self.config.limit)
157 if factor > self.config.limit:
159 self.log.info(
"Renormalizing variance by %f", factor)
160 maskedImage.variance *= factor
164 """Calculate and return both variance scaling factors without modifying the image.
168 maskedImage : `lsst.afw.image.MaskedImage`
169 Image for which to determine the variance rescaling factor.
173 R : `lsst.pipe.base.Struct`
174 - ``pixelFactor`` : `float` The pixel based variance rescaling factor
175 or 1 if all pixels are masked or invalid.
176 - ``imageFactor`` : `float` The image based variance rescaling factor
177 or 1 if all pixels are masked or invalid.
182 return Struct(pixelFactor=pixelFactor, imageFactor=imageFactor)
185 """Determine the variance rescaling factor from pixel statistics
187 We calculate SNR = image/sqrt(variance), and the distribution
188 for most of the background-subtracted image should have a standard
189 deviation of unity. We use the interquartile range as a robust estimator
190 of the SNR standard deviation. The variance rescaling factor is the
191 factor that brings that distribution to have unit standard deviation.
193 This may not work well if the image has a lot of structure in it, as
194 the assumptions are violated. In that case, use an alternate
199 maskedImage : `lsst.afw.image.MaskedImage`
200 Image for which to determine the variance rescaling factor.
205 Variance rescaling factor or 1 if all pixels are masked or non-finite.
208 maskVal = maskedImage.mask.getPlaneBitMask(self.config.maskPlanes)
209 isGood = (((maskedImage.mask.array & maskVal) == 0)
210 & np.isfinite(maskedImage.image.array)
211 & np.isfinite(maskedImage.variance.array)
212 & (maskedImage.variance.array > 0))
214 nGood = np.sum(isGood)
215 self.log.debug(
"Number of selected background pixels: %d of %d.", nGood, isGood.size)
221 snr = maskedImage.image.array[isGood]/np.sqrt(maskedImage.variance.array[isGood])
222 q1, q3 = np.percentile(snr, (25, 75))
223 stdev = 0.74*(q3 - q1)
227 """Determine the variance rescaling factor from image statistics
229 We calculate average(SNR) = stdev(image)/median(variance), and
230 the value should be unity. We use the interquartile range as a robust
231 estimator of the stdev. The variance rescaling factor is the
232 factor that brings this value to unity.
234 This may not work well if the pixels from which we measure the
235 standard deviation of the image are not effectively the same pixels
236 from which we measure the median of the variance. In that case, use
241 maskedImage : `lsst.afw.image.MaskedImage`
242 Image for which to determine the variance rescaling factor.
247 Variance rescaling factor or 1 if all pixels are masked or non-finite.
249 maskVal = maskedImage.mask.getPlaneBitMask(self.config.maskPlanes)
250 isGood = (((maskedImage.mask.array & maskVal) == 0)
251 & np.isfinite(maskedImage.image.array)
252 & np.isfinite(maskedImage.variance.array)
253 & (maskedImage.variance.array > 0))
254 nGood = np.sum(isGood)
255 self.log.debug(
"Number of selected background pixels: %d of %d.", nGood, isGood.size)
261 q1, q3 = np.percentile(maskedImage.image.array[isGood], (25, 75))
262 ratio = 0.74*(q3 - q1)/np.sqrt(np.median(maskedImage.variance.array[isGood]))
__init__(self, scaleVarianceValue, scaleVarianceLimit, **kwargs)
imageBased(self, maskedImage)
computeScaleFactors(self, maskedImage)
subtractedBackground(self, maskedImage)
__init__(self, *args, **kwargs)
pixelBased(self, maskedImage)