R/data-access-io-prepare.R

Defines functions .permute_gene_sets mutations2ags samples2ags .prepare_input_matrix_ids export_network read_network as_nearender_network convert_network as_sparse_network as_igraph_network .network_node_count .network_edge_count save.gs.list .gene_set_table save_gs_list import.net import.gs .map_network_table import_gene_sets .igraph_network_from_edges .legacy_network_from_edges .canonical_network_edges .warn_network_repair .network_edge_examples .network_value_labels .stream_network_table .top_score_indices .validate_greedy .validate_network_filters .resolve_import_column .read_nearender_table load_geneset_database load_network_database manifest load_database .load_database_artifact .database_parser .parse_pathwaycommons_total .pubmed_count_with_pseudocount .parse_pathwaycommons_intact .parse_genemania_combined .genemania_symbol_map .parse_scored_network .parse_reactome_gmt .parse_plain_gmt .read_gmt download_geneset_database download_network_database .assert_database_type download_database .database_manifest .download_file_explicit .database_artifact_paths .database_manifest_path .database_destination_dir .verify_database_artifact .explicit_cache_dir .database_cache_dir .database_entry available_databases .database_collection_annotation .database_catalog

Documented in as_igraph_network as_nearender_network as_sparse_network available_databases convert_network download_database download_geneset_database download_network_database export_network import_gene_sets import.gs import.net load_database load_geneset_database load_network_database manifest mutations2ags read_network samples2ags save_gs_list

# Data access, local import/export, representation conversion, and AGS preparation.
#
# These operations share input-boundary validation and identifier provenance.
# Section banners retain navigability without scattering closely related public
# functions across small, overlapping source files.

# ============================================================================
# CURATED DATABASE ACCESS
# ============================================================================

.database_catalog <- function() {
  msigdb <- function(id, collection, organism, release_code, filename,
      expected_gene_sets, expected_bytes, md5, identifiers,
      input_id_format) {
    list(
      id = id, version = "2026.1", provider = "MSigDB",
      type = "gene_sets", organism = organism, collection = collection,
      edge_semantics = "gene-set membership",
      score_column = NA_character_, source_score_column = NA_character_,
      score_semantics = "unscored gene-set membership",
      identifiers = identifiers, input_id_format = input_id_format,
      parser = "plain_gmt", parser_version = "plain-gmt-1",
      license = "MSigDB Terms of Use",
      terms_url = "https://www.gsea-msigdb.org/gsea/license_terms_list.jsp",
      requires_acceptance = TRUE,
      expected_gene_sets = expected_gene_sets,
      artifacts = data.frame(
        role = "gene_sets", filename = filename,
        url = paste0(
          "https://data.broadinstitute.org/gsea-msigdb/msigdb/release/",
          release_code, "/", filename),
        expected_bytes = expected_bytes, md5 = md5,
        stringsAsFactors = FALSE)
    )
  }
  scored_network <- function(id, version, provider, organism, identifiers,
      input_id_format, filename, url, expected_bytes, md5,
      expected_edges = NULL) {
    is_string <- identical(provider, "STRING")
    list(
      id = id, version = version, provider = provider, type = "network",
      organism = organism,
      edge_semantics = "weighted undirected functional protein association",
      score_column = "score",
      source_score_column = if (is_string) "combined_score" else "6:FBS_max",
      score_semantics = if (is_string) {
        "STRING combined edge confidence score (0--1000)"
      } else {
        "maximum final Bayesian edge score"
      },
      identifiers = identifiers, input_id_format = input_id_format,
      parser = "scored_network",
      from_column = if (is_string) "protein1" else "0:ProteinA",
      to_column = if (is_string) "protein2" else "1:ProteinB",
      parser_version = "scored-network-1",
      separator = if (is_string) " " else "\t",
      strip_taxon_prefix = is_string,
      license = if (is_string) "CC-BY-4.0" else "CC-BY-SA-4.0",
      terms_url = if (is_string) {
        "https://string-db.org/cgi/access"
      } else {
        "https://funcoup.org/downloads/"
      },
      requires_acceptance = FALSE,
      expected_edges = expected_edges,
      artifacts = data.frame(
        role = "network", filename = filename, url = url,
        expected_bytes = expected_bytes, md5 = md5,
        stringsAsFactors = FALSE)
    )
  }
  licensed_kegg <- function(id, organism, identifiers) {
    list(
      id = id, version = "user-supplied", provider = "KEGG",
      type = "gene_sets", organism = organism, collection = "PATHWAY",
      edge_semantics = "pathway membership",
      score_column = NA_character_, source_score_column = NA_character_,
      score_semantics = "unscored pathway membership",
      identifiers = identifiers, parser = "licensed_kegg_table",
      parser_version = "kegg-table-1",
      license = "KEGG academic subscription or applicable commercial license",
      terms_url = "https://www.kegg.jp/kegg/legal.html",
      requires_acceptance = TRUE, acquisition = "licensed_file",
      artifacts = data.frame(
        role = character(), filename = character(), url = character(),
        expected_bytes = numeric(), md5 = character(),
        stringsAsFactors = FALSE)
    )
  }

  list(
    list(
      id = "reactome_pathways", version = "97", provider = "Reactome",
      type = "gene_sets", organism = "Homo sapiens",
      edge_semantics = "pathway membership",
      score_column = NA_character_, source_score_column = NA_character_,
      score_semantics = "unscored pathway membership",
      identifiers = "HGNC gene symbols", parser = "reactome_gmt",
      parser_version = "reactome-gmt-1", license = "CC0-1.0",
      terms_url = "https://reactome.org/license", requires_acceptance = FALSE,
      artifacts = data.frame(
        role = "gene_sets", filename = "ReactomePathways.gmt.zip",
        url = "https://download.reactome.org/97/ReactomePathways.gmt.zip",
        expected_bytes = 298479,
        md5 = "f660bae1d7a48a8b5e92df1409cb2eff",
        stringsAsFactors = FALSE)
    ),
    list(
      id = "genemania_human_combined", version = "2021-04-19",
      provider = "GeneMANIA", type = "network", organism = "Homo sapiens",
      edge_semantics = "weighted undirected combined functional association",
      score_column = "score", source_score_column = "Weight",
      score_semantics = "GeneMANIA combined-network edge score",
      identifiers = "UniProt accessions", parser = "genemania_combined",
      parser_version = "genemania-combined-1",
      license = "upstream-source-dependent",
      terms_url = "https://pages.genemania.org/data/",
      requires_acceptance = TRUE,
      artifacts = data.frame(
        role = c("network", "identifier_mapping", "combination_weights"),
        filename = c("COMBINED.DEFAULT_NETWORKS.BP_COMBINING.txt",
          "identifier_mappings.txt",
          "COMBINATION_WEIGHTS.DEFAULT_NETWORKS.BP_COMBINING.txt"),
        url = c(
          "https://genemania.org/data/archive/2021-04-19/Homo_sapiens.COMBINED/COMBINED.DEFAULT_NETWORKS.BP_COMBINING.txt",
          "https://genemania.org/data/archive/2021-04-19/Homo_sapiens/identifier_mappings.txt",
          "https://genemania.org/data/archive/2021-04-19/Homo_sapiens.COMBINED/COMBINATION_WEIGHTS.DEFAULT_NETWORKS.BP_COMBINING.txt"),
        expected_bytes = c(246190113, 11793577, 17626),
        md5 = c("f527d7c1a6b3fe5bfb9994f4ce5c5328",
          "21daec9db1bf0494d38224f5f620f360",
          "710167928aa5bfb63e86bebb58142f61"),
        stringsAsFactors = FALSE)
    ),
    list(
      id = "intact_pathwaycommons", version = "14",
      provider = "Pathway Commons", type = "network",
      organism = "Homo sapiens",
      edge_semantics = "undirected physical interactions attributed to IntAct",
      score_column = NA_character_, source_score_column = NA_character_,
      score_semantics = "unscored physical interaction",
      identifiers = "HGNC gene symbols", parser = "pathwaycommons_intact",
      parser_version = "pathwaycommons-intact-1",
      license = "Apache-2.0 (IntAct); Pathway Commons attribution",
      terms_url = "https://www.ebi.ac.uk/intact/download/ftp",
      requires_acceptance = FALSE, expected_edges = 381279,
      expected_nodes = 17447,
      cache_id = "pathwaycommons_hgnc",
      artifacts = data.frame(
        role = "interaction_table", filename = "pc-hgnc.txt.gz",
        url = "https://download.baderlab.org/PathwayCommons/PC2/v14/pc-hgnc.txt.gz",
        expected_bytes = 115608500,
        md5 = "5130bd21b8f5eabab9f26b07a25a84ab",
        stringsAsFactors = FALSE)
    ),
    list(
      id = "pathwaycommons_hgnc", version = "14",
      provider = "Pathway Commons", type = "network",
      organism = "Homo sapiens",
      edge_semantics = "integrated Pathway Commons relations collapsed undirected",
      score_column = "score",
      source_score_column = "INTERACTION_PUBMED_ID",
      score_semantics = "derived count of distinct PubMed identifiers plus 0.5; maximum across duplicate edges",
      identifiers = "HGNC gene symbols", parser = "pathwaycommons_total",
      parser_version = "pathwaycommons-total-pubmed-pseudocount-3",
      license = "upstream-source-dependent aggregate",
      terms_url = "https://www.pathwaycommons.org/",
      requires_acceptance = TRUE, cache_id = "pathwaycommons_hgnc",
      expected_edges = 1573878, expected_nodes = 20895,
      artifacts = data.frame(
        role = "interaction_table", filename = "pc-hgnc.txt.gz",
        url = "https://download.baderlab.org/PathwayCommons/PC2/v14/pc-hgnc.txt.gz",
        expected_bytes = 115608500,
        md5 = "5130bd21b8f5eabab9f26b07a25a84ab",
        stringsAsFactors = FALSE)
    ),
    list(
      id = "string12_human", version = "12.0", provider = "STRING",
      type = "network", organism = "Homo sapiens",
      edge_semantics = "weighted undirected functional protein association",
      score_column = "score", source_score_column = "combined_score",
      score_semantics = "STRING combined edge confidence score (0--1000)",
      identifiers = "Ensembl peptide identifiers",
      input_id_format = "ensembl_peptide_id", parser = "scored_network",
      from_column = "protein1", to_column = "protein2",
      parser_version = "scored-network-1", separator = " ",
      strip_taxon_prefix = TRUE, license = "CC-BY-4.0",
      terms_url = "https://string-db.org/cgi/access",
      requires_acceptance = FALSE,
      expected_edges = 6712212,
      artifacts = data.frame(
        role = "network", filename = "9606.protein.links.v12.0.txt.gz",
        url = paste0(
          "https://stringdb-downloads.org/download/protein.links.v12.0/",
          "9606.protein.links.v12.0.txt.gz"),
        expected_bytes = 83164437,
        md5 = "5b7c91d02926e723ad30e81ab9d009a4",
        stringsAsFactors = FALSE)
    ),
    list(
      id = "funcoup6_human", version = "6.0", provider = "FunCoup",
      type = "network", organism = "Homo sapiens",
      edge_semantics = "weighted undirected functional protein association",
      score_column = "score", source_score_column = "6:FBS_max",
      score_semantics = "maximum final Bayesian edge score",
      identifiers = "UniProt accessions",
      input_id_format = "uniprotswissprot", parser = "scored_network",
      from_column = "0:ProteinA", to_column = "1:ProteinB",
      parser_version = "scored-network-1", separator = "\t",
      strip_taxon_prefix = FALSE, license = "CC-BY-SA-4.0",
      terms_url = "https://funcoup.org/downloads/",
      requires_acceptance = FALSE,
      expected_edges = 10196312,
      artifacts = data.frame(
        role = "network", filename = "FC6.0_H.sapiens_compact.gz",
        url = paste0("https://funcoup.org/download/network%26",
          "FC6.0_H.sapiens_compact.gz"),
        expected_bytes = 140220467,
        md5 = "0865ae8ecd8f0bc3340f6e8d5bc000e0",
        stringsAsFactors = FALSE)
    ),
    scored_network("string12_mouse", "12.0", "STRING", "Mus musculus",
      "Ensembl peptide identifiers", "ensembl_peptide_id",
      "10090.protein.links.v12.0.txt.gz",
      paste0("https://stringdb-downloads.org/download/protein.links.v12.0/",
        "10090.protein.links.v12.0.txt.gz"),
      75325207, "2463014fcf2f4b6c1c6b86e43fbd6cbb"),
    scored_network("funcoup6_mouse", "6.0", "FunCoup", "Mus musculus",
      "UniProt accessions", "uniprotswissprot",
      "FC6.0_M.musculus_compact.gz",
      "https://funcoup.org/download/network%26FC6.0_M.musculus_compact.gz",
      157638299, "7024cbf896aee5248af1c4b88aaa1e0d"),
    scored_network("string12_rat", "12.0", "STRING", "Rattus norvegicus",
      "Ensembl peptide identifiers", "ensembl_peptide_id",
      "10116.protein.links.v12.0.txt.gz",
      paste0("https://stringdb-downloads.org/download/protein.links.v12.0/",
        "10116.protein.links.v12.0.txt.gz"),
      78625664, "01d4f448689a075e86af9d540a119698"),
    scored_network("funcoup6_rat", "6.0", "FunCoup", "Rattus norvegicus",
      "UniProt accessions", "uniprotswissprot",
      "FC6.0_R.norvegicus_compact.gz",
      "https://funcoup.org/download/network%26FC6.0_R.norvegicus_compact.gz",
      143995633, "2762b4319cc9c4b40d031d56f9ebb702"),
    scored_network("string12_zebrafish", "12.0", "STRING", "Danio rerio",
      "Ensembl peptide identifiers", "ensembl_peptide_id",
      "7955.protein.links.v12.0.txt.gz",
      paste0("https://stringdb-downloads.org/download/protein.links.v12.0/",
        "7955.protein.links.v12.0.txt.gz"),
      79262128, "502c35da03dab382543dae2d55ce768c"),
    scored_network("funcoup6_zebrafish", "6.0", "FunCoup", "Danio rerio",
      "UniProt accessions", "uniprotswissprot",
      "FC6.0_D.rerio_compact.gz",
      "https://funcoup.org/download/network%26FC6.0_D.rerio_compact.gz",
      94983183, "5bba68c876f9b765bf395c0352cfcb16"),
    scored_network("string12_fly", "12.0", "STRING",
      "Drosophila melanogaster", "FlyBase annotation identifiers",
      "flybase_annot_id", "7227.protein.links.v12.0.txt.gz",
      paste0("https://stringdb-downloads.org/download/protein.links.v12.0/",
        "7227.protein.links.v12.0.txt.gz"),
      27962293, "6126649ece2ddf53695ae3035ee76a94"),
    scored_network("funcoup6_fly", "6.0", "FunCoup",
      "Drosophila melanogaster", "UniProt accessions", "uniprotswissprot",
      "FC6.0_D.melanogaster_compact.gz",
      "https://funcoup.org/download/network%26FC6.0_D.melanogaster_compact.gz",
      39741583, "5dd0c066e92c08a71270842ca250b830"),
    scored_network("string12_worm", "12.0", "STRING",
      "Caenorhabditis elegans", "Ensembl peptide identifiers",
      "ensembl_peptide_id", "6239.protein.links.v12.0.txt.gz",
      paste0("https://stringdb-downloads.org/download/protein.links.v12.0/",
        "6239.protein.links.v12.0.txt.gz"),
      60663523, "b1bb0d5613d504ad06ad1517d5de653b"),
    scored_network("funcoup6_worm", "6.0", "FunCoup",
      "Caenorhabditis elegans", "UniProt accessions", "uniprotswissprot",
      "FC6.0_C.elegans_compact.gz",
      "https://funcoup.org/download/network%26FC6.0_C.elegans_compact.gz",
      80920316, "f977f31d4bc734be26ae61145250a1e3"),
    scored_network("string12_yeast", "12.0", "STRING",
      "Saccharomyces cerevisiae", "SGD gene identifiers", "sgd_gene",
      "4932.protein.links.v12.0.txt.gz",
      paste0("https://stringdb-downloads.org/download/protein.links.v12.0/",
        "4932.protein.links.v12.0.txt.gz"),
      15771211, "0a477e579f8a3660a96094ab184d89d2"),
    scored_network("funcoup6_yeast", "6.0", "FunCoup",
      "Saccharomyces cerevisiae", "UniProt accessions", "uniprotswissprot",
      "FC6.0_S.cerevisiae_compact.gz",
      "https://funcoup.org/download/network%26FC6.0_S.cerevisiae_compact.gz",
      16268177, "c4f29b30bb128d5cd7ab005cae9ff983"),
    scored_network("string12_arabidopsis", "12.0", "STRING",
      "Arabidopsis thaliana", "UniProt accessions", "uniprotswissprot",
      "3702.protein.links.v12.0.txt.gz",
      paste0("https://stringdb-downloads.org/download/protein.links.v12.0/",
        "3702.protein.links.v12.0.txt.gz"),
      72529016, "d20b068ea82f8bfe31b29ec41809e5d9"),
    scored_network("funcoup6_arabidopsis", "6.0", "FunCoup",
      "Arabidopsis thaliana", "UniProt accessions", "uniprotswissprot",
      "FC6.0_A.thaliana_compact.gz",
      "https://funcoup.org/download/network%26FC6.0_A.thaliana_compact.gz",
      148542742, "4d1b4cff8401362fab86bb95a89c46b4"),
    scored_network("string12_ecoli", "12.0", "STRING",
      "Escherichia coli K-12 MG1655", "locus tags", "LocusTag",
      "511145.protein.links.v12.0.txt.gz",
      paste0("https://stringdb-downloads.org/download/protein.links.v12.0/",
        "511145.protein.links.v12.0.txt.gz"),
      4959344, "5d5f9df7153fc76bdb6be41aec4bce23"),
    scored_network("funcoup6_ecoli", "6.0", "FunCoup",
      "Escherichia coli K-12 MG1655", "UniProt accessions",
      "uniprotswissprot", "FC6.0_E.coli_compact.gz",
      "https://funcoup.org/download/network%26FC6.0_E.coli_compact.gz",
      6226211, "cfed4794ecdbd4757722c4e760f1a0fe"),
    msigdb("msigdb_h_human", "H", "Homo sapiens", "2026.1.Hs",
      "h.all.v2026.1.Hs.symbols.gmt", 50L, 48686,
      "367eec875967c2cfbf664a1a065b7b8d", "HGNC gene symbols",
      "hgnc_symbol"),
    msigdb("msigdb_cp_biocarta_human", "CP:BIOCARTA", "Homo sapiens",
      "2026.1.Hs", "c2.cp.biocarta.v2026.1.Hs.symbols.gmt", 292L,
      57689, "166eeb553cb2d4f7d529314150920453", "HGNC gene symbols",
      "hgnc_symbol"),
    msigdb("msigdb_cp_kegg_medicus_human", "CP:KEGG_MEDICUS",
      "Homo sapiens", "2026.1.Hs",
      "c2.cp.kegg_medicus.v2026.1.Hs.symbols.gmt", 658L, 177277,
      "a62ed196ae91134ea5509a4318ad51df", "HGNC gene symbols",
      "hgnc_symbol"),
    msigdb("msigdb_cp_pid_human", "CP:PID", "Homo sapiens", "2026.1.Hs",
      "c2.cp.pid.v2026.1.Hs.symbols.gmt", 196L, 65610,
      "291508046f73d82d13e5efb47492fa47", "HGNC gene symbols",
      "hgnc_symbol"),
    msigdb("msigdb_cp_wikipathways_human", "CP:WIKIPATHWAYS",
      "Homo sapiens", "2026.1.Hs",
      "c2.cp.wikipathways.v2026.1.Hs.symbols.gmt", 925L, 372459,
      "8e8a38972816a3997a557d6dd625138a", "HGNC gene symbols",
      "hgnc_symbol"),
    msigdb("msigdb_cp_kegg_legacy_human", "CP:KEGG_LEGACY",
      "Homo sapiens", "2026.1.Hs",
      "c2.cp.kegg_legacy.v2026.1.Hs.symbols.gmt", 186L, 100274,
      "bad4276c25ba17325686707d01447377", "HGNC gene symbols",
      "hgnc_symbol"),
    msigdb("msigdb_c6_human", "C6", "Homo sapiens", "2026.1.Hs",
      "c6.all.v2026.1.Hs.symbols.gmt", 189L, 205653,
      "aba0e2214ff63327ae3fb0ce4bcd11c2", "HGNC gene symbols",
      "hgnc_symbol"),
    msigdb("msigdb_c7_human", "C7", "Homo sapiens", "2026.1.Hs",
      "c7.all.v2026.1.Hs.symbols.gmt", 5219L, 7013985,
      "80d11a6829a99c9219159559d2f2778d", "HGNC gene symbols",
      "hgnc_symbol"),
    msigdb("msigdb_c8_human", "C8", "Homo sapiens", "2026.1.Hs",
      "c8.all.v2026.1.Hs.symbols.gmt", 866L, 1127394,
      "affa40110a0396057acd174037bb7bd8", "HGNC gene symbols",
      "hgnc_symbol"),
    msigdb("msigdb_mh_mouse", "MH", "Mus musculus", "2026.1.Mm",
      "mh.all.v2026.1.Mm.symbols.gmt", 50L, 48007,
      "b3724f26da1b12300291879be3f6e85d", "MGI gene symbols",
      "mgi_symbol"),
    msigdb("msigdb_cp_biocarta_mouse", "CP:BIOCARTA", "Mus musculus",
      "2026.1.Mm", "m2.cp.biocarta.v2026.1.Mm.symbols.gmt", 252L,
      48479, "c7546366bab3fc037d0a67c420387d5d", "MGI gene symbols",
      "mgi_symbol"),
    msigdb("msigdb_cp_wikipathways_mouse", "CP:WIKIPATHWAYS",
      "Mus musculus", "2026.1.Mm",
      "m2.cp.wikipathways.v2026.1.Mm.symbols.gmt", 202L, 88156,
      "7c0f0cee986d670e08b98c9ce774aba8", "MGI gene symbols",
      "mgi_symbol"),
    msigdb("msigdb_m7_mouse", "M7", "Mus musculus", "2026.1.Mm",
      "m7.all.v2026.1.Mm.symbols.gmt", 787L, 522688,
      "4849d2cfb748b0ca2a22e1488af1fed2", "MGI gene symbols",
      "mgi_symbol"),
    msigdb("msigdb_m8_mouse", "M8", "Mus musculus", "2026.1.Mm",
      "m8.all.v2026.1.Mm.symbols.gmt", 233L, 338067,
      "386d11807550519d31b11e9c09daa44a", "MGI gene symbols",
      "mgi_symbol"),
    licensed_kegg("kegg_pathways_human", "Homo sapiens", "HGNC gene symbols"),
    licensed_kegg("kegg_pathways_mouse", "Mus musculus", "MGI gene symbols"),
    licensed_kegg("kegg_pathways_rat", "Rattus norvegicus", "RGD gene symbols"),
    licensed_kegg("kegg_pathways_zebrafish", "Danio rerio",
      "ZFIN gene symbols"),
    licensed_kegg("kegg_pathways_fly", "Drosophila melanogaster",
      "FlyBase gene symbols"),
    licensed_kegg("kegg_pathways_worm", "Caenorhabditis elegans",
      "WormBase gene symbols"),
    licensed_kegg("kegg_pathways_yeast", "Saccharomyces cerevisiae",
      "SGD gene symbols"),
    licensed_kegg("kegg_pathways_arabidopsis", "Arabidopsis thaliana",
      "TAIR gene symbols"),
    licensed_kegg("kegg_pathways_ecoli", "Escherichia coli K-12 MG1655",
      "gene symbols")
  )
}

