Sampling error when using external C++ lpdf

Hi all,

I am trying to write a custom lpdf in C++. I started by trying to run the example from this thread, but I get an error:

Here is the C++ code:

#include <stan/model/model_base.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/err/check_positive_finite.hpp>
#include <stan/math/prim/scal/fun/log_modified_bessel_first_kind.hpp>
#include <stan/math/prim/scal/fun/modified_bessel_first_kind.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <stan/math/prim/scal/fun/size_zero.hpp>
#include <cmath>

#include <boost/math/tools/promotion.hpp>

using namespace boost::math;
using namespace std;
using namespace stan;

template <bool propto, typename T_y, typename T_loc, typename T_scale>
typename boost::math::tools::promote_args<T_y, T_loc, T_scale>::type
custom_von_mises_lpdf(T_y const& y,
                      T_loc const& mu,
                      Eigen::Matrix<T_scale, 1, Eigen::Dynamic> const& kappa,
                      std::ostream* pstream__) {

  using T_partials_return = partials_return_t<T_y, T_loc, T_scale>;

  if (size_zero(y, mu, kappa)) {
    return 0.0;
  }

  using std::log;

  T_partials_return logp = 0.0;

  if (!include_summand<propto, T_y, T_loc, T_scale>::value) {
    return logp;
  }

  const bool y_const = is_constant_all<T_y>::value;
  const bool mu_const = is_constant_all<T_loc>::value;
  const bool kappa_const = is_constant_all<T_scale>::value;

  const bool compute_bessel0 = include_summand<propto, T_scale>::value;
  const bool compute_bessel1 = !kappa_const;
  const double TWO_PI = 2.0 * pi();

  scalar_seq_view<T_y> y_vec(y);
  scalar_seq_view<T_loc> mu_vec(mu);
  scalar_seq_view<Eigen::Matrix<T_scale, 1, Eigen::Dynamic>> kappa_vec(kappa);

  VectorBuilder<true, T_partials_return, T_scale> kappa_dbl(length(kappa));
  VectorBuilder<include_summand<propto, T_scale>::value, T_partials_return,
                T_scale>
      log_bessel0(length(kappa));
  for (size_t i = 0; i < length(kappa); i++) {
    kappa_dbl[i] = value_of(kappa_vec[i]);
    if (include_summand<propto, T_scale>::value) {
      log_bessel0[i]
          = log_modified_bessel_first_kind(0, value_of(kappa_vec[i]));
    }
  }

  operands_and_partials<T_y, T_loc, Eigen::Matrix<T_scale, 1, Eigen::Dynamic>>
    ops_partials(y, mu, kappa);

  size_t N = max_size(y, mu, kappa);

  for (size_t n = 0; n < N; n++) {
    const T_partials_return y_ = value_of(y_vec[n]);
    const T_partials_return y_dbl = y_ - floor(y_ / TWO_PI) * TWO_PI;
    const T_partials_return mu_dbl = value_of(mu_vec[n]);

    T_partials_return bessel0 = 0;
    if (compute_bessel0) {
      bessel0 = modified_bessel_first_kind(0, kappa_dbl[n]);
    }
    T_partials_return bessel1 = 0;
    if (compute_bessel1) {
      bessel1 = modified_bessel_first_kind(-1, kappa_dbl[n]);
    }
    const T_partials_return kappa_sin = kappa_dbl[n] * sin(mu_dbl - y_dbl);
    const T_partials_return kappa_cos = kappa_dbl[n] * cos(mu_dbl - y_dbl);

    if (include_summand<propto>::value) {
      logp -= LOG_TWO_PI;
    }
    if (include_summand<propto, T_scale>::value) {
      logp -= log_bessel0[n];
    }
    if (include_summand<propto, T_y, T_loc, T_scale>::value) {
      logp += kappa_cos;
    }

    if (!y_const) {
      ops_partials.edge1_.partials_[n] += kappa_sin;
    }
    if (!mu_const) {
      ops_partials.edge2_.partials_[n] -= kappa_sin;
    }
    if (!kappa_const) {
      ops_partials.edge3_.partials_[n]
          += kappa_cos / kappa_dbl[n] - bessel1 / bessel0;
    }
  }
  return ops_partials.build(logp);
}

And here is the R script that does the sampling:

library(rstan)
library(circular)
options(mc.cores = parallel::detectCores())
rstan_options(auto_write = TRUE)

mu <- 2*atan(-1.0) 
kappa <- exp(0.4)
N <- 10000
K <- 1
df <- data.frame(x=rep(1, N))
X <- model.matrix(~0+., data=df)
y <- rvonmises(N, mu, kappa)

y[y > pi] <- -(2*pi - y[y > pi])

model_code <- "
functions{
  real custom_von_mises_lpdf(real y, real mu, row_vector kappa);
}
data {
  int<lower=0> N; //the number of observations
  int<lower=0> K; //the number of columns in the model matrix
  matrix[N,K] X; //the model matrix
  vector[N] y; //the response
}
parameters {
  real kappa; //the scale parameter
  real mu; //the loc parameter
}
model {
  for(i in 1:N)
    y[i] ~ custom_von_mises(2*atan(mu), exp(X[i,]*kappa));
}"

init_mu = mean(y)
init_kappa = 1

model_source = stanc(model_code = model_code, allow_undefined = TRUE,
                     verbose = TRUE)

model <- stan_model(model_code = model_code,
                    allow_undefined = TRUE,
                    verbose = TRUE, 
                    includes = paste0('\n#include "',
                                      file.path(getwd(), 'custom_von_mises_lpdf.hpp'), '"\n'))

m <- sampling(model, data = list(X=X, K=K, N=N, y=y), chains = 1, cores=4,
              init=list(list(mu=init_mu, kappa=init_kappa)))

summary(m)

I get this error when I try to run the sampling function:

SAMPLING FOR MODEL 'b785e1b459e1a1bedfb490735b98118b' NOW (CHAIN 1).
Chain 1: 
Chain 1: Gradient evaluation took 0.039457 seconds
Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 394.57 seconds.
Chain 1: Adjust your expectations accordingly!
Chain 1: 
Chain 1: 
Chain 1: Iteration:    1 / 2000 [  0%]  (Warmup)
[1] "Error in sampler$call_sampler(args_list[[i]]) : "
[2] "  c++ exception (unknown reason)"                
error occurred during calling the sampler; sampling not done

I don’t get any errors when running Stan code that doesn’t involve an external lpdf. I have also tried some of the Catalina-related suggestions discussed here to no avail:

  • Operating System: Catalina 10.15.6
  • RStan Version: rstan_2.21.1
  • Output of writeLines(readLines(file.path(Sys.getenv("HOME"), ".R/Makevars"))):
# The following statements are required to use the clang4 binary
LDFLAGS= -L/usr/local/clang4/lib
# End clang4 inclusion statements
CC=/usr/local/clang4/bin/clang
CXX=/usr/local/clang4/bin/clang++
CXX1X=/usr/local/clang4/bin/clang++
CXX98=/usr/local/clang4/bin/clang++
CXX11=/usr/local/clang4/bin/clang++
CXX14=/usr/local/clang4/bin/clang++
CXX17=/usr/local/clang4/bin/clang++
  • Output of devtools::session_info("rstan"):
─ Session info ──────────────────────────────────────────────────────────────
 setting  value                       
 version  R version 4.0.3 (2020-10-10)
 os       macOS Catalina 10.15.6      
 system   x86_64, darwin17.0          
 ui       RStudio                     
 language (EN)                        
 collate  en_US.UTF-8                 
 ctype    en_US.UTF-8                 
 tz       America/New_York            
 date     2020-10-15                  

