Skip to content

Add FFT in Rust #688

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 5, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions contents/cooley_tukey/code/rust/fft.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
extern crate num;
extern crate rand;

use num::complex::Complex;
use rand::prelude::*;
use std::f64::consts::PI;

// This is based on the Python implementation.

fn dft(x: &[Complex<f64>]) -> Vec<Complex<f64>> {
let n = x.len();
(0..n)
.map(|i| {
(0..n)
.map(|k| {
x[k] * (Complex::new(0.0_f64, -2.0_f64) * PI * (i as f64) * (k as f64)
/ (n as f64))
.exp()
})
.sum()
})
.collect::<Vec<_>>()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The turbofish isn't necessary here due to the return type in the function signature.

}

fn cooley_tukey(x: &[Complex<f64>]) -> Vec<Complex<f64>> {
let n = x.len();
if n <= 1 {
return x.to_owned();
}
let even = cooley_tukey(&x.iter().step_by(2).cloned().collect::<Vec<_>>());
let odd = cooley_tukey(&x.iter().skip(1).step_by(2).cloned().collect::<Vec<_>>());

let mut temp = vec![Complex::new(0.0_f64, 0.0_f64); n];
for k in 0..(n / 2) {
temp[k] = even[k]
+ (Complex::new(0.0_f64, -2.0_f64) * PI * (k as f64) / (n as f64)).exp() * odd[k];
temp[k + n / 2] = even[k]
- (Complex::new(0.0_f64, -2.0_f64) * PI * (k as f64) / (n as f64)).exp() * odd[k];
}
temp
}

fn bit_reverse(x: &[Complex<f64>]) -> Vec<Complex<f64>> {
let n = x.len();
let mut temp = vec![Complex::new(0.0_f64, 0.0_f64); n];
for k in 0..n {
let b: usize = (0..((n as f64).log2() as usize))
.filter(|i| k >> i & 1 != 0)
.map(|i| 1 << ((((n as f64).log2()) as usize) - 1 - i))
.sum();
temp[k] = x[b];
temp[b] = x[k];
}
temp
}

fn iterative_cooley_tukey(x: &[Complex<f64>]) -> Vec<Complex<f64>> {
let n = x.len();

let mut new_x = bit_reverse(x);

for i in 1..=((n as f64).log2() as usize) {
let stride = 2_u128.pow(i as u32);
let w = (Complex::new(0.0_f64, -2.0_f64) * PI / (stride as f64)).exp();
for j in (0..n).step_by(stride as usize) {
let mut v = Complex::new(1.0_f64, 0.0_f64);
for k in 0..((stride / 2) as usize) {
let k_plus_j = new_x[k + j];
let k_plus_j_plus_half_stride = new_x[k + j + ((stride / 2) as usize)];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this intermediate and k_plus_j_plus_half_stride_2, since they're only used in one place each, don't buy you anything and make the code harder to read.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In getting rid of those three intermediates, I had to sacrifice the -= operator. If I didn't do that, the compiler warns that I "cannot borrow new_x as immutable because it is also borrowed as mutable".

new_x[k + j + ((stride / 2) as usize)] = k_plus_j - v * k_plus_j_plus_half_stride;
let k_plus_j_plus_half_stride_2 = new_x[k + j + ((stride / 2) as usize)];
new_x[k + j] -= k_plus_j_plus_half_stride_2 - k_plus_j;
v *= w;
}
}
}

new_x
}

fn main() {
let mut x = Vec::with_capacity(64);
let mut rng = thread_rng();
for _i in 0..64 {
let real = rng.gen_range(0.0_f64, 1.0_f64);
x.push(Complex::new(real, 0.0_f64));
}
let y = cooley_tukey(&x.clone());
let z = iterative_cooley_tukey(&x.clone());
let t = dft(&x.clone());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just noticed, these don't need to be cloned either.

I also think that you should leave the functions as not taking ownership.


println!(
"{}",
y.iter().zip(z.iter()).all(|i| (i.0 - i.1).norm() < 1.0)
);
println!(
"{}",
y.iter()
.zip(t.into_iter())
.all(|i| (i.0 - i.1).norm() < 1.0)
);
}
6 changes: 6 additions & 0 deletions contents/cooley_tukey/cooley_tukey.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ For some reason, though, putting code to this transformation really helped me fi
[import:15-74, lang:"asm-x64"](code/asm-x64/fft.s)
{% sample lang="js" %}
[import:3-15, lang:"javascript"](code/javascript/fft.js)
{% sample lang="rs" %}
[import:10-23, lang:"rust"](code/rust/fft.rs)
{% endmethod %}

In this function, we define `n` to be a set of integers from $$0 \rightarrow N-1$$ and arrange them to be a column.
Expand Down Expand Up @@ -138,6 +140,8 @@ In the end, the code looks like:
[import:76-165, lang:"asm-x64"](code/asm-x64/fft.s)
{% sample lang="js" %}
[import:17-39, lang="javascript"](code/javascript/fft.js)
{% sample lang="rs" %}
[import:25-41, lang:"rust"](code/rust/fft.rs)
{% endmethod %}

As a side note, we are enforcing that the array must be a power of 2 for the operation to work.
Expand Down Expand Up @@ -249,6 +253,8 @@ Some rather impressive scratch code was submitted by Jie and can be found here:
[import, lang:"asm-x64"](code/asm-x64/fft.s)
{% sample lang="js" %}
[import, lang:"javascript"](code/javascript/fft.js)
{% sample lang="rs" %}
[import, lang:"rust"](code/rust/fft.rs)
{% endmethod %}

<script>
Expand Down