Skip to main content

lib_jsl_interpolation/one_d/
cubic_basis.rs

1//! Cubic basis (cardinal / Catmull-Rom) interpolation.
2//!
3//! Each interval is a cubic Hermite segment whose node slopes come from a tension-scaled central
4//! difference of the neighbouring points. With `tension = 0` this is the Catmull-Rom spline.
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;
9use lib_jsl_core::*;
10
11/// Builds a cardinal cubic interpolant through `(x, y)`.
12///
13/// Interior slopes are `(1 - tension) (y[i+1]-y[i-1]) / (x[i+1]-x[i-1])`; end slopes use the
14/// one-sided secant. `tension` is normally in `[0, 1]` (1 gives zero slopes, a smoothed staircase).
15/// `x` must be strictly increasing with at least two points.
16pub fn cubic_basis<'a>(x: VR1D<'a>, y: VR1D<'a>, tension: f64) -> Result<PiecewiseHermite<'a>, ErrorsJSL> {
17    let n = x.len();
18    if n != y.len() || n < 2 {
19        return Err(ErrorsJSL::IncompatibleArraySizes((n, y.len())));
20    }
21    if x.iter().zip(x.iter().skip(1)).any(|(a, b)| b <= a) {
22        return Err(ErrorsJSL::InvalidInputRange("x values must be strictly increasing"));
23    }
24    let c = 1.0 - tension;
25    let mut m = R1D::zeros(n);
26    for i in 0..n {
27        let (lo, hi) = (i.saturating_sub(1), (i + 1).min(n - 1));
28        m[i] = c * (y[hi] - y[lo]) / (x[hi] - x[lo]);
29    }
30    PiecewiseHermite::from_slopes(x, y, m)
31}
32
33#[cfg(test)]
34mod tests {
35    use super::*;
36    use crate::interpolation_trait::InterpolationTrait;
37
38    #[test]
39    fn nodes_lines_and_smooth_function() -> Result<(), ErrorsJSL> {
40        let x = R1D::from_iter((0..21).map(|k| k as f64 * 0.1));
41        let y = x.mapv(f64::sin);
42        let mut c = cubic_basis(x.view(), y.view(), 0.0)?;
43        for k in 0..21 {
44            assert!((c.interpolate_at(x[k])? - y[k]).abs() < 1e-14);
45        }
46        for k in 0..199 {
47            let v = 0.0105 + k as f64 * 0.01;
48            if v < 2.0 {
49                assert!((c.interpolate_at(v)? - v.sin()).abs() < 1e-3, "v={v}");
50            }
51        }
52        let lx = R1D::from_vec(vec![0.0, 1.0, 3.0, 4.0]);
53        let ly = lx.mapv(|v| 2.0 * v - 1.0);
54        let mut l = cubic_basis(lx.view(), ly.view(), 0.0)?;
55        assert!((l.interpolate_at(2.2)? - 3.4).abs() < 1e-12);
56        Ok(())
57    }
58
59    #[test]
60    fn full_tension_gives_flat_nodes() -> Result<(), ErrorsJSL> {
61        let x = R1D::from_vec(vec![0.0, 1.0, 2.0]);
62        let y = R1D::from_vec(vec![0.0, 2.0, 1.0]);
63        let c = cubic_basis(x.view(), y.view(), 1.0)?;
64        assert!(c.slopes().iter().all(|&s| s == 0.0));
65        Ok(())
66    }
67}