.database_collection_annotation <- function(entry) {
  descriptions <- c(
    H = "hallmark gene sets",
    MH = "mouse hallmark gene sets",
    `CP:BIOCARTA` = "BioCarta pathway gene sets",
    `CP:KEGG_MEDICUS` = "KEGG MEDICUS pathway gene sets",
    `CP:PID` = "PID pathway gene sets",
    `CP:WIKIPATHWAYS` = "WikiPathways gene sets",
    `CP:KEGG_LEGACY` = "legacy KEGG pathway gene sets",
    C6 = "oncogenic signature gene sets",
    C7 = "immunologic signature gene sets",
    C8 = "cell type signature gene sets",
    M7 = "mouse immunologic signature gene sets",
    M8 = "mouse cell type signature gene sets",
    PATHWAY = "KEGG pathways"
  )
  if (identical(entry$provider, "Reactome")) {
    description <- "Reactome pathways"
  } else if (is.null(entry$collection)) {
    return(NA_character_)
  } else {
    description <- unname(descriptions[[entry$collection]])
  }
  if (is.null(description)) description <- entry$collection
  if (!is.null(entry$expected_gene_sets)) {
    paste0(description, " (", entry$expected_gene_sets, " gene sets)")
  } else {
    description
  }
}

#' List curated databases
#'
#' Return the built-in, offline catalog of fixed-release remote resources and
#' licensed user-supplied sources. Listing the catalog never makes a network
#' request. Entries that aggregate source data with different reuse terms,
#' including MSigDB collections, are marked as requiring explicit acceptance.
#' The catalog includes collection names, plain-language collection
#' annotations, and expected gene set counts where applicable. For Pathway
#' Commons, `score_semantics` describes the derived
#' edge weight: the distinct supporting-PubMed count plus a 0.5 pseudocount.
#' @param type Database type to list: `"all"`, `"network"`, or `"pathways"`.
#'   `"gene_sets"` is accepted as a synonym for `"pathways"`.
#' @param species Optional scientific name, common name, package species ID,
#'   three-letter KEGG style organism ID, or NCBI taxonomy ID. By default,
#'   return resources for every supported species.
#' @return A data frame describing supported database releases, including
#'   resource type, organism, collection, identifiers, source edge score field
#'   and semantics, license, expected size, checksum, acquisition mode, and
#'   expected gene-set count where applicable.
#' @seealso [download_database()], [load_database()]
#' @examples
#' human_networks <- available_databases("network", species = "9606")
#' human_networks[, c("id", "version", "provider", "source_score_column")]
#' available_databases("pathways", species = "mouse")[,
#'   c("id", "collection", "expected_gene_sets")]
#' @export
available_databases <- function(
    type = c("all", "network", "pathways", "gene_sets"),
    species = NULL) {
  type <- match.arg(type)
  catalog_type <- if (type == "pathways") "gene_sets" else type
  entries <- .database_catalog()
  rows <- lapply(entries, function(entry) {
    has_artifact <- nrow(entry$artifacts) > 0L
    primary <- if (has_artifact) entry$artifacts[1L, , drop = FALSE] else NULL
    data.frame(id = entry$id, version = entry$version,
      provider = entry$provider, type = entry$type, organism = entry$organism,
      collection = if (is.null(entry$collection)) NA_character_ else {
        entry$collection
      },
      collection_annotation = .database_collection_annotation(entry),
      identifiers = entry$identifiers, edge_semantics = entry$edge_semantics,
      source_score_column = entry$source_score_column,
      score_semantics = entry$score_semantics,
      parser = entry$parser,
      license = entry$license, terms_url = entry$terms_url,
      requires_acceptance = entry$requires_acceptance,
      acquisition = if (is.null(entry$acquisition)) "download" else {
        entry$acquisition
      },
      artifact_count = nrow(entry$artifacts),
      expected_bytes = if (has_artifact) {
        sum(entry$artifacts$expected_bytes)
      } else NA_real_,
      expected_edges = if (is.null(entry$expected_edges)) {
        NA_real_
      } else as.numeric(entry$expected_edges),
      expected_nodes = if (is.null(entry$expected_nodes)) {
        NA_real_
      } else as.numeric(entry$expected_nodes),
      expected_gene_sets = if (is.null(entry$expected_gene_sets)) {
        NA_integer_
      } else as.integer(entry$expected_gene_sets),
      url = if (has_artifact) primary$url else NA_character_,
      md5 = if (has_artifact) primary$md5 else NA_character_,
      parser_version = entry$parser_version, stringsAsFactors = FALSE)
  })
  result <- do.call(rbind, rows)
  if (!is.null(species)) {
    organism <- .identifier_entry(species)$scientific_name
    result <- result[result$organism == organism, , drop = FALSE]
  }
  if (catalog_type != "all") {
    result <- result[result$type == catalog_type, , drop = FALSE]
  }
  rownames(result) <- NULL
  result
}

.database_entry <- function(id, version = NULL) {
  if (!is.character(id) || length(id) != 1L || is.na(id) || !nzchar(id)) {
    stop("id must be one non-empty character value.", call. = FALSE)
  }
  if (!is.null(version) && (!is.character(version) || length(version) != 1L ||
      is.na(version) || !nzchar(version))) {
    stop("version must be NULL or one non-empty character value.", call. = FALSE)
  }
  entries <- .database_catalog()
  selected <- vapply(entries, function(entry) entry$id == id &&
    (is.null(version) || entry$version == version), logical(1))
  if (sum(selected) != 1L) {
    stop("id and version must identify one available database.", call. = FALSE)
  }
  entries[[which(selected)]]
}

.database_cache_dir <- function(cache_dir) {
  if (!is.null(cache_dir)) {
    if (!is.character(cache_dir) || length(cache_dir) != 1L ||
        is.na(cache_dir) || !nzchar(cache_dir)) {
      stop("cache_dir must be NULL or one non-empty path.", call. = FALSE)
    }
    return(path.expand(cache_dir))
  }
  if (getRversion() >= "4.0.0") return(tools::R_user_dir("NEArender", "cache"))
  file.path(path.expand("~"), ".cache", "NEArender")
}

.explicit_cache_dir <- function(cache_dir) {
  if (is.null(cache_dir)) {
    stop("cache_dir must be supplied explicitly for operations that write files.",
      call. = FALSE)
  }
  .database_cache_dir(cache_dir)
}

.verify_database_artifact <- function(path, artifact) {
  bytes <- unname(file.info(path)$size)
  md5 <- unname(tools::md5sum(path))
  if (!identical(bytes, as.numeric(artifact$expected_bytes)) ||
      !identical(md5, as.character(artifact$md5))) {
    stop("Cached artifact failed size or checksum verification.", call. = FALSE)
  }
  list(bytes = bytes, md5 = md5)
}

.database_destination_dir <- function(root, entry) {
  cache_id <- if (is.null(entry$cache_id)) entry$id else entry$cache_id
  file.path(root, entry$provider, cache_id, entry$version)
}

.database_manifest_path <- function(destination_dir, entry) {
  file.path(destination_dir, paste0(entry$id, ".manifest.rds"))
}

.database_artifact_paths <- function(root, entry) {
  paths <- file.path(.database_destination_dir(root, entry),
    entry$artifacts$filename)
  stats::setNames(paths, entry$artifacts$role)
}

.download_file_explicit <- function(url, destination, quiet, kind) {
  tryCatch(
    withCallingHandlers(
      utils::download.file(url, destination, mode = "wb", quiet = quiet),
      warning = function(condition) {
        if (grepl("downloaded length .* reported length 0",
            conditionMessage(condition))) {
          invokeRestart("muffleWarning")
        }
      }
    ),
    error = function(error) {
      stop("Could not download ", kind, " from ", url,
        ". Check Internet availability and provider status. Original error: ",
        conditionMessage(error), call. = FALSE)
    }
  )
  if (!file.exists(destination) || is.na(file.info(destination)$size) ||
      file.info(destination)$size <= 0) {
    stop("The downloaded ", kind, " is empty: ", url, ".",
      call. = FALSE)
  }
  invisible(destination)
}

.database_manifest <- function(entry, integrity, retrieved_at = NULL) {
  artifacts <- entry$artifacts
  artifacts$bytes <- vapply(integrity, `[[`, numeric(1), "bytes")
  artifacts$verified_md5 <- vapply(integrity, `[[`, character(1), "md5")
  list(id = entry$id, version = entry$version, provider = entry$provider,
    type = entry$type, organism = entry$organism,
    collection = if (is.null(entry$collection)) NA_character_ else {
      entry$collection
    },
    expected_gene_sets = if (is.null(entry$expected_gene_sets)) {
      NA_integer_
    } else {
      as.integer(entry$expected_gene_sets)
    },
    identifiers = entry$identifiers, edge_semantics = entry$edge_semantics,
    input_id_format = if (is.null(entry$input_id_format)) {
      NA_character_
    } else {
      entry$input_id_format
    },
    score_column = entry$score_column,
    source_score_column = entry$source_score_column,
    score_semantics = entry$score_semantics,
    license = entry$license,
    terms_url = entry$terms_url, retrieved_at = retrieved_at,
    artifacts = artifacts, parser = entry$parser,
    parser_version = entry$parser_version)
}

