Expose_stan_functions not working with tuple

Using rstan, the following works fine:

model_code <-
  '
  functions {
    real standard_normal_rng() {
      return normal_rng(0,1);
   }
  }
'
expose_stan_functions(stanc(model_code = model_code))

but the following errors:

model_code <-
  '
  functions {
    tuple(real, int) log_prod_diff(vector log_a, real log_b) {
    int N = num_elements(log_a);
    real out = sum(log_a);
    int sign = 1;

    for (i in 1:N) {
      if (log_a[i] > log_b) {
        // Case: a > b
        out += -log_diff_exp(log_a[i], log_b);
      } else {
        // Case: a <= b
        out += -log_diff_exp(log_b, log_a[i]);
        sign = -sign;
      }
    }
    return (out, sign);
  }
  }
'
expose_stan_functions(stanc(model_code = model_code))

The error message is uninformative:

Error in expose_stan_functions(stanc(model_code = model_code)) :
Compilation failed!

R version 4.4.1 (2024-06-14)
Platform: aarch64-apple-darwin20
Running under: macOS Monterey 12.2.1

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRlapack.dylib; LAPACK version 3.12.0

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

time zone: Europe/London
tzcode source: internal

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] rstan_2.35.0.9000 StanHeaders_2.35.0.9000

loaded via a namespace (and not attached):
[1] vctrs_0.6.5 cli_3.6.3 rlang_1.1.4 processx_3.8.4
[5] RcppParallel_5.1.9 glue_1.7.0 BH_1.84.0-0 colorspace_2.1-1
[9] askpass_1.2.0 gridExtra_2.3 ps_1.7.7 pkgbuild_1.4.4
[13] sys_3.4.2 stats4_4.4.1 scales_1.3.0 fansi_1.0.6
[17] grid_4.4.1 munsell_0.5.1 tibble_3.2.1 lifecycle_1.0.4
[21] QuickJSR_1.3.1 inline_0.3.19 macrtools_0.0.4 compiler_4.4.1
[25] codetools_0.2-20 pkgconfig_2.0.3 Rcpp_1.0.13 RcppEigen_0.3.4.0.2
[29] R6_2.5.1 utf8_1.2.4 parallel_4.4.1 pillar_1.9.0
[33] callr_3.7.6 magrittr_2.0.3 loo_2.8.0.9000 tools_4.4.1
[37] gtable_0.3.5 matrixStats_1.4.1 ggplot2_3.5.1 remotes_2.5.0

I think tuples were introduced in 2.33 and unfortunately rstan is at 2.32 still. If you’re comfortable using cmdstanr, you can try cmdstanr’s expose_functions method:

I haven’t tested it with your function but hopefully that works.

3 Likes

Thanks! Good to know.

There is an rstan 2.35 available from the Stan r package servers… the rstan GitHub has the details for this.

1 Like