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
12
13namespace stan {
14namespace math {
15
23template <typename T, require_rev_matrix_t<T>* = nullptr>
24inline var log_determinant_spd(const T& M) {
25 if (M.size() == 0) {
26 return var(0.0);
27 }
28 check_symmetric("log_determinant", "M", M);
29
30 arena_t<T> arena_M = M;
31 matrix_d M_d = arena_M.val();
32 auto M_ldlt = M_d.ldlt();
33 if (M_ldlt.info() != Eigen::Success) {
34 constexpr double y = 0;
35 throw_domain_error("log_determinant_spd", "matrix argument", y,
36 "failed LDLT factorization");
37 }
38 // compute the inverse of A (needed for the derivative)
39 M_d.setIdentity(M.rows(), M.cols());
40 M_ldlt.solveInPlace(M_d);
41 auto arena_M_inv_transpose = to_arena(M_d.transpose());
42
43 if (M_ldlt.isNegative() || (M_ldlt.vectorD().array() <= 1e-16).any()) {
44 constexpr double y = 0;
45 throw_domain_error("log_determinant_spd", "matrix argument", y,
46 "matrix is negative definite");
47 }
48
49 var log_det = sum(log(M_ldlt.vectorD()));
50
51 reverse_pass_callback([arena_M, log_det, arena_M_inv_transpose]() mutable {
52 arena_M.adj() += log_det.adj() * arena_M_inv_transpose;
53 });
54 return log_det;
55}
56
57} // namespace math
58} // namespace stan
59#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:15
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
fvar< T > sum(const std::vector< fvar< T > > &m)
Return the sum of the entries of the specified standard vector.
Definition sum.hpp:22
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 ...