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"
35#include "core/propagation.hpp"
36#include "core/rotation.hpp"
39
58
59#include <utils/Vector.hpp>
60#include <utils/demangle.hpp>
63
64#include <boost/mpi/collectives.hpp>
65
66#include <algorithm>
67#include <array>
68#include <cassert>
69#include <cmath>
70#include <functional>
71#include <initializer_list>
72#include <memory>
73#include <stdexcept>
74#include <string>
75#include <type_traits>
76#include <vector>
77
78namespace ScriptInterface {
79namespace System {
80
81static bool system_created = false;
82
83#ifdef EXCLUSIONS
85 Variant const &exclusions) {
86 p.call_method("set_exclusions", {{"p_ids", exclusions}});
87}
88#endif // EXCLUSIONS
89
90static void set_bonds(Particles::ParticleHandle &p, Variant const &bonds) {
92 for (auto const &bond_flat : bond_list_flat) {
93 auto const bond_id = bond_flat[0];
94 auto const part_id =
95 std::vector<int>{bond_flat.begin() + 1, bond_flat.end()};
96 p.call_method("add_bond",
97 {{"bond_id", bond_id}, {"part_id", std::move(part_id)}});
98 }
99}
100
101/** @brief Container for leaves of the system class. */
103 Leaves() = default;
104 std::shared_ptr<CellSystem::CellSystem> cell_system;
105 std::shared_ptr<Integrators::IntegratorHandle> integrator;
106 std::shared_ptr<Interactions::BondedInteractions> bonded_interactions;
107#ifdef COLLISION_DETECTION
108 std::shared_ptr<CollisionDetection::CollisionDetection> collision_detection;
109#endif
110 std::shared_ptr<Thermostat::Thermostat> thermostat;
111 std::shared_ptr<Analysis::Analysis> analysis;
112 std::shared_ptr<Galilei::ComFixed> comfixed;
113 std::shared_ptr<Galilei::Galilei> galilei;
114 std::shared_ptr<BondBreakage::BreakageSpecs> bond_breakage;
115 std::shared_ptr<LeesEdwards::LeesEdwards> lees_edwards;
116 std::shared_ptr<Accumulators::AutoUpdateAccumulators>
118 std::shared_ptr<Constraints::Constraints> constraints;
119 std::shared_ptr<Interactions::NonBondedInteractions> non_bonded_inter;
120#ifdef ELECTROSTATICS
121 std::shared_ptr<Coulomb::Container> electrostatics;
122#endif
123#ifdef DIPOLES
124 std::shared_ptr<Dipoles::Container> magnetostatics;
125#endif
126 std::shared_ptr<Particles::ParticleList> part;
127
129 // Clear containers whose elements call MPI callbacks upon destruction.
130 // The containers lifetime is extended by the global context shared object
131 // registry on the head node, which can cause MPI deadlocks if they still
132 // contain elements.
134 bonded_interactions->clear();
135 }
136 if (constraints) {
137 constraints->clear();
138 }
139 }
140};
141
142System::System() : m_instance{}, m_leaves{std::make_unique<Leaves>()} {
143 auto const add_parameter =
144 [this, ptr = m_leaves.get()](std::string key, auto(Leaves::*member)) {
146 key.c_str(),
147 [this, ptr, member, key](Variant const &val) {
148 auto &dst = ptr->*member;
149 if (dst != nullptr) {
150 throw WriteError(key);
151 }
152 dst = get_value<std::remove_reference_t<decltype(dst)>>(val);
153 dst->bind_system(m_instance);
154 },
155 [ptr, member]() { return ptr->*member; })});
156 };
157
158 add_parameters({
159 {"box_l",
160 [this](Variant const &v) {
161 context()->parallel_try_catch([&]() {
164 throw std::domain_error("Attribute 'box_l' must be > 0");
165 }
166 m_instance->veto_boxl_change();
167 m_instance->box_geo->set_length(new_value);
168 m_instance->on_boxl_change();
169 });
170 },
171 [this]() { return m_instance->box_geo->length(); }},
172 {"periodicity",
173 [this](Variant const &v) {
175 for (unsigned int i = 0u; i < 3u; ++i) {
176 m_instance->box_geo->set_periodic(i, periodicity[i]);
177 }
178 context()->parallel_try_catch(
179 [&]() { m_instance->on_periodicity_change(); });
180 },
181 [this]() {
182 return Utils::Vector3b{m_instance->box_geo->periodic(0),
183 m_instance->box_geo->periodic(1),
184 m_instance->box_geo->periodic(2)};
185 }},
186 {"min_global_cut",
187 [this](Variant const &v) {
188 context()->parallel_try_catch([&]() {
189 auto const new_value = get_value<double>(v);
191 throw std::domain_error("Attribute 'min_global_cut' must be >= 0");
192 }
193 m_instance->set_min_global_cut(new_value);
194 });
195 },
196 [this]() { return m_instance->get_min_global_cut(); }},
197 {"max_oif_objects",
198 [this](Variant const &v) {
199 m_instance->oif_global->max_oif_objects = get_value<int>(v);
200 },
201 [this]() { return m_instance->oif_global->max_oif_objects; }},
202 });
203 // note: the order of leaves matters! e.g. bonds depend on thermostats,
204 // and thus a thermostat object must be instantiated before the bonds
205 add_parameter("cell_system", &Leaves::cell_system);
206 add_parameter("integrator", &Leaves::integrator);
207 add_parameter("thermostat", &Leaves::thermostat);
208 add_parameter("analysis", &Leaves::analysis);
209 add_parameter("comfixed", &Leaves::comfixed);
210 add_parameter("galilei", &Leaves::galilei);
211 add_parameter("bonded_inter", &Leaves::bonded_interactions);
212#ifdef COLLISION_DETECTION
213 add_parameter("collision_detection", &Leaves::collision_detection);
214#endif
215 add_parameter("bond_breakage", &Leaves::bond_breakage);
216 add_parameter("lees_edwards", &Leaves::lees_edwards);
217 add_parameter("auto_update_accumulators", &Leaves::auto_update_accumulators);
218 add_parameter("constraints", &Leaves::constraints);
219 add_parameter("non_bonded_inter", &Leaves::non_bonded_inter);
220#ifdef ELECTROSTATICS
221 add_parameter("electrostatics", &Leaves::electrostatics);
222#endif
223#ifdef DIPOLES
224 add_parameter("magnetostatics", &Leaves::magnetostatics);
225#endif
226 add_parameter("part", &Leaves::part);
227}
228
229template <typename LeafType>
230void System::do_set_default_parameter(std::string const &name) {
231 assert(context()->is_head_node());
232 auto const so_name = Utils::demangle<LeafType>().substr(17);
233 set_parameter(name, Variant{context()->make_shared(so_name, {})});
234}
235
236void System::do_construct(VariantMap const &params) {
237 /* When reloading the system state from a checkpoint file,
238 * the order of global variables instantiation matters.
239 * The @c box_l must be set before any other global variable.
240 * All these globals re-initialize the cell system, and we
241 * cannot use the default-constructed @c box_geo when e.g.
242 * long-range interactions exist in the system, otherwise
243 * runtime errors about the local geometry being smaller
244 * than the interaction range would be raised.
245 */
246 context()->parallel_try_catch([&]() {
247 if (not params.contains("box_l")) {
248 throw std::domain_error("Required argument 'box_l' not provided.");
249 }
250 if (params.contains("_regular_constructor") and system_created) {
251 throw std::runtime_error(
252 "You can only have one instance of the system class at a time");
253 }
254 });
255 m_instance = ::System::System::create();
256 ::System::set_system(m_instance);
257
258 // domain decomposition can only be set after box_l is set
259 m_instance->set_cell_structure_topology(CellStructureType::NSQUARE);
260 do_set_parameter("box_l", params.at("box_l"));
261 m_instance->set_cell_structure_topology(CellStructureType::REGULAR);
262
263 m_instance->lb.bind_system(m_instance);
264 m_instance->ek.bind_system(m_instance);
265
266 if (params.contains("_regular_constructor")) {
267 std::set<std::string> const setable_properties = {
268 "box_l", "min_global_cut",
269 "periodicity", "time",
270 "time_step", "force_cap",
271 "max_oif_objects", "_regular_constructor"};
272 for (auto const &kv : params) {
273 if (not setable_properties.contains(kv.first)) {
274 context()->parallel_try_catch([&kv]() {
275 throw std::domain_error(
276 "Property '" + kv.first +
277 "' cannot be set via argument to System class");
278 });
279 }
280 }
281 for (std::string attr :
282 {"min_global_cut", "periodicity", "max_oif_objects"}) {
283 if (params.contains(attr)) {
284 do_set_parameter(attr, params.at(attr));
285 }
286 }
287 if (not context()->is_head_node()) {
288 return;
289 }
290 auto integrator = std::dynamic_pointer_cast<Integrators::IntegratorHandle>(
291 context()->make_shared("Integrators::IntegratorHandle", {}));
292 set_parameter("integrator", integrator);
293 for (std::string attr : {"time", "time_step", "force_cap"}) {
294 if (params.contains(attr)) {
295 integrator->set_parameter(attr, params.at(attr));
296 }
297 }
298 // note: the order of leaves matters! e.g. bonds depend on thermostats,
299 // and thus a thermostat object must be instantiated before the bonds
303#ifdef COLLISION_DETECTION
305 "collision_detection");
306#endif
313 "auto_update_accumulators");
316 "non_bonded_inter");
317#ifdef ELECTROSTATICS
319#endif
320#ifdef DIPOLES
322#endif
324 } else {
325 for (auto const &key : get_parameter_insertion_order()) {
326 if (key != "box_l" and params.contains(key)) {
327 do_set_parameter(key, params.at(key));
328 }
329 }
330 }
331 if (not context()->is_head_node()) {
332 return;
333 }
334 call_method("internal_attach_leaves", {});
335}
336
337static void rotate_system(CellStructure &cell_structure, double phi,
338 double theta, double alpha) {
339 auto const particles = cell_structure.local_particles();
340
341 // Calculate center of mass
343 double local_mass = 0.0;
344
345 for (auto const &p : particles) {
346 if (not p.is_virtual()) {
347 local_com += p.mass() * p.pos();
348 local_mass += p.mass();
349 }
350 }
351
352 auto const total_mass =
353 boost::mpi::all_reduce(comm_cart, local_mass, std::plus<>());
354 auto const com =
355 boost::mpi::all_reduce(comm_cart, local_com, std::plus<>()) / total_mass;
356
357 // Rotation axis in Cartesian coordinates
358 Utils::Vector3d axis;
359 axis[0] = std::sin(theta) * std::cos(phi);
360 axis[1] = std::sin(theta) * std::sin(phi);
361 axis[2] = std::cos(theta);
362
363 // Rotate particle coordinates
364 for (auto &p : particles) {
365 // Move the center of mass of the system to the origin
366 p.pos() = com + Utils::vec_rotate(axis, alpha, p.pos() - com);
367#ifdef ROTATION
368 local_rotate_particle(p, axis, alpha);
369#endif
370 }
371
375}
376
377/** Rescale all particle positions in direction @p dir by a factor @p scale.
378 * @param cell_structure cell structure
379 * @param dir direction to scale (0/1/2 = x/y/z, 3 = x+y+z isotropically)
380 * @param scale factor by which to rescale (>1: stretch, <1: contract)
381 */
382static void rescale_particles(CellStructure &cell_structure, int dir,
383 double scale) {
384 for (auto &p : cell_structure.local_particles()) {
385 if (dir < 3)
386 p.pos()[dir] *= scale;
387 else {
388 p.pos() *= scale;
389 }
390 }
391}
392
393Variant System::do_call_method(std::string const &name,
394 VariantMap const &parameters) {
395 if (name == "lock_system_creation") {
396 system_created = true;
397 return {};
398 }
399 if (name == "rescale_boxl") {
400 auto &box_geo = *m_instance->box_geo;
401 auto const coord = get_value<int>(parameters, "coord");
402 auto const length = get_value<double>(parameters, "length");
403 assert(coord >= 0);
404 assert(coord != 3 or ((box_geo.length()[0] == box_geo.length()[1]) and
405 (box_geo.length()[1] == box_geo.length()[2])));
406 auto const scale = (coord == 3) ? length * box_geo.length_inv()[0]
407 : length * box_geo.length_inv()[coord];
408 context()->parallel_try_catch([&]() {
409 if (length <= 0.) {
410 throw std::domain_error("Parameter 'd_new' must be > 0");
411 }
412 m_instance->veto_boxl_change(true);
413 });
414 auto new_value = Utils::Vector3d{};
415 if (coord == 3) {
417 } else {
418 new_value = box_geo.length();
419 new_value[static_cast<unsigned>(coord)] = length;
420 }
421 // when shrinking, rescale the particles first
422 if (scale <= 1.) {
423 rescale_particles(*m_instance->cell_structure, coord, scale);
424 m_instance->on_particle_change();
425 }
426 m_instance->box_geo->set_length(new_value);
427 m_instance->on_boxl_change();
428 if (scale > 1.) {
429 rescale_particles(*m_instance->cell_structure, coord, scale);
430 m_instance->on_particle_change();
431 }
432 return {};
433 }
434 if (name == "setup_type_map") {
435 auto const types = get_value<std::vector<int>>(parameters, "type_list");
436 for (auto const type : types) {
437 ::init_type_map(type);
438 }
439 return {};
440 }
441 if (name == "number_of_particles") {
442 auto const type = get_value<int>(parameters, "type");
443 return ::number_of_particles_with_type(type);
444 }
445 if (name == "velocity_difference") {
446 auto const pos1 = get_value<Utils::Vector3d>(parameters, "pos1");
447 auto const pos2 = get_value<Utils::Vector3d>(parameters, "pos2");
448 auto const v1 = get_value<Utils::Vector3d>(parameters, "v1");
449 auto const v2 = get_value<Utils::Vector3d>(parameters, "v2");
450 return m_instance->box_geo->velocity_difference(pos2, pos1, v2, v1);
451 }
452 if (name == "distance_vec") {
453 auto const pos1 = get_value<Utils::Vector3d>(parameters, "pos1");
454 auto const pos2 = get_value<Utils::Vector3d>(parameters, "pos2");
455 return m_instance->box_geo->get_mi_vector(pos2, pos1);
456 }
457 if (name == "rotate_system") {
458 rotate_system(*m_instance->cell_structure,
461 get_value<double>(parameters, "alpha"));
462 m_instance->on_particle_change();
463 m_instance->update_dependent_particles();
464 return {};
465 }
466 if (name == "get_propagation_modes_enum") {
468 }
469 if (name == "session_shutdown") {
470 if (m_instance) {
471 if (&::System::get_system() == m_instance.get()) {
473 }
474 assert(m_instance.use_count() == 1l);
475 m_leaves.reset();
476 m_instance.reset();
477 }
478 return {};
479 }
480 if (name == "internal_attach_leaves") {
481 m_leaves->part->attach(m_leaves->cell_system,
482 m_leaves->bonded_interactions);
483#ifdef COLLISION_DETECTION
484 m_leaves->collision_detection->attach(m_leaves->bonded_interactions);
485#endif
486 return {};
487 }
488 return {};
489}
490
491/**
492 * @brief Serialize particles.
493 * Particles need to be serialized here to reduce overhead,
494 * and also to guarantee particles get instantiated after the cell structure
495 * was instantiated (since they store a weak pointer to it).
496 */
497std::string System::get_internal_state() const {
498 auto const p_ids = get_particle_ids();
499 std::vector<std::string> object_states(p_ids.size());
500
501 std::ranges::transform(p_ids, object_states.begin(), [this](auto const p_id) {
502 auto p_obj = context()->make_shared(
503 "Particles::ParticleHandle",
504 {{"id", p_id}, {"__cell_structure", m_leaves->cell_system}});
505 auto &p_handle = dynamic_cast<Particles::ParticleHandle &>(*p_obj);
506 auto const packed_state = p_handle.serialize();
507 // custom particle serialization
508 auto state = Utils::unpack<ObjectState>(packed_state);
509 state.name = "Particles::ParticleHandle";
510 auto const bonds_view = p_handle.call_method("get_bonds_view", {});
511 state.params.emplace_back(std::string{"bonds"}, pack(bonds_view));
512#ifdef EXCLUSIONS
513 auto const exclusions = p_handle.call_method("get_exclusions", {});
514 state.params.emplace_back(std::string{"exclusions"}, pack(exclusions));
515#endif // EXCLUSIONS
516 state.params.emplace_back(std::string{"__cpt_sentinel"}, pack(None{}));
517 return Utils::pack(state);
518 });
519
521}
522
523void System::set_internal_state(std::string const &state) {
524 auto const object_states = Utils::unpack<std::vector<std::string>>(state);
525#ifdef EXCLUSIONS
526 std::unordered_map<int, Variant> exclusions = {};
527#endif // EXCLUSIONS
528 std::unordered_map<int, Variant> bonds = {};
529
530 for (auto const &packed_object : object_states) {
531 auto state = Utils::unpack<ObjectState>(packed_object);
532 VariantMap params = {};
533 for (auto const &kv : state.params) {
534 params[kv.first] = unpack(kv.second, {});
535 }
536 auto const p_id = get_value<int>(params.at("id"));
537 bonds[p_id] = params.extract("bonds").mapped();
538#ifdef EXCLUSIONS
539 exclusions[p_id] = params.extract("exclusions").mapped();
540#endif // EXCLUSIONS
541 params["__cell_structure"] = get_parameter("cell_system");
542 context()->make_shared("Particles::ParticleHandle", params);
543 }
544
545 for (auto const p_id : get_particle_ids()) {
546 auto p_obj = context()->make_shared(
547 "Particles::ParticleHandle",
548 {{"id", p_id}, {"__cell_structure", m_leaves->cell_system}});
549 auto &p_handle = dynamic_cast<Particles::ParticleHandle &>(*p_obj);
550 set_bonds(p_handle, bonds[p_id]);
551#ifdef EXCLUSIONS
552 set_exclusions(p_handle, exclusions[p_id]);
553#endif // EXCLUSIONS
554 }
555}
556
557} // namespace System
558} // 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.
void add_parameters(std::vector< AutoParameter > &&params)
Type to indicate no value in Variant.
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:111
boost::mpi::communicator comm_cart
The communicator.
This file contains the defaults for ESPResSo.
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:69
auto make_unordered_map_of_variants(std::unordered_map< K, V > const &v)
Definition Variant.hpp:80
boost::make_recursive_variant< None, bool, int, std::size_t, double, std::string, ObjectRef, Utils::Vector3b, Utils::Vector3i, Utils::Vector2d, Utils::Vector3d, Utils::Vector4d, std::vector< int >, std::vector< double >, std::vector< boost::recursive_variant_ >, std::unordered_map< int, boost::recursive_variant_ >, std::unordered_map< std::string, boost::recursive_variant_ > >::type Variant
Possible types for parameters.
Definition Variant.hpp:67
Variant unpack(const PackedVariant &v, std::unordered_map< ObjectId, ObjectRef > const &objects)
Unpack a PackedVariant.
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
Various procedures concerning interactions between particles.
constexpr double INACTIVE_CUTOFF
Cutoff for deactivated interactions.
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:133
static SteepestDescentParameters params
Currently active steepest descent instance.
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
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