]> git.donarmstrong.com Git - samtools.git/blob - bam2bcf.c
Complain when BAM cannot be open. Severe bug fixed in -m haploid calling.
[samtools.git] / bam2bcf.c
1 #include <math.h>
2 #include <stdint.h>
3 #include "bam.h"
4 #include "kstring.h"
5 #include "bam2bcf.h"
6 #include "errmod.h"
7 #include "bcftools/bcf.h"
8
9 extern  void ks_introsort_uint32_t(size_t n, uint32_t a[]);
10
11 #define CALL_ETA 0.03f
12 #define CALL_MAX 256
13 #define CALL_DEFTHETA 0.83f
14 #define DEF_MAPQ 20
15
16 #define CAP_DIST 25
17
18 bcf_callaux_t *bcf_call_init(double theta, int min_baseQ)
19 {
20         bcf_callaux_t *bca;
21         if (theta <= 0.) theta = CALL_DEFTHETA;
22         bca = calloc(1, sizeof(bcf_callaux_t));
23         bca->capQ = 60;
24         bca->openQ = 40; bca->extQ = 20; bca->tandemQ = 100;
25         bca->min_baseQ = min_baseQ;
26         bca->e = errmod_init(1. - theta);
27         bca->min_frac = 0.002;
28         bca->min_support = 1;
29     bca->per_sample_flt = 0;
30         return bca;
31 }
32
33 void bcf_call_destroy(bcf_callaux_t *bca)
34 {
35         if (bca == 0) return;
36         errmod_destroy(bca->e);
37         free(bca->bases); free(bca->inscns); free(bca);
38 }
39 /* ref_base is the 4-bit representation of the reference base. It is
40  * negative if we are looking at an indel. */
41 int bcf_call_glfgen(int _n, const bam_pileup1_t *pl, int ref_base, bcf_callaux_t *bca, bcf_callret1_t *r)
42 {
43     static int *var_pos = NULL, nvar_pos = 0;
44         int i, n, ref4, is_indel, ori_depth = 0;
45         memset(r, 0, sizeof(bcf_callret1_t));
46         if (ref_base >= 0) {
47                 ref4 = bam_nt16_nt4_table[ref_base];
48                 is_indel = 0;
49         } else ref4 = 4, is_indel = 1;
50         if (_n == 0) return -1;
51         // enlarge the bases array if necessary
52         if (bca->max_bases < _n) {
53                 bca->max_bases = _n;
54                 kroundup32(bca->max_bases);
55                 bca->bases = (uint16_t*)realloc(bca->bases, 2 * bca->max_bases);
56         }
57         // fill the bases array
58         for (i = n = r->n_supp = 0; i < _n; ++i) {
59                 const bam_pileup1_t *p = pl + i;
60                 int q, b, mapQ, baseQ, is_diff, min_dist, seqQ;
61                 // set base
62                 if (p->is_del || p->is_refskip || (p->b->core.flag&BAM_FUNMAP)) continue;
63                 ++ori_depth;
64                 baseQ = q = is_indel? p->aux&0xff : (int)bam1_qual(p->b)[p->qpos]; // base/indel quality
65                 seqQ = is_indel? (p->aux>>8&0xff) : 99;
66                 if (q < bca->min_baseQ) continue;
67                 if (q > seqQ) q = seqQ;
68                 mapQ = p->b->core.qual < 255? p->b->core.qual : DEF_MAPQ; // special case for mapQ==255
69                 mapQ = mapQ < bca->capQ? mapQ : bca->capQ;
70                 if (q > mapQ) q = mapQ;
71                 if (q > 63) q = 63;
72                 if (q < 4) q = 4;
73                 if (!is_indel) {
74                         b = bam1_seqi(bam1_seq(p->b), p->qpos); // base
75                         b = bam_nt16_nt4_table[b? b : ref_base]; // b is the 2-bit base
76                         is_diff = (ref4 < 4 && b == ref4)? 0 : 1;
77                 } else {
78                         b = p->aux>>16&0x3f;
79                         is_diff = (b != 0);
80                 }
81                 if (is_diff) ++r->n_supp;
82                 bca->bases[n++] = q<<5 | (int)bam1_strand(p->b)<<4 | b;
83                 // collect annotations
84                 if (b < 4) r->qsum[b] += q;
85                 ++r->anno[0<<2|is_diff<<1|bam1_strand(p->b)];
86                 min_dist = p->b->core.l_qseq - 1 - p->qpos;
87                 if (min_dist > p->qpos) min_dist = p->qpos;
88                 if (min_dist > CAP_DIST) min_dist = CAP_DIST;
89                 r->anno[1<<2|is_diff<<1|0] += baseQ;
90                 r->anno[1<<2|is_diff<<1|1] += baseQ * baseQ;    // FIXME: signed int is not enough for thousands of samples
91                 r->anno[2<<2|is_diff<<1|0] += mapQ;
92                 r->anno[2<<2|is_diff<<1|1] += mapQ * mapQ;              // FIXME: signed int is not enough for thousands of samples
93                 r->anno[3<<2|is_diff<<1|0] += min_dist;
94                 r->anno[3<<2|is_diff<<1|1] += min_dist * min_dist;
95         }
96         r->depth = n; r->ori_depth = ori_depth;
97         // glfgen
98         errmod_cal(bca->e, n, 5, bca->bases, r->p);
99
100     // Calculate the Variant Distance Bias (make it optional?)
101     if ( nvar_pos < _n ) {
102         nvar_pos = _n;
103         var_pos = realloc(var_pos,sizeof(int)*nvar_pos);
104     }
105     int alt_dp=0, read_len=0;
106     for (i=0; i<_n; i++) {
107         const bam_pileup1_t *p = pl + i;
108         if ( bam1_seqi(bam1_seq(p->b),p->qpos) == ref_base ) 
109             continue;
110
111         var_pos[alt_dp] = p->qpos;
112         if ( (bam1_cigar(p->b)[0]&BAM_CIGAR_MASK)==4 )
113             var_pos[alt_dp] -= bam1_cigar(p->b)[0]>>BAM_CIGAR_SHIFT;
114
115         alt_dp++;
116         read_len += p->b->core.l_qseq;
117     }
118     float mvd=0;
119     int j;
120     n=0;
121     for (i=0; i<alt_dp; i++) {
122         for (j=0; j<i; j++) {
123             mvd += abs(var_pos[i] - var_pos[j]);
124             n++;
125         }
126     }
127     r->mvd[0] = n ? mvd/n : 0;
128     r->mvd[1] = alt_dp;
129     r->mvd[2] = alt_dp ? read_len/alt_dp : 0;
130
131         return r->depth;
132 }
133
134
135 void calc_vdb(int n, const bcf_callret1_t *calls, bcf_call_t *call)
136 {
137     // Variant distance bias. Samples merged by means of DP-weighted average.
138
139     float weight=0, tot_prob=0;
140
141     int i;
142     for (i=0; i<n; i++)
143     {
144         int mvd      = calls[i].mvd[0];
145         int dp       = calls[i].mvd[1];
146         int read_len = calls[i].mvd[2];
147
148         if ( dp<2 ) continue;
149
150         float prob = 0;
151         if ( dp==2 )
152         {
153             // Exact formula
154             prob = (mvd==0) ? 1.0/read_len : (read_len-mvd)*2.0/read_len/read_len;
155         }
156         else if ( dp==3 )
157         {
158             // Sin, quite accurate approximation
159             float mu = read_len/2.9;
160             prob = mvd>2*mu ? 0 : sin(mvd*3.14/2/mu) / (4*mu/3.14);
161         }
162         else
163         {
164             // Scaled gaussian curve, crude approximation, but behaves well. Using fixed depth for bigger depths.
165             if ( dp>5 )
166                 dp = 5;
167             float sigma2 = (read_len/1.9/(dp+1)) * (read_len/1.9/(dp+1));
168             float norm   = 1.125*sqrt(2*3.14*sigma2);
169             float mu     = read_len/2.9;
170             if ( mvd < mu )
171                 prob = exp(-(mvd-mu)*(mvd-mu)/2/sigma2)/norm;
172             else
173                 prob = exp(-(mvd-mu)*(mvd-mu)/3.125/sigma2)/norm;
174         }
175
176         //fprintf(stderr,"dp=%d mvd=%d read_len=%d -> prob=%f\n", dp,mvd,read_len,prob);
177         tot_prob += prob*dp;
178         weight += dp;
179     }
180     tot_prob = weight ? tot_prob/weight : 1; 
181     //fprintf(stderr,"prob=%f\n", tot_prob);
182     call->vdb = tot_prob;
183 }
184
185 int bcf_call_combine(int n, const bcf_callret1_t *calls, int ref_base /*4-bit*/, bcf_call_t *call)
186 {
187         int ref4, i, j, qsum[4];
188         int64_t tmp;
189         if (ref_base >= 0) {
190                 call->ori_ref = ref4 = bam_nt16_nt4_table[ref_base];
191                 if (ref4 > 4) ref4 = 4;
192         } else call->ori_ref = -1, ref4 = 0;
193         // calculate qsum
194         memset(qsum, 0, 4 * sizeof(int));
195         for (i = 0; i < n; ++i)
196                 for (j = 0; j < 4; ++j)
197                         qsum[j] += calls[i].qsum[j];
198     int qsum_tot=0;
199     for (j=0; j<4; j++) { qsum_tot += qsum[j]; call->qsum[j] = 0; }
200         for (j = 0; j < 4; ++j) qsum[j] = qsum[j] << 2 | j;
201         // find the top 2 alleles
202         for (i = 1; i < 4; ++i) // insertion sort
203                 for (j = i; j > 0 && qsum[j] < qsum[j-1]; --j)
204                         tmp = qsum[j], qsum[j] = qsum[j-1], qsum[j-1] = tmp;
205         // set the reference allele and alternative allele(s)
206         for (i = 0; i < 5; ++i) call->a[i] = -1;
207         call->unseen = -1;
208         call->a[0] = ref4;
209         for (i = 3, j = 1; i >= 0; --i) {
210                 if ((qsum[i]&3) != ref4) {
211                         if (qsum[i]>>2 != 0) 
212             {
213                 if ( j<4 ) call->qsum[j] = (float)(qsum[i]>>2)/qsum_tot; // ref N can make j>=4
214                 call->a[j++]  = qsum[i]&3;
215             }
216                         else break;
217                 }
218         else 
219             call->qsum[0] = (float)(qsum[i]>>2)/qsum_tot;
220         }
221         if (ref_base >= 0) { // for SNPs, find the "unseen" base
222                 if (((ref4 < 4 && j < 4) || (ref4 == 4 && j < 5)) && i >= 0)
223                         call->unseen = j, call->a[j++] = qsum[i]&3;
224                 call->n_alleles = j;
225         } else {
226                 call->n_alleles = j;
227                 if (call->n_alleles == 1) return -1; // no reliable supporting read. stop doing anything
228         }
229         // set the PL array
230         if (call->n < n) {
231                 call->n = n;
232                 call->PL = realloc(call->PL, 15 * n);
233         }
234         {
235                 int x, g[15], z;
236                 double sum_min = 0.;
237                 x = call->n_alleles * (call->n_alleles + 1) / 2;
238                 // get the possible genotypes
239                 for (i = z = 0; i < call->n_alleles; ++i)
240                         for (j = 0; j <= i; ++j)
241                                 g[z++] = call->a[j] * 5 + call->a[i];
242                 for (i = 0; i < n; ++i) {
243                         uint8_t *PL = call->PL + x * i;
244                         const bcf_callret1_t *r = calls + i;
245                         float min = 1e37;
246                         for (j = 0; j < x; ++j)
247                                 if (min > r->p[g[j]]) min = r->p[g[j]];
248                         sum_min += min;
249                         for (j = 0; j < x; ++j) {
250                                 int y;
251                                 y = (int)(r->p[g[j]] - min + .499);
252                                 if (y > 255) y = 255;
253                                 PL[j] = y;
254                         }
255                 }
256 //              if (ref_base < 0) fprintf(stderr, "%d,%d,%f,%d\n", call->n_alleles, x, sum_min, call->unseen);
257                 call->shift = (int)(sum_min + .499);
258         }
259         // combine annotations
260         memset(call->anno, 0, 16 * sizeof(int));
261         for (i = call->depth = call->ori_depth = 0, tmp = 0; i < n; ++i) {
262                 call->depth += calls[i].depth;
263                 call->ori_depth += calls[i].ori_depth;
264                 for (j = 0; j < 16; ++j) call->anno[j] += calls[i].anno[j];
265         }
266
267     calc_vdb(n, calls, call);
268
269         return 0;
270 }
271
272 int bcf_call2bcf(int tid, int pos, bcf_call_t *bc, bcf1_t *b, bcf_callret1_t *bcr, int fmt_flag,
273                                  const bcf_callaux_t *bca, const char *ref)
274 {
275         extern double kt_fisher_exact(int n11, int n12, int n21, int n22, double *_left, double *_right, double *two);
276         kstring_t s;
277         int i, j;
278         b->n_smpl = bc->n;
279         b->tid = tid; b->pos = pos; b->qual = 0;
280         s.s = b->str; s.m = b->m_str; s.l = 0;
281         kputc('\0', &s);
282         if (bc->ori_ref < 0) { // an indel
283                 // write REF
284                 kputc(ref[pos], &s);
285                 for (j = 0; j < bca->indelreg; ++j) kputc(ref[pos+1+j], &s);
286                 kputc('\0', &s);
287                 // write ALT
288                 kputc(ref[pos], &s);
289                 for (i = 1; i < 4; ++i) {
290                         if (bc->a[i] < 0) break;
291                         if (i > 1) {
292                                 kputc(',', &s); kputc(ref[pos], &s);
293                         }
294                         if (bca->indel_types[bc->a[i]] < 0) { // deletion
295                                 for (j = -bca->indel_types[bc->a[i]]; j < bca->indelreg; ++j)
296                                         kputc(ref[pos+1+j], &s);
297                         } else { // insertion; cannot be a reference unless a bug
298                                 char *inscns = &bca->inscns[bc->a[i] * bca->maxins];
299                                 for (j = 0; j < bca->indel_types[bc->a[i]]; ++j)
300                                         kputc("ACGTN"[(int)inscns[j]], &s);
301                                 for (j = 0; j < bca->indelreg; ++j) kputc(ref[pos+1+j], &s);
302                         }
303                 }
304                 kputc('\0', &s);
305         } else { // a SNP
306                 kputc("ACGTN"[bc->ori_ref], &s); kputc('\0', &s);
307                 for (i = 1; i < 5; ++i) {
308                         if (bc->a[i] < 0) break;
309                         if (i > 1) kputc(',', &s);
310                         kputc(bc->unseen == i? 'X' : "ACGT"[bc->a[i]], &s);
311                 }
312                 kputc('\0', &s);
313         }
314         kputc('\0', &s);
315         // INFO
316         if (bc->ori_ref < 0) ksprintf(&s,"INDEL;IS=%d,%f;", bca->max_support, bca->max_frac);
317         kputs("DP=", &s); kputw(bc->ori_depth, &s); kputs(";I16=", &s);
318         for (i = 0; i < 16; ++i) {
319                 if (i) kputc(',', &s);
320                 kputw(bc->anno[i], &s);
321         }
322     ksprintf(&s,";QS=%f,%f,%f,%f", bc->qsum[0],bc->qsum[1],bc->qsum[2],bc->qsum[3]);
323     if (bc->vdb != 1)
324         ksprintf(&s, ";VDB=%.4f", bc->vdb);
325         kputc('\0', &s);
326         // FMT
327         kputs("PL", &s);
328         if (bcr && fmt_flag) {
329                 if (fmt_flag & B2B_FMT_DP) kputs(":DP", &s);
330                 if (fmt_flag & B2B_FMT_DV) kputs(":DV", &s);
331                 if (fmt_flag & B2B_FMT_SP) kputs(":SP", &s);
332         }
333         kputc('\0', &s);
334         b->m_str = s.m; b->str = s.s; b->l_str = s.l;
335         bcf_sync(b);
336         memcpy(b->gi[0].data, bc->PL, b->gi[0].len * bc->n);
337         if (bcr && fmt_flag) {
338                 uint16_t *dp = (fmt_flag & B2B_FMT_DP)? b->gi[1].data : 0;
339                 uint16_t *dv = (fmt_flag & B2B_FMT_DV)? b->gi[1 + ((fmt_flag & B2B_FMT_DP) != 0)].data : 0;
340                 int32_t  *sp = (fmt_flag & B2B_FMT_SP)? b->gi[1 + ((fmt_flag & B2B_FMT_DP) != 0) + ((fmt_flag & B2B_FMT_DV) != 0)].data : 0;
341                 for (i = 0; i < bc->n; ++i) {
342                         bcf_callret1_t *p = bcr + i;
343                         if (dp) dp[i] = p->depth  < 0xffff? p->depth  : 0xffff;
344                         if (dv) dv[i] = p->n_supp < 0xffff? p->n_supp : 0xffff;
345                         if (sp) {
346                                 if (p->anno[0] + p->anno[1] < 2 || p->anno[2] + p->anno[3] < 2
347                                         || p->anno[0] + p->anno[2] < 2 || p->anno[1] + p->anno[3] < 2)
348                                 {
349                                         sp[i] = 0;
350                                 } else {
351                                         double left, right, two;
352                                         int x;
353                                         kt_fisher_exact(p->anno[0], p->anno[1], p->anno[2], p->anno[3], &left, &right, &two);
354                                         x = (int)(-4.343 * log(two) + .499);
355                                         if (x > 255) x = 255;
356                                         sp[i] = x;
357                                 }
358                         }
359                 }
360         }
361         return 0;
362 }