forked from Hollenbach-lab/PING-legacy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPING_allele_caller_v1.0.R
executable file
·1516 lines (1144 loc) · 57 KB
/
PING_allele_caller_v1.0.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
# Copyright 2016 Wesley Marin, Jill Hollenbach, Paul Norman
#
# This file is part of PING.
#
# PING is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PING is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PING. If not, see <http://www.gnu.org/licenses/>.
ping_allele_caller <- function(
sample.location = "PING_sequences/",
fastq.pattern.1 = "_1.fastq.gz",
fastq.pattern.2 = "_2.fastq.gz",
bowtie.threads = 4,
supported.loci = c("2DL1", "2DL23", "2DL4", "2DL5", "2DS3", "2DS4", "2DS5", "2DP1", "3DL1", "3DS1", "3DL2", "3DL3"),
ping.gc.output = "Combined_results.csv",
results.directory = ""
){
library(data.table) ## Used for fread
library(ape) ## Used for read.dna an seg.sites
library(stringr)
source("Resources/locus_functions.R", local = TRUE)
###################
# Helper functions --------------------------------------------------------
###################
# Creates results directory
results_directory <- function() {
cat("----- Getting PING ready -----\n\n")
if(results.directory != ""){
save_to <- results.directory
}else{
save_to <- paste0("Caller_results_", format(Sys.time(), "%Y_%m_%d_%H:%M"), "/")
count <- 1
while(file.exists(save_to)) {
save_to <- paste0("Caller_results_", format(Sys.time(), "%Y_%m_%d_%H:%M"), "_", count, "/")
count <- count + 1
}
}
dir.create(save_to)
cat(paste("Results being saved to", save_to, "\n\n"))
return(save_to)
}
# Creates results folders
ping.ready <- function() {
dir.create(results.directory, showWarnings = F)
dir.create(paste0(results.directory, "Vcf"), showWarnings = F)
dir.create(paste0(results.directory, "KIRcaller"), showWarnings = F)
dir.create(paste0(results.directory, "Fastq"), showWarnings = F)
cat("Results directories created.\n\n")
}
# Finds sequences
get_sequence_list <- function() {
sequence_list = list.files(file.path(sample.location), pattern = fastq.pattern.1)
if (is.na(sequence_list[1])) {
string <- paste("No sequences found in", sample.location, "using fastq pattern", fastq.pattern.1)
stop(string)
} else {
sequence_list <- gsub(fastq.pattern.1, "", sequence_list)
cat(paste("Found sequences: ", paste(sequence_list, collapse = "\n"), sep = "\n"))
cat("\n")
return(sequence_list)
}
}
# Reads in PING_GC results
gc.results <- function(){
gc.table <- read.csv(ping.gc.output, check.names = F)
rownames(gc.table) <- gc.table[,1]
gc.table <- gc.table[,-1, drop=F]
return(gc.table)
}
# Caps sequences at 120,000 lines
cut_fastq <- function(file.name, read.cap, post.file.name, is.gz) {
# Uncompressing if is.gz and moving to post.file.name, this happens one at a time, so space should not be a concern
if(is.gz){
file_contents <- fread(paste("zcat", file.name), sep="\n", nrows = read.cap, header = F)
}else{
file_contents <- fread(file.name, sep="\n", nrows = read.cap, header = F)
}
write.table(file_contents, file = post.file.name, quote = F, row.names = F, col.names = F)
}
# Finds files that are smaller than the recommended size
files_too_small <- function(sequence.list, is.gz){
small_samples <- NA
for(sample in sequence.list){
# Get the line counts, both for gzip and regular files
if(is.gz){
line_count <- as.numeric(system2("zcat", c(paste0(sample.location, sample, fastq.pattern.1), "|", "wc", "-l"), stdout = T))
}else{
line_count <- as.numeric(system2("wc", c("-l", "<", paste0(sample.location, sample, fastq.pattern.1)), stdout = T))
}
if(line_count < 280000){
small_samples <- c(small_samples, paste0(sample.location, sample, fastq.pattern.1))
}
# Same thing, but for _2 files
if(is.gz){
line_count <- as.numeric(system2("zcat", c(paste0(sample.location, sample, fastq.pattern.2), "|", "wc", "-l"), stdout = T))
}else{
line_count <- as.numeric(system2("wc", c("-l", "<", paste0(sample.location, sample, fastq.pattern.2)), stdout = T))
}
if(line_count < 280000){
small_samples <- c(small_samples, paste0(sample.location, sample, fastq.pattern.2))
}
}
small_samples <- small_samples[!is.na(small_samples)]
if(length(small_samples) > 0){
error.string <- "\n\nThese files have fewer than the recommended lines, results might be effected:\n"
cat(error.string)
error.log(error.string)
cat(paste(small_samples), sep='\n')
error.log(paste(small_samples, collapse='\n'))
cat("\nContinuing PING analysis...\n\n")
}
return(small_samples)
}
# Create consensus sequence -- NOT WORKING
# create_consensus <- function(sample, vcf.file, filter.directory, results.directory){
#
#
# }
# Permutates allele codes
permutator <- function(codes) {
sections <- length(codes)
section_length <- length(codes) - 1
total_length <- section_length * sections
final_codes <- data.frame(matrix(0, nrow = total_length, ncol = 2))
for(i in 0:(sections-1)){
other_codes <- codes[!codes == codes[i + 1]]
for(j in 1:section_length){
final_codes[i*section_length + j, 1] <- codes[i + 1]
final_codes[i*section_length + j, 2] <- other_codes[j]
}
}
return(final_codes)
}
# Build primer table from forward and reverse primer files
make_primer_table <- function(primerlist.file) {
primer_table = read.delim(primerlist.file, header = FALSE)
colnames(primer_table) <- c("Locus", "Primer")
primer_table$Primer <- gsub(" ", "", primer_table[["Primer"]])
return(primer_table)
}
# Counting primer matches to a table
count_primer_matches <- function(primer.table, sample, is.gz) {
primer_count_table <- data.frame(matrix(0, nrow=length(primer.table[,1]), ncol=length(sample)))
rownames(primer_count_table) <- primer.table$Locus
colnames(primer_count_table) <- sample
counter <- 1
while(counter <= 2) {
if(counter == 1) {
if(is.gz){
cat(paste0(sample, no.gz.pattern.1, "\n"))
inFile <- paste0(sample, no.gz.pattern.1)
}else{
cat(paste0(sample, fastq.pattern.1, "\n"))
inFile <- paste0(sample, fastq.pattern.1)
}
}else{
if(is.gz){
cat(paste0(sample, no.gz.pattern.2, "\n"))
inFile <- paste0(sample, no.gz.pattern.2)
}else{
cat(paste0(sample, fastq.pattern.2, "\n"))
inFile <- paste0(sample, fastq.pattern.2)
}
}
file_contents <- fread(inFile, sep="\n", header=FALSE)
file_contents <- file_contents[seq(2, length(file_contents[[1]]), 4)]
for(j in 1:length(primer.table[,"Primer"])) {
primer_count_table[j, sample] <- sum(length(grep(primer.table[j, "Primer"], file_contents[[1]], fixed=TRUE)), primer_count_table[j, sample])
}
remove(file_contents)
counter = counter + 1
}
return(primer_count_table)
}
# Normalize primer counts
reduce_and_normalize_primer_counts <- function(primer.count.table, sample) {
# Adding forward and reverse primer counts
for(i in 1:length(primer.count.table[,1])) {
primer.count.table[rownames(primer.count.table)[i],] <- primer.count.table[rownames(primer.count.table)[i],] + primer.count.table[paste0(rownames(primer.count.table)[i],"rc"),]
}
primer_rows <- rownames(primer.count.table)
primer_rows <- primer_rows[1:(length(primer_rows)/2)]
# Making a new frame from added values
reduced_table <- as.data.frame(primer.count.table[1:(length(primer.count.table[,1])/2),], row.names = primer_rows)
colnames(reduced_table) <- sample
loci_list <- unlist(strsplit(rownames(reduced_table), "_"))
loci_list <- unique(loci_list[grep(">", loci_list)])
normalized_table <- data.frame(matrix(0, nrow=length(loci_list), ncol=length(sample)))
rownames(normalized_table) <- loci_list
colnames(normalized_table) <- sample
# Build further reduced table by combining counts for each locus
for(j in 1:length(loci_list)) {
normalized_table[loci_list[j], sample] <- sum(reduced_table[grep(paste0(loci_list[j],"_"), rownames(reduced_table)), sample])
}
# Taking out all the arrows from the loci list
new_list <- unique(unlist(strsplit(loci_list, ">")))
new_list <- new_list[2:length(new_list)]
rownames(normalized_table) <- sapply(strsplit(rownames(normalized_table), ">"), '[', 2)
return(normalized_table)
}
# Check against threshold
threshold_check <- function(normalized.table, sample, threshold.kff){
# Checking to see if the results are above the set threshold value
normalized.table[, sample] <- (normalized.table[, sample] > threshold.kff) * 1
return(normalized.table)
}
# Allele generation for locus (relies on resource files)
alleles_gen.vcf <- function(current.locus){
all_alleles_preKFF <- read.delim(paste0("Resources/caller_resources/All_", current.locus, "_preKFF.fas"), header=F, colClasses="character")
length_seq <- nchar(all_alleles_preKFF[1,2])
num_seq <- length(all_alleles_preKFF[,1])
top_row <- data.frame(cbind(num_seq, length_seq))
names(top_row) <- names(all_alleles_preKFF)
all_alleles <- rbind(top_row, all_alleles_preKFF)
write.table(all_alleles, paste0(results.directory, "KIRcaller/All_", current.locus, ".txt"), row.names = FALSE, col.names = FALSE, quote = FALSE)
}
# Snps generation for locus (relies on resource files)
snps_gen.vcf <- function(current.locus){
seq_locus <- read.dna(paste0(results.directory, "KIRcaller/All_", current.locus, ".txt"), format = "sequential")
snps <- seg.sites(seq_locus)
seq_locus.2 <- read.dna(paste0(results.directory, "KIRcaller/All_", current.locus, ".txt"), format = "sequential", as.character = TRUE)
seq_locus.2 <- apply(seq_locus.2, MARGIN = c(1, 2), toupper)
seq_locus.df <- data.frame(seq_locus.2, stringsAsFactors = F)
snp.cols <- paste0("X", snps)
snps_locus <- seq_locus.df[,snp.cols]
allele <- gsub(">", "", row.names(seq_locus.2))
snps_locus <- data.frame(cbind(allele, snps_locus), stringsAsFactors = F)
write.table(snps_locus, paste0(results.directory, "KIRcaller/KIR_", current.locus, "_alleles.txt"), quote = FALSE, row.names = FALSE)
SOS_locus_lookup <- snps_locus
KIR_locus_gene_VScDNA <- read.delim(paste0("Resources/caller_resources/KIR", current.locus, "geneVScDNA.txt"))
cdna <- paste0("X", KIR_locus_gene_VScDNA$cDNA)
gene <- paste0("X", KIR_locus_gene_VScDNA$gene)
map_pos <- data.frame(cbind(cdna, gene))
pos_trans <- as.character(map_pos[match(names(SOS_locus_lookup[-1]), map_pos$cdna), 2])
names(SOS_locus_lookup) <- c("allele", pos_trans)
return(SOS_locus_lookup)
}
# Pull indels from VCF data frame
indels.vcf <- function(x) {
vcf_file <- data.frame(x)
vcf_file_indels <- vcf_file[grep("INDEL;", vcf_file[,8]),]
if(nrow(vcf_file_indels) > 0){
vcf_file_indels[,1] <- paste0(sample, vcf_file_indels[,1], sep="_")
}
return(vcf_file_indels)
}
# Remove indels from VCF data frame
nodels.vcf <- function(x) {
vcf_file <- data.frame(x)
vcf_file_nodels <- vcf_file[grep("INDEL;", vcf_file[,8], invert = TRUE),]
return(vcf_file_nodels)
}
# Format VCF data frame for allele calling functions
format.vcf <- function(x) {
vcf_file <- data.frame(x)
vcf_file[,10] <- gsub("0/0", "0", vcf_file[,10]) ### This is to convert between old and new samtools vcf format
vcf_file <- vcf_file[grep("./.", vcf_file[,10], fixed = T, invert = T),]
vcf_file <- vcf_file[grep("DP4=", vcf_file[,8]),]
genotype <- sapply(strsplit(as.character(vcf_file[,10]), ":"), "[", 1)
depth <- sapply(strsplit(as.character(vcf_file[,8]), ";"), "[", 1)
# A little check to make sure we are actually getting the depth
if(!isTRUE(length(grep("DP=", depth)) > 0)) {
stop("Bad VCF format, DP is not where expected.")
}
depth <- as.numeric(gsub("DP=", "", depth))
for_rev <- unlist(strsplit(as.character(vcf_file[,8]), ";"))
for_rev <- for_rev[grep("DP4=", for_rev)]
fw <- as.numeric(sapply(strsplit(as.character(for_rev), ","), "[", 3))
rev <- as.numeric(sapply(strsplit(as.character(for_rev), ","), "[", 4))
fw[is.na(fw)] <- 0
rev[is.na(rev)] <- 0
fw <- ifelse(fw > 3, 1, 0)
rev <- ifelse(rev > 3, 1, 0)
fwrev <- fw + rev
KIR_sample <- data.frame(cbind(as.character(vcf_file[,2]), as.character(vcf_file[,4]), as.character(vcf_file[,5]), genotype, as.character(depth), fwrev), stringsAsFactors = FALSE)
KIR_sample <- KIR_sample[!KIR_sample[,1] == "line", ]
row.names(KIR_sample) <- KIR_sample[,1]
KIR_sample_snps <- KIR_sample[as.character(positions),]
KIR_sample_snps <- na.omit(KIR_sample_snps)
names(KIR_sample_snps) <- c("position", "ref", "var", "genotype", "depth", "fwrev")
KIR_sample_snps$depth <- as.numeric(KIR_sample_snps$depth)
KIR_sample_snps <- KIR_sample_snps[!KIR_sample_snps$depth < 20,]
if(length(KIR_sample_snps[,1]) == 0){
return(NULL)
}
KIR_sample_snps$snp1 <- sapply(strsplit(as.character(KIR_sample_snps$genotype), "/"), "[", 1)
KIR_sample_snps$snp2 <- sapply(strsplit(as.character(KIR_sample_snps$genotype), "/"), "[", 2)
KIR_sample_snps[is.na(KIR_sample_snps)] <- 0
KIR_sample_snps$var_called <- as.numeric(KIR_sample_snps$snp1)+as.numeric(KIR_sample_snps$snp2)
KIR_sample_snps$var_called <- ifelse(KIR_sample_snps$var_called>0,1,0)
KIR_sample_snps$var_called <- ifelse(KIR_sample_snps$var_called>0,1,0)
KIR_sample_snps$fwrev <- ifelse(KIR_sample_snps$fwrev>0,1,0)
return(KIR_sample_snps)
}
# Even more VCF formatting
emformat.vcf <- function(x){
KIR_sample_snps <- format.vcf(x)
if(is.null(KIR_sample_snps)){
return(NULL)
}
KIR_sample_snps$badcall <- KIR_sample_snps$var_called+KIR_sample_snps$fwrev
KIR_sample_snps <- KIR_sample_snps[!KIR_sample_snps$badcall == 1, ]
if(nrow(KIR_sample_snps) == 0){
return(NULL)
}
KIR_sample_snps$genotype <- NULL
KIR_sample_snps <- KIR_sample_snps[!KIR_sample_snps$snp1>2, ]
KIR_sample_snps <- KIR_sample_snps[!KIR_sample_snps$snp2>2, ]
for( i in 1:length(KIR_sample_snps$snp1) ) {
KIR_sample_snps$snp1call[i] <- ifelse(KIR_sample_snps$snp1[i] == 0, as.character(KIR_sample_snps$ref[i]), as.character(str_split(KIR_sample_snps$var[i], ",")[[1]][as.numeric(KIR_sample_snps$snp1[i])]))
}
for( i in 1:length(KIR_sample_snps$snp2) ) {
KIR_sample_snps$snp2call[i] <- ifelse(KIR_sample_snps$snp2[i] == 0, as.character(KIR_sample_snps$ref[i]), as.character(str_split(KIR_sample_snps$var[i], ",")[[1]][as.numeric(KIR_sample_snps$snp2[i])]))
}
return(KIR_sample_snps)
}
# Check VCF data frame for correct formatting
check.vcf <- function(x){
if(length(x[,1]) == 383 && current.locus == "2DL23"){
# Generating position information for the current locus
SOS_locus_lookup <<- snps_gen.vcf("2DL2")
positions <<- gsub("X", "", names(SOS_locus_lookup)[-1])
}
KIR_sample_snps <- emformat.vcf(x)
if(length(x[,1]) == 383 && current.locus == "2DL23"){
# Generating position information for the current locus
SOS_locus_lookup <<- snps_gen.vcf(current.locus)
positions <<- gsub("X", "", names(SOS_locus_lookup)[-1])
}
good_vcf <- ifelse(dim(KIR_sample_snps)[1] > 2, "yes", "no")
if(is.null(KIR_sample_snps)){
good_vcf <- "no"
}
return(good_vcf)
}
# Function to enumerate all possible haplotypes of SNPs (all possible genotypes)
# cannibalized from haplo.stats
haplo.enum <- function(hmat, geno_call, reads_pos) {
# Exact same as haplo.enum but made for handling one whole row of ugeno
# instead of haploids
# enumerate all possible haplotypes, given input vectors
# h1 and h2 (one possible set of haplotypes)
# and return in matrices h1 and h2 all possible haps.
# This algorithm sets up the h1.mtx and h2.mtx matrices with NA
# values, then moves across the loci which are heterozygous
# (after the 1st het locus), flipping alleles at heterozygous
# locations, and saving results in rows moving down the matrices.
# next three commands added 8/23 jps
old_hmat <- hmat
hmat <- matrix(hmat,nrow=1)
h1 <- hmat[,seq(1,(ncol(hmat)-1),by=2)]
h2 <- hmat[,seq(2,ncol(hmat),by=2)]
# the rest is the same as before
het <- h1 != h2
nhet <- sum(het) # only enumerate if > 1 het loci
# Trying to work out a shortcut for highly ambiguous calls
if(nhet >= 10){
lookup <- SOS_locus_lookup
lookup <- lookup[reads_pos]
for(i in 1:ncol(old_hmat)){
lookup <- lookup[as.logical(lookup[i] == old_hmat[1,i] | lookup[i] == old_hmat[2,i]),]
if(nrow(lookup) == 0 && geno_call == T){
cat(paste("\n\nBroke out of hmat! This most likely saved a significant amount of time\n\n"))
return(list(h1 = matrix(h1, nrow = 1), h2 = matrix(h2, nrow = 1
)))
}
}
}
if(nhet <= 1) {
return(list(h1 = matrix(h1, nrow = 1), h2 = matrix(h2, nrow = 1
)))
}
# only need to flip at heterozygous loci, after 1st het locus:
nloci <- length(h1)
which <- (1:nloci)[het]
which <- which[-1]
h1.mtx <- h2.mtx <- matrix(NA, nrow = 2^(nhet - 1), ncol = nloci)
h1.mtx[1, ] <- h1
h2.mtx[1, ] <- h2
indx.row <- 1
for(i in which) {
nr <- sum(!is.na(h1.mtx[, 1]))
for(j in 1:nr) {
indx.row <- indx.row + 1
# used to move down to the next row of matrix
# now for flipping alleles across loci
if(i < nloci) {
h1.mtx[indx.row, ] <- c(h1.mtx[j, 1:(i - 1)],
h2.mtx[j, i], h1.mtx[j, (i + 1):nloci])
h2.mtx[indx.row, ] <- c(h2.mtx[j, 1:(i - 1)],
h1.mtx[j, i], h2.mtx[j, (i + 1):nloci])
}
if(i == nloci) {
h1.mtx[indx.row, ] <- c(h1.mtx[j, 1:(i - 1)],
h2.mtx[j, i])
h2.mtx[indx.row, ] <- c(h2.mtx[j, 1:(i - 1)],
h1.mtx[j, i])
}
}
}
if(nhet >= 10 && geno_call == T){
for(i in which[-1]){
lookup_strings <- do.call(paste0, lookup[,1:i])
good_haps_h1 <- apply(format(h1.mtx[,1:i]), 1, paste, collapse="") %in% lookup_strings
good_haps_h2 <- apply(format(h2.mtx[,1:i]), 1, paste, collapse="") %in% lookup_strings
h1.mtx <- h1.mtx[good_haps_h1 & good_haps_h2,, drop = FALSE]
h2.mtx <- h2.mtx[good_haps_h1 & good_haps_h2,, drop = FALSE]
if(nrow(h1.mtx) == 0){
error_string <- paste("\n\nUh ohh, all the rows got taken out trying to find new alleles for", sample, "at", current.locus, "\n\n")
cat(error_string)
error.log(error_string)
return(list(h1 = rbind(h1.mtx, "N"), h2 = rbind(h2.mtx, "N")))
}
}
}else if(nhet >= 10){
for(i in which[-1]){
lookup_strings <- do.call(paste0, lookup[,1:i])
good_haps_h1 <- apply(format(h1.mtx[,1:i]), 1, paste, collapse="") %in% lookup_strings
good_haps_h2 <- apply(format(h2.mtx[,1:i]), 1, paste, collapse="") %in% lookup_strings
h1.mtx <- h1.mtx[good_haps_h1 | good_haps_h2,, drop = FALSE]
h2.mtx <- h2.mtx[good_haps_h1 | good_haps_h2,, drop = FALSE]
if(nrow(h1.mtx) == 0){
error_string <- paste("\n\nUh ohh, all the rows got taken out trying to find new alleles for", sample, "at", current.locus, "\n\n")
cat(error_string)
error.log(error_string)
return(list(h1 = rbind(h1.mtx, "N"), h2 = rbind(h2.mtx, "N")))
}
}
}
return(list(h1 = h1.mtx, h2 = h2.mtx))
}
# Special 2DL23 genotyping
genos_2DL23 <- function(genos.out){
vector_call_2DL2 <- NA
vector_call_2DL3 <- NA
for(item in genos.out){
item_frame <- as.data.frame(item)
# Grabbing and reshaping each type of call into a vector
call_2DL2 <- grep("KIR2DL2_", item_frame)
if(length(call_2DL2) > 0){
frame_call_2DL2 <- item_frame[call_2DL2]
vector_call_2DL2 <- c(vector_call_2DL2, t(frame_call_2DL2))
vector_call_2DL2 <- vector_call_2DL2[!is.na(vector_call_2DL2)]
}
call_2DL3 <- grep("KIR2DL3_", item_frame)
if(length(call_2DL3) > 0){
frame_call_2DL3 <- item_frame[call_2DL3]
vector_call_2DL3 <- c(vector_call_2DL3, t(frame_call_2DL3))
vector_call_2DL3 <- vector_call_2DL3[!is.na(vector_call_2DL3)]
}
}
# Finding any 2DL2 alleles by finding the intersection of each 2DL2 call
if(length(vector_call_2DL2) == 3){
one <- unlist(strsplit(vector_call_2DL2, "/")[1])
two <- unlist(strsplit(vector_call_2DL2, "/")[2])
three <- unlist(strsplit(vector_call_2DL2, "/")[3])
step_one <- intersect(two, three)
allele_one <- intersect(one, step_one)
}else if(length(vector_call_2DL2) == 4){
one <- unlist(strsplit(vector_call_2DL2, "/")[1])
two <- unlist(strsplit(vector_call_2DL2, "/")[2])
three <- unlist(strsplit(vector_call_2DL2, "/")[3])
four <- unlist(strsplit(vector_call_2DL2, "/")[4])
allele_one <- intersect(one, three)
allele_two <- intersect(two, four)
if(length(allele_one) == 0 || length(allele_two) == 0){
allele_one <- intersect(one, four)
allele_two <- intersect(two, three)
}
}
# Finding any 2DL3 alleles by finding the intersection of each 2DL3 call
if(length(vector_call_2DL3) == 3){
one <- unlist(strsplit(vector_call_2DL3, "/")[1])
two <- unlist(strsplit(vector_call_2DL3, "/")[2])
three <- unlist(strsplit(vector_call_2DL3, "/")[3])
step_one <- intersect(two, three)
allele_two <- intersect(one, step_one)
}else if(length(vector_call_2DL3) == 4){
one <- unlist(strsplit(vector_call_2DL3, "/")[1])
two <- unlist(strsplit(vector_call_2DL3, "/")[2])
three <- unlist(strsplit(vector_call_2DL3, "/")[3])
four <- unlist(strsplit(vector_call_2DL3, "/")[4])
allele_one <- intersect(one, three)
allele_two <- intersect(two, four)
if(length(allele_one) == 0 || length(allele_two) == 0){
allele_one <- intersect(one, four)
allele_two <- intersect(two, three)
}
}
genos.out <- genos.out[1]
genos.out[[1]]$X1 <- tryCatch(paste(allele_one, collapse = "/"), error=function(e) "new")
genos.out[[1]]$X2 <- tryCatch(paste(allele_two, collapse = "/"), error=function(e) "new")
return(genos.out)
}
error.log <- function(error.string){
error_file <- paste0(results.directory, "Error.log")
if(file.exists(error_file)){
error_log <- file(error_file, open = "at")
}else{
error_log <- file(error_file, open = "wt")
}
sink(error_log)
cat(error.string)
sink()
close(error_log)
}
#################
# PING functions ----------------------------------------------------------
#################
# Determine presence/absence by counting probe matches
ping.kff <- function(sample, current.locus, primerlist, threshold) {
# Run KFF -------------------------------------------------
cat("\n\n")
cat("----- Running KFF -----\n")
cat("\n")
cat("\n")
cat("Building primer table. \n")
primer_table <- make_primer_table(primerlist)
cat("\n")
cat("Counting primers in: \n")
primer_match_table <- count_primer_matches(primer_table, sample, is_gz)
cat("\n")
cat("Reducing and normalizing primer counts. \n")
normalized_results <- reduce_and_normalize_primer_counts(primer_match_table, sample)
if(file.exists(paste0(results.directory, "KIRcaller/KFF_counts_", current.locus, ".txt"))){
write.table(t(normalized_results), paste0(results.directory, "KIRcaller/KFF_counts_", current.locus, ".txt"), sep = " ", append = T, row.names = T, col.names = F, quote = F)
}else{
write.table(t(normalized_results), paste0(results.directory, "KIRcaller/KFF_counts_", current.locus, ".txt"), sep = " ", row.names = T, col.names = NA, quote = F)
}
checked_results <- threshold_check(normalized_results, sample, threshold)
## If the results file already exists, just add on to the bottom of it
transposed_results <- data.frame(t(checked_results), check.names = F)
return(transposed_results)
}
# Integrate kff results with genotype calls
kff_integrator <- function(sample, current.locus, lookitup, poss_genos){
###alle calling
allele1 <- ifelse(poss_genos$X1 %in% lookitup$string, (lookitup[match(poss_genos$X1, lookitup$string), 1]),"new")
allele2 <- ifelse(poss_genos$X2 %in% lookitup$string, (lookitup[match(poss_genos$X2, lookitup$string), 1]),"new")
poss_genos <- data.frame(cbind(as.character(allele1),as.character(allele2)), stringsAsFactors = FALSE)
poss_genos <- poss_genos[!poss_genos$X1 == "new",]
poss_genos <- poss_genos[!poss_genos$X2 == "new",]
kff_legend <- read.delim(paste0("Resources/caller_resources/KIR_", current.locus, "_kff_legend.txt"))
kff_types <- kff_legend[grep("KIR", kff_legend[,1], invert=T),]
kff_legend <- kff_legend[grep("KIR", kff_legend[,1]),]
if(length(kff_legend$allele) != length(lookitup$string)) {
cat("\n\n!!\nError: Number of kff legend alleles does not equal All_*_preKFF.fas alleles.\n!!\n\n")
}
## Generate kff results to poss_genos table
kff_results <- ping.kff(sample, current.locus, "Resources/caller_resources/2DL49or10_64bit.txt", 10)
## Get allele codes for kff positive results
codes <- NULL
rownum <- grep(sample, rownames(kff_results))
for(i in 1:length(kff_results[rownum,])){
if(as.numeric(kff_results[rownum, i]) == 1){
codes <- c(codes, as.character(kff_types$code[grep(colnames(kff_results)[i], kff_types$allele)]))
}
}
## Permutate those codes
if(length(codes) == 0){
## Kff found no results, falling back on the original allele calling method
allele1 <- ifelse(poss_genos$X1 %in% lookitup$string, (lookitup[match(poss_genos$X1, lookitup$string), 3]),"new")
allele2 <- ifelse(poss_genos$X2 %in% lookitup$string, (lookitup[match(poss_genos$X2, lookitup$string), 3]),"new")
poss_genos <- data.frame(cbind(as.character(allele1),as.character(allele2)), stringsAsFactors = FALSE)
error.message <- paste0("\n\nERROR: COULD NOT FIND ADEQUATE KFF MATCHES FOR ", sample, " at ", current.locus, ". FALLING BACK ON NON-KFF ALLELE CALLING.!!\n\n")
cat(error.message)
error.log(error.message)
return(poss_genos)
}else if(length(codes) == 1){
code_frame <- data.frame(cbind(codes[1], codes[1]))
}else{
code_frame <- permutator(codes)
}
## Add the codes to poss_genos
frame_length <- length(code_frame$X1)*length(poss_genos$X1)
new_genos <- data.frame(matrix(nrow = frame_length, ncol = 2))
for(j in 0:(length(poss_genos$X1) - 1)){
for(k in 1:length(code_frame$X1)){
new_genos[j*length(code_frame$X1) + k, 1] <- paste0(poss_genos[j + 1, 1], code_frame[k, 1])
new_genos[j*length(code_frame$X1) + k, 2] <- paste0(poss_genos[j + 1, 2], code_frame[k, 2])
}
}
poss_genos <- new_genos
## Mutating the lookitup table
for(i in 1:length(kff_legend$allele)){
lookitup[grep(kff_legend[i, "allele"], rownames(lookitup)), "string"] <- paste0(lookitup[grep(kff_legend[i, "allele"], rownames(lookitup)), "string"], as.character(kff_legend[i, "code"]))
}
## Running allele calling again with the new codes
allele1 <- ifelse(poss_genos$X1 %in% lookitup$string, (lookitup[match(poss_genos$X1, lookitup$string), 3]),"new")
allele2 <- ifelse(poss_genos$X2 %in% lookitup$string, (lookitup[match(poss_genos$X2, lookitup$string), 3]),"new")
poss_genos <- data.frame(cbind(as.character(allele1),as.character(allele2)), stringsAsFactors=FALSE)
return(poss_genos)
}
# Call genotypes from VCF data frame
allele_call.vcf <- function(x, sample){
if(length(x[,1]) == 383 && current.locus == "2DL23"){
# Generating position information for the current locus
SOS_locus_lookup <<- snps_gen.vcf("2DL2")
positions <<- gsub("X", "", names(SOS_locus_lookup)[-1])
}
KIR_sample_snps <- emformat.vcf(x)
if(is.null(KIR_sample_snps)){
return(NULL)
}
reads_pos <- paste0("X", KIR_sample_snps$position)
hmat <- as.matrix(rbind(KIR_sample_snps$snp1call,KIR_sample_snps$snp2call))
poss_haps <- haplo.enum(hmat, T, reads_pos)
poss_genos <- data.frame(cbind(apply(poss_haps$h1, MARGIN=1, paste, collapse=""), apply(poss_haps$h2, MARGIN=1, paste, collapse="")))
poss_genos$X1 <- as.character(poss_genos$X1)
poss_genos$X2 <- as.character(poss_genos$X2)
##get right loookup table based on which snps we have calls for in VCF file
SOS_locus_lookup_reads<-SOS_locus_lookup[,c("allele", reads_pos)]
lookitup <- data.frame(cbind(apply(SOS_locus_lookup_reads[,-1], MARGIN=1, paste, collapse=""), as.character(SOS_locus_lookup$allele)))
names(lookitup) <- c("string", "allele")
lookitup$allele <- as.character(lookitup$allele)
lookitup$string <- as.character(lookitup$string)
##find allelic ambiguities in current lookup table
all_amb <- c(1:length(lookitup))
for(i in seq_along(lookitup$string)) {
l <- str_detect(lookitup$string,lookitup$string[i])
ll <- lookitup$allele[l]
all_amb[i] <- paste(ll, collapse="/")
}
lookitup <- cbind(lookitup,as.character(all_amb), stringsAsFactors=FALSE)
names(lookitup) <- c("string","allele","amb")
## Mutating the lookup table to accomodate kff results
if("2DL4" == current.locus){
poss_genos <- kff_integrator(sample, current.locus, lookitup, poss_genos)
}else if("2DS4" == current.locus){
kff_results <- ping.kff(sample, current.locus, "Resources/caller_resources/KFF_2DS4.txt", 10)
###alle calling
allele1 <- ifelse(poss_genos$X1 %in% lookitup$string, (lookitup[match(poss_genos$X1, lookitup$string), 3]),"new")
allele2 <- ifelse(poss_genos$X2 %in% lookitup$string, (lookitup[match(poss_genos$X2, lookitup$string), 3]),"new")
poss_genos <- data.frame(cbind(as.character(allele1),as.character(allele2)), stringsAsFactors=FALSE)
poss_genos <- poss_genos[!poss_genos$X1 == "new",]
poss_genos <- poss_genos[!poss_genos$X2 == "new",]
## Finding kff positive allele names
kff_positive <- colnames(kff_results)[kff_results == 1]
## Mutating allele names to match poss_genos names
kff_positive <- gsub(current.locus, paste0("KIR", current.locus, "_"), kff_positive)
## Check for del variant
kff_del <- "KIR2DS4_del" %in% kff_positive
if(kff_del){
kff_positive <- kff_positive[kff_positive != "KIR2DS4_del"]
if(!length(grep("del", kff_positive)) > 0){
error.string <- paste0("\n\nERROR: Positive KFF del variant hit for ", sample, " at ", current.locus, ", but no del allele found.\n\n")
cat(error.string)
error.log(error.string)
}
}
replacement_string <- "KIR2DS4_00101/KIR2DS4_00102/KIR2DS4_00103/KIR2DS4_003/KIR2DS4_006/KIR2DS4_009"
if(length(kff_positive) == 0){
error.string <- paste0("\n\nERROR: Copy number of 1 detected, but no kff matches found for ", sample, " at ", current.locus, "\n\n")
cat(error.string)
error.log(error.string)
}else if(length(grep("1", copy_number)) > 0){
if(length(grep(replacement_string, poss_genos$X1)) > 0){
poss_genos$X1 <- gsub(replacement_string, kff_positive, poss_genos$X1)
poss_genos$X2 <- gsub(replacement_string, kff_positive, poss_genos$X2)
}
}else if(length(grep("2", copy_number)) > 0){
if(length(grep(replacement_string, poss_genos$X1)) > 0 || length(grep(replacement_string, poss_genos$X2)) > 0){
if(length(kff_positive) == 1){
poss_genos$X1 <- gsub(replacement_string, kff_positive, poss_genos$X1)
poss_genos$X2 <- gsub(replacement_string, kff_positive, poss_genos$X2)
}else if(length(kff_positive) == 2){
poss_genos$X1 <- gsub(replacement_string, kff_positive[1], poss_genos$X1)
poss_genos$X2 <- gsub(replacement_string, kff_positive[2], poss_genos$X2)
}else{
error.string <- paste0("\n\nERROR: Copy number of 2 detected, but KFF hits do not match for ", sample, " at ", current.locus, "\n\n")
cat(error.string)
error.log(error.string)
}
}
}else{
error.string <- paste0("\n\nERROR: Copy number > 2 detected, please perform KFF refinement by hand for ", sample, " at ", current.locus, "\n\n")
cat(error.string)
error.log(error.string)
}
}else if("3DL1" == current.locus || "3DS1" == current.locus){
kff_results <- ping.kff(sample, current.locus, "Resources/caller_resources/KFF_3DL1.txt", 10)
###alle calling
allele1 <- ifelse(poss_genos$X1 %in% lookitup$string, (lookitup[match(poss_genos$X1, lookitup$string), 3]),"new")
allele2 <- ifelse(poss_genos$X2 %in% lookitup$string, (lookitup[match(poss_genos$X2, lookitup$string), 3]),"new")
poss_genos <- data.frame(cbind(as.character(allele1),as.character(allele2)), stringsAsFactors=FALSE)
poss_genos <- poss_genos[!poss_genos$X1 == "new",]
poss_genos <- poss_genos[!poss_genos$X2 == "new",]
kff_legend <- read.delim("Resources/caller_resources/KIR_3DL1S1_kff_legend.txt", header = F, fill = T)
kff_positive <- colnames(kff_results[which(kff_results[1,] == 1)])
if(length(kff_positive) == 0){
genos <- poss_genos
return(genos)
}
legend_rows <- grep(paste0(kff_positive, collapse = "|"), kff_legend[,1])
legend_antirows <- grep(paste0(kff_positive, collapse = "|"), kff_legend[,1], invert = T)
kff_poss_genos <- kff_legend[legend_rows,]
if(length(unlist(poss_genos)) == 0){
kff_poss_genos <- kff_poss_genos[,2:length(kff_poss_genos)]
kff.string <- paste0(kff_poss_genos[!kff_poss_genos[,1:length(kff_poss_genos)] == ""], collapse = ", ")
error.string <- paste0("\n\nERROR: KFF probe matches found, but no 3DL1/S1 genotype called for sample: ", sample, ". KFF probes matched for ", kff.string)
cat(error.string)
error.log(error.string)
}else if(length(legend_antirows) > 0){
kff_anti_genos <- kff_legend[legend_antirows,]
kff_anti_genos <- kff_anti_genos[,2:length(kff_anti_genos)]
if(any(unlist(poss_genos) %in% kff_anti_genos[kff_anti_genos[,1:length(kff_anti_genos)] != ""])){
error.string <- paste0("\n\nERROR: 3DL1/S1 genotype called for alleles not found by KFF probes for sample: ", sample)
cat(error.string)
error.log(error.string)
}
}
}else{
###alle calling
allele1 <- ifelse(poss_genos$X1 %in% lookitup$string, (lookitup[match(poss_genos$X1, lookitup$string), 3]),"new")
allele2 <- ifelse(poss_genos$X2 %in% lookitup$string, (lookitup[match(poss_genos$X2, lookitup$string), 3]),"new")
poss_genos <- data.frame(cbind(as.character(allele1),as.character(allele2)), stringsAsFactors=FALSE)
poss_genos <- poss_genos[!poss_genos$X1 == "new",]
poss_genos <- poss_genos[!poss_genos$X2 == "new",]
}
## If copy number is one, poss_genos exists, and X1 and X2 are equal, change X2 to a null allele
if( copy_number == 1 && length(poss_genos[,1]) !=0 && poss_genos$X1 == poss_genos$X2 && current.locus != "2DL23"){
poss_genos$X2 <- paste0("KIR", current.locus, "_null")
}
if(length(x[,1]) == 383 && current.locus == "2DL23"){
# Generating position information for the current locus
SOS_locus_lookup <<- snps_gen.vcf(current.locus)
positions <<- gsub("X", "", names(SOS_locus_lookup)[-1])
}
genos <- poss_genos
genos
}
# Call possible new snps from VCF data frame
new_snps_call.vcf <- function(x){
vcf_file <- data.frame(x)
vcf_file[,10] <- gsub("0/0", "0", vcf_file[,10]) ### This is to convert between old and new samtools vcf format
vcf_file <- vcf_file[grep("./.", vcf_file[,10], fixed = T, invert = T),]
vcf_file <- vcf_file[grep("DP4=", vcf_file[,8]),]
genotype <- sapply(strsplit(as.character(vcf_file[,10]), ":"), "[", 1)
depth <- sapply(strsplit(as.character(vcf_file[,8]), ";"), "[", 1)
# A little check to make sure we are actually getting the depth
if(!isTRUE(length(grep("DP=", depth)) > 0)) {
stop("Bad VCF format, DP is not where expected.")
}
depth <- as.numeric(gsub("DP=", "", depth))
for_rev <- unlist(strsplit(as.character(vcf_file[,8]), ";"))
for_rev <- for_rev[grep("DP4=", for_rev)]
fw <- as.numeric(sapply(strsplit(as.character(for_rev), ","), "[", 3))
rev <- as.numeric(sapply(strsplit(as.character(for_rev), ","), "[", 4))
fw[is.na(fw)] <- 0
rev[is.na(rev)] <- 0
fw <- ifelse(fw > 3, 1, 0)
rev <- ifelse(rev > 3, 1, 0)
fwrev <- fw + rev
KIR_sample <- data.frame(cbind(as.character(vcf_file[,2]), as.character(vcf_file[,4]), as.character(vcf_file[,5]), genotype, as.character(depth), fwrev), stringsAsFactors = FALSE)