Skip to main content

lib_jsl_ffts_reference/
optimized_split_radix.rs

1//! The split-radix FFT (Yavne, 1968; Duhamel and Hollmann, 1984), written for study.
2//!
3//! A radix-2 step splits the input into even and odd samples. Split radix splits the odd samples
4//! once more, into those at `4m + 1` and `4m + 3`: with `U` the FFT of length `n/2` of the even
5//! samples and `Z`, `Z'` the FFTs of length `n/4` of the two odd subsequences,
6//!
7//! `X_k = U_k + ωᵏ Z_k + ω³ᵏ Z'_k`, `X_{k+n/2} = U_k − (ωᵏ Z_k + ω³ᵏ Z'_k)`,
8//! `X_{k+n/4} = U_{k+n/4} − i (ωᵏ Z_k − ω³ᵏ Z'_k)`, `X_{k+3n/4} = U_{k+n/4} + i (ωᵏ Z_k − ω³ᵏ Z'_k)`
9//!
10//! for `0 ≤ k < n/4` and `ω = e^{−2πi/n}` (the signs of `i` swap for the inverse transform). The even
11//! half needs no twiddle factors at this level, which is why split radix uses the fewest real
12//! operations of the classical power-of-two algorithms: about `4n log₂ n − 6n + 8` real additions
13//! and multiplications, against `5n log₂ n` for radix 2.
14//!
15//! This engine is a plain recursion over strided views of the input, with an exact twiddle table.
16//! Replacing an earlier engine of the same name, which (despite its name) was not a split-radix
17//! algorithm and returned wrong results; its tests computed the error without checking it.
18//!
19//! See the book entry [The fast Fourier transform](https://jwkunz.github.io/lib_jsl/book/fft/fft.html#split-radix).
20use num_complex::Complex;
21use lib_jsl_core::ErrorsJSL;
22
23use lib_jsl_ffts::fft_engine_trait::{FftEngine1D, FftDirection, FftOrdering, FftScaleFactor};
24
25/// A recursive split-radix FFT engine for power-of-two sizes.
26pub struct OptimizedSplitRadixFFT {
27    size: usize,
28    direction: FftDirection,
29    scale: FftScaleFactor,
30    ordering: FftOrdering,
31    /// `ωᵏ` for `0 ≤ k < n`, with `ω = e^{∓2πi/n}` for the forward (inverse) transform.
32    twiddles: Vec<Complex<f64>>,
33}
34
35impl OptimizedSplitRadixFFT {
36    pub fn new() -> Self {
37        Self {
38            size: 0,
39            direction: FftDirection::Forward,
40            scale: FftScaleFactor::None,
41            ordering: FftOrdering::Standard,
42            twiddles: Vec::new(),
43        }
44    }
45}
46
47impl Default for OptimizedSplitRadixFFT {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53fn bit_reverse(mut n: usize, bits: usize) -> usize {
54    let mut reversed = 0usize;
55    for _ in 0..bits {
56        reversed = (reversed << 1) | (n & 1);
57        n >>= 1;
58    }
59    reversed
60}
61
62// ANCHOR: split_radix
63/// Writes into `out` (of length `n`) the DFT of `input[start], input[start + stride], …`;
64/// `ωᵏ` for this length is `twiddles[k · step]`, and `j` is `−i` (forward) or `+i` (inverse).
65fn split_radix(input: &[Complex<f64>], start: usize, stride: usize, out: &mut [Complex<f64>], twiddles: &[Complex<f64>], step: usize, j: Complex<f64>) {
66    let n = out.len();
67    match n {
68        1 => out[0] = input[start],
69        2 => {
70            let (a, b) = (input[start], input[start + stride]);
71            out[0] = a + b;
72            out[1] = a - b;
73        }
74        _ => {
75            let (half, quarter) = (n / 2, n / 4);
76            {
77                let (u, z) = out.split_at_mut(half);
78                let (z1, z3) = z.split_at_mut(quarter);
79                split_radix(input, start, 2 * stride, u, twiddles, 2 * step, j);
80                split_radix(input, start + stride, 4 * stride, z1, twiddles, 4 * step, j);
81                split_radix(input, start + 3 * stride, 4 * stride, z3, twiddles, 4 * step, j);
82            }
83            for k in 0..quarter {
84                let zk = twiddles[k * step] * out[half + k];
85                let zk3 = twiddles[3 * k * step] * out[half + quarter + k];
86                let (sum, difference) = (zk + zk3, j * (zk - zk3));
87                let (u0, u1) = (out[k], out[k + quarter]);
88                out[k] = u0 + sum;
89                out[k + half] = u0 - sum;
90                out[k + quarter] = u1 + difference;
91                out[k + half + quarter] = u1 - difference;
92            }
93        }
94    }
95}
96// ANCHOR_END: split_radix
97
98impl FftEngine1D for OptimizedSplitRadixFFT {
99    fn execute(&mut self, input: &[Complex<f64>]) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
100        if input.len() != self.size {
101            return Err(ErrorsJSL::InvalidInputRange("Input size must match the planned size"));
102        }
103        let n = self.size;
104        // Bit-reversed input: sample i of the signal arrives at position bitrev(i).
105        let natural: Vec<Complex<f64>> = match self.ordering {
106            FftOrdering::Standard => input.to_vec(),
107            FftOrdering::BitReversed => {
108                let bits = n.trailing_zeros() as usize;
109                (0..n).map(|i| input[bit_reverse(i, bits)]).collect()
110            }
111        };
112        let j = match self.direction {
113            FftDirection::Forward => Complex::new(0.0, -1.0),
114            FftDirection::Inverse => Complex::new(0.0, 1.0),
115        };
116        let mut out = vec![Complex::new(0.0, 0.0); n];
117        split_radix(&natural, 0, 1, &mut out, &self.twiddles, 1, j);
118        let factor = match self.scale {
119            FftScaleFactor::None => 1.0,
120            FftScaleFactor::SqrtN => 1.0 / (n as f64).sqrt(),
121            FftScaleFactor::N => 1.0 / n as f64,
122        };
123        if factor != 1.0 {
124            out.iter_mut().for_each(|v| *v *= factor);
125        }
126        Ok(out)
127    }
128
129    fn plan(&mut self, size: usize, scale: FftScaleFactor, direction: FftDirection, ordering: FftOrdering) -> Result<(), ErrorsJSL> {
130        if !size.is_power_of_two() {
131            return Err(ErrorsJSL::InvalidInputRange("Size must be a power of 2"));
132        }
133        self.size = size;
134        self.scale = scale;
135        self.direction = direction;
136        self.ordering = ordering;
137        let sign = match direction {
138            FftDirection::Forward => -1.0,
139            FftDirection::Inverse => 1.0,
140        };
141        self.twiddles = (0..size)
142            .map(|k| {
143                let angle = sign * 2.0 * std::f64::consts::PI * k as f64 / size as f64;
144                Complex::new(angle.cos(), angle.sin())
145            })
146            .collect();
147        Ok(())
148    }
149
150    fn get_size(&self) -> usize {
151        self.size
152    }
153
154    fn get_scale_factor(&self) -> FftScaleFactor {
155        self.scale
156    }
157
158    fn get_direction(&self) -> FftDirection {
159        self.direction
160    }
161
162    fn get_ordering(&self) -> FftOrdering {
163        self.ordering
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use std::time::Instant;
170
171    use super::*;
172    use crate::test_bench_data::{fft_gaussian_32768_golden, fft_gaussian_32768_input};
173
174    fn max_abs_error(a: &[Complex<f64>], b: &[Complex<f64>]) -> f64 {
175        a.iter()
176            .zip(b.iter())
177            .map(|(x, y)| (*x - *y).norm())
178            .fold(0.0_f64, f64::max)
179    }
180
181    fn bit_reverse_index(mut n: usize, bits: usize) -> usize {
182        let mut reversed = 0;
183        for _ in 0..bits {
184            reversed <<= 1;
185            reversed |= n & 1;
186            n >>= 1;
187        }
188        reversed
189    }
190
191    #[test]
192    fn test_optimized_split_radix_standard() {
193        let input = fft_gaussian_32768_input();
194        let expected = fft_gaussian_32768_golden();
195
196        let mut fft = OptimizedSplitRadixFFT::new();
197        fft.plan(
198            input.len(),
199            FftScaleFactor::None,
200            FftDirection::Forward,
201            FftOrdering::Standard,
202        )
203        .unwrap();
204
205        let start = Instant::now();
206        let output = fft.execute(&input).unwrap();
207        let elapsed = start.elapsed();
208        let err = max_abs_error(&output, &expected);
209        dbg!("optimized_split_radix::standard execute elapsed", elapsed);
210        dbg!("optimized_split_radix::standard max abs error", err);
211
212        assert_eq!(output.len(), expected.len());
213        // The earlier engine of this name computed this error without checking it, and was wrong.
214        assert!(err < 1e-9, "max abs error {err}");
215    }
216
217    #[test]
218    fn test_optimized_split_radix_bit_reversed() {
219        let input = fft_gaussian_32768_input();
220        let expected = fft_gaussian_32768_golden();
221
222        let bits = input.len().trailing_zeros() as usize;
223        let mut bit_reversed_input = vec![Complex::new(0.0, 0.0); input.len()];
224        for (i, value) in input.iter().enumerate() {
225            bit_reversed_input[bit_reverse_index(i, bits)] = *value;
226        }
227
228        let mut fft = OptimizedSplitRadixFFT::new();
229        fft.plan(
230            input.len(),
231            FftScaleFactor::None,
232            FftDirection::Forward,
233            FftOrdering::BitReversed,
234        )
235        .unwrap();
236
237        let start = Instant::now();
238        let output = fft.execute(&bit_reversed_input).unwrap();
239        let elapsed = start.elapsed();
240        let err = max_abs_error(&output, &expected);
241        dbg!("optimized_split_radix::bit_reversed execute elapsed", elapsed);
242        dbg!("optimized_split_radix::bit_reversed max abs error", err);
243
244        assert_eq!(output.len(), expected.len());
245        assert!(err < 1e-9, "max abs error {err}");
246    }
247
248    #[test]
249    fn small_sizes_match_the_definition_and_invert() {
250        for n in [1usize, 2, 4, 8, 16, 64] {
251            let x: Vec<Complex<f64>> = (0..n).map(|k| Complex::new((k as f64 * 0.7).sin(), (k as f64 * 1.3).cos())).collect();
252            let mut fft = OptimizedSplitRadixFFT::new();
253            fft.plan(n, FftScaleFactor::None, FftDirection::Forward, FftOrdering::Standard).unwrap();
254            let y = fft.execute(&x).unwrap();
255            for (k, yk) in y.iter().enumerate() {
256                let direct: Complex<f64> = x.iter().enumerate().map(|(m, xm)| {
257                    let a = -2.0 * std::f64::consts::PI * ((k * m) % n) as f64 / n as f64;
258                    xm * Complex::new(a.cos(), a.sin())
259                }).sum();
260                assert!((yk - direct).norm() < 1e-12, "n = {n}, k = {k}");
261            }
262            let mut inverse = OptimizedSplitRadixFFT::new();
263            inverse.plan(n, FftScaleFactor::N, FftDirection::Inverse, FftOrdering::Standard).unwrap();
264            let back = inverse.execute(&y).unwrap();
265            assert!(back.iter().zip(&x).all(|(a, b)| (a - b).norm() < 1e-13), "n = {n}");
266        }
267    }
268}