################################################## ## Project: COVID-19 Disease Map ## Script purpose: Convenience functions for accessing the MINERVA Platform ## Date: 24.12.2020 ## Author: Marek Ostaszewski ################################################## library(httr) library(jsonlite) ### A convenience function to handle API queries ask_GET <- function(fask_url, verbose = F, encoding = "UTF-8") { if(verbose) { message(URLencode(fask_url)) } resp <- httr::GET(url = URLencode(fask_url), httr::add_headers('Content-Type' = "application/x-www-form-urlencoded")) if(httr::status_code(resp) == 200) { ### when the content is sent as a zip file, it needs to be handled differently, ### i.e. saved to a tmp file and unzipped if(headers(resp)$`content-type` == "application/zip") { tmp <- tempfile() tmpc <- file(tmp, "wb") writeBin(httr::content(resp, as = "raw"), con = tmpc) close(tmpc) unzipped <- unzip(tmp) file.remove(tmp) return(unzipped) } else { return(httr::content(resp, as = "text", encoding = encoding)) } } return(NULL) } ### Get the id of the default project for this MINERVA instance get_default_project <- function(map_api) { cfg <- fromJSON(ask_GET(paste0(map_api, "configuration/"))) return(cfg$options[cfg$options$type == "DEFAULT_MAP","value"]) } ### Get the components of a given map/project on the MINERVA Platform get_map_components <- function(map_api, project_id = NULL, e_columns = "", r_columns = "") { if(is.null(project_id)) { ### If project id not given, get configuration of the map, to obtain the latest (default) version project_id <- get_default_project(map_api) } ### The address of the latest (default) build mnv_base <- paste0(map_api, "projects/",project_id,"/") message(paste0("Asking for diagrams in: ", mnv_base, "models/")) ### Get diagrams models <- fromJSON(ask_GET(paste0(mnv_base, "models/"))) if(e_columns != "") { e_columns <- paste0("?columns=", e_columns) } if(r_columns != "") { r_columns <- paste0("?columns=", r_columns) } ### Get elements of the chosen diagram model_elements <- lapply(models$idObject, function(x) fromJSON(ask_GET(paste0(mnv_base,"models/",x,"/","bioEntities/elements/",e_columns)), flatten = F)) ### Request for reactions that have at least one top 10 element as participant model_reactions <- lapply(models$idObject, function(x) fromJSON(ask_GET(paste0(mnv_base,"models/",x,"/","bioEntities/elements/",r_columns)), flatten = F)) ### Pack all into a list and return return(list(models = models, map_elements = model_elements, map_reactions = model_reactions)) } ### Get annotation of a given type, from element/reaction references get_annotation <- function(references, selected_type) { if(length(references) == 0) { return(NA) } with(data.frame(references), resource[type == selected_type]) }