# INDRA queries that read INDRA Statement JSON rather than the Relation # records of indra_subnetwork_relations: neighborhood_query() and # literature_expanded_subnetwork_query(). Statements are turned into # Relation-like records (.statements_to_relations()), so the subnetwork # filters, edge builder, and node builder are shared. #' "No limit" for CoGEx get_statements #' #' Leaving \code{limit} out gives the server default of 10, and #' \code{"limit": null} gives HTTP 500, so the largest 32-bit integer is #' sent. #' @keywords internal #' @noRd INDRA_NO_LIMIT <- .Machine$integer.max #' Seconds to wait between consecutive INDRA requests of one query #' @keywords internal #' @noRd INDRA_REQUEST_PAUSE <- 0.1 #' Statement hashes per request to the CoGEx hash endpoints #' @keywords internal #' @noRd INDRA_HASHES_PER_REQUEST <- 100L #' Statement roles that hold one agent, by statement type family #' @keywords internal #' @noRd INDRA_AGENT_PAIR_ROLES <- list(c("subj", "obj"), c("enz", "sub"), c("gef", "ras"), c("gap", "ras")) #' Statement roles that hold agents, for the measured_only check #' @keywords internal #' @noRd INDRA_AGENT_ROLES <- c("subj", "obj", "enz", "sub", "gef", "gap", "ras", "agent") #' db_refs entries that are not groundings #' @keywords internal #' @noRd INDRA_NON_GROUNDING_REFS <- c("TEXT", "TEXT_NORM") #' Namespace order for naming an agent that matches no entity row #' @keywords internal #' @noRd INDRA_GROUNDING_PRIORITY <- c("HGNC", "UP", "UPPRO", "FPLX", "CHEBI", "HMDB", "PUBCHEM", "LIPIDMAPS", "CHEMBL", "DRUGBANK", "MESH", "GO", "EGID") # INDRA neighborhood query. One CoGEx get_statements request per selected # grounding, sent by name with no limit. Statements are kept when an agent # carries the selected grounding, deduplicated on matches_hash, filtered to # the entity table (measured_only), and built into a network whose # unselected rows are "neighbor" nodes. include_entities are queried too: # those that are rows of the entity table are selected (as with # select_entities(force_include = )), and the others are latent # "user_added" nodes, named through CoGEx, that measured_only lets through. #' @rdname get_network #' @export setMethod("get_network", signature("IndraBackend", "NeighborhoodQuery"), function(backend, entities, query, interaction_types = NULL, min_evidence = 1, min_confidence = NULL, evidence_sources = NULL, include_entities = NULL, ...) { .validate_entities(entities) added <- .parse_neighborhood_include_entities(include_entities) entities <- .select_included_entity_rows(entities, added) outside <- added[!added$id %in% .entity_grounding_keys(entities), , drop = FALSE] groundings <- .get_groundings_to_query(entities) .validateIndraSubnetworkInput( .combine_query_groundings(groundings, outside), evidence_sources, NULL, max_nodes = INDRA_MAX_NODES[["neighborhood"]]) .check_min_confidence(min_confidence) outside <- .name_outside_entities(outside, backend@cogex_url) agents <- .get_query_agents( .combine_query_groundings(groundings, outside), "neighborhood_query()") message(.describe_neighborhood_question(entities, groundings, outside$id, query@measured_only)) grounding_lookup <- .allow_outside_groundings( .build_grounding_lookup(entities), outside$id) response <- .fetch_neighborhood_statements(agents, backend@cogex_url) retrieved_at <- .get_current_time() statements <- .filter_statements_to_entities( response$statements, grounding_lookup, query@measured_only) relations <- .statements_to_relations( statements, grounding_lookup, .metadata_from_source_counts(response$source_counts[intersect( .statement_hashes(statements), names(response$source_counts))])) network <- .build_statement_network( relations, grounding_lookup, "neighborhood", "neighbor", interaction_types, min_evidence, min_confidence, evidence_sources, include_entities = outside$id) network$provenance <- .build_provenance( backend_database = "INDRA", query_type = "neighborhood", backend_url = backend@cogex_url, organism = .get_column_or_default( entities, "organism", NA_character_)[entities$included_in_query], parameters = list( interaction_types = interaction_types, min_evidence = min_evidence, min_confidence = min_confidence, evidence_sources = evidence_sources, include_entities = include_entities, measured_only = query@measured_only), retrieved_at = retrieved_at) validate_network(network) network }) # INDRA literature-expanded subnetwork query. The subnetwork of the # selected groundings, as for SubnetworkQuery; the PubMed IDs of its edges; # the statements of those papers, filtered to the entity table # (measured_only); and the union, with unselected rows as # "literature_neighbor" nodes. One round: the added edges' papers are not # fetched. #' @rdname get_network #' @export setMethod("get_network", signature("IndraBackend", "LiteratureExpandedSubnetworkQuery"), function(backend, entities, query, interaction_types = NULL, min_evidence = 1, min_confidence = NULL, evidence_sources = NULL, include_entities = NULL, ...) { query_type <- "literature_expanded_subnetwork" .check_small_query_size(entities, "literature_expanded_subnetwork_query()") groundings <- .get_groundings_to_query(entities) .validateIndraSubnetworkInput(groundings, evidence_sources, include_entities) .check_min_confidence(min_confidence) message(.describe_literature_question(entities, groundings, include_entities, query@measured_only)) grounding_lookup <- .build_grounding_lookup(entities) base_relations <- .filterIndraResponse( .callIndraCogexApi(groundings$namespace, groundings$entity_id, include_entities, backend@cogex_url), interaction_types, min_evidence, evidence_sources) base_edges <- .constructEdgesDataFrame(base_relations, grounding_lookup, query_type) base_edges <- .filterEdgesDataFrame( .filter_by_min_confidence(base_edges, min_confidence)) base_hashes <- unique(base_edges$statement_id) pmids <- .fetch_pmids_for_statements(base_hashes, backend@cogex_url) fetched <- .fetch_statements_for_pmids( pmids, backend@cogex_url, grounding_lookup, query@measured_only, query@max_statements_per_pmid) statements <- fetched$statements statements <- statements[!.statement_hashes(statements) %in% base_hashes] metadata <- .fetch_statement_metadata(.statement_hashes(statements), backend@cogex_url) retrieved_at <- .get_current_time() added_relations <- .filterIndraResponse( .statements_to_relations(statements, grounding_lookup, metadata), interaction_types, min_evidence, evidence_sources) added_edges <- .filter_by_min_confidence( .constructEdgesDataFrame(added_relations, grounding_lookup, query_type), min_confidence) base_edges$literature_expansion <- rep(FALSE, nrow(base_edges)) added_edges$literature_expansion <- rep(TRUE, nrow(added_edges)) message("Literature expansion: ", length(pmids), " PubMed ID(s) ", "behind ", length(base_hashes), " subnetwork statement(s) ", "added ", nrow(added_edges), " edge(s).") edges <- rbind(base_edges, added_edges) rownames(edges) <- NULL nodes <- .build_network_nodes( grounding_lookup, edges, .list_latent_backend_nodes(c(base_relations, added_relations), grounding_lookup), neighbor_role = "literature_neighbor", include_entities = include_entities) provenance <- .build_provenance( backend_database = "INDRA", query_type = query_type, backend_url = backend@cogex_url, organism = .get_column_or_default( entities, "organism", NA_character_)[entities$included_in_query], parameters = list( interaction_types = interaction_types, min_evidence = min_evidence, min_confidence = min_confidence, evidence_sources = evidence_sources, include_entities = include_entities, measured_only = query@measured_only, max_statements_per_pmid = if (is.finite( query@max_statements_per_pmid)) query@max_statements_per_pmid else NULL, pmid_count = length(pmids), skipped_pmid_count = length(fetched$too_large)), retrieved_at = retrieved_at) network <- list(nodes = nodes, edges = edges, provenance = provenance) validate_network(network) network }) #' Stop when a small-list query has too many selected rows #' #' Used by the literature-expanded subnetwork query, whose requests grow #' with the papers behind the selection. Runs before any request is sent. #' @param entities entity table #' @param query_name the constructor, for the message #' @return \code{NULL}, invisibly; errors otherwise #' @keywords internal #' @noRd .check_small_query_size <- function(entities, query_name) { .validate_entities(entities) n_selected <- sum(entities$included_in_query %in% TRUE) if (n_selected > SMALL_QUERY_MAX_SELECTED) { stop(query_name, " is meant for small lists for now: it takes at ", "most ", SMALL_QUERY_MAX_SELECTED, " selected entities, and ", n_selected, " rows of entities have included_in_query = TRUE ", "(rows that passed the cutoffs and user_added rows). Tighten ", "the cutoffs of select_entities() to select fewer.", call. = FALSE) } invisible(NULL) } #' The INDRA names to send for the selected groundings #' #' CoGEx get_statements matches a JSON \code{agent} by name only (a #' (namespace, ID) tuple is only reachable from the Python client), so each #' grounding is sent by its INDRA name and checked by ID in the response. #' @param groundings from \code{.get_groundings_to_query()} #' @param query_name the constructor, for the message #' @return data.frame of the unique \code{namespace}, \code{entity_id}, and #' \code{entity_name}; errors when a grounding has no name #' @keywords internal #' @noRd .get_query_agents <- function(groundings, query_name) { no_name <- is.na(groundings$entity_name) | !nzchar(groundings$entity_name) if (any(no_name)) { stop(query_name, " sends each selected entity to INDRA by its name ", "(entity_name), and these rows have none: ", .list_values_for_message(unique(groundings$id[no_name])), ". Ground them with convert_ids(), or deselect them.", call. = FALSE) } agents <- groundings[, c("namespace", "entity_id", "entity_name")] agents <- agents[!duplicated(paste(agents$namespace, agents$entity_id, sep = ":")), , drop = FALSE] rownames(agents) <- NULL agents } #' The question a neighborhood query asks, with the entity counts #' @param entities entity table #' @param groundings groundings of the rows to query #' @param include_entities groundings added to the query from outside the #' input #' @param measured_only the query's setting #' @return a single string #' @keywords internal #' @noRd .describe_neighborhood_question <- function(entities, groundings, include_entities, measured_only) { paste0("INDRA neighborhood: which entities ", if (measured_only) "in the input " else "", "are directly linked to each of ", .describe_query_selection(entities, groundings, include_entities), "?") } #' Namespaces neighborhood_query() takes in include_entities #' #' CoGEx get_statements matches agents by name, and CoGEx names HGNC IDs #' (get_hgnc_names_from_hgnc_ids). Other namespaces need a name lookup. #' @keywords internal #' @noRd NEIGHBORHOOD_INCLUDE_NAMESPACES <- "HGNC" #' Parse the include_entities of a neighborhood query #' @param include_entities \code{"namespace:identifier"} strings, or #' \code{NULL} #' @return data.frame of \code{id} (the string), \code{namespace}, and #' \code{entity_id}, one row per unique grounding; errors on a malformed #' string or a namespace outside \code{NEIGHBORHOOD_INCLUDE_NAMESPACES} #' @keywords internal #' @noRd .parse_neighborhood_include_entities <- function(include_entities) { include_entities <- unique(include_entities) if (length(include_entities) > 0 && !is.character(include_entities)) { stop("include_entities must be a character vector of ", "\"namespace:identifier\" groundings, e.g. \"HGNC:1925\".", call. = FALSE) } parts <- strsplit(as.character(include_entities), ":", fixed = TRUE) malformed <- lengths(parts) != 2 | !vapply(parts, function(p) all(nzchar(p)), logical(1)) if (any(malformed)) { stop("Invalid identifier format: ", .list_values_for_message(include_entities[malformed]), ". Expected format is 'namespace:identifier', e.g. ", "'HGNC:1925'.", call. = FALSE) } added <- data.frame( id = as.character(include_entities), namespace = vapply(parts, `[`, "", 1), entity_id = vapply(parts, `[`, "", 2), stringsAsFactors = FALSE) unsupported <- !added$namespace %in% NEIGHBORHOOD_INCLUDE_NAMESPACES if (any(unsupported)) { stop("neighborhood_query() takes include_entities in the namespace ", paste(NEIGHBORHOOD_INCLUDE_NAMESPACES, collapse = ", "), " for now, since INDRA is queried by name. Got: ", .list_values_for_message(added$id[unsupported]), ".", call. = FALSE) } added } #' Select the entity rows named by include_entities #' #' An added grounding that a row of the entity table has is in the input: #' the row is selected and \code{user_added}, as with #' \code{select_entities(force_include = )}, so that it gets its #' statistics. #' @param entities entity table #' @param added from \code{.parse_neighborhood_include_entities()} #' @return \code{entities}, with those rows selected #' @keywords internal #' @noRd .select_included_entity_rows <- function(entities, added) { if (nrow(added) == 0) { return(entities) } long <- build_grounding_table(entities) rows <- entities$id %in% long$id[paste(long$namespace, long$entity_id, sep = ":") %in% added$id] newly_selected <- rows & !entities$included_in_query entities$included_in_query[rows] <- TRUE user_added <- .get_column_or_default(entities, "user_added", FALSE) user_added[newly_selected] <- TRUE entities$user_added <- user_added %in% TRUE entities } #' Combine the groundings of the selected rows and the added entities #' #' Either table may have no rows (\code{build_grounding_table()} of no rows #' has no columns), and the added entities have no \code{entity_name} #' until \code{.name_outside_entities()}. #' @param groundings from \code{.get_groundings_to_query()} #' @param outside added groundings that are not in the input #' @return data.frame of \code{id}, \code{namespace}, \code{entity_id}, #' and \code{entity_name} #' @keywords internal #' @noRd .combine_query_groundings <- function(groundings, outside) { columns <- c("id", "namespace", "entity_id", "entity_name") tables <- lapply(list(groundings, outside), function(table) { table <- as.data.frame(table, stringsAsFactors = FALSE) for (column in setdiff(columns, colnames(table))) { table[[column]] <- rep(NA_character_, nrow(table)) } table[, columns, drop = FALSE] }) do.call(rbind, tables) } #' The "namespace:identifier" groundings of an entity table #' @param entities entity table #' @return character vector #' @keywords internal #' @noRd .entity_grounding_keys <- function(entities) { long <- build_grounding_table(entities) unique(paste(long$namespace, long$entity_id, sep = ":")) } #' Name the added groundings that are not in the input, through CoGEx #' @param outside rows of \code{.parse_neighborhood_include_entities()} #' that no entity row has #' @param cogex_url base URL of INDRA CoGEx #' @return \code{outside} with \code{entity_name}; errors naming the #' groundings CoGEx has no name for #' @keywords internal #' @noRd .name_outside_entities <- function(outside, cogex_url) { outside$entity_name <- rep(NA_character_, nrow(outside)) if (nrow(outside) == 0) { return(outside) } names_by_id <- .callGetHgncNamesFromHgncIdsApi(as.list(outside$entity_id), cogex_url) outside$entity_name <- vapply(outside$entity_id, function(entity_id) { name <- names_by_id[[entity_id]] if (is.null(name) || !nzchar(name[[1]])) NA_character_ else as.character(name[[1]]) }, character(1), USE.NAMES = FALSE) unnamed <- is.na(outside$entity_name) if (any(unnamed)) { stop("INDRA has no name for these include_entities, so ", "neighborhood_query() can't query them: ", .list_values_for_message(outside$id[unnamed]), ".", call. = FALSE) } outside } #' Let the added groundings through measured_only #' #' Adds them to the lookup with no entity rows, so that an agent carrying #' one counts as allowed and gets that grounding, but maps to a latent node. #' @param grounding_lookup from \code{.build_grounding_lookup()} #' @param outside_keys \code{"namespace:identifier"} of the added groundings #' that no entity row has #' @return \code{grounding_lookup} #' @keywords internal #' @noRd .allow_outside_groundings <- function(grounding_lookup, outside_keys) { new_keys <- setdiff(outside_keys, names(grounding_lookup$rows_by_grounding)) grounding_lookup$rows_by_grounding[new_keys] <- rep(list(integer(0)), length(new_keys)) grounding_lookup } #' The question a literature-expanded subnetwork query asks #' @param entities entity table #' @param groundings groundings of the rows to query #' @param include_entities groundings added to the query #' @param measured_only the query's setting #' @return a single string #' @keywords internal #' @noRd .describe_literature_question <- function(entities, groundings, include_entities, measured_only) { paste0("INDRA literature-expanded subnetwork: how are ", .describe_query_selection(entities, groundings, include_entities), " connected to each other, and what else ", if (measured_only) "in the input " else "", "do the papers behind those connections link?") } #' Get the statements of each selected grounding from CoGEx #' #' One get_statements request per grounding, with a pause between them. #' Statements in which no agent carries the grounding (another entity with #' the same name, or an agent with no ID) are dropped, with a message. #' @param agents from \code{.get_query_agents()} #' @param cogex_url base URL of INDRA CoGEx #' @return list with \code{statements} (unique by \code{matches_hash}) and #' \code{source_counts} (hash -> source -> count) #' @keywords internal #' @noRd .fetch_neighborhood_statements <- function(agents, cogex_url) { statements <- list() source_counts <- list() n_name_only <- 0L for (i in seq_len(nrow(agents))) { if (i > 1) { .pause_between_requests() } response <- .call_indra_get_statements(agents$entity_name[i], cogex_url) has_grounding <- vapply(response$statements, .statement_has_grounding, logical(1), namespace = agents$namespace[i], entity_id = agents$entity_id[i]) n_name_only <- n_name_only + sum(!has_grounding) statements <- c(statements, response$statements[has_grounding]) source_counts[names(response$source_counts)] <- response$source_counts } if (n_name_only > 0) { message("Dropped ", n_name_only, " statement(s) that match a ", "selected entity by name only, without its namespace and ", "identifier.") } statements <- statements[!duplicated(.statement_hashes(statements))] list(statements = statements, source_counts = source_counts) } #' Get the PubMed IDs behind statements from CoGEx #' @param statement_ids statement hashes #' @param cogex_url base URL of INDRA CoGEx #' @return character vector of unique PubMed IDs #' @keywords internal #' @noRd .fetch_pmids_for_statements <- function(statement_ids, cogex_url) { batches <- .split_into_batches(unique(statement_ids), INDRA_HASHES_PER_REQUEST) pmids <- character(0) for (i in seq_along(batches)) { if (i > 1) { .pause_between_requests() } response <- .call_indra_pmids_for_stmt_hashes(batches[[i]], cogex_url) pmids <- c(pmids, as.character(unlist(response, use.names = FALSE))) } unique(pmids[!is.na(pmids) & nzchar(pmids)]) } #' Get the statements of papers from CoGEx, one request per paper #' #' A high-throughput paper can hold tens of thousands of statements, so each #' paper's statements are filtered to the entity table as they arrive (with #' \code{measured_only}), and a paper whose request fails is skipped #' with a warning. A paper with more distinct statements than #' \code{max_statements_per_pmid} (counted before the entity filter) is #' left out, with a message. #' @param pmids PubMed IDs #' @param cogex_url base URL of INDRA CoGEx #' @param grounding_lookup from \code{.build_grounding_lookup()} #' @param measured_only the query's setting #' @param max_statements_per_pmid the query's setting, \code{Inf} for no #' limit #' @return list of \code{statements} (unique by \code{matches_hash}) and #' \code{too_large}, the PubMed IDs left out for their size #' @keywords internal #' @noRd .fetch_statements_for_pmids <- function(pmids, cogex_url, grounding_lookup, measured_only, max_statements_per_pmid = Inf) { statements <- list() dropped_hashes <- character(0) failed <- character(0) too_large <- character(0) if (length(pmids) > 0) { message("Fetching the statements of ", length(pmids), " PubMed ID(s), one request each.") } for (i in seq_along(pmids)) { if (i > 1) { .pause_between_requests() } paper_statements <- tryCatch( .call_indra_stmts_for_pmids(pmids[i], cogex_url), error = function(e) NULL) if (is.null(paper_statements)) { failed <- c(failed, pmids[i]) next } n_statements <- length(unique(.statement_hashes(paper_statements))) if (n_statements > max_statements_per_pmid) { too_large <- c(too_large, pmids[i]) next } keep <- .statements_in_entities(paper_statements, grounding_lookup, measured_only) dropped_hashes <- c(dropped_hashes, .statement_hashes(paper_statements[!keep])) statements <- c(statements, paper_statements[keep]) } if (length(failed) > 0) { warning("Skipped ", length(failed), " PubMed ID(s) whose INDRA ", "request failed: ", .list_values_for_message(failed), ".", call. = FALSE) } if (length(too_large) > 0) { message("Left out ", length(too_large), " PubMed ID(s) with more ", "than ", max_statements_per_pmid, " statements ", "(max_statements_per_pmid): ", .list_values_for_message(too_large), ".") } statements <- statements[!duplicated(.statement_hashes(statements))] .message_unmeasured_statements( length(unique(dropped_hashes)), length(unique(dropped_hashes)) + length(statements)) list(statements = statements, too_large = too_large) } #' Get the evidence counts and sources of statements from CoGEx #' #' get_stmts_for_pmids gives only the evidence from the papers asked for, #' so the totals come from get_stmts_meta_for_stmt_hashes. A failed request #' warns, and its statements fall back on their inline evidence. #' @param statement_ids statement hashes #' @param cogex_url base URL of INDRA CoGEx #' @return named list: hash -> list of \code{evidence_count}, #' \code{source_counts} (JSON string), and \code{belief} #' @keywords internal #' @noRd .fetch_statement_metadata <- function(statement_ids, cogex_url) { batches <- .split_into_batches(unique(statement_ids), INDRA_HASHES_PER_REQUEST) metadata <- list() for (i in seq_along(batches)) { if (i > 1) { .pause_between_requests() } response <- tryCatch( .call_indra_stmts_meta_for_stmt_hashes(batches[[i]], cogex_url), error = function(e) { warning("Could not get the evidence counts of ", length(batches[[i]]), " statement(s); counting their ", "evidence from the papers fetched: ", conditionMessage(e), call. = FALSE) list() }) for (record in response) { hash <- as.character(record$data$stmt_hash) if (length(hash) == 1) { metadata[[hash]] <- list( evidence_count = record$data$evidence_count, source_counts = record$data$source_counts, belief = record$data$belief) } } } metadata } #' Evidence metadata from a get_statements source count map #' @param source_counts named list: hash -> named list of source -> count #' @return named list like \code{.fetch_statement_metadata()}'s #' @keywords internal #' @noRd .metadata_from_source_counts <- function(source_counts) { lapply(source_counts, function(counts) { list(evidence_count = sum(as.numeric(unlist(counts))), source_counts = .source_counts_json(counts)) }) } #' A source count map as the JSON string edges$evidence_sources holds #' @param counts named list or vector of source -> count #' @return a single JSON string, \code{"{}"} when empty #' @keywords internal #' @noRd .source_counts_json <- function(counts) { if (length(counts) == 0) { return("{}") } as.character(jsonlite::toJSON(as.list(counts), auto_unbox = TRUE)) } #' Split a vector into batches of at most a given size #' @keywords internal #' @noRd .split_into_batches <- function(values, batch_size) { if (length(values) == 0) { return(list()) } unname(split(values, ceiling(seq_along(values) / batch_size))) } #' Wait between consecutive INDRA requests of one query #' #' A function, so that tests can mock it. #' @keywords internal #' @noRd .pause_between_requests <- function() { Sys.sleep(INDRA_REQUEST_PAUSE) } #' The matches_hash of each statement, as character #' @param statements list of INDRA statements #' @return character vector, one per statement #' @keywords internal #' @noRd .statement_hashes <- function(statements) { vapply(statements, function(statement) { as.character(statement$matches_hash) }, character(1)) } #' The agents of a statement #' #' \code{members} of a Complex, and the agent of each role in #' \code{INDRA_AGENT_ROLES}. An empty role (e.g. a modification with no #' enzyme) is left out. #' @param statement one INDRA statement #' @return list of agents, each a list with \code{name} and \code{db_refs} #' @keywords internal #' @noRd .statement_agents <- function(statement) { agents <- statement$members for (role in INDRA_AGENT_ROLES) { if (!is.null(statement[[role]])) { agents <- c(agents, list(statement[[role]])) } } Filter(Negate(is.null), agents) } #' The (source, target) agent pairs of a statement #' #' Every pair of members of a Complex, the two agents of a two-agent #' statement, and a self-pair for Autophosphorylation. One-agent statements #' (Translocation, ActiveForm) and statements with an empty role give no #' pairs. #' @param statement one INDRA statement #' @return list of \code{list(source = agent, target = agent)} #' @keywords internal #' @noRd .statement_agent_pairs <- function(statement) { members <- statement$members if (length(members) >= 2) { n_members <- length(members) first <- rep(seq_len(n_members), times = n_members) second <- rep(seq_len(n_members), each = n_members) is_pair <- first < second return(Map(function(i, j) { list(source = members[[i]], target = members[[j]]) }, first[is_pair], second[is_pair])) } for (roles in INDRA_AGENT_PAIR_ROLES) { source <- statement[[roles[1]]] target <- statement[[roles[2]]] if (!is.null(source) && !is.null(target)) { return(list(list(source = source, target = target))) } } if (identical(statement$type, "Autophosphorylation") && !is.null(statement$enz)) { return(list(list(source = statement$enz, target = statement$enz))) } list() } #' The groundings of an agent, from its db_refs #' @param agent an INDRA agent #' @return list of character vectors \code{namespace} and #' \code{entity_id}, without \code{TEXT} entries #' @keywords internal #' @noRd .agent_groundings <- function(agent) { refs <- agent$db_refs refs <- refs[!names(refs) %in% INDRA_NON_GROUNDING_REFS & lengths(refs) == 1] list(namespace = as.character(names(refs)), entity_id = as.character(unlist(refs, use.names = FALSE))) } #' Whether some agent of a statement carries a grounding #' @param statement one INDRA statement #' @param namespace,entity_id the grounding #' @return \code{TRUE} or \code{FALSE} #' @keywords internal #' @noRd .statement_has_grounding <- function(statement, namespace, entity_id) { any(vapply(.statement_agents(statement), function(agent) { identical(as.character(agent$db_refs[[namespace]]), as.character(entity_id)) }, logical(1))) } #' The grounding a statement agent gets in the network #' #' The first of its groundings that a row of the entity table has, so that #' it maps onto that row's node; otherwise its first grounding in #' \code{INDRA_GROUNDING_PRIORITY} order. #' @param agent an INDRA agent #' @param grounding_lookup from \code{.build_grounding_lookup()} #' @return list of \code{namespace}, \code{entity_id} (both \code{NA} for #' an agent with no grounding), \code{name}, and \code{in_input} #' @keywords internal #' @noRd .choose_agent_grounding <- function(agent, grounding_lookup) { groundings <- .agent_groundings(agent) keys <- paste(groundings$namespace, groundings$entity_id, sep = ":") in_input <- keys %in% names(grounding_lookup$rows_by_grounding) name <- if (is.null(agent$name)) NA_character_ else as.character(agent$name) if (any(in_input)) { chosen <- which(in_input)[1] } else if (length(groundings$namespace) > 0) { chosen <- order(match(groundings$namespace, INDRA_GROUNDING_PRIORITY, nomatch = length(INDRA_GROUNDING_PRIORITY) + 1))[1] } else { return(list(namespace = NA_character_, entity_id = NA_character_, name = name, in_input = FALSE)) } list(namespace = groundings$namespace[chosen], entity_id = groundings$entity_id[chosen], name = name, in_input = any(in_input)) } #' Whether every agent of each statement is a row of the entity table #' @param statements list of INDRA statements #' @param grounding_lookup from \code{.build_grounding_lookup()} #' @param measured_only \code{FALSE} keeps every statement #' @return logical vector, one per statement #' @keywords internal #' @noRd .statements_in_entities <- function(statements, grounding_lookup, measured_only) { if (!measured_only) { return(rep(TRUE, length(statements))) } vapply(statements, function(statement) { agents <- .statement_agents(statement) length(agents) > 0 && all(vapply(agents, function(agent) { .choose_agent_grounding(agent, grounding_lookup)$in_input }, logical(1))) }, logical(1)) } #' Keep the statements whose agents are all rows of the entity table #' #' Matching is by namespace and identifier, against every row of the #' entity table, not only the selected ones. #' @param statements list of INDRA statements #' @param grounding_lookup from \code{.build_grounding_lookup()} #' @param measured_only \code{FALSE} keeps every statement #' @return the kept statements; a message counts the dropped ones #' @keywords internal #' @noRd .filter_statements_to_entities <- function(statements, grounding_lookup, measured_only) { keep <- .statements_in_entities(statements, grounding_lookup, measured_only) .message_unmeasured_statements(sum(!keep), length(statements)) statements[keep] } #' Message the number of statements measured_only dropped #' @keywords internal #' @noRd .message_unmeasured_statements <- function(n_dropped, n_total) { if (n_dropped > 0) { message("Dropped ", n_dropped, " of ", n_total, " statement(s) ", "with an entity that is not in the input ", "(measured_only = TRUE).") } invisible(NULL) } #' Turn INDRA statements into Relation-like records #' #' One record per agent pair (\code{.statement_agent_pairs()}), in the form #' of the indra_subnetwork_relations response, so that #' \code{.filterIndraResponse()}, \code{.constructEdgesDataFrame()}, and #' \code{.list_latent_backend_nodes()} read them. Records carry #' \code{statement_id} (\code{matches_hash}) and \code{site} #' (\code{residue} + \code{position}) already. Statement types outside #' \code{INTERACTION_TYPES} and pairs with an unnamed agent are left out. #' @param statements list of INDRA statements #' @param grounding_lookup from \code{.build_grounding_lookup()} #' @param metadata named list: hash -> \code{evidence_count}, #' \code{source_counts}, and optionally \code{belief}. A statement without #' an entry counts its inline evidence. #' @return list of records #' @keywords internal #' @noRd .statements_to_relations <- function(statements, grounding_lookup, metadata) { relations <- lapply(statements, function(statement) { if (!.from_indra_type(statement$type) %in% INTERACTION_TYPES) { return(list()) } hash <- as.character(statement$matches_hash) data <- .statement_relation_data(statement, metadata[[hash]]) site <- .format_statement_site(statement$residue, statement$position) lapply(.statement_agent_pairs(statement), function(pair) { source <- .choose_agent_grounding(pair$source, grounding_lookup) target <- .choose_agent_grounding(pair$target, grounding_lookup) if (is.na(source$name) || is.na(target$name)) { return(NULL) } list(source_ns = source$namespace, source_id = source$entity_id, source_name = source$name, target_ns = target$namespace, target_id = target$entity_id, target_name = target$name, statement_id = hash, site = site, data = data) }) }) Filter(Negate(is.null), unlist(relations, recursive = FALSE)) } #' The data element of a Relation-like record #' @param statement one INDRA statement #' @param metadata the statement's metadata entry, or \code{NULL} #' @return list of \code{stmt_type}, \code{belief}, \code{evidence_count}, #' and \code{source_counts} #' @keywords internal #' @noRd .statement_relation_data <- function(statement, metadata) { if (is.null(metadata)) { evidence_sources <- vapply(statement$evidence, function(evidence) { if (is.null(evidence$source_api)) NA_character_ else as.character(evidence$source_api) }, character(1)) counts <- table(evidence_sources[!is.na(evidence_sources)]) metadata <- list( evidence_count = max(1L, length(statement$evidence)), source_counts = .source_counts_json( stats::setNames(as.list(as.integer(counts)), names(counts)))) } belief <- if (!is.null(metadata$belief)) metadata$belief else statement$belief list(stmt_type = statement$type, belief = if (is.null(belief)) NULL else as.numeric(belief), evidence_count = as.integer(metadata$evidence_count), source_counts = metadata$source_counts) } #' Build a network from Relation-like records #' #' The shared filters and builders of the subnetwork query: interaction #' types, evidence count, evidence sources, confidence, then edges and #' nodes. Stops when no edges remain. #' @param relations from \code{.statements_to_relations()} #' @param grounding_lookup from \code{.build_grounding_lookup()} #' @param query_type the edges' \code{query_type} #' @param neighbor_role the \code{node_role} of unselected rows #' @param interaction_types,min_evidence,min_confidence,evidence_sources the #' \code{get_network()} filters #' @param include_entities groundings added to the query, whose latent #' nodes are \code{"user_added"} rather than \code{neighbor_role} #' @return list of \code{nodes} and \code{edges} #' @keywords internal #' @noRd .build_statement_network <- function(relations, grounding_lookup, query_type, neighbor_role, interaction_types, min_evidence, min_confidence, evidence_sources, include_entities = NULL) { relations <- .filterIndraResponse(relations, interaction_types, min_evidence, evidence_sources) edges <- .constructEdgesDataFrame(relations, grounding_lookup, query_type) edges <- .filterEdgesDataFrame( .filter_by_min_confidence(edges, min_confidence)) nodes <- .build_network_nodes( grounding_lookup, edges, .list_latent_backend_nodes(relations, grounding_lookup), neighbor_role = neighbor_role, include_entities = include_entities) list(nodes = nodes, edges = edges) } # CoGEx calls of these queries. Each posts JSON and returns the parsed # response, with big integers (statement hashes) as character; a failed # request stops. #' POST a JSON body to CoGEx and parse the response #' @param url endpoint URL #' @param body list, sent with \code{auto_unbox = TRUE} (wrap arrays in #' \code{I()}) #' @return the parsed response #' @importFrom httr POST add_headers content status_code #' @keywords internal #' @noRd .post_indra_json <- function(url, body) { response <- POST( url, body = jsonlite::toJSON(body, auto_unbox = TRUE, digits = NA), add_headers("Content-Type" = "application/json"), encode = "raw" ) if (status_code(response) != 200) { stop("INDRA request to ", url, " failed with HTTP status ", status_code(response), ".", call. = FALSE) } jsonlite::parse_json(content(response, as = "text", encoding = "UTF-8"), bigint_as_char = TRUE) } #' Get every statement of an agent from CoGEx get_statements #' @param agent_name the agent's INDRA name, e.g. "CHEK1" #' @param cogex_url base URL of INDRA CoGEx #' @return list with \code{statements} and \code{source_counts} #' @keywords internal #' @noRd .call_indra_get_statements <- function(agent_name, cogex_url) { response <- .post_indra_json( file.path(cogex_url, "api/get_statements"), list(agent = agent_name, limit = INDRA_NO_LIMIT, evidence_limit = 1L, return_source_counts = TRUE)) # With return_source_counts, the response is [statements, counts] if (length(response) == 2 && is.null(names(response)) && !is.null(names(response[[2]])) && is.null(response[[2]]$type)) { return(list(statements = response[[1]], source_counts = response[[2]])) } list(statements = response, source_counts = list()) } #' Get the PubMed IDs of statements from CoGEx get_pmids_for_stmt_hashes #' @param statement_ids statement hashes #' @param cogex_url base URL of INDRA CoGEx #' @return named list: hash -> PubMed IDs #' @keywords internal #' @noRd .call_indra_pmids_for_stmt_hashes <- function(statement_ids, cogex_url) { .post_indra_json(file.path(cogex_url, "api/get_pmids_for_stmt_hashes"), list(stmt_hashes = I(as.character(statement_ids)))) } #' Get the statements of papers from CoGEx get_stmts_for_pmids #' @param pmids PubMed IDs #' @param cogex_url base URL of INDRA CoGEx #' @return list of INDRA statements #' @keywords internal #' @noRd .call_indra_stmts_for_pmids <- function(pmids, cogex_url) { .post_indra_json(file.path(cogex_url, "api/get_stmts_for_pmids"), list(pmids = I(as.character(pmids)))) } #' Get statement metadata from CoGEx get_stmts_meta_for_stmt_hashes #' @param statement_ids statement hashes #' @param cogex_url base URL of INDRA CoGEx #' @return list of records with \code{data$stmt_hash}, #' \code{data$evidence_count}, \code{data$source_counts}, and #' \code{data$belief} #' @keywords internal #' @noRd .call_indra_stmts_meta_for_stmt_hashes <- function(statement_ids, cogex_url) { .post_indra_json( file.path(cogex_url, "api/get_stmts_meta_for_stmt_hashes"), list(stmt_hashes = I(as.character(statement_ids)))) }