tests/testthat/test-pipeline.R

test_that("run_di_pipeline executa fluxo completo com dados LONG", {

  skip_if_not_installed("openxlsx")
  skip_if_not_installed("emmeans")

  set.seed(123)

  base <- expand.grid(
    block = factor(1:6),
    trat = factor(c("A", "B", "C")),
    time = 1:4,
    class = c("F0", "F1", "F2", "F3")
  )

  # Frequencias positivas e com variacao entre
  # tratamentos, tempos, blocos e classes.
  class_num <- as.numeric(sub("F", "", base$class))
  trat_num <- match(base$trat, c("A", "B", "C")) - 1

  lambda <- 8 +
    0.8 * base$time +
    0.7 * trat_num +
    0.4 * class_num +
    0.15 * as.numeric(base$block)

  base$freq <- stats::rpois(nrow(base), lambda = lambda) + 1L

  arq <- tempfile(fileext = ".xlsx")

  openxlsx::write.xlsx(
    list(CRD_long = base),
    arq
  )

  res <- infectionIndex::run_di_pipeline(
    excel_file = arq,
    sheet_prefer = "CRD_long",
    corstr = "independence",
    save_outputs = FALSE,
    outlier_action = "flag"
  )

  expect_type(res, "list")
  expect_true(all(c(
    "out", "out_clean", "outliers"
  ) %in% names(res)))

  out <- res$out
  clean <- res$out_clean

  # 6 blocos x 3 tratamentos x 4 tempos
  expect_equal(nrow(out$di_por_tempo), 72L)

  expect_true(all(c(
    "block", "trat", "time",
    "DI", "DI_clip", "DI_ang"
  ) %in% names(out$di_por_tempo)))

  expect_true(all(is.finite(out$di_por_tempo$DI)))
  expect_true(all(
    out$di_por_tempo$DI >= 0 &
    out$di_por_tempo$DI <= 1
  ))

  # Metadados da importacao e analise
  expect_equal(out$meta$sheet_used, "CRD_long")
  expect_equal(out$meta$format_used, "LONG")
  expect_equal(out$meta$K, 3)
  expect_equal(out$meta$corstr, "independence")

  # GEE: 18 parcelas, cada uma acompanhada em 4 tempos
  expect_equal(
    length(out$gee_fit_com_interacao$geese$clusz),
    18L
  )
  expect_true(all(
    out$gee_fit_com_interacao$geese$clusz == 4L
  ))

  # Teste global da interacao
  expect_s3_class(out$interaction_test, "data.frame")
  expect_true(all(c(
    "test", "term", "statistic", "df", "p.value"
  ) %in% names(out$interaction_test)))
  expect_true(is.finite(out$interaction_test$p.value))

  # Comparacao das quatro estruturas de correlacao
  expect_s3_class(out$qic_comparison, "data.frame")
  expect_equal(nrow(out$qic_comparison), 4L)
  expect_setequal(
    out$qic_comparison$corstr,
    c("independence", "exchangeable", "ar1", "unstructured")
  )
  expect_true(any(out$qic_comparison$selected))

  # Predicoes: 3 tratamentos x 4 tempos
  expect_equal(nrow(out$predictions), 12L)
  expect_true(all(out$predictions$DI_hat >= 0))
  expect_true(all(out$predictions$DI_hat <= 1))

  # AUC: uma linha por parcela
  expect_equal(nrow(out$auc$by_parcela), 18L)
  expect_equal(nrow(out$auc$summary), 3L)
  expect_s3_class(out$auc$tests$kruskal, "htest")

  # Estrutura de outliers
  expect_true(all(c("detected", "dropped") %in%
    names(res$outliers)))

  # out_clean deve permanecer um objeto analisavel,
  # havendo ou nao outliers no conjunto sintetico.
  expect_true("di_por_tempo" %in% names(clean))
  expect_true("gee_fit_com_interacao" %in% names(clean))
  expect_true("predictions" %in% names(clean))
  expect_true("auc" %in% names(clean))

  # O bloco emmeans deve ter sido anexado.
  expect_true("emmeans" %in% names(clean))
  expect_true(all(c(
    "emm_time", "pairs_time", "trends", "pairs_trends",
    "emm_time_df", "pairs_time_df",
    "trends_df", "pairs_trends_df"
  ) %in% names(clean$emmeans)))
})

