Skip to main content

lib_jsl_interpolation/one_d/
bulirsch_stoer.rs

1//! Bulirsch-Stoer rational function interpolation.
2//!
3//! See the book entry [Rational interpolation and approximation](https://jwkunz.github.io/lib_jsl/book/interpolation/rational.html#bulirsch-stoer-rational-interpolation).
4
5use crate::interpolation_trait::InterpolationTrait;
6use lib_jsl_core::*;
7
8/// Diagonal rational function interpolation (Stoer and Bulirsch) through points with distinct
9/// abscissae. Unlike a polynomial, a rational function can follow poles and sharp resonances, and
10/// it reproduces any rational function of matching degree exactly. Each evaluation is O(n²) and
11/// also yields an error estimate (the size of the last correction).
12///
13/// A genuine pole of the interpolant at the query point produces an error. Iteration stops early
14/// once corrections fall to rounding level, which happens when the data are exactly rational of
15/// lower degree than the point count allows.
16#[derive(Debug)]
17pub struct BulirschStoer<'a> {
18    x_values: VR1D<'a>,
19    y_values: VR1D<'a>,
20}
21
22impl<'a> BulirschStoer<'a> {
23    pub fn new(x_values: VR1D<'a>, y_values: VR1D<'a>) -> Result<Self, ErrorsJSL> {
24        let mut r = BulirschStoer { x_values, y_values };
25        r.verify_sizes(1)?;
26        let n = x_values.len();
27        for i in 0..n {
28            if (0..i).any(|j| x_values[j] == x_values[i]) {
29                return Err(ErrorsJSL::InvalidInputRange("x values must be distinct"));
30            }
31        }
32        Ok(r)
33    }
34
35    /// Interpolated value at `x` together with an estimate of its error.
36    pub fn interpolate_with_error(&self, x: f64) -> Result<(f64, f64), ErrorsJSL> {
37        const TINY: f64 = 1e-25; // keeps a zero first denominator from producing 0/0
38        let (xa, ya) = (&self.x_values, &self.y_values);
39        let n = xa.len();
40        let mut c = vec![0.0; n];
41        let mut d = vec![0.0; n];
42        let mut ns = 0usize;
43        let mut hh = (x - xa[0]).abs();
44        for i in 0..n {
45            let h = (x - xa[i]).abs();
46            if h == 0.0 {
47                return Ok((ya[i], 0.0));
48            }
49            if h < hh {
50                ns = i;
51                hh = h;
52            }
53            c[i] = ya[i];
54            d[i] = ya[i] + TINY;
55        }
56        let mut y = ya[ns];
57        let mut ns = ns as isize - 1;
58        let mut dy = 0.0;
59        for m in 1..n {
60            for i in 0..n - m {
61                let w = c[i + 1] - d[i];
62                let h = xa[i + m] - x;
63                let t = (xa[i] - x) * d[i] / h;
64                let dd = t - c[i + 1];
65                if dd == 0.0 {
66                    return Err(ErrorsJSL::RuntimeError("interpolating function has a pole at the requested value"));
67                }
68                let dd = w / dd;
69                d[i] = c[i + 1] * dd;
70                c[i] = t * dd;
71            }
72            dy = if 2 * (ns + 1) < (n - m) as isize {
73                c[(ns + 1) as usize]
74            } else {
75                let v = d[ns as usize];
76                ns -= 1;
77                v
78            };
79            y += dy;
80            // Exactly representable data (a lower-degree rational function) makes later
81            // denominators collapse to zero; once the corrections vanish the fit is complete.
82            if m >= 2 && dy.abs() <= 4.0 * f64::EPSILON * y.abs() {
83                break;
84            }
85        }
86        Ok((y, dy.abs()))
87    }
88}
89
90impl<'a> InterpolationTrait<'a> for BulirschStoer<'a> {
91    fn get_x_values(&self) -> VR1D<'a> {
92        self.x_values
93    }
94    fn set_x_values(&mut self, x: VR1D<'a>) {
95        self.x_values = x;
96    }
97    fn get_y_values(&self) -> VR1D<'a> {
98        self.y_values
99    }
100    fn set_y_values(&mut self, y: VR1D<'a>) {
101        self.y_values = y;
102    }
103    fn get_cached_location(&self) -> Option<usize> {
104        None
105    }
106    fn set_cached_location(&mut self, _: usize) {}
107    fn raw_interpolate(&mut self, _: usize, _: f64) -> Result<f64, ErrorsJSL> {
108        Err(ErrorsJSL::NotImplementedYet)
109    }
110    fn interpolate_at(&mut self, x: f64) -> Result<f64, ErrorsJSL> {
111        self.interpolate_with_error(x).map(|(y, _)| y)
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    #[test]
120    fn reproduces_a_rational_function_exactly() {
121        // A [2/2] rational function is determined by 5 points.
122        let g = |x: f64| (2.0 * x * x - x + 3.0) / (x * x + 0.5 * x + 2.0);
123        let x = R1D::from_vec(vec![-2.0, -0.7, 0.4, 1.3, 2.9]);
124        let y = x.mapv(g);
125        let mut b = BulirschStoer::new(x.view(), y.view()).unwrap();
126        for &v in &[-3.5, -1.2, 0.0, 0.9, 2.0, 6.0] {
127            assert!((b.interpolate_at(v).unwrap() - g(v)).abs() < 1e-9, "v={v}");
128        }
129    }
130
131    #[test]
132    fn follows_a_near_pole_far_better_than_a_polynomial() {
133        let g = |x: f64| 1.0 / (1.0 + 25.0 * x * x);
134        let x = R1D::from_iter((0..9).map(|k| -0.93 + 0.25 * k as f64));
135        let y = x.mapv(g);
136        let mut b = BulirschStoer::new(x.view(), y.view()).unwrap();
137        let mut p = crate::one_d::lagrange_interpolant::LagrangeInterpolant::new(x.view(), y.view()).unwrap();
138        let (eb, ep) = ((b.interpolate_at(0.9).unwrap() - g(0.9)).abs(), (p.interpolate_at(0.9).unwrap() - g(0.9)).abs());
139        assert!(eb < ep, "bs {eb} poly {ep}");
140        // Exact at nodes with zero estimated error, and an error estimate elsewhere.
141        assert_eq!(b.interpolate_with_error(x[4]).unwrap(), (y[4], 0.0));
142        assert!(b.interpolate_with_error(0.37).unwrap().1 > 0.0);
143    }
144
145    #[test]
146    fn rejects_duplicate_abscissae() {
147        let x = R1D::from_vec(vec![1.0, 2.0, 1.0]);
148        assert!(BulirschStoer::new(x.view(), x.view()).is_err());
149    }
150}