1 #ifndef STAN_MATH_PRIM_FUN_LOG_INV_LOGIT_DIFF_HPP
2 #define STAN_MATH_PRIM_FUN_LOG_INV_LOGIT_DIFF_HPP
3 
4 #include <stan/math/prim/meta.hpp>
5 #include <stan/math/prim/fun/log1m_exp.hpp>
6 #include <stan/math/prim/fun/log1p_exp.hpp>
7 #include <stan/math/prim/functor/apply_scalar_binary.hpp>
8 
9 namespace stan {
10 namespace math {
11 
12 /**
13  * Returns the natural logarithm of the difference of the
14  * inverse logits of the specified arguments.
15  *
16    \f[
17      \mathrm{log\_inv\_logit\_diff}(x,y) =
18       \ln\left(\frac{1}{1+\exp(-x)}-\frac{1}{1+\exp(-y)}\right)
19    \f]
20 
21    \f[
22     \frac{\partial }{\partial x} = -\frac{e^x}{e^y-e^x}-\frac{e^x}{e^x+1}
23    \f]
24 
25    \f[
26     \frac{\partial }{\partial x} = -\frac{e^y}{e^x-e^y}-\frac{e^y}{e^y+1}
27    \f]
28  *
29  * @tparam T1 type of x argument
30  * @tparam T2 type of y argument
31  * @param x first argument
32  * @param y second argument
33  * @return Result of log difference of inverse logits of arguments.
34  */
35 template <typename T1, typename T2, require_all_arithmetic_t<T1, T2>* = nullptr>
log_inv_logit_diff(const T1 & x,const T2 & y)36 inline return_type_t<T1, T2> log_inv_logit_diff(const T1& x, const T2& y) {
37   return x - log1p_exp(x) + log1m_exp(y - x) - log1p_exp(y);
38 }
39 
40 /**
41  * Enables the vectorised application of the log_inv_logit_diff function,
42  * when the first and/or second arguments are containers.
43  *
44  * @tparam T1 type of first input
45  * @tparam T2 type of second input
46  * @param a First input
47  * @param b Second input
48  * @return log_inv_logit_diff function applied to the two inputs.
49  */
50 template <typename T1, typename T2, require_any_container_t<T1, T2>* = nullptr>
log_inv_logit_diff(const T1 & a,const T2 & b)51 inline auto log_inv_logit_diff(const T1& a, const T2& b) {
52   return apply_scalar_binary(a, b, [&](const auto& c, const auto& d) {
53     return log_inv_logit_diff(c, d);
54   });
55 }
56 
57 }  // namespace math
58 }  // namespace stan
59 
60 #endif
61