Error in stanc - c++ exception (unknown reason)

Hi Florian, R3.6 on Mac tends to have issues with RStan. Id recommend you upgrade to R 4.0/4.1 and see if it fixes your problem

Hi! Thanks for your quick response! I upgraded but I still have the error with some additional information:

Compiling Stan program…
Error in stanc(file = file, model_code = model_code, model_name = model_name, :
0

Semantic error in ‘string’, line 77, column 15 to column 17:

Identifier ‘x0’ not in scope.

R-version
platform x86_64-apple-darwin17.0
arch x86_64
os darwin17.0
system x86_64, darwin17.0
status
major 4
minor 1.0
year 2021
month 05
day 18
svn rev 80317
language R
version.string R version 4.1.0 (2021-05-18)
nickname Camp Pontanezen

What do you get if you run the rstan example model:

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

This is the output:

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 '' FROM Stan CODE TO C++ CODE NOW.
COMPILING THE C++ CODE FOR MODEL 'anon_model' NOW.
OS: x86_64, darwin17.0; rstan: 2.26.1; Rcpp: 1.0.6; inline: 0.3.18 
 >> setting environment variables: 
PKG_LIBS =  '/Library/Frameworks/R.framework/Versions/4.1/Resources/library/rstan/lib//libStanServices.a' -L'/Library/Frameworks/R.framework/Versions/4.1/Resources/library/StanHeaders/lib/' -lStanHeaders -L'/Library/Frameworks/R.framework/Versions/4.1/Resources/library/RcppParallel/lib/' -ltbb 
PKG_CPPFLAGS =   -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include/"  -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/RcppEigen/include/"  -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/RcppEigen/include/unsupported"  -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/BH/include" -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/StanHeaders/include/src/"  -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/StanHeaders/include/"  -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/RcppParallel/include/"  -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/rstan/include" -DEIGEN_NO_DEBUG  -DBOOST_DISABLE_ASSERTS  -DBOOST_PENDING_INTEGER_LOG2_HPP  -DSTAN_THREADS  -DUSE_STANC3 -DSTRICT_R_HEADERS  -DBOOST_PHOENIX_NO_VARIADIC_EXPRESSION  -DBOOST_NO_AUTO_PTR  -include '/Library/Frameworks/R.framework/Versions/4.1/Resources/library/StanHeaders/include/stan/math/prim/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 : using namespace Rcpp;
   9 : #ifndef MODELS_HPP
  10 : #define MODELS_HPP
  11 : #define STAN__SERVICES__COMMAND_HPP
  12 : #include <rstan/rstaninc.hpp>
  13 : #ifndef USE_STANC3
  14 : #define USE_STANC3
  15 : #endif
  16 : 
  17 : // Code generated by stanc v2.26.1
  18 : #include <stan/model/model_header.hpp>
  19 : namespace model521040c6d2b9__namespace {
  20 : 
  21 : 
  22 : inline void validate_positive_index(const char* var_name, const char* expr,
  23 :                                     int val) {
  24 :   if (val < 1) {
  25 :     std::stringstream msg;
  26 :     msg << "Found dimension size less than one in simplex declaration"
  27 :         << "; variable=" << var_name << "; dimension size expression=" << expr
  28 :         << "; expression value=" << val;
  29 :     std::string msg_str(msg.str());
  30 :     throw std::invalid_argument(msg_str.c_str());
  31 :   }
  32 : }
  33 : 
  34 : inline void validate_unit_vector_index(const char* var_name, const char* expr,
  35 :                                        int val) {
  36 :   if (val <= 1) {
  37 :     std::stringstream msg;
  38 :     if (val == 1) {
  39 :       msg << "Found dimension size one in unit vector declaration."
  40 :           << " One-dimensional unit vector is discrete"
  41 :           << " but the target distribution must be continuous."
  42 :           << " variable=" << var_name << "; dimension size expression=" << expr;
  43 :     } else {
  44 :       msg << "Found dimension size less than one in unit vector declaration"
  45 :           << "; variable=" << var_name << "; dimension size expression=" << expr
  46 :           << "; expression value=" << val;
  47 :     }
  48 :     std::string msg_str(msg.str());
  49 :     throw std::invalid_argument(msg_str.c_str());
  50 :   }
  51 : }
  52 : 
  53 : 
  54 : using std::istream;
  55 : using std::string;
  56 : using std::stringstream;
  57 : using std::vector;
  58 : using std::pow;
  59 : using stan::io::dump;
  60 : using stan::math::lgamma;
  61 : using stan::model::model_base_crtp;
  62 : using stan::model::rvalue;
  63 : using stan::model::cons_list;
  64 : using stan::model::index_uni;
  65 : using stan::model::index_max;
  66 : using stan::model::index_min;
  67 : using stan::model::index_min_max;
  68 : using stan::model::index_multi;
  69 : using stan::model::index_omni;
  70 : using stan::model::nil_index_list;
  71 : using namespace stan::math;
  72 : using stan::math::pow; 
  73 : 
  74 : stan::math::profile_map profiles__;
  75 : static int current_statement__= 0;
  76 : static const std::vector<string> locations_array__ = {" (found before start of program)",
  77 :                                                       " (in 'anon_model', line 1, column 32 to column 39)",
  78 :                                                       " (in 'anon_model', line 1, column 48 to column 69)",
  79 :                                                       " (in 'anon_model', line 1, column 6 to column 18)"};
  80 : 
  81 : 
  82 : 
  83 : class model521040c6d2b9_ final : public model_base_crtp<model521040c6d2b9_> {
  84 : 
  85 :  private:
  86 :   double y_mean;
  87 :  
  88 :  public:
  89 :   ~model521040c6d2b9_() { }
  90 :   
  91 :   inline std::string model_name() const final { return "model521040c6d2b9_"; }
  92 : 
  93 :   inline std::vector<std::string> model_compile_info() const noexcept {
  94 :     return std::vector<std::string>{"stanc_version = stanc3 v2.26.1", "stancflags = "};
  95 :   }
  96 :   
  97 :   
  98 :   model521040c6d2b9_(stan::io::var_context& context__,
  99 :                      unsigned int random_seed__ = 0,
 100 :                      std::ostream* pstream__ = nullptr) : model_base_crtp(0) {
 101 :     using local_scalar_t__ = double ;
 102 :     boost::ecuyer1988 base_rng__ = 
 103 :         stan::services::util::create_rng(random_seed__, 0);
 104 :     (void) base_rng__;  // suppress unused var warning
 105 :     static const char* function__ = "model521040c6d2b9__namespace::model521040c6d2b9_";
 106 :     (void) function__;  // suppress unused var warning
 107 :     local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN());
 108 :     (void) DUMMY_VAR__;  // suppress unused var warning
 109 :     
 110 :     try {
 111 :       int pos__;
 112 :       pos__ = std::numeric_limits<int>::min();
 113 :       
 114 :       pos__ = 1;
 115 :       current_statement__ = 3;
 116 :       context__.validate_dims("data initialization","y_mean","double",
 117 :           context__.to_vec());
 118 :       y_mean = std::numeric_limits<double>::quiet_NaN();
 119 :       
 120 :       current_statement__ = 3;
 121 :       y_mean = context__.vals_r("y_mean")[(1 - 1)];
 122 :     } catch (const std::exception& e) {
 123 :       stan::lang::rethrow_located(e, locations_array__[current_statement__]);
 124 :       // Next line prevents compiler griping about no return
 125 :       throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); 
 126 :     }
 127 :     num_params_r__ = 0U;
 128 :     
 129 :     try {
 130 :       num_params_r__ += 1;
 131 :     } catch (const std::exception& e) {
 132 :       stan::lang::rethrow_located(e, locations_array__[current_statement__]);
 133 :       // Next line prevents compiler griping about no return
 134 :       throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); 
 135 :     }
 136 :   }
 137 :   template <bool propto__, bool jacobian__, typename VecR, typename VecI, stan::require_vector_like_t<VecR>* = nullptr, stan::require_vector_like_vt<std::is_integral, VecI>* = nullptr>
 138 :   inline stan::scalar_type_t<VecR> log_prob_impl(VecR& params_r__,
 139 :                                                  VecI& params_i__,
 140 :                                                  std::ostream* pstream__ = nullptr) const {
 141 :     using T__ = stan::scalar_type_t<VecR>;
 142 :     using local_scalar_t__ = T__;
 143 :     T__ lp__(0.0);
 144 :     stan::math::accumulator<T__> lp_accum__;
 145 :     static const char* function__ = "model521040c6d2b9__namespace::log_prob";
 146 : (void) function__;  // suppress unused var warning
 147 : 
 148 :     stan::io::reader<local_scalar_t__> in__(params_r__, params_i__);
 149 :     local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN());
 150 :     (void) DUMMY_VAR__;  // suppress unused var warning
 151 : 
 152 :     
 153 :     try {
 154 :       local_scalar_t__ y;
 155 :       y = DUMMY_VAR__;
 156 :       
 157 :       current_statement__ = 1;
 158 :       y = in__.scalar();
 159 :       {
 160 :         current_statement__ = 2;
 161 :         lp_accum__.add(normal_lpdf<propto__>(y, y_mean, 1));
 162 :       }
 163 :     } catch (const std::exception& e) {
 164 :       stan::lang::rethrow_located(e, locations_array__[current_statement__]);
 165 :       // Next line prevents compiler griping about no return
 166 :       throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); 
 167 :     }
 168 :     lp_accum__.add(lp__);
 169 :     return lp_accum__.sum();
 170 :     } // log_prob_impl() 
 171 :     
 172 :   template <typename RNG, typename VecR, typename VecI, typename VecVar, stan::require_vector_like_vt<std::is_floating_point, VecR>* = nullptr, stan::require_vector_like_vt<std::is_integral, VecI>* = nullptr, stan::require_std_vector_vt<std::is_floating_point, VecVar>* = nullptr>
 173 :   inline void write_array_impl(RNG& base_rng__, VecR& params_r__,
 174 :                                VecI& params_i__, VecVar& vars__,
 175 :                                const bool emit_transformed_parameters__ = true,
 176 :                                const bool emit_generated_quantities__ = true,
 177 :                                std::ostream* pstream__ = nullptr) const {
 178 :     using local_scalar_t__ = double;
 179 :     vars__.resize(0);
 180 :     stan::io::reader<local_scalar_t__> in__(params_r__, params_i__);
 181 :     static const char* function__ = "model521040c6d2b9__namespace::write_array";
 182 : (void) function__;  // suppress unused var warning
 183 : 
 184 :     (void) function__;  // suppress unused var warning
 185 : 
 186 :     double lp__ = 0.0;
 187 :     (void) lp__;  // dummy to suppress unused var warning
 188 :     stan::math::accumulator<double> lp_accum__;
 189 :     local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN());
 190 :     (void) DUMMY_VAR__;  // suppress unused var warning
 191 : 
 192 :     
 193 :     try {
 194 :       double y;
 195 :       y = std::numeric_limits<double>::quiet_NaN();
 196 :       
 197 :       current_statement__ = 1;
 198 :       y = in__.scalar();
 199 :       vars__.emplace_back(y);
 200 :       if (logical_negation((primitive_value(emit_transformed_parameters__) ||
 201 :             primitive_value(emit_generated_quantities__)))) {
 202 :         return ;
 203 :       } 
 204 :       if (logical_negation(emit_generated_quantities__)) {
 205 :         return ;
 206 :       } 
 207 :     } catch (const std::exception& e) {
 208 :       stan::lang::rethrow_located(e, locations_array__[current_statement__]);
 209 :       // Next line prevents compiler griping about no return
 210 :       throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); 
 211 :     }
 212 :     } // write_array_impl() 
 213 :     
 214 :   template <typename VecVar, typename VecI, stan::require_std_vector_t<VecVar>* = nullptr, stan::require_vector_like_vt<std::is_integral, VecI>* = nullptr>
 215 :   inline void transform_inits_impl(const stan::io::var_context& context__,
 216 :                                    VecI& params_i__, VecVar& vars__,
 217 :                                    std::ostream* pstream__ = nullptr) const {
 218 :     using local_scalar_t__ = double;
 219 :     vars__.clear();
 220 :     vars__.reserve(num_params_r__);
 221 :     
 222 :     try {
 223 :       int pos__;
 224 :       pos__ = std::numeric_limits<int>::min();
 225 :       
 226 :       pos__ = 1;
 227 :       double y;
 228 :       y = std::numeric_limits<double>::quiet_NaN();
 229 :       
 230 :       current_statement__ = 1;
 231 :       y = context__.vals_r("y")[(1 - 1)];
 232 :       vars__.emplace_back(y);
 233 :     } catch (const std::exception& e) {
 234 :       stan::lang::rethrow_located(e, locations_array__[current_statement__]);
 235 :       // Next line prevents compiler griping about no return
 236 :       throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); 
 237 :     }
 238 :     } // transform_inits_impl() 
 239 :     
 240 :   inline void get_param_names(std::vector<std::string>& names__) const {
 241 :     
 242 :     names__.clear();
 243 :     names__.emplace_back("y");
 244 :     } // get_param_names() 
 245 :     
 246 :   inline void get_dims(std::vector<std::vector<size_t>>& dimss__) const {
 247 :     dimss__.clear();
 248 :     dimss__.emplace_back(std::vector<size_t>{});
 249 :     
 250 :     } // get_dims() 
 251 :     
 252 :   inline void constrained_param_names(
 253 :                                       std::vector<std::string>& param_names__,
 254 :                                       bool emit_transformed_parameters__ = true,
 255 :                                       bool emit_generated_quantities__ = true) const
 256 :     final {
 257 :     
 258 :     param_names__.emplace_back(std::string() + "y");
 259 :     if (emit_transformed_parameters__) {
 260 :       
 261 :     }
 262 :     
 263 :     if (emit_generated_quantities__) {
 264 :       
 265 :     }
 266 :     
 267 :     } // constrained_param_names() 
 268 :     
 269 :   inline void unconstrained_param_names(
 270 :                                         std::vector<std::string>& param_names__,
 271 :                                         bool emit_transformed_parameters__ = true,
 272 :                                         bool emit_generated_quantities__ = true) const
 273 :     final {
 274 :     
 275 :     param_names__.emplace_back(std::string() + "y");
 276 :     if (emit_transformed_parameters__) {
 277 :       
 278 :     }
 279 :     
 280 :     if (emit_generated_quantities__) {
 281 :       
 282 :     }
 283 :     
 284 :     } // unconstrained_param_names() 
 285 :     
 286 :   inline std::string get_constrained_sizedtypes() const {
 287 :     stringstream s__;
 288 :     s__ << "[{\"name\":\"y\",\"type\":{\"name\":\"real\"},\"block\":\"parameters\"}]";
 289 :     return s__.str();
 290 :     } // get_constrained_sizedtypes() 
 291 :     
 292 :   inline std::string get_unconstrained_sizedtypes() const {
 293 :     stringstream s__;
 294 :     s__ << "[{\"name\":\"y\",\"type\":{\"name\":\"real\"},\"block\":\"parameters\"}]";
 295 :     return s__.str();
 296 :     } // get_unconstrained_sizedtypes() 
 297 :     
 298 :   
 299 :     // Begin method overload boilerplate
 300 :     template <typename RNG>
 301 :     inline void write_array(RNG& base_rng,
 302 :                             Eigen::Matrix<double,Eigen::Dynamic,1>& params_r,
 303 :                             Eigen::Matrix<double,Eigen::Dynamic,1>& vars,
 304 :                             const bool emit_transformed_parameters = true,
 305 :                             const bool emit_generated_quantities = true,
 306 :                             std::ostream* pstream = nullptr) const {
 307 :       std::vector<double> vars_vec(vars.size());
 308 :       std::vector<int> params_i;
 309 :       write_array_impl(base_rng, params_r, params_i, vars_vec,
 310 :           emit_transformed_parameters, emit_generated_quantities, pstream);
 311 :       vars.resize(vars_vec.size());
 312 :       for (int i = 0; i < vars.size(); ++i) {
 313 :         vars.coeffRef(i) = vars_vec[i];
 314 :       }
 315 :     }
 316 : 
 317 :     template <typename RNG>
 318 :     inline void write_array(RNG& base_rng, std::vector<double>& params_r,
 319 :                             std::vector<int>& params_i,
 320 :                             std::vector<double>& vars,
 321 :                             bool emit_transformed_parameters = true,
 322 :                             bool emit_generated_quantities = true,
 323 :                             std::ostream* pstream = nullptr) const {
 324 :       write_array_impl(base_rng, params_r, params_i, vars, emit_transformed_parameters, emit_generated_quantities, pstream);
 325 :     }
 326 : 
 327 :     template <bool propto__, bool jacobian__, typename T_>
 328 :     inline T_ log_prob(Eigen::Matrix<T_,Eigen::Dynamic,1>& params_r,
 329 :                        std::ostream* pstream = nullptr) const {
 330 :       Eigen::Matrix<int, -1, 1> params_i;
 331 :       return log_prob_impl<propto__, jacobian__>(params_r, params_i, pstream);
 332 :     }
 333 : 
 334 :     template <bool propto__, bool jacobian__, typename T__>
 335 :     inline T__ log_prob(std::vector<T__>& params_r,
 336 :                         std::vector<int>& params_i,
 337 :                         std::ostream* pstream = nullptr) const {
 338 :       return log_prob_impl<propto__, jacobian__>(params_r, params_i, pstream);
 339 :     }
 340 :   
 341 : 
 342 :     inline void transform_inits(const stan::io::var_context& context,
 343 :                          Eigen::Matrix<double, Eigen::Dynamic, 1>& params_r,
 344 :                          std::ostream* pstream = nullptr) const final {
 345 :       std::vector<double> params_r_vec(params_r.size());
 346 :       std::vector<int> params_i;
 347 :       transform_inits_impl(context, params_i, params_r_vec, pstream);
 348 :       params_r.resize(params_r_vec.size());
 349 :       for (int i = 0; i < params_r.size(); ++i) {
 350 :         params_r.coeffRef(i) = params_r_vec[i];
 351 :       }
 352 :     }
 353 :     inline void transform_inits(const stan::io::var_context& context,
 354 :                                 std::vector<int>& params_i,
 355 :                                 std::vector<double>& vars,
 356 :                                 std::ostream* pstream = nullptr) const final {
 357 :       transform_inits_impl(context, params_i, vars, pstream);
 358 :     }        
 359 : 
 360 : };
 361 : }
 362 : using stan_model = model521040c6d2b9__namespace::model521040c6d2b9_;
 363 : 
 364 : #ifndef USING_R
 365 : 
 366 : // Boilerplate
 367 : stan::model::model_base& new_model(
 368 :         stan::io::var_context& data_context,
 369 :         unsigned int seed,
 370 :         std::ostream* msg_stream) {
 371 :   stan_model* m = new stan_model(data_context, seed, msg_stream);
 372 :   return *m;
 373 : }
 374 : 
 375 : stan::math::profile_map& get_stan_profile_data() {
 376 :   return model521040c6d2b9__namespace::profiles__;
 377 : }
 378 : 
 379 : #endif
 380 : 
 381 : 
 382 : 
 383 : #endif
 384 : 
 385 : RCPP_MODULE(stan_fit4model521040c6d2b9__mod) {
 386 :   class_<rstan::stan_fit<stan_model, boost::random::ecuyer1988> >(
 387 :       "stan_fit4model521040c6d2b9_")
 388 : 
 389 :       .constructor<SEXP, SEXP, SEXP>()
 390 : 
 391 :       .method(
 392 :           "call_sampler",
 393 :           &rstan::stan_fit<stan_model, boost::random::ecuyer1988>::call_sampler)
 394 :       .method(
 395 :           "param_names",
 396 :           &rstan::stan_fit<stan_model, boost::random::ecuyer1988>::param_names)
 397 :       .method("param_names_oi",
 398 :               &rstan::stan_fit<stan_model,
 399 :                                boost::random::ecuyer1988>::param_names_oi)
 400 :       .method("param_fnames_oi",
 401 :               &rstan::stan_fit<stan_model,
 402 :                                boost::random::ecuyer1988>::param_fnames_oi)
 403 :       .method(
 404 :           "param_dims",
 405 :           &rstan::stan_fit<stan_model, boost::random::ecuyer1988>::param_dims)
 406 :       .method("param_dims_oi",
 407 :               &rstan::stan_fit<stan_model,
 408 :                                boost::random::ecuyer1988>::param_dims_oi)
 409 :       .method("update_param_oi",
 410 :               &rstan::stan_fit<stan_model,
 411 :                                boost::random::ecuyer1988>::update_param_oi)
 412 :       .method("param_oi_tidx",
 413 :               &rstan::stan_fit<stan_model,
 414 :                                boost::random::ecuyer1988>::param_oi_tidx)
 415 :       .method("grad_log_prob",
 416 :               &rstan::stan_fit<stan_model,
 417 :                                boost::random::ecuyer1988>::grad_log_prob)
 418 :       .method("log_prob",
 419 :               &rstan::stan_fit<stan_model, boost::random::ecuyer1988>::log_prob)
 420 :       .method("unconstrain_pars",
 421 :               &rstan::stan_fit<stan_model,
 422 :                                boost::random::ecuyer1988>::unconstrain_pars)
 423 :       .method("constrain_pars",
 424 :               &rstan::stan_fit<stan_model,
 425 :                                boost::random::ecuyer1988>::constrain_pars)
 426 :       .method(
 427 :           "num_pars_unconstrained",
 428 :           &rstan::stan_fit<stan_model,
 429 :                            boost::random::ecuyer1988>::num_pars_unconstrained)
 430 :       .method(
 431 :           "unconstrained_param_names",
 432 :           &rstan::stan_fit<
 433 :               stan_model, boost::random::ecuyer1988>::unconstrained_param_names)
 434 :       .method(
 435 :           "constrained_param_names",
 436 :           &rstan::stan_fit<stan_model,
 437 :                            boost::random::ecuyer1988>::constrained_param_names)
 438 :       .method("standalone_gqs",
 439 :               &rstan::stan_fit<stan_model,
 440 :                                boost::random::ecuyer1988>::standalone_gqs);
 441 : }
 442 : 
 443 : 
 444 : // declarations
 445 : extern "C" {
 446 : SEXP file52103d3490e8( ) ;
 447 : }
 448 : 
 449 : // definition
 450 : SEXP file52103d3490e8() {
 451 :  return Rcpp::wrap("anon_model");
 452 : }
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='file52103d3490e8.so' OBJECTS='file52103d3490e8.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.1/Resources/library/Rcpp/include/"  -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/RcppEigen/include/"  -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/RcppEigen/include/unsupported"  -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/BH/include" -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/StanHeaders/include/src/"  -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/StanHeaders/include/"  -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/RcppParallel/include/"  -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/rstan/include" -DEIGEN_NO_DEBUG  -DBOOST_DISABLE_ASSERTS  -DBOOST_PENDING_INTEGER_LOG2_HPP  -DSTAN_THREADS  -DUSE_STANC3 -DSTRICT_R_HEADERS  -DBOOST_PHOENIX_NO_VARIADIC_EXPRESSION  -DBOOST_NO_AUTO_PTR  -include '/Library/Frameworks/R.framework/Versions/4.1/Resources/library/StanHeaders/include/stan/math/prim/fun/Eigen.hpp'  -D_REENTRANT -DRCPP_PARALLEL_USE_TBB=1   -I/usr/local/include   -fPIC  -Wall -g -O2  -c file52103d3490e8.cpp -o file52103d3490e8.o
if test  "zfile52103d3490e8.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 file52103d3490e8.so file52103d3490e8.o  '/Library/Frameworks/R.framework/Versions/4.1/Resources/library/rstan/lib//libStanServices.a' -L'/Library/Frameworks/R.framework/Versions/4.1/Resources/library/StanHeaders/lib/' -lStanHeaders -L'/Library/Frameworks/R.framework/Versions/4.1/Resources/library/RcppParallel/lib/' -ltbb   -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 file52103d3490e8.so file52103d3490e8.o  '/Library/Frameworks/R.framework/Versions/4.1/Resources/library/rstan/lib//libStanServices.a' -L'/Library/Frameworks/R.framework/Versions/4.1/Resources/library/StanHeaders/lib/' -lStanHeaders -L'/Library/Frameworks/R.framework/Versions/4.1/Resources/library/RcppParallel/lib/' -ltbb   -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation; \
	fi

