Stan Math Library  2.12.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>
20  unit_vector_constrain(const Eigen::Matrix<fvar<T>, R, C>& y) {
21  using std::sqrt;
22  using Eigen::Matrix;
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
29  = unit_vector_constrain(y_t);
30  Matrix<fvar<T>, R, C> unit_vector_y(y.size());
31  for (int k = 0; k < y.size(); ++k)
32  unit_vector_y.coeffRef(k).val_ = unit_vector_y_t.coeff(k);
33 
34  const T squared_norm = dot_self(y_t);
35  const T norm = sqrt(squared_norm);
36  const T inv_norm = inv(norm);
37  Matrix<T, Eigen::Dynamic, Eigen::Dynamic> J
38  = divide(tcrossprod(y_t), -norm * squared_norm);
39 
40  for (int m = 0; m < y.size(); ++m) {
41  J.coeffRef(m, m) += inv_norm;
42  for (int k = 0; k < y.size(); ++k) {
43  unit_vector_y.coeffRef(k).d_ = J.coeff(k, m);
44  }
45  }
46  return unit_vector_y;
47  }
48 
49  template <typename T, int R, int C>
50  inline Eigen::Matrix<fvar<T>, R, C>
51  unit_vector_constrain(const Eigen::Matrix<fvar<T>, R, C>& y, fvar<T>& lp) {
52  const fvar<T> squared_norm = dot_self(y);
53  lp -= 0.5 * squared_norm;
54  return unit_vector_constrain(y);
55  }
56 
57  }
58 }
59 #endif
fvar< T > sqrt(const fvar< T > &x)
Definition: sqrt.hpp:14
Eigen::Matrix< fvar< T >, R, R > tcrossprod(const Eigen::Matrix< fvar< T >, R, C > &m)
Definition: tcrossprod.hpp:17
fvar< T > dot_self(const Eigen::Matrix< fvar< T >, R, C > &v)
Definition: dot_self.hpp:16
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:16
fvar< T > inv(const fvar< T > &x)
Definition: inv.hpp:14

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