LSSTApplications  18.1.0
LSSTDataManagementBasePackage
BackgroundMI.cc
Go to the documentation of this file.
1 // -*- LSST-C++ -*-
2 
3 /*
4  * LSST Data Management System
5  * Copyright 2008-2015 AURA/LSST.
6  *
7  * This product includes software developed by the
8  * LSST Project (http://www.lsst.org/).
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the LSST License Statement and
21  * the GNU General Public License along with this program. If not,
22  * see <https://www.lsstcorp.org/LegalNotices/>.
23  */
24 
25 /*
26  * Background estimation class code
27  */
28 #include <iostream>
29 #include <limits>
30 #include <vector>
31 #include <cmath>
37 
38 namespace lsst {
39 namespace ex = pex::exceptions;
40 
41 namespace afw {
42 namespace math {
43 
44 namespace {
45 
46 // Given two vectors x and y, with some nans in y we want vectors x' and y' that correspond to the data
47 // without the nans basic idea is that 'x' is the values, and 'y' is the ref (where nan checking happens)
48 // cullNan(x, y, x', y')
49 void cullNan(std::vector<double> const& values, std::vector<double> const& refs,
50  std::vector<double>& culledValues, std::vector<double>& culledRefs,
51  double const defaultValue = std::numeric_limits<double>::quiet_NaN()) {
52  if (culledValues.capacity() == 0) {
53  culledValues.reserve(refs.size());
54  } else {
55  culledValues.clear();
56  }
57  if (culledRefs.capacity() == 0) {
58  culledRefs.reserve(refs.size());
59  } else {
60  culledRefs.clear();
61  }
62 
63  bool const haveDefault = !std::isnan(defaultValue);
64 
65  for (std::vector<double>::const_iterator pVal = values.begin(), pRef = refs.begin(); pRef != refs.end();
66  ++pRef, ++pVal) {
67  if (!std::isnan(*pRef)) {
68  culledValues.push_back(*pVal);
69  culledRefs.push_back(*pRef);
70  } else if (haveDefault) {
71  culledValues.push_back(*pVal);
72  culledRefs.push_back(defaultValue);
73  } else {
74  ; // drop a NaN
75  }
76  }
77 }
78 } // namespace
79 
80 template <typename ImageT>
81 BackgroundMI::BackgroundMI(ImageT const& img, BackgroundControl const& bgCtrl)
82  : Background(img, bgCtrl), _statsImage(image::MaskedImage<InternalPixelT>()) {
83  // =============================================================
84  // Loop over the cells in the image, computing statistical properties
85  // of each cell in turn and using them to set _statsImage
86  int const nxSample = bgCtrl.getNxSample();
87  int const nySample = bgCtrl.getNySample();
88  _statsImage = image::MaskedImage<InternalPixelT>(nxSample, nySample);
89 
92 
93  for (int iX = 0; iX < nxSample; ++iX) {
94  for (int iY = 0; iY < nySample; ++iY) {
95  ImageT subimg = ImageT(img,
98  image::LOCAL);
99 
101  *bgCtrl.getStatisticsControl())
102  .getResult();
103  im(iX, iY) = res.first;
104  var(iX, iY) = res.second;
105  }
106  }
107 }
109  image::MaskedImage<InternalPixelT> const& statsImage)
110  : Background(imageBBox, statsImage.getWidth(), statsImage.getHeight()), _statsImage(statsImage) {}
111 
112 void BackgroundMI::_setGridColumns(Interpolate::Style const interpStyle,
113  UndersampleStyle const undersampleStyle, int const iX,
114  std::vector<int> const& ypix) const {
116 
117  int const height = _imgBBox.getHeight();
118  _gridColumns[iX].resize(height);
119 
120  // Set _grid as a transitional measure
121  std::vector<double> _grid(_statsImage.getHeight());
122  std::copy(im.col_begin(iX), im.col_end(iX), _grid.begin());
123 
124  // remove nan from the grid values before computing columns
125  // if we do it here (ie. in _setGridColumns), it should
126  // take care of all future occurrences, so we don't need to do this elsewhere
127  std::vector<double> ycenTmp, gridTmp;
128  cullNan(_ycen, _grid, ycenTmp, gridTmp);
129 
131  try {
132  intobj = makeInterpolate(ycenTmp, gridTmp, interpStyle);
133  } catch (pex::exceptions::OutOfRangeError& e) {
134  switch (undersampleStyle) {
135  case THROW_EXCEPTION:
136  LSST_EXCEPT_ADD(e, "setting _gridcolumns");
137  throw;
138  case REDUCE_INTERP_ORDER: {
139  if (gridTmp.empty()) {
140  // Set the column to NaN. We'll deal with this properly when interpolating in x
141  ycenTmp.push_back(0);
143 
144  intobj = makeInterpolate(ycenTmp, gridTmp, Interpolate::CONSTANT);
145  break;
146  } else {
147  return _setGridColumns(lookupMaxInterpStyle(gridTmp.size()), undersampleStyle, iX, ypix);
148  }
149  }
150  case INCREASE_NXNYSAMPLE:
152  e, "The BackgroundControl UndersampleStyle INCREASE_NXNYSAMPLE is not supported.");
153  throw;
154  default:
155  LSST_EXCEPT_ADD(e, str(boost::format("The selected BackgroundControl "
156  "UndersampleStyle %d is not defined.") %
157  undersampleStyle));
158  throw;
159  }
160  } catch (ex::Exception& e) {
161  LSST_EXCEPT_ADD(e, "setting _gridcolumns");
162  throw;
163  }
164 
165  for (int iY = 0; iY < height; ++iY) {
166  _gridColumns[iX][iY] = intobj->interpolate(ypix[iY]);
167  }
168 }
169 
171  _statsImage += delta;
172  return *this;
173 }
174 
176  _statsImage -= delta;
177  return *this;
178 }
179 
180 double BackgroundMI::getPixel(Interpolate::Style const interpStyle, int const x, int const y) const {
181  (void)getImage<InternalPixelT>(interpStyle); // setup the interpolation
182 
183  // build an interpobj along the row y and get the x'th value
184  int const nxSample = _statsImage.getWidth();
185  std::vector<double> bg_x(nxSample);
186  for (int iX = 0; iX < nxSample; iX++) {
187  bg_x[iX] = _gridColumns[iX][y];
188  }
189  std::vector<double> xcenTmp, bgTmp;
190  cullNan(_xcen, bg_x, xcenTmp, bgTmp);
191 
192  try {
193  std::shared_ptr<Interpolate> intobj = makeInterpolate(xcenTmp, bgTmp, interpStyle);
194  return static_cast<double>(intobj->interpolate(x));
195  } catch (ex::Exception& e) {
196  LSST_EXCEPT_ADD(e, "in getPixel()");
197  throw;
198  }
199 }
200 template <typename PixelT>
201 std::shared_ptr<image::Image<PixelT>> BackgroundMI::doGetImage(
202  lsst::geom::Box2I const& bbox,
203  Interpolate::Style const interpStyle_, // Style of the interpolation
204  UndersampleStyle const undersampleStyle // Behaviour if there are too few points
205  ) const {
206  if (!_imgBBox.contains(bbox)) {
207  throw LSST_EXCEPT(
209  str(boost::format("BBox (%d:%d,%d:%d) out of range (%d:%d,%d:%d)") % bbox.getMinX() %
210  bbox.getMaxX() % bbox.getMinY() % bbox.getMaxY() % _imgBBox.getMinX() %
212  }
213  int const nxSample = _statsImage.getWidth();
214  int const nySample = _statsImage.getHeight();
215  Interpolate::Style interpStyle = interpStyle_; // not const -- may be modified if REDUCE_INTERP_ORDER
216 
217  /*
218  * Save the as-used interpStyle and undersampleStyle.
219  *
220  * N.b. The undersampleStyle may actually be overridden for some columns of the statsImage if they
221  * have too few good values. This doesn't prevent you reproducing the results of getImage() by
222  * calling getImage(getInterpStyle(), getUndersampleStyle())
223  */
224  _asUsedInterpStyle = interpStyle;
225  _asUsedUndersampleStyle = undersampleStyle;
226  /*
227  * Check if the requested nx,ny are sufficient for the requested interpolation style,
228  * making suitable adjustments
229  */
230  bool const isXundersampled = (nxSample < lookupMinInterpPoints(interpStyle));
231  bool const isYundersampled = (nySample < lookupMinInterpPoints(interpStyle));
232 
233  switch (undersampleStyle) {
234  case THROW_EXCEPTION:
235  if (isXundersampled && isYundersampled) {
236  throw LSST_EXCEPT(
238  "nxSample and nySample have too few points for requested interpolation style.");
239  } else if (isXundersampled) {
241  "nxSample has too few points for requested interpolation style.");
242  } else if (isYundersampled) {
244  "nySample has too few points for requested interpolation style.");
245  }
246  break;
247  case REDUCE_INTERP_ORDER:
248  if (isXundersampled || isYundersampled) {
249  Interpolate::Style const xStyle = lookupMaxInterpStyle(nxSample);
250  Interpolate::Style const yStyle = lookupMaxInterpStyle(nySample);
251  interpStyle = (nxSample < nySample) ? xStyle : yStyle;
252  _asUsedInterpStyle = interpStyle;
253  }
254  break;
255  case INCREASE_NXNYSAMPLE:
256  if (isXundersampled || isYundersampled) {
257  throw LSST_EXCEPT(
259  "The BackgroundControl UndersampleStyle INCREASE_NXNYSAMPLE is not supported.");
260  }
261  break;
262  default:
264  str(boost::format("The selected BackgroundControl "
265  "UndersampleStyle %d is not defined.") %
266  undersampleStyle));
267  }
268 
269  // if we're approximating, don't bother with the rest of the interp-related work. Return from here.
270  if (_bctrl->getApproximateControl()->getStyle() != ApproximateControl::UNKNOWN) {
271  return doGetApproximate<PixelT>(*_bctrl->getApproximateControl(), _asUsedUndersampleStyle)
272  ->getImage();
273  }
274 
275  // =============================================================
276  // --> We'll store nxSample fully-interpolated columns to interpolate the rows over
277  // make a vector containing the y pixel coords for the column
278  int const width = _imgBBox.getWidth();
279  int const height = _imgBBox.getHeight();
280  auto const bboxOff = bbox.getMin() - _imgBBox.getMin();
281 
282  std::vector<int> ypix(height);
283  for (int iY = 0; iY < height; ++iY) {
284  ypix[iY] = iY;
285  }
286 
287  _gridColumns.resize(width);
288  for (int iX = 0; iX < nxSample; ++iX) {
289  _setGridColumns(interpStyle, undersampleStyle, iX, ypix);
290  }
291 
292  // create a shared_ptr to put the background image in and return to caller
293  // start with xy0 = 0 and set final xy0 later
296 
297  // go through row by row
298  // - interpolate on the gridcolumns that were pre-computed by the constructor
299  // - copy the values to an ImageT to return to the caller.
300  std::vector<double> xcenTmp, bgTmp;
301 
302  // N.b. There's no API to set defaultValue to other than NaN (due to issues with persistence
303  // that I don't feel like fixing; #2825). If we want to address this, this is the place
304  // to start, but note that NaN is treated specially -- it means, "Interpolate" so to allow
305  // us to put a NaN into the outputs some changes will be needed
306  double defaultValue = std::numeric_limits<double>::quiet_NaN();
307 
308  for (int y = 0, iY = bboxOff.getY(); y < bbox.getHeight(); ++y, ++iY) {
309  // build an interp object for this row
310  std::vector<double> bg_x(nxSample);
311  for (int iX = 0; iX < nxSample; iX++) {
312  bg_x[iX] = static_cast<double>(_gridColumns[iX][iY]);
313  }
314  cullNan(_xcen, bg_x, xcenTmp, bgTmp, defaultValue);
315 
317  try {
318  intobj = makeInterpolate(xcenTmp, bgTmp, interpStyle);
319  } catch (pex::exceptions::OutOfRangeError& e) {
320  switch (undersampleStyle) {
321  case THROW_EXCEPTION:
322  LSST_EXCEPT_ADD(e, str(boost::format("Interpolating in y (iY = %d)") % iY));
323  throw;
324  case REDUCE_INTERP_ORDER: {
325  if (bgTmp.empty()) {
326  xcenTmp.push_back(0);
327  bgTmp.push_back(defaultValue);
328 
329  intobj = makeInterpolate(xcenTmp, bgTmp, Interpolate::CONSTANT);
330  break;
331  } else {
332  intobj = makeInterpolate(xcenTmp, bgTmp, lookupMaxInterpStyle(bgTmp.size()));
333  }
334  } break;
335  case INCREASE_NXNYSAMPLE:
337  e,
338  "The BackgroundControl UndersampleStyle INCREASE_NXNYSAMPLE is not supported.");
339  throw;
340  default:
341  LSST_EXCEPT_ADD(e, str(boost::format("The selected BackgroundControl "
342  "UndersampleStyle %d is not defined.") %
343  undersampleStyle));
344  throw;
345  }
346  } catch (ex::Exception& e) {
347  LSST_EXCEPT_ADD(e, str(boost::format("Interpolating in y (iY = %d)") % iY));
348  throw;
349  }
350 
351  // fill the image with interpolated values
352  for (int iX = bboxOff.getX(), x = 0; x < bbox.getWidth(); ++iX, ++x) {
353  (*bg)(x, y) = static_cast<PixelT>(intobj->interpolate(iX));
354  }
355  }
356  bg->setXY0(bbox.getMin());
357 
358  return bg;
359 }
360 
361 template <typename PixelT>
362 std::shared_ptr<Approximate<PixelT>> BackgroundMI::doGetApproximate(
363  ApproximateControl const& actrl, /* Approximation style */
364  UndersampleStyle const undersampleStyle /* Behaviour if there are too few points */
365  ) const {
366  auto const localBBox = lsst::geom::Box2I(lsst::geom::Point2I(0, 0), _imgBBox.getDimensions());
367  return makeApproximate(_xcen, _ycen, _statsImage, localBBox, actrl);
368 }
369 
371 /*
372  * Create the versions we need of _get{Approximate,Image} and Explicit instantiations
373  *
374  */
375 #define CREATE_BACKGROUND(m, v, TYPE) \
376  template BackgroundMI::BackgroundMI(image::Image<TYPE> const& img, BackgroundControl const& bgCtrl); \
377  template BackgroundMI::BackgroundMI(image::MaskedImage<TYPE> const& img, \
378  BackgroundControl const& bgCtrl); \
379  std::shared_ptr<image::Image<TYPE>> BackgroundMI::_getImage( \
380  lsst::geom::Box2I const& bbox, \
381  Interpolate::Style const interpStyle, /* Style of the interpolation */ \
382  UndersampleStyle const undersampleStyle, /* Behaviour if there are too few points */ \
383  TYPE /* disambiguate */ \
384  ) const { \
385  return BackgroundMI::doGetImage<TYPE>(bbox, interpStyle, undersampleStyle); \
386  }
387 
388 #define CREATE_getApproximate(m, v, TYPE) \
389  std::shared_ptr<Approximate<TYPE>> BackgroundMI::_getApproximate( \
390  ApproximateControl const& actrl, /* Approximation style */ \
391  UndersampleStyle const undersampleStyle, /* Behaviour if there are too few points */ \
392  TYPE /* disambiguate */ \
393  ) const { \
394  return BackgroundMI::doGetApproximate<TYPE>(actrl, undersampleStyle); \
395  }
396 
397 BOOST_PP_SEQ_FOR_EACH(CREATE_BACKGROUND, , LSST_makeBackground_getImage_types)
398 BOOST_PP_SEQ_FOR_EACH(CREATE_getApproximate, , LSST_makeBackground_getApproximate_types)
399 
400 } // namespace math
402 } // namespace afw
403 } // namespace lsst
Extent2I const getDimensions() const noexcept
Definition: Box.h:173
std::vector< int > _xsize
x size of sub images
Definition: Background.h:381
VariancePtr getVariance() const
Return a (shared_ptr to) the MaskedImage&#39;s variance.
Definition: MaskedImage.h:1091
std::vector< double > _xcen
x center pix coords of sub images
Definition: Background.h:377
T empty(T... args)
T copy(T... args)
std::vector< int > _yorig
y origin ...
Definition: Background.h:380
int getHeight() const noexcept
Definition: Box.h:175
lsst::geom::Box2I _imgBBox
size and origin of input image
Definition: Background.h:372
Property getStatisticsProperty() const
Definition: Background.h:218
BackgroundMI(ImageT const &img, BackgroundControl const &bgCtrl)
Constructor for BackgroundMI.
Definition: BackgroundMI.cc:81
Reports attempts to exceed implementation-defined length limits for some classes. ...
Definition: Runtime.h:76
std::shared_ptr< Interpolate > makeInterpolate(std::vector< double > const &x, std::vector< double > const &y, Interpolate::Style const style=Interpolate::AKIMA_SPLINE)
A factory function to make Interpolate objects.
Definition: Interpolate.cc:343
int y
Definition: SpanSet.cc:49
#define LSST_makeBackground_getApproximate_types
Definition: Background.h:394
std::vector< double > _ycen
y center ...
Definition: Background.h:378
T end(T... args)
Provides consistent interface for LSST exceptions.
Definition: Exception.h:107
BackgroundMI & operator+=(float const delta) override
Add a scalar to the Background (equivalent to adding a constant to the original image) ...
std::shared_ptr< Approximate< PixelT > > makeApproximate(std::vector< double > const &x, std::vector< double > const &y, image::MaskedImage< PixelT > const &im, lsst::geom::Box2I const &bbox, ApproximateControl const &ctrl)
Construct a new Approximate object, inferring the type from the type of the given MaskedImage...
Definition: Approximate.cc:279
Include errors of requested quantities.
Definition: Statistics.h:65
Pass parameters to a Background object.
Definition: Background.h:57
A virtual base class to evaluate image background levels.
Definition: Background.h:239
T resize(T... args)
ImagePtr getImage() const
Return a (shared_ptr to) the MaskedImage&#39;s image.
Definition: MaskedImage.h:1058
Point2I const getMin() const noexcept
Definition: Box.h:143
T push_back(T... args)
std::shared_ptr< lsst::afw::image::Image< PixelT > > getImage() const
Method to interpolate and return the background for entire image.
Definition: Background.h:338
y_iterator col_begin(int x) const
Return an y_iterator to the start of the y&#39;th row.
Definition: ImageBase.h:431
Control how to make an approximation.
Definition: Approximate.h:48
int getHeight() const
Return the number of rows in the image.
Definition: MaskedImage.h:1096
Interpolate::Style _asUsedInterpStyle
the style we actually used
Definition: Background.h:374
A base class for image defects.
int getMaxY() const noexcept
Definition: Box.h:149
std::shared_ptr< StatisticsControl > getStatisticsControl()
Definition: Background.h:215
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:354
def format(config, name=None, writeSourceLine=True, prefix="", verbose=False)
Definition: history.py:168
T capacity(T... args)
int getWidth() const noexcept
Definition: Box.h:174
y_iterator col_end(int x) const
Return an y_iterator to the start of the y&#39;th row.
Definition: ImageBase.h:434
T clear(T... args)
table::Box2IKey bbox
Definition: Detector.cc:169
int getMaxX() const noexcept
Definition: Box.h:148
double x
#define LSST_makeBackground_getImage_types
Definition: Background.h:393
Interpolate::Style lookupMaxInterpStyle(int const n)
Get the highest order Interpolation::Style available for &#39;n&#39; points.
Definition: Interpolate.cc:275
int getMinX() const noexcept
Definition: Box.h:144
T size(T... args)
int lookupMinInterpPoints(Interpolate::Style const style)
Get the minimum number of points needed to use the requested interpolation style. ...
Definition: Interpolate.cc:314
#define LSST_EXCEPT(type,...)
Create an exception with a given type.
Definition: Exception.h:48
Reports attempts to access elements outside a valid range of indices.
Definition: Runtime.h:89
T begin(T... args)
std::vector< int > _xorig
x origin pix coords of sub images
Definition: Background.h:379
BackgroundMI & operator-=(float const delta) override
Subtract a scalar from the Background (equivalent to subtracting a constant from the original image) ...
bool contains(Point2I const &point) const noexcept
Return true if the box contains the point.
Definition: Box.cc:117
std::shared_ptr< BackgroundControl > _bctrl
control info set by user.
Definition: Background.h:373
std::vector< int > _ysize
y size ...
Definition: Background.h:382
UndersampleStyle _asUsedUndersampleStyle
the undersampleStyle we actually used
Definition: Background.h:375
Reports invalid arguments.
Definition: Runtime.h:66
T isnan(T... args)
int getWidth() const
Return the number of columns in the image.
Definition: MaskedImage.h:1094
T quiet_NaN(T... args)
A class to evaluate image background levels.
Definition: Background.h:444
Backwards-compatibility support for depersisting the old Calib (FluxMag0/FluxMag0Err) objects...
#define LSST_EXCEPT_ADD(e, m)
Add the current location and a message to an existing exception before rethrowing it...
Definition: Exception.h:54
An integer coordinate rectangle.
Definition: Box.h:54
A class to represent a 2-dimensional array of pixels.
Definition: Image.h:59
double getPixel(Interpolate::Style const style, int const x, int const y) const
Method to retrieve the background level at a pixel coord.
int getMinY() const noexcept
Definition: Box.h:145
T reserve(T... args)