Problem with user-defined functions with Rstan

I’m seeing a strange problem with rstan where a model compiles from Stan to C++ just fine, but then I get a compiler error when the generated C++ is compiled. I have the following user-defined function in the functions block:

  matrix constrainsgn(matrix b, int[] idxpos, int[] idxneg, int xform, real s) {

Then in the transformed parameters block I have

  matrix[nresp, ncov] t_beta =
    constrainsgn(rep_matrix(t_alpha, nresp) +  t_z_beta * Lbeta', idxpos, idxneg, xform, s);

I get the following C++ compiler error:

Error in compileCode(f, code, language = language, verbose = verbose) : 
      ^file10aabec826b9.cpp:153:1: note: candidate template ignored: could not match 0 against 1constrainsgn(const Eigen::Matrix<T0__, Eigen::Dynamic, Eigen::Dynamic>& b,^72 warnings and 5 errors generated.make: *** [file10aabec826b9.o] Error 1

The problem goes away if I replace that transformed parameters definition with these two lines:

  matrix[nresp, ncov] tmp = rep_matrix(t_alpha, nresp) +  t_z_beta * Lbeta';
  matrix[nresp, ncov] t_beta = constrainsgn(tmp, idxpos, idxneg, xform, s);

Any idea what’s going on here?

The above workaround doesn’t really solve my problem, as I have a model already fit with cmdstanr, and wanted access to rstan’s built in loo moment matching method (which cmdstanr lacks). The plan was to create a stanfit object from the CmdStan output files, but that won’t work if I have to modify the Stan model to have an additional transformed parameter that was not present during model estimation.

I’m not sure what’s going on with the compiler error, but we did just release a cmdstanr that let’s you do moment matching with loo. This won’t help you with your existing fitted model object, but in the future you can use fit$loo(moment_match = TRUE).

It’s also possible that a similar compiler error would happen when cmdstanr has to compile the additional methods needed for loo with moment matching. It’s a very new feature so if you try it and run into trouble definitely let us know, there are likely still kinks to work out.