# Builds the table pasted into the prompt. Data: CDISC pilot ADAE/ADSL, unmodified.
args <- commandArgs(TRUE); src <- args[1]
# Needs the R packages haven and dplyr (install.packages(c("haven","dplyr")) if missing).
suppressMessages({library(haven);library(dplyr)})
adsl <- read_xpt(file.path(src,"adam_adsl.xpt")); adae <- read_xpt(file.path(src,"adam_adae.xpt"))
arms <- c("Placebo","Xanomeline Low Dose","Xanomeline High Dose")
saf <- adsl %>% filter(SAFFL=="Y")
N <- sapply(arms, function(a) sum(saf$TRT01A==a))
te <- adae %>% filter(SAFFL=="Y", TRTEMFL=="Y")
f <- function(n,d) sprintf("%d (%.1f%%)", n, 100*n/d)
subj <- function(df) sapply(arms, function(a) n_distinct(df$USUBJID[df$TRTA==a]))
ev   <- function(df) sapply(arms, function(a) sum(df$TRTA==a))
row <- function(lab, df) cat(sprintf("%-52s %s\n", lab, paste(sprintf("%-18s", f(subj(df),N)), collapse="")))
cat(sprintf("%-52s %s\n","", paste(sprintf("%-18s", paste0(c("Placebo","Low Dose","High Dose")," (N=",N,")")), collapse="")))
row("Any treatment-emergent AE (TEAE)", te)
cat(sprintf("%-52s %s\n","  Total TEAE events", paste(sprintf("%-18s", ev(te)), collapse="")))
row("Any serious TEAE", te %>% filter(AESER=="Y"))
row("Any severe TEAE (AESEV = SEVERE)", te %>% filter(AESEV=="SEVERE"))
row("Any TEAE recorded POSSIBLE or PROBABLE related", te %>% filter(AEREL %in% c("POSSIBLE","PROBABLE")))
dc <- saf %>% filter(DCDECOD=="ADVERSE EVENT") %>% transmute(USUBJID, TRTA=TRT01A)
row("Study discontinuation, reason ADVERSE EVENT (ADSL.DCDECOD)", dc)
dth <- saf %>% filter(DTHFL=="Y") %>% transmute(USUBJID, TRTA=TRT01A)
row("Deaths (ADSL.DTHFL = Y)", dth)
cat("\nTEAEs by preferred term, subjects n (%); PTs with >=10% in either xanomeline arm and higher than placebo, sorted by High Dose\n")
pt <- te %>% group_by(AEDECOD,TRTA) %>% summarise(n=n_distinct(USUBJID),.groups="drop") %>% tidyr::pivot_wider(names_from=TRTA,values_from=n,values_fill=0)
pt <- pt %>% mutate(pl=`Placebo`/N[1], lo=`Xanomeline Low Dose`/N[2], hi=`Xanomeline High Dose`/N[3]) %>%
  filter((lo>=.10|hi>=.10), lo>pl, hi>pl) %>% arrange(desc(hi),AEDECOD)
for(i in seq_len(nrow(pt))) cat(sprintf("%-40s %-14s %-14s %-14s\n", pt$AEDECOD[i], f(pt$Placebo[i],N[1]), f(pt$`Xanomeline Low Dose`[i],N[2]), f(pt$`Xanomeline High Dose`[i],N[3])))
cat("\nSerious TEAEs, listing\n")
print(as.data.frame(te %>% filter(AESER=="Y") %>% select(USUBJID,TRTA,AEBODSYS,AEDECOD,AESEV,AEREL,AESTDY=ASTDY)))
cat("\nDeaths listing (ADSL)\n"); print(as.data.frame(saf %>% filter(DTHFL=="Y") %>% select(USUBJID,TRT01A,DCDECOD)))
cat("\nAEACN non-missing:", sum(!is.na(adae$AEACN) & adae$AEACN!=""), " AESER=Y among deaths:", sum(adae$AESER=="Y" & adae$USUBJID %in% dth$USUBJID),"\n")
