]> git.donarmstrong.com Git - samtools.git/blobdiff - bam2bcf.c
works
[samtools.git] / bam2bcf.c
index d69c771da80ef14ed925e549548f988a766ae680..a51a406f249c05834b0d8e20f49403d5ed29a3b6 100644 (file)
--- a/bam2bcf.c
+++ b/bam2bcf.c
 #include "bam.h"
 #include "kstring.h"
 #include "bam2bcf.h"
+#include "errmod.h"
 #include "bcftools/bcf.h"
 
 extern void ks_introsort_uint32_t(size_t n, uint32_t a[]);
 
 #define CALL_ETA 0.03f
 #define CALL_MAX 256
-#define CALL_DEFTHETA 0.85f
+#define CALL_DEFTHETA 0.83f
+#define DEF_MAPQ 20
 
-struct __bcf_callaux_t {
-       int max_info, capQ;
-       double *fk;
-       uint32_t *info;
-};
+#define CAP_DIST 25
 
-bcf_callaux_t *bcf_call_init(double theta)
+bcf_callaux_t *bcf_call_init(double theta, int min_baseQ)
 {
        bcf_callaux_t *bca;
-       int n;
        if (theta <= 0.) theta = CALL_DEFTHETA;
        bca = calloc(1, sizeof(bcf_callaux_t));
        bca->capQ = 60;
-       bca->fk = calloc(CALL_MAX, sizeof(double));
-       bca->fk[0] = 1.;
-       for (n = 1; n < CALL_MAX; ++n)
-               bca->fk[n] = theta >= 1.? 1. : pow(theta, n) * (1.0 - CALL_ETA) + CALL_ETA;
-       bca->fk[CALL_MAX-1] = 0.;
+       bca->openQ = 40; bca->extQ = 20; bca->tandemQ = 100;
+       bca->min_baseQ = min_baseQ;
+       bca->e = errmod_init(1. - theta);
+       bca->min_frac = 0.002;
+       bca->min_support = 1;
+    bca->per_sample_flt = 0;
        return bca;
 }
 
 void bcf_call_destroy(bcf_callaux_t *bca)
 {
-       if (bca) {
-               free(bca->info); free(bca->fk); free(bca);
-       }
+       if (bca == 0) return;
+       errmod_destroy(bca->e);
+       free(bca->bases); free(bca->inscns); free(bca);
 }
