Stan Math Library  2.8.0
reverse mode automatic differentiation
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Groups
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 
18  namespace math {
19  // Multinomial(ns|N, theta) [0 <= n <= N; SUM ns = N;
20  // 0 <= theta[n] <= 1; SUM theta = 1]
21  template <bool propto,
22  typename T_prob>
23  typename boost::math::tools::promote_args<T_prob>::type
24  multinomial_log(const std::vector<int>& ns,
25  const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& theta) {
26  static const char* function("stan::math::multinomial_log");
27 
31  using boost::math::tools::promote_args;
32  using boost::math::lgamma;
33 
34  typename promote_args<T_prob>::type lp(0.0);
35  check_nonnegative(function, "Number of trials variable", ns);
36  check_simplex(function, "Probabilites parameter", theta);
37  check_size_match(function,
38  "Size of number of trials variable", ns.size(),
39  "rows of probabilities parameter", theta.rows());
41 
43  double sum = 1.0;
44  for (unsigned int i = 0; i < ns.size(); ++i)
45  sum += ns[i];
46  lp += lgamma(sum);
47  for (unsigned int i = 0; i < ns.size(); ++i)
48  lp -= lgamma(ns[i] + 1.0);
49  }
51  for (unsigned int i = 0; i < ns.size(); ++i)
52  lp += multiply_log(ns[i], theta[i]);
53  }
54  return lp;
55  }
56 
57  template <typename T_prob>
58  typename boost::math::tools::promote_args<T_prob>::type
59  multinomial_log(const std::vector<int>& ns,
60  const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& theta) {
61  return multinomial_log<false>(ns, theta);
62  }
63 
64  }
65 }
66 #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
fvar< T > lgamma(const fvar< T > &x)
Definition: lgamma.hpp:15
Template metaprogram to calculate whether a summand needs to be included in a proportional (log) prob...
bool check_size_match(const char *function, const char *name_i, T_size1 i, const char *name_j, T_size2 j)
Return true if the provided sizes match.
fvar< T > multiply_log(const fvar< T > &x1, const fvar< T > &x2)
bool check_simplex(const char *function, const char *name, const Eigen::Matrix< T_prob, Eigen::Dynamic, 1 > &theta)
Return true if the specified vector is simplex.
boost::math::tools::promote_args< T_prob >::type multinomial_log(const std::vector< int > &ns, const Eigen::Matrix< T_prob, Eigen::Dynamic, 1 > &theta)
bool check_nonnegative(const char *function, const char *name, const T_y &y)
Return true if y is non-negative.

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