LSST Applications g0b6bd0c080+a72a5dd7e6,g1182afd7b4+2a019aa3bb,g17e5ecfddb+2b8207f7de,g1d67935e3f+06cf436103,g38293774b4+ac198e9f13,g396055baef+6a2097e274,g3b44f30a73+6611e0205b,g480783c3b1+98f8679e14,g48ccf36440+89c08d0516,g4b93dc025c+98f8679e14,g5c4744a4d9+a302e8c7f0,g613e996a0d+e1c447f2e0,g6c8d09e9e7+25247a063c,g7271f0639c+98f8679e14,g7a9cd813b8+124095ede6,g9d27549199+a302e8c7f0,ga1cf026fa3+ac198e9f13,ga32aa97882+7403ac30ac,ga786bb30fb+7a139211af,gaa63f70f4e+9994eb9896,gabf319e997+ade567573c,gba47b54d5d+94dc90c3ea,gbec6a3398f+06cf436103,gc6308e37c7+07dd123edb,gc655b1545f+ade567573c,gcc9029db3c+ab229f5caf,gd01420fc67+06cf436103,gd877ba84e5+06cf436103,gdb4cecd868+6f279b5b48,ge2d134c3d5+cc4dbb2e3f,ge448b5faa6+86d1ceac1d,gecc7e12556+98f8679e14,gf3ee170dca+25247a063c,gf4ac96e456+ade567573c,gf9f5ea5b4d+ac198e9f13,gff490e6085+8c2580be5c,w.2022.27
LSST Data Management Base Package
interpImage.py
Go to the documentation of this file.
2# LSST Data Management System
3# Copyright 2008-2015 AURA/LSST.
4#
5# This product includes software developed by the
6# LSST Project (http://www.lsst.org/).
7#
8# This program is free software: you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation, either version 3 of the License, or
11# (at your option) any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the LSST License Statement and
19# the GNU General Public License along with this program. If not,
20# see <https://www.lsstcorp.org/LegalNotices/>.
21#
22from contextlib import contextmanager
23import lsst.pex.config as pexConfig
24import lsst.geom
25import lsst.afw.image as afwImage
26import lsst.afw.math as afwMath
27import lsst.ip.isr as ipIsr
28import lsst.meas.algorithms as measAlg
29import lsst.pipe.base as pipeBase
30from lsst.utils.timer import timeMethod
31
32__all__ = ["InterpImageConfig", "InterpImageTask"]
33
34
35class InterpImageConfig(pexConfig.Config):
36 """Config for InterpImageTask
37 """
38 modelPsf = measAlg.GaussianPsfFactory.makeField(doc="Model Psf factory")
39
40 useFallbackValueAtEdge = pexConfig.Field(
41 dtype=bool,
42 doc="Smoothly taper to the fallback value at the edge of the image?",
43 default=True,
44 )
45 fallbackValueType = pexConfig.ChoiceField(
46 dtype=str,
47 doc="Type of statistic to calculate edge fallbackValue for interpolation",
48 allowed={
49 "MEAN": "mean",
50 "MEDIAN": "median",
51 "MEANCLIP": "clipped mean",
52 "USER": "user value set in fallbackUserValue config",
53 },
54 default="MEDIAN",
55 )
56 fallbackUserValue = pexConfig.Field(
57 dtype=float,
58 doc="If fallbackValueType is 'USER' then use this as the fallbackValue; ignored otherwise",
59 default=0.0,
60 )
61 negativeFallbackAllowed = pexConfig.Field(
62 dtype=bool,
63 doc=("Allow negative values for egde interpolation fallbackValue? If False, set "
64 "fallbackValue to max(fallbackValue, 0.0)"),
65 default=False,
66 )
67 transpose = pexConfig.Field(dtype=int, default=False,
68 doc="Transpose image before interpolating? "
69 "This allows the interpolation to act over columns instead of rows.")
70
71 def validate(self):
72 pexConfig.Config.validate(self)
73 if self.useFallbackValueAtEdgeuseFallbackValueAtEdge:
74 if (not self.negativeFallbackAllowednegativeFallbackAllowed and self.fallbackValueTypefallbackValueType == "USER"
75 and self.fallbackUserValuefallbackUserValue < 0.0):
76 raise ValueError("User supplied fallbackValue is negative (%.2f) but "
77 "negativeFallbackAllowed is False" % self.fallbackUserValuefallbackUserValue)
78
79
80class InterpImageTask(pipeBase.Task):
81 """Interpolate over bad image pixels
82 """
83 ConfigClass = InterpImageConfig
84 _DefaultName = "interpImage"
85
86 def _setFallbackValue(self, mi=None):
87 """Set the edge fallbackValue for interpolation
88
89 @param[in] mi input maksedImage on which to calculate the statistics
90 Must be provided if fallbackValueType != "USER".
91
92 @return fallbackValue The value set/computed based on the fallbackValueType
93 and negativeFallbackAllowed config parameters
94 """
95 if self.config.fallbackValueType != 'USER':
96 assert mi, "No maskedImage provided"
97 if self.config.fallbackValueType == 'MEAN':
98 fallbackValue = afwMath.makeStatistics(mi, afwMath.MEAN).getValue()
99 elif self.config.fallbackValueType == 'MEDIAN':
100 fallbackValue = afwMath.makeStatistics(mi, afwMath.MEDIAN).getValue()
101 elif self.config.fallbackValueType == 'MEANCLIP':
102 fallbackValue = afwMath.makeStatistics(mi, afwMath.MEANCLIP).getValue()
103 elif self.config.fallbackValueType == 'USER':
104 fallbackValue = self.config.fallbackUserValue
105 else:
106 raise NotImplementedError("%s : %s not implemented" %
107 ("fallbackValueType", self.config.fallbackValueType))
108
109 if not self.config.negativeFallbackAllowed and fallbackValue < 0.0:
110 self.log.warning("Negative interpolation edge fallback value computed but "
111 "negativeFallbackAllowed is False: setting fallbackValue to 0.0")
112 fallbackValue = max(fallbackValue, 0.0)
113
114 self.log.info("fallbackValueType %s has been set to %.4f",
115 self.config.fallbackValueType, fallbackValue)
116
117 return fallbackValue
118
119 @timeMethod
120 def run(self, image, planeName=None, fwhmPixels=None, defects=None):
121 """!Interpolate in place over pixels in a maskedImage marked as bad
122
123 Pixels to be interpolated are set by either a mask planeName provided
124 by the caller OR a defects list of type `~lsst.meas.algorithms.Defects`
125 If both are provided an exception is raised.
126
127 Note that the interpolation code in meas_algorithms currently doesn't
128 use the input PSF (though it's a required argument), so it's not
129 important to set the input PSF parameters exactly. This PSF is set
130 here as the psf attached to the "image" (i.e if the image passed in
131 is an Exposure). Otherwise, a psf model is created using
132 measAlg.GaussianPsfFactory with the value of fwhmPixels (the value
133 passed in by the caller, or the default defaultFwhm set in
134 measAlg.GaussianPsfFactory if None).
135
136 @param[in,out] image MaskedImage OR Exposure to be interpolated
137 @param[in] planeName name of mask plane over which to interpolate
138 If None, must provide a defects list.
139 @param[in] fwhmPixels FWHM of core star (pixels)
140 If None the default is used, where the default
141 is set to the exposure psf if available
142 @param[in] defects List of defects of type ipIsr.Defects
143 over which to interpolate.
144 """
145 try:
146 maskedImage = image.getMaskedImage()
147 except AttributeError:
148 maskedImage = image
149
150 # set defectList from defects OR mask planeName provided
151 if planeName is None:
152 if defects is None:
153 raise ValueError("No defects or plane name provided")
154 else:
155 if not isinstance(defects, ipIsr.Defects):
156 defectList = ipIsr.Defects(defects)
157 else:
158 defectList = defects
159 planeName = "defects"
160 else:
161 if defects is not None:
162 raise ValueError("Provide EITHER a planeName OR a list of defects, not both")
163 if planeName not in maskedImage.getMask().getMaskPlaneDict():
164 raise ValueError("maskedImage does not contain mask plane %s" % planeName)
165 defectList = ipIsr.Defects.fromMask(maskedImage, planeName)
166
167 # set psf from exposure if provided OR using modelPsf with fwhmPixels provided
168 try:
169 psf = image.getPsf()
170 self.log.info("Setting psf for interpolation from image")
171 except AttributeError:
172 self.log.info("Creating psf model for interpolation from fwhm(pixels) = %s",
173 str(fwhmPixels) if fwhmPixels is not None else
174 (str(self.config.modelPsf.defaultFwhm)) + " [default]")
175 psf = self.config.modelPsf.apply(fwhm=fwhmPixels)
176
177 fallbackValue = 0.0 # interpolateOverDefects needs this to be a float, regardless if it is used
178 if self.config.useFallbackValueAtEdge:
179 fallbackValue = self._setFallbackValue_setFallbackValue(maskedImage)
180
181 self.interpolateImageinterpolateImage(maskedImage, psf, defectList, fallbackValue)
182
183 self.log.info("Interpolated over %d %s pixels.", len(defectList), planeName)
184
185 @contextmanager
186 def transposeContext(self, maskedImage, defects):
187 """Context manager to potentially transpose an image
188
189 This applies the ``transpose`` configuration setting.
190
191 Transposing the image allows us to interpolate along columns instead
192 of rows, which is useful when the saturation trails are typically
193 oriented along rows on the warped/coadded images, instead of along
194 columns as they typically are in raw CCD images.
195
196 Parameters
197 ----------
198 maskedImage : `lsst.afw.image.MaskedImage`
199 Image on which to perform interpolation.
200 defects : `lsst.meas.algorithms.Defects`
201 List of defects to interpolate over.
202
203 Yields
204 ------
205 useImage : `lsst.afw.image.MaskedImage`
206 Image to use for interpolation; it may have been transposed.
207 useDefects : `lsst.meas.algorithms.Defects`
208 List of defects to use for interpolation; they may have been
209 transposed.
210 """
211 def transposeImage(image):
212 """Transpose an image"""
213 transposed = image.array.T.copy() # Copy to force row-major; required for ndarray+pybind
214 return image.Factory(transposed, False, lsst.geom.Point2I(*reversed(image.getXY0())))
215
216 useImage = maskedImage
217 useDefects = defects
218 if self.config.transpose:
219 useImage = afwImage.makeMaskedImage(transposeImage(maskedImage.image),
220 transposeImage(maskedImage.mask),
221 transposeImage(maskedImage.variance))
222 useDefects = defects.transpose()
223 yield useImage, useDefects
224 if self.config.transpose:
225 maskedImage.image.array = useImage.image.array.T
226 maskedImage.mask.array = useImage.mask.array.T
227 maskedImage.variance.array = useImage.variance.array.T
228
229 def interpolateImage(self, maskedImage, psf, defectList, fallbackValue):
230 """Interpolate over defects in an image
231
232 Parameters
233 ----------
234 maskedImage : `lsst.afw.image.MaskedImage`
235 Image on which to perform interpolation.
237 Point-spread function; currently unused.
238 defectList : `lsst.meas.algorithms.Defects`
239 List of defects to interpolate over.
240 fallbackValue : `float`
241 Value to set when interpolation fails.
242 """
243 if not defectList:
244 return
245 with self.transposeContexttransposeContext(maskedImage, defectList) as (image, defects):
246 measAlg.interpolateOverDefects(image, psf, defects, fallbackValue,
247 self.config.useFallbackValueAtEdge)
int max
A polymorphic base class for representing an image's Point Spread Function.
Definition: Psf.h:76
A class to manipulate images, masks, and variance as a single object.
Definition: MaskedImage.h:73
def interpolateImage(self, maskedImage, psf, defectList, fallbackValue)
Definition: interpImage.py:229
def run(self, image, planeName=None, fwhmPixels=None, defects=None)
Interpolate in place over pixels in a maskedImage marked as bad.
Definition: interpImage.py:120
def transposeContext(self, maskedImage, defects)
Definition: interpImage.py:186
Backwards-compatibility support for depersisting the old Calib (FluxMag0/FluxMag0Err) objects.
MaskedImage< ImagePixelT, MaskPixelT, VariancePixelT > * makeMaskedImage(typename std::shared_ptr< Image< ImagePixelT > > image, typename std::shared_ptr< Mask< MaskPixelT > > mask=Mask< MaskPixelT >(), typename std::shared_ptr< Image< VariancePixelT > > variance=Image< VariancePixelT >())
A function to return a MaskedImage of the correct type (cf.
Definition: MaskedImage.h:1240
Statistics makeStatistics(lsst::afw::image::Image< Pixel > const &img, lsst::afw::image::Mask< image::MaskPixel > const &msk, int const flags, StatisticsControl const &sctrl=StatisticsControl())
Handle a watered-down front-end to the constructor (no variance)
Definition: Statistics.h:359
Fit spatial kernel using approximate fluxes for candidates, and solving a linear system of equations.