R/network-benchmark.R

Defines functions roc .roc_curve_styles .roc_mode_spec .roc_legend_names .roc_marker_source_position .roc_legend_layout benchmark universal_member_recovery_benchmark nea_member_recovery_benchmark .sample_degree_matched_controls .benchmark_network_info .prediction_counts

Documented in benchmark nea_member_recovery_benchmark roc universal_member_recovery_benchmark

.prediction_counts <- function(scores, labels) {
  keep <- is.finite(scores); scores <- scores[keep]; labels <- labels[keep]
  cutoffs <- c(Inf, sort(unique(scores), decreasing = TRUE), -Inf)
  tp <- fp <- numeric(length(cutoffs))
  positives <- sum(labels == 1L); negatives <- sum(labels == 0L)
  for (i in seq_along(cutoffs)) {
    selected <- scores >= cutoffs[[i]]
    tp[[i]] <- sum(labels[selected] == 1L); fp[[i]] <- sum(labels[selected] == 0L)
  }
  list(tp = list(tp), fp = list(fp), tn = list(negatives - fp),
    fn = list(positives - tp), cutoffs = list(cutoffs))
}

.benchmark_network_info <- function(net) {
  if (igraph::is_igraph(net)) {
    nodes <- igraph::vertex_attr(net, "name")
    degree <- stats::setNames(as.numeric(igraph::degree(net)), nodes)
  } else if (inherits(net, "nearender_indexed_network")) {
    nodes <- net$node_names
    degree <- stats::setNames(as.numeric(Matrix::rowSums(net$adjacency != 0)),
      nodes)
  } else {
    nodes <- names(net$links)
    degree <- stats::setNames(lengths(net$links), nodes)
  }
  list(nodes = nodes, degree = degree, n_vertices = length(nodes),
    n_edges = .network_edge_count(net))
}

.sample_degree_matched_controls <- function(positives, control_pool, degree) {
  if (!length(control_pool)) {
    stop("No non-member controls remain in the network.", call. = FALSE)
  }
  degree_bin <- round(log2(pmax(degree, 1)))
  vapply(positives, function(gene) {
    same_bin <- control_pool[degree_bin[control_pool] == degree_bin[[gene]]]
    if (!length(same_bin)) {
      distance <- abs(log2(pmax(degree[control_pool], 1)) -
        log2(max(degree[[gene]], 1)))
      same_bin <- control_pool[distance == min(distance)]
    }
    sample(same_bin, 1L)
  }, character(1))
}

