Debian Codegraph @

bcftools/bam2bcf.c.pysam.c

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