DDC 0.11.0
Loading...
Searching...
No Matches
fft.hpp
1// Copyright (C) The DDC development team, see COPYRIGHT.md file
2//
3// SPDX-License-Identifier: MIT
4
5#pragma once
6
7#include <cassert>
8#include <type_traits>
9#include <utility>
10
11#include <ddc/ddc.hpp>
12
13#include <KokkosFFT.hpp>
14#include <Kokkos_Core.hpp>
15
16namespace ddc {
17
18/**
19 * @brief A templated tag representing a continuous dimension in the Fourier space associated to the original continuous dimension.
20 *
21 * @tparam The tag representing the original dimension.
22 */
23template <typename Dim>
24struct Fourier;
25
26/**
27 * @brief A named argument to choose the direction of the FFT.
28 *
29 * @see kwArgsImpl, kwArgs_fft
30 */
31enum class FFT_Direction {
32 FORWARD, ///< Forward, corresponds to direct FFT up to normalization
33 BACKWARD ///< Backward, corresponds to inverse FFT up to normalization
34};
35
36/**
37 * @brief A named argument to choose the type of normalization of the FFT.
38 *
39 * @see kwArgsImpl, kwArgs_fft
40 */
41enum class FFT_Normalization {
42 OFF, ///< No normalization. Un-normalized FFT is sum_j f(x_j)*e^-ikx_j
43 FORWARD, ///< Multiply by 1/N for forward FFT, no normalization for backward FFT
44 BACKWARD, ///< No normalization for forward FFT, multiply by 1/N for backward FFT
45 ORTHO, ///< Multiply by 1/sqrt(N)
46 FULL /**<
47 * Multiply by dx/sqrt(2*pi) for forward FFT and dk/sqrt(2*pi) for backward
48 * FFT. It is aligned with the usual definition of the (continuous) Fourier transform
49 * 1/sqrt(2*pi)*int f(x)*e^-ikx*dx, and thus may be relevant for spectral analysis applications.
50 */
51};
52
53} // namespace ddc
54
55namespace ddc::detail::fft {
56
57template <typename T>
58struct RealType
59{
60 using type = T;
61};
62
63template <typename T>
64struct RealType<Kokkos::complex<T>>
65{
66 using type = T;
67};
68
69template <typename T>
70using real_type_t = typename RealType<T>::type;
71
72// is_complex : trait to determine if type is Kokkos::complex<something>
73template <typename T>
74struct is_complex : std::false_type
75{
76};
77
78template <typename T>
79struct is_complex<Kokkos::complex<T>> : std::true_type
80{
81};
82
83template <typename T>
84constexpr bool is_complex_v = is_complex<T>::value;
85
86/*
87 * @brief A structure embedding the configuration of the impl FFT function: direction and type of normalization.
88 *
89 * @see FFT_impl
90 */
91struct KwArgsImpl
92{
94 direction; // Only effective for C2C transform and for normalization BACKWARD and FORWARD
95 ddc::FFT_Normalization normalization;
96};
97
98template <typename... DDimX>
99KokkosFFT::axis_type<sizeof...(DDimX)> axes()
100{
101 return KokkosFFT::axis_type<sizeof...(DDimX)> {
102 static_cast<int>(ddc::type_seq_rank_v<DDimX, ddc::detail::TypeSeq<DDimX...>>)...};
103}
104
105KokkosFFT::Normalization ddc_fft_normalization_to_kokkos_fft(
106 FFT_Normalization ddc_fft_normalization);
107
108template <class T>
109class ScaleFn
110{
111 T m_coef;
112
113public:
114 explicit ScaleFn(T coef) noexcept : m_coef(std::move(coef)) {}
115
116 template <class U>
117 [[nodiscard]] KOKKOS_FUNCTION U operator()(U const& value) const noexcept
118 {
119 return m_coef * value;
120 }
121};
122
123template <class DDim>
124Real forward_full_norm_coef(DiscreteDomain<DDim> const& ddom) noexcept
125{
126 return rlength(ddom) / Kokkos::sqrt(2 * Kokkos::numbers::pi_v<Real>)
127 / (ddom.extents() - 1).value();
128}
129
130template <class DDim>
131Real backward_full_norm_coef(DiscreteDomain<DDim> const& ddom) noexcept
132{
133 return 1 / (forward_full_norm_coef(ddom) * ddom.extents().value());
134}
135
136/// @brief Core internal function to perform the FFT.
137template <
138 typename Tin,
139 typename Tout,
140 typename ExecSpace,
141 typename MemorySpace,
142 typename LayoutIn,
143 typename LayoutOut,
144 typename... DDimIn,
145 typename... DDimOut>
146void impl(
147 ExecSpace const& exec_space,
148 ddc::ChunkSpan<Tin, ddc::DiscreteDomain<DDimIn...>, LayoutIn, MemorySpace> const& in,
149 ddc::ChunkSpan<Tout, ddc::DiscreteDomain<DDimOut...>, LayoutOut, MemorySpace> const& out,
150 KwArgsImpl const& kwargs)
151{
152 static_assert(
153 std::is_same_v<real_type_t<Tin>, float> || std::is_same_v<real_type_t<Tin>, double>,
154 "Base type of Tin (and Tout) must be float or double.");
155 static_assert(
156 std::is_same_v<real_type_t<Tin>, real_type_t<Tout>>,
157 "Types Tin and Tout must be based on same type (float or double)");
158 static_assert(
159 Kokkos::SpaceAccessibility<ExecSpace, MemorySpace>::accessible,
160 "MemorySpace has to be accessible for ExecutionSpace.");
161
162 Kokkos::View<
163 ddc::detail::mdspan_to_kokkos_element_t<Tin, sizeof...(DDimIn)>,
164 ddc::detail::mdspan_to_kokkos_layout_t<LayoutIn>,
165 MemorySpace> const in_view
166 = in.allocation_kokkos_view();
167 Kokkos::View<
168 ddc::detail::mdspan_to_kokkos_element_t<Tout, sizeof...(DDimIn)>,
169 ddc::detail::mdspan_to_kokkos_layout_t<LayoutOut>,
170 MemorySpace> const out_view
171 = out.allocation_kokkos_view();
172 KokkosFFT::Normalization const kokkos_fft_normalization
173 = ddc_fft_normalization_to_kokkos_fft(kwargs.normalization);
174
175 // C2C
176 if constexpr (std::is_same_v<Tin, Tout>) {
177 if (kwargs.direction == ddc::FFT_Direction::FORWARD) {
178 KokkosFFT::
179 fftn(exec_space,
180 in_view,
181 out_view,
182 axes<DDimIn...>(),
183 kokkos_fft_normalization);
184 } else {
185 KokkosFFT::
186 ifftn(exec_space,
187 in_view,
188 out_view,
189 axes<DDimIn...>(),
190 kokkos_fft_normalization);
191 }
192 // R2C & C2R
193 } else {
194 if constexpr (is_complex_v<Tout>) {
195 assert(kwargs.direction == ddc::FFT_Direction::FORWARD);
196 KokkosFFT::
197 rfftn(exec_space,
198 in_view,
199 out_view,
200 axes<DDimIn...>(),
201 kokkos_fft_normalization);
202 } else {
203 assert(kwargs.direction == ddc::FFT_Direction::BACKWARD);
204 KokkosFFT::
205 irfftn(exec_space,
206 in_view,
207 out_view,
208 axes<DDimIn...>(),
209 kokkos_fft_normalization);
210 }
211 }
212
213 // The FULL normalization is mesh-dependant and thus handled by DDC
214 if (kwargs.normalization == ddc::FFT_Normalization::FULL) {
215 Real norm_coef;
216 if (kwargs.direction == ddc::FFT_Direction::FORWARD) {
217 DiscreteDomain<DDimIn...> const ddom_in = in.domain();
218 norm_coef = (forward_full_norm_coef(DiscreteDomain<DDimIn>(ddom_in)) * ...);
219 } else {
220 DiscreteDomain<DDimOut...> const ddom_out = out.domain();
221 norm_coef = (backward_full_norm_coef(DiscreteDomain<DDimOut>(ddom_out)) * ...);
222 }
223
224 ddc::parallel_transform(exec_space, out, ScaleFn<real_type_t<Tout>>(norm_coef));
225 }
226}
227
228} // namespace ddc::detail::fft
229
230namespace ddc {
231
232/**
233 * @brief Initialize a Fourier discrete dimension.
234 *
235 * Initialize the (1D) discrete space representing the Fourier discrete dimension associated
236 * to the (1D) mesh passed as argument. It is a N-periodic PeriodicSampling with a periodic window of width 2*pi/dx.
237 *
238 * This value comes from the Nyquist-Shannon theorem: the period of the spectral domain is N*dk = 2*pi/dx.
239 * Adding to this the relations dx = (xmax-xmin)/(N-1), and dk = (kmax-kmin)/(N-1), we get kmax-kmin = 2*pi*(N-1)^2/N/(xmax-xmin),
240 * which is used in the implementation (xmax, xmin, kmin and kmax are the centers of lower and upper cells inside a single period of the meshes).
241 *
242 * @tparam DDimFx A PeriodicSampling representing the Fourier discrete dimension.
243 * @tparam DDimX The type of the original discrete dimension.
244 *
245 * @param x_mesh The DiscreteDomain representing the (1D) original mesh.
246 *
247 * @return The initialized Impl representing the discrete Fourier space.
248 *
249 * @see PeriodicSampling
250 */
251template <typename DDimFx, typename DDimX>
252typename DDimFx::template Impl<DDimFx, Kokkos::HostSpace> init_fourier_space(
253 ddc::DiscreteDomain<DDimX> x_mesh)
254{
255 static_assert(
256 is_uniform_point_sampling_v<DDimX>,
257 "DDimX dimension must derive from UniformPointSampling");
258 static_assert(
259 is_periodic_sampling_v<DDimFx>,
260 "DDimFx dimension must derive from PeriodicSampling");
261 using CDimFx = typename DDimFx::continuous_dimension_type;
262 using CDimX = typename DDimX::continuous_dimension_type;
263 static_assert(
264 std::is_same_v<CDimFx, ddc::Fourier<CDimX>>,
265 "DDimX and DDimFx dimensions must be defined over the same continuous dimension");
266
267 DiscreteVectorElement const nx = get<DDimX>(x_mesh.extents());
268 double const lx = ddc::rlength(x_mesh);
269 auto [impl, ddom] = DDimFx::template init<DDimFx>(
270 ddc::Coordinate<CDimFx>(0),
271 ddc::Coordinate<CDimFx>(2 * (nx - 1) * (nx - 1) / (nx * lx) * Kokkos::numbers::pi),
272 ddc::DiscreteVector<DDimFx>(nx),
273 ddc::DiscreteVector<DDimFx>(nx));
274 return std::move(impl);
275}
276
277/**
278 * @brief Get the Fourier mesh.
279 *
280 * Compute the Fourier (or spectral) mesh on which the Discrete Fourier Transform of a
281 * discrete function is defined.
282 *
283 * @param x_mesh The DiscreteDomain representing the original mesh.
284 * @param C2C A flag indicating if a complex-to-complex DFT is going to be performed. Indeed,
285 * in this case the two meshes have same number of points, whereas for real-to-complex
286 * or complex-to-real DFT, each complex value of the Fourier-transformed function contains twice more
287 * information, and thus only half (actually Nx*Ny*(Nz/2+1) for 3D R2C FFT to take in account mode 0)
288 * values are needed (cf. DFT conjugate symmetry property for more information about this).
289 *
290 * @return The domain representing the Fourier mesh.
291 */
292template <typename... DDimFx, typename... DDimX>
293ddc::DiscreteDomain<DDimFx...> fourier_mesh(ddc::DiscreteDomain<DDimX...> x_mesh, bool C2C)
294{
295 static_assert(
296 (is_uniform_point_sampling_v<DDimX> && ...),
297 "DDimX dimensions should derive from UniformPointSampling");
298 static_assert(
299 (is_periodic_sampling_v<DDimFx> && ...),
300 "DDimFx dimensions should derive from PeriodicPointSampling");
301 ddc::DiscreteVector<DDimX...> extents = x_mesh.extents();
302 if (!C2C) {
303 detail::array(extents).back() = detail::array(extents).back() / 2 + 1;
304 }
305 return ddc::DiscreteDomain<DDimFx...>(ddc::DiscreteDomain<DDimFx>(
306 ddc::DiscreteElement<DDimFx>(0),
307 ddc::DiscreteVector<DDimFx>(get<DDimX>(extents)))...);
308}
309
310/**
311 * @brief A structure embedding the configuration of the exposed FFT function with the type of normalization.
312 *
313 * @see fft, ifft
314 */
315struct kwArgs_fft
316{
318 normalization; ///< Enum member to identify the type of normalization performed
319};
320
321/**
322 * @brief Perform a direct Fast Fourier Transform.
323 *
324 * Compute the discrete Fourier transform of a function using the specialized implementation for the Kokkos::ExecutionSpace
325 * of the FFT algorithm.
326 *
327 * @tparam Tin The type of the input elements (float, Kokkos::complex<float>, double or Kokkos::complex<double>).
328 * @tparam Tout The type of the output elements (Kokkos::complex<float> or Kokkos::complex<double>).
329 * @tparam DDimFx... The parameter pack of the Fourier discrete dimensions.
330 * @tparam DDimX... The parameter pack of the original discrete dimensions.
331 * @tparam ExecSpace The type of the Kokkos::ExecutionSpace on which the FFT is performed. It determines which specialized
332 * backend is used (ie. fftw, cuFFT...).
333 * @tparam MemorySpace The type of the Kokkos::MemorySpace on which are stored the input and output discrete functions.
334 * @tparam LayoutIn The layout of the Chunkspan representing the input discrete function.
335 * @tparam LayoutOut The layout of the Chunkspan representing the output discrete function.
336 *
337 * @param exec_space The Kokkos::ExecutionSpace on which the FFT is performed.
338 * @param out The output discrete function, represented as a ChunkSpan storing values on a spectral mesh.
339 * @param in The input discrete function, represented as a ChunkSpan storing values on a mesh.
340 * @param kwargs The kwArgs_fft configuring the FFT.
341 */
342template <
343 typename Tin,
344 typename Tout,
345 typename... DDimFx,
346 typename... DDimX,
347 typename ExecSpace,
348 typename MemorySpace,
349 typename LayoutIn,
350 typename LayoutOut>
351void fft(
352 ExecSpace const& exec_space,
353 ddc::ChunkSpan<Tout, ddc::DiscreteDomain<DDimFx...>, LayoutOut, MemorySpace> out,
354 ddc::ChunkSpan<Tin, ddc::DiscreteDomain<DDimX...>, LayoutIn, MemorySpace> in,
356{
357 static_assert(
358 std::is_same_v<LayoutIn, Kokkos::layout_right>
359 && std::is_same_v<LayoutOut, Kokkos::layout_right>,
360 "Layouts must be right-handed");
361 static_assert(
362 (is_uniform_point_sampling_v<DDimX> && ...),
363 "DDimX dimensions should derive from UniformPointSampling");
364 static_assert(
365 (is_periodic_sampling_v<DDimFx> && ...),
366 "DDimFx dimensions should derive from PeriodicPointSampling");
367
368 ddc::detail::fft::
369 impl(exec_space, in, out, {ddc::FFT_Direction::FORWARD, kwargs.normalization});
370}
371
372/**
373 * @brief Perform an inverse Fast Fourier Transform.
374 *
375 * Compute the inverse discrete Fourier transform of a spectral function using the specialized implementation for the Kokkos::ExecutionSpace
376 * of the iFFT algorithm.
377 *
378 * @warning C2R iFFT does NOT preserve input.
379 *
380 * @tparam Tin The type of the input elements (Kokkos::complex<float> or Kokkos::complex<double>).
381 * @tparam Tout The type of the output elements (float, Kokkos::complex<float>, double or Kokkos::complex<double>).
382 * @tparam DDimX... The parameter pack of the original discrete dimensions.
383 * @tparam DDimFx... The parameter pack of the Fourier discrete dimensions.
384 * @tparam ExecSpace The type of the Kokkos::ExecutionSpace on which the iFFT is performed. It determines which specialized
385 * backend is used (ie. fftw, cuFFT...).
386 * @tparam MemorySpace The type of the Kokkos::MemorySpace on which are stored the input and output discrete functions.
387 * @tparam LayoutIn The layout of the Chunkspan representing the input discrete function.
388 * @tparam LayoutOut The layout of the Chunkspan representing the output discrete function.
389 *
390 * @param exec_space The Kokkos::ExecutionSpace on which the iFFT is performed.
391 * @param out The output discrete function, represented as a ChunkSpan storing values on a mesh.
392 * @param in The input discrete function, represented as a ChunkSpan storing values on a spectral mesh.
393 * @param kwargs The kwArgs_fft configuring the iFFT.
394 */
395template <
396 typename Tin,
397 typename Tout,
398 typename... DDimX,
399 typename... DDimFx,
400 typename ExecSpace,
401 typename MemorySpace,
402 typename LayoutIn,
403 typename LayoutOut>
404void ifft(
405 ExecSpace const& exec_space,
406 ddc::ChunkSpan<Tout, ddc::DiscreteDomain<DDimX...>, LayoutOut, MemorySpace> out,
407 ddc::ChunkSpan<Tin, ddc::DiscreteDomain<DDimFx...>, LayoutIn, MemorySpace> in,
409{
410 static_assert(
411 std::is_same_v<LayoutIn, Kokkos::layout_right>
412 && std::is_same_v<LayoutOut, Kokkos::layout_right>,
413 "Layouts must be right-handed");
414 static_assert(
415 (is_uniform_point_sampling_v<DDimX> && ...),
416 "DDimX dimensions should derive from UniformPointSampling");
417 static_assert(
418 (is_periodic_sampling_v<DDimFx> && ...),
419 "DDimFx dimensions should derive from PeriodicPointSampling");
420
421 ddc::detail::fft::
422 impl(exec_space, in, out, {ddc::FFT_Direction::BACKWARD, kwargs.normalization});
423}
424
425} // namespace ddc
friend class ChunkSpan
friend class DiscreteDomain
KOKKOS_FUNCTION constexpr bool operator!=(DiscreteVector< OTags... > const &rhs) const noexcept
The top-level namespace of DDC.
ddc::FFT_Normalization normalization
Enum member to identify the type of normalization performed.
Definition fft.hpp:318
void ifft(ExecSpace const &exec_space, ddc::ChunkSpan< Tout, ddc::DiscreteDomain< DDimX... >, LayoutOut, MemorySpace > out, ddc::ChunkSpan< Tin, ddc::DiscreteDomain< DDimFx... >, LayoutIn, MemorySpace > in, ddc::kwArgs_fft kwargs={ddc::FFT_Normalization::OFF})
Perform an inverse Fast Fourier Transform.
Definition fft.hpp:404
void fft(ExecSpace const &exec_space, ddc::ChunkSpan< Tout, ddc::DiscreteDomain< DDimFx... >, LayoutOut, MemorySpace > out, ddc::ChunkSpan< Tin, ddc::DiscreteDomain< DDimX... >, LayoutIn, MemorySpace > in, ddc::kwArgs_fft kwargs={ddc::FFT_Normalization::OFF})
Perform a direct Fast Fourier Transform.
Definition fft.hpp:351
FFT_Normalization
A named argument to choose the type of normalization of the FFT.
Definition fft.hpp:41
@ BACKWARD
No normalization for forward FFT, multiply by 1/N for backward FFT.
@ OFF
No normalization. Un-normalized FFT is sum_j f(x_j)*e^-ikx_j.
@ ORTHO
Multiply by 1/sqrt(N)
@ FULL
Multiply by dx/sqrt(2*pi) for forward FFT and dk/sqrt(2*pi) for backward FFT.
@ FORWARD
Multiply by 1/N for forward FFT, no normalization for backward FFT.
ddc::DiscreteDomain< DDimFx... > fourier_mesh(ddc::DiscreteDomain< DDimX... > x_mesh, bool C2C)
Get the Fourier mesh.
Definition fft.hpp:293
DDimFx::template Impl< DDimFx, Kokkos::HostSpace > init_fourier_space(ddc::DiscreteDomain< DDimX > x_mesh)
Initialize a Fourier discrete dimension.
Definition fft.hpp:252
FFT_Direction
A named argument to choose the direction of the FFT.
Definition fft.hpp:31
@ BACKWARD
Backward, corresponds to inverse FFT up to normalization.
@ FORWARD
Forward, corresponds to direct FFT up to normalization.
A structure embedding the configuration of the exposed FFT function with the type of normalization.
Definition fft.hpp:316