#' Download a fixed-version curated database
#'
#' Downloads are explicit, versioned, and cached. Existing files are reused
#' unless `force = TRUE`. A catalog entry may comprise several jointly
#' versioned and verified artifacts. No analytical function calls this
#' function.
#' @param id Catalog identifier from [available_databases()].
#' @param version Database release specified by the catalog. By default, the
#'   release associated with `id` is used.
#' @param cache_dir Cache root. Download functions require an explicit path;
#'   read-only loaders use the package user cache when it is `NULL`.
#' @param force Replace existing cached artifacts.
#' @param quiet Suppress download progress.
#' @param accept_license Confirm that you reviewed the catalog entry's source
#'   terms. Required only when `requires_acceptance` is true.
#' @return The normalized cached artifact path, or a named vector of paths for
#'   a grouped database, invisibly.
#' @seealso [available_databases()], [load_database()]
#' @examples
#' cache <- file.path(tempdir(), "NEArender-cache")
#' \dontrun{
#' download_database("reactome_pathways", cache_dir = cache)
#' }
#' @export
download_database <- function(id, version = NULL, cache_dir = NULL,
    force = FALSE, quiet = FALSE, accept_license = FALSE) {
  .assert_flag(force, "force"); .assert_flag(quiet, "quiet")
  .assert_flag(accept_license, "accept_license")
  entry <- .database_entry(id, version)
  if (identical(entry$acquisition, "licensed_file")) {
    stop("KEGG pathway files are licensed, user-supplied inputs; use ",
      "import_kegg_pathways() instead.", call. = FALSE)
  }
  if (entry$requires_acceptance && !accept_license) {
    stop("This database has terms that require explicit acceptance; review ",
      "terms_url and set accept_license = TRUE to continue.", call. = FALSE)
  }
  root <- .explicit_cache_dir(cache_dir)
  old_timeout <- getOption("timeout", 60)
  options(timeout = max(300, old_timeout))
  on.exit(options(timeout = old_timeout), add = TRUE)
  destination_dir <- .database_destination_dir(root, entry)
  destinations <- .database_artifact_paths(root, entry)
  dir.create(destination_dir, recursive = TRUE, showWarnings = FALSE)
  integrity <- vector("list", length(destinations))
  temporary <- rep(NA_character_, length(destinations))
  on.exit(unlink(temporary[!is.na(temporary)]), add = TRUE)

  for (i in seq_along(destinations)) {
    artifact <- entry$artifacts[i, , drop = FALSE]
    if (file.exists(destinations[[i]]) && !force) {
      integrity[[i]] <- .verify_database_artifact(destinations[[i]], artifact)
      next
    }
    temporary[[i]] <- tempfile(pattern = "download-", tmpdir = destination_dir)
    .download_file_explicit(artifact$url, temporary[[i]], quiet,
      paste0("database artifact '", artifact$filename, "'"))
    integrity[[i]] <- .verify_database_artifact(temporary[[i]], artifact)
  }
  for (i in seq_along(destinations)) {
    if (is.na(temporary[[i]])) next
    if (file.exists(destinations[[i]])) unlink(destinations[[i]])
    if (!file.rename(temporary[[i]], destinations[[i]])) {
      stop("Could not move a downloaded artifact into the cache.", call. = FALSE)
    }
    temporary[[i]] <- NA_character_
  }
  manifest <- .database_manifest(entry, integrity,
    format(Sys.time(), tz = "UTC", usetz = TRUE))
  manifest_path <- .database_manifest_path(destination_dir, entry)
  manifest_temporary <- tempfile(pattern = "manifest-", tmpdir = destination_dir)
  saveRDS(manifest, manifest_temporary)
  if (file.exists(manifest_path)) unlink(manifest_path)
  if (!file.rename(manifest_temporary, manifest_path)) {
    stop("Could not write the database manifest.", call. = FALSE)
  }
  normalized <- normalizePath(destinations)
  names(normalized) <- names(destinations)
  invisible(if (length(normalized) == 1L) unname(normalized) else normalized)
}

.assert_database_type <- function(id, version, type) {
  entry <- .database_entry(id, version)
  if (!identical(entry$type, type)) {
    stop("Database '", id, "' is type '", entry$type,
      "', not '", type, "'.", call. = FALSE)
  }
  invisible(entry)
}

#' Download a curated network database
#'
#' Type-specific wrapper around [download_database()].
#' @inheritParams download_database
#' @return The downloaded artifact path or paths, invisibly.
#' @seealso [available_databases()], [load_network_database()]
#' @examples
#' \dontrun{
#' download_network_database("string12_human")
#' string <- load_network_database("string12_human", n_top = 1000000)
#' }
#' @export
download_network_database <- function(id, version = NULL, cache_dir = NULL,
    force = FALSE, quiet = FALSE, accept_license = FALSE) {
  .assert_database_type(id, version, "network")
  download_database(id, version, cache_dir, force, quiet, accept_license)
}

#' Download a curated gene-set database
#'
#' Type-specific wrapper around [download_database()].
#' @inheritParams download_database
#' @return The downloaded artifact path or paths, invisibly.
#' @seealso [available_databases()], [load_geneset_database()]
#' @examples
#' \dontrun{
#' download_geneset_database("reactome_pathways")
#' reactome <- load_geneset_database("reactome_pathways")
#' }
#' @export
download_geneset_database <- function(id, version = NULL, cache_dir = NULL,
    force = FALSE, quiet = FALSE, accept_license = FALSE) {
  .assert_database_type(id, version, "gene_sets")
  download_database(id, version, cache_dir, force, quiet, accept_license)
}

.read_gmt <- function(path, case_sensitive) {
  lines <- readLines(path, warn = FALSE)
  fields <- strsplit(lines[nzchar(lines)], "\t", fixed = TRUE)
  fields <- fields[lengths(fields) >= 3L]
  if (!length(fields)) stop("The GMT artifact contains no gene sets.", call. = FALSE)
  sets <- lapply(fields, function(x) unique(.canonical_ids(x[-c(1L, 2L)],
    case_sensitive)))
  names(sets) <- vapply(fields, `[[`, character(1), 1L)
  .mark_normalized(sets, case_sensitive)
}

.parse_plain_gmt <- function(paths, entry, manifest, case_sensitive, ...) {
  data <- .read_gmt(unname(paths[["gene_sets"]]), case_sensitive)
  if (!is.null(entry$expected_gene_sets) &&
      length(data) != entry$expected_gene_sets) {
    stop("The parsed gene-set count does not match the specified release.",
      call. = FALSE)
  }
  data <- .attach_identifier_metadata(data,
    .resolve_input_identity(entry$organism, entry$input_id_format))
  manifest$case_sensitive <- case_sensitive
  manifest$collection <- entry$collection
  manifest$gene_set_count <- length(data)
  manifest$gene_count <- length(unique(unlist(data, use.names = FALSE)))
  list(data = data, manifest = manifest)
}

.parse_reactome_gmt <- function(paths, entry, manifest, case_sensitive, ...) {
  artifact <- unname(paths[["gene_sets"]])
  archive <- utils::unzip(artifact, list = TRUE)$Name
  gmt <- archive[grepl("\\.gmt$", archive, ignore.case = TRUE)]
  if (length(gmt) != 1L) stop("The archive must contain exactly one GMT file.",
    call. = FALSE)
  temporary_dir <- tempfile("nearender-gmt-"); dir.create(temporary_dir)
  on.exit(unlink(temporary_dir, recursive = TRUE), add = TRUE)
  path <- utils::unzip(artifact, files = gmt, exdir = temporary_dir)
  data <- .read_gmt(path, case_sensitive)
  data <- .attach_identifier_metadata(data,
    .resolve_input_identity(entry$organism, "hgnc_symbol"))
  manifest$case_sensitive <- case_sensitive
  manifest$gene_set_count <- length(data)
  manifest$gene_count <- length(unique(unlist(data, use.names = FALSE)))
  list(data = data, manifest = manifest)
}

.parse_scored_network <- function(paths, entry, manifest, case_sensitive,
    min_score = NULL, n_top = NULL, greedy = TRUE, map_to_symbols = FALSE,
    chunk_size = 100000L,
    output_network_format = c("igraph", "sparse", "legacy"),
    id_mappings = NULL, ambiguous = c("error", "drop", "first", "expand"),
    unmapped = c("keep", "drop", "error"), verbose = FALSE, ...) {
  .assert_flag(map_to_symbols, "map_to_symbols")
  .assert_flag(verbose, "verbose")
  output_network_format <- match.arg(output_network_format)
  ambiguous <- match.arg(ambiguous)
  unmapped <- match.arg(unmapped)
  if (is.null(min_score) && is.null(n_top)) {
    size <- if (is.null(entry$expected_edges)) "" else paste0(
      " The full pinned release has ",
      format(entry$expected_edges, big.mark = ",", scientific = FALSE,
        trim = TRUE), " edges; see available_databases()$expected_edges.")
    stop(entry$provider, " loading requires an explicit edge-score threshold ",
      "in min_score or a top-edge count in n_top.", size, call. = FALSE)
  }
  if (map_to_symbols && is.null(id_mappings)) {
    stop("map_to_symbols = TRUE requires id_mappings from load_id_mappings().",
      call. = FALSE)
  }
  candidates <- .stream_network_table(paths[["network"]],
    entry$from_column, entry$to_column, entry$source_score_column,
    min_score = min_score, n_top = n_top, greedy = greedy,
    case_sensitive = TRUE,
    chunk_size = chunk_size, zero_score_is_edge = TRUE,
    separator = entry$separator, verbose = verbose)
  stream_info <- attr(candidates, "stream_info")
  if (isTRUE(entry$strip_taxon_prefix)) {
    candidates$from <- sub("^[^.]+\\.", "", candidates$from)
    candidates$to <- sub("^[^.]+\\.", "", candidates$to)
  }
  data <- import_network(candidates, "from", "to", "score", n_top = n_top,
    greedy = greedy, case_sensitive = case_sensitive, verbose = FALSE,
    output_network_format = output_network_format,
    species = entry$organism, input_id_format = entry$input_id_format,
    id_mappings = id_mappings, ambiguous = ambiguous, unmapped = unmapped)
  manifest$case_sensitive <- case_sensitive
  manifest$identifier_output <- if (is.null(id_mappings)) {
    entry$identifiers
  } else {
    id_mappings$manifest$master_id
  }
  manifest$filters <- list(min_score = min_score, n_top = n_top,
    greedy = greedy)
  manifest$stream <- stream_info
  manifest$output_network_format <- output_network_format
  manifest$node_count <- .network_node_count(data)
  manifest$edge_count <- .network_edge_count(data)
  list(data = data, manifest = manifest)
}

.genemania_symbol_map <- function(path, case_sensitive) {
  mapping <- utils::read.delim(path, quote = "", comment.char = "",
    colClasses = "character", check.names = FALSE)
  mapping <- unique(mapping[mapping$Source == "Gene Name",
    c("Preferred_Name", "Name"), drop = FALSE])
  counts <- table(mapping$Preferred_Name)
  ambiguous_native <- sum(counts > 1L)
  mapping <- mapping[mapping$Preferred_Name %in% names(counts[counts == 1L]),
    , drop = FALSE]
  keys <- .canonical_ids(mapping$Preferred_Name, case_sensitive = TRUE)
  values <- .canonical_ids(mapping$Name, case_sensitive)
  result <- stats::setNames(values, keys)
  value_counts <- table(values)
  case_collisions <- if (case_sensitive) 0L else {
    lowered <- tolower(mapping$Name)
    sum(vapply(split(mapping$Name, lowered), function(x) length(unique(x)) > 1L,
      logical(1)))
  }
  attr(result, "mapping_info") <- list(mapping_pairs = nrow(mapping),
    ambiguous_native_ids = ambiguous_native,
    many_to_one_symbols = sum(value_counts > 1L),
    case_collision_symbols = case_collisions)
  result
}

.parse_genemania_combined <- function(paths, entry, manifest, case_sensitive,
    min_score = NULL, n_top = NULL, greedy = TRUE, map_to_symbols = FALSE,
    chunk_size = 100000L,
    output_network_format = c("igraph", "sparse", "legacy"),
    verbose = FALSE, ...) {
  .assert_flag(map_to_symbols, "map_to_symbols")
  .assert_flag(verbose, "verbose")
  output_network_format <- match.arg(output_network_format)
  if (is.null(min_score) && is.null(n_top)) {
    stop("GeneMANIA loading requires an explicit edge-score threshold in ",
      "min_score or a top-edge count in n_top.", call. = FALSE)
  }
  candidates <- .stream_network_table(paths[["network"]], "Gene_A", "Gene_B",
    "Weight", min_score = min_score, n_top = n_top, greedy = greedy,
    case_sensitive = TRUE, chunk_size = chunk_size,
    zero_score_is_edge = TRUE, verbose = verbose)
  stream_info <- attr(candidates, "stream_info")
  mapping_report <- NULL
  if (map_to_symbols) {
    symbol_map <- .genemania_symbol_map(paths[["identifier_mapping"]],
      case_sensitive)
    map_info <- attr(symbol_map, "mapping_info")
    from <- unname(symbol_map[candidates$from])
    to <- unname(symbol_map[candidates$to])
    mapped <- !is.na(from) & nzchar(from) & !is.na(to) & nzchar(to)
    mapping_report <- c(map_info, list(candidate_edges = nrow(candidates),
      mapped_edges = sum(mapped), dropped_edges = sum(!mapped),
      mapping = "unambiguous Gene Name"))
    candidates$from <- from
    candidates$to <- to
    candidates <- candidates[mapped, , drop = FALSE]
    if (!nrow(candidates)) stop("No GeneMANIA edges map to gene symbols.",
      call. = FALSE)
  }
  data <- import_network(candidates, "from", "to", "score",
    n_top = n_top, greedy = greedy,
    case_sensitive = if (map_to_symbols) case_sensitive else TRUE,
    verbose = FALSE, output_network_format = output_network_format,
    species = entry$organism,
    input_id_format = if (map_to_symbols) "hgnc_symbol" else {
      "uniprotswissprot"
    })
  weights <- utils::read.delim(paths[["combination_weights"]], quote = "",
    comment.char = "", colClasses = "character", check.names = FALSE)
  manifest$case_sensitive <- if (map_to_symbols) case_sensitive else TRUE
  manifest$identifier_output <- if (map_to_symbols) "HGNC gene symbols" else {
    entry$identifiers
  }
  manifest$filters <- list(min_score = min_score, n_top = n_top,
    greedy = greedy)
  manifest$stream <- stream_info
  manifest$mapping <- mapping_report
  manifest$combination_weight_count <- nrow(weights)
  manifest$output_network_format <- output_network_format
  manifest$node_count <- .network_node_count(data)
  manifest$edge_count <- .network_edge_count(data)
  list(data = data, manifest = manifest)
}

.parse_pathwaycommons_intact <- function(paths, entry, manifest,
    case_sensitive, min_score = NULL, n_top = NULL, greedy = TRUE,
    chunk_size = 100000L,
    output_network_format = c("igraph", "sparse", "legacy"),
    verbose = FALSE, ...) {
  .assert_flag(verbose, "verbose")
  output_network_format <- match.arg(output_network_format)
  if (!is.null(min_score) || !is.null(n_top)) {
    warning("The Pathway Commons IntAct table is unscored; ignoring min_score ",
      "and n_top and loading the full network.", call. = FALSE)
    min_score <- NULL
    n_top <- NULL
  }
  historical_filter <- function(lines) {
    !grepl("chebi:", tolower(lines), fixed = TRUE) &
      !grepl("Reference", lines, fixed = TRUE) &
      grepl("\\bIntAct\\b", lines, perl = TRUE)
  }
  candidates <- .stream_network_table(paths[["interaction_table"]],
    "PARTICIPANT_A", "PARTICIPANT_B", case_sensitive = case_sensitive,
    chunk_size = chunk_size, line_filter = historical_filter,
    verbose = verbose)
  stream_info <- attr(candidates, "stream_info")
  data <- import_network(candidates, "from", "to",
    case_sensitive = case_sensitive, verbose = FALSE,
    output_network_format = output_network_format,
    species = entry$organism, input_id_format = "hgnc_symbol")
  if (!is.null(entry$expected_edges) &&
      .network_edge_count(data) != entry$expected_edges) {
    stop("The parsed IntAct edge count does not match the specified release.",
      call. = FALSE)
  }
  manifest$case_sensitive <- case_sensitive
  manifest$identifier_output <- entry$identifiers
  manifest$source_database <- "IntAct"
  manifest$extraction <- list(
    include = "whole-word IntAct attribution",
    exclude = c("case-insensitive chebi:", "Reference"),
    columns = c("PARTICIPANT_A", "PARTICIPANT_B"),
    edge_handling = "lexical endpoint ordering and unique undirected pairs")
  manifest$stream <- stream_info
  manifest$output_network_format <- output_network_format
  manifest$node_count <- .network_node_count(data)
  manifest$edge_count <- .network_edge_count(data)
  list(data = data, manifest = manifest)
}

