Automatic Differentiation
 
Loading...
Searching...
No Matches
dot_self.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_REV_FUN_DOT_SELF_HPP
2#define STAN_MATH_REV_FUN_DOT_SELF_HPP
3
10#include <vector>
11
12namespace stan {
13namespace math {
14
23template <typename T, require_eigen_vector_vt<is_var, T>* = nullptr>
24inline var dot_self(const T& v) {
25 const auto& v_ref = to_ref(v);
26 arena_t<T> arena_v(v_ref.size());
27 double res_val = 0;
28 for (size_t i = 0; i < arena_v.size(); ++i) {
29 arena_v.coeffRef(i) = v_ref.coeffRef(i);
30 res_val += arena_v.coeffRef(i).val() * arena_v.coeffRef(i).val();
31 }
32 var res(res_val);
33 reverse_pass_callback([res, arena_v]() mutable {
34 arena_v.adj() += 2.0 * res.adj() * arena_v.val();
35 });
36
37 return res;
38}
39
47template <typename T, require_var_matrix_t<T>* = nullptr>
48inline var dot_self(const T& v) {
49 var res = v.val().dot(v.val());
51 [res, v]() mutable { v.adj() += (2.0 * res.adj()) * v.val(); });
52
53 return res;
54}
55
56} // namespace math
57} // namespace stan
58#endif
void reverse_pass_callback(F &&functor)
Puts a callback on the autodiff stack to be called in reverse pass.
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
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.
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...