R/import-network-matrix.R

Defines functions import_network .adjacency_matrix_edge_table .release_unused_matrix_memory

Documented in import_network

.release_unused_matrix_memory <- function() {
  invisible(gc(full = TRUE))
  if (!is.loaded("C_nearender_trim_memory", PACKAGE = "NEArender")) {
    return(invisible(FALSE))
  }
  invisible(isTRUE(.Call("C_nearender_trim_memory", PACKAGE = "NEArender")))
}

.adjacency_matrix_edge_table <- function(source, min_score = NULL,
    min_abs_score = NULL, n_top = NULL, n_abs_top = NULL, greedy = TRUE) {
  if (!(is.matrix(source) || inherits(source, "Matrix"))) {
    stop("source must be a matrix when is_matrix = TRUE.", call. = FALSE)
  }
  dimensions <- dim(source)
  if (length(dimensions) != 2L || !dimensions[[1L]] ||
      dimensions[[1L]] != dimensions[[2L]]) {
    stop("An adjacency matrix must be a non-empty square matrix.",
      call. = FALSE)
  }
  if ((is.matrix(source) &&
      (!is.numeric(source) || is.complex(source))) ||
      (inherits(source, "Matrix") &&
      !methods::is(source, "dMatrix"))) {
    stop("An adjacency matrix must contain numeric values.", call. = FALSE)
  }

  node_names <- rownames(source)
  if (is.null(node_names) || is.null(colnames(source)) ||
      !identical(node_names, colnames(source)) || anyNA(node_names) ||
      any(!nzchar(node_names))) {
    stop(paste0(
      "An adjacency matrix must have identical, non-empty row and column ",
      "names."), call. = FALSE)
  }
  diagonal <- if (inherits(source, "Matrix")) {
    as.numeric(Matrix::diag(source))
  } else {
    as.numeric(diag(source))
  }
  nonzero_diagonal <- is.finite(diagonal) & diagonal != 0
  if (any(nonzero_diagonal)) {
    warning("Ignored ", sum(nonzero_diagonal),
      " nonzero diagonal entr",
      if (sum(nonzero_diagonal) == 1L) "y" else "ies",
      "; adjacency-matrix diagonal values do not define network edges.",
      call. = FALSE)
  }

  dense_top_boundary <- NULL
  retain_values <- function(values) {
    finite <- is.finite(values)
    keep <- !finite
    candidate <- finite & values != 0
    if (!is.null(min_score)) {
      candidate <- candidate & values >= min_score
    }
    if (!is.null(min_abs_score)) {
      candidate <- candidate & abs(values) >= min_abs_score
    }
    if (!is.null(dense_top_boundary)) {
      ranking <- if (!is.null(n_abs_top)) abs(values) else values
      if (isFALSE(greedy)) {
        candidate <- candidate & ranking > dense_top_boundary
      } else {
        candidate <- candidate & ranking >= dense_top_boundary
      }
    }
    keep | candidate
  }

  if (inherits(source, "sparseMatrix")) {
    if (!isTRUE(Matrix::isSymmetric(source,
        tol = sqrt(.Machine$double.eps)))) {
      stop("An undirected adjacency matrix must be symmetric.", call. = FALSE)
    }
    upper <- methods::as(Matrix::triu(source, k = 1L), "CsparseMatrix")
    entries <- Matrix::summary(upper)
    from_index <- entries$i
    to_index <- entries$j
    values <- as.numeric(entries$x)
    keep <- retain_values(values)
    if (!any(keep)) {
      stop("No adjacency-matrix edges satisfy the import filters.",
        call. = FALSE)
    }
    return(data.frame(
      from = node_names[from_index[keep]],
      to = node_names[to_index[keep]],
      score = values[keep],
      stringsAsFactors = FALSE
    ))
  }

  # Scan dense matrices in bounded-memory blocks and columns. In particular,
  # do not construct the n-by-n logical matrix made by upper.tri(), its
  # two-column index matrix, a full transpose, or an unfiltered edge table.
  n_nodes <- dimensions[[1L]]
  retained_per_column <- integer(n_nodes)
  tolerance <- sqrt(.Machine$double.eps)

  block_size <- 512L
  block_starts <- seq.int(1L, n_nodes, by = block_size)
  for (row_block in seq_along(block_starts)) {
    row_start <- block_starts[[row_block]]
    rows <- seq.int(row_start, min(row_start + block_size - 1L, n_nodes))
    for (column_block in seq.int(row_block, length(block_starts))) {
      column_start <- block_starts[[column_block]]
      columns <- seq.int(column_start,
        min(column_start + block_size - 1L, n_nodes))
      upper_block <- as.matrix(source[rows, columns, drop = FALSE])
      lower_block <- t(as.matrix(source[columns, rows, drop = FALSE]))
      if (!identical(upper_block, lower_block) &&
          !isTRUE(all.equal(upper_block, lower_block,
            tolerance = tolerance, check.attributes = FALSE))) {
        stop(paste0(
          "An undirected adjacency matrix must be symmetric; mismatch in ",
          "the block beginning at nodes '", node_names[[row_start]],
          "' and '", node_names[[column_start]], "'."), call. = FALSE)
      }
    }
  }

  # Find a dense top-N selection boundary without retaining cell coordinates.
  # Partial sorting is performed on bounded chunks plus at most N candidates.
  # A later pass materializes values at the boundary when tie handling needs
  # them; strict tie handling can discard the boundary immediately.
  if (!is.null(n_top) || !is.null(n_abs_top)) {
    top_count <- as.integer(if (!is.null(n_abs_top)) n_abs_top else n_top)
    top_candidates <- numeric()
    top_buffer <- list()
    buffered <- 0L
    flush_top_buffer <- function() {
      if (!buffered) return(invisible(NULL))
      ranking <- c(top_candidates,
        unlist(top_buffer, recursive = FALSE, use.names = FALSE))
      if (length(ranking) > top_count) {
        boundary_position <- length(ranking) - top_count + 1L
        ranking <- sort.int(ranking, partial = boundary_position,
          na.last = NA)
        ranking <- ranking[seq.int(boundary_position, length(ranking))]
      }
      top_candidates <<- ranking
      top_buffer <<- list()
      buffered <<- 0L
      invisible(NULL)
    }
    if (n_nodes > 1L) {
      for (column in seq.int(2L, n_nodes)) {
        values <- as.numeric(source[seq_len(column - 1L), column])
        values <- values[is.finite(values) & values != 0]
        if (!length(values)) next
        if (!is.null(n_abs_top)) values <- abs(values)
        top_buffer[[length(top_buffer) + 1L]] <- values
        buffered <- buffered + length(values)
        if (buffered >= 1000000L) flush_top_buffer()
      }
    }
    flush_top_buffer()
    if (length(top_candidates) >= top_count) {
      dense_top_boundary <- min(top_candidates)
    } else {
      dense_top_boundary <- -Inf
    }
  }

  # Count first so the three edge columns can be allocated at their exact
  # retained size. This pass materializes only one matrix column at a time.
  if (n_nodes > 1L) {
    for (column in seq.int(2L, n_nodes)) {
      rows <- seq_len(column - 1L)
      upper_values <- as.numeric(source[rows, column])
      retained_per_column[[column]] <- sum(retain_values(upper_values))
    }
  }

  n_edges <- sum(retained_per_column)
  if (!n_edges) {
    stop("No adjacency-matrix edges satisfy the import filters.",
      call. = FALSE)
  }
  from <- character(n_edges)
  to <- character(n_edges)
  score <- numeric(n_edges)
  position <- 0L
  for (column in seq.int(2L, n_nodes)) {
    count <- retained_per_column[[column]]
    if (!count) next
    rows <- seq_len(column - 1L)
    upper_values <- as.numeric(source[rows, column])
    selected <- which(retain_values(upper_values))
    positions <- position + seq_len(count)
    from[positions] <- node_names[selected]
    to[positions] <- node_names[[column]]
    score[positions] <- upper_values[selected]
    position <- position + count
  }
  data.frame(
    from = from,
    to = to,
    score = score,
    stringsAsFactors = FALSE
  )
}

