R/network-combine.R

Defines functions merge_networks reduce_network .network_source_record .network_score_format .network_from_combined_edges .network_edges_for_combination .resolve_merge_condition .resolve_reduction_selection .resolve_network_case_policy .network_input_format

Documented in merge_networks reduce_network

# Network reduction and merging with score and provenance safeguards.

.network_input_format <- function(network) {
  if (igraph::is_igraph(network)) return("igraph")
  if (inherits(network, c("nearender_indexed_network", "Matrix"))) {
    return("sparse")
  }
  "legacy"
}

.resolve_network_case_policy <- function(networks, case_sensitive) {
  if (!is.null(case_sensitive)) {
    .assert_flag(case_sensitive, "case_sensitive")
    return(case_sensitive)
  }
  policies <- vapply(networks, function(network) {
    metadata <- .normalization_metadata(network)
    if (is.list(metadata) && identical(metadata$normalized, TRUE) &&
        is.logical(metadata$case_sensitive) &&
        length(metadata$case_sensitive) == 1L) {
      metadata$case_sensitive
    } else {
      NA
    }
  }, logical(1))
  known <- unique(policies[!is.na(policies)])
  # Case-insensitive normalization is the only lossless common policy when
  # recorded inputs disagree.  Harmonize silently rather than making callers
  # re-import otherwise compatible networks.
  if (length(known) > 1L) return(FALSE)
  if (length(known)) known[[1L]] else FALSE
}

.resolve_reduction_selection <- function(select) {
  defaults <- list(min_score = NULL, n_top = NULL, random = FALSE)
  if (!is.list(select) || is.null(names(select)) ||
      any(!nzchar(names(select))) || anyDuplicated(names(select)) ||
      any(!names(select) %in% names(defaults))) {
    stop("select must be a named list containing only min_score, n_top, and random.",
      call. = FALSE)
  }
  defaults[names(select)] <- select
  select <- defaults
  .assert_flag(select$random, "select$random")
  if (is.null(select$min_score) == is.null(select$n_top)) {
    stop("select must specify exactly one of min_score and n_top.",
      call. = FALSE)
  }
  if (select$random && is.null(select$n_top)) {
    stop("select$random = TRUE requires select$n_top.", call. = FALSE)
  }
  .validate_network_filters(select$min_score, select$n_top, "score")
  select
}

.resolve_merge_condition <- function(condition, n_networks) {
  if (is.character(condition) && length(condition) == 1L &&
      !is.na(condition)) {
    condition <- tolower(condition)
    if (identical(condition, "union")) return(1L)
    if (identical(condition, "intersection")) return(as.integer(n_networks))
  }
  if (is.numeric(condition) && length(condition) == 1L &&
      !is.na(condition) && is.finite(condition) &&
      condition == as.integer(condition) && condition >= 1L &&
      condition <= n_networks) {
    return(as.integer(condition))
  }
  stop("condition must be 'union', 'intersection', or an integer from 1 to the number of networks.",
    call. = FALSE)
}

.network_edges_for_combination <- function(network, case_sensitive) {
  graph <- as_igraph_network(network, case_sensitive)
  edges <- igraph::as_data_frame(graph, what = "edges")
  keep <- c("from", "to",
    if ("weight" %in% names(edges)) "weight")
  edges <- edges[, keep, drop = FALSE]
  if ("weight" %in% names(edges)) {
    names(edges)[names(edges) == "weight"] <- "score"
  }
  edges
}

.network_from_combined_edges <- function(edges, output_network_format,
    case_sensitive, metadata_source) {
  result <- switch(output_network_format,
    igraph = .igraph_network_from_edges(edges, case_sensitive),
    sparse = index_sparse_network(
      .igraph_network_from_edges(edges, case_sensitive),
      preserve_weights = "score" %in% names(edges)),
    legacy = .legacy_network_from_edges(edges, case_sensitive)
  )
  .copy_identifier_metadata(result, metadata_source)
}

