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