Stan Math Library  2.20.0
reverse mode automatic differentiation
accumulator.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_FUN_ACCUMULATOR_HPP
2 #define STAN_MATH_PRIM_MAT_FUN_ACCUMULATOR_HPP
3 
6 #include <vector>
7 #include <type_traits>
8 
9 namespace stan {
10 namespace math {
11 
22 template <typename T>
23 class accumulator {
24  private:
25  std::vector<T> buf_;
26 
27  public:
31  accumulator() : buf_() {}
32 
37 
48  template <typename S>
49  typename std::enable_if<std::is_arithmetic<S>::value, void>::type add(S x) {
50  buf_.push_back(static_cast<T>(x));
51  }
52 
65  template <typename S>
66  typename std::enable_if<
67  !std::is_arithmetic<S>::value,
68  typename std::enable_if<std::is_same<S, T>::value, void>::type>::type
69  add(const S& x) {
70  buf_.push_back(x);
71  }
72 
82  template <typename S, int R, int C>
83  void add(const Eigen::Matrix<S, R, C>& m) {
84  for (int i = 0; i < m.size(); ++i)
85  add(m(i));
86  }
87 
97  template <typename S>
98  void add(const std::vector<S>& xs) {
99  for (size_t i = 0; i < xs.size(); ++i)
100  add(xs[i]);
101  }
102 
108  T sum() const {
109  using math::sum;
110  return sum(buf_);
111  }
112 };
113 
114 } // namespace math
115 } // namespace stan
116 
117 #endif
fvar< T > sum(const std::vector< fvar< T > > &m)
Return the sum of the entries of the specified standard vector.
Definition: sum.hpp:20
accumulator()
Construct an accumulator.
Definition: accumulator.hpp:31
std::enable_if< !std::is_arithmetic< S >::value, typename std::enable_if< std::is_same< S, T >::value, void >::type >::type add(const S &x)
Add the specified non-arithmetic value to the buffer.
Definition: accumulator.hpp:69
T sum() const
Return the sum of the accumulated values.
Class to accumulate values and eventually return their sum.
Definition: accumulator.hpp:23
std::enable_if< std::is_arithmetic< S >::value, void >::type add(S x)
Add the specified arithmetic type value to the buffer after static casting it to the class type T...
Definition: accumulator.hpp:49
void add(const std::vector< S > &xs)
Recursively add each entry in the specified standard vector to the buffer.
Definition: accumulator.hpp:98
void add(const Eigen::Matrix< S, R, C > &m)
Add each entry in the specified matrix, vector, or row vector of values to the buffer.
Definition: accumulator.hpp:83
~accumulator()
Destroy an accumulator.
Definition: accumulator.hpp:36

     [ Stan Home Page ] © 2011–2018, Stan Development Team.