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