Automatic Differentiation
 
Loading...
Searching...
No Matches
hessian.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_FWD_FUNCTOR_HESSIAN_HPP
2#define STAN_MATH_FWD_FUNCTOR_HESSIAN_HPP
3
6
7namespace stan {
8namespace math {
9
40template <typename T, typename F>
41void 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 }
57 fvar<fvar<T> > fx_fvar = f(x_fvar);
58 if (j == 0) {
59 fx = fx_fvar.val_.val_;
60 }
61 if (i == j) {
62 grad(i) = fx_fvar.d_.val_;
63 }
64 H(i, j) = fx_fvar.d_.d_;
65 H(j, i) = H(i, j);
66 }
67 }
68}
69
70} // namespace math
71} // namespace stan
72#endif
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()
Compute the gradient for all variables starting from the end of the AD tape.
Definition grad.hpp:26
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...
Scalar val_
The value of this variable.
Definition fvar.hpp:49
Scalar d_
The tangent (derivative) of this variable.
Definition fvar.hpp:61
This template class represents scalars used in forward-mode automatic differentiation,...
Definition fvar.hpp:40