LSST Applications g0265f82a02+0e5473021a,g02d81e74bb+0dd8ce4237,g1470d8bcf6+3ea6592b6f,g2079a07aa2+86d27d4dc4,g2305ad1205+5ca4c0b359,g295015adf3+d10818ec9d,g2a9a014e59+6f9be1b9cd,g2bbee38e9b+0e5473021a,g337abbeb29+0e5473021a,g3ddfee87b4+703ba97ebf,g487adcacf7+4fa16da234,g50ff169b8f+96c6868917,g52b1c1532d+585e252eca,g591dd9f2cf+ffa42b374e,g5a732f18d5+53520f316c,g64a986408d+0dd8ce4237,g858d7b2824+0dd8ce4237,g8a8a8dda67+585e252eca,g99cad8db69+d39438377f,g9ddcbc5298+9a081db1e4,ga1e77700b3+15fc3df1f7,ga8c6da7877+f1d96605c8,gb0e22166c9+60f28cb32d,gb6a65358fc+0e5473021a,gba4ed39666+c2a2e4ac27,gbb8dafda3b+e5339d463f,gc120e1dc64+da31e9920e,gc28159a63d+0e5473021a,gcf0d15dbbd+703ba97ebf,gdaeeff99f8+f9a426f77a,ge6526c86ff+889fc9d533,ge79ae78c31+0e5473021a,gee10cc3b42+585e252eca,gf18bd8381d+7268b93478,gff1a9f87cc+0dd8ce4237,w.2024.16
LSST Data Management Base Package
Loading...
Searching...
No Matches
Public Member Functions | Static Public Attributes | Protected Member Functions | Static Protected Attributes | List of all members
lsst.meas.algorithms.subtractBackground.SubtractBackgroundTask Class Reference
Inheritance diagram for lsst.meas.algorithms.subtractBackground.SubtractBackgroundTask:

Public Member Functions

 run (self, exposure, background=None, stats=True, statsKeys=None)
 
 fitBackground (self, maskedImage, nx=0, ny=0, algorithm=None)
 

Static Public Attributes

 ConfigClass = SubtractBackgroundConfig
 

Protected Member Functions

 _addStats (self, exposure, background, statsKeys=None)
 

Static Protected Attributes

str _DefaultName = "subtractBackground"
 

Detailed Description

Subtract the background from an exposure

Definition at line 119 of file subtractBackground.py.

Member Function Documentation

◆ _addStats()

lsst.meas.algorithms.subtractBackground.SubtractBackgroundTask._addStats ( self,
exposure,
background,
statsKeys = None )
protected
Add statistics about the background to the exposure's metadata

Parameters
----------
exposure : `lsst.afw.image.Exposure`
    Exposure whose background was subtracted.
background : `lsst.afw.math.BackgroundList`
    Background model
statsKeys : `tuple`
    Key names used to store the mean and variance of the background in
    the exposure's metadata (a tuple); if None then use
    ("BGMEAN", "BGVAR"); ignored if stats is false.

Definition at line 179 of file subtractBackground.py.

179 def _addStats(self, exposure, background, statsKeys=None):
180 """Add statistics about the background to the exposure's metadata
181
182 Parameters
183 ----------
184 exposure : `lsst.afw.image.Exposure`
185 Exposure whose background was subtracted.
186 background : `lsst.afw.math.BackgroundList`
187 Background model
188 statsKeys : `tuple`
189 Key names used to store the mean and variance of the background in
190 the exposure's metadata (a tuple); if None then use
191 ("BGMEAN", "BGVAR"); ignored if stats is false.
192 """
193 netBgImg = background.getImage()
194 if statsKeys is None:
195 statsKeys = ("BGMEAN", "BGVAR")
196 mnkey, varkey = statsKeys
197 meta = exposure.getMetadata()
198 s = afwMath.makeStatistics(netBgImg, afwMath.MEAN | afwMath.VARIANCE)
199 bgmean = s.getValue(afwMath.MEAN)
200 bgvar = s.getValue(afwMath.VARIANCE)
201 meta.addDouble(mnkey, bgmean)
202 meta.addDouble(varkey, bgvar)
203
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:361

◆ fitBackground()

lsst.meas.algorithms.subtractBackground.SubtractBackgroundTask.fitBackground ( self,
maskedImage,
nx = 0,
ny = 0,
algorithm = None )
Estimate the background of a masked image

Parameters
----------
maskedImage : `lsst.afw.image.maskedImage`
    Masked image whose background is to be computed
nx : 'int`
    Number of x bands; if 0 compute from width and `self.config.binSizeX`
ny : `int`
    Number of y bands; if 0 compute from height and `self.config.binSizeY`
algorithm : `str`
    Name of interpolation algorithm; if None use `self.config.algorithm`

Returns
-------
bg : `lsst.afw.math.Background`
    A fit background

Raises
------
RuntimeError
    Raised if lsst.afw.math.makeBackground returns None, an indicator
    of failure.

Definition at line 204 of file subtractBackground.py.

