Skip to main content

lib_jsl_dsp/discrete/
fft_cross_correlation.rs

1//! FFT-based cross-correlation, similar to `scipy.signal.correlate(..., method="fft")`.
2//!
3//! See the book entry [Convolution and correlation](https://jwkunz.github.io/lib_jsl/book/filters/convolution.html#cross-correlation-and-delay-estimation).
4
5use crate::{
6    discrete::{
7        convolve::ConvolveMode,
8        cross_correlation::{cross_correlation_lags, CorrelationMode},
9        fft_convolution::fft_convolve,
10    },
11    prelude::{ErrorsJSL, IsAnalytic},
12};
13
14fn map_mode(mode: CorrelationMode) -> ConvolveMode {
15    match mode {
16        CorrelationMode::Full => ConvolveMode::Full,
17        CorrelationMode::Same => ConvolveMode::Same,
18        CorrelationMode::Valid => ConvolveMode::Valid,
19    }
20}
21
22/// Cross-correlation of `in1` with `in2` computed with FFTs: `correlate(a, b) = convolve(a,
23/// reverse(conj(b)))`, so `out[k]` measures how well `in2` delayed by the corresponding lag
24/// matches `in1` (see [`cross_correlation_lags`] for the lag of each output).
25pub fn fft_cross_correlate<T: IsAnalytic>(in1: &[T], in2: &[T], mode: CorrelationMode) -> Result<Vec<T>, ErrorsJSL> {
26    if in1.is_empty() || in2.is_empty() {
27        return Err(ErrorsJSL::InvalidInputRange("Input arrays must be non-empty"));
28    }
29    let rhs: Vec<T> = in2.iter().rev().map(|x| x.f_conj()).collect();
30    fft_convolve(in1, &rhs, map_mode(mode))
31}
32
33/// Autocorrelation of `x` with itself (full mode: lags `-(n-1)..=n-1`, peak at lag 0).
34pub fn fft_autocorrelate<T: IsAnalytic>(x: &[T]) -> Result<Vec<T>, ErrorsJSL> {
35    fft_cross_correlate(x, x, CorrelationMode::Full)
36}
37
38/// Finds the lag at which `in1` best matches `in2` (the peak of the magnitude of their full
39/// cross-correlation). A positive lag means `in1` is `in2` delayed by that many samples.
40/// Returns `(lag, correlation value at the peak)`.
41pub fn fft_correlation_peak<T: IsAnalytic>(in1: &[T], in2: &[T]) -> Result<(isize, T), ErrorsJSL> {
42    let c = fft_cross_correlate(in1, in2, CorrelationMode::Full)?;
43    let lags = cross_correlation_lags(in1.len(), in2.len(), CorrelationMode::Full);
44    let (idx, _) = c
45        .iter()
46        .enumerate()
47        .max_by(|a, b| a.1.f_abs().partial_cmp(&b.1.f_abs()).unwrap())
48        .expect("non-empty result");
49    Ok((lags[idx], c[idx]))
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55    use crate::discrete::convolve::ConvolveMethod;
56    use crate::discrete::cross_correlation::cross_correlate;
57    use num_complex::Complex;
58
59    fn lcg(seed: &mut u64) -> f64 {
60        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
61        ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
62    }
63
64    #[test]
65    fn matches_the_direct_method_in_every_mode() {
66        let mut seed = 21;
67        for (n, m) in [(50usize, 8usize), (8, 50), (33, 33)] {
68            let a: Vec<f64> = (0..n).map(|_| lcg(&mut seed)).collect();
69            let b: Vec<f64> = (0..m).map(|_| lcg(&mut seed)).collect();
70            for mode in [CorrelationMode::Full, CorrelationMode::Same, CorrelationMode::Valid] {
71                let want = cross_correlate(&a, &b, mode, ConvolveMethod::Direct).unwrap();
72                let got = fft_cross_correlate(&a, &b, mode).unwrap();
73                assert_eq!(got.len(), want.len());
74                assert!(got.iter().zip(&want).all(|(g, w)| (g - w).abs() < 1e-11), "{mode:?} {n}x{m}");
75            }
76        }
77    }
78
79    #[test]
80    fn complex_correlation_conjugates_the_second_input() {
81        let mut seed = 4;
82        let a: Vec<Complex<f64>> = (0..40).map(|_| Complex::new(lcg(&mut seed), lcg(&mut seed))).collect();
83        let b: Vec<Complex<f64>> = (0..10).map(|_| Complex::new(lcg(&mut seed), lcg(&mut seed))).collect();
84        let want = cross_correlate(&a, &b, CorrelationMode::Full, ConvolveMethod::Direct).unwrap();
85        let got = fft_cross_correlate(&a, &b, CorrelationMode::Full).unwrap();
86        assert!(got.iter().zip(&want).all(|(g, w)| (g - w).norm() < 1e-11));
87    }
88
89    #[test]
90    fn finds_the_delay_of_a_buried_template() {
91        let mut seed = 8;
92        let template: Vec<f64> = (0..64).map(|_| lcg(&mut seed)).collect();
93        let mut signal: Vec<f64> = (0..1000).map(|_| 0.3 * lcg(&mut seed)).collect();
94        for (i, t) in template.iter().enumerate() {
95            signal[371 + i] += t;
96        }
97        let (lag, value) = fft_correlation_peak(&signal, &template).unwrap();
98        assert_eq!(lag, 371);
99        let energy: f64 = template.iter().map(|t| t * t).sum();
100        assert!((value - energy).abs() < 0.2 * energy, "peak {value} vs template energy {energy}");
101        // And the other way round: the template is "advanced" by that lag relative to the signal.
102        assert_eq!(fft_correlation_peak(&template, &signal).unwrap().0, -371);
103    }
104
105    #[test]
106    fn autocorrelation_is_symmetric_with_its_peak_at_zero_lag() {
107        let mut seed = 31;
108        let x: Vec<f64> = (0..60).map(|_| lcg(&mut seed)).collect();
109        let r = fft_autocorrelate(&x).unwrap();
110        assert_eq!(r.len(), 119);
111        let energy: f64 = x.iter().map(|v| v * v).sum();
112        assert!((r[59] - energy).abs() < 1e-10);
113        for k in 1..59 {
114            assert!((r[59 - k] - r[59 + k]).abs() < 1e-10);
115            assert!(r[59 + k].abs() <= energy + 1e-10);
116        }
117    }
118
119    #[test]
120    fn rejects_empty_inputs() {
121        assert!(fft_cross_correlate::<f64>(&[], &[1.0], CorrelationMode::Full).is_err());
122        assert!(fft_correlation_peak::<f64>(&[1.0], &[]).is_err());
123    }
124}