ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
CellStructure.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
23
28
29#include "BoxGeometry.hpp"
30#include "LocalBondState.hpp"
31#include "LocalBox.hpp"
32#include "Particle.hpp"
33#include "aosoa_pack.hpp"
35#include "communication.hpp"
36#include "ghosts.hpp"
39#include "kokkos_helpers.hpp"
42#include "particle_node.hpp"
44#include "system/System.hpp"
45
46#include <utils/Vector.hpp>
47#include <utils/contains.hpp>
49#include <utils/math/sqr.hpp>
50
51#ifdef ESPRESSO_CALIPER
52#include "caliper_utils.hpp"
53#endif
54
55#include <boost/mpi/collectives/all_reduce.hpp>
56
57#include <omp.h>
58
59#include <algorithm>
60#include <cassert>
61#include <cmath>
62#include <cstddef>
63#include <cstdint>
64#include <iterator>
65#include <memory>
66#include <numbers>
67#include <optional>
68#include <ranges>
69#include <set>
70#include <stdexcept>
71#include <string>
72#include <unordered_set>
73#include <utility>
74#include <variant>
75#include <vector>
76
78 assert(not m_pending_ghost_reduce.has_value() &&
79 "~CellStructure: ghost force reduction still in flight at destruction "
80 "— ghosts_reduce_forces_finish() was not called");
82 // Kokkos handle can only be freed after all Cabana containers have been freed
83 m_kokkos_handle.reset();
84}
85
87 m_scatter_force.reset();
88 m_local_force.reset();
89#ifdef ESPRESSO_ROTATION
90 m_scatter_torque.reset();
91 m_local_torque.reset();
92#endif
93#ifdef ESPRESSO_DIPOLE_FIELD_TRACKING
94 m_scatter_dip_fld.reset();
95 m_local_dip_fld.reset();
96#endif
97#ifdef ESPRESSO_NPT
98 m_scatter_virial.reset();
99 m_local_virial.reset();
100#endif
101 m_id_to_index.reset();
102 m_aosoa.reset();
103 m_verlet_list_cabana.reset();
104 m_bond_state->clear();
105 m_rebuild_verlet_list_cabana = true;
106}
107void CellStructure::clear_bond_properties() { m_bond_state->reset(); }
108
109void CellStructure::set_kokkos_handle(std::shared_ptr<KokkosHandle> handle) {
110 m_kokkos_handle = std::move(handle);
111 m_bond_state = std::make_unique<LocalBondState>();
112}
113
114static auto estimate_max_counts(double pair_cutoff,
115 std::size_t number_of_unique_particles,
116 double local_box_volume,
117 std::size_t num_local_particles) {
118 if (std::isinf(pair_cutoff)) {
119 return number_of_unique_particles;
120 }
121 if (pair_cutoff < 0.) {
122 pair_cutoff = 0.;
123 }
124 // Estimate number of neighbors based on local density and cutoff sphere:
125 // volume n_neighbors = rho * (4/3) * pi * r^3, where rho = n_particles /
126 // volume
127 auto const local_density =
128 (local_box_volume > 0. && num_local_particles > 0)
129 ? static_cast<double>(num_local_particles) / local_box_volume
130 : 0.;
131 auto const cutoff_sphere_volume =
132 (4. / 3.) * std::numbers::pi * Utils::int_pow<3>(pair_cutoff);
133 // account for local fluctuations. Empirical.
134 auto const fluctuation_factor = 2.;
135 auto max_counts = static_cast<std::size_t>(
136 std::ceil(fluctuation_factor * local_density * cutoff_sphere_volume));
137 std::size_t constexpr threshold_num = 16;
138 if (max_counts < threshold_num) {
139 max_counts = std::min(threshold_num, number_of_unique_particles);
140 }
141 return max_counts;
142}
143
144void CellStructure::rebuild_local_properties(double const pair_cutoff) {
145#ifdef ESPRESSO_CALIPER
147#endif
148 assert(m_kokkos_handle);
149 auto const num_part = get_unique_particles().size();
150 auto const &system = get_system();
151 auto const local_box_volume = system.local_geo->volume();
152 auto max_counts = estimate_max_counts(pair_cutoff, num_part, local_box_volume,
154#ifdef ESPRESSO_COLLISION_DETECTION
155 if (system.has_collision_detection_enabled()) {
156 // TODO: use other types of Verlet list data structures
157 max_counts = num_part * 2ul;
158 }
159#endif
160 if (m_local_force) { // local properties are reallocated
161 if (get_local_force().extent(0) == num_part) {
162 // Extents unchanged (always the case with a single MPI rank): zero the
163 // existing buffers in place instead of freeing and reallocating the
164 // O(n_threads * N) ScatterView scratch on every Verlet rebuild.
166 reset_torque_replicas_if_dirty();
167 reset_dip_fld_replicas_if_dirty();
168 } else {
169 Kokkos::realloc(get_local_force(), num_part);
170 // underlying View extent changed -> scratch buffers must be rebuilt
171 m_scatter_force.emplace(
172 Kokkos::Experimental::create_scatter_view(get_local_force()));
173#ifdef ESPRESSO_ROTATION
174 Kokkos::realloc(get_local_torque(), num_part);
175 // underlying View extent changed -> scratch buffers must be rebuilt
176 m_scatter_torque.emplace(
177 Kokkos::Experimental::create_scatter_view(get_local_torque()));
178 m_torque_replicas_dirty = false;
179#endif
180#ifdef ESPRESSO_DIPOLE_FIELD_TRACKING
181 Kokkos::realloc(get_local_dip_fld(), num_part);
182 // underlying View extent changed -> scratch buffers must be rebuilt
183 m_scatter_dip_fld.emplace(
184 Kokkos::Experimental::create_scatter_view(get_local_dip_fld()));
185 m_dip_fld_replicas_dirty = false;
186#endif
187 }
188 auto const required_index_size = get_cached_max_local_particle_id() + 1;
189 if (get_id_to_index().extent(0) !=
190 static_cast<std::size_t>(required_index_size)) {
191 Kokkos::realloc(Kokkos::WithoutInitializing, get_id_to_index(),
192 required_index_size);
193 }
195 // Resize particle views using AoSoA_pack's resize method
196 m_aosoa->resize(num_part);
197 kokkos_deep_copy(execution_space{}, m_aosoa->flags, uint8_t{0});
198 m_verlet_list_cabana->reallocData(num_part, max_counts);
199 } else { // local properties are initialized
200 m_local_force = std::make_unique<ForceType>("local_force", num_part);
201 m_scatter_force.emplace(
202 Kokkos::Experimental::create_scatter_view(*m_local_force));
203#ifdef ESPRESSO_ROTATION
204 m_local_torque = std::make_unique<ForceType>("local_torque", num_part);
205 m_scatter_torque.emplace(
206 Kokkos::Experimental::create_scatter_view(*m_local_torque));
207#endif
208#ifdef ESPRESSO_DIPOLE_FIELD_TRACKING
209 m_local_dip_fld = std::make_unique<ForceType>("local_dip_fld", num_part);
210 m_scatter_dip_fld.emplace(
211 Kokkos::Experimental::create_scatter_view(*m_local_dip_fld));
212#endif
213 m_id_to_index = std::make_unique<Kokkos::View<int *, memory_space>>(
214 Kokkos::view_alloc(execution_space{}, Kokkos::WithoutInitializing,
215 "id_to_index"),
218 // Create AoSoA_pack and initialize with resize
219 m_aosoa = std::make_unique<AoSoA_pack>();
220 m_aosoa->resize(num_part);
221 kokkos_deep_copy(execution_space{}, m_aosoa->flags, uint8_t{0});
222
223 m_verlet_list_cabana =
224 std::make_unique<ListType>(0ul, num_part, max_counts);
225 }
226#ifdef ESPRESSO_NPT
227 if (not m_local_virial) {
228 m_local_virial = std::make_unique<VirialType>("local_virial");
229 m_scatter_virial.emplace(
230 Kokkos::Experimental::create_scatter_view(*m_local_virial));
231 } else {
232 reset_virial_replicas_if_dirty();
233 }
234#endif
235}
236
239 m_scatter_force->reset();
240}
241
242void CellStructure::reset_torque_replicas_if_dirty() {
243#ifdef ESPRESSO_ROTATION
244 if (m_torque_replicas_dirty) {
246 m_scatter_torque->reset();
247 m_torque_replicas_dirty = false;
248 }
249#endif
250}
251
252void CellStructure::reset_dip_fld_replicas_if_dirty() {
253#ifdef ESPRESSO_DIPOLE_FIELD_TRACKING
254 if (m_dip_fld_replicas_dirty) {
256 m_scatter_dip_fld->reset();
257 m_dip_fld_replicas_dirty = false;
258 }
259#endif
260}
261
262void CellStructure::reset_virial_replicas_if_dirty() {
263#ifdef ESPRESSO_NPT
264 if (m_virial_replicas_dirty) {
266 m_scatter_virial->reset();
267 m_virial_replicas_dirty = false;
268 }
269#endif
270}
271
273#ifdef ESPRESSO_CALIPER
275#endif
277 reset_torque_replicas_if_dirty();
278 reset_dip_fld_replicas_if_dirty();
279 reset_virial_replicas_if_dirty();
280 kokkos_deep_copy(execution_space{}, get_aosoa().flags, uint8_t{0});
281}
282
283void CellStructure::update_bond_storage(int &pair_count, int &angle_count,
284 int &dihedral_count,
285 Particle const &p) {
286 auto &pair_list = m_bond_state->pair_list;
287 auto &pair_ids = m_bond_state->pair_ids;
288 auto &angle_list = m_bond_state->angle_list;
289 auto &angle_ids = m_bond_state->angle_ids;
290 auto &dihedral_list = m_bond_state->dihedral_list;
291 auto &dihedral_ids = m_bond_state->dihedral_ids;
292 for (auto const bond : p.bonds()) {
293 auto const partner_ids = bond.partner_ids();
294 try {
295 auto const partners = resolve_bond_partners(partner_ids);
296 // NOLINTNEXTLINE(clang-analyzer-security.ArrayBound)
297 if (partners.size() == 1u) { // pair bonds
298 auto p_index = Kokkos::atomic_fetch_add(&pair_count, 1);
299 pair_list(p_index, 0) = p.id();
300 pair_list(p_index, 1) = partners[0]->id();
301 pair_ids(p_index) = bond.bond_id();
302 } else if (partners.size() == 2u) { // angle bond
303 auto a_index = Kokkos::atomic_fetch_add(&angle_count, 1);
304 angle_list(a_index, 0) = p.id();
305 angle_list(a_index, 1) = partners[0]->id();
306 angle_list(a_index, 2) = partners[1]->id();
307 angle_ids(a_index) = bond.bond_id();
308 } else if (partners.size() == 3u) { // dihedral bond
309 auto d_index = Kokkos::atomic_fetch_add(&dihedral_count, 1);
310 dihedral_list(d_index, 0) = p.id();
311 dihedral_list(d_index, 1) = partners[0]->id();
312 dihedral_list(d_index, 2) = partners[1]->id();
313 dihedral_list(d_index, 3) = partners[2]->id();
314 dihedral_ids(d_index) = bond.bond_id();
315 }
316 } catch (BondResolutionError const &) {
317 bond_resolution_error(partner_ids);
318 }
319 }
320}
321
323#ifdef ESPRESSO_CALIPER
325#endif
326 auto &unique_particles = m_unique_particles;
327 unique_particles.clear();
328 unique_particles.resize(count_local_particles());
329 std::unordered_set<int> registered_index{};
330 using execution_space = Kokkos::DefaultHostExecutionSpace;
331 int n_threads = execution_space().concurrency();
332
333 m_bond_state->reset_counts();
334 // one cache line per thread: these counters are written on every particle,
335 // so packing them into shared cache lines makes the sweep bounce lines
336 // between L3 domains
337 struct alignas(64) PerThreadCounts {
338 int max_id = 0;
339 int pair = 0;
340 int angle = 0;
341 int dihedral = 0;
342 };
343 std::vector<PerThreadCounts> thread_counts(n_threads);
344
345 enumerate_local_particles(*this, [&unique_particles, &thread_counts](
346 std::size_t index, Particle &p) {
347 unique_particles[index] = &p;
348 auto &counts = thread_counts[omp_get_thread_num()];
349 counts.max_id = std::max(p.id(), counts.max_id);
350 for (auto const bond : p.bonds()) {
351 if (not bond.partner_ids().empty()) {
352 auto const partner_ids = bond.partner_ids();
353 if (partner_ids.size() == 1u) {
354 counts.pair += 1;
355 } else if (partner_ids.size() == 2u) {
356 counts.angle += 1;
357 } else if (partner_ids.size() == 3u) {
358 counts.dihedral += 1;
359 }
360 }
361 }
362 });
363 Kokkos::fence();
364 int pair_count = 0;
365 int angle_count = 0;
366 int dihedral_count = 0;
367 int max_id = 0;
368 for (auto const &counts : thread_counts) {
369 pair_count += counts.pair;
370 angle_count += counts.angle;
371 dihedral_count += counts.dihedral;
372 max_id = std::max(counts.max_id, max_id);
373 }
374 set_local_bond_numbers(pair_count, angle_count, dihedral_count);
375 m_bond_state->allocate();
376 for (auto &p : ghost_particles()) {
377 auto const *local_particle = get_local_particle(p.id());
378 if (not local_particle or not local_particle->is_ghost()) {
379 continue;
380 }
381 if (registered_index.contains(p.id())) {
382 continue;
383 }
384 registered_index.insert(p.id());
385 unique_particles.emplace_back(&p);
386 max_id = std::max(p.id(), max_id);
387 }
388 registered_index.clear();
389 m_cached_max_local_particle_id = max_id;
390 m_num_local_particles_cached = unique_particles.size();
391}
392
394 : m_decomposition{std::make_unique<AtomDecomposition>(box)} {}
395
397 auto const max_id = get_max_local_particle_id();
398
399 for (auto const &p : local_particles()) {
400 auto const id = p.id();
401
402 if (id < 0 or id > max_id) {
403 throw std::runtime_error("Particle id out of bounds.");
404 }
405
406 if (get_local_particle(id) != &p) {
407 throw std::runtime_error("Invalid local particle index entry.");
408 }
409 }
410
411 /* checks: local particle id */
412 std::size_t local_part_cnt = 0u;
413 for (int n = 0; n < get_max_local_particle_id() + 1; n++) {
414 if (get_local_particle(n) != nullptr) {
415 local_part_cnt++;
416 if (get_local_particle(n)->id() != n) {
417 throw std::runtime_error("local_particles part has corrupted id.");
418 }
419 }
420 }
421
422 if (local_part_cnt != local_particles().size()) {
423 throw std::runtime_error(
424 std::to_string(local_particles().size()) + " parts in cells but " +
425 std::to_string(local_part_cnt) + " parts in local_particles");
426 }
427}
428
430 for (auto cell : decomposition().local_cells()) {
431 for (auto const &p : cell->particles()) {
432 if (particle_to_cell(p) != cell) {
433 throw std::runtime_error("misplaced particle with id " +
434 std::to_string(p.id()));
435 }
436 }
437 }
438}
439
441 auto remove_all_bonds_to = [id](BondList &bl) {
442 for (auto it = bl.begin(); it != bl.end();) {
443 if (Utils::contains(it->partner_ids(), id)) {
444 it = bl.erase(it);
445 } else {
446 std::advance(it, 1);
447 }
448 }
449 };
450
451 for (auto cell : decomposition().local_cells()) {
452 auto &parts = cell->particles();
453 for (auto it = parts.begin(); it != parts.end();) {
454 if (it->id() == id) {
455 it = parts.erase(it);
456 update_particle_index(id, nullptr);
458 } else {
459 remove_all_bonds_to(it->bonds());
460 it++;
461 }
462 }
463 }
464}
465
467 auto const sort_cell = particle_to_cell(p);
468 if (sort_cell) {
469 return std::addressof(
470 append_indexed_particle(sort_cell->particles(), std::move(p)));
471 }
472
473 return {};
474}
475
477 auto const sort_cell = particle_to_cell(p);
478 /* There is always at least one cell, so if the particle
479 * does not belong to a cell on this node we can put it there. */
480 auto cell = sort_cell ? sort_cell : decomposition().local_cells()[0];
481
482 /* If the particle isn't local a global resort may be
483 * needed, otherwise a local resort if sufficient. */
485
486 return std::addressof(
487 append_indexed_particle(cell->particles(), std::move(p)));
488}
489
491 auto it = std::ranges::find_if(std::ranges::views::reverse(m_particle_index),
492 [](auto const *p) { return p != nullptr; });
493
494 return (it != m_particle_index.rend()) ? (*it)->id() : -1;
495}
496
498 return m_bond_state->pair_count;
499}
501 return m_bond_state->angle_count;
502}
504 return m_bond_state->dihedral_count;
505}
506void CellStructure::set_local_bond_numbers(int pair_value, int angle_value,
507 int dihedral_value) {
508 m_bond_state->set_counts(pair_value, angle_value, dihedral_value);
509}
510#ifdef ESPRESSO_COLLISION_DETECTION
511void CellStructure::clear_new_bonds() { m_bond_state->clear_new_bonds(); }
513 std::vector<int> const &particle_ids) {
514 m_bond_state->add_new_bond(bond_id, particle_ids, get_id_to_index());
515}
516void CellStructure::rebuild_bond_list() { m_bond_state->rebuild(); }
517#endif // ESPRESSO_COLLISION_DETECTION
518
520 for (auto cell : decomposition().local_cells()) {
521 cell->particles().clear();
522 }
523
524 m_particle_index.clear();
527 get_system().on_particle_change();
528}
529
530/* Map the data parts flags from cells to those used internally
531 * by the ghost communication */
532unsigned map_data_parts(unsigned data_parts) {
533 using namespace Cells;
534
535 /* clang-format off */
536 return GHOSTTRANS_NONE
537 | ((data_parts & DATA_PART_PROPERTIES) ? GHOSTTRANS_PROPRTS : 0u)
538 | ((data_parts & DATA_PART_POSITION) ? GHOSTTRANS_POSITION : 0u)
539 | ((data_parts & DATA_PART_MOMENTUM) ? GHOSTTRANS_MOMENTUM : 0u)
540 | ((data_parts & DATA_PART_FORCE) ? GHOSTTRANS_FORCE : 0u)
541#ifdef ESPRESSO_BOND_CONSTRAINT
542 | ((data_parts & DATA_PART_RATTLE) ? GHOSTTRANS_RATTLE : 0u)
543#endif
544#ifdef ESPRESSO_ROTATION
545 | ((data_parts & DATA_PART_QUAT) ? GHOSTTRANS_QUAT : 0u)
546 | ((data_parts & DATA_PART_TORQUE) ? GHOSTTRANS_TORQUE : 0u)
547#endif
548#ifdef ESPRESSO_DIPOLE_FIELD_TRACKING
549 | ((data_parts & DATA_PART_DIPFLD) ? GHOSTTRANS_DIPFLD : 0u)
550#endif
551 | ((data_parts & DATA_PART_BONDS) ? GHOSTTRANS_BONDS : 0u);
552 /* clang-format on */
553}
554
556#ifdef ESPRESSO_CALIPER
558#endif
560 *decomposition().halo_plan(), *get_system().box_geo, GHOSTTRANS_PARTNUM,
562 m_ghost_buffers);
563}
564
565void CellStructure::ghosts_update(unsigned data_parts) {
566#ifdef ESPRESSO_CALIPER
568#endif
569 auto const parts = map_data_parts(data_parts);
571 *decomposition().halo_plan(), *get_system().box_geo, parts,
573 m_ghost_buffers);
574}
575
577#ifdef ESPRESSO_CALIPER
579#endif
581 *decomposition().halo_plan(), *get_system().box_geo,
582 get_system().get_force_reduce_ghost_flags(),
584}
585
586#ifdef ESPRESSO_CALIPER
587// caliper annotation for split phase ghost forces reduction
588static cali_id_t ghost_reduce_async_attr() {
589 static const cali_id_t id =
591 ? cali_create_attribute("ghosts_reduce_forces_async",
592 CALI_TYPE_STRING,
593 CALI_ATTR_ASVALUE | CALI_ATTR_SCOPE_THREAD)
594 : CALI_INV_ID;
595 return id;
596}
597#endif // ESPRESSO_CALIPER
598
600 assert(not m_pending_ghost_reduce.has_value() &&
601 "ghosts_reduce_forces_start: a reduction is already in flight");
602 // BEGIN fires only after emplace succeeds so a throwing start cannot
603 // leave the Caliper region open without a matching END.
604 m_pending_ghost_reduce.emplace(GhostComm::halo_exchange_start(
605 *decomposition().halo_plan(), *get_system().box_geo,
606 get_system().get_force_reduce_ghost_flags(),
608 m_ghost_buffers));
609#ifdef ESPRESSO_CALIPER
610 if (auto id = ghost_reduce_async_attr(); id != CALI_INV_ID)
611 cali_begin_string(id, "in_flight");
612#endif
613}
614
616 assert(m_pending_ghost_reduce.has_value() &&
617 "ghosts_reduce_forces_finish: no reduction is in flight");
618 try {
619 GhostComm::halo_exchange_finish(*m_pending_ghost_reduce);
620 } catch (...) {
621 // A failed finish cannot be retried: the exchange state is half-consumed
622 // (some requests waited, some buffers unpacked). Drop the pending state so
623 // a later finish attempt (e.g. the ReduceGuard in integrate.cpp) does not
624 // re-run MPI waits on completed requests.
625 m_pending_ghost_reduce.reset();
626#ifdef ESPRESSO_CALIPER
627 if (auto id = ghost_reduce_async_attr(); id != CALI_INV_ID)
628 cali_end(id);
629#endif
630 throw;
631 }
632#ifdef ESPRESSO_CALIPER
633 // END before reset so the region is closed before the optional is cleared.
634 if (auto id = ghost_reduce_async_attr(); id != CALI_INV_ID)
635 cali_end(id);
636#endif
637 m_pending_ghost_reduce.reset();
638}
639#ifdef ESPRESSO_DIPOLE_FIELD_TRACKING
645#endif
646#ifdef ESPRESSO_BOND_CONSTRAINT
648#ifdef ESPRESSO_CALIPER
650#endif
652 *decomposition().halo_plan(), *get_system().box_geo, GHOSTTRANS_RATTLE,
654}
655#endif
656
657namespace {
658/**
659 * @brief Apply a @ref ParticleChange to a particle index.
660 */
663
665 cs->update_particle_index(rp.id, nullptr);
666 }
667 void operator()(ModifiedList mp) const { cs->update_particle_index(mp.pl); }
668};
669} // namespace
670
671void CellStructure::resort_particles(bool global_flag) {
672#ifdef ESPRESSO_CALIPER
674#endif
675 assert(not m_pending_ghost_reduce.has_value() &&
676 "resort_particles: ghost force reduction is still in flight — "
677 "call ghosts_reduce_forces_finish() first");
678 invalidate_ghosts();
679
680 std::vector<ParticleChange> diff;
681
682 m_decomposition->resort(global_flag, diff);
683
684 for (auto d : diff) {
685 std::visit(UpdateParticleIndexVisitor{this}, d);
686 }
687
688 auto const &lebc = get_system().box_geo->lees_edwards_bc();
689 m_rebuild_verlet_list = true;
690 m_rebuild_verlet_list_cabana = true;
691 m_le_pos_offset_at_last_resort = lebc.pos_offset;
692
693#ifdef ESPRESSO_ADDITIONAL_CHECKS
696#endif
697}
698
700 auto &system = get_system();
701 auto &local_geo = *system.local_geo;
702 auto const &box_geo = *system.box_geo;
703 set_particle_decomposition(
704 std::make_unique<AtomDecomposition>(::comm_cart, box_geo));
706 local_geo.set_cell_structure_type(m_type);
707 system.on_cell_structure_change();
708}
709
711 double range, std::optional<std::pair<int, int>> fully_connected_boundary) {
712 auto &system = get_system();
713 auto &local_geo = *system.local_geo;
714 auto const &box_geo = *system.box_geo;
715 set_particle_decomposition(std::make_unique<RegularDecomposition>(
716 ::comm_cart, range, box_geo, local_geo, fully_connected_boundary));
718 local_geo.set_cell_structure_type(m_type);
719 system.on_cell_structure_change();
720}
721
723 std::set<int> n_square_types) {
724 auto &system = get_system();
725 auto &local_geo = *system.local_geo;
726 auto const &box_geo = *system.box_geo;
727 set_particle_decomposition(std::make_unique<HybridDecomposition>(
728 ::comm_cart, cutoff_regular, m_verlet_skin,
729 [&system]() { return system.get_global_ghost_flags(); }, box_geo,
730 local_geo, n_square_types));
732 local_geo.set_cell_structure_type(m_type);
733 system.on_cell_structure_change();
734}
735
737 assert(value >= 0.);
738 m_verlet_skin = value;
739 m_verlet_skin_set = true;
740 m_rebuild_verlet_list_cabana = true;
741 get_system().on_verlet_skin_change();
742}
743
745 assert(not is_verlet_skin_set());
746 auto const max_cut = get_system().maximal_cutoff();
747 if (max_cut <= 0.) {
748 throw std::runtime_error(
749 "cannot automatically determine skin, please set it manually");
750 }
751 /* maximal skin that can be used without resorting is the maximal
752 * range of the cell system minus what is needed for interactions. */
753 auto const max_range = std::ranges::min(max_cutoff());
754 auto const new_skin = std::min(0.4 * max_cut, max_range - max_cut);
755 set_verlet_skin(new_skin);
756}
757
759#ifdef ESPRESSO_CALIPER
761#endif
762 /* data parts that are only updated on resort */
763 auto constexpr resort_only_parts =
765
766 auto const global_resort = boost::mpi::all_reduce(
767 ::comm_cart, m_resort_particles, std::bit_or<unsigned>());
768
769 if (global_resort != Cells::RESORT_NONE) {
770 auto const do_global_resort = (global_resort & Cells::RESORT_GLOBAL) != 0;
771
772 /* Resort cell system */
773 resort_particles(do_global_resort);
774 ghosts_count();
775 ghosts_update(data_parts);
776
777 /* Add the ghost particles to the index if we don't already
778 * have them. */
779 for (auto &p : ghost_particles()) {
780 if (get_local_particle(p.id()) == nullptr) {
781 update_particle_index(p.id(), &p);
782 }
783 }
784
785 /* Particles are now sorted */
787 } else {
788 /* Communication step: ghost information */
789 ghosts_update(data_parts & ~resort_only_parts);
790 }
791}
792
794 Utils::Vector3d const &additional_offset) const {
795 auto const lim = Utils::sqr(m_verlet_skin / 2.) - additional_offset.norm2();
796
797 auto add_partial = [lim](bool &result, Particle const &p) {
798 if ((p.pos() - p.pos_at_last_verlet_update()).norm2() > lim) {
799 result = true;
800 }
801 };
802
803 auto reduce_op = [](bool &acc, bool const &val) { acc |= val; };
804
805 return reduce_over_local_particles<bool>(*this, add_partial, reduce_op);
806}
@ NSQUARE
Atom decomposition (N-square).
@ HYBRID
Hybrid decomposition.
@ REGULAR
Regular decomposition.
static cali_id_t ghost_reduce_async_attr()
unsigned map_data_parts(unsigned data_parts)
Map the data parts flags from cells to those used internally by the ghost communication.
static auto estimate_max_counts(double pair_cutoff, std::size_t number_of_unique_particles, double local_box_volume, std::size_t num_local_particles)
unsigned map_data_parts(unsigned data_parts)
Map the data parts flags from cells to those used internally by the ghost communication.
Asynchronous, split-phase ghost-communication engine.
Vector implementation and trait types for boost qvm interoperability.
void bond_resolution_error(std::span< const int > partner_ids)
Zero-overhead Caliper guards for the inactive (no CALI_CONFIG) case.
bool espresso_cali_active() noexcept
Return true if Caliper is configured for this process.
#define ESPRESSO_CALI_MARK_FUNCTION
Guarded drop-in replacement for CALI_CXX_MARK_FUNCTION.
Atom decomposition cell system.
Bond storage.
Definition BondList.hpp:84
Describes a cell structure / cell system.
ParticleRange ghost_particles() const
auto & get_local_force()
Particle * get_local_particle(int id)
Get a local particle by id.
void set_kokkos_handle(std::shared_ptr< KokkosHandle > handle)
void check_particle_sorting() const
Check that particles are in the correct cell.
auto & get_id_to_index()
std::size_t count_local_particles() const
virtual ~CellStructure()
int get_local_angle_bond_numbers() const
void clear_resort_particles()
Set the resort level to sorted.
auto is_verlet_skin_set() const
Whether the Verlet skin is set.
void clear_local_properties()
ParticleDecomposition const & decomposition() const
Get the underlying particle decomposition.
void reset_local_force_buffers()
Zero the local force view and its scatter replicas.
int get_local_pair_bond_numbers() const
void ghosts_reduce_forces_start()
Begin the split-phase ghost force reduction (non-blocking).
void update_ghosts_and_resort_particle(unsigned data_parts)
Update ghost particles, with particle resort if needed.
Particle * add_local_particle(Particle &&p)
Add a particle.
void set_verlet_skin_heuristic()
Set the Verlet skin using a heuristic.
void set_verlet_skin(double value)
Set the Verlet skin.
void ghosts_update(unsigned data_parts)
Update ghost particles.
int get_local_dihedral_bond_numbers() const
int get_cached_max_local_particle_id() const
CellStructure(BoxGeometry const &box)
auto & get_local_torque()
auto & get_local_virial()
void update_particle_index(int id, Particle *p)
Update local particle index.
void set_local_bond_numbers(int p, int a, int d)
void ghosts_reduce_forces()
Add forces and torques from ghost particles to real particles.
auto const & get_unique_particles() const
void rebuild_local_properties(double pair_cutoff)
Utils::Vector3d max_range() const
Maximal pair range supported by current cell system.
void add_new_bond(int bond_id, std::vector< int > const &particle_ids)
bool check_resort_required(Utils::Vector3d const &additional_offset={}) const
Check whether a particle has moved further than half the skin since the last Verlet list update,...
auto resolve_bond_partners(std::span< const int > partner_ids)
Resolve ids to particles.
void ghosts_count()
Synchronize number of ghosts.
void set_resort_particles(Cells::Resort level)
Increase the local resort level at least to level.
void remove_particle(int id)
Remove a particle.
Particle * add_particle(Particle &&p)
Add a particle.
std::size_t get_num_local_particles_cached() const
Kokkos::DefaultHostExecutionSpace execution_space
void resort_particles(bool global_flag)
Resort particles.
void check_particle_index() const
Check that particle index is commensurate with particles.
void ghosts_reduce_forces_finish()
Complete the split-phase ghost force reduction.
void ghosts_reduce_dipole_field()
Add dipole fields from ghost particles to real particles.
void set_regular_decomposition(double range, std::optional< std::pair< int, int > > fully_connected_boundary)
Set the particle decomposition to RegularDecomposition.
void set_atom_decomposition()
Set the particle decomposition to AtomDecomposition.
auto & get_local_dip_fld()
void remove_all_particles()
Remove all particles from the cell system.
ParticleRange local_particles() const
void ghosts_reduce_rattle_correction()
Add rattle corrections from ghost particles to real particles.
void set_hybrid_decomposition(double cutoff_regular, std::set< int > n_square_types)
Set the particle decomposition to HybridDecomposition.
int get_max_local_particle_id() const
Get the maximal particle id on this node.
Utils::Vector3d max_cutoff() const
Maximal cutoff supported by current cell system.
void update_bond_storage(int &pair_count, int &angle_count, int &dihedral_count, Particle const &p)
Update bond storage(m_*_bond_list_kokkos and m_*_bond_id_kokkos).
void clear_bond_properties()
void reset_local_properties()
virtual std::span< Cell *const > local_cells() const =0
Get pointer to local cells.
constexpr T norm2() const
Definition Vector.hpp:173
boost::mpi::communicator comm_cart
The communicator.
Ghost particles and particle exchange.
@ GHOSTTRANS_MOMENTUM
transfer ParticleMomentum
Definition ghosts.hpp:41
@ GHOSTTRANS_RATTLE
transfer ParticleRattle
Definition ghosts.hpp:46
@ GHOSTTRANS_QUAT
transfer orientation quaternion (pushed with position; runtime-conditional)
Definition ghosts.hpp:54
@ GHOSTTRANS_DIPFLD
transfer dipole field tracking data
Definition ghosts.hpp:60
@ GHOSTTRANS_PARTNUM
resize the receiver particle arrays to the size of the senders
Definition ghosts.hpp:49
@ GHOSTTRANS_POSITION
transfer ParticlePosition
Definition ghosts.hpp:39
@ GHOSTTRANS_PROPRTS
transfer ParticleProperties
Definition ghosts.hpp:37
@ GHOSTTRANS_FORCE
transfer ParticleForce
Definition ghosts.hpp:43
@ GHOSTTRANS_NONE
Definition ghosts.hpp:35
@ GHOSTTRANS_TORQUE
transfer torque (reduced with force; runtime-conditional)
Definition ghosts.hpp:56
@ GHOSTTRANS_BONDS
Definition ghosts.hpp:50
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.
@ DATA_PART_MOMENTUM
Particle::m.
@ DATA_PART_DIPFLD
Particle::dip_fld.
@ DATA_PART_FORCE
Particle::f.
@ DATA_PART_TORQUE
torque (reduced with force)
@ DATA_PART_PROPERTIES
Particle::p.
@ DATA_PART_BONDS
Particle::bonds.
@ DATA_PART_RATTLE
Particle::rattle.
@ DATA_PART_QUAT
orientation quaternion (pushed with position)
@ DATA_PART_POSITION
Particle::r.
void halo_exchange_finish(GhostExchange &st)
Complete a halo exchange: run same-rank copies (overlapping the in-flight messages),...
void halo_exchange(HaloPlan const &plan, BoxGeometry const &box, unsigned data_parts, ExchangeOp op, ExchangeBuffers &bufs)
Blocking wrapper using a caller-owned buffer pool (no per-call alloc after warm-up).
GhostExchange halo_exchange_start(HaloPlan const &plan, BoxGeometry const &box, unsigned data_parts, ExchangeOp op, ExchangeBuffers &bufs)
Begin a halo exchange using a caller-owned buffer pool.
VectorXd< 3 > Vector3d
Definition Vector.hpp:207
DEVICE_QUALIFIER constexpr T sqr(T x)
Calculates the SQuaRe of x.
Definition sqr.hpp:28
DEVICE_QUALIFIER constexpr T int_pow(T x)
Calculate integer powers.
Definition int_pow.hpp:34
bool contains(Range &&rng, T const &value)
Check whether a range contains a value.
Definition contains.hpp:36
STL namespace.
void enumerate_local_particles(CellStructure const &cs, Kernel &&kernel)
Run a kernel on all local particles with enumeration.
void clear_particle_node()
Invalidate particle_node.
Particles creation and deletion.
ResultType reduce_over_local_particles(CellStructure const &cs, std::invocable< ResultType &, Particle const & > auto add_partial, std::invocable< ResultType &, ResultType const & > auto reduce_op)
Run a reduction over all particles.
Exception indicating that a particle id could not be resolved.
Struct holding all information for one particle.
Definition Particle.hpp:436
constexpr auto const & bonds() const
Definition Particle.hpp:473
constexpr auto const & id() const
Definition Particle.hpp:455