// FFT #include "fft.h" #include "util.h" #include #include #include #include #include #include #include #include #include #include RIT::FFT::FFT(int size, bool halfOnly): mSize(size), order(size), expLUT(size/2), mFlagHalfOnly(halfOnly) { if (!is_power_of_two(size)) throw std::invalid_argument("Size must be a power of two"); // reorder LUT for (int i = 0; i < size; ++i) { order[i] = RIT::bitreverse(i, size); } // exp LUT for (int i = 0; i < size / 2; ++i) { expLUT[i] = exp(std::complex(0,-2.*M_PI*i/size)); } } std::vector> RIT::FFT::operator()(const std::vector> &v) const { if (v.size() != mSize) throw std::length_error("Bad input size"); std::vector> result; reorder(v, result); if (mFlagHalfOnly) { fft_half(std::begin(result), mSize); result.resize(mSize/2); } else fft_recursive(std::begin(result), mSize); return result; } RIT::FFT& RIT::FFT::SetHalfOnly(bool enable) { mFlagHalfOnly = enable; return *this; } void RIT::FFT::reorder(const std::vector>& src, std::vector>& dst) const { int size = src.size(); dst.resize(size); for (int i = 0; i < size; ++i) { dst[order[i]] = src[i]; } } // N must be a power-of-2, or bad things will happen. // Currently no check for this condition. // // N input samples in X[] are FFT'd and results left in X[]. // Because of Nyquist theorem, N samples means // only first N/2 FFT results in X[] are the answer. // (upper half of X[] is a reflection with no new information). void RIT::FFT::fft_recursive(std::vector>::iterator X, int N) const { if(N > 2) { fft_recursive(X, N/2); // recurse even items fft_recursive(X+N/2, N/2); // recurse odd items } // combine results of two half recursions for(int k=0; k e = X[k ]; // even std::complex o = X[k+N/2]; // odd // w is the "twiddle-factor" std::complex w = expLUT[k * mSize / N]; X[k ] = e + w * o; X[k+N/2] = e - w * o; } } // Same as fft_recursive, but results in only half the result due to symmetry in real input void RIT::FFT::fft_half(std::vector>::iterator X, int N) const { if(N > 2) { fft_recursive(X, N/2); // recurse even items fft_recursive(X+N/2, N/2); // recurse odd items } // combine results of two half recursions for(int k=0; k (*)(const std::complex&); Impl(int size): mFft(std::make_shared(size)) {} Impl(std::shared_ptr fft): mFft(fft) {} ~Impl(){} std::shared_ptr mFft; }; RIT::IFFT::IFFT(int size): mImpl(std::make_unique(size)) { } RIT::IFFT::IFFT(std::shared_ptr fft): mImpl(std::make_unique(fft)) { } RIT::IFFT::~IFFT() { } std::vector> RIT::IFFT::operator()(const std::vector> &v) const { std::vector> input(v.size()); std::transform(std::begin(v), std::end(v), std::begin(input), static_cast(std::conj)); auto result = (*mImpl->mFft)(input); const double factor = 1.0 / v.size(); std::transform(std::begin(result), std::end(result), std::begin(result), [=](const auto& x){return std::conj(x) * factor;}); return result; }