Correlation 4.10.0
An Analysis Tool for Liquids and for Amorphous Solids
Loading...
Searching...
No Matches
FFTUtils.hpp
Go to the documentation of this file.
1
8
9#pragma once
10
11#include <complex>
12#include <stdexcept>
13#include <vector>
14
15#include "math/Precision.hpp"
16
17#ifdef CORRELATION_USE_FFTW3
18#include <fftw3.h>
19#include <mutex>
20#include <unordered_map>
21#elifdef CORRELATION_USE_MKL
22#include <mkl_dfti.h>
23#include <unordered_map>
24#else
25#include "math/Constants.hpp"
26#endif
27
28namespace correlation::math {
29
34[[nodiscard]] inline bool isGoodFFTSize(size_t n) {
35 if (n == 0) {
36 return false;
37 }
38 while (n % 2 == 0) {
39 n /= 2;
40 }
41 while (n % 3 == 0) {
42 n /= 3;
43 }
44 while (n % 5 == 0) {
45 n /= 5;
46 }
47 return n == 1;
48}
49
53[[nodiscard]] inline size_t findNextGoodFFTSize(size_t target) {
54#if defined(CORRELATION_USE_FFTW3) || defined(CORRELATION_USE_MKL)
55 while (!isGoodFFTSize(target)) {
56 target++;
57 }
58 return target;
59#else
60 // For hand-coded Cooley-Tukey, we must pad to the next power of two
61 size_t len = 1;
62 while (len < target) {
63 len <<= 1;
64 }
65 return len;
66#endif
67}
68
69#ifdef CORRELATION_USE_FFTW3
70
75struct FFTWPlanCache {
76 std::unordered_map<size_t, fftw_plan> forward_plans;
77 std::unordered_map<size_t, fftw_plan> backward_plans;
78
79 // Rule of Five: Delete copy and move operations to prevent double-destruction of fftw_plans
80 FFTWPlanCache() = default;
81 FFTWPlanCache(const FFTWPlanCache &) = delete;
82 FFTWPlanCache &operator=(const FFTWPlanCache &) = delete;
83 FFTWPlanCache(FFTWPlanCache &&) = delete;
84 FFTWPlanCache &operator=(FFTWPlanCache &&) = delete;
85
86 ~FFTWPlanCache() {
87 for (auto &[key, plan] : forward_plans) {
88 fftw_destroy_plan(plan);
89 }
90 for (auto &[key, plan] : backward_plans) {
91 fftw_destroy_plan(plan);
92 }
93 }
94};
95
96inline void computeFFT(std::vector<std::complex<double>> &data, bool invert) {
97 const size_t size = data.size();
98 if (size == 0) {
99 return;
100 }
101
102 thread_local FFTWPlanCache cache;
103 auto &plans = invert ? cache.backward_plans : cache.forward_plans;
104 auto iterator = plans.find(size);
105 fftw_plan plan = nullptr;
106 auto *fftw_data = reinterpret_cast<fftw_complex *>(data.data());
107
108 if (iterator != plans.end()) {
109 plan = iterator->second;
110 } else {
111 static std::mutex planner_mutex;
112 const std::scoped_lock lock(planner_mutex);
113
114 plan = fftw_plan_dft_1d(static_cast<int>(size), fftw_data, fftw_data,
115 invert ? FFTW_BACKWARD : FFTW_FORWARD, FFTW_ESTIMATE);
116 if (plan == nullptr) {
117 throw std::runtime_error("Failed to create FFTW plan for size " + std::to_string(size));
118 }
119 plans[size] = plan;
120 }
121
122 fftw_execute_dft(plan, fftw_data, fftw_data);
123
124 if (invert) {
125 const double scale = 1.0 / static_cast<double>(size);
126 for (auto &val : data) {
127 val *= scale;
128 }
129 }
130}
131
132#elifdef CORRELATION_USE_MKL
133
138struct MKLDescriptorCache {
139 std::unordered_map<size_t, DFTI_DESCRIPTOR_HANDLE>
140 forward_handles;
141 std::unordered_map<size_t, DFTI_DESCRIPTOR_HANDLE>
142 backward_handles;
143
144 ~MKLDescriptorCache() {
145 for (auto &p : forward_handles) {
146 DftiFreeDescriptor(&p.second);
147 }
148 for (auto &p : backward_handles) {
149 DftiFreeDescriptor(&p.second);
150 }
151 }
152};
153
154inline void computeFFT(std::vector<std::complex<double>> &data, bool invert) {
155 size_t size = data.size();
156 if (size == 0) {
157 return;
158 }
159
160 thread_local MKLDescriptorCache cache;
161 auto &handles = invert ? cache.backward_handles : cache.forward_handles;
162 auto it = handles.find(size);
163 DFTI_DESCRIPTOR_HANDLE handle = nullptr;
164
165 if (it != handles.end()) {
166 handle = it->second;
167 } else {
168 MKL_LONG status =
169 DftiCreateDescriptor(&handle, DFTI_DOUBLE, DFTI_COMPLEX, 1, static_cast<MKL_LONG>(size));
170 if (status != DFTI_NO_ERROR) {
171 throw std::runtime_error("MKL DftiCreateDescriptor failed");
172 }
173 if (invert) {
174 double scale = 1.0 / static_cast<double>(size);
175 DftiSetValue(handle, DFTI_BACKWARD_SCALE, scale);
176 }
177 status = DftiCommitDescriptor(handle);
178 if (status != DFTI_NO_ERROR) {
179 DftiFreeDescriptor(&handle);
180 throw std::runtime_error("MKL DftiCommitDescriptor failed");
181 }
182 handles[size] = handle;
183 }
184
185 MKL_LONG status;
186 if (invert) {
187 status = DftiComputeBackward(handle, data.data());
188 } else {
189 status = DftiComputeForward(handle, data.data());
190 }
191
192 if (status != DFTI_NO_ERROR) {
193 throw std::runtime_error("MKL DFTI computation failed");
194 }
195}
196
197#else
198
206template <typename T = double>
207inline void computeFFT(std::vector<std::complex<T>> &data, bool invert) {
208 size_t size = data.size();
209 if (size == 0) {
210 return;
211 }
212
213 if ((size & (size - 1)) != 0) {
214 throw std::invalid_argument("FFT length must be a power of 2");
215 }
216
217 // Bit-reversal permutation (Optimized)
218 for (size_t i = 1, j = 0; i < size; i++) {
219 size_t bit = size >> 1;
220 for (; (j & bit) != 0; bit >>= 1) {
221 j ^= bit;
222 }
223 j ^= bit;
224 if (i < j) {
225 std::swap(data[i], data[j]);
226 }
227 }
228
229 constexpr double double_two_pi = 6.283185307179586476925286766559005768;
230 for (size_t len = 2; len <= size; len <<= 1) {
231 T angle = static_cast<T>(double_two_pi / static_cast<double>(len) * (invert ? -1 : 1));
232 std::complex<T> wlen(std::cos(angle), std::sin(angle));
233 for (size_t i = 0; i < size; i += len) {
234 std::complex<T> twiddle(static_cast<T>(1.0), static_cast<T>(0.0));
235 for (size_t j = 0; j < len / 2; j++) {
236 std::complex<T> even_val = data[i + j];
237 std::complex<T> odd_val = data[i + j + len / 2] * twiddle;
238 data[i + j] = even_val + odd_val;
239 data[i + j + len / 2] = even_val - odd_val;
240 twiddle *= wlen;
241 }
242 }
243 }
244
245 if (invert) {
246 for (auto &val : data) {
247 val /= static_cast<T>(size);
248 }
249 }
250}
251#endif
252
262template <typename T = real_t>
263[[nodiscard]] inline std::vector<T> autocorrelate(const std::vector<T> &signal,
264 std::vector<std::complex<T>> &workspace) {
265 const size_t size = signal.size();
266 if (size == 0) {
267 return {};
268 }
269
270 const size_t len = findNextGoodFFTSize(2 * size - 1);
271
272 // Reuse caller-supplied workspace; only reallocates when length grows.
273 workspace.assign(len, {static_cast<T>(0.0), static_cast<T>(0.0)});
274 for (size_t i = 0; i < size; ++i) {
275 workspace[i] = {signal[i], static_cast<T>(0.0)};
276 }
277
278 // Convert to std::vector<std::complex<double>> for external FFT library computation
279 std::vector<std::complex<double>> double_ws(len);
280 for (size_t i = 0; i < len; ++i) {
281 double_ws[i] = {static_cast<double>(workspace[i].real()),
282 static_cast<double>(workspace[i].imag())};
283 }
284
285 computeFFT(double_ws, false);
286
287 // In-place |X[k]|² — no intermediate vector needed.
288 for (size_t i = 0; i < len; ++i) {
289 const double real_part = double_ws[i].real();
290 const double imag_part = double_ws[i].imag();
291 double_ws[i] = {real_part * real_part + imag_part * imag_part, 0.0};
292 }
293
294 computeFFT(double_ws, true);
295
296 std::vector<T> result(size);
297 for (size_t i = 0; i < size; ++i) {
298 result[i] = static_cast<T>(double_ws[i].real());
299 workspace[i] = {static_cast<T>(double_ws[i].real()), static_cast<T>(double_ws[i].imag())};
300 }
301 return result;
302}
303
312template <typename T = real_t>
313[[nodiscard]] inline std::vector<T> autocorrelate(const std::vector<T> &signal) {
314 std::vector<std::complex<T>> workspace;
315 return autocorrelate(signal, workspace);
316}
317
318} // namespace correlation::math
Mathematical and physical constants for the Correlation tool.
Floating point precision type definitions for Correlation.
Defines universal mathematical and physical constants.
size_t findNextGoodFFTSize(size_t target)
Finds the next "good" FFT size >= target.
Definition FFTUtils.hpp:53
std::vector< T > autocorrelate(const std::vector< T > &signal, std::vector< std::complex< T > > &workspace)
Computes the autocorrelation of a 1D real sequence using FFT.
Definition FFTUtils.hpp:263
void computeFFT(std::vector< std::complex< T > > &data, bool invert)
Simple Radix-2 Cooley-Tukey FFT implementation with bit-reversal optimization.
Definition FFTUtils.hpp:207
constexpr Matrix3< T > invert(const Matrix3< T > &matrix)
Computes the inverse of a 3x3 matrix.
Definition LinearAlgebra.hpp:571
bool isGoodFFTSize(size_t n)
Helper to check if a size is a product of small prime factors (2, 3, 5). Highly optimized for FFTW3 a...
Definition FFTUtils.hpp:34