Mercurial > repos > prog > lcmsmatching
view MsPeakForestDb.R @ 4:b34c14151f25 draft
planemo upload for repository https://github.com/workflow4metabolomics/lcmsmatching.git commit 494194bb501d1d7033613131865f7bd68976041c
author | prog |
---|---|
date | Tue, 14 Mar 2017 12:40:22 -0400 |
parents | f61ce21ed17c |
children | fb9c0409d85c |
line wrap: on
line source
if ( ! exists('MsPeakForestDb')) { # Do not load again if already loaded library(methods) source('MsDb.R') source(file.path('UrlRequestScheduler.R')) ##################### # CLASS DECLARATION # ##################### MsPeakForestDb <- setRefClass("MsPeakForestDb", contains = "MsDb", fields = list(.url = "character", .url.scheduler = "ANY", .token = "character")) ############### # CONSTRUCTOR # ############### MsPeakForestDb$methods( initialize = function(url = NA_character_, useragent = NA_character_, token = NA_character_, ...) { # Check URL if (is.null(url) || is.na(url)) stop("No URL defined for new MsPeakForestDb instance.") if (substring(url, nchar(url) - 1, 1) == '/') url <- substring(url, nchar(url) - 1) .url <<- url .url.scheduler <<- UrlRequestScheduler$new(n = 3, useragent = useragent) .self$.url.scheduler$setVerbose(1L) .token <<- token callSuper(...) }) ########### # GET URL # ########### MsPeakForestDb$methods( .get.url = function(url, params = NULL, ret.type = 'json') { res <- NULL # Add url prefix if (substring(url, 1, 1) == '/') url <- substring(url, 2) url <- paste(.self$.url, url, sep = '/') # Add token if ( ! is.na(.self$.token)) params <- c(params, token = .self$.token) param.str <- if (is.null(params)) '' else paste('?', vapply(names(params), function(p) paste(p, params[[p]], sep = '='), FUN.VALUE = ''), collapse = '&', sep = '') # Get URL content <- .self$.url.scheduler$getUrl(url = url, params = params) if (ret.type == 'json') { library(RJSONIO) res <- fromJSON(content, nullValue = NA) if (class(res) == 'list' && 'success' %in% names(res) && res$success == FALSE) { param.str <- if (is.null(params)) '' else paste('?', vapply(names(params), function(p) paste(p, params[[p]], sep = '='), FUN.VALUE = ''), collapse = '&', sep = '') stop(paste0("Failed to run web service. URL was \"", url, param.str, "\".")) } } else { if (ret.type == 'integer') { if (grepl('^[0-9]+$', content, perl = TRUE)) res <- as.integer(content) else { library(RJSONIO) res <- fromJSON(content, nullValue = NA) } } } return(res) }) #################### # GET MOLECULE IDS # #################### MsPeakForestDb$methods( getMoleculeIds = function() { ids <- as.character(.self$.get.url(url = 'compounds/all/ids')) return(ids) }) #################### # GET NB MOLECULES # #################### MsPeakForestDb$methods( getNbMolecules = function() { n <- .self$.get.url(url = 'compounds/all/count', ret.type = 'integer') return(n) }) ############################### # GET CHROMATOGRAPHIC COLUMNS # ############################### MsPeakForestDb$methods( getChromCol = function(molid = NULL) { # Set URL params <- NULL if ( ! is.null(molid)) params <- list(molids = paste(molid, collapse = ',')) # Call webservice wscols <- .self$.get.url(url = 'metadata/lc/list-code-columns', params = params) # Build data frame cols <- data.frame(id = character(), title = character()) for(id in names(wscols)) cols <- rbind(cols, data.frame(id = id, title = wscols[[id]]$name, stringsAsFactors = FALSE)) return(cols) }) ####################### # GET RETENTION TIMES # ####################### MsPeakForestDb$methods( getRetentionTimes = function(molid, col = NA_character_) { if (is.null(molid) || is.na(molid) || length(molid) != 1) stop("The parameter molid must consist only in a single value.") rt <- list() # Set URL params <- NULL if ( ! is.null(molid)) params <- list(molids = paste(molid, collapse = ',')) # Call webservice spectra <- .self$.get.url(url = 'spectra/lcms/search', params = params) if (class(spectra) == 'list' && length(spectra) > 0) { for (s in spectra) if (is.na(col) || s$liquidChromatography$columnCode %in% col) { ret.time <- (s$RTmin + s$RTmax) / 2 c <- s$liquidChromatography$columnCode if (c %in% names(rt)) { if ( ! ret.time %in% rt[[c]]) rt[[c]] <- c(rt[[c]], ret.time) } else rt[[c]] <- ret.time } } return(rt) }) ##################### # GET MOLECULE NAME # ##################### MsPeakForestDb$methods( getMoleculeName = function(molid) { library(RJSONIO) if (is.null(molid)) return(NA_character_) # Initialize names names <- as.character(molid) # Get non NA values non.na.molid <- molid[ ! is.na(molid)] if (length(non.na.molid) > 0) { # Set URL params <- c(molids = paste(non.na.molid, collapse = ',')) # Call webservice names[ ! is.na(molid)] <- .self$.get.url(url = 'compounds/all/names', params = params) } return(names) }) ################ # FIND BY NAME # ################ MsPeakForestDb$methods( findByName = function(name) { if (is.null(name)) return(NA_character_) ids <- list() for (n in name) { if (is.na(n)) ids <- c(ids, NA_character_) else { compounds <- .self$.get.url(url = paste0('search/compounds/name/', curlEscape(n)))$compoundNames ids <- c(ids, list(vapply(compounds, function(c) as.character(c$compound$id), FUN.VALUE = ''))) } } return(ids) }) ################# # GET NB PEAKS # ################# MsPeakForestDb$methods( getNbPeaks = function(molid = NA_integer_, type = NA_character_) { # Build URL params <- NULL if ( ! is.na(type)) params <- c(params, mode = if (type == MSDB.TAG.POS) 'pos' else 'neg') if ( ! is.null(molid) && (length(molid) > 1 || ! is.na(molid))) params <- c(params, molids = paste(molid, collapse = ',')) # Run request n <- .self$.get.url(url = 'spectra/lcms/count-peaks', params = params, ret.type = 'integer') return(sum(n)) }) ################# # GET MZ VALUES # ################# MsPeakForestDb$methods( getMzValues = function(mode = NULL, max.results = NA_integer_) { # Query params params <- NULL if ( ! is.null(mode)) params <- c(params, mode = if (mode == MSDB.TAG.POS) 'positive' else 'negative') # Get MZ valuels mz <- .self$.get.url(url = 'spectra/lcms/peaks/list-mz', params = params) # Apply cut-off if ( ! is.na(max.results)) mz <- mz[1:max.results] return(mz) }) ############################## # DO SEARCH FOR MZ RT BOUNDS # ############################## MsPeakForestDb$methods( .do.search.for.mz.rt.bounds = function(mode, mz.low, mz.high, rt.low = NULL, rt.high = NULL, col = NULL, attribs = NULL, molids = NULL) { # Build URL for mz search url <- paste0('spectra/lcms/peaks/get-range/', mz.low, '/', mz.high) # Get spectra spectra <- .self$.get.url(url = url) # Build result data frame results <- data.frame(MSDB.TAG.MOLID = character(), MSDB.TAG.MOLNAMES = character(), MSDB.TAG.MOLMASS = numeric(), MSDB.TAG.MZTHEO = numeric(), MSDB.TAG.COMP = character(), MSDB.TAG.ATTR = character(), MSDB.TAG.INCHI = character(), MSDB.TAG.INCHIKEY = character(), MSDB.TAG.CHEBI = character(), MSDB.TAG.HMDB = character(), MSDB.TAG.KEGG = character(), MSDB.TAG.PUBCHEM = character()) for (x in spectra) { if ('source' %in% names(x) && is.list(x$source)) mztheo <- if ('theoricalMass' %in% names(x)) as.numeric(x$theoricalMass) else NA_real_ comp <- if ('composition' %in% names(x)) x$composition else NA_character_ attr <- if ('attribution' %in% names(x)) x$attribution else NA_character_ if ('listOfCompounds' %in% names(x$source)) { molids <- vapply(x$source$listOfCompounds, function(c) as.character(c$id), FUN.VALUE = '') molnames <- vapply(x$source$listOfCompounds, function(c) paste(c$names, collapse = MSDB.MULTIVAL.FIELD.SEP), FUN.VALUE = '') mass <- vapply(x$source$listOfCompounds, function(c) as.character(c$averageMass), FUN.VALUE = '') inchi <- vapply(x$source$listOfCompounds, function(c) as.character(c$inChI), FUN.VALUE = '') inchikey <- vapply(x$source$listOfCompounds, function(c) as.character(c$inChIKey), FUN.VALUE = '') chebi <- vapply(x$source$listOfCompounds, function(c) as.character(c$ChEBI), FUN.VALUE = '') chebi[chebi == 'CHEBI:null'] <- NA_character_ hmdb <- vapply(x$source$listOfCompounds, function(c) as.character(c$HMDB), FUN.VALUE = '') hmdb[hmdb == 'HMDBnull'] <- NA_character_ kegg <- vapply(x$source$listOfCompounds, function(c) as.character(c$KEGG), FUN.VALUE = '') pubchem <- vapply(x$source$listOfCompounds, function(c) as.character(c$PubChemCID), FUN.VALUE = '') if (length(molids) > 0 && length(molids) == length(molnames)) results <- rbind(results, data.frame(MSDB.TAG.MOLID = molids, MSDB.TAG.MOLNAMES = molnames, MSDB.TAG.MOLMASS = mass, MSDB.TAG.MZTHEO = mztheo, MSDB.TAG.COMP = comp, MSDB.TAG.ATTR = attr, MSDB.TAG.INCHI = inchi, MSDB.TAG.INCHIKEY = inchikey, MSDB.TAG.CHEBI = chebi, MSDB.TAG.HMDB = hmdb, MSDB.TAG.KEGG = kegg, MSDB.TAG.PUBCHEM = pubchem, stringsAsFactors = FALSE)) } } # RT search if ( ! is.null(rt.low) && ! is.null(rt.high)) { rt.res <- data.frame(MSDB.TAG.MOLID = character(), MSDB.TAG.COL = character(), MSDB.TAG.COLRT = numeric()) if (nrow(results) > 0) { # Build URL for rt search url <- paste0('spectra/lcms/range-rt-min/', rt.low, '/', rt.high) params <- NULL if ( ! is.null(col)) params <- c(columns = paste(col, collapse = ',')) # Run query rtspectra <- .self$.get.url(url = url, params = params) # Get compound/molecule IDs for (x in spectra) rt.res <- rbind(rt.res, data.frame(MSDB.TAG.MOLID = vapply(x$listOfCompounds, function(c) as.character(c$id), FUN.VALUE = ''), MSDB.TAG.COL = as.character(x$liquidChromatography$columnCode), MSDB.TAG.COLRT = (as.numeric(x$RTmin) + as.numeric(x$RTmax)) / 2, stringsAsFactors = FALSE)) } # Add retention times and column info results <- merge(results, rt.res) } # Rename columns with proper names colnames(results) <- vapply(colnames(results), function(s) eval(parse(text=s)), FUN.VALUE = '') return(results) }) }