Stan Math Library  2.20.0
reverse mode automatic differentiation
sum.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_REV_ARR_FUN_SUM_HPP
2 #define STAN_MATH_REV_ARR_FUN_SUM_HPP
3 
4 #include <stan/math/rev/core.hpp>
5 #include <vector>
6 
7 namespace stan {
8 namespace math {
9 
14 class sum_v_vari : public vari {
15  protected:
16  vari** v_;
17  size_t length_;
18 
19  inline static double sum_of_val(const std::vector<var>& v) {
20  double result = 0;
21  for (auto x : v)
22  result += x.val();
23  return result;
24  }
25 
26  public:
27  explicit sum_v_vari(double value, vari** v, size_t length)
28  : vari(value), v_(v), length_(length) {}
29 
30  explicit sum_v_vari(const std::vector<var>& v1)
31  : vari(sum_of_val(v1)),
32  v_(reinterpret_cast<vari**>(ChainableStack::instance_->memalloc_.alloc(
33  v1.size() * sizeof(vari*)))),
34  length_(v1.size()) {
35  for (size_t i = 0; i < length_; i++)
36  v_[i] = v1[i].vi_;
37  }
38 
39  virtual void chain() {
40  for (size_t i = 0; i < length_; i++) {
41  v_[i]->adj_ += adj_;
42  }
43  }
44 };
45 
52 inline var sum(const std::vector<var>& m) {
53  if (m.empty())
54  return 0.0;
55  return var(new sum_v_vari(m));
56 }
57 
58 } // namespace math
59 } // namespace stan
60 #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
sum_v_vari(double value, vari **v, size_t length)
Definition: sum.hpp:27
The variable implementation base class.
Definition: vari.hpp:30
size_t length(const std::vector< T > &x)
Returns the length of the provided std::vector.
Definition: length.hpp:16
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:33
friend class var
Definition: vari.hpp:32
virtual void chain()
Apply the chain rule to this variable based on the variables on which it depends. ...
Definition: sum.hpp:39
int size(const std::vector< T > &x)
Return the size of the specified standard vector.
Definition: size.hpp:17
double adj_
The adjoint of this variable, which is the partial derivative of this variable with respect to the ro...
Definition: vari.hpp:44
static double sum_of_val(const std::vector< var > &v)
Definition: sum.hpp:19
This struct always provides access to the autodiff stack using the singleton pattern.
Class for sums of variables constructed with standard vectors.
Definition: sum.hpp:14
sum_v_vari(const std::vector< var > &v1)
Definition: sum.hpp:30

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