stn_md> fit <- sampling(mod, data = list(y_mean = 0))
starting worker pid=21486 on localhost:11591 at 03:40:20.107
starting worker pid=21501 on localhost:11591 at 03:40:20.305
starting worker pid=21515 on localhost:11591 at 03:40:20.495
starting worker pid=21529 on localhost:11591 at 03:40:20.690

SAMPLING FOR MODEL 'anon_model' NOW (CHAIN 1).
Chain 1: 
Chain 1: Gradient evaluation took 8e-06 seconds
Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 0.08 seconds.
Chain 1: Adjust your expectations accordingly!
Chain 1: 
Chain 1: 
Chain 1: Iteration:    1 / 2000 [  0%]  (Warmup)
Chain 1: Iteration:  200 / 2000 [ 10%]  (Warmup)
Chain 1: Iteration:  400 / 2000 [ 20%]  (Warmup)
Chain 1: Iteration:  600 / 2000 [ 30%]  (Warmup)
Chain 1: Iteration:  800 / 2000 [ 40%]  (Warmup)
Chain 1: Iteration: 1000 / 2000 [ 50%]  (Warmup)
Chain 1: Iteration: 1001 / 2000 [ 50%]  (Sampling)
Chain 1: Iteration: 1200 / 2000 [ 60%]  (Sampling)
Chain 1: Iteration: 1400 / 2000 [ 70%]  (Sampling)
Chain 1: Iteration: 1600 / 2000 [ 80%]  (Sampling)
Chain 1: Iteration: 1800 / 2000 [ 90%]  (Sampling)
Chain 1: Iteration: 2000 / 2000 [100%]  (Sampling)
Chain 1: 
Chain 1:  Elapsed Time: 0.009 seconds (Warm-up)
Chain 1:                0.01 seconds (Sampling)
Chain 1:                0.019 seconds (Total)
Chain 1: 

