R/identifier-mappings.R

Defines functions map_identifiers .map_identifiers_with_lookup .identifier_mapping_lookup load_id_mappings .read_cached_identifier_table prepare_id_mappings .prepare_ncbi_mapping .read_uniprot_gene_mapping .read_ncbi_gene_info .prepare_biomart_mapping .write_identifier_pointer .cached_current_identifier_paths .cached_identifier_paths .validate_identifier_cache .prepare_mapping_cache .replace_identifier_file .write_gzip_table .mapping_statistics .nonempty_identifier .biomart_query .biomart_response_problem .biomart_query_endpoints .read_identifier_tsv .biomart_query_xml .biomart_current_release .biomart_release_from_registry .biomart_registry_urls .download_identifier_file .identifier_pointer_path .identifier_paths .validate_identifier_release .identifier_destination_dir .identifier_species_root .identifier_cache_root available_id_formats .identifier_format_category .map_input_rows .resolve_input_identity master_id_format .master_id_label .identifier_entry .identifier_key .identifier_species_catalog

Documented in available_id_formats load_id_mappings map_identifiers master_id_format prepare_id_mappings

.identifier_species_catalog <- function() {
  main_endpoint <- "https://www.ensembl.org/biomart/martservice"
  main_registry <- paste0(main_endpoint, "?type=registry")
  plants_endpoint <- "https://plants.ensembl.org/biomart/martservice"
  plants_registry <- paste0(plants_endpoint, "?type=registry")

  biomart <- function(id, scientific_name, common_name, tax_id, dataset,
      master_id, id_formats, aliases, species, provider = "Ensembl",
      endpoint = main_endpoint, registry_url = main_registry,
      virtual_schema = "default",
      registry_regex = "ensembl_mart_([0-9]+)") {
    list(id = id, species = species, scientific_name = scientific_name,
      common_name = common_name, tax_id = tax_id, provider = provider,
      provider_key = tolower(gsub("[^A-Za-z0-9]+", "-", provider)),
      provider_type = "biomart", dataset = dataset,
      endpoint = endpoint, registry_url = registry_url,
      virtual_schema = virtual_schema, registry_regex = registry_regex,
      master_id = master_id, id_formats = unique(id_formats),
      description_attribute = "description",
      aliases = unique(c(id, species, scientific_name, common_name, tax_id,
        aliases)))
  }

  list(
    biomart("hsapiens", "Homo sapiens", "human", "9606",
      "hsapiens_gene_ensembl", "hgnc_symbol",
      c("hgnc_symbol", "ensembl_gene_id", "ensembl_peptide_id",
        "ensembl_transcript_id", "hgnc_id", "entrezgene_id",
        "uniprotswissprot"),
      c("h. sapiens"), species = "hsa"),
    biomart("mmusculus", "Mus musculus", "mouse", "10090",
      "mmusculus_gene_ensembl", "mgi_symbol",
      c("mgi_symbol", "ensembl_gene_id", "ensembl_peptide_id",
        "ensembl_transcript_id", "mgi_id", "entrezgene_id",
        "uniprotswissprot"),
      c("m. musculus"), species = "mmu"),
    biomart("rnorvegicus", "Rattus norvegicus", "rat", "10116",
      "rnorvegicus_gene_ensembl", "rgd_symbol",
      c("rgd_symbol", "ensembl_gene_id", "ensembl_peptide_id",
        "ensembl_transcript_id", "rgd_id", "entrezgene_id",
        "uniprotswissprot"),
      c("r. norvegicus"), species = "rno"),
    biomart("drerio", "Danio rerio", "zebrafish", "7955",
      "drerio_gene_ensembl", "zfin_symbol",
      c("zfin_symbol", "ensembl_gene_id", "ensembl_peptide_id",
        "ensembl_transcript_id", "zfin_id", "entrezgene_id",
        "uniprotswissprot"),
      c("d. rerio", "danio", "zfish", "drer", "danrer"),
      species = "dre"),
    biomart("dmelanogaster", "Drosophila melanogaster", "fruit fly", "7227",
      "dmelanogaster_gene_ensembl", "flybasename_gene",
      c("flybasename_gene", "ensembl_gene_id", "ensembl_peptide_id",
        "ensembl_transcript_id", "flybase_gene_id", "flybase_annot_id",
        "entrezgene_id", "uniprotswissprot"),
      c("d. melanogaster", "drosophila"), species = "dme"),
    biomart("celegans", "Caenorhabditis elegans", "roundworm", "6239",
      "celegans_gene_ensembl", "wormbase_gene",
      c("wormbase_gene", "ensembl_gene_id", "ensembl_peptide_id",
        "ensembl_transcript_id", "wormbase_gseqname", "wormbase_locus",
        "entrezgene_id", "uniprotswissprot"),
      c("c. elegans", "worm"), species = "cel"),
    biomart("scerevisiae", "Saccharomyces cerevisiae", "budding yeast",
      "4932", "scerevisiae_gene_ensembl", "sgd_gene",
      c("sgd_gene", "ensembl_gene_id", "ensembl_peptide_id",
        "ensembl_transcript_id", "entrezgene_id", "uniprotswissprot"),
      c("s. cerevisiae", "yeast"), species = "sce"),
    biomart("athaliana", "Arabidopsis thaliana", "thale cress", "3702",
      "athaliana_eg_gene", "tair_symbol",
      c("tair_symbol", "ensembl_gene_id", "ensembl_peptide_id",
        "ensembl_transcript_id", "tair_locus", "entrezgene_id",
        "uniprotswissprot"),
      c("a. thaliana", "arabidopsis"), species = "ath",
      provider = "Ensembl Plants",
      endpoint = plants_endpoint, registry_url = plants_registry,
      virtual_schema = "plants_mart",
      registry_regex = "plants_mart_([0-9]+)"),
    list(
      id = "ecoli_k12_mg1655", species = "eco",
      scientific_name = "Escherichia coli K-12 MG1655",
      common_name = "E. coli K-12 MG1655", tax_id = "511145",
      provider = "NCBI Gene", provider_key = "ncbi-gene",
      provider_type = "ncbi_gene", dataset = NA_character_,
      endpoint = paste0(
        "https://ftp.ncbi.nlm.nih.gov/gene/DATA/GENE_INFO/",
        "Archaea_Bacteria/",
        "Escherichia_coli_str._K-12_substr._MG1655.gene_info.gz"),
      uniprot_endpoint = paste0(
        "https://rest.uniprot.org/uniprotkb/stream?",
        "fields=accession%2Cgene_primary%2Cgene_oln&format=tsv&",
        "query=%28organism_id%3A83333%29%20AND%20%28reviewed%3Atrue%29"),
      registry_url = NA_character_, virtual_schema = NA_character_,
      registry_regex = NA_character_, master_id = "Symbol",
      id_formats = c("Symbol", "GeneID", "LocusTag", "uniprotswissprot"),
      description_attribute = "description",
      aliases = c("ecoli_k12_mg1655", "Escherichia coli K-12 MG1655",
        "E. coli K-12 MG1655", "E. coli", "Escherichia coli", "511145",
        "eco"))
  )
}

