Skip to main content

lib_jsl_interpolation/one_d/
hermite.rs

1//! Shared piecewise cubic Hermite machinery used by PCHIP, Akima and the cubic basis interpolators.
2//!
3//! See the book entry [Piecewise and spline interpolation](https://jwkunz.github.io/lib_jsl/book/interpolation/splines.html).
4
5use crate::interpolation_trait::InterpolationTrait;
6use lib_jsl_core::*;
7
8/// A piecewise cubic Hermite interpolant: on each interval the cubic is fixed by the end values
9/// and the end slopes. The slope-selection rule (PCHIP, Akima, Catmull-Rom, ...) lives in the
10/// constructors of the respective modules.
11///
12/// Outside the data range the end cubic pieces are extended.
13#[derive(Debug)]
14pub struct PiecewiseHermite<'a> {
15    x_values: VR1D<'a>,
16    y_values: VR1D<'a>,
17    slopes: R1D,
18    location: Option<usize>,
19}
20
21impl<'a> PiecewiseHermite<'a> {
22    /// Builds the interpolant from explicit node slopes `m[i] = f'(x[i])`.
23    pub fn from_slopes(x_values: VR1D<'a>, y_values: VR1D<'a>, slopes: R1D) -> Result<Self, ErrorsJSL> {
24        let mut result = PiecewiseHermite { x_values, y_values, slopes, location: None };
25        result.verify_sizes(2)?;
26        if result.slopes.len() != x_values.len() {
27            return Err(ErrorsJSL::IncompatibleArraySizes((x_values.len(), result.slopes.len())));
28        }
29        if x_values.iter().zip(x_values.iter().skip(1)).any(|(a, b)| b <= a) {
30            return Err(ErrorsJSL::InvalidInputRange("x values must be strictly increasing"));
31        }
32        Ok(result)
33    }
34
35    /// The node slopes in use.
36    pub fn slopes(&self) -> &R1D {
37        &self.slopes
38    }
39
40    /// The same interpolant as a [`PPoly`](super::ppoly::PPoly), with derivatives, integrals and
41    /// roots (SciPy's `PchipInterpolator` and `Akima1DInterpolator` are `PPoly`s).
42    pub fn to_ppoly(&self) -> super::ppoly::PPoly {
43        super::ppoly::PPoly::cubic_hermite(&self.x_values.to_vec(), &self.y_values.to_vec(), &self.slopes.to_vec()).expect("validated on construction")
44    }
45}
46
47impl<'a> InterpolationTrait<'a> for PiecewiseHermite<'a> {
48    fn get_x_values(&self) -> VR1D<'a> {
49        self.x_values
50    }
51    fn set_x_values(&mut self, x: VR1D<'a>) {
52        self.x_values = x;
53    }
54    fn get_y_values(&self) -> VR1D<'a> {
55        self.y_values
56    }
57    fn set_y_values(&mut self, y: VR1D<'a>) {
58        self.y_values = y;
59    }
60    fn get_cached_location(&self) -> Option<usize> {
61        self.location
62    }
63    fn set_cached_location(&mut self, x: usize) {
64        self.location = Some(x)
65    }
66
67    fn raw_interpolate(&mut self, j: usize, x: f64) -> Result<f64, ErrorsJSL> {
68        let (x0, x1) = (self.x_values[j], self.x_values[j + 1]);
69        let (y0, y1) = (self.y_values[j], self.y_values[j + 1]);
70        let h = x1 - x0;
71        let t = (x - x0) / h;
72        let (t2, t3) = (t * t, t * t * t);
73        let h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
74        let h10 = t3 - 2.0 * t2 + t;
75        let h01 = -2.0 * t3 + 3.0 * t2;
76        let h11 = t3 - t2;
77        Ok(h00 * y0 + h10 * h * self.slopes[j] + h01 * y1 + h11 * h * self.slopes[j + 1])
78    }
79}
80
81/// Secant slopes `(y[i+1]-y[i])/(x[i+1]-x[i])`.
82pub(crate) fn secants(x: VR1D, y: VR1D) -> Result<Vec<f64>, ErrorsJSL> {
83    if x.len() != y.len() {
84        return Err(ErrorsJSL::IncompatibleArraySizes((x.len(), y.len())));
85    }
86    if x.iter().zip(x.iter().skip(1)).any(|(a, b)| b <= a) {
87        return Err(ErrorsJSL::InvalidInputRange("x values must be strictly increasing"));
88    }
89    Ok((0..x.len().saturating_sub(1)).map(|i| (y[i + 1] - y[i]) / (x[i + 1] - x[i])).collect())
90}