R/ndex.R

Defines functions load_ndex_network .ndex_read_artifact .ndex_cx1_table .ndex_cx1_attributes .ndex_cx2_table .ndex_atomic_value .ndex_value .ndex_cx2_default .ndex_cx2_key .ndex_cx2_declarations .ndex_aspects .ndex_locate_cache download_ndex_network .ndex_verify_cached .ndex_validate_format .ndex_expected_bytes .ndex_atomic_rds .ndex_cache_paths .ndex_snapshot_id .ndex_server_key ndex_network_summary .ndex_get_summary_raw search_ndex_networks .ndex_catalog .ndex_empty_catalog .ndex_catalog_row .ndex_time_string .ndex_property .ndex_resource .ndex_http_download .ndex_http_json .ndex_http_request .ndex_encode_query .ndex_request_secrets .ndex_redact .ndex_validate_auth .ndex_web_server .ndex_normalize_server .ndex_assert_optional_string .ndex_scalar_numeric .ndex_scalar_logical .ndex_scalar_character .ndex_stop

Documented in download_ndex_network load_ndex_network ndex_network_summary search_ndex_networks

# NDEx discovery, acquisition, caching, and CX/CX2 import.
#
# Remote access is deliberately isolated from parsing. This lets command-line
# callers and a future web-service adapter share the same deterministic catalog,
# cache, and projection rules without placing authentication or HTTP concerns in
# the analytical core.

.ndex_public_server <- "https://www.ndexbio.org"
.ndex_parser_version <- "ndex-cx-1"

.ndex_stop <- function(message, code = "error", status = NULL) {
  condition <- structure(
    list(message = message, call = NULL, status = status),
    class = c(paste0("nearender_ndex_", code), "nearender_ndex_error",
      "error", "condition")
  )
  stop(condition)
}

.ndex_scalar_character <- function(x, default = NA_character_) {
  if (is.null(x) || !length(x)) return(default)
  value <- x[[1L]]
  if (is.null(value) || length(value) != 1L || is.na(value)) return(default)
  as.character(value)
}

.ndex_scalar_logical <- function(x, default = NA) {
  if (is.null(x) || !length(x)) return(default)
  value <- suppressWarnings(as.logical(x[[1L]]))
  if (length(value) != 1L || is.na(value)) return(default)
  value
}

.ndex_scalar_numeric <- function(x, default = NA_real_) {
  if (is.null(x) || !length(x)) return(default)
  value <- suppressWarnings(as.numeric(x[[1L]]))
  if (length(value) != 1L || is.na(value) || !is.finite(value)) return(default)
  value
}

.ndex_assert_optional_string <- function(x, argument) {
  if (!is.null(x) && (!is.character(x) || length(x) != 1L || is.na(x) ||
      !nzchar(x))) {
    stop(argument, " must be NULL or one non-empty character value.",
      call. = FALSE)
  }
  invisible(x)
}

.ndex_normalize_server <- function(server = NULL) {
  if (is.null(server)) server <- .ndex_public_server
  if (!is.character(server) || length(server) != 1L || is.na(server) ||
      !nzchar(server)) {
    stop("server must be NULL or one non-empty HTTP(S) URL.", call. = FALSE)
  }
  server <- sub("/+$", "", trimws(server))
  if (!grepl("^https?://", server, ignore.case = TRUE)) {
    stop("server must start with http:// or https://.", call. = FALSE)
  }
  if (grepl("^https?://[^/]+@", server, ignore.case = TRUE)) {
    stop("server must not contain embedded credentials.", call. = FALSE)
  }
  if (grepl("[?#]", server)) {
    stop("server must not contain a query string or fragment.", call. = FALSE)
  }
  if (grepl("/rest$", server, ignore.case = TRUE)) {
    return(server)
  }
  paste0(server, "/rest")
}

.ndex_web_server <- function(rest_server) {
  sub("/rest$", "", rest_server, ignore.case = TRUE)
}

.ndex_validate_auth <- function(server, username, password, token) {
  .ndex_assert_optional_string(username, "username")
  .ndex_assert_optional_string(password, "password")
  .ndex_assert_optional_string(token, "token")
  if (xor(is.null(username), is.null(password))) {
    stop("username and password must be supplied together.", call. = FALSE)
  }
  if (!is.null(token) && !is.null(username)) {
    stop("Use either token authentication or username/password, not both.",
      call. = FALSE)
  }
  if ((!is.null(token) || !is.null(username)) &&
      grepl("^http://", server, ignore.case = TRUE) &&
      !grepl("^http://(localhost|127\\.0\\.0\\.1)([:/]|$)", server,
        ignore.case = TRUE)) {
    stop("Authenticated NDEx requests require HTTPS except on localhost.",
      call. = FALSE)
  }
  invisible(NULL)
}

.ndex_redact <- function(text, secrets) {
  secrets <- unique(as.character(secrets))
  secrets <- secrets[!is.na(secrets) & nzchar(secrets)]
  for (secret in secrets) {
    encoded <- utils::URLencode(secret, reserved = TRUE)
    text <- gsub(secret, "<redacted>", text, fixed = TRUE)
    if (!identical(encoded, secret)) {
      text <- gsub(encoded, "<redacted>", text, fixed = TRUE)
    }
  }
  text
}

.ndex_request_secrets <- function(query, password, token) {
  query_secrets <- character()
  if (length(query) && !is.null(names(query))) {
    sensitive <- grepl("key|token|password|secret", names(query),
      ignore.case = TRUE)
    query_secrets <- unlist(query[sensitive], recursive = TRUE,
      use.names = FALSE)
  }
  c(password, token, query_secrets)
}

.ndex_encode_query <- function(query) {
  if (is.null(query) || !length(query)) return("")
  keep <- !vapply(query, is.null, logical(1))
  query <- query[keep]
  if (!length(query)) return("")
  values <- vapply(query, function(value) {
    if (is.logical(value)) value <- tolower(as.character(value))
    utils::URLencode(as.character(value[[1L]]), reserved = TRUE)
  }, character(1))
  paste0("?", paste0(utils::URLencode(names(query), reserved = TRUE), "=",
    values, collapse = "&"))
}

