# ---------------------------------------------------------------------------
# dsmb_inputs.R  (workflow: dsmb-closed-report-summary-text)
# Reproduces: Builds the safety table that was pasted into the prompt: TEAE counts by arm, serious and severe TEAEs, related TEAEs, AE discontinuations, deaths, common preferred terms, and the serious AE and death listings.
# Usage: Rscript dsmb_inputs.R <data_dir>
#   data_dir = folder containing the input files below (default: current folder).
# Input files: adam_adsl.xpt; adam_adae.xpt
#   Download the unmodified files from the public CDISC pilot repository:
#   https://github.com/cdisc-org/sdtm-adam-pilot-project  (folder updated-pilot-submission-package/900172/m5/)
#   (datasets as .xpt files).
# Expected output: see expected_output/dsmb_inputs_output.txt in this workflow's folder.
# Packages: dplyr 1.2.1, haven 2.5.5, tidyr 1.3.2. Tested with R 4.6.1 on Windows.
#   Install what is missing with install.packages(c(...)); no private library path is needed.
# Licence: code MIT (see README.md in the scripts folder). Data: CDISC SDTM/ADaM Pilot Project (CDISCPILOT01),
# credited to CDISC, used unmodified under the CDISC terms of use. The data are not included here.
# Logic is unchanged from the version that produced the saved output; only path handling and this header were changed.
# ---------------------------------------------------------------------------
args <- commandArgs(trailingOnly = TRUE)
data_dir <- if (length(args) >= 1) args[1] else "."   # folder holding the CDISC pilot .xpt files
script_dir <- local({ f <- sub("^--file=", "", grep("^--file=", commandArgs(FALSE), value = TRUE))
                      if (length(f)) dirname(normalizePath(f[1])) else "." })   # folder holding this script
# Builds the table pasted into the prompt. Data: CDISC pilot ADAE/ADSL, unmodified.
src <- data_dir
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")
