Stan  1.3
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Pages
dot_self.hpp
Go to the documentation of this file.
1 #ifndef __STAN__AGRAD__REV__MATRIX__DOT_SELF_HPP__
2 #define __STAN__AGRAD__REV__MATRIX__DOT_SELF_HPP__
3 
4 #include <vector>
8 #include <stan/agrad/rev/var.hpp>
10 
11 namespace stan {
12  namespace agrad {
13 
14  namespace {
15  class dot_self_vari : public vari {
16  protected:
17  vari** v_;
18  size_t size_;
19  public:
20  dot_self_vari(vari** v, size_t size)
21  : vari(var_dot_self(v,size)),
22  v_(v),
23  size_(size) {
24  }
25  template<typename Derived>
26  dot_self_vari(const Eigen::DenseBase<Derived> &v) :
27  vari(var_dot_self(v)), size_(v.size()) {
28  v_ = (vari**)memalloc_.alloc(size_*sizeof(vari*));
29  for (size_t i = 0; i < size_; i++)
30  v_[i] = v[i].vi_;
31  }
32  template <int R, int C>
33  dot_self_vari(const Eigen::Matrix<var,R,C>& v) :
34  vari(var_dot_self(v)), size_(v.size()) {
35  v_ = (vari**) memalloc_.alloc(size_ * sizeof(vari*));
36  for (size_t i = 0; i < size_; ++i)
37  v_[i] = v(i).vi_;
38  }
39  inline static double square(double x) { return x * x; }
40  inline static double var_dot_self(vari** v, size_t size) {
41  double sum = 0.0;
42  for (size_t i = 0; i < size; ++i)
43  sum += square(v[i]->val_);
44  return sum;
45  }
46  template<typename Derived>
47  double var_dot_self(const Eigen::DenseBase<Derived> &v) {
48  double sum = 0.0;
49  for (int i = 0; i < v.size(); ++i)
50  sum += square(v(i).vi_->val_);
51  return sum;
52  }
53  template <int R, int C>
54  inline static double var_dot_self(const Eigen::Matrix<var,R,C> &v) {
55  double sum = 0.0;
56  for (int i = 0; i < v.size(); ++i)
57  sum += square(v(i).vi_->val_);
58  return sum;
59  }
60  virtual void chain() {
61  for (size_t i = 0; i < size_; ++i)
62  v_[i]->adj_ += adj_ * 2.0 * v_[i]->val_;
63  }
64  };
65  }
76  template<int R, int C>
77  inline var dot_self(const Eigen::Matrix<var, R, C>& v) {
78  stan::math::validate_vector(v,"dot_self");
79  return var(new dot_self_vari(v));
80  }
81 
87  template<int R,int C>
88  inline Eigen::Matrix<var,1,C>
89  columns_dot_self(const Eigen::Matrix<var,R,C>& x) {
90  Eigen::Matrix<var,1,C> ret(1,x.cols());
91  for (size_type i = 0; i < x.cols(); i++) {
92  ret(i) = var(new dot_self_vari(x.col(i)));
93  }
94  return ret;
95  }
96 
97 
98  }
99 }
100 #endif

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