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