6 #define MC_MAX_SUMQ 3000
7 #define MC_MAX_SUMQP 1e-300
12 double *q2p, *pdg; // pdg -> P(D|g)
16 mc_aux_t *mc_init(int n) // FIXME: assuming diploid
20 ma = calloc(1, sizeof(mc_aux_t));
21 ma->n = n; ma->N = 2 * n;
22 ma->q2p = calloc(MC_MAX_SUMQ + 1, sizeof(double));
23 ma->qsum = calloc(4 * ma->n, sizeof(int));
24 ma->bcnt = calloc(4 * ma->n, sizeof(int));
25 ma->pdg = calloc(3 * ma->n, sizeof(double));
26 for (i = 0; i <= MC_MAX_SUMQ; ++i)
27 ma->q2p[i] = pow(10., -i / 10.);
31 void mc_destroy(mc_aux_t *ma)
34 free(ma->qsum); free(ma->bcnt);
35 free(ma->q2p); free(ma->pdg);
40 static void sum_err(int *n, const bam_pileup1_t **plp, mc_aux_t *ma)
43 memset(ma->qsum, 0, sizeof(int) * 4 * ma->n);
44 memset(ma->bcnt, 0, sizeof(int) * 4 * ma->n);
45 for (j = 0; j < ma->n; ++j) {
46 int *qsum = ma->qsum + j * 4;
47 int *bcnt = ma->bcnt + j * 4;
48 for (i = 0; i < n[j]; ++i) {
49 const bam_pileup1_t *p = plp[j] + i;
51 if (p->is_del || (p->b->core.flag&BAM_FUNMAP)) continue;
52 q = bam1_qual(p->b)[p->qpos];
53 if (p->b->core.qual < q) q = p->b->core.qual;
54 if (q < MC_MIN_QUAL) continue; // small qual
55 b = bam_nt16_nt4_table[(int)bam1_seqi(bam1_seq(p->b), p->qpos)];
56 if (b > 3) continue; // N
63 static void set_allele(int ref, mc_aux_t *ma)
65 int i, j, sum[4], tmp;
66 sum[0] = sum[1] = sum[2] = sum[3] = 0;
67 for (i = 0; i < ma->n; ++i)
68 for (j = 0; j < 4; ++j)
69 sum[j] += ma->qsum[i * 4 + j];
70 for (j = 0; j < 4; ++j) sum[j] = sum[j]<<2 | j;
71 for (i = 1; i < 4; ++i) // insertion sort
72 for (j = i; j > 0 && sum[j] < sum[j-1]; --j)
73 tmp = sum[j], sum[j] = sum[j-1], sum[j-1] = tmp;
74 ma->ref = sum[3]&3; ma->alt = sum[2]&3;
75 if (ref == ma->alt) tmp = ma->ref, ma->ref = ma->alt, ma->alt = tmp;
76 // note that ma->ref might not be ref in case of triallele
79 static void cal_pdg(mc_aux_t *ma)
82 for (j = 0; j < ma->n; ++j) {
83 int pi[3], *qsum, *bcnt;
84 double *pdg = ma->pdg + j * 3;
85 qsum = ma->qsum + j * 4;
86 bcnt = ma->bcnt + j * 4;
87 pi[1] = 3 * (bcnt[ma->ref] + bcnt[ma->alt]);
88 pi[0] = qsum[ma->alt];
89 pi[2] = qsum[ma->ref];
90 for (i = 0; i < 3; ++i)
91 pdg[i] = pi[i] < MC_MAX_SUMQ? MC_MAX_SUMQP : ma->q2p[pi[i]];
95 double mc_freq0(int ref, int *n, const bam_pileup1_t **plp, mc_aux_t *ma, int *_ref, int *alt)
102 acnt[0] = acnt[1] = acnt[2] = acnt[3] = 0;
103 for (i = 0; i < ma->n; ++i)
104 for (j = 0; j < 4; ++j)
105 acnt[j] += ma->bcnt[i * 4 + j];
106 f0 = acnt[ma->ref] + acnt[ma->alt] == 0? -1.
107 : (double)acnt[ref] / (acnt[ma->ref] + acnt[ma->alt]);
108 *_ref = ma->ref; *alt = ma->alt;
112 double mc_freq_iter(double f0, mc_aux_t *ma)
116 f3[0] = f0*f0; f3[1] = 2.*f0*(1.-f0); f3[2] = (1.-f0)*(1.-f0);
117 for (i = 0, f = 0.; i < ma->n; ++i) {
119 pdg = ma->pdg + i * 3;
120 for (j = 1, up = 0.; j < 3; ++j)
121 up += j * pdg[j] * f3[j];
122 for (j = 0, dn = 0.; j < 3; ++j)
123 dn += pdg[j] * f3[j];