199 def run(self, exposure, background=None, stats=True, statsKeys=None, backgroundToPhotometricRatio=None):
200 """Fit and subtract the background of an exposure.
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
210 If True then measure the mean and variance of the full background model and
211 record the results in the exposure's metadata.
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.
223 background : `lsst.afw.math.BackgroundList`
224 Full background model (initial model with changes), contained in an
225 `lsst.pipe.base.Struct`.
227 if background
is None:
228 background = afwMath.BackgroundList()
230 maskedImage = exposure.maskedImage
234 self.config.doApplyFlatBackgroundRatio,
235 backgroundToPhotometricRatio=backgroundToPhotometricRatio,
238 if self.config.doFilterSuperPixels:
240 superPixelFilterSize=self.config.superPixelFilterSize)
242 maskedImage -= fitBg.getImageF(self.config.algorithm, self.config.undersampleStyle)
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()))
250 self.
_addStats(exposure, background, statsKeys=statsKeys)
252 subFrame = getDebugFrame(self._display,
"subtracted")
254 subDisp = afwDisplay.getDisplay(frame=subFrame)
255 subDisp.mtv(exposure, title=
"subtracted")
257 bgFrame = getDebugFrame(self._display,
"background")
259 bgDisp = afwDisplay.getDisplay(frame=bgFrame)
260 bgImage = background.getImage()
261 bgDisp.mtv(bgImage, title=
"background")
263 return pipeBase.Struct(
264 background=background,
267 def _addStats(self, exposure, background, statsKeys=None):
268 """Add statistics about the background to the exposure's metadata
272 exposure : `lsst.afw.image.Exposure`
273 Exposure whose background was subtracted.
274 background : `lsst.afw.math.BackgroundList`
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.
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)
293 """Estimate the background of a masked image
297 maskedImage : `lsst.afw.image.maskedImage`
298 Masked image whose background is to be computed
300 Number of x bands; if 0 compute from width and `self.config.binSizeX`
302 Number of y bands; if 0 compute from height and `self.config.binSizeY`
304 Name of interpolation algorithm; if None use `self.config.algorithm`
308 bg : `lsst.afw.math.Background`
314 Raised if lsst.afw.math.makeBackground returns None, an indicator
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
322 nx = maskedImage.getWidth()//binSizeX + 1
324 ny = maskedImage.getHeight()//binSizeY + 1
326 unsubFrame = getDebugFrame(self._display,
"unsubtracted")
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)])
337 sctrl = afwMath.StatisticsControl()
338 badMask = maskedImage.mask.getPlaneBitMask(self.config.ignoredPixelMask)
340 sctrl.setAndMask(badMask)
341 sctrl.setNanSafe(self.config.isNanSafe)
343 self.log.debug(
"Ignoring mask planes: %s",
", ".join(self.config.ignoredPixelMask))
344 if (maskedImage.mask.getArray() & badMask).all():
347 if algorithm
is None:
348 algorithm = self.config.algorithm
356 with suppress_deprecations():
357 bctrl = afwMath.BackgroundControl(algorithm, nx, ny,
358 self.config.undersampleStyle, sctrl,
359 self.config.statisticsProperty)
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":
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":
392 newBinSize = min(maskedImage.getWidth(), maskedImage.getHeight())//(minNumberGridPoints-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)
402 actrl = afwMath.ApproximateControl(afwMath.ApproximateControl.CHEBYSHEV, order, order,
403 self.config.weighting)
404 bctrl.setApproximateControl(actrl)
406 bg = afwMath.makeBackground(maskedImage, bctrl)
408 raise RuntimeError(
"lsst.afw.math.makeBackground failed to fit a background model")