Skip to main content

lib_jsl_interpolation/one_d/
fourier_1d.rs

1//! Trigonometric (Fourier) interpolation of uniformly sampled periodic data.
2//!
3//! See the book entry [Trigonometric interpolation and Prony's method](https://jwkunz.github.io/lib_jsl/book/interpolation/trigonometric.html).
4
5use lib_jsl_core::*;
6use num_complex::Complex;
7use std::f64::consts::PI;
8
9/// Interpolates `n` equally spaced samples of a periodic function with the band-limited
10/// trigonometric polynomial through them. For even `n` the Nyquist term is split evenly between
11/// ±n/2 so the interpolant stays real.
12///
13/// Coefficients are computed with a direct DFT (O(n²), once); each evaluation costs O(n).
14#[derive(Debug, Clone)]
15pub struct FourierInterpolator1D {
16    x0: f64,
17    period: f64,
18    coefficients: Vec<Complex<f64>>,
19}
20
21impl FourierInterpolator1D {
22    /// `y[k]` is the function value at `x0 + k * period / n`.
23    pub fn new(y: VR1D, x0: f64, period: f64) -> Result<Self, ErrorsJSL> {
24        let n = y.len();
25        if n == 0 || period <= 0.0 {
26            return Err(ErrorsJSL::InvalidInputRange("need samples and a positive period"));
27        }
28        let coefficients = (0..n)
29            .map(|k| {
30                (0..n)
31                    .map(|j| Complex::from_polar(y[j], -2.0 * PI * ((k * j) % n) as f64 / n as f64))
32                    .sum::<Complex<f64>>()
33                    / n as f64
34            })
35            .collect();
36        Ok(FourierInterpolator1D { x0, period, coefficients })
37    }
38
39    /// Evaluates the interpolant (periodically extended) at `x`.
40    pub fn evaluate(&self, x: f64) -> f64 {
41        let n = self.coefficients.len();
42        let theta = 2.0 * PI * (x - self.x0) / self.period;
43        let mut sum = self.coefficients[0].re;
44        let half = (n - 1) / 2;
45        for k in 1..=half {
46            // Pair the +k and -k terms (conjugates for real data).
47            let (a, b) = (self.coefficients[k], self.coefficients[n - k]);
48            sum += (a * Complex::from_polar(1.0, k as f64 * theta)).re + (b * Complex::from_polar(1.0, -(k as f64) * theta)).re;
49        }
50        if n.is_multiple_of(2) && n > 1 {
51            sum += self.coefficients[n / 2].re * (0.5 * n as f64 * theta).cos();
52        }
53        sum
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn reproduces_bandlimited_signals_off_grid() {
63        let n = 16;
64        let period = 2.0;
65        let f = |x: f64| 1.0 + (2.0 * PI * x / period).sin() + 0.5 * (6.0 * PI * x / period).cos();
66        let y = R1D::from_iter((0..n).map(|k| f(0.3 + k as f64 * period / n as f64)));
67        let fi = FourierInterpolator1D::new(y.view(), 0.3, period).unwrap();
68        for k in 0..40 {
69            let x = -1.0 + k as f64 * 0.137;
70            assert!((fi.evaluate(x) - f(x)).abs() < 1e-12, "x={x}");
71        }
72    }
73
74    #[test]
75    fn odd_length_and_exact_at_samples() {
76        let n = 9;
77        let y = R1D::from_iter((0..n).map(|k| ((k * k) % 5) as f64));
78        let fi = FourierInterpolator1D::new(y.view(), 0.0, 9.0).unwrap();
79        for k in 0..n {
80            assert!((fi.evaluate(k as f64) - y[k]).abs() < 1e-12);
81        }
82        assert!(FourierInterpolator1D::new(y.view(), 0.0, 0.0).is_err());
83    }
84}