R/coverage_checks.R

Defines functions coverage_summarize_results coverage_checkpoint_rows_valid coverage_merge_shard_rows coverage_shard_output_path coverage_parse_shard_args coverage_shard_grid coverage_bootstrap_counts_valid coverage_runtime_source_paths coverage_failure_counts coverage_prebuild_receipt_valid coverage_checkpoint_metadata_matches coverage_write_checkpoint coverage_canonical_output_path coverage_acquire_run_lock coverage_fit_interval_consistency_valid coverage_interval_status_valid coverage_runtime_identity_fields coverage_interval_status_available coverage_interval_available

coverage_interval_available <- function(lower, upper) {
  if (!is.numeric(lower) || !is.numeric(upper) || length(lower) != length(upper)) {
    stop("Interval limits must be numeric vectors of equal length.", call. = FALSE)
  }
  available <- is.finite(lower) & is.finite(upper)
  if (any(available & lower > upper)) {
    stop("An available interval has a lower limit greater than its upper limit.",
         call. = FALSE)
  }
  available
}

coverage_interval_status_available <- function(lower, upper, status) {
  if (!is.character(status) || length(status) != length(lower)) {
    stop("Interval statuses must be a character vector matching the limits.",
         call. = FALSE)
  }
  coverage_interval_available(lower, upper) &
    !is.na(status) & status %in% c("ok", "bootstrap")
}

coverage_runtime_identity_fields <- function(candidate_sha,
                                             package_source_sha256,
                                             loaded_package_path,
                                             loaded_dll_sha256,
                                             tmb_version, r_version,
                                             r_platform, rng_kind) {
  fields <- c(
    candidate_sha, package_source_sha256, loaded_package_path,
    loaded_dll_sha256, tmb_version, r_version, r_platform, rng_kind
  )
  if (!is.character(fields) || length(fields) != 8L || anyNA(fields) ||
      any(!nzchar(fields))) {
    stop("Runtime identity requires eight non-empty character fields.",
         call. = FALSE)
  }
  unname(fields)
}

coverage_interval_status_valid <- function(x) {
  required <- c("conf_low", "conf_high", "interval_available",
                "method_requested", "method_returned", "conf_status")
  if (!all(required %in% names(x))) return(FALSE)
  available <- coverage_interval_status_available(
    x$conf_low, x$conf_high, as.character(x$conf_status)
  )
  if (!identical(as.logical(x$interval_available), available)) return(FALSE)
  method_requested <- as.character(x$method_requested)
  method_returned <- as.character(x$method_returned)
  status <- as.character(x$conf_status)
  if (any(available & (is.na(method_returned) | is.na(status) |
                       is.na(method_requested)))) return(FALSE)
  if (any(!is.na(method_returned) & method_returned != method_requested,
          na.rm = TRUE)) {
    return(FALSE)
  }
  expected_status <- ifelse(method_requested == "bootstrap",
                            "bootstrap", "ok")
  if (any(available & status != expected_status, na.rm = TRUE)) {
    return(FALSE)
  }
  if (any(!available & status %in% c("ok", "bootstrap"), na.rm = TRUE)) {
    return(FALSE)
  }
  TRUE
}

coverage_fit_interval_consistency_valid <- function(x) {
  required <- c("n_groups", "replicate", "target", "fit_converged",
                "pd_hess", "estimate", "conf_low", "conf_high",
                "interval_available", "method_returned", "conf_status")
  if (!is.data.frame(x) || !all(required %in% names(x)) ||
      !is.logical(x$fit_converged) || anyNA(x$fit_converged) ||
      !is.logical(x$pd_hess) || anyNA(x$pd_hess) ||
      !is.logical(x$interval_available) || anyNA(x$interval_available)) {
    return(FALSE)
  }
  failed_fit <- !x$fit_converged
  if (any(failed_fit & (x$pd_hess | x$interval_available |
                        is.finite(x$estimate) | is.finite(x$conf_low) |
                        is.finite(x$conf_high) |
                        !is.na(x$method_returned) |
                        !is.na(x$conf_status)))) {
    return(FALSE)
  }
  if (any(x$fit_converged & !is.finite(x$estimate))) return(FALSE)
  if (any(!x$pd_hess & x$interval_available &
          x$method_returned %in% "wald")) return(FALSE)
  key <- interaction(x$n_groups, x$replicate, drop = TRUE)
  for (idx in split(seq_len(nrow(x)), key)) {
    rows <- x[idx, , drop = FALSE]
    if (length(unique(rows$fit_converged)) != 1L ||
        length(unique(rows$pd_hess)) != 1L) {
      return(FALSE)
    }
    target_key <- interaction(rows$target, drop = TRUE)
    for (target_idx in split(seq_len(nrow(rows)), target_key)) {
      estimates <- rows$estimate[target_idx]
      if (length(unique(estimates)) > 1L) return(FALSE)
    }
  }
  TRUE
}

