Skip to main content

lib_jsl_dsp/discrete/
convolve.rs

1//! This module implements 1D convolution, similar to scipy.signal.convolve.
2//! It supports three modes: 'full', 'same', and 'valid', and can use direct
3//! or FFT-based convolution for analytic scalar types.
4//!
5//! See the book entry [Convolution and correlation](https://jwkunz.github.io/lib_jsl/book/filters/convolution.html).
6
7use crate::{
8    ffts::{
9        Fft,
10        fft_engine_trait::{FftEngine1D, FftDirection, FftOrdering, FftScaleFactor},
11    },
12    prelude::{ErrorsJSL, IsAnalytic},
13};
14use num_complex::Complex;
15
16#[derive(Clone, Copy, Debug)]
17pub enum ConvolveMode {
18    /// 'full' returns the convolution at each point of overlap, with an output size of in1.len() + in2.len() - 1.
19    Full,
20    /// 'same' returns the central part of the full convolution, with an output size of in1.len() (the same as the first input).
21    Same,
22    /// 'valid' returns the convolution at points where the signals overlap completely without zero-padding, with an output size of max(in1.len(), in2.len()) - min(in1.len(), in2.len()) + 1.
23    Valid,
24}
25
26#[derive(Clone, Copy, Debug)]
27pub enum ConvolveMethod {
28    /// 'auto' chooses the method based on the input sizes.
29    Auto,
30    /// 'direct' computes the convolution using a straightforward nested loop approach, which is efficient for small input sizes.
31    Direct,
32    /// 'fft' computes convolution using the Fast Fourier Transform.
33    Fft,
34}
35
36fn direct_full<T: IsAnalytic>(in1: &[T], in2: &[T]) -> Vec<T> {
37    let mut out = vec![T::zero(); in1.len() + in2.len() - 1];
38    for (i, &x) in in1.iter().enumerate() {
39        for (j, &h) in in2.iter().enumerate() {
40            out[i + j] += x * h;
41        }
42    }
43    out
44}
45
46pub(crate) fn fft_full<T: IsAnalytic>(in1: &[T], in2: &[T]) -> Result<Vec<T>, ErrorsJSL> {
47    let n = in1.len() + in2.len() - 1;
48    let nfft = n.next_power_of_two();
49
50    let mut a = vec![Complex::new(0.0, 0.0); nfft];
51    let mut b = vec![Complex::new(0.0, 0.0); nfft];
52    for (i, &v) in in1.iter().enumerate() {
53        a[i] = v.to_complex();
54    }
55    for (i, &v) in in2.iter().enumerate() {
56        b[i] = v.to_complex();
57    }
58
59    let mut fft = Fft::new();
60    fft.plan(
61        nfft,
62        FftScaleFactor::None,
63        FftDirection::Forward,
64        FftOrdering::Standard,
65    )?;
66    let a_fft = fft.execute(&a)?;
67    let b_fft = fft.execute(&b)?;
68
69    let mut c_fft = vec![Complex::new(0.0, 0.0); nfft];
70    for i in 0..nfft {
71        c_fft[i] = a_fft[i] * b_fft[i];
72    }
73
74    let mut ifft = Fft::new();
75    ifft.plan(
76        nfft,
77        FftScaleFactor::N,
78        FftDirection::Inverse,
79        FftOrdering::Standard,
80    )?;
81    let c = ifft.execute(&c_fft)?;
82    Ok(c.into_iter().take(n).map(T::from_complex).collect())
83}
84
85pub(crate) fn apply_mode<T: IsAnalytic>(full: Vec<T>, in1_len: usize, in2_len: usize, mode: ConvolveMode) -> Vec<T> {
86    match mode {
87        ConvolveMode::Full => full,
88        ConvolveMode::Same => {
89            let start = (in2_len - 1) / 2;
90            full[start..start + in1_len].to_vec()
91        }
92        ConvolveMode::Valid => {
93            if in1_len >= in2_len {
94                let start = in2_len - 1;
95                let len = in1_len - in2_len + 1;
96                full[start..start + len].to_vec()
97            } else {
98                let start = in1_len - 1;
99                let len = in2_len - in1_len + 1;
100                full[start..start + len].to_vec()
101            }
102        }
103    }
104}
105
106/// 1D convolution, similar to scipy.signal.convolve.
107pub fn convolve<T: IsAnalytic>(
108    in1: &[T],
109    in2: &[T],
110    mode: ConvolveMode,
111    method: ConvolveMethod,
112) -> Result<Vec<T>, ErrorsJSL> {
113    if in1.is_empty() || in2.is_empty() {
114        return Err(ErrorsJSL::InvalidInputRange("Input arrays must be non-empty"));
115    }
116
117    let full = match method {
118        ConvolveMethod::Direct => direct_full(in1, in2),
119        ConvolveMethod::Fft => fft_full(in1, in2)?,
120        ConvolveMethod::Auto => {
121            let work = in1.len().saturating_mul(in2.len());
122            if work <= 4096 {
123                direct_full(in1, in2)
124            } else {
125                fft_full(in1, in2)?
126            }
127        }
128    };
129    Ok(apply_mode(full, in1.len(), in2.len(), mode))
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    fn parse_csv(csv: &str) -> Vec<f64> {
137        csv.lines()
138            .filter(|l| !l.trim().is_empty())
139            .map(|l| l.trim().parse::<f64>().unwrap())
140            .collect()
141    }
142
143    #[test]
144    fn test_convolve_doc_example_full_golden() {
145        let in1 = [1.0, 2.0, 3.0];
146        let in2 = [0.0, 1.0, 0.5];
147        let y = convolve(&in1, &in2, ConvolveMode::Full, ConvolveMethod::Direct).unwrap();
148        let golden = parse_csv(include_str!("test_data/convolve_doc_full.csv"));
149        assert_eq!(y.len(), golden.len());
150        for (a, g) in y.iter().zip(golden.iter()) {
151            assert!((a - g).abs() < 1e-12, "actual={a}, golden={g}");
152        }
153    }
154
155    #[test]
156    fn test_convolve_doc_example_same_and_valid_golden() {
157        let in1 = [1.0, 2.0, 3.0];
158        let in2 = [0.0, 1.0, 0.5];
159        let same = convolve(&in1, &in2, ConvolveMode::Same, ConvolveMethod::Direct).unwrap();
160        let valid = convolve(&in1, &in2, ConvolveMode::Valid, ConvolveMethod::Direct).unwrap();
161        let golden_same = parse_csv(include_str!("test_data/convolve_doc_same.csv"));
162        let golden_valid = parse_csv(include_str!("test_data/convolve_doc_valid.csv"));
163        assert_eq!(same, golden_same);
164        assert_eq!(valid, golden_valid);
165    }
166
167    #[test]
168    fn test_convolve_fft_matches_direct() {
169        let in1 = [0.2, -1.0, 0.5, 2.0, -0.7, 0.3, 1.1];
170        let in2 = [1.0, -0.25, 0.75, -0.5];
171        let yd = convolve(&in1, &in2, ConvolveMode::Full, ConvolveMethod::Direct).unwrap();
172        let yf = convolve(&in1, &in2, ConvolveMode::Full, ConvolveMethod::Fft).unwrap();
173        assert_eq!(yd.len(), yf.len());
174        for (a, b) in yd.iter().zip(yf.iter()) {
175            assert!((a - b).abs() < 1e-9, "direct={a}, fft={b}");
176        }
177    }
178
179    #[test]
180    fn test_convolve_generic_complex_fft_matches_direct() {
181        use num_complex::Complex;
182        let in1 = [
183            Complex::new(1.0, 1.0),
184            Complex::new(2.0, -1.0),
185            Complex::new(0.5, 0.25),
186        ];
187        let in2 = [Complex::new(0.0, 1.0), Complex::new(1.0, 0.0)];
188        let yd = convolve(&in1, &in2, ConvolveMode::Full, ConvolveMethod::Direct).unwrap();
189        let yf = convolve(&in1, &in2, ConvolveMode::Full, ConvolveMethod::Fft).unwrap();
190        assert_eq!(yd.len(), yf.len());
191        for (a, b) in yd.iter().zip(yf.iter()) {
192            assert!((a.re - b.re).abs() < 1e-9 && (a.im - b.im).abs() < 1e-9);
193        }
194    }
195}