Stan Math Library  2.12.0
reverse mode automatic differentiation
hessian_times_vector.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_MIX_MAT_FUNCTOR_HESSIAN_TIMES_VECTOR_HPP
2 #define STAN_MATH_MIX_MAT_FUNCTOR_HESSIAN_TIMES_VECTOR_HPP
3 
4 #include <stan/math/fwd/core.hpp>
6 #include <stan/math/rev/core.hpp>
7 #include <stdexcept>
8 #include <vector>
9 
10 namespace stan {
11  namespace math {
12 
13  template <typename F>
14  void
16  const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
17  const Eigen::Matrix<double, Eigen::Dynamic, 1>& v,
18  double& fx,
19  Eigen::Matrix<double, Eigen::Dynamic, 1>& Hv) {
20  using Eigen::Matrix;
21  start_nested();
22  try {
23  Matrix<var, Eigen::Dynamic, 1> x_var(x.size());
24  for (int i = 0; i < x_var.size(); ++i)
25  x_var(i) = x(i);
26  var fx_var;
27  var grad_fx_var_dot_v;
28  gradient_dot_vector(f, x_var, v, fx_var, grad_fx_var_dot_v);
29  fx = fx_var.val();
30  grad(grad_fx_var_dot_v.vi_);
31  Hv.resize(x.size());
32  for (int i = 0; i < x.size(); ++i)
33  Hv(i) = x_var(i).adj();
34  } catch (const std::exception& e) {
36  throw;
37  }
39  }
40  template <typename T, typename F>
41  void
43  const Eigen::Matrix<T, Eigen::Dynamic, 1>& x,
44  const Eigen::Matrix<T, Eigen::Dynamic, 1>& v,
45  T& fx,
46  Eigen::Matrix<T, Eigen::Dynamic, 1>& Hv) {
47  using Eigen::Matrix;
48  Matrix<T, Eigen::Dynamic, 1> grad;
49  Matrix<T, Eigen::Dynamic, Eigen::Dynamic> H;
50  hessian(f, x, fx, grad, H);
51  Hv = H * v;
52  }
53 
54  }
55 }
56 #endif
void hessian(const F &f, const Eigen::Matrix< double, Eigen::Dynamic, 1 > &x, double &fx, Eigen::Matrix< double, Eigen::Dynamic, 1 > &grad, Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > &H)
Calculate the value, the gradient, and the Hessian, of the specified function at the specified argume...
Definition: hessian.hpp:44
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:30
void hessian_times_vector(const F &f, const Eigen::Matrix< double, Eigen::Dynamic, 1 > &x, const Eigen::Matrix< double, Eigen::Dynamic, 1 > &v, double &fx, Eigen::Matrix< double, Eigen::Dynamic, 1 > &Hv)
static void grad(vari *vi)
Compute the gradient for all variables starting from the specified root variable implementation.
Definition: grad.hpp:30
vari * vi_
Pointer to the implementation of this variable.
Definition: var.hpp:42
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:94
static void recover_memory_nested()
Recover only the memory used for the top nested call.
double val() const
Return the value of this variable.
Definition: var.hpp:229
void gradient_dot_vector(const F &f, const Eigen::Matrix< T1, Eigen::Dynamic, 1 > &x, const Eigen::Matrix< T2, Eigen::Dynamic, 1 > &v, T1 &fx, T1 &grad_fx_dot_v)
static void start_nested()
Record the current position so that recover_memory_nested() can find it.

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