Stan Math Library  2.14.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>
29  simplex_constrain(const Eigen::Matrix<T, Eigen::Dynamic, 1>& y) {
30  // cut & paste simplex_constrain(Eigen::Matrix, T) w/o Jacobian
31  using Eigen::Matrix;
32  using Eigen::Dynamic;
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>
63  simplex_constrain(const Eigen::Matrix<T, Eigen::Dynamic, 1>& y,
64  T& lp) {
65  using Eigen::Dynamic;
66  using Eigen::Matrix;
67  using std::log;
68 
69  typedef typename index_type<Matrix<T, Dynamic, 1> >::type size_type;
70 
71  int Km1 = y.size(); // K = Km1 + 1
72  Matrix<T, Dynamic, 1> x(Km1 + 1);
73  T stick_len(1.0);
74  for (size_type k = 0; k < Km1; ++k) {
75  double eq_share = -log(Km1 - k); // = logit(1.0/(Km1 + 1 - k));
76  T adj_y_k(y(k) + eq_share);
77  T z_k(inv_logit(adj_y_k));
78  x(k) = stick_len * z_k;
79  lp += log(stick_len);
80  lp -= log1p_exp(-adj_y_k);
81  lp -= log1p_exp(adj_y_k);
82  stick_len -= x(k); // equivalently *= (1 - z_k);
83  }
84  x(Km1) = stick_len; // no Jacobian contrib for last dim
85  return x;
86  }
87 
88  }
89 
90 }
91 
92 #endif
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:14
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:13
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:13
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–2016, Stan Development Team.