-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-mfuzz.R
598 lines (518 loc) · 19.6 KB
/
server-mfuzz.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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
#server-mfuzz.R
MFEnrichRun <- reactiveValues(MFEnrichRunValue = FALSE) # to precise the run button has not been clicked
observeEvent(input$mfuzzCountData, { # when a table is being uploaded
tryCatch({
var$mfuzzTable <- # assign the table as a data frame to this variable
data.frame(fread(input$mfuzzCountData$datapath), row.names = 1)
v$importActionValue = FALSE # precise no button has been clicked yet
},
error = function(e) { # error messages about the input table
sendSweetAlert(
session = session,
title = "Input data error!",
text = as.character(message(e)),
type = "error"
)
return()
},
warning = function(w) {
sendSweetAlert(
session = session,
title = "Input data warning!",
text = "Error in dataset",
type = "warning"
)
return()
})
var$mfuzzTable <- var$mfuzzTable[rowSums(var$mfuzzTable >= 1) > 0 , ]
var$timepoints <- as.vector(colnames(var$mfuzzTable))
output$inertia_plot <-renderPlotly({
hierdata <- as.matrix((var$mfuzzTable))
# Euclidean distance
dist <- dist(hierdata, diag=TRUE)
# Hierarchical Clustering with hclust
hc <- hclust(dist)
inertia <- sort(hc$height, decreasing = TRUE)
max <- as.numeric(input$maxclass)
inertia <- inertia[1:max]
az <- c(1:max)
df <- as.data.frame(inertia, row.names = c(1:max))
df["class"] <- az
fig <- plot_ly(
df,
x = ~az,
y = ~inertia,
type = "scatter",
mode = "markers"
)%>% add_lines(y = df$az, line = list(shape = "vh"))
fig <- fig %>% layout(
title = "Inertia drops",
xaxis = list(title = "Clusters"),
yaxis = list(title = "Inertia"),
showlegend = F
)
})
observeEvent(input$inertiaclass,{ # when a filter of low count genes is set
if (input$inertiaclass != 0) {
mfmat <- as.matrix((var$mfuzzTable))
mfmat <- DGEList(counts = mfmat, group=colnames(var$mfuzzTable))
mfmat <- calcNormFactors(mfmat)
mfcpm <- cpm(mfmat, normalized.lib.size=TRUE)
timepoint <- colnames(var$mfuzzTable)
test_data <- rbind(timepoint, mfcpm)
row.names(test_data)[1]<-"time"
#save it to a temp file so ti doesn't clutter up the blog directory
tmp <- tempfile()
write.table(test_data,file=tmp, sep='\t', col.names=NA)
#read it back in as an expression set
mfdata <- table2eset(file=tmp)
mfdata.s <- standardise(mfdata)
m1 <- mestimate(mfdata.s)
cent <- input$inertiaclass
i=0
for (i in 0:9){
N_cl<- mfuzz(mfdata.s, centers=cent, m = m1)
i = i + 1
}
ov <- overlap(N_cl)
}
output$elbow_plot <- renderPlot({
data.s <- as.matrix(mfdata.s)
scaledata <- t(scale(t(data.s))) # Centers and scales data.
scaledata <- scaledata[complete.cases(scaledata),]
#helper function for the within sum of squared error
sumsqr <- function(x, clusters){
sumsqr <- function(x) sum(scale(x, scale = FALSE)^2)
wss <- sapply(split(as.data.frame(x), clusters), sumsqr)
return(wss)
}
#get the wss for repeated clustering
iterate_fcm_WSS <- function(df,m){
totss <- numeric()
for (i in 2:20){
FCMresults <- cmeans(df,centers=i,m=m)
totss[i] <- sum(sumsqr(df,FCMresults$cluster))
}
return(totss)
}
wss_2to20 <- iterate_fcm_WSS(scaledata,m1)
max <- as.numeric(input$maxclass)
elb <- plot(1:max, wss_2to20[1:max], type="b", xlab="Number of Clusters", ylab="WSS")
elb
})
output$overlap_plot <- renderPlot({
Ptmp<- overlap.plot(N_cl,over=ov, thres=as.numeric(input$ov_threshold))
Ptmp
})
output$mfuzz_plots <- renderPlot({
if(input$inertiaclass < 10){
mfrow <- c(4,3)
var$heightplot <- 1200
}else{
mfrow <- c(10,3)
var$heightplot <- 3600
}
fuzz <- mfuzz.plot(mfdata.s,cl=N_cl,mfrow = mfrow, time.labels = var$timepoints,new.window = F)
fuzz
})
output$mfuzzbutton <- renderUI({
actionButton(
"dlmfuzz",
"Download clusters lists"
)
})
output$mfuzzcorebutton <- renderUI({
actionButton(
"dlcoremfuzz",
"Download core clusters lists"
)
})
observeEvent(input$dlmfuzz,{
clusters_list<- acore(mfdata.s,N_cl, min.acore = 0)
for (i in 1:length(clusters_list)){
write.table(clusters_list[i],
file = paste0("~/Desktop/", paste("cluster", i, "txt", sep = ".")), sep = "\t", row.names = F)
}
})
observeEvent(input$dlcoremfuzz,{
core_clusters_list <- acore(mfdata.s, N_cl, min.acore = 0.7)
for (i in 1:length(core_clusters_list)){
write.table(core_clusters_list[i],
file = paste0("~/Desktop/", paste("core_cluster", i, "txt", sep = ".")), sep = "\t", row.names = F)
}
})
})
# if the user has chosen enrichitool == gProfileR
observeEvent(input$enrichmentTool, {
if (input$enrichmentTool == "gProfiler") {
output$clus_enrich <- renderUI({
box(
title = tagList(icon("cogs"),"Parameters"),
solidHeader = T,
status = "primary",
width = NULL,
sliderInput(
"whichclust",
"Cluster to enrich",
min = 1,
max = as.numeric(input$inertiaclass),
value = 1,
step = 1
),
sliderInput(
"topres",
"Top results to show",
min = 1,
max = 50,
value = 10,
step = 1
),
selectInput(
"mforg",
"Choose your Organism",
c("Drosophila melanogaster" = "dmelanogaster",
"Mus musculus" = "mmusculus",
"Homo sapiens" = "hsapiens",
"Caenorhabditis elegans" = "celegans",
"Zebrafish" = "drerio",
"Aspergillus fumigatus Af293" = "afumigatus",
"Bonobo" = "ppaniscus",
"Cat" = "fcatus",
"Chicken" = "ggallus",
"Chimpanzee" = "ptroglodytes",
"Common Carp" = "ccarpio",
"Cow" = "btaurus",
"Dog" = "clfamiliaris",
"Dolphin" = "ttruncatus",
"Goat" = "chircus",
"Gorilla" = "ggorilla",
"Guppy" = "preticulata",
"Horse" = "ecaballus",
"Pig" = "sscrofa",
"Platypus" = "oanatinus",
"Rabbit" = "ocuniculus")
),
checkboxGroupInput(
"mfEnrich",
"Choose your enrichment",
c("GO : Biological Processes" = "GO:BP",
"GO : Molecular Functions" = "GO:MF",
"GO : Cellular Components" = "GO:CC",
"KEGG Pathways" = "KEGG",
"Reactome" = "REAC",
"WikiPathways" = "WP",
"TRANSFAC" = "TF",
"MirTarBase" = "MIRNA",
"Human Phenotype Ontology" = "HP",
"Human Protein Atlas" = "HPA",
"CORUM" = "CORUM")
),
do.call(actionBttn, c( # run button
list(
inputId = "mfenrichmentgo",
label = "Enrich",
icon = icon("play")
)))
)
})
# Specific code for gProfiler
observeEvent(input$mfenrichmentgo,{
clusters_list<- acore(mfdata.s,N_cl, min.acore = 0)
geneset <-as.character(sapply(clusters_list[as.numeric(input$whichclust)],"[[", 1 )) # takes the gene set of the chosen cluster
enrichement <- unlist(strsplit(input$mfEnrich, split = '\n'))
res <- gost(geneset,
organism = input$mforg,
user_threshold = 0.05,
correction_method = "g_SCS",
domain_scope = "annotated",
sources = enrichement,
numeric_ns = "ENTREZGENE",
significant = T)
res_mf_enrich <- as.data.frame(res$result)# result as data frame
res_mf_enrich <- res_mf_enrich[,-1]
res_mf_enrich <- res_mf_enrich[order(res_mf_enrich[,2]),]
res_mf_enrich <- res_mf_enrich[1:as.numeric(input$topres),]
res_mf_enrich <- res_mf_enrich[,-1]
res_mf_enrich <- res_mf_enrich[,-2]
res_mf_enrich <- res_mf_enrich[,-2]
res_mf_enrich <- res_mf_enrich[,-2]
res_mf_enrich <- res_mf_enrich[,-2]
res_mf_enrich <- res_mf_enrich[,-2]
res_mf_enrich <- res_mf_enrich[,-5]
res_mf_enrich <- res_mf_enrich[,-5]
MFEnrichRun$MFEnrichRunValue <- input$mfenrichmentgo # precise the run button has been clicked
output$mf_enrichdt <- DT::renderDataTable({ # result table
data <- res_mf_enrich
colnames(data) <- c("P Value","Term_id", "Enrichment","Term_name", "Parents")
DT::datatable(
data,
extensions = 'Buttons', # download button
option = list(
paging = TRUE,
searching = TRUE,
fixedColumns = TRUE,
autoWidth = TRUE,
ordering = TRUE,
dom = 'Bfrtip',
buttons = list(list(
extend = 'collection',
buttons = list(extend='csv',
filename = "cluster_enrichment"),
text = 'Download')),
scrollX = TRUE,
pageLength = 10,
searchHighlight = TRUE, # search bar
orderClasses = TRUE
),
class = "display")
}, server = FALSE)
output$mf_manhattan <- renderPlotly({
output$mf_manhattan <- renderPlotly({
data <- res
fig <- gostplot(
data,
capped = T,
interactive = T
)
fig
})
output$mf_barplot <- renderPlotly({
data <- res_mf_enrich
fig <- plot_ly(
data,
x = ~(-log10(p_value)),
y = ~term_name,
type = "bar",
color = ~factor(source)
)
fig
})
})
}
# if the user has chosen enrichitool= EnrichR
else if (input$enrichmentTool == "EnrichR") {
# Specific code for EnrichR
output$clus_enrich <- renderUI({
box(
title = tagList(icon("cogs"),"Parameters"),
solidHeader = T,
status = "primary",
width = NULL,
sliderInput(
"whichclust",
"Cluster to enrich",
min = 1,
max = as.numeric(input$inertiaclass),
value = 1,
step = 1
),
sliderInput(
"topres",
"Top results to show",
min = 1,
max = 50,
value = 10,
step = 1
),
selectInput(
"mforg",
"Choose your Organism",
c("Drosophila melanogaster" = "dmelanogaster",
"Mus musculus" = "mmusculus",
"Homo sapiens" = "hsapiens",
"Caenorhabditis elegans" = "celegans",
"Zebrafish" = "drerio",
"Aspergillus fumigatus Af293" = "afumigatus",
"Bonobo" = "ppaniscus",
"Cat" = "fcatus",
"Chicken" = "ggallus",
"Chimpanzee" = "ptroglodytes",
"Common Carp" = "ccarpio",
"Cow" = "btaurus",
"Dog" = "clfamiliaris",
"Dolphin" = "ttruncatus",
"Goat" = "chircus",
"Gorilla" = "ggorilla",
"Guppy" = "preticulata",
"Horse" = "ecaballus",
"Pig" = "sscrofa",
"Platypus" = "oanatinus",
"Rabbit" = "ocuniculus")
),
checkboxGroupInput(
"mfEnrich",
"Choose your enrichment",
c("Biological Process" = "GO_Biological_Process_2018",
"Molecular Fonction" = "GO_Molecular_Function_2018",
"Cellular Component" = "GO_Cellular_Component_2018",
"Coexpression Predicted GO Biological Process 2018" = "Coexpression_Predicted_GO_Biological_Process_2018",
"GO Cellular Component 2018" = "GO_Cellular_Component_2018",
"GO Molecular Function 2018" = "GO_Molecular_Function_2018",
"GO Biological Process 2018" = "GO_Biological_Process_2018",
"GO Biological Process GeneRIF" = "GO_Biological_Process_GeneRIF",
"KEGG 2019" = "KEGG_2019",
"PPI Network Hubs from DroID 2017" = "PPI_Network_Hubs_from_DroID_2017",
"WikiPathways 2018" = "WikiPathways_2018")
),
do.call(actionBttn, c( # run button
list(
inputId = "mfenrichmentgo",
label = "Enrich",
icon = icon("play")
)))
)
})
MFEnrichRun$MFEnrichRunValue <- input$mfenrichmentgo # precise the run button has been clicked
observeEvent(input$mfenrichmentgo, {
clusters_list <- acore(mfdata.s, N_cl, min.acore = 0)
enrichement <- unlist(strsplit(input$mfEnrich, split = '\n'))
# Create a folder to save PNG files
dir.create("plots", showWarnings = FALSE)
results <- list()
for (i in 1:length(acore(mfdata.s, N_cl, min.acore = 0))) {
geneset <- as.character(sapply(clusters_list[i], "[[", 1))
for (en in enrichement) {
res <- enrichr(geneset, en)
res_df <- as.data.frame(res) # Conversion to data frame
res_df <- res_df[, -4]
res_df <- res_df[, -4]
res_df <- res_df[, -4]
colnames(res_df) <- c("Term", "Overlap", "P.value", "Odd.Ratio", "Combined.Score", "Genes")
res_df <- res_df[order(res_df[, 3]), ]
n <- as.numeric(input$topres)
res_df <- res_df[1:n, ]
# Add column with enrichment name
res_df$Enrichment <- en
results[[en]] <- res_df # Add result to results list
}
# Join all results with the rbind function
final_result <- do.call(rbind, results)
# PNG file name based on cluster number
filename <- paste0("plots/plot", i, ".png")
# Export results to CSV or TXT files per cluster
output_file <- paste0("clusterFC_", i, "_results.txt")
write.table(results[[i]], file = output_file, sep = "\t", row.names = FALSE)
output$mf_manhattan <- renderPlotly({
# Code for the plot specific to EnrichR
# Code for saving plots as PNG files
mf_manhattan_plot <- plot_ly(
final_result,
x = ~Term,
y = ~P.value,
type = "scatter",
mode = "markers",
marker = list(size = 10, color = ~final_result$Enrichment, colorscale = "Viridis", colorbar = list(title = "Enrichment"))
) %>% layout(
xaxis = list(title = "Term Name"),
yaxis = list(title = "-log10(Q-value)"),
hovermode = "closest"
)
mf_barplot <- plot_ly(
final_result,
x = ~(-log10(P.value)),
y = ~Term,
type = "bar",
color = "red" # ~Enrichment
) %>% layout(yaxis = list(categoryorder = "total ascending"))
plotly::export(mf_manhattan_plot, file = filename)
}
)
# Display results in the datatable
output$mf_enrichdt <- DT::renderDataTable({
data <- final_result
colnames(data) <- c("Term", "Overlap", "P.value", "Odd.Ratio", "Combined.Score", "Genes")
DT::datatable(
data,
extensions = 'Buttons',
option = list(
paging = TRUE,
searching = TRUE,
fixedColumns = TRUE,
autoWidth = TRUE,
ordering = TRUE,
dom = 'Bfrtip',
buttons = list(
list(
extend = 'collection',
buttons = list(
extend = 'csv',
filename = "cluster_enrichment"
),
text = 'Download'
)
),
scrollX = TRUE,
pageLength = 10,
searchHighlight = TRUE,
orderClasses = TRUE
),
class = "display"
)
}, server = FALSE)
}
}
)
})
})
}
})
})
output$inertia_elbowUI <- renderUI({
if (nrow(var$mfuzzTable) != 0){
tabsetPanel(
# render plots
tabPanel(title = "Inertia", plotlyOutput("inertia_plot") %>% withSpinner()),
tabPanel(title = "Elbow", plotOutput("elbow_plot") %>% withSpinner())
)}else{
helpText("input a count matrix first.")
}
})
output$overlap <- renderUI({
if (nrow(var$mfuzzTable) != 0){
tagList(
fluidRow(column(
12, plotOutput('overlap_plot',height = 700) %>% withSpinner()
)))} else {
helpText("input a count matrix first.")
}
})
output$mfuzz <- renderUI({
if (nrow(var$mfuzzTable) != 0){
tagList(
fluidRow(column(12, uiOutput("mfuzzbutton"),
uiOutput("mfuzzcorebutton"),
plotOutput('mfuzz_plots',height = var$heightplot) %>% withSpinner()
)))} else {
helpText("input a count matrix first.")
}
})
output$mf_enrich <- renderUI({
if(MFEnrichRun$MFEnrichRunValue){
tagList(
fluidRow(
column(12, plotlyOutput("mf_manhattan") %>% withSpinner()),
column(12, dataTableOutput("mf_enrichdt") %>% withSpinner())
)
)} else {
helpText("Compute Mfuzz plots before, and select your parameters")
}
})
output$mfenrichement <- renderUI({
navbarPage("Cluster Enrichment",
tabPanel(
title = tagList(icon("dice-one"), "Enrichment"),
width = NULL,
solidHeader = T,
status = "primary",
tagList(
fluidRow(
column(3, uiOutput("clus_enrich")),
column(9,uiOutput("mf_enrich") %>% withSpinner())
))),
tabPanel(title = tagList(icon("dice-two"), "Bar Plot"),
width = NULL,
solidHeader = T,
status = "primary",
plotlyOutput("mf_barplot"))
)
})