Skip to main content

lib_jsl_ffts/
multidimensional_fft.rs

1//! Multidimensional FFTs: transforms along one axis, or over every axis of a 2D, 3D or N-D array.
2//!
3//! See the book entry [Real and multidimensional FFTs](https://jwkunz.github.io/lib_jsl/book/fft/real-multidimensional.html#multidimensional-transforms).
4
5use crate::fft::Fft;
6use crate::fft_engine_trait::{FftDirection, FftEngine1D, FftOrdering, FftScaleFactor};
7use lib_jsl_core::ErrorsJSL;
8use ndarray::{Array2, Array3, ArrayD, Axis};
9use num_complex::Complex;
10
11type C64 = Complex<f64>;
12
13// ANCHOR: fft_axis
14/// Transforms every 1D lane of `data` along `axis` in place. Inverse transforms are scaled by
15/// `1 / len`, so a forward and inverse pass along the same axis is the identity.
16pub fn fft_axis(data: &mut ArrayD<C64>, axis: usize, direction: FftDirection) -> Result<(), ErrorsJSL> {
17    if axis >= data.ndim() {
18        return Err(ErrorsJSL::InvalidInputRange("The axis is out of range."));
19    }
20    let len = data.len_of(Axis(axis));
21    if len == 0 {
22        return Ok(());
23    }
24    let scale = match direction {
25        FftDirection::Forward => FftScaleFactor::None,
26        FftDirection::Inverse => FftScaleFactor::N,
27    };
28    let mut fft = Fft::with_plan(len, scale, direction, FftOrdering::Standard)?;
29    for mut lane in data.lanes_mut(Axis(axis)) {
30        let out = fft.execute(&lane.to_vec())?;
31        lane.iter_mut().zip(out).for_each(|(v, o)| *v = o);
32    }
33    Ok(())
34}
35// ANCHOR_END: fft_axis
36
37/// The N-dimensional DFT `X[k] = Σ x[n] e^{∓2πi Σ_d k_d n_d / N_d}` over every axis (the inverse
38/// is scaled by `1 / Π N_d`). Any lengths are supported.
39pub fn fftn(data: &ArrayD<C64>, direction: FftDirection) -> Result<ArrayD<C64>, ErrorsJSL> {
40    let mut out = data.clone();
41    for axis in 0..out.ndim() {
42        fft_axis(&mut out, axis, direction)?;
43    }
44    Ok(out)
45}
46
47/// The 2D DFT of a matrix (rows and columns).
48pub fn fft2(data: &Array2<C64>) -> Result<Array2<C64>, ErrorsJSL> {
49    fftn(&data.clone().into_dyn(), FftDirection::Forward)?.into_dimensionality().map_err(|_| ErrorsJSL::RuntimeError("dimension"))
50}
51
52/// The inverse 2D DFT (scaled by `1 / (rows · columns)`).
53pub fn ifft2(data: &Array2<C64>) -> Result<Array2<C64>, ErrorsJSL> {
54    fftn(&data.clone().into_dyn(), FftDirection::Inverse)?.into_dimensionality().map_err(|_| ErrorsJSL::RuntimeError("dimension"))
55}
56
57/// The 3D DFT of a volume.
58pub fn fft3(data: &Array3<C64>) -> Result<Array3<C64>, ErrorsJSL> {
59    fftn(&data.clone().into_dyn(), FftDirection::Forward)?.into_dimensionality().map_err(|_| ErrorsJSL::RuntimeError("dimension"))
60}
61
62/// The inverse 3D DFT.
63pub fn ifft3(data: &Array3<C64>) -> Result<Array3<C64>, ErrorsJSL> {
64    fftn(&data.clone().into_dyn(), FftDirection::Inverse)?.into_dimensionality().map_err(|_| ErrorsJSL::RuntimeError("dimension"))
65}
66
67/// Rearranges a spectrum so the zero-frequency bin is at the centre along every axis (like
68/// NumPy's `fftshift`).
69pub fn fftshift(data: &ArrayD<C64>) -> ArrayD<C64> {
70    let shape = data.shape().to_vec();
71    ArrayD::from_shape_fn(data.raw_dim(), |idx| {
72        let src: Vec<usize> = (0..shape.len()).map(|d| (idx[d] + shape[d] - shape[d] / 2) % shape[d]).collect();
73        data[ndarray::IxDyn(&src)]
74    })
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80    use std::f64::consts::TAU;
81
82    fn dft2(x: &Array2<C64>) -> Array2<C64> {
83        let (r, c) = x.dim();
84        Array2::from_shape_fn((r, c), |(k, l)| {
85            let mut s = C64::new(0.0, 0.0);
86            for m in 0..r {
87                for n in 0..c {
88                    s += x[[m, n]] * C64::from_polar(1.0, -TAU * ((k * m) as f64 / r as f64 + (l * n) as f64 / c as f64));
89                }
90            }
91            s
92        })
93    }
94
95    #[test]
96    fn two_dimensional_transform_matches_the_definition_for_any_shape() {
97        for (r, c) in [(4, 4), (3, 5), (8, 6), (1, 7)] {
98            let x = Array2::from_shape_fn((r, c), |(i, j)| C64::new((i as f64 * 1.3 + j as f64).sin(), (i * j) as f64 * 0.1));
99            let got = fft2(&x).unwrap();
100            let want = dft2(&x);
101            assert!(got.iter().zip(want.iter()).all(|(a, b)| (a - b).norm() < 1e-9), "{r}x{c}");
102            let back = ifft2(&got).unwrap();
103            assert!(back.iter().zip(x.iter()).all(|(a, b)| (a - b).norm() < 1e-12));
104        }
105    }
106
107    #[test]
108    fn three_dimensional_plane_wave_lands_in_one_bin_and_shift_centres_dc() {
109        let (a, b, c) = (4, 6, 5);
110        let x = Array3::from_shape_fn((a, b, c), |(i, j, k)| C64::from_polar(1.0, TAU * (i as f64 / a as f64 + 2.0 * j as f64 / b as f64 + 3.0 * k as f64 / c as f64)));
111        let s = fft3(&x).unwrap();
112        let total = (a * b * c) as f64;
113        assert!((s[[1, 2, 3]].re - total).abs() < 1e-9);
114        assert!(s.indexed_iter().filter(|(ix, _)| *ix != (1, 2, 3)).all(|(_, v)| v.norm() < 1e-9));
115        assert!(ifft3(&s).unwrap().iter().zip(x.iter()).all(|(p, q)| (p - q).norm() < 1e-12));
116        // fftshift moves the DC bin to the centre.
117        let mut dc = ArrayD::<C64>::zeros(ndarray::IxDyn(&[4, 5]));
118        dc[ndarray::IxDyn(&[0, 0])] = C64::new(1.0, 0.0);
119        let shifted = fftshift(&dc);
120        assert_eq!(shifted[ndarray::IxDyn(&[2, 2])], C64::new(1.0, 0.0));
121        let mut d = x.into_dyn();
122        assert!(fft_axis(&mut d, 3, FftDirection::Forward).is_err());
123    }
124}