#' Benchmark a network using known gene sets
#'
#' Test a network's ability to recover known members of pathways or other
#' functional sets by network enrichment. For each member, the function scores
#' connectivity to the remaining members of the set to which it belongs.
#' Randomly selected network nodes, optionally matched by node degree, provide
#' negative controls for classical ROC or precision-recall evaluation. Test
#' sets can be selected by biological context with `mask`. Curves for multiple
#' networks can be combined by passing their returned predictions to [roc()].
#'
#' @param net Undirected igraph network, sparse network, or legacy network with a named
#'   adjacency list in `links` and edge count in `Ntotal`.
#' @param gs Named list of test gene sets.
#' @param mask Regular expression selecting a subset of test-set names.
#' @param min_n Minimum observed links required for a positive member.
#' @param match_by_degree Draw controls from the same rounded log2-degree bin;
#'   known members of every supplied gene set are excluded from the control
#'   pool. This is the recommended option.
#' @param show_below_p One scalar maximum one-sided enrichment p-value shown when
#'   `graph = TRUE`. The default, 1, retains the complete, canonical ROC curve.
#' @param mark_p Optional one scalar one-sided enrichment p-value marked with
#'   a circle. Use `NULL` to omit this marker.
#' @param mark_fdr Optional one scalar enrichment-only FDR threshold marked
#'   with a cross. Only positive enrichment scores are eligible for this marker.
#' @param graph Draw the curve.
#' @param seed Optional random seed for reproducible matched controls.
#' @param case_sensitive Use case-sensitive identifiers.
#' @param verbose Report progress with [message()].
#' @param ... Arguments passed by the deprecated `benchmark()` alias.
#' @return A prediction list accepted by [roc()]. `tp`, `fp`, `tn`,
#'   and `fn` contain cumulative classification counts at every value in
#'   `cutoffs`. `circle_z` and `cross_z` locate the p- and FDR-threshold
#'   markers; `mark_p` and `mark_fdr` retain their displayed probability
#'   values. `nv` and `ne` contain network vertex and edge counts.
#' @references Merid SK, Goranskaya D, Alexeyenko A (2014). Distinguishing
#'   between driver and passenger mutations in individual cancer genomes by
#'   network enrichment analysis. \doi{10.1186/1471-2105-15-308}.
#' @seealso [roc()], [nea.render()]
#' @examples
#' net <- list(links = list(
#'   a = c("b", "c"), b = c("a", "c"), c = c("a", "b", "d"),
#'   d = c("c", "e"), e = "d"), Ntotal = 5)
#' fgs <- list(pathway_1 = c("a", "b"), pathway_2 = c("d", "e"))
#' prediction <- nea_member_recovery_benchmark(net, fgs,
#'   show_below_p = 0.05, seed = 1, verbose = FALSE)
#' names(prediction)
#' @rdname nea_member_recovery_benchmark
#' @export
nea_member_recovery_benchmark <- function(net, gs, mask = ".", min_n = 0,
    match_by_degree = TRUE, show_below_p = 1, mark_p = 0.01,
    mark_fdr = 0.1, graph = FALSE, seed = NULL, case_sensitive = FALSE,
    verbose = TRUE) {
  .assert_flag(graph, "graph"); .assert_flag(case_sensitive, "case_sensitive")
  .assert_flag(match_by_degree, "match_by_degree")
  .assert_flag(verbose, "verbose")
  if (!is.numeric(show_below_p) || length(show_below_p) != 1L ||
      is.na(show_below_p) || show_below_p <= 0 || show_below_p > 1) {
    stop("show_below_p must be one number in (0, 1].", call. = FALSE)
  }
  if (!is.null(mark_p) && (!is.numeric(mark_p) || length(mark_p) != 1L ||
      is.na(mark_p) || mark_p <= 0 || mark_p > 1)) {
    stop("mark_p must be NULL or one number in (0, 1].", call. = FALSE)
  }
  if (!is.null(mark_fdr) &&
      (!is.numeric(mark_fdr) || length(mark_fdr) != 1L || is.na(mark_fdr) ||
       mark_fdr < 0 || mark_fdr > 1)) {
    stop("mark_fdr must be NULL or one number in [0, 1].", call. = FALSE)
  }
  if (!is.character(mask) || length(mask) != 1L || is.na(mask))
    stop("mask must be one regular expression.", call. = FALSE)
  if (length(min_n) != 1L || is.na(min_n) || min_n < 0)
    stop("min_n must be one non-negative number.", call. = FALSE)
  if (!is.null(seed)) {
    if (length(seed) != 1L || is.na(seed))
      stop("seed must be NULL or one value.", call. = FALSE)
    old_seed <- if (exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE))
      get(".Random.seed", envir = .GlobalEnv) else NULL
    on.exit(if (is.null(old_seed)) {
      if (exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE))
        rm(".Random.seed", envir = .GlobalEnv)
    } else assign(".Random.seed", old_seed, envir = .GlobalEnv), add = TRUE)
    set.seed(seed)
  }
  net <- .normalize_network(net, case_sensitive)
  gs <- .normalize_gene_sets(gs, "gs", case_sensitive)
  .assert_compatible_identifiers(GS = gs, NET = net)
  selected_sets <- grep(mask, names(gs), value = TRUE)
  if (!length(selected_sets)) stop("mask selects no gene sets.", call. = FALSE)
  network <- .benchmark_network_info(net)
  node_sets <- as.list(network$nodes); names(node_sets) <- network$nodes
  result <- nea.render(gs[selected_sets], node_sets, net,
    case_sensitive = case_sensitive, na_replace = 0, verbose = verbose)
  rendered <- result$statistics
  real <- null <- numeric()
  negatives <- setdiff(network$nodes, unique(unlist(gs, use.names = FALSE)))
  if (!length(negatives)) stop("No non-member controls remain in the network.",
    call. = FALSE)
  for (set_name in selected_sets) {
    members <- intersect(gs[[set_name]], rownames(rendered$z))
    if (min_n > 0) {
      members <- members[rendered$n.actual[members, set_name] >= min_n]
    }
    if (!length(members)) next
    real <- c(real, rendered$z[members, set_name])
    if (match_by_degree) {
      matched <- .sample_degree_matched_controls(members, negatives,
        network$degree)
    } else {
      matched <- sample(negatives, length(members), replace = TRUE)
    }
    null <- c(null, rendered$z[matched, set_name])
  }
  keep <- is.finite(real) & is.finite(null); real <- real[keep]; null <- null[keep]
  if (!length(real)) stop("No benchmark members map to the network.", call. = FALSE)
  prediction <- .prediction_counts(c(null, real),
    c(rep(0L, length(null)), rep(1L, length(real))))
  eligible_fdr <- if (is.null(mark_fdr)) {
    matrix(FALSE, nrow(rendered$z), ncol(rendered$z),
      dimnames = dimnames(rendered$z))
  } else {
    is.finite(rendered$z) & rendered$z > 0 &
      is.finite(rendered$q) & rendered$q <= mark_fdr
  }
  cross_z <- if (any(eligible_fdr)) {
    min(rendered$z[eligible_fdr])
  } else {
    NA_real_
  }
  prediction[c("cross_z", "nv", "ne")] <- list(cross_z,
    network$n_vertices, network$n_edges)
  prediction[c("mark_p", "mark_fdr")] <- list(mark_p, mark_fdr)
  if (!is.null(mark_p)) {
    prediction$circle_z <- stats::qnorm(mark_p, lower.tail = FALSE)
  }
  if (graph) roc(prediction, max_p = show_below_p)
  prediction
}

