Debian Codegraph @

bcftools/read_consensus.c

raw symbols SCIP
1 /* read_consensus.c -- create and maintain consensus of reads
2
3 Copyright (C) 2022 Genome Research Ltd.
4
5 Author: pd3@sanger
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 #include <assert.h>
26 #include <math.h>
27 #include "bcftools.h"
28 #include "read_consensus.h"
29 #include "cigar_state.h"
30 #include "kheap.h"
31
32
33 // Frequency arrays for each variant type
34 #define NI 10 // number of alternative insertion sequences at one position in a single sample
35 typedef struct
36 {
37 char *nt16_seq[NI];
38 int len[NI];
39 int freq[NI];
40 }
41 ins_freq_t;
42
43 typedef struct
44 {
45 int len[NI];
46 int freq[NI];
47 }
48 del_freq_t;
49
50 #define BF_DEL 5
51 typedef struct
52 {
53 int base[6]; // frequencies of A,C,G,T,N,deletion
54 }
55 base_freq_t;
56
57
58 // Candidate variants for each interesting position to build consensus haplotypes
59 enum variant_type { snv, ins, del, done };
60 typedef struct
61 {
62 enum variant_type vtype;
63 hts_pos_t pos; // variant position (reference sequence coordinates), indels follow VCF convention
64 int idx; // temporary 0-based index to rcns.cvar
65 int which, // base/ins/del in rcns.[base|ins|del]_freq array
66 depth; // coverage at the position
67 float af, af_dev; // variant allele frequency (just for debugging printout) and absolute af deviation from 0.5
68 }
69 candidate_var_t;
70 static inline int cvar_not_preferred(candidate_var_t *a, candidate_var_t *b)
71 {
72 if ( a->af_dev == b->af_dev ) return a->depth < b->depth ? 1 : 0;
73 return a->af_dev > b->af_dev ? 1 : 0;
74 }
75 KHEAP_INIT(cvh, candidate_var_t, cvar_not_preferred);
76 typedef khp_cvh_t cvar_heap_t;
77
78 #define MAX_NCVAR 8 // This results in alloc() of 2^MAX_NCVAR possible haplotypes
79 #define NHAP (1<<MAX_NCVAR) // The number of possible haplotypes
80 struct _read_cns_t
81 {
82 hts_pos_t pos, beg, end; // current position and window boundaries (0-based, inclusive, ref seq coordinates)
83 int band, // maximum absolute deviation from the diagonal, used for BAQ alignment
84 max_del; // maximum deletion lentgth starting at the tested position
85 base_freq_t *base_freq; // frequency of each variant type: base, ins, del
86 ins_freq_t *ins_freq;
87 del_freq_t *del_freq;
88 char *stmp; // temporary array
89 int mstmp, mfreq; // allocated size of stmp and *_freq arrays
90 cvar_heap_t *cv_heap; // heap to maintain the top MAX_NCVAR variants
91 int ncvar; // cvar and cv_heap size
92 candidate_var_t cvar[MAX_NCVAR]; // candidate variants, sorted by position and type
93 int hap_freq[NHAP]; // haplotype frequencies
94 bam_pileup1_t *plp; // reads to construct consensus from
95 int nplp; // number of reads in the pileup
96 int cns_hap[2], ncns; // the top two consensus haplotypes and the number of haplotypes to use
97 int mcns; // the allocated size of cns.seq and cns.pos buffers
98 cns_seq_t cns[3]; // the consensus sequences to fill
99 };
100
101 void rcns_destroy(read_cns_t *rcns)
102 {
103 if ( !rcns ) return;
104 int i,j;
105 for (i=0; i<rcns->mfreq; i++)
106 {
107 ins_freq_t *ifrq = &rcns->ins_freq[i];
108 for (j=0; j<NI && ifrq->nt16_seq[j]; j++) free(ifrq->nt16_seq[j]);
109 }
110 for (i=0; i<2; i++)
111 free(rcns->cns[i].seq);
112 free(rcns->ins_freq);
113 free(rcns->del_freq);
114 free(rcns->base_freq);
115 free(rcns->stmp);
116 khp_destroy(cvh,rcns->cv_heap);
117 free(rcns);
118 }
119 static int init_arrays(read_cns_t *rcns)
120 {
121 int i,j,n = rcns->end - rcns->beg + 1;
122 if ( n > rcns->mfreq )
123 {
124 ins_freq_t *ifrq = (ins_freq_t*) realloc(rcns->ins_freq,sizeof(*rcns->ins_freq)*n);
125 if ( !ifrq ) return -1;
126 rcns->ins_freq = ifrq;
127 memset(ifrq+rcns->mfreq,0,sizeof(*rcns->ins_freq)*(n-rcns->mfreq));
128
129 del_freq_t *dfrq = (del_freq_t*) realloc(rcns->del_freq,sizeof(*rcns->del_freq)*n);
130 if ( !dfrq ) return -1;
131 rcns->del_freq = dfrq;
132 memset(dfrq+rcns->mfreq,0,sizeof(*rcns->del_freq)*(n-rcns->mfreq));
133
134 base_freq_t *bfrq = (base_freq_t*) realloc(rcns->base_freq,sizeof(*rcns->base_freq)*n);
135 if ( !bfrq ) return -1;
136 rcns->base_freq = bfrq;
137 memset(bfrq+rcns->mfreq,0,sizeof(*rcns->base_freq)*(n-rcns->mfreq));
138
139 rcns->mfreq = n;
140 }
141 memset(rcns->base_freq,0,sizeof(*rcns->base_freq)*n);
142 memset(rcns->del_freq,0,sizeof(*rcns->del_freq)*n);
143 for (i=0; i<n; i++)
144 {
145 ins_freq_t *ifrq = &rcns->ins_freq[i];
146 for (j=0; j<NI && ifrq->nt16_seq[j]; j++) free(ifrq->nt16_seq[j]);
147 }
148 memset(rcns->ins_freq,0,sizeof(*rcns->ins_freq)*n);
149 return 0;
150 }
151 int rcns_reset(read_cns_t *rcns, hts_pos_t pos, hts_pos_t beg, hts_pos_t end)
152 {
153 rcns->band = 0;
154 rcns->pos = pos;
155 rcns->beg = beg;
156 rcns->end = end;
157 int i;
158 for (i=0; i<2; i++) rcns->cns[i].nseq = rcns->cns[i].ipos = 0;
159 // this should not be necessary if the caller did run all steps
160 while (rcns->cv_heap->ndat) khp_delete(cvh, rcns->cv_heap);
161 return init_arrays(rcns);
162 }
163
164 static inline void add_base(read_cns_t *rcns, int ref_pos, int nt16)
165 {
166 int i = ref_pos - rcns->beg;
167 rcns->base_freq[i].base[seq_nt16_int[nt16]]++;
168 }
169 static void add_ins(read_cns_t *rcns, int ref_pos, int seq_pos, uint8_t *raw_seq, int len)
170 {
171 int i = ref_pos - rcns->beg;
172 ins_freq_t *ifrq = &rcns->ins_freq[i];
173 char *str;
174 if ( rcns->mstmp < len )
175 {
176 str = realloc(rcns->stmp,len*sizeof(*str));
177 if ( !str ) return;
178 rcns->mstmp = len;
179 rcns->stmp = str;
180 }
181 else
182 str = rcns->stmp;
183 for (i=0; i<len; i++) str[i] = bam_seqi(raw_seq,i+seq_pos);
184
185 for (i=0; i<NI && ifrq->nt16_seq[i]; i++)
186 if ( ifrq->len[i]==len && !memcmp(ifrq->nt16_seq[i],str,len) ) break;
187
188 if ( i>=NI ) return; // too many choices, typically homopolymers in long reads; discard
189
190 if ( !ifrq->nt16_seq[i] ) // new insertion
191 {
192 if ( !(ifrq->nt16_seq[i]=malloc(len)) ) return;
193 memcpy(ifrq->nt16_seq[i], str, len);
194 ifrq->len[i] = len;
195 }
196 ifrq->freq[i]++;
197 }
198 static void add_del(read_cns_t *rcns, int ref_pos, int len)
199 {
200 int i = ref_pos - rcns->beg;
201 int j,n = rcns->end - rcns->beg + 1;
202 if ( i + len + 1 < n ) n = i + len + 1;
203 for (j=i+1; j<n; j++)
204 rcns->base_freq[j].base[BF_DEL]++;
205
206 del_freq_t *dfrq = &rcns->del_freq[i];
207 for (i=0; i<NI && dfrq->len[i]; i++)
208 if ( dfrq->len[i]==len ) break;
209
210 if ( i>=NI ) return; // too many choices, typically homopolymers in long reads; discard
211
212 if ( !dfrq->len[i] ) dfrq->len[i] = len; // new deletion
213 dfrq->freq[i]++;
214 }
215
216 read_cns_t *rcns_init(hts_pos_t pos, hts_pos_t beg, hts_pos_t end)
217 {
218 read_cns_t *rcns = (read_cns_t*) calloc(1,sizeof(read_cns_t));
219 rcns->pos = pos;
220 rcns->beg = beg;
221 rcns->end = end;
222 rcns->cv_heap = khp_init(cvh);
223 if ( init_arrays(rcns)!=0 )
224 {
225 rcns_destroy(rcns);
226 return NULL;
227 }
228 return rcns;
229 }
230
231 int rcns_set_reads(read_cns_t *rcns, bam_pileup1_t *plp, int nplp)
232 {
233 // save the reads for phasing, this can be called multiple times
234 rcns->plp = plp;
235 rcns->nplp = nplp;
236
237 // fill consensus arrays
238 int i,j,k, local_band_max = 0; // maximum absolute deviation from diagonal
239 for (i=0; i<nplp; i++) // for each read...
240 {
241 const bam_pileup1_t *p = plp + i;
242 bam1_t *b = p->b;
243 int x = b->core.pos; // ref coordinate
244 int y = 0; // seq coordinate
245 uint32_t *cigar = bam_get_cigar(b);
246 uint8_t *seq = bam_get_seq(b);
247 int local_band = 0; // current deviation from diagonal
248 for (k = 0; k < b->core.n_cigar; ++k)
249 {
250 int op = cigar[k] & BAM_CIGAR_MASK;
251 int len = cigar[k] >> BAM_CIGAR_SHIFT;
252 if ( op==BAM_CSOFT_CLIP ) y += len;
253 else if ( op==BAM_CMATCH || op==BAM_CEQUAL || op==BAM_CDIFF )
254 {
255 if ( x<rcns->end && x+len>rcns->beg )
256 {
257 int j_beg = rcns->beg > x ? rcns->beg - x : 0; // how many bases to skip in the ref and qry
258 int j_end = rcns->end < x + len - 1 ? rcns->end - x : len - 1;
259 x += j_beg;
260 y += j_beg;
261 for (j=j_beg; j<=j_end; j++, x++, y++) add_base(rcns,x,bam_seqi(seq,y));
262 }
263 else
264 {
265 x += len;
266 y += len;
267 }
268 }
269 else if ( op==BAM_CINS )
270 {
271 if ( x>rcns->beg && x<rcns->end )
272 {
273 local_band += p->indel;
274 add_ins(rcns,x-1,y,seq,len); // x-1: one base before as in VCF
275 }
276 y += len;
277 }
278 else if ( op==BAM_CDEL || op==BAM_CREF_SKIP ) /* note: unsure about BAM_CREF_SKIP, don't have data to test */
279 {
280 if ( x>rcns->beg && x+len-1<=rcns->end )
281 {
282 local_band += -p->indel;
283 add_del(rcns,x-1,len); // x-1: one base before as in VCF
284 }
285 x += len;
286 }
287 else if ( op==BAM_CHARD_CLIP ) continue;
288 else error("rcns_set_reads todo: unknown cigar operator %d\n",op);
289 if ( local_band_max < local_band ) local_band_max = local_band;
290 }
291
292 // Track the biggest deviation +/- from diagonal, used in BAQ alignment step.
293 if ( rcns->band < local_band_max ) rcns->band = local_band_max;
294 }
295
296 return 0;
297 }
298
299 #if DEBUG_RCNS
300 static void debug_print_base_freqs(read_cns_t *rcns, const char *ref)
301 {
302 int i,j,k,n = rcns->end - rcns->beg + 1;
303 fprintf(stderr,"beg,end,pos=%d %d %d\n",(int)rcns->beg,(int)rcns->end,(int)rcns->pos);
304 base_freq_t *bfreq = rcns->base_freq;
305 ins_freq_t *ifreq = rcns->ins_freq;
306 del_freq_t *dfreq = rcns->del_freq;
307 for (i=0; i<n && ref[i]; i++)
308 {
309 fprintf(stderr,"%"PRIhts_pos" %c\t",rcns->beg+i+1,ref[i]);
310 for (j=0; j<6; j++)
311 fprintf(stderr,"\t%d%s",bfreq[i].base[j],ref[i]=="ACGTNi"[j]?"*":"");
312 fprintf(stderr,"\t");
313 for (j=0; j<NI && dfreq[i].len[j]; j++)
314 fprintf(stderr," -%d:%d",dfreq[i].len[j],dfreq[i].freq[j]);
315 fprintf(stderr,"\t");
316 for (j=0; j<NI && ifreq[i].len[j]; j++)
317 {
318 fprintf(stderr," +");
319 for (k=0; k<ifreq[i].len[j]; k++) fprintf(stderr,"%c",seq_nt16_str[(int)ifreq[i].nt16_seq[j][k]]);
320 fprintf(stderr,":%d",ifreq[i].freq[j]);
321 }
322 fprintf(stderr,"\n");
323 }
324 }
325 static const char *vtype2string(enum variant_type vtype)
326 {
327 if ( vtype==snv ) return "snv";
328 if ( vtype==ins ) return "ins";
329 if ( vtype==del ) return "del";
330 return "???";
331 }
332 static void debug_print_candidate_variants(read_cns_t *rcns)
333 {
334 int i;
335 fprintf(stderr,"Candidate variants:\n");
336 for (i=0; i<rcns->ncvar; i++)
337 {
338 candidate_var_t *var = &rcns->cvar[i];
339 fprintf(stderr,"\tvar%d pos=%"PRIhts_pos" idx=%d vtype=%s which=%d depth=%d af=%f af_dev=%f\n",
340 i,var->pos+1,var->idx,vtype2string(var->vtype),var->which,var->depth,var->af,var->af_dev);
341 }
342 }
343 static void debug_print_haplotype_frequency_spectrum(read_cns_t *rcns)
344 {
345 int i,j;
346 fprintf(stderr,"Haplotype frequencies (bits from left correspond to var0,1,..):\n");
347 for (i=0; i<NHAP; i++)
348 {
349 if ( !rcns->hap_freq[i] ) continue;
350 fprintf(stderr,"\t%d: ",i);
351 for (j=0; j<rcns->ncvar; j++)
352 fprintf(stderr,"%d", i&(1<<j) ? 1 : 0);
353 fprintf(stderr,"\t%d\n", rcns->hap_freq[i]);
354 }
355 }
356 static void debug_print_consensus(read_cns_t *rcns, const char *ref)
357 {
358 int i,j,n = rcns->end - rcns->beg + 1;
359 fprintf(stderr,"ref: ");
360 for (i=0; i<n && ref[i]; i++) fprintf(stderr,"%c",ref[i]);
361 fprintf(stderr,"\n");
362 for (i=0; i<2; i++)
363 {
364 if ( !rcns->cns[i].nseq ) break;
365 fprintf(stderr,"Consensus%d: ",i);
366 for (j=0; j<=rcns->cns[i].ipos; j++)
367 fprintf(stderr,"%c","ACGTN"[(int)rcns->cns[i].seq[j]]);
368 fprintf(stderr,"#");
369 for (; j<rcns->cns[i].nseq; j++)
370 fprintf(stderr,"%c","ACGTN"[(int)rcns->cns[i].seq[j]]);
371 fprintf(stderr,"\n");
372 }
373 }
374 #else
375 #define debug_print_base_freqs(rcns,ref)
376 #define debug_print_candidate_variants(rcns)
377 #define debug_print_haplotype_frequency_spectrum(rcns)
378 #define debug_print_consensus(rcns,ref)
379 #endif
380
381 static int cvar_pos_cmp(const void *aptr, const void *bptr)
382 {
383 candidate_var_t *a = (candidate_var_t*)aptr;
384 candidate_var_t *b = (candidate_var_t*)bptr;
385 if ( a->pos < b->pos ) return -1;
386 if ( a->pos > b->pos ) return 1;
387 if ( a->vtype < b->vtype ) return -1;
388 if ( a->vtype > b->vtype ) return 1;
389 if ( a->which < b->which ) return -1;
390 if ( a->which > b->which ) return 1;
391 return 0;
392 }
393 static void register_variant(read_cns_t *rcns, enum variant_type vtype, int cns_pos, int which, int depth, float freq)
394 {
395 cvar_heap_t *cv_heap = rcns->cv_heap;
396 if ( vtype==done )
397 {
398 rcns->ncvar = 0;
399 while (cv_heap->ndat)
400 {
401 rcns->cvar[rcns->ncvar++] = cv_heap->dat[0];
402 khp_delete(cvh,cv_heap);
403 }
404 // sort the variants by pos,type,which to make determination of haplotypes from reads faster
405 if ( rcns->ncvar )
406 qsort(rcns->cvar, rcns->ncvar, sizeof(*rcns->cvar), cvar_pos_cmp);
407 return;
408 }
409
410 candidate_var_t var;
411 var.pos = cns_pos + rcns->beg;
412 var.which = which;
413 var.vtype = vtype;
414 var.depth = depth;
415 var.af_dev = fabs(0.5-freq);
416 var.af = freq;
417
418 int free_slot;
419
420 // keep the number of variants small, maximum MAX_NCVAR
421 if ( rcns->ncvar==MAX_NCVAR )
422 {
423 if ( cvar_not_preferred(&var,&cv_heap->dat[0]) ) return; // no need to add, the new variant is worse than the heap's worst one
424 free_slot = cv_heap->dat[0].idx;
425 khp_delete(cvh,cv_heap);
426 }
427 else
428 free_slot = rcns->ncvar++;
429 var.idx = free_slot;
430 rcns->cvar[free_slot] = var;
431 khp_insert(cvh,cv_heap,&var);
432 }
433
434 // Identify candidate variant positions. (Note that homozygous variants are not considered
435 // as those will be added trivially by taking the consensus base.) The detection limit is
436 // for now hard-wired. This has only indirect effect on sensitivity, will just not contribute
437 // to the consensus template when realigning.
438 static int select_candidate_variants(read_cns_t *rcns, const char *ref)
439 {
440 const float af_th = 0.1;
441 int i,j, n = rcns->end - rcns->beg + 1;
442 int max_ins_len = 0; // maximum total length of all insertions applied to allocate big enough buffers
443 base_freq_t *bfreq = rcns->base_freq;
444 ins_freq_t *ifreq = rcns->ins_freq;
445 del_freq_t *dfreq = rcns->del_freq;
446 for (i=0; i<n && ref[i]; i++)
447 {
448 for (j=0; j<NI && ifreq[i].len[j]; j++) max_ins_len += ifreq[i].len[j];
449
450 if ( i==rcns->pos - rcns->beg ) continue; // creating consensus from everything but the variants at the current position
451
452 int dp = 0;
453 for (j=0; j<4; j++) dp += bfreq[i].base[j];
454 for (j=0; j<NI && dfreq[i].len[j]; j++) dp += dfreq[i].freq[j];
455 for (j=0; j<NI && ifreq[i].len[j]; j++) dp += ifreq[i].freq[j];
456 float af = 0; // allele frequency
457 for (j=0; j<4; j++)
458 {
459 if ( !bfreq[i].base[j] || ref[i]=="ACGTN"[j] ) continue; // ref base or no coverage
460 af = (float)bfreq[i].base[j]/dp;
461 if ( af>af_th && af<(1-af_th) ) register_variant(rcns,snv,i,j,dp,af);
462 }
463 for (j=0; j<NI && dfreq[i].len[j]; j++)
464 {
465 af = (float)dfreq[i].freq[j]/dp;
466 if ( af>af_th && af<(1-af_th) ) register_variant(rcns,del,i,j,dp,af);
467 }
468 for (j=0; j<NI && ifreq[i].len[j]; j++)
469 {
470 af = (float)ifreq[i].freq[j]/dp;
471 if ( af>af_th && af<(1-af_th) ) register_variant(rcns,ins,i,j,dp,af);
472 }
473 }
474 register_variant(rcns,done,0,0,0,0); // finalize
475
476 // Reallocate buffers
477 if ( rcns->mcns < n + max_ins_len )
478 {
479 n += max_ins_len;
480 for (i=0; i<2; i++)
481 {
482 char *seq = (char*) realloc(rcns->cns[i].seq,sizeof(char)*n);
483 if ( !seq ) return -1;
484 rcns->cns[i].seq = seq;
485 }
486 rcns->mcns = n;
487 }
488
489 // Find the longest deletion at the query position
490 i = rcns->pos - rcns->beg;
491 rcns->max_del = 0;
492 for (j=0; j<NI && j<dfreq[i].len[j]; j++)
493 {
494 if ( rcns->max_del < dfreq[i].len[j] ) rcns->max_del = dfreq[i].len[j];
495 }
496
497 return 0;
498 }
499 static int create_haplotype_frequency_spectrum(read_cns_t *rcns)
500 {
501 memset(rcns->hap_freq,0,sizeof(rcns->hap_freq));
502
503 int i;
504 for (i=0; i<rcns->nplp; i++) // for each read...
505 {
506 const bam_pileup1_t *p = rcns->plp + i;
507 cigar_state_t cigar;
508 cstate_init(&cigar,p->b);
509
510 int j,k,hap = 0;
511 for (j=0; j<rcns->ncvar; j++)
512 {
513 candidate_var_t *cvar = &rcns->cvar[j];
514 if ( cvar->vtype==snv )
515 {
516 int iseq = cstate_seek_op_fwd(&cigar, cvar->pos, BAM_CMATCH, NULL);
517 if ( iseq==-2 ) break;
518 if ( iseq==-1 ) continue;
519 int nt16 = bam_seqi(cigar.seq, iseq);
520 if ( seq_nt16_int[nt16]==cvar->which ) hap |= 1<<j;
521 }
522 else if ( cvar->vtype==ins )
523 {
524 int len;
525 ins_freq_t *ifrq = &rcns->ins_freq[cvar->pos - rcns->beg];
526 int iseq = cstate_seek_op_fwd(&cigar, cvar->pos+1, BAM_CINS, &len);
527 if ( iseq==-2 ) break;
528 if ( iseq==-1 ) continue;
529 if ( len!=ifrq->len[cvar->which] ) continue;
530 for (k=0; k<ifrq->len[cvar->which]; k++)
531 if ( bam_seqi(cigar.seq,iseq+k)!=ifrq->nt16_seq[cvar->which][k] ) break;
532 if ( k==ifrq->len[cvar->which] ) hap |= 1<<j;
533 }
534 else if ( cvar->vtype==del )
535 {
536 int len;
537 del_freq_t *dfrq = &rcns->del_freq[cvar->pos - rcns->beg];
538 int ret = cstate_seek_op_fwd(&cigar, cvar->pos+1, BAM_CDEL, &len);
539 if ( ret==-2 ) break;
540 if ( ret==-1 ) continue;
541 if ( len!=dfrq->len[cvar->which] ) continue;
542 hap |= 1<<j;
543 }
544 }
545 rcns->hap_freq[hap]++;
546 }
547 return 0;
548 }
549
550 typedef struct
551 {
552 int haplotype, count;
553 }
554 ii_t;
555
556 static int ii_cmp(const void *a, const void *b)
557 {
558 if ( ((ii_t*)a)->count > ((ii_t*)b)->count ) return -1;
559 if ( ((ii_t*)a)->count < ((ii_t*)b)->count ) return 1;
560 return 0;
561 }
562
563 // Select two most common haplotypes trying to account for 1bp errors. Haplotypes
564 // are represented as 8-bit numbers, each bit corresponds to one candidate variant.
565 static int correct_haplotype_errors(read_cns_t *rcns)
566 {
567 int i,j, tot = 0;
568 ii_t freq[NHAP];
569 for (i=0; i<NHAP; i++)
570 {
571 freq[i].haplotype = i;
572 freq[i].count = rcns->hap_freq[i];
573 tot += rcns->hap_freq[i];
574 }
575 qsort(freq, NHAP, sizeof(ii_t), ii_cmp); // sort haplotypes in descending order
576 for (i=NHAP-1; i>1; i--)
577 {
578 if ( !freq[i].count ) continue;
579 if ( freq[1].count > tot - freq[0].count - freq[1].count ) break; // the top2 hapotypes cannot change anymore
580
581 // Find a similar haplotype with the highest frequency. Assuming errors go in 0->1
582 // direction only and considering one error only.
583 int count = freq[i].count, max_hap = 0;
584 for (j=0; j<MAX_NCVAR; j++)
585 {
586 if ( !(freq[i].haplotype & (1U<<j)) ) continue; // j-th bit not set in this haplotype
587 int hap = freq[i].haplotype ^ (1U<<j); // toggle j-th bit
588 assert( hap>=0 && hap<NHAP );
589 if ( count < rcns->hap_freq[hap] ) count = rcns->hap_freq[hap], max_hap = hap;
590 }
591 if ( count == freq[i].count ) continue;
592
593 // Update frequency and sort the two modified elements
594 count = freq[i].count;
595 freq[i].count = 0;
596 rcns->hap_freq[freq[i].haplotype] = 0;
597 rcns->hap_freq[max_hap] += count;
598 for (j=i+1; j<NHAP; j++)
599 {
600 if ( !freq[j].count ) break;
601 ii_t tmp = freq[j-1]; freq[j-1] = freq[j]; freq[j] = tmp;
602 }
603 for (j=i-1; j>=0; j--)
604 {
605 if ( freq[j].haplotype==max_hap ) freq[j].count += count; // update the best matching haplotype
606 if ( freq[j].count < freq[j+1].count )
607 {
608 ii_t tmp = freq[j]; freq[j] = freq[j+1]; freq[j+1] = tmp;
609 }
610 }
611 }
612
613 // Use only one consensus if the next best haplotype is populated by less than 10% of reads
614 rcns->ncns = ((float)freq[1].count / (freq[0].count + freq[1].count) < 0.1) ? 1 : 2;
615
616 // Remove unused candidate variants from the top two haplotypes
617 int hap0 = freq[0].haplotype;
618 int hap1 = rcns->ncns==2 ? freq[1].haplotype : 0;
619 rcns->cns_hap[0] = 0;
620 rcns->cns_hap[1] = 0;
621 for (i=0,j=0; i<MAX_NCVAR; i++)
622 {
623 if ( !((hap0|hap1) & (1U<<i)) ) continue; // unused candidate variant, skip
624 if ( i!=j ) rcns->cvar[j] = rcns->cvar[i];
625 if ( hap0 & (1U<<i) ) rcns->cns_hap[0] |= 1U<<j;
626 if ( hap1 & (1U<<i) ) rcns->cns_hap[1] |= 1U<<j;
627 j++;
628 }
629 rcns->ncvar = j;
630
631 #if DEBUG_RCNS
632 // This only matters for debugging print
633 memset(rcns->hap_freq,0,NHAP*sizeof(*rcns->hap_freq));
634 rcns->hap_freq[rcns->cns_hap[1]] = freq[1].count; // NB: the order matters when ncns==1
635 rcns->hap_freq[rcns->cns_hap[0]] = freq[0].count;
636 #endif
637
638 return 0;
639 }
640
641
642 // Check how frequent are insertions adjacent to the j-th position. Note that reads with an
643 // insertion usually increment also bfreq counts at this position, but not necessarily so,
644 // therefore the counts are approximate
645 static inline void apply_consensus_insertion(read_cns_t *rcns, cns_seq_t *cns, int j, int ivar)
646 {
647 // Only apply consensus insertions that are not being tested by bam2bcf_iaux, i.e. not at the current pos
648 hts_pos_t ref_pos = rcns->beg + j;
649 if ( rcns->pos == ref_pos ) return;
650
651 // Only apply when there is no insertion at this position registered as a variant
652 while ( ivar < rcns->ncvar && rcns->cvar[ivar].pos == ref_pos )
653 {
654 if ( rcns->cvar[ivar].vtype == ins ) return;
655 ivar++;
656 }
657
658 base_freq_t *bfreq = rcns->base_freq;
659 ins_freq_t *ifreq = rcns->ins_freq;
660 int k, nreads = 0;
661 for (k=0; k<BF_DEL; k++) nreads += bfreq[j].base[k];
662 int max_freq = 0, kmax = 0;
663 for (k=0; k<NI && ifreq[j].len[k]; k++)
664 if ( max_freq < ifreq[j].freq[k] ) max_freq = ifreq[j].freq[k], kmax = k;
665
666 // Include consensus insertion only if it has more than half of the reads
667 if ( nreads > max_freq*2 ) return;
668
669 int len = ifreq[j].len[kmax];
670 char *seq = ifreq[j].nt16_seq[kmax];
671 for (k=0; k<len; k++)
672 cns->seq[cns->nseq++] = seq_nt16_int[(int)seq[k]];
673 }
674
675 // For each position of the realignment window apply either the candidate variants
676 // from ith haplotype or decide on the base/ins/del by majority vote
677 static void create_consensus(read_cns_t *rcns, const char *ref, int ith)
678 {
679 int n = rcns->end - rcns->beg + 1;
680 cns_seq_t *cns = &rcns->cns[ith];
681 base_freq_t *bfreq = rcns->base_freq;
682 ins_freq_t *ifreq = rcns->ins_freq;
683 del_freq_t *dfreq = rcns->del_freq;
684 hts_pos_t prev_pos = 0;
685 int j,k, ivar = 0;
686 for (j=0; j<n; j++)
687 {
688 hts_pos_t ref_pos = rcns->beg + j;
689 if ( rcns->pos == ref_pos ) cns->ipos = cns->nseq;
690
691 while ( ivar < rcns->ncvar && rcns->cvar[ivar].pos < ref_pos ) ivar++;
692
693 if ( ivar >= rcns->ncvar || rcns->cvar[ivar].pos != ref_pos )
694 {
695 // This position is not recognised as a het variant so take the most frequent base, including
696 // a deletion if that is most frequent. However, for deleted bases make sure they are not part
697 // of the deletion that is being tested at this positions
698 int max_freq = 0, kmax = seq_nt16_int[seq_nt16_table[(int)ref[j]]];
699 int nk = ( ref_pos < rcns->pos || ref_pos > rcns->pos + rcns->max_del ) ? BF_DEL+1 : BF_DEL;
700 for (k=0; k<nk; k++)
701 if ( max_freq < bfreq[j].base[k] ) max_freq = bfreq[j].base[k], kmax = k;
702
703 if ( kmax!=BF_DEL ) // the most frequent base can be a deletion
704 {
705 prev_pos = ref_pos;
706 cns->seq[cns->nseq++] = kmax;
707 }
708 // Only apply consensus insertions that are not being tested by bam2bcf_iaux, i.e. not at the current pos
709 apply_consensus_insertion(rcns, cns, j, ivar);
710 continue;
711 }
712 int which = rcns->cvar[ivar].which;
713 if ( !(rcns->cns_hap[ith] & (1U<<ivar)) )
714 {
715 // This position has a heterozygous variant but not in this haplotype. Take the
716 // most frequent base different from the ivar-th variant
717 int max_freq = 0, kmax = seq_nt16_int[seq_nt16_table[(int)ref[j]]];
718 for (k=0; k<6; k++)
719 {
720 if ( rcns->cvar[ivar].vtype==snv && rcns->cvar[ivar].which==k ) continue;
721 if ( max_freq < bfreq[j].base[k] ) max_freq = bfreq[j].base[k], kmax = k;
722 }
723 if ( kmax!=BF_DEL && (!cns->nseq || prev_pos != ref_pos) )
724 {
725 prev_pos = ref_pos;
726 cns->seq[cns->nseq++] = kmax;
727 }
728 apply_consensus_insertion(rcns, cns, j, ivar);
729 continue;
730 }
731 if ( rcns->cvar[ivar].vtype == snv )
732 {
733 prev_pos = ref_pos;
734 cns->seq[cns->nseq++] = which;
735 apply_consensus_insertion(rcns, cns, j, ivar);
736 continue;
737 }
738
739 // There can be multiple variants at this position, for example snv+ins. SNVs come first
740 // thanks to cvar_pos_cmp(), make sure the base has not been added already.
741 if ( !cns->nseq || prev_pos != ref_pos )
742 {
743 int max_freq = 0, kmax = seq_nt16_int[seq_nt16_table[(int)ref[j]]];
744 for (k=0; k<6; k++)
745 {
746 if ( rcns->cvar[ivar].vtype==snv && rcns->cvar[ivar].which==k ) continue;
747 if ( max_freq < bfreq[j].base[k] ) max_freq = bfreq[j].base[k], kmax = k;
748 }
749 if ( kmax!=BF_DEL )
750 {
751 prev_pos = ref_pos;
752 cns->seq[cns->nseq++] = kmax;
753 }
754 }
755 if ( rcns->cvar[ivar].vtype == ins )
756 {
757 int len = ifreq[j].len[which];
758 char *seq = ifreq[j].nt16_seq[which];
759 for (k=0; k<len; k++)
760 {
761 prev_pos = ref_pos;
762 cns->seq[cns->nseq++] = seq_nt16_int[(int)seq[k]];
763 }
764 }
765 else if ( rcns->cvar[ivar].vtype == del ) j += dfreq[j].len[which];
766 }
767 }
768
769 // The algorithm:
770 // 1. Identify heterozygous variant positions
771 // 2. Sort variants by abs(variant_allele_freq-0.5) in descending order
772 // 3. Take the top sorted variants (up to 8 to fit in uint8_t) and count the number of
773 // corresponding reads to create frequency spectrum
774 // 4. Correct errors, collapse to the requested number of haplotypes (consensus sequences)
775 // using majority vote for the distribution tail
776 cns_seq_t *rcns_get_consensus(read_cns_t *rcns, const char *ref)
777 {
778 debug_print_base_freqs(rcns, ref);
779
780 select_candidate_variants(rcns, ref);
781 debug_print_candidate_variants(rcns);
782
783 if ( rcns->ncvar )
784 {
785 create_haplotype_frequency_spectrum(rcns);
786 debug_print_haplotype_frequency_spectrum(rcns);
787
788 correct_haplotype_errors(rcns);
789 debug_print_candidate_variants(rcns);
790 debug_print_haplotype_frequency_spectrum(rcns);
791 }
792 else
793 {
794 rcns->cns_hap[0] = 0;
795 rcns->ncns = 1;
796 }
797
798 // create consensus
799 int i;
800 for (i=0; i<rcns->ncns; i++) create_consensus(rcns,ref,i);
801 debug_print_consensus(rcns,ref);
802
803 return rcns->cns;
804 }