Page MenuHomec4science

test_fft.cc
No OneTemporary

File Metadata

Created
Thu, Nov 26, 11:00

test_fft.cc

#include "my_types.hh"
#include "fft.hh"
#include <gtest/gtest.h>
#include <fstream>
/*****************************************************************/
TEST(FFT, transform) {
UInt N = 512;
Matrix<complex> m(N);
Real k = 2 * M_PI / N;
for (auto&& entry : index(m)) {
int i = std::get<0>(entry);
int j = std::get<1>(entry);
auto& val = std::get<2>(entry);
val = cos(k * i);
}
Matrix<complex> res = FFT::transform(m);
for (auto&& entry : index(res)) {
int i = std::get<0>(entry);
int j = std::get<1>(entry);
auto& val = std::get<2>(entry);
if (std::abs(val) > 1e-10)
std::cout << i << "," << j << " = " << val << std::endl;
if (i == 1 && j == 0)
ASSERT_NEAR(std::abs(val), N * N / 2, 1e-10);
else if (i == N - 1 && j == 0)
ASSERT_NEAR(std::abs(val), N * N / 2, 1e-10);
else
ASSERT_NEAR(std::abs(val), 0, 1e-10);
}
}
/*****************************************************************/
TEST(FFT, inverse_transform) {
UInt N = 512;
Matrix<complex> m(N);
Real k = 2 * M_PI / N;
for (auto&& entry : index(m)) {
int i = std::get<0>(entry);
int j = std::get<1>(entry);
auto& val = std::get<2>(entry);
val = cos(k * i);
}
Matrix<complex> dft_m = FFT::transform(m);
Matrix<complex> invdft_dft_m = FFT::itransform(dft_m);
for (auto&& entry : index(invdft_dft_m)) {
int i = std::get<0>(entry);
int j = std::get<1>(entry);
auto& val = std::get<2>(entry);
ASSERT_NEAR(val.real(), cos(k*i), 1e-10);
}
}
/*****************************************************************/
TEST(FFT, compute_frequencies){
double tmp;
double val;
UInt N;
// These tests are based on values produced by numpy.fft.fftfreq
// which are saved in txt files
// See the python script fft_generate_test_values.py
/////////////// EVEN TEST ///////////////////////
N = 20;
Matrix<std::complex<int>> even_freqs = FFT::computeFrequencies(N);
std::ifstream in_even("fftfreq_test_values_even.txt");
if (!in_even) {
std::cout << "Cannot open even file.\n";
return;
}
for (int j = 0; j < N; j++) {
for (int i = 0; i < N; i++) {
// // DEBUG:
// std::cout << "(i,j) = (" << i << "," << j << ")" << std::endl;
in_even >> tmp;
val = even_freqs(i,j).real();
ASSERT_NEAR(val, tmp, 1e-10);
}
}
in_even.close();
/////////////// ODD TEST ///////////////////////
N = 19;
Matrix<std::complex<int>> odd_freqs = FFT::computeFrequencies(N);
std::ifstream in_odd("fftfreq_test_values_odd.txt");
if (!in_odd) {
std::cout << "Cannot open odd file.\n";
return;
}
for (int j = 0; j < N; j++) {
for (int i = 0; i < N; i++) {
// // DEBUG:
// std::cout << "(i,j) = (" << i << "," << j << ")" << std::endl;
in_odd >> tmp;
val = odd_freqs(i,j).real();
ASSERT_NEAR(val, tmp, 1e-10);
}
}
in_odd.close();
}

Event Timeline