Stan Math Library  2.11.0
reverse mode automatic differentiation
jacobian.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_REV_MAT_FUNCTOR_JACOBIAN_HPP
2 #define STAN_MATH_REV_MAT_FUNCTOR_JACOBIAN_HPP
3 
5 #include <stan/math/rev/core.hpp>
6 #include <stdexcept>
7 #include <vector>
8 
9 namespace stan {
10 
11  namespace math {
12 
13  template <typename F>
14  void
15  jacobian(const F& f,
16  const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
17  Eigen::Matrix<double, Eigen::Dynamic, 1>& fx,
18  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& J) {
19  using Eigen::Matrix;
20  using Eigen::Dynamic;
21  using stan::math::var;
22  start_nested();
23  try {
24  Matrix<var, Dynamic, 1> x_var(x.size());
25  for (int k = 0; k < x.size(); ++k)
26  x_var(k) = x(k);
27  Matrix<var, Dynamic, 1> fx_var = f(x_var);
28  fx.resize(fx_var.size());
29  for (int i = 0; i < fx_var.size(); ++i)
30  fx(i) = fx_var(i).val();
31  J.resize(fx_var.size(), x.size());
32  for (int i = 0; i < fx_var.size(); ++i) {
33  if (i > 0)
35  grad(fx_var(i).vi_);
36  for (int k = 0; k < x.size(); ++k)
37  J(i, k) = x_var(k).adj();
38  }
39  } catch (const std::exception& e) {
41  throw;
42  }
44  }
45 
46  }
47 }
48 #endif
static void set_zero_all_adjoints_nested()
Reset all adjoint values in the top nested portion of the stack to zero.
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:31
static void grad(vari *vi)
Compute the gradient for all variables starting from the specified root variable implementation.
Definition: grad.hpp:30
void jacobian(const F &f, const Eigen::Matrix< T, Eigen::Dynamic, 1 > &x, Eigen::Matrix< T, Eigen::Dynamic, 1 > &fx, Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > &J)
Definition: jacobian.hpp:14
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:95
static void recover_memory_nested()
Recover only the memory used for the top nested call.
static void start_nested()
Record the current position so that recover_memory_nested() can find it.

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