SAMPLING FOR MODEL 'anon_model' NOW (CHAIN 2).
Chain 2: 
Chain 2: Gradient evaluation took 1.6e-05 seconds
Chain 2: 1000 transitions using 10 leapfrog steps per transition would take 0.16 seconds.
Chain 2: Adjust your expectations accordingly!
Chain 2: 
Chain 2: 
Chain 2: Iteration:    1 / 2000 [  0%]  (Warmup)
Chain 2: Iteration:  200 / 2000 [ 10%]  (Warmup)
Chain 2: Iteration:  400 / 2000 [ 20%]  (Warmup)
Chain 2: Iteration:  600 / 2000 [ 30%]  (Warmup)
Chain 2: Iteration:  800 / 2000 [ 40%]  (Warmup)
Chain 2: Iteration: 1000 / 2000 [ 50%]  (Warmup)
Chain 2: Iteration: 1001 / 2000 [ 50%]  (Sampling)
Chain 2: Iteration: 1200 / 2000 [ 60%]  (Sampling)
Chain 2: Iteration: 1400 / 2000 [ 70%]  (Sampling)
Chain 2: Iteration: 1600 / 2000 [ 80%]  (Sampling)
Chain 2: Iteration: 1800 / 2000 [ 90%]  (Sampling)
Chain 2: Iteration: 2000 / 2000 [100%]  (Sampling)
Chain 2: 
Chain 2:  Elapsed Time: 0.017 seconds (Warm-up)
Chain 2:                0.01 seconds (Sampling)
Chain 2:                0.027 seconds (Total)
Chain 2: 

