Stan Math Library  2.9.0
reverse mode automatic differentiation
grad_hessian.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_MIX_MAT_FUNCTOR_GRAD_HESSIAN_HPP
2 #define STAN_MATH_MIX_MAT_FUNCTOR_GRAD_HESSIAN_HPP
3 
4 #include <stan/math/fwd/core.hpp>
6 #include <stan/math/rev/core.hpp>
7 #include <vector>
8 
9 namespace stan {
10 
11  namespace math {
12 
42  template <typename F>
43  void
44  grad_hessian(const F& f,
45  const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
46  double& fx,
47  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& H,
48  std::vector<Eigen::Matrix<double,
49  Eigen::Dynamic, Eigen::Dynamic> >&
50  grad_H) {
51  using Eigen::Matrix;
52  using Eigen::Dynamic;
53  fx = f(x);
54  int d = x.size();
55  H.resize(d, d);
56  grad_H.resize(d, Matrix<double, Dynamic, Dynamic>(d, d));
57  try {
58  for (int i = 0; i < d; ++i) {
59  for (int j = i; j < d; ++j) {
60  start_nested();
61  Matrix<fvar<fvar<var> >, Dynamic, 1> x_ffvar(d);
62  for (int k = 0; k < d; ++k)
63  x_ffvar(k) = fvar<fvar<var> >(fvar<var>(x(k), i == k),
64  fvar<var>(j == k, 0));
65  fvar<fvar<var> > fx_ffvar = f(x_ffvar);
66  H(i, j) = fx_ffvar.d_.d_.val();
67  H(j, i) = H(i, j);
68  stan::math::grad(fx_ffvar.d_.d_.vi_);
69  for (int k = 0; k < d; ++k) {
70  grad_H[i](j, k) = x_ffvar(k).val_.val_.adj();
71  grad_H[j](i, k) = grad_H[i](j, k);
72  }
74  }
75  }
76  } catch (const std::exception& e) {
78  throw;
79  }
80  }
81 
82  } // namespace math
83 } // namespace stan
84 #endif
static void grad(vari *vi)
Compute the gradient for all variables starting from the specified root variable implementation.
Definition: grad.hpp:30
void grad_hessian(const F &f, const Eigen::Matrix< double, Eigen::Dynamic, 1 > &x, double &fx, Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > &H, std::vector< Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > > &grad_H)
Calculate the value, the Hessian, and the gradient of the Hessian of the specified function at the sp...
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:95
static void recover_memory_nested()
Recover only the memory used for the top nested call.
static void start_nested()
Record the current position so that recover_memory_nested() can find it.

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