# ---------------------------------------------------------------------------
# check_bindings.R  (workflow: tfl-shell-to-ars-metadata)
# Reproduces: Checks that the datasets and variables bound in the AI-drafted ARS JSON exist in the pilot data, and counts the records each Week 24 data subset selects.
# Usage: Rscript check_bindings.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 check_bindings_output.txt on the workflow page (Scripts and full run).
# 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.
# ---------------------------------------------------------------------------
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
# Checks the dataset/variable bindings in the AI-drafted ARS JSON against the CDISC pilot ADaM data.
# Data: CDISC SDTM/ADaM Pilot Project, unmodified (attribution: CDISC). Run: Rscript check_bindings.R
suppressMessages({library(haven);library(dplyr)})
src <- paste0(sub("/+$", "", data_dir), "/")
q <- read_xpt(paste0(src,"adam_adqsadas.xpt")); sl <- read_xpt(paste0(src,"adam_adsl.xpt"))
cat("== 1. Variables the JSON binds exist in ADQSADAS?\n")
need <- c("EFFFL","TRTP","TRTPN","PARAMCD","AVISIT","AVISITN","AVAL","BASE","CHG","SITEID","SITEGR1","ANL01FL","DTYPE")
print(setNames(need %in% names(q), need))
cat("== 2. Values the JSON uses\n"); print(table(q$TRTP, q$TRTPN)); print(unique(q$PARAMCD[q$PARAMCD=="ACTOT"])); print(table(q$AVISIT, q$AVISITN))
cat("== 3. Efficacy population per arm in ADSL (EFFFL=Y)\n"); print(table(sl$TRT01P[sl$EFFFL=="Y"]))
cat("== 4. Records selected by each draft's Week 24 data subset (EFFFL=Y, PARAMCD=ACTOT, Week 24)\n")
s <- q %>% filter(EFFFL=="Y", PARAMCD=="ACTOT", AVISITN==24)
cat("Draft subset as written (no ANL01FL):  rows =", nrow(s), " distinct subjects =", n_distinct(s$USUBJID), "\n")
print(table(s$TRTP, useNA="ifany"))
s2 <- s %>% filter(ANL01FL=="Y")
cat("With ANL01FL = 'Y' added:  rows =", nrow(s2), " distinct subjects =", n_distinct(s2$USUBJID), "\n"); print(table(s2$TRTP))
cat("Subjects with more than one Week 24 row in the draft's subset:\n"); d <- s %>% count(USUBJID) %>% filter(n>1); print(nrow(d))
cat("DTYPE among ANL01FL=Y rows:\n"); print(table(s2$DTYPE, useNA="ifany"))
cat("== 5. Site variable\n"); cat("SITEID levels in analysis rows:", n_distinct(s2$SITEID), "; SITEGR1 levels:", n_distinct(s2$SITEGR1), "\n"); print(table(s2$SITEGR1))