+/* ref_base is the 4-bit representation of the reference base. It is
+ * negative if we are looking at an indel. */
+int bcf_call_glfgen(int _n, const bam_pileup1_t *pl, int ref_base, bcf_callaux_t *bca, bcf_callret1_t *r)
+{
+    static int *var_pos = NULL, nvar_pos = 0;
+       int i, n, ref4, is_indel, ori_depth = 0;
+       memset(r, 0, sizeof(bcf_callret1_t));
+       if (ref_base >= 0) {
+               ref4 = bam_nt16_nt4_table[ref_base];
+               is_indel = 0;
+       } else ref4 = 4, is_indel = 1;
+       if (_n == 0) return -1;
+       // enlarge the bases array if necessary
+       if (bca->max_bases < _n) {
+               bca->max_bases = _n;
+               kroundup32(bca->max_bases);
+               bca->bases = (uint16_t*)realloc(bca->bases, 2 * bca->max_bases);
+       }
+       // fill the bases array
+       for (i = n = r->n_supp = 0; i < _n; ++i) {
+               const bam_pileup1_t *p = pl + i;
+               int q, b, mapQ, baseQ, is_diff, min_dist, seqQ;
+               // set base
+               if (p->is_del || p->is_refskip || (p->b->core.flag&BAM_FUNMAP)) continue;
+               ++ori_depth;
+               baseQ = q = is_indel? p->aux&0xff : (int)bam1_qual(p->b)[p->qpos]; // base/indel quality
+               seqQ = is_indel? (p->aux>>8&0xff) : 99;
+               if (q < bca->min_baseQ) continue;
+               if (q > seqQ) q = seqQ;
+               mapQ = p->b->core.qual < 255? p->b->core.qual : DEF_MAPQ; // special case for mapQ==255
+               mapQ = mapQ < bca->capQ? mapQ : bca->capQ;
+               if (q > mapQ) q = mapQ;
+               if (q > 63) q = 63;
+               if (q < 4) q = 4;
+               if (!is_indel) {
+                       b = bam1_seqi(bam1_seq(p->b), p->qpos); // base
+                       b = bam_nt16_nt4_table[b? b : ref_base]; // b is the 2-bit base
+                       is_diff = (ref4 < 4 && b == ref4)? 0 : 1;
+               } else {
+                       b = p->aux>>16&0x3f;
+                       is_diff = (b != 0);
+               }
+               if (is_diff) ++r->n_supp;
+               bca->bases[n++] = q<<5 | (int)bam1_strand(p->b)<<4 | b;
+               // collect annotations
+               if (b < 4) r->qsum[b] += q;
+               ++r->anno[0<<2|is_diff<<1|bam1_strand(p->b)];
+               min_dist = p->b->core.l_qseq - 1 - p->qpos;
+               if (min_dist > p->qpos) min_dist = p->qpos;
+               if (min_dist > CAP_DIST) min_dist = CAP_DIST;
+               r->anno[1<<2|is_diff<<1|0] += baseQ;
+               r->anno[1<<2|is_diff<<1|1] += baseQ * baseQ;    // FIXME: signed int is not enough for thousands of samples
+               r->anno[2<<2|is_diff<<1|0] += mapQ;
+               r->anno[2<<2|is_diff<<1|1] += mapQ * mapQ;              // FIXME: signed int is not enough for thousands of samples
+               r->anno[3<<2|is_diff<<1|0] += min_dist;
+               r->anno[3<<2|is_diff<<1|1] += min_dist * min_dist;
+       }
+       r->depth = n; r->ori_depth = ori_depth;
+       // glfgen
+       errmod_cal(bca->e, n, 5, bca->bases, r->p);
 
-typedef struct {
-       float esum[5], fsum[5];
-       uint32_t c[5];
-       int w[8];
-} auxaux_t;
+    // Calculate the Variant Distance Bias (make it optional?)
+    if ( nvar_pos < _n ) {
+        nvar_pos = _n;
+        var_pos = realloc(var_pos,sizeof(int)*nvar_pos);
+    }
+    int alt_dp=0, read_len=0;
+    for (i=0; i<_n; i++) {
+        const bam_pileup1_t *p = pl + i;
+        if ( bam1_seqi(bam1_seq(p->b),p->qpos) == ref_base ) 
+            continue;
 
-/*
-  The following code is nearly identical to bam_maqcns_glfgen() under
-  the simplified SOAPsnp model. It does the following:
+        var_pos[alt_dp] = p->qpos;
+        if ( (bam1_cigar(p->b)[0]&BAM_CIGAR_MASK)==4 )
+            var_pos[alt_dp] -= bam1_cigar(p->b)[0]>>BAM_CIGAR_SHIFT;
 
-  1) Collect strand, base, quality and mapping quality information for
-     each base and combine them in an integer:
+        alt_dp++;
+        read_len += p->b->core.l_qseq;
+    }
+    float mvd=0;
+    int j;
+    n=0;
+    for (i=0; i<alt_dp; i++) {
+        for (j=0; j<i; j++) {
+            mvd += abs(var_pos[i] - var_pos[j]);
+            n++;
+        }
+    }
+    r->mvd[0] = n ? mvd/n : 0;
+    r->mvd[1] = alt_dp;
+    r->mvd[2] = alt_dp ? read_len/alt_dp : 0;
 
-          x = min{baseQ,mapQ}<<24 | 1<<21 | strand<<18 | base<<16 | baseQ<<8 | mapQ
+       return r->depth;
+}
 
-  2) Sort the list of integers for the next step.
 
-  3) For each base, calculate e_b, the sum of weighted qualities. For
-     each type of base on each strand, the best quality has the highest
-     weight. Only the top 255 bases on each strand are used (different
-     from maqcns).
+void calc_vdb(int n, const bcf_callret1_t *calls, bcf_call_t *call)
+{
+    // Variant distance bias. Samples merged by means of DP-weighted average.
 
-  4) Rescale the total read depth to 255.
+    float weight=0, tot_prob=0;
 
-  5) Calculate Q(D|g) = -10\log_{10}P(D|g) (d_a is the allele count):
+    int i;
+    for (i=0; i<n; i++)
+    {
+        int mvd      = calls[i].mvd[0];
+        int dp       = calls[i].mvd[1];
+        int read_len = calls[i].mvd[2];
 
-       Q(D|<aa>)=\sum_{b\not=a}e_b
-          Q(D|<aA>)=3*(d_a+d_A)+\sum_{b\not=a,b\not=A}e_b
- */
-int bcf_call_glfgen(int _n, const bam_pileup1_t *pl, int ref_base /*4-bit*/, bcf_callaux_t *bca, bcf_callret1_t *r)
-{
-       int i, j, k, c, n;
-       float *p = r->p;
-       auxaux_t aux;
+        if ( dp<2 ) continue;
 
-       memset(r, 0, sizeof(bcf_callret1_t));
-       if (_n == 0) return -1;
+        float prob = 0;
+        if ( dp==2 )
+        {
+            // Exact formula
+            prob = (mvd==0) ? 1.0/read_len : (read_len-mvd)*2.0/read_len/read_len;
+        }
+        else if ( dp==3 )
+        {
+            // Sin, quite accurate approximation
+            float mu = read_len/2.9;
+            prob = mvd>2*mu ? 0 : sin(mvd*3.14/2/mu) / (4*mu/3.14);
+        }
+        else
+        {
+            // Scaled gaussian curve, crude approximation, but behaves well. Using fixed depth for bigger depths.
+            if ( dp>5 )
+                dp = 5;
+            float sigma2 = (read_len/1.9/(dp+1)) * (read_len/1.9/(dp+1));
+            float norm   = 1.125*sqrt(2*3.14*sigma2);
+            float mu     = read_len/2.9;
+            if ( mvd < mu )
+                prob = exp(-(mvd-mu)*(mvd-mu)/2/sigma2)/norm;
+            else
+                prob = exp(-(mvd-mu)*(mvd-mu)/3.125/sigma2)/norm;
+        }
 
-       // enlarge the aux array if necessary
-       if (bca->max_info < _n) {
-               bca->max_info = _n;
-               kroundup32(bca->max_info);
-               bca->info = (uint32_t*)realloc(bca->info, 4 * bca->max_info);
-       }
-       // fill the aux array
-       for (i = n = 0; i < _n; ++i) {
-               const bam_pileup1_t *p = pl + i;
-               uint32_t q, x = 0, qq;
-               if (p->is_del || (p->b->core.flag&BAM_FUNMAP)) continue; // skip unmapped reads and deleted bases
-               q = (uint32_t)bam1_qual(p->b)[p->qpos]; // base quality
-               x |= (uint32_t)bam1_strand(p->b) << 18 | q << 8 | p->b->core.qual;
-               if (p->b->core.qual < q) q = p->b->core.qual; // cap the overall quality at mapping quality
-               x |= q << 24;
-               qq = bam1_seqi(bam1_seq(p->b), p->qpos); // base
-               q = bam_nt16_nt4_table[qq? qq : ref_base]; // q is the 2-bit base
-               if (q < 4) x |= 1 << 21 | q << 16;
-               
-               bca->info[n++] = x;
-       }
-       ks_introsort_uint32_t(n, bca->info);
-       r->depth = n;
-       // generate esum and fsum
-       memset(&aux, 0, sizeof(auxaux_t));
-       for (j = n - 1, r->sum_Q2 = 0; j >= 0; --j) { // calculate esum and fsum
-               uint32_t info = bca->info[j];
-               int tmp;
-               if (info>>24 < 4 && (info>>8&0x3f) != 0) info = 4<<24 | (info&0xffffff);
-               k = info>>16&7;
-               if (info>>24 > 0) {
-                       aux.esum[k&3] += bca->fk[aux.w[k]] * (info>>24);
-                       aux.fsum[k&3] += bca->fk[aux.w[k]];
-                       if (aux.w[k] + 1 < CALL_MAX) ++aux.w[k];
-                       ++aux.c[k&3];
-               }
-               tmp = (int)(info&0xff) < bca->capQ? (int)(info&0xff) : bca->capQ;
-               r->sum_Q2 += tmp * tmp;
-       }
-       memcpy(r->esum, aux.esum, 5 * sizeof(float));
-       // rescale ->c[]
-       for (j = c = 0; j != 4; ++j) c += aux.c[j];
-       if (c > 255) {
-               for (j = 0; j != 4; ++j) aux.c[j] = (int)(254.0 * aux.c[j] / c + 0.499);
-               for (j = c = 0; j != 4; ++j) c += aux.c[j];
-       }
-       // generate likelihood
-       for (j = 0; j != 5; ++j) {
-               float tmp;
-               // homozygous
-               for (k = 0, tmp = 0.0; k != 5; ++k)
-                       if (j != k) tmp += aux.esum[k];
-               p[j*5+j] = tmp; // anything that is not j
-               // heterozygous
-               for (k = j + 1; k < 5; ++k) {
-                       for (i = 0, tmp = 0.0; i != 5; ++i)
-                               if (i != j && i != k) tmp += aux.esum[i];
-                       p[j*5+k] = p[k*5+j] = 3.01 * (aux.c[j] + aux.c[k]) + tmp;
-               }
-       }
-       return 0;
+        //fprintf(stderr,"dp=%d mvd=%d read_len=%d -> prob=%f\n", dp,mvd,read_len,prob);
+        tot_prob += prob*dp;
+        weight += dp;
+    }
+    tot_prob = weight ? tot_prob/weight : 1; 
+    //fprintf(stderr,"prob=%f\n", tot_prob);
+    call->vdb = tot_prob;
 }
 
-/*
-  1) Find the top 2 bases (from esum[4]).
-
-  2) If the reference base is among the top 2, consider the locus is
-     potentially biallelic and set call->a[2] as -1; otherwise, the
-     locus is potentially triallelic. If the reference is ambiguous,
-     take the weakest call as the pseudo-reference.
- */
 int bcf_call_combine(int n, const bcf_callret1_t *calls, int ref_base /*4-bit*/, bcf_call_t *call)
 {
-       int ref4, i, j;
-       int64_t sum[5], tmp;
-       call->ori_ref = ref4 = bam_nt16_nt4_table[ref_base];
-       if (ref4 > 4) ref4 = 4;
-       { // calculate esum
-               double esum[5];
-               memset(esum, 0, sizeof(double) * 4);
-               for (i = 0; i < n; ++i) {
-                       for (j = 0; j < 4; ++j)
-                               esum[j] += calls[i].esum[j];
-               }
+       int ref4, i, j, qsum[4];
+       int64_t tmp;
+       if (ref_base >= 0) {
+               call->ori_ref = ref4 = bam_nt16_nt4_table[ref_base];
+               if (ref4 > 4) ref4 = 4;
+       } else call->ori_ref = -1, ref4 = 0;
+       // calculate qsum
+       memset(qsum, 0, 4 * sizeof(int));
+       for (i = 0; i < n; ++i)
                for (j = 0; j < 4; ++j)
-                       sum[j] = (int)(esum[j] * 100. + .499) << 2 | j;
-       }
+                       qsum[j] += calls[i].qsum[j];
+    int qsum_tot=0;
+    for (j=0; j<4; j++) { qsum_tot += qsum[j]; call->qsum[j] = 0; }
+       for (j = 0; j < 4; ++j) qsum[j] = qsum[j] << 2 | j;
        // find the top 2 alleles
        for (i = 1; i < 4; ++i) // insertion sort
-               for (j = i; j > 0 && sum[j] < sum[j-1]; --j)
-                       tmp = sum[j], sum[j] = sum[j-1], sum[j-1] = tmp;
+               for (j = i; j > 0 && qsum[j] < qsum[j-1]; --j)
+                       tmp = qsum[j], qsum[j] = qsum[j-1], qsum[j-1] = tmp;
        // set the reference allele and alternative allele(s)
        for (i = 0; i < 5; ++i) call->a[i] = -1;
        call->unseen = -1;
        call->a[0] = ref4;
        for (i = 3, j = 1; i >= 0; --i) {
-               if ((sum[i]&3) != ref4) {
-                       if (sum[i]>>2 != 0) call->a[j++] = sum[i]&3;
+               if ((qsum[i]&3) != ref4) {
+                       if (qsum[i]>>2 != 0) 
+            {
+                if ( j<4 ) call->qsum[j] = (float)(qsum[i]>>2)/qsum_tot; // ref N can make j>=4
+                call->a[j++]  = qsum[i]&3;
+            }
                        else break;
                }
+        else 
+            call->qsum[0] = (float)(qsum[i]>>2)/qsum_tot;
+       }
+       if (ref_base >= 0) { // for SNPs, find the "unseen" base
+               if (((ref4 < 4 && j < 4) || (ref4 == 4 && j < 5)) && i >= 0)
+                       call->unseen = j, call->a[j++] = qsum[i]&3;
+               call->n_alleles = j;
+       } else {
+               call->n_alleles = j;
+               if (call->n_alleles == 1) return -1; // no reliable supporting read. stop doing anything
        }
-       if (((ref4 < 4 && j < 4) || (ref4 == 4 && j < 5)) && i >= 0)
-               call->unseen = j, call->a[j++] = sum[i]&3;
-       call->n_alleles = j;
        // set the PL array
        if (call->n < n) {
                call->n = n;
@@ -192,8 +237,8 @@ int bcf_call_combine(int n, const bcf_callret1_t *calls, int ref_base /*4-bit*/,
                x = call->n_alleles * (call->n_alleles + 1) / 2;
                // get the possible genotypes
                for (i = z = 0; i < call->n_alleles; ++i)
-                       for (j = i; j < call->n_alleles; ++j)
-                               g[z++] = call->a[i] * 5 + call->a[j];
+                       for (j = 0; j <= i; ++j)
+                               g[z++] = call->a[j] * 5 + call->a[i];
                for (i = 0; i < n; ++i) {
                        uint8_t *PL = call->PL + x * i;
                        const bcf_callret1_t *r = calls + i;
@@ -208,36 +253,110 @@ int bcf_call_combine(int n, const bcf_callret1_t *calls, int ref_base /*4-bit*/,
                                PL[j] = y;
                        }
                }
+//             if (ref_base < 0) fprintf(stderr, "%d,%d,%f,%d\n", call->n_alleles, x, sum_min, call->unseen);
                call->shift = (int)(sum_min + .499);
        }
-       for (i = call->depth = 0, tmp = 0; i < n; ++i) {
+       // combine annotations
+       memset(call->anno, 0, 16 * sizeof(int));
+       for (i = call->depth = call->ori_depth = 0, tmp = 0; i < n; ++i) {
                call->depth += calls[i].depth;
-               tmp += calls[i].sum_Q2;
+               call->ori_depth += calls[i].ori_depth;
+               for (j = 0; j < 16; ++j) call->anno[j] += calls[i].anno[j];
        }
-       call->rmsQ = (int)(sqrt((double)tmp / call->depth) + .499);
+
+    calc_vdb(n, calls, call);
+
        return 0;
 }
 
-int bcf_call2bcf(int tid, int pos, bcf_call_t *bc, bcf1_t *b)
+int bcf_call2bcf(int tid, int pos, bcf_call_t *bc, bcf1_t *b, bcf_callret1_t *bcr, int fmt_flag,
+                                const bcf_callaux_t *bca, const char *ref)
 {
+       extern double kt_fisher_exact(int n11, int n12, int n21, int n22, double *_left, double *_right, double *two);
        kstring_t s;
-       int i;
+       int i, j;
+       b->n_smpl = bc->n;
        b->tid = tid; b->pos = pos; b->qual = 0;
        s.s = b->str; s.m = b->m_str; s.l = 0;
        kputc('\0', &s);
-       kputc("ACGTN"[bc->ori_ref], &s); kputc('\0', &s);
-       for (i = 1; i < 5; ++i) {
-               if (bc->a[i] < 0) break;
-               if (i > 1) kputc(',', &s);
-//             kputc(bc->unseen == i && i != 3? 'X' : "ACGT"[bc->a[i]], &s);
-               kputc(bc->unseen == i? 'X' : "ACGT"[bc->a[i]], &s);
+       if (bc->ori_ref < 0) { // an indel
+               // write REF
+               kputc(ref[pos], &s);
+               for (j = 0; j < bca->indelreg; ++j) kputc(ref[pos+1+j], &s);
+               kputc('\0', &s);
+               // write ALT
+               kputc(ref[pos], &s);
+               for (i = 1; i < 4; ++i) {
+                       if (bc->a[i] < 0) break;
+                       if (i > 1) {
+                               kputc(',', &s); kputc(ref[pos], &s);
+                       }
+                       if (bca->indel_types[bc->a[i]] < 0) { // deletion
+                               for (j = -bca->indel_types[bc->a[i]]; j < bca->indelreg; ++j)
+                                       kputc(ref[pos+1+j], &s);
+                       } else { // insertion; cannot be a reference unless a bug
+                               char *inscns = &bca->inscns[bc->a[i] * bca->maxins];
+                               for (j = 0; j < bca->indel_types[bc->a[i]]; ++j)
+                                       kputc("ACGTN"[(int)inscns[j]], &s);
+                               for (j = 0; j < bca->indelreg; ++j) kputc(ref[pos+1+j], &s);
+                       }
+               }
+               kputc('\0', &s);
+       } else { // a SNP
+               kputc("ACGTN"[bc->ori_ref], &s); kputc('\0', &s);
+               for (i = 1; i < 5; ++i) {
+                       if (bc->a[i] < 0) break;
+                       if (i > 1) kputc(',', &s);
+                       kputc(bc->unseen == i? 'X' : "ACGT"[bc->a[i]], &s);
+               }
+               kputc('\0', &s);
        }
        kputc('\0', &s);
+       // INFO
+       if (bc->ori_ref < 0) ksprintf(&s,"INDEL;IS=%d,%f;", bca->max_support, bca->max_frac);
+       kputs("DP=", &s); kputw(bc->ori_depth, &s); kputs(";I16=", &s);
+       for (i = 0; i < 16; ++i) {
+               if (i) kputc(',', &s);
+               kputw(bc->anno[i], &s);
+       }
+    ksprintf(&s,";QS=%f,%f,%f,%f", bc->qsum[0],bc->qsum[1],bc->qsum[2],bc->qsum[3]);
+    if (bc->vdb != 1)
+        ksprintf(&s, ";VDB=%.4f", bc->vdb);
+       kputc('\0', &s);
+       // FMT
+       kputs("PL", &s);
+       if (bcr && fmt_flag) {
+               if (fmt_flag & B2B_FMT_DP) kputs(":DP", &s);
+               if (fmt_flag & B2B_FMT_DV) kputs(":DV", &s);
+               if (fmt_flag & B2B_FMT_SP) kputs(":SP", &s);
+       }
        kputc('\0', &s);
-       kputs("MQ=", &s); kputw(bc->rmsQ, &s); kputs(";DP=", &s); kputw(bc->depth, &s); kputc('\0', &s);
-       kputs("PL", &s); kputc('\0', &s);
        b->m_str = s.m; b->str = s.s; b->l_str = s.l;
-       bcf_sync(bc->n, b);
+       bcf_sync(b);
        memcpy(b->gi[0].data, bc->PL, b->gi[0].len * bc->n);
+       if (bcr && fmt_flag) {
+               uint16_t *dp = (fmt_flag & B2B_FMT_DP)? b->gi[1].data : 0;
+               uint16_t *dv = (fmt_flag & B2B_FMT_DV)? b->gi[1 + ((fmt_flag & B2B_FMT_DP) != 0)].data : 0;
+               int32_t  *sp = (fmt_flag & B2B_FMT_SP)? b->gi[1 + ((fmt_flag & B2B_FMT_DP) != 0) + ((fmt_flag & B2B_FMT_DV) != 0)].data : 0;
+               for (i = 0; i < bc->n; ++i) {
+                       bcf_callret1_t *p = bcr + i;
+                       if (dp) dp[i] = p->depth  < 0xffff? p->depth  : 0xffff;
+                       if (dv) dv[i] = p->n_supp < 0xffff? p->n_supp : 0xffff;
+                       if (sp) {
+                               if (p->anno[0] + p->anno[1] < 2 || p->anno[2] + p->anno[3] < 2
+                                       || p->anno[0] + p->anno[2] < 2 || p->anno[1] + p->anno[3] < 2)
+                               {
+                                       sp[i] = 0;
+                               } else {
+                                       double left, right, two;
+                                       int x;
+                                       kt_fisher_exact(p->anno[0], p->anno[1], p->anno[2], p->anno[3], &left, &right, &two);
+                                       x = (int)(-4.343 * log(two) + .499);
+                                       if (x > 255) x = 255;
+                                       sp[i] = x;
+                               }
+                       }
+               }
+       }
        return 0;
 }