Skip to main content

lib_jsl_interpolation/three_d/
fourier_3d.rs

1//! Trigonometric interpolation of triply periodic gridded data.
2
3use super::Interpolation3D;
4use lib_jsl_core::*;
5use ndarray::{Array3, Axis};
6use num_complex::Complex;
7use std::f64::consts::PI;
8
9/// The band-limited triply periodic trigonometric interpolant through
10/// `v[[i, j, k]] = f(x0 + i px/nx, y0 + j py/ny, z0 + k pz/nz)`. Coefficients come from a
11/// separable direct DFT (O(N·(nx+ny+nz)) for N samples); each evaluation costs O(N). Nyquist bins
12/// of even-length axes keep their `+n/2` frequency, which leaves the interpolant real.
13#[derive(Debug, Clone)]
14pub struct FourierInterpolator3D {
15    origin: [f64; 3],
16    period: [f64; 3],
17    coefficients: Array3<Complex<f64>>,
18}
19
20fn frequency(k: usize, n: usize) -> f64 {
21    if k <= n / 2 { k as f64 } else { k as f64 - n as f64 }
22}
23
24fn dft_axis(data: &Array3<Complex<f64>>, axis: usize) -> Array3<Complex<f64>> {
25    let n = data.len_of(Axis(axis));
26    let mut out = data.clone();
27    for (lane_in, mut lane_out) in data.lanes(Axis(axis)).into_iter().zip(out.lanes_mut(Axis(axis))) {
28        for k in 0..n {
29            lane_out[k] = lane_in.iter().enumerate().map(|(j, &v)| v * Complex::from_polar(1.0, -2.0 * PI * ((k * j) % n) as f64 / n as f64)).sum();
30        }
31    }
32    out
33}
34
35impl FourierInterpolator3D {
36    /// `origin` is the position of sample `[0, 0, 0]`, `period` the periods along each axis.
37    pub fn new(v: &Array3<f64>, origin: [f64; 3], period: [f64; 3]) -> Result<Self, ErrorsJSL> {
38        if v.is_empty() || period.iter().any(|&p| p <= 0.0) {
39            return Err(ErrorsJSL::InvalidInputRange("need samples and positive periods"));
40        }
41        let mut c = v.mapv(|r| Complex::new(r, 0.0));
42        for axis in 0..3 {
43            c = dft_axis(&c, axis);
44        }
45        let scale = 1.0 / v.len() as f64;
46        c.mapv_inplace(|z| z * scale);
47        Ok(FourierInterpolator3D { origin, period, coefficients: c })
48    }
49}
50
51impl Interpolation3D for FourierInterpolator3D {
52    fn interpolate_at(&self, x: f64, y: f64, z: f64) -> Result<f64, ErrorsJSL> {
53        let (nx, ny, nz) = self.coefficients.dim();
54        let n = [nx, ny, nz];
55        let p = [x, y, z];
56        let phasors: Vec<Vec<Complex<f64>>> = (0..3)
57            .map(|d| {
58                let theta = 2.0 * PI * (p[d] - self.origin[d]) / self.period[d];
59                (0..n[d]).map(|k| Complex::from_polar(1.0, frequency(k, n[d]) * theta)).collect()
60            })
61            .collect();
62        let mut sum = Complex::new(0.0, 0.0);
63        for i in 0..nx {
64            for j in 0..ny {
65                let pij = phasors[0][i] * phasors[1][j];
66                let line: Complex<f64> = (0..nz).map(|k| self.coefficients[[i, j, k]] * phasors[2][k]).sum();
67                sum += pij * line;
68            }
69        }
70        Ok(sum.re)
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    #[test]
79    fn reproduces_bandlimited_function_and_samples() {
80        let (n, period) = ([6usize, 5, 4], [2.0, 3.0, 1.5]);
81        let origin = [0.1, -0.2, 0.3];
82        let f = |a: f64, b: f64, c: f64| {
83            1.0 + (2.0 * PI * (a - origin[0]) / period[0]).cos() * (2.0 * PI * (b - origin[1]) / period[1]).sin()
84                + 0.3 * (2.0 * PI * (c - origin[2]) / period[2] + 2.0 * PI * (a - origin[0]) / period[0]).cos()
85        };
86        let v = Array3::from_shape_fn((n[0], n[1], n[2]), |(i, j, k)| {
87            f(origin[0] + i as f64 * period[0] / n[0] as f64, origin[1] + j as f64 * period[1] / n[1] as f64, origin[2] + k as f64 * period[2] / n[2] as f64)
88        });
89        let fi = FourierInterpolator3D::new(&v, origin, period).unwrap();
90        for &(a, b, c) in &[(0.4, 0.5, 0.9), (1.7, -1.1, 0.0), (-0.8, 2.2, 1.2)] {
91            assert!((fi.interpolate_at(a, b, c).unwrap() - f(a, b, c)).abs() < 1e-11, "{a},{b},{c}");
92        }
93        let g = Array3::from_shape_fn((4, 4, 3), |(i, j, k)| ((i * 5 + j * 3 + k) % 6) as f64);
94        let t = FourierInterpolator3D::new(&g, [0.0; 3], [4.0, 4.0, 3.0]).unwrap();
95        for i in 0..4 {
96            for j in 0..4 {
97                for k in 0..3 {
98                    assert!((t.interpolate_at(i as f64, j as f64, k as f64).unwrap() - g[[i, j, k]]).abs() < 1e-11);
99                }
100            }
101        }
102        assert!(FourierInterpolator3D::new(&g, [0.0; 3], [1.0, 0.0, 1.0]).is_err());
103    }
104}