I have been trying to learn how to build a custom C++ function, but the most of the guides and forum posts provide scattered information and solutions that seem to be outdated and not working with the latests rstan/stan version.
For example, the official guide presented here: Interfacing with External C++ Code
includes output with compilation errors, which by looking at older versions of the guide seem to be an novel artifcat. Although it says it was recently updated, this seems unlikely given the strange output.
From other forum posts I understand that the precomp_v_vari is deprecated, and one should use make_callback_var instead.
I tried updating the code and running the following:
double msinc(const double& x, std::ostream* pstream__) {
return x != 0.0 ? stan::math::sin(x) / x : 1.0;
}
var msinc(const stan::math::var& x, std::ostream* pstream__) {
double x_ = x.val();
double f = x_ != 0.0 ? stan::math::sin(x_) / x_ : 1.0;
double dfdx_ = x_ != 0.0 ? (stan::math::cos(x_) - stan::math::sin(x_)) / x_ : 0.0;
return make_callback_var(f, [x_, dfdx_](auto& vi) {
x.adj() += vi.adj() * dfdx_;
});
}
with this minimal R code:
mc <-
'
functions { real msinc(real x); }
transformed data { real sinc_pi = msinc(pi()); }
'
a <- stan_model(model_code = mc, model_name = "external", allow_undefined = TRUE,
includes = paste0('\n#include "',
file.path(getwd(), 'scripts/cpp/msinc.hpp'), '"\n'))
But compiling the model gives me the following error:
Error in compileCode(f, code, language = language, verbose = verbose) :
C:/Users/vepopo/AppData/Local/R/win-library/4.3/RcppEigen/include/Eigen/src/Core/ProductEvaluators.h:35:90: required from 'Eigen::internal::evaluator<Eigen::Product<Lhs, Rhs, Option> >::evaluator(const XprType&) [with Lhs = Eigen::Product<Eigen::CwiseBinaryOp<Eigen::internal::scalar_product_op<double, double>, const Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, const Eigen::Matrix<double, 1, -1> >, const Eigen::Transpose<Eigen::Matrix<double, -1, 1> > >, Eigen::Matrix<double, -1, -1>, 0>; Rhs = Eigen::Matrix<double, -1, 1>; int Options = 0; XprType = Eigen::Product<Eigen::Product<Eigen::CwiseBinaryOp<Eigen::internal::scalar_product_op<double, double>, const Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, const Eigen::Matrix<double, 1, -1> >, const Eigen::Transpose<Eigen::Matrix<double, -1, 1> > >, Eigen::Matrix<double, -1, -1>, 0>, Eigen::Matrix<double, -1, 1>, 0>]'C:/Users/vepopo/AppData/Local/R/win-library/4.3/RcppEigen/include/Eigen
Error in sink(type = "output") : invalid connection
I tried following many examples given in the forums, but none of them seem to work. Any idea what is going on? Can some give a minimum example of a working external C++ function?