.ndex_http_request <- function(method, url, query = NULL, body = NULL,
    destination = NULL, username = NULL, password = NULL, token = NULL,
    timeout = 300, max_bytes = Inf) {
  method <- match.arg(method, c("GET", "POST"))
  .ndex_validate_auth(url, username, password, token)
  if (!is.numeric(timeout) || length(timeout) != 1L || is.na(timeout) ||
      !is.finite(timeout) || timeout <= 0) {
    stop("timeout must be one positive finite number.", call. = FALSE)
  }
  if (!is.numeric(max_bytes) || length(max_bytes) != 1L ||
      is.na(max_bytes) || max_bytes <= 0) {
    stop("max_bytes must be one positive number or Inf.", call. = FALSE)
  }
  secrets <- .ndex_request_secrets(query, password, token)
  request_url <- paste0(url, .ndex_encode_query(query))
  handle <- curl::new_handle()
  curl::handle_setopt(handle, timeout = timeout, followlocation = FALSE,
    useragent = "NEArender NDEx client")
  headers <- c(Accept = "application/json")
  if (!is.null(token)) headers <- c(headers,
    Authorization = paste("Bearer", token))
  if (method == "POST") {
    payload <- jsonlite::toJSON(body, auto_unbox = TRUE, null = "null",
      na = "null")
    curl::handle_setopt(handle, customrequest = "POST", postfields = payload)
    headers <- c(headers, `Content-Type` = "application/json")
  }
  curl::handle_setheaders(handle, .list = headers)
  if (!is.null(username)) {
    curl::handle_setopt(handle, username = username, password = password,
      httpauth = 1L)
  }
  output <- NULL
  received <- 0
  limit_exceeded <- FALSE
  close_output <- function() {
    if (!is.null(output)) {
      close(output)
      output <<- NULL
    }
  }
  on.exit(close_output(), add = TRUE)
  response <- tryCatch({
    if (is.null(destination)) {
      curl::curl_fetch_memory(request_url, handle = handle)
    } else {
      output <- file(destination, open = "wb")
      response <- curl::curl_fetch_stream(request_url, function(chunk) {
        next_bytes <- received + length(chunk)
        if (is.finite(max_bytes) && next_bytes > max_bytes) {
          limit_exceeded <<- TRUE
          stop("NDEx download exceeded max_bytes.", call. = FALSE)
        }
        writeBin(chunk, output)
        received <<- next_bytes
      }, handle = handle)
      close_output()
      response
    }
  }, error = function(error) {
    close_output()
    if (!is.null(destination) && file.exists(destination)) unlink(destination)
    if (limit_exceeded) {
      .ndex_stop("The NDEx download exceeded max_bytes during transfer.",
        "limit")
    }
    detail <- .ndex_redact(conditionMessage(error), secrets)
    .ndex_stop(paste0("Could not contact the NDEx server at ", url,
      ". Check Internet/server availability. Original error: ",
      detail), "connection")
  })
  status <- as.integer(response$status_code)
  if (is.na(status) || status < 200L || status >= 300L) {
    detail <- ""
    if (is.null(destination) && length(response$content)) {
      detail <- rawToChar(response$content)
    } else if (!is.null(destination) && file.exists(destination)) {
      bytes <- readBin(destination, what = "raw", n = 4096L)
      detail <- rawToChar(bytes)
      unlink(destination)
    }
    detail <- .ndex_redact(detail, secrets)
    detail <- gsub("[\\r\\n]+", " ", detail)
    if (nchar(detail) > 300L) detail <- paste0(substr(detail, 1L, 300L), "...")
    suffix <- if (nzchar(detail)) paste0(" Server response: ", detail) else ""
    .ndex_stop(paste0("NDEx request failed with HTTP status ", status,
      " at ", url, ".", suffix), "http", status)
  }
  response
}

.ndex_http_json <- function(method, url, query = NULL, body = NULL,
    username = NULL, password = NULL, token = NULL, timeout = 300) {
  response <- .ndex_http_request(method, url, query, body,
    username = username, password = password, token = token, timeout = timeout)
  text <- rawToChar(response$content)
  tryCatch(
    jsonlite::fromJSON(text, simplifyVector = FALSE),
    error = function(error) .ndex_stop(paste0(
      "NDEx returned malformed JSON. Original error: ",
      conditionMessage(error)), "response")
  )
}

.ndex_http_download <- function(url, destination, query = NULL,
    username = NULL, password = NULL, token = NULL, timeout = 300,
    max_bytes = Inf) {
  .ndex_http_request("GET", url, query = query, destination = destination,
    username = username, password = password, token = token, timeout = timeout,
    max_bytes = max_bytes)
}

.ndex_uuid_pattern <- paste0(
  "[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-",
  "[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}")

.ndex_resource <- function(resource, server = NULL, allow_path = FALSE) {
  if (allow_path && is.character(resource) && length(resource) == 1L &&
      !is.na(resource) && file.exists(resource)) {
    return(list(path = normalizePath(resource), uuid = NULL, server = NULL))
  }
  row_server <- NULL
  if (is.data.frame(resource)) {
    if (nrow(resource) != 1L) {
      stop("A catalog resource must contain exactly one row.", call. = FALSE)
    }
    id_column <- intersect(c("uuid", "externalId", "external_id"),
      names(resource))
    if (!length(id_column)) {
      stop("A catalog resource must contain a uuid column.", call. = FALSE)
    }
    value <- resource[[id_column[[1L]]]][[1L]]
    if ("server" %in% names(resource)) row_server <- resource$server[[1L]]
  } else {
    if (!is.character(resource) || length(resource) != 1L || is.na(resource) ||
        !nzchar(resource)) {
      stop("resource must be one NDEx UUID, network URL, or catalog row.",
        call. = FALSE)
    }
    value <- resource
    if (grepl("^https?://", value, ignore.case = TRUE)) {
      origin <- sub("^(https?://[^/]+).*$", "\\1", value,
        ignore.case = TRUE)
      if (!identical(origin, value)) row_server <- origin
    }
  }
  matches <- regmatches(as.character(value), gregexpr(.ndex_uuid_pattern,
    as.character(value), perl = TRUE))[[1L]]
  if (length(matches) != 1L || identical(matches, character(0))) {
    stop("resource must contain exactly one NDEx network UUID.", call. = FALSE)
  }
  selected_server <- if (!is.null(server)) server else row_server
  list(path = NULL, uuid = tolower(matches[[1L]]),
    server = .ndex_normalize_server(selected_server))
}

