forked from brucehoff/polypharmacology-db
-
Notifications
You must be signed in to change notification settings - Fork 0
/
global.R
394 lines (316 loc) · 11.4 KB
/
global.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
options(java.parameters = "-Xmx8g" )
options(shiny.trace = TRUE)
library(shiny)
library(DT)
library(png)
library(rJava)
library(rcdk)
library(fingerprint)
library(enrichR)
library(webchem)
library(plyr)
library(dplyr)
library(tidyr)
library(purrr)
library(tibble)
library(plotly)
library(shinyBS)
library(shinythemes)
library(visNetwork)
library(igraph)
library(shinyjs)
library(rjson)
library(shinycssloaders)
library(conflicted)
conflict_prefer("filter", "dplyr")
conflict_prefer("is.connected", "rcdk")
conflict_prefer("count", "fingerprint")
conflict_prefer("renderDataTable", "DT")
conflict_prefer("arrange", "dplyr")
conflict_prefer("mutate", "dplyr")
sessionInfo()
loading <- function() {
shinyjs::hide("loading_page")
shinyjs::show("main_content")
}
is.smiles <- function(x, verbose = TRUE) { ##corrected version from webchem
if (!requireNamespace("rcdk", quietly = TRUE)) {
stop("rcdk needed for this function to work. Please install it.",
call. = FALSE)
}
# x <- 'Clc(c(Cl)c(Cl)c1C(=O)O)c(Cl)c1Cl'
if (length(x) > 1) {
stop('Cannot handle multiple input strings.')
}
message(sprintf("In 'is.smiles'. About to call parse.smiles() with %s", toJSON(x)))
out <- try(rcdk::parse.smiles(x), silent = TRUE)
if (inherits(out[[1]], "try-error") | is.null(out[[1]])) {
return(FALSE)
} else {
return(TRUE)
}
}
parseInputFingerprint <- function(input, fp.type) {
if(is.smiles(input)==TRUE){
cat(file=stderr(), input)
message(sprintf("In 'parseInputFingerprint'. About to call parse.smiles() with %s", toJSON(as.character(input))))
input.mol <- rcdk::parse.smiles(as.character(input))
cat(file=stderr(), as.character(input.mol))
lapply(input.mol, set.atom.types)
lapply(input.mol, do.aromaticity)
lapply(input.mol, do.isotopes)
fp.inp <- lapply(input.mol, get.fingerprint, type = fp.type)
}else{
print('Please input a valid SMILES string.')
}
}
distance.minified <- function(fp1,fp.list){ #this function is a stripped down fingerprint::distance that runs about 2-3x faster; big gains for the app, but not as feature rich
n <- length(fp1)
f1 <- numeric(n)
f2 <- numeric(n)
f1[fp1@bits] <- 1
sapply(fp.list, function(x){
f2[x@bits] <- 1
sim <- 0.0
ret <- .C("fpdistance", as.double(f1), as.double(f2),
as.integer(n), as.integer(1),
as.double(sim),
PACKAGE="fingerprint")
return (ret[[5]])
})
}
convertDrugToSmiles <- function(input) {
filt <- filter(db.names, synonym == input) %>%
dplyr::select(inchikey) %>%
dplyr::inner_join(db_structures) %>%
dplyr::select(std_smiles)
filt
}
getTargetList <- function(selectdrugs) {
targets <- db %>%
filter(inchikey %in% selectdrugs) %>%
as.data.frame() %>%
dplyr::select(inchikey, pref_name, hugo_gene, mean_pchembl, n_quantitative, n_qualitative, known_selectivity_index, confidence) %>%
arrange(-n_quantitative)
}
similarityFunction <- function(input, fp.type) {
input <- input
fp.type <- fp.type
fp.inp <- parseInputFingerprint(input, fp.type)
if(fp.type=="extended"){ sim <- distance.minified(fp.inp[[1]], fp.extended) }
if(fp.type=="circular"){ sim <- distance.minified(fp.inp[[1]], fp.circular) }
if(fp.type=="maccs"){ sim <- distance.minified(fp.inp[[1]], fp.maccs) }
# if(fp.type=="kr"){ sim <- distance.minified(fp.inp[[1]], fp.kr) }
# if(fp.type=="pubchem"){ sim <- distance.minified(fp.inp[[1]], fp.pubchem)
bar <- enframe(sim) %>%
set_names(c("match", "similarity")) %>%
top_n(50, similarity) ##hard cutoff to avoid overloading the app - large n of compounds can cause sluggish response wrt visualizations
}
getSimMols <- function(sims, sim.thres) {
sims2 <- sims %>% dplyr::filter(similarity >= sim.thres) %>% arrange(-similarity)
sims2$inchikey <- as.character(sims2$match)
sims2$`Tanimoto Similarity` <- signif(sims2$similarity, 3)
targets <- left_join(sims2, db) %>%
dplyr::select(inchikey, pref_name, `Tanimoto Similarity`) %>%
distinct() %>%
as.data.frame()
}
getMolImage <- function(input) {
message(sprintf("In 'getMolImage'. About to call parse.smiles() with %s", toJSON(input)))
smi <- parse.smiles(input)
view.image.2d(smi[[1]])
}
getExternalDrugLinks <- function(inchikey_input) {
links <- filter(db.links, inchikey %in% inchikey_input)
links <- as.character(links$link)
links <- paste(links, collapse = ", ")
}
getExternalGeneLinks <- function(gene) {
links <- filter(db.gene.links, hugo_gene %in% gene)
links <- as.character(links$link)
}
getNetwork <- function(drugsfound, selectdrugs) {
targets <- drugsfound %>%
distinct() %>% filter(inchikey %in% selectdrugs)
targets$from <- "input"
targets$to <- as.character(targets$pref_name)
targets$width <- ((targets$`Tanimoto Similarity`)^2) * 10
targets$color <- "tomato"
links <- sapply(selectdrugs, function(x){
links <- getExternalDrugLinks(x)
})
targets$title <- links
targets <- dplyr::select(targets, from, to, width, color, title)
}
getTargetNetwork <- function(selectdrugs, edge.size) {
targets <- getTargetList(selectdrugs)
targets$from <- targets$pref_name
targets$to <- as.character(targets$hugo_gene)
if(edge.size==TRUE){
targets$width <- scales::rescale(targets$confidence, to = c(1,10))
}
if(edge.size==FALSE){
targets$width <- 5
}
targets$color <- "tomato"
targets <- dplyr::select(targets, from, to, width, color, inchikey) %>%
filter(from !="NA" & to != "NA")
}
dbs <- c("GO_Biological_Process_2018", "GO_Cellular_Component_2018", "GO_Biological_Process_2018",
"KEGG_2019_Human")
getGeneOntologyfromTargets <- function(selectdrugs) {
selectdrugs <- selectdrugs
targets <- getTargetList(selectdrugs) %>% as.data.frame()
target.list <- targets$hugo_gene
if (length(target.list) > 0) {
enriched <- enrichr(target.list, dbs)
} else {
print("no targets")
}
}
getMolsFromGenes <- function(genes) {
if(length(genes)>1){
mols <- db %>%
filter(hugo_gene %in% genes) %>%
group_by(inchikey) %>%
mutate(count = n()) %>%
filter(count == length(genes)) %>%
ungroup() %>%
distinct() %>%
dplyr::select(-count)
}else{
mols <- filter(db, hugo_gene == genes)
}
mols %>%
select(inchikey, pref_name, hugo_gene, mean_pchembl, n_quantitative, n_qualitative, known_selectivity_index, confidence)
}
getMolsFromGeneNetworks.edges <- function(inp.gene, genenetmols, edge.size, gene.filter.metric) {
mols <- genenetmols %>% top_n(15, !!sym(gene.filter.metric))
net <- filter(db, inchikey %in% mols$inchikey) %>% distinct()
net$from <- as.character(net$inchikey)
net$to <- as.character(net$hugo_gene)
if(edge.size==TRUE){
net$width <- (net$confidence)/10
}
if(edge.size==FALSE){
net$width <- 5
}
net$color <- "tomato"
net <- net %>% dplyr::select(from, to, width, color)
as.data.frame(net)
}
getMolsFromGeneNetworks.nodes <- function(inp.gene, genenetmols, gene.filter.metric) {
mols <- genenetmols %>% top_n(15, !!sym(gene.filter.metric))
net <- filter(db, inchikey %in% mols$inchikey) %>%
distinct() # %>%
# group_by(common_name) %>%
# top_n(20, confidence) %>%
# ungroup()
id <- c(unique(as.character(net$inchikey)),
unique(as.character(net$hugo_gene)))
label <- c(unique(as.character(net$pref_name)),
unique(as.character(net$hugo_gene)))
color <- c(rep("blue", length(unique(as.character(net$pref_name)))),
rep("green", length(unique(as.character(net$hugo_gene)))))
druglinks <- sapply(unique(as.character(net$inchikey)), function(x){
druglinks <- getExternalDrugLinks(x)
})
genelinks <- sapply(unique(as.character(net$hugo_gene)), function(x){
getExternalGeneLinks(x)
})
title <- c(druglinks, genelinks)
net <- as.data.frame(cbind(id, label, color, title))
}
convert_id_to_structure_pubchem <- function(input_id, id_type = c("name", "inchikey"), output_type = c("InChI", "InChIKey", "CanonicalSMILES", "IsomericSMILES")){
Sys.sleep(0.25) ##to prevent requests from happening too fast
input <- URLencode(input_id)
statement <- glue::glue('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/{id_type}/{input}/property/{output_type}/xml')
res <- httr::GET(statement)
if(res$status_code==200){
res_2 <- XML::xmlToList(rawToChar(res$content))
struct <- purrr::pluck(res_2, "Properties", 2)
if(is.null(struct)){struct <- NA}
}else{
message(glue::glue('input "{input_id}" appears to be invalid'))
struct <- NA
}
struct
}
plotSimCTRPDrugs <- function(input, fp.type) {
fp.inp <- parseInputFingerprint(input, fp.type = fp.type)
if(fp.type == "circular"){fp.ctrp <- fp.ctrp.circular}
if(fp.type == "extended"){fp.ctrp <- fp.ctrp.extended}
if(fp.type == "maccs"){fp.ctrp <- fp.ctrp.maccs}
sims <- lapply(fp.inp, function(i) {
sim <- sapply(fp.ctrp, function(j) {
distance(i, j)
})
bar <- as.data.frame(sim)
bar$match <- rownames(bar)
bar
})
sims <- ldply(sims)
sims2 <- sims %>% arrange(-sim)
sims2$cpd_smiles <- as.character(sims2$match)
sims2$`Tanimoto Similarity` <- signif(sims2$sim, 3)
drugs <- left_join(sims2, ctrp.structures) %>% dplyr::select(makenames, cpd_name, `Tanimoto Similarity`) %>% distinct()
top_drug <- top_n(drugs, 1, `Tanimoto Similarity`)
drug.resp.single <- drug.resp[[top_drug$makenames]]
cors<-sapply(colnames(drug.resp), function(x){
test <- data.frame(drug.resp.single, drug.resp[[x]])
if(nrow(test[complete.cases(test),])>1){
cor<-cor.test(drug.resp.single, drug.resp[[x]], method = "spearman", use = "complete.obs")
res <- c("p.val" = cor$p.value, cor$estimate)
}else{
res <- c("p.val" = -1, "rho" = 0)
}
})
cors <- cors %>%
t() %>%
as.data.frame() %>%
rownames_to_column("makenames") %>%
inner_join(drugs) %>%
filter(p.val != -1)
cors$Correlation <- cors$rho
cors$`BH adj p.val` <- p.adjust(cors$p.val, method = "BH")
cors
}
plotSimSangDrugs <- function(input, fp.type) {
fp.inp <- parseInputFingerprint(input, fp.type = fp.type)
if(fp.type == "circular"){fp.sang <- fp.sang.circular}
if(fp.type == "extended"){fp.sang <- fp.sang.extended}
if(fp.type == "maccs"){fp.sang <- fp.sang.maccs}
sims <- lapply(fp.inp, function(i) {
sim <- sapply(fp.sang, function(j) {
distance(i, j)
})
bar <- as.data.frame(sim)
bar$match <- rownames(bar)
bar
})
sims <- ldply(sims)
sims2 <- sims %>% arrange(-sim)
sims2$smiles <- as.character(sims2$match)
sims2$`Tanimoto Similarity` <- signif(sims2$sim, 3)
drugs <- left_join(sims2, sang.structures) %>% dplyr::select(makenames, sanger_names, `Tanimoto Similarity`) %>% distinct()
top_drug <- top_n(drugs, 1, `Tanimoto Similarity`)
drug.resp.single <- drug.resp.sang[[top_drug$makenames]]
cors<-sapply(colnames(drug.resp.sang), function(x){
test <- data.frame(drug.resp.single, drug.resp.sang[[x]])
if(nrow(test[complete.cases(test),])>1){
cor<-cor.test(drug.resp.single, drug.resp.sang[[x]], method = "spearman", use = "complete.obs")
res <- c("p.val" = cor$p.value, cor$estimate)
}else{
res <- c("p.val" = -1, "rho" = 0)
}
})
cors <- cors %>%
t() %>%
as.data.frame() %>%
rownames_to_column("makenames") %>%
inner_join(drugs) %>%
filter(p.val != -1)
cors$Correlation <- cors$rho
cors$`BH adj p.val` <- p.adjust(cors$p.val, method = "BH")
cors
}