ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
energy.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#include <config/config.hpp>
23
24#include "BoxGeometry.hpp"
25#include "Observable_stat.hpp"
26#include "Particle.hpp"
29#include "constraints/Constraints.hpp"
30#include "energy_cabana.hpp"
31#include "energy_inline.hpp"
33#include "kokkos_helpers.hpp"
37#include "short_range_loop.hpp"
40#include "system/System.hpp"
41
44
45#include <cmath>
46#include <cstddef>
47#include <memory>
48#include <optional>
49#include <span>
50#include <vector>
51
53 using execution_space = Kokkos::DefaultHostExecutionSpace;
54 std::unique_ptr<Observable_stat> observable;
55 Kokkos::View<double **, Kokkos::LayoutRight, execution_space> local;
56};
57
58namespace System {
59
61
62 if (not m_obs_energy) {
63 auto const n_threads = EnergyObservable::execution_space{}.concurrency();
64 m_obs_energy = std::make_shared<EnergyObservable>();
65 m_obs_energy->observable = std::make_unique<Observable_stat>(1ul, 0ul, 0);
66 m_obs_energy->local =
67 decltype(m_obs_energy->local)("local_energy", n_threads, 1ul);
68 }
69
70 auto &local_energy = m_obs_energy->local;
71 auto &obs_energy = *m_obs_energy->observable;
72 obs_energy.reset(static_cast<std::size_t>(bonded_ias->get_next_key()),
73 nonbonded_ias->get_max_seen_particle_type());
74
75 if (long_range_interactions_sanity_checks()) {
76 return obs_energy;
77 }
78
79#if defined(ESPRESSO_CUDA) and \
80 (defined(ESPRESSO_ELECTROSTATICS) or defined(ESPRESSO_DIPOLES))
81 gpu->clear_energy_on_device();
82 gpu->update();
83#endif
84 on_observable_calc();
85
86 auto const local_parts = cell_structure->local_particles();
87
88 for (auto const &p : local_parts) {
89 obs_energy.kinetic_lin[0] += translational_kinetic_energy(p);
90 obs_energy.kinetic_rot[0] += rotational_kinetic_energy(p);
91 }
92
93 auto const coulomb_kernel = coulomb.pair_energy_kernel();
94 auto const dipoles_kernel = dipoles.pair_energy_kernel();
95
96#ifdef ESPRESSO_CALIPER
97 CALI_MARK_BEGIN("cabana_short_range");
98#endif
99 // Factory instead of an eager criterion: construction fills an O(n_types^2)
100 // cutoff table, so it only runs on the link-cell fallback path.
101 auto const make_verlet_criterion = [&] {
102 return VerletCriterion<>{*this,
103 cell_structure->get_verlet_skin(),
104 get_interaction_range(),
105 coulomb.cutoff(),
106 dipoles.cutoff(),
108 };
110
111 EnergyBinLayout layout{
112 static_cast<std::size_t>(bonded_ias->get_next_key()),
113 std::size_t(nonbonded_ias->get_max_seen_particle_type() + 1)};
114
115 using exec = Kokkos::DefaultHostExecutionSpace;
116 if (local_energy.extent(1) != layout.total) {
117 Kokkos::realloc(Kokkos::WithoutInitializing, local_energy,
118 exec{}.concurrency(), layout.total);
119 }
120 kokkos_deep_copy(exec{}, local_energy, 0.);
121
122 auto const &unique_particles = cell_structure->get_unique_particles();
123 auto const n_particles = unique_particles.size();
124 Kokkos::View<int *, Kokkos::LayoutRight, exec> mol_id("mol_id", n_particles);
125 for (std::size_t i = 0; i < n_particles; ++i) {
126 mol_id(i) = unique_particles[i]->mol_id();
127 }
128
129 // Non Bonded energies
130 EnergyKernel pair_e_kernel{*bonded_ias,
131 *nonbonded_ias,
132 coulomb,
133 get_ptr(coulomb_kernel),
134 get_ptr(dipoles_kernel),
135 *box_geo,
136 cell_structure->get_unique_particles(),
137 local_energy,
138 layout,
139 cell_structure->get_aosoa(),
140 mol_id,
141 maximal_cutoff()};
142
143 // Bonded energies: write a BondsEnergyKernelData + *BondsEnergyKernel
144 auto &bs = cell_structure->bond_state();
145 BondsEnergyKernelData bonds_e_data{*bonded_ias, *box_geo, local_energy,
146 layout, cell_structure->get_aosoa()};
148 get_ptr(coulomb_kernel)};
150 bs.angle_ids};
152 bs.dihedral_ids};
153
155 pair_e_kernel, *cell_structure, get_interaction_range(),
156 bonded_ias->maximal_cutoff(), make_verlet_criterion,
157 propagation->integ_switch);
158
159 reduce_cabana_energy(local_energy, layout, obs_energy, *bonded_ias,
160 nonbonded_ias->get_max_seen_particle_type() + 1);
161#ifdef ESPRESSO_CALIPER
162 CALI_MARK_END("cabana_short_range");
163#endif
164
165#ifdef ESPRESSO_ELECTROSTATICS
166 /* calculate k-space part of electrostatic interaction. */
167 obs_energy.coulomb[1] = coulomb.calc_energy_long_range();
168#endif
169
170#ifdef ESPRESSO_DIPOLES
171 /* calculate k-space part of magnetostatic interaction. */
172 obs_energy.dipolar[1] = dipoles.calc_energy_long_range();
173#endif
174
175 constraints->add_energy(local_parts, get_sim_time(), obs_energy);
176
177#if defined(ESPRESSO_CUDA) and \
178 (defined(ESPRESSO_ELECTROSTATICS) or defined(ESPRESSO_DIPOLES))
179 auto const energy_host = gpu->copy_energy_to_host();
180 if (!obs_energy.coulomb.empty())
181 obs_energy.coulomb[1] += static_cast<double>(energy_host.coulomb);
182 if (!obs_energy.dipolar.empty())
183 obs_energy.dipolar[1] += static_cast<double>(energy_host.dipolar);
184#endif
185
186 obs_energy.mpi_reduce();
187 return obs_energy;
188 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
189}
190
192 if (cell_structure->get_resort_particles()) {
193 cell_structure->update_ghosts_and_resort_particle(get_global_ghost_flags());
194 }
195
196 auto ret = 0.0;
197 if (auto const p = cell_structure->get_local_particle(pid)) {
198 auto const coulomb_kernel = coulomb.pair_energy_kernel();
199 auto kernel = [&ret, this](Particle const &p, Particle const &p1,
200 Utils::Vector3d const &vec) {
201#ifdef ESPRESSO_EXCLUSIONS
202 if (not do_nonbonded(p, p1))
203 return;
204#endif
205 auto const &ia_params = nonbonded_ias->get_ia_param(p.type(), p1.type());
206 // Add energy for current particle pair to result
208 *bonded_ias, coulomb, nullptr);
209 };
210 cell_structure->run_on_particle_short_range_neighbors(*p, kernel);
211 }
212 return ret;
213}
214
215std::optional<double> System::particle_bond_energy(int pid, int bond_id,
216 std::vector<int> partners) {
217 if (cell_structure->get_resort_particles()) {
218 cell_structure->update_ghosts_and_resort_particle(get_global_ghost_flags());
219 }
220 Particle const *p = cell_structure->get_local_particle(pid);
221 if (not p or p->is_ghost())
222 return {}; // not available on this MPI rank or ghost
223 auto const &iaparams = *bonded_ias->at(bond_id);
224 try {
225 auto resolved_partners = cell_structure->resolve_bond_partners(partners);
226 auto const coulomb_kernel = coulomb.pair_energy_kernel();
227 return calc_bonded_energy(
228 iaparams, *p,
229 std::span(resolved_partners.data(), resolved_partners.size()), *box_geo,
230 get_ptr(coulomb_kernel));
231 } catch (const BondResolutionError &) {
233 return {};
234 }
235}
236
237} // namespace System
void bond_broken_error(int id, std::span< const int > partner_ids)
Observable for the pressure and energy.
double particle_short_range_energy_contribution(int pid)
Compute the short-range energy of a particle.
Definition energy.cpp:191
std::optional< double > particle_bond_energy(int pid, int bond_id, std::vector< int > partners)
Compute the energy of a given bond which has to exist on the given particle.
Definition energy.cpp:215
Observable_stat const & calculate_energy()
Calculate the total energy.
Definition energy.cpp:60
Returns true if the particles are to be considered for short range interactions.
cudaStream_t stream[1]
CUDA streams for parallel computing on CPU and GPU.
constexpr double inactive_cutoff
Special cutoff value for an inactive interaction.
Definition config.hpp:53
const T * get_ptr(std::optional< T > const &opt)
static void reduce_cabana_energy(Kokkos::View< double **, Kokkos::LayoutRight, Kokkos::HostSpace > const &local_energy, EnergyBinLayout const &layout, Observable_stat &obs, BondedInteractionsMap const &bonded_ias, int n_types)
Energy calculation.
std::optional< double > calc_bonded_energy(Bonded_IA_Parameters const &iaparams, Particle const &p1, std::span< Particle * > partners, BoxGeometry const &box_geo, Coulomb::ShortRangeEnergyKernel::kernel_type const *kernel)
double translational_kinetic_energy(Particle const &p)
Calculate kinetic energies from translation for one particle.
double rotational_kinetic_energy(Particle const &p)
Calculate kinetic energies from rotation for one particle.
double calc_non_bonded_pair_energy(Particle const &p1, Particle const &p2, IA_parameters const &ia_params, Utils::Vector3d const &d, double const dist, BondedInteractionsMap const &bonded_ias, Coulomb::Solver const &coulomb, Coulomb::ShortRangeEnergyKernel::kernel_type const *coulomb_kernel)
Calculate non-bonded energies between a pair of particles.
bool do_nonbonded(Particle const &p1, Particle const &p2)
Determine if the non-bonded interactions between p1 and p2 should be calculated.
ESPRESSO_ATTR_ALWAYS_INLINE void kokkos_deep_copy(auto const &exec_space, auto const &view, auto const &value)
Wrapper for Kokkos::deep_copy that skips fork/join when the number of threads is 1.
Various procedures concerning interactions between particles.
void cabana_short_range(auto const &pair_bonds_kernel, auto const &angle_bonds_kernel, auto const &dihedral_bonds_kernel, auto const &nonbonded_kernel, CellStructure &cell_structure, double pair_cutoff, double bond_cutoff, auto const &make_verlet_criterion, auto const integ_switch, ShortRangeVerletPairLoop const &verlet_pair_loop={})
void update_verlet_state(System::System const &system, double const collision_cut)
Exception indicating that a particle id could not be resolved.
std::unique_ptr< Observable_stat > observable
Definition energy.cpp:54
Kokkos::DefaultHostExecutionSpace execution_space
Definition energy.cpp:53
Kokkos::View< double **, Kokkos::LayoutRight, execution_space > local
Definition energy.cpp:55
Struct holding all information for one particle.
Definition Particle.hpp:436
constexpr auto const & id() const
Definition Particle.hpp:455
constexpr bool is_ghost() const
Definition Particle.hpp:485