faunus
sparsehistogram.h
1 #pragma once
2 
3 #include <format>
4 #include <map>
5 #include <fstream>
6 #if __cplusplus >= 202002L
7 #include <concepts>
8 #endif
9 
10 namespace Faunus {
11 
18 template <std::floating_point T = double> class SparseHistogram
19 {
20  const T resolution;
21  using map_type = std::map<int, unsigned int>;
22  map_type data;
23 
24  public:
25  explicit SparseHistogram(T resolution)
26  : resolution(resolution)
27  {
28  }
29 
30  const T getResolution() const { return resolution; }
31 
32  void add(const T value)
33  {
34  if (std::isfinite(value)) {
35  const auto index = static_cast<map_type::key_type>(std::round(value / resolution));
36  data[index]++;
37  }
38  else {
39  faunus_logger->warn("histogram: skipping inf/nan number");
40  }
41  }
42 
43  friend auto& operator<<(std::ostream& stream, const SparseHistogram& histogram)
44  {
45  std::for_each(histogram.data.begin(), histogram.data.end(), [&](const auto& sample) {
46  stream << std::format(
47  "{:.6E} {}\n", static_cast<T>(sample.first) * histogram.resolution, sample.second);
48  });
49  return stream;
50  }
51 };
52 } // namespace Faunus
double T
floating point size
Definition: units.h:73
Cell list class templates.
Definition: actions.cpp:11
Histogram for an arbitrary set of values using a sparse memory layout (map)
Definition: sparsehistogram.h:18