| Stan Math Library 2.11.0 reverse mode automatic differentiation

- Main Page
- Modules
- Namespaces
- Classes
- Files

- File List
- File Members

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/prim/mat/fun/Eigen.hpp>
5 #include <stan/math/rev/core.hpp>
6 #include <stdexcept>
7
8 namespace stan {
9
10 namespace math {
11
41 template <typename F>
42 void
43 gradient(const F& f,
44 const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
45 double& fx,
46 Eigen::Matrix<double, Eigen::Dynamic, 1>& grad_fx) {
47 using stan::math::var;
48 start_nested();
49 try {
50 Eigen::Matrix<var, Eigen::Dynamic, 1> x_var(x.size());
51 for (int i = 0; i < x.size(); ++i)
52 x_var(i) = x(i);
53 var fx_var = f(x_var);
54 fx = fx_var.val();
55 grad_fx.resize(x.size());
56 stan::math::grad(fx_var.vi_);
57 for (int i = 0; i < x.size(); ++i)
58 grad_fx(i) = x_var(i).adj();
59 } catch (const std::exception& /*e*/) {
60 stan::math::recover_memory_nested();
61 throw;
62 }
63 stan::math::recover_memory_nested();
64 }
65 } // namespace math
66 } // namespace stan
67 #endif
core.hpp
stan
Definition: log_sum_exp.hpp:8
stan::math::var
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:31
stan::math::grad
static void grad(vari *vi)
Compute the gradient for all variables starting from the specified root variable implementation.
Definition: grad.hpp:30
stan::math::var::vi_
vari * vi_
Pointer to the implementation of this variable.
Definition: var.hpp:43
Eigen.hpp
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:20
stan::math::var::val
double val() const
Return the value of this variable.
Definition: var.hpp:233
stan::math::gradient
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:41
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 Home Page ] © 2011–2016, Stan Development Team.