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>
6 #include <stan/math/rev/core.hpp>
7 #include <stdexcept>
8 #include <vector>
9 
10 namespace stan {
11 namespace math {
12 
13 /**
14  * Calculate the value, the Hessian, and the gradient of the Hessian
15  * of the specified function at the specified argument.
16  *
17  * <p>The functor must implement
18  *
19  * <code>
20  * fvar<fvar<var> >
21  * operator()(const Eigen::Matrix<fvar<fvar<var> >,
22  * Eigen::Dynamic, 1>&)
23  * </code>
24  *
25  * using only operations that are defined for
26  * <code>fvar</code> and <code>var</code>.
27  *
28  * This latter constraint usually
29  * requires the functions to be defined in terms of the libraries
30  * defined in Stan or in terms of functions with appropriately
31  * general namespace imports that eventually depend on functions
32  * defined in Stan.
33  *
34  * @tparam F Type of function
35  * @param[in] f Function
36  * @param[in] x Argument to function
37  * @param[out] fx Function applied to argument
38  * @param[out] H Hessian of function at argument
39  * @param[out] grad_H Gradient of the Hessian of function at argument
40  */
41 template <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  try {
54  for (int i = 0; i < d; ++i) {
55  for (int j = i; j < d; ++j) {
56  start_nested();
57  Matrix<fvar<fvar<var> >, Dynamic, 1> x_ffvar(d);
58  for (int k = 0; k < d; ++k)
59  x_ffvar(k)
60  = fvar<fvar<var> >(fvar<var>(x(k), i == k), fvar<var>(j == k, 0));
61  fvar<fvar<var> > fx_ffvar = f(x_ffvar);
62  H(i, j) = fx_ffvar.d_.d_.val();
63  H(j, i) = H(i, j);
64  grad(fx_ffvar.d_.d_.vi_);
65  for (int k = 0; k < d; ++k) {
66  grad_H[i](j, k) = x_ffvar(k).val_.val_.adj();
67  grad_H[j](i, k) = grad_H[i](j, k);
68  }
70  }
71  }
72  } catch (const std::exception& e) {
74  throw;
75  }
76 }
77 
78 } // namespace math
79 } // namespace stan
80 #endif
#define F(x, y, z)
::xsd::cxx::tree::exception< char > exception
Definition: Database.h:225
static void grad(vari *vi)
Definition: grad.hpp:30
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)
Float_t d
Definition: plot.C:236
const double j
Definition: BetheBloch.cxx:29
double e()
Definition: constants.hpp:89
static void recover_memory_nested()
static void start_nested()