Stan Math Library  2.20.0
reverse mode automatic differentiation
hessian.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_MIX_MAT_FUNCTOR_HESSIAN_HPP
2 #define STAN_MATH_MIX_MAT_FUNCTOR_HESSIAN_HPP
3 
4 #include <stan/math/fwd/core.hpp>
6 #include <stan/math/rev/core.hpp>
7 #include <stdexcept>
8 
9 namespace stan {
10 namespace math {
11 
41 template <typename F>
42 void hessian(const F& f, const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
43  double& fx, Eigen::Matrix<double, Eigen::Dynamic, 1>& grad,
44  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& H) {
45  H.resize(x.size(), x.size());
46  grad.resize(x.size());
47 
48  // need to compute fx even with size = 0
49  if (x.size() == 0) {
50  fx = f(x);
51  return;
52  }
53  try {
54  for (int i = 0; i < x.size(); ++i) {
55  start_nested();
56  Eigen::Matrix<fvar<var>, Eigen::Dynamic, 1> x_fvar(x.size());
57  for (int j = 0; j < x.size(); ++j)
58  x_fvar(j) = fvar<var>(x(j), i == j);
59  fvar<var> fx_fvar = f(x_fvar);
60  grad(i) = fx_fvar.d_.val();
61  if (i == 0)
62  fx = fx_fvar.val_.val();
63  stan::math::grad(fx_fvar.d_.vi_);
64  for (int j = 0; j < x.size(); ++j)
65  H(i, j) = x_fvar(j).val_.adj();
67  }
68  } catch (const std::exception& e) {
70  throw;
71  }
72 }
73 
74 } // namespace math
75 } // namespace stan
76 #endif
T d_
The tangent (derivative) of this variable.
Definition: fvar.hpp:50
void hessian(const F &f, const Eigen::Matrix< T, Eigen::Dynamic, 1 > &x, T &fx, Eigen::Matrix< T, Eigen::Dynamic, 1 > &grad, Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > &H)
Calculate the value, the gradient, and the Hessian, of the specified function at the specified argume...
Definition: hessian.hpp:41
static void grad(vari *vi)
Compute the gradient for all variables starting from the specified root variable implementation.
Definition: grad.hpp:30
T val_
The value of this variable.
Definition: fvar.hpp:45
vari * vi_
Pointer to the implementation of this variable.
Definition: var.hpp:45
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:87
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.
double val() const
Return the value of this variable.
Definition: var.hpp:294
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

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