coverage_acquire_run_lock <- function(output_path) {
  lock_path <- paste0(output_path, ".lock")
  if (!dir.create(lock_path, showWarnings = FALSE, recursive = FALSE)) {
    stop(
      "A coverage run lock already exists at ", lock_path,
      ". Confirm no run is active, then remove a stale lock explicitly.",
      call. = FALSE
    )
  }
  owner <- c(
    paste0("pid=", Sys.getpid()),
    paste0("host=", Sys.info()[["nodename"]]),
    paste0("started=", format(Sys.time(), tz = "UTC", usetz = TRUE))
  )
  tryCatch(writeLines(owner, file.path(lock_path, "owner")), error = function(e) {
    unlink(lock_path, recursive = TRUE)
    stop("Could not record coverage lock owner: ", conditionMessage(e),
         call. = FALSE)
  })
  function() unlink(lock_path, recursive = TRUE)
}

coverage_canonical_output_path <- function(path) {
  if (!is.character(path) || length(path) != 1L || is.na(path) ||
      !nzchar(path) || basename(path) %in% c(".", "..")) {
    stop("Coverage output must be one non-empty file path.", call. = FALSE)
  }
  path <- path.expand(path)
  parent <- dirname(path)
  dir.create(parent, showWarnings = FALSE, recursive = TRUE)
  parent <- normalizePath(parent, winslash = "/", mustWork = TRUE)
  canonical <- file.path(parent, basename(path))
  if (dir.exists(canonical)) {
    stop("Coverage output path names a directory: ", canonical, call. = FALSE)
  }
  link_target <- Sys.readlink(canonical)
  if (length(link_target) && !is.na(link_target) && nzchar(link_target) &&
      !file.exists(canonical)) {
    stop("Coverage output cannot be a dangling symbolic link: ", canonical,
         call. = FALSE)
  }
  if (file.exists(canonical)) {
    canonical <- normalizePath(canonical, winslash = "/", mustWork = TRUE)
  }
  canonical
}

coverage_write_checkpoint <- function(checkpoint, checkpoint_path) {
  tmp_path <- tempfile(
    pattern = paste0(basename(checkpoint_path), ".tmp-"),
    tmpdir = dirname(checkpoint_path)
  )
  on.exit(unlink(tmp_path), add = TRUE)
  saveRDS(checkpoint, tmp_path)
  if (!file.rename(tmp_path, checkpoint_path)) {
    stop("Could not atomically replace checkpoint at ", checkpoint_path,
         call. = FALSE)
  }
  invisible(checkpoint_path)
}

coverage_checkpoint_metadata_matches <- function(checkpoint_meta, expected) {
  if (!is.list(checkpoint_meta) || !is.list(expected) ||
      is.null(names(expected)) || any(!nzchar(names(expected)))) {
    return(FALSE)
  }
  identical(checkpoint_meta[names(expected)], expected)
}

