Stan Math Library  2.8.0
reverse mode automatic differentiation
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Groups
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 (size_t i = 0; i < v.size(); i++)
22  result += v[i].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 
31  explicit sum_v_vari(const std::vector<var> &v1)
32  : vari(sum_of_val(v1)),
33  v_(reinterpret_cast<vari**>(ChainableStack::memalloc_
34  .alloc(v1.size() * sizeof(vari*)))),
35  length_(v1.size()) {
36  for (size_t i = 0; i < length_; i++)
37  v_[i] = v1[i].vi_;
38  }
39 
40  virtual void chain() {
41  for (size_t i = 0; i < length_; i++) {
42  v_[i]->adj_ += adj_;
43  }
44  }
45  };
46 
53  inline var sum(const std::vector<var>& m) {
54  if (m.size() == 0)
55  return 0.0;
56  return var(new sum_v_vari(m));
57  }
58 
59  }
60 }
61 #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:28
size_t length(const std::vector< T > &x)
Definition: length.hpp:10
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:32
virtual void chain()
Apply the chain rule to this variable based on the variables on which it depends. ...
Definition: sum.hpp:40
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:42
static double sum_of_val(const std::vector< var > &v)
Definition: sum.hpp:19
Class for sums of variables constructed with standard vectors.
Definition: sum.hpp:14
sum_v_vari(const std::vector< var > &v1)
Definition: sum.hpp:31

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