Stan Math Library  2.20.0
reverse mode automatic differentiation
unit_vector_constrain.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_FWD_MAT_FUN_UNIT_VECTOR_CONSTRAIN_HPP
2 #define STAN_MATH_FWD_MAT_FUN_UNIT_VECTOR_CONSTRAIN_HPP
3 
4 #include <stan/math/fwd/core.hpp>
14 
15 namespace stan {
16 namespace math {
17 
18 template <typename T, int R, int C>
19 inline Eigen::Matrix<fvar<T>, R, C> unit_vector_constrain(
20  const Eigen::Matrix<fvar<T>, R, C>& y) {
21  using Eigen::Matrix;
22  using std::sqrt;
23 
24  Matrix<T, R, C> y_t(y.size());
25  for (int k = 0; k < y.size(); ++k)
26  y_t.coeffRef(k) = y.coeff(k).val_;
27 
28  Matrix<T, R, C> unit_vector_y_t = unit_vector_constrain(y_t);
29  Matrix<fvar<T>, R, C> unit_vector_y(y.size());
30  for (int k = 0; k < y.size(); ++k)
31  unit_vector_y.coeffRef(k).val_ = unit_vector_y_t.coeff(k);
32 
33  T squared_norm = dot_self(y_t);
34  T norm = sqrt(squared_norm);
35  T inv_norm = inv(norm);
36  Matrix<T, Eigen::Dynamic, Eigen::Dynamic> J
37  = divide(tcrossprod(y_t), -norm * squared_norm);
38 
39  for (int m = 0; m < y.size(); ++m) {
40  J.coeffRef(m, m) += inv_norm;
41  for (int k = 0; k < y.size(); ++k)
42  unit_vector_y.coeffRef(k).d_ = J.coeff(k, m);
43  }
44  return unit_vector_y;
45 }
46 
47 template <typename T, int R, int C>
48 inline Eigen::Matrix<fvar<T>, R, C> unit_vector_constrain(
49  const Eigen::Matrix<fvar<T>, R, C>& y, fvar<T>& lp) {
50  fvar<T> squared_norm = dot_self(y);
51  lp -= 0.5 * squared_norm;
52  return unit_vector_constrain(y);
53 }
54 
55 } // namespace math
56 } // namespace stan
57 #endif
fvar< T > sqrt(const fvar< T > &x)
Definition: sqrt.hpp:13
Eigen::Matrix< fvar< T >, R, R > tcrossprod(const Eigen::Matrix< fvar< T >, R, C > &m)
Definition: tcrossprod.hpp:12
fvar< T > dot_self(const Eigen::Matrix< fvar< T >, R, C > &v)
Definition: dot_self.hpp:13
Eigen::Matrix< fvar< T >, R, C > unit_vector_constrain(const Eigen::Matrix< fvar< T >, R, C > &y)
Eigen::Matrix< fvar< T >, R, C > divide(const Eigen::Matrix< fvar< T >, R, C > &v, const fvar< T > &c)
Definition: divide.hpp:11
This template class represents scalars used in forward-mode automatic differentiation, which consist of values and directional derivatives of the specified template type.
Definition: fvar.hpp:41
fvar< T > inv(const fvar< T > &x)
Definition: inv.hpp:12

     [ Stan Home Page ] © 2011–2018, Stan Development Team.