Loading [MathJax]/extensions/TeX/AMSmath.js
ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages Concepts
particle_node.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#include "particle_node.hpp"
23
24#include "BoxGeometry.hpp"
25#include "Particle.hpp"
27#include "cells.hpp"
28#include "communication.hpp"
30#include "system/System.hpp"
31
32#include <utils/Cache.hpp>
33#include <utils/Vector.hpp>
34#include <utils/mpi/gatherv.hpp>
35
36#include <boost/mpi/collectives/all_gather.hpp>
37#include <boost/mpi/collectives/all_reduce.hpp>
38#include <boost/mpi/collectives/gather.hpp>
39#include <boost/mpi/collectives/reduce.hpp>
40#include <boost/mpi/collectives/scatter.hpp>
41
42#include <algorithm>
43#include <cmath>
44#include <functional>
45#include <iterator>
46#include <ranges>
47#include <span>
48#include <stdexcept>
49#include <string>
50#include <unordered_map>
51#include <unordered_set>
52#include <utility>
53#include <vector>
54
55constexpr auto some_tag = 42;
56
57/** @brief Enable particle type tracking in @ref particle_type_map. */
58static bool type_list_enable;
59
60/** @brief Mapping particle types to lists of particle ids. */
61static std::unordered_map<int, std::unordered_set<int>> particle_type_map;
62
63/** @brief Mapping particle ids to MPI ranks. */
64static std::unordered_map<int, int> particle_node;
65
66static auto &get_cell_structure() {
68}
69
70/**
71 * @brief Keep track of the largest particle id.
72 * This book-keeping variable is necessary to make particle insertion run
73 * in constant time. Traversing the @ref particle_node to find the largest
74 * particle id scales with O(N) and traversing the local cells in parallel
75 * followed by a reduction scales with O(N^2).
76 */
77static int max_seen_pid = -1;
78
79static auto rebuild_needed() {
80 auto is_rebuild_needed = ::particle_node.empty();
81 boost::mpi::broadcast(::comm_cart, is_rebuild_needed, 0);
82 return is_rebuild_needed;
83}
84
86 boost::mpi::broadcast(::comm_cart, ::max_seen_pid, 0);
87}
88
89void init_type_map(int type) {
90 if (type < 0) {
91 throw std::runtime_error("Types may not be negative");
92 }
93 ::type_list_enable = true;
94 auto &nonbonded_ias = *System::get_system().nonbonded_ias;
95 nonbonded_ias.make_particle_type_exist(type);
96
97 std::vector<int> local_pids;
98 for (auto const &p : get_cell_structure().local_particles()) {
99 if (p.type() == type) {
100 local_pids.emplace_back(p.id());
101 }
102 }
103
104 std::vector<std::vector<int>> global_pids;
105 boost::mpi::all_gather(::comm_cart, local_pids, global_pids);
106 ::particle_type_map[type].clear();
107 for (auto const &vec : global_pids) {
108 for (auto const &p_id : vec) {
109 ::particle_type_map[type].insert(p_id);
110 }
111 }
112}
113
114static void remove_id_from_map(int p_id, int type) {
115 auto it = particle_type_map.find(type);
116 if (it != particle_type_map.end())
117 it->second.erase(p_id);
118}
119
120static void add_id_to_type_map(int p_id, int type) {
121 auto it = particle_type_map.find(type);
122 if (it != particle_type_map.end())
123 it->second.insert(p_id);
124}
125
126void on_particle_type_change(int p_id, int old_type, int new_type) {
127 if (::type_list_enable) {
128 if (old_type == type_tracking::any_type) {
129 for (auto &kv : ::particle_type_map) {
130 auto it = kv.second.find(p_id);
131 if (it != kv.second.end()) {
132 kv.second.erase(it);
133#ifndef NDEBUG
134 if (auto p = get_cell_structure().get_local_particle(p_id)) {
135 assert(p->type() == kv.first);
136 }
137#endif
138 break;
139 }
140 }
141 } else if (old_type != type_tracking::new_part) {
142 if (old_type != new_type) {
143 remove_id_from_map(p_id, old_type);
144 }
145 }
146 add_id_to_type_map(p_id, new_type);
147 }
148}
149
150namespace {
151/* Limit cache to 100 MiB */
152std::size_t const max_cache_size = (100ul * 1048576ul) / sizeof(Particle);
154} // namespace
155
157std::size_t fetch_cache_max_size() { return particle_fetch_cache.max_size(); }
158
159static void mpi_send_particle_data_local(int p_id) {
160 auto const p = get_cell_structure().get_local_particle(p_id);
161 auto const found = p and not p->is_ghost();
162 assert(1 == boost::mpi::all_reduce(::comm_cart, static_cast<int>(found),
163 std::plus<>()) &&
164 "Particle not found");
165 if (found) {
166 ::comm_cart.send(0, 42, *p);
167 }
168}
169
171
172const Particle &get_particle_data(int p_id) {
173 auto const pnode = get_particle_node(p_id);
174
175 if (pnode == this_node) {
176 auto const p = get_cell_structure().get_local_particle(p_id);
177 assert(p != nullptr);
178 return *p;
179 }
180
181 /* Query the cache */
182 auto const p_ptr = particle_fetch_cache.get(p_id);
183 if (p_ptr) {
184 return *p_ptr;
185 }
186
187 /* Cache miss, fetch the particle,
188 * put it into the cache and return a pointer into the cache. */
190 Particle result{};
191 ::comm_cart.recv(boost::mpi::any_source, boost::mpi::any_tag, result);
192 return *(particle_fetch_cache.put(p_id, std::move(result)));
193}
194
196 std::vector<int> local_ids;
197 boost::mpi::scatter(comm_cart, local_ids, 0);
198
199 std::vector<Particle> parts(local_ids.size());
200 std::ranges::transform(local_ids, parts.begin(), [](int p_id) {
201 auto const p = get_cell_structure().get_local_particle(p_id);
202 assert(p != nullptr);
203 return *p;
204 });
205
206 Utils::Mpi::gatherv(comm_cart, parts.data(), static_cast<int>(parts.size()),
207 0);
208}
209
211
212/**
213 * @brief Get multiple particles at once.
214 *
215 * *WARNING* Particles are returned in an arbitrary order.
216 *
217 * @param ids The ids of the particles that should be returned.
218 *
219 * @returns The particle list.
220 */
221static std::vector<Particle> mpi_get_particles(std::span<const int> ids) {
223 /* Return value */
224 std::vector<Particle> parts(ids.size());
225
226 /* Group ids per node */
227 static std::vector<std::vector<int>> node_ids(comm_cart.size());
228 for (auto &per_node : node_ids) {
229 per_node.clear();
230 }
231
232 for (auto const &p_id : ids) {
233 auto const p_node = get_particle_node(p_id);
234 node_ids[p_node].emplace_back(p_id);
235 }
236 /* We shouldn't be prefetching particles that are already on the head node */
237 assert(node_ids[this_node].empty());
238
239 /* Distribute ids to the worker nodes */
240 {
241 static std::vector<int> ignore;
242 boost::mpi::scatter(comm_cart, node_ids, ignore, 0);
243 assert(ignore.empty());
244 }
245
246 static std::vector<int> node_sizes(comm_cart.size());
247 std::ranges::transform(std::as_const(node_ids), node_sizes.begin(),
248 std::size<std::vector<int>>);
249
250 Utils::Mpi::gatherv(comm_cart, parts.data(), static_cast<int>(parts.size()),
251 parts.data(), node_sizes.data(), 0);
252
253 return parts;
254}
255
256void prefetch_particle_data(std::span<const int> in_ids) {
257 /* Nothing to do on a single node. */
258 // NOLINTNEXTLINE(clang-analyzer-core.NonNullParamChecker)
259 if (comm_cart.size() == 1)
260 return;
261
262 static std::vector<int> ids;
263 ids.clear();
264 auto out_ids = std::back_inserter(ids);
265
266 /* Don't prefetch particles already on the head node or already cached. */
267 std::ranges::copy_if(in_ids, out_ids, [](int id) {
268 return (get_particle_node(id) != this_node) && particle_fetch_cache.has(id);
269 });
270
271 /* Don't prefetch more particles than fit the cache. */
272 if (ids.size() > particle_fetch_cache.max_size())
273 ids.resize(particle_fetch_cache.max_size());
274
275 /* Fetch the particles... */
276 for (auto &p : mpi_get_particles(ids)) {
277 auto id = p.id();
278 particle_fetch_cache.put(id, std::move(p));
279 }
280}
281
282static void mpi_who_has_local() {
283 static std::vector<int> sendbuf;
284
285 auto local_particles = get_cell_structure().local_particles();
286 auto const n_part = static_cast<int>(local_particles.size());
287 boost::mpi::gather(comm_cart, n_part, 0);
288
289 if (n_part == 0) {
291 return;
292 }
293
294 sendbuf.resize(n_part);
295
296 std::transform(local_particles.begin(), local_particles.end(),
297 sendbuf.begin(), [](Particle const &p) { return p.id(); });
298
299 comm_cart.send(0, some_tag, sendbuf);
301}
302
304
305static void mpi_who_has_head() {
306 auto local_particles = get_cell_structure().local_particles();
307
308 static std::vector<int> n_parts;
309 boost::mpi::gather(comm_cart, static_cast<int>(local_particles.size()),
310 n_parts, 0);
311
312 static std::vector<int> pdata;
313 auto const n_nodes = ::comm_cart.size();
314 max_seen_pid = -1;
315
316 /* then fetch particle locations */
317 for (int pnode = 0; pnode < n_nodes; pnode++) {
318 if (pnode == this_node) {
319 for (auto const &p : local_particles) {
320 particle_node[p.id()] = this_node;
321 max_seen_pid = std::max(max_seen_pid, p.id());
322 }
323 } else if (n_parts[pnode] > 0) {
324 pdata.resize(n_parts[pnode]);
325 comm_cart.recv(pnode, some_tag, pdata);
326 for (int i = 0; i < n_parts[pnode]; i++) {
327 particle_node[pdata[i]] = pnode;
328 max_seen_pid = std::max(max_seen_pid, pdata[i]);
329 }
330 }
331 }
333}
334
335/**
336 * @brief Rebuild the particle index.
337 */
342
343/**
344 * @brief Rebuild the particle index.
345 */
347 if (this_node == 0) {
349 } else {
351 }
352}
353
354int get_particle_node(int p_id) {
355 if (p_id < 0) {
356 throw std::domain_error("Invalid particle id: " + std::to_string(p_id));
357 }
358
359 if (particle_node.empty())
361
362 auto const needle = particle_node.find(p_id);
363
364 // Check if particle has a node, if not, we assume it does not exist.
365 if (needle == particle_node.end()) {
366 throw std::runtime_error("Particle node for id " + std::to_string(p_id) +
367 " not found!");
368 }
369 return needle->second;
370}
371
373 if (p_id < 0) {
374 throw std::domain_error("Invalid particle id: " + std::to_string(p_id));
375 }
376
377 if (rebuild_needed()) {
379 }
380
381 if (this_node != 0) {
382 return -1;
383 }
384
385 auto const needle = particle_node.find(p_id);
386
387 // Check if particle has a node, if not, we assume it does not exist.
388 if (needle == particle_node.end()) {
389 throw std::runtime_error("Particle node for id " + std::to_string(p_id) +
390 " not found!");
391 }
392 return needle->second;
393}
394
396 ::max_seen_pid = -1;
397 particle_node.clear();
398}
399
401 for (auto &kv : ::particle_type_map) {
402 kv.second.clear();
403 }
404}
405
406/**
407 * @brief Calculate the largest particle id.
408 * Traversing the @ref particle_node to find the largest particle id
409 * scales with O(N). Consider using the cached value in @ref max_seen_pid
410 * if possible. This function is only necessary when the cached value is
411 * invalidated, for example when removing the particle which has the
412 * largest id.
413 */
415 return std::accumulate(
416 particle_node.begin(), particle_node.end(), -1,
417 [](int max, auto const &kv) { return std::max(max, kv.first); });
418}
419
420/**
421 * @brief Create a new particle and attach it to a cell.
422 * @param p_id The identity of the particle to create.
423 * @param pos The particle position.
424 * @return Whether the particle was created on that node.
425 */
426static bool maybe_insert_particle(int p_id, Utils::Vector3d const &pos) {
427 auto const &box_geo = *System::get_system().box_geo;
428 auto folded_pos = pos;
429 auto image_box = Utils::Vector3i{};
430 box_geo.fold_position(folded_pos, image_box);
431
432 Particle new_part;
433 new_part.id() = p_id;
434 new_part.pos() = folded_pos;
435 new_part.image_box() = image_box;
436
437 return get_cell_structure().add_local_particle(std::move(new_part)) !=
438 nullptr;
439}
440
441/**
442 * @brief Move particle to a new position.
443 * @param p_id The identity of the particle to move.
444 * @param pos The new particle position.
445 * @return Whether the particle was moved from that node.
446 */
447static bool maybe_move_particle(int p_id, Utils::Vector3d const &pos) {
448 auto const &system = System::get_system();
449 auto const &box_geo = *system.box_geo;
450 auto p = system.cell_structure->get_local_particle(p_id);
451 if (p == nullptr) {
452 return false;
453 }
454 auto folded_pos = pos;
455 auto image_box = Utils::Vector3i{};
456 box_geo.fold_position(folded_pos, image_box);
457 p->pos() = folded_pos;
458 p->image_box() = image_box;
459 return true;
460}
461
468
469void remove_particle(int p_id) {
470 if (::type_list_enable) {
471 auto p = get_cell_structure().get_local_particle(p_id);
472 auto p_type = -1;
473 if (p != nullptr and not p->is_ghost()) {
474 if (this_node == 0) {
475 p_type = p->type();
476 } else {
477 ::comm_cart.send(0, 42, p->type());
478 }
479 } else if (this_node == 0) {
480 ::comm_cart.recv(boost::mpi::any_source, 42, p_type);
481 }
482 assert(this_node != 0 or p_type != -1);
483 boost::mpi::broadcast(::comm_cart, p_type, 0);
484 remove_id_from_map(p_id, p_type);
485 }
486
487 if (this_node == 0) {
488 particle_node[p_id] = -1;
489 }
490 get_cell_structure().remove_particle(p_id);
493 if (this_node == 0) {
494 particle_node.erase(p_id);
495 if (p_id == ::max_seen_pid) {
497 // if there is a gap (i.e. there is no particle with id max_seen_pid - 1,
498 // then the cached value is invalidated and has to be recomputed (slow)
499 if (particle_node.count(::max_seen_pid) == 0 or
502 }
503 }
504 }
506}
507
508void make_new_particle(int p_id, Utils::Vector3d const &pos) {
509 if (rebuild_needed()) {
511 }
512 auto const has_created = maybe_insert_particle(p_id, pos);
514
515 auto node = -1;
516 auto const node_local = (has_created) ? ::comm_cart.rank() : 0;
517 boost::mpi::reduce(::comm_cart, node_local, node, std::plus<int>{}, 0);
518 if (::this_node == 0) {
519 particle_node[p_id] = node;
520 max_seen_pid = std::max(max_seen_pid, p_id);
521 assert(not has_created or node == 0);
522 }
524}
525
526void set_particle_pos(int p_id, Utils::Vector3d const &pos) {
527 auto const has_moved = maybe_move_particle(p_id, pos);
528 get_cell_structure().set_resort_particles(Cells::RESORT_GLOBAL);
530
531 auto success = false;
532 boost::mpi::reduce(::comm_cart, has_moved, success, std::plus<bool>{}, 0);
533 if (::this_node == 0 and !success) {
534 throw std::runtime_error("Particle node for id " + std::to_string(p_id) +
535 " not found!");
536 }
537}
538
539int get_random_p_id(int type, int random_index_in_type_map) {
540 auto it = particle_type_map.find(type);
541 if (it == particle_type_map.end()) {
542 throw std::runtime_error("The provided particle type " +
543 std::to_string(type) +
544 " is currently not tracked by the system.");
545 }
546
547 if (random_index_in_type_map + 1 > it->second.size())
548 throw std::runtime_error("The provided index exceeds the number of "
549 "particle types listed in the particle_type_map");
550 // there is no guarantee of order across MPI ranks
551 auto p_id = *std::next(it->second.begin(), random_index_in_type_map);
552 boost::mpi::broadcast(::comm_cart, p_id, 0);
553 return p_id;
554}
555
557 auto it = particle_type_map.find(type);
558 if (it == particle_type_map.end()) {
559 throw std::runtime_error("The provided particle type " +
560 std::to_string(type) +
561 " is currently not tracked by the system.");
562 }
563
564 return static_cast<int>(it->second.size());
565}
566
567bool particle_exists(int p_id) {
568 if (particle_node.empty())
570 return particle_node.contains(p_id);
571}
572
573std::vector<int> get_particle_ids() {
574 if (particle_node.empty())
576
577 std::vector<int> pids{};
578 std::ranges::copy(std::views::keys(particle_node), std::back_inserter(pids));
579 std::ranges::sort(pids);
580
581 return pids;
582}
583
584std::vector<int> get_particle_ids_parallel() {
585 if (rebuild_needed()) {
587 }
588 std::vector<int> pids{};
589 std::ranges::copy(std::views::keys(particle_node), std::back_inserter(pids));
590 boost::mpi::broadcast(::comm_cart, pids, 0);
591 return pids;
592}
593
595 if (rebuild_needed()) {
597 }
598
599 return max_seen_pid;
600}
601
603 if (particle_node.empty())
605
606 return static_cast<int>(particle_node.size());
607}
#define REGISTER_CALLBACK(cb)
Register a static callback without return value.
Vector implementation and trait types for boost qvm interoperability.
This file contains everything related to the global cell structure / cell system.
auto call_all(void(*fp)(Args...), ArgRef &&...args) const -> std::enable_if_t< std::is_void_v< decltype(fp(args...))> >
Call a callback on all nodes.
void on_particle_change()
Called every time a particle property changes.
std::shared_ptr< CellStructure > cell_structure
std::shared_ptr< BoxGeometry > box_geo
std::shared_ptr< InteractionsNonBonded > nonbonded_ias
boost::mpi::communicator comm_cart
The communicator.
int this_node
The number of this node.
void mpi_call(void(*fp)(Args...), ArgRef &&...args)
Call a local function.
MpiCallbacks & mpiCallbacks()
Returns a reference to the global callback class instance.
System & get_system()
void gatherv(const boost::mpi::communicator &comm, const T *in_values, int in_size, T *out_values, const int *sizes, const int *displs, int root)
Definition gatherv.hpp:87
Utils::Cache< int, Particle > particle_fetch_cache(max_cache_size)
auto constexpr new_part
auto constexpr any_type
Various procedures concerning interactions between particles.
std::vector< int > get_particle_ids_parallel()
static int max_seen_pid
Keep track of the largest particle id.
static void add_id_to_type_map(int p_id, int type)
static bool maybe_move_particle(int p_id, Utils::Vector3d const &pos)
Move particle to a new position.
static void build_particle_node()
Rebuild the particle index.
void make_new_particle(int p_id, Utils::Vector3d const &pos)
Create a new particle and attach it to a cell.
const Particle & get_particle_data(int p_id)
Get particle data.
static std::unordered_map< int, int > particle_node
Mapping particle ids to MPI ranks.
int get_particle_node(int p_id)
Get the MPI rank which owns the a specific particle.
int number_of_particles_with_type(int type)
void set_particle_pos(int p_id, Utils::Vector3d const &pos)
Move particle to a new position.
void init_type_map(int type)
static void remove_id_from_map(int p_id, int type)
static void mpi_synchronize_max_seen_pid_local()
void remove_all_particles()
Remove all particles.
int get_random_p_id(int type, int random_index_in_type_map)
Find a particle of given type and return its id.
static int calculate_max_seen_id()
Calculate the largest particle id.
void remove_particle(int p_id)
Remove particle with a given identity.
static void mpi_get_particles_local()
static void mpi_who_has_head()
static std::vector< Particle > mpi_get_particles(std::span< const int > ids)
Get multiple particles at once.
int get_maximal_particle_id()
Get maximal particle id.
int get_particle_node_parallel(int p_id)
constexpr auto some_tag
std::vector< int > get_particle_ids()
Get all particle ids.
std::size_t fetch_cache_max_size()
Return the maximal number of particles that are kept in the fetch cache.
void prefetch_particle_data(std::span< const int > in_ids)
Fetch a range of particle into the fetch cache.
void invalidate_fetch_cache()
Invalidate the fetch cache for get_particle_data.
static auto rebuild_needed()
static auto & get_cell_structure()
static void build_particle_node_parallel()
Rebuild the particle index.
static bool maybe_insert_particle(int p_id, Utils::Vector3d const &pos)
Create a new particle and attach it to a cell.
void clear_particle_node()
Invalidate particle_node.
static bool type_list_enable
Enable particle type tracking in particle_type_map.
static void mpi_who_has_local()
void on_particle_type_change(int p_id, int old_type, int new_type)
static void mpi_send_particle_data_local(int p_id)
int get_n_part()
Get number of particles.
static void clear_particle_type_map()
static std::unordered_map< int, std::unordered_set< int > > particle_type_map
Mapping particle types to lists of particle ids.
bool particle_exists(int p_id)
Check if particle exists.
Particles creation and deletion.
Struct holding all information for one particle.
Definition Particle.hpp:395