Automatic Differentiation
 
Loading...
Searching...
No Matches
categorical_logit_rng.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_PROB_CATEGORICAL_LOGIT_RNG_HPP
2#define STAN_MATH_PRIM_PROB_CATEGORICAL_LOGIT_RNG_HPP
3
9#include <boost/random/uniform_01.hpp>
10#include <boost/random/variate_generator.hpp>
11
12namespace stan {
13namespace math {
14
28template <class RNG>
29inline int categorical_logit_rng(const Eigen::VectorXd& beta, RNG& rng) {
30 using boost::uniform_01;
31 using boost::variate_generator;
32 static constexpr const char* function = "categorical_logit_rng";
33 check_finite(function, "Log odds parameter", beta);
34
35 variate_generator<RNG&, uniform_01<> > uniform01_rng(rng, uniform_01<>());
36 Eigen::VectorXd theta = softmax(beta);
37 Eigen::VectorXd index = cumulative_sum(theta);
38
39 double c = uniform01_rng();
40 int b = 0;
41 while (c > index(b)) {
42 b++;
43 }
44 return b + 1;
45}
46} // namespace math
47} // namespace stan
48#endif
int categorical_logit_rng(const Eigen::VectorXd &beta, RNG &rng)
Return a draw from a Categorical distribution given a a vector of unnormalized log probabilities and ...
auto softmax(const ColVec &alpha)
Definition softmax.hpp:16
auto cumulative_sum(T_vec &&v)
Return the cumulative sum of the specified vector.
void check_finite(const char *function, const char *name, const T_y &y)
Return true if all values in y are finite.
fvar< T > beta(const fvar< T > &x1, const fvar< T > &x2)
Return fvar with the beta function applied to the specified arguments and its gradient.
Definition beta.hpp:51
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...