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