+
+int mc_call_gt(const mc_aux_t *ma, double f0, int k)
+{
+ double sum, g[3];
+ double max, f3[3], *pdg = ma->pdg + k * 3;
+ int q, i, max_i;
+ f3[0] = (1.-f0)*(1.-f0); f3[1] = 2.*f0*(1.-f0); f3[2] = f0*f0;
+ for (i = 0, sum = 0.; i < 3; ++i)
+ sum += (g[i] = pdg[i] * f3[i]);
+ for (i = 0, max = -1., max_i = 0; i < 3; ++i) {
+ g[i] /= sum;
+ if (g[i] > max) max = g[i], max_i = i;
+ }
+ max = 1. - max;
+ if (max < 1e-308) max = 1e-308;
+ q = (int)(-3.434 * log(max) + .499);
+ if (q > 99) q = 99;
+ return q<<2|max_i;
+}
+
+static void mc_cal_z(mc_aux_t *ma)
+{
+ double *z[2], *tmp, *pdg;
+ int i, j;
+ z[0] = ma->z;
+ z[1] = ma->zswap;
+ pdg = ma->pdg;
+ z[0][0] = 1.; z[0][1] = z[0][2] = 0.;
+ for (j = 0; j < ma->n; ++j) {
+ int max = (j + 1) * 2;
+ double p[3];
+ pdg = ma->pdg + j * 3;
+ p[0] = pdg[0]; p[1] = 2. * pdg[1]; p[2] = pdg[2];
+ z[1][0] = p[0] * z[0][0];
+ z[1][1] = p[0] * z[0][1] + p[1] * z[0][0];
+ for (i = 2; i <= max; ++i)
+ z[1][i] = p[0] * z[0][i] + p[1] * z[0][i-1] + p[2] * z[0][i-2];
+ if (j < ma->n - 1) z[1][max+1] = z[1][max+2] = 0.;
+ tmp = z[0]; z[0] = z[1]; z[1] = tmp;
+ }
+ if (z[0] != ma->z) memcpy(ma->z, z[0], sizeof(double) * (2 * ma->n + 1));
+}
+
+static double mc_add_afs(mc_aux_t *ma)
+{
+ int k, l;
+ double sum = 0., avg = 0.;
+ memset(ma->afs1, 0, sizeof(double) * (ma->M + 1));
+ mc_cal_z(ma);
+ for (k = 0; k <= ma->M; ++k) {
+ for (l = 0, sum = 0.; l <= ma->M; ++l)
+ sum += ma->phi[l] * ma->z[l];
+ ma->afs1[k] = ma->phi[k] * ma->z[k] / sum;
+ }
+ for (k = 0; k <= ma->M; ++k)
+ if (isnan(ma->afs1[k]) || isinf(ma->afs1[k])) return -1.;
+ for (k = 0, sum = avg = 0.; k <= ma->M; ++k) {
+ ma->afs[k] += ma->afs1[k];
+ sum += ma->afs1[k];
+ avg += k * ma->afs1[k];
+ }
+// for (k = 0; k <= ma->M; ++k) printf("^%lg:%lg:%lg ", ma->z[k], ma->phi[k], ma->afs1[k]);
+ return avg / ma->M;
+}
+
+int mc_cal(int ref, int *n, const bam_pileup1_t **plp, mc_aux_t *ma, mc_rst_t *rst, int level)
+{
+ int i, tot;
+ memset(rst, 0, sizeof(mc_rst_t));
+ rst->f_em = rst->f_exp = -1.; rst->ref = rst->alt = -1;
+ // precalculation
+ tot = sum_err(n, plp, ma);
+ if (tot == 0) return 0; // no good bases
+ set_allele(ref, ma);
+ cal_pdg(ma);
+ // set ref/major allele
+ rst->ref = ma->ref; rst->alt = ma->alt; rst->alt2 = ma->alt2;
+ // calculate naive and Nielsen's freq
+ rst->f_naive = mc_freq0(ma, &rst->f_nielsen);
+ { // calculate f_em
+ double flast = rst->f_naive;
+ for (i = 0; i < MC_MAX_EM_ITER; ++i) {
+ rst->f_em = mc_freq_iter(flast, ma);
+ if (fabs(rst->f_em - flast) < MC_EM_EPS) break;
+ flast = rst->f_em;
+ }
+ }
+ if (level >= 2) {
+ rst->f_exp = mc_add_afs(ma);
+ rst->p_ref = ma->afs1[ma->M];
+ }
+ return tot;
+}
+
+void mc_dump_afs(mc_aux_t *ma)
+{
+ int k;
+ fprintf(stderr, "[afs]");
+ for (k = 0; k <= ma->M; ++k)
+ fprintf(stderr, " %d:%.3lf", k, ma->afs[ma->M - k]);
+ fprintf(stderr, "\n");
+ memset(ma->afs, 0, sizeof(double) * (ma->M + 1));
+}