All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Groups
cholesky_factor_constrain.hpp
Go to the documentation of this file.
#ifndef STAN_MATH_PRIM_MAT_FUN_CHOLESKY_FACTOR_CONSTRAIN_HPP
#define STAN_MATH_PRIM_MAT_FUN_CHOLESKY_FACTOR_CONSTRAIN_HPP
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/sum.hpp>
#include <cmath>
#include <stdexcept>
#include <vector>
namespace stan {
namespace math {
// CHOLESKY FACTOR
template <typename T>
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
cholesky_factor_constrain(const Eigen::Matrix<T, Eigen::Dynamic, 1>& x,
int M,
int N) {
using std::exp;
if (M < N)
throw std::domain_error("cholesky_factor_constrain: "
"num rows must be >= num cols");
if (x.size() != ((N * (N + 1)) / 2 + (M - N) * N))
throw std::domain_error("cholesky_factor_constrain: x.size() must"
" be (N * (N + 1)) / 2 + (M - N) * N");
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> y(M, N);
T zero(0);
int pos = 0;
// upper square
for (int m = 0; m < N; ++m) {
for (int n = 0; n < m; ++n)
y(m, n) = x(pos++);
y(m, m) = exp(x(pos++));
for (int n = m + 1; n < N; ++n)
y(m, n) = zero;
}
// lower rectangle
for (int m = N; m < M; ++m)
for (int n = 0; n < N; ++n)
y(m, n) = x(pos++);
return y;
}
template <typename T>
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
cholesky_factor_constrain(const Eigen::Matrix<T, Eigen::Dynamic, 1>& x,
int M,
int N,
T& lp) {
// cut-and-paste from above, so checks twice
using stan::math::sum;
if (x.size() != ((N * (N + 1)) / 2 + (M - N) * N))
throw std::domain_error("cholesky_factor_constrain: x.size() "
"must be (k choose 2) + k");
int pos = 0;
std::vector<T> log_jacobians(N);
for (int n = 0; n < N; ++n) {
pos += n;
log_jacobians[n] = x(pos++);
}
lp += sum(log_jacobians); // optimized for autodiff vs. direct lp +=
return cholesky_factor_constrain(x, M, N);
}
}
}
#endif
stan::math::sum
fvar< T > sum(const std::vector< fvar< T > > &m)
Return the sum of the entries of the specified standard vector.
Definition: sum.hpp:20
stan::math::cholesky_factor_constrain
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.
Definition: cholesky_factor_constrain.hpp:29
stan::math::exp
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:10
stan::math::domain_error
void domain_error(const char *function, const char *name, const T &y, const char *msg1, const char *msg2)
Throw a domain error with a consistently formatted message.
Definition: domain_error.hpp:32
Eigen.hpp
sum.hpp

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