Stan Math Library  2.10.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 each input position
41  for (int m = 0; m < y.size(); ++m) {
42  J.coeffRef(m, m) += inv_norm;
43  // for each output position
44  for (int k = 0; k < y.size(); ++k) {
45  // chain from input to output
46  unit_vector_y.coeffRef(k).d_ = J.coeff(k, m);
47  }
48  }
49  return unit_vector_y;
50  }
51 
52  template <typename T, int R, int C>
53  inline Eigen::Matrix<fvar<T>, R, C>
54  unit_vector_constrain(const Eigen::Matrix<fvar<T>, R, C>& y, fvar<T>& lp) {
55  const fvar<T> squared_norm = dot_self(y);
56  lp -= 0.5 * squared_norm;
57  return unit_vector_constrain(y);
58  }
59 
60  }
61 }
62 #endif
fvar< T > sqrt(const fvar< T > &x)
Definition: sqrt.hpp:15
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:15

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