Mercurial > repos > prog > lcmsmatching
comparison ChemspiderCompound.R @ 0:e66bb061af06 draft
planemo upload for repository https://github.com/workflow4metabolomics/lcmsmatching.git commit 3529b25417f8e1a5836474c9adec4b696d35099d-dirty
| author | prog |
|---|---|
| date | Tue, 12 Jul 2016 12:02:37 -0400 |
| parents | |
| children | 253d531a0193 |
comparison
equal
deleted
inserted
replaced
| -1:000000000000 | 0:e66bb061af06 |
|---|---|
| 1 if ( ! exists('ChemspiderCompound')) { # Do not load again if already loaded | |
| 2 | |
| 3 source('BiodbEntry.R') | |
| 4 | |
| 5 ##################### | |
| 6 # CLASS DECLARATION # | |
| 7 ##################### | |
| 8 | |
| 9 ChemspiderCompound <- setRefClass("ChemspiderCompound", contains = "BiodbEntry") | |
| 10 | |
| 11 ########### | |
| 12 # FACTORY # | |
| 13 ########### | |
| 14 | |
| 15 createChemspiderCompoundFromHtml <- function(contents, drop = TRUE) { | |
| 16 | |
| 17 library(XML) | |
| 18 | |
| 19 compounds <- list() | |
| 20 | |
| 21 # Define xpath expressions | |
| 22 xpath.expr <- character() | |
| 23 | |
| 24 for (html in contents) { | |
| 25 | |
| 26 # Create instance | |
| 27 compound <- ChemspiderCompound$new() | |
| 28 | |
| 29 # Parse HTML | |
| 30 xml <- htmlTreeParse(html, asText = TRUE, useInternalNodes = TRUE) | |
| 31 | |
| 32 # Test generic xpath expressions | |
| 33 for (field in names(xpath.expr)) { | |
| 34 v <- xpathSApply(xml, xpath.expr[[field]], xmlValue) | |
| 35 if (length(v) > 0) | |
| 36 compound$setField(field, v) | |
| 37 } | |
| 38 | |
| 39 # Get accession | |
| 40 accession <- xpathSApply(xml, "//li[starts-with(., 'ChemSpider ID')]", xmlValue) | |
| 41 if (length(accession) > 0) { | |
| 42 accession <- sub('^ChemSpider ID([0-9]+)$', '\\1', accession, perl = TRUE) | |
| 43 compound$setField(RBIODB.ACCESSION, accession) | |
| 44 } | |
| 45 | |
| 46 compounds <- c(compounds, compound) | |
| 47 } | |
| 48 | |
| 49 # Replace elements with no accession id by NULL | |
| 50 compounds <- lapply(compounds, function(x) if (is.na(x$getField(RBIODB.ACCESSION))) NULL else x) | |
| 51 | |
| 52 # If the input was a single element, then output a single object | |
| 53 if (drop && length(contents) == 1) | |
| 54 compounds <- compounds[[1]] | |
| 55 | |
| 56 return(compounds) | |
| 57 } | |
| 58 } | |
| 59 |
