R/render-spectral.R

Defines functions spectral.render spectral_eigenpairs .spectral_score .spectral_eigen .spectral_pathway_graph .spectral_graph

Documented in spectral_eigenpairs spectral.render

.spectral_features <- c("rlq", "rlw", "dir", "diw")

.spectral_graph <- function(nodes, net, weighted) {
  if (weighted && is.null(net$weights)) {
    stop("Weighted spectral features require net$weights.", call. = FALSE)
  }
  adjacency <- matrix(0, length(nodes), length(nodes),
    dimnames = list(nodes, nodes))
  if (weighted) {
    for (node in nodes) {
      weights <- net$weights[[node]]
      if (length(weights)) {
        neighbors <- intersect(names(weights), setdiff(nodes, node))
        adjacency[node, neighbors] <- abs(weights[neighbors])
      }
    }
  } else {
    for (node in nodes) {
      neighbors <- intersect(net$links[[node]], setdiff(nodes, node))
      adjacency[node, neighbors] <- 1
    }
  }
  adjacency <- pmax(adjacency, t(adjacency))
  degree <- rowSums(adjacency)
  keep <- degree > 0
  adjacency <- adjacency[keep, keep, drop = FALSE]
  degree <- degree[keep]
  degree_matrix <- diag(degree, nrow = length(degree))
  dimnames(degree_matrix) <- list(names(degree), names(degree))
  list(L = degree_matrix - adjacency, T = degree_matrix)
}

.spectral_pathway_graph <- function(members, available_nodes, net, min_ngenes,
    scope, weighted) {
  pathway <- intersect(members, intersect(available_nodes, names(net$links)))
  if (length(pathway) < min_ngenes) return(NULL)
  nodes <- pathway
  if (scope == "boundary-expanded") {
    boundary <- unique(unlist(net$links[pathway], use.names = FALSE))
    nodes <- unique(c(pathway, intersect(boundary, available_nodes)))
  }
  graph <- .spectral_graph(nodes, net, weighted = weighted)
  if (!nrow(graph$L)) NULL else graph
}

.spectral_eigen <- function(graph) {
  inverse_sqrt_degree <- 1 / sqrt(diag(graph$T))
  normalized_laplacian <- graph$L *
    outer(inverse_sqrt_degree, inverse_sqrt_degree)
  decomposition <- eigen(normalized_laplacian, symmetric = TRUE)
  ordering <- order(decomposition$values)
  values <- decomposition$values[ordering]
  zero_tolerance <- 100 * .Machine$double.eps * max(1, abs(values))
  values[abs(values) <= zero_tolerance] <- 0
  vectors <- sweep(decomposition$vectors[, ordering, drop = FALSE], 1L,
    sqrt(diag(graph$T)), "/")
  rownames(vectors) <- rownames(graph$L)
  structure(list(values = values, vectors = vectors), class = "eigen")
}

.spectral_score <- function(values, graph, quotient) {
  numerator <- as.numeric(crossprod(values, graph$L %*% values))
  if (!quotient) return(numerator)
  denominator <- as.numeric(crossprod(values, graph$T %*% values))
  if (denominator == 0) NA_real_ else numerator / denominator
}