.ndex_property <- function(properties, name, default = NA_character_) {
  if (is.null(properties) || is.null(properties[[name]])) return(default)
  value <- properties[[name]]
  if (is.list(value) && !is.null(value$v)) value <- value$v
  .ndex_scalar_character(value, default)
}

.ndex_time_string <- function(value) {
  if (is.null(value) || !length(value) || is.na(value[[1L]])) {
    return(NA_character_)
  }
  value <- value[[1L]]
  if (is.numeric(value) || (is.character(value) &&
      grepl("^[0-9]+(?:\\.[0-9]+)?$", value))) {
    number <- suppressWarnings(as.numeric(value))
    if (!is.finite(number)) return(NA_character_)
    if (number > 1e11) number <- number / 1000
    return(format(as.POSIXct(number, origin = "1970-01-01", tz = "UTC"),
      "%Y-%m-%dT%H:%M:%SZ", tz = "UTC"))
  }
  as.character(value)
}

.ndex_catalog_row <- function(record, server, source = c("search", "summary")) {
  source <- match.arg(source)
  attributes <- if (source == "search") record$attributes else record$properties
  property <- function(name, default = NA_character_) {
    .ndex_property(attributes, name, default)
  }
  direct_or_property <- function(name, default = NA_character_) {
    direct <- record[[name]]
    if (!is.null(direct) && length(direct)) {
      return(.ndex_scalar_character(direct, default))
    }
    property(name, default)
  }
  uuid <- direct_or_property("uuid")
  node_count <- if (source == "search") {
    .ndex_scalar_numeric(attributes$nodeCount)
  } else .ndex_scalar_numeric(record$nodeCount)
  edge_count <- if (source == "search") {
    .ndex_scalar_numeric(record$edges)
  } else .ndex_scalar_numeric(record$edgeCount)
  cx_bytes <- if (source == "search") {
    .ndex_scalar_numeric(attributes$cxFileSize)
  } else .ndex_scalar_numeric(record$cxFileSize)
  cx2_bytes <- if (source == "search") {
    .ndex_scalar_numeric(attributes$cx2FileSize)
  } else .ndex_scalar_numeric(record$cx2FileSize)
  completed <- if (source == "search") record$isCompleted else record$completed
  valid <- if (source == "search") record$isValid else record$isValid
  data.frame(
    uuid = uuid,
    name = direct_or_property("name"),
    owner = direct_or_property("owner"),
    version = direct_or_property("version"),
    description = direct_or_property("description"),
    organism = property("organism"),
    rights = property("rights"),
    rights_holder = property("rightsHolder"),
    reference = property("reference"),
    visibility = direct_or_property("visibility"),
    node_count = node_count,
    edge_count = edge_count,
    cx_bytes = cx_bytes,
    cx2_bytes = cx2_bytes,
    modification_time = .ndex_time_string(record$modificationTime),
    doi = direct_or_property("doi"),
    certified = .ndex_scalar_logical(record$isCertified),
    valid = .ndex_scalar_logical(valid),
    completed = .ndex_scalar_logical(completed),
    server = server,
    web_url = paste0(.ndex_web_server(server), "/viewer/networks/", uuid),
    stringsAsFactors = FALSE
  )
}

.ndex_empty_catalog <- function() {
  data.frame(
    uuid = character(), name = character(), owner = character(),
    version = character(), description = character(), organism = character(),
    rights = character(), rights_holder = character(), reference = character(),
    visibility = character(), node_count = numeric(), edge_count = numeric(),
    cx_bytes = numeric(), cx2_bytes = numeric(), modification_time = character(),
    doi = character(), certified = logical(), valid = logical(),
    completed = logical(), server = character(), web_url = character(),
    stringsAsFactors = FALSE
  )
}

.ndex_catalog <- function(rows, total = NULL, offset = NULL, query = NULL,
    server = NULL) {
  result <- if (!length(rows)) .ndex_empty_catalog() else do.call(rbind, rows)
  rownames(result) <- NULL
  class(result) <- c("nearender_ndex_catalog", "data.frame")
  if (!is.null(total)) attr(result, "total_hits") <- as.numeric(total)
  if (!is.null(offset)) attr(result, "offset") <- as.integer(offset)
  if (!is.null(query)) attr(result, "query") <- query
  if (!is.null(server)) attr(result, "server") <- server
  result
}

