Stan Math Library  2.9.0
reverse mode automatic differentiation
precomputed_gradients.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_REV_CORE_PRECOMPUTED_GRADIENTS_HPP
2 #define STAN_MATH_REV_CORE_PRECOMPUTED_GRADIENTS_HPP
3 
6 #include <algorithm>
7 #include <vector>
8 #include <stdexcept>
9 
10 namespace stan {
11 
12  namespace math {
13 
22  protected:
23  const size_t size_;
25  double* gradients_;
26 
27  public:
38  size_t size,
39  vari** varis,
40  double* gradients)
41  : vari(val),
42  size_(size),
43  varis_(varis),
44  gradients_(gradients) {
45  }
46 
59  const std::vector<var>& vars,
60  const std::vector<double>& gradients)
61  : vari(val),
62  size_(vars.size()),
63  varis_(ChainableStack::memalloc_
64  .alloc_array<vari*>(vars.size())),
65  gradients_(ChainableStack::memalloc_
66  .alloc_array<double>(vars.size())) {
67  if (vars.size() != gradients.size())
68  throw std::invalid_argument("sizes of vars and gradients"
69  " do not match");
70  for (size_t i = 0; i < vars.size(); ++i)
71  varis_[i] = vars[i].vi_;
72  std::copy(gradients.begin(), gradients.end(), gradients_);
73  }
74 
79  void chain() {
80  for (size_t i = 0; i < size_; ++i)
81  varis_[i]->adj_ += adj_ * gradients_[i];
82  }
83  };
84 
85 
98  var precomputed_gradients(const double value,
99  const std::vector<var>& operands,
100  const std::vector<double>& gradients) {
101  return var(new precomputed_gradients_vari(value, operands, gradients));
102  }
103  }
104 }
105 #endif
var precomputed_gradients(const double value, const std::vector< var > &operands, const std::vector< double > &gradients)
This function returns a var for an expression that has the specified value, vector of operands...
The variable implementation base class.
Definition: vari.hpp:30
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:31
A variable implementation taking a sequence of operands and partial derivatives with respect to the o...
precomputed_gradients_vari(double val, const std::vector< var > &vars, const std::vector< double > &gradients)
Construct a precomputed vari with the specified value, operands, and gradients.
void invalid_argument(const char *function, const char *name, const T &y, const char *msg1, const char *msg2)
Throw an invalid_argument exception with a consistently formatted message.
void chain()
Implements the chain rule for this variable, using the prestored operands and gradient.
int size(const std::vector< T > &x)
Return the size of the specified standard vector.
Definition: size.hpp:17
double adj_
The adjoint of this variable, which is the partial derivative of this variable with respect to the ro...
Definition: vari.hpp:44
precomputed_gradients_vari(double val, size_t size, vari **varis, double *gradients)
Construct a precomputed vari with the specified value, operands, and gradients.

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