R/validation.R

Defines functions .select_sample_matrix .warn_investigation_normalization .prepare_investigation_network .validate_investigation_network .normalize_network .normalize_legacy_network .legacy_weight_edges .warn_legacy_node_collisions .normalize_gene_sets .assert_reversible_case_policy .already_normalized .assert_compatible_identifiers .copy_identifier_metadata .attach_identifier_metadata .identifier_metadata .mark_normalized normalization_info .normalization_metadata .canonical_ids .validate_renderer_args .assert_flag

Documented in normalization_info

.assert_flag <- function(x, name) {
  if (!is.logical(x) || length(x) != 1L || is.na(x)) {
    stop(name, " must be TRUE or FALSE.", call. = FALSE)
  }
  x
}

.validate_renderer_args <- function(renderer_args, renderer, method,
    managed = character(), managed_label = "dispatcher-managed arguments") {
  if (!is.list(renderer_args) ||
      (length(renderer_args) && is.null(names(renderer_args))) ||
      anyNA(names(renderer_args)) || any(!nzchar(names(renderer_args))) ||
      anyDuplicated(names(renderer_args))) {
    stop("renderer_args must be a named list with unique, non-empty names.",
      call. = FALSE)
  }
  protected <- intersect(names(renderer_args), managed)
  if (length(protected)) {
    stop("renderer_args must not override ", managed_label, ": ",
      paste(protected, collapse = ", "), ".", call. = FALSE)
  }
  renderer_formals <- names(formals(renderer))
  unknown <- if ("..." %in% renderer_formals) {
    character()
  } else {
    setdiff(names(renderer_args), renderer_formals)
  }
  if (length(unknown)) {
    stop("Unknown renderer_args for ", method, ": ",
      paste(unknown, collapse = ", "), ".", call. = FALSE)
  }
  invisible(renderer_args)
}

.canonical_ids <- function(ids, case_sensitive) {
  ids <- as.character(ids)
  if (case_sensitive) ids else tolower(ids)
}

.normalization_metadata <- function(x) {
  attr(x, "nearender_normalization", exact = TRUE)
}

#' Inspect identifier-normalization metadata
#'
#' Imported and prepared datasets record whether identifiers have already been
#' normalized, which case policy was used, and an `identifiers` sublist with
#' the declared species, submitted namespace, resulting namespace, and mapping
#' provenance when applicable. Legacy unmarked objects return `NULL`.
#'
#' @param x A gene-set collection or network.
#' @return A normalization metadata list, or `NULL`.
#' @examples
#' sets <- import_gene_sets(data.frame(gene = c("TP53", "MDM2")),
#'   layout = "single_set", species = "human")
#' normalization_info(sets)$identifiers
#' @export
normalization_info <- function(x) .normalization_metadata(x)

.mark_normalized <- function(x, case_sensitive) {
  previous <- .normalization_metadata(x)
  metadata <- list(
    normalized = TRUE,
    case_sensitive = case_sensitive,
    normalizer_version = 1L
  )
  if (is.list(previous) && !is.null(previous$identifiers)) {
    metadata$identifiers <- previous$identifiers
  }
  attr(x, "nearender_normalization") <- metadata
  x
}

.identifier_metadata <- function(x) {
  metadata <- .normalization_metadata(x)
  if (is.list(metadata)) metadata$identifiers else NULL
}

.attach_identifier_metadata <- function(x, identifiers) {
  metadata <- .normalization_metadata(x)
  if (!is.list(metadata)) metadata <- list()
  metadata$identifiers <- identifiers
  attr(x, "nearender_normalization") <- metadata
  x
}

.copy_identifier_metadata <- function(x, from) {
  identifiers <- .identifier_metadata(from)
  if (!is.null(identifiers)) x <- .attach_identifier_metadata(x, identifiers)
  database_manifest <- attr(from, "nearender_manifest", exact = TRUE)
  if (!is.null(database_manifest)) {
    attr(x, "nearender_manifest") <- database_manifest
  }
  x
}

.assert_compatible_identifiers <- function(...) {
  objects <- list(...)
  labels <- names(objects)
  if (is.null(labels)) labels <- rep("object", length(objects))
  metadata <- lapply(objects, .identifier_metadata)
  known <- !vapply(metadata, is.null, logical(1))
  if (sum(known) < 2L) return(invisible(NULL))
  species <- vapply(metadata[known], function(x) x$species_id,
    character(1))
  formats <- vapply(metadata[known], function(x) x$output_id_format,
    character(1))
  if (length(unique(species)) > 1L) {
    detail <- paste0(labels[known], "=", species, collapse = ", ")
    stop("Input species are incompatible: ", detail, ".", call. = FALSE)
  }
  if (length(unique(formats)) > 1L) {
    detail <- paste0(labels[known], "=", formats, collapse = ", ")
    stop("Input identifier formats are incompatible: ", detail, ".",
      " Convert them to the species master format reported by ",
      "master_id_format().",
      call. = FALSE)
  }
  invisible(NULL)
}

