Debian Codegraph @

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