AutoPas  3.0.0
Loading...
Searching...
No Matches
LogicHandler.h
Go to the documentation of this file.
1
7#pragma once
8#include <atomic>
9#include <limits>
10#include <memory>
11#include <optional>
12#include <tuple>
13#include <type_traits>
14#include <vector>
15
33#include "autopas/utils/Timer.h"
42
43namespace autopas {
44
50template <typename Particle_T>
52 public:
60 LogicHandler(const std::shared_ptr<TuningManager> &tunerManager, const LogicHandlerInfo &logicHandlerInfo,
61 unsigned int rebuildFrequency, const std::string &outputSuffix)
62 : _tuningManager(tunerManager),
63 _logicHandlerInfo(logicHandlerInfo),
64 _neighborListRebuildFrequency{rebuildFrequency},
65 _particleBuffer(autopas_get_max_threads()),
66 _haloParticleBuffer(autopas_get_max_threads()),
67 _remainderPairwiseInteractionHandler(_spatialLocks),
68 _remainderTriwiseInteractionHandler(_spatialLocks),
69 _verletClusterSize(logicHandlerInfo.verletClusterSize),
70 _aosSortingThreshold(logicHandlerInfo.aosSortingThreshold),
71 _soaSortingThreshold(logicHandlerInfo.soaSortingThreshold),
72 _iterationLogger(outputSuffix,
73 std::any_of(tunerManager->getAutoTuners().begin(), tunerManager->getAutoTuners().end(),
74 [](const auto &tuner) { return tuner.second->canMeasureEnergy(); })),
75 _flopLogger(outputSuffix),
76 _liveInfoLogger(outputSuffix) {
77 using namespace autopas::utils::ArrayMath::literals;
78 // Initialize AutoPas with tuners for given interaction types
79 for (const auto &[interactionType, tuner] : tunerManager->getAutoTuners()) {
80 _interactionTypes.insert(interactionType);
81
82 const auto configuration = tuner->getCurrentConfig();
83 // initialize the container and make sure it is valid
84 _currentContainerSelectorInfo = ContainerSelectorInfo{
85 _logicHandlerInfo.boxMin, _logicHandlerInfo.boxMax, _logicHandlerInfo.cutoff,
86 configuration.cellSizeFactor, _logicHandlerInfo.verletSkin, _verletClusterSize,
87 _aosSortingThreshold, _soaSortingThreshold, configuration.loadEstimator};
88 _currentContainer =
89 ContainerSelector<Particle_T>::generateContainer(configuration.container, _currentContainerSelectorInfo);
90 checkMinimalSize();
91 }
92
93 // initialize locks needed for remainder traversal
94 const auto interactionLength = logicHandlerInfo.cutoff + logicHandlerInfo.verletSkin;
95 const auto interactionLengthInv = 1. / interactionLength;
96 const auto boxLengthWithHalo = logicHandlerInfo.boxMax - logicHandlerInfo.boxMin + (2 * interactionLength);
97 initSpatialLocks(boxLengthWithHalo, interactionLengthInv);
98 }
99
104 ParticleContainerInterface<Particle_T> &getContainer() { return *_currentContainer; }
105
111 [[nodiscard]] std::vector<Particle_T> collectLeavingParticlesFromBuffer(bool insertOwnedParticlesToContainer) {
112 const auto &boxMin = _currentContainer->getBoxMin();
113 const auto &boxMax = _currentContainer->getBoxMax();
114 std::vector<Particle_T> leavingBufferParticles{};
115 for (auto &cell : _particleBuffer) {
116 auto &buffer = cell._particles;
117 if (insertOwnedParticlesToContainer) {
118 // Can't be const because we potentially modify ownership before re-adding
119 for (auto &p : buffer) {
120 if (p.isDummy()) {
121 continue;
122 }
123 if (utils::inBox(p.getR(), boxMin, boxMax)) {
124 p.setOwnershipState(OwnershipState::owned);
125 _currentContainer->addParticle(p);
126 } else {
127 leavingBufferParticles.push_back(p);
128 }
129 }
130 buffer.clear();
131 } else {
132 for (auto iter = buffer.begin(); iter < buffer.end();) {
133 auto &p = *iter;
134
135 auto fastRemoveP = [&]() {
136 // Fast remove of particle, i.e., swap with last entry && pop.
137 std::swap(p, buffer.back());
138 buffer.pop_back();
139 // Do not increment the iter afterward!
140 };
141 if (p.isDummy()) {
142 // We remove dummies!
143 fastRemoveP();
144 // In case we swapped a dummy here, don't increment the iterator and do another iteration to check again.
145 continue;
146 }
147 // if p was a dummy a new particle might now be at the memory location of p so we need to check that.
148 // We also just might have deleted the last particle in the buffer in that case the inBox check is meaningless
149 if (not buffer.empty() and utils::notInBox(p.getR(), boxMin, boxMax)) {
150 leavingBufferParticles.push_back(p);
151 fastRemoveP();
152 } else {
153 ++iter;
154 }
155 }
156 }
157 }
158 return leavingBufferParticles;
159 }
160
164 std::vector<Particle_T> updateContainer() {
165 ++_iteration;
166
167#ifdef AUTOPAS_ENABLE_DYNAMIC_CONTAINERS
169
170 if (_tuningManager->isStartOfTuningPhase(_iteration)) {
171 _numRebuildsInNonTuningPhase = 0;
172 }
173
174 // Rebuild frequency estimation should be triggered early in the tuning phase.
175 // This is necessary because runtime prediction for each trial configuration
176 // depends on the rebuild frequency.
177 // To avoid the influence of poorly initialized velocities at the start of the simulation,
178 // the rebuild frequency is estimated at iteration corresponding to the last sample of the first configuration.
179 // The rebuild frequency estimated here is then reused for the remainder of the tuning phase.
180 if (_tuningManager->inFirstConfigurationLastSample(_iteration)) {
181 // Fetch the needed information for estimating the rebuild frequency from _logicHandlerInfo
182 // and estimate the current rebuild frequency using the velocity method.
183 double rebuildFrequencyEstimate =
184 getVelocityMethodRFEstimate(_logicHandlerInfo.verletSkin, _logicHandlerInfo.deltaT);
185 double userProvidedRF = static_cast<double>(_neighborListRebuildFrequency);
186 // The user defined rebuild frequency is considered as the upper bound.
187 // If velocity method estimate exceeds upper bound, set the rebuild frequency to the user defined value.
188 // This is done because we currently use the user defined rebuild frequency as the upper bound to avoid expensive
189 // buffer interactions.
190 _tuningManager->setRebuildFrequency(std::min(userProvidedRF, rebuildFrequencyEstimate));
191 }
192#endif
193 bool doDataStructureUpdate = not neighborListsAreValid();
194
195 if (_tuningManager->tuningPhaseJustFinished()) {
196 _iterationAfterLastTuningPhase = _iteration;
197 }
198 // We will do a rebuild in this timestep
199 if (not _neighborListsAreValid.load(std::memory_order_relaxed)) {
200 _stepsSinceLastListRebuild = 0;
201 }
202 ++_stepsSinceLastListRebuild;
203
204 // The next call also adds particles to the container if doDataStructureUpdate is true.
205 auto leavingBufferParticles = collectLeavingParticlesFromBuffer(doDataStructureUpdate);
206
207 AutoPasLog(TRACE, "Initiating container update.");
208 auto leavingParticles = _currentContainer->updateContainer(not doDataStructureUpdate);
209 leavingParticles.insert(leavingParticles.end(), leavingBufferParticles.begin(), leavingBufferParticles.end());
210
211 // Subtract the amount of leaving particles from the number of owned particles.
212 _numParticlesOwned.fetch_sub(leavingParticles.size(), std::memory_order_relaxed);
213 // updateContainer deletes all halo particles.
214 std::for_each(_haloParticleBuffer.begin(), _haloParticleBuffer.end(), [](auto &buffer) { buffer.clear(); });
215 _numParticlesHalo.store(0, std::memory_order_relaxed);
216 return leavingParticles;
217 }
218
225 std::vector<Particle_T> resizeBox(const std::array<double, 3> &boxMin, const std::array<double, 3> &boxMax) {
226 using namespace autopas::utils::ArrayMath::literals;
227 const auto &oldMin = _currentContainer->getBoxMin();
228 const auto &oldMax = _currentContainer->getBoxMax();
229
230 // if nothing changed, do nothing
231 if (oldMin == boxMin and oldMax == boxMax) {
232 return {};
233 }
234
235 // sanity check that new size is actually positive
236 for (size_t i = 0; i < boxMin.size(); ++i) {
237 if (boxMin[i] >= boxMax[i]) {
239 "New box size in dimension {} is not positive!\nboxMin[{}] = {}\nboxMax[{}] = {}", i, i, boxMin[i], i,
240 boxMax[i]);
241 }
242 }
243
244 // warn if domain changes too drastically
245 const auto newLength = boxMax - boxMin;
246 const auto oldLength = oldMax - oldMin;
247 const auto relDiffLength = newLength / oldLength;
248 for (size_t i = 0; i < newLength.size(); ++i) {
249 // warning threshold is set arbitrary and up for change if needed
250 if (relDiffLength[i] > 1.3 or relDiffLength[i] < 0.7) {
251 AutoPasLog(WARN,
252 "LogicHandler.resize(): Domain size changed drastically in dimension {}! Gathered AutoTuning "
253 "information might not be applicable anymore!\n"
254 "Size old box : {}\n"
255 "Size new box : {}\n"
256 "Relative diff: {}",
258 utils::ArrayUtils::to_string(relDiffLength));
259 }
260 }
261
262 // The new box size is valid, so update the current container info.
263 _currentContainerSelectorInfo.boxMin = boxMin;
264 _currentContainerSelectorInfo.boxMax = boxMax;
265
266 // check all particles
267 std::vector<Particle_T> particlesNowOutside;
268 for (auto pIter = _currentContainer->begin(); pIter.isValid(); ++pIter) {
269 // make sure only owned ones are present
270 if (not pIter->isOwned()) {
272 "LogicHandler::resizeBox() encountered non owned particle. "
273 "When calling resizeBox() these should be already deleted. "
274 "This could be solved by calling updateContainer() before resizeBox().");
275 }
276 // owned particles that are now outside are removed from the container and returned
277 if (not utils::inBox(pIter->getR(), boxMin, boxMax)) {
278 particlesNowOutside.push_back(*pIter);
281 }
282 }
283
284 // Resize by generating a new container with the new box size and moving all particles to it.
285 auto newContainer = ContainerSelector<Particle_T>::generateContainer(_currentContainer->getContainerType(),
286 _currentContainerSelectorInfo);
287 setCurrentContainer(std::move(newContainer));
288 // The container might have changed sufficiently that we would need a different number of spatial locks.
289 const auto boxLength = boxMax - boxMin;
290 const auto interactionLengthInv = 1. / _currentContainer->getInteractionLength();
291 initSpatialLocks(boxLength, interactionLengthInv);
292
293 // Set this flag, s.t., the container is rebuilt!
294 _neighborListsAreValid.store(false, std::memory_order_relaxed);
295
296 return particlesNowOutside;
297 }
298
305 void reserve(size_t numParticles) {
306 const auto numParticlesHaloEstimate = autopas::utils::NumParticlesEstimator::estimateNumHalosUniform(
307 numParticles, _currentContainer->getBoxMin(), _currentContainer->getBoxMax(),
308 _currentContainer->getInteractionLength());
309 reserve(numParticles, numParticlesHaloEstimate);
310 }
311
318 void reserve(size_t numParticles, size_t numHaloParticles) {
319 const auto numHaloParticlesPerBuffer = numHaloParticles / _haloParticleBuffer.size();
320 for (auto &buffer : _haloParticleBuffer) {
321 buffer.reserve(numHaloParticlesPerBuffer);
322 }
323 // there is currently no good heuristic for this buffer, so reuse the one for halos.
324 for (auto &buffer : _particleBuffer) {
325 buffer.reserve(numHaloParticlesPerBuffer);
326 }
327
328 // reserve is called for the container only in the rebuild iterations.
329 // during non-rebuild iterations, particles are not added in the container but in buffer.
330 if (not _neighborListsAreValid.load(std::memory_order_relaxed)) {
331 _currentContainer->reserve(numParticles, numHaloParticles);
332 }
333 }
334
338 void addParticle(const Particle_T &p) {
339 // first check that the particle actually belongs in the container
340 const auto &boxMin = _currentContainer->getBoxMin();
341 const auto &boxMax = _currentContainer->getBoxMax();
342 if (utils::notInBox(p.getR(), boxMin, boxMax)) {
344 "LogicHandler: Trying to add a particle that is not in the bounding box.\n"
345 "Box Min {}\n"
346 "Box Max {}\n"
347 "{}",
348 boxMin, boxMax, p.toString());
349 }
350 Particle_T particleCopy = p;
351 particleCopy.setOwnershipState(OwnershipState::owned);
352 if (not _neighborListsAreValid.load(std::memory_order_relaxed)) {
353 // Container has to (about to) be invalid to be able to add Particles!
354 _currentContainer->template addParticle<false>(particleCopy);
355 } else {
356 // If the container is valid, we add it to the particle buffer.
357 _particleBuffer[autopas_get_thread_num()].addParticle(particleCopy);
358 }
359 _numParticlesOwned.fetch_add(1, std::memory_order_relaxed);
360 }
361
365 void addHaloParticle(const Particle_T &haloParticle) {
366 const auto &boxMin = _currentContainer->getBoxMin();
367 const auto &boxMax = _currentContainer->getBoxMax();
368 Particle_T haloParticleCopy = haloParticle;
369 if (utils::inBox(haloParticleCopy.getR(), boxMin, boxMax)) {
371 "LogicHandler: Trying to add a halo particle that is not outside the box of the container.\n"
372 "Box Min {}\n"
373 "Box Max {}\n"
374 "{}",
375 utils::ArrayUtils::to_string(boxMin), utils::ArrayUtils::to_string(boxMax), haloParticleCopy.toString());
376 }
377 haloParticleCopy.setOwnershipState(OwnershipState::halo);
378 if (not _neighborListsAreValid.load(std::memory_order_relaxed)) {
379 // If the neighbor lists are not valid, we can add the particle.
380 _currentContainer->template addHaloParticle</* checkInBox */ false>(haloParticleCopy);
381 } else {
382 // Check if we can update an existing halo(dummy) particle.
383 bool updated = _currentContainer->updateHaloParticle(haloParticleCopy);
384 if (not updated) {
385 // If we couldn't find an existing particle, add it to the halo particle buffer.
386 _haloParticleBuffer[autopas_get_thread_num()].addParticle(haloParticleCopy);
387 }
388 }
389 _numParticlesHalo.fetch_add(1, std::memory_order_relaxed);
390 }
391
396 _neighborListsAreValid.store(false, std::memory_order_relaxed);
397 _currentContainer->deleteAllParticles();
398 std::for_each(_particleBuffer.begin(), _particleBuffer.end(), [](auto &buffer) { buffer.clear(); });
399 std::for_each(_haloParticleBuffer.begin(), _haloParticleBuffer.end(), [](auto &buffer) { buffer.clear(); });
400 // all particles are gone -> reset counters.
401 _numParticlesOwned.store(0, std::memory_order_relaxed);
402 _numParticlesHalo.store(0, std::memory_order_relaxed);
403 }
404
411 std::tuple<bool, bool> deleteParticleFromBuffers(Particle_T &particle) {
412 // find the buffer the particle belongs to
413 auto &bufferCollection = particle.isOwned() ? _particleBuffer : _haloParticleBuffer;
414 for (auto &cell : bufferCollection) {
415 auto &buffer = cell._particles;
416 // if the address of the particle is between start and end of the buffer it is in this buffer
417 if (not buffer.empty() and &(buffer.front()) <= &particle and &particle <= &(buffer.back())) {
418 const bool isRearParticle = &particle == &buffer.back();
419 // swap-delete
420 particle = buffer.back();
421 buffer.pop_back();
422 return {true, not isRearParticle};
423 }
424 }
425 return {false, true};
426 }
427
433 void decreaseParticleCounter(Particle_T &particle) {
434 if (particle.isOwned()) {
435 _numParticlesOwned.fetch_sub(1, std::memory_order_relaxed);
436 } else {
437 _numParticlesHalo.fetch_sub(1, std::memory_order_relaxed);
438 }
439 }
440
461 template <class Functor>
462 bool computeInteractionsPipeline(Functor *functor, const InteractionTypeOption &interactionType);
463
470 template <class Iterator>
471 typename Iterator::ParticleVecType gatherAdditionalVectors(IteratorBehavior behavior) {
472 typename Iterator::ParticleVecType additionalVectors;
473 if (not(behavior & IteratorBehavior::containerOnly)) {
474 additionalVectors.reserve(static_cast<bool>(behavior & IteratorBehavior::owned) * _particleBuffer.size() +
475 static_cast<bool>(behavior & IteratorBehavior::halo) * _haloParticleBuffer.size());
476 if (behavior & IteratorBehavior::owned) {
477 for (auto &buffer : _particleBuffer) {
478 // Don't insert empty buffers. This also means that we won't pick up particles added during iterating if they
479 // go to the buffers. But since we wouldn't pick them up if they go into the container to a cell that the
480 // iterators already passed this is unsupported anyways.
481 if (not buffer.isEmpty()) {
482 additionalVectors.push_back(&(buffer._particles));
483 }
484 }
485 }
486 if (behavior & IteratorBehavior::halo) {
487 for (auto &buffer : _haloParticleBuffer) {
488 if (not buffer.isEmpty()) {
489 additionalVectors.push_back(&(buffer._particles));
490 }
491 }
492 }
493 }
494 return additionalVectors;
495 }
496
501 auto additionalVectors = gatherAdditionalVectors<ContainerIterator<Particle_T, true, false>>(behavior);
502 return _currentContainer->begin(behavior, std::ref(additionalVectors));
503 }
504
508 ContainerIterator<Particle_T, false, false> begin(IteratorBehavior behavior) const {
509 auto additionalVectors =
511 behavior);
512 return _currentContainer->begin(behavior, std::ref(additionalVectors));
513 }
514
518 ContainerIterator<Particle_T, true, true> getRegionIterator(const std::array<double, 3> &lowerCorner,
519 const std::array<double, 3> &higherCorner,
520 IteratorBehavior behavior) {
521 // sanity check: Most of our stuff depends on `inBox`, which does not handle lowerCorner > higherCorner well.
522 for (size_t d = 0; d < 3; ++d) {
523 if (lowerCorner[d] > higherCorner[d]) {
525 "Requesting region Iterator where the upper corner is lower than the lower corner!\n"
526 "Lower corner: {}\n"
527 "Upper corner: {}",
528 lowerCorner, higherCorner);
529 }
530 }
531
532 auto additionalVectors = gatherAdditionalVectors<ContainerIterator<Particle_T, true, true>>(behavior);
533 return _currentContainer->getRegionIterator(lowerCorner, higherCorner, behavior, std::ref(additionalVectors));
534 }
535
539 ContainerIterator<Particle_T, false, true> getRegionIterator(const std::array<double, 3> &lowerCorner,
540 const std::array<double, 3> &higherCorner,
541 IteratorBehavior behavior) const {
542 // sanity check: Most of our stuff depends on `inBox`, which does not handle lowerCorner > higherCorner well.
543 for (size_t d = 0; d < 3; ++d) {
544 if (lowerCorner[d] > higherCorner[d]) {
546 "Requesting region Iterator where the upper corner is lower than the lower corner!\n"
547 "Lower corner: {}\n"
548 "Upper corner: {}",
549 lowerCorner, higherCorner);
550 }
551 }
552
553 auto additionalVectors =
555 return std::as_const(_currentContainer)
556 ->getRegionIterator(lowerCorner, higherCorner, behavior, std::ref(additionalVectors));
557 }
558
563 [[nodiscard]] unsigned long getNumberOfParticlesOwned() const { return _numParticlesOwned; }
564
569 [[nodiscard]] unsigned long getNumberOfParticlesHalo() const { return _numParticlesHalo; }
570
594 template <class Functor>
595 [[nodiscard]] std::tuple<std::unique_ptr<TraversalInterface>, bool> isConfigurationApplicable(
596 const Configuration &config, Functor &functor);
597
608 void setParticleBuffers(const std::vector<FullParticleCell<Particle_T>> &particleBuffers,
609 const std::vector<FullParticleCell<Particle_T>> &haloParticleBuffers);
610
618 std::tuple<const std::vector<FullParticleCell<Particle_T>> &, const std::vector<FullParticleCell<Particle_T>> &>
619 getParticleBuffers() const;
620
632 [[nodiscard]] double getMeanRebuildFrequency(bool considerOnlyLastNonTuningPhase = false) const {
633#ifdef AUTOPAS_ENABLE_DYNAMIC_CONTAINERS
634 const auto numRebuilds = considerOnlyLastNonTuningPhase ? _numRebuildsInNonTuningPhase : _numRebuilds;
635 // The total number of iterations is iteration + 1
636 const auto iterationCount =
637 considerOnlyLastNonTuningPhase ? _iteration - _iterationAfterLastTuningPhase : _iteration + 1;
638 if (numRebuilds == 0) {
639 return static_cast<double>(_neighborListRebuildFrequency);
640 } else {
641 return static_cast<double>(iterationCount) / numRebuilds;
642 }
643#else
644 return static_cast<double>(_neighborListRebuildFrequency);
645#endif
646 }
647
655 double getVelocityMethodRFEstimate(const double skin, const double deltaT) const {
657 // Initialize the maximum velocity to zero
658 double maxVelocity = 0;
659 // Iterate over the owned particles in container to determine maximum velocity
660 AUTOPAS_OPENMP(parallel reduction(max : maxVelocity))
661 for (auto iter = this->begin(IteratorBehavior::owned | IteratorBehavior::containerOnly); iter.isValid(); ++iter) {
662 std::array<double, 3> tempVel = iter->getV();
663 double tempVelAbs = sqrt(dot(tempVel, tempVel));
664 maxVelocity = std::max(tempVelAbs, maxVelocity);
665 }
666 // return the rebuild frequency estimate
667 return skin / maxVelocity / deltaT / 2;
668 }
674
680
686
696
697 private:
710 void initSpatialLocks(const std::array<double, 3> &boxLength, double interactionLengthInv) {
711 using namespace autopas::utils::ArrayMath::literals;
714
715 // The maximum number of spatial locks is capped at 1e6.
716 // This limit is chosen more or less arbitrary. It is big enough so that our regular MD simulations
717 // fall well within it and small enough so that no memory issues arise.
718 // There were no rigorous tests for an optimal number of locks.
719 // Without this cap, very large domains (or tiny cutoffs) would generate an insane number of locks,
720 // that could blow up the memory.
721 constexpr size_t maxNumSpacialLocks{1000000};
722
723 // One lock per interaction length or less if this would generate too many.
724 const std::array<size_t, 3> locksPerDim = [&]() {
725 // First naively calculate the number of locks if we simply take the desired cell length.
726 // Ceil because both decisions are possible, and we are generous gods.
727 const std::array<size_t, 3> locksPerDimNaive =
728 static_cast_copy_array<size_t>(ceil(boxLength * interactionLengthInv));
729 const auto totalLocksNaive =
730 std::accumulate(locksPerDimNaive.begin(), locksPerDimNaive.end(), 1ul, std::multiplies<>());
731 // If the number of locks is within the limits everything is fine and we can return.
732 if (totalLocksNaive <= maxNumSpacialLocks) {
733 return locksPerDimNaive;
734 } else {
735 // If the number of locks grows too large, calculate the locks per dimension proportionally to the side lengths.
736 // Calculate side length relative to dimension 0.
737 const std::array<double, 3> boxSideProportions = {
738 1.,
739 boxLength[0] / boxLength[1],
740 boxLength[0] / boxLength[2],
741 };
742 // With this, calculate the number of locks the first dimension should receive.
743 const auto prodProportions =
744 std::accumulate(boxSideProportions.begin(), boxSideProportions.end(), 1., std::multiplies<>());
745 // Needs floor, otherwise we exceed the limit.
746 const auto locksInFirstDimFloat = std::floor(std::cbrt(maxNumSpacialLocks * prodProportions));
747 // From this and the proportions relative to the first dimension, we can calculate the remaining number of locks
748 const std::array<size_t, 3> locksPerDimLimited = {
749 static_cast<size_t>(locksInFirstDimFloat), // omitted div by 1
750 static_cast<size_t>(locksInFirstDimFloat / boxSideProportions[1]),
751 static_cast<size_t>(locksInFirstDimFloat / boxSideProportions[2]),
752 };
753 return locksPerDimLimited;
754 }
755 }();
756 _spatialLocks.resize(locksPerDim[0]);
757 for (auto &lockVecVec : _spatialLocks) {
758 lockVecVec.resize(locksPerDim[1]);
759 for (auto &lockVec : lockVecVec) {
760 lockVec.resize(locksPerDim[2]);
761 for (auto &lockPtr : lockVec) {
762 if (not lockPtr) {
763 lockPtr = std::make_unique<std::mutex>();
764 }
765 }
766 }
767 }
768 }
769
777 template <class Functor>
778 std::tuple<Configuration, std::unique_ptr<TraversalInterface>, bool> selectConfiguration(
779 Functor &functor, const InteractionTypeOption &interactionType);
780
785 void setCurrentContainer(std::unique_ptr<ParticleContainerInterface<Particle_T>> newContainer);
786
801 template <class Functor>
802 IterationMeasurements computeInteractions(Functor &functor, TraversalInterface &traversal);
803
814 template <class Functor>
815 void computeRemainderInteractions(Functor &functor, bool newton3, bool useSoA);
816
822 void checkMinimalSize() const;
823
824 const LogicHandlerInfo _logicHandlerInfo;
828 unsigned int _neighborListRebuildFrequency;
829
833 unsigned int _verletClusterSize;
834
838 size_t _numRebuilds{0};
839
844 size_t _numRebuildsInNonTuningPhase{0};
845
849 size_t _aosSortingThreshold;
850
854 size_t _soaSortingThreshold;
855
856 std::shared_ptr<TuningManager> _tuningManager;
857
861 std::unique_ptr<ParticleContainerInterface<Particle_T>> _currentContainer{nullptr};
862
866 ContainerSelectorInfo _currentContainerSelectorInfo;
867
871 RemainderPairwiseInteractionHandler<Particle_T> _remainderPairwiseInteractionHandler;
872
876 RemainderTriwiseInteractionHandler<Particle_T> _remainderTriwiseInteractionHandler;
877
881 std::set<InteractionTypeOption> _interactionTypes{};
882
886 std::atomic<bool> _neighborListsAreValid{false};
887
891 size_t _stepsSinceLastListRebuild{0};
892
897 size_t _iteration{std::numeric_limits<size_t>::max()};
898
902 size_t _iterationAfterLastTuningPhase{0};
903
907 std::atomic<size_t> _numParticlesOwned{0ul};
908
912 std::atomic<size_t> _numParticlesHalo{0ul};
913
917 std::vector<FullParticleCell<Particle_T>> _particleBuffer;
918
922 std::vector<FullParticleCell<Particle_T>> _haloParticleBuffer;
923
929 std::vector<std::vector<std::vector<std::unique_ptr<std::mutex>>>> _spatialLocks;
930
934 IterationLogger _iterationLogger;
935
940 bool _neighborListInvalidDoDynamicRebuild{false};
941
945 void updateRebuildPositions();
946
950 LiveInfoLogger _liveInfoLogger;
951
955 FLOPLogger _flopLogger;
956};
957
958template <typename Particle_T>
960#ifdef AUTOPAS_ENABLE_DYNAMIC_CONTAINERS
961 // The owned particles in buffer are ignored because they do not rely on the structure of the particle containers,
962 // e.g. neighbour list, and these are iterated over using the region iterator. Movement of particles in buffer doesn't
963 // require a rebuild of neighbor lists.
964 AUTOPAS_OPENMP(parallel)
965 for (auto iter = this->begin(IteratorBehavior::owned | IteratorBehavior::containerOnly); iter.isValid(); ++iter) {
966 iter->resetRAtRebuild();
967 }
968#endif
969}
970
971template <typename Particle_T>
973 // check boxSize at least cutoff + skin
974 for (unsigned int dim = 0; dim < 3; ++dim) {
975 if (_currentContainer->getBoxMax()[dim] - _currentContainer->getBoxMin()[dim] <
976 _currentContainer->getInteractionLength()) {
978 "Box (boxMin[{}]={} and boxMax[{}]={}) is too small.\nHas to be at least cutoff({}) + skin({}) = {}.", dim,
979 _currentContainer->getBoxMin()[dim], dim, _currentContainer->getBoxMax()[dim], _currentContainer->getCutoff(),
980 _currentContainer->getVerletSkin(), _currentContainer->getCutoff() + _currentContainer->getVerletSkin());
981 }
982 }
983}
984
985template <typename Particle_T>
987 return _neighborListInvalidDoDynamicRebuild;
988}
989
990template <typename Particle_T>
992 if (_stepsSinceLastListRebuild >= _neighborListRebuildFrequency
993#ifdef AUTOPAS_ENABLE_DYNAMIC_CONTAINERS
994 or getNeighborListsInvalidDoDynamicRebuild()
995#endif
996 or _tuningManager->requiresRebuilding(_iteration)) {
997 _neighborListsAreValid.store(false, std::memory_order_relaxed);
998 }
999
1000 return _neighborListsAreValid.load(std::memory_order_relaxed);
1001}
1002
1003template <typename Particle_T>
1005#ifdef AUTOPAS_ENABLE_DYNAMIC_CONTAINERS
1006 const auto skin = getContainer().getVerletSkin();
1007 // (skin/2)^2
1008 const auto halfSkinSquare = skin * skin * 0.25;
1009 // The owned particles in buffer are ignored because they do not rely on the structure of the particle containers,
1010 // e.g. neighbour list, and these are iterated over using the region iterator. Movement of particles in buffer doesn't
1011 // require a rebuild of neighbor lists.
1012 AUTOPAS_OPENMP(parallel reduction(or : _neighborListInvalidDoDynamicRebuild))
1013 for (auto iter = this->begin(IteratorBehavior::owned | IteratorBehavior::containerOnly); iter.isValid(); ++iter) {
1014 const auto distance = iter->calculateDisplacementSinceRebuild();
1015 const double distanceSquare = utils::ArrayMath::dot(distance, distance);
1016
1017 _neighborListInvalidDoDynamicRebuild |= distanceSquare >= halfSkinSquare;
1018 }
1019#endif
1020}
1021
1022template <typename Particle_T>
1024 _neighborListInvalidDoDynamicRebuild = false;
1025}
1026
1027template <typename Particle_T>
1029 const std::vector<FullParticleCell<Particle_T>> &particleBuffers,
1030 const std::vector<FullParticleCell<Particle_T>> &haloParticleBuffers) {
1031 auto exchangeBuffer = [](const auto &newBuffers, auto &oldBuffers, auto &particleCounter) {
1032 // sanity check
1033 if (oldBuffers.size() < newBuffers.size()) {
1035 "The number of new buffers ({}) is larger than number of existing buffers ({})!", newBuffers.size(),
1036 oldBuffers.size());
1037 }
1038
1039 // we will clear the old buffers so subtract the particles from the counters.
1040 const auto numParticlesInOldBuffers =
1041 std::transform_reduce(oldBuffers.begin(), std::next(oldBuffers.begin(), newBuffers.size()), 0, std::plus<>(),
1042 [](const auto &cell) { return cell.size(); });
1043 particleCounter.fetch_sub(numParticlesInOldBuffers, std::memory_order_relaxed);
1044
1045 // clear the old buffers and copy the content of the new buffers over.
1046 size_t numParticlesInNewBuffers = 0;
1047 for (size_t i = 0; i < newBuffers.size(); ++i) {
1048 oldBuffers[i].clear();
1049 for (const auto &p : newBuffers[i]) {
1050 ++numParticlesInNewBuffers;
1051 oldBuffers[i].addParticle(p);
1052 }
1053 }
1054 // update the counters.
1055 particleCounter.fetch_add(numParticlesInNewBuffers, std::memory_order_relaxed);
1056 };
1057
1058 exchangeBuffer(particleBuffers, _particleBuffer, _numParticlesOwned);
1059 exchangeBuffer(haloParticleBuffers, _haloParticleBuffer, _numParticlesHalo);
1060}
1061
1062template <typename Particle_T>
1063std::tuple<const std::vector<FullParticleCell<Particle_T>> &, const std::vector<FullParticleCell<Particle_T>> &>
1065 return {_particleBuffer, _haloParticleBuffer};
1066}
1067
1068template <typename Particle_T>
1069template <class Functor>
1071 // Helper to derive the Functor type at compile time
1072 constexpr auto interactionType = [] {
1074 return InteractionTypeOption::pairwise;
1075 } else if (utils::isTriwiseFunctor<Functor>()) {
1076 return InteractionTypeOption::triwise;
1077 } else {
1079 "LogicHandler::computeInteractions(): Functor is not valid. Only pairwise and triwise functors are "
1080 "supported. "
1081 "Please use a functor derived from "
1082 "PairwiseFunctor or TriwiseFunctor.");
1083 }
1084 }();
1085
1086 auto &autoTuner = *_tuningManager->getAutoTuners()[interactionType];
1087 utils::Timer timerTotal;
1088 utils::Timer timerRebuild;
1089 utils::Timer timerComputeInteractions;
1090 utils::Timer timerComputeRemainder;
1091 long energyTotalRebuild;
1092
1093 const bool energyMeasurementsPossible = autoTuner.resetEnergy();
1094 timerTotal.start();
1095 timerRebuild.start();
1096 functor.initTraversal();
1097
1098 // if lists are not valid -> rebuild;
1099 if (not _neighborListsAreValid.load(std::memory_order_relaxed)) {
1100#ifdef AUTOPAS_ENABLE_DYNAMIC_CONTAINERS
1101 this->updateRebuildPositions();
1102#endif
1103 _currentContainer->rebuildNeighborLists(&traversal);
1104#ifdef AUTOPAS_ENABLE_DYNAMIC_CONTAINERS
1105 this->resetNeighborListsInvalidDoDynamicRebuild();
1106 _numRebuilds++;
1107 if (not autoTuner.inTuningPhase()) {
1108 _numRebuildsInNonTuningPhase++;
1109 }
1110#endif
1111 _neighborListsAreValid.store(true, std::memory_order_relaxed);
1112 }
1113 timerRebuild.stop();
1114 std::tie(std::ignore, std::ignore, std::ignore, energyTotalRebuild) = autoTuner.sampleEnergy();
1115
1116 // Balance buffer vectors
1117 const auto cellToVec = [](auto &cell) -> std::vector<Particle_T> & { return cell._particles; };
1118 utils::ArrayUtils::balanceVectors(_particleBuffer, cellToVec);
1119 utils::ArrayUtils::balanceVectors(_haloParticleBuffer, cellToVec);
1120
1121 // For InteractionListGeneratorFunctor or child classes thereof, initialize their neighbor
1122 if constexpr (std::is_base_of_v<InteractionListGeneratorFunctor<Particle_T, false>, Functor> or
1123 std::is_base_of_v<InteractionListGeneratorFunctor<Particle_T, true>, Functor>) {
1124 functor.initializeNeighborList(this->begin(IteratorBehavior::ownedOrHalo));
1125 }
1126
1127 timerComputeInteractions.start();
1128 _currentContainer->computeInteractions(&traversal);
1129 timerComputeInteractions.stop();
1130
1131 timerComputeRemainder.start();
1132 const bool newton3 = autoTuner.getCurrentConfig().newton3;
1133 const auto dataLayout = autoTuner.getCurrentConfig().dataLayout;
1134 computeRemainderInteractions(functor, newton3, dataLayout);
1135 timerComputeRemainder.stop();
1136
1137 functor.endTraversal(newton3);
1138
1139 const auto [energyWatts, energyJoules, energyDeltaT, energyTotal] = autoTuner.sampleEnergy();
1140 timerTotal.stop();
1141
1142 constexpr auto nanD = std::numeric_limits<double>::quiet_NaN();
1143 constexpr auto nanL = std::numeric_limits<long>::quiet_NaN();
1144 return {timerComputeInteractions.getTotalTime(),
1145 timerComputeRemainder.getTotalTime(),
1146 timerRebuild.getTotalTime(),
1147 timerTotal.getTotalTime(),
1148 energyMeasurementsPossible,
1149 energyMeasurementsPossible ? energyWatts : nanD,
1150 energyMeasurementsPossible ? energyJoules : nanD,
1151 energyMeasurementsPossible ? energyDeltaT : nanD,
1152 energyMeasurementsPossible ? energyTotalRebuild : nanL,
1153 energyMeasurementsPossible ? energyTotal - energyTotalRebuild
1154 : nanL, // ComputeInteractions + Remainder Traversal energy consumption
1155 energyMeasurementsPossible ? energyTotal : nanL};
1156}
1157
1158template <typename Particle_T>
1159template <class Functor>
1160void LogicHandler<Particle_T>::computeRemainderInteractions(Functor &functor, bool newton3, bool useSoA) {
1161 withStaticContainerType(*_currentContainer, [&](auto &actualContainerType) {
1162 if constexpr (utils::isPairwiseFunctor<Functor>()) {
1163 if (newton3) {
1164 _remainderPairwiseInteractionHandler.template computeRemainderInteractions<true>(
1165 &functor, actualContainerType, _particleBuffer, _haloParticleBuffer, useSoA);
1166 } else {
1167 _remainderPairwiseInteractionHandler.template computeRemainderInteractions<false>(
1168 &functor, actualContainerType, _particleBuffer, _haloParticleBuffer, useSoA);
1169 }
1170 } else if constexpr (utils::isTriwiseFunctor<Functor>()) {
1171 if (newton3) {
1172 _remainderTriwiseInteractionHandler.template computeRemainderInteractions<true>(
1173 &functor, actualContainerType, _particleBuffer, _haloParticleBuffer);
1174 } else {
1175 _remainderTriwiseInteractionHandler.template computeRemainderInteractions<false>(
1176 &functor, actualContainerType, _particleBuffer, _haloParticleBuffer);
1177 }
1178 }
1179 });
1180}
1181
1182template <typename Particle_T>
1183template <class Functor>
1184std::tuple<Configuration, std::unique_ptr<TraversalInterface>, bool> LogicHandler<Particle_T>::selectConfiguration(
1185 Functor &functor, const InteractionTypeOption &interactionType) {
1186 // Todo: Make LiveInfo persistent between multiple functor calls in the same timestep (e.g. 2B + 3B)
1187 // https://github.com/AutoPas/AutoPas/issues/916
1188 LiveInfo info{};
1189#ifdef AUTOPAS_LOG_LIVEINFO
1190 auto particleIter = this->begin(IteratorBehavior::ownedOrHalo);
1191 info.gather(particleIter, _neighborListRebuildFrequency, getNumberOfParticlesOwned(), _logicHandlerInfo.boxMin,
1192 _logicHandlerInfo.boxMax, _logicHandlerInfo.cutoff, _logicHandlerInfo.verletSkin);
1193 _liveInfoLogger.logLiveInfo(info, _iteration);
1194#endif
1195
1196 // if this iteration is not relevant, take the same algorithm config as before.
1197 if (not functor.isRelevantForTuning()) {
1198 auto configuration = _tuningManager->getCurrentConfig(interactionType);
1199 auto [traversalPtr, _] = isConfigurationApplicable(configuration, functor);
1200
1201 if (not traversalPtr) {
1202 // TODO: Can we handle this case gracefully?
1204 "LogicHandler: Functor {} is not relevant for tuning but the given configuration is not applicable!",
1205 functor.getName());
1206 }
1207 functor.setVecPattern(configuration.vecPattern);
1208 return {configuration, std::move(traversalPtr), false};
1209 }
1210
1211 if (_tuningManager->needsLiveInfo(_iteration)) {
1212 // If live info has not been gathered yet, gather it now and send it to the tuner.
1213 if (info.get().empty()) {
1214 auto particleIter = this->begin(IteratorBehavior::ownedOrHalo);
1215 info.gather(particleIter, _neighborListRebuildFrequency, getNumberOfParticlesOwned(), _logicHandlerInfo.boxMin,
1216 _logicHandlerInfo.boxMax, _logicHandlerInfo.cutoff, _logicHandlerInfo.verletSkin);
1217 }
1218 }
1219
1220 size_t numRejectedConfigs = 0;
1221 utils::TraceTimer selectConfigurationTimer;
1222 selectConfigurationTimer.start();
1223
1224 auto stillTuning = _tuningManager->tune(_iteration, info);
1225
1226 auto configuration = _tuningManager->getCurrentConfig(interactionType);
1227
1228 // loop as long as we don't get a valid configuration
1229 do {
1230 // applicability check also sets the container
1231 auto [traversalPtr, rejectIndefinitely] = isConfigurationApplicable(configuration, functor);
1232 if (traversalPtr) {
1233 functor.setVecPattern(configuration.vecPattern);
1234 selectConfigurationTimer.stop();
1235 AutoPasLog(TRACE, "Select Configuration took {} ms. A total of {} configurations were rejected.",
1236 selectConfigurationTimer.getTotalTime(), numRejectedConfigs);
1237 return {configuration, std::move(traversalPtr), stillTuning};
1238 }
1239 numRejectedConfigs++;
1240 // if no config is left after rejecting this one, an exception is thrown here.
1241 configuration = _tuningManager->rejectConfiguration(configuration, rejectIndefinitely, interactionType);
1242 } while (true);
1243}
1244
1245template <typename Particle_T>
1247 std::unique_ptr<ParticleContainerInterface<Particle_T>> newContainer) {
1248 // copy particles so they do not get lost when the container is switched
1249 if (_currentContainer != nullptr and newContainer != nullptr) {
1250 // with these assumptions slightly more space is reserved as numParticlesTotal already includes halos
1251 const auto numParticlesTotal = _currentContainer->size();
1252 const auto numParticlesHalo = utils::NumParticlesEstimator::estimateNumHalosUniform(
1253 numParticlesTotal, _currentContainer->getBoxMin(), _currentContainer->getBoxMax(),
1254 _currentContainer->getInteractionLength());
1255
1256 newContainer->reserve(numParticlesTotal, numParticlesHalo);
1257 for (auto particleIter = _currentContainer->begin(IteratorBehavior::ownedOrHalo); particleIter.isValid();
1258 ++particleIter) {
1259 // add a particle as inner if it is owned
1260 if (particleIter->isOwned()) {
1261 newContainer->addParticle(*particleIter);
1262 } else {
1263 newContainer->addHaloParticle(*particleIter);
1264 }
1265 }
1266 }
1267
1268 _currentContainer = std::move(newContainer);
1269}
1270
1271template <typename Particle_T>
1272template <class Functor>
1274 const InteractionTypeOption &interactionType) {
1275 if (not _interactionTypes.contains(interactionType)) {
1277 "LogicHandler::computeInteractionsPipeline(): AutPas was not initialized for the Functor's interactions type: "
1278 "{}.",
1279 interactionType);
1280 }
1282 utils::Timer tuningTimer;
1283 tuningTimer.start();
1284 const auto [configuration, traversalPtr, stillTuning] = selectConfiguration(*functor, interactionType);
1285 tuningTimer.stop();
1286 _tuningManager->logTuningResult(tuningTimer.getTotalTime(), _iteration, interactionType);
1287
1288 // Retrieve rebuild info before calling `computeInteractions()` to get the correct value.
1289 const auto rebuildIteration = not _neighborListsAreValid.load(std::memory_order_relaxed);
1290
1292 AutoPasLog(DEBUG, "Iterating with configuration: {} tuning: {}", configuration.toString(), stillTuning);
1293 const IterationMeasurements measurements = computeInteractions(*functor, *traversalPtr);
1294
1296 auto bufferSizeListing = [](const auto &buffers) -> std::string {
1297 std::stringstream ss;
1298 size_t sum = 0;
1299 for (const auto &buffer : buffers) {
1300 ss << buffer.size() << ", ";
1301 sum += buffer.size();
1302 }
1303 ss << " Total: " << sum;
1304 return ss.str();
1305 };
1306 AutoPasLog(TRACE, "particleBuffer size : {}", bufferSizeListing(_particleBuffer));
1307 AutoPasLog(TRACE, "haloParticleBuffer size : {}", bufferSizeListing(_haloParticleBuffer));
1308 AutoPasLog(DEBUG, "Type of interaction : {}", interactionType.to_string());
1309 AutoPasLog(DEBUG, "Container::computeInteractions took {} ns", measurements.timeComputeInteractions);
1310 AutoPasLog(DEBUG, "RemainderTraversal took {} ns", measurements.timeRemainderTraversal);
1311 AutoPasLog(DEBUG, "RebuildNeighborLists took {} ns", measurements.timeRebuild);
1312 AutoPasLog(DEBUG, "AutoPas::computeInteractions took {} ns", measurements.timeTotal);
1313 if (measurements.energyMeasurementsPossible) {
1314 AutoPasLog(DEBUG, "Energy Consumption: Watts: {} Joules: {} Seconds: {}", measurements.energyWatts,
1315 measurements.energyJoules, measurements.energyDeltaT);
1316 }
1317 _iterationLogger.logIteration(configuration, _iteration, functor->getName(), stillTuning, tuningTimer.getTotalTime(),
1318 measurements);
1319
1320 _flopLogger.logIteration(_iteration, functor->getNumFLOPs(), functor->getHitRate());
1321
1323 // if this was a major iteration add measurements
1324 if (functor->isRelevantForTuning()) {
1325 if (stillTuning) {
1326 // choose the metric of interest
1327 const auto measurement = [&]() {
1328 switch (_tuningManager->getTuningMetric(interactionType)) {
1330 return std::make_pair(measurements.timeRebuild,
1331 measurements.timeComputeInteractions + measurements.timeRemainderTraversal);
1333 return std::make_pair(measurements.energyTotalRebuild, measurements.energyTotalNonRebuild);
1334 default:
1335 utils::ExceptionHandler::exception("LogicHandler::computeInteractionsPipeline(): Unknown tuning metric.");
1336 return std::make_pair(0l, 0l);
1337 }
1338 }();
1339 _tuningManager->addMeasurement(measurement.first, measurement.second, rebuildIteration, _iteration,
1340 interactionType);
1341 }
1342 } else {
1343 AutoPasLog(TRACE, "Skipping adding of sample because functor is not marked relevant.");
1344 }
1345 return stillTuning;
1346}
1347
1348template <typename Particle_T>
1349template <class Functor>
1350std::tuple<std::unique_ptr<TraversalInterface>, bool> LogicHandler<Particle_T>::isConfigurationApplicable(
1351 const Configuration &config, Functor &functor) {
1352 // Check if the configuration is compatible, independent of domain or functor
1353 if (not config.hasCompatibleValues()) {
1354 AutoPasLog(
1355 WARN,
1356 "A configuration was rejected by LogicHandler::isConfigurationApplicable, as it was incompatible"
1357 " independently of domain or functor. This should not occur and implies illegal configurations are being added"
1358 " to the configuration queue during simulation (potentially by a tuning strategy).");
1359 AutoPasLog(WARN, "Configuration rejected: {}", config.toString());
1360 // Such illegal configurations should be filtered out in the generation of the search space.
1361 return {nullptr, /*rejectIndefinitely*/ true};
1362 }
1363
1364 // Check if the functor supports the required Newton 3 mode
1365 if ((config.newton3 == Newton3Option::enabled and not functor.allowsNewton3()) or
1366 (config.newton3 == Newton3Option::disabled and not functor.allowsNonNewton3())) {
1367 AutoPasLog(DEBUG, "Configuration rejected: The functor doesn't support Newton 3 {}!", config.newton3);
1368 return {nullptr, /*rejectIndefinitely*/ true};
1369 }
1370
1371 // Check if the VectorizationPattern is supported by the functor
1372 if (not functor.isVecPatternAllowed(config.vecPattern)) {
1373 AutoPasLog(DEBUG, "Configuration rejected: The functor doesn't support the Vectorization Pattern {}!",
1374 config.vecPattern);
1375 return {nullptr, /*rejectIndefinitely*/ true};
1376 }
1377
1378 std::unique_ptr<ParticleContainerInterface<Particle_T>> containerPtr{nullptr};
1379 auto containerInfo =
1380 ContainerSelectorInfo(_currentContainer->getBoxMin(), _currentContainer->getBoxMax(),
1381 _currentContainer->getCutoff(), config.cellSizeFactor, _currentContainer->getVerletSkin(),
1382 _verletClusterSize, _aosSortingThreshold, _soaSortingThreshold, config.loadEstimator);
1383
1384 // If we have no current container or needs to be updated to the new config.container, we need to generate a new
1385 // container.
1386 const bool generateNewContainer = _currentContainer == nullptr or
1387 _currentContainer->getContainerType() != config.container or
1388 containerInfo != _currentContainerSelectorInfo;
1389
1390 if (generateNewContainer) {
1391 // For now, set the local containerPtr to the new container. We do not copy the particles over and set the member
1392 // _currentContainer until after we know that the traversal is applicable to the domain.
1393 containerPtr = ContainerSelector<Particle_T>::generateContainer(config.container, containerInfo);
1394 }
1395
1396 const auto traversalInfo =
1397 generateNewContainer ? containerPtr->getTraversalSelectorInfo() : _currentContainer->getTraversalSelectorInfo();
1398
1399 // Generates a traversal if applicable to domain, otherwise returns a nullptr
1400 auto traversalPtr =
1401 TraversalSelector::generateTraversalFromConfig<Particle_T, Functor>(config, functor, traversalInfo);
1402
1403 // If the traversal is applicable to the domain, and the configuration requires generating a new container,
1404 // update the member _currentContainer with setCurrentContainer, copying the particle data over, and update
1405 // _currentContainerSelectorInfo.
1406 if (traversalPtr and generateNewContainer) {
1407 _currentContainerSelectorInfo = containerInfo;
1408 setCurrentContainer(std::move(containerPtr));
1409 }
1410
1411 return {std::move(traversalPtr), /*rejectIndefinitely*/ false};
1412}
1413
1414} // namespace autopas
#define AutoPasLog(lvl, fmt,...)
Macro for logging providing common meta information without filename.
Definition: Logger.h:24
#define AUTOPAS_OPENMP(args)
Empty macro to throw away any arguments.
Definition: WrapOpenMP.h:126
Class containing multiple options that form an algorithm configuration for the pairwise iteration.
Definition: Configuration.h:26
std::string toString() const
Returns string representation in JSON style of the configuration object.
Definition: Configuration.cpp:12
LoadEstimatorOption loadEstimator
Load Estimator option.
Definition: Configuration.h:146
double cellSizeFactor
CellSizeFactor.
Definition: Configuration.h:158
ContainerOption container
Container option.
Definition: Configuration.h:134
Newton3Option newton3
Newton 3 option.
Definition: Configuration.h:154
VectorizationPatternOption vecPattern
Vectorization Pattern option.
Definition: Configuration.h:142
bool hasCompatibleValues() const
Checks if any of the configuration values are incompatible with each other.
Definition: Configuration.cpp:53
Public iterator class that iterates over a particle container and additional vectors (which are typic...
Definition: ContainerIterator.h:95
Info to generate a container.
Definition: ContainerSelectorInfo.h:17
std::array< double, 3 > boxMin
Lower corner of the container.
Definition: ContainerSelectorInfo.h:97
std::array< double, 3 > boxMax
Upper corner of the container.
Definition: ContainerSelectorInfo.h:102
static std::unique_ptr< ParticleContainerInterface< Particle_T > > generateContainer(ContainerOption containerChoice, const ContainerSelectorInfo &containerInfo)
Container factory method.
Definition: ContainerSelector.h:44
Helper to log FLOP count and HitRate for AutoPas::iteratePairwise() calls with the functors in the mo...
Definition: FLOPLogger.h:30
This class handles the storage of particles in their full form.
Definition: FullParticleCell.h:26
Functor base class.
Definition: Functor.h:41
virtual size_t getNumFLOPs() const
Get the number of FLOPs.
Definition: Functor.h:206
virtual bool isVecPatternAllowed(const VectorizationPatternOption::Value vecPattern)=0
Specifies whether the functor is capable of using the specified Vectorization Pattern in the SoA func...
virtual bool allowsNewton3()=0
Specifies whether the functor is capable of Newton3-like functors.
virtual void setVecPattern(const VectorizationPatternOption::Value vecPattern)
Setter for the vectorization pattern to be used.
Definition: Functor.h:197
virtual void initTraversal()
This function is called at the start of each traversal.
Definition: Functor.h:64
virtual bool allowsNonNewton3()=0
Specifies whether the functor is capable of non-Newton3-like functors.
virtual void endTraversal(bool newton3)
This function is called at the end of each traversal.
Definition: Functor.h:71
virtual bool isRelevantForTuning()=0
Specifies whether the functor should be considered for the auto-tuning process.
virtual std::string getName()=0
Returns name of functor.
virtual double getHitRate() const
Get the hit rate.
Definition: Functor.h:216
Helper to log performance data of AutoPas::computeInteractions() to a csv file for easier analysis.
Definition: IterationLogger.h:24
Helper to log the collected LiveInfo data during tuning to a csv file for easier analysis.
Definition: LiveInfoLogger.h:23
This class is able to gather and store important information for a tuning phase from a container and ...
Definition: LiveInfo.h:33
Class that wraps all arguments for the logic handler to provide a more stable API.
Definition: LogicHandlerInfo.h:16
double verletSkin
Length added to the cutoff for the Verlet lists' skin.
Definition: LogicHandlerInfo.h:33
std::array< double, 3 > boxMax
Upper corner of the container without halo.
Definition: LogicHandlerInfo.h:25
double deltaT
Time step used in the simulation.
Definition: LogicHandlerInfo.h:52
double cutoff
Cutoff radius to be used in this simulation.
Definition: LogicHandlerInfo.h:29
std::array< double, 3 > boxMin
Lower corner of the container without halo.
Definition: LogicHandlerInfo.h:21
The LogicHandler takes care of the containers s.t.
Definition: LogicHandler.h:51
void setParticleBuffers(const std::vector< FullParticleCell< Particle_T > > &particleBuffers, const std::vector< FullParticleCell< Particle_T > > &haloParticleBuffers)
Directly exchange the internal particle and halo buffers with the given vectors and update particle c...
Definition: LogicHandler.h:1028
void reserve(size_t numParticles, size_t numHaloParticles)
Reserves space in the particle buffers and the container.
Definition: LogicHandler.h:318
std::tuple< std::unique_ptr< TraversalInterface >, bool > isConfigurationApplicable(const Configuration &config, Functor &functor)
Checks if the given configuration can be used with the given functor and the current state of the sim...
Definition: LogicHandler.h:1350
ContainerIterator< Particle_T, true, false > begin(IteratorBehavior behavior)
Iterate over all particles by using for(auto iter = autoPas.begin(); iter.isValid(); ++iter)
Definition: LogicHandler.h:500
std::vector< Particle_T > updateContainer()
Updates the container.
Definition: LogicHandler.h:164
unsigned long getNumberOfParticlesOwned() const
Get the number of owned particles.
Definition: LogicHandler.h:563
bool computeInteractionsPipeline(Functor *functor, const InteractionTypeOption &interactionType)
This function covers the full pipeline of all mechanics happening during the computation of particle ...
Definition: LogicHandler.h:1273
std::tuple< const std::vector< FullParticleCell< Particle_T > > &, const std::vector< FullParticleCell< Particle_T > > & > getParticleBuffers() const
Getter for the particle buffers.
Definition: LogicHandler.h:1064
void addParticle(const Particle_T &p)
Adds a particle to the container.
Definition: LogicHandler.h:338
void decreaseParticleCounter(Particle_T &particle)
Decrease the correct internal particle counters.
Definition: LogicHandler.h:433
std::vector< Particle_T > collectLeavingParticlesFromBuffer(bool insertOwnedParticlesToContainer)
Collects leaving particles from buffer and potentially inserts owned particles to the container.
Definition: LogicHandler.h:111
bool neighborListsAreValid()
Checks if in the next iteration the neighbor lists have to be rebuilt.
Definition: LogicHandler.h:991
unsigned long getNumberOfParticlesHalo() const
Get the number of halo particles.
Definition: LogicHandler.h:569
std::tuple< bool, bool > deleteParticleFromBuffers(Particle_T &particle)
Takes a particle, checks if it is in any of the particle buffers, and deletes it from them if found.
Definition: LogicHandler.h:411
LogicHandler(const std::shared_ptr< TuningManager > &tunerManager, const LogicHandlerInfo &logicHandlerInfo, unsigned int rebuildFrequency, const std::string &outputSuffix)
Constructor of the LogicHandler.
Definition: LogicHandler.h:60
double getVelocityMethodRFEstimate(const double skin, const double deltaT) const
Estimates the rebuild frequency based on the current maximum velocity in the container Using the form...
Definition: LogicHandler.h:655
void checkNeighborListsInvalidDoDynamicRebuild()
Checks if any particle has moved more than skin/2.
Definition: LogicHandler.h:1004
Iterator::ParticleVecType gatherAdditionalVectors(IteratorBehavior behavior)
Create the additional vectors vector for a given iterator behavior.
Definition: LogicHandler.h:471
ParticleContainerInterface< Particle_T > & getContainer()
Returns a non-const reference to the currently selected particle container.
Definition: LogicHandler.h:104
void addHaloParticle(const Particle_T &haloParticle)
Adds a particle to the container that lies in the halo region of the container.
Definition: LogicHandler.h:365
ContainerIterator< Particle_T, false, true > getRegionIterator(const std::array< double, 3 > &lowerCorner, const std::array< double, 3 > &higherCorner, IteratorBehavior behavior) const
Iterate over all particles in a specified region.
Definition: LogicHandler.h:539
void deleteAllParticles()
Deletes all particles.
Definition: LogicHandler.h:395
ContainerIterator< Particle_T, false, false > begin(IteratorBehavior behavior) const
Iterate over all particles by using for(auto iter = autoPas.begin(); iter.isValid(); ++iter)
Definition: LogicHandler.h:508
bool getNeighborListsInvalidDoDynamicRebuild()
getter function for _neighborListInvalidDoDynamicRebuild
Definition: LogicHandler.h:986
void resetNeighborListsInvalidDoDynamicRebuild()
Checks if any particle has moved more than skin/2.
Definition: LogicHandler.h:1023
double getMeanRebuildFrequency(bool considerOnlyLastNonTuningPhase=false) const
Getter for the mean rebuild frequency.
Definition: LogicHandler.h:632
std::vector< Particle_T > resizeBox(const std::array< double, 3 > &boxMin, const std::array< double, 3 > &boxMax)
Pass values to the actual container.
Definition: LogicHandler.h:225
void reserve(size_t numParticles)
Estimates the number of halo particles via autopas::utils::NumParticlesEstimator::estimateNumHalosUni...
Definition: LogicHandler.h:305
ContainerIterator< Particle_T, true, true > getRegionIterator(const std::array< double, 3 > &lowerCorner, const std::array< double, 3 > &higherCorner, IteratorBehavior behavior)
Iterate over all particles in a specified region.
Definition: LogicHandler.h:518
The ParticleContainerInterface class provides a basic interface for all Containers within AutoPas.
Definition: ParticleContainerInterface.h:38
Handles pairwise interactions involving particle buffers (particles not yet inserted into the main co...
Definition: RemainderPairwiseInteractionHandler.h:31
Handles triwise interactions involving particle buffers (particles not yet inserted into the main con...
Definition: RemainderTriwiseInteractionHandler.h:30
This interface serves as a common parent class for all traversals.
Definition: TraversalInterface.h:18
@ energy
Optimize for least energy usage.
Definition: TuningMetricOption.h:31
@ time
Optimize for shortest simulation time.
Definition: TuningMetricOption.h:27
static void exception(const Exception e)
Handle an exception derived by std::exception.
Definition: ExceptionHandler.h:64
Timer class to stop times.
Definition: Timer.h:27
void start()
start the timer.
Definition: Timer.cpp:17
long getTotalTime() const
Get total accumulated time.
Definition: Timer.h:60
long stop()
Stops the timer and returns the time elapsed in nanoseconds since the last call to start.
Definition: Timer.cpp:25
A wrapper around autopas::utils::Timer that only compiles implementation logic if the SPDLOG_ACTIVE_L...
Definition: TraceTimer.h:20
long getTotalTime() const
Get total accumulated time.
Definition: TraceTimer.h:63
void start()
start the timer.
Definition: TraceTimer.h:25
long stop()
Stops the timer and returns the time elapsed in nanoseconds since the last call to start.
Definition: TraceTimer.h:34
void markParticleAsDeleted(Particle_T &p)
Marks a particle as deleted.
Definition: markParticleAsDeleted.h:23
constexpr T dot(const std::array< T, SIZE > &a, const std::array< T, SIZE > &b)
Generates the dot product of two arrays.
Definition: ArrayMath.h:233
constexpr std::array< T, SIZE > ceil(const std::array< T, SIZE > &a)
For each element in a, computes the smallest integer value not less than the element.
Definition: ArrayMath.h:316
void balanceVectors(OuterContainerT &vecvec)
Given a collection of vectors, redistributes the elements of the vectors so they all have the same (o...
Definition: ArrayUtils.h:151
constexpr std::array< output_t, SIZE > static_cast_copy_array(const std::array< input_t, SIZE > &a)
Creates a new array by performing an element-wise static_cast<>.
Definition: ArrayUtils.h:33
void to_string(std::ostream &os, const Container &container, const std::string &delimiter, const std::array< std::string, 2 > &surround, Fun elemToString)
Generates a string representation of a container which fulfills the Container requirement (provide cb...
Definition: ArrayUtils.h:54
size_t estimateNumHalosUniform(size_t numParticles, const std::array< double, 3 > &boxMin, const std::array< double, 3 > &boxMax, double haloWidth)
Given a number of particles and the dimensions of a box, estimate the number of halo particles.
Definition: NumParticlesEstimator.cpp:9
decltype(isTriwiseFunctorImpl(std::declval< FunctorT >())) isTriwiseFunctor
Check whether a Functor Type is inheriting from TriwiseFunctor.
Definition: checkFunctorType.h:56
bool notInBox(const std::array< T, 3 > &position, const std::array< T, 3 > &low, const std::array< T, 3 > &high)
Checks if position is not inside of a box defined by low and high.
Definition: inBox.h:50
decltype(isPairwiseFunctorImpl(std::declval< FunctorT >())) isPairwiseFunctor
Check whether a Functor Type is inheriting from PairwiseFunctor.
Definition: checkFunctorType.h:49
bool inBox(const std::array< T, 3 > &position, const std::array< T, 3 > &low, const std::array< T, 3 > &high)
Checks if position is inside of a box defined by low and high.
Definition: inBox.h:26
This is the main namespace of AutoPas.
Definition: AutoPasDecl.h:34
int autopas_get_max_threads()
Dummy for omp_get_max_threads() when no OpenMP is available.
Definition: WrapOpenMP.h:144
@ halo
Halo state, a particle with this state is an actual particle, but not owned by the current AutoPas ob...
@ owned
Owned state, a particle with this state is an actual particle and owned by the current AutoPas object...
decltype(auto) withStaticContainerType(ParticleContainerInterface< Particle_T > &container, FunctionType &&function)
Will execute the passed function body with the static container type of container.
Definition: StaticContainerSelector.h:35
int autopas_get_thread_num()
Dummy for omp_set_lock() when no OpenMP is available.
Definition: WrapOpenMP.h:132
Struct to collect all sorts of measurements taken during a computeInteractions iteration.
Definition: IterationMeasurements.h:13
double energyWatts
Average energy consumed per time in Watts.
Definition: IterationMeasurements.h:42
double energyDeltaT
Time in seconds during which energy was consumed.
Definition: IterationMeasurements.h:52
long timeRebuild
Time it takes for rebuilding neighbor lists.
Definition: IterationMeasurements.h:27
long timeTotal
Time it takes for the complete iteratePairwise pipeline.
Definition: IterationMeasurements.h:32
long energyTotalRebuild
Total energy consumed during rebuilding.
Definition: IterationMeasurements.h:57
long timeRemainderTraversal
Time it takes for the Remainder Traversal.
Definition: IterationMeasurements.h:22
long energyTotalNonRebuild
Total energy consumed during compute interactions and remainder traversal.
Definition: IterationMeasurements.h:62
long timeComputeInteractions
Time it takes for the LogicHandler's computeInteractions() function.
Definition: IterationMeasurements.h:17
bool energyMeasurementsPossible
Bool whether energy measurements are currently possible.
Definition: IterationMeasurements.h:37
double energyJoules
Total energy consumed in Joules.
Definition: IterationMeasurements.h:47