# Optional independent-software validation of the Python calculation.
# Run with R 4.5.1, metafor 5.2-1 and jsonlite 2.0.0.
# This is author validation using another implementation, not external review.
library(metafor)
library(jsonlite)
args <- commandArgs(trailingOnly=TRUE)
root <- if (length(args)) args[[1]] else "."
d <- fromJSON(file.path(root,"data/target-forest-inputs.json"),simplifyVector=FALSE)
fit_one <- function(rows) {
  x <- do.call(rbind,lapply(rows,unlist))
  a <- as.numeric(x[,1]);n1 <- as.numeric(x[,2]);c <- as.numeric(x[,3]);n0 <- as.numeric(x[,4])
  yi <- log((a/n1)/(c/n0));vi <- 1/a-1/n1+1/c-1/n0
  fit <- rma.uni(yi=yi,vi=vi,method="REML",test="knha",control=list(threshold=1e-10))
  list(rr=exp(as.numeric(fit$b)),ci=c(exp(fit$ci.lb),exp(fit$ci.ub)),p=fit$pval,tau2=fit$tau2)
}
result <- list(input_sha256=digest::digest(file=file.path(root,"data/target-forest-inputs.json"),algo="sha256"),software=list(R=R.version.string,metafor=as.character(packageVersion("metafor")),jsonlite=as.character(packageVersion("jsonlite"))),reproduction=list(),sensitivities=list())
for (outcome in c("mortality","labelled_death_disabling_stroke")) {
  result$reproduction[[outcome]] <- lapply(d[[outcome]],fit_one)
}
for (panel in c("1_year","longest")) {
  rows <- d$labelled_death_disabling_stroke[[panel]]
  rows$DEDICATE <- d$confirmed_endpoint_substitutions$DEDICATE$source_death_disabling_stroke
  rows$UKTAVI <- d$confirmed_endpoint_substitutions$UKTAVI$source_death_disabling_nonfatal_stroke
  result$sensitivities[[paste0(panel,"_two_endpoint_substitutions")]] <- fit_one(rows)
  if (panel=="1_year") {
    r3 <- rows;r3$Evolut <- d$additional_count_discrepancy$observed_source_1_year
    result$sensitivities$`1_year_add_observed_evolut_counts_arithmetic_only` <- fit_one(r3)
    rows$Evolut <- NULL
    result$sensitivities$`1_year_two_substitutions_omit_evolut` <- fit_one(rows)
  }
}
write_json(result,file.path(root,"results/metafor-reference.json"),pretty=TRUE,auto_unbox=TRUE,digits=16)
print(result)
