R/plot-subgraph.R

Defines functions plot_subgraph .plot_subgraph_apply_attributes .plot_subgraph_attributes .plot_subgraph_color_values .plot_subgraph_igraph .plot_subgraph_indexed .plot_subgraph_legacy .plot_subgraph_from_edges .plot_subgraph_unique_edges .plot_subgraph_pathway

Documented in plot_subgraph

.plot_subgraph_pathway <- function(fgs, case_sensitive) {
  pathway_name <- NULL
  if (is.list(fgs)) {
    if (length(fgs) != 1L) {
      stop("fgs must contain exactly one pathway; select one with, for ",
        "example, fgs[\"pathway_name\"].", call. = FALSE)
    }
    if (is.null(names(fgs)) || is.na(names(fgs)) || !nzchar(names(fgs))) {
      stop("A pathway supplied as a list must have one non-empty name.",
        call. = FALSE)
    }
    pathway_name <- names(fgs)
    normalized <- .normalize_gene_sets(fgs, "fgs", case_sensitive)
  } else {
    if (!is.atomic(fgs) || !is.null(dim(fgs))) {
      stop("fgs must be a gene vector or a one-element named list.",
        call. = FALSE)
    }
    normalized <- .normalize_gene_sets(
      stats::setNames(list(fgs), ".pathway"), "fgs", case_sensitive)
  }
  members <- normalized[[1L]]
  if (!length(members)) {
    stop("fgs must contain at least one non-missing gene identifier.",
      call. = FALSE)
  }
  list(members = members, name = pathway_name, normalized = normalized)
}

.plot_subgraph_unique_edges <- function(from, to, node_order,
    weight = NULL) {
  weighted <- !is.null(weight)
  empty <- data.frame(from = character(), to = character(),
    stringsAsFactors = FALSE)
  if (weighted) empty$weight <- numeric()
  if (!length(from)) return(empty)

  from_id <- match(from, node_order)
  to_id <- match(to, node_order)
  keep <- !is.na(from_id) & !is.na(to_id) & from_id != to_id
  if (!any(keep)) return(empty)
  from_id <- from_id[keep]
  to_id <- to_id[keep]
  if (weighted) weight <- weight[keep]
  left <- pmin(from_id, to_id)
  right <- pmax(from_id, to_id)
  ordering <- order(left, right)
  left <- left[ordering]
  right <- right[ordering]
  if (weighted) weight <- weight[ordering]
  first <- !duplicated(paste(left, right, sep = ":"))
  result <- data.frame(
    from = node_order[left[first]],
    to = node_order[right[first]],
    stringsAsFactors = FALSE
  )
  if (weighted) result$weight <- as.numeric(weight[first])
  result
}

.plot_subgraph_from_edges <- function(nodes, edges) {
  if (!nrow(edges)) {
    graph <- igraph::make_empty_graph(length(nodes), directed = FALSE)
    return(igraph::set_vertex_attr(graph, "name", value = nodes))
  }
  igraph::graph_from_data_frame(
    edges, directed = FALSE,
    vertices = data.frame(name = nodes, stringsAsFactors = FALSE)
  )
}

.plot_subgraph_legacy <- function(network, mapped, scope) {
  node_names <- names(network$links)
  selected <- mapped
  if (scope == "boundary-expanded") {
    boundary <- unique(unlist(network$links[mapped], use.names = FALSE))
    selected <- unique(c(mapped, intersect(boundary, node_names)))
  }

  adjacent <- lapply(network$links[selected], intersect, y = selected)
  from <- rep(selected, lengths(adjacent))
  to <- unlist(adjacent, use.names = FALSE)
  weight <- NULL
  if (!is.null(network$weights) && length(from)) {
    weight <- mapply(function(node, neighbor) {
      value <- network$weights[[node]][neighbor]
      if (length(value) != 1L || is.na(value) || !is.finite(value)) {
        stop("Legacy weights must provide one finite value for every edge.",
          call. = FALSE)
      }
      unname(value)
    }, from, to, USE.NAMES = FALSE)
  } else if (!is.null(network$weights)) {
    weight <- numeric()
  }
  edges <- .plot_subgraph_unique_edges(from, to, node_names, weight)
  .plot_subgraph_from_edges(selected, edges)
}