#' Import an undirected interaction network
#'
#' Read a global undirected network from a tabular edge list, import a square
#' adjacency matrix, or normalize a supported network object. Reciprocal and
#' duplicate edges are collapsed and self-links are removed. When scored
#' duplicate rows disagree, a warning reports their count and examples. The
#' highest edge score is retained, or the highest absolute score when an
#' absolute-value selector is used. The selected source edge-score column
#' becomes the single canonical igraph `weight` attribute or
#' adjacency-aligned legacy weights. In a user-supplied scored table, a source
#' score of zero is interpreted as no edge and skipped. Existing network
#' objects and curated adapters preserve zero edge weights.
#'
#' @param source File path, URL, connection, matrix, data frame, or supported
#'   network object.
#' @param species Required species identifier. Accepts any scientific/common
#'   name, package species ID, three-letter KEGG style organism ID, or
#'   taxonomy ID listed by [available_id_formats()]. Use explicit `NULL` only
#'   for unsupported species or non-biological data.
#' @param input_id_format Submitted identifier format. Defaults to
#'   [master_id_format()] for `species`; non-master input must name a format
#'   listed by [available_id_formats()]. Required when `species = NULL`.
#' @param id_mappings Optional object from [load_id_mappings()]. When supplied,
#'   both endpoints are converted to its species master format.
#' @param ambiguous,unmapped Mapping policies passed to [map_identifiers()].
#' @param from_column,to_column Names or one-based indices of edge endpoint
#'   columns.
#' @param score_column Optional name or one-based index of the source edge
#'   score column. Its numeric values are stored as edge weights. If `NULL`,
#'   imported edges are unweighted.
#' @param output_network_format Return an igraph, sparse, or legacy NEArender
#'   network.
#' @param min_score Optional minimum retained edge score.
#' @param min_abs_score Optional minimum retained absolute edge score. This is
#'   useful for signed adjacency matrices such as correlation matrices. The
#'   signed value is preserved as the edge weight.
#' @param n_top Optional number of highest-scoring unique edges to retain.
#' @param n_abs_top Optional number of unique edges with the highest absolute
#'   scores to retain. Signed edge weights are preserved. The `greedy`
#'   boundary-tie policy also applies to this option.
#'   Only one of `min_score`, `min_abs_score`, `n_top`, and `n_abs_top`
#'   may be supplied.
#' @param greedy Boundary-tie policy used with `n_top` or `n_abs_top`. The
#'   default, `TRUE`, includes every edge tied at the selection boundary;
#'   `FALSE` keeps only edges strictly above it; and `NULL` returns exactly
#'   the requested number of edges by filling the tie in alphanumeric
#'   canonical-endpoint order. Use `greedy = NULL` when equal network sizes
#'   are required for consistent benchmarks.
#' @param header Whether a text source has a header row. Ignored for a matrix or
#'   data frame.
#' @param sep Field separator used for text sources. Ignored for a matrix or
#'   data frame.
#' @param comment_char Comment marker used for text sources. The default
#'   disables comment processing. Ignored for a matrix or data frame.
#' @param is_matrix Treat `source` as a square undirected adjacency matrix
#'   rather than as a tabular edge list. Row and column names must be identical
#'   and non-empty, and the matrix must be symmetric. Its values become edge
#'   weights; the diagonal is ignored and zero off-diagonal entries are
#'   treated as absent edges. `from_column`, `to_column`, and `score_column`
#'   may be omitted or explicitly set to `NULL` in this mode.
#' @param case_sensitive Preserve case when matching node identifiers.
#' @param verbose Report the imported node and edge counts.
#' @details An edge weight is stored metadata; it is not automatically a
#'   transition probability. Renderers such as [rwr.render()] and
#'   [pagerank.render()] use topology alone unless `use_edge_weights = TRUE`.
#'   A transition probability is derived, when requested, by normalizing the
#'   non-negative outgoing edge weights.
#'
#'   NEArender does not create directed networks. With `is_matrix = TRUE`,
#'   `source` must therefore be a symmetric adjacency matrix. Asymmetric
#'   matrices are rejected rather than interpreted as directed networks.
#'   For dense matrices, edge-score filtering is applied while the matrix is
#'   scanned, so excluded cells are never materialized as edge rows. Top-N
#'   selection uses bounded chunks to determine its score boundary first.
#'   After a matrix import, temporary edge tables are collected. On Linux
#'   systems using glibc, free allocator pages are also returned to the
#'   operating system so repeated imports do not retain their peak RSS.
#'
#'   Pathway Commons aggregates interaction evidence from multiple curated
#'   resources and records supporting publications for most edges. The
#'   catalogued `pathwaycommons_hgnc` adapter derives a PubMed-count edge
#'   score: the number of distinct supporting publications plus a 0.5
#'   pseudocount. Relations without a linked PubMed record therefore remain
#'   edges with weight 0.5. With [load_network_database()],
#'   `min_score = 1.5` requires at least one publication and
#'   `min_score = 2.5` requires at least two.
#' @return A checked and normalized undirected igraph object by default, a
#'   sparse network, or a named-adjacency-list network. Weighted igraph output
#'   has one numeric `weight` edge attribute; sparse output stores binary
#'   `adjacency` separately from `weights`; legacy output stores named
#'   adjacency-aligned `weights`. Identifier and repair metadata are available
#'   through [normalization_info()].
#' @seealso [available_databases()], [load_network_database()], [read_network()],
#'   [export_network()], [convert_network()]
#' @export
#' @examples
#' edges <- data.frame(from = c("A", "B", "B"), to = c("B", "A", "C"),
#'   score = c(0.8, 0.9, 0.7))
#' import_network(edges, "from", "to", "score", verbose = FALSE,
#'   species = "human")
#' correlation <- matrix(c(0, 0.8, -0.4, 0.8, 0, 0.2, -0.4, 0.2, 0),
#'   nrow = 3, dimnames = list(c("A", "B", "C"), c("A", "B", "C")))
#' import_network(correlation, is_matrix = TRUE, min_abs_score = 0.4,
#'   verbose = FALSE, species = NULL, input_id_format = "custom")
#' import_network(correlation, is_matrix = TRUE, n_abs_top = 2,
#'   greedy = NULL, verbose = FALSE, species = NULL,
#'   input_id_format = "custom")
import_network <- function(source, from_column = 1L, to_column = 2L,
    score_column = NULL, min_score = NULL, n_top = NULL, greedy = TRUE,
    header = FALSE,
    sep = "\t", comment_char = "", case_sensitive = FALSE, verbose = TRUE,
    output_network_format = c("igraph", "sparse", "legacy"),
    species, input_id_format = master_id_format(species), id_mappings = NULL,
    ambiguous = c("error", "drop", "first", "expand"),
    unmapped = c("keep", "drop", "error"), is_matrix = FALSE,
    min_abs_score = NULL, n_abs_top = NULL) {
  .assert_flag(case_sensitive, "case_sensitive")
  .assert_flag(verbose, "verbose")
  .assert_flag(is_matrix, "is_matrix")
  from_column_supplied <- !missing(from_column)
  to_column_supplied <- !missing(to_column)
  score_column_supplied <- !missing(score_column)
  zero_score_is_edge <- isTRUE(attr(source,
    "nearender_zero_score_is_edge", exact = TRUE))
  ambiguous <- match.arg(ambiguous)
  unmapped <- match.arg(unmapped)
  identity <- .resolve_input_identity(species, input_id_format, id_mappings)
  output_network_format <- match.arg(output_network_format)

  if (is_matrix) {
    if ((from_column_supplied && !is.null(from_column)) ||
        (to_column_supplied && !is.null(to_column)) ||
        (score_column_supplied && !is.null(score_column))) {
      stop(paste0("from_column, to_column, and score_column must be NULL or ",
        "omitted when is_matrix = TRUE."), call. = FALSE)
    }
    .validate_network_filters(min_score, n_top, "score", min_abs_score,
      n_abs_top)
    .validate_greedy(greedy)
    source <- .adjacency_matrix_edge_table(source,
      min_score = min_score, min_abs_score = min_abs_score, n_top = n_top,
      n_abs_top = n_abs_top, greedy = greedy)
    from_column <- "from"
    to_column <- "to"
    score_column <- "score"
    zero_score_is_edge <- FALSE
  }

  is_network_object <- igraph::is_igraph(source) ||
    inherits(source, c("nearender_indexed_network", "Matrix")) ||
    (is.list(source) && !is.null(source$links))
  if (is_network_object) {
    zero_score_is_edge <- TRUE
    existing_identity <- .identifier_metadata(source)
    if (!is.null(existing_identity) &&
        (!identical(existing_identity$species_id, identity$species_id) ||
         !identical(existing_identity$output_id_format,
           identity$input_id_format))) {
      stop("Declared species or input_id_format conflicts with the source network metadata.",
        call. = FALSE)
    }
    source <- as_igraph_network(source, case_sensitive)
    source <- igraph::as_data_frame(source, what = "edges")
    from_column <- 1L
    to_column <- 2L
    if (is.null(score_column) && "weight" %in% names(source)) {
      score_column <- "weight"
    }
  }
  .validate_network_filters(min_score, n_top, score_column, min_abs_score,
    n_abs_top)
  table <- .read_nearender_table(source, header, sep, comment_char)
  if (!is.null(id_mappings)) {
    from_position <- .resolve_import_column(table, from_column, "from_column")
    to_position <- .resolve_import_column(table, to_column, "to_column")
    mapped <- .map_network_table(table, from_position, to_position, identity,
      id_mappings, ambiguous, unmapped, case_sensitive)
    table <- mapped$table
    identity$mapping$from_statistics <- mapped$from_statistics
    identity$mapping$to_statistics <- mapped$to_statistics
  }
  edges <- .canonical_network_edges(table, from_column, to_column,
    score_column, min_score, n_top, greedy, case_sensitive,
    zero_score_is_edge = zero_score_is_edge,
    min_abs_score = min_abs_score, n_abs_top = n_abs_top)
  graph <- .igraph_network_from_edges(edges, case_sensitive)
  result <- switch(output_network_format,
    igraph = graph,
    sparse = index_sparse_network(graph, preserve_weights = TRUE),
    legacy = .legacy_network_from_edges(edges, case_sensitive))
  if (verbose) message("Network of ", nrow(edges), " edges between ",
    length(unique(c(edges$from, edges$to))), " nodes.")
  result <- .attach_identifier_metadata(result, identity)
  if (is_matrix) {
    rm(source, table, edges, graph)
    .release_unused_matrix_memory()
  }
  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.