-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.R
executable file
·1203 lines (1062 loc) · 58.5 KB
/
helpers.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
#initialize table for "disambiguating" sequences
ambig_col <- rep(c("S","W","R","Y","K","M"),each = 2)
ref_col <- c("G","C","A","T","A","G","C","T","G","T","A","C")
res_col <- c("C","G","T","A","G","A","T","C","T","G","C","A")
ambig_dt <- data.table(ambig = ambig_col,ref = ref_col,res = res_col)
setkey(ambig_dt,ambig,ref)
annotate_calls <- function(calls,intens,intens_rev,glassed_cod){
#contains codons table
if(gsub(".glassed.codons.rdata","",gsub("data/refs/","",glassed_cod))=="-"){
calls[,`:=`(codon=NA,ord_in_cod=NA,coding_seq=NA,aa_ref=NA)]
}else{
load(glassed_cod)
calls[,gen_coord := ceiling(gen_coord)]
calls <- merge(x = calls, y = cod_table[,list(gen_coord,codon,ord_in_cod,coding_seq,aa_ref=AA)], by = "gen_coord", all.x = TRUE)
calls[aa_ref != "",aa_ref:=my_aaa(toupper(aa_ref))]
#calls[aa_ref=="Stp",aa_ref:='*']
cod_table <<- cod_table
}
calls[,c("aa_sample","aa_mut"):=aa_ref]
#reorder columns so that id is first (so that the checkbox from the shiny data table selects the correct value and the delete button knows what to delete)
if(colnames(calls)[1]!="id"){
setcolorder(calls,c("id",colnames(calls)[-2]))
}
#calculate the noise levels
calls[,noise_abs_fwd:=noise(iA_fwd,iC_fwd,iG_fwd,iT_fwd,TRUE),by=1:nrow(calls)]
# calls[,noise_rel_fwd:=noise(iA_fwd,iC_fwd,iG_fwd,iT_fwd,FALSE),by=1:nrow(calls)]
calls[,roll_noise_abs_mean_ratio_fwd := rollapply(calls$noise_abs_fwd, 11, function(x) (mean(x[1:5])+0)/(mean(x[7:11])+0), fill = "1")]
# calls[,roll_noise_rel_mean_ratio_fwd := rollapply(calls$noise_rel_fwd, 11, function(x) (mean(x[1:5])+1)/(mean(x[7:11])+1), fill = "1")]
if("call_rev" %in% colnames(calls)){
calls[,noise_abs_rev:=noise(iA_rev,iC_rev,iG_rev,iT_rev,TRUE),by=1:nrow(calls)]
# calls[,noise_rel_rev:=noise(iA_rev,iC_rev,iG_rev,iT_rev,FALSE),by=1:nrow(calls)]
calls[,roll_noise_abs_mean_ratio_rev := rollapply(calls$noise_abs_rev, 11, function(x) (mean(x[1:5])+0)/(mean(x[7:11])+0), fill = "1")]
# calls[,roll_noise_rel_mean_ratio_rev := rollapply(calls$noise_rel_rev, 11, function(x) (mean(x[1:5])+1)/(mean(x[7:11])+1), fill = "1")]
}
# #precalculate neighbourhood (absolute,relative)x(forward,reverse)
# nbrhd_a_f <- rollmean(calls$noise_abs_fwd,k=7)
# nbrhd_r_f <- rollmean(calls$noise_rel_fwd,k=7)
# if("call_rev" %in% colnames(calls)){
# nbrhd_a_r <- rollmean(calls$noise_abs_rev,k=7)
# nbrhd_r_r <- rollmean(calls$noise_rel_rev,k=7)
# }
#
# calls[,rm7noise_abs_fwd := c(rep(nbrhd_a_f[1],3),nbrhd_a_f,rep(nbrhd_a_f[length(nbrhd_a_f)],3))]
# calls[,rm7noise_rel_fwd := c(rep(nbrhd_r_f[1],3),nbrhd_r_f,rep(nbrhd_r_f[length(nbrhd_r_f)],3))]
# if("call_rev" %in% colnames(calls)){
# calls[,rm7noise_abs_rev := c(rep(nbrhd_a_r[1],3),nbrhd_a_r,rep(nbrhd_a_r[length(nbrhd_a_r)],3))]
# calls[,rm7noise_rel_rev := c(rep(nbrhd_r_r[1],3),nbrhd_r_r,rep(nbrhd_r_r[length(nbrhd_r_r)],3))]
# }
#ref peak = pseudo trace = sum of intensities
calls[,ref_peak_abs_fwd:=sum(iA_fwd,iC_fwd,iG_fwd,iT_fwd),by=1:nrow(calls)]
if("call_rev" %in% colnames(calls)) calls[,ref_peak_abs_rev:=sum(iA_rev,iC_rev,iG_rev,iT_rev),by=1:nrow(calls)]
#add information about the first and second highest peak
calls[,c("sample_peak_base_fwd","sample_peak_abs_fwd") := i_wo_p(1,iA_fwd,iC_fwd,iG_fwd,iT_fwd),by=1:nrow(calls)]
calls[,sample_peak_pct_fwd := ((100/ref_peak_abs_fwd)*sample_peak_abs_fwd)]
calls[,c("mut_peak_base_fwd","mut_peak_abs_fwd") := i_wo_p(2,iA_fwd,iC_fwd,iG_fwd,iT_fwd),by=1:nrow(calls)]
calls[,mut_peak_pct_fwd := ((100/ref_peak_abs_fwd)*mut_peak_abs_fwd)]
calls[,mut_s2n_abs_fwd:=mut_peak_abs_fwd/noise_abs_fwd]
calls[,mut_call_fwd:=call]
if("call_rev" %in% colnames(calls)){
calls[,c("sample_peak_base_rev","sample_peak_abs_rev") := i_wo_p(1,iA_rev,iC_rev,iG_rev,iT_rev),by=1:nrow(calls)]
calls[,sample_peak_pct_rev := ((100/ref_peak_abs_rev)*sample_peak_abs_rev)]
calls[,c("mut_peak_base_rev","mut_peak_abs_rev") := i_wo_p(2,iA_rev,iC_rev,iG_rev,iT_rev),by=1:nrow(calls)]
calls[,mut_peak_pct_rev := ((100/ref_peak_abs_rev)*mut_peak_abs_rev)]
calls[,mut_s2n_abs_rev:=mut_peak_abs_rev/noise_abs_rev]
calls[,mut_call_rev:=call_rev]
suppressWarnings(calls[,sample_peak_pct := max(c(sample_peak_pct_fwd,sample_peak_pct_rev),na.rm=TRUE),by=1:nrow(calls)])
calls[,mut_peak_pct := mean(c(mut_peak_pct_fwd,mut_peak_pct_rev),na.rm=TRUE),by=1:nrow(calls)]
} else {
calls[,sample_peak_pct := sample_peak_pct_fwd]
calls[,mut_peak_pct := mut_peak_pct_fwd]
}
calls[,set_by_user:=FALSE]
#disambiguate
calls[,mut_call_fwd := ambig_min(mut_call_fwd, reference)]
calls[,call := ambig_min(mut_call_fwd, call)]
calls[!(user_sample %in% c('A','C','G','T')), user_sample:=call]
if("call_rev" %in% colnames(calls)){
calls[,mut_call_rev := ambig_min(mut_call_rev, reference)]
calls[,call_rev := ambig_min(mut_call_rev, call_rev)]
calls[!(user_sample %in% c('A','C','G','T')) & quality_fwd < quality_rev,user_sample:=call_rev]
}
calls <- adjust_ref_mut(calls,intens_rev)
calls[,user_sample_orig:=user_sample]
# calls[set_by_user == FALSE, user_sample_orig := ambig_min(user_sample,reference)]
return(calls)
}
get_noisy_neighbors <- function(calls){
if("call_rev" %in% colnames(calls)){
noisy_neighbors <- calls[trace_peak != "NA" & !is.na(gen_coord) & call != "-" & call_rev != "-"
& roll_noise_abs_mean_ratio_fwd > 0 & roll_noise_abs_mean_ratio_fwd < 10 & roll_noise_abs_mean_ratio_rev > 0 & roll_noise_abs_mean_ratio_rev < 10
& roll_noise_abs_mean_ratio_fwd / roll_noise_abs_mean_ratio_rev >= 5
]
} else {
noisy_neighbors <- calls[trace_peak != "NA" & !is.na(gen_coord) & call != "-"
& roll_noise_abs_mean_ratio_fwd > 0 & roll_noise_abs_mean_ratio_fwd < 10
& roll_noise_abs_mean_ratio_fwd >= 2
]
}
setkey(noisy_neighbors,id)
return(noisy_neighbors)
}
splice_variants <- function(intrexdat){
intrexdat$intrex$splicevar <- mapply(function(x,y) if (x == 'intron9' & abs(133 - y) <= 1) { '|beta variant' } else { '' }, intrexdat$intrex$attr, intrexdat$intrex$length)
return(intrexdat)
}
include_locked_indels <- function(calls,vec,indels,fwd){
vec <- copy(vec)
get_del_positions <- function(code,pos,vec){
coord1 <- as.numeric(gsub("c\\.(\\d*).*","\\1",code))
coord2 <- suppressWarnings(as.numeric(gsub("c\\.\\d*_(\\d*).*","\\1",code)))
if(is.na(coord2)) del_len <- 0
else del_len <- coord2 - coord1
if(vec[pos + 1] == "-") pos <- pos + 1
return(0:del_len + pos)
}
get_ins_positions <- function(code,pos,vec){
if(length(grep("nt",code)) > 0) ins_len <- as.numeric(gsub(".*nt(\\d*)","\\1",code))
else ins_len <- nchar(gsub(".*[ins|dup](.*)","\\1",code))
if(all(calls$reference[pos] == "-")) pos <- pos - 1
return(1:ins_len + floor(pos))
}
dels <- lapply(names(indels)[grep("del",names(indels))],function(x) get_del_positions(x,indels[[x]],vec))
if(length(dels) > 0){
sec_dels <- dels[which(sapply(dels,function(x) all(vec[x] != "-")))]
prim_dels <- setdiff(dels,sec_dels)
} else{
sec_dels <- list()
prim_dels <- list()
}
ins <- lapply(names(indels)[grep("ins|dup",names(indels))],function(x) get_ins_positions(x,indels[[x]],vec))
if(length(ins) > 0){
sec_ins <- ins[which(sapply(ins,function(x) all(calls$reference[x] != "-")))]
prim_ins <- setdiff(ins,sec_ins)
} else{
sec_ins <- list()
prim_ins <- list()
}
move_vec <- numeric(length(vec))
if(fwd){
if(length(sec_dels) > 0) move_vec[sapply(sec_dels,function(x) max(x) + 1)] <- - sapply(sec_dels,length)
if(length(prim_dels) > 0) move_vec[sapply(prim_dels,min)] <- sapply(prim_dels,length)
if(length(sec_ins) > 0) move_vec[sapply(sec_ins,min)] <- sapply(sec_ins,length)
if(length(prim_ins) > 0) move_vec[sapply(prim_ins,function(x) max(x) + 1)] <- -sapply(prim_ins,length)
move_vec <- cumsum(move_vec)
} else {
if(length(sec_dels) > 0) move_vec[sapply(sec_dels,function(x) min(x) - 1)] <- sapply(sec_dels,length)
if(length(prim_dels) > 0) move_vec[sapply(prim_dels,max)] <- -sapply(prim_dels,length)
if(length(sec_ins) > 0)move_vec[sapply(sec_ins,max)] <- -sapply(sec_ins,length)
if(length(prim_ins) > 0) move_vec[sapply(prim_ins,function(x) min(x) - 1)] <- sapply(prim_ins,length)
move_vec <- rev(cumsum(rev(move_vec)))
}
new_vec <- rep("-",length(vec))
vec[unlist(prim_dels)] <- calls$reference[unlist(prim_dels)]
pos_vec <- seq_along(new_vec) + move_vec
pos_vec[pos_vec < 1] <- 1
new_vec[pos_vec] <- vec
new_vec <- new_vec[1:length(vec)]
new_vec[unlist(prim_dels)] <- "-"
if(fwd) new_vec[unlist(sec_ins)] <- calls$mut_peak_base_fwd[unlist(sec_ins)]
else new_vec[unlist(sec_ins)] <- calls$mut_peak_base_rev[unlist(sec_ins)]
# if(length(het_dels) > 0){
# vec <- vec[-het_dels]
# if(fwd) {
# vec <- c(vec,rep("-",length(het_dels)))
# } else {
# vec <- c(rep("-",length(het_dels)),vec)
# }
# }
#
# prim_dels <- setdiff(dels,het_dels)
# if(length(prim_dels) > 0){
# vec[prim_dels] <- g_calls$reference[prim_dels]
# new_vec <- rep("-",length(vec))
# if(fwd) {
# vec <- vec[1:min(length(vec),length(new_vec) - length(prim_dels))]
# new_vec[setdiff(seq_along(new_vec),prim_dels)] <- vec
# } else {
# vec <- vec[1 + length(vec) - min(length(vec),length(new_vec) - length(prim_dels)):1]
# new_vec[setdiff(seq_along(new_vec),prim_dels)] <- vec
# }
# vec <- new_vec
# }
return(new_vec)
}
call_variants <- function(calls, qual_thres, mut_min, s2n_min,stored_het_indels,brush_fwd,brush_rev,incorp,single_rev){
if('het_mut_call_fwd' %in% colnames(calls)){
calls[,het_mut_call_fwd := NULL]
}
if('het_mut_call_rev' %in% colnames(calls)){
calls[,het_mut_call_rev := NULL]
}
# reset all but set_by_user
calls[set_by_user == FALSE, user_sample := user_sample_orig]
calls[set_by_user == FALSE, user_mut := user_sample_orig]
calls[set_by_user == FALSE, mut_call_fwd := call]
if(length(grep("del|ins|dup",names(stored_het_indels))) > 0){
#g_indels_present <<- TRUE
calls[, mut_call_fwd := include_locked_indels(calls,mut_call_fwd,stored_het_indels,fwd = T)]
}else#{
# g_indels_present <<- FALSE
#}
# calls[set_by_user == FALSE, mut_call_fwd := ambig_minus(call,reference),by=1:nrow(calls[set_by_user==FALSE,])]
# mut
if("call_rev" %in% colnames(calls)) {
# reset all but set_by_user
calls[set_by_user == FALSE, mut_call_rev := call_rev]
if(length(grep("del|ins|dup",names(stored_het_indels))) > 0){
calls[, mut_call_rev := include_locked_indels(mut_call_rev,stored_het_indels,fwd = F)]
}
# calls[set_by_user == FALSE, mut_call_rev := ambig_minus(call_rev,reference),by=1:nrow(calls[set_by_user==FALSE,])]
# initialising mut calls
calls[
mut_peak_pct_fwd >= mut_min
& mut_s2n_abs_fwd >= s2n_min
#& quality_fwd >= qual_thres
, mut_call_fwd := mut_peak_base_fwd
]
#calls[set_by_user == FALSE, mut_call_fwd := ambig_min(mut_call_fwd,reference)]
calls[
mut_peak_pct_rev >= mut_min
& mut_s2n_abs_rev >= s2n_min
#& quality_rev >= qual_thres
, mut_call_rev := mut_peak_base_rev
]
#calls[set_by_user == FALSE, mut_call_rev := ambig_min(mut_call_rev,reference)]
# calls[
# set_by_user == FALSE
# #& mut_call_fwd != call
# , c("user_mut","mut_peak_pct") := list(mut_call_fwd,mut_peak_pct_fwd)
# ]
# setting user muts based on reference and quality
calls[
mut_call_fwd!=reference
& mut_call_rev==reference
& quality_fwd > qual_thres
& set_by_user == FALSE
, c("user_mut","mut_peak_pct") := list(mut_call_fwd,mut_peak_pct_fwd)
]
calls[
mut_call_fwd==reference
& mut_call_rev!=reference
& quality_rev > qual_thres
& set_by_user == FALSE
, c("user_mut","mut_peak_pct") := list(mut_call_rev,mut_peak_pct_rev)
]
calls[
mut_call_fwd!=reference
& mut_call_rev!=reference
& set_by_user == FALSE
# & mut_call_rev != call_rev
, c("user_mut","mut_peak_pct") := list(mut_call_fwd,mut_peak_pct_fwd)
]
calls[
mut_call_fwd!=reference
& mut_call_rev!=reference
& quality_rev > quality_fwd
& set_by_user == FALSE
# & mut_call_rev != call_rev
, c("user_mut","mut_peak_pct") := list(mut_call_rev,mut_peak_pct_rev)
]
} else { #only FWD
calls[
mut_peak_pct_fwd >= mut_min
& mut_s2n_abs_fwd >= s2n_min
& mut_peak_base_fwd != reference
, mut_call_fwd := mut_peak_base_fwd
]
rows <- 1:nrow(calls[set_by_user==FALSE,])
#calls[set_by_user == FALSE, mut_call_fwd := ambig_min(mut_call_fwd,reference)]
calls[
set_by_user == FALSE
& mut_call_fwd != call
, c("user_mut","mut_peak_pct") := list(mut_call_fwd,mut_peak_pct_fwd)
]
}
# masking low quality
calls[quality < qual_thres & set_by_user == FALSE, c("user_sample","user_mut") := "N"]
return(calls)
}
complement <- function(base){
return (chartr("ATGCRYKMBVDH","TACGYRMKVBHD",base))
}
ambig_min <- function(ambig,ref){
ambig <- toupper(ambig)
ref <- toupper(ref)
search <- list(ambig,ref)
ret <- ambig_dt[search]
ret[is.na(res),res := ambig]
ret$res
}
retranslate <- function(calls){
# USER SAMPLE
coding <- calls[ord_in_cod>0 & !is.na(codon) & codon != 'intron',list(as.numeric(coding_seq),codon,ord_in_cod,user_sample,reference)]
setnames(coding,"V1","coding_seq")
push = 0
#get missing bases for the first frame if incomplete
if(is.na(coding[1,ord_in_cod])){
return(calls)
}
while(coding[1,ord_in_cod]!=1){
coding<-rbind(cod_table[coding_seq==(as.numeric(coding[1,coding_seq])-1),list(coding_seq=as.numeric(coding_seq),codon,ord_in_cod,user_sample=seq,reference=seq)],coding)
#setkey(coding,coding_seq)
push = push +1
}
#get missing bases for the last frame if incomplete
while(coding[nrow(coding),ord_in_cod] != 3){
coding<-rbind(coding,cod_table[coding_seq==(as.numeric(coding[nrow(coding),coding_seq])+1),list(coding_seq=as.numeric(coding_seq),codon,ord_in_cod,user_sample=seq,reference=seq)])
#setkey(coding,coding_seq)
}
#231017
#coding[,user_sample:=ambig_min(ambig=user_sample,ref=reference)]
trans <- seqinr::translate(coding[user_sample != '-',user_sample],frame = (coding[1,ord_in_cod]-1), NAstring = "X", ambiguous = F)
#Shift annotation of codons by '-'s
ord_sample<-rep(c(1,2,3),length(trans))
suppressWarnings(trans_sample <- my_aaa(trans))
#! # calls[ord_in_cod>0,aa_sample := rep(trans,each=3)[(1+push):(length(aa_sample)+push)]]
# USER MUT
coding <- calls[ord_in_cod>0 & !is.na(codon) & codon != 'intron',list(as.numeric(coding_seq),codon,ord_in_cod,user_mut,reference)]
setnames(coding,"V1","coding_seq")
push = 0
while(coding[1,ord_in_cod]!=1){
coding<-rbind(cod_table[coding_seq==(as.numeric(coding[1,coding_seq])-1),list(coding_seq=as.numeric(coding_seq),codon,ord_in_cod,user_mut=seq,reference=seq)],coding)
#setkey(coding,coding_seq)
push = push +1
}
#!infinite loop
while(coding[nrow(coding),ord_in_cod] < 3){
coding<-rbind(coding,cod_table[coding_seq==(as.numeric(coding[nrow(coding),coding_seq])+1),list(coding_seq=as.numeric(coding_seq),codon,ord_in_cod,user_mut=seq,reference=seq)])
#setkey(coding,coding_seq)
}
#231027
#coding[,user_mut:=ambig_min(ambig=user_mut,ref=reference)]
#! # ord<-rep(c(1,2,3),length(trans))
trans <- seqinr::translate(coding[user_mut != '-',user_mut],frame = (coding[1,ord_in_cod]-1), NAstring = "X", ambiguous = F)
ord_mut<-rep(c(1,2,3),length(trans))
suppressWarnings(trans_mut <- my_aaa(trans))
#create a string as long as trans rep(123),add them to ord in cod where user_mut != "-"s
calls[ord_in_cod>0 & user_sample == "-", sample_ord_in_cod := 0 ]
calls[ord_in_cod>0 & user_mut == "-", mut_ord_in_cod := 0 ]
calls[ord_in_cod>0 & user_sample == "-", aa_sample := "-"]
calls[ord_in_cod>0 & user_mut == "-", aa_mut := "-"]
calls[ord_in_cod>0 & user_sample != "-", sample_ord_in_cod := ord_sample[(1+push):(length(aa_sample)+push)]]
calls[ord_in_cod>0 & user_mut != "-", mut_ord_in_cod := ord_mut[(1+push):(length(aa_mut) +push)]]
calls[sample_ord_in_cod>0 & user_sample != "-", aa_sample := rep(trans_sample,each=3)[(1+push):(length(aa_sample)+push)]]
calls[mut_ord_in_cod>0 & user_mut != "-", aa_mut := rep(trans_mut,each=3)[(1+push):(length(aa_mut) +push)]]
# if(!is.na(g_hetero_del_tab[1])) dels <- as.vector(unlist(apply(g_hetero_del_tab,1,function(x) x[1]:x[2])))
# else dels <- numeric()
# if(!is.na(g_hetero_ins_tab[1])) ins <- as.vector(unlist(apply(g_hetero_ins_tab,1,function(x) x[1]:x[2])))
# else ins <- numeric()
# if(max(length(dels),length(ins)) != 0){
# calls[,aa_mut := incorporate_single_vec(calls[["aa_mut"]],ins,dels,"char",T)]
# }
return(calls)
}
get_choices <- function(calls,ref){
#hoices <- calls[user_sample != "N" & (user_sample != reference | user_mut != reference) & trace_peak != "NA" & !is.na(gen_coord)]
choices <- calls[ (user_sample != reference | user_mut != reference) & trace_peak != "NA" & !is.na(gen_coord)]
if(gsub(".glassed.intrex.fasta","",gsub("data/refs/","",ref))=="-" & nrow(choices)==0){
if("call_rev" %in% colnames(calls)){
choices <- calls[call != call_rev]
}
}
if (nrow(choices) > 0) {
choices[,strand:= 0]
if("call_rev" %in% names(choices)){
if('het_mut_call_fwd'%in%colnames(calls)){
choices[(call != reference) | (het_mut_call_fwd!= reference), strand:=strand+1 ]
choices[(call_rev != reference) | (het_mut_call_rev!= reference), strand:=strand+2 ]
}else{
choices[(call != reference) | (mut_call_fwd!= reference), strand:=strand+1 ]
choices[(call_rev != reference) | (mut_call_rev!= reference), strand:=strand+2 ]
}
}else{
choices[,strand:=strand+3]
}
choices[(user_sample == "-") | (user_mut == "-"),strand:=strand+4]
#choices <- choices[,`:=` (user_sample=ambig_minus(user_sample,reference),user_mut=ambig_minus(user_mut,reference)),by=1:nrow(choices)]
choices[,ids:=NA,by=1:nrow(choices)]
#231017
#choices[,user_sample:=ambig_min(user_sample,reference)]
#choices[,user_mut:=ambig_min(user_mut,reference)]
choices[,sample_peak_pct := mround(sample_peak_pct,1),by=1:nrow(choices)]
choices[,mut_peak_pct := mround(mut_peak_pct,1),by=1:nrow(choices)]
choices[,`:=`(coding = paste0("c.", coding_seq), protein="p.?")]
# 1st variant
# mismatch
choices[user_sample != reference & user_sample != "-" & reference != "-", ':=' (coding = paste0(coding, reference, ">", user_sample), VAF = sample_peak_pct)]#, "(", sample_peak_pct, "%)")]
# ins
choices[user_sample != reference & reference == "-", ':=' (coding = paste0(coding, "ins", user_sample), VAF = sample_peak_pct)]#, "(", sample_peak_pct, "%)")]
# del
choices[user_sample != reference & user_sample == "-", ':=' (coding = paste0(coding, "del", reference), VAF = sample_peak_pct)]#, "(", sample_peak_pct, "%)")]
# protein
choices[aa_sample != aa_ref, protein:= paste0("p.", aa_ref, codon, aa_sample)]#, "(", sample_peak_pct, "%)")]
choices[aa_sample == aa_ref, protein:= "p.(=)"]
choices[codon == 'intron', protein:= "p.?"]
# 2nd variant
# mismatch without 1st variant
choices[user_mut != reference & user_sample == reference & user_mut != "-" & reference != "-", ':=' (coding = paste0(coding, reference, ">", user_mut), VAF = mut_peak_pct)]#, "(", mut_peak_pct, "%)")]
# mismatch with 1st variant
choices[user_mut != reference & user_sample != reference & user_mut != user_sample & user_mut != "-" & reference != "-", ':=' (coding = paste0(coding, ">", user_mut), VAF = mut_peak_pct)]#, "(", mut_peak_pct, "%)")]
# ins
choices[user_mut != reference & user_mut != user_sample & reference == "-" & reference == user_sample, ':='(coding = paste0(coding, "ins", user_mut), VAF = NA)]#, "(", mut_peak_pct, "%)")]
# del
choices[user_mut != reference & user_mut != user_sample & user_mut == "-" & reference == user_sample, ':='(coding = paste0(coding, "del", reference), VAF = NA)]#, "(", mut_peak_pct, "%)")]
# protein without 1st variant
choices[aa_mut != aa_ref & aa_sample == aa_ref, protein:= paste0("p.", aa_ref, codon, aa_mut)]#, "(", mut_peak_pct, "%)")]
# protein with 1st variant
choices[aa_mut != aa_ref & aa_sample != aa_ref & aa_sample != aa_mut, protein:= paste0(protein, aa_mut)]#, "(", mut_peak_pct, "%)")]
#choices[aa_mut != aa_ref & aa_sample== aa_ref & aa_mut=="-", protein:= paste0("p.",aa_ref,codon,"fs")]
}
setkey(choices,id)
return(choices)
}
#remove consecutive single base deletions/insertion and replace them with one long del/ins in table
get_view<-function(calls,choices,snps){
compute_consecutives <- function(ids){
ids <- round(ids * 100)
res <- rle(ids - c(Inf,ids[-length(ids)]))
ccc <- cumsum(res$lengths)
ccc[which(res$values != 1 & res$values != 100)] <- 0
res <- rep(ccc,res$lengths)
res2 <- res - c(res[-1],0)
res2[res2 >= 0] <- 0
return(res - res2)
}
squeeze_indels <- function(tab){
get_value <- function(c){
if(grepl('-',c)){
splt <- strsplit(c,'-')[[1]]
value <- as.numeric(splt[1]) - as.numeric(splt[2])
return(value)
}
if(grepl('\\+',c)){
splt <- strsplit(c,'\\+')[[1]]
value <- as.numeric(splt[1]) + as.numeric(splt[2])
return(value)
}
return(as.numeric(c))
}
if(nrow(tab) > 0){
coord <- gsub("c\\.(\\d*[-,\\+]*\\d*).*","\\1",tab$coding)
nucs <- gsub("c\\.\\d*[-,\\+]*\\d*...(.)","\\1",tab$coding)
type <- gsub("c\\.\\d*[-,\\+]*\\d*(...).*","\\1",tab$coding)[1]
vals <- unlist(lapply(coord,get_value))
#condition true if insertion
if(max(tab$gen_coord) == min(tab$gen_coord)) {
gen_coord <- paste0(max(tab$gen_coord) + 1,"_",as.numeric(max(tab$gen_coord)))
}
else gen_coord <- paste0(max(tab$gen_coord),"_",min(tab$gen_coord))
pos_min <- match(min(vals), vals)
pos_max <- match(max(vals), vals)
#condition true for insertion
max_coord <- coord[pos_max]
min_coord <- coord[pos_min]
if(min_coord == max_coord){
#adding + 1 different if intron
if (grepl('\\+',max_coord)){
v <- unlist(strsplit(max_coord,"\\+"))
max_coord <- paste0(v[1],"+",as.numeric(v[2]) + 1)
}
else if( grepl('-',max_coord)){
v <- unlist(strsplit(max_coord,"-"))
max_coord <- paste0(v[1],"-",as.numeric(v[2]) - 1)
}else{
max_coord <- as.numeric(max_coord)+1
}
}
coding <- paste0("c.",min_coord,"_",max_coord,type, paste(nucs,collapse = ""))
#return(list(id = floor(min(tab$id)),gen_coord = gen_coord,coding = coding,set_by_user=tab$set_by_user[1],protein = tab$protein[1],trace_peak=min(tab$trace_peak)))
tab1 = tab[1,]
tab <- tab[!grepl('intron',exon_intron),]
if (nrow(tab) == 0){
tab = tab1
}
return(list(id = min(tab$id),gen_coord = gen_coord,coding = coding,set_by_user=tab$set_by_user[1],protein = tab$protein[1],trace_peak=min(tab$trace_peak)))
} else {
return(tab)
}
}
choices[,consecutives := compute_consecutives(id) ][,mut_type := gsub("c\\.\\d*[-,\\+]*\\d*(...).*","\\1",coding)]
indel_tab <- choices[intersect(grep("del|ins",mut_type),which(consecutives != 0)), squeeze_indels(.SD),by = c("mut_type","consecutives")]
#represent consecutive indels on one line
if(nrow(indel_tab) > 0){
choices <- choices[union(grep("del|ins",mut_type,invert = T),which(consecutives == 0)),]
choices <- rbind(choices,indel_tab,fill=TRUE)
}
#identify frame shifts and inframe indels
for(i in grep("del|ins",choices$mut_type)){
#I only need the "coding" part so remove + - coords in case of indels spanning through intron/exon
seq <- gsub("c\\.\\d*[-,\\+]*\\d*_*\\d*[-,\\+]*\\d*...(.)","\\1",choices[i,]$coding)
if(grepl('-', choices[i,]$coding)){
if (str_count(choices[i,]$coding, '-') == 2){
seq = ""
}else{
prefix <- gsub("c\\.\\d*-(\\d*)_*\\d*.*","\\1",choices[i,]$coding)
seq <- substr(seq, prefix, nchar(seq))
}
}
if(grepl('\\+', choices[i,]$coding)){
if(str_count(choices[i,]$coding, '\\+') == 2){
seq = ""
}else{
suffix <- gsub("c\\.\\d*_*\\d*\\+(\\d*).*","\\1",choices[i,]$coding)
seq <- substr(seq, 1, nchar(seq)-as.numeric(suffix))
}
}
#if(length(seq) > 10,paste0(length(seq),"nt")
if(nchar(seq) == 0){
choices[i,]$protein = "p.?"
}else{
if((str_length(seq) %% 3)!=0){
prot <- gsub("(p\\....\\d*).*","\\1",choices[i]$protein)
aa <- gsub("p\\.(...)\\d*.*","\\1",choices[i]$protein)
cod <- as.numeric(gsub("p\\....(\\d*).*","\\1",choices[i]$protein))
while((calls[codon == cod][1]$aa_ref == calls[codon == cod][1]$aa_mut)&
(calls[codon == cod][1]$aa_ref == calls[codon == cod][1]$aa_sample)&
(!is.na(calls[codon == cod][1]$aa_sample))) {cod = cod +1}
aa <- calls[codon ==cod]$aa_ref[1]
choices[i,]$protein = paste0("p.",aa,cod, "fs")
}else{ #in frame
if(choices[i,]$mut_type == "ins"){
from <- as.numeric(calls[choices[i]$id]$codon)
to <- as.numeric(calls[choices[i]$id]$codon) +1
choices[i,]$protein = paste0("p.",calls[codon==from,][1]$aa_ref,from,"_",
calls[codon==to,][1]$aa_ref,to,choices[i,]$mut_type,
paste(my_aaa(seqinr::translate(strsplit(seq,"")[[1]])),collapse = ""))
}
if(choices[i,]$mut_type=="del"){
from <- as.numeric(calls[choices[i]$id]$codon)
to <- as.numeric(calls[choices[i]$id]$codon) + nchar(seq)/3 -1
#from <- as.numeric(g_calls[choices[i]$id]$codon) - 10
#to <- as.numeric(g_calls[choices[i]$id]$codon) + nchar(seq)/3 + 10
#lapply(g_calls[codon %in% c(from:to) & ord_in_cod == 1]$aa_ref,mya)
choices[i,]$protein = paste0("p.",calls[codon==from,][1]$aa_ref,from,"_",
calls[codon==to,][1]$aa_ref,to,choices[i,]$mut_type)
}
}
}
}
#identify duplications (special kind of insertions)
for(i in grep("ins",choices$mut_type)){
seq <- gsub("c\\.\\d*[-,\\+]*\\d*_*\\d*[-,\\+]*\\d*...(.)","\\1",choices[i,]$coding)
shift <- 0
if(floor(choices[i,]$id) == choices[i,]$id) {
#note sure about this, id number doesn't have to match the order in calls
prev_seq <- paste0(calls[-(nchar(seq) - 1):0 + choices[i,]$id - 1,]$reference,collapse = "")
shift <- 1
}else
prev_seq <- paste0(calls[-(nchar(seq) - 1):0 + choices[i,]$id,]$reference,collapse = "")
if(seq == prev_seq) {
choices[i,coding := gsub("ins","dup",coding)]
#the coordinates are changed to the sequence that is duplicated #! find test for these
if(nchar(seq)>1){
choices[i,]$coding <- paste0("c.",calls[id == floor(choices[i,]$id) - nchar(seq) + 1 - shift]$coding_seq ,"_",calls[id == floor(choices[i,]$id) - shift,]$coding_seq,"dup",seq)
}else{
choices[i,]$coding <- paste0("c.",calls[id == floor(choices[i,]$id) - shift]$coding_seq ,"dup",seq)
}
}else{
if(nchar(seq)==1)
choices[i,]$coding <- paste0("c.",calls[id == ceiling(choices[i]$id - 1),]$coding_seq,"_",calls[id == floor(choices[i]$id + 1),]$coding_seq,"ins",seq)
#choices[i,]$coding <- paste0("c.",calls[i-1,]$coding_seq,"_",calls[i+1,]$coding_seq,'ins',seq)
}
}
setkey(choices,id)
if(!is.null(snps)){
### Position based identification of SNPs
#positionsStr <- unlist(lapply(choices$gen_coord,toString))
#positionsPair <- lapply(strsplit(positionsStr,"_"),function(x){if(is.na(x[2])){c(x[1],x[1])}else{x}})
#rsids<-lapply(positionsPair,function(x){paste(snps[snps$"V2"==x[1]&snps$V3==x[2]]$V8,"",sep="")})
#choices <- cbind(choices,"dbSNP"=unlist(rsids))
#Exact matching for SNPs, probably needs finetuning for indels
getSNP <- getSNP <- function(pos,call,mut){return(snps[snps$V2==pos & snps$V3==pos & (snps$V5==call | snps$V5==mut)]$V8)}
choices <- choices[,dbSNP:=getSNP(gen_coord,user_sample,user_mut),by=1:nrow(choices)]
}
return(choices)
}
mya <- function(x){
if(is.na(x)){return(".")}
else{ if(x == "-"){return("-")}
else{return(a(x))}
}
}
mround <- function(x,base){
base*round(x/base)
}
report_hetero_indels <- function(calls){
rev <- !is.null(calls[["call_rev"]])
if(rev) {
secondary_seq <- gsub("[ -]","",paste(get_consensus_mut(calls[["mut_call_fwd"]],calls[["mut_call_rev"]],calls[,list(iA_fwd,iC_fwd,iG_fwd,iT_fwd,iA_rev,iC_rev,iG_rev,iT_rev)],calls[["user_sample"]]),collapse = ""))
} else secondary_seq <- gsub("[ -]","",paste(calls[["mut_call_fwd"]],collapse = ""))
primary_seq <- gsub("[ -]","",paste(calls[["user_sample"]],collapse = ""))
hetero_indel_aln <- pairwiseAlignment(primary_seq, secondary_seq,type = "overlap",substitutionMatrix = sm,gapOpening = -15, gapExtension = -1)
hetero_ins_tab <- stringi::stri_locate_all_regex(compareStrings(hetero_indel_aln),"[\\-]+")[[1]] + start(pattern(hetero_indel_aln)) - 1
hetero_del_tab <- stringi::stri_locate_all_regex(compareStrings(hetero_indel_aln),"[\\+]+")[[1]] + start(pattern(hetero_indel_aln)) - 1
is.in.primery <- apply(hetero_ins_tab,1,function(x) all(x %in% which(calls[["user_sample"]] == "-")))
if(length(hetero_ins_tab[which(!is.in.primery),2]) > 0){
move_vec <- numeric(nchar(primary_seq))
move_vec[hetero_ins_tab[which(!is.in.primery),2] + 1] <- -(hetero_ins_tab[which(!is.in.primery),2]-hetero_ins_tab[which(!is.in.primery),1])-1
move_vec <- cumsum(move_vec)
hetero_del_tab <- apply(hetero_del_tab,c(1,2),function(x) x + move_vec[x])
hetero_ins_tab <- apply(hetero_ins_tab,c(1,2),function(x) x + move_vec[x])
}
is.in.reference <- apply(hetero_del_tab,1,function(x) all(x %in% which(calls[["reference"]] == "-")))
ins_counts <- sum(hetero_ins_tab[which(!is.in.primery),2]-hetero_ins_tab[which(!is.in.primery),1]+1,na.rm = T) + sum(hetero_del_tab[which(is.in.reference),2]-hetero_del_tab[which(is.in.reference),1]+1,na.rm = T)
del_counts <- sum(hetero_ins_tab[which(is.in.primery),2]-hetero_ins_tab[which(is.in.primery),1]+1,na.rm = T) + sum(hetero_del_tab[which(!is.in.reference),2]-hetero_del_tab[which(!is.in.reference),1]+1,na.rm = T)
# if(nrow(hetero_ins_tab) > 0) g_minor_het_insertions <<- data.table::data.table(pos = )
if(nrow(hetero_ins_tab) > 0) {
offset <- -start(pattern(hetero_indel_aln)) + start(subject(hetero_indel_aln))
minor_het_insertions <<- data.table::data.table(pos = hetero_ins_tab[which(!is.in.primery),1],seq = stri_sub(secondary_seq,hetero_ins_tab[which(!is.in.primery),1] + offset,hetero_ins_tab[which(!is.in.primery),2] + offset))
}
else minor_het_insertions <<- data.table::data.table()
hetero_indel_aln <<- hetero_indel_aln
hetero_indel_pid <<- round(pid(hetero_indel_aln),1)
hetero_ins_tab <<- hetero_ins_tab
hetero_del_tab <<- hetero_del_tab
hetero_indel_report <<- paste0("alignment identity: ",hetero_indel_pid,"%\nins/del counts : ",ins_counts," / ",del_counts)
if((ins_counts > 0)||(del_counts > 0)){
indels_present <- TRUE
}else{
indels_present <- FALSE
}
return(list(indels_present=indels_present,minor_het_insertions=minor_het_insertions,hetero_indel_aln=hetero_indel_aln,hetero_ins_tab=hetero_ins_tab,hetero_del_tab=hetero_del_tab,hetero_indel_pid=hetero_indel_pid,hetero_indel_report=hetero_indel_report))
}
get_consensus_mut <- function(mut_fwd,mut_rev,intens_tab,primery_seq){
# if(length(which(primery_seq == "-")) > 0){
# mut_fwd <- mut_fwd[-which(primery_seq == "-")]
# mut_rev <- mut_rev[-which(primery_seq == "-")]
# }
names <- structure(c(1,1:4),names = c("N","A","C","G","T"))
pa <- pairwiseAlignment(gsub("[ -]","",paste(mut_fwd[mut_fwd != "NA"],collapse = "")), gsub("[ -]","",paste(mut_rev[mut_rev != "NA"],collapse = "")),type = "overlap",substitutionMatrix = sm,gapOpening = -10, gapExtension = -1)
fwd <- strsplit(as.character(pattern(pa)),"")[[1]]
rev <- strsplit(as.character(subject(pa)),"")[[1]]
fwd_i <- numeric(length(fwd))
rev_i <- numeric(length(rev))
fwd_start <- min(which(mut_fwd != "-")) + start(pattern(pa)) - 1
rev_start <- min(which(mut_rev != "-")) + start(subject(pa)) - 1
fwd_matrix <- as.matrix(intens_tab[,1:4,with = F])
rev_matrix <- as.matrix(intens_tab[,5:8,with = F])
fwd_i[which(fwd != "-")] <- diag(fwd_matrix[start(pattern(pa)):nrow(fwd_matrix),names[fwd[which(fwd != "-")]]])
rev_i[which(rev != "-")] <- diag(rev_matrix[start(subject(pa)):nrow(rev_matrix),names[rev[which(rev != "-")]]])
cons <- fwd
cons[which(rev_i > fwd_i)] <- rev[which(rev_i > fwd_i)]
return(cons)
}
incorporate_single_vec <- function(vec,ins,dels,type,fwd,primarySeq){
orig_vec <- vec
if(type == "num") elem <- 0
else elem <- "-"
new_vec <- rep(elem,length(vec))
if(length(ins) > 0) {
if(fwd) {
vec <- vec[-ins]
vec <- c(vec,rep(elem,length(ins)))
} else {
vec <- vec[-(ins - length(ins))]
vec <- c(rep(elem,length(ins)),vec)
}
}
if(fwd) {
vec <- vec[1:min(length(vec),length(new_vec) - length(dels))]
new_vec[setdiff(seq_along(new_vec),dels)] <- vec
} else {
vec <- vec[1 + length(vec) - min(length(vec),length(new_vec) - length(dels)):1]
new_vec[setdiff(seq_along(new_vec),dels)] <- vec
}
if(type == "char" && !is.null(primarySeq)){
move_vec <- numeric(length(new_vec))
if(fwd){
move_vec[ins] <- -1
move_vec[dels] <- 1
move_vec <- cumsum(move_vec)
move_vec[which(rep(rle(move_vec)$length,rle(move_vec)$length) == 1)] <- move_vec[which(rep(rle(move_vec)$length,rle(move_vec)$length) == 1) + 1]
} else {
move_vec[ins] <- 1
move_vec[dels] <- -1
move_vec <- rev(cumsum(rev(move_vec)))
move_vec[which(rep(rle(move_vec)$length,rle(move_vec)$length) == 1)] <- move_vec[which(rep(rle(move_vec)$length,rle(move_vec)$length) == 1) - 1]
}
replace <- setdiff(which(orig_vec == primarySeq) + move_vec[which(orig_vec == primarySeq)],c(ins,dels))
replace <- replace[replace < length(primarySeq)]
replace <- replace[replace > 0]
new_vec[replace] <- primarySeq[replace]
}
return(new_vec)
}
#reconstructs user_mut and mut_peak_pct by shifting user_call_fwd and user_call_rev by detected indels
incorporate_hetero_indels_func <- function(calls,hetero_del_tab,hetero_ins_tab,g_minor_het_insertions,qual_thres,single_rev){
vec <- calls$id *100
vec2 <- vec %% 100
vec3 <- vec2 != 0
vec4 <- cumsum(vec3) #compensate for insertions introduced before incorporate
if(!is.na(hetero_del_tab[1])) {
dels <- as.vector(unlist(apply(hetero_del_tab,1,function(x) {x[1]:x[2] + vec4[x[1]-1]})))
#dels <- calls[id %in% dels_pos,which = TRUE]
}
else dels <- numeric()
if(!is.na(hetero_ins_tab[1])){
ins <- as.vector(unlist(apply(hetero_ins_tab,1,function(x) {x[1]:x[2]+ vec4[x[1]-1]})))
#ins <- calls[id %in% ins_pos,which = TRUE]
}
else ins <- numeric()
forward=TRUE
if(single_rev){
forward = FALSE
}
#update call fwd and rev
if(max(length(dels),length(ins)) != 0){
#quick fix for single strand
if('het_quality_fwd' %in% colnames(calls)){calls[,het_quality_fwd := NULL]}
calls[,het_mut_call_fwd := incorporate_single_vec(calls[["mut_call_fwd"]],ins,dels,"char",forward,calls[["sample_peak_base_fwd"]])]
calls[,het_mut_peak_pct_fwd := incorporate_single_vec(calls[["mut_peak_pct_fwd"]],ins,dels,"num",forward)]
calls[,het_quality_fwd := incorporate_single_vec(calls[["quality_fwd"]],ins,dels,"num",forward)]
calls[,het_mut_s2n_abs_fwd := incorporate_single_vec(calls[["mut_s2n_abs_fwd"]],ins,dels,"num",forward)]
#calls[set_by_user == FALSE, c("user_mut","mut_peak_pct") := list(het_mut_call_fwd,het_mut_peak_pct_fwd)]
#calls[set_by_user == FALSE & (mut_call_fwd != het_mut_call_fwd),c("user_mut","mut_peak_pct") := list(het_mut_call_fwd,het_mut_peak_pct_fwd)]
if(any(colnames(calls) == "call_rev")){
calls[,het_mut_call_rev := incorporate_single_vec(calls[["mut_call_rev"]],ins,dels,"char",F,calls[["sample_peak_base_rev"]])]
calls[,het_mut_peak_pct_rev := incorporate_single_vec(calls[["mut_peak_pct_rev"]],ins,dels,"num",F)]
calls[,het_quality_rev := incorporate_single_vec(calls[["quality_rev"]],ins,dels,"num",F)]
calls[,het_mut_s2n_abs_rev := incorporate_single_vec(calls[["mut_s2n_abs_rev"]],ins,dels,"num",F)]
#calls[(quality_fwd< quality_rev | user_mut == "-") & set_by_user == FALSE, c("user_mut","mut_peak_pct") := list(het_mut_call_rev,het_mut_peak_pct_rev)]
#calls[(het_quality_fwd < het_quality_rev | user_mut == "-") & set_by_user == FALSE, c("user_mut","mut_peak_pct") := list(het_mut_call_rev,het_mut_peak_pct_rev)]
calls[ set_by_user == FALSE & ( mut_call_fwd == het_mut_call_fwd & mut_call_rev != het_mut_call_rev) | mut_call_rev == "-", c("user_mut","mut_peak_pct") := list(het_mut_call_fwd,het_mut_peak_pct_fwd)]
calls[ set_by_user == FALSE & ( mut_call_rev == het_mut_call_rev & mut_call_fwd != het_mut_call_fwd) | mut_call_fwd == "-", c("user_mut","mut_peak_pct") := list(het_mut_call_rev,het_mut_peak_pct_rev)]
calls[ set_by_user == FALSE & ( mut_call_rev != het_mut_call_rev & mut_call_fwd != het_mut_call_fwd) | mut_call_rev == "-", c("user_mut","mut_peak_pct") := list(het_mut_call_fwd,het_mut_peak_pct_fwd)]
calls[ set_by_user == FALSE & ((mut_call_rev != het_mut_call_rev & mut_call_fwd != het_mut_call_fwd) | mut_call_fwd == "-") & het_quality_rev > het_quality_fwd, c("user_mut","mut_peak_pct") := list(het_mut_call_rev,het_mut_peak_pct_rev)]
calls[ set_by_user == FALSE & (mut_call_rev == het_mut_call_rev & mut_call_fwd == het_mut_call_fwd) & het_quality_rev <= het_quality_fwd, c("user_mut","mut_peak_pct") := list(het_mut_call_fwd,het_mut_peak_pct_fwd)]
calls[ set_by_user == FALSE & (mut_call_rev == het_mut_call_rev & mut_call_fwd == het_mut_call_fwd) & het_quality_rev > het_quality_fwd, c("user_mut","mut_peak_pct") := list(het_mut_call_rev,het_mut_peak_pct_rev)]
#calls[
# het_mut_call_fwd!=reference
# & het_mut_call_rev==reference
# & het_quality_fwd > qual_thres
# & set_by_user == FALSE
# , c("user_mut","mut_peak_pct") := list(het_mut_call_fwd,het_mut_peak_pct_fwd)
# ]
#calls[
# het_mut_call_fwd==reference
# & het_mut_call_rev!=reference
# & het_quality_rev > qual_thres
# & set_by_user == FALSE
# , c("user_mut","mut_peak_pct") := list(het_mut_call_rev,het_mut_peak_pct_rev)
# ]
#calls[
# het_mut_call_fwd!=reference
# & het_mut_call_rev!=reference
# & set_by_user == FALSE
# & het_quality_fwd > qual_thres
# # & mut_call_rev != call_rev
# , c("user_mut","mut_peak_pct") := list(het_mut_call_fwd,het_mut_peak_pct_fwd)
# ]
#calls[
# het_mut_call_fwd!=reference
# & het_mut_call_rev!=reference
# & het_quality_rev > het_quality_fwd
# & het_quality_rev > qual_thres
# & set_by_user == FALSE
# # & mut_call_rev != call_rev
# , c("user_mut","mut_peak_pct") := list(het_mut_call_rev,het_mut_peak_pct_rev)
# ]
}else{
calls[set_by_user == FALSE, c("user_mut","mut_peak_pct") := list(het_mut_call_fwd,het_mut_peak_pct_fwd)]
}
}
#add insertion
if(nrow(g_minor_het_insertions[!is.na(pos)]) > 0){
get_ins_data_table <- function(pos,seq){
ins_seq <- strsplit(seq,"")[[1]]
ins_id <- pos -1
ins_tab <- calls[id %in% ins_id,]
ins_tab <- ins_tab[rep(1,length(ins_seq)),]
ins_tab[,id := id + seq_along(id)/100]
ins_tab[,user_sample := "-"][,reference := "-"][,user_mut := ins_seq]
ins_tab[,`:=`(iA_fwd=0,iC_fwd=0,iG_fwd=0,iT_fwd=0,ord_in_cod=4)]
#ins_tab[,`:=`(iA_fwd=0,iC_fwd=0,iG_fwd=0,iT_fwd=0)]
if("call_rev" %in% row.names(calls)){
ins_tab[,`:=`(iA_rev=0,iC_rev=0,iG_rev=0,iT_rev=0)]
}
return(ins_tab)
}
if(nrow(g_minor_het_insertions[!is.na(pos)])>0){
ins_tabs <- lapply(1:nrow(minor_het_insertions[!is.na(pos),]),function(x) get_ins_data_table(minor_het_insertions[!is.na(pos),]$pos[x],g_minor_het_insertions$seq[x]))
added <- lapply(1:nrow(g_minor_het_insertions[!is.na(pos),]),function(x) paste0(ins_tabs[[x]]$id,collapse= " "))
g_minor_het_insertions[,added:=added]
#g_minor_het_insertions$added = rbindlist(ins_tabs)$id;
calls <- rbindlist(c(list(calls),ins_tabs))
}
}
return(calls)
}
add_intensities <- function(added,calls,intens,intens_rev,intrexdat){
#update intensities
id <- calls[id == as.integer(added[1]),]$trace_peak + 6
add<-data.table("id"=id + (1:(length(added)*12)/1000),"A"=0,"C"=0,"G"=0,"T"=0)
intens <- rbind(intens, add)
setkey(intens, id)
if("call_rev" %in% colnames(calls)){
intens_rev <- rbind(intens_rev, add)
setkey(intens_rev, id)
}
#intens_rev must match intens (hopefully they do otherwise its a bigger problem)
#update peak positions in calls table
calls$trace_peak <- seq(from = calls[1]$trace_peak, by = 12, length.out = nrow(calls))
calls$trace_peak_rev <- seq(from = calls[1]$trace_peak, by = 12, length.out = nrow(calls))
intens$id_new <- 1:length(intens$id)
# we're renaming the intensities, have to update the 'added' ones
add$id <- intens[id %in% add$id]$id_new
intens[,id:=id_new]
intens[,id_new:=NULL]
if(!is.null(intens_rev)){
intens_rev$id <- 1:length(intens_rev$id)
}
#update intrex
intrexdat$intrex <- setnames(calls[!is.na(exon_intron),list(max(id)-min(id)+1,min(trace_peak),max(trace_peak)),by = exon_intron],c("attr","length","trace_peak","end"))
intrexdat$intrex <- setnames(merge(intrexdat$intrex,calls[,list(id,trace_peak)],by="trace_peak"),"trace_peak","start")
intrexdat <- splice_variants(intrexdat)
intrexdat$max_x <- nrow(intens)
return(list(ins_added=paste0(add$id,collapse= " "),calls=calls,intens=intens,intens_rev=intens_rev,intrexdat=intrexdat))
}
remove_intensities <- function(added,calls,intens,intens_rev,intrexdat,minor_het_insertions){
#update intensities (this operation takes too long)
intens <- intens[!id %in% as.numeric(str_split(minor_het_insertions$ins_added," ")[[1]]),]
#update peak positions in calls table
calls$trace_peak <- seq(from = calls[1]$trace_peak, by = 12, length.out = nrow(calls))
if("call_rev" %in% colnames(calls)){
intens_rev <- intens_rev[! id %in% as.numeric(str_split(minor_het_insertions$ins_added," ")[[1]]),]
calls$trace_peak_rev <- seq(from = calls[1]$trace_peak, by = 12, length.out = nrow(calls))
}
#update intrex
intrexdat$intrex <- setnames(calls[!is.na(exon_intron),list(max(id)-min(id)+1,min(trace_peak),max(trace_peak)),by = exon_intron],c("attr","length","trace_peak","end"))
intrexdat$intrex <- setnames(merge(intrexdat$intrex,calls[,list(id,trace_peak)],by="trace_peak"),"trace_peak","start")
intrexdat <- splice_variants(intrexdat)
intrexdat$max_x <- nrow(intens)
return(list(calls=calls,intens=intens,intens_rev=intens_rev,intrexdat=intrexdat))
}
#background noise absolute or relative to reference peak
noise <- function(a,b,c,d,abs=FALSE){
vec <- sort(c(a,b,c,d))
if(a==0 & b==0 & c==0 & d==0) return(0)
if(abs) return(mean(vec[1:3]))
else return(mean(vec[1:3]/sum(vec[4])))
}
#retrieve the name, intens value, and with/without trace pos of the p'th peak as this may differ from the "call" which may bey ambiguous iupac (S,W,R...)
i_wo_p <- function(p,iA,iC,iG,iT){
a <- c(iA,iC,iG,iT)
if(p==2){
a[which(a==max(a))[1]]=0
}#max function may return more than one hits, in that case chose the first in order when p==1, or second when p==2
res = which(a==max(a))[1]
ret = list(c('A','C','G','T')[res],a[res])
return(ret)
#mut_peak <- (sort(c(iA,iC,iG,iT),decreasing = TRUE)[p])
# if (mut_peak == 0 ) return(list("-",mut_peak))
#else if (mut_peak == iA) return(list("A",mut_peak))
#else if (mut_peak == iC) return(list("C",mut_peak))
#else if (mut_peak == iG) return(list("G",mut_peak))
#else if (mut_peak == iT) return(list("T",mut_peak))
#else return(list("-",mut_peak))
}
# i_w_p <- function(p,iA,iC,iG,iT,pA,pC,pG,pT){
# mut_peak <- (sort(c(iA,iC,iG,iT),decreasing = TRUE)[p])
# if (mut_peak == 0 ) return(list(" ",mut_peak,pA))
# else if (mut_peak == iA) return(list("A",mut_peak,pA))
# else if (mut_peak == iC) return(list("C",mut_peak,pC))
# else if (mut_peak == iG) return(list("G",mut_peak,pG))
# else if (mut_peak == iT) return(list("T",mut_peak,pT))
# }
get_expected_het_indels <- function(calls){
min_het_pct <- 0.04
rev <- !is.null(calls[["call_rev"]])
if(rev) intens_tab <- calls[,list(iA_fwd,iC_fwd,iG_fwd,iT_fwd,iA_rev,iC_rev,iG_rev,iT_rev)]
else intens_tab <- calls[,list(iA_fwd,iC_fwd,iG_fwd,iT_fwd)]
fwd_matrix <- as.matrix(intens_tab[,1:4,with = F])
fwd_matrix2 <- fwd_matrix / rowSums(fwd_matrix)
fwd_matrix2[which(is.na(fwd_matrix2))] <- 0
sec_fwd_vec <- apply(fwd_matrix2,1,function(x) max(x[-which.max(x)]))
if(rev){
rev_matrix <- as.matrix(intens_tab[,5:8,with = F])
rev_matrix2 <- rev_matrix / rowSums(rev_matrix)
rev_matrix2[which(is.na(rev_matrix2))] <- 0
sec_rev_vec <- apply(rev_matrix2,1,function(x) max(x[-which.max(x)]))
sec_vec <- c(sec_fwd_vec,sec_rev_vec)
} else {
sec_vec <- sec_fwd_vec
}
hst <- hist(sec_vec,breaks = 100,plot = F)
xz <- as.zoo(hst$density)
min <- rollapply(xz, 9, function(x) which.min(x)==5)