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-2022 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#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
52#include <Kokkos_Core.hpp>
53#include <omp.h>
54#endif
55
56#include <algorithm>
57#include <cmath>
58#include <cstddef>
59#include <limits>
60#include <numbers>
61#include <stdexcept>
62#include <variant>
63#include <vector>
64
65/** Calculate the electrostatic forces between source charges (= real charges)
66 * and wall charges. For each electrostatic method, the proper functions
67 * for short- and long-range parts are called. Long-range parts are calculated
68 * directly, short-range parts need helper functions according to the particle
69 * data organisation. This is a modified version of
70 * @ref System::System::calculate_forces.
71 */
72static void force_calc_icc(
73 CellStructure &cell_structure,
76 // reset forces
77 auto const reset_kernel = [](Particle &p) { p.force_and_torque() = {}; };
78 cell_structure.for_each_local_particle(reset_kernel);
79 cell_structure.for_each_ghost_particle(reset_kernel);
80#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
81 cell_structure.reset_local_force();
82#endif
83
84 // calc ICC forces
85 cell_structure.non_bonded_loop(
86 [coulomb_kernel_ptr = get_ptr(coulomb_kernel),
87 elc_kernel_ptr = get_ptr(elc_kernel)](Particle &p1, Particle &p2,
88 Distance const &d) {
89 auto const q1q2 = p1.q() * p2.q();
90 if (q1q2 != 0.) {
91 auto force = (*coulomb_kernel_ptr)(q1q2, d.vec21, std::sqrt(d.dist2));
92 p1.force() += force;
93 p2.force() -= force;
94#ifdef ESPRESSO_P3M
95 if (elc_kernel_ptr) {
96 (*elc_kernel_ptr)(p1.pos(), p2.pos(), p1.force_and_torque().f,
97 p2.force_and_torque().f, q1q2);
98 }
99#endif // ESPRESSO_P3M
100 }
101 });
102}
103
105 try {
106 sanity_check();
107 } catch (std::runtime_error const &err) {
108 runtimeErrorMsg() << err.what();
109 return;
110 }
111
112 auto &system = get_system();
113 auto &cell_structure = *system.cell_structure;
114 auto const &coulomb = system.coulomb;
115 auto const particles = cell_structure.local_particles();
116 auto const prefactor = std::visit(
117 [](auto const &ptr) { return ptr->prefactor; }, *coulomb.impl->solver);
118 auto const pref = 1. / (prefactor * 2. * std::numbers::pi);
119 auto const kernel = coulomb.pair_force_kernel();
120 auto const elc_kernel = coulomb.pair_force_elc_kernel();
122
123#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
124 using execution_space = Kokkos::DefaultExecutionSpace;
125 auto const &unique_particles = cell_structure.get_unique_particles();
126 auto const &local_force = cell_structure.get_local_force();
127#endif // ESPRESSO_SHARED_MEMORY_PARALLELISM
128
129 auto global_max_rel_diff = 0.;
130
131 for (int j = 0; j < icc_cfg.max_iterations; j++) {
132 auto charge_density_max = 0.;
133
134 // calculate electrostatic forces (SR+LR) excluding self-interactions
135 force_calc_icc(cell_structure, kernel, elc_kernel);
136 system.coulomb.calc_long_range_force();
137 cell_structure.ghosts_reduce_forces();
138#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
139 // force reduction
140 int num_threads = execution_space().concurrency();
141 kokkos_parallel_range_for<Kokkos::RangePolicy<execution_space>>(
142 "reduction", std::size_t{0}, unique_particles.size(),
143 [&local_force, &unique_particles, num_threads](std::size_t const i) {
144 auto &force = unique_particles.at(i)->force();
145 for (int tid = 0; tid < num_threads; ++tid) {
146 force[0] += local_force(i, tid, 0);
147 force[1] += local_force(i, tid, 1);
148 force[2] += local_force(i, tid, 2);
149 }
150 });
151 Kokkos::fence();
152#endif // ESPRESSO_SHARED_MEMORY_PARALLELISM
153
154 auto max_rel_diff = 0.;
155
156 for (auto &p : particles) {
157 auto const pid = p.id();
158 if (pid >= icc_cfg.first_id and pid < icc_cfg.n_icc + icc_cfg.first_id) {
159 if (p.q() == 0.) {
161 << "ICC found zero electric charge on a particle. This must "
162 "never happen";
163 break;
164 }
165 auto const id = p.id() - icc_cfg.first_id;
166 /* the dielectric-related prefactor: */
167 auto const eps_in = icc_cfg.epsilons[id];
168 auto const eps_out = icc_cfg.eps_out;
169 auto const del_eps = (eps_in - eps_out) / (eps_in + eps_out);
170 /* calculate the electric field at the certain position */
171 auto const local_e_field = p.force() / p.q() + icc_cfg.ext_field;
172
173 if (local_e_field.norm2() == 0.) {
175 << "ICC found zero electric field on a charge. This must "
176 "never happen";
177 }
178
179 auto const charge_density_old = p.q() / icc_cfg.areas[id];
180
181 charge_density_max =
182 std::max(charge_density_max, std::abs(charge_density_old));
183
184 auto const charge_density_update =
185 del_eps * pref * (local_e_field * icc_cfg.normals[id]) +
187 icc_cfg.sigmas[id];
188 /* relative variation: never use an estimator which can be negative
189 * here */
190 auto const charge_density_new =
191 (1. - icc_cfg.relaxation) * charge_density_old +
192 (icc_cfg.relaxation) * charge_density_update;
193
194 /* Take the largest error to check for convergence */
195 auto const relative_difference =
196 std::abs((charge_density_new - charge_density_old) /
197 (charge_density_max +
198 std::abs(charge_density_new + charge_density_old)));
199
200 max_rel_diff = std::max(max_rel_diff, relative_difference);
201
202 p.q() = charge_density_new * icc_cfg.areas[id];
203
204 /* check if the charge now is more than 1e6, to determine if ICC still
205 * leads to reasonable results. This is kind of an arbitrary measure
206 * but does a good job of spotting divergence! */
207 if (std::abs(p.q()) > 1e6) {
209 << "Particle with id " << p.id() << " has a charge (q=" << p.q()
210 << ") that is too large for the ICC algorithm";
211
212 max_rel_diff = std::numeric_limits<double>::max();
213 break;
214 }
215 }
216 }
217
218 /* Update charges on ghosts. */
219 cell_structure.ghosts_update(Cells::DATA_PART_PROPERTIES);
220#ifdef ESPRESSO_SHARED_MEMORY_PARALLELISM
221 // refresh local properties
222 update_aosoa_charges(cell_structure);
223#endif
224
226
227 boost::mpi::all_reduce(comm_cart, max_rel_diff, global_max_rel_diff,
228 boost::mpi::maximum<double>());
229
230 if (global_max_rel_diff < icc_cfg.convergence)
231 break;
232 }
233
234 if (global_max_rel_diff > icc_cfg.convergence) {
236 << "ICC failed to converge in the given number of maximal steps.";
237 }
238
239 system.on_particle_charge_change();
240}
241
243 if (n_icc <= 0)
244 throw std::domain_error("Parameter 'n_icc' must be >= 1");
245 if (convergence <= 0.)
246 throw std::domain_error("Parameter 'convergence' must be > 0");
247 if (relaxation < 0. or relaxation > 2.)
248 throw std::domain_error("Parameter 'relaxation' must be >= 0 and <= 2");
249 if (max_iterations <= 0)
250 throw std::domain_error("Parameter 'max_iterations' must be > 0");
251 if (first_id < 0)
252 throw std::domain_error("Parameter 'first_id' must be >= 0");
253 if (eps_out <= 0.)
254 throw std::domain_error("Parameter 'eps_out' must be > 0");
255 if (areas.size() != static_cast<std::size_t>(n_icc))
256 throw std::invalid_argument("Parameter 'areas' has incorrect shape");
257 if (epsilons.size() != static_cast<std::size_t>(n_icc))
258 throw std::invalid_argument("Parameter 'epsilons' has incorrect shape");
259 if (sigmas.size() != static_cast<std::size_t>(n_icc))
260 throw std::invalid_argument("Parameter 'sigmas' has incorrect shape");
261 if (normals.size() != static_cast<std::size_t>(n_icc))
262 throw std::invalid_argument("Parameter 'normals' has incorrect shape");
263}
264
266 data.sanity_checks();
267 icc_cfg = std::move(data);
268}
269
271 sanity_check();
272 auto &system = get_system();
273 system.on_particle_charge_change();
274}
275
277 template <typename T> void operator()(std::shared_ptr<T> const &) const {}
278#ifdef ESPRESSO_P3M
279#ifdef ESPRESSO_CUDA
280 void operator()(std::shared_ptr<CoulombP3M> const &p) const {
281 if (p->is_gpu()) {
282 throw std::runtime_error("ICC does not work with P3MGPU");
283 }
284 }
285#endif // ESPRESSO_CUDA
286 void
287 operator()(std::shared_ptr<ElectrostaticLayerCorrection> const &actor) const {
288 if (actor->elc.dielectric_contrast_on) {
289 throw std::runtime_error("ICC conflicts with ELC dielectric contrast");
290 }
291 std::visit(*this, actor->base_solver);
292 }
293#endif // ESPRESSO_P3M
294 [[noreturn]] void operator()(std::shared_ptr<DebyeHueckel> const &) const {
295 throw std::runtime_error("ICC does not work with DebyeHueckel.");
296 }
297 [[noreturn]] void operator()(std::shared_ptr<ReactionField> const &) const {
298 throw std::runtime_error("ICC does not work with ReactionField.");
299 }
300};
301
304#ifdef ESPRESSO_NPT
305 if (get_system().has_npt_enabled()) {
306 throw std::runtime_error("ICC does not work in the NpT ensemble");
307 }
308#endif
309}
310
312 auto &system = get_system();
313 if (system.coulomb.impl->solver) {
314 std::visit(SanityChecksICC(), *system.coulomb.impl->solver);
315 } else {
316 throw std::runtime_error("An electrostatics solver is needed by ICC");
317 }
318}
319
321 return coulomb.impl->extension and
322 std::holds_alternative<std::shared_ptr<ICCStar>>(
323 *coulomb.impl->extension);
324}
325
327 if (coulomb.impl->extension) {
328 if (auto icc = std::get_if<std::shared_ptr<ICCStar>>(
329 get_ptr(coulomb.impl->extension))) {
330 (**icc).iteration();
331 }
332 }
333}
334
335#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:326
bool has_icc_enabled() const
Definition icc.cpp:320
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:72
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:311
void iteration()
The main iterative scheme, where the surface element charges are calculated self-consistently.
Definition icc.cpp:104
icc_data icc_cfg
ICC parameters.
Definition icc.hpp:90
void on_activation() const
Definition icc.cpp:270
void sanity_check() const
Definition icc.cpp:302
ICCStar(icc_data data)
Definition icc.cpp:265
Struct holding all information for one particle.
Definition Particle.hpp:450
void operator()(std::shared_ptr< T > const &) const
Definition icc.cpp:277
void operator()(std::shared_ptr< ReactionField > const &) const
Definition icc.cpp:297
void operator()(std::shared_ptr< CoulombP3M > const &p) const
Definition icc.cpp:280
void operator()(std::shared_ptr< DebyeHueckel > const &) const
Definition icc.cpp:294
void operator()(std::shared_ptr< ElectrostaticLayerCorrection > const &actor) const
Definition icc.cpp:287
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:242
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