-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprelim.R
130 lines (100 loc) · 2.31 KB
/
prelim.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
library(tidyverse)
# create data settings
sigmas <- c(1:5, 10, 25, 50, 75, 100)
mus <- c(0, 1, 5, 10, 25, 50, 100)
N <- c(10, 25, 50, 100)
priors <- crossing(mus, sigmas, N) %>%
mutate(setting = glue::glue("mu = {mus} sigma = {sigmas} N = {N}")) %>%
data.frame()
nrow(priors)
# Bob's stan model code
model_string <- "
data {
real mu_mu;
real sigma_mu;
int N;
vector[N] y;
}
parameters {
real mu;
real sigma;
}
model {
y ~ normal(mu, sigma);
mu ~ normal(mu_mu, sigma_mu);
sigma ~ normal(0, 10);
}
"
# function to run models
run_model <- function(
data_settings,
model,
verbose = TRUE,
...) {
data_settings <- unlist(data_settings[1:3])
mu_mu <- data_settings[1]
sigma_mu <- data_settings[2]
y <- rnorm(data_settings[3])
data <- list(
N = length(y),
y = y,
mu_mu = mu_mu,
sigma_mu = sigma_mu
)
fit <- sampling(
model,
data,
refresh = 0,
seed = 8675309,
...
)
if (verbose) {
print(sprintf("mu_mu = %10.5f sigma_mu = %10.5f", mu_mu, sigma_mu), quote = FALSE)
print(fit, prob = c(), digits = 4, pars = c("mu", "sigma"))
}
fit
}
# testing
library(rstan)
# debugonce(run_model)
#
init_model <- stan_model(model_code = model_string)
#
# run_model(priors[1, , drop = F], model = init_model)
library(rstan)
library(future)
library(furrr)
plan(multiprocess(workers = 10))
# takes ~ 1
system.time({
results_raw <- priors %>%
group_split(setting) %>%
future_map(run_model,
model = stan_model(model_code = model_string),
verbose = FALSE,
iter = 1e4,
thin = 20, # to reduce size (1e4/2/20*4 = 1k post warmup)
control = list(
adapt_delta = .99,
max_treedepth = 15
),
.progress = TRUE
)
})
names(results_raw) <- priors$setting
plan(sequential)
clean_up <- function(raw_result) {
summary(raw_result)$summary %>%
as_tibble(rownames = "parameter")
}
results_summaries <- results_raw %>%
map_df(clean_up, .id = "setting")
results_clean <- results_summaries %>%
left_join(priors) %>%
mutate(
ratio = sd / sigmas,
sensitive = ratio > .1
) %>%
arrange(sigmas)
save(results_raw, file = "results_raw.RData")
save(results_summaries, results_clean, file = "results_summaries.RData")