## =====================================================================
## Paper 1 (tropical Bos indicus) - DDG/DDGS meta-analysis, reproducible
## Input : Paper1_TROPICAL_consolidado.xlsx (arm-level; header on row 3)
## Effect: mean difference (DDG/DDGS arm - within-study control)
## Pooling: random effects (DerSimonian-Laird), metafor::rma
## RVE  : CR2 cluster-robust, Satterthwaite df (clubSandwich via metafor::robust)
## Clusters: study, except N6/N16/N18 (same UNESP research group) = one cluster
## NOTE: "mineral only" arms (negative controls in N6, N18) are NOT DDG arms
##       and are excluded from all contrasts.
## =====================================================================
suppressMessages({library(readxl); library(metafor); library(clubSandwich); library(jsonlite)})
args <- commandArgs(trailingOnly = TRUE)
xlsx <- if (length(args)) args[1] else "Paper1_TROPICAL_consolidado.xlsx"
outdir <- if (length(args) > 1) args[2] else "."
d <- as.data.frame(read_excel(xlsx, sheet = 1, skip = 2))
d <- d[!is.na(d$study_id) & !is.na(d$mean), ]
d$inclusion_pct <- suppressWarnings(as.numeric(d$inclusion_pct))

## ---- build arm-vs-control contrasts ----
mk <- function(d){
  out <- list()
  for (key in unique(paste(d$study_id, d$outcome))) {
    g <- d[paste(d$study_id, d$outcome) == key, ]
    c <- g[g$is_control == "yes", ]; if (nrow(c) != 1) next
    t <- g[g$is_control != "yes" & g$dg_type != "mineral only", ]
    if (!nrow(t)) next
    out[[key]] <- data.frame(study = t$study_id, outcome = t$outcome, arm = t$arm_label,
      design = t$design_type, system = t$system, dg = t$dg_type, dose = t$inclusion_pct,
      yi = t$mean - c$mean, vi = t$sd^2/t$n + c$sd^2/c$n)
  }
  x <- do.call(rbind, out); rownames(x) <- NULL
  ## clusters = research group (non-independence of trials from the same group/facility)
  grp <- c(N6="UNESP-Jaboticabal", N16="UNESP-Jaboticabal", N18="UNESP-Jaboticabal", X10="UNESP-Jaboticabal",
           B5="ESALQ", N17="ESALQ", X03="ESALQ", Nardi2026="ESALQ",
           B24="UFMT-Sinop", X06="UFMT-Sinop",
           T2="UFMT-Cuiaba", X04="UFMT-Cuiaba",
           T1="UFV", X05="X05", X02="UNESP-Botucatu")
  x$cluster <- unname(ifelse(x$study %in% names(grp), grp[x$study], x$study))
  ## co-product class
  x$dg_class <- ifelse(grepl("fiber\\+solubles|WDBS", x$dg), "fiber+solubles",
                 ifelse(grepl("HP-DDG", x$dg), "high-protein", "conventional"))
  x$crossbred <- x$study %in% c("X02","X18")
  ## dose on %DM scale only for feedlot diets; protein-replacement doses are % of protein meal replaced
  x$dose_dm <- ifelse(x$design == "protein-replacement", NA, x$dose)
  x
}
C <- mk(d)
res <- list(); tab <- list()
pool <- function(g){
  f <- rma(yi, vi, data = g, method = "DL")
  r <- list(k = nrow(g), studies = length(unique(g$study)), clusters = length(unique(g$cluster)),
            est = f$b[1], lo = f$ci.lb, hi = f$ci.ub, p = f$pval, I2 = f$I2, tau2 = f$tau2)
  if (r$clusters >= 2) {
    rb <- robust(f, cluster = g$cluster, clubSandwich = TRUE)
    r$rve_lo <- rb$ci.lb; r$rve_hi <- rb$ci.ub; r$rve_df <- rb$dfs; r$rve_p <- rb$pval
  }
  gd <- g[!is.na(g$dose_dm), ]
  if (length(unique(gd$study)) >= 2) {
    fd <- rma(yi, vi, mods = ~ I(dose_dm/10), data = gd, method = "DL")
    r$dose_k <- nrow(gd); r$dose_studies <- length(unique(gd$study))
    r$dose <- fd$b[2]; r$dose_lo <- fd$ci.lb[2]; r$dose_hi <- fd$ci.ub[2]; r$dose_p <- fd$pval[2]
    rbd <- try(robust(fd, cluster = gd$cluster, clubSandwich = TRUE), silent = TRUE)
    if (!inherits(rbd, "try-error")) { r$dose_rve_lo <- rbd$ci.lb[2]; r$dose_rve_hi <- rbd$ci.ub[2]; r$dose_rve_df <- rbd$dfs[2] }
  }
  r
}
for (o in c("HCW","DRESS","ADG","DMI","FBW","GF","REA")) res[[o]] <- pool(C[C$outcome == o, ])

