Skip to main content

lib_jsl_ffts_reference/
simple_cooley_tukey.rs

1//! The textbook radix-2 decimation-in-time Cooley-Tukey FFT, for study.
2//!
3//! The input is permuted into bit-reversed order, then `log₂ n` stages of butterflies combine
4//! transforms of length `m/2` into transforms of length `m`, in place. As in many textbooks, the
5//! twiddle factors of each stage are generated by the recurrence `w ← w · W_m` rather than computed
6//! directly; each multiplication adds a rounding error, so the error grows like `n ε` instead of
7//! `ε log n` (about 1e-11 relative at n = 2²⁰, against 6e-16 for [`crate::optimized_radix2`], which
8//! precomputes exact twiddles). That is a lesson, not something to copy.
9//!
10//! See the book entry [The fast Fourier transform](https://jwkunz.github.io/lib_jsl/book/fft/fft.html#the-radix-2-cooley-tukey-algorithm).
11use num_complex::Complex;
12use lib_jsl_core::ErrorsJSL;
13
14use lib_jsl_ffts::fft_engine_trait::{FftEngine1D, FftDirection, FftOrdering, FftScaleFactor};
15 pub struct SimpleCooleyTukeyFFT {
16    size: usize,
17    direction: FftDirection,
18    scale: FftScaleFactor,
19    ordering: FftOrdering,
20}
21
22impl SimpleCooleyTukeyFFT {
23    pub fn new() -> Self {
24        SimpleCooleyTukeyFFT {
25            size: 0,
26            direction: FftDirection::Forward,
27            scale: FftScaleFactor::None,
28            ordering: FftOrdering::Standard,
29        }
30    }
31}
32
33impl Default for SimpleCooleyTukeyFFT {
34    fn default() -> Self {
35        Self::new()
36    }
37}
38
39fn bit_reverse(mut n: usize, bits: usize) -> usize {
40    let mut reversed = 0;
41    for _ in 0..bits {
42        reversed <<= 1;
43        reversed |= n & 1;
44        n >>= 1;
45    }
46    reversed
47}   
48
49impl FftEngine1D for SimpleCooleyTukeyFFT {
50    fn plan(&mut self, size: usize, scale: FftScaleFactor, direction: FftDirection, ordering: FftOrdering) -> Result<(), ErrorsJSL> {
51        if !size.is_power_of_two() {
52            return Err(ErrorsJSL::InvalidInputRange("Size must be a power of 2"));
53        }
54        self.size = size;
55        self.scale = scale;
56        self.direction = direction;
57        self.ordering = ordering;
58        Ok(())
59    }
60
61    
62    fn execute(&mut self, input: &[Complex<f64>]) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
63        if input.len() != self.size {
64            return Err(ErrorsJSL::InvalidInputRange("Input size must match the planned size"));
65        }
66        // Fast log2 calculation using trailing_zeros, since size is a power of 2
67        let log2n = self.size.trailing_zeros() as usize;
68
69        let mut buffer = input.to_vec();
70        if matches!(self.ordering, FftOrdering::Standard) {
71            // Do pre bit reversal permutation to compensate for in-place FFT
72            for i in 0..self.size {
73                let j = bit_reverse(i, log2n);
74                if i < j {
75                    buffer.swap(i, j);
76                }
77            }
78        }
79        // Do in place radix-2 Cooley-Tukey FFT with bit reversal
80        // ANCHOR: radix2_stages
81        for s in 1..=log2n {
82            // m = 2^s is the size of the sub-FFTs being combined
83            let m = 1 << s;
84            // Compute the twiddle factor W_m = exp(-2*pi*i/m) for forward FFT or exp(2*pi*i/m) for inverse FFT
85            let theta = match self.direction {
86                FftDirection::Forward => -2.0 * std::f64::consts::PI / m as f64,
87                FftDirection::Inverse => 2.0 * std::f64::consts::PI / m as f64,
88            };
89            let wm = Complex::new(theta.cos(), theta.sin());
90            // Combine sub-FFTs of size m/2 into sub-FFTs of size m
91            for k in (0..self.size).step_by(m) {
92                // w starts at 1 and is multiplied by W_m in each iteration to get the next twiddle factor
93                let mut w = Complex::new(1.0, 0.0);
94                // Perform the butterfly operations for the current stage
95                for j in 0..(m / 2) {
96                    // t = w * buffer[k + j + m/2] is the contribution from the second half of the sub-FFT
97                    // u = buffer[k + j] is the contribution from the first half of the sub-FFT before the butterfly operation  
98                    let t = w * buffer[k + j + m / 2];
99                    let u = buffer[k + j];
100                    // Update the buffer with the results of the butterfly operation    
101                    buffer[k + j] = u + t;
102                    buffer[k + j + m / 2] = u - t;
103                    // Update w to the next twiddle factor for the next iteration of the butterfly operation
104                    w *= wm;
105                }
106            }
107        }
108        // ANCHOR_END: radix2_stages
109        // Scale the output if necessary according to the planned scale factor
110        Ok(match self.scale {
111            FftScaleFactor::None => buffer,
112            FftScaleFactor::SqrtN => buffer.into_iter().map(|x| x / (self.size as f64).sqrt()).collect(),
113            FftScaleFactor::N => buffer.into_iter().map(|x| x / self.size as f64).collect(),
114        })
115    }
116
117    fn get_direction(&self) -> FftDirection {
118        self.direction
119    }
120
121    fn get_scale_factor(&self) -> FftScaleFactor {
122        self.scale
123    }
124
125    fn get_size(&self) -> usize {
126        self.size
127    }
128    fn get_ordering(&self) -> lib_jsl_ffts::fft_engine_trait::FftOrdering {
129        self.ordering
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use std::time::Instant;
136
137    use super::*;
138    use crate::test_bench_data::{fft_gaussian_32768_golden, fft_gaussian_32768_input};
139
140    fn assert_complex_close(actual: Complex<f64>, expected: Complex<f64>, tol: f64) {
141        assert!(
142            (actual.re - expected.re).abs() < tol && (actual.im - expected.im).abs() < tol,
143            "actual={actual:?}, expected={expected:?}, tol={tol}"
144        );
145    }
146
147    fn bit_reverse_index(mut n: usize, bits: usize) -> usize {
148        let mut reversed = 0;
149        for _ in 0..bits {
150            reversed <<= 1;
151            reversed |= n & 1;
152            n >>= 1;
153        }
154        reversed
155    }
156
157    #[test]
158    fn test_cooley_tukey_fft() {
159        let input = fft_gaussian_32768_input();
160        let mut fft = SimpleCooleyTukeyFFT::new();
161        fft.plan(input.len(), FftScaleFactor::None, FftDirection::Forward, FftOrdering::Standard).unwrap();
162
163        let start = Instant::now();
164        let output = fft.execute(input.as_slice()).unwrap();
165        let elapsed = start.elapsed();
166        dbg!("simple_cooley_tukey::standard execute elapsed", elapsed);
167
168        let expected = fft_gaussian_32768_golden();
169
170        assert_eq!(output.len(), expected.len());
171        for (actual, expected) in output.iter().zip(expected.iter()) {
172            assert_complex_close(*actual, *expected, 1e-9);
173        }
174    }
175
176    #[test]
177    fn test_cooley_tukey_fft_bit_reversed_ordering() {
178        let input = fft_gaussian_32768_input();
179
180        let bits = input.len().trailing_zeros() as usize;
181        let mut bit_reversed_input = vec![Complex::new(0.0, 0.0); input.len()];
182        for (i, value) in input.iter().enumerate() {
183            bit_reversed_input[bit_reverse_index(i, bits)] = *value;
184        }
185
186        let mut fft = SimpleCooleyTukeyFFT::new();
187        fft.plan(
188            bit_reversed_input.len(),
189            FftScaleFactor::None,
190            FftDirection::Forward,
191            FftOrdering::BitReversed,
192        )
193        .unwrap();
194
195        let start = Instant::now();
196        let output = fft.execute(bit_reversed_input.as_slice()).unwrap();
197        let elapsed = start.elapsed();
198        dbg!("simple_cooley_tukey::bit_reversed execute elapsed", elapsed);
199
200        let expected = fft_gaussian_32768_golden();
201
202        assert_eq!(output.len(), expected.len());
203        for (actual, expected) in output.iter().zip(expected.iter()) {
204            assert_complex_close(*actual, *expected, 1e-9);
205        }
206    }
207}