-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.R
2265 lines (1991 loc) · 81.8 KB
/
helper.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
# after ensembl query
# remove duplicated entries if any
# replace NA with original ensembl_gene_id
convert_mouse_ensembl_to_mgi_symbol <- function(ensembl_gene_id){
ensembl <- useMart("ensembl", dataset = "mmusculus_gene_ensembl")
val <- ensembl_gene_id
out <- getBM(attributes=c('ensembl_gene_id', "mgi_symbol"),
filters = 'ensembl_gene_id',
values = val,
mart = ensembl)
unmatched <- genelist[! genelist %in% res[,1] ]
unmatched <- cbind(unmatched, toupper(unmatched))
colnames(unmatched) <- colnames(res)
res <- rbind(res, unmatched)
# resort the result to match original order
idx <- match(genelist, res[,1])
return(res[idx, ])
return(out)
}
convert_mouse_gene_to_human_gene_symbol <- function(genelist){
human = useMart("ensembl", dataset = "hsapiens_gene_ensembl")
mouse = useMart("ensembl", dataset = "mmusculus_gene_ensembl")
#human = useMart("ENSEMBL_MART_ENSEMBL", dataset = "hsapiens_gene_ensembl")
#mouse = useMart("ENSEMBL_MART_ENSEMBL", dataset = "mmusculus_gene_ensembl")
res <- getLDS(attributes = c("mgi_symbol"),
filters = "mgi_symbol",
values = genelist,
mart = mouse,
attributesL = c("hgnc_symbol"),
martL = human
)
unmatched <- genelist[! genelist %in% res[,1] ] %>% unlist() %>% as.character()
unmatched <- cbind(unmatched, toupper(unmatched))
colnames(unmatched) <- colnames(res)
res <- rbind(res, unmatched)
# resort the result to match original order
idx <- match(genelist, res[,1])
return(res[idx, ])
}
#' A Cat Function
#'
#' This function allows you to express your love of cats.
#' @param love Do you love cats? Defaults to TRUE.
#' @keywords cats
#' @export
#' @examples
#' cat_function()
create.brewer.color <- function(data, num=8, name="Set1")
{
if(name=="naikai"){
my_pallete <- c(
rgb(236,67,35, maxColorValue=255),
rgb(56,146,208, maxColorValue=255),
rgb(230,235,88, maxColorValue=255),
rgb(116,187,88, maxColorValue=255),
rgb(196,95,46, maxColorValue=255),
rgb(203,77,202, maxColorValue=255),
rgb(118,220,65, maxColorValue=255),
rgb(115,113,206, maxColorValue=255))
return(create.manual.color(data, my_pallete))
}else if(name=="naikai2"){
my_pallete <- c(
rgb(10,10,10, maxColorValue=255),
rgb(230,235,88, maxColorValue=255),
rgb(118,220,65, maxColorValue=255),
rgb(203,77,202, maxColorValue=255),
rgb(196,95,46, maxColorValue=255),
rgb(116,187,88, maxColorValue=255),
rgb(236,67,35, maxColorValue=255),
rgb(56,146,208, maxColorValue=255),
rgb(115,113,206, maxColorValue=255))
return(create.manual.color(data, my_pallete))
}else if(name=="cellline"){
my_pallete <- c(
"#89EB6B",
"#349B1B",
"#FF7265",
"#DA364D",
"#6099FF",
"#2256DB",
"#BEBADA",
"#00006D",
rgb(230,235,88, maxColorValue=255),
rgb(118,220,65, maxColorValue=255),
rgb(203,77,202, maxColorValue=255),
rgb(196,95,46, maxColorValue=255),
rgb(116,187,88, maxColorValue=255),
rgb(236,67,35, maxColorValue=255),
rgb(56,146,208, maxColorValue=255),
rgb(115,113,206, maxColorValue=255))
return(create.manual.color(data, my_pallete))
}else{
groupCodes <- as.factor(data)
colorCodes <- colorRampPalette(brewer.pal(num, name))(num)
color.idx <- match(groupCodes, levels(groupCodes))
label.color <- colorCodes[color.idx]
return(label.color)
}
}
#' Manually specify coloring for provided groups
#'
#' Assign colors to data, if more unique data than provided colors, will impute the missing ones and fill them in
#' @param data data
#' @param group.color colors for each factorial group
#' @keywords color manual
#' @export
#' @examples
#' create.manual.color(c(1,2,3,1,2,3,2,3), c("red", "blue", "green"))
create.manual.color <- function(data, group.color)
{
num_uniq_data <- length(unique(data))
if(num_uniq_data > length(group.color)){
require(RColorBrewer)
group.color <- colorRampPalette(group.color)(num_uniq_data)
}
data <- as.numeric(factor(data))
return(group.color[data])
}
#' Check rownames from data and auto detect which platform it is from
#'
#' Basically we want to convert those affy metrix array data and just
#' leave normal gene_symbols intact
#' @param data Gene list you want to convert
#' @keywords standardize
#' @export
#' @examples
#' detect_genecnt_platform("TP53")
detect_genecnt_platform <- function(data, method="mean"){
require("annotate")
require(magrittr)
PROBES <- as.character(rownames(data))
num.genes <- nrow(data)
# for now just use simple nrow as check point
if(num.genes == 22283){
require(hgu133a.db) # 22283 probes
GPL="GPL96"
print ("Guess it's hgu133a")
}else if(num.genes == 22645){
require(hgu133b.db) # 22645 probes
GPL="GPL97"
print ("Guess it's hgu133b")
}else if(num.genes == 54675 || num.genes == 44137){
require(hgu133plus2.db) # 54675 probes
# hard fix here for now, need to add mapped rownames to all these probe.annotation and then decide which one
GPL="GPL570"
print ("Guess it's hgu133plus2")
}else if(num.genes == 22277){
require(hgu133a2.db)
GPL="GPL571"
print ("Guess it's hgu133a2")
}else{
print ("Guess its normal RNA-Seq, do nothing")
return(data)
}
if(method == "mean"){
select.fun <- function(x) rowMeans(x)
}else if(method == "sd"){
select.fun <- function(x) rowSds(x)
}else if(method == "max"){
select.fun <- function(x) rowMax(x)
}else if(method == "min"){
select.fun <- function(x) rowMin(x)
}else if(method == "iqr"){
select.fun <- function(x) apply(x, 1, IQR)
}
# There are two levels of mutliple mapping
# one is that each probe_ids may have multiple mapped gene_symbols
# For now, we just select the first gene_symbols if there are multiples
gene.symbols <- affy_probe_to_gene_symbol(PROBES, GPL) %>%
filter(!duplicated(PROBEID)) %>%
dplyr::select(SYMBOL) %>%
unlist
# Another place is that there may be multiple probes designed for each gene
# Now we select the probes with the max(mean expression across samples)
# Mayb fix it later by adding more different filter selections? Ray. 2015-10-30
data.gene <- data %>% as.data.table %>%
'['(, RowExp := select.fun(.SD)) %>%
'['(, SYMBOL := gene.symbols) %>% group_by(., SYMBOL) %>%
filter(., which.max(RowExp))
# Remove rows without gene_symbols (NAs), then convert back to data.frame
final.data <- data.gene %>%
filter(!is.na(SYMBOL)) %>%
setDF %>%
set_rownames(.$SYMBOL) %>%
'['(, !(colnames(.) %in% c("RowExp", "SYMBOL")))
return(final.data)
}
#' A Cat Function
#'
#' This function allows you to read data with fread (faster)
#' @param love Do you love cats? Defaults to TRUE.
#' @keywords cats
#' @export
#' @examples
#' cat_function()
# plot tSNE result
myfread.table <- function(filepath, check.platform=T, header=T, sep="\t", detect.file.ext=T){
require(data.table)
require(tools)
require(magrittr)
ext <- file_ext(filepath)
if(detect.file.ext){
if (ext=="csv"){
sep=","
}else if (ext=="out" || ext=="tsv" || ext=="txt"){
sep="\t"
}else{
warning("File format doesn't support, please try again")
return(NULL)
}
}
header <- read.table(filepath, nrows = 1, header = FALSE, sep=sep, stringsAsFactors = FALSE)
first_data <- read.table(filepath, nrows=1, sep=sep, skip=1)
if(length(header)==length(first_data)){
cols <- c("character", rep("numeric", length(header)-1))
}else if(length(header)==length(first_data)-1){
cols <- c("character", rep("numeric", length(header)))
}
rawdata <- fread(filepath, header=F, sep=sep, skip=1, colClasses=cols)
### Again. Add more checking in case there are duplicate rownames
# read in the first column and check, if there is duplicated rownames (mostly gene names)
# then send out a warning and then make it unique
if(sum(duplicated(rawdata$V1))>0){
warning("There are duplicated rownames in your data")
warning("Please double check your gene count table")
rawdata$V1 <- make.names(rawdata$V1, unique=TRUE)
}
### Add more checking in case there are duplicated column names
# make.names(names, unique=TRUE)
rawdata %<>% setDF %>% set_rownames(.$V1) %>%
'['(colnames(.) != "V1") #%>% as.numeric
# data doesn't have colnames for first row (rownames)
if(length(header) == dim(rawdata)[2]){
# colnames(rawdata) <- unlist(header)
colnames(rawdata) <- make.names(unlist(header), unique=TRUE)
}else if (length(header) == dim(rawdata)[2] + 1){
# colnames(rawdata) <- unlist(header)[-1]
colnames(rawdata) <- make.names(unlist(header)[-1], unique=TRUE)
}
# Add checking data platform
if(check.platform){
rawdata <- detect_genecnt_platform(rawdata)
}
return(rawdata)
}
rpm <- function(data, mapped_reads){
data <- t(t(data)/mapped_reads*1000000)
}
run_DESeq2 <- function(countData, annot, column="Time"){
require(DESeq2)
register(BiocParallel::MulticoreParam(8))
group <- dplyr::pull(annot, column) %>% factor()
coldat <- DataFrame(grp = group)
ddsfeatureCounts <- DESeqDataSetFromMatrix(countData = countData,
colData = coldat,
design = ~ grp)
dds <- DESeq2::DESeq(ddsfeatureCounts, parallel=T)
detach("package:DESeq2")
return(dds)
}
run_DESeq2_norep <- function(countData, annot, column="Time"){
require(DESeq2)
register(BiocParallel::MulticoreParam(8))
group <- dplyr::pull(annot, column) %>% factor()
coldat <- DataFrame(grp = group)
ddsfeatureCounts <- DESeqDataSetFromMatrix(countData = countData,
colData = coldat,
design = ~ grp)
rld <- rlogTransformation( dds )
res <- data.frame(assay(rld),
avgLogExpr = ( assay(rld)[,2] + assay(rld)[,1] ) / 2,
rLogFC = assay(rld)[,2] - assay(rld)[,1] )
#dds <- DESeq2::DESeq(ddsfeatureCounts, parallel=T)
detach("package:DESeq2")
return(res)
}
run_DESeq <- function(countData, annot, column="Time"){
require(DESeq)
group <- dplyr::pull(annot, column) %>% factor()
y <- newCountDataSet(countData, group)
y <- estimateSizeFactors(y)
y <- estimateDispersions(y, fitType="local")
# result <- nbinomTest(y, 2, 1)
detach("package:DESeq")
return(y)
}
run_DESeq_norep <- function(countData, annot, column="Time"){
require(DESeq)
group <- dplyr::pull(annot, column) %>% factor()
y <- newCountDataSet(countData, group)
y <- estimateSizeFactors(y)
y <- estimateDispersions(y, fitType="local", method="blind",sharingMode="fit-only")
# result <- nbinomTest(y, 2, 1)
detach("package:DESeq")
return(y)
}
run_edgeR <- function(countData, annot, column="Time", method="TMM"){
require(edgeR)
group <- dplyr::pull(annot, column) %>% factor()
y <- DGEList(counts=countData,
group=group,
genes=rownames(countData))
y <- calcNormFactors(y)
y <- estimateDisp(y, method=method)
#y <- estimateTagwiseDisp(y)
detach("package:edgeR")
return(y)
}
run_edgeR_norep <- function(countData, annot, column="Time", method="TMM"){
require(edgeR)
group <- dplyr::pull(annot, column) %>% factor()
y <- DGEList(counts=countData,
group=group,
genes=rownames(countData))
y <- calcNormFactors(y)
y <- estimateDisp(y, method=method)
#y <- estimateTagwiseDisp(y)
detach("package:edgeR")
return(y)
}
run_voom <- function(countData, annot, column="Time"){
require(edgeR)
y <- DGEList(counts=countData)
y <- calcNormFactors(y) # Scale normalization
#group <- dplyr::pull(annot, column) %>% rev() %>% factor()
group <- dplyr::pull(annot, column) %>% factor(., levels=unique(.) %>% rev)
design <- model.matrix(~ group)
v <- voom(y, design, plot=TRUE)
fit <- lmFit(v,design)
fit <- eBayes(fit)
detach("package:edgeR")
return(fit)
}
run_voom_norep <- function(countData, annot, column="Time"){
require(edgeR)
y <- DGEList(counts=countData)
y <- calcNormFactors(y) # Scale normalization
group <- dplyr::pull(annot, column) %>% rev() %>% factor()
#design <- model.matrix(~ group)
v <- voom(y, plot=TRUE)
fit <- lmFit(v)
fit <- eBayes(fit)
detach("package:edgeR")
return(fit)
}
run_DESeq2_sizefctr <- function(countData, annot, column="Time", control.idx=NULL){
require(DESeq2)
register(BiocParallel::MulticoreParam(8))
group <- dplyr::pull(annot, column) %>% factor()
coldat <- DataFrame(grp = group)
ddsfeatureCounts <- DESeqDataSetFromMatrix(countData = countData,
colData = coldat,
design = ~ grp)
if(is.numeric(control.idx)){
if(sum(is.na(countData[control.idx, ])) == 0){
dds <- estimateSizeFactors(ddsfeatureCounts, controlGenes=house.idx)
dds <- estimateDispersions(dds)
dds <- nbinomWaldTest(dds)
}else{
warnings("### Not all the index in control.idx are found")
}
}else{
dds <- DESeq2::DESeq(ddsfeatureCounts, parallel=T)
}
detach("package:DESeq2")
return(dds)
}
run_edgeR_sizefctr <- function(countData, annot, column="Time", method="TMM"){
require(edgeR)
group <- dplyr::pull(annot, column) %>% factor()
y <- DGEList(counts=countData,
group=group,
genes=rownames(countData))
y <- calcNormFactors(y, method=method)
y <- estimateCommonDisp(y)
y <- estimateTagwiseDisp(y)
detach("package:edgeR")
return(y)
}
# summary for volcane, logfc, and waterfall plots
sgRNA_summary_plot <- function(deseq2.res, prefix = "sgRNA", n.water.genes=30){
deseq2.plot.res <- deseq2.res %>%
as.data.frame() %>%
as_tibble() %>%
mutate(Gene = rownames(deseq2.res),
log2FC = log2FoldChange) %>%
dplyr::select(Gene, log2FC, padj)
pdf(paste0(prefix, ".Volcano.pdf"), height=10, width=10)
plot_de_res_volcano(deseq2.plot.res, title = prefix)
dev.off()
pdf(paste0(prefix, ".log2FC.pdf"), height=10, width=10, title=prefix)
plot_de_res_log2FC(deseq2.plot.res, ymin = -12, ymax=10)
dev.off()
tmp <- deseq2.plot.res %>%
filter(padj <= 0.5) %>%
arrange(log2FC)
if(nrow(tmp) >= 30){
pdf(paste0(prefix, ".waterfall.pdf"), height=8, width=10, title=prefix)
genelist <- bind_rows(head(tmp, n.water.genes), tail(tmp, n.water.genes)) %>% pull(Gene)
plot_de_res_waterfall(deseq2.plot.res, genelist=genelist)
dev.off()
}else{
warnings("### Not enough genes pass through the p.adj filter")
}
}
# volcano
plot_de_res_volcano <- function(de.res, n.genes=10, color="red", title=""){
# select top n padj, top10 log2FC, top10 -log2FC genes to label
filter.res <- bind_rows(top_n(de.res, n.genes, -padj),
top_n(filter(de.res, is.finite(log2FC)), n.genes, log2FC),
top_n(filter(de.res, is.finite(log2FC)), n.genes, -log2FC)) %>%
distinct(Gene, .keep_all = TRUE)
if(nrow(filter.res) >= 100){
filter.res <- filter.res %>%
arrange(abs(log2FC)) %>%
dplyr::slice(1:50)
}
xlim.range <- de.res$log2FC %>% range %>% abs %>% max %>% round() %>% "+"(3)
r_volcano <- de.res %>%
ggplot(aes(x=log2FC, -log10(padj), label=Gene)) +
geom_point(alpha=0.6) +
geom_point(data = filter.res, col=color, alpha=0.6) +
theme_bw() +
xlim(-xlim.range, xlim.range) +
ggtitle(title)
r_volcano_label <- r_volcano +
geom_text_repel(data= filter.res,
aes(label=Gene), size=2, col="gray15",
point.padding = 0.6)
print(r_volcano)
print(r_volcano_label)
}
plot_de_res_log2FC <- function(de.res, n.genes=10, color="red", title="", ymin=-6, ymax=6){
# color <- "red"
# n.genes <- 10
de.res <- arrange(de.res, log2FC) %>%
mutate(index = 1:nrow(.))
sig.res <- top_n(de.res, n.genes, -padj)
if(nrow(sig.res) >= 30){
sig.res <- sig.res %>%
arrange(abs(log2FC)) %>%
dplyr::slice(1:30)
}
top.res <- bind_rows(top_n(filter(de.res, is.finite(log2FC)), n.genes, log2FC),
top_n(filter(de.res, is.finite(log2FC)), -n.genes, log2FC)) %>%
distinct(Gene, .keep_all = TRUE)
if(nrow(top.res) >= 30){
top.res <- top.res %>%
arrange(abs(log2FC)) %>%
dplyr::slice(1:30)
}
r_log2FC <- de.res %>%
ggplot(aes(x=index, y=log2FC)) +
geom_point(size=1, alpha=0.5) +
geom_point(data = top.res, col="orange", alpha=0.6) +
geom_point(data = sig.res, col=color, alpha=0.9) +
theme_classic() +
geom_hline(yintercept = c(0), linetype="solid", lwd=0.2) +
geom_hline(yintercept = c(-1, 1), linetype="longdash", lwd=0.2) +
ylim(c(ymin, ymax)) +
xlab("") +
ylab(paste0("log2FoldChange( ", prefix, " )")) +
ggtitle(title)
r_log2FC_label <- r_log2FC +
geom_text_repel(data= sig.res,
aes(label=Gene), size=3, col=color,
point.padding = 1) +
geom_text_repel(data= top.res,
aes(label=Gene), size=2, col="gray15",
point.padding = 1)
print(r_log2FC)
print(r_log2FC_label)
}
# random pick 100 genes
plot_de_res_waterfall <- function(de.res, genelist, title="", size=3){
water.de.res <- filter(de.res, Gene %in% genelist) %>%
arrange(log2FC) %>%
mutate(index = 1:nrow(.)) %>%
#mutate(Group = gsub("-.*", "", Gene))
mutate(Group = gsub("\\..*", "", Gene))
ylim.range <- water.de.res$log2FC %>% abs %>% max %>% round() %>% "+"(3)
r_waterfall <- water.de.res %>%
ggplot(aes(x=index, y=log2FC)) +
geom_bar(stat="identity",
width=0.7,
position = position_dodge(width=0.4)) +
ggtitle(title) +
xlab("") +
ylab(paste0("log2FoldChange( ", prefix, " )")) +
theme_classic() +
theme(axis.line.x = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_text(size=size + 10),
axis.ticks.x = element_blank(),
axis.title.y = element_text(face="bold",angle=90)) +
coord_cartesian(ylim = c(-ylim.range, ylim.range))
r_waterfall_label1 <- r_waterfall +
geom_text(data = subset(water.de.res, log2FC >= 0), aes(label=Gene), angle = 90, vjust=0.5, hjust=-0.2, size=size) +
geom_text(data = subset(water.de.res, log2FC < 0), aes(label=Gene), angle = 90, vjust=0.5, hjust=1.2, size=size)
r_waterfall <- water.de.res %>%
ggplot(aes(x=index, y=log2FC, fill=Group)) +
geom_bar(stat="identity",
width=0.7,
position = position_dodge(width=0.4)) +
scale_fill_manual(values = colorRampPalette(brewer.pal(9, "Set1"))(length(genelist))) +
ggtitle(title) +
xlab("") +
ylab(paste0("log2FoldChange( ", prefix, " )")) +
theme_classic() +
theme(axis.line.x = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_text(size=size + 10),
axis.ticks.x = element_blank(),
axis.title.y = element_text(face="bold",angle=90)) +
theme(legend.position = "none") +
coord_cartesian(ylim = c(-ylim.range, ylim.range))
r_waterfall_label2 <- r_waterfall +
geom_text(data = subset(water.de.res, log2FC >= 0), aes(label=Gene), angle = 90, vjust=0.5, hjust=-0.2, size=size) +
geom_text(data = subset(water.de.res, log2FC < 0), aes(label=Gene), angle = 90, vjust=0.5, hjust=1.2, size=size)
print(r_waterfall_label1)
print(r_waterfall_label2)
}
convert_tibble_to_dataframe <- function(x){
res <- as.data.frame(x[, -1])
rownames(res) <- x[, 1] %>% unlist()
return(res)
}
convert_data_to_tibble <- function(x, name="Gene"){
res <- as.data.frame(x) %>%
rownames_to_column(name) %>%
as_tibble()
return(res)
}
pheatmap_fontsize_row <- function(x){
if(class(x) %in% c("data.frame", "matrix")){
n.genes <- nrow(x)
}else if(class(x) == "character"){
n.genes <- length(x)
}else{
stop(paste("unknown data type", class(x)))
}
fontsize_row <- case_when(
n.genes > 1000 ~ 0.5,
n.genes > 800 ~ 0.6,
n.genes > 500 ~ 1,
n.genes > 300 ~ 2,
n.genes > 200 ~ 3,
n.genes > 120 ~ 4,
n.genes > 90 ~ 5,
n.genes > 60 ~ 6,
n.genes > 40 ~ 7,
n.genes > 20 ~ 8,
n.genes > 10 ~ 9,
TRUE ~ 10
)
return(fontsize_row)
}
pheatmap_fontsize_col <- function(x){
if(class(x) %in% c("data.frame", "matrix")){
n.samples <- ncol(x)
}else if(class(x) == "character"){
n.samples <- length(x)
}else{
stop(paste("unknown data type", class(x)))
}
fontsize_col <- case_when(
n.samples > 1000 ~ 0.4,
n.samples > 800 ~ 0.6,
n.samples > 500 ~ 1,
n.samples > 300 ~ 2,
n.samples > 200 ~ 3,
n.samples > 120 ~ 4,
n.samples > 100 ~ 4.5,
n.samples > 80 ~ 5,
n.samples > 60 ~ 5.5,
n.samples > 40 ~ 6,
n.samples > 20 ~ 7,
TRUE ~ 8
)
return(fontsize_col)
}
pheatmap_pdf_width <- function(x){
if(class(x) %in% c("data.frame", "matrix")){
n.samples <- ncol(x)
}else if(class(x) == "character"){
n.samples <- length(x)
}else{
stop(paste("unknown data type", class(x)))
}
pdf_width <- case_when(
n.samples > 500 ~ 22,
n.samples > 400 ~ 20,
n.samples > 350 ~ 19,
n.samples > 300 ~ 18,
n.samples > 250 ~ 17,
n.samples > 200 ~ 16,
n.samples > 150 ~ 15,
n.samples > 120 ~ 14,
n.samples > 90 ~ 13,
n.samples > 70 ~ 12,
n.samples > 50 ~ 11,
n.samples > 30 ~ 10,
n.samples > 24 ~ 9,
n.samples > 17 ~ 8,
n.samples > 10 ~ 7.5,
TRUE ~ 7
)
return(pdf_width)
}
pheatmap_pdf_height <- function(x){
if(class(x) %in% c("data.frame", "matrix")){
n.genes <- nrow(x)
}else if(class(x) == "character"){
n.genes <- length(x)
}else{
stop(paste("unknown data type", class(x)))
}
pdf_height <- case_when(
n.genes > 300 ~ 20,
n.genes > 100 ~ 15,
n.genes > 80 ~ 12,
n.genes > 70 ~ 11,
n.genes > 60 ~ 10,
n.genes > 50 ~ 9,
n.genes > 40 ~ 10,
n.genes > 30 ~ 9,
n.genes > 25 ~ 8.5,
n.genes > 20 ~ 8,
n.genes > 15 ~ 7.5,
n.genes > 12 ~ 7,
n.genes > 9 ~ 6.5,
n.genes > 7 ~ 6,
n.genes > 5 ~ 5,
n.genes > 3 ~ 4.5,
n.genes > 2 ~ 4.5,
TRUE ~ 4
)
return(pdf_height)
}
# divide always works row-wise
# first time to divide each transcript by length (row-wise)
# transpose second time to divide samples by sample_total_reads
cnt_to_fpkm <- function(x, gene_len){
num.reads <- colSums(x)
res <- t(t(x/gene_len)/num.reads) * 10^9
return(res)
}
# transcript first normalized by length
# sum the total normalized reads
# calculate the proportionn as tpm
cnt_to_tpm <- function(x, gene_len){
x_norm_len <- x/gene_len
sum_norm_len <- colSums(x_norm_len)
res <- t(t(x_norm_len)/sum_norm_len) * 10^6
}
stat_smooth_func <- function(mapping = NULL, data = NULL,
geom = "smooth", position = "identity",
...,
method = "auto",
formula = y ~ x,
se = TRUE,
n = 80,
span = 0.75,
fullrange = FALSE,
level = 0.95,
method.args = list(),
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE,
xpos = NULL,
ypos = NULL) {
layer(
data = data,
mapping = mapping,
stat = StatSmoothFunc,
geom = geom,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
method = method,
formula = formula,
se = se,
n = n,
fullrange = fullrange,
level = level,
na.rm = na.rm,
method.args = method.args,
span = span,
xpos = xpos,
ypos = ypos,
...
)
)
}
StatSmoothFunc <- ggproto("StatSmooth", Stat,
setup_params = function(data, params) {
# Figure out what type of smoothing to do: loess for small datasets,
# gam with a cubic regression basis for large data
# This is based on the size of the _largest_ group.
if (identical(params$method, "auto")) {
max_group <- max(table(data$group))
if (max_group < 1000) {
params$method <- "loess"
} else {
params$method <- "gam"
params$formula <- y ~ s(x, bs = "cs")
}
}
if (identical(params$method, "gam")) {
params$method <- mgcv::gam
}
params
},
compute_group = function(data, scales, method = "auto", formula = y~x,
se = TRUE, n = 80, span = 0.75, fullrange = FALSE,
xseq = NULL, level = 0.95, method.args = list(),
na.rm = FALSE, xpos=NULL, ypos=NULL) {
if (length(unique(data$x)) < 2) {
# Not enough data to perform fit
return(data.frame())
}
if (is.null(data$weight)) data$weight <- 1
if (is.null(xseq)) {
if (is.integer(data$x)) {
if (fullrange) {
xseq <- scales$x$dimension()
} else {
xseq <- sort(unique(data$x))
}
} else {
if (fullrange) {
range <- scales$x$dimension()
} else {
range <- range(data$x, na.rm = TRUE)
}
xseq <- seq(range[1], range[2], length.out = n)
}
}
# Special case span because it's the most commonly used model argument
if (identical(method, "loess")) {
method.args$span <- span
}
if (is.character(method)) method <- match.fun(method)
base.args <- list(quote(formula), data = quote(data), weights = quote(weight))
model <- do.call(method, c(base.args, method.args))
m = model
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(coef(m)[1], digits = 3),
b = format(coef(m)[2], digits = 3),
r2 = format(summary(m)$r.squared, digits = 3)))
func_string = as.character(as.expression(eq))
if(is.null(xpos)) xpos = min(data$x)*0.9
if(is.null(ypos)) ypos = max(data$y)*0.9
data.frame(x=xpos, y=ypos, label=func_string)
},
required_aes = c("x", "y")
)
lm_eqn = function(m) {
l <- list(a = format(coef(m)[1], digits = 2),
b = format(abs(coef(m)[2]), digits = 2),
r2 = format(summary(m)$r.squared, digits = 3));
if (coef(m)[2] >= 0) {
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,l)
} else {
eq <- substitute(italic(y) == a - b %.% italic(x)*","~~italic(r)^2~"="~r2,l)
}
as.character(as.expression(eq));
}
annotate_data <- function(rawdata, gene_col="Gene_name", species="Human"){
if(species == "Human"){
annot_file <- "~/Copy/MSKCC/gtf_files/GRCh38_Ensembl91_p10_mart_export_GO_20180308.txt"
}else if(species == "Mouse"){
annot_file <- "~/Copy/MSKCC/gtf_files/GRCm38_Ensembl91_p5_mart_export_GO_20180308.txt"
}else{
warning("### Error: we only support 'human' and 'mouse' for now")
exit
}
# for each of the ensembl_gene_id, there are multiple transcripts
# we will summarise all the transcript_length and use that for fpkm/tpm calculation
GRC38.91.ensembl <- read_tsv(annot_file) %>%
set_names(gsub(" ", "_", colnames(.))) %>%
rename(transcript_length = `Transcript_length_(including_UTRs_and_CDS)`,
chromosome_name = `Chromosome/scaffold_name`,
start_position = `Gene_start_(bp)`,
end_position = `Gene_end_(bp)`
) %>%
dplyr::select(-contains("Transcript", ignore.case = FALSE))
# we have to do it for transcript_length and GO_term separately
GRC38.91.ensembl.length <- GRC38.91.ensembl %>%
dplyr::select(Gene_stable_ID, transcript_length) %>%
group_by(Gene_stable_ID) %>%
summarise_all(sum) #%>%
GRC38.91.ensembl.GO <- GRC38.91.ensembl %>%
dplyr::select(Gene_stable_ID, GO_term_name, GO_term_accession) %>%
group_by(Gene_stable_ID) %>%
summarise(GO_term = paste(ifelse(is.na(GO_term_name), "", GO_term_name), collapse = "/"),
GO_accession = paste(ifelse(is.na(GO_term_accession), "", GO_term_accession), collapse = "/")) %>%
mutate(GO_term = gsub("^\\/{1,}$", NA, GO_term)) %>%
mutate(GO_term = gsub("^\\/{1,}", "", GO_term)) %>%
mutate(GO_term = gsub("\\/{1,}$", "", GO_term)) %>%
mutate(GO_accession = gsub("^\\/{1,}$", NA, GO_accession)) %>%
mutate(GO_accession = gsub("^\\/{1,}", "", GO_accession)) %>%
mutate(GO_accession = gsub("\\/{1,}$", "", GO_accession)) %>%
mutate(GO_term = ifelse(nchar(GO_term) == 0, NA, GO_term),
GO_accession = ifelse(nchar(GO_accession) == 0, NA, GO_accession))
GRC38.91.ensembl <-
left_join(dplyr::select(GRC38.91.ensembl, -transcript_length, -contains("GO")) %>% distinct(.), GRC38.91.ensembl.length) %>%
left_join(., GRC38.91.ensembl.GO, by="Gene_stable_ID") %>%
dplyr::select(Gene_stable_ID, Gene_name:end_position, transcript_length, everything()) %>%
mutate(Strand = ifelse(Strand == 1, "+", "-")) %>%
arrange(Gene_stable_ID)
# match the order of the info
# res <- left_join(rawdata, GRC38.91.ensembl, by=c( (!!rlang::sym(gene_col))="Gene_stable_ID"))
res <- left_join(rawdata, GRC38.91.ensembl, by="Gene_name")
#res <- left_join(rawdata, GRC38.91.ensembl, by=c("ID"="Gene_name"))
return(res)
}
annotate_data_HPA_protein <- function(rawdata, gene_col="Gene", species="Human", simple=FALSE){
protein <- read_tsv("~/Copy/MSKCC/Human_Protein_Atlas/proteinatlas.tsv") %>%
set_names(gsub(" ", "_", colnames(.)))
if(simple){
protein <- protein %>%
dplyr::select(Gene, Gene_description:Antibody, Subcellular_location, `TPM_max_in_non-specific`)
}
# match the order of the info
res <- left_join(rawdata, protein, by="Gene")
return(res)
}
# add prognostic info
annotate_data_HPA_pathology <- function(rawdata, tissue="pancreatic"){
pathology <- read_tsv("~/Copy/MSKCC/Human_Protein_Atlas/pathology.tsv") %>%
set_names(gsub(" - ", "_", colnames(.))) %>%
set_names(gsub(" ", "_", colnames(.))) %>%
mutate(Cancer = gsub(" cancer", "", Cancer)) %>%
filter(grepl(tissue, Cancer)) %>%
dplyr::select(Gene= Gene_name, Anti_High = High, Anti_Medium = Medium, Anti_Low = Low,
Anti_Not_detected = Not_detected, prognostic_favourable, prognostic_unfavourable)
if(nrow(pathology) > 0){
res <- left_join(rawdata, pathology, by="Gene")
return(res)
}else{
print(paste("Something wrong with the tissue name:", tissue, "please check again"))
return(NA)
}
}
annotate_data_HPA_tissue <- function(rawdata, tissue="pancreas"){
# add tissue specific TPM
tis <- read_tsv("~/Copy/MSKCC/Human_Protein_Atlas/rna_tissue.tsv") %>%
set_names(gsub(" ", "_", colnames(.))) %>%
filter(Sample == tissue) %>%
dplyr::select(Gene = Gene_name, Value) %>%
dplyr::rename(!!sym(paste0(tissue, "_TPM")) := Value)
if(nrow(tis) > 0){
res <- left_join(rawdata, tis, by="Gene")
return(res)
}else{
print(paste("Something wrong with the tissue name:", tissue, "; please check again"))
return(NA)
}
}
annotate_data_addlink <- function(rawdata, gene_col="Gene"){
link <- read_csv("~/Copy/MSKCC/gtf_files/GRCh38_Ensembl91_p10_mart_export_AnnotLinks.csv") %>%
dplyr::select(-Gene_stable_ID) %>%
group_by(Gene) %>%
dplyr::slice(1) %>%
ungroup()
res <- left_join(rawdata, link, by="Gene")
return(res)
}
annotate_data_by_ensemblID <- function(rawdata, id_col="Gene_stable_ID", species="Human"){
if(species == "Human" | species == "human"){
annot_file <- "~/Copy/MSKCC/gtf_files/GRCh38_Ensembl91_p10_mart_export_GO_20180308.txt"
}else if(species == "Mouse" | species == "mouse"){
annot_file <- "~/Copy/MSKCC/gtf_files/GRCm38_Ensembl91_p5_mart_export_GO_20180308.txt"
}else{
warning("### Error: we only support 'human' and 'mouse' for now")
exit()
}
# for each of the ensembl_gene_id, there are multiple transcripts
# we will summarise all the transcript_length and use that for fpkm/tpm calculation
GRC38.91.ensembl <- read_tsv(annot_file) %>%
set_names(gsub(" ", "_", colnames(.))) %>%
rename(transcript_length = `Transcript_length_(including_UTRs_and_CDS)`,
chromosome_name = `Chromosome/scaffold_name`,