forked from gexijin/iDEP-old-version
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.R
4136 lines (3496 loc) · 166 KB
/
server.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
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
library(shiny)
library(RSQLite)
library(gplots)
library(ggplot2)
library(e1071) # computing kurtosis
library(reshape2) # for melt correlation matrix in heatmap
library(DT) # for renderDataTable
library(plotly) # for interactive heatmap
# bioconductor packages
library(limma) # Differential expression
library(DESeq2) # count data analysis
library(edgeR) # count data D.E.
library(gage) # pathway analysis
library(PGSEA) # pathway
library(fgsea) # fast GSEA
library(ReactomePA) # pathway analysis
library(pathview)
library(PREDA) # showing expression on genome
library(PREDAsampledata)
library(sfsmisc)
library(lokern)
library(multtest)
iDEPversion = "iDEP 0.35"
# R packages needed
# install.packages(c("shiny","RSQLite","gplots","ggplot2","e1071","shinyAce","shinyBS","reshape2","DT","plotly" ) )
# bioconductor packages
#source("https://bioconductor.org/biocLite.R")
#biocLite(c( "limma", "DESeq2","edgeR","gage", "PGSEA", "fgsea", "ReactomePA", "pathview" ))
# annotation packages needed by pathview
#biocLite( c( "org.Ag.eg.db","org.At.tair.db","org.Bt.eg.db","org.Ce.eg.db","org.Cf.eg.db","org.Dm.eg.db","org.Dr.eg.db","org.EcK12.eg.db","org.EcSakai.eg.db","org.Gg.eg.db","org.Hs.eg.db","org.Hs.ipi.db","org.Mm.eg.db","org.Mmu.eg.db","org.Pf.plasmo.db","org.Pt.eg.db","org.Rn.eg.db","org.Sc.sgd.db","org.Sco.eg.db","org.Ss.eg.db","org.Tgondii.eg.db","org.Xl.eg.db") )
pdf(NULL) # this prevents error Cannot open file 'Rplots.pdf'
Min_overlap <- 2
minSetSize = 3;
mappingCoverage = 0.60 # 60% percent genes has to be mapped for confident mapping
mappingEdge = 0.5 # Top species has 50% more genes mapped
PvalGeneInfo = 0.05; minGenes = 10 # min number of genes for ploting
kurtosis.log = 50 # log transform is enforced when kurtosis is big
kurtosis.warning = 10 # log transformation recommnded
minGenesEnrichment = 2 # perform GO or promoter analysis only if more than this many genes
PREDA_Permutations =1000
# this need to be removed. Also replace go to go for folder
# setwd("C:/Users/Xijin.Ge/Google Drive/research/Shiny/RNAseqer")
sqlite <- dbDriver("SQLite")
convert <- dbConnect(sqlite,"../go/convertIDs.db",flags=SQLITE_RO) #read only mode
set.seed(2)
mycolors = sort(rainbow(20))[c(1,20,10,11,2,19,3,12,4,13,5,14,6,15,7,16,8,17,9,18)] # 20 colors for kNN clusters
hclust2 <- function(x, method="average", ...)
hclust(x, method=method, ...)
dist2 <- function(x, ...)
as.dist(1-cor(t(x), method="pearson"))
keggSpeciesID = read.csv("KEGG_Species_ID.csv")
detectGroups <- function (x){ # x are col names
tem <- gsub("[0-9]*$","",x) # Remove all numbers from end
#tem = gsub("_Rep|_rep|_REP","",tem)
tem <- gsub("_$","",tem); # remove "_" from end
tem <- gsub("_Rep$","",tem); # remove "_Rep" from end
tem <- gsub("_rep$","",tem); # remove "_rep" from end
tem <- gsub("_REP$","",tem) # remove "_REP" from end
return( tem )
}
myheatmap <- function (x,n=-1) {
if(n == -1) n=dim(x)[1]
geneSD = apply(x,1,sd)
x = x[order(-geneSD),]
# this will cutoff very large values, which could skew the color
x=as.matrix(x[1:n,])-apply(x[1:n,],1,mean)
cutoff = median(unlist(x)) + 3*sd (unlist(x))
x[x>cutoff] <- cutoff
cutoff = median(unlist(x)) - 3*sd (unlist(x))
x[x< cutoff] <- cutoff
hy <- heatmap.2(x, distfun = dist2,hclustfun=hclust2,
col=greenred(75), density.info="none", trace="none", scale="none", keysize=.5
#,Colv=FALSE,
,key=F
,margins = c(6, 8)
)
}
myheatmap3 <- function (x,n=-1) {
if( n > 0 && n< dim(x)[1] )
{ geneSD = apply(x,1,sd)
x = x[order(-geneSD),]
# this will cutoff very large values, which could skew the color
x=as.matrix(x[1:n,])
}
x=as.matrix(x)-apply(x,1,mean)
cutoff = median(unlist(x)) + 3*sd (unlist(x))
x[x>cutoff] <- cutoff
cutoff = median(unlist(x)) - 3*sd (unlist(x))
x[x< cutoff] <- cutoff
groups = detectGroups(colnames(x))
colnames(x) = detectGroups(colnames(x))
hy <- heatmap.2(x, dendrogram ="row",distfun = dist2,hclustfun=hclust2,
col=greenred(75), density.info="none", trace="none", scale="none", keysize=.5
#,Colv=FALSE,
,labRow=""
#,labCol=""
,ColSideColors=mycolors[ groups]
,key=F
,margins = c(6, 20)
)
if(0) {
lmat = rbind(c(5,4),c(0,1),c(3,2))
lwid = c(1.5,6)
lhei = c(1,.2,8)
if( dim(x)[1]>100)
heatmap.2(x, distfun = dist2,hclustfun=hclust2,
col=greenred(75), density.info="none", trace="none", scale="none", keysize=.5
,key=T, symkey=F
,ColSideColors=mycolors[ groups]
,labRow=""
,margins=c(6,8)
,srtCol=45
#,lmat = lmat, lwid = lwid, lhei = lhei
)
if( dim(x)[1] <=100)
heatmap.2(x, distfun = dist2,hclustfun=hclust2,
col=greenred(75), density.info="none", trace="none", scale="none", keysize=.5
,key=T, symkey=F,
#,labRow=labRow
,ColSideColors=mycolors[ groups]
,margins=c(6,8)
,cexRow=1.5
,srtCol=45
#,lmat = lmat, lwid = lwid, lhei = lhei
)
}
}
# randomly samples genes
myheatmap4 <- function (x,n=-1) {
if( n > 0 && n< dim(x)[1] )
{
ix = sample(1:dim(x)[1], n)
# this will cutoff very large values, which could skew the color
x=as.matrix(x[ix,])
}
x=as.matrix(x)-apply(x,1,mean)
cutoff = median(unlist(x)) + 3*sd (unlist(x))
x[x>cutoff] <- cutoff
cutoff = median(unlist(x)) - 3*sd (unlist(x))
x[x< cutoff] <- cutoff
groups = detectGroups(colnames(x))
colnames(x) = detectGroups(colnames(x))
hy <- heatmap.2(x, dendrogram ="row",distfun = dist2,hclustfun=hclust2,
col=greenred(75), density.info="none", trace="none", scale="none", keysize=.5
,Colv=FALSE,
,labRow=""
#,labCol=""
,ColSideColors=mycolors[ groups]
,key=F
,margins = c(6, 20)
)
}
myheatmap2 <- function (x,bar,n=-1 ) {
# number of genes to show
ngenes = as.character( table(bar))
if(length(bar) >n && n != -1) {ix = sort( sample(1:length(bar),n) ); bar = bar[ix]; x = x[ix,] }
# this will cutoff very large values, which could skew the color
x=as.matrix(x)-apply(x,1,mean)
cutoff = median(unlist(x)) + 3*sd (unlist(x))
x[x>cutoff] <- cutoff
cutoff = median(unlist(x)) - 3*sd (unlist(x))
x[x< cutoff] <- cutoff
#colnames(x)= detectGroups(colnames(x))
heatmap.2(x, Rowv =F,Colv=F, dendrogram ="none",
col=greenred(75), density.info="none", trace="none", scale="none", keysize=.3
,key=F, labRow = F,
,RowSideColors = mycolors[bar]
,margins = c(8, 24)
,srtCol=45
)
legend.text = paste("Cluster ", toupper(letters)[unique(bar)], " (N=", ngenes,")", sep="")
par(lend = 1) # square line ends for the color legend
legend("topright", # location of the legend on the heatmap plot
legend = legend.text, # category labels
col = mycolors, # color key
lty= 1, # line style
lwd = 10 # line width
)
}
cleanGeneSet <- function (x){
# remove duplicate; upper case; remove special characters
x <- unique( toupper( gsub("\n| ","",x) ) )
x <- x[ which( nchar(x)>1) ] # genes should have at least two characters
return(x)
}
# read GMT files, does NO cleaning. Assumes the GMT files are created with cleanGeneSet()
readGMT <- function (fileName){
x <- scan(fileName, what="", sep="\n")
x <- strsplit(x, "\t")
# Extract the first vector element and set it as the list element name
names(x) <- sapply(x, `[[`, 1)
x <- lapply(x, `[`, -c(1,2)) # 2nd element is comment, ignored
x = x[which(sapply(x,length) > 1)] # gene sets smaller than 1 is ignored!!!
return(x)
}
# This functions cleans and converts to upper case
readGMTRobust <- function (file1) { # size restriction
# Read in the first file
x <- scan(file1, what="", sep="\n")
# x <- gsub("\t\t.","",x) # GMT files saved by Excel has a lot of empty cells "\t\t\t\t" "\t." means one or more tab
x <- gsub(" ","",x) # remove white space
x <- toupper(x) # convert to upper case
#----Process the first file
# Separate elements by one or more whitespace
y <- strsplit(x, "\t")
# Extract the first vector element and set it as the list element name
names(y) <- sapply(y, `[[`, 1)
#names(y) <- sapply(y, function(x) x[[1]]) # same as above
# Remove the first vector element from each list element
y <- lapply(y, `[`, -c(1,2))
#y <- lapply(y, function(x) x[-1]) # same as above
# remove duplicated elements
for ( i in 1:length(y) ) y[[i]] <- cleanGeneSet(y[[i]])
# check the distribution of the size of gene lists sapply(y, length) hold a vector of sizes
if( max( sapply(y,length) ) <5) cat("Warning! Gene sets have very small number of genes!\n Please double check format.")
y <- y[which(sapply(y,length) > 1)] # gene sets smaller than 1 is ignored!!!
return(y)
}
# Given a gene set, finds significant overlaps with a gene set database object
findOverlapGMT <- function ( query, geneSet, minFDR=.2 ,minSize=2,maxSize=10000 ){
#geneSets <- readGMT("exampleData/MousePath_TF_gmt.gmt")
#query <- geneSets[['TF_MM_FRIARD_C-REL']]
#query <- query[1:60]
total_elements = 30000
Min_overlap <- 1
maxTerms =10 # max number of enriched terms
noSig <- as.data.frame("No significant enrichment found!")
query <- cleanGeneSet(query) # convert to upper case, unique()
if(length(query) <=2) return(noSig)
if(length(geneSet) <1) return(noSig)
geneSet <- geneSet[which(sapply(geneSet,length) > minSize)] # gene sets smaller than 1 is ignored!!!
geneSet <- geneSet[which(sapply(geneSet,length) < maxSize)] # gene sets smaller than 1 is ignored!!!
result <- unlist( lapply(geneSet, function(x) length( intersect (query, x) ) ) )
result <- cbind(unlist( lapply(geneSet, length) ), result )
result <- result[ which(result[,2]>Min_overlap), ,drop=F]
if(dim(result)[1] == 0) return( noSig)
xx <- result[,2]
mm <- length(query)
nn <- total_elements - mm
kk <- result[,1]
Pval_enrich=phyper(xx-1,mm,nn,kk, lower.tail=FALSE );
FDR <- p.adjust(Pval_enrich,method="fdr",n=length(geneSet) )
result <- as.data.frame(cbind(FDR,result))
result <- result[,c(1,3,2)]
result$pathway = rownames(result)
result$Genes = "" # place holder just
colnames(result)= c("Corrected P value (FDR)", "Genes in list", "Total genes in category","Functional Category","Genes" )
result <- result[ which( result[,1] < minFDR),,drop=F]
if( dim( result)[1] == 0) return(noSig)
if(min(FDR) > minFDR) return(noSig)
result <- result[order(result[,1] ),]
if(dim(result)[1] > maxTerms ) result <- result[1:maxTerms,]
return( result)
}
geneChange <- function(x){
n = length(x)
if( n<4) return( max(x)-min(x) ) else
return(sort(x)[n-1] - sort(x)[2] )
}
myPGSEA <- function (exprs, cl, range = c(25, 500), ref = NULL, center = TRUE,
p.value = 0.005, weighted = TRUE, nPermutation=100, enforceRange = TRUE, ...)
{
if (is(exprs, "ExpressionSet"))
exprs <- exprs(exprs)
if (!is.list(cl))
stop("cl need to be a list")
if (!is.null(ref)) {
if (!is.numeric(ref))
stop("column index's required")
}
if (!is.null(ref)) {
if (options()$verbose)
cat("Creating ratios...", "\n")
ref_mean <- apply(exprs[, ref], 1, mean, na.rm = TRUE)
exprs <- sweep(exprs, 1, ref_mean, "-")
}
if (center)
exprs <- scale(exprs, scale = FALSE) # column centering is done
results <- matrix(NA, length(cl), ncol(exprs))
rownames(results) <- names(cl)
colnames(results) <- colnames(exprs)
mode(results) <- "numeric"
Setsize = c(rep(0,length(cl))) # gene set size vector
mean2 = c(rep(0,length(cl))) # mean of the range of means
meanSD = c(rep(0,length(cl))) # SD of the range of means
if (is.logical(p.value))
{ p.results <- results; mean.results <- results;}
for (i in 1:length(cl)) { # for each gene list
#cat("\nProcessing gene set",i);
if (class(cl[[i]]) == "smc") {
clids <- cl[[i]]@ids
}
else if (class(cl[[i]]) %in% c("GeneColorSet", "GeneSet")) {
clids <- cl[[i]]@geneIds
}
else {
clids <- cl[[i]]
}
if (options()$verbose)
cat("Testing region ", i, "\n")
ix <- match(clids, rownames(exprs))
ix <- unique(ix[!is.na(ix)])
present <- sum(!is.na(ix))
Setsize[i] <- present
if (present < range[1]) {
if (options()$verbose)
cat("Skipping region ", i, " because too small-",
present, ",\n")
next
}
if (present > range[2]) {
if (options()$verbose)
cat("Skipping region ", i, " because too large-",
present, "\n")
next
}
texprs <- exprs[ix, ] # expression matrix for genes in gene set
if (any(is.na(texprs)))
cat("Warning - 'NA' values within expression data, enrichment scores are estimates only.\n")
if (!is.matrix(texprs))
texprs <- as.matrix(texprs)
stat <- try(apply(texprs, 2, t.test, ...))
means <- try(apply(texprs, 2, mean,trim=0.1)) # trim mean
ps <- unlist(lapply(stat, function(x) x$p.value))
stat <- unlist(lapply(stat, function(x) x$statistic))
p.results[i, ] <- ps
mean.results[i,] <- means
results[i, ] <- as.numeric(stat)
# permutation of gene sets of the same size
if(nPermutation > 2 ) { # no permutation if <=2
meansRanges = c(0, rep(nPermutation))
for( k in 1:nPermutation ) {
ix <- sample.int( dim(exprs)[1], length(ix) )
texprs <- exprs[ix, ]
means <- try(apply(texprs, 2, mean,trim=0.1)) # trim mean
meansRanges[k] = dynamicRange(means)
}
mean2[i] = mean(meansRanges)
meanSD[i]= sd(meansRanges,na.rm=TRUE) # NA are removed before calculating standard deviation
}
}
return(list(results = results, p.results = p.results, means = mean.results, size=Setsize, mean2=mean2, meanSD=meanSD))
}
dynamicRange <- function( x ) {
y = sort(x)
if(length(x)>=4) k =2 else k =1;
return( y[length(x)-k+1] - y[k])
}
# Create a list of GMT files in /gmt sub folder
gmtFiles = list.files(path = "../go/pathwayDB",pattern=".*\\.db")
gmtFiles = paste("../go/pathwayDB/",gmtFiles,sep="")
geneInfoFiles = list.files(path = "../go/geneInfo",pattern=".*GeneInfo\\.csv")
geneInfoFiles = paste("../go/geneInfo/",geneInfoFiles,sep="")
motifFiles = list.files(path = "../go/motif",pattern=".*\\.db")
motifFiles = paste("../go/motif/",motifFiles,sep="")
# Create a list for Select Input options
orgInfo <- dbGetQuery(convert, paste("select distinct * from orgInfo " ))
orgInfo <- orgInfo[order(orgInfo$name),]
speciesChoice <- setNames(as.list( orgInfo$id ), orgInfo$name2 )
# add a defult element to list # new element name value
speciesChoice <- append( setNames( "NEW","**NEW SPECIES**"), speciesChoice )
speciesChoice <- append( setNames( "BestMatch","Best matching species"), speciesChoice )
# move one element to the 2nd place
move2 <- function(i) c(speciesChoice[1:2],speciesChoice[i],speciesChoice[-c(1,i)])
i= grep("Glycine max" ,names(speciesChoice)); speciesChoice <- move2(i)
i= grep("Zea mays" ,names(speciesChoice)); speciesChoice <- move2(i)
i= grep("Arabidopsis thaliana",names(speciesChoice)); speciesChoice <- move2(i)
i= grep("Saccharomyces cerevisiae" ,names(speciesChoice)); speciesChoice <- move2(i)
i= grep("Caenorhabditis elegans",names(speciesChoice)); speciesChoice <- move2(i)
i= grep("Danio rerio" ,names(speciesChoice)); speciesChoice <- move2(i)
i= grep("Bos taurus" ,names(speciesChoice)); speciesChoice <- move2(i)
i= grep("Rattus norvegicus" ,names(speciesChoice)); speciesChoice <- move2(i)
i= grep("Mus musculus",names(speciesChoice)); speciesChoice <- move2(i)
i= grep("Homo sapiens",names(speciesChoice)); speciesChoice <- move2(i)
GO_levels = dbGetQuery(convert, "select distinct id,level from GO
WHERE GO = 'biological_process'" )
level2Terms = GO_levels[which(GO_levels$level %in% c(2,3)) ,1] # level 2 and 3
idIndex <- dbGetQuery(convert, paste("select distinct * from idIndex " ))
quotes <- dbGetQuery(convert, " select * from quotes")
quotes = paste0("\"",quotes$quotes,"\"", " -- ",quotes$author,". ")
# This function convert gene set names
# x="GOBP_mmu_mgi_GO:0000183_chromatin_silencing_at_rDNA"
# chromatin silencing at rDNA
proper=function(x) paste0(toupper(substr(x, 1, 1)), substring(x, 2))
extract1 <- function (x) {
words <- unlist ( strsplit(x,"_"))
if(length( words ) <=4 ) return(gsub("_"," ",x)) else {
words <- words[-c(1:4)]
return( proper(paste(words,collapse = " ") ) )}
}
#find idType based on index
findIDtypeById <- function(x){ # find
return( idIndex$idType[ as.numeric(x)] )
}
findSpeciesById <- function (speciesID){ # find species name use id
return( orgInfo[which(orgInfo$id == speciesID),] )
}
# just return name
findSpeciesByIdName <- function (speciesID){ # find species name use id
return( orgInfo[which(orgInfo$id == speciesID),3] )
}
# convert sorted species:idType combs into a list for repopulate species choice
matchedSpeciesInfo <- function (x) {
a<- c()
for( i in 1:length(x)) {
a = c(a,paste( gsub("genes.*","",findSpeciesByIdName( as.numeric(gsub(" .*","",names(x[i])) ))), " (",
x[i]," mapped from ",findIDtypeById( gsub(".* ","",names(x[i]) ) ),")",sep="")
) }
return(a )
}
# convert gene IDs to ensembl gene ids and find species
convertID <- function (query,selectOrg, selectGO) {
querySet <- cleanGeneSet( unlist( strsplit( toupper(query),'\t| |\n|\\,' ) ) )
result <- dbGetQuery( convert,
paste( " select distinct id,ens,species from mapping where id IN ('", paste(querySet,collapse="', '"), "')",sep="") )
if( dim(result)[1] == 0 ) return(NULL)
if(selectOrg == speciesChoice[[1]]) {
comb = paste( result$species,result$idType)
sortedCounts = sort( table(comb ),decreasing=T)
recognized =names(sortedCounts[1] )
result <- result[which(comb == recognized ) , ]
speciesMatched=sortedCounts
names(speciesMatched )= sapply(as.numeric(gsub(" .*","",names(sortedCounts) ) ), findSpeciesByIdName )
speciesMatched <- as.data.frame( speciesMatched )
if(length(sortedCounts) == 1) { # if only one species matched
speciesMatched[1,1] <-paste( rownames(speciesMatched), "(",speciesMatched[1,1],")",sep="")
} else {# if more than one species matched
speciesMatched[,1] <- as.character(speciesMatched[,1])
speciesMatched[,1] <- paste( speciesMatched[,1]," (",speciesMatched[,2], ")", sep="")
speciesMatched[1,1] <- paste( speciesMatched[1,1]," ***Used in mapping*** To change, select from above and resubmit query.")
speciesMatched <- as.data.frame(speciesMatched[,1])
}
} else { # if species is selected
result <- result[which(result$species == selectOrg ) ,]
if( dim(result)[1] == 0 ) return(NULL) #stop("ID not recognized!")
speciesMatched <- as.data.frame(paste("Using selected species ", findSpeciesByIdName(selectOrg) ) )
}
result <- result[which(!duplicated(result[,2]) ),] # remove duplicates in ensembl_gene_id
colnames(speciesMatched) = c("Matched Species (genes)" )
conversionTable <- result[,1:2]; colnames(conversionTable) = c("User_input","ensembl_gene_id")
conversionTable$Species = sapply(result[,3], findSpeciesByIdName )
if(0){
# generate a list of gene set categories
ix = grep(findSpeciesById(result$species[1])[1,1],gmtFiles)
if (length(ix) == 0 ) {categoryChoices = NULL}
# If selected species is not the default "bestMatch", use that species directly
if(selectOrg != speciesChoice[[1]]) {
ix = grep(findSpeciesById(selectOrg)[1,1], gmtFiles )
if (length(ix) == 0 ) {categoryChoices = NULL}
totalGenes <- orgInfo[which(orgInfo$id == as.numeric(selectOrg)),7]
}
pathway <- dbConnect(sqlite,gmtFiles[ix])
# Generate a list of geneset categories such as "GOBP", "KEGG" from file
geneSetCategory <- dbGetQuery(pathway, "select distinct * from categories " )
geneSetCategory <- geneSetCategory[,1]
categoryChoices <- setNames(as.list( geneSetCategory ), geneSetCategory )
categoryChoices <- append( setNames( "All","All available gene sets"), categoryChoices )
#change GOBO to the full description for display
names(categoryChoices)[ match("GOBP",categoryChoices) ] <- "GO Biological Process"
names(categoryChoices)[ match("GOCC",categoryChoices) ] <- "GO Cellular Component"
names(categoryChoices)[ match("GOMF",categoryChoices) ] <- "GO Molecular Function"
dbDisconnect(pathway)
} #if (0)
return(list(originalIDs = querySet,IDs=unique( result[,2]),
species = findSpeciesById(result$species[1]),
#idType = findIDtypeById(result$idType[1] ),
speciesMatched = speciesMatched,
conversionTable = conversionTable
) )
}
convertEnsembl2Entrez <- function (query,Species) {
querySet <- cleanGeneSet( unlist( strsplit( toupper(names( query)),'\t| |\n|\\,' ) ) )
speciesID <- orgInfo$id[ which(orgInfo$ensembl_dataset == Species)] # note uses species Identifying
# idType 6 for entrez gene ID
result <- dbGetQuery( convert,
paste( " select id,ens,species from mapping where ens IN ('", paste(querySet,collapse="', '"),
"') AND idType ='6'",sep="") ) # slow
if( dim(result)[1] == 0 ) return(NULL)
result <- subset(result, species==speciesID, select = -species)
ix = match(result$ens,names(query) )
tem <- query[ix]; names(tem) = result$id
return(tem)
}
convertEnsembl2KEGG <- function (query,Species) { # not working
querySet <- cleanGeneSet( unlist( strsplit( toupper(names( query)),'\t| |\n|\\,' ) ) )
speciesID <- orgInfo$id[ which(orgInfo$ensembl_dataset == Species)] # note uses species Identifying
# idType 6 for entrez gene ID
result <- dbGetQuery( convert,
paste( " select id,ens,species from mapping where ens IN ('", paste(querySet,collapse="', '"),
"') AND idType ='107'",sep="") ) # slow
if( dim(result)[1] == 0 ) return(NULL)
result <- subset(result, species==speciesID, select = -species)
ix = match(result$ens,names(query) )
tem <- query[ix]; names(tem) = result$id
return(tem)
}
geneInfo <- function (converted,selectOrg){
# query = scan("query_temp.txt",what=""); selectOrg ="BestMatch";
# query = scan("zebrafish_test.gmt", what="" ); selectOrg ="BestMatch";
# query = scan("Celegans_test.gmt", what="" ); selectOrg ="BestMatch";
# query = scan("test_query_mouse_symbol.txt", what="" ); selectOrg ="BestMatch";
# query = scan("soy_test.txt", what="" );selectOrg ="BestMatch";
# querySet <- cleanGeneSet( unlist( strsplit( toupper(query),'\t| |\n|\\,')))
# converted = convertID( querySet,selectOrg)
if(is.null(converted) ) return(as.data.frame("ID not recognized!") ) # no ID
querySet <- converted$IDs
if(length(querySet) == 0) return(as.data.frame("ID not recognized!") )
ix = grep(converted$species[1,1],geneInfoFiles)
if (length(ix) == 0 ) {return(as.data.frame("No matching gene info file found") )} else {
# If selected species is not the default "bestMatch", use that species directly
if(selectOrg != speciesChoice[[1]]) {
ix = grep(findSpeciesById(selectOrg)[1,1], geneInfoFiles )
}
if(length(ix) == 1) # if only one file #WBGene0000001 some ensembl gene ids in lower case
{ x = read.csv(as.character(geneInfoFiles[ix]) ); x[,1]= toupper(x[,1]) } else # read in the chosen file
{ return(as.data.frame("Multiple geneInfo file found!") ) }
Set = match(x$ensembl_gene_id, querySet)
Set[which(is.na(Set))]="Genome"
Set[which(Set!="Genome")] ="List"
# x = cbind(x,Set) } # just for debuging
return( cbind(x,Set) )}
}
# Main function. Find a query set of genes enriched with functional category
FindOverlap <- function (converted,gInfo, GO,selectOrg,minFDR) {
maxTerms =10 # max number of enriched terms
idNotRecognized = as.data.frame("ID not recognized!")
if(is.null(converted) ) return(idNotRecognized) # no ID
# only coding
gInfo <- gInfo[which( gInfo$gene_biotype == "protein_coding"),]
querySet <- intersect( converted$IDs, gInfo[,1]);
if(length(querySet) == 0) return(idNotRecognized )
ix = grep(converted$species[1,1],gmtFiles)
totalGenes <- converted$species[1,7]
if (length(ix) == 0 ) {return(idNotRecognized )}
# If selected species is not the default "bestMatch", use that species directly
if(selectOrg != speciesChoice[[1]]) {
ix = grep(findSpeciesById(selectOrg)[1,1], gmtFiles )
if (length(ix) == 0 ) {return(idNotRecognized )}
totalGenes <- orgInfo[which(orgInfo$id == as.numeric(selectOrg)),7]
}
pathway <- dbConnect(sqlite,gmtFiles[ix])
sqlQuery = paste( " select distinct gene,pathwayID from pathway where gene IN ('", paste(querySet,collapse="', '"),"')" ,sep="")
#cat(paste0("HH",GO,"HH") )
if( GO != "All") sqlQuery = paste0(sqlQuery, " AND category ='",GO,"'")
result <- dbGetQuery( pathway, sqlQuery )
if( dim(result)[1] ==0) {return(as.data.frame("No matching species or gene ID file!" )) }
# given a pathway id, it finds the overlapped genes, symbol preferred
sharedGenesPrefered <- function(pathwayID) {
tem <- result[which(result[,2]== pathwayID ),1]
ix = match(tem, converted$conversionTable$ensembl_gene_id) # convert back to original
tem2 <- unique( converted$conversionTable$User_input[ix] )
if(length(unique(gInfo$symbol) )/dim(gInfo)[1] >.7 ) # if 70% genes has symbol in geneInfo
{ ix = match(tem, gInfo$ensembl_gene_id);
tem2 <- unique( gInfo$symbol[ix] ) }
return( paste( tem2 ,collapse=" ",sep="") )}
x0 = table(result$pathwayID)
x0 = as.data.frame( x0[which(x0>=Min_overlap)] )# remove low overlaps
if(dim(x0)[1] <= 5 ) return(idNotRecognized) # no data
colnames(x0)=c("pathwayID","overlap")
pathwayInfo <- dbGetQuery( pathway, paste( " select distinct id,n,Description from pathwayInfo where id IN ('",
paste(x0$pathwayID,collapse="', '"), "') ",sep="") )
x = merge(x0,pathwayInfo, by.x='pathwayID', by.y='id')
x$Pval=phyper(x$overlap-1,length(querySet),totalGenes - length(querySet),as.numeric(x$n), lower.tail=FALSE );
x$FDR = p.adjust(x$Pval,method="fdr")
x <- x[ order( x$FDR) ,] # sort according to FDR
if(min(x$FDR) > minFDR) x=as.data.frame("No significant enrichment found!") else {
x <- x[which(x$FDR < minFDR),]
if(dim(x)[1] > maxTerms ) x = x[1:maxTerms,]
x= cbind(x,sapply( x$pathwayID, sharedGenesPrefered ) )
colnames(x)[7]= "Genes"
x <- subset(x,select = c(FDR,overlap,n,description,Genes) )
colnames(x) = c("Corrected P value (FDR)", "Genes in list", "Total genes in category","Functional Category","Genes" )
}
dbDisconnect(pathway)
return(x )
}
#, categoryChoices = categoryChoices
#Given a KEGG pathway description, found pathway ids
keggPathwayID <- function (pathwayDescription, Species, GO,selectOrg) {
ix = grep(Species,gmtFiles)
if (length(ix) == 0 ) {return(NULL)}
# If selected species is not the default "bestMatch", use that species directly
if(selectOrg != speciesChoice[[1]]) {
ix = grep(findSpeciesById(selectOrg)[1,1], gmtFiles )
if (length(ix) == 0 ) {return(NULL )}
totalGenes <- orgInfo[which(orgInfo$id == as.numeric(selectOrg)),7]
}
pathway <- dbConnect(sqlite,gmtFiles[ix])
pathwayInfo <- dbGetQuery( pathway, paste( " select * from pathwayInfo where description = '",
pathwayDescription, "' AND name LIKE '",GO,"%'",sep="") )
dbDisconnect(pathway);
if(dim(pathwayInfo)[1] != 1 ) {return(NULL) }
tem = gsub(".*:","",pathwayInfo[1,2])
return( gsub("_.*","",tem) )
}
gmtCategory <- function (converted, convertedData, selectOrg,gmtFile) {
if(selectOrg == "NEW" && !is.null(gmtFile) )
return( list(Custom_GeneSet ="Custom" ) )
idNotRecognized = as.data.frame("ID not recognized!")
if(is.null(converted) ) return(idNotRecognized) # no ID
querySet <- rownames(convertedData)
if(length(querySet) == 0) return(idNotRecognized )
ix = grep(converted$species[1,1],gmtFiles)
if (length(ix) == 0 ) {return(idNotRecognized )}
# If selected species is not the default "bestMatch", use that species directly
if(selectOrg != speciesChoice[[1]]) {
ix = grep(findSpeciesById(selectOrg)[1,1], gmtFiles )
if (length(ix) == 0 ) {return(idNotRecognized )}
}
pathway <- dbConnect(sqlite,gmtFiles[ix])
cat(paste("selectOrg:",selectOrg) )
# Generate a list of geneset categories such as "GOBP", "KEGG" from file
geneSetCategory <- dbGetQuery(pathway, "select distinct * from categories " )
geneSetCategory <- geneSetCategory[,1]
categoryChoices <- setNames(as.list( geneSetCategory ), geneSetCategory )
categoryChoices <- append( setNames( "All","All available gene sets"), categoryChoices )
#change GOBO to the full description for display
names(categoryChoices)[ match("GOBP",categoryChoices) ] <- "GO Biological Process"
names(categoryChoices)[ match("GOCC",categoryChoices) ] <- "GO Cellular Component"
names(categoryChoices)[ match("GOMF",categoryChoices) ] <- "GO Molecular Function"
dbDisconnect(pathway)
return(categoryChoices )
}
# Main function. Find a query set of genes enriched with functional category
readGeneSets <- function (converted, convertedData, GO,selectOrg, myrange) {
idNotRecognized = as.data.frame("ID not recognized!")
if(is.null(converted) ) return(idNotRecognized) # no ID
querySet <- rownames(convertedData)
if(length(querySet) == 0) return(idNotRecognized )
ix = grep(converted$species[1,1],gmtFiles)
if (length(ix) == 0 ) {return(idNotRecognized )}
# If selected species is not the default "bestMatch", use that species directly
if(selectOrg != speciesChoice[[1]]) {
ix = grep(findSpeciesById(selectOrg)[1,1], gmtFiles )
if (length(ix) == 0 ) {return(idNotRecognized )}
}
pathway <- dbConnect(sqlite,gmtFiles[ix])
if(is.null(GO) ) GO <- "GOBP" # initial value not properly set; enforcing
# get Gene sets
querySet = rownames(convertedData)
sqlQuery = paste( " select distinct gene,pathwayID from pathway where gene IN ('", paste(querySet,collapse="', '"),"')" ,sep="")
# cat(paste0("\n\nhere:",GO,"There"))
if( GO != "All") sqlQuery = paste0(sqlQuery, " AND category ='",GO,"'")
result <- dbGetQuery( pathway, sqlQuery )
if( dim(result)[1] ==0) {return(list( x=as.data.frame("No matching species or gene ID file!" )) )}
# list pathways and frequency of genes
pathwayIDs = aggregate( result$pathwayID, by = list(unique.values = result$pathwayID), FUN = length)
pathwayIDs = pathwayIDs[which(pathwayIDs[,2]>= myrange[1] ),]
pathwayIDs = pathwayIDs[which( pathwayIDs[,2] <= myrange[2] ),]
if(dim(pathwayIDs)[1] ==0 ) geneSets = NULL;
# convert pathways into lists like those generated by readGMT
geneSets = lapply(pathwayIDs[,1], function(x) result[which(result$pathwayID == x ),1] )
pathwayInfo <- dbGetQuery( pathway, paste( " select distinct id,Description from pathwayInfo where id IN ('",
paste(pathwayIDs[,1],collapse="', '"), "') ",sep="") )
ix = match( pathwayIDs[,1], pathwayInfo[,1])
names(geneSets) <- pathwayInfo[ix,2]
#geneSets <- geneSets[ -which(duplicated(names(geneSets) ))] # remove geneSets with the same name
dbDisconnect(pathway)
return( geneSets )
}
PGSEApathway <- function (converted,convertedData, selectOrg,GO,gmt, myrange,Pval_pathway,top){
subtype = detectGroups(colnames(convertedData))
Pvalue = 0.01 # cut off to report in PGSEA. Otherwise NA
#Pval_pathway = 0.2 # cut off for P value of ANOVA test to writ to file
# top = 30 # number of pathways to show
if(length(gmt) ==0 ) return( list(pg3 = NULL, best = best ) )
# centering by mean
#pg = myPGSEA (convertedData - rowMeans(convertedData),
# cl=gmt,range=myrange,p.value=TRUE, weighted=FALSE,nPermutation=100)
pg = PGSEA (convertedData - rowMeans(convertedData),cl=gmt,range=myrange,p.value=TRUE, weighted=FALSE)
pg2 = pg$results;
pg2 = pg2[rowSums(is.na(pg2))<ncol(pg2) ,] # remove se/wrts with all missing(non-signficant)
if (dim(pg2)[1] < 2 ) return()
best = max(abs(pg2))
if(length(subtype) < 4 || length(unique(subtype)) <2 ||length(unique(subtype)) == dim(convertedData)[2] ) {
pg2 = pg2[order(-apply(pg2,1,sd) ) ,]
return( list(pg3 = pg2[1:top,], best = best ) )
}
cat("\nComputing P values using ANOVA\n");
pathPvalue <- function ( k){
return( summary(aov(pg2[k,]~subtype) )[[1]][["Pr(>F)"]][1] )
}
Pvalues = sapply(1:dim(pg2)[1], pathPvalue)
Pvalues = p.adjust(Pvalues, "fdr")
#if(min(Pvalues) > Pval_pathway ) return( list(pg3 = NULL, best = best ) ) else {
if(sort(Pvalues)[2] > Pval_pathway ) return( list(pg3 = NULL, best = best ) ) else {
NsigT = rowSums(pg$p.results<Pvalue)
result=cbind( as.matrix(Pvalues),NsigT,pg2);
result = result[ order(result[,1]) ,]
result = result[which(result[,1] < Pval_pathway),,drop=F]
#result = result[which(result[,2] >2) ,]
pg2 = result[,-2]
# when there is only 1 left in the matrix pg2 becomes a vector
if(sum( Pvalues<Pval_pathway) == 1) { pg3 = t( as.matrix(pg2));pg3 = rbind(pg3,pg3);} else
{ if(dim(pg2)[1] > top ) { pg3 = pg2[1:top,]; } else { pg3 = pg2; } }
rownames(pg3) = sapply(rownames(pg3) , extract1)
a=sprintf("%-1.0e",pg3[,1])
rownames(pg3) = paste(a,rownames(pg3),sep=" ")
pg3 =pg3[,-1]
pg3 <- pg3[order( -apply(pg3,1,sd) ),] # sort by SD
return( list(pg3 = pg3, best = best ) )
}
}
if(0){ # for testing LIMMA
x = read.csv("C:/Users/Xijin.Ge/Google Drive/research/Shiny/RNAseqer/doc/Hoxa1-1/GSE50813_reduced.csv")
rownames(x) = x[,1]
x = x[,-1]
maxP_limma=.1; minFC_limma=2; rawCounts=NULL; countsDEGMethods=2;priorCounts=4; dataFormat=2;
}
DEG.limma <- function (x, maxP_limma=.1, minFC_limma=2, rawCounts,countsDEGMethods,priorCounts, dataFormat){
topGenes = list(); limmaTrend = FALSE
if( dataFormat == 2) { # if normalized data
eset = new("ExpressionSet", exprs=as.matrix(x)) } else { # counts data
if (countsDEGMethods == 1 ) { # limma-trend method selected for counts data
dge <- DGEList(counts=rawCounts);
dge <- calcNormFactors(dge)
eset <- cpm(dge, log=TRUE, prior.count=priorCounts)
limmaTrend = TRUE
}
}
groups = colnames(x)
groups = detectGroups( groups)
g = unique(groups)
# check for replicates, removes samples without replicates
reps = as.matrix(table(groups)) # number of replicates per biological sample
if ( sum( reps[,1] >= 2) <2 ) # if less than 2 samples with replicates
return( list(results= NULL, comparisons = NULL, Exp.type="Failed to parse sample names to define groups.
Cannot perform DEGs and pathway analysis. Please double check column names! Use WT_Rep1, WT_Rep2 etc. ", topGenes=NULL))
# remove samples without replicates
g <- rownames(reps)[which(reps[,1] >1)]
ix <- which( groups %in% g)
groups <- groups[ix]
x<- x[,ix]; rawCounts <- rawCounts[,ix]
if(length(g) ==2 ) {
g= unique(groups)
comparisons <- paste(g[2],"-",g[1],sep="")
design <- model.matrix(~0+groups)
colnames(design) <- g
if( !is.null(rawCounts) && countsDEGMethods == 2) { # voom
v <- voom(rawCounts, design); fit <- lmFit(v, design) } else
fit <- lmFit(eset, design) # regular limma
cont.matrix <- makeContrasts(contrasts=comparisons, levels=design)
fit2 <- contrasts.fit(fit, cont.matrix)
fit2 <- eBayes(fit2, trend=limmaTrend)
# calls differential gene expression 1 for up, -1 for down
results <- decideTests(fit2, p.value=maxP_limma, lfc=log2(minFC_limma) )
#vennDiagram(results,circle.col=rainbow(5))
topGenes1 =topTable(fit2, number = 1e12,sort.by="M" )
if (dim(topGenes1)[1] != 0) {
topGenes1 = topGenes1[,c('logFC','adj.P.Val')]
# topGenes1[,1] <- -1* topGenes1[,1] # reverse direction
topGenes[[1]] <- topGenes1 }
# log fold change is actually substract of means. So if the data is natral log transformed, it shoudl be natral log.
Exp.type = "2 biological samples."
}
if(length(g) > 2 ) {
design <- model.matrix(~ 0+factor(groups))
colnames(design) <- gsub(".*)","",colnames(design))
if( !is.null(rawCounts) && countsDEGMethods == 2) { # voom
v <- voom(rawCounts, design); fit <- lmFit(v, design) } else
fit <- lmFit(eset, design)
fit <- eBayes(fit, trend=limmaTrend)
comparisons = ""
for( i in 1:(length(g)-1) )
for (j in (i+1):length(g))
comparisons = c(comparisons,paste(g[j],"-",g[i],sep="" ) )
comparisons <- comparisons[-1]
contrast1 <- makeContrasts(contrasts=comparisons[1], levels=design)
for( kk in 2:length(comparisons) )
contrast1<- cbind(contrast1,makeContrasts(contrasts=comparisons[kk], levels=design) )
Exp.type = paste(length(g)," samples detected.")
# if factorial design 2x2, 2x3, 3x5 etc.
# all samples must be something like WT_control_rep1
if ( sum(sapply(strsplit(g,"_"),length) == 2 ) == length(g) ) {
comparisons = ""
for( i in 1:(length(g)-1) )
for (j in (i+1):length(g))
if( strsplit(g[i],"_")[[1]][1] == strsplit(g[j],"_")[[1]][1]| strsplit(g[i],"_")[[1]][2] == strsplit(g[j],"_")[[1]][2]) # only compare WT_control vs. WT_treatment
comparisons = c(comparisons,paste(g[j],"-",g[i],sep="" ) )
comparisons <- comparisons[-1]
extract_treatment <- function (x) paste( gsub( ".*_","",unlist( strsplit(x,"-")) ), collapse="-")
extract_genotype <- function (x) gsub( "_.*","",unlist( strsplit(x,"-")) )[1]
extract_treatment_counting <- unique( gsub( ".*_","",unlist( strsplit(g,"-")) ))
treatments = sapply(comparisons, extract_treatment)
genotypes = sapply(comparisons, extract_genotype)
Exp.type = paste( Exp.type, "\nFactorial design:",length(unique(genotypes)),"X", length( extract_treatment_counting ), sep="" )
contrast1 <- makeContrasts(contrasts=comparisons[1], levels=design)
for( kk in 2:length(comparisons) )
contrast1<- cbind(contrast1,makeContrasts(contrasts=comparisons[kk], levels=design) )
contrast.names = colnames(contrast1)
for ( kk in 1:(length(comparisons)-1) ) {
for( kp in (kk+1):length(comparisons))
if( treatments[kp]== treatments[kk] )
{
contrast1 = cbind(contrast1, contrast1[,kp]- contrast1[,kk] )
contrast.names = c(contrast.names, paste("Diff:", genotypes[kp], "-", genotypes[kk],"(",gsub("-",".vs.",treatments[kp]),")",sep="" ) )
}
}
colnames(contrast1)=contrast.names
comparisons = contrast.names
}
fit2 <- contrasts.fit(fit, contrast1)
fit2 <- eBayes(fit2, trend=limmaTrend)
#topTable(fit2, coef=1, adjust="BH")
results <- decideTests(fit2, p.value=maxP_limma, lfc= log2(minFC_limma ))
#vennDiagram(results[,1:5],circle.col=rainbow(5))
# extract fold change for each comparison
# there is issues with direction of foldchange. Sometimes opposite
top <- function (comp) {
tem <- topTable(fit2, number = 1e12,coef=comp,sort.by="M" )
if(dim(tem)[1] == 0) return (1) else {
# compute fold change for the first gene (ranked by absolute value)
tem2 = as.numeric( x[ which(rownames(x)== rownames(tem)[1]) , ] )
names(tem2) = colnames(x)
# compute real fold change in A-B comparison
realFC = mean ( tem2[which( groups == gsub("-.*","",comp))] ) - # average in A
mean ( tem2[which( groups == gsub(".*-","",comp))] ) # average in B
if( realFC * tem[1,1] <0 ) # if reversed
tem[,1] <- -1*tem[,1]; # reverse direction if needed
return( tem[,c(1,5)]) }
} # no significant gene returns 1, otherwise a data frame
topGenes <- lapply(comparisons, top)
topGenes <- setNames(topGenes, comparisons )
ix <- which( unlist( lapply(topGenes, class) ) == "numeric")
if( length(ix)>0) topGenes <- topGenes[ - ix ]
# if (length(topGenes) == 0) topGenes = NULL;
}
return( list(results= results, comparisons = comparisons, Exp.type=Exp.type, topGenes=topGenes))
}
DEG.DESeq2 <- function ( rawCounts,maxP_limma=.05, minFC_limma=2){
groups = as.character ( detectGroups( colnames( rawCounts ) ) )
g = unique(groups)# order is reversed
# check for replicates, removes samples without replicates
reps = as.matrix(table(groups)) # number of replicates per biological sample
if ( sum( reps[,1] >= 2) <2 ) # if less than 2 samples with replicates
return( list(results= NULL, comparisons = NULL, Exp.type="Failed to parse sample names to define groups.
Cannot perform DEGs and pathway analysis. Please double check column names! Use WT_Rep1, WT_Rep2 etc. ", topGenes=NULL))
# remove samples without replicates
g <- rownames(reps)[which(reps[,1] >1)]
ix <- which( groups %in% g)
groups <- groups[ix]
rawCounts <- rawCounts[,ix]
Exp.type = paste(length(g)," samples detected.")
comparisons = ""
for( i in 1:(length(g)-1) )
for (j in (i+1):length(g))
comparisons = c(comparisons,paste(g[j],"-",g[i],sep="" ) )
comparisons <- comparisons[-1]
colData = cbind(colnames(rawCounts), groups )
# Set up the DESeqDataSet Object and run the DESeq pipeline
dds = DESeqDataSetFromMatrix(countData=rawCounts,
colData=colData,
design=~groups)
dds = DESeq(dds) # main function
result1 = NULL; allCalls = NULL;
topGenes = list(); pk = 1 # counter
pp=0 # first results?
for( kk in 1:length(comparisons) ) {
tem = unlist( strsplit(comparisons[kk],"-") )
selected = results(dds, contrast=c("groups", tem[1], tem[2]) ) #, lfcThreshold=log2(minFC_limma))
# selected = subset(res, padj < maxP_limma )
if(dim(selected)[1] == 0 ) next; # no significant genes
selected = selected[order(-abs(selected$log2FoldChange)),]
selected$calls =0
selected$calls [which( selected$log2FoldChange > log2(minFC_limma) & selected$padj < maxP_limma ) ] <- 1
selected$calls [ which( selected$log2FoldChange < -log2(minFC_limma) & selected$padj < maxP_limma ) ] <- -1
colnames(selected)= paste( as.character(comparisons[kk]), "___",colnames(selected),sep="" )
selected = as.data.frame(selected)
if (pp==0){ # if first one with significant genes, collect gene list and Pval+ fold