Stan Math Library  2.20.0
reverse mode automatic differentiation
hessian.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_FWD_MAT_FUNCTOR_HESSIAN_HPP
2 #define STAN_MATH_FWD_MAT_FUNCTOR_HESSIAN_HPP
3 
4 #include <stan/math/fwd/core.hpp>
6 
7 namespace stan {
8 namespace math {
9 
40 template <typename T, typename F>
41 void hessian(const F& f, const Eigen::Matrix<T, Eigen::Dynamic, 1>& x, T& fx,
42  Eigen::Matrix<T, Eigen::Dynamic, 1>& grad,
43  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& H) {
44  H.resize(x.size(), x.size());
45  grad.resize(x.size());
46  // size 0 separate because nothing to loop over in main body
47  if (x.size() == 0) {
48  fx = f(x);
49  return;
50  }
51  Eigen::Matrix<fvar<fvar<T> >, Eigen::Dynamic, 1> x_fvar(x.size());
52  for (int i = 0; i < x.size(); ++i) {
53  for (int j = i; j < x.size(); ++j) {
54  for (int k = 0; k < x.size(); ++k)
55  x_fvar(k) = fvar<fvar<T> >(fvar<T>(x(k), j == k), fvar<T>(i == k, 0));
56  fvar<fvar<T> > fx_fvar = f(x_fvar);
57  if (j == 0)
58  fx = fx_fvar.val_.val_;
59  if (i == j)
60  grad(i) = fx_fvar.d_.val_;
61  H(i, j) = fx_fvar.d_.d_;
62  H(j, i) = H(i, j);
63  }
64  }
65 }
66 
67 } // namespace math
68 } // namespace stan
69 #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
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.