Nothing
# Author-released network resources used for comparative network analyses.
.author_network_specs <- function() {
make <- function(id, scope, context, modality, url, parser = "table",
from = 1L, to = 2L, score = 3L, header = FALSE,
id_format = "entrezgene_id", sep = "\t", large = FALSE,
md5 = NULL, publication = "", status = "published") {
list(id = id, comprehensive = identical(scope, "comprehensive"),
scope = scope, context = context, modality = modality, url = url,
parser = parser, from = from, to = to, score = score, header = header,
id_format = id_format, sep = sep, large = large, md5 = md5,
publication = publication, publication_status = status)
}
specs <- list(
make("funcoup6", "comprehensive", "global", "multiple evidence classes",
"https://funcoup.org/download/network%26FC6.0_H.sapiens_compact.gz",
from = "0:ProteinA", to = "1:ProteinB", score = "6:FBS_max",
header = TRUE, id_format = "uniprotswissprot",
md5 = "0865ae8ecd8f0bc3340f6e8d5bc000e0",
publication = "https://doi.org/10.1093/nar/gkae1021"),
make("string11", "comprehensive", "global",
"multiple evidence classes; historical pre-BioBERT baseline",
"https://stringdb-downloads.org/download/protein.links.v11.0/9606.protein.links.v11.0.txt.gz",
parser = "string", header = TRUE, sep = " ",
id_format = "ensembl_peptide_id",
publication = "https://doi.org/10.1093/nar/gky1131"),
make("string115", "comprehensive", "global",
"multiple evidence classes; includes BioBERT-era text mining",
"https://stringdb-downloads.org/download/protein.links.v11.5/9606.protein.links.v11.5.txt.gz",
parser = "string", header = TRUE, sep = " ",
id_format = "ensembl_peptide_id",
publication = "https://doi.org/10.1093/nar/gkaa1074"),
make("string12", "comprehensive", "global", "multiple evidence classes",
"https://stringdb-downloads.org/download/protein.links.v12.0/9606.protein.links.v12.0.txt.gz",
parser = "string", header = TRUE, sep = " ",
id_format = "ensembl_peptide_id",
md5 = "5b7c91d02926e723ad30e81ab9d009a4",
publication = "https://doi.org/10.1093/nar/gkac1000"),
make("string125", "comprehensive", "global", "multiple evidence classes",
"https://stringdb-downloads.org/download/protein.links.v12.5/9606.protein.links.v12.5.txt.gz",
parser = "string", header = TRUE, sep = " ",
id_format = "ensembl_peptide_id",
publication = "https://doi.org/10.1093/nar/gkae1113"),
make("genemania2021", "comprehensive", "global", "multiple evidence classes",
"https://genemania.org/data/archive/2021-04-19/Homo_sapiens.COMBINED/COMBINED.DEFAULT_NETWORKS.BP_COMBINING.txt",
parser = "genemania", from = "Gene_A", to = "Gene_B",
score = "Weight", header = TRUE, id_format = "genemania_preferred",
large = TRUE, md5 = "f527d7c1a6b3fe5bfb9994f4ce5c5328",
publication = "https://pages.genemania.org/data/"),
make("humannet3_fn", "comprehensive", "global",
"multiple evidence classes, no co-citation extension",
"https://www.inetbio.org/humannetv3/networks/HumanNet-FN.tsv.gz",
md5 = "071c4f7c4952fa0ba6d300361f94919c",
publication = "https://doi.org/10.1093/nar/gkab1048"),
make("humannet3_xc", "comprehensive", "global",
"multiple evidence classes plus co-citation",
"https://www.inetbio.org/humannetv3/networks/HumanNet-XC.tsv.gz",
publication = "https://doi.org/10.1093/nar/gkab1048"),
make("pcnet2_1", "comprehensive", "global",
"consensus of broad source networks",
"https://public.ndexbio.org/v2/network/e9c574f4-e87a-11ee-9621-005056ae23aa",
parser = "ndex", score = NULL, large = TRUE,
publication = "https://doi.org/10.1038/s44320-024-00077-y"),
make("pcnet2_2", "comprehensive", "global",
"consensus; excludes text-only evidence as defined by authors",
"https://public.ndexbio.org/v2/network/8b4b54fa-e87d-11ee-9621-005056ae23aa",
parser = "ndex", score = NULL, large = TRUE,
publication = "https://doi.org/10.1038/s44320-024-00077-y"),
make("humanbase_giant_global", "comprehensive", "global",
"multiple genomic evidence classes",
"https://s3-us-west-2.amazonaws.com/humanbase/networks/global_top.gz",
large = TRUE, publication = "https://doi.org/10.1038/ng.3259"),
make("humanbase_mage_global", "comprehensive", "global",
"multiple genomic evidence classes",
"https://s3-us-west-2.amazonaws.com/humanbase/networks/v3/global.dat.gz",
large = TRUE,
status = "author network release; MAGE-specific paper not independently verified",
publication = "https://humanbase.readthedocs.io/en/latest/functional-networks.html"),
make("fava", "restricted", "pooled human",
"single-cell RNA and bulk proteomics",
"https://zenodo.org/records/6803472/files/Fava_Network_SingleCells_Proteomics_CombinedScores_Over15percent.tsv.gz?download=1",
parser = "string", id_format = "ensembl_peptide_id",
md5 = "f82dc31324f23c0426d7fc25f94168f1",
publication = "https://doi.org/10.1093/bioinformatics/btae010"),
make("funmap_native", "restricted", "pan-cancer", "RNA and proteomics",
"https://funmap.linkedomics.org/data/download/funmap.tsv",
score = NULL, id_format = "hgnc_symbol",
md5 = "0ef7076d31902b65d808c1957562d2f2",
publication = "https://doi.org/10.1038/s43018-024-00869-z"),
make("funmap_scores", "restricted", "pan-cancer", "RNA and proteomics",
"https://zenodo.org/records/10080764/files/all_pair_prediction_score.tsv.gz?download=1",
parser = "funmap_scores", header = TRUE, score = "ALL_RNA_PRO",
id_format = "ensembl_gene_id", large = TRUE,
publication = "https://zenodo.org/records/10080764"),
make("intact_native", "restricted", "pooled human",
"experimentally curated molecular interactions",
"https://ftp.ebi.ac.uk/pub/databases/intact/current/psimitab/species/human.zip",
parser = "intact", score = NULL, header = TRUE,
id_format = "uniprotswissprot", large = TRUE,
publication = "https://www.ebi.ac.uk/intact/download"),
make("bioplex293t", "restricted", "HEK293T", "AP-MS physical association",
"https://bioplex.hms.harvard.edu/data/BioPlex_293T_Network_10K_Dec_2019.tsv",
from = "GeneA", to = "GeneB", score = "pInt", header = TRUE,
md5 = "3e4d18a9da218583ceff95a0bd1dada3",
publication = "https://doi.org/10.1016/j.cell.2021.04.011"),
make("bioplexhct116", "restricted", "HCT116", "AP-MS physical association",
"https://bioplex.hms.harvard.edu/data/BioPlex_HCT116_Network_5.5K_Dec_2019.tsv",
from = "GeneA", to = "GeneB", score = "pInt", header = TRUE,
md5 = "25877d33ce9c551df82c0b87c3c965ab",
publication = "https://doi.org/10.1016/j.cell.2021.04.011"),
make("huri", "restricted", "human ORFeome",
"binary physical interaction, Y2H",
"https://interactome-atlas.org/data/HuRI.tsv", score = NULL,
id_format = "ensembl_gene_id",
publication = "https://doi.org/10.1038/s41586-020-2188-x")
)
stats::setNames(specs, vapply(specs, `[[`, character(1), "id"))
}
#' Describe a released STRING evidence channel
#'
#' @param channel STRING evidence-channel column.
#' @param version Supported STRING release.
#' @param network_type Functional or physical STRING network.
#' @return A resource specification accepted by [prepare_resource()].
#' @export
string_channel_spec <- function(channel = "textmining", version = "12.0",
network_type = c("functional", "physical")) {
network_type <- match.arg(network_type)
versions <- c("11.0", "11.5", "12.0", "12.5")
channels <- c("textmining", "textmining_transferred", "coexpression",
"experiments", "database", "neighborhood", "fusion", "cooccurence")
if (!version %in% versions || !channel %in% channels) {
stop("Unsupported STRING release or evidence channel.", call. = FALSE)
}
if (network_type == "physical" && (version == "11.0" ||
!channel %in% c("textmining", "textmining_transferred", "experiments",
"database"))) {
stop("This physical network/channel combination is not in the verified release set.",
call. = FALSE)
}
base_id <- c(`11.0` = "string11", `11.5` = "string115",
`12.0` = "string12", `12.5` = "string125")[[version]]
spec <- .author_network_specs()[[base_id]]
spec$id <- paste0("string", version, "_", network_type, "_", channel)
spec$scope <- "restricted"; spec$comprehensive <- FALSE
spec$modality <- paste("STRING author", network_type, "channel", channel)
kind <- if (network_type == "physical") {
"protein.physical.links.full"
} else "protein.links.full"
spec$url <- paste0("https://stringdb-downloads.org/download/", kind, ".v",
version, "/9606.", kind, ".v", version, ".txt.gz")
spec$from <- "protein1"; spec$to <- "protein2"; spec$score <- channel
spec$md5 <- NULL; spec$large <- TRUE
spec
}
#' Describe a tissue-specific HumanBase network
#'
#' @param tissue HumanBase tissue name.
#' @param version GIANT or MAGE network generation.
#' @return A resource specification accepted by [prepare_resource()].
#' @export
humanbase_spec <- function(tissue, version = c("giant", "mage")) {
version <- match.arg(version)
if (!is.character(tissue) || length(tissue) != 1L || is.na(tissue) ||
!nzchar(tissue)) stop("tissue must be one non-empty string.", call. = FALSE)
spec <- .author_network_specs()[[paste0("humanbase_", version, "_global")]]
slug <- tolower(gsub(" ", "_", tissue, fixed = TRUE))
if (!grepl("^[a-z0-9_-]+$", slug)) stop("tissue contains unsupported characters.",
call. = FALSE)
spec$id <- paste0("humanbase_", version, "_", slug)
spec$context <- tissue
spec$url <- paste0("https://s3-us-west-2.amazonaws.com/humanbase/networks/",
if (version == "mage") "v3/" else "", slug,
if (version == "mage") ".dat.gz" else "_top.gz")
spec
}
.resolve_author_network_spec <- function(id) {
if (is.list(id)) return(id)
if (!is.character(id) || length(id) != 1L || is.na(id) || !nzchar(id)) {
stop("id must be a resource identifier or specification.", call. = FALSE)
}
spec <- .author_network_specs()[[id]]
if (!is.null(spec)) return(spec)
match <- regmatches(id, regexec(
"^string(11\\.0|11\\.5|12\\.0|12\\.5)_(functional|physical)_(.+)$", id))[[1L]]
if (length(match) == 4L) return(string_channel_spec(match[[4L]], match[[2L]],
match[[3L]]))
stop("Unknown resource: ", id, call. = FALSE)
}
#' List author-released network resources
#'
#' This catalog complements [available_databases()] with network releases used
#' for comparative benchmarking, including registered NDEx snapshots.
#' @return A data frame with one row per resource.
#' @seealso [download_resource()], [prepare_resource()]
#' @export
network_catalog <- function() {
extras <- c(lapply(c("11.0", "11.5", "12.0", "12.5"), function(version) {
string_channel_spec("textmining", version, "functional")
}), lapply(c("11.5", "12.0", "12.5"), function(version) {
string_channel_spec("textmining", version, "physical")
}))
do.call(rbind, lapply(c(.author_network_specs(), extras), function(spec) {
data.frame(id = spec$id, comprehensive = spec$comprehensive,
scope = spec$scope, context = spec$context, modality = spec$modality,
ranked = !is.null(spec$score), author_network = TRUE,
source_identifier = spec$id_format, large_download = spec$large,
context_global = identical(spec$context, "global"),
publication_status = spec$publication_status,
publication = spec$publication, download_url = spec$url,
stringsAsFactors = FALSE)
}))
}
.fetch_author_resource <- function(url, path, expected_md5 = NULL,
quiet = FALSE) {
dir.create(dirname(path), recursive = TRUE, showWarnings = FALSE)
if (!file.exists(path)) {
temporary <- paste0(path, ".partial")
on.exit(if (file.exists(temporary)) unlink(temporary), add = TRUE)
old_timeout <- getOption("timeout", 60)
options(timeout = max(old_timeout, 3600))
on.exit(options(timeout = old_timeout), add = TRUE)
.download_file_explicit(url, temporary, quiet, "author network resource")
if (!file.rename(temporary, path)) {
stop("Could not finalize the downloaded resource.", call. = FALSE)
}
}
actual <- unname(tools::md5sum(path))
if (!is.null(expected_md5) &&
!identical(tolower(actual), tolower(expected_md5))) {
stop("MD5 mismatch for ", path, ".", call. = FALSE)
}
invisible(path)
}
#' Download an author-released network resource
#'
#' Downloads occur only when this function, or [prepare_resource()], is called
#' explicitly. Files are cached below the supplied directory.
#' @param spec Resource identifier from [network_catalog()] or a specification
#' returned by [string_channel_spec()] or [humanbase_spec()].
#' @param cache_dir Explicit cache root.
#' @param allow_large Confirm a catalog entry marked as a large download.
#' @param quiet Suppress download progress.
#' @return A named character vector of cached artifact paths, invisibly.
#' @export
download_resource <- function(spec, cache_dir, allow_large = FALSE,
quiet = FALSE) {
spec <- .resolve_author_network_spec(spec)
.assert_flag(allow_large, "allow_large"); .assert_flag(quiet, "quiet")
if (!is.character(cache_dir) || length(cache_dir) != 1L || is.na(cache_dir) ||
!nzchar(cache_dir)) stop("cache_dir must be one explicit path.", call. = FALSE)
if (isTRUE(spec$large) && !allow_large) {
stop("Large download: set allow_large = TRUE after reviewing its size.",
call. = FALSE)
}
root <- file.path(path.expand(cache_dir), spec$id)
if (identical(spec$parser, "ndex")) {
paths <- stats::setNames(file.path(root,
paste0(c("nodes", "edges", "summary"), ".json")),
c("nodes", "edges", "summary"))
for (aspect in names(paths)) {
suffix <- if (aspect == "summary") "/summary" else paste0("/aspect/", aspect)
.fetch_author_resource(paste0(spec$url, suffix), paths[[aspect]],
quiet = quiet)
}
return(invisible(paths))
}
filename <- basename(sub("\\?.*$", "", spec$url))
if (startsWith(filename, "network%26")) filename <- sub("^network%26", "", filename)
path <- file.path(root, filename)
.fetch_author_resource(spec$url, path, spec$md5, quiet)
if (identical(spec$parser, "genemania")) {
mapping <- file.path(root, "identifier_mappings.txt")
weights <- file.path(root,
"COMBINATION_WEIGHTS.DEFAULT_NETWORKS.BP_COMBINING.txt")
.fetch_author_resource(
"https://genemania.org/data/archive/2021-04-19/Homo_sapiens/identifier_mappings.txt",
mapping, "21daec9db1bf0494d38224f5f620f360", quiet)
.fetch_author_resource(
"https://genemania.org/data/archive/2021-04-19/Homo_sapiens.COMBINED/COMBINATION_WEIGHTS.DEFAULT_NETWORKS.BP_COMBINING.txt",
weights, "710167928aa5bfb63e86bebb58142f61", quiet)
return(invisible(c(network = path, identifier_mapping = mapping,
combination_weights = weights)))
}
if (identical(spec$parser, "intact")) {
entries <- utils::unzip(path, list = TRUE)$Name
selected <- entries[basename(entries) == "human.txt"]
if (length(selected) != 1L || grepl(
"(^/|^[A-Za-z]:|(^|[/\\\\])\\.\\.([/\\\\]|$))", selected)) {
stop("The IntAct archive does not contain one safe human.txt path.",
call. = FALSE)
}
utils::unzip(path, files = selected, exdir = root)
return(invisible(c(network = file.path(root, selected), archive = path)))
}
invisible(c(network = path))
}
.resource_id_mapper <- function(mappings, from) {
if (!inherits(mappings, "nearender_id_mappings")) {
stop("mappings must come from load_id_mappings().", call. = FALSE)
}
ids <- unique(mappings$mappings$source_id[mappings$mappings$id_format == from])
if (identical(from, mappings$manifest$master_id)) {
ids <- unique(c(ids, mappings$mappings$master_id))
}
ids <- ids[!is.na(ids) & nzchar(ids)]
mapped <- map_identifiers(stats::setNames(ids, ids), mappings, from = from,
ambiguous = "drop", unmapped = "drop", case_sensitive = TRUE)
lookup <- stats::setNames(as.character(mapped), names(mapped))
function(x) unname(lookup[x])
}
.resource_genemania_mapper <- function(path, symbol_mapper) {
mapping_table <- utils::read.delim(path, quote = "", check.names = FALSE,
colClasses = "character")
mapping_table <- unique(mapping_table[mapping_table$Source == "Gene Name",
c("Preferred_Name", "Name")])
counts <- table(mapping_table$Preferred_Name)
mapping_table <- mapping_table[
mapping_table$Preferred_Name %in% names(counts[counts == 1L]), ]
lookup <- stats::setNames(mapping_table$Name, mapping_table$Preferred_Name)
function(x) symbol_mapper(unname(lookup[x]))
}
.resource_canonical_edges <- function(table, n_top = NULL) {
weighted <- "score" %in% names(table)
keep <- !is.na(table$from) & !is.na(table$to) & nzchar(table$from) &
nzchar(table$to) & table$from != table$to
if (weighted) keep <- keep & is.finite(table$score)
table <- table[keep, , drop = FALSE]
if (!nrow(table)) return(table)
left <- pmin(table$from, table$to); right <- pmax(table$from, table$to)
table$from <- left; table$to <- right
order <- if (weighted) order(-table$score, left, right, method = "radix") else {
order(left, right, method = "radix")
}
table <- table[order, , drop = FALSE]
table <- table[!duplicated(paste(table$from, table$to, sep = "\r")), ,
drop = FALSE]
if (!is.null(n_top)) table <- utils::head(table, n_top)
rownames(table) <- NULL
table
}
.resource_split_lines <- function(lines, sep) {
if (identical(sep, " ")) strsplit(trimws(lines), "[[:space:]]+") else {
strsplit(lines, sep, fixed = TRUE)
}
}
.resource_parse_chunk <- function(lines, spec, header_names = NULL) {
fields <- .resource_split_lines(lines, spec$sep)
position <- function(value) if (is.character(value)) {
match(value, header_names)
} else as.integer(value)
extract <- function(index) vapply(fields, `[[`, character(1), index)
if (identical(spec$parser, "intact")) {
if (any(lengths(fields) < 36L)) stop("Incomplete IntAct MITAB row.", call. = FALSE)
keep <- grepl("taxid:9606([(|]|$)", extract(10L)) &
grepl("taxid:9606([(|]|$)", extract(11L)) &
grepl("MI:0326", extract(21L), fixed = TRUE) &
grepl("MI:0326", extract(22L), fixed = TRUE) &
tolower(extract(36L)) == "false" &
grepl("^uniprotkb:[^|]+$", extract(1L)) &
grepl("^uniprotkb:[^|]+$", extract(2L))
result <- data.frame(from = sub("^uniprotkb:", "", extract(1L)),
to = sub("^uniprotkb:", "", extract(2L)), stringsAsFactors = FALSE)
return(result[keep, , drop = FALSE])
}
score <- if (is.null(spec$score)) NULL else position(spec$score)
required <- c(position(spec$from), position(spec$to), score)
if (anyNA(required) || any(lengths(fields) < max(required))) {
stop("Source schema mismatch: ", spec$id, call. = FALSE)
}
if (identical(spec$parser, "funmap_scores")) {
tuples <- extract(1L)
matches <- regmatches(tuples,
regexec("^\\('([^']+)',[[:space:]]*'([^']+)'\\)$", tuples))
if (any(lengths(matches) != 3L)) {
stop("Unexpected author FunMap pair identifier.", call. = FALSE)
}
from <- vapply(matches, `[[`, character(1), 2L)
to <- vapply(matches, `[[`, character(1), 3L)
} else {
from <- extract(position(spec$from)); to <- extract(position(spec$to))
}
unquote <- function(x) sub('"$', "", sub('^"', "", x))
from <- unquote(from); to <- unquote(to)
if (identical(spec$parser, "string")) {
if (any(!grepl("^9606\\.", c(from, to)))) {
stop("Expected human taxon-prefixed protein IDs.", call. = FALSE)
}
from <- sub("^9606\\.", "", from); to <- sub("^9606\\.", "", to)
}
result <- data.frame(from = from, to = to, stringsAsFactors = FALSE)
if (!is.null(score)) {
result$score <- suppressWarnings(as.numeric(extract(score)))
if (any(!is.finite(result$score))) {
stop("Missing or non-numeric author score: ", spec$id, call. = FALSE)
}
}
result
}
.resource_stream_edges <- function(path, spec, mapper = identity,
n_top = NULL, universe = NULL, chunk_size = 100000L, min_score = NULL) {
if (!is.null(n_top) && (length(n_top) != 1L || !is.finite(n_top) ||
n_top < 1 || n_top != floor(n_top))) {
stop("n_top must be a positive integer.", call. = FALSE)
}
if (!is.null(n_top) && is.null(spec$score)) {
stop("Cannot rank unscored author edges.", call. = FALSE)
}
connection <- if (grepl("\\.gz$", path)) gzfile(path, "rt") else file(path, "rt")
on.exit(close(connection), add = TRUE)
headers <- if (spec$header) {
header <- .resource_split_lines(readLines(connection, n = 1L, warn = FALSE),
spec$sep)[[1L]]
sub('"$', "", sub('^"', "", header))
} else NULL
result <- data.frame(from = character(), to = character(),
stringsAsFactors = FALSE)
if (!is.null(spec$score)) result$score <- numeric()
rows_read <- filtered_rows <- mapping_lost <- self_rows <- 0L
repeat {
lines <- readLines(connection, n = chunk_size, warn = FALSE)
if (!length(lines)) break
lines <- lines[nzchar(lines) & !startsWith(lines, "#")]
rows_read <- rows_read + length(lines)
if (!length(lines)) next
table <- .resource_parse_chunk(lines, spec, headers)
filtered_rows <- filtered_rows + length(lines) - nrow(table)
table$from <- mapper(table$from); table$to <- mapper(table$to)
missing <- is.na(table$from) | is.na(table$to) |
!nzchar(table$from) | !nzchar(table$to)
mapping_lost <- mapping_lost + sum(missing)
self_rows <- self_rows + sum(!missing & table$from == table$to, na.rm = TRUE)
table <- table[!missing, , drop = FALSE]
if (!is.null(universe)) {
table <- table[table$from %in% universe & table$to %in% universe, ,
drop = FALSE]
}
if (!is.null(min_score)) {
if (is.null(spec$score)) stop("min_score requires an author score.",
call. = FALSE)
table <- table[table$score >= min_score, , drop = FALSE]
}
table <- .resource_canonical_edges(table, n_top)
result <- .resource_canonical_edges(rbind(result, table), n_top)
}
if (!nrow(result)) stop("No admissible edges remain.", call. = FALSE)
attr(result, "preprocessing") <- list(rows_read = rows_read,
source_filter_rows_lost = filtered_rows, mapping_rows_lost = mapping_lost,
mapping_self_rows = self_rows, retained_edges = nrow(result),
requested_edges = n_top,
shortfall = if (is.null(n_top)) 0 else max(0, n_top - nrow(result)),
selection_order = paste("map -> universe -> undirected unique pairs",
"(maximum) -> top K"),
tie_policy = "score descending, canonical endpoints ascending (radix)",
score_threshold = min_score)
result
}
.resource_read_ndex_edges <- function(paths, mapper = identity,
universe = NULL) {
nodes <- jsonlite::fromJSON(paths[["nodes"]])
edges <- jsonlite::fromJSON(paths[["edges"]])
if (!all(c("@id", "r") %in% names(nodes)) ||
!all(c("s", "t", "i") %in% names(edges))) {
stop("Unexpected NDEx CX aspect schema.", call. = FALSE)
}
if (any(edges$i != "interacts-with")) {
stop("Directed or typed NDEx relations cannot be flattened automatically.",
call. = FALSE)
}
if (any(!grepl("^ncbigene:[0-9]+$", nodes$r))) {
stop("Expected NCBI Gene node represents IDs.", call. = FALSE)
}
identifiers <- stats::setNames(sub("^ncbigene:", "", nodes$r),
as.character(nodes[["@id"]]))
result <- data.frame(
from = mapper(unname(identifiers[as.character(edges$s)])),
to = mapper(unname(identifiers[as.character(edges$t)])),
stringsAsFactors = FALSE)
if (!is.null(universe)) {
result <- result[result$from %in% universe & result$to %in% universe, ,
drop = FALSE]
}
.resource_canonical_edges(result)
}
#' Download, harmonize, and import an author-released network
#'
#' This high-level interface implements the resource workflow represented by
#' [network_catalog()]. It never runs implicitly: callers must provide an
#' explicit cache directory, and large resources require confirmation.
#' @param id Resource identifier or specification.
#' @param cache_dir Explicit cache root.
#' @param mappings Optional identifier mappings from [load_id_mappings()].
#' @param n_top Optional number of highest-scoring mapped edges.
#' @param allow_large Confirm a resource marked as a large download.
#' @param paths Optional named paths returned by [download_resource()].
#' @param universe Optional vector restricting both mapped endpoints.
#' @param mapper Optional endpoint mapping function, overriding `mappings`.
#' @param chunk_size Positive number of source rows parsed per chunk.
#' @param min_score Optional minimum author score.
#' @param quiet Suppress download progress.
#' @return An undirected igraph network with a provenance manifest available
#' through [manifest()].
#' @export
prepare_resource <- function(id, cache_dir, mappings = NULL, n_top = NULL,
allow_large = FALSE, paths = NULL, universe = NULL, mapper = NULL,
chunk_size = 100000L, min_score = NULL, quiet = FALSE) {
spec <- .resolve_author_network_spec(id)
if (!is.null(n_top) && is.null(spec$score)) {
stop("Use the complete published network for ", spec$id, call. = FALSE)
}
if (is.null(paths)) paths <- download_resource(spec, cache_dir, allow_large,
quiet)
mapped <- !is.null(mappings) || !is.null(mapper)
if (is.null(mapper)) {
if (is.null(mappings)) {
mapper <- identity
} else if (identical(spec$parser, "genemania")) {
mapper <- .resource_genemania_mapper(paths[["identifier_mapping"]],
.resource_id_mapper(mappings, "hgnc_symbol"))
} else {
mapper <- .resource_id_mapper(mappings, spec$id_format)
}
}
edges <- if (identical(spec$parser, "ndex")) {
.resource_read_ndex_edges(paths, mapper, universe)
} else {
.resource_stream_edges(paths[["network"]], spec, mapper, n_top, universe,
chunk_size, min_score)
}
if (!is.null(n_top) && nrow(edges) != n_top) {
warning("Top-K shortfall; do not treat this as a size-matched result: ",
spec$id, call. = FALSE)
}
import_format <- if (mapped) "hgnc_symbol" else spec$id_format
graph_edges <- edges
if ("score" %in% names(graph_edges)) {
names(graph_edges)[names(graph_edges) == "score"] <- "weight"
}
graph <- igraph::graph_from_data_frame(graph_edges, directed = FALSE)
graph <- import_network(graph,
species = if (identical(import_format, "genemania_preferred")) NULL else "human",
input_id_format = import_format, case_sensitive = TRUE, verbose = FALSE)
provenance <- list(id = spec$id, source = "author_network_resource",
resource = spec, preprocessing = attr(edges, "preprocessing"),
files = data.frame(path = normalizePath(paths, mustWork = TRUE),
bytes = unname(file.info(paths)$size),
md5 = unname(tools::md5sum(paths)), stringsAsFactors = FALSE),
prepared_utc = format(Sys.time(), tz = "UTC", usetz = TRUE),
mapping = if (is.null(mappings)) NULL else mappings$manifest,
harmonized = mapped, universe = universe,
nearender_version = as.character(utils::packageVersion("NEArender")))
attr(graph, "network_benchmark_manifest") <- provenance
attr(graph, "nearender_manifest") <- provenance
graph
}
#' Summarize network coverage and topology
#'
#' @param g A network accepted by [as_igraph_network()].
#' @param universe Optional complete gene universe; absent genes receive degree
#' zero.
#' @return A one-row network quality-control data frame.
#' @export
network_qc <- function(g, universe = NULL) {
graph <- as_igraph_network(g, case_sensitive = TRUE)
degree <- igraph::degree(graph, loops = FALSE)
if (!is.null(universe)) {
if (any(!igraph::V(graph)$name %in% universe)) {
stop("Network has nodes outside the declared universe.", call. = FALSE)
}
complete_degree <- stats::setNames(rep(0, length(universe)), universe)
complete_degree[names(degree)] <- degree
degree <- complete_degree
}
sorted <- sort(as.numeric(degree)); n <- length(sorted)
gini <- if (!n || sum(sorted) == 0) 0 else {
2 * sum(seq_len(n) * sorted) / (n * sum(sorted)) - (n + 1) / n
}
components <- igraph::components(graph)
data.frame(nodes_with_edges = sum(degree > 0), edges = igraph::ecount(graph),
universe_size = length(degree), coverage = mean(degree > 0),
degree_gini = gini, median_degree = stats::median(degree),
max_degree = if (length(degree)) max(degree) else 0,
largest_component_fraction = if (length(components$csize)) {
max(components$csize) / length(degree)
} else 0)
}
#' Render a harmonized panel of author networks
#'
#' @param networks Named list of networks returned by [prepare_resource()].
#' @param ags,fgs Altered and functional gene-set lists.
#' @param scope Render comprehensive or restricted networks.
#' @return A named list of [nea.render()] results.
#' @export
render_panel <- function(networks, ags, fgs,
scope = c("comprehensive", "restricted")) {
scope <- match.arg(scope)
manifests <- lapply(networks, attr, which = "network_benchmark_manifest")
if (any(vapply(manifests, is.null, logical(1)))) {
stop("Every network needs a resource provenance manifest.", call. = FALSE)
}
keep <- vapply(manifests, function(item) {
identical(item$resource$scope, scope)
}, logical(1))
networks <- networks[keep]; manifests <- manifests[keep]
if (!length(networks)) stop("No networks in this scope.", call. = FALSE)
if (any(!vapply(manifests, function(item) isTRUE(item$harmonized),
logical(1)))) {
stop("Map all networks to one frozen gene namespace before benchmarking.",
call. = FALSE)
}
lapply(networks, function(network) nea.render(ags = ags, fgs = fgs,
net = network, case_sensitive = TRUE, verbose = FALSE))
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.