SAMPLING FOR MODEL 'anon_model' NOW (CHAIN 3).
Chain 3: 
Chain 3: Gradient evaluation took 7e-06 seconds
Chain 3: 1000 transitions using 10 leapfrog steps per transition would take 0.07 seconds.
Chain 3: Adjust your expectations accordingly!
Chain 3: 
Chain 3: 
Chain 3: Iteration:    1 / 2000 [  0%]  (Warmup)
Chain 3: Iteration:  200 / 2000 [ 10%]  (Warmup)
Chain 3: Iteration:  400 / 2000 [ 20%]  (Warmup)
Chain 3: Iteration:  600 / 2000 [ 30%]  (Warmup)
Chain 3: Iteration:  800 / 2000 [ 40%]  (Warmup)
Chain 3: Iteration: 1000 / 2000 [ 50%]  (Warmup)
Chain 3: Iteration: 1001 / 2000 [ 50%]  (Sampling)
Chain 3: Iteration: 1200 / 2000 [ 60%]  (Sampling)
Chain 3: Iteration: 1400 / 2000 [ 70%]  (Sampling)
Chain 3: Iteration: 1600 / 2000 [ 80%]  (Sampling)
Chain 3: Iteration: 1800 / 2000 [ 90%]  (Sampling)
Chain 3: Iteration: 2000 / 2000 [100%]  (Sampling)
Chain 3: 
Chain 3:  Elapsed Time: 0.014 seconds (Warm-up)
Chain 3:                0.012 seconds (Sampling)
Chain 3:                0.026 seconds (Total)
Chain 3: 

