Stan Math Library  2.8.0
reverse mode automatic differentiation
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Groups
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 
7 namespace stan {
8 
9  namespace math {
10 
11  using Eigen::Dynamic;
12 
42  template <typename F>
43  void
44  gradient(const F& f,
45  const Eigen::Matrix<double, Dynamic, 1>& x,
46  double& fx,
47  Eigen::Matrix<double, Dynamic, 1>& grad_fx) {
48  using stan::math::var;
49  start_nested();
50  try {
51  Eigen::Matrix<var, Dynamic, 1> x_var(x.size());
52  for (int i = 0; i < x.size(); ++i)
53  x_var(i) = x(i);
54  var fx_var = f(x_var);
55  fx = fx_var.val();
56  grad_fx.resize(x.size());
57  stan::math::grad(fx_var.vi_);
58  for (int i = 0; i < x.size(); ++i)
59  grad_fx(i) = x_var(i).adj();
60  } catch (const std::exception& /*e*/) {
62  throw;
63  }
65  }
66  } // namespace math
67 } // namespace stan
68 #endif
static void grad(chainable *vi)
Compute the gradient for all variables starting from the specified root variable implementation.
Definition: grad.hpp:30
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:32
vari * vi_
Pointer to the implementation of this variable.
Definition: var.hpp:44
static void recover_memory_nested()
Recover only the memory used for the top nested call.
double val() const
Return the value of this variable.
Definition: var.hpp:234
void gradient(const F &f, const Eigen::Matrix< T, Dynamic, 1 > &x, T &fx, Eigen::Matrix< T, Dynamic, 1 > &grad_fx)
Calculate the value and the gradient of the specified function at the specified argument.
Definition: gradient.hpp:44
static void start_nested()
Record the current position so that recover_memory_nested() can find it.

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