Debian Codegraph @

bcftools/bam2bcf_iaux.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* bam2bcf_iaux.c -- modified indel caller
4
5 Copyright (C) 2022 Genome Research Ltd.
6
7 Author: pd3@sanger, jkb
8
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15
16 The above copyright notice and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25 DEALINGS IN THE SOFTWARE
26 */
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 "bcftools.h"
36 #include "bam2bcf.h"
37 #include "read_consensus.h"
38 #include "cigar_state.h"
39
40 #include <htslib/ksort.h>
41 KSORT_INIT_STATIC_GENERIC(uint32_t)
42
43 #ifndef DEBUG_ALN
44 #define DEBUG_ALN 0
45 #endif
46
47 #define MAX_TYPES 64
48
49 typedef struct
50 {
51 int pos; // current position
52 char *chr; // current chromosome
53 int nsmpl; // number of samples
54 int *nplp; // per-sample number of reads
55 bam_pileup1_t **plp; // per-sample reads
56 bcf_callaux_t *bca; // auxiliary bam2bcf structure
57 const char *ref; // reference genome (ASCII)
58 uint32_t *uitmp; // temporary unsigned int array
59 char *inscns; // insertions consensus "ACGTN"[itype*max_ins_len+i]
60 int muitmp, minscns; // size of uitmp, inscns
61 int iref_type, ntypes, types[MAX_TYPES]; // indel types
62 int max_ins_len; // largest insertion
63 int left, right; // consensus sequence boundaries, 0-based fa ref coordinates
64 read_cns_t *rcns; // read consensus
65 cns_seq_t *cns_seq; // array of consensus sequences
66 int *cns_pos; // array of relative pos indexes within cns_seq sequences
67 uint8_t *ref_seq, *qry_seq; // reference and query sequence to align
68 int nref_seq, nqry_seq; // the allocated size of ref_seq and qry_seq
69 uint8_t *qual;
70 int nqual;
71 int *read_scores, // read scores for each indel type [ntypes*iread+itype]
72 mread_scores,
73 ref_qual[MAX_TYPES], // refseq quality at pos for each indel type in the context of homopolymer runs
74 sum_qual[MAX_TYPES]; // qual contributions to each indel type from all reads
75 }
76 indel_aux_t;
77
78 #if DEBUG_ALN
79 static void debug_print_types(indel_aux_t *iaux)
80 {
81 int i,j;
82 fprintf(bcftools_stderr,"types at %s:%d ntypes=%d... ",iaux->chr,iaux->pos+1,iaux->ntypes);
83 for (i=0; i<iaux->ntypes; i++)
84 {
85 fprintf(bcftools_stderr," type%d=",i);
86 if ( iaux->types[i]<=0 )
87 {
88 if ( i==iaux->iref_type ) fprintf(bcftools_stderr,"%d(ref)",iaux->types[i]);
89 else fprintf(bcftools_stderr,"%d",iaux->types[i]);
90 continue;
91 }
92 char *cns = &iaux->inscns[i*iaux->max_ins_len];
93 for (j=0; j<iaux->types[i]; j++) fprintf(bcftools_stderr,"%c","ACGTN"[(int)cns[j]]);
94 }
95 fprintf(bcftools_stderr,"\n");
96 }
97 #else
98 #define debug_print_types(iaux)
99 #endif
100
101 void bcf_iaux_destroy(bcf_callaux_t *bca)
102 {
103 if ( !bca->iaux ) return;
104 indel_aux_t *iaux = (indel_aux_t*)bca->iaux;
105 free(iaux->uitmp);
106 free(iaux->inscns);
107 free(iaux->ref_seq);
108 free(iaux->qry_seq);
109 free(iaux->qual);
110 free(iaux->read_scores);
111 rcns_destroy(iaux->rcns);
112 free(iaux);
113 }
114
115 static void iaux_init_sequence_context(indel_aux_t *iaux)
116 {
117 // Calculate left and right boundary. The array types is sorted in ascending order, the first
118 // element is the largest deletion (if a deletion present)
119 iaux->left = iaux->pos > iaux->bca->indel_win_size ? iaux->pos - iaux->bca->indel_win_size : 0;
120 iaux->right = iaux->pos + iaux->bca->indel_win_size;
121 if ( iaux->types[0] < 0 ) iaux->right -= iaux->types[0]; // extend by the largest deletion length
122
123 // In case the alignments stand out the reference
124 int i;
125 for (i=iaux->pos; i<iaux->right; i++)
126 if ( !iaux->ref[i] ) break;
127 iaux->right = i;
128
129 // Sequence quality in the context of homopolymers for each indel type
130 int l_run = bcf_cgp_l_run(iaux->ref, iaux->pos); // The length of the homopolymer run around the current position
131 for (i=0; i<iaux->ntypes; i++)
132 {
133 int l = iaux->types[i];
134
135 // This is the original est_seqQ() code. FIXME: check if the inserted sequence is consistent with the homopolymer run
136 int q = iaux->bca->openQ + iaux->bca->extQ * (abs(l) - 1);
137 int qh = l_run >= 3? (int)(iaux->bca->tandemQ * (double)abs(l) / l_run + .499) : 1000;
138 if ( q > qh ) q = qh;
139
140 iaux->ref_qual[i] = q < 255 ? q : 255;
141 }
142
143 // Determine the indel region, this makes the difference between e.g. T>TA vs TA>TAA
144 iaux->bca->indelreg = 0;
145 for (i=0; i<iaux->ntypes; i++)
146 {
147 if ( !iaux->types[i] ) continue;
148 int ireg;
149 if ( iaux->types[i] > 0 )
150 ireg = est_indelreg(iaux->pos, iaux->ref, iaux->types[i], &iaux->inscns[i*iaux->max_ins_len]);
151 else
152 ireg = est_indelreg(iaux->pos, iaux->ref, -iaux->types[i], 0);
153 if ( ireg > iaux->bca->indelreg ) iaux->bca->indelreg = ireg;
154 }
155 }
156
157 static int iaux_init_scores(indel_aux_t *iaux, int ismpl)
158 {
159 int n = iaux->nplp[ismpl] * iaux->ntypes;
160 if ( iaux->mread_scores < n )
161 {
162 int *tmp = (int*) realloc(iaux->read_scores,n*sizeof(int));
163 if ( !tmp ) return -1;
164 iaux->mread_scores = n;
165 iaux->read_scores = tmp;
166 }
167 memset(iaux->read_scores,0,n);
168 return 0;
169 }
170
171 static int _have_indel_reads(indel_aux_t *iaux)
172 {
173 int i,j;
174 for (i=0; i<iaux->nsmpl; i++)
175 {
176 for (j=0; j<iaux->nplp[i]; j++)
177 if ( iaux->plp[i][j].indel ) return 1;
178 }
179 return 0;
180 }
181
182 // For insertions only their sizes were collected so far. Now go through the reads and
183 // create consensus sequence for each insert, therefore note that there can be only one
184 // sequence per insertion length
185 static int iaux_init_ins_types(indel_aux_t *iaux)
186 {
187 if ( !iaux->max_ins_len ) return 0;
188
189 uint32_t *aux;
190 int naux = 5 * iaux->ntypes * iaux->max_ins_len;
191 if ( iaux->muitmp < naux )
192 {
193 aux = (uint32_t*) realloc(iaux->uitmp,naux*sizeof(*aux));
194 if ( !aux ) return -1;
195 iaux->uitmp = aux;
196 iaux->muitmp = naux;
197 }
198 else aux = iaux->uitmp;
199 memset(aux,0,naux*sizeof(*aux));
200
201 // count the number of occurrences of each base at each position for each type of insertion
202 int t,s,i,j;
203 for (t=0; t<iaux->ntypes; t++)
204 {
205 if ( iaux->types[t] <= 0) continue;
206 for (s=0; s<iaux->nsmpl; s++)
207 {
208 for (i=0; i<iaux->nplp[s]; i++)
209 {
210 bam_pileup1_t *plp = iaux->plp[s] + i;
211 if ( plp->indel != iaux->types[t] ) continue;
212 uint8_t *seq = bam_get_seq(plp->b);
213 for (j=0; j<plp->indel; j++)
214 {
215 int c = seq_nt16_int[bam_seqi(seq, plp->qpos+j+1)];
216 assert(c<5);
217 aux[5*(t*iaux->max_ins_len+j) + c]++;
218 }
219 }
220 }
221 }
222
223 char *cns;
224 int ncns = iaux->ntypes * iaux->max_ins_len;
225 if ( iaux->minscns < ncns )
226 {
227 cns = (char*) realloc(iaux->inscns,naux*sizeof(*aux));
228 if ( !cns ) return -1;
229 iaux->inscns = cns;
230 iaux->minscns = ncns;
231 }
232 else cns = iaux->inscns;
233 memset(aux,0,ncns*sizeof(*cns));
234
235 // use the majority rule to construct the consensus
236 for (t=0; t<iaux->ntypes; t++)
237 {
238 for (i=0; i<iaux->types[t]; i++) // this naturally includes only insertions
239 {
240 uint32_t *tmp = &aux[5*(t*iaux->max_ins_len+i)], max = tmp[0], max_j = 0;
241 for (j=1; j<5; j++)
242 if ( max < tmp[j] ) max = tmp[j], max_j = j;
243 cns[t*iaux->max_ins_len + i] = max ? max_j : 4;
244 if ( max_j==4 ) { iaux->types[t] = 0; break; } // discard insertions which contain N's
245 }
246 }
247 return 0;
248 }
249
250 #define MINUS_CONST 0x10000000
251 static int iaux_init_types(indel_aux_t *iaux)
252 {
253 if ( !_have_indel_reads(iaux) ) return 0;
254
255 iaux->bca->max_support = 0;
256 memset(iaux->sum_qual,0,MAX_TYPES*sizeof(*iaux->sum_qual));
257
258 int i,j, nreads = 0;
259 for (i=0; i<iaux->nsmpl; i++) nreads += iaux->nplp[i];
260
261 uint32_t *aux;
262 if ( iaux->muitmp < nreads+1 )
263 {
264 aux = (uint32_t*) realloc(iaux->uitmp,(nreads+1)*sizeof(*iaux->uitmp));
265 if ( !aux ) return -1;
266 iaux->uitmp = aux;
267 iaux->muitmp = nreads+1;
268 }
269 else aux = iaux->uitmp;
270 memset(aux,0,(nreads+1)*sizeof(*aux));
271
272 int naux = 0, indel_support_ok = 0, n_alt = 0, n_tot = 0;
273 int max_rd_len = 0; // max sequence length that includes ref+del bases
274
275 // Fill out aux[] array with all the non-zero indel sizes. This is an unsorted list with as many
276 // entries as there are reads
277 aux[naux++] = MINUS_CONST; // zero indel is always a type (REF)
278 for (i=0; i<iaux->nsmpl; i++)
279 {
280 int nalt = naux, ntot = 0; // per sample values
281 for (j=0; j<iaux->nplp[i]; j++)
282 {
283 const bam_pileup1_t *plp = iaux->plp[i] + j;
284 ntot++;
285 if ( plp->indel ) aux[naux++] = MINUS_CONST + plp->indel;
286 if ( !PLP_QLEN(&plp->cd) ) PLP_QLEN(&plp->cd) = bam_cigar2qlen(plp->b->core.n_cigar, bam_get_cigar(plp->b));
287 if ( PLP_QLEN(&plp->cd) > max_rd_len ) max_rd_len = PLP_QLEN(&plp->cd);
288 }
289 nalt = naux - nalt;
290 if ( iaux->bca->per_sample_flt )
291 {
292 double frac = (double)nalt/naux;
293 if ( nalt >= iaux->bca->min_support && frac >= iaux->bca->min_frac ) indel_support_ok = 1;
294 if ( nalt > iaux->bca->max_support && frac > 0 ) iaux->bca->max_support = nalt, iaux->bca->max_frac = frac;
295 }
296 else
297 {
298 n_alt += nalt;
299 n_tot += ntot;
300 }
301 }
302
303 // Check if the minimum required number of indel reads has been observed
304 if ( !iaux->bca->per_sample_flt && n_alt >= iaux->bca->min_support && (double)n_alt/n_tot >= iaux->bca->min_frac ) indel_support_ok = 1;
305 if ( naux==1 || !indel_support_ok ) return 0;
306
307 // To prevent long stretches of N's to be mistaken for indels (sometimes thousands of bases), check the number of N's in the
308 // sequence and skip places where half or more reference bases in the sequence that follows pos are Ns
309 int nN = 0, i_end = iaux->pos + (iaux->bca->indel_win_size < max_rd_len ? iaux->bca->indel_win_size : max_rd_len);
310 for (i=iaux->pos; i<i_end && iaux->ref[i]; i++)
311 if ( iaux->ref[i] == 'N' ) nN++;
312 if ( 2*nN > i - iaux->pos ) return -1;
313
314 // Sort aux[] and dedup indel types
315 int n_types = 1;
316 ks_introsort(uint32_t, naux, aux);
317 for (i=1; i<naux; i++)
318 if ( aux[i] != aux[i-1] ) n_types++;
319
320 if ( n_types >= MAX_TYPES )
321 {
322 static int warned = 0;
323 if ( !warned )
324 {
325 fprintf(bcftools_stderr, "Warning: excessive number of INDEL alleles at %s:%d, skipping. (This warning is printed only once)\n",iaux->chr,iaux->pos+1);
326 warned = 1;
327 }
328 return -1;
329 }
330
331 // Fill out the types[] array detailing the size of insertion or deletion.
332 iaux->ntypes = 0;
333 iaux->max_ins_len = 0;
334 for (i=0; i<naux; i++)
335 {
336 int isize = (int32_t)(aux[i] - MINUS_CONST);
337 for (j=i+1; j<naux; j++)
338 if ( aux[j] != aux[i] ) break;
339
340 // Only include the REF type and types with sufficient support. Note that the position
341 // already passed, this is just to reduce the number of indel types. The check is
342 // permissive, the thresholds min_support and min_frac are not enforced in per-sample mode
343 int is_ok = 0;
344 if ( !isize )
345 {
346 is_ok = 1;
347 iaux->iref_type = iaux->ntypes;
348 }
349 else
350 {
351 if ( j-i >= iaux->bca->min_support ) is_ok = 1;
352 // What is the best way to handle the -pmF options:
353 // - consider only sites where a single indel type passes the -mF threshold, as opposed to all indel types cumulatively
354 // - once a site passes, include all indel types in the evaluation, as opposed to considering only the strong candidates
355 // In this implementation sites are selected by counting reads from all indel types cumulatively and all indel types
356 // are considered.
357 // Uncomment the following condition to consider only strong indel candidates once the site has been selected
358 // if ( !iaux->bca->per_sample_flt && (double)(j-i) / n_tot < iaux->bca->min_frac ) is_ok = 0;
359 }
360 if ( is_ok )
361 {
362 iaux->types[iaux->ntypes++] = isize;
363 if ( isize > 0 && isize > iaux->max_ins_len ) iaux->max_ins_len = isize;
364 }
365 i = j-1;
366 }
367 if ( iaux->ntypes <= 1 ) return 0;
368
369 // Init insertion types, including their sequence
370 if ( iaux_init_ins_types(iaux) < 0 ) return -1;
371
372 iaux_init_sequence_context(iaux);
373
374 return iaux->ntypes;
375 }
376 #undef MINUS_CONST
377
378 static int iaux_set_consensus(indel_aux_t *iaux, int ismpl)
379 {
380 if ( !iaux->rcns )
381 iaux->rcns = rcns_init(iaux->pos, iaux->left, iaux->right);
382 else
383 rcns_reset(iaux->rcns, iaux->pos, iaux->left, iaux->right);
384
385 rcns_set_reads(iaux->rcns, iaux->plp[ismpl], iaux->nplp[ismpl]);
386
387 iaux->cns_seq = rcns_get_consensus(iaux->rcns, iaux->ref + iaux->left);
388
389 // todo:
390 // rcns should also collect localized number of mismatches as a substitute
391 // for uninformative MQ. This would not affect calling but would help with
392 // filtering
393
394 return 0;
395 }
396
397 #if 0
398 // Finds the smallest index in the seq_pos array holding value equal to pos, or if there is no
399 // such value, the largest index with value smaller than pos. Starts at initial guess ioff.
400 // This could use a binary search but the assumption is that the initial guess is indel-size close
401 // to the actual coordinate.
402 //
403 // TODO: remove this function and seq_pos from cns creation as it seems unnecessary
404 static int find_ref_offset(hts_pos_t pos, hts_pos_t *seq_pos, int nseq_pos, int ioff)
405 {
406 if ( ioff<0 ) ioff = 0;
407 else if ( ioff >= nseq_pos ) ioff = nseq_pos - 1;
408 if ( seq_pos[ioff] < pos )
409 {
410 while ( ioff+1 < nseq_pos && seq_pos[ioff] < pos ) ioff++;
411 if ( seq_pos[ioff] > pos ) ioff--;
412 return ioff;
413 }
414 while ( ioff > 0 && seq_pos[ioff-1] >= pos ) ioff--;
415 return ioff;
416 }
417 #endif
418
419 static int iaux_align_read(indel_aux_t *iaux, bam1_t *bam, uint8_t *ref_seq, int nref_seq)
420 {
421 if ( bam->core.flag & BAM_FUNMAP ) return 1; // skip unmapped reads
422
423 // Trim both ref and qry to the window of interest
424 hts_pos_t ref_beg = iaux->left; // fa ref coordinates
425 hts_pos_t ref_end = iaux->right < ref_beg + nref_seq ? iaux->right : ref_beg + nref_seq - 1;
426
427 cigar_state_t cigar;
428 cstate_init(&cigar,bam);
429 int qry_off1, qry_off2, ref_off1, ref_off2;
430 if ( ref_beg > bam->core.pos )
431 {
432 // the read needs trimming from left
433 qry_off1 = cstate_seek_fwd(&cigar, &ref_beg, 1);
434 ref_off1 = ref_beg - iaux->left;
435
436 if ( ref_beg + (bam->core.l_qseq - qry_off1) > ref_end )
437 {
438 // the read needs trimming from right
439 qry_off2 = ref_end - ref_beg + qry_off1;
440 ref_off2 = ref_end - iaux->left;
441 }
442 else
443 {
444 // the ref template needs trimming from right
445 qry_off2 = bam->core.l_qseq - 1;
446 ref_off2 = ref_off1 + qry_off2 - qry_off1;
447 }
448 }
449 else
450 {
451 // the ref template needs trimming from left
452 qry_off1 = 0;
453 ref_off1 = bam->core.pos - ref_beg;
454
455 if ( bam->core.pos + bam->core.l_qseq - 1 > ref_end )
456 {
457 // the read needs trimming from right
458 ref_off2 = ref_end - iaux->left;
459 qry_off2 = ref_off2 - ref_off1;
460 }
461 else
462 {
463 // the ref template needs trimming from right
464 qry_off2 = bam->core.l_qseq - 1;
465 ref_off2 = ref_off1 + qry_off2 - qry_off1;
466 }
467 }
468 //fprintf(bcftools_stderr,"xtrim: %s .. left,right=%d,%d rbeg,end=%d,%d qpos=%d qlen=%d qoff=%d,%d roff=%d,%d rlen=%d\n",bam_get_qname(bam),iaux->left,iaux->right,(int)ref_beg,(int)ref_end,(int)bam->core.pos,bam->core.l_qseq, qry_off1,qry_off2,ref_off1,ref_off2,nref_seq);
469
470 assert( qry_off1<=qry_off2 );
471 assert( qry_off1>=0 && qry_off1<bam->core.l_qseq );
472 assert( qry_off2>=0 && qry_off2<bam->core.l_qseq );
473
474 assert( ref_off1<=ref_off2 );
475 assert( ref_off1>=0 && ref_off1<nref_seq );
476 assert( ref_off2>=0 && ref_off2<nref_seq );
477
478 // prepare query sequence
479 int i, qlen = qry_off2 - qry_off1 + 1, rlen = ref_off2 - ref_off1 + 1;
480 if ( iaux->nqry_seq < qlen )
481 {
482 uint8_t *tmp = (uint8_t*) realloc(iaux->qry_seq, qlen);
483 if ( !tmp ) return -1; // critical error
484 iaux->qry_seq = tmp;
485 iaux->nqry_seq = qlen;
486 }
487 uint8_t *seq = bam_get_seq(bam);
488 for (i=qry_off1; i<=qry_off2; i++) iaux->qry_seq[i-qry_off1] = seq_nt16_int[bam_seqi(seq,i)];
489
490 // prepare qualities, either BQ or BAQ qualities (ZQ)
491 if ( iaux->nqual < qlen )
492 {
493 uint8_t *tmp = (uint8_t*) realloc(iaux->qual, qlen);
494 if ( !tmp ) return -1; // critical error
495 iaux->qual = tmp;
496 iaux->nqual = qlen;
497 }
498 uint8_t *qual = iaux->qual;
499 const uint8_t *qq = bam_get_qual(bam);
500 const uint8_t *bq = (uint8_t*)bam_aux_get(bam, "ZQ");
501 if ( bq ) bq++; // skip type
502 for (i=qry_off1; i<=qry_off2; i++)
503 {
504 int j = i - qry_off1;
505 qual[j] = bq ? qq[i] + (bq[i] - 64) : qq[i];
506 if ( qual[j] > 30 ) qual[j] = 30;
507 if ( qual[j] < 7 ) qual[j] = 7;
508 }
509
510 // Illumina
511 probaln_par_t apf = { 1e-4, 1e-2, 10 };
512
513 // align
514 int score = probaln_glocal(ref_seq + ref_off1, rlen, iaux->qry_seq, qlen, qual, &apf, 0, 0);
515 int adj_score = (int)(100. * score / qlen + .499) * iaux->bca->indel_bias;
516
517 #if DEBUG_ALN
518 fprintf(bcftools_stderr,"aln: %d/%d\t%s\n\tref: ",score,adj_score,bam_get_qname(bam));
519 for (i=0; i<rlen; i++) fprintf(bcftools_stderr,"%c","ACGTN"[(int)ref_seq[ref_off1 + i]]);
520 fprintf(bcftools_stderr,"\n\tqry: ");
521 for (i=0; i<qlen; i++) fprintf(bcftools_stderr,"%c","ACGTN"[(int)iaux->qry_seq[i]]);
522 fprintf(bcftools_stderr,"\n\tqual: ");
523 for (i=0; i<qlen; i++) fprintf(bcftools_stderr,"%c",(char)(qual[i]+64));
524 fprintf(bcftools_stderr,"\n\ttrim: qry_len=%d qry_off=%d,%d ref_len=%d ref_off=%d,%d ref_beg,end=%d,%d\n",qlen,qry_off1,qry_off2,rlen,ref_off1,ref_off2,(int)ref_beg,(int)ref_end);
525 #endif
526
527 if ( adj_score > 255 ) adj_score = 255;
528 return score<<8 | adj_score;
529 }
530
531 // Score all reads for this sample and indel type using the up to two consensus sequence templates.
532 // On output sets iaux->read_scores[iread*ntypes+itype] = (raw_score<<8 | length_adjusted_score)
533 static int iaux_score_reads(indel_aux_t *iaux, int ismpl, int itype)
534 {
535 int i;
536 cns_seq_t *cns = iaux->cns_seq;
537 while ( cns->nseq )
538 {
539 // Resize buffers if necessary
540 int ref_len = cns->nseq + iaux->types[itype];
541 if ( iaux->nref_seq < ref_len )
542 {
543 uint8_t *ref_buf = (uint8_t*) realloc(iaux->ref_seq,sizeof(uint8_t)*ref_len);
544 if ( !ref_buf ) return -1;
545 iaux->ref_seq = ref_buf;
546 iaux->nref_seq = ref_len;
547 }
548
549 // Apply the indel and create the template ref sequence...
550 memcpy(iaux->ref_seq,cns->seq,(cns->ipos+1)*sizeof(*iaux->ref_seq));
551 if ( iaux->types[itype] < 0 ) // deletion
552 memcpy(iaux->ref_seq + cns->ipos + 1, cns->seq + cns->ipos + 1 - iaux->types[itype], (cns->nseq - cns->ipos - 1 + iaux->types[itype])*sizeof(*iaux->ref_seq));
553 else
554 {
555 char *ins = &iaux->inscns[itype*iaux->max_ins_len];
556 for (i=0; i<iaux->types[itype]; i++) iaux->ref_seq[cns->ipos+1+i] = ins[i];
557 memcpy(iaux->ref_seq + cns->ipos + 1 + iaux->types[itype], cns->seq + 1 + cns->ipos, (cns->nseq - cns->ipos - 1)*sizeof(*iaux->ref_seq));
558 }
559
560 #if DEBUG_ALN
561 fprintf(bcftools_stderr,"template %d, type %d, sample %d: ",cns==iaux->cns_seq?0:1,itype,ismpl);
562 for (i=0; i<ref_len; i++) fprintf(bcftools_stderr,"%c","ACGTN"[(int)iaux->ref_seq[i]]);
563 fprintf(bcftools_stderr,"\n");
564 #endif
565
566 // Align and score reads
567 for (i=0; i<iaux->nplp[ismpl]; i++)
568 {
569 const bam_pileup1_t *plp = iaux->plp[ismpl] + i;
570 int aln_score = iaux_align_read(iaux, plp->b, iaux->ref_seq, ref_len);
571 int *score = &iaux->read_scores[i*iaux->ntypes+itype];
572 if ( cns==iaux->cns_seq || *score > aln_score ) *score = aln_score;
573 }
574 cns++;
575 }
576 return 0;
577 }
578
579 // Determines indel quality for each read and populates 22 bits of pileup aux field with
580 // three integers as follows
581 // plp->aux = indel_type << 16 | seqQ << 8 | indelQ
582 static int iaux_eval_scored_reads(indel_aux_t *iaux, int ismpl)
583 {
584 int i,j;
585 for (i=0; i<iaux->nplp[ismpl]; i++)
586 {
587 bam_pileup1_t *plp = iaux->plp[ismpl] + i;
588
589 // Find the best indel type and the ref type, their scores difference is the indel quality
590 int *score = &iaux->read_scores[i*iaux->ntypes];
591 int alt_score = INT_MAX, alt_j = 0;
592 for (j=0; j<iaux->iref_type; j++)
593 if ( alt_score > score[j] ) alt_score = score[j], alt_j = j;
594 for (j=iaux->iref_type+1; j<iaux->ntypes; j++)
595 if ( alt_score > score[j] ) alt_score = score[j], alt_j = j;
596 int ref_score = score[iaux->iref_type];
597 int sc0, sc1, j0;
598 if ( alt_score < ref_score ) sc0 = alt_score, sc1 = ref_score, j0 = alt_j;
599 else sc0 = ref_score, sc1 = alt_score, j0 = iaux->iref_type;
600
601 int indelQ = (sc1>>8) - (sc0>>8); // low=bad, high=good
602 int seqQ = iaux->ref_qual[alt_j];
603
604 // Reduce indelQ. High length-normalized alignment scores (i.e. bad alignments)
605 // lower the quality more (e.g. gnuplot> plot [0:111] (1-x/111.)*255)
606 int len_normQ = sc0 & 0xff; // length-normalized score of the best match (ref or alt)
607 int adj_indelQ; // final indelQ used in calling
608 if ( len_normQ > 111 )
609 {
610 // In the original code reads matching badly to any indel type or reference had indelQ set to 0
611 // here and thus would be effectively removed from calling. This leads to problems when there are
612 // many soft clipped reads and a few good matching indel reads (see noisy-softclips.bam in
613 // mpileup-tests). Only the few good quality indel reads would become visible to the caller and
614 // the indel would be called with high quality. Here we change the logic to make the badly matching
615 // reads low quality reference reads. The threshold was set to make the test case still be called
616 // as an indel, but with very low quality.
617 //
618 // Original code:
619 // adj_indelQ = 0;
620 //
621 adj_indelQ = 12;
622 j0 = iaux->iref_type;
623 }
624 else
625 adj_indelQ = (int)((1. - len_normQ/111.) * indelQ + .499);
626
627 #if DEBUG_ALN
628 // Prints the selected indel type (itype); adjusted indelQ which will be used if bigger than seqQ;
629 // raw indelQ; length-normalized indelQ and sequence context quality; ref and best alt indel type
630 // and their raw and length-normalized scores
631 fprintf(bcftools_stderr,"itype=%d adj_indelQ=%d\trawQ=%d\tlen_normQ=%d\tseqQ=%d\tref:%d=%d/%d alt:%d=%d/%d)\t%s\n",
632 j0,adj_indelQ,indelQ,len_normQ,seqQ,iaux->iref_type,ref_score>>8,ref_score&0xff,alt_j,alt_score>>8,alt_score&0xff,bam_get_qname(plp->b));
633 #endif
634
635 if ( adj_indelQ > seqQ ) adj_indelQ = seqQ; // seqQ already capped at 255
636 plp->aux = j0<<16 | seqQ<<8 | adj_indelQ; // use 22 bits in total
637 iaux->sum_qual[j0] += adj_indelQ;
638 }
639 return 0;
640 }
641
642 // Find the best indel types, include the ref type plus maximum three alternate indel alleles.
643 static int iaux_eval_best_indels(indel_aux_t *iaux)
644 {
645 bcf_callaux_t *bca = iaux->bca;
646 bca->maxins = iaux->max_ins_len;
647 bca->inscns = (char*) realloc(bca->inscns, bca->maxins * 4);
648 if ( bca->maxins && !bca->inscns ) return -1;
649
650 // insertion sort, descending, high-quality indels come first
651 int i,j,t, tmp, *sumq = iaux->sum_qual, ntypes = iaux->ntypes;
652 for (t=0; t<ntypes; t++) sumq[t] = sumq[t]<<6 | t;
653 for (t=1; t<ntypes; t++)
654 for (j=t; j>0 && sumq[j] > sumq[j-1]; j--)
655 tmp = sumq[j], sumq[j] = sumq[j-1], sumq[j-1] = tmp;
656 for (t=0; t<ntypes; t++) // look for the reference type
657 if ( (sumq[t]&0x3f)==iaux->iref_type ) break;
658 if ( t )
659 {
660 // move the reference type to the first
661 tmp = sumq[t];
662 for (; t>0; t--) sumq[t] = sumq[t-1];
663 sumq[0] = tmp;
664 }
665
666 // Initialize bca's structures and create a mapping between old and new types
667 int old2new_type[MAX_TYPES];
668 for (t=0; t<iaux->ntypes; t++)
669 {
670 int itype = sumq[t] & 0x3f;
671 old2new_type[itype] = t;
672 if ( t>=4 ) continue;
673 bca->indel_types[t] = iaux->types[itype];
674 if ( bca->indel_types[t] <= 0 ) continue;
675 memcpy(&bca->inscns[t*bca->maxins], &iaux->inscns[itype*iaux->max_ins_len], bca->maxins);
676 }
677
678 // Update indel type in plp->aux for all reads
679 int ismpl, n_alt = 0;
680 for (ismpl=0; ismpl<iaux->nsmpl; ismpl++)
681 {
682 for (i=0; i<iaux->nplp[ismpl]; i++)
683 {
684 bam_pileup1_t *plp = iaux->plp[ismpl] + i;
685 int itype_old = (plp->aux >> 16) & 0x3f;
686 int itype_new = old2new_type[itype_old];
687 plp->aux = itype_new<<16 | (itype_new>=4 ? 0 : (plp->aux & 0xffff));
688 if ( itype_new>0 ) n_alt++;
689 }
690 }
691 return n_alt;
692 }
693
694 /*
695 notes:
696 - n .. number of samples
697 - the routine sets bam_pileup1_t.aux (27 bits) of each read as follows:
698 - 5: unused
699 - 6: the call; index to bcf_callaux_t.indel_types .. (aux>>16)&0x3f
700 - 8: estimated sequence quality .. (aux>>8)&0xff
701 - 8: indel quality .. aux&0xff
702 */
703 int bcf_iaux_gap_prep(int n, int *n_plp, bam_pileup1_t **plp, int pos, bcf_callaux_t *bca, const char *ref)
704 {
705 assert(!(ref == 0 || bca == 0)); // can this ever happen? when?
706 if (ref == 0 || bca == 0) return -1;
707
708 if ( !bca->iaux ) bca->iaux = calloc(1,sizeof(indel_aux_t));
709 indel_aux_t *iaux = bca->iaux;
710 iaux->nsmpl = n;
711 iaux->nplp = n_plp;
712 iaux->plp = plp;
713 iaux->bca = bca;
714 iaux->ref = ref;
715 iaux->pos = pos;
716 iaux->chr = bca->chr;
717
718 // Check if there is an indel at this position and if yes, find all indel types and determine
719 // window boundaries. todo: We want this information cached so that for long reads we don't keep
720 // redoing the whole analysis again and again
721 int ntypes = iaux_init_types(iaux);
722 if ( ntypes<=0 ) return -1;
723
724 debug_print_types(iaux);
725
726 // Create two template consensus sequences for each sample (assuming max diploid organism).
727 // Then apply each indel type on top of the templates, realign every read and remember score
728 int i,j;
729 for (i=0; i<iaux->nsmpl; i++)
730 {
731 iaux_set_consensus(iaux, i);
732 iaux_init_scores(iaux, i);
733 for (j=0; j<ntypes; j++) iaux_score_reads(iaux, i, j);
734 iaux_eval_scored_reads(iaux, i);
735 }
736 int nalt = iaux_eval_best_indels(iaux);
737 return nalt > 0 ? 0 : -1;
738 }
739