Automatic Differentiation
 
Loading...
Searching...
No Matches
multinomial_logit_rng.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_PROB_MULTINOMIAL_LOGIT_RNG_HPP
2#define STAN_MATH_PRIM_PROB_MULTINOMIAL_LOGIT_RNG_HPP
3
9#include <vector>
10
11namespace stan {
12namespace math {
13
27template <class RNG, typename T_beta,
28 require_eigen_col_vector_t<T_beta>* = nullptr>
29inline std::vector<int> multinomial_logit_rng(const T_beta& beta, int N,
30 RNG& rng) {
31 static constexpr const char* function = "multinomial_logit_rng";
32 const auto& beta_ref = to_ref(beta);
33 check_finite(function, "Log-probabilities parameter", beta_ref);
34 check_nonnegative(function, "number of trials variables", N);
35
36 plain_type_t<T_beta> theta = softmax(beta_ref);
37 std::vector<int> result(theta.size(), 0);
38 double mass_left = 1.0;
39 int n_left = N;
40
41 for (int k = 0; n_left > 0 && k < theta.size(); ++k) {
42 double p = theta.coeff(k) / mass_left;
43 if (p > 1.0) {
44 p = 1.0;
45 }
46 result[k] = binomial_rng(n_left, p, rng);
47 n_left -= result[k];
48 mass_left -= theta.coeff(k);
49 }
50
51 return result;
52} // namespace math
53
54} // namespace math
55} // namespace stan
56#endif
std::vector< int > multinomial_logit_rng(const T_beta &beta, int N, RNG &rng)
Return a draw from a Multinomial distribution given a vector of unnormalized log probabilities,...
VectorBuilder< true, int, T_N, T_theta >::type binomial_rng(const T_N &N, const T_theta &theta, RNG &rng)
Return a pseudorandom binomial random variable for the given population size and chance of success pa...
void check_nonnegative(const char *function, const char *name, const T_y &y)
Check if y is non-negative.
auto softmax(const ColVec &alpha)
Definition softmax.hpp:16
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:17
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
typename plain_type< T >::type plain_type_t
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...