-
Notifications
You must be signed in to change notification settings - Fork 19
/
webAccess.R
executable file
·546 lines (459 loc) · 14.7 KB
/
webAccess.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
#' @import XML RCurl rjson httr
NULL
## library(XML)
## library(RCurl)
#' Retrieve information from Cactus
#'
#' Retrieves information from the Cactus Chemical Identifier Resolver
#' (PubChem).
#'
#' It is not necessary to specify in which format the \code{identifier} is.
#' Somehow, cactus does this automatically.
#'
#' @usage getCactus(identifier, representation)
#' @param identifier Any identifier interpreted by the resolver, e.g. an InChI
#' key or a SMILES code.
#' @param representation The desired representation, as required from the
#' resolver. e.g. \code{stdinchikey}, \code{chemspider_id}, \code{formula}...
#' Refer to the webpage for details.
#' @return The result of the query, in plain text. Can be NA, or one or
#' multiple lines (character array) of results.
#' @note Note that the InChI key is retrieved with a prefix (\code{InChIkey=}),
#' which must be removed for most database searches in other databases (e.g.
#' CTS).
#' @author Michael Stravs
#' @seealso \code{\link{getCtsRecord}}, \code{\link{getPcId}}
#' @references cactus Chemical Identifier Resolver:
#' \url{http://cactus.nci.nih.gov/chemical/structure}
#' @examples
#'
#' # Benzene:
#' getCactus("C1=CC=CC=C1", "cas")
#' getCactus("C1=CC=CC=C1", "stdinchikey")
#' getCactus("C1=CC=CC=C1", "chemspider_id")
#'
#' @export
#'
#'
getCactus <- function(identifier,representation){
ret <- tryCatch(httr::GET(paste("https://cactus.nci.nih.gov/chemical/structure/",
URLencode(identifier), "/", representation, sep = "")),
error = function(e) NA)
if (all(is.na(ret)))
return(NA)
if (ret[2] == 404)
return(NA)
ret <- httr::content(ret)
return(unlist(strsplit(ret, "\n")))
}
#' Search Pubchem CID
#'
#' Retrieves PubChem CIDs for a search term.
#'
#' Only the first result is returned currently. \bold{The function should be
#' regarded as experimental and has not thoroughly been tested.}
#'
#' @usage getPcId(query, from = "inchikey")
#' @param query ID to be converted
#' @param from Type of input ID
#' @return The PubChem CID (in string type).
#' @author Michael Stravs, Erik Mueller
#' @seealso \code{\link{getCtsRecord}}, \code{\link{getCactus}}
#' @references PubChem search: \url{http://pubchem.ncbi.nlm.nih.gov/}
#'
#' Pubchem REST:
#' \url{https://pubchem.ncbi.nlm.nih.gov/pug_rest/PUG_REST.html}
#' @examples
#' getPcId("MKXZASYAUGDDCJ-NJAFHUGGSA-N")
#'
#' @export
getPcId <- function(query, from = "inchikey")
{
baseURL <- "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound"
url <- paste(baseURL, from, query, "description", "json", sep="/")
errorvar <- 0
currEnvir <- environment()
tryCatch(
data <- getURL(URLencode(url),timeout=5),
error=function(e){
currEnvir$errorvar <- 1
})
if(errorvar){
return(NA)
}
# This happens if the InChI key is not found:
r <- fromJSON(data)
if(!is.null(r$Fault))
return(NA)
titleEntry <- which(unlist(lapply(r$InformationList$Information, function(i) !is.null(i$Title))))
titleEntry <- titleEntry[which.min(sapply(titleEntry, function(x)r$InformationList$Information[[x]]$CID))]
PcID <- r$InformationList$Information[[titleEntry]]$CID
if(is.null(PcID)){
return(NA)
} else{
return(PcID)
}
}
# The following function is unfinished.
# getPcRecord <- function(pcid)
# {
# baseUrl <- "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/"
# term <- paste(baseUrl, "esummary.fcgi?db=pccompound&id=", URLencode(as.character(pcid)),
#
# sep='')
# ret <- getURL(term)
# xml <- xmlParseDoc(ret,asText=TRUE)
# browser()
# }
# Note: some of the CHEBI codes returned are erroneous. (When the entry in
# CTS starts with "CHEBI:" instead of just the number, the XML output)
# Also, there is no ChemSpider ID in the XML output, unfortunately.
#' Retrieve information from CTS
#'
#' Retrieves a complete CTS record from the InChI key.
#'
#' @usage getCtsRecord(key)
#'
#' @param key The InChI key.
#' @return Returns a list with all information from CTS: \code{inchikey,
#' inchicode, formula, exactmass} contain single values. \code{synonyms} contains
#' an unordered list of scored synonyms (\code{type, name, score}, where \code{type}
#' indicates either a normal name or a specific IUPAC name, see below).
#' \code{externalIds} contains an unordered list of identifiers of the compound in
#' various databases (\code{name, value}, where \code{name} is the database name and
#' \code{value} the identifier in that database.)
#'
#' @note Currently, the CTS results are still incomplete; the name scores are all 0,
#' formula and exact mass return zero.
#' @references Chemical Translation Service:
#' \url{https://cts.fiehnlab.ucdavis.edu}
#'
#' @examples
#' data <- getCtsRecord("UHOVQNZJYSORNB-UHFFFAOYSA-N")
#' # show all synonym "types"
#' types <- unique(unlist(lapply(data$synonyms, function(i) i$type)))
#' \dontrun{print(types)}
#'
#' @author Michele Stravs, Eawag <stravsmi@@eawag.ch>
#' @export
getCtsRecord <- function(key)
{
baseURL <- "https://cts.fiehnlab.ucdavis.edu/service/compound/"
errorvar <- 0
currEnvir <- environment()
##tryCatch a CTS timeout
##
tryCatch(
{
data <- getURL(paste0(baseURL,key), timeout=7)
},
error=function(e){
currEnvir$errorvar <- 1
}
)
if(errorvar){
warning("CTS seems to be currently unavailable or incapable of interpreting your request")
return(NULL)
}
r <- fromJSON(data)
if(length(r) == 1)
if(r == "You entered an invalid InChIKey")
return(list())
return(r)
}
#' Convert a single ID to another using CTS.
#'
#' @usage getCtsKey(query, from = "Chemical Name", to = "InChIKey")
#' @param query ID to be converted
#' @param from Type of input ID
#' @param to Desired output ID
#' @return An unordered array with the resulting converted key(s).
#'
#' @examples
#' k <- getCtsKey("benzene", "Chemical Name", "InChIKey")
#' @author Michele Stravs, Eawag <stravsmi@@eawag.ch>
#' @export
getCtsKey <- function(query, from = "Chemical Name", to = "InChIKey")
{
baseURL <- "https://cts.fiehnlab.ucdavis.edu/service/convert"
url <- paste(baseURL, from, to, query, sep='/')
errorvar <- 0
currEnvir <- environment()
##tryCatch a CTS timeout
##
tryCatch(
{
data <- getURL(URLencode(url), timeout=7)
},
error=function(e){
currEnvir$errorvar <- 1
}
)
if(errorvar){
warning("CTS seems to be currently unavailable or incapable of interpreting your request")
return(NULL)
}
r <- fromJSON(data)
if(length(r) == 0)
return(NULL)
else
{
# read out the results in simplest form:
results <- unlist(lapply(r, function(row) row$result))
return(results)
}
}
#' Select a subset of external IDs from a CTS record.
#'
#' @usage CTS.externalIdSubset(data, database)
#' @param data The complete CTS record as retrieved by \code{\link{getCtsRecord}}.
#' @param database The database for which keys should be returned.
#' @return Returns an array of all external identifiers stored in the record for the
#' given database.
#'
#' @examples
#'
#' \dontrun{
#' # Return all CAS registry numbers stored for benzene.
#' data <- getCtsRecord("UHOVQNZJYSORNB-UHFFFAOYSA-N")
#' cas <- CTS.externalIdSubset(data, "CAS")
#' }
#'
#' @author Michele Stravs, Eawag <stravsmi@@eawag.ch>
#' @export
CTS.externalIdSubset <- function(data, database)
{
select <- which(unlist(lapply(data$externalIds, function(id)
{
id[["name"]] == database
})))
keyEntries <- data$externalIds[select]
keys <- unlist(lapply(keyEntries, function(e) e[["value"]]))
}
#' Find all available databases for a CTS record
#'
#' @usage CTS.externalIdTypes(data)
#' @param data The complete CTS record as retrieved by \code{\link{getCtsRecord}}.
#' @return Returns an array of all database names for which there are external
#' identifiers stored in the record.
#'
#' @examples
#'
#' \dontrun{
#' # Return all databases for which the benzene entry has
#' # links in the CTS record.
#'
#' data <- getCTS("UHOVQNZJYSORNB-UHFFFAOYSA-N")
#' databases <- CTS.externalIdTypes(data)
#' }
#'
#' @author Michele Stravs, Eawag <stravsmi@@eawag.ch>
#' @export
CTS.externalIdTypes <- function(data)
{
unique(unlist(lapply(data$externalIds, function(id)
{
id[["name"]]
})))
}
.pubChemOnline <- function(){
baseURL <- "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound"
url <- paste(baseURL, "inchikey", "QEIXBXXKTUNWDK-UHFFFAOYSA-N", "description", "json", sep="/")
errorvar <- 0
currEnvir <- environment()
tryCatch(
ret <- getURL(URLencode(url), timeout=5),
error=function(e){
currEnvir$errorvar <- 1
})
if(errorvar){
warning("Pubchem is currently offline")
return(FALSE)
} else{
return(TRUE)
}
}
getPcCHEBI <- function(query, from = "inchikey")
{
# Get the JSON-Data from Pubchem
baseURL <- "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound"
url <- paste(baseURL, from, query, "synonyms", "json", sep="/")
errorvar <- 0
currEnvir <- environment()
tryCatch(
data <- getURL(URLencode(url),timeout=5),
error=function(e){
currEnvir$errorvar <- 1
})
if(errorvar){
return(NA)
}
r <- fromJSON(data)
# This happens if the InChI key is not found:
if(!is.null(r$Fault))
return(NA)
# Find the entries which contain Chebi-links
synonymEntry <- which(unlist(lapply(r$InformationList$Information, function(i) !is.null(i$Synonym))))
synonymList <- r$InformationList$Information[[synonymEntry]]$Synonym
matchChebi <- which(grepl("CHEBI:", synonymList, fixed=TRUE))
# It doesn't matter if the db is down or if chebi isn't found, so return NA also
if(length(matchChebi) == 0){
return (NA)
} else {
return (sapply(matchChebi, function(x) synonymList[[x]]))
}
}
#' Retrieve the Chemspider ID for a given compound
#'
#' Given an InChIKey, this function queries the chemspider web API to retrieve
#' the Chemspider ID of he compound with that InChIkey.
#'
#' @usage getCSID(query)
#'
#' @param query The InChIKey of the compound
#' @return Returns the chemspide
#'
#' @examples
#'
#' \dontrun{
#' # Return all CAS registry numbers stored for benzene.
#' data <- getCtsRecord("UHOVQNZJYSORNB-UHFFFAOYSA-N")
#' cas <- CTS.externalIdSubset(data, "CAS")
#' }
#'
#' @author Michele Stravs, Eawag <stravsmi@@eawag.ch>
#' @author Erik Mueller, UFZ <erik.mueller@@ufz.de>
#' @export
getCSID <- function(query)
{
baseURL <- "http://www.chemspider.com/InChI.asmx/InChIKeyToCSID?inchi_key="
url <- paste0(baseURL, query)
errorvar <- 0
currEnvir <- environment()
tryCatch(
data <- getURL(URLencode(url), timeout=5),
error=function(e){
currEnvir$errorvar <- 1
})
if(errorvar){
warning("Chemspider is currently offline")
return(NA)
}
xml <- xmlParseDoc(data,asText=TRUE)
# the returned XML document contains only the root node called "string" which contains the correct CSID
idNodes <- getNodeSet(xml, "/")
id <- xmlValue(idNodes[[1]])
return(id)
}
##This function returns a sensible name for the compound
getPcSynonym <- function (query, from = "inchikey")
{
# Get the JSON-Data from Pubchem
baseURL <- "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound"
url <- paste(baseURL, from, query, "description", "json", sep="/")
errorvar <- 0
currEnvir <- environment()
tryCatch(
data <- getURL(URLencode(url),timeout=5),
error=function(e){
currEnvir$errorvar <- 1
})
if(errorvar){
return(NA)
}
r <- fromJSON(data)
# This happens if the InChI key is not found:
if(!is.null(r$Fault))
return(NA)
# Find the synonym
titleEntry <- which(unlist(lapply(r$InformationList$Information, function(i) !is.null(i$Title))))
titleEntry <- titleEntry[which.min(sapply(titleEntry, function(x)r$InformationList$Information[[x]]$CID))]
title <- r$InformationList$Information[[titleEntry]]$Title
if(is.null(title)){
return(NA)
} else{
return(title)
}
}
##A function to retrieve a IUPAC Name from Pubchem
getPcIUPAC <- function (query, from = "inchikey")
{
# Get the JSON-Data from Pubchem
baseURL <- "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound"
url <- paste(baseURL, from, query, "record", "json", sep="/")
errorvar <- 0
currEnvir <- environment()
tryCatch(
data <- getURL(URLencode(url),timeout=5),
error=function(e){
currEnvir$errorvar <- 1
})
if(errorvar){
return(NA)
}
r <- fromJSON(data)
# This happens if the InChI key is not found:
if(!is.null(r$Fault))
return(NA)
# Find the IUPAC-Names
if(!is.null(r$PC_Compounds[[1]]$props)){
IUPACIndex <- which(unlist(lapply(r$PC_Compounds[[1]]$props, function(i) (i$urn$label == "IUPAC Name"))))
if(length(IUPACIndex) > 0){
# Retrieve all IUPAC-Names
IUPACEntries <- lapply(IUPACIndex, function(x) r$PC_Compounds[[1]]$props[[x]])
if(!is.null(IUPACEntries)){
# Is there a preferred IUPAC-Name? If yes, retrieve that
PrefIUPAC <- which(unlist(lapply(IUPACEntries, function(x) x$urn$name == "Preferred")))
} else{return(NA)}
} else{return(NA)}
} else{return(NA)}
if(length(PrefIUPAC) == 1){
return(IUPACEntries[[PrefIUPAC]]$value$sval)
} else{
# Else it doesn't matter which
return(IUPACEntries[[1]]$value$sval)
}
}
getPcInchiKey <- function(query, from = "smiles"){
# Get the JSON-Data from Pubchem
baseURL <- "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound"
url <- paste(baseURL, from, query, "record", "json", sep="/")
errorvar <- 0
currEnvir <- environment()
tryCatch(
data <- getURL(URLencode(url),timeout=5),
error=function(e){
currEnvir$errorvar <- 1
})
if(errorvar){
return(NA)
}
r <- fromJSON(data)
# This happens if the InChI key is not found:
if(!is.null(r$Fault))
return(NA)
# Find the entries which contain Chebi-links
if(!is.null(r$PC_Compounds[[1]]$props)){
INKEYindex <- which(sapply(r$PC_Compounds[[1]]$props, function(x) x$urn$label) == "InChIKey")
if(length(INKEYindex) > 0){
return(r$PC_Compounds[[1]]$props[[INKEYindex]]$value$sval)
} else{return(NA)}
} else{return(NA)}
}
getPcSDF <- function(query, from = "smiles"){
baseURL <- "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound"
url <- paste(baseURL, from, query, "sdf", sep="/")
errorvar <- 0
currEnvir <- environment()
tryCatch(
data <- getURL(URLencode(url),timeout=5),
error=function(e){
currEnvir$errorvar <- 1
})
if(errorvar){
return(NA)
}
molEnd <- regexpr(data,pattern="M END",fixed=TRUE)+5
data <- c(strsplit(substring(data,1,molEnd),"\n")[[1]],"$$$$")
return(data)
}