1 #ifndef STAN_MATH_REV_MAT_FUN_SUM_HPP
2 #define STAN_MATH_REV_MAT_FUN_SUM_HPP
3
4 #include <stan/math/prim/mat/fun/Eigen.hpp>
5 #include <stan/math/prim/mat/fun/typedefs.hpp>
6 #include <stan/math/rev/core.hpp>
7 #include <stan/math/rev/arr/fun/sum.hpp>
8
9 namespace stan {
10 namespace math {
11
12 /**
13 * Class for representing sums with constructors for Eigen.
14 * The <code>chain()</code> method and member variables are
15 * managed by the superclass <code>sum_v_vari</code>.
16 */
17 class sum_eigen_v_vari : public sum_v_vari {
18 protected:
19 template <typename Derived>
sum_of_val(const Eigen::DenseBase<Derived> & v)20 inline static double sum_of_val(const Eigen::DenseBase<Derived>& v) {
21 double result = 0;
22 for (int i = 0; i < v.size(); i++)
23 result += v(i).vi_->val_;
24 return result;
25 }
26
27 public:
28 template <int R1, int C1>
sum_eigen_v_vari(const Eigen::Matrix<var,R1,C1> & v1)29 explicit sum_eigen_v_vari(const Eigen::Matrix<var, R1, C1>& v1)
30 : sum_v_vari(
31 sum_of_val(v1),
32 reinterpret_cast<vari**>(ChainableStack::instance().memalloc_.alloc(
33 v1.size() * sizeof(vari*))),
34 v1.size()) {
35 for (size_t i = 0; i < length_; i++)
36 v_[i] = v1(i).vi_;
37 }
38 };
39
40 /**
41 * Returns the sum of the coefficients of the specified
42 * matrix, column vector or row vector.
43 *
44 * @tparam R Row type for matrix.
45 * @tparam C Column type for matrix.
46 * @param m Specified matrix or vector.
47 * @return Sum of coefficients of matrix.
48 */
49 template <int R, int C>
sum(const Eigen::Matrix<var,R,C> & m)50 inline var sum(const Eigen::Matrix<var, R, C>& m) {
51 if (m.size() == 0)
52 return 0.0;
53 return var(new sum_eigen_v_vari(m));
54 }
55
56 } // namespace math
57 } // namespace stan
58 #endif
59