#' Calculate pathway Laplacian eigenpairs
#'
#' Calculate the graph spectrum of each pathway without requiring a function
#' over its nodes. The returned generalized eigenpairs are the structural
#' counterparts of the Rayleigh quotients calculated by [spectral.render()].
#'
#' @param fgs Named list of functional gene sets whose subnetworks are extracted
#'   from the global network `net`.
#' @param net Undirected igraph network, or a legacy network with a named
#'   adjacency list in `links`. When `use_edge_weights = TRUE`, the igraph
#'   `weight` edge attribute or legacy named edge-weight vectors in `weights`
#'   are required.
#' @param min_ngenes Minimum genes per set that must map to network nodes before
#'   scope expansion.
#' @param use_edge_weights Use the magnitudes of stored network edge weights.
#'   The default, `FALSE`, uses binary topology.
#' @param scope Graph scope: `"within-pathway"` uses within-set edges;
#'   `"boundary-expanded"` also includes all one-hop network neighbors of
#'   mapped pathway genes.
#' @param case_sensitive Use case-sensitive identifier matching.
#' @param n_cores Positive integer number of worker processes. Independent
#'   pathways are distributed across workers when `n_cores > 1`.
#' @param verbose Report progress with [message()].
#' @details For adjacency matrix `A`, degree matrix `D`, and combinatorial
#'   Laplacian `L = D - A`, this function solves the generalized eigenproblem
#'   `L v = lambda D v`. This is equivalent to diagonalizing the symmetric
#'   normalized Laplacian `D^(-1/2) L D^(-1/2)` and transforming its
#'   eigenvectors back to the original node coordinates. Returned eigenvectors
#'   are therefore `D`-orthonormal, so their Rayleigh quotients under the
#'   corresponding `rlq` or `rlw` definition equal their eigenvalues.
#'
#'   Isolated nodes, including nodes incident only to zero-weight edges in a
#'   weighted analysis, are removed before decomposition. Negative stored
#'   weights are interpreted by magnitude, as in [spectral.render()]. Because
#'   no sample matrix limits node availability, `"boundary-expanded"` includes
#'   every one-hop neighbor represented in `net`. Eigenvector signs and the
#'   basis chosen within a repeated-eigenvalue eigenspace are not unique.
#'
#'   `n_cores` controls only the distribution of pathways among R worker
#'   processes. Each worker calls [base::eigen()], and the BLAS/LAPACK library
#'   linked to R may independently use all available CPU cores. Actual CPU use
#'   can therefore exceed `n_cores`. Different BLAS/LAPACK implementations and
#'   versions can also produce small numerical differences, especially for
#'   eigenvectors in repeated or nearly repeated eigenspaces.
#' @return A named list in the same order as `fgs`. Each pathway with at least
#'   `min_ngenes` mapped genes and one usable edge contains an object of class
#'   `"eigen"` with numeric `values` and `vectors`. Eigenvalues are in ascending
#'   order, rows of `vectors` are named by retained network nodes, and column
#'   `i` is the eigenvector for `values[i]`. An ineligible or edge-free pathway
#'   has a `NULL` entry.
#' @references Chung FRK (1997). *Spectral Graph Theory*. CBMS Regional
#'   Conference Series in Mathematics 92, American Mathematical Society.
#'   ISBN 978-0-8218-0315-8.
#' @seealso [spectral.render()]
#' @examples
#' fgs <- list(pathway = c("A", "B"))
#' net <- list(
#'   links = list(A = "B", B = c("A", "C"), C = "B"),
#'   Ntotal = 2)
#' pairs <- spectral_eigenpairs(fgs, net, min_ngenes = 2,
#'   scope = "boundary-expanded", verbose = FALSE)
#' pairs$pathway$values
#' rownames(pairs$pathway$vectors)
#' @export
spectral_eigenpairs <- function(fgs, net, min_ngenes = 5,
    use_edge_weights = FALSE,
    scope = c("within-pathway", "boundary-expanded"),
    case_sensitive = FALSE, n_cores = 1L, verbose = TRUE) {
  if (!missing(scope) && length(scope) != 1L) {
    stop("scope must select exactly one graph scope.", call. = FALSE)
  }
  scope <- match.arg(scope)
  if (length(min_ngenes) != 1L || is.na(min_ngenes) || min_ngenes < 1 ||
      min_ngenes != as.integer(min_ngenes)) {
    stop("min_ngenes must be one positive integer.", call. = FALSE)
  }
  .assert_flag(use_edge_weights, "use_edge_weights")
  .assert_flag(case_sensitive, "case_sensitive")
  .assert_flag(verbose, "verbose")
  n_cores <- .validate_n_cores(n_cores)
  fgs <- .normalize_gene_sets(fgs, "fgs", case_sensitive)
  net <- as_nearender_network(
    .normalize_network(net, case_sensitive), case_sensitive)
  .assert_compatible_identifiers(fgs = fgs, net = net)
  if (use_edge_weights && is.null(net$weights)) {
    stop("use_edge_weights = TRUE requires net$weights.", call. = FALSE)
  }
  if (verbose) message("Calculating ", scope, " eigenpairs.")
  result <- .parallel_lapply(seq_along(fgs), function(set_index) {
    graph <- .spectral_pathway_graph(
      members = fgs[[set_index]], available_nodes = names(net$links),
      net = net, min_ngenes = min_ngenes, scope = scope,
      weighted = use_edge_weights)
    if (is.null(graph)) NULL else .spectral_eigen(graph)
  }, n_cores = n_cores)
  stats::setNames(result, names(fgs))
}

