58#include "communication.hpp"
65#include "system/System.hpp"
74#include <boost/mpi/collectives/all_reduce.hpp>
75#include <boost/mpi/collectives/broadcast.hpp>
76#include <boost/mpi/collectives/reduce.hpp>
77#include <boost/mpi/communicator.hpp>
78#include <boost/range/combine.hpp>
79#include <boost/range/numeric.hpp>
81#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
82#include <Kokkos_Core.hpp>
92#include <initializer_list>
103template <
typename FloatType>
104std::complex<FloatType>
107 return std::complex<FloatType>(-z.imag() * k, z.real() * k);
110template <
typename FloatType>
111std::complex<FloatType>
114 return std::complex<FloatType>(z.real() * k, z.imag() * k);
119 return mesh[0u] % node_grid[0u] == 0 and mesh[1u] % node_grid[1u] == 0 and
120 mesh[2u] % node_grid[2u] == 0;
123template <
typename FloatType, Arch Architecture,
class FFTConfig>
125 FFTConfig>::count_charged_particles() {
127 std::size_t local_n = std::size_t{0u};
128 double local_q = 0.0;
129 double local_q2 = 0.0;
135 acc.local_q += p.q();
140 a.local_n += b.local_n;
141 a.local_q += b.local_q;
142 a.local_q2 += b.local_q2;
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,
151 p3m.square_sum_q =
Utils::sqr(p3m.square_sum_q);
163template <
typename FloatType, Arch Architecture,
class FFTConfig>
165 FFTConfig>::calc_influence_function_force() {
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) {
171 influence_function_r2c<FFTConfig::r2c_dir>(p3m.g_force, p3m.params.mesh,
172 p3m.fft->ks_local_size(),
173 p3m.fft->ks_local_ld_index());
180template <
typename FloatType, Arch Architecture,
class FFTConfig>
182 FFTConfig>::calc_influence_function_energy() {
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) {
188 influence_function_r2c<FFTConfig::r2c_dir>(p3m.g_energy, p3m.params.mesh,
189 p3m.fft->ks_local_size(),
190 p3m.fft->ks_local_ld_index());
202 auto constexpr exp_min = -708.4;
203 auto const factor1 =
Utils::sqr(std::numbers::pi * alpha_L_i);
211 mesh_start, mesh_stop, indices,
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);
219 alias2 += energy * ex * (shift * nm) / norm_sq;
221 [&](
unsigned dim,
int n) {
222 nm[dim] = shift[dim] + n * mesh[dim];
226 return std::make_pair(alias1, alias2);
240 std::size_t n_c_part,
double sum_q2,
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);
262 int cao, std::size_t n_c_part,
double sum_q2,
267 auto const alpha_L_i = 1. / alpha_L;
268 auto const mesh_stop = mesh / 2;
269 auto const mesh_start = -mesh_stop;
275 mesh_start, mesh_stop, indices,
277 if ((indices[0] != 0) or (indices[1] != 0) or (indices[2] != 0)) {
278 auto const n2 = indices.norm2();
280 auto const [alias1, alias2] =
282 auto const d = alias1 -
Utils::sqr(alias2 / cs) / n2;
290 [&values, &mesh_i, cotangent_sum](
unsigned dim,
int n) {
291 values[dim] = cotangent_sum(n, mesh_i[dim]);
294 return 2. * pref * sum_q2 * sqrt(he_q /
static_cast<double>(n_c_part)) /
295 (box_l[1] * box_l[2]);
298template <
typename FloatType, Arch Architecture,
class FFTConfig>
302 assert(p3m.params.alpha > 0.);
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();
309 p3m.params.cao3 = Utils::int_pow<3>(p3m.params.cao);
310 p3m.params.recalc_a_ai_cao_cut(box_geo.length());
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;
320 p3m.local_mesh.calc_local_ca_mesh(p3m.params, local_geo, skin, elc_layer);
321 p3m.fft = std::make_shared<P3MFFT<FloatType, FFTConfig>>(
322 ::comm_cart, p3m.params.mesh, p3m.local_mesh.ld_no_halo,
324 auto const rs_array_size =
326 auto const rs_array_size_no_halo =
327 static_cast<std::size_t
>(
Utils::product(p3m.local_mesh.dim_no_halo));
328 auto const fft_mesh_size =
329 static_cast<std::size_t
>(
Utils::product(p3m.fft->ks_local_size()));
330 p3m.rs_charge_density.resize(rs_array_size);
331 p3m.ks_charge_density.resize(fft_mesh_size);
332 for (
auto d : {0u, 1u, 2u}) {
333 p3m.ks_E_fields[d].resize(fft_mesh_size);
334 p3m.rs_E_fields[d].resize(rs_array_size);
335 p3m.rs_E_fields_no_halo[d].resize(rs_array_size_no_halo);
337 p3m.calc_differential_operator();
342 count_charged_particles();
351 p3m_interpolate(p3m.local_mesh, weights, [q, &p3m](
int ind,
double w) {
352 p3m.rs_charge_density[ind] += value_type(w * q);
359 auto const weights = p3m_calculate_interpolation_weights<cao, memory_order>(
360 real_pos, p3m.params.ai, p3m.local_mesh);
361 inter_weights.
store(weights);
362 this->operator()(p3m, q, weights);
367 auto const weights = p3m_calculate_interpolation_weights<cao, memory_order>(
368 real_pos, p3m.params.ai, p3m.local_mesh);
369 this->operator()(p3m, q, weights);
372#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
377 auto const &aosoa = cell_structure.get_aosoa();
378 auto const n_part = cell_structure.count_local_particles();
381 "InterpolateCharges", std::size_t{0u}, n_part, [&](
auto p_index) {
382 auto const tid = omp_get_thread_num();
383 auto const pos = aosoa.get_vector_at(aosoa.position, p_index);
384 auto const q = aosoa.charge(p_index);
386 p3m_calculate_interpolation_weights<cao, memory_order>(
387 pos, p3m.params.ai, p3m.local_mesh);
388 p3m.inter_weights.store_at(p_index, weights);
390 p3m.local_mesh, weights, [&, tid, q](
int ind,
double w) {
391 p3m.rs_charge_density_kokkos(tid, ind) += value_type(w * q);
395 using execution_space = Kokkos::DefaultExecutionSpace;
396 int num_threads = execution_space().concurrency();
397 Kokkos::RangePolicy<execution_space> policy(std::size_t{0},
398 p3m.local_mesh.size);
399 Kokkos::parallel_for(
"ReduceInterpolatedCharges", policy,
400 [&p3m, num_threads](std::size_t
const i) {
402 for (
int tid = 0; tid < num_threads; ++tid) {
403 acc += p3m.rs_charge_density_kokkos(tid, i);
405 p3m.rs_charge_density.at(i) += acc;
410 void operator()(
auto &p3m,
auto const &p_q_pos_range) {
411 for (
auto zipped : p_q_pos_range) {
412 auto const p_q = boost::get<0>(zipped);
414 auto const &p_pos = boost::get<1>(zipped);
415 this->operator()(p3m, p_q, p_pos, p3m.inter_weights);
423template <
typename FloatType, Arch Architecture,
class FFTConfig>
426 prepare_fft_mesh(
true);
428#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
429 Utils::integral_parameter<int, AssignCharge, p3m_min_cao, p3m_max_cao>(
430 p3m.params.cao, p3m, *get_system().cell_structure);
435 Utils::integral_parameter<int, AssignCharge, p3m_min_cao, p3m_max_cao>(
436 p3m.params.cao, p3m, boost::combine(p_q_range, p_pos_range));
440template <
typename FloatType, Arch Architecture,
class FFTConfig>
444 Utils::integral_parameter<int, AssignCharge, p3m_min_cao, p3m_max_cao>(
445 p3m.params.cao, p3m, q, real_pos);
447 Utils::integral_parameter<int, AssignCharge, p3m_min_cao, p3m_max_cao>(
448 p3m.params.cao, p3m, q, real_pos, p3m.inter_weights);
455#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
458 auto const &p_q_force_range
462 assert(cao == p3m.inter_weights.cao());
464 auto const kernel = [&p3m](
auto pref,
auto &p_force, std::size_t p_index) {
465 auto const weights = p3m.inter_weights.template load<cao>(p_index);
469 [&force, &p3m](
int ind,
double w) {
470 force[0u] += w * double(p3m.rs_E_fields[0u][ind]);
471 force[1u] += w * double(p3m.rs_E_fields[1u][ind]);
472 force[2u] += w * double(p3m.rs_E_fields[2u][ind]);
475#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
476 auto const thread_id = omp_get_thread_num();
477 p_force(p_index, thread_id, 0) -= pref * force[0];
478 p_force(p_index, thread_id, 1) -= pref * force[1];
479 p_force(p_index, thread_id, 2) -= pref * force[2];
481 p_force -= pref * force;
485#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
486 auto const n_part = cell_structure.count_local_particles();
487 auto const &aosoa = cell_structure.get_aosoa();
488 auto &local_force = cell_structure.get_local_force();
490 "AssignForces", std::size_t{0u}, n_part, [&](std::size_t p_index) {
491 if (
auto const pref = aosoa.charge(p_index) * force_prefac) {
492 kernel(pref, local_force, p_index);
497 std::size_t p_index{0ul};
499 for (
auto zipped : p_q_force_range) {
500 auto p_q = boost::get<0>(zipped);
502 auto &p_force = boost::get<1>(zipped);
503 kernel(p_q * force_prefac, p_force, p_index);
512#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
514 auto const &cs,
auto const &box_geo) {
515 auto const local_dip = reduce_over_local_particles<Utils::Vector3d>(
518 acc += p.
q() * box_geo.unfolded_position(p.
pos(), p.
image_box());
521 return boost::mpi::all_reduce(comm, local_dip, std::plus<>());
525 auto const &p_q_unfolded_pos_range) {
526 auto const local_dip =
529 auto const p_q = boost::get<0>(q_pos);
530 auto const &p_unfolded_pos = boost::get<1>(q_pos);
531 return dip + p_q * p_unfolded_pos;
533 return boost::mpi::all_reduce(comm, local_dip, std::plus<>());
537template <
typename FloatType, Arch Architecture,
class FFTConfig>
539 FFTConfig>::kernel_ks_charge_density() {
541 p3m.halo_comm.gather_grid(
comm_cart, p3m.rs_charge_density.data(),
545 auto charge_density_no_halos =
546 extract_block<Utils::MemoryOrder::ROW_MAJOR, FFTConfig::r_space_order>(
547 p3m.rs_charge_density, p3m.local_mesh.dim, p3m.local_mesh.n_halo_ld,
548 p3m.local_mesh.dim - p3m.local_mesh.n_halo_ur);
554 p3m.fft->forward(charge_density_no_halos.data(),
555 p3m.ks_charge_density.data());
558template <
typename FloatType, Arch Architecture,
class FFTConfig>
560 FFTConfig>::kernel_rs_electric_field() {
561 auto const mesh_start = p3m.fft->ks_local_ld_index();
562 auto const mesh_stop = p3m.fft->ks_local_ur_index();
566 auto const wavevector =
570 for_each_3d_lin<FFTConfig::k_space_order>(
571 mesh_start, mesh_stop,
573#ifdef ESPRESSO_ADDITIONAL_CHECKS
574 assert(local_index ==
575 Utils::get_linear_index<FFTConfig::k_space_order>(
576 indices - mesh_start, p3m.fft->ks_local_size()));
579 p3m.ks_charge_density[local_index], p3m.g_force[local_index]);
581 for (
auto d : {0u, 1u, 2u}) {
583 auto const k = FloatType(p3m.d_op[d][indices[d]]) * wavevector[d];
585 p3m.ks_E_fields[d][local_index] =
591 auto const size = p3m.local_mesh.ur_no_halo - p3m.local_mesh.ld_no_halo;
593 for (
auto d : {0u, 1u, 2u}) {
594 auto k_space = p3m.ks_E_fields[d].data();
595 auto r_space = p3m.rs_E_fields_no_halo[d].data();
596 p3m.fft->backward(k_space, r_space);
599 auto const begin = p3m.rs_E_fields_no_halo[d].begin();
603 std::span(begin, rs_mesh_size_no_halo), p3m.local_mesh.dim_no_halo,
604 p3m.local_mesh.n_halo_ld, p3m.local_mesh.n_halo_ur);
608 std::array<FloatType *, 3u> rs_fields = {{p3m.rs_E_fields[0u].data(),
609 p3m.rs_E_fields[1u].data(),
610 p3m.rs_E_fields[2u].data()}};
611 p3m.halo_comm.spread_grid(
comm_cart, rs_fields, p3m.local_mesh.dim);
619template <
typename FloatType, Arch Architecture,
class FFTConfig>
623 auto const &box_geo = *get_system().
box_geo;
626 if (p3m.sum_q2 > 0.) {
628 kernel_ks_charge_density();
630 auto constexpr r2c_dir = FFTConfig::r2c_dir;
632 auto const &global_size = p3m.params.mesh;
633 auto const local_size = p3m.fft->ks_local_size();
634 auto const local_origin = p3m.fft->ks_local_ld_index();
635 auto const half_alpha_inv_sq =
Utils::sqr(1. / 2. / p3m.params.alpha);
636 auto const wavevector = (2. * std::numbers::pi) * box_geo.length_inv();
637 auto const cutoff_left = 1 - local_origin[r2c_dir];
638 auto const cutoff_right = global_size[r2c_dir] / 2 - local_origin[r2c_dir];
640 auto &short_dim = local_index[r2c_dir];
642 std::size_t index = 0u;
643 for_each_3d_order<FFTConfig::k_space_order>(
644 mesh_start, local_size, local_index, [&]() {
645 if (short_dim <= cutoff_right) {
646 auto const global_index = local_index + local_origin;
647 auto const kx = p3m.d_op[0u][global_index[0u]] * wavevector[0u];
648 auto const ky = p3m.d_op[1u][global_index[1u]] * wavevector[1u];
649 auto const kz = p3m.d_op[2u][global_index[2u]] * wavevector[2u];
655 static_cast<double>(p3m.g_energy[index] *
656 std::norm(p3m.ks_charge_density[index]));
657 if (short_dim >= cutoff_left and short_dim <= cutoff_right - 1) {
665 auto const vterm = -2. * (1. / norm_sq + half_alpha_inv_sq);
666 auto const pref = cell_energy * vterm;
667 diagonal += cell_energy;
668 node_k_space_pressure_tensor[0u] += pref * kx * kx;
669 node_k_space_pressure_tensor[1u] += pref * kx * ky;
670 node_k_space_pressure_tensor[2u] += pref * kx * kz;
671 node_k_space_pressure_tensor[4u] += pref * ky * ky;
672 node_k_space_pressure_tensor[5u] += pref * ky * kz;
673 node_k_space_pressure_tensor[8u] += pref * kz * kz;
679 node_k_space_pressure_tensor[0u] += diagonal;
680 node_k_space_pressure_tensor[4u] += diagonal;
681 node_k_space_pressure_tensor[8u] += diagonal;
682 node_k_space_pressure_tensor[3u] = node_k_space_pressure_tensor[1u];
683 node_k_space_pressure_tensor[6u] = node_k_space_pressure_tensor[2u];
684 node_k_space_pressure_tensor[7u] = node_k_space_pressure_tensor[5u];
687 return node_k_space_pressure_tensor * prefactor / (2. * box_geo.volume());
690template <
typename FloatType, Arch Architecture,
class FFTConfig>
692 bool force_flag,
bool energy_flag,
ParticleRange const &particles) {
694 auto const &system = get_system();
695 auto const &box_geo = *system.box_geo;
697 auto const npt_flag = force_flag and system.has_npt_enabled();
699 auto constexpr npt_flag =
false;
701 if (p3m.sum_qpart == 0u) {
705 if (not has_actor_of_type<ElectrostaticLayerCorrection>(
706 system.coulomb.impl->solver)) {
710 kernel_ks_charge_density();
712#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
713 auto &cell_structure = *system.cell_structure;
714 auto const &local_force = cell_structure.get_local_force();
715 auto const &aosoa = cell_structure.get_aosoa();
719 auto p_unfolded_pos_range =
726#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
730 boost::combine(p_q_range,
731 p_unfolded_pos_range)))
734 auto const volume = box_geo.volume();
736 4. * std::numbers::pi / volume / (2. * p3m.params.epsilon + 1.);
741 kernel_rs_electric_field();
744 auto const force_prefac = prefactor / volume;
745#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
746 auto &particle_data = cell_structure;
748 auto const particle_data = boost::combine(p_q_range, p_force_range);
750 Utils::integral_parameter<int, AssignForces, p3m_min_cao, p3m_max_cao>(
751 p3m.params.cao, p3m, force_prefac, particle_data);
756 auto const dm = prefactor * pref * box_dipole.value();
757#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
758 auto const n_part = cell_structure.count_local_particles();
760 "AssignForcesBoxDipole", std::size_t{0u}, n_part,
761 [&aosoa, &local_force, dm](
auto p_index) {
762 auto const thread_id = omp_get_thread_num();
763 auto const q = aosoa.charge(p_index);
764 local_force(p_index, thread_id, 0) -= q * dm[0];
765 local_force(p_index, thread_id, 1) -= q * dm[1];
766 local_force(p_index, thread_id, 2) -= q * dm[2];
769 for (
auto zipped : boost::combine(p_q_range, p_force_range)) {
770 auto p_q = boost::get<0>(zipped);
771 auto &p_force = boost::get<1>(zipped);
779 if (energy_flag or npt_flag) {
780 auto constexpr r2c_dir = FFTConfig::r2c_dir;
782 auto const &global_size = p3m.params.mesh;
783 auto const local_size = p3m.fft->ks_local_size();
784 auto const local_origin = p3m.fft->ks_local_ld_index();
785 auto const cutoff_left = 1 - local_origin[r2c_dir];
786 auto const cutoff_right = global_size[r2c_dir] / 2 - local_origin[r2c_dir];
788 auto &short_dim = local_index[r2c_dir];
789 auto node_energy = 0.;
790 std::size_t index = 0u;
791 for_each_3d_order<FFTConfig::k_space_order>(
792 mesh_start, local_size, local_index, [&]() {
793 if (short_dim <= cutoff_right) {
794 auto const &cell_field = p3m.ks_charge_density[index];
795 auto cell_energy =
static_cast<double>(p3m.g_energy[index] *
796 std::norm(cell_field));
797 if (short_dim >= cutoff_left and short_dim <= cutoff_right - 1) {
800 cell_energy += cell_energy;
802 node_energy += cell_energy;
806 node_energy /= 2. * volume;
809 boost::mpi::reduce(
::comm_cart, node_energy, energy, std::plus<>(), 0);
813 energy -= p3m.sum_q2 * p3m.params.alpha * std::numbers::inv_sqrtpi;
816 energy -= p3m.square_sum_q * std::numbers::pi /
821 energy += pref * box_dipole.value().norm2();
830 if (not energy_flag) {
838template <
typename FloatType, Arch Architecture,
class FFTConfig>
842 double m_mesh_density_min = -1., m_mesh_density_max = -1.;
844 bool m_tune_mesh =
false;
845 std::pair<std::optional<int>, std::optional<int>> m_tune_limits;
851 auto constexpr memory_order = FFTConfig::k_space_order;
860 double prefactor,
int timings,
861 decltype(m_tune_limits) tune_limits)
863 m_tune_limits{
std::move(tune_limits)} {}
870 auto const on_gpu = Architecture ==
Arch::CUDA;
872 auto const on_gpu =
false;
874 m_logger = std::make_unique<TuningLogger>(
875 verbose and
this_node == 0, (on_gpu) ?
"CoulombP3MGPU" :
"CoulombP3M",
882 std::optional<std::string>
885 if (
auto actor = get_actor_by_type<ElectrostaticLayerCorrection>(solver)) {
886 return actor->veto_r_cut(r_cut);
899 auto valid_decomposition =
false;
905 return Utils::Vector3i{{std::max(lhs[0u], rhs[0u]),
906 std::max(lhs[1u], rhs[1u]),
907 std::max(lhs[2u], rhs[2u])}};
910 if constexpr (FFTConfig::use_r2c) {
912 mesh_size_k_space[FFTConfig::r2c_dir] -= 1;
913 mesh_size_k_space[FFTConfig::r2c_dir] *= 2;
918 valid_decomposition =
919 (mesh_size_r_space[0u] == mesh_size_k_space[KX] and
920 mesh_size_r_space[1u] == mesh_size_k_space[KY] and
921 mesh_size_r_space[2u] == mesh_size_k_space[KZ] and
924 boost::mpi::broadcast(
::comm_cart, valid_decomposition, 0);
925 std::optional<std::string> retval{
"conflict with FFT domain decomposition"};
926 if (valid_decomposition) {
927 retval = std::nullopt;
932 std::tuple<double, double, double, double>
934 double r_cut_iL)
const override {
936 auto const &box_geo = *m_system.box_geo;
937 double alpha_L, rs_err, ks_err;
941 p3m.
sum_q2, 0., box_geo.length());
945 alpha_L = sqrt(log(std::numbers::sqrt2 * rs_err / p3m.
params.
accuracy)) /
956 p3m.
sum_q2, alpha_L, box_geo.length());
962 p3m.
sum_q2, alpha_L, box_geo.length().data());
964 boost::mpi::broadcast(
comm_cart, ks_err, 0);
968 p3m.
sum_q2, alpha_L, box_geo.length());
974 auto const &box_geo = *m_system.box_geo;
975 auto const mesh_density =
976 static_cast<double>(p3m.
params.
mesh[0]) * box_geo.length_inv()[0];
980 auto const normalized_box_dim = std::cbrt(box_geo.volume());
981 auto const max_npart_per_dim = 512.;
985 auto const min_npart_per_dim = std::min(
986 max_npart_per_dim, std::cbrt(
static_cast<double>(p3m.
sum_qpart)));
987 m_mesh_density_min = min_npart_per_dim / normalized_box_dim;
988 m_mesh_density_max = max_npart_per_dim / normalized_box_dim;
989 if (m_tune_limits.first or m_tune_limits.second) {
990 auto const &box_l = box_geo.length();
991 auto const dim = std::max({box_l[0], box_l[1], box_l[2]});
992 if (m_tune_limits.first) {
993 m_mesh_density_min =
static_cast<double>(*m_tune_limits.first) / dim;
995 if (m_tune_limits.second) {
996 m_mesh_density_max =
static_cast<double>(*m_tune_limits.second) / dim;
1001 m_mesh_density_min = m_mesh_density_max = mesh_density;
1005 for (
auto i : {1u, 2u}) {
1007 static_cast<int>(std::round(mesh_density * box_geo.length()[i]));
1012 m_logger->report_fixed_mesh(p3m.
params.
mesh);
1017 auto const &box_geo = *m_system.box_geo;
1018 auto const &solver = m_system.coulomb.impl->solver;
1020 auto time_best = time_sentinel;
1021 auto mesh_density = m_mesh_density_min;
1024 for (
auto i : {0u, 1u, 2u}) {
1026 static_cast<int>(std::round(box_geo.length()[i] * mesh_density));
1028 current_mesh[i] += current_mesh[i] % 2;
1032 while (mesh_density <= m_mesh_density_max) {
1034 trial_params.
mesh = current_mesh;
1035 trial_params.cao = cao_best;
1036 trial_params.cao = cao_best;
1038 auto const trial_time =
1039 get_m_time(trial_params.mesh, trial_params.cao, trial_params.r_cut_iL,
1040 trial_params.alpha_L, trial_params.accuracy);
1042 if (trial_time >= 0.) {
1045 if (has_actor_of_type<CoulombP3M>(solver)) {
1046 m_r_cut_iL_max = trial_params.r_cut_iL;
1049 if (trial_time < time_best) {
1052 tuned_params = trial_params;
1053 time_best = tuned_params.time = trial_time;
1054 }
else if (trial_time > time_best + time_granularity or
1055 get_n_trials() > max_n_consecutive_trials) {
1062 mesh_density = current_mesh[0] / box_geo.length()[0];
1067 return tuned_params;
1071template <
typename FloatType, Arch Architecture,
class FFTConfig>
1073 auto &system = get_system();
1074 auto const &box_geo = *system.
box_geo;
1081 if (not is_tuned()) {
1082 count_charged_particles();
1084 throw std::runtime_error(
1085 "CoulombP3M: no charged particles in the system");
1089 system, p3m, prefactor, tuning.timings, tuning.limits);
1109 auto const &box_geo = *system.
box_geo;
1110 auto const &local_geo = *system.
local_geo;
1111 for (
auto i = 0u; i < 3u; i++) {
1114 std::stringstream msg;
1116 <<
" is larger than half of box dimension " << box_geo.length()[i];
1117 throw std::runtime_error(msg.str());
1120 std::stringstream msg;
1122 <<
" is larger than local box dimension " << local_geo.length()[i];
1123 throw std::runtime_error(msg.str());
1128 if ((box_geo.length()[0] != box_geo.length()[1]) or
1129 (box_geo.length()[1] != box_geo.length()[2]) or
1132 throw std::runtime_error(
1133 "CoulombP3M: non-metallic epsilon requires cubic box");
1140 if (!box_geo.periodic(0) or !box_geo.periodic(1) or !box_geo.periodic(2)) {
1141 throw std::runtime_error(
1142 "CoulombP3M: requires periodicity (True, True, True)");
1147 auto const &local_geo = *
get_system().local_geo;
1150 throw std::runtime_error(
1151 "CoulombP3M: requires the regular or hybrid decomposition cell system");
1155 throw std::runtime_error(
1156 "CoulombP3M: does not work with the hybrid decomposition cell system, "
1157 "if using more than one MPI node");
1161template <
typename FloatType, Arch Architecture,
class FFTConfig>
1163 auto const &box_geo = *get_system().
box_geo;
1168 sanity_checks_boxl();
1169 calc_influence_function_force();
1170 calc_influence_function_energy();
1175template <
typename FloatType, Arch Architecture,
class FFTConfig>
1184 static_cast<void>(particles);
1187 auto &gpu = get_system().
gpu;
1199template <
typename FloatType, Arch Architecture,
class FFTConfig>
1202 auto &system = get_system();
1203 if (has_actor_of_type<ElectrostaticLayerCorrection>(
1212template <
typename FloatType, Arch Architecture,
class FFTConfig>
1215 auto &gpu_particle_data = get_system().
gpu;
@ HYBRID
Hybrid decomposition.
@ REGULAR
Regular decomposition.
Vector implementation and trait types for boost qvm interoperability.
Describes a cell structure / cell system.
void determine_mesh_limits() override
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)
constexpr std::tuple< int, int, int > get_memory_layout() const
std::optional< std::string > fft_decomposition_veto(Utils::Vector3i const &mesh_size_r_space) const override
P3MParameters & get_params() override
void enable_property(std::size_t property)
std::size_t n_particles() const
std::shared_ptr< LocalBox > local_geo
void npt_add_virial_contribution(double energy)
bool has_npt_enabled() const
std::shared_ptr< BoxGeometry > box_geo
Tuning algorithm for P3M.
System::System & m_system
void determine_cao_limits(int initial_cao)
Determine a sensible range for the charge assignment order.
void determine_r_cut_limits()
Determine a sensible range for the real-space cutoff.
std::unique_ptr< TuningLogger > m_logger
DEVICE_QUALIFIER constexpr pointer data() noexcept
static DEVICE_QUALIFIER constexpr Vector< T, N > broadcast(typename Base::value_type const &value) noexcept
Create a vector that has all entries set to the same value.
Cache for interpolation weights.
void zfill(std::size_t size)
Fill cache with zero-initialized data.
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.
void charge_assign(elc_data const &elc, CoulombP3M &solver, combined_ranges const &p_q_pos_range)
ELC algorithm for long-range Coulomb interactions.
This file contains the errorhandling code for severe errors, like a broken bond or illegal parameter ...
auto pad_with_zeros_discard_imag(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.
and std::invocable< Projector, unsigned, int > 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.
std::vector< FloatType > grid_influence_function(P3MParameters const ¶ms, Utils::Vector3i const &n_start, Utils::Vector3i const &n_stop, Utils::Vector3d const &inv_box_l)
Map influence function over a grid.
void p3m_interpolate(P3MLocalMesh const &local_mesh, WeightsStorage< cao > const &weights, Kernel kernel)
P3M grid interpolation.
constexpr int p3m_min_cao
Minimal charge assignment order.
constexpr int p3m_max_cao
Maximal charge assignment order.
#define P3M_BRILLOUIN
P3M: Number of Brillouin zones taken into account in the calculation of the optimal influence functio...
auto charge_range(ParticleRange const &particles)
auto pos_range(ParticleRange const &particles)
auto force_range(ParticleRange const &particles)
auto unfolded_pos_range(ParticleRange const &particles, BoxGeometry const &box)
std::function< void(ResultType &, ResultType const &)> ReductionOp
Join two partial reduction results.
std::function< void(ResultType &, Particle const &)> AddPartialResultKernel
Kernel that adds the result from a single particle to a reduction.
T product(Vector< T, N > const &v)
DEVICE_QUALIFIER constexpr T sqr(T x)
Calculates the SQuaRe of x.
DEVICE_QUALIFIER auto sinc(T x)
Calculate the function .
auto get_analytic_cotangent_sum_kernel(int cao)
Exports for the NpT code.
auto constexpr P3M_EPSILON_METALLIC
This value indicates metallic boundary conditions.
P3M algorithm for long-range Coulomb interaction.
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)
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 (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)
ResultType reduce_over_local_particles(CellStructure const &cs, Reduction::AddPartialResultKernel< ResultType > add_partial, Reduction::ReductionOp< ResultType > reduce_op)
performs a reduction over all particles
ESPRESSO_ATTR_ALWAYS_INLINE void kokkos_parallel_range_for(auto const &name, auto start, auto end, auto const &kernel)
Utils::Vector3i node_grid
void charge_assign(ParticleRange const &particles) override
void assign_charge(double q, Utils::Vector3d const &real_pos, bool skip_cache) override
double long_range_kernel(bool force_flag, bool energy_flag, ParticleRange const &particles)
Compute the k-space part of forces and energies.
void add_long_range_forces_gpu(ParticleRange const &particles)
Utils::Vector9d long_range_pressure(ParticleRange const &particles) override
void scaleby_box_l() override
Base class for the electrostatics P3M algorithm.
std::size_t sum_qpart
number of charged particles.
std::shared_ptr< P3MFFT< FloatType, FFTConfig > > fft
p3m_send_mesh< FloatType > halo_comm
double sum_q2
Sum of square of charges.
p3m_interpolation_cache inter_weights
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
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.
void recalc_ld_pos(P3MParameters const ¶ms)
Recalculate quantities derived from the mesh and box length: ld_pos (position of the left down mesh).
Structure to hold P3M parameters and some dependent variables.
Utils::Vector3d cao_cut
cutoff for charge assignment.
double alpha
unscaled alpha_L for use with fast inline functions only
double r_cut_iL
cutoff radius for real space electrostatics (>0), rescaled to r_cut_iL = r_cut * box_l_i.
int cao
charge assignment order ([0,7]).
double accuracy
accuracy of the actual parameter set.
double alpha_L
Ewald splitting parameter (0.
double r_cut
unscaled r_cut_iL for use with fast inline functions only
void recalc_a_ai_cao_cut(Utils::Vector3d const &box_l)
Recalculate quantities derived from the mesh and box length: a, ai and cao_cut.
bool tuning
tuning or production?
Utils::Vector3i mesh
number of mesh points per coordinate direction (>0), in real space.
double epsilon
epsilon of the "surrounding dielectric".
P3MParameters params
P3M base parameters.
P3MLocalMesh local_mesh
Local mesh geometry information for this MPI rank.
Struct holding all information for one particle.
auto const & image_box() const
void operator()(auto &p3m, double q, InterpolationWeights< cao > const &weights)
void operator()(auto &p3m, auto &cell_structure)
void operator()(auto &p3m, double q, Utils::Vector3d const &real_pos)
void operator()(auto &p3m, double q, Utils::Vector3d const &real_pos, p3m_interpolation_cache &inter_weights)
void operator()(auto &p3m, auto force_prefac, CellStructure &cell_structure) const