.pubmed_count_with_pseudocount <- function(values) {
  vapply(strsplit(values, ";", fixed = TRUE), function(ids) {
    ids <- trimws(ids)
    length(unique(ids[nzchar(ids)])) + 0.5
  }, numeric(1))
}

.parse_pathwaycommons_total <- function(paths, entry, manifest,
    case_sensitive, min_score = NULL, n_top = NULL, greedy = TRUE,
    chunk_size = 100000L,
    output_network_format = c("igraph", "sparse", "legacy"),
    verbose = FALSE, ...) {
  .assert_flag(verbose, "verbose")
  output_network_format <- match.arg(output_network_format)
  gene_only <- function(lines) {
    !grepl("chebi:", tolower(lines), fixed = TRUE) &
      !grepl("Reference", lines, fixed = TRUE)
  }
  candidates <- .stream_network_table(paths[["interaction_table"]],
    "PARTICIPANT_A", "PARTICIPANT_B", "INTERACTION_PUBMED_ID",
    min_score = min_score, n_top = n_top, greedy = greedy,
    case_sensitive = case_sensitive, chunk_size = chunk_size,
    line_filter = gene_only,
    score_transform = .pubmed_count_with_pseudocount,
    reduce_duplicates = TRUE, zero_score_is_edge = TRUE,
    verbose = verbose)
  stream_info <- attr(candidates, "stream_info")
  data <- import_network(candidates, "from", "to", "score",
    n_top = n_top, greedy = greedy, case_sensitive = case_sensitive, verbose = FALSE,
    output_network_format = output_network_format,
    species = entry$organism, input_id_format = "hgnc_symbol")
  if (is.null(min_score) && is.null(n_top)) {
    if (!is.null(entry$expected_edges) &&
        .network_edge_count(data) != entry$expected_edges) {
      stop("The parsed Pathway Commons edge count does not match the specified release.",
        call. = FALSE)
    }
    if (!is.null(entry$expected_nodes) &&
        .network_node_count(data) != entry$expected_nodes) {
      stop("The parsed Pathway Commons node count does not match the specified release.",
        call. = FALSE)
    }
  }
  manifest$case_sensitive <- case_sensitive
  manifest$identifier_output <- entry$identifiers
  manifest$score <- list(
    name = "distinct PubMed evidence count plus 0.5",
    source_column = "INTERACTION_PUBMED_ID",
    raw_empty_count = 0,
    pseudocount = 0.5,
    empty_value = 0.5,
    zero_policy = "not applicable after adding the 0.5 pseudocount",
    row_aggregation = "distinct semicolon-delimited identifiers",
    duplicate_edge_aggregation = "maximum")
  manifest$filters <- list(min_score = min_score, n_top = n_top,
    greedy = greedy)
  manifest$extraction <- list(
    exclude = c("case-insensitive chebi:", "Reference"),
    columns = c("PARTICIPANT_A", "PARTICIPANT_B"),
    edge_handling = "lexical endpoint ordering and unique undirected pairs")
  manifest$stream <- stream_info
  manifest$output_network_format <- output_network_format
  manifest$node_count <- .network_node_count(data)
  manifest$edge_count <- .network_edge_count(data)
  list(data = data, manifest = manifest)
}

.database_parser <- function(name) {
  parsers <- list(plain_gmt = .parse_plain_gmt,
    reactome_gmt = .parse_reactome_gmt,
    scored_network = .parse_scored_network,
    genemania_combined = .parse_genemania_combined,
    pathwaycommons_intact = .parse_pathwaycommons_intact,
    pathwaycommons_total = .parse_pathwaycommons_total)
  parser <- parsers[[name]]
  if (is.null(parser)) stop("No parser is registered for this database.",
    call. = FALSE)
  parser
}

.load_database_artifact <- function(artifact, entry, case_sensitive, ...) {
  if (is.data.frame(entry)) {
    legacy <- entry
    entry <- list(id = legacy$id, version = legacy$version,
      provider = legacy$provider, type = legacy$type,
      organism = legacy$organism, identifiers = legacy$identifiers,
      edge_semantics = if ("edge_semantics" %in% names(legacy)) {
        legacy$edge_semantics
      } else "pathway membership",
      score_column = if ("score_column" %in% names(legacy)) {
        legacy$score_column
      } else NA_character_,
      source_score_column = if ("source_score_column" %in% names(legacy)) {
        legacy$source_score_column
      } else NA_character_,
      score_semantics = if ("score_semantics" %in% names(legacy)) {
        legacy$score_semantics
      } else "unscored pathway membership",
      license = legacy$license,
      terms_url = if ("terms_url" %in% names(legacy)) {
        legacy$terms_url
      } else NA_character_,
      parser = "reactome_gmt", parser_version = legacy$parser_version,
      artifacts = data.frame(role = "gene_sets", filename = basename(artifact),
        url = legacy$url, expected_bytes = legacy$expected_bytes,
        md5 = legacy$md5, stringsAsFactors = FALSE))
  }
  paths <- stats::setNames(artifact, entry$artifacts$role)
  integrity <- lapply(seq_along(paths), function(i) {
    .verify_database_artifact(paths[[i]], entry$artifacts[i, , drop = FALSE])
  })
  manifest <- .database_manifest(entry, integrity)
  .database_parser(entry$parser)(paths, entry, manifest, case_sensitive, ...)
}

#' Load a cached curated database
#'
#' Parsing is offline and verifies every cached artifact before use. Large
#' network adapters parse in chunks and may require an explicit edge filter.
#' For `pathwaycommons_hgnc`, the edge weight is the number of distinct
#' supporting PubMed publications plus a 0.5 pseudocount. Thus uncited
#' curated relations remain edges with weight 0.5; use `min_score = 2.5` to
#' require at least two publications. Selected source edge scores are stored
#' as the canonical network edge weight.
#' @inheritParams download_database
#' @param case_sensitive Preserve identifier case.
#' @param min_score Optional minimum network edge score.
#' @param n_top Optional number of highest-scoring unique network edges.
#' @param greedy Boundary-tie policy used with `n_top`. The default, `TRUE`,
#'   includes every edge tied at the score of the `n_top`th edge and can
#'   therefore return more than `n_top` edges. `FALSE` keeps only edges
#'   strictly above that boundary score and can return fewer edges. `NULL`
#'   returns exactly `n_top` edges by filling a boundary tie in alphanumeric
#'   canonical-endpoint order. The strict-size `NULL` mode is useful when
#'   benchmarked networks must contain consistent edge counts.
#' @param map_to_symbols Convert network identifiers to the species master
#'   identifier format. The default, `NULL`, enables conversion for networks
#'   and disables this network-only option for gene-set resources. GeneMANIA
#'   uses its bundled release-matched mapping. STRING and FunCoup use a cached
#'   mapping prepared by [prepare_id_mappings()]. Set this to `FALSE` only to
#'   retain provider-native identifiers.
#' @param id_mappings Optional object from [load_id_mappings()] used to convert
#'   native STRING or FunCoup identifiers. When omitted, the loader uses the
#'   verified local mapping cache and tells the user to run
#'   [prepare_id_mappings()] first if it is absent.
#' @param ambiguous,unmapped Identifier-mapping policies passed to
#'   [import_network()].
#' @param chunk_size Number of network rows parsed per chunk.
#' @param output_network_format Return curated networks as igraph objects,
#'   sparse networks, or legacy NEArender adjacency lists. Gene set databases
#'   are unaffected.
#' @param network_format Deprecated alias for `output_network_format`.
#' @param verbose Report validation, parsing progress, and final object sizes.
#' @return The loaded network or gene-set collection. Use [manifest()] to
#'   inspect its provenance and loading statistics.
#' @seealso [available_databases()], [download_database()], [import_network()],
#'   [import_gene_sets()]
#' @examples
#' \dontrun{
#' download_database("string12_human")
#' loaded <- load_database("string12_human", n_top = 1000000)
#' loaded
#' manifest(loaded)
#' }
#' @export
load_database <- function(id, version = NULL, cache_dir = NULL,
    case_sensitive = FALSE, min_score = NULL, n_top = NULL, greedy = TRUE,
    map_to_symbols = NULL, chunk_size = 100000L,
    id_mappings = NULL,
    ambiguous = c("drop", "error", "first", "expand"),
    unmapped = c("drop", "keep", "error"),
    output_network_format = c("igraph", "sparse", "legacy"),
    network_format = NULL, verbose = TRUE) {
  .assert_flag(case_sensitive, "case_sensitive")
  .validate_greedy(greedy)
  if (!is.null(map_to_symbols)) .assert_flag(map_to_symbols, "map_to_symbols")
  .assert_flag(verbose, "verbose")
  ambiguous <- match.arg(ambiguous)
  unmapped <- match.arg(unmapped)
  if (!is.null(network_format)) {
    if (!missing(output_network_format)) {
      stop("Use only output_network_format; network_format is deprecated.",
        call. = FALSE)
    }
    warning("network_format is deprecated; use output_network_format.",
      call. = FALSE)
    output_network_format <- network_format
  }
  output_network_format <- match.arg(output_network_format)
  entry <- .database_entry(id, version)
  if (is.null(map_to_symbols)) {
    map_to_symbols <- identical(entry$type, "network")
  }
  if (identical(entry$acquisition, "licensed_file")) {
    stop("KEGG pathway files are licensed, user-supplied inputs; use ",
      "import_kegg_pathways() instead.", call. = FALSE)
  }
  paths <- .database_artifact_paths(.database_cache_dir(cache_dir), entry)
  if (any(!file.exists(paths))) {
    stop("Database is not cached; call download_database() explicitly first.",
      call. = FALSE)
  }
  if (map_to_symbols && identical(entry$parser, "scored_network") &&
      is.null(id_mappings) && (!is.null(min_score) || !is.null(n_top))) {
    id_mappings <- tryCatch(load_id_mappings(entry$organism),
      error = function(error) {
        stop("Master-identifier conversion is enabled by default for ", id,
          ", but its mapping cache is unavailable. Run ",
          "prepare_id_mappings(\"", entry$organism,
          "\") once and retry, pass id_mappings = load_id_mappings(...), ",
          "or explicitly set map_to_symbols = FALSE to retain native IDs.",
          call. = FALSE)
      })
  }
  if (verbose) {
    message("Loading ", id, " (", entry$provider, " ", entry$version, ").")
    message("Verifying ", length(paths), " cached artifact",
      if (length(paths) == 1L) "." else "s.")
  }
  integrity <- lapply(seq_along(paths), function(i) {
    .verify_database_artifact(paths[[i]], entry$artifacts[i, , drop = FALSE])
  })
  manifest_path <- .database_manifest_path(dirname(paths[[1L]]), entry)
  manifest <- if (file.exists(manifest_path)) readRDS(manifest_path) else {
    .database_manifest(entry, integrity)
  }
  if (verbose) message("Parsing cached data.")
  loaded <- .database_parser(entry$parser)(paths, entry, manifest, case_sensitive,
    min_score = min_score, n_top = n_top, greedy = greedy,
    map_to_symbols = map_to_symbols,
    chunk_size = chunk_size,
    id_mappings = id_mappings, ambiguous = ambiguous, unmapped = unmapped,
    output_network_format = output_network_format, verbose = verbose)
  if (verbose) {
    if (identical(entry$type, "network")) {
      message("Loaded ", format(loaded$manifest$node_count, big.mark = ",",
        scientific = FALSE, trim = TRUE), " nodes and ",
        format(loaded$manifest$edge_count, big.mark = ",", scientific = FALSE,
          trim = TRUE), " edges.")
    } else {
      message("Loaded ", format(loaded$manifest$gene_set_count, big.mark = ",",
        scientific = FALSE, trim = TRUE), " gene sets containing ",
        format(loaded$manifest$gene_count, big.mark = ",", scientific = FALSE,
          trim = TRUE), " unique genes.")
    }
  }
  attr(loaded$data, "nearender_manifest") <- loaded$manifest
  loaded$data
}

#' Inspect a curated-database provenance manifest
#'
#' Return the manifest attached to an object loaded by [load_database()],
#' [load_network_database()], [load_geneset_database()],
#' [load_ontology_collection()], or one of the local ontology importers.
#' Objects without recorded provenance return `NULL`.
#'
#' @param x A network, gene-set, or ontology collection.
#' @return A provenance manifest list, or `NULL`.
#' @examples
#' manifest(list(pathway = c("TP53", "MDM2")))
#' @export
manifest <- function(x) attr(x, "nearender_manifest", exact = TRUE)

#' Load a cached curated network database
#'
#' Type-safe wrapper around [load_database()] with a network-specific
#' signature and master-identifier conversion enabled by default.
#' @inheritParams load_database
#' @return The loaded network. Use [manifest()] for provenance.
#' @seealso [download_network_database()], [import_network()]
#' @examples
#' \dontrun{
#' network <- load_network_database("string12_human", n_top = 1000000)
#' manifest(network)$filters
#' }
#' @export
load_network_database <- function(id, version = NULL, cache_dir = NULL,
    case_sensitive = FALSE, min_score = NULL, n_top = NULL, greedy = TRUE,
    map_to_symbols = TRUE, chunk_size = 100000L, id_mappings = NULL,
    ambiguous = c("drop", "error", "first", "expand"),
    unmapped = c("drop", "keep", "error"),
    output_network_format = c("igraph", "sparse", "legacy"),
    network_format = NULL, verbose = TRUE) {
  .assert_database_type(id, version, "network")
  if (!is.null(network_format)) {
    if (!missing(output_network_format)) {
      stop(
        "Use only `output_network_format`; `network_format` is a deprecated alias.",
        call. = FALSE
      )
    }
    warning(
      "`network_format` is deprecated; use `output_network_format`.",
      call. = FALSE
    )
    output_network_format <- network_format
    network_format <- NULL
  }
  load_database(id = id, version = version, cache_dir = cache_dir,
    case_sensitive = case_sensitive, min_score = min_score, n_top = n_top,
    greedy = greedy,
    map_to_symbols = map_to_symbols, chunk_size = chunk_size,
    id_mappings = id_mappings, ambiguous = ambiguous, unmapped = unmapped,
    output_network_format = output_network_format,
    network_format = network_format, verbose = verbose)
}

#' Load a cached curated gene-set database
#'
#' Type-safe wrapper around [load_database()] with a gene-set-specific
#' signature.
#' @inheritParams load_database
#' @return The loaded gene-set collection. Use [manifest()] for provenance.
#' @seealso [download_geneset_database()], [import_gene_sets()]
#' @examples
#' \dontrun{
#' pathways <- load_geneset_database("reactome_pathways")
#' length(pathways)
#' }
#' @export
load_geneset_database <- function(id, version = NULL, cache_dir = NULL,
    case_sensitive = FALSE, verbose = TRUE) {
  .assert_database_type(id, version, "gene_sets")
  load_database(id = id, version = version, cache_dir = cache_dir,
    case_sensitive = case_sensitive, map_to_symbols = FALSE,
    verbose = verbose)
}

# ============================================================================
# SHARED TABLE PARSING AND LOCAL IMPORT
# ============================================================================