coverage_prebuild_receipt_valid <- function(receipt_lines, candidate_sha,
                                            source_root, dll_sha256) {
  if (!is.character(receipt_lines) || anyNA(receipt_lines) ||
      length(candidate_sha) != 1L || is.na(candidate_sha) ||
      length(source_root) != 1L || is.na(source_root) ||
      length(dll_sha256) != 1L || is.na(dll_sha256)) {
    return(FALSE)
  }
  has_equals <- grepl("=", receipt_lines, fixed = TRUE)
  if (any(!has_equals)) return(FALSE)
  keys <- sub("=.*$", "", receipt_lines)
  values <- sub("^[^=]*=", "", receipt_lines)
  if (anyDuplicated(keys)) return(FALSE)
  expected <- c(
    candidate_sha = candidate_sha,
    dll_sha256 = dll_sha256,
    root = source_root
  )
  for (key in names(expected)) {
    index <- match(key, keys)
    if (is.na(index) || !identical(values[[index]], unname(expected[[key]]))) {
      return(FALSE)
    }
  }
  TRUE
}

coverage_failure_counts <- function(replicates) {
  required <- c(
    "fit_converged", "pd_hess", "interval_available",
    "method_requested", "method_returned"
  )
  if (!is.data.frame(replicates) || !all(required %in% names(replicates))) {
    stop("Replicate rows lack fields required for failure counts.", call. = FALSE)
  }
  for (field in c("fit_converged", "pd_hess", "interval_available")) {
    if (!is.logical(replicates[[field]]) || anyNA(replicates[[field]])) {
      stop("Replicate field `", field, "` must contain non-missing logical values.",
           call. = FALSE)
    }
  }
  if (!is.character(replicates$method_requested) ||
      !is.character(replicates$method_returned)) {
    stop("Requested and returned methods must be character vectors.", call. = FALSE)
  }
  c(
    n_fit_failed = as.integer(sum(!replicates$fit_converged)),
    n_pd_hess_failed = as.integer(sum(replicates$fit_converged &
                                        !replicates$pd_hess)),
    n_interval_unavailable = as.integer(sum(!replicates$interval_available)),
    n_fallback = as.integer(sum(!is.na(replicates$method_returned) &
                                  replicates$method_returned !=
                                    replicates$method_requested))
  )
}

coverage_runtime_source_paths <- function(root = ".") {
  old <- getwd()
  on.exit(setwd(old), add = TRUE)
  setwd(root)
  c(
    "DESCRIPTION", "NAMESPACE",
    sort(list.files("R", pattern = "[.]R$", recursive = TRUE,
                    full.names = TRUE)),
    sort(list.files("src", pattern = "[.](cpp|h)$", recursive = TRUE,
                    full.names = TRUE))
  )
}

coverage_bootstrap_counts_valid <- function(replicates, nboot,
                                            min_usable = 20L) {
  required <- c(
    "n_groups", "replicate", "method_requested", "fit_converged",
    "n_boot_requested", "n_boot_converged", "n_boot_failed",
    "bootstrap_error"
  )
  if (!is.data.frame(replicates) || !all(required %in% names(replicates))) {
    return(FALSE)
  }
  key <- interaction(replicates$n_groups, replicates$replicate, drop = TRUE)
  for (idx in split(seq_len(nrow(replicates)), key)) {
    rows <- replicates[idx, , drop = FALSE]
    if (length(unique(rows$fit_converged)) != 1L) return(FALSE)
    counts <- rows[c("n_boot_requested", "n_boot_converged", "n_boot_failed")]
    if (!isTRUE(rows$fit_converged[[1L]])) {
      if (any(!is.na(unlist(counts)))) return(FALSE)
      next
    }
    if (any(is.na(rows$n_boot_requested)) ||
        any(rows$n_boot_requested != nboot)) return(FALSE)
    count_matrix <- as.matrix(counts[c("n_boot_converged", "n_boot_failed")])
    if (all(is.na(count_matrix))) {
      failed <- any(rows$method_requested == "bootstrap" &
                      !is.na(rows$bootstrap_error) &
                      nzchar(rows$bootstrap_error))
      if (!failed) return(FALSE)
      next
    }
    if (anyNA(count_matrix) ||
        any(count_matrix[, 1L] < 0L | count_matrix[, 1L] > nboot) ||
        any(count_matrix[, 2L] < 0L | count_matrix[, 2L] > nboot) ||
        any(rowSums(count_matrix) != nboot) ||
        any(apply(count_matrix, 2L, function(x) length(unique(x)) != 1L))) {
      return(FALSE)
    }
  }
  if (all(c("conf_low", "conf_high", "conf_status") %in%
          names(replicates))) {
    bootstrap_available <- replicates$method_requested == "bootstrap" &
      coverage_interval_status_available(
        replicates$conf_low, replicates$conf_high,
        as.character(replicates$conf_status)
      )
    if (any(bootstrap_available &
            replicates$n_boot_converged < min_usable)) {
      return(FALSE)
    }
  }
  TRUE
}

