Stan  2.5.0
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerations 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>
7 #include <stan/agrad/rev/var.hpp>
10 
11 // FIXME: use explicit files
12 #include <stan/agrad/rev.hpp>
13 
14 namespace stan {
15  namespace agrad {
16 
17  namespace {
18  template<int R,int C>
19  class determinant_vari : public vari {
20  int _rows;
21  int _cols;
22  double* A_;
23  vari** _adjARef;
24  public:
25  determinant_vari(const Eigen::Matrix<var,R,C> &A)
26  : vari(determinant_vari_calc(A)),
27  _rows(A.rows()),
28  _cols(A.cols()),
29  A_((double*)stan::agrad::memalloc_.alloc(sizeof(double)
30  * A.rows() * A.cols())),
31  _adjARef((vari**)stan::agrad::memalloc_.alloc(sizeof(vari*)
32  * A.rows() * A.cols()))
33  {
34  size_t pos = 0;
35  for (size_type j = 0; j < _cols; j++) {
36  for (size_type i = 0; i < _rows; i++) {
37  A_[pos] = A(i,j).val();
38  _adjARef[pos++] = A(i,j).vi_;
39  }
40  }
41  }
42  static
43  double determinant_vari_calc(const Eigen::Matrix<var,R,C> &A) {
44  Eigen::Matrix<double,R,C> Ad(A.rows(),A.cols());
45  for (size_type j = 0; j < A.rows(); j++)
46  for (size_type i = 0; i < A.cols(); i++)
47  Ad(i,j) = A(i,j).val();
48  return Ad.determinant();
49  }
50  virtual void chain() {
51  using Eigen::Matrix;
52  using Eigen::Map;
53  Matrix<double,R,C> adjA(_rows,_cols);
54  adjA = (adj_ * val_) *
55  Map<Matrix<double,R,C> >(A_,_rows,_cols).inverse().transpose();
56  size_t pos = 0;
57  for (size_type j = 0; j < _cols; j++) {
58  for (size_type i = 0; i < _rows; i++) {
59  _adjARef[pos++]->adj_ += adjA(i,j);
60  }
61  }
62  }
63  };
64  }
65 
66  template <int R, int C>
67  inline var determinant(const Eigen::Matrix<var,R,C>& m) {
68  stan::math::check_square("determinant(%1%)",m,"m",(double*)0);
69  return var(new determinant_vari<R,C>(m));
70  }
71 
72  }
73 }
74 #endif
vari ** _adjARef
Definition: determinant.hpp:23
memory::stack_alloc memalloc_
Definition: var_stack.cpp:16
int _cols
Definition: determinant.hpp:21
double * A_
Definition: determinant.hpp:22
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic >::Index size_type
Definition: typedefs.hpp:14
size_t rows(const Eigen::Matrix< T, R, C > &m)
Definition: rows.hpp:12
int _rows
Definition: determinant.hpp:20
size_t cols(const Eigen::Matrix< T, R, C > &m)
Definition: cols.hpp:12
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:27
fvar< T > determinant(const Eigen::Matrix< fvar< T >, R, C > &m)
Definition: determinant.hpp:21
bool check_square(const char *function, const Eigen::Matrix< T_y, Eigen::Dynamic, Eigen::Dynamic > &y, const char *name, T_result *result)
Return true if the specified matrix is square.

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