Stan Math Library  2.14.0
reverse mode automatic differentiation
multinomial_log.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_PROB_MULTINOMIAL_LOG_HPP
2 #define STAN_MATH_PRIM_MAT_PROB_MULTINOMIAL_LOG_HPP
3 
4 #include <boost/math/special_functions/gamma.hpp>
5 #include <boost/random/uniform_01.hpp>
6 #include <boost/random/variate_generator.hpp>
14 #include <vector>
15 
16 namespace stan {
17  namespace math {
18  // Multinomial(ns|N, theta) [0 <= n <= N; SUM ns = N;
19  // 0 <= theta[n] <= 1; SUM theta = 1]
20  template <bool propto,
21  typename T_prob>
22  typename boost::math::tools::promote_args<T_prob>::type
23  multinomial_log(const std::vector<int>& ns,
24  const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& theta) {
25  static const char* function("multinomial_log");
26 
27  using boost::math::tools::promote_args;
28  using boost::math::lgamma;
29 
30  typename promote_args<T_prob>::type lp(0.0);
31  check_nonnegative(function, "Number of trials variable", ns);
32  check_simplex(function, "Probabilites parameter", theta);
33  check_size_match(function,
34  "Size of number of trials variable", ns.size(),
35  "rows of probabilities parameter", theta.rows());
36 
38  double sum = 1.0;
39  for (unsigned int i = 0; i < ns.size(); ++i)
40  sum += ns[i];
41  lp += lgamma(sum);
42  for (unsigned int i = 0; i < ns.size(); ++i)
43  lp -= lgamma(ns[i] + 1.0);
44  }
46  for (unsigned int i = 0; i < ns.size(); ++i)
47  lp += multiply_log(ns[i], theta[i]);
48  }
49  return lp;
50  }
51 
52  template <typename T_prob>
53  typename boost::math::tools::promote_args<T_prob>::type
54  multinomial_log(const std::vector<int>& ns,
55  const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& theta) {
56  return multinomial_log<false>(ns, theta);
57  }
58 
59  }
60 }
61 #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:20
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_log(const std::vector< int > &ns, const Eigen::Matrix< T_prob, Eigen::Dynamic, 1 > &theta)

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