R/network-overlap.R

Defines functions network_overlap .plot_network_overlap_upset .network_overlap_venn_counts .network_overlap_venn_style .format_network_overlap_totals .network_overlap_intersections .network_overlap_sets

Documented in network_overlap

.network_overlap_sets <- function(net, normalize, case_sensitive) {
  net <- .prepare_investigation_network(net, normalize, case_sensitive)

  if (igraph::is_igraph(net)) {
    vertices <- igraph::vertex_attr(net, "name")
    edge_ids <- igraph::as_edgelist(net, names = FALSE)
    from_id <- edge_ids[, 1L]
    to_id <- edge_ids[, 2L]
  } else if (inherits(net, "nearender_indexed_network")) {
    entries <- methods::as(net$adjacency, "TsparseMatrix")
    vertices <- net$node_names
    from_id <- methods::slot(entries, "i") + 1L
    to_id <- methods::slot(entries, "j") + 1L
  } else {
    link_counts <- lengths(net$links)
    to_names <- unlist(net$links, use.names = FALSE)
    vertices <- unique(c(names(net$links), to_names))
    vertices <- vertices[!is.na(vertices) & nzchar(vertices)]
    from_id <- rep(match(names(net$links), vertices), link_counts)
    to_id <- match(to_names, vertices)
  }

  valid <- !is.na(from_id) & !is.na(to_id)
  first <- pmin.int(from_id[valid], to_id[valid])
  second <- pmax.int(from_id[valid], to_id[valid])
  edge_codes <- first + (second - 1) * length(vertices)
  keep <- !duplicated(edge_codes)
  edges <- paste(vertices[first[keep]], vertices[second[keep]], sep = " -- ")

  list(vertices = vertices, edges = edges)
}

.network_overlap_intersections <- function(sets) {
  universe <- unique(unlist(sets, use.names = FALSE))
  network_count <- length(sets)
  if (!length(universe)) {
    membership <- matrix(logical(), nrow = 0L, ncol = network_count,
      dimnames = list(NULL, names(sets)))
    return(list(
      table = data.frame(intersection = character(), pattern = character(),
        degree = integer(), count = integer()),
      membership = membership,
      members = list()
    ))
  }

  # Numeric bit masks are exact for the supported maximum of 30 networks.
  weights <- 2^(seq_len(network_count) - 1L)
  codes <- numeric(length(universe))
  for (i in seq_along(sets)) {
    positions <- match(sets[[i]], universe, nomatch = 0L)
    positions <- positions[positions > 0L]
    codes[positions] <- codes[positions] + weights[[i]]
  }

  observed <- unique(codes)
  code_index <- match(codes, observed)
  counts <- tabulate(code_index, nbins = length(observed))
  membership <- outer(observed, weights, function(code, weight) {
    (code %/% weight) %% 2 == 1
  })
  colnames(membership) <- names(sets)
  degree <- rowSums(membership)
  order_index <- order(counts, degree, decreasing = TRUE)

  membership <- membership[order_index, , drop = FALSE]
  counts <- counts[order_index]
  degree <- degree[order_index]
  members_by_code <- split(universe,
    factor(code_index, levels = seq_along(unique(codes))))
  members <- unname(members_by_code[order_index])
  patterns <- apply(membership, 1L, function(x) paste0(as.integer(x),
    collapse = ""))
  labels <- apply(membership, 1L, function(x) {
    paste(names(sets)[x], collapse = " & ")
  })
  names(members) <- labels

  table <- data.frame(
    intersection = labels,
    pattern = patterns,
    degree = degree,
    count = counts,
    stringsAsFactors = FALSE
  )
  table <- cbind(table,
    as.data.frame(membership, check.names = FALSE, stringsAsFactors = FALSE))
  rownames(table) <- NULL

  list(table = table, membership = membership, members = members)
}

.format_network_overlap_totals <- function(values) {
  format(values, big.mark = ",", scientific = FALSE, trim = TRUE)
}

.network_overlap_venn_style <- function(network_names) {
  maximum_width <- max(nchar(network_names, type = "width"))
  side_margin <- min(7, 3.5 + max(0, maximum_width - 18) / 8)
  name_cex <- max(0.55, min(0.85, 18 / max(18, maximum_width) * 0.85))
  list(
    mar = c(2.5, side_margin, 3, side_margin),
    sncs = name_cex,
    xpd = NA
  )
}

.network_overlap_venn_counts <- function(overlap, network_count) {
  counts <- numeric(2^network_count)
  if (nrow(overlap$table)) {
    positions <- strtoi(overlap$table$pattern, base = 2L) + 1L
    counts[positions] <- overlap$table$count
  }
  counts
}