#' Benchmark networks and rendering methods by held-out member recovery
#'
#' Randomly split each sufficiently large mapped gene set into training seeds
#' and held-out members. The selected renderer scores every network node
#' against every training set. Held-out members are compared with an equal
#' number of pathway-specific non-member controls.
#'
#' @param net,gs,mask,match_by_degree,graph,seed,case_sensitive,verbose See
#'   [nea_member_recovery_benchmark()].
#' @param method Renderer used for scoring: `"nea"`, `"rwr"`, or
#'   `"pagerank"`.
#' @param renderer_args Named list of additional arguments for the renderer.
#'   Benchmark-managed inputs and options cannot be overridden.
#' @param train_fraction Proportion of mapped set members used as training
#'   seeds.
#' @param min_size Minimum mapped gene-set size eligible for splitting.
#' @param members Whether to return the potentially large training, held-out,
#'   and matched-control identifier lists in `splits` and `controls`.
#' @return A prediction list accepted by [roc()], including classification
#'   counts and cutoffs as well as the method, renderer arguments, score
#'   identifier, train/test splits, matched controls, and split sizes used for
#'   reproducibility.
#' @examples
#' net <- list(links = list(
#'   a = c("b", "c"), b = c("a", "c"), c = c("a", "b", "d"),
#'   d = c("c", "e"), e = c("d", "f"), f = c("e", "g"),
#'   g = c("f", "h"), h = c("g", "i"), i = c("h", "j"),
#'   j = c("i", "k"), k = "j"), Ntotal = 11)
#' fgs <- list(pathway = letters[1:9])
#' prediction <- universal_member_recovery_benchmark(net, fgs,
#'   method = "nea", min_size = 6, seed = 1, verbose = FALSE)
#' prediction$split_sizes
#' @export
universal_member_recovery_benchmark <- function(
    net,
    gs,
    method = c("nea", "rwr", "pagerank"),
    renderer_args = list(),
    mask = ".",
    train_fraction = 2 / 3,
    min_size = 9L,
    match_by_degree = TRUE,
    members = FALSE,
    graph = FALSE,
    seed = NULL,
    case_sensitive = FALSE,
    verbose = TRUE) {
  method <- match.arg(method)
  .assert_flag(match_by_degree, "match_by_degree")
  .assert_flag(members, "members")
  .assert_flag(graph, "graph")
  .assert_flag(case_sensitive, "case_sensitive")
  .assert_flag(verbose, "verbose")
  renderer <- switch(method,
    nea = nea.render,
    rwr = rwr.render,
    pagerank = pagerank.render)
  score_id <- switch(method,
    nea = "z",
    rwr = "rwr",
    pagerank = "pagerank")
  managed_args <- c("ags", "fgs", "net", "case_sensitive", "verbose")
  if (method == "nea") managed_args <- c(managed_args, "na_replace")
  .validate_renderer_args(renderer_args, renderer, method,
    managed = managed_args, managed_label = "benchmark-managed arguments")
  if (!is.character(mask) || length(mask) != 1L || is.na(mask)) {
    stop("mask must be one regular expression.", call. = FALSE)
  }
  if (!is.numeric(train_fraction) || length(train_fraction) != 1L ||
      is.na(train_fraction) || !is.finite(train_fraction) ||
      train_fraction <= 0 || train_fraction >= 1) {
    stop("train_fraction must be one finite number strictly between 0 and 1.",
      call. = FALSE)
  }
  if (length(min_size) != 1L || is.na(min_size) || min_size < 2L ||
      min_size != as.integer(min_size)) {
    stop("min_size must be one integer of at least 2.", call. = FALSE)
  }
  min_size <- as.integer(min_size)
  if (!is.null(seed)) {
    if (length(seed) != 1L || is.na(seed)) {
      stop("seed must be NULL or one value.", call. = FALSE)
    }
    old_seed <- if (exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) {
      get(".Random.seed", envir = .GlobalEnv)
    } else NULL
    on.exit(if (is.null(old_seed)) {
      if (exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) {
        rm(".Random.seed", envir = .GlobalEnv)
      }
    } else {
      assign(".Random.seed", old_seed, envir = .GlobalEnv)
    }, add = TRUE)
    set.seed(seed)
  }

  net <- .normalize_network(net, case_sensitive)
  gs <- .normalize_gene_sets(gs, "gs", case_sensitive)
  .assert_compatible_identifiers(GS = gs, NET = net)
  selected_sets <- grep(mask, names(gs), value = TRUE)
  if (!length(selected_sets)) {
    stop("mask selects no gene sets.", call. = FALSE)
  }

  network <- .benchmark_network_info(net)
  network_nodes <- network$nodes
  mapped_sets <- lapply(gs[selected_sets], intersect, y = network_nodes)
  mapped_sets <- mapped_sets[lengths(mapped_sets) >= min_size]
  if (!length(mapped_sets)) {
    stop("No selected gene set has at least min_size mapped network members.",
      call. = FALSE)
  }
  splits <- lapply(mapped_sets, function(members) {
    n_seed <- round(length(members) * train_fraction)
    n_seed <- max(1L, min(length(members) - 1L, n_seed))
    training <- sample(members, n_seed, replace = FALSE)
    list(training = training, held_out = setdiff(members, training))
  })
  training_sets <- lapply(splits, `[[`, "training")
  node_sets <- as.list(network_nodes)
  names(node_sets) <- network_nodes

  render_args <- list(
    ags = training_sets,
    fgs = node_sets,
    net = net,
    case_sensitive = case_sensitive,
    verbose = verbose
  )
  if (method == "nea") render_args$na_replace <- 0
  rendered <- do.call(renderer, c(render_args, renderer_args))
  scores <- rendered$scores[[score_id]]

  positive_scores <- control_scores <- numeric()
  control_sets <- stats::setNames(vector("list", length(splits)), names(splits))
  for (set_name in names(splits)) {
    positives <- splits[[set_name]]$held_out
    control_pool <- setdiff(network_nodes, mapped_sets[[set_name]])
    if (!length(control_pool)) {
      stop("No non-member controls remain for gene set ", set_name, ".",
        call. = FALSE)
    }
    controls <- if (match_by_degree) {
      .sample_degree_matched_controls(positives, control_pool, network$degree)
    } else {
      sample(control_pool, length(positives), replace = TRUE)
    }
    control_sets[[set_name]] <- controls
    positive_scores <- c(
      positive_scores, scores[positives, set_name, drop = TRUE])
    control_scores <- c(
      control_scores, scores[controls, set_name, drop = TRUE])
  }
  keep <- is.finite(positive_scores) & is.finite(control_scores)
  positive_scores <- positive_scores[keep]
  control_scores <- control_scores[keep]
  if (!length(positive_scores)) {
    stop("No finite benchmark comparisons were produced.", call. = FALSE)
  }

  prediction <- .prediction_counts(
    c(control_scores, positive_scores),
    c(rep(0L, length(control_scores)), rep(1L, length(positive_scores)))
  )
  prediction[c("cross_z", "nv", "ne")] <- list(
    NA_real_, network$n_vertices, network$n_edges)
  prediction[c("mark_p", "mark_fdr")] <- list(NULL, NULL)
  prediction$method <- method
  prediction$renderer_args <- renderer_args
  prediction$score_id <- score_id
  prediction$train_fraction <- train_fraction
  prediction$min_size <- min_size
  prediction$split_sizes <- lapply(splits, function(x) {
    c(training = length(x$training), held_out = length(x$held_out))
  })
  prediction$members <- members
  if (members) {
    prediction$splits <- splits
    prediction$controls <- control_sets
  }
  if (graph) roc(prediction, mode = "roc")
  prediction
}
#' @rdname nea_member_recovery_benchmark
#' @export
benchmark <- function(...) {
  .Deprecated("nea_member_recovery_benchmark")
  nea_member_recovery_benchmark(...)
}

