-
Notifications
You must be signed in to change notification settings - Fork 0
/
InCRIMP Script.R
12774 lines (9538 loc) · 543 KB
/
InCRIMP Script.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#=============================================================================
#
# Code chunk 0: Pre-requisites
#
#=============================================================================
# devtools::install_github("r-dbi/DBI")
# devtools::install_github("r-dbi/RMariaDB")
# devtools::install_github("truecluster/bit64")
# devtools::install_github("tidyverse/blob")
# devtools::install_github("tidyverse/lubridate")
# devtools::install_github("tidyverse/hms")
# devtools::install_github("RcppCore/Rcpp")
library(DBI)
library(RMariaDB)
library(bigrquery)
library(dplyr)
library(tidyverse)
library(influential)
library(httr)
library(jsonlite)
library(VariantAnnotation) ## A very good package for preprocessing and preparing the VCF files for downstream analyses
library(parallel)
#=============================================================================
#
# Code chunk 1: Prepare the settings fro retrieving data from Database
#
#=============================================================================
# Connecting to the database
## Connect to the database
db <- dbConnect(
drv = RMariaDB::MariaDB(),
default.file=".my.cnf",
groups="azure_lkcgp_curated" # must be the same as the name between [] in .my.cnf file
)
#=============================================================================
#
# Code chunk 2: Get the sample data from Database
#
#=============================================================================
## Get Patient and Sample data
lkcgp_sample <- tbl(db, "lkcgp_sample") %>% as.data.frame()
### Add diagnosis instead of those cancer_types that are NA
lkcgp_sample$cancer_type[which(is.na(lkcgp_sample$cancer_type))] <- lkcgp_sample$diagnosis[which(is.na(lkcgp_sample$cancer_type))]
## Retain only PRISM study data
lkcgp_sample <- subset(lkcgp_sample, study == "PRISM")
###########################
## Prepare the sample tables for publication
somatic_samples_tbl <- somatic_snv %>% dplyr::select(sample_id, cancer_type) %>% dplyr::distinct(sample_id, .keep_all = T)
germline_samples_tbl <- germline_snv %>% dplyr::select(sample_id, cancer_type) %>% dplyr::distinct(sample_id, .keep_all = T)
somatic_samples_tbl <- table(somatic_samples_tbl$cancer_type) %>% data.frame()
colnames(somatic_samples_tbl) <- c("Cancer_type", "Number_of_samples")
somatic_samples_tbl$Context <- 'Somatic'
germline_samples_tbl <- table(germline_samples_tbl$cancer_type) %>% data.frame()
colnames(germline_samples_tbl) <- c("Cancer_type", "Number_of_samples")
germline_samples_tbl$Context <- 'Germline'
combined_samples_tbl <- rbind(somatic_samples_tbl, germline_samples_tbl)
## Unify names
combined_samples_tbl <- combined_samples_tbl[-which(combined_samples_tbl$Cancer_type == "Glioma Other"),]
combined_samples_tbl[which(combined_samples_tbl$Cancer_type == "Glioma other" & combined_samples_tbl$Context == 'Somatic'),2] <- 15
write_csv(x = combined_samples_tbl, file = "Results/combined_samples_tbl.csv")
#=============================================================================
#
# Code chunk 3: Get and prepare the germline SNV data
#
#=============================================================================
## Get the SNV data
### Germline variants
germline_snv <- tbl(db, "lkcgp_curated_germline_snv") %>% as.data.frame()
sample_germline_snv <- tbl(db, "lkcgp_curated_sample_germline_snv") %>% as.data.frame()
### Complement the dataset
germline_snv <- germline_snv[c(germline_snv$variant_id %in% sample_germline_snv$variant_id),]
germline_snv$exon <- NULL
sample_germline_snv <- sample_germline_snv[,c(1:12)]
sample_germline_snv <- cbind(germline_snv[match(sample_germline_snv$variant_id, germline_snv$variant_id),],
sample_germline_snv[,-3])
germline_snv <- sample_germline_snv
rm(sample_germline_snv)
germline_snv <- germline_snv[c(germline_snv$sample_id %in% lkcgp_sample$matched_normal_id),]
germline_snv$study <- lkcgp_sample$study[match(germline_snv$sample_id, lkcgp_sample$matched_normal_id)]
## Retain only PRISM study data
germline_snv <- subset(germline_snv, study == "PRISM")
## Split the variants that have two alternative alterations (denoted by a comma) into two
germline_snv <- tidyr::separate_rows(germline_snv, alt)
## Calculate nalt for all variants
germline_snv_nalt <- lapply(unique(germline_snv$variant_id), function(i) {
tmp_data <- subset(germline_snv, variant_id == i)
ref <- tmp_data$ref[1]
genotypes <- tmp_data$genotype %>%
stringr::str_split(pattern = "/", n = 2) %>% unlist()
count <- length(genotypes) - grep(pattern = paste0("^", ref, "$"), x = genotypes) %>% length()
tmp_tbl <- data.frame(variant_id = i, nalt = count)
})
germline_snv_nalt <- do.call(rbind, germline_snv_nalt)
germline_snv$nalt <- germline_snv_nalt$nalt[match(germline_snv$variant_id, germline_snv_nalt$variant_id)]
#### Add patient ID, cancer type, Study, and lastUpdated date
germline_snv$patient_id <- lkcgp_sample$patient_id[match(germline_snv$sample_id, lkcgp_sample$matched_normal_id)]
germline_snv$cancer_type <- lkcgp_sample$cancer_type[match(germline_snv$sample_id, lkcgp_sample$matched_normal_id)]
germline_snv$lastUpdated <- lkcgp_sample$lastUpdated[match(germline_snv$sample_id, lkcgp_sample$matched_normal_id)]
## Remove variants with 0 or NA depth
germline_snv <- germline_snv[-c(which(germline_snv$depth == 0 | is.na(germline_snv$depth))),]
## Remove variants with <= 3 altAD or NA altAD
germline_snv <- germline_snv[-c(which(germline_snv$altad <= 3 | is.na(germline_snv$altad))),]
## Remove the stars (*) from alt column as these denote spanning deletions and the the effects of the their other corresponding variants will be captured by their own data record
germline_snv$alt <- gsub(pattern = ",[*]|[*],", replacement = "", x = germline_snv$alt)
# Process downloaded gnomAD pop freq. data
### First, get min and max genomic positions of all chromosomes and create batches of 100,000 bps (genomic positions) for each chromosome
germline_snv_chr <-
unique(germline_snv$chr)
germline_snv_chr_tbl <-
parallel::mclapply(1:length(germline_snv_chr), FUN = function(i) {
## Calculate the min and max of chromosome i
germline_snv_chr_min <- min(germline_snv$pos[which(germline_snv$chr %in% germline_snv_chr[i])]) - 10
germline_snv_chr_max <- max(germline_snv$pos[which(germline_snv$chr %in% germline_snv_chr[i])]) + 10
germline_snv_chr_tbl_tmp <- data.frame(chr = germline_snv_chr[i],
min = germline_snv_chr_min,
max = germline_snv_chr_max)
}, mc.cores = parallel::detectCores() - 3)
germline_snv_chr_tbl <- do.call(rbind, germline_snv_chr_tbl)
############################
## Get the header of VCF file
genomes.r2.1.1.exome_calling_header <- VariantAnnotation::scanVcfHeader(file = "Datasets/gnomAD/V2/gnomad.genomes.r2.1.1.exome_calling_intervals.sites.vcf.bgz")
## Filter out chromosomes of germline_snv_chr_tbl that are not available in the genomes.r2.1.1.exome_calling_header
genomes.r2.1.1.exome_calling_chrs <- GenomeInfoDb::seqlevels(genomes.r2.1.1.exome_calling_header)
germline_snv_chr_gnomAD_tbl <- germline_snv_chr_tbl[which(germline_snv_chr_tbl$chr %in% genomes.r2.1.1.exome_calling_chrs),]
## Remove Y chromosome as it is not present in the Tabix index file
germline_snv_chr_gnomAD_tbl <- germline_snv_chr_gnomAD_tbl[-which(germline_snv_chr_gnomAD_tbl$chr == "Y"),]
## Get the info column names
infoCols <- rownames(VariantAnnotation::info(genomes.r2.1.1.exome_calling_header))
## Separate the AF column names
AFcols <- infoCols[grep("^AF", infoCols)]
## Filter out the first and third column names (overall AF and AF_raw) and AF_popmax as well as male/female sub-populations as we are not looking for sex-specific variant
AFcols <- AFcols[-c(1, grep("male|raw|popmax", AFcols))]
germline_snv_popFreq_list <- parallel::mclapply(1:nrow(germline_snv_chr_gnomAD_tbl), function(i) {
## Define a genomic ranges
chr = germline_snv_chr_gnomAD_tbl[i,1]
start.loc <- germline_snv_chr_gnomAD_tbl[i,2]
end.loc <- germline_snv_chr_gnomAD_tbl[i,3]
gr <- GenomicRanges::GRanges(chr, IRanges::IRanges(start.loc, end.loc))
## restrict VCF INFO columns to AC and AN values
vcfPar <- VariantAnnotation::ScanVcfParam(geno = NA,
fixed = c("ALT", "FILTER"),
info = AFcols,
which = gr)
# Load the desired chunk of VCF file
vcf <- VariantAnnotation::readVcf(
Rsamtools::TabixFile("Datasets/gnomAD/V2/gnomad.genomes.r2.1.1.exome_calling_intervals.sites.vcf.bgz"),
param=vcfPar)
# Discard variants not passing all FILTERS
mask <- VariantAnnotation::filt(vcf) == "PASS"
vcf <- vcf[mask, ]
# prepare the variants freq data
ref <- VariantAnnotation::ref(vcf) %>% as.character()
alt <- VariantAnnotation::alt(vcf) %>% unlist() %>% as.character()
pos <- MatrixGenerics::rowRanges(vcf) %>% BiocGenerics::start()
af <- VariantAnnotation::info(vcf) %>% as.data.frame()
# Generate the gnomAD pop. freq. table
gnomAD_af_tbl <- cbind(data.frame(chr = chr, pos = pos, ref = ref, alt = alt), af)
gnomAD_af_tbl
}, mc.cores = parallel::detectCores() - 3)
germline_snv_popFreq_list <- do.call(rbind, germline_snv_popFreq_list)
############################3
## Filter out high gnomAD pop freq vars
### identify gnomAD vars that are present in germline_snv
germline_snv_gnomAD_pop_freq_index <- which(paste(germline_snv_popFreq_list$chr,
germline_snv_popFreq_list$pos,
germline_snv_popFreq_list$ref,
"_",
germline_snv_popFreq_list$alt, sep = "") %in%
paste(germline_snv$chr,
germline_snv$pos,
germline_snv$ref,
"_",
germline_snv$alt, sep = ""))
### identify germline_snv_gnomAD_pop_freq_index which have high frequency (FC > 0.01)
germline_snv_gnomAD_pop_freq_high_freq_index <- (((germline_snv_popFreq_list[germline_snv_gnomAD_pop_freq_index,c(5:ncol(germline_snv_popFreq_list))] > 0.01) %>%
rowSums(na.rm = TRUE)) > 0)
### Filter out rare vars of germline_snv_gnomAD_pop_freq_index
germline_snv_gnomAD_pop_freq_index <- germline_snv_gnomAD_pop_freq_index[germline_snv_gnomAD_pop_freq_high_freq_index]
### identify index of high freq vars in germline_snv
germline_snv_gnomAD_index <- match(paste(germline_snv_popFreq_list$chr,
germline_snv_popFreq_list$pos,
germline_snv_popFreq_list$ref,
germline_snv_popFreq_list$alt, sep = "_")[germline_snv_gnomAD_pop_freq_index],
paste(germline_snv$chr,
germline_snv$pos,
germline_snv$ref,
germline_snv$alt, sep = "_"))
# filter the germline_snv
germline_snv_flt <- germline_snv[-germline_snv_gnomAD_index,]
# remove the germline_snv_popFreq_list to free up space
rm(germline_snv_popFreq_list)
################################################
# Shell script for compressing the CADD data (adapted from https://gist.github.com/arq5x/9378020)
# We will perform the same pipeline on the InDel data as well to compresse it.
## 1. Download the raw CADD TSV and Tabix index (no annotations, just scores)
### https://krishna.gs.washington.edu/download/CADD/v1.6/GRCh37/whole_genome_SNVs.tsv.gz
### https://krishna.gs.washington.edu/download/CADD/v1.6/GRCh37/whole_genome_SNVs.tsv.gz.tbi
##########
## 2. Add the required tools to the path (downloaded from https://vcf.iobio.io/help.html; https://vcf.iobio.io/tabix/TabixBinary.zip)
### export PATH=$PATH:/Users/asalavaty/OneDrive\ -\ Childrens\ Cancer\ Institute\ Australia/Apps\ and\ Libraries/TabixBinary/
##########
## 3. Have a look at the data and its size (remove `<` from after zcat when working within linux)
### ls -ltrh whole_genome_SNVs.tsv.gz
### zcat < whole_genome_SNVs.tsv.gz | head
##########
## 4. Do the following for compressing the file:
### Remove the 5th column (raw CADD scores)
# zcat < whole_genome_SNVs.tsv.gz \
# | cut -f 1,2,3,4,6 \
# | bgzip \
# > whole_genome_SNVs.compressed.tsv.gz
##########
## 5. As the original file is changed, we need to re-index the file
# tabix -p vcf -f whole_genome_SNVs.compressed.tsv.gz
##########
## 6. Move the Compressed directory to your desired location (OneDrive)
##########
######################
# Define a function for retrieving the CADD scores and reformat them to a proper and readable style for downstream analyses
scanCADD2df <- function(variants_table, # Table of variants to check their CADD scores (Chromosome number/name on the first column, and POS, REFs and ALTs on the second third, and forth columns, respectively).
tabix_snv_file = NULL, # The tabix indexed file of SNVs (located in the same directory that .tbi file is located)
tabix_indel_file = NULL, # The tabix indexed file of InDels (located in the same directory that .tbi file is located)
gr_table, # A dataframe of genomic regions to scan; Chromosome number/name on the first column, and start and end positions on the second and third columns, respectively.
verbose = TRUE,
...){
# Check if a tabix file is provided
if(is.null(tabix_snv_file) & is.null(tabix_indel_file)) {
stop("Either of tabix_snv_file or tabix_indel_file, or both should be provided!")
}
library(magrittr)
library(dplyr)
if(verbose) {
print(paste("There are ", nrow(gr_table), " chunks to be processed!", sep = ""))
}
# Make sure variants_table and are of data.frame class
variants_table <- as.data.frame(variants_table)
gr_table <- as.data.frame(gr_table)
# Initialize a vector of variants
variants <- paste(variants_table[,1], as.integer(variants_table[,2]),
variants_table[,3], variants_table[,4], sep = "_")
# Define regions for the seqminer package
gr_table$region <- paste(gr_table[,1], ":", as.integer(gr_table[,2]), "-", as.integer(gr_table[,3]), sep = "")
# Retrieve the tabix data based on gr_table
cadd_df_list <-
lapply(1:nrow(gr_table), function(i) {
# Retrieve tabix SNV data
tabix_snv_data <- if(is.null(tabix_snv_file)) {
NULL
} else {
seqminer::tabix.read(tabixFile = tabix_snv_file,
tabixRange = gr_table$region[i])
}
# Retrieve tabix InDel data
tabix_indel_data <- if(is.null(tabix_indel_file)) {
NULL
} else {
seqminer::tabix.read(tabixFile = tabix_indel_file,
tabixRange = gr_table$region[i])
}
# Combine SNV and InDel results
tabix_data <- c(tabix_snv_data, tabix_indel_data)
# Prepare the tabix_data and re-format it
tabix_data <- tabix_data %>%
stringr::str_split_fixed(pattern = "\t", n = 5) %>%
as.data.frame()
# Set column names
colnames(tabix_data) <- c("CHROM", "POS", "REF", "ALT", "CADD_PHRED")
# Correct the class of POS and CADD_PHRED
tabix_data$POS <- as.integer(tabix_data$POS)
tabix_data$CADD_PHRED <- as.numeric(tabix_data$CADD_PHRED)
# Match the variants in the tabix_data with variants vector generated from the variants_table
tabix_data_variants <- paste(tabix_data[,1], as.integer(tabix_data[,2]),
tabix_data[,3], tabix_data[,4], sep = "_")
variants_index <- which(variants %in% tabix_data_variants)
cadd_phred_scores <- tabix_data$CADD_PHRED[match(variants[variants_index], tabix_data_variants)]
rm(tabix_data, tabix_data_variants)
if(verbose) {
print(paste("The chunk number ", i, " is done!", sep = ""))
}
return(data.frame(index = variants_index, score = cadd_phred_scores))
})
# Merge the lists of results
cadd_df_list <- base::do.call(rbind, cadd_df_list)
# Remove duplicates in case there are multiple duplicates of the same variant (e.g. corresponding to different tissues/cancers)
cadd_df_list <- cadd_df_list %>% dplyr::distinct(index, .keep_all = TRUE)
cadd_df_list
}
######################
# Define a function for creating intervals
interval_gen <- function(min, max, size) {
# Generate sequence of intervals
interval_seq <- seq(min, max, by = size)
# Add the last item if the modulus of min-max by size does not equal zero
if(!identical(max(interval_seq), max)) {
interval_seq <- c(interval_seq, max)
}
# Generate the intervals table
interval_tbl <- data.frame(min = vector(mode = "integer"), max = vector(mode = "integer"))
lapply(0:(length(interval_seq) - 2), FUN = function(i) {
if(i == 0) {
interval_tbl <<- rbind(interval_tbl, c(interval_seq[i + 1], interval_seq[i + 2]))
} else {
interval_tbl <<- rbind(interval_tbl, c((interval_seq[i + 1] + 1), interval_seq[i + 2]))
}
})
colnames(interval_tbl) <- c("min", "max")
return(interval_tbl)
}
######################
## Prepare germline_snv_chr_cadd_tbl table
genomic_intervals <- 50000
germline_snv_chr_cadd_tbl <-
lapply(1:length(germline_snv_chr), FUN = function(i) {
## Calculate the min and max of chromosome i
germline_snv_chr_min <- min(germline_snv_flt$pos[which(germline_snv_flt$chr %in% germline_snv_chr[i])])
germline_snv_chr_max <- max(germline_snv_flt$pos[which(germline_snv_flt$chr %in% germline_snv_chr[i])])
## Define the intervals for chromosome i
if((germline_snv_chr_max - germline_snv_chr_min) <= genomic_intervals) {
germline_snv_chr_cadd_tbl_tmp <- data.frame(min = germline_snv_chr_min, max = germline_snv_chr_max)
} else {
germline_snv_chr_cadd_tbl_tmp <-
interval_gen(min = germline_snv_chr_min,
max = germline_snv_chr_max,
size = genomic_intervals)
}
## Add chromosome and refs columns to the table
germline_snv_chr_cadd_tbl_tmp <- cbind(chr = germline_snv_chr[i],
germline_snv_chr_cadd_tbl_tmp,
refs = vector(mode = "logical", length = nrow(germline_snv_chr_cadd_tbl_tmp)))
## Define the refs for each interval
sapply(as.list(1:nrow(germline_snv_chr_cadd_tbl_tmp)), function(j) {
germline_snv_chr_cadd_tbl_tmp[j, 4] <<- ifelse(any(germline_snv_flt$chr %in% germline_snv_chr[i] &
germline_snv_flt$pos >= germline_snv_chr_cadd_tbl_tmp[j, 2] &
germline_snv_flt$pos < germline_snv_chr_cadd_tbl_tmp[j, 3]),
TRUE, FALSE)
})
germline_snv_chr_cadd_tbl_tmp$refs <- as.logical(germline_snv_chr_cadd_tbl_tmp$refs)
germline_snv_chr_cadd_tbl_tmp
})
## Merge the list of tables
germline_snv_chr_cadd_tbl <- do.call(rbind, germline_snv_chr_cadd_tbl)
## Filter out genomic regions that have no variants in them
germline_snv_chr_cadd_tbl <- germline_snv_chr_cadd_tbl[germline_snv_chr_cadd_tbl$refs,]
## Remove MT rows corresponding to mitochondrial chromosome
germline_snv_chr_cadd_tbl <- germline_snv_chr_cadd_tbl[-grep("MT", germline_snv_chr_cadd_tbl$chr),]
germline_snv_chr_cadd_tbl$refs <- NULL
## Retrieve CADD scores for all chromosomes of germline_snv (each interval of 50,000 last ~ 0.7-0.8 sec to be retrieved)
germline_snv_cadd_phred_scores <- scanCADD2df(variants_table = germline_snv_flt[,-1],
tabix_snv_file = "Datasets/CADD/v1.6-hg19 (compressed)/whole_genome_SNVs.compressed.tsv.gz",
tabix_indel_file = "Datasets/CADD/v1.6-hg19 (compressed)/InDels.compressed.tsv.gz",
gr_table = germline_snv_chr_cadd_tbl)
germline_snv_cadd_phred_scores <- do.call(rbind, germline_snv_cadd_phred_scores)
## Add CADD scores to the germline_snv_flt
germline_snv_flt$cadd_phred[germline_snv_cadd_phred_scores$index] <- germline_snv_cadd_phred_scores$score
## Remove variants with Ref == Alt (These are wrong)
germline_snv_flt <- germline_snv_flt[which(germline_snv_flt$ref != germline_snv_flt$alt), ]
### Filter out intergenic variants
germline_snv_flt <- germline_snv_flt[-which(germline_snv_flt$consequence == "intergenic_variant"),]
dim(germline_snv_flt)
length(unique(germline_snv_flt$variant_id))
germline_snv_flt$sample_id %>% unique() %>% length()
germline_snv_flt_withCADD <- germline_snv_flt
# Retrieve missing CADD scores
germline_snv_cadd_phred_scores_missing_indices <- which(is.na(germline_snv_flt_withCADD$cadd_phred))
germline_snv_flt_withCADD_missed <- germline_snv_flt_withCADD[germline_snv_cadd_phred_scores_missing_indices,]
germline_snv_chr_cadd_tbl_missed <- germline_snv_flt_withCADD_missed[,c(2,3)]
colnames(germline_snv_chr_cadd_tbl_missed) <- c("chr", "min")
germline_snv_chr_cadd_tbl_missed$max <- germline_snv_chr_cadd_tbl_missed$min
germline_snv_cadd_phred_scores_missed <- scanCADD2df(variants_table = germline_snv_flt_withCADD_missed[,-1],
tabix_snv_file = "Datasets/CADD/v1.6-hg19 (compressed)/whole_genome_SNVs.compressed.tsv.gz",
tabix_indel_file = "Datasets/CADD/v1.6-hg19 (compressed)/InDels.compressed.tsv.gz",
gr_table = germline_snv_chr_cadd_tbl_missed)
germline_snv_cadd_phred_scores_missed <- do.call(rbind, germline_snv_cadd_phred_scores_missed)
germline_snv_flt_withCADD$cadd_phred[germline_snv_cadd_phred_scores_missed$index] <- germline_snv_cadd_phred_scores_missed$score
### Filter out SNV variants (length of ref and alt == 1) with NA CADD scores (these SNVs have wrong Refs in our data)
germline_snv_flt_withCADD <- germline_snv_flt_withCADD[-which(is.na(germline_snv_flt_withCADD$cadd_phred) &
nchar(germline_snv_flt_withCADD$ref) == 1 &
nchar(germline_snv_flt_withCADD$alt) == 1),]
#################################################
### Visualize CADD score distribution for getting an idea for imputation of the remaining NA CADD scores
vep_impact_tbl <- read.delim("Datasets/Ensembl_VEP_IMPACT_tbl.txt", sep = "\t")
vep_impact_tbl$IMPACT_score <- 1
vep_impact_tbl$IMPACT_score[vep_impact_tbl$IMPACT == "LOW"] <- 2
vep_impact_tbl$IMPACT_score[vep_impact_tbl$IMPACT == "MODERATE"] <- 3
vep_impact_tbl$IMPACT_score[vep_impact_tbl$IMPACT == "HIGH"] <- 4
germline_snv_flt_withCADD_noNA <- germline_snv_flt_withCADD[-which(is.na(germline_snv_flt_withCADD$cadd_phred)),]
germline_snv_flt_withCADD_noNA$consequence <-
sapply(germline_snv_flt_withCADD_noNA$consequence, function(i) {
tmp_consequence <-
if(length(grep("&|,", i)) > 0) {
split_cons <- strsplit(x = i, split = "&|,") %>% unlist()
split_cons_impact <- vep_impact_tbl$IMPACT_score[match(split_cons, vep_impact_tbl$SO.term)]
split_cons_final <-
split_cons[which(split_cons_impact == max(split_cons_impact))[1]]
split_cons_final
} else {
i
}
tmp_consequence
}) %>% unlist()
#### Add Variant type to the table (SNV vs InDel)
germline_snv_flt_withCADD_noNA$Type <- "InDel"
germline_snv_flt_withCADD_noNA$Type[which(nchar(germline_snv_flt_withCADD_noNA$ref) == 1 & nchar(germline_snv_flt_withCADD_noNA$alt) == 1)] <- "SNV"
germline_snv_flt_withCADD_noNA_cons_plot <-
ggplot(germline_snv_flt_withCADD_noNA, aes(x = consequence, y = cadd_phred, fill = consequence)) +
geom_boxplot() +
facet_wrap(~Type) +
scale_fill_discrete(name = "Consequence Type", type = fishualize::fish(n = 22)) +
labs(x = NULL, y= "CADD Phred Score") +
coord_flip() +
guides(fill=guide_legend(ncol=1)) +
theme_bw() +
theme(panel.grid.minor = element_blank())
ggsave(filename = "Results/Germline SNV/germline_snv_flt_withCADD_noNA_cons_plot.pdf",
plot = germline_snv_flt_withCADD_noNA_cons_plot, device = "pdf",
width = 16, height = 16, units = "in")
#################################################
### Assign Ensembl VEP IMPACT type to our variants for imputing the CADD scores of variants with no CADD score
#### Add Variant type to the table (SNV vs InDel)
germline_snv_flt_withCADD$Type <- "InDel"
germline_snv_flt_withCADD$Type[which(nchar(germline_snv_flt_withCADD$ref) == 1 & nchar(germline_snv_flt_withCADD$alt) == 1)] <- "SNV"
#### Convert multiple consequence variants to single consequence by keeping only the consequence with the highest VEP impact
germline_snv_flt_withCADD$consequence <-
sapply(germline_snv_flt_withCADD$consequence, function(i) {
tmp_consequence <-
if(length(grep("&|,", i)) > 0) {
split_cons <- strsplit(x = i, split = "&|,") %>% unlist()
split_cons_impact <- vep_impact_tbl$IMPACT_score[match(split_cons, vep_impact_tbl$SO.term)]
split_cons_final <-
split_cons[which(split_cons_impact == max(split_cons_impact))[1]]
split_cons_final
} else {
i
}
tmp_consequence
}) %>% unlist()
#### Remove SNV Type variants that belong to frameshift or synonymous (with high CADD phred scores) consequence class:
##### frameshift:their Alt is wrong and there are only 18 of them
##### synonymous: these variants strangely have high CADD phred scores (above 15) and there are only three of them
germline_snv_flt_withCADD <- germline_snv_flt_withCADD[-which(germline_snv_flt_withCADD$Type == "SNV" &
germline_snv_flt_withCADD$consequence == "frameshift_variant" |
germline_snv_flt_withCADD$consequence == "synonymous_variant" &
germline_snv_flt_withCADD$cadd_phred > 15),]
germline_snv_flt_withCADD$VEP_IMPACT <- ""
for(i in c("MODIFIER", "LOW", "MODERATE", "HIGH")) {
so_terms_index <- which(vep_impact_tbl$IMPACT == i)
so_terms <- c(vep_impact_tbl$SO.term[so_terms_index], vep_impact_tbl$Display.term[so_terms_index])
vep_impact_index <- grep(paste0(so_terms, collapse = "|"), germline_snv_flt_withCADD$consequence, ignore.case = TRUE)
germline_snv_flt_withCADD$VEP_IMPACT[vep_impact_index] <- i
}
#### Impute the missing CADD scores
##### Calculate the median of CADD scores of each class of VEP Impacts
germline_VEP_HIGH_median <- median(germline_snv_flt_withCADD$cadd_phred[germline_snv_flt_withCADD$VEP_IMPACT == "HIGH"], na.rm = TRUE)
germline_VEP_MODERATE_median <- median(germline_snv_flt_withCADD$cadd_phred[germline_snv_flt_withCADD$VEP_IMPACT == "MODERATE"], na.rm = TRUE)
germline_VEP_LOW_median <- median(germline_snv_flt_withCADD$cadd_phred[germline_snv_flt_withCADD$VEP_IMPACT == "LOW"], na.rm = TRUE)
germline_VEP_MODIFIER_median <- median(germline_snv_flt_withCADD$cadd_phred[germline_snv_flt_withCADD$VEP_IMPACT == "MODIFIER"], na.rm = TRUE)
germline_snv_flt_withCADD$cadd_phred <-
sapply(1:nrow(germline_snv_flt_withCADD), function(i) {
imputed_score <-
if(!is.na(germline_snv_flt_withCADD$cadd_phred[i])) {
germline_snv_flt_withCADD$cadd_phred[i]
} else if(germline_snv_flt_withCADD$VEP_IMPACT[i] == "HIGH") {
germline_VEP_HIGH_median
} else if(germline_snv_flt_withCADD$VEP_IMPACT[i] == "MODERATE") {
germline_VEP_MODERATE_median
} else if(germline_snv_flt_withCADD$VEP_IMPACT[i] == "LOW") {
germline_VEP_LOW_median
} else if(germline_snv_flt_withCADD$VEP_IMPACT[i] == "MODIFIER") {
germline_VEP_MODIFIER_median
}
})
#################################################
## Calibrating the CADD scores
### First define the binary labels (pathogenic (1) vs benign (0)) based on clinVar data for training a calibration model
#### Download the clinVar data file (variant_summary.txt.gz)
download.file(url = "https://ftp.ncbi.nlm.nih.gov/pub/clinvar/tab_delimited/variant_summary.txt.gz",
destfile = "~/Downloads/variant_summary.txt.gz")
#### Read in the file
clinVar_summary_con <- gzfile("~/Downloads/variant_summary.txt.gz")
clinVar_summary <- readr::read_delim(clinVar_summary_con, delim = "\t")
rm(clinVar_summary_con)
#### Remove redundant columns
#### and retain only rows with Benign and Pathogenic ClinicalSignificance
#### and remove rows with unknown Position/Ref/Alt ("na" ReferenceAlleleVCF)
clinVar_summary <- clinVar_summary %>% select(Type, Name, GeneSymbol,
ClinicalSignificance, ReviewStatus, Assembly,
Chromosome, PositionVCF,
ReferenceAlleleVCF, AlternateAlleleVCF) %>%
dplyr::filter(grepl("practice guideline|reviewed by expert panel", ReviewStatus)) %>%
dplyr::filter(grepl('^Benign$|^Pathogenic$', ClinicalSignificance)) %>%
subset(ReferenceAlleleVCF != "na")
#### Add coding/non-coding class to the table
clinVar_summary$coding_type <- "noncoding"
clinVar_summary$coding_type[grep(" \\(p\\.", clinVar_summary$Name)] <- "coding"
#### Save the dataset for later use
clinVar_summary_con <- gzfile("Datasets/clinVar_summary.txt.gz")
readr::write_delim(clinVar_summary, clinVar_summary_con, delim = "\t")
rm(clinVar_summary_con)
#################
clinVar_summary_con <- gzfile("Datasets/clinVar_summary.txt.gz")
clinVar_summary <- readr::read_delim(clinVar_summary_con, delim = "\t")
rm(clinVar_summary_con)
### Retain only hg19 for our current project
clinVar_summary <- subset(clinVar_summary, Assembly == "GRCh37")
### Remove germline and somatic variants (testing/calibrating set) from clinVar_summary to make it ready for training
clinVar_summary_omit_index <- which(c(paste(clinVar_summary$Chromosome, as.integer(clinVar_summary$PositionVCF),
clinVar_summary$ReferenceAlleleVCF, clinVar_summary$AlternateAlleleVCF, sep = "_")) %in%
c(paste(germline_snv_flt_withCADD$chr, as.integer(germline_snv_flt_withCADD$pos),
germline_snv_flt_withCADD$ref, germline_snv_flt_withCADD$alt, sep = "_"),
paste(somatic_snv_flt_withCADD$chr, as.integer(somatic_snv_flt_withCADD$pos),
somatic_snv_flt_withCADD$ref, somatic_snv_flt_withCADD$alt, sep = "_")))
clinVar_summary <- clinVar_summary[-clinVar_summary_omit_index,]
### Randomly select 1500 pathogenic (some of them will not have CADD scores) and 1500 benign variants
set.seed(1234)
clinVar_summary_pathogenic <- clinVar_summary[sample(which(clinVar_summary$ClinicalSignificance == "Pathogenic"), size = 1500),]
set.seed(1234)
clinVar_summary_benign <- clinVar_summary[sample(which(clinVar_summary$ClinicalSignificance == "Benign"), size = 1500),]
clinVar_summary_for_training <- rbind(clinVar_summary_pathogenic, clinVar_summary_benign)
rm(clinVar_summary_pathogenic, clinVar_summary_benign)
### Get the CADD scores of the training set
clinVar_summary_for_training$ClinicalSigLabel <- 0
clinVar_summary_for_training$ClinicalSigLabel[clinVar_summary_for_training$ClinicalSignificance == "Pathogenic"] <- 1
#### Shuffle the rows
clinVar_summary_for_training <- clinVar_summary_for_training[sample(nrow(clinVar_summary_for_training)),]
#### Prepare clinVar_summary_chr_cadd_tbl table
clinVar_summary_chr_cadd_tbl <- clinVar_summary_for_training[,c(7,8)]
colnames(clinVar_summary_chr_cadd_tbl) <- c("chr", "min")
clinVar_summary_chr_cadd_tbl$max <- clinVar_summary_chr_cadd_tbl$min
## Retrieve CADD scores for all chromosomes of clinVar_summary
clinVar_summary_cadd_phred_scores <- scanCADD2df(variants_table = clinVar_summary_for_training[,c(7:10)],
tabix_snv_file = "Datasets/CADD/v1.6-hg19 (compressed)/whole_genome_SNVs.compressed.tsv.gz",
tabix_indel_file = "Datasets/CADD/v1.6-hg19 (compressed)/InDels.compressed.tsv.gz",
gr_table = clinVar_summary_chr_cadd_tbl)
## Add cadd data to the table
clinVar_summary_for_training$cadd_phred[clinVar_summary_cadd_phred_scores$index] <- clinVar_summary_cadd_phred_scores$score
# Retrieve missing CADD scores
clinVar_summary_cadd_phred_scores_missing_indices <- which(is.na(clinVar_summary_for_training$cadd_phred))
clinVar_summary_for_training_missed <- clinVar_summary_for_training[clinVar_summary_cadd_phred_scores_missing_indices,]
clinVar_summary_chr_cadd_tbl_missed <- clinVar_summary_for_training_missed[,c(7,8)]
colnames(clinVar_summary_chr_cadd_tbl_missed) <- c("chr", "min")
clinVar_summary_chr_cadd_tbl_missed$max <- clinVar_summary_chr_cadd_tbl_missed$min
clinVar_summary_cadd_phred_scores_missed <- scanCADD2df(variants_table = clinVar_summary_for_training_missed[,c(7:10)],
tabix_snv_file = "Datasets/CADD/v1.6-hg19 (compressed)/whole_genome_SNVs.compressed.tsv.gz",
tabix_indel_file = "Datasets/CADD/v1.6-hg19 (compressed)/InDels.compressed.tsv.gz",
gr_table = clinVar_summary_chr_cadd_tbl_missed)
## Remove the variants with NA cadd scores
clinVar_summary_for_training <- clinVar_summary_for_training[-which(is.na(clinVar_summary_for_training$cadd_phred)),]
## Get the number of remaining Benign and Pathogenic variants
table(clinVar_summary_for_training$ClinicalSignificance)
#Benign Pathogenic
#1485 1443
## Equalize the number of Benign and Pathogenic
diff_ClinicalSignificance <- table(clinVar_summary_for_training$ClinicalSignificance) %>% sort() %>% diff()
set.seed(1234)
clinVar_summary_for_training <- clinVar_summary_for_training[-sample(which(clinVar_summary_for_training$ClinicalSignificance == "Benign"), size = diff_ClinicalSignificance),]
#####################
## Calibrate using GAM
### Visualize coding vs non-coding
library(mgcv)
clinVar_summary_for_training_gam <- gam(data = clinVar_summary_for_training,
formula = ClinicalSigLabel ~ s(cadd_phred, by=as.factor(coding_type)),
family=binomial())
plot(clinVar_summary_for_training_gam,pages=1,residuals=TRUE) ## show partial residuals
### Train for coding and noncoding together
clinVar_summary_for_training_gam <- gam(data = clinVar_summary_for_training,
formula = ClinicalSigLabel ~ s(cadd_phred),
family=binomial())
### We can either use the type="link" to get (-Inf,Inf) predictions then use logistic regression to transform it to (0,1) probabilities or use type="response" to directly get (0,1) probabilities.
#### with type="response" predictions on the scale of the response are returned. So, type="link" would be redundant.
# germline_snv_flt_withCADD_gam_prob <- 1/(1+exp(-predict(clinVar_summary_for_training_gam,
# newdata = germline_snv_flt_withCADD[,"cadd_phred"],
# type="link")))
### get the gam probabilities using the logistic transformation
germline_snv_flt_withCADD_gam_prob <- predict(clinVar_summary_for_training_gam,
newdata = germline_snv_flt_withCADD[,"cadd_phred"],
type="response")
### Visualize calibration probabilities vs original cadd
germline_snv_flt_withCADD$calibCADD_GAM_prob <- as.numeric(germline_snv_flt_withCADD_gam_prob)
germline_snv_flt_GAM_probvsPhred_plot <-
ggplot(germline_snv_flt_withCADD, aes(x = cadd_phred, y = calibCADD_GAM_prob, color = VEP_IMPACT)) +
geom_point() +
scale_color_discrete(name = "Ensembl\nVEP IMPACT", type = fishualize::fish(n = 4)) +
labs(x = "CADD Phred Score", y= "GAM-based Calibrated CADD Score (Pathogenicity Probability)") +
guides(fill=guide_legend(ncol=1)) +
theme_bw() +
theme(panel.grid.minor = element_blank())
germline_snv_flt_GAM_probvsPhred_plot
ggsave(filename = "Results/Germline SNV/ML-based calibration/GAM/germline_snv_flt_GAM_probvsPhred_plot.pdf",
plot = germline_snv_flt_GAM_probvsPhred_plot,
device = "pdf", width = 8, height = 8, units = "in")
# Log transform GAM probabilities
germline_snv_flt_withCADD$calibCADD_GAM_prob_log <- (-10)*log10(1-germline_snv_flt_withCADD$calibCADD_GAM_prob)
###################
# Define Min-Max (range) normalization
range_normalize <- function(data, min = 0, max = 1, na.rm = TRUE, ...) {
min+(((data-min(data, na.rm = na.rm, ...))*(max-min))/
(max(data, na.rm = na.rm, ...)-min(data, na.rm = na.rm, ...)))
}
#################################################
## Retain only PRISM study data
germline_snv_flt_withCADD <- subset(germline_snv_flt_withCADD, study == "PRISM")
## Calculate nalt for all variants
germline_snv_flt_withCADD_nalt <- lapply(unique(germline_snv_flt_withCADD$variant_id), function(i) {
tmp_data <- subset(germline_snv_flt_withCADD, variant_id == i)
ref <- tmp_data$ref[1]
genotypes <- tmp_data$genotype %>%
stringr::str_split(pattern = "/", n = 2) %>% unlist()
count <- length(genotypes) - grep(pattern = paste0("^", ref, "$"), x = genotypes) %>% length()
tmp_tbl <- data.frame(variant_id = i, nalt = count)
})
germline_snv_flt_withCADD_nalt <- do.call(rbind, germline_snv_flt_withCADD_nalt)
germline_snv_flt_withCADD$nalt <- germline_snv_flt_withCADD_nalt$nalt[match(germline_snv_flt_withCADD$variant_id, germline_snv_flt_withCADD_nalt$variant_id)]
######################################################################################
######################################################################################
# Evaluating whether the variants that have recurrences fall within the bad genomic regions or not
library(rtracklayer)
library(GenomicRanges)
library(parallel)
## Import bad (difficult to sequence regions)
GRCh37_difficult_regions <- rtracklayer::import("Datasets/GRCh37_alldifficultregions.bed.gz")
germline_query_granges <- GenomicRanges::GRanges(seqnames = germline_snv_flt_withCADD$chr,
ranges = IRanges(germline_snv_flt_withCADD$pos, width = 1))
germline_bad_region <- GenomicRanges::findOverlaps(germline_query_granges, GRCh37_difficult_regions) %>%
as.data.frame() %>% select(queryHits) %>% unlist() %>% unname()
### Add to the dataset whether each variant is within a bad region or not
germline_snv_flt_withCADD$bad_region <- FALSE
germline_snv_flt_withCADD$bad_region[germline_bad_region] <- TRUE
### Add to the dataset whether each variant is recurrent or not
germline_recurrrent_vars <- # name of the vector will be the name of recurrent variants and the value of each element will be its number of recurrence
germline_snv_flt_withCADD %>%
janitor::get_dupes(variant_id) %>%
select(variant_id) %>%
unlist() %>%
unname() %>%
table()
germline_snv_flt_withCADD <-
germline_snv_flt_withCADD %>%
mutate(recurrent = ifelse(variant_id %in% names(germline_recurrrent_vars), TRUE, FALSE))
#### Add the number of recurrence
germline_snv_flt_withCADD$n_recurrence <- 1
lapply(1:length(germline_recurrrent_vars), function(i) {
germline_snv_flt_withCADD$n_recurrence[germline_snv_flt_withCADD$variant_id == names(germline_recurrrent_vars)[i]] <<-
germline_recurrrent_vars[i]
return(NULL)
})
germline_snv_flt_withCADD$recurrent[germline_snv_flt_withCADD$recurrent == TRUE] <- "Recurrent"
germline_snv_flt_withCADD$recurrent[germline_snv_flt_withCADD$recurrent == FALSE] <- "Non-recurrent"
germline_snv_flt_withCADD$bad_region[germline_snv_flt_withCADD$bad_region == TRUE] <- "Difficult Region"
germline_snv_flt_withCADD$bad_region[germline_snv_flt_withCADD$bad_region == FALSE] <- "Non-difficult Region"
### Visualizing the results
germline_snv_bad_region_vis1 <- ggplot(data = germline_snv_flt_withCADD, aes(x = recurrent, fill = bad_region)) +
geom_bar(position = "dodge") +
labs(fill = "Region Quality Type") +
ylab("Number of variants") +
xlab(NULL) +
fishualize::scale_fill_fish_d() +
theme_classic()
germline_snv_bad_region_vis2 <- ggplot(data = germline_snv_flt_withCADD, aes(x = recurrent, fill = bad_region)) +
geom_bar(position = "fill") +
ylab("Proportion") +
labs(fill = "Region Quality Type") +
xlab(NULL) +
stat_count(geom = "text",
aes(label = stat(count)),
position=position_fill(vjust=0.5), colour="white") +
fishualize::scale_fill_fish_d() +
theme_classic()
######################################################################################
######################################################################################
# filtering out variants seen in > 5% of the cohort (filtering out platform errors)
## Although it is conceivable that real biological signal might be present at 5% rate within a cohort (specific cancer type), it's less likely that such signal would be present at 5% across all cancers. But platform error will be present at the same rate in all.
### Save the data that include the highly recurrent variants as well
saveRDS(object = germline_snv_flt_withCADD, file = "Germline data with recurrences/germline_snv_flt_withCADD.rds")
### Also keep as an object
germline_snv_withRecurr_withCADD <- germline_snv_flt_withCADD
germline_snv_flt_withCADD <- subset(germline_snv_flt_withCADD, n_recurrence <= round(0.05*length(unique(germline_snv_flt_withCADD$patient_id))))
## Plot that highly frequent variants are removed.
table(janitor::get_dupes(germline_snv_flt_withCADD, variant_id)$variant_id) %>% table() %>% plot()
### Visualize the results
germline_snv_recurrflt_bad_region_vis1 <- ggplot(data = germline_snv_flt_withCADD, aes(x = recurrent, fill = bad_region)) +
geom_bar(position = "dodge") +
labs(fill = "Region Quality Type") +
ylab("Number of variants") +
xlab(NULL) +
fishualize::scale_fill_fish_d() +
theme_classic()
germline_snv_recurrflt_bad_region_vis2 <- ggplot(data = germline_snv_flt_withCADD, aes(x = recurrent, fill = bad_region)) +
geom_bar(position = "fill") +
ylab("Proportion") +
labs(fill = "Region Quality Type") +
xlab(NULL) +
stat_count(geom = "text",
aes(label = stat(count)),
position=position_fill(vjust=0.5), colour="white") +
fishualize::scale_fill_fish_d() +
theme_classic()
### We see that Generally, the recurrent variants are mostly present in the "Difficult regions".
### After filtration, we still have recurrent variants in the difficult regions but the proportion of "Difficult region"- vs "Non-difficult regions"-recurrent variants has changed after the filtration.
######################################################################################
######################################################################################
# checking the region quality type of ribosomal protein genes
ribo_p_pattern <- "^RPS\\d+$|^RPL\\d+$"
germline_snv_ribosomal_genes <- germline_snv_flt_withCADD$gene[stringr::str_detect(germline_snv_flt_withCADD$gene, ribo_p_pattern)]
ggplot(data = germline_snv_flt_withCADD %>% filter(gene %in% germline_snv_ribosomal_genes), aes(x = recurrent, fill = bad_region)) +
geom_bar(position = "fill") +
ylab("Proportion") +
labs(fill = "Region Quality Type") +
xlab(NULL) +
stat_count(geom = "text",
aes(label = stat(count)),
position=position_fill(vjust=0.5), colour="white") +
fishualize::scale_fill_fish_d() +
theme_classic()
germline_snv_flt_withCADD %>% filter(gene %in% germline_snv_ribosomal_genes) %>% filter(bad_region == "Non-difficult Region") %>% select(variant_id, chr, pos, ref, alt, gene, transcript, cadd_phred, bad_region, n_recurrence) %>% View()
################################
## check if the ribosomal protein gene variants fall within repeatitive regions
library(rtracklayer)
library(GenomicRanges)
library(UCSCRepeatMasker)
library(AnnotationHub)
germline_snv_flt_withCADD_ribo <- germline_snv_flt_withCADD %>% filter(gene %in% germline_snv_ribosomal_genes)
### Load AnnotationHub
ah <- AnnotationHub()
### find the reference version you wanna use
query(ah, c("RepeatMasker", "Homo sapiens"))
### retrieve RepeatMaskers
rmskhg19 <- ah[["AH99002"]]
### create the GRanges of germline_snv_flt_withCADD_ribo
germline_snv_ribo_granges <- GenomicRanges::GRanges(seqnames = paste("chr", germline_snv_flt_withCADD_ribo$chr, sep = ""),
ranges = IRanges(germline_snv_flt_withCADD_ribo$pos, width = 1))
### find the overlap between RepeatMaskers and our variants