Automatic Differentiation
 
Loading...
Searching...
No Matches
simplex_free.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_FUN_SIMPLEX_FREE_HPP
2#define STAN_MATH_PRIM_FUN_SIMPLEX_FREE_HPP
3
10#include <cmath>
11
12namespace stan {
13namespace math {
14
29template <typename Vec, require_eigen_vector_t<Vec>* = nullptr>
30inline plain_type_t<Vec> simplex_free(const Vec& x) {
31 using std::log;
32 using T = value_type_t<Vec>;
33
34 const auto& x_ref = to_ref(x);
35 check_simplex("stan::math::simplex_free", "Simplex variable", x_ref);
36 Eigen::Index Km1 = x_ref.size() - 1;
37 plain_type_t<Vec> y(Km1);
38 T stick_len = x_ref.coeff(Km1);
39 for (Eigen::Index k = Km1; --k >= 0;) {
40 stick_len += x_ref.coeff(k);
41 T z_k = x_ref.coeff(k) / stick_len;
42 y.coeffRef(k) = logit(z_k) + log(Km1 - k);
43 // note: log(Km1 - k) = logit(1.0 / (Km1 + 1 - k));
44 }
45 return y;
46}
47
55template <typename T, require_std_vector_t<T>* = nullptr>
56auto simplex_free(const T& x) {
58 [](auto&& v) { return simplex_free(v); });
59}
60
61} // namespace math
62} // namespace stan
63
64#endif
typename value_type< T >::type value_type_t
Helper function for accessing underlying type.
fvar< T > logit(const fvar< T > &x)
Definition logit.hpp:14
fvar< T > log(const fvar< T > &x)
Definition log.hpp:15
plain_type_t< Vec > simplex_free(const Vec &x)
Return an unconstrained vector that when transformed produces the specified simplex.
void check_simplex(const char *function, const char *name, const T &theta)
Throw an exception if the specified vector is not a simplex.
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:17
typename plain_type< T >::type plain_type_t
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...
Definition fvar.hpp:9