Stan Math Library  2.12.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  namespace math {
11 
12  template <typename F>
13  void
14  jacobian(const F& f,
15  const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
16  Eigen::Matrix<double, Eigen::Dynamic, 1>& fx,
17  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& J) {
18  using Eigen::Matrix;
19  using Eigen::Dynamic;
20  start_nested();
21  try {
22  Matrix<var, Dynamic, 1> x_var(x.size());
23  for (int k = 0; k < x.size(); ++k)
24  x_var(k) = x(k);
25  Matrix<var, Dynamic, 1> fx_var = f(x_var);
26  fx.resize(fx_var.size());
27  for (int i = 0; i < fx_var.size(); ++i)
28  fx(i) = fx_var(i).val();
29  J.resize(fx_var.size(), x.size());
30  for (int i = 0; i < fx_var.size(); ++i) {
31  if (i > 0)
33  grad(fx_var(i).vi_);
34  for (int k = 0; k < x.size(); ++k)
35  J(i, k) = x_var(k).adj();
36  }
37  } catch (const std::exception& e) {
39  throw;
40  }
42  }
43 
44  }
45 }
46 #endif
static void set_zero_all_adjoints_nested()
Reset all adjoint values in the top nested portion of the stack to zero.
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:13
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:94
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.