#' Render a sample matrix as pathway-level spectral features
#'
#' Calculate pathway-level Dirichlet sums and Rayleigh quotients from a sample
#' matrix. Dirichlet sums quantify contrasts between adjacent node states;
#' Rayleigh quotients additionally normalize those contrasts by individual
#' node states.
#'
#' @param fgs Named list of functional gene sets whose subnetworks are extracted
#'   from the global network `net`.
#' @param mtr Numeric gene-by-sample matrix. Values become sample-specific node
#'   attributes.
#' @param net Undirected igraph network, or a legacy network with a named
#'   adjacency list in `links`. Weighted features use the igraph `weight`
#'   edge attribute or legacy named edge-weight vectors in `weights`.
#' @param min_ngenes Minimum mapped genes per set before scope expansion.
#' @param features Unique spectral features. `rlq` and `dir` use binary
#'   topology; `rlw` and `diw` use stored network edge weights. The default
#'   requests all four implemented features.
#' @param scope Graph scope: `"within-pathway"` uses within-set edges;
#'   `"boundary-expanded"` also uses boundary edges to one-hop neighbors.
#' @param case_sensitive Use case-sensitive identifier matching.
#' @param n_cores Positive integer number of worker processes. Independent
#'   spectral features are distributed across workers when `n_cores > 1`.
#' @param verbose Report progress with [message()].
#' @details The implemented spectral features are Dirichlet sums (`dir` and
#'   `diw` for edge-unweighted and weighted versions, respectively) and
#'   Rayleigh quotients (`rlq` and `rlw` for edge-unweighted and weighted
#'   versions, respectively). The former summarize contrasts between states of
#'   adjacent network nodes within a pathway, whereas the latter also normalize
#'   the contrasts by individual node states. A separate pathway-by-sample
#'   matrix is produced for each requested feature. Running
#'   `scope = "boundary-expanded"` may take about ten times as long as
#'   `"within-pathway"`; the exact increase depends on the network and pathway
#'   sizes. Submit alternative scope analyses as separate calls so that each
#'   result has an unambiguous graph scope.
#' @return A `nearender_result`. `scores` contains one
#'   pathway-by-sample matrix for every requested feature, in request order.
#'   `statistics` contains the same master score matrices under the same names.
#'   `rlq` and `rlw` are Rayleigh quotients; `dir` and `diw` are
#'   Dirichlet sums. Rows with fewer than `min_ngenes` mapped genes, or with no
#'   usable scoped edges, contain `NA`. `diagnostics$fgs_network_sizes`
#'   reports mapped pathway sizes; no p- or q-values are calculated.
#' @references Chung FRK (1997). *Spectral Graph Theory*. CBMS Regional
#'   Conference Series in Mathematics 92, American Mathematical Society.
#'   ISBN 978-0-8218-0315-8.
#' @seealso [spectral_eigenpairs()], [texture.render()], [gsva.render()]
#' @examples
#' profiles <- matrix(c(1, 3, 5, 2, 2, 2), nrow = 3,
#'   dimnames = list(c("A", "B", "C"), c("sample_1", "sample_2")))
#' fgs <- list(pathway = c("A", "B"))
#' net <- list(
#'   links = list(A = "B", B = c("A", "C"), C = "B"),
#'   weights = list(A = c(B = 2), B = c(A = 2, C = 1), C = c(B = 1)),
#'   Ntotal = 2)
#' spectral <- spectral.render(fgs, profiles, net, min_ngenes = 2,
#'   scope = "within-pathway", verbose = FALSE)
#' spectral$scores$rlq
#' spectral$scores$rlw
#' @export
spectral.render <- function(fgs, mtr, net, min_ngenes = 5,
    features = c("rlq", "rlw", "dir", "diw"),
    scope = c("within-pathway", "boundary-expanded"),
    case_sensitive = FALSE, n_cores = 1L, verbose = TRUE) {
  if (!missing(scope) && length(scope) != 1L) {
    stop("scope must select exactly one graph scope.", call. = FALSE)
  }
  scope <- match.arg(scope)
  if (length(min_ngenes) != 1L || is.na(min_ngenes) || min_ngenes < 1 ||
      min_ngenes != as.integer(min_ngenes)) {
    stop("min_ngenes must be one positive integer.", call. = FALSE)
  }
  if (!is.character(features) || !length(features) || anyNA(features) ||
      anyDuplicated(features) ||
      length(setdiff(features, .spectral_features))) {
    stop("features must contain unique implemented spectral features.",
      call. = FALSE)
  }
  .assert_flag(case_sensitive, "case_sensitive"); .assert_flag(verbose, "verbose")
  n_cores <- .validate_n_cores(n_cores)
  fgs <- .normalize_gene_sets(fgs, "fgs", case_sensitive)
  weighted_features <- grepl("w$", features)
  net <- as_nearender_network(
    .normalize_network(net, case_sensitive), case_sensitive)
  .assert_compatible_identifiers(fgs = fgs, net = net)
  mtr <- .select_sample_matrix(mtr, NULL, NULL)
  genes <- .canonical_ids(rownames(mtr), case_sensitive)
  if (anyDuplicated(genes)) stop("Matrix gene names collide under the identifier case policy.", call. = FALSE)
  rownames(mtr) <- genes
  if (anyNA(mtr) || any(!is.finite(mtr))) stop("mtr must contain only finite values.", call. = FALSE)
  if (any(weighted_features) && is.null(net$weights))
    stop("Weighted spectral features require net$weights.", call. = FALSE)
  if (verbose) message("Calculating ", scope, " spectral scores.")
  scores <- stats::setNames(.parallel_lapply(features, function(metric) {
    out <- matrix(NA_real_, length(fgs), ncol(mtr),
      dimnames = list(names(fgs), colnames(mtr)))
    for (set_index in seq_along(fgs)) {
      graph <- .spectral_pathway_graph(
        members = fgs[[set_index]], available_nodes = genes, net = net,
        min_ngenes = min_ngenes, scope = scope,
        weighted = grepl("w$", metric))
      if (is.null(graph)) next
      out[set_index, ] <- apply(mtr[rownames(graph$L), , drop = FALSE], 2L,
        .spectral_score, graph = graph, quotient = grepl("^rl", metric))
    }
    out
  }, n_cores = n_cores), features)
  mapped <- vapply(fgs, function(x) length(intersect(x,
    intersect(genes, names(net$links)))), integer(1))
  .new_nearender_result(scores, .new_score_info(features, "spectral", features,
    mode = scope,
    parameters = ifelse(grepl("w$", features), "weighted", "unweighted")),
    inputs = list(fgs_names = names(fgs), fgs_sizes = lengths(fgs)),
    diagnostics = list(fgs_network_sizes = mapped),
    parameters = list(scope = scope, min_ngenes = min_ngenes,
      case_sensitive = case_sensitive,
      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.