#' Search the NDEx network catalog
#'
#' Query an NDEx 3 server for network resources and return a stable, tabular
#' catalog. Search is an explicit network operation; it is never called by a
#' renderer or loader. The result can be serialized directly by a web-service
#' adapter, and a one-row result can be passed to [ndex_network_summary()] or
#' [download_ndex_network()].
#'
#' @param query Search text. The default `"*:*"` lists networks visible under
#'   the selected filters.
#' @param account Optional NDEx account name used to restrict ownership.
#' @param visibility Visibility filter: public, private, or all resources the
#'   credentials can read. Private searches require authentication.
#' @param offset Zero-based result offset.
#' @param limit Maximum number of rows, from 1 through 1000. Use pagination for
#'   larger catalogs.
#' @param server NDEx server root or REST root. Defaults to the public NDEx
#'   server. Redirects are not followed. Internet-facing callers must allow-list
#'   trusted HTTPS origins rather than passing an arbitrary user-supplied URL.
#' @param username,password Optional Basic authentication pair.
#' @param token Optional bearer token. Do not combine with Basic credentials.
#' @param timeout Positive request timeout in seconds.
#' @return A `nearender_ndex_catalog` data frame. The `total_hits` attribute
#'   reports the number of matches on the server.
#' @seealso [ndex_network_summary()], [download_ndex_network()],
#'   [load_ndex_network()]
#' @examples
#' \dontrun{
#' catalog <- search_ndex_networks("SIGNOR", limit = 20)
#' catalog[, c("uuid", "name", "owner", "node_count", "edge_count")]
#' }
#' @export
search_ndex_networks <- function(query = "*:*", account = NULL,
    visibility = c("PUBLIC", "PRIVATE", "all"), offset = 0L, limit = 100L,
    server = NULL, username = NULL, password = NULL, token = NULL,
    timeout = 300) {
  if (!is.character(query) || length(query) != 1L || is.na(query) ||
      !nzchar(query)) {
    stop("query must be one non-empty character value.", call. = FALSE)
  }
  .ndex_assert_optional_string(account, "account")
  visibility <- match.arg(visibility)
  if (!is.numeric(offset) || length(offset) != 1L || is.na(offset) ||
      !is.finite(offset) || offset < 0 || offset != as.integer(offset)) {
    stop("offset must be one non-negative integer.", call. = FALSE)
  }
  if (!is.numeric(limit) || length(limit) != 1L || is.na(limit) ||
      !is.finite(limit) || limit < 1 || limit > 1000 ||
      limit != as.integer(limit)) {
    stop("limit must be one integer from 1 through 1000.", call. = FALSE)
  }
  server <- .ndex_normalize_server(server)
  .ndex_validate_auth(server, username, password, token)
  body <- list(type = "NETWORK", searchString = query)
  if (!is.null(account)) body$accountName <- account
  parameters <- list(start = as.integer(offset), size = as.integer(limit))
  if (visibility != "all") parameters$visibility <- visibility
  response <- .ndex_http_json("POST", paste0(server, "/v3/search/files"),
    query = parameters, body = body, username = username,
    password = password, token = token, timeout = timeout)
  files <- response$files
  if (is.null(files)) files <- list()
  rows <- lapply(files, .ndex_catalog_row, server = server, source = "search")
  .ndex_catalog(rows, total = .ndex_scalar_numeric(response$numFound, 0),
    offset = .ndex_scalar_numeric(response$start, offset), query = query,
    server = server)
}

.ndex_get_summary_raw <- function(resource, server = NULL, access_key = NULL,
    username = NULL, password = NULL, token = NULL, timeout = 300) {
  resolved <- .ndex_resource(resource, server)
  .ndex_assert_optional_string(access_key, "access_key")
  response <- .ndex_http_json("GET", paste0(resolved$server,
    "/v3/networks/", resolved$uuid, "/summary"),
    query = list(format = "FULL", accesskey = access_key),
    username = username, password = password, token = token, timeout = timeout)
  if (is.null(response$uuid)) response$uuid <- resolved$uuid
  attr(response, "server") <- resolved$server
  response
}

#' Retrieve one NDEx network summary
#'
#' Retrieve current metadata before deciding whether to download a network.
#' This is an explicit online operation and returns the same columns as
#' [search_ndex_networks()].
#'
#' @param resource One NDEx network UUID, NDEx network URL, or one row returned
#'   by [search_ndex_networks()].
#' @inheritParams search_ndex_networks
#' @param access_key Optional NDEx access key for an unlisted resource. It is
#'   used only for the request and is never written to a manifest.
#' @return A one-row `nearender_ndex_catalog` data frame.
#' @examples
#' \dontrun{
#' ndex_network_summary("f71ab602-97f0-11eb-9e72-0ac135e8bacf")
#' }
#' @export
ndex_network_summary <- function(resource, server = NULL, access_key = NULL,
    username = NULL, password = NULL, token = NULL, timeout = 300) {
  summary <- .ndex_get_summary_raw(resource, server, access_key, username,
    password, token, timeout)
  rest_server <- attr(summary, "server", exact = TRUE)
  .ndex_catalog(list(.ndex_catalog_row(summary, rest_server, "summary")),
    total = 1, offset = 0L, server = rest_server)
}

.ndex_server_key <- function(server) {
  key <- sub("^https?://", "", tolower(server))
  key <- gsub("[^a-z0-9._-]+", "_", key)
  sub("_+$", "", key)
}

.ndex_snapshot_id <- function(summary) {
  modified <- .ndex_scalar_numeric(summary$modificationTime)
  if (!is.na(modified)) return(paste0("m", format(modified,
    scientific = FALSE, trim = TRUE, digits = 16)))
  modified_text <- .ndex_scalar_character(summary$modificationTime)
  if (!is.na(modified_text)) {
    key <- gsub("[^A-Za-z0-9._-]+", "_", modified_text)
    if (nzchar(key)) return(paste0("m", key))
  }
  paste0("retrieved-", format(Sys.time(), "%Y%m%dT%H%M%SZ", tz = "UTC"))
}

.ndex_cache_paths <- function(root, server, uuid, snapshot, format) {
  directory <- file.path(root, "NDEx", .ndex_server_key(server), uuid,
    snapshot)
  extension <- if (format == "cx2") "cx2.json" else "cx.json"
  list(
    directory = directory,
    artifact = file.path(directory, paste0(uuid, ".", extension)),
    manifest = file.path(directory, paste0(format, ".manifest.rds")),
    pointer = file.path(root, "NDEx", .ndex_server_key(server), uuid,
      paste0("current-", format, ".rds"))
  )
}

.ndex_atomic_rds <- function(object, path) {
  directory <- dirname(path)
  dir.create(directory, recursive = TRUE, showWarnings = FALSE)
  temporary <- tempfile("ndex-rds-", tmpdir = directory)
  on.exit(unlink(temporary), add = TRUE)
  saveRDS(object, temporary)
  if (!file.rename(temporary, path)) {
    if (file.exists(path)) unlink(path)
    if (!file.rename(temporary, path)) {
      stop("Could not write the NDEx cache manifest.", call. = FALSE)
    }
  }
  invisible(path)
}

.ndex_expected_bytes <- function(summary, format) {
  field <- if (format == "cx2") summary$cx2FileSize else summary$cxFileSize
  .ndex_scalar_numeric(field)
}

