LSSTApplications  11.0-13-gbb96280,12.1+18,12.1+7,12.1-1-g14f38d3+72,12.1-1-g16c0db7+5,12.1-1-g5961e7a+84,12.1-1-ge22e12b+23,12.1-11-g06625e2+4,12.1-11-g0d7f63b+4,12.1-19-gd507bfc,12.1-2-g7dda0ab+38,12.1-2-gc0bc6ab+81,12.1-21-g6ffe579+2,12.1-21-gbdb6c2a+4,12.1-24-g941c398+5,12.1-3-g57f6835+7,12.1-3-gf0736f3,12.1-37-g3ddd237,12.1-4-gf46015e+5,12.1-5-g06c326c+20,12.1-5-g648ee80+3,12.1-5-gc2189d7+4,12.1-6-ga608fc0+1,12.1-7-g3349e2a+5,12.1-7-gfd75620+9,12.1-9-g577b946+5,12.1-9-gc4df26a+10
LSSTDataManagementBasePackage
Interpolate.cc
Go to the documentation of this file.
1 // -*- LSST-C++ -*-
2 
3 /*
4  * LSST Data Management System
5  * Copyright 2008, 2009, 2010 LSST Corporation.
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 <http://www.lsstcorp.org/LegalNotices/>.
23  */
24 
30 #include <limits>
31 #include <algorithm>
32 #include <map>
33 #include "boost/format.hpp"
34 #include <memory>
35 #include "gsl/gsl_errno.h"
36 #include "gsl/gsl_interp.h"
37 #include "gsl/gsl_spline.h"
38 #include "ndarray.h"
39 #include "lsst/pex/exceptions.h"
41 
42 namespace lsst {
43 namespace afw {
44 namespace math {
45 
46 /************************************************************************************************************/
47 
48 namespace {
49  std::pair<std::vector<double>, std::vector<double> >
50  recenter(std::vector<double> const &x,
51  std::vector<double> const &y)
52  {
53  if (x.size() != y.size()) {
54  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
55  str(boost::format("Dimensions of x and y must match; %ul != %ul")
56  % x.size() % y.size()));
57  }
58  std::size_t const len = x.size();
59  if (len == 0) {
60  throw LSST_EXCEPT(pex::exceptions::OutOfRangeError,
61  "You must provide at least 1 point");
62  } else if (len == 1) {
63  return std::make_pair(x, y);
64  }
65 
66  std::vector<double> recentered_x(len + 1);
67  std::vector<double> recentered_y(len + 1);
68 
69  recentered_x[0] = 0.5*(3*x[0] - x[1]);
70  recentered_y[0] = y[0];
71 
72  for (std::size_t i = 0, j = 1; i < len - 1; ++i, ++j) {
73  recentered_x[j] = 0.5*(x[i] + x[i + 1]);
74  recentered_y[j] = 0.5*(y[i] + y[i + 1]);
75  }
76  recentered_x[len] = 0.5*(3*x[len - 1] - x[len - 2]);
77  recentered_y[len] = y[len - 1];
78 
79  return std::make_pair(recentered_x, recentered_y);
80  }
81 }
82 
84  friend PTR(Interpolate) makeInterpolate(std::vector<double> const &x, std::vector<double> const &y,
85  Interpolate::Style const style);
86 public:
87  virtual ~InterpolateConstant() {}
88  virtual double interpolate(double const x) const;
89 private:
90  InterpolateConstant(std::vector<double> const &x,
91  std::vector<double> const &y,
92  Interpolate::Style const style
93  ) :
94  Interpolate(recenter(x, y)), _old(_x.begin()) {}
95  mutable std::vector<double>::const_iterator _old; // last position we found xInterp at
96 };
97 
98 
100 double InterpolateConstant::interpolate(double const xInterp // the value we want to interpolate to
101  ) const
102 {
103  //
104  // Look for the interval wherein lies xInterp. We could naively use std::upper_bound, but that requires a
105  // logarithmic time lookup so we'll cache the previous answer in _old -- this is a good idea if people
106  // usually call this routine repeatedly for a range of x
107  //
108  // We start by searching up from _old
109  //
110  if (xInterp < *_old) { // We're to the left of the cache
111  if (_old == _x.begin()) { // ... actually off the array
112  return _y[0];
113  }
114  _old = _x.begin(); // reset the cached point to the start of the array
115  } else { // see if we're still in the same interval
116  if (_old < _x.end() - 1 and xInterp < *(_old + 1)) { // we are, so we're done
117  return _y[_old - _x.begin()];
118  }
119  }
120  // We're to the right of the cached point and not in the same inverval, so search up from _old
121  std::vector<double>::const_iterator low = std::upper_bound(_old, _x.end(), xInterp);
122  //
123  // Did that work?
124  if (low == _old && _old != _x.begin()) {
125  // No. Sigh. Search the entire range.
126  low = std::upper_bound(_x.begin(), low + 1, xInterp);
127  }
128  //
129  // OK, we've found the right interval. Return the desired value, being careful at the ends
130  //
131  if (low == _x.end()) {
132  return _y[_y.size() - 1];
133  } else if (low == _x.begin()) {
134  return _y[0];
135  } else {
136  --low;
137  _old = low;
138  return _y[low - _x.begin()];
139  }
140 }
141 
142 /************************************************************************************************************/
143 namespace {
144 /*
145  * Conversion function to switch an Interpolate::Style to a gsl_interp_type.
146  */
147 ::gsl_interp_type const *
148 styleToGslInterpType(Interpolate::Style const style)
149 {
150  switch (style) {
152  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, "CONSTANT interpolation not supported.");
153  case Interpolate::LINEAR:
154  return ::gsl_interp_linear;
156  return ::gsl_interp_cspline;
158  return ::gsl_interp_cspline;
160  return ::gsl_interp_cspline_periodic;
162  return ::gsl_interp_akima;
164  return ::gsl_interp_akima_periodic;
166  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
167  "I am unable to make an interpolator of type UNKNOWN");
169  throw LSST_EXCEPT(pex::exceptions::LogicError,
170  str(boost::format("You can't get here: style == %") % style));
171  }
172 }
173 }
174 
175 class InterpolateGsl : public Interpolate {
176  friend PTR(Interpolate) makeInterpolate(std::vector<double> const &x, std::vector<double> const &y,
177  Interpolate::Style const style);
178 public:
179  virtual ~InterpolateGsl();
180  virtual double interpolate(double const x) const;
181 private:
182  InterpolateGsl(std::vector<double> const &x, std::vector<double> const &y, Interpolate::Style const style);
183 
184  ::gsl_interp_type const *_interpType;
185  ::gsl_interp_accel *_acc;
186  ::gsl_interp *_interp;
187 };
188 
189 InterpolateGsl::InterpolateGsl(std::vector<double> const &x,
190  std::vector<double> const &y,
191  Interpolate::Style const style
192  ) :
193  Interpolate(x, y), _interpType(styleToGslInterpType(style))
194 {
195  _acc = ::gsl_interp_accel_alloc();
196  if (!_acc) {
197  throw LSST_EXCEPT(pex::exceptions::MemoryError, "gsl_interp_accel_alloc failed");
198  }
199 
200  _interp = ::gsl_interp_alloc(_interpType, _y.size());
201  if (!_interp) {
202  throw LSST_EXCEPT(pex::exceptions::OutOfRangeError,
203  str(boost::format("Failed to initialise spline for type %s, length %d")
204  % _interpType->name % _y.size()));
205 
206  }
207  // Note, "x" and "y" are vector<double>; gsl_inter_init requires double[].
208  // The &(x[0]) here is valid because std::vector guarantees that the values are
209  // stored contiguously in memory (for types other than bool); C++0X 23.3.6.1 for
210  // those of you reading along.
211  int const status = ::gsl_interp_init(_interp, &x[0], &y[0], _y.size());
212  if (status != 0) {
213  throw LSST_EXCEPT(pex::exceptions::RuntimeError,
214  str(boost::format("gsl_interp_init failed: %s [%d]")
215  % ::gsl_strerror(status) % status));
216  }
217 }
218 
220  ::gsl_interp_free(_interp);
221  ::gsl_interp_accel_free(_acc);
222 }
223 
224 double InterpolateGsl::interpolate(double const xInterp) const
225 {
226  // New GSL versions refuse to extrapolate.
227  // gsl_interp_init() requires x to be ordered, so can just check
228  // the array endpoints for out-of-bounds.
229  if ((xInterp < _x.front() || (xInterp > _x.back()))) {
230  // do our own quadratic extrapolation.
231  // (GSL only provides first and second derivative functions)
232  /* could also just fail via:
233  throw LSST_EXCEPT(
234  pex::exceptions::InvalidParameterError,
235  (boost::format("Interpolation point %f outside range [%f, %f]")
236  % x % _x.front() % _x.back()).str()
237  );
238  */
239  double x0, y0;
240  if (xInterp < _x.front()) {
241  x0 = _x.front();
242  y0 = _y.front();
243  } else {
244  x0 = _x.back();
245  y0 = _y.back();
246  }
247  // first derivative at endpoint
248  double d = ::gsl_interp_eval_deriv(_interp, &_x[0], &_y[0], x0, _acc);
249  // second derivative at endpoint
250  double d2 = ::gsl_interp_eval_deriv2(_interp, &_x[0], &_y[0], x0, _acc);
251  return y0 + (xInterp - x0)*d + 0.5*(xInterp - x0)*(xInterp - x0)*d2;
252  }
253  assert(xInterp >= _x.front());
254  assert(xInterp <= _x.back());
255  return ::gsl_interp_eval(_interp, &_x[0], &_y[0], xInterp, _acc);
256 }
257 
258 /************************************************************************************************************/
263 Interpolate::Style stringToInterpStyle(std::string const &style
264  )
265 {
266  static std::map<std::string, Interpolate::Style> gslInterpTypeStrings;
267  if (gslInterpTypeStrings.empty()) {
268  gslInterpTypeStrings["CONSTANT"] = Interpolate::CONSTANT;
269  gslInterpTypeStrings["LINEAR"] = Interpolate::LINEAR;
270  gslInterpTypeStrings["CUBIC_SPLINE"] = Interpolate::CUBIC_SPLINE;
271  gslInterpTypeStrings["NATURAL_SPLINE"] = Interpolate::NATURAL_SPLINE;
272  gslInterpTypeStrings["CUBIC_SPLINE_PERIODIC"] = Interpolate::CUBIC_SPLINE_PERIODIC;
273  gslInterpTypeStrings["AKIMA_SPLINE"] = Interpolate::AKIMA_SPLINE;
274  gslInterpTypeStrings["AKIMA_SPLINE_PERIODIC"] = Interpolate::AKIMA_SPLINE_PERIODIC;
275  }
276 
277  if ( gslInterpTypeStrings.find(style) == gslInterpTypeStrings.end()) {
278  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, "Interp style not found: "+style);
279  }
280  return gslInterpTypeStrings[style];
281 }
282 
287  ) {
288  if (n < 1) {
289  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, "n must be greater than 0");
290  } else if (n > 4) {
292  } else {
293  static std::vector<Interpolate::Style> styles;
294  if (styles.empty()) {
295  styles.resize(5);
296 
297  styles[0] = Interpolate::UNKNOWN; // impossible to reach as we check for n < 1
298  styles[1] = Interpolate::CONSTANT;
299  styles[2] = Interpolate::LINEAR;
300  styles[3] = Interpolate::CUBIC_SPLINE;
301  styles[4] = Interpolate::CUBIC_SPLINE;
302  }
303  return styles[n];
304  }
305 }
306 
307 std::vector<double> Interpolate::interpolate(std::vector<double> const& x) const
308 {
309  size_t const num = x.size();
310  std::vector<double> out(num);
311  for (size_t i = 0; i < num; ++i) {
312  out[i] = interpolate(x[i]);
313  }
314  return out;
315 }
316 
317 ndarray::Array<double, 1> Interpolate::interpolate(ndarray::Array<double const, 1> const& x) const
318 {
319  int const num = x.getShape()[0];
320  ndarray::Array<double, 1> out = ndarray::allocate(ndarray::makeVector(num));
321  for (size_t i = 0; i < num; ++i) {
322  std::cout << "Interpolating " << x[i] << std::endl;
323  out[i] = interpolate(x[i]);
324  }
325  return out;
326 }
327 
332  ) {
333  static std::vector<int> minPoints;
334  if (minPoints.empty()) {
335  minPoints.resize(Interpolate::NUM_STYLES);
336  minPoints[Interpolate::CONSTANT] = 1;
337  minPoints[Interpolate::LINEAR] = 2;
338  minPoints[Interpolate::NATURAL_SPLINE] = 3;
339  minPoints[Interpolate::CUBIC_SPLINE] = 3;
340  minPoints[Interpolate::CUBIC_SPLINE_PERIODIC] = 3;
341  minPoints[Interpolate::AKIMA_SPLINE] = 5;
342  minPoints[Interpolate::AKIMA_SPLINE_PERIODIC] = 5;
343  }
344 
345  if (style >= 0 && style < Interpolate::NUM_STYLES) {
346  return minPoints[style];
347  } else {
348  throw LSST_EXCEPT(pex::exceptions::OutOfRangeError,
349  str(boost::format("Style %d is out of range 0..%d")
350  % style % (Interpolate::NUM_STYLES - 1)));
351  }
352 }
353 
354 /************************************************************************************************************/
364  std::pair<std::vector<double>, std::vector<double> > const xy,
365  Interpolate::Style const style
367  ) : _x(xy.first), _y(xy.second), _style(style)
368 {
369  ;
370 }
371 
375 PTR(Interpolate) makeInterpolate(std::vector<double> const &x,
376  std::vector<double> const &y,
377  Interpolate::Style const style
378  )
379 {
380  switch (style) {
382  return PTR(Interpolate)(new InterpolateConstant(x, y, style));
383  default: // use GSL
384  return PTR(Interpolate)(new InterpolateGsl(x, y, style));
385  }
386 }
387 
388 PTR(Interpolate) makeInterpolate(ndarray::Array<double const, 1> const &x,
389  ndarray::Array<double const, 1> const &y,
390  Interpolate::Style const style)
391 {
392  return makeInterpolate(std::vector<double>(x.begin(), x.end()), std::vector<double>(y.begin(), y.end()),
393  style);
394 }
395 
396 }}}
int y
Interpolate::Style stringToInterpStyle(std::string const &style)
Conversion function to switch a string to an Interpolate::Style.
Definition: Interpolate.cc:263
Interpolate values for a set of x,y vector&lt;&gt;s.
Definition: Interpolate.h:38
std::vector< double >::const_iterator _old
Definition: Interpolate.cc:95
virtual double interpolate(double const x) const
Interpolate a constant to the point xInterp.
Definition: Interpolate.cc:100
friend boost::shared_ptr< Interpolate > makeInterpolate(std::vector< double > const &x, std::vector< double > const &y, Interpolate::Style const style)
A factory function to make Interpolate objects.
Definition: Interpolate.cc:375
virtual double interpolate(double const x) const =0
Include files required for standard LSST Exception handling.
virtual double interpolate(double const x) const
Definition: Interpolate.cc:224
boost::shared_ptr< Interpolate > makeInterpolate(std::vector< double > const &x, std::vector< double > const &y, Interpolate::Style const style)
A factory function to make Interpolate objects.
Definition: Interpolate.cc:375
int const x0
Definition: saturated.cc:45
::gsl_interp_type const * _interpType
Definition: Interpolate.cc:184
metadata import lsst afw display as afwDisplay n
::gsl_interp_accel * _acc
Definition: Interpolate.cc:185
double x
std::vector< double > const _x
Definition: Interpolate.h:70
InterpolateConstant(std::vector< double > const &x, std::vector< double > const &y, Interpolate::Style const style)
Definition: Interpolate.cc:90
InterpolateGsl(std::vector< double > const &x, std::vector< double > const &y, Interpolate::Style const style)
Definition: Interpolate.cc:189
Interpolate::Style lookupMaxInterpStyle(int const n)
Get the highest order Interpolation::Style available for &#39;n&#39; points.
Definition: Interpolate.cc:286
int lookupMinInterpPoints(Interpolate::Style const style)
Get the minimum number of points needed to use the requested interpolation style. ...
Definition: Interpolate.cc:331
#define LSST_EXCEPT(type,...)
Create an exception with a given type and message and optionally other arguments (dependent on the ty...
Definition: Exception.h:46
Interpolate(std::vector< double > const &x, std::vector< double > const &y, Interpolate::Style const style=UNKNOWN)
Base class ctor.
Definition: Interpolate.h:63
friend boost::shared_ptr< Interpolate > makeInterpolate(std::vector< double > const &x, std::vector< double > const &y, Interpolate::Style const style)
A factory function to make Interpolate objects.
Definition: Interpolate.cc:375
int status
#define PTR(...)
Definition: base.h:41
std::vector< double > const _y
Definition: Interpolate.h:71
int const y0
Definition: saturated.cc:45