| Stan Math Library 2.11.0 reverse mode automatic differentiation

- Main Page
- Modules
- Namespaces
- Classes
- Files

- File List
- File Members

grad_hessian.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_MIX_MAT_FUNCTOR_GRAD_HESSIAN_HPP
2 #define STAN_MATH_MIX_MAT_FUNCTOR_GRAD_HESSIAN_HPP
3
4 #include <stan/math/fwd/core.hpp>
5 #include <stan/math/prim/mat/fun/Eigen.hpp>
6 #include <stan/math/rev/core.hpp>
7 #include <stdexcept>
8 #include <vector>
9
10 namespace stan {
11
12 namespace math {
13
43 template <typename F>
44 void
45 grad_hessian(const F& f,
46 const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
47 double& fx,
48 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& H,
49 std::vector<Eigen::Matrix<double,
50 Eigen::Dynamic, Eigen::Dynamic> >&
51 grad_H) {
52 using Eigen::Matrix;
53 using Eigen::Dynamic;
54 fx = f(x);
55 int d = x.size();
56 H.resize(d, d);
57 grad_H.resize(d, Matrix<double, Dynamic, Dynamic>(d, d));
58 try {
59 for (int i = 0; i < d; ++i) {
60 for (int j = i; j < d; ++j) {
61 start_nested();
62 Matrix<fvar<fvar<var> >, Dynamic, 1> x_ffvar(d);
63 for (int k = 0; k < d; ++k)
64 x_ffvar(k) = fvar<fvar<var> >(fvar<var>(x(k), i == k),
65 fvar<var>(j == k, 0));
66 fvar<fvar<var> > fx_ffvar = f(x_ffvar);
67 H(i, j) = fx_ffvar.d_.d_.val();
68 H(j, i) = H(i, j);
69 stan::math::grad(fx_ffvar.d_.d_.vi_);
70 for (int k = 0; k < d; ++k) {
71 grad_H[i](j, k) = x_ffvar(k).val_.val_.adj();
72 grad_H[j](i, k) = grad_H[i](j, k);
73 }
74 recover_memory_nested();
75 }
76 }
77 } catch (const std::exception& e) {
78 stan::math::recover_memory_nested();
79 throw;
80 }
81 }
82
83 } // namespace math
84 } // namespace stan
85 #endif
core.hpp
core.hpp
stan::math::fvar::d_
T d_
Definition: fvar.hpp:15
stan
Definition: log_sum_exp.hpp:8
stan::math::grad
static void grad(vari *vi)
Compute the gradient for all variables starting from the specified root variable implementation.
Definition: grad.hpp:30
stan::math::grad_hessian
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...
Definition: grad_hessian.hpp:45
Eigen.hpp
stan::math::e
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:95
stan::math::recover_memory_nested
static void recover_memory_nested()
Recover only the memory used for the top nested call.
Definition: recover_memory_nested.hpp:20
stan::math::start_nested
static void start_nested()
Record the current position so that recover_memory_nested() can find it.
Definition: start_nested.hpp:13
stan::math::fvar
Definition: fvar.hpp:13

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