Debian Codegraph @

bcftools/bam2bcf_edlib.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* bam2bcf_indel.c -- indel caller.
4
5 Copyright (C) 2010, 2011 Broad Institute.
6 Copyright (C) 2012-2014,2016-2017, 2021-2024 Genome Research Ltd.
7
8 Author: Heng Li <[email protected]>
9 Petr Danecek <[email protected]>
10 James Bonfield <[email protected]>
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in
20 all copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28 DEALINGS IN THE SOFTWARE. */
29
30 // Show consensus
31 //#define CONS_DEBUG
32
33 // Show alignments to consensus
34 //#define ALIGN_DEBUG
35
36 #include <assert.h>
37 #include <ctype.h>
38 #include <string.h>
39 #include <math.h>
40 #include <htslib/hts.h>
41 #include <htslib/sam.h>
42 #include <htslib/khash_str2int.h>
43 #include "bam2bcf.h"
44 #include "str_finder.h"
45
46 #include <htslib/ksort.h>
47 // Is there no way to share these between the 3 implementations?
48 KSORT_INIT_STATIC_GENERIC(uint32_t)
49
50 #define MINUS_CONST 0x10000000
51
52 #define MAX_TYPES 64
53
54 #ifndef MIN
55 # define MIN(a,b) ((a)<(b)?(a):(b))
56 #endif
57
58 #ifndef ABS
59 # define ABS(a) ((a)<0?-(a):(a))
60 #endif
61
62 #ifndef MAX
63 # define MAX(a,b) ((a)>(b)?(a):(b))
64 #endif
65
66 // l is the relative gap length and l_run is the length of the homopolymer
67 // on the reference.
68 //
69 // Larger seqQ is good, so increasing tandemQ calls more indels,
70 // and longer l_run means fewer calls. It is capped later at 255.
71 // For short l_runs, the qual is simply based on size of indel
72 // larger ones being considered more likely to be real.
73 // Longer indels get assigned a score based on the relative indel size
74 // to homopolymer, where l_run base will have already been verified by
75 // the caller to ensure it's compatible.
76 static inline int est_seqQ(const bcf_callaux_t *bca, int l, int l_run, int str_len)
77 {
78 int q, qh;
79 // Short indels are more likely sequencing error than large ones.
80 // So "seqQ" scales with size of observation "l".
81 //
82 // Note openQ and extQ are error likelihoods in Phred scale. Hence high
83 // openQ means we're very unlikely to miscall an indel.
84 // Ie it's not the open/ext "costs" normally used in alignment; more the reverse.
85 //
86 // We use MIN(q,qh) below, so we can remove the q component by specifying
87 // a large -o parameter in mpileup.
88 q = bca->openQ + bca->extQ * (abs(l) - 1);
89
90 // Orig method; best with Illumina (high openQ)
91 // qh = bca->tandemQ * (double)abs(l) / l_run + .499;
92
93 // Penalise longer homopolymers quadratically more, but boost shorter ones.
94 // Best with CCS (low openQ)
95 //qh = 2 * bca->tandemQ * pow((double)abs(l) / l_run, 1.5) + .499;
96
97 // (l/l_run)^1.26 for openQ=25 or ^1 for openQ=40.
98 // double openQ = MIN(40, bca->openQ);
99 // qh = (30/openQ) * bca->tandemQ
100 // * pow((double)abs(l) / l_run, 1/sqrt(openQ/40)) + .499;
101
102 // Linear scaled on openQ too
103 qh = bca->tandemQ * (double)abs(l) / l_run + .499;
104
105 // Generic maybe ?
106 // power = 1/sqrt(MIN(40,bca->openQ)/40.);
107 // qh = ... * pow((double)abs(l)/l_run, power)
108
109 // bam2bcf.c caps has "if q>seqQ) q=seqQ" so it caps base qual 'q'.
110 // A 1bp indel would therefore have a maximum qual it could be considered based
111 // on open+ext. Hence why openQ is phred score indicating if the base is real
112 // or an over/under-call. (high openQ means high trust in base)
113 return q < qh? q : qh;
114 }
115
116 // Part of bcf_call_gap_prep.
117 //
118 // Scans the pileup to identify all the different sizes of indels
119 // present.
120 // types[] returned is sorted by size, from smallest (maybe negative) to largest.
121 //
122 // Returns types and fills out n_types_r, max_rd_len_r and ref_type_r,
123 // or NULL on error.
124 static int *bcf_cgp_find_types(int n, int *n_plp, bam_pileup1_t **plp,
125 int pos, bcf_callaux_t *bca, const char *ref,
126 int *max_rd_len_r, int *n_types_r,
127 int *ref_type_r, int *N_r) {
128 int i, j, t, s, N, m, max_rd_len, n_types;
129 int n_alt = 0, n_tot = 0, indel_support_ok = 0;
130 uint32_t *aux;
131 int *types;
132
133 // N is the total number of reads
134 for (s = N = 0; s < n; ++s)
135 N += n_plp[s];
136
137 bca->max_support = bca->max_frac = 0;
138 aux = (uint32_t*) calloc(N + 1, 4);
139 if (!aux)
140 return NULL;
141
142 m = max_rd_len = 0;
143 aux[m++] = MINUS_CONST; // zero indel is always a type (REF)
144
145 // Fill out aux[] array with all the non-zero indel sizes.
146 // Also tally number with indels (n_alt) and total (n_tot).
147 for (s = 0; s < n; ++s) {
148 int na = 0, nt = 0;
149 for (i = 0; i < n_plp[s]; ++i) {
150 const bam_pileup1_t *p = plp[s] + i;
151 ++nt;
152 if (p->indel != 0) {
153 ++na;
154 aux[m++] = MINUS_CONST + p->indel;
155 }
156
157 // FIXME: cache me in pileup struct.
158 j = bam_cigar2qlen(p->b->core.n_cigar, bam_get_cigar(p->b));
159 if (j > max_rd_len) max_rd_len = j;
160 }
161 double frac = (double)na/nt;
162 if ( !indel_support_ok && na >= bca->min_support
163 && frac >= bca->min_frac )
164 indel_support_ok = 1;
165 if ( na > bca->max_support && frac > 0 )
166 bca->max_support = na, bca->max_frac = frac;
167
168 n_alt += na;
169 n_tot += nt;
170 }
171
172 // Sort aux[] and dedup
173 ks_introsort(uint32_t, m, aux);
174 for (i = 1, n_types = 1; i < m; ++i)
175 if (aux[i] != aux[i-1]) ++n_types;
176
177 // Taking totals makes it hard to call rare indels (IMF filter)
178 if ( !bca->per_sample_flt )
179 indel_support_ok = ( (double)n_alt / n_tot < bca->min_frac
180 || n_alt < bca->min_support )
181 ? 0 : 1;
182 if ( n_types == 1 || !indel_support_ok ) { // then skip
183 free(aux);
184 return NULL;
185 }
186
187 // Bail out if we have far too many types of indel
188 if (n_types >= MAX_TYPES) {
189 free(aux);
190 // TODO revisit how/whether to control printing this warning
191 if (hts_verbose >= 2)
192 fprintf(bcftools_stderr, "[%s] excessive INDEL alleles at position %d. "
193 "Skip the position.\n", __func__, pos + 1);
194 return NULL;
195 }
196
197 // To prevent long stretches of N's to be mistaken for indels
198 // (sometimes thousands of bases), check the number of N's in the
199 // sequence and skip places where half or more reference bases are Ns.
200 int nN=0, i_end = pos + (2*bca->indel_win_size < max_rd_len
201 ?2*bca->indel_win_size : max_rd_len);
202 for (i=pos; i<i_end && ref[i]; i++)
203 nN += ref[i] == 'N';
204 if ( nN*2>(i-pos) ) {
205 free(aux);
206 return NULL;
207 }
208
209 // Finally fill out the types[] array detailing the size of insertion
210 // or deletion.
211 types = (int*)calloc(n_types, sizeof(int));
212 if (!types) {
213 free(aux);
214 return NULL;
215 }
216 t = 0;
217 for (i = 0; i < m; ++i) {
218 int sz = (int32_t)(aux[i] - MINUS_CONST);
219 int j;
220 for (j = i+1; j < m; j++)
221 if (aux[j] != aux[i])
222 break;
223
224 if (sz == 0
225 || (j-i >= bca->min_support &&
226 // Note, doesn't handle bca->per_sample_flt yet
227 (bca->per_sample_flt
228 || (double)(j-i) / n_tot >= bca->min_frac)))
229 types[t++] = sz;
230 i = j-1;
231 }
232 free(aux);
233
234 if (t <= 1) {
235 free(types);
236 return NULL;
237 }
238 n_types = t;
239
240 // Find reference type; types[?] == 0)
241 for (t = 0; t < n_types; ++t)
242 if (types[t] == 0) break;
243
244 *ref_type_r = t;
245 *n_types_r = n_types;
246 *max_rd_len_r = max_rd_len;
247 *N_r = N;
248
249 return types;
250 }
251
252 // Increment ins["str"] and freq["str"]
253 #define NI 100 // number of alternative insertion sequences
254 // Could use a hash table too, but expectation is a tiny number of alternatives
255 typedef struct {
256 char *str[NI];
257 int len[NI];
258 int freq[NI];
259 } str_freq;
260
261 static int bcf_cgp_append_cons(str_freq *sf, char *str, int len, int freq) {
262 int j;
263
264 for (j = 0; j < NI && sf->str[j]; j++) {
265 if (sf->len[j] == len && memcmp(sf->str[j], str, len) == 0)
266 break;
267 }
268 if (j >= NI)
269 return 0; // too many choices; discard
270
271 sf->freq[j]+=freq;
272 if (!sf->str[j]) {
273 // new insertion
274 if (!(sf->str[j] = malloc(len+1)))
275 return -1;
276 memcpy(sf->str[j], str, len);
277 sf->len[j] = len;
278 }
279
280 return 0;
281 }
282
283 /*
284 * Compute the consensus for a specific indel type at pos.
285 *
286 * left_shift is the number of inserted(+) or deleted(-) bases added to
287 * the consensus before we get to pos. This is necessary so the alignment
288 * band is correct as it's expected to start at left/right edges in
289 * sync
290 *
291 * We accumulate into several buffers for counting base types:
292 * cons_base - consensus of data with p->indel == type, bases or gap
293 * ref_base - consensus of data with p->indel != type, bases or gap
294 * cons_ins - consensus of data with p->indel == type, insertions
295 * ref_ins - consensus of data with p->indel == type, bases or gap
296 *
297 * The purpose of cons_ins vs cons_base is if we have very low
298 * coverage due to nearly all reads being another type, then we can
299 * still get a robust consensus using the other data. If we don't
300 * have shallow data, then we'll not use as much of ref_base as we may
301 * have correlated variants.
302 *
303 * Eg:
304 * REF: AGCTATGAGGCTGATA
305 * SEQ: AGGTAGGAGGGTGATA (x1)
306 * SEQ: AGCTACGAGG*TGATA (x24)
307 * SEQ: AGCTACTAGG*TGATA (x24)
308 *
309 * Cons for no-del is Cs not Gs. Cannot trust it, so use N if shallow.
310 * CON: AGCTACNAGGGTGATA
311 *
312 * There are still some problems in cons_ins vs ref_ins assignment.
313 * We sometimes seem multiple similar-length insertions added at
314 * different locations. Ideally we'd like to consider these as all
315 * the same insertion if the size is the same and it's comparable seq.
316 */
317 #define MAX_INS 8192
318 static char **bcf_cgp_consensus(int n, int *n_plp, bam_pileup1_t **plp,
319 int pos, bcf_callaux_t *bca, const char *ref,
320 int ref_len, int left, int right,
321 int sample, int type, int biggest_del,
322 int *left_shift, int *right_shift,
323 int *band, int *tcon_len, int *cpos_pos,
324 int pos_l, int pos_r) {
325 // Map ASCII ACGTN* to 012345
326 static uint8_t base6[256] = {
327 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,
328 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,
329 //A C G *^ T
330 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,
331 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,
332
333 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,
334 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,
335 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,
336 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,
337 };
338
339 // single base or del
340 int (*cons_base)[6] = calloc(right - left + 1, sizeof(*cons_base));
341 // multi-base insertions
342 str_freq *cons_ins = calloc(right - left + 1, sizeof(*cons_ins));
343
344 // non-indel ref for all reads on this sample, rather than those just
345 // matching type. We use this for handling the case where we have a
346 // homozygous deletion being studied, but with 1 or 2 reads misaligned
347 // and containing a base there.
348 //
349 // Eg if the type[]=0 consensus is made up of a very small sample size,
350 // which is also enriched for highly error prone data. We can use
351 // the other reads from type[] != 0 to flesh out the consensus and
352 // improve accuracy.
353 int (*ref_base)[6] = calloc(right - left + 1, sizeof(*ref_base));
354 str_freq *ref_ins = calloc(right - left + 1, sizeof(*ref_ins));
355 int i, j, k, s = sample;
356 char **cons = NULL;
357
358 if (!cons_base || !cons_ins || !ref_base || !ref_ins)
359 goto err;
360
361 //--------------------------------------------------
362 // Accumulate sequences into cons_base and cons_ins arrays
363 int local_band_max = 0; // maximum absolute deviation from diagonal
364 int total_span_str = 0;
365 int type_depth = 0;
366 for (i = 0; i < n_plp[s]; i++) {
367 const bam_pileup1_t *p = plp[s] + i;
368 bam1_t *b = p->b;
369 int x = b->core.pos; // ref coordinate
370 int y = 0; // seq coordinate
371 uint32_t *cigar = bam_get_cigar(b);
372 uint8_t *seq = bam_get_seq(b);
373
374 int local_band = 0; // current deviation from diagonal
375 for (k = 0; k < b->core.n_cigar; ++k) {
376 int op = cigar[k] & BAM_CIGAR_MASK;
377 int len = cigar[k] >> BAM_CIGAR_SHIFT;
378 int base;
379 int skip_to = 0;
380
381 switch(op) {
382 case BAM_CSOFT_CLIP:
383 y += len;
384 break;
385
386 case BAM_CMATCH:
387 case BAM_CEQUAL:
388 case BAM_CDIFF: {
389 // Can short-cut this with j_start and j_end based on
390 // x+len and left,right
391 for (j = 0; j < len; j++, x++, y++) {
392 if (x < left) continue;
393 if (x >= right) break;
394
395 base = bam_seqi(seq, y);
396 if (p->indel == type)
397 // Convert 4-bit base ambig code to 0,1,2,3,4 range
398 cons_base[x-left][seq_nt16_int[base]]++;
399 else if (x != pos+1) // indel being assessed question
400 ref_base[x-left][seq_nt16_int[base]]++;
401 }
402 break;
403 }
404
405 case BAM_CINS: {
406 if (x >= left && x < right) {
407 local_band += p->indel;
408 if (local_band_max < local_band)
409 local_band_max = local_band;
410 }
411
412 char ins[MAX_INS];
413 for (j = 0; j < len; j++, y++) {
414 if (x < left) continue;
415 if (x >= right)
416 break;
417 base = bam_seqi(seq, y);
418 if (j < MAX_INS)
419 ins[j] = seq_nt16_int[base];
420 }
421
422 // Insertions come before a ref match.
423 // 5I 5M is IIIIIM M M M M events, not
424 // {IIIII,M} M M M M choice. So we need to include the
425 // next match in our sequence when choosing the consensus.
426 if (x >= left && x < right) {
427 int ilen = j<MAX_INS?j:MAX_INS;
428 if (p->indel == type /*&& x == pos+1*/) {
429 // Assume any ins of the same size is the same ins.
430 // (This rescues misaligned insertions.)
431 if (bcf_cgp_append_cons(&cons_ins[x-left], ins,
432 ilen, 1) < 0)
433 goto err;
434 type_depth += (x == pos+1);
435 } else if (x != pos+1){
436 if (bcf_cgp_append_cons(&ref_ins[x-left], ins,
437 ilen, 1) < 0)
438 goto err;
439 }
440 }
441 break;
442 }
443
444 case BAM_CDEL:
445 if (x >= left && x < right) {
446 local_band += p->indel;
447 if (local_band_max < -local_band)
448 local_band_max = -local_band;
449 }
450
451 // Maybe not perfect for I/D combos, but likely sufficient.
452 for (j = 0; j < len; j++, x++) {
453 if (x < left) continue;
454 if (x >= right) break;
455 if ((p->indel == type && !p->is_del) || // starts here
456 (p->indel == 0 && p->is_del && len == -type)) { // left
457 cons_base[x-left][5]++;
458 type_depth += (x == pos+1);
459 } else if (x+len <= pos+1 || (skip_to && x > skip_to))
460 ref_base[x-left][5]++;
461 else if (x <= pos && x+len > pos+1) {
462 // we have a deletion which overlaps pos, but
463 // isn't the same "type". We don't wish to
464 // include these as they may bias the
465 // evaluation by confirming against a
466 // secondary consensus produced with the other
467 // deletion. We set a marker for how long to
468 // skip adding to ref_base.
469 if (x > skip_to)
470 skip_to = x+len;
471 }
472 }
473 break;
474 }
475 }
476
477 if (b->core.pos <= pos_l && x >= pos_r)
478 total_span_str++;
479
480 // Also track the biggest deviation +/- from diagonal. We use
481 // this band observation in our BAQ alignment step.
482 if (*band < local_band_max)
483 *band = local_band_max;
484 }
485
486 //--------------------------------------------------
487 // Expand cons_base to include depth from ref_base/ref_ins
488 // Caveat: except at pos itself, where true ref is used if type != 0
489
490 #if 1 // TEST 1
491 // We could retest this heuristic further maybe.
492 for (i = 0; i < right-left; i++) {
493 // Total observed depth
494 int t = cons_base[i][0] + cons_base[i][1] + cons_base[i][2] +
495 cons_base[i][3] + cons_base[i][4] + cons_base[i][5];
496 for (j = 0; j < NI; j++) {
497 if (!cons_ins[i].str[j])
498 break;
499 t += cons_ins[i].freq[j];
500 }
501
502 // Similarly for depth on the non-ALT calls (NB: not necessarily
503 // REF as maybe it's other ALTs).
504 int r = ref_base[i][0] + ref_base[i][1] + ref_base[i][2] +
505 ref_base[i][3] + ref_base[i][4] + ref_base[i][5];
506 for (j = 0; j < NI; j++) {
507 if (!ref_ins[i].str[j])
508 break;
509 r += ref_ins[i].freq[j];
510 }
511
512 // When evaluating this particular indel, we don't want to
513 // penalise alignments by SNP errors elsewhere. This can
514 // happen when we have low depth for a particular 'type'.
515 //
516 // So add in a little data from ref_base/ref_ins.
517 double rfract = (r - t*2)*.75 / (r+1);
518
519 if (rfract < 1.01 / (r+1e-10))
520 rfract = 1.01 / (r+1e-10); // low depth compensation
521 // if (rfract > 0.2)
522 // rfract = 0.2;
523
524 // TODO: consider limiting rfract so we never drown out the
525 // signal. We want to use the remaining data only to correct
526 // for sequencing errors in low depth alleles. If we get
527 // conflicts, it's better to use N than to change a base
528 // incase that variant is genuine.
529 if (i+left >= pos+1 && i+left < pos+1-biggest_del) {
530 // We're overlapping the current indel region, so
531 // we don't wish to bring in evidence from the other
532 // "type" data as it'll harm calling.
533 continue;
534 } else {
535 // Otherwise add in a portion of other data to
536 // boost low population numbers.
537 cons_base[i][0] += rfract * ref_base[i][0];
538 cons_base[i][1] += rfract * ref_base[i][1];
539 cons_base[i][2] += rfract * ref_base[i][2];
540 cons_base[i][3] += rfract * ref_base[i][3];
541 cons_base[i][4] += rfract * ref_base[i][4];
542 cons_base[i][5] += rfract * ref_base[i][5];
543 }
544
545 // Similarly for insertions too; consider a different rfract here?
546 for (j = 0; j < NI; j++) {
547 if (!ref_ins[i].str[j])
548 break;
549 if (bcf_cgp_append_cons(&cons_ins[i],
550 ref_ins[i].str[j], ref_ins[i].len[j],
551 rfract * ref_ins[i].freq[j]) < 0)
552 goto err;
553 }
554 }
555 #endif
556
557 //--------------------------------------------------
558 // Allocate consensus buffer, to worst case length
559 int max_len = right-left;
560 for (i = 0; i < right-left; i++) {
561 if (!cons_ins[i].str[0])
562 continue;
563
564 int ins = 0;
565 for (j = 0; j < NI; j++) {
566 if (!cons_ins[i].str[j])
567 break;
568 if (cons_ins[i].str[j] && ins < cons_ins[i].len[j])
569 ins = cons_ins[i].len[j];
570 }
571 max_len += ins;
572 }
573 max_len += MAX(0, type); // incase type inserted bases never occur
574 cons = malloc((max_len+1)*2 + sizeof(char *)*2);
575 if (!cons)
576 goto err;
577 cons[0] = (char *)&cons[2];
578 cons[1] = cons[0] + max_len+1;
579
580 //--------------------------------------------------
581 // Merge insertions where they are the same length but different
582 // sequences.
583 // NB: we could just index by length and have accumulators for each,
584 // instead of storing separately and merging later (here).
585 // Ie str_freq.str is [NI][5] instead.
586 for (i = 0; i < right-left; i++) {
587 int ins[MAX_INS][5];
588 for (j = 0; j < NI; j++) {
589 if (!cons_ins[i].str[j])
590 break;
591
592 if (cons_ins[i].freq[j] == 0)
593 continue; // already merged
594
595 int l;
596 for (l = 0; l < cons_ins[i].len[j]; l++) {
597 // Append to relevant frequency counter, zero all others
598 ins[l][0] = ins[l][1] = ins[l][2] = ins[l][3] = ins[l][4] = 0;
599 uint8_t b = cons_ins[i].str[j][l];
600 ins[l][b] = cons_ins[i].freq[j];
601 }
602
603 // Merge other insertions of the same length to ins[] counters
604 for (k = j+1; k < NI; k++) {
605 if (!cons_ins[i].str[k])
606 break;
607 if (cons_ins[i].len[k] != cons_ins[i].len[j])
608 continue;
609 if (cons_ins[i].freq[k] == 0)
610 continue; // redundant?
611
612 // Merge str[j] and str[k]
613 for (l = 0; l < cons_ins[i].len[k]; l++) {
614 uint8_t b = cons_ins[i].str[k][l];
615 ins[l][b] += cons_ins[i].freq[k];
616 }
617 cons_ins[i].freq[j] += cons_ins[i].freq[k];
618 cons_ins[i].freq[k] = 0;
619 }
620
621 // Now replace ins[j] with the consensus insertion of this len.
622 for (l = 0; l < cons_ins[i].len[j]; l++) {
623 int max_v = 0, base = 0;
624 int tot = ins[l][0] + ins[l][1] + ins[l][2]
625 + ins[l][3] + ins[l][4];
626 if (max_v < ins[l][0]) max_v = ins[l][0], base = 0;
627 if (max_v < ins[l][1]) max_v = ins[l][1], base = 1;
628 if (max_v < ins[l][2]) max_v = ins[l][2], base = 2;
629 if (max_v < ins[l][3]) max_v = ins[l][3], base = 3;
630 if (max_v < ins[l][4]) max_v = ins[l][4], base = 4;
631
632 cons_ins[i].str[j][l] = (max_v > 0.6*tot) ? base : 4;
633 }
634 }
635 }
636
637 #define CONS_CUTOFF .40 // % needed for base vs N
638 #define CONS_CUTOFF_DEL .35 // % to include any het del
639 #define CONS_CUTOFF2 .80 // % needed for gap in cons[1]
640 #define CONS_CUTOFF_INC .35 // % to include any insertion cons[0]
641 #define CONS_CUTOFF_INC2 .80 // % to include any insertion cons[1] HOM
642 #define CONS_CUTOFF_INS .60 // and then 60% needed for it to be bases vs N
643
644 //--------------------------------------------------
645 // Walk through the frequency arrays to call the consensus.
646 // We produce cons[0] and cons[1]. Both include strongly
647 // homozygous indels. Both also include the indel at 'pos'.
648 // However for heterozygous indels we call the most likely event
649 // for cons[0] and the less-likely alternative in cons[1].
650 // TODO: a proper phase analysis so multiple events end up
651 // combining together into the correct consensus.
652 *left_shift = 0;
653 *right_shift = 0;
654 int cnum;
655
656 // Het call filled out in cnum==0 (+ve or -ve).
657 // Used in cnum==1 to do the opposite of whichever way we did before.
658 int heti[MAX_INS] = {0}, hetd[MAX_INS] = {0};
659
660 *cpos_pos = -1;
661 for (cnum = 0; cnum < 2; cnum++) {
662 for (i = k = 0; i < right-left; i++) {
663 // Location in consensus matching the indel itself
664 if (i >= pos-left+1 && *cpos_pos == -1)
665 *cpos_pos = k;
666
667 int max_v = 0, max_v2 = 0, max_j = 4, max_j2 = 4, tot = 0;
668 for (j = 0; j < 6; j++) {
669 // Top 2 consensus calls
670 if (max_v < cons_base[i][j]) {
671 max_v2 = max_v, max_j2 = max_j;
672 max_v = cons_base[i][j], max_j = j;
673 } else if (max_v2 < cons_base[i][j]) {
674 max_v2 = cons_base[i][j], max_j2 = j;
675 }
676 tot += cons_base[i][j];
677 }
678
679 // +INS
680 int max_v_ins = 0, max_j_ins = 0;
681 int tot_ins = 0;
682 for (j = 0; j < NI; j++) {
683 if (i+left==pos+1)
684 if (type > 0 && i+left == pos+1
685 && cons_ins[i].len[j] < type && j == 0) {
686 cons_ins[i].str[j] = realloc(cons_ins[i].str[j], type);
687 if (!cons_ins[i].str[j])
688 goto err;
689 memset(cons_ins[i].str[j] + cons_ins[i].len[j],
690 4, type - cons_ins[i].len[j]);
691 cons_ins[i].len[j] = type;
692 }
693 if (!cons_ins[i].str[j])
694 break;
695 if (cons_ins[i].freq[j] == 0)
696 continue; // previously merged
697
698 if (max_v_ins < cons_ins[i].freq[j])
699 //if (i != pos-left+1 || cons_ins[i].len[j] == type)
700 max_v_ins = cons_ins[i].freq[j], max_j_ins = j;
701 tot_ins += cons_ins[i].freq[j];
702 }
703
704 // NB: tot is based on next matching base, so it includes
705 // everything with or without the insertion.
706 int tot_sum = tot;
707 int always_ins =
708 (i == pos-left+1 && type>0) || // current eval
709 max_v_ins > CONS_CUTOFF_INC2*tot_sum;// HOM
710 int het_ins = 0;
711 if (!always_ins && max_v_ins >= bca->min_support) {
712 // Candidate HET ins.
713 if (cnum == 0) {
714 het_ins = max_v_ins > CONS_CUTOFF_INC * tot_sum;
715 if (i < MAX_INS) heti[i] = het_ins
716 ? 1
717 : (max_v_ins > .3*tot_sum ? -1:0);
718 } else {
719 // HET but uncalled before
720 het_ins = i < MAX_INS ? (heti[i] == -1) : 0;
721 }
722 }
723
724 if (always_ins || het_ins) {
725 if (max_v_ins > CONS_CUTOFF_INS*tot_ins) {
726 // Insert bases
727 for (j = 0; j < cons_ins[i].len[max_j_ins]; j++) {
728 if (cnum == 0) {
729 if (k < pos-left+*left_shift)
730 (*left_shift)++;
731 else
732 (*right_shift)++;
733 }
734 cons[cnum][k++] = cons_ins[i].str[max_j_ins][j];
735 }
736 } else {
737 for (j = 0; j < cons_ins[i].len[max_j_ins]; j++)
738 cons[cnum][k++] = 4; // 'N';
739 }
740 }
741
742 // Call deletions & bases
743 int always_del = (type < 0 && i > pos-left && i <= pos-left-type)
744 || cons_base[i][5] > CONS_CUTOFF2 * tot; // HOM del
745 int het_del = 0;
746 if (!always_del && cons_base[i][5] >= bca->min_support) {
747 // Candidate HET del.
748 if (cnum == 0) {
749 int tot2 = tot;
750 if (i > pos-left && i <= pos-left-biggest_del)
751 tot2 = total_span_str - type_depth;
752 het_del = cons_base[i][5] >= CONS_CUTOFF_DEL * tot2;
753
754 if (i < MAX_INS) {
755 if (i > pos-left && i <= pos-left-biggest_del)
756 hetd[i] = 0;
757 else
758 hetd[i] = het_del
759 ? 1
760 : (cons_base[i][5] >= .3 * tot2 ? -1 : 0);
761 }
762 } else {
763 // HET del uncalled on cnum 0
764 het_del = i < MAX_INS ? (hetd[i] == -1) : 0;
765 if (max_j == 5 && het_del == 0) {
766 max_v = max_v2;
767 max_j = max_j2;
768 }
769 }
770 }
771 if (always_del || het_del) {
772 // Deletion
773 if (k < pos-left+*left_shift)
774 (*left_shift)--;
775 else
776 (*right_shift)++;
777 } else {
778 // Finally the easy case - a non-indel base or an N
779 if (max_v > CONS_CUTOFF*tot)
780 cons[cnum][k++] = max_j; // "ACGTN*"
781 else if (max_v > 0)
782 cons[cnum][k++] = 4; // 'N';
783 else {
784 cons[cnum][k] = left+k < ref_len
785 ? base6[(uint8_t)ref[left+k]]
786 : 4;
787 k++;
788 }
789 }
790 }
791
792 tcon_len[cnum] = k;
793 }
794
795 // TODO: replace by io_lib's string pool for rapid tidying.
796 // For now this isn't the bottleneck though.
797 for (i = 0; i < right-left; i++) {
798 for (j = 0; j < NI; j++) {
799 if (cons_ins[i].str[j])
800 free(cons_ins[i].str[j]);
801 if (ref_ins[i].str[j])
802 free(ref_ins[i].str[j]);
803 }
804 }
805
806 err:
807 free(cons_base);
808 free(ref_base);
809 free(cons_ins);
810 free(ref_ins);
811
812 return cons;
813 }
814
815 // A rename of bcf_cgp_calc_cons from bam2bcf_indel.c
816 //
817 // Compute the insertion consensus for this sample 's' via a basic
818 // majority rule.
819 //
820 // TODO: merge this into bcf_cgp_consensus as another return value?
821 static char *bcf_cgp_calc_ins_cons(int n, int *n_plp, bam_pileup1_t **plp,
822 int pos, int *types, int n_types,
823 int max_ins, int s) {
824 return bcf_cgp_calc_cons(n, n_plp, plp, pos, types, n_types, max_ins, s);
825 }
826
827 #define MAX(a,b) ((a)>(b)?(a):(b))
828 #define MIN(a,b) ((a)<(b)?(a):(b))
829
830 // Compile with LIBS="-L. -ldl -ledlib" CLD=g++
831
832 // This is faster than ksw and BAQ, meaning we can use larger --indel-size and
833 // get a more accurate context, improving alignments further. This *may*
834 // compensate for reduced sensitivity.
835 #include "edlib.h"
836 int edlib_glocal(uint8_t *ref, int l_ref, uint8_t *query, int l_query,
837 double m, double del_bias)
838 {
839 EdlibAlignConfig cfg =
840 edlibNewAlignConfig(
841 //ABS(type)+ABS(l_ref-l_query)+10,
842 -1, // k; use small positive for faster alignment
843 EDLIB_MODE_HW, // mode
844 #ifdef ALIGN_DEBUG
845 EDLIB_TASK_PATH,
846 #else
847 EDLIB_TASK_LOC,
848 #endif
849 NULL, // additionalEqualities
850 0); // additionalEqualitiesLength
851 EdlibAlignResult r =
852 edlibAlign((char *)query, l_query, (char *)ref, l_ref, cfg);
853
854 if (r.status != EDLIB_STATUS_OK || r.numLocations < 1 ||
855 !r.endLocations || !r.startLocations) {
856 edlibFreeAlignResult(r);
857 return INT_MAX;
858 }
859
860 #ifdef ALIGN_DEBUG
861 // NB: Needs linking against the C++ libedlib.a as our cut-down C
862 // implementation misses the alignment generation code.
863 {
864 int i, j = 0, pt = r.startLocations[0], pq = 0;
865 char line1[80];
866 char line2[80];
867 char line3[80];
868 for (i = 0; i < r.alignmentLength && pt < r.endLocations[0]; i++) {
869 int n;
870 switch (n = r.alignment[i]) {
871 case 0: // match
872 case 3: // mismatch
873 line1[j] = "ACGTN"[ref[pt++]];
874 line2[j] = "ACGTN"[query[pq++]];
875 line3[j] = " x"[n==3];
876 break;
877 case 2: // insertion to ref
878 line1[j] = "ACGTN"[ref[pt++]];
879 line2[j] = '-';
880 line3[j] = '-';
881 break;
882 case 1: // insertion to query
883 line1[j] = '-';
884 line2[j] = "ACGTN"[query[pq++]];
885 line3[j] = '+';
886 break;
887 }
888
889 if (++j == sizeof(line1)) {
890 fprintf(bcftools_stderr, "%.*s\n", j, line1);
891 fprintf(bcftools_stderr, "%.*s\n", j, line2);
892 fprintf(bcftools_stderr, "%.*s\n", j, line3);
893 j = 0;
894 }
895 }
896 if (j) {
897 fprintf(bcftools_stderr, "%.*s\n", j, line1);
898 fprintf(bcftools_stderr, "%.*s\n", j, line2);
899 fprintf(bcftools_stderr, "%.*s\n", j, line3);
900 }
901 }
902 #endif
903
904 // Aligned target length minus query length is an indication of the number
905 // of insertions and/or deletions.
906 //
907 // For CIGAR 10M1I10M t_len > l_query ("AC" / "ATC")
908 // For CIGAR 10M1D10M t_len < l_query ("ATC" / "AC")
909 // Hence t_len-l_query is -ve for net insertions and +ve for net deletions.
910 // If we compute nins and ndel directly via walking though EDLIB_TASK_PATH
911 // we'll see t_len-l_query == ndel-nins.
912 //
913 // If a technology has a significantly higher chance of making deletion
914 // errors than insertion errors, then we would view deletions as less
915 // indicative of this sequence not coming from this candidate allele than
916 // if it had insertion (as the deletions are more likely to be errors
917 // rather than real, relative to the insertions). Hence we can skew the
918 // score by the net delta of num_del - num_ins.
919 //
920 // Note this is an approximation that doesn't account for multiple
921 // insertions and deletions within the same sequence, but it is much faster
922 // as it doesn't require EDLIB_TASK_PATH to be computed.
923 //
924 // Given editDistance is +1 for every mismatch, insertion and deletion,
925 // provided the t_len-l_query multiplier < 1 then this is always +ve.
926
927 int t_len = *r.endLocations - *r.startLocations + 1;
928 int score = m*(r.editDistance - del_bias*(t_len - l_query));
929
930 edlibFreeAlignResult(r);
931 return score;
932 }
933
934 // Part of bcf_call_gap_prep.
935 //
936 // Realign using BAQ to get an alignment score of a single read vs
937 // a haplotype consensus. TODO: replace BAQ with something more robust.
938 //
939 // There are many coordinates, so let's explain them.
940 // - left, right, tbeg, tend, r_start and r_end are in aligned reference
941 // coordinates.
942 // left/right start from pos +/- indel_win_size.
943 // r_start/r_end are the BAM first and last mapped coord on the reference.
944 // tbeg and tend are the intersection of the two.
945 // - qbeg and qend are in BAM sequence coordinates
946 // - qpos is in sequence coordinates, relative to qbeg.
947 //
948 // To see what this means, we have illustrations with coordinates
949 // above the seqs in reference space and below the seqs in BAM seq space.
950 //
951 // Overlap left:
952 // tbeg tend
953 // r_start left pos r_end right
954 // REF :..............|--------------------#------:--------------|...
955 // SEQ :..............|--------------------#------|
956 // 0 qbeg qpos qend
957 //
958 // Overlap right:
959 // r_start tend
960 // left tbeg pos right r_end
961 // REF ...|--------------:-----#---------------------|...........:
962 // SEQ |-----#---------------------|...........:
963 // qbeg qpos qend
964 // 0
965 //
966 // The "-" sequence is the bit passed in.
967 // Ie ref2 spans left..right and query spans qbeg..qend.
968 // We need to adjust ref2 therefore to tbeg..tend.
969 //
970 // Fills out score
971 // Returns 0 on success,
972 // <0 on error
973 static int bcf_cgp_align_score(bam_pileup1_t *p, bcf_callaux_t *bca,
974 int type, int band,
975 uint8_t *ref1, uint8_t *ref2, uint8_t *query,
976 int r_start, int r_end,
977 int tbeg, int tend1, int tend2,
978 int left, int right,
979 int qbeg, int qend,
980 int pos, int qpos, int max_deletion,
981 double qavg, double del_bias, int *score,
982 int *str_len1_p, int *str_len2_p) {
983 int atype = abs(type);
984 int l, sc1, sc2;
985
986 // Trim poly_Ns at ends of ref.
987 // This helps to keep len(ref) and len(query) similar, to reduce
988 // band size and reduce the chance of -ve BAQ scores.
989 for (l = 0; l < tend1-tbeg && l < tend2-tbeg; l++)
990 if (ref1[l + tbeg-left] != 4 || ref2[l + tbeg-left] != 4)
991 break;
992 if (l > atype)
993 tbeg += l-atype;
994
995 for (l = tend1-tbeg-1; l >= 0; l--)
996 if (ref1[l + tbeg-left] != 4)
997 break;
998 l = tend1-tbeg-1 - l;
999 if (l > atype)
1000 tend1 -= l-atype;
1001
1002 for (l = tend2-tbeg-1; l >= 0; l--)
1003 if (ref2[l + tbeg-left] != 4)
1004 break;
1005 l = tend2-tbeg-1 - l;
1006 if (l > atype) {
1007 tend2 -= l-atype;
1008 }
1009
1010 // The bottom 8 bits are length-normalised score while
1011 // the top bits are unnormalised.
1012 //
1013 // Try original cons and new cons and pick best.
1014 // This doesn't reduce FN much (infact maybe adds very slightly),
1015 // but it does reduce GT errors and is a slight reduction to FP.
1016
1017 double mm = 30; // a const average qual for now. Could tune
1018 sc2 = edlib_glocal(ref2 + tbeg - left, tend2 - tbeg,
1019 query, qend - qbeg, mm, del_bias);
1020
1021 if (tend1 != tend2 ||
1022 memcmp((char *)ref1 + tbeg - left, (char *)ref2 + tbeg - left,
1023 tend1 - tbeg) != 0)
1024 sc1 = edlib_glocal(ref1 + tbeg - left, tend1 - tbeg,
1025 query, qend - qbeg, mm, del_bias);
1026 else
1027 sc1 = INT_MAX; // skip
1028
1029 // Find the best of the two alignments
1030 if (sc1 < 0 && sc2 < 0) {
1031 *score = 0xffffff;
1032 return 0;
1033 }
1034 if (sc1 < 0) {
1035 // sc2 is already correct
1036 } else if (sc2 < 0) {
1037 sc2 = sc1;
1038 } else {
1039 // sc1 and sc2 both pass, so use best
1040 if (sc2 > sc1)
1041 sc2 = sc1;
1042 }
1043
1044 // Sc is overall alignment score, in top 24 bits (SeqQ). It's based
1045 // purely on the scores for the whole alignment.
1046 // We also have a separate indel score in bottom 8 bits (IndelQ).
1047 // This is a function of all sorts of attributes of the candidate indel
1048 // itself, such as STR length and the presence of poor quality bases.
1049
1050 // Used for adjusting indelQ below. Lower l is more likely to call
1051 // (--FN, ++FP). (NB CLI --indel_bias is 1/indel_bias var).
1052 // Starts as average score per base, and then adjusted based on seq
1053 // complexity / quality.
1054
1055 l = .5*(100. * sc2 / (qend - qbeg) + .499);
1056
1057 *score = (sc2<<8) | (int)MIN(255, l * bca->indel_bias * .5);
1058
1059 return 0;
1060 }
1061
1062 // Part of bcf_call_gap_prep.
1063 //
1064 // Returns n_alt on success
1065 // -1 on failure
1066
1067 // TODO: almost identical to bam2bcf_indel.c's copy, so we could share
1068 // the code and add a check on bca->edlib.
1069 static int bcf_cgp_compute_indelQ(int n, int *n_plp, bam_pileup1_t **plp,
1070 bcf_callaux_t *bca, char *inscns,
1071 int l_run, int max_ins,
1072 int ref_type, int *types, int n_types,
1073 double qavg, int *score,
1074 int str_len1, int str_len2) {
1075 // FIXME: n_types has a maximum; no need to alloc - use a #define?
1076 int sc[MAX_TYPES], sumq[MAX_TYPES], s, i, j, t, K, n_alt, tmp;
1077 memset(sumq, 0, n_types * sizeof(int));
1078 int sum_indelQ1[100] = {0}; // n
1079 int sum_indelQ2[100] = {0}; // n
1080
1081 // Confusing variable naming and bit usage.
1082 //
1083 // score[] is low 8 bits normalised (by len) alignment score
1084 // top 24 bits full alignment score
1085 // This gets cast into "sct"; mnemonic score-per-indel-type.
1086 //
1087 // sc = (score<<6) | type (index to types[] array for indel size)
1088 // So sc>>14 = score>>(14-6) = score>>8. Ie full alignment score
1089 for (s = K = 0; s < n; ++s) {
1090 for (i = 0; i < n_plp[s]; ++i, ++K) {
1091 bam_pileup1_t *p = plp[s] + i;
1092 // Labelling is confusing here.
1093 // sct is short for score.
1094 // sc is score + t(type)
1095 // Why aren't these variable names reversed?
1096 int *sct = &score[K*n_types], seqQ, indelQ1=0, indelQ2=0, indelQ=0;
1097 for (t = 0; t < n_types; ++t) sc[t] = sct[t]<<6 | t;
1098 for (t = 1; t < n_types; ++t) // insertion sort
1099 for (j = t; j > 0 && sc[j] < sc[j-1]; --j)
1100 tmp = sc[j], sc[j] = sc[j-1], sc[j-1] = tmp;
1101
1102 #ifdef ALIGN_DEBUG
1103 fprintf(bcftools_stderr, "READ %s\tscores ", bam_get_qname(p->b));
1104 for (t = 0; t < n_types; ++t) {
1105 fprintf(bcftools_stderr, "%+2d/%-3d ", types[sc[t]&0x3f], sc[t]>>14);
1106 }
1107 #endif
1108
1109 /* errmod_cal() assumes that if the call is wrong, the
1110 * likelihoods of other events are equal. This is about
1111 * right for substitutions, but is not desired for
1112 * indels. To reuse errmod_cal(), I have to make
1113 * compromise for multi-allelic indels.
1114 */
1115 if ((sc[0]&0x3f) == ref_type) {
1116 // sc >> 14 is the total score. It's been shifted by 8
1117 // from normalised score and 6 from type.
1118 // &0x3f is type number
1119
1120 // Best call is REF. Compare vs best indel
1121 indelQ = (sc[1]>>14) - (sc[0]>>14);
1122 seqQ = est_seqQ(bca, types[sc[1]&0x3f], l_run, str_len1);
1123 } else {
1124 // look for the reference type
1125 for (t = 0; t < n_types; ++t) {
1126 if ((sc[t]&0x3f) == ref_type)
1127 break;
1128 }
1129 indelQ = indelQ1 = (sc[t]>>14) - (sc[0]>>14);
1130 // fprintf(bcftools_stderr, "IndelQ = %d: %d-%d",
1131 // indelQ, (sc[t]>>14), (sc[0]>>14));
1132
1133 // Best call is non-ref, compare vs next best non-ref,
1134 // or ref if it's just 2 choices (most common case).
1135 for (t = 1; t < n_types; t++)
1136 if ((sc[t]&0x3f) == ref_type)
1137 continue;
1138 else break;
1139 if (t == n_types)
1140 t--; // it's ref, but it'll do as next best.
1141 indelQ2 = (sc[t]>>14) - (sc[0]>>14);
1142 seqQ = est_seqQ(bca, types[sc[0]&0x3f], l_run, str_len1);
1143
1144 #if 1 // TEST 3
1145 indelQ = bca->vs_ref*indelQ1 + (1-bca->vs_ref)*indelQ2;
1146 #endif
1147 }
1148
1149 // So we lower qual in some, but raise the average to keep FN/FP
1150 // ratios up.
1151 // Is this key diff for PacBio old vs new HiFi?
1152 indelQ /= bca->indel_bias*0.5;
1153 indelQ1 /= bca->indel_bias*0.5;
1154
1155 // Or maybe just *2 if bca->poly_mqual and be done with it?
1156 // Or perhaps adjust the MIN(qavg/20, ...) to MIN(qavg/10) ?
1157
1158 // Skew SeqQ and IndelQ based on a portion of the minimum quality
1159 // found within a homopolymer. This is useful where the quality
1160 // values are a bit mutable and move around in such data, but less
1161 // so on clocked sequencing technologies.
1162 //
1163 // Enabling this causes lots of GT errors on Illumina.
1164 // However on PacBio it's key to removal of false positives.
1165 // ONT and UG seem somewhere inbetween.
1166 if (bca->poly_mqual) { // TEST 4
1167 int qpos = p->qpos, l;
1168 uint8_t *seq = bam_get_seq(p->b);
1169 uint8_t *qual = bam_get_qual(p->b);
1170 int min_q = qual[qpos];
1171
1172 // scan homopolymer left
1173 char baseL = bam_seqi(seq, qpos+1 < p->b->core.l_qseq
1174 ? qpos+1 : qpos);
1175 for (l = qpos; l >= 0; l--) {
1176 if (bam_seqi(seq, l) != baseL)
1177 break;
1178 if (min_q > qual[l])
1179 min_q = qual[l];
1180 }
1181
1182 // scan homo-polymer right (including site of indel)
1183 char base = bam_seqi(seq, qpos+1);
1184 for (l = qpos+1; l < p->b->core.l_qseq; l++) {
1185 if (min_q > qual[l])
1186 min_q = qual[l];
1187 if (bam_seqi(seq, l) != base)
1188 break;
1189 }
1190
1191 // We reduce -h so homopolymers get reduced likelihood of being
1192 // called, but then optionally increase or decrease from there
1193 // based on base quality. Hence lack of low quality bases in
1194 // homopolymer will rescue the score back again, reducing FNs.
1195
1196 // The score factors here may also be machine specific, but for
1197 // now these work well (tuned on PB HiFi).
1198 seqQ += MIN(qavg/20, min_q - qavg/10);
1199 indelQ += MIN(qavg/20, min_q - qavg/5);
1200 indelQ1+= MIN(qavg/20, min_q - qavg/5);
1201
1202 if (seqQ < 0) seqQ = 0;
1203 if (indelQ < 0) indelQ = 0;
1204 if (indelQ1< 0) indelQ1= 0;
1205 }
1206
1207 // This is the length-normalised score from bcf_cgp_align_score
1208 tmp = sc[0]>>6 & 0xff;
1209
1210 // reduce indelQ
1211 // high score = bad, low score = good; flip for indelQ
1212 // low normalised scores leave indelQ unmodified
1213 // high normalised scores set indelQ to 0
1214 // inbetween scores have a linear scale from indelQ to 0
1215 // Altering the MAGIC value below (originally 111, but chosen for unknown
1216 // reasons) is comparable to altering --indel-bias.
1217 #define TMP_MAGIC 255.0
1218
1219 indelQ = tmp > TMP_MAGIC? 0 : (int)((1. - tmp/TMP_MAGIC) * indelQ + .499);
1220 indelQ1= tmp > TMP_MAGIC? 0 : (int)((1. - tmp/TMP_MAGIC) * indelQ1+ .499);
1221
1222 indelQ = MIN(indelQ, 255);
1223 indelQ1 = MIN(indelQ1, 255);
1224
1225 // Doesn't really help accuracy, but permits -h to take
1226 // affect still.
1227 if (indelQ > seqQ) indelQ = seqQ;
1228 if (indelQ > 255) indelQ = 255;
1229 if (indelQ1> 255) indelQ1= 255;
1230 if (seqQ > 255) seqQ = 255;
1231
1232 // Use 22 bits in total.
1233 // 0-7 IndelQ
1234 // 8-15 SeqQ
1235 // 16-22 Score-per-base
1236 p->aux = (sc[0]&0x3f)<<16 | seqQ<<8 | indelQ;
1237 sumq[sc[0]&0x3f] += indelQ;
1238
1239 #ifdef ALIGN_DEBUG
1240 fprintf(bcftools_stderr, "\t%d\t%d\n", indelQ, seqQ);
1241 #endif
1242
1243 // Experiment in p->aux vs sumq.
1244 // One gives likelihood of an indel being here, while the other
1245 // is likelihood of a specific genotype? But which is which?
1246
1247 sum_indelQ1[s] += indelQ1;
1248 sum_indelQ2[s] += indelQ;
1249 }
1250 }
1251
1252 // Determine bca->indel_types[] and bca->inscns.
1253 // Sumq[0] is always reference.
1254 // Sumq[1] is best non-ref (and maybe better than ref)
1255 bca->maxins = max_ins;
1256 bca->inscns = (char*) realloc(bca->inscns, bca->maxins * 4);
1257 if (bca->maxins && !bca->inscns)
1258 return -1;
1259 for (t = 0; t < n_types; ++t)
1260 sumq[t] = sumq[t]<<6 | t;
1261 for (t = 1; t < n_types; ++t) // insertion sort
1262 for (j = t; j > 0 && sumq[j] > sumq[j-1]; --j)
1263 tmp = sumq[j], sumq[j] = sumq[j-1], sumq[j-1] = tmp;
1264 for (t = 0; t < n_types; ++t) // look for the reference type
1265 if ((sumq[t]&0x3f) == ref_type) break;
1266
1267 if (t) { // then move the reference type to the first
1268 tmp = sumq[t];
1269 for (; t > 0; --t) sumq[t] = sumq[t-1];
1270 sumq[0] = tmp;
1271 }
1272
1273 for (t = 0; t < 4; ++t) bca->indel_types[t] = B2B_INDEL_NULL;
1274 for (t = 0; t < 4 && t < n_types; ++t) {
1275 bca->indel_types[t] = types[sumq[t]&0x3f];
1276 #ifdef ALIGN_DEBUG
1277 fprintf(bcftools_stderr, "TYPE %+2d %d\n", types[t], sumq[t]>>6);
1278 #endif
1279 if (bca->maxins) // potentially an insertion
1280 memcpy(&bca->inscns[t * bca->maxins],
1281 &inscns[(sumq[t]&0x3f) * max_ins], bca->maxins);
1282 }
1283
1284 // Update p->aux.
1285 // If per-alignment type isn't found, then indelQ/seqQ is 0,
1286 // otherwise unchanged.
1287 for (s = n_alt = 0; s < n; ++s) {
1288 for (i = 0; i < n_plp[s]; ++i) {
1289 bam_pileup1_t *p = plp[s] + i;
1290 int x = types[p->aux>>16&0x3f];
1291 for (j = 0; j < 4; ++j)
1292 if (x == bca->indel_types[j]) break;
1293 p->aux = j<<16 | (j == 4? 0 : (p->aux&0xffff));
1294 if ((p->aux>>16&0x3f) > 0) ++n_alt;
1295 #ifdef ALIGN_DEBUG
1296 fprintf(bcftools_stderr, "FIN %s\t%d\t%d\t%d\n",
1297 bam_get_qname(p->b), (p->aux>>16)&0x3f,
1298 bca->indel_types[(p->aux>>16)&0x3f], p->aux&0xff);
1299 #endif
1300 }
1301 }
1302
1303 return n_alt;
1304 }
1305
1306 /*
1307 FIXME: with high number of samples, do we handle IMF correctly? Is it
1308 fraction of indels across entire data set, or just fraction for this
1309 specific sample? Needs to check bca->per_sample_flt (--per-sample-mF) opt.
1310 */
1311
1312 /*
1313 notes:
1314 - n .. number of samples
1315 - the routine sets bam_pileup1_t.aux of each read as follows:
1316 - 6: unused
1317 - 6: the call; index to bcf_callaux_t.indel_types .. (aux>>16)&0x3f
1318 - 8: estimated sequence quality .. (aux>>8)&0xff
1319 - 8: indel quality .. aux&0xff
1320 */
1321 int bcf_edlib_gap_prep(int n, int *n_plp, bam_pileup1_t **plp, int pos,
1322 bcf_callaux_t *bca, const char *ref, int ref_len)
1323 {
1324 if (ref == 0 || bca == 0) return -1;
1325
1326 int i, s, t, n_types, *types = NULL, max_rd_len, left, right, max_ins;
1327 int *score = NULL;
1328 int N, K, l_run, ref_type, n_alt = -1;
1329 char *inscns = NULL, *query = NULL;
1330
1331 // determine if there is a gap
1332 for (s = N = 0; s < n; ++s) {
1333 for (i = 0; i < n_plp[s]; ++i)
1334 if (plp[s][i].indel != 0) break;
1335 if (i < n_plp[s]) break;
1336 }
1337 if (s == n)
1338 // there is no indel at this position.
1339 return -1;
1340
1341 // Find average base quality over this region
1342 double qavg = 30, qsum = 0, qcount = 0;
1343 int qmax = 0;
1344 for (s = 0; s < n; s++) {
1345 for (i = 0; i < n_plp[s]; i++) {
1346 #define QWIN 50
1347 bam_pileup1_t *p = plp[s] + i;
1348 int kstart = p->qpos - QWIN > 0 ? p->qpos - QWIN : 0;
1349 int kend = p->qpos + QWIN < p->b->core.l_qseq
1350 ? p->qpos + QWIN : p->b->core.l_qseq;
1351 uint8_t *qual = bam_get_qual(p->b);
1352 int k;
1353 for (k = kstart; k < kend; k++) {
1354 qsum += qual[k];
1355 qcount++;
1356 if (qmax < qual[k])
1357 qmax = qual[k];
1358 }
1359 }
1360 }
1361 qavg = (qsum+1) / (qcount+1);
1362
1363 // find out how many types of indels are present
1364 types = bcf_cgp_find_types(n, n_plp, plp, pos, bca, ref,
1365 &max_rd_len, &n_types, &ref_type, &N);
1366 if (!types)
1367 goto err;
1368
1369
1370 // calculate left and right boundary, based on type size for a bit more
1371 // speed.
1372 int max_indel = 20*MAX(ABS(types[0]), ABS(types[n_types-1]))
1373 + bca->indel_win_size/4;
1374 if (max_indel > bca->indel_win_size)
1375 max_indel = bca->indel_win_size;
1376 left = pos > max_indel ? pos - max_indel : 0;
1377 right = pos + max_indel;
1378
1379 int del_size = types[0]<0 ? -types[0] : 0;
1380 right += del_size;
1381
1382 // in case the alignments stand out the reference
1383 for (i = pos; i < right; ++i)
1384 if (ref[i] == 0) break;
1385 right = i;
1386
1387 // compute the likelihood given each type of indel for each read
1388 max_ins = types[n_types - 1]; // max_ins is at least 0
1389
1390 // The length of the homopolymer run around the current position
1391 l_run = bcf_cgp_l_run(ref, pos);
1392 int l_run_base = seq_nt16_table[(uint8_t)ref[pos+1]];
1393 int l_run_ins = 0;
1394
1395 // construct the consensus sequence (minus indels, which are added later)
1396 if (max_ins > 0) {
1397 // TODO: replace filling inscns[] with calc_consensus return
1398 // so the merges of the insertion consensus for type[t] is
1399 // reported directly. (It may need adjustment to avoid N)
1400 inscns = bcf_cgp_calc_ins_cons(n, n_plp, plp, pos,
1401 types, n_types, max_ins, s);
1402 if (!inscns)
1403 return -1;
1404 }
1405
1406 query = (char*) calloc(right - left + max_rd_len + max_ins + 2, 1);
1407 score = (int*) calloc(N * n_types, sizeof(int));
1408 bca->indelreg = 0;
1409 double nqual_over_60 = bca->nqual / 60.0;
1410
1411 int biggest_del = 0;
1412 int biggest_ins = 0;
1413 for (t = 0; t < n_types; t++) {
1414 if (biggest_del > types[t])
1415 biggest_del = types[t];
1416 if (biggest_ins < types[t])
1417 biggest_ins = types[t];
1418 }
1419 int band = biggest_ins - biggest_del; // NB del is -ve
1420
1421 // Find left & right extents of STR covering pos, from ref
1422 int pos_l = pos, pos_r = pos;
1423 {
1424 rep_ele *reps, *elt, *tmp;
1425 int pstart = MAX(0, pos-30);
1426 int pmid = pos-pstart;
1427 int pend = MIN(ref_len, pos+30);
1428 reps = find_STR((char *)&ref[pstart], pend-pstart, 0);
1429 DL_FOREACH_SAFE(reps, elt, tmp) {
1430 if (elt->end >= pmid && elt->start <= pmid) {
1431 if (pos_l > pstart + elt->start)
1432 pos_l = pstart + elt->start;
1433 if (pos_r < pstart + elt->end)
1434 pos_r = pstart + elt->end;
1435 }
1436 DL_DELETE(reps, elt);
1437 free(elt);
1438 }
1439 }
1440
1441 int str_len1 = l_run, str_len2 = l_run/4;
1442 for (t = 0; t < n_types; ++t) {
1443 int l, ir;
1444
1445 // Compute indelreg. This is the context in the reference. Eg:
1446 //
1447 // REF: AG--TTTC Inscns is "TT".
1448 // SEQ: AGTTTTTC Indelreg is 3; next 3 "TTT" bases
1449 //
1450 // => GTTT GTTTTT is call.
1451 if (types[t] == 0)
1452 ir = 0;
1453 else if (types[t] > 0)
1454 ir = est_indelreg(pos, ref, types[t], &inscns[t*max_ins]);
1455 else
1456 ir = est_indelreg(pos, ref, -types[t], 0);
1457
1458 if (ir > bca->indelreg)
1459 bca->indelreg = ir;
1460
1461 // Realignment score, computed via BAQ
1462 for (s = K = 0; s < n; ++s) {
1463 char **tcons;
1464 int left_shift, right_shift;
1465 int tcon_len[2];
1466 int cpos_pos;
1467 tcons = bcf_cgp_consensus(n, n_plp, plp, pos, bca, ref, ref_len,
1468 left, right, s, types[t], biggest_del,
1469 &left_shift, &right_shift, &band,
1470 tcon_len, &cpos_pos, pos_l, pos_r);
1471 // TODO: Consensus for a deletion shouldn't match the
1472 // consensus for type 0. Eg consider
1473 // vv vv
1474 // REF: AATGTGTGAACAA REF: AATGTG--AACAA
1475 // T0: AATGTG--AACAA T0: AATGTG--AACAA
1476 // T-2: AA--TGTGAATAA T-2: AA--TGTGAATAA:
1477 //
1478 // On left: both T0 and T-2 are the same length, as it's
1479 // just a deletion that moved. We may end up assigning
1480 // reads to an indel allele based on the SNP they have and
1481 // not the actual indel.
1482 // There *is* a deletion here though, but only 1. How do
1483 // we call it once only? Need to replace entire region
1484 // with a reassembly.
1485 //
1486 // On right: T0 and T-2 have same length again, but there
1487 // isn't an indel as it's ins+del vs del+ins. They're
1488 // also the same length as the REF for this region.
1489 // Hence likelihood of this variant existing is tied in
1490 // with their equal and high similarity with/to the ref.
1491 //
1492 // We could do an alignment of tcons[0] and tcons[1] and check
1493 // whether their differences are consistent with (ie the
1494 // hamming distance is at least ABS(types[t]/2). I don't think
1495 // it'll rescue many FPs though.
1496
1497 #ifdef CONS_DEBUG
1498 {
1499 int j;
1500 for (j = 0; j < 2; j++) {
1501 int k;
1502 fprintf(bcftools_stderr, "Cons%d @ %d %4d/%4d ",
1503 j, pos, types[t], left_shift);
1504 for (k = 0; k < tcon_len[j]; k++) {
1505 if (k == cpos_pos)
1506 putc('#', bcftools_stderr);
1507 putc("ACGTN"[(uint8_t)tcons[j][k]], bcftools_stderr);
1508 }
1509 putc('\n', bcftools_stderr);
1510 }
1511 }
1512 #endif
1513
1514 // Scan for base-runs in the insertion.
1515 // We use this to avoid over-correction in est_seqQ when the
1516 // insertion is not part of the neighbouring homopolymer.
1517 int k = tcons[0][cpos_pos], j;
1518 for (j = 0; j < types[t]; j++)
1519 if (tcons[0][cpos_pos+j] != k)
1520 break;
1521 if (j && j == types[t])
1522 l_run_ins |= "\x1\x2\x4\x8\xf"[k]; // ACGTN
1523 if (types[t] < 0)
1524 l_run_ins |= 0xff;
1525
1526 // align each read to consensus(es)
1527 for (i = 0; i < n_plp[s]; ++i, ++K) {
1528 bam_pileup1_t *p = plp[s] + i;
1529
1530 // Some basic ref vs alt stats.
1531 int imq = p->b->core.qual > 59 ? 59 : p->b->core.qual;
1532 imq *= nqual_over_60;
1533
1534 int sc_len, slen, epos, sc_end;
1535
1536 // Only need to gather stats on one type, as it's
1537 // identical calculation for all the subsequent ones
1538 // and we're sharing the same stats array
1539 if (t == 0) {
1540 // Gather stats for INFO field to aid filtering.
1541 // mq and sc_len not very helpful for filtering, but could
1542 // help in assigning a better QUAL value.
1543 //
1544 // Pos is slightly useful.
1545 // Base qual can be useful, but need qual prior to BAQ?
1546 // May need to cache orig quals in aux tag so we can fetch
1547 // them even after mpileup step.
1548 get_pos(bca, p, &sc_len, &slen, &epos, &sc_end);
1549
1550 assert(imq >= 0 && imq < bca->nqual);
1551 assert(epos >= 0 && epos < bca->npos);
1552 assert(sc_len >= 0 && sc_len < 100);
1553 if (p->indel) {
1554 bca->ialt_mq[imq]++;
1555 bca->ialt_scl[sc_len]++;
1556 bca->ialt_pos[epos]++;
1557 } else {
1558 bca->iref_mq[imq]++;
1559 bca->iref_scl[sc_len]++;
1560 bca->iref_pos[epos]++;
1561 }
1562 }
1563
1564 int qbeg, qpos, qend, tbeg, tend, kk;
1565 uint8_t *seq = bam_get_seq(p->b);
1566 uint32_t *cigar = bam_get_cigar(p->b);
1567 if (p->b->core.flag & BAM_FUNMAP) continue;
1568
1569 // FIXME: the following loop should be better moved outside;
1570 // nonetheless, realignment should be much slower anyway.
1571 for (kk = 0; kk < p->b->core.n_cigar; ++kk)
1572 if ((cigar[kk]&BAM_CIGAR_MASK) == BAM_CREF_SKIP)
1573 break;
1574 if (kk < p->b->core.n_cigar)
1575 continue;
1576
1577 // determine the start and end of sequences for alignment
1578 int left2 = left, right2 = right;
1579 int min_win_size = MAX(-biggest_del, biggest_ins);
1580 min_win_size += ABS(left_shift) + ABS(right_shift);
1581 {
1582 rep_ele *reps, *elt, *tmp;
1583 reps = find_STR(tcons[0], tcon_len[0], 0);
1584 //int max_str = 0;
1585 int tot_str = 0;
1586 DL_FOREACH_SAFE(reps, elt, tmp) {
1587 // if (max_str < elt->end - elt->start)
1588 // max_str = elt->end - elt->start;
1589 tot_str += elt->end - elt->start;
1590 DL_DELETE(reps, elt);
1591 free(elt);
1592 }
1593
1594 // Ideally max_str should be enough, but it's still not
1595 // sufficient in longer range some repeats.
1596 //min_win_size += max_str;
1597 min_win_size += tot_str;
1598 }
1599 min_win_size += 10;
1600
1601 // TEST 8
1602 if (p->b->core.l_qseq > 1000) {
1603 // long read data needs less context. It also tends to
1604 // have many more candidate indels to investigate so
1605 // speed here matters more.
1606 if (pos - left >= min_win_size)
1607 left2 = MAX(left2, pos - min_win_size);
1608 if (right-pos >= min_win_size)
1609 right2 = MIN(right2, pos + min_win_size);
1610 }
1611
1612 // Genomic coords for first and last base of query
1613 // alignment. This is only used in bcf_cgp_align_score
1614 // for computing scores by looking for the proximity
1615 // of STRs with the end of the query alignment.
1616 int r_start = p->b->core.pos;
1617 int r_end = bam_cigar2rlen(p->b->core.n_cigar,
1618 bam_get_cigar(p->b));
1619 r_end += -1 + r_start;
1620
1621
1622 // Map left2/right2 genomic coordinates to qbeg/qend
1623 // query coordinates. The query may not span the
1624 // entire left/right region, so this also returns the
1625 // equivalent genomic coords for qbeg/qend in tbeg/tend.
1626 qbeg = tpos2qpos(&p->b->core, bam_get_cigar(p->b),
1627 left2, 0, &tbeg);
1628 qpos = tpos2qpos(&p->b->core, bam_get_cigar(p->b), pos,
1629 0, &tend) - qbeg;
1630 qend = tpos2qpos(&p->b->core, bam_get_cigar(p->b),
1631 right2, 1, &tend);
1632
1633 int old_tend = tend;
1634 int old_tbeg = tbeg;
1635
1636 // write the query sequence
1637 for (l = qbeg; l < qend; ++l)
1638 query[l - qbeg] = seq_nt16_int[bam_seqi(seq, l)];
1639
1640 // tbeg and tend are the genomic locations equivalent
1641 // to qbeg and qend on the sequence.
1642 // These may being entirely within our left/right
1643 // coordinates over which we've computed the
1644 // consensus, or overlapping to left/right.
1645 //
1646 // We know an estimation of band, plus biggest indel,
1647 // so we can trim tbeg/tend to a smaller region if we
1648 // wish here. This speeds up BAQ scoring.
1649 int wband = band + MAX(-biggest_del, biggest_ins)*2 + 20;
1650 int tend1 = left + tcon_len[0] - (left2-left);
1651 int tend2 = left + tcon_len[1] - (left2-left);
1652 tend1 = MIN(tend1, old_tend + wband);
1653 tend2 = MIN(tend2, old_tend + wband);
1654 tbeg = MAX(left2, old_tbeg - wband);
1655
1656 // do realignment; this is the bottleneck.
1657 //
1658 // Note low score = good, high score = bad.
1659 if (tend1 > tbeg && tend2 > tbeg) {
1660 //fprintf(bcftools_stderr, "Num %d\n", i);
1661 if (bcf_cgp_align_score(p, bca, types[t], band,
1662 (uint8_t *)tcons[0] + left2-left,
1663 (uint8_t *)tcons[1] + left2-left,
1664 (uint8_t *)query,
1665 r_start, r_end,
1666 tbeg, tend1, tend2,
1667 left2, left + tcon_len[0],
1668 qbeg, qend, pos,qpos, -biggest_del,
1669 qavg, bca->del_bias,
1670 &score[K*n_types + t],
1671 &str_len1, &str_len2) < 0) {
1672 goto err;
1673 }
1674 #ifdef ALIGN_DEBUG
1675 fprintf(bcftools_stderr, "type %d %x / %x\t%s\n",
1676 types[t],
1677 score[K*n_types + t] >> 8,
1678 score[K*n_types + t] & 0xff,
1679 bam_get_qname(p->b));
1680 #endif
1681 } else {
1682 // place holder large cost for reads that cover the
1683 // region entirely within a deletion (thus tend < tbeg).
1684 score[K*n_types + t] = 0xffffff;
1685 }
1686 }
1687 free(tcons);
1688 }
1689 }
1690
1691 // compute indelQ
1692 if (!(l_run_base & l_run_ins))
1693 l_run = 1; // different base type in ins to flanking region.
1694 n_alt = bcf_cgp_compute_indelQ(n, n_plp, plp, bca, inscns, l_run, max_ins,
1695 ref_type, types, n_types, qavg, score,
1696 str_len1, str_len2);
1697
1698 err:
1699 // free
1700 free(query);
1701 free(score);
1702 free(types);
1703 free(inscns);
1704
1705 return n_alt > 0? 0 : -1;
1706 }