lsst.afw  13.0-49-g6f23dda
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
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 
25 /*
26  * Interpolate values for a set of x,y vector<>s
27  */
28 #include <limits>
29 #include <algorithm>
30 #include <map>
31 #include "boost/format.hpp"
32 #include <memory>
33 #include "gsl/gsl_errno.h"
34 #include "gsl/gsl_interp.h"
35 #include "gsl/gsl_spline.h"
36 #include "ndarray.h"
37 #include "lsst/pex/exceptions.h"
39 
40 namespace lsst {
41 namespace afw {
42 namespace math {
43 
44 namespace {
45 std::pair<std::vector<double>, std::vector<double> > recenter(std::vector<double> const &x,
46  std::vector<double> const &y) {
47  if (x.size() != y.size()) {
48  throw LSST_EXCEPT(
49  pex::exceptions::InvalidParameterError,
50  str(boost::format("Dimensions of x and y must match; %ul != %ul") % x.size() % y.size()));
51  }
52  std::size_t const len = x.size();
53  if (len == 0) {
54  throw LSST_EXCEPT(pex::exceptions::OutOfRangeError, "You must provide at least 1 point");
55  } else if (len == 1) {
56  return std::make_pair(x, y);
57  }
58 
59  std::vector<double> recentered_x(len + 1);
60  std::vector<double> recentered_y(len + 1);
61 
62  recentered_x[0] = 0.5 * (3 * x[0] - x[1]);
63  recentered_y[0] = y[0];
64 
65  for (std::size_t i = 0, j = 1; i < len - 1; ++i, ++j) {
66  recentered_x[j] = 0.5 * (x[i] + x[i + 1]);
67  recentered_y[j] = 0.5 * (y[i] + y[i + 1]);
68  }
69  recentered_x[len] = 0.5 * (3 * x[len - 1] - x[len - 2]);
70  recentered_y[len] = y[len - 1];
71 
72  return std::make_pair(recentered_x, recentered_y);
73 }
74 }
75 
77  friend std::shared_ptr<Interpolate> makeInterpolate(std::vector<double> const &x,
78  std::vector<double> const &y,
79  Interpolate::Style const style);
80 
81 public:
82  virtual ~InterpolateConstant() {}
83  virtual double interpolate(double const x) const;
84 
85 private:
86  InterpolateConstant(std::vector<double> const &x,
87  std::vector<double> const &y,
88  Interpolate::Style const style
89  )
90  : Interpolate(recenter(x, y)), _old(_x.begin()) {}
91  mutable std::vector<double>::const_iterator _old; // last position we found xInterp at
92 };
93 
95 double InterpolateConstant::interpolate(double const xInterp // the value we want to interpolate to
96  ) const {
97  //
98  // Look for the interval wherein lies xInterp. We could naively use std::upper_bound, but that requires a
99  // logarithmic time lookup so we'll cache the previous answer in _old -- this is a good idea if people
100  // usually call this routine repeatedly for a range of x
101  //
102  // We start by searching up from _old
103  //
104  if (xInterp < *_old) { // We're to the left of the cache
105  if (_old == _x.begin()) { // ... actually off the array
106  return _y[0];
107  }
108  _old = _x.begin(); // reset the cached point to the start of the array
109  } else { // see if we're still in the same interval
110  if (_old < _x.end() - 1 and xInterp < *(_old + 1)) { // we are, so we're done
111  return _y[_old - _x.begin()];
112  }
113  }
114  // We're to the right of the cached point and not in the same inverval, so search up from _old
115  std::vector<double>::const_iterator low = std::upper_bound(_old, _x.end(), xInterp);
116  //
117  // Did that work?
118  if (low == _old && _old != _x.begin()) {
119  // No. Sigh. Search the entire range.
120  low = std::upper_bound(_x.begin(), low + 1, xInterp);
121  }
122  //
123  // OK, we've found the right interval. Return the desired value, being careful at the ends
124  //
125  if (low == _x.end()) {
126  return _y[_y.size() - 1];
127  } else if (low == _x.begin()) {
128  return _y[0];
129  } else {
130  --low;
131  _old = low;
132  return _y[low - _x.begin()];
133  }
134 }
135 
136 namespace {
137 /*
138  * Conversion function to switch an Interpolate::Style to a gsl_interp_type.
139  */
140 ::gsl_interp_type const *styleToGslInterpType(Interpolate::Style const style) {
141  switch (style) {
143  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
144  "CONSTANT interpolation not supported.");
145  case Interpolate::LINEAR:
146  return ::gsl_interp_linear;
148  return ::gsl_interp_cspline;
150  return ::gsl_interp_cspline;
152  return ::gsl_interp_cspline_periodic;
154  return ::gsl_interp_akima;
156  return ::gsl_interp_akima_periodic;
158  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
159  "I am unable to make an interpolator of type UNKNOWN");
161  throw LSST_EXCEPT(pex::exceptions::LogicError,
162  str(boost::format("You can't get here: style == %") % style));
163  }
164 }
165 }
166 
167 class InterpolateGsl : public Interpolate {
168  friend std::shared_ptr<Interpolate> makeInterpolate(std::vector<double> const &x,
169  std::vector<double> const &y,
170  Interpolate::Style const style);
171 
172 public:
173  virtual ~InterpolateGsl();
174  virtual double interpolate(double const x) const;
175 
176 private:
177  InterpolateGsl(std::vector<double> const &x, std::vector<double> const &y,
178  Interpolate::Style const style);
179 
180  ::gsl_interp_type const *_interpType;
181  ::gsl_interp_accel *_acc;
182  ::gsl_interp *_interp;
183 };
184 
185 InterpolateGsl::InterpolateGsl(std::vector<double> const &x,
186  std::vector<double> const &y,
187  Interpolate::Style const style
188  )
189  : Interpolate(x, y), _interpType(styleToGslInterpType(style)) {
190  // Turn the gsl error handler off, we want to use our own exceptions
191  ::gsl_set_error_handler_off();
192 
193  _acc = ::gsl_interp_accel_alloc();
194  if (!_acc) {
195  throw LSST_EXCEPT(pex::exceptions::MemoryError, "gsl_interp_accel_alloc failed");
196  }
197 
198  _interp = ::gsl_interp_alloc(_interpType, _y.size());
199  if (!_interp) {
200  throw LSST_EXCEPT(pex::exceptions::OutOfRangeError,
201  str(boost::format("Failed to initialise spline for type %s, length %d") %
202  _interpType->name % _y.size()));
203  }
204  // Note, "x" and "y" are vector<double>; gsl_inter_init requires double[].
205  // The &(x[0]) here is valid because std::vector guarantees that the values are
206  // stored contiguously in memory (for types other than bool); C++0X 23.3.6.1 for
207  // those of you reading along.
208  int const status = ::gsl_interp_init(_interp, &x[0], &y[0], _y.size());
209  if (status != 0) {
210  throw LSST_EXCEPT(
211  pex::exceptions::RuntimeError,
212  str(boost::format("gsl_interp_init failed: %s [%d]") % ::gsl_strerror(status) % status));
213  }
214 }
215 
217  ::gsl_interp_free(_interp);
218  ::gsl_interp_accel_free(_acc);
219 }
220 
221 double InterpolateGsl::interpolate(double const xInterp) const {
222  // New GSL versions refuse to extrapolate.
223  // gsl_interp_init() requires x to be ordered, so can just check
224  // the array endpoints for out-of-bounds.
225  if ((xInterp < _x.front() || (xInterp > _x.back()))) {
226  // do our own quadratic extrapolation.
227  // (GSL only provides first and second derivative functions)
228  /* could also just fail via:
229  throw LSST_EXCEPT(
230  pex::exceptions::InvalidParameterError,
231  (boost::format("Interpolation point %f outside range [%f, %f]")
232  % x % _x.front() % _x.back()).str()
233  );
234  */
235  double x0, y0;
236  if (xInterp < _x.front()) {
237  x0 = _x.front();
238  y0 = _y.front();
239  } else {
240  x0 = _x.back();
241  y0 = _y.back();
242  }
243  // first derivative at endpoint
244  double d = ::gsl_interp_eval_deriv(_interp, &_x[0], &_y[0], x0, _acc);
245  // second derivative at endpoint
246  double d2 = ::gsl_interp_eval_deriv2(_interp, &_x[0], &_y[0], x0, _acc);
247  return y0 + (xInterp - x0) * d + 0.5 * (xInterp - x0) * (xInterp - x0) * d2;
248  }
249  assert(xInterp >= _x.front());
250  assert(xInterp <= _x.back());
251  return ::gsl_interp_eval(_interp, &_x[0], &_y[0], xInterp, _acc);
252 }
253 
254 Interpolate::Style stringToInterpStyle(std::string const &style) {
255  static std::map<std::string, Interpolate::Style> gslInterpTypeStrings;
256  if (gslInterpTypeStrings.empty()) {
257  gslInterpTypeStrings["CONSTANT"] = Interpolate::CONSTANT;
258  gslInterpTypeStrings["LINEAR"] = Interpolate::LINEAR;
259  gslInterpTypeStrings["CUBIC_SPLINE"] = Interpolate::CUBIC_SPLINE;
260  gslInterpTypeStrings["NATURAL_SPLINE"] = Interpolate::NATURAL_SPLINE;
261  gslInterpTypeStrings["CUBIC_SPLINE_PERIODIC"] = Interpolate::CUBIC_SPLINE_PERIODIC;
262  gslInterpTypeStrings["AKIMA_SPLINE"] = Interpolate::AKIMA_SPLINE;
263  gslInterpTypeStrings["AKIMA_SPLINE_PERIODIC"] = Interpolate::AKIMA_SPLINE_PERIODIC;
264  }
265 
266  if (gslInterpTypeStrings.find(style) == gslInterpTypeStrings.end()) {
267  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, "Interp style not found: " + style);
268  }
269  return gslInterpTypeStrings[style];
270 }
271 
273  if (n < 1) {
274  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, "n must be greater than 0");
275  } else if (n > 4) {
277  } else {
278  static std::vector<Interpolate::Style> styles;
279  if (styles.empty()) {
280  styles.resize(5);
281 
282  styles[0] = Interpolate::UNKNOWN; // impossible to reach as we check for n < 1
283  styles[1] = Interpolate::CONSTANT;
284  styles[2] = Interpolate::LINEAR;
285  styles[3] = Interpolate::CUBIC_SPLINE;
286  styles[4] = Interpolate::CUBIC_SPLINE;
287  }
288  return styles[n];
289  }
290 }
291 
292 std::vector<double> Interpolate::interpolate(std::vector<double> const &x) const {
293  size_t const num = x.size();
294  std::vector<double> out(num);
295  for (size_t i = 0; i < num; ++i) {
296  out[i] = interpolate(x[i]);
297  }
298  return out;
299 }
300 
301 ndarray::Array<double, 1> Interpolate::interpolate(ndarray::Array<double const, 1> const &x) const {
302  int const num = x.getShape()[0];
303  ndarray::Array<double, 1> out = ndarray::allocate(ndarray::makeVector(num));
304  for (size_t i = 0; i < num; ++i) {
305  std::cout << "Interpolating " << x[i] << std::endl;
306  out[i] = interpolate(x[i]);
307  }
308  return out;
309 }
310 
312  static std::vector<int> minPoints;
313  if (minPoints.empty()) {
314  minPoints.resize(Interpolate::NUM_STYLES);
315  minPoints[Interpolate::CONSTANT] = 1;
316  minPoints[Interpolate::LINEAR] = 2;
317  minPoints[Interpolate::NATURAL_SPLINE] = 3;
318  minPoints[Interpolate::CUBIC_SPLINE] = 3;
319  minPoints[Interpolate::CUBIC_SPLINE_PERIODIC] = 3;
320  minPoints[Interpolate::AKIMA_SPLINE] = 5;
321  minPoints[Interpolate::AKIMA_SPLINE_PERIODIC] = 5;
322  }
323 
324  if (style >= 0 && style < Interpolate::NUM_STYLES) {
325  return minPoints[style];
326  } else {
327  throw LSST_EXCEPT(
328  pex::exceptions::OutOfRangeError,
329  str(boost::format("Style %d is out of range 0..%d") % style % (Interpolate::NUM_STYLES - 1)));
330  }
331 }
332 
333 Interpolate::Interpolate(std::pair<std::vector<double>, std::vector<double> > const xy,
334 
335  Interpolate::Style const style)
336  : _x(xy.first), _y(xy.second), _style(style) {
337  ;
338 }
339 
340 std::shared_ptr<Interpolate> makeInterpolate(std::vector<double> const &x, std::vector<double> const &y,
341  Interpolate::Style const style) {
342  switch (style) {
344  return std::shared_ptr<Interpolate>(new InterpolateConstant(x, y, style));
345  default: // use GSL
346  return std::shared_ptr<Interpolate>(new InterpolateGsl(x, y, style));
347  }
348 }
349 
350 std::shared_ptr<Interpolate> makeInterpolate(ndarray::Array<double const, 1> const &x,
351  ndarray::Array<double const, 1> const &y,
352  Interpolate::Style const style) {
353  return makeInterpolate(std::vector<double>(x.begin(), x.end()), std::vector<double>(y.begin(), y.end()),
354  style);
355 }
356 }
357 }
358 }
Interpolate::Style stringToInterpStyle(std::string const &style)
Conversion function to switch a string to an Interpolate::Style.
Definition: Interpolate.cc:254
virtual double interpolate(double const x) const
Definition: Interpolate.cc:95
virtual double interpolate(double const x) const =0
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:340
virtual double interpolate(double const x) const
Definition: Interpolate.cc:221
std::vector< double > const _x
Definition: Interpolate.h:79
double x
Interpolate::Style lookupMaxInterpStyle(int const n)
Get the highest order Interpolation::Style available for &#39;n&#39; points.
Definition: Interpolate.cc:272
int lookupMinInterpPoints(Interpolate::Style const style)
Get the minimum number of points needed to use the requested interpolation style. ...
Definition: Interpolate.cc:311
friend std::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.
Interpolate(std::vector< double > const &x, std::vector< double > const &y, Interpolate::Style const style=UNKNOWN)
Base class ctor.
Definition: Interpolate.h:63
std::vector< double > const _y
Definition: Interpolate.h:80
friend std::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.