Stan Math Library  2.20.0
reverse mode automatic differentiation
simplex_constrain.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_FUN_SIMPLEX_CONSTRAIN_HPP
2 #define STAN_MATH_PRIM_MAT_FUN_SIMPLEX_CONSTRAIN_HPP
3 
10 #include <cmath>
11 
12 namespace stan {
13 namespace math {
14 
27 template <typename T>
28 Eigen::Matrix<T, Eigen::Dynamic, 1> simplex_constrain(
29  const Eigen::Matrix<T, Eigen::Dynamic, 1>& y) {
30  // cut & paste simplex_constrain(Eigen::Matrix, T) w/o Jacobian
31  using Eigen::Dynamic;
32  using Eigen::Matrix;
33  using std::log;
34  typedef typename index_type<Matrix<T, Dynamic, 1> >::type size_type;
35 
36  int Km1 = y.size();
37  Matrix<T, Dynamic, 1> x(Km1 + 1);
38  T stick_len(1.0);
39  for (size_type k = 0; k < Km1; ++k) {
40  T z_k(inv_logit(y(k) - log(Km1 - k)));
41  x(k) = stick_len * z_k;
42  stick_len -= x(k);
43  }
44  x(Km1) = stick_len;
45  return x;
46 }
47 
61 template <typename T>
62 Eigen::Matrix<T, Eigen::Dynamic, 1> simplex_constrain(
63  const Eigen::Matrix<T, Eigen::Dynamic, 1>& y, T& lp) {
64  using Eigen::Dynamic;
65  using Eigen::Matrix;
66  using std::log;
67 
68  typedef typename index_type<Matrix<T, Dynamic, 1> >::type size_type;
69 
70  int Km1 = y.size(); // K = Km1 + 1
71  Matrix<T, Dynamic, 1> x(Km1 + 1);
72  T stick_len(1.0);
73  for (size_type k = 0; k < Km1; ++k) {
74  double eq_share = -log(Km1 - k); // = logit(1.0/(Km1 + 1 - k));
75  T adj_y_k(y(k) + eq_share);
76  T z_k(inv_logit(adj_y_k));
77  x(k) = stick_len * z_k;
78  lp += log(stick_len);
79  lp -= log1p_exp(-adj_y_k);
80  lp -= log1p_exp(adj_y_k);
81  stick_len -= x(k); // equivalently *= (1 - z_k);
82  }
83  x(Km1) = stick_len; // no Jacobian contrib for last dim
84  return x;
85 }
86 
87 } // namespace math
88 
89 } // namespace stan
90 
91 #endif
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:12
fvar< T > inv_logit(const fvar< T > &x)
Returns the inverse logit function applied to the argument.
Definition: inv_logit.hpp:20
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic >::Index size_type
Type for sizes and indexes in an Eigen matrix with double e.
Definition: typedefs.hpp:11
Primary template class for the metaprogram to compute the index type of a container.
Definition: index_type.hpp:18
fvar< T > log1p_exp(const fvar< T > &x)
Definition: log1p_exp.hpp:12
Eigen::Matrix< T, Eigen::Dynamic, 1 > simplex_constrain(const Eigen::Matrix< T, Eigen::Dynamic, 1 > &y)
Return the simplex corresponding to the specified free vector.

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