-
Notifications
You must be signed in to change notification settings - Fork 3
/
mutationProfiles.R
2294 lines (1780 loc) · 73.6 KB
/
mutationProfiles.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
list.of.packages <- c('ggplot2', 'dplyr', 'plyr', 'RColorBrewer',
'BSgenome.Dmelanogaster.UCSC.dm6', 'deconstructSigs',
'reshape', 'data.table', 'ggpubr', 'plotly', 'grid', 'VennDiagram')
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)){
cat('Installing missing packages...\n')
install.packages(new.packages)
}
cat('Silently loading packages...')
suppressMessages(library(ggplot2))
suppressMessages(library(dplyr))
suppressMessages(library(plyr))
suppressMessages(library(RColorBrewer))
suppressMessages(library(BSgenome.Dmelanogaster.UCSC.dm6))
suppressMessages(library(deconstructSigs))
suppressMessages(library(reshape))
suppressMessages(library(data.table))
suppressMessages(library(ggpubr))
suppressMessages(library(plotly))
suppressMessages(library(grid))
suppressMessages(library(VennDiagram))
set.seed(42)
#' getData
#'
#' Function to clean cnv files
#' @param infile File to process [Required]
#' @keywords get
#' @import dplyr
#' @export
#' @return Dataframe
getData <- function(infile = "data/annotated_snvs.txt", expression_data='data/isc_genes_rnaSeq.csv'){
snv_data<-read.delim(infile, header = T)
colnames(snv_data)=c("sample", "chrom", "pos", "ref", "alt", "tri", "trans", "decomposed_tri", "grouped_trans", "a_freq", "caller", "variant_type", "status", "snpEff_anno", "feature", "gene", "id")
# Read in tissue specific expression data
seq_data<-read.csv(header = F, expression_data)
colnames(seq_data)<-c('id', 'fpkm')
snv_data <- join(snv_data,seq_data,"id", type = 'left')
snv_data$fpkm <- ifelse(is.na(snv_data$fpkm), 0, round(as.numeric(snv_data$fpkm), 1))
# Order by FPKM
snv_data<- dplyr::arrange(snv_data, desc(fpkm))
# Find vars called by both Mu and Var
# Must also filter one of these calls out...
snv_data$dups<-duplicated(snv_data[,1:3])
snv_data<-mutate(snv_data, caller = ifelse(dups == "TRUE", 'varscan2_mutect2' , as.character(caller)))
##############
## Filters ###
##############
# Filter for calls made by both V and M
# snv_data<-filter(snv_data, caller == 'mutect2' | caller == 'varscan2_mutect2')
# Filter for old/new data
# cat("Filtering for old/new data\n")
# snv_data <- filter(snv_data, !grepl("^A|H", sample))
# Filter for genes expressed in RNA-Seq data
# cat("Filtering out non-expressed genes\n")
# snv_data<-filter(snv_data, !is.na(fpkm) & fpkm > 0.1)
# Filter for genes NOT expressed in RNA-Seq data
# cat("Filtering out expressed genes\n")
# snv_data<-filter(snv_data, fpkm == 0)
# Filter on allele freq
# cat("Filtering on allele frequency\n")
#snv_data<-filter(snv_data, is.na(a_freq))
# snv_data<-filter(snv_data, a_freq >= 0.20)
# Filter out samples
# snv_data<-filter(snv_data, sample != "A373R1" & sample != "A373R7" & sample != "A512R17" )
# snv_data <- filter(snv_data, !sample %in% c("A373R1", "A373R7", "A512R17", "A373R11", "A785-A788R1", "A785-A788R11", "A785-A788R3", "A785-A788R5", "A785-A788R7", "A785-A788R9"))
# snv_data<-filter(snv_data, sample != "A373R11" & sample != 'A373R13')
# snv_data <- snv_data %>%
# filter(!sample %in% c("A373R1", "A373R7", "A512R17", "A373R11", "D050R07-2")) %>%
# droplevels()
# snv_data <- snv_data %>%
# filter(sample %in% c("D050R01", "D050R03", "D050R05", "D050R07-1")) %>%
# droplevels()
dir.create(file.path("plots"), showWarnings = FALSE)
return(snv_data)
}
#' cleanTheme
#'
#' Clean theme for plotting
#' @param base_size Base font size [Default 12]
#' @import ggplot2
#' @keywords theme
#' @export
cleanTheme <- function(base_size = 12){
theme(
plot.title = element_text(hjust = 0.5, size = 20),
panel.background = element_blank(),
plot.background = element_rect(fill = "transparent",colour = NA),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
axis.line.x = element_line(color="black", size = 0.5),
axis.line.y = element_line(color="black", size = 0.5),
axis.text = element_text(size=12),
axis.title = element_text(size=30)
)
}
#' genTris
#'
#' This function returns all possible trinucleotide combinations
#' @keywords trinucleotides
#' @export
#' @return Character string containing all 96 trinucleotides
#' genTris()
genTris <- function(){
all.tri = c()
for(i in c("A", "C", "G", "T")){
for(j in c("C", "T")){
for(k in c("A", "C", "G", "T")){
if(j != k){
for(l in c("A", "C", "G", "T")){
tmp = paste(i, "[", j, ">", k, "]", l, sep = "")
all.tri = c(all.tri, tmp)
}
}
}
}
}
all.tri <- all.tri[order(substr(all.tri, 3, 5))]
return(all.tri)
}
#' setCols
#'
#' Get colours for n levels
#' @import RColorBrewer
#' @param df Dataframe [Required]
#' @param col Column of snv_dataframe. Colours will be set to levels(df$cols) [Required]
#' @keywords cols
#' @export
setCols <- function(df, col){
names<-levels(df[[col]])
cat("Setting colour levles:", names, "\n")
level_number<-length(names)
mycols<-brewer.pal(level_number, "Set2")
names(mycols) <- names
colScale <- scale_fill_manual(name = col,values = mycols)
return(colScale)
}
#' snvStats
#'
#' Calculate some basic stats for snv snv_data
#' @import dplyr
#' @keywords stats
#' @export
snvStats <- function(){
snv_data<-getData()
cat("sample", "snvs", sep='\t', "\n")
rank<-sort(table(snv_data$sample), decreasing = TRUE)
rank<-as.array(rank)
total=0
scores=list()
for (i in 1:nrow(rank)){
cat(names(rank[i]), rank[i], sep='\t', "\n")
total<-total + rank[i]
scores[i]<-rank[i]
}
cat('--------------', '\n')
scores<-unlist(scores)
mean<-as.integer(mean(scores))
med<-as.integer(median(scores))
cat('total', total, sep='\t', '\n')
cat('samples', nrow(rank), sep='\t', '\n')
cat('--------------', '\n')
cat('mean', mean, sep='\t', '\n')
cat('median', med, sep='\t', '\n')
cat('\n')
all_ts<-nrow(filter(snv_data, trans == "A>G" | trans == "C>T" | trans == "G>A" | trans == "T>C"))
all_tv<-nrow(filter(snv_data, trans != "A>G" & trans != "C>T" & trans != "G>A" & trans != "T>C"))
ts_tv<-round((all_ts/all_tv), digits=2)
cat("ts/tv = ", ts_tv, sep='', '\n')
}
#' rainfall
#'
#' Plot log10 distances between snvs as rainfall plot
#' @import ggplot2
#' @keywords rainfall
#' @export
rainfall <- function(){
snv_data <- getData()
distances <- do.call(rbind, lapply(split(snv_data[order(snv_data$chrom, snv_data$pos),], snv_data$chrom[order(snv_data$chrom, snv_data$pos)]),
function(a)
data.frame(a,
dist=c(diff(a$pos), NA),
logdist = c(log10(diff(a$pos)), NA))
)
)
distances$logdist[is.infinite(distances$logdist)] <- 0
distances<-filter(distances, chrom != 4)
p<-ggplot(distances)
p<-p + geom_point(aes(pos/1000000, logdist, colour = grouped_trans))
p <- p + cleanTheme() +
theme(axis.text.x = element_text(angle=45, hjust = 1),
panel.grid.major.y = element_line(color="grey80", size = 0.5, linetype = "dotted"),
strip.text = element_text(size=20)
)
p<-p + facet_wrap(~chrom, scale = "free_x", ncol = 6)
#p<-p + scale_x_continuous("Mbs", breaks = seq(0,33,by=1), limits = c(0, 33), expand = c(0.01, 0.01))
p<-p + scale_x_continuous("Mbs", breaks = seq(0,max(distances$pos),by=10))
rainfall_out<-paste("rainfall.pdf")
cat("Writing file", rainfall_out, "\n")
ggsave(paste("plots/", rainfall_out, sep=""), width = 20, height = 5)
p
}
#' samplesPlot
#'
#' Plot the snv distribution for each sample
#' @import ggplot2
#' @param count Output total counts instead of frequency if set [Default no]
#' @keywords spectrum
#' @export
samplesPlot <- function(count=NA){
snv_data<-getData()
mut_class<-c("C>A", "C>G", "C>T", "T>A", "T>C", "T>G")
p<-ggplot(snv_data)
if(is.na(count)){
p<-p + geom_bar(aes(x = grouped_trans, y = (..count..)/sum(..count..), group = sample, fill = sample), position="dodge",stat="count")
p<-p + scale_y_continuous("Relative contribution to total mutation load", expand = c(0.0, .001))
tag='_freq'
}
else{
p<-p + geom_bar(aes(x = grouped_trans, y = ..count.., group = sample, fill = sample), position="dodge",stat="count")
p<-p + scale_y_continuous("Count", expand = c(0.0, .001))
tag='_count'
}
p<-p + scale_x_discrete("Mutation class", limits=mut_class)
p<-p + cleanTheme() +
theme(panel.grid.major.y = element_line(color="grey80", size = 0.5, linetype = "dotted"),
axis.title = element_text(size=20),
strip.text.x = element_text(size = 10)
)
p<-p + facet_wrap(~sample, ncol = 4, scale = "free_x" )
samples_mut_spect<-paste("mutation_spectrum_samples", tag, ".pdf", sep = '')
cat("Writing file", samples_mut_spect, "\n")
ggsave(paste("plots/", samples_mut_spect, sep=""), width = 20, height = 10)
p
}
#calledSnvs
calledSnvs <- function(){
snv_data<-getData()
calls<-table(snv_data$caller)
calls<-as.data.frame(unlist(calls))
calls$Var1 <- as.factor(calls$Var1)
grid.newpage()
draw.pairwise.venn(area1 = calls$Freq[calls$Var1 == 'mutect2'],
area2 = calls$Freq[calls$Var1 == 'varscan2'],
cross.area = calls$Freq[calls$Var1 == 'varscan2_mutect2'],
category = c("Mutect2","Varscan2"),
#lty = rep('blank', 2),
lwd = rep(0.3, 2),
cex = rep(2, 3),
cat.cex = rep(2, 2),
fill = c("#E7B800", "#00AFBB"),
alpha = rep(0.4, 2),
cat.pos = c(0, 0),
#cat.dist = rep(0.025, 2)
ext.text = 'FALSE'
)
}
#' mutSigs
#'
#' Calculate and plot the mutational signatures accross samples using the package `deconstructSigs`
#' @param samples Calculates and plots mutational signatures on a per-sample basis [Default no]
#' @param pie Plot a pie chart shwoing contribution of each signature to overall profile [Default no]
#' @import deconstructSigs
#' @import BSgenome.Dmelanogaster.UCSC.dm6
#' @keywords signatures
#' @export
mutSigs <- function(samples=NULL, pie=FALSE, write=FALSE){
if(!exists('scaling_factor')){
cat("calculating trinucleotide frequencies in genome\n")
scaling_factor <-triFreq()
}
snv_data<-getData()
genome <- BSgenome.Dmelanogaster.UCSC.dm6
if(missing(samples)){
cat("Plotting for all samples\n")
snv_data$tissue = 'All'
sigs.input <- mut.to.sigs.input(mut.ref = snv_data, sample.id = "tissue", chr = "chrom", pos = "pos", alt = "alt", ref = "ref", bsg = genome)
sig_plot<-whichSignatures(tumor.ref = sigs.input, signatures.ref = signatures.cosmic, sample.id = 'All',
contexts.needed = TRUE,
tri.counts.method = scaling_factor
)
if(write){
cat("Writing to file 'plots/all_signatures.pdf'\n")
pdf('plots/all_signatures.pdf', width = 20, height = 10)
plotSignatures(sig_plot)
dev.off()
}
plotSignatures(sig_plot)
if(pie){
makePie(sig_plot)
}
}
else{
sigs.input <- mut.to.sigs.input(mut.ref = snv_data, sample.id = "sample", chr = "chrom", pos = "pos", alt = "alt", ref = "ref", bsg = genome)
cat("sample", "snv_count", sep="\t", "\n")
for(s in levels(snv_data$sample)) {
snv_count<-nrow(filter(snv_data, sample == s))
if(snv_count > 50){
cat(s, snv_count, sep="\t", "\n")
sig_plot<-whichSignatures(tumor.ref = sigs.input, signatures.ref = signatures.cosmic, sample.id = s,
contexts.needed = TRUE,
tri.counts.method = scaling_factor)
if(write){
outfile<-(paste('plots/', s, '_signatures.pdf', sep = ''))
cat("Writing to file", outfile, "\n")
pdf(outfile, width = 20, height = 10)
plotSignatures(sig_plot)
dev.off()
}
plotSignatures(sig_plot)
if(pie){
makePie(sig_plot)
}
}
}
}
}
#' sigTypes
#'
#' Calculate and plot the mutational signatures accross samples using the package `deconstructSigs`
#' @param samples Calculates and plots mutational signatures on a per-sample basis [Default no]
#' @param pie Plot a pie chart shwoing contribution of each signature to overall profile [Default no]
#' @import deconstructSigs
#' @import data.table
#' @import reshape
#' @import forcats
#' @import BSgenome.Dmelanogaster.UCSC.dm6
#' @keywords signatures
#' @export
sigTypes <- function(write=FALSE){
suppressMessages(require(BSgenome.Dmelanogaster.UCSC.dm6))
suppressMessages(require(deconstructSigs))
if(!exists('scaling_factor')){
cat("Calculating trinucleotide frequencies in genome\n")
scaling_factor <-triFreq()
}
snv_data<-getData()
genome <- BSgenome.Dmelanogaster.UCSC.dm6
sigs.input <- mut.to.sigs.input(mut.ref = snv_data, sample.id = "sample", chr = "chrom", pos = "pos", alt = "alt", ref = "ref", bsg = genome)
l = list()
for(s in levels(snv_data$sample)) {
snv_count<-nrow(filter(snv_data, sample == s))
if(snv_count > 50){
sig_plot<-whichSignatures(tumor.ref = sigs.input, signatures.ref = signatures.cosmic, sample.id = s,
contexts.needed = TRUE,
tri.counts.method = scaling_factor)
l[[s]] <- sig_plot
}
}
mutSigs<-do.call(rbind, l)
mutSigs<-as.data.frame(mutSigs)
mutWeights<-mutSigs$weights
mutData<-melt(rbindlist(mutWeights, idcol = 'sample'),
id = 'sample', variable.name = 'signature', value.name = 'score')
mutData <- mutData %>%
filter(score > 0.1) %>%
group_by(sample) %>%
mutate(total = sum(score))
p <- ggplot(mutData)
p <- p + geom_bar(aes(fct_reorder(sample, -total), score, fill=signature),colour="black", stat = "identity")
p <- p + scale_x_discrete("Sample")
p <- p + scale_y_continuous("Signature contribution", expand = c(0.01, 0.01), breaks=seq(0, 1, by=0.1))
p <- p + cleanTheme() +
theme(axis.text.x = element_text(angle = 45, hjust=1),
axis.text = element_text(size=30)
)
if(write){
sigTypes<-paste("sigTypes.pdf")
cat("Writing file", sigTypes, "\n")
ggsave(paste("plots/", sigTypes, sep=""), width = 20, height = 10)
}
p
}
####
# sigTypesPie
####
sigPie <- function() {
df <- data.frame(
group = c("Sig3", "Sig5", "Sig8", "Unknown"),
value = c(21, 14, 25, 40),
cols = c('#DB8E00', '#64B200', '#00BD5C', '#00BADE'))
all <- data.frame(
group = c("Sig3", "Sig8", "Sig9", "Sig21", "Sig25", "Unknown"),
value = c(29, 17, 10, 7, 7, 30),
cols = c('#E68613', '#0CB702', '#00BE67', '#ED68ED', '#FF61CC', 'grey'))
bp <- ggplot(all, aes(x="", y=value, fill = cols)) +
geom_bar(width = 1, stat = "identity", colour = "white") +
scale_fill_manual(values = levels(all$cols), labels = levels(all$group))
pie <- bp + coord_polar("y", start=0)
pie + cleanTheme() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())
}
#' mutSpectrum
#'
#' Plots the mutations spectrum for all samples combined
#' @import ggplot2
#' @keywords spectrum
#' @export
mutSpectrum <- function(write=FALSE, max_y=25){
snv_data<-getData()
cat("Showing global contribution of tri class to mutation load", "\n")
p <- ggplot(snv_data)
p <- p + geom_bar(aes(x = decomposed_tri, y = (..count..)/sum(..count..), group = decomposed_tri, fill = grouped_trans), position="dodge",stat="count")
p <- p + scale_y_continuous("Contribution to mutation load", limits = c(0, max_y/100), breaks=seq(0,max_y/100,by=0.025), labels=paste0(seq(0,max_y,by=2.5), "%"), expand = c(0.0, .0005))
p <- p + scale_x_discrete("Genomic context", expand = c(.005, .005))
p <- p + cleanTheme() +
theme(panel.grid.major.y = element_line(color="grey80", size = 0.5, linetype = "dotted"),
axis.text.x = element_text(angle = 90, hjust=1),
axis.text.y = element_text(size=15),
axis.title = element_text(size=20),
strip.text.x = element_text(size = 15)
)
p <- p + facet_wrap(~grouped_trans, ncol = 6, scale = "free_x" )
p <- p + guides(grouped_trans = FALSE)
if(write){
mut_spectrum<-paste("mutation_spectrum.pdf")
cat("Writing file", mut_spectrum, "\n")
ggsave(paste("plots/", mut_spectrum, sep=""), width = 20, height = 5)
}
p
}
#' featureEnrichment
#'
#' Function to calculate enrichment of snv hits in genomic features
#' @description Calculate the enrichment of snv hits in genomic features
#' A 'features' file must be provided with the follwing format:
#' feature length percentage
#' This can be generated using the script 'script/genomic_features.pl' and a genome .gtf file
#' The defualt genome length is set to the mappable regions of the Drosophila melanogastor Dmel6.12 genome (GEM mappability score > .5)
#' (118274340). The full, assembled genome legnth for chroms 2/3/4/X/Y is 137547960
#' @param features File containing total genomic lengths of features [Default 'data/genomic_features.txt']
#' @param genome_length The total legnth of the genome [Default 118274340 (mappable regions on chroms 2, 3, 4, X & Y for Drosophila melanogastor Dmel6.12)]
#' @keywords enrichment
#' @import dplyr ggpubr
#' @return A snv_data frame with FC scores for all genes seen at least n times in snv snv_data
#' @export
featureEnrichment <- function(features='data/genomic_features.txt', genome_length=118274340, write=FALSE){
genome_features<-read.delim(features, header = T)
snv_data<-getData()
mutCount<-nrow(snv_data)
# To condense exon counts into "exon"
snv_data$feature<-as.factor(gsub("exon_.*", "exon", snv_data$feature))
classCount<-table(snv_data$feature)
classLengths<-setNames(as.list(genome_features$length), genome_features$feature)
fun <- function(f) {
# Calculate the fraction of geneome occupied by each feature
featureFraction<-classLengths[[f]]/genome_length
# How many times should we expect to see this feature hit in our snv_data (given number of obs. and fraction)?
featureExpect<-(mutCount*featureFraction)
# observed/expected
fc<-classCount[[f]]/featureExpect
Log2FC<-log2(fc)
featureExpect<-round(featureExpect,digits=3)
# Binomial test
if(!is.null(classLengths[[f]])){
if(classCount[f] >= featureExpect){
stat<-binom.test(x = classCount[f], n = mutCount, p = featureFraction, alternative = "greater")
test<-"enrichment"
}
else{
stat<-binom.test(x = classCount[f], n = mutCount, p = featureFraction, alternative = "less")
test<-"depletion"
}
sig_val <- ifelse(stat$p.value <= 0.001, "***",
ifelse(stat$p.value <= 0.01, "**",
ifelse(stat$p.value <= 0.05, "*", "")))
p_val<-format.pval(stat$p.value, digits = 3, eps=0.0001)
list(feature = f, observed = classCount[f], expected = featureExpect, Log2FC = Log2FC, test = test, sig = sig_val, p_val = p_val)
}
}
enriched<-lapply(levels(snv_data$feature), fun)
enriched<-do.call(rbind, enriched)
featuresFC<-as.data.frame(enriched)
# Sort by FC value
featuresFC<-dplyr::arrange(featuresFC,desc(abs(as.numeric(Log2FC))))
featuresFC$Log2FC<-round(as.numeric(featuresFC$Log2FC), 1)
if(write){
featuresFC <- filter(featuresFC, observed >= 5)
first.step <- lapply(featuresFC, unlist)
second.step <- as.data.frame(first.step, stringsAsFactors = F)
ggpubr::ggtexttable(second.step, rows = NULL, theme = ttheme("mGreen"))
feat_enrichment_table <- paste("feature_enrichment_table.tiff")
cat("Writing to file: ", 'plots/', feat_enrichment_table, sep = '')
ggsave(paste("plots/", feat_enrichment_table, sep=""), width = 5.5, height = (nrow(featuresFC)/3), dpi=300)
} else{
return(featuresFC)
}
}
featureEnrichmentPlot <- function(write=FALSE) {
feature_enrichment<-featureEnrichment()
feature_enrichment$feature <- as.character(feature_enrichment$feature)
feature_enrichment$Log2FC <- as.numeric(feature_enrichment$Log2FC)
feature_enrichment <- transform(feature_enrichment, feature = reorder(feature, -Log2FC))
feature_enrichment <- filter(feature_enrichment, observed >= 5)
# Custom sorting
# feature_enrichment$feature <- factor(feature_enrichment$feature, levels=c("intron", "intergenic", "exon", "3UTR", "ncRNA", "5UTR"))
p<-ggplot(feature_enrichment)
p<-p + geom_bar(aes(feature, Log2FC, fill = as.character(test)), stat="identity")
p<-p + guides(fill=FALSE)
p<-p + ylim(-2,2)
p<-p + cleanTheme() +
theme(panel.grid.major.y = element_line(color="grey80", size = 0.5, linetype = "dotted"),
axis.text.x = element_text(angle = 45, hjust=1),
axis.text = element_text(size=20)
)
if(write){
feat_plot <- paste("feat_plot.pdf")
cat("Writing file", feat_plot, "\n")
ggsave(paste("plots/", feat_plot, sep=""), width = 5, height = 10)
}
p
}
#' geneEnrichment
#'
#' Function to calculate fold change enrichment in a set of snv calls correcting for gene length
#' @description Calculate the enrichment of snv hits in length-corrected genes
#' A 'gene_lengths' file must be provided with the following fields (cols 1..6 required)
#' gene length chrom start end tss scaling_factor
#' This can be generated using the script 'script/genomic_features.pl' and a genome .gtf file
#' The defualt genome length is set to the mappable regions of the Drosophila melanogastor Dmel6.12 genome (GEM mappability score > .5)
#' (118274340). The full, assembled genome legnth for chroms 2/3/4/X/Y is 137547960
#' @param gene_lengths File containing all genes and their lengths (as generated by 'script/genomefeatures.pl') [Default 'data/gene_lengths.txt']
#' @param n The number of times we need to have seen a gene in our snv_data to view its enrichment score [Default 3]
#' @param genome_length The total legnth of the genome [Default 137547960 (chroms 2, 3, 4, X & Y for Drosophila melanogastor Dmel6.12)]
#' @keywords enrichment
#' @import dplyr
#' @import ggpubr
#' @return A snv_data frame with FC scores for all genes seen at least n times in snv snv_data
#' @export
geneEnrichment <- function(gene_lengths_in="data/gene_lengths.txt", n=10, genome_length=118274340, write=FALSE){
snv_data <- getData() %>%
dplyr::filter(gene != "intergenic") %>%
droplevels()
snv_count<-nrow(snv_data)
gene_lengths <- read.delim(gene_lengths_in, header = T)
gene_lengths <- gene_lengths %>%
dplyr::filter(length > 1000) %>%
dplyr::select(gene, length) %>%
droplevels()
genes<-setNames(as.list(gene_lengths$length), gene_lengths$gene)
snv_data<-join(gene_lengths, snv_data, 'gene', type = 'left')
snv_data$fpkm <- ifelse(snv_data$fpkm=='NULL' | snv_data$fpkm=='NA' | is.na(snv_data$fpkm), 0, snv_data$fpkm)
snv_data$observed <- ifelse(is.numeric(snv_data$observed), snv_data$observed, 0)
hit_genes<-table(factor(snv_data$gene, levels = levels(snv_data$gene) ))
expression<-setNames(as.list(snv_data$fpkm), snv_data$gene)
fun <- function(g) {
# Calculate the fraction of geneome occupied by each gene
genefraction<-genes[[g]]/genome_length
# How many times should we expect to see this gene hit in our snv_data (given number of obs. and fraction of genome)?
gene_expect<-snv_count*(genefraction)
# observed/expected
fc<-hit_genes[[g]]/gene_expect
log2FC = log2(fc)
if (hit_genes[[g]] >= gene_expect) {
stat <- binom.test(x = hit_genes[[g]], n = snv_count, p = genefraction, alternative = "greater")
test <- "enrichment"
} else {
stat <- binom.test(x = hit_genes[[g]], n = snv_count, p = genefraction, alternative = "less")
test <- "depletion"
}
sig_val <- ifelse(stat$p.value <= 0.001, "***",
ifelse(stat$p.value <= 0.01, "**",
ifelse(stat$p.value <= 0.05, "*", "")))
sig_val <- ifelse(stat$p.value > 0.05, "-", sig_val)
p_val <- format.pval(stat$p.value, digits = 3)
gene_expect<-round(gene_expect,digits=3)
list(gene = g, length = genes[[g]], fpkm = expression[[g]], test=test, observed = hit_genes[g], expected = gene_expect, fc = fc, log2FC = log2FC, sig_val=sig_val, p_val=p_val)
}
enriched<-lapply(levels(snv_data$gene), fun)
enriched<-do.call(rbind, enriched)
genesFC<-as.data.frame(enriched)
# Filter for genes with few observations
genesFC <- genesFC %>%
dplyr::filter(observed >= n) %>%
dplyr::mutate(expected = round(as.numeric(expected),digits=3)) %>%
dplyr::mutate(log2FC = round(as.numeric(log2FC),digits=2)) %>%
dplyr::mutate(p_val = as.numeric(p_val)) %>%
dplyr::mutate(eScore = abs(log2FC) * -log10(p_val)) %>%
dplyr::mutate(eScore = round(as.numeric(eScore),digits=2)) %>%
dplyr::select(gene, observed, expected, log2FC, test, sig_val, p_val, eScore) %>%
dplyr::arrange(-eScore, p_val, -abs(log2FC)) %>%
droplevels()
if(write){
cat("printing")
first.step <- lapply(genesFC, unlist)
second.step <- as.data.frame(first.step, stringsAsFactors = F)
arrange(second.step,desc(as.integer(log2FC)))
ggpubr::ggtexttable(second.step, rows = NULL, theme = ttheme("mGreen"))
gene_enrichment_table <- paste("gene_enrichment_table.tiff")
ggsave(paste("plots/", gene_enrichment_table, sep=""), width = 5.2, height = (nrow(genesFC)/3), dpi=300)
} else{
return(genesFC)
}
}
# EnrichmentVolcano
#'
#' Plot the enrichment of SNVs in genes features
#' @keywords enrichment
#' @import dplyr
#' @import plotly
#' @export
EnrichmentVolcano <- function(d){
gene_enrichment <- d
minPval <- min(gene_enrichment$p_val[gene_enrichment$p_val>0])
gene_enrichment$p_val <- ifelse(gene_enrichment$p_val==0, minPval/abs(gene_enrichment$log2FC), gene_enrichment$p_val)
gene_enrichment$p_val <- ifelse(gene_enrichment$p_val==0, minPval, gene_enrichment$p_val)
maxLog2 <- max(abs(gene_enrichment$log2FC[is.finite(gene_enrichment$log2FC)]))
maxLog2 <- as.numeric(round_any(maxLog2, 1, ceiling))
ax <- list(
size = 25
)
ti <- list(
size = 25
)
p <- plot_ly(data = gene_enrichment,
x = ~log2FC,
y = ~-log10(p_val),
type = 'scatter',
# showlegend = FALSE,
mode = 'markers',
# height = 1200,
# width = 1000,
# frame = ~p_val,
text = ~paste("Gene: ", gene, "\n",
"Observed: ", observed, "\n",
"Expected: ", expected, "\n",
"P-val: ", p_val, "\n"),
color = ~log10(p_val),
colors = "Spectral",
size = ~-log10(p_val)
) %>%
layout(
xaxis = list(title="Log2(FC)", titlefont = ax, range = c(-maxLog2, maxLog2)),
yaxis = list(title="-Log10(p)", titlefont = ax)
)
p
}
#' snvinGene
#'
#' Plot all snvs found in a given gene
#' @description Plot all snvs found in a given gene.
#' A 'gene_lengths' file must be provided with the following fields (cols 1..6 required)
#' gene length chrom start end tss scaling_factor
#' This can be generated using the script 'script/genomic_features.pl' and a genome .gtf file
#' @param gene_lengths File containing all genes and their lengths (as generated by 'script/genomefeatures.pl') [Default 'data/gene_lengths.txt']
#' @param gene2plot Name of the gene to plot
#' @import ggplot2 dplyr
#' @keywords gene
#' @export
snvinGene <- function(gene_lengths="data/gene_lengths.txt", gene2plot='kuz', annotated=TRUE, col_by_status=TRUE, write=FALSE){
gene_lengths <- read.delim(gene_lengths, header = T)
region <- gene_lengths %>%
dplyr::filter(gene == gene2plot) %>%
droplevels()
gene_length <-(region$end-region$start)
wStart<-(region$start - gene_length/10)
wEnd<-(region$end + gene_length/10)
wChrom<-as.character(region$chrom)
wTss<-suppressWarnings(as.numeric(levels(region$tss))[region$tss])
snv_data<-getData() %>%
dplyr::filter(chrom == wChrom & pos >= wStart & pos <= wEnd)
if(nrow(snv_data) == 0){
stop(paste("There are no snvs in", gene2plot, "- Exiting", "\n"))
}
snv_data$colour_var <- snv_data$feature
if(annotated){
snv_data$colour_var <- snv_data$variant_type
if(col_by_status)
snv_data$colour_var <- snv_data$status
}
p <- ggplot(snv_data)
p <- p + geom_point(aes(pos/1000000, sample, colour = colour_var, size = 1.5), position=position_jitter(width=0, height=0.2))
p <- p + guides(size = FALSE, sample = FALSE)
p <- p + cleanTheme() +
theme(axis.title.y=element_blank(),
panel.grid.major.y = element_line(color="grey80", size = 0.5, linetype = "dotted"),
axis.text.y = element_text(size = 30)
)
p <- p + scale_x_continuous("Mbs", expand = c(0,0), breaks = seq(round(wStart/1000000, digits = 2),round(wEnd/1000000, digits = 2),by=0.05), limits=c(wStart/1000000, wEnd/1000000))
p <- p + annotate("rect", xmin=region$start/1000000, xmax=region$end/1000000, ymin=0, ymax=0.3, alpha=.2, fill="skyblue")
p <- p + geom_vline(xintercept = wTss/1000000, colour="red", alpha=.7, linetype="solid")
p <- p + geom_segment(aes(x = wTss/1000000, y = 0, xend= wTss/1000000, yend = 0.1), colour="red")
middle<-((wEnd/1000000+wStart/1000000)/2)
p <- p + annotate("text", x = middle, y = 0.15, label=gene2plot, size=6)
p <- p + ggtitle(paste("Chromosome:", wChrom))
if(write){
hit_gene<-paste(gene2plot, "_hits.pdf", sep='')
cat("Writing file", hit_gene, "\n")
ggsave(paste("plots/", hit_gene, sep=""), width = 10, height = 10)
}
p
}
#' featuresHit
#'
#' Show top hit features
#' @import ggplot2
#' @keywords features
#' @export
featuresHit <- function(..., write=FALSE){
snv_data<-getData(...)
# To condense exon counts into "exon"
snv_data$feature<-as.factor(gsub("exon_.*", "exon", snv_data$feature))
# Reoders descending
snv_data$feature<-factor(snv_data$feature, levels = names(sort(table(snv_data$feature), decreasing = TRUE)))
snv_data <- snv_data %>%
dplyr::group_by(feature) %>%
dplyr::add_tally() %>%
ungroup() %>%
dplyr::filter(n >= 5) %>%
droplevels()
#cols<-setCols(snv_data, "feature")
p <- ggplot(snv_data)
p <- p + geom_bar(aes(feature, fill = feature))
#p<-p + cols
p <- p + cleanTheme() +
theme(axis.title.x=element_blank(),
panel.grid.major.y = element_line(color="grey80", size = 0.5, linetype = "dotted"))
p <- p + scale_x_discrete(expand = c(0.01, 0.01))
p <- p + scale_y_continuous(expand = c(0.01, 0.01))
# colour to a pub palette:
# p<-p + ggpar(p, palette = 'jco')
if(write){
features_outfile<-paste("hit_features_count.pdf")
cat("Writing file", features_outfile, "\n")
ggsave(paste("plots/", features_outfile, sep=""), width = 20, height = 10)
}
p
}
#' geneHit
#'
#' Show top hit genes
#' @import dplyr
#' @keywords gene
#' @param n Show top n hits [Default 10]
#' @export
geneHit <- function(..., n=10){
snv_data<-getData(...)
snv_data<-filter(snv_data, gene != "intergenic")
hit_count<-as.data.frame(sort(table(unlist(snv_data$gene)), decreasing = T))
colnames(hit_count)<- c("gene", "count")
head(hit_count, n)
}
#' triFreq
#'
#' This function counts the number of times each triunucleotide is found in a supplied genome
#' @param genome BS.genome file defaults to BSgenome.Dmelanogaster.UCSC.dm6
#' @param count Output total counts instead of frequency if set [Default no]
#' @import dplyr
#' @keywords trinucleotides
#' @export
#' @return Dataframe of trinucs and freqs (or counts if count=1)
triFreq <- function(genome=NULL, count=FALSE){
if(missing(genome)){
cat("No genome specfied, defaulting to 'BSgenome.Dmelanogaster.UCSC.dm6'\n")
library(BSgenome.Dmelanogaster.UCSC.dm6, quietly = TRUE)
genome <- BSgenome.Dmelanogaster.UCSC.dm6
}
params <- new("BSParams", X = Dmelanogaster, FUN = trinucleotideFrequency, exclude = c("M", "_"), simplify = TRUE)
snv_data<-as.data.frame(bsapply(params))
snv_data$genome<-as.integer(rowSums(snv_data))
snv_data$genome_adj<-(snv_data$genome*2)
if(count){
tri_count<-snv_data['genome_adj']
tri_count<-cbind(tri = rownames(tri_count), tri_count)
colnames(tri_count) <- c("tri", "count")
rownames(tri_count) <- NULL
return(tri_count)
}
else{
snv_data$x <- (1/snv_data$genome)
scaling_factor<-snv_data['x']
return(scaling_factor)
}
}
# Functions to calculate the distance
# from each breakpoint to user-provided loci (e.g. TSS)
#' generateData
#' Prepare data for dist2motif
#' @keywords simulate
#' @import ggplot2
#' @import dplyr
#' @import colorspace
#' @import RColorBrewer
#' @export
generateData <- function(..., breakpoints=NA, sim=NA, keep=NULL){
if(is.na(breakpoints)){
# if(!missing(keep)){
# real_data <- notchFilt(..., keep=keep)
# } else {
real_data <- getData(..., genotype=='somatic_tumour', !sample %in% c("A373R7", "A512R17", "A785-A788R1", "A785-A788R11", "A785-A788R3", "A785-A788R5", "A785-A788R7", "A785-A788R9"))
# }
real_data <- real_data %>%
dplyr::filter(chrom == "2L" | chrom == "2R" | chrom == "3L" | chrom == "3R" | chrom == "X" ) %>%
dplyr::mutate(pos = bp) %>%
dplyr::select(chrom, pos) %>%
droplevels()
} else{
real_data <- read.table(breakpoints, header = F)
if(is.null(real_data$V3)){
real_data$V3 <- real_data$V2 + 2
}