Skip to main content

lib_jsl_interpolation/one_d/
pchip.rs

1//! Piecewise cubic Hermite interpolating polynomial (PCHIP), after Fritsch and Carlson.
2//!
3//! The interpolant is monotone wherever the data are monotone and never overshoots the data, at
4//! the price of only first-derivative continuity.
5//!
6//! See the book entry [Piecewise and spline interpolation](https://jwkunz.github.io/lib_jsl/book/interpolation/splines.html).
7
8use super::hermite::{PiecewiseHermite, secants};
9use lib_jsl_core::*;
10
11/// End slope from the three-point formula, limited to preserve shape (as in MATLAB/SciPy).
12fn end_slope(h0: f64, h1: f64, d0: f64, d1: f64) -> f64 {
13    let m = ((2.0 * h0 + h1) * d0 - h0 * d1) / (h0 + h1);
14    if m.signum() != d0.signum() {
15        0.0
16    } else if d0.signum() != d1.signum() && m.abs() > 3.0 * d0.abs() {
17        3.0 * d0
18    } else {
19        m
20    }
21}
22
23/// Builds a PCHIP interpolant through `(x, y)`; `x` must be strictly increasing, at least two points.
24pub fn pchip<'a>(x: VR1D<'a>, y: VR1D<'a>) -> Result<PiecewiseHermite<'a>, ErrorsJSL> {
25    let d = secants(x, y)?;
26    let n = x.len();
27    if n < 2 {
28        return Err(ErrorsJSL::IncompatibleArraySizes((n, y.len())));
29    }
30    let h: Vec<f64> = (0..n - 1).map(|i| x[i + 1] - x[i]).collect();
31    let mut m = R1D::zeros(n);
32    if n == 2 {
33        m.fill(d[0]);
34    } else {
35        for i in 1..n - 1 {
36            if d[i - 1] * d[i] > 0.0 {
37                // Weighted harmonic mean (Fritsch-Butland).
38                let w1 = 2.0 * h[i] + h[i - 1];
39                let w2 = h[i] + 2.0 * h[i - 1];
40                m[i] = (w1 + w2) / (w1 / d[i - 1] + w2 / d[i]);
41            }
42        }
43        m[0] = end_slope(h[0], h[1], d[0], d[1]);
44        m[n - 1] = end_slope(h[n - 2], h[n - 3], d[n - 2], d[n - 3]);
45    }
46    PiecewiseHermite::from_slopes(x, y, m)
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52    use crate::interpolation_trait::InterpolationTrait;
53
54    #[test]
55    fn exact_at_nodes_and_linear_data() -> Result<(), ErrorsJSL> {
56        let x = R1D::from_vec(vec![0.0, 1.0, 2.5, 4.0, 5.0]);
57        let y = x.mapv(|v| 2.0 * v + 1.0);
58        let mut p = pchip(x.view(), y.view())?;
59        for &v in &[0.0, 0.3, 1.0, 1.7, 3.3, 4.9, 5.0] {
60            assert!((p.interpolate_at(v)? - (2.0 * v + 1.0)).abs() < 1e-12);
61        }
62        Ok(())
63    }
64
65    #[test]
66    fn preserves_monotonicity() -> Result<(), ErrorsJSL> {
67        // A step-like monotone data set where a plain cubic spline would overshoot.
68        let x = R1D::from_vec(vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
69        let y = R1D::from_vec(vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]);
70        let mut p = pchip(x.view(), y.view())?;
71        let mut prev = -1.0;
72        for k in 0..=600 {
73            let v = p.interpolate_at(k as f64 * 0.01)?;
74            assert!((-1e-12..=1.0 + 1e-12).contains(&v), "overshoot {v}");
75            assert!(v >= prev - 1e-12, "not monotone");
76            prev = v;
77        }
78        // Matches SciPy's PchipInterpolator at x = 2.5 (symmetric step => 0.5).
79        assert!((p.interpolate_at(2.5)? - 0.5).abs() < 1e-12);
80        Ok(())
81    }
82
83    #[test]
84    fn rejects_bad_input() {
85        let x = R1D::from_vec(vec![0.0, 1.0, 1.0]);
86        let y = R1D::from_vec(vec![0.0, 1.0, 2.0]);
87        assert!(pchip(x.view(), y.view()).is_err());
88    }
89}