Skip to main content

lib_jsl_interpolation/one_d/
pronys_method.rs

1//! Prony's method: fit uniformly sampled data with a sum of complex exponentials.
2//!
3//! See the book entry [Trigonometric interpolation and Prony's method](https://jwkunz.github.io/lib_jsl/book/interpolation/trigonometric.html#pronys-method). With noisy data, fit more exponentials than the
4//! signal contains: the extra ones absorb the noise as strongly damped components.
5
6use lib_jsl_core::*;
7use ndarray::{Array1, Array2};
8use lib_jsl_linalg::{Eig, LeastSquaresSvd};
9use num_complex::Complex;
10
11/// `y(x) = Re Σ_i c_i z_i^((x - x0)/dx)` fitted to samples at `x0 + k dx`. Each `z_i` is a
12/// discrete-time pole (`|z|` is the per-sample decay, `arg z` the per-sample phase advance), which
13/// makes the model both an interpolator and an extrapolator for damped oscillations.
14#[derive(Debug, Clone)]
15pub struct PronyModel {
16    x0: f64,
17    dx: f64,
18    poles: Vec<Complex<f64>>,
19    amplitudes: Vec<Complex<f64>>,
20}
21
22impl PronyModel {
23    /// Fits `order` exponentials to `y` (needs `y.len() >= 2 * order`; extra samples are used in a
24    /// least-squares sense, which averages down noise).
25    pub fn new(y: VR1D, x0: f64, dx: f64, order: usize) -> Result<Self, ErrorsJSL> {
26        let n = y.len();
27        if order == 0 || n < 2 * order || dx <= 0.0 {
28            return Err(ErrorsJSL::InvalidInputRange("need order > 0, dx > 0 and at least 2*order samples"));
29        }
30        // ANCHOR: prony_steps
31        // Linear prediction: y[k+p] = -Σ_{j=1..p} a_j y[k+p-j] for k = 0..n-p.
32        let rows = n - order;
33        let a = Array2::from_shape_fn((rows, order), |(k, j)| y[k + order - 1 - j]);
34        let b = Array1::from_shape_fn(rows, |k| -y[k + order]);
35        let coef = a
36            .least_squares(&b)
37            .map_err(|_| ErrorsJSL::RuntimeError("prediction least squares failed"))?
38            .solution;
39        // Poles are the roots of z^p + a_1 z^(p-1) + ... + a_p: eigenvalues of the companion matrix.
40        let mut companion = Array2::<f64>::zeros((order, order));
41        for j in 0..order {
42            companion[[0, j]] = -coef[j];
43        }
44        for i in 1..order {
45            companion[[i, i - 1]] = 1.0;
46        }
47        let (eigenvalues, _) = companion.eig().map_err(|_| ErrorsJSL::RuntimeError("eigenvalue solve failed"))?;
48        let poles: Vec<Complex<f64>> = eigenvalues.to_vec();
49        // Amplitudes: least squares on the Vandermonde system y[k] = Σ c_i z_i^k.
50        let v = Array2::from_shape_fn((n, order), |(k, i)| poles[i].powi(k as i32));
51        let yc = Array1::from_shape_fn(n, |k| Complex::new(y[k], 0.0));
52        let amplitudes = v
53            .least_squares(&yc)
54            .map_err(|_| ErrorsJSL::RuntimeError("amplitude least squares failed"))?
55            .solution
56            .to_vec();
57        // ANCHOR_END: prony_steps
58        Ok(PronyModel { x0, dx, poles, amplitudes })
59    }
60
61    /// The fitted discrete-time poles `z_i`.
62    pub fn poles(&self) -> &[Complex<f64>] {
63        &self.poles
64    }
65
66    /// The complex amplitudes `c_i`.
67    pub fn amplitudes(&self) -> &[Complex<f64>] {
68        &self.amplitudes
69    }
70
71    /// Continuous-time exponents `s_i = ln(z_i) / dx`, so `y(x) = Re Σ c_i exp(s_i (x - x0))`.
72    pub fn exponents(&self) -> Vec<Complex<f64>> {
73        self.poles.iter().map(|z| z.ln() / self.dx).collect()
74    }
75
76    /// Evaluates the model (the real part of the exponential sum) at `x`.
77    pub fn evaluate(&self, x: f64) -> f64 {
78        let t = (x - self.x0) / self.dx;
79        self.poles
80            .iter()
81            .zip(&self.amplitudes)
82            .map(|(z, c)| (c * Complex::from_polar(z.norm().powf(t), z.arg() * t)).re)
83            .sum()
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90
91    #[test]
92    fn recovers_damped_sinusoid_parameters() {
93        let (dx, alpha, omega) = (0.05, -0.8, 7.0);
94        let f = |x: f64| 2.0 * (alpha * x).exp() * (omega * x + 0.4).cos();
95        let y = R1D::from_iter((0..40).map(|k| f(k as f64 * dx)));
96        let m = PronyModel::new(y.view(), 0.0, dx, 2).unwrap();
97        // The two poles are conjugates at exp((alpha ± i omega) dx).
98        let want = Complex::new(alpha, omega) * dx;
99        let want = want.exp();
100        assert!(m.poles().iter().any(|z| (z - want).norm() < 1e-9));
101        assert!(m.poles().iter().any(|z| (z - want.conj()).norm() < 1e-9));
102        // Off-grid interpolation and extrapolation beyond the data.
103        for &x in &[0.0123, 0.777, 1.9, 3.3] {
104            assert!((m.evaluate(x) - f(x)).abs() < 1e-8, "x={x}");
105        }
106    }
107
108    #[test]
109    fn two_real_exponentials_and_overdetermined_noise() {
110        let f = |x: f64| 3.0 * (-x).exp() + 1.5 * (-4.0 * x).exp();
111        let y = R1D::from_iter((0..30).map(|k| f(k as f64 * 0.1)));
112        let m = PronyModel::new(y.view(), 0.0, 0.1, 2).unwrap();
113        let mut s: Vec<f64> = m.exponents().iter().map(|e| e.re).collect();
114        s.sort_by(f64::total_cmp);
115        assert!((s[0] + 4.0).abs() < 1e-7 && (s[1] + 1.0).abs() < 1e-7, "{s:?}");
116        assert!((m.evaluate(0.55) - f(0.55)).abs() < 1e-8);
117    }
118
119    #[test]
120    fn rejects_too_few_samples() {
121        let y = R1D::zeros(3);
122        assert!(PronyModel::new(y.view(), 0.0, 1.0, 2).is_err());
123    }
124}