13 KSTREAM_INIT(gzFile, gzread, 16384)
15 #define MC_MAX_EM_ITER 16
16 #define MC_EM_EPS 1e-5
17 #define MC_DEF_INDEL 0.15
21 unsigned char seq_nt4_table[256] = {
22 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
23 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
24 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 /*'-'*/, 4, 4,
25 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
26 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4,
27 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
28 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4,
29 4, 4, 4, 4, 3, 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 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
36 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
37 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4
40 struct __bcf_p1aux_t {
41 int n, M, n1, is_indel;
42 uint8_t *ploidy; // haploid or diploid ONLY
43 double *q2p, *pdg; // pdg -> P(D|g)
44 double *phi, *phi_indel;
45 double *z, *zswap; // aux for afs
46 double *z1, *z2, *phi1, *phi2; // only calculated when n1 is set
47 double **hg; // hypergeometric distribution
48 double *lf; // log factorial
50 double *afs, *afs1; // afs: accumulative AFS; afs1: site posterior distribution
51 const uint8_t *PL; // point to PL
55 void bcf_p1_indel_prior(bcf_p1aux_t *ma, double x)
58 for (i = 0; i < ma->M; ++i)
59 ma->phi_indel[i] = ma->phi[i] * x;
60 ma->phi_indel[ma->M] = 1. - ma->phi[ma->M] * x;
63 static void init_prior(int type, double theta, int M, double *phi)
66 if (type == MC_PTYPE_COND2) {
67 for (i = 0; i <= M; ++i)
68 phi[i] = 2. * (i + 1) / (M + 1) / (M + 2);
69 } else if (type == MC_PTYPE_FLAT) {
70 for (i = 0; i <= M; ++i)
71 phi[i] = 1. / (M + 1);
74 for (i = 0, sum = 0.; i < M; ++i)
75 sum += (phi[i] = theta / (M - i));
80 void bcf_p1_init_prior(bcf_p1aux_t *ma, int type, double theta)
82 init_prior(type, theta, ma->M, ma->phi);
83 bcf_p1_indel_prior(ma, MC_DEF_INDEL);
86 void bcf_p1_init_subprior(bcf_p1aux_t *ma, int type, double theta)
88 if (ma->n1 <= 0 || ma->n1 >= ma->M) return;
89 init_prior(type, theta, 2*ma->n1, ma->phi1);
90 init_prior(type, theta, 2*(ma->n - ma->n1), ma->phi2);
93 int bcf_p1_read_prior(bcf_p1aux_t *ma, const char *fn)
100 memset(&s, 0, sizeof(kstring_t));
101 fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r");
103 memset(ma->phi, 0, sizeof(double) * (ma->M + 1));
104 while (ks_getuntil(ks, '\n', &s, &dret) >= 0) {
105 if (strstr(s.s, "[afs] ") == s.s) {
107 for (k = 0; k <= ma->M; ++k) {
110 x = strtol(p, &p, 10);
111 if (x != k && (errno == EINVAL || errno == ERANGE)) return -1;
114 if (y == 0. && (errno == EINVAL || errno == ERANGE)) return -1;
115 ma->phi[ma->M - k] += y;
122 for (sum = 0., k = 0; k <= ma->M; ++k) sum += ma->phi[k];
123 fprintf(stderr, "[prior]");
124 for (k = 0; k <= ma->M; ++k) ma->phi[k] /= sum;
125 for (k = 0; k <= ma->M; ++k) fprintf(stderr, " %d:%.3lg", k, ma->phi[ma->M - k]);
127 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));
128 fprintf(stderr, "[%s] heterozygosity=%lf, ", __func__, (double)sum);
129 for (sum = 0., k = 1; k <= ma->M; ++k) sum += k * ma->phi[ma->M - k] / ma->M;
130 fprintf(stderr, "theta=%lf\n", (double)sum);
131 bcf_p1_indel_prior(ma, MC_DEF_INDEL);
135 bcf_p1aux_t *bcf_p1_init(int n, uint8_t *ploidy)
139 ma = calloc(1, sizeof(bcf_p1aux_t));
141 ma->n = n; ma->M = 2 * n;
143 ma->ploidy = malloc(n);
144 memcpy(ma->ploidy, ploidy, n);
145 for (i = 0, ma->M = 0; i < n; ++i) ma->M += ploidy[i];
146 if (ma->M == 2 * n) {
151 ma->q2p = calloc(256, sizeof(double));
152 ma->pdg = calloc(3 * ma->n, sizeof(double));
153 ma->phi = calloc(ma->M + 1, sizeof(double));
154 ma->phi_indel = calloc(ma->M + 1, sizeof(double));
155 ma->phi1 = calloc(ma->M + 1, sizeof(double));
156 ma->phi2 = calloc(ma->M + 1, sizeof(double));
157 ma->z = calloc(ma->M + 1, sizeof(double));
158 ma->zswap = calloc(ma->M + 1, sizeof(double));
159 ma->z1 = calloc(ma->M + 1, sizeof(double)); // actually we do not need this large
160 ma->z2 = calloc(ma->M + 1, sizeof(double));
161 ma->afs = calloc(ma->M + 1, sizeof(double));
162 ma->afs1 = calloc(ma->M + 1, sizeof(double));
163 ma->lf = calloc(ma->M + 1, sizeof(double));
164 for (i = 0; i < 256; ++i)
165 ma->q2p[i] = pow(10., -i / 10.);
166 for (i = 0; i <= ma->M; ++i) ma->lf[i] = lgamma(i + 1);
167 bcf_p1_init_prior(ma, MC_PTYPE_FULL, 1e-3); // the simplest prior
171 int bcf_p1_get_M(bcf_p1aux_t *b) { return b->M; }
173 int bcf_p1_set_n1(bcf_p1aux_t *b, int n1)
175 if (n1 == 0 || n1 >= b->n) return -1;
176 if (b->M != b->n * 2) {
177 fprintf(stderr, "[%s] unable to set `n1' when there are haploid samples.\n", __func__);
184 void bcf_p1_set_ploidy(bcf1_t *b, bcf_p1aux_t *ma)
186 // bcf_p1aux_t fields are not visible outside of prob1.c, hence this wrapper.
187 // Ideally, this should set ploidy per site to allow pseudo-autosomal regions
188 b->ploidy = ma->ploidy;
191 void bcf_p1_destroy(bcf_p1aux_t *ma)
196 if (ma->hg && ma->n1 > 0) {
197 for (k = 0; k <= 2*ma->n1; ++k) free(ma->hg[k]);
200 free(ma->ploidy); free(ma->q2p); free(ma->pdg);
201 free(ma->phi); free(ma->phi_indel); free(ma->phi1); free(ma->phi2);
202 free(ma->z); free(ma->zswap); free(ma->z1); free(ma->z2);
203 free(ma->afs); free(ma->afs1);
208 extern double kf_gammap(double s, double z);
209 int test16(bcf1_t *b, anno16_t *a);
211 int call_multiallelic_gt(bcf1_t *b, bcf_p1aux_t *ma, double threshold)
215 for (p=b->alt; *p; p++)
217 if ( *p=='X' || p[0]=='.' ) break;
218 if ( p[0]==',' ) nals++;
220 if ( b->alt[0] && !*p ) nals++;
222 if ( nals==1 ) return 1;
226 if ( *b->ref=='N' ) return 0;
227 fprintf(stderr,"Not ready for this, more than 4 alleles at %d: %s, %s\n", b->pos+1, b->ref,b->alt);
231 // find PL and DP FORMAT indexes
235 for (i = 0; i < b->n_gi; ++i)
237 if (b->gi[i].fmt == bcf_str2int("PL", 2))
239 pl = (uint8_t*)b->gi[i].data;
242 if (b->gi[i].fmt == bcf_str2int("DP", 2)) idp=i;
244 if ( !pl ) return -1;
246 assert(ma->q2p[0] == 1);
249 int npdg = nals*(nals+1)/2;
251 _pdg = pdg = malloc(sizeof(double)*ma->n*npdg);
252 for (i=0; i<ma->n; i++)
256 for (j=0; j<npdg; j++)
258 //_pdg[j] = pow(10,-0.1*pl[j]);
259 _pdg[j] = ma->q2p[pl[j]];
263 for (j=0; j<npdg; j++) _pdg[j] /= sum;
268 if ((p = strstr(b->info, "QS=")) == 0) { fprintf(stderr,"INFO/QS is required with -m, exiting\n"); exit(1); }
270 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); }
273 // Calculate the most likely combination of alleles
274 int ia,ib,ic, max_als=0, max_als2=0;
275 double ref_lk = 0, max_lk = INT_MIN, max_lk2 = INT_MIN, lk_sum = INT_MIN;
276 for (ia=0; ia<nals; ia++)
279 int iaa = (ia+1)*(ia+2)/2-1;
281 for (isample=0; isample<ma->n; isample++)
283 double *p = pdg + isample*npdg;
284 // assert( log(p[iaa]) <= 0 );
285 lk_tot += log(p[iaa]);
287 if ( ia==0 ) ref_lk = lk_tot;
288 if ( max_lk<lk_tot ) { max_lk2 = max_lk; max_als2 = max_als; max_lk = lk_tot; max_als = 1<<ia; }
289 else if ( max_lk2<lk_tot ) { max_lk2 = lk_tot; max_als2 = 1<<ia; }
290 lk_sum = lk_tot>lk_sum ? lk_tot + log(1+exp(lk_sum-lk_tot)) : lk_sum + log(1+exp(lk_tot-lk_sum));
294 for (ia=0; ia<nals; ia++)
296 if ( qsum[ia]==0 ) continue;
297 int iaa = (ia+1)*(ia+2)/2-1;
298 for (ib=0; ib<ia; ib++)
300 if ( qsum[ib]==0 ) continue;
302 double fa = qsum[ia]/(qsum[ia]+qsum[ib]);
303 double fb = qsum[ib]/(qsum[ia]+qsum[ib]);
304 double fab = 2*fa*fb; fa *= fa; fb *= fb;
305 int isample, ibb = (ib+1)*(ib+2)/2-1, iab = iaa - ia + ib;
306 for (isample=0; isample<ma->n; isample++)
308 double *p = pdg + isample*npdg;
309 //assert( log(fa*p[iaa] + fb*p[ibb] + fab*p[iab]) <= 0 );
310 if ( b->ploidy && b->ploidy[isample]==1 )
311 lk_tot += log(fa*p[iaa] + fb*p[ibb]);
313 lk_tot += log(fa*p[iaa] + fb*p[ibb] + fab*p[iab]);
315 if ( max_lk<lk_tot ) { max_lk2 = max_lk; max_als2 = max_als; max_lk = lk_tot; max_als = 1<<ia|1<<ib; }
316 else if ( max_lk2<lk_tot ) { max_lk2 = lk_tot; max_als2 = 1<<ia|1<<ib; }
317 lk_sum = lk_tot>lk_sum ? lk_tot + log(1+exp(lk_sum-lk_tot)) : lk_sum + log(1+exp(lk_tot-lk_sum));
323 for (ia=0; ia<nals; ia++)
325 if ( qsum[ia]==0 ) continue;
326 int iaa = (ia+1)*(ia+2)/2-1;
327 for (ib=0; ib<ia; ib++)
329 if ( qsum[ib]==0 ) continue;
330 int ibb = (ib+1)*(ib+2)/2-1;
331 int iab = iaa - ia + ib;
332 for (ic=0; ic<ib; ic++)
334 if ( qsum[ic]==0 ) continue;
336 double fa = qsum[ia]/(qsum[ia]+qsum[ib]+qsum[ic]);
337 double fb = qsum[ib]/(qsum[ia]+qsum[ib]+qsum[ic]);
338 double fc = qsum[ic]/(qsum[ia]+qsum[ib]+qsum[ic]);
339 double fab = 2*fa*fb, fac = 2*fa*fc, fbc = 2*fb*fc; fa *= fa; fb *= fb; fc *= fc;
340 int isample, icc = (ic+1)*(ic+2)/2-1;
341 int iac = iaa - ia + ic, ibc = ibb - ib + ic;
342 for (isample=0; isample<ma->n; isample++)
344 double *p = pdg + isample*npdg;
345 //assert( log(fa*p[iaa] + fb*p[ibb] + fc*p[icc] + fab*p[iab] + fac*p[iac] + fbc*p[ibc]) <= 0 );
346 if ( b->ploidy && b->ploidy[isample]==1 )
347 lk_tot += log(fa*p[iaa] + fb*p[ibb] + fc*p[icc]);
349 lk_tot += log(fa*p[iaa] + fb*p[ibb] + fc*p[icc] + fab*p[iab] + fac*p[iac] + fbc*p[ibc]);
351 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; }
352 else if ( max_lk2<lk_tot ) { max_lk2 = lk_tot; max_als2 = 1<<ia|1<<ib|1<<ic; }
353 lk_sum = lk_tot>lk_sum ? lk_tot + log(1+exp(lk_sum-lk_tot)) : lk_sum + log(1+exp(lk_tot-lk_sum));
359 // Should we add another allele, does it increase the likelihood significantly?
361 for (i=0; i<nals; i++) if ( max_als&1<<i) n1++;
362 for (i=0; i<nals; i++) if ( max_als2&1<<i) n2++;
363 if ( n2<n1 && kf_gammap(1,2.0*(max_lk-max_lk2))<threshold )
369 // Get the BCF record ready for GT and GQ
371 int old_n_gi = b->n_gi;
372 s.m = b->m_str; s.l = b->l_str - 1; s.s = b->str;
373 kputs(":GT:GQ", &s); kputc('\0', &s);
374 b->m_str = s.m; b->l_str = s.l; b->str = s.s;
378 int isample, gts=0, ac[4] = {0,0,0,0};
379 for (isample = 0; isample < b->n_smpl; isample++)
381 int ploidy = b->ploidy ? b->ploidy[isample] : 2;
382 double *p = pdg + isample*npdg;
384 double lk = 0, lk_sum=0;
385 for (ia=0; ia<nals; ia++)
387 if ( !(max_als&1<<ia) ) continue;
388 int iaa = (ia+1)*(ia+2)/2-1;
389 double _lk = p[iaa]*qsum[ia]*qsum[ia];
390 if ( _lk > lk ) { lk = _lk; als = ia<<3 | ia; }
395 for (ia=0; ia<nals; ia++)
397 if ( !(max_als&1<<ia) ) continue;
398 int iaa = (ia+1)*(ia+2)/2-1;
399 for (ib=0; ib<ia; ib++)
401 if ( !(max_als&1<<ib) ) continue;
402 int iab = iaa - ia + ib;
403 double _lk = 2*qsum[ia]*qsum[ib]*p[iab];
404 if ( _lk > lk ) { lk = _lk; als = ib<<3 | ia; }
409 lk = -log(1-lk/lk_sum)/0.2302585;
410 if ( idp>=0 && ((uint16_t*)b->gi[idp].data)[isample]==0 )
412 ((uint8_t*)b->gi[old_n_gi].data)[isample] = 1<<7;
413 ((uint8_t*)b->gi[old_n_gi+1].data)[isample] = 0;
416 ((uint8_t*)b->gi[old_n_gi].data)[isample] = als;
417 ((uint8_t*)b->gi[old_n_gi+1].data)[isample] = lk<100 ? (int)lk : 99;
419 gts |= 1<<(als>>3&7) | 1<<(als&7);
423 bcf_fit_alt(b,max_als);
426 // Prepare BCF for output: ref, alt, filter, info, format
427 memset(&s, 0, sizeof(kstring_t)); kputc('\0', &s);
428 kputs(b->ref, &s); kputc('\0', &s);
429 kputs(b->alt, &s); kputc('\0', &s); kputc('\0', &s);
432 for (i=0; i<nals; i++)
435 if ( i>0 && ac[i] ) nalts++;
437 ksprintf(&s, "AN=%d;", an);
441 for (i=1; i<nals; i++)
443 if ( !(gts&1<<i) ) continue;
445 ksprintf(&s,"%d", ac[i]);
446 if ( nalts>0 ) kputc(',', &s);
452 int has_I16 = test16(b, &a) >= 0? 1 : 0;
455 if ( a.is_tested) ksprintf(&s, ";PV4=%.2g,%.2g,%.2g,%.2g", a.p[0], a.p[1], a.p[2], a.p[3]);
456 ksprintf(&s, ";DP4=%d,%d,%d,%d;MQ=%d", a.d[0], a.d[1], a.d[2], a.d[3], a.mq);
462 kputs(b->fmt, &s); kputc('\0', &s);
464 b->m_str = s.m; b->l_str = s.l; b->str = s.s;
465 b->qual = gts>1 ? -4.343*(ref_lk - lk_sum) : -4.343*(max_lk - lk_sum);
466 if ( b->qual>999 ) b->qual = 999;
474 static int cal_pdg(const bcf1_t *b, bcf_p1aux_t *ma)
478 p = alloca(b->n_alleles * sizeof(long));
479 memset(p, 0, sizeof(long) * b->n_alleles);
480 for (j = 0; j < ma->n; ++j) {
481 const uint8_t *pi = ma->PL + j * ma->PL_len;
482 double *pdg = ma->pdg + j * 3;
483 pdg[0] = ma->q2p[pi[2]]; pdg[1] = ma->q2p[pi[1]]; pdg[2] = ma->q2p[pi[0]];
484 for (i = 0; i < b->n_alleles; ++i)
485 p[i] += (int)pi[(i+1)*(i+2)/2-1];
487 for (i = 0; i < b->n_alleles; ++i) p[i] = p[i]<<4 | i;
488 for (i = 1; i < b->n_alleles; ++i) // insertion sort
489 for (j = i; j > 0 && p[j] < p[j-1]; --j)
490 tmp = p[j], p[j] = p[j-1], p[j-1] = tmp;
491 for (i = b->n_alleles - 1; i >= 0; --i)
492 if ((p[i]&0xf) == 0) break;
497 int bcf_p1_call_gt(const bcf_p1aux_t *ma, double f0, int k)
500 double max, f3[3], *pdg = ma->pdg + k * 3;
501 int q, i, max_i, ploidy;
502 ploidy = ma->ploidy? ma->ploidy[k] : 2;
504 f3[0] = (1.-f0)*(1.-f0); f3[1] = 2.*f0*(1.-f0); f3[2] = f0*f0;
506 f3[0] = 1. - f0; f3[1] = 0; f3[2] = f0;
508 for (i = 0, sum = 0.; i < 3; ++i)
509 sum += (g[i] = pdg[i] * f3[i]);
510 for (i = 0, max = -1., max_i = 0; i < 3; ++i) {
512 if (g[i] > max) max = g[i], max_i = i;
515 if (max < 1e-308) max = 1e-308;
516 q = (int)(-4.343 * log(max) + .499);
523 static void mc_cal_y_core(bcf_p1aux_t *ma, int beg)
525 double *z[2], *tmp, *pdg;
526 int _j, last_min, last_max;
527 assert(beg == 0 || ma->M == ma->n*2);
531 memset(z[0], 0, sizeof(double) * (ma->M + 1));
532 memset(z[1], 0, sizeof(double) * (ma->M + 1));
534 last_min = last_max = 0;
536 if (ma->M == ma->n * 2) {
538 for (_j = beg; _j < ma->n; ++_j) {
539 int k, j = _j - beg, _min = last_min, _max = last_max, M0;
542 pdg = ma->pdg + _j * 3;
543 p[0] = pdg[0]; p[1] = 2. * pdg[1]; p[2] = pdg[2];
544 for (; _min < _max && z[0][_min] < TINY; ++_min) z[0][_min] = z[1][_min] = 0.;
545 for (; _max > _min && z[0][_max] < TINY; --_max) z[0][_max] = z[1][_max] = 0.;
547 if (_min == 0) k = 0, z[1][k] = (M0-k+1) * (M0-k+2) * p[0] * z[0][k];
548 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];
549 for (k = _min < 2? 2 : _min; k <= _max; ++k)
550 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];
551 for (k = _min, sum = 0.; k <= _max; ++k) sum += z[1][k];
552 ma->t += log(sum / (M * (M - 1.)));
553 for (k = _min; k <= _max; ++k) z[1][k] /= sum;
554 if (_min >= 1) z[1][_min-1] = 0.;
555 if (_min >= 2) z[1][_min-2] = 0.;
556 if (j < ma->n - 1) z[1][_max+1] = z[1][_max+2] = 0.;
557 if (_j == ma->n1 - 1) { // set pop1; ma->n1==-1 when unset
559 memcpy(ma->z1, z[1], sizeof(double) * (ma->n1 * 2 + 1));
561 tmp = z[0]; z[0] = z[1]; z[1] = tmp;
562 last_min = _min; last_max = _max;
564 //for (_j = 0; _j < last_min; ++_j) z[0][_j] = 0.; // TODO: are these necessary?
565 //for (_j = last_max + 1; _j < ma->M; ++_j) z[0][_j] = 0.;
566 } else { // this block is very similar to the block above; these two might be merged in future
568 for (j = 0; j < ma->n; ++j) {
569 int k, M0, _min = last_min, _max = last_max;
571 pdg = ma->pdg + j * 3;
572 for (; _min < _max && z[0][_min] < TINY; ++_min) z[0][_min] = z[1][_min] = 0.;
573 for (; _max > _min && z[0][_max] < TINY; --_max) z[0][_max] = z[1][_max] = 0.;
576 if (ma->ploidy[j] == 1) {
577 p[0] = pdg[0]; p[1] = pdg[2];
579 if (_min == 0) k = 0, z[1][k] = (M0+1-k) * p[0] * z[0][k];
580 for (k = _min < 1? 1 : _min; k <= _max; ++k)
581 z[1][k] = (M0+1-k) * p[0] * z[0][k] + k * p[1] * z[0][k-1];
582 for (k = _min, sum = 0.; k <= _max; ++k) sum += z[1][k];
583 ma->t += log(sum / M);
584 for (k = _min; k <= _max; ++k) z[1][k] /= sum;
585 if (_min >= 1) z[1][_min-1] = 0.;
586 if (j < ma->n - 1) z[1][_max+1] = 0.;
587 } else if (ma->ploidy[j] == 2) {
588 p[0] = pdg[0]; p[1] = 2 * pdg[1]; p[2] = pdg[2];
590 if (_min == 0) k = 0, z[1][k] = (M0-k+1) * (M0-k+2) * p[0] * z[0][k];
591 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];
592 for (k = _min < 2? 2 : _min; k <= _max; ++k)
593 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];
594 for (k = _min, sum = 0.; k <= _max; ++k) sum += z[1][k];
595 ma->t += log(sum / (M * (M - 1.)));
596 for (k = _min; k <= _max; ++k) z[1][k] /= sum;
597 if (_min >= 1) z[1][_min-1] = 0.;
598 if (_min >= 2) z[1][_min-2] = 0.;
599 if (j < ma->n - 1) z[1][_max+1] = z[1][_max+2] = 0.;
601 tmp = z[0]; z[0] = z[1]; z[1] = tmp;
602 last_min = _min; last_max = _max;
605 if (z[0] != ma->z) memcpy(ma->z, z[0], sizeof(double) * (ma->M + 1));
607 gzwrite(bcf_p1_fp_lk, ma->z, sizeof(double) * (ma->M + 1));
610 static void mc_cal_y(bcf_p1aux_t *ma)
612 if (ma->n1 > 0 && ma->n1 < ma->n && ma->M == ma->n * 2) { // NB: ma->n1 is ineffective when there are haploid samples
615 memset(ma->z1, 0, sizeof(double) * (2 * ma->n1 + 1));
616 memset(ma->z2, 0, sizeof(double) * (2 * (ma->n - ma->n1) + 1));
617 ma->t1 = ma->t2 = 0.;
618 mc_cal_y_core(ma, ma->n1);
620 memcpy(ma->z2, ma->z, sizeof(double) * (2 * (ma->n - ma->n1) + 1));
621 mc_cal_y_core(ma, 0);
623 x = expl(ma->t - (ma->t1 + ma->t2));
624 for (k = 0; k <= ma->M; ++k) ma->z[k] *= x;
625 } else mc_cal_y_core(ma, 0);
628 #define CONTRAST_TINY 1e-30
630 extern double kf_gammaq(double s, double z); // incomplete gamma function for chi^2 test
632 static inline double chi2_test(int a, int b, int c, int d)
635 x = (double)(a+b) * (c+d) * (b+d) * (a+c);
636 if (x == 0.) return 1;
638 return kf_gammaq(.5, .5 * z * z * (a+b+c+d) / x);
641 // chi2=(a+b+c+d)(ad-bc)^2/[(a+b)(c+d)(a+c)(b+d)]
642 static inline double contrast2_aux(const bcf_p1aux_t *p1, double sum, int k1, int k2, double x[3])
644 double p = p1->phi[k1+k2] * p1->z1[k1] * p1->z2[k2] / sum * p1->hg[k1][k2];
645 int n1 = p1->n1, n2 = p1->n - p1->n1;
646 if (p < CONTRAST_TINY) return -1;
647 if (.5*k1/n1 < .5*k2/n2) x[1] += p;
648 else if (.5*k1/n1 > .5*k2/n2) x[2] += p;
650 return p * chi2_test(k1, k2, (n1<<1) - k1, (n2<<1) - k2);
653 static double contrast2(bcf_p1aux_t *p1, double ret[3])
655 int k, k1, k2, k10, k20, n1, n2;
658 n1 = p1->n1; n2 = p1->n - p1->n1;
659 if (n1 <= 0 || n2 <= 0) return 0.;
660 if (p1->hg == 0) { // initialize the hypergeometric distribution
661 /* NB: the hg matrix may take a lot of memory when there are many samples. There is a way
662 to avoid precomputing this matrix, but it is slower and quite intricate. The following
663 computation in this block can be accelerated with a similar strategy, but perhaps this
664 is not a serious concern for now. */
665 double tmp = lgamma(2*(n1+n2)+1) - (lgamma(2*n1+1) + lgamma(2*n2+1));
666 p1->hg = calloc(2*n1+1, sizeof(void*));
667 for (k1 = 0; k1 <= 2*n1; ++k1) {
668 p1->hg[k1] = calloc(2*n2+1, sizeof(double));
669 for (k2 = 0; k2 <= 2*n2; ++k2)
670 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));
674 long double suml = 0;
675 for (k = 0; k <= p1->M; ++k) suml += p1->phi[k] * p1->z[k];
678 { // get the max k1 and k2
681 for (k = 0, max = 0, max_k = -1; k <= 2*n1; ++k) {
682 double x = p1->phi1[k] * p1->z1[k];
683 if (x > max) max = x, max_k = k;
686 for (k = 0, max = 0, max_k = -1; k <= 2*n2; ++k) {
687 double x = p1->phi2[k] * p1->z2[k];
688 if (x > max) max = x, max_k = k;
692 { // 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.
694 long double z = 0., L[2];
695 x[0] = x[1] = x[2] = 0; L[0] = L[1] = 0;
696 for (k1 = k10; k1 >= 0; --k1) {
697 for (k2 = k20; k2 >= 0; --k2) {
698 if ((y = contrast2_aux(p1, sum, k1, k2, x)) < 0) break;
701 for (k2 = k20 + 1; k2 <= 2*n2; ++k2) {
702 if ((y = contrast2_aux(p1, sum, k1, k2, x)) < 0) break;
706 ret[0] = x[0]; ret[1] = x[1]; ret[2] = x[2];
707 x[0] = x[1] = x[2] = 0;
708 for (k1 = k10 + 1; k1 <= 2*n1; ++k1) {
709 for (k2 = k20; k2 >= 0; --k2) {
710 if ((y = contrast2_aux(p1, sum, k1, k2, x)) < 0) break;
713 for (k2 = k20 + 1; k2 <= 2*n2; ++k2) {
714 if ((y = contrast2_aux(p1, sum, k1, k2, x)) < 0) break;
718 ret[0] += x[0]; ret[1] += x[1]; ret[2] += x[2];
719 if (ret[0] + ret[1] + ret[2] < 0.95) { // in case of bad things happened
720 ret[0] = ret[1] = ret[2] = 0; L[0] = L[1] = 0;
721 for (k1 = 0, z = 0.; k1 <= 2*n1; ++k1)
722 for (k2 = 0; k2 <= 2*n2; ++k2)
723 if ((y = contrast2_aux(p1, sum, k1, k2, ret)) >= 0) z += y;
724 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...
725 z = 1.0, ret[0] = ret[1] = ret[2] = 1./3;
731 static double mc_cal_afs(bcf_p1aux_t *ma, double *p_ref_folded, double *p_var_folded)
734 long double sum = 0., sum2;
735 double *phi = ma->is_indel? ma->phi_indel : ma->phi;
736 memset(ma->afs1, 0, sizeof(double) * (ma->M + 1));
739 for (k = 0, sum = 0.; k <= ma->M; ++k)
740 sum += (long double)phi[k] * ma->z[k];
741 for (k = 0; k <= ma->M; ++k) {
742 ma->afs1[k] = phi[k] * ma->z[k] / sum;
743 if (isnan(ma->afs1[k]) || isinf(ma->afs1[k])) return -1.;
745 // compute folded variant probability
746 for (k = 0, sum = 0.; k <= ma->M; ++k)
747 sum += (long double)(phi[k] + phi[ma->M - k]) / 2. * ma->z[k];
748 for (k = 1, sum2 = 0.; k < ma->M; ++k)
749 sum2 += (long double)(phi[k] + phi[ma->M - k]) / 2. * ma->z[k];
750 *p_var_folded = sum2 / sum;
751 *p_ref_folded = (phi[k] + phi[ma->M - k]) / 2. * (ma->z[ma->M] + ma->z[0]) / sum;
752 // the expected frequency
753 for (k = 0, sum = 0.; k <= ma->M; ++k) {
754 ma->afs[k] += ma->afs1[k];
755 sum += k * ma->afs1[k];
760 int bcf_p1_cal(const bcf1_t *b, int do_contrast, bcf_p1aux_t *ma, bcf_p1rst_t *rst)
763 long double sum = 0.;
764 ma->is_indel = bcf_is_indel(b);
767 for (i = 0; i < b->n_gi; ++i) {
768 if (b->gi[i].fmt == bcf_str2int("PL", 2)) {
769 ma->PL = (uint8_t*)b->gi[i].data;
770 ma->PL_len = b->gi[i].len;
774 if (i == b->n_gi) return -1; // no PL
775 if (b->n_alleles < 2) return -1; // FIXME: find a better solution
777 rst->rank0 = cal_pdg(b, ma);
778 rst->f_exp = mc_cal_afs(ma, &rst->p_ref_folded, &rst->p_var_folded);
779 rst->p_ref = ma->afs1[ma->M];
780 for (k = 0, sum = 0.; k < ma->M; ++k)
782 rst->p_var = (double)sum;
783 { // compute the allele count
786 for (k = 0; k <= ma->M; ++k)
787 if (max < ma->z[k]) max = ma->z[k], rst->ac = k;
788 rst->ac = ma->M - rst->ac;
790 // calculate f_flat and f_em
791 for (k = 0, sum = 0.; k <= ma->M; ++k)
792 sum += (long double)ma->z[k];
794 for (k = 0; k <= ma->M; ++k) {
795 double p = ma->z[k] / sum;
796 rst->f_flat += k * p;
798 rst->f_flat /= ma->M;
799 { // estimate equal-tail credible interval (95% level)
802 for (i = 0, p = 0.; i <= ma->M; ++i)
803 if (p + ma->afs1[i] > 0.025) break;
804 else p += ma->afs1[i];
806 for (i = ma->M, p = 0.; i >= 0; --i)
807 if (p + ma->afs1[i] > 0.025) break;
808 else p += ma->afs1[i];
810 rst->cil = (double)(ma->M - h) / ma->M; rst->cih = (double)(ma->M - l) / ma->M;
812 if (ma->n1 > 0) { // compute LRT
813 double max0, max1, max2;
814 for (k = 0, max0 = -1; k <= ma->M; ++k)
815 if (max0 < ma->z[k]) max0 = ma->z[k];
816 for (k = 0, max1 = -1; k <= ma->n1 * 2; ++k)
817 if (max1 < ma->z1[k]) max1 = ma->z1[k];
818 for (k = 0, max2 = -1; k <= ma->M - ma->n1 * 2; ++k)
819 if (max2 < ma->z2[k]) max2 = ma->z2[k];
820 rst->lrt = log(max1 * max2 / max0);
821 rst->lrt = rst->lrt < 0? 1 : kf_gammaq(.5, rst->lrt);
822 } else rst->lrt = -1.0;
823 rst->cmp[0] = rst->cmp[1] = rst->cmp[2] = rst->p_chi2 = -1.0;
824 if (do_contrast && rst->p_var > 0.5) // skip contrast2() if the locus is a strong non-variant
825 rst->p_chi2 = contrast2(ma, rst->cmp);
829 void bcf_p1_dump_afs(bcf_p1aux_t *ma)
832 fprintf(stderr, "[afs]");
833 for (k = 0; k <= ma->M; ++k)
834 fprintf(stderr, " %d:%.3lf", k, ma->afs[ma->M - k]);
835 fprintf(stderr, "\n");
836 memset(ma->afs, 0, sizeof(double) * (ma->M + 1));