## ---- subgroups (ADG) ----
A <- C[C$outcome == "ADG", ]
res$ADG_feedlot <- pool(A[A$design != "protein-replacement", ])
res$ADG_protein_replacement <- pool(A[A$design == "protein-replacement", ])
sg <- rma(yi, vi, mods = ~ I(design == "protein-replacement"), data = A, method = "DL")
res$ADG_subgroup_test <- list(QM = sg$QM, p = sg$QMp)

## ---- leave-one-cluster-out (HCW, ADG) ----
for (o in c("HCW","ADG")) {
  g <- C[C$outcome == o, ]
  res[[paste0(o, "_LOCO")]] <- lapply(setNames(unique(g$cluster), unique(g$cluster)), function(cl) {
    f <- rma(yi, vi, data = g[g$cluster != cl, ], method = "DL"); c(est = f$b[1], lo = f$ci.lb, hi = f$ci.ub, I2 = f$I2) })
}

## ---- sensitivity: Nardi et al. (2026) conference abstract (no variance reported) ----
## HCW -14.66 kg at 40% DM (linear) -> -7.33 kg at 20%; variance imputed over a grid
H <- C[C$outcome == "HCW", ]
grid <- expand.grid(sd = c(5, 8, 10, 15), n = 18)  # n = 18 pens per treatment (reported)
res$HCW_sens_Nardi2026 <- t(apply(grid, 1, function(z) {
  add <- data.frame(study = "Nardi2026", outcome = "HCW", arm = c("20","40"), design = "inclusion-gradient",
                    system = "feedlot", dg = "fiber-separated DDGS", dose = c(20, 40), yi = c(-7.33, -14.66),
                    vi = rep(2 * z[["sd"]]^2 / z[["n"]], 2), cluster = "ESALQ", dose_dm = c(20, 40), dg_class = "fiber+solubles", crossbred = FALSE)
  f <- rma(yi, vi, data = rbind(H, add), method = "DL")
  c(sd = z[["sd"]], n_per_arm = z[["n"]], est = f$b[1], lo = f$ci.lb, hi = f$ci.ub, I2 = f$I2)
}))


## ---- sensitivity: Nardi et al. (2026) for ADG (-0.219 kg/d at 40%, linear) ----
A2 <- C[C$outcome == "ADG", ]
res$ADG_sens_Nardi2026 <- t(sapply(c(0.08, 0.10, 0.15), function(sdv) {
  add <- data.frame(study = "Nardi2026", outcome = "ADG", arm = c("20","40"), design = "inclusion-gradient",
                    system = "feedlot", dg = "fiber-separated DDGS", dose = c(20, 40), yi = c(-0.1095, -0.219),
                    vi = rep(2 * sdv^2 / 18, 2), cluster = "ESALQ", dose_dm = c(20, 40), dg_class = "fiber+solubles", crossbred = FALSE)
  f <- rma(yi, vi, data = rbind(A2, add), method = "DL")
  c(sd = sdv, n_per_arm = 18, est = f$b[1], lo = f$ci.lb, hi = f$ci.ub, I2 = f$I2)
}))

