Skip to main content

lib_jsl_interpolation/one_d/
natural_cubic_spline_interpolator.rs

1use crate::interpolation_trait::InterpolationTrait;
2use lib_jsl_core::*;
3
4/// The natural cubic spline through `(x, y)`: piecewise cubic with continuous first and second
5/// derivatives, and zero second derivative at both ends. `x` must be strictly increasing.
6///
7/// See the book entry [Piecewise and spline interpolation](https://jwkunz.github.io/lib_jsl/book/interpolation/splines.html#cubic-splines).
8
9#[derive(Debug)]
10pub struct NaturalCubicSplineInterpolator<'a> {
11    x_values: VR1D<'a>,
12    y_values: VR1D<'a>,
13    location: Option<usize>,
14    a: R1D,
15    b: R1D,
16    c: R1D, 
17    d: R1D,
18}
19
20impl<'a> InterpolationTrait<'a> for NaturalCubicSplineInterpolator<'a> {
21    fn get_x_values(&self) -> VR1D<'a> {
22        self.x_values
23    }
24    fn set_x_values(&mut self, x: VR1D<'a>) {
25        self.x_values = x;
26    }
27    fn get_y_values(&self) -> VR1D<'a> {
28        self.y_values
29    }
30    fn set_y_values(&mut self, y: VR1D<'a>) {
31        self.y_values = y;
32    }
33    fn get_cached_location(&self) -> Option<usize> {
34        self.location
35    }
36    fn set_cached_location(&mut self, x: usize) {
37        self.location = Some(x)
38    }
39
40    /// Evaluates the cubic piece of interval `jlo`.
41    fn raw_interpolate(&mut self, jlo: usize, x: f64) -> Result<f64, ErrorsJSL> {
42        let dx = x - self.x_values[jlo];
43        let dx2 = dx*dx;
44        let dx3 = dx2*dx;
45        Ok(self.a[jlo] + self.b[jlo] * dx + self.c[jlo] * dx2 + self.d[jlo] * dx3)
46    }
47}
48
49impl<'a> NaturalCubicSplineInterpolator<'a> {
50        /// Compute the coefficients of a natural cubic spline.
51        /// 
52        /// The spline is represented piecewise by:
53        /// `S_i(x) = a[i] + b[i]*(x - x_i) + c[i]*(x - x_i)^2 + d[i]*(x - x_i)^3`
54        /// for x in [x_i, x_{i+1}].
55        pub fn init_natural_cubic_spline(&mut self){
56        // ANCHOR: natural_spline
57        let n = self.x_values.len();
58        let a = self.y_values.to_owned();
59        let mut b = R1D::zeros(n - 1);
60        let mut c = R1D::zeros(n);
61        let mut d = R1D::zeros(n - 1);
62
63        // Step 1: compute h
64        let h = R1D::from_iter(self.x_values.iter()
65                .zip(self.x_values.iter().skip(1))
66                .map(|(&x0, &x1)| x1 - x0)
67        );
68
69        // Step 2: set up tridiagonal system
70        let mut alpha = R1D::zeros(n);
71        for i in 1..n - 1 {
72            alpha[i] = (3.0 / h[i]) * (a[i + 1] - a[i])
73                - (3.0 / h[i - 1]) * (a[i] - a[i - 1]);
74        }
75
76        // Step 3: solve tridiagonal system for c (Thomas algorithm)
77        let mut l = R1D::zeros(n);
78        let mut mu = R1D::zeros(n);
79        let mut z = R1D::zeros(n);
80
81        l[0] = 1.0;
82        mu[0] = 0.0;
83        z[0] = 0.0;
84
85        for i in 1..n - 1 {
86            l[i] = 2.0 * (self.x_values[i + 1] - self.x_values[i - 1]) - h[i - 1] * mu[i - 1];
87            mu[i] = h[i] / l[i];
88            z[i] = (alpha[i] - h[i - 1] * z[i - 1]) / l[i];
89        }
90
91        l[n - 1] = 1.0;
92        z[n - 1] = 0.0;
93        c[n - 1] = 0.0;
94
95        for j in (0..n - 1).rev() {
96            c[j] = z[j] - mu[j] * c[j + 1];
97            b[j] = ((a[j + 1] - a[j]) / h[j]) - (h[j] * (c[j + 1] + 2.0 * c[j]) / 3.0);
98            d[j] = (c[j + 1] - c[j]) / (3.0 * h[j]);
99        }
100
101        // ANCHOR_END: natural_spline
102        self.a = a;
103        self.b = b;
104        self.c = c;
105        self.d = d;
106    }
107
108    /// Initialize with y_values = f(x_values)
109    pub fn new(x_values: VR1D<'a>, y_values: VR1D<'a>) -> Result<Self, ErrorsJSL> {
110
111        let mut result = NaturalCubicSplineInterpolator{
112            x_values,
113            y_values,
114            location: None,
115            a: R1D::default(0),
116            b: R1D::default(0),
117            c: R1D::default(0),
118            d: R1D::default(0),
119        };
120        result.verify_sizes(3)?;
121        if x_values.iter().zip(x_values.iter().skip(1)).any(|(a, b)| b <= a || a.is_nan() || b.is_nan()) {
122            return Err(ErrorsJSL::InvalidInputRange("x values must be strictly increasing"));
123        }
124        result.init_natural_cubic_spline();
125        Ok(result)
126    }
127}
128
129#[cfg(test)]
130mod test {
131    use super::*;
132
133    // Helper for comparing floats
134    fn approx_eq(a: f64, b: f64, epsilon: f64) -> bool {
135    (a - b).abs() < epsilon
136    }
137
138    #[test]
139    fn natural_spline_values() -> Result<(), ErrorsJSL> {
140        let x = R1D::from_vec(vec![0.0, 1.0, 2.0, 3.0]);
141        let y = R1D::from_vec(vec![1.0, 2.0, 0.0, -1.0]);
142
143        let mut dut = NaturalCubicSplineInterpolator::new(x.view(), y.view())?;
144
145        // Exact hits
146        let y_interp = dut.interpolate_at(0.0)?;
147        assert!(approx_eq(y_interp,1.0,1E-9));
148        let y_interp = dut.interpolate_at(1.0)?;
149        assert!(approx_eq(y_interp,2.0,1E-9));
150        let y_interp = dut.interpolate_at(2.0)?;
151        assert!(approx_eq(y_interp,0.0,1E-9));
152        let y_interp = dut.interpolate_at(3.0)?;
153        assert!(approx_eq(y_interp,-1.0,1E-9));
154
155        // Interpolations
156        let y_interp = dut.interpolate_at(0.5)?;
157        assert!(approx_eq(y_interp,1.825,1E-9));
158        let y_interp = dut.interpolate_at(1.5)?;
159        assert!(approx_eq(y_interp,1.15,1E-9));
160        let y_interp = dut.interpolate_at(2.5)?;
161        assert!(approx_eq(y_interp,-0.675,1E-9));
162        let y_interp = dut.interpolate_at(3.5)?;
163        assert!(approx_eq(y_interp,-1.325,1E-9));
164        let y_interp = dut.interpolate_at(-1.0)?;
165        assert!(approx_eq(y_interp,0.0,1E-9));
166        Ok(())
167    }
168
169    #[test]
170    fn rejects_unordered_abscissas() {
171        let x = R1D::from_vec(vec![0.0, 2.0, 1.0]);
172        let y = R1D::from_vec(vec![0.0, 1.0, 2.0]);
173        assert!(NaturalCubicSplineInterpolator::new(x.view(), y.view()).is_err());
174        assert!(crate::one_d::linear_interpolator::LinearInterpolator::new(x.view(), y.view()).is_err());
175    }
176}