Automatic Differentiation
 
Loading...
Searching...
No Matches
cov_matrix_free.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_CONSTRAINT_COV_MATRIX_FREE_HPP
2#define STAN_MATH_PRIM_CONSTRAINT_COV_MATRIX_FREE_HPP
3
9#include <cmath>
10
11namespace stan {
12namespace math {
13
37template <typename T, require_eigen_t<T>* = nullptr>
38inline Eigen::Matrix<value_type_t<T>, Eigen::Dynamic, 1> cov_matrix_free(
39 const T& y) {
40 const auto& y_ref = to_ref(y);
41 check_square("cov_matrix_free", "y", y_ref);
42 check_nonzero_size("cov_matrix_free", "y", y_ref);
43
44 using std::log;
45 int K = y_ref.rows();
46 check_positive("cov_matrix_free", "y", y_ref.diagonal());
47 Eigen::Matrix<value_type_t<T>, Eigen::Dynamic, 1> x((K * (K + 1)) / 2);
48 // FIXME: see Eigen LDLT for rank-revealing version -- use that
49 // even if less efficient?
50 Eigen::LLT<plain_type_t<T>> llt(y_ref.rows());
51 llt.compute(y_ref);
52 plain_type_t<T> L = llt.matrixL();
53 int i = 0;
54 for (int m = 0; m < K; ++m) {
55 x.segment(i, m) = L.row(m).head(m);
56 i += m;
57 x.coeffRef(i++) = log(L.coeff(m, m));
58 }
59 return x;
60}
61
69template <typename T, require_std_vector_t<T>* = nullptr>
70inline auto cov_matrix_free(T&& x) {
71 return apply_vector_unary<T>::apply(std::forward<T>(x), [](auto&& v) {
72 return cov_matrix_free(std::forward<decltype(v)>(v));
73 });
74}
75
76} // namespace math
77} // namespace stan
78
79#endif
void check_square(const char *function, const char *name, const T_y &y)
Check if the specified matrix is square.
fvar< T > log(const fvar< T > &x)
Definition log.hpp:18
Eigen::Matrix< value_type_t< T >, Eigen::Dynamic, 1 > cov_matrix_free(const T &y)
The covariance matrix derived from the symmetric view of the lower-triangular view of the K by K spec...
void check_nonzero_size(const char *function, const char *name, const T_y &y)
Check if the specified matrix/vector is of non-zero size.
void check_positive(const char *function, const char *name, const T_y &y)
Check if y is positive.
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:18
typename plain_type< std::decay_t< T > >::type plain_type_t
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...