Debian Codegraph @

bcftools/bam2bcf.c

raw symbols SCIP
1 /* bam2bcf.c -- variant calling.
2
3 Copyright (C) 2010-2012 Broad Institute.
4 Copyright (C) 2012-2024 Genome Research Ltd.
5
6 Author: Heng Li <[email protected]>
7
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14
15 The above copyright notice and this permission notice shall be included in
16 all copies or substantial portions of the Software.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 DEALINGS IN THE SOFTWARE. */
25
26 #include <math.h>
27 #include <stdint.h>
28 #include <assert.h>
29 #include <float.h>
30 #include <htslib/hts.h>
31 #include <htslib/sam.h>
32 #include <htslib/kstring.h>
33 #include <htslib/kfunc.h>
34 #include "bam2bcf.h"
35
36 extern void ks_introsort_uint32_t(size_t n, uint32_t a[]);
37
38 #define CALL_DEFTHETA 0.83
39 #define DEF_MAPQ 20
40
41 #define CAP_DIST 25
42
43 bcf_callaux_t *bcf_call_init(double theta, int min_baseQ, int max_baseQ,
44 int delta_baseQ)
45 {
46 bcf_callaux_t *bca;
47 if (theta <= 0.) theta = CALL_DEFTHETA;
48 bca = (bcf_callaux_t*) calloc(1, sizeof(bcf_callaux_t));
49 bca->capQ = 60;
50 bca->openQ = 40; bca->extQ = 20; bca->tandemQ = 100;
51 bca->min_baseQ = min_baseQ;
52 bca->max_baseQ = max_baseQ;
53 bca->delta_baseQ = delta_baseQ;
54 bca->e = errmod_init(1. - theta);
55 bca->min_frac = 0.002;
56 bca->min_support = 1;
57 bca->per_sample_flt = 0;
58 bca->npos = 100;
59 bca->ref_pos = (int*) malloc(bca->npos*sizeof(int));
60 bca->alt_pos = (int*) malloc(bca->npos*sizeof(int));
61 bca->iref_pos= (int*) malloc(bca->npos*sizeof(int));
62 bca->ialt_pos= (int*) malloc(bca->npos*sizeof(int));
63 bca->nqual = 60;
64 bca->ref_mq = (int*) malloc(bca->nqual*sizeof(int));
65 bca->alt_mq = (int*) malloc(bca->nqual*sizeof(int));
66 bca->iref_mq = (int*) malloc(bca->nqual*sizeof(int));
67 bca->ialt_mq = (int*) malloc(bca->nqual*sizeof(int));
68 bca->ref_bq = (int*) malloc(bca->nqual*sizeof(int));
69 bca->alt_bq = (int*) malloc(bca->nqual*sizeof(int));
70 bca->fwd_mqs = (int*) malloc(bca->nqual*sizeof(int));
71 bca->rev_mqs = (int*) malloc(bca->nqual*sizeof(int));
72 return bca;
73 }
74
75 void bcf_iaux_destroy(bcf_callaux_t *bca);
76 void bcf_call_destroy(bcf_callaux_t *bca)
77 {
78 if (bca == 0) return;
79 bcf_iaux_destroy(bca);
80 errmod_destroy(bca->e);
81 if (bca->npos) {
82 free(bca->ref_pos); free(bca->alt_pos);
83 free(bca->iref_pos); free(bca->ialt_pos);
84 bca->npos = 0;
85 }
86 free(bca->ref_mq); free(bca->alt_mq);
87 free(bca->iref_mq); free(bca->ialt_mq);
88 free(bca->ref_bq); free(bca->alt_bq);
89 free(bca->fwd_mqs); free(bca->rev_mqs);
90 bca->nqual = 0;
91 free(bca->bases); free(bca->inscns); free(bca);
92 }
93
94 static int get_aux_nm(const bam_pileup1_t *p, int32_t qpos, int is_ref)
95 {
96 int64_t nm;
97 const bam_pileup_cd *cd = &p->cd;
98
99 if ( PLP_NM(cd) == -1 ) return -1;
100 if ( PLP_NM(cd) == PLP_NM_UNSET )
101 {
102 // todo: make this localized to be useful for long reads as well
103 bam1_t *rec = p->b;
104 uint8_t *nm_tag = bam_aux_get(rec, "NM");
105 if ( !nm_tag )
106 {
107 PLP_NM(cd) = -1;
108 return -1;
109 }
110 nm = bam_aux2i(nm_tag);
111
112 // Count indels as single events, not as the number of inserted/deleted
113 // bases (which is what NM does). Add soft clips as mismatches.
114 int i;
115 for (i=0; i < rec->core.n_cigar; i++)
116 {
117 int val = bam_get_cigar(rec)[i] & BAM_CIGAR_MASK;
118 if ( val==BAM_CSOFT_CLIP )
119 {
120 nm += bam_get_cigar(rec)[i] >> BAM_CIGAR_SHIFT;
121 }
122 else if ( val==BAM_CINS || val==BAM_CDEL )
123 {
124 val = bam_get_cigar(rec)[i] >> BAM_CIGAR_SHIFT;
125 if ( val > 1 ) nm -= val - 1;
126 }
127 }
128 PLP_NM(cd) = nm;
129 }
130 else
131 nm = PLP_NM(cd);
132
133 // Take into account MNPs, 2% of de novo SNVs appear within 20bp of another de novo SNV
134 // http://www.genome.org/cgi/doi/10.1101/gr.239756.118
135 nm -= is_ref ? 1 : 2;
136
137 if ( nm < 0 ) nm = 0;
138 if ( nm >= B2B_N_NM ) nm = B2B_N_NM - 1;
139
140 return nm;
141 }
142
143 // position in the sequence with respect to the aligned part of the read
144 static int get_position(const bam_pileup1_t *p, int *len,
145 int *sc_len, int *sc_dist) {
146 int i, j, edist = p->qpos + 1;
147 int sc_left = 0, sc_right = 0;
148 int sc_left_dist = -1, sc_right_dist = -1;
149
150 // left end
151 for (i = 0; i < p->b->core.n_cigar; i++) {
152 int cig = bam_get_cigar(p->b)[i] & BAM_CIGAR_MASK;
153 if (cig == BAM_CHARD_CLIP)
154 continue;
155 else if (cig == BAM_CSOFT_CLIP)
156 sc_left += bam_get_cigar(p->b)[i] >> BAM_CIGAR_SHIFT;
157 else
158 break;
159 }
160 if (sc_left)
161 sc_left_dist = p->qpos+1 - sc_left;
162 edist -= sc_left;
163
164 // right end
165 for (j = p->b->core.n_cigar-1; j >= i; j--) {
166 int cig = bam_get_cigar(p->b)[j] & BAM_CIGAR_MASK;
167 if (cig == BAM_CHARD_CLIP)
168 continue;
169 else if (cig == BAM_CSOFT_CLIP)
170 sc_right += bam_get_cigar(p->b)[j] >> BAM_CIGAR_SHIFT;
171 else
172 break;
173 }
174 if (sc_right)
175 sc_right_dist = p->b->core.l_qseq - sc_right - p->qpos;
176
177 // Distance to nearest soft-clips and length of that clip.
178 if (sc_left_dist >= 0) {
179 if (sc_right_dist < 0 || sc_left_dist < sc_right_dist) {
180 *sc_len = sc_left;
181 *sc_dist = sc_left_dist;
182 }
183 } else if (sc_right_dist >= 0) {
184 *sc_len = sc_right;
185 *sc_dist = sc_right_dist;
186 } else {
187 *sc_len = 0;
188 *sc_dist = 0;
189 }
190
191 *len = p->b->core.l_qseq - sc_left - sc_right;
192 return edist;
193 }
194
195 void bcf_callaux_clean(bcf_callaux_t *bca, bcf_call_t *call)
196 {
197 memset(bca->ref_pos,0,sizeof(int)*bca->npos);
198 memset(bca->alt_pos,0,sizeof(int)*bca->npos);
199 memset(bca->iref_pos,0,sizeof(int)*bca->npos);
200 memset(bca->ialt_pos,0,sizeof(int)*bca->npos);
201 memset(bca->ref_mq,0,sizeof(int)*bca->nqual);
202 memset(bca->alt_mq,0,sizeof(int)*bca->nqual);
203 memset(bca->iref_mq,0,sizeof(int)*bca->nqual);
204 memset(bca->ialt_mq,0,sizeof(int)*bca->nqual);
205 memset(bca->ref_bq,0,sizeof(int)*bca->nqual);
206 memset(bca->alt_bq,0,sizeof(int)*bca->nqual);
207 memset(bca->fwd_mqs,0,sizeof(int)*bca->nqual);
208 memset(bca->rev_mqs,0,sizeof(int)*bca->nqual);
209 if ( call->ADF ) memset(call->ADF,0,sizeof(int32_t)*(call->n+1)*B2B_MAX_ALLELES);
210 if ( call->ADR ) memset(call->ADR,0,sizeof(int32_t)*(call->n+1)*B2B_MAX_ALLELES);
211 if ( call->SCR ) memset(call->SCR,0,sizeof(*call->SCR)*(call->n+1));
212 if ( call->SCR ) memset(call->SCR,0,sizeof(*call->SCR)*(call->n+1));
213 if ( bca->fmt_flag&B2B_FMT_NMBZ )
214 {
215 memset(call->ref_nm,0,sizeof(*call->ref_nm)*(call->n+1)*B2B_N_NM);
216 memset(call->alt_nm,0,sizeof(*call->alt_nm)*(call->n+1)*B2B_N_NM);
217 }
218 else
219 {
220 memset(call->ref_nm,0,sizeof(*call->ref_nm)*B2B_N_NM);
221 memset(call->alt_nm,0,sizeof(*call->alt_nm)*B2B_N_NM);
222 }
223 memset(call->QS,0,sizeof(*call->QS)*call->n*B2B_MAX_ALLELES);
224 memset(bca->ref_scl, 0, 100*sizeof(int));
225 memset(bca->alt_scl, 0, 100*sizeof(int));
226 memset(bca->iref_scl, 0, 100*sizeof(int));
227 memset(bca->ialt_scl, 0, 100*sizeof(int));
228 int i;
229 for (i=0; i<2; i++) bca->nnm[i] = 0;
230 for (i=0; i<2; i++) bca->nm[i] = 0;
231 }
232
233 /*
234 Notes:
235 - Called from bam_plcmd.c by mpileup. Amongst other things, sets the bcf_callret1_t.QS frequencies
236 which are carried over via bcf_call_combine and bcf_call2bcf to the output BCF as the INFO/QS and FMT/QS annotations.
237 Later it's used for multiallelic calling by `call -m`, `call -mG` and `+trio-dnm`.
238 - ref_base is the 4-bit representation of the reference base. It is negative if we are looking at an indel.
239 */
240 /*
241 * This function is called once for each sample.
242 * _n is number of pilesups pl contributing reads to this sample
243 * pl is pointer to array of _n pileups (one pileup per read)
244 * ref_base is the 4-bit representation of the reference base. It is negative if we are looking at an indel.
245 * bca is the settings to perform calls across all samples
246 * r is the returned value of the call
247 */
248 int bcf_call_glfgen(int _n, const bam_pileup1_t *pl, int ref_base, bcf_callaux_t *bca, bcf_callret1_t *r)
249 {
250 int i, n, ref4, is_indel, ori_depth = 0;
251
252 #ifdef GLF_DEBUG
253 fprintf(stderr, "Call GLFGEN\n");
254 #endif
255
256 // clean from previous run
257 r->ori_depth = 0;
258 r->mq0 = 0;
259 memset(r->anno,0,sizeof(double)*16);
260 memset(r->p,0,sizeof(float)*25);
261 r->SCR = 0;
262
263 if (ref_base >= 0) {
264 ref4 = seq_nt16_int[ref_base];
265 is_indel = 0;
266 } else ref4 = 4, is_indel = 1;
267 if (_n == 0) return -1;
268 // enlarge the bases array if necessary
269 if (bca->max_bases < _n) {
270 bca->max_bases = _n;
271 kroundup32(bca->max_bases);
272 bca->bases = (uint16_t*)realloc(bca->bases, 2 * bca->max_bases);
273 }
274
275 // Detect if indel occurs anywhere in this sample
276 int indel_in_sample = 0;
277 if (bca->edlib) {
278 for (i = n = 0; i < _n; ++i) {
279 const bam_pileup1_t *p = pl + i;
280 if (p->indel) indel_in_sample = 1;
281 }
282 }
283
284 // fill the bases array
285 double nqual_over_60 = bca->nqual / 60.0;
286 int ADR_ref_missed[4] = {0};
287 int ADF_ref_missed[4] = {0};
288 for (i = n = 0; i < _n; ++i) {
289 const bam_pileup1_t *p = pl + i;
290 int b; // the base or indel type
291 int q; // the base or indel quality used to calculate PL
292 int seqQ; // used to cap the indel quality given the sequence context
293 int mapQ; // to cap the quality for low MQ reads
294 int baseQ; // used only for supporting INFO annotations
295 int is_diff; // is this base or indel type different from the reference
296 int min_dist; // distance from the end, used for tail distance bias
297 if ( bca->fmt_flag&(B2B_INFO_SCR|B2B_FMT_SCR) && PLP_HAS_SOFT_CLIP(&p->cd) ) r->SCR++;
298 if (p->is_refskip || (p->b->core.flag&BAM_FUNMAP)) continue;
299
300 // The meaning of the indel related variables:
301 // is_indel .. is this position currently tested for an indel
302 // p->is_del .. is the current base a deletion in this read (unrelated to the tested indel)
303 // p->indel .. is there an indel starting after this position (i.e. does this read have the tested indel)
304 if (p->is_del && !is_indel) continue; // not testing an indel and the read has a spanning deletion
305
306 int inm = -1;
307
308 ++ori_depth;
309 if (is_indel) // testing an indel position
310 {
311 b = p->aux>>16&0x3f; // indel type
312 seqQ = q = (p->aux & 0xff); // mp2 + builtin indel-bias
313
314 if (bca->edlib) {
315 if (indel_in_sample) {
316 seqQ = q = (p->aux & 0xff); // mp2 + builtin indel-bias
317 } else if (p->aux & 0xff) {
318 // An indel in another sample, but not this. So just use
319 // basic sequence confidences.
320 q = bam_get_qual(p->b)[p->qpos];
321 if (q > bca->max_baseQ) q = bca->max_baseQ;
322 seqQ = 99;
323 }
324 }
325
326 if ( !bca->indels_v20 && !bca->edlib )
327 {
328 /*
329 This heuristics was introduced by e4e161068 and claims to fix #1446. However, we obtain
330 correct result on the provided test case even when this code is commented out, so this
331 may not be needed anymore. Leaving it in only for backward compatibility for now.
332 See mpileup-tests homdel-issue-1446 and CHM1_CHM13_2.45x-1-1701408 which work only when
333 this code is disabled.
334 */
335 if (p->indel == 0 && (q < _n/2 || _n > 20)) {
336 // high quality indel calls without p->indel set aren't
337 // particularly indicative of being a good REF match either,
338 // at least not in low coverage. So require solid coverage
339 // before we start utilising such quals.
340 b = 0;
341 q = (int)bam_get_qual(p->b)[p->qpos];
342 seqQ = (3*seqQ + 2*q)/8;
343 }
344 if (_n > 20 && seqQ > 40) seqQ = 40;
345 }
346
347 is_diff = b ? 1 : 0;
348 if ( bca->fmt_flag&(B2B_FMT_NMBZ|B2B_INFO_NMBZ|B2B_INFO_NM) )
349 {
350 inm = get_aux_nm(p,p->qpos,is_diff?0:1);
351 if ( inm>=0 )
352 {
353 bca->nnm[is_diff]++;
354 bca->nm[is_diff] += inm;
355 }
356 }
357
358 #ifdef GLF_DEBUG
359 fprintf(stderr, "GLF %s\t%d\t%d\n", bam_get_qname(p->b),
360 bca->indel_types[b], q);
361 #endif
362 if (q < bca->min_baseQ)
363 {
364 if (!p->indel && b < 4) // not an indel read
365 {
366 if (bam_is_rev(p->b))
367 ADR_ref_missed[b]++;
368 else
369 ADF_ref_missed[b]++;
370 }
371 continue;
372 }
373
374 #ifndef MIN
375 #define MIN(a,b) ((a)<(b)?(a):(b))
376 #endif
377
378 #ifndef MAX
379 #define MAX(a,b) ((a)>(b)?(a):(b))
380 #endif
381
382 #if 1 // TEST 6
383 if (bca->edlib) {
384 // Deeper data should rely more heavily on counts of data
385 // than quality, as quality can be unreliable and prone to
386 // miscalculations through BAQ, STR analysis, etc.
387 // So we put a cap on how good seqQ can be.
388 //
389 // Is it simply the equivalent of increasing -F filter?
390 // Not quite, as the latter removes many real variants upfront.
391 // This calls them and then post-adjusts quality, potentially
392 // dropping it later or changing genotype. So we still get
393 // calls, but lower qual.
394 seqQ = MIN(seqQ, bca->seqQ_offset-(MIN(20,_n)*5));
395
396 if (indel_in_sample && p->indel == 0 && b != 0) {
397 // This read doesn't contain an indel in CIGAR, but it
398 // is assigned to an indel now (b != 0), These are
399 // reads we've corrected with realignment, but they're
400 // also enriched for FPs so at high depth we reduce their
401 // confidence and let the depth do the talking. If it's
402 // real and deep, then we don't need every read aligning.
403 // We also reduce base quality too to reflect the
404 // chance of our realignment being incorrect.
405
406 seqQ = MIN(seqQ, seqQ/2 + 5); // q2p5
407
408 // Finally reduce indel quality.
409 // This is a blend of indelQ and base QUAL.
410 q = MIN((int)bam_get_qual(p->b)[p->qpos]/4+10, q/4+1);
411 }
412 }
413 #endif
414
415 // Note baseQ changes some output fields such as I16, but has no
416 // significant affect on "call".
417 baseQ = p->aux>>8&0xff;
418 }
419 else
420 {
421 b = bam_seqi(bam_get_seq(p->b), p->qpos); // base
422 b = seq_nt16_int[b? b : ref_base]; // b is the 2-bit base
423
424 // Lowest of this and neighbour quality values
425 uint8_t *qual = bam_get_qual(p->b);
426 q = qual[p->qpos];
427 if (p->qpos > 0 &&
428 q > qual[p->qpos-1]+bca->delta_baseQ)
429 q = qual[p->qpos-1]+bca->delta_baseQ;
430 if (p->qpos+1 < p->b->core.l_qseq &&
431 q > qual[p->qpos+1]+bca->delta_baseQ)
432 q = qual[p->qpos+1]+bca->delta_baseQ;
433
434 if (q < bca->min_baseQ) continue;
435 if (q > bca->max_baseQ) q = bca->max_baseQ;
436 baseQ = q;
437 seqQ = 99;
438 is_diff = (ref4 < 4 && b == ref4)? 0 : 1;
439 if ( bca->fmt_flag&(B2B_FMT_NMBZ|B2B_INFO_NMBZ|B2B_INFO_NM) )
440 {
441 inm = get_aux_nm(p,p->qpos,is_diff?0:1);
442 if ( inm>=0 )
443 {
444 bca->nnm[is_diff]++;
445 bca->nm[is_diff] += inm;
446 }
447 }
448 }
449 mapQ = p->b->core.qual < 255? p->b->core.qual : DEF_MAPQ; // special case for mapQ==255
450 if ( !mapQ ) r->mq0++;
451 #ifdef GLF_DEBUG
452 fprintf(stderr, "GLF2 %s\t%d\t%d\t%d,%d\n",
453 bam_get_qname(p->b), b, q,
454 seqQ, mapQ);
455 #endif
456 if (q > seqQ) q = seqQ;
457 mapQ = mapQ < bca->capQ? mapQ : bca->capQ;
458 if (q > mapQ) q = mapQ;
459 if (q > 63) q = 63;
460 if (q < 4) q = 4; // MQ=0 reads count as BQ=4
461 bca->bases[n++] = q<<5 | (int)bam_is_rev(p->b)<<4 | b;
462 //if (is_indel) fprintf(stderr,"xx:base,q,strand\t%d\t%d\t%d\n",b,q,bam_is_rev(p->b)?0:1);
463
464 // collect annotations
465 if (b < 4)
466 {
467 r->QS[b] += q;
468 if ( r->ADF )
469 {
470 if ( bam_is_rev(p->b) )
471 r->ADR[b]++;
472 else
473 r->ADF[b]++;
474 }
475 }
476 ++r->anno[0<<2|is_diff<<1|bam_is_rev(p->b)];
477 min_dist = p->b->core.l_qseq - 1 - p->qpos;
478 if (min_dist > p->qpos) min_dist = p->qpos;
479 if (min_dist > CAP_DIST) min_dist = CAP_DIST;
480 r->anno[1<<2|is_diff<<1|0] += baseQ;
481 r->anno[1<<2|is_diff<<1|1] += baseQ * baseQ;
482 r->anno[2<<2|is_diff<<1|0] += mapQ;
483 r->anno[2<<2|is_diff<<1|1] += mapQ * mapQ;
484 r->anno[3<<2|is_diff<<1|0] += min_dist;
485 r->anno[3<<2|is_diff<<1|1] += min_dist * min_dist;
486
487 // collect for bias tests
488 if ( baseQ > 59 ) baseQ = 59;
489 if ( mapQ > 59 ) mapQ = 59;
490 int len, epos = 0, sc_len = 0, sc_dist = 0;
491 if ( bca->fmt_flag & (B2B_INFO_RPBZ|B2B_INFO_VDB|B2B_INFO_SCBZ) )
492 {
493 int pos = get_position(p, &len, &sc_len, &sc_dist);
494 epos = (double)pos/(len+1) * (bca->npos - 1);
495 if (sc_len) {
496 sc_len = 15.0*sc_len / (sc_dist+1);
497 if (sc_len > 99) sc_len = 99;
498 }
499 assert( epos>=0 && epos<bca->npos );
500 assert( sc_len>=0 && sc_len<bca->npos );
501 }
502 int imq = mapQ * nqual_over_60;
503 int ibq = baseQ * nqual_over_60;
504
505 if ( bam_is_rev(p->b) )
506 bca->rev_mqs[imq]++;
507 else
508 bca->fwd_mqs[imq]++;
509
510 if ( !is_diff )
511 {
512 bca->ref_pos[epos]++;
513 bca->ref_bq[ibq]++;
514 bca->ref_mq[imq]++;
515 bca->ref_scl[sc_len]++;
516 if ( inm>=0 )
517 {
518 bca->ref_nm[inm]++;
519 if ( r->ref_nm ) r->ref_nm[inm]++;
520 }
521 }
522 else
523 {
524 bca->alt_pos[epos]++;
525 bca->alt_bq[ibq]++;
526 bca->alt_mq[imq]++;
527 bca->alt_scl[sc_len]++;
528 if ( inm>=0 )
529 {
530 bca->alt_nm[inm]++;
531 if ( r->alt_nm ) r->alt_nm[inm]++;
532 }
533 }
534 }
535
536 // Compensate for AD not being counted on low quality REF indel matches.
537 if ( r->ADF && bca->ambig_reads==B2B_INC_AD0 )
538 {
539 for (i=0; i<4; i++)
540 {
541 r->ADR[0] += ADR_ref_missed[i];
542 r->ADF[0] += ADF_ref_missed[i];
543 }
544 }
545 else if ( r->ADF && bca->ambig_reads==B2B_INC_AD )
546 {
547 int dp = 0, dp_ambig = 0;
548 for (i=0; i<4; i++) dp += r->ADR[i];
549 for (i=0; i<4; i++) dp_ambig += ADR_ref_missed[i];
550 if ( dp )
551 for (i=0; i<4; i++) r->ADR[i] += lroundf((float)dp_ambig * r->ADR[i]/dp);
552 dp = 0, dp_ambig = 0;
553 for (i=0; i<4; i++) dp += r->ADF[i];
554 for (i=0; i<4; i++) dp_ambig += ADF_ref_missed[i];
555 if ( dp )
556 for (i=0; i<4; i++) r->ADF[i] += lroundf((float)dp_ambig * r->ADF[i]/dp);
557 }
558
559 // Else consider downgrading bca->bases[] scores by AD vs AD_ref_missed
560 // ratios. This is detrimental on Illumina, but beneficial on PacBio CCS.
561 // It's possibly related to the homopolyer error likelihoods or overall
562 // Indel accuracy. Maybe tie this in to the -h option?
563
564 r->ori_depth = ori_depth;
565 // glfgen
566 errmod_cal(bca->e, n, 5, bca->bases, r->p); // calculate PL of each genotype
567
568 // TODO: account for the number of unassigned reads. If depth is 50,
569 // but AD is 5,7 then it may look like a variant but it probably
570 // should be low quality.
571
572 return n;
573 }
574
575
576 /*
577 * calc_vdb() - returns value between zero (most biased) and one (no bias)
578 * on success, or HUGE_VAL when VDB cannot be calculated because
579 * of insufficient depth (<2x)
580 *
581 * Variant Distance Bias tests if the variant bases are positioned within the
582 * reads with sufficient randomness. Unlike other tests, it looks only at
583 * variant reads and therefore gives different kind of information than Read
584 * Position Bias for instance. VDB was developed for detecting artefacts in
585 * RNA-seq calls where reads from spliced transcripts span splice site
586 * boundaries. The current implementation differs somewhat from the original
587 * version described in supplementary material of PMID:22524474, but the idea
588 * remains the same. (Here the random variable tested is the average distance
589 * from the averaged position, not the average pairwise distance.)
590 *
591 * For coverage of 2x, the calculation is exact but is approximated for the
592 * rest. The result is most accurate between 4-200x. For 3x or >200x, the
593 * reported values are slightly more favourable than those of a true random
594 * distribution.
595 */
596 double calc_vdb(int *pos, int npos)
597 {
598 // Note well: the parameters were obtained by fitting to simulated data of
599 // 100bp reads. This assumes rescaling to 100bp in bcf_call_glfgen().
600 const int readlen = 100;
601 assert( npos==readlen );
602
603 #define nparam 15
604 const float param[nparam][3] = { {3,0.079,18}, {4,0.09,19.8}, {5,0.1,20.5}, {6,0.11,21.5},
605 {7,0.125,21.6}, {8,0.135,22}, {9,0.14,22.2}, {10,0.153,22.3}, {15,0.19,22.8},
606 {20,0.22,23.2}, {30,0.26,23.4}, {40,0.29,23.5}, {50,0.35,23.65}, {100,0.5,23.7},
607 {200,0.7,23.7} };
608
609 int i, dp = 0;
610 float mean_pos = 0, mean_diff = 0;
611 for (i=0; i<npos; i++)
612 {
613 if ( !pos[i] ) continue;
614 dp += pos[i];
615 mean_pos += pos[i]*i;
616 }
617 if ( dp<2 ) return HUGE_VAL; // one or zero reads can be placed anywhere
618
619 mean_pos /= dp;
620 for (i=0; i<npos; i++)
621 {
622 if ( !pos[i] ) continue;
623 mean_diff += pos[i] * fabs(i - mean_pos);
624 }
625 mean_diff /= dp;
626
627 int ipos = mean_diff; // tuned for float-to-int implicit conversion
628 if ( dp==2 )
629 return (2*readlen-2*(ipos+1)-1)*(ipos+1)/(readlen-1)/(readlen*0.5);
630
631 if ( dp>=200 )
632 i = nparam; // shortcut for big depths
633 else
634 {
635 for (i=0; i<nparam; i++)
636 if ( param[i][0]>=dp ) break;
637 }
638 float pshift, pscale;
639 if ( i==nparam )
640 {
641 // the depth is too high, go with 200x
642 pscale = param[nparam-1][1];
643 pshift = param[nparam-1][2];
644 }
645 else if ( i>0 && param[i][0]!=dp )
646 {
647 // linear interpolation of parameters
648 pscale = (param[i-1][1] + param[i][1])*0.5;
649 pshift = (param[i-1][2] + param[i][2])*0.5;
650 }
651 else
652 {
653 pscale = param[i][1];
654 pshift = param[i][2];
655 }
656 return 0.5*kf_erfc(-(mean_diff-pshift)*pscale);
657 }
658
659 double calc_chisq_bias(int *a, int *b, int n)
660 {
661 int na = 0, nb = 0, i, ndf = n;
662 for (i=0; i<n; i++) na += a[i];
663 for (i=0; i<n; i++) nb += b[i];
664 if ( !na || !nb ) return HUGE_VAL;
665
666 double chisq = 0;
667 for (i=0; i<n; i++)
668 {
669 if ( !a[i] && !b[i] ) ndf--;
670 else
671 {
672 double tmp = a[i] - b[i];
673 chisq += tmp*tmp/(a[i]+b[i]);
674 }
675 }
676 /*
677 kf_gammq: incomplete gamma function Q(a,x) = 1 - P(a,x) = Gamma(a,x)/Gamma(a)
678 1 if the distributions are identical, 0 if very different
679 */
680 double prob = kf_gammaq(0.5*ndf, 0.5*chisq);
681 return prob;
682 }
683
684 static double mann_whitney_1947_(int n, int m, int U)
685 {
686 if (U<0) return 0;
687 if (n==0||m==0) return U==0 ? 1 : 0;
688 return (double)n/(n+m)*mann_whitney_1947_(n-1,m,U-m) + (double)m/(n+m)*mann_whitney_1947_(n,m-1,U);
689 }
690
691 double mann_whitney_1947(int n, int m, int U)
692 {
693 #include "mw.h"
694
695 assert(n >= 2 && m >= 2);
696
697 return (n < 8 && m < 8 && U < 50)
698 ? mw[n-2][m-2][U]
699 : mann_whitney_1947_(n,m,U);
700 }
701
702 double mann_whitney_1947_cdf(int n, int m, int U)
703 {
704 int i;
705 double sum = 0;
706 for (i=0; i<=U; i++)
707 sum += mann_whitney_1947(n,m,i);
708 return sum;
709 }
710
711 double calc_mwu_bias_cdf(int *a, int *b, int n)
712 {
713 int na = 0, nb = 0, i;
714 double U = 0;
715 //double ties = 0;
716 for (i=0; i<n; i++)
717 {
718 na += a[i];
719 U += a[i] * (nb + b[i]*0.5);
720 nb += b[i];
721 // if ( a[i] && b[i] )
722 // {
723 // double tie = a[i] + b[i];
724 // ties += (tie*tie-1)*tie;
725 // }
726 }
727 if ( !na || !nb ) return HUGE_VAL;
728
729 // Always work with the smaller U
730 double U_min = ((double)na * nb) - U;
731 if ( U < U_min ) U_min = U;
732
733 if ( na==1 ) return 2.0 * (floor(U_min)+1) / (nb+1);
734 if ( nb==1 ) return 2.0 * (floor(U_min)+1) / (na+1);
735
736 // Normal approximation, very good for na>=8 && nb>=8 and reasonable if na<8 or nb<8
737 if ( na>=8 || nb>=8 )
738 {
739 double mean = ((double)na*nb)*0.5;
740 // Correction for ties:
741 // double N = na+nb;
742 // double var2 = (N*N-1)*N-ties;
743 // if ( var2==0 ) return 1.0;
744 // var2 *= ((double)na*nb)/N/(N-1)/12.0;
745 // No correction for ties:
746 double var2 = ((double)na*nb)*(na+nb+1)/12.0;
747 double z = (U_min - mean)/sqrt(2*var2); // z is N(0,1)
748 return 2.0 - kf_erfc(z); // which is 1 + erf(z)
749 }
750
751 // Exact calculation
752 double pval = 2*mann_whitney_1947_cdf(na,nb,U_min);
753 return pval>1 ? 1 : pval;
754 }
755
756 double calc_mwu_bias(int *a, int *b, int n, int left)
757 {
758 int na = 0, nb = 0, i;
759 double U = 0;
760 // double ties = 0;
761 for (i=0; i<n; i++)
762 {
763 if (!a[i]) {
764 if (!b[i]) continue;
765 nb += b[i];
766 } else if (!b[i]) {
767 na += a[i];
768 U += a[i] * nb;
769 } else {
770 na += a[i];
771 U += a[i] * (nb + b[i]*0.5);
772 nb += b[i];
773 // double tie = a[i] + b[i];
774 // ties += (tie*tie-1)*tie;
775 }
776 }
777 if ( !na || !nb ) return HUGE_VAL;
778 if ( na==1 || nb==1 ) return 1.0; // Flat probability, all U values are equally likely
779
780 double mean = ((double)na*nb)*0.5;
781 if (left && U > mean) return 1; // for MQB which is asymmetrical
782 if ( na==2 || nb==2 )
783 {
784 // Linear approximation
785 return U>mean ? (2.0*mean-U)/mean : U/mean;
786 }
787 // Correction for ties:
788 // double N = na+nb;
789 // double var2 = (N*N-1)*N-ties;
790 // if ( var2==0 ) return 1.0;
791 // var2 *= ((double)na*nb)/N/(N-1)/12.0;
792 // No correction for ties:
793 double var2 = ((double)na*nb)*(na+nb+1)/12.0;
794 if ( na>=8 || nb>=8 )
795 {
796 // Normal approximation, very good for na>=8 && nb>=8 and reasonable if na<8 or nb<8
797 return exp(-0.5*(U-mean)*(U-mean)/var2);
798 }
799
800 // Exact calculation
801 return mann_whitney_1947(na,nb,U) * sqrt(2*M_PI*var2);
802 }
803
804 // A Z-score version of the above function.
805 //
806 // See "Normal approximation and tie correction" at
807 // https://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U_test
808 //
809 // The Z score is the number of standard deviations above or below the mean
810 // with 0 being equality of the two distributions and +ve/-ve from there.
811 //
812 // This is a more robust score to filter on.
813 double calc_mwu_biasZ(int *a, int *b, int n, int left_only, int do_Z) {
814 int i;
815 int64_t t;
816
817 // Optimisation
818 for (i = 0; i < n; i++)
819 if (b[i])
820 break;
821 int b_empty = (i == n);
822
823 // Count equal (e), less-than (l) and greater-than (g) permutations.
824 int e = 0, l = 0, na = 0, nb = 0;
825 if (b_empty) {
826 for (t = 0, i = n-1; i >= 0; i--) {
827 na += a[i];
828 t += (a[i]*a[i]-1)*a[i]; // adjustment score for ties
829 }
830 } else {
831 for (t = 0, i = n-1; i >= 0; i--) {
832 // Combinations of a[i] and b[j] for i==j
833 e += a[i]*b[i];
834
835 // nb is running total of b[i+1]..b[n-1].
836 // Therefore a[i]*nb is the number of combinations of a[i] and b[j]
837 // for all i < j.
838 l += a[i]*nb; // a<b
839
840 na += a[i];
841 nb += b[i];
842 int p = a[i]+b[i];
843 t += (p*p-1)*p; // adjustment score for ties
844 }
845 }
846
847 if (!na || !nb)
848 return HUGE_VAL;
849
850 double U, m;
851 U = l + e*0.5; // Mann-Whitney U score
852 m = na*nb / 2.0;
853
854 // With ties adjustment
855 double var2 = (na*nb)/12.0 * ((na+nb+1) - t/(double)((na+nb)*(na+nb-1)));
856 // var = na*nb*(na+nb+1)/12.0; // simpler; minus tie adjustment
857 if (var2 <= 0)
858 return do_Z ? 0 : 1;
859
860 if (do_Z) {
861 // S.D. normalised Z-score
862 //Z = (U - m - (U-m >= 0 ? 0.5 : -0.5)) / sd; // gatk method?
863 return (U - m) / sqrt(var2);
864 }
865
866 // Else U score, which can be asymmetric for some data types.
867 if (left_only && U > m)
868 return HUGE_VAL; // one-sided, +ve bias is OK, -ve is not.
869
870 if (na >= 8 || nb >= 8) {
871 // Normal approximation, very good for na>=8 && nb>=8 and
872 // reasonable if na<8 or nb<8
873 return exp(-0.5*(U-m)*(U-m)/var2);
874 }
875
876 // Exact calculation
877 if (na==1 || nb == 1)
878 return mann_whitney_1947_(na, nb, U) * sqrt(2*M_PI*var2);
879 else
880 return mann_whitney_1947(na, nb, U) * sqrt(2*M_PI*var2);
881 }
882
883 static inline double logsumexp2(double a, double b)
884 {
885 if ( a>b )
886 return log(1 + exp(b-a)) + a;
887 else
888 return log(1 + exp(a-b)) + b;
889 }
890
891 void calc_SegBias(const bcf_callret1_t *bcr, bcf_call_t *call)
892 {
893 call->seg_bias = HUGE_VAL;
894 if ( !bcr ) return;
895
896 int nr = call->anno[2] + call->anno[3]; // number of observed non-reference reads
897 if ( !nr ) return;
898
899 int avg_dp = (call->anno[0] + call->anno[1] + nr) / call->n; // average depth
900 double M = floor((double)nr / avg_dp + 0.5); // an approximate number of variants samples in the population
901 if ( M>call->n ) M = call->n; // clamp M at the number of samples
902 else if ( M==0 ) M = 1;
903 double f = M / 2. / call->n; // allele frequency
904 double p = (double) nr / call->n; // number of variant reads per sample expected if variant not real (poisson)
905 double q = (double) nr / M; // number of variant reads per sample expected if variant is real (poisson)
906 double sum = 0;
907 const double log2 = log(2.0);
908
909 // fprintf(stderr,"M=%.1f p=%e q=%e f=%f dp=%d\n",M,p,q,f,avg_dp);
910 int i;
911 for (i=0; i<call->n; i++)
912 {
913 int oi = bcr[i].anno[2] + bcr[i].anno[3]; // observed number of non-ref reads
914 double tmp;
915 if ( oi )
916 {
917 // tmp = log(f) + oi*log(q/p) - q + log(2*(1-f) + f*pow(2,oi)*exp(-q)) + p; // this can under/overflow
918 tmp = logsumexp2(log(2*(1-f)), log(f) + oi*log2 - q);
919 tmp += log(f) + oi*log(q/p) - q + p;
920 }
921 else
922 tmp = log(2*f*(1-f)*exp(-q) + f*f*exp(-2*q) + (1-f)*(1-f)) + p;
923 sum += tmp;
924 // fprintf(stderr,"oi=%d %e\n", oi,tmp);
925 }
926 call->seg_bias = sum;
927 }
928
929 /**
930 * bcf_call_combine() - sets the PL array and VDB, RPB annotations, finds the top two alleles
931 * @n: number of samples
932 * @calls: each sample's calls
933 * @bca: auxiliary data structure for holding temporary values
934 * @ref_base: the reference base
935 * @call: filled with the annotations
936 *
937 * Combines calls across the various samples being studied
938 * 1. For each allele at each base across all samples the quality is summed so
939 * you end up with a set of quality sums for each allele present 2. The quality
940 * sums are sorted.
941 * 3. Using the sorted quality sums we now create the allele ordering array
942 * A\subN. This is done by doing the following:
943 * a) If the reference allele is known it always comes first, otherwise N
944 * comes first.
945 * b) Then the rest of the alleles are output in descending order of quality
946 * sum (which we already know the qsum array was sorted). Any allelles with
947 * qsum 0 will be excluded.
948 * 4. Using the allele ordering array we create the genotype ordering array.
949 * In the worst case with an unknown reference this will be: A0/A0 A1/A0 A1/A1
950 * A2/A0 A2/A1 A2/A2 A3/A0 A3/A1 A3/A2 A3/A3 A4/A0 A4/A1 A4/A2 A4/A3 A4/A4
951 * 5. The genotype ordering array is then used to extract data from the error
952 * model 5*5 matrix and is used to produce a Phread likelihood array for each
953 * sample.
954 */
955 int bcf_call_combine(int n, const bcf_callret1_t *calls, bcf_callaux_t *bca, int ref_base /*4-bit*/, bcf_call_t *call)
956 {
957 int ref4, i, j;
958 float qsum[B2B_MAX_ALLELES] = {0,0,0,0,0};
959 if (ref_base >= 0) {
960 call->ori_ref = ref4 = seq_nt16_int[ref_base];
961 if (ref4 > 4) ref4 = 4;
962 } else call->ori_ref = -1, ref4 = 0;
963
964 // calculate qsum, this is done by summing normalized qsum across all samples,
965 // to account for differences in coverage
966 for (i = 0; i < n; ++i)
967 {
968 float sum = 0;
969 for (j = 0; j < 4; ++j) sum += calls[i].QS[j];
970 if ( sum )
971 for (j = 0; j < 4; j++) qsum[j] += (float)calls[i].QS[j] / sum;
972 }
973
974 // sort qsum in ascending order (insertion sort)
975 float *ptr[5], *tmp;
976 for (i=0; i<5; i++) ptr[i] = &qsum[i];
977 for (i=1; i<4; i++)
978 for (j=i; j>0 && *ptr[j] < *ptr[j-1]; j--)
979 tmp = ptr[j], ptr[j] = ptr[j-1], ptr[j-1] = tmp;
980
981 // Set the reference allele and alternative allele(s)
982 for (i=0; i<5; i++) call->a[i] = -1;
983 for (i=0; i<B2B_MAX_ALLELES; i++) call->qsum[i] = 0;
984 call->unseen = -1;
985 call->a[0] = ref4;
986 for (i=3, j=1; i>=0; i--) // i: alleles sorted by QS; j, a[j]: output allele ordering
987 {
988 int ipos = ptr[i] - qsum; // position in sorted qsum array
989 if ( ipos==ref4 )
990 call->qsum[0] = qsum[ipos]; // REF's qsum
991 else
992 {
993 if ( !qsum[ipos] ) break; // qsum is 0, this and consequent alleles are not seen in the pileup
994 call->qsum[j] = qsum[ipos];
995 call->a[j++] = ipos;
996 }
997 }
998 if (ref_base >= 0)
999 {
1000 // for SNPs, find the "unseen" base
1001 if (((ref4 < 4 && j < 4) || (ref4 == 4 && j < 5)) && i >= 0)
1002 call->unseen = j, call->a[j++] = ptr[i] - qsum;
1003 call->n_alleles = j;
1004 }
1005 else
1006 {
1007 call->n_alleles = j;
1008 if (call->n_alleles == 1) return -1; // no reliable supporting read. stop doing anything
1009 }
1010 int has_alt = (call->n_alleles==2 && call->unseen!=-1) ? 0 : 1;
1011 /*
1012 * Set the phread likelihood array (call->PL) This array is 15 entries long
1013 * for each sample because that is size of an upper or lower triangle of a
1014 * worst case 5x5 matrix of possible genotypes. This worst case matrix will
1015 * occur when all 4 possible alleles are present and the reference allele
1016 * is unknown. The sides of the matrix will correspond to the reference
1017 * allele (if known) followed by the alleles present in descending order of
1018 * quality sum
1019 */
1020 {
1021 int x, g[15], z;
1022 double sum_min = 0.;
1023 x = call->n_alleles * (call->n_alleles + 1) / 2;
1024 // get the possible genotypes
1025 // this is done by creating an ordered list of locations g for call (allele a, allele b) in the genotype likelihood matrix
1026 for (i = z = 0; i < call->n_alleles; ++i) {
1027 for (j = 0; j <= i; ++j) {
1028 g[z++] = call->a[j] * 5 + call->a[i];
1029 }
1030 }
1031 // for each sample calculate the PL
1032 for (i = 0; i < n; ++i)
1033 {
1034 int32_t *PL = call->PL + x * i;
1035 const bcf_callret1_t *r = calls + i;
1036 float min = FLT_MAX;
1037 for (j = 0; j < x; ++j) {
1038 if (min > r->p[g[j]]) min = r->p[g[j]];
1039 }
1040 sum_min += min;
1041 for (j = 0; j < x; ++j) {
1042 int y;
1043 y = (int)(r->p[g[j]] - min + .499);
1044 if (y > 255) y = 255;
1045 PL[j] = y;
1046 }
1047 }
1048 if ( call->DP4 )
1049 {
1050 for (i=0; i<n; i++)
1051 {
1052 call->DP4[4*i] = calls[i].anno[0];
1053 call->DP4[4*i+1] = calls[i].anno[1];
1054 call->DP4[4*i+2] = calls[i].anno[2];
1055 call->DP4[4*i+3] = calls[i].anno[3];
1056 }
1057 }
1058 if ( call->SCR )
1059 {
1060 for (i=0; i<n; i++)
1061 {
1062 call->SCR[0] += calls[i].SCR;
1063 call->SCR[1+i] = calls[i].SCR;
1064 }
1065 }
1066 if ( call->ADF )
1067 {
1068 assert( call->n_alleles<=B2B_MAX_ALLELES ); // this is always true for SNPs and so far for indels as well
1069
1070 // reorder ADR,ADF to match the allele ordering at this site
1071 int32_t tmp[B2B_MAX_ALLELES];
1072 int32_t *adr = call->ADR + B2B_MAX_ALLELES, *adr_out = call->ADR + B2B_MAX_ALLELES;
1073 int32_t *adf = call->ADF + B2B_MAX_ALLELES, *adf_out = call->ADF + B2B_MAX_ALLELES;
1074 int32_t *adr_tot = call->ADR; // the first bin stores total counts per site
1075 int32_t *adf_tot = call->ADF;
1076 for (i=0; i<n; i++)
1077 {
1078 for (j=0; j<call->n_alleles; j++)
1079 {
1080 tmp[j] = adr[ call->a[j] ];
1081 adr_tot[j] += tmp[j];
1082 }
1083 for (j=0; j<call->n_alleles; j++) adr_out[j] = tmp[j];
1084 for (j=0; j<call->n_alleles; j++)
1085 {
1086 tmp[j] = adf[ call->a[j] ];
1087 adf_tot[j] += tmp[j];
1088 }
1089 for (j=0; j<call->n_alleles; j++) adf_out[j] = tmp[j];
1090 adf_out += call->n_alleles;
1091 adr_out += call->n_alleles;
1092 adr += B2B_MAX_ALLELES;
1093 adf += B2B_MAX_ALLELES;
1094 }
1095 }
1096 if ( bca->fmt_flag & B2B_FMT_QS )
1097 {
1098 assert( call->n_alleles<=B2B_MAX_ALLELES ); // this is always true for SNPs and so far for indels as well
1099
1100 // reorder QS to match the allele ordering at this site
1101 int32_t tmp[B2B_MAX_ALLELES];
1102 int32_t *qs = call->QS, *qs_out = call->QS;
1103 for (i=0; i<n; i++)
1104 {
1105 for (j=0; j<call->n_alleles; j++) tmp[j] = qs[ call->a[j] ];
1106 for (j=0; j<call->n_alleles; j++) qs_out[j] = tmp[j] < BCF_MAX_BT_INT32 ? tmp[j] : BCF_MAX_BT_INT32;
1107 qs_out += call->n_alleles;
1108 qs += B2B_MAX_ALLELES;
1109 }
1110 }
1111
1112 // if (ref_base < 0) fprintf(stderr, "%d,%d,%f,%d\n", call->n_alleles, x, sum_min, call->unseen);
1113 // fprintf(stderr,"sum_min=%f\n",sum_min);
1114 call->shift = (int)(sum_min + .499);
1115 }
1116 // combine annotations
1117 memset(call->anno, 0, 16 * sizeof(double));
1118 call->ori_depth = 0;
1119 call->depth = 0;
1120 call->mq0 = 0;
1121 for (i = 0; i < n; ++i) {
1122 call->depth += calls[i].anno[0] + calls[i].anno[1] + calls[i].anno[2] + calls[i].anno[3];
1123 call->ori_depth += calls[i].ori_depth;
1124 call->mq0 += calls[i].mq0;
1125 for (j = 0; j < 16; ++j) call->anno[j] += calls[i].anno[j];
1126 }
1127
1128 // No need to calculate MWU tests when there is no ALT allele, this should speed up things slightly
1129 if ( !has_alt ) return 0;
1130
1131 if ( bca->fmt_flag & B2B_INFO_FS )
1132 {
1133 double left,right,two;
1134 call->strand_bias = kt_fisher_exact(call->anno[0], call->anno[1], call->anno[2], call->anno[3], &left, &right, &two);
1135 }
1136 if ( bca->fmt_flag & B2B_INFO_SGB ) calc_SegBias(calls, call);
1137
1138 // calc_chisq_bias("XPOS", call->bcf_hdr->id[BCF_DT_CTG][call->tid].key, call->pos, bca->ref_pos, bca->alt_pos, bca->npos);
1139 // calc_chisq_bias("XMQ", call->bcf_hdr->id[BCF_DT_CTG][call->tid].key, call->pos, bca->ref_mq, bca->alt_mq, bca->nqual);
1140 // calc_chisq_bias("XBQ", call->bcf_hdr->id[BCF_DT_CTG][call->tid].key, call->pos, bca->ref_bq, bca->alt_bq, bca->nqual);
1141
1142 // U z-normalised as +/- number of standard deviations from mean.
1143 if (call->ori_ref < 0) { // indel
1144 if ( bca->fmt_flag & B2B_INFO_RPBZ )
1145 call->mwu_pos = calc_mwu_biasZ(bca->iref_pos, bca->ialt_pos, bca->npos, 0, 1);
1146 if ( bca->fmt_flag & B2B_INFO_MQBZ )
1147 call->mwu_mq = calc_mwu_biasZ(bca->iref_mq, bca->ialt_mq, bca->nqual,1,1);
1148 if ( bca->fmt_flag & B2B_INFO_SCBZ )
1149 call->mwu_sc = calc_mwu_biasZ(bca->iref_scl, bca->ialt_scl, 100, 0,1);
1150 } else {
1151 if ( bca->fmt_flag & B2B_INFO_RPBZ )
1152 call->mwu_pos = calc_mwu_biasZ(bca->ref_pos, bca->alt_pos, bca->npos, 0, 1);
1153 if ( bca->fmt_flag & B2B_INFO_MQBZ )
1154 call->mwu_mq = calc_mwu_biasZ(bca->ref_mq, bca->alt_mq, bca->nqual,1,1);
1155 if ( bca->fmt_flag & B2B_INFO_BQBZ )
1156 call->mwu_bq = calc_mwu_biasZ(bca->ref_bq, bca->alt_bq, bca->nqual,0,1);
1157 if ( bca->fmt_flag & B2B_INFO_MQSBZ )
1158 call->mwu_mqs = calc_mwu_biasZ(bca->fwd_mqs, bca->rev_mqs, bca->nqual,0,1);
1159 if ( bca->fmt_flag & B2B_INFO_SCBZ )
1160 call->mwu_sc = calc_mwu_biasZ(bca->ref_scl, bca->alt_scl, 100, 0,1);
1161 }
1162 if ( bca->fmt_flag & B2B_INFO_NMBZ )
1163 call->mwu_nm[0] = calc_mwu_biasZ(bca->ref_nm, bca->alt_nm, B2B_N_NM,0,1);
1164 if ( bca->fmt_flag & B2B_FMT_NMBZ )
1165 {
1166 for (i=0; i<n; i++)
1167 {
1168 float val = calc_mwu_biasZ(calls[i].ref_nm, calls[i].alt_nm, B2B_N_NM,0,1);
1169 call->mwu_nm[i+1] = val!=HUGE_VAL ? val : 0;
1170 }
1171 }
1172 if ( bca->fmt_flag & B2B_INFO_VDB )
1173 call->vdb = calc_vdb(bca->alt_pos, bca->npos);
1174
1175 return 0;
1176 }
1177
1178 int bcf_call2bcf(bcf_call_t *bc, bcf1_t *rec, bcf_callret1_t *bcr, int fmt_flag, const bcf_callaux_t *bca, const char *ref)
1179 {
1180 extern double kt_fisher_exact(int n11, int n12, int n21, int n22, double *_left, double *_right, double *two);
1181 int i, j, nals = 1, has_alt = 0;
1182
1183 bcf_hdr_t *hdr = bc->bcf_hdr;
1184 rec->rid = bc->tid;
1185 rec->pos = bc->pos;
1186 rec->qual = 0;
1187
1188 bc->tmp.l = 0;
1189 if (bc->ori_ref < 0) // indel
1190 {
1191 // REF
1192 kputc(ref[bc->pos], &bc->tmp);
1193 for (j = 0; j < bca->indelreg; ++j) kputc(ref[bc->pos+1+j], &bc->tmp);
1194
1195 // ALT
1196 for (i=1; i<4; i++)
1197 {
1198 if (bc->a[i] < 0) break;
1199 kputc(',', &bc->tmp); kputc(ref[bc->pos], &bc->tmp);
1200
1201 if (bca->indel_types[bc->a[i]] < 0) { // deletion
1202 for (j = -bca->indel_types[bc->a[i]]; j < bca->indelreg; ++j)
1203 kputc(ref[bc->pos+1+j], &bc->tmp);
1204 } else { // insertion; cannot be a reference unless a bug
1205 char *inscns = &bca->inscns[bc->a[i] * bca->maxins];
1206 for (j = 0; j < bca->indel_types[bc->a[i]]; ++j)
1207 kputc("ACGTN"[(int)inscns[j]], &bc->tmp);
1208 for (j = 0; j < bca->indelreg; ++j) kputc(ref[bc->pos+1+j], &bc->tmp);
1209 }
1210 nals++;
1211 has_alt = 1;
1212 }
1213 }
1214 else // SNP
1215 {
1216 kputc("ACGTN"[bc->ori_ref], &bc->tmp);
1217 for (i=1; i<5; i++)
1218 {
1219 if (bc->a[i] < 0) break;
1220 kputc(',', &bc->tmp);
1221 if ( bc->unseen==i ) kputs("<*>", &bc->tmp);
1222 else
1223 {
1224 kputc("ACGT"[bc->a[i]], &bc->tmp);
1225 has_alt = 1;
1226 }
1227 nals++;
1228 }
1229 }
1230 bcf_update_alleles_str(hdr, rec, bc->tmp.s);
1231
1232 bc->tmp.l = 0;
1233
1234 // INFO
1235 if ( bc->ori_ref < 0 )
1236 {
1237 bcf_update_info_flag(hdr, rec, "INDEL", NULL, 1);
1238 uint32_t idv = bca->max_support;
1239 if ( fmt_flag&B2B_INFO_IMF) {
1240 float max_frac;
1241 // Recompute IDV and IMF based on alignment results for more
1242 // accurate counts, but only when in new "--indels-cns" mode.
1243 if (bc->ADF && bc->ADR && bca->edlib) {
1244 int max_ad = 0;
1245 for (int k = 1; k < rec->n_allele; k++) {
1246 if (max_ad < bc->ADF[k] + bc->ADR[k])
1247 max_ad = bc->ADF[k] + bc->ADR[k];
1248 }
1249 max_frac = (double)(max_ad) / bc->ori_depth;
1250 idv = max_ad;
1251 } else {
1252 max_frac = bca->max_frac;
1253 }
1254 // Copied here to maintain order for consistency of "make check"
1255 if ( fmt_flag&B2B_INFO_IDV )
1256 bcf_update_info_int32(hdr, rec, "IDV", &idv, 1);
1257 bcf_update_info_float(hdr, rec, "IMF", &max_frac, 1);
1258 } else {
1259 if ( fmt_flag&B2B_INFO_IDV )
1260 bcf_update_info_int32(hdr, rec, "IDV", &idv, 1);
1261 }
1262 }
1263 bcf_update_info_int32(hdr, rec, "DP", &bc->ori_depth, 1);
1264 if ( fmt_flag&B2B_INFO_ADF )
1265 bcf_update_info_int32(hdr, rec, "ADF", bc->ADF, rec->n_allele);
1266 if ( fmt_flag&B2B_INFO_ADR )
1267 bcf_update_info_int32(hdr, rec, "ADR", bc->ADR, rec->n_allele);
1268 if ( fmt_flag&(B2B_INFO_AD|B2B_INFO_DPR) )
1269 {
1270 for (i=0; i<rec->n_allele; i++) bc->ADF[i] += bc->ADR[i];
1271 if ( fmt_flag&B2B_INFO_AD )
1272 bcf_update_info_int32(hdr, rec, "AD", bc->ADF, rec->n_allele);
1273 if ( fmt_flag&B2B_INFO_DPR )
1274 bcf_update_info_int32(hdr, rec, "DPR", bc->ADF, rec->n_allele);
1275 }
1276 if ( fmt_flag&B2B_INFO_SCR )
1277 bcf_update_info_int32(hdr, rec, "SCR", bc->SCR, 1);
1278
1279 float tmpf[16];
1280 for (i=0; i<16; i++) tmpf[i] = bc->anno[i];
1281 bcf_update_info_float(hdr, rec, "I16", tmpf, 16);
1282 bcf_update_info_float(hdr, rec, "QS", bc->qsum, nals);
1283
1284 if ( has_alt )
1285 {
1286 if ( fmt_flag&B2B_INFO_MIN_PL_SUM )
1287 bcf_update_info_int32(hdr, rec, "MIN_PL_SUM", &bc->shift, 1);
1288 if ( fmt_flag&B2B_INFO_VDB && bc->vdb != HUGE_VAL )
1289 bcf_update_info_float(hdr, rec, "VDB", &bc->vdb, 1);
1290 if ( fmt_flag&B2B_INFO_SGB && bc->seg_bias != HUGE_VAL )
1291 bcf_update_info_float(hdr, rec, "SGB", &bc->seg_bias, 1);
1292 if ( fmt_flag&B2B_INFO_NM && (bca->nnm[0] || bca->nnm[1]) )
1293 {
1294 for (i=0; i<2; i++) bc->nm[i] = bca->nnm[i] ? bca->nm[i]/bca->nnm[i] : 0;
1295 bcf_update_info_float(hdr, rec, "NM", bc->nm, 2);
1296 }
1297
1298 if ( fmt_flag&B2B_INFO_RPBZ && bc->mwu_pos != HUGE_VAL )
1299 bcf_update_info_float(hdr, rec, "RPBZ", &bc->mwu_pos, 1);
1300 if ( fmt_flag&B2B_INFO_MQBZ && bc->mwu_mq != HUGE_VAL )
1301 bcf_update_info_float(hdr, rec, "MQBZ", &bc->mwu_mq, 1);
1302 if ( fmt_flag&B2B_INFO_MQSBZ && bc->mwu_mqs != HUGE_VAL )
1303 bcf_update_info_float(hdr, rec, "MQSBZ", &bc->mwu_mqs, 1);
1304 if ( fmt_flag&B2B_INFO_BQBZ && bc->mwu_bq != HUGE_VAL )
1305 bcf_update_info_float(hdr, rec, "BQBZ", &bc->mwu_bq, 1);
1306 if ( fmt_flag&B2B_INFO_NMBZ && bc->mwu_nm[0] != HUGE_VAL )
1307 bcf_update_info_float(hdr, rec, "NMBZ", bc->mwu_nm, 1);
1308 if ( fmt_flag&B2B_INFO_SCBZ && bc->mwu_sc != HUGE_VAL )
1309 bcf_update_info_float(hdr, rec, "SCBZ", &bc->mwu_sc, 1);
1310 if ( fmt_flag&B2B_INFO_FS && bc->strand_bias != HUGE_VAL )
1311 bcf_update_info_float(hdr, rec, "FS", &bc->strand_bias, 1);
1312 }
1313
1314 tmpf[0] = bc->ori_depth ? (float)bc->mq0/bc->ori_depth : 0;
1315 if ( fmt_flag&B2B_INFO_MQ0F )
1316 bcf_update_info_float(hdr, rec, "MQ0F", tmpf, 1);
1317
1318 // FORMAT
1319 rec->n_sample = bc->n;
1320 bcf_update_format_int32(hdr, rec, "PL", bc->PL, nals*(nals+1)/2 * rec->n_sample);
1321 if ( fmt_flag&B2B_FMT_DP )
1322 {
1323 int32_t *ptr = (int32_t*) bc->fmt_arr;
1324 for (i=0; i<bc->n; i++)
1325 ptr[i] = bc->DP4[4*i] + bc->DP4[4*i+1] + bc->DP4[4*i+2] + bc->DP4[4*i+3];
1326 bcf_update_format_int32(hdr, rec, "DP", bc->fmt_arr, rec->n_sample);
1327 }
1328 if ( fmt_flag&B2B_FMT_DV )
1329 {
1330 int32_t *ptr = (int32_t*) bc->fmt_arr;
1331 for (i=0; i<bc->n; i++)
1332 ptr[i] = bc->DP4[4*i+2] + bc->DP4[4*i+3];
1333 bcf_update_format_int32(hdr, rec, "DV", bc->fmt_arr, rec->n_sample);
1334 }
1335 if ( fmt_flag&B2B_FMT_SP )
1336 {
1337 int32_t *ptr = (int32_t*) bc->fmt_arr;
1338 for (i=0; i<bc->n; i++)
1339 {
1340 int fwd_ref = bc->DP4[4*i], rev_ref = bc->DP4[4*i+1], fwd_alt = bc->DP4[4*i+2], rev_alt = bc->DP4[4*i+3];
1341 if ( fwd_ref+rev_ref<2 || fwd_alt+rev_alt<2 || fwd_ref+fwd_alt<2 || rev_ref+rev_alt<2 )
1342 ptr[i] = 0;
1343 else
1344 {
1345 double left, right, two;
1346 kt_fisher_exact(fwd_ref, rev_ref, fwd_alt, rev_alt, &left, &right, &two);
1347 int32_t x = (int)(-4.343 * log(two) + .499);
1348 if (x > 255) x = 255;
1349 ptr[i] = x;
1350 }
1351 }
1352 bcf_update_format_int32(hdr, rec, "SP", bc->fmt_arr, rec->n_sample);
1353 }
1354 if ( fmt_flag&B2B_FMT_DP4 )
1355 bcf_update_format_int32(hdr, rec, "DP4", bc->DP4, rec->n_sample*4);
1356 if ( fmt_flag&B2B_FMT_ADF )
1357 bcf_update_format_int32(hdr, rec, "ADF", bc->ADF+B2B_MAX_ALLELES, rec->n_sample*rec->n_allele);
1358 if ( fmt_flag&B2B_FMT_ADR )
1359 bcf_update_format_int32(hdr, rec, "ADR", bc->ADR+B2B_MAX_ALLELES, rec->n_sample*rec->n_allele);
1360 if ( fmt_flag&(B2B_FMT_AD|B2B_FMT_DPR) )
1361 {
1362 for (i=0; i<rec->n_sample*rec->n_allele; i++) bc->ADF[B2B_MAX_ALLELES+i] += bc->ADR[B2B_MAX_ALLELES+i];
1363 if ( fmt_flag&B2B_FMT_AD )
1364 bcf_update_format_int32(hdr, rec, "AD", bc->ADF+B2B_MAX_ALLELES, rec->n_sample*rec->n_allele);
1365 if ( fmt_flag&B2B_FMT_DPR )
1366 bcf_update_format_int32(hdr, rec, "DPR", bc->ADF+B2B_MAX_ALLELES, rec->n_sample*rec->n_allele);
1367 }
1368 if ( fmt_flag&B2B_FMT_SCR )
1369 bcf_update_format_int32(hdr, rec, "SCR", bc->SCR+1, rec->n_sample);
1370 if ( fmt_flag&B2B_FMT_QS )
1371 bcf_update_format_int32(hdr, rec, "QS", bc->QS, rec->n_sample*rec->n_allele);
1372
1373 if ( has_alt )
1374 {
1375 if ( fmt_flag&B2B_FMT_NMBZ )
1376 bcf_update_format_float(hdr, rec, "NMBZ", bc->mwu_nm+1, rec->n_sample);
1377 }
1378
1379 return 0;
1380 }