SAMPLING FOR MODEL 'anon_model' NOW (CHAIN 4).
Chain 4: 
Chain 4: Gradient evaluation took 2.5e-05 seconds
Chain 4: 1000 transitions using 10 leapfrog steps per transition would take 0.25 seconds.
Chain 4: Adjust your expectations accordingly!
Chain 4: 
Chain 4: 
Chain 4: Iteration:    1 / 2000 [  0%]  (Warmup)
Chain 4: Iteration:  200 / 2000 [ 10%]  (Warmup)
Chain 4: Iteration:  400 / 2000 [ 20%]  (Warmup)
Chain 4: Iteration:  600 / 2000 [ 30%]  (Warmup)
Chain 4: Iteration:  800 / 2000 [ 40%]  (Warmup)
Chain 4: Iteration: 1000 / 2000 [ 50%]  (Warmup)
Chain 4: Iteration: 1001 / 2000 [ 50%]  (Sampling)
Chain 4: Iteration: 1200 / 2000 [ 60%]  (Sampling)
Chain 4: Iteration: 1400 / 2000 [ 70%]  (Sampling)
Chain 4: Iteration: 1600 / 2000 [ 80%]  (Sampling)
Chain 4: Iteration: 1800 / 2000 [ 90%]  (Sampling)
Chain 4: Iteration: 2000 / 2000 [100%]  (Sampling)
Chain 4: 
Chain 4:  Elapsed Time: 0.012 seconds (Warm-up)
Chain 4:                0.009 seconds (Sampling)
Chain 4:                0.021 seconds (Total)
Chain 4: 

