1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
use rustfft::num_complex::Complex;
use rustfft::num_traits::Zero;
use rustfft::FFTplanner;
use std::error;
use std::fmt;
type Res<T> = Result<T, Box<dyn error::Error>>;
#[derive(Debug)]
pub struct FftError {
desc: String,
}
impl fmt::Display for FftError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.desc)
}
}
impl error::Error for FftError {
fn description(&self) -> &str {
&self.desc
}
}
impl FftError {
pub fn new(desc: &str) -> Self {
FftError {
desc: desc.to_owned(),
}
}
}
pub struct RealToComplex<T> {
sin: Vec<T>,
cos: Vec<T>,
length: usize,
fft: std::sync::Arc<dyn rustfft::FFT<T>>,
buffer_out: Vec<Complex<T>>,
}
pub struct ComplexToReal<T> {
sin: Vec<T>,
cos: Vec<T>,
length: usize,
fft: std::sync::Arc<dyn rustfft::FFT<T>>,
buffer_in: Vec<Complex<T>>,
}
macro_rules! impl_r2c {
($ft:ty) => {
impl RealToComplex<$ft> {
pub fn new(length: usize) -> Res<Self> {
if length % 2 > 0 {
return Err(Box::new(FftError::new("Length must be even")));
}
let buffer_out = vec![Complex::zero(); length / 2 + 1];
let mut sin = Vec::with_capacity(length / 2);
let mut cos = Vec::with_capacity(length / 2);
let pi = std::f64::consts::PI as $ft;
for k in 0..length / 2 {
sin.push((k as $ft * pi / (length / 2) as $ft).sin());
cos.push((k as $ft * pi / (length / 2) as $ft).cos());
}
let mut fft_planner = FFTplanner::<$ft>::new(false);
let fft = fft_planner.plan_fft(length / 2);
Ok(RealToComplex {
sin,
cos,
length,
fft,
buffer_out,
})
}
pub fn process(&mut self, input: &mut [$ft], output: &mut [Complex<$ft>]) -> Res<()> {
if input.len() != self.length {
return Err(Box::new(FftError::new(
format!(
"Wrong length of input, expected {}, got {}",
self.length,
input.len()
)
.as_str(),
)));
}
if output.len() != (self.length / 2 + 1) {
return Err(Box::new(FftError::new(
format!(
"Wrong length of output, expected {}, got {}",
self.length / 2 + 1,
input.len()
)
.as_str(),
)));
}
let fftlen = self.length / 2;
let mut buf_in = unsafe {
let ptr = input.as_mut_ptr() as *mut Complex<$ft>;
let len = input.len();
std::slice::from_raw_parts_mut(ptr, len / 2)
};
self.fft
.process(&mut buf_in, &mut self.buffer_out[0..fftlen]);
self.buffer_out[fftlen] = self.buffer_out[0];
for k in 0..fftlen {
let xr = 0.5
* ((self.buffer_out[k].re + self.buffer_out[fftlen - k].re)
+ self.cos[k]
* (self.buffer_out[k].im + self.buffer_out[fftlen - k].im)
- self.sin[k]
* (self.buffer_out[k].re - self.buffer_out[fftlen - k].re));
let xi = 0.5
* ((self.buffer_out[k].im - self.buffer_out[fftlen - k].im)
- self.sin[k]
* (self.buffer_out[k].im + self.buffer_out[fftlen - k].im)
- self.cos[k]
* (self.buffer_out[k].re - self.buffer_out[fftlen - k].re));
output[k] = Complex::new(xr, xi);
}
output[fftlen] = Complex::new(self.buffer_out[0].re - self.buffer_out[0].im, 0.0);
Ok(())
}
}
};
}
impl_r2c!(f64);
impl_r2c!(f32);
macro_rules! impl_c2r {
($ft:ty) => {
impl ComplexToReal<$ft> {
pub fn new(length: usize) -> Res<Self> {
if length % 2 > 0 {
return Err(Box::new(FftError::new("Length must be even")));
}
let buffer_in = vec![Complex::zero(); length / 2];
let mut sin = Vec::with_capacity(length / 2);
let mut cos = Vec::with_capacity(length / 2);
let pi = std::f64::consts::PI as $ft;
for k in 0..length / 2 {
sin.push((k as $ft * pi / (length / 2) as $ft).sin());
cos.push((k as $ft * pi / (length / 2) as $ft).cos());
}
let mut fft_planner = FFTplanner::<$ft>::new(true);
let fft = fft_planner.plan_fft(length / 2);
Ok(ComplexToReal {
sin,
cos,
length,
fft,
buffer_in,
})
}
pub fn process(&mut self, input: &[Complex<$ft>], output: &mut [$ft]) -> Res<()> {
if input.len() != (self.length / 2 + 1) {
return Err(Box::new(FftError::new(
format!(
"Wrong length of input, expected {}, got {}",
self.length / 2 + 1,
input.len()
)
.as_str(),
)));
}
if output.len() != self.length {
return Err(Box::new(FftError::new(
format!(
"Wrong length of output, expected {}, got {}",
self.length,
input.len()
)
.as_str(),
)));
}
let fftlen = self.length / 2;
for k in 0..fftlen {
let xr = 0.5
* ((input[k].re + input[fftlen - k].re)
- self.cos[k] * (input[k].im + input[fftlen - k].im)
- self.sin[k] * (input[k].re - input[fftlen - k].re));
let xi = 0.5
* ((input[k].im - input[fftlen - k].im)
+ self.cos[k] * (input[k].re - input[fftlen - k].re)
- self.sin[k] * (input[k].im + input[fftlen - k].im));
self.buffer_in[k] = Complex::new(xr, xi);
}
let mut buf_out = unsafe {
let ptr = output.as_mut_ptr() as *mut Complex<$ft>;
let len = output.len();
std::slice::from_raw_parts_mut(ptr, len / 2)
};
self.fft.process(&mut self.buffer_in, &mut buf_out);
Ok(())
}
}
};
}
impl_c2r!(f64);
impl_c2r!(f32);
#[cfg(test)]
mod tests {
use crate::{ComplexToReal, RealToComplex};
use rustfft::num_complex::Complex;
use rustfft::num_traits::Zero;
use rustfft::FFTplanner;
fn compare_complex(a: &[Complex<f64>], b: &[Complex<f64>], tol: f64) -> bool {
a.iter().zip(b.iter()).fold(true, |eq, (val_a, val_b)| {
eq && (val_a.re - val_b.re).abs() < tol && (val_a.im - val_b.im).abs() < tol
})
}
fn compare_f64(a: &[f64], b: &[f64], tol: f64) -> bool {
a.iter()
.zip(b.iter())
.fold(true, |eq, (val_a, val_b)| eq && (val_a - val_b).abs() < tol)
}
#[test]
fn real_to_complex() {
let mut indata = vec![0.0f64; 256];
indata[0] = 1.0;
indata[3] = 0.5;
let mut indata_c = indata
.iter()
.map(|val| Complex::from(val))
.collect::<Vec<Complex<f64>>>();
let mut fft_planner = FFTplanner::<f64>::new(false);
let fft = fft_planner.plan_fft(256);
let mut r2c = RealToComplex::<f64>::new(256).unwrap();
let mut out_a: Vec<Complex<f64>> = vec![Complex::zero(); 129];
let mut out_b: Vec<Complex<f64>> = vec![Complex::zero(); 256];
fft.process(&mut indata_c, &mut out_b);
r2c.process(&mut indata, &mut out_a).unwrap();
assert!(compare_complex(&out_a[0..129], &out_b[0..129], 1.0e-9));
}
#[test]
fn complex_to_real() {
let mut indata = vec![Complex::<f64>::zero(); 256];
indata[0] = Complex::new(1.0, 0.0);
indata[1] = Complex::new(1.0, 0.4);
indata[255] = Complex::new(1.0, -0.4);
indata[3] = Complex::new(0.3, 0.2);
indata[253] = Complex::new(0.3, -0.2);
let mut fft_planner = FFTplanner::<f64>::new(true);
let fft = fft_planner.plan_fft(256);
let mut c2r = ComplexToReal::<f64>::new(256).unwrap();
let mut out_a: Vec<f64> = vec![0.0; 256];
let mut out_b: Vec<Complex<f64>> = vec![Complex::zero(); 256];
c2r.process(&indata[0..129], &mut out_a).unwrap();
fft.process(&mut indata, &mut out_b);
let out_b_r = out_b.iter().map(|val| 0.5 * val.re).collect::<Vec<f64>>();
assert!(compare_f64(&out_a, &out_b_r, 1.0e-9));
}
#[test]
fn real_to_complex_odd() {
let mut indata = vec![0.0f64; 254];
indata[0] = 1.0;
indata[3] = 0.5;
let mut indata_c = indata
.iter()
.map(|val| Complex::from(val))
.collect::<Vec<Complex<f64>>>();
let mut fft_planner = FFTplanner::<f64>::new(false);
let fft = fft_planner.plan_fft(254);
let mut r2c = RealToComplex::<f64>::new(254).unwrap();
let mut out_a: Vec<Complex<f64>> = vec![Complex::zero(); 128];
let mut out_b: Vec<Complex<f64>> = vec![Complex::zero(); 254];
fft.process(&mut indata_c, &mut out_b);
r2c.process(&mut indata, &mut out_a).unwrap();
assert!(compare_complex(&out_a[0..128], &out_b[0..128], 1.0e-9));
}
#[test]
fn complex_to_real_odd() {
let mut indata = vec![Complex::<f64>::zero(); 254];
indata[0] = Complex::new(1.0, 0.0);
indata[1] = Complex::new(1.0, 0.4);
indata[253] = Complex::new(1.0, -0.4);
indata[3] = Complex::new(0.3, 0.2);
indata[251] = Complex::new(0.3, -0.2);
let mut fft_planner = FFTplanner::<f64>::new(true);
let fft = fft_planner.plan_fft(254);
let mut c2r = ComplexToReal::<f64>::new(254).unwrap();
let mut out_a: Vec<f64> = vec![0.0; 254];
let mut out_b: Vec<Complex<f64>> = vec![Complex::zero(); 254];
c2r.process(&indata[0..128], &mut out_a).unwrap();
fft.process(&mut indata, &mut out_b);
let out_b_r = out_b.iter().map(|val| 0.5 * val.re).collect::<Vec<f64>>();
assert!(compare_f64(&out_a, &out_b_r, 1.0e-9));
}
}