.already_normalized <- function(x, case_sensitive) {
  metadata <- .normalization_metadata(x)
  is.list(metadata) && identical(metadata$normalized, TRUE) &&
    identical(metadata$case_sensitive, case_sensitive) &&
    identical(metadata$normalizer_version, 1L)
}

.assert_reversible_case_policy <- function(x, case_sensitive, name) {
  metadata <- .normalization_metadata(x)
  if (isTRUE(case_sensitive) && is.list(metadata) &&
      identical(metadata$normalized, TRUE) &&
      identical(metadata$case_sensitive, FALSE)) {
    stop(name, " was normalized case-insensitively; original identifier case ",
      "cannot be restored.", call. = FALSE)
  }
}

.normalize_gene_sets <- function(gene_sets, name, case_sensitive) {
  if (!is.list(gene_sets) || is.null(names(gene_sets))) {
    stop(name, " must be a named list of gene identifiers.", call. = FALSE)
  }
  if (anyNA(names(gene_sets)) || any(names(gene_sets) == "") ||
      anyDuplicated(names(gene_sets))) {
    stop(name, " must have unique, non-empty set names.", call. = FALSE)
  }
  if (.already_normalized(gene_sets, case_sensitive)) return(gene_sets)
  .assert_reversible_case_policy(gene_sets, case_sensitive, name)

  normalized <- lapply(gene_sets, function(genes) {
    genes <- .canonical_ids(genes, case_sensitive)
    unique(genes[!is.na(genes) & nzchar(genes)])
  })
  names(normalized) <- names(gene_sets)
  normalized <- .mark_normalized(normalized, case_sensitive)
  .copy_identifier_metadata(normalized, gene_sets)
}

.warn_legacy_node_collisions <- function(raw_names, case_sensitive) {
  canonical <- .canonical_ids(raw_names, case_sensitive)
  valid <- !is.na(canonical) & nzchar(canonical)
  groups <- split(seq_along(canonical)[valid], canonical[valid])
  groups <- groups[lengths(groups) > 1L]
  if (!length(groups)) return(invisible(NULL))
  examples <- vapply(utils::head(groups, 5L), function(group) {
    paste0(paste(unique(raw_names[group]), collapse = "/"), " -> ",
      canonical[group[[1L]]])
  }, character(1))
  warning("Collapsed ", sum(lengths(groups) - 1L),
    " legacy network nodes whose names collide under the identifier case ",
    "policy; examples: ", paste(examples, collapse = ", "),
    call. = FALSE)
  invisible(NULL)
}

