OSCR

Age and loneliness relate to reduced trust learning and alterations in amygdala function.

Code ↔ Paper

3 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 3 matches
  1. [1] § STAR★Methods › Method details › Behavioral data analysis ↔ tg_sulpride_analysis.Rmd, lines 2673–2799 · score 0.53 · precision weighted learning, Model comparison, HGF, publication, prediction, game
  2. [2] § STAR★Methods › Method details › Functional MRI data acquisition, processing, and analyses ↔ results_2026-04-16.ipynb, lines 1554–1644 · score 0.51 · template, masks, ANTs, MRI, MNI, Preprocessing
  3. [3] § STAR★Methods › Method details › Functional MRI data acquisition, processing, and analyses ↔ results_2025-11-01.ipynb, lines 1531–1605 · score 0.51 · template, masks, ANTs, MRI, MNI, Preprocessing

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

R Markdown · 3,974 lines · 195 KB · no license · 1 match

  1. ---
  2. title: "Sulpride effects on learning about trustworthiness of others - figures"
  3. author: "Nace Mikus"
  4. date: "26 3 2020"
  5. output:
  6. word_document: default
  7. pdf_document: default
  8. html_document:
  9. df_print: paged
  10. ---
  11. ```{r setup, include=FALSE}
  12. knitr::opts_chunk$set(echo = TRUE)
  13. ```
  14. # Preparing the terrain
  15. ```{r load packages and data, include = FALSE, eval = TRUE}
  16. # load packages -----------------------------------------------------------
  17. library(tidyverse) # ggplot, dplyr, and friends
  18. library(nlme)
  19. library(lme4)
  20. library(lmerTest)
  21. library(brms)
  22. library(ggridges) # Ridge plots
  23. library(ggstance) # Horizontal pointranges and bars
  24. library(patchwork) # Lay out multiple ggplot plots;
  25. library(scales) # Nicer formatting for numbers
  26. library(broom)
  27. library(rstan)
  28. library(loo)
  29. library(cowplot)
  30. library(ggthemes)
  31. library(foreign)
  32. # utility functions
  33. source("theme_functions.r")
  34. logit <- function(x) log(x/(1-x))
  35. inv_logit <- function(x) 1/(1+exp(-x))
  36. pw = function(x,delta) x^delta/(x^delta + (1-x)^delta)
  37. sf <- function(x, pub = 0, prob_vect = c(0.5,0.025,0.975), dec_no = 3) {
  38. y <- quantile(x, probs=prob_vect)%>% round(dec_no)
  39. y[[4]] <- mean(x<0) %>% round(3)
  40. names(y)[4] <- "p"
  41. p_val = y[[4]];
  42. if (y[[4]] > 0.5) p_val = 1 - p_val
  43. if (y[[1]] < 0) {
  44. y_text = paste("b = ", y[[1]], ", 95% CrI [",y[[2]], ", ",y[[3]], "], P(b>0) = ",p_val, sep ="")
  45. } else y_text = paste("b = ", y[[1]], ", 95% CrI [",y[[2]], ", ",y[[3]], "], P(b<0) = ",p_val, sep ="")
  46. if (pub == 0) {
  47. return(y)
  48. } else {
  49. return(y_text)
  50. } }
  51. wo <- function(x, d = 3, remove.na = FALSE) {
  52. if (remove.na) {
  53. x <- x[abs(x - mean(x, na.rm =TRUE)) <d*sd(x, na.rm =TRUE)]
  54. } else {
  55. x[abs(x - mean(x, na.rm =TRUE)) > d*sd(x, na.rm =TRUE)] <- NA
  56. }
  57. return(x)}
  58. # load data ---------------------------------------------------------------
  59. data_beh <- readRDS("Behavioural_data.rds")
  60. # data_sul <- data_beh[data_beh$Treatment == "sulpiride",] # for serum correlation analysis
  61. data_group <- readRDS("Data_group_level.rds")
  62. data_group = data_group[order(data_group$ID_n),]
  63. # social interaction data ---------------------------------
  64. data_beh_SI <- read.dta("nrprdataset.dta")
  65. # glimpse(data_beh_SI)
  66. data_beh_SI_selected <- data_beh_SI %>% select(bmi, risk)
  67. data_beh_SI = as_tibble(data_beh_SI)
  68. data_beh_SI$Treatment = factor(data_beh_SI$sulpiride == "Sulpiride pill", levels = c(FALSE, TRUE), labels = c("control", "sulpride"))
  69. data_beh_SI$ID = as.factor(data_beh_SI$IDNumber)
  70. data_beh_SI <- data_beh_SI%>% mutate(NegRecFeel = FeelDelighted + FeelReward + FeelPleasure)
  71. data_beh_SI <- data_beh_SI%>% mutate(PosRecFeel = FeelDelightedPR + FeelRewardPR + FeelPleasurePR)
  72. # basic stats across groups
  73. if (FALSE) {
  74. data_demo <- data_beh_SI %>%
  75. filter(Period == 1, ID %in% unique(data_beh$ID)) %>%
  76. group_by(genotype, Treatment) %>% summarize(N = n(),
  77. IQ = mean(fulliq, na.rm = TRUE),
  78. IQ_sd = sd(fulliq, na.rm = TRUE),
  79. verbalIQ = mean(verbaliq, na.rm = TRUE),
  80. verbalIQ_sd = sd(verbaliq, na.rm = TRUE),
  81. BMI_id = mean(bmi, na.rm = TRUE),
  82. BMI_id_sd = sd(bmi, na.rm = TRUE))
  83. data_demo <- data_demo %>% mutate(across(where(is.numeric), round, 3))
  84. data_demo %>% write_csv("BasicDemo_table.csv")
  85. lm(data = data_beh_SI %>% filter(Period == 1, ID %in% unique(data_beh$ID), !is.na(fulliq)), fulliq ~ genotype*Treatment) %>% summary()
  86. lm(data = data_beh_SI %>% filter(Period == 1, ID %in% unique(data_beh$ID), !is.na(verbaliq)), verbaliq ~ genotype*Treatment) %>% summary()
  87. lm(data = data_beh_SI %>% filter(Period == 1, ID %in% unique(data_beh$ID), !is.na(bmi)), bmi ~ genotype*Treatment) %>% summary()
  88. data_beh%>% filter(Trial == 1, Trustee =="Good") %>% group_by(Genotype, Treatment) %>% summarize(N = n())
  89. }
  90. # define the legend plot for all the plots #####
  91. g_legend_plot <- ggplot(data = data_group %>% mutate(drug = factor(drug, levels = c("control", "sulpride"), labels = c("Placebo (P)", "Sulpiride (S)"))), aes(x = drug, y =transfer ))+ # group = ID, linetype = Genotype))
  92. # geom_violin(aes(fill = drug))+
  93. # stat_summary(fun.y=mean, geom="point", shape=20, size=14, color="red", fill="red") +
  94. geom_point(aes(fill = drug, colour = drug), position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1)+theme_Publication(base_size = 8)+
  95. theme(axis.ticks.x = element_blank(),
  96. axis.text.x = element_blank(),
  97. panel.grid.major = element_blank(),
  98. legend.position = "bottom",
  99. legend.title = element_blank(),
  100. legend.key = element_blank(),
  101. plot.margin = unit(c(0, 0, 0, 0), "cm")) +
  102. discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462")))
  103. g_legend_point_plot = get_legend(g_legend_plot)
  104. g_legend_plot <- ggplot(data = data_group %>% mutate(drug = factor(drug, levels = c("control", "sulpride"), labels = c("Placebo", "Sulpiride"))), aes(x = drug, y =transfer ))+ # group = ID, linetype = Genotype))
  105. # geom_violin(aes(fill = drug))+
  106. # stat_summary(fun.y=mean, geom="point", shape=20, size=14, color="red", fill="red") +
  107. geom_point(aes(fill = drug, colour = drug), position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1)+theme_Publication()+
  108. theme(axis.ticks.x = element_blank(),
  109. axis.text.x = element_blank(),
  110. panel.grid.major = element_blank(),
  111. legend.position = "bottom",
  112. legend.title = element_blank(),
  113. legend.key = element_blank(),
  114. plot.margin = unit(c(0, 0, 0, 0), "cm")) +
  115. discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462")))
  116. g_legend_point_plot2 = get_legend(g_legend_plot)
  117. g_legend_plot <- ggplot(data = data_group %>% mutate(drug = factor(drug, levels = c("control", "sulpride"), labels = c("Placebo (P)", "Sulpiride (S)"))), aes(x = drug, y =transfer ))+ # group = ID, linetype = Genotype))
  118. # geom_violin(aes(fill = drug))+
  119. # stat_summary(fun.y=mean, geom="point", shape=20, size=14, color="red", fill="red") +
  120. geom_point(aes(fill = drug, colour = drug), position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1)+theme_Publication()+
  121. theme(axis.ticks.x = element_blank(),
  122. axis.text.x = element_blank(),
  123. panel.grid.major = element_blank(),
  124. legend.position = "left",
  125. legend.title = element_blank(),
  126. legend.key = element_blank(),
  127. plot.margin = unit(c(0, 0, 0, 0), "cm")) +
  128. discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462")))
  129. g_legend_point_plot3 = get_legend(g_legend_plot)
  130. ```
  131. # D2/3 receptor antagonism increases investment updates
  132. # plot effect of sulpiride on abs change across time
  133. ```{r plot investment change across time with Treatment only,fig.width=11, echo=FALSE, message= FALSE}
  134. savemodelname = 'brms_abschange_z_treatment_notrustee_trialc'
  135. if(!file.exists(paste("Behavioral Models/", savemodelname, sep = ""))){
  136. print(paste("estimating model",savemodelname ))
  137. brms_abschange_treatment <- brm(formula = abs_change_z ~ Treatment*Trial_c + (1|ID),
  138. data = data_beh, family = gaussian(),
  139. prior = c(set_prior("cauchy(0,2)", class = "sd"),
  140. set_prior("normal(0,3)", class = "b")),
  141. warmup = 800, iter = 3000, chains =4,
  142. control = list(adapt_delta = 0.95))
  143. saveRDS(brms_abschange_treatment, file = paste("Behavioral Models/", savemodelname, sep=""))
  144. } else {
  145. brms_abschange_treatment <- readRDS(paste("Behavioral Models/", savemodelname,".rds", sep = ""))
  146. }
  147. data_beh2 = data_beh
  148. levels(data_beh2$Treatment) = c("control", "sulpride")
  149. new_data<- fitted(brms_abschange_treatment , newdata = data_beh2, re_formula = NA)
  150. new_data_zinv <- new_data*sd(data_beh$abs_change, na.rm = TRUE) + mean(data_beh$abs_change, na.rm=TRUE)
  151. new_data_abs_change <- cbind(data_beh,new_data_zinv)
  152. g_abs_change_time <- new_data_abs_change %>% filter(!is.na(abs_change)) %>%
  153. ggplot(aes(x = Trial, y = abs_change, group = ID, colour = Treatment)) +#
  154. geom_ribbon(data = new_data_abs_change, aes(x = Trial, ymin = Q2.5, ymax = Q97.5), fill = "#E6E6E6", alpha = 0.3, size = 0.5 )+
  155. # geom_ribbon(data = new_data_temp, aes(x = Trial, ymin = Q25, ymax = Q75),fill = "grey70", alpha = 0.8 )+
  156. geom_line(data = new_data_abs_change, aes(x = Trial, y = Estimate, group = Treatment, colour = Treatment), size = 1)+
  157. stat_summary(aes(group = Treatment), geom = "point", fun.y = mean, shape = 17, size = 1, alpha = 0.5) +
  158. theme_Publication(base_size = 10) +
  159. theme(axis.ticks.x = element_blank(),
  160. axis.text.x = element_text(size=10),
  161. panel.grid.major = element_blank(),
  162. legend.position = "none") +
  163. ylab("Mean absolute change\nin investment") + scale_colour_Publication() + scale_fill_Publication() +scale_x_discrete(name = "Trials", limits=c(0,10,20))
  164. g_abs_change_time
  165. if (TRUE) {
  166. post <- brms_abschange_treatment %>% posterior_samples()
  167. post <- post %>% mutate(sd_total = sqrt(sigma^2 + sd_ID__Intercept^2 ))
  168. post <- post/post$sd_total # get the effect size
  169. post_abs_change <- post
  170. post_no_z = post*sd(data_beh$abs_change, na.rm = TRUE) # in native space
  171. # (post$`b_Treatmentsulpride:Trial`*24 + post$b_Treatmentsulpride )%>% sf()
  172. # effect sizes slope of sulpride
  173. (post$`b_Treatmentsulpride:Trial_c`*24) %>% sf(1)
  174. (post_no_z$`b_Treatmentsulpride:Trial_c`*24) %>% sf(1)
  175. # effect sizes of sulpride (at trial 12)
  176. ( post$b_Treatmentsulpride )%>% sf(1) # effect size
  177. (post_no_z$b_Treatmentsulpride )%>% sf(1) # native space
  178. # effect sizes of sulpride (at trial 24)
  179. (post$`b_Treatmentsulpride:Trial_c`*12 + post$b_Treatmentsulpride )%>% sf(1)
  180. ((post_no_z$`b_Treatmentsulpride:Trial`*12 + post_no_z$b_Treatmentsulpride ))%>% sf(1)
  181. # effect sizes of sulpride (at trial 1)
  182. (-post$`b_Treatmentsulpride:Trial`*12 + post$b_Treatmentsulpride )%>% sf(1)
  183. (-post_no_z$`b_Treatmentsulpride:Trial`*12 + post_no_z$b_Treatmentsulpride )%>% sf(1)
  184. (post$`b_Treatmentsulpride:Trial`+ post$b_Treatmentsulpride )%>% quantile(probs= c(0.5,0.025,0.975)) %>% round(3)
  185. post$`b_Treatmentsulpride:Trial` %>% quantile(probs= c(0.5,0.025,0.975)) %>% round(3)
  186. post$b_Treatmentsulpride %>% quantile(probs= c(0.5,0.025,0.975)) %>% round(3)
  187. (post_no_z$`b_Treatmentsulpride:Trial`*25 + post_no_z$b_Treatmentsulpride )%>% quantile(probs= c(0.5,0.025,0.975)) %>% round(2)
  188. (post_no_z$`b_Treatmentsulpride:Trial`*12 + post_no_z$b_Treatmentsulpride )%>% quantile(probs= c(0.5,0.025,0.975)) %>% round(2)
  189. (post_no_z$`b_Treatmentsulpride:Trial`+ post_no_z$b_Treatmentsulpride )%>% quantile(probs= c(0.5,0.025,0.975)) %>% round(2)
  190. post$`b_Treatmentsulpride:Trial` %>% quantile(probs= c(0.5,0.025,0.975)) %>% round(3)
  191. # ggsave("behavior_w_legend.png", plot = g_beh, device = NULL, path = NULL,
  192. # scale = 1, width =11, height = 5, dpi = 300, limitsize = TRUE)
  193. # g_abs_change_time + facet_wrap(~Genotype)
  194. # g_beh
  195. g_stats <- bind_cols(post_abs_change%>% transmute(C_Sul = b_Treatmentsulpride),
  196. post_abs_change%>% transmute(B_SulXTrials_end = `b_Treatmentsulpride:Trial_c`*12 + b_Treatmentsulpride),
  197. post_abs_change%>% transmute(A_SulXTrials = `b_Treatmentsulpride:Trial_c`*24)
  198. ) %>%
  199. # convert them to the long format, group, and get the posterior summaries
  200. pivot_longer(everything()) %>%
  201. group_by(name) %>%
  202. summarise(mean = mean(value),
  203. ll = quantile(value, prob = .025),
  204. ul = quantile(value, prob = .975),
  205. lls = quantile(value, prob = .25),
  206. uls = quantile(value, prob = .75)) %>% # since the `key` variable is really two variables in one, here we split them up
  207. # plot!
  208. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  209. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  210. geom_vline(xintercept = 0, linetype = "dashed") +
  211. geom_pointrange(color = "firebrick") +
  212. labs( y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  213. theme_Publication(base_size = 10) +
  214. theme(panel.grid = element_blank(),
  215. axis.text.x = element_text(size=10),
  216. strip.background = element_rect(fill = "transparent", color = "transparent"),
  217. axis.title.x = element_blank()) +
  218. scale_y_discrete(labels = rev(c("S - P", "S - P last trial", "(S - P) * Trials")) )
  219. # plot_grid(g_abs_change_time + theme(legend.position = "none"), g_stats, nrow = 2, rel_heights = c(1,.3)
  220. }
  221. ```
  222. # Plot investment change across time with Genotype, trustee and Treatment
  223. ```{r abs investment change across time with Genotype, trustee and Treatment}
  224. # stats and supplementary figure 1 a
  225. data_beh_id <- data_beh %>% group_by(ID,Treatment, Genotype) %>% summarize(abschange_id =abs_change %>% mean(na.rm = T))
  226. data_beh_sum <- data_beh_id %>% group_by(Treatment, Genotype) %>% summarize(N = n(),
  227. abschange_mean =abschange_id %>% mean(na.rm = T),
  228. abschange_se = sd(abschange_id, na.rm = T)/sqrt(N))
  229. g_abschange_gen <- ggplot(data=data_beh_sum) +
  230. # geom_hline(yintercept = 0, linetype = "dashed")+
  231. geom_point(data = data_beh_id, aes(x = Treatment, y = abschange_id, fill= Treatment, colour= Treatment), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1)+
  232. # geom_errorbar(data= model_pp_change, aes(x = Backtransfer_f, ymin = Q25, ymax = Q75, group= Treatment), width = 0, position = position_dodge(0.9),size = 2)+
  233. geom_errorbar(aes(x = Treatment, ymin = abschange_mean - abschange_se, ymax = abschange_mean + abschange_se, group= Treatment), width = 0, position = position_dodge(0.9),size = 1.5)+
  234. geom_point(aes(x = Treatment, y = abschange_mean, fill= Treatment, colour= Treatment), position = position_dodge(0.9), size = 3, shape= 21, colour = "black")+
  235. # geom_bar(aes(x = Backtransfer_f, y = mean_change, group= Treatment, fill = Treatment), stat = "identity", position = position_dodge()) +
  236. # geom_errorbar(aes(x = Backtransfer_f, ymin = mean_change - se_change, ymax = mean_change + se_change, group= Treatment), width = 0, position = position_dodge(0.9))+
  237. theme_Publication(base_size = 10) + theme(legend.position = "none",
  238. axis.text.x = element_text(size=15),
  239. axis.title.x = element_blank(),
  240. panel.grid.major = element_blank()) + #scale_x_discrete(labels = c("Betray", "Equalize")) +
  241. ylab("Mean absolute change\nin investment") + scale_x_discrete(labels = c("P", "S")) + scale_colour_Publication() + scale_fill_Publication()+ facet_wrap(~Genotype)#
  242. savemodelname = 'brms_abschange_z_treatment_gen_trustee_trial_c.rds'
  243. if(!file.exists(paste("Behavioral Models/", savemodelname, sep = ""))){
  244. print(paste("estimating model",savemodelname ))
  245. mc.treatment.notrustee <- brm(formula = abs_change_z ~ Treatment*Trial_c*Trustee_c*Genotype_c + (Trustee_c|ID),
  246. data = data_beh, family = gaussian(),
  247. prior = c(set_prior("cauchy(0,2)", class = "sd"),
  248. set_prior("normal(0,3)", class = "b"),
  249. set_prior("lkj(2)", class = "cor")),
  250. warmup = 800, iter = 3000, chains =4,
  251. control = list(adapt_delta = 0.95))
  252. cat("Saving intercept ~ change_z in ", savemodelname, "... \n")
  253. saveRDS(mc.treatment.notrustee, file = paste("Behavioral Models/", savemodelname, sep=""))
  254. } else brms_abschange_z_treatment_gen_trustee_trial_c <- readRDS("Behavioral Models/brms_abschange_z_treatment_gen_trustee_trial_c.rds")
  255. #
  256. post <- brms_abschange_z_treatment_gen_trustee_trial_c %>% posterior_samples()
  257. post <- post%>% mutate(sd_total = (sqrt(sigma^2 + sd_ID__Intercept^2 + sd_ID__Trustee_c1^2)) )
  258. post <- post/post$sd_total
  259. post_abs_change_gen <- post
  260. post_no_z = post*sd(data_beh$abs_change, na.rm = TRUE)
  261. # main effect
  262. ( post_no_z$b_Treatmentsulpride)%>% sf(1)
  263. # three way interactuon
  264. ( post_no_z$`b_Treatmentsulpride:Trial_c:Genotype_c1`)%>% sf(1)
  265. # two way interactuon
  266. ( post_no_z$`b_Treatmentsulpride:Genotype_c1`)%>% sf(1)
  267. # slope effects
  268. (( post_no_z$`b_Treatmentsulpride:Trial_c` )*24)%>% sf()
  269. (( post_no_z$`b_Treatmentsulpride:Trial_c` + 0.5*post_no_z$`b_Treatmentsulpride:Trial_c:Genotype_c1`)*24) %>% sf()
  270. (( post_no_z$`b_Treatmentsulpride:Trial_c` - 0.5*post_no_z$`b_Treatmentsulpride:Trial_c:Genotype_c1`)*24) %>% sf()
  271. # main effect sizes
  272. ( post$b_Treatmentsulpride)%>% sf(1)
  273. ( post$b_Treatmentsulpride + 1/2*post$`b_Treatmentsulpride:Genotype_c1`)%>% sf(1)
  274. ( post$b_Treatmentsulpride - 1/2*post$`b_Treatmentsulpride:Genotype_c1`)%>% sf(1)
  275. # main effects
  276. ( post_no_z$b_Treatmentsulpride)%>% sf()
  277. ( post_no_z$b_Treatmentsulpride + 1/2*post_no_z$`b_Treatmentsulpride:Genotype_c1`)%>% sf()
  278. ( post_no_z$b_Treatmentsulpride - 1/2*post_no_z$`b_Treatmentsulpride:Genotype_c1`)%>% sf()
  279. # effect sizes of differences in the end
  280. ( post$b_Treatmentsulpride + ( post$`b_Treatmentsulpride:Trial_c`)*12)%>% sf()
  281. ( post$b_Treatmentsulpride + 1/2*post$`b_Treatmentsulpride:Genotype_c1` + ( post$`b_Treatmentsulpride:Trial_c` + 0.5*post$`b_Treatmentsulpride:Trial_c:Genotype_c1`)*12)%>% sf()
  282. ( post$b_Treatmentsulpride - 1/2*post$`b_Treatmentsulpride:Genotype_c1` +( post$`b_Treatmentsulpride:Trial_c` - 0.5*post$`b_Treatmentsulpride:Trial_c:Genotype_c1`)*12)%>% sf()
  283. # effects of differences in the end
  284. ( post_no_z$b_Treatmentsulpride + ( post_no_z$`b_Treatmentsulpride:Trial_c`)*12)%>% sf()
  285. ( post_no_z$b_Treatmentsulpride + 1/2*post_no_z$`b_Treatmentsulpride:Genotype_c1` + ( post_no_z$`b_Treatmentsulpride:Trial_c` + 0.5*post_no_z$`b_Treatmentsulpride:Trial_c:Genotype_c1`)*12)%>% sf()
  286. ( post_no_z$b_Treatmentsulpride - 1/2*post_no_z$`b_Treatmentsulpride:Genotype_c1` +( post_no_z$`b_Treatmentsulpride:Trial_c` - 0.5*post_no_z$`b_Treatmentsulpride:Trial_c:Genotype_c1`)*12)%>% sf()
  287. # g_beh
  288. g_stats_gen_supp <- bind_cols(
  289. post_abs_change_gen %>% transmute(A7 = `b_Treatmentsulpride:Trial_c`*24),
  290. post_abs_change_gen %>% transmute(A4 = (`b_Treatmentsulpride:Trial_c` + 0.5*`b_Treatmentsulpride:Trial_c:Genotype_c1`)*24) ,
  291. post_abs_change_gen %>% transmute(A1 =(`b_Treatmentsulpride:Trial_c` - 0.5*`b_Treatmentsulpride:Trial_c:Genotype_c1`)*24) ,
  292. post_abs_change_gen %>% transmute(A9 =b_Treatmentsulpride),
  293. post_abs_change_gen %>% transmute(A6 =b_Treatmentsulpride + 1/2*`b_Treatmentsulpride:Genotype_c1`),
  294. post_abs_change_gen %>% transmute(A3 =b_Treatmentsulpride - 1/2*`b_Treatmentsulpride:Genotype_c1`),
  295. post_abs_change_gen %>% transmute(A8 =b_Treatmentsulpride + ( `b_Treatmentsulpride:Trial_c`)*12),
  296. post_abs_change_gen %>% transmute(A5 =b_Treatmentsulpride + 1/2*`b_Treatmentsulpride:Genotype_c1` + ( `b_Treatmentsulpride:Trial_c` + 0.5*`b_Treatmentsulpride:Trial_c:Genotype_c1`)*12),
  297. post_abs_change_gen %>% transmute(A2 =b_Treatmentsulpride - 1/2*`b_Treatmentsulpride:Genotype_c1` +( `b_Treatmentsulpride:Trial_c` - 0.5*`b_Treatmentsulpride:Trial_c:Genotype_c1`)*12)
  298. ) %>%
  299. # convert them to the long format, group, and get the post_abs_change_generior summaries
  300. pivot_longer(everything()) %>%
  301. group_by(name) %>%
  302. summarise(mean = mean(value),
  303. ll = quantile(value, prob = .025),
  304. ul = quantile(value, prob = .975),
  305. lls = quantile(value, prob = .25),
  306. uls = quantile(value, prob = .75)) %>% # since the `key` variable is really two variables in one, here we split them up
  307. # plot!
  308. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  309. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  310. geom_vline(xintercept = 0, color = "black", linetype = "dashed") +
  311. geom_pointrange(color = "firebrick") +
  312. labs(y = NULL) + # subtitle = "Effect size (95% and 50% quantiles)",
  313. theme_Publication() +
  314. theme(panel.grid = element_blank(),
  315. strip.background = element_rect(fill = "transparent", color = "transparent"),
  316. axis.title.x = element_blank()) +
  317. scale_y_discrete(labels = rev(c("S - P", "S - P last trial", "(S - P)*trials",
  318. "S-P in A1+", "S - P last trial in A1+", "(S - P)*trials in A1+",
  319. "S - P in A1-", "S - P last trial in A1-", "(S - P)*trials in A1-")) )
  320. ```
  321. Look at stats for the above (tables saved for the supplementary).
  322. ```{r abs change supplementary tables and lme models}
  323. if (FALSE) {
  324. # Supplementary Table 1
  325. brms_abschange_treatment %>% fixef()%>% round(3) %>% write.csv("brms_abschange_treatment.csv")
  326. # Supplementary Table 2
  327. model_abs_change <- lme(abs_change_z ~ Treatment*Trial_c, data = data_beh%>% filter(!is.na(abs_change)), random = ~1|ID, method = "ML")
  328. model_abs_change %>% summary() %>% coef() %>% as.data.frame()%>% round(3) %>% write.csv("lme_abschange_z_treatment_notrustee_trialc.csv")
  329. # Supplementary Table 3
  330. model_abs_change_log <- lme(log_abs_change_z ~ Treatment*Trial_c, data = data_beh%>% filter(!is.na(abs_change)), random = ~1|ID, method = "ML")
  331. model_abs_change_log %>% summary() %>% coef() %>% as.data.frame() %>% round(3) %>% write.csv("lme_abschange_log_z_treatment_notrustee_trialc.csv")
  332. brms_abschange_z_treatment_gen_trustee_trial_c %>% fixef()%>% round(3) %>% write.csv("brms_abschange_z_treatment_gen_trustee_trialc.csv")
  333. }
  334. ```
  335. # Plot Change in response to Back-transfer
  336. ```{r plot chage trial means, fig.width = 10, fig.height = 9, echo=FALSE, warning= FALSE}
  337. # Supplementary figure 1 b
  338. # plot change trial means genotype investment -------------------------------------------------
  339. savemodelname = 'brms_change_z_treatment_genotype.rds'
  340. if(!file.exists(paste("Behavioral Models/", savemodelname, sep = ""))){
  341. brms_change_z_treatment_genotype <- brm(formula = Change_z ~ Treatment*Genotype*Backtransfer*Trustee_c + (Trustee_c|ID),
  342. data = data_beh, family = gaussian(),
  343. prior = c(set_prior("cauchy(0,2)", class = "sd"),
  344. set_prior("normal(0,3)", class = "b"),
  345. set_prior("lkj(2)", class = "cor")),
  346. warmup = 800, iter = 3000, chains =4,
  347. control = list(adapt_delta = 0.95))
  348. # summary(mc.baseline)
  349. cat("Saving intercept ~ change_z in ", savemodelname, "... \n")
  350. saveRDS(mc.baseline.change_z.notrustee, file = paste("Behavioral Models/", savemodelname, sep=""))
  351. } else brms_change_z_treatment_genotype <- readRDS("Behavioral Models/brms_change_z_treatment_genotype.rds")
  352. data_beh$Backtransfer_f <- factor(data_beh$Backtransfer, levels = c(-1,1), labels = c("Betray", "Equalize"))
  353. data_change_id <- data_beh %>% filter(!is.na(Change)) %>% group_by(Treatment, Genotype, Backtransfer_f, ID) %>% summarise( Change = mean(Change))
  354. data_change <- data_change_id %>% group_by(Treatment, Genotype, Backtransfer_f) %>% summarise(N = n(),
  355. mean_change = mean(Change),
  356. se_change = sd(Change)/sqrt(N))
  357. new_data_change <- expand.grid(Treatment = data_beh$Treatment%>% unique(),
  358. Genotype = data_beh$Genotype %>% unique(),
  359. Backtransfer = data_beh$Backtransfer %>% unique(),
  360. Trustee_c = data_beh$Trustee_c %>% unique())
  361. model_pp <- fitted(brms_change_z_treatment_genotype, newdata = new_data_change, re_formula = NA, summary = FALSE)
  362. model_pp <- model_pp*sd(data_beh$Change, na.rm =TRUE) + mean(data_beh$Change, na.rm = TRUE)
  363. model_pp <- (model_pp[,new_data_change$Trustee_c == "Good"] + model_pp[,new_data_change$Trustee_c == "Bad"]) / 2
  364. model_pp_all <- new_data_change %>% filter(Trustee_c == "Good")
  365. model_pp_change <- model_pp_all %>% mutate(Est = model_pp %>% apply(2, quantile, probs = c(0.5)),
  366. Q2.5 =model_pp %>% apply(2, quantile, probs = c(0.025)),
  367. Q25 = model_pp %>% apply(2, quantile, probs = c(0.25)),
  368. Q75 = model_pp %>% apply(2, quantile, probs = c(0.75)),
  369. Q975 = model_pp %>% apply(2, quantile, probs = c(0.975)))
  370. model_pp_change$Backtransfer_f <- factor(model_pp_change$Backtransfer, levels = c(-1,1), labels = c("Betray", "Equalize"))
  371. # model_pp_change %>% glimpse()
  372. g_change_gen <- ggplot(data=data_change) +
  373. geom_hline(yintercept = 0, linetype = "dashed")+
  374. geom_point(data = data_change_id, aes(x = Backtransfer_f, y = Change, fill= Treatment, colour= Treatment), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 1, stroke = 0.5)+
  375. geom_errorbar(data= model_pp_change, aes(x = Backtransfer_f, ymin = Q2.5, ymax = Q975, group= Treatment), width = 0, position = position_dodge(0.9),size = 1)+
  376. geom_point(data= model_pp_change, aes( x = Backtransfer_f, y = Est, fill= Treatment, colour= Treatment), position = position_dodge(0.9), size = 3, shape= 21, colour = "black")+
  377. theme_Publication(base_size = 10) + theme(legend.position = "none",
  378. axis.text.x = element_text(size=10),
  379. panel.grid.major = element_blank()) +
  380. ylab("Mean Change") + xlab("Back-transfer (BT)") + scale_colour_Publication() + scale_fill_Publication()+ facet_wrap(~Genotype)#
  381. df.sigplot = data.frame(x = c("Betray", "Betray"),
  382. xend = c("Equalize", "Betray"),
  383. txt = c("*", ""),
  384. x_pt1 = c("Betray", NA),
  385. x_pt2 = c("Equalize", NA),
  386. y_pt = c(1.4 , NA),
  387. Genotype = model_pp_change$Genotype%>% unique() )
  388. g_change_gen <- g_change_gen + geom_segment(data = df.sigplot, aes(x = x, y = 1.5, xend = xend, yend = 1.5)) +
  389. geom_text(data = df.sigplot, aes(label = txt), x = 1.5, y = 1.6, size = 10) +
  390. geom_point(data = df.sigplot,aes(x = x_pt1, y = y_pt), shape = 17, size = 3 ) +
  391. geom_point(data = df.sigplot,aes(x = x_pt2, y = y_pt), shape = 17, size = 3 )
  392. if (FALSE) {
  393. post = posterior_samples(brms_change_z_treatment_genotype )
  394. # back to absolute scale
  395. post_no_z <- post*sd(data_beh$Change, na.rm =TRUE)
  396. # turn to effect size
  397. post <- post %>% mutate(sd_total = sqrt(sigma^2 + sd_ID__Intercept^2 + sd_ID__Trustee_c1^2))
  398. post <- post/post$sd_total
  399. post_change <- post
  400. (post$`b_Treatmentsulpiride:GenotypeA1M:Backtransfer`) %>% sf(1)
  401. (post_no_z$`b_Treatmentsulpiride:GenotypeA1M:Backtransfer`) %>% sf(1)
  402. (post$`b_Treatmentsulpiride:Backtransfer` + 1/2*post$`b_Treatmentsulpiride:GenotypeA1M:Backtransfer`) %>% sf(1)
  403. (post_no_z$`b_Treatmentsulpiride:Backtransfer` + 1/2*post_no_z$`b_Treatmentsulpiride:GenotypeA1M:Backtransfer`) %>% sf(1)
  404. (post$`b_Treatmentsulpiride:Backtransfer` ) %>% sf(1)
  405. (post_no_z$`b_Treatmentsulpiride:Backtransfer` ) %>% sf(1)
  406. (post$`b_Treatmentsulpiride:Backtransfer` + post$`b_Treatmentsulpiride:GenotypeA1M:Backtransfer` ) %>% sf(1)
  407. (post_no_z$`b_Treatmentsulpiride:Backtransfer` + post_no_z$`b_Treatmentsulpiride:GenotypeA1M:Backtransfer` ) %>% sf(1)
  408. }
  409. g_stats_change <- bind_cols(post_change%>% transmute(C_Sul = `b_Treatmentsulpiride:Backtransfer` + 1/2*`b_Treatmentsulpiride:GenotypeA1M:Backtransfer`),
  410. post_change%>% transmute(B_SulXTrials_end =`b_Treatmentsulpiride:Backtransfer`),
  411. post_change%>% transmute(A_SulXTrials =`b_Treatmentsulpiride:Backtransfer` + `b_Treatmentsulpiride:GenotypeA1M:Backtransfer`)
  412. ) %>%
  413. # convert them to the long format, group, and get the posterior summaries
  414. pivot_longer(everything()) %>%
  415. group_by(name) %>%
  416. summarise(mean = mean(value),
  417. ll = quantile(value, prob = .025),
  418. ul = quantile(value, prob = .975),
  419. lls = quantile(value, prob = .25),
  420. uls = quantile(value, prob = .75)) %>% # since the `key` variable is really two variables in one, here we split them up
  421. # plot!
  422. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  423. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  424. geom_vline(xintercept = 0, linetype="dashed") +
  425. geom_pointrange(color = "firebrick") +
  426. labs(y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  427. theme_Publication(base_size = 10) +
  428. theme(panel.grid = element_blank(),
  429. axis.text.x = element_text(size=10),
  430. strip.background = element_rect(fill = "transparent", color = "transparent"),
  431. axis.title.x = element_blank()) +
  432. scale_y_discrete(labels = rev(c("(S - P)*BT", "(S - P)*BT in A1+", "(S - P)*BT in A1-")) )
  433. # plot_grid(g_abs_change_time + theme(legend.position = "none"), g_stats, nrow = 2, rel_heights = c(1,.3)
  434. g_supplementary_figure1 <- plot_grid(
  435. plot_grid(g_abschange_gen+ xlab("") + theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")), g_stats_gen_supp+ theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")), ncol = 1, rel_heights = c(1,0.5)),
  436. plot_grid(g_change_gen+ theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")),g_legend_point_plot, g_stats_change+ theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")), ncol = 1, rel_heights = c(1,0.2,0.3)),
  437. rel_widths = c(1,1),
  438. nrow = 1, labels = "auto")
  439. g_supplementary_figure1
  440. ggsave("g_supplementary_figure1.pdf", plot = g_supplementary_figure1, device = "pdf", units = "mm",
  441. scale = 1, width =179 , height = 120, dpi = 600, limitsize = TRUE)
  442. ggsave("g_supplementary_figure1.png", plot = g_supplementary_figure1, device = "png", units = "mm",
  443. scale = 1, width =179 , height = 120, dpi = 600, limitsize = TRUE)
  444. ```
  445. Stats for the above for the supplementary
  446. ```{r change supplementary, tables and lme models}
  447. # for supplementary
  448. if (FALSE) {
  449. brms_change_z_treatment_genotype %>% fixef()%>% round(3) %>% write.csv("brms_change_z_treatment_genotype.csv")
  450. model_change <- lme(Change_z ~ Treatment*Backtransfer*Genotype*Trustee_c, data = data_beh%>% filter(!is.na(abs_change)), random = ~Trustee_c|ID, method = "REML")
  451. model_change %>% summary() %>% coef() %>% as.data.frame()%>% round(3) %>% write.csv("lme_change_z_treatment_genotype.csv")
  452. model_change2 <- lme(Change_z ~ Treatment*Backtransfer*Genotype, data = data_beh%>% filter(!is.na(abs_change)), random = ~1|ID, method = "ML")
  453. summary(model_change2)
  454. anova(model_change, model_change2)
  455. data_beh$log_abs_change <- log(1+data_beh$abs_change)
  456. model_abs_change <- lme(log_abs_change ~ Treatment*Trial_c, data = data_beh%>% filter(!is.na(abs_change)), random = ~1|ID, method = "ML")
  457. summary(model_abs_change)
  458. data_beh$log_abs_change <- log(1+data_beh$abs_change)
  459. model_abs_change2 <- lme(log_abs_change ~ Treatment*Trial_c*Trustee_c*Genotype, data = data_beh%>% filter(!is.na(abs_change)), random = ~Trustee_c|ID, method = "ML")
  460. summary(model_abs_change2)
  461. }
  462. # data = data_beh_SI_analysis)
  463. ```
  464. # plot reciprocal trials
  465. ```{r reciprocal trials}
  466. savemodelname = 'brms_rec_treatment_genotype_Trustee_c.rds'
  467. if(!file.exists(paste("Behavioral Models/", savemodelname, sep = ""))){
  468. print(paste("estimating model",savemodelname ))
  469. mc.rec.model <- brm(rec ~ Treatment*Genotype*Trustee_c + (Trustee_c|ID),
  470. data = data_beh, family = bernoulli(),
  471. prior = c(set_prior("cauchy(0,2)", class = "sd"),
  472. set_prior("normal(0,3)", class = "b"),
  473. set_prior("lkj(2)", class = "cor")),
  474. warmup = 800, iter = 3000, chains =4,
  475. control = list(adapt_delta = 0.95))
  476. # summary(mc.baseline)
  477. saveRDS(mc.rec.model, file = paste("Behavioral Models/", savemodelname, sep=""))
  478. } else brms_rec_treatment_genotype_Trustee_c <- readRDS("Behavioral Models/brms_rec_treatment_genotype_Trustee_c.rds")
  479. data_rec_id<- data_beh %>% filter(!is.na(Change)) %>%
  480. group_by(ID, Treatment, Genotype) %>%
  481. summarise(N =n(),
  482. Serum = Serum[1],
  483. rec_id = (sum(pos_rec)+sum(neg_rec))/N,
  484. incon_id = sum(incongruent) /N,
  485. absolute_id = sum(absolute)/N) %>%
  486. ungroup()
  487. new_data_rec <- expand.grid(Treatment = data_beh$Treatment%>% unique(),
  488. Genotype = data_beh$Genotype %>% unique(),
  489. Trustee_c = data_beh$Trustee_c %>% unique())
  490. model_pp <- fitted(brms_rec_treatment_genotype_Trustee_c, newdata = new_data_rec, re_formula = NA, summary = FALSE)
  491. # model_pp %>% glimpse()
  492. model_pp <- (model_pp[,new_data_rec$Trustee_c == "Good"] + model_pp[,new_data_rec$Trustee_c == "Bad"]) / 2
  493. model_pp_all <- new_data_rec %>% filter(Trustee_c == "Good")
  494. model_pp_rec <- model_pp_all %>% mutate(Est = model_pp %>% apply(2, quantile, probs = c(0.5)),
  495. Q2.5 =model_pp %>% apply(2, quantile, probs = c(0.025)),
  496. Q25 = model_pp %>% apply(2, quantile, probs = c(0.25)),
  497. Q75 = model_pp %>% apply(2, quantile, probs = c(0.75)),
  498. Q975 = model_pp %>% apply(2, quantile, probs = c(0.975)))
  499. g_rec <- ggplot() +
  500. geom_point(data = data_rec_id, aes(x = Treatment, y = rec_id, fill= Treatment, colour= Treatment), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 1, stroke =0.5)+
  501. geom_errorbar(data= model_pp_rec, aes(x = Treatment, ymin = Q2.5, ymax = Q975, group= Treatment), width = 0, position = position_dodge(0.9),size = 1.5)+
  502. geom_point(data= model_pp_rec, aes(x = Treatment, y = Est, fill= Treatment, colour= Treatment), position = position_dodge(0.9), size = 3, shape= 21, colour = "black")+
  503. theme_Publication(base_size = 10) + theme(legend.position = "none",
  504. axis.text.x = element_text(size=10),
  505. panel.grid.major = element_blank()) + #scale_x_discrete(labels = c("Betray", "Equalize")) +
  506. ylab("Proportion of\nreciprocal trials") + xlab(" ") + scale_x_discrete(labels = c("P", "S"))+ scale_colour_Publication() + scale_fill_Publication()#
  507. g_rec_gen <- g_rec + facet_wrap(~Genotype)
  508. df.sigplot = data.frame(x = c("control", "control"),
  509. xend = c("sulpiride", "control"),
  510. txt = c("*", ""),
  511. Genotype = model_pp_rec$Genotype%>% unique() )
  512. g_rec_gen <- g_rec_gen + geom_segment(data = df.sigplot, aes(x = x, y = 0.85, xend = xend, yend = 0.85)) +
  513. geom_text(data = df.sigplot, aes(label = txt), x = 1.5, y = 0.86, size = 10)
  514. if (FALSE) {
  515. post = posterior_samples(brms_rec_treatment_genotype_Trustee_c )
  516. # back to absolute scale
  517. # turn to effect size
  518. post <- post %>% mutate(sd_total = sqrt(sd_ID__Intercept^2 + sd_ID__Trustee_c1^2))
  519. post <- post/post$sd_total
  520. post_rec <- post
  521. (post$b_Treatmentsulpiride + 1/2*post$`b_Treatmentsulpiride:GenotypeA1M`) %>% sf(1)
  522. (post$b_Treatmentsulpiride) %>% sf(1)
  523. (post$b_Treatmentsulpiride + post$`b_Treatmentsulpiride:GenotypeA1M`) %>% sf(1)
  524. (post$`b_Treatmentsulpiride:GenotypeA1M`) %>% sf(1)
  525. }
  526. g_stats_rec <- bind_cols(post_rec%>% transmute(C_Sul = b_Treatmentsulpiride + 1/2*`b_Treatmentsulpiride:GenotypeA1M`),
  527. post_rec%>% transmute(B_Sul =b_Treatmentsulpiride),
  528. post_rec%>% transmute(A_Sul =b_Treatmentsulpiride + `b_Treatmentsulpiride:GenotypeA1M`)
  529. ) %>%
  530. # convert them to the long format, group, and get the posterior summaries
  531. pivot_longer(everything()) %>%
  532. group_by(name) %>%
  533. summarise(mean = mean(value),
  534. ll = quantile(value, prob = .025),
  535. ul = quantile(value, prob = .975),
  536. lls = quantile(value, prob = .25),
  537. uls = quantile(value, prob = .75)) %>% # since the `key` variable is really two variables in one, here we split them up
  538. # plot!
  539. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  540. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  541. geom_vline(xintercept = 0, linetype="dashed") +
  542. geom_pointrange(color = "firebrick") +
  543. labs(y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  544. theme_Publication(base_size = 10) +
  545. theme(panel.grid = element_blank(),
  546. axis.text.x = element_text(size=10, ),
  547. strip.background = element_rect(fill = "transparent", color = "transparent"),
  548. axis.title.x = element_blank()) +
  549. scale_y_discrete(labels = rev(c("S - P", "S - P in A1+", "S - P in A1-")) ) +
  550. scale_x_continuous(breaks = c(0, 0.4,0.8))
  551. # plot_grid(g_abs_change_time + theme(legend.position = "none"), g_stats, nrow = 2, rel_heights = c(1,.3)
  552. ```
  553. ```{r mistake trials}
  554. # for figure on gamma (Fig 4)
  555. savemodelname = 'brms_incon_treatment_genotype_Trustee_c.rds'
  556. if(!file.exists(paste("Behavioral Models/", savemodelname, sep = ""))){
  557. print(paste("estimating model",savemodelname ))
  558. brms_incon_treatment_genotype_Trustee_c <- brm(incongruent ~ Treatment*Genotype*Trustee_c + (Trustee_c|ID),
  559. data = data_beh, family = bernoulli(),
  560. prior = c(set_prior("cauchy(0,2)", class = "sd"),
  561. set_prior("normal(0,3)", class = "b"),
  562. set_prior("lkj(2)", class = "cor")),
  563. warmup = 800, iter = 3000, chains =4,
  564. control = list(adapt_delta = 0.95))
  565. # summary(mc.baseline)
  566. saveRDS(mc.incon.model, file = paste("Behavioral Models/", savemodelname, sep=""))
  567. }else brms_incon_treatment_genotype_Trustee_c <- readRDS("Behavioral Models/brms_incon_treatment_genotype_Trustee_c.rds")
  568. data_rec_id<- data_beh %>% filter(!is.na(Change)) %>%
  569. group_by(ID, Treatment, Genotype) %>%
  570. summarise(N =n(),
  571. Serum = Serum[1],
  572. rec_id = (sum(pos_rec)+sum(neg_rec))/N,
  573. incon_id = sum(incongruent) /N,
  574. absolute_id = sum(absolute)/N) %>%
  575. ungroup()
  576. new_data_rec <- expand.grid(Treatment = data_beh$Treatment%>% unique(),
  577. Genotype = data_beh$Genotype %>% unique(),
  578. Trustee_c = data_beh$Trustee_c %>% unique())
  579. model_pp <- fitted(brms_incon_treatment_genotype_Trustee_c, newdata = new_data_rec, re_formula = NA, summary = FALSE)
  580. model_pp <- (model_pp[,new_data_rec$Trustee_c == "Good"] + model_pp[,new_data_rec$Trustee_c == "Bad"]) / 2
  581. model_pp_all <- new_data_rec %>% filter(Trustee_c == "Good")
  582. model_pp_rec <- model_pp_all %>% mutate(Est = model_pp %>% apply(2, quantile, probs = c(0.5)),
  583. Q2.5 =model_pp %>% apply(2, quantile, probs = c(0.025)),
  584. Q25 = model_pp %>% apply(2, quantile, probs = c(0.25)),
  585. Q75 = model_pp %>% apply(2, quantile, probs = c(0.75)),
  586. Q975 = model_pp %>% apply(2, quantile, probs = c(0.975)))
  587. data_rec_id %>% glimpse()
  588. g_incon<- ggplot() +
  589. geom_point(data = data_rec_id, aes(x = Treatment, y = incon_id, fill= Treatment, colour= Treatment), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.5), shape = 21, colour = "black", size = 1, stroke =0.5)+
  590. geom_errorbar(data= model_pp_rec, aes(x = Treatment, ymin = Q2.5, ymax = Q975, group= Treatment), width = 0, position = position_dodge(0.9),size = 1.5)+
  591. geom_point(data= model_pp_rec, aes(x = Treatment, y = Est, fill= Treatment, colour= Treatment), position = position_dodge(0.9), size = 3, shape= 21, colour = "black")+
  592. theme_Publication(base_size = 10) + theme(legend.position = "none",
  593. axis.text.x = element_blank(),
  594. axis.ticks.x = element_blank(),
  595. axis.title.x = element_blank(),
  596. panel.grid.major = element_blank()) + #scale_x_discrete(labels = c("Betray", "Equalize")) +
  597. ylab("Proportion of\nmistake trials") + scale_colour_Publication() + scale_fill_Publication()#
  598. g_incon_gen <- g_incon + facet_wrap(~Genotype)
  599. df.sigplot = data.frame(x = c("control", "control"),
  600. xend = c("control", "sulpiride"),
  601. txt = c("", "*"),
  602. Genotype = model_pp_rec$Genotype%>% unique() )
  603. g_incon_gen <- g_incon_gen + geom_segment(data = df.sigplot, aes(x = x, y = 0.35, xend = xend, yend = 0.35)) +
  604. geom_text(data = df.sigplot, aes(label = txt), x = 1.5, y = 0.36, size = 10)
  605. if (FALSE) {
  606. post = posterior_samples(brms_incon_treatment_genotype_Trustee_c )
  607. # back to absolute scale
  608. # turn to effect size
  609. post <- post %>% mutate(sd_total = sqrt(sd_ID__Intercept^2 + sd_ID__Trustee_c1^2))
  610. post <- post/post$sd_total
  611. post_incon <- post
  612. (post$b_Treatmentsulpiride + 1/2*post$`b_Treatmentsulpiride:GenotypeA1M`) %>% sf(1)
  613. (post$b_Treatmentsulpiride) %>% sf(1)
  614. (post$b_Treatmentsulpiride + post$`b_Treatmentsulpiride:GenotypeA1M`) %>% sf(1)
  615. (post$`b_Treatmentsulpiride:GenotypeA1M`) %>% sf(1)
  616. }
  617. g_stats_incon <- bind_cols(post_incon%>% transmute(C_Sul = b_Treatmentsulpiride + 1/2*`b_Treatmentsulpiride:GenotypeA1M`),
  618. post_incon%>% transmute(B_Sul =b_Treatmentsulpiride),
  619. post_incon%>% transmute(A_Sul =b_Treatmentsulpiride + `b_Treatmentsulpiride:GenotypeA1M`)
  620. ) %>%
  621. # convert them to the long format, group, and get the posterior summaries
  622. pivot_longer(everything()) %>%
  623. group_by(name) %>%
  624. summarise(mean = mean(value),
  625. ll = quantile(value, prob = .025),
  626. ul = quantile(value, prob = .975),
  627. lls = quantile(value, prob = .25),
  628. uls = quantile(value, prob = .75)) %>% # since the `key` variable is really two variables in one, here we split them up
  629. # plot!
  630. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  631. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  632. geom_vline(xintercept = 0, linetype="dashed") +
  633. geom_pointrange(color = "firebrick") +
  634. labs(y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  635. theme_Publication(base_size = 10) +
  636. theme(panel.grid = element_blank(),
  637. axis.text.x = element_text(size=10, ),
  638. strip.background = element_rect(fill = "transparent", color = "transparent"),
  639. axis.title.x = element_blank()) +
  640. scale_y_discrete(labels = rev(c("S - P", "S - P in A1+", "S - P in A1-")) ) +
  641. scale_x_continuous(breaks = c(0,1))
  642. ```
  643. Stats for the above
  644. ```{r reciprocal and mistake trials stats}
  645. # reciprocal trials ####
  646. savemodelname = 'brms_rec_logserum_genotype_trustee_c.rds'
  647. if(!file.exists(paste("Behavioral Models/", savemodelname, sep = ""))){
  648. print(paste("estimating model",savemodelname ))
  649. brms_rec_logserum_genotype_trustee_c <- brm(rec ~ logserum_s*Genotype*Trustee_c + (Trustee_c|ID),
  650. data = data_sul, family = bernoulli(),
  651. prior = c(set_prior("cauchy(0,2)", class = "sd"),
  652. set_prior("normal(0,3)", class = "b"),
  653. set_prior("lkj(2)", class = "cor")),
  654. warmup = 800, iter = 3000, chains =4,
  655. control = list(adapt_delta = 0.95))
  656. # summary(mc.baseline)
  657. saveRDS(mc.rec.model, file = paste("Behavioral Models/", savemodelname, sep=""))
  658. }else brms_rec_logserum_genotype_trustee_c <- readRDS("Behavioral Models/brms_rec_logserum_genotype_trustee_c.rds")
  659. post_rec <- posterior_samples(brms_rec_logserum_genotype_trustee_c)
  660. post_rec$b_logserum_s%>% sf(1)
  661. # model_rec <- glmer(rec ~ Treatment*Genotype*Trustee_c + (Trustee_c|ID), data = data_beh%>% filter(!is.na(abs_change)), family = binomial())
  662. data_serum_rec = data_beh%>% filter(!is.na(abs_change), Treatment == "sulpiride")
  663. data_serum_rec$logserum_s = ave(log(data_serum_rec$Serum), FUN = scale)
  664. data_group_sul = data_group %>% filter(drug == "sulpiride")
  665. data_group_sul$logserum_s = data_group_sul$serum %>% log() %>% ave(FUN = scale)
  666. data_rec_id$Serum_s = ave(data_rec_id$Serum, FUN = scale)
  667. mod_rec_ser <- lm(data= data_rec_id%>% filter(Treatment == "sulpiride"),rec_id ~ Serum_s*Genotype*Trustee)
  668. mod_rec_ser%>% summary()
  669. model_rec %>% summary() %>% coef() %>% as.data.frame()%>% round(3) %>% write.csv("lme_rec_z_treatment_genotype_trustee.csv")
  670. # mistake (incongruent) trials ####
  671. savemodelname = 'brms_incon_logserum_genotype_trustee_c.rds'
  672. if(!file.exists(paste("Behavioral Models/", savemodelname, sep = ""))){
  673. print(paste("estimating model",savemodelname ))
  674. model_incon_serum <- brm(incongruent ~ logserum_s*Genotype*Trustee_c + (Trustee_c|ID),
  675. data = data_sul, family = bernoulli(),
  676. prior = c(set_prior("cauchy(0,2)", class = "sd"),
  677. set_prior("normal(0,3)", class = "b"),
  678. set_prior("lkj(2)", class = "cor")),
  679. warmup = 800, iter = 3000, chains =4,
  680. control = list(adapt_delta = 0.95))
  681. # summary(mc.baseline)
  682. saveRDS(model_incon_serum, file = paste("Behavioral Models/", savemodelname, sep=""))
  683. }else model_incon_serum <-readRDS(file = paste("Behavioral Models/", savemodelname, sep=""))
  684. if (FALSE) {
  685. brms_rec_treatment_genotype_Trustee_c %>% fixef()%>% round(3) %>% write.csv("brms_rec_treatment_genotype_Trustee_c.csv")
  686. brms_rec_logserum_genotype_trustee_c %>% fixef()%>% round(3) %>% write.csv("brms_rec_logserum_genotype_trustee_c.csv")
  687. data_beh$incongruent %>% hist()
  688. model_incon <- glmer(incongruent ~ Treatment*Genotype + (1|ID), data = data_beh%>% filter(!is.na(abs_change)), family = binomial())
  689. model_rec_serum <- glmer(rec ~ logserum_s*Genotype*Trustee_c + (Trustee_c|ID), data = data_serum_rec, family = binomial())
  690. summary(model_rec_serum)
  691. model_incon_serum
  692. post_incon <- posterior_samples(model_incon_serum)
  693. post_incon$b_logserum_s%>% sf(1)
  694. (post_incon$b_logserum_s + post_incon$`b_logserum_s:GenotypeA1M`) %>% sf(1)
  695. # glmer
  696. model_rec_serum <- glmer(rec ~ Serum_s*Genotype*Trustee + (Trustee|ID), data = data_serum_rec, family = binomial())
  697. summary(model_rec_serum)
  698. model_incon_serum <- glmer(incongruent ~ Serum_s*Genotype*Trustee + (1|ID), data = data_serum_rec, family = binomial())
  699. summary(model_incon_serum)
  700. }
  701. ```
  702. ```{r Figure 1}
  703. title_effect_sizes <- ggdraw() +
  704. draw_label(
  705. "Effect sizes (means with 50% and 95% CrI)",
  706. fontface = 'bold',size = 10#,
  707. # x = 0,
  708. # hjust = -0.7
  709. )
  710. # ggdraw() + draw_label("A1- subjects", fontface='bold',size = 13)
  711. g_rtg_blank <- ggplot() + theme_foundation() + theme(panel.background = element_rect(colour = NA),
  712. plot.background = element_rect(colour = NA),
  713. panel.border = element_rect(colour = NA))
  714. g_figure1 <- plot_grid(
  715. plot_grid(g_rtg_blank, g_abs_change_time + theme(plot.margin = unit(c(0.2,0.2,0.2,0.2), "cm")), g_rec_gen +theme(plot.margin = unit(c(0.2,0.2,0.2,0.2), "cm")), nrow = 1, labels="auto"),
  716. plot_grid(g_legend_point_plot3, g_stats+theme(plot.margin = unit(c(0.2,0.2,0.2,0.2), "cm")), g_stats_rec+theme(plot.margin = unit(c(0.2,0.2,0.2,0.2), "cm")), nrow = 1, rel_widths = c(1,1.1,1)),
  717. plot_grid(g_rtg_blank, title_effect_sizes, nrow= 1, rel_widths = c(1,3)),
  718. nrow = 3, rel_heights = c(1,0.4,0.1))
  719. ggsave("g_figure1.pdf", plot = g_figure1, device = "pdf", units = "mm",
  720. scale = 1, width =179 , height = 100, dpi = 600, limitsize = TRUE)
  721. ```
  722. # Computational modelling
  723. ```{r load script for the running the models, echo=FALSE, warning= FALSE, massage = FALSE}
  724. # Warning: this can take time. An already estimated model is available by request from the authors ([email hidden])
  725. source("run_stan_models_wrapper_function.R") # defining the wrapper function
  726. # run the hgf model with gamma in the response model
  727. run_model_fit("Stan_scripts/tg_hgf_gamma.stan", "Model_results/M_tg_hgf_gamma.rds", 3000)
  728. # run the hgf model without gamma in the response model
  729. run_model_fit("Stan_scripts/tg_hgf.stan", "Model_results/M_tg_hgf.rds", 3000)
  730. # run the rw model
  731. run_model_fit("Stan_scripts/tg_rw.stan", "Model_results/M_rw.rds", 3000)
  732. ```
  733. ```{r load stan model stats, echo=FALSE, warning= FALSE, massage = FALSE}
  734. M_tg_hgf_gamma <- readRDS("Model_results/M_tg_hgf_gamma.rds")
  735. data_group$om1 <- get_posterior_mean(M_tg_hgf_gamma, pars=c('om_good'))[,5]
  736. data_group$om2 <- get_posterior_mean(M_tg_hgf_gamma, pars=c('om_bad'))[,5]
  737. data_group$om_mean <- 1/2*(data_group$om1 + data_group$om2)
  738. data_group$om_diff <- data_group$om1 - data_group$om2
  739. data_group$mu0 <- get_posterior_mean(M_tg_hgf_gamma, pars=c('mu0'))[,5]
  740. data_group$noise <- get_posterior_mean(M_tg_hgf_gamma, pars=c('noise'))[,5]
  741. data_group$gam <- get_posterior_mean(M_tg_hgf_gamma, pars=c('gam'))[,5]
  742. # plot parameter posterior distributions ####
  743. # plot effect size distributions
  744. if (TRUE) {
  745. pars_beta <- grep("^beta_", names(M_tg_hgf_gamma), value = T)
  746. pars_sigma <- grep("^sigma", names(M_tg_hgf_gamma), value = T)
  747. pars_mu <- grep("^mu_p", names(M_tg_hgf_gamma), value = T)
  748. pars_beta<- c(pars_beta, pars_sigma, pars_mu)
  749. # pars_all_model <- pars_all_model[!grepl("^beta_pr", pars_all_model)]
  750. Pars_posterior_samples <- extract(M_tg_hgf_gamma, pars = pars_beta )
  751. sigma_volatility = Pars_posterior_samples$`sigma[1]`
  752. sigma_volatility_trustee = Pars_posterior_samples$`sigma[2]`
  753. sigma_noise = Pars_posterior_samples$`sigma[3]`
  754. sigma_gam = Pars_posterior_samples$`sigma[5]`
  755. sigma_mu0 = Pars_posterior_samples$`sigma[4]`
  756. sd_total = sqrt(sigma_volatility^2 + sigma_volatility_trustee^2)
  757. # random_effects_model_wm <- extract(M_tg_hgf_gamma, pars = "r1" )
  758. # M_tg_hgf_gamma %>% View
  759. # are beliefs about bad people more volatile?
  760. ((Pars_posterior_samples$`mu_p[2]` + 1/2*(Pars_posterior_samples$beta_sul_trustee + 1/2*Pars_posterior_samples$beta_sul_ankk_trustee + Pars_posterior_samples$beta_ankk_trustee))/sd_total) %>% sf(1)
  761. # are people initial more trustworthy??
  762. # (beta_mu0 + beta_sul_ankk_mu0*ankk[i])*sulpiride[i]+
  763. # beta_ankk_mu0*ankk[i];
  764. ((Pars_posterior_samples$`mu_p[4]` + 1/2*(Pars_posterior_samples$beta_mu0 + 1/2*Pars_posterior_samples$beta_sul_ankk_mu0 + Pars_posterior_samples$beta_ankk_mu0))/sigma_mu0) %>% sf(1)
  765. ## main effect of sulpiride on belief stability
  766. (Pars_posterior_samples$beta_sul+ 1/2*Pars_posterior_samples$beta_sul_ankk) %>% sf(1)
  767. ( (Pars_posterior_samples$beta_sul+ 1/2*Pars_posterior_samples$beta_sul_ankk)/sd_total ) %>% sf(1)
  768. d_sul = ( (Pars_posterior_samples$beta_sul+ 1/2*Pars_posterior_samples$beta_sul_ankk)/sd_total )
  769. ## main effect of sulpiride on belief stability good trustee
  770. # (Pars_posterior_samples$beta_sul+ 1/2*Pars_posterior_samples$beta_sul_ankk) %>% sf(1)
  771. d_sul_good =( (Pars_posterior_samples$beta_sul+ 1/2*Pars_posterior_samples$beta_sul_trustee + 1/2*(Pars_posterior_samples$beta_sul_ankk +1/2*Pars_posterior_samples$beta_sul_ankk_trustee) )/sd_total )
  772. ## main effect of sulpiride on belief stability bad trustee
  773. # (Pars_posterior_samples$beta_sul+ 1/2*Pars_posterior_samples$beta_sul_ankk) %>% sf(1)
  774. d_sul_bad =( (Pars_posterior_samples$beta_sul - 1/2*Pars_posterior_samples$beta_sul_trustee + 1/2*(Pars_posterior_samples$beta_sul_ankk - 1/2*Pars_posterior_samples$beta_sul_ankk_trustee) )/sd_total )
  775. ## effect of sulpiride on belief stability in A1-
  776. Pars_posterior_samples$beta_sul %>% sf(1)
  777. (Pars_posterior_samples$beta_sul/sd_total) %>% sf(1)
  778. d_sul_a1p = (Pars_posterior_samples$beta_sul/sd_total)
  779. ## effect of sulpiride on belief stability in A1+
  780. (Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk) %>% sf(1)
  781. ( (Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk)/sd_total ) %>% sf(1)
  782. d_sul_a1m = ( (Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk)/sd_total )
  783. ## interaction effect of sulpiride * genotype on belief stability
  784. (Pars_posterior_samples$beta_sul_ankk) %>% sf(1)
  785. ( (Pars_posterior_samples$beta_sul_ankk)/sd_total ) %>% sf(1)
  786. d_sul_gene <- ( (Pars_posterior_samples$beta_sul_ankk)/sd_total )
  787. ## interaction effect of sulpiride on belief stability in A1+ trustees
  788. Pars_posterior_samples$beta_sul_trustee %>% sf(1)
  789. ## effect of sulpiride on belief stability in A1+ for good trustee
  790. (Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_sul_trustee) %>% sf(1)
  791. ((Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_sul_trustee) /sd_total) %>% sf(1)
  792. d_sul_a1p_good = ((Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_sul_trustee) /sd_total)
  793. ## effect of sulpiride on belief stability in A1+ for bad trustee
  794. (Pars_posterior_samples$beta_sul - 1/2*Pars_posterior_samples$beta_sul_trustee) %>% sf(1)
  795. ((Pars_posterior_samples$beta_sul - 1/2*Pars_posterior_samples$beta_sul_trustee)/sd_total) %>% sf(1)
  796. d_sul_a1p_bad = ((Pars_posterior_samples$beta_sul - 1/2*Pars_posterior_samples$beta_sul_trustee) /sd_total)
  797. ## interaction effect of sulpiride on belief stability in A1- trustees
  798. ((Pars_posterior_samples$beta_sul_trustee+ Pars_posterior_samples$beta_sul_ankk_trustee)/sd_total ) %>% sf(1)
  799. ((Pars_posterior_samples$beta_sul_trustee)/sd_total ) %>% sf(1)
  800. ## effect of sulpiride on belief stability in A1- for bad trustee
  801. (Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk - 1/2*(Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee)) %>% sf(1)
  802. d_sul_a1m_bad = ((Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk - 1/2*(Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee))/sd_total )
  803. d_sul_a1m_bad %>% sf(1)
  804. ## effect of sulpiride on belief stability in A1- for good trustee
  805. (Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk + 1/2*(Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee)) %>% sf(1)
  806. d_sul_a1m_good<- ((Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk + 1/2*(Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee))/sd_total )
  807. d_sul_a1m_good%>% sf(1)
  808. ## interaction effect of sulpiride on belief stability in A1+ trustees
  809. (Pars_posterior_samples$beta_sul_trustee) %>% sf(1)
  810. ((Pars_posterior_samples$beta_sul_trustee)/sd_total) %>% sf(1)
  811. d_sul_a1p_trustee=((Pars_posterior_samples$beta_sul_trustee)/sd_total)
  812. (Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee) %>% sf(1)
  813. ## main effect of sulpiride on noise
  814. (Pars_posterior_samples$beta_noise + 1/2*Pars_posterior_samples$beta_sul_ankk_noise) %>% sf(1)
  815. d_eta <- ((Pars_posterior_samples$beta_noise + 1/2*Pars_posterior_samples$beta_sul_ankk_noise)/sigma_noise)
  816. d_eta %>% sf(1)
  817. ## main effect of sulpiride on noise in A1+
  818. Pars_posterior_samples$beta_noise %>% sf(1)
  819. d_eta_a1p <- (Pars_posterior_samples$beta_noise/sigma_noise)
  820. d_eta_a1p %>% sf(1)
  821. ## main effect of sulpiride on noise in A1-
  822. (Pars_posterior_samples$beta_noise + Pars_posterior_samples$beta_sul_ankk_noise) %>% sf(1)
  823. d_eta_a1m <- ((Pars_posterior_samples$beta_noise + Pars_posterior_samples$beta_sul_ankk_noise)/sigma_noise)
  824. d_eta_a1m %>% sf(1)
  825. ## effect of sulpiride on mu0 in A1+
  826. d_mu0_a1p <- Pars_posterior_samples$beta_mu0 /sigma_mu0
  827. d_mu0_a1p %>% sf(1)
  828. # sigma_gamma = Pars_posterior_samples$`sigma[5]`
  829. # (Pars_posterior_samples$beta_gam/sigma_gamma) %>% quantile(probs = c(0.025,0.5,0.975)) %>% round(2)
  830. ## effect of sulpiride on mu0 in a1-
  831. d_mu0_a1m <- (Pars_posterior_samples$beta_mu0 + Pars_posterior_samples$beta_sul_ankk_mu0)/sigma_mu0
  832. d_mu0_a1m %>% sf(1)
  833. ## effect of sulpiride on mu0
  834. d_mu0 <- (Pars_posterior_samples$beta_mu0 + 1/2*Pars_posterior_samples$beta_sul_ankk_mu0)/sigma_mu0
  835. d_mu0 %>% sf(1)
  836. #
  837. ## effect of sulpiride on gamma
  838. (Pars_posterior_samples$beta_gam + 1/2*Pars_posterior_samples$beta_sul_ankk_gam) %>% sf(1)
  839. d_gam <- ((Pars_posterior_samples$beta_gam + 1/2*Pars_posterior_samples$beta_sul_ankk_gam)/sigma_gam)
  840. d_gam %>% sf(1)
  841. ## effect of sulpiride on gamma in A1+
  842. (Pars_posterior_samples$beta_gam + Pars_posterior_samples$beta_sul_ankk_gam) %>% sf(1)
  843. d_gam_a1m<- ((Pars_posterior_samples$beta_gam + Pars_posterior_samples$beta_sul_ankk_gam)/sigma_gam)
  844. d_gam_a1m %>% sf(1)
  845. ## effect of sulpiride on gamma in A1-
  846. (Pars_posterior_samples$beta_gam) %>% sf(1)
  847. d_gam_a1p<- ((Pars_posterior_samples$beta_gam)/sigma_gam)
  848. d_gam_a1p %>% sf(1)
  849. ## interaction effect
  850. d_gam_sul_gene <- (Pars_posterior_samples$beta_sul_ankk_gam)/sigma_gam
  851. d_gam_sul_gene %>% sf(1)
  852. ## effect of genotype on gamma
  853. (1/2*(Pars_posterior_samples$beta_sul_ankk_gam) + Pars_posterior_samples$beta_ankk) %>% sf(1)
  854. (0*(Pars_posterior_samples$beta_sul_ankk_gam) + Pars_posterior_samples$beta_ankk) %>% sf(1)
  855. (1*(Pars_posterior_samples$beta_sul_ankk_gam) + Pars_posterior_samples$beta_ankk) %>% sf(1)
  856. d_gam <- ((Pars_posterior_samples$beta_gam + 1/2*Pars_posterior_samples$beta_sul_ankk_gam)/sigma_gam)
  857. d_gam %>% sf(1)
  858. ## effect of genotype in controls on volatility
  859. (Pars_posterior_samples$beta_ankk) %>% quantile(probs = c(0.025,0.5,0.975)) %>% round(2)
  860. ## effect of genotype in controls on mu0
  861. (Pars_posterior_samples$beta_ankk_mu0) %>% quantile(probs = c(0.025,0.5,0.975)) %>% round(2)
  862. ## effect of genotype in controls on noise
  863. (Pars_posterior_samples$beta_ankk_noise) %>% quantile(probs = c(0.025,0.5,0.975)) %>% round(2)
  864. ## effect of genotype in controls on gamma
  865. (Pars_posterior_samples$beta_ankk_gam) %>% quantile(probs = c(0.025,0.5,0.975)) %>% round(2)
  866. data_group$ankk %>% glimpse()
  867. ## effect of gen drug interaction on initial trust
  868. ## interaction effect
  869. d_mu0_sul_gene <- (Pars_posterior_samples$beta_sul_ankk_mu0)/sigma_mu0
  870. d_mu0_sul_gene %>% sf(1)
  871. }
  872. CI_outer = 0.95; # 99 CrI
  873. g_stats_om_ankk <- bind_cols(c_d_sul = d_sul,
  874. b_d_sul_a1p = d_sul_a1p,
  875. a_d_sul_a1m = d_sul_a1m) %>%
  876. # convert them to the long format, group, and get the posterior summaries
  877. pivot_longer(everything()) %>%
  878. group_by(name) %>%
  879. summarise(mean = mean(value),
  880. ll = quantile(value, prob = (1-CI_outer)/2),
  881. ul = quantile(value, prob = 1- (1-CI_outer)/2),
  882. lls = quantile(value, prob = .25),
  883. uls = quantile(value, prob = .75)) %>%
  884. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  885. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  886. geom_vline(xintercept = 0, linetype = "dashed") +
  887. geom_pointrange(color = "firebrick") +
  888. labs( y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  889. theme_Publication(base_size = 10) +
  890. theme(panel.grid = element_blank(),
  891. axis.text.x = element_text(size=10),
  892. strip.background = element_rect(fill = "transparent", color = "transparent"),
  893. axis.title.x = element_blank()) +
  894. scale_y_discrete(labels = rev(c("S - P", "S - P in A1+", "S - P in A1-")) )
  895. # plot_grid(g_abs_change_time + theme(legend.position = "none"), g_stats, nrow = 2, rel_heights = c(1,.3)
  896. g_stats_om1_ankk <- bind_cols(c_d_sul_good = d_sul_good,
  897. b_d_sul_a1p_good = d_sul_a1p_good,
  898. a_d_sul_a1m_good = d_sul_a1m_good) %>%
  899. # convert them to the long format, group, and get the posterior summaries
  900. pivot_longer(everything()) %>%
  901. group_by(name) %>%
  902. summarise(mean = mean(value),
  903. ll = quantile(value, prob = (1-CI_outer)/2),
  904. ul = quantile(value, prob = 1- (1-CI_outer)/2),
  905. lls = quantile(value, prob = .25),
  906. uls = quantile(value, prob = .75)) %>%
  907. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  908. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  909. geom_vline(xintercept = 0, linetype = "dashed") +
  910. geom_pointrange(color = "firebrick") +
  911. labs( y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  912. theme_Publication(base_size = 10) +
  913. theme(panel.grid = element_blank(),
  914. axis.text.x = element_text(size=10),
  915. strip.background = element_rect(fill = "transparent", color = "transparent"),
  916. axis.title.x = element_blank()) +
  917. scale_y_discrete(labels = rev(c("S - P in vs good T", "S - P in A1+ vs good T", "S - P in A1- vs good T")))
  918. g_stats_om2_ankk <- bind_cols(c_d_sul_bad = d_sul_bad,
  919. b_d_sul_a1p_bad = d_sul_a1p_bad,
  920. a_d_sul_a1m_bad = d_sul_a1m_bad) %>%
  921. # convert them to the long format, group, and get the posterior summaries
  922. pivot_longer(everything()) %>%
  923. group_by(name) %>%
  924. summarise(mean = mean(value),
  925. ll = quantile(value, prob = (1-CI_outer)/2),
  926. ul = quantile(value, prob = 1- (1-CI_outer)/2),
  927. lls = quantile(value, prob = .25),
  928. uls = quantile(value, prob = .75)) %>%
  929. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  930. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  931. geom_vline(xintercept = 0, linetype = "dashed") +
  932. geom_pointrange(color = "firebrick") +
  933. labs( y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  934. theme_Publication(base_size = 10) +
  935. theme(panel.grid = element_blank(),
  936. axis.text.x = element_text(size=10),
  937. strip.background = element_rect(fill = "transparent", color = "transparent"),
  938. axis.title.x = element_blank()) +
  939. scale_y_discrete(labels = rev(c("S - P in vs bad T", "S - P in A1+ vs bad T", "S - P in A1- vs bad T")))
  940. # plot_grid(g_abs_change_time + theme(legend.position = "none"), g_stats, nrow = 2, rel_heights = c(1,.3)
  941. g_stats_eta_ankk <- bind_cols(c = d_eta,
  942. b = d_eta_a1p,
  943. a = d_eta_a1m) %>%
  944. # convert them to the long format, group, and get the posterior summaries
  945. pivot_longer(everything()) %>%
  946. group_by(name) %>%
  947. summarise(mean = mean(value),
  948. ll = quantile(value, prob = (1-CI_outer)/2),
  949. ul = quantile(value, prob = 1- (1-CI_outer)/2),
  950. lls = quantile(value, prob = .25),
  951. uls = quantile(value, prob = .75)) %>%
  952. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  953. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  954. geom_vline(xintercept = 0, linetype = "dashed") +
  955. geom_pointrange(color = "firebrick") +
  956. labs( y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  957. theme_Publication(base_size = 10) +
  958. theme(panel.grid = element_blank(),
  959. axis.text.x = element_text(size=10),
  960. strip.background = element_rect(fill = "transparent", color = "transparent"),
  961. axis.title.x = element_blank()) +
  962. scale_y_discrete(labels = rev(c("S - P", "S - P in A1+", "S - P in A1-")) )
  963. # plot_grid(g_abs_change_time + theme(legend.position = "none"), g_stats, nrow = 2, rel_heights = c(1,.3)
  964. g_stats_gam_ankk <- bind_cols(c = d_gam,
  965. b = d_gam_a1p,
  966. a = d_gam_a1m) %>%
  967. # convert them to the long format, group, and get the posterior summaries
  968. pivot_longer(everything()) %>%
  969. group_by(name) %>%
  970. summarise(mean = mean(value),
  971. ll = quantile(value, prob = (1-CI_outer)/2),
  972. ul = quantile(value, prob = 1- (1-CI_outer)/2),
  973. lls = quantile(value, prob = .25),
  974. uls = quantile(value, prob = .75)) %>%
  975. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  976. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  977. geom_vline(xintercept = 0, linetype = "dashed") +
  978. geom_pointrange(color = "firebrick") +
  979. labs( y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  980. theme_Publication(base_size = 10) +
  981. theme(panel.grid = element_blank(),
  982. axis.text.x = element_text(size=10),
  983. strip.background = element_rect(fill = "transparent", color = "transparent"),
  984. axis.title.x = element_blank()) +
  985. scale_x_continuous(breaks = c(0,-1,-2))+
  986. scale_y_discrete(labels = rev(c("S - P", "S - P in A1+", "S - P in A1-")) )
  987. g_stats_mu0_ankk <- bind_cols(c = d_mu0,
  988. b = d_mu0_a1p,
  989. a = d_mu0_a1m) %>%
  990. # convert them to the long format, group, and get the posterior summaries
  991. pivot_longer(everything()) %>%
  992. group_by(name) %>%
  993. summarise(mean = mean(value),
  994. ll = quantile(value, prob = (1-CI_outer)/2),
  995. ul = quantile(value, prob = 1- (1-CI_outer)/2),
  996. lls = quantile(value, prob = .25),
  997. uls = quantile(value, prob = .75)) %>%
  998. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  999. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  1000. geom_vline(xintercept = 0, linetype = "dashed") +
  1001. geom_pointrange(color = "firebrick") +
  1002. labs( y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  1003. theme_Publication(base_size = 10) +
  1004. theme(panel.grid = element_blank(),
  1005. axis.text.x = element_text(size=10),
  1006. strip.background = element_rect(fill = "transparent", color = "transparent"),
  1007. axis.title.x = element_blank()) +
  1008. scale_y_discrete(labels = rev(c("S - P", "S - P in A1+", "S - P in A1-")) )
  1009. # plot_grid(g_abs_change_time + theme(legend.position = "none"), g_stats, nrow = 2, rel_heights = c(1,.3)
  1010. ```
  1011. # Plot group level results from the winning model
  1012. ```{r free parameter graphs, fig.width = 15, fig.height = 7, echo=FALSE, warning= FALSE}
  1013. g_gen_om_mean <- ggplot(data = data_group, aes(x = drug, y = om_mean))+ # group = ID, linetype = Genotype))
  1014. # geom_violin(aes(fill = drug))+
  1015. geom_boxplot(aes(fill = drug), width=0.5, color="black", outlier.colour = NA)+
  1016. # stat_summary(fun.y=mean, geom="point", shape=20, size=14, color="red", fill="red") +
  1017. geom_point(aes(fill = drug, colour = drug), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1)+
  1018. theme_Publication() +
  1019. theme(axis.ticks.x = element_blank(),
  1020. axis.text.x = element_blank(),
  1021. panel.grid.major = element_blank(),
  1022. legend.position = "none") +
  1023. ylab(expression(paste("Belief volatility - ", "\U1D714"))) + # ylab(expression("\U1D714"[good])) +
  1024. xlab("")+ discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462")))
  1025. # df.sigplot = data.frame(x = c("Betray", "Betray"),
  1026. # xend = c("Equalize", "Betray"),
  1027. # fit_ txt = c("*", ""),
  1028. # x_pt1 = c("Betray", NA),
  1029. # x_pt2 = c("Equalize", NA),
  1030. # y_pt = c(1.4 , NA),
  1031. # Genotype = model_pp_change$Genotype%>% unique() )
  1032. #
  1033. # g_change_gen <- g_change_gen + geom_segment(data = df.sigplot, aes(x = x, y = 1.5, xend = xend, yend = 1.5)) +
  1034. # geom_text(data = df.sigplot, aes(label = txt), x = 1.5, y = 1.6, size = 10) +
  1035. # geom_point(data = df.sigplot,aes(x = x_pt1, y = y_pt), shape = 17, size = 3 ) +
  1036. # geom_point(data = df.sigplot,aes(x = x_pt2, y = y_pt), shape = 17, size = 3 )
  1037. g_gen_noise <- ggplot(data = data_group, aes(x = drug, y = noise))+ # group = ID, linetype = Genotype))
  1038. # geom_violin(aes(fill = drug))+
  1039. geom_boxplot(aes(fill = drug), width=0.5, color="black", outlier.colour = NA)+
  1040. # stat_summary(fun.y=mean, geom="point", shape=20, size=14, color="red", fill="red") +
  1041. geom_point(aes(fill = drug, colour = drug), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1)+
  1042. theme_Publication() +
  1043. theme(axis.text.x = element_blank(),
  1044. axis.ticks.x = element_blank(),
  1045. panel.grid.major = element_blank(),
  1046. legend.position = "none") +
  1047. ylab("\U1D702") + xlab("")+ discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462")))
  1048. g_gen_noise_a1p <- ggplot(data = data_group %>% filter(ankk == "A1+"), aes(x = drug, y = noise))+ # group = ID, linetype = Genotype))
  1049. # geom_violin(aes(fill = drug))+
  1050. geom_boxplot(aes(fill = drug), width=0.5, color="black")+
  1051. geom_point(aes(fill = drug, colour = drug), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1)+
  1052. theme_Publication() +
  1053. theme(axis.text.x = element_blank(),
  1054. axis.ticks.x = element_blank(),
  1055. panel.grid.major = element_blank(),
  1056. legend.position = "none") +
  1057. ylab("\U1D702") + xlab("")+ discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462"))) + facet_wrap(~ankk)
  1058. g_gen_mu0 <- ggplot(data = data_group, aes(x = drug, y = mu0))+ # group = ID, linetype = Genotype))
  1059. # geom_violin(aes(fill = drug))+
  1060. geom_boxplot(aes(fill = drug), width=0.5, color="black", outlier.colour = NA)+
  1061. geom_point(aes(fill = drug, colour = drug), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1)+
  1062. theme_Publication() +
  1063. theme(axis.text.x = element_blank(),
  1064. axis.ticks.x = element_blank(),
  1065. panel.grid.major = element_blank(),
  1066. legend.position = "none") +
  1067. ylab(expression(bold("\U1D707"[0]))) + xlab("")+ discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462"))) + facet_wrap(~ankk)
  1068. g_gen_gam <- ggplot(data = data_group, aes(x = drug, y = log(gam)))+ # group = ID, linetype = Genotype))
  1069. # geom_violin(aes(fill = drug))+
  1070. geom_boxplot(aes(fill = drug), width=0.5, color="black", outlier.colour = NA)+
  1071. geom_point(aes(fill = drug, colour = drug), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 1, stroke =0.5 )+
  1072. theme_Publication() +
  1073. theme(axis.text.x = element_blank(),
  1074. axis.ticks.x = element_blank(),
  1075. axis.title.x = element_blank(),
  1076. panel.grid.major = element_blank(),
  1077. legend.position = "none") +
  1078. ylab("Choice Precision - \U1D6FE'") + discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462")))
  1079. g_gen_gam_a1p <- ggplot(data = data_group %>% filter(ankk == "A1+"), aes(x = drug, y = log(gam)))+ # group = ID, linetype = Genotype))
  1080. # geom_violin(aes(fill = drug))+
  1081. geom_boxplot(aes(fill = drug), width=0.5, color="black")+
  1082. geom_point(aes(fill = drug, colour = drug), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1)+
  1083. theme_Publication() +
  1084. theme(axis.text.x = element_blank(),
  1085. axis.ticks.x = element_blank(),
  1086. panel.grid.major = element_blank(),
  1087. legend.position = "none") +
  1088. ylab("\U1D6FE'") + xlab("")+ discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462"))) + facet_wrap(~ankk)
  1089. ```
  1090. # good vs bad trustee plots
  1091. ```{r}
  1092. g_gen_om1 <- data_group %>% ggplot(aes(x = drug, y = om1))+ # group = ID, linetype = Genotype))
  1093. # geom_violin(aes(fill = drug))+
  1094. geom_boxplot(aes(fill = drug), width=0.5, color="black", outlier.colour = NA)+
  1095. # stat_summary(fun.y=mean, geom="point", shape=20, size=14, color="red", fill="red") +
  1096. geom_point(aes(fill = drug, colour = drug), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1)+
  1097. theme_Publication() +
  1098. theme(axis.ticks.x = element_blank(),
  1099. axis.text.x = element_blank(),
  1100. panel.grid.major = element_blank(),
  1101. legend.position = "none") +
  1102. ylab(expression("\U1D714"[good])) +
  1103. xlab("")+ discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462")))+ facet_wrap(~ankk)
  1104. # g_gen_om1
  1105. g_gen_om2 <- data_group %>% ggplot(aes(x = drug, y = om2))+ # group = ID, linetype = Genotype))
  1106. # geom_violin(aes(fill = drug))+
  1107. geom_boxplot(aes(fill = drug), width=0.5, color="black", outlier.colour = NA)+
  1108. # stat_summary(fun.y=mean, geom="point", shape=20, size=14, color="red", fill="red") +
  1109. geom_point(aes(fill = drug, colour = drug), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1)+
  1110. theme_Publication() +
  1111. theme(axis.text.x = element_blank(),
  1112. axis.ticks.x = element_blank(),
  1113. panel.grid.major = element_blank(),
  1114. legend.position = "none")+
  1115. ylab(expression("\U1D714"[bad])) +
  1116. xlab("")+ discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462")))+ facet_wrap(~ankk)
  1117. title <- ggdraw() +
  1118. draw_label(
  1119. "Effect sizes (means with 50% and 95% CrI)",
  1120. fontface = 'bold' )
  1121. g_suppfig_om_trustee = plot_grid(
  1122. plot_grid(
  1123. g_gen_mu0 + theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")),
  1124. g_gen_om1 + theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")),
  1125. g_gen_om2 + theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")),
  1126. rel_widths = c(1,1,1), nrow = 1, labels = c("a", "b", "c")),
  1127. g_legend_point_plot,
  1128. plot_grid(g_stats_mu0_ankk + theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")),
  1129. g_stats_om1_ankk + theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")),
  1130. g_stats_om2_ankk+ theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")), rel_widths = c(1,1,1), nrow = 1),
  1131. title, ncol = 1, rel_heights = c(1,0.2,0.4,0.1))
  1132. g_suppfig_om_trustee
  1133. ggsave("g_suppfig_om_trustee.pdf", plot = g_suppfig_om_trustee, device = cairo_pdf, units = "mm",
  1134. width =179 , height = 80, dpi = 600)
  1135. ggsave("g_suppfig_om_trustee.png", plot = g_suppfig_om_trustee, device = "png", units = "mm",
  1136. width =179 , height = 80, dpi = 600)
  1137. ```
  1138. # choice uncertainty plots
  1139. ```{r plot gam}
  1140. data_group <- data_group %>%
  1141. group_by(drug,ankk) %>%
  1142. mutate(N = length(gam),
  1143. mean_gam = mean(gam),
  1144. se_gam = sd(gam)/sqrt(N),
  1145. mean_eta = mean(noise),
  1146. se_eta =sd(noise)/sqrt(N)) %>% ungroup()
  1147. data_all <- merge(data_beh, data_group, by = "ID")
  1148. data_all <- data_all %>%
  1149. mutate(seq01 = round(0.95*(Trial-1)/24,2)+ as.numeric(Trustee == "Good")*0.02,
  1150. seq01_pw =round(pw(seq01, gam),2),
  1151. seq01_pw2 =round(pw(seq01, mean_gam),2),
  1152. seq01_pw2_low =round(pw(seq01, mean_gam-se_gam),2),
  1153. seq01_pw2_up =round(pw(seq01, mean_gam+se_gam),2))
  1154. data_gam_sum <- data_all %>% group_by(Treatment, Genotype, seq01) %>% summarize(N=n(),
  1155. mean_seq01_pw = mean(seq01_pw),
  1156. se_seq01_pw = sd(seq01_pw)/sqrt(N)) %>% as_tibble()
  1157. data_all %>% glimpse()
  1158. # filter(Genotype == "A1-") %>%
  1159. g_gam_pw <- ggplot(data_all, aes(x = seq01, y = seq01_pw)) +
  1160. geom_line(aes(group = gam, colour = Treatment), alpha = 0.5, size =0.3) +
  1161. geom_line(data = data_gam_sum, aes(x =seq01, y = mean_seq01_pw, colour = Treatment), size =1)+
  1162. theme_Publication() +
  1163. theme(legend.position = "none")+
  1164. scale_colour_Publication() +
  1165. scale_x_continuous(breaks = c(0,0.5,1))+
  1166. scale_y_continuous(breaks = c(0,0.5,1))+
  1167. xlab("Probability of\npositive BT") + ylab("Probability weight")+
  1168. facet_wrap(~Genotype, nrow =2)
  1169. g_gam_pw
  1170. prop_no = 25
  1171. g_gam_ridge <-data_beh %>% mutate(Trial_bin = ceiling(Trial/prop_no)*prop_no )%>% filter(Trial_bin!=27) %>%
  1172. ggplot() +
  1173. geom_density_ridges(aes( x = Investment, y = as.factor(Trial_bin) ,fill = Treatment, height = ..density..), alpha = 0.5 ) +
  1174. theme_Publication() + scale_fill_Publication() +
  1175. theme(legend.position = "none",axis.text.y = element_blank(), axis.ticks.y = element_blank(), axis.title.x = element_text(size = 10)) + #,
  1176. ylab("") + xlab("Investment\ndistributions") + scale_x_continuous(breaks = c(0,5,10)) + coord_cartesian(xlim = c(0,10)) + ylab("") + scale_y_discrete(expand = c(0, 0)) + facet_wrap(~Genotype, nrow =2)
  1177. g_modelling_gamma <- plot_grid(
  1178. plot_grid(
  1179. plot_grid(
  1180. g_gen_gam + facet_wrap(~ankk)+theme(plot.margin = unit(c(0.2,0.2, 0, 1), "cm")), g_incon_gen + theme(plot.margin = unit(c(0.2, 0.2, 0, 0.2), "cm")),
  1181. g_stats_gam_ankk+ theme(plot.margin = unit(c(0.2, 0.2, 0, 0.2), "cm")), g_stats_incon+ theme(plot.margin = unit(c(0.2, 0.2, 0, 0.2), "cm")),
  1182. ncol = 2, rel_heights = c(1,0.5), rel_widths = c(0.9,1), labels = c("a", "b")),
  1183. g_gam_pw, g_gam_ridge,
  1184. nrow =1, rel_widths = c(1.3,0.6,0.5) ,labels = c("", "c", "d")),
  1185. plot_grid(title_effect_sizes, g_legend_point_plot, nrow = 1),
  1186. ncol = 1, rel_heights = c(1,0.1))
  1187. ggsave("g_modelling_gamma.pdf", plot = g_modelling_gamma, device = cairo_pdf, units = "mm",
  1188. width =179 , height = 80, dpi = 600)
  1189. ggsave("g_modelling_gamma.png", plot = g_modelling_gamma, device = "png", units = "mm",
  1190. width =179 , height = 80, dpi = 600)
  1191. ```
  1192. # rec and incongruent with serum and computational parameters -----
  1193. ```{r with reciprocity}
  1194. if (FALSE) {
  1195. data_group_new <- data_group %>% select(-N) %>% left_join(data_rec_id, group_by = "ID")
  1196. data_group_new <- data_group_new %>% mutate(
  1197. # rec_id_s = ave(rec_id,FUN =scale),
  1198. # rec_id_sig = ave(logit(rec_id),FUN =scale),
  1199. # incon_id_s = ave(incon_id,FUN =scale),
  1200. # incon_id_sig = ave(logit(incon_id+0.1),FUN =scale),
  1201. noise_s = ave(noise,FUN =scale) ,
  1202. om_s = ave(om_mean,FUN =scale) ,
  1203. loggam_s = ave(log(gam),FUN =scale) ,
  1204. mu0_s = ave(mu0,FUN =scale)
  1205. )
  1206. data_beh_group <- merge(data_group_new%>% select(ID, noise_s : mu0_s), data_beh, by = "ID")
  1207. saveRDS(data_beh_group, file ="data_beh_group.rds")
  1208. } else data_beh_group <- readRDS(file ="data_beh_group.rds")
  1209. # data_group %>%
  1210. # ggplot(aes(x=om_mean, y = log(gam), colour = drug)) +
  1211. # geom_point() + theme_Publication() + scale_fill_Publication() + scale_colour_Publication() + facet_wrap(~ankk)
  1212. #
  1213. # data_beh_group <- data_beh_group %>% mutate(extreme_trials = (Investment == 10|Investment ==0))
  1214. #
  1215. ttl_size = 10
  1216. g_om_rec <- data_group_new %>%
  1217. ggplot(aes(x=om_mean, y = rec_id)) +
  1218. geom_smooth(method= "lm", colour = "black", se = FALSE)+
  1219. geom_point(alpha = 0.5) + theme_Publication() +
  1220. theme(axis.ticks.x = element_blank(),
  1221. axis.text.x = element_blank(),
  1222. axis.title.y = element_text(size = 10),
  1223. panel.grid.major = element_blank(),
  1224. legend.position = "none",
  1225. plot.title = element_text(size = ttl_size)) +
  1226. scale_fill_Publication() + scale_colour_Publication()+
  1227. ylab("Reciprocal Trials") +
  1228. xlab("\U1D714")
  1229. g_gam_incon <- data_group_new %>%
  1230. ggplot(aes(x=log(gam), y = incon_id)) +
  1231. geom_smooth(method= "lm", colour = "black", se = FALSE)+
  1232. geom_point(alpha = 0.5) + theme_Publication() +
  1233. theme(axis.ticks.x = element_blank(),
  1234. axis.text.x = element_blank(),
  1235. axis.title.y = element_text(size = 10),
  1236. panel.grid.major = element_blank(),
  1237. legend.position = "none",
  1238. plot.title = element_text(size = ttl_size)) +
  1239. scale_fill_Publication() + scale_colour_Publication()+
  1240. ylab("Mistake Trials") +
  1241. xlab("\U1D6FE'")
  1242. # labs(title = paste("r = ", round(cor.test(log(data_group_new$gam),data_group_new$rec_id)[["estimate"]],2), sep=""))
  1243. g_model_beh <- plot_grid(g_om_rec, g_gam_incon, nrow = 1)
  1244. ```
  1245. ```{r stats for the above, for the supplementry }
  1246. savemodelname = 'brms_rec_comp_par.rds'
  1247. if(!file.exists(paste("Behavioral Models/", savemodelname, sep = ""))){
  1248. print(paste("estimating model",savemodelname ))
  1249. brms_rec_comp_par <- brm(rec ~ om_s + loggam_s + noise_s + mu0_s + (1|ID),
  1250. data = data_beh_group, family = bernoulli(),
  1251. prior = c(set_prior("cauchy(0,2)", class = "sd"),
  1252. set_prior("normal(0,3)", class = "b")),
  1253. warmup = 800, iter = 3000, chains =4,
  1254. control = list(adapt_delta = 0.95))
  1255. # summary(mc.baseline)
  1256. saveRDS(mc.rec.model, file = paste("Behavioral Models/", savemodelname, sep=""))
  1257. }else brms_rec_comp_par <- readRDS("Behavioral Models/brms_rec_comp_par.rds")
  1258. brms_rec_comp_par %>% fixef()%>% round(3) %>% write.csv("brms_rec_comp_par.csv")
  1259. savemodelname = 'brms_incon_comp_par.rds'
  1260. if(!file.exists(paste("Behavioral Models/", savemodelname, sep = ""))){
  1261. print(paste("estimating model",savemodelname ))
  1262. mc.incon.model <- brm(incongruent ~ om_s + loggam_s + noise_s + mu0_s + (1|ID),
  1263. data = data_beh_group, family = bernoulli(),
  1264. prior = c(set_prior("cauchy(0,2)", class = "sd"),
  1265. set_prior("normal(0,3)", class = "b")),
  1266. warmup = 800, iter = 3000, chains =4,
  1267. control = list(adapt_delta = 0.95))
  1268. # summary(mc.baseline)
  1269. saveRDS(mc.incon.model, file = paste("Behavioral Models/", savemodelname, sep=""))
  1270. } else brms_incon_comp_par <- readRDS("Behavioral Models/brms_incon_comp_par.rds")
  1271. brms_incon_comp_par %>% fixef()%>% round(3) %>% write.csv("brms_incon_comp_par.csv")
  1272. mod1 <- glmer(incongruent ~ loggam_s + (1|ID), family = binomial(), data = data_beh_group)
  1273. mod1 %>% summary() %>% coef() %>% as.data.frame()%>% round(3) %>% write.csv("lme_incon_comp_par.csv")
  1274. mod2 <- glmer(rec ~ om_s + loggam_s + noise_s + mu0_s + (1|ID), family = binomial(), data = data_beh_group )
  1275. mod2 %>% summary() %>% coef() %>% as.data.frame()%>% round(3) %>% write.csv("lme_rec_comp_par.csv")
  1276. mod2%>% fixef()%>% round(3)
  1277. ```
  1278. # parameter retrieval ----------------
  1279. ```{r, echo=FALSE, warning= FALSE, fig.width = 12}
  1280. # run the parameter retrieval script (this will take some time!)
  1281. if (FALSE) source("refit_model.r")
  1282. savedataset = "Refit_lkj_hgf_pw"
  1283. drf_temp <- readRDS(paste(savedataset, "_pars_all.rds", sep=""))
  1284. drf_temp$om_mean <- 1/2*(drf_temp$om_good +drf_temp$om_bad)
  1285. drf_temp$om_mean_rf <- 1/2*(drf_temp$om_good_rf +drf_temp$om_bad_rf)
  1286. drf_temp$om_diff <- drf_temp$om_good - drf_temp$om_bad
  1287. # drf_temp$om_diff_rf <- drf_temp$om_good_rf -drf_temp$om_bad_rf
  1288. # cor.test(drf_temp$om_diff,drf_temp$om_diff_rf)
  1289. ttl_size = 15
  1290. g_rf_om_mean<- ggplot(data =drf_temp, aes(x= om_mean, y = om_mean_rf)) +
  1291. geom_point(alpha = 0.5)+
  1292. geom_abline(slope = 1) +
  1293. # geom_line(data = data.frame(x = c(min(drf_temp-6,1), y = c(-6,1)), aes(x=x, y= y))+
  1294. # geom_smooth(method = "lm", se = FALSE, colour = "black") + # se = "FALSE")
  1295. # coord_cartesian(xlim = c(-8,0), ylim = c(-8,0)) +
  1296. theme_Publication() +
  1297. theme(axis.ticks = element_blank(),
  1298. axis.text = element_blank(),
  1299. panel.grid.major = element_blank(),
  1300. legend.position = "none",
  1301. plot.title = element_text(size = ttl_size)) + ylab("") +xlab("\U1D714") + #ylab("\U1D714 (refitted)") +
  1302. labs(title = paste("r = ", round(cor.test(drf_temp$om_mean,drf_temp$om_mean_rf)[["estimate"]],2), sep=""))
  1303. # geom_text(data = data.frame(txt = paste("r = ", round(cor.test(drf_temp$om_mean,drf_temp$om_mean_rf)[["estimate"]],2), sep="") ), aes(label = txt), x = -5, y = 0, size = 8)
  1304. # labs(title=paste("r = ", round(cor.test(drf_temp$om_mean,drf_temp$om_mean_rf)[["estimate"]],2), sep=""))
  1305. # \U1D702 "\U1D707" \U1D6FE
  1306. g_rf_noise<- ggplot(data =drf_temp, aes(x= noise, y = noise_rf)) +
  1307. geom_point(alpha = 0.5)+
  1308. geom_abline(slope = 1) +
  1309. # geom_smooth(method = "lm", se = FALSE, colour = "black") + # se = "FALSE")
  1310. # coord_cartesian(xlim = c(-8,0), ylim = c(-8,0)) +
  1311. theme_Publication() +
  1312. theme(axis.ticks = element_blank(), axis.text = element_blank(),
  1313. panel.grid.major = element_blank(),
  1314. legend.position = "none",
  1315. plot.title = element_text(size = ttl_size)) + ylab("") + xlab("\U1D702") + # ylab("\U1D702 (refitted)")
  1316. # coord_fixed() +
  1317. labs(title = paste("r = ", round(cor.test(drf_temp$noise,drf_temp$noise_rf)[["estimate"]],2), sep="") )
  1318. g_rf_mu0<- ggplot(data =drf_temp, aes(x= mu0, y = mu0_rf)) +
  1319. geom_point(alpha = 0.5)+
  1320. geom_abline(slope = 1) +
  1321. # geom_smooth(method = "lm", se = FALSE, colour = "black") + # se = "FALSE")
  1322. # coord_cartesian(xlim = c(-8,0), ylim = c(-8,0)) +
  1323. theme_Publication() +
  1324. theme(axis.ticks = element_blank(),
  1325. axis.text = element_blank(),
  1326. panel.grid.major = element_blank(),
  1327. legend.position = "none",
  1328. plot.title = element_text(size = ttl_size)) + ylab("") + xlab(expression(bold("\U1D707"[0])))+
  1329. labs(title = paste("r = ", round(cor.test(drf_temp$mu0,drf_temp$mu0_rf)[["estimate"]],2), sep="") )
  1330. g_rf_loggam<- ggplot(data =drf_temp, aes(x= loggam, y = loggam_rf)) +
  1331. geom_point(alpha = 0.5)+
  1332. geom_abline(slope = 1) +
  1333. # geom_smooth(method = "lm", se = FALSE, colour = "black") + # se = "FALSE")
  1334. # coord_cartesian(xlim = c(-8,0), ylim = c(-8,0)) +
  1335. theme_Publication() +
  1336. theme(axis.ticks = element_blank(),
  1337. axis.text = element_blank(),
  1338. panel.grid.major = element_blank(),
  1339. legend.position = "none",
  1340. plot.title = element_text(size = ttl_size)) + ylab("") + xlab("\U1D6FE'") + #ylab("\U1D6FE' (refitted)")
  1341. labs(title = paste("r = ",round(cor.test(drf_temp$loggam,drf_temp$loggam_rf)[["estimate"]],2), sep=""))
  1342. # geom_text(data = data.frame(txt = paste("r = ",round(cor.test(drf_temp$loggam,drf_temp$loggam_rf)[["estimate"]],2), sep="") ), aes(label = txt),x = -2, y = 2, size = 8)
  1343. g_rf <- plot_grid(g_rf_om_mean, g_rf_loggam, g_rf_noise, g_rf_mu0, nrow = 1) #, ncol = 2)
  1344. ```
  1345. # Model comparison
  1346. ```{r compare stan models}
  1347. # stan model compare models -------------------
  1348. if (FALSE) {
  1349. M_tg_hgf_ka<- readRDS("Model_results/M_hgf_ka.rds")
  1350. M_rw <- readRDS("Model_results/M_rw.rds")
  1351. loo.M_tg_hgf_gamma <- loo::loo(M_tg_hgf_gamma)
  1352. loo.M_tg_hgf_ka<- loo::loo(M_tg_hgf_ka)
  1353. loo.M_rw <- loo::loo(M_rw)
  1354. cdata <- loo_compare(loo.M_tg_hgf_gamma, loo.M_tg_hgf_ka, loo.M_rw)
  1355. cData <- as.data.frame(cdata)
  1356. saveRDS(cData,file = "Model_comparison_single_pt.rds")
  1357. }
  1358. cData <-readRDS(file = "Model_comparison_single_pt.rds")
  1359. cData %>% glimpse()
  1360. g_compare_models <- ggplot(cData, aes(x = model, y = elpd_diff)) +
  1361. geom_errorbar(aes(ymin= elpd_diff - se_diff, ymax = elpd_diff+se_diff), width = 0.2, position = position_dodge(0.9)) + theme_Publication() +
  1362. geom_bar(position = position_dodge(), stat = "identity") + scale_x_discrete(name="", limits = c("HGF + ɣ", "HGF", "RW"), labels = c("HGF M1\n(with \U1D6FE)", "HGF M2\n(with \U1D705)", "RW")) +
  1363. ylab("Comparing expected\nlog predictive density")
  1364. g_compare_models
  1365. df1 <- readRDS(file = "Model_comparison_across_trials2.rds")
  1366. df1 %>% filter(type %in% c("loglik_rw", "loglik_hgf")) %>% ggplot(aes(x=trials, y = looic, group = type, colour = type)) +
  1367. geom_point(stat = "identity") +
  1368. geom_ribbon(aes(ymin = looic -se, ymax = looic + se, fill = type), alpha = 0.2) +
  1369. theme_Publication() + facet_wrap(~trustee)
  1370. # df1 <- readRDS(file = "Model_comparison_across_trials.rds")
  1371. #
  1372. g_compare_models_trials <- df1 %>% filter(type %in% c("loglik_rw", "loglik_hgf")) %>% mutate(type2 = factor(type, labels = c("HGF M1", "RW") ) ) %>% ggplot(aes(x=trials, y = looic, group = type2)) +
  1373. geom_smooth(aes(colour = type2), se = F)+
  1374. # geom_smooth(aes(y =looic -se, colour = type), linetype= "dashed", se = F)+
  1375. # geom_smooth(aes(y =looic +se, colour = type), linetype= "dashed", se = F)+
  1376. # geom_smooth(aes(colour = type), se = F)+
  1377. # geom_ribbon(aes(ymin = looic -se, ymax = looic + se, fill = type), alpha = 0.2) +
  1378. theme_Publication() + theme(legend.title = element_blank()) + facet_wrap(~trustee) + xlab("Trials") +ylab("LOOIC")+
  1379. discrete_scale("colour","Publication",manual_pal(values = c("#9c6a5a","#4e767e")))
  1380. ```
  1381. # Plot figure 2
  1382. ```{r prepare for figure 2}
  1383. g_blank <- ggplot() + theme_foundation() + theme(panel.background = element_rect(colour = NA),
  1384. plot.background = element_rect(colour = NA),
  1385. panel.border = element_rect(colour = NA))
  1386. model_com_title <- ggdraw() +
  1387. draw_label(
  1388. "Correlation with behavior")
  1389. g_example = readRDS( file = "example2.rds")
  1390. # g_model_comp_blank <- plot_grid(model_com_title, g_rtg_blank, ncol = 1, rel_heights = c(0.1,1))
  1391. g_model_beh_ttl <-plot_grid(model_com_title, g_model_beh + labs(title = ""), ncol = 1, rel_heights = c(0.1,1))
  1392. g_example_ttl <- plot_grid(example_title, g_rtg_blank, ncol = 1, rel_heights = c(0.1,1))
  1393. rf_title <- ggdraw() +
  1394. draw_label(
  1395. "Parameter recovery" )
  1396. g_rt_ttl <- plot_grid(rf_title, g_rf, ncol = 1, rel_heights = c(0.2,1))
  1397. # g_example_ttl
  1398. g_figure_modelling <- plot_grid(
  1399. plot_grid(g_rtg_blank, g_rtg_blank, labels = c("a","b")),
  1400. plot_grid(g_rt_ttl, g_model_beh_ttl, rel_widths = c(2,1), labels = c("c", "d"), align = "h") ,
  1401. rel_heights = c(1,1),
  1402. nrow = 2)
  1403. ggsave("g_figure_modelling.pdf", plot = g_figure_modelling, device = cairo_pdf, units = "mm",
  1404. width =179, height = 130, dpi = 600)
  1405. ```
  1406. # Posterior predictive checks ----------------
  1407. collect the model predictions
  1408. ```{r collect the model predictions, fig.width = 10, fig.height = 9, echo=FALSE, warning= FALSE}
  1409. # collect the model predictions -----------------------------------------------------------
  1410. Pars_extract_set <- rstan::extract(M_tg_hgf_gamma, pars=c('gam',
  1411. 'y_pred',
  1412. 'mu_good_vect',
  1413. 'mu_bad_vect',
  1414. 'mu_good2_vect',
  1415. 'mu_bad2_vect',
  1416. 'pi_good_vect',
  1417. 'pi_bad_vect',
  1418. 'pi_good2_vect',
  1419. 'pi_bad2_vect',
  1420. 'om_good',
  1421. 'c'))
  1422. Pars_extract_set_rw <- rstan::extract(M_rw, pars=c('y_pred'))
  1423. # Pars_extract_set$c %>% colMeans()
  1424. if (file.exists("Data_beh_with_predictions.rds")) {
  1425. # lr1_mat<- readRDS("Data4PlottingLearningRates.rds")
  1426. data_beh <- readRDS("Data_beh_with_predictions.rds")
  1427. } else {
  1428. colSdColMeans <- function(x, na.rm=TRUE) {
  1429. if (na.rm) {
  1430. n <- colSums(!is.na(x)) # thanks @flodel
  1431. } else {
  1432. n <- nrow(x)
  1433. }
  1434. colVar <- colMeans(x*x, na.rm=na.rm) - (colMeans(x, na.rm=na.rm))^2
  1435. return(sqrt(colVar * n/(n-1)))
  1436. }
  1437. data_temp <- readRDS("belief-volatility-da-trustgame/Behavioural_data.rds")
  1438. data_temp <- data_temp[order(data_temp$ID, data_temp$Trial),]
  1439. data_temp$Backtransfer[data_temp$Backtransfer == -1] =0
  1440. sub_no = dim(Pars_extract_set$y_pred)[2]
  1441. # data_temp_stan = fit_model_gen %>% View
  1442. sample_no <- dim(Pars_extract_set$y_pred)[1]
  1443. # someData <- rep(sample_no*sub_no*50);
  1444. lr1_mat<- array(NA, c( sample_no,sub_no*50))
  1445. lr1_mat_gammed<- array(NA, c( sample_no,sub_no*50))
  1446. PE_mat<- array(NA, c( sample_no,sub_no*50))
  1447. mu2_mat<- array(NA, c( sample_no,sub_no*50))
  1448. prec_weighted_PE_mat<- array(NA, c( sample_no,sub_no*50))
  1449. pi1_mat<- array(NA, c( sample_no,sub_no*50))
  1450. pi2_mat<- array(NA, c( sample_no,sub_no*50))
  1451. prec_weights_mat<- array(NA, c( sample_no,sub_no*50))
  1452. prec_weights_lr_mat <- array(NA, c( sample_no,sub_no*50))
  1453. prec_weights_lr_sul <- array(NA, c( sample_no,1))
  1454. prec_weights_lr_sul_a1p <- array(NA, c( sample_no,1))
  1455. prec_weights_lr_sul_a1m <- array(NA, c( sample_no,1))
  1456. y_pred_change_BT <- array(NA, c( sample_no,sub_no*2))
  1457. y_pred_change<- array(NA, c( sample_no,sub_no*50))
  1458. y_pred_abschange<- array(NA, c( sample_no,sub_no*50))
  1459. y_pred_pos<- array(NA, c( sample_no,sub_no*50))
  1460. y_pred_neg<- array(NA, c( sample_no,sub_no*50))
  1461. y_pred_incon<- array(NA, c( sample_no,sub_no*50))
  1462. y_pred_change_mean <- array(NA, c( sample_no,sub_no))
  1463. y_pred_abschange_mean <- array(NA, c( sample_no,sub_no))
  1464. y_pred_pos_sum<- array(NA, c( sample_no,sub_no))
  1465. y_pred_neg_sum<- array(NA, c( sample_no,sub_no))
  1466. y_pred_incon_sum<- array(NA, c( sample_no,sub_no))
  1467. y_pred_rec_sum <- array(NA, c( sample_no,sub_no))
  1468. # rw part
  1469. y_pred_rw_change <- array(NA, c( sample_no,sub_no*50))
  1470. y_pred_rw_abschange<- array(NA, c( sample_no,sub_no*50))
  1471. y_pred_rw_pos<- array(NA, c( sample_no,sub_no*50))
  1472. y_pred_rw_neg<- array(NA, c( sample_no,sub_no*50))
  1473. y_pred_rw_incon<- array(NA, c( sample_no,sub_no*50))
  1474. y_pred_rw_change_mean <- array(NA, c( sample_no,sub_no))
  1475. y_pred_rw_abschange_mean <- array(NA, c( sample_no,sub_no))
  1476. y_pred_rw_pos_sum<- array(NA, c( sample_no,sub_no))
  1477. y_pred_rw_neg_sum<- array(NA, c( sample_no,sub_no))
  1478. y_pred_rw_incon_sum<- array(NA, c( sample_no,sub_no))
  1479. y_pred_rw_rec_sum <- array(NA, c( sample_no,sub_no))
  1480. for (i in 1:sample_no) {
  1481. if (i/(sample_no/100) == i%/%(sample_no/100) ) print(paste(i/sample_no*100, "%"))
  1482. gam_sample = Pars_extract_set$gam[i,]
  1483. y_pred_chain <- Pars_extract_set$y_pred[i,,]
  1484. y_pred_chain_long <- as.vector(t(y_pred_chain))
  1485. Inv_Mat_good <- matrix(y_pred_chain_long[data_temp$Trustee == "Good"],nrow = 25)
  1486. Inv_Mat_bad <- matrix(y_pred_chain_long[data_temp$Trustee == "Bad"],nrow = 25)
  1487. # dim(Inv_Mat_good_change_temp[1:24,])
  1488. Inv_Mat_good_change <- Inv_Mat_good[2:25,] - Inv_Mat_good[1:24,]
  1489. Inv_Mat_bad_change <- Inv_Mat_bad[2:25,] - Inv_Mat_bad[1:24,]
  1490. # Inv_Mat_bad_change <- c(Na, Inv_Mat_bad_change)
  1491. # head(Inv_Mat_bad_change_temp)
  1492. Inv_Mat_good_change_temp <- matrix(0, 25,sub_no)
  1493. Inv_Mat_good_change_temp[25,] <- NA
  1494. Inv_Mat_good_change_temp[1:24,] <- Inv_Mat_good_change
  1495. Inv_Mat_bad_change_temp <- matrix(0, 25,sub_no)
  1496. Inv_Mat_bad_change_temp[25,] <- NA
  1497. Inv_Mat_bad_change_temp[1:24,] <- Inv_Mat_bad_change
  1498. Inv_Mat_good_change_long <- as.numeric(as.vector(Inv_Mat_good_change_temp))
  1499. Inv_Mat_bad_change_long <- as.numeric(as.vector(Inv_Mat_bad_change_temp))
  1500. Change_check <- rep(-99, sub_no*50)
  1501. Change_check[data_temp$Trustee=="Good"] <- Inv_Mat_good_change_long
  1502. Change_check[data_temp$Trustee=="Bad"] <- Inv_Mat_bad_change_long
  1503. mu_good2_vect_chain_long <- as.vector(t(Pars_extract_set$mu_good2_vect[i,,]))
  1504. pi_good2_vect_chain_long <- as.vector(t(Pars_extract_set$pi_good2_vect[i,,]))
  1505. pi_good1_vect_chain_long <- as.vector(t(Pars_extract_set$pi_good_vect[i,,]))
  1506. pi_bad2_vect_chain_long <- as.vector(t(Pars_extract_set$pi_bad2_vect[i,,]))
  1507. pi_bad1_vect_chain_long <- as.vector(t(Pars_extract_set$pi_bad_vect[i,,]))
  1508. pi1_vect_chain_long <- pi_good1_vect_chain_long
  1509. pi1_vect_chain_long[pi_good2_vect_chain_long == -1] <- pi_bad1_vect_chain_long[pi_good2_vect_chain_long == -1]
  1510. pi2_vect_chain_long <- pi_good2_vect_chain_long
  1511. pi2_vect_chain_long[pi_good2_vect_chain_long == -1] <- pi_bad2_vect_chain_long[pi_good2_vect_chain_long == -1]
  1512. pi2_pred_vect_chain_long = pi2_vect_chain_long + 1/pi1_vect_chain_long
  1513. pi1_mat[i, ]<-pi1_vect_chain_long
  1514. pi2_mat[i, ]<- pi2_vect_chain_long
  1515. prec_weights_mat[i,] <- pi2_pred_vect_chain_long
  1516. prec_weights_lr_mat[i,] <- 1/pi2_pred_vect_chain_long
  1517. prec_weights_lr_sul[i] <- mean(1/pi2_pred_vect_chain_long[data_temp$Treatment=="sulpiride"]) - mean(1/pi2_pred_vect_chain_long[data_temp$Treatment=="control"])
  1518. prec_weights_lr_sul_a1p[i] <- mean(1/pi2_pred_vect_chain_long[data_temp$Treatment=="sulpiride"& data_temp$Genotype=="A1+"]) - mean(1/pi2_pred_vect_chain_long[data_temp$Treatment=="control"& data_temp$Genotype=="A1+"])
  1519. prec_weights_lr_sul_a1m[i] <- mean(1/pi2_pred_vect_chain_long[data_temp$Treatment=="sulpiride"& data_temp$Genotype=="A1-"]) - mean(1/pi2_pred_vect_chain_long[data_temp$Treatment=="control"& data_temp$Genotype=="A1-"])
  1520. mu_good1_vect_chain_long <- 1/(1+ exp(- mu_good2_vect_chain_long))
  1521. mu_vect_mat_good <- matrix(mu_good1_vect_chain_long[data_temp$Trustee == "Good"],nrow = 25)
  1522. # mu_good1_vect_chain_long[data_temp$Trustee=="Bad"] %>% unique
  1523. mu_vect_mat_good_gammed <- mu_vect_mat_good %>% apply(1, pw, delta = gam_sample) %>% t()
  1524. # mu_good1_vect_chain_long_gammed <- mu_good1_vect_chain_long %>% apply(1, pw, delta = gam_sample)
  1525. diff_sgmmu2_mat = array(NA, c(25,75))
  1526. diff_sgmmu2_mat[1:24,] = mu_vect_mat_good[2:25,] - mu_vect_mat_good[1:24,]
  1527. # ((dasgmmu2_mat - as.numeric(data_temp[data_temp$Trustee == "Good",]$Backtransfer==1)) != 0 ) %>% any
  1528. diff_sgmmu2_mat_gammed = array(NA, c(25,75))
  1529. diff_sgmmu2_mat_gammed = mu_vect_mat_good_gammed[2:25,] - mu_vect_mat_good_gammed[1:24,]
  1530. dasgmmu2_mat = matrix(as.numeric(data_temp[data_temp$Trustee == "Good",]$Backtransfer==1),nrow = 25 )
  1531. # dasgmmu2 = as.numeric(data_temp$Backtransfer==1) - mu_good1_vect_chain_long;
  1532. # dasgmmu2_mat <- matrix(dasgmmu2[data_temp$Trustee == "Good"],nrow = 25)
  1533. # as.numeric(diff_sgmmu2_mat[,2] > 0) - (dasgmmu2_mat[,2]> 0)
  1534. # dasgmmu2 = as.numeric(diff_sgmmu2_mat > 0) - mu_good1_vect_chain_long;
  1535. #
  1536. # dasgmmu2_mat <- matrix(t(dasgmmu2[data_temp$Trustee == "Good"]),nrow = 25)
  1537. #
  1538. lr1_good = dasgmmu2_mat
  1539. lr1_good[1:24,] = diff_sgmmu2_mat[1:24,]/dasgmmu2_mat[1:24,];
  1540. lr1_good[25,] = NA
  1541. lr1_good[dasgmmu2_mat==0] = 0;
  1542. lr1_good[lr1_good == -Inf] = 0;
  1543. lr1_good_gammed = dasgmmu2_mat
  1544. lr1_good_gammed[1:24,] = diff_sgmmu2_mat_gammed[1:24,]/dasgmmu2_mat[1:24,];
  1545. lr1_good_gammed[25,] = NA
  1546. lr1_good_gammed[dasgmmu2_mat==0] = 0;
  1547. lr1_good_gammed[lr1_good_gammed == -Inf] = 0;
  1548. mu_bad2_vect_chain_long <- as.vector(t(Pars_extract_set$mu_bad2_vect[i,,]))
  1549. mu_bad1_vect_chain_long <- 1/(1+ exp(-mu_bad2_vect_chain_long));
  1550. mu_vect_mat_bad <- matrix(mu_bad1_vect_chain_long[data_temp$Trustee == "Bad"],nrow = 25)
  1551. mu_vect_mat_bad_gammed <- mu_vect_mat_bad %>% apply(1, pw, delta = gam_sample) %>% t()
  1552. diff_sgmmu2_mat =array(NA, c(25,75))
  1553. diff_sgmmu2_mat[1:24,] = mu_vect_mat_bad[2:25,] - mu_vect_mat_bad[1:24,]
  1554. dasgmmu2_mat = matrix(as.numeric(data_temp[data_temp$Trustee == "Bad",]$Backtransfer==1),nrow = 25 )
  1555. # ((dasgmmu2_mat - as.numeric(data_temp[data_temp$Trustee == "Good",]$Backtransfer==1)) != 0 ) %>% any
  1556. diff_sgmmu2_mat_gammed =array(NA, c(25,75))
  1557. diff_sgmmu2_mat_gammed[1:24,] = mu_vect_mat_bad_gammed[2:25,] - mu_vect_mat_bad_gammed[1:24,]
  1558. lr1_bad = dasgmmu2_mat
  1559. lr1_bad[1:24,] = diff_sgmmu2_mat[1:24,]/dasgmmu2_mat[1:24,];
  1560. lr1_bad[25,] = NA
  1561. lr1_bad[dasgmmu2_mat==0] = 0;
  1562. lr1_bad[lr1_bad == -Inf] = 0;
  1563. lr1_bad_gammed = dasgmmu2_mat
  1564. lr1_bad_gammed[1:24,] = diff_sgmmu2_mat_gammed[1:24,]/dasgmmu2_mat[1:24,];
  1565. lr1_bad_gammed[25,] = NA
  1566. lr1_bad_gammed[dasgmmu2_mat==0] = 0;
  1567. lr1_bad_gammed[lr1_bad_gammed == -Inf] = 0;
  1568. lr1_mat[i,data_temp$Trustee=="Good"] <- as.vector(lr1_good)
  1569. lr1_mat[i,data_temp$Trustee=="Bad"] <- as.vector(lr1_bad)
  1570. lr1_mat_gammed[i,data_temp$Trustee=="Good"] <- as.vector(lr1_good_gammed)
  1571. lr1_mat_gammed[i,data_temp$Trustee=="Bad"] <- as.vector(lr1_bad_gammed)
  1572. mu2_vect_chain_long <- mu_good2_vect_chain_long
  1573. mu2_vect_chain_long[mu2_vect_chain_long==-1] = mu_bad2_vect_chain_long[mu2_vect_chain_long==-1]
  1574. mu1_vect_chain_long = 1/(1+ exp(-mu2_vect_chain_long));
  1575. mu2_mat[i,] = mu2_vect_chain_long
  1576. PE_mat[i,] = as.numeric(data_temp$Backtransfer==1) - mu1_vect_chain_long
  1577. prec_weighted_PE_mat[i,] = PE_mat[i,]* 1/pi2_pred_vect_chain_long
  1578. y_pred_change[i,] <- Change_check
  1579. y_pred_abschange[i,] <- abs(Change_check)
  1580. y_pred_pos[i,] <- (data_temp$Backtransfer == 1 & Change_check > 0) | (data_temp$Backtransfer == 1 & y_pred_chain_long == 10)
  1581. y_pred_neg[i,] <- (data_temp$Backtransfer == -1 & Change_check < 0 ) | (data_temp$Backtransfer == -1 & y_pred_chain_long == 0)
  1582. y_pred_incon[i,] <- (data_temp$Backtransfer == 1 & Change_check < 0) | (data_temp$Backtransfer == -1 & Change_check > 0)
  1583. data_pred_temp <- tibble(y_pred_pos_temp = y_pred_pos[i,],
  1584. y_pred_neg_temp = y_pred_neg[i,],
  1585. y_pred_incon_temp = y_pred_incon[i,],
  1586. ID = data_temp$ID,
  1587. Change_temp = Change_check) %>%
  1588. filter(!is.na(Change_temp)) %>%
  1589. group_by(ID) %>%
  1590. summarise(sumincon = sum(y_pred_incon_temp),
  1591. sumposrec = sum(y_pred_pos_temp),
  1592. sumnegrec = sum(y_pred_neg_temp),
  1593. sumrec = sum(y_pred_pos_temp)+sum(y_pred_neg_temp),
  1594. abschange_mean = mean(abs(Change_temp)))
  1595. # data_pred_temp
  1596. y_pred_abschange_mean[i,] <- data_pred_temp$abschange_mean
  1597. y_pred_pos_sum[i,]<- data_pred_temp$sumposrec
  1598. y_pred_neg_sum[i,]<- data_pred_temp$sumnegrec
  1599. y_pred_incon_sum[i,] <-data_pred_temp$sumincon
  1600. y_pred_rec_sum[i,] <- data_pred_temp$sumrec
  1601. # rw part: ####
  1602. y_pred_rw_chain <- Pars_extract_set_rw$y_pred[i,,]
  1603. y_pred_rw_chain_long <- as.vector(t(y_pred_rw_chain))
  1604. Inv_Mat_good <- matrix(y_pred_rw_chain_long[data_temp$Trustee == "Good"],nrow = 25)
  1605. Inv_Mat_bad <- matrix(y_pred_rw_chain_long[data_temp$Trustee == "Bad"],nrow = 25)
  1606. # dim(Inv_Mat_good)
  1607. Inv_Mat_good_change <- Inv_Mat_good[2:25,] - Inv_Mat_good[1:24,]
  1608. Inv_Mat_bad_change <- Inv_Mat_bad[2:25,] - Inv_Mat_bad[1:24,]
  1609. # Inv_Mat_bad_change <- c(Na, Inv_Mat_bad_change)
  1610. # head(Inv_Mat_bad_change_temp)
  1611. Inv_Mat_good_change_temp <- matrix(0, 25,sub_no)
  1612. Inv_Mat_good_change_temp[25,] <- NA
  1613. Inv_Mat_good_change_temp[1:24,] <- Inv_Mat_good_change
  1614. Inv_Mat_bad_change_temp <- matrix(0, 25,sub_no)
  1615. Inv_Mat_bad_change_temp[25,] <- NA
  1616. Inv_Mat_bad_change_temp[1:24,] <- Inv_Mat_bad_change
  1617. Inv_Mat_good_change_long <- as.numeric(as.vector(Inv_Mat_good_change_temp))
  1618. Inv_Mat_bad_change_long <- as.numeric(as.vector(Inv_Mat_bad_change_temp))
  1619. Change_check <- rep(-99, sub_no*50)
  1620. Change_check[data_temp$Trustee=="Good"] <- Inv_Mat_good_change_long
  1621. Change_check[data_temp$Trustee=="Bad"] <- Inv_Mat_bad_change_long
  1622. #
  1623. y_pred_rw_change[i,] <- Change_check
  1624. y_pred_rw_abschange[i,] <- abs(Change_check)
  1625. y_pred_rw_pos[i,] <- (data_temp$Backtransfer == 1 & Change_check > 0) | (data_temp$Backtransfer == 1 & y_pred_rw_chain_long == 10)
  1626. y_pred_rw_neg[i,] <- (data_temp$Backtransfer == -1 & Change_check < 0 ) | (data_temp$Backtransfer == -1 & y_pred_rw_chain_long == 0)
  1627. y_pred_rw_incon[i,] <- (data_temp$Backtransfer == 1 & Change_check < 0) | (data_temp$Backtransfer == -1 & Change_check > 0)
  1628. data_pred_temp <- tibble(y_pred_rw_pos_temp = y_pred_rw_pos[i,],
  1629. y_pred_rw_neg_temp = y_pred_rw_neg[i,],
  1630. y_pred_rw_incon_temp = y_pred_rw_incon[i,],
  1631. ID = data_temp$ID,
  1632. Change_temp = Change_check) %>%
  1633. filter(!is.na(Change_temp)) %>%
  1634. group_by(ID) %>%
  1635. summarise(sumincon = sum(y_pred_rw_incon_temp),
  1636. sumposrec = sum(y_pred_rw_pos_temp),
  1637. sumnegrec = sum(y_pred_rw_neg_temp),
  1638. sumrec = sum(y_pred_rw_pos_temp)+sum(y_pred_rw_neg_temp),
  1639. abschange_mean = mean(abs(Change_temp)))
  1640. # data_pred_temp
  1641. y_pred_rw_abschange_mean[i,] <- data_pred_temp$abschange_mean
  1642. y_pred_rw_pos_sum[i,]<- data_pred_temp$sumposrec
  1643. y_pred_rw_neg_sum[i,]<- data_pred_temp$sumnegrec
  1644. y_pred_rw_incon_sum[i,] <-data_pred_temp$sumincon
  1645. y_pred_rw_rec_sum[i,] <- data_pred_temp$sumrec
  1646. }
  1647. data_temp$predictions_rec <- (y_pred_rec_sum/50) %>% apply(2, quantile, probs = 0.5, na.rm = TRUE)
  1648. data_temp$predictions <- as.vector(t(colMeans(Pars_extract_set$y_pred)))
  1649. data_temp$predictions_abschange <- colMeans(y_pred_abschange)
  1650. data_temp$predictions_abschange_ci025 <- y_pred_abschange %>% apply(2, quantile, probs = 0.025, na.rm = TRUE)
  1651. data_temp$predictions_abschange_ci25 <- y_pred_abschange %>% apply(2, quantile, probs = 0.25, na.rm = TRUE)
  1652. data_temp$predictions_abschange_ci5 <- y_pred_abschange %>% apply(2, quantile, probs = 0.5, na.rm = TRUE)
  1653. data_temp$predictions_abschange_ci75 <- y_pred_abschange %>% apply(2, quantile, probs = 0.75, na.rm = TRUE)
  1654. data_temp$predictions_abschange_ci975 <- y_pred_abschange %>% apply(2, quantile, probs = 0.975, na.rm = TRUE)
  1655. data_temp$predictions_change <- colMeans(y_pred_change)
  1656. data_temp$predictions_change_ci025 <- y_pred_change %>% apply(2, quantile, probs = 0.025, na.rm = TRUE)
  1657. data_temp$predictions_change_ci25 <- y_pred_change %>% apply(2, quantile, probs = 0.25, na.rm = TRUE)
  1658. data_temp$predictions_change_ci5 <- y_pred_change %>% apply(2, quantile, probs = 0.5, na.rm = TRUE)
  1659. data_temp$predictions_change_ci75 <- y_pred_change %>% apply(2, quantile, probs = 0.75, na.rm = TRUE)
  1660. data_temp$predictions_change_ci975 <- y_pred_change %>% apply(2, quantile, probs = 0.975, na.rm = TRUE)
  1661. data_temp$lr1 = colMeans(lr1_mat)
  1662. data_temp$lr1_ci025 <- lr1_mat %>% apply(2, quantile, probs = 0.025, na.rm = TRUE)
  1663. data_temp$lr1_ci25 <- lr1_mat %>% apply(2, quantile, probs = 0.25, na.rm = TRUE)
  1664. data_temp$lr1_ci5 <- lr1_mat %>% apply(2, quantile, probs = 0.5, na.rm = TRUE)
  1665. data_temp$lr1_ci75 <- lr1_mat %>% apply(2, quantile, probs = 0.75, na.rm = TRUE)
  1666. data_temp$lr1_ci975 <- lr1_mat %>% apply(2, quantile, probs = 0.975, na.rm = TRUE)
  1667. data_temp$lr1_gammed = colMeans(lr1_mat_gammed)
  1668. data_temp$lr1_gammed_ci025 <- lr1_mat_gammed %>% apply(2, quantile, probs = 0.025, na.rm = TRUE)
  1669. data_temp$lr1_gammed_ci25 <- lr1_mat_gammed %>% apply(2, quantile, probs = 0.25, na.rm = TRUE)
  1670. data_temp$lr1_gammed_ci5 <- lr1_mat_gammed %>% apply(2, quantile, probs = 0.5, na.rm = TRUE)
  1671. data_temp$lr1_gammed_ci75 <- lr1_mat_gammed %>% apply(2, quantile, probs = 0.75, na.rm = TRUE)
  1672. data_temp$lr1_gammed_ci975 <- lr1_mat_gammed %>% apply(2, quantile, probs = 0.975, na.rm = TRUE)
  1673. data_temp$prec_weights = colMeans(prec_weights_mat)
  1674. data_temp$prec_weights_ci025 <- prec_weights_mat %>% apply(2, quantile, probs = 0.025, na.rm = TRUE)
  1675. data_temp$prec_weights_ci25 <- prec_weights_mat %>% apply(2, quantile, probs = 0.25, na.rm = TRUE)
  1676. data_temp$prec_weights_ci5 <- prec_weights_mat %>% apply(2, quantile, probs = 0.5, na.rm = TRUE)
  1677. data_temp$prec_weights_ci75 <- prec_weights_mat %>% apply(2, quantile, probs = 0.75, na.rm = TRUE)
  1678. data_temp$prec_weights_ci975 <- prec_weights_mat %>% apply(2, quantile, probs = 0.975, na.rm = TRUE)
  1679. data_temp$prec_weights_lr = colMeans(prec_weights_lr_mat)
  1680. data_temp$prec_weights_lr_ci025 <- prec_weights_lr_mat %>% apply(2, quantile, probs = 0.025, na.rm = TRUE)
  1681. data_temp$prec_weights_lr_ci25 <- prec_weights_lr_mat %>% apply(2, quantile, probs = 0.25, na.rm = TRUE)
  1682. data_temp$prec_weights_lr_ci5 <- prec_weights_lr_mat %>% apply(2, quantile, probs = 0.5, na.rm = TRUE)
  1683. data_temp$prec_weights_lr_ci75 <- prec_weights_lr_mat %>% apply(2, quantile, probs = 0.75, na.rm = TRUE)
  1684. data_temp$prec_weights_lr_ci975 <- prec_weights_lr_mat %>% apply(2, quantile, probs = 0.975, na.rm = TRUE)
  1685. data_temp$PE <- colMeans(PE_mat)
  1686. data_temp$prec_weighted_PE <- colMeans(prec_weighted_PE_mat)
  1687. data_temp$pi1 <- colMeans(pi1_mat)
  1688. data_temp$pi1_ci025 <- pi1_mat %>% apply(2, quantile, probs = 0.025, na.rm = TRUE)
  1689. data_temp$pi1_ci25 <- pi1_mat %>% apply(2, quantile, probs = 0.25, na.rm = TRUE)
  1690. data_temp$pi1_ci5 <- pi1_mat %>% apply(2, quantile, probs = 0.5, na.rm = TRUE)
  1691. data_temp$pi1_ci75 <- pi1_mat %>% apply(2, quantile, probs = 0.75, na.rm = TRUE)
  1692. data_temp$pi1_ci975 <- pi1_mat %>% apply(2, quantile, probs = 0.975, na.rm = TRUE)
  1693. data_temp$si1 <- colMeans(1/pi1_mat)
  1694. data_temp$si1_ci025 <- (1/pi1_mat) %>% apply(2, quantile, probs = 0.025, na.rm = TRUE)
  1695. data_temp$si1_ci25 <- (1/pi1_mat) %>% apply(2, quantile, probs = 0.25, na.rm = TRUE)
  1696. data_temp$si1_ci5 <- (1/pi1_mat) %>% apply(2, quantile, probs = 0.5, na.rm = TRUE)
  1697. data_temp$si1_ci75 <- (1/pi1_mat) %>% apply(2, quantile, probs = 0.75, na.rm = TRUE)
  1698. data_temp$si1_ci975 <- (1/pi1_mat) %>% apply(2, quantile, probs = 0.975, na.rm = TRUE)
  1699. data_temp$mu2 <- colMeans(mu2_mat)
  1700. data_temp$mu2_ci025 <- mu2_mat %>% apply(2, quantile, probs = 0.025, na.rm = TRUE)
  1701. data_temp$mu2_ci25 <- mu2_mat %>% apply(2, quantile, probs = 0.25, na.rm = TRUE)
  1702. data_temp$mu2_ci5 <- mu2_mat %>% apply(2, quantile, probs = 0.5, na.rm = TRUE)
  1703. data_temp$mu2_ci75 <- mu2_mat %>% apply(2, quantile, probs = 0.75, na.rm = TRUE)
  1704. data_temp$mu2_ci975 <- mu2_mat %>% apply(2, quantile, probs = 0.975, na.rm = TRUE)
  1705. data_temp$pi2 <- colMeans(pi2_mat)
  1706. data_temp$mu_good2 <- as.vector(t(colMeans(Pars_extract_set$mu_good2_vect)))
  1707. data_temp$mu_bad2 <- as.vector(t(colMeans(Pars_extract_set$mu_bad2_vect)))
  1708. data_temp$pi_good <- as.vector(t(colMeans(Pars_extract_set$pi_good_vect)))
  1709. data_temp$pi_bad <- as.vector(t(colMeans(Pars_extract_set$pi_bad_vect)))
  1710. data_temp$pi_good2 <- as.vector(t(colMeans(Pars_extract_set$pi_good2_vect)))
  1711. data_temp$pi_bad2 <- as.vector(t(colMeans(Pars_extract_set$pi_bad2_vect)))
  1712. data_beh <- data_temp
  1713. saveRDS(data_temp, "Data_beh_with_predictions.rds")
  1714. saveRDS(lr1_mat, "Data4PlottingLearningRates.rds")
  1715. saveRDS(pi1_mat, "Data4PlottingOutcomePrecision.rds")
  1716. saveRDS(prec_weights_lr_mat, "Data4PlottingPrecWeightedLearningRates.rds")
  1717. }
  1718. ```
  1719. Plot model predictions for investment and change
  1720. ```{r Plot model predictions for investment and change}
  1721. data_beh = readRDS( "Data_beh_with_predictions.rds")
  1722. # plot model predictions across time -------------------------------------------------
  1723. data_good <- data_beh[data_beh$Trustee =="Good",]
  1724. data_bad <- data_beh[data_beh$Trustee =="Bad",]
  1725. data_beh_pp <- data_temp %>% filter(Trial!=25) %>%
  1726. group_by(Trial, Treatment, Genotype,Trustee) %>%
  1727. summarize(N = n(),
  1728. predictions_se = sd(predictions, na.rm = T)/sqrt(N-1),
  1729. predictions_mean = mean(predictions, na.rm = T))
  1730. g_investment_pred <- data_beh %>%
  1731. ggplot(aes(x= Trial, colour = Treatment)) +#
  1732. # stat_smooth(aes(group = Treatment)) +
  1733. geom_ribbon(data= data_beh_pp %>% filter(Trustee == "Good"), aes(x = Trial, colour = Treatment, ymin = predictions_mean -predictions_se, ymax = predictions_mean+predictions_se), fill = "#E6E6E6", alpha = 0.3, size = 0.3)+
  1734. # geom_ribbon(data= data_beh_pp_abschange, aes(x = Trial, colour = Treatment, ymin = predictions_abschange_ci5 -predictions_abschange_ci5_se, ymax = predictions_abschange_ci5+predictions_abschange_ci5_se), fill = "#E6E6E6", alpha = 0.3, size = 0.3)+
  1735. geom_line(data= data_beh_pp %>% filter(Trustee == "Good"), aes(x = Trial, colour = Treatment, y = predictions_mean), size = 1)+
  1736. stat_summary(data= data_beh %>% filter(Trustee == "Good"), aes(y = Investment, group = Treatment), geom = "point", fun.y = mean, shape = 17, size = 1, alpha = 0.5) +
  1737. geom_ribbon(data= data_beh_pp %>% filter(Trustee == "Bad"), aes(x = Trial, colour = Treatment, ymin = predictions_mean -predictions_se, ymax = predictions_mean+predictions_se), fill = "#E6E6E6", alpha = 0.3, size = 0.3)+
  1738. # geom_ribbon(data= data_beh_pp_abschange, aes(x = Trial, colour = Treatment, ymin = predictions_abschange_ci5 -predictions_abschange_ci5_se, ymax = predictions_abschange_ci5+predictions_abschange_ci5_se), fill = "#E6E6E6", alpha = 0.3, size = 0.3)+
  1739. geom_line(data= data_beh_pp %>% filter(Trustee == "Bad"), aes(x = Trial, colour = Treatment, y = predictions_mean), size = 1)+
  1740. stat_summary(data= data_beh %>% filter(Trustee == "Bad"), aes(y = Investment, group = Treatment), geom = "point", fun.y = mean, shape = 17, size = 1, alpha = 0.5)+
  1741. theme_Publication(base_size = 10) +theme(axis.ticks.x = element_blank(),
  1742. panel.grid.major = element_blank(),
  1743. legend.position = "none") +
  1744. ylab("Posterior predicted investments") + scale_colour_Publication() + scale_fill_Publication() +facet_wrap(~Genotype)+ scale_x_discrete(name = "Trials", limits=c(1,10,20))
  1745. data_mu_across_time <-
  1746. data_beh %>% merge(data_group, by = "ID") %>%
  1747. group_by(ID,Treatment, Genotype, Trial, Trustee) %>%
  1748. summarize(mean_perID1 = mean(pw(inv_logit(mu2_ci5), gam)),
  1749. mean_perID2= median(mu2_ci5),
  1750. mean_perID = mean(inv_logit(mu2_ci5)),
  1751. mean_si = median(si1_ci5)) %>%
  1752. group_by(Treatment, Genotype, Trial, Trustee) %>% summarize(N =n(),
  1753. mean_mu = mean(mean_perID2, na.rm = TRUE),
  1754. se_mu = sd(mean_perID2, na.rm = TRUE)/sqrt(N),
  1755. sd_mu = mean(mean_si, na.rm = TRUE))
  1756. g_mu_across_time<- ggplot(data =data_mu_across_time %>% filter(Trustee == "Good"), aes(x=Trial, y= mean_mu, colour = Treatment, ymin = mean_mu - sd_mu, ymax = mean_mu + sd_mu)) +
  1757. # geom_hline(yintercept = c(7/25), linetype= "dashed")+
  1758. # geom_hline(yintercept = c(18/25), linetype= "dashed")+
  1759. geom_ribbon(fill = "#E6E6E6", size = 0.3, alpha = 0.5)+
  1760. geom_line(size = 1) +
  1761. geom_ribbon(data =data_mu_across_time %>% filter(Trustee == "Bad"), fill = "#E6E6E6", size =0.3, alpha = 0.5)+
  1762. geom_line(data =data_mu_across_time %>% filter(Trustee == "Bad"), size = 1) +
  1763. facet_wrap(~Genotype) + theme_Publication() +theme(axis.ticks.x = element_blank(),
  1764. legend.position = "none",
  1765. panel.grid.major = element_blank())+
  1766. # title = element_blank()) +
  1767. ylab("Trustworthiness belief") + scale_colour_Publication() + scale_fill_Publication() + scale_x_discrete(name = "Trials", limits=c(1,10,20))
  1768. g_mu_across_time
  1769. g_legend_pred <- get_legend(g_investment_smooth_pred +
  1770. theme(legend.position = "right",
  1771. legend.key = element_rect(colour = NA),
  1772. # legend.direction = "horizontal",
  1773. legend.key.size= unit(0.2, "cm"),
  1774. # legend.margin = unit(0, "cm"),
  1775. legend.title = element_text(face="italic")))
  1776. data_beh_pp_abschange <- data_temp %>% filter(Trial!=25) %>%
  1777. group_by(Trial, Treatment) %>%
  1778. summarize(N = n(),
  1779. predictions_abschange_ci5_se = sd(predictions_abschange_ci5, na.rm = T)/sqrt(N-1),
  1780. predictions_abschange_ci5 = mean(predictions_abschange_ci5, na.rm = T),
  1781. predictions_abschange_ci025 = mean(predictions_abschange_ci025, na.rm = T),
  1782. predictions_abschange_ci25 = mean(predictions_abschange_ci25, na.rm = T),
  1783. predictions_abschange_ci75 = mean(predictions_abschange_ci75, na.rm = T),
  1784. predictions_abschange_ci975 = mean(predictions_abschange_ci975, na.rm = T))
  1785. p_abs_change_pred <- data_beh %>% filter(!is.na(abs_change)) %>%
  1786. ggplot(aes(x = Trial, y = predictions_abschange_ci5, colour = Treatment)) +#
  1787. # stat_smooth(aes(group = Treatment)) +
  1788. geom_ribbon(data= data_beh_pp_abschange, aes(x = Trial, colour = Treatment, ymin = predictions_abschange_ci5 -predictions_abschange_ci5_se, ymax = predictions_abschange_ci5+predictions_abschange_ci5_se), fill = "#E6E6E6", alpha = 0.3, size = 0.3)+
  1789. # geom_ribbon(data= data_beh_pp_abschange, aes(x = Trial, colour = Treatment, ymin = predictions_abschange_ci025, ymax = predictions_abschange_ci975), fill = "#E6E6E6", alpha = 0.3, size = 0.3)+
  1790. geom_line(data= data_beh_pp_abschange, aes(x = Trial, colour = Treatment, y = predictions_abschange_ci5), size = 1)+
  1791. stat_summary(aes(y = abs_change, group = Treatment), geom = "point", fun.y = mean, shape = 17, size = 1, alpha = 0.5) +
  1792. theme_Publication(base_size = 10) +theme(axis.ticks.x = element_blank(),
  1793. panel.grid.major = element_blank(),
  1794. legend.position = "none") +
  1795. ylab("Posterior predicted\n absolute change in investment") + scale_colour_Publication() + scale_fill_Publication() +scale_x_discrete(name = "Trials", limits=c(1,10,20))
  1796. # stat_smooth(data = data_beh,aes(x = Trial, y = predictions_abschange,group = Treatment))
  1797. # plot_grid(g_investment_smooth, g_abs_change_time)
  1798. ```
  1799. ```{r pp reciprocity and change}
  1800. data_change_id <- data_beh %>% filter(!is.na(Change)) %>% group_by(Treatment, Genotype, Backtransfer_f, ID) %>% summarise( Change = mean(Change))
  1801. data_pred_change_id <- data_beh %>% filter(!is.na(predictions_change)) %>%
  1802. group_by(Treatment, Genotype, Backtransfer_f, ID) %>%
  1803. summarise( Change = mean(predictions_change),
  1804. change_ci025 = mean(predictions_change_ci025),
  1805. change_ci25 = mean(predictions_change_ci25),
  1806. change_ci5 = mean(predictions_change_ci5),
  1807. change_ci75 = mean(predictions_change_ci75),
  1808. change_ci975 = mean(predictions_change_ci975) )
  1809. data_pred_change <- data_pred_change_id %>%
  1810. group_by(Treatment, Genotype, Backtransfer_f) %>%
  1811. summarise(N = n(),
  1812. mean_change = mean(Change),
  1813. change_ci5_se = sd(change_ci5),
  1814. change_ci025 = mean(change_ci025),
  1815. change_ci25 = mean(change_ci25),
  1816. change_ci5 = mean(change_ci5),
  1817. change_ci75 = mean(change_ci75),
  1818. change_ci975 = mean(change_ci975) ,
  1819. se_change = sd(Change))
  1820. g_pp_change_gen <- ggplot(data=data_pred_change) +
  1821. geom_hline(yintercept = 0, linetype = "dashed")+
  1822. geom_point(data = data_change_id, aes(x = Backtransfer_f, y = Change, fill= Treatment, colour= Treatment), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 1, stroke =0.5)+
  1823. geom_errorbar(data= data_pred_change, aes(x = Backtransfer_f, ymin = mean_change - se_change, ymax = mean_change + se_change, group= Treatment), width = 0, position = position_dodge(0.9),size = 1, colour = "black")+
  1824. geom_point(data= data_pred_change, aes( x = Backtransfer_f, y = mean_change, group= Treatment, fill= Treatment), position = position_dodge(0.9), shape = 21, colour = "black", size = 2)+
  1825. # geom_bar(aes(x = Backtransfer_f, y = mean_change, group= Treatment, fill = Treatment), stat = "identity", position = position_dodge()) +
  1826. # geom_errorbar(aes(x = Backtransfer_f, ymin = mean_change - se_change, ymax = mean_change + se_change, group= Treatment), width = 0, position = position_dodge(0.9))+
  1827. theme_Publication(base_size = 10) + theme(legend.position = "none",
  1828. axis.text.x = element_text(size=10),
  1829. panel.grid.major = element_blank()) + #scale_x_discrete(labels = c("Betray", "Equalize")) +
  1830. ylab("Posterior Mean Change (with Std. Dev)") + xlab("Back transfer") + scale_colour_Publication() + scale_fill_Publication()+ facet_wrap(~Genotype) #
  1831. g_pp_model_comp <- plot_grid(p_abs_change_pred+theme(plot.margin = unit(c(0,0,0,0), "cm")), g_investment_pred+theme(plot.margin = unit(c(0,0,0,0), "cm")), g_mu_across_time+theme(plot.margin = unit(c(0,0,0,0), "cm")), nrow = 1, rel_widths = c(0.7,1,1), labels =c("e", "f", "g", "h")) #,
  1832. ggsave("g_pp_model_comp.pdf", plot = g_pp_model_comp, device = cairo_pdf, units = "mm",
  1833. width =179, height = 80, dpi = 600)
  1834. # g_investment_smooth_pred + facet_wrap(~Genotype)
  1835. # g_pp_model_comp <-
  1836. # plot_grid(p_abs_change_pred, g_pp_change_gen,g_investment_pred, ncol = 2, rel_widths = c(1,1), labels =c("a", "b", "c")),
  1837. # plot_grid(g_compare_models,g_compare_models_trials, ncol = 2, rel_widths = c(1,1.3), labels =c("c", "d")),
  1838. # ncol =1,
  1839. # rel_heights = c(1,0.6))
  1840. # g_pp_model_comp
  1841. #
  1842. # pp_title <- ggdraw() + draw_label(
  1843. # "Posterior predictive plots",
  1844. # x = 0,
  1845. # hjust = -0.5
  1846. # )
  1847. # plot_grid(pp_title, g_pp, nrow = 2, rel_heights = c(0.2,1))
  1848. g_pp
  1849. ```
  1850. ```{r rw model output}
  1851. data_group$ag <- get_posterior_mean(M_rw, pars=c('ag'))[,5]
  1852. data_group$al <- get_posterior_mean(M_rw, pars=c('al'))[,5]
  1853. data_group$a_mean <- 1/2*(data_group$ag + data_group$al)
  1854. data_group$mu0_rw <- get_posterior_mean(M_rw, pars=c('mu0'))[,5]
  1855. data_group$noise_rw <- get_posterior_mean(M_rw, pars=c('noise'))[,5]
  1856. g_gen_a_mean <- ggplot(data = data_group, aes(x = drug, y = a_mean))+ # group = ID, linetype = Genotype))
  1857. # geom_violin(aes(fill = drug))+
  1858. geom_boxplot(aes(fill = drug), width=0.5, color="black", outlier.colour = NA)+
  1859. # stat_summary(fun.y=mean, geom="point", shape=20, size=14, color="red", fill="red") +
  1860. geom_point(aes(fill = drug, colour = drug), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1)+
  1861. theme_Publication() +
  1862. theme(axis.ticks.x = element_blank(),
  1863. axis.text.x = element_blank(),
  1864. panel.grid.major = element_blank(),
  1865. legend.position = "none",axis.title.x = element_blank()) +
  1866. ylab(paste("Learning rate - ", expression("\U1D736"))) + # ylab(expression("\U1D714"[good])) +
  1867. xlab("")+ discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462")))
  1868. g_gen_ag <- ggplot(data = data_group, aes(x = drug, y = ag))+ # group = ID, linetype = Genotype))
  1869. # geom_violin(aes(fill = drug))+
  1870. geom_boxplot(aes(fill = drug), width=0.5, color="black", outlier.colour = NA)+
  1871. # stat_summary(fun.y=mean, geom="point", shape=20, size=14, color="red", fill="red") +
  1872. geom_point(aes(fill = drug, colour = drug), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1)+
  1873. theme_Publication() +
  1874. theme(axis.ticks.x = element_blank(),
  1875. axis.text.x = element_blank(),
  1876. panel.grid.major = element_blank(),
  1877. legend.position = "none",
  1878. axis.title.x = element_blank()) +
  1879. ylab(expression("\U1D736"[gain])) + # ylab(expression("\U1D714"[good])) +
  1880. discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462")))
  1881. # g_gen_ag + facet_wrap(~ankk)
  1882. g_gen_al <- ggplot(data = data_group, aes(x = drug, y = al))+ # group = ID, linetype = Genotype))
  1883. # geom_violin(aes(fill = drug))+
  1884. geom_boxplot(aes(fill = drug), width=0.5, color="black", outlier.colour = NA)+
  1885. # stat_summary(fun.y=mean, geom="point", shape=20, size=14, color="red", fill="red") +
  1886. geom_point(aes(fill = drug, colour = drug), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1)+
  1887. theme_Publication() +
  1888. theme(axis.ticks.x = element_blank(),
  1889. axis.text.x = element_blank(),
  1890. panel.grid.major = element_blank(),
  1891. legend.position = "none", axis.title.x = element_blank()) +
  1892. ylab(expression("\U1D736"[loss])) + # ylab(expression("\U1D714"[good])) +
  1893. xlab("")+ discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462")))
  1894. # g_gen_al + facet_wrap(~ankk)
  1895. if (TRUE) {
  1896. pars_beta <- grep("^beta_", names(M_rw), value = T)
  1897. pars_sigma <- grep("^sigma", names(M_rw), value = T)
  1898. pars_beta<- c(pars_beta, pars_sigma)
  1899. # pars_all_model <- pars_all_model[!grepl("^beta_pr", pars_all_model)]
  1900. Pars_posterior_samples <- extract(M_rw, pars = c(pars_beta, 'mu_p[2]') )
  1901. sigma_lr = Pars_posterior_samples$`sigma[1]`
  1902. sigma_lr_trustee = Pars_posterior_samples$`sigma[2]`
  1903. sigma_total = sqrt(sigma_lr^2 + sigma_lr_trustee^2)
  1904. ## effect of sulpiride on lr
  1905. (Pars_posterior_samples$beta_sul+ 1/2*Pars_posterior_samples$beta_sul_ankk) %>% sf(1)
  1906. ( (Pars_posterior_samples$beta_sul+ 1/2*Pars_posterior_samples$beta_sul_ankk)/sigma_total ) %>% sf(1)
  1907. d_rw_sul_a = ( (Pars_posterior_samples$beta_sul+ 1/2*Pars_posterior_samples$beta_sul_ankk)/sigma_total )
  1908. ## effect of sulpiride on lr in A1-
  1909. Pars_posterior_samples$beta_sul %>% sf(1)
  1910. (Pars_posterior_samples$beta_sul/sigma_total) %>% sf(1)
  1911. d_rw_sul_a1p = (Pars_posterior_samples$beta_sul/sigma_total)
  1912. ## effect of sulpiride on lr in A1+
  1913. (Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk) %>% sf(1)
  1914. ( (Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk)/sigma_total ) %>% sf(1)
  1915. d_rw_sul_a1m = ( (Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk)/sigma_total )
  1916. ## interaction effect of sulpiride * genotype on lr
  1917. (Pars_posterior_samples$beta_sul_ankk) %>% sf(1)
  1918. ( (Pars_posterior_samples$beta_sul_ankk)/sigma_total ) %>% sf(1)
  1919. d_rw_sul_gene <- ( (Pars_posterior_samples$beta_sul_ankk)/sigma_total )
  1920. d_rw_lr_diff <- ( (Pars_posterior_samples$`mu_p[2]`)/sigma_total )
  1921. ## effect of sulpiride on lr for gain
  1922. (Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_sul_ankk + 1/2*(Pars_posterior_samples$beta_sul_trustee + 1/2*Pars_posterior_samples$beta_sul_ankk_trustee )) %>% sf(1)
  1923. ((Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_sul_ankk + 1/2*(Pars_posterior_samples$beta_sul_trustee + 1/2*Pars_posterior_samples$beta_sul_ankk_trustee)) /sigma_total) %>% sf(1)
  1924. d_rw_sul_a_gain = (Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_ankk + 1/2*(Pars_posterior_samples$beta_sul_trustee + 1/2*Pars_posterior_samples$beta_sul_ankk_trustee)) /sigma_total
  1925. ## effect of sulpiride on lr for loss
  1926. (Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_sul_ankk - 1/2*(Pars_posterior_samples$beta_sul_trustee + 1/2*Pars_posterior_samples$beta_sul_ankk_trustee )) %>% sf(1)
  1927. ((Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_sul_ankk- 1/2*(Pars_posterior_samples$beta_sul_trustee + 1/2*Pars_posterior_samples$beta_sul_ankk_trustee)) /sigma_total) %>% sf(1)
  1928. d_rw_sul_a_loss = (Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_sul_ankk - 1/2*(Pars_posterior_samples$beta_sul_trustee + 1/2*Pars_posterior_samples$beta_sul_ankk_trustee)) /sigma_total
  1929. # effect of sulpiride on lr in A1- for gain
  1930. (Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_sul_trustee) %>% sf(1)
  1931. ((Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_sul_trustee) /sigma_total) %>% sf(1)
  1932. d_rw_sul_a1p_gain = ((Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_sul_trustee) /sigma_total)
  1933. ## effect of sulpiride on lr in A1- for loss
  1934. (Pars_posterior_samples$beta_sul - 1/2*Pars_posterior_samples$beta_sul_trustee) %>% sf(1)
  1935. ((Pars_posterior_samples$beta_sul - 1/2*Pars_posterior_samples$beta_sul_trustee)/sigma_total) %>% sf(1)
  1936. d_rw_sul_a1p_loss = ((Pars_posterior_samples$beta_sul - 1/2*Pars_posterior_samples$beta_sul_trustee) /sigma_total)
  1937. ## effect of sulpiride on lr in A1+ for gain
  1938. (Pars_posterior_samples$beta_sul + Pars_posterior_samples$beta_sul_ankk + 1/2*(Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee )) %>% sf(1)
  1939. ((Pars_posterior_samples$beta_sul + Pars_posterior_samples$beta_sul_ankk + 1/2*(Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee)) /sigma_total) %>% sf(1)
  1940. d_rw_sul_a1m_gain = (Pars_posterior_samples$beta_sul + Pars_posterior_samples$beta_sul_ankk + 1/2*(Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee)) /sigma_total
  1941. ## effect of sulpiride on lr in A1+ for loss trustee
  1942. (Pars_posterior_samples$beta_sul + Pars_posterior_samples$beta_sul_ankk - 1/2*(Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee )) %>% sf(1)
  1943. ((Pars_posterior_samples$beta_sul + Pars_posterior_samples$beta_sul_ankk - 1/2*(Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee)) /sigma_total) %>% sf(1)
  1944. d_rw_sul_a1m_loss = (Pars_posterior_samples$beta_sul + Pars_posterior_samples$beta_sul_ankk - 1/2*(Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee)) /sigma_total
  1945. ## interaction effect of sulpiride on lr in A1+ trustees
  1946. (Pars_posterior_samples$beta_sul_trustee) %>% sf(1)
  1947. ((Pars_posterior_samples$beta_sul_trustee)/sigma_total) %>% sf(1)
  1948. d_rw_sul_a1p_gainloss =((Pars_posterior_samples$beta_sul_trustee)/sigma_total)
  1949. }
  1950. # d_rw_sul_a, d_rw_sul_a1m, d_rw_sul_a_gain d_rw_sul_a1m_gain
  1951. g_stats_a_ankk <- bind_cols(c_d_sul = d_rw_sul_a,
  1952. b_d_sul_a1p = d_rw_sul_a1p,
  1953. a_d_sul_a1m = d_rw_sul_a1m) %>%
  1954. # convert them to the long format, group, and get the posterior summaries
  1955. pivot_longer(everything()) %>%
  1956. group_by(name) %>%
  1957. summarise(mean = mean(value),
  1958. ll = quantile(value, prob = .025),
  1959. ul = quantile(value, prob = .975),
  1960. lls = quantile(value, prob = .25),
  1961. uls = quantile(value, prob = .75)) %>%
  1962. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  1963. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  1964. geom_vline(xintercept = 0, linetype = "dashed") +
  1965. geom_pointrange(color = "firebrick") +
  1966. labs( y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  1967. theme_Publication(base_size = 10) +
  1968. theme(panel.grid = element_blank(),
  1969. axis.text.x = element_text(size=10),
  1970. strip.background = element_rect(fill = "transparent", color = "transparent"),
  1971. axis.title.x = element_blank()) +
  1972. scale_y_discrete(labels = rev(c("S - P", "S - P in A1+", "S - P in A1-")) )
  1973. # plot_grid(g_abs_change_time + theme(legend.position = "none"), g_stats, nrow = 2, rel_heights = c(1,.3)
  1974. g_stats_ag_ankk <- bind_cols(c_d_sul = d_rw_sul_a_gain,
  1975. b_d_sul_a1p = d_rw_sul_a1p_gain,
  1976. a_d_sul_a1m = d_rw_sul_a1m_gain) %>%
  1977. # convert them to the long format, group, and get the posterior summaries
  1978. pivot_longer(everything()) %>%
  1979. group_by(name) %>%
  1980. summarise(mean = mean(value),
  1981. ll = quantile(value, prob = .025),
  1982. ul = quantile(value, prob = .975),
  1983. lls = quantile(value, prob = .25),
  1984. uls = quantile(value, prob = .75)) %>%
  1985. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  1986. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  1987. geom_vline(xintercept = 0, linetype = "dashed") +
  1988. geom_pointrange(color = "firebrick") +
  1989. labs( y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  1990. theme_Publication(base_size = 10) +
  1991. theme(panel.grid = element_blank(),
  1992. axis.text.x = element_text(size=10),
  1993. strip.background = element_rect(fill = "transparent", color = "transparent"),
  1994. axis.title.x = element_blank()) +
  1995. scale_y_discrete(labels = rev(c("S - P", "S - P in A1+", "S - P in A1-")) )
  1996. g_stats_al_ankk <- bind_cols(c_d_sul = d_rw_sul_a_loss,
  1997. b_d_sul_a1p = d_rw_sul_a1p_loss,
  1998. a_d_sul_a1m = d_rw_sul_a1m_loss) %>%
  1999. # convert them to the long format, group, and get the posterior summaries
  2000. pivot_longer(everything()) %>%
  2001. group_by(name) %>%
  2002. summarise(mean = mean(value),
  2003. ll = quantile(value, prob = .025),
  2004. ul = quantile(value, prob = .975),
  2005. lls = quantile(value, prob = .25),
  2006. uls = quantile(value, prob = .75)) %>%
  2007. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  2008. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  2009. geom_vline(xintercept = 0, linetype = "dashed") +
  2010. geom_pointrange(color = "firebrick") +
  2011. labs( y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  2012. theme_Publication(base_size = 10) +
  2013. theme(panel.grid = element_blank(),
  2014. axis.text.x = element_text(size=10),
  2015. strip.background = element_rect(fill = "transparent", color = "transparent"),
  2016. axis.title.x = element_blank()) +
  2017. scale_y_discrete(labels = rev(c("S - P", "S - P in A1+", "S - P in A1-")) )
  2018. # ylimits = c(-7,0)
  2019. g_rw_lr <- plot_grid(
  2020. g_gen_a_mean + facet_wrap(~ankk), # + coord_cartesian(ylim=ylimits)
  2021. g_gen_ag + facet_wrap(~ankk),
  2022. g_gen_al + facet_wrap(~ankk),
  2023. rel_widths = c(1,1,1), nrow = 1, labels = c("a", "b", "c"))
  2024. title <- ggdraw() +
  2025. draw_label(
  2026. "Effect sizes (means with 50% and 95% CrI)",
  2027. fontface = 'bold' )
  2028. g_lr_stats <- plot_grid(g_rw_lr ,
  2029. g_legend_point_plot,
  2030. plot_grid(g_stats_a_ankk+theme(plot.margin = unit(c(0, 0, 0, 0), "cm")), g_stats_ag_ankk+ theme(plot.margin = unit(c(0, 0, 0, 0), "cm")), g_stats_al_ankk+ theme(plot.margin = unit(c(0, 0, 0, 0), "cm")), rel_widths = c(1,1,1), nrow = 1),
  2031. title,
  2032. nrow = 4, rel_heights = c(1,0.2,0.4,0.1))
  2033. g_lr_stats
  2034. ggsave("g_lr_stats.pdf", plot = g_lr_stats, device = cairo_pdf, units = "mm",
  2035. width =179, height = 100, dpi = 600)
  2036. ggsave("g_lr_stats.png", plot = g_lr_stats, device = "png", units = "mm",
  2037. width =179, height = 100, dpi = 600)
  2038. ```
  2039. Comparing RW and HGF predictions
  2040. ```{r comparing rw and hgf}
  2041. # plotting learning rates and average precision weights
  2042. data_group <- data_group %>% merge(data_beh %>% group_by(ID) %>% summarize(psi =prec_weights_lr_ci5 %>% mean(na.rm = T)) %>% select(ID, psi), by = c("ID"))
  2043. data_group <- data_group %>% merge(data_beh %>% group_by(ID) %>% summarize(psi_last =prec_weights_lr_ci5[25]) %>% select(ID, psi_last), by = c("ID"))
  2044. data_group <- data_group %>% merge(data_beh %>% filter(Trustee == "Good") %>% group_by(ID) %>% summarize(psi_good = prec_weights_lr_ci5 %>% mean(na.rm = T)) %>% select(ID, psi_good), by = c("ID"))
  2045. data_group <- data_group %>% merge(data_beh %>% filter(Trustee == "Bad") %>% group_by(ID) %>% summarize(psi_bad = prec_weights_lr_ci5 %>% mean(na.rm = T)) %>% select(ID, psi_bad), by = c("ID"))
  2046. cor.test(data_group$psi, data_group$a_mean )
  2047. cor.test(data_group$psi , data_group$a_mean )
  2048. cor.test(data_group$psi , data_group$a_mean )
  2049. cor.test(data_group$om_mean , data_group$a_mean )
  2050. cor.test(data_group$gam , data_group$a_mean )
  2051. lm(data = data_group, a_mean %>%log %>% scale ~ om_mean %>% scale * gam %>% log() %>% scale) %>% summary()
  2052. data_group <- data_group %>% mutate(gam_cat = case_when(gam%>% log %>% scale >1 ~1,
  2053. gam%>% log %>% scale < -1 ~-1,
  2054. TRUE ~ 0),
  2055. om_cat = case_when(om_mean %>% scale >1 ~1,
  2056. om_mean %>% scale < -1 ~-1,
  2057. TRUE ~ 0))
  2058. g_rw_hgf_gam <- data_group %>% ggplot( aes(x = om_mean , y = a_mean %>% log() ))+ # group = ID,
  2059. geom_point(data = data_group %>% filter(ankk == "A1+"), aes(fill= drug), shape = 21, colour = "black", size = 2, stroke =1)+
  2060. geom_point(data = data_group %>% filter(ankk == "A1-"), aes(colour= drug), shape = 17, size = 2, stroke =1)+
  2061. geom_smooth(method = "lm", se = F, colour = "black") +
  2062. theme_Publication() +
  2063. theme(panel.grid.major = element_blank(),
  2064. legend.position = "none",axis.title.x = element_blank()) +
  2065. ylab(expression("\U1D736")) + # ylab(expression("\U1D714"[good])) +
  2066. xlab("")+ discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462"))) + facet_wrap(~gam_cat) + scale_colour_Publication()
  2067. g_rw_hgf_om <- data_group %>% ggplot(aes(x = gam %>% log , y = a_mean %>% log() ))+ # group = ID,
  2068. geom_point(data = data_group %>% filter(ankk == "A1+"), aes(fill= drug), shape = 21, colour = "black", size = 2, stroke =1)+
  2069. geom_point(data = data_group %>% filter(ankk == "A1-"), aes(colour= drug), shape = 17, size = 2, stroke =1)+
  2070. geom_smooth(method = "lm", se = F, colour = "black") +
  2071. theme_Publication() +
  2072. theme(panel.grid.major = element_blank(),
  2073. legend.position = "none",axis.title.x = element_blank()) +
  2074. ylab(expression("\U1D736")) + # ylab(expression("\U1D714"[good])) +
  2075. xlab("")+ discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462"))) + scale_colour_Publication()+ facet_wrap(~om_cat)
  2076. if (exists("Comparing_Model_predictions.rds")) {
  2077. df <- readRDS(file = "Comparing_Model_predictions.rds")
  2078. } else {
  2079. prediction_corr_mat = array(NA, c( sample_no, 24, 2 , 2))
  2080. prediction_change_corr_mat= array(NA, c( sample_no, 24, 2 , 2))
  2081. # data_temp = data_temp %>% mutate(Trial_group = (Trial/group_trials) %>% ceiling())
  2082. # sample_no
  2083. for (i in 1 : sample_no ) {
  2084. if (i/(sample_no/100) == i%/%(sample_no/100) ) print(paste(i/sample_no*100, "%"))
  2085. for (tr in 1: 24) {
  2086. y_pred_chain <- Pars_extract_set$y_pred[i,,]
  2087. y_pred_chain_long <- as.vector(t(y_pred_chain))
  2088. y_pred_chain <- Pars_extract_set_rw$y_pred[i,,]
  2089. y_pred_rw_chain_long <- as.vector(t(y_pred_chain))
  2090. prediction_corr_mat[i,tr, 1,1] = cor(y_pred_chain_long[data_temp$Trial == tr &data_temp$Trustee == "Good" ], data_temp$Investment[data_temp$Trial == tr &data_temp$Trustee == "Good" ], use = "complete.obs")
  2091. prediction_change_corr_mat[i,tr, 1,1] = cor(y_pred_change[i,data_temp$Trial == tr &data_temp$Trustee == "Good" ], data_temp$Change[data_temp$Trial == tr &data_temp$Trustee == "Good" ], use = "complete.obs")
  2092. prediction_corr_mat[i,tr, 1,2] = cor(y_pred_rw_chain_long[data_temp$Trial == tr &data_temp$Trustee == "Good" ], data_temp$Investment[data_temp$Trial == tr &data_temp$Trustee == "Good" ], use = "complete.obs")
  2093. prediction_change_corr_mat[i,tr, 1,2] = cor(y_pred_rw_change[i,data_temp$Trial == tr &data_temp$Trustee == "Good" ], data_temp$Change[data_temp$Trial == tr &data_temp$Trustee == "Good" ], use = "complete.obs")
  2094. prediction_corr_mat[i,tr, 2,1] = cor(y_pred_chain_long[data_temp$Trial == tr &data_temp$Trustee == "Bad" ], data_temp$Investment[data_temp$Trial == tr &data_temp$Trustee == "Bad" ], use = "complete.obs")
  2095. prediction_change_corr_mat[i,tr, 2,1] = cor(y_pred_change[i,data_temp$Trial == tr &data_temp$Trustee == "Bad" ], data_temp$Change[data_temp$Trial == tr &data_temp$Trustee == "Bad" ], use = "complete.obs")
  2096. prediction_corr_mat[i,tr, 2,2] = cor(y_pred_rw_chain_long[data_temp$Trial == tr &data_temp$Trustee == "Bad" ], data_temp$Investment[data_temp$Trial == tr &data_temp$Trustee == "Bad" ], use = "complete.obs")
  2097. prediction_change_corr_mat[i,tr, 2,2] = cor(y_pred_rw_change[i,data_temp$Trial == tr &data_temp$Trustee == "Bad" ], data_temp$Change[data_temp$Trial == tr &data_temp$Trustee == "Bad" ], use = "complete.obs")
  2098. }
  2099. }
  2100. df = tibble(r_change = c( prediction_change_corr_mat[,,1,1] %>% colMeans(),
  2101. prediction_change_corr_mat[,,1,1] %>% colMeans(),
  2102. prediction_change_corr_mat[,,2,1] %>% colMeans(),
  2103. prediction_change_corr_mat[,,2,1] %>% colMeans(),
  2104. prediction_change_corr_mat[,,1,2] %>% colMeans(),
  2105. prediction_change_corr_mat[,,1,2] %>% colMeans(),
  2106. prediction_change_corr_mat[,,2,2] %>% colMeans(),
  2107. prediction_change_corr_mat[,,2,2] %>% colMeans()),
  2108. r_investent = c( prediction_corr_mat[,,1,1] %>% colMeans(),
  2109. prediction_corr_mat[,,1,1] %>% colMeans(),
  2110. prediction_corr_mat[,,2,1] %>% colMeans(),
  2111. prediction_corr_mat[,,2,1] %>% colMeans(),
  2112. prediction_corr_mat[,,1,2] %>% colMeans(),
  2113. prediction_corr_mat[,,1,2] %>% colMeans(),
  2114. prediction_corr_mat[,,2,2] %>% colMeans(),
  2115. prediction_corr_mat[,,2,2] %>% colMeans()),
  2116. Trials = rep(c(1:24), 8),
  2117. Trustee = rep( c(rep("Good", 2*24), rep("Bad", 2*24)), 2 ) ,
  2118. Model = c(rep("HGF", 4*24), rep("RW", 4*24)) )
  2119. saveRDS(df, file = "Comparing_Model_predictions.rds")
  2120. }
  2121. df$Model = factor(df$Model, labels = c("HGF M1", "RW"))
  2122. g_rw_hgf_investments <- df %>% ggplot(aes(x = Trials, y = r_investent, colour = Model)) + geom_smooth() + facet_wrap(~Trustee) + theme_Publication()+ ylab("Correlation between investments and\nmodel predicted investments")+discrete_scale("colour","Publication",manual_pal(values = c("#9c6a5a","#4e767e")))+theme(legend.title = element_blank(),legend.position = "bottom")
  2123. g_model_comparison_figure = plot_grid(plot_grid(g_compare_models + theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")), g_compare_models_trials+theme(legend.position = "none", plot.margin = unit(c(0.2,0.2,0,0.2), "cm")), g_rw_hgf_investments+theme(legend.position = "none", plot.margin = unit(c(0.2,0.2,0,0.2), "cm")),nrow = 1, rel_widths = c(0.7,1,1.1), labels = "auto"),
  2124. get_legend(g_rw_hgf_investments),
  2125. ncol = 1,
  2126. rel_heights = c(1,0.2))
  2127. g_model_comparison_figure
  2128. ggsave("g_model_comparison_figure.pdf", plot = g_model_comparison_figure, device = cairo_pdf, units = "mm",
  2129. width =179, height = 50, dpi = 600)
  2130. ```
  2131. # Plotting precision weighted lr ----------------
  2132. ```{r precision weights}
  2133. data_prc_weights_lr_mean_id <-
  2134. data_beh %>% filter(!is.na(prec_weights)) %>%
  2135. group_by(ID) %>%
  2136. summarize(Treatment=Treatment[1],
  2137. Genotype=Genotype[1],
  2138. Serum = Serum[1],
  2139. mean_perID_prec_weights_lr = mean(prec_weights_lr),
  2140. prec_weights_lr_ci025 = mean(prec_weights_lr_ci025),
  2141. prec_weights_lr_ci25 = mean(prec_weights_lr_ci25),
  2142. prec_weights_lr_ci5 = mean(prec_weights_lr_ci5),
  2143. prec_weights_lr_ci75 = mean(prec_weights_lr_ci75),
  2144. prec_weights_lr_ci975 = mean(prec_weights_lr_ci975))
  2145. data_prc_weights_lr_mean <- data_prc_weights_lr_mean_id %>%
  2146. group_by(Treatment, Genotype) %>%
  2147. summarize(N =n(),
  2148. mean_prec_weights_lr = mean(mean_perID_prec_weights_lr),
  2149. se_prec_weights_lr = sd(mean_perID_prec_weights_lr)/sqrt(N),
  2150. prec_weights_lr_ci025 = mean(prec_weights_lr_ci025),
  2151. prec_weights_lr_ci25 = mean(prec_weights_lr_ci25),
  2152. prec_weights_lr_ci5 = mean(prec_weights_lr_ci5),
  2153. prec_weights_lr_ci75 = mean(prec_weights_lr_ci75),
  2154. prec_weights_lr_ci975 = mean(prec_weights_lr_ci975))
  2155. g_prc_weights_lr_mean <-
  2156. data_prc_weights_lr_mean %>%
  2157. ggplot(aes(x=Treatment)) +
  2158. geom_point(data = data_prc_weights_lr_mean_id, aes(y = prec_weights_lr_ci5, fill= Treatment, colour= Treatment), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.3), shape = 21, colour = "black", size = 2, stroke =1) +
  2159. geom_errorbar(aes(ymin = prec_weights_lr_ci25, ymax = prec_weights_lr_ci75), width = 0, size =2)+
  2160. geom_errorbar(aes(ymin = prec_weights_lr_ci025, ymax = prec_weights_lr_ci975), width = 0, size =1)+
  2161. geom_point(aes(x=Treatment, y= prec_weights_lr_ci5, fill = Treatment), position = position_dodge(1), shape = 21, colour = "black",size = 4) +
  2162. facet_wrap(~Genotype) + theme_Publication() + theme(axis.text.x = element_blank(),
  2163. axis.ticks.x = element_blank(),
  2164. legend.position = "none",
  2165. panel.grid.major = element_blank())+
  2166. # title = element_blank()) +
  2167. xlab("")+
  2168. ylab(expression(paste("Mean precision-weights - ", bold(bar("\U1D713"))))) + scale_colour_Publication() + scale_fill_Publication()
  2169. g_prc_weights_lr_mean
  2170. # data_prc_weights_mean_id
  2171. # if prec_weights_lr_sul does not exists you need to calculate it again from prec_weights_lr_mat
  2172. # prec_weights_lr_mat %>% dim()
  2173. prec_weights_lr_mat <- readRDS("Data4PlottingPrecWeightedLearningRates.rds")
  2174. sd_per_sample = prec_weights_lr_mat %>% apply(1, sd)
  2175. prec_weights_lr_mat %>% glimpse
  2176. prec_weights_lr_mat_d <- prec_weights_lr_mat/sd_per_sample
  2177. prec_weights_lr_sul <- prec_weights_lr_mat_d %>% apply(1, function(x) { return(mean(x[data_beh$Treatment == "sulpiride"]) - mean(x[data_beh$Treatment != "sulpiride"]))})
  2178. prec_weights_lr_ankk <- prec_weights_lr_mat_d %>% apply(1, function(x) { return(mean(x[data_beh$Genotype == "A1+"]) - mean(x[data_beh$Genotype != "A1+"]))})
  2179. prec_weights_lr_sul_a1p <- prec_weights_lr_mat_d %>% apply(1, function(x) { return(mean(x[data_beh$Treatment == "sulpiride" & data_beh$Genotype == "A1+"]) - mean(x[data_beh$Treatment != "sulpiride" & data_beh$Genotype == "A1+"]))})
  2180. prec_weights_lr_sul_a1m <- prec_weights_lr_mat_d %>% apply(1, function(x) { return(mean(x[data_beh$Treatment == "sulpiride"& data_beh$Genotype == "A1-" ]) - mean(x[data_beh$Treatment != "sulpiride" & data_beh$Genotype == "A1-"]))})
  2181. prec_weights_lr_sul_ankk <- prec_weights_lr_mat_d %>%
  2182. apply(1, function(x) {
  2183. d_sul_a1p = mean(x[data_beh$Treatment == "sulpiride" & data_beh$Genotype == "A1+"]) - mean(x[data_beh$Treatment != "sulpiride" & data_beh$Genotype == "A1+"])
  2184. d_sul_a1m = mean(x[data_beh$Treatment == "sulpiride" & data_beh$Genotype != "A1+"]) - mean(x[data_beh$Treatment != "sulpiride" & data_beh$Genotype != "A1+"])
  2185. return(
  2186. d_sul_a1p - d_sul_a1m
  2187. )
  2188. }
  2189. )
  2190. prec_weights_lr_sul_a1m <- prec_weights_lr_mat_d %>% apply(1, function(x) { return(mean(x[data_beh$Treatment == "sulpiride"& data_beh$Genotype == "A1-" ]) - mean(x[data_beh$Treatment != "sulpiride" & data_beh$Genotype == "A1-"]))})
  2191. prec_weights_lr_sul%>% sf(1)
  2192. prec_weights_lr_sul_ankk %>% sf(1)
  2193. prec_weights_lr_sul_a1p %>% sf(1)
  2194. prec_weights_lr_sul_a1m %>% sf(1)
  2195. data_stat_prc_weights_lr <- bind_cols(c_d_sul = prec_weights_lr_sul,
  2196. b_d_sul_a1p = prec_weights_lr_sul_a1p,
  2197. a_d_sul_a1m = prec_weights_lr_sul_a1m) %>%
  2198. # convert them to the long format, group, and get the posterior summaries
  2199. pivot_longer(everything()) %>%
  2200. group_by(name) %>%
  2201. summarise(mean = mean(value),
  2202. ll = quantile(value, prob = .025),
  2203. ul = quantile(value, prob = .975),
  2204. lls = quantile(value, prob = .25),
  2205. uls = quantile(value, prob = .75))
  2206. g_stat_prc_weights_lr <- data_stat_prc_weights_lr %>% ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  2207. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  2208. geom_vline(xintercept = 0, linetype="dashed") +
  2209. geom_pointrange(color = "firebrick") +
  2210. labs(y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  2211. theme_Publication(base_size = 10) +
  2212. theme(panel.grid = element_blank(),
  2213. axis.text.x = element_text(size=10),
  2214. strip.background = element_rect(fill = "transparent", color = "transparent"),
  2215. axis.title.x = element_blank()) +
  2216. scale_y_discrete(labels = rev(c("S - P", "S - P in A1+", "S - P in A1-")) )
  2217. # plot_grid(g_abs_change_time + theme(legend.position = "none"), g_stats, nrow = 2, rel_heights = c(1,.3)
  2218. ```
  2219. Plotting weights with serum
  2220. ```{r prc weights with serum, fig.width= 4}
  2221. # data_beh %>% glimpse()
  2222. data_serum_id <- data_prc_weights_lr_mean_id %>% filter(Treatment == "sulpiride")
  2223. g_serum <-data_serum_id %>% filter(Genotype == "A1+") %>% ggplot(aes(x=log(Serum), y = prec_weights_lr_ci5)) +
  2224. geom_point(fill= "#fdb462", alpha = 0.3, shape = 21, colour = "black", size = 2, stroke =1) +
  2225. geom_smooth(method = "lm", se = FALSE, colour = "black")+ theme_Publication() + theme(axis.text.x = element_blank(),
  2226. axis.ticks.x = element_blank(),
  2227. legend.position = "none",
  2228. panel.grid.major = element_blank())+
  2229. # title = element_blank()) +
  2230. ylab(expression(paste("Mean precision-weights - ", bold(bar("\U1D713"))))) + xlab(expression("Serum")) + facet_wrap(~Genotype)+
  2231. scale_y_continuous(breaks = c(0.5,1,1.5))
  2232. g_serum
  2233. data_serum_id$logserum_s <- scale(log(data_serum_id$Serum))
  2234. data_serum_id$serum_s <- scale(data_serum_id$Serum)
  2235. data_serum_id$prec_weights_lr_ci5_s <- scale(data_serum_id$prec_weights_lr_ci5)
  2236. #
  2237. # model1 <- lm(data = data_serum_id, mean_perID_prec_weights_lr_s ~ serum_s*Genotype )
  2238. #
  2239. # model1 <- lm(data = data_serum_id, log(prec_weights_lr_ci5) ~ logserum_s*Genotype )
  2240. # summary(model1)
  2241. #
  2242. data_sul = data_beh %>% filter(Treatment == "sulpiride")
  2243. options(mc.cores=4)
  2244. if (!file.exists("Behavioral Models/brm_serum.rds")) {
  2245. brms_serum <- brm(data = data_sul, prec_weights_lr_ci5_s ~ logserum_s*Genotype + (1|ID),
  2246. prior = c(set_prior("normal(0,1)", class = "b"),
  2247. set_prior("cauchy(0,2)", class = "sd")),
  2248. warmup = 500, iter = 2000, chains =4)
  2249. saveRDS(brms_serum2, file ="Behavioral Models/brm_serum.rds")
  2250. } else brms_serum <- readRDS(file ="Behavioral Models/brm_serum.rds")
  2251. brms_serum%>% fixef()%>% round(3) %>% write.csv("brms_serum.csv")
  2252. post_serum = posterior_samples(brms_serum)
  2253. post_serum <- post_serum %>% mutate(sd_total = sqrt(sd_ID__Intercept^2 + sigma^2))
  2254. post_serum <- post_serum/post_serum$sd_total
  2255. # sd_total post_serum$sd_ID__Intercept
  2256. (post_serum$b_logserum_s +1/2*post_serum$`b_logserum_s:GenotypeA1M`) %>% sf(1)
  2257. post_serum$b_logserum_s %>% sf(1)
  2258. (post_serum$b_logserum_s +post_serum$`b_logserum_s:GenotypeA1M` )%>% sf(1)
  2259. g_stat_prc_weights_lr_serum <- bind_cols(c_d_sul = post_serum$b_logserum_s +1/2*post_serum$`b_logserum_s:GenotypeA1M` ,
  2260. b_d_sul_a1p = post_serum$b_logserum_s,
  2261. a_d_sul_a1m = post_serum$b_logserum_s +post_serum$`b_logserum_s:GenotypeA1M`) %>%
  2262. # convert them to the long format, group, and get the posterior summaries
  2263. pivot_longer(everything()) %>%
  2264. group_by(name) %>%
  2265. summarise(mean = mean(value),
  2266. ll = quantile(value, prob = .025),
  2267. ul = quantile(value, prob = .975),
  2268. lls = quantile(value, prob = .25),
  2269. uls = quantile(value, prob = .75)) %>%
  2270. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  2271. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  2272. geom_vline(xintercept = 0, linetype="dashed") +
  2273. geom_pointrange(color = "firebrick") +
  2274. labs(y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  2275. theme_Publication(base_size = 10) +
  2276. theme(panel.grid = element_blank(),
  2277. axis.text.x = element_text(size=10),
  2278. strip.background = element_rect(fill = "transparent", color = "transparent"),
  2279. axis.title.x = element_blank()) +
  2280. scale_y_discrete(labels = rev(c("Serum", "Serum in A1+", "Serum in A1-")) ) +
  2281. scale_x_continuous(breaks = c(0,0.3,0.6))
  2282. ```
  2283. # modelling results figure
  2284. ```{r modeling figure}
  2285. ylimits = c(-7,0)
  2286. g_om <- plot_grid(
  2287. g_gen_om_mean + coord_cartesian(ylim=ylimits) + facet_wrap(~ankk) + theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")),
  2288. g_prc_weights_lr_mean + theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")),
  2289. g_serum + theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")),
  2290. rel_widths = c(0.7, 1,0.7,0.7), nrow = 1, labels = c("a", "b", "c"))
  2291. title <- ggdraw() +
  2292. draw_label(
  2293. "Effect sizes (means with 50% and 95% CrI)",
  2294. fontface = 'bold')
  2295. g_om_stats <- plot_grid(g_om,
  2296. g_legend_point_plot,
  2297. plot_grid(g_stats_om_ankk+ theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")), g_stat_prc_weights_lr+ theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")), g_stat_prc_weights_lr_serum+ theme(plot.margin = unit(c(0.2,0.2,0,0.2), "cm")), rel_widths = c(1,1,1), nrow = 1),
  2298. title,
  2299. ncol = 1, rel_heights = c(1,0.2,0.4,0.1))
  2300. ggsave("g_om_stats.pdf", plot = g_om_stats, device = cairo_pdf, units = "mm",
  2301. width =179, height = 100, dpi = 600)
  2302. g_prc_weights <- plot_grid(
  2303. g_prc_weights_lr_mean,
  2304. g_serum, labels = c("c", "d"),
  2305. rel_widths = c(1,1), nrow = 1)
  2306. g_prc_all <- plot_grid(g_prc_weights,
  2307. plot_grid(g_stat_prc_weights_lr,
  2308. g_stat_prc_weights_lr_serum,
  2309. nrow = 1, labels = c("g","h")),
  2310. nrow = 2, rel_heights = c(1,0.4))
  2311. g_prc_all
  2312. g_figure3_modelling_results <- plot_grid(g_om_stats,g_prc_all, rel_widths = c(1,0.8))
  2313. g_figure3_modelling_results_different_arrangement <-
  2314. plot_grid(
  2315. #row 1
  2316. title1,
  2317. g_om,
  2318. #row 2
  2319. title_d,
  2320. plot_grid(g_stats_om_ankk, g_stats_om_a1_p_trustee, labels = c("c", "d") , rel_widths = c(0.85,1)),
  2321. #row 3
  2322. title2,
  2323. plot_grid( g_prc_weights_lr_mean,
  2324. g_serum, labels = c("e", "f"),
  2325. rel_widths = c(1,1), nrow = 1),
  2326. #row 4
  2327. title_d,
  2328. plot_grid(g_stat_prc_weights_lr,
  2329. g_stat_prc_weights_lr_serum,
  2330. nrow = 1, labels = c("g","h")),
  2331. nrow = 8, rel_heights = c(0.2,1,0.2,0.4,0.2,1,0.2,0.4))
  2332. title1 <- ggdraw() +
  2333. draw_label(
  2334. "Effects of sulpiride on Belief Volatility",
  2335. x = 0,
  2336. hjust = 0.5
  2337. )
  2338. title_d <-
  2339. ggdraw() +
  2340. draw_label(
  2341. "Effect sizes",
  2342. x = 0,
  2343. hjust = 0.5
  2344. )
  2345. title2 <- ggdraw() +
  2346. draw_label(
  2347. "Effects of sulpiride on Precision-weighted learning rates",
  2348. x = 0,
  2349. hjust = 0
  2350. )
  2351. model_com_title <- ggdraw() +
  2352. draw_label(
  2353. "Model Comparison",
  2354. x = 0,
  2355. hjust = -0.5
  2356. )
  2357. ```
  2358. Look at Gamma and incongruent trials
  2359. ```{r gam plot with incongruent trials}
  2360. # g_legend_model <- get_legend(g_gen_om_mean +
  2361. # theme(legend.position = "right",
  2362. # legend.key = element_rect(colour = NA),
  2363. # legend.direction = "horizontal",
  2364. # legend.key.size= unit(0.2, "cm"),
  2365. # # legend.margin = unit(0, "cm"),
  2366. # legend.title = element_blank()))
  2367. # plot_grid(g_model, g_legend_model, rel_widths = c(1,.2))
  2368. g_gam <- g_gen_gam + facet_wrap(~ankk)
  2369. # g_serum
  2370. ```
  2371. # model posterior predictive checks ----------------
  2372. plotting the posterior predictive checks for reciprocity and incongruency
  2373. ```{r, fig.width = 10, fig.height = 9, echo=FALSE, warning= FALSE}
  2374. if(!exists("theme_Publication", mode = "function")) source("theme_functions.r")
  2375. g_pred_incon <- ggplot(data_plot_model_pred, aes(x = drug, y = mean_incon))+
  2376. geom_errorbar(aes(ymin = mean_incon - se_incon, ymax = mean_incon + se_incon), size = 1.5, width = 0) +
  2377. geom_point(aes(x=drug, y= mean_incon, colour = drug), size = 5, shape = 18) +
  2378. theme_Publication() +theme(axis.text.x = element_blank(),
  2379. axis.ticks.x = element_blank(),
  2380. panel.grid.major = element_blank(),
  2381. legend.key.size = unit(0.5, "cm"),
  2382. legend.position= "none",
  2383. axis.title.x = element_blank()) +
  2384. ylab("Incongruent Trials") + scale_colour_Publication()
  2385. g_pred_pos <- ggplot(data_plot_model_pred, aes(x = drug, y = mean_posrec))+
  2386. geom_errorbar(aes(ymin = mean_posrec - se_posrec, ymax = mean_posrec + se_posrec), width = 0, size = 1.5)+
  2387. geom_point(aes(x=drug, y= mean_posrec, colour = drug), size = 5, shape = 18) +
  2388. theme_Publication() + theme(axis.text.x = element_blank(),
  2389. legend.position = "none",
  2390. axis.ticks.x = element_blank(),
  2391. panel.grid.major = element_blank(),
  2392. axis.title.x = element_blank()) +
  2393. ylab("Reciprocal Trials") + scale_colour_Publication()# '' +
  2394. # coord_cartesian(ylim = c(13,19))
  2395. # g_pred_pos
  2396. g_pred_neg <- ggplot(data_plot_model_pred, aes(x = drug, y = mean_negrec))+
  2397. geom_errorbar(aes(ymin = mean_negrec - se_negrec, ymax = mean_negrec + se_negrec), width = 0, size = 1.5)+
  2398. geom_point(aes(x=drug, y= mean_negrec, colour = drug), size = 5, shape = 18) +
  2399. theme_Publication() + theme(axis.text.x = element_blank(),
  2400. legend.position = "none",
  2401. axis.ticks.x = element_blank(),
  2402. panel.grid.major = element_blank(),
  2403. axis.title.x = element_blank()) +
  2404. ylab("Reciprocal Trials") + scale_colour_Publication()# '' +
  2405. # coord_cartesian(ylim = c(13,19))
  2406. # g_pred_neg
  2407. g_pred_rec <- ggplot(data_plot_model_pred, aes(x = drug, y = mean_rec))+
  2408. geom_errorbar(aes(ymin = mean_rec - se_rec, ymax = mean_rec + se_rec), width = 0, size = 1.5)+
  2409. geom_point(aes(x=drug, y= mean_rec, colour = drug), size = 5, shape = 18) +
  2410. theme_Publication() + theme(axis.text.x = element_blank(),
  2411. legend.position = "none",
  2412. axis.ticks.x = element_blank(),
  2413. panel.grid.major = element_blank(),
  2414. axis.title.x = element_blank()) +
  2415. ylab("Reciprocal Trials") + scale_colour_Publication()# '' +
  2416. # coord_cartesian(ylim = c(13,19))
  2417. # g_pred_rec
  2418. #
  2419. #
  2420. # ```{r}
  2421. # fig_trials <- plot_grid(g_incon, g_rec, rel_widths = c(1, 1.6))
  2422. # fig_trials
  2423. g_pred_incon_gen <- ggplot(data_plot_model_pred_gen, aes(x = drug, y = mean_incon))+
  2424. geom_errorbar(aes(ymin = mean_incon - se_incon, ymax = mean_incon + se_incon, group = drug), width = 0, size = 1.5, position = position_dodge(0.2)) +
  2425. geom_point(aes(x=drug, y= mean_incon, colour = drug), size = 5, position = position_dodge(0.2), shape = 18) +
  2426. facet_wrap(~ankk) + ylab("") + theme_Publication() +theme(axis.text.x = element_blank(),
  2427. axis.ticks.x = element_blank(),
  2428. legend.position = "none",
  2429. panel.grid.major = element_blank(),
  2430. axis.title.x = element_blank()) +
  2431. scale_colour_Publication()
  2432. # coord_cartesian(ylim = c(0,10))
  2433. # g_pred_incon_gen
  2434. g_pred_rec_gen <- ggplot(data_plot_model_pred_gen, aes(x = drug, y = mean_rec))+
  2435. geom_errorbar(aes(ymin = mean_rec - se_rec, ymax = mean_rec + se_rec), width = 0, size =1.5)+
  2436. geom_point(aes(x=drug, y= mean_rec, colour = drug), size = 5, shape = 18) +
  2437. facet_wrap(~ankk) + theme_Publication() +theme(axis.text.x = element_blank(),
  2438. axis.ticks.x = element_blank(),
  2439. legend.position = "none",
  2440. panel.grid.major = element_blank(),
  2441. axis.title.x = element_blank(),
  2442. title = element_blank()) +
  2443. ylab("") + scale_colour_Publication()
  2444. # g_pred_rec_gen
  2445. g_pred_posrec_gen <- ggplot(data_plot_model_pred_gen, aes(x = drug, y = mean_posrec))+
  2446. geom_errorbar(aes(ymin = mean_posrec - se_posrec, ymax = mean_posrec + se_posrec), width = 0, size =1.5)+
  2447. geom_point(aes(x=drug, y= mean_posrec, colour = drug), size = 5, shape = 18) +
  2448. facet_wrap(~ankk) + theme_Publication() +theme(axis.text.x = element_blank(),
  2449. axis.ticks.x = element_blank(),
  2450. legend.position = "none",
  2451. panel.grid.major = element_blank(),
  2452. axis.title.x = element_blank(),
  2453. title = element_blank()) +
  2454. ylab("") + scale_colour_Publication()
  2455. g_pred_negrec_gen <- ggplot(data_plot_model_pred_gen, aes(x = drug, y = mean_negrec))+
  2456. geom_errorbar(aes(ymin = mean_negrec - se_negrec, ymax = mean_negrec + se_negrec), width = 0, size =1.5)+
  2457. geom_point(aes(x=drug, y= mean_negrec, colour = drug), size = 5, shape = 18) +
  2458. facet_wrap(~ankk) + theme_Publication() +theme(axis.text.x = element_blank(),
  2459. axis.ticks.x = element_blank(),
  2460. legend.position = "none",
  2461. panel.grid.major = element_blank(),
  2462. axis.title.x = element_blank(),
  2463. title = element_blank()) +
  2464. ylab("") + scale_colour_Publication()
  2465. g_legend <- get_legend(g_pred_rec_gen +
  2466. theme(legend.position = "right",
  2467. legend.key = element_rect(colour = NA),
  2468. legend.direction = "horizontal",
  2469. legend.key.size= unit(0.2, "cm"),
  2470. # legend.margin = unit(0, "cm"),
  2471. legend.title = element_blank()))
  2472. g_pred_trials_gen <- plot_grid(
  2473. plot_grid(g_pred_rec+labs(title=""),g_pred_rec_gen, ncol=2, rel_widths = c(0.6,1) , labels = c('a','b'), label_size = 20),
  2474. plot_grid(g_pred_incon+labs(title=""),g_pred_incon_gen, ncol=2, rel_widths = c(0.6,1),labels = c('c','d'), label_size = 20),
  2475. g_legend,
  2476. ncol =1, rel_heights = c(1,1,0.1)
  2477. )
  2478. g_pred_trials_gen
  2479. ```
  2480. # single round social interaction tasks
  2481. ```{r, fig.width = 7, fig.height = 8}
  2482. # # negative reciprocity plot ----------------------------------------------------
  2483. #
  2484. levels(data_beh_SI$Treatment) <- c("control", "sulpride")
  2485. savemodelname = "brms_negrec_genotype.rds"
  2486. if(!file.exists(paste("Behavioral Models/", savemodelname, sep = ""))){
  2487. brms_negrec_genotype <- update(mc.negrec.treatment,
  2488. formula. = ~ . + Treatment*genotype,
  2489. newdata = data_beh_SI_neg_rec_analysis)
  2490. saveRDS(brms_negrec_genotype, file = paste("Behavioral Models/", savemodelname, sep=""))
  2491. } else brms_negrec_genotype <- readRDS("Behavioral Models/brms_negrec_genotype.rds")
  2492. data_beh_SI_neg_rec_analysis <- data_beh_SI %>% filter(BDoesTransfer ==0, !is.na(BDoesTransfer))
  2493. # data_beh_SI_neg_rec_analysis
  2494. brms_negrec_genotype %>% fixef()%>% round(3) %>% write.csv("brms_negrec_genotype.csv")
  2495. model_pp <- fitted(brms_negrec_genotype, newdata = data_beh_SI_neg_rec_analysis , re_formula = NA, summary = FALSE)
  2496. # a<- model_pp %>% apply(2, quantile, probs = c(0.5))
  2497. # model_pp %>% glimpse()
  2498. model_pp_neg_rec <- data_beh_SI_neg_rec_analysis
  2499. model_pp_neg_rec <- model_pp_neg_rec %>% mutate(Est = model_pp %>% apply(2, quantile, probs = c(0.5)),
  2500. Q2.5 =model_pp %>% apply(2, quantile, probs = c(0.025)),
  2501. Q25 = model_pp %>% apply(2, quantile, probs = c(0.25)),
  2502. Q75 = model_pp %>% apply(2, quantile, probs = c(0.75)),
  2503. Q975 = model_pp %>% apply(2, quantile, probs = c(0.975)))
  2504. # model_pp_neg_rec %>% glimpse()
  2505. # model_pp_neg_rec
  2506. # plot(model_pp_all$Est[model_pp_all$ID == 1], model_pp_all$Est[model_pp_all$ID == 5])
  2507. # model_pp <- cbind(model_pp, data_beh)
  2508. data_neg_rec_id <- model_pp_neg_rec %>% group_by(ID, Treatment, genotype) %>%
  2509. summarize(mean_pun_id = mean(Punishment))
  2510. g_punishment<- ggplot(data= model_pp_neg_rec) +
  2511. geom_point(data = data_neg_rec_id, aes(x = Treatment, y = mean_pun_id, fill= Treatment, colour= Treatment), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.5), shape = 21, colour = "black", size = 2, stroke =1)+
  2512. # geom_errorbar(data= model_pp_rec, aes(x = Treatment, ymin = Q25, ymax = Q75, group= Treatment), width = 0, position = position_dodge(0.9),size = 2)+
  2513. geom_errorbar(aes(x = Treatment, ymin = Q2.5, ymax = Q975, group= Treatment), width = 0, position = position_dodge(0.9),size = 1.5)+
  2514. geom_point(aes(x = Treatment, y = Est, fill= Treatment, colour= Treatment), position = position_dodge(0.9), size = 3, shape= 21, colour = "black")+
  2515. # geom_bar(aes(x = Backtransfer_f, y = mean_change, group= Treatment, fill = Treatment), stat = "identity", position = position_dodge()) +
  2516. # geom_errorbar(aes(x = Backtransfer_f, ymin = mean_change - se_change, ymax = mean_change + se_change, group= Treatment), width = 0, position = position_dodge(0.9))+
  2517. theme_Publication(base_size = 10) + theme(legend.position = "none",
  2518. axis.text.x = element_blank(),
  2519. axis.ticks.x = element_blank(),
  2520. axis.title.x = element_blank(),
  2521. panel.grid.major = element_blank()) + #scale_x_discrete(labels = c("Betray", "Equalize")) +
  2522. ylab("Mean Punishment") + scale_colour_Publication() + scale_fill_Publication()#
  2523. if (FALSE) {
  2524. post = posterior_samples(brms_negrec_genotype )
  2525. # back to absolute scale
  2526. # turn to effect size
  2527. post <- post %>% mutate(sd_total = sqrt(sd_ID__Intercept^2 + sigma^2))
  2528. post <- post/post$sd_total
  2529. post_neg_rec <- post
  2530. d_sul <- (post$b_Treatmentsulpride + 1/2*post$`b_Treatmentsulpride:genotypeA1M`)
  2531. d_sul%>% sf(1)
  2532. d_sul_a1p<- (post$b_Treatmentsulpride)
  2533. d_sul_a1p %>% sf(1)
  2534. d_sul_a1m<- (post$b_Treatmentsulpride + post$`b_Treatmentsulpride:genotypeA1M`)
  2535. d_sul_a1m %>% sf(1)
  2536. }
  2537. g_stats_negrec <- bind_cols(C_Sul = d_sul,
  2538. B_Sul =d_sul_a1p,
  2539. A_Sul =d_sul_a1m) %>%
  2540. # convert them to the long format, group, and get the posterior summaries
  2541. pivot_longer(everything()) %>%
  2542. group_by(name) %>%
  2543. summarise(mean = mean(value),
  2544. ll = quantile(value, prob = .025),
  2545. ul = quantile(value, prob = .975),
  2546. lls = quantile(value, prob = .25),
  2547. uls = quantile(value, prob = .75)) %>% # since the `key` variable is really two variables in one, here we split them up
  2548. # plot!
  2549. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  2550. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  2551. geom_vline(xintercept = 0, linetype="dashed") +
  2552. geom_pointrange(color = "firebrick") +
  2553. labs(y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  2554. theme_Publication(base_size = 10) +
  2555. theme(panel.grid = element_blank(),
  2556. axis.text.x = element_text(size=10, ),
  2557. strip.background = element_rect(fill = "transparent", color = "transparent"),
  2558. axis.title.x = element_blank()) +
  2559. scale_y_discrete(labels = rev(c("S - P", "S - P in A1+", "S - P in A1-")) )
  2560. ```
  2561. ```{r positive reciprocity}
  2562. # positive reciprocity ####
  2563. savemodelname = "brms_posrec_genotype.rds"
  2564. if(!file.exists(paste("Behavioral Models/", savemodelname, sep = ""))){
  2565. brms_posrec_genotype <- update(mc.posrec.treatment,
  2566. formula. = ~ . + Treatment*genotype,
  2567. newdata = data_beh_SI_pos_rec_analysis)
  2568. saveRDS(brms_posrec_genotype, file = paste("Behavioral Models/", savemodelname, sep=""))
  2569. }else brms_posrec_genotype <- readRDS("Behavioral Models/brms_posrec_genotype.rds")
  2570. data_beh_SI_pos_rec_analysis <- data_beh_SI %>% filter(Implement ==0, !is.na(Implement))
  2571. # data_beh_SI_neg_rec_analysis
  2572. brms_posrec_genotype %>% fixef()%>% round(3) %>% write.csv("brms_posrec_genotype.csv")
  2573. model_pp <- fitted(brms_posrec_genotype, newdata = data_beh_SI_pos_rec_analysis, re_formula = NA, summary = FALSE)
  2574. # a<- model_pp %>% apply(2, quantile, probs = c(0.5))
  2575. # model_pp %>% glimpse()
  2576. model_pp_pos_rec <- data_beh_SI_pos_rec_analysis
  2577. model_pp_pos_rec <- model_pp_pos_rec %>% mutate(Est = model_pp %>% apply(2, quantile, probs = c(0.5)),
  2578. Q2.5 =model_pp %>% apply(2, quantile, probs = c(0.025)),
  2579. Q25 = model_pp %>% apply(2, quantile, probs = c(0.25)),
  2580. Q75 = model_pp %>% apply(2, quantile, probs = c(0.75)),
  2581. Q975 = model_pp %>% apply(2, quantile, probs = c(0.975)))
  2582. # model_pp_neg_rec %>% glimpse()
  2583. # model_pp_neg_rec
  2584. # plot(model_pp_all$Est[model_pp_all$ID == 1], model_pp_all$Est[model_pp_all$ID == 5])
  2585. # model_pp <- cbind(model_pp, data_beh)
  2586. data_pos_rec_id <- model_pp_pos_rec %>% group_by(ID, Treatment, genotype) %>%
  2587. summarize(mean_rew_id = mean(RewardA))
  2588. g_reward <- ggplot(data= model_pp_pos_rec) +
  2589. geom_point(data = data_pos_rec_id, aes(x = Treatment, y = mean_rew_id, fill= Treatment, colour= Treatment), alpha = 0.3, position = position_jitterdodge(dodge.width= 0.9, jitter.width = 0.5), shape = 21, colour = "black", size = 2, stroke =1)+
  2590. # geom_errorbar(data= model_pp_rec, aes(x = Treatment, ymin = Q25, ymax = Q75, group= Treatment), width = 0, position = position_dodge(0.9),size = 2)+
  2591. geom_errorbar(aes(x = Treatment, ymin = Q2.5, ymax = Q975, group= Treatment), width = 0, position = position_dodge(0.9),size = 1.5)+
  2592. geom_point(aes(x = Treatment, y = Est, fill= Treatment, colour= Treatment), position = position_dodge(0.9), size = 3, shape= 21, colour = "black")+
  2593. # geom_bar(aes(x = Backtransfer_f, y = mean_change, group= Treatment, fill = Treatment), stat = "identity", position = position_dodge()) +
  2594. # geom_errorbar(aes(x = Backtransfer_f, ymin = mean_change - se_change, ymax = mean_change + se_change, group= Treatment), width = 0, position = position_dodge(0.9))+
  2595. theme_Publication(base_size = 10) + theme(legend.position = "none",
  2596. axis.text.x = element_blank(),
  2597. axis.ticks.x = element_blank(),
  2598. axis.title.x = element_blank(),
  2599. panel.grid.major = element_blank()) + #scale_x_discrete(labels = c("Betray", "Equalize")) +
  2600. ylab("Mean Back-Transfer") + scale_colour_Publication() + scale_fill_Publication()#
  2601. if (FALSE) {
  2602. post = posterior_samples(brms_posrec_genotype )
  2603. # back to absolute scale
  2604. # turn to effect size
  2605. post <- post %>% mutate(sd_total = sqrt(sd_ID__Intercept^2 + sigma^2))
  2606. post <- post/post$sd_total
  2607. post_pos_rec <- post
  2608. d_sul <- (post$b_Treatmentsulpride + 1/2*post$`b_Treatmentsulpride:genotypeA1M`)
  2609. d_sul%>% sf(1)
  2610. d_sul_a1p<- (post$b_Treatmentsulpride)
  2611. d_sul_a1p %>% sf(1)
  2612. d_sul_a1m<- (post$b_Treatmentsulpride + post$`b_Treatmentsulpride:genotypeA1M`)
  2613. d_sul_a1m %>% sf(1)
  2614. }
  2615. g_stats_posrec <- bind_cols(C_Sul = d_sul,
  2616. B_Sul =d_sul_a1p,
  2617. A_Sul =d_sul_a1m) %>%
  2618. # convert them to the long format, group, and get the posterior summaries
  2619. pivot_longer(everything()) %>%
  2620. group_by(name) %>%
  2621. summarise(mean = mean(value),
  2622. ll = quantile(value, prob = .025),
  2623. ul = quantile(value, prob = .975),
  2624. lls = quantile(value, prob = .25),
  2625. uls = quantile(value, prob = .75)) %>% # since the `key` variable is really two variables in one, here we split them up
  2626. # plot!
  2627. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  2628. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5,color = "firebrick", width = 0)+
  2629. geom_vline(xintercept = 0, linetype="dashed") +
  2630. geom_pointrange(color = "firebrick") +
  2631. labs(y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  2632. theme_Publication(base_size = 10) +
  2633. theme(panel.grid = element_blank(),
  2634. axis.text.x = element_text(size=10, ),
  2635. strip.background = element_rect(fill = "transparent", color = "transparent"),
  2636. axis.title.x = element_blank()) +
  2637. scale_y_discrete(labels = rev(c("S - P", "S - P in A1+", "S - P in A1-")) )
  2638. title <- ggdraw() +
  2639. draw_label(
  2640. "Effect sizes (means with 50% and 95% CrI)",
  2641. fontface = 'bold')
  2642. title_pos <- ggdraw() +
  2643. draw_label(
  2644. "Single-round positive reciprocity game",
  2645. fontface = 'bold',
  2646. size = 12)
  2647. title_neg <- ggdraw() +
  2648. draw_label(
  2649. "Single-round negative reciprocity game",
  2650. fontface = 'bold',
  2651. size = 12)
  2652. g_rtg_blank <- ggplot() + theme_foundation() + theme(panel.background = element_rect(colour = NA),
  2653. plot.background = element_rect(colour = NA),
  2654. panel.border = element_rect(colour = NA))
  2655. g_SI <- plot_grid(plot_grid(
  2656. title_pos, title_neg,
  2657. g_rtg_blank,g_rtg_blank,
  2658. g_reward + facet_wrap(~genotype), g_punishment + facet_wrap(~genotype),
  2659. g_stats_posrec+ theme(plot.margin = unit(c(0,0,0,0), "cm")), g_stats_negrec+ theme(plot.margin = unit(c(0,0,0,0), "cm")),
  2660. ncol = 2, rel_heights = c(0.2,0.7,1.1,0.4), labels = c("a", "b", "", "", "c", "d" ,"", "")),
  2661. title,
  2662. ncol= 1,
  2663. rel_heights = c(2.3,0.2))
  2664. g_SI
  2665. ```
  2666. # working memory data ####
  2667. ```{r wm data}
  2668. getwd()
  2669. swmdataset <- read.csv("swmdataset.csv", sep="\t")
  2670. swmdataset <- swmdataset %>% mutate(ID = as.factor(IDNumber))%>%
  2671. filter(IDNumber %in% unique(data_beh$ID))
  2672. swmdataset_sum <- swmdataset%>%
  2673. group_by(ID, problemnumber) %>%
  2674. summarize(error_sum = sum(betweenerror))
  2675. swmdataset_sum %>% group_by(ID) %>% summarize(N=n(),
  2676. error_sum_id = error_sum %>% sum())
  2677. remove_subj = c(6)
  2678. swmdataset <- swmdataset %>% filter(IDNumber != 6)
  2679. swmdataset_sum <- swmdataset %>% mutate(ID = as.factor(IDNumber)) %>%
  2680. filter(IDNumber %in% unique(data_beh$ID)) %>%
  2681. group_by(ID, numberofboxes) %>%
  2682. summarize(error_sum = sum(betweenerror))
  2683. swmdataset_data <- swmdataset_sum %>% merge(data_group, by = "ID")
  2684. g_wm <- swmdataset_data %>% group_by(numberofboxes, drug) %>% summarize(N=n(),
  2685. mean_error = mean(error_sum),
  2686. se_error = sd(error_sum)/sqrt(N-1)) %>%
  2687. ggplot(aes(x = numberofboxes, y = mean_error, group = drug, colour = drug)) +
  2688. geom_point() +
  2689. geom_errorbar(aes(ymin = mean_error - se_error, ymax = mean_error + se_error)) + theme_Publication()
  2690. g_wm_gen <- swmdataset_data %>% group_by(numberofboxes, ankk, drug) %>% summarize(N=n(),
  2691. mean_error = mean(error_sum),
  2692. se_error = sd(error_sum)/sqrt(N-1)) %>%
  2693. ggplot(aes(x = numberofboxes, y = mean_error, group = drug, colour = drug)) +
  2694. geom_point() +
  2695. geom_errorbar(aes(ymin = mean_error - se_error, ymax = mean_error + se_error)) + theme_Publication() +
  2696. facet_wrap(~ankk)
  2697. mod1 = glmer(data = swmdataset_data, error_sum ~ numberofboxes *ankk*drug + (numberofboxes|ID), family = "poisson")
  2698. summary(mod1)
  2699. contrasts(swmdataset_data$ankk) <- c(-1,1)
  2700. mod1 = glm(data = swmdataset_data %>% filter(numberofboxes == 12), error_sum ~ ankk*drug, family = "poisson")
  2701. summary(mod1)
  2702. mod1 = glm(data = swmdataset_data %>% filter(numberofboxes == 10), error_sum ~ ankk*drug, family = "poisson")
  2703. summary(mod1)
  2704. ## merge swm data with group data ####
  2705. if (FALSE) {
  2706. swmdataset_sum <- swmdataset %>%
  2707. group_by(ID) %>%
  2708. summarize(error_sum = sum(betweenerror))
  2709. data_group <- data_group %>% merge(swmdataset_sum, by = "ID") %>% rename(error_sum_all = error_sum)
  2710. data_beh <- data_beh %>% merge(swmdataset_sum, by = "ID") %>% rename(error_sum_all = error_sum)
  2711. swmdataset_sum <- swmdataset %>% filter(numberofboxes %in% c(10,12)) %>%
  2712. group_by(ID) %>%
  2713. summarize(error_sum = sum(betweenerror))
  2714. data_group <- data_group %>% merge(swmdataset_sum, by = "ID") %>% rename(error_sum_hardonly = error_sum)
  2715. data_beh <- data_beh %>% merge(swmdataset_sum, by = "ID") %>% rename(error_sum_hardonly = error_sum)
  2716. data_beh %>% saveRDS("Behavioural_data.rds")
  2717. data_group %>% saveRDS("Data_group_level.rds")
  2718. }
  2719. ## correlations of wm with model pars ####
  2720. # look at residuals from the model group
  2721. par_extract <- extract(M_tg_hgf_gamma, pars = 'r1')
  2722. par_extract$r1 %>% glimpse
  2723. data_group$om_res = par_extract$r1[,1,] %>%colMeans()
  2724. data_group$gam_res = par_extract$r1[,5,] %>%colMeans()
  2725. g_wm_om <- data_group %>% ggplot(aes(x = error_sum_all, y = om_res)) +
  2726. geom_point() +
  2727. geom_smooth(method= "lm")+
  2728. theme_Publication(base_size = 8)
  2729. g_wm_gam <- data_group %>% ggplot(aes(x = error_sum_all, y = gam_res)) +
  2730. geom_point() +
  2731. geom_smooth(method= "lm")+
  2732. theme_Publication(base_size = 8)
  2733. g_wm_noise <- data_group %>% ggplot(aes(x = error_sum_all, y = noise)) +
  2734. geom_point() +
  2735. geom_smooth(method= "lm")+
  2736. theme_Publication()
  2737. mod_swm_par <- glm(data = data_group, error_sum_all ~ om_mean + log(gam) + noise + mu0, family = "poisson" )
  2738. contrasts(data_group$ankk) = c(-0.5,0.5)
  2739. data_group =data_group %>% mutate(error_sum_all_s = ave(error_sum_all, FUN = scale),
  2740. error_sum_hard_s = ave(error_sum_hardonly, FUN = scale))
  2741. mod_om <- lm(data = data_group, om_mean ~ ankk*drug + error_sum_all_s)
  2742. summary(mod_om)
  2743. mod_gam <- lm(data = data_group, log(gam) ~ ankk*drug + error_sum_all_s)
  2744. summary(mod_gam)
  2745. mod_noise <- lm(data = data_group, noise ~ ankk*drug + error_sum_all_s)
  2746. summary(mod_noise)
  2747. ## condition on wm - does it change inference of model pars???
  2748. ```
  2749. # rerun the computional model with wm
  2750. ```{r wm data and stan}
  2751. if (FALSE) {
  2752. # run the hgf model with gamma with working memory data
  2753. run_model_fit("Stan_scripts/tg_hgf_gamma_wm.stan", "Model_results/M_tg_gamma_wm.rds", 3000)
  2754. # run the hgf model with gamma with working memory data but not drug or genotype data (for residuals)
  2755. run_model_fit("Stan_scripts/tg_hgf_gamma_wm_nodrug.stan", "Model_results/M_tg_gamma_wm_nodrug.rds", 3000)
  2756. }
  2757. M_tg_gamma_wm <- readRDS("Model_results/M_tg_gamma_wm.rds")
  2758. M_tg_gamma_wm_nodrug <- readRDS("Model_results/M_hgf_gamma_wm_nodrug.rds")
  2759. random_effects_model_wm <- extract(M_tg_gamma_wm_nodrug, pars = "r1" )
  2760. data_group = data_group[order(data_group$ID_n),]
  2761. data_group$om1_wm <- get_posterior_mean(M_tg_gamma_wm, pars=c('om_good'))[,5]
  2762. data_group$om2_wm <- get_posterior_mean(M_tg_gamma_wm, pars=c('om_bad'))[,5]
  2763. data_group$om_mean_wm <- 1/2*(data_group$om1_wm + data_group$om2_wm)
  2764. data_group$om_mean_res <- random_effects_model_wm$r1[,1,] %>%colMeans()
  2765. data_group$mu0_wm <- get_posterior_mean(M_tg_gamma_wm, pars=c('mu0'))[,5]
  2766. data_group$noise_wm <- get_posterior_mean(M_tg_gamma_wm, pars=c('noise'))[,5]
  2767. data_group$gam_wm <- get_posterior_mean(M_tg_gamma_wm, pars=c('gam'))[,5]
  2768. data_group$gam_res <- random_effects_model_wm$r1[,5,] %>%colMeans()
  2769. # plot correlations swm with model parameters #####
  2770. if (TRUE) {
  2771. pars_beta <- grep("^beta_", names(M_tg_gamma_wm_nodrug), value = T)
  2772. pars_sigma <- grep("^sigma", names(M_tg_gamma_wm_nodrug), value = T)
  2773. pars_beta<- c(pars_beta, pars_sigma)
  2774. # pars_all_model <- pars_all_model[!grepl("^beta_pr", pars_all_model)]
  2775. Pars_posterior_samples <- extract(M_tg_gamma_wm_nodrug, pars = pars_beta )
  2776. sigma_volatility = Pars_posterior_samples$`sigma[1]`
  2777. sigma_volatility_trustee = Pars_posterior_samples$`sigma[2]`
  2778. sigma_noise = Pars_posterior_samples$`sigma[3]`
  2779. sigma_gam = Pars_posterior_samples$`sigma[5]`
  2780. sigma_mu0 = Pars_posterior_samples$`sigma[4]`
  2781. sigma_total = sqrt(sigma_volatility^2 + sigma_volatility_trustee^2)
  2782. d_om_swm = (Pars_posterior_samples$beta_om_swm/sigma_volatility)
  2783. d_gam_swm = (Pars_posterior_samples$beta_gam_swm/sigma_gam)
  2784. d_noise_swm = (Pars_posterior_samples$beta_noise_swm/sigma_noise)
  2785. d_mu0_swm = (Pars_posterior_samples$beta_mu0_swm/sigma_mu0)
  2786. CI_outer = 0.95; # 99 CrI
  2787. data_stats_swm <- bind_cols(d_d_om_swm = d_om_swm,
  2788. c_d_gam_swm = d_gam_swm,
  2789. b_d_noise_swm = d_noise_swm,
  2790. a_d_mu0_swm=d_mu0_swm) %>%
  2791. # convert them to the long format, group, and get the posterior summaries
  2792. pivot_longer(everything()) %>%
  2793. group_by(name) %>%
  2794. summarise(mean = mean(value),
  2795. ll = quantile(value, prob = (1-CI_outer)/2),
  2796. ul = quantile(value, prob = 1- (1-CI_outer)/2),
  2797. lls = quantile(value, prob = .25),
  2798. uls = quantile(value, prob = .75))
  2799. g_stats_swm = data_stats_swm %>%
  2800. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name)) +
  2801. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5, width = 0, position = position_dodge(width= 0.5), colour = "firebrick")+
  2802. geom_vline(xintercept = 0, linetype = "dashed") +
  2803. geom_pointrange(position = position_dodge(width= 0.5), colour = "firebrick") +
  2804. labs( y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  2805. theme_Publication(base_size = 10) +
  2806. theme(panel.grid = element_blank(),
  2807. axis.text.x = element_text(size=10),
  2808. strip.background = element_rect(fill = "transparent", color = "transparent"),
  2809. axis.title.x = element_blank(),
  2810. legend.title = element_blank()) +
  2811. scale_y_discrete(labels = rev(c("\U1D714", "\U1D6FE'", "\U1D702", expression("\U1D707"[0]))) )+#\U1D707
  2812. scale_colour_manual(values = c("firebrick" , "red"))
  2813. g_om_swm <- ggplot(data = data_group, aes(x = error_sum_all, y = om_mean_wm ))+ # group = ID, linetype = Genotype))
  2814. # geom_violin(aes(fill = drug))+
  2815. # geom_boxplot(aes(fill = drug), width=0.5, color="black", outlier.colour = NA)+
  2816. # stat_summary(fun.y=mean, geom="point", shape=20, size=14, color="red", fill="red") +
  2817. geom_point(alpha = 0.8, shape = 21, colour = "black", size = 2, stroke =1)+
  2818. geom_smooth(method = "lm", se = F, colour ="black")+
  2819. theme_Publication(base_size = 8) +
  2820. theme(axis.ticks.x = element_blank(),
  2821. axis.text.x = element_blank(),
  2822. panel.grid.major = element_blank(),
  2823. legend.position = "none") +
  2824. ylab(expression(paste("Belief volatility - ", "\U1D714"))) + # ylab(expression("\U1D714"[good])) +
  2825. xlab("Errors (WM)") + discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462")))
  2826. g_gam_swm <- ggplot(data = data_group, aes(x = error_sum_all, y = log(gam_wm) ))+ # group = ID, linetype = Genotype))
  2827. # geom_violin(aes(fill = drug))+
  2828. # geom_boxplot(aes(fill = drug), width=0.5, color="black", outlier.colour = NA)+
  2829. # stat_summary(fun.y=mean, geom="point", shape=20, size=14, color="red", fill="red") +
  2830. geom_point(alpha = 0.8, shape = 21, colour = "black", size = 2, stroke =1)+
  2831. geom_smooth(method = "lm", se = F, colour ="black")+
  2832. theme_Publication(base_size = 8) +
  2833. theme(axis.ticks.x = element_blank(),
  2834. axis.text.x = element_blank(),
  2835. panel.grid.major = element_blank(),
  2836. legend.position = "none") +
  2837. ylab(expression(paste("Choice Precision - ", "\U1D6FE'"))) + # ylab(expression("\U1D714"[good])) +
  2838. xlab("Errors (WM)") + discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462")))
  2839. }
  2840. # plot effect size distributions
  2841. if (TRUE) {
  2842. pars_beta <- grep("^beta_", names(M_tg_gamma_wm), value = T)
  2843. pars_sigma <- grep("^sigma", names(M_tg_gamma_wm), value = T)
  2844. pars_beta<- c(pars_beta, pars_sigma)
  2845. # pars_all_model <- pars_all_model[!grepl("^beta_pr", pars_all_model)]
  2846. Pars_posterior_samples <- extract(M_tg_gamma_wm, pars = pars_beta )
  2847. sigma_volatility = Pars_posterior_samples$`sigma[1]`
  2848. sigma_volatility_trustee = Pars_posterior_samples$`sigma[2]`
  2849. sigma_noise = Pars_posterior_samples$`sigma[3]`
  2850. sigma_gam = Pars_posterior_samples$`sigma[5]`
  2851. sigma_mu0 = Pars_posterior_samples$`sigma[4]`
  2852. sigma_total = sqrt(sigma_volatility^2 + sigma_volatility_trustee^2)
  2853. # random_effects_model_wm <- extract(M_tg_gamma_wm, pars = "r1" )
  2854. # M_tg_gamma_wm %>% View
  2855. # om_good[i] = mu_p[1] + r1[1,i] +
  2856. # (beta_sul + beta_sul_ankk*ankk[i] + beta_sul_swm*swm_error[i])*sulpiride[i]+
  2857. # beta_ankk*ankk[i] + beta_om_swm*swm_error[i] +
  2858. # 0.5*(mu_p[2] + r1[2,i] +
  2859. # (beta_sul_trustee + beta_sul_ankk_trustee*ankk[i])*sulpiride[i]+
  2860. # beta_ankk_trustee*ankk[i]) -2;
  2861. ## main effect of sulpiride on belief stability
  2862. (Pars_posterior_samples$beta_sul+ 1/2*Pars_posterior_samples$beta_sul_ankk) %>% sf(1)
  2863. ( (Pars_posterior_samples$beta_sul+ 1/2*Pars_posterior_samples$beta_sul_ankk)/sigma_total ) %>% sf(1)
  2864. d_wm_sul = ( (Pars_posterior_samples$beta_sul+ 1/2*Pars_posterior_samples$beta_sul_ankk)/sigma_total )
  2865. ## effect of sulpiride on belief stability in A1-
  2866. Pars_posterior_samples$beta_sul %>% sf(1)
  2867. (Pars_posterior_samples$beta_sul/sigma_total) %>% sf(1)
  2868. d_wm_sul_a1p = (Pars_posterior_samples$beta_sul/sigma_total)
  2869. ## effect of sulpiride on belief stability in A1+
  2870. (Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk) %>% sf(1)
  2871. ( (Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk)/sigma_total ) %>% sf(1)
  2872. d_wm_sul_a1m = ( (Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk)/sigma_total )
  2873. ## interaction effect of sulpiride * genotype on belief stability
  2874. (Pars_posterior_samples$beta_sul_ankk) %>% sf(1)
  2875. ( (Pars_posterior_samples$beta_sul_ankk)/sigma_total ) %>% sf(1)
  2876. d_wm_sul_gene <- ( (Pars_posterior_samples$beta_sul_ankk)/sigma_total )
  2877. ## interaction effect of sulpiride on belief stability in A1+ trustees
  2878. Pars_posterior_samples$beta_sul_trustee %>% sf(1)
  2879. ## effect of sulpiride on belief stability in A1+ for good trustee
  2880. (Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_sul_trustee) %>% sf(1)
  2881. ((Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_sul_trustee) /sigma_total) %>% sf(1)
  2882. d_wm_sul_a1p_good = ((Pars_posterior_samples$beta_sul + 1/2*Pars_posterior_samples$beta_sul_trustee) /sigma_total)
  2883. ## effect of sulpiride on belief stability in A1+ for bad trustee
  2884. (Pars_posterior_samples$beta_sul - 1/2*Pars_posterior_samples$beta_sul_trustee) %>% sf(1)
  2885. ((Pars_posterior_samples$beta_sul - 1/2*Pars_posterior_samples$beta_sul_trustee)/sigma_total) %>% sf(1)
  2886. d_wm_sul_a1p_bad = ((Pars_posterior_samples$beta_sul - 1/2*Pars_posterior_samples$beta_sul_trustee) /sigma_total)
  2887. ## interaction effect of sulpiride on belief stability in A1- trustees
  2888. (Pars_posterior_samples$beta_sul_trustee+ Pars_posterior_samples$beta_sul_ankk_trustee) %>% sf(1)
  2889. ## effect of sulpiride on belief stability in A1- for bad trustee
  2890. (Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk - 1/2*(Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee)) %>% sf(1)
  2891. ((Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk - 1/2*(Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee))/sigma_total ) %>% sf(1)
  2892. ## effect of sulpiride on belief stability in A1- for good trustee
  2893. (Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk + 1/2*(Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee)) %>% sf(1)
  2894. ((Pars_posterior_samples$beta_sul+ Pars_posterior_samples$beta_sul_ankk + 1/2*(Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee))/sigma_total ) %>% sf(1)
  2895. ## interaction effect of sulpiride on belief stability in A1+ trustees
  2896. (Pars_posterior_samples$beta_sul_trustee) %>% sf(1)
  2897. ((Pars_posterior_samples$beta_sul_trustee)/sigma_total) %>% sf(1)
  2898. d_wm_sul_a1p_trustee=((Pars_posterior_samples$beta_sul_trustee)/sigma_total)
  2899. (Pars_posterior_samples$beta_sul_trustee + Pars_posterior_samples$beta_sul_ankk_trustee) %>% sf(1)
  2900. ## main effect of sulpiride on noise
  2901. (Pars_posterior_samples$beta_noise + 1/2*Pars_posterior_samples$beta_sul_ankk_noise) %>% sf(1)
  2902. d_wm_eta <- ((Pars_posterior_samples$beta_noise + 1/2*Pars_posterior_samples$beta_sul_ankk_noise)/sigma_noise)
  2903. d_wm_eta %>% sf(1)
  2904. ## main effect of sulpiride on noise in A1+
  2905. Pars_posterior_samples$beta_noise %>% sf(1)
  2906. d_wm_eta_a1p <- (Pars_posterior_samples$beta_noise/sigma_noise)
  2907. d_wm_eta_a1p %>% sf(1)
  2908. ## main effect of sulpiride on noise in A1-
  2909. (Pars_posterior_samples$beta_noise + Pars_posterior_samples$beta_sul_ankk_noise) %>% sf(1)
  2910. d_wm_eta_a1m <- ((Pars_posterior_samples$beta_noise + Pars_posterior_samples$beta_sul_ankk_noise)/sigma_noise)
  2911. d_wm_eta_a1m %>% sf(1)
  2912. ## effect of sulpiride on mu0 in A1+
  2913. d_wm_mu0_a1p <- Pars_posterior_samples$beta_mu0 /sigma_mu0
  2914. d_wm_mu0_a1p %>% sf(1)
  2915. # sigma_gamma = Pars_posterior_samples$`sigma[5]`
  2916. # (Pars_posterior_samples$beta_gam/sigma_gamma) %>% quantile(probs = c(0.025,0.5,0.975)) %>% round(2)
  2917. ## effect of sulpiride on mu0 in a1-
  2918. d_wm_mu0_a1m <- (Pars_posterior_samples$beta_mu0 + Pars_posterior_samples$beta_sul_ankk_mu0)/sigma_mu0
  2919. d_wm_mu0_a1m %>% sf(1)
  2920. ## effect of sulpiride on mu0
  2921. d_wm_mu0 <- (Pars_posterior_samples$beta_mu0 + 1/2*Pars_posterior_samples$beta_sul_ankk_mu0)/sigma_mu0
  2922. d_wm_mu0 %>% sf(1)
  2923. #
  2924. ## effect of sulpiride on gamma
  2925. (Pars_posterior_samples$beta_gam + 1/2*Pars_posterior_samples$beta_sul_ankk_gam) %>% sf(1)
  2926. d_wm_gam <- ((Pars_posterior_samples$beta_gam + 1/2*Pars_posterior_samples$beta_sul_ankk_gam)/sigma_gam)
  2927. d_wm_gam %>% sf(1)
  2928. ## effect of sulpiride on gamma in A1+
  2929. (Pars_posterior_samples$beta_gam + Pars_posterior_samples$beta_sul_ankk_gam) %>% sf(1)
  2930. d_wm_gam_a1m<- ((Pars_posterior_samples$beta_gam + Pars_posterior_samples$beta_sul_ankk_gam)/sigma_gam)
  2931. d_wm_gam_a1m %>% sf(1)
  2932. ## effect of sulpiride on gamma in A1-
  2933. (Pars_posterior_samples$beta_gam) %>% sf(1)
  2934. d_wm_gam_a1p<- ((Pars_posterior_samples$beta_gam)/sigma_gam)
  2935. d_wm_gam_a1p %>% sf(1)
  2936. ## interaction effect
  2937. d_wm_gam_sul_gene <- (Pars_posterior_samples$beta_sul_ankk_gam)/sigma_gam
  2938. d_wm_gam_sul_gene %>% sf(1)
  2939. ## effect of genotype on gamma
  2940. (1/2*(Pars_posterior_samples$beta_sul_ankk_gam) + Pars_posterior_samples$beta_ankk) %>% sf(1)
  2941. (0*(Pars_posterior_samples$beta_sul_ankk_gam) + Pars_posterior_samples$beta_ankk) %>% sf(1)
  2942. (1*(Pars_posterior_samples$beta_sul_ankk_gam) + Pars_posterior_samples$beta_ankk) %>% sf(1)
  2943. d_wm_gam <- ((Pars_posterior_samples$beta_gam + 1/2*Pars_posterior_samples$beta_sul_ankk_gam)/sigma_gam)
  2944. d_wm_gam %>% sf(1)
  2945. ## effect of genotype in controls on volatility
  2946. (Pars_posterior_samples$beta_ankk) %>% quantile(probs = c(0.025,0.5,0.975)) %>% round(2)
  2947. ## effect of genotype in controls on mu0
  2948. (Pars_posterior_samples$beta_ankk_mu0) %>% quantile(probs = c(0.025,0.5,0.975)) %>% round(2)
  2949. ## effect of genotype in controls on noise
  2950. (Pars_posterior_samples$beta_ankk_noise) %>% quantile(probs = c(0.025,0.5,0.975)) %>% round(2)
  2951. ## effect of genotype in controls on gamma
  2952. (Pars_posterior_samples$beta_ankk_gam) %>% quantile(probs = c(0.025,0.5,0.975)) %>% round(2)
  2953. data_group$ankk %>% glimpse()
  2954. ## effect of gen drug interaction on initial trust
  2955. ## interaction effect
  2956. d_wm_mu0_sul_gene <- (Pars_posterior_samples$beta_sul_ankk_mu0)/sigma_mu0
  2957. d_wm_mu0_sul_gene %>% sf(1)
  2958. }
  2959. # plot ####
  2960. CI_outer = 0.95; # 99 CrI
  2961. data_stats_om_ankk <- bind_cols(c_d_sul = d_sul,
  2962. b_d_sul_a1p = d_sul_a1p,
  2963. a_d_sul_a1m = d_sul_a1m) %>%
  2964. # convert them to the long format, group, and get the posterior summaries
  2965. pivot_longer(everything()) %>%
  2966. group_by(name) %>%
  2967. summarise(mean = mean(value),
  2968. ll = quantile(value, prob = (1-CI_outer)/2),
  2969. ul = quantile(value, prob = 1- (1-CI_outer)/2),
  2970. lls = quantile(value, prob = .25),
  2971. uls = quantile(value, prob = .75))
  2972. data_stats_om_ankk_wm <- bind_cols(c_d_sul = d_wm_sul,
  2973. b_d_sul_a1p = d_wm_sul_a1p,
  2974. a_d_sul_a1m = d_wm_sul_a1m) %>%
  2975. # convert them to the long format, group, and get the posterior summaries
  2976. pivot_longer(everything()) %>%
  2977. group_by(name) %>%
  2978. summarise(mean = mean(value),
  2979. ll = quantile(value, prob = (1-CI_outer)/2),
  2980. ul = quantile(value, prob = 1- (1-CI_outer)/2),
  2981. lls = quantile(value, prob = .25),
  2982. uls = quantile(value, prob = .75))
  2983. data_stats_om_ankk <- data_stats_om_ankk %>% mutate(type = "Without WM Data")
  2984. data_stats_om_ankk_wm<- data_stats_om_ankk_wm %>% mutate(type = "With WM Data")
  2985. data_stats_om_ankk_wm <- rbind(data_stats_om_ankk_wm, data_stats_om_ankk)
  2986. g_stats_om_wm = data_stats_om_ankk_wm %>%
  2987. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name, group = type, colour = type )) +
  2988. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5, width = 0, position = position_dodge(width= 0.5))+
  2989. geom_vline(xintercept = 0, linetype = "dashed") +
  2990. geom_pointrange(position = position_dodge(width= 0.5)) +
  2991. labs( y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  2992. theme_Publication(base_size = 10) +
  2993. theme(panel.grid = element_blank(),
  2994. axis.text.x = element_text(size=10),
  2995. strip.background = element_rect(fill = "transparent", color = "transparent"),
  2996. axis.title.x = element_blank(),
  2997. legend.title = element_blank()) +
  2998. scale_y_discrete(labels = rev(c("S - P", "S - P in A1+", "S - P in A1-")) )+
  2999. scale_colour_manual(values = c("firebrick" , "red"))+
  3000. scale_x_continuous(breaks = c(0, 1,2))
  3001. # plot_grid(g_abs_change_time + theme(legend.position = "none"), g_stats, nrow = 2, rel_heights = c(1,.3)
  3002. data_stats_gam_ankk <- bind_cols(c_d_gam = d_gam,
  3003. b_d_gam_a1p = d_gam_a1p,
  3004. a_d_gam_a1m = d_gam_a1m) %>%
  3005. # convert them to the long format, group, and get the posterior summaries
  3006. pivot_longer(everything()) %>%
  3007. group_by(name) %>%
  3008. summarise(mean = mean(value),
  3009. ll = quantile(value, prob = (1-CI_outer)/2),
  3010. ul = quantile(value, prob = 1- (1-CI_outer)/2),
  3011. lls = quantile(value, prob = .25),
  3012. uls = quantile(value, prob = .75))
  3013. data_stats_gam_ankk_wm <- bind_cols(c_d_gam = d_wm_gam,
  3014. b_d_gam_a1p = d_wm_gam_a1p,
  3015. a_d_gam_a1m = d_wm_gam_a1m) %>%
  3016. # convert them to the long format, group, and get the posterior summaries
  3017. pivot_longer(everything()) %>%
  3018. group_by(name) %>%
  3019. summarise(mean = mean(value),
  3020. ll = quantile(value, prob = (1-CI_outer)/2),
  3021. ul = quantile(value, prob = 1- (1-CI_outer)/2),
  3022. lls = quantile(value, prob = .25),
  3023. uls = quantile(value, prob = .75))
  3024. data_stats_gam_ankk <- data_stats_gam_ankk %>% mutate(type = "Without WM Data")
  3025. data_stats_gam_ankk_wm<- data_stats_gam_ankk_wm %>% mutate(type = "With WM Data")
  3026. data_stats_gam_ankk_wm <- rbind(data_stats_gam_ankk_wm, data_stats_gam_ankk)
  3027. g_stats_gam_wm = data_stats_gam_ankk_wm %>%
  3028. ggplot(aes(x = mean, xmin = ll, xmax = ul, y = name, group = type, colour = type )) +
  3029. geom_errorbar(aes(xmin = lls, xmax = uls), size = 1.5, width = 0, position = position_dodge(width= 0.5))+
  3030. geom_vline(xintercept = 0, linetype = "dashed") +
  3031. geom_pointrange(position = position_dodge(width= 0.5)) +
  3032. labs( y = NULL) + # subtitle = "Effect sizes (95% and 50% quantiles)",
  3033. theme_Publication(base_size = 10) +
  3034. theme(panel.grid = element_blank(),
  3035. axis.text.x = element_text(size=10),
  3036. strip.background = element_rect(fill = "transparent", color = "transparent"),
  3037. axis.title.x = element_blank(),
  3038. legend.title = element_blank()) +
  3039. scale_y_discrete(labels = rev(c("S - P", "S - P in A1+", "S - P in A1-")) )+
  3040. scale_colour_manual(values = c("firebrick" , "red"))+
  3041. scale_x_continuous(breaks = c(0, -1,-2))
  3042. # plot_grid(g_abs_change_time + theme(legend.position = "none"), g_stats, nrow = 2, rel_heights = c(1,.3)
  3043. data_stats_eta_ankk <- bind_cols(c_d_eta = d_eta,
  3044. b_d_eta_a1p = d_eta_a1p,
  3045. a_d_eta_a1m = d_eta_a1m) %>%
  3046. # convert them to the long format, group, and get the posterior summaries
  3047. pivot_longer(everything()) %>%
  3048. group_by(name) %>%
  3049. summarise(mean = mean(value),
  3050. ll = quantile(value, prob = (1-CI_outer)/2),
  3051. ul = quantile(value, prob =

tg_sulpride_analysis.Rmd at commit 4d97ad1, no license · at the source

Overview

  1. Social, Cognitive and Affective Neuroscience Unit, Department of Cognition, Emotion, and Methods in Psychology, University of Vienna, Vienna, Austria
Institutions: University of Vienna (Austria)
Journal: iScience, volume 29, issue 8, article 116747
Dates: received 30 January 2026; accepted 24 June 2026; published online 11 July 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1016/j.isci.2026.116747 · PMID 42519067 · PMCID PMC13382064 · OpenAlex W7168022583
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: fMRI (modality), human (organism), cognitive (subfield)
Methods: Statistics, Preprocessing, fMRI & imaging
Keywords: trust, amygdala, aging, loneliness, social cognition, learning, prediction error, hierarchical gaussian filter, fMRI, dopamine
Topic: Functional Brain Connectivity Studies (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: Austrian Science Fund FWF; Vienna Science and Technology Fund
Citations: not cited yet (Europe PMC); 71 references in the paper

Abstract

Functional relationships are essential for healthy aging and they rely on social cognition skills such as establishing and monitoring whom to trust. However, aging and loneliness can negatively affect social brain function, potentially leading to a vicious cycle. Using functional MRI and computational modeling, we investigated trust learning in a sample of neurotypical older (64–84 years, n = 29 f/23 m) compared to younger adults (20–33 years, n = 31 f/31 m). Older participants displayed lower initial trust and less trust learning when repeatedly interacting with a trustworthy and an untrustworthy trustee. Their basolateral and central amygdala activation was lower during trust decisions, and this was associated with less optimal trust behavior. Computational modeling also revealed that a crucial learning parameter, precision of the trust prediction error, and activation in the dopaminergic midbrain were decoupled from basolateral amygdala activation, and this effect was pronounced in lonely older adults. These findings indicate that differences in amygdala and dopamine function at older ages together with higher loneliness could impair trust learning, leading to poorer social cognition and putting individuals’ sociality and well-being at risk.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repositories

Its files are read in the Code ↔ Paper reader above, with 3 matches between paragraphs and lines of code.

scanunit/aging-and-loneliness-impair-trust-learning

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: d58ed03d0315441db625951f6b3d7434f0d667e2, 21 April 2026
Languages: Jupyter (2)
Size: 12 files, 2 scripts
Software Heritage: not archived
Found in: “Data and code availability”
Holds: 2 notebooks
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: brms (2 files), broom (2 files), car (2 files), cowplot (2 files), easystats (2 files), emmeans (2 files), lme4 (2 files), lmerTest (2 files), nlme (2 files), patchwork (2 files), Stan (2 files), tidyverse (2 files)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
2 files

nacemikus/belief-volatility-da-trustgame

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 4d97ad1c7fe42d906d7dd0e24d98fb93396038fd, 15 December 2024
Languages: Stan (5), R (5)
Size: 16 files, 10 scripts
Software Heritage: archived
Found in: the text, “Behavioral data analysis”
Holds: README, 1 notebook
Not found: license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Stan (9 files), tidyverse (4 files), ggplot2 (2 files), brms (1 file), broom (1 file), cowplot (1 file), lme4 (1 file), lmerTest (1 file), nlme (1 file), patchwork (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
11 files

The paper's code and data availability statement is in the Data section.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 12 scripts, each with its path and the digest of its content;
  • 3 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data and code availability

Data (Group-level SPM, single subject VOI and behavioral data, HGF results) required to reproduce our results and figures are publicly available on https://github.com/scanunit/aging-and-loneliness-impair-trust-learning.

Code (Jupyter Notebook) required to reproduce our results and figures are publicly available on https://github.com/scanunit/aging-and-loneliness-impair-trust-learning.

Any additional information required to reanalyze the data reported in this paper is available from the lead contact upon request.

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 2, 28 September 2026

  • Authors: added Federica Riva (0000-0002-1332-6312); removed Federica Riva

Version 1, 27 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 3 authors, 10 keywords, 2 funders, 71 references.

Cite

This paper

Sladky, R., Riva, F., & Lamm, C. (2026). Age and loneliness relate to reduced trust learning and alterations in amygdala function. iScience, 29(8), 116747. https://doi.org/10.1016/j.isci.2026.116747

BibTeX

@article{sladky2026age,
author = {Sladky, Ronald and Riva, Federica and Lamm, Claus},
title = {{Age and loneliness relate to reduced trust learning and alterations in amygdala function}},
journal = {iScience},
year = {2026},
month = jul,
volume = {29},
number = {8},
pages = {116747},
publisher = {Elsevier},
issn = {2589-0042},
doi = {10.1016/j.isci.2026.116747},
url = {https://doi.org/10.1016/j.isci.2026.116747},
pmid = {42519067},
pmcid = {PMC13382064}
}

RIS

TY - JOUR
AU - Sladky, Ronald
AU - Riva, Federica
AU - Lamm, Claus
TI - Age and loneliness relate to reduced trust learning and alterations in amygdala function
T2 - iScience
J2 - iScience
PY - 2026
DA - 2026/07/11
VL - 29
IS - 8
SP - 116747
SN - 2589-0042
PB - Elsevier
DO - 10.1016/j.isci.2026.116747
UR - https://doi.org/10.1016/j.isci.2026.116747
LA - en
ER -

CSL-JSON

{
"id": "10.1016/j.isci.2026.116747",
"type": "article-journal",
"title": "Age and loneliness relate to reduced trust learning and alterations in amygdala function",
"container-title": "iScience",
"author": [
{
"family": "Sladky",
"given": "Ronald"
},
{
"family": "Riva",
"given": "Federica"
},
{
"family": "Lamm",
"given": "Claus"
}
],
"container-title-short": "iScience",
"volume": "29",
"issue": "8",
"page": "116747",
"DOI": "10.1016/j.isci.2026.116747",
"PMID": "42519067",
"PMCID": "PMC13382064",
"ISSN": "2589-0042",
"publisher": "Elsevier",
"URL": "https://doi.org/10.1016/j.isci.2026.116747",
"language": "en",
"issued": {
"date-parts": [
[
2026,
7,
11
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1016/j.celrep.2026.117505 [code]
Impaired spatial coding and neuronal hyperactivity in the medial entorhinal cortex of aged APP knock-in mice.
Journal: Cell reports
In common: Stan, brms, nlme, 9 other tools
[2] doi:10.1073/pnas.2606871123 [code]
Oxytocin modulates the neurocomputational mechanisms engaged in learning rank relationships in social networks.
Journal: Proceedings of the National Academy of Sciences of the United States of America
In common: nlme, easystats, car, 8 other tools
[3] doi:10.1126/sciadv.aec9291 [code]
Computational mechanisms of perception in autism revealed using games inspired by rodent operant tasks.
Journal: Science advances
In common: Stan, nlme, easystats, 7 other tools, cognitive
[4] doi:10.1371/journal.pone.0355165 [code]
Pupillary dynamics during hands-off L2 driving and transitions of control under high cognitive load.
Journal: PloS one
In common: Stan, brms, easystats, 7 other tools, cognitive
[5] doi:10.1038/s41467-026-73865-9 [code]
Histamine shapes the neurocomputational dynamics of human learning.
Journal: Nature communications
In common: brms, easystats, car, 7 other tools, cognitive
[6] doi:10.1126/sciadv.aeb8106 [code]
A thyroid hormone-mediated opsin switch initiates metamorphosis in a proto-vertebrate.
Journal: Science advances
In common: easystats, car, broom, 7 other tools
[7] doi:10.1111/psyp.70265 [code]
Neurocognitive Dynamics of Translating Information From a Spatial Map Into Action.
Journal: Psychophysiology
In common: nlme, easystats, car, 6 other tools, cognitive
[8] doi:10.64898/2026.03.02.709173 [code]
Corpus Callosum Dysgenesis impairs metacognition: evidence from multi-modality and multi-cohort replications
Journal: bioRxiv (preprint)
In common: Stan, brms, easystats, 5 other tools, cognitive
[9] doi:10.1038/s41467-026-71415-x [code]
Regional BOLD variability reflects microstructural maturation and neuronal ensheathment in the preterm infant cortex.
Journal: Nature communications
In common: nlme, easystats, broom, 5 other tools, fMRI, 1 reference
[10] doi:10.1038/s41398-026-04010-9 [code]
Bullying victimization and brain development: a longitudinal structural magnetic resonance imaging study from adolescence to early adulthood.
Journal: Translational psychiatry
In common: nlme, easystats, broom, 6 other tools

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.