Stan Math Library  2.20.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 
4 #include <stan/math/rev/meta.hpp>
9 #include <stan/math/rev/core.hpp>
10 
11 namespace stan {
12 namespace math {
13 
14 template <int R, int C>
15 inline var log_determinant_spd(const Eigen::Matrix<var, R, C>& m) {
16  using Eigen::Matrix;
17 
18  check_square("log_determinant_spd", "m", m);
19 
20  Matrix<double, R, C> m_d(m.rows(), m.cols());
21  for (int i = 0; i < m.size(); ++i)
22  m_d(i) = m(i).val();
23 
24  Eigen::LDLT<Matrix<double, R, C> > ldlt(m_d);
25  if (ldlt.info() != Eigen::Success) {
26  double y = 0;
27  domain_error("log_determinant_spd", "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", "matrix argument", y,
38  "matrix is negative definite");
39  }
40 
41  double val = ldlt.vectorD().array().log().sum();
42 
43  check_finite("log_determinant_spd",
44  "log determininant of the matrix argument", val);
45 
46  vari** operands
48  for (int i = 0; i < m.size(); ++i)
49  operands[i] = m(i).vi_;
50 
51  double* gradients
52  = ChainableStack::instance_->memalloc_.alloc_array<double>(m.size());
53  for (int i = 0; i < m.size(); ++i)
54  gradients[i] = m_d(i);
55 
56  return var(
57  new precomputed_gradients_vari(val, m.size(), operands, gradients));
58 }
59 
60 } // namespace math
61 
62 } // namespace stan
63 #endif
void check_finite(const char *function, const char *name, const T_y &y)
Check if y is finite.
void check_square(const char *function, const char *name, const matrix_cl &y)
Check if the matrix_cl is square.
The variable implementation base class.
Definition: vari.hpp:30
static STAN_THREADS_DEF AutodiffStackStorage * instance_
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:33
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.
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:87
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–2018, Stan Development Team.