1 #ifndef STAN_MATH_REV_MAT_FUN_SQUARED_DISTANCE_HPP 2 #define STAN_MATH_REV_MAT_FUN_SQUARED_DISTANCE_HPP 21 class squared_distance_vv_vari :
public vari {
27 template <
int R1,
int C1,
int R2,
int C2>
29 var_squared_distance(
const Eigen::Matrix<var, R1, C1> &v1,
30 const Eigen::Matrix<var, R2, C2> &v2) {
32 typedef typename index_type<Matrix<var, R1, R2> >::type idx_t;
34 for (idx_t i = 0; i < v1.size(); i++) {
35 double diff = v1(i).vi_->val_ - v2(i).vi_->val_;
42 template<
int R1,
int C1,
int R2,
int C2>
43 squared_distance_vv_vari(
const Eigen::Matrix<var, R1, C1> &v1,
44 const Eigen::Matrix<var, R2, C2> &v2)
45 : vari(var_squared_distance(v1, v2)),
length_(v1.size()) {
47 .
alloc(length_*
sizeof(vari*)));
48 for (
size_t i = 0; i <
length_; i++)
52 .
alloc(length_*
sizeof(vari*)));
53 for (
size_t i = 0; i <
length_; i++)
56 virtual void chain() {
57 for (
size_t i = 0; i <
length_; i++) {
58 double di = 2 * adj_ * (v1_[i]->val_ - v2_[i]->val_);
64 class squared_distance_vd_vari :
public vari {
70 template<
int R1,
int C1,
int R2,
int C2>
72 var_squared_distance(
const Eigen::Matrix<var, R1, C1> &v1,
73 const Eigen::Matrix<double, R2, C2> &v2) {
75 typedef typename index_type<Matrix<double, R1, C1> >::type idx_t;
78 for (idx_t i = 0; i < v1.size(); i++) {
79 double diff = v1(i).vi_->val_ - v2(i);
86 template<
int R1,
int C1,
int R2,
int C2>
87 squared_distance_vd_vari(
const Eigen::Matrix<var, R1, C1> &v1,
88 const Eigen::Matrix<double, R2, C2> &v2)
89 : vari(var_squared_distance(v1, v2)),
length_(v1.size()) {
91 .
alloc(length_*
sizeof(vari*)));
92 for (
size_t i = 0; i <
length_; i++)
96 .
alloc(length_*
sizeof(
double)));
97 for (
size_t i = 0; i <
length_; i++)
100 virtual void chain() {
101 for (
size_t i = 0; i <
length_; i++) {
102 v1_[i]->adj_ += 2 * adj_ * (v1_[i]->val_ - v2_[i]);
108 template<
int R1,
int C1,
int R2,
int C2>
110 const Eigen::Matrix<var, R2, C2>& v2) {
116 return var(
new squared_distance_vv_vari(v1, v2));
118 template<
int R1,
int C1,
int R2,
int C2>
120 const Eigen::Matrix<double, R2, C2>& v2) {
126 return var(
new squared_distance_vd_vari(v1, v2));
128 template<
int R1,
int C1,
int R2,
int C2>
130 const Eigen::Matrix<var, R2, C2>& v2) {
136 return var(
new squared_distance_vd_vari(v2, v1));
static stack_alloc memalloc_
void check_vector(const char *function, const char *name, const Eigen::Matrix< T, R, C > &x)
Check if the matrix is either a row vector or column vector.
Independent (input) and dependent (output) variables for gradients.
fvar< T > squared_distance(const Eigen::Matrix< fvar< T >, R, C > &v1, const Eigen::Matrix< double, R, C > &v2)
Returns the squared distance between the specified vectors of the same dimensions.
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.
void * alloc(size_t len)
Return a newly allocated block of memory of the appropriate size managed by the stack allocator...