.ndex_validate_format <- function(path, format) {
  if (!format %in% c("cx2", "cx")) {
    .ndex_stop("The NDEx cache manifest has an unsupported format.", "cache")
  }
  connection <- file(path, open = "rb")
  on.exit(close(connection), add = TRUE)
  prefix <- readChar(connection, nchars = 4096L, useBytes = TRUE)
  close(connection)
  on.exit(NULL, add = FALSE)
  bytes <- unname(file.info(path)$size)
  validation <- "header"
  if (!is.na(bytes) && bytes <= 10 * 1024^2) {
    connection <- file(path, open = "rb")
    on.exit(close(connection), add = TRUE)
    valid_json <- tryCatch({
      jsonlite::parse_json(connection, simplifyVector = FALSE,
        bigint_as_char = TRUE)
      TRUE
    }, error = function(error) FALSE)
    if (!isTRUE(valid_json)) {
      .ndex_stop("The downloaded NDEx artifact is not valid JSON.", "artifact")
    }
    validation <- "full"
  }
  valid_marker <- if (format == "cx2") {
    grepl('"CXVersion"[[:space:]]*:[[:space:]]*"2\\.0"', prefix)
  } else {
    grepl('"numberVerification"[[:space:]]*:', prefix)
  }
  if (!valid_marker) {
    .ndex_stop(paste0("The downloaded artifact is not an NDEx ",
      toupper(format), " network."), "artifact")
  }
  invisible(validation)
}

.ndex_verify_cached <- function(paths) {
  if (!file.exists(paths$artifact) || !file.exists(paths$manifest)) {
    .ndex_stop("The NDEx cache snapshot is incomplete.", "cache")
  }
  manifest <- readRDS(paths$manifest)
  bytes <- unname(file.info(paths$artifact)$size)
  md5 <- unname(tools::md5sum(paths$artifact))
  if (is.null(manifest$bytes) || is.null(manifest$md5) ||
      !identical(as.numeric(bytes), as.numeric(manifest$bytes)) ||
      !identical(as.character(md5), as.character(manifest$md5))) {
    .ndex_stop("The cached NDEx artifact failed size or checksum verification.",
      "cache")
  }
  .ndex_validate_format(paths$artifact, manifest$format)
  list(path = normalizePath(paths$artifact), manifest = manifest)
}

#' Download an NDEx network snapshot
#'
#' Download one arbitrary NDEx network in native CX2 (NDEx 3) or CX (NDEx 2)
#' format. The current server summary is recorded first; the raw response is
#' written to a temporary file, checked for the requested exchange-format
#' marker and against the advertised byte count, checksummed, and atomically
#' installed in a snapshot cache. Artifacts up to 10 MiB are also fully parsed
#' as JSON before installation; larger artifacts are fully parsed when loaded.
#' Repeated calls reuse a verified snapshot unless `force = TRUE`.
#'
#' @inheritParams ndex_network_summary
#' @param format Native exchange format. CX2 is the current default; CX is
#'   provided for compatibility with clients that require the v2 representation.
#' @param cache_dir Explicit cache root required for this writing operation.
#' @param force Replace a valid cached snapshot.
#' @param quiet Suppress download messages.
#' @param max_bytes Maximum advertised and downloaded artifact size. The
#'   default is one gigabyte; use `Inf` only when the caller provides its own
#'   resource controls. The limit is enforced while response bytes are written.
#' @return The normalized raw artifact path, invisibly.
#' @seealso [search_ndex_networks()], [load_ndex_network()], [manifest()]
#' @examples
#' \dontrun{
#' path <- download_ndex_network(
#'   "f71ab602-97f0-11eb-9e72-0ac135e8bacf",
#'   cache_dir = file.path(tempdir(), "NEArender-cache")
#' )
#' }
#' @export
download_ndex_network <- function(resource, format = c("cx2", "cx"),
    cache_dir = NULL, force = FALSE, quiet = FALSE, max_bytes = 1e9,
    server = NULL, access_key = NULL, username = NULL, password = NULL,
    token = NULL, timeout = 300) {
  format <- match.arg(format)
  .assert_flag(force, "force")
  .assert_flag(quiet, "quiet")
  if (!is.numeric(max_bytes) || length(max_bytes) != 1L ||
      is.na(max_bytes) || max_bytes <= 0) {
    stop("max_bytes must be one positive number or Inf.", call. = FALSE)
  }
  cache_dir <- .explicit_cache_dir(cache_dir)
  summary <- .ndex_get_summary_raw(resource, server, access_key, username,
    password, token, timeout)
  rest_server <- attr(summary, "server", exact = TRUE)
  uuid <- .ndex_scalar_character(summary$uuid)
  if (is.na(uuid)) uuid <- .ndex_resource(resource, server)$uuid
  completed <- .ndex_scalar_logical(summary$completed)
  if (identical(completed, FALSE)) {
    .ndex_stop("The NDEx network is not ready for download.", "resource")
  }
  expected_bytes <- .ndex_expected_bytes(summary, format)
  if (!is.na(expected_bytes) && is.finite(max_bytes) &&
      expected_bytes > max_bytes) {
    .ndex_stop(paste0("The NDEx network advertises ", expected_bytes,
      " bytes, exceeding max_bytes."), "limit")
  }
  snapshot <- .ndex_snapshot_id(summary)
  paths <- .ndex_cache_paths(.database_cache_dir(cache_dir), rest_server,
    uuid, snapshot, format)
  if (file.exists(paths$artifact) && file.exists(paths$manifest) && !force) {
    verified <- .ndex_verify_cached(paths)
    .ndex_atomic_rds(list(snapshot = snapshot, format = format), paths$pointer)
    return(invisible(verified$path))
  }
  dir.create(paths$directory, recursive = TRUE, showWarnings = FALSE)
  temporary <- tempfile("ndex-download-", tmpdir = paths$directory)
  on.exit(unlink(temporary), add = TRUE)
  api_version <- if (format == "cx2") "v3" else "v2"
  endpoint <- if (format == "cx2") {
    paste0(rest_server, "/v3/networks/", uuid)
  } else paste0(rest_server, "/v2/network/", uuid)
  if (!quiet) message("Downloading NDEx network ", uuid, " as ",
    toupper(format), ".")
  .ndex_http_download(endpoint, temporary,
    query = list(download = TRUE, accesskey = access_key),
    username = username, password = password, token = token, timeout = timeout,
    max_bytes = max_bytes)
  bytes <- unname(file.info(temporary)$size)
  if (is.na(bytes) || bytes <= 0) {
    .ndex_stop("The downloaded NDEx artifact is empty.", "artifact")
  }
  if (is.finite(max_bytes) && bytes > max_bytes) {
    .ndex_stop("The downloaded NDEx artifact exceeds max_bytes.", "limit")
  }
  if (!is.na(expected_bytes) && bytes != expected_bytes) {
    .ndex_stop(paste0("The NDEx network changed during download: expected ",
      expected_bytes, " bytes but received ", bytes, ". Retry to acquire a ",
      "consistent snapshot."), "artifact")
  }
  validation <- .ndex_validate_format(temporary, format)
  md5 <- unname(tools::md5sum(temporary))
  if (!file.rename(temporary, paths$artifact)) {
    if (file.exists(paths$artifact)) unlink(paths$artifact)
    if (!file.rename(temporary, paths$artifact)) {
      stop("Could not move the NDEx artifact into the cache.", call. = FALSE)
    }
  }
  manifest <- list(
    provider = "NDEx", server = rest_server, uuid = uuid,
    snapshot = snapshot, name = .ndex_scalar_character(summary$name),
    version = .ndex_property(summary$properties, "version"),
    modification_time = .ndex_time_string(summary$modificationTime),
    owner = .ndex_scalar_character(summary$owner),
    visibility = .ndex_scalar_character(summary$visibility),
    rights = .ndex_property(summary$properties, "rights"),
    rights_holder = .ndex_property(summary$properties, "rightsHolder"),
    reference = .ndex_property(summary$properties, "reference"),
    format = format, validation = validation, api_version = api_version,
    retrieved_at = base::format(Sys.time(), tz = "UTC", usetz = TRUE),
    bytes = as.numeric(bytes), expected_bytes = expected_bytes,
    md5 = as.character(md5), node_count = .ndex_scalar_numeric(
      summary$nodeCount), edge_count = .ndex_scalar_numeric(summary$edgeCount),
    summary = summary
  )
  .ndex_atomic_rds(manifest, paths$manifest)
  .ndex_atomic_rds(list(snapshot = snapshot, format = format), paths$pointer)
  invisible(normalizePath(paths$artifact))
}