.plot_network_overlap_upset <- function(overlap, main, max_intersections,
    set_sizes, total_label) {
  table <- overlap$table
  if (!nrow(table)) {
    graphics::plot.new()
    graphics::title(main = main)
    graphics::text(0.5, 0.5, "No elements")
    return(invisible(NULL))
  }

  shown <- seq_len(min(nrow(table), max_intersections))
  membership <- overlap$membership[shown, , drop = FALSE]
  counts <- table$count[shown]
  x <- seq_along(shown)
  maximum <- max(counts)
  bar_height <- counts / maximum
  matrix_y <- seq(-0.18, -0.92, length.out = ncol(membership))

  graphics::plot.new()
  graphics::plot.window(xlim = c(0.3, length(x) + 0.7), ylim = c(-1, 1.16),
    xaxs = "i", yaxs = "i")
  graphics::rect(x - 0.38, 0, x + 0.38, bar_height,
    col = "gray35", border = NA)
  graphics::text(x, bar_height + 0.035, labels = format(counts, big.mark = ","),
    cex = 0.62, srt = 90, adj = c(0, 0.5), xpd = NA)

  ticks <- pretty(c(0, maximum), n = 4L)
  ticks <- ticks[ticks >= 0 & ticks <= maximum]
  graphics::axis(2, at = ticks / maximum, labels = format(ticks,
    big.mark = ",", scientific = FALSE), las = 1, cex.axis = 0.72)
  graphics::mtext("Intersection size", side = 2, line = 3.4, cex = 0.8)
  graphics::abline(h = matrix_y, col = "gray92", lwd = 0.8)

  for (i in seq_along(x)) {
    selected <- which(membership[i, ])
    if (length(selected) > 1L) {
      graphics::segments(x[[i]], matrix_y[min(selected)], x[[i]],
        matrix_y[max(selected)], lwd = 1.2)
    }
  }
  graphics::points(rep(x, each = ncol(membership)), rep(matrix_y, length(x)),
    pch = 16, col = ifelse(c(t(membership)), "black", "gray85"), cex = 0.7)
  row_labels <- sprintf("%s\n%s = %s", colnames(membership), total_label,
    .format_network_overlap_totals(set_sizes[colnames(membership)]))
  row_cex <- max(0.45, min(0.68, 4.2 / ncol(membership)))
  graphics::text(0.18, matrix_y, labels = row_labels, adj = c(1, 0.5),
    xpd = NA, cex = row_cex)
  graphics::title(main = main)
  graphics::mtext(sprintf("Largest %d of %d observed intersections",
    length(shown), nrow(table)), side = 1, line = 0.2, cex = 0.68)
  invisible(NULL)
}

