-
Notifications
You must be signed in to change notification settings - Fork 240
/
bam2bcf_edlib.c
1704 lines (1518 loc) · 65.8 KB
/
bam2bcf_edlib.c
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
/* bam2bcf_indel.c -- indel caller.
Copyright (C) 2010, 2011 Broad Institute.
Copyright (C) 2012-2014,2016-2017, 2021-2024 Genome Research Ltd.
Author: Heng Li <[email protected]>
Petr Danecek <[email protected]>
James Bonfield <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. */
// Show consensus
//#define CONS_DEBUG
// Show alignments to consensus
//#define ALIGN_DEBUG
#include <assert.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <htslib/hts.h>
#include <htslib/sam.h>
#include <htslib/khash_str2int.h>
#include "bam2bcf.h"
#include "str_finder.h"
#include <htslib/ksort.h>
// Is there no way to share these between the 3 implementations?
KSORT_INIT_STATIC_GENERIC(uint32_t)
#define MINUS_CONST 0x10000000
#define MAX_TYPES 64
#ifndef MIN
# define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#ifndef ABS
# define ABS(a) ((a)<0?-(a):(a))
#endif
#ifndef MAX
# define MAX(a,b) ((a)>(b)?(a):(b))
#endif
// l is the relative gap length and l_run is the length of the homopolymer
// on the reference.
//
// Larger seqQ is good, so increasing tandemQ calls more indels,
// and longer l_run means fewer calls. It is capped later at 255.
// For short l_runs, the qual is simply based on size of indel
// larger ones being considered more likely to be real.
// Longer indels get assigned a score based on the relative indel size
// to homopolymer, where l_run base will have already been verified by
// the caller to ensure it's compatible.
static inline int est_seqQ(const bcf_callaux_t *bca, int l, int l_run, int str_len)
{
int q, qh;
// Short indels are more likely sequencing error than large ones.
// So "seqQ" scales with size of observation "l".
//
// Note openQ and extQ are error likelihoods in Phred scale. Hence high
// openQ means we're very unlikely to miscall an indel.
// Ie it's not the open/ext "costs" normally used in alignment; more the reverse.
//
// We use MIN(q,qh) below, so we can remove the q component by specifying
// a large -o parameter in mpileup.
q = bca->openQ + bca->extQ * (abs(l) - 1);
// Orig method; best with Illumina (high openQ)
// qh = bca->tandemQ * (double)abs(l) / l_run + .499;
// Penalise longer homopolymers quadratically more, but boost shorter ones.
// Best with CCS (low openQ)
//qh = 2 * bca->tandemQ * pow((double)abs(l) / l_run, 1.5) + .499;
// (l/l_run)^1.26 for openQ=25 or ^1 for openQ=40.
// double openQ = MIN(40, bca->openQ);
// qh = (30/openQ) * bca->tandemQ
// * pow((double)abs(l) / l_run, 1/sqrt(openQ/40)) + .499;
// Linear scaled on openQ too
qh = bca->tandemQ * (double)abs(l) / l_run + .499;
// Generic maybe ?
// power = 1/sqrt(MIN(40,bca->openQ)/40.);
// qh = ... * pow((double)abs(l)/l_run, power)
// bam2bcf.c caps has "if q>seqQ) q=seqQ" so it caps base qual 'q'.
// A 1bp indel would therefore have a maximum qual it could be considered based
// on open+ext. Hence why openQ is phred score indicating if the base is real
// or an over/under-call. (high openQ means high trust in base)
return q < qh? q : qh;
}
// Part of bcf_call_gap_prep.
//
// Scans the pileup to identify all the different sizes of indels
// present.
// types[] returned is sorted by size, from smallest (maybe negative) to largest.
//
// Returns types and fills out n_types_r, max_rd_len_r and ref_type_r,
// or NULL on error.
static int *bcf_cgp_find_types(int n, int *n_plp, bam_pileup1_t **plp,
int pos, bcf_callaux_t *bca, const char *ref,
int *max_rd_len_r, int *n_types_r,
int *ref_type_r, int *N_r) {
int i, j, t, s, N, m, max_rd_len, n_types;
int n_alt = 0, n_tot = 0, indel_support_ok = 0;
uint32_t *aux;
int *types;
// N is the total number of reads
for (s = N = 0; s < n; ++s)
N += n_plp[s];
bca->max_support = bca->max_frac = 0;
aux = (uint32_t*) calloc(N + 1, 4);
if (!aux)
return NULL;
m = max_rd_len = 0;
aux[m++] = MINUS_CONST; // zero indel is always a type (REF)
// Fill out aux[] array with all the non-zero indel sizes.
// Also tally number with indels (n_alt) and total (n_tot).
for (s = 0; s < n; ++s) {
int na = 0, nt = 0;
for (i = 0; i < n_plp[s]; ++i) {
const bam_pileup1_t *p = plp[s] + i;
++nt;
if (p->indel != 0) {
++na;
aux[m++] = MINUS_CONST + p->indel;
}
// FIXME: cache me in pileup struct.
j = bam_cigar2qlen(p->b->core.n_cigar, bam_get_cigar(p->b));
if (j > max_rd_len) max_rd_len = j;
}
double frac = (double)na/nt;
if ( !indel_support_ok && na >= bca->min_support
&& frac >= bca->min_frac )
indel_support_ok = 1;
if ( na > bca->max_support && frac > 0 )
bca->max_support = na, bca->max_frac = frac;
n_alt += na;
n_tot += nt;
}
// Sort aux[] and dedup
ks_introsort(uint32_t, m, aux);
for (i = 1, n_types = 1; i < m; ++i)
if (aux[i] != aux[i-1]) ++n_types;
// Taking totals makes it hard to call rare indels (IMF filter)
if ( !bca->per_sample_flt )
indel_support_ok = ( (double)n_alt / n_tot < bca->min_frac
|| n_alt < bca->min_support )
? 0 : 1;
if ( n_types == 1 || !indel_support_ok ) { // then skip
free(aux);
return NULL;
}
// Bail out if we have far too many types of indel
if (n_types >= MAX_TYPES) {
free(aux);
// TODO revisit how/whether to control printing this warning
if (hts_verbose >= 2)
fprintf(stderr, "[%s] excessive INDEL alleles at position %d. "
"Skip the position.\n", __func__, pos + 1);
return NULL;
}
// To prevent long stretches of N's to be mistaken for indels
// (sometimes thousands of bases), check the number of N's in the
// sequence and skip places where half or more reference bases are Ns.
int nN=0, i_end = pos + (2*bca->indel_win_size < max_rd_len
?2*bca->indel_win_size : max_rd_len);
for (i=pos; i<i_end && ref[i]; i++)
nN += ref[i] == 'N';
if ( nN*2>(i-pos) ) {
free(aux);
return NULL;
}
// Finally fill out the types[] array detailing the size of insertion
// or deletion.
types = (int*)calloc(n_types, sizeof(int));
if (!types) {
free(aux);
return NULL;
}
t = 0;
for (i = 0; i < m; ++i) {
int sz = (int32_t)(aux[i] - MINUS_CONST);
int j;
for (j = i+1; j < m; j++)
if (aux[j] != aux[i])
break;
if (sz == 0
|| (j-i >= bca->min_support &&
// Note, doesn't handle bca->per_sample_flt yet
(bca->per_sample_flt
|| (double)(j-i) / n_tot >= bca->min_frac)))
types[t++] = sz;
i = j-1;
}
free(aux);
if (t <= 1) {
free(types);
return NULL;
}
n_types = t;
// Find reference type; types[?] == 0)
for (t = 0; t < n_types; ++t)
if (types[t] == 0) break;
*ref_type_r = t;
*n_types_r = n_types;
*max_rd_len_r = max_rd_len;
*N_r = N;
return types;
}
// Increment ins["str"] and freq["str"]
#define NI 100 // number of alternative insertion sequences
// Could use a hash table too, but expectation is a tiny number of alternatives
typedef struct {
char *str[NI];
int len[NI];
int freq[NI];
} str_freq;
static int bcf_cgp_append_cons(str_freq *sf, char *str, int len, int freq) {
int j;
for (j = 0; j < NI && sf->str[j]; j++) {
if (sf->len[j] == len && memcmp(sf->str[j], str, len) == 0)
break;
}
if (j >= NI)
return 0; // too many choices; discard
sf->freq[j]+=freq;
if (!sf->str[j]) {
// new insertion
if (!(sf->str[j] = malloc(len+1)))
return -1;
memcpy(sf->str[j], str, len);
sf->len[j] = len;
}
return 0;
}
/*
* Compute the consensus for a specific indel type at pos.
*
* left_shift is the number of inserted(+) or deleted(-) bases added to
* the consensus before we get to pos. This is necessary so the alignment
* band is correct as it's expected to start at left/right edges in
* sync
*
* We accumulate into several buffers for counting base types:
* cons_base - consensus of data with p->indel == type, bases or gap
* ref_base - consensus of data with p->indel != type, bases or gap
* cons_ins - consensus of data with p->indel == type, insertions
* ref_ins - consensus of data with p->indel == type, bases or gap
*
* The purpose of cons_ins vs cons_base is if we have very low
* coverage due to nearly all reads being another type, then we can
* still get a robust consensus using the other data. If we don't
* have shallow data, then we'll not use as much of ref_base as we may
* have correlated variants.
*
* Eg:
* REF: AGCTATGAGGCTGATA
* SEQ: AGGTAGGAGGGTGATA (x1)
* SEQ: AGCTACGAGG*TGATA (x24)
* SEQ: AGCTACTAGG*TGATA (x24)
*
* Cons for no-del is Cs not Gs. Cannot trust it, so use N if shallow.
* CON: AGCTACNAGGGTGATA
*
* There are still some problems in cons_ins vs ref_ins assignment.
* We sometimes seem multiple similar-length insertions added at
* different locations. Ideally we'd like to consider these as all
* the same insertion if the size is the same and it's comparable seq.
*/
#define MAX_INS 8192
static char **bcf_cgp_consensus(int n, int *n_plp, bam_pileup1_t **plp,
int pos, bcf_callaux_t *bca, const char *ref,
int ref_len, int left, int right,
int sample, int type, int biggest_del,
int *left_shift, int *right_shift,
int *band, int *tcon_len, int *cpos_pos,
int pos_l, int pos_r) {
// Map ASCII ACGTN* to 012345
static uint8_t base6[256] = {
4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,
4,4,4,4,4,4,4,4, 4,4,5,4,4,4,4,4, 4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,
//A C G *^ T
4,0,4,1,4,4,4,2, 4,4,4,4,4,4,4,4, 4,4,4,4,3,3,4,4, 4,4,4,4,4,4,4,4,
4,0,4,1,4,4,4,2, 4,4,4,4,4,4,4,4, 4,4,4,4,3,3,4,4, 4,4,4,4,4,4,4,4,
4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,
4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,
4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,
4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,
};
// single base or del
int (*cons_base)[6] = calloc(right - left + 1, sizeof(*cons_base));
// multi-base insertions
str_freq *cons_ins = calloc(right - left + 1, sizeof(*cons_ins));
// non-indel ref for all reads on this sample, rather than those just
// matching type. We use this for handling the case where we have a
// homozygous deletion being studied, but with 1 or 2 reads misaligned
// and containing a base there.
//
// Eg if the type[]=0 consensus is made up of a very small sample size,
// which is also enriched for highly error prone data. We can use
// the other reads from type[] != 0 to flesh out the consensus and
// improve accuracy.
int (*ref_base)[6] = calloc(right - left + 1, sizeof(*ref_base));
str_freq *ref_ins = calloc(right - left + 1, sizeof(*ref_ins));
int i, j, k, s = sample;
char **cons = NULL;
if (!cons_base || !cons_ins || !ref_base || !ref_ins)
goto err;
//--------------------------------------------------
// Accumulate sequences into cons_base and cons_ins arrays
int local_band_max = 0; // maximum absolute deviation from diagonal
int total_span_str = 0;
int type_depth = 0;
for (i = 0; i < n_plp[s]; i++) {
const bam_pileup1_t *p = plp[s] + i;
bam1_t *b = p->b;
int x = b->core.pos; // ref coordinate
int y = 0; // seq coordinate
uint32_t *cigar = bam_get_cigar(b);
uint8_t *seq = bam_get_seq(b);
int local_band = 0; // current deviation from diagonal
for (k = 0; k < b->core.n_cigar; ++k) {
int op = cigar[k] & BAM_CIGAR_MASK;
int len = cigar[k] >> BAM_CIGAR_SHIFT;
int base;
int skip_to = 0;
switch(op) {
case BAM_CSOFT_CLIP:
y += len;
break;
case BAM_CMATCH:
case BAM_CEQUAL:
case BAM_CDIFF: {
// Can short-cut this with j_start and j_end based on
// x+len and left,right
for (j = 0; j < len; j++, x++, y++) {
if (x < left) continue;
if (x >= right) break;
base = bam_seqi(seq, y);
if (p->indel == type)
// Convert 4-bit base ambig code to 0,1,2,3,4 range
cons_base[x-left][seq_nt16_int[base]]++;
else if (x != pos+1) // indel being assessed question
ref_base[x-left][seq_nt16_int[base]]++;
}
break;
}
case BAM_CINS: {
if (x >= left && x < right) {
local_band += p->indel;
if (local_band_max < local_band)
local_band_max = local_band;
}
char ins[MAX_INS];
for (j = 0; j < len; j++, y++) {
if (x < left) continue;
if (x >= right)
break;
base = bam_seqi(seq, y);
if (j < MAX_INS)
ins[j] = seq_nt16_int[base];
}
// Insertions come before a ref match.
// 5I 5M is IIIIIM M M M M events, not
// {IIIII,M} M M M M choice. So we need to include the
// next match in our sequence when choosing the consensus.
if (x >= left && x < right) {
int ilen = j<MAX_INS?j:MAX_INS;
if (p->indel == type /*&& x == pos+1*/) {
// Assume any ins of the same size is the same ins.
// (This rescues misaligned insertions.)
if (bcf_cgp_append_cons(&cons_ins[x-left], ins,
ilen, 1) < 0)
goto err;
type_depth += (x == pos+1);
} else if (x != pos+1){
if (bcf_cgp_append_cons(&ref_ins[x-left], ins,
ilen, 1) < 0)
goto err;
}
}
break;
}
case BAM_CDEL:
if (x >= left && x < right) {
local_band += p->indel;
if (local_band_max < -local_band)
local_band_max = -local_band;
}
// Maybe not perfect for I/D combos, but likely sufficient.
for (j = 0; j < len; j++, x++) {
if (x < left) continue;
if (x >= right) break;
if ((p->indel == type && !p->is_del) || // starts here
(p->indel == 0 && p->is_del && len == -type)) { // left
cons_base[x-left][5]++;
type_depth += (x == pos+1);
} else if (x+len <= pos+1 || (skip_to && x > skip_to))
ref_base[x-left][5]++;
else if (x <= pos && x+len > pos+1) {
// we have a deletion which overlaps pos, but
// isn't the same "type". We don't wish to
// include these as they may bias the
// evaluation by confirming against a
// secondary consensus produced with the other
// deletion. We set a marker for how long to
// skip adding to ref_base.
if (x > skip_to)
skip_to = x+len;
}
}
break;
}
}
if (b->core.pos <= pos_l && x >= pos_r)
total_span_str++;
// Also track the biggest deviation +/- from diagonal. We use
// this band observation in our BAQ alignment step.
if (*band < local_band_max)
*band = local_band_max;
}
//--------------------------------------------------
// Expand cons_base to include depth from ref_base/ref_ins
// Caveat: except at pos itself, where true ref is used if type != 0
#if 1 // TEST 1
// We could retest this heuristic further maybe.
for (i = 0; i < right-left; i++) {
// Total observed depth
int t = cons_base[i][0] + cons_base[i][1] + cons_base[i][2] +
cons_base[i][3] + cons_base[i][4] + cons_base[i][5];
for (j = 0; j < NI; j++) {
if (!cons_ins[i].str[j])
break;
t += cons_ins[i].freq[j];
}
// Similarly for depth on the non-ALT calls (NB: not necessarily
// REF as maybe it's other ALTs).
int r = ref_base[i][0] + ref_base[i][1] + ref_base[i][2] +
ref_base[i][3] + ref_base[i][4] + ref_base[i][5];
for (j = 0; j < NI; j++) {
if (!ref_ins[i].str[j])
break;
r += ref_ins[i].freq[j];
}
// When evaluating this particular indel, we don't want to
// penalise alignments by SNP errors elsewhere. This can
// happen when we have low depth for a particular 'type'.
//
// So add in a little data from ref_base/ref_ins.
double rfract = (r - t*2)*.75 / (r+1);
if (rfract < 1.01 / (r+1e-10))
rfract = 1.01 / (r+1e-10); // low depth compensation
// if (rfract > 0.2)
// rfract = 0.2;
// TODO: consider limiting rfract so we never drown out the
// signal. We want to use the remaining data only to correct
// for sequencing errors in low depth alleles. If we get
// conflicts, it's better to use N than to change a base
// incase that variant is genuine.
if (i+left >= pos+1 && i+left < pos+1-biggest_del) {
// We're overlapping the current indel region, so
// we don't wish to bring in evidence from the other
// "type" data as it'll harm calling.
continue;
} else {
// Otherwise add in a portion of other data to
// boost low population numbers.
cons_base[i][0] += rfract * ref_base[i][0];
cons_base[i][1] += rfract * ref_base[i][1];
cons_base[i][2] += rfract * ref_base[i][2];
cons_base[i][3] += rfract * ref_base[i][3];
cons_base[i][4] += rfract * ref_base[i][4];
cons_base[i][5] += rfract * ref_base[i][5];
}
// Similarly for insertions too; consider a different rfract here?
for (j = 0; j < NI; j++) {
if (!ref_ins[i].str[j])
break;
if (bcf_cgp_append_cons(&cons_ins[i],
ref_ins[i].str[j], ref_ins[i].len[j],
rfract * ref_ins[i].freq[j]) < 0)
goto err;
}
}
#endif
//--------------------------------------------------
// Allocate consensus buffer, to worst case length
int max_len = right-left;
for (i = 0; i < right-left; i++) {
if (!cons_ins[i].str[0])
continue;
int ins = 0;
for (j = 0; j < NI; j++) {
if (!cons_ins[i].str[j])
break;
if (cons_ins[i].str[j] && ins < cons_ins[i].len[j])
ins = cons_ins[i].len[j];
}
max_len += ins;
}
max_len += MAX(0, type); // incase type inserted bases never occur
cons = malloc((max_len+1)*2 + sizeof(char *)*2);
if (!cons)
goto err;
cons[0] = (char *)&cons[2];
cons[1] = cons[0] + max_len+1;
//--------------------------------------------------
// Merge insertions where they are the same length but different
// sequences.
// NB: we could just index by length and have accumulators for each,
// instead of storing separately and merging later (here).
// Ie str_freq.str is [NI][5] instead.
for (i = 0; i < right-left; i++) {
int ins[MAX_INS][5];
for (j = 0; j < NI; j++) {
if (!cons_ins[i].str[j])
break;
if (cons_ins[i].freq[j] == 0)
continue; // already merged
int l;
for (l = 0; l < cons_ins[i].len[j]; l++) {
// Append to relevant frequency counter, zero all others
ins[l][0] = ins[l][1] = ins[l][2] = ins[l][3] = ins[l][4] = 0;
uint8_t b = cons_ins[i].str[j][l];
ins[l][b] = cons_ins[i].freq[j];
}
// Merge other insertions of the same length to ins[] counters
for (k = j+1; k < NI; k++) {
if (!cons_ins[i].str[k])
break;
if (cons_ins[i].len[k] != cons_ins[i].len[j])
continue;
if (cons_ins[i].freq[k] == 0)
continue; // redundant?
// Merge str[j] and str[k]
for (l = 0; l < cons_ins[i].len[k]; l++) {
uint8_t b = cons_ins[i].str[k][l];
ins[l][b] += cons_ins[i].freq[k];
}
cons_ins[i].freq[j] += cons_ins[i].freq[k];
cons_ins[i].freq[k] = 0;
}
// Now replace ins[j] with the consensus insertion of this len.
for (l = 0; l < cons_ins[i].len[j]; l++) {
int max_v = 0, base = 0;
int tot = ins[l][0] + ins[l][1] + ins[l][2]
+ ins[l][3] + ins[l][4];
if (max_v < ins[l][0]) max_v = ins[l][0], base = 0;
if (max_v < ins[l][1]) max_v = ins[l][1], base = 1;
if (max_v < ins[l][2]) max_v = ins[l][2], base = 2;
if (max_v < ins[l][3]) max_v = ins[l][3], base = 3;
if (max_v < ins[l][4]) max_v = ins[l][4], base = 4;
cons_ins[i].str[j][l] = (max_v > 0.6*tot) ? base : 4;
}
}
}
#define CONS_CUTOFF .40 // % needed for base vs N
#define CONS_CUTOFF_DEL .35 // % to include any het del
#define CONS_CUTOFF2 .80 // % needed for gap in cons[1]
#define CONS_CUTOFF_INC .35 // % to include any insertion cons[0]
#define CONS_CUTOFF_INC2 .80 // % to include any insertion cons[1] HOM
#define CONS_CUTOFF_INS .60 // and then 60% needed for it to be bases vs N
//--------------------------------------------------
// Walk through the frequency arrays to call the consensus.
// We produce cons[0] and cons[1]. Both include strongly
// homozygous indels. Both also include the indel at 'pos'.
// However for heterozygous indels we call the most likely event
// for cons[0] and the less-likely alternative in cons[1].
// TODO: a proper phase analysis so multiple events end up
// combining together into the correct consensus.
*left_shift = 0;
*right_shift = 0;
int cnum;
// Het call filled out in cnum==0 (+ve or -ve).
// Used in cnum==1 to do the opposite of whichever way we did before.
int heti[MAX_INS] = {0}, hetd[MAX_INS] = {0};
*cpos_pos = -1;
for (cnum = 0; cnum < 2; cnum++) {
for (i = k = 0; i < right-left; i++) {
// Location in consensus matching the indel itself
if (i >= pos-left+1 && *cpos_pos == -1)
*cpos_pos = k;
int max_v = 0, max_v2 = 0, max_j = 4, max_j2 = 4, tot = 0;
for (j = 0; j < 6; j++) {
// Top 2 consensus calls
if (max_v < cons_base[i][j]) {
max_v2 = max_v, max_j2 = max_j;
max_v = cons_base[i][j], max_j = j;
} else if (max_v2 < cons_base[i][j]) {
max_v2 = cons_base[i][j], max_j2 = j;
}
tot += cons_base[i][j];
}
// +INS
int max_v_ins = 0, max_j_ins = 0;
int tot_ins = 0;
for (j = 0; j < NI; j++) {
if (i+left==pos+1)
if (type > 0 && i+left == pos+1
&& cons_ins[i].len[j] < type && j == 0) {
cons_ins[i].str[j] = realloc(cons_ins[i].str[j], type);
if (!cons_ins[i].str[j])
goto err;
memset(cons_ins[i].str[j] + cons_ins[i].len[j],
4, type - cons_ins[i].len[j]);
cons_ins[i].len[j] = type;
}
if (!cons_ins[i].str[j])
break;
if (cons_ins[i].freq[j] == 0)
continue; // previously merged
if (max_v_ins < cons_ins[i].freq[j])
//if (i != pos-left+1 || cons_ins[i].len[j] == type)
max_v_ins = cons_ins[i].freq[j], max_j_ins = j;
tot_ins += cons_ins[i].freq[j];
}
// NB: tot is based on next matching base, so it includes
// everything with or without the insertion.
int tot_sum = tot;
int always_ins =
(i == pos-left+1 && type>0) || // current eval
max_v_ins > CONS_CUTOFF_INC2*tot_sum;// HOM
int het_ins = 0;
if (!always_ins && max_v_ins >= bca->min_support) {
// Candidate HET ins.
if (cnum == 0) {
het_ins = max_v_ins > CONS_CUTOFF_INC * tot_sum;
if (i < MAX_INS) heti[i] = het_ins
? 1
: (max_v_ins > .3*tot_sum ? -1:0);
} else {
// HET but uncalled before
het_ins = i < MAX_INS ? (heti[i] == -1) : 0;
}
}
if (always_ins || het_ins) {
if (max_v_ins > CONS_CUTOFF_INS*tot_ins) {
// Insert bases
for (j = 0; j < cons_ins[i].len[max_j_ins]; j++) {
if (cnum == 0) {
if (k < pos-left+*left_shift)
(*left_shift)++;
else
(*right_shift)++;
}
cons[cnum][k++] = cons_ins[i].str[max_j_ins][j];
}
} else {
for (j = 0; j < cons_ins[i].len[max_j_ins]; j++)
cons[cnum][k++] = 4; // 'N';
}
}
// Call deletions & bases
int always_del = (type < 0 && i > pos-left && i <= pos-left-type)
|| cons_base[i][5] > CONS_CUTOFF2 * tot; // HOM del
int het_del = 0;
if (!always_del && cons_base[i][5] >= bca->min_support) {
// Candidate HET del.
if (cnum == 0) {
int tot2 = tot;
if (i > pos-left && i <= pos-left-biggest_del)
tot2 = total_span_str - type_depth;
het_del = cons_base[i][5] >= CONS_CUTOFF_DEL * tot2;
if (i < MAX_INS) {
if (i > pos-left && i <= pos-left-biggest_del)
hetd[i] = 0;
else
hetd[i] = het_del
? 1
: (cons_base[i][5] >= .3 * tot2 ? -1 : 0);
}
} else {
// HET del uncalled on cnum 0
het_del = i < MAX_INS ? (hetd[i] == -1) : 0;
if (max_j == 5 && het_del == 0) {
max_v = max_v2;
max_j = max_j2;
}
}
}
if (always_del || het_del) {
// Deletion
if (k < pos-left+*left_shift)
(*left_shift)--;
else
(*right_shift)++;
} else {
// Finally the easy case - a non-indel base or an N
if (max_v > CONS_CUTOFF*tot)
cons[cnum][k++] = max_j; // "ACGTN*"
else if (max_v > 0)
cons[cnum][k++] = 4; // 'N';
else {
cons[cnum][k] = left+k < ref_len
? base6[(uint8_t)ref[left+k]]
: 4;
k++;
}
}
}
tcon_len[cnum] = k;
}
// TODO: replace by io_lib's string pool for rapid tidying.
// For now this isn't the bottleneck though.
for (i = 0; i < right-left; i++) {
for (j = 0; j < NI; j++) {
if (cons_ins[i].str[j])
free(cons_ins[i].str[j]);
if (ref_ins[i].str[j])
free(ref_ins[i].str[j]);
}
}
err:
free(cons_base);
free(ref_base);
free(cons_ins);
free(ref_ins);
return cons;
}
// A rename of bcf_cgp_calc_cons from bam2bcf_indel.c
//
// Compute the insertion consensus for this sample 's' via a basic
// majority rule.
//
// TODO: merge this into bcf_cgp_consensus as another return value?
static char *bcf_cgp_calc_ins_cons(int n, int *n_plp, bam_pileup1_t **plp,
int pos, int *types, int n_types,
int max_ins, int s) {
return bcf_cgp_calc_cons(n, n_plp, plp, pos, types, n_types, max_ins, s);
}
#define MAX(a,b) ((a)>(b)?(a):(b))
#define MIN(a,b) ((a)<(b)?(a):(b))
// Compile with LIBS="-L. -ldl -ledlib" CLD=g++
// This is faster than ksw and BAQ, meaning we can use larger --indel-size and
// get a more accurate context, improving alignments further. This *may*
// compensate for reduced sensitivity.
#include "edlib.h"
int edlib_glocal(uint8_t *ref, int l_ref, uint8_t *query, int l_query,
double m, double del_bias)
{
EdlibAlignConfig cfg =
edlibNewAlignConfig(
//ABS(type)+ABS(l_ref-l_query)+10,
-1, // k; use small positive for faster alignment
EDLIB_MODE_HW, // mode
#ifdef ALIGN_DEBUG
EDLIB_TASK_PATH,
#else
EDLIB_TASK_LOC,
#endif
NULL, // additionalEqualities
0); // additionalEqualitiesLength
EdlibAlignResult r =
edlibAlign((char *)query, l_query, (char *)ref, l_ref, cfg);
if (r.status != EDLIB_STATUS_OK || r.numLocations < 1 ||
!r.endLocations || !r.startLocations) {
edlibFreeAlignResult(r);
return INT_MAX;
}
#ifdef ALIGN_DEBUG
// NB: Needs linking against the C++ libedlib.a as our cut-down C
// implementation misses the alignment generation code.
{
int i, j = 0, pt = r.startLocations[0], pq = 0;
char line1[80];
char line2[80];
char line3[80];
for (i = 0; i < r.alignmentLength && pt < r.endLocations[0]; i++) {
int n;
switch (n = r.alignment[i]) {
case 0: // match
case 3: // mismatch
line1[j] = "ACGTN"[ref[pt++]];
line2[j] = "ACGTN"[query[pq++]];
line3[j] = " x"[n==3];
break;
case 2: // insertion to ref
line1[j] = "ACGTN"[ref[pt++]];
line2[j] = '-';
line3[j] = '-';
break;
case 1: // insertion to query
line1[j] = '-';
line2[j] = "ACGTN"[query[pq++]];
line3[j] = '+';
break;
}
if (++j == sizeof(line1)) {
fprintf(stderr, "%.*s\n", j, line1);
fprintf(stderr, "%.*s\n", j, line2);
fprintf(stderr, "%.*s\n", j, line3);
j = 0;
}
}
if (j) {
fprintf(stderr, "%.*s\n", j, line1);
fprintf(stderr, "%.*s\n", j, line2);
fprintf(stderr, "%.*s\n", j, line3);
}
}
#endif
// Aligned target length minus query length is an indication of the number
// of insertions and/or deletions.
//
// For CIGAR 10M1I10M t_len > l_query ("AC" / "ATC")
// For CIGAR 10M1D10M t_len < l_query ("ATC" / "AC")
// Hence t_len-l_query is -ve for net insertions and +ve for net deletions.
// If we compute nins and ndel directly via walking though EDLIB_TASK_PATH
// we'll see t_len-l_query == ndel-nins.
//
// If a technology has a significantly higher chance of making deletion
// errors than insertion errors, then we would view deletions as less
// indicative of this sequence not coming from this candidate allele than
// if it had insertion (as the deletions are more likely to be errors
// rather than real, relative to the insertions). Hence we can skew the
// score by the net delta of num_del - num_ins.
//
// Note this is an approximation that doesn't account for multiple
// insertions and deletions within the same sequence, but it is much faster
// as it doesn't require EDLIB_TASK_PATH to be computed.
//
// Given editDistance is +1 for every mismatch, insertion and deletion,
// provided the t_len-l_query multiplier < 1 then this is always +ve.
int t_len = *r.endLocations - *r.startLocations + 1;
int score = m*(r.editDistance - del_bias*(t_len - l_query));
edlibFreeAlignResult(r);
return score;
}
// Part of bcf_call_gap_prep.
//
// Realign using BAQ to get an alignment score of a single read vs
// a haplotype consensus. TODO: replace BAQ with something more robust.
//
// There are many coordinates, so let's explain them.
// - left, right, tbeg, tend, r_start and r_end are in aligned reference
// coordinates.
// left/right start from pos +/- indel_win_size.
// r_start/r_end are the BAM first and last mapped coord on the reference.
// tbeg and tend are the intersection of the two.
// - qbeg and qend are in BAM sequence coordinates
// - qpos is in sequence coordinates, relative to qbeg.
//
// To see what this means, we have illustrations with coordinates
// above the seqs in reference space and below the seqs in BAM seq space.
//
// Overlap left:
// tbeg tend
// r_start left pos r_end right
// REF :..............|--------------------#------:--------------|...
// SEQ :..............|--------------------#------|
// 0 qbeg qpos qend
//
// Overlap right:
// r_start tend
// left tbeg pos right r_end
// REF ...|--------------:-----#---------------------|...........:
// SEQ |-----#---------------------|...........:
// qbeg qpos qend
// 0
//
// The "-" sequence is the bit passed in.
// Ie ref2 spans left..right and query spans qbeg..qend.
// We need to adjust ref2 therefore to tbeg..tend.
//
// Fills out score
// Returns 0 on success,
// <0 on error
static int bcf_cgp_align_score(bam_pileup1_t *p, bcf_callaux_t *bca,
int type, int band,
uint8_t *ref1, uint8_t *ref2, uint8_t *query,
int r_start, int r_end,
int tbeg, int tend1, int tend2,
int left, int right,
int qbeg, int qend,
int pos, int qpos, int max_deletion,
double qavg, double del_bias, int *score,
int *str_len1_p, int *str_len2_p) {
int atype = abs(type);
int l, sc1, sc2;
// Trim poly_Ns at ends of ref.
// This helps to keep len(ref) and len(query) similar, to reduce
// band size and reduce the chance of -ve BAQ scores.
for (l = 0; l < tend1-tbeg && l < tend2-tbeg; l++)
if (ref1[l + tbeg-left] != 4 || ref2[l + tbeg-left] != 4)
break;
if (l > atype)
tbeg += l-atype;
for (l = tend1-tbeg-1; l >= 0; l--)
if (ref1[l + tbeg-left] != 4)
break;
l = tend1-tbeg-1 - l;
if (l > atype)
tend1 -= l-atype;
for (l = tend2-tbeg-1; l >= 0; l--)