stn_md> fit2 <- sampling(mod, data = list(y_mean = 5))
starting worker pid=21547 on localhost:11591 at 03:40:28.803
starting worker pid=21561 on localhost:11591 at 03:40:29.015
starting worker pid=21575 on localhost:11591 at 03:40:29.235
starting worker pid=21589 on localhost:11591 at 03:40:29.485

SAMPLING FOR MODEL 'anon_model' NOW (CHAIN 1).
Chain 1: 
Chain 1: Gradient evaluation took 8e-06 seconds
Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 0.08 seconds.
Chain 1: Adjust your expectations accordingly!
Chain 1: 
Chain 1: 
Chain 1: Iteration:    1 / 2000 [  0%]  (Warmup)
Chain 1: Iteration:  200 / 2000 [ 10%]  (Warmup)
Chain 1: Iteration:  400 / 2000 [ 20%]  (Warmup)
Chain 1: Iteration:  600 / 2000 [ 30%]  (Warmup)
Chain 1: Iteration:  800 / 2000 [ 40%]  (Warmup)
Chain 1: Iteration: 1000 / 2000 [ 50%]  (Warmup)
Chain 1: Iteration: 1001 / 2000 [ 50%]  (Sampling)
Chain 1: Iteration: 1200 / 2000 [ 60%]  (Sampling)
Chain 1: Iteration: 1400 / 2000 [ 70%]  (Sampling)
Chain 1: Iteration: 1600 / 2000 [ 80%]  (Sampling)
Chain 1: Iteration: 1800 / 2000 [ 90%]  (Sampling)
Chain 1: Iteration: 2000 / 2000 [100%]  (Sampling)
Chain 1: 
Chain 1:  Elapsed Time: 0.009 seconds (Warm-up)
Chain 1:                0.01 seconds (Sampling)
Chain 1:                0.019 seconds (Total)
Chain 1: 

