lsst.meas.algorithms g9e410d2b8e+8270314bb8
Loading...
Searching...
No Matches
subtractBackground.py
Go to the documentation of this file.
2# LSST Data Management System
3#
4# Copyright 2008-2017 AURA/LSST.
5#
6# This product includes software developed by the
7# LSST Project (http://www.lsst.org/).
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the LSST License Statement and
20# the GNU General Public License along with this program. If not,
21# see <https://www.lsstcorp.org/LegalNotices/>.
22#
23__all__ = ("SubtractBackgroundConfig", "SubtractBackgroundTask", "backgroundFlatContext")
24
25import itertools
26
27from contextlib import contextmanager
28import numpy
29from scipy.ndimage import median_filter
30
31from lsstDebug import getDebugFrame
32from lsst.utils import suppress_deprecations
33
34import lsst.afw.display as afwDisplay
35import lsst.afw.image as afwImage
36import lsst.afw.math as afwMath
37import lsst.pex.config as pexConfig
38import lsst.pipe.base as pipeBase
39
40
41@contextmanager
42def backgroundFlatContext(maskedImage, doApply, backgroundToPhotometricRatio=None):
43 """Context manager to convert from photometric-flattened to background-
44 flattened image.
45
46 Parameters
47 ----------
48 maskedImage : `lsst.afw.image.MaskedImage`
49 Masked image (image + mask + variance) to convert from a
50 photometrically flat image to an image suitable for background
51 subtraction.
52 doApply : `bool`
53 Apply the conversion? If False, this context manager will not
54 do anything.
55 backgroundToPhotometricRatio : `lsst.afw.image.Image`, optional
56 Image to multiply a photometrically-flattened image by to obtain a
57 background-flattened image.
58 Only used if ``doApply`` is ``True``.
59
60 Yields
61 ------
62 maskedImage : `lsst.afw.image.MaskedImage`
63 Masked image converted into an image suitable for background
64 subtraction.
65
66 Raises
67 ------
68 RuntimeError if doApply is True and no ratio is supplied.
69 ValueError if the ratio is not an `lsst.afw.image.Image`.
70 """
71 if doApply:
72 if backgroundToPhotometricRatio is None:
73 raise RuntimeError("backgroundFlatContext called with doApply=True, "
74 "but without a backgroundToPhotometricRatio")
75 if not isinstance(backgroundToPhotometricRatio, afwImage.Image):
76 raise ValueError("The backgroundToPhotometricRatio must be an lsst.afw.image.Image")
77
78 maskedImage *= backgroundToPhotometricRatio
79
80 try:
81 yield maskedImage
82 finally:
83 if doApply:
84 maskedImage /= backgroundToPhotometricRatio
85
86
87class TooManyMaskedPixelsError(pipeBase.AlgorithmError):
88 """Raised when all pixels in the image are masked and no background
89 can be estimated.
90 """
91 def metadata(self) -> dict:
92 """There is no metadata associated with this error.
93 """
94 return {}
95
96
97class SubtractBackgroundConfig(pexConfig.Config):
98 """Config for SubtractBackgroundTask
99
100 Many of these fields match fields in `lsst.afw.math.BackgroundControl`,
101 the control class for `lsst.afw.math.makeBackground`
102 """
103 statisticsProperty = pexConfig.ChoiceField(
104 doc="type of statistic to use for grid points",
105 dtype=str, default="MEANCLIP",
106 allowed={
107 "MEANCLIP": "clipped mean",
108 "MEAN": "unclipped mean",
109 "MEDIAN": "median",
110 }
111 )
112 undersampleStyle = pexConfig.ChoiceField(
113 doc="behaviour if there are too few points in grid for requested interpolation style",
114 dtype=str, default="REDUCE_INTERP_ORDER",
115 allowed={
116 "THROW_EXCEPTION": "throw an exception if there are too few points",
117 "REDUCE_INTERP_ORDER": "use an interpolation style with a lower order.",
118 "INCREASE_NXNYSAMPLE": "Increase the number of samples used to make the interpolation grid.",
119 },
120 )
121 binSize = pexConfig.RangeField(
122 doc="how large a region of the sky should be used for each background point",
123 dtype=int, default=128, min=1,
124 )
125 binSizeX = pexConfig.RangeField(
126 doc=("Sky region size to be used for each background point in X direction. "
127 "If 0, the binSize config is used."),
128 dtype=int, default=0, min=0,
129 )
130 binSizeY = pexConfig.RangeField(
131 doc=("Sky region size to be used for each background point in Y direction. "
132 "If 0, the binSize config is used."),
133 dtype=int, default=0, min=0,
134 )
135 algorithm = pexConfig.ChoiceField(
136 doc="how to interpolate the background values. This maps to an enum; see afw::math::Background",
137 dtype=str, default="AKIMA_SPLINE", optional=True,
138 allowed={
139 "CONSTANT": "Use a single constant value",
140 "LINEAR": "Use linear interpolation",
141 "NATURAL_SPLINE": "cubic spline with zero second derivative at endpoints",
142 "AKIMA_SPLINE": "higher-level nonlinear spline that is more robust to outliers",
143 "NONE": "No background estimation is to be attempted",
144 },
145 )
146 ignoredPixelMask = pexConfig.ListField(
147 doc="Names of mask planes to ignore while estimating the background",
148 dtype=str, default=["BAD", "EDGE", "DETECTED", "DETECTED_NEGATIVE", "NO_DATA", ],
149 itemCheck=lambda x: x in afwImage.Mask().getMaskPlaneDict().keys(),
150 )
151 isNanSafe = pexConfig.Field(
152 doc="Ignore NaNs when estimating the background",
153 dtype=bool, default=False,
154 )
155
156 useApprox = pexConfig.Field(
157 doc="Use Approximate (Chebyshev) to model background.",
158 dtype=bool, default=True,
159 )
160 approxOrderX = pexConfig.Field(
161 doc="Approximation order in X for background Chebyshev (valid only with useApprox=True)",
162 dtype=int, default=6,
163 )
164 # Note: Currently X- and Y-orders must be equal due to a limitation in math::Chebyshev1Function2
165 # The following is being added so that the weighting attribute can also be configurable for the
166 # call to afwMath.ApproximateControl
167 approxOrderY = pexConfig.Field(
168 doc="Approximation order in Y for background Chebyshev (valid only with useApprox=True)",
169 dtype=int, default=-1,
170 )
171 weighting = pexConfig.Field(
172 doc="Use inverse variance weighting in calculation (valid only with useApprox=True)",
173 dtype=bool, default=True,
174 )
175 doApplyFlatBackgroundRatio = pexConfig.Field(
176 doc="Convert from a photometrically flat image to one suitable to background subtraction? "
177 "If True, then a backgroundToPhotometricRatio must be supplied to the task run method.",
178 dtype=bool,
179 default=False,
180 )
181 doFilterSuperPixels = pexConfig.Field(
182 doc="Remove outliers from the binned image.",
183 dtype=bool,
184 default=False,
185 )
186 superPixelFilterSize = pexConfig.Field(
187 doc="Size of the median filter to use to remove outliers from the binned image.",
188 dtype=int,
189 default=3,
190 )
191
192
193class SubtractBackgroundTask(pipeBase.Task):
194 """Subtract the background from an exposure
195 """
196 ConfigClass = SubtractBackgroundConfig
197 _DefaultName = "subtractBackground"
198
199 def run(self, exposure, background=None, stats=True, statsKeys=None, backgroundToPhotometricRatio=None):
200 """Fit and subtract the background of an exposure.
201
202 Parameters
203 ----------
204 exposure : `lsst.afw.image.Exposure`
205 Exposure whose background is to be subtracted.
206 background : `lsst.afw.math.BackgroundList`
207 Initial background model already subtracted. May be None if no background
208 has been subtracted.
209 stats : `bool`
210 If True then measure the mean and variance of the full background model and
211 record the results in the exposure's metadata.
212 statsKeys : `tuple`
213 Key names used to store the mean and variance of the background in the
214 exposure's metadata (another tuple); if None then use ("BGMEAN", "BGVAR");
215 ignored if stats is false.
216 backgroundToPhotometricRatio : `lsst.afw.image.Image`, optional
217 Image to multiply a photometrically-flattened image by to obtain a
218 background-flattened image.
219 Only used if config.doApplyFlatBackgroundRatio = True.
220
221 Returns
222 -------
223 background : `lsst.afw.math.BackgroundList`
224 Full background model (initial model with changes), contained in an
225 `lsst.pipe.base.Struct`.
226 """
227 if background is None:
228 background = afwMath.BackgroundList()
229
230 maskedImage = exposure.maskedImage
231
233 maskedImage,
234 self.config.doApplyFlatBackgroundRatio,
235 backgroundToPhotometricRatio=backgroundToPhotometricRatio,
236 ):
237 fitBg = self.fitBackground(maskedImage)
238 if self.config.doFilterSuperPixels:
239 filterSuperPixels(maskedImage.getBBox(), fitBg,
240 superPixelFilterSize=self.config.superPixelFilterSize)
241
242 maskedImage -= fitBg.getImageF(self.config.algorithm, self.config.undersampleStyle)
243
244 actrl = fitBg.getBackgroundControl().getApproximateControl()
245 background.append((fitBg, getattr(afwMath.Interpolate, self.config.algorithm),
246 fitBg.getAsUsedUndersampleStyle(), actrl.getStyle(),
247 actrl.getOrderX(), actrl.getOrderY(), actrl.getWeighting()))
248
249 if stats:
250 self._addStats(exposure, background, statsKeys=statsKeys)
251
252 subFrame = getDebugFrame(self._display, "subtracted")
253 if subFrame:
254 subDisp = afwDisplay.getDisplay(frame=subFrame)
255 subDisp.mtv(exposure, title="subtracted")
256
257 bgFrame = getDebugFrame(self._display, "background")
258 if bgFrame:
259 bgDisp = afwDisplay.getDisplay(frame=bgFrame)
260 bgImage = background.getImage()
261 bgDisp.mtv(bgImage, title="background")
262
263 return pipeBase.Struct(
264 background=background,
265 )
266
267 def _addStats(self, exposure, background, statsKeys=None):
268 """Add statistics about the background to the exposure's metadata
269
270 Parameters
271 ----------
272 exposure : `lsst.afw.image.Exposure`
273 Exposure whose background was subtracted.
274 background : `lsst.afw.math.BackgroundList`
275 Background model
276 statsKeys : `tuple`
277 Key names used to store the mean and variance of the background in
278 the exposure's metadata (a tuple); if None then use
279 ("BGMEAN", "BGVAR"); ignored if stats is false.
280 """
281 netBgImg = background.getImage()
282 if statsKeys is None:
283 statsKeys = ("BGMEAN", "BGVAR")
284 mnkey, varkey = statsKeys
285 meta = exposure.getMetadata()
286 s = afwMath.makeStatistics(netBgImg, afwMath.MEAN | afwMath.VARIANCE)
287 bgmean = s.getValue(afwMath.MEAN)
288 bgvar = s.getValue(afwMath.VARIANCE)
289 meta.addDouble(mnkey, bgmean)
290 meta.addDouble(varkey, bgvar)
291
292 def fitBackground(self, maskedImage, nx=0, ny=0, algorithm=None):
293 """Estimate the background of a masked image
294
295 Parameters
296 ----------
297 maskedImage : `lsst.afw.image.maskedImage`
298 Masked image whose background is to be computed
299 nx : 'int`
300 Number of x bands; if 0 compute from width and `self.config.binSizeX`
301 ny : `int`
302 Number of y bands; if 0 compute from height and `self.config.binSizeY`
303 algorithm : `str`
304 Name of interpolation algorithm; if None use `self.config.algorithm`
305
306 Returns
307 -------
308 bg : `lsst.afw.math.Background`
309 A fit background
310
311 Raises
312 ------
313 RuntimeError
314 Raised if lsst.afw.math.makeBackground returns None, an indicator
315 of failure.
316 """
317
318 binSizeX = self.config.binSize if self.config.binSizeX == 0 else self.config.binSizeX
319 binSizeY = self.config.binSize if self.config.binSizeY == 0 else self.config.binSizeY
320
321 if not nx:
322 nx = maskedImage.getWidth()//binSizeX + 1
323 if not ny:
324 ny = maskedImage.getHeight()//binSizeY + 1
325
326 unsubFrame = getDebugFrame(self._display, "unsubtracted")
327 if unsubFrame:
328 unsubDisp = afwDisplay.getDisplay(frame=unsubFrame)
329 unsubDisp.mtv(maskedImage, title="unsubtracted")
330 xPosts = numpy.rint(numpy.linspace(0, maskedImage.getWidth() + 1, num=nx, endpoint=True))
331 yPosts = numpy.rint(numpy.linspace(0, maskedImage.getHeight() + 1, num=ny, endpoint=True))
332 with unsubDisp.Buffering():
333 for (xMin, xMax), (yMin, yMax) in itertools.product(zip(xPosts[:-1], xPosts[1:]),
334 zip(yPosts[:-1], yPosts[1:])):
335 unsubDisp.line([(xMin, yMin), (xMin, yMax), (xMax, yMax), (xMax, yMin), (xMin, yMin)])
336
337 sctrl = afwMath.StatisticsControl()
338 badMask = maskedImage.mask.getPlaneBitMask(self.config.ignoredPixelMask)
339
340 sctrl.setAndMask(badMask)
341 sctrl.setNanSafe(self.config.isNanSafe)
342
343 self.log.debug("Ignoring mask planes: %s", ", ".join(self.config.ignoredPixelMask))
344 if (maskedImage.mask.getArray() & badMask).all():
345 raise TooManyMaskedPixelsError("All pixels masked. Cannot estimate background.")
346
347 if algorithm is None:
348 algorithm = self.config.algorithm
349
350 # TODO: DM-22814. This call to a deprecated BackgroundControl constructor
351 # is necessary to support the algorithm parameter; it # should be replaced with
352 #
353 # afwMath.BackgroundControl(nx, ny, sctrl, self.config.statisticsProperty)
354 #
355 # when algorithm has been deprecated and removed.
356 with suppress_deprecations():
357 bctrl = afwMath.BackgroundControl(algorithm, nx, ny,
358 self.config.undersampleStyle, sctrl,
359 self.config.statisticsProperty)
360
361 # TODO: The following check should really be done within lsst.afw.math.
362 # With the current code structure, it would need to be accounted for in the doGetImage()
363 # function in BackgroundMI.cc (which currently only checks against the interpolation settings,
364 # which is not appropriate when useApprox=True)
365 # and/or the makeApproximate() function in afw/Approximate.cc.
366 # See ticket DM-2920: "Clean up code in afw for Approximate background
367 # estimation" (which includes a note to remove the following and the
368 # similar checks in pipe_tasks/matchBackgrounds.py once implemented)
369 #
370 # Check that config setting of approxOrder/binSize make sense
371 # (i.e. ngrid (= shortDimension/binSize) > approxOrderX) and perform
372 # appropriate undersampleStlye behavior.
373 if self.config.useApprox:
374 if self.config.approxOrderY not in (self.config.approxOrderX, -1):
375 raise ValueError("Error: approxOrderY not in (approxOrderX, -1)")
376 order = self.config.approxOrderX
377 minNumberGridPoints = order + 1
378 if min(nx, ny) <= order:
379 self.log.warning("Too few points in grid to constrain fit: min(nx, ny) < approxOrder) "
380 "[min(%d, %d) < %d]", nx, ny, order)
381 if self.config.undersampleStyle == "THROW_EXCEPTION":
382 raise ValueError("Too few points in grid (%d, %d) for order (%d) and binSize (%d, %d)" %
383 (nx, ny, order, binSizeX, binSizeY))
384 elif self.config.undersampleStyle == "REDUCE_INTERP_ORDER":
385 if order < 1:
386 raise ValueError("Cannot reduce approxOrder below 0. "
387 "Try using undersampleStyle = \"INCREASE_NXNYSAMPLE\" instead?")
388 order = min(nx, ny) - 1
389 self.log.warning("Reducing approxOrder to %d", order)
390 elif self.config.undersampleStyle == "INCREASE_NXNYSAMPLE":
391 # Reduce bin size to the largest acceptable square bins
392 newBinSize = min(maskedImage.getWidth(), maskedImage.getHeight())//(minNumberGridPoints-1)
393 if newBinSize < 1:
394 raise ValueError("Binsize must be greater than 0")
395 newNx = maskedImage.getWidth()//newBinSize + 1
396 newNy = maskedImage.getHeight()//newBinSize + 1
397 bctrl.setNxSample(newNx)
398 bctrl.setNySample(newNy)
399 self.log.warning("Decreasing binSize from (%d, %d) to %d for a grid of (%d, %d)",
400 binSizeX, binSizeY, newBinSize, newNx, newNy)
401
402 actrl = afwMath.ApproximateControl(afwMath.ApproximateControl.CHEBYSHEV, order, order,
403 self.config.weighting)
404 bctrl.setApproximateControl(actrl)
405
406 bg = afwMath.makeBackground(maskedImage, bctrl)
407 if bg is None:
408 raise RuntimeError("lsst.afw.math.makeBackground failed to fit a background model")
409 return bg
410
411
412def filterSuperPixels(bbox, background, superPixelFilterSize=3):
413 """Remove outliers from the binned background model.
414
415 Parameters
416 ----------
417 bbox : `lsst.geom.Box2I`
418 Bounding box of the original image.
419 background : `lsst.afw.math.BackgroundMI`
420 Fit and binned background image, which will be modified in place.
421 superPixelFilterSize : `int`, optional
422 Size of the median filter to use, in pixels.
423 """
424 statsImg = background.getStatsImage()
425 statsImg.image.array = median_filter(statsImg.image.array, mode='reflect', size=superPixelFilterSize)
426 background = afwMath.BackgroundMI(bbox, statsImg)
run(self, exposure, background=None, stats=True, statsKeys=None, backgroundToPhotometricRatio=None)
fitBackground(self, maskedImage, nx=0, ny=0, algorithm=None)
filterSuperPixels(bbox, background, superPixelFilterSize=3)
backgroundFlatContext(maskedImage, doApply, backgroundToPhotometricRatio=None)