spline1d 0.1.1

One-dimensional cubic splines, quadratic single-interval interpolation, and inverse lookup primitives.
Documentation
// spline1d::spline.rs

//! The main structure in this module, `Spline`, encapsulates the calculated cubic spline coefficients and automatically handles interval location and interpolation using the appropriate set of cubic coefficients.

use core::fmt;

use alloc::vec;
use alloc::vec::Vec;
use num_traits::Float;

use crate::binsearch::{binary_search_interval, interval_inside, kernel_conv};
use crate::solve::calculate_root;

/*************************************************************************************************************/
/*************************************************************************************************************/

/// One-dimensional Piecewise-Polynomial structure storing `xs` and `ys` break points and the calculated cubic coefficients.
#[derive(Debug, Clone)]
pub struct Spline<T: Float + fmt::Debug> {
    pub breaks_x: Vec<T>,
    pub breaks_y: Vec<T>,
    pub coeffs: Vec<[T; 4]>,
    last: usize,
}

impl<T: Float + fmt::Debug> Spline<T> {
    // A new instance using xx and yy breaks + slopes calculated elsewhere.
    pub fn new(xx: &[T], yy: &[T], ss: &[T]) -> Self {
        // xx is the principal variable, yy is a dependent variable
        let dxx: Vec<T> = kernel_conv(xx, &[-T::one(), T::one()]).collect(); // calculate differences in xx
        let dyy: Vec<T> = kernel_conv(yy, &[-T::one(), T::one()]).collect(); // calculate differences in yy
        let divdif: Vec<T> = dxx.iter().zip(dyy.iter()).map(|(x, y)| *y / *x).collect(); // divide y by x
        let dzzdx: Vec<T> = dxx
            .iter()
            .zip(divdif.iter().zip(ss.iter()))
            .map(|(dx, (dydx, s))| (*dydx - *s) / *dx)
            .collect();
        let dzdxx: Vec<T> = dxx
            .iter()
            .zip(divdif.iter().zip(ss[1..].iter()))
            .map(|(dx, (dydx, s))| (*s - *dydx) / *dx)
            .collect();
        let mut coeffs: Vec<[T; 4]> = (0..xx.len() - 1)
            .map(|idx| {
                [
                    (dzdxx[idx] - dzzdx[idx]) / dxx[idx],
                    (dzzdx[idx] + dzzdx[idx]) - dzdxx[idx],
                    ss[idx],
                    yy[idx],
                ]
            })
            .collect();
        for coeff in &mut coeffs {
            for value in coeff.iter_mut() {
                if value.is_nan() {
                    *value = T::zero();
                }
            }
        }
        Self {
            breaks_x: xx.to_vec(),
            breaks_y: yy.to_vec(),
            coeffs,
            last: 0,
        }
    }
    /// A new instance using `AKIMA` method.
    pub fn akima(xx: &[T], yy: &[T]) -> Self {
        crate::methods::akima::akima(xx, yy)
    }

    /// A new instance using `MAKIMA` method.
    pub fn makima(xx: &[T], yy: &[T]) -> Self {
        crate::methods::makima::makima(xx, yy)
    }

    /// A new instance using `PCHIP` method.
    pub fn pchip(xx: &[T], yy: &[T]) -> Self {
        crate::methods::pchip::pchip(xx, yy)
    }

    /// A new instance using `STEFFEN` method.
    pub fn steffen(xx: &[T], yy: &[T]) -> Self {
        crate::methods::steffen::steffen(xx, yy)
    }

    /// A new instance using `CATMULL-ROM` method.
    pub fn catmullrom(xx: &[T], yy: &[T]) -> Self {
        crate::methods::catmullrom::catmullrom(xx, yy)
    }

    /// A new instance using `CARDINAL` method.
    pub fn cardinal(xx: &[T], yy: &[T], tension: T) -> Self {
        crate::methods::cardinal::cardinal(xx, yy, tension)
    }

    /// A new instance using `FRITSCH-BUTLAND` method.
    pub fn fritschbutland(xx: &[T], yy: &[T]) -> Self {
        crate::methods::fritschbutland::fritschbutland(xx, yy)
    }

    /// Returns the index of the interval containing value x.
    pub fn index(&self, x: &T) -> Option<usize> {
        binary_search_interval(self.breaks_x.len(), x, |loc| self.breaks_x[loc])
    }
    /// Checks whether value x is inside interval at `idx` interval.
    fn check_index(&self, idx: &usize, x: &T) -> bool {
        interval_inside(x, (&self.breaks_x[*idx], &self.breaks_x[*idx + 1]))
    }

    /// `Y` break value at `index`.
    pub fn yvalue(&self, index: usize) -> T {
        self.breaks_y[index]
    }

    /// Finds the maximum value of `Y` among the stored break values and returns the corresponding index.
    pub fn max_value_index(&self) -> usize {
        // linear scan of nodes
        let mut curr = self.coeffs[0][3];
        let mut currindex: usize = 0;
        for k in 0..self.breaks_y.len() {
            let val = self.breaks_y[k];
            if val > curr {
                curr = val;
                currindex = k;
            }
        }
        currindex
    }

