All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Groups
grad_hessian.hpp
Go to the documentation of this file.
#ifndef STAN_MATH_MIX_MAT_FUNCTOR_GRAD_HESSIAN_HPP
#define STAN_MATH_MIX_MAT_FUNCTOR_GRAD_HESSIAN_HPP
#include <stan/math/fwd/core.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/rev/core.hpp>
#include <vector>
namespace stan {
namespace math {
using Eigen::Dynamic;
template <typename F>
void
grad_hessian(const F& f,
const Eigen::Matrix<double, Dynamic, 1>& x,
double& fx,
Eigen::Matrix<double, Dynamic, Dynamic>& H,
std::vector<Eigen::Matrix<double, Dynamic, Dynamic> >&
grad_H) {
using Eigen::Matrix;
fx = f(x);
int d = x.size();
H.resize(d, d);
grad_H.resize(d, Matrix<double, Dynamic, Dynamic>(d, d));
try {
for (int i = 0; i < d; ++i) {
for (int j = i; j < d; ++j) {
start_nested();
Matrix<fvar<fvar<var> >, Dynamic, 1> x_ffvar(d);
for (int k = 0; k < d; ++k)
x_ffvar(k) = fvar<fvar<var> >(fvar<var>(x(k), i == k),
fvar<var>(j == k, 0));
fvar<fvar<var> > fx_ffvar = f(x_ffvar);
H(i, j) = fx_ffvar.d_.d_.val();
H(j, i) = H(i, j);
stan::math::grad(fx_ffvar.d_.d_.vi_);
for (int k = 0; k < d; ++k) {
grad_H[i](j, k) = x_ffvar(k).val_.val_.adj();
grad_H[j](i, k) = grad_H[i](j, k);
}
recover_memory_nested();
}
}
} catch (const std::exception& e) {
stan::math::recover_memory_nested();
throw;
}
}
} // namespace math
} // namespace stan
#endif
core.hpp
core.hpp
stan::math::fvar::d_
T d_
Definition: fvar.hpp:15
stan::math::grad
static void grad(chainable *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, Dynamic, 1 > &x, double &fx, Eigen::Matrix< double, Dynamic, Dynamic > &H, std::vector< Eigen::Matrix< double, Dynamic, 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:46
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:21
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–2015, Stan Development Team.