.network_score_format <- function(network) {
  source_manifest <- manifest(network)
  if (!is.list(source_manifest)) return(NULL)
  declared <- source_manifest$score_format
  if (is.character(declared) && length(declared) == 1L &&
      !is.na(declared) && nzchar(declared)) {
    return(declared)
  }
  semantics <- source_manifest$score_semantics
  source_column <- source_manifest$source_score_column
  if ((!is.character(semantics) || length(semantics) != 1L ||
      is.na(semantics) || !nzchar(semantics)) &&
      is.list(source_manifest$score)) {
    semantics <- source_manifest$score$name
    source_column <- source_manifest$score$source_column
  }
  if (!is.character(semantics) || length(semantics) != 1L ||
      is.na(semantics) || !nzchar(semantics)) {
    return(NULL)
  }
  if (is.character(source_column) && length(source_column) == 1L &&
      !is.na(source_column) && nzchar(source_column)) {
    paste0(semantics, " [source: ", source_column, "]")
  } else {
    semantics
  }
}

.network_source_record <- function(name, network, case_sensitive) {
  graph <- as_igraph_network(network, case_sensitive)
  list(
    name = name,
    node_count = igraph::vcount(graph),
    edge_count = igraph::ecount(graph),
    manifest = manifest(network)
  )
}

#' Reduce a scored network
#'
#' Retain edges from a scored network using either a minimum score or a top-edge
#' rule. Source edge weights and identifier metadata are preserved, and the
#' returned object's [manifest()] records the filter and source provenance.
#'
#' @param net A supported weighted network object.
#' @param select Named selection list with `min_score`, `n_top`, and `random`.
#'   Specify either `min_score`, or `n_top`. With `n_top`, set `random = TRUE`
#'   to sample that many unique edges instead of ranking them by score.
#' @param greedy Boundary-tie policy used with `n_top`. The default, `TRUE`,
#'   includes all edges tied at the boundary and can exceed `n_top`.
#'   `FALSE` excludes the whole boundary tie and can return fewer edges.
#'   `NULL` returns exactly `n_top` edges, resolving a boundary tie by
#'   alphanumeric canonical-endpoint order. Strict `greedy = NULL` selection
#'   is useful for size-matched network benchmarks.
#' @param output_network_format Output representation. `"same"` preserves the
#'   input representation.
#' @param case_sensitive Identifier case policy. By default, reuse the recorded
#'   policy of `net`, or use case-insensitive matching for an unmarked object.
#' @return A reduced network with a transformation provenance manifest.
#' @seealso [merge_networks()], [load_network_database()], [manifest()]
#' @examples
#' edges <- data.frame(from = c("A", "A", "B", "C"),
#'   to = c("B", "C", "C", "D"), score = c(5, 4, 4, 2))
#' network <- import_network(edges, score_column = "score", species = NULL,
#'   input_id_format = "custom", verbose = FALSE)
#' reduce_network(network, select = list(n_top = 2))
#' @export
reduce_network <- function(net,
    select = list(min_score = NULL, n_top = NULL, random = FALSE),
    greedy = TRUE,
    output_network_format = c("same", "igraph", "sparse", "legacy"),
    case_sensitive = NULL) {
  output_network_format <- match.arg(output_network_format)
  select <- .resolve_reduction_selection(select)
  .validate_greedy(greedy)
  case_sensitive <- .resolve_network_case_policy(list(net), case_sensitive)
  if (output_network_format == "same") {
    output_network_format <- .network_input_format(net)
  }

  edges <- .network_edges_for_combination(net, case_sensitive)
  if (!"score" %in% names(edges)) {
    stop("net must contain numeric edge weights for reduction.", call. = FALSE)
  }
  original_edge_count <- nrow(edges)
  canonical_edges <- .canonical_network_edges(edges, "from", "to", "score",
    case_sensitive = case_sensitive, warn_repairs = FALSE,
    zero_score_is_edge = TRUE)
  if (select$random) {
    if (select$n_top > nrow(canonical_edges)) {
      stop("select$n_top cannot exceed the number of unique edges.",
        call. = FALSE)
    }
    reduced_edges <- canonical_edges[sort(sample.int(
      nrow(canonical_edges), select$n_top)), , drop = FALSE]
  } else {
    reduced_edges <- .canonical_network_edges(canonical_edges, "from", "to",
      "score", min_score = select$min_score, n_top = select$n_top,
      greedy = greedy, case_sensitive = case_sensitive,
      warn_repairs = FALSE, zero_score_is_edge = TRUE)
  }
  result <- .network_from_combined_edges(reduced_edges,
    output_network_format, case_sensitive, net)

  source_manifest <- manifest(net)
  result_manifest <- list(
    type = "network",
    operation = "reduce_network",
    source = .network_source_record("net", net, case_sensitive),
    select = select,
    selection_mode = if (select$random) "random" else if (
      !is.null(select$n_top)) "top" else "minimum_score",
    filters = c(select, list(greedy = greedy)),
    score_preserved = TRUE,
    score_format = .network_score_format(net),
    input_edge_count = original_edge_count,
    node_count = .network_node_count(result),
    edge_count = .network_edge_count(result),
    output_network_format = output_network_format,
    case_sensitive = case_sensitive
  )
  if (is.list(source_manifest) && length(source_manifest$transformations)) {
    result_manifest$prior_transformations <- source_manifest$transformations
  }
  attr(result, "nearender_manifest") <- result_manifest
  result
}