204 def fitBackground(self, maskedImage, nx=0, ny=0, algorithm=None):
205 """Estimate the background of a masked image
206
207 Parameters
208 ----------
209 maskedImage : `lsst.afw.image.maskedImage`
210 Masked image whose background is to be computed
211 nx : 'int`
212 Number of x bands; if 0 compute from width and `self.config.binSizeX`
213 ny : `int`
214 Number of y bands; if 0 compute from height and `self.config.binSizeY`
215 algorithm : `str`
216 Name of interpolation algorithm; if None use `self.config.algorithm`
217
218 Returns
219 -------
220 bg : `lsst.afw.math.Background`
221 A fit background
222
223 Raises
224 ------
225 RuntimeError
226 Raised if lsst.afw.math.makeBackground returns None, an indicator
227 of failure.
228 """
229
230 binSizeX = self.config.binSize if self.config.binSizeX == 0 else self.config.binSizeX
231 binSizeY = self.config.binSize if self.config.binSizeY == 0 else self.config.binSizeY
232
233 if not nx:
234 nx = maskedImage.getWidth()//binSizeX + 1
235 if not ny:
236 ny = maskedImage.getHeight()//binSizeY + 1
237
238 unsubFrame = getDebugFrame(self._display, "unsubtracted")
239 if unsubFrame:
240 unsubDisp = afwDisplay.getDisplay(frame=unsubFrame)
241 unsubDisp.mtv(maskedImage, title="unsubtracted")
242 xPosts = numpy.rint(numpy.linspace(0, maskedImage.getWidth() + 1, num=nx, endpoint=True))
243 yPosts = numpy.rint(numpy.linspace(0, maskedImage.getHeight() + 1, num=ny, endpoint=True))
244 with unsubDisp.Buffering():
245 for (xMin, xMax), (yMin, yMax) in itertools.product(zip(xPosts[:-1], xPosts[1:]),
246 zip(yPosts[:-1], yPosts[1:])):
247 unsubDisp.line([(xMin, yMin), (xMin, yMax), (xMax, yMax), (xMax, yMin), (xMin, yMin)])
248
250 badMask = maskedImage.mask.getPlaneBitMask(self.config.ignoredPixelMask)
251
252 sctrl.setAndMask(badMask)
253 sctrl.setNanSafe(self.config.isNanSafe)
254
255 self.log.debug("Ignoring mask planes: %s", ", ".join(self.config.ignoredPixelMask))
256 if (maskedImage.mask.getArray() & badMask).all():
257 raise pipeBase.TaskError("All pixels masked. Cannot estimate background")
258
259 if algorithm is None:
260 algorithm = self.config.algorithm
261
262 # TODO: DM-22814. This call to a deprecated BackgroundControl constructor
263 # is necessary to support the algorithm parameter; it # should be replaced with
264 #
265 # afwMath.BackgroundControl(nx, ny, sctrl, self.config.statisticsProperty)
266 #
267 # when algorithm has been deprecated and removed.
268 with suppress_deprecations():
269 bctrl = afwMath.BackgroundControl(algorithm, nx, ny,
270 self.config.undersampleStyle, sctrl,
271 self.config.statisticsProperty)
272
273 # TODO: The following check should really be done within lsst.afw.math.
274 # With the current code structure, it would need to be accounted for in the doGetImage()
275 # function in BackgroundMI.cc (which currently only checks against the interpolation settings,
276 # which is not appropriate when useApprox=True)
277 # and/or the makeApproximate() function in afw/Approximate.cc.
278 # See ticket DM-2920: "Clean up code in afw for Approximate background
279 # estimation" (which includes a note to remove the following and the
280 # similar checks in pipe_tasks/matchBackgrounds.py once implemented)
281 #
282 # Check that config setting of approxOrder/binSize make sense
283 # (i.e. ngrid (= shortDimension/binSize) > approxOrderX) and perform
284 # appropriate undersampleStlye behavior.
285 if self.config.useApprox:
286 if self.config.approxOrderY not in (self.config.approxOrderX, -1):
287 raise ValueError("Error: approxOrderY not in (approxOrderX, -1)")
288 order = self.config.approxOrderX
289 minNumberGridPoints = order + 1
290 if min(nx, ny) <= order:
291 self.log.warning("Too few points in grid to constrain fit: min(nx, ny) < approxOrder) "
292 "[min(%d, %d) < %d]", nx, ny, order)
293 if self.config.undersampleStyle == "THROW_EXCEPTION":
294 raise ValueError("Too few points in grid (%d, %d) for order (%d) and binSize (%d, %d)" %
295 (nx, ny, order, binSizeX, binSizeY))
296 elif self.config.undersampleStyle == "REDUCE_INTERP_ORDER":
297 if order < 1:
298 raise ValueError("Cannot reduce approxOrder below 0. "
299 "Try using undersampleStyle = \"INCREASE_NXNYSAMPLE\" instead?")
300 order = min(nx, ny) - 1
301 self.log.warning("Reducing approxOrder to %d", order)
302 elif self.config.undersampleStyle == "INCREASE_NXNYSAMPLE":
303 # Reduce bin size to the largest acceptable square bins
304 newBinSize = min(maskedImage.getWidth(), maskedImage.getHeight())//(minNumberGridPoints-1)
305 if newBinSize < 1:
306 raise ValueError("Binsize must be greater than 0")
307 newNx = maskedImage.getWidth()//newBinSize + 1
308 newNy = maskedImage.getHeight()//newBinSize + 1
309 bctrl.setNxSample(newNx)
310 bctrl.setNySample(newNy)
311 self.log.warning("Decreasing binSize from (%d, %d) to %d for a grid of (%d, %d)",
312 binSizeX, binSizeY, newBinSize, newNx, newNy)
313
314 actrl = afwMath.ApproximateControl(afwMath.ApproximateControl.CHEBYSHEV, order, order,
315 self.config.weighting)
316 bctrl.setApproximateControl(actrl)
317
318 bg = afwMath.makeBackground(maskedImage, bctrl)
319 if bg is None:
320 raise RuntimeError("lsst.afw.math.makeBackground failed to fit a background model")
321 return bg
int min
Control how to make an approximation.
Definition Approximate.h:48
Pass parameters to a Background object.
Definition Background.h:56
Pass parameters to a Statistics object.
Definition Statistics.h:83
std::shared_ptr< Background > makeBackground(ImageT const &img, BackgroundControl const &bgCtrl)
A convenience function that uses function overloading to make the correct type of Background.
Definition Background.h:526

