Skip to main content

lib_jsl_ffts/
best_fft.rs

1//! BestFft: the crate's high-performance FFT for power-of-two sizes.
2//!
3//! The transform is an iterative decimation-in-time Cooley-Tukey FFT on bit-reversed data, tuned in
4//! five ways compared with a textbook radix-2 loop:
5//!
6//! 1. **Radix-4 passes.** Pairs of radix-2 stages are fused into one radix-4 pass. Each pass reads and
7//!    writes the array once instead of twice, and needs three complex twiddle multiplications per
8//!    four outputs instead of four (the `±i` rotations inside a radix-4 butterfly are free). For an
9//!    odd `log2(n)` one radix-2 pass comes first.
10//! 2. **SIMD.** On x86-64 with AVX2 and FMA (detected at run time) the passes process two complex
11//!    values per 256-bit register, with complex multiplication done by `fmaddsub`. Other targets use
12//!    a portable scalar implementation of the same algorithm.
13//! 3. **Cache blocking.** Every stage whose butterflies span at most `BLOCK` points is run on one
14//!    `BLOCK`-point chunk at a time (all those stages for a chunk, then the next chunk), so the chunk
15//!    stays in L1/L2 cache. Only the few largest stages make full passes over a big array.
16//! 4. **Bandwidth-saving large passes.** Passes that sweep the whole array store only `W^j` and form
17//!    `W^2j` and `W^3j` in registers, cutting their twiddle traffic by a factor of three.
18//! 5. **Cache-friendly permutation, no extra copies.** The bit-reversal permutation is done in 16×16
19//!    tiles that use whole cache lines, writes straight into the output vector with any scaling
20//!    folded in, and the transform then runs in place in the output.
21//!
22//! Twiddle factors are computed once at planning time from exact angles (no recurrences), and laid
23//! out per pass in exactly the order the kernels read them.
24//!
25//! See the book entry [The fast Fourier transform](https://jwkunz.github.io/lib_jsl/book/fft/fft.html#the-production-engines).
26use num_complex::Complex;
27use lib_jsl_core::ErrorsJSL;
28
29use crate::fft_engine_trait::{FftEngine1D, FftDirection, FftOrdering, FftScaleFactor};
30
31/// Points per cache block (16 bytes each): 4096 points = 64 KiB, comfortably inside L2.
32const BLOCK: usize = 4096;
33
34/// Bit width of the tiles used for the bit-reversal permutation: 16 × 16 tiles whose rows are 16
35/// contiguous points (256 bytes, four cache lines).
36const TILE_BITS: usize = 4;
37
38/// Smallest `log2(size)` that uses the tiled permutation. Below it the whole array sits in L1
39/// cache, a plain gather is cheaper, and tiling only adds index arithmetic.
40const TILED_PERMUTATION_MIN_LOG2: usize = 12;
41
42/// One pass of the transform.
43#[derive(Clone, Copy, Debug)]
44enum Pass {
45    /// Radix-2 butterflies on adjacent pairs (no twiddles).
46    Radix2First,
47    /// Radix-4 butterflies on adjacent quadruples (no twiddles).
48    Radix4First,
49    /// Radix-4 butterflies combining four length-`l` sub-transforms; twiddles start at `offset`
50    /// (in complex values) in the twiddle table.
51    Radix4 { l: usize, offset: usize },
52    /// Like `Radix4`, but only `W^j` is stored (`l` values) and `W^2j`, `W^3j` are computed on the
53    /// fly. Used for the passes that sweep the whole array, where memory bandwidth, not arithmetic,
54    /// is the limit, so a third of the twiddle traffic is worth two extra multiplications.
55    Radix4Compact { l: usize, offset: usize },
56    /// The first two passes fused into one register-resident codelet: an 8-point (`l = 2`, after a
57    /// radix-2 first pass) or 16-point (`l = 4`, after a radix-4 first pass) transform of each
58    /// block, using the `Radix4 { l, offset }` twiddles.
59    Codelet { l: usize, offset: usize },
60}
61
62impl Pass {
63    /// Number of points each butterfly group spans.
64    fn span(&self) -> usize {
65        match *self {
66            Pass::Radix2First => 2,
67            Pass::Radix4First => 4,
68            Pass::Radix4 { l, .. } | Pass::Radix4Compact { l, .. } | Pass::Codelet { l, .. } => 4 * l,
69        }
70    }
71}
72
73#[derive(Debug)]
74pub struct BestFft {
75    size: usize,
76    direction: FftDirection,
77    scale: FftScaleFactor,
78    ordering: FftOrdering,
79    /// `bit_reverse_map[i]` is `i` with its `log2(size)` bits reversed (small sizes only).
80    bit_reverse_map: Vec<u32>,
81    /// Bit reversal of `TILE_BITS`-bit values, for the tiled permutation of large sizes.
82    rev_tile: Vec<u32>,
83    /// Bit reversal of the middle `log2(size) - 2·TILE_BITS` index bits; empty for small sizes.
84    rev_mid: Vec<u32>,
85    passes: Vec<Pass>,
86    /// For each radix-4 pass, for each pair of butterfly indices `(j, j + 1)`:
87    /// `[W^2j, W^2(j+1), W^j, W^(j+1), W^3j, W^3(j+1)]` with `W = exp(∓2πi / 4l)`.
88    twiddles: Vec<Complex<f64>>,
89    use_avx: bool,
90}
91
92impl BestFft {
93    pub fn new() -> Self {
94        Self {
95            size: 0,
96            direction: FftDirection::Forward,
97            scale: FftScaleFactor::None,
98            ordering: FftOrdering::Standard,
99            bit_reverse_map: Vec::new(),
100            rev_tile: Vec::new(),
101            rev_mid: Vec::new(),
102            passes: Vec::new(),
103            twiddles: Vec::new(),
104            use_avx: false,
105        }
106    }
107
108    fn inverse(&self) -> bool {
109        matches!(self.direction, FftDirection::Inverse)
110    }
111
112    /// Runs one pass over `data` (whose length is a multiple of the pass span).
113    fn run_pass(&self, data: &mut [Complex<f64>], pass: Pass) {
114        let inverse = self.inverse();
115        match pass {
116            Pass::Radix2First => radix2_first(data),
117            Pass::Radix4First => radix4_first(data, inverse),
118            Pass::Radix4 { l, offset } => {
119                let tw = &self.twiddles[offset..offset + 3 * l];
120                #[cfg(target_arch = "x86_64")]
121                if self.use_avx {
122                    // SAFETY: `use_avx` is only set when AVX2 and FMA were detected at run time; the
123                    // kernel reads and writes within `data` (length a multiple of 4l) and `tw`
124                    // (length 3l), as checked by the debug assertions inside.
125                    unsafe { avx::radix4_pass(data, tw, l, inverse) };
126                    return;
127                }
128                radix4_pass_scalar(data, tw, l, inverse);
129            }
130            Pass::Radix4Compact { l, offset } => {
131                let tw = &self.twiddles[offset..offset + l];
132                #[cfg(target_arch = "x86_64")]
133                if self.use_avx {
134                    // SAFETY: as above; `tw` has length l.
135                    unsafe { avx::radix4_pass_compact(data, tw, l, inverse) };
136                    return;
137                }
138                radix4_pass_compact_scalar(data, tw, l, inverse);
139            }
140            Pass::Codelet { l, offset } => {
141                let tw = &self.twiddles[offset..offset + 3 * l];
142                #[cfg(target_arch = "x86_64")]
143                if self.use_avx {
144                    let p = data.as_mut_ptr();
145                    // SAFETY: AVX2/FMA detected; the codelet reads each block fully before writing
146                    // it, so reading and writing the same buffer is fine.
147                    unsafe { avx::codelet(p, None, 1.0, p, data.len(), tw, l, inverse) };
148                    return;
149                }
150                if l == 2 { radix2_first(data) } else { radix4_first(data, inverse) }
151                radix4_pass_scalar(data, tw, l, inverse);
152            }
153        }
154    }
155
156    /// Bit-reverse permutes `input` into a new vector, multiplying by `s` on the way.
157    ///
158    /// For large sizes the index is split into high, middle and low `TILE_BITS`-bit fields; reversal
159    /// swaps (and reverses) the high and low fields and reverses the middle one. For each middle
160    /// value a 16 × 16 tile is copied whose source rows and destination rows are each 16 contiguous
161    /// points, so every cache line touched is fully used, unlike a plain gather whose reads land on
162    /// a different cache line every time.
163    fn permute(&self, input: &[Complex<f64>], s: f64) -> Vec<Complex<f64>> {
164        let n = self.size;
165        let mut out: Vec<Complex<f64>> = Vec::with_capacity(n);
166        let dst = out.as_mut_ptr();
167        if self.rev_mid.is_empty() {
168            for (i, &r) in self.bit_reverse_map.iter().enumerate() {
169                // SAFETY: i < n = capacity; r < n because it is a bit-reversed index.
170                unsafe { dst.add(i).write(*input.get_unchecked(r as usize) * s) };
171            }
172        } else {
173            let tile = 1usize << TILE_BITS;
174            let high_shift = n.trailing_zeros() as usize - TILE_BITS;
175            for (m, &rm) in self.rev_mid.iter().enumerate() {
176                let (src_mid, dst_mid) = ((rm as usize) << TILE_BITS, m << TILE_BITS);
177                for a in 0..tile {
178                    let dst_row = (a << high_shift) + dst_mid;
179                    let src_col = src_mid + self.rev_tile[a] as usize;
180                    for (b, &rb) in self.rev_tile.iter().enumerate() {
181                        let src = ((rb as usize) << high_shift) + src_col;
182                        // SAFETY: (a, m, b) ranges over every index once, and both the destination
183                        // and its bit-reversed source are below n.
184                        unsafe { dst.add(dst_row + b).write(*input.get_unchecked(src) * s) };
185                    }
186                }
187            }
188        }
189        // SAFETY: every one of the n slots was written above (the mapping is a bijection).
190        unsafe { out.set_len(n) };
191        out
192    }
193
194    /// Runs the first (twiddle-free) pass while reading the input, so no separate permutation or
195    /// copy pass is needed: element `i` of the first pass's input is `input[map[i]] · s` (or
196    /// `input[i] · s` without a map). Returns the vector after the first pass.
197    fn fused_first_pass(&self, input: &[Complex<f64>], map: Option<&[u32]>, s: f64) -> Vec<Complex<f64>> {
198        let n = self.size;
199        let mut out: Vec<Complex<f64>> = Vec::with_capacity(n);
200        let dst = out.as_mut_ptr();
201        let inverse = self.inverse();
202        // SAFETY (all branches): every index 0..n of `dst` is written exactly once, and every source
203        // index is below n (`map` is a permutation of 0..n).
204        match self.passes.first() {
205            None => {
206                for (i, &v) in input.iter().enumerate() {
207                    unsafe { dst.add(i).write(v * s) };
208                }
209            }
210            #[cfg(target_arch = "x86_64")]
211            Some(&Pass::Codelet { l, offset }) if self.use_avx => unsafe {
212                avx::codelet(input.as_ptr(), map, s, dst, n, &self.twiddles[offset..offset + 3 * l], l, inverse)
213            },
214            #[cfg(target_arch = "x86_64")]
215            Some(Pass::Radix2First) if self.use_avx && n >= 4 => unsafe { avx::first_radix2(input, map, s, dst, n) },
216            #[cfg(target_arch = "x86_64")]
217            Some(Pass::Radix4First) if self.use_avx => unsafe { avx::first_radix4(input, map, s, dst, n, inverse) },
218            Some(&first) => {
219                let get = |i: usize| input[map.map_or(i, |m| m[i] as usize)] * s;
220                match first {
221                    Pass::Radix2First | Pass::Codelet { l: 2, .. } => {
222                        for q in 0..n / 2 {
223                            let (a, b) = (get(2 * q), get(2 * q + 1));
224                            unsafe {
225                                dst.add(2 * q).write(a + b);
226                                dst.add(2 * q + 1).write(a - b);
227                            }
228                        }
229                    }
230                    _ => {
231                        for q in 0..n / 4 {
232                            let (a, b, c, d) = (get(4 * q), get(4 * q + 1), get(4 * q + 2), get(4 * q + 3));
233                            let (t0, t1, t2, t3) = (a + b, a - b, c + d, rotate(c - d, inverse));
234                            unsafe {
235                                dst.add(4 * q).write(t0 + t2);
236                                dst.add(4 * q + 1).write(t1 + t3);
237                                dst.add(4 * q + 2).write(t0 - t2);
238                                dst.add(4 * q + 3).write(t1 - t3);
239                            }
240                        }
241                    }
242                }
243            }
244        }
245        unsafe { out.set_len(n) };
246        // Without SIMD a codelet is the radix-2/radix-4 first pass above plus its second pass.
247        if let Some(&Pass::Codelet { l, offset }) = self.passes.first()
248            && !self.use_avx
249        {
250            radix4_pass_scalar(&mut out, &self.twiddles[offset..offset + 3 * l], l, inverse);
251        }
252        out
253    }
254}
255
256impl Default for BestFft {
257    fn default() -> Self {
258        Self::new()
259    }
260}
261
262#[inline]
263fn bit_reverse(mut n: usize, bits: usize) -> usize {
264    let mut reversed = 0usize;
265    for _ in 0..bits {
266        reversed = (reversed << 1) | (n & 1);
267        n >>= 1;
268    }
269    reversed
270}
271
272/// Multiplies by `-i` (forward transform) or `+i` (inverse transform).
273#[inline(always)]
274fn rotate(v: Complex<f64>, inverse: bool) -> Complex<f64> {
275    if inverse { Complex::new(-v.im, v.re) } else { Complex::new(v.im, -v.re) }
276}
277
278/// First pass for odd `log2(n)`: length-2 DFTs of adjacent pairs.
279fn radix2_first(data: &mut [Complex<f64>]) {
280    let (pairs, _) = data.as_chunks_mut::<2>();
281    for pair in pairs {
282        let (a, b) = (pair[0], pair[1]);
283        pair[0] = a + b;
284        pair[1] = a - b;
285    }
286}
287
288/// First pass for even `log2(n)`: length-4 DFTs of adjacent quadruples (memory order A, B, C, D
289/// holds the sub-transforms of the inputs congruent to 0, 2, 1, 3 mod 4).
290fn radix4_first(data: &mut [Complex<f64>], inverse: bool) {
291    let (quads, _) = data.as_chunks_mut::<4>();
292    for q in quads {
293        let (a, b, c, d) = (q[0], q[1], q[2], q[3]);
294        let (t0, t1, t2, t3) = (a + b, a - b, c + d, rotate(c - d, inverse));
295        q[0] = t0 + t2;
296        q[1] = t1 + t3;
297        q[2] = t0 - t2;
298        q[3] = t1 - t3;
299    }
300}
301
302// ANCHOR: radix4_pass
303/// A radix-4 pass combining four length-`l` sub-transforms in every block of `4l` points.
304///
305/// With `W = exp(∓2πi / 4l)` and the block's four quarters `A, B, C, D` (sub-transforms of the
306/// inputs congruent to 0, 2, 1, 3 modulo 4), output `j + q·l` for `q = 0..3` is
307/// `A + W^2j B ± …` arranged as two radix-2 layers with a free `±i` rotation.
308fn radix4_pass_scalar(data: &mut [Complex<f64>], tw: &[Complex<f64>], l: usize, inverse: bool) {
309    for block in data.chunks_exact_mut(4 * l) {
310        let (ab, cd) = block.split_at_mut(2 * l);
311        let (qa, qb) = ab.split_at_mut(l);
312        let (qc, qd) = cd.split_at_mut(l);
313        for j in 0..l {
314            // Twiddles are stored per pair of j values: [w2_j, w2_j+1, w1_j, w1_j+1, w3_j, w3_j+1].
315            let base = 6 * (j / 2) + (j % 2);
316            let (w2, w1, w3) = (tw[base], tw[base + 2], tw[base + 4]);
317            let a = qa[j];
318            let tb = qb[j] * w2;
319            let tc = qc[j] * w1;
320            let td = qd[j] * w3;
321            let (t0, t1, t2, t3) = (a + tb, a - tb, tc + td, rotate(tc - td, inverse));
322            qa[j] = t0 + t2;
323            qb[j] = t1 + t3;
324            qc[j] = t0 - t2;
325            qd[j] = t1 - t3;
326        }
327    }
328}
329// ANCHOR_END: radix4_pass
330
331/// `radix4_pass_scalar` with only `W^j` stored; `W^2j` and `W^3j` are computed on the fly.
332fn radix4_pass_compact_scalar(data: &mut [Complex<f64>], tw: &[Complex<f64>], l: usize, inverse: bool) {
333    for block in data.chunks_exact_mut(4 * l) {
334        let (ab, cd) = block.split_at_mut(2 * l);
335        let (qa, qb) = ab.split_at_mut(l);
336        let (qc, qd) = cd.split_at_mut(l);
337        for j in 0..l {
338            let w1 = tw[j];
339            let w2 = w1 * w1;
340            let w3 = w2 * w1;
341            let a = qa[j];
342            let tb = qb[j] * w2;
343            let tc = qc[j] * w1;
344            let td = qd[j] * w3;
345            let (t0, t1, t2, t3) = (a + tb, a - tb, tc + td, rotate(tc - td, inverse));
346            qa[j] = t0 + t2;
347            qb[j] = t1 + t3;
348            qc[j] = t0 - t2;
349            qd[j] = t1 - t3;
350        }
351    }
352}
353
354#[cfg(target_arch = "x86_64")]
355mod avx {
356    use num_complex::Complex;
357    use std::arch::x86_64::*;
358
359    /// Complex product of two pairs of complex values with FMA.
360    #[inline(always)]
361    unsafe fn cmul(v: __m256d, w: __m256d) -> __m256d {
362        // SAFETY: only called from AVX2/FMA-enabled functions, into which it is inlined.
363        unsafe {
364            let wr = _mm256_movedup_pd(w); // (wr, wr) for each complex
365            let wi = _mm256_permute_pd(w, 0b1111); // (wi, wi)
366            let vs = _mm256_permute_pd(v, 0b0101); // (vi, vr)
367            // even lanes: vr wr - vi wi ; odd lanes: vi wr + vr wi
368            _mm256_fmaddsub_pd(v, wr, _mm256_mul_pd(vs, wi))
369        }
370    }
371
372    /// AVX2/FMA version of `radix4_pass_scalar`, two butterflies (j, j + 1) per iteration.
373    ///
374    /// # Safety
375    /// The CPU must support AVX2 and FMA; `data.len()` must be a multiple of `4l`, `l` must be
376    /// even, and `tw.len()` must be at least `3l`.
377    #[target_feature(enable = "avx2,fma")]
378    pub(super) unsafe fn radix4_pass(data: &mut [Complex<f64>], tw: &[Complex<f64>], l: usize, inverse: bool) {
379        debug_assert!(l.is_multiple_of(2) && data.len().is_multiple_of(4 * l) && tw.len() >= 3 * l);
380        // Multiplying (x, y) by -i gives (y, -x): swap, then negate the odd lanes. By +i: (-y, x).
381        let sign = if inverse { _mm256_set_pd(0.0, -0.0, 0.0, -0.0) } else { _mm256_set_pd(-0.0, 0.0, -0.0, 0.0) };
382        let n = data.len();
383        let base = data.as_mut_ptr() as *mut f64;
384        let twp = tw.as_ptr() as *const f64;
385        let quarter = 2 * l; // f64 offset between quarters
386        let mut k = 0usize;
387        unsafe {
388            while k < n {
389                let pa = base.add(2 * k);
390                let (pb, pc, pd) = (pa.add(quarter), pa.add(2 * quarter), pa.add(3 * quarter));
391                let mut j = 0usize;
392                let mut t = twp;
393                while j < l {
394                    let o = 2 * j;
395                    let a = _mm256_loadu_pd(pa.add(o));
396                    let b = _mm256_loadu_pd(pb.add(o));
397                    let c = _mm256_loadu_pd(pc.add(o));
398                    let d = _mm256_loadu_pd(pd.add(o));
399                    let w2 = _mm256_loadu_pd(t);
400                    let w1 = _mm256_loadu_pd(t.add(4));
401                    let w3 = _mm256_loadu_pd(t.add(8));
402                    let tb = cmul(b, w2);
403                    let tc = cmul(c, w1);
404                    let td = cmul(d, w3);
405                    let t0 = _mm256_add_pd(a, tb);
406                    let t1 = _mm256_sub_pd(a, tb);
407                    let t2 = _mm256_add_pd(tc, td);
408                    let t3 = _mm256_xor_pd(_mm256_permute_pd(_mm256_sub_pd(tc, td), 0b0101), sign);
409                    _mm256_storeu_pd(pa.add(o), _mm256_add_pd(t0, t2));
410                    _mm256_storeu_pd(pb.add(o), _mm256_add_pd(t1, t3));
411                    _mm256_storeu_pd(pc.add(o), _mm256_sub_pd(t0, t2));
412                    _mm256_storeu_pd(pd.add(o), _mm256_sub_pd(t1, t3));
413                    t = t.add(12);
414                    j += 2;
415                }
416                k += 4 * l;
417            }
418        }
419    }
420
421    /// `radix4_pass` with only `W^j` stored (`tw.len() >= l`); `W^2j = (W^j)²` and
422    /// `W^3j = W^j · W^2j` are formed in registers.
423    ///
424    /// # Safety
425    /// As for `radix4_pass`, with `tw.len() >= l`.
426    #[target_feature(enable = "avx2,fma")]
427    pub(super) unsafe fn radix4_pass_compact(data: &mut [Complex<f64>], tw: &[Complex<f64>], l: usize, inverse: bool) {
428        debug_assert!(l.is_multiple_of(2) && data.len().is_multiple_of(4 * l) && tw.len() >= l);
429        let sign = if inverse { _mm256_set_pd(0.0, -0.0, 0.0, -0.0) } else { _mm256_set_pd(-0.0, 0.0, -0.0, 0.0) };
430        let n = data.len();
431        let base = data.as_mut_ptr() as *mut f64;
432        let twp = tw.as_ptr() as *const f64;
433        let quarter = 2 * l;
434        let mut k = 0usize;
435        unsafe {
436            while k < n {
437                let pa = base.add(2 * k);
438                let (pb, pc, pd) = (pa.add(quarter), pa.add(2 * quarter), pa.add(3 * quarter));
439                let mut j = 0usize;
440                while j < l {
441                    let o = 2 * j;
442                    let w1 = _mm256_loadu_pd(twp.add(o));
443                    let w2 = cmul(w1, w1);
444                    let w3 = cmul(w2, w1);
445                    let a = _mm256_loadu_pd(pa.add(o));
446                    let tb = cmul(_mm256_loadu_pd(pb.add(o)), w2);
447                    let tc = cmul(_mm256_loadu_pd(pc.add(o)), w1);
448                    let td = cmul(_mm256_loadu_pd(pd.add(o)), w3);
449                    let t0 = _mm256_add_pd(a, tb);
450                    let t1 = _mm256_sub_pd(a, tb);
451                    let t2 = _mm256_add_pd(tc, td);
452                    let t3 = _mm256_xor_pd(_mm256_permute_pd(_mm256_sub_pd(tc, td), 0b0101), sign);
453                    _mm256_storeu_pd(pa.add(o), _mm256_add_pd(t0, t2));
454                    _mm256_storeu_pd(pb.add(o), _mm256_add_pd(t1, t3));
455                    _mm256_storeu_pd(pc.add(o), _mm256_sub_pd(t0, t2));
456                    _mm256_storeu_pd(pd.add(o), _mm256_sub_pd(t1, t3));
457                    j += 2;
458                }
459                k += 4 * l;
460            }
461        }
462    }
463
464    /// Loads source element `i` (through `map`, if any) as a 128-bit vector.
465    #[inline(always)]
466    unsafe fn load(input: &[Complex<f64>], map: Option<&[u32]>, i: usize) -> __m128d {
467        // SAFETY: callers pass i < n and map (if any) holds indices below n = input.len().
468        unsafe {
469            let j = match map {
470                Some(m) => *m.get_unchecked(i) as usize,
471                None => i,
472            };
473            _mm_loadu_pd(input.as_ptr().add(j) as *const f64)
474        }
475    }
476
477    /// Loads source element `i` (through `map`, if any) from a raw pointer as a 128-bit vector.
478    #[inline(always)]
479    unsafe fn load_ptr(src: *const Complex<f64>, map: Option<&[u32]>, i: usize) -> __m128d {
480        // SAFETY: callers pass i < n, map entries below n, and `src` valid for n reads.
481        unsafe {
482            let j = match map {
483                Some(m) => *m.get_unchecked(i) as usize,
484                None => i,
485            };
486            _mm_loadu_pd(src.add(j) as *const f64)
487        }
488    }
489
490    /// One radix-4 butterfly on two lanes: inputs `a, b, c, d` (quarters), twiddles for b, c, d.
491    #[inline(always)]
492    unsafe fn butterfly4([a, b, c, d]: [__m256d; 4], [w2, w1, w3]: [__m256d; 3], sign: __m256d) -> [__m256d; 4] {
493        // SAFETY: only inlined into AVX2/FMA functions.
494        unsafe {
495            let (tb, tc, td) = (cmul(b, w2), cmul(c, w1), cmul(d, w3));
496            let (t0, t1, t2) = (_mm256_add_pd(a, tb), _mm256_sub_pd(a, tb), _mm256_add_pd(tc, td));
497            let t3 = _mm256_xor_pd(_mm256_permute_pd(_mm256_sub_pd(tc, td), 0b0101), sign);
498            [_mm256_add_pd(t0, t2), _mm256_add_pd(t1, t3), _mm256_sub_pd(t0, t2), _mm256_sub_pd(t1, t3)]
499        }
500    }
501
502    /// Register-resident codelet for the first two passes: for every block of `4l` points
503    /// (`l = 2`: 8 points, `l = 4`: 16 points) it reads the block's inputs (element `i` is
504    /// `src[map[i]] · s`, or `src[i] · s` without a map), applies the radix-2 (`l = 2`) or
505    /// radix-4 (`l = 4`) first layer and the radix-4 second layer in registers, and stores the
506    /// block once. `tw` is the second layer's twiddle table (`3l` values).
507    ///
508    /// # Safety
509    /// AVX2/FMA required; `n` a multiple of `4l`; `src` and `dst` valid for `n` elements (they may
510    /// be the same buffer: each block is read completely before it is written); `map` (if any) a
511    /// permutation of `0..n`.
512    #[target_feature(enable = "avx2,fma")]
513    #[allow(clippy::too_many_arguments)]
514    pub(super) unsafe fn codelet(src: *const Complex<f64>, map: Option<&[u32]>, s: f64, dst: *mut Complex<f64>, n: usize, tw: &[Complex<f64>], l: usize, inverse: bool) {
515        debug_assert!((l == 2 || l == 4) && n.is_multiple_of(4 * l) && tw.len() >= 3 * l);
516        unsafe {
517            let sv = _mm256_set1_pd(s);
518            let sign = if inverse { _mm256_set_pd(0.0, -0.0, 0.0, -0.0) } else { _mm256_set_pd(-0.0, 0.0, -0.0, 0.0) };
519            let t = tw.as_ptr() as *const f64;
520            let out = dst as *mut f64;
521            // Builds the two-lane vector (element p, element q) of the block starting at `base`.
522            let pair = |base: usize, p: usize, q: usize| _mm256_mul_pd(_mm256_set_m128d(load_ptr(src, map, base + q), load_ptr(src, map, base + p)), sv);
523            if l == 2 {
524                let (w2, w1, w3) = (_mm256_loadu_pd(t), _mm256_loadu_pd(t.add(4)), _mm256_loadu_pd(t.add(8)));
525                for base in (0..n).step_by(8) {
526                    // First layer: radix-2 on pairs (0,1), (2,3), (4,5), (6,7), two pairs per vector.
527                    let (x, y) = (pair(base, 0, 2), pair(base, 1, 3));
528                    let (s01, d01) = (_mm256_add_pd(x, y), _mm256_sub_pd(x, y));
529                    let (x2, y2) = (pair(base, 4, 6), pair(base, 5, 7));
530                    let (s23, d23) = (_mm256_add_pd(x2, y2), _mm256_sub_pd(x2, y2));
531                    // Regroup into quarters: A = outputs of pair 0, B = pair 1, C = pair 2, D = pair 3.
532                    let a = _mm256_permute2f128_pd(s01, d01, 0x20);
533                    let b = _mm256_permute2f128_pd(s01, d01, 0x31);
534                    let c = _mm256_permute2f128_pd(s23, d23, 0x20);
535                    let d = _mm256_permute2f128_pd(s23, d23, 0x31);
536                    let r = butterfly4([a, b, c, d], [w2, w1, w3], sign);
537                    let o = out.add(2 * base);
538                    _mm256_storeu_pd(o, r[0]);
539                    _mm256_storeu_pd(o.add(4), r[1]);
540                    _mm256_storeu_pd(o.add(8), r[2]);
541                    _mm256_storeu_pd(o.add(12), r[3]);
542                }
543            } else {
544                let w = [_mm256_loadu_pd(t), _mm256_loadu_pd(t.add(4)), _mm256_loadu_pd(t.add(8)), _mm256_loadu_pd(t.add(12)), _mm256_loadu_pd(t.add(16)), _mm256_loadu_pd(t.add(20))];
545                for base in (0..n).step_by(16) {
546                    // First layer: radix-4 on quads 0..3, quads (0, 1) and (2, 3) side by side.
547                    let q01 = butterfly4_plain(pair(base, 0, 4), pair(base, 1, 5), pair(base, 2, 6), pair(base, 3, 7), sign);
548                    let q23 = butterfly4_plain(pair(base, 8, 12), pair(base, 9, 13), pair(base, 10, 14), pair(base, 11, 15), sign);
549                    // Second layer for outputs j = 0, 1 and j = 2, 3 of each quad.
550                    for (half, (x0, x1), (y0, y1)) in [(0usize, (q01[0], q01[1]), (q23[0], q23[1])), (1, (q01[2], q01[3]), (q23[2], q23[3]))] {
551                        let a = _mm256_permute2f128_pd(x0, x1, 0x20);
552                        let b = _mm256_permute2f128_pd(x0, x1, 0x31);
553                        let c = _mm256_permute2f128_pd(y0, y1, 0x20);
554                        let d = _mm256_permute2f128_pd(y0, y1, 0x31);
555                        let r = butterfly4([a, b, c, d], [w[3 * half], w[3 * half + 1], w[3 * half + 2]], sign);
556                        let o = out.add(2 * (base + 2 * half));
557                        _mm256_storeu_pd(o, r[0]);
558                        _mm256_storeu_pd(o.add(8), r[1]);
559                        _mm256_storeu_pd(o.add(16), r[2]);
560                        _mm256_storeu_pd(o.add(24), r[3]);
561                    }
562                }
563            }
564        }
565    }
566
567    /// A radix-4 butterfly with unit twiddles.
568    #[inline(always)]
569    unsafe fn butterfly4_plain(a: __m256d, b: __m256d, c: __m256d, d: __m256d, sign: __m256d) -> [__m256d; 4] {
570        // SAFETY: only inlined into AVX2/FMA functions.
571        unsafe {
572            let (t0, t1, t2) = (_mm256_add_pd(a, b), _mm256_sub_pd(a, b), _mm256_add_pd(c, d));
573            let t3 = _mm256_xor_pd(_mm256_permute_pd(_mm256_sub_pd(c, d), 0b0101), sign);
574            [_mm256_add_pd(t0, t2), _mm256_add_pd(t1, t3), _mm256_sub_pd(t0, t2), _mm256_sub_pd(t1, t3)]
575        }
576    }
577
578    /// Fused permutation + radix-2 first pass, two butterflies per iteration.
579    ///
580    /// # Safety
581    /// AVX2/FMA required; `n` a multiple of 4, `input.len() == n`, `map` (if any) a permutation of
582    /// `0..n`, and `dst` valid for `n` writes.
583    #[target_feature(enable = "avx2,fma")]
584    pub(super) unsafe fn first_radix2(input: &[Complex<f64>], map: Option<&[u32]>, s: f64, dst: *mut Complex<f64>, n: usize) {
585        unsafe {
586            let sv = _mm256_set1_pd(s);
587            let out = dst as *mut f64;
588            for q in 0..n / 4 {
589                let i = 4 * q;
590                // x = (e0, e2), y = (e1, e3): the two butterflies side by side.
591                let x = _mm256_mul_pd(_mm256_set_m128d(load(input, map, i + 2), load(input, map, i)), sv);
592                let y = _mm256_mul_pd(_mm256_set_m128d(load(input, map, i + 3), load(input, map, i + 1)), sv);
593                let (sum, diff) = (_mm256_add_pd(x, y), _mm256_sub_pd(x, y));
594                _mm256_storeu_pd(out.add(2 * i), _mm256_permute2f128_pd(sum, diff, 0x20));
595                _mm256_storeu_pd(out.add(2 * i + 4), _mm256_permute2f128_pd(sum, diff, 0x31));
596            }
597        }
598    }
599
600    /// Fused permutation + radix-4 first pass, one length-4 DFT per iteration.
601    ///
602    /// # Safety
603    /// As for `first_radix2`.
604    #[target_feature(enable = "avx2,fma")]
605    pub(super) unsafe fn first_radix4(input: &[Complex<f64>], map: Option<&[u32]>, s: f64, dst: *mut Complex<f64>, n: usize, inverse: bool) {
606        unsafe {
607            let sv = _mm256_set1_pd(s);
608            // Rotate only the upper complex by -i (forward) or +i (inverse), after a swap.
609            let sign = if inverse { _mm256_set_pd(0.0, -0.0, 0.0, 0.0) } else { _mm256_set_pd(-0.0, 0.0, 0.0, 0.0) };
610            let out = dst as *mut f64;
611            for q in 0..n / 4 {
612                let i = 4 * q;
613                let x = _mm256_mul_pd(_mm256_set_m128d(load(input, map, i + 2), load(input, map, i)), sv); // (a, c)
614                let y = _mm256_mul_pd(_mm256_set_m128d(load(input, map, i + 3), load(input, map, i + 1)), sv); // (b, d)
615                let sum = _mm256_add_pd(x, y); // (t0, t2)
616                let diff = _mm256_sub_pd(x, y); // (t1, c - d)
617                let rotated = _mm256_xor_pd(_mm256_permute_pd(diff, 0b0101), sign);
618                let qv = _mm256_blend_pd(diff, rotated, 0b1100); // (t1, t3)
619                let u = _mm256_permute2f128_pd(sum, qv, 0x20); // (t0, t1)
620                let w = _mm256_permute2f128_pd(sum, qv, 0x31); // (t2, t3)
621                _mm256_storeu_pd(out.add(2 * i), _mm256_add_pd(u, w));
622                _mm256_storeu_pd(out.add(2 * i + 4), _mm256_sub_pd(u, w));
623            }
624        }
625    }
626}
627
628impl FftEngine1D for BestFft {
629    fn execute(&mut self, input: &[Complex<f64>]) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
630        if input.len() != self.size {
631            return Err(ErrorsJSL::InvalidInputRange(
632                "Input size must match the planned size",
633            ));
634        }
635        let n = self.size;
636        let s = match self.scale {
637            FftScaleFactor::None => 1.0,
638            FftScaleFactor::SqrtN => 1.0 / (n as f64).sqrt(),
639            FftScaleFactor::N => 1.0 / n as f64,
640        };
641
642        // Large standard-order transforms permute in cache-friendly tiles first; otherwise the first
643        // pass reads the input directly (through the bit-reversal map when needed).
644        let (mut out, passes) = match self.ordering {
645            FftOrdering::Standard if !self.rev_mid.is_empty() => (self.permute(input, s), &self.passes[..]),
646            FftOrdering::Standard => (self.fused_first_pass(input, Some(&self.bit_reverse_map), s), self.passes.get(1..).unwrap_or(&[])),
647            FftOrdering::BitReversed => (self.fused_first_pass(input, None, s), self.passes.get(1..).unwrap_or(&[])),
648        };
649
650        // Cache-blocked stages first, then the stages that span more than one block.
651        let block = BLOCK.min(n);
652        let split = passes.iter().position(|p| p.span() > block).unwrap_or(passes.len());
653        if split > 0 {
654            for chunk in out.chunks_exact_mut(block) {
655                for &pass in &passes[..split] {
656                    self.run_pass(chunk, pass);
657                }
658            }
659        }
660        for &pass in &passes[split..] {
661            self.run_pass(&mut out, pass);
662        }
663        Ok(out)
664    }
665
666    fn plan(
667        &mut self,
668        size: usize,
669        scale: FftScaleFactor,
670        direction: FftDirection,
671        ordering: FftOrdering,
672    ) -> Result<(), ErrorsJSL> {
673        if !size.is_power_of_two() {
674            return Err(ErrorsJSL::InvalidInputRange("Size must be a power of 2"));
675        }
676        if size > u32::MAX as usize {
677            return Err(ErrorsJSL::InvalidInputRange("Size must fit in 32 bits"));
678        }
679
680        self.size = size;
681        self.scale = scale;
682        self.direction = direction;
683        self.ordering = ordering;
684
685        let log2n = size.trailing_zeros() as usize;
686        if log2n >= TILED_PERMUTATION_MIN_LOG2.max(2 * TILE_BITS) {
687            self.bit_reverse_map = Vec::new();
688            self.rev_tile = (0..1usize << TILE_BITS).map(|i| bit_reverse(i, TILE_BITS) as u32).collect();
689            let mid_bits = log2n - 2 * TILE_BITS;
690            self.rev_mid = (0..1usize << mid_bits).map(|i| bit_reverse(i, mid_bits) as u32).collect();
691        } else {
692            self.bit_reverse_map = (0..size).map(|i| bit_reverse(i, log2n) as u32).collect();
693            self.rev_tile = Vec::new();
694            self.rev_mid = Vec::new();
695        }
696
697        let sign = match direction {
698            FftDirection::Forward => -1.0_f64,
699            FftDirection::Inverse => 1.0_f64,
700        };
701        self.passes.clear();
702        self.twiddles.clear();
703        // Sub-transform length after the first pass.
704        let mut l = match log2n {
705            0 => return Ok(()),
706            _ if log2n % 2 == 1 => {
707                self.passes.push(Pass::Radix2First);
708                2
709            }
710            _ => {
711                self.passes.push(Pass::Radix4First);
712                4
713            }
714        };
715        let block = BLOCK.min(size);
716        while l < size {
717            let offset = self.twiddles.len();
718            let w = |e: usize| {
719                let theta = sign * 2.0 * std::f64::consts::PI * e as f64 / (4 * l) as f64;
720                Complex::new(theta.cos(), theta.sin())
721            };
722            if 4 * l > block {
723                // A full-array pass: store W^j only.
724                self.twiddles.extend((0..l).map(w));
725                self.passes.push(Pass::Radix4Compact { l, offset });
726            } else {
727                for j in (0..l).step_by(2) {
728                    self.twiddles.extend_from_slice(&[w(2 * j), w(2 * (j + 1)), w(j), w(j + 1), w(3 * j), w(3 * (j + 1))]);
729                }
730                self.passes.push(Pass::Radix4 { l, offset });
731            }
732            l *= 4;
733        }
734
735        // Fuse the twiddle-free first pass and the next radix-4 pass into a codelet.
736        if let [Pass::Radix2First | Pass::Radix4First, Pass::Radix4 { l, offset }, ..] = self.passes[..]
737            && (l == 2 || l == 4)
738        {
739            self.passes.splice(0..2, [Pass::Codelet { l, offset }]);
740        }
741
742        #[cfg(target_arch = "x86_64")]
743        {
744            self.use_avx = std::arch::is_x86_feature_detected!("avx2") && std::arch::is_x86_feature_detected!("fma");
745        }
746        Ok(())
747    }
748
749    fn get_size(&self) -> usize {
750        self.size
751    }
752
753    fn get_scale_factor(&self) -> FftScaleFactor {
754        self.scale
755    }
756
757    fn get_direction(&self) -> FftDirection {
758        self.direction
759    }
760
761    fn get_ordering(&self) -> FftOrdering {
762        self.ordering
763    }
764}
765
766#[cfg(test)]
767mod tests {
768    use std::time::Instant;
769
770    use super::*;
771    use crate::test_bench_data::{fft_gaussian_32768_golden, fft_gaussian_32768_input};
772
773    fn assert_complex_close(actual: Complex<f64>, expected: Complex<f64>, tol: f64) {
774        assert!(
775            (actual.re - expected.re).abs() < tol && (actual.im - expected.im).abs() < tol,
776            "actual={actual:?}, expected={expected:?}, tol={tol}"
777        );
778    }
779
780    fn bit_reverse_index(mut n: usize, bits: usize) -> usize {
781        let mut reversed = 0;
782        for _ in 0..bits {
783            reversed <<= 1;
784            reversed |= n & 1;
785            n >>= 1;
786        }
787        reversed
788    }
789
790    fn lcg(seed: &mut u64) -> f64 {
791        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
792        ((*seed >> 11) as f64 / (1u64 << 53) as f64) - 0.5
793    }
794
795    fn random_signal(n: usize, seed: u64) -> Vec<Complex<f64>> {
796        let mut s = seed;
797        (0..n).map(|_| Complex::new(lcg(&mut s), lcg(&mut s))).collect()
798    }
799
800    /// Exact O(n²) DFT.
801    fn naive_dft(x: &[Complex<f64>], inverse: bool) -> Vec<Complex<f64>> {
802        let n = x.len();
803        let sign = if inverse { 1.0 } else { -1.0 };
804        (0..n)
805            .map(|k| {
806                x.iter()
807                    .enumerate()
808                    .map(|(t, v)| v * Complex::from_polar(1.0, sign * 2.0 * std::f64::consts::PI * ((k * t) % n) as f64 / n as f64))
809                    .sum()
810            })
811            .collect()
812    }
813
814    /// Straightforward radix-2 reference with exactly computed twiddles (for large sizes).
815    fn reference_fft(x: &[Complex<f64>], inverse: bool) -> Vec<Complex<f64>> {
816        let n = x.len();
817        let bits = n.trailing_zeros() as usize;
818        let mut a: Vec<Complex<f64>> = (0..n).map(|i| x[bit_reverse_index(i, bits)]).collect();
819        let sign = if inverse { 1.0 } else { -1.0 };
820        let mut m = 2;
821        while m <= n {
822            for k in (0..n).step_by(m) {
823                for j in 0..m / 2 {
824                    let w = Complex::from_polar(1.0, sign * 2.0 * std::f64::consts::PI * j as f64 / m as f64);
825                    let (u, t) = (a[k + j], w * a[k + j + m / 2]);
826                    a[k + j] = u + t;
827                    a[k + j + m / 2] = u - t;
828                }
829            }
830            m *= 2;
831        }
832        a
833    }
834
835    fn run(n: usize, direction: FftDirection, ordering: FftOrdering, scale: FftScaleFactor, input: &[Complex<f64>]) -> Vec<Complex<f64>> {
836        let mut fft = BestFft::new();
837        fft.plan(n, scale, direction, ordering).unwrap();
838        fft.execute(input).unwrap()
839    }
840
841    #[test]
842    fn test_best_fft_standard_ordering() {
843        let input = fft_gaussian_32768_input();
844        let expected = fft_gaussian_32768_golden();
845        let mut fft = BestFft::new();
846        fft.plan(
847            input.len(),
848            FftScaleFactor::None,
849            FftDirection::Forward,
850            FftOrdering::Standard,
851        )
852        .unwrap();
853
854        let start = Instant::now();
855        let output = fft.execute(&input).unwrap();
856        dbg!("best_fft::standard execute elapsed", start.elapsed());
857
858        assert_eq!(output.len(), expected.len());
859        for (actual, expected) in output.iter().zip(expected.iter()) {
860            assert_complex_close(*actual, *expected, 1e-9);
861        }
862    }
863
864    #[test]
865    fn test_best_fft_bit_reversed_ordering() {
866        let input = fft_gaussian_32768_input();
867        let expected = fft_gaussian_32768_golden();
868        let bits = input.len().trailing_zeros() as usize;
869        let mut bit_reversed_input = vec![Complex::new(0.0, 0.0); input.len()];
870        for (i, value) in input.iter().enumerate() {
871            bit_reversed_input[bit_reverse_index(i, bits)] = *value;
872        }
873        let mut fft = BestFft::new();
874        fft.plan(
875            input.len(),
876            FftScaleFactor::None,
877            FftDirection::Forward,
878            FftOrdering::BitReversed,
879        )
880        .unwrap();
881
882        let start = Instant::now();
883        let output = fft.execute(&bit_reversed_input).unwrap();
884        dbg!("best_fft::bit_reversed execute elapsed", start.elapsed());
885
886        assert_eq!(output.len(), expected.len());
887        for (actual, expected) in output.iter().zip(expected.iter()) {
888            assert_complex_close(*actual, *expected, 1e-9);
889        }
890    }
891
892    #[test]
893    fn matches_the_exact_dft_for_every_small_size_and_both_directions() {
894        for log2n in 0..=9 {
895            let n = 1usize << log2n;
896            let x = random_signal(n, 7 + log2n as u64);
897            for (direction, inverse) in [(FftDirection::Forward, false), (FftDirection::Inverse, true)] {
898                let got = run(n, direction, FftOrdering::Standard, FftScaleFactor::None, &x);
899                let want = naive_dft(&x, inverse);
900                for (g, w) in got.iter().zip(&want) {
901                    assert!((g - w).norm() < 1e-11 * (n as f64).max(1.0), "n={n} inverse={inverse}: {g} vs {w}");
902                }
903            }
904        }
905    }
906
907    #[test]
908    fn matches_an_exact_reference_for_large_sizes_spanning_cache_blocks() {
909        // Sizes on both sides of the cache block, with even and odd log2.
910        for log2n in [10usize, 11, 12, 13, 14, 15, 16, 17] {
911            let n = 1usize << log2n;
912            let x = random_signal(n, 100 + log2n as u64);
913            for (direction, inverse) in [(FftDirection::Forward, false), (FftDirection::Inverse, true)] {
914                let got = run(n, direction, FftOrdering::Standard, FftScaleFactor::None, &x);
915                let want = reference_fft(&x, inverse);
916                let worst = got.iter().zip(&want).map(|(g, w)| (g - w).norm()).fold(0.0, f64::max);
917                assert!(worst < 1e-10 * (n as f64).sqrt() * log2n as f64, "n={n} inverse={inverse}: worst error {worst}");
918            }
919        }
920    }
921
922    #[test]
923    fn bit_reversed_input_and_scale_factors() {
924        for log2n in [1usize, 2, 3, 6, 11, 14] {
925            let n = 1usize << log2n;
926            let x = random_signal(n, 300 + log2n as u64);
927            let reversed: Vec<Complex<f64>> = (0..n).map(|i| x[bit_reverse_index(i, log2n)]).collect();
928            let plain = run(n, FftDirection::Forward, FftOrdering::Standard, FftScaleFactor::None, &x);
929            let from_reversed = run(n, FftDirection::Forward, FftOrdering::BitReversed, FftScaleFactor::None, &reversed);
930            assert!(plain.iter().zip(&from_reversed).all(|(a, b)| (a - b).norm() < 1e-12));
931            for (scale, factor) in [(FftScaleFactor::SqrtN, 1.0 / (n as f64).sqrt()), (FftScaleFactor::N, 1.0 / n as f64)] {
932                let scaled = run(n, FftDirection::Forward, FftOrdering::Standard, scale, &x);
933                assert!(plain.iter().zip(&scaled).all(|(a, b)| (a * factor - b).norm() < 1e-12 * (n as f64)), "n={n} {scale:?}");
934                let scaled_rev = run(n, FftDirection::Forward, FftOrdering::BitReversed, scale, &reversed);
935                assert!(plain.iter().zip(&scaled_rev).all(|(a, b)| (a * factor - b).norm() < 1e-12 * (n as f64)));
936            }
937        }
938    }
939
940    #[test]
941    fn forward_then_inverse_with_n_scaling_round_trips() {
942        for log2n in [0usize, 1, 2, 5, 12, 13, 16] {
943            let n = 1usize << log2n;
944            let x = random_signal(n, 500 + log2n as u64);
945            let y = run(n, FftDirection::Forward, FftOrdering::Standard, FftScaleFactor::None, &x);
946            let back = run(n, FftDirection::Inverse, FftOrdering::Standard, FftScaleFactor::N, &y);
947            let worst = x.iter().zip(&back).map(|(a, b)| (a - b).norm()).fold(0.0, f64::max);
948            assert!(worst < 1e-13 * log2n.max(1) as f64, "n={n}: {worst}");
949        }
950    }
951
952    #[test]
953    fn the_scalar_kernel_agrees_with_the_simd_kernel() {
954        // Force the portable path and compare with whatever the CPU selected.
955        for log2n in [1usize, 2, 3, 4, 9, 11, 12, 15] {
956            let n = 1usize << log2n;
957            let x = random_signal(n, 900 + log2n as u64);
958            for direction in [FftDirection::Forward, FftDirection::Inverse] {
959                for ordering in [FftOrdering::Standard, FftOrdering::BitReversed] {
960                    for scale in [FftScaleFactor::None, FftScaleFactor::N] {
961                        let mut fast = BestFft::new();
962                        fast.plan(n, scale, direction, ordering).unwrap();
963                        let mut scalar = BestFft::new();
964                        scalar.plan(n, scale, direction, ordering).unwrap();
965                        scalar.use_avx = false;
966                        let (a, b) = (fast.execute(&x).unwrap(), scalar.execute(&x).unwrap());
967                        assert!(a.iter().zip(&b).all(|(p, q)| (p - q).norm() < 1e-12 * n as f64), "n={n} {direction:?} {ordering:?} {scale:?}");
968                    }
969                }
970            }
971        }
972    }
973
974    #[test]
975    fn repeated_execution_reuses_the_plan_and_rejects_wrong_sizes() {
976        let mut fft = BestFft::new();
977        fft.plan(64, FftScaleFactor::None, FftDirection::Forward, FftOrdering::Standard).unwrap();
978        let x = random_signal(64, 1);
979        let first = fft.execute(&x).unwrap();
980        assert_eq!(fft.execute(&x).unwrap(), first);
981        assert!(fft.execute(&x[..32]).is_err());
982        assert!(fft.plan(48, FftScaleFactor::None, FftDirection::Forward, FftOrdering::Standard).is_err());
983        // Replanning to a different size and direction works.
984        fft.plan(8, FftScaleFactor::N, FftDirection::Inverse, FftOrdering::Standard).unwrap();
985        assert_eq!(fft.get_size(), 8);
986        let one = vec![Complex::new(1.0, 0.0); 8];
987        let out = fft.execute(&one).unwrap();
988        assert!((out[0] - Complex::new(1.0, 0.0)).norm() < 1e-15 && out[1..].iter().all(|v| v.norm() < 1e-15));
989    }
990}