Stan  1.3
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Pages
log_determinant.hpp
Go to the documentation of this file.
1 #ifndef __STAN__AGRAD__REV__MATRIX__LOG_DETERMINANT_HPP__
2 #define __STAN__AGRAD__REV__MATRIX__LOG_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 log_determinant_vari : public vari {
21  int _rows;
22  int _cols;
23  double* _A;
24  vari** _adjARef;
25  public:
26  log_determinant_vari(const Eigen::Matrix<var,R,C> &A)
27  : vari(log_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 log_determinant_vari_calc(const Eigen::Matrix<var,R,C> &A)
45  {
46  Eigen::Matrix<double,R,C> Ad(A.rows(),A.cols());
47  for (size_type j = 0; j < A.cols(); j++)
48  for (size_type i = 0; i < A.rows(); i++)
49  Ad(i,j) = A(i,j).val();
50  return Ad.fullPivHouseholderQr().logAbsDeterminant();
51  }
52  virtual void chain() {
53  using Eigen::Matrix;
54  using Eigen::Map;
55  Matrix<double,R,C> adjA(_rows,_cols);
56  adjA = adj_
57  * Map<Matrix<double,R,C> >(_A,_rows,_cols)
58  .inverse().transpose();
59  size_t pos = 0;
60  for (size_type j = 0; j < _cols; j++) {
61  for (size_type i = 0; i < _rows; i++) {
62  _adjARef[pos++]->adj_ += adjA(i,j);
63  }
64  }
65  }
66  };
67  }
68 
69  template <int R, int C>
70  inline var log_determinant(const Eigen::Matrix<var,R,C>& m) {
71  stan::math::validate_square(m,"log_determinant");
72  return var(new log_determinant_vari<R,C>(m));
73  }
74 
75  }
76 }
77 #endif

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