suppressPackageStartupMessages({library(metafor);library(jsonlite)})
e <- read.csv('/job/evidence/fresh-effects.csv')
t <- fromJSON('/job/bundle/data/trials.json',simplifyVector=FALSE)
names(t)<-vapply(t,function(z)z$trial,'')
# Preserve the author's arm split while mapping design codes to effect rows.
e$induction <- vapply(e$parent,function(id) any(vapply(t[[id]]$design$arms,function(a)identical(a$role,'ketamine')&&identical(a$start,'at_induction'),TRUE)),TRUE)
e$known_early_end <- vapply(e$parent,function(id)identical(t[[id]]$design$late_dosing,FALSE),TRUE)
f <- function(d){
 if(nrow(d)<2)return(list(k=nrow(d)))
 m<-rma(yi=d$yi,vi=d$vi,method='REML',test='knha')
 list(k=m$k,n=sum(d$n),g=unname(coef(m)[1]),lower=m$ci.lb,upper=m$ci.ub,p=m$pval,ids=d$trial)
}
early<-subset(e,outcome=='depression' & window=='early' & group=='masked')
ans<-list(baseline=f(early),exclude_induction=f(subset(early,!induction)),
 known_early_end_only=f(subset(early,known_early_end)),
 exclude_induction_and_unknown_end=f(subset(early,!induction & known_early_end)),
 selected_baseline=f(subset(early,selected)),selected_exclude_induction=f(subset(early,selected & !induction)),
 masked_induction_trials=early$trial[early$induction],
 strict_includes_unknown=early$trial[!early$late & !early$known_early_end])
for(w in c('middle','late')){
 d<-subset(e,outcome=='depression' & window==w & group=='masked')
 ans[[paste0(w,'_baseline')]]<-f(d)
 ans[[paste0(w,'_exclude_induction')]]<-f(subset(d,!induction))
}
# Leave the whole shared-control trial out of the between-study regression.
s<-subset(e,outcome=='depression' & window=='early' & setting=='surgery' & group %in% c('masked','awake') & parent!='T097')
m<-rma(yi=s$yi,vi=s$vi,mods=~I(s$group=='awake')+I(s$selected),method='REML',test='knha')
ans$moderator_without_shared_control<-list(k=m$k,g=unname(coef(m)[2]),lower=m$ci.lb[2],upper=m$ci.ub[2],p=m$pval[2])
cat(toJSON(ans,auto_unbox=TRUE,pretty=TRUE,digits=8),'\n')