.roc_legend_layout <- function(display_names, objects, cex_leg,
    print_stats, wrap_at = 24L) {
  labels <- display_names
  common_stats <- NULL
  if (print_stats) {
    format_count <- function(value) {
      format(round(as.numeric(value)), big.mark = ",", scientific = FALSE,
        trim = TRUE)
    }
    statistics <- vapply(objects, function(prediction) {
      paste0("N(V)=", format_count(prediction$nv),
        "; N(E)=", format_count(prediction$ne))
    }, character(1))
    if (length(unique(statistics)) == 1L) {
      common_stats <- statistics[[1L]]
    } else {
      separators <- ifelse(nchar(display_names, type = "width") > wrap_at,
        "\n", "; ")
      labels <- paste0(display_names, separators, statistics)
    }
  }
  list(
    labels = labels,
    common_stats = common_stats,
    cex = if (any(grepl("\n", labels, fixed = TRUE))) {
      0.9 * cex_leg
    } else cex_leg
  )
}

.roc_marker_source_position <- function(marker, cutoffs) {
  if (is.null(marker) || length(marker) != 1L || is.na(marker)) {
    return(NA_integer_)
  }
  position <- match(marker, cutoffs)
  if (is.na(position) && is.finite(marker)) {
    distance <- abs(cutoffs - marker)
    distance[!is.finite(distance)] <- Inf
    if (any(is.finite(distance))) position <- which.min(distance)
  }
  position
}

