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