Imported Upstream version 0.1.5c
[samtools.git] / bam_tview.c
1 #ifndef _NO_CURSES
2 #include <curses.h>
3 #ifdef NCURSES_VERSION
4 #include <ctype.h>
5 #include <assert.h>
6 #include <string.h>
7 #include "bam.h"
8 #include "faidx.h"
9 #include "bam_maqcns.h"
10
11 char bam_aux_getCEi(bam1_t *b, int i);
12 char bam_aux_getCSi(bam1_t *b, int i);
13 char bam_aux_getCQi(bam1_t *b, int i);
14
15 #define TV_MIN_ALNROW 2
16 #define TV_MAX_GOTO  40
17 #define TV_LOW_MAPQ  10
18
19 #define TV_COLOR_MAPQ   0
20 #define TV_COLOR_BASEQ  1
21 #define TV_COLOR_NUCL   2
22 #define TV_COLOR_COL    3
23 #define TV_COLOR_COLQ   4
24
25 #define TV_BASE_NUCL 0
26 #define TV_BASE_COLOR_SPACE 1
27
28 typedef struct {
29         int mrow, mcol;
30         WINDOW *wgoto, *whelp;
31
32         bam_index_t *idx;
33         bam_lplbuf_t *lplbuf;
34         bam_header_t *header;
35         bamFile fp;
36         int curr_tid, left_pos;
37         faidx_t *fai;
38         bam_maqcns_t *bmc;
39
40         int ccol, last_pos, row_shift, base_for, color_for, is_dot, l_ref, ins;
41         char *ref;
42 } tview_t;
43
44 int tv_pl_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pl, void *data)
45 {
46         tview_t *tv = (tview_t*)data;
47         int i, j, c, rb, attr, max_ins = 0;
48         uint32_t call = 0;
49         if (pos < tv->left_pos || tv->ccol > tv->mcol) return 0; // out of screen
50         // print referece
51         rb = (tv->ref && pos - tv->left_pos < tv->l_ref)? tv->ref[pos - tv->left_pos] : 'N';
52         for (i = tv->last_pos + 1; i < pos; ++i) {
53                 if (i%10 == 0) mvprintw(0, tv->ccol, "%-d", i+1);
54                 c = tv->ref? tv->ref[i - tv->left_pos] : 'N';
55                 mvaddch(1, tv->ccol++, c);
56         }
57         if (pos%10 == 0) mvprintw(0, tv->ccol, "%-d", pos+1);
58         // print consensus
59         call = bam_maqcns_call(n, pl, tv->bmc);
60         attr = A_UNDERLINE;
61         c = ",ACMGRSVTWYHKDBN"[call>>28&0xf];
62         i = (call>>8&0xff)/10+1;
63         if (i > 4) i = 4;
64         attr |= COLOR_PAIR(i);
65         if (c == toupper(rb)) c = '.';
66         attron(attr);
67         mvaddch(2, tv->ccol, c);
68         attroff(attr);
69         if(tv->ins) {
70                 // calculate maximum insert
71                 for (i = 0; i < n; ++i) {
72                         const bam_pileup1_t *p = pl + i;
73                         if (p->indel > 0 && max_ins < p->indel) max_ins = p->indel;
74                 }
75         }
76         // core loop
77         for (j = 0; j <= max_ins; ++j) {
78                 for (i = 0; i < n; ++i) {
79                         const bam_pileup1_t *p = pl + i;
80                         int row = TV_MIN_ALNROW + p->level - tv->row_shift;
81                         if (j == 0) {
82                                 if (!p->is_del) {
83                                         if (tv->base_for == TV_BASE_COLOR_SPACE && 
84                                                         (c = bam_aux_getCSi(p->b, p->qpos))) {
85                                                 c = bam_aux_getCSi(p->b, p->qpos);
86                                                 // assume that if we found one color, we will be able to get the color error
87                                                 if (tv->is_dot && '-' == bam_aux_getCEi(p->b, p->qpos)) c = bam1_strand(p->b)? ',' : '.';
88                                         }
89                                         else {
90                                                 c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos)];
91                                                 if (tv->is_dot && toupper(c) == toupper(rb)) c = bam1_strand(p->b)? ',' : '.';
92                                         }
93                                 } else c = '*';
94                         } else { // padding
95                                 if (j > p->indel) c = '*';
96                                 else { // insertion
97                                         if (tv->base_for ==  TV_BASE_NUCL) {
98                                                 c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos + j)];
99                                                 if (j == 0 && tv->is_dot && toupper(c) == toupper(rb)) c = bam1_strand(p->b)? ',' : '.';
100                                         }
101                                         else {
102                                                 c = bam_aux_getCSi(p->b, p->qpos + j);
103                                                 if (tv->is_dot && '-' == bam_aux_getCEi(p->b, p->qpos + j)) c = bam1_strand(p->b)? ',' : '.';
104                                         }
105                                 }
106                         }
107                         if (row > TV_MIN_ALNROW && row < tv->mrow) {
108                                 int x;
109                                 attr = 0;
110                                 if (((p->b->core.flag&BAM_FPAIRED) && !(p->b->core.flag&BAM_FPROPER_PAIR))
111                                                 || (p->b->core.flag & BAM_FSECONDARY)) attr |= A_UNDERLINE;
112                                 if (tv->color_for == TV_COLOR_BASEQ) {
113                                         x = bam1_qual(p->b)[p->qpos]/10 + 1;
114                                         if (x > 4) x = 4;
115                                         attr |= COLOR_PAIR(x);
116                                 } else if (tv->color_for == TV_COLOR_MAPQ) {
117                                         x = p->b->core.qual/10 + 1;
118                                         if (x > 4) x = 4;
119                                         attr |= COLOR_PAIR(x);
120                                 } else if (tv->color_for == TV_COLOR_NUCL) {
121                                         x = bam_nt16_nt4_table[bam1_seqi(bam1_seq(p->b), p->qpos)] + 5;
122                                         attr |= COLOR_PAIR(x);
123                                 } else if(tv->color_for == TV_COLOR_COL) {
124                                         x = 0;
125                                         switch(bam_aux_getCSi(p->b, p->qpos)) {
126                                                 case '0': x = 0; break;
127                                                 case '1': x = 1; break;
128                                                 case '2': x = 2; break;
129                                                 case '3': x = 3; break;
130                                                 case '4': x = 4; break;
131                                                 default: x = bam_nt16_nt4_table[bam1_seqi(bam1_seq(p->b), p->qpos)]; break;
132                                         }
133                                         x+=5;
134                                         attr |= COLOR_PAIR(x);
135                                 } else if(tv->color_for == TV_COLOR_COLQ) {
136                                         x = bam_aux_getCQi(p->b, p->qpos);
137                                         if(0 == x) x = bam1_qual(p->b)[p->qpos];
138                                         x = x/10 + 1;
139                                         if (x > 4) x = 4;
140                                         attr |= COLOR_PAIR(x);
141                                 }
142                                 attron(attr);
143                                 mvaddch(row, tv->ccol, bam1_strand(p->b)? tolower(c) : toupper(c));
144                                 attroff(attr);
145                         }
146                 }
147                 c = j? '*' : rb;
148                 if (c == '*') {
149                         attr = COLOR_PAIR(8);
150                         attron(attr);
151                         mvaddch(1, tv->ccol++, c);
152                         attroff(attr);
153                 } else mvaddch(1, tv->ccol++, c);
154         }
155         tv->last_pos = pos;
156         return 0;
157 }
158
159 tview_t *tv_init(const char *fn, const char *fn_fa)
160 {
161         tview_t *tv = (tview_t*)calloc(1, sizeof(tview_t));
162         tv->is_dot = 1;
163         tv->idx = bam_index_load(fn);
164         if (tv->idx == 0) exit(1);
165         tv->fp = bam_open(fn, "r");
166         bgzf_set_cache_size(tv->fp, 8 * 1024 *1024);
167         assert(tv->fp);
168         tv->header = bam_header_read(tv->fp);
169         tv->lplbuf = bam_lplbuf_init(tv_pl_func, tv);
170         if (fn_fa) tv->fai = fai_load(fn_fa);
171         tv->bmc = bam_maqcns_init();
172         tv->ins = 1;
173         bam_maqcns_prepare(tv->bmc);
174
175         initscr();
176         keypad(stdscr, TRUE);
177         clear();
178         noecho();
179         cbreak();
180 #ifdef NCURSES_VERSION
181         getmaxyx(stdscr, tv->mrow, tv->mcol);
182 #else
183         tv->mrow = 80; tv->mcol = 40;
184 #endif
185         tv->wgoto = newwin(3, TV_MAX_GOTO + 10, 10, 5);
186         tv->whelp = newwin(27, 40, 5, 5);
187         tv->color_for = TV_COLOR_MAPQ;
188         start_color();
189         init_pair(1, COLOR_BLUE, COLOR_BLACK);
190         init_pair(2, COLOR_GREEN, COLOR_BLACK);
191         init_pair(3, COLOR_YELLOW, COLOR_BLACK);
192         init_pair(4, COLOR_WHITE, COLOR_BLACK);
193         init_pair(5, COLOR_GREEN, COLOR_BLACK);
194         init_pair(6, COLOR_CYAN, COLOR_BLACK);
195         init_pair(7, COLOR_YELLOW, COLOR_BLACK);
196         init_pair(8, COLOR_RED, COLOR_BLACK);
197         init_pair(9, COLOR_BLUE, COLOR_BLACK);
198         return tv;
199 }
200
201 void tv_destroy(tview_t *tv)
202 {
203         delwin(tv->wgoto); delwin(tv->whelp);
204         endwin();
205
206         bam_lplbuf_destroy(tv->lplbuf);
207         bam_maqcns_destroy(tv->bmc);
208         bam_index_destroy(tv->idx);
209         if (tv->fai) fai_destroy(tv->fai);
210         free(tv->ref);
211         bam_header_destroy(tv->header);
212         bam_close(tv->fp);
213         free(tv);
214 }
215
216 int tv_fetch_func(const bam1_t *b, void *data)
217 {
218         tview_t *tv = (tview_t*)data;
219         bam_lplbuf_push(b, tv->lplbuf);
220         return 0;
221 }
222
223 int tv_draw_aln(tview_t *tv, int tid, int pos)
224 {
225         // reset
226         clear();
227         tv->curr_tid = tid; tv->left_pos = pos;
228         tv->last_pos = tv->left_pos - 1;
229         tv->ccol = 0;
230         // print ref and consensus
231         if (tv->fai) {
232                 char *str;
233                 if (tv->ref) free(tv->ref);
234                 str = (char*)calloc(strlen(tv->header->target_name[tv->curr_tid]) + 30, 1);
235                 sprintf(str, "%s:%d-%d", tv->header->target_name[tv->curr_tid], tv->left_pos + 1, tv->left_pos + tv->mcol);
236                 tv->ref = fai_fetch(tv->fai, str, &tv->l_ref);
237                 free(str);
238         }
239         // draw aln
240         bam_lplbuf_reset(tv->lplbuf);
241         bam_fetch(tv->fp, tv->idx, tv->curr_tid, tv->left_pos, tv->left_pos + tv->mcol, tv, tv_fetch_func);
242         bam_lplbuf_push(0, tv->lplbuf);
243         return 0;
244 }
245
246 static void tv_win_goto(tview_t *tv, int *tid, int *pos)
247 {
248         char str[256];
249         int i, l = 0;
250         wborder(tv->wgoto, '|', '|', '-', '-', '+', '+', '+', '+');
251         mvwprintw(tv->wgoto, 1, 2, "Goto: ");
252         for (;;) {
253                 int c = wgetch(tv->wgoto);
254                 wrefresh(tv->wgoto);
255                 if (c == KEY_BACKSPACE || c == '\010' || c == '\177') {
256                         --l;
257                 } else if (c == KEY_ENTER || c == '\012' || c == '\015') {
258                         int _tid = -1, _beg, _end;
259                         bam_parse_region(tv->header, str, &_tid, &_beg, &_end);
260                         if (_tid >= 0) {
261                                 *tid = _tid; *pos = _beg;
262                                 return;
263                         }
264                 } else if (isgraph(c)) {
265                         if (l < TV_MAX_GOTO) str[l++] = c;
266                 } else if (c == '\027') l = 0;
267                 else if (c == '\033') return;
268                 str[l] = '\0';
269                 for (i = 0; i < TV_MAX_GOTO; ++i) mvwaddch(tv->wgoto, 1, 8 + i, ' ');
270                 mvwprintw(tv->wgoto, 1, 8, "%s", str);
271         }
272 }
273
274 static void tv_win_help(tview_t *tv) {
275         int r = 1;
276         WINDOW *win = tv->whelp;
277         wborder(win, '|', '|', '-', '-', '+', '+', '+', '+');
278         mvwprintw(win, r++, 2, "        -=-    Help    -=- ");
279         r++;
280         mvwprintw(win, r++, 2, "?          This window");
281         mvwprintw(win, r++, 2, "Arrows     Small scroll movement");
282         mvwprintw(win, r++, 2, "h,j,k,l    Small scroll movement");
283         mvwprintw(win, r++, 2, "H,J,K,L    Large scroll movement");
284         mvwprintw(win, r++, 2, "ctrl-H     Scroll 1k left");
285         mvwprintw(win, r++, 2, "ctrl-L     Scroll 1k right");
286         mvwprintw(win, r++, 2, "space      Scroll one screen");
287         mvwprintw(win, r++, 2, "backspace  Scroll back one screen");
288         mvwprintw(win, r++, 2, "g          Go to specific location");
289         mvwprintw(win, r++, 2, "m          Color for mapping qual");
290         mvwprintw(win, r++, 2, "n          Color for nucleotide");
291         mvwprintw(win, r++, 2, "b          Color for base quality");
292         mvwprintw(win, r++, 2, "c          Color for cs color");
293         mvwprintw(win, r++, 2, "z          Color for cs qual");
294         mvwprintw(win, r++, 2, ".          Toggle on/off dot view");
295         mvwprintw(win, r++, 2, "N          Turn on nt view");
296         mvwprintw(win, r++, 2, "C          Turn on cs view");
297         mvwprintw(win, r++, 2, "i          Toggle on/off ins");
298         mvwprintw(win, r++, 2, "q          Exit");
299         r++;
300         mvwprintw(win, r++, 2, "Underline:      Secondary or orphan");
301         mvwprintw(win, r++, 2, "Blue:    0-9    Green: 10-19");
302         mvwprintw(win, r++, 2, "Yellow: 20-29   White: >=30");
303         wrefresh(win);
304         wgetch(win);
305 }
306
307 void tv_loop(tview_t *tv)
308 {
309         int tid, pos;
310         tid = tv->curr_tid; pos = tv->left_pos;
311         while (1) {
312                 int c = getch();
313                 //if(256 < c) {c = 1 + (c%256);} // Terminal was displaying ctrl-H as 263 via ssh from Mac OS X 10.5 computer 
314                 switch (c) {
315                         case '?': tv_win_help(tv); break;
316                         case '\033':
317                         case 'q': goto end_loop;
318                         case 'g': tv_win_goto(tv, &tid, &pos); break;
319                         case 'm': tv->color_for = TV_COLOR_MAPQ; break;
320                         case 'b': tv->color_for = TV_COLOR_BASEQ; break;
321                         case 'n': tv->color_for = TV_COLOR_NUCL; break;
322                         case 'c': tv->color_for = TV_COLOR_COL; break;
323                         case 'z': tv->color_for = TV_COLOR_COLQ; break;
324                         case KEY_LEFT:
325                         case 'h': --pos; break;
326                         case KEY_RIGHT:
327                         case 'l': ++pos; break;
328                         case KEY_SLEFT:
329                         case 'H': pos -= 20; break;
330                         case KEY_SRIGHT:
331                         case 'L': pos += 20; break;
332                         case '.': tv->is_dot = !tv->is_dot; break;
333                         case 'N': tv->base_for = TV_BASE_NUCL; break;
334                         case 'C': tv->base_for = TV_BASE_COLOR_SPACE; break;
335                         case 'i': tv->ins = !tv->ins; break;
336                         case '\010': pos -= 1000; break;
337                         case '\014': pos += 1000; break;
338                         case ' ': pos += tv->mcol; break;
339                         case KEY_UP:
340                         case 'j': --tv->row_shift; break;
341                         case KEY_DOWN:
342                         case 'k': ++tv->row_shift; break;
343                         case KEY_BACKSPACE:
344                         case '\177': pos -= tv->mcol; break;
345 #ifdef KEY_RESIZE
346                         case KEY_RESIZE: getmaxyx(stdscr, tv->mrow, tv->mcol); break;
347 #endif
348                         default: continue;
349                 }
350                 if (pos < 0) pos = 0;
351                 if (tv->row_shift < 0) tv->row_shift = 0;
352                 tv_draw_aln(tv, tid, pos);
353         }
354 end_loop:
355         return;
356 }
357
358 int bam_tview_main(int argc, char *argv[])
359 {
360         tview_t *tv;
361         if (argc == 1) {
362                 fprintf(stderr, "Usage: bamtk tview <aln.bam> [ref.fasta]\n");
363                 return 1;
364         }
365         tv = tv_init(argv[1], (argc == 2)? 0 : argv[2]);
366         tv_draw_aln(tv, 0, 0);
367         tv_loop(tv);
368         tv_destroy(tv);
369         return 0;
370 }
371 #else // #ifdef NCURSES_VERSION
372 #warning "The ncurses library is unavailable; tview is disabled."
373 int bam_tview_main(int argc, char *argv[])
374 {
375         fprintf(stderr, "[bam_tview_main] The ncurses library is unavailable; tview is not compiled.\n");
376         return 1;
377 }
378 #endif
379 #endif // #ifndef _NO_CURSES