Skip to main content

lib_jsl_interpolation/one_d/
akima.rs

1//! Akima interpolation: a locally determined piecewise cubic that avoids the wiggles of a global spline.
2//!
3//! See the book entry [Piecewise and spline interpolation](https://jwkunz.github.io/lib_jsl/book/interpolation/splines.html).
4
5use super::hermite::{PiecewiseHermite, secants};
6use lib_jsl_core::*;
7
8/// Builds an Akima (1970) interpolant through `(x, y)`; `x` strictly increasing, at least two
9/// points (two give a straight line).
10///
11/// Slopes are weighted averages of neighbouring secants; the two secants beyond each end are
12/// extrapolated linearly in the secant sequence, as in the original paper. The weights, the fill
13/// value where they vanish and the cutoff for that follow SciPy's `Akima1DInterpolator`.
14pub fn akima<'a>(x: VR1D<'a>, y: VR1D<'a>) -> Result<PiecewiseHermite<'a>, ErrorsJSL> {
15    PiecewiseHermite::from_slopes(x, y, R1D::from_vec(akima_slopes(x, y, false)?))
16}
17
18/// The modified Akima interpolant (`makima`, Cosmin Ionita 2019; SciPy's
19/// `Akima1DInterpolator(method="makima")`): the weights `|m₄ − m₃| + |m₄ + m₃|/2` and
20/// `|m₂ − m₁| + |m₂ + m₁|/2` also count the secants' size, so flat stretches and repeated
21/// secants no longer produce overshoot.
22pub fn makima<'a>(x: VR1D<'a>, y: VR1D<'a>) -> Result<PiecewiseHermite<'a>, ErrorsJSL> {
23    PiecewiseHermite::from_slopes(x, y, R1D::from_vec(akima_slopes(x, y, true)?))
24}
25
26// ANCHOR: akima_slopes
27/// The node slopes of Akima's method (`modified = false`) or of `makima` (`modified = true`).
28pub fn akima_slopes(x: VR1D, y: VR1D, modified: bool) -> Result<Vec<f64>, ErrorsJSL> {
29    let d = secants(x, y)?;
30    let n = x.len();
31    if n < 2 {
32        return Err(ErrorsJSL::IncompatibleArraySizes((n, 2)));
33    }
34    if n == 2 {
35        return Ok(vec![d[0]; 2]);
36    }
37    // Extended secants: m[k+2] = d[k], with two extrapolated values at each end.
38    let mut m = vec![0.0; n + 3];
39    m[2..n + 1].copy_from_slice(&d);
40    m[1] = 2.0 * m[2] - m[3];
41    m[0] = 2.0 * m[1] - m[2];
42    m[n + 1] = 2.0 * m[n] - m[n - 1];
43    m[n + 2] = 2.0 * m[n + 1] - m[n];
44    let weight = |a: f64, b: f64| (a - b).abs() + if modified { 0.5 * (a + b).abs() } else { 0.0 };
45    let f1: Vec<f64> = (0..n).map(|i| weight(m[i + 3], m[i + 2])).collect();
46    let f2: Vec<f64> = (0..n).map(|i| weight(m[i + 1], m[i])).collect();
47    let f12: Vec<f64> = f1.iter().zip(&f2).map(|(a, b)| a + b).collect();
48    let cutoff = 1e-9 * f12.iter().copied().fold(f64::NEG_INFINITY, f64::max);
49    Ok((0..n)
50        .map(|i| if f12[i] > cutoff { m[i + 1] + f2[i] / f12[i] * (m[i + 2] - m[i + 1]) } else { 0.5 * (m[i + 3] + m[i]) })
51        .collect())
52}
53// ANCHOR_END: akima_slopes
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58    use crate::interpolation_trait::InterpolationTrait;
59
60    #[test]
61    fn reproduces_lines_and_nodes() -> Result<(), ErrorsJSL> {
62        let x = R1D::from_vec(vec![-1.0, 0.0, 0.5, 2.0, 3.0, 4.5]);
63        let y = x.mapv(|v| 3.0 - 0.5 * v);
64        let mut a = akima(x.view(), y.view())?;
65        for &v in &[-1.0, -0.2, 0.5, 1.1, 2.9, 4.5] {
66            assert!((a.interpolate_at(v)? - (3.0 - 0.5 * v)).abs() < 1e-12);
67        }
68        Ok(())
69    }
70
71    #[test]
72    fn matches_reference_values() -> Result<(), ErrorsJSL> {
73        // Akima's classic data set; reference from the algorithm worked by hand at the knots' slopes.
74        let x = R1D::from_vec(vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]);
75        let y = R1D::from_vec(vec![10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.5, 15.0, 50.0, 60.0, 85.0]);
76        let mut a = akima(x.view(), y.view())?;
77        // Flat region stays flat (no ringing, unlike a natural spline).
78        for k in 0..=50 {
79            assert!((a.interpolate_at(k as f64 * 0.1)? - 10.0).abs() < 1e-12);
80        }
81        // Slope at x=7 per Akima's weights: m = (|d8-d7| d6 + |d6-d5| d7)/(...) with d5=.5,d6=4.5,d7=35,d8=10.
82        let w1 = (10.0f64 - 35.0).abs();
83        let w2 = (4.5f64 - 0.5).abs();
84        let want = (w1 * 4.5 + w2 * 35.0) / (w1 + w2);
85        assert!((a.slopes()[7] - want).abs() < 1e-12);
86        Ok(())
87    }
88}