coverage_shard_grid <- function(group_counts, nsim, shard_index = 1L,
                                shard_count = 1L) {
  valid_positive_integer <- function(x, name) {
    is.numeric(x) && length(x) == 1L && !is.na(x) && is.finite(x) &&
      x >= 1 && x == as.integer(x)
  }
  if (!is.numeric(group_counts) || !length(group_counts) ||
      anyNA(group_counts) || any(!is.finite(group_counts)) ||
      any(group_counts < 2L) || any(group_counts != as.integer(group_counts)) ||
      anyDuplicated(group_counts)) {
    stop("`group_counts` must contain unique integers of at least two groups.",
         call. = FALSE)
  }
  if (!valid_positive_integer(nsim, "nsim")) {
    stop("`nsim` must be one positive integer.", call. = FALSE)
  }
  if (!valid_positive_integer(shard_count, "shard_count")) {
    stop("`shard_count` must be one positive integer.", call. = FALSE)
  }
  if (!valid_positive_integer(shard_index, "shard_index") ||
      shard_index > shard_count) {
    stop("`shard_index` must be an integer in 1:`shard_count`.",
         call. = FALSE)
  }
  if (shard_count > length(group_counts) * nsim) {
    stop("`shard_count` cannot exceed the number of replicate datasets.",
         call. = FALSE)
  }

  grid <- do.call(rbind, lapply(as.integer(group_counts), function(group) {
    data.frame(n_groups = group, replicate = seq_len(as.integer(nsim)))
  }))
  assigned <- (seq_len(nrow(grid)) - 1L) %% as.integer(shard_count) + 1L
  grid[assigned == as.integer(shard_index), , drop = FALSE]
}

coverage_parse_shard_args <- function(args) {
  if (!is.character(args) || anyNA(args)) {
    stop("Command-line arguments must be non-missing character values.",
         call. = FALSE)
  }
  index_flag <- which(args == "--shard-index")
  count_flag <- which(args == "--shard-count")
  if (length(index_flag) != length(count_flag) ||
      length(index_flag) > 1L) {
    stop("Supply `--shard-index` and `--shard-count` exactly once as a pair.",
         call. = FALSE)
  }
  if (!length(index_flag)) {
    return(list(shard_index = 1L, shard_count = 1L,
                remaining_args = args))
  }
  positions <- c(index_flag, count_flag)
  if (any(positions == length(args)) || abs(diff(positions)) != 2L) {
    stop("Each shard flag must have an integer value and they must be paired.",
         call. = FALSE)
  }
  index_text <- args[[index_flag + 1L]]
  count_text <- args[[count_flag + 1L]]
  parse_integer <- function(x, name) {
    if (!grepl("^[1-9][0-9]*$", x)) {
      stop("`", name, "` must be a positive integer.", call. = FALSE)
    }
    value <- suppressWarnings(as.integer(x))
    if (is.na(value)) stop("`", name, "` is too large.", call. = FALSE)
    value
  }
  shard_index <- parse_integer(index_text, "--shard-index")
  shard_count <- parse_integer(count_text, "--shard-count")
  if (shard_index > shard_count) {
    stop("`--shard-index` cannot exceed `--shard-count`.", call. = FALSE)
  }
  remove <- c(index_flag, index_flag + 1L, count_flag, count_flag + 1L)
  list(shard_index = shard_index, shard_count = shard_count,
       remaining_args = args[-remove])
}

