Stan Math Library  2.15.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 
5 #include <stan/math/rev/core.hpp>
6 #include <stdexcept>
7 
8 namespace stan {
9  namespace math {
10 
40  template <typename F>
41  void
42  gradient(const F& f,
43  const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
44  double& fx,
45  Eigen::Matrix<double, Eigen::Dynamic, 1>& grad_fx) {
46  start_nested();
47  try {
48  Eigen::Matrix<var, Eigen::Dynamic, 1> x_var(x.size());
49  for (int i = 0; i < x.size(); ++i)
50  x_var(i) = x(i);
51  var fx_var = f(x_var);
52  fx = fx_var.val();
53  grad_fx.resize(x.size());
54  grad(fx_var.vi_);
55  for (int i = 0; i < x.size(); ++i)
56  grad_fx(i) = x_var(i).adj();
57  } catch (const std::exception& /*e*/) {
59  throw;
60  }
62  }
63 
64  }
65 }
66 #endif
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:30
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:42
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:40
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:230

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