SAMPLING FOR MODEL 'anon_model' NOW (CHAIN 2).
Chain 2: 
Chain 2: Gradient evaluation took 8e-06 seconds
Chain 2: 1000 transitions using 10 leapfrog steps per transition would take 0.08 seconds.
Chain 2: Adjust your expectations accordingly!
Chain 2: 
Chain 2: 
Chain 2: Iteration:    1 / 2000 [  0%]  (Warmup)
Chain 2: Iteration:  200 / 2000 [ 10%]  (Warmup)
Chain 2: Iteration:  400 / 2000 [ 20%]  (Warmup)
Chain 2: Iteration:  600 / 2000 [ 30%]  (Warmup)
Chain 2: Iteration:  800 / 2000 [ 40%]  (Warmup)
Chain 2: Iteration: 1000 / 2000 [ 50%]  (Warmup)
Chain 2: Iteration: 1001 / 2000 [ 50%]  (Sampling)
Chain 2: Iteration: 1200 / 2000 [ 60%]  (Sampling)
Chain 2: Iteration: 1400 / 2000 [ 70%]  (Sampling)
Chain 2: Iteration: 1600 / 2000 [ 80%]  (Sampling)
Chain 2: Iteration: 1800 / 2000 [ 90%]  (Sampling)
Chain 2: Iteration: 2000 / 2000 [100%]  (Sampling)
Chain 2: 
Chain 2:  Elapsed Time: 0.009 seconds (Warm-up)
Chain 2:                0.01 seconds (Sampling)
Chain 2:                0.019 seconds (Total)
Chain 2: 

I cut out the 3rd and 4th chain given restrictions on the number of characters.

Alright, so this means that your rstan installation is fine, but the error is caused by the model/data being passed to stan.

Can you post the model that you’re trying to run?

lossData0 <- fread("https://raw.githubusercontent.com/mages/diesunddas/master/Data/WorkersComp337.csv")
lossData0[,c(1, 2, 5, 8)] <- lapply(lossData0[,c(1, 2, 5, 8)], as.numeric)


myFuns <- "
real[] ode_claimsprocess(real t, real [] y,  real [] theta, 
                         real [] x_r, int[] x_i){
  real dydt[3];
  
  dydt[1] = - theta[1] * t * y[1]; // Exposure
  dydt[2] = theta[1] * t * theta[2] * y[1] - theta[3] * y[2]; // OS
  dydt[3] = theta[3] * theta[4] * y[2]; // Paid
  
  return dydt;
}
real claimsprocess(real t, real premium, real Ber, real kp, 
                   real RLR, real RRF, real delta){
  real y0[3];
  real y[1, 3];
  real theta[4];
  theta[1] = Ber;
  theta[2] = RLR;
  theta[3] = kp;
  theta[4] = RRF;
  y0[1] = premium;
  y0[2] = 0;
  y0[3] = 0;
  y = integrate_ode_rk45(ode_claimsprocess, 
                        y0, 0, rep_array(t, 1), theta,
                        rep_array(0.0, 0), rep_array(1, 1),
                        0.001, 0.001, 100); // tolerances, steps
      return (y[1, 2] * (1 - delta) + y[1, 3] * delta);
}
"

frml <- bf(loss_train ~ claimsprocess(dev, premium, Ber, kp, RLR, RRF, delta),
           RLR ~ 1 + (1 | p | accident_year), # 'p' allow for correlation with RRF 
           RRF ~ 1 + (1 | p | accident_year), # 'p' allow for correlation with RLR
           Ber ~ 1,
           kp ~ 1,
           sigma ~ 0 + deltaf, # different sigma for OS and paid
           nl = TRUE)


mypriors <- c(prior(gamma(4, 5), nlpar = "RLR", lb=0),
              prior(gamma(4, 5), nlpar = "RRF", lb=0),
              prior(gamma(12, 3), nlpar = "Ber", lb=x0),
              prior(gamma(3, 4), nlpar = "kp", lb=0),
              set_prior("lkj(2)", class = "cor"))

b4 <- brm(
  frml, stanvars = stanvar(scode = myFuns, block = "functions"),
  data = lossData0[cal <= max(accident_year) & dev > 0], backend = 'rstan',
  family = brmsfamily("lognormal", link_sigma = "log"),
  prior = mypriors, chains = 1,
  control = list(adapt_delta = 0.999, max_treedepth=5),
  seed = 1, iter = 10, file = "bf4RStan.rds")

This is the model.

In your declaration of the priors:

mypriors <- c(prior(gamma(4, 5), nlpar = "RLR", lb=0),
              prior(gamma(4, 5), nlpar = "RRF", lb=0),
              prior(gamma(12, 3), nlpar = "Ber", lb=x0),
              prior(gamma(3, 4), nlpar = "kp", lb=0),
              set_prior("lkj(2)", class = "cor"))

Should this lower bound be 0 and not x0?

prior(gamma(12, 3), nlpar = "Ber", lb=x0),

Yes, that was it many thanks! I guess I didn’t see the bigger picture after all the errors.

Thanks so much for your quick help and have a nice day!

1 Like

The task is to fix some errors within my code. Running the code of Example.R results in the error: Compiling Stan program… Error in stanc(file = file, model_code = model_code, model_name = model_name, : 0 Semantic error in ‘string’, line 22, column 16 to column 32: Ill-typed arguments supplied to function ‘f_B’. Available signatures: (int, int, real, real[]) => real Instead supplied arguments of incompatible type: int, int, real. Furthermore as I am using the brms-interface, I would like to define the a-parameters of the spline-function as an k x 1 - array where I could either define the spline-parameters as random-effects (with a normal population prior with a common mu- and sigma-parameter) or giving every individual array-element its own prior?

Hi Ayush, can you open a new topic with your issue? Please include the syntax (brms or stan) and if possible some example data that reproduces the issue

How do I open a new Topic ? Following is the code

f_test_stan =
"
// B-Spline basis function
real f_B(int i, // index
int d, // degree
real x, // variable
real [] knots_x) { // knot values

real a;
real b;
real out;

if (d == 0) {
  if (x >= knots_x[i] && x < knots_x[i + 1]) {
    out = 1;
  } else {
    out = 0;
  }
} else {
  a = (x - knots_x[i]) / (knots_x[i + d] - knots_x[i]);
  b = (knots_x[i + d + 1] - x) / (knots_x[i + d + 1] - knots_x[i + 1]);
  out = a * f_B(i, d - 1, x) + b * f_B(i + 1, d - 1, x);
}
return out;

}

// Spline function
real f_spline(real x, // variable
real a1, // parameters
real a2,
real a3,
real a4,
real a5,
real a6,
real a7,
real a8,
real a9,
real a10,
real a11,
real a12){

real out;
int d;
row_vector [15] knots_1;

// initialize values
d = 2;
knots_1 = [-4.0, -2.0, 0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0, 22.0, 24.0];
// knots(n = 10, d = 2, min = 1, max = 7)

// There are n + d many B-splines
out = a1 * f_B(1, d, x, knots_1);
out = out + a2 * f_B(2, d, x, knots_1);
out = out + a3 * f_B(3, d, x, knots_1);
out = out + a4 * f_B(4, d, x, knots_1);
out = out + a5 * f_B(5, d, x, knots_1);
out = out + a6 * f_B(6, d, x, knots_1);
out = out + a7 * f_B(7, d, x, knots_1);
out = out + a8 * f_B(8, d, x, knots_1);
out = out + a9 * f_B(9, d, x, knots_1);
out = out + a10 * f_B(10, d, x, knots_1);
out = out + a11 * f_B(11, d, x, knots_1);
out = out + a12 * f_B(12, d, x, knots_1);
return out;

}
"

out = out + a7 * f_B(7, d, x, knots);out = out + a4 * f_B(4, d, x, knots);# test
test_data = data.table(x = seq(0, 20, 0.01))
test_data[,y := sin(x) + rnorm(1, 0, 0.1), by = ‘x’]
ggplot(test_data, aes(x = x, y = y)) + geom_point(alpha = 0.5) + theme_bw()

Get knot-sequence

k = knots(n = 10, d = 2, min = 0, max = 20)
k
test_data[1, B(i = 5, d = 2, var = x, knots.var = k)]

prior_test = c(set_prior(“normal(0, 1)”, nlpar = “a1”),
set_prior(“normal(0, 1)”, nlpar = “a2”),
set_prior(“normal(0, 1)”, nlpar = “a3”),
set_prior(“normal(0, 1)”, nlpar = “a4”),
set_prior(“normal(0, 1)”, nlpar = “a5”),
set_prior(“normal(0, 1)”, nlpar = “a6”),
set_prior(“normal(0, 1)”, nlpar = “a7”),
set_prior(“normal(0, 1)”, nlpar = “a8”),
set_prior(“normal(0, 1)”, nlpar = “a9”),
set_prior(“normal(0, 1)”, nlpar = “a10”),
set_prior(“normal(0, 1)”, nlpar = “a11”),
set_prior(“normal(0, 1)”, nlpar = “a12”))

eq_test= bf(y ~ f_spline(x, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12),
a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 ~ 1,
nl = TRUE)

stan_vars_test = stanvar(scode = f_test_stan, block = ‘functions’)

mod_test = brm(eq_test,
family = gaussian(),
data = test_data,
prior = prior_test,
stanvars = stan_vars_test,
cores = 4,
iter = 1000,
control = list(adapt_delta = 0.5,
max_treedepth = 15))

Your error is because you have defined the knots_x argument to f_B as taking an array of reals (real[]), but you are passing a row vector (row_vector [15] knots_1).

Try changing the definition to:

real f_B(int i, // index
int d, // degree
real x, // variable
row_vector knots_x)

If experience any more issues, open a new topic using the ‘New Topic’ button on the top-right of the home screen:

1 Like

Thanks a lot. I will surely open a “New Topic” If I experience any more issues.

1 Like