.identifier_key <- function(x) {
  tolower(gsub("[^[:alnum:]]+", "", trimws(x)))
}

.identifier_entry <- function(species) {
  if (!is.character(species) || length(species) != 1L ||
      is.na(species) || !nzchar(trimws(species))) {
    stop("species must be one non-empty character value.", call. = FALSE)
  }
  key <- .identifier_key(species)
  entries <- .identifier_species_catalog()
  selected <- vapply(entries, function(entry) {
    key %in% .identifier_key(entry$aliases)
  }, logical(1))
  if (sum(selected) != 1L) {
    supported <- vapply(entries, function(x) x[["scientific_name"]],
      character(1))
    stop("Unsupported species. Available species are: ",
      paste(supported, collapse = ", "), ".", call. = FALSE)
  }
  entries[[which(selected)]]
}

.master_id_label <- function(entry) {
  switch(entry$id,
    hsapiens = "HGNC",
    mmusculus = "MGI",
    rnorvegicus = "RGD",
    drerio = "ZFIN",
    dmelanogaster = "FlyBase",
    celegans = "WormBase",
    scerevisiae = "SGD",
    athaliana = "TAIR",
    ecoli_k12_mg1655 = "Symbol",
    entry$master_id)
}

#' Return the master identifier format for a species
#'
#' Resolve any supported species alias and return the concise, user-facing
#' name of its symbol-oriented master identifier format.
#'
#' @param species Scientific or common name, package species ID, three-letter
#'   KEGG style organism ID, or NCBI taxonomy ID accepted by [available_id_formats()].
#' @return One character value naming the species master format, such as
#'   `"HGNC"`, `"MGI"`, or `"RGD"`.
#' @export
#' @examples
#' master_id_format("9606")
#' master_id_format("mouse")
master_id_format <- function(species) {
  if (is.null(species)) {
    stop("input_id_format must be supplied explicitly when species = NULL.",
      call. = FALSE)
  }
  .master_id_label(.identifier_entry(species))
}

.resolve_input_identity <- function(species, input_id_format,
    id_mappings = NULL) {
  if (!is.character(input_id_format) || length(input_id_format) != 1L ||
      is.na(input_id_format) || !nzchar(trimws(input_id_format))) {
    stop("input_id_format must be one non-empty character value.",
      call. = FALSE)
  }
  input_id_format <- trimws(input_id_format)
  if (is.null(species)) {
    if (!is.null(id_mappings)) {
      stop("species cannot be NULL when id_mappings is supplied.",
        call. = FALSE)
    }
    return(list(species_id = NA_character_, species = NA_character_,
      organism = NA_character_, tax_id = NA_character_,
      input_id_format = input_id_format,
      output_id_format = input_id_format, mapping = NULL))
  }
  entry <- .identifier_entry(species)
  if (identical(.identifier_key(input_id_format),
      .identifier_key(.master_id_label(entry)))) {
    input_id_format <- entry$master_id
  }
  format_keys <- .identifier_key(entry$id_formats)
  selected <- which(format_keys == .identifier_key(input_id_format))
  if (length(selected) != 1L) {
    stop("input_id_format is not supported for ", entry$scientific_name,
      "; use one of: ", paste(entry$id_formats, collapse = ", "), ".",
      call. = FALSE)
  }
  input_id_format <- entry$id_formats[[selected]]
  mapping <- NULL
  output_id_format <- input_id_format
  if (!is.null(id_mappings)) {
    if (!inherits(id_mappings, "nearender_id_mappings") ||
        !is.list(id_mappings$manifest)) {
      stop("id_mappings must be returned by load_id_mappings().",
        call. = FALSE)
    }
    if (!identical(id_mappings$manifest$species_id, entry$id)) {
      stop("id_mappings belongs to a different species.", call. = FALSE)
    }
    if (!input_id_format %in% id_mappings$manifest$id_formats) {
      stop("input_id_format is absent from the mapping manifest.",
        call. = FALSE)
    }
    output_id_format <- id_mappings$manifest$master_id
    mapping <- list(provider = id_mappings$manifest$provider,
      release = id_mappings$manifest$release,
      master_id = id_mappings$manifest$master_id)
  }
  list(species_id = entry$id, species = entry$species,
    organism = entry$scientific_name, tax_id = entry$tax_id,
    master_id_format = .master_id_label(entry), master_id = entry$master_id,
    input_id_format = input_id_format,
    output_id_format = output_id_format, mapping = mapping)
}

.map_input_rows <- function(ids, identity, id_mappings,
    ambiguous, unmapped, case_sensitive, lookup = NULL) {
  if (is.null(id_mappings)) {
    return(list(ids = as.character(ids), source_row = seq_along(ids),
      mapping_info = NULL))
  }
  ids <- as.character(ids)
  valid <- !is.na(ids) & nzchar(ids)
  if (is.null(lookup)) {
    lookup <- .identifier_mapping_lookup(id_mappings,
      identity$input_id_format, case_sensitive)
  }
  mapped <- .map_identifiers_with_lookup(ids[valid], lookup,
    ambiguous, unmapped)
  valid_rows <- which(valid)
  mapped_rows <- valid_rows[mapped$source_row]
  mapped_ids <- c(mapped$ids, ids[!valid])
  source_row <- c(mapped_rows, which(!valid))
  order <- order(source_row, method = "radix")
  list(ids = mapped_ids[order], source_row = source_row[order],
    mapping_info = mapped$mapping_info,
    ambiguous_source_row = valid_rows[which(mapped$multiple)],
    unmapped_source_row = valid_rows[which(mapped$missing)])
}