.roc_legend_names <- function(display_names, objects, fdr_odds_ratios) {
  labels <- display_names
  show_odds_ratio <- vapply(objects, function(prediction) {
    !is.null(prediction$mark_fdr)
  }, logical(1))
  format_odds_ratio <- function(value) {
    if (length(value) != 1L || !is.finite(value) || value <= 0) return("NA")
    format(signif(value, 3L), trim = TRUE, scientific = FALSE)
  }
  labels[show_odds_ratio] <- paste0(
    labels[show_odds_ratio], "; OR=",
    vapply(fdr_odds_ratios[show_odds_ratio], format_odds_ratio, character(1))
  )
  labels
}

.roc_mode_spec <- function(mode) {
  modes <- c(
    "roc", "specificity_vs_sensitivity",
    "prc", "sensitivity_vs_tdp", "recall_vs_tdp",
    "f1_vs_tdp", "tdp_vs_mcc", "sensitivity_vs_f1",
    "sensitivity_vs_mcc"
  )
  mode <- match.arg(mode, modes)
  axis_labels <- c(
    specificity = "Specificity, TN / (TN + FP)",
    sensitivity = "Sensitivity, TP / (TP + FN)",
    recall = "Recall, TP / (TP + FN)",
    tdp = "True discovery proportion, TP / (TP + FP)",
    f1 = "F1, 2TP / (2TP + FP + FN)",
    mcc = paste0(
      "MCC, (TP * TN - FP * FN) / ",
      "sqrt((TP + FP)(TP + FN)(TN + FP)(TN + FN))"
    )
  )
  switch(mode,
    roc =,
    specificity_vs_sensitivity = list(
      x = "specificity", y = "sensitivity",
      xlab = axis_labels[["specificity"]],
      ylab = axis_labels[["sensitivity"]], baseline = "roc"),
    prc =,
    sensitivity_vs_tdp = list(
      x = "sensitivity", y = "tdp",
      xlab = axis_labels[["sensitivity"]],
      ylab = axis_labels[["tdp"]], baseline = "prc"),
    recall_vs_tdp = list(
      x = "sensitivity", y = "tdp",
      xlab = axis_labels[["recall"]],
      ylab = axis_labels[["tdp"]], baseline = "prc"),
    f1_vs_tdp = list(
      x = "f1", y = "tdp", xlab = axis_labels[["f1"]],
      ylab = axis_labels[["tdp"]]),
    tdp_vs_mcc = list(
      x = "tdp", y = "mcc", xlab = axis_labels[["tdp"]],
      ylab = axis_labels[["mcc"]]),
    sensitivity_vs_f1 = list(
      x = "sensitivity", y = "f1",
      xlab = axis_labels[["sensitivity"]],
      ylab = axis_labels[["f1"]]),
    sensitivity_vs_mcc = list(
      x = "sensitivity", y = "mcc",
      xlab = axis_labels[["sensitivity"]],
      ylab = axis_labels[["mcc"]])
  )
}

