Automatic Differentiation
 
Loading...
Searching...
No Matches
grad_hessian.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_MIX_FUNCTOR_GRAD_HESSIAN_HPP
2#define STAN_MATH_MIX_FUNCTOR_GRAD_HESSIAN_HPP
3
7#include <stdexcept>
8#include <vector>
9
10namespace stan {
11namespace math {
12
41template <typename F>
43 const F& f, const Eigen::Matrix<double, Eigen::Dynamic, 1>& x, double& fx,
44 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& H,
45 std::vector<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> >&
46 grad_H) {
47 using Eigen::Dynamic;
48 using Eigen::Matrix;
49 fx = f(x);
50 int d = x.size();
51 H.resize(d, d);
52 grad_H.resize(d, Matrix<double, Dynamic, Dynamic>(d, d));
53 for (int i = 0; i < d; ++i) {
54 for (int j = i; j < d; ++j) {
55 // Run nested autodiff in this scope
57
58 Matrix<fvar<fvar<var> >, Dynamic, 1> x_ffvar(d);
59 for (int k = 0; k < d; ++k) {
60 x_ffvar(k)
61 = fvar<fvar<var> >(fvar<var>(x(k), i == k), fvar<var>(j == k, 0));
62 }
63 fvar<fvar<var> > fx_ffvar = f(x_ffvar);
64 H(i, j) = fx_ffvar.d_.d_.val();
65 H(j, i) = H(i, j);
66 grad(fx_ffvar.d_.d_.vi_);
67 for (int k = 0; k < d; ++k) {
68 grad_H[i](j, k) = x_ffvar(k).val_.val_.adj();
69 grad_H[j](i, k) = grad_H[i](j, k);
70 }
71 }
72 }
73}
74
75} // namespace math
76} // namespace stan
77#endif
A class following the RAII idiom to start and recover nested autodiff scopes.
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...
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 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