ERF
Energy Research and Forecasting: An Atmospheric Modeling Code
ERF_RunningStats.H
Go to the documentation of this file.
1 #ifndef ERF_RUNNING_STATS_H
2 #define ERF_RUNNING_STATS_H
3 
4 /** Running mean, rms, minimum and maximum of a body's scalar diagnostics, carried across checkpoints. */
5 
6 #include <cmath>
7 #include <fstream>
8 #include <iomanip>
9 #include <limits>
10 #include <map>
11 #include <sstream>
12 #include <string>
13 #include <vector>
14 
15 #include <AMReX.H>
16 #include <AMReX_BLassert.H>
17 #include <AMReX_ParallelDescriptor.H>
18 #include <AMReX_Print.H>
19 #include <AMReX_REAL.H>
20 #include <AMReX_Utility.H>
21 #include <AMReX_Vector.H>
22 
23 #include "ERF_DiagnosticsLog.H"
24 
25 namespace erf_actuator {
26 
27 /**
28  * One set of running statistics: the mean, the root mean square, the minimum and the maximum of
29  * each named scalar quantity over every sample added since the caller's averaging start.
30  * write() rewrites <output_root>_stats.csv with the current
31  * values; the sums are part of the checkpoint, so the statistics continue across a restart.
32  * A non-finite sample aborts, naming the statistics and the quantity.
33  */
35 {
36 public:
37  RunningStats (std::string name, std::string output_root, std::vector<std::string> quantities)
38  : m_name(std::move(name)), m_output_root(std::move(output_root)), m_names(std::move(quantities)),
39  m_sum(m_names.size(), 0.0), m_sum2(m_names.size(), 0.0),
40  m_min(m_names.size(), std::numeric_limits<amrex::Real>::max()),
41  m_max(m_names.size(), std::numeric_limits<amrex::Real>::lowest()) {}
42 
43  const std::string& name () const { return m_name; }
44  const std::vector<std::string>& quantities () const { return m_names; }
45 
46  /**
47  * Accept a checkpoint listing quantity `old_name` where `now` stands: an earlier name of the same
48  * quantity (`same` true: its statistics continue), or of another quantity (`same` false: the
49  * statistics start afresh at the restart, and say so).
50  */
51  void renamed_from (const std::string& old_name, const std::string& now, bool same)
52  {
53  m_renamed[old_name] = std::make_pair(now, same);
54  }
55  int num_samples () const { return m_count; }
56  double t_first () const { return m_t_first; }
57  double t_last () const { return m_t_last; }
58 
59  /** Add one sample of every quantity, taken at time t (s). */
60  void accumulate (double t, const std::vector<amrex::Real>& values)
61  {
62  AMREX_ALWAYS_ASSERT_WITH_MESSAGE(values.size() == m_names.size(), "RunningStats::accumulate: one value per quantity");
63  for (std::size_t i = 0; i < values.size(); ++i) {
64  if (!std::isfinite(values[i])) {
65  std::ostringstream msg;
66  msg << "RunningStats " << m_name << ": quantity " << m_names[i] << " is not finite at t = " << t << " s";
67  amrex::Abort(msg.str());
68  }
69  }
70  if (m_count == 0) { m_t_first = t; }
71  m_t_last = t;
72  for (std::size_t i = 0; i < values.size(); ++i) {
73  const double v = static_cast<double>(values[i]);
74  m_sum[i] += v;
75  m_sum2[i] += v * v;
76  m_min[i] = std::min(m_min[i], values[i]);
77  m_max[i] = std::max(m_max[i], values[i]);
78  }
79  ++m_count;
80  }
81  amrex::Real mean (std::size_t i) const { return (m_count > 0) ? static_cast<amrex::Real>(m_sum[i] / m_count) : amrex::Real(0.0); }
82  amrex::Real rms (std::size_t i) const
83  {
84  return (m_count > 0) ? static_cast<amrex::Real>(std::sqrt(std::max(m_sum2[i] / m_count, 0.0))) : amrex::Real(0.0);
85  }
86  amrex::Real min (std::size_t i) const { return (m_count > 0) ? m_min[i] : amrex::Real(0.0); }
87  amrex::Real max (std::size_t i) const { return (m_count > 0) ? m_max[i] : amrex::Real(0.0); }
88 
89  /** Rewrite <output_root>_stats.csv: one row per quantity with the current statistics. */
90  void write () const
91  {
92  if (!amrex::ParallelDescriptor::IOProcessor()) { return; }
93  std::ofstream out;
94  open_log(out, m_output_root + "_stats.csv", true);
95  out << "samples,t_first,t_last,quantity,mean,rms,min,max\n" << std::setprecision(10);
96  for (std::size_t i = 0; i < m_names.size(); ++i) {
97  out << m_count << "," << m_t_first << "," << m_t_last << "," << m_names[i] << ","
98  << mean(i) << "," << rms(i) << "," << min(i) << "," << max(i) << "\n";
99  }
100  }
101 
102  /** The state for a checkpoint: <dir>/<name>_stats.dat. */
103  void write_state (const std::string& dir) const
104  {
105  if (!amrex::ParallelDescriptor::IOProcessor()) { return; }
106  std::ofstream out(dir + "/" + m_name + "_stats.dat", std::ios::trunc);
107  if (!out) { amrex::Abort("cannot write the statistics checkpoint for " + m_name + " in '" + dir + "'"); }
108  out << std::setprecision(17) << "count = " << m_count << "\nsize = " << m_names.size()
109  << "\nt_first = " << m_t_first << "\nt_last = " << m_t_last << "\n";
110  for (std::size_t i = 0; i < m_names.size(); ++i) {
111  out << m_names[i] << " " << m_sum[i] << " " << m_sum2[i] << " " << m_min[i] << " " << m_max[i] << "\n";
112  }
113  }
114  /**
115  * Restore the state written by write_state(); false when there is none. Aborts, changing
116  * nothing, when the file is malformed: a negative count, t_last before t_first, a non-finite
117  * value, or quantities other than this object's (but those accepted by renamed_from).
118  */
119  bool read_state (const std::string& dir)
120  {
121  const std::string fname = dir + "/" + m_name + "_stats.dat";
122  if (!file_exists_everywhere(fname)) {
123  amrex::Print() << "RunningStats " << m_name << ": no " << fname << " in the checkpoint; the statistics start afresh\n";
124  return false;
125  }
126  amrex::Vector<char> chars;
127  amrex::ParallelDescriptor::ReadAndBcastFile(fname, chars);
128  std::istringstream in(std::string(chars.dataPtr(), chars.size()));
129  std::string key, eq, qname;
130  std::size_t size = 0;
131  int count = 0;
132  double t0 = 0.0, t1 = 0.0;
133  if (!(in >> key >> eq >> count) || key != "count" || !(in >> key >> eq >> size) || key != "size" ||
134  !(in >> key >> eq >> t0) || key != "t_first" || !(in >> key >> eq >> t1) || key != "t_last") {
135  amrex::Abort("malformed statistics checkpoint '" + fname + "'");
136  }
137  if (size != m_names.size()) {
138  amrex::Abort("the statistics checkpoint '" + fname + "' holds " + std::to_string(size) + " quantities but " +
139  m_name + " has " + std::to_string(m_names.size()));
140  }
141  if (count < 0 || !std::isfinite(t0) || !std::isfinite(t1) || (count > 0 && t1 < t0)) {
142  amrex::Abort("malformed statistics checkpoint '" + fname + "': the count must be >= 0 and t_first <= t_last, both finite");
143  }
144  std::vector<double> sum(size), sum2(size);
145  std::vector<amrex::Real> mn(size), mx(size);
146  std::string afresh;
147  for (std::size_t i = 0; i < size; ++i) {
148  if (!(in >> qname >> sum[i] >> sum2[i] >> mn[i] >> mx[i])) {
149  amrex::Abort("the statistics checkpoint '" + fname + "' is truncated: " + m_names[i] + " is missing or incomplete");
150  }
151  if (qname != m_names[i]) {
152  const auto r = m_renamed.find(qname);
153  if (r == m_renamed.end() || r->second.first != m_names[i]) {
154  amrex::Abort("the statistics checkpoint '" + fname + "' does not list " + m_names[i] + " where expected");
155  }
156  if (r->second.second) {
157  amrex::Print() << "RunningStats " << m_name << ": the checkpoint's " << qname << " statistics continue as "
158  << m_names[i] << "\n";
159  } else if (afresh.empty()) {
160  afresh = qname;
161  }
162  }
163  if (!std::isfinite(sum[i]) || !std::isfinite(sum2[i]) || !std::isfinite(mn[i]) || !std::isfinite(mx[i])) {
164  amrex::Abort("malformed statistics checkpoint '" + fname + "': a value of " + m_names[i] + " is not finite");
165  }
166  }
167  if (!afresh.empty()) {
168  amrex::Print() << "RunningStats " << m_name << ": the checkpoint lists " << afresh << ", another quantity than "
169  << m_renamed[afresh].first << " here; all statistics of " << m_name << " start afresh at the restart\n";
170  return true;
171  }
172  m_sum = sum; m_sum2 = sum2; m_min = mn; m_max = mx;
173  m_count = count; m_t_first = t0; m_t_last = t1;
174  return true;
175  }
176 
177 private:
178  std::string m_name, m_output_root;
179  std::vector<std::string> m_names;
180  std::vector<double> m_sum, m_sum2; //!< in double: a float sum over many steps would lose the samples
181  std::vector<amrex::Real> m_min, m_max;
182  int m_count{0};
183  double m_t_first{0.0}, m_t_last{0.0};
184  std::map<std::string, std::pair<std::string, bool>> m_renamed; //!< old name -> (name now, same quantity)
185 };
186 
187 } // namespace erf_actuator
188 
189 #endif
int count
Definition: ERF_ActuatorSpreading.cpp:264
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(axis >=0 &&axis< AMREX_SPACEDIM, "prob.axis must be 0, 1 or 2")
Definition: ERF_RunningStats.H:35
void renamed_from(const std::string &old_name, const std::string &now, bool same)
Definition: ERF_RunningStats.H:51
int num_samples() const
Definition: ERF_RunningStats.H:55
std::vector< double > m_sum2
in double: a float sum over many steps would lose the samples
Definition: ERF_RunningStats.H:180
double m_t_last
Definition: ERF_RunningStats.H:183
int m_count
Definition: ERF_RunningStats.H:182
const std::vector< std::string > & quantities() const
Definition: ERF_RunningStats.H:44
const std::string & name() const
Definition: ERF_RunningStats.H:43
void accumulate(double t, const std::vector< amrex::Real > &values)
Definition: ERF_RunningStats.H:60
std::vector< double > m_sum
Definition: ERF_RunningStats.H:180
RunningStats(std::string name, std::string output_root, std::vector< std::string > quantities)
Definition: ERF_RunningStats.H:37
std::vector< amrex::Real > m_min
Definition: ERF_RunningStats.H:181
std::vector< std::string > m_names
Definition: ERF_RunningStats.H:179
std::vector< amrex::Real > m_max
Definition: ERF_RunningStats.H:181
void write_state(const std::string &dir) const
Definition: ERF_RunningStats.H:103
std::map< std::string, std::pair< std::string, bool > > m_renamed
old name -> (name now, same quantity)
Definition: ERF_RunningStats.H:184
double t_last() const
Definition: ERF_RunningStats.H:57
amrex::Real min(std::size_t i) const
Definition: ERF_RunningStats.H:86
amrex::Real mean(std::size_t i) const
Definition: ERF_RunningStats.H:81
void write() const
Definition: ERF_RunningStats.H:90
bool read_state(const std::string &dir)
Definition: ERF_RunningStats.H:119
double m_t_first
Definition: ERF_RunningStats.H:183
amrex::Real rms(std::size_t i) const
Definition: ERF_RunningStats.H:82
std::string m_name
Definition: ERF_RunningStats.H:178
double t_first() const
Definition: ERF_RunningStats.H:56
std::string m_output_root
Definition: ERF_RunningStats.H:178
amrex::Real max(std::size_t i) const
Definition: ERF_RunningStats.H:87
@ t
Definition: ERF_WSM6.H:295
Definition: ERF_ConsoleIO.cpp:17
Definition: ERF_ActuatorDeviceBuffers.H:14
bool file_exists_everywhere(const std::string &fname)
Definition: ERF_DiagnosticsLog.H:43
bool open_log(std::ofstream &out, const std::string &fname, bool truncate)
Definition: ERF_DiagnosticsLog.H:22
real(c_double), parameter t0
Definition: ERF_module_model_constants.F90:39