Debian Codegraph @

bcftools/read_consensus.c.pysam.c

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