Skip to main content

lib_jsl_interpolation/one_d/
aaa.rs

1//! AAA rational approximation (Nakatsukasa, Sète and Trefethen, 2018) for real data.
2//!
3//! See the book entry [Rational interpolation and approximation](https://jwkunz.github.io/lib_jsl/book/interpolation/rational.html#the-aaa-algorithm).
4
5use lib_jsl_core::*;
6use ndarray::Array2;
7use lib_jsl_linalg::SVD;
8
9/// A barycentric rational approximant `r(x) = Σ w_k f_k / (x - z_k) / Σ w_k / (x - z_k)` chosen
10/// greedily from the sample points to reach a target accuracy.
11#[derive(Debug, Clone)]
12pub struct AaaApproximation {
13    support_points: Vec<f64>,
14    support_values: Vec<f64>,
15    weights: Vec<f64>,
16}
17
18impl AaaApproximation {
19    /// Fits samples `f(z)` (distinct `z`) with relative tolerance `tol` (e.g. `1e-13`) and at most
20    /// `max_terms` support points.
21    pub fn new(z: VR1D, f: VR1D, tol: f64, max_terms: usize) -> Result<Self, ErrorsJSL> {
22        let m = z.len();
23        if m != f.len() || m < 2 {
24            return Err(ErrorsJSL::IncompatibleArraySizes((m, f.len())));
25        }
26        let mut sorted: Vec<f64> = z.to_vec();
27        sorted.sort_by(f64::total_cmp);
28        if sorted.windows(2).any(|w| w[0] == w[1]) || sorted.iter().any(|v| !v.is_finite()) {
29            return Err(ErrorsJSL::InvalidInputRange("the sample points must be finite and distinct"));
30        }
31        let f_norm = f.iter().fold(0.0f64, |a, &v| a.max(v.abs()));
32        let mut remaining: Vec<usize> = (0..m).collect();
33        let mut support: Vec<usize> = Vec::new();
34        let mut weights: Vec<f64> = Vec::new();
35        let mean = f.sum() / m as f64;
36        let mut approx = vec![mean; m];
37        for _ in 0..max_terms.min(m) {
38            // Greedy: add the point with the worst current error.
39            let (pos, &worst) = remaining
40                .iter()
41                .enumerate()
42                .max_by(|a, b| (f[*a.1] - approx[*a.1]).abs().total_cmp(&(f[*b.1] - approx[*b.1]).abs()))
43                .ok_or(ErrorsJSL::RuntimeError("no points left"))?;
44            if (f[worst] - approx[worst]).abs() <= tol * f_norm {
45                break;
46            }
47            support.push(worst);
48            remaining.remove(pos);
49            let k = support.len();
50            if remaining.len() < k {
51                // Not enough rows left for a null-space estimate; keep the previous fit.
52                support.pop();
53                break;
54            }
55            // ANCHOR: aaa_step
56            // Loewner matrix on the remaining points.
57            let a = Array2::from_shape_fn((remaining.len(), k), |(i, j)| {
58                let (r, s) = (remaining[i], support[j]);
59                (f[r] - f[s]) / (z[r] - z[s])
60            });
61            let (_, _, vt) = a.svd(false, true).map_err(|_| ErrorsJSL::RuntimeError("SVD failed"))?;
62            let vt = vt.ok_or(ErrorsJSL::RuntimeError("SVD returned no right vectors"))?;
63            weights = vt.row(vt.nrows() - 1).to_vec();
64            // ANCHOR_END: aaa_step
65            // Fit residual at the remaining points.
66            let sz: Vec<f64> = support.iter().map(|&s| z[s]).collect();
67            let sf: Vec<f64> = support.iter().map(|&s| f[s]).collect();
68            for &r in &remaining {
69                approx[r] = eval(&sz, &sf, &weights, z[r]);
70            }
71            for &s in &support {
72                approx[s] = f[s];
73            }
74        }
75        if support.is_empty() {
76            // Constant data: the degree-0 fit.
77            return Ok(AaaApproximation { support_points: vec![z[0]], support_values: vec![f[0]], weights: vec![1.0] });
78        }
79        Ok(AaaApproximation {
80            support_points: support.iter().map(|&s| z[s]).collect(),
81            support_values: support.iter().map(|&s| f[s]).collect(),
82            weights,
83        })
84    }
85
86    /// Number of support points (the degree of the rational function is one less).
87    pub fn terms(&self) -> usize {
88        self.support_points.len()
89    }
90
91    /// Evaluates the approximant at `x`.
92    pub fn evaluate(&self, x: f64) -> f64 {
93        eval(&self.support_points, &self.support_values, &self.weights, x)
94    }
95}
96
97fn eval(z: &[f64], f: &[f64], w: &[f64], x: f64) -> f64 {
98    let (mut num, mut den) = (0.0, 0.0);
99    for k in 0..z.len() {
100        let d = x - z[k];
101        if d == 0.0 {
102            return f[k];
103        }
104        let t = w[k] / d;
105        num += t * f[k];
106        den += t;
107    }
108    num / den
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    #[test]
116    fn recovers_a_rational_function_exactly() {
117        let g = |x: f64| (x * x + 1.0) / (x * x - 2.0 * x + 5.0); // poles off the real line
118        let z = R1D::from_iter((0..200).map(|k| -3.0 + 6.0 * k as f64 / 199.0));
119        let f = z.mapv(g);
120        let a = AaaApproximation::new(z.view(), f.view(), 1e-13, 30).unwrap();
121        assert!(a.terms() <= 6, "terms {}", a.terms());
122        for k in 0..50 {
123            let x = -2.9 + k as f64 * 0.117;
124            assert!((a.evaluate(x) - g(x)).abs() < 1e-9, "x={x}");
125        }
126    }
127
128    #[test]
129    fn approximates_a_nonrational_function_and_extrapolates_gracefully() {
130        let z = R1D::from_iter((0..400).map(|k| -1.0 + 2.0 * k as f64 / 399.0));
131        let f = z.mapv(|x| (3.0 * x).exp() * x.cos());
132        let a = AaaApproximation::new(z.view(), f.view(), 1e-12, 40).unwrap();
133        for k in 0..30 {
134            let x = -0.98 + k as f64 * 0.0657;
135            let want = (3.0 * x).exp() * x.cos();
136            assert!((a.evaluate(x) - want).abs() < 1e-8 * want.abs().max(1.0), "x={x}");
137        }
138    }
139
140    #[test]
141    fn constant_data_and_bad_input() {
142        let z = R1D::from_vec(vec![0.0, 1.0, 2.0, 3.0]);
143        let f = R1D::from_vec(vec![2.0; 4]);
144        let a = AaaApproximation::new(z.view(), f.view(), 1e-13, 10).unwrap();
145        assert_eq!(a.evaluate(1.7), 2.0);
146        assert!(AaaApproximation::new(z.view(), R1D::zeros(3).view(), 1e-13, 5).is_err());
147    }
148
149    #[test]
150    fn rejects_repeated_sample_points() {
151        let z = R1D::from_vec(vec![0.0, 0.5, 0.5, 1.0]);
152        let f = R1D::from_vec(vec![1.0, 2.0, 3.0, 4.0]);
153        assert!(AaaApproximation::new(z.view(), f.view(), 1e-13, 10).is_err());
154    }
155}