Using cmdstanr in SimDesign

library(SimDesign)
library(cmdstanr)

[Update: Use parallel computing with two cores.]

Adapted from https://cran.r-project.org/web/packages/SimDesign/vignettes/SimDesign-intro.html

See https://mc-stan.org/cmdstanr/articles/cmdstanr.html for using cmdstanr

Design <- createDesign(sample_size = c(30, 60, 120, 240), 
                       distribution = c('norm', 'chi'))
Design
## # A tibble: 8 × 2
##   sample_size distribution
##         <dbl> <chr>       
## 1          30 norm        
## 2          60 norm        
## 3         120 norm        
## 4         240 norm        
## 5          30 chi         
## 6          60 chi         
## 7         120 chi         
## 8         240 chi
Generate <- function(condition, fixed_objects = NULL) {
    N <- condition$sample_size
    dist <- condition$distribution
    if(dist == 'norm'){
        dat <- rnorm(N, mean = 3)
    } else if(dist == 'chi'){
        dat <- rchisq(N, df = 3)
    }
    dat
}

Define Bayes estimator of the mean with STAN

# STAN model
bmean_stan <- "
    data {
        int<lower=0> N;
        real x[N];
    }
    parameters {
        real mu;
        real<lower=0> sigma;
    }
    model {
        target += normal_lpdf(mu | 0, 10);  // weakly informative prior
        target += normal_lpdf(x | mu, sigma);
    }
"
# Save file
stan_path <- write_stan_file(bmean_stan)
mod <- cmdstan_model(stan_path)
## Warning in '/tmp/RtmpVU5PBw/model-7f13b1ada25b1.stan', line 4, column 8: Declaration
##     of arrays by placing brackets after a variable name is deprecated and
##     will be removed in Stan 2.32.0. Instead use the array keyword before the
##     type. This can be changed automatically using the auto-format flag to
##     stanc
Analyse <- function(condition, dat, fixed_objects = NULL) {
    mod <- fixed_objects$mod
    M0 <- mean(dat)
    M1 <- mean(dat, trim = .1)
    M2 <- mean(dat, trim = .2)
    med <- median(dat)
    stan_fit <- quiet(mod$sample(list(x = dat, N = length(dat)),
                                 refresh = 0, chains = 1, 
                                 show_messages = FALSE))
    MB <- stan_fit$summary("mu", mean)$mean[1]
    ret <- c(mean_no_trim = M0, mean_trim.1 = M1, 
             mean_trim.2 = M2, median = med, 
             bayes_mean = MB)
    ret
}
Summarise <- function(condition, results, fixed_objects = NULL) {
    obs_bias <- bias(results, parameter = 3)
    obs_RMSE <- RMSE(results, parameter = 3)
    ret <- c(bias = obs_bias, RMSE = obs_RMSE, RE = RE(obs_RMSE))
    ret
}
res <- runSimulation(Design, replications = 50, generate = Generate, 
                     analyse = Analyse, summarise = Summarise, 
                     parallel = TRUE,
                     ncores = min(2, parallel::detectCores()), 
                     fixed_objects = list(mod = mod),
                     packages = "cmdstanr")
## 
## Number of parallel clusters in use: 2
## 
## 
Design row: 1/8;   Started: Sun Jul 31 00:06:14 2022;   Total elapsed time: 0.00s 
## 
## 
Design row: 2/8;   Started: Sun Jul 31 00:06:21 2022;   Total elapsed time: 6.80s 
## 
## 
Design row: 3/8;   Started: Sun Jul 31 00:06:27 2022;   Total elapsed time: 12.65s 
## 
## 
Design row: 4/8;   Started: Sun Jul 31 00:06:34 2022;   Total elapsed time: 19.65s 
## 
## 
Design row: 5/8;   Started: Sun Jul 31 00:06:39 2022;   Total elapsed time: 25.48s 
## 
## 
Design row: 6/8;   Started: Sun Jul 31 00:06:45 2022;   Total elapsed time: 31.54s 
## 
## 
Design row: 7/8;   Started: Sun Jul 31 00:06:52 2022;   Total elapsed time: 38.26s 
## 
## 
Design row: 8/8;   Started: Sun Jul 31 00:06:59 2022;   Total elapsed time: 44.83s
## 
## Simulation complete. Total execution time: 50.90s
knitr::kable(res)
sample_sizedistributionbias.mean_no_trimbias.mean_trim.1bias.mean_trim.2bias.medianbias.bayes_meanRMSE.mean_no_trimRMSE.mean_trim.1RMSE.mean_trim.2RMSE.medianRMSE.bayes_meanRE.mean_no_trimRE.mean_trim.1RE.mean_trim.2RE.medianRE.bayes_meanREPLICATIONSSIM_TIMECOMPLETEDSEED
30norm-0.01181900.00148620.01263670.0417798-0.01240520.19253570.19622110.19742390.23400950.193164311.0386491.0514211.4772171.0065399506.802Sun Jul 31 00:06:21 2022919770021
60norm0.01385000.01237980.01590130.01434480.01375750.12940690.13222490.13405430.16209160.129623911.0440271.0731171.5689401.0033577505.844Sun Jul 31 00:06:27 20221147125301
120norm0.02486420.02516200.02622310.03092490.02439470.09030660.09251410.09661940.11554420.089668811.0494861.1446951.6370340.9859249507.003Sun Jul 31 00:06:34 2022165936352
240norm-0.0124981-0.0135860-0.0141574-0.0148045-0.01234180.06810800.06858000.07151820.08276850.068808611.0139081.1026461.4768401.0206777505.828Sun Jul 31 00:06:39 20221169202745
30chi0.0300504-0.2925417-0.4179901-0.47757840.02194840.44608870.52561650.60785320.70306880.442867411.3883391.8567572.4840100.9856100506.064Sun Jul 31 00:06:45 2022666552130
60chi0.0302642-0.3434107-0.5061163-0.66352790.03064210.31896060.44173580.57244860.71512310.321727011.9180113.2210605.0267511.0174211506.715Sun Jul 31 00:06:52 2022245891705
120chi0.0297133-0.3006558-0.4464628-0.58092950.02887480.24206120.37484950.49838420.62946950.240143412.3980794.2391446.7623710.9842171506.571Sun Jul 31 00:06:59 20221719562701
240chi0.0170796-0.3419476-0.4842108-0.62317520.01669400.14002200.36833620.50326540.64555980.139853916.91984212.91818921.2559410.9976008506.076Sun Jul 31 00:07:05 20221548188555
Yuan Bo 袁博
Yuan Bo 袁博
Associate Professor of Psychology (Social Psychology)

My research examines the nature and dynamics of social norms, namely how norms may emerge and become stable, why norms may suddenly change, how is it possible that inefficient or unpopular norms survive, and what motivates people to obey norms. I combines laboratory and simulation experiments to test theoretical predictions and build empirically-grounded models of social norms and their dynamics.

comments powered by Disqus

Related