R/render-walks.R

Defines functions pagerank.render rwr.render .walk_result .walk_weights .prepare_walk_renderer

Documented in pagerank.render rwr.render

.prepare_walk_renderer <- function(ags, fgs, net, case_sensitive) {
  ags <- .normalize_gene_sets(ags, "ags", case_sensitive)
  fgs <- .normalize_gene_sets(fgs, "fgs", case_sensitive)
  graph <- as_igraph_network(net, case_sensitive)
  .assert_compatible_identifiers(ags = ags, fgs = fgs, net = graph)
  nodes <- igraph::vertex_attr(graph, "name")
  membership <- function(sets) {
    indices <- match(unlist(sets, use.names = FALSE), nodes)
    columns <- rep(seq_along(sets), lengths(sets))
    mapped <- !is.na(indices)
    Matrix::sparseMatrix(
      i = indices[mapped], j = columns[mapped], x = 1,
      dims = c(length(nodes), length(sets)),
      dimnames = list(nodes, names(sets))
    )
  }
  seeds <- membership(ags)
  seed_sizes <- Matrix::colSums(seeds)
  if (any(seed_sizes == 0)) {
    stop("Every AGS must contain a network gene; missing: ",
      paste(names(ags)[seed_sizes == 0], collapse = ", "), call. = FALSE)
  }
  seeds <- seeds %*% Matrix::Diagonal(x = 1 / seed_sizes)
  fgs_matrix <- membership(fgs)
  list(ags = ags, fgs = fgs, graph = graph, seeds = seeds,
    fgs_matrix = fgs_matrix, diagnostics = list(
      ags_original_sizes = lengths(ags),
      ags_network_sizes = stats::setNames(as.integer(seed_sizes), names(ags)),
      fgs_original_sizes = lengths(fgs),
      fgs_network_sizes = stats::setNames(
        as.integer(Matrix::colSums(fgs_matrix)), names(fgs))))
}

.walk_weights <- function(graph, use_edge_weights) {
  .assert_flag(use_edge_weights, "use_edge_weights")
  if (!use_edge_weights) return(list(values = NA, attribute = NULL))
  if (!"weight" %in% igraph::edge_attr_names(graph)) {
    stop("use_edge_weights = TRUE requires a numeric igraph `weight` edge ",
      "attribute.", call. = FALSE)
  }
  weights <- igraph::edge_attr(graph, "weight")
  if (anyNA(weights) || any(!is.finite(weights)) || any(weights < 0))
    stop("Weighted walks require finite, non-negative values in the igraph ",
      "`weight` edge attribute.", call. = FALSE)
  if (!any(weights > 0))
    stop("Weighted walks require at least one positive igraph edge weight.",
      call. = FALSE)
  list(values = weights, attribute = "weight")
}

.walk_result <- function(x, scores, renderer, parameters, citation) {
  scores <- as.matrix(scores)
  dimnames(scores) <- list(names(x$fgs), names(x$ags))
  .new_nearender_result(
    scores = stats::setNames(list(scores), renderer),
    score_info = .new_score_info(renderer, renderer, "total_fgs_affinity",
      parameters = paste(names(parameters), parameters, sep = "=", collapse = ";"),
      citation = citation),
    inputs = list(ags_names = names(x$ags), fgs_names = names(x$fgs),
      ags_sizes = lengths(x$ags), fgs_sizes = lengths(x$fgs)),
    diagnostics = x$diagnostics, parameters = parameters)
}