.legacy_weight_edges <- function(net, topology, case_sensitive) {
  weights <- net$weights
  zero_scores <- function(problem) {
    warning(problem, " Assigned edge score 0 to all ", nrow(topology),
      " normalized edges.", call. = FALSE)
    result <- topology
    result$score <- 0
    result
  }
  if (!is.list(weights) || is.null(names(weights))) {
    return(zero_scores(
      "Legacy weights must be a named list of numeric vectors."))
  }

  raw_link_names <- names(net$links)
  link_names <- .canonical_ids(raw_link_names, case_sensitive)
  raw_weight_names <- names(weights)
  weight_names <- .canonical_ids(raw_weight_names, case_sensitive)
  invalid_weight_nodes <- is.na(weight_names) | !nzchar(weight_names)
  if (any(invalid_weight_nodes)) {
    warning("Ignored ", sum(invalid_weight_nodes),
      " legacy weight entries with missing or empty node names: ",
      paste(utils::head(.network_value_labels(
        raw_weight_names[invalid_weight_nodes]), 5L), collapse = ", "),
      call. = FALSE)
  }
  unknown_weight_nodes <- !invalid_weight_nodes &
    !weight_names %in% unique(link_names)
  if (any(unknown_weight_nodes)) {
    warning("Ignored ", sum(unknown_weight_nodes),
      " legacy weight nodes absent from links; examples: ",
      paste(utils::head(unique(raw_weight_names[unknown_weight_nodes]), 5L),
        collapse = ", "), call. = FALSE)
  }

  candidates <- vector("list", length(weights))
  positional_nodes <- character()
  unaligned_nodes <- character()
  for (i in seq_along(weights)) {
    if (invalid_weight_nodes[[i]] || unknown_weight_nodes[[i]]) next
    values <- weights[[i]]
    if (!is.atomic(values)) {
      unaligned_nodes <- c(unaligned_nodes, raw_weight_names[[i]])
      next
    }
    neighbors <- names(values)
    if (is.null(neighbors)) {
      link_entry <- which(link_names == weight_names[[i]])
      if (length(link_entry) == 1L &&
          length(values) == length(net$links[[link_entry]])) {
        neighbors <- net$links[[link_entry]]
        positional_nodes <- c(positional_nodes, raw_weight_names[[i]])
      } else {
        unaligned_nodes <- c(unaligned_nodes, raw_weight_names[[i]])
        next
      }
    }
    candidates[[i]] <- data.frame(
      from = rep(raw_weight_names[[i]], length(values)),
      to = neighbors,
      score = values,
      stringsAsFactors = FALSE)
  }
  if (length(positional_nodes)) {
    warning("Aligned unnamed legacy weight vectors by link order for nodes: ",
      paste(utils::head(unique(positional_nodes), 5L), collapse = ", "),
      call. = FALSE)
  }
  if (length(unaligned_nodes)) {
    warning("Could not align legacy weights for nodes: ",
      paste(utils::head(unique(unaligned_nodes), 5L), collapse = ", "),
      "; their missing edge scores on the normalized network were set to 0.",
      call. = FALSE)
  }
  candidates <- candidates[lengths(candidates) > 0L]
  weighted <- NULL
  if (length(candidates)) {
    candidates <- do.call(rbind, candidates)
    candidate_from <- .canonical_ids(candidates$from, case_sensitive)
    candidate_to <- .canonical_ids(candidates$to, case_sensitive)
    candidate_score <- suppressWarnings(as.numeric(candidates$score))
    usable <- !is.na(candidate_from) & nzchar(candidate_from) &
      !is.na(candidate_to) & nzchar(candidate_to) &
      candidate_from != candidate_to & !is.na(candidate_score) &
      is.finite(candidate_score)
    if (any(usable)) {
      weighted <- .canonical_network_edges(candidates, "from", "to", "score",
        case_sensitive = case_sensitive, zero_score_is_edge = TRUE)
    } else {
      .warn_network_repair(!is.na(candidate_from) & nzchar(candidate_from) &
        !is.na(candidate_to) & nzchar(candidate_to) &
        candidate_from != candidate_to,
        "Ignored legacy edges with non-finite or nonnumeric edge weights",
        candidates$from, candidates$to, candidates$score)
    }
  }

  result <- topology
  result$score <- 0
  if (!is.null(weighted)) {
    topology_key <- paste(topology$from, topology$to, sep = "\r")
    weighted_key <- paste(weighted$from, weighted$to, sep = "\r")
    matched <- match(topology_key, weighted_key)
    available <- !is.na(matched)
    result$score[available] <- weighted$score[matched[available]]
  } else {
    available <- rep(FALSE, nrow(topology))
  }
  if (any(!available)) {
    warning("Assigned edge score 0 to ", sum(!available),
      " normalized legacy edges without a usable weight; examples: ",
      .network_edge_examples(topology$from, topology$to, !available),
      call. = FALSE)
  }
  result
}

.normalize_legacy_network <- function(net, case_sensitive) {
  if (is.null(net$links) || !is.list(net$links) || is.null(names(net$links))) {
    stop("net$links must be a named adjacency list.", call. = FALSE)
  }
  .warn_legacy_node_collisions(names(net$links), case_sensitive)
  link_counts <- lengths(net$links)
  raw_edges <- data.frame(
    from = rep(names(net$links), link_counts),
    to = unlist(net$links, use.names = FALSE),
    stringsAsFactors = FALSE)
  topology <- .canonical_network_edges(raw_edges, "from", "to",
    case_sensitive = case_sensitive)
  actual_edges <- nrow(topology)
  stored_edges <- net$Ntotal
  valid_stored <- is.numeric(stored_edges) && length(stored_edges) == 1L &&
    !is.na(stored_edges) && is.finite(stored_edges) && stored_edges > 0
  if (!valid_stored) {
    warning("Legacy Ntotal is missing or invalid (",
      paste(.network_value_labels(stored_edges), collapse = ", "),
      "); using normalized topology count ", actual_edges, ".", call. = FALSE)
  } else if (!isTRUE(all.equal(as.numeric(stored_edges),
      as.numeric(actual_edges)))) {
    warning("Legacy Ntotal (", stored_edges,
      ") differs from the normalized unique undirected topology (",
      actual_edges, "); using ", actual_edges, ".", call. = FALSE)
  }

  if (!is.null(net$weights)) {
    topology <- .legacy_weight_edges(net, topology, case_sensitive)
  }
  result <- .legacy_network_from_edges(topology, case_sensitive)
  if (valid_stored && isTRUE(all.equal(as.numeric(stored_edges),
      as.numeric(actual_edges)))) {
    result$Ntotal <- stored_edges
  }
  if (!is.null(net$name)) result$name <- net$name
  .copy_identifier_metadata(result, net)
}