.identifier_format_category <- function(format, master_id) {
  if (identical(format, master_id)) return("master")
  if (grepl("peptide", format, ignore.case = TRUE)) return("protein")
  if (grepl("transcript", format, ignore.case = TRUE)) return("transcript")
  "gene"
}

#' List supported identifier formats
#'
#' Return the offline catalog of species-specific gene, transcript, and protein
#' identifiers available for conversion. For each species, the catalog lists
#' the master identifier and alternative formats so that input gene sets and
#' networks can be converted to the same identifier space. When multiple source
#' identifiers map to one master identifier, they are collapsed during
#' conversion. Mapping tables can be prepared on demand from remote providers;
#' listing the catalog does not make a network request.
#'
#' @param species Optional scientific name, common name, package species ID,
#'   three-letter KEGG style organism ID, or NCBI taxonomy ID. By default,
#'   return every supported species.
#' @return A data frame with one row per species and identifier format. The
#'   `species` column contains the three-letter KEGG style organism ID used by
#'   the package catalog, the eviNet `species` request field, and KEGG.
#' @examples
#' formats <- available_id_formats()
#' species <- unique(formats[, c("species_id", "species", "organism", "tax_id")])
#' print(species, row.names = FALSE)
#' available_id_formats("rat")[, c("master_id", "id_format", "category")]
#' @export
available_id_formats <- function(species = NULL) {
  entries <- if (is.null(species)) .identifier_species_catalog() else {
    list(.identifier_entry(species))
  }
  rows <- lapply(entries, function(entry) {
    data.frame(
      species_id = entry$id,
      species = entry$species,
      organism = entry$scientific_name,
      tax_id = entry$tax_id,
      provider = entry$provider,
      dataset = entry$dataset,
      master_id = entry$master_id,
      id_format = entry$id_formats,
      category = vapply(entry$id_formats, .identifier_format_category,
        character(1), master_id = entry$master_id),
      description_attribute = entry$description_attribute,
      stringsAsFactors = FALSE
    )
  })
  result <- do.call(rbind, rows)
  rownames(result) <- NULL
  result
}

.identifier_cache_root <- function(cache_dir) {
  file.path(.database_cache_dir(cache_dir), "identifier-mappings")
}

.identifier_species_root <- function(root, entry) {
  file.path(root, entry$provider_key, entry$id)
}

.identifier_destination_dir <- function(root, entry, release) {
  file.path(.identifier_species_root(root, entry), release)
}

.validate_identifier_release <- function(release) {
  if (!is.character(release) || length(release) != 1L ||
      is.na(release) || !grepl("^[A-Za-z0-9][A-Za-z0-9._-]*$", release) ||
      release %in% c(".", "..")) {
    stop("release must be one safe, non-empty release identifier.",
      call. = FALSE)
  }
  release
}

.identifier_paths <- function(root, entry, release) {
  destination <- .identifier_destination_dir(root, entry, release)
  c(
    mappings = file.path(destination, "id-mappings.tsv.gz"),
    annotations = file.path(destination, "gene-annotations.tsv.gz"),
    manifest = file.path(destination, "manifest.rds")
  )
}

.identifier_pointer_path <- function(root, entry) {
  file.path(.identifier_species_root(root, entry), "current.rds")
}

.download_identifier_file <- function(url, destination, quiet) {
  .download_file_explicit(url, destination, quiet, "identifier source")
}

.biomart_registry_urls <- function(entry) {
  urls <- entry$registry_url
  if (identical(entry$registry_url,
      "https://www.ensembl.org/biomart/martservice?type=registry")) {
    urls <- c(urls,
      "https://asia.ensembl.org/biomart/martservice?type=registry",
      "https://useast.ensembl.org/biomart/martservice?type=registry")
  }
  unique(urls)
}

.biomart_release_from_registry <- function(registry, entry) {
  text <- paste(readLines(registry, warn = FALSE), collapse = "")
  if (grepl("<!DOCTYPE\\s+html|<html(?:\\s|>)", text,
      ignore.case = TRUE, perl = TRUE)) {
    stop("BioMart registry returned an HTML page instead of XML.",
      call. = FALSE)
  }
  matches <- regmatches(text,
    gregexpr(entry$registry_regex, text, perl = TRUE))[[1L]]
  if (!length(matches) || identical(matches, character(0))) {
    stop("Could not determine the current BioMart release.", call. = FALSE)
  }
  releases <- unique(sub(entry$registry_regex, "\\1", matches, perl = TRUE))
  if (length(releases) != 1L || !grepl("^[0-9]+$", releases)) {
    stop("The BioMart registry did not identify one release.", call. = FALSE)
  }
  releases
}

.biomart_current_release <- function(entry, quiet) {
  registry <- tempfile("nearender-biomart-registry-")
  on.exit(unlink(registry), add = TRUE)
  failures <- character()
  for (url in .biomart_registry_urls(entry)) {
    result <- try(.download_identifier_file(url, registry, quiet),
      silent = TRUE)
    if (inherits(result, "try-error")) {
      failures <- c(failures, paste0(url, ": download failed"))
      next
    }
    release <- try(.biomart_release_from_registry(registry, entry),
      silent = TRUE)
    if (!inherits(release, "try-error")) {
      return(list(release = release,
        registry_md5 = unname(tools::md5sum(registry)),
        registry_url = url))
    }
    failures <- c(failures, paste0(url, ": ",
      conditionMessage(attr(release, "condition"))))
  }
  stop("Could not determine the current BioMart release. Tried: ",
    paste(failures, collapse = "; "), ".", call. = FALSE)
}

