ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
CellStructure.hpp
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#pragma once
23
25
26#include "BoxGeometry.hpp"
27#include "LocalBox.hpp"
28#include "Particle.hpp"
29#include "ParticleList.hpp"
30#include "ParticleRange.hpp"
32#include "bond_error.hpp"
33#include "cell_system/Cell.hpp"
35#include "config/config.hpp"
37#include "ghosts.hpp"
38#include "system/Leaf.hpp"
39
40#include <utils/Vector.hpp>
41
42#include <boost/container/static_vector.hpp>
43#include <boost/iterator/indirect_iterator.hpp>
44#include <boost/range/algorithm/transform.hpp>
45
46#include <Cabana_Core.hpp>
47#include <Cabana_NeighborList.hpp>
48#include <Kokkos_Core.hpp>
49#include <Kokkos_ScatterView.hpp>
50
51#include <algorithm>
52#include <cassert>
53#include <concepts>
54#include <cstddef>
55#include <iterator>
56#include <memory>
57#include <optional>
58#include <set>
59#include <span>
60#include <stdexcept>
61#include <unordered_set>
62#include <utility>
63#include <vector>
64
65#ifdef ESPRESSO_CALIPER
66#include <caliper/cali.h>
67#endif
68
69// forward declarations
70struct KokkosHandle;
71struct LocalBondState;
72
73template <typename Callable>
74concept ParticleCallback = requires(Callable c, Particle &p) {
75 { c(p) } -> std::same_as<void>;
76};
77
78namespace Cells {
79enum Resort : unsigned {
82 RESORT_GLOBAL = 2u
83};
84
85/**
86 * @brief Flags to select particle parts for communication.
87 */
88enum DataPart : unsigned {
89 DATA_PART_NONE = 0u, /**< Nothing */
90 DATA_PART_PROPERTIES = 1u, /**< Particle::p */
91 DATA_PART_POSITION = 2u, /**< Particle::r */
92 DATA_PART_MOMENTUM = 8u, /**< Particle::m */
93 DATA_PART_FORCE = 16u, /**< Particle::f */
94#ifdef ESPRESSO_BOND_CONSTRAINT
95 DATA_PART_RATTLE = 32u, /**< Particle::rattle */
96#endif
97 DATA_PART_BONDS = 64u /**< Particle::bonds */
98};
99} // namespace Cells
100
101/**
102 * @brief Map the data parts flags from cells to those
103 * used internally by the ghost communication.
104 *
105 * @param data_parts data parts flags
106 * @return ghost communication flags
107 */
108unsigned map_data_parts(unsigned data_parts);
109
110namespace Cells {
111inline ParticleRange particles(std::span<Cell *const> cells) {
112 /* Find first non-empty cell */
113 auto first_non_empty = std::ranges::find_if(
114 cells, [](const Cell *c) { return not c->particles().empty(); });
115
116 return {CellParticleIterator(first_non_empty, cells.end()),
117 CellParticleIterator(cells.end())};
118}
119} // namespace Cells
120
121/**
122 * @brief Distance vector and length handed to pair kernels.
123 */
124struct Distance {
126 : vec21(vec21), dist2(vec21.norm2()) {}
127
129 double dist2;
130};
131
132namespace detail {
133// NOLINTNEXTLINE(bugprone-exception-escape)
134struct MinimalImageDistance {
135 BoxGeometry const box;
136
137 Distance operator()(Particle const &p1, Particle const &p2) const {
138 return Distance(box.get_mi_vector(p1.pos(), p2.pos()));
139 }
140};
141
142struct EuclidianDistance {
143 Distance operator()(Particle const &p1, Particle const &p2) const {
144 return Distance(p1.pos() - p2.pos());
145 }
146};
147} // namespace detail
148
149/** Describes a cell structure / cell system. Contains information
150 * about the communication of cell contents (particles, ghosts, ...)
151 * between different nodes and the relation between particle
152 * positions and the cell system. All other properties of the cell
153 * system which are not common between different cell systems have to
154 * be stored in separate structures.
155 */
156class CellStructure : public System::Leaf<CellStructure> {
157public:
158 static constexpr auto vector_length = 1;
159 using memory_space = Kokkos::HostSpace;
160 using execution_space = Kokkos::DefaultHostExecutionSpace;
161 struct AoSoA_pack;
162 using ForceType =
163 Kokkos::View<double *[3], Kokkos::LayoutRight, memory_space>;
164 using VirialType = Kokkos::View<double[3], Kokkos::LayoutRight, memory_space>;
166 Kokkos::Experimental::ScatterView<double *[3], Kokkos::LayoutRight,
169 Kokkos::Experimental::ScatterView<double[3], Kokkos::LayoutRight,
171 using ListAlgorithm = Cabana::HalfNeighborTag;
172 using ListType =
173 CustomVerletList<memory_space, ListAlgorithm, Cabana::VerletLayout2D,
174 Cabana::TeamVectorOpTag>;
175
176private:
177 /** The local id-to-particle index */
178 std::vector<Particle *> m_particle_index;
179 /** Implementation of the primary particle decomposition */
180 std::unique_ptr<ParticleDecomposition> m_decomposition;
181 /** Active type in m_decomposition */
183 /** One of @ref Cells::Resort, announces the level of resort needed.
184 */
185 unsigned m_resort_particles = Cells::RESORT_NONE;
186 bool m_verlet_skin_set = false;
187 bool m_rebuild_verlet_list = true;
188 bool m_rebuild_verlet_list_cabana = true;
189 std::vector<std::pair<Particle *, Particle *>> m_verlet_list;
190 double m_le_pos_offset_at_last_resort = 0.;
191 /** @brief Verlet list skin. */
192 double m_verlet_skin = 0.;
193 double m_verlet_reuse = 0.;
194 int m_cached_max_local_particle_id = 0;
195 std::size_t m_num_local_particles_cached = 0;
196 int m_max_id = 0;
197 std::unique_ptr<Kokkos::View<int *, memory_space>> m_id_to_index;
198 std::unique_ptr<ForceType> m_local_force;
199 std::optional<ScatterForce> m_scatter_force;
200#ifdef ESPRESSO_ROTATION
201 std::unique_ptr<ForceType> m_local_torque;
202 std::optional<ScatterForce> m_scatter_torque;
203#endif
204#ifdef ESPRESSO_NPT
205 std::unique_ptr<VirialType> m_local_virial;
206 std::optional<ScatterVirial> m_scatter_virial;
207#endif
208 std::unique_ptr<LocalBondState> m_bond_state;
209 std::unique_ptr<ListType> m_verlet_list_cabana;
210 /** particle properties using individual Kokkos Views */
211 std::unique_ptr<AoSoA_pack> m_aosoa;
212 /** The local id-to-index for aosoa data */
213 std::vector<Particle *> m_unique_particles;
214 std::shared_ptr<KokkosHandle> m_kokkos_handle;
215
216public:
217 CellStructure(BoxGeometry const &box);
218 virtual ~CellStructure();
219
220 bool use_verlet_list = true;
221
222 /**
223 * @brief Update local particle index.
224 *
225 * Update the entry for a particle in the local particle
226 * index.
227 *
228 * @param id Entry to update.
229 * @param p Pointer to the particle.
230 */
232 assert(id >= 0);
233 // cppcheck-suppress assertWithSideEffect
234 assert(not p or p->id() == id);
235
236 if (static_cast<unsigned int>(id) >= m_particle_index.size())
237 m_particle_index.resize(static_cast<unsigned int>(id + 1));
238
239 m_particle_index[static_cast<unsigned int>(id)] = p;
240 }
241
242 /**
243 * @brief Update local particle index.
244 *
245 * Update the entry for a particle in the local particle
246 * index.
247 *
248 * @param p Pointer to the particle.
249 */
251 update_particle_index(p.id(), std::addressof(p));
252 }
253
254 /**
255 * @brief Update local particle index.
256 *
257 * @param pl List of particles whose index entries should be updated.
258 */
260 for (auto &p : pl) {
261 update_particle_index(p.id(), std::addressof(p));
262 }
263 }
264
265 /**
266 * @brief Clear the particles index.
267 */
268 void clear_particle_index() { m_particle_index.clear(); }
269
270private:
271 /**
272 * @brief Append a particle to a list and update this
273 * particle index accordingly.
274 * @param pl List to add the particle to.
275 * @param p Particle to add.
276 */
277 Particle &append_indexed_particle(ParticleList &pl, Particle &&p) {
278 /* Check if cell may reallocate, in which case the index
279 * entries for all particles in this cell have to be
280 * updated. */
281 auto const may_reallocate = pl.size() >= pl.capacity();
282 auto &new_part = pl.insert(std::move(p));
283
284 if (may_reallocate)
286 else {
287 update_particle_index(new_part);
288 }
289
290 return new_part;
291 }
292
293public:
294 /**
295 * @brief Get a local particle by id.
296 *
297 * @param id Particle to get.
298 * @return Pointer to particle if it is local,
299 * nullptr otherwise.
300 */
302 assert(id >= 0);
303
304 if (static_cast<unsigned int>(id) >= m_particle_index.size())
305 return nullptr;
306
307 return m_particle_index[static_cast<unsigned int>(id)];
308 }
309
310 /** @overload */
311 const Particle *get_local_particle(int id) const {
312 assert(id >= 0);
313
314 if (static_cast<unsigned int>(id) >= m_particle_index.size())
315 return nullptr;
316
317 return m_particle_index[static_cast<unsigned int>(id)];
318 }
319
320 template <class InputRange, class OutputIterator>
322 std::ranges::transform(ids, out,
323 [this](int id) { return get_local_particle(id); });
324 }
325
326 CellStructureType decomposition_type() const { return m_type; }
327
328 /** Maximal cutoff supported by current cell system. */
330
331 /** Maximal pair range supported by current cell system. */
333
335 return Cells::particles(decomposition().local_cells());
336 }
337
339 return Cells::particles(decomposition().ghost_cells());
340 }
341
342 std::size_t count_local_particles() const {
343 std::size_t count = 0;
344 for (auto const &cell : m_decomposition->local_cells()) {
345 count += cell->particles().size();
346 }
347 return count;
348 }
349
350 /** @brief whether to use parallel version of @ref for_each_local_particle */
351 bool use_parallel_for_each_local_particle() const { return true; }
352
353 /**
354 * @brief Run a kernel on all local particles.
355 * The kernel is assumed to be thread-safe.
356 */
357 template <typename Callable>
358 void for_each_local_particle(Callable &&f, bool parallel = true) const {
360 parallel_for_each_particle_impl(decomposition().local_cells(), f);
361 return;
362 }
363 for (auto &p : local_particles()) {
364 f(p);
365 }
366 }
367
368 /**
369 * @brief Run a kernel on all ghost particles.
370 * The kernel is assumed to be thread-safe.
371 */
372 template <typename Callable>
374 for (auto &p : ghost_particles()) {
375 f(p);
376 }
377 }
378
379private:
380 /** Cell system dependent function to find the right cell for a
381 * particle.
382 * \param p Particle.
383 * \return pointer to cell where to put the particle, nullptr
384 * if the particle does not belong on this node.
385 */
386 Cell *particle_to_cell(const Particle &p) {
388 }
389 Cell const *particle_to_cell(const Particle &p) const {
391 }
392
393 template <typename Callable>
394 inline void parallel_for_each_particle_impl(std::span<Cell *const> cells,
395 Callable &f) const;
396
397public:
398 /**
399 * @brief Add a particle.
400 *
401 * Moves a particle into the cell system. This adds
402 * a particle to the local node, irrespective of where
403 * it belongs.
404 *
405 * @param p Particle to add.
406 * @return Pointer to the particle in the cell
407 * system.
408 */
410
411 /**
412 * @brief Add a particle.
413 *
414 * Moves a particle into the cell system, if it
415 * belongs to this node. Otherwise this does not
416 * have an effect and the particle is discarded.
417 * This can be used to add a particle without
418 * knowledge where it should be placed by calling
419 * the function on all nodes, it will then add
420 * the particle in exactly one place.
421 *
422 * @param p Particle to add.
423 * @return Pointer to particle if it is local, null
424 * otherwise.
425 */
427
428 /**
429 * @brief Remove a particle.
430 *
431 * Removes a particle and all bonds pointing
432 * to it. This is a collective call.
433 *
434 * @param id Id of particle to remove.
435 */
436 void remove_particle(int id);
437
438 /**
439 * @brief Get the maximal particle id on this node.
440 *
441 * This returns the highest particle id on
442 * this node, or -1 if there are no particles on this node.
443 */
444 int get_max_local_particle_id() const;
446 return m_cached_max_local_particle_id;
447 }
448 std::size_t get_num_local_particles_cached() const {
449 return m_num_local_particles_cached;
450 }
451 int get_local_pair_bond_numbers() const;
454 void set_local_bond_numbers(int p, int a, int d);
455#ifdef ESPRESSO_COLLISION_DETECTION
456 void clear_new_bonds();
457 void add_new_bond(int bond_id, std::vector<int> const &particle_ids);
458 void rebuild_bond_list();
459#endif // ESPRESSO_COLLISION_DETECTION
460
461 /**
462 * @brief Remove all particles from the cell system.
463 *
464 * This allows linear time removal of all particles from
465 * the system, removing each particle individually would
466 * be quadratic.
467 */
469
470 /**
471 * @brief Get the underlying particle decomposition.
472 *
473 * Should be used solely for informative purposes.
474 *
475 * @return The active particle decomposition.
476 */
478 return assert(m_decomposition), *m_decomposition;
479 }
480
481private:
483 return assert(m_decomposition), *m_decomposition;
484 }
485
486public:
487 /**
488 * @brief Increase the local resort level at least to @p level.
489 */
491 m_resort_particles |= level;
492 assert(m_resort_particles >= level);
493 }
494
495 /**
496 * @brief Get the currently scheduled resort level.
497 */
498 unsigned get_resort_particles() const { return m_resort_particles; }
499
500 /**
501 * @brief Set the resort level to sorted.
502 */
503 void clear_resort_particles() { m_resort_particles = Cells::RESORT_NONE; }
504
505 /**
506 * @brief Check whether a particle has moved further than half the skin
507 * since the last Verlet list update, thus requiring a resort.
508 * @param additional_offset Offset which is added to the distance the
509 * particle has travelled when comparing to half
510 * the Verlet skin (e.g., for Lees-Edwards BC).
511 * @return Whether a resort is needed.
512 */
513 bool
515
517 return m_le_pos_offset_at_last_resort;
518 }
519
520 /**
521 * @brief Synchronize number of ghosts.
522 */
523 void ghosts_count();
524
525 /**
526 * @brief Update ghost particles.
527 *
528 * Update ghost particles with data from the real particles.
529 *
530 * @param data_parts Particle parts to update, combination of @ref
531 * Cells::DataPart
532 */
533 void ghosts_update(unsigned data_parts);
534
535 /**
536 * @brief Update ghost particles, with particle resort if needed.
537 *
538 * Update ghost particles with data from the real particles.
539 * Resort particles if a resort is due.
540 *
541 * @param data_parts Particle parts to update, combination of @ref
542 * Cells::DataPart
543 */
545
546 /**
547 * @brief Add forces and torques from ghost particles to real particles.
548 */
550
551 /** Set forces and torques on all ghosts to zero. */
554 }
555
556#ifdef ESPRESSO_BOND_CONSTRAINT
557 /**
558 * @brief Add rattle corrections from ghost particles to real particles.
559 */
561#endif
562
563 /**
564 * @brief Resort particles.
565 */
566 void resort_particles(bool global_flag);
567
568 /** @brief Whether the Verlet skin is set. */
569 auto is_verlet_skin_set() const { return m_verlet_skin_set; }
570
571 /** @brief Get the Verlet skin. */
572 auto get_verlet_skin() const { return m_verlet_skin; }
573
574 /** @brief Set the Verlet skin. */
575 void set_verlet_skin(double value);
576
577 /** @brief Set the Verlet skin using a heuristic. */
579
581 if (n_verlet_updates > 0) {
582 m_verlet_reuse = n_steps / static_cast<double>(n_verlet_updates);
583 } else {
584 m_verlet_reuse = 0.;
585 }
586 }
587
588 /** @brief Average number of integration steps the Verlet list was re-used */
589 auto get_verlet_reuse() const { return m_verlet_reuse; }
590
591 /**
592 * @brief Resolve ids to particles.
593 *
594 * @throws BondResolutionError if one of the ids
595 * was not found.
596 *
597 * @param partner_ids Ids to resolve.
598 * @return Vector of Particle pointers.
599 */
600 auto resolve_bond_partners(std::span<const int> partner_ids) {
601 boost::container::static_vector<Particle *, 4> partners;
602 get_local_particles(partner_ids, std::back_inserter(partners));
603
604 /* Check if id resolution failed for any partner */
605 if (std::ranges::find(partners, nullptr) != partners.end()) {
606 throw BondResolutionError{};
607 }
608
609 return partners;
610 }
611
612private:
613 /**
614 * @brief Execute kernel for every bond on particle.
615 * @tparam Handler Callable, which can be invoked with
616 * (Particle, int, std::span<Particle *>),
617 * returning a bool.
618 * @param p Particles for whom the bonds are evaluated.
619 * @param handler is called for every bond, and handed
620 * p, the bond id and a span with the bond
621 * partners as arguments. Its return value
622 * should indicate if the bond was broken.
623 */
624 template <class Handler>
625 void execute_bond_handler(Particle &p, Handler const &handler) {
626 for (const BondView bond : p.bonds()) {
627 auto const partner_ids = bond.partner_ids();
628
629 try {
630 auto partners = resolve_bond_partners(partner_ids);
631 auto const partners_span = std::span(partners.data(), partners.size());
632 auto const bond_broken = handler(p, bond.bond_id(), partners_span);
633 if (bond_broken) {
634 bond_broken_error(p.id(), partner_ids);
635 }
636 } catch (BondResolutionError const &) {
637 bond_resolution_error(partner_ids);
638 }
639 }
640 }
641
642 /**
643 * @brief Go through ghost cells and remove the ghost entries from the
644 * local particle index.
645 */
646 void invalidate_ghosts() {
647 for (auto const &p : ghost_particles()) {
648 if (get_local_particle(p.id()) == &p) {
649 update_particle_index(p.id(), nullptr);
650 }
651 }
652 }
653
654 /** @brief Set the particle decomposition, keeping the particles. */
655 void set_particle_decomposition(
656 std::unique_ptr<ParticleDecomposition> &&decomposition) {
658
659 /* Swap in new cell system */
660 std::swap(m_decomposition, decomposition);
661
662 /* Add particles to new system */
663 for (auto &p : Cells::particles(decomposition->local_cells())) {
664 add_particle(std::move(p));
665 }
666 }
667
668public:
669 /**
670 * @brief Set the particle decomposition to @ref AtomDecomposition.
671 */
673
674 /**
675 * @brief Set the particle decomposition to @ref RegularDecomposition.
676 *
677 * @param range Interaction range.
678 * @param fully_connected_boundary neighbor cell directions for Lees-Edwards.
679 */
681 double range,
682 std::optional<std::pair<int, int>> fully_connected_boundary);
683
684 /**
685 * @brief Set the particle decomposition to @ref HybridDecomposition.
686 *
687 * @param cutoff_regular Interaction cutoff_regular.
688 * @param n_square_types Particle types to put into n_square decomposition.
689 */
691 std::set<int> n_square_types);
692
693private:
694 /**
695 * @brief Run link_cell algorithm for local cells.
696 *
697 * @tparam Kernel Needs to be callable with (Particle, Particle, Distance).
698 * @param kernel Pair kernel functor.
699 */
700 template <class Kernel> void link_cell(Kernel kernel) {
703 auto const first = boost::make_indirect_iterator(local_cells_span.begin());
704 auto const last = boost::make_indirect_iterator(local_cells_span.end());
705
706 if (maybe_box) {
708 first, last,
709 [&kernel, df = detail::MinimalImageDistance{decomposition().box()}](
710 Particle &p1, Particle &p2) { kernel(p1, p2, df(p1, p2)); });
711 } else {
712 if (decomposition().box().type() != BoxType::CUBOID) {
713 throw std::runtime_error("Non-cuboid box type is not compatible with a "
714 "particle decomposition that relies on "
715 "EuclideanDistance for distance calculation.");
716 }
718 first, last,
719 [&kernel, df = detail::EuclidianDistance{}](
720 Particle &p1, Particle &p2) { kernel(p1, p2, df(p1, p2)); });
721 }
722 }
723
724public:
725 auto get_max_id() const { return m_max_id; }
726
727 void set_kokkos_handle(std::shared_ptr<KokkosHandle> handle);
731
732 auto &get_id_to_index() { return *m_id_to_index; }
733 auto &get_local_force() { return *m_local_force; }
734 auto get_scatter_force() { return *m_scatter_force; }
735#ifdef ESPRESSO_ROTATION
736 auto &get_local_torque() { return *m_local_torque; }
737 auto get_scatter_torque() { return *m_scatter_torque; }
738#endif
739#ifdef ESPRESSO_NPT
740 auto &get_local_virial() { return *m_local_virial; }
741 auto get_scatter_virial() { return *m_scatter_virial; }
742#endif
743
744 auto &get_aosoa() { return *m_aosoa; }
745 auto const &get_aosoa() const { return *m_aosoa; }
746 auto const &get_unique_particles() const { return m_unique_particles; }
747 auto const &get_verlet_list_cabana() const { return *m_verlet_list_cabana; }
748 auto &bond_state() { return *m_bond_state; }
749 auto const &bond_state() const { return *m_bond_state; }
752
754 return m_rebuild_verlet_list_cabana;
755 }
756
757 /**
758 * @brief Update bond storage(m_*_bond_list_kokkos and m_*_bond_id_kokkos).
759 * @param pair_count Index for pair bond storage.
760 * @param angle_count Index for angle bond storage.
761 * @param dihedral_count Index for dihedral bond storage.
762 * @param p Particle pointer.
763 */
764 void update_bond_storage(int &pair_count, int &angle_count,
765 int &dihedral_count, Particle const &p);
766
767 /**
768 * @brief Reset local properties of the Verlet list.
769 * @param cutoff Pair interaction cutoff.
770 * @return True if a rebuild is needed.
771 */
772 [[nodiscard]] auto prepare_verlet_list_cabana(double cutoff) {
773 auto const rebuild = is_verlet_list_cabana_rebuild_needed();
774 if (rebuild) {
775 // If we have to rebuild, we need to count the particles
776 set_index_map(); // parallelized index_map
777 // Create essential variables for MD
779 } else {
780 // If we do not rebuild we can use the saved map
782 }
783 return rebuild;
784 }
785
789 kernel(m_decomposition->local_cells(), m_decomposition->box(),
790 *m_verlet_list_cabana);
791 }
792 m_rebuild_verlet_list_cabana = false;
793 }
794
795 void set_index_map();
796
797 inline void cell_list_loop(auto &&kernel) {
798 kernel(m_decomposition->local_cells(), m_decomposition->box());
799 }
800
801private:
802 /** Non-bonded pair loop with verlet lists.
803 *
804 * @param pair_kernel Kernel to apply
805 * @param verlet_criterion Filter for verlet lists.
806 */
807 template <class PairKernel, class VerletCriterion>
808 void verlet_list_loop(PairKernel pair_kernel,
810 /* In this case the verlet list update is attached to
811 * the pair kernel, and the verlet list is rebuilt as
812 * we go. */
813 if (m_rebuild_verlet_list) {
814 m_verlet_list.clear();
815
816 link_cell([&](Particle &p1, Particle &p2, Distance const &d) {
817 if (verlet_criterion(p1, p2, d.dist2)) {
818 m_verlet_list.emplace_back(&p1, &p2);
819 pair_kernel(p1, p2, d);
820 }
821 });
822
823 m_rebuild_verlet_list = false;
824 m_rebuild_verlet_list_cabana = true;
825 } else {
827 /* In this case the pair kernel is just run over the verlet list. */
828 if (maybe_box) {
829 auto const distance_function =
830 detail::MinimalImageDistance{decomposition().box()};
831 for (auto const &[p1, p2] : m_verlet_list) {
833 }
834 } else {
835 auto const distance_function = detail::EuclidianDistance{};
836 for (auto const &[p1, p2] : m_verlet_list) {
838 }
839 }
840 }
841 }
842
843public:
844 /** Bonded pair loop.
845 * @param bond_kernel Kernel to apply
846 */
847 template <class BondKernel> void bond_loop(BondKernel const &bond_kernel) {
848 for (auto &p : local_particles()) {
849 execute_bond_handler(p, bond_kernel);
850 }
851 }
852
853 /** Non-bonded pair loop.
854 * @param pair_kernel Kernel to apply
855 */
856 template <class PairKernel> void non_bonded_loop(PairKernel pair_kernel) {
857 link_cell(pair_kernel);
858 }
859
860 /** Non-bonded pair loop with potential use
861 * of verlet lists.
862 * @param pair_kernel Kernel to apply
863 * @param verlet_criterion Filter for verlet lists.
864 */
865 template <class PairKernel, class VerletCriterion>
868 if (use_verlet_list) {
869 verlet_list_loop(pair_kernel, verlet_criterion);
870 } else {
871 /* No verlet lists, just run the kernel with pairs from the cells. */
872 link_cell(pair_kernel);
873 }
874 }
875
876 /**
877 * @brief Check that particle index is commensurate with particles.
878 *
879 * For each local particles is checked that has a correct entry
880 * in the particles index, and that there are no excess (non-existing)
881 * particles in the index.
882 */
883 void check_particle_index() const;
884
885 /**
886 * @brief Check that particles are in the correct cell.
887 *
888 * This checks for all local particles that the result
889 * of particles_to_cell is the cell the particles is
890 * actually in, e.g. that the particles are sorted according
891 * to particles_to_cell.
892 */
893 void check_particle_sorting() const;
894
895public:
896 /**
897 * @brief Find cell a particle is stored in.
898 *
899 * For local particles, this returns the cell they
900 * are stored in, otherwise nullptr is returned.
901 *
902 * @param p Particle to find cell for
903 * @return Cell for particle or nullptr.
904 */
907
908 if (p.is_ghost()) {
909 return nullptr;
910 }
911
912 return particle_to_cell(p);
913 }
914
915 /**
916 * @brief Run kernel on all particles inside local cell and its neighbors.
917 *
918 * @param p Particle to find cell for
919 * @param kernel Function with signature <tt>double(Particle const&,
920 * Particle const&, Utils::Vector3d const&)</tt>
921 * @return false if cell is not found, otherwise true
922 */
923 template <class Kernel>
925 Kernel &kernel) {
926 auto const cell = find_current_cell(p);
927
928 if (cell == nullptr) {
929 return false;
930 }
931
933
934 if (maybe_box) {
935 auto const distance_function =
936 detail::MinimalImageDistance{decomposition().box()};
937 short_range_neighbor_loop(p, cell, kernel, distance_function);
938 } else {
939 auto const distance_function = detail::EuclidianDistance{};
940 short_range_neighbor_loop(p, cell, kernel, distance_function);
941 }
942 return true;
943 }
944
945private:
946 template <class Kernel, class DistanceFunc>
947 void short_range_neighbor_loop(Particle const &p1, Cell *const cell,
948 Kernel &kernel, DistanceFunc const &df) {
949 /* Iterate over particles inside cell */
950 for (auto const &p2 : cell->particles()) {
951 if (p1.id() != p2.id()) {
952 auto const vec = df(p1, p2).vec21;
953 kernel(p1, p2, vec);
954 }
955 }
956 /* Iterate over all neighbors */
957 for (auto const neighbor : cell->neighbors().all()) {
958 /* Iterate over particles in neighbors */
959 if (neighbor != cell) {
960 for (auto const &p2 : neighbor->particles()) {
961 auto const vec = df(p1, p2).vec21;
962 kernel(p1, p2, vec);
963 }
964 }
965 }
966 }
967};
ParticleIterator< std::span< Cell *const >::iterator > CellParticleIterator
CellStructureType
Cell structure topology.
@ NSQUARE
Atom decomposition (N-square).
unsigned map_data_parts(unsigned data_parts)
Map the data parts flags from cells to those used internally by the ghost communication.
Vector implementation and trait types for boost qvm interoperability.
void bond_broken_error(int id, std::span< const int > partner_ids)
void bond_resolution_error(std::span< const int > partner_ids)
Immutable view on a bond.
Definition BondList.hpp:44
ESPRESSO_ATTR_ALWAYS_INLINE Utils::Vector3< T > get_mi_vector(Utils::Vector3< T > const &a, Utils::Vector3< T > const &b) const
Get the minimum-image vector between two coordinates.
BoxType type() const
Describes a cell structure / cell system.
ParticleRange ghost_particles() const
auto & get_local_force()
void for_each_ghost_particle(Callable &&f) const
Run a kernel on all ghost particles.
Particle * get_local_particle(int id)
Get a local particle by id.
Kokkos::Experimental::ScatterView< double *[3], Kokkos::LayoutRight, memory_space > ScatterForce
void set_kokkos_handle(std::shared_ptr< KokkosHandle > handle)
void update_particle_index(ParticleList &pl)
Update local particle index.
void check_particle_sorting() const
Check that particles are in the correct cell.
void rebuild_verlet_list_cabana(auto &&kernel, bool rebuild_verlet_list)
auto & get_id_to_index()
std::size_t count_local_particles() const
auto get_scatter_virial()
auto const & bond_state() const
virtual ~CellStructure()
int get_local_angle_bond_numbers() const
void clear_resort_particles()
Set the resort level to sorted.
Cell * find_current_cell(const Particle &p)
Find cell a particle is stored in.
auto get_max_id() const
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.
int get_local_pair_bond_numbers() const
void clear_particle_index()
Clear the particles index.
Kokkos::Experimental::ScatterView< double[3], Kokkos::LayoutRight, memory_space > ScatterVirial
auto prepare_verlet_list_cabana(double cutoff)
Reset local properties of the Verlet list.
static constexpr auto vector_length
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.
void for_each_local_particle(Callable &&f, bool parallel=true) const
Run a kernel on all local particles.
auto get_le_pos_offset_at_last_resort() const
int get_local_dihedral_bond_numbers() const
Kokkos::HostSpace memory_space
int get_cached_max_local_particle_id() const
void get_local_particles(InputRange ids, OutputIterator out)
void update_verlet_stats(int n_steps, int n_verlet_updates)
Kokkos::View< double *[3], Kokkos::LayoutRight, memory_space > ForceType
auto & get_local_torque()
void ghosts_reset_forces()
Set forces and torques on all ghosts to zero.
Kokkos::View< double[3], Kokkos::LayoutRight, memory_space > VirialType
auto const & get_aosoa() const
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
unsigned get_resort_particles() const
Get the currently scheduled resort level.
auto get_verlet_reuse() const
Average number of integration steps the Verlet list was re-used.
void rebuild_local_properties(double pair_cutoff)
void non_bonded_loop(PairKernel pair_kernel)
Non-bonded pair loop.
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,...
const Particle * get_local_particle(int id) const
This is an overloaded member function, provided for convenience. It differs from the above function o...
auto resolve_bond_partners(std::span< const int > partner_ids)
Resolve ids to particles.
void bond_loop(BondKernel const &bond_kernel)
Bonded pair loop.
void ghosts_count()
Synchronize number of ghosts.
void set_resort_particles(Cells::Resort level)
Increase the local resort level at least to level.
void cell_list_loop(auto &&kernel)
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.
Cabana::HalfNeighborTag ListAlgorithm
auto get_scatter_torque()
auto get_verlet_skin() const
Get the Verlet skin.
void set_regular_decomposition(double range, std::optional< std::pair< int, int > > fully_connected_boundary)
Set the particle decomposition to RegularDecomposition.
void reset_local_force_and_torque()
void set_atom_decomposition()
Set the particle decomposition to AtomDecomposition.
auto const & get_verlet_list_cabana() const
bool run_on_particle_short_range_neighbors(Particle const &p, Kernel &kernel)
Run kernel on all particles inside local cell and its neighbors.
bool use_parallel_for_each_local_particle() const
whether to use parallel version of for_each_local_particle
void remove_all_particles()
Remove all particles from the cell system.
ParticleRange local_particles() const
void update_particle_index(Particle &p)
Update local particle index.
void ghosts_reduce_rattle_correction()
Add rattle corrections from ghost particles to real particles.
CellStructureType decomposition_type() const
auto is_verlet_list_cabana_rebuild_needed() const
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 non_bonded_loop(PairKernel pair_kernel, const VerletCriterion &verlet_criterion)
Non-bonded pair loop with potential use of verlet lists.
void reset_local_properties()
Definition Cell.hpp:96
auto & particles()
Particles.
Definition Cell.hpp:103
A distributed particle decomposition.
virtual Utils::Vector3d max_cutoff() const =0
Maximum supported cutoff.
virtual std::span< Cell *const > local_cells() const =0
Get pointer to local cells.
virtual Cell * particle_to_cell(Particle const &p)=0
Determine which cell a particle id belongs to.
virtual Utils::Vector3d max_range() const =0
Range in which calculations are performed.
virtual std::optional< BoxGeometry > minimum_image_distance() const =0
Return the box geometry needed for distance calculation if minimum image convention should be used ne...
virtual BoxGeometry const & box() const =0
A range of particles.
Abstract class that represents a component of the system.
std::size_t capacity() const
Capacity of the container.
Definition Bag.hpp:104
T & insert(T const &v)
Insert an element into the container.
Definition Bag.hpp:147
std::size_t size() const
Number of elements in the container.
Definition Bag.hpp:90
Returns true if the particles are to be considered for short range interactions.
cudaStream_t stream[1]
CUDA streams for parallel computing on CPU and GPU.
Ghost particles and particle exchange.
void link_cell(CellIterator first, CellIterator last, PairKernel &&pair_kernel)
Iterates over all particles in the cell range, and over all pairs within the cells and with their nei...
Definition link_cell.hpp:32
DataPart
Flags to select particle parts for communication.
@ DATA_PART_MOMENTUM
Particle::m.
@ DATA_PART_FORCE
Particle::f.
@ DATA_PART_PROPERTIES
Particle::p.
@ DATA_PART_BONDS
Particle::bonds.
@ DATA_PART_NONE
Nothing.
@ DATA_PART_RATTLE
Particle::rattle.
@ DATA_PART_POSITION
Particle::r.
ParticleRange particles(std::span< Cell *const > cells)
auto constexpr new_part
Exception indicating that a particle id could not be resolved.
Distance vector and length handed to pair kernels.
Utils::Vector3d vec21
Distance(Utils::Vector3d const &vec21)
Struct holding all information for one particle.
Definition Particle.hpp:436
constexpr auto const & id() const
Definition Particle.hpp:455
constexpr auto const & force_and_torque() const
Definition Particle.hpp:482
constexpr bool is_ghost() const
Definition Particle.hpp:485