grad.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_REV_CORE_GRAD_HPP
2 #define STAN_MATH_REV_CORE_GRAD_HPP
3 
9 #include <vector>
10 
11 namespace stan {
12 namespace math {
13 
14 /**
15  * Compute the gradient for all variables starting from the
16  * specified root variable implementation. Does not recover
17  * memory. This chainable variable's adjoint is initialized using
18  * the method <code>init_dependent()</code> and then the chain
19  * rule is applied working down the stack from this vari and
20  * calling each vari's <code>chain()</code> method in turn.
21  *
22  * <p>This function computes a nested gradient only going back as far
23  * as the last nesting.
24  *
25  * <p>This function does not recover any memory from the computation.
26  *
27  * @param vi Variable implementation for root of partial
28  * derivative propagation.
29  */
30 static void grad(vari* vi) {
31  // simple reference implementation (intended as doc):
32  // vi->init_dependent();
33  // size_t end = var_stack_.size();
34  // size_t begin = empty_nested() ? 0 : end - nested_size();
35  // for (size_t i = end; --i > begin; )
36  // var_stack_[i]->chain();
37 
38  typedef std::vector<vari*>::reverse_iterator it_t;
39  vi->init_dependent();
40  it_t begin = ChainableStack::instance().var_stack_.rbegin();
42  : begin + nested_size();
43  for (it_t it = begin; it < end; ++it) {
44  (*it)->chain();
45  }
46 }
47 
48 } // namespace math
49 } // namespace stan
50 
51 #endif
static bool empty_nested()
set< int >::iterator it
static void grad(vari *vi)
Definition: grad.hpp:30
static size_t nested_size()
Definition: nested_size.hpp:10
static AutodiffStackStorage & instance()
void init_dependent()
Definition: vari.hpp:93