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