.plot_subgraph_indexed <- function(network, mapped, scope) {
  node_names <- network$node_names
  mapped_id <- match(mapped, node_names)
  selected_id <- mapped_id
  if (scope == "boundary-expanded") {
    outgoing <- Matrix::summary(network$adjacency[mapped_id, , drop = FALSE])
    incoming <- Matrix::summary(network$adjacency[, mapped_id, drop = FALSE])
    boundary_id <- unique(c(outgoing$j, incoming$i))
    selected_id <- unique(c(mapped_id, boundary_id))
  }
  selected <- node_names[selected_id]
  entries <- Matrix::summary(
    network$adjacency[selected_id, selected_id, drop = FALSE])
  from <- selected[entries$i]
  to <- selected[entries$j]
  weight <- NULL
  if (!is.null(network$weights)) {
    weight <- as.numeric(network$weights[cbind(
      selected_id[entries$i], selected_id[entries$j])])
  }
  edges <- .plot_subgraph_unique_edges(from, to, node_names, weight)
  .plot_subgraph_from_edges(selected, edges)
}

.plot_subgraph_igraph <- function(network, mapped, scope) {
  node_names <- igraph::vertex_attr(network, "name")
  mapped_id <- match(mapped, node_names)
  selected_id <- mapped_id
  if (scope == "boundary-expanded") {
    boundary_id <- unique(unlist(lapply(mapped_id, function(node) {
      as.integer(igraph::neighbors(network, node, mode = "all"))
    }), use.names = FALSE))
    selected_id <- unique(c(mapped_id, boundary_id))
  }
  igraph::induced_subgraph(network, vids = selected_id)
}

.plot_subgraph_color_values <- function(values) {
  result <- rep(NA_character_, length(values))
  names(result) <- names(values)
  present <- !is.na(values)
  if (!any(present)) return(result)

  if (is.numeric(values)) {
    numeric_values <- as.numeric(values[present])
    if (any(!is.finite(numeric_values))) {
      stop("Color attributes must not contain infinite values.",
        call. = FALSE)
    }
    value_range <- range(numeric_values)
    scaled <- if (diff(value_range) == 0) {
      rep(0.5, length(numeric_values))
    } else {
      (numeric_values - value_range[[1L]]) / diff(value_range)
    }
    palette <- grDevices::hcl.colors(256L, "Viridis")
    result[present] <- palette[1L + floor(255 * scaled)]
    return(result)
  }

  labels <- as.character(values[present])
  literal_colors <- tryCatch({
    grDevices::col2rgb(labels)
    TRUE
  }, error = function(error) FALSE)
  if (literal_colors) {
    rgba <- grDevices::col2rgb(labels, alpha = TRUE)
    result[present] <- grDevices::rgb(
      rgba[1L, ], rgba[2L, ], rgba[3L, ], alpha = rgba[4L, ],
      maxColorValue = 255)
    return(result)
  }

  levels <- sort(unique(labels))
  palette <- grDevices::hcl.colors(max(3L, length(levels)), "Dark 3")
  color_key <- stats::setNames(palette[seq_along(levels)], levels)
  result[present] <- unname(color_key[labels])
  result
}