─ Packages ──────────────────────────────────────────────────────────────────
 package      * version   date       lib source        
 assertthat     0.2.1     2019-03-21 [1] CRAN (R 4.0.2)
 backports      1.1.10    2020-09-15 [1] CRAN (R 4.0.2)
 BH             1.72.0-3  2020-01-08 [1] CRAN (R 4.0.2)
 callr          3.5.1     2020-10-13 [1] CRAN (R 4.0.3)
 checkmate      2.0.0     2020-02-06 [1] CRAN (R 4.0.2)
 cli            2.1.0     2020-10-12 [1] CRAN (R 4.0.3)
 colorspace     1.4-1     2019-03-18 [1] CRAN (R 4.0.2)
 crayon         1.3.4     2017-09-16 [1] CRAN (R 4.0.2)
 curl           4.3       2019-12-02 [1] CRAN (R 4.0.1)
 desc           1.2.0     2018-05-01 [1] CRAN (R 4.0.2)
 digest         0.6.25    2020-02-23 [1] CRAN (R 4.0.2)
 ellipsis       0.3.1     2020-05-15 [1] CRAN (R 4.0.2)
 evaluate       0.14      2019-05-28 [1] CRAN (R 4.0.1)
 fansi          0.4.1     2020-01-08 [1] CRAN (R 4.0.2)
 farver         2.0.3     2020-01-16 [1] CRAN (R 4.0.2)
 ggplot2      * 3.3.2     2020-06-19 [1] CRAN (R 4.0.2)
 glue           1.4.2     2020-08-27 [1] CRAN (R 4.0.2)
 gridExtra      2.3       2017-09-09 [1] CRAN (R 4.0.2)
 gtable         0.3.0     2019-03-25 [1] CRAN (R 4.0.2)
 inline         0.3.16    2020-09-06 [1] CRAN (R 4.0.2)
 isoband        0.2.2     2020-06-20 [1] CRAN (R 4.0.2)
 jsonlite       1.7.1     2020-09-07 [1] CRAN (R 4.0.2)
 labeling       0.3       2014-08-23 [1] CRAN (R 4.0.2)
 lattice        0.20-41   2020-04-02 [1] CRAN (R 4.0.3)
 lifecycle      0.2.0     2020-03-06 [1] CRAN (R 4.0.2)
 loo            2.3.1     2020-07-14 [1] CRAN (R 4.0.2)
 magrittr       1.5       2014-11-22 [1] CRAN (R 4.0.2)
 MASS           7.3-53    2020-09-09 [1] CRAN (R 4.0.3)
 Matrix         1.2-18    2019-11-27 [1] CRAN (R 4.0.3)
 matrixStats    0.57.0    2020-09-25 [1] CRAN (R 4.0.2)
 mgcv           1.8-33    2020-08-27 [1] CRAN (R 4.0.3)
 munsell        0.5.0     2018-06-12 [1] CRAN (R 4.0.2)
 nlme           3.1-149   2020-08-23 [1] CRAN (R 4.0.3)
 pillar         1.4.6     2020-07-10 [1] CRAN (R 4.0.2)
 pkgbuild       1.1.0     2020-07-13 [1] CRAN (R 4.0.2)
 pkgconfig      2.0.3     2019-09-22 [1] CRAN (R 4.0.2)
 pkgload        1.1.0     2020-05-29 [1] CRAN (R 4.0.2)
 praise         1.0.0     2015-08-11 [1] CRAN (R 4.0.2)
 prettyunits    1.1.1     2020-01-24 [1] CRAN (R 4.0.2)
 processx       3.4.4     2020-09-03 [1] CRAN (R 4.0.2)
 ps             1.4.0     2020-10-07 [1] CRAN (R 4.0.2)
 R6             2.4.1     2019-11-12 [1] CRAN (R 4.0.2)
 RColorBrewer   1.1-2     2014-12-07 [1] CRAN (R 4.0.2)
 Rcpp           1.0.5     2020-07-06 [1] CRAN (R 4.0.2)
 RcppEigen      0.3.3.7.0 2019-11-16 [1] CRAN (R 4.0.2)
 RcppParallel   5.0.2     2020-06-24 [1] CRAN (R 4.0.2)
 rlang          0.4.8     2020-10-08 [1] CRAN (R 4.0.2)
 rprojroot      1.3-2     2018-01-03 [1] CRAN (R 4.0.2)
 rstan        * 2.21.1    2020-07-08 [1] CRAN (R 4.0.2)
 rstudioapi     0.11      2020-02-07 [1] CRAN (R 4.0.2)
 scales         1.1.1     2020-05-11 [1] CRAN (R 4.0.2)
 StanHeaders  * 2.21.0-6  2020-08-16 [1] CRAN (R 4.0.2)
 testthat       2.3.2     2020-03-02 [1] CRAN (R 4.0.2)
 tibble         3.0.4     2020-10-12 [1] CRAN (R 4.0.3)
 utf8           1.1.4     2018-05-24 [1] CRAN (R 4.0.2)
 V8             3.2.0     2020-06-19 [1] CRAN (R 4.0.2)
 vctrs          0.3.4     2020-08-29 [1] CRAN (R 4.0.2)
 viridisLite    0.3.0     2018-02-01 [1] CRAN (R 4.0.1)
 withr          2.3.0     2020-09-22 [1] CRAN (R 4.0.2)

[1] /Library/Frameworks/R.framework/Versions/4.0/Resources/library

Thanks in advance.

1 Like

For R 4.x on Macs, you should get rid of ~/.R/Makevars file and eliminate any line that sets the path in ~/.Renviron or ~/.Rprofile. Then it should work because it will compile with the same XCode toolchain that was used to build R.

Thanks for the reply @bgoodri. I removed ~/.R/Makevars (and didn’t have a ~/.Renviron or ~/.Rprofile), but I am now getting a new error. Here’s the full error message

ERROR(s) during compilation: source code errors or compiler configuration errors!

