Working FFTs

This commit is contained in:
2025-09-24 09:03:13 +02:00
parent d191b912b0
commit bd7ae2b19e
9 changed files with 15071 additions and 5003 deletions

View File

@ -9,14 +9,26 @@ use std::iter::Map;
use crate::{
complex::Complex32,
fft::{
dft::NaiveDFT, mixed_radix::MixedRadixFFT, rader::RaderFFT, rader2::Rader2FFT,
radix2::Radix2FFT,
},
fft::{dft::NaiveDFT, mixed_radix::MixedRadixFFT, rader::RaderFFT, radix2::Radix2FFT},
};
#[derive(Copy, Clone)]
pub enum FFTDirection {
Forward,
Inverse,
}
impl FFTDirection {
fn sign(&self) -> f32 {
match self {
FFTDirection::Forward => 1.,
FFTDirection::Inverse => -1.,
}
}
}
pub trait DFT {
fn create(size: usize) -> Self
fn create(size: usize, direction: FFTDirection) -> Self
where
Self: Sized;
@ -30,25 +42,23 @@ pub trait DFTWindow {
fn eval(t: f32) -> f32;
}
pub fn create_fft(size: usize) -> Box<dyn DFT> {
pub fn create_fft(size: usize, direction: FFTDirection) -> Box<dyn DFT> {
if size <= 16 {
println!("Naive {size}");
return Box::new(NaiveDFT::create(size));
//println!("Naive {size}");
return Box::new(NaiveDFT::create(size, direction));
}
if size.count_ones() == 1 {
// TODO: Return hardcoded fft for small sized
println!("Radix 2 {size}");
return Box::new(Radix2FFT::create(size));
//return Box::new(::create(size));
//println!("Radix 2 {size}");
return Box::new(Radix2FFT::create(size, direction));
}
if is_prime(size) {
println!("Prime rader {size}");
return Box::new(RaderFFT::create(size));
//println!("Prime rader {size}");
return Box::new(RaderFFT::create(size, direction));
}
println!("Mixed radix {size}");
Box::new(MixedRadixFFT::create(size))
//println!("Mixed radix {size}");
Box::new(MixedRadixFFT::create(size, direction))
}
// Utilities

View File

@ -1,21 +1,23 @@
use crate::complex::Complex32;
use crate::fft::DFT;
use crate::fft::{DFT, FFTDirection};
use std::f32::consts::PI;
pub struct NaiveDFT {
output_buffer: Box<[Complex32]>,
input_buffer: Box<[Complex32]>,
direction: FFTDirection,
size: usize,
}
impl DFT for NaiveDFT {
fn create(size: usize) -> Self
fn create(size: usize, direction: FFTDirection) -> Self
where
Self: Sized,
{
NaiveDFT {
output_buffer: vec![Complex32::zero(); size].into_boxed_slice(),
input_buffer: vec![Complex32::zero(); size].into_boxed_slice(),
direction,
size,
}
}
@ -25,11 +27,13 @@ impl DFT for NaiveDFT {
*out = Complex32::zero();
for (i, inp) in self.input_buffer.iter().enumerate() {
*out = *out
+ ((*inp * Complex32::cexp(-2. * PI * (i * freq) as f32 / self.size as f32))
+ ((*inp
* Complex32::cexp(
-2. * self.direction.sign() * PI * (i * freq) as f32 / self.size as f32,
))
* window(i as f32 / self.size as f32));
}
}
}
fn get_input(&mut self) -> &mut [Complex32] {
@ -40,18 +44,3 @@ impl DFT for NaiveDFT {
&self.output_buffer
}
}
impl NaiveDFT
{
pub fn execute_inv(&mut self, window: fn(f32) -> f32) {
for (freq, out) in self.output_buffer.iter_mut().enumerate() {
*out = Complex32::zero();
for (i, inp) in self.input_buffer.iter().enumerate() {
*out = *out
+ ((*inp * Complex32::cexp(2. * PI * (i * freq) as f32 / self.size as f32))
* window(i as f32 / self.size as f32));
}
}
}
}

View File

@ -4,7 +4,7 @@ use std::f32::consts::PI;
use crate::{
complex::Complex32,
fft::{DFT, create_fft, dft::NaiveDFT, prime_factors, windows},
fft::{DFT, FFTDirection, create_fft, dft::NaiveDFT, prime_factors, windows},
};
pub struct MixedRadixFFT {
@ -23,23 +23,20 @@ pub struct MixedRadixFFT {
}
impl DFT for MixedRadixFFT {
fn create(size: usize) -> Self {
fn create(size: usize, direction: FFTDirection) -> Self {
let q = decide_radix_factor(size);
let p = size / q;
println!("{} {}", p, q);
// TODO: Figure out why it does not work in the other direction ...
//let (p, q) = (q, p);
let qfft = create_fft(q);
let pfft = create_fft(p);
let qfft = create_fft(q, direction);
let pfft = create_fft(p, direction);
let qfft = Box::new(NaiveDFT::create(q));
let pfft = Box::new(NaiveDFT::create(p));
//let qfft = Box::new(NaiveDFT::create(q, direction));
//let pfft = Box::new(NaiveDFT::create(p, direction));
MixedRadixFFT {
input_buffer: vec![Complex32::zero(); size].into_boxed_slice(),
output_buffer: vec![Complex32::zero(); size].into_boxed_slice(),
size,
twiddle_factors: compute_twiddle_factors(size),
twiddle_factors: compute_twiddle_factors(size, direction),
qfft,
pfft,
@ -92,11 +89,11 @@ impl DFT for MixedRadixFFT {
}
}
fn compute_twiddle_factors(size: usize) -> Box<[Complex32]> {
fn compute_twiddle_factors(size: usize, direction: FFTDirection) -> Box<[Complex32]> {
let mut factors = vec![Complex32::zero(); size].into_boxed_slice();
for i in 0..size {
factors[i] = Complex32::cexp(-2. * PI * i as f32 / (size as f32));
factors[i] = Complex32::cexp(-2. * direction.sign() * PI * i as f32 / (size as f32));
}
factors
}

View File

@ -5,7 +5,7 @@ use std::{f32::consts::PI, ops::Deref};
use super::mixed_radix;
use crate::{
complex::Complex32,
fft::{DFT, create_fft, dft::NaiveDFT, is_prime, windows},
fft::{DFT, FFTDirection, create_fft, dft::NaiveDFT, is_prime, windows},
};
pub struct RaderFFT {
@ -14,13 +14,14 @@ pub struct RaderFFT {
permutations: Box<[usize]>,
convolution_op: Box<[Complex32]>,
conv_fft: Box<NaiveDFT>,
inv_fft: Box<dyn DFT>,
conv_fft: Box<dyn DFT>,
size: usize,
}
impl DFT for RaderFFT {
fn create(size: usize) -> Self
fn create(size: usize, direction: FFTDirection) -> Self
where
Self: Sized,
{
@ -28,14 +29,16 @@ impl DFT for RaderFFT {
let g = compute_prime_primitive_root(size);
let permutations: Box<[usize]> = (0..(size - 1)).map(|i| exp_mod(g, i + 1, size)).collect();
let mut conv_fft = Box::new(NaiveDFT::create(size - 1));
let mut conv_fft = create_fft(size - 1, FFTDirection::Forward);
//let mut conv_fft = create_fft(size - 1);
conv_fft
.get_input()
.iter_mut()
.enumerate()
.for_each(|(i, x)| {
*x = Complex32::cexp(-2. * PI * (permutations[i] as f32) / (size as f32))
*x = Complex32::cexp(
-2. * direction.sign() * PI * (permutations[i] as f32) / (size as f32),
)
});
conv_fft.execute(windows::rectanguar);
@ -45,6 +48,7 @@ impl DFT for RaderFFT {
permutations,
convolution_op: conv_fft.get_output().iter().copied().collect(),
inv_fft: create_fft(size - 1, FFTDirection::Inverse),
conv_fft,
size,
@ -61,21 +65,20 @@ impl DFT for RaderFFT {
self.conv_fft.execute(windows::rectanguar);
for i in 0..(self.size - 1) {
self.output_buffer[i] =
self.conv_fft.get_output()[i] * self.convolution_op[i];
self.output_buffer[i] = self.conv_fft.get_output()[i] * self.convolution_op[i];
}
for i in 0..(self.size - 1) {
//self.conv_fft.get_input()[i] = self.output_buffer[i];
self.conv_fft.get_input()[i] = -self.output_buffer[self.size - 1 - i - 1];
self.inv_fft.get_input()[i] = self.output_buffer[i];
}
self.conv_fft.execute(windows::rectanguar);
self.inv_fft.execute(windows::rectanguar);
for i in 0..(self.size - 1) {
let k = self.permutations[i];
self.output_buffer[k] =
(self.conv_fft.get_output()[i] / (self.size - 1) as f32) + self.input_buffer[0];
(self.inv_fft.get_output()[i] / (self.size - 1) as f32) + self.input_buffer[0];
}
self.output_buffer[0] = self.input_buffer.iter().copied().sum();

View File

@ -1,11 +1,12 @@
// Implementation of raders's fft for prime sized ffts
/*
use std::{f32::consts::PI, ops::Deref};
use super::mixed_radix;
use crate::{
complex::Complex32,
fft::{DFT, create_fft, dft::NaiveDFT, is_prime, windows},
fft::{DFT, FFTDirection, create_fft, dft::NaiveDFT, is_prime, windows},
};
pub struct Rader2FFT {
@ -22,7 +23,7 @@ pub struct Rader2FFT {
}
impl DFT for Rader2FFT {
fn create(size: usize) -> Self
fn create(size: usize, direction: FFTDirection) -> Self
where
Self: Sized,
{
@ -165,3 +166,4 @@ pub fn next_pow2(mut n: usize) -> usize {
}
1 << pow
}
*/

View File

@ -1,19 +1,20 @@
// Cooley-Tukey algorithm
use crate::complex::Complex32;
use crate::fft::DFT;
use crate::fft::{DFT, FFTDirection};
use std::f32::consts::PI;
pub struct Radix2FFT {
output_buffer: Box<[Complex32]>,
input_buffer: Box<[Complex32]>,
direction: FFTDirection,
size: usize,
length: usize,
}
impl DFT for Radix2FFT {
// Size as power of two
fn create(size: usize) -> Self {
fn create(size: usize, direction: FFTDirection) -> Self {
if !is_power_of_two(size) {
panic!("Tried to create a Radix2 FFT with a non power of two size.");
}
@ -22,6 +23,7 @@ impl DFT for Radix2FFT {
output_buffer: vec![Complex32::zero(); size].into_boxed_slice(),
input_buffer: vec![Complex32::zero(); size].into_boxed_slice(),
size: size.ilog2() as usize,
direction,
length: size,
}
}
@ -41,7 +43,7 @@ impl DFT for Radix2FFT {
// Compute current polynomial at each unit root
let a = self.output_buffer[s + i];
let b = self.output_buffer[s + i + mid_point];
let angle = -2. * PI * (i as f32) / (pol_length as f32);
let angle = -2. * self.direction.sign() * PI * (i as f32) / (pol_length as f32);
let phasor = Complex32::cexp(angle);
self.output_buffer[i + s] = a + phasor * b;
self.output_buffer[i + s + mid_point] = a - phasor * b;

View File

@ -1,5 +1,8 @@
use std::{
f32::consts::PI, fs::File, io::{Read, Write}, ops::{Add, Div, Mul, Sub}
f32::consts::PI,
fs::File,
io::{Read, Write},
ops::{Add, Div, Mul, Sub},
};
mod bfsk;
@ -15,12 +18,11 @@ use nco::Nco;
use plotters::prelude::*;
use crate::fft::{
DFT, create_fft,
DFT, FFTDirection, create_fft,
dft::NaiveDFT,
mixed_radix::MixedRadixFFT,
prime_factors,
rader::{RaderFFT, compute_prime_primitive_root, exp_mod},
rader2::{Rader2FFT, next_pow2},
radix2::Radix2FFT,
windows,
};
@ -33,135 +35,7 @@ where
((input - in_min.clone()) / (in_max - in_min)) * (out_max - out_min.clone()) + out_min
}
fn euclid_mod(a: f32, m: f32) -> f32 {
let r = a % m;
if r < 0.0 { r + m } else { r }
}
struct QuickLCG(i32);
impl QuickLCG
{
pub fn seed(val: i32) -> QuickLCG
{
QuickLCG(val % 10)
}
pub fn next(&mut self) -> i32
{
self.0 = self.0.overflowing_mul(9321).0.overflowing_add(5672).0 % 10;
self.0
}
}
fn main() {
//test();
simple_test();
}
fn simple_test()
{
let sample_count = 7;
let mut dft = NaiveDFT::create(sample_count);
let mut fft = RaderFFT::create(sample_count);
let mut rand = QuickLCG::seed(2981237);
for (a, b) in dft.get_input().iter_mut().zip(fft.get_input().iter_mut())
{
let re = (rand.next() - 5) as f32;
let im = (rand.next() - 5) as f32;
*a = Complex32::new(re, im);
*b = Complex32::new(re, im);
}
dft.execute(windows::rectanguar);
fft.execute(windows::rectanguar);
for (a, b) in dft.get_output().iter().zip(fft.get_output().iter())
{
println!("{:0<7.3} {:0<7.3} \t {:0<7.3} {:0<7.3}", a.re, a.im, b.re, b.im);
}
}
fn test() {
let freq1 = 2. * PI / 4.0;
let freq2 = 2. * PI / 8.0;
//let sample_count = 71*71;
//let sample_count = 71 * 71;
//let sample_count = 4804;
let sample_count = 4809;
let mut o1 = Nco::new(freq1);
let mut o2 = Nco::new(freq2);
//let mut fft = ::create(sample_count);
//let mut dft = MixedRadixFFT::create(sample_count);
let mut fft = create_fft(sample_count);
//let mut dft = create_fft(sample_count);
for x in fft.get_input().iter_mut() {
*x = o1.cexp() + o2.cexp();
//*y = *x;
o1.step();
o2.step();
}
fft.execute(windows::rectanguar);
//dft.execute(windows::rectanguar);
let root = BitMapBackend::new("out.png", (640, 480)).into_drawing_area();
root.fill(&WHITE).unwrap();
let mut chart = ChartBuilder::on(&root)
.caption("fft", ("sans-serif", 50).into_font())
.margin(5)
.x_label_area_size(30)
.y_label_area_size(30)
.build_cartesian_2d(0f32..(sample_count as f32), -PI..PI)
.unwrap();
//chart.configure_mesh().draw()?;
/*
chart
.draw_series(LineSeries::new(
(0..sample_count)
.zip(dft.get_output().iter())
.map(|(x, y)| (x as f32, (*y).arg() )),
&RED,
))
.unwrap()
.legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], RED));
*/
chart
.draw_series(LineSeries::new(
(0..sample_count)
.zip(fft.get_output().iter())
.map(|(x, y)| (x as f32, (*y).mag() / sample_count as f32)),
&BLUE,
))
.unwrap()
.legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], BLUE));
chart
.configure_series_labels()
.background_style(&WHITE.mix(0.8))
.border_style(&BLACK)
.draw()
.unwrap();
root.present().unwrap();
let mut f = File::create("out.csv").unwrap();
for x in fft.get_output().iter()
{
f.write_all(
format!("{},\n", x.mag() / sample_count as f32).to_string().as_bytes()
).unwrap();
}
}
fn main() {}
fn modulate() {
let sample_rate = 44100;