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