.biomart_query_xml <- function(entry, attributes) {
  paste0(
    '<Query virtualSchemaName="', entry$virtual_schema,
    '" formatter="TSV" header="1" uniqueRows="1" count="" ',
    'datasetConfigVersion="0.6"><Dataset name="', entry$dataset,
    '" interface="default">',
    paste0('<Attribute name="', attributes, '"/>', collapse = ""),
    "</Dataset></Query>"
  )
}

.read_identifier_tsv <- function(path, expected_names = NULL) {
  data <- utils::read.delim(path, quote = "", comment.char = "",
    colClasses = "character", check.names = FALSE, stringsAsFactors = FALSE,
    na.strings = "")
  if (!is.null(expected_names)) {
    if (ncol(data) != length(expected_names)) {
      stop("Identifier source returned an unexpected number of columns.",
        call. = FALSE)
    }
    names(data) <- expected_names
  }
  data
}

.biomart_query_endpoints <- function(entry, preferred = NULL) {
  endpoints <- entry$endpoint
  if (identical(entry$endpoint,
      "https://www.ensembl.org/biomart/martservice")) {
    endpoints <- c(endpoints,
      "https://asia.ensembl.org/biomart/martservice",
      "https://useast.ensembl.org/biomart/martservice")
  }
  unique(c(preferred, endpoints))
}

.biomart_response_problem <- function(path) {
  first <- readLines(path, n = 1L, warn = FALSE)
  if (!length(first)) return("an empty response")
  if (grepl("^Query ERROR", first)) return(first)
  if (grepl("^\\s*(?:<!DOCTYPE\\s+html|<html)(?:\\s|>)", first,
      ignore.case = TRUE, perl = TRUE)) {
    return("an HTML page instead of a TSV table")
  }
  NULL
}

.biomart_query <- function(entry, attributes, quiet, preferred = NULL) {
  query <- .biomart_query_xml(entry, attributes)
  artifact <- tempfile("nearender-biomart-query-")
  on.exit(unlink(artifact), add = TRUE)
  failures <- character()
  for (endpoint in .biomart_query_endpoints(entry, preferred)) {
    url <- paste0(endpoint, "?query=",
      utils::URLencode(query, reserved = TRUE))
    result <- try(.download_identifier_file(url, artifact, quiet),
      silent = TRUE)
    if (inherits(result, "try-error")) {
      condition <- attr(result, "condition", exact = TRUE)
      reason <- if (inherits(condition, "condition")) {
        conditionMessage(condition)
      } else {
        "download failed"
      }
      failures <- c(failures, paste0(endpoint, ": ", reason))
      next
    }
    problem <- .biomart_response_problem(artifact)
    if (is.null(problem)) {
      data <- try(.read_identifier_tsv(artifact, attributes), silent = TRUE)
      if (!inherits(data, "try-error")) {
        attr(data, "biomart_endpoint") <- endpoint
        return(data)
      }
      problem <- "a malformed TSV table"
    }
    if (grepl("^Query ERROR", problem)) {
      stop("BioMart rejected the identifier query: ", problem,
        call. = FALSE)
    }
    failures <- c(failures, paste0(endpoint, ": ", problem))
  }
  stop("BioMart did not return an identifier table. Tried: ",
    paste(failures, collapse = "; "), ".", call. = FALSE)
}

.nonempty_identifier <- function(x) {
  !is.na(x) & nzchar(trimws(x)) & trimws(x) != "-"
}

.mapping_statistics <- function(mappings, formats, masters) {
  rows <- lapply(formats, function(format) {
    selected <- mappings[mappings$id_format == format, , drop = FALSE]
    source_fanout <- if (nrow(selected)) {
      vapply(split(selected$master_id, selected$source_id),
        function(x) length(unique(x)), integer(1))
    } else integer()
    master_fanin <- if (nrow(selected)) {
      vapply(split(selected$source_id, selected$master_id),
        function(x) length(unique(x)), integer(1))
    } else integer()
    mapped_masters <- unique(selected$master_id)
    data.frame(
      id_format = format,
      mapping_pairs = nrow(selected),
      distinct_source_ids = length(unique(selected$source_id)),
      mapped_master_ids = length(mapped_masters),
      missing_master_ids = length(setdiff(masters, mapped_masters)),
      ambiguous_source_ids = sum(source_fanout > 1L),
      maximum_source_fanout = if (length(source_fanout)) {
        max(source_fanout)
      } else 0L,
      multi_id_master_ids = sum(master_fanin > 1L),
      maximum_master_fanin = if (length(master_fanin)) {
        max(master_fanin)
      } else 0L,
      stringsAsFactors = FALSE
    )
  })
  do.call(rbind, rows)
}

.write_gzip_table <- function(x, path) {
  connection <- gzfile(path, open = "wt", encoding = "UTF-8")
  on.exit(close(connection))
  utils::write.table(x, connection, sep = "\t", quote = FALSE,
    row.names = FALSE, col.names = TRUE, na = "")
  invisible(path)
}

.replace_identifier_file <- function(source, destination) {
  if (file.exists(destination)) unlink(destination)
  if (!file.rename(source, destination)) {
    stop("Could not move a prepared identifier artifact into the cache.",
      call. = FALSE)
  }
  invisible(destination)
}

