# Reproducible R figure exports from the R calculation, never Python output.
# Run: Rscript --vanilla figures.R outputs/r figures/r
library(jsonlite)
library(ggplot2)
args <- commandArgs(trailingOnly=TRUE); input <- args[1]; output <- args[2]
dir.create(output,recursive=TRUE,showWarnings=FALSE)
palette <- c('Placebo'='#0072B2','Xanomeline Low Dose'='#009E73','Xanomeline High Dose'='#CC79A7')
for(case in c('baseline','disposition','longitudinal','adverse-events','laboratory','subgroups','time-to-event')) {
  d <- fromJSON(file.path(input,paste0(case,'.json'))); d <- subset(d,stratum=='All')
  if(case=='baseline') d <- subset(d,measure=='Age (years)')
  if(case=='longitudinal') d <- subset(d,measure=='Change from baseline')
  if(case=='adverse-events') d <- subset(d,level=='SOC')
  if(case=='disposition') d <- subset(d,measure!='Analysis cohort')
  d$arm <- factor(d$arm,levels=names(palette))
  d <- d[!is.na(d$estimate),]
  if(case %in% c('longitudinal','time-to-event')) {
    p <- ggplot(d,aes(time,estimate,color=arm,group=arm))
    if(case=='time-to-event') {
      p <- p+geom_step(linewidth=.8)+geom_point(data=subset(d,censored>0),shape=3,size=2)+labs(x='Days since treatment start',y='Event-free probability')+ylim(0,1)
    } else p <- p+geom_line(linewidth=.8)+geom_point(size=2)+geom_errorbar(aes(ymin=lower,ymax=upper),width=.8)+labs(x='Analysis visit (weeks)',y='ADAS-Cog change (points)')
  } else {
    d$measure <- factor(d$measure,levels=rev(unique(d$measure)))
    p <- ggplot(d,aes(estimate,measure,color=arm,group=arm))+geom_point(position=position_dodge(width=.6),size=2)
    if('lower' %in% names(d)) p <- p+geom_errorbar(aes(xmin=lower,xmax=upper),position=position_dodge(width=.6),width=.25,orientation='y')
    p <- p+labs(x=if(case=='baseline') 'Age (years): mean and 95% CI' else if(case=='subgroups') 'Active - placebo change (points), 95% CI' else 'Participants (%)',y=NULL)
    if(case=='subgroups') p <- p+geom_vline(xintercept=0,linetype=2,color='grey60')
  }
  p <- p+scale_color_manual(values=palette,drop=FALSE)+theme_minimal(base_size=11)+theme(legend.position='bottom',legend.title=element_blank(),panel.grid.minor=element_blank(),plot.title=element_text(face='bold'))+labs(title=paste('CDISC Pilot |',case),subtitle='All participants | independently computed in R',caption='Educational reanalysis. See case methods and limitations. Source: CDISC Pilot, 667511d.')
  ggsave(file.path(output,paste0(case,'.svg')),p,width=10,height=if(case=='adverse-events')9 else 6,device=grDevices::svg)
}
cat('R figures: 7 SVG exports; ggplot2 ',as.character(packageVersion('ggplot2')),'\n')
