Skip to main content

lib_jsl_ffts/
fft.rs

1//! [`Fft`]: the default FFT engine. Plan it once, then call [`FftEngine1D::execute`] repeatedly.
2//!
3//! See the book entry [The fast Fourier transform](https://jwkunz.github.io/lib_jsl/book/fft/fft.html#the-production-engines).
4
5use crate::best_fft::BestFft;
6use crate::bluestein_fft::BluesteinFft;
7use crate::fft_engine_trait::{FftDirection, FftEngine1D, FftOrdering, FftScaleFactor};
8use lib_jsl_core::ErrorsJSL;
9use num_complex::Complex;
10
11#[derive(Debug)]
12enum Backend {
13    Unplanned,
14    PowerOfTwo(Box<BestFft>),
15    Arbitrary(Box<BluesteinFft>),
16}
17
18/// A one-dimensional complex FFT of any length that picks the best algorithm for the size:
19///
20/// - powers of two use [`BestFft`] (radix-4 passes, AVX2/FMA kernels where available, cache
21///   blocking), which is competitive with the fastest Rust FFT libraries;
22/// - every other length uses [`BluesteinFft`], which costs a few power-of-two FFTs of roughly twice
23///   the length but is still O(n log n).
24///
25/// ```
26/// use lib_jsl_ffts::{Fft, FftDirection, FftEngine1D, FftOrdering, FftScaleFactor};
27/// use num_complex::Complex;
28///
29/// let mut fft = Fft::new();
30/// fft.plan(6, FftScaleFactor::None, FftDirection::Forward, FftOrdering::Standard).unwrap();
31/// let spectrum = fft.execute(&[Complex::new(1.0, 0.0); 6]).unwrap();
32/// assert!((spectrum[0].re - 6.0).abs() < 1e-12); // a constant signal is all DC
33/// ```
34///
35/// `FftOrdering::BitReversed` input is only available for power-of-two sizes.
36#[derive(Debug)]
37pub struct Fft {
38    backend: Backend,
39    size: usize,
40    scale: FftScaleFactor,
41    direction: FftDirection,
42    ordering: FftOrdering,
43}
44
45impl Fft {
46    pub fn new() -> Self {
47        Fft {
48            backend: Backend::Unplanned,
49            size: 0,
50            scale: FftScaleFactor::None,
51            direction: FftDirection::Forward,
52            ordering: FftOrdering::Standard,
53        }
54    }
55
56    /// Creates and plans an engine in one step.
57    pub fn with_plan(size: usize, scale: FftScaleFactor, direction: FftDirection, ordering: FftOrdering) -> Result<Self, ErrorsJSL> {
58        let mut fft = Self::new();
59        fft.plan(size, scale, direction, ordering)?;
60        Ok(fft)
61    }
62}
63
64impl Default for Fft {
65    fn default() -> Self {
66        Self::new()
67    }
68}
69
70impl FftEngine1D for Fft {
71    fn execute(&mut self, input: &[Complex<f64>]) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
72        match &mut self.backend {
73            Backend::Unplanned => Err(ErrorsJSL::InvalidInputRange("FFT must be planned before it is executed")),
74            Backend::PowerOfTwo(engine) => engine.execute(input),
75            Backend::Arbitrary(engine) => engine.execute(input),
76        }
77    }
78
79    fn plan(&mut self, size: usize, scale: FftScaleFactor, direction: FftDirection, ordering: FftOrdering) -> Result<(), ErrorsJSL> {
80        if size == 0 {
81            return Err(ErrorsJSL::InvalidInputRange("Size must be greater than 0"));
82        }
83        let backend = if size.is_power_of_two() {
84            let mut engine = BestFft::new();
85            engine.plan(size, scale, direction, ordering)?;
86            Backend::PowerOfTwo(Box::new(engine))
87        } else {
88            if matches!(ordering, FftOrdering::BitReversed) {
89                return Err(ErrorsJSL::InvalidInputRange("BitReversed ordering requires a power-of-two transform size"));
90            }
91            let mut engine = BluesteinFft::new();
92            engine.plan(size, scale, direction, ordering)?;
93            Backend::Arbitrary(Box::new(engine))
94        };
95        // Commit only after the chosen engine planned successfully.
96        self.backend = backend;
97        (self.size, self.scale, self.direction, self.ordering) = (size, scale, direction, ordering);
98        Ok(())
99    }
100
101    fn get_size(&self) -> usize {
102        self.size
103    }
104    fn get_scale_factor(&self) -> FftScaleFactor {
105        self.scale
106    }
107    fn get_direction(&self) -> FftDirection {
108        self.direction
109    }
110    fn get_ordering(&self) -> FftOrdering {
111        self.ordering
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118    use std::f64::consts::PI;
119
120    fn naive(input: &[Complex<f64>], inverse: bool) -> Vec<Complex<f64>> {
121        let n = input.len();
122        let sign = if inverse { 1.0 } else { -1.0 };
123        (0..n)
124            .map(|k| input.iter().enumerate().map(|(j, &x)| x * Complex::from_polar(1.0, sign * 2.0 * PI * ((k * j) % n) as f64 / n as f64)).sum())
125            .collect()
126    }
127
128    fn signal(n: usize) -> Vec<Complex<f64>> {
129        (0..n).map(|i| Complex::new((i as f64 * 0.7).sin() + 0.1 * i as f64, (i as f64 * 1.3).cos())).collect()
130    }
131
132    #[test]
133    fn matches_the_dft_for_power_of_two_and_arbitrary_sizes() {
134        for n in [1usize, 2, 3, 4, 5, 6, 7, 8, 12, 16, 17, 31, 32, 63, 64, 100, 128, 255] {
135            for (direction, inverse) in [(FftDirection::Forward, false), (FftDirection::Inverse, true)] {
136                let x = signal(n);
137                let mut fft = Fft::with_plan(n, FftScaleFactor::None, direction, FftOrdering::Standard).unwrap();
138                let got = fft.execute(&x).unwrap();
139                let want = naive(&x, inverse);
140                let worst = got.iter().zip(&want).map(|(a, b)| (a - b).norm()).fold(0.0, f64::max);
141                assert!(worst < 1e-9 * n as f64, "n={n} inverse={inverse} worst={worst}");
142            }
143        }
144    }
145
146    #[test]
147    fn scaling_round_trip_and_replanning() {
148        let mut fwd = Fft::new();
149        let mut inv = Fft::new();
150        for n in [12usize, 64, 45, 1024] {
151            fwd.plan(n, FftScaleFactor::SqrtN, FftDirection::Forward, FftOrdering::Standard).unwrap();
152            inv.plan(n, FftScaleFactor::SqrtN, FftDirection::Inverse, FftOrdering::Standard).unwrap();
153            let x = signal(n);
154            let back = inv.execute(&fwd.execute(&x).unwrap()).unwrap();
155            assert!(x.iter().zip(&back).all(|(a, b)| (a - b).norm() < 1e-9), "n={n}");
156            assert_eq!(fwd.get_size(), n);
157        }
158    }
159
160    #[test]
161    fn errors_leave_the_previous_plan_intact() {
162        let mut fft = Fft::new();
163        assert!(fft.execute(&[Complex::new(1.0, 0.0)]).is_err());
164        fft.plan(8, FftScaleFactor::None, FftDirection::Forward, FftOrdering::Standard).unwrap();
165        assert!(fft.plan(0, FftScaleFactor::None, FftDirection::Forward, FftOrdering::Standard).is_err());
166        assert!(fft.plan(12, FftScaleFactor::None, FftDirection::Forward, FftOrdering::BitReversed).is_err());
167        assert_eq!(fft.get_size(), 8);
168        assert!(fft.execute(&signal(8)).is_ok());
169        assert!(fft.execute(&signal(9)).is_err());
170    }
171}