.prepare_mapping_cache <- function(entry, release, query_fun, source,
    root) {
  paths <- .identifier_paths(root, entry, release)
  destination <- dirname(paths[["manifest"]])
  dir.create(destination, recursive = TRUE, showWarnings = FALSE)
  temporary <- c(
    mappings = tempfile("id-mappings-", tmpdir = destination),
    annotations = tempfile("gene-annotations-", tmpdir = destination),
    manifest = tempfile("manifest-", tmpdir = destination)
  )
  on.exit(unlink(temporary[file.exists(temporary)]), add = TRUE)

  master_description <- query_fun(
    c(entry$master_id, entry$description_attribute))
  names(master_description) <- c("master_id", "description")
  master_description$master_id <- trimws(master_description$master_id)
  master_description$description <- trimws(master_description$description)
  valid_master <- .nonempty_identifier(master_description$master_id)
  masters <- sort(unique(master_description$master_id[valid_master]),
    method = "radix")
  if (!length(masters)) {
    stop("The provider returned no non-empty master identifiers.",
      call. = FALSE)
  }
  valid_description <- valid_master &
    .nonempty_identifier(master_description$description)
  annotations <- unique(master_description[valid_description,
    c("master_id", "description"), drop = FALSE])
  annotations <- annotations[order(annotations$master_id,
    annotations$description, method = "radix"), , drop = FALSE]

  mapping_parts <- list(data.frame(
    id_format = entry$master_id,
    source_id = masters,
    master_id = masters,
    stringsAsFactors = FALSE
  ))
  other_formats <- setdiff(entry$id_formats, entry$master_id)
  for (format in other_formats) {
    pairs <- query_fun(c(entry$master_id, format))
    names(pairs) <- c("master_id", "source_id")
    pairs$master_id <- trimws(pairs$master_id)
    pairs$source_id <- trimws(pairs$source_id)
    valid <- .nonempty_identifier(pairs$master_id) &
      .nonempty_identifier(pairs$source_id)
    pairs <- unique(pairs[valid, c("source_id", "master_id"), drop = FALSE])
    pairs$id_format <- format
    mapping_parts[[length(mapping_parts) + 1L]] <-
      pairs[, c("id_format", "source_id", "master_id"), drop = FALSE]
  }
  mappings <- unique(do.call(rbind, mapping_parts))
  mappings <- mappings[order(mappings$id_format, mappings$source_id,
    mappings$master_id, method = "radix"), , drop = FALSE]
  rownames(mappings) <- NULL
  rownames(annotations) <- NULL
  mapping_stats <- .mapping_statistics(mappings, entry$id_formats, masters)
  description_fanout <- if (nrow(annotations)) {
    lengths(split(annotations$description, annotations$master_id))
  } else integer()

  .write_gzip_table(mappings, temporary[["mappings"]])
  .write_gzip_table(annotations, temporary[["annotations"]])
  artifacts <- data.frame(
    role = c("mappings", "annotations"),
    filename = basename(paths[c("mappings", "annotations")]),
    bytes = as.numeric(file.info(temporary[c("mappings", "annotations")])$size),
    md5 = unname(tools::md5sum(
      temporary[c("mappings", "annotations")])),
    stringsAsFactors = FALSE
  )
  manifest <- list(
    format_version = 1L,
    species_id = entry$id,
    species = entry$species,
    organism = entry$scientific_name,
    tax_id = entry$tax_id,
    provider = entry$provider,
    dataset = entry$dataset,
    release = as.character(release),
    master_id = entry$master_id,
    id_formats = entry$id_formats,
    description_attribute = entry$description_attribute,
    retrieved_at = format(Sys.time(), tz = "UTC", usetz = TRUE),
    source = source,
    master_count = length(masters),
    description_count = nrow(annotations),
    masters_with_multiple_descriptions = sum(description_fanout > 1L),
    mapping_statistics = mapping_stats,
    artifacts = artifacts
  )
  saveRDS(manifest, temporary[["manifest"]])

  .replace_identifier_file(temporary[["mappings"]], paths[["mappings"]])
  temporary[["mappings"]] <- NA_character_
  .replace_identifier_file(temporary[["annotations"]], paths[["annotations"]])
  temporary[["annotations"]] <- NA_character_
  .replace_identifier_file(temporary[["manifest"]], paths[["manifest"]])
  temporary[["manifest"]] <- NA_character_
  stats::setNames(normalizePath(paths, mustWork = TRUE), names(paths))
}

.validate_identifier_cache <- function(paths) {
  if (any(!file.exists(paths))) {
    stop("Identifier mappings are not cached; call prepare_id_mappings() ",
      "explicitly first.", call. = FALSE)
  }
  manifest <- readRDS(paths[["manifest"]])
  required <- c("mappings", "annotations")
  artifacts <- manifest$artifacts
  if (!is.data.frame(artifacts) ||
      !all(c("role", "bytes", "md5") %in% names(artifacts)) ||
      !all(required %in% artifacts$role)) {
    stop("The identifier mapping manifest is malformed.", call. = FALSE)
  }
  for (role in required) {
    artifact <- artifacts[match(role, artifacts$role), , drop = FALSE]
    bytes <- as.numeric(file.info(paths[[role]])$size)
    md5 <- unname(tools::md5sum(paths[[role]]))
    if (!identical(bytes, as.numeric(artifact$bytes)) ||
        !identical(md5, as.character(artifact$md5))) {
      stop("Cached identifier mapping failed size or checksum verification.",
        call. = FALSE)
    }
  }
  manifest
}

.cached_identifier_paths <- function(root, entry, release) {
  paths <- .identifier_paths(root, entry, release)
  .validate_identifier_cache(paths)
  stats::setNames(normalizePath(paths, mustWork = TRUE), names(paths))
}

.cached_current_identifier_paths <- function(root, entry) {
  pointer_path <- .identifier_pointer_path(root, entry)
  if (!file.exists(pointer_path)) return(NULL)
  pointer <- try(readRDS(pointer_path), silent = TRUE)
  if (inherits(pointer, "try-error") || !is.list(pointer) ||
      !identical(pointer$species_id, entry$id) ||
      !identical(pointer$provider, entry$provider) ||
      !is.character(pointer$release) || length(pointer$release) != 1L) {
    return(NULL)
  }
  release <- try(.validate_identifier_release(pointer$release), silent = TRUE)
  if (inherits(release, "try-error")) return(NULL)
  result <- try(.cached_identifier_paths(root, entry, release), silent = TRUE)
  if (inherits(result, "try-error")) NULL else result
}

.write_identifier_pointer <- function(root, entry, release) {
  path <- .identifier_pointer_path(root, entry)
  dir.create(dirname(path), recursive = TRUE, showWarnings = FALSE)
  temporary <- tempfile("current-", tmpdir = dirname(path))
  on.exit(unlink(temporary), add = TRUE)
  saveRDS(list(species_id = entry$id, provider = entry$provider,
    release = as.character(release)), temporary)
  if (file.exists(path)) unlink(path)
  if (!file.rename(temporary, path)) {
    stop("Could not update the current identifier-cache pointer.",
      call. = FALSE)
  }
  invisible(path)
}