#' Merge network topologies
#'
#' Combine the edge unions of two or more networks after checking identifier
#' compatibility. Edge scores are omitted by default. They can be retained only
#' by explicit request when every input is weighted and their recorded score
#' formats are compatible. Duplicate scored edges retain the maximum score.
#'
#' @param nets Named list containing at least two supported network objects.
#' @param preserve_scores Preserve compatible input edge scores. The default,
#'   `FALSE`, creates an unweighted network.
#' @param score_format Optional explicit score-format declaration. This is
#'   required with `preserve_scores = TRUE` when any scored input lacks score
#'   provenance. It does not override conflicting recorded formats.
#' @param output_network_format Output representation.
#' @param condition Edge-presence rule: `"union"`, `"intersection"`, or an
#'   integer giving the minimum number of distinct input networks in which an
#'   edge must occur.
#' @param case_sensitive Identifier case policy. By default, reuse the common
#'   recorded policy of the inputs, or use case-insensitive matching when none
#'   is recorded.
#' @return A merged network whose [manifest()] records all sources, score
#'   handling, and output counts.
#' @seealso [reduce_network()], [network_overlap()], [manifest()]
#' @examples
#' first <- import_network(data.frame(from = c("A", "B"), to = c("B", "C")),
#'   species = NULL, input_id_format = "custom", verbose = FALSE)
#' second <- import_network(data.frame(from = "C", to = "D"),
#'   species = NULL, input_id_format = "custom", verbose = FALSE)
#' merge_networks(list(first = first, second = second))
#' @export
merge_networks <- function(nets, preserve_scores = FALSE,
    score_format = NULL,
    condition = "union",
    output_network_format = c("igraph", "sparse", "legacy"),
    case_sensitive = NULL) {
  .assert_flag(preserve_scores, "preserve_scores")
  output_network_format <- match.arg(output_network_format)
  if (!is.list(nets) || length(nets) < 2L || is.null(names(nets)) ||
      anyNA(names(nets)) || any(!nzchar(names(nets))) ||
      anyDuplicated(names(nets))) {
    stop("nets must be a named list of at least two networks with unique, non-empty names.",
      call. = FALSE)
  }
  if (!is.null(score_format) &&
      (!is.character(score_format) || length(score_format) != 1L ||
       is.na(score_format) || !nzchar(score_format))) {
    stop("score_format must be NULL or one non-empty character value.",
      call. = FALSE)
  }
  if (!preserve_scores && !is.null(score_format)) {
    stop("score_format is used only when preserve_scores = TRUE.",
      call. = FALSE)
  }

  do.call(.assert_compatible_identifiers, nets)
  case_sensitive <- .resolve_network_case_policy(nets, case_sensitive)
  minimum_networks <- .resolve_merge_condition(condition, length(nets))
  edge_tables <- lapply(nets, .network_edges_for_combination,
    case_sensitive = case_sensitive)
  weighted <- vapply(edge_tables, function(edges) {
    "score" %in% names(edges)
  }, logical(1))

  resolved_score_format <- NULL
  if (preserve_scores) {
    if (!all(weighted)) {
      stop("preserve_scores = TRUE requires weights in every input network.",
        call. = FALSE)
    }
    formats <- lapply(nets, .network_score_format)
    known <- unlist(formats[!vapply(formats, is.null, logical(1))],
      use.names = FALSE)
    if (length(unique(known)) > 1L) {
      detail <- paste0(names(nets)[!vapply(formats, is.null, logical(1))],
        "=", known, collapse = "; ")
      stop("Input edge-score formats are incompatible: ", detail, ".",
        call. = FALSE)
    }
    if (any(vapply(formats, is.null, logical(1))) &&
        is.null(score_format)) {
      stop("Score provenance is missing for one or more inputs; supply an explicit score_format or set preserve_scores = FALSE.",
        call. = FALSE)
    }
    if (!is.null(score_format) && length(known) &&
        !identical(score_format, known[[1L]])) {
      stop("score_format conflicts with recorded input score provenance: ",
        known[[1L]], ".", call. = FALSE)
    }
    resolved_score_format <- if (is.null(score_format)) known[[1L]] else {
      score_format
    }
  }

  canonical_tables <- lapply(edge_tables, function(edges) {
    .canonical_network_edges(edges, "from", "to",
      score_column = if ("score" %in% names(edges)) "score" else NULL,
      case_sensitive = case_sensitive, warn_repairs = FALSE,
      zero_score_is_edge = TRUE)
  })
  presence <- do.call(rbind, Map(function(edges, source) {
    data.frame(from = edges$from, to = edges$to, source = source,
      stringsAsFactors = FALSE)
  }, canonical_tables, seq_along(canonical_tables)))
  multiplicity <- stats::aggregate(source ~ from + to, presence,
    function(x) length(unique(x)))
  names(multiplicity)[[3L]] <- "network_count"

  combined <- do.call(rbind, lapply(canonical_tables, function(edges) {
    edges[, c("from", "to", if (preserve_scores) "score"), drop = FALSE]
  }))
  merged_edges <- .canonical_network_edges(combined, "from", "to",
    score_column = if (preserve_scores) "score" else NULL,
    case_sensitive = case_sensitive, warn_repairs = FALSE,
    zero_score_is_edge = TRUE)
  counts <- multiplicity$network_count[match(
    paste(merged_edges$from, merged_edges$to, sep = "\r"),
    paste(multiplicity$from, multiplicity$to, sep = "\r"))]
  merged_edges <- merged_edges[counts >= minimum_networks, , drop = FALSE]
  result <- .network_from_combined_edges(merged_edges,
    output_network_format, case_sensitive, nets[[1L]])

  attr(result, "nearender_manifest") <- list(
    type = "network",
    operation = "merge_networks",
    sources = Map(function(name, network) {
      .network_source_record(name, network, case_sensitive)
    }, names(nets), nets),
    preserve_scores = preserve_scores,
    condition = condition,
    minimum_networks = minimum_networks,
    score_format = resolved_score_format,
    duplicate_edge_aggregation = if (preserve_scores) "maximum" else NA_character_,
    node_count = .network_node_count(result),
    edge_count = .network_edge_count(result),
    output_network_format = output_network_format,
    case_sensitive = case_sensitive
  )
  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.