Debian Codegraph @

bcftools/bam2bcf_edlib.c

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