Program source:
  1: 
  2: // includes from the plugin
  3: // [[Rcpp::plugins(cpp14)]]
  4: 
  5: 
  6: // user includes
  7: #include <Rcpp.h>
  8: #include <rstan/io/rlist_ref_var_context.hpp>
  9: #include <rstan/io/r_ostream.hpp>
 10: #include <rstan/stan_args.hpp>
 11: #include <boost/integer/integer_log2.hpp>
 12: // Code generated by Stan version 2.21.0
 13: 
 14: #include <stan/model/model_header.hpp>
 15: 
 16: namespace modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b_namespace {
 17: 
 18: using std::istream;
 19: using std::string;
 20: using std::stringstream;
 21: using std::vector;
 22: using stan::io::dump;
 23: using stan::math::lgamma;
 24: using stan::model::prob_grad;
 25: using namespace stan::math;
 26: 
 27: static int current_statement_begin__;
 28: 
 29: stan::io::program_reader prog_reader__() {
 30:     stan::io::program_reader reader;
 31:     reader.add_event(0, 0, "start", "modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b");
 32:     reader.add_event(20, 18, "end", "modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b");
 33:     return reader;
 34: }
 35: 
 36: template <bool propto, typename T0__, typename T1__, typename T2__>
 37: typename boost::math::tools::promote_args<T0__, T1__, T2__>::type
 38: custom_von_mises_lpdf(const T0__& y,
 39:                           const T1__& mu,
 40:                           const Eigen::Matrix<T2__, 1, Eigen::Dynamic>& kappa, std::ostream* pstream__);
 41: 
 42: 
 43: #include "/Users/ramin/custm_von_mises_lpdf2.hpp"
 44:  class modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b
 45:   : public stan::model::model_base_crtp<modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b> {
 46: private:
 47:         int N;
 48:         int K;
 49:         matrix_d X;
 50:         vector_d y;
 51: public:
 52:     modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b(rstan::io::rlist_ref_var_context& context__,
 53:         std::ostream* pstream__ = 0)
 54:         : model_base_crtp(0) {
 55:         ctor_body(context__, 0, pstream__);
 56:     }
 57: 
 58:     modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b(stan::io::var_context& context__,
 59:         unsigned int random_seed__,
 60:         std::ostream* pstream__ = 0)
 61:         : model_base_crtp(0) {
 62:         ctor_body(context__, random_seed__, pstream__);
 63:     }
 64: 
 65:     void ctor_body(stan::io::var_context& context__,
 66:                    unsigned int random_seed__,
 67:                    std::ostream* pstream__) {
 68:         typedef double local_scalar_t__;
 69: 
 70:         boost::ecuyer1988 base_rng__ =
 71:           stan::services::util::create_rng(random_seed__, 0);
 72:         (void) base_rng__;  // suppress unused var warning
 73: 
 74:         current_statement_begin__ = -1;
 75: 
 76:         static const char* function__ = "modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b_namespace::modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b";
 77:         (void) function__;  // dummy to suppress unused var warning
 78:         size_t pos__;
 79:         (void) pos__;  // dummy to suppress unused var warning
 80:         std::vector<int> vals_i__;
 81:         std::vector<double> vals_r__;
 82:         local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN());
 83:         (void) DUMMY_VAR__;  // suppress unused var warning
 84: 
 85:         try {
 86:             // initialize data block variables from context__
 87:             current_statement_begin__ = 6;
 88:             context__.validate_dims("data initialization", "N", "int", context__.to_vec());
 89:             N = int(0);
 90:             vals_i__ = context__.vals_i("N");
 91:             pos__ = 0;
 92:             N = vals_i__[pos__++];
 93:             check_greater_or_equal(function__, "N", N, 0);
 94: 
 95:             current_statement_begin__ = 7;
 96:             context__.validate_dims("data initialization", "K", "int", context__.to_vec());
 97:             K = int(0);
 98:             vals_i__ = context__.vals_i("K");
 99:             pos__ = 0;
100:             K = vals_i__[pos__++];
101:             check_greater_or_equal(function__, "K", K, 0);
102: 
103:             current_statement_begin__ = 8;
104:             validate_non_negative_index("X", "N", N);
105:             validate_non_negative_index("X", "K", K);
106:             context__.validate_dims("data initialization", "X", "matrix_d", context__.to_vec(N,K));
107:             X = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>(N, K);
108:             vals_r__ = context__.vals_r("X");
109:             pos__ = 0;
110:             size_t X_j_2_max__ = K;
111:             size_t X_j_1_max__ = N;
112:             for (size_t j_2__ = 0; j_2__ < X_j_2_max__; ++j_2__) {
113:                 for (size_t j_1__ = 0; j_1__ < X_j_1_max__; ++j_1__) {
114:                     X(j_1__, j_2__) = vals_r__[pos__++];
115:                 }
116:             }
117: 
118:             current_statement_begin__ = 9;
119:             validate_non_negative_index("y", "N", N);
120:             context__.validate_dims("data initialization", "y", "vector_d", context__.to_vec(N));
121:             y = Eigen::Matrix<double, Eigen::Dynamic, 1>(N);
122:             vals_r__ = context__.vals_r("y");
123:             pos__ = 0;
124:             size_t y_j_1_max__ = N;
125:             for (size_t j_1__ = 0; j_1__ < y_j_1_max__; ++j_1__) {
126:                 y(j_1__) = vals_r__[pos__++];
127:             }
128: 
129: 
130:             // initialize transformed data variables
131:             // execute transformed data statements
132: 
133:             // validate transformed data
134: 
135:             // validate, set parameter ranges
136:             num_params_r__ = 0U;
137:             param_ranges_i__.clear();
138:             current_statement_begin__ = 12;
139:             num_params_r__ += 1;
140:             current_statement_begin__ = 13;
141:             num_params_r__ += 1;
142:         } catch (const std::exception& e) {
143:             stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__());
144:             // Next line prevents compiler griping about no return
145:             throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***");
146:         }
147:     }
148: 
149:     ~modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b() { }
150: 
151: 
152:     void transform_inits(const stan::io::var_context& context__,
153:                          std::vector<int>& params_i__,
154:                          std::vector<double>& params_r__,
155:                          std::ostream* pstream__) const {
156:         typedef double local_scalar_t__;
157:         stan::io::writer<double> writer__(params_r__, params_i__);
158:         size_t pos__;
159:         (void) pos__; // dummy call to supress warning
160:         std::vector<double> vals_r__;
161:         std::vector<int> vals_i__;
162: 
163:         current_statement_begin__ = 12;
164:         if (!(context__.contains_r("kappa")))
165:             stan::lang::rethrow_located(std::runtime_error(std::string("Variable kappa missing")), current_statement_begin__, prog_reader__());
166:         vals_r__ = context__.vals_r("kappa");
167:         pos__ = 0U;
168:         context__.validate_dims("parameter initialization", "kappa", "double", context__.to_vec());
169:         double kappa(0);
170:         kappa = vals_r__[pos__++];
171:         try {
172:             writer__.scalar_unconstrain(kappa);
173:         } catch (const std::exception& e) {
174:             stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable kappa: ") + e.what()), current_statement_begin__, prog_reader__());
175:         }
176: 
177:         current_statement_begin__ = 13;
178:         if (!(context__.contains_r("mu")))
179:             stan::lang::rethrow_located(std::runtime_error(std::string("Variable mu missing")), current_statement_begin__, prog_reader__());
180:         vals_r__ = context__.vals_r("mu");
181:         pos__ = 0U;
182:         context__.validate_dims("parameter initialization", "mu", "double", context__.to_vec());
183:         double mu(0);
184:         mu = vals_r__[pos__++];
185:         try {
186:             writer__.scalar_unconstrain(mu);
187:         } catch (const std::exception& e) {
188:             stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable mu: ") + e.what()), current_statement_begin__, prog_reader__());
189:         }
190: 
191:         params_r__ = writer__.data_r();
192:         params_i__ = writer__.data_i();
193:     }
194: 
195:     void transform_inits(const stan::io::var_context& context,
196:                          Eigen::Matrix<double, Eigen::Dynamic, 1>& params_r,
197:                          std::ostream* pstream__) const {
198:       std::vector<double> params_r_vec;
199:       std::vector<int> params_i_vec;
200:       transform_inits(context, params_i_vec, params_r_vec, pstream__);
201:       params_r.resize(params_r_vec.size());
202:       for (int i = 0; i < params_r.size(); ++i)
203:         params_r(i) = params_r_vec[i];
204:     }
205: 
206: 
207:     template <bool propto__, bool jacobian__, typename T__>
208:     T__ log_prob(std::vector<T__>& params_r__,
209:                  std::vector<int>& params_i__,
210:                  std::ostream* pstream__ = 0) const {
211: 
212:         typedef T__ local_scalar_t__;
213: 
214:         local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN());
215:         (void) DUMMY_VAR__;  // dummy to suppress unused var warning
216: 
217:         T__ lp__(0.0);
218:         stan::math::accumulator<T__> lp_accum__;
219:         try {
220:             stan::io::reader<local_scalar_t__> in__(params_r__, params_i__);
221: 
222:             // model parameters
223:             current_statement_begin__ = 12;
224:             local_scalar_t__ kappa;
225:             (void) kappa;  // dummy to suppress unused var warning
226:             if (jacobian__)
227:                 kappa = in__.scalar_constrain(lp__);
228:             else
229:                 kappa = in__.scalar_constrain();
230: 
231:             current_statement_begin__ = 13;
232:             local_scalar_t__ mu;
233:             (void) mu;  // dummy to suppress unused var warning
234:             if (jacobian__)
235:                 mu = in__.scalar_constrain(lp__);
236:             else
237:                 mu = in__.scalar_constrain();
238: 
239:             // model body
240: 
241:             current_statement_begin__ = 16;
242:             for (int i = 1; i <= N; ++i) {
243:                 current_statement_begin__ = 17;
244:                 lp_accum__.add(custom_von_mises_lpdf<propto__>(get_base1(y, i, "y", 1), (2 * stan::math::atan(mu)), stan::math::exp(multiply(stan::model::rvalue(X, stan::model::cons_list(stan::model::index_uni(i), stan::model::cons_list(stan::model::index_omni(), stan::model::nil_index_list())), "X"), kappa)), pstream__));
245:             }
246: 
247:         } catch (const std::exception& e) {
248:             stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__());
249:             // Next line prevents compiler griping about no return
250:             throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***");
251:         }
252: 
253:         lp_accum__.add(lp__);
254:         return lp_accum__.sum();
255: 
256:     } // log_prob()
257: 
258:     template <bool propto, bool jacobian, typename T_>
259:     T_ log_prob(Eigen::Matrix<T_,Eigen::Dynamic,1>& params_r,
260:                std::ostream* pstream = 0) const {
261:       std::vector<T_> vec_params_r;
262:       vec_params_r.reserve(params_r.size());
263:       for (int i = 0; i < params_r.size(); ++i)
264:         vec_params_r.push_back(params_r(i));
265:       std::vector<int> vec_params_i;
266:       return log_prob<propto,jacobian,T_>(vec_params_r, vec_params_i, pstream);
267:     }
268: 
269: 
270:     void get_param_names(std::vector<std::string>& names__) const {
271:         names__.resize(0);
272:         names__.push_back("kappa");
273:         names__.push_back("mu");
274:     }
275: 
276: 
277:     void get_dims(std::vector<std::vector<size_t> >& dimss__) const {
278:         dimss__.resize(0);
279:         std::vector<size_t> dims__;
280:         dims__.resize(0);
281:         dimss__.push_back(dims__);
282:         dims__.resize(0);
283:         dimss__.push_back(dims__);
284:     }
285: 
286:     template <typename RNG>
287:     void write_array(RNG& base_rng__,
288:                      std::vector<double>& params_r__,
289:                      std::vector<int>& params_i__,
290:                      std::vector<double>& vars__,
291:                      bool include_tparams__ = true,
292:                      bool include_gqs__ = true,
293:                      std::ostream* pstream__ = 0) const {
294:         typedef double local_scalar_t__;
295: 
296:         vars__.resize(0);
297:         stan::io::reader<local_scalar_t__> in__(params_r__, params_i__);
298:         static const char* function__ = "modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b_namespace::write_array";
299:         (void) function__;  // dummy to suppress unused var warning
300: 
301:         // read-transform, write parameters
302:         double kappa = in__.scalar_constrain();
303:         vars__.push_back(kappa);
304: 
305:         double mu = in__.scalar_constrain();
306:         vars__.push_back(mu);
307: 
308:         double lp__ = 0.0;
309:         (void) lp__;  // dummy to suppress unused var warning
310:         stan::math::accumulator<double> lp_accum__;
311: 
312:         local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN());
313:         (void) DUMMY_VAR__;  // suppress unused var warning
314: 
315:         if (!include_tparams__ && !include_gqs__) return;
316: 
317:         try {
318:             if (!include_gqs__ && !include_tparams__) return;
319:             if (!include_gqs__) return;
320:         } catch (const std::exception& e) {
321:             stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__());
322:             // Next line prevents compiler griping about no return
323:             throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***");
324:         }
325:     }
326: 
327:     template <typename RNG>
328:     void write_array(RNG& base_rng,
329:                      Eigen::Matrix<double,Eigen::Dynamic,1>& params_r,
330:                      Eigen::Matrix<double,Eigen::Dynamic,1>& vars,
331:                      bool include_tparams = true,
332:                      bool include_gqs = true,
333:                      std::ostream* pstream = 0) const {
334:       std::vector<double> params_r_vec(params_r.size());
335:       for (int i = 0; i < params_r.size(); ++i)
336:         params_r_vec[i] = params_r(i);
337:       std::vector<double> vars_vec;
338:       std::vector<int> params_i_vec;
339:       write_array(base_rng, params_r_vec, params_i_vec, vars_vec, include_tparams, include_gqs, pstream);
340:       vars.resize(vars_vec.size());
341:       for (int i = 0; i < vars.size(); ++i)
342:         vars(i) = vars_vec[i];
343:     }
344: 
345:     std::string model_name() const {
346:         return "modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b";
347:     }
348: 
349: 
350:     void constrained_param_names(std::vector<std::string>& param_names__,
351:                                  bool include_tparams__ = true,
352:                                  bool include_gqs__ = true) const {
353:         std::stringstream param_name_stream__;
354:         param_name_stream__.str(std::string());
355:         param_name_stream__ << "kappa";
356:         param_names__.push_back(param_name_stream__.str());
357:         param_name_stream__.str(std::string());
358:         param_name_stream__ << "mu";
359:         param_names__.push_back(param_name_stream__.str());
360: 
361:         if (!include_gqs__ && !include_tparams__) return;
362: 
363:         if (include_tparams__) {
364:         }
365: 
366:         if (!include_gqs__) return;
367:     }
368: 
369: 
370:     void unconstrained_param_names(std::vector<std::string>& param_names__,
371:                                    bool include_tparams__ = true,
372:                                    bool include_gqs__ = true) const {
373:         std::stringstream param_name_stream__;
374:         param_name_stream__.str(std::string());
375:         param_name_stream__ << "kappa";
376:         param_names__.push_back(param_name_stream__.str());
377:         param_name_stream__.str(std::string());
378:         param_name_stream__ << "mu";
379:         param_names__.push_back(param_name_stream__.str());
380: 
381:         if (!include_gqs__ && !include_tparams__) return;
382: 
383:         if (include_tparams__) {
384:         }
385: 
386:         if (!include_gqs__) return;
387:     }
388: 
389: }; // model
390: 
391: }  // namespace
392: 
393: typedef modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b_namespace::modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b stan_model;
394: 
395: #ifndef USING_R
396: 
397: stan::model::model_base& new_model(
398:         stan::io::var_context& data_context,
399:         unsigned int seed,
400:         std::ostream* msg_stream) {
401:   stan_model* m = new stan_model(data_context, seed, msg_stream);
402:   return *m;
403: }
404: 
405: #endif
406: 
407: 
408: 
409: #include <rstan_next/stan_fit.hpp>
410: 
411: struct stan_model_holder {
412:     stan_model_holder(rstan::io::rlist_ref_var_context rcontext,
413:                       unsigned int random_seed)
414:     : rcontext_(rcontext), random_seed_(random_seed)
415:      {
416:      }
417: 
418:    //stan::math::ChainableStack ad_stack;
419:    rstan::io::rlist_ref_var_context rcontext_;
420:    unsigned int random_seed_;
421: };
422: 
423: Rcpp::XPtr<stan::model::model_base> model_ptr(stan_model_holder* smh) {
424:   Rcpp::XPtr<stan::model::model_base> model_instance(new stan_model(smh->rcontext_, smh->random_seed_), true);
425:   return model_instance;
426: }
427: 
428: Rcpp::XPtr<rstan::stan_fit_base> fit_ptr(stan_model_holder* smh) {
429:   return Rcpp::XPtr<rstan::stan_fit_base>(new rstan::stan_fit(model_ptr(smh), smh->random_seed_), true);
430: }
431: 
432: std::string model_name(stan_model_holder* smh) {
433:   return model_ptr(smh).get()->model_name();
434: }
435: 
436: RCPP_MODULE(stan_fit4modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b_mod){
437:   Rcpp::class_<stan_model_holder>("stan_fit4modela56e72a1d7fc_b785e1b459e1a1bedfb490735b98118b")
438:   .constructor<rstan::io::rlist_ref_var_context, unsigned int>()
439:   .method("model_ptr", &model_ptr)
440:   .method("fit_ptr", &fit_ptr)
441:   .method("model_name", &model_name)
442:   ;
443: }
444: 
445: 
446: // declarations
447: extern "C" {
448: SEXP filea56e5f6b1c2f( ) ;
449: }
450: 
451: // definition
452: 
453: SEXP filea56e5f6b1c2f(  ){
454:  return Rcpp::wrap("b785e1b459e1a1bedfb490735b98118b");
455: }
456: 
457: 

