Automatic Differentiation
 
Loading...
Searching...
No Matches
unit_vector_constrain.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_REV_CONSTRAINT_UNIT_VECTOR_CONSTRAIN_HPP
2#define STAN_MATH_REV_CONSTRAINT_UNIT_VECTOR_CONSTRAIN_HPP
3
15#include <cmath>
16
17namespace stan {
18namespace math {
19
29template <typename T, require_rev_col_vector_t<T>* = nullptr>
30inline auto unit_vector_constrain(const T& y) {
31 using ret_type = return_var_matrix_t<T>;
32 check_nonzero_size("unit_vector", "y", y);
33
34 arena_t<T> arena_y = y;
35 arena_t<promote_scalar_t<double, T>> arena_y_val = arena_y.val();
36
37 const double r = arena_y_val.norm();
38 arena_t<ret_type> res = arena_y_val / r;
39
40 reverse_pass_callback([arena_y, res, r, arena_y_val]() mutable {
41 arena_y.adj() += res.adj() / r
42 - arena_y_val
43 * ((arena_y_val.array() * res.adj().array()).sum()
44 / (r * r * r));
45 });
46
47 return ret_type(res);
48}
49
60template <typename T, require_eigen_col_vector_vt<is_var, T>* = nullptr>
61inline auto unit_vector_constrain(const T& y, var& lp) {
62 const auto& y_ref = to_ref(y);
63 auto x = unit_vector_constrain(y_ref);
64 lp -= 0.5 * dot_self(y_ref);
65 return x;
66}
67
78template <typename T, require_var_col_vector_t<T>* = nullptr>
79inline auto unit_vector_constrain(const T& y, var& lp) {
80 auto x = unit_vector_constrain(y);
81 lp -= 0.5 * dot_self(y);
82 return x;
83}
84
85} // namespace math
86} // namespace stan
87#endif
void reverse_pass_callback(F &&functor)
Puts a callback on the autodiff stack to be called in reverse pass.
auto unit_vector_constrain(const EigMat &y)
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:17
var_value< double > var
Definition var.hpp:1187
void check_nonzero_size(const char *function, const char *name, const T_y &y)
Check if the specified matrix/vector is of non-zero size.
auto dot_self(const T &a)
Returns squared norm of a vector or matrix.
Definition dot_self.hpp:21
typename internal::arena_type_impl< std::decay_t< T > >::type arena_t
Determines a type that can be used in place of T that does any dynamic allocations on the AD stack.
std::conditional_t< is_any_var_matrix< ReturnType, Types... >::value, stan::math::var_value< stan::math::promote_scalar_t< double, plain_type_t< ReturnType > > >, stan::math::promote_scalar_t< stan::math::var_value< double >, plain_type_t< ReturnType > > > return_var_matrix_t
Given an Eigen type and several inputs, determine if a matrix should be var<Matrix> or Matrix<var>.
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...