forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB50503afTahinli3 months ago1344 commits

fft.rs776 lines, 27.2 KiBHistoryRawDownload
1//! Power-of-two complex FFT, plus a real-input wrapper.
2//!
3//! The kernel is a Stockham auto-sort decimation-in-frequency transform,
4//! radix-4 wherever the remaining size allows and radix-2 for the odd stage.
5//! Stockham was chosen over the textbook bit-reversed Cooley-Tukey for one
6//! reason: every read and write inside a stage is unit stride, which is what
7//! makes the inner loop vectorise with no shuffles at all.
8//!
9//! Data is held **split** — real parts in one slice, imaginary in another —
10//! because that is the layout SIMD wants. [`Fft::forward`] and
11//! [`Fft::inverse`] accept the interleaved [`Complex`] form for callers who
12//! prefer it and de-interleave internally; the DCT and MDCT plans call the
13//! split entry points and never pay that pass.
14
15use core::ops::{Add, Mul, Sub};
16
17use crate::Real;
18
19/// The largest transform the plans accept, matching the largest window any
20/// codec in the family uses with room to spare.
21pub const MAX_LEN: usize = 1 << 16;
22
23/// A complex number in the crate's own minimal form (no `num-complex` dep).
24#[derive(Clone, Copy, Debug, Default, PartialEq)]
25pub struct Complex<T> {
26 /// Real part.
27 pub re: T,
28 /// Imaginary part.
29 pub im: T,
30}
31
32impl<T> Complex<T> {
33 /// A complex number from its parts.
34 pub const fn new(re: T, im: T) -> Complex<T> {
35 Complex { re, im }
36 }
37}
38
39impl<T: Real> Complex<T> {
40 /// Zero.
41 pub const ZERO: Complex<T> = Complex {
42 re: T::ZERO,
43 im: T::ZERO,
44 };
45
46 /// Complex conjugate.
47 #[inline]
48 pub fn conj(self) -> Complex<T> {
49 Complex::new(self.re, -self.im)
50 }
51
52 /// Multiplication by a real scalar.
53 #[inline]
54 pub fn scale(self, k: T) -> Complex<T> {
55 Complex::new(self.re * k, self.im * k)
56 }
57
58 /// Multiplication by `-i`, i.e. a quarter turn clockwise.
59 #[inline]
60 pub fn mul_neg_i(self) -> Complex<T> {
61 Complex::new(self.im, -self.re)
62 }
63
64 /// Squared magnitude.
65 #[inline]
66 pub fn norm_sqr(self) -> T {
67 self.re * self.re + self.im * self.im
68 }
69}
70
71impl<T: Real> Add for Complex<T> {
72 type Output = Complex<T>;
73 #[inline]
74 fn add(self, rhs: Complex<T>) -> Complex<T> {
75 Complex::new(self.re + rhs.re, self.im + rhs.im)
76 }
77}
78
79impl<T: Real> Sub for Complex<T> {
80 type Output = Complex<T>;
81 #[inline]
82 fn sub(self, rhs: Complex<T>) -> Complex<T> {
83 Complex::new(self.re - rhs.re, self.im - rhs.im)
84 }
85}
86
87impl<T: Real> Mul for Complex<T> {
88 type Output = Complex<T>;
89 #[inline]
90 fn mul(self, rhs: Complex<T>) -> Complex<T> {
91 Complex::new(
92 self.re * rhs.re - self.im * rhs.im,
93 self.re * rhs.im + self.im * rhs.re,
94 )
95 }
96}
97
98/// A complex FFT plan for one power-of-two size, in `f32` or `f64`.
99///
100/// Holds the twiddle table and the ping-pong scratch the Stockham passes need,
101/// so a transform allocates nothing. Because the scratch lives in the plan the
102/// transform methods take `&mut self`; share across threads by cloning.
103///
104/// ```
105/// use ec_dsp::{Complex, Fft};
106///
107/// let mut fft = Fft::<f32>::new(8);
108/// let mut data = [Complex::new(1.0, 0.0); 8];
109/// fft.forward(&mut data);
110/// // A constant signal has all its energy in bin 0.
111/// assert!((data[0].re - 8.0).abs() < 1e-5);
112/// assert!(data[1].norm_sqr() < 1e-10);
113/// fft.inverse(&mut data);
114/// assert!((data[3].re - 1.0).abs() < 1e-6);
115/// ```
116#[derive(Clone, Debug)]
117pub struct Fft<T: Real> {
118 n: usize,
119 twiddle_re: Vec<T>,
120 twiddle_im: Vec<T>,
121 scratch_re: Vec<T>,
122 scratch_im: Vec<T>,
123 split_re: Vec<T>,
124 split_im: Vec<T>,
125}
126
127impl<T: Real> Fft<T> {
128 /// A plan for `n` points.
129 ///
130 /// # Panics
131 /// If `n` is not a power of two in `1..=`[`MAX_LEN`]. Sizes are a
132 /// compile-time property of a codec, so a bad one is API misuse.
133 pub fn new(n: usize) -> Fft<T> {
134 assert!(
135 n.is_power_of_two() && n <= MAX_LEN,
136 "fft length must be a power of two up to {MAX_LEN}, got {n}"
137 );
138 let mut twiddle_re = Vec::with_capacity(n);
139 let mut twiddle_im = Vec::with_capacity(n);
140 for k in 0..n {
141 // exp(-2*pi*i*k/n), always evaluated in f64 and rounded once.
142 let angle = -2.0 * core::f64::consts::PI * k as f64 / n as f64;
143 twiddle_re.push(T::from_f64(angle.cos()));
144 twiddle_im.push(T::from_f64(angle.sin()));
145 }
146 Fft {
147 n,
148 twiddle_re,
149 twiddle_im,
150 scratch_re: vec![T::ZERO; n],
151 scratch_im: vec![T::ZERO; n],
152 split_re: vec![T::ZERO; n],
153 split_im: vec![T::ZERO; n],
154 }
155 }
156
157 /// Points per transform.
158 pub fn size(&self) -> usize {
159 self.n
160 }
161
162 /// Forward transform, `exp(-2*pi*i*k*n/N)`, in place.
163 ///
164 /// # Panics
165 /// If `data.len() != self.size()`.
166 pub fn forward(&mut self, data: &mut [Complex<T>]) {
167 self.interleaved(data, false);
168 }
169
170 /// Inverse transform **including** the `1/n` scaling, in place, so that
171 /// `inverse(forward(x)) == x`.
172 ///
173 /// # Panics
174 /// If `data.len() != self.size()`.
175 pub fn inverse(&mut self, data: &mut [Complex<T>]) {
176 self.interleaved(data, true);
177 }
178
179 fn interleaved(&mut self, data: &mut [Complex<T>], inverse: bool) {
180 assert_eq!(data.len(), self.n, "fft input length must equal plan size");
181 for ((re, im), c) in self
182 .split_re
183 .iter_mut()
184 .zip(self.split_im.iter_mut())
185 .zip(data.iter())
186 {
187 *re = c.re;
188 *im = c.im;
189 }
190 let (mut re, mut im) = (
191 core::mem::take(&mut self.split_re),
192 core::mem::take(&mut self.split_im),
193 );
194 if inverse {
195 self.inverse_split(&mut re, &mut im);
196 } else {
197 self.forward_split(&mut re, &mut im);
198 }
199 for (c, (re, im)) in data.iter_mut().zip(re.iter().zip(im.iter())) {
200 *c = Complex::new(*re, *im);
201 }
202 self.split_re = re;
203 self.split_im = im;
204 }
205
206 /// Forward transform of split-layout data, in place. The allocation-free
207 /// entry point the other transforms in this crate use.
208 ///
209 /// # Panics
210 /// If either slice length differs from [`Fft::size`].
211 pub fn forward_split(&mut self, re: &mut [T], im: &mut [T]) {
212 self.stockham(re, im);
213 }
214
215 /// Inverse transform of split-layout data, in place, including `1/n`.
216 ///
217 /// Uses the identity `ifft(x) = swap(fft(swap(x)))/n`, where `swap`
218 /// exchanges real and imaginary parts — one kernel serves both directions.
219 ///
220 /// # Panics
221 /// If either slice length differs from [`Fft::size`].
222 pub fn inverse_split(&mut self, re: &mut [T], im: &mut [T]) {
223 self.stockham(im, re);
224 let norm = T::ONE / T::from_f64(self.n as f64);
225 crate::scale(re, norm);
226 crate::scale(im, norm);
227 }
228
229 fn stockham(&mut self, re: &mut [T], im: &mut [T]) {
230 assert_eq!(re.len(), self.n, "fft input length must equal plan size");
231 assert_eq!(im.len(), self.n, "fft input length must equal plan size");
232 let Fft {
233 n: total,
234 twiddle_re,
235 twiddle_im,
236 scratch_re,
237 scratch_im,
238 ..
239 } = self;
240
241 let mut xr: &mut [T] = re;
242 let mut xi: &mut [T] = im;
243 let mut yr: &mut [T] = scratch_re;
244 let mut yi: &mut [T] = scratch_im;
245
246 // Invariant across the loop: n * stride == total, so the twiddle for
247 // stage angle exp(-2*pi*i*p/n) is table entry p*stride.
248 let mut n = *total;
249 let mut stride = 1usize;
250 let mut in_scratch = false;
251 while n > 1 {
252 if n % 4 == 0 {
253 pass4(stride, xr, xi, yr, yi, twiddle_re, twiddle_im);
254 n /= 4;
255 stride *= 4;
256 } else {
257 pass2(stride, xr, xi, yr, yi, twiddle_re, twiddle_im);
258 n /= 2;
259 stride *= 2;
260 }
261 core::mem::swap(&mut xr, &mut yr);
262 core::mem::swap(&mut xi, &mut yi);
263 in_scratch = !in_scratch;
264 }
265 if in_scratch {
266 // Odd number of passes: the result sits in the scratch (`x` now),
267 // the caller's buffers are `y`.
268 yr.copy_from_slice(xr);
269 yi.copy_from_slice(xi);
270 }
271 }
272}
273
274/// One radix-2 Stockham pass. `stride` is the run length; the input holds two
275/// halves and the output two interleaved runs per block.
276///
277/// Every loop here walks `chunks_exact`, never an index: that is what makes
278/// the bounds checks fold away, and it is worth 10x — measured against the
279/// same code written with indices, which spent more instructions on checks
280/// than on arithmetic.
281#[inline]
282fn pass2<T: Real>(
283 stride: usize,
284 xr: &[T],
285 xi: &[T],
286 yr: &mut [T],
287 yi: &mut [T],
288 twiddle_re: &[T],
289 twiddle_im: &[T],
290) {
291 let half = xr.len() / 2;
292 let (a_re, b_re) = xr.split_at(half);
293 let (a_im, b_im) = xi.split_at(half);
294 let lanes = T::LANES;
295
296 let blocks = a_re
297 .chunks_exact(stride)
298 .zip(a_im.chunks_exact(stride))
299 .zip(b_re.chunks_exact(stride).zip(b_im.chunks_exact(stride)))
300 .zip(
301 yr.chunks_exact_mut(2 * stride)
302 .zip(yi.chunks_exact_mut(2 * stride)),
303 );
304 for (p, (((ar, ai), (br, bi)), (out_re, out_im))) in blocks.enumerate() {
305 let (wr, wi) = (twiddle_re[p * stride], twiddle_im[p * stride]);
306 let (o0r, o1r) = out_re.split_at_mut(stride);
307 let (o0i, o1i) = out_im.split_at_mut(stride);
308 if stride >= lanes {
309 let (wrv, wiv) = (wr.splat(), wi.splat());
310 let ins = ar
311 .chunks_exact(lanes)
312 .zip(ai.chunks_exact(lanes))
313 .zip(br.chunks_exact(lanes).zip(bi.chunks_exact(lanes)));
314 let outs = o0r
315 .chunks_exact_mut(lanes)
316 .zip(o0i.chunks_exact_mut(lanes))
317 .zip(o1r.chunks_exact_mut(lanes).zip(o1i.chunks_exact_mut(lanes)));
318 for (input, output) in ins.zip(outs) {
319 let ((a_lane_re, a_lane_im), (b_lane_re, b_lane_im)) = input;
320 let ((y0r, y0i), (y1r, y1i)) = output;
321 let (arv, aiv) = (T::load(a_lane_re), T::load(a_lane_im));
322 let (brv, biv) = (T::load(b_lane_re), T::load(b_lane_im));
323 T::store(arv + brv, y0r);
324 T::store(aiv + biv, y0i);
325 let (dr, di) = (arv - brv, aiv - biv);
326 T::store(dr * wrv - di * wiv, y1r);
327 T::store(dr * wiv + di * wrv, y1i);
328 }
329 } else {
330 for q in 0..stride {
331 let (arq, aiq) = (ar[q], ai[q]);
332 let (brq, biq) = (br[q], bi[q]);
333 o0r[q] = arq + brq;
334 o0i[q] = aiq + biq;
335 let (dr, di) = (arq - brq, aiq - biq);
336 o1r[q] = dr * wr - di * wi;
337 o1i[q] = dr * wi + di * wr;
338 }
339 }
340 }
341}
342
343/// One radix-4 Stockham pass — half the passes of radix-2 for the same size,
344/// which is where most of the speed comes from. Same chunk discipline as
345/// [`pass2`].
346#[inline]
347fn pass4<T: Real>(
348 stride: usize,
349 xr: &[T],
350 xi: &[T],
351 yr: &mut [T],
352 yi: &mut [T],
353 twiddle_re: &[T],
354 twiddle_im: &[T],
355) {
356 let quarter = xr.len() / 4;
357 let (a_re, rest) = xr.split_at(quarter);
358 let (b_re, rest) = rest.split_at(quarter);
359 let (c_re, d_re) = rest.split_at(quarter);
360 let (a_im, rest) = xi.split_at(quarter);
361 let (b_im, rest) = rest.split_at(quarter);
362 let (c_im, d_im) = rest.split_at(quarter);
363 let lanes = T::LANES;
364
365 let blocks = a_re
366 .chunks_exact(stride)
367 .zip(a_im.chunks_exact(stride))
368 .zip(b_re.chunks_exact(stride).zip(b_im.chunks_exact(stride)))
369 .zip(
370 c_re.chunks_exact(stride)
371 .zip(c_im.chunks_exact(stride))
372 .zip(d_re.chunks_exact(stride).zip(d_im.chunks_exact(stride))),
373 )
374 .zip(
375 yr.chunks_exact_mut(4 * stride)
376 .zip(yi.chunks_exact_mut(4 * stride)),
377 );
378 for (p, ((((ar, ai), (br, bi)), ((cr, ci), (dr, di))), (out_re, out_im))) in blocks.enumerate()
379 {
380 let step = p * stride;
381 let (w1r, w1i) = (twiddle_re[step], twiddle_im[step]);
382 let (w2r, w2i) = (twiddle_re[2 * step], twiddle_im[2 * step]);
383 let (w3r, w3i) = (twiddle_re[3 * step], twiddle_im[3 * step]);
384 let mut runs_re = out_re.chunks_exact_mut(stride);
385 let (o0r, o1r, o2r, o3r) = (
386 runs_re.next().expect("four output runs"),
387 runs_re.next().expect("four output runs"),
388 runs_re.next().expect("four output runs"),
389 runs_re.next().expect("four output runs"),
390 );
391 let mut runs_im = out_im.chunks_exact_mut(stride);
392 let (o0i, o1i, o2i, o3i) = (
393 runs_im.next().expect("four output runs"),
394 runs_im.next().expect("four output runs"),
395 runs_im.next().expect("four output runs"),
396 runs_im.next().expect("four output runs"),
397 );
398 if stride >= lanes {
399 let (w1rv, w1iv) = (w1r.splat(), w1i.splat());
400 let (w2rv, w2iv) = (w2r.splat(), w2i.splat());
401 let (w3rv, w3iv) = (w3r.splat(), w3i.splat());
402 let ins = ar
403 .chunks_exact(lanes)
404 .zip(ai.chunks_exact(lanes))
405 .zip(br.chunks_exact(lanes).zip(bi.chunks_exact(lanes)))
406 .zip(
407 cr.chunks_exact(lanes)
408 .zip(ci.chunks_exact(lanes))
409 .zip(dr.chunks_exact(lanes).zip(di.chunks_exact(lanes))),
410 );
411 let outs = o0r
412 .chunks_exact_mut(lanes)
413 .zip(o0i.chunks_exact_mut(lanes))
414 .zip(o1r.chunks_exact_mut(lanes).zip(o1i.chunks_exact_mut(lanes)))
415 .zip(
416 o2r.chunks_exact_mut(lanes)
417 .zip(o2i.chunks_exact_mut(lanes))
418 .zip(o3r.chunks_exact_mut(lanes).zip(o3i.chunks_exact_mut(lanes))),
419 );
420 for (input, output) in ins.zip(outs) {
421 let (((a_lr, a_li), (b_lr, b_li)), ((c_lr, c_li), (d_lr, d_li))) = input;
422 let (((y0r, y0i), (y1r, y1i)), ((y2r, y2i), (y3r, y3i))) = output;
423 let (arv, aiv) = (T::load(a_lr), T::load(a_li));
424 let (brv, biv) = (T::load(b_lr), T::load(b_li));
425 let (crv, civ) = (T::load(c_lr), T::load(c_li));
426 let (drv, div) = (T::load(d_lr), T::load(d_li));
427 let (apc_r, apc_i) = (arv + crv, aiv + civ);
428 let (amc_r, amc_i) = (arv - crv, aiv - civ);
429 let (bpd_r, bpd_i) = (brv + drv, biv + div);
430 let (bmd_r, bmd_i) = (brv - drv, biv - div);
431 // t0 = (a+c) + (b+d)
432 T::store(apc_r + bpd_r, y0r);
433 T::store(apc_i + bpd_i, y0i);
434 // t1 = (a-c) - i(b-d), times w^p
435 let (t1r, t1i) = (amc_r + bmd_i, amc_i - bmd_r);
436 T::store(t1r * w1rv - t1i * w1iv, y1r);
437 T::store(t1r * w1iv + t1i * w1rv, y1i);
438 // t2 = (a+c) - (b+d), times w^2p
439 let (t2r, t2i) = (apc_r - bpd_r, apc_i - bpd_i);
440 T::store(t2r * w2rv - t2i * w2iv, y2r);
441 T::store(t2r * w2iv + t2i * w2rv, y2i);
442 // t3 = (a-c) + i(b-d), times w^3p
443 let (t3r, t3i) = (amc_r - bmd_i, amc_i + bmd_r);
444 T::store(t3r * w3rv - t3i * w3iv, y3r);
445 T::store(t3r * w3iv + t3i * w3rv, y3i);
446 }
447 } else {
448 for q in 0..stride {
449 let (arq, aiq) = (ar[q], ai[q]);
450 let (brq, biq) = (br[q], bi[q]);
451 let (crq, ciq) = (cr[q], ci[q]);
452 let (drq, diq) = (dr[q], di[q]);
453 let (apc_r, apc_i) = (arq + crq, aiq + ciq);
454 let (amc_r, amc_i) = (arq - crq, aiq - ciq);
455 let (bpd_r, bpd_i) = (brq + drq, biq + diq);
456 let (bmd_r, bmd_i) = (brq - drq, biq - diq);
457 o0r[q] = apc_r + bpd_r;
458 o0i[q] = apc_i + bpd_i;
459 let (t1r, t1i) = (amc_r + bmd_i, amc_i - bmd_r);
460 o1r[q] = t1r * w1r - t1i * w1i;
461 o1i[q] = t1r * w1i + t1i * w1r;
462 let (t2r, t2i) = (apc_r - bpd_r, apc_i - bpd_i);
463 o2r[q] = t2r * w2r - t2i * w2i;
464 o2i[q] = t2r * w2i + t2i * w2r;
465 let (t3r, t3i) = (amc_r - bmd_i, amc_i + bmd_r);
466 o3r[q] = t3r * w3r - t3i * w3i;
467 o3i[q] = t3r * w3i + t3i * w3r;
468 }
469 }
470 }
471}
472
473/// Real-input FFT: an `n`-point real transform on an `n/2`-point complex one.
474///
475/// Half the work and half the memory of stuffing zeros into a complex FFT.
476/// The spectrum is the `n/2 + 1` non-redundant bins; bins `0` and `n/2` are
477/// real, and the caller gets the conjugate half back for free by symmetry.
478///
479/// ```
480/// use ec_dsp::RealFft;
481///
482/// let mut rfft = RealFft::<f64>::new(16);
483/// let signal: Vec<f64> = (0..16).map(|n| (n as f64).sin()).collect();
484/// let mut spectrum = vec![Default::default(); 9];
485/// rfft.forward(&signal, &mut spectrum);
486/// let mut back = vec![0.0; 16];
487/// rfft.inverse(&spectrum, &mut back);
488/// assert!(back.iter().zip(&signal).all(|(a, b)| (a - b).abs() < 1e-12));
489/// ```
490#[derive(Clone, Debug)]
491pub struct RealFft<T: Real> {
492 n: usize,
493 half: Fft<T>,
494 twiddle_re: Vec<T>,
495 twiddle_im: Vec<T>,
496 buf_re: Vec<T>,
497 buf_im: Vec<T>,
498}
499
500impl<T: Real> RealFft<T> {
501 /// A plan for `n` real points.
502 ///
503 /// # Panics
504 /// If `n` is not a power of two of at least 4, or exceeds [`MAX_LEN`].
505 pub fn new(n: usize) -> RealFft<T> {
506 assert!(
507 n.is_power_of_two() && (4..=MAX_LEN).contains(&n),
508 "real fft length must be a power of two in 4..={MAX_LEN}, got {n}"
509 );
510 let half = n / 2;
511 let mut twiddle_re = Vec::with_capacity(half + 1);
512 let mut twiddle_im = Vec::with_capacity(half + 1);
513 for k in 0..=half {
514 let angle = -2.0 * core::f64::consts::PI * k as f64 / n as f64;
515 twiddle_re.push(T::from_f64(angle.cos()));
516 twiddle_im.push(T::from_f64(angle.sin()));
517 }
518 RealFft {
519 n,
520 half: Fft::new(half),
521 twiddle_re,
522 twiddle_im,
523 buf_re: vec![T::ZERO; half],
524 buf_im: vec![T::ZERO; half],
525 }
526 }
527
528 /// Points per transform (the real-domain length).
529 pub fn size(&self) -> usize {
530 self.n
531 }
532
533 /// Bins in the spectrum, `size()/2 + 1`.
534 pub fn spectrum_len(&self) -> usize {
535 self.n / 2 + 1
536 }
537
538 /// Transforms `input` into `spectrum`.
539 ///
540 /// # Panics
541 /// If `input.len() != size()` or `spectrum.len() != spectrum_len()`.
542 pub fn forward(&mut self, input: &[T], spectrum: &mut [Complex<T>]) {
543 assert_eq!(input.len(), self.n, "real fft input length must equal size");
544 assert_eq!(
545 spectrum.len(),
546 self.spectrum_len(),
547 "spectrum length must be size()/2 + 1"
548 );
549 let m = self.n / 2;
550 for j in 0..m {
551 self.buf_re[j] = input[2 * j];
552 self.buf_im[j] = input[2 * j + 1];
553 }
554 self.half.forward_split(&mut self.buf_re, &mut self.buf_im);
555
556 let half_scale = T::from_f64(0.5);
557 for (k, bin) in spectrum.iter_mut().enumerate() {
558 let z = Complex::new(self.buf_re[k % m], self.buf_im[k % m]);
559 let zc = Complex::new(self.buf_re[(m - k) % m], self.buf_im[(m - k) % m]).conj();
560 let even = (z + zc).scale(half_scale);
561 let odd = (z - zc).scale(half_scale);
562 let tw = Complex::new(self.twiddle_re[k], self.twiddle_im[k]);
563 *bin = even + (tw * odd).mul_neg_i();
564 }
565 }
566
567 /// Reconstructs `output` from `spectrum`, scaled so that
568 /// `inverse(forward(x)) == x`.
569 ///
570 /// # Panics
571 /// If `output.len() != size()` or `spectrum.len() != spectrum_len()`.
572 pub fn inverse(&mut self, spectrum: &[Complex<T>], output: &mut [T]) {
573 assert_eq!(
574 output.len(),
575 self.n,
576 "real fft output length must equal size"
577 );
578 assert_eq!(
579 spectrum.len(),
580 self.spectrum_len(),
581 "spectrum length must be size()/2 + 1"
582 );
583 let m = self.n / 2;
584 let half_scale = T::from_f64(0.5);
585 for k in 0..m {
586 let a = spectrum[k];
587 let b = spectrum[m - k].conj();
588 let even = (a + b).scale(half_scale);
589 let odd = (a - b).scale(half_scale);
590 // Conjugate twiddle, and +i instead of -i: the forward step run backwards.
591 let tw = Complex::new(self.twiddle_re[k], self.twiddle_im[k]).conj();
592 let z = even - (tw * odd).mul_neg_i();
593 self.buf_re[k] = z.re;
594 self.buf_im[k] = z.im;
595 }
596 self.half.inverse_split(&mut self.buf_re, &mut self.buf_im);
597 for j in 0..m {
598 output[2 * j] = self.buf_re[j];
599 output[2 * j + 1] = self.buf_im[j];
600 }
601 }
602}
603
604#[cfg(test)]
605mod tests {
606 use super::*;
607 use crate::tests::{noise, rel_error};
608
609 /// O(n^2) DFT in `f64` — the reference the fast path is judged against.
610 /// Test-only by construction: nothing outside `#[cfg(test)]` can call it,
611 /// which is the family rule about naive transforms in shipping paths.
612 fn reference_dft(input: &[Complex<f64>], inverse: bool) -> Vec<Complex<f64>> {
613 let n = input.len();
614 let sign = if inverse { 1.0 } else { -1.0 };
615 (0..n)
616 .map(|k| {
617 let mut acc = Complex::new(0.0, 0.0);
618 for (j, x) in input.iter().enumerate() {
619 let angle = sign * 2.0 * core::f64::consts::PI * (j * k % n) as f64 / n as f64;
620 acc = acc + *x * Complex::new(angle.cos(), angle.sin());
621 }
622 acc
623 })
624 .collect()
625 }
626
627 fn complex_noise(n: usize, seed: u64) -> Vec<Complex<f64>> {
628 let re: Vec<f64> = noise(n, seed);
629 let im: Vec<f64> = noise(n, seed ^ 0x9e37_79b9);
630 re.iter()
631 .zip(&im)
632 .map(|(r, i)| Complex::new(*r, *i))
633 .collect()
634 }
635
636 #[test]
637 fn agrees_with_reference_dft_f64() {
638 let mut worst = 0.0f64;
639 let mut size = 0;
640 for shift in 3..=13 {
641 let n = 1usize << shift;
642 let input = complex_noise(n, 0x1234 + n as u64);
643 let want = reference_dft(&input, false);
644 let mut got = input.clone();
645 Fft::new(n).forward(&mut got);
646 let error = complex_error(&got, &want);
647 if error > worst {
648 worst = error;
649 size = n;
650 }
651 assert!(error < 1e-12, "n = {n}: f64 error {error:e}");
652 }
653 println!("f64 FFT vs reference DFT: worst rel error {worst:e} (n = {size})");
654 }
655
656 #[test]
657 fn agrees_with_reference_dft_f32() {
658 let mut worst = 0.0f64;
659 let mut size = 0;
660 for shift in 3..=13 {
661 let n = 1usize << shift;
662 let input = complex_noise(n, 0x5678 + n as u64);
663 let want = reference_dft(&input, false);
664 let mut got: Vec<Complex<f32>> = input
665 .iter()
666 .map(|c| Complex::new(c.re as f32, c.im as f32))
667 .collect();
668 Fft::new(n).forward(&mut got);
669 let widened: Vec<Complex<f64>> = got
670 .iter()
671 .map(|c| Complex::new(c.re as f64, c.im as f64))
672 .collect();
673 let error = complex_error(&widened, &want);
674 if error > worst {
675 worst = error;
676 size = n;
677 }
678 assert!(error < 1e-5, "n = {n}: f32 error {error:e}");
679 }
680 println!("f32 FFT vs reference DFT: worst rel error {worst:e} (n = {size})");
681 }
682
683 #[test]
684 fn inverse_reference_matches_plan() {
685 let n = 64;
686 let input = complex_noise(n, 99);
687 let want = reference_dft(&input, true);
688 let mut got = input.clone();
689 let mut fft = Fft::new(n);
690 fft.inverse(&mut got);
691 // The plan normalises by n; the reference does not.
692 let scaled: Vec<Complex<f64>> = want.iter().map(|c| c.scale(1.0 / n as f64)).collect();
693 assert!(complex_error(&got, &scaled) < 1e-12);
694 }
695
696 #[test]
697 fn round_trips_f32_every_size() {
698 let mut worst = 0.0f64;
699 let mut size = 0;
700 for shift in 3..=15 {
701 let n = 1usize << shift;
702 let input: Vec<f32> = noise(n, 0xabc + n as u64);
703 let mut data: Vec<Complex<f32>> = input.iter().map(|v| Complex::new(*v, 0.0)).collect();
704 let mut fft = Fft::new(n);
705 fft.forward(&mut data);
706 fft.inverse(&mut data);
707 let got: Vec<f32> = data.iter().map(|c| c.re).collect();
708 let error = rel_error(&got, &input);
709 if error > worst {
710 worst = error;
711 size = n;
712 }
713 assert!(error < 1e-6, "n = {n}: round-trip error {error:e}");
714 }
715 println!("f32 FFT round trip: worst rel error {worst:e} (n = {size})");
716 }
717
718 #[test]
719 fn split_and_interleaved_agree() {
720 let n = 256;
721 let input = complex_noise(n, 4242);
722 let mut fft = Fft::new(n);
723 let mut interleaved = input.clone();
724 fft.forward(&mut interleaved);
725 let mut re: Vec<f64> = input.iter().map(|c| c.re).collect();
726 let mut im: Vec<f64> = input.iter().map(|c| c.im).collect();
727 fft.forward_split(&mut re, &mut im);
728 for (k, c) in interleaved.iter().enumerate() {
729 assert!((c.re - re[k]).abs() < 1e-12 && (c.im - im[k]).abs() < 1e-12);
730 }
731 }
732
733 #[test]
734 fn real_fft_matches_complex_fft() {
735 for shift in 2..=12 {
736 let n = 1usize << shift;
737 let signal: Vec<f64> = noise(n, 0xfeed + n as u64);
738 let mut rfft = RealFft::new(n);
739 let mut spectrum = vec![Complex::new(0.0, 0.0); n / 2 + 1];
740 rfft.forward(&signal, &mut spectrum);
741
742 let mut want: Vec<Complex<f64>> =
743 signal.iter().map(|v| Complex::new(*v, 0.0)).collect();
744 Fft::new(n).forward(&mut want);
745 for k in 0..=n / 2 {
746 assert!(
747 (spectrum[k].re - want[k].re).abs() < 1e-10
748 && (spectrum[k].im - want[k].im).abs() < 1e-10,
749 "n = {n}, bin {k}: {:?} vs {:?}",
750 spectrum[k],
751 want[k]
752 );
753 }
754
755 let mut back = vec![0.0; n];
756 rfft.inverse(&spectrum, &mut back);
757 assert!(rel_error(&back, &signal) < 1e-12, "n = {n} real round trip");
758 }
759 }
760
761 #[test]
762 #[should_panic(expected = "power of two")]
763 fn rejects_non_power_of_two() {
764 let _ = Fft::<f32>::new(48);
765 }
766
767 fn complex_error(got: &[Complex<f64>], want: &[Complex<f64>]) -> f64 {
768 let mut num = 0.0;
769 let mut den = 0.0;
770 for (g, w) in got.iter().zip(want) {
771 num += (*g - *w).norm_sqr();
772 den += w.norm_sqr();
773 }
774 (num / den).sqrt()
775 }
776}