Stan Math Library  2.14.0
reverse mode automatic differentiation
grad_tr_mat_times_hessian.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_MIX_MAT_FUNCTOR_GRAD_TR_MAT_TIMES_HESSIAN_HPP
2 #define STAN_MATH_MIX_MAT_FUNCTOR_GRAD_TR_MAT_TIMES_HESSIAN_HPP
3 
4 #include <stan/math/fwd/core.hpp>
6 #include <stan/math/rev/core.hpp>
8 #include <stdexcept>
9 #include <vector>
10 
11 namespace stan {
12  namespace math {
13 
14  template <typename F>
15  void
17  const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
18  const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& M,
19  Eigen::Matrix<double, Eigen::Dynamic, 1>& grad_tr_MH) {
20  using Eigen::Matrix;
21  using Eigen::Dynamic;
22  start_nested();
23  try {
24  grad_tr_MH.resize(x.size());
25 
26  Matrix<var, Dynamic, 1> x_var(x.size());
27  for (int i = 0; i < x.size(); ++i)
28  x_var(i) = x(i);
29 
30  Matrix<fvar<var>, Dynamic, 1> x_fvar(x.size());
31 
32  var sum(0.0);
33  Matrix<double, Dynamic, 1> M_n(x.size());
34  for (int n = 0; n < x.size(); ++n) {
35  for (int k = 0; k < x.size(); ++k)
36  M_n(k) = M(n, k);
37  for (int k = 0; k < x.size(); ++k)
38  x_fvar(k) = fvar<var>(x_var(k), k == n);
39  fvar<var> fx;
40  fvar<var> grad_fx_dot_v;
41  gradient_dot_vector<fvar<var>, double>(f, x_fvar, M_n, fx,
42  grad_fx_dot_v);
43  sum += grad_fx_dot_v.d_;
44  }
45 
46  grad(sum.vi_);
47  for (int i = 0; i < x.size(); ++i)
48  grad_tr_MH(i) = x_var(i).adj();
49  } catch (const std::exception& e) {
51  throw;
52  }
54  }
55 
56  }
57 }
58 #endif
fvar< T > sum(const std::vector< fvar< T > > &m)
Return the sum of the entries of the specified standard vector.
Definition: sum.hpp:20
void grad_tr_mat_times_hessian(const F &f, const Eigen::Matrix< double, Eigen::Dynamic, 1 > &x, const Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > &M, Eigen::Matrix< double, Eigen::Dynamic, 1 > &grad_tr_MH)
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:30
static void grad(vari *vi)
Compute the gradient for all variables starting from the specified root variable implementation.
Definition: grad.hpp:30
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.