.roc_curve_styles <- function(objects, use_lty) {
  .assert_flag(use_lty, "use_lty")
  n <- length(objects)
  if (!n) return(list(col = character(), lty = integer()))
  if (n == 1L) {
    colors <- "black"
  } else if (use_lty) {
    colors <- rep(grDevices::rainbow(min(6L, n)), length.out = n)
  } else {
    colors <- grDevices::rainbow(n)
  }
  line_types <- if (use_lty) {
    rep(c(1L, 2L, 3L), each = 6L, length.out = n)
  } else {
    rep(1L, n)
  }
  for (i in seq_along(objects)) {
    color <- objects[[i]]$col
    if (!is.null(color)) {
      if (!is.character(color) || length(color) != 1L || is.na(color) ||
          !nzchar(color) || inherits(try(grDevices::col2rgb(color),
            silent = TRUE), "try-error")) {
        stop("Each curve col override must be one valid R color.",
          call. = FALSE)
      }
      colors[[i]] <- color
    }
    line_type <- objects[[i]]$lty
    if (!is.null(line_type)) {
      if (!is.numeric(line_type) || length(line_type) != 1L ||
          is.na(line_type) || !is.finite(line_type) ||
          line_type != as.integer(line_type) || line_type < 0L ||
          line_type > 6L) {
        stop("Each curve lty override must be one integer from 0 to 6.",
          call. = FALSE)
      }
      line_types[[i]] <- as.integer(line_type)
    }
  }
  list(col = colors, lty = line_types)
}