.ndex_locate_cache <- function(resource, cache_dir, server, snapshot, format) {
  resolved <- .ndex_resource(resource, server)
  root <- .database_cache_dir(cache_dir)
  formats <- if (format == "auto") c("cx2", "cx") else format
  for (candidate in formats) {
    selected_snapshot <- snapshot
    base <- file.path(root, "NDEx", .ndex_server_key(resolved$server),
      resolved$uuid)
    if (is.null(selected_snapshot)) {
      pointer <- file.path(base, paste0("current-", candidate, ".rds"))
      if (!file.exists(pointer)) next
      current <- readRDS(pointer)
      selected_snapshot <- current$snapshot
    }
    if (!is.character(selected_snapshot) || length(selected_snapshot) != 1L ||
        is.na(selected_snapshot) || !grepl("^[A-Za-z0-9._-]+$",
          selected_snapshot)) {
      .ndex_stop("The NDEx cache snapshot identifier is malformed.", "cache")
    }
    paths <- .ndex_cache_paths(root, resolved$server, resolved$uuid,
      selected_snapshot, candidate)
    if (file.exists(paths$artifact) || file.exists(paths$manifest)) return(paths)
  }
  .ndex_stop("The NDEx network is not cached; call download_ndex_network() explicitly first.",
    "cache")
}

.ndex_aspects <- function(cx, name) {
  values <- list()
  for (fragment in cx) {
    if (!is.list(fragment) || is.null(fragment[[name]])) next
    aspect <- fragment[[name]]
    if (!is.list(aspect)) next
    values <- c(values, aspect)
  }
  values
}

.ndex_cx2_declarations <- function(cx, scope) {
  declarations <- .ndex_aspects(cx, "attributeDeclarations")
  result <- list()
  for (declaration in declarations) {
    scoped <- declaration[[scope]]
    if (!is.null(scoped)) result <- utils::modifyList(result, scoped)
  }
  result
}

.ndex_cx2_key <- function(declarations, key) {
  declaration <- declarations[[key]]
  alias <- if (is.null(declaration)) NULL else declaration$a
  if (is.null(alias) || !length(alias)) key else as.character(alias[[1L]])
}

.ndex_cx2_default <- function(declarations, key) {
  declaration <- declarations[[key]]
  if (is.null(declaration) || is.null(declaration$v)) return(NULL)
  declaration$v
}

.ndex_value <- function(values, key, declarations = list()) {
  alias <- .ndex_cx2_key(declarations, key)
  value <- values[[alias]]
  if (is.null(value) && alias != key) value <- values[[key]]
  if (is.null(value)) value <- .ndex_cx2_default(declarations, key)
  value
}

.ndex_atomic_value <- function(value) {
  if (is.null(value) || !length(value)) return(NA_character_)
  if (is.list(value)) {
    if (length(value) != 1L || is.list(value[[1L]])) return(NA_character_)
    value <- value[[1L]]
  }
  if (length(value) != 1L || is.na(value)) return(NA_character_)
  as.character(value)
}

.ndex_cx2_table <- function(cx, node_key, score_column) {
  header <- cx[[1L]]
  if (is.null(header$CXVersion) ||
      !identical(as.character(header$CXVersion), "2.0")) {
    .ndex_stop("The artifact does not contain a CX2 network.", "artifact")
  }
  statuses <- .ndex_aspects(cx, "status")
  if (length(statuses) && any(vapply(statuses, function(status) {
      identical(status$success, FALSE)
    }, logical(1)))) {
    .ndex_stop("The CX2 stream reports an unsuccessful status.", "artifact")
  }
  nodes <- .ndex_aspects(cx, "nodes")
  edges <- .ndex_aspects(cx, "edges")
  if (!length(nodes) || !length(edges)) {
    .ndex_stop("The CX2 network must contain nodes and edges.", "artifact")
  }
  node_declarations <- .ndex_cx2_declarations(cx, "nodes")
  edge_declarations <- .ndex_cx2_declarations(cx, "edges")
  node_ids <- vapply(nodes, function(node) .ndex_atomic_value(node$id),
    character(1))
  labels <- vapply(nodes, function(node) {
    if (identical(node_key, "id")) return(.ndex_atomic_value(node$id))
    values <- if (is.null(node$v)) list() else node$v
    .ndex_atomic_value(.ndex_value(values, node_key, node_declarations))
  }, character(1))
  if (anyDuplicated(node_ids)) {
    .ndex_stop("The CX2 network contains duplicate node identifiers.", "artifact")
  }
  if (all(is.na(labels) | !nzchar(labels))) {
    .ndex_stop("node_key does not identify a scalar CX2 node attribute.", "artifact")
  }
  lookup <- stats::setNames(labels, node_ids)
  from_ids <- vapply(edges, function(edge) .ndex_atomic_value(edge$s),
    character(1))
  to_ids <- vapply(edges, function(edge) .ndex_atomic_value(edge$t),
    character(1))
  table <- data.frame(from = unname(lookup[from_ids]),
    to = unname(lookup[to_ids]), stringsAsFactors = FALSE)
  if (!is.null(score_column)) {
    table$score <- vapply(edges, function(edge) {
      values <- if (is.null(edge$v)) list() else edge$v
      value <- .ndex_value(values, score_column, edge_declarations)
      suppressWarnings(as.numeric(.ndex_atomic_value(value)))
    }, numeric(1))
    if (all(is.na(table$score))) {
      .ndex_stop("score_column does not identify a scalar numeric CX2 edge attribute.",
        "artifact")
    }
  }
  network_attributes <- .ndex_aspects(cx, "networkAttributes")
  list(edges = table, node_count = length(nodes), edge_count = length(edges),
    network_attributes = network_attributes)
}