    /// Interpolate `Y` for a given `X` (cubic); includes interval search.
    pub fn interpolate(&self, x: &T) -> Option<T> {
        let index = if self.check_index(&self.last, x) {
            self.last
        } else {
            self.index(x)?
        };
        let xs = *x - self.breaks_x[index];
        Some(
            self.coeffs[index]
                .iter()
                .fold(T::zero(), |acc, c| xs * acc + *c),
        )
    }

    /// Interpolation of `Y` for a given `X` using linear approximation; includes interval search.
    pub fn interpolate_linear(&self, x: &T) -> Option<T> {
        let index = if self.check_index(&self.last, x) {
            self.last
        } else {
            self.index(x)?
        };
        let x0 = self.breaks_x[index];
        let x1 = self.breaks_x[index + 1];
        let xs = (*x - self.breaks_x[index]) / (x1 - x0);
        let y0 = self.breaks_y[index];
        let y1 = self.breaks_y[index + 1];
        Some(y0 * (T::one() - xs) + y1 * xs)
    }

    /// Interpolate first-derivative dY/dX using the cubic coefficients; includes interval search.
    pub fn interpolate_diff1(&self, x: &T) -> Option<T> {
        let index = if self.check_index(&self.last, x) {
            self.last
        } else {
            self.index(x)?
        };
        self.interpolate_diff1_for_index(x, index)
    }

    /// Interpolate second-derivative d2Y/dX2; includes interval search.
    pub fn interpolate_diff2(&self, x: &T) -> Option<T> {
        let index = if self.check_index(&self.last, x) {
            self.last
        } else {
            self.index(x)?
        };
        self.interpolate_diff2_for_index(x, index)
    }

    /// Cubic interpolation but no interval search is involved; the required interval index is entered explicitly.
    pub fn interpolate_for_index(&self, x: &T, index: usize) -> Option<T> {
        let xs = *x - self.breaks_x[index];
        Some(
            self.coeffs[index]
                .iter()
                .fold(T::zero(), |acc, c| xs * acc + *c),
        )
    }

    /// First-derivative interpolation (dY/dX) with no interval search; the required interval index is entered explicitly.
    pub fn interpolate_diff1_for_index(&self, x: &T, index: usize) -> Option<T> {
        let xs = *x - self.breaks_x[index];
        let coeffs = &self.coeffs[index];
        let c1 = coeffs[0] * xs * xs;
        let c2 = coeffs[1] * xs;
        Some(c1 + c1 + c1 + c2 + c2 + coeffs[2])
    }

    /// Second-derivative interpolation (d2Y/dX2) with no interval search; the required interval index is entered explicitly.
    pub fn interpolate_diff2_for_index(&self, x: &T, index: usize) -> Option<T> {
        let xs = *x - self.breaks_x[index];
        let coeffs = &self.coeffs[index];
        let c1 = coeffs[0] * xs;
        let c2 = coeffs[1];
        Some(c1 + c1 + c1 + c1 + c1 + c1 + c2 + c2)
    }
}

/*************************************************************************************************************/
/*************************************************************************************************************/

impl Spline<f64> {
    /// Calculate the intersection point of two distinct splines for intervals at `index1` and `index2`, correspondingly in the first and the second spline. Uses the Kardani formula.
    pub fn intersection_with_exact(
        &self,
        other: &Spline<f64>,
        index1: usize,
        index2: usize,
    ) -> Option<(f64, f64)> {
        let mut coeffs = vec![0.0; 4];
        coeffs[0] = self.coeffs[index1][0] - other.coeffs[index2][0];
        coeffs[1] = self.coeffs[index1][1] - other.coeffs[index2][1];
        coeffs[2] = self.coeffs[index1][2] - other.coeffs[index2][2];
        coeffs[3] = self.coeffs[index1][3] - other.coeffs[index2][3];
        let x1 = self.breaks_x[index1] + calculate_root(&coeffs);
        let y1 = self.interpolate_for_index(&x1, index1)?;
        Some((x1, y1))
    }

    /// Calculate the intersection point of two distinct splines for intervals at `index1` and `index2`, correspondingly in the first and the second spline. Uses numerical iterative search.
    pub fn intersection_with_numeric(
        &self,
        other: &Spline<f64>,
        index1: usize,
        index2: usize,
    ) -> Option<(f64, f64)> {
        let mut x1 = self.breaks_x[index1];
        let mut x2 = other.breaks_x[index2];
        let func = |x| self.interpolate(&x).unwrap() - other.interpolate(&x).unwrap();
        let y1 = func(x1);
        let _y2 = func(x2);
        while (x1 - x2).abs() > 1.0e-6 {
            let x = (x1 + x2) / 2.0;
            let y = func(x);
            if ((y > 0.0) && (y1 > 0.0)) || ((y < 0.0) && (y1 < 0.0)) {
                x1 = x;
                //y1 = y;
            } else {
                x2 = x;
                //y2 = y;
            }
        }
        let x = (x1 + x2) / 2.0;
        let y = self.interpolate(&x)?;
        Some((x, y))
    }
}

/*************************************************************************************************************/
/*************************************************************************************************************/