.read_nearender_table <- function(source, header = FALSE, sep = "\t",
    comment_char = "") {
  if (is.data.frame(source) || is.matrix(source)) {
    table <- as.data.frame(source, stringsAsFactors = FALSE,
      check.names = FALSE)
  } else {
    .assert_flag(header, "header")
    if (!is.character(sep) || length(sep) != 1L || is.na(sep)) {
      stop("sep must be one character value.", call. = FALSE)
    }
    if (!is.character(comment_char) || length(comment_char) != 1L ||
        is.na(comment_char)) {
      stop("comment_char must be one character value.", call. = FALSE)
    }
    if ((is.character(source) && length(source) == 1L && !is.na(source)) ||
        inherits(source, "connection")) {
      table <- utils::read.table(source, header = header, sep = sep, quote = "",
        comment.char = comment_char, colClasses = "character",
        stringsAsFactors = FALSE, check.names = FALSE)
    } else {
      stop("source must be a file path, URL, connection, matrix, or data frame.",
        call. = FALSE)
    }
  }
  if (!nrow(table) || !ncol(table)) {
    stop("source contains no tabular data.", call. = FALSE)
  }
  table
}

.resolve_import_column <- function(table, column, argument) {
  if (is.character(column) && length(column) == 1L && !is.na(column)) {
    position <- match(column, names(table))
    if (is.na(position)) stop(argument, " does not name a source column.",
      call. = FALSE)
    return(position)
  }
  if (!is.numeric(column) || length(column) != 1L || is.na(column) ||
      column < 1 || column != as.integer(column) || column > ncol(table)) {
    stop(argument, " must identify one source column.", call. = FALSE)
  }
  as.integer(column)
}

.validate_network_filters <- function(min_score, n_top, score_column,
    min_abs_score = NULL, n_abs_top = NULL) {
  selected_filters <- sum(c(!is.null(min_score), !is.null(min_abs_score),
    !is.null(n_top), !is.null(n_abs_top)))
  if (selected_filters > 1L) {
    stop(paste0("min_score, min_abs_score, n_top, and n_abs_top are ",
      "mutually exclusive."), call. = FALSE)
  }
  if (!is.null(min_score) && (!is.numeric(min_score) ||
      length(min_score) != 1L || is.na(min_score) || !is.finite(min_score))) {
    stop("min_score must be NULL or one finite number.", call. = FALSE)
  }
  if (!is.null(min_abs_score) && (!is.numeric(min_abs_score) ||
      is.complex(min_abs_score) ||
      length(min_abs_score) != 1L || is.na(min_abs_score) ||
      !is.finite(min_abs_score) || min_abs_score < 0)) {
    stop("min_abs_score must be NULL or one finite non-negative number.",
      call. = FALSE)
  }
  if (!is.null(n_top) && (!is.numeric(n_top) || length(n_top) != 1L ||
      is.na(n_top) || n_top < 1 || n_top != as.integer(n_top))) {
    stop("n_top must be NULL or one positive integer.", call. = FALSE)
  }
  if (!is.null(n_abs_top) && (!is.numeric(n_abs_top) ||
      is.complex(n_abs_top) || length(n_abs_top) != 1L ||
      is.na(n_abs_top) || !is.finite(n_abs_top) || n_abs_top < 1 ||
      n_abs_top != as.integer(n_abs_top))) {
    stop("n_abs_top must be NULL or one positive integer.", call. = FALSE)
  }
  if (selected_filters > 0L && is.null(score_column)) {
    stop("score_column is required for edge-score filtering.", call. = FALSE)
  }
  invisible(NULL)
}

.validate_greedy <- function(greedy) {
  if (!is.null(greedy)) .assert_flag(greedy, "greedy")
  invisible(NULL)
}

.top_score_indices <- function(score, n_top, greedy = TRUE,
    from = NULL, to = NULL) {
  .validate_greedy(greedy)
  n_top <- as.integer(n_top)
  if (length(score) <= n_top) {
    return(order(score, decreasing = TRUE, method = "radix"))
  }
  pivot <- length(score) - n_top + 1L
  threshold <- sort.int(score, partial = pivot)[[pivot]]
  above <- which(score > threshold)
  tied <- which(score == threshold)
  if (is.null(greedy) && !is.null(from) && !is.null(to)) {
    tied <- tied[order(from[tied], to[tied], method = "radix")]
  }
  selected <- if (isTRUE(greedy)) {
    c(above, tied)
  } else if (identical(greedy, FALSE)) {
    above
  } else {
    c(above, utils::head(tied, n_top - length(above)))
  }
  if (!length(selected)) return(integer())
  selected[order(score[selected], decreasing = TRUE, method = "radix")]
}

.stream_network_table <- function(path, from_column, to_column,
    score_column = NULL, min_score = NULL, n_top = NULL,
    greedy = TRUE, case_sensitive = FALSE, chunk_size = 100000L,
    line_filter = NULL,
    score_transform = NULL, reduce_duplicates = FALSE,
    zero_score_is_edge = FALSE, separator = "\t", verbose = FALSE) {
  .validate_network_filters(min_score, n_top, score_column)
  .validate_greedy(greedy)
  if (!is.null(line_filter) && !is.function(line_filter)) {
    stop("line_filter must be NULL or a function.", call. = FALSE)
  }
  if (!is.null(score_transform) && !is.function(score_transform)) {
    stop("score_transform must be NULL or a function.", call. = FALSE)
  }
  .assert_flag(reduce_duplicates, "reduce_duplicates")
  .assert_flag(zero_score_is_edge, "zero_score_is_edge")
  .assert_flag(verbose, "verbose")
  if (!is.character(separator) || length(separator) != 1L ||
      is.na(separator) || !nzchar(separator)) {
    stop("separator must be one non-empty character value.", call. = FALSE)
  }
  if (!is.numeric(chunk_size) || length(chunk_size) != 1L ||
      is.na(chunk_size) || chunk_size < 1 || chunk_size != as.integer(chunk_size)) {
    stop("chunk_size must be one positive integer.", call. = FALSE)
  }
  connection <- if (grepl("\\.gz$", path, ignore.case = TRUE)) {
    gzfile(path, open = "rt")
  } else file(path, open = "rt")
  on.exit(close(connection), add = TRUE)
  heading <- readLines(connection, n = 1L, warn = FALSE)
  if (!length(heading)) stop("The network artifact is empty.", call. = FALSE)
  column_names <- strsplit(heading, separator, fixed = TRUE)[[1L]]
  positions <- vapply(list(from_column, to_column, score_column), function(x) {
    if (is.null(x)) return(NA_integer_)
    if (is.character(x)) {
      position <- match(x, column_names)
    } else {
      position <- suppressWarnings(as.integer(x))
      if (length(position) != 1L || is.na(position) || position != x ||
          position < 1L || position > length(column_names)) position <- NA_integer_
    }
    position
  }, integer(1))
  if (anyNA(positions[seq_len(if (is.null(score_column)) 2L else 3L)])) {
    stop("Network columns do not match the artifact header.", call. = FALSE)
  }
  use_scan_parser <- is.null(line_filter) && is.null(score_transform)
  scan_template <- rep(list(NULL), length(column_names))
  if (use_scan_parser) {
    selected_positions <- unique(positions[!is.na(positions)])
    scan_template[selected_positions] <- rep(list(""), length(selected_positions))
  }

  chunks <- list()
  rows_read <- 0L
  malformed_rows <- 0L
  invalid_score_rows <- 0L
  zero_score_rows <- 0L
  filtered_score_rows <- 0L
  invalid_endpoint_rows <- 0L
  filtered_line_rows <- 0L
  next_progress_row <- 1000000
  repeat {
    if (use_scan_parser) {
      fields <- scan(connection, what = scan_template, sep = separator,
        quote = "", comment.char = "", nlines = as.integer(chunk_size),
        quiet = TRUE, fill = TRUE, flush = TRUE, multi.line = FALSE,
        blank.lines.skip = TRUE)
      from <- fields[[positions[[1L]]]]
      if (!length(from)) break
      to <- fields[[positions[[2L]]]]
      rows_read <- rows_read + length(from)
      raw_score <- if (is.null(score_column)) NULL else {
        fields[[positions[[3L]]]]
      }
    } else {
      lines <- readLines(connection, n = as.integer(chunk_size), warn = FALSE)
      if (!length(lines)) break
      rows_read <- rows_read + length(lines)
      if (!is.null(line_filter)) {
        keep_line <- line_filter(lines)
        if (!is.logical(keep_line) || length(keep_line) != length(lines) ||
            anyNA(keep_line)) {
          stop("line_filter must return one non-missing logical per line.",
            call. = FALSE)
        }
        filtered_line_rows <- filtered_line_rows + sum(!keep_line)
        lines <- lines[keep_line]
        if (!length(lines)) next
      }
      nonempty <- lines[nzchar(lines)]
      fields <- lapply(strsplit(paste0(nonempty, separator, "."), separator,
        fixed = TRUE), function(x) x[-length(x)])
      needed <- max(positions, na.rm = TRUE)
      malformed_rows <- malformed_rows + sum(lengths(fields) < needed)
      fields <- fields[lengths(fields) >= needed]
      if (!length(fields)) next
      from <- vapply(fields, `[[`, character(1), positions[[1L]])
      to <- vapply(fields, `[[`, character(1), positions[[2L]])
      raw_score <- if (is.null(score_column)) NULL else {
        vapply(fields, `[[`, character(1), positions[[3L]])
      }
    }
    if (verbose && rows_read >= next_progress_row) {
      message("Read ", format(rows_read, big.mark = ",", scientific = FALSE,
        trim = TRUE), " network rows...")
      while (next_progress_row <= rows_read) {
        next_progress_row <- next_progress_row + 1000000
      }
    }
    part <- data.frame(from = from, to = to, stringsAsFactors = FALSE)
    if (!is.null(score_column)) {
      transformed <- if (is.null(score_transform)) {
        suppressWarnings(as.numeric(raw_score))
      } else score_transform(raw_score)
      if (!is.numeric(transformed) || length(transformed) != length(raw_score)) {
        stop("score_transform must return one numeric value per edge score.",
          call. = FALSE)
      }
      part$score <- suppressWarnings(as.numeric(transformed))
      valid_score <- !is.na(part$score) & is.finite(part$score)
      invalid_score_rows <- invalid_score_rows + sum(!valid_score)
      zero_score <- valid_score & part$score == 0
      zero_score_rows <- zero_score_rows + sum(zero_score)
      if (!zero_score_is_edge) valid_score <- valid_score & !zero_score
      if (!is.null(min_score)) {
        filtered_score_rows <- filtered_score_rows +
          sum(valid_score & part$score < min_score)
        valid_score <- valid_score & part$score >= min_score
      }
      part <- part[valid_score, , drop = FALSE]
    }
    if (!nrow(part)) next
    part$from <- .canonical_ids(part$from, case_sensitive)
    part$to <- .canonical_ids(part$to, case_sensitive)
    valid <- !is.na(part$from) & nzchar(part$from) & !is.na(part$to) &
      nzchar(part$to) & part$from != part$to
    invalid_endpoint_rows <- invalid_endpoint_rows + sum(!valid)
    part <- part[valid, , drop = FALSE]
    if (!nrow(part)) next
    if (reduce_duplicates) {
      part <- .canonical_network_edges(part, "from", "to",
        score_column = if (is.null(score_column)) NULL else "score",
        case_sensitive = case_sensitive, warn_repairs = FALSE,
        zero_score_is_edge = zero_score_is_edge)
    }
    if (!is.null(n_top) && nrow(part) > n_top) {
      part <- part[.top_score_indices(part$score, n_top, greedy,
        part$from, part$to), , drop = FALSE]
    }
    chunks[[length(chunks) + 1L]] <- part
    if (reduce_duplicates && is.null(n_top) && length(chunks) >= 8L) {
      candidates <- do.call(rbind, chunks)
      reduced <- .canonical_network_edges(candidates, "from", "to",
        score_column = if (is.null(score_column)) NULL else "score",
        case_sensitive = case_sensitive, warn_repairs = FALSE,
        zero_score_is_edge = zero_score_is_edge)
      chunks <- list(reduced)
    }
    if (!is.null(n_top) && sum(vapply(chunks, nrow, integer(1))) > 2L * n_top) {
      candidates <- do.call(rbind, chunks)
      reduced <- .canonical_network_edges(candidates, "from", "to", "score",
        n_top = n_top, greedy = greedy, case_sensitive = case_sensitive,
        warn_repairs = FALSE, zero_score_is_edge = zero_score_is_edge)
      chunks <- list(reduced)
    }
  }
  if (!length(chunks)) stop("No network edges satisfy the import filters.",
    call. = FALSE)
  result <- do.call(rbind, chunks)
  if (reduce_duplicates) {
    result <- .canonical_network_edges(result, "from", "to",
      score_column = if (is.null(score_column)) NULL else "score",
      case_sensitive = case_sensitive, warn_repairs = FALSE,
        zero_score_is_edge = zero_score_is_edge)
  }
  rownames(result) <- NULL
  attr(result, "nearender_zero_score_is_edge") <- zero_score_is_edge
  attr(result, "stream_info") <- list(rows_read = rows_read,
    candidate_rows = nrow(result), malformed_rows = malformed_rows,
    invalid_score_rows = invalid_score_rows,
    zero_score_rows = zero_score_rows,
    filtered_score_rows = filtered_score_rows,
    invalid_endpoint_rows = invalid_endpoint_rows,
    filtered_line_rows = filtered_line_rows,
    chunk_size = as.integer(chunk_size))
  result
}

.network_value_labels <- function(x) {
  x <- as.character(x)
  x[is.na(x)] <- "<NA>"
  x[!nzchar(x)] <- "<empty>"
  x
}

.network_edge_examples <- function(from, to, rows, score = NULL,
    limit = 5L) {
  rows <- utils::head(which(rows), limit)
  if (!length(rows)) return("")
  labels <- paste0(.network_value_labels(from[rows]), "--",
    .network_value_labels(to[rows]))
  if (!is.null(score)) {
    labels <- paste0(labels, " [edge score=",
      .network_value_labels(score[rows]), "]")
  }
  paste(labels, collapse = ", ")
}

.warn_network_repair <- function(rows, problem, from, to, score = NULL) {
  count <- sum(rows)
  if (!count) return(invisible(NULL))
  warning(problem, ": ", count, " row", if (count == 1L) "" else "s",
    "; examples: ", .network_edge_examples(from, to, rows, score),
    call. = FALSE)
  invisible(NULL)
}

