Automatic Differentiation
 
Loading...
Searching...
No Matches
multinomial_lpmf.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_PROB_MULTINOMIAL_LPMF_HPP
2#define STAN_MATH_PRIM_PROB_MULTINOMIAL_LPMF_HPP
3
9#include <vector>
10
11namespace stan {
12namespace math {
13// Multinomial(ns|N, theta) [0 <= n <= N; SUM ns = N;
14// 0 <= theta[n] <= 1; SUM theta = 1]
15template <bool propto, typename T_prob,
16 require_eigen_col_vector_t<T_prob>* = nullptr>
17return_type_t<T_prob> multinomial_lpmf(const std::vector<int>& ns,
18 const T_prob& theta) {
19 static constexpr const char* function = "multinomial_lpmf";
20 check_size_match(function, "Size of number of trials variable", ns.size(),
21 "rows of probabilities parameter", theta.rows());
22 check_nonnegative(function, "Number of trials variable", ns);
23 const auto& theta_ref = to_ref(theta);
24 check_simplex(function, "Probabilities parameter", theta_ref);
25
27
29 double sum = 1.0;
30 for (int n : ns) {
31 sum += n;
32 lp -= lgamma(n + 1.0);
33 }
34 lp += lgamma(sum);
35 }
37 for (unsigned int i = 0; i < ns.size(); ++i) {
38 lp += multiply_log(ns[i], theta_ref.coeff(i));
39 }
40 }
41 return lp;
42}
43
44template <typename T_prob>
45return_type_t<T_prob> multinomial_lpmf(const std::vector<int>& ns,
46 const T_prob& theta) {
47 return multinomial_lpmf<false>(ns, theta);
48}
49
50} // namespace math
51} // namespace stan
52#endif
typename return_type< Ts... >::type return_type_t
Convenience type for the return type of the specified template parameters.
fvar< T > multiply_log(const fvar< T > &x1, const fvar< T > &x2)
void check_nonnegative(const char *function, const char *name, const T_y &y)
Check if y is non-negative.
return_type_t< T_prob > multinomial_lpmf(const std::vector< int > &ns, const T_prob &theta)
fvar< T > sum(const std::vector< fvar< T > > &m)
Return the sum of the entries of the specified standard vector.
Definition sum.hpp:22
void check_simplex(const char *function, const char *name, const T &theta)
Throw an exception if the specified vector is not a simplex.
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:17
fvar< T > lgamma(const fvar< T > &x)
Return the natural logarithm of the gamma function applied to the specified argument.
Definition lgamma.hpp:21
void check_size_match(const char *function, const char *name_i, T_size1 i, const char *name_j, T_size2 j)
Check if the provided sizes match.
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...
Definition fvar.hpp:9
Template metaprogram to calculate whether a summand needs to be included in a proportional (log) prob...