]> git.donarmstrong.com Git - samtools.git/blob - bam_plcmd.c
* samtools-0.1.7-6
[samtools.git] / bam_plcmd.c
1 #include <math.h>
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <ctype.h>
5 #include "sam.h"
6 #include "faidx.h"
7 #include "bam_maqcns.h"
8 #include "khash.h"
9 #include "glf.h"
10 #include "kstring.h"
11
12 typedef int *indel_list_t;
13 KHASH_MAP_INIT_INT64(64, indel_list_t)
14
15 #define BAM_PLF_SIMPLE     0x01
16 #define BAM_PLF_CNS        0x02
17 #define BAM_PLF_INDEL_ONLY 0x04
18 #define BAM_PLF_GLF        0x08
19 #define BAM_PLF_VAR_ONLY   0x10
20 #define BAM_PLF_2ND        0x20
21 #define BAM_PLF_RANBASE    0x40
22 #define BAM_PLF_1STBASE    0x80
23 #define BAM_PLF_ALLBASE    0x100
24
25 typedef struct {
26         bam_header_t *h;
27         bam_maqcns_t *c;
28         bam_maqindel_opt_t *ido;
29         faidx_t *fai;
30         khash_t(64) *hash;
31         uint32_t format;
32         int tid, len, last_pos;
33         int mask;
34         char *ref;
35         glfFile fp_glf; // for glf output only
36 } pu_data_t;
37
38 char **__bam_get_lines(const char *fn, int *_n);
39 void bam_init_header_hash(bam_header_t *header);
40 int32_t bam_get_tid(const bam_header_t *header, const char *seq_name);
41
42 static khash_t(64) *load_pos(const char *fn, bam_header_t *h)
43 {
44         char **list;
45         int i, j, n, *fields, max_fields;
46         khash_t(64) *hash;
47         bam_init_header_hash(h);
48         list = __bam_get_lines(fn, &n);
49         hash = kh_init(64);
50         max_fields = 0; fields = 0;
51         for (i = 0; i < n; ++i) {
52                 char *str = list[i];
53                 int chr, n_fields, ret;
54                 khint_t k;
55                 uint64_t x;
56                 n_fields = ksplit_core(str, 0, &max_fields, &fields);
57                 if (n_fields < 2) continue;
58                 chr = bam_get_tid(h, str + fields[0]);
59                 if (chr < 0) {
60                         fprintf(stderr, "[load_pos] unknown reference sequence name: %s\n", str + fields[0]);
61                         continue;
62                 }
63                 x = (uint64_t)chr << 32 | (atoi(str + fields[1]) - 1);
64                 k = kh_put(64, hash, x, &ret);
65                 if (ret == 0) {
66                         fprintf(stderr, "[load_pos] position %s:%s has been loaded.\n", str+fields[0], str+fields[1]);
67                         continue;
68                 }
69                 kh_val(hash, k) = 0;
70                 if (n_fields > 2) {
71                         // count
72                         for (j = 2; j < n_fields; ++j) {
73                                 char *s = str + fields[j];
74                                 if ((*s != '+' && *s != '-') || !isdigit(s[1])) break;
75                         }
76                         if (j > 2) { // update kh_val()
77                                 int *q, y, z;
78                                 q = kh_val(hash, k) = (int*)calloc(j - 1, sizeof(int));
79                                 q[0] = j - 2; z = j; y = 1;
80                                 for (j = 2; j < z; ++j)
81                                         q[y++] = atoi(str + fields[j]);
82                         }
83                 }
84                 free(str);
85         }
86         free(list); free(fields);
87         return hash;
88 }
89
90 // an analogy to pileup_func() below
91 static int glt3_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pu, void *data)
92 {
93         pu_data_t *d = (pu_data_t*)data;
94         bam_maqindel_ret_t *r = 0;
95         int rb, *proposed_indels = 0;
96         glf1_t *g;
97         glf3_t *g3;
98
99         if (d->fai == 0) {
100                 fprintf(stderr, "[glt3_func] reference sequence is required for generating GLT. Abort!\n");
101                 exit(1);
102         }
103         if (d->hash) { // only output a list of sites
104                 khint_t k = kh_get(64, d->hash, (uint64_t)tid<<32|pos);
105                 if (k == kh_end(d->hash)) return 0;
106                 proposed_indels = kh_val(d->hash, k);
107         }
108         g3 = glf3_init1();
109         if (d->fai && (int)tid != d->tid) {
110                 if (d->ref) { // then write the end mark
111                         g3->rtype = GLF3_RTYPE_END;
112                         glf3_write1(d->fp_glf, g3);
113                 }
114                 glf3_ref_write(d->fp_glf, d->h->target_name[tid], d->h->target_len[tid]); // write reference
115                 free(d->ref);
116                 d->ref = fai_fetch(d->fai, d->h->target_name[tid], &d->len);
117                 d->tid = tid;
118                 d->last_pos = 0;
119         }
120         rb = (d->ref && (int)pos < d->len)? d->ref[pos] : 'N';
121         g = bam_maqcns_glfgen(n, pu, bam_nt16_table[rb], d->c);
122         memcpy(g3, g, sizeof(glf1_t));
123         g3->rtype = GLF3_RTYPE_SUB;
124         g3->offset = pos - d->last_pos;
125         d->last_pos = pos;
126         glf3_write1(d->fp_glf, g3);
127         if (pos < d->len) {
128                 if (proposed_indels)
129                         r = bam_maqindel(n, pos, d->ido, pu, d->ref, proposed_indels[0], proposed_indels+1);
130                 else r = bam_maqindel(n, pos, d->ido, pu, d->ref, 0, 0);
131         }
132         if (r) { // then write indel line
133                 int het = 3 * n, min;
134                 min = het;
135                 if (min > r->gl[0]) min = r->gl[0];
136                 if (min > r->gl[1]) min = r->gl[1];
137                 g3->ref_base = 0;
138                 g3->rtype = GLF3_RTYPE_INDEL;
139                 memset(g3->lk, 0, 10);
140                 g3->lk[0] = r->gl[0] - min < 255? r->gl[0] - min : 255;
141                 g3->lk[1] = r->gl[1] - min < 255? r->gl[1] - min : 255;
142                 g3->lk[2] = het - min < 255? het - min : 255;
143                 g3->offset = 0;
144                 g3->indel_len[0] = r->indel1;
145                 g3->indel_len[1] = r->indel2;
146                 g3->min_lk = min < 255? min : 255;
147                 g3->max_len = (abs(r->indel1) > abs(r->indel2)? abs(r->indel1) : abs(r->indel2)) + 1;
148                 g3->indel_seq[0] = strdup(r->s[0]+1);
149                 g3->indel_seq[1] = strdup(r->s[1]+1);
150                 glf3_write1(d->fp_glf, g3);
151                 bam_maqindel_ret_destroy(r);
152         }
153         free(g);
154         glf3_destroy1(g3);
155         return 0;
156 }
157
158 static int pileup_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pu, void *data)
159 {
160         pu_data_t *d = (pu_data_t*)data;
161         bam_maqindel_ret_t *r = 0;
162         int i, j, rb, rms_mapq = -1, *proposed_indels = 0;
163         uint64_t rms_aux;
164         uint32_t cns = 0;
165
166         // if GLF is required, suppress -c completely
167         if (d->format & BAM_PLF_GLF) return glt3_func(tid, pos, n, pu, data);
168         // if d->hash is initialized, only output the sites in the hash table
169         if (d->hash) {
170                 khint_t k = kh_get(64, d->hash, (uint64_t)tid<<32|pos);
171                 if (k == kh_end(d->hash)) return 0;
172                 proposed_indels = kh_val(d->hash, k);
173         }
174         // update d->ref if necessary
175         if (d->fai && (int)tid != d->tid) {
176                 free(d->ref);
177                 d->ref = faidx_fetch_seq(d->fai, d->h->target_name[tid], 0, 0x7fffffff, &d->len);
178                 d->tid = tid;
179         }
180         rb = (d->ref && (int)pos < d->len)? d->ref[pos] : 'N';
181         // when the indel-only mode is asked for, return if no reads mapped with indels
182         if (d->format & BAM_PLF_INDEL_ONLY) {
183                 for (i = 0; i < n; ++i)
184                         if (pu[i].indel != 0) break;
185                 if (i == n) return 0;
186         }
187         // call the consensus and indel
188         if (d->format & BAM_PLF_CNS) { // call consensus
189                 if (d->format & (BAM_PLF_RANBASE|BAM_PLF_1STBASE)) { // use a random base or the 1st base as the consensus call
190                         const bam_pileup1_t *p = (d->format & BAM_PLF_1STBASE)? pu : pu + (int)(drand48() * n);
191                         int q = bam1_qual(p->b)[p->qpos];
192                         int mapQ = p->b->core.qual < d->c->cap_mapQ? p->b->core.qual : d->c->cap_mapQ;
193                         uint32_t b = bam1_seqi(bam1_seq(p->b), p->qpos);
194                         cns = b<<28 | 0xf<<24 | mapQ<<16 | q<<8;
195                 } else if (d->format & BAM_PLF_ALLBASE) { // collapse all bases
196                         uint64_t rmsQ = 0;
197                         uint32_t b = 0;
198                         for (i = 0; i < n; ++i) {
199                                 const bam_pileup1_t *p = pu + i;
200                                 int q = p->b->core.qual < d->c->cap_mapQ? p->b->core.qual : d->c->cap_mapQ;
201                                 b |= bam1_seqi(bam1_seq(p->b), p->qpos);
202                                 rmsQ += q * q;
203                         }
204                         rmsQ = (uint64_t)(sqrt((double)rmsQ / n) + .499);
205                         cns = b<<28 | 0xf<<24 | rmsQ<<16 | 60<<8;
206                 } else cns = bam_maqcns_call(n, pu, d->c);
207         }
208         if ((d->format & (BAM_PLF_CNS|BAM_PLF_INDEL_ONLY)) && d->ref && pos < d->len) { // call indels
209                 if (proposed_indels) // the first element gives the size of the array
210                         r = bam_maqindel(n, pos, d->ido, pu, d->ref, proposed_indels[0], proposed_indels+1);
211                 else r = bam_maqindel(n, pos, d->ido, pu, d->ref, 0, 0);
212         }
213         // when only variant sites are asked for, test if the site is a variant
214         if ((d->format & BAM_PLF_CNS) && (d->format & BAM_PLF_VAR_ONLY)) {
215                 if (!(bam_nt16_table[rb] != 15 && cns>>28 != bam_nt16_table[rb])) { // not a SNP
216                         if (!(r && (r->gt == 2 || strcmp(r->s[r->gt], "*")))) { // not an indel
217                                 if (r) bam_maqindel_ret_destroy(r);
218                                 return 0;
219                         }
220                 }
221         }
222         // print the first 3 columns
223         printf("%s\t%d\t%c\t", d->h->target_name[tid], pos + 1, rb);
224         // print consensus information if required
225         if (d->format & BAM_PLF_CNS) {
226                 int ref_q, rb4 = bam_nt16_table[rb];
227                 ref_q = 0;
228                 if (rb4 != 15 && cns>>28 != 15 && cns>>28 != rb4) { // a SNP
229                         ref_q = ((cns>>24&0xf) == rb4)? cns>>8&0xff : (cns>>8&0xff) + (cns&0xff);
230                         if (ref_q > 255) ref_q = 255;
231                 }
232                 rms_mapq = cns>>16&0xff;
233                 printf("%c\t%d\t%d\t%d\t", bam_nt16_rev_table[cns>>28], cns>>8&0xff, ref_q, rms_mapq);
234         }
235         // print pileup sequences
236         printf("%d\t", n);
237         rms_aux = 0; // we need to recalculate rms_mapq when -c is not flagged on the command line
238         for (i = 0; i < n; ++i) {
239                 const bam_pileup1_t *p = pu + i;
240                 int tmp = p->b->core.qual < d->c->cap_mapQ? p->b->core.qual : d->c->cap_mapQ;
241                 rms_aux += tmp * tmp;
242                 if (p->is_head) printf("^%c", p->b->core.qual > 93? 126 : p->b->core.qual + 33);
243                 if (!p->is_del) {
244                         int c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos)];
245                         if (c == '=' || toupper(c) == toupper(rb)) c = bam1_strand(p->b)? ',' : '.';
246                         else c = bam1_strand(p->b)? tolower(c) : toupper(c);
247                         putchar(c);
248                         if (p->indel > 0) {
249                                 printf("+%d", p->indel);
250                                 for (j = 1; j <= p->indel; ++j) {
251                                         c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos + j)];
252                                         putchar(bam1_strand(p->b)? tolower(c) : toupper(c));
253                                 }
254                         } else if (p->indel < 0) {
255                                 printf("%d", p->indel);
256                                 for (j = 1; j <= -p->indel; ++j) {
257                                         c = (d->ref && (int)pos+j < d->len)? d->ref[pos+j] : 'N';
258                                         putchar(bam1_strand(p->b)? tolower(c) : toupper(c));
259                                 }
260                         }
261                 } else putchar('*');
262                 if (p->is_tail) putchar('$');
263         }
264         // finalize rms_mapq
265         rms_aux = (uint64_t)(sqrt((double)rms_aux / n) + .499);
266         if (rms_mapq < 0) rms_mapq = rms_aux;
267         putchar('\t');
268         // print quality
269         for (i = 0; i < n; ++i) {
270                 const bam_pileup1_t *p = pu + i;
271                 int c = bam1_qual(p->b)[p->qpos] + 33;
272                 if (c > 126) c = 126;
273                 putchar(c);
274         }
275         if (d->format & BAM_PLF_2ND) { // print 2nd calls and qualities
276                 const unsigned char *q;
277                 putchar('\t');
278                 for (i = 0; i < n; ++i) {
279                         const bam_pileup1_t *p = pu + i;
280                         q = bam_aux_get(p->b, "E2");
281                         putchar(q? q[p->qpos + 1] : 'N');
282                 }
283                 putchar('\t');
284                 for (i = 0; i < n; ++i) {
285                         const bam_pileup1_t *p = pu + i;
286                         q = bam_aux_get(p->b, "U2");
287                         putchar(q? q[p->qpos + 1] : '!');
288                 }
289         }
290         // print mapping quality if -s is flagged on the command line
291         if (d->format & BAM_PLF_SIMPLE) {
292                 putchar('\t');
293                 for (i = 0; i < n; ++i) {
294                         int c = pu[i].b->core.qual + 33;
295                         if (c > 126) c = 126;
296                         putchar(c);
297                 }
298         }
299         putchar('\n');
300         // print the indel line if r has been calculated. This only happens if:
301         // a) -c or -i are flagged, AND b) the reference sequence is available
302         if (r) {
303                 printf("%s\t%d\t*\t", d->h->target_name[tid], pos + 1);
304                 if (r->gt < 2) printf("%s/%s\t", r->s[r->gt], r->s[r->gt]);
305                 else printf("%s/%s\t", r->s[0], r->s[1]);
306                 printf("%d\t%d\t", r->q_cns, r->q_ref);
307                 printf("%d\t%d\t", rms_mapq, n);
308                 printf("%s\t%s\t", r->s[0], r->s[1]);
309                 //printf("%d\t%d\t", r->gl[0], r->gl[1]);
310                 printf("%d\t%d\t%d\t", r->cnt1, r->cnt2, r->cnt_anti);
311                 printf("%d\t%d\n", r->cnt_ref, r->cnt_ambi);
312                 bam_maqindel_ret_destroy(r);
313         }
314         return 0;
315 }
316
317 int bam_pileup(int argc, char *argv[])
318 {
319         int c, is_SAM = 0;
320         char *fn_list = 0, *fn_fa = 0, *fn_pos = 0;
321         pu_data_t *d = (pu_data_t*)calloc(1, sizeof(pu_data_t));
322         d->tid = -1; d->mask = BAM_DEF_MASK;
323         d->c = bam_maqcns_init();
324         d->ido = bam_maqindel_opt_init();
325         while ((c = getopt(argc, argv, "st:f:cT:N:r:l:im:gI:G:vM:S2aR:")) >= 0) {
326                 switch (c) {
327                 case 'a': d->c->is_soap = 1; break;
328                 case 's': d->format |= BAM_PLF_SIMPLE; break;
329                 case 't': fn_list = strdup(optarg); break;
330                 case 'l': fn_pos = strdup(optarg); break;
331                 case 'f': fn_fa = strdup(optarg); break;
332                 case 'T': d->c->theta = atof(optarg); break;
333                 case 'N': d->c->n_hap = atoi(optarg); break;
334                 case 'r': d->c->het_rate = atof(optarg); break;
335                 case 'M': d->c->cap_mapQ = atoi(optarg); break;
336                 case 'c': d->format |= BAM_PLF_CNS; break;
337                 case 'i': d->format |= BAM_PLF_INDEL_ONLY; break;
338                 case 'v': d->format |= BAM_PLF_VAR_ONLY; break;
339                 case 'm': d->mask = strtol(optarg, 0, 0); break;
340                 case 'g': d->format |= BAM_PLF_GLF; break;
341                 case '2': d->format |= BAM_PLF_2ND; break;
342                 case 'I': d->ido->q_indel = atoi(optarg); break;
343                 case 'G': d->ido->r_indel = atof(optarg); break;
344                 case 'S': is_SAM = 1; break;
345                 case 'R':
346                         if (strcmp(optarg, "random") == 0) d->format |= BAM_PLF_RANBASE;
347                         else if (strcmp(optarg, "first") == 0) d->format |= BAM_PLF_1STBASE;
348                         else if (strcmp(optarg, "all") == 0) d->format |= BAM_PLF_ALLBASE;
349                         else fprintf(stderr, "[bam_pileup] unrecognized -R\n");
350                         break;
351                 default: fprintf(stderr, "Unrecognizd option '-%c'.\n", c); return 1;
352                 }
353         }
354         if (fn_list) is_SAM = 1;
355         if (optind == argc) {
356                 fprintf(stderr, "\n");
357                 fprintf(stderr, "Usage:  samtools pileup [options] <in.bam>|<in.sam>\n\n");
358                 fprintf(stderr, "Option: -s        simple (yet incomplete) pileup format\n");
359                 fprintf(stderr, "        -S        the input is in SAM\n");
360                 fprintf(stderr, "        -a        use the SOAPsnp model for SNP calling\n");
361                 fprintf(stderr, "        -2        output the 2nd best call and quality\n");
362                 fprintf(stderr, "        -i        only show lines/consensus with indels\n");
363                 fprintf(stderr, "        -m INT    filtering reads with bits in INT [%d]\n", d->mask);
364                 fprintf(stderr, "        -M INT    cap mapping quality at INT [%d]\n", d->c->cap_mapQ);
365                 fprintf(stderr, "        -t FILE   list of reference sequences (force -S)\n");
366                 fprintf(stderr, "        -l FILE   list of sites at which pileup is output\n");
367                 fprintf(stderr, "        -f FILE   reference sequence in the FASTA format\n\n");
368                 fprintf(stderr, "        -c        output the maq consensus sequence\n");
369                 fprintf(stderr, "        -v        print variants only (for -c)\n");
370                 fprintf(stderr, "        -g        output in the GLFv3 format (suppressing -c/-i/-s)\n");
371                 fprintf(stderr, "        -T FLOAT  theta in maq consensus calling model (for -c/-g) [%f]\n", d->c->theta);
372                 fprintf(stderr, "        -N INT    number of haplotypes in the sample (for -c/-g) [%d]\n", d->c->n_hap);
373                 fprintf(stderr, "        -r FLOAT  prior of a difference between two haplotypes (for -c/-g) [%f]\n", d->c->het_rate);
374                 fprintf(stderr, "        -G FLOAT  prior of an indel between two haplotypes (for -c/-g) [%f]\n", d->ido->r_indel);
375                 fprintf(stderr, "        -I INT    phred prob. of an indel in sequencing/prep. (for -c/-g) [%d]\n", d->ido->q_indel);
376                 fprintf(stderr, "\n");
377                 free(fn_list); free(fn_fa); free(d);
378                 return 1;
379         }
380         if (d->format & (BAM_PLF_RANBASE|BAM_PLF_1STBASE|BAM_PLF_ALLBASE)) d->format |= BAM_PLF_CNS;
381         if (fn_fa) d->fai = fai_load(fn_fa);
382         if (d->format & (BAM_PLF_CNS|BAM_PLF_GLF)) bam_maqcns_prepare(d->c); // consensus calling
383         if (d->format & BAM_PLF_GLF) { // for glf output
384                 glf3_header_t *h;
385                 h = glf3_header_init();
386                 d->fp_glf = bgzf_fdopen(fileno(stdout), "w");
387                 glf3_header_write(d->fp_glf, h);
388                 glf3_header_destroy(h);
389         }
390         if (d->fai == 0 && (d->format & (BAM_PLF_CNS|BAM_PLF_INDEL_ONLY)))
391                 fprintf(stderr, "[bam_pileup] indels will not be called when -f is absent.\n");
392         if (fn_fa && is_SAM && fn_list == 0) fn_list = samfaipath(fn_fa);
393
394         {
395                 samfile_t *fp;
396                 fp = is_SAM? samopen(argv[optind], "r", fn_list) : samopen(argv[optind], "rb", 0);
397                 if (fp == 0 || fp->header == 0) {
398                         fprintf(stderr, "[bam_pileup] fail to read the header: non-exisiting file or wrong format.\n");
399                         return 1;
400                 }
401                 d->h = fp->header;
402                 if (fn_pos) d->hash = load_pos(fn_pos, d->h);
403                 sampileup(fp, d->mask, pileup_func, d);
404                 samclose(fp); // d->h will be destroyed here
405         }
406
407         // free
408         if (d->format & BAM_PLF_GLF) bgzf_close(d->fp_glf);
409         if (fn_pos) { // free the hash table
410                 khint_t k;
411                 for (k = kh_begin(d->hash); k < kh_end(d->hash); ++k)
412                         if (kh_exist(d->hash, k)) free(kh_val(d->hash, k));
413                 kh_destroy(64, d->hash);
414         }
415         free(fn_pos); free(fn_list); free(fn_fa);
416         if (d->fai) fai_destroy(d->fai);
417         bam_maqcns_destroy(d->c);
418         free(d->ido); free(d->ref); free(d);
419         return 0;
420 }