.plot_subgraph_attributes <- function(attributes, case_sensitive) {
  if (is.null(attributes)) return(NULL)
  if (is.data.frame(attributes) || is.matrix(attributes)) {
    node_names <- rownames(attributes)
    if (is.null(node_names)) {
      stop("Tabular attributes must have node identifiers as row names.",
        call. = FALSE)
    }
    if (is.null(colnames(attributes))) {
      stop("Tabular attributes must have color and/or size columns.",
        call. = FALSE)
    }
    selected <- intersect(c("color", "size"), colnames(attributes))
    if (!length(selected)) {
      stop("Tabular attributes must contain a color and/or size column.",
        call. = FALSE)
    }
    attributes <- lapply(selected, function(column) {
      value <- attributes[, column]
      names(value) <- node_names
      value
    })
    names(attributes) <- selected
  } else if (is.atomic(attributes) && is.null(dim(attributes))) {
    attributes <- list(color = attributes)
  } else if (!is.list(attributes)) {
    stop("attributes must be a named vector, a color/size list, or a ",
      "node-by-attribute table.", call. = FALSE)
  }

  if (!length(attributes) || is.null(names(attributes)) ||
      anyNA(names(attributes)) || any(!nzchar(names(attributes))) ||
      anyDuplicated(names(attributes)) ||
      any(!names(attributes) %in% c("color", "size"))) {
    stop("attributes must contain uniquely named color and/or size values.",
      call. = FALSE)
  }
  styles <- names(attributes)
  attributes <- lapply(styles, function(style) {
    values <- attributes[[style]]
    if (!is.atomic(values) || is.null(names(values)) ||
        length(names(values)) != length(values)) {
      stop("Each attributes element must be an atomic vector named by node.",
        call. = FALSE)
    }
    node_names <- .canonical_ids(names(values), case_sensitive)
    if (anyNA(node_names) || any(!nzchar(node_names))) {
      stop("Attribute node names must be non-missing and non-empty.",
        call. = FALSE)
    }
    if (anyDuplicated(node_names)) {
      stop("Attribute node names must remain unique under the identifier ",
        "case policy.", call. = FALSE)
    }
    names(values) <- node_names
    if (style == "color") return(.plot_subgraph_color_values(values))

    numeric_values <- suppressWarnings(as.numeric(
      if (is.factor(values)) as.character(values) else values))
    invalid <- !is.na(values) &
      (is.na(numeric_values) | !is.finite(numeric_values) |
        numeric_values < 0)
    if (any(invalid)) {
      stop("Size attributes must be non-negative finite numbers or NA.",
        call. = FALSE)
    }
    names(numeric_values) <- node_names
    numeric_values
  })
  names(attributes) <- styles
  attributes
}

.plot_subgraph_apply_attributes <- function(graph, attributes) {
  node_names <- igraph::vertex_attr(graph, "name")
  pathway_member <- igraph::vertex_attr(graph, "pathway_member")
  colors <- ifelse(pathway_member, "#E69F00", "#56B4E9")
  if (!is.null(attributes$color)) {
    matched <- match(node_names, names(attributes$color))
    replace <- which(!is.na(matched))
    supplied <- attributes$color[matched[replace]]
    replace <- replace[!is.na(supplied)]
    supplied <- supplied[!is.na(supplied)]
    colors[replace] <- unname(supplied)
  }
  graph <- igraph::set_vertex_attr(graph, "color", value = colors)

  if (!is.null(attributes$size)) {
    sizes <- rep(15, length(node_names))
    matched <- match(node_names, names(attributes$size))
    replace <- which(!is.na(matched))
    supplied <- attributes$size[matched[replace]]
    replace <- replace[!is.na(supplied)]
    supplied <- supplied[!is.na(supplied)]
    sizes[replace] <- unname(supplied)
    graph <- igraph::set_vertex_attr(graph, "size", value = sizes)
  }
  graph
}

