Version: SMASH-3.1
interpolation.cc
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2015-2018,2020
3  * SMASH Team
4  *
5  * GNU General Public License (GPLv3 or later)
6  */
7 
8 #include "smash/interpolation.h"
9 
10 #include <iostream>
11 
12 namespace smash {
13 
14 InterpolateDataSpline::InterpolateDataSpline(const std::vector<double>& x,
15  const std::vector<double>& y) {
16  const auto N = x.size();
17  if (y.size() != N) {
18  throw std::runtime_error(
19  "Need two vectors of equal length for interpolation.");
20  }
21  if (N < 3) {
22  throw std::runtime_error(
23  "Need at least 3 data points for cubic spline interpolation.");
24  }
25  const auto p = generate_sort_permutation(
26  x, [&](double const& a, double const& b) { return a < b; });
27  const std::vector<double> sorted_x = apply_permutation(x, p);
28  const std::vector<double> sorted_y = apply_permutation(y, p);
29  check_duplicates(sorted_x, "InterpolateDataSpline");
30 
31  first_x_ = sorted_x.front();
32  last_x_ = sorted_x.back();
33  first_y_ = sorted_y.front();
34  last_y_ = sorted_y.back();
35  acc_ = gsl_interp_accel_alloc();
36  spline_ = gsl_spline_alloc(gsl_interp_cspline, N);
37  gsl_spline_init(spline_, &(*sorted_x.begin()), &(*sorted_y.begin()), N);
38 }
39 
41  gsl_spline_free(spline_);
42  gsl_interp_accel_free(acc_);
43 }
44 
45 double InterpolateDataSpline::operator()(double xi) const {
46  // constant extrapolation
47  if (xi < first_x_) {
48  return first_y_;
49  }
50  if (xi > last_x_) {
51  return last_y_;
52  }
53  // cubic spline interpolation
54  return gsl_spline_eval(spline_, xi, acc_);
55 }
56 
57 } // namespace smash
double first_x_
First x value.
gsl_spline * spline_
GSL spline.
InterpolateDataSpline(const std::vector< double > &x, const std::vector< double > &y)
Interpolate function f given discrete samples f(x_i) = y_i.
double last_y_
Last y value.
double operator()(double x) const
Calculate spline interpolation at x.
double first_y_
First y value.
gsl_interp_accel * acc_
GSL iterator for interpolation lookups.
double last_x_
Last x value.
constexpr int p
Proton.
Definition: action.h:24
std::vector< T > apply_permutation(const std::vector< T > &v, const Permutation &p)
Apply a permutation to a vector.
void check_duplicates(const std::vector< T > &x, const std::string &error_position)
Check whether two components have the same value in a sorted vector x.
Permutation generate_sort_permutation(std::vector< T > const &v, Cmp compare)
Calculate the permutations necessary for sorting a vector.