Version: SMASH-3.1
average.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2015,2017-2018,2020
3  * SMASH Team
4  *
5  * GNU General Public License (GPLv3 or later)
6  */
7 
8 #ifndef SRC_INCLUDE_SMASH_AVERAGE_H_
9 #define SRC_INCLUDE_SMASH_AVERAGE_H_
10 
11 #include <cassert>
12 #include <cstdint>
13 #include <sstream>
14 #include <stdexcept>
15 #include <utility>
16 #include <vector>
17 
18 namespace smash {
19 
24 template <typename T>
25 class Average {
26  public:
28  Average() : avg_(0), n_(0) {}
29 
31  void add(T x) {
32  avg_ = (avg_ * n_ + x) / (n_ + 1);
33  n_++;
34  }
35 
37  T average() const { return avg_; }
38 
40  uint64_t number_of_values() const { return n_; }
41 
43  void clear() {
44  avg_ = 0;
45  n_ = 0;
46  }
47 
48  private:
50  T avg_;
52  uint64_t n_;
53 };
54 
64 template <typename T>
65 std::pair<std::vector<T>, std::vector<T>> dedup_avg(const std::vector<T>& x,
66  const std::vector<T>& y) {
67  if (x.size() != y.size()) {
68  std::stringstream ss;
69  ss << "x and y have to be of same size: " << x.size() << " != " << y.size();
70  throw std::runtime_error(ss.str());
71  }
72  if (x.size() < 1) {
73  throw std::runtime_error("x cannot be empty.");
74  }
75  std::vector<T> new_x;
76  new_x.reserve(x.size());
77  std::vector<T> new_y;
78  new_y.reserve(y.size());
79  Average<T> avg;
80  T prev_x = x[0];
81  for (size_t i = 0; i < x.size(); i++) {
82  if (x[i] == prev_x) {
83  avg.add(y[i]);
84  } else {
85  assert(i != 0);
86  new_x.push_back(x[i - 1]);
87  new_y.push_back(avg.average());
88  avg.clear();
89  avg.add(y[i]);
90  prev_x = x[i];
91  }
92  }
93  new_x.push_back(x.back());
94  new_y.push_back(avg.average());
95  return std::make_pair(std::move(new_x), std::move(new_y));
96 }
97 
98 } // namespace smash
99 
100 #endif // SRC_INCLUDE_SMASH_AVERAGE_H_
Calculate an average value incrementally.
Definition: average.h:25
T avg_
Average.
Definition: average.h:50
void clear()
Reset the average to 0.
Definition: average.h:43
void add(T x)
Add a value x to the set of numbers defining the average.
Definition: average.h:31
T average() const
Definition: average.h:37
Average()
Create a new object to calculate an average.
Definition: average.h:28
uint64_t n_
Sample size.
Definition: average.h:52
uint64_t number_of_values() const
Definition: average.h:40
Definition: action.h:24
std::pair< std::vector< T >, std::vector< T > > dedup_avg(const std::vector< T > &x, const std::vector< T > &y)
Remove duplicates from data (x, y) by averaging y.
Definition: average.h:65