]> git.donarmstrong.com Git - samtools.git/blob - bam_tview.c
Complain when BAM cannot be open. Severe bug fixed in -m haploid calling.
[samtools.git] / bam_tview.c
1 #undef _HAVE_CURSES
2
3 #if _CURSES_LIB == 0
4 #elif _CURSES_LIB == 1
5 #include <curses.h>
6 #ifndef NCURSES_VERSION
7 #warning "_CURSES_LIB=1 but NCURSES_VERSION not defined; tview is NOT compiled"
8 #else
9 #define _HAVE_CURSES
10 #endif
11 #elif _CURSES_LIB == 2
12 #include <xcurses.h>
13 #define _HAVE_CURSES
14 #else
15 #warning "_CURSES_LIB is not 0, 1 or 2; tview is NOT compiled"
16 #endif
17
18 #ifdef _HAVE_CURSES
19 #include <ctype.h>
20 #include <assert.h>
21 #include <string.h>
22 #include <math.h>
23 #include <unistd.h>
24 #include "bam.h"
25 #include "faidx.h"
26 #include "bam2bcf.h"
27 #include "sam_header.h"
28 #include "khash.h"
29
30 KHASH_MAP_INIT_STR(kh_rg, const char *)
31
32 char bam_aux_getCEi(bam1_t *b, int i);
33 char bam_aux_getCSi(bam1_t *b, int i);
34 char bam_aux_getCQi(bam1_t *b, int i);
35
36 #define TV_MIN_ALNROW 2
37 #define TV_MAX_GOTO  40
38 #define TV_LOW_MAPQ  10
39
40 #define TV_COLOR_MAPQ   0
41 #define TV_COLOR_BASEQ  1
42 #define TV_COLOR_NUCL   2
43 #define TV_COLOR_COL    3
44 #define TV_COLOR_COLQ   4
45
46 #define TV_BASE_NUCL 0
47 #define TV_BASE_COLOR_SPACE 1
48
49 typedef struct {
50         int mrow, mcol;
51         WINDOW *wgoto, *whelp;
52
53         bam_index_t *idx;
54         bam_lplbuf_t *lplbuf;
55         bam_header_t *header;
56         bamFile fp;
57         int curr_tid, left_pos;
58         faidx_t *fai;
59         bcf_callaux_t *bca;
60
61         int ccol, last_pos, row_shift, base_for, color_for, is_dot, l_ref, ins, no_skip, show_name;
62         char *ref;
63     khash_t(kh_rg) *rg_hash;
64 } tview_t;
65
66 int tv_pl_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pl, void *data)
67 {
68         extern unsigned char bam_nt16_table[256];
69         tview_t *tv = (tview_t*)data;
70         int i, j, c, rb, attr, max_ins = 0;
71         uint32_t call = 0;
72         if (pos < tv->left_pos || tv->ccol > tv->mcol) return 0; // out of screen
73         // print referece
74         rb = (tv->ref && pos - tv->left_pos < tv->l_ref)? tv->ref[pos - tv->left_pos] : 'N';
75         for (i = tv->last_pos + 1; i < pos; ++i) {
76                 if (i%10 == 0 && tv->mcol - tv->ccol >= 10) mvprintw(0, tv->ccol, "%-d", i+1);
77                 c = tv->ref? tv->ref[i - tv->left_pos] : 'N';
78                 mvaddch(1, tv->ccol++, c);
79         }
80         if (pos%10 == 0 && tv->mcol - tv->ccol >= 10) mvprintw(0, tv->ccol, "%-d", pos+1);
81         { // call consensus
82                 bcf_callret1_t bcr;
83                 int qsum[4], a1, a2, tmp;
84                 double p[3], prior = 30;
85                 bcf_call_glfgen(n, pl, bam_nt16_table[rb], tv->bca, &bcr);
86                 for (i = 0; i < 4; ++i) qsum[i] = bcr.qsum[i]<<2 | i;
87                 for (i = 1; i < 4; ++i) // insertion sort
88                         for (j = i; j > 0 && qsum[j] > qsum[j-1]; --j)
89                                 tmp = qsum[j], qsum[j] = qsum[j-1], qsum[j-1] = tmp;
90                 a1 = qsum[0]&3; a2 = qsum[1]&3;
91                 p[0] = bcr.p[a1*5+a1]; p[1] = bcr.p[a1*5+a2] + prior; p[2] = bcr.p[a2*5+a2];
92                 if ("ACGT"[a1] != toupper(rb)) p[0] += prior + 3;
93                 if ("ACGT"[a2] != toupper(rb)) p[2] += prior + 3;
94                 if (p[0] < p[1] && p[0] < p[2]) call = (1<<a1)<<16 | (int)((p[1]<p[2]?p[1]:p[2]) - p[0] + .499);
95                 else if (p[2] < p[1] && p[2] < p[0]) call = (1<<a2)<<16 | (int)((p[0]<p[1]?p[0]:p[1]) - p[2] + .499);
96                 else call = (1<<a1|1<<a2)<<16 | (int)((p[0]<p[2]?p[0]:p[2]) - p[1] + .499);
97         }
98         attr = A_UNDERLINE;
99         c = ",ACMGRSVTWYHKDBN"[call>>16&0xf];
100         i = (call&0xffff)/10+1;
101         if (i > 4) i = 4;
102         attr |= COLOR_PAIR(i);
103         if (c == toupper(rb)) c = '.';
104         attron(attr);
105         mvaddch(2, tv->ccol, c);
106         attroff(attr);
107         if(tv->ins) {
108                 // calculate maximum insert
109                 for (i = 0; i < n; ++i) {
110                         const bam_pileup1_t *p = pl + i;
111                         if (p->indel > 0 && max_ins < p->indel) max_ins = p->indel;
112                 }
113         }
114         // core loop
115         for (j = 0; j <= max_ins; ++j) {
116                 for (i = 0; i < n; ++i) {
117                         const bam_pileup1_t *p = pl + i;
118                         int row = TV_MIN_ALNROW + p->level - tv->row_shift;
119                         if (j == 0) {
120                                 if (!p->is_del) {
121                                         if (tv->base_for == TV_BASE_COLOR_SPACE && 
122                                                         (c = bam_aux_getCSi(p->b, p->qpos))) {
123                                                 // assume that if we found one color, we will be able to get the color error
124                                                 if (tv->is_dot && '-' == bam_aux_getCEi(p->b, p->qpos)) c = bam1_strand(p->b)? ',' : '.';
125                                         } else {
126                                                 if (tv->show_name) {
127                                                         char *name = bam1_qname(p->b);
128                                                         c = (p->qpos + 1 >= p->b->core.l_qname)? ' ' : name[p->qpos];
129                                                 } else {
130                                                         c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos)];
131                                                         if (tv->is_dot && toupper(c) == toupper(rb)) c = bam1_strand(p->b)? ',' : '.';
132                                                 }
133                                         }
134                                 } else c = p->is_refskip? (bam1_strand(p->b)? '<' : '>') : '*';
135                         } else { // padding
136                                 if (j > p->indel) c = '*';
137                                 else { // insertion
138                                         if (tv->base_for ==  TV_BASE_NUCL) {
139                                                 if (tv->show_name) {
140                                                         char *name = bam1_qname(p->b);
141                                                         c = (p->qpos + j + 1 >= p->b->core.l_qname)? ' ' : name[p->qpos + j];
142                                                 } else {
143                                                         c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos + j)];
144                                                         if (j == 0 && tv->is_dot && toupper(c) == toupper(rb)) c = bam1_strand(p->b)? ',' : '.';
145                                                 }
146                                         } else {
147                                                 c = bam_aux_getCSi(p->b, p->qpos + j);
148                                                 if (tv->is_dot && '-' == bam_aux_getCEi(p->b, p->qpos + j)) c = bam1_strand(p->b)? ',' : '.';
149                                         }
150                                 }
151                         }
152                         if (row > TV_MIN_ALNROW && row < tv->mrow) {
153                                 int x;
154                                 attr = 0;
155                                 if (((p->b->core.flag&BAM_FPAIRED) && !(p->b->core.flag&BAM_FPROPER_PAIR))
156                                                 || (p->b->core.flag & BAM_FSECONDARY)) attr |= A_UNDERLINE;
157                                 if (tv->color_for == TV_COLOR_BASEQ) {
158                                         x = bam1_qual(p->b)[p->qpos]/10 + 1;
159                                         if (x > 4) x = 4;
160                                         attr |= COLOR_PAIR(x);
161                                 } else if (tv->color_for == TV_COLOR_MAPQ) {
162                                         x = p->b->core.qual/10 + 1;
163                                         if (x > 4) x = 4;
164                                         attr |= COLOR_PAIR(x);
165                                 } else if (tv->color_for == TV_COLOR_NUCL) {
166                                         x = bam_nt16_nt4_table[bam1_seqi(bam1_seq(p->b), p->qpos)] + 5;
167                                         attr |= COLOR_PAIR(x);
168                                 } else if(tv->color_for == TV_COLOR_COL) {
169                                         x = 0;
170                                         switch(bam_aux_getCSi(p->b, p->qpos)) {
171                                                 case '0': x = 0; break;
172                                                 case '1': x = 1; break;
173                                                 case '2': x = 2; break;
174                                                 case '3': x = 3; break;
175                                                 case '4': x = 4; break;
176                                                 default: x = bam_nt16_nt4_table[bam1_seqi(bam1_seq(p->b), p->qpos)]; break;
177                                         }
178                                         x+=5;
179                                         attr |= COLOR_PAIR(x);
180                                 } else if(tv->color_for == TV_COLOR_COLQ) {
181                                         x = bam_aux_getCQi(p->b, p->qpos);
182                                         if(0 == x) x = bam1_qual(p->b)[p->qpos];
183                                         x = x/10 + 1;
184                                         if (x > 4) x = 4;
185                                         attr |= COLOR_PAIR(x);
186                                 }
187                                 attron(attr);
188                                 mvaddch(row, tv->ccol, bam1_strand(p->b)? tolower(c) : toupper(c));
189                                 attroff(attr);
190                         }
191                 }
192                 c = j? '*' : rb;
193                 if (c == '*') {
194                         attr = COLOR_PAIR(8);
195                         attron(attr);
196                         mvaddch(1, tv->ccol++, c);
197                         attroff(attr);
198                 } else mvaddch(1, tv->ccol++, c);
199         }
200         tv->last_pos = pos;
201         return 0;
202 }
203
204 tview_t *tv_init(const char *fn, const char *fn_fa, char *samples)
205 {
206         tview_t *tv = (tview_t*)calloc(1, sizeof(tview_t));
207         tv->is_dot = 1;
208         tv->fp = bam_open(fn, "r");
209         bgzf_set_cache_size(tv->fp, 8 * 1024 *1024);
210         assert(tv->fp);
211         tv->header = bam_header_read(tv->fp);
212         tv->idx = bam_index_load(fn);
213         if (tv->idx == 0) exit(1);
214         tv->lplbuf = bam_lplbuf_init(tv_pl_func, tv);
215         if (fn_fa) tv->fai = fai_load(fn_fa);
216         tv->bca = bcf_call_init(0.83, 13);
217         tv->ins = 1;
218
219     if ( samples ) 
220     {
221         if ( !tv->header->dict ) tv->header->dict = sam_header_parse2(tv->header->text);
222         void *iter = tv->header->dict;
223         const char *key, *val;
224         int n = 0;
225         tv->rg_hash = kh_init(kh_rg);
226         while ( (iter = sam_header2key_val(iter, "RG","ID","SM", &key, &val)) )
227         {
228             if ( !strcmp(samples,key) || (val && !strcmp(samples,val)) )
229             {
230                 khiter_t k = kh_get(kh_rg, tv->rg_hash, key);
231                 if ( k != kh_end(tv->rg_hash) ) continue;
232                 int ret;
233                 k = kh_put(kh_rg, tv->rg_hash, key, &ret);
234                 kh_value(tv->rg_hash, k) = val;
235                 n++;
236             }
237         }
238         if ( !n )
239         {
240             fprintf(stderr,"The sample or read group \"%s\" not present.\n", samples);
241             exit(-1);
242         }
243     }
244
245         initscr();
246         keypad(stdscr, TRUE);
247         clear();
248         noecho();
249         cbreak();
250         tv->mrow = 24; tv->mcol = 80;
251         getmaxyx(stdscr, tv->mrow, tv->mcol);
252         tv->wgoto = newwin(3, TV_MAX_GOTO + 10, 10, 5);
253         tv->whelp = newwin(29, 40, 5, 5);
254         tv->color_for = TV_COLOR_MAPQ;
255         start_color();
256         init_pair(1, COLOR_BLUE, COLOR_BLACK);
257         init_pair(2, COLOR_GREEN, COLOR_BLACK);
258         init_pair(3, COLOR_YELLOW, COLOR_BLACK);
259         init_pair(4, COLOR_WHITE, COLOR_BLACK);
260         init_pair(5, COLOR_GREEN, COLOR_BLACK);
261         init_pair(6, COLOR_CYAN, COLOR_BLACK);
262         init_pair(7, COLOR_YELLOW, COLOR_BLACK);
263         init_pair(8, COLOR_RED, COLOR_BLACK);
264         init_pair(9, COLOR_BLUE, COLOR_BLACK);
265         return tv;
266 }
267
268 void tv_destroy(tview_t *tv)
269 {
270         delwin(tv->wgoto); delwin(tv->whelp);
271         endwin();
272
273         bam_lplbuf_destroy(tv->lplbuf);
274         bcf_call_destroy(tv->bca);
275         bam_index_destroy(tv->idx);
276         if (tv->fai) fai_destroy(tv->fai);
277         free(tv->ref);
278         bam_header_destroy(tv->header);
279         bam_close(tv->fp);
280         free(tv);
281 }
282
283 int tv_fetch_func(const bam1_t *b, void *data)
284 {
285         tview_t *tv = (tview_t*)data;
286     if ( tv->rg_hash )
287     {
288         const uint8_t *rg = bam_aux_get(b, "RG");
289         if ( !rg ) return 0; 
290         khiter_t k = kh_get(kh_rg, tv->rg_hash, (const char*)(rg + 1));
291         if ( k == kh_end(tv->rg_hash) ) return 0;
292     }
293         if (tv->no_skip) {
294                 uint32_t *cigar = bam1_cigar(b); // this is cheating...
295                 int i;
296                 for (i = 0; i <b->core.n_cigar; ++i) {
297                         if ((cigar[i]&0xf) == BAM_CREF_SKIP)
298                                 cigar[i] = cigar[i]>>4<<4 | BAM_CDEL;
299                 }
300         }
301         bam_lplbuf_push(b, tv->lplbuf);
302         return 0;
303 }
304
305 int tv_draw_aln(tview_t *tv, int tid, int pos)
306 {
307         // reset
308         clear();
309         tv->curr_tid = tid; tv->left_pos = pos;
310         tv->last_pos = tv->left_pos - 1;
311         tv->ccol = 0;
312         // print ref and consensus
313         if (tv->fai) {
314                 char *str;
315                 if (tv->ref) free(tv->ref);
316                 str = (char*)calloc(strlen(tv->header->target_name[tv->curr_tid]) + 30, 1);
317                 sprintf(str, "%s:%d-%d", tv->header->target_name[tv->curr_tid], tv->left_pos + 1, tv->left_pos + tv->mcol);
318                 tv->ref = fai_fetch(tv->fai, str, &tv->l_ref);
319                 free(str);
320         }
321         // draw aln
322         bam_lplbuf_reset(tv->lplbuf);
323         bam_fetch(tv->fp, tv->idx, tv->curr_tid, tv->left_pos, tv->left_pos + tv->mcol, tv, tv_fetch_func);
324         bam_lplbuf_push(0, tv->lplbuf);
325
326         while (tv->ccol < tv->mcol) {
327                 int pos = tv->last_pos + 1;
328                 if (pos%10 == 0 && tv->mcol - tv->ccol >= 10) mvprintw(0, tv->ccol, "%-d", pos+1);
329                 mvaddch(1, tv->ccol++, (tv->ref && pos < tv->l_ref)? tv->ref[pos - tv->left_pos] : 'N');
330                 ++tv->last_pos;
331         }
332         return 0;
333 }
334
335 static void tv_win_goto(tview_t *tv, int *tid, int *pos)
336 {
337         char str[256], *p;
338         int i, l = 0;
339         wborder(tv->wgoto, '|', '|', '-', '-', '+', '+', '+', '+');
340         mvwprintw(tv->wgoto, 1, 2, "Goto: ");
341         for (;;) {
342                 int c = wgetch(tv->wgoto);
343                 wrefresh(tv->wgoto);
344                 if (c == KEY_BACKSPACE || c == '\010' || c == '\177') {
345                         if(l > 0) --l;
346                 } else if (c == KEY_ENTER || c == '\012' || c == '\015') {
347                         int _tid = -1, _beg, _end;
348                         if (str[0] == '=') {
349                                 _beg = strtol(str+1, &p, 10) - 1;
350                                 if (_beg > 0) {
351                                         *pos = _beg;
352                                         return;
353                                 }
354                         } else {
355                                 bam_parse_region(tv->header, str, &_tid, &_beg, &_end);
356                                 if (_tid >= 0) {
357                                         *tid = _tid; *pos = _beg;
358                                         return;
359                                 }
360                         }
361                 } else if (isgraph(c)) {
362                         if (l < TV_MAX_GOTO) str[l++] = c;
363                 } else if (c == '\027') l = 0;
364                 else if (c == '\033') return;
365                 str[l] = '\0';
366                 for (i = 0; i < TV_MAX_GOTO; ++i) mvwaddch(tv->wgoto, 1, 8 + i, ' ');
367                 mvwprintw(tv->wgoto, 1, 8, "%s", str);
368         }
369 }
370
371 static void tv_win_help(tview_t *tv) {
372         int r = 1;
373         WINDOW *win = tv->whelp;
374         wborder(win, '|', '|', '-', '-', '+', '+', '+', '+');
375         mvwprintw(win, r++, 2, "        -=-    Help    -=- ");
376         r++;
377         mvwprintw(win, r++, 2, "?          This window");
378         mvwprintw(win, r++, 2, "Arrows     Small scroll movement");
379         mvwprintw(win, r++, 2, "h,j,k,l    Small scroll movement");
380         mvwprintw(win, r++, 2, "H,J,K,L    Large scroll movement");
381         mvwprintw(win, r++, 2, "ctrl-H     Scroll 1k left");
382         mvwprintw(win, r++, 2, "ctrl-L     Scroll 1k right");
383         mvwprintw(win, r++, 2, "space      Scroll one screen");
384         mvwprintw(win, r++, 2, "backspace  Scroll back one screen");
385         mvwprintw(win, r++, 2, "g          Go to specific location");
386         mvwprintw(win, r++, 2, "m          Color for mapping qual");
387         mvwprintw(win, r++, 2, "n          Color for nucleotide");
388         mvwprintw(win, r++, 2, "b          Color for base quality");
389         mvwprintw(win, r++, 2, "c          Color for cs color");
390         mvwprintw(win, r++, 2, "z          Color for cs qual");
391         mvwprintw(win, r++, 2, ".          Toggle on/off dot view");
392         mvwprintw(win, r++, 2, "s          Toggle on/off ref skip");
393         mvwprintw(win, r++, 2, "r          Toggle on/off rd name");
394         mvwprintw(win, r++, 2, "N          Turn on nt view");
395         mvwprintw(win, r++, 2, "C          Turn on cs view");
396         mvwprintw(win, r++, 2, "i          Toggle on/off ins");
397         mvwprintw(win, r++, 2, "q          Exit");
398         r++;
399         mvwprintw(win, r++, 2, "Underline:      Secondary or orphan");
400         mvwprintw(win, r++, 2, "Blue:    0-9    Green: 10-19");
401         mvwprintw(win, r++, 2, "Yellow: 20-29   White: >=30");
402         wrefresh(win);
403         wgetch(win);
404 }
405
406 void tv_loop(tview_t *tv)
407 {
408         int tid, pos;
409         tid = tv->curr_tid; pos = tv->left_pos;
410         while (1) {
411                 int c = getch();
412                 switch (c) {
413                         case '?': tv_win_help(tv); break;
414                         case '\033':
415                         case 'q': goto end_loop;
416                         case '/': 
417                         case 'g': tv_win_goto(tv, &tid, &pos); break;
418                         case 'm': tv->color_for = TV_COLOR_MAPQ; break;
419                         case 'b': tv->color_for = TV_COLOR_BASEQ; break;
420                         case 'n': tv->color_for = TV_COLOR_NUCL; break;
421                         case 'c': tv->color_for = TV_COLOR_COL; break;
422                         case 'z': tv->color_for = TV_COLOR_COLQ; break;
423                         case 's': tv->no_skip = !tv->no_skip; break;
424                         case 'r': tv->show_name = !tv->show_name; break;
425                         case KEY_LEFT:
426                         case 'h': --pos; break;
427                         case KEY_RIGHT:
428                         case 'l': ++pos; break;
429                         case KEY_SLEFT:
430                         case 'H': pos -= 20; break;
431                         case KEY_SRIGHT:
432                         case 'L': pos += 20; break;
433                         case '.': tv->is_dot = !tv->is_dot; break;
434                         case 'N': tv->base_for = TV_BASE_NUCL; break;
435                         case 'C': tv->base_for = TV_BASE_COLOR_SPACE; break;
436                         case 'i': tv->ins = !tv->ins; break;
437                         case '\010': pos -= 1000; break;
438                         case '\014': pos += 1000; break;
439                         case ' ': pos += tv->mcol; break;
440                         case KEY_UP:
441                         case 'j': --tv->row_shift; break;
442                         case KEY_DOWN:
443                         case 'k': ++tv->row_shift; break;
444                         case KEY_BACKSPACE:
445                         case '\177': pos -= tv->mcol; break;
446                         case KEY_RESIZE: getmaxyx(stdscr, tv->mrow, tv->mcol); break;
447                         default: continue;
448                 }
449                 if (pos < 0) pos = 0;
450                 if (tv->row_shift < 0) tv->row_shift = 0;
451                 tv_draw_aln(tv, tid, pos);
452         }
453 end_loop:
454         return;
455 }
456
457 void error(const char *format, ...)
458 {
459     if ( !format )
460     {
461         fprintf(stderr, "\n");
462         fprintf(stderr, "Usage: bamtk tview [options] <aln.bam> [ref.fasta]\n");
463         fprintf(stderr, "Options:\n");
464         fprintf(stderr, "   -p chr:pos      go directly to this position\n");
465         fprintf(stderr, "   -s STR          display only reads from this sample or grou\n");
466         fprintf(stderr, "\n\n");
467     }
468     else
469     {
470         va_list ap;
471         va_start(ap, format);
472         vfprintf(stderr, format, ap);
473         va_end(ap);
474     }
475     exit(-1);
476 }
477
478
479 int bam_tview_main(int argc, char *argv[])
480 {
481         tview_t *tv;
482     char *samples=NULL, *position=NULL;
483     int c;
484     while ((c = getopt(argc, argv, "s:p:")) >= 0) {
485         switch (c) {
486             case 's': samples=optarg; break;
487             case 'p': position=optarg; break;
488             default: error(NULL);
489         }
490     }
491         if (argc==optind) error(NULL);
492         tv = tv_init(argv[optind], (optind+1>=argc)? 0 : argv[optind+1], samples);
493     if ( position )
494     {
495         int _tid = -1, _beg, _end;
496         bam_parse_region(tv->header, position, &_tid, &_beg, &_end);
497         if (_tid >= 0) { tv->curr_tid = _tid; tv->left_pos = _beg; }
498     }
499         tv_draw_aln(tv, tv->curr_tid, tv->left_pos);
500         tv_loop(tv);
501         tv_destroy(tv);
502         return 0;
503 }
504 #else // #ifdef _HAVE_CURSES
505 #include <stdio.h>
506 #warning "No curses library is available; tview is disabled."
507 int bam_tview_main(int argc, char *argv[])
508 {
509         fprintf(stderr, "[bam_tview_main] The ncurses library is unavailable; tview is not compiled.\n");
510         return 1;
511 }
512 #endif // #ifdef _HAVE_CURSES