Skip to content

Instantly share code, notes, and snippets.

@maedoc
Last active January 27, 2022 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maedoc/79fd2e13e9db29181e8a979c8e8436fc to your computer and use it in GitHub Desktop.
Save maedoc/79fd2e13e9db29181e8a979c8e8436fc to your computer and use it in GitHub Desktop.
minimal Stan user func with external files
model: model.stan support.o support.hpp
STANCFLAGS=--allow-undefined USER_HEADER=$$PWD/support.hpp LDLIBS_OS=$$PWD/support.o make -C ~/.cmdstan/cmdstan-2.28.2/ $$PWD/model
functions {
real usersum(matrix m);
}
parameters {
real theta;
}
model {
matrix[5,5] m = rep_matrix(-theta*theta, 5, 5);
target += usersum(m);
}
double support_sum(int n, const double*const els) {
double acc = 0.0;
for (int i=0; i<n; i++) acc += els[i];
return acc;
}
void support_sum_adj(int n, const double g, double*adj){
for (int i=0; i<n; i++)
adj[i] += g;
}
extern "C" double support_sum(int n, const double*els);
extern "C" void support_sum_adj(int n, const double g, double*adj);
#include <stan/math.hpp>
#include <stan/math/rev/core/reverse_pass_callback.hpp>
#include "support.h"
namespace model_model_namespace {
using namespace stan;
using namespace std;
double usersum(const Eigen::MatrixXd& m, ostream *pstream__) {
return support_sum(m.size(), m.data());
}
template <typename M>
promote_args_t<value_type_t<M>>
usersum(const M& m, ostream *pstream__) {
using value_t = value_type_t<M>; // var_value<double>
using ret_type = promote_var_matrix_t<M,M>; // Eigen::Matrix<stan::math::var_value<double>, -1, -1, 0>
Eigen::MatrixXd mv = value_of(m);
const double *md = mv.data();
value_t ret(support_sum(m.size(), md));
arena_t<M> arena_m(m);
arena_t<value_t> aret(ret);
math::reverse_pass_callback([aret, arena_m]() mutable {
Eigen::MatrixXd adj(arena_m.rows(), arena_m.cols());
support_sum_adj(adj.size(), aret.adj(), adj.data());
arena_m.adj() += adj;
});
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment