This repository has been archived by the owner on Dec 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChebiConn.R
401 lines (319 loc) · 12.6 KB
/
ChebiConn.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
#' ChEBI connector class.
#'
#' This is the connector class for connecting to the ChEBI database through its
#' web services.
#'
#' @examples
#' # Create an instance with default settings:
#' mybiodb <- biodb::newInst()
#'
#' # Create a connector
#' conn <- mybiodb$getFactory()$createConn('chebi')
#'
#' # Get an entry
#' e <- conn$getEntry('15440')
#'
#' # Convert an InChI KEY to a ChEBI identifier
#' conn$convInchiToChebi('YYGNTYWPHWGJRM-AAJYLUCBSA-N')
#'
#' # Terminate instance.
#' mybiodb$terminate()
#'
#' @importFrom R6 R6Class
#' @export
ChebiConn <- R6::R6Class("ChebiConn",
inherit=biodb::BiodbConn,
public=list(
#' @description
#' New instance initializer. Connector classes must not be instantiated
#' directly. Instead, you must use the createConn() method of the factory class.
#' @param ... All parameters are passed to the super class initializer.
#' @return Nothing.
initialize=function(...) {
super$initialize(...)
private$wsdl <- NULL
private$wsValues <- list()
},
#' @description
#' Retrieves the complete WSDL from the web server.
#' @param retfmt The return format to use. 'plain' will return the value as it
#' is returned by the server. 'parsed' will return an XML object. 'request'
#' will return a BiodbRequest object representing the request that would have
#' been sent.
#' @return Depending on `retfmt` value.
wsWsdl=function(retfmt=c('plain', 'parsed', 'request')) {
retfmt <- match.arg(retfmt)
# Build request
url <- c(self$getPropValSlot('urls', 'ws.url'), 'webservice')
request <- self$makeRequest(method='get', url=BiodbUrl$new(url=url,
params='wsdl'))
if (retfmt == 'request')
return(request)
# Send request
results <- self$getBiodb()$getRequestScheduler()$sendRequest(request)
# Parse
if (retfmt == 'parsed')
results <- XML::xmlInternalTreeParse(results, asText=TRUE)
return(results)
},
#' @description
#' Calls getLiteEntity web service and returns the XML result. Be careful when
#' searching by mass (search.category='MASS' or 'MONOISOTOPIC MASS'), since the
#' search is made in text mode, thus the number must be exactly written as it
#' is stored in database, eventually padded with 0 in order to have exactly 5
#' digits after the decimal. An easy solution is to use wildcards to search a
#' mass '410;.718*'.
#' See http //www.ebi.ac.uk/chebi/webServices.do for more details.
#' @param search The text or pattern to search.
#' @param search.category The search category. Call `getSearchCategories()` to
#' get a full list of search categories.
#' @param max.results The maximum of results to return.
#' @param stars How many starts the returned entities should have. Call
#' `getStarsCategories() to get a full list of starts categories.`
#' @param retfmt The return format to use. 'plain' will return the results as
#' given by the server, in a string. 'parsed' will return an XML object.
#' 'request' will return a BiodbRequest object representing the request as
#' would have been sent. 'ids' will return a list of matched entity IDs.
#' @return Depending on `retfmt` value.
wsGetLiteEntity=function(search=NULL, search.category='ALL', stars='ALL',
max.results=10, retfmt=c('plain', 'parsed', 'request', 'ids')) {
retfmt <- match.arg(retfmt)
# Check parameters
chk::chk_string(search)
chk::chk_subset(search.category, self$getSearchCategories())
chk::chk_number(max.results)
chk::chk_gte(max.results, 0)
chk::chk_subset(stars, self$getStarsCategories())
# Build request
params <- c(search=search,
searchCategory=search.category,
maximumResults=max.results,
starsCategory=stars)
url <- c(self$getPropValSlot('urls', 'ws.url'), 'test/getLiteEntity')
request <- self$makeRequest(method='get',
url=BiodbUrl$new(url=url, params=params), encoding='UTF-8')
if (retfmt == 'request')
return(request)
# Send request
results <- self$getBiodb()$getRequestScheduler()$sendRequest(request)
# Parse
if (retfmt != 'plain') {
# Parse XML
results <- XML::xmlInternalTreeParse(results, asText=TRUE)
if (retfmt == 'ids') {
ns <- self$getPropertyValue('xml.ns')
results <- XML::xpathSApply(results, "//chebi:chebiId",
XML::xmlValue, namespaces=ns)
results <- sub('CHEBI:', '', results)
if (length(grep("^[0-9]+$", results)) != length(results))
biodb::error("Impossible to parse XML to get entry IDs.")
}
}
return(results)
},
#' @description
#' Converts a list of IDs (InChI, InChI Keys, CAS, ...) into a list of ChEBI
#' IDs. Several ChEBI IDs may be returned for a single ID.
#' @param ids The identifiers to convert.
#' @param simplify If set to TRUE and only one ChEBI ID has been found for each
#' ID, then a character vector is returned. Otherwise a list of character
#' vectors is returned.
#' @param search.category The search category. Call `getSearchCategories()` to
#' get a full list of search categories.
#' @return Depending on the value of simplify.
convIdsToChebiIds=function(ids, search.category, simplify=TRUE) {
chebi <- list()
msg <- paste('Converting', search.category, 'IDs to ChEBI IDs.')
# Loop on all cas IDs
prg <- biodb::Progress$new(biodb=self$getBiodb(), msg=msg,
total=length(ids))
for (id in ids) {
# Get ChEBI IDs for this ID
if (is.na(id))
x <- character()
else
x <- self$wsGetLiteEntity(id, search.category=search.category,
retfmt='ids')
chebi <- c(chebi, list(x))
# Send progress message
prg$increment()
}
# Simplify
if (simplify && all(vapply(chebi, length, FUN.VALUE=1L) < 2)) {
chebi <- lapply(chebi, function(x) if (length(x) == 0) NA_character_
else x)
chebi <- unlist(chebi)
}
return(chebi)
},
#' @description
#' Converts a list of InChI or InChI KEYs into a list of ChEBI IDs. Several
#' ChEBI IDs may be returned for a single InChI or InChI KEY.
#' @param inchi The InChI values to convert.
#' @param simplify If set to TRUE and only one ChEBI ID has been found for each
#' ID, then a character vector is returned. Otherwise a list of character
#' vectors is returned.
#' @return Depending on the value of simplify.
convInchiToChebi=function(inchi, simplify=TRUE) {
return(self$convIdsToChebiIds(inchi, search.category='INCHI/INCHI KEY',
simplify=simplify))
},
#' @description
#' Converts a list of CAS IDs into a list of ChEBI IDs. Several ChEBI IDs may
#' be returned for a single InChI or InChI KEY.
#' @param cas The CAS IDs to convert.
#' @param simplify If set to TRUE and only one ChEBI ID has been found for each
#' ID, then a character vector is returned. Otherwise a list of character
#' vectors is returned.
#' @return Depending on the value of simplify.
convCasToChebi=function(cas, simplify=TRUE) {
return(self$convIdsToChebiIds(cas, search.category='REGISTRY NUMBERS',
simplify=simplify))
},
#' @description
#' Gets the WSDL as an XML object.
#' @return The ChEBI WSDL as an XML object.
getWsdl=function() {
if (is.null(private$wsdl))
private$wsdl <- self$wsWsdl(retfmt='parsed')
return(private$wsdl)
},
#' @description
#' Extracts a list of values from an enumeration in the WSDL.
#' @param name The name of the enumeration for which to retrieve the values.
#' @return A character vector listing the enumerated values.
getWsdlEnumeration=function(name) {
if ( ! name %in% names(private$wsValues)) {
ns <- self$getPropertyValue('xml.ns')
# Get search categories
expr <- paste0("//xsd:simpleType[@name='", name, "']//xsd:enumeration")
res <- XML::xpathSApply(self$getWsdl(), expr, XML::xmlGetAttr, 'value',
namespaces=ns)
private$wsValues[[name]] <- res
}
return(private$wsValues[[name]])
},
#' @description
#' Gets the list of allowed stars categories for the getLiteEntity web service.
#' @return Returns all the possible stars categories as a character vector.
getStarsCategories=function() {
return(self$getWsdlEnumeration('StarsCategory'))
},
#' @description
#' Gets the list of allowed search categories for the getLiteEntity web
#' service.
#' @return Returns all the possible search categories as a character vector.
getSearchCategories=function() {
return(self$getWsdlEnumeration('SearchCategory'))
}
),
private=list(
wsdl=NULL,
wsValues=NULL,
searchByMass=function(mass.field, mass.min, mass.max, max.results=0) {
ids <- character()
# Set search category
if (mass.field == 'monoisotopic.mass')
search.category <- 'MONOISOTOPIC MASS'
else if (mass.field == 'molecular.mass')
search.category <- 'MASS'
else
biodb::error('Unknown mass field "%s".', mass.field)
# Search for all masses in the range
n <- floor(log10(mass.max - mass.min))
if (n >= 0)
n <- -1
firstMass <- floor(mass.min * 10^-n) * 10^n
lastMass <- ceiling(mass.max * 10^-n) * 10^n
for (m in seq(firstMass, lastMass, 10^n)) {
# Get entries matching integer mass
x <- self$wsGetLiteEntity(search=paste0(m, '*'),
search.category=search.category, max.results=0, retfmt='ids')
# Remove IDs that we already have
x <- x[ ! x %in% ids]
# Filter on mass range
x <- private$filterIdsOnMassRange(x, mass.min, mass.max, mass.field,
max.results - length(ids))
# Add IDs
ids <- c(ids, x)
if ( ! is.na(max.results) && max.results > 0 && length(ids)
>= max.results)
break
}
# Remove duplicates
ids <- ids[ ! duplicated(ids)]
return(ids)
},
doSearchForEntries=function(fields=NULL, max.results=0) {
ids <- NULL
if ( ! is.null(fields)) {
# Search by name
if ('name' %in% names(fields))
ids <- self$wsGetLiteEntity(search=fields$name,
search.category="ALL NAMES", max.results=0, retfmt='ids')
# Search by mass
for (mass.field in c('monoisotopic.mass', 'molecular.mass'))
if (mass.field %in% names(fields)) {
rng <- do.call(Range$new, fields[[mass.field]])
if (is.null(ids))
ids <- private$searchByMass(mass.field,
mass.min=rng$getMin(), mass.max=rng$getMax(),
max.results=max.results)
else
ids <- private$filterIdsOnMassRange(ids,
mass.min=rng$getMin(), mass.max=rng$getMax(),
mass.field=mass.field, limit=max.results)
}
}
return(ids)
},
doGetEntryContentRequest=function(id, concatenate=TRUE) {
url <- c(self$getPropValSlot('urls', 'ws.url'), 'test',
'getCompleteEntity')
urls <- vapply(id, function(x) BiodbUrl$new(url=url,
params=list(chebiId=x))$toString(), FUN.VALUE='')
return(urls)
},
doGetEntryPageUrl=function(id) {
url <- c(self$getPropValSlot('urls', 'base.url'), 'searchId.do')
urls <- vapply(id, function(x) BiodbUrl$new(url=url,
params=list(chebiId=x))$toString(), FUN.VALUE='')
return(urls)
},
doGetEntryImageUrl=function(id) {
url <- c(self$getPropValSlot('urls', 'base.url'), 'displayImage.do')
urls <- vapply(id, function(x) BiodbUrl$new(url=url,
params=list(defaultImage='true', imageIndex=0, chebiId=x,
dimensions=400))$toString(), FUN.VALUE='')
return(urls)
},
doGetEntryIds=function(max.results=NA_integer_) {
return(self$wsGetLiteEntity(search='1*', search.category='CHEBI ID',
max.results=max.results, retfmt='ids'))
},
filterIdsOnMassRange=function(ids, mass.min, mass.max, mass.field, limit=0) {
retids <- character()
msg <- paste0('Filtering ChEBI entries on mass range [', mass.min, ',
', mass.max, '] and field "', mass.field, '".')
# Loop on all IDs
prg <- biodb::Progress$new(biodb=self$getBiodb(), msg=msg,
total=length(ids))
for (id in ids) {
# Print progress
prg$increment()
# Get entry
e <- self$getEntry(id, drop=TRUE)
# Test mass
if ( ! is.null(e)) {
m <- e$getFieldValue(mass.field)
if ( ! is.na(m) && m >= mass.min && m <= mass.max) {
retids <- c(retids, id)
# Stop if limit is reached
if (limit > 0 && length(retids) >= limit)
break
}
}
}
return(retids)
}
))