Skip to main content

lib_jsl_ffts/
real_fft.rs

1//! FFTs of real-valued signals.
2//!
3//! See the book entry [Real and multidimensional FFTs](https://jwkunz.github.io/lib_jsl/book/fft/real-multidimensional.html#the-real-fft-by-half-length-packing).
4
5use crate::fft::Fft;
6use crate::fft_engine_trait::{FftDirection, FftEngine1D, FftOrdering, FftScaleFactor};
7use lib_jsl_core::ErrorsJSL;
8use num_complex::Complex;
9use std::f64::consts::TAU;
10
11type C64 = Complex<f64>;
12
13/// A planned FFT for real input of length `n`. The spectrum of a real signal is conjugate
14/// symmetric, so only the `n/2 + 1` non-negative-frequency bins are returned.
15///
16/// For even `n` the signal is packed into a complex sequence of half the length (even samples as
17/// real parts, odd samples as imaginary parts), transformed, and untangled with one twiddle per
18/// bin. For `n` of a few thousand or more this takes a quarter to a third less time than a complex
19/// FFT of the real data; for `n` up to about a thousand the O(n) packing and untangling cost as
20/// much as the shorter FFT saves (and more for very short signals). Odd lengths use a full
21/// complex transform. The forward transform is unscaled; [`RealFft::inverse`] divides by `n`, so it
22/// exactly inverts [`RealFft::forward`].
23#[derive(Debug)]
24pub struct RealFft {
25    n: usize,
26    forward: Fft,
27    inverse: Fft,
28    twiddles: Vec<C64>,
29}
30
31impl RealFft {
32    pub fn new(n: usize) -> Result<Self, ErrorsJSL> {
33        if n == 0 {
34            return Err(ErrorsJSL::InvalidInputRange("The length must be positive."));
35        }
36        let inner = if n.is_multiple_of(2) { n / 2 } else { n };
37        let forward = Fft::with_plan(inner, FftScaleFactor::None, FftDirection::Forward, FftOrdering::Standard)?;
38        let inverse = Fft::with_plan(inner, FftScaleFactor::N, FftDirection::Inverse, FftOrdering::Standard)?;
39        let twiddles = (0..=n / 2).map(|k| C64::from_polar(1.0, -TAU * k as f64 / n as f64)).collect();
40        Ok(RealFft { n, forward, inverse, twiddles })
41    }
42
43    /// The signal length.
44    pub fn len(&self) -> usize {
45        self.n
46    }
47
48    pub fn is_empty(&self) -> bool {
49        self.n == 0
50    }
51
52    /// The number of spectrum bins, `n/2 + 1`.
53    pub fn spectrum_len(&self) -> usize {
54        self.n / 2 + 1
55    }
56
57    // ANCHOR: real_forward
58    /// The bins `X_0 ..= X_{n/2}` of the unscaled DFT `X_k = Σ x_m e^{-2πi km/n}`.
59    pub fn forward(&mut self, x: &[f64]) -> Result<Vec<C64>, ErrorsJSL> {
60        if x.len() != self.n {
61            return Err(ErrorsJSL::IncompatibleArraySizes((x.len(), self.n)));
62        }
63        if !self.n.is_multiple_of(2) {
64            let full = self.forward.execute(&x.iter().map(|&v| C64::new(v, 0.0)).collect::<Vec<_>>())?;
65            return Ok(full[..self.spectrum_len()].to_vec());
66        }
67        let m = self.n / 2;
68        let packed: Vec<C64> = (0..m).map(|j| C64::new(x[2 * j], x[2 * j + 1])).collect();
69        let z = self.forward.execute(&packed)?;
70        // X_k = ½[(Z_k + conj Z_{m−k}) − i w_k (Z_k − conj Z_{m−k})], w_k = e^{−2πik/n}. The bins k and
71        // m − k use the same two values of Z and are computed together; only k = 0 and k = m wrap
72        // around (Z_m = Z_0). (An earlier version took two integer moduli per bin to handle the
73        // wrap-around, which cost more than the half-length FFT itself.)
74        let mut out = vec![C64::new(0.0, 0.0); m + 1];
75        out[0] = C64::new(z[0].re + z[0].im, 0.0);
76        out[m] = C64::new(z[0].re - z[0].im, 0.0);
77        for k in 1..=m / 2 {
78            let (a, b) = (z[k], z[m - k]);
79            let (sum, difference) = (a + b.conj(), a - b.conj());
80            let wd = self.twiddles[k] * difference;
81            out[k] = C64::new(0.5 * (sum.re + wd.im), 0.5 * (sum.im - wd.re));
82            let (sum, difference) = (b + a.conj(), b - a.conj());
83            let wd = self.twiddles[m - k] * difference;
84            out[m - k] = C64::new(0.5 * (sum.re + wd.im), 0.5 * (sum.im - wd.re));
85        }
86        Ok(out)
87    }
88    // ANCHOR_END: real_forward
89
90    /// The real signal whose spectrum bins are `spectrum` (`n/2 + 1` values; the imaginary parts
91    /// of `X_0`, and of `X_{n/2}` for even `n`, are ignored as they must vanish).
92    pub fn inverse(&mut self, spectrum: &[C64]) -> Result<Vec<f64>, ErrorsJSL> {
93        if spectrum.len() != self.spectrum_len() {
94            return Err(ErrorsJSL::IncompatibleArraySizes((spectrum.len(), self.spectrum_len())));
95        }
96        let n = self.n;
97        if !n.is_multiple_of(2) {
98            let full: Vec<C64> = (0..n).map(|k| if k < spectrum.len() { spectrum[k] } else { spectrum[n - k].conj() }).collect();
99            let mut full = full;
100            full[0].im = 0.0;
101            return Ok(self.inverse.execute(&full)?.iter().map(|v| v.re).collect());
102        }
103        let m = n / 2;
104        let mut s = spectrum.to_vec();
105        s[0].im = 0.0;
106        s[m].im = 0.0;
107        let z: Vec<C64> = (0..m)
108            .map(|k| {
109                let (a, b) = (s[k], s[m - k].conj());
110                let even = (a + b) * 0.5;
111                let odd = (a - b) * 0.5 * self.twiddles[k].conj();
112                even + C64::new(0.0, 1.0) * odd
113            })
114            .collect();
115        let packed = self.inverse.execute(&z)?;
116        Ok(packed.iter().flat_map(|v| [v.re, v.im]).collect())
117    }
118}
119
120/// One-shot real FFT: the `n/2 + 1` non-negative-frequency bins of a real signal.
121pub fn rfft(x: &[f64]) -> Result<Vec<C64>, ErrorsJSL> {
122    RealFft::new(x.len())?.forward(x)
123}
124
125/// One-shot inverse real FFT for a signal of length `n`.
126pub fn irfft(spectrum: &[C64], n: usize) -> Result<Vec<f64>, ErrorsJSL> {
127    RealFft::new(n)?.inverse(spectrum)
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    fn dft(x: &[f64]) -> Vec<C64> {
135        let n = x.len();
136        (0..n).map(|k| x.iter().enumerate().map(|(m, &v)| C64::from_polar(v, -TAU * ((k * m) % n) as f64 / n as f64)).sum()).collect()
137    }
138
139    fn signal(n: usize) -> Vec<f64> {
140        (0..n).map(|i| (i as f64 * 0.37).sin() + 0.2 * (i as f64).powf(0.5) - 0.5 * ((i * 7) % 5) as f64).collect()
141    }
142
143    #[test]
144    fn matches_the_complex_dft_for_even_odd_and_power_of_two_lengths() {
145        for n in [1, 2, 3, 4, 5, 6, 8, 9, 12, 15, 16, 31, 64, 100, 127, 256] {
146            let x = signal(n);
147            let got = rfft(&x).unwrap();
148            let want = dft(&x);
149            assert_eq!(got.len(), n / 2 + 1);
150            let worst = got.iter().zip(&want).map(|(a, b)| (a - b).norm()).fold(0.0, f64::max);
151            assert!(worst < 1e-9 * n as f64, "n = {n}: {worst}");
152            let back = irfft(&got, n).unwrap();
153            assert!(back.iter().zip(&x).all(|(a, b)| (a - b).abs() < 1e-10), "round trip n = {n}");
154        }
155    }
156
157    #[test]
158    fn planned_reuse_and_validation() {
159        let mut plan = RealFft::new(10).unwrap();
160        assert_eq!((plan.len(), plan.spectrum_len()), (10, 6));
161        for seed in 0..3 {
162            let x: Vec<f64> = (0..10).map(|i| ((i + seed) as f64).cos()).collect();
163            let s = plan.forward(&x).unwrap();
164            assert!(s[0].im.abs() < 1e-12 && s[5].im.abs() < 1e-12); // DC and Nyquist are real
165            assert!(plan.inverse(&s).unwrap().iter().zip(&x).all(|(a, b)| (a - b).abs() < 1e-12));
166        }
167        assert!(plan.forward(&[1.0; 3]).is_err() && plan.inverse(&[C64::new(0.0, 0.0); 3]).is_err());
168        assert!(RealFft::new(0).is_err());
169        // A pure cosine puts all its energy in one bin.
170        let n = 64;
171        let x: Vec<f64> = (0..n).map(|i| (TAU * 5.0 * i as f64 / n as f64).cos()).collect();
172        let s = rfft(&x).unwrap();
173        assert!((s[5].re - 32.0).abs() < 1e-9 && s.iter().enumerate().filter(|(k, _)| *k != 5).all(|(_, v)| v.norm() < 1e-9));
174    }
175}