coverage_shard_output_path <- function(base_path, shard_index, shard_count) {
  is_positive_integer <- function(x) {
    is.numeric(x) && length(x) == 1L && !is.na(x) && is.finite(x) &&
      x >= 1 && x == as.integer(x)
  }
  if (!is.character(base_path) || length(base_path) != 1L ||
      is.na(base_path) || !nzchar(base_path) ||
      basename(base_path) %in% c(".", "..")) {
    stop("`base_path` must be one non-empty file path.", call. = FALSE)
  }
  if (!is_positive_integer(shard_count) ||
      !is_positive_integer(shard_index) || shard_index > shard_count) {
    stop("Shard index and count must be positive integers with index <= count.",
         call. = FALSE)
  }
  if (shard_count == 1L) return(base_path)
  extension <- tools::file_ext(base_path)
  stem <- if (nzchar(extension)) {
    substr(base_path, 1L, nchar(base_path) - nchar(extension) - 1L)
  } else {
    base_path
  }
  suffix <- sprintf(".shard-%03d-of-%03d", as.integer(shard_index),
                     as.integer(shard_count))
  paste0(stem, suffix, if (nzchar(extension)) paste0(".", extension) else "")
}

coverage_merge_shard_rows <- function(shards, group_counts, nsim,
                                      methods = list(
                                        CTmax = c("wald", "profile", "bootstrap"),
                                        sigma_CTmax = c("wald", "bootstrap")
                                      )) {
  if (!is.list(shards) || !length(shards) ||
      any(!vapply(shards, is.data.frame, logical(1)))) {
    stop("`shards` must be a non-empty list of data frames.", call. = FALSE)
  }
  key_columns <- c("n_groups", "replicate", "target", "method_requested")
  if (any(!vapply(shards, function(x) all(key_columns %in% names(x)),
                  logical(1)))) {
    stop("Every shard must contain the dataset and requested-method key columns.",
         call. = FALSE)
  }
  if (any(!vapply(shards, function(x) identical(names(x), names(shards[[1L]])),
                  logical(1)))) {
    stop("Shard result columns must have identical names and order.",
         call. = FALSE)
  }
  if (!is.list(methods) || is.null(names(methods)) ||
      any(!nzchar(names(methods))) || anyDuplicated(names(methods)) ||
      any(!vapply(methods, function(x) is.character(x) && length(x) &&
                  !anyNA(x) && !anyDuplicated(x), logical(1)))) {
    stop("`methods` must be a named list of unique requested methods.",
         call. = FALSE)
  }

  observed <- do.call(rbind, shards)
  key <- function(x) do.call(paste, c(x[key_columns], sep = "|"))
  observed_key <- key(observed)
  if (anyDuplicated(observed_key)) {
    stop("Merged shard results contain duplicate dataset/method rows.",
         call. = FALSE)
  }
  expected <- do.call(rbind, lapply(as.integer(group_counts), function(group) {
    do.call(rbind, lapply(seq_len(as.integer(nsim)), function(replicate) {
      do.call(rbind, lapply(names(methods), function(target) {
        data.frame(
          n_groups = group, replicate = replicate, target = target,
          method_requested = methods[[target]], stringsAsFactors = FALSE
        )
      }))
    }))
  }))
  expected_key <- key(expected)
  if (length(observed_key) != length(expected_key) ||
      !setequal(observed_key, expected_key)) {
    stop("Merged shard results do not contain the complete requested design.",
         call. = FALSE)
  }
  observed[match(expected_key, observed_key), , drop = FALSE]
}