Compilation ERROR, function(s)/method(s) not created!
Error in compileCode(f, code, language = language, verbose = verbose) : 
  /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/cmath:649:25: error: no template named 'numeric_limits'  return _FloatBigger ? numeric_limits<_IntT>::max() :  (numeric_limits<_IntT>::max() >> _Bits << _Bits);                        ^fatal error: too many errors emitted, stopping now [-ferror-limit=]20 errors generated.make: *** [filea56e5f6b1c2f.o] Error 1

I’m getting this error at the call to stan_model in the below script

library(rstan)
library(circular)
options(mc.cores = parallel::detectCores())
rstan_options(auto_write = TRUE)

mu <- 2*atan(-1.0) 
kappa <- exp(0.4)
N <- 10000
K <- 1
df <- data.frame(x=rep(1, N))
X <- model.matrix(~0+., data=df)
y <- rvonmises(N, mu, kappa)

y[y > pi] <- -(2*pi - y[y > pi])

model_code <- "
functions{
  real custom_von_mises_lpdf(real y, real mu, row_vector kappa);
}
data {
  int<lower=0> N; //the number of observations
  int<lower=0> K; //the number of columns in the model matrix
  matrix[N,K] X; //the model matrix
  vector[N] y; //the response
}
parameters {
  real kappa; //the scale parameter
  real mu; //the loc parameter
}
model {
  for(i in 1:N)
    y[i] ~ custom_von_mises(2*atan(mu), exp(X[i,]*kappa));
}"

