AutoPas  3.0.0
Loading...
Searching...
No Matches
LiveInfo.h
Go to the documentation of this file.
1
7#pragma once
8
9#include <algorithm>
10#include <cmath>
11#include <cstddef>
12#include <limits>
13#include <variant>
14
24#include "autopas/utils/Timer.h"
26
27namespace autopas {
28
33class LiveInfo {
34 // The class currently needs to be defined in a header only since iteration over a particle container requires to
35 // know the Particle type. Actually, no particle specific information can be used here, so only a pointer to
36 // ParticleBase would suffice, but iteration doesn't work that way at the moment.
37
38 private:
49 static utils::ParticleBinStructure buildCellBinStructure(const std::array<double, 3> &domainSize,
50 const double interactionLength,
51 const std::array<double, 3> &boxMin,
52 const std::array<double, 3> &boxMax, double cutoff) {
53 std::array<size_t, 3> cellsPerDim{};
54 std::array<double, 3> cellLength{};
55
56 for (int d = 0; d < 3; ++d) {
57 // The number of cells is rounded down because the cells will be stretched to fit.
58 // std::max to ensure there is at least one cell.
59 cellsPerDim[d] = std::max(static_cast<size_t>(std::floor(domainSize[d] / interactionLength)), 1ul);
60 cellLength[d] = domainSize[d] / static_cast<double>(cellsPerDim[d]);
61 }
62
63 return {cellsPerDim, cellLength, boxMin, boxMax, cutoff};
64 }
65
79 static utils::ParticleBinStructure buildParticleDependentBinStructure(const std::array<double, 3> &domainSize,
80 const size_t numParticles,
81 const std::array<double, 3> &boxMin,
82 const std::array<double, 3> &boxMax,
83 double cutoff) {
84 using namespace autopas::utils::ArrayMath::literals;
85
86 const auto targetNumberOfBins = std::max(std::ceil(static_cast<double>(numParticles) / 10.), 1.);
87 const auto targetNumberOfBinsPerDim = std::cbrt(targetNumberOfBins);
88 // This is probably not an integer, so we floor to get more than 10 particles per bin
89 const auto numberOfBinsPerDim = static_cast<size_t>(std::floor(targetNumberOfBinsPerDim));
90 const auto binDimensions = domainSize / static_cast<double>(numberOfBinsPerDim);
91
92 return {numberOfBinsPerDim, binDimensions, boxMin, boxMax, cutoff};
93 }
94
104 static utils::ParticleBinStructure buildBlurredBinStructure(const std::array<double, 3> &domainSize,
105 const std::array<double, 3> &boxMin,
106 const std::array<double, 3> &boxMax, double cutoff) {
107 using namespace autopas::utils::ArrayMath::literals;
108
109 const auto binLength = domainSize / 3.;
110
111 return {3, binLength, boxMin, boxMax, cutoff};
112 }
113
114 public:
118 using InfoType = std::variant<bool, double, size_t, ContainerOption, TraversalOption, LoadEstimatorOption,
119 DataLayoutOption, Newton3Option>;
120
188 template <class Particle_T>
189 void gather(ContainerIterator<Particle_T, true, false> particleIter, size_t rebuildFrequency,
190 size_t numOwnedParticles, std::array<double, 3> boxMin, std::array<double, 3> boxMax, double cutoff,
191 double skin) {
192 using namespace utils::ArrayMath::literals;
194
195 // Timer for debugging
196 utils::Timer timerGatherLiveInfo;
197 timerGatherLiveInfo.start();
198
199 // Aliases and info of particle distribution independent information
200 const auto interactionLength = cutoff + skin;
201
202 infos["cutoff"] = cutoff;
203 infos["skin"] = skin;
204 infos["rebuildFrequency"] = rebuildFrequency;
205 infos["particleSize"] = sizeof(Particle_T);
206 infos["threadCount"] = static_cast<size_t>(autopas_get_max_threads());
207
208 infos["numOwnedParticles"] = numOwnedParticles;
209
210 const auto domainSize = boxMax - boxMin;
211 infos["domainSizeX"] = domainSize[0];
212 infos["domainSizeY"] = domainSize[1];
213 infos["domainSizeZ"] = domainSize[2];
214
215 // Build bin structures
216 auto cellBinStruct = buildCellBinStructure(domainSize, interactionLength, boxMin, boxMax, cutoff);
217 auto particleDependentBinStruct =
218 buildParticleDependentBinStructure(domainSize, numOwnedParticles, boxMin, boxMax, cutoff);
219 auto blurredBinStruct = buildBlurredBinStructure(domainSize, boxMin, boxMax, cutoff);
220
221 infos["numCells"] = cellBinStruct.getNumberOfBins();
222
223 // Count the number of owned particles per bin for each bin structure. Also include total count for halo particles.
224 size_t numOwnedParticlesCount = 0;
225 size_t numHaloParticlesCount = 0;
226 for (; particleIter.isValid(); ++particleIter) {
227 if (particleIter->isOwned()) {
228 numOwnedParticlesCount++;
229 const auto particlePos = particleIter->getR();
230 if (utils::inBox(particlePos, boxMin, boxMax)) {
231 cellBinStruct.countParticle(particlePos);
232 particleDependentBinStruct.countParticle(particlePos);
233 blurredBinStruct.countParticle(particlePos);
234 }
235 } else if (particleIter->isHalo()) {
236 numHaloParticlesCount++;
237 }
238 }
239
240 // Sanity Check
241 if (numOwnedParticlesCount != numOwnedParticles) {
242 AutoPasLog(ERROR,
243 "Number of owned particles tracked by AutoPas ({}) does not match number of owned particles "
244 "counted using the iterator ({}).",
245 numOwnedParticles, numOwnedParticlesCount);
246 }
247
248 infos["numOwnedParticles"] = numOwnedParticlesCount;
249 infos["numHaloParticles"] = numHaloParticlesCount;
250
251 // calculate statistics
252 cellBinStruct.calculateStatistics();
253 particleDependentBinStruct.calculateStatistics();
254 blurredBinStruct.calculateStatistics();
255
256 // write cellBinStruct statistics to live info
257 infos["numEmptyCells"] = cellBinStruct.getNumEmptyBins();
258 infos["maxParticlesPerCell"] = cellBinStruct.getMaxParticlesPerBin();
259 infos["minParticlesPerCell"] = cellBinStruct.getMinParticlesPerBin();
260 infos["medianParticlesPerCell"] = cellBinStruct.getMedianParticlesPerBin();
261 infos["lowerQuartileParticlesPerCell"] = cellBinStruct.getLowerQuartileParticlesPerBin();
262 infos["upperQuartileParticlesPerCell"] = cellBinStruct.getUpperQuartileParticlesPerBin();
263 infos["meanParticlesPerCell"] = cellBinStruct.getMeanParticlesPerBin();
264 infos["relativeParticlesPerCellStdDev"] = cellBinStruct.getRelStdDevParticlesPerBin();
265 infos["particlesPerCellStdDev"] = cellBinStruct.getStdDevParticlesPerBin();
266 infos["estimatedNumNeighborInteractions"] = cellBinStruct.getEstimatedNumberOfNeighborInteractions();
267
268 // write particle dependent bin statistics to live info
269 infos["particleDependentBinMaxDensity"] = particleDependentBinStruct.getMaxDensity();
270 infos["particleDependentBinDensityStdDev"] = particleDependentBinStruct.getStdDevDensity();
271
272 // write blurred bin statistics to live info
273 infos["maxParticlesPerBlurredBin"] = blurredBinStruct.getMaxParticlesPerBin();
274 infos["minParticlesPerBlurredBin"] = blurredBinStruct.getMinParticlesPerBin();
275 infos["medianParticlesPerBlurredBin"] = blurredBinStruct.getMedianParticlesPerBin();
276 infos["lowerQuartileParticlesPerBlurredBin"] = blurredBinStruct.getLowerQuartileParticlesPerBin();
277 infos["upperQuartileParticlesPerBlurredBin"] = blurredBinStruct.getUpperQuartileParticlesPerBin();
278 infos["meanParticlesPerBlurredBin"] = blurredBinStruct.getMeanParticlesPerBin();
279 infos["relativeParticlesPerBlurredBinStdDev"] = blurredBinStruct.getRelStdDevParticlesPerBin();
280 infos["particlesPerBlurredBinStdDev"] = blurredBinStruct.getStdDevParticlesPerBin();
281
282 timerGatherLiveInfo.stop();
283 AutoPasLog(DEBUG, "Gathering of LiveInfo took {} ns.", timerGatherLiveInfo.getTotalTime());
284 }
285
290 [[nodiscard]] const auto &get() const { return infos; }
291
298 template <typename T>
299 T get(const std::string &key) const {
300 // Find the key in the map
301 const auto it = infos.find(key);
302
303 // If key is not found, log an error
304 if (it == infos.end()) {
305 AutoPasLog(ERROR, "Key '" + key + "' not found in infos map.");
306 }
307
308 // Use std::get<T> to extract the value of the desired type
309 try {
310 return std::get<T>(it->second);
311 } catch (const std::bad_variant_access &e) {
312 AutoPasLog(ERROR, "Type mismatch for key '" + key + "'. Requested type does not match the stored type.");
313 }
314 }
315
320 [[nodiscard]] std::string toString() const {
321 auto typeToString = [](auto type) {
322 if constexpr (std::is_same_v<decltype(type), bool> or std::is_same_v<decltype(type), double> or
323 std::is_same_v<decltype(type), size_t>) {
324 return std::to_string(type);
325 } else if constexpr (std::is_base_of_v<Option<decltype(type)>, decltype(type)>) {
326 return type.to_string();
327 }
328 return std::string{"fail"};
329 };
330 auto pairToString = [&](const auto &pair) { return pair.first + "=" + std::visit(typeToString, pair.second); };
331 std::string res{"Live Info: "};
332 if (not infos.empty()) {
333 // We initialize the accumulation with the first element. Hence, the accumulation starts at next(begin).
334 res += std::accumulate(std::next(infos.begin()), infos.end(), pairToString(*infos.begin()),
335 [&](std::string s, const auto &elem) { return std::move(s) + " " + pairToString(elem); });
336 }
337 return res;
338 }
339
346 friend std::ostream &operator<<(std::ostream &out, const LiveInfo &info) {
347 out << info.infos.size() << ' ';
348 for (const auto &[name, val] : info.infos) {
349 // val.index here is the index of this value's type in the LiveInfo::InfoType variant type.
350 // This is needed for determining the type when reading this file via readIndex.
351 out << name << ' ' << val.index() << ' ';
352 std::visit([&](const auto &v) { out << v << ' '; }, val);
353 }
354 return out;
355 }
356
363 friend std::istream &operator>>(std::istream &in, LiveInfo &info) {
364 size_t numElements{0};
365 in >> numElements;
366 for (size_t i = 0; i < numElements; i++) {
367 std::string name;
368 in >> name;
369 size_t idx{0};
370 in >> idx;
371 const auto val =
372 readIndex<LiveInfo::InfoType>(in, idx, std::make_index_sequence<std::variant_size_v<LiveInfo::InfoType>>());
373 info.infos[name] = val;
374 }
375 return in;
376 }
377
383 [[nodiscard]] std::pair<std::string, std::string> getCSVLine() const {
384 // match all words (anything that is neither a ' ' or '='), that are followed by a '=',
385 // ignoring the 'Live Info: ' prefix
386 const auto keyRegex = std::regex("([^= ]+)=[^ ]*");
387 // match all words that are preceded by a '='
388 const auto valueRegex = std::regex("=([^ ]+)");
389
390 auto searchString = toString();
391 // remove leading Live Info:
392 searchString = searchString.substr(std::string("Live Info: ").size());
393
394 std::sregex_iterator keyIter(searchString.begin(), searchString.end(), keyRegex);
395 std::sregex_iterator valueIter(searchString.begin(), searchString.end(), valueRegex);
396 std::sregex_iterator end;
397
398 std::stringstream header;
399 std::stringstream line;
400
401 while (keyIter != end) {
402 // first submatch is the match of the capture group
403 header << keyIter->str(1) << ",";
404 ++keyIter;
405 }
406 while (valueIter != end) {
407 // first submatch is the match of the capture group
408 line << valueIter->str(1) << ",";
409 ++valueIter;
410 }
411
412 auto headerStr = header.str();
413 auto lineStr = line.str();
414 // drop trailing ','
415 headerStr.pop_back();
416 lineStr.pop_back();
417
418 return std::make_pair(headerStr, lineStr);
419 }
420
421 private:
432 template <class Variant, class Type, size_t Idx>
433 static void readIndexHelper(std::istream &in, size_t idx, Variant &var) {
434 if (Idx == idx) {
435 Type val;
436 in >> val;
437 var = val;
438 }
439 }
440
449 template <class Variant, size_t... Idx>
450 static Variant readIndex(std::istream &in, size_t idx, std::index_sequence<Idx...>) {
451 Variant var;
452 (readIndexHelper<Variant, std::variant_alternative_t<Idx, Variant>, Idx>(in, idx, var), ...);
453 return var;
454 }
455
459 std::map<std::string, InfoType> infos;
460};
461
462} // namespace autopas
#define AutoPasLog(lvl, fmt,...)
Macro for logging providing common meta information without filename.
Definition: Logger.h:24
Public iterator class that iterates over a particle container and additional vectors (which are typic...
Definition: ContainerIterator.h:93
bool isValid() const
Check whether the iterator currently points to a valid particle.
Definition: ContainerIterator.h:295
This class is able to gather and store important information for a tuning phase from a container and ...
Definition: LiveInfo.h:33
std::string toString() const
Creates a string containing all live info gathered.
Definition: LiveInfo.h:320
T get(const std::string &key) const
Gets a single value from the infos that corresponds to the given string.
Definition: LiveInfo.h:299
std::pair< std::string, std::string > getCSVLine() const
Generate a csv representation containing all values from the toString() method.
Definition: LiveInfo.h:383
friend std::istream & operator>>(std::istream &in, LiveInfo &info)
Stream operator to read the LiveInfo in from a stream.
Definition: LiveInfo.h:363
friend std::ostream & operator<<(std::ostream &out, const LiveInfo &info)
Stream operator to write the LiveInfo to a stream.
Definition: LiveInfo.h:346
std::variant< bool, double, size_t, ContainerOption, TraversalOption, LoadEstimatorOption, DataLayoutOption, Newton3Option > InfoType
The type of an info.
Definition: LiveInfo.h:119
void gather(ContainerIterator< Particle_T, true, false > particleIter, size_t rebuildFrequency, size_t numOwnedParticles, std::array< double, 3 > boxMin, std::array< double, 3 > boxMax, double cutoff, double skin)
Gathers key statistics that define the computational profile of the simulation, in order to provide l...
Definition: LiveInfo.h:189
const auto & get() const
Returns a map of all infos.
Definition: LiveInfo.h:290
Class representing the load estimator choices.
Definition: LoadEstimatorOption.h:18
Particle-counting bin structure.
Definition: ParticleBinStructure.h:34
Timer class to stop times.
Definition: Timer.h:20
void start()
start the timer.
Definition: Timer.cpp:17
long getTotalTime() const
Get total accumulated time.
Definition: Timer.h:53
long stop()
Stops the timer and returns the time elapsed in nanoseconds since the last call to start.
Definition: Timer.cpp:25
constexpr std::array< target_T, SIZE > ceilAndCast(const std::array< float_T, SIZE > &a)
Ceils all array elements and converts them to a different type.
Definition: ArrayMath.h:352
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:32
int autopas_get_max_threads()
Dummy for omp_get_max_threads() when no OpenMP is available.
Definition: WrapOpenMP.h:144
Type
Enum describing all types that are allowed in a rule program.
Definition: RuleBasedProgramTree.h:10