test_that("run_di_pipeline supports Czermainski and McKinney indices", {

  skip_if_not_installed("openxlsx")
  skip_if_not_installed("emmeans")

  set.seed(456)

  base <- expand.grid(
    block = factor(1:4),
    trat = factor(c("A", "B")),
    time = 1:3,
    class = c("F0", "F1", "F2", "F3")
  )

  class_num <- as.numeric(sub("F", "", base$class))
  trat_num <- match(base$trat, c("A", "B")) - 1

  lambda <- 8 +
    0.8 * base$time +
    0.7 * trat_num +
    0.4 * class_num +
    0.15 * as.numeric(base$block)

  base$freq <- stats::rpois(nrow(base), lambda = lambda) + 1L

  arq <- tempfile(fileext = ".xlsx")
  openxlsx::write.xlsx(list(CRD_long = base), arq)

  res_default <- infectionIndex::run_di_pipeline(
    excel_file = arq,
    sheet_prefer = "CRD_long",
    corstr = "independence",
    save_outputs = FALSE
  )

  res_cz <- infectionIndex::run_di_pipeline(
    excel_file = arq,
    sheet_prefer = "CRD_long",
    index = "czermainski",
    corstr = "independence",
    save_outputs = FALSE
  )

  res_mk <- infectionIndex::run_di_pipeline(
    excel_file = arq,
    sheet_prefer = "CRD_long",
    index = "mckinney",
    corstr = "independence",
    save_outputs = FALSE
  )

  expect_equal(res_default$out$meta$index, "czermainski")
  expect_equal(res_cz$out$meta$index, "czermainski")
  expect_equal(res_mk$out$meta$index, "mckinney")

  expect_equal(
    res_default$out$di_por_tempo$DI,
    res_cz$out$di_por_tempo$DI,
    tolerance = 1e-14
  )

  first <- base[
    base$block == 1 &
    base$trat == "A" &
    base$time == 1,
  ]

  first <- first[order(as.numeric(sub("F", "", first$class))), ]

  expected_mk <- infectionIndex::mckinney_I(first$freq)

  di_mk <- res_mk$out$di_por_tempo |>
    dplyr::arrange(block, trat, time)

  got_mk <- di_mk$DI[1]

  expect_equal(got_mk, expected_mk, tolerance = 1e-14)

  expect_equal(res_mk$out_clean$meta$index, "mckinney")

  expect_false(isTRUE(all.equal(
    res_cz$out$di_por_tempo$DI,
    res_mk$out$di_por_tempo$DI,
    tolerance = 1e-12
  )))
})