.ndex_cx1_attributes <- function(cx, aspect, selected_name) {
  if (is.null(selected_name)) return(character())
  attributes <- .ndex_aspects(cx, aspect)
  attributes <- attributes[vapply(attributes, function(attribute) {
    identical(.ndex_atomic_value(attribute$n), selected_name)
  }, logical(1))]
  if (!length(attributes)) return(character())
  positions <- vapply(attributes, function(attribute) {
    .ndex_atomic_value(attribute$po)
  }, character(1))
  values <- vapply(attributes, function(attribute) {
    .ndex_atomic_value(attribute$v)
  }, character(1))
  stats::setNames(values, positions)
}

.ndex_cx1_table <- function(cx, node_key, score_column) {
  if (!length(.ndex_aspects(cx, "numberVerification"))) {
    .ndex_stop("The artifact does not contain a CX network.", "artifact")
  }
  statuses <- .ndex_aspects(cx, "status")
  if (length(statuses) && any(vapply(statuses, function(status) {
      identical(status$success, FALSE)
    }, logical(1)))) {
    .ndex_stop("The CX stream reports an unsuccessful status.", "artifact")
  }
  nodes <- .ndex_aspects(cx, "nodes")
  edges <- .ndex_aspects(cx, "edges")
  if (!length(nodes) || !length(edges)) {
    .ndex_stop("The CX network must contain nodes and edges.", "artifact")
  }
  node_ids <- vapply(nodes, function(node) .ndex_atomic_value(node[["@id"]]),
    character(1))
  key <- switch(node_key, name = "n", represents = "r", id = "@id",
    node_key)
  supplemental <- if (key %in% c("n", "r", "@id")) character() else {
    .ndex_cx1_attributes(cx, "nodeAttributes", node_key)
  }
  labels <- vapply(nodes, function(node) {
    id <- .ndex_atomic_value(node[["@id"]])
    value <- node[[key]]
    if (is.null(value) && length(supplemental)) {
      selected <- supplemental[id]
      if (length(selected)) value <- unname(selected[[1L]])
    }
    .ndex_atomic_value(value)
  }, character(1))
  if (anyDuplicated(node_ids)) {
    .ndex_stop("The CX network contains duplicate node identifiers.", "artifact")
  }
  if (all(is.na(labels) | !nzchar(labels))) {
    .ndex_stop("node_key does not identify a scalar CX node attribute.", "artifact")
  }
  lookup <- stats::setNames(labels, node_ids)
  from_ids <- vapply(edges, function(edge) .ndex_atomic_value(edge$s),
    character(1))
  to_ids <- vapply(edges, function(edge) .ndex_atomic_value(edge$t),
    character(1))
  table <- data.frame(from = unname(lookup[from_ids]),
    to = unname(lookup[to_ids]), stringsAsFactors = FALSE)
  if (!is.null(score_column)) {
    core_key <- if (score_column == "interaction") "i" else score_column
    supplemental_score <- .ndex_cx1_attributes(cx, "edgeAttributes",
      score_column)
    table$score <- vapply(edges, function(edge) {
      edge_id <- .ndex_atomic_value(edge[["@id"]])
      value <- edge[[core_key]]
      if (is.null(value) && length(supplemental_score)) {
        selected <- supplemental_score[edge_id]
        if (length(selected)) value <- unname(selected[[1L]])
      }
      suppressWarnings(as.numeric(.ndex_atomic_value(value)))
    }, numeric(1))
    if (all(is.na(table$score))) {
      .ndex_stop("score_column does not identify a scalar numeric CX edge attribute.",
        "artifact")
    }
  }
  network_attributes <- .ndex_aspects(cx, "networkAttributes")
  list(edges = table, node_count = length(nodes), edge_count = length(edges),
    network_attributes = network_attributes)
}

.ndex_read_artifact <- function(path, format, node_key, score_column,
    max_bytes) {
  bytes <- unname(file.info(path)$size)
  if (is.na(bytes) || bytes <= 0) {
    .ndex_stop("The NDEx artifact is empty.", "artifact")
  }
  if (is.finite(max_bytes) && bytes > max_bytes) {
    .ndex_stop("The NDEx artifact exceeds max_bytes for in-memory parsing.",
      "limit")
  }
  cx <- tryCatch(jsonlite::fromJSON(path, simplifyVector = FALSE,
      bigint_as_char = TRUE),
    error = function(error) .ndex_stop(paste0(
      "Could not parse the NDEx artifact: ", conditionMessage(error)),
      "artifact"))
  if (!is.list(cx) || !length(cx)) {
    .ndex_stop("The NDEx artifact has no CX aspects.", "artifact")
  }
  if (format == "auto") {
    format <- if (!is.null(cx[[1L]]$CXVersion)) "cx2" else if (
      !is.null(cx[[1L]]$numberVerification)) "cx" else NA_character_
    if (is.na(format)) {
      .ndex_stop("Could not identify the NDEx artifact as CX2 or CX.",
        "artifact")
    }
  }
  parsed <- if (format == "cx2") {
    .ndex_cx2_table(cx, node_key, score_column)
  } else .ndex_cx1_table(cx, node_key, score_column)
  parsed$format <- format
  parsed
}

