Automatic Differentiation
 
Loading...
Searching...
No Matches
reduce_sum.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_FWD_FUNCTOR_REDUCE_SUM_HPP
2#define STAN_MATH_FWD_FUNCTOR_REDUCE_SUM_HPP
3
6
7#include <algorithm>
8#include <tuple>
9#include <vector>
10
11namespace stan {
12namespace math {
13
14namespace internal {
15template <typename ReduceFunction, typename Enable, typename ReturnType,
16 typename Vec, typename... Args>
17struct reduce_sum_impl;
18
27template <typename ReduceFunction, typename Enable, typename ReturnType,
28 typename Vec, typename... Args>
62 inline return_type_t<Vec, Args...> operator()(Vec&& vmapped,
63 bool auto_partitioning,
64 int grainsize,
65 std::ostream* msgs,
66 Args&&... args) const {
67 if (vmapped.empty()) {
68 return 0.0;
69 }
70
71 if (auto_partitioning) {
72 return ReduceFunction()(std::forward<Vec>(vmapped), 0, vmapped.size() - 1,
73 msgs, std::forward<Args>(args)...);
74 } else {
75 return_type_t<Vec, Args...> sum = 0.0;
76 for (size_t i = 0; i < (vmapped.size() + grainsize - 1) / grainsize;
77 ++i) {
78 size_t start = i * grainsize;
79 size_t end = std::min((i + 1) * grainsize, vmapped.size()) - 1;
80
81 std::decay_t<Vec> sub_slice;
82 sub_slice.reserve(end - start + 1);
83 for (size_t i = start; i <= end; ++i) {
84 sub_slice.emplace_back(vmapped[i]);
85 }
86
87 sum += ReduceFunction()(std::forward<Vec>(sub_slice), start, end, msgs,
88 std::forward<Args>(args)...);
89 }
90 return sum;
91 }
92 }
93};
94
95} // namespace internal
96
97} // namespace math
98} // namespace stan
99
100#endif
typename return_type< Ts... >::type return_type_t
Convenience type for the return type of the specified template parameters.
fvar< T > sum(const std::vector< fvar< T > > &m)
Return the sum of the entries of the specified standard vector.
Definition sum.hpp:22
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...
Definition fvar.hpp:9
return_type_t< Vec, Args... > operator()(Vec &&vmapped, bool auto_partitioning, int grainsize, std::ostream *msgs, Args &&... args) const
Call an instance of the function ReduceFunction on every element of an input sequence and sum these t...
reduce_sum_impl implementation for any autodiff type.