#' Render gene sets by random walk with restart
#'
#' Nodes in each AGS define a uniform restart distribution. Steady-state node
#' affinities are summed over the members of each FGS. This sparse-matrix
#' implementation follows the `dnet::dRWR()` algorithm without requiring the
#' dnet package at run time.
#'
#' Node-affinity vectors are stored as columns and updated by left
#' multiplication with the transition matrix. Under this convention,
#' `normalise = "column"` constructs `A D^-1`, whose columns sum to one, so
#' each source node distributes its probability among its neighbors.
#' `normalise = "row"` constructs `D^-1 A`, whose rows sum to one; when applied
#' to column vectors, this is a different, non-probability-conserving
#' propagation rule. For an undirected network the two matrices are transposes,
#' but they coincide only when connected nodes have equal degrees. The
#' `dnet::dRWR()` interface used the opposite labels; NEArender names the
#' options for the margin of the resulting transition matrix that is actually
#' normalized.
#'
#' @inheritParams nea.render
#' @param restart Restart probability in `[0, 1]`. Increasing it concentrates
#'   affinity nearer the AGS seeds and reduces contributions from longer paths.
#' @param normalise Adjacency normalization method. The `"column"` and
#'   `"row"` labels describe the normalized matrix margin and differ from the
#'   dnet labels.
#' @param tol Positive L1 convergence tolerance.
#' @param max_iter Positive maximum iteration count.
#' @param use_edge_weights Use the igraph `weight` edge attribute to determine
#'   transition probabilities. The default is `FALSE` because imported edge
#'   weights may encode evidence or confidence rather than a transition model.
#' @details With `use_edge_weights = FALSE`, every retained edge has equal
#'   weight. With `TRUE`, the non-negative igraph `weight` attribute is
#'   normalized according to `normalise` to derive propagation coefficients;
#'   for `normalise = "column"`, these are transition probabilities. The
#'   returned affinities are relative scores, not p- or q-values.
#' @return A `nearender_result`. `scores$rwr` is an FGS-by-AGS matrix whose
#'   cells sum steady-state node affinity over the corresponding FGS;
#'   `statistics$rwr` is the identical master score matrix.
#'   `diagnostics` reports mapped input sizes, convergence, and iteration
#'   count; `parameters` records restart, normalization, tolerance, iteration
#'   limit, weight use, and identifier case policy.
#' @references Fang H, Gough J (2014). \doi{10.1186/s13073-014-0064-8}.
#' @seealso [pagerank.render()], [nea.render()], [spectral.render()]
#' @examples
#' edges <- data.frame(from = c("A", "A", "B"), to = c("B", "C", "C"),
#'   confidence = c(5, 1, 2))
#' net <- import_network(edges, "from", "to", "confidence",
#'   species = NULL, input_id_format = "custom", verbose = FALSE)
#' ags <- list(sample = "a")
#' fgs <- list(pathway_b = "b", pathway_c = "c")
#' rwr <- rwr.render(ags, fgs, net, verbose = FALSE)
#' rwr$scores$rwr
#' @export
rwr.render <- function(ags, fgs, net, restart = 0.75,
                       normalise = c("laplacian", "column", "row", "none"),
                       tol = 1e-6, max_iter = 50L,
                       use_edge_weights = FALSE, case_sensitive = FALSE,
                       verbose = TRUE) {
  .assert_flag(case_sensitive, "case_sensitive")
  .assert_flag(verbose, "verbose")
  normalise <- match.arg(normalise)
  if (!is.numeric(restart) || length(restart) != 1L || is.na(restart) ||
      restart < 0 || restart > 1)
    stop("restart must be one number between 0 and 1.", call. = FALSE)
  if (!is.numeric(tol) || length(tol) != 1L || !is.finite(tol) || tol <= 0)
    stop("tol must be one positive finite number.", call. = FALSE)
  if (length(max_iter) != 1L || is.na(max_iter) || max_iter < 1 ||
      max_iter != as.integer(max_iter))
    stop("max_iter must be one positive integer.", call. = FALSE)
  if (verbose) message("Preparing gene sets and network for random walk.")
  x <- .prepare_walk_renderer(ags, fgs, net, case_sensitive)
  weights <- .walk_weights(x$graph, use_edge_weights)
  if (verbose) message("Building the sparse transition matrix.")
  adjacency <- igraph::as_adjacency_matrix(x$graph,
    attr = weights$attribute, sparse = TRUE)
  if (normalise == "laplacian") {
    strength <- Matrix::colSums(adjacency)
    scale <- ifelse(strength == 0, 0, strength^-0.5)
    transition <- Matrix::Diagonal(x = scale) %*% adjacency %*%
      Matrix::Diagonal(x = scale)
  } else if (normalise == "column") {
    sums <- Matrix::colSums(adjacency)
    transition <- adjacency %*% Matrix::Diagonal(
      x = ifelse(sums == 0, 0, 1 / sums))
  } else if (normalise == "row") {
    sums <- Matrix::rowSums(adjacency)
    transition <- Matrix::Diagonal(x = ifelse(sums == 0, 0, 1 / sums)) %*%
      adjacency
  } else transition <- adjacency
  if (verbose) message("Calculating random-walk affinities.")
  affinity <- x$seeds
  converged <- FALSE
  iterations <- 0L
  for (iteration in seq_len(as.integer(max_iter))) {
    updated <- (1 - restart) * transition %*% affinity + restart * x$seeds
    iterations <- iteration
    if (sum(abs(updated - affinity)) <= tol) {
      affinity <- updated
      converged <- TRUE
      break
    }
    affinity <- updated
  }
  totals <- Matrix::colSums(affinity)
  affinity <- affinity %*% Matrix::Diagonal(
    x = ifelse(totals == 0, 0, 1 / totals))
  x$diagnostics$converged <- converged
  x$diagnostics$iterations <- iterations
  parameters <- list(restart = restart, normalise = normalise, tol = tol,
    max_iter = as.integer(max_iter), use_edge_weights = use_edge_weights,
    case_sensitive = case_sensitive)
  .walk_result(x, Matrix::crossprod(x$fgs_matrix, affinity), "rwr",
    parameters, "Fang and Gough (2014), doi:10.1093/nar/gku035")
}

