Stan  1.3
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Pages
determinant.hpp
Go to the documentation of this file.
1 #ifndef __STAN__AGRAD__REV__MATRIX__DETERMINANT_HPP__
2 #define __STAN__AGRAD__REV__MATRIX__DETERMINANT_HPP__
3 
4 #include <vector>
9 #include <stan/agrad/rev/var.hpp>
11 
12 // FIXME: use explicit files
13 #include <stan/agrad/agrad.hpp>
14 
15 namespace stan {
16  namespace agrad {
17 
18  namespace {
19  template<int R,int C>
20  class determinant_vari : public vari {
21  int _rows;
22  int _cols;
23  double* _A;
24  vari** _adjARef;
25  public:
26  determinant_vari(const Eigen::Matrix<var,R,C> &A)
27  : vari(determinant_vari_calc(A)),
28  _rows(A.rows()),
29  _cols(A.cols()),
30  _A((double*)stan::agrad::memalloc_.alloc(sizeof(double)
31  * A.rows() * A.cols())),
32  _adjARef((vari**)stan::agrad::memalloc_.alloc(sizeof(vari*)
33  * A.rows() * A.cols()))
34  {
35  size_t pos = 0;
36  for (size_type j = 0; j < _cols; j++) {
37  for (size_type i = 0; i < _rows; i++) {
38  _A[pos] = A(i,j).val();
39  _adjARef[pos++] = A(i,j).vi_;
40  }
41  }
42  }
43  static
44  double determinant_vari_calc(const Eigen::Matrix<var,R,C> &A) {
45  Eigen::Matrix<double,R,C> Ad(A.rows(),A.cols());
46  for (size_type j = 0; j < A.rows(); j++)
47  for (size_type i = 0; i < A.cols(); i++)
48  Ad(i,j) = A(i,j).val();
49  return Ad.determinant();
50  }
51  virtual void chain() {
52  using Eigen::Matrix;
53  using Eigen::Map;
54  Matrix<double,R,C> adjA(_rows,_cols);
55  adjA = (adj_ * val_) *
56  Map<Matrix<double,R,C> >(_A,_rows,_cols).inverse().transpose();
57  size_t pos = 0;
58  for (size_type j = 0; j < _cols; j++) {
59  for (size_type i = 0; i < _rows; i++) {
60  _adjARef[pos++]->adj_ += adjA(i,j);
61  }
62  }
63  }
64  };
65  }
66 
67  template <int R, int C>
68  inline var determinant(const Eigen::Matrix<var,R,C>& m) {
69  stan::math::validate_square(m,"determinant");
70  return var(new determinant_vari<R,C>(m));
71  }
72 
73  }
74 }
75 #endif

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