Stan Math Library  2.20.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 
4 #include <stan/math/rev/meta.hpp>
6 #include <stan/math/rev/core.hpp>
7 #include <stdexcept>
8 #include <vector>
9 
10 namespace stan {
11 namespace math {
12 
13 template <typename F>
14 void jacobian(const F& f, const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
15  Eigen::Matrix<double, Eigen::Dynamic, 1>& fx,
16  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& J) {
17  using Eigen::Dynamic;
18  using Eigen::Matrix;
19  start_nested();
20  try {
21  Matrix<var, Dynamic, 1> x_var(x.size());
22  for (int k = 0; k < x.size(); ++k)
23  x_var(k) = x(k);
24  Matrix<var, Dynamic, 1> fx_var = f(x_var);
25  fx.resize(fx_var.size());
26  for (int i = 0; i < fx_var.size(); ++i)
27  fx(i) = fx_var(i).val();
28  J.resize(fx_var.size(), x.size());
29  for (int i = 0; i < fx_var.size(); ++i) {
30  if (i > 0)
32  grad(fx_var(i).vi_);
33  for (int k = 0; k < x.size(); ++k)
34  J(i, k) = x_var(k).adj();
35  }
36  } catch (const std::exception& e) {
38  throw;
39  }
41 }
42 
43 } // namespace math
44 } // namespace stan
45 #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:11
double e()
Return the base of the natural logarithm.
Definition: constants.hpp:87
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–2018, Stan Development Team.