1 #ifndef STAN_MATH_PRIM_FUN_CUMULATIVE_SUM_HPP
2 #define STAN_MATH_PRIM_FUN_CUMULATIVE_SUM_HPP
3 
4 #include <stan/math/prim/fun/Eigen.hpp>
5 #include <stan/math/prim/meta.hpp>
6 #include <vector>
7 #include <numeric>
8 #include <functional>
9 
10 namespace stan {
11 namespace math {
12 
13 /**
14  * Return the cumulative sum of the specified vector.
15  *
16  * The cumulative sum of a vector of values \code{x} is the
17  *
18  * \code x[0], x[1] + x[2], ..., x[1] + , ..., + x[x.size()-1] @endcode
19  *
20  * @tparam T type of elements in the vector
21  * @param x Vector of values.
22  * @return Cumulative sum of values.
23  */
24 template <typename T>
cumulative_sum(const std::vector<T> & x)25 inline std::vector<T> cumulative_sum(const std::vector<T>& x) {
26   std::vector<T> result(x.size());
27   if (x.size() == 0) {
28     return result;
29   }
30   std::partial_sum(x.begin(), x.end(), result.begin(), std::plus<T>());
31   return result;
32 }
33 
34 /**
35  * Return the cumulative sum of the specified vector.
36  *
37  * The cumulative sum is of the same type as the input and
38  * has values defined by
39  *
40  * \code x(0), x(1) + x(2), ..., x(1) + , ..., + x(x.size()-1) @endcode
41  *
42  * @tparam EigVec type of the vector (must be derived from \c Eigen::MatrixBase
43  * and have one compile time dimension equal to 1)
44  *
45  * @param m Vector of values.
46  * @return Cumulative sum of values.
47  */
48 template <typename EigVec, require_eigen_vector_t<EigVec>* = nullptr>
cumulative_sum(const EigVec & m)49 inline auto cumulative_sum(const EigVec& m) {
50   using T_scalar = value_type_t<EigVec>;
51   Eigen::Matrix<T_scalar, EigVec::RowsAtCompileTime, EigVec::ColsAtCompileTime>
52       result(m.rows(), m.cols());
53   if (m.size() == 0) {
54     return result;
55   }
56   const Eigen::Ref<const plain_type_t<EigVec>>& m_ref = m;
57   std::partial_sum(m_ref.data(), m_ref.data() + m_ref.size(), result.data(),
58                    std::plus<T_scalar>());
59   return result;
60 }
61 
62 }  // namespace math
63 }  // namespace stan
64 
65 #endif
66