1 #ifndef STAN_MATH_REV_FUN_SUM_HPP 2 #define STAN_MATH_REV_FUN_SUM_HPP 3 4 #include <stan/math/prim/fun/Eigen.hpp> 5 #include <stan/math/rev/core.hpp> 6 #include <stan/math/rev/meta.hpp> 7 #include <stan/math/rev/core/arena_matrix.hpp> 8 #include <stan/math/rev/core/reverse_pass_callback.hpp> 9 #include <stan/math/rev/fun/to_arena.hpp> 10 #include <stan/math/rev/fun/sum.hpp> 11 #include <stan/math/rev/fun/value_of.hpp> 12 #include <stan/math/rev/core/typedefs.hpp> 13 #include <stan/math/prim/fun/as_array_or_scalar.hpp> 14 #include <vector> 15 16 namespace stan { 17 namespace math { 18 19 /** 20 * Returns the sum of the entries of the specified vector. 21 * 22 * @param m Vector. 23 * @return Sum of vector entries. 24 */ 25 template <typename Alloc> sum(const std::vector<var,Alloc> & m)26inline var sum(const std::vector<var, Alloc>& m) { 27 if (unlikely(m.empty())) { 28 return 0.0; 29 } else { 30 auto arena_m = to_arena(as_array_or_scalar(m)); 31 return make_callback_var(arena_m.val().sum(), [arena_m](auto& vi) mutable { 32 arena_m.adj() += vi.adj(); 33 }); 34 } 35 } 36 37 /** 38 * Returns the sum of the coefficients of the specified 39 * matrix. 40 * 41 * @tparam T type of the matrix of vector. Can be either a var matrix or 42 * matrix of vars. 43 * @param x Specified var_value containing a matrix or vector. 44 * @return Sum of coefficients of matrix. 45 */ 46 template <typename T, require_rev_matrix_t<T>* = nullptr> sum(const T & x)47inline var sum(const T& x) { 48 arena_t<T> x_arena = x; 49 return make_callback_var(sum(x_arena.val()), [x_arena](auto& vi) mutable { 50 x_arena.adj().array() += vi.adj(); 51 }); 52 } 53 54 } // namespace math 55 } // namespace stan 56 #endif 57