R/render-nea.R

Defines functions nea.render calculate_nea_statistics .legacy_nea_q .format_connected_members .resolve_network_name

Documented in nea.render

.resolve_network_name <- function(net, network_name = NULL) {
  if (is.null(network_name)) {
    network_name <- if (igraph::is_igraph(net)) {
      igraph::graph_attr(net, "name")
    } else if (is.list(net)) {
      net[["name"]]
    }
  }
  if (is.null(network_name)) {
    network_name <- attr(net, "network_name", exact = TRUE)
  }
  if (is.null(network_name)) {
    network_name <- attr(net, "name", exact = TRUE)
  }
  if (is.null(network_name)) return(NA_character_)
  if (!is.character(network_name) || length(network_name) != 1L ||
      (!is.na(network_name) && !nzchar(network_name))) {
    stop("network_name must be NULL or one non-empty string.", call. = FALSE)
  }
  network_name
}


.format_connected_members <- function(gene_sets, node_names, connectivity,
    n_cores = 1L) {
  node_index <- stats::setNames(seq_along(node_names), node_names)
  rows <- .parallel_lapply(seq_along(gene_sets), function(i) {
    output <- rep("", ncol(connectivity))
    genes <- gene_sets[[i]]
    positions <- unname(node_index[genes])
    mapped <- !is.na(positions)
    genes <- genes[mapped]
    positions <- positions[mapped]
    if (!length(positions)) return(output)
    hits <- Matrix::summary(connectivity[positions, , drop = FALSE])
    if (!nrow(hits)) return(output)
    rows_by_column <- split(hits$i, hits$j)
    columns <- as.integer(names(rows_by_column))
    output[columns] <- vapply(rows_by_column, function(rows) {
      paste(genes[unique(rows)], collapse = ", ")
    }, character(1))
    output
  }, n_cores = n_cores)
  matrix(unlist(rows, use.names = FALSE), nrow = length(gene_sets),
    byrow = TRUE,
    dimnames = list(names(gene_sets), colnames(connectivity)))
}


.legacy_nea_q <- function(p, z) {
  q <- matrix(stats::p.adjust(as.vector(p), method = "BH"),
    nrow = nrow(p), ncol = ncol(p), dimnames = dimnames(p))
  q[!is.na(z) & z < 0] <- 1
  q
}


# Calculate legacy analytic NEA statistics with sparse matrix operations.
calculate_nea_statistics <- function(ags, fgs, net, na_replace = 0,
    network_name = NULL, members = FALSE, n_cores = 1L) {
  .assert_flag(members, "members")
  n_cores <- .validate_n_cores(n_cores)
  network_name <- .resolve_network_name(net, network_name)
  indexed <- if (inherits(net, "nearender_indexed_network")) {
    net
  } else {
    index_sparse_network(net)
  }

  ags_membership <- make_sparse_membership(ags, indexed$node_id)
  fgs_membership <- make_sparse_membership(fgs, indexed$node_id)

  A <- indexed$adjacency
  G <- ags_membership$matrix
  F <- fgs_membership$matrix

  AG <- A %*% G
  n_actual <- as.matrix(Matrix::crossprod(F, AG))
  n_actual[n_actual == 0] <- na_replace

  cumulative_degree_ags <- Matrix::colSums(AG)
  degree <- Matrix::rowSums(A)
  cumulative_degree_fgs <- as.numeric(Matrix::crossprod(F, degree))

  names(cumulative_degree_ags) <- colnames(G)
  names(cumulative_degree_fgs) <- colnames(F)

  n_expected <- tcrossprod(
    cumulative_degree_fgs,
    cumulative_degree_ags
  ) / (2 * indexed$n_edges)
  dimnames(n_expected) <- list(colnames(F), colnames(G))

  # Retain the legacy formula until its edge-count denominator and boundary
  # behavior have been reviewed as a separate scientific decision.
  chi <- (
    ((n_actual - n_expected)^2) / n_expected +
      (((indexed$n_edges - n_actual) -
        (indexed$n_edges - n_expected))^2) /
        (indexed$n_edges - n_expected)
  )

  p <- stats::pchisq(chi, df = 1, lower.tail = FALSE)
  z <- stats::qnorm(p / 2, lower.tail = FALSE)
  depleted <- sign(n_actual - n_expected) < 0
  z[depleted] <- -abs(z[depleted])
  z[is.nan(z)] <- NA_real_

  # Preserve the finite-score convention used by legacy nea.render(): when a
  # p-value underflows to zero, replace the resulting infinite z-score by one
  # unit beyond the corresponding finite extreme in this result matrix.
  finite_z <- is.finite(z)
  if (any(finite_z)) {
    lower_z <- min(z[finite_z], na.rm = TRUE) - 1
    upper_z <- max(z[finite_z], na.rm = TRUE) + 1
    z[is.infinite(z) & z < 0] <- lower_z
    z[is.infinite(z) & z > 0] <- upper_z
  }

  # Preserve the legacy contract: adjust the reported two-sided p-values
  # together, then suppress depleted discoveries in the enrichment q matrix.
  q <- .legacy_nea_q(p, z)

  result <- list(
    cumulativeDegrees = list(
      AGS = cumulative_degree_ags,
      FGS = cumulative_degree_fgs
    ),
    n.actual = n_actual,
    n.expected = n_expected,
    chi = chi,
    z = z,
    p = p,
    q = q,
    diagnostics = list(
      ags_original_sizes = ags_membership$original_sizes,
      ags_network_sizes = ags_membership$mapped_sizes,
      fgs_original_sizes = fgs_membership$original_sizes,
      fgs_network_sizes = fgs_membership$mapped_sizes
    ),
    network = list(
      name = network_name,
      n_nodes = length(indexed$node_names),
      n_edges = indexed$n_edges
    )
  )
  if (members) {
    AF <- A %*% F
    result$members.ags <- .format_connected_members(
      ags, indexed$node_names, AF, n_cores)
    result$members.fgs <- .format_connected_members(
      fgs, indexed$node_names, AG, n_cores)
  }
  result
}


