-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest1_sim_fit_recover_attempt2.Rmd
306 lines (255 loc) · 8.02 KB
/
test1_sim_fit_recover_attempt2.Rmd
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
---
title: "Sim, Fit, Recover"
output: html_document
---
```{r setup, message=FALSE}
library(dplyr)
library(tidyr)
library(ggplot2)
library(ggpubr)
library(rstan)
library(cmdstanr)
library(posterior)
library(bayesplot)
CurrentSourceWD<-dirname(rstudioapi::getSourceEditorContext()$path)
setwd(CurrentSourceWD)
source("RW1lr1beta_2arm.R")
source("RW1lr1beta_cf.R")
source("sim_vis_RL2c1o.R")
```
```{r}
task<-list(outcome=data.frame(ref=rep(c(1,1,1,1,0,1,1,1,0,1,1,1,0,0,0,1,0,0,1,0,0),4),
alt=rep(c(0,0,0,0,1,0,0,0,1,0,0,0,1,1,1,0,1,1,0,1,1),4)))
params<-list(alpha=0.3,beta=5)
sim_vis_RL2c1o(RW1lr1beta_2arm,params,task)
sim_vis_RL2c1o(RW1lr1beta_cf,params,task)
```
# simulate from single participant, and fit single-participant
```{r}
#adapting from https://github.com/CCS-Lab/hBayesDM/blob/develop/commons/stan_files/prl_fictitious.stan
stanRW1lr1beta_2arm<-'
data {
int<lower=1> T; // number of trials
int<lower=-1, upper=2> choice[T]; // The choices made; 1 & 2 coding
matrix[T,2] outcome; // The outcome; I modified it...
}
transformed data {
vector[2] initV;
initV = rep_vector(0.5, 2); //start at 0.5
}
// Declare all parameters as vectors for vectorizing
parameters {
// Subject-specific, raw parameters
real alpha_pr; // learning rate
real beta_pr; // inverse temperature
}
transformed parameters {
// Transform into the bounds
real<lower=0, upper=1> alpha;
real<lower=0, upper=10> beta; //need to think: should we impose this bound??
alpha = inv_logit(alpha_pr); //not inv_logit? may be more efficient?
beta = inv_logit(beta_pr)*10; //can this cope with the bound we gave for beta??
}
model {
// Define values
vector[2] ev; // expected value
vector[2] prob; // probability
real prob_1_;
real PE; // prediction error
// Individual parameters: I had to move these BELOW the vector[] and real; how did the hBayesDM code work???
alpha_pr ~ normal(0, 1); //is this weakly informative??
beta_pr ~ normal(0, 1);
// Initialize values
ev = initV; // initial ev values
for (t in 1:T) {
// Compute action probabilities
prob[1] = 1 / (1 + exp(-(beta * (ev[1] - ev[2])))); //could there be a missing minus sign??
prob_1_ = prob[1];
prob[2] = 1 - prob_1_;
choice[t] ~ categorical(prob); //categorical takes in vector? and output 1 or 2
// Prediction error
PE = outcome[t,choice[t]] - ev[choice[t]];
// Value updating (learning)
ev[choice[t]] += alpha * PE;
}
}
'
```
```{r}
compiled_RW1lr1beta_2arm <- stan_model(model_code = stanRW1lr1beta_2arm)
```
```{r}
params_sim<-list(alpha=0.2,beta=1)
s1_2arm<-RW1lr1beta_2arm(params_sim,task)
ntrials = length(s1_2arm$choice)
d_s1 = list('T' = ntrials,#okay using T is a bad, bad idea
choice = s1_2arm$choice,
outcome = as.matrix(task$outcome))
fit_RW1lr1beta_2arm <- sampling(compiled_RW1lr1beta_2arm,
data = d_s1)#,
#chain=4,iter = 12000, warmup = 4000)
```
```{r}
traceplot(fit_RW1lr1beta_2arm)
```
```{r}
alpha_posterior <- rstan::extract(fit_RW1lr1beta_2arm,pars="alpha")
beta_posterior <- rstan::extract(fit_RW1lr1beta_2arm,pars="beta")
hist(alpha_posterior$alpha)
hist(beta_posterior$beta)
mean(alpha_posterior$alpha)
mean(beta_posterior$beta)
```
```{r}
try1<-RW1lr1beta_2arm(list(alpha=0.4,beta=5),d_s1)
try1$loglik
try2<-RW1lr1beta_2arm(list(alpha=0.3,beta=5),d_s1)
try2$loglik
try3<-RW1lr1beta_2arm(list(alpha=0.5,beta=5),d_s1)
try3$loglik
```
# Parameter recovery (for the simple 2arm model):
```{r}
nsims<-50
alpha_range<-runif(nsims,0,1)
beta_range<-rexp(nsims,1/6) #warning: rexp "rate" is not mean
alpha_est<-rep(NA,nsims)
beta_est<-rep(NA,nsims)
for(i in 1:nsims){
params_sim<-list(alpha=alpha_range[i],beta=beta_range[i])
s1_2arm<-RW1lr1beta_2arm(params_sim,task=task)
ntrials = length(s1_2arm$choice)
d_s1 = list('T' = ntrials,#okay using T is a bad, bad idea
choice = s1_2arm$choice,
outcome = as.matrix(task$outcome))
fit_RW1lr1beta_2arm <- sampling(compiled_RW1lr1beta_2arm,
data = d_s1,
chain=4,iter = 4000, warmup = 1000, #by visual inspection, I don't think iter high improved much?
refresh=0)#suppress output
alpha_posterior <- rstan::extract(fit_RW1lr1beta_2arm,pars="alpha")
beta_posterior <- rstan::extract(fit_RW1lr1beta_2arm,pars="beta")
alpha_est[i]<-mean(alpha_posterior$alpha)
beta_est[i]<-mean(beta_posterior$beta)
rm(fit_RW1lr1beta_2arm,alpha_posterior,beta_posterior,s1_2arm,d_s1)
}
```
```{r}
plot(alpha_range,alpha_est)+abline(coef = c(0,1))
plot(beta_range,beta_est)+abline(coef = c(0,1))
```
# Parameter recovery for the counterfactual update model
```{r}
compiled_RW1lr1beta_cf<-stan_model(file="modelSTANfiles/single_RW1lr1beta_cf.stan")
```
```{r}
nsims<-30
alpha_range<-runif(nsims,0,1)
beta_range<-rexp(nsims,1/6) #warning: rexp "rate" is not mean
alpha_est<-rep(NA,nsims)
beta_est<-rep(NA,nsims)
for(i in 1:nsims){
params_sim<-list(alpha=alpha_range[i],beta=beta_range[i])
s1<-RW1lr1beta_cf(params_sim,task=task)
ntrials = length(s1$choice)
d_s1 = list('T' = ntrials,#okay using T is a bad, bad idea
choice = s1$choice,
outcome = as.matrix(task$outcome))
fit_RW1lr1beta_cf <- sampling(compiled_RW1lr1beta_cf,
data = d_s1,
chain=4,iter = 4000, warmup = 1000,
refresh=0)#suppress output
alpha_posterior <- rstan::extract(fit_RW1lr1beta_cf,pars="alpha")
beta_posterior <- rstan::extract(fit_RW1lr1beta_cf,pars="beta")
alpha_est[i]<-mean(alpha_posterior$alpha)
beta_est[i]<-mean(beta_posterior$beta)
rm(fit_RW1lr1beta_cf,alpha_posterior,beta_posterior,s1,d_s1)
}
```
```{r}
plot(alpha_range,alpha_est)+abline(coef = c(0,1))
plot(beta_range,beta_est)+abline(coef = c(0,1))
```
## Meanwhile with maximum likelihood estimation
```{R}
```
# cmdstanr: an alternative
https://mc-stan.org/cmdstanr/articles/cmdstanr.html
```{r}
file <- file.path('modelSTANfiles/single_RW1lr1beta_2arm.stan')
mod <- cmdstan_model(file)
```
```{r}
mod$print()
```
```{r}
fit <- mod$sample(
data = d_s1,
seed = 123,
chains = 4,
parallel_chains = 4,
refresh = 500 # print update every 500 iters
)
```
```{r}
fit$summary()
fit$summary(
variables = NULL,
posterior::default_summary_measures(),
extra_quantiles = ~posterior::quantile2(., probs = c(.0275, .975))
)
draws_df <- fit$draws(format = "df")
mean(draws_df$alpha)
mean(draws_df$beta)
```
```{r}
mcmc_hist(fit$draws("alpha"))+
vline_at(params_sim$alpha, size = 1.5)
mcmc_hist(fit$draws("beta"))+
vline_at(params_sim$beta, size = 1.5)
```
We can also do other approximations
```{r}
# fit_laplace <- mod$laplace(
# mode = fit_map,
# draws = 4000,
# data = d_s1,
# seed = 123,
# refresh = 1000
# )
# mcmc_hist(fit_laplace$draws("alpha"), binwidth = 0.025)
# fit_mle <- mod$optimize(data = d_s1, seed = 123)
# somehow only available in cmdstan >= 2.32
```
# Parameter recovery for cmdstanr
```{r}
nsims<-30
alpha_range<-runif(nsims,0,1)
beta_range<-rexp(nsims,1/6) #warning: rexp "rate" is not mean
alpha_est<-rep(NA,nsims)
beta_est<-rep(NA,nsims)
for(i in 1:nsims){
#again, simulate
params_sim<-list(alpha=alpha_range[i],beta=beta_range[i])
s1_2arm<-RW1lr1beta_2arm(params_sim,task=task)
ntrials = length(s1_2arm$choice)
d_s1 = list('T' = ntrials,#okay using T is a bad, bad idea
choice = s1_2arm$choice,
outcome = as.matrix(task$outcome))
#fit here
fit_RW1lr1beta_2arm <- mod$sample(
data = d_s1,
seed = 123,
chains = 4,
parallel_chains = 4,
refresh = 0 # supress output
)
fitSum<-fit_RW1lr1beta_2arm$summary()
alpha_est[i]<-fitSum$mean[fitSum$variable=="alpha"]
beta_est[i]<-fitSum$mean[fitSum$variable=="beta"]
rm(fit_RW1lr1beta_2arm,s1_2arm,d_s1)
}
```
```{r}
plot(alpha_range,alpha_est)+abline(coef = c(0,1))
plot(beta_range,beta_est)+abline(coef = c(0,1))
```