Skip to main content

lib_jsl_ffts/
bluestein_fft.rs

1//! Bluestein's algorithm (the chirp-z transform) for FFTs of any length.
2//!
3//! The identity `jk = (j² + k² − (k − j)²)/2` turns the DFT into a convolution with the chirp
4//! `e^{iπ k²/n}`, which is computed with power-of-two FFTs of length at least `2n − 1`. The chirp
5//! angles are reduced exactly (`k² mod 2n` in integers) before taking cosines and sines, so the
6//! transform is accurate to rounding at every length.
7//!
8//! See the book entry [Bluestein's algorithm and the fractional Fourier transform](https://jwkunz.github.io/lib_jsl/book/fft/bluestein-fractional.html#bluesteins-algorithm).
9use num_complex::Complex;
10use lib_jsl_core::ErrorsJSL;
11
12use crate::{
13    best_fft::BestFft,
14    fft_engine_trait::{FftEngine1D, FftDirection, FftOrdering, FftScaleFactor},
15};
16
17#[derive(Debug)]
18pub struct BluesteinFft {
19    size: usize,
20    direction: FftDirection,
21    scale: FftScaleFactor,
22    ordering: FftOrdering,
23    conv_size: usize,
24    chirp: Vec<Complex<f64>>,
25    b_fft: Vec<Complex<f64>>,
26    fft_engine: BestFft,
27    ifft_engine: BestFft,
28    bit_reverse_map: Vec<usize>,
29}
30
31impl BluesteinFft {
32    pub fn new() -> Self {
33        Self {
34            size: 0,
35            direction: FftDirection::Forward,
36            scale: FftScaleFactor::None,
37            ordering: FftOrdering::Standard,
38            conv_size: 0,
39            chirp: Vec::new(),
40            b_fft: Vec::new(),
41            fft_engine: BestFft::new(),
42            ifft_engine: BestFft::new(),
43            bit_reverse_map: Vec::new(),
44        }
45    }
46}
47
48impl Default for BluesteinFft {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54#[inline]
55fn bit_reverse(mut n: usize, bits: usize) -> usize {
56    let mut reversed = 0usize;
57    for _ in 0..bits {
58        reversed = (reversed << 1) | (n & 1);
59        n >>= 1;
60    }
61    reversed
62}
63
64impl FftEngine1D for BluesteinFft {
65    // ANCHOR: bluestein
66    fn execute(&mut self, input: &[Complex<f64>]) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
67        if input.len() != self.size {
68            return Err(ErrorsJSL::InvalidInputRange(
69                "Input size must match the planned size",
70            ));
71        }
72        // Prepare the input sequence in the appropriate order based on the planned ordering
73        let x: Vec<Complex<f64>> = match self.ordering {
74            FftOrdering::Standard => input.to_vec(),
75            FftOrdering::BitReversed => {
76                if !self.size.is_power_of_two() {
77                    return Err(ErrorsJSL::InvalidInputRange(
78                        "BitReversed ordering requires a power-of-two transform size",
79                    ));
80                }
81                let mut natural = vec![Complex::new(0.0, 0.0); self.size];
82                for i in 0..self.size {
83                    natural[i] = input[self.bit_reverse_map[i]];
84                }
85                natural
86            }
87        };
88        // Step 1: Multiply input by chirp factors to prepare for convolution
89        let mut a = vec![Complex::new(0.0, 0.0); self.conv_size];
90        for n in 0..self.size {
91            a[n] = x[n] * self.chirp[n];
92        }
93        // Step 2: Perform convolution using FFTs - compute the FFT of a, multiply by precomputed FFT of b, and then compute the inverse FFT to get the convolution result  
94        let a_fft = self.fft_engine.execute(&a)?;
95        let mut prod = vec![Complex::new(0.0, 0.0); self.conv_size];
96        for i in 0..self.conv_size {
97            prod[i] = a_fft[i] * self.b_fft[i];
98        }
99        let conv = self.ifft_engine.execute(&prod)?;
100        // Step 3: Multiply the convolution result by the chirp factors to get the final FFT output 
101        let mut out = vec![Complex::new(0.0, 0.0); self.size];
102        for k in 0..self.size {
103            out[k] = conv[k] * self.chirp[k];
104        }
105        // Step 4: Apply scaling if necessary and return the result
106        Ok(match self.scale {
107            FftScaleFactor::None => out,
108            FftScaleFactor::SqrtN => out
109                .into_iter()
110                .map(|x| x / (self.size as f64).sqrt())
111                .collect(),
112            FftScaleFactor::N => out.into_iter().map(|x| x / self.size as f64).collect(),
113        })
114    }
115    // ANCHOR_END: bluestein
116
117    fn plan(
118        &mut self,
119        size: usize,
120        scale: FftScaleFactor,
121        direction: FftDirection,
122        ordering: FftOrdering,
123    ) -> Result<(), ErrorsJSL> {
124        if size == 0 {
125            return Err(ErrorsJSL::InvalidInputRange("Size must be greater than 0"));
126        }
127
128        self.size = size;
129        self.scale = scale;
130        self.direction = direction;
131        self.ordering = ordering;
132        if size.is_power_of_two() {
133            let bits = size.trailing_zeros() as usize;
134            self.bit_reverse_map = (0..size).map(|i| bit_reverse(i, bits)).collect();
135        } else {
136            self.bit_reverse_map.clear();
137        }
138        // The convolution size must be at least 2N-1 to avoid circular convolution issues, and we round up to the next power of two for efficient FFT computation  
139        self.conv_size = (2 * size - 1).next_power_of_two();
140
141        let sign = match direction {
142            FftDirection::Forward => -1.0_f64,
143            FftDirection::Inverse => 1.0_f64,
144        };
145        // The chirp exp(±iπ k²/n). Its angle is reduced exactly first: exp(iπ m/n) has period 2n in
146        // m, so k² is taken mod 2n in integers. (Forming π k²/n in floating point gave angles up to
147        // π n radians, and errors of 1e-11 at n = 1e5 and 3e-10 at n = 2^20.)
148        let chirp_angle = |k: usize| std::f64::consts::PI * ((k as u128 * k as u128) % (2 * size as u128)) as f64 / size as f64;
149        self.chirp = (0..size)
150            .map(|k| {
151                let theta = sign * chirp_angle(k);
152                Complex::new(theta.cos(), theta.sin())
153            })
154            .collect();
155        // Prepare the b sequence for convolution, which is the chirp sequence extended to the convolution size with appropriate symmetry  
156        let mut b = vec![Complex::new(0.0, 0.0); self.conv_size];
157        for n in 0..size {
158            let theta = -sign * chirp_angle(n);
159            let val = Complex::new(theta.cos(), theta.sin());
160            b[n] = val;
161            if n != 0 {
162                b[self.conv_size - n] = val;
163            }
164        }
165        // Plan the FFTs for the convolution step using the underlying FFT engines  
166        self.fft_engine.plan(
167            self.conv_size,
168            FftScaleFactor::None,
169            FftDirection::Forward,
170            FftOrdering::Standard,
171        )?;
172        // We only need to compute the FFT of b once since it doesn't depend on the input
173        self.ifft_engine.plan(
174            self.conv_size,
175            FftScaleFactor::N,
176            FftDirection::Inverse,
177            FftOrdering::Standard,
178        )?;
179        // Compute the FFT of b for the convolution step and store it for reuse during execution
180        self.b_fft = self.fft_engine.execute(&b)?;
181
182        Ok(())
183    }
184
185    fn get_size(&self) -> usize {
186        self.size
187    }
188
189    fn get_scale_factor(&self) -> FftScaleFactor {
190        self.scale
191    }
192
193    fn get_direction(&self) -> FftDirection {
194        self.direction
195    }
196
197    fn get_ordering(&self) -> FftOrdering {
198        self.ordering
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use std::time::Instant;
205
206    use super::*;
207    use crate::test_bench_data::{fft_gaussian_63_golden, fft_gaussian_63_input};
208
209    fn assert_complex_close(actual: Complex<f64>, expected: Complex<f64>, tol: f64) {
210        assert!(
211            (actual.re - expected.re).abs() < tol && (actual.im - expected.im).abs() < tol,
212            "actual={actual:?}, expected={expected:?}, tol={tol}"
213        );
214    }
215
216    #[test]
217    fn test_bluestein_fft_len_63_standard() {
218        let input = fft_gaussian_63_input();
219        let expected = fft_gaussian_63_golden();
220
221        let mut fft = BluesteinFft::new();
222        fft.plan(
223            input.len(),
224            FftScaleFactor::None,
225            FftDirection::Forward,
226            FftOrdering::Standard,
227        )
228        .unwrap();
229
230        let start = Instant::now();
231        let output = fft.execute(&input).unwrap();
232        dbg!("bluestein_fft::len63 standard execute elapsed", start.elapsed());
233
234        assert_eq!(output.len(), expected.len());
235        for (actual, expected) in output.iter().zip(expected.iter()) {
236            assert_complex_close(*actual, *expected, 1e-8);
237        }
238    }
239
240    #[test]
241    fn large_prime_lengths_keep_full_accuracy() {
242        // x_k = exp(2πi f k / n) transforms to n at bin f. The chirp angle π k²/n was once formed in
243        // floating point, which cost about five digits at n = 100 003.
244        let n = 100_003usize;
245        let f = 12_345usize;
246        let x: Vec<Complex<f64>> = (0..n)
247            .map(|k| {
248                let a = 2.0 * std::f64::consts::PI * ((f * k) % n) as f64 / n as f64;
249                Complex::new(a.cos(), a.sin())
250            })
251            .collect();
252        let mut fft = BluesteinFft::new();
253        fft.plan(n, FftScaleFactor::None, FftDirection::Forward, FftOrdering::Standard).unwrap();
254        let y = fft.execute(&x).unwrap();
255        let err = y.iter().enumerate().map(|(k, v)| (v - Complex::new(if k == f { n as f64 } else { 0.0 }, 0.0)).norm_sqr()).sum::<f64>().sqrt();
256        // ‖X‖ = n; the old chirp gave a relative error of 2.5e-11 here, the new one about 1e-15.
257        assert!(err / (n as f64) < 1e-14, "relative error {:e}", err / n as f64);
258    }
259}