Hello,
I’m trying to write a custom C++ function with an analytical gradient that I’d like to call from Stan. I’ve found two relevant examples in the documentation:
First, the “Translating Stan to C++” chapter of the cmdstanr
guide provides the following example of a custom C++ function:
namespace bernoulli_model_namespace {
template <typename T0__> inline typename
boost::math::tools::promote_args<T0__>::type make_odds(const T0__&
theta, std::ostream* pstream__) {
return theta / (1 - theta); }
}
with a corresponding definition in the Stan file:
functions {
real make_odds(real theta);
}
How might I modify the C++ function to return an analytical gradient?
Second, say I follow the model in Contributing New Functions to Stan and define a new function in the stan::math namespace:
#include "my_foo.hpp"
#include <stan/math/rev/core.hpp>
namespace stan {
namespace math {
vector<double> foo(const vector<double>& x) {
return bar::foo(x);
}
vector<var> foo(const vector<var>& x) {
vector<double> a = value_of(x);
double fa = bar::foo(a);
vector<double> grad_fa = bar::grad_foo(a);
return precomputed_gradients(fa, x, grad_fa);
}
}
}
How should I call this function foo
from a Stan model?
Thanks!