.prepare_biomart_mapping <- function(entry, root, force, quiet) {
  release_info <- .biomart_current_release(entry, quiet)
  release <- release_info$release
  paths <- .identifier_paths(root, entry, release)
  if (all(file.exists(paths)) && !force) {
    result <- try(.cached_identifier_paths(root, entry, release), silent = TRUE)
    if (inherits(result, "try-error")) {
      stop("The cached identifier mapping is invalid; set force = TRUE to ",
        "replace it.", call. = FALSE)
    }
    .write_identifier_pointer(root, entry, release)
    return(result)
  }
  preferred_endpoint <- NULL
  query_fun <- function(attributes) {
    result <- .biomart_query(entry, attributes, quiet, preferred_endpoint)
    preferred_endpoint <<- attr(result, "biomart_endpoint", exact = TRUE)
    result
  }
  source <- list(
    type = "BioMart",
    endpoint = entry$endpoint,
    query_endpoints = .biomart_query_endpoints(entry),
    query_endpoint_policy = paste("try each official endpoint using the R",
      "session download timeout and reuse the first successful endpoint"),
    query_timeout_seconds = getOption("timeout"),
    registry_url = release_info$registry_url,
    registry_md5 = release_info$registry_md5,
    virtual_schema = entry$virtual_schema,
    dataset = entry$dataset,
    query_policy = "one source attribute per query; unique rows"
  )
  result <- .prepare_mapping_cache(entry, release, query_fun, source, root)
  .write_identifier_pointer(root, entry, release)
  result
}

.read_ncbi_gene_info <- function(path, entry) {
  connection <- gzfile(path, open = "rt", encoding = "UTF-8")
  on.exit(close(connection))
  data <- utils::read.delim(connection, quote = "", comment.char = "",
    colClasses = "character", check.names = FALSE, stringsAsFactors = FALSE,
    na.strings = c("", "-"))
  derived <- intersect(entry$id_formats, "uniprotswissprot")
  required <- unique(c("#tax_id", entry$master_id,
    setdiff(entry$id_formats, derived),
    entry$description_attribute, "Modification_date"))
  if (!all(required %in% names(data))) {
    stop("The NCBI gene-info table is missing required columns.",
      call. = FALSE)
  }
  data <- data[data[["#tax_id"]] == entry$tax_id, , drop = FALSE]
  if (!nrow(data)) {
    stop("The NCBI gene-info table contains no rows for the requested taxon.",
      call. = FALSE)
  }
  data
}

.read_uniprot_gene_mapping <- function(path, gene_info, entry) {
  data <- utils::read.delim(path, quote = "", comment.char = "",
    colClasses = "character", check.names = FALSE, stringsAsFactors = FALSE,
    na.strings = c("", "-"))
  required <- c("Entry", "Gene Names (primary)",
    "Gene Names (ordered locus)")
  if (!all(required %in% names(data))) {
    stop("The UniProt table is missing required columns.", call. = FALSE)
  }
  data <- data[.nonempty_identifier(data[["Entry"]]), , drop = FALSE]
  lookup <- unique(rbind(
    data.frame(identifier = gene_info[[entry[["master_id"]]]],
      master_id = gene_info[[entry[["master_id"]]]],
      stringsAsFactors = FALSE),
    data.frame(identifier = gene_info[["LocusTag"]],
      master_id = gene_info[[entry[["master_id"]]]],
      stringsAsFactors = FALSE)
  ))
  valid_lookup <- .nonempty_identifier(lookup[["identifier"]]) &
    .nonempty_identifier(lookup[["master_id"]])
  lookup <- lookup[valid_lookup, , drop = FALSE]
  tokens <- lapply(seq_len(nrow(data)), function(i) {
    values <- c(data[["Gene Names (primary)"]][[i]],
      strsplit(ifelse(is.na(data[["Gene Names (ordered locus)"]][[i]]),
        "", data[["Gene Names (ordered locus)"]][[i]]),
        "\\s+", perl = TRUE)[[1L]])
    unique(values[.nonempty_identifier(values)])
  })
  candidates <- data.frame(
    row = rep(seq_len(nrow(data)), lengths(tokens)),
    identifier = unlist(tokens, use.names = FALSE),
    stringsAsFactors = FALSE
  )
  matched <- merge(candidates, lookup, by = "identifier",
    all = FALSE, sort = FALSE)
  unique(data.frame(
    master = matched[["master_id"]],
    value = data[["Entry"]][matched[["row"]]],
    stringsAsFactors = FALSE
  ))
}

.prepare_ncbi_mapping <- function(entry, root, force, quiet) {
  source_path <- tempfile("nearender-ncbi-gene-info-", fileext = ".gz")
  uniprot_path <- tempfile("nearender-uniprot-", fileext = ".tsv")
  on.exit(unlink(c(source_path, uniprot_path)), add = TRUE)
  .download_identifier_file(entry$endpoint, source_path, quiet)
  .download_identifier_file(entry$uniprot_endpoint, uniprot_path, quiet)
  data <- .read_ncbi_gene_info(source_path, entry)
  uniprot_pairs <- .read_uniprot_gene_mapping(uniprot_path, data, entry)
  dates <- data$Modification_date[
    grepl("^[0-9]{8}$", data$Modification_date)]
  if (!length(dates)) {
    stop("The NCBI gene-info table has no usable modification date.",
      call. = FALSE)
  }
  source_md5 <- unname(tools::md5sum(source_path))
  uniprot_md5 <- unname(tools::md5sum(uniprot_path))
  release <- paste0(max(dates), "-", substr(source_md5, 1L, 6L),
    substr(uniprot_md5, 1L, 6L))
  paths <- .identifier_paths(root, entry, release)
  if (all(file.exists(paths)) && !force) {
    result <- try(.cached_identifier_paths(root, entry, release), silent = TRUE)
    if (inherits(result, "try-error")) {
      stop("The cached identifier mapping is invalid; set force = TRUE to ",
        "replace it.", call. = FALSE)
    }
    .write_identifier_pointer(root, entry, release)
    return(result)
  }
  query_fun <- function(attributes) {
    if (identical(attributes[[2L]], "uniprotswissprot")) {
      return(uniprot_pairs)
    }
    data[, attributes, drop = FALSE]
  }
  source <- list(
    type = "NCBI Gene gene_info",
    url = entry$endpoint,
    bytes = as.numeric(file.info(source_path)$size),
    md5 = source_md5,
    supplementary_source = list(
      type = "UniProtKB reviewed accessions",
      url = entry$uniprot_endpoint,
      tax_id = "83333",
      bytes = as.numeric(file.info(uniprot_path)$size),
      md5 = uniprot_md5
    ),
    raw_source_retained = FALSE
  )
  result <- .prepare_mapping_cache(entry, release, query_fun, source, root)
  .write_identifier_pointer(root, entry, release)
  result
}

