finite_diff_grad.hpp
Go to the documentation of this file.
1 #ifndef STAN_MODEL_FINITE_DIFF_GRAD_HPP
2 #define STAN_MODEL_FINITE_DIFF_GRAD_HPP
3 
5 #include <iostream>
6 #include <vector>
7 
8 namespace stan {
9  namespace model {
10 
11  /**
12  * Compute the gradient using finite differences for
13  * the specified parameters, writing the result into the
14  * specified gradient, using the specified perturbation.
15  *
16  * @tparam propto True if calculation is up to proportion
17  * (double-only terms dropped).
18  * @tparam jacobian_adjust_transform True if the log absolute
19  * Jacobian determinant of inverse parameter transforms is added to the
20  * log probability.
21  * @tparam M Class of model.
22  * @param model Model.
23  * @param interrupt interrupt callback to be called before calculating
24  * the finite differences for each parameter.
25  * @param params_r Real-valued parameters.
26  * @param params_i Integer-valued parameters.
27  * @param[out] grad Vector into which gradient is written.
28  * @param epsilon
29  * @param[in,out] msgs
30  */
31  template <bool propto, bool jacobian_adjust_transform, class M>
32  void finite_diff_grad(const M& model,
33  stan::callbacks::interrupt& interrupt,
34  std::vector<double>& params_r,
35  std::vector<int>& params_i,
36  std::vector<double>& grad,
37  double epsilon = 1e-6,
38  std::ostream* msgs = 0) {
39  std::vector<double> perturbed(params_r);
40  grad.resize(params_r.size());
41  for (size_t k = 0; k < params_r.size(); k++) {
42  interrupt();
43  perturbed[k] += epsilon;
44  double logp_plus
45  = model
46  .template log_prob<propto,
47  jacobian_adjust_transform>(perturbed, params_i,
48  msgs);
49  perturbed[k] = params_r[k] - epsilon;
50  double logp_minus
51  = model
52  .template log_prob<propto,
53  jacobian_adjust_transform>(perturbed, params_i,
54  msgs);
55  double gradest = (logp_plus - logp_minus) / (2*epsilon);
56  grad[k] = gradest;
57  perturbed[k] = params_r[k];
58  }
59  }
60 
61  }
62 }
63 #endif
static void grad(vari *vi)
Definition: grad.hpp:30
void finite_diff_grad(const M &model, stan::callbacks::interrupt &interrupt, std::vector< double > &params_r, std::vector< int > &params_i, std::vector< double > &grad, double epsilon=1e-6, std::ostream *msgs=0)
double epsilon
Float_t e
Definition: plot.C:35
const XML_Char XML_Content * model
Definition: expat.h:151