test_that("pipeline supports AUDPC and AUDPS progress metrics", {

  skip_if_not_installed("openxlsx")
  skip_if_not_installed("emmeans")

  set.seed(789)

  base <- expand.grid(
    block = factor(1:4),
    trat = factor(c("A", "B")),
    time = 1:4,
    class = c("F0", "F1", "F2", "F3")
  )

  class_num <- as.numeric(sub("F", "", base$class))
  trat_num <- match(base$trat, c("A", "B")) - 1

  lambda <- 7 +
    0.9 * base$time +
    0.8 * trat_num +
    0.5 * class_num +
    0.2 * as.numeric(base$block)

  base$freq <- stats::rpois(nrow(base), lambda = lambda) + 1L

  arq <- tempfile(fileext = ".xlsx")
  openxlsx::write.xlsx(list(CRD_long = base), arq)

  run_one <- function(index, progress_metric) {
    infectionIndex::run_di_pipeline(
      excel_file = arq,
      sheet_prefer = "CRD_long",
      index = index,
      progress_metric = progress_metric,
      corstr = "independence",
      save_outputs = FALSE
    )
  }

  cz_pc <- run_one("czermainski", "audpc")
  cz_ps <- run_one("czermainski", "audps")
  mk_pc <- run_one("mckinney", "audpc")
  mk_ps <- run_one("mckinney", "audps")

  results <- list(cz_pc, cz_ps, mk_pc, mk_ps)
  expected_index <- c("czermainski", "czermainski", "mckinney", "mckinney")
  expected_metric <- c("audpc", "audps", "audpc", "audps")

  for (i in seq_along(results)) {
    r <- results[[i]]

    expect_equal(r$out$meta$index, expected_index[i])
    expect_equal(r$out$meta$progress_metric, expected_metric[i])

    expect_true(all(c("AUC", "AUDPC", "AUDPS") %in%
                    names(r$out$auc$by_parcela)))

    if (expected_metric[i] == "audpc") {
      expect_equal(r$out$auc$by_parcela$AUC,
                   r$out$auc$by_parcela$AUDPC)
    } else {
      expect_equal(r$out$auc$by_parcela$AUC,
                   r$out$auc$by_parcela$AUDPS)
    }

    expect_equal(r$out_clean$meta$index, expected_index[i])
    expect_equal(r$out_clean$meta$progress_metric, expected_metric[i])

    expect_true(all(c("AUC", "AUDPC", "AUDPS") %in%
                    names(r$out_clean$auc$by_parcela)))

    if (expected_metric[i] == "audpc") {
      expect_equal(r$out_clean$auc$by_parcela$AUC,
                   r$out_clean$auc$by_parcela$AUDPC)
    } else {
      expect_equal(r$out_clean$auc$by_parcela$AUC,
                   r$out_clean$auc$by_parcela$AUDPS)
    }
  }

  # Changing only the progress metric must not change DI.
  expect_equal(
    cz_pc$out$di_por_tempo$DI,
    cz_ps$out$di_por_tempo$DI,
    tolerance = 1e-14
  )

  expect_equal(
    mk_pc$out$di_por_tempo$DI,
    mk_ps$out$di_por_tempo$DI,
    tolerance = 1e-14
  )

  # AUDPS and AUDPC should not collapse to the same quantity here.
  expect_false(isTRUE(all.equal(
    cz_pc$out$auc$by_parcela$AUDPC,
    cz_pc$out$auc$by_parcela$AUDPS,
    tolerance = 1e-12
  )))
})



test_that("outlier_action flag detects but does not remove flagged parcels", {

  set.seed(20260929)

  base <- expand.grid(
    block = paste0("bl", 1:6),
    trat = c("A", "B", "C"),
    time = 1:4,
    class = 0:3,
    KEEP.OUT.ATTRS = FALSE,
    stringsAsFactors = FALSE
  )

  # Variable frequencies avoid a singular GEE covariance matrix.
  base$freq <- stats::rpois(nrow(base), lambda = 8) + 1L

  # Deliberately create one extreme parcel.
  idx_extreme <- base$block == "bl6" & base$trat == "A"
  base$freq[idx_extreme & base$class < 3] <- 1L
  base$freq[idx_extreme & base$class == 3] <- 200L

  arq <- tempfile(fileext = ".xlsx")
  openxlsx::write.xlsx(list(CRD_long = base), arq)

  res <- infectionIndex::run_di_pipeline(
    excel_file = arq,
    sheet_prefer = "CRD_long",
    corstr = "independence",
    outlier_action = "flag",
    save_outputs = FALSE
  )

  expect_gt(nrow(res$outliers$detected), 0L)
  expect_equal(nrow(res$outliers$dropped), 0L)
  expect_equal(res$out$meta$outlier_action, "flag")
  expect_equal(res$out_clean$meta$outlier_action, "flag")
  expect_equal(res$out$meta$n_outliers_flagged,
               nrow(res$outliers$detected))
  expect_equal(res$out_clean$meta$n_outliers_removed, 0L)
  expect_equal(nrow(res$out$di_por_tempo),
               nrow(res$out_clean$di_por_tempo))
})