#' Extract and plot one pathway subgraph
#'
#' Quickly extract the network induced by one pathway and optionally draw it
#' with igraph. Pathway members are retained even when they are isolated in the
#' selected scope, and the extracted igraph object is returned invisibly.
#'
#' @param net An undirected igraph network, a legacy network with a named
#'   adjacency list in `links`, an indexed sparse NEArender network, or a
#'   sparse adjacency matrix.
#' @param fgs A character vector containing one pathway, or a one-element named
#'   gene-set list. A named list supplies the default plot title.
#' @param scope Graph scope. `"within-pathway"` returns the subgraph induced by
#'   mapped pathway members. `"boundary-expanded"` also includes all one-hop
#'   neighbors and edges among the selected nodes.
#' @param attributes Optional node display attributes. Supply a named vector to
#'   color-code nodes, a named list with `color` and/or `size` vectors, or a
#'   data frame or matrix with node identifiers as row names and `color` and/or
#'   `size` columns. Numeric color values use a continuous palette; categorical
#'   values use a discrete palette; valid R colors are used literally. Sizes
#'   are non-negative values in igraph plotting units. Attribute node names use
#'   the same case policy as `fgs` and `net`; omitted or `NA` values retain the
#'   defaults.
#' @param plot Draw the extracted graph.
#' @param main Plot title. By default, use the pathway name when `fgs` is a
#'   named list, otherwise `"Pathway subgraph"`.
#' @param case_sensitive Use case-sensitive identifier matching.
#' @param ... Additional arguments passed to igraph's plot method. Explicit
#'   `vertex.color` and `vertex.size` arguments override the stored display
#'   attributes for that drawing.
#' @details By default, pathway members are orange and boundary nodes are blue.
#'   The returned graph has a logical `pathway_member` vertex attribute,
#'   display `color` (and, when supplied, `size`) vertex attributes, and retains
#'   source edge weights. Partial pathway and attribute mapping is allowed, but
#'   at least one pathway member must map to the network.
#' @return Invisibly, a simple undirected igraph graph for the selected scope.
#' @seealso [spectral_eigenpairs()], [as_igraph_network()]
#' @examples
#' net <- list(
#'   links = list(A = "B", B = c("A", "C"), C = "B"),
#'   Ntotal = 2)
#' graph <- plot_subgraph(net, list(signaling = c("A", "B")),
#'   scope = "boundary-expanded", plot = FALSE,
#'   attributes = list(color = c(A = "activated", B = "repressed"),
#'     size = c(A = 20, B = 12)))
#' igraph::vertex_attr(graph, "pathway_member")
#' @export
plot_subgraph <- function(net, fgs,
    scope = c("within-pathway", "boundary-expanded"), attributes = NULL,
    plot = TRUE, main = NULL, case_sensitive = FALSE, ...) {
  if (!missing(scope) && length(scope) != 1L) {
    stop("scope must select exactly one graph scope.", call. = FALSE)
  }
  scope <- match.arg(scope)
  .assert_flag(plot, "plot")
  .assert_flag(case_sensitive, "case_sensitive")
  if (!is.null(main) &&
      (!is.character(main) || length(main) != 1L || is.na(main))) {
    stop("main must be NULL or one non-missing character value.",
      call. = FALSE)
  }

  pathway <- .plot_subgraph_pathway(fgs, case_sensitive)
  network <- if (inherits(net, "Matrix")) {
    as_igraph_network(net, case_sensitive)
  } else {
    .normalize_network(net, case_sensitive)
  }
  .assert_compatible_identifiers(fgs = pathway$normalized, net = network)

  node_names <- if (igraph::is_igraph(network)) {
    igraph::vertex_attr(network, "name")
  } else if (inherits(network, "nearender_indexed_network")) {
    network$node_names
  } else {
    names(network$links)
  }
  mapped <- intersect(pathway$members, node_names)
  if (!length(mapped)) {
    stop("No pathway members in fgs map to network nodes.", call. = FALSE)
  }

  graph <- if (igraph::is_igraph(network)) {
    .plot_subgraph_igraph(network, mapped, scope)
  } else if (inherits(network, "nearender_indexed_network")) {
    .plot_subgraph_indexed(network, mapped, scope)
  } else {
    .plot_subgraph_legacy(network, mapped, scope)
  }
  graph_nodes <- igraph::vertex_attr(graph, "name")
  graph <- igraph::set_vertex_attr(graph, "pathway_member",
    value = graph_nodes %in% mapped)
  graph <- igraph::set_graph_attr(graph, "Ntotal",
    value = igraph::ecount(graph))
  graph <- igraph::set_graph_attr(graph, "nearender_scope", value = scope)
  graph <- igraph::set_graph_attr(graph, "nearender_case_sensitive",
    value = case_sensitive)
  if (!is.null(pathway$name)) {
    graph <- igraph::set_graph_attr(graph, "nearender_pathway",
      value = pathway$name)
  }
  graph <- .mark_normalized(graph, case_sensitive)
  identifiers <- .identifier_metadata(network)
  if (is.null(identifiers)) {
    identifiers <- .identifier_metadata(pathway$normalized)
  }
  if (!is.null(identifiers)) {
    graph <- .attach_identifier_metadata(graph, identifiers)
  }

  display_attributes <- .plot_subgraph_attributes(attributes, case_sensitive)
  graph <- .plot_subgraph_apply_attributes(graph, display_attributes)
  if (is.null(main)) {
    main <- if (is.null(pathway$name)) "Pathway subgraph" else pathway$name
  }
  if (plot) graphics::plot(graph, main = main, ...)
  invisible(graph)
}

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.