## ---- as-submitted reproduction (mineral-only arms wrongly included), for the record ----
d2 <- d; d2$dg_type[d2$dg_type == "mineral only"] <- "MINERAL"
Cbad <- mk(d2)
res$ADG_as_submitted <- pool(Cbad[Cbad$outcome == "ADG", ])

## ---- co-product class moderator (feedlot contrasts) ----
for (o in c("HCW","ADG","DMI","FBW")) {
  g <- C[C$outcome == o & C$dg_class != "high-protein", ]
  if (length(unique(g$dg_class)) == 2) {
    f <- rma(yi, vi, mods = ~ dg_class, data = g, method = "DL")
    res[[paste0(o, "_dgclass_test")]] <- list(k = nrow(g), diff_fiber_minus_conv = f$b[2], lo = f$ci.lb[2], hi = f$ci.ub[2], p = f$pval[2])
    for (cl in unique(g$dg_class)) res[[paste0(o, "_", gsub("[^a-z]", "", cl))]] <- pool(g[g$dg_class == cl, ])
  }
}
## ---- sensitivity: exclude crossbreds ----
for (o in c("HCW","ADG")) res[[paste0(o, "_no_crossbred")]] <- pool(C[C$outcome == o & !C$crossbred, ])

write_json(res, file.path(outdir, "Paper1_TROPICAL_resultados_v2.json"), auto_unbox = TRUE, digits = 6, pretty = TRUE)
write.csv(C, file.path(outdir, "Paper1_TROPICAL_contrasts_v2.csv"), row.names = FALSE)

## ---- figures: dose-response (feedlot, %DM) ----
fig <- function(o, ylab, fn){
  g <- C[C$outcome == o & !is.na(C$dose_dm), ]
  f <- rma(yi, vi, mods = ~ dose_dm, data = g, method = "DL")
  for (dev in c("png","pdf")) {
  if (dev == "png") png(file.path(outdir, fn), width = 2400, height = 1800, res = 300) else pdf(file.path(outdir, sub("png$","pdf",fn)), width = 8, height = 6)
  par(mar = c(4.5, 4.8, 1, 1))
  nm <- c(B5="Benez (2024)", N17="Antunes et al. (2025)", T1="Alhadas et al. (2021)", T2="da Rosa e Silva et al. (2022)", X02="Ferreira et al. (2020)", X03="Lima Junior et al. (2022)", X04="Ormond et al. (2025)", X05="Reis et al. (2020)", X18="Rodriguez et al. (2013)")
  g$lab <- factor(nm[g$study]); PCH <- c(15,16,17,18,0,1,2,5,6); COL <- c("#1f4e79","#c55a11","#2e7d32","#6a1b9a","#b71c1c","#00838f","#5d4037","#455a64","#ef6c00"); pch <- PCH[as.numeric(g$lab)]; colv <- COL[as.numeric(g$lab)]
  plot(g$dose_dm, g$yi, cex = 0.6 + 2.5 * sqrt((1/g$vi)/max(1/g$vi)), pch = pch, col = colv,
       xlab = "DDG/DDGS inclusion (% of diet DM)", ylab = ylab, las = 1, xlim = c(0, 47))
  abline(h = 0, lty = 3)
  xs <- seq(0, max(g$dose_dm), 1); p <- predict(f, newmods = xs)
  polygon(c(xs, rev(xs)), c(p$ci.lb, rev(p$ci.ub)), col = adjustcolor("grey50", .25), border = NA)
  lines(xs, p$pred, lwd = 2)
  legend("topleft", legend = levels(g$lab), pch = PCH[1:nlevels(g$lab)], col = COL[1:nlevels(g$lab)], bty = "n", cex = .8)
  dev.off() }
}
fig("HCW", "Hot carcass weight, MD vs control (kg)", "Figure_2_HCW_dose.png")
fig("ADG", "Average daily gain, MD vs control (kg/d)", "Figure_3_ADG_dose.png")
cat("done\n")
