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