Stan Math Library  2.20.0
reverse mode automatic differentiation
dirichlet_rng.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_PROB_DIRICHLET_RNG_HPP
2 #define STAN_MATH_PRIM_MAT_PROB_DIRICHLET_RNG_HPP
3 
5 #include <boost/math/special_functions/gamma.hpp>
6 #include <boost/random/gamma_distribution.hpp>
7 #include <boost/random/uniform_real_distribution.hpp>
8 #include <boost/random/variate_generator.hpp>
10 #include <cmath>
11 
12 namespace stan {
13 namespace math {
14 
36 template <class RNG>
37 inline Eigen::VectorXd dirichlet_rng(
38  const Eigen::Matrix<double, Eigen::Dynamic, 1>& alpha, RNG& rng) {
39  using Eigen::VectorXd;
40  using boost::gamma_distribution;
41  using boost::random::uniform_real_distribution;
42  using boost::variate_generator;
43  using std::exp;
44  using std::log;
45 
46  // separate algorithm if any parameter is less than 1
47  if (alpha.minCoeff() < 1) {
48  variate_generator<RNG&, uniform_real_distribution<> > uniform_rng(
49  rng, uniform_real_distribution<>(0.0, 1.0));
50  VectorXd log_y(alpha.size());
51  for (int i = 0; i < alpha.size(); ++i) {
52  variate_generator<RNG&, gamma_distribution<> > gamma_rng(
53  rng, gamma_distribution<>(alpha(i) + 1, 1));
54  double log_u = log(uniform_rng());
55  log_y(i) = log(gamma_rng()) + log_u / alpha(i);
56  }
57  double log_sum_y = log_sum_exp(log_y);
58  VectorXd theta(alpha.size());
59  for (int i = 0; i < alpha.size(); ++i)
60  theta(i) = exp(log_y(i) - log_sum_y);
61  return theta;
62  }
63 
64  // standard normalized gamma algorithm
65  Eigen::VectorXd y(alpha.rows());
66  for (int i = 0; i < alpha.rows(); i++) {
67  variate_generator<RNG&, gamma_distribution<> > gamma_rng(
68  rng, gamma_distribution<>(alpha(i, 0), 1e-7));
69  y(i) = gamma_rng();
70  }
71  return y / y.sum();
72 }
73 
74 } // namespace math
75 } // namespace stan
76 #endif
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:12
fvar< T > log_sum_exp(const std::vector< fvar< T > > &v)
Definition: log_sum_exp.hpp:12
VectorBuilder< true, double, T_alpha, T_beta >::type uniform_rng(const T_alpha &alpha, const T_beta &beta, RNG &rng)
Return a uniform random variate for the given upper and lower bounds using the specified random numbe...
Definition: uniform_rng.hpp:36
Eigen::VectorXd dirichlet_rng(const Eigen::Matrix< double, Eigen::Dynamic, 1 > &alpha, RNG &rng)
Return a draw from a Dirichlet distribution with specified parameters and pseudo-random number genera...
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:11
VectorBuilder< true, double, T_shape, T_inv >::type gamma_rng(const T_shape &alpha, const T_inv &beta, RNG &rng)
Return a gamma random variate for the given shape and inverse scale parameters using the specified ra...
Definition: gamma_rng.hpp:33
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:87

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