Stan Math Library  2.6.3
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros
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 <vector>
9 
10 namespace stan {
11 
12  namespace math {
13 
14  using Eigen::Dynamic;
15 
16  // FIXME: add other results that are easy to extract
17  // // N * (fwd(2) + bk)
18  template <typename F>
19  void
21  const Eigen::Matrix<double, Dynamic, 1>& x,
22  const Eigen::Matrix<double, Dynamic, Dynamic>& M,
23  Eigen::Matrix<double, Dynamic, 1>& grad_tr_MH) {
24  using Eigen::Matrix;
25  start_nested();
26  try {
27  grad_tr_MH.resize(x.size());
28 
29  Matrix<var, Dynamic, 1> x_var(x.size());
30  for (int i = 0; i < x.size(); ++i)
31  x_var(i) = x(i);
32 
33  Matrix<fvar<var>, Dynamic, 1> x_fvar(x.size());
34 
35  var sum(0.0);
36  Matrix<double, Dynamic, 1> M_n(x.size());
37  for (int n = 0; n < x.size(); ++n) {
38  for (int k = 0; k < x.size(); ++k)
39  M_n(k) = M(n, k);
40  for (int k = 0; k < x.size(); ++k)
41  x_fvar(k) = fvar<var>(x_var(k), k == n);
42  fvar<var> fx;
43  fvar<var> grad_fx_dot_v;
44  gradient_dot_vector<fvar<var>, double>(f, x_fvar, M_n, fx,
45  grad_fx_dot_v);
46  sum += grad_fx_dot_v.d_;
47  }
48 
49  stan::math::grad(sum.vi_);
50  for (int i = 0; i < x.size(); ++i)
51  grad_tr_MH(i) = x_var(i).adj();
52  } catch (const std::exception& e) {
54  throw;
55  }
57  }
58 
59 
60  } // namespace math
61 } // namespace stan
62 #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, Dynamic, 1 > &x, const Eigen::Matrix< double, Dynamic, Dynamic > &M, Eigen::Matrix< double, Dynamic, 1 > &grad_tr_MH)
static void grad(chainable *vi)
Compute the gradient for all variables starting from the specified root variable implementation.
Definition: grad.hpp:30
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:32
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–2015, Stan Development Team.