#' Load a cached or local NDEx network
#'
#' Parse a previously downloaded CX2/CX artifact and project it into
#' NEArender's simple undirected network model. Loading is strictly offline.
#' Node identifiers come from the explicitly selected CX node attribute;
#' direction, visual styles, and unselected attributes remain in the raw
#' artifact rather than being guessed into the analytical network. Reciprocal
#' and duplicate edges are collapsed by [import_network()].
#'
#' @param resource One cached NDEx UUID, one catalog row, or a local CX/CX2
#'   artifact path. A path need not reside in the NEArender cache.
#' @param species Required species declaration passed to [import_network()].
#'   Use explicit `NULL` for unsupported species or non-biological nodes.
#' @param input_id_format Submitted node identifier format. It defaults to the
#'   species master format and must be explicit when `species = NULL`.
#' @param cache_dir Cache root used when `resource` is a UUID or catalog row.
#' @param snapshot Optional cached snapshot identifier. By default the most
#'   recently downloaded snapshot pointer is used.
#' @param format Exchange format. `"auto"` detects a local file and prefers a
#'   cached CX2 snapshot over CX.
#' @param node_key CX node identifier field. Use `"name"`, `"represents"`,
#'   `"id"`, or any scalar node attribute present in the network.
#' @param score_column Optional scalar numeric CX edge attribute to retain as
#'   the canonical NEArender edge weight.
#' @param max_bytes Maximum raw artifact size accepted for in-memory JSON
#'   parsing.
#' @param output_network_format Return an igraph, sparse, or legacy NEArender
#'   network.
#' @param min_score,n_top,greedy Edge filtering passed to [import_network()].
#' @param case_sensitive Preserve identifier case.
#' @param verbose Report import dimensions.
#' @param id_mappings Optional object from [load_id_mappings()].
#' @param ambiguous,unmapped Identifier mapping policies passed to
#'   [import_network()].
#' @inheritParams ndex_network_summary
#' @return A normalized NEArender network with NDEx acquisition and projection
#'   provenance available through [manifest()].
#' @seealso [download_ndex_network()], [search_ndex_networks()],
#'   [import_network()]
#' @examples
#' \dontrun{
#' download_ndex_network("f71ab602-97f0-11eb-9e72-0ac135e8bacf")
#' network <- load_ndex_network(
#'   "f71ab602-97f0-11eb-9e72-0ac135e8bacf",
#'   species = "human", node_key = "name"
#' )
#' manifest(network)
#' }
#' @export
load_ndex_network <- function(resource, species,
    input_id_format = master_id_format(species), cache_dir = NULL,
    snapshot = NULL, format = c("auto", "cx2", "cx"), node_key = "name",
    score_column = NULL, max_bytes = 1e9,
    output_network_format = c("igraph", "sparse", "legacy"),
    min_score = NULL, n_top = NULL, greedy = TRUE, case_sensitive = FALSE,
    verbose = TRUE, id_mappings = NULL,
    ambiguous = c("error", "drop", "first", "expand"),
    unmapped = c("keep", "drop", "error"), server = NULL) {
  format <- match.arg(format)
  output_network_format <- match.arg(output_network_format)
  ambiguous <- match.arg(ambiguous)
  unmapped <- match.arg(unmapped)
  if (!is.character(node_key) || length(node_key) != 1L || is.na(node_key) ||
      !nzchar(node_key)) {
    stop("node_key must be one non-empty character value.", call. = FALSE)
  }
  .ndex_assert_optional_string(score_column, "score_column")
  .ndex_assert_optional_string(snapshot, "snapshot")
  if (!is.numeric(max_bytes) || length(max_bytes) != 1L ||
      is.na(max_bytes) || max_bytes <= 0) {
    stop("max_bytes must be one positive number or Inf.", call. = FALSE)
  }
  resolved <- .ndex_resource(resource, server, allow_path = TRUE)
  download_manifest <- NULL
  if (!is.null(resolved$path)) {
    path <- resolved$path
  } else {
    paths <- .ndex_locate_cache(resource, cache_dir, server, snapshot, format)
    verified <- .ndex_verify_cached(paths)
    path <- verified$path
    download_manifest <- verified$manifest
    if (format == "auto") format <- download_manifest$format
  }
  parsed <- .ndex_read_artifact(path, format, node_key, score_column,
    max_bytes)
  edges <- parsed$edges
  attr(edges, "nearender_zero_score_is_edge") <- TRUE
  network <- import_network(edges, from_column = "from", to_column = "to",
    score_column = if (is.null(score_column)) NULL else "score",
    min_score = min_score, n_top = n_top, greedy = greedy,
    case_sensitive = case_sensitive, verbose = verbose,
    output_network_format = output_network_format, species = species,
    input_id_format = input_id_format, id_mappings = id_mappings,
    ambiguous = ambiguous, unmapped = unmapped)
  source_manifest <- if (is.null(download_manifest)) {
    list(provider = "NDEx", source = "local_file", path = path,
      format = parsed$format, bytes = as.numeric(file.info(path)$size),
      md5 = unname(tools::md5sum(path)))
  } else download_manifest
  source_manifest$parser <- "ndex_cx"
  source_manifest$parser_version <- .ndex_parser_version
  source_manifest$node_key <- node_key
  source_manifest$score_column <- if (is.null(score_column)) {
    NA_character_
  } else score_column
  source_manifest$direction_policy <- "projected to a simple undirected network"
  source_manifest$source_node_count <- parsed$node_count
  source_manifest$source_edge_count <- parsed$edge_count
  source_manifest$network_attributes <- parsed$network_attributes
  source_manifest$output_node_count <- if (igraph::is_igraph(network)) {
    igraph::vcount(network)
  } else if (inherits(network, "nearender_indexed_network")) {
    length(network$node_names)
  } else length(network$links)
  source_manifest$output_edge_count <- .network_edge_count(network)
  attr(network, "nearender_manifest") <- source_manifest
  network
}

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.