.canonical_network_edges <- function(table, from_column = 1L, to_column = 2L,
    score_column = NULL, min_score = NULL, n_top = NULL,
    greedy = TRUE, case_sensitive = FALSE, warn_repairs = TRUE,
    zero_score_is_edge = FALSE, min_abs_score = NULL, n_abs_top = NULL) {
  .validate_network_filters(min_score, n_top, score_column, min_abs_score,
    n_abs_top)
  .validate_greedy(greedy)
  .assert_flag(warn_repairs, "warn_repairs")
  .assert_flag(zero_score_is_edge, "zero_score_is_edge")
  from_column <- .resolve_import_column(table, from_column, "from_column")
  to_column <- .resolve_import_column(table, to_column, "to_column")
  raw_from <- table[[from_column]]
  raw_to <- table[[to_column]]
  from <- .canonical_ids(raw_from, case_sensitive)
  to <- .canonical_ids(raw_to, case_sensitive)
  valid_endpoint <- !is.na(from) & nzchar(from) & !is.na(to) & nzchar(to)
  .warn_network_repair(!valid_endpoint,
    "Dropped network rows with missing or empty endpoint identifiers",
    raw_from, raw_to)
  self_link <- valid_endpoint & from == to
  if (warn_repairs) {
    .warn_network_repair(self_link,
      "Removed self-links from the undirected network", raw_from, raw_to)
  }
  valid <- valid_endpoint & from != to

  score <- NULL
  if (!is.null(score_column)) {
    score_column <- .resolve_import_column(table, score_column, "score_column")
    raw_score <- table[[score_column]]
    score <- suppressWarnings(as.numeric(raw_score))
    valid_score <- !is.na(score) & is.finite(score)
    .warn_network_repair(valid & !valid_score,
      "Dropped network rows with non-finite or nonnumeric edge scores",
      raw_from, raw_to, raw_score)
    zero_score <- valid & valid_score & score == 0
    if (!zero_score_is_edge && warn_repairs) {
      .warn_network_repair(zero_score,
        "Skipped custom-network rows with edge score 0 (interpreted as no edge)",
        raw_from, raw_to, raw_score)
    }
    valid <- valid & valid_score & (zero_score_is_edge | score != 0)
  }
  from <- from[valid]
  to <- to[valid]
  if (!length(from)) stop("No non-self network edges remain.", call. = FALSE)
  first <- ifelse(from <= to, from, to)
  second <- ifelse(from <= to, to, from)

  if (is.null(score_column)) {
    edges <- unique(data.frame(from = first, to = second,
      stringsAsFactors = FALSE))
  } else {
    score <- score[valid]
    absolute_filter <- !is.null(min_abs_score) || !is.null(n_abs_top)
    edge_key <- paste(first, second, sep = "\r")
    duplicate_key <- duplicated(edge_key) | duplicated(edge_key,
      fromLast = TRUE)
    if (warn_repairs && any(duplicate_key)) {
      score_by_edge <- split(score[duplicate_key], edge_key[duplicate_key])
      conflicting_keys <- names(Filter(function(values) {
        length(unique(values)) > 1L
      }, score_by_edge))
      conflicting <- duplicate_key & edge_key %in% conflicting_keys
      if (any(conflicting)) {
        warning(
          "Collapsed duplicate or reciprocal network rows with different ",
          "edge scores, retaining the highest ",
          if (absolute_filter) "absolute " else "", "score: ",
          sum(conflicting), " rows across ", length(conflicting_keys),
          " unique edge", if (length(conflicting_keys) == 1L) "" else "s",
          "; examples: ", .network_edge_examples(
            raw_from[valid], raw_to[valid], conflicting, score),
          call. = FALSE
        )
      }
    }
    if (!any(duplicate_key)) {
      edges <- data.frame(from = first, to = second, score = score,
        stringsAsFactors = FALSE)
    } else {
      unique_keys <- unique(edge_key)
      ranking_score <- if (absolute_filter) abs(score) else score
      ranked <- order(ranking_score, decreasing = TRUE, method = "radix")
      best <- ranked[!duplicated(edge_key[ranked])]
      keep <- best[order(match(edge_key[best], unique_keys), method = "radix")]
      edges <- data.frame(from = first[keep], to = second[keep],
        score = score[keep], stringsAsFactors = FALSE)
    }
    if (!is.null(min_score)) edges <- edges[edges$score >= min_score, , drop = FALSE]
    if (!is.null(min_abs_score)) {
      edges <- edges[abs(edges$score) >= min_abs_score, , drop = FALSE]
    }
    if (!is.null(n_top)) {
      edges <- edges[.top_score_indices(edges$score, n_top, greedy,
        edges$from, edges$to), , drop = FALSE]
    }
    if (!is.null(n_abs_top)) {
      edges <- edges[.top_score_indices(abs(edges$score), n_abs_top, greedy,
        edges$from, edges$to), , drop = FALSE]
    }
  }
  rownames(edges) <- NULL
  if (!nrow(edges)) stop("No network edges satisfy the import filters.",
    call. = FALSE)
  edges
}

.legacy_network_from_edges <- function(edges, case_sensitive) {
  nodes <- unique(c(edges$from, edges$to))
  from_rows <- split(seq_len(nrow(edges)),
    factor(edges$from, levels = nodes), drop = FALSE)
  to_rows <- split(seq_len(nrow(edges)),
    factor(edges$to, levels = nodes), drop = FALSE)
  links <- lapply(seq_along(nodes), function(i) {
    c(edges$to[from_rows[[i]]], edges$from[to_rows[[i]]])
  })
  names(links) <- nodes
  result <- list(links = links, Ntotal = nrow(edges))
  if ("score" %in% names(edges)) {
    weights <- lapply(seq_along(nodes), function(i) {
      adjacent <- c(edges$to[from_rows[[i]]], edges$from[to_rows[[i]]])
      values <- c(edges$score[from_rows[[i]]], edges$score[to_rows[[i]]])
      stats::setNames(values, adjacent)
    })
    names(weights) <- nodes
    result$weights <- weights
  }
  .mark_normalized(result, case_sensitive)
}

.igraph_network_from_edges <- function(edges, case_sensitive) {
  if ("score" %in% names(edges)) names(edges)[names(edges) == "score"] <- "weight"
  graph <- igraph::graph_from_data_frame(edges, directed = FALSE)
  graph <- igraph::set_graph_attr(graph, "Ntotal", value = nrow(edges))
  graph <- igraph::set_graph_attr(graph, "nearender_case_sensitive",
    value = case_sensitive)
  .mark_normalized(graph, case_sensitive)
}

#' Import altered or functional gene sets
#'
#' Read a tabular altered gene set (AGS) or functional gene set (FGS) source
#' into the named-list representation used by NEArender. In grouped layout,
#' each row associates one gene or protein identifier with a sample, pathway,
#' or other set identifier. Single-set layout combines all genes into one set;
#' single-gene layout creates one set per distinct gene.
#'
#' Gene identifiers are unique within each set and are matched
#' case-insensitively by default. Set names retain their submitted spelling.
#' In `layout = "grouped"`, each distinct `set_column` value creates one list
#' element. `layout = "single_set"` combines the selected gene column into one
#' set named by `set_name`. `layout = "single_gene"` creates one single-member
#' set per distinct identifier; this can be used to treat network genes as FGSs
#' in NEA, whereas overlap-based ORA has no analogous edge-enrichment use.
#'
#' @param source File path, URL, connection, matrix, or data frame.
#' @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,
#'   identifiers are converted to its species master format.
#' @param ambiguous,unmapped Mapping policies passed to [map_identifiers()].
#' @param gene_column Name or one-based index of the gene/protein column.
#' @param set_column Name or one-based index of the set column. Required for
#'   `layout = "grouped"` and ignored by the other layouts.
#' @param mask Optional POSIX regular expression passed to [grepl()] to retain
#'   set names in grouped layout. For example, `"^keep_"` matches a prefix,
#'   `"_pathway$"` matches a suffix, and `"first|second"` matches either
#'   alternative. Escape regular-expression metacharacters when matching them
#'   literally. The default, `NULL`, retains every set.
#' @param layout Input organization: `"grouped"`, `"single_set"`, or
#'   `"single_gene"`.
#' @param set_name Name used for `layout = "single_set"`.
#' @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 case_sensitive Preserve case when matching gene identifiers.
#' @return A named list whose elements contain unique gene identifiers, with
#'   normalization metadata available through [normalization_info()].
#' @seealso [save_gs_list()], [import_kegg_pathways()], [load_geneset_database()],
#'   [samples2ags()], [mutations2ags()]
#' @export
#' @examples
#' table <- data.frame(gene = c("A", "B", "C"),
#'   pathway = c("first", "first", "second"))
#' import_gene_sets(table, "gene", "pathway", species = "human")
#' import_gene_sets(table, "gene", "pathway", mask = "^first$",
#'   species = "human")
#' one_column <- data.frame(gene = c("A", "B", "C"))
#' import_gene_sets(one_column, layout = "single_set", set_name = "panel",
#'   species = "human")

import_gene_sets <- function(source, gene_column = 1L, set_column = 2L,
    layout = c("grouped", "single_set", "single_gene"),
    set_name = "user_set", header = FALSE, sep = "\t", comment_char = "",
    case_sensitive = FALSE, mask = NULL, species,
    input_id_format = master_id_format(species),
    id_mappings = NULL, ambiguous = c("error", "drop", "first", "expand"),
    unmapped = c("keep", "drop", "error")) {
  layout <- match.arg(layout)
  ambiguous <- match.arg(ambiguous)
  unmapped <- match.arg(unmapped)
  .assert_flag(case_sensitive, "case_sensitive")
  identity <- .resolve_input_identity(species, input_id_format, id_mappings)
  table <- .read_nearender_table(source, header, sep, comment_char)
  gene_column <- .resolve_import_column(table, gene_column, "gene_column")
  mapped <- .map_input_rows(table[[gene_column]], identity, id_mappings,
    ambiguous, unmapped, case_sensitive)
  table <- table[mapped$source_row, , drop = FALSE]
  genes <- .canonical_ids(mapped$ids, case_sensitive)
  if (!is.null(mapped$mapping_info)) {
    identity$mapping$statistics <- mapped$mapping_info
  }
  finish <- function(result) {
    result <- .mark_normalized(result, case_sensitive)
    .attach_identifier_metadata(result, identity)
  }
  valid_gene <- !is.na(genes) & nzchar(genes)
  if (!any(valid_gene)) stop("The gene column contains no identifiers.",
    call. = FALSE)

  if (layout == "single_gene") {
    genes <- unique(genes[valid_gene])
    result <- as.list(genes)
    names(result) <- genes
    return(finish(result))
  }
  if (layout == "single_set") {
    if (!is.character(set_name) || length(set_name) != 1L || is.na(set_name) ||
        !nzchar(set_name)) {
      stop("set_name must be one non-empty character value.", call. = FALSE)
    }
    result <- stats::setNames(list(unique(genes[valid_gene])), set_name)
    return(finish(result))
  }

  set_column <- .resolve_import_column(table, set_column, "set_column")
  sets <- as.character(table[[set_column]])
  valid <- valid_gene & !is.na(sets) & nzchar(sets)
  if (!is.null(mask)) {
    if (!is.character(mask) || length(mask) != 1L || is.na(mask)) {
      stop("mask must be NULL or one character value.", call. = FALSE)
    }
    valid <- valid & grepl(mask, sets)
  }
  if (!any(valid)) stop("No rows contain both gene and set identifiers.",
    call. = FALSE)
  result <- split(genes[valid], factor(sets[valid], levels = unique(sets[valid])))
  finish(lapply(result, unique))
}

.map_network_table <- function(table, from_position, to_position, identity,
    id_mappings, ambiguous, unmapped, case_sensitive) {
  raw_from <- as.character(table[[from_position]])
  raw_to <- as.character(table[[to_position]])
  nodes <- unique(c(raw_from, raw_to))
  lookup <- .identifier_mapping_lookup(id_mappings,
    identity$input_id_format, case_sensitive)
  mapped <- .map_input_rows(nodes, identity, id_mappings, ambiguous, unmapped,
    case_sensitive, lookup = lookup)
  groups <- split(mapped$ids,
    factor(mapped$source_row, levels = seq_along(nodes)), drop = FALSE)
  group_lengths <- lengths(groups)
  from_index <- match(raw_from, nodes)
  to_index <- match(raw_to, nodes)
  from_lengths <- group_lengths[from_index]
  to_lengths <- group_lengths[to_index]
  retained <- from_lengths > 0L & to_lengths > 0L
  if (!any(retained)) {
    stop("No network endpoints remain after identifier mapping.",
      call. = FALSE)
  }

  single_value <- rep(NA_character_, length(nodes))
  singleton <- group_lengths == 1L
  single_value[singleton] <- vapply(groups[singleton], `[[`, character(1), 1L)
  simple_rows <- which(retained & from_lengths == 1L & to_lengths == 1L)
  complex_rows <- which(retained & (from_lengths > 1L | to_lengths > 1L))
  parts <- list()
  source_rows <- list()
  if (length(simple_rows)) {
    simple <- table[simple_rows, , drop = FALSE]
    simple[[from_position]] <- single_value[from_index[simple_rows]]
    simple[[to_position]] <- single_value[to_index[simple_rows]]
    parts[[length(parts) + 1L]] <- simple
    source_rows[[length(source_rows) + 1L]] <- simple_rows
  }
  if (length(complex_rows)) {
    left <- groups[from_index[complex_rows]]
    right <- groups[to_index[complex_rows]]
    left_lengths <- lengths(left)
    right_lengths <- lengths(right)
    expansion_sizes <- left_lengths * right_lengths
    expanded_rows <- rep(complex_rows, times = expansion_sizes)
    expanded <- table[expanded_rows, , drop = FALSE]
    expanded[[from_position]] <- unlist(Map(function(values, times) {
      rep(values, times = times)
    }, left, right_lengths), use.names = FALSE)
    expanded[[to_position]] <- unlist(Map(function(values, each) {
      rep(values, each = each)
    }, right, left_lengths), use.names = FALSE)
    parts[[length(parts) + 1L]] <- expanded
    source_rows[[length(source_rows) + 1L]] <- expanded_rows
  }
  result <- if (length(parts) == 1L) parts[[1L]] else do.call(rbind, parts)
  original_order <- unlist(source_rows, use.names = FALSE)
  result <- result[order(original_order, method = "radix"), , drop = FALSE]
  rownames(result) <- NULL

  ambiguous_node <- rep(FALSE, length(nodes))
  ambiguous_node[mapped$ambiguous_source_row] <- TRUE
  unmapped_node <- rep(FALSE, length(nodes))
  unmapped_node[mapped$unmapped_source_row] <- TRUE
  side_statistics <- function(raw, index) {
    info <- mapped$mapping_info
    valid <- !is.na(raw) & nzchar(raw)
    info$input_count <- sum(valid)
    info$output_count <- sum(group_lengths[index[valid]])
    info$ambiguous_count <- sum(ambiguous_node[index[valid]])
    info$unmapped_count <- sum(unmapped_node[index[valid]])
    info
  }
  list(table = result,
    from_statistics = side_statistics(raw_from, from_index),
    to_statistics = side_statistics(raw_to, to_index))
}

#' Legacy gene-set importer
#'
#' @param tbl,lowercase,col_gene,col_set,gs_type Legacy arguments. The modern
#'   `header` argument is shared by both interfaces.
#' @rdname import_gene_sets
#' @export
import.gs <- function(tbl, lowercase = 1, col_gene = 2, col_set = 3,
    gs_type = "", header = FALSE) {
  .Deprecated("import_gene_sets")
  if (!is.numeric(lowercase) || length(lowercase) != 1L || is.na(lowercase)) {
    stop("lowercase must be one numeric value.", call. = FALSE)
  }
  layout <- if (col_set > 0) "grouped" else if (col_set < 0) {
    "single_gene"
  } else "single_set"
  import_gene_sets(tbl, gene_column = col_gene, set_column = max(1, col_set),
    layout = layout, set_name = paste0("users_single_", gs_type, "gs"),
    header = header, case_sensitive = lowercase <= 0,
    species = NULL, input_id_format = "legacy_custom")
}

#' Legacy network importer
#'
#' `import.net()` is retained for compatibility with legacy NEArender scripts.
#' New code should use [import_network()], which has explicit input-column and
#' output-format arguments.
#'
#' @param tbl,lowercase,col_1,col_2,col_score,min_score,n_top,echo Legacy
#'   arguments.
#' @return A legacy NEArender network list with `links` and `Ntotal`.
#' @seealso [import_network()]
#' @export
import.net <- function(tbl, lowercase = 1, col_1 = 1, col_2 = 2,
    col_score = 3, min_score = NA, n_top = NA, echo = 1) {
  .Deprecated("import_network")
  score_column <- if (col_score > 0) col_score else NULL
  import_network(tbl, from_column = col_1, to_column = col_2,
    score_column = score_column,
    min_score = if (length(min_score) == 1L && is.na(min_score)) NULL else min_score,
    n_top = if (length(n_top) == 1L && is.na(n_top)) NULL else n_top,
    case_sensitive = lowercase <= 0, verbose = echo > 0,
    output_network_format = "legacy", species = NULL,
    input_id_format = "legacy_custom")
}

# ============================================================================
# GENE-SET SERIALIZATION
# ============================================================================

