-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsummariseMAFs.Rmd
2988 lines (2223 loc) · 145 KB
/
summariseMAFs.Rmd
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
---
title: "MAF files summary"
author: "UMCCR"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
html_document:
theme: readable
css: summariseMAFs.css
toc: true
toc_float: true
code_folding: hide
rmdformats::material:
highlight: kate
params:
maf_dir: '/Users/kanwals/UMCCR/research/PAAD_atlas/maf_analysis/data/'
maf_files: 'SBJ-somatic-PASS.maf'
datasets: 'pdac_test'
samples_id_cols: NULL
genes_min: '2'
genes_list: 'none'
genes_keep_order: TRUE
genes_blacklist: 'none'
samples_show: FALSE
samples_keep_order: TRUE
samples_keep_order_annot: TRUE
sort_by_annotation: FALSE
samples_list: 'none'
samples_blacklist: 'none'
nonSyn_list: 'Frame_Shift_Del,Frame_Shift_Ins,Splice_Site,Translation_Start_Site,Nonsense_Mutation,Nonstop_Mutation,In_Frame_Del,In_Frame_Ins,Missense_Mutation'
remove_duplicated_variants: TRUE
pathways: 'none'
purple: 'none'
purple_hd: 0.5
purple_loh: 1.5
purple_amp: 6
cnvkit: 'none'
cnvkit_hd: 0.5
cnvkit_loh: 1.5
cnvkit_amp: 6
gistic: 'none'
draw_titv: FALSE
clinical_info: 'none'
clinical_features: 'none'
clinical_enrichment_p: 0.05
signature_enrichment_p: 0.05
maf_comp_p: 0.05
maf_comp_fdr: 1
out_folder: 'MAF_summary_report'
hide_code_btn: TRUE
ucsc_genome_assembly: 38
---
Report summarising and visualising mutation data in [Mutation Annotation Format](https://software.broadinstitute.org/software/igv/MutationAnnotationFormat){target="_blank"} (MAF) file(s) for the following dataset(s): **`r gsub(",", ", ", params$datasets) `**
***
<span style="color:#ff0000">NOTE</span>: this report summarises **only non-synonymous variants** (see definitions below).
<details>
<summary>Variants consequence definitions</summary>
<font size="2">
**Non-synonymous variants** are defined as variants with the following consequences: *`r paste(params$nonSyn_list, collapse = ", ")`*. Rest will be considered as silent variants.
NOTE: by default, variants considered as non-synonymous are those with high/moderate variant consequences, which include: *frame shift deletions*, *frame shift insertions*, *splice site mutations*, *translation start site mutations*, *nonsense mutation*, *nonstop mutations*, *in-frame deletion*, *in-frame insertions* and *missense mutation*.
* [*High impact variant consequence*](http://asia.ensembl.org/Help/Glossary?id=535){target="_blank"} - the variant is assumed to have high (disruptive) impact in the protein, probably causing protein truncation, loss of function or triggering nonsense mediated decay.
* [*Moderate impact variant consequence*](http://asia.ensembl.org/Help/Glossary?id=535){target="_blank"} - a non-disruptive variant that might change protein effectiveness.
* [*Low impact variant consequence*](http://asia.ensembl.org/Help/Glossary?id=535){target="_blank"} - a variant that is assumed to be mostly harmless or unlikely to change protein behaviour.
</font>
</details>
***
<details>
<summary>Input parameters</summary>
<font size="2">
* **maf_dir**: `r params$maf_dir`
* **maf_files**: `r params$maf_files`
* **datasets**: `r params$datasets`
* **samples_id_cols**: `r params$samples_id_cols`
* **genes_min**: `r params$genes_min`
* **genes_list**: `r params$genes_list`
* **genes_keep_order**: `r params$genes_keep_order`
* **genes_blacklist**: `r params$genes_blacklist`
* **samples_show**: `r params$samples_show`
* **samples_keep_order**: `r params$samples_keep_order`
* **samples_keep_order_annot**: `r params$samples_keep_order_annot`
* **samples_list**: `r params$samples_list`
* **samples_blacklist**: `r params$samples_blacklist`
* **nonSyn_list**: `r params$nonSyn_list`
* **remove_duplicated_variants**: `r params$remove_duplicated_variants`
* **pathways**: `r params$pathways`
* **purple**: `r params$purple`
`r if ( params$purple !="none" ) { c(paste0("* **purple_hd**: ",params$purple_hd)) }`
`r if ( params$purple !="none" ) { c(paste0("* **purple_loh**: ",params$purple_loh)) }`
`r if ( params$purple !="none" ) { c(paste0("* **purple_amp**: ",params$purple_amp)) }`
* **cnvkit**: `r params$cnvkit`
`r if ( params$cnvkit !="none" ) { c(paste0("* **cnvkit_hd**: ",params$cnvkit_hd)) }`
`r if ( params$cnvkit !="none" ) { c(paste0("* **cnvkit_loh**: ",params$cnvkit_loh)) }`
`r if ( params$cnvkit !="none" ) { c(paste0("* **cnvkit_amp**: ",params$cnvkit_amp)) }`
* **gistic**: `r params$gistic`
* **draw_titv**: `r params$draw_titv`
* **clinical_info**: `r params$clinical_info`
* **clinical_features**: `r params$clinical_features`
* **clinical_enrichment_p**: `r params$clinical_enrichment_p`
* **signature_enrichment_p**: `r params$signature_enrichment_p`
* **maf_comp_p**: `r params$maf_comp_p`
* **maf_comp_fdr**: `r params$maf_comp_fdr`
* **out_folder**: `r params$out_folder`
* **hide_code_btn**: `r params$hide_code_btn`
* **ucsc_genome_assembly**: `r params$ucsc_genome_assembly`
</font>
</details>
***
```{r code_display, echo = FALSE}
##### Include or exclude the "Code" buttom allowing to "show"/"hide" code chunks from the report
if ( params$hide_code_btn ) {
writeLines(".btn { display: none ;", con = "summariseMAFs.css")
} else {
writeLines(" ", con = "summariseMAFs.css")
}
```
```{r define_functions, comment=NA, message=FALSE, warning=FALSE}
##### Define functions
##### Create 'not in' operator
"%!in%" <- function(x,table) match(x,table, nomatch = 0) == 0
##### Assign colours to different datasets. These colours will be used to distinguish tabs in generated excel summary spreadsheets
getDatasetsColours <- function(datasets) {
##### Predefined selection of colours for datasets
datasets.colours <- c("dodgerblue","firebrick","lightslategrey","darkseagreen","orange","darkcyan","bisque", "coral2", "cadetblue3","red","blue","green")
f.datasets <- factor(datasets)
vec.datasets <- datasets.colours[1:length(levels(f.datasets))]
datasets.colour <- rep(0,length(f.datasets))
for(i in 1:length(f.datasets))
datasets.colour[i] <- vec.datasets[ f.datasets[i]==levels(f.datasets)]
return( list(vec.datasets, datasets.colour) )
}
###### Generate dataTable for each dataset with all mutation information for selected gene(s), as provided in MAF files. User can filter variants to include only non-synonymous (default), silent or all variants
mut.details.datasets <- function(mafInfo, datasets, genes, type = "nonsynonymous") {
##### Vector with datasets with no mutations reported in selected genes
datasets.noMut <- NULL
##### Create a list for htmlwidgets
widges.list <- htmltools::tagList()
for ( i in 1:length(datasets) ) {
##### Include all variants
if ( type == "all" ) {
mut.details.genes <- mafInfo[[datasets[i]]]@data[ mafInfo[[datasets[i]]]@data[, Hugo_Symbol] %in% genes, ]
mut.details.genes <- rbind(mut.details.genes, mafInfo[[datasets[i]]]@maf.silent[ mafInfo[[datasets[i]]]@maf.silent[, Hugo_Symbol] %in% genes, ] )
##### Include silent variants
} else if ( type == "silent" ) {
mut.details.genes <- mafInfo[[datasets[i]]]@maf.silent[ mafInfo[[datasets[i]]]@maf.silent[, Hugo_Symbol] %in% genes, ]
##### Include only non-synonymous variants
} else {
mut.details.genes <- mafInfo[[datasets[i]]]@data[ mafInfo[[datasets[i]]]@data[, Hugo_Symbol] %in% genes, ]
}
if ( nrow(mut.details.genes) != 0 ) {
##### Sort table by gene symbol and then by sample ID
mut.details.genes <- mut.details.genes[ order(mut.details.genes$Hugo_Symbol, mut.details.genes$Tumor_Sample_Barcode), ]
#### Move column with Hugo_Symbol to the first place and Tumor_Sample_Barcode to the second
col_idx <- grep("Tumor_Sample_Barcode", names(mut.details.genes))
mut.details.genes <- as.data.frame(mut.details.genes)[, c(col_idx, (1:ncol(mut.details.genes))[-col_idx]) ]
col_idx <- grep("Hugo_Symbol", names(mut.details.genes))
mut.details.genes <- as.data.frame(mut.details.genes)[, c(col_idx, (1:ncol(mut.details.genes))[-col_idx]) ]
widges.list[[i]] <- DT::datatable( data = mut.details.genes, caption = htmltools::tags$caption(style = 'caption-side: top; text-align: left;', htmltools::strong(datasets[i])), filter = "top", extensions = c('Buttons','FixedColumns','Scroller'), options = list(pageLength = 10, dom = 'Bfrtip', buttons = c('excel', 'csv', 'pdf','copy','colvis'), scrollX = TRUE, fixedColumns = list(leftColumns = 2), deferRender = TRUE, scrollY = 200, scroller = TRUE), width = 800, escape = FALSE ) %>%
DT::formatStyle( columns = names(mut.details.genes), 'text-align' = 'center' )
} else {
datasets.noMut <- c(datasets.noMut, datasets[i])
}
}
##### Report datasets with no mutations reported in selected genes
if ( length(datasets.noMut) != 0 ) {
if ( type == "nonsynonymous" ) {
cat(paste("<span style=\"color:#ff0000\">NOTE</span>: none of queried gene(s) have non-synonymous variants reported in the following dataset(s):", paste(datasets.noMut, collapse = ", "), "\n\n", sep=" "))
} else if ( type == "silent" ) {
cat(paste("NOTE, none of queried gene(s) have silent variants reported in the following dataset(s):", paste(datasets.noMut, collapse = ", "), "\n\n", sep=" "))
}
}
##### Print a list of htmlwidgets
widges.list
}
###### Generate lollipop plot for each dataset for selected gene
lollipops.datasets <- function(mafInfo, datasets, gene) {
##### Create a list to store MAF info for individual datasets
for ( dataset in datasets ) {
mut = subsetMaf(maf = mafInfo[[dataset]], includeSyn = FALSE, genes = gene, mafObj = FALSE, query = "Variant_Type != 'CNV'", dropLevels = FALSE)
##### Check if the gene has any mutations in correspoding dataset
if ( nrow(mut) != 0 ) {
##### Drawing lollipop for the top 10 genes in each dataset
##### Check if the amino acid changes information is available in MAF provided files. The script expects column called "HGVSp_Short", which is produced with vcf2maf (https://github.com/mskcc/vcf2maf) when converting VCFs to MAFs (https://github.com/cBioPortal/cbioportal/issues/2996) and describes a mutation's amino acid change. The "aa_mutation" field used for annotation in ICGC samples is also acceptable. NOTE: other possibilities are: "Protein_Change", "AAChange""
pchange = c('HGVSp_Short', 'Protein_Change', 'AAChange')
##### Define the column with protein change info
pchange = pchange[pchange %in% colnames(mut)]
##### Check if the protein change field is not empty
if ( any(!is.na(as.data.frame(mut)[ , pchange ])) ) {
cat(paste("\n\n <b>", dataset, "</b> \n\n", sep=" "))
##### Check if non-synonymous variats are detected
if ( gene %in% mut$Hugo_Symbol ) {
##### Make it plot to a dummy graphics device file (e.g. /dev/null) to avoid plotting to the console
pdf(file=paste0(mutationMapsDir, "/", paste(dataset, gene, sep="_"), ".pdf"), width = 8, height = 5)
lollipopPlot.image <- capture.output(maftools::lollipopPlot(maf = mafInfo[[dataset]], gene = gene, AACol = pchange, printCount = FALSE, showDomainLabel = FALSE, repel = FALSE, labelPos = "all" , showMutationRate = TRUE, cBioPortal = TRUE))
invisible(dev.off())
##### Export pdf to png
lollipopPlot.image <- image_read_pdf(paste(mutationMapsDir, "/", paste(dataset, gene, sep="_"), ".pdf", sep = ""), pages = NULL, density = 300)
image_write(lollipopPlot.image, path = paste(mutationMapsDir, "/", paste(dataset, gene, sep="_"), ".png", sep = ""), format = "png")
##### Read in the PNG files
cat("![](",paste(paste0(mutationMapsDir, "/", paste(dataset, gene, sep="_")), ".png", sep = ""),")")
cat("<br/><br/><br/>")
##### Remove redundant pdf plot
file.remove(paste(mutationMapsDir, "/", paste(dataset, gene, sep="_"), ".pdf", sep = ""))
while (!is.null(dev.list())) invisible(dev.off())
} else {
cat(paste("**", gene, " have no non-synonymous variants detected in ", dataset, "dataset**.\n\n", sep=" "))
cat("\n***\n")
}
##### ...otherwise leave a message
} else {
##### Check if the genes has any synonymous vatiants
if ( length(pchange[pchange %in% colnames(mafInfo[[dataset]]@maf.silent)]) > 0 && gene %in% mafInfo[[dataset]]@maf.silent$Hugo_Symbol && any(!is.na(as.data.frame(mafInfo[[dataset]]@maf.silent)[ , pchange ])) ) {
cat(paste("This section was skipped for dataset", dataset, "since only synonymous variants were detected in", gene, "gene.\n\n", sep=" "))
} else {
cat(paste("This section was skipped for dataset", dataset, "since the corresponding MAF does not contain field with amino acid changes details!\n\n", sep=" "))
}
}
} else {
cat(paste("\n\n <b>", dataset, "</b> \n\n", sep=" "))
cat(paste("Gene <i>", gene, "</i> has no mutations reported in dataset", dataset, "\n\n", sep=" "))
}
}
}
##### A wrapper to saveWidget which compensates for arguable BUG in saveWidget which requires `file` to be in current working directory (see post https://github.com/ramnathv/htmlwidgets/issues/299 )
saveWidgetFix <- function ( widget, file, ...) {
wd<-getwd()
on.exit(setwd(wd))
outDir<-dirname(file)
file<-basename(file)
setwd(outDir);
htmlwidgets::saveWidget(widget,file=file,...)
}
##### Function for suppressing output from in-function printed message
quiet <- function(x) {
sink(tempfile())
on.exit(sink())
invisible(force(x))
}
##### Function to create oncomatrix that is also used for the oncoplot function
createOncoMatrix = function(m, g = NULL, chatty = TRUE, add_missing = FALSE){
if(is.null(g)){
stop("Please provde atleast two genes!")
}
subMaf = subsetMaf(maf = m, genes = g, includeSyn = FALSE, mafObj = FALSE, dropLevels = FALSE)
if(nrow(subMaf) == 0){
if(add_missing){
numericMatrix = matrix(data = 0, nrow = length(g), ncol = length(levels(getSampleSummary(x = m)[,Tumor_Sample_Barcode])))
rownames(numericMatrix) = g
colnames(numericMatrix) = levels(getSampleSummary(x = m)[,Tumor_Sample_Barcode])
oncoMatrix = matrix(data = "", nrow = length(g), ncol = length(levels(getSampleSummary(x = m)[,Tumor_Sample_Barcode])))
rownames(oncoMatrix) = g
colnames(oncoMatrix) = levels(getSampleSummary(x = m)[,Tumor_Sample_Barcode])
vc = c("")
names(vc) = 0
return(list(oncoMatrix = oncoMatrix, numericMatrix = numericMatrix, vc = vc))
}else{
return(NULL)
}
}
if(add_missing){
subMaf[, Hugo_Symbol := factor(x = Hugo_Symbol, levels = g)]
}
oncomat = data.table::dcast(data = subMaf[,.(Hugo_Symbol, Variant_Classification, Tumor_Sample_Barcode)], formula = Hugo_Symbol ~ Tumor_Sample_Barcode,
fun.aggregate = function(x){
x = unique(as.character(x))
xad = x[x %in% c('Amp', 'Del')]
xvc = x[!x %in% c('Amp', 'Del')]
if(length(xvc)>0){
xvc = ifelse(test = length(xvc) > 1, yes = 'Multi_Hit', no = xvc)
}
x = ifelse(test = length(xad) > 0, yes = paste(xad, xvc, sep = ';'), no = xvc)
x = gsub(pattern = ';$', replacement = '', x = x)
x = gsub(pattern = '^;', replacement = '', x = x)
return(x)
} , value.var = 'Variant_Classification', fill = '', drop = FALSE)
#convert to matrix
data.table::setDF(oncomat)
rownames(oncomat) = oncomat$Hugo_Symbol
oncomat = as.matrix(oncomat[,-1, drop = FALSE])
variant.classes = as.character(unique(subMaf[,Variant_Classification]))
variant.classes = c('',variant.classes, 'Multi_Hit')
names(variant.classes) = 0:(length(variant.classes)-1)
#Complex variant classes will be assigned a single integer.
vc.onc = unique(unlist(apply(oncomat, 2, unique)))
vc.onc = vc.onc[!vc.onc %in% names(variant.classes)]
names(vc.onc) = rep(as.character(as.numeric(names(variant.classes)[length(variant.classes)])+1), length(vc.onc))
variant.classes2 = c(variant.classes, vc.onc)
oncomat.copy <- oncomat
#Make a numeric coded matrix
for(i in 1:length(variant.classes2)){
oncomat[oncomat == variant.classes2[i]] = names(variant.classes2)[i]
}
#If maf has only one gene
if(nrow(oncomat) == 1){
mdf = t(matrix(as.numeric(oncomat)))
rownames(mdf) = rownames(oncomat)
colnames(mdf) = colnames(oncomat)
return(list(oncoMatrix = oncomat.copy, numericMatrix = mdf, vc = variant.classes))
}
#convert from character to numeric
mdf = as.matrix(apply(oncomat, 2, function(x) as.numeric(as.character(x))))
rownames(mdf) = rownames(oncomat.copy)
#If MAF file contains a single sample, simple sorting is enuf.
if(ncol(mdf) == 1){
sampleId = colnames(mdf)
mdf = as.matrix(mdf[order(mdf, decreasing = TRUE),])
colnames(mdf) = sampleId
oncomat.copy = as.matrix(oncomat.copy[rownames(mdf),])
colnames(oncomat.copy) = sampleId
return(list(oncoMatrix = oncomat.copy, numericMatrix = mdf, vc = variant.classes))
} else{
#Sort by rows as well columns if >1 samples present in MAF
#Add total variants per gene
mdf = cbind(mdf, variants = apply(mdf, 1, function(x) {
length(x[x != "0"])
}))
#Sort by total variants
mdf = mdf[order(mdf[, ncol(mdf)], decreasing = TRUE), ]
#colnames(mdf) = gsub(pattern = "^X", replacement = "", colnames(mdf))
nMut = mdf[, ncol(mdf)]
mdf = mdf[, -ncol(mdf)]
mdf.temp.copy = mdf #temp copy of original unsorted numeric coded matrix
mdf[mdf != 0] = 1 #replacing all non-zero integers with 1 improves sorting (& grouping)
tmdf = t(mdf) #transposematrix
mdf = t(tmdf[do.call(order, c(as.list(as.data.frame(tmdf)), decreasing = TRUE)), ]) #sort
mdf.temp.copy = mdf.temp.copy[rownames(mdf),] #organise original matrix into sorted matrix
mdf.temp.copy = mdf.temp.copy[,colnames(mdf)]
mdf = mdf.temp.copy
#organise original character matrix into sorted matrix
oncomat.copy <- oncomat.copy[,colnames(mdf)]
oncomat.copy <- oncomat.copy[rownames(mdf),]
return(list(oncoMatrix = oncomat.copy, numericMatrix = mdf, vc = variant.classes))
}
}
```
```{r load_libraries, warning=FALSE}
suppressMessages(library(knitr))
suppressMessages(library(maftools))
suppressMessages(library(pheatmap))
suppressMessages(library(NMF))
suppressMessages(library(openxlsx))
suppressMessages(library(ggplot2))
suppressMessages(library(DT))
suppressMessages(library(purrr))
suppressMessages(library(tidyverse))
suppressMessages(library(magick))
suppressMessages(library(htmltools))
suppressMessages(library(htmlwidgets))
suppressMessages(library(package=paste0("BSgenome.Hsapiens.UCSC.hg", params$ucsc_genome_assembly), character.only = TRUE))
```
```{r seed}
##### Set the seed
seed <- sample(0:99999999, 1, replace = TRUE)
set.seed(seed)
```
## Datasets
```{r datasets, comment = NA, message=FALSE, warning=FALSE}
##### Present patient cohorts to be summarised
##### Split the string of MAF files and put them into a vector
mafFiles <- unlist(strsplit(params$maf_files, split=',', fixed=TRUE))
mafFiles <- paste(params$maf_dir, mafFiles, sep="/")
##### Split the string of datasets names and put them into a vector
datasets.list <- unlist(strsplit(params$datasets, split=',', fixed=TRUE))
datasets.df <- as.data.frame( cbind(datasets.list, unlist(strsplit(params$maf_files, split=',', fixed=TRUE))) )
names(datasets.df) <- c("Dataset", "MAF file")
DT::datatable( data = datasets.df, filter = "none", extensions = 'Buttons', options = list(pageLength = length(mafFiles), dom = 'Bfrtip', buttons = c('excel', 'csv', 'pdf','copy')) ) %>%
DT::formatStyle( columns = names(datasets.df), 'text-align' = 'center' )
```
```{r load_data, comment = NA, message=FALSE, warning=FALSE, results='hide'}
##### Check if list of genes of interest is provided
if ( params$genes_list != "none" ) {
goi_status <- TRUE
} else {
goi_status <- FALSE
}
##### Check if list of pathways is provided
if ( params$pathways != "none" ) {
pathways_status <- TRUE
} else {
pathways_status <- FALSE
}
##### Read MAF files and put associated info into a list
##### Create a list to store MAF info for individual datasets
mafInfo <- vector("list", length(mafFiles))
names(mafInfo) <- datasets.list
mafInfo_tcgaCompare <- vector("list", length(mafFiles))
names(mafInfo_tcgaCompare) <- datasets.list
##### Check if file with clinical information is provided
clinicalInfo <- vector("list", length(mafFiles))
names(clinicalInfo) <- datasets.list
clinicalFeatures <- vector("list", length(mafFiles))
names(clinicalFeatures) <- datasets.list
if ( params$clinical_info != "none" ){
clinicalFiles <- unlist(strsplit(params$clinical_info, split=',', fixed=TRUE))
for ( i in 1:length(mafFiles) ) {
clinicalInfo[[i]] <- read.table(clinicalFiles[[i]], sep="\t", as.is=TRUE, header=TRUE, row.names=NULL, quote = "")
##### Define columns to be drawn in the oncoplot(s)
if ( params$clinical_features != "none" ){
clinicalFeatures[[i]] <- unlist(strsplit(params$clinical_features, split=',', fixed=TRUE))
##### Keep only those that are acrually present in provided clinical information file
clinicalFeatures[[i]] <- clinicalFeatures[[i]][ clinicalFeatures[[i]] %in% names(clinicalInfo[[i]]) ]
} else {
clinicalFeatures[[i]] <- ""
}
}
} else {
for ( i in 1:length(mafFiles) ) {
clinicalInfo[[i]] <- NA
}
}
##### NOTE: maftools by default summarises only non-synonymous variants with high/moderate variant consequences and ignores silent variants (https://github.com/PoisonAlien/maftools/issues/63), which are stored in "maf.silent" slot of the class MAF object (mafInfo[[i]]@maf.silent)
for ( i in 1:length(mafFiles) ) {
##### Add clinical information if provided
if ( any(!is.na(clinicalInfo[[i]])) ){
mafInfo[[i]] <- maftools::read.maf(maf = mafFiles[i], vc_nonSyn = unlist(strsplit(params$nonSyn_list, split=',', fixed=TRUE)), removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, clinicalData = NULL)
##### Make sure that the input MAF doesn't contain empty rows, which would throw errors in downstream analyses
##### List all samples and remove empty sample names
tsb <- as.vector(unlist(unique(mafInfo[[i]]@maf.silent[, "Tumor_Sample_Barcode"])))
tsb <- tsb[ tsb != "" ]
##### Subset the maf object to include only non-empty samples
maf.data <- subsetMaf(maf = mafInfo[[i]], tsb = tsb, genes = NULL, fields = NULL, query = NULL, mafObj = FALSE, includeSyn = TRUE, dropLevels=TRUE)
##### Convert the MAF data into Maf object
mafInfo[[i]] <- maftools::read.maf(maf = maf.data, vc_nonSyn = unlist(strsplit(params$nonSyn_list, split=',', fixed=TRUE)), removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, clinicalData = NULL)
##### Check if for any sample the clincal info is missing and add "NA"" to these samples
if ( length(unique(mafInfo[[i]]@data$Tumor_Sample_Barcode)[ unique(mafInfo[[i]]@data$Tumor_Sample_Barcode) %!in% clinicalInfo[[i]]$Tumor_Sample_Barcode]) > 0 ) {
clinicalInfo.missing <- unique(mafInfo[[1]]@data$Tumor_Sample_Barcode)[ unique(mafInfo[[1]]@data$Tumor_Sample_Barcode) %!in% clinicalInfo[[i]]$Tumor_Sample_Barcode]
##### Identify samples with missing info and add "NA"" to these samples
clinicalInfo.missing <- data.frame(cbind(as.character(clinicalInfo.missing)), rep(NA, length(clinicalInfo.missing)))
names(clinicalInfo.missing) <- names(clinicalInfo[[i]])
clinicalInfo[[i]] <- rbind(clinicalInfo[[i]], clinicalInfo.missing)
}
#### Convert numeric values to characters and make sure the clinical features names are correct
for (j in 1:length(clinicalFeatures[[i]])) {
clinicalInfo[[i]][, clinicalFeatures[[i]][j]] <- as.character(clinicalInfo[[i]][, clinicalFeatures[[i]][j]])
#clinicalInfo[[i]][, clinicalFeatures[[i]][j]] <- make.names(clinicalInfo[[i]][, clinicalFeatures[[i]][j]])
}
mafInfo[[i]] <- maftools::read.maf(maf = mafFiles[i], vc_nonSyn = unlist(strsplit(params$nonSyn_list, split=',', fixed=TRUE)), removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, clinicalData = clinicalInfo[[i]])
} else {
mafInfo[[i]] <- maftools::read.maf(maf = mafFiles[i], vc_nonSyn = unlist(strsplit(params$nonSyn_list, split=',', fixed=TRUE)), removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, clinicalData = NULL)
##### Make sure that the input MAF doesn't contain empty rows, which would throw errors in downstream analyses
##### List all samples and remove empty sample names
#tsb <- as.vector(unlist(unique(mafInfo[[i]]@maf.silent[, "Tumor_Sample_Barcode"])))
#tsb <- tsb[ tsb != "" ]
##### Subset the maf object to include only non-empty samples
#maf.data <- subsetMaf(maf = mafInfo[[i]], tsb = tsb, genes = NULL, fields = NULL, query = NULL, mafObj = FALSE, includeSyn = TRUE, dropLevels=TRUE)
##### Convert the MAF data into Maf object
#mafInfo[[i]] <- maftools::read.maf(maf = maf.data, vc_nonSyn = unlist(strsplit(params$nonSyn_list, split=',', fixed=TRUE)), removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, clinicalData = NULL)
}
}
##### Collect the number indiciating minimal percentage of patients carrying mutations in individual genes to be included in the report
##### Create a list to store MAF info for individual datasets
genes_min <- vector("list", length(mafFiles))
names(genes_min) <- datasets.list
for ( i in 1:length(mafFiles) ) {
genes_min[[i]] <- unlist(strsplit(params$genes_min, split=',', fixed=TRUE))[[i]]
}
##### If two datasets are provided then also perform cohorts comparison with mafCompare() function
if ( length(mafFiles) == 2 ) {
runMafCompare <- TRUE
} else {
runMafCompare <- FALSE
}
##### Read in PURPLE output files if defined by user
# https://www.bioconductor.org/packages/devel/bioc/vignettes/maftools/inst/doc/oncoplots.html#032_custom_copy-number_table
nonSyn_list <- unlist(strsplit(params$nonSyn_list, split=',', fixed=TRUE))
cn_df <- NULL
if ( params$purple != "none" ){
purpleFiles <- unlist(strsplit(params$purple, split=',', fixed=TRUE))
for ( i in 1:length(mafFiles) ) {
cn_df <- NULL
##### Deal with the newer PURPLE output format
purple_files <- list.files(purpleFiles, pattern = "*.purple.cnv.gene.tsv", full.names = TRUE)
if ( length(purple_files) > 0 ) {
purple_dfs <- purple_files %>% map(~ mutate(read_tsv(.), fname = .))
purple_df = purple_dfs %>%
bind_rows %>%
#filter(gene %in% c("KRAS", "TP53")) %>%
mutate(sample = fname %>% basename %>% str_replace('.purple.cnv.gene.tsv', '')) %>%
rowwise() %>% mutate(cn = mean(minCopyNumber, maxCopyNumber)) %>%
select(gene, sample, cn) %>%
mutate(
ampdel = case_when(
(cn < params$purple_hd) ~ "HD",
(cn >= params$purple_hd & cn < params$purple_loh) ~ "LOH",
(cn >= params$purple_loh & cn < params$purple_amp) ~ "NA",
(cn >= params$purple_amp) ~ "AMP",
TRUE ~ "NA"
))
##### Remove entries with NAs
purple_df = purple_df %>%
filter(ampdel %!in% "NA")
cn_df <- purple_df
}
##### Also deal with the older PURPLE output format
purple_files <- list.files(purpleFiles, pattern = "*.purple.gene.cnv", full.names = TRUE)
if ( length(purple_files) > 0 ) {
purple_dfs <- purple_files %>% map(~ mutate(read_tsv(.), fname = .))
purple_df = purple_dfs %>%
bind_rows %>%
#filter(gene %in% c("KRAS", "TP53")) %>%
mutate(sample = fname %>% basename %>% str_replace('.purple.cnv.gene.tsv', '')) %>%
rowwise() %>% mutate(cn = mean(MinCopyNumber, MaxCopyNumber)) %>%
select(Gene, sample, cn) %>%
mutate(
ampdel = case_when(
(cn < params$purple_hd) ~ "HD",
(cn >= params$purple_hd & cn < params$purple_loh) ~ "LOH",
(cn >= params$purple_loh & cn < params$purple_amp) ~ "NA",
(cn >= params$purple_amp) ~ "AMP",
TRUE ~ "NA"
))
##### Remove entries with NAs
purple_df = purple_df %>%
filter(ampdel %!in% "NA")
colnames(purple_df) <- gsub("Gene", "gene", colnames(purple_df))
cn_df <- rbind(cn_df, purple_df)
}
# Then feed the result into read.maf
maf.data <- rbind(mafInfo[[i]]@data, mafInfo[[i]]@maf.silent)
nonSyn_list <- unique(c(nonSyn_list, cn_df$ampdel))
##### Save maf object without CN results for the tcgaCompare fucntion frist
mafInfo_tcgaCompare[[i]] <- maftools::read.maf(maf = maf.data, vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, clinicalData = NULL)
##### Add clinical information if provided
if ( !is.na(clinicalInfo[[i]]) ) {
mafInfo[[i]] <- maftools::read.maf(maf = maf.data, vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, cnTable = cn_df %>% select(Gene = gene, Sample_name = sample, CN = ampdel), clinicalData = clinicalInfo[[i]])
} else {
mafInfo[[i]] <- maftools::read.maf(maf = maf.data, vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, cnTable = cn_df %>% select(Gene = gene, Sample_name = sample, CN = ampdel), clinicalData = NULL)
}
##### For some reason the read.maf() function adds "Tumor_Sample_barcode" column with "NA"s
tsb <- as.vector(unlist(unique(mafInfo[[i]]@maf.silent[, "Tumor_Sample_Barcode"])))
tsb <- tsb[ tsb != "" ]
mafInfo[[i]] <- subsetMaf(maf = mafInfo[[i]], tsb = tsb, genes = NULL, fields = colnames(mafInfo[[i]]@data)[!colnames(mafInfo[[i]]@data) %in% "Tumor_Sample_barcode" ], query = NULL, mafObj = TRUE, includeSyn = TRUE, dropLevels=TRUE)
}
}
##### Read in CNVkit output files if defined by user
# https://www.bioconductor.org/packages/devel/bioc/vignettes/maftools/inst/doc/oncoplots.html#032_custom_copy-number_table
if ( params$cnvkit != "none" ){
cnvkitFiles <- unlist(strsplit(params$purple, split=',', fixed=TRUE))
for ( i in 1:length(mafFiles) ) {
cnvkit_files <- list.files(cnvkitFiles, pattern = "*-cnvkit-call.cns", full.names = T)
cnvkit_df = cnvkit_files %>%
map(~ mutate(read_tsv(.), fname = .)) %>%
bind_rows %>%
mutate(sample = fname %>% basename %>% str_replace("-cnvkit-call.cns", "")) %>%
select(gene, sample, cn) %>%
mutate(gene = gene %>% str_split(",")) %>%
unnest(gene)
cnvkit_df = cnvkit_df %>%
mutate(
ampdel = case_when(
(cn < params$cnvkit_hd) ~ "HD",
(cn >= params$cnvkit_hd & cn < params$cnvkit_loh) ~ "LOH",
(cn >= params$cnvkit_loh & cn < params$cnvkit_amp) ~ "NA",
(cn >= params$cnvkit_amp) ~ "AMP",
TRUE ~ "NA"
))
##### Remove entries with NAs
##### Add PURPLE results if provided
if ( !is.null( cn_df) ) {
cnvkit_df = cnvkit_df %>%
filter(ampdel %!in% "NA")
cn_df <- rbind(cn_df, cnvkit_df)
} else {
cnvkit_df = cnvkit_df %>%
filter(ampdel %!in% "NA")
cn_df <- cnvkit_df
}
# Then feed the result into read.maf
maf.data <- rbind(mafInfo[[i]]@data, mafInfo[[i]]@maf.silent)
nonSyn_list <- unique(c(nonSyn_list, cn_df$ampdel))
##### Save maf object without CN results for the tcgaCompare fucntion frist
mafInfo_tcgaCompare[[i]] <- maftools::read.maf(maf = maf.data, vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, clinicalData = NULL)
##### Add clinical information if provided
if ( !is.na(clinicalInfo[[i]]) ) {
mafInfo[[i]] <- maftools::read.maf(maf = maf.data, vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, cnTable = cn_df %>% select(Gene = gene, Sample_name = sample, CN = ampdel), clinicalData = clinicalInfo[[i]])
} else {
mafInfo[[i]] <- maftools::read.maf(maf = maf.data, vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, cnTable = cn_df %>% select(Gene = gene, Sample_name = sample, CN = ampdel), clinicalData = NULL)
}
##### For some reason the read.maf() function adds "Tumor_Sample_barcode" column with "NA"s
##### For some reason the read.maf() function adds "Tumor_Sample_barcode" column with "NA"s
tsb <- as.vector(unlist(unique(mafInfo[[i]]@maf.silent[, "Tumor_Sample_Barcode"])))
tsb <- tsb[ tsb != "" ]
mafInfo[[i]] <- subsetMaf(maf = mafInfo[[i]], tsb = tsb, genes = NULL, fields = colnames(mafInfo[[i]]@data)[!colnames(mafInfo[[i]]@data) %in% "Tumor_Sample_barcode" ], query = NULL, mafObj = TRUE, includeSyn = TRUE, dropLevels=TRUE)
}
}
##### Read in GISTIC output files if defined by user
runGistic <- FALSE
##### Create a list to store GISTIC info for individual datasets
gisticInfo <- vector("list", length(mafFiles))
names(gisticInfo) <- datasets.list
if ( params$gistic != "none" ){
gisticFiles <- unlist(strsplit(params$gistic, split=',', fixed=TRUE))
for ( i in 1:length(mafFiles) ) {
##### List required files in the GISTIC output directory
gisticInfo[[i]]$all.lesions <- list.files(params$gistic, pattern="all_lesions.conf", all.files=FALSE,
full.names=TRUE)
gisticInfo[[i]]$amp.genes <- list.files(params$gistic, pattern="amp_genes.conf", all.files=FALSE,
full.names=TRUE)
gisticInfo[[i]]$del.genes <- list.files(params$gistic, pattern="del_genes.conf", all.files=FALSE,
full.names=TRUE)
gisticInfo[[i]]$scores.gis <- list.files(params$gistic, pattern="scores.gistic", all.files=FALSE,
full.names=TRUE)
##### Check if GISTIC output files exist
if ( !is.na(gisticInfo[[i]]$all.lesions[1]) && !is.na(gisticInfo[[i]]$amp.genes[1]) && !is.na(gisticInfo[[i]]$del.genes[1]) && !is.na(gisticInfo[[i]]$scores.gis[1]) ) {
runGistic <- TRUE
gisticInfo[[i]]$status <- TRUE
gisticInfo[[i]]$summary = readGistic(gisticAllLesionsFile = gisticInfo[[i]]$all.lesions, gisticAmpGenesFile = gisticInfo[[i]]$amp.genes, gisticDelGenesFile = gisticInfo[[i]]$del.genes, gisticScoresFile = gisticInfo[[i]]$scores.gis)
nonSyn_list <- unique(c(nonSyn_list, gisticInfo[[i]]$summary@classCode[ gisticInfo[[i]]$summary@classCode != "" ]))
} else {
gisticInfo[[i]]$status <- FALSE
}
}
} else {
for ( i in 1:length(mafFiles) ) {
gisticInfo[[i]]$status <- FALSE
}
}
##### Change the column to be used to indicate samples' IDs
if ( !is.null(params$samples_id_cols) ) {
samples_id_cols <- make.names(unlist(strsplit(params$samples_id_cols, split=',', fixed=TRUE)))
for ( i in 1:length(mafFiles) ) {
##### Check if use-defined column name exists
if ( samples_id_cols[i] %in% names(mafInfo[[i]]@data) && samples_id_cols[i] != "Tumor_Sample_Barcode" ) {
##### Change the use-defined column with samples' IDs to "Tumor_Sample_Barcode". If this column name already exist, then renames it to "Tumor_Sample_Barcode.orig"
maf.data <- rbind(mafInfo[[i]]@data, mafInfo[[i]]@maf.silent)
if ( samples_id_cols[i] %in% names(maf.data) ) {
names(maf.data) <- gsub("Tumor_Sample_Barcode", "Tumor_Sample_Barcode.orig", names(maf.data))
names(maf.data) <- gsub(samples_id_cols[i], "Tumor_Sample_Barcode", names(maf.data))
} else {
cat(paste0("\nColumn \"", samples_id_cols[i], "\" does not exist in MAF file ", mafFiles[i], "!\n\n"))
}
##### Now read the data with changess column names as a maf object
if ( gisticInfo[[i]]$status ) {
##### Add clinical information if provided
if ( !is.na(clinicalInfo[[i]]) ){
mafInfo[[i]] <- maftools::read.maf(maf = maf.data, vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, gisticAllLesionsFile = gisticInfo[[i]]$all.lesions, gisticAmpGenesFile = gisticInfo[[i]]$amp.genes, gisticDelGenesFile = gisticInfo[[i]]$del.genes, gisticScoresFile = gisticInfo[[i]]$scores.gis, verbose = FALSE, clinicalData = clinicalInfo[[i]])
} else {
mafInfo[[i]] <- maftools::read.maf(maf = maf.data, vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, gisticAllLesionsFile = gisticInfo[[i]]$all.lesions, gisticAmpGenesFile = gisticInfo[[i]]$amp.genes, gisticDelGenesFile = gisticInfo[[i]]$del.genes, gisticScoresFile = gisticInfo[[i]]$scores.gis, verbose = FALSE, clinicalData = NULL)
}
##### Save maf object without GISTIC results as well for the tcgaCompare fucntion
mafInfo_tcgaCompare[[i]] <- maftools::read.maf(maf = maf.data, vc_nonSyn = onSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, clinicalData = NULL)
} else {
##### Add clinical information if provided
if ( !is.na(clinicalInfo[[i]]) ){
mafInfo[[i]] <- maftools::read.maf(maf = maf.data, vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, clinicalData = clinicalInfo[[i]])
} else {
mafInfo[[i]] <- maftools::read.maf(maf = maf.data, vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, clinicalData = NULL)
}
}
}
}
} else {
##### Add GISTIC results if defined by user
for ( i in 1:length(mafFiles) ) {
if ( gisticInfo[[i]]$status ) {
##### Add clinical information if provided
if ( !is.na(clinicalInfo[[i]]) ){
mafInfo[[i]] <- maftools::read.maf(maf = mafFiles[i], vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, gisticAllLesionsFile = gisticInfo[[i]]$all.lesions, gisticAmpGenesFile = gisticInfo[[i]]$amp.genes, gisticDelGenesFile = gisticInfo[[i]]$del.genes, gisticScoresFile = gisticInfo[[i]]$scores.gis, verbose = FALSE, clinicalData = clinicalInfo[[i]])
} else {
mafInfo[[i]] <- maftools::read.maf(maf = mafFiles[i], vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, gisticAllLesionsFile = gisticInfo[[i]]$all.lesions, gisticAmpGenesFile = gisticInfo[[i]]$amp.genes, gisticDelGenesFile = gisticInfo[[i]]$del.genes, gisticScoresFile = gisticInfo[[i]]$scores.gis, verbose = FALSE)
}
##### Save maf object without GISTIC results as well for the tcgaCompare fucntion
mafInfo_tcgaCompare[[i]] <- maftools::read.maf(maf = mafFiles[i], vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE, clinicalData = NULL)
}
}
}
##### Create directory for output files
outDir <- paste(params$maf_dir, params$out_folder, "results", sep = "/")
if ( !file.exists(params$out_folder) ){
dir.create(outDir, recursive=TRUE)
}
##### Read in list of genes of interest of specified
goi <- vector("list", length(mafFiles))
names(goi) <- datasets.list
if ( params$genes_list != "none" ){
genes_lists <- unlist(strsplit(params$genes_list, split=',', fixed=TRUE))
for ( i in 1:length(mafFiles) ) {
goi[[i]] <- unique(read.table(genes_lists[i], sep="\t", as.is=TRUE, header=FALSE, row.names=NULL)[,1])
}
}
```
```{r include_exclude_samples, comment=NA, message=FALSE, warning=FALSE, results='hide'}
##### Include user-defined samples(s) for the analysis
if ( params$samples_list != "none" ) {
for ( i in 1:length(mafFiles) ) {
##### Read in list of samples to be included
inclsamples.df <- read.table(params$samples_list, sep="\t", as.is=TRUE, header=TRUE, row.names=NULL)
samples2keep <- unique(inclsamples.df[,"Tumor_Sample_Barcode"])
##### Subset the maf object to include only use-defined sample(s)
##### Initially don't save the subset output as maf object, as this will exlude samples with no non-synonymous mutations from the summary
mafInfo[[i]] <- subsetMaf(maf = mafInfo[[i]], tsb = as.vector(samples2keep), genes = NULL, fields = NULL, query = NULL, mafObj = FALSE, includeSyn = TRUE, dropLevels=TRUE)
##### Now read the data subset as a maf object
if ( gisticInfo[[i]]$status ) {
mafInfo[[i]] <- maftools::read.maf(maf = mafInfo[[i]], vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, gisticAllLesionsFile = gisticInfo[[i]]$all.lesions, gisticAmpGenesFile = gisticInfo[[i]]$amp.genes, gisticDelGenesFile = gisticInfo[[i]]$del.genes, gisticScoresFile = gisticInfo[[i]]$scores.gis, verbose = FALSE)
} else {
mafInfo[[i]] <- maftools::read.maf(maf = mafInfo[[i]], vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE)
}
}
}
if ( params$samples_blacklist != "none" ) {
for ( i in 1:length(mafFiles) ) {
##### Read in list of samples to be excluded and convert to char vector
exclsamples.df <- read.table(params$samples_blacklist, sep="\t", as.is=TRUE, header=TRUE, row.names=NULL)
exclsamples_char <- unique(exclsamples.df$Tumor_Sample_Barcode)
tumor_sample_barcodes <- mafInfo[[i]]@data$Tumor_Sample_Barcode
unique_tumor_barcodes <- unique(tumor_sample_barcodes)
samples2keep <- unique_tumor_barcodes[!unique_tumor_barcodes %in% exclsamples_char]
#samples2keep <- unlist(unique( mafInfo[[i]]@data[, "Tumor_Sample_Barcode"])[ unique(mafInfo[[i]]@data[, "Tumor_Sample_Barcode"]) %!in% exclsamples_char ])
##### Subset the maf object to exclude use-defined sample(s)
##### Initially don't save the subset output as maf object, as this will exclude samples with no non-synonymous mutations from the summary
#mafInfo[[i]] <- filterMaf(maf = mafInfo[[i]], tsb = exclsamples_char, mafObj = FALSE)
mafInfo[[i]] <- subsetMaf(maf = mafInfo[[i]], tsb = as.vector(samples2keep), genes = NULL, fields = NULL, query = NULL, mafObj = FALSE, includeSyn = TRUE, dropLevels=TRUE)
##### Now read the data subset as a maf object
if ( gisticInfo[[i]]$status ) {
mafInfo[[i]] <- maftools::read.maf(maf = mafInfo[[i]], vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, gisticAllLesionsFile = gisticInfo[[i]]$all.lesions, gisticAmpGenesFile = gisticInfo[[i]]$amp.genes, gisticDelGenesFile = gisticInfo[[i]]$del.genes, gisticScoresFile = gisticInfo[[i]]$scores.gis, verbose = FALSE)
} else {
mafInfo[[i]] <- maftools::read.maf(maf = mafInfo[[i]], vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE)
}
}
}
```
```{r exclude_genes, comment=NA, message=FALSE, warning=FALSE}
##### Exclude user-defined gene(s) from the analysis
if ( params$genes_blacklist != "none" ) {
for ( i in 1:length(mafFiles) ) {
##### Read in list of genes to be excluded
exclgenes <- unique(read.table(params$genes_blacklist, sep="\t", as.is=TRUE, header=FALSE, row.names=NULL)[,1])
genes2keep <- unique( mafInfo[[i]]@data$Hugo_Symbol)[ unique( mafInfo[[i]]@data$Hugo_Symbol) %!in% exclgenes ]
##### Subset the maf object to exclude use-defined gene(s)
##### Initially don't save the subset output as maf object, as this will exlude samples with no non-synonymous mutations from the summary
mafInfo[[i]] <- subsetMaf(maf = mafInfo[[i]], tsb = NULL, genes = genes2keep, fields = NULL, query = NULL, mafObj = FALSE, includeSyn = TRUE)
##### Now read the data subset as a maf object
if ( gisticInfo[[i]]$status ) {
mafInfo[[i]] <- maftools::read.maf(maf = mafInfo[[i]], vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, gisticAllLesionsFile = gisticInfo[[i]]$all.lesions, gisticAmpGenesFile = gisticInfo[[i]]$amp.genes, gisticDelGenesFile = gisticInfo[[i]]$del.genes, gisticScoresFile = gisticInfo[[i]]$scores.gis, verbose = FALSE)
} else {
mafInfo[[i]] <- maftools::read.maf(maf = mafInfo[[i]], vc_nonSyn = nonSyn_list, removeDuplicatedVariants = params$remove_duplicated_variants, verbose = FALSE)
}
}
}
```
```{r silent_variants, comment = NA, message=FALSE, warning=FALSE}
##### Identify and record samples with no non-synonymous mutations
##### Prepare list to store all samples and samples with > 0 non-synonymous variants
MAF_samples <- vector("list", length(datasets.list))
names(MAF_samples) <- datasets.list
MAF_samples.silent.df <- NULL
##### Loop through MAF files
for ( i in 1:length(mafFiles) ) {
##### Identify samples with no non-synonymours variants according to corresponding MAF file
MAF_samples[[i]]$all <- unlist(unique(mafInfo[[i]]@maf.silent[, "Tumor_Sample_Barcode"]))
MAF_samples[[i]]$nonsyn <- unlist(maftools::getSampleSummary(mafInfo[[i]])[, "Tumor_Sample_Barcode"])
MAF_samples[[i]]$silent <- MAF_samples[[i]]$all[ MAF_samples[[i]]$all %!in% MAF_samples[[i]]$nonsyn ]
##### Check if there are any samples with no non-synonymours variants. If so, add them to data frame
if ( length(MAF_samples[[i]]$silent) > 0 ) {
for ( sample in MAF_samples[[i]]$silent ) {
MAF_samples.silent.df <- rbind( MAF_samples.silent.df, cbind( datasets.list[i], sample))
}
colnames(MAF_samples.silent.df) <- c("Dataset", "Sample")
}
}
##### List silent variants classifications
silent_categories <- NULL
for ( i in 1:length(mafFiles) ) {
silent_categories <- unique( c(silent_categories, mafInfo[[i]]@maf.silent$Variant_Classification) )
}
```
***
## Summary
### Tables {.tabset}
#### Overall summary
Table(s) with basic information about each dataset based on data in corresponding MAF file(s).
```{r overll_summary, comment = NA, message=FALSE, warning=FALSE}
dir.create(paste(outDir, "summary", datasets.df[[i]], sep="/"), recursive = TRUE)
##### Write overall summary into a file
for ( i in 1:length(mafFiles) ) {
write.mafSummary(maf = mafInfo[[i]], basename = paste(outDir, "summary", datasets.df[[i]], sep="/"))
}
##### Assign different colour to individual datasets
datasets.colour <- getDatasetsColours(datasets.list)
##### Create a new workbook
wb <- createWorkbook("MAF_summary.xlsx")
##### Add worksheets, one for each dataset
for ( i in 1:length(mafFiles) ) {
addWorksheet(wb, substring(datasets.list[i], 0, 31), tabColour = datasets.colour[[1]][i])
writeData(wb, sheet = i, mafInfo[[i]]@summary)
}