Automatic Differentiation
 
Loading...
Searching...
No Matches
dot_product.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_REV_FUN_DOT_PRODUCT_HPP
2#define STAN_MATH_REV_FUN_DOT_PRODUCT_HPP
3
15#include <type_traits>
16#include <vector>
17
18namespace stan {
19namespace math {
20
32template <typename T1, typename T2, require_all_vector_t<T1, T2>* = nullptr,
33 require_not_complex_t<return_type_t<T1, T2>>* = nullptr,
34 require_all_not_std_vector_t<T1, T2>* = nullptr,
35 require_any_st_var<T1, T2>* = nullptr>
36inline var dot_product(const T1& v1, const T2& v2) {
37 check_matching_sizes("dot_product", "v1", v1, "v2", v2);
38
39 if (v1.size() == 0) {
40 return 0.0;
41 }
42
46 return make_callback_var(
47 v1_arena.val().dot(v2_arena.val()),
48 [v1_arena, v2_arena](const auto& vi) mutable {
49 const auto res_adj = vi.adj();
50 for (Eigen::Index i = 0; i < v1_arena.size(); ++i) {
51 v1_arena.adj().coeffRef(i) += res_adj * v2_arena.val().coeff(i);
52 v2_arena.adj().coeffRef(i) += res_adj * v1_arena.val().coeff(i);
53 }
54 });
55 } else if (!is_constant<T2>::value) {
58 return make_callback_var(v1_val_arena.dot(v2_arena.val()),
59 [v1_val_arena, v2_arena](const auto& vi) mutable {
60 v2_arena.adj().array()
61 += vi.adj() * v1_val_arena.array();
62 });
63 } else {
64 arena_t<promote_scalar_t<var, T1>> v1_arena = v1;
65 arena_t<promote_scalar_t<double, T2>> v2_val_arena = value_of(v2);
66 return make_callback_var(v1_arena.val().dot(v2_val_arena),
67 [v1_arena, v2_val_arena](const auto& vi) mutable {
68 v1_arena.adj().array()
69 += vi.adj() * v2_val_arena.array();
70 });
71 }
72}
73
74} // namespace math
75} // namespace stan
76#endif
var_value< plain_type_t< T > > make_callback_var(T &&value, F &&functor)
Creates a new var initialized with a callback_vari with a given value and reverse-pass callback funct...
T value_of(const fvar< T > &v)
Return the value of the specified variable.
Definition value_of.hpp:18
void check_matching_sizes(const char *function, const char *name1, const T_y1 &y1, const char *name2, const T_y2 &y2)
Check if two structures at the same size.
auto dot_product(const T_a &a, const T_b &b)
Returns the dot product of the specified vectors.
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 ...
Metaprogramming struct to detect whether a given type is constant in the mathematical sense (not the ...