-
Notifications
You must be signed in to change notification settings - Fork 1
/
190507.rdownstream.central.R
executable file
·2313 lines (1887 loc) · 78.1 KB
/
190507.rdownstream.central.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
rm(list=ls())
######################################################################
# helper functions
######################################################################
####################################################################
# binquire() and inquire()
####################################################################
source("~/inquire.R")
# not yet tested
biocUpgrade <- function(){
source("https://bioconductor.org/biocLite.R")
biocLite("BiocUpgrade")
}
detach_package <- function(pkg, character.only = FALSE) {
if(!character.only) {
pkg <- deparse(substitute(pkg))
}
search_item <- paste("package", pkg, sep = ":")
while(search_item %in% search()) {
detach(search_item, unload = TRUE, character.only = TRUE)
}
}
####################################################################
# required packages
####################################################################
binquire(DESeq2) # DE analysis
# inquire(xlsx) # xlsx printing
binquire(edgeR) # DE analysis
binquire(biomaRt) # for Annotations
# for this necessary:
# sudo apt install libssl-dev
binquire(org.Mm.eg.db)
binquire(org.Hs.eg.db)
binquire(GO.db) # for GO analysis
binquire(GOstats) # for GO analysis
binquire(gage) # for KEGG analysis
binquire(gageData)
binquire(KEGG.db)
binquire(annotate)
binquire(genefilter)
binquire(vsn)
# inquire(Cairo) # pdf output
# # necessary:
# # sudo apt install libcairo2-dev libxt-dev
# CairoFonts(
# regular="Arial:style=Regular",
# bold="Arial:style=Bold",
# italic="Arial:style=Italic",
# bolditalic="Arial:style=Bold Italic,BoldItalic",
# symbol="Symbol")
inquire(ggplot2) # for plots
binquire(Glimma) # for interactive plots
#####################################################################
inquire(SummarizedExperiment)
inquire(ggplot2) # for graphics
inquire(reshape) # for graphics
inquire(gplots) # for heatmap
inquire(RColorBrewer) # for heatmap
binquire(pheatmap) # for heatmap
require(gskb) # for gskb
require(clusterProfiler)
require(GenomicFeatures)
require(openxlsx)
require(clusterProfiler)
require(org.Mm.eg.db)
require(plotly)
require(magrittr)
options(java.parameters = "-Xmx3000m")
# https://stackoverflow.com/questions/21937640/handling-java-lang-outofmemoryerror-when-writing-to-excel-from-r
####################################################################
# pseudoannotation
####################################################################
pseudodf <- function(vec) {
df <- data.frame(GeneID = as.character(vec), symbol = as.character(vec), stringsAsFactors=FALSE)
rownames(df) <- as.character(vec)
colnames(df) <- "symbol"
df
}
####################################################################
# non-overlapping gene lengths from gtf
# (required for DGEList obj and normalizations)
# thanks to Irsan # https://www.biostars.org/p/83901/
####################################################################
gtf2gene.length <- function(gtf.path) {
gc()
require(GenomicFeatures)
txdb <- makeTxDbFromGFF(gtf.path, format = "gtf")
exons.list.per.gene <- exonsBy(txdb, by="gene")
exonic.gene.sizes <- as.data.frame(sum(width(reduce(exons.list.per.gene))))
colnames(exonic.gene.sizes) <- "length"
exonic.gene.sizes
}
#####################################################################
# Load openxlsx
#####################################################################
require(openxlsx)
#####################################################################
# list flattener
#####################################################################
once.flatten <- function(obj) unlist(obj, recursive = FALSE)
k.flatten <- function(obj, k) repeated(obj, k, once.flatten)
flatten <- function(obj) unlist(obj)
#####################################################################
# utility function look list elements by head
#####################################################################
lhead <- function(l) lapply(l, head)
#####################################################################
# read xlsx files to dfs list
#####################################################################
xlsx2df.list <- function(xlsx.path, rowNames = TRUE, colNames = TRUE, ...) {
wb <- loadWorkbook(xlsx.path)
sheetNames <- names(wb)
res <- lapply(sheetNames, function(sheetName) {
read.xlsx(wb, sheet = sheetName, rowNames = rowNames, colNames = colNames, ...)
})
names(res) <- sheetNames
res
}
#####################################################################
# printing dfs to xlsx files
#####################################################################
withNames <- function(...) {
# Returns a list constructed by using
# alterning name, obj, name, obj arguments
p.l <- list(...)
len <- length(p.l)
if (len %% 2 == 1) {
stop("withNames call with odd numbers of arguments")
print()
}
seconds <- p.l[seq(2, len, 2)]
firsts <- p.l[seq(1, len, 2)]
names(seconds) <- unlist(firsts)
seconds
}
write.dfs <- function(df.list, fpath) {
wb <- createWorkbook()
Map(function(data, name) {
addWorksheet(wb, name)
writeData(wb, name, data, rowNames = TRUE, colNames = TRUE)
}, df.list, names(df.list))
saveWorkbook(wb, file = fpath, overwrite = TRUE)
}
#####################################################################
# select a df by list of rownames -> df.list
#####################################################################
select.by.names.vec.list <- function(data.df, list.of.names.vecs) {
lapply(list.of.names.vecs, function(names.vec) data.df[names.vec, ])
}
#####################################################################
# Return for a df, its sortings by l2FC, p-val and rownames
#####################################################################
df.sortings <- function(DE.res.df) {
list(l2FC.srt = DE.res.df[order(DE.res.df$log2FoldChange, decreasing = TRUE), ],
p.srt = DE.res.df[order(DE.res.df$pvalue, decreasing = FALSE), ],
names.srt = DE.res.df[order(rownames(DE.res.df), decreasing = FALSE), ])
}
#####################################################################
# print DE sortings
#####################################################################
print.DE.sortings <- function(DE.list, fname, dir = ".") {
DE.list.with.sortings <- lapply(once.flatten(lapply(DE.list, df.sortings)), as.data.frame)
write.dfs(DE.list.with.sortings, file.path(dir, fname))
}
#####################################################################
# print cnts selections of DE
#####################################################################
print.cnts.DE.sortings <- function(cnts, DE.list, fname, dir = ".") {
DE.list.with.sortings <- lapply(once.flatten(lapply(DE.list, df.sortings)),
as.data.frame)
DE.list.with.sortings.names <- lapply(DE.list.with.sortings, rownames)
DE.cnts.list.with.sortings <- select.by.names.vec.list(as.data.frame(cnts),
DE.list.with.sortings.names)
write.dfs(DE.cnts.list.with.sortings, file.path(dir, fname))
}
####################################################################
# helper functions for timestamp
####################################################################
time.now <- function() format(Sys.time(), "%y%m%d%H%M%S")
#####################################################################
# helper functions for averaging tables
#####################################################################
counts.avg.build <- function(cnts.df, cols.list, groups){
cnts.df <- as.data.frame(cnts.df)
ncol_old <- length(colnames(cnts.df))
ncol_limit <- length(groups) + ncol_old
new_col_names <- c(colnames(cnts.df), groups)
cnts.df <- cbind(cnts.df,
lapply(cols.list,
function(idxs) rowMeans(cnts.df[, idxs, drop = FALSE])))
colnames(cnts.df) <- new_col_names
cnts.df[, (ncol_old + 1):ncol_limit]
}
counts.std.build <- function(cnts.df, cols.list, groups){
cnts.df <- as.data.frame(cnts.df)
rowSds <- function(df) apply(df, 1, sd)
ncol_old <- length(colnames(cnts.df))
ncol_limit <- length(groups) + ncol_old
new_col_names <- c(colnames(cnts.df), groups)
cnts.df <- cbind(cnts.df,
lapply(cols.list,
function(idxs) rowSds(cnts.df[, idxs, drop = FALSE])))
colnames(cnts.df) <- new_col_names
cnts.df[, (ncol_old + 1):ncol_limit]
}
scale.raw.counts.with.SD <- function(cnts.DE.sig.fpath, meta.fpath, out.fpath = "") {
# Takes cnts.DE.sig.fpath and meta.fpath and calculates standard deviation
# and puts the new file with '-scaled-avg-' into same path like ctns.DE.sig.fpath.
cnts.DE.sig <- xlsx2df.list(cnts.DE.sig.fpath)[["all.names.srt"]] # xslx2dfs
meta.df <- read.table(meta.fpath, sep = '\t', header = T, stringsAsFactors = F)
meta.df$condition <- factor(meta.df$condition,
levels = unique(meta.df$condition))
cond <- unique(as.character(meta.df$condition))
cond.cols <- lapply(cond,
function(cd) which(as.character(meta.df$condition) == cd))
names(cond.cols) <- cond
cnts.avg <- counts.avg.build(cnts.DE.sig, cond.cols, cond)
std.avg <- counts.std.build(cnts.DE.sig, cond.cols, cond)
scaledata <- t(scale(t(cnts.avg)))
scaled.sds <- std.avg/apply(cnts.avg, 1, sd)
upper.sds.values <- scaledata + scaled.sds
lower.sds.values <- scaledata - scaled.sds
res <- list(scaled_values = scaledata,
scaled_StdDevs = scaled.sds,
upper_SD_values = upper.sds.values,
lower_SD_values = lower.sds.values)
res <- lapply(res, as.data.frame)
if (out.fpath == "") {
out.fpath <- gsub("-cnts-", "-scaled-avg-", cnts.DE.sig.fpath)
}
write.dfs(res, out.fpath) # dfs2xlsx
res
}
# ####################################################################
# Read-in meta.df and indirpath to count-matrix
# ####################################################################
read.tab <- function(fpath) {
read.delim(fpath, sep = "\t", head = F, row.names = 1, stringsAsFactors = F)
}
read.dfs2table <- function(meta.df, indirpath) {
files <- file.path(indirpath, as.character(meta.df$fileName))
df.list <- lapply(files, read.tab)
res.df <- Reduce(cbind, df.list)
names(res.df) <- meta.df$sampleName
res.df
}
# ####################################################################
# Translate vector values
# ####################################################################
translate.vec <- function(values.vec, from.vec, to.vec) {
tr.vec <- to.vec
names(tr.vec) <- from.vec
tr.vec[values.vec]
}
# ####################################################################
# cluster df sorting helper functions
# ####################################################################
# df to list and back ################################################
select_df <- function(df, val, col.selector) {
df[ df[, col.selector] == val, ]
}
df2dflist <- function(df, col.selector) { # actually it is split()
col.vals <- unique(df[, col.selector])
dfl <- lapply(seq(col.vals),
function(i) select_df(df,
val = col.vals[i],
col.selector))
names(dfl) <- col.vals
dfl
}
dflist2df <- function(dfl) {
Reduce(rbind, dfl)
}
# ordering df lists #################################################
order.list.by.col.mean <- function(dfl, col.selector) {
dfl[order(unlist(lapply(dfl, function(df) mean(df[, col.selector]))))]
}
order.list.by.df.function <- function(dfl, df.function, ...) {
dfl[order(unlist(lapply(dfl, function(df) df.function(df, ...))))]
}
list.order.by.col.mean <- function(dfl, col.selector) {
order(unlist(lapply(dfl, function(df) mean(df[, col.selector]))))
}
list.order.manually.by.vec <- function(dfl, vec) {
dfl[vec]
}
repeated.values.into.df.list <- function(dfl, col.selector, vals) {
Map(function(df, val) {df[, col.selector] <- val; df}, dfl, vals)
}
list.order.by.col.mean.diffs <-
function(dfl, col.selector.one, col.selector.two, decreasing = FALSE) {
dfl[order(unlist(lapply(dfl, function(df) mean(df[, col.selector.one]))) -
unlist(lapply(dfl, function(df) mean(df[, col.selector.two]))),
decreasing = decreasing)]
}
#######################################################################
#######################################################################
# create a DESeq2 obj out of
# - path to counts
# - file names in meta.txt
# - (outputpath)
#######################################################################
meta2DESeq2.obj <- function(meta.df, indirpath, normalized=FALSE) {
# require(DESeq2)
count.matrix <- read.dfs2table(meta.df, indirpath)
DESeq2.obj <- DESeqDataSetFromMatrix(
countData = count.matrix,
colData = meta.df,
design = ~ 0 + condition)
if (normalized) {
DESeq2.obj <- estimateSizeFactors(DESeq2.obj)
DESeq2.obj <- estimateDispersions(DESeq2.obj)
}
DESeq2.obj
}
#######################################################################
# create a raw count table out of
# - path to counts
# - file names in meta.txt
# - (outputpath)
# create a DESeq2-normalized table out of
# - path to counts
# - file names in meta.txt
# - (outputpath)
# create an averaged DESeq2-normalized table out of
# - path to counts
# - file names in meta.txt
# - (outputpath)
#######################################################################
meta2cnts <- function(meta.df, DESeq2.obj, outdirpath=".",
dataname = dataname,
printp=FALSE, normalized=FALSE, averaged=FALSE,
sheetName) {
cnts <- counts(DESeq2.obj, normalized=normalized)
if (averaged) {
cond <- unique(as.character(meta.df$condition))
cond.cols <- lapply(cond,
function(cd) which(as.character(meta.df$condition) == cd))
names(cond.cols) <- cond
cnts.avg <- counts.avg.build(cnts, cond.cols, cond)
cnts.sd <- counts.std.build(cnts, cond.cols, cond)
res <- withNames(ifelse(normalized, "nrm-counts-avg", "raw-counts-avg"), cnts.avg,
ifelse(normalized, "nrm-counts-sd", "raw-counts-sd"), cnts.sd)
if (not(printp)) {
return(res)
}
}
if (printp) {
if (averaged) {
filename <- paste0(ifelse(normalized, "nrm-counts-", "raw-counts-"),
"avg-",
dataname, "-", core.name(meta.df), ".xlsx")
write.dfs(res,
file.path(outdirpath, filename))
return(res)
}
filename <- paste0(ifelse(normalized, "nrm-counts-", "raw-counts-"),
ifelse(averaged, "avg-", ""),
dataname, "-", core.name(meta.df), ".xlsx")
write.dfs(withNames(ifelse(normalized, "nrm-counts", "raw-counts"), cnts),
file.path(outdirpath, filename))
}
cnts
}
#######################################################################
# create list of differentially expressed genes
# create list of differentially upregulated genes
# create list of differentially downregulated genes
# print them out
# out of
# path to counts
# file name in meta.txt - metapath
# also for single-rep RNAseq analysis! ("DESeq2")
#######################################################################
DEanalysis <- function(meta.df, DESeq2.obj.disp, outdirpath=".", dataname="",
printp=FALSE, prior.count=0,
alpha=0.05, lFC=1, filterp=FALSE) {
dds <- DESeq(DESeq2.obj)
res <- results(dds, contrast=c("condition", num(meta.df), denom(meta.df)),
cooksCutoff = Inf,
independentFiltering = FALSE) # those two avoid NA!
if (filterp) {
res <- subset(subset(res, padj < alpha), abs(log2FoldChange) > lFC)
}
up <- subset(res, res$log2FoldChange > 0)
down <- subset(res, res$log2FoldChange < 0)
res <- list(all=res, up=up, down=down)
if (printp) {
filecorename <- paste0("DE_", ifelse(filterp, "sig_", ""),
dataname, "_", core.name(meta.df), "_", time.now())
if (filterp) { filecorename <- paste0(filecorename, "_", alpha, "_", lFC) }
filename <- paste0(filecorename, ".xlsx")
print.DE.sortings(res, fname = filename, dir = DE.outdir)
}
res
}
#######################################################################
# create an averaged heatmap and group-pictures out of
# - k
# - (DESeq2 obj OR DEGList obj OR raw count table OR cpm-normalized table OR
# DESeq2-normalized table)
# metapath and indirpath
# - (outputpath)
#######################################################################
meta2heatmap <- function(meta.df, cnts.avg.nrm, resSig, outdirpath=".",
dataname = dataname, selected.genes = NULL, name.add = "", # for showing in name
k = k, printp=FALSE,
alpha = alpha, lFC= lFC, filterp=FALSE,
xlsxp=TRUE, csvp=FALSE, tsvp=FALSE) {
res.names <- rownames(resSig$all)
## if sth given in 'selected.genes': if "up" or "down" use them from resSig, else the vector given:
if (length(selected.genes) > 0) {
if (selected.genes == "up") {
res.names <- rownames(resSig$up)
} else if (selected.genes == "down") {
res.names <- rownames(resSig$down)
} else {
res.names <- selected.genes
}
}
cnts.res <- cnts.avg.nrm[res.names, ]
# gene-wise normalization
scaledata <- t(scale(t(cnts.res)))
scaledata <- scaledata[complete.cases(scaledata), ]
# k means clustering
kClust <- kmeans(scaledata, centers = k, nstart = 1000, iter.max = 30)
kClusters <- kClust$cluster
# function to find centroid (cluster core) in cluster i
clust.centroid <- function(i, dat, clusters) {
ind = (clusters == i)
colMeans(dat[ind, ])
}
kClustcentroids <- sapply(levels(factor(kClusters)),
clust.centroid, scaledata, kClusters) ## is a matrix
# plot centroids
Kmolten <- melt(kClustcentroids)
colnames(Kmolten) <- c("sample", "cluster", "value")
# ensure correct factorizing
Kmolten$sample <- factor(Kmolten$sample,
levels = unique(meta.df$condition))
{
p1 <- ggplot(Kmolten, aes(x=factor(sample, levels = unique(meta.df$condition)),
y=value, group = cluster,
colour=as.factor(cluster))) +
geom_point() +
geom_line() +
xlab("Time") +
ylab("Expression") +
labs(title = "Cluster Expression by Group", color = "Cluster")
png(paste0(outdirpath, "/k", k, "_", core.name(meta.df), paste0("-ClusterAll_", alpha, "_", lFC, "_", time.now(), ".png")))
print(p1)
dev.off()
}
# check similarity of centroids
print(cor(kClustcentroids))
for (i in 1:k) {
# subset cores molten df to plot core
assign(paste0("core", i), Kmolten[Kmolten$cluster == i, ])
eval(parse(text = paste0("core", i, "$sample <- factor(core", i,
"$sample, levels = unique(meta.df$condition))")))
# get clusters
assign(paste0("K", i), scaledata[kClusters == i, ])
# calculate correlation with core
assign(paste0("corescore", i),
eval(parse(text = paste0("function(x) {cor(x, core", i, "$value)}"))))
assign(paste0("score", i),
eval(parse(text = paste0("apply(K", i, ", 1, corescore", i, ")"))))
# get data frame into long format for plotting
assign(paste0("K", i, "molten"),
eval(parse(text = paste0("melt(K", i, ")"))))
eval(parse(text = paste0("colnames(K", i, "molten) <- c('gene', 'sample', 'value')")))
# add the score
eval(parse(text = paste0("K", i, "molten <- merge(K", i, "molten, score", i, ", by.x = 'gene', by.y = 'row.names', all.x = T)")))
eval(parse(text = paste0("colnames(K", i, "molten) <- c('gene', 'sample', 'value', 'score')")))
# order
eval(parse(text = paste0("K", i, "molten <- K", i, "molten[order(K", i, "molten$score), ]")))
}
# plot cluster groups
for (i in 1:k) {
text = paste0("sp", i, " <- ggplot(K", i, "molten, aes(x=factor(sample,",
" levels=unique(meta.df$condition)), y=value)) + ",
"geom_line(aes(colour=score, group=gene)) + ",
"scale_color_gradientn(colours=c('blue1', 'red2')) + ",
# this adds the core
"geom_line(data=core", i, ", aes(sample,value,group=cluster), ",
"color='black', inherit.aes=FALSE) + ",
"xlab('Time') + ",
"ylab('Expression') + ",
"labs(title='Cluster ", i, " Expression by Group', color = 'Score'); ",
"png('", outdirpath, "/k", k, "_", core.name(meta.df), "-Cluster", i, "_", dataname, "_", alpha, "_", lFC, name.add, ".png'); ",
"print(sp", i, "); dev.off()"
)
eval(parse(text = text))
}
# prepare heatmap
colors.kr <- colorRampPalette(c("black", "red"))(100)
# colors.kgr <- colorRampPalette(c("black", "grey88", "red"))(100)
eval(parse(text = paste0("scores <- c(", paste(paste("score", 1:k, sep = ''),
collapse = ", "), ")")))
# add cluster number and score for sorting the data
scaledata.k <-cbind(scaledata,
cluster = kClust$cluster,
score = scores[rownames(scaledata)])
scaledata.k <- scaledata.k[order(scaledata.k[, "cluster"], scaledata.k[, "score"]), ]
# outpath
outname <- file.path(outdirpath, paste0("k", k, "_khmap_", dataname, "_", time.now(), "_UO_", alpha, "_", lFC, name.add))
# for gaps
gaps.idxs <- cumsum(table(scaledata.k[, "cluster"])) # scaledata.k is one matrix! only column 'cluster'
# dim(scaledata.k)
# unordered clusters
##################
# black to red
##################
{
svg(paste0(outname, ".svg"))
pheatmap(scaledata.k[, 1:length(unique(meta.df$condition))],
cluster_rows = F,
cluster_cols = F,
cellwidth = 40,
col = colors.kr,
fontsize_row = 0.5,
border_color = NA,
gaps_row = gaps.idxs # gap after each block
)
dev.off()
}
{
setEPS()
postscript(paste0(outname, ".eps"))
pheatmap(scaledata.k[, 1:length(unique(meta.df$condition))],
cluster_rows = F,
cluster_cols = F,
cellwidth = 40,
col = colors.kr,
fontsize_row = 0.5,
border_color = NA,
gaps_row = gaps.idxs # gap after each block
)
dev.off()
}
# ##################
# # black grey red
# ##################
#
# {
# svg(paste0(outname, "kgr.svg"))
# pheatmap(scaledata.k[, 1:length(unique(meta.df$condition))],
# cluster_rows = F,
# cluster_cols = F,
# cellwidth = 40,
# col = colors.kgr,
# fontsize_row = 0.5,
# border_color = NA,
# gaps_row = gaps.idxs # gap after each block
# )
# dev.off()
# }
#
# {
# setEPS()
# postscript(paste0(outname, "kgr.eps"))
# pheatmap(scaledata.k[, 1:length(unique(meta.df$condition))],
# cluster_rows = F,
# cluster_cols = F,
# cellwidth = 40,
# col = colors.kgr,
# fontsize_row = 0.5,
# border_color = NA,
# gaps_row = gaps.idxs # gap after each block
#
# )
# dev.off()
# }
#
# print scaledata
scaledata_list <- df2dflist(scaledata.k, "cluster")
outfname <- paste0(outname, '.xlsx')
names(scaledata_list) <- paste("cluster", 1:k, sep = "")
write.dfs(scaledata_list, outfname)
eval(parse(text = paste0("Kmolten.list <- list(", paste(paste("K", 1:k, "molten", sep = ''), collapse = ", "), ")")))
names(Kmolten.list) <- paste("K", 1:k, "molten", sep = '')
eval(parse(text = paste0("core.list <- list(", paste(paste("core", 1:k, sep = ''), collapse = ", "), ")")))
names(Kmolten.list) <- paste("core", 1:k, sep = '')
eval(parse(text = paste0("score.list <- list(", paste(paste("score", 1:k, sep = ''), collapse = ", "), ")")))
names(Kmolten.list) <- paste("score", 1:k, sep = '')
data <- list(scaledata_list, Kmolten.list, core.list, score.list)
names(data) <- c("scaledata_list", "Kmolten.list", "core.list", "score.list")
saveRDS(data, file = paste0(outdirpath, "/scaledata.Kmolten.core.score.list.", dataname, ".", time.now(), ".", name.add, ".rds"))
data
}
#######################################################################
# create an averaged heatmap and group-pictures out of
# unordered list (xlsx) and an ordervector
# - path to unordered .xlsx file
# - ordervector
# - outpath
#######################################################################
unordered2orderedheatmap <- function(UO.heatmap.path, order.vec, outdirpath=".",
sheet="all", gaps.after.blocks=c(),
alpha=alpha, lFC=lFC, dataname=dataname) {
dfl <- xlsx2df.list(UO.heatmap.path)
# remove 'all' sheet
all.idx <- which(names(dfl) == "all")
if (length(all.idx > 0)) {
dfl <- dfl[-all.idx]
}
# within cluster sort by score
dflsc <- lapply(dfl, function(df) df[order(df[, "score"]), ])
dflo <- list.order.manually.by.vec(dflsc, order.vec)
k <- length(dfl)
names(dflo) <- 1:k
dflo.corr <- repeated.values.into.df.list(dflo, "cluster", 1:k)
scaledata.k.ordered <- dflist2df(dflo.corr)
if (length(gaps.after.blocks) > 0) {
gaps_idxs <- cumsum(unlist(lapply(df2dflist(scaledata.k.ordered, "cluster"),
function(df) dim(df)[1])))
gaps_idxs <- gaps_idxs[gaps.after.blocks]
}
dir.create(outdirpath, recursive = T, showWarnings = F)
outname <- file.path(outdirpath, paste0("k", k, "_khmap_", dataname, "_", time.now(), "_O_", alpha, "_", lFC))
outfname <- paste0(outname, ".xlsx")
colfunc <- colorRampPalette(c("black", "red"))
{
setEPS()
postscript(paste0(outname, ".eps"))
# svg(paste0(outname, ".svg"))
pheatmap(scaledata.k.ordered[, 1:(length(colnames(dfl[[1]]))-2)], # without cluster scores
cluster_rows = F,
cluster_cols = F,
cellwidth = 40,
gaps_row = ifelse(length(gaps.after.blocks) > 0, list(gaps_idxs), list(dim(df)[1]))[[1]],
border_color = NA,
col = colfunc(100),
fontsize_row = 0.5
)
dev.off()
}
{
svg(paste0(outname, ".svg"))
pheatmap(scaledata.k.ordered[, 1:(length(colnames(dfl[[1]]))-2)], # without cluster scores
cluster_rows = F,
cluster_cols = F,
cellwidth = 40,
gaps_row = ifelse(length(gaps.after.blocks) > 0, list(gaps_idxs), list(dim(df)[1]))[[1]],
border_color = NA,
col = colfunc(100),
fontsize_row = 0.3
)
dev.off()
}
scaledata_list <- df2dflist(scaledata.k.ordered, "cluster")
names(scaledata_list) <- paste("cluster", 1:k, sep = "")
write.dfs(scaledata_list, outfname)
}
UO2O.hm <- function(filepath, s.K.c.s.list, order.vec, outdirpath=".",
sheet="all", gaps.after.blocks=c(),
alpha=alpha, lFC=lFC, dataname=dataname) {
colfunc <- colorRampPalette(c("black", "red"))
if (filepath == "") {
scaledata.Kmolten.core.score.list <- s.K.c.s.list
} else if (endsWith(filepath, suffix = ".rds")) {
scaledata.Kmolten.core.score.list <- readRDS(filepath)
} else {
load_obj <- function(f) {
env <- new.env()
nm <- load(f, env)[1]
env[[nm]]
}
scaledata.Kmolten.core.score.list <- load_obj(filepath)
}
scaledata_list <- scaledata.Kmolten.core.score.list$scaledata_list
new.scaledata <- list.order.manually.by.vec(scaledata_list, order.vec)
k <- length(scaledata_list)
names(new.scaledata) <- 1:k
new.scaledata.corr <- repeated.values.into.df.list(new.scaledata, "cluster", 1:k)
scaledata.k.ordered <- dflist2df(new.scaledata.corr)
if (length(gaps.after.blocks) > 0) {
gaps_idxs <- cumsum(unlist(lapply(df2dflist(scaledata.k.ordered, "cluster"),
function(df) dim(df)[1])))
gaps_idxs <- gaps_idxs[gaps.after.blocks]
}
outname <- file.path(outdirpath, paste0("k", k, "_khmap_", dataname, "_", time.now(), "_O_", alpha, "_", lFC))
outfname <- paste0(outname, ".xlsx")
df <- scaledata_list[[1]] # exemplarisches df
{
# setEPS()
# postscript(paste0(outname, ".eps"))
svg(paste0(outname, ".svg"))
pheatmap(scaledata.k.ordered[, 1:(length(colnames(df))-2)], # without cluster scores
cluster_rows = F,
cluster_cols = F,
cellwidth = 40,
gaps_row = ifelse(length(gaps.after.blocks) > 0, list(gaps_idxs), list(dim(df)[1]))[[1]],
border_color = NA,
col = colfunc(100),
fontsize_row = 0.5
)
dev.off()
}
{
svg(paste0(outname, ".svg"))
pheatmap(scaledata.k.ordered[, 1:(length(colnames(df))-2)], # without cluster scores
cluster_rows = F,
cluster_cols = F,
cellwidth = 40,
gaps_row = ifelse(length(gaps.after.blocks) > 0, list(gaps_idxs), list(dim(df)[1]))[[1]],
border_color = NA,
col = colfunc(100),
fontsize_row = 0.3
)
dev.off()
}
scaledata_list <- df2dflist(scaledata.k.ordered, "cluster")
names(scaledata_list) <- paste("cluster", 1:k, sep = "")
write.dfs(scaledata_list, outfname)
Kmolten.list <- scaledata.Kmolten.core.score.list$Kmolten.list
new.Kmolten.list <- Kmolten.list[order.vec]
names(new.Kmolten.list) <- paste("K", 1:k, "molten", sep = '')
for (i in 1:k) {
eval(parse(text = paste0("K", i, "molten <- new.Kmolten.list[[", i, "]]")))
}
core.list <- scaledata.Kmolten.core.score.list$core.list
new.core.list <- core.list[order.vec]
names(new.core.list) <- paste("core", 1:k, sep = '')
for (i in 1:k) {
eval(parse(text = paste0("core", i, " <- new.core.list[[", i, "]]")))
}
if (endsWith(filepath, suffix = ".rds")) {
score.list <- scaledata.Kmolten.core.score.list$score.list
new.score.list <- score.list[order.vec]
names(new.score.list) <- paste("score", 1:k, sep = '')
for (i in 1:k) {
eval(parse(text = paste0("score", i, " <- new.score.list[[", i, "]]")))
}
}
# plot cluster groups
for (i in 1:k) {
text = paste0("sp", i, " <- ggplot(K", i, "molten, aes(x=factor(sample,",
" levels=unique(meta.df$condition)), y=value)) + ",
"geom_line(aes(colour=score, group=gene)) + ",
"scale_color_gradientn(colours=c('blue1', 'red2')) + ",
# this adds the core
"geom_line(data=core", i, ", aes(sample,value,group=cluster), ",
"color='black', inherit.aes=FALSE) + ",
"xlab('Time') + ",
"ylab('Expression') + ",
"labs(title='Cluster ", i, " Expression by Group', color = 'Score'); ",
"png('", outdirpath, "/k", k, "_", core.name(meta.df), "-Cluster", i, "_", dataname, "_", alpha, "_", lFC, ".png'); ",
"print(sp", i, "); dev.off()"
)
eval(parse(text = text))
}
}
#######################################################################
# MDS plot, iMDS plot
# - metapath
# - indirpath
# - lFC, alpha
# - method
# - outdirpath
#######################################################################
meta2iMDSplot <- function(meta.df, DESeq2.obj.disp, outdirpath=".",
dataname = dataname, top=500,
launch = TRUE) {
title <- paste0("MDS Plot ", dataname, " ", time.now())
filename <- paste0("iMDS_", dataname, "_", core.name(meta.df), "_", time.now(), "_DESeq2", collapse = "_")
glMDSPlot(DESeq2.obj,
top = top,
path = outdirpath,
main = title,
html = filename,
launch = launch
)
}
#######################################################################
# volcano plot, iVolcano Plot, MD plot, iMD plot
# - metapath
# - indirpath
# - lFC, alpha
# - method
# - outdirpath
#######################################################################
meta2iVolcano <- function(meta.df, DESeq2.obj, DESeq2.obj.disp, outdirpath=".",
dataname= dataname,
lFC=lFC, alpha=alpha, launch = TRUE) {
wald.test <- nbinomWaldTest(DESeq2.obj.disp)
res.DESeq2 <- results(wald.test, alpha=alpha, pAdjustMethod = "BH",
contrast = c("condition", num(meta.df), denom(meta.df)),
cooksCutoff = Inf,
independentFiltering = FALSE) # avoid NA in padj
title <- paste0("Volcano Plot ", dataname, " ", time.now())
filename <- paste0("iVolcano_", dataname, "_", core.name(meta.df), "_", time.now(), "_", alpha, "_", lFC, "_DESeq2")
{
# remove NAs in status vector
status.vec <- ifelse(abs(res.DESeq2$log2FoldChange) > lFC &
res.DESeq2$padj < alpha, 1, 0)
status.vec[is.na(status.vec)] <- 0
glXYPlot(x=res.DESeq2$log2FoldChange, y=-log10(res.DESeq2$pvalue),
counts = counts(DESeq2.obj)[rownames(res.DESeq2), ],
anno = pseudodf(rownames(counts(DESeq2.obj))),
groups = meta.df$condition,
samples = meta.df$sampleName,
xlab = "log2FC",
ylab = "log10padj",
main = title,
status = status.vec,
side.main = "symbol",
side.xlab = "Group",
side.ylab = "Counts",
path = outdirpath,
html = filename,
launch = launch)
}
title <- paste0("iMD Plot ", dataname, " ", time.now())
filename <- paste0("iMD_", dataname, "_", core.name(meta.df), "_", time.now(), "_DESeq2")
{
# remove NAs in status vector
status.vec <- ifelse(abs(res.DESeq2$log2FoldChange) > lFC &
res.DESeq2$padj < alpha, 1, 0)
status.vec[is.na(status.vec)] <- 0
glMDPlot(x = res.DESeq2,
counts = counts(DESeq2.obj)[rownames(res.DESeq2), ],
anno = pseudodf(rownames(counts(DESeq2.obj))), # GeneID and symbol as col
groups = factor(meta.df$condition, levels=unique(meta.df$condition)),
samples = meta.df$sampleName,
ylab = "log2FC",
xlab = "Average log10 CPM",
main = title,
status = status.vec,
side.xlab = "Group",
side.ylab = "Counts",
side.main = "symbol",
path = outdirpath,
html = filename,
launch = launch)
}
}
#####################################################################