Automatic Differentiation
 
Loading...
Searching...
No Matches
finite_diff_grad_hessian_auto.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_MIX_FUNCTOR_FINITE_DIFF_GRAD_HESSIAN_AUTO_HPP
2#define STAN_MATH_MIX_FUNCTOR_FINITE_DIFF_GRAD_HESSIAN_AUTO_HPP
3
8#include <vector>
9
10namespace stan {
11namespace math {
12
43template <typename F>
44void finite_diff_grad_hessian_auto(const F& f, const Eigen::VectorXd& x,
45 double& fx, Eigen::MatrixXd& hess,
46 std::vector<Eigen::MatrixXd>& grad_hess_fx) {
47 int d = x.size();
48
49 grad_hess_fx.clear();
50 grad_hess_fx.reserve(d);
51
52 Eigen::VectorXd x_temp(x);
53 Eigen::VectorXd grad_auto(d);
54 Eigen::MatrixXd hess_auto(d, d);
55 Eigen::MatrixXd hess_diff(d, d);
56
57 hessian(f, x, fx, grad_auto, hess);
58
59 for (int i = 0; i < d; ++i) {
60 double dummy_fx_eval;
61 double epsilon = finite_diff_stepsize(x(i));
62 hess_diff.setZero();
63
64 x_temp(i) = x(i) + 2 * epsilon;
65 hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
66 hess_diff = -hess_auto;
67
68 x_temp(i) = x(i) + -2 * epsilon;
69 hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
70 hess_diff += hess_auto;
71
72 x_temp(i) = x(i) + epsilon;
73 hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
74 hess_diff += 8 * hess_auto;
75
76 x_temp(i) = x(i) + -epsilon;
77 hessian(f, x_temp, dummy_fx_eval, grad_auto, hess_auto);
78 hess_diff -= 8 * hess_auto;
79
80 x_temp(i) = x(i);
81 hess_diff /= 12 * epsilon;
82
83 grad_hess_fx.push_back(hess_diff);
84 }
85 fx = f(x);
86}
87
88} // namespace math
89} // namespace stan
90#endif
void finite_diff_grad_hessian_auto(const F &f, const Eigen::VectorXd &x, double &fx, Eigen::MatrixXd &hess, std::vector< Eigen::MatrixXd > &grad_hess_fx)
Calculate the value, Hessian, and the gradient of the Hessian of the specified function at the specif...
double finite_diff_stepsize(double u)
Return the stepsize for finite difference evaluations at the specified scalar.
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
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...