#' Save a gene-set list in two-column text format
#'
#' Each output row represents one gene or protein and the altered or functional
#' gene set to which it belongs. The tab-delimited file representation can be
#' read by tools that accept NEArender group files, including EviNet. Vector and
#' matrix return modes expose the same representation without writing a file.
#'
#' @param gs_list Named list of gene identifier vectors.
#' @param file Output file path. This must be supplied explicitly when
#'   `output = "file"`; it is ignored for the non-writing return modes.
#' @param output Return mode: `"file"`, `"vector"`, or `"matrix"`. File
#'   output is the default, but no default path is assumed.
#' @return For file output, the normalized path invisibly; otherwise a named
#'   gene vector or a two-column `gene`-by-`group` character matrix.
#' @references Alexeyenko A et al. (2012). \doi{10.1186/1471-2105-13-226}.
#'   Jeggari A, Alexeyenko A (2017). \doi{10.1186/s12859-017-1534-y}.
#'   Jeggari A et al. (2018). \doi{10.1093/nar/gky485}.
#' @seealso [import_gene_sets()], [samples2ags()], [mutations2ags()]
#' @examples
#' sets <- list(first = c("A", "B"), second = c("C", "D"))
#' save_gs_list(sets, output = "matrix")
#' group_file <- tempfile(fileext = ".groups")
#' save_gs_list(sets, file = group_file)
#' unlink(group_file)
#' @export
save_gs_list <- function(gs_list, file = NULL,
                         output = c("file", "vector", "matrix")) {
  output <- match.arg(output)
  table <- .gene_set_table(gs_list)
  if (output == "file") {
    if (!is.character(file) || length(file) != 1L || is.na(file) ||
        !nzchar(file)) {
      stop("file must be supplied when output = \"file\".", call. = FALSE)
    }
    utils::write.table(table, file, quote = FALSE, sep = "\t",
                       row.names = FALSE, col.names = FALSE, na = "NA")
    return(invisible(normalizePath(file, mustWork = FALSE)))
  }
  if (output == "vector") {
    result <- table[, 2L]
    names(result) <- table[, 1L]
    return(result)
  }
  table
}
.gene_set_table <- function(gs_list) {
  if (!is.list(gs_list) || is.null(names(gs_list)) ||
      anyNA(names(gs_list)) || any(names(gs_list) == "")) {
    stop("gs_list must be a named list.", call. = FALSE)
  }
  if (any(!vapply(gs_list, is.atomic, logical(1)))) {
    stop("Each gene set must be an atomic vector.", call. = FALSE)
  }
  genes <- unlist(lapply(gs_list, as.character), use.names = FALSE)
  groups <- rep(names(gs_list), lengths(gs_list))
  matrix(c(genes, groups), ncol = 2L,
         dimnames = list(NULL, c("gene", "group")))
}
# Retained internally for the evinet.org backend.
save.gs.list <- function(gs_list, file = NULL,
                         scale = c("-1...+1", "original", "inRange",
                                   "zeroPreserved"),
                         scale_max = NULL, scale_min = NULL,
                         attributes = FALSE, shape = NA) {
  scale <- match.arg(scale)
  if (!is.character(file) || length(file) != 1L || is.na(file) ||
      !nzchar(file)) {
    stop("file must be supplied explicitly.", call. = FALSE)
  }
  if (scale == "inRange" &&
      (is.null(scale_max) || is.null(scale_min) || scale_max <= scale_min)) {
    stop("inRange requires scale_max > scale_min.", call. = FALSE)
  }
  if (scale != "inRange" &&
      (!is.null(scale_max) || !is.null(scale_min))) {
    stop("scale_max and scale_min are only used with inRange.", call. = FALSE)
  }
  if (!attributes) {
    table <- .gene_set_table(gs_list)
  } else {
    rows <- lapply(names(gs_list), function(group) {
      values <- gs_list[[group]]
      scaled <- switch(scale, original = values,
        `-1...+1` = 2 * (values - max(values, na.rm = TRUE)) /
          diff(range(values, na.rm = TRUE)) + 1,
        inRange = 2 * (values - scale_max) / (scale_max - scale_min) + 1,
        zeroPreserved = sign(values) * values /
          ifelse(values >= 0, max(values, na.rm = TRUE),
                 min(values, na.rm = TRUE)))
      cbind(names(values), group, scaled, shape)
    })
    table <- do.call(rbind, rows)
  }
  utils::write.table(table, file, quote = FALSE, sep = "\t",
                     row.names = FALSE, col.names = FALSE, na = "NA")
  invisible(normalizePath(file, mustWork = FALSE))
}

# ============================================================================
# NETWORK CONVERSION AND FILE EXCHANGE
# ============================================================================

.network_edge_count <- function(network) {
  if (igraph::is_igraph(network)) return(igraph::ecount(network))
  if (inherits(network, "nearender_indexed_network")) return(network$n_edges)
  network$Ntotal
}

.network_node_count <- function(network) {
  if (igraph::is_igraph(network)) return(igraph::vcount(network))
  if (inherits(network, "nearender_indexed_network")) {
    return(length(network$node_names))
  }
  length(network$links)
}

#' Convert a network to igraph
#'
#' Convert legacy NEArender adjacency lists or indexed sparse networks to a
#' simple undirected igraph object. A selected source edge score or legacy
#' weight is stored in the canonical igraph `weight` edge attribute. The
#' stored legacy edge count is checked against the topology.
#'
#' @param network An igraph, sparse matrix, legacy NEArender, or indexed
#'   NEArender network.
#' @param case_sensitive Preserve identifier case.
#' @return A simple undirected igraph object.
#' @seealso [as_sparse_network()], [as_nearender_network()], [convert_network()]
#' @examples
#' legacy <- list(links = list(a = "b", b = "a"), Ntotal = 1,
#'   weights = list(a = c(b = 2), b = c(a = 2)))
#' graph <- as_igraph_network(legacy)
#' igraph::edge_attr(graph, "weight")
#' @export
as_igraph_network <- function(network, case_sensitive = FALSE) {
  .assert_flag(case_sensitive, "case_sensitive")
  if (inherits(network, "Matrix")) {
    if (nrow(network) != ncol(network)) {
      stop("A sparse network matrix must be square.", call. = FALSE)
    }
    node_names <- rownames(network)
    if (is.null(node_names) || is.null(colnames(network)) ||
        !identical(node_names, colnames(network)) || anyNA(node_names) ||
        any(!nzchar(node_names))) {
      stop("A sparse network matrix must have identical, non-empty row and column names.",
        call. = FALSE)
    }
    entries <- Matrix::summary(methods::as(network, "CsparseMatrix"))
    edges <- data.frame(
      from = node_names[entries$i],
      to = node_names[entries$j],
      score = entries$x,
      stringsAsFactors = FALSE
    )
    edges <- .canonical_network_edges(edges, "from", "to", "score",
      case_sensitive = case_sensitive)
    return(.copy_identifier_metadata(
      .igraph_network_from_edges(edges, case_sensitive), network))
  }
  if (igraph::is_igraph(network)) {
    edge_attributes <- igraph::edge_attr_names(network)
    if (.already_normalized(network, case_sensitive) &&
        !"score" %in% edge_attributes) return(network)
    .assert_reversible_case_policy(network, case_sensitive, "network")
    graph <- network
    if (igraph::is_directed(network)) {
      warning("Converted a directed igraph network with ",
        igraph::ecount(graph), " edges to undirected form; reciprocal edges ",
        "will be collapsed.", call. = FALSE)
      graph <- igraph::as_undirected(graph, mode = "each")
    }
    node_names <- igraph::vertex_attr(graph, "name")
    invalid_names <- if (is.null(node_names)) {
      rep(TRUE, igraph::vcount(graph))
    } else is.na(node_names) | !nzchar(node_names)
    if (any(invalid_names)) {
      positions <- which(invalid_names)
      before_edges <- igraph::ecount(graph)
      graph <- igraph::delete_vertices(graph, positions)
      warning("Removed ", length(positions),
        " igraph vertices with missing or empty names (vertex positions: ",
        paste(utils::head(positions, 5L), collapse = ", "),
        if (length(positions) > 5L) ", ..." else "", ") and ",
        before_edges - igraph::ecount(graph), " incident edges.",
        call. = FALSE)
    }
    if (!igraph::vcount(graph) || !igraph::ecount(graph)) {
      stop("No network edges remain after removing invalid igraph vertices.",
        call. = FALSE)
    }
    node_names <- .canonical_ids(node_names, case_sensitive)
    node_names <- node_names[!invalid_names]
    edge_attributes <- igraph::edge_attr_names(graph)
    weight_attribute <- if ("weight" %in% edge_attributes) {
      "weight"
    } else if ("score" %in% edge_attributes) {
      "score"
    } else NULL
    if (!is.null(weight_attribute)) {
      raw_weight <- igraph::edge_attr(graph, weight_attribute)
      weight <- suppressWarnings(as.numeric(raw_weight))
      invalid_weight <- is.na(weight) | !is.finite(weight)
      edge_table <- igraph::as_data_frame(graph, what = "edges")
      if (any(invalid_weight)) {
        warning("Dropped ", sum(invalid_weight),
          " igraph edges with non-finite or nonnumeric edge weights; examples: ",
          .network_edge_examples(edge_table$from, edge_table$to,
            invalid_weight, raw_weight), call. = FALSE)
      }
      retained_weight <- !invalid_weight
      graph <- igraph::delete_edges(graph, which(!retained_weight))
      weight <- weight[retained_weight]
      if (!igraph::ecount(graph)) {
        stop("No network edges remain after validating igraph edge weights.",
          call. = FALSE)
      }
      graph <- igraph::set_edge_attr(graph, "weight", value = weight)
    }
    if ("score" %in% igraph::edge_attr_names(graph)) {
      graph <- igraph::delete_edge_attr(graph, "score")
    }
    duplicate_groups <- split(seq_along(node_names), node_names)
    duplicate_groups <- duplicate_groups[lengths(duplicate_groups) > 1L]
    if (length(duplicate_groups)) {
      original_names <- igraph::vertex_attr(graph, "name")
      examples <- vapply(utils::head(duplicate_groups, 5L), function(group) {
        paste0(paste(unique(original_names[group]), collapse = "/"), " -> ",
          node_names[group[[1L]]])
      }, character(1))
      warning("Collapsed ", sum(lengths(duplicate_groups) - 1L),
        " igraph vertices whose names collide under the identifier case ",
        "policy; examples: ", paste(examples, collapse = ", "),
        call. = FALSE)
      graph <- igraph::set_vertex_attr(graph, "name", value = node_names)
      mapping <- match(node_names, unique(node_names))
      graph <- igraph::contract(graph, mapping,
        vertex.attr.comb = list(name = "first", ".default" = "first"))
    } else {
      graph <- igraph::set_vertex_attr(graph, "name", value = node_names)
    }
    graph <- igraph::simplify(graph, remove.multiple = TRUE,
      remove.loops = TRUE,
      edge.attr.comb = list(weight = "max", ".default" = "first"))
    graph <- igraph::set_graph_attr(graph, "Ntotal",
      value = igraph::ecount(graph))
    graph <- igraph::set_graph_attr(graph, "nearender_case_sensitive",
      value = case_sensitive)
    return(.copy_identifier_metadata(
      .mark_normalized(graph, case_sensitive), network))
  }

  if (inherits(network, "nearender_indexed_network")) {
    entries <- methods::as(network$adjacency, "TsparseMatrix")
    from <- network$node_names[methods::slot(entries, "i") + 1L]
    to <- network$node_names[methods::slot(entries, "j") + 1L]
    table <- data.frame(from = from, to = to, stringsAsFactors = FALSE)
    score_column <- NULL
    stored_weights <- network$weights
    if (is.null(stored_weights) && !is.null(network$scores)) {
      warning("The sparse-network `scores` field is deprecated; converting it ",
        "to `weights`.", call. = FALSE)
      stored_weights <- network$scores
    }
    if (!is.null(stored_weights)) {
      weight_values <- as.numeric(stored_weights[cbind(
        methods::slot(entries, "i") + 1L,
        methods::slot(entries, "j") + 1L
      )])
      table$score <- weight_values
      score_column <- "score"
    }
    edges <- .canonical_network_edges(table, "from", "to", score_column,
      case_sensitive = case_sensitive, zero_score_is_edge = TRUE)
    return(.copy_identifier_metadata(
      .igraph_network_from_edges(edges, case_sensitive), network))
  }

  normalized <- .normalize_network(network, case_sensitive)
  if (.already_normalized(normalized, case_sensitive) &&
      is.null(normalized$weights)) {
    nodes <- names(normalized$links)
    node_id <- stats::setNames(seq_along(nodes), nodes)
    adjacency <- lapply(normalized$links, function(neighbors) {
      unname(node_id[neighbors])
    })
    if (anyNA(unlist(adjacency, use.names = FALSE))) {
      stop("Normalized legacy adjacency contains unknown nodes.",
        call. = FALSE)
    }
    graph <- igraph::graph_from_adj_list(adjacency, mode = "all",
      duplicate = TRUE)
    graph <- igraph::set_vertex_attr(graph, "name", value = nodes)
    graph <- igraph::set_graph_attr(graph, "Ntotal",
      value = igraph::ecount(graph))
    graph <- igraph::set_graph_attr(graph, "nearender_case_sensitive",
      value = case_sensitive)
    return(.copy_identifier_metadata(
      .mark_normalized(graph, case_sensitive), network))
  }
  link_counts <- lengths(normalized$links)
  edges <- data.frame(
    from = rep(names(normalized$links), link_counts),
    to = unlist(normalized$links, use.names = FALSE),
    stringsAsFactors = FALSE)
  score_column <- NULL
  if (!is.null(normalized$weights)) {
    if (!setequal(names(normalized$weights), names(normalized$links))) {
      stop("Legacy weight nodes must match legacy link nodes.", call. = FALSE)
    }
    scores <- Map(function(node, adjacent) {
      weights <- normalized$weights[[node]]
      if (is.null(names(weights)) || !all(adjacent %in% names(weights))) {
        stop("Legacy weights must name every adjacent node.", call. = FALSE)
      }
      unname(weights[adjacent])
    }, names(normalized$links), normalized$links)
    edges$score <- unlist(scores, use.names = FALSE)
    score_column <- "score"
  }
  edges <- .canonical_network_edges(edges, "from", "to", score_column,
    case_sensitive = case_sensitive, zero_score_is_edge = TRUE)
  .copy_identifier_metadata(
    .igraph_network_from_edges(edges, case_sensitive), network)
}

#' Convert a network to the NEArender sparse representation
#'
#' The returned object stores binary topology in `adjacency` and, when
#' available, edge weights in a separate `weights` sparse matrix. Keeping
#' these matrices separate prevents source edge scores from silently becoming
#' transition probabilities in graph-based calculations.
#'
#' @inheritParams as_igraph_network
#' @return A `nearender_sparse_network` object.
#' @seealso [as_igraph_network()], [as_nearender_network()], [convert_network()]
#' @examples
#' graph <- import_network(data.frame(from = "A", to = "B", score = 2),
#'   score_column = "score", species = NULL, input_id_format = "custom",
#'   verbose = FALSE)
#' sparse <- as_sparse_network(graph)
#' sparse$adjacency
#' sparse$weights
#' @export
as_sparse_network <- function(network, case_sensitive = FALSE) {
  graph <- as_igraph_network(network, case_sensitive)
  index_sparse_network(graph, preserve_weights = TRUE)
}

#' Convert between supported network representations
#'
#' This is the central object-to-object conversion interface. Use
#' [import_network()] for files and tabular edge data, and [read_network()] for
#' graph file formats handled by igraph, and [export_network()] to write
#' third-party graph formats.
#'
#' @param from An igraph object, sparse matrix, indexed sparse network, or
#'   legacy NEArender network.
#' @param to Output representation: `"igraph"`, `"sparse"`, or `"legacy"`.
#' @inheritParams as_nearender_network
#' @return A normalized network in the requested representation.
#' @seealso [as_igraph_network()], [as_sparse_network()], [as_nearender_network()],
#'   [import_network()], [read_network()], [export_network()]
#' @examples
#' graph <- import_network(data.frame(from = "A", to = "B"),
#'   species = NULL, input_id_format = "custom", verbose = FALSE)
#' sparse <- convert_network(graph, "sparse")
#' legacy <- convert_network(sparse, "legacy")
#' legacy$links
#' @export
convert_network <- function(from, to = c("igraph", "sparse", "legacy"),
    case_sensitive = FALSE) {
  to <- match.arg(to)
  input_format <- if (igraph::is_igraph(from)) {
    "igraph"
  } else if (inherits(from, c("nearender_indexed_network", "Matrix"))) {
    "sparse"
  } else {
    "legacy"
  }
  if (identical(input_format, to)) {
    warning("Input and output network formats are both '", to,
      "'; validating and normalizing the network.", call. = FALSE)
  }
  switch(to,
    igraph = as_igraph_network(from, case_sensitive),
    sparse = as_sparse_network(from, case_sensitive),
    legacy = as_nearender_network(from, case_sensitive)
  )
}

