-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCGC search.R
More file actions
2405 lines (2008 loc) · 123 KB
/
CGC search.R
File metadata and controls
2405 lines (2008 loc) · 123 KB
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
###################################################################
#### This is a file with random functions that accummulates
###################################################################
MC3_bailey = MC3_bailey_filtered
intersect(intersect(grep("LOW", MC3_bailey$IMPACT),
grep("benign", MC3_bailey$PolyPhen)),
grep("tolerated|tolerated_low_confidence", MC3_bailey$SIFT)) -> id
MC3_bailey_filtered = MC3_bailey
MC3_bailey = MC3_bailey_filtered
library(dplyr)
summary_cohort = MC3_bailey %>%
group_by(CODE) %>%
summarise(num_samples = n_distinct(Tumor_Sample_Barcode),
num_alterations = n())
summary_cohort$CODE = factor(summary_cohort$CODE,levels = summary_cohort$CODE[order(summary_cohort$num_samples)])
library(dplyr)
library(ggplot2)
library(ggrepel)
library(forcats)
library(scales)
df=melt(summary_cohort)
p<-ggplot(data=df, aes(x=CODE, y=value)) +
geom_col()+
facet_grid( variable ~ ., scales = "free")+
# ggtitle("Number of samples in each cancer type") +
ylab("Number of samples and alterations") + xlab("Cancer types") +
theme(axis.text.x=element_text(angle=30,hjust=0.75,vjust=0.75, size = 12, face = "bold"))
p
ggsave("/Users/let/Desktop/a.png",width = 12, height = 9)
df = data.frame(sort(summary(MC3_bailey_filtered$Variant_Classification)))
df$MutClass = rownames(df)
colnames(df)[1] = "value"
df %>%
mutate(prop = round(df$value*100 / sum(df$value), 2)) -> df
df$position = cumsum(df$prop) - df$prop/2
pie <- ggplot(df, aes(x ="", y = prop, fill = fct_reorder(MutClass,prop, desc))) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y") +
geom_label_repel(aes(y=position, label = value), size=5, show.legend = F, nudge_x = 1) +
guides(fill = guide_legend(title = "Mutation Class"))
pie
library(plotrix)
pie3D(df$prop, labels = df$MutClass, main = "Mutation Class",
explode=0.1, radius=.9, labelcex = 1.2, start=0.7)
CGC_types = Census_allMon.Oct.29.14_00_10.2018$Tumour.Types.Somatic.
uniqueCGCtypes = unique(unlist(strsplit(CGC_types, ", ", fixed = TRUE, perl = FALSE, useBytes = FALSE)))
CGC_genelist = list()
CGC_genelist$ACC = CGC$Gene.Symbol[grep('adrenocortical', CGC$Tumour.Types.Somatic.)]
CGC_genelist$BLCA = CGC$Gene.Symbol[setdiff(grep('bladder|urothelial', CGC$Tumour.Types.Somatic.),
grep('gall', CGC$Tumour.Types.Somatic.))]
CGC_genelist$BRCA = CGC$Gene.Symbol[grep('breast', CGC$Tumour.Types.Somatic.)] #breast_cancer and triple_negative_breast_cancer
CGC_genelist$CESC = CGC$Gene.Symbol[grep('cervical', CGC$Tumour.Types.Somatic.)]
CGC_genelist$CHOL = CGC$Gene.Symbol[grep('cholangiocarcinoma|biliary tract', CGC$Tumour.Types.Somatic.)]
CGC_genelist$COAD = CGC$Gene.Symbol[grep('colon|colorectal', CGC$Tumour.Types.Somatic.)] #colorectal = colon + rectum => combine or not
CGC_genelist$DLBC = CGC$Gene.Symbol[grep('DLBCL', CGC$Tumour.Types.Somatic.)] #or anything with B cell carcinoma ("B-")?
CGC_genelist$ESCA = CGC$Gene.Symbol[grep('oesophageal', CGC$Tumour.Types.Somatic.)]
CGC_genelist$GBM = CGC$Gene.Symbol[grep('glioblastoma|GBM', CGC$Tumour.Types.Somatic.)]
CGC_genelist$HNSC = CGC$Gene.Symbol[grep('HNSCC|head|neck|oral squamous', CGC$Tumour.Types.Somatic.)]
CGC_genelist$KICH = CGC$Gene.Symbol[grep('kidney', CGC$Tumour.Types.Somatic.)] # no chromophobe mensioned
CGC_genelist$KIRC = CGC$Gene.Symbol[grep('kidney|clear cell renal|RCC', CGC$Tumour.Types.Somatic.)] #CGC only have kidney cancer
CGC_genelist$KIRP = CGC$Gene.Symbol[grep('kidney|papillary renal', CGC$Tumour.Types.Somatic.)] # 90% of kidney cancers are clear cell
CGC_genelist$LAML = CGC$Gene.Symbol[grep('AML', CGC$Tumour.Types.Somatic.)]
CGC_genelist$LGG = CGC$Gene.Symbol[setdiff(grep('glioma', CGC$Tumour.Types.Somatic.),
grep('paraganglioma', CGC$Tumour.Types.Somatic.))]
CGC_genelist$LIHC = CGC$Gene.Symbol[grep('hepatocellular', CGC$Tumour.Types.Somatic.)]
CGC_genelist$LUAD = CGC$Gene.Symbol[grep('lung adenocarcinoma', CGC$Tumour.Types.Somatic.)] #lung, lung cancer , lung carcinoma, NSCLC can be both
CGC_genelist$LUSC = CGC$Gene.Symbol[grep('lung SCC', CGC$Tumour.Types.Somatic.)]
CGC_genelist$MESO = CGC$Gene.Symbol[grep('mesothelioma', CGC$Tumour.Types.Somatic.)]
CGC_genelist$OV = CGC$Gene.Symbol[setdiff(grep('ovarian', CGC$Tumour.Types.Somatic.),
grep('mixed germ cell tumour', CGC$Tumour.Types.Somatic.))]
CGC_genelist$PAAD = CGC$Gene.Symbol[setdiff(grep('pancrea', CGC$Tumour.Types.Somatic.),
grep("neuroendocrine", CGC$Tumour.Types.Somatic.))]
CGC_genelist$PCPG = CGC$Gene.Symbol[grep('pheochromocytoma|paraganglioma', CGC$Tumour.Types.Somatic.)]
CGC_genelist$PRAD = CGC$Gene.Symbol[grep('prostate', CGC$Tumour.Types.Somatic.)]
CGC_genelist$READ = CGC$Gene.Symbol[grep('colorectal', CGC$Tumour.Types.Somatic.)]
CGC_genelist$SARC = CGC$Gene.Symbol[setdiff(grep('sarcoma', CGC$Tumour.Types.Somatic.),
grep('uterine|endometrial', CGC$Tumour.Types.Somatic.))]
CGC_genelist$SKCM = CGC$Gene.Symbol[setdiff(grep('melanoma', CGC$Tumour.Types.Somatic.),
grep('mucosal|soft|uveal', CGC$Tumour.Types.Somatic.))]
CGC_genelist$STAD = CGC$Gene.Symbol[grep('stomach|gastric', CGC$Tumour.Types.Somatic.)]
CGC_genelist$TGCT = CGC$Gene.Symbol[grep('testicular', CGC$Tumour.Types.Somatic.)]
CGC_genelist$THCA = CGC$Gene.Symbol[setdiff(grep('thyroid', CGC$Tumour.Types.Somatic.),
grep('parathyroid', CGC$Tumour.Types.Somatic.))]
CGC_genelist$THYM = CGC$Gene.Symbol[grep('thymoma', CGC$Tumour.Types.Somatic.)] #there is no thymic or thymoma
CGC_genelist$UCEC = CGC$Gene.Symbol[setdiff(grep('uterine serous|endometri', CGC$Tumour.Types.Somatic.),
grep('stromal', CGC$Tumour.Types.Somatic.))]
CGC_genelist$UCS = CGC$Gene.Symbol[grep('uterine carcinosarcoma', CGC$Tumour.Types.Somatic.)]
CGC_genelist$UVM = CGC$Gene.Symbol[grep('uveal', CGC$Tumour.Types.Somatic.)]
library(reshape2)
CGC_genes = melt(CGC_genelist)
CGC_genes_CODEsum = as.data.frame(table(CGC_genes$L1))
p<-ggplot(data=CGC_genes_CODEsum, aes(x=Var1, y=Freq)) +
geom_bar(stat="identity") +
theme(axis.text.x=element_text(angle=30,hjust=1,vjust=1))
p
# Over lapping the number of samples and alterations
trainsetCGC = data.frame(matrix(ncol=115))
colnames(trainsetCGC) = colnames(MC3_bailey_filtered)
for (i in 1:length(CGC_genelist)){
trainsetCGC = rbind(trainsetCGC,
MC3_bailey_filtered[intersect(which(MC3_bailey_filtered$CODE == names(CGC_genelist)[i]),
which(MC3_bailey_filtered$Hugo_Symbol %in% unlist(CGC_genelist[i]))),])
}
trainsetCGC = trainsetCGC[-1,]
df = trainsetCGC %>%
group_by(CODE) %>%
summarise(num_samples = n_distinct(Tumor_Sample_Barcode),
num_alterations = n())
##############################################################
#### Search in NCG6
##############################################################
NCGgene = NCG6_systemslevelproperties$symbol[grep("cgc|vog", NCG6_systemslevelproperties$cancer_type)]
#NCG6_cancergenes = NCG6_cancergenes.tsv
#NCG6_cancergenes.tsv = NCG6_cancergenes[which(NCG6_cancergenes$symbol %in% NCGgene),]
NCG_genelist = list()
#common = NCG6_cancergenes.tsv$symbol[grep('multiple', NCG6_cancergenes.tsv$primary_site)]
NCG_genelist$ACC = NCG6_cancergenes.tsv$symbol[grep('adrenocortical', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$BLCA = NCG6_cancergenes.tsv$symbol[grep('bladder_cancer', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$BRCA = NCG6_cancergenes.tsv$symbol[grep('breast', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$CESC = NCG6_cancergenes.tsv$symbol[grep('cervical', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$CHOL = NCG6_cancergenes.tsv$symbol[grep('cholangio|biliary_tract_cancer', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$COAD = NCG6_cancergenes.tsv$symbol[grep('colorectal', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$DLBC = NCG6_cancergenes.tsv$symbol[grep('B-cell|cutaneous_DLBCL', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$ESCA = NCG6_cancergenes.tsv$symbol[grep('esophageal', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$GBM = NCG6_cancergenes.tsv$symbol[grep('glioblastoma', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$HNSC = NCG6_cancergenes.tsv$symbol[grep('squamous_head_and_neck', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$KICH = NCG6_cancergenes.tsv$symbol[grep('chromophobe', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$KIRC = NCG6_cancergenes.tsv$symbol[grep('clear_cell_renal_cancer', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$KIRP = NCG6_cancergenes.tsv$symbol[grep('papillary_renal_cell_carcinoma', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$LAML = NCG6_cancergenes.tsv$symbol[grep('acute_myeloid_leukemia', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$LGG = NCG6_cancergenes.tsv$symbol[grep('low_grade_glioma', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$LIHC = NCG6_cancergenes.tsv$symbol[grep('hepatocellular_carcinoma|pan-liver', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$LUAD = NCG6_cancergenes.tsv$symbol[grep('lung_adenocarcinoma|lung_cancer', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$LUSC = NCG6_cancergenes.tsv$symbol[grep('lung_squamous|non-small_cell_lung_cancer', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$MESO = NCG6_cancergenes.tsv$symbol[grep('meso', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$OV = NCG6_cancergenes.tsv$symbol[grep('ovarian_serous|ovarian_cancer', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$PAAD = NCG6_cancergenes.tsv$symbol[grep('pancreatic', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$PCPG = NCG6_cancergenes.tsv$symbol[grep('pheochromocytoma,_paraganglioma', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$PRAD = NCG6_cancergenes.tsv$symbol[grep('prostate_cancer', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$READ = NCG6_cancergenes.tsv$symbol[grep('colorectal', NCG6_cancergenes.tsv$cancer_type)] # colon and rectal are bound
NCG_genelist$SARC = NCG6_cancergenes.tsv$symbol[setdiff(grep('sarcoma', NCG6_cancergenes.tsv$cancer_type),
grep('uterine', NCG6_cancergenes.tsv$cancer_type))]
NCG_genelist$SKCM = NCG6_cancergenes.tsv$symbol[setdiff(grep('melanoma', NCG6_cancergenes.tsv$cancer_type),
union(grep('mucosal', NCG6_cancergenes.tsv$cancer_type),
grep('uvea', NCG6_cancergenes.tsv$primary_site)))]
NCG_genelist$STAD = NCG6_cancergenes.tsv$symbol[grep('gastric', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$TGCT = NCG6_cancergenes.tsv$symbol[grep('testicular', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$THCA = NCG6_cancergenes.tsv$symbol[grep('thyroid', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$THYM = NCG6_cancergenes.tsv$symbol[grep('thymic', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$UCEC = NCG6_cancergenes.tsv$symbol[grep('endometrial', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$UCS = NCG6_cancergenes.tsv$symbol[grep('uterine', NCG6_cancergenes.tsv$cancer_type)]
NCG_genelist$UVM = NCG6_cancergenes.tsv$symbol[grep('uvea', NCG6_cancergenes.tsv$primary_site)]
'''
for (i in 1:length(NCG_genelist)){
NCG_genelist[i] = list(union(unlist(NCG_genelist[i]), common))
}
'''
NCG_genes = melt(NCG_genelist)
NCG_genes_CODEsum = as.data.frame(table(NCG_genes$L1))
p<-ggplot(data=NCG_genes_CODEsum, aes(x=Var1, y=Freq)) +
geom_bar(stat="identity") +
theme(axis.text.x=element_text(angle=30,hjust=1,vjust=1, size = 12))
p + geom_text(aes(label = Freq), size = 4, hjust = 0.5, vjust = -1)
##############################################################
#### Overlaps between TCGA and NCG
##############################################################
trainsetNCG = data.frame(matrix(ncol=115))
colnames(trainsetNCG) = colnames(MC3_bailey_filtered)
for (i in 1:length(NCG_genelist)){
trainsetNCG = rbind(trainsetNCG,
MC3_bailey_filtered[intersect(which(MC3_bailey_filtered$CODE == names(NCG_genelist)[i]),
which(MC3_bailey_filtered$Hugo_Symbol %in% unlist(NCG_genelist[i]))),])
}
trainsetNCG = trainsetNCG[-1,]
df = trainsetNCG %>%
group_by(CODE) %>%
summarise(num_samples = n_distinct(Tumor_Sample_Barcode),
num_alterations = n())
"""k
alterations_all = as.data.frame(table(MC3_bailey_filtered$CODE))
alterations_train = as.data.frame(table(trainsetNCG$CODE))
alterations_all = merge(alterations_all,alterations_train, by = "Var1")
colnames(alterations_all) = c("CancerTypes","all_alterations","train_alteration")
alterations_all$test_alteration = alterations_all$all_alterations - alterations_all$train_alteration
alterations_all$train_percentage = alterations_all$train_alteration/alterations_all$all_alterations*100
df = melt(alterations_all)
"""
#df$variable = as.character(df$variable)
p = ggplot(df[which(!df$variable %in% c("all_alterations","train_percentage")),],
aes(x=CancerTypes, y = value, fill=variable))+
geom_bar(stat = "identity") +
ylab("Number of alterations") + xlab("Cancer types") +
theme(axis.text.x=element_text(angle=30,hjust=0.75,vjust=0.75, size = 12, face = "bold"))
p + geom_text(data=df[which(df$variable=="train_percentage"),],aes(y=df[which(df$variable=="all_alterations"),]$value,label = round(value)),
size = 4, hjust = 0.5, vjust = -1)
# Number of samples left after minus training set
for (i in 1:nrow(alterations_all)){
MC3_bailey_filtered$CODE ==
length(unique(MC3_bailey_filtered$Tumor_Sample_Barcode))
}
##############################################################
#### Overlaps between TCGA and Vogelstein
##############################################################
trainsetVogelstein = data.frame(matrix(ncol=115))
colnames(trainsetVogelstein) = colnames(MC3_bailey_filtered)
for (i in 1:nrow(Vogelstein)){
trainsetVogelstein = rbind(trainsetVogelstein,
MC3_bailey_filtered[which(MC3_bailey_filtered$Hugo_Symbol %in% unlist(Vogelstein$`Gene Symbol`[i])),])
}
trainsetVogelstein = trainsetVogelstein[-1,]
df = trainsetVogelstein %>%
group_by(CODE) %>%
summarise(num_samples = n_distinct(Tumor_Sample_Barcode),
num_alterations = n())
df = merge(df, summary_cohort, by="CODE")
colnames(df) = c("CancerTypes","n.sample.train","n.alterations.train","n.sample.all","n.alterations.all")
df$n.sample.test = df$n.sample.all - df$n.sample.train
df$percent.sample.train = df$n.sample.train/df$n.sample.all
df$n.alterations.test = df$n.alterations.all - df$n.alterations.train
df$percent.alterations.train = df$n.alterations.train/df$n.alterations.all
plotthis <- melt(df)
p = ggplot(plotthis[which(plotthis$variable %in% c("n.sample.train","n.sample.test")),],
aes(x=CancerTypes, y = value, fill=variable))+
geom_bar(stat = "identity") +
ylab("Number of samples") + xlab("Cancer types") +
theme(axis.text.x=element_text(angle=30,hjust=0.75,vjust=0.75, size = 12, face = "bold"))
p + geom_text(data=plotthis[which(plotthis$variable=="percent.sample.train"),],
aes(y=plotthis[which(plotthis$variable %in% c("n.sample.all")),]$value,label = round(value*100)),
size = 4, hjust = 0.5, vjust = -1)
###################################################################
#### Intersection of mc3_bailey with ncg6 genes
###################################################################
# Intersecting Bailey and NCG6 file
a = c()
for (i in 1:nrow(NCG6_systemslevelproperties)){
k = grep(NCG6_systemslevelproperties$symbol[i],MC3_bailey$Hugo_Symbol)
a = c(a,k)
# overlapNCG = rbind(overlapNCG, MC3_bailey[k,])
}
MC3_bailey_overlapNCG = MC3_bailey[unique(a),]
# Intersecting Bailey and NCG6 711 cancer genes
a = c()
for (i in 1:711){
k = grep(NCGgene[i],MC3_bailey$Hugo_Symbol)
a = c(a,k)
# overlapNCG = rbind(overlapNCG, MC3_bailey[k,])
}
MC3_bailey_overlap711NCG = MC3_bailey[unique(a),]
#################
a = data.frame(table(MC3_bailey[,c("Tumor_Sample_Barcode","CODE")])) #freq = number of mutated genes in the original driver discovery file
a[which(a$Freq)]
for (i in 1:3){
k = MC3_bailey$Gene[which(MC3_bailey$Tumor_Sample_Barcode == a[i,1])]
}
# counting number of discovered driver genes per sample
a = data.frame(table(MC3_bailey[,c("Tumor_Sample_Barcode","CODE")])) #freq = number of mutated genes in the original driver discovery file
a = a[which(a$Freq!=0)] #1 sample per tumor type
a$drivergene = 0
MC3_bailey_overlapNCG_damaged=muts1_exon_ncg_onco_cnv_damaging#muts1_exon #muts1_exon_ncg_onco_damaging #muts1_exon #
cancertype = unique(Bailey_finalgenelist$Cancer)
MC3_bailey_overlapNCG_damaged$Driver_status = 0
MC3_bailey_overlapNCG_damaged$Driver_status_Pancan = 0
cancertype=unique(MC3_bailey_overlapNCG_damaged$Cancer_type)
colnames(MC3_bailey_overlapNCG_damaged)[17]="CODE"
for (i in cancertype){
# For each cancer type in the consensus list, grab all the driver gene names
drivers = Bailey_finalgenelist$Gene[grep(i, Bailey_finalgenelist$Cancer)]
# Find in a specific cancer, which sample contain driver gene
# Accounting for special cases of COADREAD and PANCAN
if (i == "COADREAD"){
k = intersect(which(MC3_bailey_overlapNCG_damaged$CODE %in% c("COAD","READ")), which(MC3_bailey_overlapNCG_damaged$symbol_19549 %in% drivers))
# add driver status to the specific gene & tumor sample & cancer type combination
MC3_bailey_overlapNCG_damaged$Driver_status[k] = MC3_bailey_overlapNCG_damaged$Driver_status[k] + 1
} else if (i == "ESCA"){
k = intersect(which(MC3_bailey_overlapNCG_damaged$CODE %in% c("OAC","OSCC")), which(MC3_bailey_overlapNCG_damaged$symbol_19549 %in% drivers))
# add driver status to the specific gene & tumor sample & cancer type combination
MC3_bailey_overlapNCG_damaged$Driver_status[k] = MC3_bailey_overlapNCG_damaged$Driver_status[k] + 1
} else if (i == "PANCAN"){
k = which(MC3_bailey_overlapNCG_damaged$symbol_19549 %in% drivers)
MC3_bailey_overlapNCG_damaged$Driver_status_Pancan[k] = MC3_bailey_overlapNCG_damaged$Driver_status_Pancan[k] + 1
} else {
k = intersect(which(MC3_bailey_overlapNCG_damaged$CODE == i), which(MC3_bailey_overlapNCG_damaged$symbol_19549 %in% drivers))
# add driver status to the specific gene & tumor sample & cancer type combination
MC3_bailey_overlapNCG_damaged$Driver_status[k] = MC3_bailey_overlapNCG_damaged$Driver_status[k] + 1
}
}
table(MC3_bailey_overlapNCG_damaged$Driver_status)
length(unique(MC3_bailey_overlapNCG_damaged$Sample[which(MC3_bailey_overlapNCG_damaged$Driver_status==1)]))
length(intersect(substring(MC3_bailey$Tumor_Sample_Barcode,1,19), substring(CN_broad$Sample, 1, 19))) #8775 samples matched
length(intersect(substring(MC3_bailey$Tumor_Sample_Barcode,1,19),
substring(CN_broad$Sample, 1, 19))) #8775 samples matched
###################################################################
#### Filtering for damaging mutation
###################################################################
truncating_alt = which(MC3_bailey_overlapNCG$Consequence %in% c("frameshift_variant","stop_gained","stop_lost",
"incomplete_terminal_codon_variant","start_lost")) #different to stop lost?
nonframeshift = which(MC3_bailey_overlapNCG$Consequence %in% c("inframe_deletion","inframe_insertion"))
nonsynonymous = which(MC3_bailey_overlapNCG$Consequence %in% c("missense_variant"))
splicing = which(MC3_bailey_overlapNCG$Consequence %in% c("splice_acceptor_variant","splice_donor_variant","splice_region_variant"))
notsure = c("protein_altering_alteration","transcript_ablation")
SIFT_Polyphen2 = union(grep("deleterious", MC3_bailey_overlapNCG$SIFT),# this includes also deleterious_low_confidence
grep("damaging", MC3_bailey_overlapNCG$PolyPhen)) # includes also probably_damaging
VEP = which(MC3_bailey_overlapNCG$IMPACT %in% c("HIGH","MODERATE"))
dam2 = intersect(union(nonframeshift, nonsynonymous), SIFT_Polyphen2)
dam_splice = intersect(splicing, VEP)
dam_all = union(union(truncating_alt, dam2), dam_splice)
MC3_bailey_overlapNCG_damaged = MC3_bailey_overlapNCG[dam_all,]
'''
ascat_acf_ploidy$Sample<-gsub("[.]","-",ascat_acf_ploidy$Sample)
length(intersect(substring(ascat_acf_ploidy$Sample,1,19),
substring(NC_broad$Sample,1,19)))
'''
###################################################################
#### Copy Number data mapping to genes, Gain Loss Distribution
###################################################################
df = merge(Thanos[,c("Sample","Copy_number","Entrez")],
sum_seg,
by.x=c("Sample","Entrez"), by.y =c("Sample","entrez"))
colnames(df)[c(3,9)] = c("Copy_number_Thanos","Copy_number_Trang")
tmp = melt(table(df[,c(3,9)]))
ggplot(tmp, aes(x=Copy_number_Thanos, y =Copy_number_Trang, fill=value))+
geom_tile()+
scale_fill_continuous(high = "red", low = "white")
k=which(df$Copy_number_Thanos != df$Copy_number_Trang) #the difference between thanos CN and mine CN
# mapping done in HPC
path= "~/Rosalind/CNV/CN_intersectBed_filtered"
code = c("GBM","OV","LUAD","LUSC", "PRAD", "UCEC", "BLCA", "TGCT", "ESCA", "PAAD", "KIRP", "LIHC", "SARC", "BRCA", "THYM",
"MESO", "COAD", "STAD", "SKCM", "CHOL", "KIRC", "THCA", "CESC", "HNSC", "LAML", "READ", "LGG", "DLBC", "KICH", "UCS",
"ACC", "PCPG", "UVM")
GainLoss_summary <- function(CODE){
tmp1 = readRDS(sprintf("%s/%s_gainloss_2ploidy.rds",path, CODE))
tmp2 = readRDS(sprintf("%s/%s_gainloss_segmentmean.rds",path ,CODE))
df = base::merge(tmp1 %>% group_by(sampleID) %>% summarise(CNVGain_ploidy = sum(CNV_type=="Gain",na.rm = TRUE), CNVLoss_ploidy = sum(CNV_type=="Loss",na.rm = TRUE)),
tmp2 %>% group_by(sampleID) %>% summarise(CNVGain_seg = sum(CNV_type=="Gain"), CNVLoss_seg = sum(CNV_type=="Loss")),
all=TRUE)
df$CODE = CODE
df
}
df = data.frame()
for (i in unique(MC3_bailey$CODE)) {
if (i =="ESCA"){
tmp1 = readRDS(sprintf("%s/%s_gainloss_2ploidy.rds", path,i))
tmp2 = readRDS(sprintf("%/%s_gainloss_segmentmean.rds", i))
k=which(tmp1$sampleID%in% substring(oac,1,15))
saveRDS(tmp1[k,],sprintf("%s/OAC_gainloss_2ploidy.rds", path))
saveRDS(tmp1[-k,],sprintf("%s/OSCC_gainloss_2ploidy.rds", path))
k=which(tmp2$sampleID%in% substring(oac,1,15))
saveRDS(tmp2[k,],sprintf("%s/OAC_gainloss_OAC_gainloss_segmentmean.rds", path))
saveRDS(tmp2[-k,],sprintf("%s/OAC_gainloss_OSCC_gainloss_segmentmean.rds", path))
tmp = GainLoss_summary("OAC")
df = rbind(df,tmp)
tmp = GainLoss_summary("OSCC")
df = rbind(df,tmp)
} else {
tmp = GainLoss_summary(i)
df = rbind(df,tmp)
}
}
saveRDS(df, sprintf("%s/summary.rds", path))
for (i in code){
cnv_ann = read.table(sprintf('%s/%s.txt', path, i))
sprintf('%s has %s samples 15 char and %s samples 19 char', i, length(unique(cnv_ann$sampleID)), length(unique(cnv_ann$Sample)))
id = unique(cnv_ann$sampleID)
saveRDS(id, sprintf("%s/%s_sample.rds",path,i))
}
df <- readRDS("~/Rosalind/CNV/CN_intersectBed_filtered/summary.rds")
CN_mc3 = df[which(df$sampleID %in% substring(code$Sample,1,15)),]
plotthis = melt(CN_mc3)
library(ggplot2)
ggplot(plotthis, aes(CODE,value, color=variable))+
geom_boxplot()+
theme_boss()
ggplot(plotthis, aes(variable,value))+
geom_boxplot()+
# stat_summary(aes(label=round(..y..)), fun.y=mean, geom="text", size=4,position = position_nudge(y = 50)) +
stat_summary(aes(label=..y..), fun.y=min, geom="text", size=4,position = position_nudge(y = -100)) +
stat_summary(aes(label=..y..), fun.y=max, geom="text", size=4,position = position_nudge(y = 100)) +
theme_boss()
tmp = plotthis %>% group_by(variable) %>% summarise(n_sample = n_distinct(sampleID),
CNV = sum(value, na.rm = T))
theme_boss <- function(base_size = 12, base_family = "sans"){
theme_bw(base_size = base_size, base_family = base_family) %+replace%
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
panel.border=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=16),
axis.title=element_text(size=14),
axis.text.x=element_text(angle=30,hjust=0.75,vjust=0.75, size = 16, face = "bold")
)
}
###################################################################
#### Distribution of cancer genes per sample
###################################################################
# this status only flag all driver genes in the samples. This means that it can't differentiate which mutation is the driver in that gene
# MC3_bailey$Driver_status
# MC3_bailey$Driver_status_Pancan
#All exonic mutations
muts1=MC3_bailey
MC3_bailey_exonic = muts1 %>% subset(!grepl("downstream_gene_variant", muts1$Consequence) &
!grepl("upstream_gene_variant", muts1$Consequence) &
# !grepl("intergenic", muts1$Func.refGene) &
!grepl("non_coding_transcript_variant",muts1$Consequence) &
# !grepl("non_coding_transcript_exon_variant", muts1$Consequence) &
!grepl("intron_variant", muts1$Consequence) &
!grepl("5_prime_UTR_variant", muts1$Consequence) &
!grepl("3_prime_UTR_variant", muts1$Consequence))
library(dplyr)
MC3_bailey_overlapNCG_damaged$Sample = substring(MC3_bailey_overlapNCG_damaged$sample,1,12)
df = MC3_bailey_overlapNCG_damaged[which(MC3_bailey_overlapNCG_damaged$Driver_status_Pancan==1),] %>%
group_by(Sample) %>%
summarise(num_driver = n_distinct(symbol_19549))
nodriver = setdiff(unique(CODE$Sample), df$Sample)
df[(nrow(df)+1):(nrow(df)+length(nodriver)),1] = nodriver
df[(9079-length(nodriver)+1):9079,2] = 0
#code = unique(MC3_bailey_overlapNCG_damaged[,c("Sample","CODE")])
df = merge(df, CODE, by='Sample')
#driver_per_type = df
#driver_per_type$Analysis_Type = "individual cancer"
df$Analysis_Type = 'PANCAN'
df2 = rbind(df, driver_per_type)
#Driver_exon2= df2
Driver_damaging2=df2
library(ggplot2)
library(reshape2)
plotthis = df2 #data.frame(table(df$CODE,df$num_driver))
plotthis %>% mutate(label=replace(label, "PANCAN (9072)")) %>%
+ as.data.frame()
### Driver distribution (bailey mutation VEP)
tmp_sum = driver_per_type %>% group_by(CODE) %>% summarise(n_all = length(unique(Sample)))
tmp_sum$label = paste0(tmp_sum$CODE, " (",tmp_sum$n_all,")")
#tmp_sum[35,] = c("PANCAN",9072,"PANCAN (9072)")
plotthis = merge(plotthis,tmp_sum)
plotthis$category = "individual"
plotthis = rbind(plotthis, plotthis %>% mutate(label=replace(label, TRUE,"PANCAN (9072)"), category="pancan") %>% as.data.frame())
order =
p <- ggplot(plotthis, aes(label, num_driver),dodge=Type) +
geom_boxplot(aes(fill = Analysis_Type), alpha=0.2) +
geom_hline(yintercept=3, linetype="dashed", color = "red")+
#stat_summary(aes(label=..y..), fun.y=median, geom="label", size=4) +
#stat_summary(aes(label=..y..), fun.y=min, geom="label", size=4) +
#stat_summary(aes(label=..y..), fun.y=max, geom="label", size=4) +
xlab('Cancer types') + ylab('number of driver genes per sample')+
facet_grid(.~category,space = "free_x", scales = "free_x")+
theme_boss_xtilted()
p
ggsave(filename=paste0("~/Rosalind/Plots/Bailey_Driver_per_sample_damaging.png"),
plot=p,width = 25, height = 15, dpi = 300)
### Plotthing the number of samples with 1,2,3 drivers etc
df = rbind(Driver_exon2%>% mutate(Type="exonic"),
Driver_damaging2 %>% mutate(Type="damaging"))
df$Type = factor(df$Type,levels = c("exonic", "damaging"))
df = data.frame(table(df[,c(2,5,6)]))
df = df %>% group_by(Analysis_Type, Type) %>% mutate(percent = Freq/sum(Freq),
label = ifelse(as.numeric(as.character(num_driver))>10,">10", as.character(num_driver)))
df$label=factor(df$label,levels=c(0:10,">10"))
df = df %>% group_by(Analysis_Type, Type,label) %>% summarise(percent_corrected = sum(percent),
Freq_corrected = sum(Freq))
df$percent_corrected_char = paste0(as.character(round(df$percent_corrected*100)),"%")
## Bar plot
p <- ggplot(df, aes(label, Freq_corrected,fill=Analysis_Type)) +
geom_bar(stat='identity',position=position_dodge(),alpha=0.8) +
ylab('Number of samples') + xlab('Number of cancer genes per sample')+
facet_wrap(.~Type,strip.position ="top")+
geom_text(aes(y=Freq_corrected, label=percent_corrected_char),
vjust=1.5, color="black", position = position_dodge(0.9), size=7)+
# theme(axis.text.x=element_text(angle=30,hjust=0.75,vjust=0.75, size = 12, face = "bold"))
theme_boss(base_size = 40)
p
pdf(file = "~/Trang/Plots/Bailey_NumberDriver_per_sample_exonic_damaging_19022019.pdf", width = 25, height = 10)
p
dev.off()
ggsave(filename=paste0("~/Trang/Plots/Bailey_NumberDriver_per_sample_exonic_damaging.pdf"),
plot=p,width = 25, height = 10, dpi = 300)
## Piechart
p <- ggplot(df[which(df$Type="exonic"),]) +
geom_bar(aes(x="", percent_corrected,fill=label), stat='identity',width = 1,alpha=0.8) +
coord_polar("y", start=0)+
theme_void()+
geom_text(aes(x=1, y = cumsum(percent_corrected) - percent_corrected/2, label=percent_corrected))+
ylab('Number of samples') + xlab('Number of driver genes per sample')+
facet_wrap(.~Analysis_Type)+
theme_boss(base_size = 40)
p
ggsave(filename=paste0("~/Trang/Plots/Bailey_NumberDriver_per_sample_exonic_damaging.png"),
plot=p,width = 25, height = 10, dpi = 300)
#### sample ID: [1:19] characters are portion for TCGA
k=intersect(unique(substring(CN_broad$Sample,1,19)), unique(substring(MC3_bailey$Tumor_Sample_Barcode,1,19)))
CN_broad$SampleID = substring(CN_broad$Sample,1,19)
CN_9079 = CN_broad[which(CN_broad$SampleID %in% k),]
CN_9079 = merge(CN_9079, code, by='SampleID', all.x =TRUE)
#CN = CN[,c(2,3,4,5,6,1,8,10)]
for (i in unique(code$CODE)){
tmp = CN_9079[which(CN$CODE == i),]
write.table(tmp, file=paste0('/Users/let/Rosalind/CN_segmentmean/',i,".bed"),
row.names = F, col.names = F, sep = "\t", quote = F)
}
###################################################################
#### Distribution of damaging mutation per cohort
###################################################################
theme_boss <- function(base_size = 12, base_family = "sans"){
theme_bw(base_size = base_size, base_family = base_family) %+replace%
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
panel.border=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=base_size),
axis.title=element_text(size=base_size, face = "bold")
)
}
theme_boss_xtilted <- function(base_size = 12, base_family = "sans"){
theme_bw(base_size = base_size, base_family = base_family) %+replace%
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
panel.border=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=16),
axis.title=element_text(size=14),
axis.text.x=element_text(angle=30,hjust=0.75,vjust=0.75, size = 12, face = "bold")
)
}
library(dplyr)
df = muts1_exon_ncg %>%
group_by(Sample) %>%
summarise(num_alterations = n(),
num_gene = n_distinct(Gene.refGene))
dist_bailey = merge(df, code, by='Tumor_Sample_Barcode')
dist_bailey$Type = "all"
dist_overlappNCG = merge(df, code, by='Tumor_Sample_Barcode')
dist_overlappNCG$Type = "all_ncg6"
dist_damaging = merge(df, code, by.x = "Sample", by.y='Tumor_Sample_Barcode')
dist_damaging$Type = "damaging"
all_dist = rbind(dist_bailey[,-1],dist_overlappNCG[,-1],dist_damaging[,-1])
plotthis = all_dist[which(all_dist$CODE=="ESCA"),]
plotthis = plotthis[which(plotthis$SampleID %in% substring(oacs,1,19)),]
library(ggplot2)
total_table_CODE <- readRDS("~/Trang/tabl") #readRDS("~/Rosalind/table_muts_snvindelGOF_CODE.rds")
total_table_CODE$CODE[which(total_table_CODE$CODE=="ESCA")] = "OSCC"
code = unique(total_table_CODE[,c("CODE", "Sample")])
plotthis = melt(total_table_CODE)
for (i in unique(code$CODE)) {
tmp = plotthis[which(plotthis$CODE==i),]
tmp_sum = tmp %>% group_by(Type) %>% summarise(n_all = length(unique(Sample)))
stat = tmp %>% group_by(variable,Type) %>% summarise(med = median(value),maxim = max(value),minim = min(value))
p=ggplot(tmp %>% mutate(value = replace(value, value==0, 0.9999)), aes(Type, value)) +
geom_jitter(position=position_jitter(width=0.3, height=0.2), aes(colour=factor(Type)), alpha=0.1) +
scale_y_log10() +
geom_boxplot(aes(fill = Type), alpha=0.2) +
xlab('Cancer types') + ylab('number per sample')+
stat_summary(aes(label=..y..), fun.y=median, geom="label", size=4) +
#stat_summary(aes(label=..y..), fun.y=min, geom="label", size=4) +
#stat_summary(aes(label=..y..), fun.y=max, geom="label", size=4) +
facet_grid(.~variable)+
annotate("label", x=stat$Type, y=replace(stat$med, stat$med==0, 0.9999), label=stat$med) +
annotate("label", x=1:nrow(stat), y=replace(stat$maxim, stat$maxim==0, 0.9999), label=stat$maxim) +
annotate("label", x=1:nrow(stat), y=replace(stat$minim, stat$minim==0, 0.9999), label=stat$minim) +
xlab("")+
ggtitle(paste0(i, sprintf(" (n_all=%s,n_ncg6=%s,n_damaging=%s)", tmp_sum$n_all[1], tmp_sum$n_all[2], tmp_sum$n_all[3]))) +
theme(axis.text.x=element_text(angle=30,hjust=0.75,vjust=0.75, size = 12, face = "bold"))
ggsave(filename=paste0("~/Rosalind/Plots/damaging_snvindel_Onco/",i,"_withOutliers.png"),
plot=p,width = 16, height = 9, dpi = 100)
}
##########################################
###### CN & segment mean distribution
##########################################
plotthis=rbind(rbind(bailey_0,bailey_1),rbind(bailey_2,bailey_3))
plotthis = merge(plotthis, CODE)
tmp=melt(plotthis)
tmp = tmp[which(tmp$variable=="mutated_genes"),]
#tmp_sum = tmp[!which(tmp$Type=="damaging"),] %>% group_by(CODE) %>% summarise(n_all = length(unique(Sample)))
#tmp_sum = tmp %>% group_by(Type) %>% summarise(n_all = length(unique(Sample)))
#tmp_sum$label = paste0("PANCAN", " (",tmp_sum$n_all,")")
tmp$label = "PANCAN (9079)"
stat = tmp %>% group_by(label,Type) %>% summarise(med = median(value),maxim = max(value),minim = min(value))# %>% arrange(med) #arrange(desc(med))
p=ggplot(tmp %>% mutate(value = replace(value, value==0, 0.9999)), aes(x=Type, y=value)) +
geom_jitter(position=position_jitter(width=0.3, height=0.2), aes(colour=factor(Type)), alpha=0.1) +
scale_color_manual(values = c("dodgerblue1","deepskyblue2","blue3")) +
geom_boxplot(alpha=0.2) + #aes(fill=factor(category))
scale_y_log10() +
theme_boss(base_size = 40)+
#facet_wrap(~category, scales = 'free')+
annotate("label", x=1:nrow(stat), y=replace(stat$med, stat$med==0, 0.9999), label=stat$med, size = 13) +
annotate("label", x=1:nrow(stat), y=replace(stat$maxim, stat$maxim==0, 0.9999), label=stat$maxim, size = 13) +
annotate("label", x=1:nrow(stat), y=replace(stat$minim, stat$minim==0, 0.9999), label=stat$minim, size = 13) +
ylab("Number of mutated genes") + xlab("Category")
p
ggsave(filename=paste0("~/Trang//Plots/damaging_snvindel_Onco/MutatedGenes_all_distribution.png"),
plot=p,width = 20, height = 10, dpi = 300)
### plot the mutations and mutated genes distribution across cancers
total_table_CODE <- readRDS("~/Trang/table_muts_snvindelGOF_CODE.rds")
total_table_CODE$CODE[which(total_table_CODE$CODE=="ESCA")] = "OSCC"
code = unique(total_table_CODE[,c("CODE", "Sample")])
plotthis = melt(total_table_CODE)
tmp=melt(plotthis)
tmp_sum = tmp[which(tmp$Type=="exonic_ncg6"),] %>% group_by(CODE) %>% summarise(n_all = length(unique(Sample)))
tmp_sum$label = paste0(tmp_sum$CODE, " (",tmp_sum$n_all,")")
plotthis2 = merge(tmp[intersect(which(tmp$variable=="mutations"), which(tmp$Type == "exonic_ncg6")),], tmp_sum) #merge(tmp,tmp_sum)
plotthis2 = plotthis2 %>% group_by(CODE) %>% mutate(median = median(value))
plotthis2$category = "cancertype"
plotthis_pancan = plotthis2
plotthis_pancan$label="PANCAN (9072)"
plotthis_pancan$category = "PANCAN"
plotthis_pancan$median = median(plotthis_pancan$value)
stat = plotthis2 %>% group_by(label,category) %>% summarise(med = median(value),maxim = max(value),minim = min(value)) %>% arrange(med) #arrange(desc(med))
stat = rbind(stat, plotthis_pancan %>% group_by(label,category) %>% summarise(med = median(value),maxim = max(value),minim = min(value)))
plotthis2 = rbind(plotthis2, plotthis_pancan)
order = c(levels(reorder(plotthis2$label, plotthis2$median))[-19],"PANCAN (9072)")
p=ggplot(plotthis2 %>% mutate(value = replace(value, value==0, 0.9999)), aes(x=factor(label, order), y=value)) +
geom_jitter(position=position_jitter(width=0.3, height=0.2), aes(colour=factor(category)), alpha=0.1) +
geom_boxplot(alpha=0.2) + #aes(fill=factor(category))
scale_y_log10() +
theme_boss_xtilted()+
#facet_wrap(~category, scales = 'free') +#, space = "free_x", scales = "free_x")+
annotate("label", x=1:nrow(stat), y=replace(stat$med, stat$med==0, 0.9999), label=stat$med, na.rm = TRUE) +
annotate("label", x=1:nrow(stat), y=replace(stat$maxim, stat$maxim==0, 0.9999), label=stat$maxim) +
annotate("label", x=1:nrow(stat), y=replace(stat$minim, stat$minim==0, 0.9999), label=stat$minim) +
ylab("Number of exonic mutations") + xlab("Cohort(#samples)")
p
ggsave(filename=paste0("~/Rosalind/Plots/damaging_snvindel_Onco/ExonicMutations_ncg6_distribution_withOutliers.png"),
plot=p,width = 25, height = 15, dpi = 300)
dev.off()
ggsave(filename=paste0("~/Rosalind/Plots/damaging_snvindel_Onco/Mutation_damaging_PANCAN_distribution_withOutliers.png"),
plot=p,width = 4, height = 15, dpi = 300)
###### CN & segment mean distribution
code = unique(mc3.v0.2.8.PUBLIC.code.filtered[,c("CODE","Tumor_Sample_Barcode")])
code$sampleID=substring(code$Tumor_Sample_Barcode,1,15)
code$CODE=as.character(code$CODE)
code[which(code$sampleID %in% oac),]$CODE ="OAC"
code[which(code$CODE =="ESCA"),]$CODE ="OSCC"
broad.mit.edu_PANCAN_Genome_Wide_SNP_6_whitelisted$sampleID=substring(broad.mit.edu_PANCAN_Genome_Wide_SNP_6_whitelisted$Sample,1,15)
CN = merge(broad.mit.edu_PANCAN_Genome_Wide_SNP_6_whitelisted,code, by="sampleID")
summarySample = cbind(table(code$CODE),
CN %>% group_by(CODE) %>% summarise(count=n_distinct(sampleID)))
summarySample = summarySample[,c(3,2,4)]
colnames(summarySample)[2:3] = c("n_muts","n_cnv")
#Density plots of segment means in 34 cancer types
p <- ggplot(CN, aes(Segment_Mean, colour=CODE, fill=CODE))+
geom_density(alpha=0.55)
ggsave(filename=paste0("~/Rosalind/Plots/CN_segmentmean/CNsegmentmean_distribution.png"),
plot=p,width = 25, height = 15, dpi = 300)
df = CN %>% group_by(sampleID) %>% summarise(CN_mean = mean(Segment_Mean))
df = merge(df,code, by="sampleID")
df_pancan = df
df_pancan$CODE ="PANCAN"
df = rbind(df,df_pancan)
df = merge(df,
df %>% group_by(CODE) %>% summarise(n_sample = n_distinct(sampleID)),
by="CODE")
df$label = paste0(df$CODE," (",df$n_sample,")")
ggplot(df , aes(reorder(label,CN_mean),CN_mean))+geom_boxplot()+
stat_summary(aes(label=round(..y..,2)), fun.y=median, geom="text", size=4) +
stat_summary(aes(label=round(..y..,2)), fun.y=min, geom="text", size=4) +
stat_summary(aes(label=round(..y..,2)), fun.y=max, geom="text", size=4) +
ylab('Mean of CN Segment_Mean per sample')+
xlab('Cancer type')+
theme(axis.text.x=element_text(angle=30,hjust=0.75,vjust=0.75, size = 15, face = "bold"))
ggsave(filename=paste0("~/Rosalind/Plots/CN_segmentmean/CNsegmentmean_meanperSample_distribution.png"), width = 25, height = 15, dpi = 300)
TCGA_mastercalls.abs_tables_JSedit.fixed <- read.delim("~/Downloads/TCGA_mastercalls.abs_tables_JSedit.fixed.txt")
ploidy = TCGA_mastercalls.abs_tables_JSedit.fixed[,c(1,2,4,5)]
ploidy$sampleID = substring(ploidy$sample,1,15)
ploidy2 = merge(ploidy,code,by.x = "array", by.y = "sampleID")
tmp=ploidy2 %>% group_by(CODE) %>% summarise(n_ploidy = n_distinct(array))
summarySample = merge(summarySample,tmp)
summarySample$label = paste0(summarySample$CODE," (",summarySample$n_ploidy,")")
ploidy2 = merge(ploidy2, summarySample[,c("CODE","label")], all = F)
ploidy2 %>% group_by(CODE) %>% summarise(Mean = mean(ploidy))
geom_boxplot()+
theme(axis.text.x=element_text(angle=30,hjust=0.75,vjust=0.75, size = 15, face = "bold"))
###################################################################
#### intersection of snv cnv and indels
###################################################################
library(VennDiagram)
draw.triple.venn(area1 = 9079, area2 = 10965, area3 = 10786, n12 = 8774, n23 = 8025, n13 = 6349, n123 = 6184,
category = c("snv_indels (9079)", "cnv (10965)", "ploidy (8524)"),
lty = "blank",
fill = c("skyblue", "pink1", "mediumorchid") ,
cex=2, cat.cex=2,
cat.fontfamily = rep("serif", 3))
dev.off()
length(unique(substring(CN_broad$Sample,1,16)))
draw.pairwise.venn(area1 = 9079, area2 = 10965, cross.area = 8774,
category = c("snv_indels", "cnv"),
lty = "blank",
fill = c("skyblue", "pink1") ,
cex=2, cat.cex=2)
###########################################################
## This function combines all types of data to single table
## and prepares them for the extraction of drivers and prediction
createTotalTable = function(muts=NULL, cnvs=NULL, svs=NULL, exclude_samples=NULL){
ns = c("nonsynonymous","stopgain","frameshift deletion","splicing","frameshift insertion","nonframeshift deletion","nonframeshift insertion","nonframeshift substitution","stoploss","frameshift substitution")
dam = c("nonsynonymous","frameshift deletion","frameshift insertion","frameshift substitution","splicing","stopgain","stoploss")
trunc = c("frameshift deletion","frameshift insertion","frameshift substitution","stopgain","stoploss") ## Always damaging==TRUE
non_trunc = c("nonsynonymous","splicing")
## Make the lists
message("Integrating SNVs...")
df_mut = muts
if(!is.null(exclude_samples)){
df_mut = df_mut %>% subset(!sample%in%exclude_samples)
message(paste0("Samples excluded in mutation data: ", paste0(exclude_samples, collapse=",")))
}
## Fix nonsilent here
df_mut = df_mut %>% select(-nonsilent)
df_mut=is_nonsilent(df_mut)
## In order to get the number of all mutations per gene and because
## I have WGS data, I exclude mutations that fall in the following categories
## Exclude genes that are not in 19014
df_mut = df_mut %>% subset(!is.na(entrez_19549))
## Add oncodriveClust
df_mut = df_mut %>% left_join(onco_out %>% select(IGV, oncodriveClust), by = 'IGV')
## Create the total table
total_muts = ddply(df_mut, .(sample, symbol_19549, entrez_19549), dplyr::summarise,
no_ALL_muts=n(),
no_NSI_muts=sum(nonsilent),
no_TRUNC_muts = sum(ExonicFunc.refGene %in% trunc),
no_NTDam_muts = sum(ExonicFunc.refGene %in% non_trunc & damaging),
no_GOF_muts = sum(oncodriveClust), .progress = 'text'
)
## Add protein position if needed
#aa = df_mut %>% select(sample, entrez_19549, symbol_19014, AAChange.refGene) %>% group_by(sample, entrez_19549, symbol_19014) %>% summarise(AAChange=paste(unique(AAChange.refGene), collapse=","))
#total_muts = total_muts %>% left_join(aa)
# ## Check that you see a difference in the number of total mutations
# geneInfo_fn="/Volumes/mourikisa/data/geneInfoNCG5.Rdata"
# cancerGenes_fn="/Volumes/mourikisa/data/cancerGenesNCG5.Rdata"
# load(geneInfo_fn)
# load(cancerGenes_fn)
# ## Fix gene info table from NCG
# geneInfo = geneInfo %>% select(entrez, cancer_type) %>% unique
# ## Get a cancer gene with all the associated primary sites and cancer sites
# cancerGenes = cancerGenes %>% select(entrez, primary_site, cancer_site) %>%
# group_by(entrez) %>% summarise(primary_site=paste(unique(primary_site), collapse=","),
# cancer_site=paste(unique(cancer_site), collapse=",")) %>%
# ungroup
# geneInfo = geneInfo %>% left_join(cancerGenes, by=c("entrez"))
# test = total_muts %>% left_join(geneInfo, by=c("entrez_19549"="entrez"))
#
# test = test %>% mutate(sumDrivers = rowSums(.[6:8]))
# test = test %>% mutate(dVa=sumDrivers/no_ALL_muts)
# test %>% subset(dVa==1) %>% head
# wilcox.test(test%>%subset(cancer_type=="cgc")%>%.$dVa, test%>%subset(cancer_type=="can")%>%.$dVa)
# summary(test%>%subset(cancer_type=="cgc")%>%.$dVa)
# summary(test%>%subset(cancer_type=="can")%>%.$dVa)
## Bring in the total_table the SVs
message("Integrating SVs...")
if(!is.null(exclude_samples)){
svs = svs %>% subset(!sample%in%exclude_samples)
message(paste0("Samples excluded in SV data: ", paste0(exclude_samples, collapse=",")))
}
if(!is.null(svs)){
## There are 2 genes duplicated in 4 samples due to aliases
svs = svs %>% subset(!is.na(entrez_19549)) %>% mutate(key=paste(sample, entrez_19549, sep=".")) %>% subset(!duplicated(key)) %>% select(-key)
svs = svs %>% subset(BND>0 | INS>0 | INV>0) %>% select(-symbol, -cancer_type, -primary_site, -cancer_site)
## And put them in the total table as well
total_table = total_muts %>% full_join(svs%>%select(sample, BND, INS, INV, entrez_19549)%>%subset(!is.na(entrez_19549)))
total_table = total_table %>% mutate(key=paste(sample, entrez_19549, sep="."))
}else{
total_table = total_muts %>% mutate(BND=0, INS=0, INV=0)
total_table = total_table %>% mutate(key=paste(sample, entrez_19549, sep="."))
}
message("Integrating CNVs...")
## Add also the genes that are in muts and SVs to get their ploidy and Copy number
cnvs = cnvs %>% mutate(key=paste(sample, entrez_19549, sep="."))
df_cnv = cnvs %>% subset(key%in%total_table$key | !is.na(CNV_type_corrected)) ## Also get the real CNVs
if(!is.null(exclude_samples)){
df_cnv = df_cnv %>% subset(!sample%in%exclude_samples)
message(paste0("Samples excluded in CNV data: ", paste0(exclude_samples, collapse=",")))
}
## define Gains and Losses - this was done in previous step
## Deduplicate the CNV data, because some genes may fall into two regions (sometimes it can be gain and loss)
message("Resolving duplicated entries in CNVs...")
dups = df_cnv %>% group_by(key) %>% mutate(n=n(), types=paste(unique(CNV_type_corrected), collapse=","), ntypes=length(unique(CNV_type_corrected))) %>% subset(n>1)
dups = dups %>% ungroup()
## In here you will find two kinds of duplications those that are duplicates but associated with one type of CNV (i.e Gain/Loss)
## And those that are associated with two types of CNVs
## I didn't use overlap function in the end
overlap <- function(start1, end1, start2, end2){
res = pmin(end1, end2) - pmax(start2, start1)
if(res>=0){
return(res)
}else if(res<0){
res=0
return(res)
}
}
dups_refined = NULL
for (t in unique(dups$types)){
if (grepl(",NA|NA,", t)){ ## When arrange always on top will be Gain/Loss and those will be selected when deduplicate
d = dups %>% subset(types==t) %>% arrange(key, desc(CNV_type_corrected)) %>% subset(!duplicated(key))
dups_refined = rbind(dups_refined, d)
}else if (t=="Gain" | t=="NA" | t=="Loss"){ ## Choose the one with the highest overlap
d = dups %>% subset(types==t) %>% mutate(overlap=(overlap(start, end, Start, End)/(end-start))*100) %>% arrange(key, desc(overlap)) %>% subset(!duplicated(key)) %>% select(-overlap)
dups_refined = rbind(dups_refined, d)
}else if (grepl("Gain", t) & grepl("Loss", t)){ ## For those genes we have both gain and loss, I set CNV_type to NA because we cannot distinguish between the two
d = dups %>% subset(types==t) %>% mutate(CNV_type_corrected=NA) %>% arrange(key) %>% subset(!duplicated(key))
dups_refined = rbind(dups_refined, d)
}
}
## For now deduplicte them and keep as CNV_type_corrected the concatenation of both types to see how many they are in the drivers
## Take them out first from the df_cnv
df_cnv = df_cnv %>% subset(!key%in%dups$key)
df_cnv$n = 1
## Fix dups
dups_refined = dups_refined %>% select(-types, -ntypes)
## Put the back in the df_cnv
df_cnv = rbind(df_cnv, dups_refined)
## Create total table from mutations and CNVs
total_table = total_table %>% subset(!is.na(entrez_19549)) %>%
full_join(df_cnv%>%select(sample, entrez_19549, Total_CN, CNV_type_corrected, ploidy, n)%>%rename(CNV_entries=n)%>%subset(!is.na(entrez_19549)))
total_table$na_19549 = apply(total_table[,c("symbol_19549", "entrez_19549")], 1, function(x) length(x[is.na(x)]))
total_table = total_table %>% mutate(in_19549=ifelse(na_19549<2, TRUE, FALSE)) %>% select(-na_19549) %>% subset(in_19549==TRUE)
return(total_table)
}
for (i in 1:nrow(CN_9079)){
CN_9079[i,"gain_loss"] = 1
}
dist_damaging %>%
group_by(CODE) %>%
summarise(n_sample = n_distinct(Sample),
n_mutation = sum(num_alterations)) -> df
snvindel[which(snvindel$damaging==TRUE),] %>%
group_by(CODE) %>%
summarise(n_mutation = n(),
n_gene = n_distinct(symbol_19549)) ->df2
######################################################################################
### separate snvindels to 34 files for each cancer (easier processed to total table)
######################################################################################
snvindel = set_IGV_code(mc3_bailey_ann_damaging_oncodriveclust)
code = unique(snvindel$CODE)
for (i in code){
tmp = snvindel[which(snvindel$CODE==i),]
saveRDS(tmp, sprintf("/Users/let/Trang/OncodriveClust/result_12022019/34cancer_types/%s.rds", i))
}
######################################################################################
### create total table
######################################################################################
library(plyr)
library(dplyr)
library(tidyr)
for (i in code){
df_mut = readRDS(sprintf("/Users/let/Rosalind/OncodriveClust/result_30112018/34cancer_types/%s.rds", i))
df_mut$sample = substring(df_mut$Sample,1,15)
## Fix nonsilent here
df_mut = df_mut %>% select(-nonsilent)
df_mut=is_nonsilent(df_mut)
# Exclude all non-exonic mutations
df_mut = df_mut %>% subset(Func.refGene!="" &
!grepl("downstream", df_mut$Func.refGene) &
!grepl("upstream", df_mut$Func.refGene) &
!grepl("intergenic", df_mut$Func.refGene) &
!grepl("ncRNA", df_mut$Func.refGene) &