forked from vedderb/vesc_tool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfftw3wrapper.h
More file actions
97 lines (84 loc) · 2.01 KB
/
fftw3wrapper.h
File metadata and controls
97 lines (84 loc) · 2.01 KB
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
#pragma once
#include <complex>
#include <fftw3.h>
#include <QVector>
#include <ranges>
#include <span>
class FFT {
public:
FFT(int n) : N(n) {
in = (double*)fftw_malloc(sizeof(double) * N);
out = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * (N / 2 + 1));
p = fftw_plan_dft_r2c_1d(N, in, out, FFTW_MEASURE); // or FFTW_ESTIMATE?
}
~FFT() {
fftw_destroy_plan(p);
fftw_free(in);
fftw_free(out);
}
QVector<std::complex<double>> transform(const QVector<double>& input) {
// copy data
std::ranges::copy(input, in);
//for (int i = 0; i < N; ++i) {
// in[i] = input[i];
//}
// perform FFT
fftw_execute(p);
// copy FFT output to QVector
QVector<std::complex<double>> output(N / 2 + 1);
for (int i = 0; i < N / 2 + 1; ++i) {
output[i] = { out[i][0], out[i][1] };
}
return output;
}
static QVector<double> getAbs(std::span<std::complex<double>> input) {
QVector<double> ret(input.size());
auto j = std::begin(ret);
for (auto& i : input) {
*j++ = std::abs(i);
}
return ret;
}
static void applyLowPassFilter(QVector<std::complex<double>>& input, int cutoff_freq) {
using namespace std::complex_literals;
std::ranges::fill(input | std::views::drop(cutoff_freq), 0i);
}
private:
int N;
double* in;
fftw_complex* out;
fftw_plan p;
};
class IFFT {
public:
IFFT(int n) : N(n) {
in = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * (N / 2 + 1));
out = (double*)fftw_malloc(sizeof(double) * N);
p = fftw_plan_dft_c2r_1d(N, in, out, FFTW_MEASURE);
}
~IFFT() {
fftw_destroy_plan(p);
fftw_free(in);
fftw_free(out);
}
QVector<double> transform(const QVector<std::complex<double>>& input) {
// copy data to IFFT input
for (int i = 0; i < (N / 2 + 1); ++i) {
in[i][0] = input[i].real();
in[i][1] = input[i].imag();
}
// perform IFFT
fftw_execute(p);
// copy IFFT output to QVector
QVector<double> output(N);
for (int i = 0; i < N; ++i) {
output[i] = out[i] / N;
}
return output;
}
private:
int N;
fftw_complex* in;
double* out;
fftw_plan p;
};