-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathserver.R
More file actions
2299 lines (1917 loc) · 98.6 KB
/
Copy pathserver.R
File metadata and controls
2299 lines (1917 loc) · 98.6 KB
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# BEAVR: A Browser-based tool for the Exploration And Visualization of RNA-seq data
# Developed by Pirunthan Perampalam @ https://github.com/developerpiru/
# See Github for documentation & ReadMe: https://github.com/developerpiru/BEAVR
app_version = "1.0.11"
# added:
# +1 to all reads; avoid 0 read count errors
# multiple comparisons
# show >2 conditions on PCA plot
# adjust results based on different conditions
# options for plots to show labels
# select either sample names or replicate names for labels
# boxplot or jitter plot option for read count plot
# use ggrepel for plot labels so labels don't overlap
# automatically install required packages if not already installed
# toggle for biocmanager packages
# fixed volcano plot
# ability to customize font sizes and point sizes for all graphs/plots
# ability to plot multiple read count plots at once
# customize legend positions on multiple read count plots
# drag to customize the area of all plots
# option to show y-axis title only on first plot per row
# option to show log10 scale y-axis
# dropped single read plot feature - use multi version with 1x1 grid for a single plot
# ability to pick human or mouse reference genomes to map ENSEMBL IDs
# ability to filter results table based on any/all columns
# ability to turn filtering on/off
# ability to download filtered results table
# volcano plot now shows filtered results if filtering is enabled
# updated UI colours and other aesthetics
# fixed legend positions for multi read count plots
# sample clustering plot (pearson correlation, euclidean, etc)
# count matrix heatmap to show most significant genes with highest variance between condition and treatment groups
# sample clustering heatmap colors
# fixed colors for all heatmaps
# specify distance and clustering type for count matrix heatmap
# fix variance transformations for small nsubs (small sample sets)
# volcano plot colors
# enter gene names for heatmap
# fixed color selection for boxplot and jitter plots
# calculate statistics in read count plots
# fixed statistics placements on read count plots
# updated count matrix heatmap function to use ComplexHeatmap
# fixed annoations for count matrix heatmap
# ability to customize colors of count matrix heatmap annotations
# full customization of count matrix heatmap now working
# improve dynamic colorbox rendering
# global num_conditions and num_replicates values added
# fixed heatmap annotation customizations and fonts
# div tags for all plot areas showing plot area boundary
# save all plots as png, jpg, svg, tiff or pdf
# select dpi setting for svg and pdf formats
# cleaned up ui
# pathway enrichment analysis using ReactomePA and enrichplot packages (overenrichment analysis and GSEA maps and plots)
# full customization of pathway and gsea plots/maps
# added results tables for pathway enrichment results and GSEA results
# added shiny.port option to use port 3838
# start info bar containing basic steps
# help tab for basic help/tips info
# fixed heatmap name bug
# removed default white border on sample clustering heatmap
# fixed bug where alert was not shown if filtering was not enabled when running enrichment functions; now requires library(shinyalert)
# fixed heatmap vst nsub bug: nsub now forced to nrow(dds table)
# heatmap variance stabilization defaulted to vst instead of rlog for better performance
# fixed colour widget ordering bug where widgets didn't match order of colour legend in PCA and read counts plots
# added ability to turn on/off labels for heatmap row and column names
# bugs"
#### PCA, gene count, volcano plots don't auto-update to new dds dataset after changing treatment condition factor level
#### legend symbols show letter 'a' below symbol on jitter plots
#increase max file size to 1000MB
#set port to 3838
options(shiny.maxRequestSize = 1000*1024^2, shiny.port = 3838)
shinyServer(function(input, output, session) {
#---BEGIN DATA INPUT---#
#reactive to get and store raw reads data
#upload read count file
cts <- reactive({
req(input$rawreadsfile)
#store in rawreadsdata variable
rawreadsdata <- read.csv(input$rawreadsfile$datapath,
header = TRUE,
sep = input$sep1)
rownames(rawreadsdata) <- rawreadsdata$gene_id
rawreadsdata <- rawreadsdata[,-1]
#increment all reads by 1 to avoid 0 read count errors
rawreadsdata <- rawreadsdata + 1
return(rawreadsdata)
})
#reactive to get and store coldata table
#upload column data file
coldata <- reactive({
req(input$coldatafile)
#store in coldata variable
coldata <- read.csv(input$coldatafile$datapath,
header = TRUE,
sep = input$sep2)
#reorder alphabetically by condition name
#coldata <- coldata[order("condition"),]
return(coldata)
})
#---END DATA INPUT---#
#---START DYNAMIC EXPERIMENT SETTINGS---#
#get control condition from list
output$control_condslist <- renderUI({
temp_coldata <- coldata()
temp_condslist <- unique(temp_coldata[,2])
selectInput("control_condslist", "Choose control condition", temp_condslist, selected = temp_condslist[1])
})
#get treatment condition from list
output$treatment1_condslist <- renderUI({
temp_coldata <- coldata()
temp_condslist <- unique(temp_coldata[,2])
selectInput("treatment1_condslist", "Choose treatment condition", temp_condslist, selected = temp_condslist[2])
})
#get false discovery rate from user
output$FDR_value <- renderUI({
numericInput("FDRvalue", "False Discovery Rate %",value = 10)
})
#get minimum read count values to keep from user
output$min_reads <- renderUI({
numericInput("min_reads_value", "Drop genes with reads below:",value = 10)
})
#function to dynamically update the dropdown box for detected GSEA pathways
output$gseaPlotPathways <- renderUI({
#gsea_plot_data[paste0(input$gseaPlotPathway), "Description"]
selectInput("gseaPlotPathways", "Detected pathways (from most to least significant)",
gsea_plot_data$Description,
selected = gsea_plot_data[1, "Description"])
})
#---END DYNAMIC EXPERIMENT SETTINGS---#
#DEBUG - function to check coldata against read count table column names
coldatacompare <- reactive({
#cts <- output$rawreadstable
#coldata <- output$coldatatable
temp_coldata <- coldata()
temp_cts <- cts()
#check1 <- all(rownames(temp_coldata) %in% colnames(temp_cts))
check1 <- all(rownames(temp_coldata) %in% colnames(temp_cts))
check2 <- all(rownames(temp_coldata) == colnames(temp_cts))
temp_cts <- temp_cts[, rownames(temp_coldata)]
check3 <- all(rownames(temp_coldata) == colnames(temp_cts))
return(check3)
})
#DEBUG - check coldata and read count tables for matching row\column names
output$coldatachecker <- renderText({
coldatacompare()
})
#---BEGIN CALCULATIONS---#
#create DESeq2 data set (dds)
calc_get_dds <- reactive({
#get values
temp_cts <- cts()
temp_coldata <<- coldata()
#get number of unique conditions
num_conditions <<- length(unique(temp_coldata[,2]))
num_replicates <<- length(unique(temp_coldata[,3]))
#prepare list of condition names
conds_names <<- levels(temp_coldata[,2])
#control condition selected by the user
control_factor <<- input$control_condslist
#the following are deprecated
# treatment1_factor <- input$treatment1_condslist
# treatment2_factor <- input$treatment2_condslist
# treatment3_factor <- input$treatment3_condslist
#construct a DESeqDataSet
dds <- DESeqDataSetFromMatrix(countData = temp_cts, colData = temp_coldata, design = ~ condition)
#dds
#pre-filter dds table to only keep genes that have at least input$min_reads_value reads set by user
keep <- rowSums(counts(dds)) > input$min_reads_value
dds <- dds[keep,]
#NEW METHOD - Setting the factor level
dds$condition <- relevel(dds$condition, ref = control_factor)
#Differential expression analysis
dds <- DESeq(dds)
#write.csv(as.data.frame(dds), file='dds-output.csv')
return(dds)
})
#calculate results from dds
#calculates LFC and FDR
calc_res <- reactive({
#set flag to FALSE for first run indicator -- used in multi gene count function
first_run_flag1 <<- TRUE
first_run_flag2 <<- TRUE
first_run_flag3 <<- TRUE
#Update progress bar
totalSteps = 8 + 3
currentStep = 1
incProgress(currentStep/totalSteps*100, detail = paste("Initializing..."))
control_factor <- input$control_condslist
treatment1_factor <- input$treatment1_condslist
#build LFC argument based define experimental conditions
LFC_coef <- paste("condition_", treatment1_factor, sep="")
LFC_coef <- paste(LFC_coef, control_factor, sep="_vs_")
FDR_aplha <- (input$FDRvalue)/100
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Performing DESeq2 calculations..."))
#calcate dds values
dds <<- calc_get_dds()
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Determing differential expression..."))
#new way to set multifactor comparisons - log2FC[final/initial]
res <<- results(dds, contrast=c("condition", treatment1_factor, control_factor))
#Log fold change shrinkage for visualization and ranking
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Performing LFC shrinkage..."))
#adjust conditions based on contrast
if (input$shrinkage_method == 1){
resLFC <<- lfcShrink(dds, coef=LFC_coef, type="apeglm")
} else {
resLFC <<- lfcShrink(dds, coef=LFC_coef, type="normal")
}
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Ordering by p values..."))
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Applying FDR correction..."))
#filter res based on FDR cut off (10% = alpha of 0.1)
resFDR <<- results(dds, alpha=FDR_aplha)
#summary(res10)
#sum(res10$padj < FDR_aplha, na.rm=TRUE)
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Mapping ENSEMBL names to readable gene symbols..."))
#map ensembl symbols to gene ids
#check which reference genome was selected by the user and translate ENSEMBL IDs using the correct one
if (input$ref_genome_organism == 1){
# 1 = human
res$GeneID <<- mapIds(org.Hs.eg.db,keys=rownames(res),column="SYMBOL",keytype="ENSEMBL",multiVals="first")
resFDR$GeneID <<- mapIds(org.Hs.eg.db,keys=rownames(resFDR),column="SYMBOL",keytype="ENSEMBL",multiVals="first")
} else if (input$ref_genome_organism == 2){
# 2 = mouse
res$GeneID <<- mapIds(org.Mm.eg.db,keys=rownames(res),column="SYMBOL",keytype="ENSEMBL",multiVals="first")
resFDR$GeneID <<- mapIds(org.Mm.eg.db,keys=rownames(resFDR),column="SYMBOL",keytype="ENSEMBL",multiVals="first")
}
#make a separate table of ensembl symbols and gene ids
#required for gene read counts plot function
#make a copy of res table
listofgenes <<- as.data.frame(res)
#keep only the GeneID column; drop everything else
listofgenes <<- subset(listofgenes, select = c(GeneID))
#save ENSEMBL IDs in new ENSEMBL column
listofgenes$ENSEMBL <<- rownames(listofgenes)
#write files
#write.csv(as.data.frame(resFDR), file='resFDR.csv')
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Preparing to display table..."))
resFDR <<- resFDR[,c(7,1:6)]
#update numericInputs for data filtering with the min/max values from resFDR
updateNumericInput(session, "log2FC_min", value = min(resFDR$log2FoldChange, na.rm=T))
updateNumericInput(session, "log2FC_max", value = max(resFDR$log2FoldChange, na.rm=T))
updateNumericInput(session, "pvalue_min", value = min(resFDR$pvalue, na.rm=T))
updateNumericInput(session, "pvalue_max", value = max(resFDR$pvalue, na.rm=T))
updateNumericInput(session, "padj_min", value = min(resFDR$padj, na.rm=T))
updateNumericInput(session, "padj_max", value = max(resFDR$padj, na.rm=T))
updateNumericInput(session, "baseMean_min", label = "Min", value = min(resFDR$baseMean, na.rm=T))
updateNumericInput(session, "baseMean_max", label = "Max", value = max(resFDR$baseMean, na.rm=T))
updateNumericInput(session, "lfcSE_min", label = "Min", value = min(resFDR$lfcSE, na.rm=T))
updateNumericInput(session, "lfcSE_max", label = "Max", value = max(resFDR$lfcSE, na.rm=T))
updateNumericInput(session, "stat_min", value = min(resFDR$stat, na.rm=T))
updateNumericInput(session, "stat_max", value = max(resFDR$stat, na.rm=T))
return(resFDR)
})
#---END CALCULATIONS---#
#output calculated dds + FDR table
#function to show table
output$calc_res_values <- DT::renderDataTable({
withProgress(message = 'Performing calculations...', value = 1, min = 1, max = 100, {
unfilteredTable <<- as.data.frame(calc_res())
#check if the Enable filtering checkbox is checked; if so, enable filtering as below
#save filtered table to filteredTable global variable
#if not, save the unfiltered table to filteredTable global variable
#that way, functions can be simplified and the same variable (filteredTable) can carry both table types
if (input$filterTableEnabled == TRUE){
filteredTable <<- subset(unfilteredTable,
baseMean >= input$baseMean_min &
baseMean <= input$baseMean_max &
log2FoldChange >= input$log2FC_min &
log2FoldChange <= input$log2FC_max &
lfcSE >= input$lfcSE_min &
lfcSE <= input$lfcSE_max &
stat >= input$stat_min &
stat <= input$stat_max &
pvalue >= input$pvalue_min &
pvalue <= input$pvalue_max &
padj >= input$padj_min &
padj <= input$padj_max
)
} else {
filteredTable <<- unfilteredTable
#reset all values to max values
#update numericInputs for data filtering with the min/max values from resFDR
updateNumericInput(session, "log2FC_min", value = min(filteredTable$log2FoldChange, na.rm=T))
updateNumericInput(session, "log2FC_max", value = max(filteredTable$log2FoldChange, na.rm=T))
updateNumericInput(session, "pvalue_min", value = min(filteredTable$pvalue, na.rm=T))
updateNumericInput(session, "pvalue_max", value = max(filteredTable$pvalue, na.rm=T))
updateNumericInput(session, "padj_min", value = min(filteredTable$padj, na.rm=T))
updateNumericInput(session, "padj_max", value = max(filteredTable$padj, na.rm=T))
updateNumericInput(session, "baseMean_min", label = "Min", value = min(filteredTable$baseMean, na.rm=T))
updateNumericInput(session, "baseMean_max", label = "Max", value = max(filteredTable$baseMean, na.rm=T))
updateNumericInput(session, "lfcSE_min", label = "Min", value = min(filteredTable$lfcSE, na.rm=T))
updateNumericInput(session, "lfcSE_max", label = "Max", value = max(filteredTable$lfcSE, na.rm=T))
updateNumericInput(session, "stat_min", value = min(filteredTable$stat, na.rm=T))
updateNumericInput(session, "stat_max", value = max(filteredTable$stat, na.rm=T))
}
#show table
filteredTable
})
})
#download DE gene table
output$downloadDEGeneTable <- downloadHandler(
filename = function() {
paste("Differentially Expressed Genes.csv")
},
content = function(file) {
#write to file
write.csv(as.data.frame(filteredTable), file, row.names = FALSE)
}
)
#call function to show PCA plot
output$PCA_plot = renderPlot({
withProgress(message = 'Generating PCA plot...', value = 1, min = 1, max = 100, {
do_PCA_plot()
})
})
#function to draw PCA plot
do_PCA_plot <- reactive({
#Update progress bar
totalSteps = 3 + 3
currentStep = 1
incProgress(currentStep/totalSteps*100, detail = paste("Initializing..."))
#transform data using variance stabilization method
vsd <<- varianceStabilizingTransformation(dds, blind = FALSE)
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Plotting..."))
#run only if first_run_flag2 boolean is TRUE; meaning ui is being initialized
if (first_run_flag2 == TRUE){
#call function to loop through and create more colour widgets for each condition in the experiment
#widget names are pcaColorX, where X is an integer
#selector is the target div tag container in ui
dynamic_colorgen(widget_name = "pcaColor", selector = "#pcaColorbox", sourcelist = "condition", heatmap = FALSE)
}
#set first run flag to false so color widgets are no longer made
first_run_flag2 <<- FALSE
#vector to save colours
multi_colorslist <- NULL
#loop through and get the colours that the user choses
for (count in 1:num_conditions){
multi_colorslist[count] <- input[[paste0('pcaColor', count)]]
}
#plot transformed data in PCA
pcaData <<- plotPCA(vsd, intgroup=c("condition", "replicate"), returnData=TRUE)
percentVar <- round(100 * attr(pcaData, "percentVar"))
#generate the plot
p <- ggplot(pcaData, aes(PC1, PC2, color=condition, shape=replicate)) +
geom_point(size = input$pcaPointSize) +
scale_color_manual(values = multi_colorslist) +
labs(shape="Replicate", color="Condition") +
xlab(paste0("PC1: ",percentVar[1],"% variance")) +
ylab(paste0("PC2: ",percentVar[2],"% variance")) +
theme_classic() +
theme(axis.text.x = element_text(color="black",size=input$pcaFontSize_xy_axis,angle=0,hjust=.5,vjust=.5,face="plain"),
axis.text.y = element_text(color="black",size=input$pcaFontSize_xy_axis,angle=0,hjust=1,vjust=0,face="plain"),
axis.title.x = element_text(color="black",size=input$pcaFontSize_xy_axis,angle=0,hjust=.5,vjust=.5,face="plain"),
axis.title.y = element_text(color="black",size=input$pcaFontSize_xy_axis,angle=90,hjust=.5,vjust=.5,face="plain"),
legend.title = element_text(color="black",size=input$pcaFontSize_legend_title,angle=0,hjust=.5,vjust=.5,face="plain"),
legend.text = element_text(color="black",size=input$pcaFontSize_legend_text,angle=0,hjust=.5,vjust=.5,face="plain"),
legend.text.align = 0,
text = element_text(size=input$pcaFontSize_x_axis))
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Finalizing..."))
#show labels for points as determined by user
if (input$PCAplot_labels == 1){
#no labels
p <- p
} else if (input$PCAplot_labels == 2){
#sample names as labels
p <- p + geom_text_repel(size=input$pcaLabelFontSize, nudge_x=0.1, nudge_y=0.1, segment.color=NA, aes(label=rownames(pcaData)))
aes(shape=rownames(d))
} else if (input$PCAplot_labels == 3){
#replicate names as labels
p <- p + geom_text_repel(size=input$pcaLabelFontSize, nudge_x=0.1, nudge_y=0.1, segment.color=NA, aes(label=replicate))
}
#return the plot
print(p)
})
#call function to show sample clustering plot
output$sampleClustering_plot = renderPlot({
withProgress(message = 'Generating sample clustering heatmap...', value = 1, min = 1, max = 100, {
do_sampleClustering_plot2()
})
})
#function to calculate sample clustering using ComplexHeatmap
do_sampleClustering_plot2 <- reactive({
#Update progress bar
totalSteps = 3 + 3
currentStep = 1
incProgress(currentStep/totalSteps*100, detail = paste("Initializing..."))
#get some user defined values
clust_dist = input$sampleClustering_method
if (input$sampleClustering_cellNums == FALSE){
display_cellVals = FALSE
} else if (input$sampleClustering_cellNums == "%.2f"){
display_cellVals = TRUE
cellVals_format = "%.2f"
} else if (input$sampleClustering_cellNums == "%.1e"){
display_cellVals = TRUE
cellVals_format = "%.1e"
}
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Calculating..."))
#transform data using variance stabilization method
vsd <<- varianceStabilizingTransformation(dds, blind = FALSE)
#transpose the data
sampleDists <- dist(t(assay(vsd)))
#generate heatmap for sample clustering
sampleDistMatrix <- as.matrix(sampleDists)
rownames(sampleDistMatrix) <- paste(vsd$condition, vsd$replicate, sep="-")
colnames(sampleDistMatrix) <- paste(vsd$condition, vsd$replicate, sep="-")
map_colors <- colorRampPalette( rev(brewer.pal(9, paste(input$sampleClustering_mapColor))) )(255)
#generate heatmap
p = Heatmap(sampleDistMatrix,
#name
name = " ",
#colour
col = map_colors,
#row distance method
clustering_distance_rows = input$sampleClustering_method,
#column distance method
clustering_distance_columns = input$sampleClustering_method,
#show row labels
show_row_names = input$sampleClusterin_rowlabels,
#show column labels
show_column_names = input$sampleClusterin_columnlabels,
#position of gene names
row_names_side = input$sampleClusterin_rowlabel_position,
#position of sample names
column_names_side = input$sampleClusterin_collabel_position,
#rotate row names
row_names_rot = input$sampleClusterin_row_rotation,
#rotate column names
column_names_rot = input$sampleClusterin_col_rotation,
#position of row dendrogam
row_dend_side = input$sampleClusterin_row_dend_position,
#position of column dendrogram
column_dend_side = input$sampleClusterin_col_dend_position,
#width of row dendrogram
row_dend_width = unit(input$sampleClusterin_row_dend_width, "cm"),
#height of column dendrogram
column_dend_height = unit(input$sampleClusterin_col_dend_height, "cm"),
#cell border settings
rect_gp = gpar(col = input$sampleClustering_borderColor, lwd = 1),
#size and color of row names
row_names_gp = gpar(fontsize = input$sampleClustering_fontsize_rowNames, col = input$sampleClustering_rowlabelColor),
#size and color of column names
column_names_gp = gpar(fontsize = input$sampleClustering_fontsize_colNames, col = input$sampleClustering_collabelColor),
#legend direction
heatmap_legend_param = list(direction = input$sampleClustering_main_legend_dir,
legend_height = unit(input$sampleClustering_main_legend_size, "cm"),
legend_width = unit(input$sampleClustering_main_legend_size, "cm"),
labels_gp = gpar(fontsize = input$sampleClustering_fontsize_legends, col = input$sampleClustering_legendColor)),
#show cell values
cell_fun = function(j, i, x, y, width, height, fill) {
if(input$sampleClustering_cellNums == "%.2f"){
grid.text(sprintf("%.1f", sampleDistMatrix[i, j]), x, y, gp = gpar(fontsize = input$sampleClustering_fontsize_cellNums, col = input$sampleClustering_cellNumsColor))
} else if (input$sampleClustering_cellNums == "%.1e"){
grid.text(sprintf("%.1e", sampleDistMatrix[i, j]), x, y, gp = gpar(fontsize = input$sampleClustering_fontsize_cellNums, col = input$sampleClustering_cellNumsColor))
}
}
)
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Finalizing..."))
#show the heatmap
draw(p, padding = unit(c(10, 10, 10, 10), "mm"),
merge_legend = TRUE,
heatmap_legend_side = input$sampleClustering_main_legend)
})
#call function to show count matrix heatmap
output$countMatrix_heatmap = renderPlot({
withProgress(message = 'Generating heatmap...', value = 1, min = 1, max = 100, {
do_countMatrix_heatmap2()
})
})
#new function to draw count matrix heatmap using ComplexHeatmap
do_countMatrix_heatmap2 <- reactive({
#Update progress bar
totalSteps = 3 + 3
currentStep = 1
incProgress(currentStep/totalSteps*100, detail = paste("Initializing..."))
#get some user defined values
#clust_dist = input$heatmap_distance
if (input$heatmap_cellNums == FALSE){
display_cellVals = FALSE
} else if (input$heatmap_cellNums == "%.2f"){
display_cellVals = TRUE
cellVals_format = "%.2f"
} else if (input$heatmap_cellNums == "%.1e"){
display_cellVals = TRUE
cellVals_format = "%.1e"
}
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Calculating..."))
#transform data using variance stabilization method
if (input$heatmap_varlogmethod == "vst")
transform_data <<- varianceStabilizingTransformation(dds, blind = FALSE)
else
transform_data <<- rlog(dds, blind=FALSE)
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Subsetting..."))
#get annotations for labels
annot <- as.data.frame(colData(dds)[,c("condition","replicate")])
if (input$heatmap_pickTopGenes == TRUE){
#get the top X genes as defined by user
#genestokeep <- order(rowMeans(counts(dds, normalized = TRUE)), decreasing = TRUE)[1:input$heatmap_numGenes]
genestokeep <- order(rowVars(assay(transform_data)), decreasing = TRUE)[1:input$heatmap_numGenes]
} else {
#get the list of genes entered by the user
genestomap_HGNC <<- unlist(strsplit(toupper(input$heatmap_GeneNames), ","))
#convert the user-entered gene symbols to ENSEMBL IDS
if (input$ref_genome_organism == 1){
# 1 = human
genestokeep <<- mapIds(org.Hs.eg.db,keys=genestomap_HGNC,column="ENSEMBL",keytype="SYMBOL",multiVals="first")
} else if (input$ref_genome_organism == 2){
# 2 = mouse
genestokeep <<- mapIds(org.Mm.eg.db,keys=genestomap_HGNC,column="ENSEMBL",keytype="SYMBOL",multiVals="first")
}
}
#subset the required genes from the transformed data
heatmap_data <- as.data.frame(assay(transform_data)[genestokeep,])
#get the gene names for the subsetted data
if (input$ref_genome_organism == 1){
# 1 = human
heatmap_data$GeneID <- mapIds(org.Hs.eg.db,keys=rownames(heatmap_data),column="SYMBOL",keytype="ENSEMBL",multiVals="first")
} else if (input$ref_genome_organism == 2){
# 2 = mouse
heatmap_data$GeneID <- mapIds(org.Mm.eg.db,keys=rownames(heatmap_data),column="SYMBOL",keytype="ENSEMBL",multiVals="first")
}
# #drop any rows that don't have HGNC symbols (have NA instead)
# heatmap_data <- na.omit(heatmap_data, cols = c("GeneID"))
#set flag to TRUE by default
show_geneNames = TRUE
#check which option is set for rownames in the heatmap by the user
if (input$heatmap_GeneNameType == "HGNC"){
#drop any rows that don't have HGNC symbols (have NA instead)
heatmap_data <- na.omit(heatmap_data, cols = c("GeneID"))
#set rownames to GeneID
rownames(heatmap_data) <- heatmap_data$GeneID
#if false, rownames are already set to ENSEMBL IDs so don't change anything
}
#drop GeneID column before sending to pheatmap, which must be numerical data
heatmap_data <- subset(heatmap_data, select = -c(GeneID))
#scale the data across all genes
heatmap_data2 = t(apply(heatmap_data, 1, function(x) {
scale(x)
}))
#set sample names (column names)
colnames(heatmap_data2) = colnames(heatmap_data)
#run only if first_run_flag3 boolean is TRUE; meaning ui is being initialized
if (first_run_flag3 == TRUE){
#call function to loop through and create more colour widgets for each replicate and condition in the experiment
#widget names are heatmap_replicateColorX and heatmap_conditionColorX, where X is an integer
#selector is the target div tag container in ui
dynamic_colorgen(widget_name = "heatmap_conditionColor", selector = "#heatmap_conditionColorbox", sourcelist = "condition", heatmap = TRUE)
dynamic_colorgen(widget_name = "heatmap_replicateColor", selector = "#heatmap_replicateColorbox", sourcelist = "replicate", heatmap = FALSE)
}
#set first run flag to false so color widgets are no longer made
first_run_flag3 <<- FALSE
#vector to save colours
replicate_colors = 0
condition_colors = 0
#loop through and get the colours that the user chooses for replicate annotations
for (count in 1:num_replicates){
replicate_colors[count] = input[[paste0('heatmap_replicateColor', count)]]
}
#loop through and get the colours that the user chooses for condition annotations
for (count in 1:num_conditions){
condition_colors[count] = input[[paste0('heatmap_conditionColor', count)]]
}
#set the names of colour vectors to replicate names or condition names, respectively
names(replicate_colors) = unique(temp_coldata[,3]) # column 3 is replicates
names(condition_colors) = unique(temp_coldata[,2]) # column 2 is conditions
if (input$heatmap_anno_legend_dir == "vertical")
anno_horizontal_flip = num_replicates
else if (input$heatmap_anno_legend_dir == "horizontal")
anno_horizontal_flip = 1
#define the replicate annotation
if (input$heatmap_annotations == "replicate"){
heatmap_anno = HeatmapAnnotation(Replicates = as.matrix(colData(dds)[,c("replicate")]),
col = list(Replicates = replicate_colors),
annotation_name_gp = gpar(fontsize = input$heatmap_fontsize_annotations),
annotation_legend_param = list(Replicates = list(nrow = anno_horizontal_flip,
title_gp = gpar(fontsize = input$heatmap_fontsize_legends, fontface = "bold"),
labels_gp = gpar(fontsize = input$heatmap_fontsize_legends))))
} else if (input$heatmap_annotations == "treatment") {
heatmap_anno = HeatmapAnnotation(Condition = as.matrix(colData(dds)[,c("condition")]),
col = list(Condition = condition_colors),
annotation_name_gp = gpar(fontsize = input$heatmap_fontsize_annotations),
annotation_legend_param = list(Condition = list(nrow = anno_horizontal_flip,
title_gp = gpar(fontsize = input$heatmap_fontsize_legends, fontface = "bold"),
labels_gp = gpar(fontsize = input$heatmap_fontsize_legends))))
} else if (input$heatmap_annotations == "both") {
heatmap_anno = HeatmapAnnotation(Replicates = as.matrix(colData(dds)[,c("replicate")]),
Condition = as.matrix(colData(dds)[,c("condition")]),
col = list(Replicates = replicate_colors, Condition = condition_colors),
annotation_name_gp = gpar(fontsize = input$heatmap_fontsize_annotations),
annotation_legend_param = list(Replicates = list(nrow = anno_horizontal_flip,
title_gp = gpar(fontsize = input$heatmap_fontsize_legends, fontface = "bold"),
labels_gp = gpar(fontsize = input$heatmap_fontsize_legends)),
Condition = list(nrow = anno_horizontal_flip,
title_gp = gpar(fontsize = input$heatmap_fontsize_legends, fontface = "bold"),
labels_gp = gpar(fontsize = input$heatmap_fontsize_legends))))
} else if (input$heatmap_annotations == "none") {
heatmap_anno = NULL
}
#generate heatmap
p = Heatmap(heatmap_data2,
#name
name = "Expression\n",
#sample annotation,
top_annotation = heatmap_anno,
#colour
col = colorRamp2(c(input$heatmap_scale_range[1], 0, input$heatmap_scale_range[2]), c(input$heatmap_lowColor, input$heatmap_midColor, input$heatmap_highColor)),
#cluster rows?
cluster_rows = input$heatmap_clustRows,
#cluster columns?
cluster_columns = input$heatmap_clustCols,
#row distance method
clustering_distance_rows = input$heatmap_distance,
#column distance method
clustering_distance_columns = input$heatmap_distance,
#row cluster method
clustering_method_rows = input$heatmap_clustMethod,
#column cluster method
clustering_method_columns = input$heatmap_clustMethod,
#position of gene names
row_names_side = input$heatmap_genelabel_position,
#show or hide gene (row) labels
show_row_names = input$heatmap_show_genelabels,
#show or hide sample (column) labels
show_column_names = input$heatmap_show_samplelabels,
#position of sample names
column_names_side = input$heatmap_samplelabel_position,
#rotate row names
row_names_rot = input$heatmap_row_rotation,
#rotate column names
column_names_rot = input$heatmap_col_rotation,
#position of row dendrogam
row_dend_side = input$heatmap_row_dend_position,
#position of column dendrogram
column_dend_side = input$heatmap_col_dend_position,
#width of row dendrogram
row_dend_width = unit(input$heatmap_row_dend_width, "cm"),
#height of column dendrogram
column_dend_height = unit(input$heatmap_col_dend_height, "cm"),
#cell border settings
rect_gp = gpar(col = input$heatmap_borderColor, lwd = 1),
#size and color of row names
row_names_gp = gpar(fontsize = input$heatmap_fontsize_geneNames, col = input$heatmap_rowlabelColor),
#size and color of column names
column_names_gp = gpar(fontsize = input$heatmap_fontsize_sampleNames, col = input$heatmap_collabelColor),
#legend direction, size, color
heatmap_legend_param = list(direction = input$heatmap_main_legend_dir,
title_gp = gpar(fontsize = input$heatmap_fontsize_legends, fontface = "bold"),
labels_gp = gpar(fontsize = input$heatmap_fontsize_legends,
col = input$heatmap_legendColor),
legend_height = unit(input$heatmap_main_legend_size, "cm"),
legend_width = unit(input$heatmap_main_legend_size, "cm")),
#show cell values
cell_fun = function(j, i, x, y, width, height, fill) {
if(input$heatmap_cellNums == "%.2f"){
grid.text(sprintf("%.1f", heatmap_data2[i, j]), x, y, gp = gpar(fontsize = input$heatmap_fontsize_cellNums, col = input$heatmap_cellNumsColor))
} else if (input$heatmap_cellNums == "%.1e"){
grid.text(sprintf("%.1e", heatmap_data2[i, j]), x, y, gp = gpar(fontsize = input$heatmap_fontsize_cellNums, col = input$heatmap_cellNumsColor))
}
}
)
# #Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Finalizing..."))
#show the heatmap
draw(p, padding = unit(c(10, 10, 10, 10), "mm"),
#merge_legend = TRUE,
heatmap_legend_side = input$heatmap_main_legend,
annotation_legend_side = input$heatmap_anno_legend)
})
#make volcano plot highlight genes that have an FDR cutoff and Log2FC cutoff as determined by the user (input$volcanopCutoff and input$volcanoFCcutoff)
output$volcanoPlot = renderPlot({
withProgress(message = 'Generating volcano plot...', value = 1, min = 1, max = 100, {
do_volcano_plot()
})
})
#function to plot gene counts for user defined genes
do_volcano_plot <- reactive({
#Update progress bar
totalSteps = 2 + 3
currentStep = 1
incProgress(currentStep/totalSteps*100, detail = paste("Initializing..."))
#get RNAseq data
#if filtering is enabled, use filtered data
if (input$filterTableEnabled == TRUE){
RNAseqdatatoplot <- as.data.frame(filteredTable)
} else {
#otherwise, use unfiltered data
RNAseqdatatoplot <- as.data.frame(unfilteredTable)
}
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Finalizing..."))
if (input$volcanoCutoffLines == TRUE){
p <- EnhancedVolcano(RNAseqdatatoplot,
title = paste(input$control_condslist, input$treatment1_condslist, sep = " vs. "),
subtitle = "",
lab = RNAseqdatatoplot$GeneID,
x = "log2FoldChange",
y = input$volcanopCutoffType,
pCutoff = as.numeric(input$volcanopCutoff),
FCcutoff = as.numeric(input$volcanoFCcutoff),
titleLabSize = input$volcanoFontSize_plot_title,
axisLabSize = input$volcanoFontSize_xy_axis,
pointSize = input$volcanoPointSize,
labSize = input$volcanoFontSize_label,
legendLabSize = input$volcanoFontSize_legend_title,
gridlines.major = FALSE,
gridlines.minor = FALSE,
legendPosition = input$volcanoLegendPosition,
legendLabels = c('Not Significant', expression(Log[2]~FC~only), "p-value only", expression(p-value~and~log[2]~FC)),
cutoffLineType = "longdash",
cutoffLineCol = 'black',
labCol = 'black',
col = c(input$volcano_NSColor, input$volcano_LFCColor, input$volcano_pvalColor, input$volcano_pvalLFCColor),
caption = ""
)
} else {
p <- EnhancedVolcano(RNAseqdatatoplot,
title = paste(input$control_condslist, input$treatment1_condslist, sep = " vs. "),
subtitle = "",
lab = RNAseqdatatoplot$GeneID,
x = "log2FoldChange",
y = input$volcanopCutoffType,
pCutoff = as.numeric(input$volcanopCutoff),
FCcutoff = as.numeric(input$volcanoFCcutoff),
titleLabSize = input$volcanoFontSize_plot_title,
axisLabSize = input$volcanoFontSize_xy_axis,
pointSize = input$volcanoPointSize,
labSize = input$volcanoFontSize_label,
legendLabSize = input$volcanoFontSize_legend_title,
gridlines.major = FALSE,
gridlines.minor = FALSE,
legendPosition = input$volcanoLegendPosition,
legendLabels = c('Not Significant', expression(Log[2]~FC~only), "p-value only", expression(p-value~and~log[2]~FC)),
cutoffLineType = "blank",
labCol = 'black',
col = c(input$volcano_NSColor, input$volcano_LFCColor, input$volcano_pvalColor, input$volcano_pvalLFCColor),
caption = ""
)
}
#return the plot
print(p)
})
#multi gene count plot
output$multi_genecount_plot1 = renderPlot({
withProgress(message = 'Generating read count plots...', value = 1, min = 1, max = 100, {
do_multi_genecount_plot()
})
})
#function to plot gene counts for user defined genes
do_multi_genecount_plot <- reactive({
#Update progress bar
totalSteps = 3
currentStep = 1
incProgress(currentStep/totalSteps*100, detail = paste("Initializing..."))
#get multi gene names from user input
#need to check which genome is selected and do upper case or lower case based on that
if (input$ref_genome_organism == 1){
# 1 = human
multi_gene_names <- unlist(strsplit(toupper(input$multi_gene_name), ","))
} else if (input$ref_genome_organism == 2) {
# 2 = mouse
multi_gene_names <- unlist(strsplit(input$multi_gene_name, ","))
}
#Update progress bar
currentStep = currentStep + 1
incProgress(currentStep/totalSteps*100, detail = paste("Plotting..."))
#run only if first_run_flag1 boolean is TRUE; meaning ui is being initialized
if (first_run_flag1 == TRUE){
#call function to loop through and create more colour widgets for each condition in the experiment
#widget names are pcaColorX, where X is an integer
#selector is the target div tag container in ui
dynamic_colorgen(widget_name = "multi_genecountColor", selector = "#multi_genecountColorbox", sourcelist = "condition", heatmap = FALSE)
}
#set first run flag to false so color widgets are no longer made
first_run_flag1 <<- FALSE
#vector to save colours
multi_colorslist <- NULL
#loop through and get the colours that the user choses
for (count in 1:num_conditions){
multi_colorslist[count] <- input[[paste0('multi_genecountColor', count)]]
}
#initialize variables to run through and generate all the gene count plots
p = list()
i = 0
#loop through and generate the plots for gene names entered
for (val in multi_gene_names){
i = i+1
#check which genome was selected
#if human is selected, make sure gene names are upper case
if (input$ref_genome_organism == 1){
# 1 = human
val = toupper(val)
}
#get read counts
d <<- plotCounts(dds, gene=listofgenes[which(listofgenes$GeneID==val),2], intgroup=c("condition", "replicate"), returnData=TRUE)
#change plot type to boxplot or jitter plot based on user selection
if (input$multi_readcountplot_type == 1){
#boxplot
p[[i]] <- ggboxplot(d, x = "condition", y = "count", fill = "condition", palette = multi_colorslist) +
ggtitle(val) +
xlab("") +