#' Render gene sets by personalized PageRank
#'
#' Nodes in each AGS supply a uniform personalization vector to
#' [igraph::page_rank()]. PageRank probabilities are summed over each FGS.
#'
#' @inheritParams nea.render
#' @param damping PageRank damping factor in the interval `(0, 1)`. Increasing
#'   it raises the probability of following network edges, lowers the implicit
#'   restart probability `1 - damping`, and permits longer-range diffusion.
#'   Thus its direction is opposite to increasing `restart` in [rwr.render()].
#' @param use_edge_weights Use the igraph `weight` edge attribute to determine
#'   transition probabilities. The default is `FALSE` because imported edge
#'   weights may encode evidence or confidence rather than a transition model.
#' @param n_cores Positive integer number of worker processes. Independent AGS
#'   personalization vectors are distributed across workers when greater than
#'   one.
#' @details With `use_edge_weights = FALSE`, NEArender explicitly suppresses
#'   igraph's automatic use of a `weight` attribute. With `TRUE`, each
#'   source node's edge weights are normalized to transition probabilities by
#'   PageRank. Returned pathway affinities are relative scores, not p- or
#'   q-values.
#' @return A `nearender_result`. `scores$pagerank` is an FGS-by-AGS matrix
#'   obtained by summing personalized PageRank probabilities over each FGS;
#'   `statistics$pagerank` is the identical master score matrix.
#'   `diagnostics` reports original and mapped AGS/FGS sizes, and
#'   `parameters` records damping, edge-weight use, case policy, and workers.
#' @seealso [rwr.render()], [nea.render()], [spectral.render()]
#' @examples
#' edges <- data.frame(from = c("A", "A", "B"), to = c("B", "C", "C"),
#'   confidence = c(5, 1, 2))
#' net <- import_network(edges, "from", "to", "confidence",
#'   species = NULL, input_id_format = "custom", verbose = FALSE)
#' ags <- list(sample = "a")
#' fgs <- list(pathway_b = "b", pathway_c = "c")
#' page <- pagerank.render(ags, fgs, net, verbose = FALSE)
#' page$scores$pagerank
#' @export
pagerank.render <- function(ags, fgs, net, damping = 0.15,
                            use_edge_weights = FALSE,
                            case_sensitive = FALSE, n_cores = 1L,
                            verbose = TRUE) {
  .assert_flag(case_sensitive, "case_sensitive")
  .assert_flag(verbose, "verbose")
  n_cores <- .validate_n_cores(n_cores)
  if (!is.numeric(damping) || length(damping) != 1L || is.na(damping) ||
      damping <= 0 || damping >= 1)
    stop("damping must be one number strictly between 0 and 1.", call. = FALSE)
  if (verbose) message("Preparing gene sets and network for PageRank.")
  x <- .prepare_walk_renderer(ags, fgs, net, case_sensitive)
  weights <- .walk_weights(x$graph, use_edge_weights)
  if (verbose) message("Calculating personalized PageRank scores.")
  affinity <- .parallel_lapply(seq_len(ncol(x$seeds)), function(index) {
    igraph::page_rank(x$graph, directed = FALSE, damping = damping,
      personalized = as.numeric(x$seeds[, index]),
      weights = weights$values)$vector
  }, n_cores = n_cores)
  affinity <- do.call(cbind, affinity)
  parameters <- list(damping = damping, use_edge_weights = use_edge_weights,
    case_sensitive = case_sensitive,
    n_cores = n_cores)
  .walk_result(x, Matrix::crossprod(x$fgs_matrix, affinity), "pagerank",
    parameters, "igraph personalized PageRank")
}

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.