Debian Codegraph @

bcftools/bam2bcf_indel.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 Genome Research Ltd.
5
6 Author: Heng Li <[email protected]>
7
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14
15 The above copyright notice and this permission notice shall be included in
16 all copies or substantial portions of the Software.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 DEALINGS IN THE SOFTWARE. */
25
26 #include <assert.h>
27 #include <ctype.h>
28 #include <string.h>
29 #include <math.h>
30 #include <htslib/hts.h>
31 #include <htslib/sam.h>
32 #include <htslib/khash_str2int.h>
33 #include "bam2bcf.h"
34 #include "str_finder.h"
35
36 #include <htslib/ksort.h>
37 KSORT_INIT_GENERIC(uint32_t)
38
39 #define MINUS_CONST 0x10000000
40
41 #define MAX_TYPES 64
42
43 // Take a reference position tpos and convert to a query position (returned).
44 // This uses the CIGAR string plus alignment c->pos to do the mapping.
45 //
46 // *_tpos is returned as tpos if query overlaps tpos, but for deletions
47 // it'll be either the start (is_left) or end (!is_left) ref position.
48 int tpos2qpos(const bam1_core_t *c, const uint32_t *cigar, int32_t tpos, int is_left, int32_t *_tpos)
49 {
50 // x = pos in ref, y = pos in query seq
51 int k, x = c->pos, y = 0, last_y = 0;
52 *_tpos = c->pos;
53 for (k = 0; k < c->n_cigar; ++k) {
54 int op = cigar[k] & BAM_CIGAR_MASK;
55 int l = cigar[k] >> BAM_CIGAR_SHIFT;
56 if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
57 if (c->pos > tpos) return y;
58 if (x + l > tpos) {
59 *_tpos = tpos;
60 return y + (tpos - x);
61 }
62 x += l; y += l;
63 last_y = y;
64 } else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) y += l;
65 else if (op == BAM_CDEL || op == BAM_CREF_SKIP) {
66 if (x + l > tpos) {
67 *_tpos = is_left? x : x + l;
68 return y;
69 }
70 x += l;
71 }
72 }
73 *_tpos = x;
74 return last_y;
75 }
76
77 // FIXME: check if the inserted sequence is consistent with the homopolymer run
78 // l is the relative gap length and l_run is the length of the homopolymer on the reference
79 static inline int est_seqQ(const bcf_callaux_t *bca, int l, int l_run)
80 {
81 int q, qh;
82 q = bca->openQ + bca->extQ * (abs(l) - 1);
83 qh = l_run >= 3? (int)(bca->tandemQ * (double)abs(l) / l_run + .499) : 1000;
84 return q < qh? q : qh;
85 }
86
87 inline int est_indelreg(int pos, const char *ref, int l, char *ins4)
88 {
89 int i, j, max = 0, max_i = pos, score = 0;
90 l = abs(l);
91 for (i = pos + 1, j = 0; ref[i]; ++i, ++j) {
92 if (ins4) score += (toupper(ref[i]) != "ACGTN"[(int)ins4[j%l]])? -10 : 1;
93 else score += (toupper(ref[i]) != toupper(ref[pos+1+j%l]))? -10 : 1;
94 if (score < 0) break;
95 if (max < score) max = score, max_i = i;
96 }
97 return max_i - pos;
98 }
99
100 // Identify spft-clip length, position in seq, and clipped seq len
101 void get_pos(const bcf_callaux_t *bca, bam_pileup1_t *p,
102 int *sc_len_r, int *slen_r, int *epos_r, int *end) {
103 bam1_t *b = p->b;
104 int sc_len = 0, sc_dist = -1, at_left = 1;
105 int epos = p->qpos, slen = b->core.l_qseq;
106 int k;
107 uint32_t *cigar = bam_get_cigar(b);
108 *end = -1;
109 for (k = 0; k < b->core.n_cigar; k++) {
110 int op = bam_cigar_op(cigar[k]);
111 if (op == BAM_CSOFT_CLIP) {
112 slen -= bam_cigar_oplen(cigar[k]);
113 if (at_left) {
114 // left end
115 sc_len += bam_cigar_oplen(cigar[k]);
116 epos -= sc_len; // don't count SC in seq pos
117 sc_dist = epos;
118 *end = 0;
119 } else {
120 // right end
121 int srlen = bam_cigar_oplen(cigar[k]);
122 int rd = b->core.l_qseq - srlen - p->qpos;
123 if (sc_dist < 0 || sc_dist > rd) {
124 // closer to right end than left
125 // FIXME: compensate for indel length too?
126 sc_dist = rd;
127 sc_len = srlen;
128 *end = 1;
129 }
130 }
131 } else if (op != BAM_CHARD_CLIP) {
132 at_left = 0;
133 }
134 }
135
136 if (p->indel > 0 && slen - (epos+p->indel) < epos)
137 epos += p->indel-1; // end of insertion, if near end of seq
138
139 // slen is now length of sequence minus soft-clips and
140 // epos is position of indel in seq minus left-clip.
141 *epos_r = (double)epos / (slen+1) * bca->npos;
142
143 if (sc_len) {
144 // scale importance of clip by distance to closest end
145 *sc_len_r = 15.0*sc_len / (sc_dist+1);
146 if (*sc_len_r > 99) *sc_len_r = 99;
147 } else {
148 *sc_len_r = 0;
149 }
150
151 *slen_r = slen;
152 }
153
154 // Part of bcf_call_gap_prep.
155 //
156 // Scans the pileup to identify all the different sizes of indels
157 // present.
158 // types[] returned is sorted by size, from smallest (maybe negative) to largest.
159 //
160 // Returns types and fills out n_types_r, max_rd_len_r and ref_type_r,
161 // or NULL on error.
162 static int *bcf_cgp_find_types(int n, int *n_plp, bam_pileup1_t **plp,
163 int pos, bcf_callaux_t *bca, const char *ref,
164 int *max_rd_len_r, int *n_types_r,
165 int *ref_type_r, int *N_r) {
166 int i, j, t, s, N, m, max_rd_len, n_types;
167 int n_alt = 0, n_tot = 0, indel_support_ok = 0;
168 uint32_t *aux;
169 int *types;
170
171 // N is the total number of reads
172 for (s = N = 0; s < n; ++s)
173 N += n_plp[s];
174
175 bca->max_support = bca->max_frac = 0;
176 aux = (uint32_t*) calloc(N + 1, 4);
177 if (!aux)
178 return NULL;
179
180 m = max_rd_len = 0;
181 aux[m++] = MINUS_CONST; // zero indel is always a type (REF)
182
183 // Fill out aux[] array with all the non-zero indel sizes.
184 // Also tally number with indels (n_alt) and total (n_tot).
185 for (s = 0; s < n; ++s) {
186 int na = 0, nt = 0;
187 for (i = 0; i < n_plp[s]; ++i) {
188 const bam_pileup1_t *p = plp[s] + i;
189 ++nt;
190 if (p->indel != 0) {
191 ++na;
192 aux[m++] = MINUS_CONST + p->indel;
193 }
194
195 // FIXME: cache me in pileup struct.
196 j = bam_cigar2qlen(p->b->core.n_cigar, bam_get_cigar(p->b));
197 if (j > max_rd_len) max_rd_len = j;
198 }
199 double frac = (double)na/nt;
200 if ( !indel_support_ok && na >= bca->min_support
201 && frac >= bca->min_frac )
202 indel_support_ok = 1;
203 if ( na > bca->max_support && frac > 0 )
204 bca->max_support = na, bca->max_frac = frac;
205
206 n_alt += na;
207 n_tot += nt;
208 }
209
210 // Sort aux[] and dedup
211 ks_introsort(uint32_t, m, aux);
212 for (i = 1, n_types = 1; i < m; ++i)
213 if (aux[i] != aux[i-1]) ++n_types;
214
215 // Taking totals makes it hard to call rare indels (IMF filter)
216 if ( !bca->per_sample_flt )
217 indel_support_ok = ( (double)n_alt / n_tot < bca->min_frac
218 || n_alt < bca->min_support )
219 ? 0 : 1;
220 if ( n_types == 1 || !indel_support_ok ) { // then skip
221 free(aux);
222 return NULL;
223 }
224
225 // Bail out if we have far too many types of indel
226 if (n_types >= MAX_TYPES) {
227 free(aux);
228 // TODO revisit how/whether to control printing this warning
229 if (hts_verbose >= 2)
230 fprintf(stderr, "[%s] excessive INDEL alleles at position %d. "
231 "Skip the position.\n", __func__, pos + 1);
232 return NULL;
233 }
234
235 // To prevent long stretches of N's to be mistaken for indels
236 // (sometimes thousands of bases), check the number of N's in the
237 // sequence and skip places where half or more reference bases are Ns.
238 int nN=0, i_end = pos + (2*bca->indel_win_size < max_rd_len
239 ?2*bca->indel_win_size : max_rd_len);
240 for (i=pos; i<i_end && ref[i]; i++)
241 nN += ref[i] == 'N';
242 if ( nN*2>(i-pos) ) {
243 free(aux);
244 return NULL;
245 }
246
247 // Finally fill out the types[] array detailing the size of insertion
248 // or deletion.
249 types = (int*)calloc(n_types, sizeof(int));
250 if (!types) {
251 free(aux);
252 return NULL;
253 }
254 t = 0;
255 types[t++] = aux[0] - MINUS_CONST;
256 for (i = 1; i < m; ++i)
257 if (aux[i] != aux[i-1])
258 types[t++] = aux[i] - MINUS_CONST;
259 free(aux);
260
261 // Find reference type; types[?] == 0)
262 for (t = 0; t < n_types; ++t)
263 if (types[t] == 0) break;
264
265 *ref_type_r = t;
266 *n_types_r = n_types;
267 *max_rd_len_r = max_rd_len;
268 *N_r = N;
269
270 return types;
271 }
272
273 // Part of bcf_call_gap_prep.
274 //
275 // Construct per-sample consensus.
276 //
277 // Returns an array of consensus seqs,
278 // or NULL on failure.
279 static char **bcf_cgp_ref_sample(int n, int *n_plp, bam_pileup1_t **plp,
280 int pos, bcf_callaux_t *bca, const char *ref,
281 int left, int right) {
282 int i, k, s, L = right - left + 1, max_i, max2_i;
283 char **ref_sample; // returned
284 uint32_t *cns = NULL, max, max2;
285 char *ref0 = NULL, *r;
286 ref_sample = (char**) calloc(n, sizeof(char*));
287 cns = (uint32_t*) calloc(L, 4);
288 ref0 = (char*) calloc(L, 1);
289 if (!ref_sample || !cns || !ref0) {
290 n = 0;
291 goto err;
292 }
293
294 // Convert ref ASCII to 0-15.
295 for (i = 0; i < right - left; ++i)
296 ref0[i] = seq_nt16_table[(int)ref[i+left]];
297
298 // NB: one consensus per sample 'n', not per indel type.
299 // FIXME: consider fixing this. We should compute alignments vs
300 // types, not vs samples? Or types/sample combined?
301 for (s = 0; s < n; ++s) {
302 r = ref_sample[s] = (char*) calloc(L, 1);
303 if (!r) {
304 n = s-1;
305 goto err;
306 }
307
308 memset(cns, 0, sizeof(int) * L);
309
310 // collect ref and non-ref counts in cns
311 for (i = 0; i < n_plp[s]; ++i) {
312 bam_pileup1_t *p = plp[s] + i;
313 bam1_t *b = p->b;
314 uint32_t *cigar = bam_get_cigar(b);
315 uint8_t *seq = bam_get_seq(b);
316 int x = b->core.pos, y = 0;
317
318 // TODO: pileup exposes pileup_ind, but we also need e.g.
319 // pileup_len to know how much of the current CIGAR op-len
320 // we've used (or have remaining). If we had that, we
321 // could start at p->qpos without having to scan through
322 // the entire CIGAR string until we find it.
323 //
324 // Without it about all we could do is have a side channel
325 // to cache the last known coords. Messy, so punt for now.
326 // This is no longer the bottle neck until we get to 1000s of
327 // CIGAR ops.
328
329 for (k = 0; k < b->core.n_cigar; ++k) {
330 int op = cigar[k]&0xf;
331 int j, l = cigar[k]>>4;
332 if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
333 if (x + l >= left) {
334 j = left - x > 0 ? left - x : 0;
335 int j_end = right - x < l ? right - x : l;
336 for (; j < j_end; j++)
337 // Append to cns. Note this is ref coords,
338 // so insertions aren't in cns and deletions
339 // will have lower coverage.
340
341 // FIXME: want true consensus (with ins) per
342 // type, so we can independently compare each
343 // seq to each consensus and see which it
344 // matches best, so we get proper GT analysis.
345 cns[x+j-left] +=
346 (bam_seqi(seq, y+j) == ref0[x+j-left])
347 ? 1 // REF
348 : (1<<16); // ALT
349 }
350 x += l; y += l;
351 } else if (op == BAM_CDEL || op == BAM_CREF_SKIP) {
352 x += l;
353 } else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) {
354 y += l;
355 }
356
357 if (x > right)
358 break;
359 }
360 }
361
362 // Determine a sample specific reference.
363 for (i = 0; i < right - left; ++i)
364 r[i] = ref0[i];
365
366 // Find deepest and 2nd deepest ALT region (max & max2).
367 max = max2 = 0; max_i = max2_i = -1;
368 for (i = 0; i < right - left; ++i) {
369 if (cns[i]>>16 >= max>>16)
370 max2 = max, max2_i = max_i, max = cns[i], max_i = i;
371 else if (cns[i]>>16 >= max2>>16)
372 max2 = cns[i], max2_i = i;
373 }
374
375 // Masks mismatches present in at least 70% of the reads with 'N'.
376 // This code is nREF/(nREF+n_ALT) >= 70% for deepest region.
377 // The effect is that at least 30% of bases differing to REF will
378 // use "N" in consensus, so we don't penalise ALT or REF when
379 // aligning against it. (A poor man IUPAC code)
380 //
381 // Why is it only done in two loci at most?
382 if ((double)(max&0xffff) / ((max&0xffff) + (max>>16)) >= 0.7)
383 max_i = -1;
384 if ((double)(max2&0xffff) / ((max2&0xffff) + (max2>>16)) >= 0.7)
385 max2_i = -1;
386 if (max_i >= 0) r[max_i] = 15;
387 if (max2_i >= 0) r[max2_i] = 15;
388
389 //for (i = 0; i < right - left; ++i)
390 // fputc("=ACMGRSVTWYHKDBN"[(int)r[i]], stderr);
391 //fputc('\n', stderr);
392 }
393
394 free(ref0);
395 free(cns);
396
397 return ref_sample;
398
399 err:
400 free(ref0);
401 free(cns);
402 if (ref_sample) {
403 for (s = 0; s < n; s++)
404 free(ref_sample[s]);
405 free(ref_sample);
406 }
407
408 return NULL;
409 }
410
411 // The length of the homopolymer run around the current position
412 int bcf_cgp_l_run(const char *ref, int pos) {
413 int i, l_run;
414
415 int c = seq_nt16_table[(int)ref[pos + 1]];
416 if (c == 15) {
417 l_run = 1;
418 } else {
419 for (i = pos + 2; ref[i]; ++i)
420 if (seq_nt16_table[(int)ref[i]] != c) break;
421 l_run = i;
422 for (i = pos; i >= 0; --i)
423 if (seq_nt16_table[(int)ref[i]] != c) break;
424 l_run -= i + 1;
425 }
426
427 return l_run;
428 }
429
430
431 // Compute the consensus for this sample 's', minus indels which
432 // get added later.
433 char *bcf_cgp_calc_cons(int n, int *n_plp, bam_pileup1_t **plp,
434 int pos, int *types, int n_types,
435 int max_ins, int s) {
436 int i, j, t, k;
437 int *inscns_aux = (int*)calloc(5 * n_types * max_ins, sizeof(int));
438 if (!inscns_aux)
439 return NULL;
440
441 // Count the number of occurrences of each base at each position for
442 // each type of insertion.
443 for (t = 0; t < n_types; ++t) {
444 if (types[t] > 0) {
445 for (s = 0; s < n; ++s) {
446 for (i = 0; i < n_plp[s]; ++i) {
447 bam_pileup1_t *p = plp[s] + i;
448 if (p->indel == types[t]) {
449 uint8_t *seq = bam_get_seq(p->b);
450 for (k = 1; k <= p->indel; ++k) {
451 int c = seq_nt16_int[bam_seqi(seq, p->qpos + k)];
452 assert(c<5);
453 ++inscns_aux[(t*max_ins+(k-1))*5 + c];
454 }
455 }
456 }
457 }
458 }
459 }
460
461 // Use the majority rule to construct the consensus
462 char *inscns = (char *)calloc(n_types * max_ins, 1);
463 for (t = 0; t < n_types; ++t) {
464 for (j = 0; j < types[t]; ++j) {
465 int max = 0, max_k = -1, *ia = &inscns_aux[(t*max_ins+j)*5];
466 for (k = 0; k < 5; ++k)
467 if (ia[k] > max)
468 max = ia[k], max_k = k;
469 inscns[t*max_ins + j] = max ? max_k : 4;
470 if (max_k == 4) {
471 // discard insertions which contain N's
472 types[t] = 0;
473 break;
474 }
475 }
476 }
477 free(inscns_aux);
478
479 return inscns;
480 }
481
482 #ifndef MIN
483 # define MIN(a,b) ((a)<(b)?(a):(b))
484 #endif
485
486 // Part of bcf_call_gap_prep.
487 //
488 // Realign using BAQ to get an alignment score of a single read vs
489 // a haplotype consensus.
490 //
491 // Fills out score
492 // Returns 0 on success,
493 // <0 on error
494 static int bcf_cgp_align_score(bam_pileup1_t *p, bcf_callaux_t *bca,
495 int type, uint8_t *ref2, uint8_t *query,
496 int r_start, int r_end, int long_read,
497 int tbeg, int tend,
498 int left, int right,
499 int qbeg, int qend,
500 int qpos, int max_deletion,
501 int *score) {
502 // Illumina
503 probaln_par_t apf = { 1e-4, 1e-2, 10 };
504
505 // Parameters that work better on PacBio CCS 15k.
506 // We should consider querying the header and RG PU field.
507 // See also htslib/realn.c:sam_prob_realn()
508 if (long_read) {
509 apf.d = 1e-3;
510 apf.e = 1e-1;
511 }
512
513 type = abs(type);
514 apf.bw = type + 3;
515 int l, sc;
516 const uint8_t *qual = bam_get_qual(p->b), *bq;
517 uint8_t *qq;
518
519 // Get segment of quality, either ZQ tag or if absent QUAL.
520 if (!(qq = (uint8_t*) calloc(qend - qbeg, 1)))
521 return -1;
522 bq = (uint8_t*)bam_aux_get(p->b, "ZQ");
523 if (bq) ++bq; // skip type
524 for (l = qbeg; l < qend; ++l) {
525 int qval = bq? qual[l] + (bq[l] - 64) : qual[l];
526 if (qval > 30)
527 qval = 30;
528 if (qval < 7)
529 qval = 7;
530 qq[l - qbeg] = qval;
531 }
532
533 // The bottom 8 bits are length-normalised score while
534 // the top bits are unnormalised.
535 sc = probaln_glocal(ref2 + tbeg - left, tend - tbeg + type,
536 query, qend - qbeg, qq, &apf, 0, 0);
537 if (sc < 0) {
538 *score = 0xffffff;
539 free(qq);
540 return 0;
541 }
542
543 // used for adjusting indelQ below
544 l = (int)(100. * sc / (qend - qbeg) + .499) * bca->indel_bias;
545 *score = sc<<8 | MIN(255, l);
546
547 rep_ele *reps, *elt, *tmp;
548 uint8_t *seg = ref2 + tbeg - left;
549 int seg_len = tend - tbeg + type;
550
551 // Note: although seg moves (tbeg varies), ref2 is reused many times
552 // so we could factor out some find_STR calls. However it's not the
553 // bottleneck for now.
554
555 // FIXME: need to make this work on IUPAC.
556 reps = find_STR((char *)seg, seg_len, 0);
557 int iscore = 0;
558
559 // Identify STRs in ref covering the indel up to
560 // (or close to) the end of the sequence.
561 // Those having an indel and right at the sequence
562 // end do not confirm the total length of indel
563 // size. Specifically a *lack* of indel at the
564 // end, where we know indels occur in other
565 // sequences, is a possible reference bias.
566 //
567 // This is emphasised further if the sequence ends with
568 // soft clipping.
569 DL_FOREACH_SAFE(reps, elt, tmp) {
570 if (elt->start <= qpos && elt->end >= qpos) {
571 iscore += (elt->end-elt->start) / elt->rep_len; // c
572 if (elt->start+tbeg <= r_start ||
573 elt->end+tbeg >= r_end)
574 iscore += 2*(elt->end-elt->start);
575 }
576
577 DL_DELETE(reps, elt);
578 free(elt);
579 }
580
581 // Apply STR score to existing indelQ
582 l = (*score&0xff)*.8 + iscore*2;
583 *score = (*score & ~0xff) | MIN(255, l);
584
585 free(qq);
586
587 return 0;
588 }
589
590 // Part of bcf_call_gap_prep.
591 //
592 // Returns n_alt on success
593 // -1 on failure
594 static int bcf_cgp_compute_indelQ(int n, int *n_plp, bam_pileup1_t **plp,
595 bcf_callaux_t *bca, char *inscns,
596 int l_run, int max_ins,
597 int ref_type, int *types, int n_types,
598 int *score) {
599 // FIXME: n_types has a maximum; no need to alloc - use a #define?
600 int sc[MAX_TYPES], sumq[MAX_TYPES], s, i, j, t, K, n_alt, tmp;
601 memset(sumq, 0, n_types * sizeof(int));
602 for (s = K = 0; s < n; ++s) {
603 for (i = 0; i < n_plp[s]; ++i, ++K) {
604 bam_pileup1_t *p = plp[s] + i;
605 int *sct = &score[K*n_types], seqQ, indelQ;
606 for (t = 0; t < n_types; ++t) sc[t] = sct[t]<<6 | t;
607 for (t = 1; t < n_types; ++t) // insertion sort
608 for (j = t; j > 0 && sc[j] < sc[j-1]; --j)
609 tmp = sc[j], sc[j] = sc[j-1], sc[j-1] = tmp;
610
611 /* errmod_cal() assumes that if the call is wrong, the
612 * likelihoods of other events are equal. This is about
613 * right for substitutions, but is not desired for
614 * indels. To reuse errmod_cal(), I have to make
615 * compromise for multi-allelic indels.
616 */
617 if ((sc[0]&0x3f) == ref_type) {
618 indelQ = (sc[1]>>14) - (sc[0]>>14);
619 seqQ = est_seqQ(bca, types[sc[1]&0x3f], l_run);
620 } else {
621 for (t = 0; t < n_types; ++t) // look for the reference type
622 if ((sc[t]&0x3f) == ref_type) break;
623 indelQ = (sc[t]>>14) - (sc[0]>>14);
624 seqQ = est_seqQ(bca, types[sc[0]&0x3f], l_run);
625 }
626 tmp = sc[0]>>6 & 0xff;
627 // reduce indelQ
628 indelQ = tmp > 111? 0 : (int)((1. - tmp/111.) * indelQ + .499);
629
630 // Doesn't really help accuracy, but permits -h to take
631 // affect still.
632 if (indelQ > seqQ) indelQ = seqQ;
633 if (indelQ > 255) indelQ = 255;
634 if (seqQ > 255) seqQ = 255;
635 p->aux = (sc[0]&0x3f)<<16 | seqQ<<8 | indelQ; // use 22 bits in total
636 sumq[sc[0]&0x3f] += indelQ < seqQ? indelQ : seqQ;
637 // fprintf(stderr, "pos=%d read=%d:%d name=%s call=%d indelQ=%d seqQ=%d\n", pos, s, i, bam1_qname(p->b), types[sc[0]&0x3f], indelQ, seqQ);
638 }
639 }
640 // determine bca->indel_types[] and bca->inscns
641 bca->maxins = max_ins;
642 bca->inscns = (char*) realloc(bca->inscns, bca->maxins * 4);
643 if (bca->maxins && !bca->inscns)
644 return -1;
645 for (t = 0; t < n_types; ++t)
646 sumq[t] = sumq[t]<<6 | t;
647 for (t = 1; t < n_types; ++t) // insertion sort
648 for (j = t; j > 0 && sumq[j] > sumq[j-1]; --j)
649 tmp = sumq[j], sumq[j] = sumq[j-1], sumq[j-1] = tmp;
650 for (t = 0; t < n_types; ++t) // look for the reference type
651 if ((sumq[t]&0x3f) == ref_type) break;
652 if (t) { // then move the reference type to the first
653 tmp = sumq[t];
654 for (; t > 0; --t) sumq[t] = sumq[t-1];
655 sumq[0] = tmp;
656 }
657 for (t = 0; t < 4; ++t) bca->indel_types[t] = B2B_INDEL_NULL;
658 for (t = 0; t < 4 && t < n_types; ++t) {
659 bca->indel_types[t] = types[sumq[t]&0x3f];
660 if (bca->maxins)
661 memcpy(&bca->inscns[t * bca->maxins],
662 &inscns[(sumq[t]&0x3f) * max_ins], bca->maxins);
663 }
664 // update p->aux
665 for (s = n_alt = 0; s < n; ++s) {
666 for (i = 0; i < n_plp[s]; ++i) {
667 bam_pileup1_t *p = plp[s] + i;
668 int x = types[p->aux>>16&0x3f];
669 for (j = 0; j < 4; ++j)
670 if (x == bca->indel_types[j]) break;
671 p->aux = j<<16 | (j == 4? 0 : (p->aux&0xffff));
672 if ((p->aux>>16&0x3f) > 0) ++n_alt;
673 //fprintf(stderr, "X pos=%d read=%d:%d name=%s call=%d type=%d seqQ=%d indelQ=%d\n", pos, s, i, bam_get_qname(p->b), (p->aux>>16)&0x3f, bca->indel_types[(p->aux>>16)&0x3f], (p->aux>>8)&0xff, p->aux&0xff);
674 }
675 }
676
677 return n_alt;
678 }
679
680 /*
681 FIXME: with high number of samples, do we handle IMF correctly? Is it
682 fraction of indels across entire data set, or just fraction for this
683 specific sample? Needs to check bca->per_sample_flt (--per-sample-mF) opt.
684 */
685
686 /*
687 notes:
688 - n .. number of samples
689 - the routine sets bam_pileup1_t.aux of each read as follows:
690 - 6: unused
691 - 6: the call; index to bcf_callaux_t.indel_types .. (aux>>16)&0x3f
692 - 8: estimated sequence quality .. (aux>>8)&0xff
693 - 8: indel quality .. aux&0xff
694 */
695 int bcf_call_gap_prep(int n, int *n_plp, bam_pileup1_t **plp, int pos,
696 bcf_callaux_t *bca, const char *ref)
697 {
698 if (ref == 0 || bca == 0) return -1;
699
700 int i, s, j, k, t, n_types, *types, max_rd_len, left, right, max_ins;
701 int *score, max_ref2;
702 int N, K, l_run, ref_type, n_alt;
703 char *inscns = 0, *ref2, *query, **ref_sample;
704
705 // determine if there is a gap
706 for (s = N = 0; s < n; ++s) {
707 for (i = 0; i < n_plp[s]; ++i)
708 if (plp[s][i].indel != 0) break;
709 if (i < n_plp[s]) break;
710 }
711 if (s == n)
712 // there is no indel at this position.
713 return -1;
714
715 // find out how many types of indels are present
716 types = bcf_cgp_find_types(n, n_plp, plp, pos, bca, ref,
717 &max_rd_len, &n_types, &ref_type, &N);
718 if (!types)
719 return -1;
720
721
722 // calculate left and right boundary
723 left = pos > bca->indel_win_size ? pos - bca->indel_win_size : 0;
724 right = pos + bca->indel_win_size;
725 if (types[0] < 0) right -= types[0];
726
727 // in case the alignments stand out the reference
728 for (i = pos; i < right; ++i)
729 if (ref[i] == 0) break;
730 right = i;
731
732
733 /* The following call fixes a long-existing flaw in the INDEL
734 * calling model: the interference of nearby SNPs. However, it also
735 * reduces the power because sometimes, substitutions caused by
736 * indels are not distinguishable from true mutations. Multiple
737 * sequence realignment helps to increase the power.
738 *
739 * Masks mismatches present in at least 70% of the reads with 'N'.
740 */
741 ref_sample = bcf_cgp_ref_sample(n, n_plp, plp, pos, bca, ref, left, right);
742
743 // The length of the homopolymer run around the current position
744 l_run = bcf_cgp_l_run(ref, pos);
745
746 // construct the consensus sequence (minus indels, which are added later)
747 max_ins = types[n_types - 1]; // max_ins is at least 0
748 if (max_ins > 0) {
749 inscns = bcf_cgp_calc_cons(n, n_plp, plp, pos,
750 types, n_types, max_ins, s);
751 if (!inscns)
752 return -1;
753 }
754
755 // compute the likelihood given each type of indel for each read
756 max_ref2 = right - left + 2 + 2 * (max_ins > -types[0]? max_ins : -types[0]);
757 ref2 = (char*) calloc(max_ref2, 1);
758 query = (char*) calloc(right - left + max_rd_len + max_ins + 2, 1);
759 score = (int*) calloc(N * n_types, sizeof(int));
760 bca->indelreg = 0;
761 double nqual_over_60 = bca->nqual / 60.0;
762
763 for (t = 0; t < n_types; ++t) {
764 int l, ir;
765
766 // compute indelreg
767 if (types[t] == 0)
768 ir = 0;
769 else if (types[t] > 0)
770 ir = est_indelreg(pos, ref, types[t], &inscns[t*max_ins]);
771 else
772 ir = est_indelreg(pos, ref, -types[t], 0);
773
774 if (ir > bca->indelreg)
775 bca->indelreg = ir;
776
777 // Identify max deletion length
778 int max_deletion = 0;
779 for (s = 0; s < n; ++s) {
780 for (i = 0; i < n_plp[s]; ++i, ++K) {
781 bam_pileup1_t *p = plp[s] + i;
782 if (max_deletion < -p->indel)
783 max_deletion = -p->indel;
784 }
785 }
786
787 // Realignment score, computed via BAQ
788 for (s = K = 0; s < n; ++s) {
789 // Construct ref2 from ref_sample, inscns and indels.
790 // This is now the true sample consensus (possibly prepended
791 // and appended with reference if sample data doesn't span
792 // the full length).
793 for (k = 0, j = left; j <= pos; ++j)
794 ref2[k++] = seq_nt16_int[(int)ref_sample[s][j-left]];
795
796 if (types[t] <= 0)
797 j += -types[t];
798 else
799 for (l = 0; l < types[t]; ++l)
800 ref2[k++] = inscns[t*max_ins + l];
801
802 for (; j < right && ref[j]; ++j)
803 ref2[k++] = seq_nt16_int[(int)ref_sample[s][j-left]];
804 for (; k < max_ref2; ++k)
805 ref2[k] = 4;
806
807 if (right > j)
808 right = j;
809
810 // align each read to ref2
811 for (i = 0; i < n_plp[s]; ++i, ++K) {
812 bam_pileup1_t *p = plp[s] + i;
813
814 // Some basic ref vs alt stats.
815 int imq = p->b->core.qual > 59 ? 59 : p->b->core.qual;
816 imq *= nqual_over_60;
817
818 int sc_len, slen, epos, sc_end;
819
820 // Only need to gather stats on one type, as it's
821 // identical calculation for all the subsequent ones
822 // and we're sharing the same stats array
823 if (t == 0) {
824 // Gather stats for INFO field to aid filtering.
825 // mq and sc_len not very helpful for filtering, but could
826 // help in assigning a better QUAL value.
827 //
828 // Pos is slightly useful.
829 // Base qual can be useful, but need qual prior to BAQ?
830 // May need to cache orig quals in aux tag so we can fetch
831 // them even after mpileup step.
832 get_pos(bca, p, &sc_len, &slen, &epos, &sc_end);
833
834 assert(imq >= 0 && imq < bca->nqual);
835 assert(epos >= 0 && epos < bca->npos);
836 assert(sc_len >= 0 && sc_len < 100);
837 if (p->indel) {
838 bca->ialt_mq[imq]++;
839 bca->ialt_scl[sc_len]++;
840 bca->ialt_pos[epos]++;
841 } else {
842 bca->iref_mq[imq]++;
843 bca->iref_scl[sc_len]++;
844 bca->iref_pos[epos]++;
845 }
846 }
847
848 int qbeg, qpos, qend, tbeg, tend, kk;
849 uint8_t *seq = bam_get_seq(p->b);
850 uint32_t *cigar = bam_get_cigar(p->b);
851 if (p->b->core.flag & BAM_FUNMAP) continue;
852
853 // FIXME: the following loop should be better moved outside;
854 // nonetheless, realignment should be much slower anyway.
855 for (kk = 0; kk < p->b->core.n_cigar; ++kk)
856 if ((cigar[kk]&BAM_CIGAR_MASK) == BAM_CREF_SKIP)
857 break;
858 if (kk < p->b->core.n_cigar)
859 continue;
860
861 // determine the start and end of sequences for alignment
862 // FIXME: loops over CIGAR multiple times
863 int left2 = left, right2 = right;
864 if (p->b->core.l_qseq > 1000) {
865 // long read data needs less context. It also tends to
866 // have many more candidate indels to investigate so
867 // speed here matters more.
868 if (pos - left >= bca->indel_win_size)
869 left2 += bca->indel_win_size/2;
870 if (right-pos >= bca->indel_win_size)
871 right2 -= bca->indel_win_size/2;
872 }
873
874 int r_start = p->b->core.pos;
875 int r_end = bam_cigar2rlen(p->b->core.n_cigar,
876 bam_get_cigar(p->b))
877 -1 + r_start;
878
879 qbeg = tpos2qpos(&p->b->core, bam_get_cigar(p->b), left2,
880 0, &tbeg);
881 qpos = tpos2qpos(&p->b->core, bam_get_cigar(p->b), pos,
882 0, &tend) - qbeg;
883 qend = tpos2qpos(&p->b->core, bam_get_cigar(p->b), right2,
884 1, &tend);
885
886 if (types[t] < 0) {
887 int l = -types[t];
888 tbeg = tbeg - l > left? tbeg - l : left;
889 }
890
891 // write the query sequence
892 for (l = qbeg; l < qend; ++l)
893 query[l - qbeg] = seq_nt16_int[bam_seqi(seq, l)];
894
895 // A fudge for now. Consider checking SAM header for
896 // RG platform field.
897 int long_read = p->b->core.l_qseq > 1000;
898
899 // do realignment; this is the bottleneck
900 if (tend > tbeg) {
901 if (bcf_cgp_align_score(p, bca, types[t],
902 (uint8_t *)ref2 + left2-left,
903 (uint8_t *)query,
904 r_start, r_end, long_read,
905 tbeg, tend, left2, right2,
906 qbeg, qend, qpos, max_deletion,
907 &score[K*n_types + t]) < 0) {
908 score[K*n_types + t] = 0xffffff;
909 return -1;
910 }
911 } else {
912 // place holder large cost for reads that cover the
913 // region entirely within a deletion (thus tend < tbeg).
914 score[K*n_types + t] = 0xffffff;
915 }
916 #if 0
917 for (l = 0; l < tend - tbeg + abs(types[t]); ++l)
918 fputc("ACGTN"[(int)ref2[tbeg-left+l]], stderr);
919 fputc('\n', stderr);
920 for (l = 0; l < qend - qbeg; ++l)
921 fputc("ACGTN"[(int)query[l]], stderr);
922 fputc('\n', stderr);
923 fprintf(stderr, "pos=%d type=%d read=%d:%d name=%s "
924 "qbeg=%d tbeg=%d score=%d\n",
925 pos, types[t], s, i, bam_get_qname(p->b),
926 qbeg, tbeg, score[K*n_types + t]);
927 #endif
928 }
929 }
930 }
931
932 // compute indelQ
933 n_alt = bcf_cgp_compute_indelQ(n, n_plp, plp, bca, inscns, l_run, max_ins,
934 ref_type, types, n_types, score);
935
936 // free
937 free(ref2);
938 free(query);
939 free(score);
940
941 for (i = 0; i < n; ++i)
942 free(ref_sample[i]);
943
944 free(ref_sample);
945 free(types); free(inscns);
946
947 return n_alt > 0? 0 : -1;
948 }