#' Download and prepare identifier mappings
#'
#' Explicitly acquire mapping data only for the requested species, transform it
#' into a release-specific long table, and cache the result. BioMart attributes
#' are queried independently to avoid Cartesian expansion across transcript and
#' peptide identifiers.
#' E. coli mappings supplement NCBI Gene symbols and locus tags with reviewed
#' UniProtKB accessions. No renderer or package installation invokes this
#' function. This is the explicit online first step in the public mapping
#' workflow: call `prepare_id_mappings()`, then [load_id_mappings()], then
#' either pass the loaded object to an importer or call [map_identifiers()]
#' directly.
#'
#' @param species One or more supported scientific names, common names, package
#'   species IDs, three-letter KEGG style organism IDs, or NCBI taxonomy IDs.
#' @param release 'current' to reuse the checksum-validated local current
#'   release when available, or otherwise discover and record the current
#'   provider release. A concrete release must already be cached.
#' @param cache_dir Explicit cache root required for this writing operation.
#' @param force Contact the provider even when a valid current cache exists,
#'   and replace a valid cached mapping when the resolved release is unchanged.
#' @param quiet Suppress provider download progress.
#' @return A named list containing cached artifact paths, invisibly.
#' @seealso [load_id_mappings()], [map_identifiers()]
#' @examples
#' cache <- file.path(tempdir(), "NEArender-cache")
#' \dontrun{
#' prepare_id_mappings("human", cache_dir = cache)
#' mappings <- load_id_mappings("human", cache_dir = cache)
#' }
#' @export
prepare_id_mappings <- function(species, release = "current",
    cache_dir = NULL, force = FALSE, quiet = FALSE) {
  if (!is.character(species) || !length(species) || anyNA(species) ||
      any(!nzchar(trimws(species)))) {
    stop("species must contain one or more non-empty character values.",
      call. = FALSE)
  }
  if (!is.character(release) || length(release) != 1L ||
      is.na(release) || !nzchar(trimws(release))) {
    stop("release must be one non-empty character value.", call. = FALSE)
  }
  release <- .validate_identifier_release(trimws(release))
  .assert_flag(force, "force")
  .assert_flag(quiet, "quiet")
  entries <- lapply(species, .identifier_entry)
  ids <- vapply(entries, function(x) x[["id"]], character(1))
  entries <- entries[!duplicated(ids)]
  ids <- ids[!duplicated(ids)]
  root <- .identifier_cache_root(.explicit_cache_dir(cache_dir))

  if (!identical(release, "current")) {
    result <- lapply(entries, function(entry) {
      .cached_identifier_paths(root, entry, release)
    })
    names(result) <- ids
    return(invisible(result))
  }

  old_timeout <- getOption("timeout")
  options(timeout = max(300, old_timeout))
  on.exit(options(timeout = old_timeout), add = TRUE)
  result <- lapply(entries, function(entry) {
    if (!force) {
      cached <- .cached_current_identifier_paths(root, entry)
      if (!is.null(cached)) return(cached)
    }
    if (identical(entry$provider_type, "biomart")) {
      .prepare_biomart_mapping(entry, root, force, quiet)
    } else if (identical(entry$provider_type, "ncbi_gene")) {
      .prepare_ncbi_mapping(entry, root, force, quiet)
    } else {
      stop("No identifier provider is registered for this species.",
        call. = FALSE)
    }
  })
  names(result) <- ids
  invisible(result)
}

.read_cached_identifier_table <- function(path) {
  connection <- gzfile(path, open = "rt", encoding = "UTF-8")
  on.exit(close(connection))
  utils::read.delim(connection, quote = "", comment.char = "",
    colClasses = "character", check.names = FALSE, stringsAsFactors = FALSE)
}

#' Load cached identifier mappings
#'
#' Read a previously prepared identifier mapping without making a network
#' request.
#'
#' @param species One supported scientific name, common name, package species
#'   ID, three-letter KEGG style organism ID, or NCBI taxonomy ID.
#' @param release Concrete cached release. NULL or 'current' uses the most
#'   recently prepared release for the species.
#' @param cache_dir Cache root. By default, this is
#'   `tools::R_user_dir("NEArender", which = "cache")`.
#' @return A list containing long-form mappings, annotations, and the
#'   provenance manifest.
#' @examples
#' \dontrun{
#' mappings <- load_id_mappings("human")
#' mappings$manifest$release
#' }
#' @export
load_id_mappings <- function(species, release = NULL, cache_dir = NULL) {
  entry <- .identifier_entry(species)
  root <- .identifier_cache_root(cache_dir)
  if (is.null(release) || identical(release, "current")) {
    pointer_path <- .identifier_pointer_path(root, entry)
    if (!file.exists(pointer_path)) {
      stop("Identifier mappings are not cached; call prepare_id_mappings() ",
        "explicitly first.", call. = FALSE)
    }
    pointer <- readRDS(pointer_path)
    if (!identical(pointer$species_id, entry$id) ||
        !is.character(pointer$release) || length(pointer$release) != 1L) {
      stop("The current identifier-cache pointer is malformed.",
        call. = FALSE)
    }
    release <- pointer$release
  }
  release <- .validate_identifier_release(release)
  paths <- .identifier_paths(root, entry, release)
  manifest <- .validate_identifier_cache(paths)
  structure(list(
    mappings = .read_cached_identifier_table(paths[["mappings"]]),
    annotations = .read_cached_identifier_table(paths[["annotations"]]),
    manifest = manifest
  ), class = "nearender_id_mappings")
}