◆ run()

lsst.meas.algorithms.subtractBackground.SubtractBackgroundTask.run ( self,
exposure,
background = None,
stats = True,
statsKeys = None )
Fit and subtract the background of an exposure.

Parameters
----------
exposure : `lsst.afw.image.Exposure`
    Exposure whose background is to be subtracted.
background : `lsst.afw.math.BackgroundList`
    Initial background model already subtracted. May be None if no background
    has been subtracted.
stats : `bool`
    If True then measure the mean and variance of the full background model and
    record the results in the exposure's metadata.
statsKeys : `tuple`
    Key names used to store the mean and variance of the background in the
    exposure's metadata (another tuple); if None then use ("BGMEAN", "BGVAR");
    ignored if stats is false.

Returns
-------
background : `lsst.afw.math.BackgroundLst`
    Full background model (initial model with changes), contained in an
    `lsst.pipe.base.Struct`.

Definition at line 125 of file subtractBackground.py.

125 def run(self, exposure, background=None, stats=True, statsKeys=None):
126 """Fit and subtract the background of an exposure.
127
128 Parameters
129 ----------
130 exposure : `lsst.afw.image.Exposure`
131 Exposure whose background is to be subtracted.
132 background : `lsst.afw.math.BackgroundList`
133 Initial background model already subtracted. May be None if no background
134 has been subtracted.
135 stats : `bool`
136 If True then measure the mean and variance of the full background model and
137 record the results in the exposure's metadata.
138 statsKeys : `tuple`
139 Key names used to store the mean and variance of the background in the
140 exposure's metadata (another tuple); if None then use ("BGMEAN", "BGVAR");
141 ignored if stats is false.
142
143 Returns
144 -------
145 background : `lsst.afw.math.BackgroundLst`
146 Full background model (initial model with changes), contained in an
147 `lsst.pipe.base.Struct`.
148 """
149 if background is None:
150 background = afwMath.BackgroundList()
151
152 maskedImage = exposure.getMaskedImage()
153 fitBg = self.fitBackground(maskedImage)
154 maskedImage -= fitBg.getImageF(self.config.algorithm, self.config.undersampleStyle)
155
156 actrl = fitBg.getBackgroundControl().getApproximateControl()
157 background.append((fitBg, getattr(afwMath.Interpolate, self.config.algorithm),
158 fitBg.getAsUsedUndersampleStyle(), actrl.getStyle(),
159 actrl.getOrderX(), actrl.getOrderY(), actrl.getWeighting()))
160
161 if stats:
162 self._addStats(exposure, background, statsKeys=statsKeys)
163
164 subFrame = getDebugFrame(self._display, "subtracted")
165 if subFrame:
166 subDisp = afwDisplay.getDisplay(frame=subFrame)
167 subDisp.mtv(exposure, title="subtracted")
168
169 bgFrame = getDebugFrame(self._display, "background")
170 if bgFrame:
171 bgDisp = afwDisplay.getDisplay(frame=bgFrame)
172 bgImage = background.getImage()
173 bgDisp.mtv(bgImage, title="background")
174
175 return pipeBase.Struct(
176 background=background,
177 )
178

Member Data Documentation

◆ _DefaultName

str lsst.meas.algorithms.subtractBackground.SubtractBackgroundTask._DefaultName = "subtractBackground"
staticprotected

Definition at line 123 of file subtractBackground.py.

◆ ConfigClass

lsst.meas.algorithms.subtractBackground.SubtractBackgroundTask.ConfigClass = SubtractBackgroundConfig
static

Definition at line 122 of file subtractBackground.py.


The documentation for this class was generated from the following file: