Debian Codegraph @

bcftools/bam2bcf_iaux.c

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