Skip to main content

lib_jsl_interpolation/two_d/
fourier_2d.rs

1//! Trigonometric interpolation of doubly periodic gridded data.
2
3use super::Interpolation2D;
4use lib_jsl_core::*;
5use num_complex::Complex;
6use std::f64::consts::PI;
7
8/// The band-limited doubly periodic trigonometric interpolant through `z[[i, j]] = f(x0 + i px/nx,
9/// y0 + j py/ny)`. Coefficients come from a separable direct DFT; each evaluation costs O(nx·ny).
10/// Nyquist terms (even sizes) are handled so the interpolant stays real.
11#[derive(Debug, Clone)]
12pub struct FourierInterpolator2D {
13    x0: f64,
14    y0: f64,
15    px: f64,
16    py: f64,
17    coefficients: Vec<Vec<Complex<f64>>>,
18}
19
20fn dft_matrix(n: usize) -> Vec<Vec<Complex<f64>>> {
21    (0..n).map(|k| (0..n).map(|j| Complex::from_polar(1.0, -2.0 * PI * ((k * j) % n) as f64 / n as f64)).collect()).collect()
22}
23
24/// Signed frequency of FFT bin `k` of `n`; the Nyquist bin keeps `+n/2`.
25fn frequency(k: usize, n: usize) -> f64 {
26    if k <= n / 2 { k as f64 } else { k as f64 - n as f64 }
27}
28
29impl FourierInterpolator2D {
30    /// `px`, `py` are the periods along each axis, `(x0, y0)` the position of sample `[0, 0]`.
31    pub fn new(z: VR2D, x0: f64, y0: f64, px: f64, py: f64) -> Result<Self, ErrorsJSL> {
32        let (nx, ny) = z.dim();
33        if nx == 0 || ny == 0 || px <= 0.0 || py <= 0.0 {
34            return Err(ErrorsJSL::InvalidInputRange("need samples and positive periods"));
35        }
36        let (fx, fy) = (dft_matrix(nx), dft_matrix(ny));
37        // Rows (over j) first: t[i][l] = Σ_j z[i][j] e^{-2πi jl/ny}; then columns.
38        let t: Vec<Vec<Complex<f64>>> =
39            (0..nx).map(|i| (0..ny).map(|l| (0..ny).map(|j| fy[l][j] * z[[i, j]]).sum()).collect()).collect();
40        let scale = 1.0 / (nx * ny) as f64;
41        let coefficients = (0..nx)
42            .map(|k| (0..ny).map(|l| (0..nx).map(|i| fx[k][i] * t[i][l]).sum::<Complex<f64>>() * scale).collect())
43            .collect();
44        Ok(FourierInterpolator2D { x0, y0, px, py, coefficients })
45    }
46}
47
48impl Interpolation2D for FourierInterpolator2D {
49    fn interpolate_at(&self, x: f64, y: f64) -> Result<f64, ErrorsJSL> {
50        let (nx, ny) = (self.coefficients.len(), self.coefficients[0].len());
51        let tx = 2.0 * PI * (x - self.x0) / self.px;
52        let ty = 2.0 * PI * (y - self.y0) / self.py;
53        // Pre-compute the 1D phasors, then Re Σ C[k][l] e^{i(f_k tx + f_l ty)}.
54        let ex: Vec<Complex<f64>> = (0..nx).map(|k| Complex::from_polar(1.0, frequency(k, nx) * tx)).collect();
55        let ey: Vec<Complex<f64>> = (0..ny).map(|l| Complex::from_polar(1.0, frequency(l, ny) * ty)).collect();
56        let mut sum = Complex::new(0.0, 0.0);
57        for (coef_row, phase) in self.coefficients.iter().zip(&ex) {
58            let row: Complex<f64> = coef_row.iter().zip(&ey).map(|(c, e)| c * e).sum();
59            sum += row * phase;
60        }
61        Ok(sum.re)
62    }
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    fn reproduces_bandlimited_functions_off_grid() {
71        let (nx, ny) = (12, 9);
72        let (px, py) = (3.0, 2.0);
73        let f = |a: f64, b: f64| {
74            1.0 + (2.0 * PI * a / px).cos() * (2.0 * PI * b / py).sin() + 0.4 * (4.0 * PI * a / px + 2.0 * PI * b / py).cos()
75        };
76        let z = R2D::from_shape_fn((nx, ny), |(i, j)| f(0.2 + i as f64 * px / nx as f64, -0.1 + j as f64 * py / ny as f64));
77        let fi = FourierInterpolator2D::new(z.view(), 0.2, -0.1, px, py).unwrap();
78        for &(a, b) in &[(0.37, 0.52), (1.9, -0.4), (2.8, 1.7), (-1.0, 3.3)] {
79            assert!((fi.interpolate_at(a, b).unwrap() - f(a, b)).abs() < 1e-11, "{a},{b}");
80        }
81    }
82
83    #[test]
84    fn exact_at_samples_for_arbitrary_data_even_sizes() {
85        let z = R2D::from_shape_fn((8, 6), |(i, j)| ((i * 5 + j * 11) % 7) as f64 - 3.0);
86        let fi = FourierInterpolator2D::new(z.view(), 0.0, 0.0, 8.0, 6.0).unwrap();
87        for i in 0..8 {
88            for j in 0..6 {
89                assert!((fi.interpolate_at(i as f64, j as f64).unwrap() - z[[i, j]]).abs() < 1e-11);
90            }
91        }
92        assert!(FourierInterpolator2D::new(z.view(), 0.0, 0.0, 0.0, 1.0).is_err());
93    }
94}