-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.R
More file actions
1511 lines (1350 loc) · 52.7 KB
/
Copy pathfunctions.R
File metadata and controls
1511 lines (1350 loc) · 52.7 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
##When the remove samples button is clicked in the normalized tab
#####Display interactive boxplot
boxplot_output<-function(edata,pData,col)
{
library(RColorBrewer)
n <- 60
qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',]
colors = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))
data<-edata
pheno<-pData
print(head(data))
# #order pheno data by condition
# pheno<-pheno[order(pheno[,2]),]
#Rename sample id with row just for display
i<-1:nrow(pheno)
print("pheno")
print(pheno)
#get which column u want to plot by
var<-as.numeric(col)
print(var)
print(as.vector(pheno[,1]))
# #set order of columns in expression data as same as order of sample ID in pheno data
data=data[,as.vector(pheno[,1])]#1
colnames(data)<- as.vector(pheno[,var])
print(var)
boxplot.matrix(as.matrix(data),outline=FALSE,xlab='Rows',ylab='Value',col=colors[pheno[,var]],boxwex=0.25,names=lapply(i,function(x) paste('row',x[1])))
legend("topright", legend = unique(pheno[,var]),xpd=TRUE, pch = 16, col = colors[unique(pheno[,var])], cex=0.85,inset=0.0005)
# print(head(melt(data)))
# ggplot(data=melt(data), aes(as.factor(Var2), value,fill=as.factor(Var2))) + geom_boxplot(outlier.shape = NA)+
# labs(x="Samples",y="Gene Counts")
}
pca_components<-function(dataset,column_no,annotation,resize_factor=NULL){
#obtain PC (principle components)
pca = prcomp(t(dataset),scale=F)
#signif rounds off the percentage calculated by 3 digits
pcaVars2=signif(((pca$sdev^2))/(sum((pca$sdev^2))),3)*100
signed = ifelse(max(pca$x[,2] > 70), 1, -1) # make same sign
signed1 = ifelse(max(pca$x[,3] > 70), 1, -1) # make same sign
total_variance = sum(pcaVars2[1:3])
c<-annotation[,column_no]
#print(c)
#print(typeof(c))
return(list(pca$x[,1],signed*pca$x[,2],signed1*pca$x[,3],pcaVars2[1],pcaVars2[2],pcaVars2[3],c))
#o/p returned is a list of (PC1,PC2,PC3,Percentage of variance contributed by PC1,
# Percentage of variance contributed by PC2,
# Percentage of variance contributed by PC3,
# annotation)
}
pcaplot<-function(data,annotation,top,plotType,resize_factor=NULL,point_size)
{
# Create a Progress object
progress <- shiny::Progress$new()
# Make sure it closes when we exit this reactive, even if there's an error
on.exit(progress$close())
progress$set(message = "Making plot", value = 0)
# Number of times we'll go through the loop to update progres bar
n1 <- 3
#========user input=======#
pheno<-data[[2]] #annotation table
dat<-data[[3]] #rlog transformed data
var<-as.numeric(annotation)#Get which column u want to plot by
#========================#
# print("input")
# print(head(pheno))
# print(head(dat))
#compute variance of all genes. this is done by taking the row variance (rowvars function) for each gene.
rv <- rowVars(dat)
#pick the top 500 most variable genes. This list will be used if user wants PCA of top 500 genes to be displayed
genes<-order(rv,decreasing=TRUE)[seq_len(min(500,length(rv)))]
# Increment the progress bar once input recieved, and update the detail text.
progress$inc(1/n1, detail = paste("Doing part", 1,"/",n1))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
#Get the components of PCA
parameters<-list()
if(top==2) parameters<-pca_components(dat,var,pheno)# pca components computed for all genes #input
else parameters<-pca_components(dat[genes,],var,pheno)#pca compnents of top 500 most variable genes
# print("line 84")
# print(parameters)
# Increment the progress bar after obtaining the components, and update the detail text.
progress$inc(1/n1, detail = paste("Doing part", 2,"/",n1))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
#Define color pallete. This is needed to color the sample points on the pca plot.
library(RColorBrewer)
n <- 60
qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',]
colors = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))
#Obtain the percentage of variance explained by each component
xlab = paste("PC1:",parameters[[4]],"%")
ylab = paste("PC2:",parameters[[5]],"%")
zlab = paste("PC3:",parameters[[6]],"%")
#condense the principle component vectors(PCA1,PCA2,PCA3) and colors assigned to each sample into a dataframe
#df is matrix with rows correspond to samples and columns (PCA1,PCA2,PCA3,Colors assigned to each sample)
df<-data.frame(PCA1=parameters[[1]],PCA2=parameters[[2]],PCA3=parameters[[3]],an=parameters[[7]])
print(colnames(pheno)[var])
print(dim(df))
print(length(colors[unique(df$an)]))
p<-plotly_empty() %>% layout(autosize = F,width=1000,height=800)
if(!is.null(resize_factor)) p<-plotly_empty() %>% layout(autosize = F,width=500,height=400)
#check if the color column of df is not empty
print("line 105 -functions")
p0<-NULL
if(length(colors[unique(df$an)])!=0)
{
print("hey")
if (identical(plotType, "2D")) { #variable plotType is input obtained from user: 2d/3d
print(colors[unique(df$an)])
p0 <- ggplot(df, aes(x = PCA1, y = PCA2, color=df$an)) +
geom_point(size=point_size)+
labs(x=xlab,y=ylab)+
scale_color_manual(name=colnames(pheno)[var],values=colors[unique(df$an)])+ theme_bw() #2d PCA plot
#req(p0)
if(!is.null(resize_factor)) p<-ggplotly(p0) %>% layout(autosize = F,dragmode ="select",width=500,height=400)
else p<-ggplotly(p0) %>% layout(autosize = F,width=1000,height=800,dragmode = "select")
} else {
#print()
if(!is.null(resize_factor))
{
p<- plot_ly(x=df$PCA1,y=df$PCA2,z=df$PCA3) %>% #3D PCA plot
add_markers(type = "scatter3d",color=df$an,colors = unique(colors[df$an])) %>%
layout(autosize = F,width=500,height=400,scene = list(xaxis = list(title = xlab),
yaxis = list(title = ylab),
zaxis = list(title = zlab)))
}
else
{
p<- plot_ly(x=df$PCA1,y=df$PCA2,z=df$PCA3) %>% #3D PCA plot
add_markers(type = "scatter3d",color=df$an,colors = unique(colors[df$an])) %>%
layout(autosize = F,width=1000,height=800,scene = list(xaxis = list(title = xlab),
yaxis = list(title = ylab),
zaxis = list(title = zlab)))
}
}
}
else
{
if(!is.null(resize_factor)) p<-plotly_empty() %>% layout(autosize = F,width=500,height=400)
else p<-plotly_empty() %>% layout(autosize = F,width=1000,height=800)
}
# Increment the progress bar when PCA plot has been successfully generated, and update the detail text.
progress$inc(1/n1, detail = paste("Doing part", 3,"/",n1))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
return(list(p,p0)) #return PCA plot
}
# The following function ensures each treatment/condition has a min of 3 samples
# else returns treatment/condition groups containing either one or two samples
min_samples_three <- function(dds.norm) {
print('Inside function min_samples_three')
dt1<-as.vector(sapply( levels(dds.norm$condition), function(lvl)
{
#Obtain number of samples present in each treatmen/conditiont group
num<-ncol(counts(dds.norm,normalized=TRUE)[,dds.norm$condition == lvl] )
if(is.null(num)) num<-1
num
}))
#dt1 is a dataframe with two columns namely treatment/condition group and number of samples in a treatment group
print(dt1)
#Which treatment/condition groups in dt1 have 2 samples (Obtain index)
two_samples<-which(dt1 %in% 2)
print('two')
#Which treatment/condition groups in dt1 has 1 sample (Obtain index)
one_sample<-which(dt1 %in% 1)
print('one sample')
#Get a list of all treatment/condition groups
conditions<-levels(dds.norm$condition)
#return only those treatment/condition groups having only one or two samples
if(length(one_sample)!=0) return (list(conditions[one_sample],1))#return treatment/condition groups containing only one sample
else if(length(two_samples)!=0) return (list(conditions[two_samples],2))#return treatment/condition groups containing only two samples
else if(length(one_sample)!=0 && length(two_samples)!=0) NULL #return null if there are no treatment/condition groups with neither one or two samples
}
#The following plots (density and ECDF plots) is used as a quality control for normalized data
#It is triggered by clicking the QC button in normalized table tab(represented as a sub tab under normalization tab)
#Plot 1: Density plot function: returns density plot
density_plot<-function(normal,x,y,zoom) #input(normalized table,x and y limits of plots if parameter zoom =True
# Zoom parameter is true when user wants to zoom in,this results in resizing the plot )
{
library(RColorBrewer)
n <- 60
qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',]
colors = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))
#print('ya')
library(geneplotter)
#To assess whether the normalization has worked,
#we plot the densities of counts for the different samples.
#Since most of the genes are (heavily) affected by the experimental conditions,
#a succesful normalization will lead to overlapping densities.
if(zoom==F) multidensity( normal,xlab="mean counts",xlim=c(0,1000),col=colors)
else multidensity( normal,xlab="mean counts",xlim=x,ylim=y,col=colors)
}
#plot 2: ECDF plot function
ECDF_plot<-function(normal)
{
library(RColorBrewer)
n <- 60
qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',]
colors = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))
#print('ya')
library(geneplotter)
#In an ECDF plot, the estimated probility is plotted on the y-axis and the count values
#on the x-axis. I.e. you can read of the median and other quantiles from this plot.
#As already mentioned, if the normalization has worked, the ECDFs of the different samples
#should be overlapping.
multiecdf(normal, normalized = T,xlab="Normalized gene counts", xlim = c(0,1000),col=colors)
}
#batch correction function
cleanY = function(y, mod, svs) {
X = cbind(mod, svs)
Hat = solve(t(X) %*% X) %*% t(X)
beta = (Hat %*% t(y))
rm(Hat)
gc()
P = ncol(mod)
return(y - t(as.matrix(X[,-c(1:P)]) %*% beta[-c(1:P),]))
}
heatmap_sample<-function(sampleDists,vsd)
{
library("RColorBrewer")
library("pheatmap")
# Create a Progress object
progress <- shiny::Progress$new()
# Make sure it closes when we exit this reactive, even if there's an error
on.exit(progress$close())
progress$set(message = "Making plot", value = 0)
# Number of times we'll go through the loop
n <- 3
# Increment the progress bar, and update the detail text.
progress$inc(1/n, detail = paste("Doing part", 1,"/",n))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
sampleDistMatrix <- as.matrix(sampleDists)
rownames(sampleDistMatrix) <- paste(vsd$condition, sep="-")
colnames(sampleDistMatrix) <- paste(paste(vsd$condition, sep="-"),"(",colnames(vsd),")",sep=" ")#NULL
colors <- colorRampPalette( rev(brewer.pal(9, "Blues")) )(255)
# Increment the progress bar, and update the detail text.
progress$inc(1/n, detail = paste("Doing part", 2,"/",n))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
p<- pheatmap(sampleDistMatrix,
clustering_distance_rows=sampleDists,
clustering_distance_cols=sampleDists,
col=colors)
# Increment the progress bar, and update the detail text.
progress$inc(1/n, detail = paste("Doing part", 3,"/",n))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
p
}
#ma plot
ma_plot<-function(ma_choice,combination,DE_genes,scale,p_values)
{
if(!is.null(ma_choice))
{
# Create a Progress object
progress <- shiny::Progress$new()
# Make sure it closes when we exit this reactive, even if there's an error
on.exit(progress$close())
progress$set(message = "Processing Data", value = 0)
num<- length(combination)
#Get the deseq2 dataset
#dds.fc<-batch_design()[[1]]
res<-DE_genes[[as.numeric(ma_choice)]][5] [[1]]
print(head(res))
# Increment the progress bar, and update the detail text.
progress$inc(1/3, detail = paste("Doing part", 1,"/",3))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
#filter most significant genes with fdr cut off 0.05
resSig <- subset(res, padj < p_values[[as.numeric(ma_choice)]])# & abs(res$log2FoldChange)>1)
print(head(resSig))
print("hey")
#get down regulated genes
head(resSig[ order(resSig$log2FoldChange), ])
d<-resSig[resSig$log2FoldChange<1,]
topGene_down<-rownames(head(d[order(d$log2FoldChange),],2))
print(topGene_down)
#get up regulated genes
head(resSig[ order(resSig$log2FoldChange,decreasing = TRUE), ])
u<-resSig[resSig$log2FoldChange>1,]
topGene_up<-rownames(head(u[order(u$log2FoldChange,decreasing = TRUE),],2))
print(topGene_up)
#top variable genes
#plotMA(res, ylim=c(-10,10),xlim=c(0.01,100))
topGene <- rownames(resSig)[which.min(resSig$padj)]# only most significant gene
#topGene<-rownames(res)[which(res$padj<0.05)]#all top DEG between conditions in contrast
# Increment the progress bar, and update the detail text.
progress$inc(1/3, detail = paste("Doing part", 2,"/",3))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
print('hey')
print(scale)
print('ok')
plotMA(res,ylim=c(-1*scale,scale))
# with(res[topGene, ], {
# points(baseMean, log2FoldChange, col="green", cex=2, lwd=2)
# text(baseMean, log2FoldChange, topGene, pos=2, col="green")
# })
# #display both up and down regulated genes
# with(res[topGene_down, ], {
# points(baseMean, log2FoldChange, col="dodgerblue", cex=2, lwd=2)
# text(baseMean, log2FoldChange, topGene_down, pos=2, col="dodgerblue")
# })
# with(res[topGene_up, ], {
# points(baseMean, log2FoldChange, col="hot pink", cex=2, lwd=2)
# text(baseMean, log2FoldChange, topGene_up, pos=2, col="hot pink")
# })
# Increment the progress bar, and update the detail text.
progress$inc(1/3, detail = paste("Doing part", 3,"/",3))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
}
}
#volcano plot
volcano_plot<-function(vol_choice,combination,DE_genes,scale_volx,scale_voly,p_values,hypothesis_choice)
{
# Create a Progress object
progress <- shiny::Progress$new()
# Make sure it closes when we exit this reactive, even if there's an error
on.exit(progress$close())
num<- length(combination)
#Get the deseq2 dataset
res<-DE_genes[[as.numeric(vol_choice)]][5] [[1]]
print(head(res))
progress$set(message = "Processing Data", value = 0)
padj_cutoff<-p_values[[as.numeric(vol_choice)]]
logfc_cutoff<-0
if(hypothesis_choice[[as.numeric(vol_choice)]]!=1)
{
logfc_cutoff<-log2(input[[paste0("FC_cutoff",as.numeric(vol_choice))]])
}
gene_list<-as.data.frame(res[c("log2FoldChange", "padj")])
##Highlight genes that have an absolute fold change > 2 and a p-value < Bonferroni cut-off
gene_list$group = as.factor(abs(gene_list$log2FoldChange) > logfc_cutoff & gene_list$padj < padj_cutoff)
#gene_list<-complete.cases(gene_list)
print(head(gene_list))
# Increment the progress bar, and update the detail text.
progress$inc(1/3, detail = paste("Doing part", 1,"/",3))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
# # Find and label the top peaks..
gene_list_complete<-na.omit(gene_list)
top_peaks <- gene_list_complete[with(gene_list_complete, order(log2FoldChange,padj)),][1:10,]
top_peaks <- rbind(top_peaks, gene_list_complete[with(gene_list_complete, order(-log2FoldChange,padj)),][1:10,])
# Add gene labels for all of the top genes we found
# here we are creating an empty list, and filling it with entries for each row in the dataframe
# each list entry is another list with named items that will be used by Plot.ly
print(top_peaks)
a <- list()
for (i in seq_len(nrow(top_peaks))) {
m <- top_peaks[i, ]
a[[i]] <- list(
x = m[["log2FoldChange"]],
y = -log10(m[["padj"]]),
text = rownames(m),
showarrow = TRUE,
arrowhead = 0.5,
ax = 20,
ay = -40
)
}
print("a")
print(a)
print(nrow(subset(na.omit(gene_list),group=="FALSE")))
print(nrow(subset(na.omit(gene_list),group=="TRUE")))
# Increment the progress bar, and update the detail text.
progress$inc(1/3, detail = paste("Doing part", 2,"/",3))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
##Construct the plot object
g = ggplot(data=na.omit(gene_list), aes(x=log2FoldChange, y=-log10(padj)) )+
geom_point(aes(col=group,text=sprintf("Gene name: %s<br>p-value: %s", rownames(na.omit(gene_list)),padj)))+#alpha=0.4, size=1.75) +
#geom_point(aes(col = factor(Significant))) +
#scale_color_manual(values=c("black", "red")) +
xlim(c(-1*scale_volx,scale_volx)) +
ylim(c(0,scale_voly)) +
#scale_y_continuous(trans = "log1p")+
xlab("log2 fold change") + ylab("-log10 p-value")+ labs(color = "Significant")+ theme_bw(base_size = 15)#+
# geom_text_repel(
# data = top_peaks,#subset(na.omit(gene_list),abs(log2FoldChange) > logfc_cutoff & padj < padj_cutoff),
# mapping=aes(label =rownames(top_peaks)),
# box.padding = unit(0.5, "lines"),
# point.padding = unit(0.5, "lines"),
# arrow = arrow(length = unit(0.01, 'npc')))
# #g
g1<-g+geom_text_repel(
data = top_peaks,#subset(na.omit(gene_list),abs(log2FoldChange) > logfc_cutoff & padj < padj_cutoff),
aes(label =rownames(top_peaks)),
box.padding = unit(0.25, "lines"),
point.padding = unit(0.1, "lines"),
arrow = arrow(length = unit(0.01, 'npc')))
# Increment the progress bar, and update the detail text.
progress$inc(1/3, detail = paste("Doing part", 3,"/",3))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
g0<-ggplotly(g)%>%layout(annotations = a)
return(list(g1,g0))
#g
}
get_pheno<-function(data,pheno)
{
#Expression table and annotation table should not be null
if(!is.null(data) && !is.null(pheno))
{
#Assuming that the first column of annotation table is sample id ,extract all sample IDs
sample_id = pheno[,1]
#print(sample_id)
#Get all sample IDs from expression table(sample ID refer to column names of expression table)
exp_sample_id = colnames(data)
#print('all')
# print(exp_sample_id)
#Check if all sample ID in expression table are present in the annotation table
if (all(exp_sample_id %in% sample_id))
{
#print("Yay")
#set all variables of annotation table as factors
col<-1:ncol(pheno)
for (i in col)
{
pheno[,i]<-as.factor(pheno[,i])
}
#Remove those sample IDs that are present in the expression table but absent in the annotation table from the annotation table
idx<-NULL
if(!all(sample_id %in% exp_sample_id))
{
idx<-which(!(sample_id %in% exp_sample_id))
pheno <- pheno[-idx, ]
}
pheno<-pheno
}
else
{
pheno<-NULL
#print('nay')
}
return(pheno)
}
}
#Enrichment function(returns object of enrichment function called)
#if Kegg anallysis is performed the enrichKegg function is called and its o/p is returned
enrichment_function<-function(enrichment_type,enrichment_input)
{
obj<-NULL
if(enrichment_type=="kegg")
{
obj<-enrichKEGG(gene = enrichment_input[[1]],
organism = enrichment_input[[2]],
pvalueCutoff = 1)
}
else if(enrichment_type=="biological process")
{
obj<-enrichGO(gene = enrichment_input[[1]],
universe = enrichment_input[[2]],
OrgDb = enrichment_input[[3]],
ont = "BP",
pAdjustMethod = "BH",
pvalueCutoff = 1,
qvalueCutoff = 1,
readable = TRUE)
}
else if(enrichment_type=="hallmark")
{
obj<-enricher(enrichment_input[[1]],
TERM2GENE = enrichment_input[[2]],#c1_hallmark,
universe = enrichment_input[[3]],
pvalueCutoff = 1,
#pAdjustMethod = "none",
qvalueCutoff = 1)
}
}
#enrichment (result=DE_genes(),
#organism=input$organism,
#dds.fc=batch_design()[[1]]
#num<- length(input$combination),
#wgcna_modules<-wgcna_output()$modules)
# WGCNA_matrix<-wgcna()[[2]]
# mod<- heat_wgcna()[[1]]
enrichment_main<-function(enrichment_type,result,input_organism,dds.fc,num,mod,WGCNA_matrix,c1_hallmark)
{
# Create a Progress object
progress <- shiny::Progress$new()
# Make sure it closes when we exit this reactive, even if there's an error
on.exit(progress$close())
progress$set(message = "Processing data", value = 0)
#get all de genes
#result
org<-NULL
organism<-NULL
universe<-NULL
All_genes<-NULL
#get the organism
if(as.numeric(input_organism)==1)
{
org<-org.Hs.eg.db
if(enrichment_type=="kegg") organism<-'hsa'
else
{
All_genes=AnnotationDbi::select(org,rownames(assay(dds.fc)),"ENTREZID","SYMBOL",multiVals='first')
}
}
else if (as.numeric(input_organism)==2)
{
org<-org.Mm.eg.db
if(enrichment_type=="kegg") organism<-'mmu'
else if (enrichment_type=="hallmark")
{
human = useMart(host = "jul2015.archive.ensembl.org",#"ensembl",
biomart = "ENSEMBL_MART_ENSEMBL",
dataset = "hsapiens_gene_ensembl")
mouse = useMart(host = "jul2015.archive.ensembl.org",#"ensembl",
biomart = "ENSEMBL_MART_ENSEMBL",
dataset = "mmusculus_gene_ensembl")
All_genes=rownames(assay(dds.fc))
genes_backgroud = getLDS(attributes = c("mgi_symbol"), filters = "mgi_symbol", values = as.character(All_genes), mart = mouse, attributesL = c("hgnc_symbol"), martL = human, uniqueRows=T)
print(head(genes_backgroud))
universe_genes <- genes_backgroud[,2]
entrez_background = bitr(universe_genes, fromType="SYMBOL", toType="ENTREZID", OrgDb="org.Hs.eg.db")
idx_all <- match(universe_genes, entrez_background$SYMBOL)
universe<- entrez_background[idx_all,]$ENTREZID
}
else if (enrichment_type=="biological process")
{
All_genes=AnnotationDbi::select(org,rownames(assay(dds.fc)),"ENTREZID","SYMBOL",multiVals='first')
}
}
#All genes
#dds.fc
#All_genes=rownames(assay(dds.fc))
#all de comparisons
#num <- length(combination())
n<-num*2
Enriched_list<-list()
Enriched_obj<-list()
Enriched_Kegg_gene<-list()#needed to display user selecetd kegg batch way.(contains a list of genes
#pertaining to the selected pathway and the corresponding foldchange values)
k<-0
#if wgcna is performed then we perform enrichment analysis on the
if(length(mod)>0)
{
modules<-as.data.frame(table(mod))
n<-n+nrow(modules)
}
#print(head(result))
for(i in 1:num) # looping through all DE comparisons
{
e_list<-list()
e_obj<-list()
kegg_genelist<-list() #used only for kegg
for(j in 1:2) #two loops. First loop for up regulated de genes in a comparison
{ #Second loop for down regulated de genes in a comparison
k<-k+1
print("k")
print(num)
print(i)
res<-as.data.frame(result[[i]][j]) #get up/down regulated de genes for a comparison
print(nrow(res))
if(nrow(res)!=0)
{
genes<-res[,1]
df<-res[,-1]
rownames(df)<-genes
print(head(df))
entrez_id<-NULL
gene_symbol<-NULL
obj<-NULL
geneList<-NULL #only popuated when kegg is computed
if((enrichment_type=="hallmark") && (as.numeric(input_organism)==2))
{
genes_de = getLDS(attributes = c("mgi_symbol"), filters = "mgi_symbol", values = as.character(rownames(df)), mart = mouse, attributesL = c("hgnc_symbol"), martL = human, uniqueRows=T)
reg = bitr(genes_de[,2], fromType="SYMBOL", toType="ENTREZID", OrgDb="org.Hs.eg.db")
idx <- match(genes_de[,2], reg$SYMBOL)
entrez<-reg[idx,]$ENTREZID
#gene_symbol<-reg[idx,]$SYMBOL
gene_symbol<-reg$SYMBOL[idx]
entrez_id<-entrez[!is.na(entrez)]
}
else
{
#convert de gene names to entrez id(input format required to perform enrichment analysis)
reg=AnnotationDbi::select(org,rownames(df),"ENTREZID","SYMBOL",multiVals="first")
idx <- match(rownames(df), reg$SYMBOL)
df$entrez<-reg[idx,]$ENTREZID
#gene_symbol<-reg[idx,]$SYMBOL
gene_symbol<-reg$SYMBOL[idx]
#print(gene_symbol)
entrez_id<-df$entrez[!is.na(df$entrez)]
}
if(enrichment_type=="kegg")
{
input<-list(entrez_id,organism)
obj<-enrichment_function("kegg",input)
#compute gene list for kegg
temp<-data.frame(entrez=c(reg[idx,]$ENTREZID),foldchange=c(df[idx,]$log2FoldChange))
#temp<-temp[!is.na(temp)]
#temp<-complete.cases(temp)
temp<-temp[complete.cases(temp), ]
#print(temp)
geneList<-temp$foldchange
#names(geneList)<-temp[,1]
names(geneList)<-temp$entrez
}
else if(enrichment_type=="hallmark")
{
input<-list(entrez_id,c1_hallmark,universe)
obj<-enrichment_function("hallmark",input)
}
else if(enrichment_type=="biological process")
{
input<-list(entrez_id,All_genes$ENTREZID,org)
obj<-enrichment_function("biological process",input)
}
#print(head(summary(kk)))
print('obj')
#print(obj)
print('summary')
#print(summary(obj))
print(nrow(as.data.frame(summary(obj))))
df_obj<-NULL
if(!is.null(obj))
{
if(nrow(as.data.frame(summary(obj)))>0)
{
df_obj<-as.data.frame(summary(obj))[1:8]
if(enrichment_type!="biological process")
{
df_obj<-as.data.frame(summary(obj))[1:8]
print('df_obj')
#print(df_obj)
for(x in 1:length(df_obj[,8]))
{
print('kegg_sum')
#print(typeof(x))
#print(df_obj[x,8])
temp<-strsplit(df_obj[x,8],"/")
#print(temp)
print('temp1')
#print(temp[[1]])
id<-which(entrez_id %in% temp[[1]] )
#print(id)
#print(gene_symbol)
#print(paste(reg$SYMBOL[id], collapse = '/'))
df_obj[x,8]<-paste(gene_symbol[id], collapse = '/')
#print(sapply(reg$SYMBOL[id],function(y) paste(y,'/')))
}
}
e_list[[length(e_list)+1]]<-df_obj
e_obj[[length(e_obj)+1]]<-obj
kegg_genelist[[length(kegg_genelist)+1]]<-geneList
}
else
{
e_list[[length(e_list)+1]]<-data.frame(matrix(NA, nrow = 0, ncol = 8))
e_obj[[length(e_obj)+1]]<-NULL
kegg_genelist[[length(kegg_genelist)+1]]<-NULL
}
}
else
{
e_list[[length(e_list)+1]]<-data.frame(matrix(NA, nrow = 0, ncol = 8))
e_obj[[length(e_obj)+1]]<-NULL
kegg_genelist[[length(kegg_genelist)+1]]<-NULL
}
}
else
{
e_list[[length(e_list)+1]]<-data.frame(matrix(NA, nrow = 0, ncol = 8))
e_obj[[length(e_obj)+1]]<-NULL
kegg_genelist[[length(kegg_genelist)+1]]<-NULL
}
# Increment the progress bar, and update the detail text.
progress$inc(1/n, detail = paste("Doing part", k,"/",n))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
}
e_list[[length(e_list)+1]]<-data.frame(matrix(NA, nrow = 0, ncol = 8))
e_obj[[length(e_obj)+1]]<-NULL
kegg_genelist[[length(kegg_genelist)+1]]<-NULL
#print(head(kegg))
Enriched_list[[i]]<-e_list
Enriched_obj[[i]]<-e_obj
Enriched_Kegg_gene[[i]]<-kegg_genelist
}
if(length(mod)>0)
{
modules<-as.data.frame(table(mod))
colnames(modules)<-c("Var1","number")
#mod
#WGCNA_matrix
for(i in 1:nrow(modules))
{
#print(nrow(as.data.frame(result[[i]][1])))
print('freq')
print(modules$Freq[i])
print(modules$Var1[i])
idx_w<-which(mod==modules$Var1[i])
print(head(idx_w))
DEG<-colnames(WGCNA_matrix)[idx_w]
print(head(as.data.frame(DEG)))
e_list<-list()
e_obj<-list()
k<-k+1
print("k")
if(!identical(character(0),DEG))
{
entrez_id<-NULL
gene_symbol<-NULL
obj<-NULL
if((enrichment_type=="hallmark") && (as.numeric(input_organism)==2))
{
genes_de = getLDS(attributes = c("mgi_symbol"), filters = "mgi_symbol", values = as.character(DEG), mart = mouse, attributesL = c("hgnc_symbol"), martL = human, uniqueRows=T)
reg = bitr(genes_de[,2], fromType="SYMBOL", toType="ENTREZID", OrgDb="org.Hs.eg.db")
idx <- match(genes_de[,2],reg$SYMBOL)
entrez<-reg[idx,]$ENTREZID
gene_symbol<-reg$SYMBOL[idx]
entrez_id<-entrez[!is.na(entrez)]
}
else
{
#convert de gene names to entrez id(input format required to perform enrichment analysis)
#get entrez id of genes
reg=AnnotationDbi::select(org,DEG,"ENTREZID","SYMBOL",multiVals="first")
idx <- match(DEG,reg$SYMBOL) #match gene name to entrez id
entrez<-reg[idx,]$ENTREZID
gene_symbol<-reg$SYMBOL[idx]
print(head(gene_symbol))
print('entrez')
print(entrez)
entrez_id<-entrez[!is.na(entrez)]
}
if(enrichment_type=="kegg")
{
input<-list(entrez_id,organism)
obj<-enrichment_function("kegg",input)
}
else if(enrichment_type=="hallmark")
{
input<-list(entrez_id,c1_hallmark,universe)
obj<-enrichment_function("hallmark",input)
}
else if(enrichment_type=="biological process")
{
input<-list(entrez_id,All_genes$ENTREZID,org)
obj<-enrichment_function("biological process",input)
}
print('obj')
print(obj)
print('summary')
print(summary(obj))
print(nrow(summary(obj)))
print(head(as.data.frame(summary(obj))[,8]))
#print(nrow(as.data.frame(summary(kk))[,8]))
if(!is.null(obj))
{
if(nrow(as.data.frame(summary(obj)))>0)
{
df_obj<-as.data.frame(summary(obj))[1:8]
print('df_obj')
print(df_obj)
if(enrichment_type!="biological process")
{
for(x in 1:length(df_obj[,8]))
{
print('kegg_sum')
#print(typeof(x))
print(df_obj[x,8])
temp<-strsplit(df_obj[x,8],"/")
#print(temp)
print('temp1')
#print(temp[[1]])
print(gene_symbol)
id<-which(entrez_id %in% temp[[1]] ) #get entrez id of genes in a pathway
#print(id)
print(paste(gene_symbol[id], collapse = '/'))
df_obj[x,8]<-paste(gene_symbol[id], collapse = '/')#convert entrez id to genes
#print(sapply(reg$SYMBOL[id],function(y) paste(y,'/')))
}
}
d<-data.frame(matrix(NA, nrow = 0, ncol = 8))
Enriched_list[[length(Enriched_list)+1]]<-list(d,d,df_obj)
Enriched_obj[[length(Enriched_obj)+1]]<-list(NULL,NULL,obj)
Enriched_Kegg_gene[[length(Enriched_Kegg_gene)+1]]<-list(NULL,NULL,NULL)
}
else
{
d<-data.frame(matrix(NA, nrow = 0, ncol = 8))
Enriched_list[[length(Enriched_list)+1]]<-list(d,d,d)
Enriched_obj[[length(Enriched_obj)+1]]<-list(NULL,NULL,NULL)
Enriched_Kegg_gene[[length(Enriched_Kegg_gene)+1]]<-list(NULL,NULL,NULL)
}
}
else
{
d<-data.frame(matrix(NA, nrow = 0, ncol = 8))
Enriched_list[[length(Enriched_list)+1]]<-list(d,d,d)
Enriched_obj[[length(Enriched_obj)+1]]<-list(NULL,NULL,NULL)
Enriched_Kegg_gene[[length(Enriched_Kegg_gene)+1]]<-list(NULL,NULL,NULL)
}
}
else
{
d<-data.frame(matrix(NA, nrow = 0, ncol = 8))
Enriched_list[[length(Enriched_list)+1]]<-list(d,d,d)
Enriched_obj[[length(Enriched_obj)+1]]<-list(NULL,NULL,NULL)
Enriched_Kegg_gene[[length(Enriched_Kegg_gene)+1]]<-list(NULL,NULL,NULL)
}
# Increment the progress bar, and update the detail text.
progress$inc(1/n, detail = paste("Doing part", k,"/",n))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
}
}
return(list(Enriched_list,Enriched_obj,Enriched_Kegg_gene))
}
#Display barplot of top 10 kegg pathway identified for selected comparison
#result<-Enriched_Kegg()[[2]] #obj
# res<-Enriched_Kegg()[[1]]
#input$category
#input$plot_k
#enrichment input
#category_go
#input$plotType_bp (plot_type)
#input$category_bp category
enrichment_plot<-function(enrichment_type,result,res,row,col,category,category_go){
# Create a Progress object
progress <- shiny::Progress$new()
# Make sure it closes when we exit this reactive, even if there's an error
on.exit(progress$close())
progress$set(message = "Making plot", value = 0)
# Number of times we'll go through the loop
n <- 2
# Increment the progress bar, and update the detail text.
progress$inc(1/n, detail = paste("Doing part", 1,"/",n))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
#up regulated column
up<-unique(nrow(res[[row]][[1]]))
print('up')
print(up)
#down regulated column
down<-unique(nrow(res[[row]][[2]]))
#which column is null
col_idx<-NULL
if(length(up)==1 && up==0) col_idx<- 1
else if (length(down)==1 && down==0) col_idx<-2
print('colidx')
print(col_idx)
if(enrichment_type!="biological process"){
# if(!is.null(col_idx)){
# col <- col-1
# kk<-result[[row]][[col]]
# p<-barplot(kk, showCategory=as.numeric(category))
#
# # Increment the progress bar, and update the detail text.
# progress$inc(1/n, detail = paste("Doing part", 1,"/",n))
#
# # Pause for 0.1 seconds to simulate a long computation.
# Sys.sleep(0.1)
# #print(head(x))
# return(p)
# }
# else{
kk<-result[[row]][[col]]
p<-barplot(kk, showCategory=as.numeric(category))
# Increment the progress bar, and update the detail text.
progress$inc(1/n, detail = paste("Doing part", 1,"/",n))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
#print(head(x))
return(p)
# }
}
else{
if(nrow(res[[row]][[col]])!=0) ego<-result[[row]][[col]]
else ego<-NULL
x<-NULL
if(category_go!=""){
x<-gofilter(ego,level=as.numeric(category_go))#dropGO(ego, level = as.numeric(input$category_go), term = NULL)
}
else x<-ego
# Increment the progress bar, and update the detail text.
progress$inc(1/n, detail = paste("Doing part", 1,"/",n))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
#print(head(x))
print(x)
if(!is.null(x)){
p<-barplot(x, showCategory=as.numeric(category))
}
# Increment the progress bar, and update the detail text.
progress$inc(1/n, detail = paste("Doing part", 2,"/",n))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)