Stan Math Library  2.6.3
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros
read_corr_L.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_FUN_READ_CORR_L_HPP
2 #define STAN_MATH_PRIM_MAT_FUN_READ_CORR_L_HPP
3 
8 #include <cstddef>
9 #include <iostream>
10 
11 namespace stan {
12 
13  namespace math {
14 
15 
16  // MATRIX TRANSFORMS +/- JACOBIANS
17 
39  template <typename T>
40  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
41  read_corr_L(const Eigen::Array<T, Eigen::Dynamic, 1>& CPCs, // on (-1, 1)
42  const size_t K) {
43  Eigen::Array<T, Eigen::Dynamic, 1> temp;
44  Eigen::Array<T, Eigen::Dynamic, 1> acc(K-1);
45  acc.setOnes();
46  // Cholesky factor of correlation matrix
47  Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> L(K, K);
48  L.setZero();
49 
50  size_t position = 0;
51  size_t pull = K - 1;
52 
53  L(0, 0) = 1.0;
54  L.col(0).tail(pull) = temp = CPCs.head(pull);
55  acc.tail(pull) = T(1.0) - temp.square();
56  for (size_t i = 1; i < (K - 1); i++) {
57  position += pull;
58  pull--;
59  temp = CPCs.segment(position, pull);
60  L(i, i) = sqrt(acc(i-1));
61  L.col(i).tail(pull) = temp * acc.tail(pull).sqrt();
62  acc.tail(pull) *= T(1.0) - temp.square();
63  }
64  L(K-1, K-1) = sqrt(acc(K-2));
65  return L.matrix();
66  }
67 
68 
93  template <typename T>
94  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
95  read_corr_L(const Eigen::Array<T, Eigen::Dynamic, 1>& CPCs,
96  const size_t K,
97  T& log_prob) {
98  using stan::math::log1m;
99  using stan::math::square;
100  using stan::math::sum;
101 
102  Eigen::Matrix<T, Eigen::Dynamic, 1> values(CPCs.rows() - 1);
103  size_t pos = 0;
104  // no need to abs() because this Jacobian determinant
105  // is strictly positive (and triangular)
106  // see inverse of Jacobian in equation 11 of LKJ paper
107  for (size_t k = 1; k <= (K - 2); k++)
108  for (size_t i = k + 1; i <= K; i++) {
109  values(pos) = (K - k - 1) * log1m(square(CPCs(pos)));
110  pos++;
111  }
112 
113  log_prob += 0.5 * sum(values);
114  return read_corr_L(CPCs, K);
115  }
116 
117  }
118 
119 }
120 
121 #endif
fvar< T > sum(const std::vector< fvar< T > > &m)
Return the sum of the entries of the specified standard vector.
Definition: sum.hpp:20
fvar< T > sqrt(const fvar< T > &x)
Definition: sqrt.hpp:15
fvar< T > square(const fvar< T > &x)
Definition: square.hpp:15
Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > read_corr_L(const Eigen::Array< T, Eigen::Dynamic, 1 > &CPCs, const size_t K)
Return the Cholesky factor of the correlation matrix of the specified dimensionality corresponding to...
Definition: read_corr_L.hpp:41
fvar< T > log1m(const fvar< T > &x)
Definition: log1m.hpp:16

     [ Stan Home Page ] © 2011–2015, Stan Development Team.