#' Plot ROC or precision-recall curves
#'
#' Plot one or more network member-recovery benchmarks. ROC mode reports
#' normalized specificity and sensitivity. `max_p` truncates curves at a
#' threshold specified by a one-sided enrichment p-value.
#' Precision-recall mode reports recall and precision as proportions, uses
#' precision 1 before the first positive prediction, and shows the class
#' prevalence as its no-skill baseline.
#'
#' @param tpvsfp Prediction list from [nea_member_recovery_benchmark()], or a
#'   named list of them.
#' @param mode Plot coordinates. Supported values are `"roc"` (an alias for
#'   `"specificity_vs_sensitivity"`), `"prc"` (an alias for
#'   `"sensitivity_vs_tdp"`), `"recall_vs_tdp"`, `"f1_vs_tdp"`,
#'   `"tdp_vs_mcc"`, `"sensitivity_vs_f1"`, and `"sensitivity_vs_mcc"`.
#' @param max_p Maximum one-sided enrichment p-value shown in ROC mode. The
#'   default, 1, retains the complete curve.
#' @param coff_z Deprecated direct cutoff for the NEA z-score. It remains
#'   available when
#'   `max_p` is not supplied; supplying both explicitly is an error.
#' @param cex_main,cex_leg Text sizes for title and legend.
#' @param main Plot title.
#' @param use_lty Use varying line types. For more than six curves, colors
#'   cycle through a six-color palette before line types 1, 2, and 3 cycle.
#' @param print_stats Show node and edge counts. Counts shared by all curves are
#'   printed once below the main title; differing counts appear in the legend.
#' @param sort_by_letter_and_remove Remove a leading letter-and-colon prefix.
#' @details Curves and their colors are ordered alphabetically by their
#'   displayed labels. A prediction element may contain scalar `col` and `lty`
#'   fields to override its automatically assigned style. Differing network
#'   sizes are appended on the same legend
#'   line for labels of at most 24 characters. Longer labels put the sizes on a
#'   second line and use slightly smaller legend text. Common sizes are printed
#'   once below the title, which is useful when curves compare renderers on the
#'   same network. When benchmark marker thresholds are available, a top-left legend
#'   identifies the circle as `p` and the cross as `FDR`.
#'
#'   OR (odds ratio), shown next to each network name in the legend when
#'   `mark_fdr` is not `NULL` and returned as `odds_ratio`, is calculated as
#'   `sensitivity / (1 - specificity)` (Merid et al., 2014), i.e. sensitivity
#'   divided by the false-positive rate at the cutoff selected by `mark_fdr`.
#'   Both sensitivity and the false-positive rate must be non-zero; otherwise
#'   OR is `NA`. With equally sized positive and negative gene sets, a higher
#'   OR at a fixed `mark_fdr` indicates a lower false-positive rate for a given
#'   sensitivity. This is not the cross-product odds ratio of a 2 by 2
#'   contingency table. The returned column contains the same ratio at every
#'   displayed cutoff so that the marked value can be inspected directly.
#' @return Invisibly, an alphabetically named list of data frames containing
#'   the x coordinate, y coordinate, score cutoff, and Merid-style
#'   `odds_ratio` used for every displayed curve. ROC coordinates are
#'   specificity and sensitivity; precision-recall coordinates are recall and
#'   true discovery proportion.
#' @references Merid SK, Goranskaya D, Alexeyenko A (2014).
#'   \doi{10.1186/1471-2105-15-308}.
#' @seealso [nea_member_recovery_benchmark()]
#' @examples
#' net <- igraph::graph_from_edgelist(matrix(c(
#'   "b", "c", "b", "d", "e", "f", "a", "g", "f", "g",
#'   "b", "h", "d", "h", "c", "i", "a", "j", "b", "j",
#'   "e", "j", "h", "k", "c", "l"
#' ), ncol = 2, byrow = TRUE), directed = FALSE)
#' prediction <- nea_member_recovery_benchmark(net,
#'   list(pathway = c("a", "b", "c", "d", "g")),
#'   seed = 7, verbose = FALSE)
#' curves <- roc(list(example_network = prediction), mode = "roc")
#' curves$example_network
#' @export
roc <- function(tpvsfp, mode = "roc", max_p = 1, coff_z = NULL,
    cex_main = 1, cex_leg = 0.75, main = NULL,
    use_lty = FALSE, print_stats = TRUE,
    sort_by_letter_and_remove = FALSE) {
  mode_spec <- .roc_mode_spec(mode)
  required <- c("cross_z", "cutoffs", "ne", "nv", "tp", "fp", "tn", "fn")
  if (!is.list(tpvsfp)) stop("tpvsfp must be a prediction list.", call. = FALSE)
  .assert_flag(use_lty, "use_lty")
  .assert_flag(print_stats, "print_stats")
  .assert_flag(sort_by_letter_and_remove, "sort_by_letter_and_remove")
  objects <- if (all(required %in% names(tpvsfp))) list(`1` = tpvsfp) else tpvsfp
  valid <- vapply(objects, function(x) is.list(x) &&
    all(required %in% names(x)), logical(1))
  if (!length(objects) || any(!valid))
    stop("Every curve must contain the benchmark prediction fields.", call. = FALSE)
  if (!is.numeric(max_p) || length(max_p) != 1L || is.na(max_p) ||
      max_p <= 0 || max_p > 1) {
    stop("max_p must be one number in (0, 1].", call. = FALSE)
  }
  if (!is.null(coff_z) && (!is.numeric(coff_z) || length(coff_z) != 1L ||
      is.na(coff_z))) {
    stop("coff_z must be NULL or one numeric value.", call. = FALSE)
  }
  if (!is.null(coff_z) && !missing(max_p)) {
    stop("Supply only one of max_p and the deprecated coff_z.", call. = FALSE)
  }
  z_cutoff <- if (is.null(coff_z)) {
    stats::qnorm(max_p, lower.tail = FALSE)
  } else {
    warning("coff_z is deprecated; use max_p for one-sided ROC truncation.",
      call. = FALSE)
    coff_z
  }

  object_names <- names(objects)
  if (is.null(object_names) || any(!nzchar(object_names))) {
    object_names <- as.character(seq_along(objects))
  }
  display_names <- if (sort_by_letter_and_remove) {
    sub("^[A-Z]:", "", object_names, ignore.case = TRUE)
  } else object_names
  ordering <- order(tolower(display_names), display_names)
  objects <- objects[ordering]
  object_names <- object_names[ordering]
  display_names <- display_names[ordering]
  styles <- .roc_curve_styles(objects, use_lty)
  colors <- styles$col
  curves <- vector("list", length(objects)); names(curves) <- object_names
  curve_positions <- vector("list", length(objects))
  fdr_odds_ratios <- rep(NA_real_, length(objects))
  for (i in seq_along(objects)) {
    pred <- objects[[i]]
    cutoff <- pred$cutoffs[[1L]]
    tp <- pred$tp[[1L]]
    fp <- pred$fp[[1L]]
    tn <- pred$tn[[1L]]
    fn <- pred$fn[[1L]]
    proportion <- function(numerator, denominator, zero = 0) {
      ifelse(denominator > 0, numerator / denominator, zero)
    }
    mcc_denominator <- sqrt(
      (tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)
    )
    metrics <- list(
      sensitivity = proportion(tp, tp + fn),
      specificity = proportion(tn, tn + fp),
      tdp = proportion(tp, tp + fp, zero = 1),
      f1 = proportion(2 * tp, 2 * tp + fp + fn),
      mcc = proportion(tp * tn - fp * fn, mcc_denominator)
    )
    false_positive_rate <- 1 - metrics$specificity
    odds_ratio <- ifelse(
      metrics$sensitivity > 0 & false_positive_rate > 0,
      metrics$sensitivity / false_positive_rate,
      NA_real_
    )
    if (!is.null(pred$mark_fdr)) {
      fdr_position <- .roc_marker_source_position(pred$cross_z, cutoff)
      if (!is.na(fdr_position)) {
        fdr_odds_ratios[[i]] <- odds_ratio[[fdr_position]]
      }
    }
    pick <- which(cutoff >= z_cutoff)
    curves[[i]] <- data.frame(
      x = metrics[[mode_spec$x]][pick],
      y = metrics[[mode_spec$y]][pick],
      cutoff = cutoff[pick],
      odds_ratio = odds_ratio[pick]
    )
    curve_positions[[i]] <- pick
  }
  xlim <- if (mode_spec$x == "mcc") {
    c(-1, 1)
  } else if (mode_spec$x == "specificity") {
    c(1, 0)
  } else {
    c(0, 1)
  }
  ylim <- if (mode_spec$y == "mcc") c(-1, 1) else c(0, 1)
  legend_names <- .roc_legend_names(display_names, objects, fdr_odds_ratios)
  legend_layout <- .roc_legend_layout(legend_names, objects, cex_leg,
    print_stats)
  graphics::plot(NA, xlim = xlim, ylim = ylim,
    xlab = mode_spec$xlab, ylab = mode_spec$ylab,
    main = main, cex.main = cex_main)
  if (!is.null(legend_layout$common_stats)) {
    graphics::mtext(legend_layout$common_stats, side = 3, line = 0.25,
      cex = 0.95 * cex_leg)
  }
  marker_position <- function(marker, cutoffs, displayed) {
    source_position <- .roc_marker_source_position(marker, cutoffs)
    match(source_position, displayed)
  }
  labels <- legend_layout$labels
  for (i in seq_along(objects)) {
    pred <- objects[[i]]
    graphics::lines(curves[[i]]$x, curves[[i]]$y, col = colors[[i]],
      lty = styles$lty[[i]])
    cross_position <- marker_position(pred$cross_z, pred$cutoffs[[1L]],
      curve_positions[[i]])
    if (!is.na(cross_position)) {
      graphics::points(curves[[i]]$x[[cross_position]],
        curves[[i]]$y[[cross_position]], pch = 4, col = colors[[i]])
    }
    circle_position <- marker_position(pred$circle_z, pred$cutoffs[[1L]],
      curve_positions[[i]])
    if (!is.na(circle_position)) {
      graphics::points(curves[[i]]$x[[circle_position]],
        curves[[i]]$y[[circle_position]], pch = 1, col = colors[[i]])
    }
  }
  if (identical(mode_spec$baseline, "roc")) {
    graphics::abline(1, -1, col = "gray60", lwd = 0.5, lty = 2)
  } else if (identical(mode_spec$baseline, "prc")) {
    prevalence <- vapply(objects, function(pred) {
      positives <- utils::tail(pred$tp[[1L]], 1L)
      negatives <- utils::tail(pred$fp[[1L]], 1L)
      positives / (positives + negatives)
    }, numeric(1))
    for (i in seq_along(prevalence)) {
      graphics::abline(h = prevalence[[i]], col = if (length(objects) == 1L) {
        "gray60"
      } else colors[[i]], lwd = 0.5, lty = 2)
    }
  }
  marker_p <- unique(unlist(lapply(objects, function(pred) {
    if (!is.null(pred$mark_p)) return(pred$mark_p)
    if (!is.null(pred$circle_z) && length(pred$circle_z) == 1L &&
        is.finite(pred$circle_z)) {
      return(stats::pnorm(pred$circle_z, lower.tail = FALSE))
    }
    NULL
  }), use.names = FALSE))
  marker_fdr <- unique(unlist(lapply(objects, function(pred) pred$mark_fdr),
    use.names = FALSE))
  marker_labels <- c(
    if (length(marker_p)) paste0("p=", format(marker_p, trim = TRUE)),
    if (length(marker_fdr)) paste0("FDR=", format(marker_fdr, trim = TRUE))
  )
  marker_pch <- c(rep(1, length(marker_p)), rep(4, length(marker_fdr)))
  if (length(marker_labels)) {
    graphics::legend("topleft", legend = marker_labels, pch = marker_pch,
      bty = "o", cex = cex_leg)
  }
  graphics::legend("bottomright", legend = labels, col = colors, bty = "n",
    lty = styles$lty,
    cex = legend_layout$cex)
  invisible(curves)
}

Try the NEArender package in your browser

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

NEArender documentation built on Nov. 28, 2026, 5:10 p.m.