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
25template <class RNG, typename T_beta,
26 require_eigen_col_vector_t<T_beta>* = nullptr>
27inline std::vector<int> multinomial_logit_rng(const T_beta& beta, int N,
28 RNG& rng) {
29 static constexpr const char* function = "multinomial_logit_rng";
30 const auto& beta_ref = to_ref(beta);
31 check_finite(function, "Log-probabilities parameter", beta_ref);
32 check_positive(function, "number of trials variables", N);
33
34 plain_type_t<T_beta> theta = softmax(beta_ref);
35 std::vector<int> result(theta.size(), 0);
36 double mass_left = 1.0;
37 int n_left = N;
38
39 for (int k = 0; n_left > 0 && k < theta.size(); ++k) {
40 double p = theta.coeff(k) / mass_left;
41 if (p > 1.0) {
42 p = 1.0;
43 }
44 result[k] = binomial_rng(n_left, p, rng);
45 n_left -= result[k];
46 mass_left -= theta.coeff(k);
47 }
48
49 return result;
50} // namespace math
51
52} // namespace math
53} // namespace stan
54#endif
std::vector< int > multinomial_logit_rng(const T_beta &beta, int N, RNG &rng)
Return a draw from a Multinomial distribution given a a vector of unnormalized log probabilities and ...
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...
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.
void check_positive(const char *function, const char *name, const T_y &y)
Check if y is positive.
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 ...
Definition fvar.hpp:9