#' Calculate and present shared vertices and edges among networks
#'
#' `network_overlap()` treats edges as undirected, collapses reciprocal and
#' duplicate adjacency-list entries, and compares the resulting exact edge and
#' vertex sets. Curated, experimental, and computational networks may have low
#' exact overlap because each contains false-positive edges and misses real
#' interactions. Overlap is therefore a structural comparison, not an absolute
#' performance measure; use [nea_member_recovery_benchmark()] for pathway-member
#' recovery. The function draws Venn diagrams for up to five networks by
#' default and switches to UpSet-style plots for larger comparisons. Venn
#' panels use expanded side margins and adaptive text for long names. Network
#' labels include the corresponding total numbers of vertices or edges.
#'
#' @param networks Named list containing two or more networks. Each network may
#'   be an undirected igraph, a legacy named adjacency list with `links` and
#'   `Ntotal`, or an indexed network created internally by NEArender.
#' @param plot Draw the vertex and edge overlap plots.
#' @param plot_type One of `"auto"`, `"venn"`, `"upset"`, or `"both"`.
#'   Automatic mode uses Venn diagrams for at most five networks and UpSet-style
#'   plots for more. `"both"` draws Venn diagrams on the first page and
#'   UpSet-style plots on the second. Venn output supports at most seven
#'   networks.
#' @param max_intersections Maximum number of observed intersections shown in
#'   each UpSet-style plot. All observed intersections are still returned as
#'   tables.
#' @param case_sensitive Identifier case policy used when `normalize = TRUE`.
#' @param colors Colors passed to [venn::venn()] as its `zcolor` argument.
#' @param opacity Venn region opacity between zero and one.
#' @param normalize Re-normalize network node identifiers. The default is
#'   `FALSE` because networks are normally normalized during import. Enabling
#'   this option warns because it copies and processes the full adjacency data.
#' @return Invisibly, a list with per-network summaries and exact vertex and
#'   edge sets, intersection tables, and intersection members. In an
#'   intersection pattern, positions correspond to `names(networks)` and `1`
#'   denotes membership.
#' @seealso [nea_member_recovery_benchmark()], [node_degrees()], [topology_2nd()]
#' @export
#' @examples
#' first <- list(links = list(a = "b", b = c("a", "c"), c = "b"),
#'   Ntotal = 2)
#' second <- list(links = list(b = "c", c = c("b", "d"), d = "c"),
#'   Ntotal = 2)
#' overlap <- network_overlap(list(first = first, second = second), plot = FALSE)
#' overlap$vertices$table
network_overlap <- function(networks, plot = TRUE,
    plot_type = c("auto", "venn", "upset", "both"),
    max_intersections = 30L,
    case_sensitive = FALSE, colors = "style", opacity = 0.3,
    normalize = FALSE) {
  .assert_flag(plot, "plot")
  .assert_flag(case_sensitive, "case_sensitive")
  .assert_flag(normalize, "normalize")
  plot_type <- match.arg(plot_type)
  if (!is.list(networks) || is.null(names(networks)) || length(networks) < 2L) {
    stop("networks must be a named list containing at least two networks.",
      call. = FALSE)
  }
  if (anyNA(names(networks)) || any(!nzchar(names(networks))) ||
      anyDuplicated(names(networks))) {
    stop("networks must have unique, non-empty names.", call. = FALSE)
  }
  if (length(networks) > 30L) {
    stop("network_overlap() supports at most 30 networks per comparison.",
      call. = FALSE)
  }
  if (length(max_intersections) != 1L || is.na(max_intersections) ||
      max_intersections < 1L || max_intersections != as.integer(max_intersections)) {
    stop("max_intersections must be one positive integer.", call. = FALSE)
  }
  if (!is.numeric(opacity) || length(opacity) != 1L || is.na(opacity) ||
      opacity < 0 || opacity > 1) {
    stop("opacity must be one number between zero and one.", call. = FALSE)
  }

  if (normalize) .warn_investigation_normalization("network_overlap")
  extracted <- lapply(networks, .network_overlap_sets, normalize = normalize,
    case_sensitive = case_sensitive)
  vertex_sets <- lapply(extracted, `[[`, "vertices")
  edge_sets <- lapply(extracted, `[[`, "edges")
  names(vertex_sets) <- names(edge_sets) <- names(networks)
  vertices <- .network_overlap_intersections(vertex_sets)
  edges <- .network_overlap_intersections(edge_sets)
  summary <- data.frame(
    network = names(networks),
    vertices = lengths(vertex_sets),
    edges = lengths(edge_sets),
    stringsAsFactors = FALSE
  )
  rownames(summary) <- NULL

  result <- list(
    summary = summary,
    vertices = c(list(sets = vertex_sets), vertices),
    edges = c(list(sets = edge_sets), edges)
  )
  class(result) <- c("nearender_network_overlap", "list")

  if (plot) {
    selected_plot <- if (plot_type == "auto") {
      if (length(networks) <= 5L) "venn" else "upset"
    } else plot_type
    draw_venn <- selected_plot %in% c("venn", "both")
    draw_upset <- selected_plot %in% c("upset", "both")
    if (draw_venn && length(networks) > 7L) {
      stop("Venn output supports at most seven networks; use plot_type = 'upset'.",
        call. = FALSE)
    }
    old_par <- graphics::par(no.readonly = TRUE)
    on.exit(graphics::par(old_par), add = TRUE)
    if (draw_venn) {
      if (!requireNamespace("venn", quietly = TRUE)) {
        stop("Venn plotting requires the suggested venn package; install it or use plot_type = 'upset'.",
          call. = FALSE)
      }
      venn_style <- .network_overlap_venn_style(names(networks))
      graphics::par(mfrow = c(1L, 2L), mar = venn_style$mar,
        xpd = venn_style$xpd)
      vertex_labels <- sprintf("%s\nn(V) = %s", names(networks),
        .format_network_overlap_totals(lengths(vertex_sets)))
      edge_labels <- sprintf("%s\nn(E) = %s", names(networks),
        .format_network_overlap_totals(lengths(edge_sets)))
      venn::venn(length(networks), snames = vertex_labels,
        counts = .network_overlap_venn_counts(vertices, length(networks)),
        zcolor = colors,
        opacity = opacity, par = FALSE, box = FALSE, sncs = venn_style$sncs)
      graphics::title(main = "Shared vertices")
      venn::venn(length(networks), snames = edge_labels,
        counts = .network_overlap_venn_counts(edges, length(networks)),
        zcolor = colors,
        opacity = opacity, par = FALSE, box = FALSE, sncs = venn_style$sncs)
      graphics::title(main = "Shared edges")
    }
    if (draw_upset) {
      graphics::par(mfrow = c(1L, 2L), mar = c(2.5, 7.5, 3, 1.5),
        xpd = NA)
      .plot_network_overlap_upset(vertices, "Shared vertices",
        as.integer(max_intersections), lengths(vertex_sets), "n(V)")
      .plot_network_overlap_upset(edges, "Shared edges",
        as.integer(max_intersections), lengths(edge_sets), "n(E)")
    }
  }

  invisible(result)
}

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.