lsst.afw  14.0-25-g0e8fc950e+3
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 }
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, geom::Box2I(geom::Point2I(_xorig[iX], _yorig[iY]),
96  geom::Extent2I(_xsize[iX], _ysize[iY])),
97  image::LOCAL);
98 
100  *bgCtrl.getStatisticsControl())
101  .getResult();
102  im(iX, iY) = res.first;
103  var(iX, iY) = res.second;
104  }
105  }
106 }
108  : Background(imageBBox, statsImage.getWidth(), statsImage.getHeight()), _statsImage(statsImage) {}
109 
110 void BackgroundMI::_setGridColumns(Interpolate::Style const interpStyle,
111  UndersampleStyle const undersampleStyle, int const iX,
112  std::vector<int> const& ypix) const {
114 
115  int const height = _imgBBox.getHeight();
116  _gridColumns[iX].resize(height);
117 
118  // Set _grid as a transitional measure
119  std::vector<double> _grid(_statsImage.getHeight());
120  std::copy(im.col_begin(iX), im.col_end(iX), _grid.begin());
121 
122  // remove nan from the grid values before computing columns
123  // if we do it here (ie. in _setGridColumns), it should
124  // take care of all future occurrences, so we don't need to do this elsewhere
125  std::vector<double> ycenTmp, gridTmp;
126  cullNan(_ycen, _grid, ycenTmp, gridTmp);
127 
129  try {
130  intobj = makeInterpolate(ycenTmp, gridTmp, interpStyle);
131  } catch (pex::exceptions::OutOfRangeError& e) {
132  switch (undersampleStyle) {
133  case THROW_EXCEPTION:
134  LSST_EXCEPT_ADD(e, "setting _gridcolumns");
135  throw;
136  case REDUCE_INTERP_ORDER: {
137  if (gridTmp.empty()) {
138  // Set the column to NaN. We'll deal with this properly when interpolating in x
139  ycenTmp.push_back(0);
141 
142  intobj = makeInterpolate(ycenTmp, gridTmp, Interpolate::CONSTANT);
143  break;
144  } else {
145  return _setGridColumns(lookupMaxInterpStyle(gridTmp.size()), undersampleStyle, iX, ypix);
146  }
147  }
148  case INCREASE_NXNYSAMPLE:
150  e, "The BackgroundControl UndersampleStyle INCREASE_NXNYSAMPLE is not supported.");
151  throw;
152  default:
153  LSST_EXCEPT_ADD(e, str(boost::format("The selected BackgroundControl "
154  "UndersampleStyle %d is not defined.") %
155  undersampleStyle));
156  throw;
157  }
158  } catch (ex::Exception& e) {
159  LSST_EXCEPT_ADD(e, "setting _gridcolumns");
160  throw;
161  }
162 
163  for (int iY = 0; iY < height; ++iY) {
164  _gridColumns[iX][iY] = intobj->interpolate(ypix[iY]);
165  }
166 }
167 
169  _statsImage += delta;
170  return *this;
171 }
172 
174  _statsImage -= delta;
175  return *this;
176 }
177 
178 double BackgroundMI::getPixel(Interpolate::Style const interpStyle, int const x, int const y) const {
179  (void)getImage<InternalPixelT>(interpStyle); // setup the interpolation
180 
181  // build an interpobj along the row y and get the x'th value
182  int const nxSample = _statsImage.getWidth();
183  std::vector<double> bg_x(nxSample);
184  for (int iX = 0; iX < nxSample; iX++) {
185  bg_x[iX] = _gridColumns[iX][y];
186  }
187  std::vector<double> xcenTmp, bgTmp;
188  cullNan(_xcen, bg_x, xcenTmp, bgTmp);
189 
190  try {
191  std::shared_ptr<Interpolate> intobj = makeInterpolate(xcenTmp, bgTmp, interpStyle);
192  return static_cast<double>(intobj->interpolate(x));
193  } catch (ex::Exception& e) {
194  LSST_EXCEPT_ADD(e, "in getPixel()");
195  throw;
196  }
197 }
198 template <typename PixelT>
199 std::shared_ptr<image::Image<PixelT>> BackgroundMI::doGetImage(
200  geom::Box2I const& bbox,
201  Interpolate::Style const interpStyle_, // Style of the interpolation
202  UndersampleStyle const undersampleStyle // Behaviour if there are too few points
203  ) const {
204  if (!_imgBBox.contains(bbox)) {
205  throw LSST_EXCEPT(
207  str(boost::format("BBox (%d:%d,%d:%d) out of range (%d:%d,%d:%d)") % bbox.getMinX() %
208  bbox.getMaxX() % bbox.getMinY() % bbox.getMaxY() % _imgBBox.getMinX() %
210  }
211  int const nxSample = _statsImage.getWidth();
212  int const nySample = _statsImage.getHeight();
213  Interpolate::Style interpStyle = interpStyle_; // not const -- may be modified if REDUCE_INTERP_ORDER
214 
215  /*
216  * Save the as-used interpStyle and undersampleStyle.
217  *
218  * N.b. The undersampleStyle may actually be overridden for some columns of the statsImage if they
219  * have too few good values. This doesn't prevent you reproducing the results of getImage() by
220  * calling getImage(getInterpStyle(), getUndersampleStyle())
221  */
222  _asUsedInterpStyle = interpStyle;
223  _asUsedUndersampleStyle = undersampleStyle;
224  /*
225  * Check if the requested nx,ny are sufficient for the requested interpolation style,
226  * making suitable adjustments
227  */
228  bool const isXundersampled = (nxSample < lookupMinInterpPoints(interpStyle));
229  bool const isYundersampled = (nySample < lookupMinInterpPoints(interpStyle));
230 
231  switch (undersampleStyle) {
232  case THROW_EXCEPTION:
233  if (isXundersampled && isYundersampled) {
234  throw LSST_EXCEPT(
236  "nxSample and nySample have too few points for requested interpolation style.");
237  } else if (isXundersampled) {
239  "nxSample has too few points for requested interpolation style.");
240  } else if (isYundersampled) {
242  "nySample has too few points for requested interpolation style.");
243  }
244  break;
245  case REDUCE_INTERP_ORDER:
246  if (isXundersampled || isYundersampled) {
247  Interpolate::Style const xStyle = lookupMaxInterpStyle(nxSample);
248  Interpolate::Style const yStyle = lookupMaxInterpStyle(nySample);
249  interpStyle = (nxSample < nySample) ? xStyle : yStyle;
250  _asUsedInterpStyle = interpStyle;
251  }
252  break;
253  case INCREASE_NXNYSAMPLE:
254  if (isXundersampled || isYundersampled) {
255  throw LSST_EXCEPT(
257  "The BackgroundControl UndersampleStyle INCREASE_NXNYSAMPLE is not supported.");
258  }
259  break;
260  default:
262  str(boost::format("The selected BackgroundControl "
263  "UndersampleStyle %d is not defined.") %
264  undersampleStyle));
265  }
266 
267  // if we're approximating, don't bother with the rest of the interp-related work. Return from here.
268  if (_bctrl->getApproximateControl()->getStyle() != ApproximateControl::UNKNOWN) {
269  return doGetApproximate<PixelT>(*_bctrl->getApproximateControl(), _asUsedUndersampleStyle)
270  ->getImage();
271  }
272 
273  // =============================================================
274  // --> We'll store nxSample fully-interpolated columns to interpolate the rows over
275  // make a vector containing the y pixel coords for the column
276  int const width = _imgBBox.getWidth();
277  int const height = _imgBBox.getHeight();
278  auto const bboxOff = bbox.getMin() - _imgBBox.getMin();
279 
280  std::vector<int> ypix(height);
281  for (int iY = 0; iY < height; ++iY) {
282  ypix[iY] = iY;
283  }
284 
285  _gridColumns.resize(width);
286  for (int iX = 0; iX < nxSample; ++iX) {
287  _setGridColumns(interpStyle, undersampleStyle, iX, ypix);
288  }
289 
290  // create a shared_ptr to put the background image in and return to caller
291  // start with xy0 = 0 and set final xy0 later
294 
295  // go through row by row
296  // - interpolate on the gridcolumns that were pre-computed by the constructor
297  // - copy the values to an ImageT to return to the caller.
298  std::vector<double> xcenTmp, bgTmp;
299 
300  // N.b. There's no API to set defaultValue to other than NaN (due to issues with persistence
301  // that I don't feel like fixing; #2825). If we want to address this, this is the place
302  // to start, but note that NaN is treated specially -- it means, "Interpolate" so to allow
303  // us to put a NaN into the outputs some changes will be needed
304  double defaultValue = std::numeric_limits<double>::quiet_NaN();
305 
306  for (int y = 0, iY = bboxOff.getY(); y < bbox.getHeight(); ++y, ++iY) {
307  // build an interp object for this row
308  std::vector<double> bg_x(nxSample);
309  for (int iX = 0; iX < nxSample; iX++) {
310  bg_x[iX] = static_cast<double>(_gridColumns[iX][iY]);
311  }
312  cullNan(_xcen, bg_x, xcenTmp, bgTmp, defaultValue);
313 
315  try {
316  intobj = makeInterpolate(xcenTmp, bgTmp, interpStyle);
317  } catch (pex::exceptions::OutOfRangeError& e) {
318  switch (undersampleStyle) {
319  case THROW_EXCEPTION:
320  LSST_EXCEPT_ADD(e, str(boost::format("Interpolating in y (iY = %d)") % iY));
321  throw;
322  case REDUCE_INTERP_ORDER: {
323  if (bgTmp.empty()) {
324  xcenTmp.push_back(0);
325  bgTmp.push_back(defaultValue);
326 
327  intobj = makeInterpolate(xcenTmp, bgTmp, Interpolate::CONSTANT);
328  break;
329  } else {
330  intobj = makeInterpolate(xcenTmp, bgTmp, lookupMaxInterpStyle(bgTmp.size()));
331  }
332  } break;
333  case INCREASE_NXNYSAMPLE:
335  e,
336  "The BackgroundControl UndersampleStyle INCREASE_NXNYSAMPLE is not supported.");
337  throw;
338  default:
339  LSST_EXCEPT_ADD(e, str(boost::format("The selected BackgroundControl "
340  "UndersampleStyle %d is not defined.") %
341  undersampleStyle));
342  throw;
343  }
344  } catch (ex::Exception& e) {
345  LSST_EXCEPT_ADD(e, str(boost::format("Interpolating in y (iY = %d)") % iY));
346  throw;
347  }
348 
349  // fill the image with interpolated values
350  for (int iX = bboxOff.getX(), x = 0; x < bbox.getWidth(); ++iX, ++x) {
351  (*bg)(x, y) = static_cast<PixelT>(intobj->interpolate(iX));
352  }
353  }
354  bg->setXY0(bbox.getMin());
355 
356  return bg;
357 }
358 
359 template <typename PixelT>
360 std::shared_ptr<Approximate<PixelT>> BackgroundMI::doGetApproximate(
361  ApproximateControl const& actrl, /* Approximation style */
362  UndersampleStyle const undersampleStyle /* Behaviour if there are too few points */
363  ) const {
364  auto const localBBox = afw::geom::Box2I(afw::geom::Point2I(0, 0), _imgBBox.getDimensions());
365  return makeApproximate(_xcen, _ycen, _statsImage, localBBox, actrl);
366 }
367 
369 /*
370  * Create the versions we need of _get{Approximate,Image} and Explicit instantiations
371  *
372  */
373 #define CREATE_BACKGROUND(m, v, TYPE) \
374  template BackgroundMI::BackgroundMI(image::Image<TYPE> const& img, BackgroundControl const& bgCtrl); \
375  template BackgroundMI::BackgroundMI(image::MaskedImage<TYPE> const& img, \
376  BackgroundControl const& bgCtrl); \
377  std::shared_ptr<image::Image<TYPE>> BackgroundMI::_getImage( \
378  geom::Box2I const& bbox, Interpolate::Style const interpStyle, /* Style of the interpolation */ \
379  UndersampleStyle const undersampleStyle, /* Behaviour if there are too few points */ \
380  TYPE /* disambiguate */ \
381  ) const { \
382  return BackgroundMI::doGetImage<TYPE>(bbox, interpStyle, undersampleStyle); \
383  }
384 
385 #define CREATE_getApproximate(m, v, TYPE) \
386  std::shared_ptr<Approximate<TYPE>> BackgroundMI::_getApproximate( \
387  ApproximateControl const& actrl, /* Approximation style */ \
388  UndersampleStyle const undersampleStyle, /* Behaviour if there are too few points */ \
389  TYPE /* disambiguate */ \
390  ) const { \
391  return BackgroundMI::doGetApproximate<TYPE>(actrl, undersampleStyle); \
392  }
393 
394 BOOST_PP_SEQ_FOR_EACH(CREATE_BACKGROUND, , LSST_makeBackground_getImage_types)
395 BOOST_PP_SEQ_FOR_EACH(CREATE_getApproximate, , LSST_makeBackground_getApproximate_types)
396 
397 }
399 }
400 } // lsst::afw::math
std::vector< int > _xsize
x size of sub images
Definition: Background.h:371
VariancePtr getVariance() const
Return a (shared_ptr to) the MaskedImage&#39;s variance.
Definition: MaskedImage.h:1074
Point2I const getMin() const
Definition: Box.h:123
std::vector< double > _xcen
x center pix coords of sub images
Definition: Background.h:367
T empty(T... args)
T copy(T... args)
std::vector< int > _yorig
y origin ...
Definition: Background.h:370
int getMinX() const
Definition: Box.h:124
Property getStatisticsProperty() const
Definition: Background.h:213
BackgroundMI(ImageT const &img, BackgroundControl const &bgCtrl)
Constructor for BackgroundMI.
Definition: BackgroundMI.cc:81
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
geom::Box2I _imgBBox
size and origin of input image
Definition: Background.h:362
#define LSST_makeBackground_getApproximate_types
Definition: Background.h:384
std::vector< double > _ycen
y center ...
Definition: Background.h:368
T end(T... args)
int getHeight() const
Definition: Box.h:155
std::shared_ptr< Approximate< PixelT > > makeApproximate(std::vector< double > const &x, std::vector< double > const &y, image::MaskedImage< PixelT > const &im, 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:234
An integer coordinate rectangle.
Definition: Box.h:55
T resize(T... args)
ImagePtr getImage() const
Return a (shared_ptr to) the MaskedImage&#39;s image.
Definition: MaskedImage.h:1041
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:328
y_iterator col_begin(int x) const
Return an y_iterator to the start of the y&#39;th row.
Definition: ImageBase.h:414
Control how to make an approximation.
Definition: Approximate.h:50
int getHeight() const
Return the number of rows in the image.
Definition: MaskedImage.h:1079
Interpolate::Style _asUsedInterpStyle
the style we actually used
Definition: Background.h:364
A base class for image defects.
std::shared_ptr< StatisticsControl > getStatisticsControl()
Definition: Background.h:210
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:348
T capacity(T... args)
y_iterator col_end(int x) const
Return an y_iterator to the start of the y&#39;th row.
Definition: ImageBase.h:417
double x
T clear(T... args)
int getWidth() const
Definition: Box.h:154
bool contains(Point2I const &point) const
Return true if the box contains the point.
#define LSST_makeBackground_getImage_types
Definition: Background.h:383
Interpolate::Style lookupMaxInterpStyle(int const n)
Get the highest order Interpolation::Style available for &#39;n&#39; points.
Definition: Interpolate.cc:275
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,...)
T begin(T... args)
std::vector< int > _xorig
x origin pix coords of sub images
Definition: Background.h:369
Extent2I const getDimensions() const
Definition: Box.h:153
int getMaxX() const
Definition: Box.h:128
std::shared_ptr< BackgroundControl > _bctrl
control info set by user.
Definition: Background.h:363
std::vector< int > _ysize
y size ...
Definition: Background.h:372
UndersampleStyle _asUsedUndersampleStyle
the undersampleStyle we actually used
Definition: Background.h:365
T isnan(T... args)
virtual BackgroundMI & operator+=(float const delta)
Add a scalar to the Background (equivalent to adding a constant to the original image) ...
int getWidth() const
Return the number of columns in the image.
Definition: MaskedImage.h:1077
int getMaxY() const
Definition: Box.h:129
T quiet_NaN(T... args)
A class to evaluate image background levels.
Definition: Background.h:436
int getMinY() const
Definition: Box.h:125
virtual BackgroundMI & operator-=(float const delta)
Subtract a scalar from the Background (equivalent to subtracting a constant from the original image) ...
#define LSST_EXCEPT_ADD(e, m)
A class to represent a 2-dimensional array of pixels.
Definition: Image.h:68
double getPixel(Interpolate::Style const style, int const x, int const y) const
Method to retrieve the background level at a pixel coord.
T reserve(T... args)