init_mu = mean(y)
init_kappa = 1

model_source = stanc(model_code = model_code, allow_undefined = TRUE,
                     verbose = TRUE)

model <- stan_model(model_code = model_code,
                    allow_undefined = TRUE,
                    verbose = TRUE, 
                    includes = paste0('\n#include "',
                                      file.path(getwd(), 'custom_von_mises_lpdf2.hpp'), '"\n'))

m <- sampling(model, data = list(X=X, K=K, N=N, y=y), chains = 1, cores=4,
              init=list(list(mu=init_mu, kappa=init_kappa)))

summary(m)

This all works for me, so I think you toolchain is messed up. Can you do

example(stan_model, package = "rstan", run.dontrun = TRUE)

?

I get an error message:

Compilation ERROR, function(s)/method(s) not created!
Error in compileCode(f, code, language = language, verbose = verbose) : 
  /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/cmath:649:25: error: no template named 'numeric_limits'  return _FloatBigger ? numeric_limits<_IntT>::max() :  (numeric_limits<_IntT>::max() >> _Bits << _Bits);                        ^fatal error: too many errors emitted, stopping now [-ferror-limit=]20 errors generated.make: *** [filea56e23ac94ff.o] Error 1
In addition: Warning messages:
1: In system2(CXX, args = ARGS) : error in running command
2: In file.remove(c(unprocessed, processed)) :
  cannot remove file '/var/folders/5j/8cyf3lpd3wzfsrrq1rp8thbm0000gp/T//Rtmp7yIoPe/filea56e195edfa4.stan', reason 'No such file or directory

OK, your problem is definitely that your C++ toolchain is messed up rather than anything having to do with the external C++. What was the part of the messages under the line β€œmake would use”?

Here’s what is says under make would use:

make would use
clang++ -mmacosx-version-min=10.13 -std=gnu++14 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/Rcpp/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppEigen/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppEigen/include/unsupported"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/BH/include" -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/include/src/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppParallel/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/rstan/include" -DEIGEN_NO_DEBUG  -DBOOST_DISABLE_ASSERTS  -DBOOST_PENDING_INTEGER_LOG2_HPP  -DSTAN_THREADS  -DBOOST_NO_AUTO_PTR  -include '/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/include/stan/math/prim/mat/fun/Eigen.hpp'  -D_REENTRANT -DRCPP_PARALLEL_USE_TBB=1   -I/usr/local/include   -fPIC  -Wall -g -O2  -c filea56e23ac94ff.cpp -o filea56e23ac94ff.o
if test  "zfilea56e23ac94ff.o" != "z"; then \
	  echo clang++ -mmacosx-version-min=10.13 -std=gnu++14 -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L"/Library/Frameworks/R.framework/Resources/lib" -L/usr/local/lib -o filea56e23ac94ff.so filea56e23ac94ff.o  /Library/Frameworks/R.framework/Versions/4.0/Resources/library/rstan/lib//libStanServices.a -L'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/lib/' -lStanHeaders -L'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppParallel/lib/' -ltbb -ltbbmalloc -ltbbmalloc_proxy  -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation; \
	  clang++ -mmacosx-version-min=10.13 -std=gnu++14 -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L"/Library/Frameworks/R.framework/Resources/lib" -L/usr/local/lib -o filea56e23ac94ff.so filea56e23ac94ff.o  /Library/Frameworks/R.framework/Versions/4.0/Resources/library/rstan/lib//libStanServices.a -L'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/lib/' -lStanHeaders -L'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppParallel/lib/' -ltbb -ltbbmalloc -ltbbmalloc_proxy  -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation; \
	fi

I can’t post the full error message because it’s too big, but here’s most of it:

stn_md> stancode <- 'data {real y_mean;} parameters {real y;} model {y ~ normal(y_mean,1);}'

stn_md> mod <- stan_model(model_code = stancode, verbose = TRUE)

TRANSLATING MODEL '16a540c6086086816528e4524def24d9' FROM Stan CODE TO C++ CODE NOW.
successful in parsing the Stan model '16a540c6086086816528e4524def24d9'.
sh: clang++ -mmacosx-version-min=10.13: command not found
The NEXT version of Stan will not be able to pre-process your Stan program.
Please open an issue at
 https://github.com/stan-dev/stanc3/issues 
if you can share or at least describe your Stan program. This will help ensure that Stan
continues to work on your Stan programs in the future. Thank you!
This message can be avoided by wrapping your function call inside suppressMessages().
COMPILING THE C++ CODE FOR MODEL '16a540c6086086816528e4524def24d9' NOW.
OS: x86_64, darwin17.0; rstan: 2.21.1; Rcpp: 1.0.5; inline: 0.3.16 
 >> setting environment variables: 
