# ---------------------------------------------------------------------------
# replicate_14-3-01.R  (workflow: fda-ir-replication-instructions)
# Reproduces: Follows the AI-written replication plan step by step and compares the result with CSR Table 14-3.01 (ADAS-Cog(11) total, Week 24, efficacy population): 37 cells including the dose-response p-value and the three treatment differences.
# Usage: Rscript replicate_14-3-01.R <data_dir>
#   data_dir = folder containing the input files below (default: current folder).
# Input files: adam_adsl.xpt; adam_adqsadas.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/replicate_14-3-01_output.txt in this workflow's folder.
# Packages: dplyr 1.2.1, haven 2.5.5. 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.
# ---------------------------------------------------------------------------
# Executes the cold GOOD response plan (fda-ir-replication-instructions) step by step in R on the
# unmodified CDISC pilot ADaM files, then compares to CSR Table 14-3.01 (typed from the CSR, PDF p.49).
# Usage: Rscript replicate_14-3-01.R <folder with adam_adsl.xpt and adam_adqsadas.xpt>
# Data: CDISC SDTM/ADaM Pilot Project, used unmodified, attribution to CDISC.
#
# Where the plan left a gap (its OPEN QUESTIONS) this script had to choose; each choice is marked CHOICE.
suppressMessages({library(haven); library(dplyr)})
d <- if (length(commandArgs(TRUE)) >= 1) commandArgs(TRUE)[1] else "."
adsl  <- read_xpt(file.path(d, "adam_adsl.xpt"))
adqs  <- read_xpt(file.path(d, "adam_adqsadas.xpt"))

# Plan step 1: ADSL, EFFFL == "Y"
adsl_eff <- adsl %>% filter(EFFFL == "Y") %>% select(USUBJID, TRT01P, TRT01PN, SITEGR1)
cat("Step 1 efficacy subjects in ADSL:", nrow(adsl_eff), "\n")

# Plan steps 2-3: PARAMCD == ACTOT, Week 24 (CHOICE: AVISITN == 24, open question 2), ANL01FL == "Y"; DTYPE not filtered
q <- adqs %>% filter(PARAMCD == "ACTOT", AVISITN == 24, ANL01FL == "Y") %>% select(USUBJID, AVAL, BASE, CHG, DTYPE)
cat("Step 3 rows:", nrow(q), " subjects:", n_distinct(q$USUBJID), " DTYPE:", paste(names(table(q$DTYPE)), table(q$DTYPE), collapse = "; "), "\n")
stopifnot(!any(duplicated(q$USUBJID)))   # plan check: one row per subject

# Plan step 4: inner join
dd <- inner_join(adsl_eff, q, by = "USUBJID")
cat("Step 4 joined rows:", nrow(dd), " efficacy subjects with no Week 24 row:", sum(!adsl_eff$USUBJID %in% q$USUBJID), "\n")
dd$site <- factor(dd$SITEGR1)
dd$trt  <- factor(dd$TRT01P, levels = c("Placebo", "Xanomeline Low Dose", "Xanomeline High Dose"))
dd$dose <- dd$TRT01PN      # CHOICE: open question 4; plan names TRT01PN. Values in the file: 0, 54, 81
cat("Dose scores used:", paste(sort(unique(dd$dose)), collapse = ", "), "\n")
cat("Missing BASE or CHG:", sum(is.na(dd$BASE) | is.na(dd$CHG)), "\n")
cat("Step 5 check CHG == AVAL - BASE:", all(abs(dd$CHG - (dd$AVAL - dd$BASE)) < 1e-9), "\n")

rh <- function(x, nd) { s <- ifelse(x < 0, -1, 1); s * floor(abs(x) * 10^nd + 0.5 + 1e-9) / 10^nd }   # SAS-style half up
f  <- function(x, nd) formatC(rh(x, nd), format = "f", digits = nd)

# Plan step 6: descriptives
mine <- list()
for (g in levels(dd$trt)) for (v in c("BASE", "AVAL", "CHG")) {
  x <- dd[[v]][dd$trt == g]
  mine[[paste(g, v, "n")]]      <- as.character(length(x))
  mine[[paste(g, v, "meansd")]] <- sprintf("%s (%s)", f(mean(x), 1), f(sd(x), 2))
  mine[[paste(g, v, "medrange")]] <- sprintf("%s (%s;%s)", f(median(x), 1), f(min(x), 0), f(max(x), 0))
}

# Plan step 7: dose-response, CHG ~ BASE + site + dose (numeric); p of the dose coefficient (two-sided t-test)
fit_dose <- lm(CHG ~ BASE + site + dose, data = dd)
p_dose <- summary(fit_dose)$coefficients["dose", "Pr(>|t|)"]
# Plan step 8-9: categorical model; differences of LS means. With no interaction the LS mean difference is the
# coefficient contrast, so site weighting (open question 9) does not change it.
fit_cat <- lm(CHG ~ BASE + site + trt, data = dd)
b <- coef(fit_cat); V <- vcov(fit_cat); dfr <- df.residual(fit_cat)
cn <- c("trtXanomeline Low Dose", "trtXanomeline High Dose")
contr <- function(w) { est <- sum(w * b[names(w)]); se <- sqrt(drop(t(w) %*% V[names(w), names(w)] %*% w))
  tq <- qt(0.975, dfr); c(est = est, se = se, lo = est - tq * se, hi = est + tq * se, p = 2 * pt(-abs(est / se), dfr)) }
