Stan Math Library  2.20.0
reverse mode automatic differentiation
cholesky_factor_constrain.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_FUN_CHOLESKY_FACTOR_CONSTRAIN_HPP
2 #define STAN_MATH_PRIM_MAT_FUN_CHOLESKY_FACTOR_CONSTRAIN_HPP
3 
8 #include <cmath>
9 #include <stdexcept>
10 #include <vector>
11 
12 namespace stan {
13 namespace math {
14 
26 template <typename T>
27 Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> cholesky_factor_constrain(
28  const Eigen::Matrix<T, Eigen::Dynamic, 1>& x, int M, int N) {
29  using std::exp;
30  check_greater_or_equal("cholesky_factor_constrain",
31  "num rows (must be greater or equal to num cols)", M,
32  N);
33  check_size_match("cholesky_factor_constrain", "x.size()", x.size(),
34  "((N * (N + 1)) / 2 + (M - N) * N)",
35  ((N * (N + 1)) / 2 + (M - N) * N));
36  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> y(M, N);
37  T zero(0);
38  int pos = 0;
39 
40  for (int m = 0; m < N; ++m) {
41  for (int n = 0; n < m; ++n)
42  y(m, n) = x(pos++);
43  y(m, m) = exp(x(pos++));
44  for (int n = m + 1; n < N; ++n)
45  y(m, n) = zero;
46  }
47 
48  for (int m = N; m < M; ++m)
49  for (int n = 0; n < N; ++n)
50  y(m, n) = x(pos++);
51  return y;
52 }
53 
68 template <typename T>
69 Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> cholesky_factor_constrain(
70  const Eigen::Matrix<T, Eigen::Dynamic, 1>& x, int M, int N, T& lp) {
71  check_size_match("cholesky_factor_constrain", "x.size()", x.size(),
72  "((N * (N + 1)) / 2 + (M - N) * N)",
73  ((N * (N + 1)) / 2 + (M - N) * N));
74  int pos = 0;
75  std::vector<T> log_jacobians(N);
76  for (int n = 0; n < N; ++n) {
77  pos += n;
78  log_jacobians[n] = x(pos++);
79  }
80  lp += sum(log_jacobians);
81  return cholesky_factor_constrain(x, M, N);
82 }
83 
84 } // namespace math
85 } // namespace stan
86 #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
void check_size_match(const char *function, const char *name_i, T_size1 i, const char *name_j, T_size2 j)
Check if the provided sizes match.
void check_greater_or_equal(const char *function, const char *name, const T_y &y, const T_low &low)
Check if y is greater or equal than low.
Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > cholesky_factor_constrain(const Eigen::Matrix< T, Eigen::Dynamic, 1 > &x, int M, int N)
Return the Cholesky factor of the specified size read from the specified vector.
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:11

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