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>
38Eigen::Matrix<value_type_t<T>, Eigen::Dynamic, 1> cov_matrix_free(const T& y) {
39 const auto& y_ref = to_ref(y);
40 check_square("cov_matrix_free", "y", y_ref);
41 check_nonzero_size("cov_matrix_free", "y", y_ref);
42
43 using std::log;
44 int K = y_ref.rows();
45 check_positive("cov_matrix_free", "y", y_ref.diagonal());
46 Eigen::Matrix<value_type_t<T>, Eigen::Dynamic, 1> x((K * (K + 1)) / 2);
47 // FIXME: see Eigen LDLT for rank-revealing version -- use that
48 // even if less efficient?
49 Eigen::LLT<plain_type_t<T>> llt(y_ref.rows());
50 llt.compute(y_ref);
51 plain_type_t<T> L = llt.matrixL();
52 int i = 0;
53 for (int m = 0; m < K; ++m) {
54 x.segment(i, m) = L.row(m).head(m);
55 i += m;
56 x.coeffRef(i++) = log(L.coeff(m, m));
57 }
58 return x;
59}
60
68template <typename T, require_std_vector_t<T>* = nullptr>
69auto cov_matrix_free(const T& x) {
71 x, [](auto&& v) { return cov_matrix_free(v); });
72}
73
74} // namespace math
75} // namespace stan
76
77#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...
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:17
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.
typename plain_type< T >::type plain_type_t
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...