cmp <- list(
  low_pbo  = contr(setNames(1, cn[1])),                          # CHOICE: direction Xanomeline minus comparator
  high_pbo = contr(setNames(1, cn[2])),
  high_low = contr(setNames(c(1, -1), cn[c(2, 1)])))

res <- function(est) sprintf("%s (%s)", f(est["est"], 1), f(est["se"], 2))
ci  <- function(est) sprintf("(%s;%s)", f(est["lo"], 1), f(est["hi"], 1))

# CSR Table 14-3.01 (PDF p.49), typed from pdftotext output
csr <- c(
 "Placebo BASE n"="79","Placebo BASE meansd"="24.1 (12.19)","Placebo BASE medrange"="21.0 (5;61)",
 "Placebo AVAL n"="79","Placebo AVAL meansd"="26.7 (13.79)","Placebo AVAL medrange"="24.0 (5;62)",
 "Placebo CHG n"="79","Placebo CHG meansd"="2.5 (5.80)","Placebo CHG medrange"="2.0 (-11;16)",
 "Xanomeline Low Dose BASE n"="81","Xanomeline Low Dose BASE meansd"="24.4 (12.92)","Xanomeline Low Dose BASE medrange"="21.0 (5;57)",
 "Xanomeline Low Dose AVAL n"="81","Xanomeline Low Dose AVAL meansd"="26.4 (13.18)","Xanomeline Low Dose AVAL medrange"="25.0 (6;62)",
 "Xanomeline Low Dose CHG n"="81","Xanomeline Low Dose CHG meansd"="2.0 (5.55)","Xanomeline Low Dose CHG medrange"="2.0 (-11;17)",
 "Xanomeline High Dose BASE n"="74","Xanomeline High Dose BASE meansd"="21.3 (11.74)","Xanomeline High Dose BASE medrange"="18.0 (3;57)",
 "Xanomeline High Dose AVAL n"="74","Xanomeline High Dose AVAL meansd"="22.8 (12.48)","Xanomeline High Dose AVAL medrange"="20.0 (3;62)",
 "Xanomeline High Dose CHG n"="74","Xanomeline High Dose CHG meansd"="1.5 (4.26)","Xanomeline High Dose CHG medrange"="1.0 (-7;13)")
mine2 <- c(unlist(mine),
  "p dose response" = unname(f(p_dose, 3)),
  "Low-Pbo p" = unname(f(cmp$low_pbo["p"], 3)),  "Low-Pbo diff (SE)" = res(cmp$low_pbo),  "Low-Pbo 95% CI" = ci(cmp$low_pbo),
  "High-Pbo p" = unname(f(cmp$high_pbo["p"], 3)), "High-Pbo diff (SE)" = res(cmp$high_pbo), "High-Pbo 95% CI" = ci(cmp$high_pbo),
  "High-Low p" = unname(f(cmp$high_low["p"], 3)), "High-Low diff (SE)" = res(cmp$high_low), "High-Low 95% CI" = ci(cmp$high_low))
csr2 <- c(csr, "p dose response"="0.245",
  "Low-Pbo p"="0.569","Low-Pbo diff (SE)"="-0.5 (0.82)","Low-Pbo 95% CI"="(-2.1;1.1)",
  "High-Pbo p"="0.233","High-Pbo diff (SE)"="-1.0 (0.84)","High-Pbo 95% CI"="(-2.7;0.7)",
  "High-Low p"="0.520","High-Low diff (SE)"="-0.5 (0.84)","High-Low 95% CI"="(-2.2;1.1)")
# The plan's "diff (SE)" for the CSR is printed with 1 decimal for diff and 2 for SE; compare as text.
stopifnot(identical(sort(names(csr2)), sort(names(mine2))))
ok <- mine2[names(csr2)] == csr2
for (n in names(csr2)) cat(sprintf("%-8s %-40s replicated=%-14s CSR=%s\n", ifelse(ok[n], "OK", "MISMATCH"), n, mine2[n], csr2[n]))
cat(sprintf("\n%d of %d cells match, %d mismatch.\n", sum(ok), length(ok), sum(!ok)))
cat(if (all(ok)) "RESULT: PASS\n" else "RESULT: FAIL\n")
dd$dose012 <- as.numeric(dd$trt) - 1   # dose score 0,1,2; the p-value is picked by coefficient NAME, not position
cat("\nSensitivity (not part of the plan): dose scores 0,1,2 instead of 0,54,81 give dose-response p =",
    f(summary(lm(CHG ~ BASE + site + dose012, data = dd))$coefficients["dose012", "Pr(>|t|)"], 3), "\n")
nofl <- adqs %>% filter(PARAMCD == "ACTOT", AVISITN == 24) %>% inner_join(adsl_eff, by = "USUBJID")
cat("Sensitivity (not part of the plan): Week 24 ACTOT rows for efficacy subjects WITHOUT the ANL01FL filter:", nrow(nofl),
    " subjects:", n_distinct(nofl$USUBJID), "\n")
