1 #ifndef STAN_MATH_PRIM_FUN_PROB_CONSTRAIN_HPP
2 #define STAN_MATH_PRIM_FUN_PROB_CONSTRAIN_HPP
3 
4 #include <stan/math/prim/meta.hpp>
5 #include <stan/math/prim/fun/inv_logit.hpp>
6 #include <stan/math/prim/fun/log.hpp>
7 #include <stan/math/prim/fun/log1m.hpp>
8 #include <cmath>
9 
10 namespace stan {
11 namespace math {
12 
13 /**
14  * Return a probability value constrained to fall between 0 and 1
15  * (inclusive) for the specified free scalar.
16  *
17  * <p>The transform is the inverse logit,
18  *
19  * <p>\f$f(x) = \mbox{logit}^{-1}(x) = \frac{1}{1 + \exp(x)}\f$.
20  *
21  * @tparam T type of scalar
22  * @param[in] x unconstrained value
23  * @return result constrained to fall in (0, 1)
24  */
25 template <typename T>
prob_constrain(const T & x)26 inline T prob_constrain(const T& x) {
27   return inv_logit(x);
28 }
29 
30 /**
31  * Return a probability value constrained to fall between 0 and 1
32  * (inclusive) for the specified free scalar and increment the
33  * specified log probability reference with the log absolute Jacobian
34  * determinant of the transform.
35  *
36  * <p>The transform is as defined for <code>prob_constrain(T)</code>.
37  * The log absolute Jacobian determinant is
38  *
39  * <p>The log absolute Jacobian determinant is
40  *
41  * <p>\f$\log | \frac{d}{dx} \mbox{logit}^{-1}(x) |\f$
42  * <p>\f$\log ((\mbox{logit}^{-1}(x)) (1 - \mbox{logit}^{-1}(x))\f$
43  * <p>\f$\log (\mbox{logit}^{-1}(x)) + \log (1 - \mbox{logit}^{-1}(x))\f$.
44  *
45  * @tparam T type of scalar
46  * @param[in] x unconstrained value
47  * @param[in, out] lp log density
48  * @return result constrained to fall in (0, 1)
49  */
50 template <typename T>
prob_constrain(const T & x,T & lp)51 inline T prob_constrain(const T& x, T& lp) {
52   using std::log;
53   T inv_logit_x = inv_logit(x);
54   lp += log(inv_logit_x) + log1m(inv_logit_x);
55   return inv_logit_x;
56 }
57 
58 /**
59  * Return a probability value constrained to fall between 0 and 1 (inclusive)
60  * for the specified free scalar. If the `Jacobian` parameter is `true`, the log
61  * density accumulator is incremented with the log absolute Jacobian determinant
62  * of the transform.  All of the transforms are specified with their Jacobians
63  * in the *Stan Reference Manual* chapter Constraint Transforms.
64  *
65  * @tparam Jacobian if `true`, increment log density accumulator with log
66  * absolute Jacobian determinant of constraining transform
67  * @tparam T type of scalar
68  * @param[in] x unconstrained value
69  * @param[in, out] lp log density accumulator
70  * @return result constrained to fall in (0, 1)
71  */
72 template <bool Jacobian, typename T>
prob_constrain(const T & x,T & lp)73 inline auto prob_constrain(const T& x, T& lp) {
74   if (Jacobian) {
75     return prob_constrain(x, lp);
76   } else {
77     return prob_constrain(x);
78   }
79 }
80 }  // namespace math
81 }  // namespace stan
82 
83 #endif
84