ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
p3m.impl.definitions.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_P3M
25
28
31#ifdef ESPRESSO_CUDA
34#endif // ESPRESSO_CUDA
36
37#include "electrostatics/p3m.impl.hpp" // must be included after coulomb.hpp
38
39#include "p3m/P3MFFT.hpp"
42#include "p3m/TuningLogger.hpp"
44#include "p3m/for_each_3d.hpp"
46#include "p3m/math.hpp"
47
48#include "BoxGeometry.hpp"
49#include "LocalBox.hpp"
50#include "Particle.hpp"
52#include "PropagationMode.hpp"
53#include "actor/visitors.hpp"
54#include "aosoa_pack.hpp"
58#include "communication.hpp"
59#include "errorhandling.hpp"
61#include "kokkos_helpers.hpp"
62#include "npt.hpp"
63#include "p3m/send_mesh.hpp"
66#include "system/System.hpp"
67#include "tuning.hpp"
68
69#include <utils/Vector.hpp>
72#include <utils/math/sqr.hpp>
74
75#include <boost/mpi/collectives/all_reduce.hpp>
76#include <boost/mpi/collectives/broadcast.hpp>
77#include <boost/mpi/collectives/reduce.hpp>
78#include <boost/mpi/communicator.hpp>
79#include <boost/range/combine.hpp>
80#include <boost/range/numeric.hpp>
81
82#include <Kokkos_Core.hpp>
83#include <Kokkos_ScatterView.hpp>
84
85#include <algorithm>
86#include <array>
87#include <cassert>
88#include <complex>
89#include <cstddef>
90#include <functional>
91#include <initializer_list>
92#include <numbers>
93#include <optional>
94#include <span>
95#include <sstream>
96#include <stdexcept>
97#include <string>
98#include <tuple>
99#include <type_traits>
100#include <utility>
101#include <vector>
102
103template <typename FloatType>
104std::complex<FloatType>
105multiply_complex_by_imaginary(std::complex<FloatType> const &z, FloatType k) {
106 // Perform the multiplication manually: (re + i*imag) * (i*k)
107 return std::complex<FloatType>(-z.imag() * k, z.real() * k);
108}
109
110template <typename FloatType>
111std::complex<FloatType>
112multiply_complex_by_real(std::complex<FloatType> const &z, FloatType k) {
113 // Perform the multiplication manually: (re + i*imag) * k
114 return std::complex<FloatType>(z.real() * k, z.imag() * k);
115}
116
118 Utils::Vector3i const &mesh) {
119 return mesh[0u] % node_grid[0u] == 0 and mesh[1u] % node_grid[1u] == 0 and
120 mesh[2u] % node_grid[2u] == 0;
121}
122
123template <typename FloatType, Arch Architecture, class FFTConfig>
124void CoulombP3MImpl<FloatType, Architecture,
126 struct Res {
127 std::size_t local_n = std::size_t{0u};
128 double local_q = 0.0;
129 double local_q2 = 0.0;
130 };
131 auto kernel = [](Res &acc, auto const &p) {
132 if (p.q() != 0.0) {
133 acc.local_n++;
134 acc.local_q2 += Utils::sqr(p.q());
135 acc.local_q += p.q();
136 }
137 };
138
139 auto reduce = [](Res &a, Res const &b) {
140 a.local_n += b.local_n;
141 a.local_q += b.local_q;
142 a.local_q2 += b.local_q2;
143 };
144 auto res = reduce_over_local_particles<Res>(*(get_system().cell_structure),
145 kernel, reduce);
146
147 boost::mpi::all_reduce(comm_cart, res.local_n, p3m.sum_qpart, std::plus<>());
148 boost::mpi::all_reduce(comm_cart, res.local_q2, p3m.sum_q2, std::plus<>());
149 boost::mpi::all_reduce(comm_cart, res.local_q, p3m.square_sum_q,
150 std::plus<>());
151 p3m.square_sum_q = Utils::sqr(p3m.square_sum_q);
152}
153
154/** Calculate the optimal influence function of @cite hockney88a.
155 * (optimised for force calculations)
156 *
157 * Each node calculates only the values for its domain in k-space.
158 *
159 * See also: @cite hockney88a eq. 8-22 (p. 275). Note the somewhat
160 * different convention for the prefactors, which is described in
161 * @cite deserno98a @cite deserno98b.
162 */
163template <typename FloatType, Arch Architecture, class FFTConfig>
164void CoulombP3MImpl<FloatType, Architecture,
166 p3m.g_force = grid_influence_function<FloatType, 1, P3M_BRILLOUIN,
167 FFTConfig::k_space_order>(
168 p3m.params, p3m.fft->ks_local_ld_index(), p3m.fft->ks_local_ur_index(),
169 get_system().box_geo->length_inv());
170 if constexpr (FFTConfig::use_r2c) {
172 p3m.fft->ks_local_size(),
173 p3m.fft->ks_local_ld_index());
174 }
175}
176
177/** Calculate the influence function optimized for the energy and the
178 * self energy correction.
179 */
180template <typename FloatType, Arch Architecture, class FFTConfig>
181void CoulombP3MImpl<FloatType, Architecture,
183 p3m.g_energy = grid_influence_function<FloatType, 0, P3M_BRILLOUIN,
184 FFTConfig::k_space_order>(
185 p3m.params, p3m.fft->ks_local_ld_index(), p3m.fft->ks_local_ur_index(),
186 get_system().box_geo->length_inv());
187 if constexpr (FFTConfig::use_r2c) {
189 p3m.fft->ks_local_size(),
190 p3m.fft->ks_local_ld_index());
191 }
192}
193
194/** Aliasing sum used by @ref p3m_k_space_error. */
196 Utils::Vector3i const &mesh,
197 Utils::Vector3d const &mesh_i, int cao,
198 double alpha_L_i) {
199
200 auto constexpr mesh_start = Utils::Vector3i::broadcast(-P3M_BRILLOUIN);
201 auto constexpr mesh_stop = Utils::Vector3i::broadcast(P3M_BRILLOUIN + 1);
202 auto constexpr exp_min = -708.4; // for IEEE-compatible double
203 auto const factor1 = Utils::sqr(std::numbers::pi * alpha_L_i);
204 auto alias1 = 0.;
205 auto alias2 = 0.;
206
207 Utils::Vector3i indices{};
208 Utils::Vector3i nm{};
209 Utils::Vector3d fnm{};
211 mesh_start, mesh_stop, indices,
212 [&]() {
213 auto const norm_sq = nm.norm2();
214 auto const exponent = -factor1 * norm_sq;
215 auto const exp_limit = (exp_min + std::log(norm_sq)) / 2.;
216 auto const ex = (exponent < exp_limit) ? 0. : std::exp(exponent);
217 auto const energy = std::pow(Utils::product(fnm), 2 * cao);
218 alias1 += Utils::sqr(ex) / norm_sq;
219 alias2 += energy * ex * (shift * nm) / norm_sq;
220 },
221 [&](unsigned dim, int n) {
222 nm[dim] = shift[dim] + n * mesh[dim];
223 fnm[dim] = math::sinc(nm[dim] * mesh_i[dim]);
224 });
225
226 return std::make_pair(alias1, alias2);
227}
228
229/** Calculate the real space contribution to the rms error in the force (as
230 * described by Kolafa and Perram).
231 * \param pref Prefactor of Coulomb interaction.
232 * \param r_cut_iL rescaled real space cutoff for p3m method.
233 * \param n_c_part number of charged particles in the system.
234 * \param sum_q2 sum of square of charges in the system
235 * \param alpha_L rescaled Ewald splitting parameter.
236 * \param box_l box dimensions.
237 * \return real space error
238 */
239inline double p3m_real_space_error(double pref, double r_cut_iL,
240 std::size_t n_c_part, double sum_q2,
241 double alpha_L,
242 Utils::Vector3d const &box_l) {
243 auto const volume = Utils::product(box_l);
244 return (2. * pref * sum_q2 * exp(-Utils::sqr(r_cut_iL * alpha_L))) /
245 sqrt(static_cast<double>(n_c_part) * r_cut_iL * box_l[0] * volume);
246}
247
248/** Calculate the analytic expression of the error estimate for the
249 * P3M method in @cite hockney88a (eq. 8-23 p. 275) in
250 * order to obtain the rms error in the force for a system of N
251 * randomly distributed particles in a cubic box (k-space part).
252 * \param pref Prefactor of Coulomb interaction.
253 * \param mesh number of mesh points in one direction.
254 * \param cao charge assignment order.
255 * \param n_c_part number of charged particles in the system.
256 * \param sum_q2 sum of square of charges in the system
257 * \param alpha_L rescaled Ewald splitting parameter.
258 * \param box_l box dimensions.
259 * \return reciprocal (k) space error
260 */
261inline double p3m_k_space_error(double pref, Utils::Vector3i const &mesh,
262 int cao, std::size_t n_c_part, double sum_q2,
263 double alpha_L, Utils::Vector3d const &box_l) {
264
265 auto const cotangent_sum = math::get_analytic_cotangent_sum_kernel(cao);
266 auto const mesh_i = 1. / Utils::Vector3d(mesh);
267 auto const alpha_L_i = 1. / alpha_L;
268 auto const mesh_stop = mesh / 2;
269 auto const mesh_start = -mesh_stop;
270 auto indices = Utils::Vector3i{};
271 auto values = Utils::Vector3d{};
272 auto he_q = 0.;
273
275 mesh_start, mesh_stop, indices,
276 [&]() {
277 if ((indices[0] != 0) or (indices[1] != 0) or (indices[2] != 0)) {
278 auto const n2 = indices.norm2();
279 auto const cs = Utils::product(values);
280 auto const [alias1, alias2] =
281 p3m_tune_aliasing_sums(indices, mesh, mesh_i, cao, alpha_L_i);
282 auto const d = alias1 - Utils::sqr(alias2 / cs) / n2;
283 /* at high precision, d can become negative due to extinction;
284 also, don't take values that have no significant digits left*/
285 if (d > 0. and std::fabs(d / alias1) > round_error_prec) {
286 he_q += d;
287 }
288 }
289 },
290 [&values, &mesh_i, cotangent_sum](unsigned dim, int n) {
291 values[dim] = cotangent_sum(n, mesh_i[dim]);
292 });
293
294 return 2. * pref * sum_q2 * sqrt(he_q / static_cast<double>(n_c_part)) /
295 (box_l[1] * box_l[2]);
296}
297
298template <typename FloatType, Arch Architecture, class FFTConfig>
300 assert(p3m.params.mesh >= Utils::Vector3i::broadcast(1));
301 assert(p3m.params.cao >= p3m_min_cao and p3m.params.cao <= p3m_max_cao);
302 assert(p3m.params.alpha > 0.);
303
304 auto const &system = get_system();
305 auto const &box_geo = *system.box_geo;
306 auto const &local_geo = *system.local_geo;
307 auto const skin = system.cell_structure->get_verlet_skin();
308
309 p3m.params.cao3 = Utils::int_pow<3>(p3m.params.cao);
310 p3m.params.recalc_a_ai_cao_cut(box_geo.length());
311
313
314 auto const &solver = system.coulomb.impl->solver;
315 double elc_layer = 0.;
316 if (auto actor = get_actor_by_type<ElectrostaticLayerCorrection>(solver)) {
317 elc_layer = actor->elc.space_layer;
318 }
319
320 p3m.local_mesh.calc_local_ca_mesh(p3m.params, local_geo, skin, elc_layer);
321 std::shared_ptr<P3MFFTBackend<FloatType, FFTConfig>> fft_backend;
322 // The kokkos-fft backend serves only the row-major r2c config on the CPU;
323 // the factory additionally requires kokkos-fft support to be compiled in
324 // and a single MPI rank, and returns nullptr otherwise. The factory is
325 // defined once inside the espresso_p3m target, so backend selection is
326 // identical in every translation unit that instantiates this solver.
327 if constexpr (Architecture == Arch::CPU and
328 std::is_same_v<FFTConfig, P3MFFTKokkosConfig>) {
330 ::comm_cart, p3m.params.mesh, p3m.local_mesh.ld_no_halo,
331 p3m.local_mesh.ur_no_halo, ::communicator.node_grid);
332 }
333 if (not fft_backend) {
334 fft_backend = std::make_shared<P3MFFTHeffte<FloatType, FFTConfig>>(
335 ::comm_cart, p3m.params.mesh, p3m.local_mesh.ld_no_halo,
336 p3m.local_mesh.ur_no_halo, ::communicator.node_grid, 3u);
337 }
338 p3m.fft = std::move(fft_backend);
339 auto const rs_array_size =
340 static_cast<std::size_t>(Utils::product(p3m.local_mesh.dim));
341 auto const rs_array_size_no_halo =
342 static_cast<std::size_t>(Utils::product(p3m.local_mesh.dim_no_halo));
343 auto const fft_mesh_size =
344 static_cast<std::size_t>(Utils::product(p3m.fft->ks_local_size()));
345 p3m.rs_charge_density.resize(rs_array_size);
346 p3m.ks_charge_density.resize(fft_mesh_size);
347 p3m.rs_E_fields_no_halo_batched.resize(3ul * rs_array_size_no_halo);
348 p3m.ks_E_fields_batched.resize(3ul * fft_mesh_size);
349 for (auto d : {0u, 1u, 2u}) {
350 p3m.ks_E_fields[d] = {p3m.ks_E_fields_batched.data() + d * fft_mesh_size,
351 fft_mesh_size};
352 p3m.rs_E_fields[d].resize(rs_array_size);
353 p3m.rs_E_fields_no_halo[d] = {p3m.rs_E_fields_no_halo_batched.data() +
354 d * rs_array_size_no_halo,
355 rs_array_size_no_halo};
356 }
357 p3m.calc_differential_operator();
358
359 /* fix box length dependent constants */
361
363}
364
365namespace {
366template <int cao> struct AssignCharge {
367 void operator()(auto &p3m, double q,
368 InterpolationWeights<cao> const &weights) {
369 using CoulombP3MState = std::remove_reference_t<decltype(p3m)>;
370 using value_type = CoulombP3MState::value_type;
371 p3m_interpolate(p3m.local_mesh, weights, [q, &p3m](int ind, double w) {
372 p3m.rs_charge_density[ind] += value_type(w * q);
373 });
374 }
375
376 void operator()(auto &p3m, double q, Utils::Vector3d const &real_pos,
377 p3m_interpolation_cache &inter_weights) {
378 auto constexpr memory_order = Utils::MemoryOrder::ROW_MAJOR;
380 real_pos.as_span(), p3m.params.ai, p3m.local_mesh);
381 inter_weights.store(weights);
382 this->operator()(p3m, q, weights);
383 }
384
385 void operator()(auto &p3m, double q, Utils::Vector3d const &real_pos) {
386 auto constexpr memory_order = Utils::MemoryOrder::ROW_MAJOR;
388 real_pos.as_span(), p3m.params.ai, p3m.local_mesh);
389 this->operator()(p3m, q, weights);
390 }
391
392 void operator()(auto &p3m, auto &cell_structure) {
393 using CoulombP3MState = std::remove_reference_t<decltype(p3m)>;
394 using value_type = CoulombP3MState::value_type;
395 using execution_space = Kokkos::DefaultHostExecutionSpace;
396 auto const &aosoa = cell_structure.get_aosoa();
397 auto const n_part = cell_structure.count_local_particles();
398 p3m.inter_weights.zfill(n_part); // allocate buffer for parallel write
400 "InterpolateCharges", std::size_t{0u}, n_part, [&](auto p_index) {
401 auto constexpr memory_order = Utils::MemoryOrder::ROW_MAJOR;
402 auto const tid = omp_get_thread_num();
403 auto const pos = aosoa.get_span_at(aosoa.position, p_index);
404 auto const q = aosoa.charge(p_index);
405 auto const weights =
407 pos, p3m.params.ai, p3m.local_mesh);
408 p3m.inter_weights.store_at(p_index, weights);
410 p3m.local_mesh, weights, [&, tid, q](int ind, double w) {
411 p3m.rs_charge_density_kokkos(tid, ind) += value_type(w * q);
412 });
413 });
414 Kokkos::fence();
415 auto const num_threads = execution_space().concurrency();
416 if (num_threads > 1) {
418 "ReduceInterpolatedCharges", std::size_t{0}, p3m.local_mesh.size,
419 [&p3m, num_threads](std::size_t const i) {
420 value_type acc{};
421 for (int tid = 0; tid < num_threads; ++tid) {
422 acc += p3m.rs_charge_density_kokkos(tid, i);
423 }
424 p3m.rs_charge_density.at(i) = acc;
425 });
426 Kokkos::fence();
427 } else {
428 std::copy_n(p3m.rs_charge_density_kokkos.data(), p3m.local_mesh.size,
429 p3m.rs_charge_density.begin());
430 }
431 }
432};
433} // namespace
434
435template <typename FloatType, Arch Architecture, class FFTConfig>
442
443template <typename FloatType, Arch Architecture, class FFTConfig>
445 double q, Utils::Vector3d const &real_pos, bool skip_cache) {
446 if (skip_cache) {
448 p3m.params.cao, p3m, q, real_pos);
449 } else {
451 p3m.params.cao, p3m, q, real_pos, p3m.inter_weights);
452 }
453}
454
455namespace {
456template <int cao> struct AssignForces {
457 void operator()(auto &p3m, auto force_prefac,
458 CellStructure &cell_structure) const {
459
460 assert(cao == p3m.inter_weights.cao());
461 using execution_space = Kokkos::DefaultHostExecutionSpace;
462
463 auto const kernel = [&p3m](auto pref, auto &p_force, std::size_t p_index) {
464 auto const weights = p3m.inter_weights.template load<cao>(p_index);
465
466 Utils::Vector3d force{};
467 p3m_interpolate(p3m.local_mesh, weights,
468 [&force, &p3m](int ind, double w) {
469 force[0u] += w * double(p3m.rs_E_fields[0u][ind]);
470 force[1u] += w * double(p3m.rs_E_fields[1u][ind]);
471 force[2u] += w * double(p3m.rs_E_fields[2u][ind]);
472 });
473
474 auto access = p_force.access();
475 access(p_index, 0) -= pref * force[0];
476 access(p_index, 1) -= pref * force[1];
477 access(p_index, 2) -= pref * force[2];
478 };
479
480 auto const n_part = cell_structure.count_local_particles();
481 auto const &aosoa = cell_structure.get_aosoa();
482 auto scatter_force = cell_structure.get_scatter_force();
484 "AssignForces", std::size_t{0u}, n_part, [&](std::size_t p_index) {
485 if (auto const pref = aosoa.charge(p_index) * force_prefac) {
486 kernel(pref, scatter_force, p_index);
487 }
488 });
489 }
490};
491} // namespace
492
493inline auto calc_dipole_moment(boost::mpi::communicator const &comm,
494 auto const &cs, auto const &box_geo) {
496 cs,
497 [&box_geo](Utils::Vector3d &acc, Particle const &p) {
498 acc += p.q() * box_geo.unfolded_position(p.pos(), p.image_box());
499 },
500 [](Utils::Vector3d &a, Utils::Vector3d const &b) { a = a + b; });
501 return boost::mpi::all_reduce(comm, local_dip, std::plus<>());
502}
503
504template <typename FloatType, Arch Architecture, class FFTConfig>
505void CoulombP3MImpl<FloatType, Architecture,
506 FFTConfig>::kernel_ks_charge_density() {
507 // halo communication of real space charge density
508 p3m.halo_comm.gather_grid(comm_cart, p3m.rs_charge_density.data(),
509 p3m.local_mesh.dim);
510
511 // Extract the real-space charge density without ghost layers straight into
512 // the FFT backend's own input buffer, so a backend that can transform in
513 // place (kokkos-fft) does so without an extra copy.
514 auto *const fft_input = p3m.fft->forward_input_buffer();
516 fft_input, p3m.rs_charge_density, p3m.local_mesh.dim,
517 p3m.local_mesh.n_halo_ld, p3m.local_mesh.dim - p3m.local_mesh.n_halo_ur);
518
519 // Set up the FFT using the Heffte library.
520 // This is in global mesh coordinates without any ghost layers
521 // The memory layout has to be specified, so the parts of
522 // the mesh held by each MPI rank are assembled correctly.
523 p3m.fft->forward(fft_input, p3m.ks_charge_density.data());
524}
525
526template <typename FloatType, Arch Architecture, class FFTConfig>
527void CoulombP3MImpl<FloatType, Architecture,
528 FFTConfig>::kernel_rs_electric_field() {
529 auto const mesh_start = p3m.fft->ks_local_ld_index();
530 auto const mesh_stop = p3m.fft->ks_local_ur_index();
531 auto const &box_geo = *get_system().box_geo;
532
533 // i*k differentiation
534 auto const wavevector =
535 Utils::Vector3<FloatType>((2. * std::numbers::pi) * box_geo.length_inv());
536
537 // compute electric field, Eq. (3.49) @cite deserno00b
539 mesh_start, mesh_stop,
540 [&](Utils::Vector3i const &indices, int local_index) {
541#ifdef ESPRESSO_ADDITIONAL_CHECKS
542 assert(local_index ==
544 indices - mesh_start, p3m.fft->ks_local_size()));
545#endif
546 auto const phi_hat = multiply_complex_by_real(
547 p3m.ks_charge_density[local_index], p3m.g_force[local_index]);
548
549 for (auto d : {0u, 1u, 2u}) {
550 // wave vector of the current mesh point
551 auto const k = FloatType(p3m.d_op[d][indices[d]]) * wavevector[d];
552 // electric field in k-space
553 p3m.ks_E_fields[d][local_index] =
555 }
556 });
557
558 // back-transform the k-space electric field to real space
559 auto const size = p3m.local_mesh.ur_no_halo - p3m.local_mesh.ld_no_halo;
560 auto const rs_mesh_size_no_halo = Utils::product(size);
561 p3m.fft->backward_batch(3u, p3m.ks_E_fields_batched.data(),
562 p3m.rs_E_fields_no_halo_batched.data());
563 for (auto d : {0u, 1u, 2u}) {
564 // add zeros around the E-field in real space to make room for ghost
565 // layers, writing straight into the persistent halo-sized buffer (no
566 // per-step allocation, only the halo shells are zeroed)
567 auto const begin = p3m.rs_E_fields_no_halo[d].begin();
568 assert(p3m.rs_E_fields[d].size() ==
569 static_cast<std::size_t>(Utils::product(p3m.local_mesh.dim)));
570 pad_with_zeros_discard_imag_into<FFTConfig::r_space_order,
572 p3m.rs_E_fields[d].data(), std::span(begin, rs_mesh_size_no_halo),
573 p3m.local_mesh.dim_no_halo, p3m.local_mesh.n_halo_ld,
574 p3m.local_mesh.n_halo_ur);
575 }
576
577 // ghost communicate the boundary layers of the E-field in real space
578 std::array<FloatType *, 3u> rs_fields = {{p3m.rs_E_fields[0u].data(),
579 p3m.rs_E_fields[1u].data(),
580 p3m.rs_E_fields[2u].data()}};
581 p3m.halo_comm.spread_grid(comm_cart, rs_fields, p3m.local_mesh.dim);
582}
583
584/** @details Calculate the long range electrostatics part of the pressure
585 * tensor. This is part \f$\Pi_{\textrm{rec}, \alpha, \beta}\f$ eq. (2.7)
586 * in @cite essmann95a. The part \f$\Pi_{\textrm{corr}, \alpha, \beta}\f$
587 * eq. (2.8) is not present here since M is the empty set in our simulations.
588 */
589template <typename FloatType, Arch Architecture, class FFTConfig>
592 auto const &box_geo = *get_system().box_geo;
593 Utils::Vector9d node_k_space_pressure_tensor{};
594
595 if (p3m.sum_q2 > 0.) {
597 kernel_ks_charge_density();
598
599 auto constexpr r2c_dir = FFTConfig::r2c_dir;
600 auto constexpr mesh_start = Utils::Vector3i::broadcast(0);
601 auto const &global_size = p3m.params.mesh;
602 auto const local_size = p3m.fft->ks_local_size();
603 auto const local_origin = p3m.fft->ks_local_ld_index();
604 auto const half_alpha_inv_sq = Utils::sqr(1. / 2. / p3m.params.alpha);
605 auto const wavevector = (2. * std::numbers::pi) * box_geo.length_inv();
606 auto const cutoff_left = 1 - local_origin[r2c_dir];
607 auto const cutoff_right = global_size[r2c_dir] / 2 - local_origin[r2c_dir];
608 auto local_index = Utils::Vector3i::broadcast(0);
609 auto &short_dim = local_index[r2c_dir];
610 auto diagonal = 0.;
611 std::size_t index = 0u;
613 mesh_start, local_size, local_index, [&]() {
614 if (short_dim <= cutoff_right) {
615 auto const global_index = local_index + local_origin;
616 auto const kx = p3m.d_op[0u][global_index[0u]] * wavevector[0u];
617 auto const ky = p3m.d_op[1u][global_index[1u]] * wavevector[1u];
618 auto const kz = p3m.d_op[2u][global_index[2u]] * wavevector[2u];
619 auto const norm_sq =
620 Utils::sqr(kx) + Utils::sqr(ky) + Utils::sqr(kz);
621
622 if (norm_sq != 0.) {
623 auto cell_energy =
624 static_cast<double>(p3m.g_energy[index] *
625 std::norm(p3m.ks_charge_density[index]));
626 if (short_dim >= cutoff_left and short_dim <= cutoff_right - 1) {
627 // k-space symmetry: double counting except in the first and
628 // last planes of the short dimension; although the wavevector
629 // points in the opposite direction in the redundant region of
630 // k-space, the product of two components of the wavevector
631 // cancels out the negative sign
632 cell_energy *= 2.;
633 }
634 auto const vterm = -2. * (1. / norm_sq + half_alpha_inv_sq);
635 auto const pref = cell_energy * vterm;
636 diagonal += cell_energy;
637 node_k_space_pressure_tensor[0u] += pref * kx * kx; /* sigma_xx */
638 node_k_space_pressure_tensor[1u] += pref * kx * ky; /* sigma_xy */
639 node_k_space_pressure_tensor[2u] += pref * kx * kz; /* sigma_xz */
640 node_k_space_pressure_tensor[4u] += pref * ky * ky; /* sigma_yy */
641 node_k_space_pressure_tensor[5u] += pref * ky * kz; /* sigma_yz */
642 node_k_space_pressure_tensor[8u] += pref * kz * kz; /* sigma_zz */
643 }
644 }
645 ++index;
646 });
647
648 node_k_space_pressure_tensor[0u] += diagonal;
649 node_k_space_pressure_tensor[4u] += diagonal;
650 node_k_space_pressure_tensor[8u] += diagonal;
651 node_k_space_pressure_tensor[3u] = node_k_space_pressure_tensor[1u];
652 node_k_space_pressure_tensor[6u] = node_k_space_pressure_tensor[2u];
653 node_k_space_pressure_tensor[7u] = node_k_space_pressure_tensor[5u];
654 }
655
656 return node_k_space_pressure_tensor * prefactor / (2. * box_geo.volume());
657}
658
659template <typename FloatType, Arch Architecture, class FFTConfig>
661 bool force_flag, bool energy_flag) {
662
663 auto const &system = get_system();
664 auto const &box_geo = *system.box_geo;
665#ifdef ESPRESSO_NPT
666 auto const npt_flag = force_flag and system.has_npt_enabled();
667#else
668 auto constexpr npt_flag = false;
669#endif
670 if (p3m.sum_qpart == 0u) {
671 return 0.;
672 }
673 auto &cell_structure = *system.cell_structure;
674
676 system.coulomb.impl->solver)) {
678 }
679
680 kernel_ks_charge_density();
681
682 auto scatter_force = system.cell_structure->get_scatter_force();
683 auto const &aosoa = cell_structure.get_aosoa();
684
685 // The dipole moment is only needed if we don't have metallic boundaries
686 auto const box_dipole = (p3m.params.epsilon != P3M_EPSILON_METALLIC)
687 ? std::make_optional(calc_dipole_moment(
688 comm_cart, cell_structure, box_geo))
689 : std::nullopt;
690 auto const volume = box_geo.volume();
691 auto const pref =
692 4. * std::numbers::pi / volume / (2. * p3m.params.epsilon + 1.);
693 auto energy = 0.;
694
695 /* === k-space force calculation === */
696 if (force_flag) {
697 kernel_rs_electric_field();
698
699 // assign particle forces
700 auto const force_prefac = prefactor / volume;
701 auto &particle_data = cell_structure;
703 p3m.params.cao, p3m, force_prefac, particle_data);
704
705 // add dipole forces
706 // Eq. (3.19) @cite deserno00b
707 if (box_dipole) {
708 using execution_space = Kokkos::DefaultHostExecutionSpace;
709 auto const dm = prefactor * pref * box_dipole.value();
710 auto const n_part = cell_structure.count_local_particles();
712 "AssignForcesBoxDipole", std::size_t{0u}, n_part,
713 [&aosoa, &scatter_force, dm](auto p_index) {
714 auto access = scatter_force.access();
715 auto const q = aosoa.charge(p_index);
716 access(p_index, 0) -= q * dm[0];
717 access(p_index, 1) -= q * dm[1];
718 access(p_index, 2) -= q * dm[2];
719 });
720 }
721 }
722
723 /* === k-space energy calculation === */
724 if (energy_flag or npt_flag) {
725 auto constexpr r2c_dir = FFTConfig::r2c_dir;
726 auto constexpr mesh_start = Utils::Vector3i::broadcast(0);
727 auto const &global_size = p3m.params.mesh;
728 auto const local_size = p3m.fft->ks_local_size();
729 auto const local_origin = p3m.fft->ks_local_ld_index();
730 auto const cutoff_left = 1 - local_origin[r2c_dir];
731 auto const cutoff_right = global_size[r2c_dir] / 2 - local_origin[r2c_dir];
732 auto local_index = Utils::Vector3i::broadcast(0);
733 auto &short_dim = local_index[r2c_dir];
734 auto node_energy = 0.;
735 std::size_t index = 0u;
737 mesh_start, local_size, local_index, [&]() {
738 if (short_dim <= cutoff_right) {
739 auto const &cell_field = p3m.ks_charge_density[index];
740 auto cell_energy = static_cast<double>(p3m.g_energy[index] *
741 std::norm(cell_field));
742 if (short_dim >= cutoff_left and short_dim <= cutoff_right - 1) {
743 // leverage symmetry of k-space: double counting except in the
744 // first and last planes of the short dimension
745 cell_energy += cell_energy;
746 }
747 node_energy += cell_energy;
748 }
749 ++index;
750 });
751 node_energy /= 2. * volume;
752
753 // add up energy contributions from all mpi ranks
754 boost::mpi::reduce(::comm_cart, node_energy, energy, std::plus<>(), 0);
755 if (this_node == 0) {
756 /* self energy correction */
757 // Eq. (3.8) @cite deserno00b
758 energy -= p3m.sum_q2 * p3m.params.alpha * std::numbers::inv_sqrtpi;
759 /* net charge correction */
760 // Eq. (3.11) @cite deserno00b
761 energy -= p3m.square_sum_q * std::numbers::pi /
762 (2. * volume * Utils::sqr(p3m.params.alpha));
763 /* dipole correction */
764 // Eq. (3.9) @cite deserno00b
765 if (box_dipole) {
766 energy += pref * box_dipole.value().norm2();
767 }
768 }
769 energy *= prefactor;
770#ifdef ESPRESSO_NPT
771 if (npt_flag) {
772 get_system().npt_add_virial_contribution(energy);
773 }
774#endif
775 if (not energy_flag) {
776 energy = 0.;
777 }
778 }
779
780 return energy;
781}
782
783template <typename FloatType, Arch Architecture, class FFTConfig>
785 using CoulombP3MStateClass =
787 CoulombP3MStateClass &p3m;
788 double m_mesh_density_min = -1., m_mesh_density_max = -1.;
789 // indicates if mesh should be tuned
790 bool m_tune_mesh = false;
791 std::pair<std::optional<int>, std::optional<int>> m_tune_limits;
792
793protected:
794 P3MParameters &get_params() override { return p3m.params; }
795
796 static constexpr std::tuple<int, int, int> get_memory_layout() {
797 using enum Utils::MemoryOrder;
798 auto constexpr memory_order = FFTConfig::k_space_order;
799 auto constexpr layout_col_major = std::tuple(2, 1, 0);
800 auto constexpr layout_row_major = std::tuple(0, 1, 2);
801 return (memory_order == COLUMN_MAJOR) ? layout_col_major : layout_row_major;
802 }
803
804public:
805 CoulombTuningAlgorithm(System::System &system, auto &input_p3m,
806 double prefactor, int timings,
807 decltype(m_tune_limits) tune_limits)
808 : TuningAlgorithm(system, prefactor, timings), p3m{input_p3m},
809 m_tune_limits{std::move(tune_limits)} {}
810
811 void on_solver_change() const override { m_system.on_coulomb_change(); }
812
813 void setup_logger(bool verbose) override {
814 auto const &box_geo = *m_system.box_geo;
815#ifdef ESPRESSO_CUDA
816 auto const on_gpu = Architecture == Arch::CUDA;
817#else
818 auto const on_gpu = false;
819#endif
820 m_logger = std::make_unique<TuningLogger>(
821 verbose and this_node == 0, (on_gpu) ? "CoulombP3MGPU" : "CoulombP3M",
823 m_logger->tuning_goals(p3m.params.accuracy, m_prefactor,
824 box_geo.length()[0], p3m.sum_qpart, p3m.sum_q2);
825 m_logger->log_tuning_start();
826 }
827
828 std::optional<std::string>
829 layer_correction_veto_r_cut(double r_cut) const override {
830 auto const &solver = m_system.coulomb.impl->solver;
831 if (auto actor = get_actor_by_type<ElectrostaticLayerCorrection>(solver)) {
832 return actor->veto_r_cut(r_cut);
833 }
834 return {};
835 }
836
837 std::optional<std::string> fft_decomposition_veto(
838 Utils::Vector3i const &mesh_size_r_space) const override {
839#ifdef ESPRESSO_CUDA
840 if constexpr (Architecture == Arch::CUDA) {
841 return std::nullopt;
842 }
843#endif
844 assert(p3m.fft != nullptr);
845 auto const [KX, KY, KZ] = get_memory_layout();
846 auto valid_decomposition = false;
847 // calculate box size in k-space
848 Utils::Vector3i mesh_size_k_space = {};
849 boost::mpi::reduce(
850 ::comm_cart, p3m.fft->ks_local_ur_index(), mesh_size_k_space,
851 [](Utils::Vector3i const &lhs, Utils::Vector3i const &rhs) {
852 return Utils::Vector3i{{std::max(lhs[0u], rhs[0u]),
853 std::max(lhs[1u], rhs[1u]),
854 std::max(lhs[2u], rhs[2u])}};
855 },
856 0);
857 if constexpr (FFTConfig::use_r2c) {
858 // adjust for reduced dimension
859 mesh_size_k_space[FFTConfig::r2c_dir] -= 1;
860 mesh_size_k_space[FFTConfig::r2c_dir] *= 2;
861 }
862 // check consistency with box size in real-space
863 if (::this_node == 0) {
864 auto const &node_grid = ::communicator.node_grid;
865 valid_decomposition =
866 (mesh_size_r_space[0u] == mesh_size_k_space[KX] and
867 mesh_size_r_space[1u] == mesh_size_k_space[KY] and
868 mesh_size_r_space[2u] == mesh_size_k_space[KZ] and
869 is_node_grid_compatible_with_mesh(node_grid, mesh_size_r_space));
870 }
871 boost::mpi::broadcast(::comm_cart, valid_decomposition, 0);
872 std::optional<std::string> retval{"conflict with FFT domain decomposition"};
873 if (valid_decomposition) {
874 retval = std::nullopt;
875 }
876 return retval;
877 }
878
879 std::tuple<double, double, double, double>
881 double r_cut_iL) const override {
882
883 auto const &box_geo = *m_system.box_geo;
884 double alpha_L, rs_err, ks_err;
885
886 /* calc maximal real space error for setting */
887 rs_err = p3m_real_space_error(m_prefactor, r_cut_iL, p3m.sum_qpart,
888 p3m.sum_q2, 0., box_geo.length());
889
890 if (std::numbers::sqrt2 * rs_err > p3m.params.accuracy) {
891 /* assume rs_err = ks_err -> rs_err = accuracy/sqrt(2.0) -> alpha_L */
892 alpha_L = sqrt(log(std::numbers::sqrt2 * rs_err / p3m.params.accuracy)) /
893 r_cut_iL;
894 } else {
895 /* even alpha=0 is ok, however, we cannot choose it since it kills the
896 k-space error formula.
897 Anyways, this very likely NOT the optimal solution */
898 alpha_L = 0.1;
899 }
900
901 /* calculate real-space and k-space error for this alpha_L */
902 rs_err = p3m_real_space_error(m_prefactor, r_cut_iL, p3m.sum_qpart,
903 p3m.sum_q2, alpha_L, box_geo.length());
904#ifdef ESPRESSO_CUDA
905 if constexpr (Architecture == Arch::CUDA) {
906 if (this_node == 0) {
907 ks_err =
908 p3m_k_space_error_gpu(m_prefactor, mesh.data(), cao, p3m.sum_qpart,
909 p3m.sum_q2, alpha_L, box_geo.length().data());
910 }
911 boost::mpi::broadcast(comm_cart, ks_err, 0);
912 } else
913#endif
914 ks_err = p3m_k_space_error(m_prefactor, mesh, cao, p3m.sum_qpart,
915 p3m.sum_q2, alpha_L, box_geo.length());
916
917 return {Utils::Vector2d{rs_err, ks_err}.norm(), rs_err, ks_err, alpha_L};
918 }
919
920 void determine_mesh_limits() override {
921 auto const &box_geo = *m_system.box_geo;
922 auto const mesh_density =
923 static_cast<double>(p3m.params.mesh[0]) * box_geo.length_inv()[0];
924
925 if (p3m.params.mesh == Utils::Vector3i::broadcast(-1)) {
926 /* avoid using more than 1 GB of FFT arrays */
927 auto const normalized_box_dim = std::cbrt(box_geo.volume());
928 auto const max_npart_per_dim = 512.;
929 /* simple heuristic to limit the tried meshes if the accuracy cannot
930 be obtained with smaller meshes, but normally not all these
931 meshes have to be tested */
932 auto const min_npart_per_dim = std::min(
933 max_npart_per_dim, std::cbrt(static_cast<double>(p3m.sum_qpart)));
934 m_mesh_density_min = min_npart_per_dim / normalized_box_dim;
935 m_mesh_density_max = max_npart_per_dim / normalized_box_dim;
936 if (m_tune_limits.first or m_tune_limits.second) {
937 auto const &box_l = box_geo.length();
938 auto const dim = std::max({box_l[0], box_l[1], box_l[2]});
939 if (m_tune_limits.first) {
940 m_mesh_density_min = static_cast<double>(*m_tune_limits.first) / dim;
941 }
942 if (m_tune_limits.second) {
943 m_mesh_density_max = static_cast<double>(*m_tune_limits.second) / dim;
944 }
945 }
946 m_tune_mesh = true;
947 } else {
948 m_mesh_density_min = m_mesh_density_max = mesh_density;
949 assert(p3m.params.mesh[0] >= 1);
950 if (p3m.params.mesh[1] == -1 and p3m.params.mesh[2] == -1) {
951 // determine the two missing values by rescaling by the box length
952 for (auto i : {1u, 2u}) {
953 p3m.params.mesh[i] =
954 static_cast<int>(std::round(mesh_density * box_geo.length()[i]));
955 // make the mesh even in all directions
956 p3m.params.mesh[i] += p3m.params.mesh[i] % 2;
957 }
958 }
959 m_logger->report_fixed_mesh(p3m.params.mesh);
960 }
961 }
962
964 auto const &box_geo = *m_system.box_geo;
965 auto const &solver = m_system.coulomb.impl->solver;
966 auto tuned_params = TuningAlgorithm::Parameters{};
967 auto time_best = time_sentinel;
968 auto mesh_density = m_mesh_density_min;
969 auto current_mesh = p3m.params.mesh;
970 if (m_tune_mesh) {
971 for (auto i : {0u, 1u, 2u}) {
972 current_mesh[i] =
973 static_cast<int>(std::round(box_geo.length()[i] * mesh_density));
974 // make the mesh even in all directions
975 current_mesh[i] += current_mesh[i] % 2;
976 }
977 }
978
979 while (mesh_density <= m_mesh_density_max) {
980 auto trial_params = TuningAlgorithm::Parameters{};
981 trial_params.mesh = current_mesh;
982 trial_params.cao = cao_best;
983 trial_params.cao = cao_best;
984
985 auto const trial_time =
986 get_m_time(trial_params.mesh, trial_params.cao, trial_params.r_cut_iL,
987 trial_params.alpha_L, trial_params.accuracy);
988
989 if (trial_time >= 0.) {
990 /* the optimum r_cut for this mesh is the upper limit for higher meshes,
991 everything else is slower */
992 if (has_actor_of_type<CoulombP3M>(solver)) {
993 m_r_cut_iL_max = trial_params.r_cut_iL;
994 }
995
996 if (trial_time < time_best) {
997 /* new optimum */
999 tuned_params = trial_params;
1000 time_best = tuned_params.time = trial_time;
1001 } else if (trial_time > time_best + time_granularity or
1003 /* no hope of further optimisation */
1004 break;
1005 }
1006 }
1007 if (m_tune_mesh) {
1008 current_mesh += Utils::Vector3i::broadcast(2);
1009 mesh_density = current_mesh[0] / box_geo.length()[0];
1010 } else {
1011 break;
1012 }
1013 }
1014 return tuned_params;
1015 }
1016};
1017
1018template <typename FloatType, Arch Architecture, class FFTConfig>
1020 auto &system = get_system();
1021 auto const &box_geo = *system.box_geo;
1022 if (p3m.params.alpha_L == 0. and p3m.params.alpha != 0.) {
1023 p3m.params.alpha_L = p3m.params.alpha * box_geo.length()[0];
1024 }
1025 if (p3m.params.r_cut_iL == 0. and p3m.params.r_cut != 0.) {
1026 p3m.params.r_cut_iL = p3m.params.r_cut * box_geo.length_inv()[0];
1027 }
1028 if (not is_tuned()) {
1030 if (p3m.sum_qpart == 0) {
1031 throw std::runtime_error(
1032 "CoulombP3M: no charged particles in the system");
1033 }
1034 try {
1036 system, p3m, prefactor, tuning.timings, tuning.limits);
1037 parameters.setup_logger(tuning.verbose);
1038 // parameter ranges
1039 parameters.determine_mesh_limits();
1040 parameters.determine_r_cut_limits();
1041 parameters.determine_cao_limits(7);
1042 // run tuning algorithm
1043 parameters.tune();
1044 m_is_tuned = true;
1045 system.on_coulomb_change();
1046 } catch (...) {
1047 p3m.params.tuning = false;
1048 throw;
1049 }
1050 }
1051 init();
1052}
1053
1055 auto const &system = get_system();
1056 auto const &box_geo = *system.box_geo;
1057 auto const &local_geo = *system.local_geo;
1058 for (auto i = 0u; i < 3u; i++) {
1059 /* check k-space cutoff */
1060 if (p3m_params.cao_cut[i] >= box_geo.length_half()[i]) {
1061 std::stringstream msg;
1062 msg << "P3M_init: k-space cutoff " << p3m_params.cao_cut[i]
1063 << " is larger than half of box dimension " << box_geo.length()[i];
1064 throw std::runtime_error(msg.str());
1065 }
1066 if (p3m_params.cao_cut[i] >= local_geo.length()[i]) {
1067 std::stringstream msg;
1068 msg << "P3M_init: k-space cutoff " << p3m_params.cao_cut[i]
1069 << " is larger than local box dimension " << local_geo.length()[i];
1070 throw std::runtime_error(msg.str());
1071 }
1072 }
1073
1074 if (p3m_params.epsilon != P3M_EPSILON_METALLIC) {
1075 if ((box_geo.length()[0] != box_geo.length()[1]) or
1076 (box_geo.length()[1] != box_geo.length()[2]) or
1077 (p3m_params.mesh[0] != p3m_params.mesh[1]) or
1078 (p3m_params.mesh[1] != p3m_params.mesh[2])) {
1079 throw std::runtime_error(
1080 "CoulombP3M: non-metallic epsilon requires cubic box");
1081 }
1082 }
1083}
1084
1086 auto const &box_geo = *get_system().box_geo;
1087 if (!box_geo.periodic(0) or !box_geo.periodic(1) or !box_geo.periodic(2)) {
1088 throw std::runtime_error(
1089 "CoulombP3M: requires periodicity (True, True, True)");
1090 }
1091}
1092
1094 auto const &local_geo = *get_system().local_geo;
1095 if (local_geo.cell_structure_type() != CellStructureType::REGULAR and
1096 local_geo.cell_structure_type() != CellStructureType::HYBRID) {
1097 throw std::runtime_error(
1098 "CoulombP3M: requires the regular or hybrid decomposition cell system");
1099 }
1100 if (::communicator.size > 1 and
1101 local_geo.cell_structure_type() == CellStructureType::HYBRID) {
1102 throw std::runtime_error(
1103 "CoulombP3M: does not work with the hybrid decomposition cell system, "
1104 "if using more than one MPI node");
1105 }
1106}
1107
1108template <typename FloatType, Arch Architecture, class FFTConfig>
1110 auto const &box_geo = *get_system().box_geo;
1111 p3m.params.r_cut = p3m.params.r_cut_iL * box_geo.length()[0];
1112 p3m.params.alpha = p3m.params.alpha_L * box_geo.length_inv()[0];
1113 p3m.params.recalc_a_ai_cao_cut(box_geo.length());
1114 p3m.local_mesh.recalc_ld_pos(p3m.params);
1118 p3m.halo_comm.resize(::comm_cart, p3m.local_mesh);
1119}
1120
1121#ifdef ESPRESSO_CUDA
1122template <typename FloatType, Arch Architecture, class FFTConfig>
1123void CoulombP3MImpl<FloatType, Architecture,
1125 if constexpr (Architecture == Arch::CUDA) {
1126#ifdef ESPRESSO_NPT
1127 if (get_system().has_npt_enabled()) {
1128 get_system().npt_add_virial_contribution(long_range_energy());
1129 }
1130#endif
1131 if (this_node == 0) {
1132 auto &gpu = *get_system().gpu;
1134 gpu.n_particles());
1135 }
1136 }
1137}
1138
1139/* Initialize the GPU force kernel and the CPU energy kernel.
1140 * This operation is time-consuming and sets up data members
1141 * that are only relevant for ELC force corrections, since the
1142 * GPU implementation uses CPU kernels to compute energies.
1143 */
1144template <typename FloatType, Arch Architecture, class FFTConfig>
1146 if constexpr (Architecture == Arch::CUDA) {
1147 auto &system = get_system();
1149 system.coulomb.impl->solver)) {
1151 }
1152 p3m_gpu_init(m_gpu_data, p3m.params.cao, p3m.params.mesh, p3m.params.alpha,
1153 system.box_geo->length(), system.gpu->n_particles());
1154 }
1155}
1156
1157template <typename FloatType, Arch Architecture, class FFTConfig>
1159 if constexpr (Architecture == Arch::CUDA) {
1160 auto &gpu_particle_data = *get_system().gpu;
1161 gpu_particle_data.enable_property(GpuParticleData::prop::force);
1162 gpu_particle_data.enable_property(GpuParticleData::prop::q);
1163 gpu_particle_data.enable_property(GpuParticleData::prop::pos);
1164 }
1165}
1166#endif // ESPRESSO_CUDA
1167
1168#endif // ESPRESSO_P3M
@ HYBRID
Hybrid decomposition.
@ REGULAR
Regular decomposition.
std::shared_ptr< P3MFFTBackend< FloatType, P3MFFTKokkosConfig > > make_p3m_kokkos_fft_backend(boost::mpi::communicator const &comm, Utils::Vector3i const &global_mesh, Utils::Vector3i const &rs_local_ld_index, Utils::Vector3i const &rs_local_ur_index, Utils::Vector3i const &node_grid)
Build the single-rank kokkos-fft backend (P3MFFTKokkos) when it can serve this run,...
Vector implementation and trait types for boost qvm interoperability.
Utils::Vector3d const & length() const
Box length.
Describes a cell structure / cell system.
std::size_t count_local_particles() const
std::optional< std::string > layer_correction_veto_r_cut(double r_cut) const override
TuningAlgorithm::Parameters get_time() override
void setup_logger(bool verbose) override
std::tuple< double, double, double, double > calculate_accuracy(Utils::Vector3i const &mesh, int cao, double r_cut_iL) const override
void on_solver_change() const override
CoulombTuningAlgorithm(System::System &system, auto &input_p3m, double prefactor, int timings, decltype(m_tune_limits) tune_limits)
static constexpr std::tuple< int, int, int > get_memory_layout()
std::optional< std::string > fft_decomposition_veto(Utils::Vector3i const &mesh_size_r_space) const override
P3MParameters & get_params() override
std::size_t n_particles() const
Main system class.
std::shared_ptr< LocalBox > local_geo
std::shared_ptr< GpuParticleData > gpu
Coulomb::Solver coulomb
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).
DEVICE_QUALIFIER constexpr pointer data() noexcept
Definition Array.hpp:133
constexpr std::span< const T, N > as_span() const noexcept
Definition Vector.hpp:156
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
Cache for interpolation weights.
void store(InterpolationWeights< cao > const &weights)
Push back weights for one point.
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
void charge_assign(elc_data const &elc, CoulombP3M &solver, auto const &cs)
Definition elc.cpp:1108
ELC algorithm for long-range Coulomb interactions.
This file contains the errorhandling code for severe errors, like a broken bond or illegal parameter ...
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.
void for_each_3d_lin(detail::IndexVectorConcept auto &&start, detail::IndexVectorConcept auto &&stop, auto &&kernel)
Run a kernel(index_3d, linear_index) over the given 3d range with given memory order.
std::vector< FloatType > grid_influence_function(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 int get_linear_index(int a, int b, int c, Vector3i const &adim)
Definition index.hpp:36
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
Vector< T, 3 > Vector3
Definition Vector.hpp:203
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.
MemoryOrder
Definition index.hpp:33
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.
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.
P3M algorithm for long-range Coulomb interaction.
double p3m_k_space_error(double pref, Utils::Vector3i const &mesh, int cao, std::size_t n_c_part, double sum_q2, double alpha_L, Utils::Vector3d const &box_l)
Calculate the analytic expression of the error estimate for the P3M method in hockney88a (eq.
std::complex< FloatType > multiply_complex_by_real(std::complex< FloatType > const &z, FloatType k)
auto p3m_tune_aliasing_sums(Utils::Vector3i const &shift, Utils::Vector3i const &mesh, Utils::Vector3d const &mesh_i, int cao, double alpha_L_i)
Aliasing sum used by p3m_k_space_error.
double p3m_real_space_error(double pref, double r_cut_iL, std::size_t n_c_part, double sum_q2, double alpha_L, Utils::Vector3d const &box_l)
Calculate the real space contribution to the rms error in the force (as described by Kolafa and Perra...
std::complex< FloatType > multiply_complex_by_imaginary(std::complex< FloatType > const &z, FloatType k)
auto calc_dipole_moment(boost::mpi::communicator const &comm, auto const &cs, auto const &box_geo)
bool is_node_grid_compatible_with_mesh(Utils::Vector3i const &node_grid, Utils::Vector3i const &mesh)
void p3m_gpu_add_farfield_force(P3MGpuParams &data, GpuParticleData &gpu, double prefactor, std::size_t n_part)
The long-range part of the P3M algorithm.
void p3m_gpu_init(std::shared_ptr< P3MGpuParams > &data, int cao, Utils::Vector3i const &mesh, double alpha, Utils::Vector3d const &box_l, std::size_t n_part)
Initialize the internal data structure of the P3M GPU.
P3M electrostatics on GPU.
double p3m_k_space_error_gpu(double prefactor, const int *mesh, int cao, int npart, double sum_q2, double alpha_L, const double *box)
ResultType reduce_over_local_particles(CellStructure const &cs, std::invocable< ResultType &, Particle const & > auto add_partial, std::invocable< ResultType &, ResultType const & > auto reduce_op)
Run a reduction over all particles.
Utils::Vector3i node_grid
void count_charged_particles() override
bool is_tuned() const noexcept override
Definition p3m.impl.hpp:174
CoulombP3MStateClass & p3m
Coulomb P3M parameters.
Definition p3m.impl.hpp:119
void init() override
Definition p3m.impl.hpp:152
void charge_assign() override
double long_range_energy() override
Definition p3m.impl.hpp:199
double long_range_kernel(bool force_flag, bool energy_flag)
Compute the k-space part of forces and energies.
Utils::Vector9d long_range_pressure() override
void scaleby_box_l() override
void calc_influence_function_force() override
Calculate the optimal influence function of hockney88a.
void assign_charge(double q, Utils::Vector3d const &real_pos, bool skip_cache) override
std::shared_ptr< P3MGpuParams > m_gpu_data
Definition p3m.impl.hpp:243
void prepare_fft_mesh(bool reset_weights, bool zero_rs) override
Definition p3m.impl.hpp:217
void calc_influence_function_energy() override
Calculate the influence function optimized for the energy and the self energy correction.
Base class for the electrostatics P3M algorithm.
Definition p3m.impl.hpp:64
FloatType value_type
Definition p3m.impl.hpp:66
void sanity_checks_periodicity() const
void sanity_checks_boxl() const
Checks for correctness of the k-space cutoff.
void sanity_checks_cell_structure() const
P3MParameters const & p3m_params
Definition p3m.hpp:56
void sanity_checks() const
Definition p3m.hpp:79
std::unique_ptr< Implementation > impl
Pointer-to-implementation.
static constexpr std::size_t force
static constexpr std::size_t pos
static constexpr std::size_t q
Interpolation weights for one point.
Structure to hold P3M parameters and some dependent variables.
Struct holding all information for one particle.
Definition Particle.hpp:436
constexpr auto const & pos() const
Definition Particle.hpp:476
constexpr auto const & image_box() const
Definition Particle.hpp:489
constexpr auto const & q() const
Definition Particle.hpp:597
void operator()(auto &p3m, double q, Utils::Vector3d const &real_pos, p3m_interpolation_cache &inter_weights)
void operator()(auto &p3m, double q, Utils::Vector3d const &real_pos)
void operator()(auto &p3m, double q, InterpolationWeights< cao > const &weights)
void operator()(auto &p3m, auto force_prefac, CellStructure &cell_structure) const
auto has_actor_of_type(Variant const &variant)
Check if an actor of a specific type is active, recursively.
Definition visitors.hpp:71
std::shared_ptr< Actor > get_actor_by_type(Variant const &variant)
Get an active actor of a specific type, recursively.
Definition visitors.hpp:46