Skip to main content

lib_jsl_dsp/discrete/
fft_convolution.rs

1//! FFT-based convolution, similar to `scipy.signal.fftconvolve`.
2//!
3//! Convolution in the time domain is multiplication in the frequency domain, so a length-`N`
4//! signal convolved with a length-`M` kernel costs `O((N + M) log(N + M))` instead of `O(N M)`.
5//! The 1D routine works for any [`IsAnalytic`] sample type (real or complex); the 2D routine works
6//! on real images and is the basis for frequency-domain image filtering.
7//!
8//! See the book entry [Convolution and correlation](https://jwkunz.github.io/lib_jsl/book/filters/convolution.html#fast-convolution).
9
10use crate::{
11    discrete::convolve::{apply_mode, fft_full, ConvolveMode},
12    ffts::{
13        Fft,
14        fft_engine_trait::{FftEngine1D, FftDirection, FftOrdering, FftScaleFactor},
15    },
16    prelude::{ErrorsJSL, IsAnalytic},
17};
18use ndarray::Array2;
19use num_complex::Complex;
20
21/// 1D convolution of `in1` and `in2` computed with FFTs.
22///
23/// `mode` selects the output extent exactly as for [`convolve`](crate::discrete::convolve::convolve)
24/// (`Full`, `Same` = the size of `in1`, `Valid`). The result matches direct convolution to rounding
25/// error.
26pub fn fft_convolve<T: IsAnalytic>(in1: &[T], in2: &[T], mode: ConvolveMode) -> Result<Vec<T>, ErrorsJSL> {
27    if in1.is_empty() || in2.is_empty() {
28        return Err(ErrorsJSL::InvalidInputRange("Input arrays must be non-empty"));
29    }
30    let full = fft_full(in1, in2)?;
31    Ok(apply_mode(full, in1.len(), in2.len(), mode))
32}
33
34/// Transforms every row, then every column, of a complex matrix whose dimensions are powers of two.
35pub(crate) fn fft2d(data: &Array2<Complex<f64>>, inverse: bool) -> Result<Array2<Complex<f64>>, ErrorsJSL> {
36    let (rows, cols) = data.dim();
37    let (direction, scale) = if inverse { (FftDirection::Inverse, FftScaleFactor::N) } else { (FftDirection::Forward, FftScaleFactor::None) };
38    let mut row_fft = Fft::new();
39    row_fft.plan(cols, scale, direction, FftOrdering::Standard)?;
40    let mut col_fft = Fft::new();
41    col_fft.plan(rows, scale, direction, FftOrdering::Standard)?;
42    let mut tmp = Array2::<Complex<f64>>::zeros((rows, cols));
43    for r in 0..rows {
44        let row: Vec<Complex<f64>> = data.row(r).to_vec();
45        for (c, v) in row_fft.execute(&row)?.into_iter().enumerate() {
46            tmp[(r, c)] = v;
47        }
48    }
49    let mut out = Array2::<Complex<f64>>::zeros((rows, cols));
50    for c in 0..cols {
51        let col: Vec<Complex<f64>> = tmp.column(c).to_vec();
52        for (r, v) in col_fft.execute(&col)?.into_iter().enumerate() {
53            out[(r, c)] = v;
54        }
55    }
56    Ok(out)
57}
58
59/// 2D convolution of real images computed with FFTs.
60///
61/// `Full` has shape `(r1 + r2 - 1, c1 + c2 - 1)`; `Same` has the shape of `in1`, centred; `Valid`
62/// has shape `(r1 - r2 + 1, c1 - c2 + 1)` and requires `in1` to be at least as large as `in2`
63/// in both dimensions.
64pub fn fft_convolve_2d(in1: &Array2<f64>, in2: &Array2<f64>, mode: ConvolveMode) -> Result<Array2<f64>, ErrorsJSL> {
65    let ((r1, c1), (r2, c2)) = (in1.dim(), in2.dim());
66    if r1 == 0 || c1 == 0 || r2 == 0 || c2 == 0 {
67        return Err(ErrorsJSL::InvalidInputRange("Input arrays must be non-empty"));
68    }
69    let (fr, fc) = (r1 + r2 - 1, c1 + c2 - 1);
70    let (pr, pc) = (fr.next_power_of_two(), fc.next_power_of_two());
71    let pad = |a: &Array2<f64>| {
72        let mut p = Array2::<Complex<f64>>::zeros((pr, pc));
73        for ((r, c), &v) in a.indexed_iter() {
74            p[(r, c)] = Complex::new(v, 0.0);
75        }
76        p
77    };
78    let fa = fft2d(&pad(in1), false)?;
79    let fb = fft2d(&pad(in2), false)?;
80    let prod = &fa * &fb;
81    let spatial = fft2d(&prod, true)?;
82    let full = Array2::from_shape_fn((fr, fc), |(r, c)| spatial[(r, c)].re);
83    match mode {
84        ConvolveMode::Full => Ok(full),
85        ConvolveMode::Same => {
86            let (r0, c0) = ((r2 - 1) / 2, (c2 - 1) / 2);
87            Ok(Array2::from_shape_fn((r1, c1), |(r, c)| full[(r + r0, c + c0)]))
88        }
89        ConvolveMode::Valid => {
90            if r1 < r2 || c1 < c2 {
91                return Err(ErrorsJSL::InvalidInputRange("Valid mode requires in1 to be at least as large as in2 in both dimensions"));
92            }
93            Ok(Array2::from_shape_fn((r1 - r2 + 1, c1 - c2 + 1), |(r, c)| full[(r + r2 - 1, c + c2 - 1)]))
94        }
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::discrete::convolve::{convolve, ConvolveMethod};
102
103    fn lcg(seed: &mut u64) -> f64 {
104        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
105        ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
106    }
107
108    #[test]
109    fn matches_direct_convolution_in_every_mode() {
110        let mut seed = 5;
111        for (n, m) in [(1usize, 1usize), (7, 3), (3, 7), (100, 31), (257, 64), (64, 257)] {
112            let a: Vec<f64> = (0..n).map(|_| lcg(&mut seed)).collect();
113            let b: Vec<f64> = (0..m).map(|_| lcg(&mut seed)).collect();
114            for mode in [ConvolveMode::Full, ConvolveMode::Same, ConvolveMode::Valid] {
115                let want = convolve(&a, &b, mode, ConvolveMethod::Direct).unwrap();
116                let got = fft_convolve(&a, &b, mode).unwrap();
117                assert_eq!(got.len(), want.len(), "{mode:?} {n}x{m}");
118                for (g, w) in got.iter().zip(&want) {
119                    assert!((g - w).abs() < 1e-11, "{mode:?} {n}x{m}: {g} vs {w}");
120                }
121            }
122        }
123    }
124
125    #[test]
126    fn complex_signals_and_identity_kernel() {
127        let mut seed = 9;
128        let a: Vec<Complex<f64>> = (0..50).map(|_| Complex::new(lcg(&mut seed), lcg(&mut seed))).collect();
129        let delta = vec![Complex::new(1.0, 0.0)];
130        let y = fft_convolve(&a, &delta, ConvolveMode::Full).unwrap();
131        for (g, w) in y.iter().zip(&a) {
132            assert!((g - w).norm() < 1e-12);
133        }
134        let b: Vec<Complex<f64>> = (0..9).map(|_| Complex::new(lcg(&mut seed), lcg(&mut seed))).collect();
135        let want = convolve(&a, &b, ConvolveMode::Full, ConvolveMethod::Direct).unwrap();
136        let got = fft_convolve(&a, &b, ConvolveMode::Full).unwrap();
137        for (g, w) in got.iter().zip(&want) {
138            assert!((g - w).norm() < 1e-11);
139        }
140    }
141
142    #[test]
143    fn rejects_empty_inputs() {
144        assert!(fft_convolve::<f64>(&[], &[1.0], ConvolveMode::Full).is_err());
145        assert!(fft_convolve::<f64>(&[1.0], &[], ConvolveMode::Full).is_err());
146    }
147
148    fn direct_2d(a: &Array2<f64>, b: &Array2<f64>) -> Array2<f64> {
149        let ((r1, c1), (r2, c2)) = (a.dim(), b.dim());
150        let mut out = Array2::<f64>::zeros((r1 + r2 - 1, c1 + c2 - 1));
151        for ((i, j), &x) in a.indexed_iter() {
152            for ((k, l), &h) in b.indexed_iter() {
153                out[(i + k, j + l)] += x * h;
154            }
155        }
156        out
157    }
158
159    #[test]
160    fn two_dimensional_matches_direct() {
161        let mut seed = 77;
162        let a = Array2::from_shape_fn((13, 9), |_| lcg(&mut seed));
163        let b = Array2::from_shape_fn((4, 5), |_| lcg(&mut seed));
164        let want = direct_2d(&a, &b);
165        let got = fft_convolve_2d(&a, &b, ConvolveMode::Full).unwrap();
166        assert_eq!(got.dim(), want.dim());
167        assert!(got.iter().zip(want.iter()).all(|(g, w)| (g - w).abs() < 1e-11));
168        let same = fft_convolve_2d(&a, &b, ConvolveMode::Same).unwrap();
169        assert_eq!(same.dim(), a.dim());
170        for r in 0..13 {
171            for c in 0..9 {
172                assert!((same[(r, c)] - want[(r + 1, c + 2)]).abs() < 1e-11);
173            }
174        }
175        let valid = fft_convolve_2d(&a, &b, ConvolveMode::Valid).unwrap();
176        assert_eq!(valid.dim(), (10, 5));
177        assert!((valid[(0, 0)] - want[(3, 4)]).abs() < 1e-11);
178        assert!(fft_convolve_2d(&b, &a, ConvolveMode::Valid).is_err());
179    }
180
181    #[test]
182    fn fft2d_round_trip() {
183        let mut seed = 3;
184        let x = Array2::from_shape_fn((8, 16), |_| Complex::new(lcg(&mut seed), lcg(&mut seed)));
185        let back = fft2d(&fft2d(&x, false).unwrap(), true).unwrap();
186        assert!(x.iter().zip(back.iter()).all(|(a, b)| (a - b).norm() < 1e-12));
187        // A single impulse transforms to a flat spectrum.
188        let mut imp = Array2::<Complex<f64>>::zeros((4, 4));
189        imp[(0, 0)] = Complex::new(1.0, 0.0);
190        assert!(fft2d(&imp, false).unwrap().iter().all(|v| (v - Complex::new(1.0, 0.0)).norm() < 1e-12));
191    }
192}