.identifier_mapping_lookup <- function(mappings, from, case_sensitive) {
  .assert_flag(case_sensitive, "case_sensitive")
  if (!inherits(mappings, "nearender_id_mappings") ||
      !is.data.frame(mappings$mappings) || !is.list(mappings$manifest)) {
    stop("mappings must be an object returned by load_id_mappings().",
      call. = FALSE)
  }
  if (!is.character(from) || length(from) != 1L || is.na(from) ||
      !nzchar(from) || !from %in% mappings$manifest$id_formats) {
    stop("from must identify one format available in the mapping manifest.",
      call. = FALSE)
  }
  selected <- mappings$mappings[mappings$mappings$id_format == from,
    c("source_id", "master_id"), drop = FALSE]
  key <- function(x) if (case_sensitive) x else tolower(x)
  selected$key <- key(selected$source_id)
  values <- lapply(split(selected$master_id, selected$key), function(ids) {
    sort(unique(ids))
  })
  list(values = values, key = key, species_id = mappings$manifest$species_id,
    release = mappings$manifest$release, from = from,
    to = mappings$manifest$master_id, case_sensitive = case_sensitive)
}

.map_identifiers_with_lookup <- function(ids, lookup, ambiguous, unmapped) {
  input_keys <- lookup$key(ids)
  candidates <- unname(lookup$values[input_keys])
  missing <- lengths(candidates) == 0L
  multiple <- lengths(candidates) > 1L
  if (any(multiple) && ambiguous == "error") {
    examples <- unique(ids[multiple])
    stop("Ambiguous source identifiers map to several master IDs; examples: ",
      paste(utils::head(examples, 5L), collapse = ", "), ".",
      call. = FALSE)
  }
  if (any(missing) && unmapped == "error") {
    examples <- unique(ids[missing])
    stop("Source identifiers have no master-ID mapping; examples: ",
      paste(utils::head(examples, 5L), collapse = ", "), ".",
      call. = FALSE)
  }

  if (ambiguous == "expand") {
    mapped <- candidates
    if (any(missing)) {
      mapped[missing] <- if (unmapped == "keep") {
        lapply(ids[missing], function(id) id)
      } else rep(list(character()), sum(missing))
    }
    output_lengths <- lengths(mapped)
    source_row <- rep.int(seq_along(ids), output_lengths)
    result <- unlist(mapped, use.names = FALSE)
  } else {
    keep <- rep(TRUE, length(ids))
    if (unmapped == "drop") keep[missing] <- FALSE
    if (ambiguous == "drop") keep[multiple] <- FALSE
    result <- ids
    available <- !missing
    if (any(available)) {
      result[available] <- vapply(candidates[available], `[[`, character(1), 1L)
    }
    source_row <- which(keep)
    result <- result[keep]
  }
  list(ids = result, source_row = source_row, missing = missing,
    multiple = multiple, mapping_info = list(
      species_id = lookup$species_id, release = lookup$release,
      from = lookup$from, to = lookup$to,
      input_count = length(ids), output_count = length(result),
      ambiguous_count = sum(multiple), unmapped_count = sum(missing),
      ambiguous_policy = ambiguous, unmapped_policy = unmapped,
      case_sensitive = lookup$case_sensitive))
}

#' Map identifiers to a species master namespace
#'
#' Apply a mapping loaded by [load_id_mappings()] without network access.
#' Mapping is deliberately explicit: callers select the input namespace and
#' policies for ambiguous and unmapped identifiers before importing or
#' preparing analytical objects. This public helper is also useful for mapping
#' an identifier vector independently of an import operation.
#'
#' @param ids Character vector of source identifiers.
#' @param mappings A `nearender_id_mappings` object returned by
#'   [load_id_mappings()].
#' @param from Source identifier format listed by [available_id_formats()].
#' @param ambiguous Policy for source IDs with several master IDs: error,
#'   drop, keep the first sorted match, or expand to all matches.
#' @param unmapped Policy for source IDs without a mapping: keep, drop, or
#'   error.
#' @param case_sensitive Match source identifiers with case sensitivity.
#' @return A character vector in the master namespace. With
#'   `ambiguous = "expand"`, one input may yield several output values.
#'   A `mapping_info` attribute records mapping counts and policies.
#' @seealso [prepare_id_mappings()], [load_id_mappings()]
#' @examples
#' example_mappings <- structure(list(
#'   mappings = data.frame(id_format = "ensembl_gene_id",
#'     source_id = c("ENSG1", "ENSG2"), master_id = c("TP53", "MDM2")),
#'   manifest = list(id_formats = "ensembl_gene_id")),
#'   class = "nearender_id_mappings")
#' map_identifiers(c("ENSG1", "ENSG2"), example_mappings,
#'   from = "ensembl_gene_id")
#' @export
map_identifiers <- function(ids, mappings, from,
    ambiguous = c("error", "drop", "first", "expand"),
    unmapped = c("keep", "drop", "error"), case_sensitive = TRUE) {
  ambiguous <- match.arg(ambiguous)
  unmapped <- match.arg(unmapped)
  if (!is.character(ids) || anyNA(ids)) {
    stop("ids must be a character vector without missing values.",
      call. = FALSE)
  }
  lookup <- .identifier_mapping_lookup(mappings, from, case_sensitive)
  mapped <- .map_identifiers_with_lookup(ids, lookup, ambiguous, unmapped)
  result <- mapped$ids
  source_names <- names(ids)
  if (!is.null(source_names)) names(result) <- source_names[mapped$source_row]
  attr(result, "mapping_info") <- mapped$mapping_info
  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.