Stan  2.5.0
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
sum.hpp
Go to the documentation of this file.
1 #ifndef STAN__AGRAD__REV__MATRIX__SUM_HPP
2 #define STAN__AGRAD__REV__MATRIX__SUM_HPP
3 
4 #include <vector>
7 #include <stan/agrad/rev/var.hpp>
10 
11 namespace stan {
12  namespace agrad {
13 
14  namespace {
15  class sum_v_vari : public vari{
16  protected:
17  vari** v_;
18  size_t length_;
19  inline static double var_sum(const var *v, size_t length) {
20  double result = 0;
21  for (size_t i = 0; i < length; i++)
22  result += v[i].vi_->val_;
23  return result;
24  }
25  template<typename Derived>
26  inline static double var_sum(const Eigen::DenseBase<Derived> &v) {
27  double result = 0;
28  for (int i = 0; i < v.size(); i++)
29  result += v(i).vi_->val_;
30  return result;
31  }
32  public:
33  template<typename Derived>
34  sum_v_vari(const Eigen::DenseBase<Derived> &v) :
35  vari(var_sum(v)), length_(v.size()) {
36  v_ = (vari**)memalloc_.alloc(length_*sizeof(vari*));
37  for (size_t i = 0; i < length_; i++)
38  v_[i] = v(i).vi_;
39  }
40  template<int R1,int C1>
41  sum_v_vari(const Eigen::Matrix<var,R1,C1> &v1) :
42  vari(var_sum(v1)), length_(v1.size()) {
43  v_ = (vari**)memalloc_.alloc(length_*sizeof(vari*));
44  for (size_t i = 0; i < length_; i++)
45  v_[i] = v1(i).vi_;
46  }
47  sum_v_vari(const var *v, size_t len) :
48  vari(var_sum(v,len)), length_(len) {
49  v_ = (vari**)memalloc_.alloc(length_*sizeof(vari*));
50  for (size_t i = 0; i < length_; i++)
51  v_[i] = v[i].vi_;
52  }
53  virtual void chain() {
54  for (size_t i = 0; i < length_; i++) {
55  v_[i]->adj_ += adj_;
56  }
57  }
58  };
59  }
60 
67  template <int R, int C>
68  inline var sum(const Eigen::Matrix<var,R,C>& m) {
69  if (m.size() == 0)
70  return 0.0;
71  return var(new sum_v_vari(m));
72  }
73 
74  }
75 }
76 #endif
size_t length(const T &)
Definition: traits.hpp:159
memory::stack_alloc memalloc_
Definition: var_stack.cpp:16
size_t length_
Definition: sum.hpp:18
fvar< T > sum(const Eigen::Matrix< fvar< T >, R, C > &m)
Definition: sum.hpp:14
vari ** v_
Definition: sum.hpp:17
void * alloc(size_t len)
Return a newly allocated block of memory of the appropriate size managed by the stack allocator...
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:27
int size(const std::vector< T > &x)
Definition: size.hpp:11

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