Skip to main content

lib_jsl_dsp/discrete/spectral/
goertzel.rs

1//! The Goertzel algorithm for single DFT bins.
2//!
3//! See the book entry [Spectra at chosen frequencies: Goertzel, chirp-z and Fourier integrals](https://jwkunz.github.io/lib_jsl/book/spectral/chosen-frequencies.html#goertzels-recursion).
4
5use lib_jsl_core::ErrorsJSL;
6use num_complex::Complex;
7use std::f64::consts::TAU;
8
9/// The DFT of `x` at one (possibly non-integer) bin `k`, `X(k) = Σ x_n e^{−2πi k n / N}`, by the
10/// generalised Goertzel recursion `s_n = x_n + 2cos(ω) s_{n−1} − s_{n−2}` (`ω = 2πk/N`) and a final
11/// phase correction. Costs one real multiply-add per sample, so it beats an FFT when only a few
12/// bins are needed (tone detection).
13pub fn goertzel(x: &[f64], k: f64) -> Result<Complex<f64>, ErrorsJSL> {
14    let n = x.len();
15    if n == 0 || !k.is_finite() {
16        return Err(ErrorsJSL::InvalidInputRange("Need a non-empty signal and a finite bin."));
17    }
18    // ANCHOR: goertzel
19    let omega = TAU * k / n as f64;
20    let coefficient = 2.0 * omega.cos();
21    let (mut s1, mut s2) = (0.0, 0.0);
22    for &v in x {
23        let s0 = v + coefficient * s1 - s2;
24        s2 = s1;
25        s1 = s0;
26    }
27    // y_{N−1} = s_{N−1} − e^{−iω} s_{N−2} = e^{iω(N−1)} X(k); undo the phase.
28    let y = Complex::new(s1, 0.0) - Complex::from_polar(1.0, -omega) * s2;
29    Ok(y * Complex::from_polar(1.0, -omega * (n - 1) as f64))
30    // ANCHOR_END: goertzel
31}
32
33/// `|X(k)|²` at bin `k` without the final complex rotation:
34/// `s_{N−1}² + s_{N−2}² − 2cos(ω) s_{N−1} s_{N−2}`.
35pub fn goertzel_power(x: &[f64], k: f64) -> Result<f64, ErrorsJSL> {
36    let n = x.len();
37    if n == 0 || !k.is_finite() {
38        return Err(ErrorsJSL::InvalidInputRange("Need a non-empty signal and a finite bin."));
39    }
40    let coefficient = 2.0 * (TAU * k / n as f64).cos();
41    let (mut s1, mut s2) = (0.0, 0.0);
42    for &v in x {
43        let s0 = v + coefficient * s1 - s2;
44        s2 = s1;
45        s1 = s0;
46    }
47    Ok(s1 * s1 + s2 * s2 - coefficient * s1 * s2)
48}
49
50/// The DFT at frequency `f` (Hz) of `x` sampled at `fs`.
51pub fn goertzel_frequency(x: &[f64], f: f64, fs: f64) -> Result<Complex<f64>, ErrorsJSL> {
52    goertzel(x, f * x.len() as f64 / fs)
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    fn dft(x: &[f64], k: f64) -> Complex<f64> {
60        x.iter().enumerate().map(|(n, &v)| Complex::from_polar(v, -TAU * k * n as f64 / x.len() as f64)).sum()
61    }
62
63    #[test]
64    fn matches_the_direct_dft_at_integer_and_fractional_bins() {
65        let x: Vec<f64> = (0..137).map(|i| (0.3 * i as f64).sin() + 0.1 * ((i * i) % 13) as f64).collect();
66        for k in [0.0, 1.0, 7.0, 21.5, 68.0, 100.25] {
67            let g = goertzel(&x, k).unwrap();
68            assert!((g - dft(&x, k)).norm() < 1e-9, "k={k}");
69            assert!((goertzel_power(&x, k).unwrap() - g.norm_sqr()).abs() < 1e-8 * (1.0 + g.norm_sqr()));
70        }
71        assert!(goertzel(&[], 1.0).is_err());
72    }
73
74    #[test]
75    fn detects_dtmf_digits() {
76        // Digit 9 = 852 Hz + 1477 Hz at 8 kHz over 205 samples (the classic DTMF block).
77        let fs = 8000.0;
78        let x: Vec<f64> = (0..205).map(|i| { let t = i as f64 / fs; (TAU * 852.0 * t).sin() + (TAU * 1477.0 * t).sin() }).collect();
79        let rows = [697.0, 770.0, 852.0, 941.0];
80        let columns = [1209.0, 1336.0, 1477.0];
81        let strongest = |freqs: &[f64]| (0..freqs.len()).max_by(|&i, &j| goertzel_frequency(&x, freqs[i], fs).unwrap().norm().total_cmp(&goertzel_frequency(&x, freqs[j], fs).unwrap().norm())).unwrap();
82        assert_eq!((rows[strongest(&rows)], columns[strongest(&columns)]), (852.0, 1477.0));
83    }
84}