Stan Math Library  2.15.0
reverse mode automatic differentiation
log_determinant_spd.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_REV_MAT_FUN_LOG_DETERMINANT_SPD_HPP
2 #define STAN_MATH_REV_MAT_FUN_LOG_DETERMINANT_SPD_HPP
3 
8 #include <stan/math/rev/core.hpp>
9 
10 namespace stan {
11  namespace math {
12 
13  template <int R, int C>
14  inline var log_determinant_spd(const Eigen::Matrix<var, R, C>& m) {
15  using Eigen::Matrix;
16 
17  check_square("log_determinant_spd", "m", m);
18 
19  Matrix<double, R, C> m_d(m.rows(), m.cols());
20  for (int i = 0; i < m.size(); ++i)
21  m_d(i) = m(i).val();
22 
23  Eigen::LDLT<Matrix<double, R, C> > ldlt(m_d);
24  if (ldlt.info() != Eigen::Success) {
25  double y = 0;
26  domain_error("log_determinant_spd",
27  "matrix argument", y,
28  "failed LDLT factorization");
29  }
30 
31  // compute the inverse of A (needed for the derivative)
32  m_d.setIdentity(m.rows(), m.cols());
33  ldlt.solveInPlace(m_d);
34 
35  if (ldlt.isNegative() || (ldlt.vectorD().array() <= 1e-16).any()) {
36  double y = 0;
37  domain_error("log_determinant_spd",
38  "matrix argument", y,
39  "matrix is negative definite");
40  }
41 
42  double val = ldlt.vectorD().array().log().sum();
43 
44  check_finite("log_determinant_spd",
45  "log determininant of the matrix argument", val);
46 
47  vari** operands = ChainableStack::memalloc_
48  .alloc_array<vari*>(m.size());
49  for (int i = 0; i < m.size(); ++i)
50  operands[i] = m(i).vi_;
51 
52  double* gradients = ChainableStack::memalloc_
53  .alloc_array<double>(m.size());
54  for (int i = 0; i < m.size(); ++i)
55  gradients[i] = m_d(i);
56 
57  return var(new precomputed_gradients_vari(val, m.size(),
58  operands, gradients));
59  }
60 
61  }
62 
63 }
64 #endif
void check_finite(const char *function, const char *name, const T_y &y)
Check if y is finite.
The variable implementation base class.
Definition: vari.hpp:30
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:30
A variable implementation taking a sequence of operands and partial derivatives with respect to the o...
void domain_error(const char *function, const char *name, const T &y, const char *msg1, const char *msg2)
Throw a domain error with a consistently formatted message.
void check_square(const char *function, const char *name, const Eigen::Matrix< T_y, Eigen::Dynamic, Eigen::Dynamic > &y)
Check if the specified matrix is square.
T * alloc_array(size_t n)
Allocate an array on the arena of the specified size to hold values of the specified template paramet...
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:94
T log_determinant_spd(const Eigen::Matrix< T, R, C > &m)
Returns the log absolute determinant of the specified square matrix.

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