Stan Math Library  2.20.0
reverse mode automatic differentiation
gradient.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_REV_MAT_FUNCTOR_GRADIENT_HPP
2 #define STAN_MATH_REV_MAT_FUNCTOR_GRADIENT_HPP
3 
4 #include <stan/math/rev/meta.hpp>
6 #include <stan/math/rev/core.hpp>
7 #include <stdexcept>
8 
9 namespace stan {
10 namespace math {
11 
41 template <typename F>
42 void gradient(const F& f, const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
43  double& fx, Eigen::Matrix<double, Eigen::Dynamic, 1>& grad_fx) {
44  start_nested();
45  try {
46  Eigen::Matrix<var, Eigen::Dynamic, 1> x_var(x.size());
47  for (int i = 0; i < x.size(); ++i)
48  x_var(i) = x(i);
49  var fx_var = f(x_var);
50  fx = fx_var.val();
51  grad_fx.resize(x.size());
52  grad(fx_var.vi_);
53  for (int i = 0; i < x.size(); ++i)
54  grad_fx(i) = x_var(i).adj();
55  } catch (const std::exception& /*e*/) {
57  throw;
58  }
60 }
61 
62 } // namespace math
63 } // namespace stan
64 #endif
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:33
static void grad(vari *vi)
Compute the gradient for all variables starting from the specified root variable implementation.
Definition: grad.hpp:30
vari * vi_
Pointer to the implementation of this variable.
Definition: var.hpp:45
static void recover_memory_nested()
Recover only the memory used for the top nested call.
void gradient(const F &f, const Eigen::Matrix< T, Eigen::Dynamic, 1 > &x, T &fx, Eigen::Matrix< T, Eigen::Dynamic, 1 > &grad_fx)
Calculate the value and the gradient of the specified function at the specified argument.
Definition: gradient.hpp:39
static void start_nested()
Record the current position so that recover_memory_nested() can find it.
double val() const
Return the value of this variable.
Definition: var.hpp:294

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