PKG_LIBS =  /Library/Frameworks/R.framework/Versions/4.0/Resources/library/rstan/lib//libStanServices.a -L'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/lib/' -lStanHeaders -L'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppParallel/lib/' -ltbb -ltbbmalloc -ltbbmalloc_proxy
PKG_CPPFLAGS =   -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/Rcpp/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppEigen/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppEigen/include/unsupported"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/BH/include" -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/include/src/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppParallel/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/rstan/include" -DEIGEN_NO_DEBUG  -DBOOST_DISABLE_ASSERTS  -DBOOST_PENDING_INTEGER_LOG2_HPP  -DSTAN_THREADS  -DBOOST_NO_AUTO_PTR  -include '/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/include/stan/math/prim/mat/fun/Eigen.hpp'  -D_REENTRANT -DRCPP_PARALLEL_USE_TBB=1 
 >> Program source :

   1 : 
   2 : // includes from the plugin
   3 : // [[Rcpp::plugins(cpp14)]]
   4 : 
   5 : 
   6 : // user includes
   7 : #include <Rcpp.h>
   8 : #include <rstan/io/rlist_ref_var_context.hpp>
   9 : #include <rstan/io/r_ostream.hpp>
  10 : #include <rstan/stan_args.hpp>
  11 : #include <boost/integer/integer_log2.hpp>
  12 : // Code generated by Stan version 2.21.0
  13 : 
  14 : #include <stan/model/model_header.hpp>
  15 : 
  16 : namespace modela56e666cb8f6_16a540c6086086816528e4524def24d9_namespace {
  17 : 
  18 : using std::istream;
  19 : using std::string;
  20 : using std::stringstream;
  21 : using std::vector;
  22 : using stan::io::dump;
  23 : using stan::math::lgamma;
  24 : using stan::model::prob_grad;
  25 : using namespace stan::math;
  26 : 
  27 : static int current_statement_begin__;
  28 : 
  29 : stan::io::program_reader prog_reader__() {
  30 :     stan::io::program_reader reader;
  31 :     reader.add_event(0, 0, "start", "modela56e666cb8f6_16a540c6086086816528e4524def24d9");
  32 :     reader.add_event(3, 1, "end", "modela56e666cb8f6_16a540c6086086816528e4524def24d9");
  33 :     return reader;
  34 : }
  35 : 
  36 : class modela56e666cb8f6_16a540c6086086816528e4524def24d9
  37 :   : public stan::model::model_base_crtp<modela56e666cb8f6_16a540c6086086816528e4524def24d9> {
  38 : private:
  39 :         double y_mean;
  40 : public:
  41 :     modela56e666cb8f6_16a540c6086086816528e4524def24d9(rstan::io::rlist_ref_var_context& context__,
  42 :         std::ostream* pstream__ = 0)
  43 :         : model_base_crtp(0) {
  44 :         ctor_body(context__, 0, pstream__);
  45 :     }
  46 : 
  47 :     modela56e666cb8f6_16a540c6086086816528e4524def24d9(stan::io::var_context& context__,
  48 :         unsigned int random_seed__,
  49 :         std::ostream* pstream__ = 0)
  50 :         : model_base_crtp(0) {
  51 :         ctor_body(context__, random_seed__, pstream__);
  52 :     }
  53 : 
  54 :     void ctor_body(stan::io::var_context& context__,
  55 :                    unsigned int random_seed__,
  56 :                    std::ostream* pstream__) {
  57 :         typedef double local_scalar_t__;
  58 : 
  59 :         boost::ecuyer1988 base_rng__ =
  60 :           stan::services::util::create_rng(random_seed__, 0);
  61 :         (void) base_rng__;  // suppress unused var warning
  62 : 
  63 :         current_statement_begin__ = -1;
  64 : 
  65 :         static const char* function__ = "modela56e666cb8f6_16a540c6086086816528e4524def24d9_namespace::modela56e666cb8f6_16a540c6086086816528e4524def24d9";
  66 :         (void) function__;  // dummy to suppress unused var warning
  67 :         size_t pos__;
  68 :         (void) pos__;  // dummy to suppress unused var warning
  69 :         std::vector<int> vals_i__;
  70 :         std::vector<double> vals_r__;
  71 :         local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN());
  72 :         (void) DUMMY_VAR__;  // suppress unused var warning
  73 : 
  74 :         try {
  75 :             // initialize data block variables from context__
  76 :             current_statement_begin__ = 1;
  77 :             context__.validate_dims("data initialization", "y_mean", "double", context__.to_vec());
  78 :             y_mean = double(0);
  79 :             vals_r__ = context__.vals_r("y_mean");
  80 :             pos__ = 0;
  81 :             y_mean = vals_r__[pos__++];
  82 : 
  83 : 
  84 :             // initialize transformed data variables
  85 :             // execute transformed data statements
  86 : 
  87 :             // validate transformed data
  88 : 
  89 :             // validate, set parameter ranges
  90 :             num_params_r__ = 0U;
  91 :             param_ranges_i__.clear();
...
 265 : 
 266 :     std::string model_name() const {
 267 :         return "modela56e666cb8f6_16a540c6086086816528e4524def24d9";
 268 :     }
 269 : 
 270 : 
 271 :     void constrained_param_names(std::vector<std::string>& param_names__,
 272 :                                  bool include_tparams__ = true,
 273 :                                  bool include_gqs__ = true) const {
 274 :         std::stringstream param_name_stream__;
 275 :         param_name_stream__.str(std::string());
 276 :         param_name_stream__ << "y";
 277 :         param_names__.push_back(param_name_stream__.str());
 278 : 
 279 :         if (!include_gqs__ && !include_tparams__) return;
 280 : 
 281 :         if (include_tparams__) {
 282 :         }
 283 : 
 284 :         if (!include_gqs__) return;
 285 :     }
 286 : 
 287 : 
 288 :     void unconstrained_param_names(std::vector<std::string>& param_names__,
 289 :                                    bool include_tparams__ = true,
 290 :                                    bool include_gqs__ = true) const {
 291 :         std::stringstream param_name_stream__;
 292 :         param_name_stream__.str(std::string());
 293 :         param_name_stream__ << "y";
 294 :         param_names__.push_back(param_name_stream__.str());
 295 : 
 296 :         if (!include_gqs__ && !include_tparams__) return;
 297 : 
 298 :         if (include_tparams__) {
 299 :         }
 300 : 
 301 :         if (!include_gqs__) return;
 302 :     }
 303 : 
 304 : }; // model
 305 : 
 306 : }  // namespace
 307 : 
 308 : typedef modela56e666cb8f6_16a540c6086086816528e4524def24d9_namespace::modela56e666cb8f6_16a540c6086086816528e4524def24d9 stan_model;
 309 : 
 310 : #ifndef USING_R
 311 : 
 312 : stan::model::model_base& new_model(
 313 :         stan::io::var_context& data_context,
 314 :         unsigned int seed,
 315 :         std::ostream* msg_stream) {
 316 :   stan_model* m = new stan_model(data_context, seed, msg_stream);
 317 :   return *m;
 318 : }
 319 : 
 320 : #endif
 321 : 
 322 : 
 323 : 
 324 : #include <rstan_next/stan_fit.hpp>
 325 : 
 326 : struct stan_model_holder {
 327 :     stan_model_holder(rstan::io::rlist_ref_var_context rcontext,
 328 :                       unsigned int random_seed)
 329 :     : rcontext_(rcontext), random_seed_(random_seed)
 330 :      {
 331 :      }
 332 : 
 333 :    //stan::math::ChainableStack ad_stack;
 334 :    rstan::io::rlist_ref_var_context rcontext_;
 335 :    unsigned int random_seed_;
 336 : };
 337 : 
 338 : Rcpp::XPtr<stan::model::model_base> model_ptr(stan_model_holder* smh) {
 339 :   Rcpp::XPtr<stan::model::model_base> model_instance(new stan_model(smh->rcontext_, smh->random_seed_), true);
 340 :   return model_instance;
 341 : }
 342 : 
 343 : Rcpp::XPtr<rstan::stan_fit_base> fit_ptr(stan_model_holder* smh) {
 344 :   return Rcpp::XPtr<rstan::stan_fit_base>(new rstan::stan_fit(model_ptr(smh), smh->random_seed_), true);
 345 : }
 346 : 
 347 : std::string model_name(stan_model_holder* smh) {
 348 :   return model_ptr(smh).get()->model_name();
 349 : }
 350 : 
 351 : RCPP_MODULE(stan_fit4modela56e666cb8f6_16a540c6086086816528e4524def24d9_mod){
 352 :   Rcpp::class_<stan_model_holder>("stan_fit4modela56e666cb8f6_16a540c6086086816528e4524def24d9")
 353 :   .constructor<rstan::io::rlist_ref_var_context, unsigned int>()
 354 :   .method("model_ptr", &model_ptr)
 355 :   .method("fit_ptr", &fit_ptr)
 356 :   .method("model_name", &model_name)
 357 :   ;
 358 : }
 359 : 
 360 : 
 361 : // declarations
 362 : extern "C" {
 363 : SEXP filea56e23ac94ff( ) ;
 364 : }
 365 : 
 366 : // definition
 367 : 
 368 : SEXP filea56e23ac94ff(  ){
 369 :  return Rcpp::wrap("16a540c6086086816528e4524def24d9");
 370 : }
 371 : 
 372 : 
make cmd is
  make -f '/Library/Frameworks/R.framework/Resources/etc/Makeconf' -f '/Library/Frameworks/R.framework/Resources/share/make/shlib.mk' CXX='$(CXX14) $(CXX14STD)' CXXFLAGS='$(CXX14FLAGS)' CXXPICFLAGS='$(CXX14PICFLAGS)' SHLIB_LDFLAGS='$(SHLIB_CXX14LDFLAGS)' SHLIB_LD='$(SHLIB_CXX14LD)' SHLIB='filea56e23ac94ff.so' OBJECTS='filea56e23ac94ff.o'

make would use
clang++ -mmacosx-version-min=10.13 -std=gnu++14 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/Rcpp/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppEigen/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppEigen/include/unsupported"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/BH/include" -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/include/src/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppParallel/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/rstan/include" -DEIGEN_NO_DEBUG  -DBOOST_DISABLE_ASSERTS  -DBOOST_PENDING_INTEGER_LOG2_HPP  -DSTAN_THREADS  -DBOOST_NO_AUTO_PTR  -include '/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/include/stan/math/prim/mat/fun/Eigen.hpp'  -D_REENTRANT -DRCPP_PARALLEL_USE_TBB=1   -I/usr/local/include   -fPIC  -Wall -g -O2  -c filea56e23ac94ff.cpp -o filea56e23ac94ff.o
if test  "zfilea56e23ac94ff.o" != "z"; then \
	  echo clang++ -mmacosx-version-min=10.13 -std=gnu++14 -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L"/Library/Frameworks/R.framework/Resources/lib" -L/usr/local/lib -o filea56e23ac94ff.so filea56e23ac94ff.o  /Library/Frameworks/R.framework/Versions/4.0/Resources/library/rstan/lib//libStanServices.a -L'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/lib/' -lStanHeaders -L'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppParallel/lib/' -ltbb -ltbbmalloc -ltbbmalloc_proxy  -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation; \
	  clang++ -mmacosx-version-min=10.13 -std=gnu++14 -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L"/Library/Frameworks/R.framework/Resources/lib" -L/usr/local/lib -o filea56e23ac94ff.so filea56e23ac94ff.o  /Library/Frameworks/R.framework/Versions/4.0/Resources/library/rstan/lib//libStanServices.a -L'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/lib/' -lStanHeaders -L'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppParallel/lib/' -ltbb -ltbbmalloc -ltbbmalloc_proxy  -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation; \
	fi

ERROR(s) during compilation: source code errors or compiler configuration errors!

Program source:
  1: 
  2: // includes from the plugin
  3: // [[Rcpp::plugins(cpp14)]]
  4: 
  5: 
  6: // user includes
  7: #include <Rcpp.h>
  8: #include <rstan/io/rlist_ref_var_context.hpp>
  9: #include <rstan/io/r_ostream.hpp>
 10: #include <rstan/stan_args.hpp>
 11: #include <boost/integer/integer_log2.hpp>
 12: // Code generated by Stan version 2.21.0
 13: 
 14: #include <stan/model/model_header.hpp>
 15: 
 16: namespace modela56e666cb8f6_16a540c6086086816528e4524def24d9_namespace {
 17: 
 18: using std::istream;
 19: using std::string;
 20: using std::stringstream;
 21: using std::vector;
 22: using stan::io::dump;
 23: using stan::math::lgamma;
 24: using stan::model::prob_grad;
 25: using namespace stan::math;
 26: 
 27: static int current_statement_begin__;
 28: 
 29: stan::io::program_reader prog_reader__() {
 30:     stan::io::program_reader reader;
 31:     reader.add_event(0, 0, "start", "modela56e666cb8f6_16a540c6086086816528e4524def24d9");
 32:     reader.add_event(3, 1, "end", "modela56e666cb8f6_16a540c6086086816528e4524def24d9");
 33:     return reader;
 34: }
 35: 
 36: class modela56e666cb8f6_16a540c6086086816528e4524def24d9
 37:   : public stan::model::model_base_crtp<modela56e666cb8f6_16a540c6086086816528e4524def24d9> {
 38: private:
 39:         double y_mean;
 40: public:
 41:     modela56e666cb8f6_16a540c6086086816528e4524def24d9(rstan::io::rlist_ref_var_context& context__,
 42:         std::ostream* pstream__ = 0)
 43:         : model_base_crtp(0) {
 44:         ctor_body(context__, 0, pstream__);
 45:     }
 46: 
 47:     modela56e666cb8f6_16a540c6086086816528e4524def24d9(stan::io::var_context& context__,
 48:         unsigned int random_seed__,
 49:         std::ostream* pstream__ = 0)
 50:         : model_base_crtp(0) {
 51:         ctor_body(context__, random_seed__, pstream__);
 52:     }
 53: 
 54:     void ctor_body(stan::io::var_context& context__,
 55:                    unsigned int random_seed__,
 56:                    std::ostream* pstream__) {
 57:         typedef double local_scalar_t__;
 58: 
 59:         boost::ecuyer1988 base_rng__ =
 60:           stan::services::util::create_rng(random_seed__, 0);
 61:         (void) base_rng__;  // suppress unused var warning
 62: 
 63:         current_statement_begin__ = -1;
 64: 
 65:         static const char* function__ = "modela56e666cb8f6_16a540c6086086816528e4524def24d9_namespace::modela56e666cb8f6_16a540c6086086816528e4524def24d9";
 66:         (void) function__;  // dummy to suppress unused var warning
 67:         size_t pos__;
 68:         (void) pos__;  // dummy to suppress unused var warning
 69:         std::vector<int> vals_i__;
 70:         std::vector<double> vals_r__;
 71:         local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN());
 72:         (void) DUMMY_VAR__;  // suppress unused var warning
 73: 
 74:         try {
 75:             // initialize data block variables from context__
 76:             current_statement_begin__ = 1;
 77:             context__.validate_dims("data initialization", "y_mean", "double", context__.to_vec());
 78:             y_mean = double(0);
 79:             vals_r__ = context__.vals_r("y_mean");
 80:             pos__ = 0;
 81:             y_mean = vals_r__[pos__++];
 82: 
 83: 
 84:             // initialize transformed data variables
 85:             // execute transformed data statements
 86: 
 87:             // validate transformed data
 88: 
 89:             // validate, set parameter ranges
 90:             num_params_r__ = 0U;
 91:             param_ranges_i__.clear();
 92:             current_statement_begin__ = 1;
 93:             num_params_r__ += 1;
 94:         } catch (const std::exception& e) {
 95:             stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__());
 96:             // Next line prevents compiler griping about no return
 97:             throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***");
 98:         }
 99:     }
100: 
101:     ~modela56e666cb8f6_16a540c6086086816528e4524def24d9() { }
102: 
103: 
104:     void transform_inits(const stan::io::var_context& context__,
105:                          std::vector<int>& params_i__,
106:                          std::vector<double>& params_r__,
107:                          std::ostream* pstream__) const {
108:         typedef double local_scalar_t__;
109:         stan::io::writer<double> writer__(params_r__, params_i__);
110:         size_t pos__;
111:         (void) pos__; // dummy call to supress warning
112:         std::vector<double> vals_r__;
113:         std::vector<int> vals_i__;
114: 
115:         current_statement_begin__ = 1;
116:         if (!(context__.contains_r("y")))
117:             stan::lang::rethrow_located(std::runtime_error(std::string("Variable y missing")), current_statement_begin__, prog_reader__());
118:         vals_r__ = context__.vals_r("y");
119:         pos__ = 0U;
120:         context__.validate_dims("parameter initialization", "y", "double", context__.to_vec());
121:         double y(0);
122:         y = vals_r__[pos__++];
123:         try {
124:             writer__.scalar_unconstrain(y);
125:         } catch (const std::exception& e) {
126:             stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable y: ") + e.what()), current_statement_begin__, prog_reader__());
127:         }
128: 
129:         params_r__ = writer__.data_r();
130:         params_i__ = writer__.data_i();
131:     }
132: 
133:     void transform_inits(const stan::io::var_context& context,
134:                          Eigen::Matrix<double, Eigen::Dynamic, 1>& params_r,
135:                          std::ostream* pstream__) const {
136:       std::vector<double> params_r_vec;
137:       std::vector<int> params_i_vec;
138:       transform_inits(context, params_i_vec, params_r_vec, pstream__);
139:       params_r.resize(params_r_vec.size());
140:       for (int i = 0; i < params_r.size(); ++i)
141:         params_r(i) = params_r_vec[i];
142:     }
143: 
144: 
145:     template <bool propto__, bool jacobian__, typename T__>
146:     T__ log_prob(std::vector<T__>& params_r__,
147:                  std::vector<int>& params_i__,
148:                  std::ostream* pstream__ = 0) const {
149: 
150:         typedef T__ local_scalar_t__;
151: 
152:         local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN());
153:         (void) DUMMY_VAR__;  // dummy to suppress unused var warning
154: 
155:         T__ lp__(0.0);
156:         stan::math::accumulator<T__> lp_accum__;
157:         try {
158:             stan::io::reader<local_scalar_t__> in__(params_r__, params_i__);
159: 
160:             // model parameters
161:             current_statement_begin__ = 1;
162:             local_scalar_t__ y;
163:             (void) y;  // dummy to suppress unused var warning
164:             if (jacobian__)
165:                 y = in__.scalar_constrain(lp__);
166:             else
167:                 y = in__.scalar_constrain();
168: 
169:             // model body
170: 
171:             current_statement_begin__ = 1;
...
355:   .method("fit_ptr", &fit_ptr)
356:   .method("model_name", &model_name)
357:   ;
358: }
359: 
360: 
361: // declarations
362: extern "C" {
363: SEXP filea56e23ac94ff( ) ;
364: }
365: 
366: // definition
367: 
368: SEXP filea56e23ac94ff(  ){
369:  return Rcpp::wrap("16a540c6086086816528e4524def24d9");
370: }
371: 
372: 

Compilation ERROR, function(s)/method(s) not created!
Error in compileCode(f, code, language = language, verbose = verbose) : 
  /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/cmath:649:25: error: no template named 'numeric_limits'  return _FloatBigger ? numeric_limits<_IntT>::max() :  (numeric_limits<_IntT>::max() >> _Bits << _Bits);                        ^fatal error: too many errors emitted, stopping now [-ferror-limit=]20 errors generated.make: *** [filea56e23ac94ff.o] Error 1
In addition: Warning messages:
1: In system2(CXX, args = ARGS) : error in running command
2: In file.remove(c(unprocessed, processed)) :
  cannot remove file '/var/folders/5j/8cyf3lpd3wzfsrrq1rp8thbm0000gp/T//Rtmp7yIoPe/filea56e195edfa4.stan', reason 'No such file or directory'
example(cxxfunction, package = "inline", run.dontrun = TRUE)

works?

I get an error from that too:

cxxfnc> # default plugin
cxxfnc> fx <- cxxfunction( signature(x = "integer", y = "numeric" ) , '
cxxfnc+ 	return ScalarReal( INTEGER(x)[0] * REAL(y)[0] ) ;
cxxfnc+ ' )

ERROR(s) during compilation: source code errors or compiler configuration errors!
make cmd is
  make -f '/Library/Frameworks/R.framework/Resources/etc/Makeconf' -f '/Library/Frameworks/R.framework/Resources/share/make/shlib.mk' SHLIB_LDFLAGS='$(SHLIB_CXXLDFLAGS)' SHLIB_LD='$(SHLIB_CXXLD)' SHLIB='filea56e38ebccb1.so' OBJECTS='filea56e38ebccb1.o'

make would use
clang++ -mmacosx-version-min=10.13 -std=gnu++11 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/Rcpp/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppEigen/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppEigen/include/unsupported"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/BH/include" -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/include/src/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppParallel/include/"  -I"/Library/Frameworks/R.framework/Versions/4.0/Resources/library/rstan/include" -DEIGEN_NO_DEBUG  -DBOOST_DISABLE_ASSERTS  -DBOOST_PENDING_INTEGER_LOG2_HPP  -DSTAN_THREADS  -DBOOST_NO_AUTO_PTR  -include '/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/include/stan/math/prim/mat/fun/Eigen.hpp'  -D_REENTRANT -DRCPP_PARALLEL_USE_TBB=1   -I/usr/local/include   -fPIC  -Wall -g -O2  -c filea56e38ebccb1.cpp -o filea56e38ebccb1.o
if test  "zfilea56e38ebccb1.o" != "z"; then \
	  echo clang++ -mmacosx-version-min=10.13 -std=gnu++11 -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L"/Library/Frameworks/R.framework/Resources/lib" -L/usr/local/lib -o filea56e38ebccb1.so filea56e38ebccb1.o  /Library/Frameworks/R.framework/Versions/4.0/Resources/library/rstan/lib//libStanServices.a -L'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/lib/' -lStanHeaders -L'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppParallel/lib/' -ltbb -ltbbmalloc -ltbbmalloc_proxy  -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation; \
	  clang++ -mmacosx-version-min=10.13 -std=gnu++11 -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L"/Library/Frameworks/R.framework/Resources/lib" -L/usr/local/lib -o filea56e38ebccb1.so filea56e38ebccb1.o  /Library/Frameworks/R.framework/Versions/4.0/Resources/library/rstan/lib//libStanServices.a -L'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/StanHeaders/lib/' -lStanHeaders -L'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/RcppParallel/lib/' -ltbb -ltbbmalloc -ltbbmalloc_proxy  -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation; \
	fi

Program source:
  1: 
  2: // includes from the plugin
  3: #include <R.h>
  4: #include <Rdefines.h>
  5: #include <R_ext/Error.h>
  6: 
  7: 
  8: // user includes
  9: 
 10: 
 11: // declarations
 12: extern "C" {
 13: SEXP filea56e38ebccb1( SEXP x, SEXP y) ;
 14: }
 15: 
 16: // definition
 17: 
 18: SEXP filea56e38ebccb1( SEXP x, SEXP y ){
 19: 
 20: 	return ScalarReal( INTEGER(x)[0] * REAL(y)[0] ) ;
 21:  
 22: Rf_warning("your C++ program does not return anything"); 
 23:  return R_NilValue ; 
 24: }
 25: 
 26: 

Compilation ERROR, function(s)/method(s) not created!
Error in compileCode(f, code, language = language, verbose = verbose) : 
  /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/cmath:649:25: error: no template named 'numeric_limits'  return _FloatBigger ? numeric_limits<_IntT>::max() :  (numeric_limits<_IntT>::max() >> _Bits << _Bits);                        ^fatal error: too many errors emitted, stopping now [-ferror-limit=]20 errors generated.make: *** [filea56e38ebccb1.o] Error 1

And you’re sure you have the latest version of XCode?

And you’re sure you have the latest version of XCode?

I think so. I updated XCode 3 weeks ago and there are no updates currently available.

I have had a bunch of problems with XCode over the last few months and mostly solved them with patchwork solutions that could have had unintended consequences. I have uninstalled and reinstalled R, RStudio, and Command Line Tools, but I still run into problems afterwards.

In case this is helpful, I just noticed that I am having other Command Line Tools problems. When I try to compile this C++ code

#include <iostream>
#include <cmath>

int main() {

  std::cout << "hello!" << std::endl;

  return 0;
}

I get a bunch of errors. Here’s the top of the error message.

/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/cmath:317:9: error: no member
      named 'signbit' in the global namespace
using ::signbit;
      ~~^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/cmath:318:9: error: no member
      named 'fpclassify' in the global namespace
using ::fpclassify;
      ~~^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/cmath:319:9: error: no member
      named 'isfinite' in the global namespace; did you mean 'finite'?
using ::isfinite;
      ~~^
/usr/local/include/math.h:749:12: note: 'finite' declared here
extern int finite(double)
           ^

Someone with Catalina compile Hello World with the -v option to see where it is supposed to be looking for headers.

in that β€œmake would use” msg - near the end of the call to clang++ there’s this -I flag:
-I/usr/local/include

I don’t think this is where you want to be looking - cf: https://stackoverflow.com/questions/51762620/where-is-the-c-standard-library-on-macos

Not sure if you solved your issue. I ran into similar error messages in bizarre cases for some models that worked fine with cmdstanr but failed with rstan even though other models worked fine both on rstan and cmdstanr in the same r session.

I found these threads helpful:



For me cleaning my .r/Makevars and then quitting and restarting rstudio did the trick but I’m not yet sure if this will cause any problems for other packages (especially those that depend on data.table, why I had edited my Makevars to begin with).

Thanks @zenkavi !

I ended up solving my issue by reinstalling XCode, R, RStudio and deleting some header files that I had previously copied to a new directory to solve another issue.