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