#' Convert a network to the NEArender named-adjacency-list representation
#'
#' Convert an igraph or indexed network to the named adjacency-list
#' representation used by NEArender. The igraph `weight` attribute is
#' preserved as adjacency-aligned legacy `weights`; renderers still decide
#' explicitly whether those weights define their analysis.
#'
#' @inheritParams as_igraph_network
#' @return A list with `links` and `Ntotal`, and `weights` when edge
#'   weights are available.
#' @seealso [as_igraph_network()], [as_sparse_network()], [convert_network()]
#' @examples
#' graph <- import_network(data.frame(from = "A", to = "B", score = 2),
#'   score_column = "score", species = NULL, input_id_format = "custom",
#'   verbose = FALSE)
#' legacy <- as_nearender_network(graph)
#' legacy$weights
#' @export
as_nearender_network <- function(network, case_sensitive = FALSE) {
  .assert_flag(case_sensitive, "case_sensitive")
  if (!igraph::is_igraph(network) &&
      !inherits(network, c("nearender_indexed_network", "Matrix"))) {
    return(.normalize_network(network, case_sensitive))
  }
  graph <- as_igraph_network(network, case_sensitive)
  edges <- igraph::as_data_frame(graph, what = "edges")
  retained <- edges[, c("from", "to",
    if ("weight" %in% names(edges)) "weight"), drop = FALSE]
  if ("weight" %in% names(retained)) {
    names(retained)[names(retained) == "weight"] <- "score"
  }
  result <- .legacy_network_from_edges(retained, case_sensitive)
  .copy_identifier_metadata(result, network)
}

#' Read a third-party graph file with igraph
#'
#' @param path Input graph file.
#' @param species Required species identifier accepted by
#'   [available_id_formats()]. Use explicit `NULL` for unsupported species or
#'   non-biological data.
#' @param input_id_format Submitted identifier format. Defaults to
#'   [master_id_format()] for `species`; 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 format An igraph reader format.
#' @param output_network_format Return an igraph, sparse, or legacy NEArender
#'   network.
#' @param network_format Deprecated alias for `output_network_format`.
#' @param ... Additional arguments passed to [igraph::read_graph()].
#' @inheritParams as_igraph_network
#' @return A normalized igraph, sparse, or legacy NEArender network.
#' @seealso [import_network()], [export_network()], [convert_network()]
#' @examples
#' graph <- import_network(data.frame(from = "A", to = "B", score = 2),
#'   score_column = "score", species = NULL, input_id_format = "custom",
#'   verbose = FALSE)
#' path <- tempfile(fileext = ".graphml")
#' export_network(graph, path)
#' restored <- read_network(path, species = NULL, input_id_format = "custom")
#' unlink(path)
#' igraph::edge_attr(restored, "weight")
#' @export
read_network <- function(path,
    format = c("graphml", "gml", "ncol", "lgl", "pajek", "edgelist"),
    output_network_format = c("igraph", "sparse", "legacy"),
    case_sensitive = FALSE, ..., network_format = NULL, species,
    input_id_format = master_id_format(species), id_mappings = NULL,
    ambiguous = c("error", "drop", "first", "expand"),
    unmapped = c("keep", "drop", "error")) {
  format <- match.arg(format)
  if (!is.null(network_format)) {
    if (!missing(output_network_format)) {
      stop("Use only output_network_format; network_format is deprecated.",
        call. = FALSE)
    }
    warning("network_format is deprecated; use output_network_format.",
      call. = FALSE)
    output_network_format <- network_format
  }
  output_network_format <- match.arg(output_network_format)
  graph <- igraph::read_graph(path, format = format, ...)
  import_network(graph, case_sensitive = case_sensitive, verbose = FALSE,
    output_network_format = output_network_format, species = species,
    input_id_format = input_id_format, id_mappings = id_mappings,
    ambiguous = ambiguous, unmapped = unmapped)
}

#' Export a network through igraph
#'
#' GraphML and GML are recommended when edge weights or other attributes must
#' be retained. Simpler edge-list formats may discard attributes.
#'
#' @param network An igraph, legacy NEArender, or indexed sparse NEArender
#'   network graph.
#' @param path Output graph file.
#' @param format A format passed to the igraph writer.
#' @param case_sensitive Preserve identifier case during conversion. When this
#'   argument is omitted for a normalized object, its recorded case policy is
#'   retained.
#' @param ... Additional arguments passed to [igraph::write_graph()].
#' @return `path`, invisibly.
#' @seealso [read_network()], [import_network()], [convert_network()]
#' @examples
#' graph <- import_network(data.frame(from = "A", to = "B"),
#'   species = NULL, input_id_format = "custom", verbose = FALSE)
#' path <- tempfile(fileext = ".graphml")
#' export_network(graph, path)
#' file.exists(path)
#' unlink(path)
#' @export
export_network <- function(network, path,
    format = c("graphml", "gml", "ncol", "lgl", "pajek", "edgelist"),
    case_sensitive = TRUE, ...) {
  format <- match.arg(format)
  if (missing(case_sensitive)) {
    metadata <- .normalization_metadata(network)
    if (is.list(metadata) && identical(metadata$normalized, TRUE)) {
      case_sensitive <- metadata$case_sensitive
    }
  }
  graph <- as_igraph_network(network, case_sensitive)
  igraph::write_graph(graph, file = path, format = format, ...)
  invisible(path)
}

# ============================================================================
# ALTERED GENE-SET PREPARATION
# ============================================================================

# Prepare and optionally map matrix row identifiers before AGS selection.
.prepare_input_matrix_ids <- function(x, identity, id_mappings,
    ambiguous, unmapped, case_sensitive, duplicate_ids) {
  mapped <- .map_input_rows(rownames(x), identity, id_mappings,
    ambiguous, unmapped, case_sensitive)
  x <- x[mapped$source_row, , drop = FALSE]
  gene_ids <- .canonical_ids(mapped$ids, case_sensitive)
  valid <- !is.na(gene_ids) & nzchar(gene_ids)
  x <- x[valid, , drop = FALSE]
  gene_ids <- gene_ids[valid]
  if (!length(gene_ids)) {
    stop("No matrix rows remain after identifier mapping.", call. = FALSE)
  }
  if (anyDuplicated(gene_ids)) {
    if (duplicate_ids == "error") {
      stop("Gene identifiers collide after mapping and case normalization; set duplicate_ids to an explicit aggregation method.",
        call. = FALSE)
    }
    groups <- split(seq_along(gene_ids),
      factor(gene_ids, levels = unique(gene_ids)))
    sample_names <- colnames(x)
    aggregate_group <- function(rows) {
      values <- x[rows, , drop = FALSE]
      if (length(rows) == 1L) return(as.numeric(values[1L, ]))
      switch(duplicate_ids,
        mean = colMeans(values),
        sum = colSums(values),
        max = apply(values, 2L, max))
    }
    x <- do.call(rbind, lapply(groups, aggregate_group))
    colnames(x) <- sample_names
    rownames(x) <- names(groups)
    gene_ids <- names(groups)
  } else {
    rownames(x) <- gene_ids
  }
  list(matrix = x, gene_ids = gene_ids,
    mapping_info = mapped$mapping_info)
}

#' Create altered gene sets from continuous sample profiles
#'
#' Convert a gene-by-sample matrix, such as expression, copy-number, protein,
#' or methylation measurements, into one altered gene set (AGS) per sample.
#' `"top"` ranks absolute, unstandardized deviations from each gene's
#' across-sample mean; `"toppos"` ranks signed deviations in descending order,
#' selecting the upper side of the value distribution. Both remain fixed-size
#' methods and apply no significance or positivity cutoff. `"topnorm"` ranks
#' absolute within-gene z-scores. `"bestp"` ranks one-sided upper-tail
#' probabilities calculated from `abs(z)`, whereas `"significant"` retains genes
#' below `cutoff_q` after Benjamini-Hochberg adjustment of the same probabilities.
#' This adjustment is applied to both directions of deviation and does not use
#' the enrichment-only q-value convention of [nea.render()]. `"toprandom"`
#' samples genes without replacement.
#'
#' @param x Numeric gene-by-sample matrix with gene identifiers as row names.
#' @param species Required species identifier accepted by
#'   [available_id_formats()]. Use explicit `NULL` for unsupported species or
#'   non-biological data.
#' @param input_id_format Submitted identifier format. Defaults to
#'   [master_id_format()] for `species`; required when `species = NULL`.
#' @param id_mappings Optional object from [load_id_mappings()].
#' @param ambiguous,unmapped Mapping policies passed to [map_identifiers()].
#' @param duplicate_ids Policy for rows that collapse to one identifier after
#'   mapping: error, mean, sum, or maximum.
#' @param n_top Number of genes retained by top-ranking methods. Values around
#'   30--300 are often useful; very large sets may reduce specificity.
#' @param sample_columns Optional names or indices selecting sample columns.
#' @param column_pattern Optional regular expression selecting sample columns.
#' @param method Preparation method. `"top"`, `"toppos"`, `"topnorm"`,
#'   `"bestp"`, and `"toprandom"` require `n_top`; `"significant"` uses
#'   `cutoff_q` and can return an empty AGS.
#' @param cutoff_q Benjamini-Hochberg-adjusted probability cutoff for
#'   `method = "significant"`.
#' @param case_sensitive Use case-sensitive identifier matching. The default
#'   treats all gene identifiers case-insensitively.
#' @return A named list containing one altered gene vector per sample, with
#'   normalization metadata available through [normalization_info()].
#' @seealso [mutations2ags()], [import_gene_sets()], [save_gs_list()]
#' @examples
#' profiles <- matrix(c(
#'   9, 1, 2, 8, 5, 5,
#'   1, 9, 8, 2, 5, 5), nrow = 6,
#'   dimnames = list(paste0("gene", 1:6), c("sample_1", "sample_2")))
#' top <- samples2ags(profiles, n_top = 2, method = "top",
#'   species = NULL, input_id_format = "custom")
#' toppos <- samples2ags(profiles, n_top = 2, method = "toppos",
#'   species = NULL, input_id_format = "custom")
#' top
#' toppos
#' @export
samples2ags <- function(
    x,
    n_top = NULL,
    sample_columns = NULL,
    column_pattern = NULL,
    method = c("significant", "top", "toppos", "topnorm", "bestp",
               "toprandom"),
    cutoff_q = 0.05,
    case_sensitive = FALSE, species,
    input_id_format = master_id_format(species), id_mappings = NULL,
    ambiguous = c("error", "drop", "first", "expand"),
    unmapped = c("keep", "drop", "error"),
    duplicate_ids = c("error", "mean", "sum", "max")) {
  method <- match.arg(method)
  ambiguous <- match.arg(ambiguous)
  unmapped <- match.arg(unmapped)
  duplicate_ids <- match.arg(duplicate_ids)
  .assert_flag(case_sensitive, "case_sensitive")
  identity <- .resolve_input_identity(species, input_id_format, id_mappings)
  x <- .select_sample_matrix(x, sample_columns, column_pattern)
  prepared_ids <- .prepare_input_matrix_ids(x, identity, id_mappings,
    ambiguous, unmapped, case_sensitive, duplicate_ids)
  x <- prepared_ids$matrix
  gene_ids <- prepared_ids$gene_ids
  if (!is.null(prepared_ids$mapping_info)) {
    identity$mapping$statistics <- prepared_ids$mapping_info
  }

  ranked <- method != "significant"
  if (ranked) {
    if (is.null(n_top) || length(n_top) != 1L || is.na(n_top) ||
        n_top < 1 || n_top != as.integer(n_top)) {
      stop("n_top must be one positive integer.", call. = FALSE)
    }
    n_top <- min(as.integer(n_top), nrow(x))
  } else if (!is.null(n_top)) {
    stop("n_top is not used by method = 'significant'.", call. = FALSE)
  }
  if (!is.numeric(cutoff_q) || length(cutoff_q) != 1L ||
      is.na(cutoff_q) || cutoff_q <= 0 || cutoff_q > 1) {
    stop("cutoff_q must be a number in (0, 1].", call. = FALSE)
  }

  centered <- sweep(x, 1L, rowMeans(x, na.rm = TRUE), FUN = "-")
  prepared <- if (method == "toprandom") {
    x
  } else if (method %in% c("significant", "topnorm", "bestp")) {
    sweep(centered, 1L, apply(x, 1L, stats::sd, na.rm = TRUE), FUN = "/")
  } else {
    centered
  }

  result <- vector("list", ncol(x))
  names(result) <- colnames(x)
  for (j in seq_len(ncol(x))) {
    values <- prepared[, j]
    if (method == "significant") {
      q <- stats::p.adjust(stats::pnorm(abs(values), lower.tail = FALSE),
        method = "BH")
      result[[j]] <- gene_ids[which(q < cutoff_q)]
    } else if (method == "bestp") {
      probability <- stats::pnorm(abs(values), lower.tail = FALSE)
      result[[j]] <- gene_ids[order(probability)][seq_len(n_top)]
    } else if (method == "toprandom") {
      result[[j]] <- sample(gene_ids, n_top, replace = FALSE)
    } else {
      ranking <- if (method == "toppos") values else abs(values)
      result[[j]] <- gene_ids[order(ranking, decreasing = TRUE)][
        seq_len(n_top)
      ]
    }
  }
  result <- .mark_normalized(result, case_sensitive)
  .attach_identifier_metadata(result, identity)
}

#' Create altered gene sets from binary sample profiles
#'
#' Convert a gene-by-sample mutation or other qualitative event matrix into one
#' altered gene set (AGS) per sample. Every nonzero, nonmissing entry is treated
#' as an event; event categories and magnitudes are otherwise ignored. Optional
#' permutation preserves sample set sizes while randomly sampling genes
#' according to their cohort-wide event frequencies.
#'
#' @param x Gene-by-sample matrix. Nonzero, nonmissing entries are altered.
#' @param species Required species identifier accepted by
#'   [available_id_formats()]. Use explicit `NULL` for unsupported species or
#'   non-biological data.
#' @param input_id_format Submitted identifier format. Defaults to
#'   [master_id_format()] for `species`; required when `species = NULL`.
#' @param id_mappings Optional object from [load_id_mappings()].
#' @param ambiguous,unmapped Mapping policies passed to [map_identifiers()].
#' @param duplicate_ids Policy for rows that collapse to one identifier after
#'   mapping: error, mean, sum, or maximum.
#' @param sample_columns Optional names or indices selecting sample columns.
#' @param column_pattern Optional regular expression selecting sample columns.
#' @param permute Randomize sets while preserving their sizes and accounting
#'   for relative event frequencies across the cohort.
#' @param case_sensitive Use case-sensitive identifier matching. The default
#'   treats all gene identifiers case-insensitively.
#' @return A named list containing one altered gene vector per sample, with
#'   normalization metadata available through [normalization_info()].
#' @seealso [samples2ags()], [import_gene_sets()], [save_gs_list()]
#' @examples
#' events <- matrix(c(1, 0, 1, 0, 0, 1), nrow = 3,
#'   dimnames = list(c("TP53", "KRAS", "EGFR"),
#'     c("sample_1", "sample_2")))
#' mutations2ags(events, species = "human")
#' @export
mutations2ags <- function(
    x,
    sample_columns = NULL,
    column_pattern = NULL,
    permute = FALSE,
    case_sensitive = FALSE, species,
    input_id_format = master_id_format(species), id_mappings = NULL,
    ambiguous = c("error", "drop", "first", "expand"),
    unmapped = c("keep", "drop", "error"),
    duplicate_ids = c("error", "mean", "sum", "max")) {
  .assert_flag(permute, "permute")
  .assert_flag(case_sensitive, "case_sensitive")
  ambiguous <- match.arg(ambiguous)
  unmapped <- match.arg(unmapped)
  duplicate_ids <- match.arg(duplicate_ids)
  identity <- .resolve_input_identity(species, input_id_format, id_mappings)
  x <- .select_sample_matrix(x, sample_columns, column_pattern)
  prepared_ids <- .prepare_input_matrix_ids(x, identity, id_mappings,
    ambiguous, unmapped, case_sensitive, duplicate_ids)
  x <- prepared_ids$matrix
  gene_ids <- prepared_ids$gene_ids
  if (!is.null(prepared_ids$mapping_info)) {
    identity$mapping$statistics <- prepared_ids$mapping_info
  }

  result <- lapply(seq_len(ncol(x)), function(j) {
    unique(gene_ids[which(!is.na(x[, j]) & x[, j] != 0)])
  })
  names(result) <- colnames(x)

  if (permute) result <- .permute_gene_sets(result)
  result <- .mark_normalized(result, case_sensitive)
  .attach_identifier_metadata(result, identity)
}

.permute_gene_sets <- function(gene_sets) {
  occurrences <- table(unlist(gene_sets, use.names = FALSE))
  probabilities <- occurrences / length(gene_sets)
  result <- lapply(gene_sets, function(genes) {
    sample(
      names(probabilities),
      length(genes),
      replace = FALSE,
      prob = probabilities
    )
  })
  names(result) <- names(gene_sets)
  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.