CubicSpline.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include "CubicSpline.h"
  2. CubicSpline::CubicSpline(const std::vector<std::pair<float, float> >& dataPoints, bool useSlopes) :
  3. useSlopes{ useSlopes }
  4. {
  5. if (dataPoints.size() < 2) {
  6. return;
  7. }
  8. points.push_back({ dataPoints[0].first, dataPoints[0].second,
  9. (dataPoints[1].second - dataPoints[0].second) /
  10. (dataPoints[1].first - dataPoints[0].first) });
  11. for (size_t i = 1; i < dataPoints.size() - 1; i++) {
  12. auto& dp1 = dataPoints[i - 1];
  13. auto& dp2 = dataPoints[i];
  14. auto& dp3 = dataPoints[i + 1];
  15. float w1 = dp2.first - dp1.first;
  16. float w2 = dp3.first - dp2.first;
  17. float h1 = dp2.second - dp1.second;
  18. float h2 = dp3.second - dp2.second;
  19. float s1 = h1 / w1;
  20. float s2 = h2 / w2;
  21. float avgSlope = (s1 + s2) / 2;
  22. points.push_back({ dp2.first, dp2.second, avgSlope });
  23. }
  24. points.push_back({ dataPoints[dataPoints.size() - 1].first, dataPoints[dataPoints.size() - 1].second,
  25. (dataPoints[dataPoints.size() - 2].second - dataPoints[dataPoints.size() - 1].second) /
  26. (dataPoints[dataPoints.size() - 2].first - dataPoints[dataPoints.size() - 1].first) });
  27. }
  28. float CubicSpline::interpolateAt(float x)
  29. {
  30. const static auto h00 = [] (float t) { return (1 + 2 * t) * (1 - t) * (1 - t); };
  31. const static auto h01 = [] (float t) { return t * t * (3 - 2 * t); };
  32. const static auto h10 = [] (float t) { return t * (1 - t) * (1 - t); };
  33. const static auto h11 = [] (float t) { return t * t * (t - 1); };
  34. for (auto it = points.begin(); it != points.end() && (it + 1) != points.end(); ++it) {
  35. auto& left = *it;
  36. auto& right = *(it + 1);
  37. float xleft = std::get<0>(left);
  38. float xright = std::get<0>(right);
  39. if (xleft < x && xright >= x) {
  40. float w = (xright - xleft);
  41. float t = (x - xleft) / w;
  42. float yleft = std::get<1>(left);
  43. float yright = std::get<1>(right);
  44. float sleft = std::get<2>(left);
  45. float sright = std::get<2>(right);
  46. float inter = h00(t) * yleft +
  47. h01(t) * yright;
  48. if (useSlopes)
  49. inter += h10(t) * w * sleft +
  50. h11(t) * w * sright;
  51. return inter;
  52. }
  53. }
  54. return std::get<1>(points[points.size() - 1]);
  55. }