R/ear.R

Defines functions ear

Documented in ear

#' Enrichment analysis on a rich, functionally biased gene/protein universe
#'
#' EAR compares the enrichment score for each observed altered gene set (AGS)
#' with scores from `n_perm` equally sized random sets sampled without
#' replacement from the same eligible gene universe. The finite-sample
#' corrected empirical probability is `(1 + n_exceed) / (n_perm + 1)`, where
#' `n_exceed` is the number of random scores greater than or equal to the
#' observed score.
#'
#' @param universe Character vector of genes on which the observed sets are
#'   based and that are eligible for random controls.
#' @param n_perm Positive integer number of controls per AGS.
#' @param ags Named list of altered gene sets.
#' @param fgs Named list of functional gene sets.
#' @param net Network used for NEA. It is required when `method = "nea"`.
#' @param method Renderer used for calibration: `"nea"` or `"ora"`.
#' @param renderer_args Named list of additional arguments forwarded to the
#'   selected renderer. EAR-managed inputs and options cannot be overridden.
#' @param seed Optional integer seed for reproducible control sampling.
#' @param case_sensitive Use case-sensitive identifier matching.
#' @param na_replace Value used for zero observed NEA link counts.
#' @param n_cores Positive integer passed to the selected renderer. ORA
#'   distributes functional-set rows. NEA accepts the value for consistency,
#'   although EAR does not request member matrices and its sparse calculations
#'   remain single-process matrix operations.
#' @param verbose Report progress with [message()].
#' @param network_nodes_only For NEA, whether to restrict the random-control
#'   universe to genes present as network nodes. The default, `FALSE`, retains
#'   every gene in the submitted `universe`; genes absent from the network can
#'   occur in AGSs and controls but contribute no network edges. When `TRUE`,
#'   the universe is intersected with the network nodes and every AGS member
#'   must occur in that restricted universe.
#' @details Calibration uses the upper tail: an empirical p-value counts
#'   random scores greater than or equal to the observed score. Q-values are
#'   adjusted separately within each AGS column. AGSs of different sizes use
#'   separate random reference banks. For NEA, the submitted gene universe is
#'   used by default even when some genes are absent from the network. Set
#'   `network_nodes_only = TRUE` to reproduce network-restricted sampling.
#' @return A `nearender_result` whose master score is the upper-tail empirical
#'   probability matrix `p.ear`, available identically in `scores$p.ear` and
#'   `statistics$p.ear`. `statistics` also contains the ordinary renderer
#'   probabilities as `p.trivial`, their adjusted values as `q.trivial`, the
#'   empirical adjusted values as `q.ear`, and every other ordinary renderer
#'   statistic with a `.trivial` suffix. EAR settings are recorded in
#'   `parameters`; reference-bank information is recorded in `diagnostics`.
#' @seealso [nea.render()], [ora.render()], [samples2ags()]
#' @examples
#' data("NEArender.test")
#' ags <- NEArender.test$AGS$CCLE[1]
#' fgs <- NEArender.test$FGS$Hallmarks[1:2]
#' universe <- unique(c(unlist(ags), unlist(fgs), paste0("control", 1:150)))
#' calibrated <- ear(universe, n_perm = 9, ags = ags, fgs = fgs,
#'   method = "ora", seed = 1, verbose = FALSE)
#' calibrated$scores$p.ear
#' calibrated$statistics$p.trivial
#' @export
ear <- function(
    universe,
    n_perm = 100L,
    ags,
    fgs,
    net = NULL,
    method = c("nea", "ora"),
    renderer_args = list(),
    seed = NULL,
    case_sensitive = FALSE,
    na_replace = 0,
    n_cores = 1L,
    verbose = TRUE,
    network_nodes_only = FALSE) {
  method <- match.arg(method)
  .assert_flag(case_sensitive, "case_sensitive")
  .assert_flag(verbose, "verbose")
  .assert_flag(network_nodes_only, "network_nodes_only")
  n_cores <- .validate_n_cores(n_cores)
  renderer_function <- switch(method,
    nea = nea.render,
    ora = ora.render)
  managed_args <- if (method == "nea") {
    c("ags", "fgs", "net", "case_sensitive", "na_replace", "n_cores",
      "verbose")
  } else {
    c("ags", "fgs", "universe", "case_sensitive", "n_cores", "verbose")
  }
  .validate_renderer_args(renderer_args, renderer_function, method,
    managed = managed_args, managed_label = "EAR-managed arguments")
  if (length(n_perm) != 1L || is.na(n_perm) || !is.numeric(n_perm) ||
      !is.finite(n_perm) || n_perm < 1 || n_perm != as.integer(n_perm)) {
    stop("n_perm must be one positive integer.", call. = FALSE)
  }
  n_perm <- as.integer(n_perm)
  if (!is.null(seed)) {
    if (length(seed) != 1L || is.na(seed) || !is.numeric(seed) ||
        !is.finite(seed) || seed != as.integer(seed)) {
      stop("seed must be NULL or one integer.", call. = FALSE)
    }
    set.seed(as.integer(seed))
  }

  ags <- .normalize_gene_sets(ags, "ags", case_sensitive)
  fgs <- .normalize_gene_sets(fgs, "fgs", case_sensitive)
  .assert_compatible_identifiers(ags = ags, fgs = fgs)
  universe <- unique(.canonical_ids(universe, case_sensitive))
  universe <- universe[!is.na(universe) & nzchar(universe)]
  if (!length(universe)) {
    stop("universe must contain at least one identifier.", call. = FALSE)
  }

  ags_members <- unique(unlist(ags, use.names = FALSE))
  outside <- setdiff(ags_members, universe)
  if (length(outside)) {
    stop(
      "Every AGS member must occur in the submitted EAR universe; missing: ",
      paste(utils::head(outside, 5L), collapse = ", "),
      if (length(outside) > 5L) ", ..." else "",
      ". Recreate or import AGS and universe with the same identifier ",
      "namespace and case policy. Inspect normalization_info(ags); use ",
      "load_id_mappings() when identifier conversion is required.",
      call. = FALSE
    )
  }

  if (method == "nea") {
    if (is.null(net)) {
      stop("net is required for NEA calibration.", call. = FALSE)
    }
    net <- .normalize_network(net, case_sensitive)
    .assert_compatible_identifiers(ags = ags, fgs = fgs, net = net)
    if (network_nodes_only) {
      eligible_nodes <- if (igraph::is_igraph(net)) {
        igraph::vertex_attr(net, "name")
      } else if (inherits(net, "nearender_indexed_network")) {
        net$node_names
      } else {
        unique(c(names(net$links), unlist(net$links, use.names = FALSE)))
      }
      universe <- intersect(universe, eligible_nodes)
      outside_network <- setdiff(ags_members, universe)
      if (length(outside_network)) {
        stop(
          "network_nodes_only = TRUE requires every AGS member to occur in ",
          "the network-restricted EAR universe; missing: ",
          paste(utils::head(outside_network, 5L), collapse = ", "),
          if (length(outside_network) > 5L) ", ..." else "",
          ". Set network_nodes_only = FALSE to retain submitted-universe ",
          "genes that are absent from the network.",
          call. = FALSE
        )
      }
    }
  }
  largest_ags <- max(lengths(ags), 0L)
  if (length(universe) < 2L * largest_ags) {
    stop(
      "The eligible EAR universe must contain at least twice as many genes ",
      "as the largest AGS.",
      call. = FALSE
    )
  }

  reference_sizes <- sort(unique(lengths(ags)))
  control_sets <- vector("list", length(reference_sizes) * n_perm)
  if (length(reference_sizes) > 1L) {
    warning(
      "AGS sizes vary, so EAR must build a separate reference bank for each ",
      "size. Fixed Ntop preparation is faster and is expected to produce ",
      "similar results to method = \"significant\".",
      call. = FALSE
    )
  }
  control_size <- integer(length(control_sets))
  position <- 0L
  for (ags_size in reference_sizes) {
    for (permutation in seq_len(n_perm)) {
      position <- position + 1L
      control_sets[[position]] <- sort(
        sample(universe, ags_size, replace = FALSE)
      )
      control_size[[position]] <- ags_size
    }
  }
  names(control_sets) <- sprintf(".ear_control_%08d", seq_along(control_sets))

  render <- function(render_ags) {
    render_args <- if (method == "nea") {
      list(
        ags = render_ags,
        fgs = fgs,
        net = net,
        case_sensitive = case_sensitive,
        na_replace = na_replace,
        n_cores = n_cores,
        verbose = FALSE
      )
    } else {
      list(
        ags = render_ags,
        fgs = fgs,
        universe = universe,
        case_sensitive = case_sensitive,
        n_cores = n_cores,
        verbose = FALSE
      )
    }
    do.call(renderer_function, c(render_args, renderer_args))
  }

  if (verbose) {
    message(
      "Calibrating ", length(ags), " AGS",
      if (length(ags) == 1L) "" else "s",
      " with ", n_perm, " controls each."
    )
  }
  score_id <- if (method == "nea") "z" else "odds_ratio"
  calibration_sets <- c(ags, control_sets)
  names(calibration_sets)[seq_along(ags)] <- sprintf(
    ".ear_actual_%08d", seq_along(ags)
  )
  calibration_score <- render(calibration_sets)$scores[[score_id]]
  observed_score <- calibration_score[, seq_along(ags), drop = FALSE]
  dimnames(observed_score) <- list(rownames(calibration_score), names(ags))
  control_score <- calibration_score[
    , length(ags) + seq_along(control_sets), drop = FALSE
  ]
  observed <- render(ags)

  p_ear <- matrix(
    NA_real_, nrow(observed_score), ncol(observed_score),
    dimnames = dimnames(observed_score)
  )
  for (sample_index in seq_along(ags)) {
    sample_controls <- control_score[
      , control_size == length(ags[[sample_index]]), drop = FALSE
    ]
    p_ear[, sample_index] <- (
      1 + rowSums(sample_controls >= observed_score[, sample_index])
    ) / (n_perm + 1)
  }
  q_ear <- apply(p_ear, 2L, stats::p.adjust, method = "BH")
  if (is.null(dim(q_ear))) {
    q_ear <- matrix(
      q_ear, nrow = nrow(p_ear), ncol = ncol(p_ear),
      dimnames = dimnames(p_ear)
    )
  } else {
    dimnames(q_ear) <- dimnames(p_ear)
  }

  trivial_statistics <- observed$statistics
  names(trivial_statistics) <- paste0(names(trivial_statistics), ".trivial")
  primary_statistics <- list(
    p.trivial = trivial_statistics$p.trivial,
    q.ear = q_ear,
    q.trivial = trivial_statistics$q.trivial
  )
  remaining_statistics <- trivial_statistics[setdiff(
    names(trivial_statistics), c("p.trivial", "q.trivial")
  )]

  inputs <- observed$inputs
  inputs$universe_size <- length(universe)
  diagnostics <- observed$diagnostics
  diagnostics$calibrated_score_id <- score_id
  diagnostics$reference_sizes <- reference_sizes
  diagnostics$n_reference_sets <- length(control_sets)

  .new_nearender_result(
    scores = list(p.ear = p_ear),
    score_info = .new_score_info(
      score_id = "p.ear",
      renderer = "ear",
      metric = "upper_tail_empirical_probability",
      input_variant = method,
      mode = "empirical_calibration",
      parameters = paste0("calibrated_score=", score_id)
    ),
    statistics = c(primary_statistics, remaining_statistics),
    inputs = inputs,
    diagnostics = diagnostics,
    parameters = list(
      method = method,
      calibrated_score_id = score_id,
      renderer_parameters = observed$parameters,
      renderer_args = renderer_args,
      tail = "greater",
      strict = FALSE,
      finite_sample_correction = TRUE,
      n_perm = n_perm,
      n_cores = n_cores,
      network_nodes_only = network_nodes_only,
      seed = seed
    )
  )
}

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.