]> git.donarmstrong.com Git - samtools.git/blob - bcftools/prob1.c
Complain when BAM cannot be open. Severe bug fixed in -m haploid calling.
[samtools.git] / bcftools / prob1.c
1 #include <math.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <stdio.h>
5 #include <errno.h>
6 #include <assert.h>
7 #include <limits.h>
8 #include "prob1.h"
9 #include "kstring.h"
10
11 #include "kseq.h"
12 KSTREAM_INIT(gzFile, gzread, 16384)
13
14 #define MC_MAX_EM_ITER 16
15 #define MC_EM_EPS 1e-5
16 #define MC_DEF_INDEL 0.15
17
18 unsigned char seq_nt4_table[256] = {
19         4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4, 
20         4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4, 
21         4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4,  4, 4 /*'-'*/, 4, 4,
22         4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4, 
23         4, 0, 4, 1,  4, 4, 4, 2,  4, 4, 4, 4,  4, 4, 4, 4, 
24         4, 4, 4, 4,  3, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4, 
25         4, 0, 4, 1,  4, 4, 4, 2,  4, 4, 4, 4,  4, 4, 4, 4, 
26         4, 4, 4, 4,  3, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4, 
27         4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4, 
28         4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4, 
29         4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4, 
30         4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4, 
31         4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4, 
32         4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4, 
33         4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4, 
34         4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4,  4, 4, 4, 4
35 };
36
37 struct __bcf_p1aux_t {
38         int n, M, n1, is_indel;
39         uint8_t *ploidy; // haploid or diploid ONLY
40         double *q2p, *pdg; // pdg -> P(D|g)
41         double *phi, *phi_indel;
42         double *z, *zswap; // aux for afs
43         double *z1, *z2, *phi1, *phi2; // only calculated when n1 is set
44         double **hg; // hypergeometric distribution
45         double *lf; // log factorial
46         double t, t1, t2;
47         double *afs, *afs1; // afs: accumulative AFS; afs1: site posterior distribution
48         const uint8_t *PL; // point to PL
49         int PL_len;
50 };
51
52 void bcf_p1_indel_prior(bcf_p1aux_t *ma, double x)
53 {
54         int i;
55         for (i = 0; i < ma->M; ++i)
56                 ma->phi_indel[i] = ma->phi[i] * x;
57         ma->phi_indel[ma->M] = 1. - ma->phi[ma->M] * x;
58 }
59
60 static void init_prior(int type, double theta, int M, double *phi)
61 {
62         int i;
63         if (type == MC_PTYPE_COND2) {
64                 for (i = 0; i <= M; ++i)
65                         phi[i] = 2. * (i + 1) / (M + 1) / (M + 2);
66         } else if (type == MC_PTYPE_FLAT) {
67                 for (i = 0; i <= M; ++i)
68                         phi[i] = 1. / (M + 1);
69         } else {
70                 double sum;
71                 for (i = 0, sum = 0.; i < M; ++i)
72                         sum += (phi[i] = theta / (M - i));
73                 phi[M] = 1. - sum;
74         }
75 }
76
77 void bcf_p1_init_prior(bcf_p1aux_t *ma, int type, double theta)
78 {
79         init_prior(type, theta, ma->M, ma->phi);
80         bcf_p1_indel_prior(ma, MC_DEF_INDEL);
81 }
82
83 void bcf_p1_init_subprior(bcf_p1aux_t *ma, int type, double theta)
84 {
85         if (ma->n1 <= 0 || ma->n1 >= ma->M) return;
86         init_prior(type, theta, 2*ma->n1, ma->phi1);
87         init_prior(type, theta, 2*(ma->n - ma->n1), ma->phi2);
88 }
89
90 int bcf_p1_read_prior(bcf_p1aux_t *ma, const char *fn)
91 {
92         gzFile fp;
93         kstring_t s;
94         kstream_t *ks;
95         long double sum;
96         int dret, k;
97         memset(&s, 0, sizeof(kstring_t));
98         fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r");
99         ks = ks_init(fp);
100         memset(ma->phi, 0, sizeof(double) * (ma->M + 1));
101         while (ks_getuntil(ks, '\n', &s, &dret) >= 0) {
102                 if (strstr(s.s, "[afs] ") == s.s) {
103                         char *p = s.s + 6;
104                         for (k = 0; k <= ma->M; ++k) {
105                                 int x;
106                                 double y;
107                                 x = strtol(p, &p, 10);
108                                 if (x != k && (errno == EINVAL || errno == ERANGE)) return -1;
109                                 ++p;
110                                 y = strtod(p, &p);
111                                 if (y == 0. && (errno == EINVAL || errno == ERANGE)) return -1;
112                                 ma->phi[ma->M - k] += y;
113                         }
114                 }
115         }
116         ks_destroy(ks);
117         gzclose(fp);
118         free(s.s);
119         for (sum = 0., k = 0; k <= ma->M; ++k) sum += ma->phi[k];
120         fprintf(stderr, "[prior]");
121         for (k = 0; k <= ma->M; ++k) ma->phi[k] /= sum;
122         for (k = 0; k <= ma->M; ++k) fprintf(stderr, " %d:%.3lg", k, ma->phi[ma->M - k]);
123         fputc('\n', stderr);
124         for (sum = 0., k = 1; k < ma->M; ++k) sum += ma->phi[ma->M - k] * (2.* k * (ma->M - k) / ma->M / (ma->M - 1));
125         fprintf(stderr, "[%s] heterozygosity=%lf, ", __func__, (double)sum);
126         for (sum = 0., k = 1; k <= ma->M; ++k) sum += k * ma->phi[ma->M - k] / ma->M;
127         fprintf(stderr, "theta=%lf\n", (double)sum);
128         bcf_p1_indel_prior(ma, MC_DEF_INDEL);
129         return 0;
130 }
131
132 bcf_p1aux_t *bcf_p1_init(int n, uint8_t *ploidy)
133 {
134         bcf_p1aux_t *ma;
135         int i;
136         ma = calloc(1, sizeof(bcf_p1aux_t));
137         ma->n1 = -1;
138         ma->n = n; ma->M = 2 * n;
139         if (ploidy) {
140                 ma->ploidy = malloc(n);
141                 memcpy(ma->ploidy, ploidy, n);
142                 for (i = 0, ma->M = 0; i < n; ++i) ma->M += ploidy[i];
143                 if (ma->M == 2 * n) {
144                         free(ma->ploidy);
145                         ma->ploidy = 0;
146                 }
147         }
148         ma->q2p = calloc(256, sizeof(double));
149         ma->pdg = calloc(3 * ma->n, sizeof(double));
150         ma->phi = calloc(ma->M + 1, sizeof(double));
151         ma->phi_indel = calloc(ma->M + 1, sizeof(double));
152         ma->phi1 = calloc(ma->M + 1, sizeof(double));
153         ma->phi2 = calloc(ma->M + 1, sizeof(double));
154         ma->z = calloc(ma->M + 1, sizeof(double));
155         ma->zswap = calloc(ma->M + 1, sizeof(double));
156         ma->z1 = calloc(ma->M + 1, sizeof(double)); // actually we do not need this large
157         ma->z2 = calloc(ma->M + 1, sizeof(double));
158         ma->afs = calloc(ma->M + 1, sizeof(double));
159         ma->afs1 = calloc(ma->M + 1, sizeof(double));
160         ma->lf = calloc(ma->M + 1, sizeof(double));
161         for (i = 0; i < 256; ++i)
162                 ma->q2p[i] = pow(10., -i / 10.);
163         for (i = 0; i <= ma->M; ++i) ma->lf[i] = lgamma(i + 1);
164         bcf_p1_init_prior(ma, MC_PTYPE_FULL, 1e-3); // the simplest prior
165         return ma;
166 }
167
168 int bcf_p1_set_n1(bcf_p1aux_t *b, int n1)
169 {
170         if (n1 == 0 || n1 >= b->n) return -1;
171         if (b->M != b->n * 2) {
172                 fprintf(stderr, "[%s] unable to set `n1' when there are haploid samples.\n", __func__);
173                 return -1;
174         }
175         b->n1 = n1;
176         return 0;
177 }
178
179 void bcf_p1_set_ploidy(bcf1_t *b, bcf_p1aux_t *ma)
180 {
181     // bcf_p1aux_t fields are not visible outside of prob1.c, hence this wrapper.
182     // Ideally, this should set ploidy per site to allow pseudo-autosomal regions
183     b->ploidy = ma->ploidy;
184 }
185
186 void bcf_p1_destroy(bcf_p1aux_t *ma)
187 {
188         if (ma) {
189                 int k;
190                 free(ma->lf);
191                 if (ma->hg && ma->n1 > 0) {
192                         for (k = 0; k <= 2*ma->n1; ++k) free(ma->hg[k]);
193                         free(ma->hg);
194                 }
195                 free(ma->ploidy); free(ma->q2p); free(ma->pdg);
196                 free(ma->phi); free(ma->phi_indel); free(ma->phi1); free(ma->phi2);
197                 free(ma->z); free(ma->zswap); free(ma->z1); free(ma->z2);
198                 free(ma->afs); free(ma->afs1);
199                 free(ma);
200         }
201 }
202
203 extern double kf_gammap(double s, double z);
204 int test16(bcf1_t *b, anno16_t *a);
205
206 int call_multiallelic_gt(bcf1_t *b, bcf_p1aux_t *ma, double threshold)
207 {
208     int nals = 1;
209     char *p;
210     for (p=b->alt; *p; p++)
211     {
212         if ( *p=='X' || p[0]=='.' ) break;
213         if ( p[0]==',' ) nals++;
214     }
215     if ( b->alt[0] && !*p ) nals++;
216
217     if ( nals==1 ) return 1;
218
219     if ( nals>4 )
220     {
221         if ( *b->ref=='N' ) return 0;
222         fprintf(stderr,"Not ready for this, more than 4 alleles at %d: %s, %s\n", b->pos+1, b->ref,b->alt); 
223         exit(1);
224     }
225
226     // find PL and DP FORMAT indexes
227     uint8_t *pl = NULL;
228     int npl = 0, idp=-1;
229     int i;
230     for (i = 0; i < b->n_gi; ++i) 
231     {
232         if (b->gi[i].fmt == bcf_str2int("PL", 2)) 
233         {
234             pl  = (uint8_t*)b->gi[i].data;
235             npl = b->gi[i].len;
236         }
237         if (b->gi[i].fmt == bcf_str2int("DP", 2))  idp=i;
238     }
239     if ( !pl ) return -1;
240
241     assert(ma->q2p[0] == 1);
242
243     // Init P(D|G)
244     int npdg = nals*(nals+1)/2;
245     double *pdg,*_pdg;
246     _pdg = pdg = malloc(sizeof(double)*ma->n*npdg);
247     for (i=0; i<ma->n; i++)
248     {
249         int j; 
250         double sum = 0;
251         for (j=0; j<npdg; j++)
252         {
253             //_pdg[j] = pow(10,-0.1*pl[j]); 
254             _pdg[j] = ma->q2p[pl[j]];
255             sum += _pdg[j];
256         }
257         if ( sum )
258             for (j=0; j<npdg; j++) _pdg[j] /= sum;
259         _pdg += npdg;
260         pl += npl;
261     }
262
263     if ((p = strstr(b->info, "QS=")) == 0) { fprintf(stderr,"INFO/QS is required with -m, exiting\n"); exit(1); }
264     double qsum[4];
265     if ( sscanf(p+3,"%lf,%lf,%lf,%lf",&qsum[0],&qsum[1],&qsum[2],&qsum[3])!=4 ) { fprintf(stderr,"Could not parse %s\n",p); exit(1); }
266
267
268     // Calculate the most likely combination of alleles
269     int ia,ib,ic, max_als=0, max_als2=0;
270     double ref_lk = 0, max_lk = INT_MIN, max_lk2 = INT_MIN, lk_sum = INT_MIN;
271     for (ia=0; ia<nals; ia++)
272     {
273         double lk_tot = 0;
274         int iaa = (ia+1)*(ia+2)/2-1;
275         int isample;
276         for (isample=0; isample<ma->n; isample++)
277         {
278             double *p = pdg + isample*npdg;
279             // assert( log(p[iaa]) <= 0 );
280             lk_tot += log(p[iaa]);
281         }
282         if ( ia==0 ) ref_lk = lk_tot;
283         if ( max_lk<lk_tot ) { max_lk2 = max_lk; max_als2 = max_als; max_lk = lk_tot; max_als = 1<<ia; }
284         else if ( max_lk2<lk_tot ) { max_lk2 = lk_tot; max_als2 = 1<<ia; }
285         lk_sum = lk_tot>lk_sum ? lk_tot + log(1+exp(lk_sum-lk_tot)) : lk_sum + log(1+exp(lk_tot-lk_sum));
286     }
287     if ( nals>1 )
288     {
289         for (ia=0; ia<nals; ia++)
290         {
291             if ( qsum[ia]==0 ) continue;
292             int iaa = (ia+1)*(ia+2)/2-1;
293             for (ib=0; ib<ia; ib++)
294             {
295                 if ( qsum[ib]==0 ) continue;
296                 double lk_tot = 0;
297                 double fa  = qsum[ia]/(qsum[ia]+qsum[ib]);
298                 double fb  = qsum[ib]/(qsum[ia]+qsum[ib]);
299                 double fab = 2*fa*fb; fa *= fa; fb *= fb;
300                 int isample, ibb = (ib+1)*(ib+2)/2-1, iab = iaa - ia + ib;
301                 for (isample=0; isample<ma->n; isample++)
302                 {
303                     double *p = pdg + isample*npdg;
304                     //assert( log(fa*p[iaa] + fb*p[ibb] + fab*p[iab]) <= 0 );
305                     if ( b->ploidy && b->ploidy[isample]==1 )
306                         lk_tot +=  log(fa*p[iaa] + fb*p[ibb]);
307                     else 
308                         lk_tot +=  log(fa*p[iaa] + fb*p[ibb] + fab*p[iab]);
309                 }
310                 if ( max_lk<lk_tot ) { max_lk2 = max_lk; max_als2 = max_als; max_lk = lk_tot; max_als = 1<<ia|1<<ib; }
311                 else if ( max_lk2<lk_tot ) { max_lk2 = lk_tot; max_als2 = 1<<ia|1<<ib; }
312                 lk_sum = lk_tot>lk_sum ? lk_tot + log(1+exp(lk_sum-lk_tot)) : lk_sum + log(1+exp(lk_tot-lk_sum));
313             }
314         }
315     }
316     if ( nals>2 )
317     {
318         for (ia=0; ia<nals; ia++)
319         {
320             if ( qsum[ia]==0 ) continue;
321             int iaa = (ia+1)*(ia+2)/2-1;
322             for (ib=0; ib<ia; ib++)
323             {
324                 if ( qsum[ib]==0 ) continue;
325                 int ibb = (ib+1)*(ib+2)/2-1; 
326                 int iab = iaa - ia + ib;
327                 for (ic=0; ic<ib; ic++)
328                 {
329                     if ( qsum[ic]==0 ) continue;
330                     double lk_tot = 0;
331                     double fa  = qsum[ia]/(qsum[ia]+qsum[ib]+qsum[ic]);
332                     double fb  = qsum[ib]/(qsum[ia]+qsum[ib]+qsum[ic]);
333                     double fc  = qsum[ic]/(qsum[ia]+qsum[ib]+qsum[ic]);
334                     double fab = 2*fa*fb, fac = 2*fa*fc, fbc = 2*fb*fc; fa *= fa; fb *= fb; fc *= fc;
335                     int isample, icc = (ic+1)*(ic+2)/2-1;
336                     int iac = iaa - ia + ic, ibc = ibb - ib + ic;
337                     for (isample=0; isample<ma->n; isample++)
338                     {
339                         double *p = pdg + isample*npdg;
340                         //assert( log(fa*p[iaa] + fb*p[ibb] + fc*p[icc] + fab*p[iab] + fac*p[iac] + fbc*p[ibc]) <= 0 );
341                         if ( b->ploidy && b->ploidy[isample]==1 ) 
342                             lk_tot += log(fa*p[iaa] + fb*p[ibb] + fc*p[icc]);
343                         else
344                             lk_tot += log(fa*p[iaa] + fb*p[ibb] + fc*p[icc] + fab*p[iab] + fac*p[iac] + fbc*p[ibc]);
345                     }
346                     if ( max_lk<lk_tot ) { max_lk2 = max_lk; max_als2 = max_als; max_lk = lk_tot; max_als = 1<<ia|1<<ib|1<<ic; }
347                     else if ( max_lk2<lk_tot ) { max_lk2 = lk_tot; max_als2 = 1<<ia|1<<ib|1<<ic; }
348                     lk_sum = lk_tot>lk_sum ? lk_tot + log(1+exp(lk_sum-lk_tot)) : lk_sum + log(1+exp(lk_tot-lk_sum));
349                 }
350             }
351         }
352     }
353
354     // Should we add another allele, does it increase the likelihood significantly?
355     int n1=0, n2=0;
356     for (i=0; i<nals; i++) if ( max_als&1<<i) n1++;
357     for (i=0; i<nals; i++) if ( max_als2&1<<i) n2++;
358     if ( n2<n1 && kf_gammap(1,2.0*(max_lk-max_lk2))<threshold )
359     {
360         max_lk = max_lk2;
361         max_als = max_als2;
362     }
363
364     // Get the BCF record ready for GT and GQ
365     kstring_t s;
366     int old_n_gi = b->n_gi;
367     s.m = b->m_str; s.l = b->l_str - 1; s.s = b->str;
368     kputs(":GT:GQ", &s); kputc('\0', &s);
369     b->m_str = s.m; b->l_str = s.l; b->str = s.s;
370     bcf_sync(b);
371
372     // Call GTs
373     int isample, gts=0, ac[4] = {0,0,0,0};
374     for (isample = 0; isample < b->n_smpl; isample++) 
375     {
376         int ploidy = b->ploidy ? b->ploidy[isample] : 2;
377         double *p = pdg + isample*npdg;
378         int ia, als = 0;
379         double lk = 0, lk_sum=0;
380         for (ia=0; ia<nals; ia++)
381         {
382             if ( !(max_als&1<<ia) ) continue;
383             int iaa = (ia+1)*(ia+2)/2-1;
384             double _lk = p[iaa]*qsum[ia]*qsum[ia];
385             if ( _lk > lk ) { lk = _lk; als = ia<<3 | ia; }
386             lk_sum += _lk;
387         }
388         if ( ploidy==2 ) 
389         {
390             for (ia=0; ia<nals; ia++)
391             {
392                 if ( !(max_als&1<<ia) ) continue;
393                 int iaa = (ia+1)*(ia+2)/2-1;
394                 for (ib=0; ib<ia; ib++)
395                 {
396                     if ( !(max_als&1<<ib) ) continue;
397                     int iab = iaa - ia + ib;
398                     double _lk = 2*qsum[ia]*qsum[ib]*p[iab];
399                     if ( _lk > lk ) { lk = _lk; als = ib<<3 | ia; }
400                     lk_sum += _lk;
401                 }
402             }
403         }
404         lk = -log(1-lk/lk_sum)/0.2302585;
405         if ( idp>=0 && ((uint16_t*)b->gi[idp].data)[isample]==0 ) 
406         {
407             ((uint8_t*)b->gi[old_n_gi].data)[isample]   = 1<<7;
408             ((uint8_t*)b->gi[old_n_gi+1].data)[isample] = 0;
409             continue;
410         }
411         ((uint8_t*)b->gi[old_n_gi].data)[isample]   = als;
412         ((uint8_t*)b->gi[old_n_gi+1].data)[isample] = lk<100 ? (int)lk : 99;
413
414         gts |= 1<<(als>>3&7) | 1<<(als&7);
415         ac[ als>>3&7 ]++;
416         ac[ als&7 ]++;
417     }
418     bcf_fit_alt(b,max_als);
419
420
421     // Prepare BCF for output: ref, alt, filter, info, format
422     memset(&s, 0, sizeof(kstring_t)); kputc('\0', &s); 
423     kputs(b->ref, &s); kputc('\0', &s);
424     kputs(b->alt, &s); kputc('\0', &s); kputc('\0', &s);
425     {
426         int an=0, nalts=0;
427         for (i=0; i<nals; i++)
428         {
429             an += ac[i];
430             if ( i>0 && ac[i] ) nalts++;
431         }
432         ksprintf(&s, "AN=%d;", an);
433         if ( nalts )
434         {
435             kputs("AC=", &s);
436             for (i=1; i<nals; i++)
437             {
438                 if ( !(gts&1<<i) ) continue;
439                 nalts--;
440                 ksprintf(&s,"%d", ac[i]);
441                 if ( nalts>0 ) kputc(',', &s);
442             }
443             kputc(';', &s);
444         }
445         kputs(b->info, &s); 
446         anno16_t a;
447         int has_I16 = test16(b, &a) >= 0? 1 : 0;
448         if (has_I16 )
449         {
450             if ( a.is_tested) ksprintf(&s, ";PV4=%.2g,%.2g,%.2g,%.2g", a.p[0], a.p[1], a.p[2], a.p[3]);
451             ksprintf(&s, ";DP4=%d,%d,%d,%d;MQ=%d", a.d[0], a.d[1], a.d[2], a.d[3], a.mq);
452         }
453         kputc('\0', &s);
454         rm_info(&s, "I16=");
455         rm_info(&s, "QS=");
456     }
457     kputs(b->fmt, &s); kputc('\0', &s);
458     free(b->str);
459     b->m_str = s.m; b->l_str = s.l; b->str = s.s;
460     b->qual = gts>1 ? -4.343*(ref_lk - lk_sum) : -4.343*(max_lk - lk_sum);
461     if ( b->qual>999 ) b->qual = 999;
462     bcf_sync(b);
463
464
465     free(pdg);
466     return gts;
467 }
468
469 static int cal_pdg(const bcf1_t *b, bcf_p1aux_t *ma)
470 {
471     int i, j;
472     long *p, tmp;
473     p = alloca(b->n_alleles * sizeof(long));
474     memset(p, 0, sizeof(long) * b->n_alleles);
475     for (j = 0; j < ma->n; ++j) {
476         const uint8_t *pi = ma->PL + j * ma->PL_len;
477         double *pdg = ma->pdg + j * 3;
478         pdg[0] = ma->q2p[pi[2]]; pdg[1] = ma->q2p[pi[1]]; pdg[2] = ma->q2p[pi[0]];
479         for (i = 0; i < b->n_alleles; ++i)
480             p[i] += (int)pi[(i+1)*(i+2)/2-1];
481     }
482     for (i = 0; i < b->n_alleles; ++i) p[i] = p[i]<<4 | i;
483     for (i = 1; i < b->n_alleles; ++i) // insertion sort
484         for (j = i; j > 0 && p[j] < p[j-1]; --j)
485             tmp = p[j], p[j] = p[j-1], p[j-1] = tmp;
486     for (i = b->n_alleles - 1; i >= 0; --i)
487         if ((p[i]&0xf) == 0) break;
488     return i;
489 }
490
491
492 int bcf_p1_call_gt(const bcf_p1aux_t *ma, double f0, int k)
493 {
494         double sum, g[3];
495         double max, f3[3], *pdg = ma->pdg + k * 3;
496         int q, i, max_i, ploidy;
497         ploidy = ma->ploidy? ma->ploidy[k] : 2;
498         if (ploidy == 2) {
499                 f3[0] = (1.-f0)*(1.-f0); f3[1] = 2.*f0*(1.-f0); f3[2] = f0*f0;
500         } else {
501                 f3[0] = 1. - f0; f3[1] = 0; f3[2] = f0;
502         }
503         for (i = 0, sum = 0.; i < 3; ++i)
504                 sum += (g[i] = pdg[i] * f3[i]);
505         for (i = 0, max = -1., max_i = 0; i < 3; ++i) {
506                 g[i] /= sum;
507                 if (g[i] > max) max = g[i], max_i = i;
508         }
509         max = 1. - max;
510         if (max < 1e-308) max = 1e-308;
511         q = (int)(-4.343 * log(max) + .499);
512         if (q > 99) q = 99;
513         return q<<2|max_i;
514 }
515
516 #define TINY 1e-20
517
518 static void mc_cal_y_core(bcf_p1aux_t *ma, int beg)
519 {
520         double *z[2], *tmp, *pdg;
521         int _j, last_min, last_max;
522         assert(beg == 0 || ma->M == ma->n*2);
523         z[0] = ma->z;
524         z[1] = ma->zswap;
525         pdg = ma->pdg;
526         memset(z[0], 0, sizeof(double) * (ma->M + 1));
527         memset(z[1], 0, sizeof(double) * (ma->M + 1));
528         z[0][0] = 1.;
529         last_min = last_max = 0;
530         ma->t = 0.;
531         if (ma->M == ma->n * 2) {
532                 int M = 0;
533                 for (_j = beg; _j < ma->n; ++_j) {
534                         int k, j = _j - beg, _min = last_min, _max = last_max, M0;
535                         double p[3], sum;
536                         M0 = M; M += 2;
537                         pdg = ma->pdg + _j * 3;
538                         p[0] = pdg[0]; p[1] = 2. * pdg[1]; p[2] = pdg[2];
539                         for (; _min < _max && z[0][_min] < TINY; ++_min) z[0][_min] = z[1][_min] = 0.;
540                         for (; _max > _min && z[0][_max] < TINY; --_max) z[0][_max] = z[1][_max] = 0.;
541                         _max += 2;
542                         if (_min == 0) k = 0, z[1][k] = (M0-k+1) * (M0-k+2) * p[0] * z[0][k];
543                         if (_min <= 1) k = 1, z[1][k] = (M0-k+1) * (M0-k+2) * p[0] * z[0][k] + k*(M0-k+2) * p[1] * z[0][k-1];
544                         for (k = _min < 2? 2 : _min; k <= _max; ++k)
545                                 z[1][k] = (M0-k+1)*(M0-k+2) * p[0] * z[0][k] + k*(M0-k+2) * p[1] * z[0][k-1] + k*(k-1)* p[2] * z[0][k-2];
546                         for (k = _min, sum = 0.; k <= _max; ++k) sum += z[1][k];
547                         ma->t += log(sum / (M * (M - 1.)));
548                         for (k = _min; k <= _max; ++k) z[1][k] /= sum;
549                         if (_min >= 1) z[1][_min-1] = 0.;
550                         if (_min >= 2) z[1][_min-2] = 0.;
551                         if (j < ma->n - 1) z[1][_max+1] = z[1][_max+2] = 0.;
552                         if (_j == ma->n1 - 1) { // set pop1; ma->n1==-1 when unset
553                                 ma->t1 = ma->t;
554                                 memcpy(ma->z1, z[1], sizeof(double) * (ma->n1 * 2 + 1));
555                         }
556                         tmp = z[0]; z[0] = z[1]; z[1] = tmp;
557                         last_min = _min; last_max = _max;
558                 }
559                 //for (_j = 0; _j < last_min; ++_j) z[0][_j] = 0.; // TODO: are these necessary?
560                 //for (_j = last_max + 1; _j < ma->M; ++_j) z[0][_j] = 0.;
561         } else { // this block is very similar to the block above; these two might be merged in future
562                 int j, M = 0;
563                 for (j = 0; j < ma->n; ++j) {
564                         int k, M0, _min = last_min, _max = last_max;
565                         double p[3], sum;
566                         pdg = ma->pdg + j * 3;
567                         for (; _min < _max && z[0][_min] < TINY; ++_min) z[0][_min] = z[1][_min] = 0.;
568                         for (; _max > _min && z[0][_max] < TINY; --_max) z[0][_max] = z[1][_max] = 0.;
569                         M0 = M;
570                         M += ma->ploidy[j];
571                         if (ma->ploidy[j] == 1) {
572                                 p[0] = pdg[0]; p[1] = pdg[2];
573                                 _max++;
574                                 if (_min == 0) k = 0, z[1][k] = (M0+1-k) * p[0] * z[0][k];
575                                 for (k = _min < 1? 1 : _min; k <= _max; ++k)
576                                         z[1][k] = (M0+1-k) * p[0] * z[0][k] + k * p[1] * z[0][k-1];
577                                 for (k = _min, sum = 0.; k <= _max; ++k) sum += z[1][k];
578                                 ma->t += log(sum / M);
579                                 for (k = _min; k <= _max; ++k) z[1][k] /= sum;
580                                 if (_min >= 1) z[1][_min-1] = 0.;
581                                 if (j < ma->n - 1) z[1][_max+1] = 0.;
582                         } else if (ma->ploidy[j] == 2) {
583                                 p[0] = pdg[0]; p[1] = 2 * pdg[1]; p[2] = pdg[2];
584                                 _max += 2;
585                                 if (_min == 0) k = 0, z[1][k] = (M0-k+1) * (M0-k+2) * p[0] * z[0][k];
586                                 if (_min <= 1) k = 1, z[1][k] = (M0-k+1) * (M0-k+2) * p[0] * z[0][k] + k*(M0-k+2) * p[1] * z[0][k-1];
587                                 for (k = _min < 2? 2 : _min; k <= _max; ++k)
588                                         z[1][k] = (M0-k+1)*(M0-k+2) * p[0] * z[0][k] + k*(M0-k+2) * p[1] * z[0][k-1] + k*(k-1)* p[2] * z[0][k-2];
589                                 for (k = _min, sum = 0.; k <= _max; ++k) sum += z[1][k];
590                                 ma->t += log(sum / (M * (M - 1.)));
591                                 for (k = _min; k <= _max; ++k) z[1][k] /= sum;
592                                 if (_min >= 1) z[1][_min-1] = 0.;
593                                 if (_min >= 2) z[1][_min-2] = 0.;
594                                 if (j < ma->n - 1) z[1][_max+1] = z[1][_max+2] = 0.;
595                         }
596                         tmp = z[0]; z[0] = z[1]; z[1] = tmp;
597                         last_min = _min; last_max = _max;
598                 }
599         }
600         if (z[0] != ma->z) memcpy(ma->z, z[0], sizeof(double) * (ma->M + 1));
601 }
602
603 static void mc_cal_y(bcf_p1aux_t *ma)
604 {
605         if (ma->n1 > 0 && ma->n1 < ma->n && ma->M == ma->n * 2) { // NB: ma->n1 is ineffective when there are haploid samples
606                 int k;
607                 long double x;
608                 memset(ma->z1, 0, sizeof(double) * (2 * ma->n1 + 1));
609                 memset(ma->z2, 0, sizeof(double) * (2 * (ma->n - ma->n1) + 1));
610                 ma->t1 = ma->t2 = 0.;
611                 mc_cal_y_core(ma, ma->n1);
612                 ma->t2 = ma->t;
613                 memcpy(ma->z2, ma->z, sizeof(double) * (2 * (ma->n - ma->n1) + 1));
614                 mc_cal_y_core(ma, 0);
615                 // rescale z
616                 x = expl(ma->t - (ma->t1 + ma->t2));
617                 for (k = 0; k <= ma->M; ++k) ma->z[k] *= x;
618         } else mc_cal_y_core(ma, 0);
619 }
620
621 #define CONTRAST_TINY 1e-30
622
623 extern double kf_gammaq(double s, double z); // incomplete gamma function for chi^2 test
624
625 static inline double chi2_test(int a, int b, int c, int d)
626 {
627         double x, z;
628         x = (double)(a+b) * (c+d) * (b+d) * (a+c);
629         if (x == 0.) return 1;
630         z = a * d - b * c;
631         return kf_gammaq(.5, .5 * z * z * (a+b+c+d) / x);
632 }
633
634 // chi2=(a+b+c+d)(ad-bc)^2/[(a+b)(c+d)(a+c)(b+d)]
635 static inline double contrast2_aux(const bcf_p1aux_t *p1, double sum, int k1, int k2, double x[3])
636 {
637         double p = p1->phi[k1+k2] * p1->z1[k1] * p1->z2[k2] / sum * p1->hg[k1][k2];
638         int n1 = p1->n1, n2 = p1->n - p1->n1;
639         if (p < CONTRAST_TINY) return -1;
640         if (.5*k1/n1 < .5*k2/n2) x[1] += p;
641         else if (.5*k1/n1 > .5*k2/n2) x[2] += p;
642         else x[0] += p;
643         return p * chi2_test(k1, k2, (n1<<1) - k1, (n2<<1) - k2);
644 }
645
646 static double contrast2(bcf_p1aux_t *p1, double ret[3])
647 {
648         int k, k1, k2, k10, k20, n1, n2;
649         double sum;
650         // get n1 and n2
651         n1 = p1->n1; n2 = p1->n - p1->n1;
652         if (n1 <= 0 || n2 <= 0) return 0.;
653         if (p1->hg == 0) { // initialize the hypergeometric distribution
654                 /* NB: the hg matrix may take a lot of memory when there are many samples. There is a way
655                    to avoid precomputing this matrix, but it is slower and quite intricate. The following
656                    computation in this block can be accelerated with a similar strategy, but perhaps this
657                    is not a serious concern for now. */
658                 double tmp = lgamma(2*(n1+n2)+1) - (lgamma(2*n1+1) + lgamma(2*n2+1));
659                 p1->hg = calloc(2*n1+1, sizeof(void*));
660                 for (k1 = 0; k1 <= 2*n1; ++k1) {
661                         p1->hg[k1] = calloc(2*n2+1, sizeof(double));
662                         for (k2 = 0; k2 <= 2*n2; ++k2)
663                                 p1->hg[k1][k2] = exp(lgamma(k1+k2+1) + lgamma(p1->M-k1-k2+1) - (lgamma(k1+1) + lgamma(k2+1) + lgamma(2*n1-k1+1) + lgamma(2*n2-k2+1) + tmp));
664                 }
665         }
666         { // compute
667                 long double suml = 0;
668                 for (k = 0; k <= p1->M; ++k) suml += p1->phi[k] * p1->z[k];
669                 sum = suml;
670         }
671         { // get the max k1 and k2
672                 double max;
673                 int max_k;
674                 for (k = 0, max = 0, max_k = -1; k <= 2*n1; ++k) {
675                         double x = p1->phi1[k] * p1->z1[k];
676                         if (x > max) max = x, max_k = k;
677                 }
678                 k10 = max_k;
679                 for (k = 0, max = 0, max_k = -1; k <= 2*n2; ++k) {
680                         double x = p1->phi2[k] * p1->z2[k];
681                         if (x > max) max = x, max_k = k;
682                 }
683                 k20 = max_k;
684         }
685         { // We can do the following with one nested loop, but that is an O(N^2) thing. The following code block is much faster for large N.
686                 double x[3], y;
687                 long double z = 0., L[2];
688                 x[0] = x[1] = x[2] = 0; L[0] = L[1] = 0;
689                 for (k1 = k10; k1 >= 0; --k1) {
690                         for (k2 = k20; k2 >= 0; --k2) {
691                                 if ((y = contrast2_aux(p1, sum, k1, k2, x)) < 0) break;
692                                 else z += y;
693                         }
694                         for (k2 = k20 + 1; k2 <= 2*n2; ++k2) {
695                                 if ((y = contrast2_aux(p1, sum, k1, k2, x)) < 0) break;
696                                 else z += y;
697                         }
698                 }
699                 ret[0] = x[0]; ret[1] = x[1]; ret[2] = x[2];
700                 x[0] = x[1] = x[2] = 0;
701                 for (k1 = k10 + 1; k1 <= 2*n1; ++k1) {
702                         for (k2 = k20; k2 >= 0; --k2) {
703                                 if ((y = contrast2_aux(p1, sum, k1, k2, x)) < 0) break;
704                                 else z += y;
705                         }
706                         for (k2 = k20 + 1; k2 <= 2*n2; ++k2) {
707                                 if ((y = contrast2_aux(p1, sum, k1, k2, x)) < 0) break;
708                                 else z += y;
709                         }
710                 }
711                 ret[0] += x[0]; ret[1] += x[1]; ret[2] += x[2];
712                 if (ret[0] + ret[1] + ret[2] < 0.95) { // in case of bad things happened
713                         ret[0] = ret[1] = ret[2] = 0; L[0] = L[1] = 0;
714                         for (k1 = 0, z = 0.; k1 <= 2*n1; ++k1)
715                                 for (k2 = 0; k2 <= 2*n2; ++k2)
716                                         if ((y = contrast2_aux(p1, sum, k1, k2, ret)) >= 0) z += y;
717                         if (ret[0] + ret[1] + ret[2] < 0.95) // It seems that this may be caused by floating point errors. I do not really understand why...
718                                 z = 1.0, ret[0] = ret[1] = ret[2] = 1./3;
719                 }
720                 return (double)z;
721         }
722 }
723
724 static double mc_cal_afs(bcf_p1aux_t *ma, double *p_ref_folded, double *p_var_folded)
725 {
726         int k;
727         long double sum = 0., sum2;
728         double *phi = ma->is_indel? ma->phi_indel : ma->phi;
729         memset(ma->afs1, 0, sizeof(double) * (ma->M + 1));
730         mc_cal_y(ma);
731         // compute AFS
732         for (k = 0, sum = 0.; k <= ma->M; ++k)
733                 sum += (long double)phi[k] * ma->z[k];
734         for (k = 0; k <= ma->M; ++k) {
735                 ma->afs1[k] = phi[k] * ma->z[k] / sum;
736                 if (isnan(ma->afs1[k]) || isinf(ma->afs1[k])) return -1.;
737         }
738         // compute folded variant probability
739         for (k = 0, sum = 0.; k <= ma->M; ++k)
740                 sum += (long double)(phi[k] + phi[ma->M - k]) / 2. * ma->z[k];
741         for (k = 1, sum2 = 0.; k < ma->M; ++k)
742                 sum2 += (long double)(phi[k] + phi[ma->M - k]) / 2. * ma->z[k];
743         *p_var_folded = sum2 / sum;
744         *p_ref_folded = (phi[k] + phi[ma->M - k]) / 2. * (ma->z[ma->M] + ma->z[0]) / sum;
745         // the expected frequency
746         for (k = 0, sum = 0.; k <= ma->M; ++k) {
747                 ma->afs[k] += ma->afs1[k];
748                 sum += k * ma->afs1[k];
749         }
750         return sum / ma->M;
751 }
752
753 int bcf_p1_cal(const bcf1_t *b, int do_contrast, bcf_p1aux_t *ma, bcf_p1rst_t *rst)
754 {
755         int i, k;
756         long double sum = 0.;
757         ma->is_indel = bcf_is_indel(b);
758         rst->perm_rank = -1;
759         // set PL and PL_len
760         for (i = 0; i < b->n_gi; ++i) {
761                 if (b->gi[i].fmt == bcf_str2int("PL", 2)) {
762                         ma->PL = (uint8_t*)b->gi[i].data;
763                         ma->PL_len = b->gi[i].len;
764                         break;
765                 }
766         }
767         if (i == b->n_gi) return -1; // no PL
768         if (b->n_alleles < 2) return -1; // FIXME: find a better solution
769         // 
770         rst->rank0 = cal_pdg(b, ma);
771         rst->f_exp = mc_cal_afs(ma, &rst->p_ref_folded, &rst->p_var_folded);
772         rst->p_ref = ma->afs1[ma->M];
773         for (k = 0, sum = 0.; k < ma->M; ++k)
774                 sum += ma->afs1[k];
775         rst->p_var = (double)sum;
776         { // compute the allele count
777                 double max = -1;
778                 rst->ac = -1;
779                 for (k = 0; k <= ma->M; ++k)
780                         if (max < ma->z[k]) max = ma->z[k], rst->ac = k;
781                 rst->ac = ma->M - rst->ac;
782         }
783         // calculate f_flat and f_em
784         for (k = 0, sum = 0.; k <= ma->M; ++k)
785                 sum += (long double)ma->z[k];
786         rst->f_flat = 0.;
787         for (k = 0; k <= ma->M; ++k) {
788                 double p = ma->z[k] / sum;
789                 rst->f_flat += k * p;
790         }
791         rst->f_flat /= ma->M;
792         { // estimate equal-tail credible interval (95% level)
793                 int l, h;
794                 double p;
795                 for (i = 0, p = 0.; i <= ma->M; ++i)
796                         if (p + ma->afs1[i] > 0.025) break;
797                         else p += ma->afs1[i];
798                 l = i;
799                 for (i = ma->M, p = 0.; i >= 0; --i)
800                         if (p + ma->afs1[i] > 0.025) break;
801                         else p += ma->afs1[i];
802                 h = i;
803                 rst->cil = (double)(ma->M - h) / ma->M; rst->cih = (double)(ma->M - l) / ma->M;
804         }
805         if (ma->n1 > 0) { // compute LRT
806                 double max0, max1, max2;
807                 for (k = 0, max0 = -1; k <= ma->M; ++k)
808                         if (max0 < ma->z[k]) max0 = ma->z[k];
809                 for (k = 0, max1 = -1; k <= ma->n1 * 2; ++k)
810                         if (max1 < ma->z1[k]) max1 = ma->z1[k];
811                 for (k = 0, max2 = -1; k <= ma->M - ma->n1 * 2; ++k)
812                         if (max2 < ma->z2[k]) max2 = ma->z2[k];
813                 rst->lrt = log(max1 * max2 / max0);
814                 rst->lrt = rst->lrt < 0? 1 : kf_gammaq(.5, rst->lrt);
815         } else rst->lrt = -1.0;
816         rst->cmp[0] = rst->cmp[1] = rst->cmp[2] = rst->p_chi2 = -1.0;
817         if (do_contrast && rst->p_var > 0.5) // skip contrast2() if the locus is a strong non-variant
818                 rst->p_chi2 = contrast2(ma, rst->cmp);
819         return 0;
820 }
821
822 void bcf_p1_dump_afs(bcf_p1aux_t *ma)
823 {
824         int k;
825         fprintf(stderr, "[afs]");
826         for (k = 0; k <= ma->M; ++k)
827                 fprintf(stderr, " %d:%.3lf", k, ma->afs[ma->M - k]);
828         fprintf(stderr, "\n");
829         memset(ma->afs, 0, sizeof(double) * (ma->M + 1));
830 }