Stan Math Library  2.20.0
reverse mode automatic differentiation
multinomial_lpmf.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_PROB_MULTINOMIAL_LPMF_HPP
2 #define STAN_MATH_PRIM_MAT_PROB_MULTINOMIAL_LPMF_HPP
3 
10 #include <vector>
11 
12 namespace stan {
13 namespace math {
14 // Multinomial(ns|N, theta) [0 <= n <= N; SUM ns = N;
15 // 0 <= theta[n] <= 1; SUM theta = 1]
16 template <bool propto, typename T_prob>
17 typename boost::math::tools::promote_args<T_prob>::type multinomial_lpmf(
18  const std::vector<int>& ns,
19  const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& theta) {
20  static const char* function = "multinomial_lpmf";
21 
22  using boost::math::tools::promote_args;
23 
24  typename promote_args<T_prob>::type lp(0.0);
25  check_nonnegative(function, "Number of trials variable", ns);
26  check_simplex(function, "Probabilities parameter", theta);
27  check_size_match(function, "Size of number of trials variable", ns.size(),
28  "rows of probabilities parameter", theta.rows());
29 
31  double sum = 1.0;
32  for (int n : ns)
33  sum += n;
34  lp += lgamma(sum);
35  for (int n : ns)
36  lp -= lgamma(n + 1.0);
37  }
39  for (unsigned int i = 0; i < ns.size(); ++i)
40  lp += multiply_log(ns[i], theta[i]);
41  }
42  return lp;
43 }
44 
45 template <typename T_prob>
46 typename boost::math::tools::promote_args<T_prob>::type multinomial_lpmf(
47  const std::vector<int>& ns,
48  const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& theta) {
49  return multinomial_lpmf<false>(ns, theta);
50 }
51 
52 } // namespace math
53 } // namespace stan
54 #endif
fvar< T > sum(const std::vector< fvar< T > > &m)
Return the sum of the entries of the specified standard vector.
Definition: sum.hpp:20
void check_simplex(const char *function, const char *name, const Eigen::Matrix< T_prob, Eigen::Dynamic, 1 > &theta)
Check if the specified vector is simplex.
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.
Template metaprogram to calculate whether a summand needs to be included in a proportional (log) prob...
void check_nonnegative(const char *function, const char *name, const T_y &y)
Check if y is non-negative.
fvar< T > multiply_log(const fvar< T > &x1, const fvar< T > &x2)
boost::math::tools::promote_args< T_prob >::type multinomial_lpmf(const std::vector< int > &ns, const Eigen::Matrix< T_prob, Eigen::Dynamic, 1 > &theta)

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