ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
dp3m_heffte.impl.hpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2010-2026 The ESPResSo project
3 * Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009,2010
4 * Max-Planck-Institute for Polymer Research, Theory Group
5 *
6 * This file is part of ESPResSo.
7 *
8 * ESPResSo is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * ESPResSo is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#include <config/config.hpp>
23
24#ifdef ESPRESSO_DP3M
25
27
30
31#include "magnetostatics/dp3m_heffte.hpp" // must be included after dipoles.hpp
32
33#include "fft/fft.hpp"
34#include "p3m/P3MFFT.hpp"
36#include "p3m/TuningLogger.hpp"
37#include "p3m/common.hpp"
40#include "p3m/interpolation.hpp"
41#include "p3m/math.hpp"
42
43#include "BoxGeometry.hpp"
44#include "LocalBox.hpp"
45#include "Particle.hpp"
46#include "PropagationMode.hpp"
49#include "communication.hpp"
50#include "errorhandling.hpp"
52#include "kokkos_helpers.hpp"
53#include "npt.hpp"
54#include "system/System.hpp"
55#include "tuning.hpp"
56
57#include <utils/Vector.hpp>
60#include <utils/math/sqr.hpp>
61
62#include <boost/mpi/collectives/all_reduce.hpp>
63#include <boost/mpi/collectives/reduce.hpp>
64
65#include <Kokkos_Core.hpp>
66#include <Kokkos_ScatterView.hpp>
67
68#include <algorithm>
69#include <array>
70#include <cmath>
71#include <cstddef>
72#include <cstdio>
73#include <functional>
74#include <iterator>
75#include <memory>
76#include <numbers>
77#include <optional>
78#include <span>
79#include <sstream>
80#include <stdexcept>
81#include <tuple>
82#include <utility>
83#include <vector>
84
85#ifdef ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
86#ifndef NDEBUG
87template <typename T>
88bool heffte_almost_equal(T const &value, T const &reference) {
89 auto const diff = std::abs(value - reference);
90 using FT = std::remove_cvref_t<decltype(diff)>;
91 auto constexpr atol = std::is_same_v<FT, float> ? FT{2e-4} : FT{1e-6};
92 auto constexpr rtol = std::is_same_v<FT, float> ? FT{5e-5} : FT{1e-5};
93 auto const non_zero = std::abs(reference) != FT{0};
94 return (diff < atol) or (non_zero and (diff / std::abs(reference) < rtol));
95}
96#endif // not NDEBUG
97#endif // ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
98
99template <typename FloatType, Arch Architecture, class FFTConfig>
100void DipolarP3MHeffte<FloatType, Architecture,
102 auto local_n = std::size_t{0u};
103 double local_mu2 = 0.;
104
105 for (auto const &p : get_system().cell_structure->local_particles()) {
106 if (p.dipm() != 0.) {
107 local_mu2 += p.calc_dip().norm2();
108 local_n++;
109 }
110 }
111
112 boost::mpi::all_reduce(comm_cart, local_mu2, dp3m.sum_mu2, std::plus<>());
113 boost::mpi::all_reduce(comm_cart, local_n, dp3m.sum_dip_part, std::plus<>());
114}
115
116inline double dp3m_k_space_error(double box_size, int mesh, int cao,
117 std::size_t n_c_part, double sum_q2,
118 double alpha_L);
119
120inline double dp3m_real_space_error(double box_size, double r_cut_iL,
121 std::size_t n_c_part, double sum_q2,
122 double alpha_L);
123
124/** Compute the value of alpha through a bisection method.
125 * Based on eq. (33) @cite wang01a.
126 */
127double dp3m_rtbisection(double box_size, double r_cut_iL, std::size_t n_c_part,
128 double sum_q2, double x1, double x2, double xacc,
129 double tuned_accuracy);
130
131template <typename FloatType, Arch Architecture, class FFTConfig>
132double DipolarP3MHeffte<FloatType, Architecture,
134 auto const &box_geo = *get_system().box_geo;
135 auto const node_phi =
137 dp3m.params, dp3m.mesh.start, dp3m.mesh.stop, dp3m.g_energy);
138
139 double phi = 0.;
140 boost::mpi::reduce(comm_cart, node_phi, phi, std::plus<>(), 0);
141 phi /= 3. * box_geo.length()[0] *
142 Utils::int_pow<3>(static_cast<double>(dp3m.params.mesh[0]));
143 return phi * std::numbers::pi;
144}
145
146template <typename FloatType, Arch Architecture, class FFTConfig>
148 assert(dp3m.params.mesh >= Utils::Vector3i::broadcast(1));
149 assert(dp3m.params.cao >= p3m_min_cao and dp3m.params.cao <= p3m_max_cao);
150 assert(dp3m.params.alpha > 0.);
151
152 auto const &system = get_system();
153 auto const &box_geo = *system.box_geo;
154 auto const &local_geo = *system.local_geo;
155 auto const verlet_skin = system.cell_structure->get_verlet_skin();
156
157 dp3m.params.cao3 = Utils::int_pow<3>(dp3m.params.cao);
158 dp3m.params.recalc_a_ai_cao_cut(box_geo.length());
159
160 assert(dp3m.fft);
161 dp3m.local_mesh.calc_local_ca_mesh(dp3m.params, local_geo, verlet_skin, 0.);
162 dp3m.fft_buffers->init_halo();
163 dp3m.fft->init(dp3m.params);
164 dp3m.mesh.ks_pnum = dp3m.fft->get_ks_pnum();
165 dp3m.fft_buffers->init_meshes(dp3m.fft->get_ca_mesh_size());
166 dp3m.update_mesh_views();
167#ifdef ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
168 dp3m.heffte.world_size = comm_cart.size();
169 try {
170 dp3m.heffte.fft =
171 std::make_shared<P3MFFT<FloatType, Architecture, FFTConfig>>(
172 nullptr, ::comm_cart, dp3m.params.mesh, dp3m.local_mesh.ld_no_halo,
173 dp3m.local_mesh.ur_no_halo, ::communicator.node_grid);
174 dp3m.resize_heffte_buffers();
175 } catch (p3m_tuning_exception const &) {
176 dp3m.heffte.fft.reset();
177 }
178#endif // ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
179 dp3m.calc_differential_operator();
180
181 /* fix box length dependent constants */
183
185}
186
187namespace {
188template <int cao> struct AssignDipole {
189 void operator()(auto &dp3m, auto &cell_structure) {
190 using DipolarP3MState = std::remove_reference_t<decltype(dp3m)>;
191 using value_type = DipolarP3MState::value_type;
192 using execution_space = Kokkos::DefaultHostExecutionSpace;
193 auto const &aosoa = cell_structure.get_aosoa();
194 auto const &unique_particles = cell_structure.get_unique_particles();
195 auto const n_part = cell_structure.count_local_particles();
196 dp3m.inter_weights.zfill(n_part); // allocate buffer for parallel write
198 "InterpolateDipoles", std::size_t{0u}, n_part, [&](auto p_index) {
199 auto constexpr memory_order = Utils::MemoryOrder::ROW_MAJOR;
200 auto const tid = omp_get_thread_num();
201 auto const p_pos = aosoa.get_span_at(aosoa.position, p_index);
202 auto const dip = unique_particles.at(p_index)->calc_dip();
203 auto const weights =
205 p_pos, dp3m.params.ai, dp3m.local_mesh);
206 dp3m.inter_weights.store_at(p_index, weights);
208 dp3m.local_mesh, weights, [&dip, tid, &dp3m](int ind, double w) {
209 dp3m.rs_fields_kokkos(tid, 0u, ind) += value_type(w * dip[0u]);
210 dp3m.rs_fields_kokkos(tid, 1u, ind) += value_type(w * dip[1u]);
211 dp3m.rs_fields_kokkos(tid, 2u, ind) += value_type(w * dip[2u]);
212 });
213 });
214 Kokkos::fence();
215 int num_threads = execution_space().concurrency();
217 "ReduceInterpolatedDipoles", std::size_t{0}, dp3m.local_mesh.size,
218 [&dp3m, num_threads](std::size_t const i) {
219 for (int dir = 0; dir < 3; ++dir) {
220 value_type acc{};
221 for (int tid = 0; tid < num_threads; ++tid) {
222 acc += dp3m.rs_fields_kokkos(tid, dir, i);
223 }
224 dp3m.mesh.rs_fields[dir][i] += acc;
225#ifdef ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
226 if (dp3m.heffte.fft != nullptr) {
227 dp3m.heffte.rs_dipole_density[dir][i] += acc;
228 }
229#endif
230 }
231 });
232 Kokkos::fence();
233 }
234};
235} // namespace
236
237template <typename FloatType, Arch Architecture, class FFTConfig>
244
245namespace {
246template <int cao> struct AssignTorques {
247 void operator()(auto &dp3m, double pref, int d_rs,
248 CellStructure &cell_structure) const {
249
250 assert(cao == dp3m.inter_weights.cao());
251 using execution_space = Kokkos::DefaultHostExecutionSpace;
252
253 auto const kernel = [d_rs, pref, &dp3m](auto const &dip,
254#ifdef ESPRESSO_DIPOLE_FIELD_TRACKING
255 auto &p_dip_fld,
256#endif
257 auto &p_torque,
258 std::size_t p_index) {
259 auto const weights = dp3m.inter_weights.template load<cao>(p_index);
260 Utils::Vector3d E{};
261 p3m_interpolate(dp3m.local_mesh, weights,
262 [&E, &dp3m, d_rs](int ind, double w) {
263 // heFFTe data: dp3m.heffte.ks_scalar.real()
264 E[d_rs] += w * double(dp3m.mesh.rs_scalar[ind]);
265 });
266
267 auto const torque = pref * vector_product(dip, E);
268 auto access = p_torque.access();
269 access(p_index, 0) -= torque[0];
270 access(p_index, 1) -= torque[1];
271 access(p_index, 2) -= torque[2];
272#ifdef ESPRESSO_DIPOLE_FIELD_TRACKING
273 auto const dip_fld = pref * E;
274 auto access_dip_fld = p_dip_fld.access();
275 access_dip_fld(p_index, 0) -= dip_fld[0];
276 access_dip_fld(p_index, 1) -= dip_fld[1];
277 access_dip_fld(p_index, 2) -= dip_fld[2];
278#endif
279 };
280
281 auto const n_part = dp3m.inter_weights.size();
282 auto const &unique_particles = cell_structure.get_unique_particles();
283 cell_structure.mark_torque_replicas_dirty();
284 auto scatter_torque = cell_structure.get_scatter_torque();
285#ifdef ESPRESSO_DIPOLE_FIELD_TRACKING
286 auto scatter_dip_fld = cell_structure.get_scatter_dip_fld();
287#endif
289 "AssignTorques", std::size_t{0u}, n_part, [&](std::size_t p_index) {
290 auto const &p = *unique_particles.at(p_index);
291 if (p.dipm() != 0.) {
292 kernel(p.calc_dip(),
293#ifdef ESPRESSO_DIPOLE_FIELD_TRACKING
294 scatter_dip_fld,
295#endif
296 scatter_torque, p_index);
297 }
298 });
299 }
300};
301
302template <int cao> struct AssignForcesDip {
303 void operator()(auto &dp3m, double pref, int d_rs,
304 CellStructure &cell_structure) const {
305
306 assert(cao == dp3m.inter_weights.cao());
307 using execution_space = Kokkos::DefaultHostExecutionSpace;
308
309 auto const kernel = [d_rs, pref, &dp3m](auto const &dip, auto &p_force,
310 std::size_t p_index) {
311 auto const weights = dp3m.inter_weights.template load<cao>(p_index);
312
313 Utils::Vector3d E{};
314 p3m_interpolate(dp3m.local_mesh, weights, [&E, &dp3m](int ind, double w) {
315 // heFFTe data: dp3m.heffte.rs_B_fields
316 E[0u] += w * double(dp3m.mesh.rs_fields[0u][ind]);
317 E[1u] += w * double(dp3m.mesh.rs_fields[1u][ind]);
318 E[2u] += w * double(dp3m.mesh.rs_fields[2u][ind]);
319 });
320
321 auto access = p_force.access();
322 access(p_index, d_rs) += pref * (dip * E);
323 };
324
325 auto const n_part = dp3m.inter_weights.size();
326 auto const &unique_particles = cell_structure.get_unique_particles();
327 auto scatter_force = cell_structure.get_scatter_force();
329 "AssignForcesDip", std::size_t{0u}, n_part, [&](std::size_t p_index) {
330 auto const &p = *unique_particles.at(p_index);
331 if (p.dipm() != 0.) {
332 kernel(p.calc_dip(), scatter_force, p_index);
333 }
334 });
335 }
336};
337} // namespace
338
339#ifdef ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
340template <typename FloatType, class FFTConfig>
342 auto const rs_array_size =
343 static_cast<std::size_t>(Utils::product(this->local_mesh.dim));
344 auto const rs_array_size_no_halo =
345 static_cast<std::size_t>(Utils::product(this->local_mesh.dim_no_halo));
346 auto const fft_mesh_size =
347 static_cast<std::size_t>(Utils::product(heffte.fft->ks_local_size()));
348 for (auto d : {0u, 1u, 2u}) {
349 heffte.rs_dipole_density[d].resize(rs_array_size);
350 heffte.ks_dipole_density[d].resize(fft_mesh_size);
351 heffte.rs_B_fields[d].resize(rs_array_size);
352 heffte.rs_B_fields_no_halo[d].resize(rs_array_size_no_halo);
353 }
354 heffte.ks_B_field_storage.resize(fft_mesh_size);
355 heffte.ks_scalar.resize(fft_mesh_size);
356}
357#endif // ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
358
359/**
360 * @brief Reciprocal-space virial for the dipolar Ewald/P3M sum. Obtained
361 * via the same Nose-Klein strain-derivative method used for the Coulomb
362 * case (@cite essmann95a eq. (2.7), \f$\Pi_{\textrm{rec}, \alpha, \beta}\f$),
363 * applied to the dipolar structure
364 * factor \f$Q(\vec k) = \vec M(\vec k)\cdot\vec k\f$ with
365 * \f$\vec M(\vec k) = \sum_j \vec \mu_j \exp(i\vec k\cdot\vec r_j)\f$.
366 * Unlike the charge structure factor, \f$Q(\vec k)\f$ depends on
367 * \f$\vec k\f$ explicitly (not only through the phase factor), which
368 * produces an extra cross term beyond the charge-case \f$k_a k_b\f$
369 * envelope. This cross term is generally asymmetric in \f$(a,b)\f$: its
370 * symmetric half, \f$k_a\Re[M_b Q^*] + k_b\Re[M_a Q^*]\f$, is the
371 * dipole-dipole reciprocal-space pressure tensor eq. (46) in
372 * @cite aguado03a (their \f$\vec h\f$, \f$\kappa\f$ correspond to
373 * \f$\vec k\f$, \f$\alpha\f$ here), which only ever reports that
374 * symmetrized form. The remaining antisymmetric half is not in that
375 * reference -- it is the reciprocal-space image of the same
376 * dipole-dipole torque that already makes the real-space virial
377 * asymmetric (see @ref DipolarDirectSum::long_range_pressure and
378 * @ref DipolarP3M::pair_force), derived here by differentiating
379 * the reciprocal energy directly (via the strain parametrization
380 * \f$H(\varepsilon)=LI+\varepsilon E_{ab}\f$) instead of presupposing a
381 * symmetric result.
382 *
383 * Care is needed with the index convention: probing the strain component
384 * \f$\varepsilon_{ab}\f$ (i.e. \f$H(\varepsilon)=LI+\varepsilon E_{ab}\f$)
385 * yields \f$-\partial U/\partial\varepsilon_{ab} = r_b F_a\f$ for a pair
386 * separation \f$\vec r\f$ and force \f$\vec F\f$ -- the *transpose* of the
387 * \f$r_a F_b\f$ (@ref Utils::tensor_product "d (x) f") convention used by
388 * the real-space term and by @ref DipolarDirectSum::long_range_pressure.
389 * Concretely, differentiating \f$Q(\vec k)=\vec k\cdot\vec M\f$ gives a
390 * cross-term contribution to \f$-\partial U/\partial\varepsilon_{ab}\f$
391 * proportional to \f$k_a\Re[M_bQ^*]\f$; to match the \f$r_aF_b\f$
392 * convention, this must be stored as the \f$(b,a)\f$ tensor component,
393 * i.e. \f$\Pi_{ab}\f$ gets cross term \f$2k_b\Re[M_aQ^*]\f$ (indices
394 * swapped relative to the strain probe that produced it).
395 */
396template <typename FloatType, Arch Architecture, class FFTConfig>
399 auto const &system = get_system();
400 auto const &box_geo = *system.box_geo;
401 auto const dipole_prefac = prefactor / Utils::product(dp3m.params.mesh);
402 Utils::Vector9d node_k_space_pressure_tensor{};
403
404 if (dp3m.sum_mu2 > 0.) {
406 dp3m.fft_buffers->perform_vector_halo_gather();
407 for (auto &rs_mesh : dp3m.fft_buffers->get_vector_mesh()) {
408 dp3m.fft->forward_fft(rs_mesh);
409 }
410 dp3m.update_mesh_views();
411
412 auto constexpr mesh_start = Utils::Vector3i::broadcast(0);
413 auto local_index = Utils::Vector3i::broadcast(0);
414 auto const wavevector = 2. * std::numbers::pi * box_geo.length_inv()[0];
415 auto const half_alpha_inv_sq = Utils::sqr(1. / (2. * dp3m.params.alpha));
416
417 auto index = std::size_t(0u);
418 auto it_energy = dp3m.g_energy.begin();
419 for_each_3d(mesh_start, dp3m.mesh.size, local_index, [&]() {
420 auto constexpr KX = 2, KY = 0, KZ = 1;
421 auto const shift = local_index + dp3m.mesh.start;
422 auto const &d_op = dp3m.d_op[0u];
423 auto const &mesh_dip = dp3m.mesh.rs_fields;
424 auto const d_op_x = static_cast<FloatType>(d_op[shift[KX]]);
425 auto const d_op_y = static_cast<FloatType>(d_op[shift[KY]]);
426 auto const d_op_z = static_cast<FloatType>(d_op[shift[KZ]]);
427
428 // Re(M(k)) and Re(Q(k)) = Re(M(k)).n, same as the energy kernel's `re`
429 auto const Mx_re = mesh_dip[0u][index];
430 auto const My_re = mesh_dip[1u][index];
431 auto const Mz_re = mesh_dip[2u][index];
432 auto const Q_re = Mx_re * d_op_x + My_re * d_op_y + Mz_re * d_op_z;
433 ++index;
434 // Im(M(k)) and Im(Q(k))
435 auto const Mx_im = mesh_dip[0u][index];
436 auto const My_im = mesh_dip[1u][index];
437 auto const Mz_im = mesh_dip[2u][index];
438 auto const Q_im = Mx_im * d_op_x + My_im * d_op_y + Mz_im * d_op_z;
439 ++index;
440
441 auto const nx = static_cast<double>(d_op[shift[KX]]);
442 auto const ny = static_cast<double>(d_op[shift[KY]]);
443 auto const nz = static_cast<double>(d_op[shift[KZ]]);
444 auto const kx = nx * wavevector;
445 auto const ky = ny * wavevector;
446 auto const kz = nz * wavevector;
447 auto const norm_sq = Utils::sqr(kx) + Utils::sqr(ky) + Utils::sqr(kz);
448 if (norm_sq != 0.) {
449 auto const g = static_cast<double>(*it_energy);
450 auto const cell_energy =
451 g * static_cast<double>(Utils::sqr(Q_re) + Utils::sqr(Q_im));
452 auto const vterm = -2. * (1. / norm_sq + half_alpha_inv_sq);
453
454 // g * Re(M_a(k) * Q(k)^*), a in {x, y, z}
455 auto const Rx = g * static_cast<double>(Mx_re * Q_re + Mx_im * Q_im);
456 auto const Ry = g * static_cast<double>(My_re * Q_re + My_im * Q_im);
457 auto const Rz = g * static_cast<double>(Mz_re * Q_re + Mz_im * Q_im);
458
459 // Full (generally asymmetric) tensor: Pi_ab = cell_energy * (delta_ab
460 // + vterm * k_a * k_b) + 2 * k_b * R_a (note: indices of the cross
461 // term are swapped relative to the strain probe that produces it --
462 // see the class-level comment above for the derivation). The
463 // symmetric combination (R_a k_b + R_b k_a)/2 recovers the
464 // literature (Aguado & Madden, eq. 46) result; the leftover
465 // antisymmetric part is the k-space image of the same
466 // dipolar-torque signature that already makes the real-space term
467 // asymmetric (see dipolar_direct_sum.cpp / dp3m.hpp).
468 node_k_space_pressure_tensor[0u] +=
469 cell_energy * (1. + vterm * kx * kx) + 2. * nx * Rx; /* xx */
470 node_k_space_pressure_tensor[1u] +=
471 cell_energy * vterm * kx * ky + 2. * ny * Rx; /* xy */
472 node_k_space_pressure_tensor[2u] +=
473 cell_energy * vterm * kx * kz + 2. * nz * Rx; /* xz */
474 node_k_space_pressure_tensor[3u] +=
475 cell_energy * vterm * ky * kx + 2. * nx * Ry; /* yx */
476 node_k_space_pressure_tensor[4u] +=
477 cell_energy * (1. + vterm * ky * ky) + 2. * ny * Ry; /* yy */
478 node_k_space_pressure_tensor[5u] +=
479 cell_energy * vterm * ky * kz + 2. * nz * Ry; /* yz */
480 node_k_space_pressure_tensor[6u] +=
481 cell_energy * vterm * kz * kx + 2. * nx * Rz; /* zx */
482 node_k_space_pressure_tensor[7u] +=
483 cell_energy * vterm * kz * ky + 2. * ny * Rz; /* zy */
484 node_k_space_pressure_tensor[8u] +=
485 cell_energy * (1. + vterm * kz * kz) + 2. * nz * Rz; /* zz */
486 }
487 std::advance(it_energy, 1);
488 });
489 }
490
491 return node_k_space_pressure_tensor * dipole_prefac * std::numbers::pi *
492 box_geo.length_inv()[0];
493}
494
495template <typename FloatType, Arch Architecture, class FFTConfig>
497 bool force_flag, bool energy_flag) {
498 /* k-space energy */
499 double energy = 0.;
500 auto const &system = get_system();
501 auto const &box_geo = *system.box_geo;
502 auto const dipole_prefac = prefactor / Utils::product(dp3m.params.mesh);
503
504 auto constexpr mesh_start = Utils::Vector3i::broadcast(0);
505 auto local_index = Utils::Vector3i::broadcast(0);
506#ifdef ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
507 auto constexpr r2c_dir = FFTConfig::r2c_dir;
508#ifndef NDEBUG
509 int line_stride = 0;
510 int plane_stride = 0;
511#endif
512 int cutoff_left = 0;
513 int cutoff_right = 0;
514 Utils::Vector3i local_origin{};
515 if (dp3m.heffte.fft != nullptr) {
516 auto local_size_full = dp3m.heffte.fft->ks_local_size();
517 if constexpr (FFTConfig::use_r2c) {
518 local_size_full[r2c_dir] -= 1;
519 local_size_full[r2c_dir] *= 2;
520 }
521 local_origin = dp3m.heffte.fft->ks_local_ld_index();
522#ifndef NDEBUG
523 line_stride = local_size_full[0];
524 plane_stride = local_size_full[0] * local_size_full[0];
525#endif
526 auto const &global_size = dp3m.params.mesh;
527 cutoff_left = 1 - local_origin[r2c_dir];
528 cutoff_right = global_size[r2c_dir] / 2 - local_origin[r2c_dir];
529 dp3m.resize_heffte_buffers();
530 }
531 auto &short_dim = local_index[r2c_dir];
532#endif
533
534 if (dp3m.sum_mu2 > 0.) {
536 dp3m.fft_buffers->perform_vector_halo_gather();
537 for (auto &rs_mesh : dp3m.fft_buffers->get_vector_mesh()) {
538 dp3m.fft->forward_fft(rs_mesh);
539 }
540 dp3m.update_mesh_views();
541
542#ifdef ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
543 if (dp3m.heffte.world_size == 1 and dp3m.heffte.fft != nullptr) {
544 auto const rs_local_size = dp3m.heffte.fft->rs_local_size();
545 // halo communication of real space dipoles density
546 std::array<FloatType *, 3u> rs_fields = {
547 {dp3m.heffte.rs_dipole_density[0u].data(),
548 dp3m.heffte.rs_dipole_density[1u].data(),
549 dp3m.heffte.rs_dipole_density[2u].data()}};
550 dp3m.heffte.halo_comm.gather_grid(::comm_cart, rs_fields,
551 dp3m.local_mesh.dim);
552
553 for (auto dir : {0u, 1u, 2u}) {
554 // get real-space dipoles density without ghost layers
556 FFTConfig::r_space_order>(
557 dp3m.rs_field_no_halo_kokkos.data(),
558 dp3m.heffte.rs_dipole_density[dir], dp3m.local_mesh.dim,
559 dp3m.local_mesh.n_halo_ld,
560 dp3m.local_mesh.dim - dp3m.local_mesh.n_halo_ur);
561 // re-order data in row-major
562 std::size_t index_row_major = 0u;
564 mesh_start, rs_local_size, local_index, [&]() {
565 auto constexpr KX = 1, KY = 2, KZ = 0;
566 auto const index = local_index[KZ] +
567 rs_local_size[0] * local_index[KY] +
568 Utils::sqr(rs_local_size[0]) * local_index[KX];
569 dp3m.rs_field_no_halo_reorder_kokkos(index_row_major) =
570 dp3m.rs_field_no_halo_kokkos(index);
571 ++index_row_major;
572 });
573 dp3m.heffte.fft->forward(dp3m.rs_field_no_halo_reorder_kokkos.data(),
574 dp3m.heffte.ks_dipole_density[dir].data());
575#ifndef NDEBUG
576 if (not dp3m.params.tuning) {
577 auto const local_size = dp3m.heffte.fft->ks_local_size();
578 std::size_t index_row_major_r2c = 0u;
580 mesh_start, local_size, local_index, [&]() {
581 if (not FFTConfig::use_r2c or (short_dim <= cutoff_right)) {
582 auto constexpr KX = 2, KY = 0, KZ = 1;
583 auto const index_fft_legacy = local_index[KZ] +
584 line_stride * local_index[KY] +
585 plane_stride * local_index[KX];
586 auto const old_value = std::complex<FloatType>(
587 dp3m.mesh.rs_fields[dir][2 * index_fft_legacy],
588 dp3m.mesh.rs_fields[dir][2 * index_fft_legacy + 1]);
589 auto const &new_value =
590 dp3m.heffte.ks_dipole_density[dir][index_row_major_r2c];
591 assert(heffte_almost_equal(new_value, old_value));
592 ++index_row_major_r2c;
593 }
594 });
595 }
596#endif // not NDEBUG
597 }
598 }
599#endif // ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
600 }
601
602 /* === k-space energy calculation === */
603 if (energy_flag) {
604 /*********************
605 Dipolar energy
606 **********************/
607 if (dp3m.sum_mu2 > 0.) {
608 /* i*k differentiation for dipolar gradients:
609 * |(\Fourier{\vect{mu}}(k)\cdot \vect{k})|^2 */
610
611 auto index = std::size_t(0u);
612 auto it_energy = dp3m.g_energy.begin();
613 auto node_energy = 0.;
614 for_each_3d(mesh_start, dp3m.mesh.size, local_index, [&]() {
615 auto constexpr KX = 2, KY = 0, KZ = 1;
616 auto const shift = local_index + dp3m.mesh.start;
617 auto const &d_op = dp3m.d_op[0u];
618 auto const &mesh_dip = dp3m.mesh.rs_fields;
619 // Re(mu)*k
620 auto const re = mesh_dip[0u][index] * FloatType(d_op[shift[KX]]) +
621 mesh_dip[1u][index] * FloatType(d_op[shift[KY]]) +
622 mesh_dip[2u][index] * FloatType(d_op[shift[KZ]]);
623 ++index;
624 // Im(mu)*k
625 auto const im = mesh_dip[0u][index] * FloatType(d_op[shift[KX]]) +
626 mesh_dip[1u][index] * FloatType(d_op[shift[KY]]) +
627 mesh_dip[2u][index] * FloatType(d_op[shift[KZ]]);
628 ++index;
629 node_energy += *it_energy * (Utils::sqr(re) + Utils::sqr(im));
630 std::advance(it_energy, 1);
631 });
632#ifdef ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
633 if (dp3m.heffte.world_size == 1 and dp3m.heffte.fft != nullptr) {
634 auto const local_size = dp3m.heffte.fft->ks_local_size();
635 [[maybe_unused]] auto node_energy_heffte = 0.;
636 std::size_t index_row_major_r2c = 0u;
638 mesh_start, local_size, local_index, [&]() {
639 if (not FFTConfig::use_r2c or (short_dim <= cutoff_right)) {
640 auto const global_index = local_origin + local_index;
641 auto const &mesh_dip = dp3m.heffte.ks_dipole_density;
642 auto const cell_field =
643 mesh_dip[0u][index_row_major_r2c] *
644 FloatType(dp3m.d_op[0u][global_index[1u]]) +
645 mesh_dip[1u][index_row_major_r2c] *
646 FloatType(dp3m.d_op[1u][global_index[2u]]) +
647 mesh_dip[2u][index_row_major_r2c] *
648 FloatType(dp3m.d_op[2u][global_index[0u]]);
649 auto cell_energy = static_cast<double>(
650 dp3m.heffte.g_energy[index_row_major_r2c] *
651 std::norm(cell_field));
652 if (FFTConfig::use_r2c and (short_dim >= cutoff_left and
653 short_dim <= cutoff_right - 1)) {
654 // k-space symmetry: double counting except in the first and
655 // last planes of the short dimension; although the wavevector
656 // points in the opposite direction in the redundant region of
657 // k-space, the product of two components of the wavevector
658 // cancels out the negative sign
659 cell_energy *= 2.;
660 }
661 node_energy_heffte += cell_energy;
662 }
663 ++index_row_major_r2c;
664 });
665 assert(heffte_almost_equal(static_cast<FloatType>(node_energy_heffte),
666 static_cast<FloatType>(node_energy)));
667 }
668#endif // ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
669 node_energy *= dipole_prefac * std::numbers::pi * box_geo.length_inv()[0];
670 boost::mpi::reduce(comm_cart, node_energy, energy, std::plus<>(), 0);
671
672 if (dp3m.energy_correction == 0.)
674
675 if (this_node == 0) {
676 /* self energy correction */
677 energy -= prefactor * dp3m.sum_mu2 * std::numbers::inv_sqrtpi *
678 (2. / 3.) * Utils::int_pow<3>(dp3m.params.alpha);
679
680 /* dipolar energy correction due to systematic Madelung-self effects */
681 energy += prefactor * dp3m.energy_correction / box_geo.volume();
682 }
683 }
684 } // if (energy_flag)
685
686 /* === k-space force calculation === */
687 if (force_flag) {
688 /****************************
689 * DIPOLAR TORQUES (k-space)
690 ****************************/
691 if (dp3m.sum_mu2 > 0.) {
692 auto const wavenumber = 2. * std::numbers::pi * box_geo.length_inv()[0u];
693 dp3m.ks_scalar.resize(dp3m.local_mesh.size);
694 /* fill in ks_scalar array for torque calculation */
695 {
696 auto index{std::size_t(0u)};
697 auto it_energy = dp3m.g_energy.begin();
698 auto it_ks_scalar = dp3m.ks_scalar.begin();
699 for_each_3d(mesh_start, dp3m.mesh.size, local_index, [&]() mutable {
700 auto constexpr KX = 2, KY = 0, KZ = 1;
701 auto const shift = local_index + dp3m.mesh.start;
702 auto const &d_op = dp3m.d_op[0u];
703 auto const &mesh_dip = dp3m.mesh.rs_fields;
704 // Re(mu)*k
705 auto const re = mesh_dip[0u][index] * FloatType(d_op[shift[KX]]) +
706 mesh_dip[1u][index] * FloatType(d_op[shift[KY]]) +
707 mesh_dip[2u][index] * FloatType(d_op[shift[KZ]]);
708 ++index;
709 // Im(mu)*k
710 auto const im = mesh_dip[0u][index] * FloatType(d_op[shift[KX]]) +
711 mesh_dip[1u][index] * FloatType(d_op[shift[KY]]) +
712 mesh_dip[2u][index] * FloatType(d_op[shift[KZ]]);
713 ++index;
714 *it_ks_scalar = *it_energy * std::complex<FloatType>(re, im);
715 std::advance(it_energy, 1);
716 std::advance(it_ks_scalar, 1);
717 });
718 }
719#ifdef ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
720 if (dp3m.heffte.world_size == 1 and dp3m.heffte.fft != nullptr) {
721 auto const local_size = dp3m.heffte.fft->ks_local_size();
722 std::size_t index_row_major_r2c = 0u;
724 mesh_start, local_size, local_index, [&]() {
725 if (not FFTConfig::use_r2c or (short_dim <= cutoff_right)) {
726 auto const global_index = local_origin + local_index;
727 auto const &mesh_dip = dp3m.heffte.ks_dipole_density;
728 dp3m.heffte.ks_scalar[index_row_major_r2c] =
729 dp3m.heffte.g_energy[index_row_major_r2c] *
730 (mesh_dip[0u][index_row_major_r2c] *
731 FloatType(dp3m.d_op[0u][global_index[1u]]) +
732 mesh_dip[1u][index_row_major_r2c] *
733 FloatType(dp3m.d_op[1u][global_index[2u]]) +
734 mesh_dip[2u][index_row_major_r2c] *
735 FloatType(dp3m.d_op[2u][global_index[0u]]));
736#ifndef NDEBUG
737 if (not dp3m.params.tuning) {
738 auto constexpr KX = 2, KY = 0, KZ = 1;
739 auto const index_fft_legacy = local_index[KZ] +
740 line_stride * local_index[KY] +
741 plane_stride * local_index[KX];
742 assert(heffte_almost_equal(
743 dp3m.heffte.ks_scalar[index_row_major_r2c],
744 dp3m.ks_scalar[index_fft_legacy]));
745 }
746#endif // not NDEBUG
747 ++index_row_major_r2c;
748 }
749 });
750 }
751#endif // ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
752
753 /* Torque component loop */
754 for (int d = 0; d < 3; d++) {
755 auto it_ks_scalar = dp3m.ks_scalar.begin();
756 auto index = 0u;
757 for_each_3d(mesh_start, dp3m.mesh.size, local_index, [&]() {
758 auto const &offset = dp3m.mesh.start;
759 auto const &d_op = dp3m.d_op[0u];
760 auto const d_op_val = FloatType(d_op[local_index[d] + offset[d]]);
761 auto const &value = *it_ks_scalar;
762 dp3m.mesh.rs_scalar[index] = d_op_val * value.real();
763 ++index;
764 dp3m.mesh.rs_scalar[index] = d_op_val * value.imag();
765 ++index;
766 std::advance(it_ks_scalar, 1);
767 });
768#ifdef ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
769 if (dp3m.heffte.world_size == 1 and dp3m.heffte.fft != nullptr) {
770 auto const local_size = dp3m.heffte.fft->ks_local_size();
771 unsigned int constexpr d_ks[3] = {2u, 0u, 1u};
772 std::size_t index_row_major_r2c = 0u;
774 mesh_start, local_size, local_index, [&]() {
775 if (not FFTConfig::use_r2c or (short_dim <= cutoff_right)) {
776 auto const global_index = local_origin + local_index;
777 auto const d_op_val =
778 FloatType(dp3m.d_op[d][global_index[d_ks[d]]]);
779 dp3m.heffte.ks_B_field_storage[index_row_major_r2c] =
780 d_op_val * dp3m.heffte.ks_scalar[index_row_major_r2c];
781#ifndef NDEBUG
782 if (not dp3m.params.tuning) {
783 auto constexpr KX = 2, KY = 0, KZ = 1;
784 auto const index_fft_legacy =
785 local_index[KZ] + line_stride * local_index[KY] +
786 plane_stride * local_index[KX];
787 auto const old_value = std::complex<FloatType>(
788 dp3m.mesh.rs_scalar[2 * index_fft_legacy],
789 dp3m.mesh.rs_scalar[2 * index_fft_legacy + 1]);
790 auto const &new_value =
791 dp3m.heffte.ks_B_field_storage[index_row_major_r2c];
792 assert(heffte_almost_equal(new_value, old_value));
793 }
794#endif // not NDEBUG
795 ++index_row_major_r2c;
796 }
797 });
798 dp3m.heffte.fft->backward(dp3m.heffte.ks_B_field_storage.data(),
799 dp3m.heffte.rs_B_fields_no_halo[d].data());
800 // pad zeros around the B-field in real space for ghost layers,
801 // writing straight into the persistent halo-sized buffer
802 pad_with_zeros_discard_imag_into<FFTConfig::r_space_order,
804 dp3m.heffte.rs_B_fields[d].data(),
805 std::span(dp3m.heffte.rs_B_fields_no_halo[d]),
806 dp3m.local_mesh.dim_no_halo, dp3m.local_mesh.n_halo_ld,
807 dp3m.local_mesh.n_halo_ur);
808 // communicate ghost layers of the B-field in real space
809 dp3m.heffte.halo_comm.spread_grid(::comm_cart,
810 dp3m.heffte.rs_B_fields[d].data(),
811 dp3m.local_mesh.dim);
812 }
813#endif // ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
814 dp3m.fft->backward_fft(dp3m.fft_buffers->get_scalar_mesh());
815 // communicate ghost layers of the B-field in real space
816 dp3m.fft_buffers->perform_scalar_halo_spread();
817 // assign torque component from mesh to particle
818 auto const d_rs = (d + dp3m.mesh.ks_pnum) % 3;
820 dp3m.params.cao, dp3m, dipole_prefac * wavenumber, d_rs,
821 *system.cell_structure);
822 }
823
824 /***************************
825 DIPOLAR FORCES (k-space)
826 ****************************/
827 // Compute forces after torques because the algorithm below overwrites the
828 // grids dp3m.mesh.rs_fields !
829 // Note: I'll do here 9 inverse FFTs. By symmetry, we can reduce this
830 // number to 6 !
831 /* fill in ks_scalar array for force calculation */
832 {
833 auto it_force = dp3m.g_force.begin();
834 auto it_ks_scalar = dp3m.ks_scalar.begin();
835 std::size_t index = 0u;
836 for_each_3d(mesh_start, dp3m.mesh.size, local_index, [&]() {
837 auto constexpr KX = 2, KY = 0, KZ = 1;
838 auto const shift = local_index + dp3m.mesh.start;
839 auto const &d_op = dp3m.d_op[0u];
840 auto const &mesh_dip = dp3m.mesh.rs_fields;
841 // Re(mu)*k
842 auto const re = mesh_dip[0u][index] * FloatType(d_op[shift[KX]]) +
843 mesh_dip[1u][index] * FloatType(d_op[shift[KY]]) +
844 mesh_dip[2u][index] * FloatType(d_op[shift[KZ]]);
845 ++index;
846 // Im(mu)*k
847 auto const im = mesh_dip[0u][index] * FloatType(d_op[shift[KX]]) +
848 mesh_dip[1u][index] * FloatType(d_op[shift[KY]]) +
849 mesh_dip[2u][index] * FloatType(d_op[shift[KZ]]);
850 ++index;
851 *it_ks_scalar = {*it_force * im, *it_force * (-re)};
852 std::advance(it_force, 1);
853 std::advance(it_ks_scalar, 1);
854 });
855 }
856
857#ifdef ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
858 if (dp3m.heffte.world_size == 1 and dp3m.heffte.fft != nullptr) {
859 auto const local_size = dp3m.heffte.fft->ks_local_size();
860 std::size_t index_row_major_r2c = 0u;
862 mesh_start, local_size, local_index, [&]() {
863 if (not FFTConfig::use_r2c or (short_dim <= cutoff_right)) {
864 auto const global_index = local_origin + local_index;
865 auto const &mesh_dip = dp3m.heffte.ks_dipole_density;
866 auto const value =
867 dp3m.heffte.g_force[index_row_major_r2c] *
868 (mesh_dip[0u][index_row_major_r2c] *
869 FloatType(dp3m.d_op[0u][global_index[1u]]) +
870 mesh_dip[1u][index_row_major_r2c] *
871 FloatType(dp3m.d_op[1u][global_index[2u]]) +
872 mesh_dip[2u][index_row_major_r2c] *
873 FloatType(dp3m.d_op[2u][global_index[0u]]));
874 dp3m.heffte.ks_scalar[index_row_major_r2c] =
875 std::complex<FloatType>(value.imag(), -value.real());
876#ifndef NDEBUG
877 if (not dp3m.params.tuning) {
878 auto constexpr KX = 2, KY = 0, KZ = 1;
879 auto const index_fft_legacy = local_index[KZ] +
880 line_stride * local_index[KY] +
881 plane_stride * local_index[KX];
882 assert(heffte_almost_equal(
883 dp3m.heffte.ks_scalar[index_row_major_r2c],
884 dp3m.ks_scalar[index_fft_legacy]));
885 }
886#endif // not NDEBUG
887 ++index_row_major_r2c;
888 }
889 });
890 }
891#endif // ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
892
893 /* Force component loop */
894 for (int d = 0; d < 3; d++) {
895 std::size_t index = 0u;
896 auto it_ks_scalar = dp3m.ks_scalar.begin();
897 for_each_3d(mesh_start, dp3m.mesh.size, local_index, [&]() {
898 auto constexpr KX = 2, KY = 0, KZ = 1;
899 auto const shift = local_index + dp3m.mesh.start;
900 auto const &d_op = dp3m.d_op[0u];
901 auto const &mesh_dip = dp3m.mesh.rs_fields;
902 auto const d_op_val = FloatType(d_op[shift[d]]);
903 auto const f = *it_ks_scalar * d_op_val;
904 mesh_dip[0u][index] = FloatType(d_op[shift[KX]]) * f.real();
905 mesh_dip[1u][index] = FloatType(d_op[shift[KY]]) * f.real();
906 mesh_dip[2u][index] = FloatType(d_op[shift[KZ]]) * f.real();
907 ++index;
908 mesh_dip[0u][index] = FloatType(d_op[shift[KX]]) * f.imag();
909 mesh_dip[1u][index] = FloatType(d_op[shift[KY]]) * f.imag();
910 mesh_dip[2u][index] = FloatType(d_op[shift[KZ]]) * f.imag();
911 ++index;
912 std::advance(it_ks_scalar, 1);
913 });
914
915#ifdef ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
916 if (dp3m.heffte.world_size == 1 and dp3m.heffte.fft != nullptr) {
917 auto const local_size = dp3m.heffte.fft->ks_local_size();
918 std::size_t index_row_major_r2c = 0u;
920 mesh_start, local_size, local_index, [&]() {
921 if (not FFTConfig::use_r2c or (short_dim <= cutoff_right)) {
922 auto constexpr KX = 1, KY = 2, KZ = 0;
923 auto const global_index = local_origin + local_index;
924 auto const remapped_index =
925 local_index[KZ] + local_index[KY] * local_size[KZ] +
926 local_index[KX] * local_size[KZ] * local_size[KY];
927 auto const d_op_val =
928 FloatType(dp3m.d_op[d][global_index[d]]);
929 auto &mesh_dip = dp3m.heffte.ks_dipole_density;
930 mesh_dip[0u][index_row_major_r2c] =
931 FloatType(dp3m.d_op[d][global_index[2u]]) * d_op_val *
932 dp3m.heffte.ks_scalar[remapped_index];
933 mesh_dip[1u][index_row_major_r2c] =
934 FloatType(dp3m.d_op[d][global_index[0u]]) * d_op_val *
935 dp3m.heffte.ks_scalar[remapped_index];
936 mesh_dip[2u][index_row_major_r2c] =
937 FloatType(dp3m.d_op[d][global_index[1u]]) * d_op_val *
938 dp3m.heffte.ks_scalar[remapped_index];
939#ifndef NDEBUG
940 if (not FFTConfig::use_r2c and not dp3m.params.tuning) {
941 auto const index_fft_legacy = local_index[2] +
942 line_stride * local_index[1] +
943 plane_stride * local_index[0];
944 for (int j = 0; j < 3; ++j) {
945 auto const old_value = std::complex<FloatType>(
946 dp3m.mesh.rs_fields[j][2 * index_fft_legacy],
947 dp3m.mesh.rs_fields[j][2 * index_fft_legacy + 1]);
948 auto const &new_value = mesh_dip[j][index_row_major_r2c];
949 assert(heffte_almost_equal(new_value, old_value));
950 }
951 }
952#endif // not NDEBUG
953 ++index_row_major_r2c;
954 }
955 });
956 for (int dir = 0u; dir < 3u; ++dir) {
957 dp3m.heffte.fft->backward(
958 dp3m.heffte.ks_dipole_density[dir].data(),
959 dp3m.heffte.rs_B_fields_no_halo[dir].data());
960 // pad zeros around the B-field in real space for ghost layers,
961 // writing straight into the persistent halo-sized buffer
962 pad_with_zeros_discard_imag_into<FFTConfig::r_space_order,
964 dp3m.heffte.rs_B_fields[d].data(),
965 std::span(dp3m.heffte.rs_B_fields_no_halo[dir]),
966 dp3m.local_mesh.dim_no_halo, dp3m.local_mesh.n_halo_ld,
967 dp3m.local_mesh.n_halo_ur);
968 }
969 // communicate ghost layers of the B-field in real space
970 auto rs_fields =
971 std::array<FloatType *, 3u>{{dp3m.heffte.rs_B_fields[0u].data(),
972 dp3m.heffte.rs_B_fields[1u].data(),
973 dp3m.heffte.rs_B_fields[2u].data()}};
974 dp3m.heffte.halo_comm.spread_grid(::comm_cart, rs_fields,
975 dp3m.local_mesh.dim);
976 }
977#endif // ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
978 for (auto &rs_mesh : dp3m.fft_buffers->get_vector_mesh()) {
979 dp3m.fft->backward_fft(rs_mesh);
980 }
981 // communicate ghost layers of the B-field in real space
982 dp3m.fft_buffers->perform_vector_halo_spread();
983 // assign force component from mesh to particle
984 auto const d_rs = (d + dp3m.mesh.ks_pnum) % 3;
985 Utils::integral_parameter<int, AssignForcesDip, p3m_min_cao,
987 dp3m.params.cao, dp3m, dipole_prefac * Utils::sqr(wavenumber), d_rs,
988 *system.cell_structure);
989 }
990 } /* if (dp3m.sum_mu2 > 0) */
991 } /* if (force_flag) */
992
993 if (dp3m.params.epsilon != P3M_EPSILON_METALLIC) {
994 auto const surface_term = calc_surface_term(force_flag, energy_flag);
995 if (this_node == 0) {
996 energy += surface_term;
997 }
998 }
999#ifdef ESPRESSO_NPT
1000 if (force_flag and system.has_npt_enabled()) {
1001 // reuse the validated reciprocal-space pressure tensor (same one used by
1002 // the pressure observable) instead of an energy-proxy: unlike Coulomb,
1003 // the dipolar structure factor is not simply homogeneous in k, so energy
1004 // is not a valid substitute for the virial trace here (see
1005 // long_range_pressure())
1006 auto const pressure_tensor = long_range_pressure();
1009 }
1010#endif
1011 if (not energy_flag) {
1012 energy = 0.;
1013 }
1014
1015 return energy;
1016}
1017
1018template <typename FloatType, Arch Architecture, class FFTConfig>
1020 bool force_flag, bool energy_flag) {
1021 auto const &system = get_system();
1022 auto const &box_geo = *system.box_geo;
1023 auto const particles = system.cell_structure->local_particles();
1024 auto const pref = prefactor * 4. * std::numbers::pi / box_geo.volume() /
1025 (2. * dp3m.params.epsilon + 1.);
1026 auto const n_local_part = particles.size();
1027
1028 // We put all the dipolar momenta in a the arrays mx,my,mz according to the
1029 // id-number of the particles
1030 std::vector<double> mx(n_local_part);
1031 std::vector<double> my(n_local_part);
1032 std::vector<double> mz(n_local_part);
1033
1034 std::size_t ip = 0u;
1035 for (auto const &p : particles) {
1036 auto const dip = p.calc_dip();
1037 mx[ip] = dip[0u];
1038 my[ip] = dip[1u];
1039 mz[ip] = dip[2u];
1040 ip++;
1041 }
1042
1043 // we will need the sum of all dipolar momenta vectors
1044 auto local_dip = Utils::Vector3d{};
1045 for (std::size_t i = 0u; i < n_local_part; i++) {
1046 local_dip[0u] += mx[i];
1047 local_dip[1u] += my[i];
1048 local_dip[2u] += mz[i];
1049 }
1050 auto const box_dip =
1051 boost::mpi::all_reduce(comm_cart, local_dip, std::plus<>());
1052
1053 double energy = 0.;
1054 if (energy_flag) {
1055 double sum_e = 0.;
1056 for (std::size_t i = 0u; i < n_local_part; i++) {
1057 sum_e += mx[i] * box_dip[0] + my[i] * box_dip[1] + mz[i] * box_dip[2];
1058 }
1059 energy =
1060 0.5 * pref * boost::mpi::all_reduce(comm_cart, sum_e, std::plus<>());
1061 }
1062
1063 if (force_flag) {
1064
1065 std::vector<double> sumix(n_local_part);
1066 std::vector<double> sumiy(n_local_part);
1067 std::vector<double> sumiz(n_local_part);
1068
1069 for (std::size_t i = 0u; i < n_local_part; i++) {
1070 sumix[i] = my[i] * box_dip[2u] - mz[i] * box_dip[1u];
1071 sumiy[i] = mz[i] * box_dip[0u] - mx[i] * box_dip[2u];
1072 sumiz[i] = mx[i] * box_dip[1u] - my[i] * box_dip[0u];
1073 }
1074
1075 ip = 0u;
1076 for (auto &p : particles) {
1077 auto &torque = p.torque();
1078 torque[0u] -= pref * sumix[ip];
1079 torque[1u] -= pref * sumiy[ip];
1080 torque[2u] -= pref * sumiz[ip];
1081#ifdef ESPRESSO_DIPOLE_FIELD_TRACKING
1082 p.dip_fld() -= pref * box_dip;
1083#endif
1084 ip++;
1085 }
1086 }
1087
1088 return energy;
1089}
1090
1091template <typename FloatType, Arch Architecture, class FFTConfig>
1092void DipolarP3MHeffte<FloatType, Architecture,
1094 dp3m.g_force = grid_influence_function_dipolar<FloatType, 3, P3M_BRILLOUIN,
1095 FFTConfig::k_space_order>(
1096 dp3m.params, dp3m.mesh.start, dp3m.mesh.stop,
1097 get_system().box_geo->length_inv());
1098#ifdef ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
1099 if (dp3m.heffte.world_size == 1 and dp3m.heffte.fft != nullptr) {
1100 dp3m.heffte.g_force =
1102 FFTConfig::k_space_order>(
1103 dp3m.params, dp3m.heffte.fft->ks_local_ld_index(),
1104 dp3m.heffte.fft->ks_local_ur_index(),
1105 get_system().box_geo->length_inv());
1106 if constexpr (FFTConfig::use_r2c) {
1108 dp3m.heffte.g_force, dp3m.params.mesh,
1109 dp3m.heffte.fft->ks_local_size(),
1110 dp3m.heffte.fft->ks_local_ld_index());
1111 }
1112 }
1113#endif
1114}
1115
1116template <typename FloatType, Arch Architecture, class FFTConfig>
1117void DipolarP3MHeffte<FloatType, Architecture,
1119 dp3m.g_energy = grid_influence_function_dipolar<FloatType, 2, P3M_BRILLOUIN,
1120 FFTConfig::k_space_order>(
1121 dp3m.params, dp3m.mesh.start, dp3m.mesh.stop,
1122 get_system().box_geo->length_inv());
1123#ifdef ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
1124 if (dp3m.heffte.world_size == 1 and dp3m.heffte.fft != nullptr) {
1125 dp3m.heffte.g_energy =
1127 FFTConfig::k_space_order>(
1128 dp3m.params, dp3m.heffte.fft->ks_local_ld_index(),
1129 dp3m.heffte.fft->ks_local_ur_index(),
1130 get_system().box_geo->length_inv());
1131 if constexpr (FFTConfig::use_r2c) {
1133 dp3m.heffte.g_energy, dp3m.params.mesh,
1134 dp3m.heffte.fft->ks_local_size(),
1135 dp3m.heffte.fft->ks_local_ld_index());
1136 }
1137 }
1138#endif
1139}
1140
1141template <typename FloatType, Arch Architecture, class FFTConfig>
1144 int m_mesh_max = -1, m_mesh_min = -1;
1145 std::pair<std::optional<int>, std::optional<int>> m_tune_limits;
1146
1147public:
1148 DipolarTuningAlgorithm(System::System &system, decltype(dp3m) &input_dp3m,
1149 double prefactor, int timings,
1150 decltype(m_tune_limits) tune_limits)
1151 : TuningAlgorithm(system, prefactor, timings), dp3m{input_dp3m},
1152 m_tune_limits{std::move(tune_limits)} {}
1153
1154 P3MParameters &get_params() override { return dp3m.params; }
1155
1156 void on_solver_change() const override { m_system.on_dipoles_change(); }
1157
1158 std::optional<std::string>
1159 layer_correction_veto_r_cut(double) const override {
1160 return {};
1161 }
1162
1163 void setup_logger(bool verbose) override {
1164 auto const &box_geo = *m_system.box_geo;
1165 m_logger = std::make_unique<TuningLogger>(
1166 verbose and this_node == 0, "DipolarP3M", TuningLogger::Mode::Dipolar);
1167 m_logger->tuning_goals(dp3m.params.accuracy, m_prefactor,
1168 box_geo.length()[0], dp3m.sum_dip_part,
1169 dp3m.sum_mu2);
1170 m_logger->log_tuning_start();
1171 }
1172
1173 std::tuple<double, double, double, double>
1175 double r_cut_iL) const override {
1176
1177 double alpha_L, rs_err, ks_err;
1178 auto const &box_geo = *m_system.box_geo;
1179
1180 /* calc maximal real space error for setting */
1181 rs_err = dp3m_real_space_error(box_geo.length()[0], r_cut_iL,
1182 dp3m.sum_dip_part, dp3m.sum_mu2, 0.001);
1183 // alpha cannot be zero for dipoles because real-space formula breaks down
1184
1185 if (std::numbers::sqrt2 * rs_err > dp3m.params.accuracy) {
1186 /* assume rs_err = ks_err -> rs_err = accuracy/sqrt(2.0) -> alpha_L */
1187 alpha_L = dp3m_rtbisection(
1188 box_geo.length()[0], r_cut_iL, dp3m.sum_dip_part, dp3m.sum_mu2,
1189 0.0001 * box_geo.length()[0], 5. * box_geo.length()[0], 0.0001,
1190 dp3m.params.accuracy);
1191 } else {
1192 /* even alpha=0 is ok, however, we cannot choose it since it kills the
1193 k-space error formula.
1194 Anyways, this very likely NOT the optimal solution */
1195 alpha_L = 0.1;
1196 }
1197
1198 /* calculate real-space and k-space error for this alpha_L */
1199 rs_err = dp3m_real_space_error(box_geo.length()[0], r_cut_iL,
1200 dp3m.sum_dip_part, dp3m.sum_mu2, alpha_L);
1201 ks_err = dp3m_k_space_error(box_geo.length()[0], mesh[0], cao,
1202 dp3m.sum_dip_part, dp3m.sum_mu2, alpha_L);
1203
1204 return {Utils::Vector2d{rs_err, ks_err}.norm(), rs_err, ks_err, alpha_L};
1205 }
1206
1207 void determine_mesh_limits() override {
1208 if (dp3m.params.mesh[0] == -1) {
1209 /* simple heuristic to limit the tried meshes if the accuracy cannot
1210 be obtained with smaller meshes, but normally not all these
1211 meshes have to be tested */
1212 auto const expo = std::log2(dp3m.sum_dip_part) / 3.;
1213 /* Medium-educated guess for the minimal mesh */
1214 m_mesh_min = static_cast<int>(std::round(std::pow(2., std::floor(expo))));
1215 /* avoid using more than 1 GB of FFT arrays */
1216 m_mesh_max = 128;
1217 if (m_tune_limits.first) {
1218 m_mesh_min = *m_tune_limits.first;
1219 }
1220 if (m_tune_limits.second) {
1221 m_mesh_max = *m_tune_limits.second;
1222 }
1223 } else {
1224 m_mesh_min = m_mesh_max = dp3m.params.mesh[0];
1225 m_logger->report_fixed_mesh(dp3m.params.mesh);
1226 }
1227 }
1228
1230 auto tuned_params = TuningAlgorithm::Parameters{};
1231 auto time_best = time_sentinel;
1232 for (auto tmp_mesh = m_mesh_min; tmp_mesh <= m_mesh_max; tmp_mesh += 2) {
1233 auto trial_params = TuningAlgorithm::Parameters{};
1234 trial_params.mesh = Utils::Vector3i::broadcast(tmp_mesh);
1235 trial_params.cao = cao_best;
1236
1237 auto const trial_time =
1238 get_m_time(trial_params.mesh, trial_params.cao, trial_params.r_cut_iL,
1239 trial_params.alpha_L, trial_params.accuracy);
1240
1241 /* this mesh does not work at all */
1242 if (trial_time < 0.)
1243 continue;
1244
1245 /* the optimum r_cut for this mesh is the upper limit for higher meshes,
1246 everything else is slower */
1247 m_r_cut_iL_max = trial_params.r_cut_iL;
1248
1249 if (trial_time < time_best) {
1250 /* new optimum */
1252 tuned_params = trial_params;
1253 time_best = tuned_params.time = trial_time;
1254 } else if (trial_time > time_best + time_granularity or
1256 /* no hope of further optimisation */
1257 break;
1258 }
1259 }
1260 return tuned_params;
1261 }
1262};
1263
1264template <typename FloatType, Arch Architecture, class FFTConfig>
1266 auto &system = get_system();
1267 auto const &box_geo = *system.box_geo;
1268 if (dp3m.params.alpha_L == 0. and dp3m.params.alpha != 0.) {
1269 dp3m.params.alpha_L = dp3m.params.alpha * box_geo.length()[0];
1270 }
1271 if (dp3m.params.r_cut_iL == 0. and dp3m.params.r_cut != 0.) {
1272 dp3m.params.r_cut_iL = dp3m.params.r_cut * box_geo.length_inv()[0];
1273 }
1274 if (not is_tuned()) {
1276 if (dp3m.sum_dip_part == 0) {
1277 throw std::runtime_error(
1278 "DipolarP3M: no dipolar particles in the system");
1279 }
1280 try {
1282 system, dp3m, prefactor, tuning.timings, tuning.limits);
1283 parameters.setup_logger(tuning.verbose);
1284 // parameter ranges
1285 parameters.determine_mesh_limits();
1286 parameters.determine_r_cut_limits();
1287 parameters.determine_cao_limits(3);
1288 // run tuning algorithm
1289 parameters.tune();
1290 m_is_tuned = true;
1291 system.on_dipoles_change();
1292 } catch (...) {
1293 dp3m.params.tuning = false;
1294 throw;
1295 }
1296 }
1297 init();
1298}
1299
1300/** Tuning dipolar-P3M */
1301inline auto dp3m_tune_aliasing_sums(Utils::Vector3i const &shift, int mesh,
1302 double mesh_i, int cao, double alpha_L_i) {
1303
1304 auto constexpr mesh_start = Utils::Vector3i::broadcast(-P3M_BRILLOUIN);
1305 auto constexpr mesh_stop = Utils::Vector3i::broadcast(P3M_BRILLOUIN + 1);
1306 auto const factor1 = Utils::sqr(std::numbers::pi * alpha_L_i);
1307 auto alias1 = 0.;
1308 auto alias2 = 0.;
1309
1310 Utils::Vector3i indices{};
1311 Utils::Vector3i nm{};
1312 Utils::Vector3d fnm{};
1314 mesh_start, mesh_stop, indices,
1315 [&]() {
1316 auto const norm_sq = nm.norm2();
1317 auto const ex = std::exp(-factor1 * norm_sq);
1318 auto const U2 = std::pow(Utils::product(fnm), 2 * cao);
1319 alias1 += Utils::sqr(ex) * norm_sq;
1320 alias2 += U2 * ex * std::pow(shift * nm, 3) / norm_sq;
1321 },
1322 [&](unsigned dim, int n) {
1323 nm[dim] = shift[dim] + n * mesh;
1324 fnm[dim] = math::sinc(nm[dim] * mesh_i);
1325 });
1326
1327 return std::make_pair(alias1, alias2);
1328}
1329
1330/** Calculate the k-space error of dipolar-P3M */
1331inline double dp3m_k_space_error(double box_size, int mesh, int cao,
1332 std::size_t n_c_part, double sum_q2,
1333 double alpha_L) {
1334
1335 auto const cotangent_sum = math::get_analytic_cotangent_sum_kernel(cao);
1336 auto const mesh_i = 1. / static_cast<double>(mesh);
1337 auto const alpha_L_i = 1. / alpha_L;
1338 auto const mesh_stop = Utils::Vector3i::broadcast(mesh / 2);
1339 auto const mesh_start = -mesh_stop;
1340 auto indices = Utils::Vector3i{};
1341 auto values = Utils::Vector3d{};
1342 auto he_q = 0.;
1343
1345 mesh_start, mesh_stop, indices,
1346 [&]() {
1347 if ((indices[0] != 0) or (indices[1] != 0) or (indices[2] != 0)) {
1348 auto const n2 = indices.norm2();
1349 auto const cs = Utils::product(values);
1350 auto const [alias1, alias2] =
1351 dp3m_tune_aliasing_sums(indices, mesh, mesh_i, cao, alpha_L_i);
1352 auto const d =
1353 alias1 - Utils::sqr(alias2 / cs) /
1354 Utils::int_pow<3>(static_cast<double>(n2));
1355 /* at high precision, d can become negative due to extinction;
1356 also, don't take values that have no significant digits left*/
1357 if (d > 0. and std::fabs(d / alias1) > round_error_prec)
1358 he_q += d;
1359 }
1360 },
1361 [&values, &mesh_i, cotangent_sum](unsigned dim, int n) {
1362 values[dim] = cotangent_sum(n, mesh_i);
1363 });
1364
1365 return 8. * Utils::sqr(std::numbers::pi) / 3. * sum_q2 *
1366 sqrt(he_q / static_cast<double>(n_c_part)) /
1367 Utils::int_pow<4>(box_size);
1368}
1369
1370/** Calculate the value of the errors for the REAL part of the force in terms
1371 * of the splitting parameter alpha of Ewald. Based on eq. (33) @cite wang01a.
1372 *
1373 * Please note that in this more refined approach we don't use
1374 * eq. (37), but eq. (33) which maintains all the powers in alpha.
1375 */
1376inline double dp3m_real_space_error(double box_size, double r_cut_iL,
1377 std::size_t n_c_part, double sum_q2,
1378 double alpha_L) {
1379 auto constexpr exp_min = -708.4; // for IEEE-compatible double
1380 double d_error_f, d_cc, d_dc, d_con;
1381
1382 auto const d_rcut = r_cut_iL * box_size;
1383 auto const d_rcut2 = Utils::sqr(d_rcut);
1384 auto const d_rcut4 = Utils::sqr(d_rcut2);
1385
1386 auto const d_a2 = Utils::sqr(alpha_L) / Utils::sqr(box_size);
1387 auto const exponent = -d_a2 * d_rcut2;
1388 auto const exp_term = (exponent < exp_min) ? 0. : std::exp(exponent);
1389 auto const d_c = sum_q2 * exp_term;
1390
1391 d_cc = 4. * Utils::sqr(d_a2) * Utils::sqr(d_rcut2) + 6. * d_a2 * d_rcut2 + 3.;
1392
1393 d_dc = 8. * Utils::int_pow<3>(d_a2) * Utils::int_pow<3>(d_rcut2) +
1394 20. * Utils::sqr(d_a2) * d_rcut4 + 30. * d_a2 * d_rcut2 + 15.;
1395
1396 d_con = 1. / sqrt(Utils::int_pow<3>(box_size) * Utils::sqr(d_a2) * d_rcut *
1397 Utils::sqr(d_rcut4) * static_cast<double>(n_c_part));
1398
1399 d_error_f = d_c * d_con *
1400 sqrt((13. / 6.) * Utils::sqr(d_cc) +
1401 (2. / 15.) * Utils::sqr(d_dc) - (13. / 15.) * d_cc * d_dc);
1402
1403 return d_error_f;
1404}
1405
1406/** Using bisection, find the root of a function "func-tuned_accuracy/sqrt(2.)"
1407 * known to lie between x1 and x2. The root, returned as rtbis, will be
1408 * refined until its accuracy is \f$\pm\f$ @p xacc.
1409 */
1410double dp3m_rtbisection(double box_size, double r_cut_iL, std::size_t n_c_part,
1411 double sum_q2, double x1, double x2, double xacc,
1412 double tuned_accuracy) {
1413 constexpr int JJ_RTBIS_MAX = 40;
1414
1415 auto const constant = tuned_accuracy / std::numbers::sqrt2;
1416
1417 auto const f1 =
1418 dp3m_real_space_error(box_size, r_cut_iL, n_c_part, sum_q2, x1) -
1419 constant;
1420 auto const f2 =
1421 dp3m_real_space_error(box_size, r_cut_iL, n_c_part, sum_q2, x2) -
1422 constant;
1423 if (f1 * f2 >= 0.0) {
1424 throw std::runtime_error(
1425 "Root must be bracketed for bisection in dp3m_rtbisection");
1426 }
1427 // Orient the search dx, and set rtb to x1 or x2 ...
1428 double dx;
1429 double rtb = f1 < 0.0 ? (dx = x2 - x1, x1) : (dx = x1 - x2, x2);
1430 for (int j = 1; j <= JJ_RTBIS_MAX; j++) {
1431 auto const xmid = rtb + (dx *= 0.5);
1432 auto const fmid =
1433 dp3m_real_space_error(box_size, r_cut_iL, n_c_part, sum_q2, xmid) -
1434 constant;
1435 if (fmid <= 0.0)
1436 rtb = xmid;
1437 if (fabs(dx) < xacc || fmid == 0.0)
1438 return rtb;
1439 }
1440 throw std::runtime_error("Too many bisections in dp3m_rtbisection");
1441}
1442
1444 auto const &system = get_system();
1445 auto const &box_geo = *system.box_geo;
1446 auto const &local_geo = *system.local_geo;
1447 for (auto i = 0u; i < 3u; i++) {
1448 /* check k-space cutoff */
1449 if (dp3m_params.cao_cut[i] >= box_geo.length_half()[i]) {
1450 std::stringstream msg;
1451 msg << "dipolar P3M_init: k-space cutoff " << dp3m_params.cao_cut[i]
1452 << " is larger than half of box dimension " << box_geo.length()[i];
1453 throw std::runtime_error(msg.str());
1454 }
1455 if (dp3m_params.cao_cut[i] >= local_geo.length()[i]) {
1456 std::stringstream msg;
1457 msg << "dipolar P3M_init: k-space cutoff " << dp3m_params.cao_cut[i]
1458 << " is larger than local box dimension " << local_geo.length()[i];
1459 throw std::runtime_error(msg.str());
1460 }
1461 }
1462
1463 if ((box_geo.length()[0] != box_geo.length()[1]) or
1464 (box_geo.length()[1] != box_geo.length()[2])) {
1465 throw std::runtime_error("DipolarP3M: requires a cubic box");
1466 }
1467}
1468
1470 auto const &box_geo = *get_system().box_geo;
1471 if (!box_geo.periodic(0) or !box_geo.periodic(1) or !box_geo.periodic(2)) {
1472 throw std::runtime_error(
1473 "DipolarP3M: requires periodicity (True, True, True)");
1474 }
1475}
1476
1478 auto const &local_geo = *get_system().local_geo;
1479 if (local_geo.cell_structure_type() != CellStructureType::REGULAR and
1480 local_geo.cell_structure_type() != CellStructureType::HYBRID) {
1481 throw std::runtime_error(
1482 "DipolarP3M: requires the regular or hybrid decomposition cell system");
1483 }
1484 if (::communicator.size > 1 and
1485 local_geo.cell_structure_type() == CellStructureType::HYBRID) {
1486 throw std::runtime_error(
1487 "DipolarP3M: does not work with the hybrid decomposition cell system, "
1488 "if using more than one MPI node");
1489 }
1490}
1491
1493 auto const &node_grid = ::communicator.node_grid;
1494 if (node_grid[0] < node_grid[1] or node_grid[1] < node_grid[2]) {
1495 throw std::runtime_error(
1496 "DipolarP3M: node grid must be sorted, largest first");
1497 }
1498}
1499
1500template <typename FloatType, Arch Architecture, class FFTConfig>
1502 auto const &box_geo = *get_system().box_geo;
1503 dp3m.params.r_cut = dp3m.params.r_cut_iL * box_geo.length()[0];
1504 dp3m.params.alpha = dp3m.params.alpha_L * box_geo.length_inv()[0];
1505 dp3m.params.recalc_a_ai_cao_cut(box_geo.length());
1506 dp3m.local_mesh.recalc_ld_pos(dp3m.params);
1510 dp3m.energy_correction = 0.;
1511#ifdef ESPRESSO_DP3M_HEFFTE_CROSS_CHECKS
1512 if (dp3m.heffte.world_size == 1 and dp3m.heffte.fft != nullptr) {
1513 dp3m.heffte.halo_comm.resize(::comm_cart, dp3m.local_mesh);
1514 }
1515#endif
1516}
1517
1518template <typename FloatType, Arch Architecture, class FFTConfig>
1519void DipolarP3MHeffte<FloatType, Architecture,
1521 auto const &box_geo = *get_system().box_geo;
1522 auto const Ukp3m = calc_average_self_energy_k_space() * box_geo.volume();
1523 auto const Ewald_volume = Utils::int_pow<3>(dp3m.params.alpha_L);
1524 auto const Eself = -2. * Ewald_volume * std::numbers::inv_sqrtpi / 3.;
1525 dp3m.energy_correction =
1526 -dp3m.sum_mu2 * (Ukp3m + Eself + 2. * std::numbers::pi / 3.);
1527}
1528
1529#ifdef ESPRESSO_NPT
1530template <typename FloatType, Arch Architecture, class FFTConfig>
1531void DipolarP3MHeffte<FloatType, Architecture,
1532 FFTConfig>::npt_add_virial_contribution(double virial)
1533 const {
1534 get_system().npt_add_virial_contribution(virial);
1535}
1536#endif // ESPRESSO_NPT
1537
1538#endif // ESPRESSO_DP3M
@ HYBRID
Hybrid decomposition.
@ REGULAR
Regular decomposition.
Vector implementation and trait types for boost qvm interoperability.
Describes a cell structure / cell system.
auto const & get_unique_particles() const
auto get_scatter_dip_fld()
auto get_scatter_torque()
void mark_torque_replicas_dirty()
Declare that a kernel scattering into the torque view is about to run.
std::tuple< double, double, double, double > calculate_accuracy(Utils::Vector3i const &mesh, int cao, double r_cut_iL) const override
TuningAlgorithm::Parameters get_time() override
DipolarTuningAlgorithm(System::System &system, decltype(dp3m) &input_dp3m, double prefactor, int timings, decltype(m_tune_limits) tune_limits)
void on_solver_change() const override
void determine_mesh_limits() override
P3MParameters & get_params() override
std::optional< std::string > layer_correction_veto_r_cut(double) const override
void setup_logger(bool verbose) override
base_type::size_type size() const
Main system class.
std::shared_ptr< LocalBox > local_geo
void npt_add_virial_contribution(double energy)
Definition npt.cpp:137
std::shared_ptr< BoxGeometry > box_geo
double get_m_time(Utils::Vector3i const &mesh, int &tuned_cao, double &tuned_r_cut_iL, double &tuned_alpha_L, double &tuned_accuracy)
Get the optimal alpha and the corresponding computation time for a fixed mesh.
static auto constexpr time_sentinel
Value for invalid time measurements.
static auto constexpr max_n_consecutive_trials
Maximal number of consecutive trials that don't improve runtime.
System::System & m_system
void determine_cao_limits(int initial_cao)
Determine a sensible range for the charge assignment order.
TuningAlgorithm(System::System &system, double prefactor, int timings)
void determine_r_cut_limits()
Determine a sensible range for the real-space cutoff.
std::unique_ptr< TuningLogger > m_logger
static auto constexpr time_granularity
Granularity of the time measurement (milliseconds).
static DEVICE_QUALIFIER constexpr Vector< int, N > broadcast(typename Base::value_type const &value) noexcept
Definition Vector.hpp:144
constexpr T norm2() const
Definition Vector.hpp:173
Communicator communicator
boost::mpi::communicator comm_cart
The communicator.
int this_node
The number of this node.
constexpr auto round_error_prec
Precision below which a double-precision float is assumed to be zero.
Definition config.hpp:47
__device__ void vector_product(float const *a, float const *b, float *out)
static std::size_t count_magnetic_particles(ParticleRange const &particles)
Definition dlc.cpp:400
P3M algorithm for long-range magnetic dipole-dipole interaction.
double dp3m_real_space_error(double box_size, double r_cut_iL, std::size_t n_c_part, double sum_q2, double alpha_L)
Calculate the value of the errors for the REAL part of the force in terms of the splitting parameter ...
double dp3m_rtbisection(double box_size, double r_cut_iL, std::size_t n_c_part, double sum_q2, double x1, double x2, double xacc, double tuned_accuracy)
Compute the value of alpha through a bisection method.
auto dp3m_tune_aliasing_sums(Utils::Vector3i const &shift, int mesh, double mesh_i, int cao, double alpha_L_i)
Tuning dipolar-P3M.
double dp3m_k_space_error(double box_size, int mesh, int cao, std::size_t n_c_part, double sum_q2, double alpha_L)
Calculate the k-space error of dipolar-P3M.
This file contains the errorhandling code for severe errors, like a broken bond or illegal parameter ...
Routines, row decomposition, data structures and communication for the 3D-FFT.
void extract_block_into(OutValue *out, Container const &in_array, Utils::Vector3i const &dimensions, Utils::Vector3i const &start, Utils::Vector3i const &stop)
Extract a 3D block from the halo field into a caller-provided buffer.
void pad_with_zeros_discard_imag_into(OutValue *out, std::span< T > cropped_array, Utils::Vector3i const &cropped_dim, Utils::Vector3i const &pad_left, Utils::Vector3i const &pad_right)
Pad a 3D matrix with zeros to restore halo regions, writing into a caller-provided buffer of product(...
void for_each_3d_order(detail::IndexVectorConcept auto &&start, detail::IndexVectorConcept auto &&stop, detail::IndexVectorConcept auto &&counters, Kernel &&kernel, Projector &&projector=detail::noop_projector)
Repeat an operation on every element of a 3D grid.
void for_each_3d(detail::IndexVectorConcept auto &&start, detail::IndexVectorConcept auto &&stop, detail::IndexVectorConcept auto &&counters, Kernel &&kernel, Projector &&projector=detail::noop_projector)
Repeat an operation on every element of a 3D grid.
double grid_influence_function_self_energy(P3MParameters const &params, Utils::Vector3i const &n_start, Utils::Vector3i const &n_stop, std::vector< FloatType > const &g)
Calculate self-energy of the influence function.
std::vector< FloatType > grid_influence_function_dipolar(P3MParameters const &params, Utils::Vector3i const &n_start, Utils::Vector3i const &n_stop, Utils::Vector3d const &inv_box_l)
Map influence function over a grid.
InterpolationWeights< cao > p3m_calculate_interpolation_weights(std::span< const double, 3 > position, Utils::Vector3d const &ai, P3MLocalMesh const &local_mesh)
Calculate the P-th order interpolation weights.
void p3m_interpolate(P3MLocalMesh const &local_mesh, WeightsStorage< cao > const &weights, Kernel kernel)
P3M grid interpolation.
ESPRESSO_ATTR_ALWAYS_INLINE void kokkos_parallel_range_for(auto const &name, auto start, auto end, auto const &kernel)
Wrapper for Kokkos::parallel_for that skips fork/join when the number of threads is 1.
constexpr int p3m_min_cao
Minimal charge assignment order.
Definition math.hpp:48
constexpr int p3m_max_cao
Maximal charge assignment order.
Definition math.hpp:50
#define P3M_BRILLOUIN
P3M: Number of Brillouin zones taken into account in the calculation of the optimal influence functio...
Definition math.hpp:38
System & get_system()
VectorXd< 9 > Vector9d
Definition Vector.hpp:210
T product(Vector< T, N > const &v)
Definition Vector.hpp:379
VectorXd< 2 > Vector2d
Definition Vector.hpp:206
VectorXd< 3 > Vector3d
Definition Vector.hpp:207
DEVICE_QUALIFIER constexpr T sqr(T x)
Calculates the SQuaRe of x.
Definition sqr.hpp:28
DEVICE_QUALIFIER constexpr T int_pow(T x)
Calculate integer powers.
Definition int_pow.hpp:34
VectorXi< 3 > Vector3i
Definition Vector.hpp:216
decltype(auto) integral_parameter(T i, Args &&...args)
Generate a call table for an integral non-type template parameter.
DEVICE_QUALIFIER auto sinc(T x)
Calculate the function .
Definition math.hpp:71
auto get_analytic_cotangent_sum_kernel(int cao)
Definition math.hpp:146
STL namespace.
Exports for the NpT code.
Common functions for dipolar and charge P3M.
void influence_function_r2c(auto &g_function, auto const &global_size, auto const &local_size, auto const &local_origin)
Adapt an influence function grid for real-to-complex FFTs.
auto constexpr P3M_EPSILON_METALLIC
This value indicates metallic boundary conditions.
double calc_surface_term(bool force_flag, bool energy_flag) override
void init() override
void dipole_assign() override
Utils::Vector9d long_range_pressure() override
Reciprocal-space virial for the dipolar Ewald/P3M sum.
void calc_influence_function_energy() override
void scaleby_box_l() override
void calc_influence_function_force() override
DipolarP3MStateClass & dp3m
Dipolar P3M parameters.
void npt_add_virial_contribution(double virial) const override
double long_range_kernel(bool force_flag, bool energy_flag)
Compute the k-space part of forces and energies.
double calc_average_self_energy_k_space() const override
void calc_energy_correction() override
bool is_tuned() const noexcept override
Base class for the magnetostatics P3M algorithm.
FloatType value_type
void resize_heffte_buffers()
void sanity_checks_boxl() const
Checks for correctness of the k-space cutoff.
void sanity_checks_cell_structure() const
P3MParameters const & dp3m_params
Definition dp3m.hpp:55
void sanity_checks_periodicity() const
void sanity_checks_node_grid() const
Structure to hold P3M parameters and some dependent variables.
void operator()(auto &dp3m, double pref, int d_rs, CellStructure &cell_structure) const
void operator()(auto &dp3m, double pref, int d_rs, CellStructure &cell_structure) const