.normalize_network <- function(net, case_sensitive) {
  if (igraph::is_igraph(net)) {
    return(as_igraph_network(net, case_sensitive))
  }
  if (inherits(net, "nearender_indexed_network")) {
    if (.already_normalized(net, case_sensitive)) return(net)
    .assert_reversible_case_policy(net, case_sensitive, "net")
    node_names <- .canonical_ids(net$node_names, case_sensitive)
    if (anyDuplicated(node_names)) {
      stop("Indexed network node names collide under the identifier case policy.",
           call. = FALSE)
    }
    net$node_names <- node_names
    names(net$node_id) <- node_names
    dimnames(net$adjacency) <- list(node_names, node_names)
    if (!is.null(net$weights)) {
      dimnames(net$weights) <- list(node_names, node_names)
    }
    return(.mark_normalized(net, case_sensitive))
  }
  if (.already_normalized(net, case_sensitive)) return(net)
  .assert_reversible_case_policy(net, case_sensitive, "net")
  .normalize_legacy_network(net, case_sensitive)
}

.validate_investigation_network <- function(net) {
  if (igraph::is_igraph(net)) {
    if (igraph::is_directed(net)) {
      stop("Investigation networks must be undirected.", call. = FALSE)
    }
    node_names <- igraph::vertex_attr(net, "name")
    if (is.null(node_names) || anyNA(node_names) || any(!nzchar(node_names)) ||
        anyDuplicated(node_names)) {
      stop("igraph vertices must have unique, non-empty name attributes.",
        call. = FALSE)
    }
    if (!igraph::is_simple(net)) {
      stop("Investigation networks must not contain loops or parallel edges; ",
        "use normalize = TRUE.", call. = FALSE)
    }
    return(net)
  }
  if (inherits(net, "nearender_indexed_network")) {
    if (is.null(net$adjacency) || is.null(net$node_names) ||
        length(net$node_names) != nrow(net$adjacency) ||
        length(net$node_names) != ncol(net$adjacency) ||
        anyNA(net$node_names) || any(!nzchar(net$node_names)) ||
        anyDuplicated(net$node_names)) {
      stop("Indexed network must have an adjacency matrix and unique, non-empty node names.",
        call. = FALSE)
    }
    return(net)
  }
  if (is.null(net$links) || !is.list(net$links) || is.null(names(net$links))) {
    stop("net$links must be a named adjacency list.", call. = FALSE)
  }
  if (anyNA(names(net$links)) || any(!nzchar(names(net$links))) ||
      anyDuplicated(names(net$links))) {
    stop("Network node names must be unique and non-empty.", call. = FALSE)
  }
  if (is.null(net$Ntotal) || length(net$Ntotal) != 1L ||
      !is.finite(net$Ntotal) || net$Ntotal <= 0) {
    stop("net$Ntotal must be one positive finite edge count.", call. = FALSE)
  }
  net
}

.prepare_investigation_network <- function(net, normalize, case_sensitive) {
  if (normalize) {
    .normalize_network(net, case_sensitive)
  } else {
    .validate_investigation_network(net)
  }
}

.warn_investigation_normalization <- function(function_name) {
  warning(function_name,
    "(normalize = TRUE) copies and normalizes all network identifiers; ",
    "this may be slow for large networks.",
    call. = FALSE)
}

.select_sample_matrix <- function(x, sample_columns, column_pattern) {
  if (!is.matrix(x) && !is.data.frame(x)) {
    stop("x must be a matrix or data frame.", call. = FALSE)
  }
  if (is.null(rownames(x)) || anyNA(rownames(x)) ||
      any(rownames(x) == "")) {
    stop("x must have non-empty gene identifiers as row names.",
         call. = FALSE)
  }
  if (!is.null(sample_columns)) x <- x[, sample_columns, drop = FALSE]
  if (!is.null(column_pattern)) {
    if (!is.character(column_pattern) || length(column_pattern) != 1L) {
      stop("column_pattern must be NULL or one regular expression.",
           call. = FALSE)
    }
    x <- x[, grepl(column_pattern, colnames(x)), drop = FALSE]
  }
  if (ncol(x) == 0L) stop("No sample columns remain.", call. = FALSE)

  x <- as.matrix(x)
  storage.mode(x) <- "double"
  x
}

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.