#' Render altered gene sets as pathway-level network enrichment features
#'
#' Given altered gene sets (AGSs), functional gene sets (FGSs), and a global
#' network, evaluate enrichment from the number of network edges connecting
#' each AGS--FGS pair. Expected counts are calibrated from the degree sums of
#' all member nodes under the null model. Edges confined within only the AGS or
#' only the FGS do not contribute. Returned matrices have FGSs in rows and AGSs
#' in columns.
#' Observed and expected edge counts and two-sided chi-square p-values accompany
#' the signed z-score used for downstream modelling. Q-values follow the
#' enrichment convention: BH correction is applied to all two-sided p-values,
#' after which depleted scores are assigned q-value 1.
#'
#' @param ags Named list of altered gene sets.
#' @param fgs Named list of functional gene sets.
#' @param net Undirected igraph network, or a legacy network with a named
#'   adjacency list in `links` and an edge count in `Ntotal`.
#' @param network_name Optional non-empty network name recorded in the result.
#'   When omitted, a name stored on `net` is used, if available.
#' @param case_sensitive Use case-sensitive identifier matching. By default,
#'   identifiers in AGS, FGS, and NET are matched case-insensitively.
#' @param na_replace Value used for zero observed link counts.
#' @param members Whether to return the potentially large `members.ags` and
#'   `members.fgs` matrices of connected identifiers.
#' @param n_cores Positive integer number of worker processes used only to
#'   format member matrices when `members = TRUE`. Sparse matrix calculations
#'   are not distributed across workers.
#' @param verbose Report progress with [message()].
#' @return A `nearender_result`. `scores$z` is the signed standardized
#'   deviation of observed AGS--FGS edge counts from the degree-based null.
#'   `statistics` contains AGS and FGS cumulative degrees, observed
#'   (`n.actual`) and expected (`n.expected`) edge counts, chi-square
#'   statistics, two-sided p-values, and BH-adjusted enrichment q-values
#'   (depleted cells are set to 1). When `members = TRUE`, it also contains
#'   connected AGS and FGS member matrices. The master `z` matrix occurs
#'   identically in both `scores` and `statistics`; all other matrices occur
#'   only in `statistics`.
#' @references Alexeyenko A et al. (2012). \doi{10.1186/1471-2105-13-226}.
#'   Jeggari A and Alexeyenko A (2017). \doi{10.1186/s12859-017-1534-y}.
#' @seealso [ora.render()], [ear()], [rwr.render()], [pagerank.render()],
#'   [texture.render()], [spectral.render()], [gsva.render()],
#'   [samples2ags()], [mutations2ags()], [set.heat()]
#' @examples
#' data("NEArender.test")
#' ags <- NEArender.test$AGS$CCLE[1:2]
#' fgs <- NEArender.test$FGS$Hallmarks[1:3]
#' net <- NEArender.test$NET$STRING.300K
#' nea <- nea.render(ags, fgs, net, verbose = FALSE)
#' nea$scores$z
#' nea$statistics$q
#' @export
nea.render <- function(
    ags,
    fgs,
    net,
    case_sensitive = FALSE,
    na_replace = 0,
    verbose = TRUE,
    network_name = NULL,
    members = FALSE,
    n_cores = 1L) {
  .assert_flag(case_sensitive, "case_sensitive")
  .assert_flag(members, "members")
  n_cores <- .validate_n_cores(n_cores)
  network_name <- .resolve_network_name(net, network_name)
  .assert_flag(verbose, "verbose")
  if (length(na_replace) != 1L ||
      (!is.na(na_replace) && !is.numeric(na_replace))) {
    stop("na_replace must be one numeric value or NA.", call. = FALSE)
  }
  ags <- .normalize_gene_sets(ags, "ags", case_sensitive)
  fgs <- .normalize_gene_sets(fgs, "fgs", case_sensitive)
  net <- .normalize_network(net, case_sensitive)
  .assert_compatible_identifiers(ags = ags, fgs = fgs, net = net)

  if (verbose) {
    message("Calculating network enrichment scores using sparse matrix format.")
  }
  result <- calculate_nea_statistics(ags, fgs, net, na_replace,
    network_name = network_name, members = members, n_cores = n_cores)
  statistic_names <- c(
    "cumulativeDegrees", "n.actual", "n.expected", "chi", "p", "q")
  if (members) {
    statistic_names <- c(statistic_names, "members.ags", "members.fgs")
  }
  statistics <- result[statistic_names]
  .new_nearender_result(
    scores = list(z = result$z),
    score_info = .new_score_info(
      score_id = "z",
      renderer = "nea",
      metric = "signed_z"
    ),
    statistics = statistics,
    inputs = list(
      ags_names = names(ags),
      fgs_names = names(fgs),
      ags_sizes = lengths(ags),
      fgs_sizes = lengths(fgs),
      network = result$network
    ),
    diagnostics = result$diagnostics,
    parameters = list(
      case_sensitive = case_sensitive,
      na_replace = na_replace,
      members = members,
      n_cores = n_cores
    )
  )
}

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.