Hi. I’m writing a MCMC code in C++ using the interface Rcpp.
I’m interested to get the gradient and Hessian for the full conditional posterior density of a block of parameters. I’m trying to use StanHeaders Package like showed in Using the Stan Math C++ Library.
The gradient is working fine to the latent Gaussian Process “f” of a log-Gaussian Cox Process as shown below:
// [[Rcpp::export]]
Eigen::VectorXd lccGFast(Eigen::VectorXd f, Eigen::VectorXd y, Eigen::MatrixXd Km1){
double fx;
Eigen::VectorXd grad_fx;
stan::math::gradient([&y,&Km1](auto f){
int n = y.rows();
stan::math::var fKm1f = -(1.0/2.0)*f.transpose()*Km1*f;
stan::math::vector_v efyf(n);
for(int i=0; i< n; i++){
efyf[i] = 0.0;
efyf[i] = (exp(f[i])-y[i]*f[i]);
}
return(fKm1f-sum(efyf));},
f, fx, grad_fx);
return grad_fx;
}
but when I try to use the similar “function” for the same example to get the Hessian:
// [[Rcpp::export]]
Eigen::MatrixXd lccHFast(Eigen::VectorXd f, Eigen::VectorXd y, Eigen::MatrixXd Km1){
double fx;
Eigen::VectorXd grad_fx;
Eigen::MatrixXd H;
stan::math::hessian([&y,&Km1](auto f){
int n = y.rows();
stan::math::var fKm1f = -(1.0/2.0)*f.transpose()*Km1*f;
stan::math::vector_v efyf(n);
for(int i=0; i< n; i++){
efyf[i] = 0.0;
efyf[i] = (exp(f[i])-y[i]*f[i]);
}
return(fKm1f-sum(efyf));
},
f, fx, grad_fx, H);
return H;
}
many errors are reported (there are hundred of lines of error in R, i don’t know which part is important to help me to realize what is not working).
What am I missing?
Thanks in advance.