ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
icc.cpp
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/** \file
23 * Functions to compute the electric field acting on the induced charges,
24 * excluding forces other than the electrostatic ones. Detailed information
25 * about the ICC* method is included in the corresponding header file
26 * \ref icc.hpp.
27 */
28
29#include <config/config.hpp>
30
31#ifdef ESPRESSO_ELECTROSTATICS
32
33#include "icc.hpp"
34
35#include "Particle.hpp"
36#include "PropagationMode.hpp"
37#include "actor/visitors.hpp"
39#include "communication.hpp"
43#include "errorhandling.hpp"
46#include "system/System.hpp"
47
48#include <boost/mpi/collectives/all_reduce.hpp>
49#include <boost/mpi/operations.hpp>
50
51#include <Kokkos_Core.hpp>
52#include <omp.h>
53
54#include <algorithm>
55#include <cmath>
56#include <cstddef>
57#include <limits>
58#include <numbers>
59#include <stdexcept>
60#include <variant>
61#include <vector>
62
63/** Calculate the electrostatic forces between source charges (= real charges)
64 * and wall charges. For each electrostatic method, the proper functions
65 * for short- and long-range parts are called. Long-range parts are calculated
66 * directly, short-range parts need helper functions according to the particle
67 * data organisation. This is a modified version of
68 * @ref System::System::calculate_forces.
69 */
70static void force_calc_icc(
71 CellStructure &cell_structure,
74 // reset forces
75 auto const reset_kernel = [](Particle &p) { p.force_and_torque() = {}; };
76 cell_structure.for_each_local_particle(reset_kernel);
77 cell_structure.for_each_ghost_particle(reset_kernel);
78 cell_structure.reset_local_force();
79
80 // calc ICC forces
81 cell_structure.non_bonded_loop(
82 [coulomb_kernel_ptr = get_ptr(coulomb_kernel),
83 elc_kernel_ptr = get_ptr(elc_kernel)](Particle &p1, Particle &p2,
84 Distance const &d) {
85 auto const q1q2 = p1.q() * p2.q();
86 if (q1q2 != 0.) {
87 auto force = (*coulomb_kernel_ptr)(q1q2, d.vec21, std::sqrt(d.dist2));
88 p1.force() += force;
89 p2.force() -= force;
90#ifdef ESPRESSO_P3M
91 if (elc_kernel_ptr) {
92 (*elc_kernel_ptr)(p1.pos(), p2.pos(), p1.force_and_torque().f,
93 p2.force_and_torque().f, q1q2);
94 }
95#endif // ESPRESSO_P3M
96 }
97 });
98}
99
101 try {
102 sanity_check();
103 } catch (std::runtime_error const &err) {
104 runtimeErrorMsg() << err.what();
105 return;
106 }
107
108 auto &system = get_system();
109 auto &cell_structure = *system.cell_structure;
110 auto const &coulomb = system.coulomb;
111 auto const particles = cell_structure.local_particles();
112 auto const prefactor = std::visit(
113 [](auto const &ptr) { return ptr->prefactor; }, *coulomb.impl->solver);
114 auto const pref = 1. / (prefactor * 2. * std::numbers::pi);
115 auto const kernel = coulomb.pair_force_kernel();
116 auto const elc_kernel = coulomb.pair_force_elc_kernel();
118
119 using execution_space = Kokkos::DefaultExecutionSpace;
120 auto const &unique_particles = cell_structure.get_unique_particles();
121 auto const &local_force = cell_structure.get_local_force();
122
123 auto global_max_rel_diff = 0.;
124
125 for (int j = 0; j < icc_cfg.max_iterations; j++) {
126 auto charge_density_max = 0.;
127
128 // calculate electrostatic forces (SR+LR) excluding self-interactions
129 force_calc_icc(cell_structure, kernel, elc_kernel);
130 system.coulomb.calc_long_range_force();
131 cell_structure.ghosts_reduce_forces();
132 // force reduction
133 int num_threads = execution_space().concurrency();
134 kokkos_parallel_range_for<Kokkos::RangePolicy<execution_space>>(
135 "reduction", std::size_t{0}, unique_particles.size(),
136 [&local_force, &unique_particles, num_threads](std::size_t const i) {
137 auto &force = unique_particles.at(i)->force();
138 for (int tid = 0; tid < num_threads; ++tid) {
139 force[0] += local_force(i, tid, 0);
140 force[1] += local_force(i, tid, 1);
141 force[2] += local_force(i, tid, 2);
142 }
143 });
144 Kokkos::fence();
145
146 auto max_rel_diff = 0.;
147
148 for (auto &p : particles) {
149 auto const pid = p.id();
150 if (pid >= icc_cfg.first_id and pid < icc_cfg.n_icc + icc_cfg.first_id) {
151 if (p.q() == 0.) {
153 << "ICC found zero electric charge on a particle. This must "
154 "never happen";
155 break;
156 }
157 auto const id = p.id() - icc_cfg.first_id;
158 /* the dielectric-related prefactor: */
159 auto const eps_in = icc_cfg.epsilons[id];
160 auto const eps_out = icc_cfg.eps_out;
161 auto const del_eps = (eps_in - eps_out) / (eps_in + eps_out);
162 /* calculate the electric field at the certain position */
163 auto const local_e_field = p.force() / p.q() + icc_cfg.ext_field;
164
165 if (local_e_field.norm2() == 0.) {
167 << "ICC found zero electric field on a charge. This must "
168 "never happen";
169 }
170
171 auto const charge_density_old = p.q() / icc_cfg.areas[id];
172
173 charge_density_max =
174 std::max(charge_density_max, std::abs(charge_density_old));
175
176 auto const charge_density_update =
177 del_eps * pref * (local_e_field * icc_cfg.normals[id]) +
179 icc_cfg.sigmas[id];
180 /* relative variation: never use an estimator which can be negative
181 * here */
182 auto const charge_density_new =
183 (1. - icc_cfg.relaxation) * charge_density_old +
184 (icc_cfg.relaxation) * charge_density_update;
185
186 /* Take the largest error to check for convergence */
187 auto const relative_difference =
188 std::abs((charge_density_new - charge_density_old) /
189 (charge_density_max +
190 std::abs(charge_density_new + charge_density_old)));
191
192 max_rel_diff = std::max(max_rel_diff, relative_difference);
193
194 p.q() = charge_density_new * icc_cfg.areas[id];
195
196 /* check if the charge now is more than 1e6, to determine if ICC still
197 * leads to reasonable results. This is kind of an arbitrary measure
198 * but does a good job of spotting divergence! */
199 if (std::abs(p.q()) > 1e6) {
201 << "Particle with id " << p.id() << " has a charge (q=" << p.q()
202 << ") that is too large for the ICC algorithm";
203
204 max_rel_diff = std::numeric_limits<double>::max();
205 break;
206 }
207 }
208 }
209
210 /* Update charges on ghosts. */
211 cell_structure.ghosts_update(Cells::DATA_PART_PROPERTIES);
212 // refresh local properties
213 update_aosoa_charges(cell_structure);
214
216
217 boost::mpi::all_reduce(comm_cart, max_rel_diff, global_max_rel_diff,
218 boost::mpi::maximum<double>());
219
220 if (global_max_rel_diff < icc_cfg.convergence)
221 break;
222 }
223
224 if (global_max_rel_diff > icc_cfg.convergence) {
226 << "ICC failed to converge in the given number of maximal steps.";
227 }
228
229 system.on_particle_charge_change();
230}
231
233 if (n_icc <= 0)
234 throw std::domain_error("Parameter 'n_icc' must be >= 1");
235 if (convergence <= 0.)
236 throw std::domain_error("Parameter 'convergence' must be > 0");
237 if (relaxation < 0. or relaxation > 2.)
238 throw std::domain_error("Parameter 'relaxation' must be >= 0 and <= 2");
239 if (max_iterations <= 0)
240 throw std::domain_error("Parameter 'max_iterations' must be > 0");
241 if (first_id < 0)
242 throw std::domain_error("Parameter 'first_id' must be >= 0");
243 if (eps_out <= 0.)
244 throw std::domain_error("Parameter 'eps_out' must be > 0");
245 if (areas.size() != static_cast<std::size_t>(n_icc))
246 throw std::invalid_argument("Parameter 'areas' has incorrect shape");
247 if (epsilons.size() != static_cast<std::size_t>(n_icc))
248 throw std::invalid_argument("Parameter 'epsilons' has incorrect shape");
249 if (sigmas.size() != static_cast<std::size_t>(n_icc))
250 throw std::invalid_argument("Parameter 'sigmas' has incorrect shape");
251 if (normals.size() != static_cast<std::size_t>(n_icc))
252 throw std::invalid_argument("Parameter 'normals' has incorrect shape");
253}
254
256 data.sanity_checks();
257 icc_cfg = std::move(data);
258}
259
261 sanity_check();
262 auto &system = get_system();
263 system.on_particle_charge_change();
264}
265
267 template <typename T> void operator()(std::shared_ptr<T> const &) const {}
268#ifdef ESPRESSO_P3M
269#ifdef ESPRESSO_CUDA
270 void operator()(std::shared_ptr<CoulombP3M> const &p) const {
271 if (p->is_gpu()) {
272 throw std::runtime_error("ICC does not work with P3M on GPU");
273 }
274 }
275#endif // ESPRESSO_CUDA
276 void
277 operator()(std::shared_ptr<ElectrostaticLayerCorrection> const &actor) const {
278 if (actor->elc.dielectric_contrast_on) {
279 throw std::runtime_error("ICC conflicts with ELC dielectric contrast");
280 }
281 std::visit(*this, actor->base_solver);
282 }
283#endif // ESPRESSO_P3M
284 [[noreturn]] void operator()(std::shared_ptr<DebyeHueckel> const &) const {
285 throw std::runtime_error("ICC does not work with DebyeHueckel.");
286 }
287 [[noreturn]] void operator()(std::shared_ptr<ReactionField> const &) const {
288 throw std::runtime_error("ICC does not work with ReactionField.");
289 }
290};
291
294#ifdef ESPRESSO_NPT
295 if (get_system().has_npt_enabled()) {
296 throw std::runtime_error("ICC does not work in the NpT ensemble");
297 }
298#endif
299}
300
302 auto &system = get_system();
303 if (system.coulomb.impl->solver) {
304 std::visit(SanityChecksICC(), *system.coulomb.impl->solver);
305 } else {
306 throw std::runtime_error("An electrostatics solver is needed by ICC");
307 }
308}
309
311 return coulomb.impl->extension and
312 std::holds_alternative<std::shared_ptr<ICCStar>>(
313 *coulomb.impl->extension);
314}
315
317 if (coulomb.impl->extension) {
318 if (auto icc = std::get_if<std::shared_ptr<ICCStar>>(
319 get_ptr(coulomb.impl->extension))) {
320 (**icc).iteration();
321 }
322 }
323}
324
325#endif // ESPRESSO_ELECTROSTATICS
Describes a cell structure / cell system.
void for_each_local_particle(ParticleUnaryOp &&f, bool parallel=true) const
Run a kernel on all local particles.
void non_bonded_loop(PairKernel pair_kernel)
Non-bonded pair loop.
void for_each_ghost_particle(ParticleUnaryOp &&f) const
Run a kernel on all ghost particles.
void update_icc_particles()
Definition icc.cpp:316
bool has_icc_enabled() const
Definition icc.cpp:310
boost::mpi::communicator comm_cart
The communicator.
const T * get_ptr(std::optional< T > const &opt)
This file contains the errorhandling code for severe errors, like a broken bond or illegal parameter ...
#define runtimeErrorMsg()
static void force_calc_icc(CellStructure &cell_structure, Coulomb::ShortRangeForceKernel::result_type const &coulomb_kernel, Coulomb::ShortRangeForceCorrectionsKernel::result_type const &elc_kernel)
Calculate the electrostatic forces between source charges (= real charges) and wall charges.
Definition icc.cpp:70
ICC is a method that allows to take into account the influence of arbitrarily shaped dielectric inter...
@ DATA_PART_PROPERTIES
Particle::p.
P3M algorithm for long-range Coulomb interaction.
ESPRESSO_ATTR_ALWAYS_INLINE void update_aosoa_charges(CellStructure &cell_structure)
std::optional< kernel_type > result_type
std::optional< kernel_type > result_type
Distance vector and length handed to pair kernels.
void sanity_checks_active_solver() const
Definition icc.cpp:301
void iteration()
The main iterative scheme, where the surface element charges are calculated self-consistently.
Definition icc.cpp:100
icc_data icc_cfg
ICC parameters.
Definition icc.hpp:90
void on_activation() const
Definition icc.cpp:260
void sanity_check() const
Definition icc.cpp:292
ICCStar(icc_data data)
Definition icc.cpp:255
Struct holding all information for one particle.
Definition Particle.hpp:435
void operator()(std::shared_ptr< T > const &) const
Definition icc.cpp:267
void operator()(std::shared_ptr< ReactionField > const &) const
Definition icc.cpp:287
void operator()(std::shared_ptr< CoulombP3M > const &p) const
Definition icc.cpp:270
void operator()(std::shared_ptr< DebyeHueckel > const &) const
Definition icc.cpp:284
void operator()(std::shared_ptr< ElectrostaticLayerCorrection > const &actor) const
Definition icc.cpp:277
ICC data structure.
Definition icc.hpp:59
double convergence
convergence criteria
Definition icc.hpp:73
int first_id
first ICC particle id
Definition icc.hpp:83
double relaxation
relaxation parameter
Definition icc.hpp:79
std::vector< Utils::Vector3d > normals
surface normal vectors
Definition icc.hpp:75
int max_iterations
maximum number of iterations
Definition icc.hpp:63
int n_icc
First id of ICC particle.
Definition icc.hpp:61
double eps_out
bulk dielectric constant
Definition icc.hpp:65
void sanity_checks() const
Definition icc.cpp:232
std::vector< double > sigmas
surface charge density of the particles
Definition icc.hpp:71
std::vector< double > epsilons
dielectric constants of the particles
Definition icc.hpp:69
Utils::Vector3d ext_field
external electric field
Definition icc.hpp:77
int citeration
last number of iterations
Definition icc.hpp:81
std::vector< double > areas
areas of the particles
Definition icc.hpp:67