Automatic Differentiation
 
Loading...
Searching...
No Matches
log_determinant_spd.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_REV_FUN_LOG_DETERMINANT_SPD_HPP
2#define STAN_MATH_REV_FUN_LOG_DETERMINANT_SPD_HPP
3
13
14namespace stan {
15namespace math {
16
24template <typename T, require_rev_matrix_t<T>* = nullptr>
25inline var log_determinant_spd(const T& M) {
26 if (M.size() == 0) {
27 return var(0.0);
28 }
29 check_symmetric("log_determinant", "M", M);
30
31 arena_t<T> arena_M = M;
32 matrix_d M_d = arena_M.val();
33 auto M_ldlt = M_d.ldlt();
34 if (M_ldlt.info() != Eigen::Success) {
35 constexpr double y = 0;
36 throw_domain_error("log_determinant_spd", "matrix argument", y,
37 "failed LDLT factorization");
38 }
39 // compute the inverse of A (needed for the derivative)
40 M_d.setIdentity(M.rows(), M.cols());
41 M_ldlt.solveInPlace(M_d);
42 auto arena_M_inv_transpose = to_arena(M_d.transpose());
43
44 if (M_ldlt.isNegative() || (M_ldlt.vectorD().array() <= 1e-16).any()) {
45 constexpr double y = 0;
46 throw_domain_error("log_determinant_spd", "matrix argument", y,
47 "matrix is negative definite");
48 }
49
50 var log_det = sum(log(M_ldlt.vectorD()));
51
52 reverse_pass_callback([arena_M, log_det, arena_M_inv_transpose]() mutable {
53 arena_M.adj() += log_det.adj() * arena_M_inv_transpose;
54 });
55 return log_det;
56}
57
58} // namespace math
59} // namespace stan
60#endif
void check_symmetric(const char *function, const char *name, const matrix_cl< T > &y)
Check if the matrix_cl is symmetric.
static constexpr double e()
Return the base of the natural logarithm.
Definition constants.hpp:20
value_type_t< EigMat > log_determinant_spd(const EigMat &m)
Returns the log absolute determinant of the specified square matrix.
void reverse_pass_callback(F &&functor)
Puts a callback on the autodiff stack to be called in reverse pass.
fvar< T > log(const fvar< T > &x)
Definition log.hpp:18
void throw_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.
arena_t< T > to_arena(const T &a)
Converts given argument into a type that either has any dynamic allocation on AD stack or schedules i...
Definition to_arena.hpp:25
auto sum(const std::vector< T > &m)
Return the sum of the entries of the specified standard vector.
Definition sum.hpp:23
var_value< double > var
Definition var.hpp:1187
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > matrix_d
Type for matrix of double values.
Definition typedefs.hpp:19
typename internal::arena_type_impl< std::decay_t< T > >::type arena_t
Determines a type that can be used in place of T that does any dynamic allocations on the AD stack.
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...