test_that("outlier_action remove_all removes every flagged parcel", {

  set.seed(20260929)

  base <- expand.grid(
    block = paste0("bl", 1:6),
    trat = c("A", "B", "C"),
    time = 1:4,
    class = 0:3,
    KEEP.OUT.ATTRS = FALSE,
    stringsAsFactors = FALSE
  )

  base$freq <- stats::rpois(nrow(base), lambda = 8) + 1L

  idx_extreme <- base$block == "bl6" & base$trat == "A"
  base$freq[idx_extreme & base$class < 3] <- 1L
  base$freq[idx_extreme & base$class == 3] <- 200L

  arq <- tempfile(fileext = ".xlsx")
  openxlsx::write.xlsx(list(CRD_long = base), arq)

  res <- infectionIndex::run_di_pipeline(
    excel_file = arq,
    sheet_prefer = "CRD_long",
    corstr = "independence",
    outlier_action = "remove_all",
    save_outputs = FALSE
  )

  n_flag <- nrow(res$outliers$detected)

  expect_gt(n_flag, 0L)
  expect_equal(nrow(res$outliers$dropped), n_flag)
  expect_equal(res$out$meta$outlier_action, "remove_all")
  expect_equal(res$out_clean$meta$outlier_action, "remove_all")
  expect_equal(res$out_clean$meta$n_outliers_flagged, n_flag)
  expect_equal(res$out_clean$meta$n_outliers_removed, n_flag)

  flagged <- paste(
    res$outliers$detected$block,
    res$outliers$detected$trat,
    sep = "::"
  )

  remaining <- paste(
    res$out_clean$di_por_tempo$block,
    res$out_clean$di_por_tempo$trat,
    sep = "::"
  )

  expect_false(any(flagged %in% remaining))
})


test_that("run_di_pipeline supports DIC with explicit unit and no block", {

  set.seed(456)

  d <- expand.grid(
    unit = paste0("U", 1:12),
    time = 1:4,
    class = 0:3,
    KEEP.OUT.ATTRS = FALSE,
    stringsAsFactors = FALSE
  )

  unit_trat <- setNames(
    rep(c("A", "B"), each = 6),
    paste0("U", 1:12)
  )

  d$trat <- unit_trat[d$unit]
  d$freq <- sample(1:12, nrow(d), replace = TRUE)
  d <- d[, c("unit", "trat", "time", "class", "freq")]

  f <- tempfile(fileext = ".xlsx")

  openxlsx::write.xlsx(
    d,
    f,
    sheetName = "DIC_long",
    overwrite = TRUE
  )

  res <- infectionIndex::run_di_pipeline(
    excel_file = f,
    sheet_prefer = "DIC_long",
    index = "czermainski",
    corstr = "independence",
    progress_metric = "audpc",
    save_outputs = FALSE,
    outlier_action = "flag"
  )

  expect_equal(nrow(res$out$di_por_tempo), 48L)
  expect_equal(length(unique(res$out$di_por_tempo$unit)), 12L)
  expect_false("block" %in% names(res$out$di_por_tempo))

  expect_equal(
    length(res$out$gee_fit_com_interacao$geese$clusz),
    12L
  )
  expect_true(all(
    res$out$gee_fit_com_interacao$geese$clusz == 4L
  ))

  expect_equal(nrow(res$out$auc$by_parcela), 12L)
  expect_true("unit" %in% names(res$out$auc$by_parcela))
  expect_equal(nrow(res$out$predictions), 8L)

  expect_equal(res$out$meta$index, "czermainski")
  expect_equal(res$out$meta$progress_metric, "audpc")
})


test_that("run_di_pipeline preserves block when explicit unit is supplied", {
  set.seed(789)

  d <- expand.grid(
    unit = paste0("U", 1:12),
    time = 1:4,
    class = 0:3,
    KEEP.OUT.ATTRS = FALSE,
    stringsAsFactors = FALSE
  )

  unit_trat <- setNames(
    rep(c("A", "B"), each = 6),
    paste0("U", 1:12)
  )

  unit_block <- setNames(
    rep(1:6, times = 2),
    paste0("U", 1:12)
  )

  d$block <- unit_block[d$unit]
  d$trat  <- unit_trat[d$unit]
  d$freq  <- sample(1:12, nrow(d), replace = TRUE)

  d <- d[, c("unit", "block", "trat", "time", "class", "freq")]

  f <- tempfile(fileext = ".xlsx")
  openxlsx::write.xlsx(
    d, f,
    sheetName = "unit_block_long",
    overwrite = TRUE
  )

  res <- run_di_pipeline(
    excel_file = f,
    sheet_prefer = "unit_block_long",
    index = "czermainski",
    corstr = "independence",
    progress_metric = "audpc",
    save_outputs = FALSE,
    outlier_action = "flag"
  )

  di <- res$out$di_por_tempo

  expect_equal(nrow(di), 48L)
  expect_true("unit" %in% names(di))
  expect_true("block" %in% names(di))
  expect_equal(length(unique(di$unit)), 12L)
  expect_equal(length(unique(di$block)), 6L)

  clusz <- res$out$gee_fit_com_interacao$geese$clusz
  expect_equal(length(clusz), 12L)
  expect_true(all(clusz == 4L))

  expect_equal(nrow(res$out$auc$by_parcela), 12L)
  expect_true("unit" %in% names(res$out$auc$by_parcela))
  expect_true("block" %in% names(res$out$auc$by_parcela))
}) 


