ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
script_interface/system/System.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2013-2022 The ESPResSo project
3 *
4 * This file is part of ESPResSo.
5 *
6 * ESPResSo is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * ESPResSo is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include "System.hpp"
21
22#include "config/config.hpp"
23
24#include "core/BoxGeometry.hpp"
25#include "core/Particle.hpp"
29#include "core/cells.hpp"
31#include "core/exclusions.hpp"
33#include "core/npt.hpp"
36#include "core/propagation.hpp"
37#include "core/rotation.hpp"
40
59
60#include <utils/Vector.hpp>
61#include <utils/demangle.hpp>
64
65#include <boost/mpi/collectives.hpp>
66
67#include <algorithm>
68#include <array>
69#include <cassert>
70#include <cmath>
71#include <functional>
72#include <initializer_list>
73#include <memory>
74#include <ranges>
75#include <stdexcept>
76#include <string>
77#include <type_traits>
78#include <vector>
79
80namespace ScriptInterface {
81namespace System {
82
83static bool system_created = false;
84
85#ifdef ESPRESSO_EXCLUSIONS
87 Variant const &exclusions) {
88 p.call_method("set_exclusions", {{"p_ids", exclusions}});
89}
90#endif // ESPRESSO_EXCLUSIONS
91
92static void set_bonds(Particles::ParticleHandle &p, Variant const &bonds) {
94 for (auto const &bond_flat : bond_list_flat) {
95 auto const bond_id = bond_flat[0];
96 auto const part_id =
97 std::vector<int>{bond_flat.begin() + 1, bond_flat.end()};
98 p.call_method("add_bond",
99 {{"bond_id", bond_id}, {"part_id", std::move(part_id)}});
100 }
101}
102
103/** @brief Container for leaves of the system class. */
105 Leaves() = default;
106 std::shared_ptr<CellSystem::CellSystem> cell_system;
107 std::shared_ptr<Integrators::IntegratorHandle> integrator;
108 std::shared_ptr<Interactions::BondedInteractions> bonded_interactions;
109#ifdef ESPRESSO_COLLISION_DETECTION
110 std::shared_ptr<CollisionDetection::CollisionDetection> collision_detection;
111#endif
112 std::shared_ptr<Thermostat::Thermostat> thermostat;
113 std::shared_ptr<Analysis::Analysis> analysis;
114 std::shared_ptr<Galilei::ComFixed> comfixed;
115 std::shared_ptr<Galilei::Galilei> galilei;
116 std::shared_ptr<BondBreakage::BreakageSpecs> bond_breakage;
117 std::shared_ptr<LeesEdwards::LeesEdwards> lees_edwards;
118 std::shared_ptr<Accumulators::AutoUpdateAccumulators>
120 std::shared_ptr<Constraints::Constraints> constraints;
121 std::shared_ptr<Interactions::NonBondedInteractions> non_bonded_inter;
122#ifdef ESPRESSO_ELECTROSTATICS
123 std::shared_ptr<Coulomb::Container> electrostatics;
124#endif
125#ifdef ESPRESSO_DIPOLES
126 std::shared_ptr<Dipoles::Container> magnetostatics;
127#endif
128 std::shared_ptr<Particles::ParticleList> part;
129
131 // Clear containers whose elements call MPI callbacks upon destruction.
132 // The containers lifetime is extended by the global context shared object
133 // registry on the head node, which can cause MPI deadlocks if they still
134 // contain elements.
136 bonded_interactions->clear();
137 }
138 if (constraints) {
139 constraints->clear();
140 }
141 }
142};
143
144System::System() : m_instance{}, m_leaves{std::make_unique<Leaves>()} {
145 auto const add_parameter =
146 [this, ptr = m_leaves.get()](std::string key, auto Leaves::*member) {
148 key.c_str(),
149 [this, ptr, member, key](Variant const &val) {
150 auto &dst = ptr->*member;
151 if (dst != nullptr) {
152 throw WriteError(key);
153 }
154 dst = get_value<std::remove_reference_t<decltype(dst)>>(val);
155 dst->bind_system(m_instance);
156 },
157 [ptr, member]() { return ptr->*member; })});
158 };
159
160 add_parameters({
161 {"box_l",
162 [this](Variant const &v) {
163 context()->parallel_try_catch([&]() {
166 throw std::domain_error("Attribute 'box_l' must be > 0");
167 }
168 m_instance->veto_boxl_change();
169 m_instance->box_geo->set_length(new_value);
170 m_instance->on_boxl_change();
171 });
172 },
173 [this]() { return m_instance->box_geo->length(); }},
174 {"periodicity",
175 [this](Variant const &v) {
177 for (unsigned int i = 0u; i < 3u; ++i) {
178 m_instance->box_geo->set_periodic(i, periodicity[i]);
179 }
180 context()->parallel_try_catch(
181 [&]() { m_instance->on_periodicity_change(); });
182 },
183 [this]() {
184 return Utils::Vector3b{m_instance->box_geo->periodic(0),
185 m_instance->box_geo->periodic(1),
186 m_instance->box_geo->periodic(2)};
187 }},
188 {"min_global_cut",
189 [this](Variant const &v) {
190 context()->parallel_try_catch([&]() {
191 auto const new_value = get_value<double>(v);
193 throw std::domain_error("Attribute 'min_global_cut' must be >= 0");
194 }
195 m_instance->set_min_global_cut(new_value);
196 });
197 },
198 [this]() { return m_instance->get_min_global_cut(); }},
199 {"max_oif_objects",
200 [this](Variant const &v) {
201 m_instance->oif_global->max_oif_objects = get_value<int>(v);
202 },
203 [this]() { return m_instance->oif_global->max_oif_objects; }},
204 });
205 // note: the order of leaves matters! e.g. bonds depend on thermostats,
206 // and thus a thermostat object must be instantiated before the bonds
207 add_parameter("cell_system", &Leaves::cell_system);
208 add_parameter("integrator", &Leaves::integrator);
209 add_parameter("thermostat", &Leaves::thermostat);
210 add_parameter("analysis", &Leaves::analysis);
211 add_parameter("comfixed", &Leaves::comfixed);
212 add_parameter("galilei", &Leaves::galilei);
213 add_parameter("bonded_inter", &Leaves::bonded_interactions);
214#ifdef ESPRESSO_COLLISION_DETECTION
215 add_parameter("collision_detection", &Leaves::collision_detection);
216#endif
217 add_parameter("bond_breakage", &Leaves::bond_breakage);
218 add_parameter("lees_edwards", &Leaves::lees_edwards);
219 add_parameter("auto_update_accumulators", &Leaves::auto_update_accumulators);
220 add_parameter("constraints", &Leaves::constraints);
221 add_parameter("non_bonded_inter", &Leaves::non_bonded_inter);
222#ifdef ESPRESSO_ELECTROSTATICS
223 add_parameter("electrostatics", &Leaves::electrostatics);
224#endif
225#ifdef ESPRESSO_DIPOLES
226 add_parameter("magnetostatics", &Leaves::magnetostatics);
227#endif
228 add_parameter("part", &Leaves::part);
229}
230
231template <typename LeafType>
232void System::do_set_default_parameter(std::string const &name) {
233 assert(context()->is_head_node());
234 auto const so_name = Utils::demangle<LeafType>().substr(17);
235 set_parameter(name, Variant{context()->make_shared(so_name, {})});
236}
237
238void System::do_construct(VariantMap const &params) {
239 /* When reloading the system state from a checkpoint file,
240 * the order of global variables instantiation matters.
241 * The @c box_l must be set before any other global variable.
242 * All these globals re-initialize the cell system, and we
243 * cannot use the default-constructed @c box_geo when e.g.
244 * long-range interactions exist in the system, otherwise
245 * runtime errors about the local geometry being smaller
246 * than the interaction range would be raised.
247 */
248 context()->parallel_try_catch([&]() {
249 if (not params.contains("box_l")) {
250 throw std::domain_error("Required argument 'box_l' not provided.");
251 }
252 if (params.contains("_regular_constructor") and system_created) {
253 throw std::runtime_error(
254 "You can only have one instance of the system class at a time");
255 }
256 });
257 m_instance = ::System::System::create();
258 ::System::set_system(m_instance);
259
260 // domain decomposition can only be set after box_l is set
261 m_instance->set_cell_structure_topology(CellStructureType::NSQUARE);
262 do_set_parameter("box_l", params.at("box_l"));
263 m_instance->set_cell_structure_topology(CellStructureType::REGULAR);
264
265 m_instance->lb.bind_system(m_instance);
266 m_instance->ek.bind_system(m_instance);
267
268 if (params.contains("_regular_constructor")) {
269 std::set<std::string> const setable_properties = {
270 "box_l", "min_global_cut",
271 "periodicity", "time",
272 "time_step", "force_cap",
273 "max_oif_objects", "_regular_constructor"};
274 for (auto const &name : std::views::elements<0>(params)) {
275 if (not setable_properties.contains(name)) {
276 context()->parallel_try_catch([&name]() {
277 throw std::domain_error(
278 "Property '" + name +
279 "' cannot be set via argument to System class");
280 });
281 }
282 }
283 for (std::string attr :
284 {"min_global_cut", "periodicity", "max_oif_objects"}) {
285 if (params.contains(attr)) {
286 do_set_parameter(attr, params.at(attr));
287 }
288 }
289 if (not context()->is_head_node()) {
290 return;
291 }
292 auto integrator = std::dynamic_pointer_cast<Integrators::IntegratorHandle>(
293 context()->make_shared("Integrators::IntegratorHandle", {}));
294 set_parameter("integrator", integrator);
295 for (std::string attr : {"time", "time_step", "force_cap"}) {
296 if (params.contains(attr)) {
297 integrator->set_parameter(attr, params.at(attr));
298 }
299 }
300 // note: the order of leaves matters! e.g. bonds depend on thermostats,
301 // and thus a thermostat object must be instantiated before the bonds
305#ifdef ESPRESSO_COLLISION_DETECTION
307 "collision_detection");
308#endif
315 "auto_update_accumulators");
318 "non_bonded_inter");
319#ifdef ESPRESSO_ELECTROSTATICS
321#endif
322#ifdef ESPRESSO_DIPOLES
324#endif
326 } else {
327 for (auto const &key : get_parameter_insertion_order()) {
328 if (key != "box_l" and params.contains(key)) {
329 do_set_parameter(key, params.at(key));
330 }
331 }
332 }
333 if (not context()->is_head_node()) {
334 return;
335 }
336 call_method("internal_attach_leaves", {});
337}
338
339static void rotate_system(CellStructure &cell_structure, double phi,
340 double theta, double alpha) {
341 auto const particles = cell_structure.local_particles();
342
343 // Calculate center of mass
345 double local_mass = 0.0;
346
347 for (auto const &p : particles) {
348 if (not p.is_virtual()) {
349 local_com += p.mass() * p.pos();
350 local_mass += p.mass();
351 }
352 }
353
354 auto const total_mass =
355 boost::mpi::all_reduce(comm_cart, local_mass, std::plus<>());
356 auto const com =
357 boost::mpi::all_reduce(comm_cart, local_com, std::plus<>()) / total_mass;
358
359 // Rotation axis in Cartesian coordinates
360 Utils::Vector3d axis;
361 axis[0] = std::sin(theta) * std::cos(phi);
362 axis[1] = std::sin(theta) * std::sin(phi);
363 axis[2] = std::cos(theta);
364
365 // Rotate particle coordinates
366 for (auto &p : particles) {
367 // Move the center of mass of the system to the origin
368 p.pos() = com + Utils::vec_rotate(axis, alpha, p.pos() - com);
369#ifdef ESPRESSO_ROTATION
370 local_rotate_particle(p, axis, alpha);
371#endif
372 }
373
377}
378
379/** Rescale all particle positions in direction @p dir by a factor @p scale.
380 * @param cell_structure cell structure
381 * @param dir direction to scale (0/1/2 = x/y/z, 3 = x+y+z isotropically)
382 * @param scale factor by which to rescale (>1: stretch, <1: contract)
383 */
384static void rescale_particles(CellStructure &cell_structure, int dir,
385 double scale) {
386 for (auto &p : cell_structure.local_particles()) {
387 if (dir < 3)
388 p.pos()[dir] *= scale;
389 else {
390 p.pos() *= scale;
391 }
392 }
393}
394
395Variant System::do_call_method(std::string const &name,
396 VariantMap const &parameters) {
397 if (name == "lock_system_creation") {
398 system_created = true;
399 return {};
400 }
401 if (name == "rescale_boxl") {
402 auto &box_geo = *m_instance->box_geo;
403 auto const coord = get_value<int>(parameters, "coord");
404 auto const length = get_value<double>(parameters, "length");
405 assert(coord >= 0);
406 assert(coord != 3 or ((box_geo.length()[0] == box_geo.length()[1]) and
407 (box_geo.length()[1] == box_geo.length()[2])));
408 auto const scale = (coord == 3) ? length * box_geo.length_inv()[0]
409 : length * box_geo.length_inv()[coord];
410 context()->parallel_try_catch([&]() {
411 if (length <= 0.) {
412 throw std::domain_error("Parameter 'd_new' must be > 0");
413 }
414 m_instance->veto_boxl_change(true);
415 });
416 auto new_value = Utils::Vector3d{};
417 if (coord == 3) {
419 } else {
420 new_value = box_geo.length();
421 new_value[static_cast<unsigned>(coord)] = length;
422 }
423 // when shrinking, rescale the particles first
424 if (scale <= 1.) {
425 rescale_particles(*m_instance->cell_structure, coord, scale);
426 m_instance->on_particle_change();
427 }
428 m_instance->box_geo->set_length(new_value);
429 m_instance->on_boxl_change();
430 if (scale > 1.) {
431 rescale_particles(*m_instance->cell_structure, coord, scale);
432 m_instance->on_particle_change();
433 }
434 return {};
435 }
436 if (name == "setup_type_map") {
437 auto const types = get_value<std::vector<int>>(parameters, "type_list");
438 for (auto const type : types) {
439 ::init_type_map(type);
440 }
441 return {};
442 }
443 if (name == "number_of_particles") {
444 auto const type = get_value<int>(parameters, "type");
445 return ::number_of_particles_with_type(type);
446 }
447 if (name == "velocity_difference") {
448 auto const pos1 = get_value<Utils::Vector3d>(parameters, "pos1");
449 auto const pos2 = get_value<Utils::Vector3d>(parameters, "pos2");
450 auto const v1 = get_value<Utils::Vector3d>(parameters, "v1");
451 auto const v2 = get_value<Utils::Vector3d>(parameters, "v2");
452 return m_instance->box_geo->velocity_difference(pos2, pos1, v2, v1);
453 }
454 if (name == "distance_vec") {
455 auto const pos1 = get_value<Utils::Vector3d>(parameters, "pos1");
456 auto const pos2 = get_value<Utils::Vector3d>(parameters, "pos2");
457 return m_instance->box_geo->get_mi_vector(pos2, pos1);
458 }
459 if (name == "rotate_system") {
460 rotate_system(*m_instance->cell_structure,
463 get_value<double>(parameters, "alpha"));
464 m_instance->on_particle_change();
465 m_instance->update_dependent_particles();
466 return {};
467 }
468 if (name == "get_propagation_modes_enum") {
470 }
471 if (name == "session_shutdown") {
472 if (m_instance) {
473 if (&::System::get_system() == m_instance.get()) {
475 }
476 assert(m_instance.use_count() == 1l);
477 m_leaves.reset();
478 m_instance.reset();
479 }
480 return {};
481 }
482 if (name == "internal_attach_leaves") {
483 m_leaves->part->attach(m_leaves->cell_system,
484 m_leaves->bonded_interactions);
485#ifdef ESPRESSO_COLLISION_DETECTION
486 m_leaves->collision_detection->attach(m_leaves->bonded_interactions);
487#endif
488 return {};
489 }
490 return {};
491}
492
493/**
494 * @brief Serialize particles.
495 * Particles need to be serialized here to reduce overhead,
496 * and also to guarantee particles get instantiated after the cell structure
497 * was instantiated (since they store a weak pointer to it).
498 */
499std::string System::get_internal_state() const {
500 auto const p_ids = get_particle_ids();
501 std::vector<std::string> object_states(p_ids.size());
502
503 std::ranges::transform(p_ids, object_states.begin(), [this](auto const p_id) {
504 auto p_obj = context()->make_shared(
505 "Particles::ParticleHandle",
506 {{"id", p_id}, {"__cell_structure", m_leaves->cell_system}});
507 auto &p_handle = dynamic_cast<Particles::ParticleHandle &>(*p_obj);
508 auto const packed_state = p_handle.serialize();
509 // custom particle serialization
510 auto state = Utils::unpack<ObjectState>(packed_state);
511 state.name = "Particles::ParticleHandle";
512 auto const bonds_view = p_handle.call_method("get_bonds_view", {});
513 state.params.emplace_back(std::string{"bonds"}, pack(bonds_view));
514#ifdef ESPRESSO_EXCLUSIONS
515 auto const exclusions = p_handle.call_method("get_exclusions", {});
516 state.params.emplace_back(std::string{"exclusions"}, pack(exclusions));
517#endif // ESPRESSO_EXCLUSIONS
518 state.params.emplace_back(std::string{"__cpt_sentinel"}, pack(None{}));
519 return Utils::pack(state);
520 });
521
523}
524
525void System::set_internal_state(std::string const &state) {
526 auto const object_states = Utils::unpack<std::vector<std::string>>(state);
527#ifdef ESPRESSO_EXCLUSIONS
528 std::unordered_map<int, Variant> exclusions = {};
529#endif // ESPRESSO_EXCLUSIONS
530 std::unordered_map<int, Variant> bonds = {};
531
532 for (auto const &packed_object : object_states) {
533 auto state = Utils::unpack<ObjectState>(packed_object);
534 VariantMap params = {};
535 for (auto const &[name, packed_value] : state.params) {
536 params[name] = unpack(packed_value, {});
537 }
538 auto const p_id = get_value<int>(params.at("id"));
539 bonds[p_id] = params.extract("bonds").mapped();
540#ifdef ESPRESSO_EXCLUSIONS
541 exclusions[p_id] = params.extract("exclusions").mapped();
542#endif // ESPRESSO_EXCLUSIONS
543 params["__cell_structure"] = get_parameter("cell_system");
544 context()->make_shared("Particles::ParticleHandle", params);
545 }
546
547 for (auto const p_id : get_particle_ids()) {
548 auto p_obj = context()->make_shared(
549 "Particles::ParticleHandle",
550 {{"id", p_id}, {"__cell_structure", m_leaves->cell_system}});
551 auto &p_handle = dynamic_cast<Particles::ParticleHandle &>(*p_obj);
552 set_bonds(p_handle, bonds[p_id]);
553#ifdef ESPRESSO_EXCLUSIONS
554 set_exclusions(p_handle, exclusions[p_id]);
555#endif // ESPRESSO_EXCLUSIONS
556 }
557}
558
559} // namespace System
560} // namespace ScriptInterface
@ NSQUARE
Atom decomposition (N-square).
@ REGULAR
Regular decomposition.
static int coord(std::string const &s)
Vector implementation and trait types for boost qvm interoperability.
This file contains everything related to the global cell structure / cell system.
Describes a cell structure / cell system.
void update_ghosts_and_resort_particle(unsigned data_parts)
Update ghost particles, with particle resort if needed.
void set_resort_particles(Cells::Resort level)
Increase the local resort level at least to level.
ParticleRange local_particles() const
void add_parameters(std::vector< AutoParameter > &&params)
Type to indicate no value in Variant.
Definition None.hpp:32
std::string serialize() const
Variant call_method(const std::string &name, const VariantMap &params)
Call a method on the object.
static std::shared_ptr< System > create()
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.
Definition Vector.hpp:132
boost::mpi::communicator comm_cart
The communicator.
constexpr double inactive_cutoff
Special cutoff value for an inactive interaction.
Definition config.hpp:44
This file contains the asynchronous MPI communication.
@ DATA_PART_PROPERTIES
Particle::p.
@ DATA_PART_POSITION
Particle::r.
static void set_bonds(Particles::ParticleHandle &p, Variant const &bonds)
static void set_exclusions(Particles::ParticleHandle &p, Variant const &exclusions)
static void rotate_system(CellStructure &cell_structure, double phi, double theta, double alpha)
static void rescale_particles(CellStructure &cell_structure, int dir, double scale)
Rescale all particle positions in direction dir by a factor scale.
PackedVariant pack(const Variant &v)
Transform a Variant to a PackedVariant.
T get_value(Variant const &v)
Extract value of specific type T from a Variant.
std::unordered_map< std::string, Variant > VariantMap
Definition Variant.hpp:133
auto make_unordered_map_of_variants(std::unordered_map< K, V > const &v)
Definition Variant.hpp:144
Variant unpack(const PackedVariant &v, std::unordered_map< ObjectId, ObjectRef > const &objects)
Unpack a PackedVariant.
make_recursive_variant< ObjectRef > Variant
Possible types for parameters.
Definition Variant.hpp:131
System & get_system()
void set_system(std::shared_ptr< System > new_instance)
Vector3d vec_rotate(const Vector3d &axis, double angle, const Vector3d &vector)
Rotate a vector around an axis.
std::string pack(T const &v)
Pack a serialize type into a string.
Definition pack.hpp:38
STL namespace.
Various procedures concerning interactions between particles.
Exports for the NpT code.
Routines to calculate the OIF global forces for a particle triple (triangle from mesh).
void init_type_map(int type)
std::vector< int > get_particle_ids()
Get all particle ids.
Particles creation and deletion.
std::unordered_map< std::string, int > propagation_flags_map()
Convert PropagationMode::PropagationMode to name/value pairs.
This file contains all subroutines required to process rotational motion.
void local_rotate_particle(Particle &p, const Utils::Vector3d &axis_space_frame, const double phi)
Rotate the particle p around the NORMALIZED axis aSpaceFrame by amount phi.
Definition rotation.hpp:134
static SteepestDescentParameters params
Currently active steepest descent instance.
Description and getter/setter for a parameter.
Container for leaves of the system class.
std::shared_ptr< Thermostat::Thermostat > thermostat
std::shared_ptr< Integrators::IntegratorHandle > integrator
std::shared_ptr< Dipoles::Container > magnetostatics
std::shared_ptr< CellSystem::CellSystem > cell_system
std::shared_ptr< Particles::ParticleList > part
std::shared_ptr< BondBreakage::BreakageSpecs > bond_breakage
std::shared_ptr< Constraints::Constraints > constraints
std::shared_ptr< Interactions::BondedInteractions > bonded_interactions
std::shared_ptr< CollisionDetection::CollisionDetection > collision_detection
std::shared_ptr< Interactions::NonBondedInteractions > non_bonded_inter
std::shared_ptr< Coulomb::Container > electrostatics
std::shared_ptr< Accumulators::AutoUpdateAccumulators > auto_update_accumulators
std::shared_ptr< LeesEdwards::LeesEdwards > lees_edwards
Recursive variant implementation.
Definition Variant.hpp:84