coverage_checkpoint_rows_valid <- function(rows, allowed_grid,
                                           methods = list(
                                             CTmax = c("wald", "profile", "bootstrap"),
                                             sigma_CTmax = c("wald", "bootstrap")
                                           )) {
  if (!is.data.frame(rows) || !nrow(rows) ||
      !is.data.frame(allowed_grid) ||
      !all(c("n_groups", "replicate") %in% names(allowed_grid)) ||
      !all(c("n_groups", "replicate", "target", "method_requested") %in%
           names(rows)) ||
      !is.list(methods) || is.null(names(methods)) ||
      any(!nzchar(names(methods))) || anyDuplicated(names(methods)) ||
      any(!vapply(methods, function(x) is.character(x) && length(x) &&
                  !anyNA(x) && !anyDuplicated(x), logical(1)))) {
    return(FALSE)
  }
  expected_methods <- do.call(rbind, lapply(names(methods), function(target) {
    data.frame(target = target, method_requested = methods[[target]],
               stringsAsFactors = FALSE)
  }))
  method_key <- function(x) paste(x$target, x$method_requested, sep = "|")
  expected_method_key <- method_key(expected_methods)
  row_key <- function(x) paste(x$n_groups, x$replicate, x$target,
                               x$method_requested, sep = "|")
  dataset_key <- function(x) paste(x$n_groups, x$replicate, sep = "|")
  allowed_key <- dataset_key(allowed_grid)
  observed_grid <- unique(rows[c("n_groups", "replicate")])
  observed_dataset_key <- dataset_key(observed_grid)
  observed_row_key <- row_key(rows)
  if (anyDuplicated(allowed_key) || anyDuplicated(observed_row_key) ||
      any(!observed_dataset_key %in% allowed_key) ||
      any(table(factor(dataset_key(rows), levels = observed_dataset_key)) !=
          length(expected_method_key))) {
    return(FALSE)
  }
  for (key in observed_dataset_key) {
    subset <- rows[dataset_key(rows) == key, , drop = FALSE]
    if (!setequal(method_key(subset), expected_method_key)) return(FALSE)
  }
  TRUE
}

coverage_summarize_results <- function(replicates) {
  required <- c(
    "n_groups", "target", "method_requested", "fit_converged", "pd_hess",
    "interval_available", "covered", "width", "estimate", "error_estimate",
    "method_returned"
  )
  if (!is.data.frame(replicates) || !all(required %in% names(replicates)) ||
      !nrow(replicates)) {
    stop("Replicate rows lack fields required for coverage summaries.",
         call. = FALSE)
  }
  key <- interaction(replicates$n_groups, replicates$target,
                     replicates$method_requested, drop = TRUE)
  summary_rows <- lapply(split(replicates, key), function(x) {
    ok_interval <- x$interval_available
    ok_estimate <- is.finite(x$estimate)
    estimate_error <- x$error_estimate[ok_estimate]
    rmse <- if (length(estimate_error)) {
      sqrt(mean(estimate_error^2))
    } else {
      NA_real_
    }
    failure_counts <- coverage_failure_counts(x)
    data.frame(
      n_groups = x$n_groups[[1L]], target = x$target[[1L]],
      method = x$method_requested[[1L]], n_requested = nrow(x),
      as.list(failure_counts),
      fit_rate = mean(x$fit_converged), pd_hess_rate = mean(x$pd_hess),
      interval_rate = mean(ok_interval),
      coverage_available = if (any(ok_interval)) {
        mean(x$covered[ok_interval])
      } else {
        NA_real_
      },
      coverage_mcse = if (any(ok_interval)) {
        p <- mean(x$covered[ok_interval])
        sqrt(p * (1 - p) / sum(ok_interval))
      } else {
        NA_real_
      },
      coverage_all_requested = mean(x$covered),
      median_width = if (any(ok_interval)) median(x$width[ok_interval]) else NA_real_,
      bias = if (length(estimate_error)) mean(estimate_error) else NA_real_,
      bias_mcse = if (length(estimate_error) > 1L) {
        stats::sd(estimate_error) / sqrt(length(estimate_error))
      } else {
        NA_real_
      },
      rmse = rmse,
      rmse_mcse = if (length(estimate_error) > 1L &&
                      is.finite(rmse) && rmse > 0) {
        stats::sd(estimate_error^2) /
          (2 * sqrt(length(estimate_error)) * rmse)
      } else {
        NA_real_
      },
      stringsAsFactors = FALSE
    )
  })
  summary <- do.call(rbind, summary_rows)
  rownames(summary) <- NULL
  summary
}

Try the freqTLS package in your browser

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

freqTLS documentation built on Dec. 4, 2026, 5:11 p.m.