Automatic Differentiation
 
Loading...
Searching...
No Matches
cholesky_corr_free.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_CONSTRAINT_CHOLESKY_CORR_FREE_HPP
2#define STAN_MATH_PRIM_CONSTRAINT_CHOLESKY_CORR_FREE_HPP
3
8#include <cmath>
9
10namespace stan {
11namespace math {
12
13template <typename T, require_eigen_t<T>* = nullptr>
14inline auto cholesky_corr_free(const T& x) {
15 using Eigen::Dynamic;
16 using Eigen::Matrix;
17 using std::sqrt;
18
19 const auto& x_ref = to_ref(x);
20 check_cholesky_factor_corr("cholesky_corr_free", "x", x_ref);
21
22 int K = (x.rows() * (x.rows() - 1)) / 2;
23 Matrix<value_type_t<T>, Dynamic, 1> z(K);
24 int k = 0;
25 for (int i = 1; i < x.rows(); ++i) {
26 z.coeffRef(k++) = corr_free(x_ref.coeff(i, 0));
27 auto sum_sqs = square(x_ref.coeff(i, 0));
28 for (int j = 1; j < i; ++j) {
29 z.coeffRef(k++) = corr_free(x_ref.coeff(i, j) / sqrt(1.0 - sum_sqs));
30 sum_sqs += square(x_ref.coeff(i, j));
31 }
32 }
33 return z;
34}
35
43template <typename T, require_std_vector_t<T>* = nullptr>
44inline auto cholesky_corr_free(T&& x) {
45 return apply_vector_unary<T>::apply(std::forward<T>(x), [](auto&& v) {
46 return cholesky_corr_free(std::forward<decltype(v)>(v));
47 });
48}
49
50} // namespace math
51} // namespace stan
52#endif
auto cholesky_corr_free(const T &x)
plain_type_t< T > corr_free(T &&y)
Return the unconstrained scalar that when transformed to a valid correlation produces the specified v...
Definition corr_free.hpp:28
void check_cholesky_factor_corr(const char *function, const char *name, const Mat &y)
Throw an exception if the specified matrix is not a valid Cholesky factor of a correlation matrix.
fvar< T > sqrt(const fvar< T > &x)
Definition sqrt.hpp:18
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:18
fvar< T > square(const fvar< T > &x)
Definition square.hpp:12
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...