ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
particle_node.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 "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() {
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
127 if (::type_list_enable) {
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) {
144 }
145 }
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
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
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 // cannot use range-based transform with GCC 13 + ASAN
248 std::transform(node_ids.begin(), node_ids.end(), node_sizes.begin(),
249 std::size<std::vector<int>>);
250
251 Utils::Mpi::gatherv(comm_cart, parts.data(), static_cast<int>(parts.size()),
252 parts.data(), node_sizes.data(), 0);
253
254 return parts;
255}
256
257void prefetch_particle_data(std::span<const int> in_ids) {
258 /* Nothing to do on a single node. */
259 // NOLINTNEXTLINE(clang-analyzer-core.NonNullParamChecker)
260 if (comm_cart.size() == 1)
261 return;
262
263 static std::vector<int> ids;
264 ids.clear();
265 auto out_ids = std::back_inserter(ids);
266
267 /* Don't prefetch particles already on the head node or already cached. */
268 std::ranges::copy_if(in_ids, out_ids, [](int id) {
269 return (get_particle_node(id) != this_node) && particle_fetch_cache.has(id);
270 });
271
272 /* Don't prefetch more particles than fit the cache. */
273 if (ids.size() > particle_fetch_cache.max_size())
274 ids.resize(particle_fetch_cache.max_size());
275
276 /* Fetch the particles... */
277 for (auto &p : mpi_get_particles(ids)) {
278 auto id = p.id();
279 particle_fetch_cache.put(id, std::move(p));
280 }
281}
282
283static void mpi_who_has_local() {
284 static std::vector<int> sendbuf;
285
286 auto local_particles = get_cell_structure().local_particles();
287 auto const n_part = static_cast<int>(local_particles.size());
288 boost::mpi::gather(comm_cart, n_part, 0);
289
290 if (n_part == 0) {
292 return;
293 }
294
295 sendbuf.resize(n_part);
296
297 std::transform(local_particles.begin(), local_particles.end(),
298 sendbuf.begin(), [](Particle const &p) { return p.id(); });
299
300 comm_cart.send(0, some_tag, sendbuf);
302}
303
305
307 auto local_particles = get_cell_structure().local_particles();
308
309 static std::vector<int> n_parts;
310 boost::mpi::gather(comm_cart, static_cast<int>(local_particles.size()),
311 n_parts, 0);
312
313 static std::vector<int> pdata;
314 auto const n_nodes = ::comm_cart.size();
315 max_seen_pid = -1;
316
317 /* then fetch particle locations */
318 for (int pnode = 0; pnode < n_nodes; pnode++) {
319 if (pnode == this_node) {
320 for (auto const &p : local_particles) {
321 particle_node[p.id()] = this_node;
322 max_seen_pid = std::max(max_seen_pid, p.id());
323 }
324 } else if (n_parts[pnode] > 0) {
325 pdata.resize(n_parts[pnode]);
327 for (int i = 0; i < n_parts[pnode]; i++) {
329 max_seen_pid = std::max(max_seen_pid, pdata[i]);
330 }
331 }
332 }
334}
335
336/**
337 * @brief Rebuild the particle index.
338 */
343
344/**
345 * @brief Rebuild the particle index.
346 */
348 if (this_node == 0) {
350 } else {
352 }
353}
354
356 if (p_id < 0) {
357 throw std::domain_error("Invalid particle id: " + std::to_string(p_id));
358 }
359
360 if (particle_node.empty())
362
363 auto const needle = particle_node.find(p_id);
364
365 // Check if particle has a node, if not, we assume it does not exist.
366 if (needle == particle_node.end()) {
367 throw std::runtime_error("Particle node for id " + std::to_string(p_id) +
368 " not found!");
369 }
370 return needle->second;
371}
372
374 if (p_id < 0) {
375 throw std::domain_error("Invalid particle id: " + std::to_string(p_id));
376 }
377
378 if (rebuild_needed()) {
380 }
381
382 if (this_node != 0) {
383 return -1;
384 }
385
386 auto const needle = particle_node.find(p_id);
387
388 // Check if particle has a node, if not, we assume it does not exist.
389 if (needle == particle_node.end()) {
390 throw std::runtime_error("Particle node for id " + std::to_string(p_id) +
391 " not found!");
392 }
393 return needle->second;
394}
395
397 ::max_seen_pid = -1;
398 particle_node.clear();
399}
400
402 for (auto &kv : ::particle_type_map) {
403 kv.second.clear();
404 }
405}
406
407/**
408 * @brief Calculate the largest particle id.
409 * Traversing the @ref particle_node to find the largest particle id
410 * scales with O(N). Consider using the cached value in @ref max_seen_pid
411 * if possible. This function is only necessary when the cached value is
412 * invalidated, for example when removing the particle which has the
413 * largest id.
414 */
416 return std::accumulate(
417 particle_node.begin(), particle_node.end(), -1,
418 [](int max, auto const &kv) { return std::max(max, kv.first); });
419}
420
421/**
422 * @brief Create a new particle and attach it to a cell.
423 * @param p_id The identity of the particle to create.
424 * @param pos The particle position.
425 * @return Whether the particle was created on that node.
426 */
427static bool maybe_insert_particle(int p_id, Utils::Vector3d const &pos) {
428 auto const &box_geo = *System::get_system().box_geo;
429 auto folded_pos = pos;
430 auto image_box = Utils::Vector3i{};
431 box_geo.fold_position(folded_pos, image_box);
432
433 Particle new_part;
434 new_part.id() = p_id;
435 new_part.pos() = folded_pos;
436 new_part.image_box() = image_box;
437
438 return get_cell_structure().add_local_particle(std::move(new_part)) !=
439 nullptr;
440}
441
442/**
443 * @brief Move particle to a new position.
444 * @param p_id The identity of the particle to move.
445 * @param pos The new particle position.
446 * @return Whether the particle was moved from that node.
447 */
448static bool maybe_move_particle(int p_id, Utils::Vector3d const &pos) {
449 auto const &system = System::get_system();
450 auto const &box_geo = *system.box_geo;
451 auto p = system.cell_structure->get_local_particle(p_id);
452 if (p == nullptr) {
453 return false;
454 }
455 auto folded_pos = pos;
456 auto image_box = Utils::Vector3i{};
457 box_geo.fold_position(folded_pos, image_box);
458 p->pos() = folded_pos;
459 p->image_box() = image_box;
460 return true;
461}
462
469
471 if (::type_list_enable) {
472 auto p = get_cell_structure().get_local_particle(p_id);
473 auto p_type = -1;
474 if (p != nullptr and not p->is_ghost()) {
475 if (this_node == 0) {
476 p_type = p->type();
477 } else {
478 ::comm_cart.send(0, 42, p->type());
479 }
480 } else if (this_node == 0) {
481 ::comm_cart.recv(boost::mpi::any_source, 42, p_type);
482 }
483 assert(this_node != 0 or p_type != -1);
484 boost::mpi::broadcast(::comm_cart, p_type, 0);
486 }
487
488 if (this_node == 0) {
489 particle_node[p_id] = -1;
490 }
491 get_cell_structure().remove_particle(p_id);
494 if (this_node == 0) {
495 particle_node.erase(p_id);
496 if (p_id == ::max_seen_pid) {
498 // if there is a gap (i.e. there is no particle with id max_seen_pid - 1,
499 // then the cached value is invalidated and has to be recomputed (slow)
500 if (not particle_node.contains(::max_seen_pid) or
503 }
504 }
505 }
507}
508
510 if (rebuild_needed()) {
512 }
513 auto const has_created = maybe_insert_particle(p_id, pos);
515
516 auto node = -1;
517 auto const node_local = (has_created) ? ::comm_cart.rank() : 0;
518 boost::mpi::reduce(::comm_cart, node_local, node, std::plus<int>{}, 0);
519 if (::this_node == 0) {
520 particle_node[p_id] = node;
521 max_seen_pid = std::max(max_seen_pid, p_id);
522 assert(not has_created or node == 0);
523 }
525}
526
527void set_particle_pos(int p_id, Utils::Vector3d const &pos) {
528 auto const has_moved = maybe_move_particle(p_id, pos);
529 get_cell_structure().set_resort_particles(Cells::RESORT_GLOBAL);
531
532 auto success = false;
533 boost::mpi::reduce(::comm_cart, has_moved, success, std::plus<bool>{}, 0);
534 if (::this_node == 0 and !success) {
535 throw std::runtime_error("Particle node for id " + std::to_string(p_id) +
536 " not found!");
537 }
538}
539
541 auto it = particle_type_map.find(type);
542 if (it == particle_type_map.end()) {
543 throw std::runtime_error("The provided particle type " +
544 std::to_string(type) +
545 " is currently not tracked by the system.");
546 }
547
548 if (random_index_in_type_map + 1 > it->second.size())
549 throw std::runtime_error("The provided index exceeds the number of "
550 "particle types listed in the particle_type_map");
551 // there is no guarantee of order across MPI ranks
552 auto p_id = *std::next(it->second.begin(), random_index_in_type_map);
553 boost::mpi::broadcast(::comm_cart, p_id, 0);
554 return p_id;
555}
556
558 auto it = particle_type_map.find(type);
559 if (it == particle_type_map.end()) {
560 throw std::runtime_error("The provided particle type " +
561 std::to_string(type) +
562 " is currently not tracked by the system.");
563 }
564
565 return static_cast<int>(it->second.size());
566}
567
569 if (particle_node.empty())
571 return particle_node.contains(p_id);
572}
573
574std::vector<int> get_particle_ids() {
575 if (particle_node.empty())
577
578 std::vector<int> pids{};
579 std::ranges::copy(std::views::keys(particle_node), std::back_inserter(pids));
580 std::ranges::sort(pids);
581
582 return pids;
583}
584
585std::vector<int> get_particle_ids_parallel() {
586 if (rebuild_needed()) {
588 }
589 std::vector<int> pids{};
590 std::ranges::copy(std::views::keys(particle_node), std::back_inserter(pids));
591 boost::mpi::broadcast(::comm_cart, pids, 0);
592 return pids;
593}
594
596 if (rebuild_needed()) {
598 }
599
600 return max_seen_pid;
601}
602
604 if (particle_node.empty())
606
607 return static_cast<int>(particle_node.size());
608}
#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
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
cudaStream_t stream[1]
CUDA streams for parallel computing on CPU and GPU.
boost::mpi::communicator comm_cart
The communicator.
int this_node
The number of this node.
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)
STL namespace.
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:435