test_that("run_di_pipeline supports factorial designs end-to-end", {
  set.seed(20260930)

  d <- expand.grid(
    block = paste0("B", 1:4),
    cultivar = c("C1", "C2"),
    produto = c("P1", "P2"),
    time = 1:4,
    class = 0:2,
    KEEP.OUT.ATTRS = FALSE,
    stringsAsFactors = FALSE
  )

  # Frequências positivas com variação entre blocos,
  # fatores, tempo e classes.
  block_eff <- c(B1 = 0L, B2 = 1L, B3 = 2L, B4 = 1L)

  d$freq <- with(
    d,
    8L +
      block_eff[block] +
      2L * (cultivar == "C2") +
      3L * (produto == "P2") +
      time +
      2L * class +
      ((as.integer(factor(block)) + time + class) %% 3L)
  )

  d$freq <- as.integer(d$freq)

  f <- tempfile(fileext = ".xlsx")

  openxlsx::write.xlsx(
    d,
    f,
    sheetName = "factorial_long",
    overwrite = TRUE
  )

  res <- run_di_pipeline(
    excel_file = f,
    sheet_prefer = "factorial_long",
    index = "czermainski",
    corstr = "independence",
    progress_metric = "audpc",
    save_outputs = FALSE,
    outlier_action = "flag",
    factors = c("cultivar", "produto")
  )

  di <- res$out$di_por_tempo

  expect_equal(nrow(di), 64L)
  expect_true(all(c("block", "cultivar", "produto", "time") %in% names(di)))
  expect_equal(res$out$meta$factors, c("cultivar", "produto"))

  clusz <- res$out$gee_fit_com_interacao$geese$clusz
  expect_equal(length(clusz), 16L)
  expect_true(all(clusz == 4L))

  expect_equal(nrow(res$out$predictions), 16L)
  expect_true(all(c("cultivar", "produto", "time") %in%
                  names(res$out$predictions)))

  expect_equal(nrow(res$out$auc$by_parcela), 16L)
  expect_true(all(c("block", "cultivar", "produto") %in%
                  names(res$out$auc$by_parcela)))

  expect_equal(nrow(res$out$auc$summary), 4L)
  expect_true(all(c("cultivar", "produto", "n", "mean", "sd", "se",
                    "lwr", "upr") %in% names(res$out$auc$summary)))
  expect_equal(sum(res$out$auc$summary$n), 16L)

  # O teste robusto legado de progresso permanece unifatorial.
  expect_null(res$out$auc$tests)

  expect_s3_class(res$out$plots$pred_gee, "ggplot")
  expect_s3_class(res$out$plots$auc_violin, "ggplot")
  expect_s3_class(res$out$plots$heatmap, "ggplot")

  expect_false(is.null(res$out_clean$emmeans$emm_time_df))
  expect_equal(nrow(res$out_clean$emmeans$emm_time_df), 4L)
  expect_true(all(c("cultivar", "produto") %in%
                  names(res$out_clean$emmeans$emm_time_df)))

  expect_false(is.null(res$out_clean$emmeans$trends_df))
  expect_equal(nrow(res$out_clean$emmeans$trends_df), 4L)
  expect_true(all(c("cultivar", "produto", "time.trend") %in%
                  names(res$out_clean$emmeans$trends_df)))

  expect_s3_class(res$out_clean$plots$trends, "ggplot")

  expect_true(is.data.frame(res$out$interaction_test))
  expect_equal(res$out$interaction_test$term, "interaction")
  expect_equal(res$out$interaction_test$df, 3)
})

Try the infectionIndex package in your browser

Any scripts or data that you put into this service are public.

infectionIndex documentation built on Dec. 4, 2026, 5:10 p.m.