-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathX11BamCov.cpp
817 lines (712 loc) · 21 KB
/
X11BamCov.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
/*
The MIT License (MIT)
Copyright (c) 2019 Pierre Lindenbaum PhD.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/Xutil.h>
#include <iostream>
#include <vector>
#include <iostream>
#include <stdexcept>
#include <fstream>
#include <sstream>
#include <cmath>
#include <limits.h>
#include <unistd.h>
#include <getopt.h>
#include <cerrno>
#include <htslib/sam.h>
#include <htslib/faidx.h>
#include <htslib/kstring.h>
#include <htslib/khash_str2int.h>
#include "Palette.hh"
#include "Hershey.hh"
using namespace std;
class BamW;
#define THROW_INVALID_ARG(a) do {\
cerr << a << endl;\
ostringstream _os; _os << "[ERROR]" << __FILE__ <<":" << __LINE__ << ": " << a ; \
throw invalid_argument(_os.str());\
} while(0)
typedef short pixel_t;
/** convert string to int */
static int parseInt(const char* s) {
char* p2;
errno=0;
long int i = strtol(s,&p2,10);
if(*p2!=0 || errno!=0) THROW_INVALID_ARG("Bad number \"" << s << "\". Cannot convert to integer.");
return (int)i;
}
/** convert int to string with comma sep */
static string niceInt(int i) {
ostringstream os;
os << i;
string s1(os.str());
string s2;
for(size_t k=0; k < s1.length();k++)
{
if(k>0 && k%3==0) s2.insert(0,",",1);
s2.insert(0,s1,(s1.length()-1)-k,1);
}
return s2;
}
/** return true if s1 starts with s2 */
static bool starts_with(std::string s1,const char* s2) {
size_t len2=strlen(s2);
if(len2> s1.size()) return false;
return s1.compare(0,len2, s2) == 0;
}
/** an interval */
class ChromStartEnd
{
public:
/* chrom */
std::string chrom;
/* start, 1-based, after extending */
int start;
/* end, 1-based, after extending */
int end;
/** remaining element in the bed file , 4th column */
std::string label;
/* start before extending */
int original_start;
/* end, before extending */
int original_end;
/** constructor: accept bed or interval */
ChromStartEnd(std::string line):label("") {
std::string::size_type tab = line.find('\t');
std::string::size_type colon = line.find(':');
std::string::size_type p3;
if(colon!=string::npos && (tab==string::npos || tab > colon) ) {
std::string::size_type p1 = colon;
if(p1==string::npos) THROW_INVALID_ARG("cannot find first tab or colon in " << line) ;
std::string::size_type p2 = line.find('-',p1+1);
if(p2==string::npos) THROW_INVALID_ARG("cannot find hyphen in " << line);
p3 = line.find_first_of(" \t",p2+1);
if(p3==string::npos) p3=line.length();
this->chrom.assign(line.substr(0,p1));
this->start= parseInt(line.substr(p1+1,p2-(p1+1)).c_str());
this->end= parseInt(line.substr(p2+1,(p3-(p2+1))).c_str());
}
else if(tab!=string::npos)
{
std::string::size_type p1 = tab;
std::string::size_type p2 = line.find('\t',p1+1);
if(p2==string::npos) THROW_INVALID_ARG( "cannot find second tab in " << line) ;
std::string::size_type p3 = line.find('\t',p2+1);
if(p3==string::npos) p3=line.length();
this->chrom.assign(line.substr(0,p1));
this->start= 1 + parseInt(line.substr(p1+1,p2-(p1+1)).c_str());
this->end= parseInt(line.substr(p2+1,(p3-(p2+1))).c_str());
}
else
{
THROW_INVALID_ARG("Bad interval " << line);
}
if(this->chrom.empty()) THROW_INVALID_ARG("Empty chrom in " << line);
if(this->start >= this->end) THROW_INVALID_ARG("Empty/negative interval " << line);
if(p3<line.size()) {
this->label.assign(line.substr(p3+1));
}
this->original_start = this->start;
this->original_end = this->end;
}
int length() {
return 1+ (this->end - this->start);
}
};
class X11BamCov
{
public:
Display *display;
Screen *screen;
int screen_number;
Window window;
std::vector<BamW*> bams;
std::vector<ChromStartEnd*> regions;
size_t region_idx;
int window_width;
int window_height;
Hershey hershey;
float extend_factor;
int num_columns;
Palette* palette;
int cap_depth;
bool show_sample_name;
int smooth_factor;
X11BamCov();
~X11BamCov();
int doWork(int argc,char** argv);
void repaint();
void paint();
void resized();
void usage(std::ostream& out);
};
class BamW
{
public:
X11BamCov* owner;
std::string filename;
std::string sample;
std::vector<float> coverage;
samFile *fp;
bam_hdr_t *hdr; // the file header
hts_idx_t *idx = NULL;
bool bad_flag;
double max_depth;
XRectangle bounds;
BamW(X11BamCov* owner,std::string fn);
~BamW();
};
BamW::BamW(X11BamCov* owner,std::string fn):owner(owner),filename(fn),sample(fn) {
fp = ::hts_open(fn.c_str(), "r");
if(fp==NULL) {
cerr << "Cannot open " << fn << ". " << ::strerror(errno) << endl;
exit(EXIT_FAILURE);
}
hdr = sam_hdr_read(fp);
if (hdr == NULL) {
cerr << "Cannot open header for " << fn << "." << endl;
exit(EXIT_FAILURE);
}
idx = sam_index_load(this->fp,fn.c_str());
if(idx==NULL) {
cerr << "Cannot open index for " << fn << "." << endl;
exit(EXIT_FAILURE);
}
if(hdr->text!=NULL)
{
std::istringstream iss(hdr->text);
std::string line;
while(std::getline(iss, line, '\n'))
{
if(!starts_with(line,"@RG\t")) continue;
string::size_type p = line.find("\tSM:");
if(p==string::npos) continue;
p+=4;
string::size_type p2 = line.find("\t",p);
if(p2==string::npos) p2=line.size();
sample = line.substr(p,(p2-p));
break;
}
}
}
BamW::~BamW() {
::hts_idx_destroy(idx);
::bam_hdr_destroy(hdr);
::hts_close(fp);
}
X11BamCov::X11BamCov():palette(0),show_sample_name(true),smooth_factor(20) {
region_idx = 0UL;
window_width = 0;
window_height = 0;
num_columns = 1 ;
extend_factor = 0.0f;
cap_depth = -1;
}
X11BamCov::~X11BamCov() {
for(auto iter:bams) {
delete iter;
}
for(auto iter:regions) {
delete iter;
}
if(palette!=0) delete palette;
}
#define MARGIN_TOP 20
void X11BamCov::paint() {
GC gc = ::XCreateGC(this->display, this->window, 0, 0);
XSetForeground(this->display, gc, WhitePixel(this->display, this->screen_number));
::XFillRectangle(this->display,this->window, gc,0,0,this->window_width,this->window_height);
double max_depth = 1.0;
for(auto bam: this->bams) {
max_depth = std::max(max_depth,bam->max_depth);
}
for(auto bam: this->bams) {
bam->max_depth = max_depth;
}
XSetForeground(this->display, gc, BlackPixel(this->display, this->screen_number));
ChromStartEnd* rgn = this->regions[this->region_idx];
string win_title;
{
ostringstream os;
os << rgn->chrom << ":" << niceInt(rgn->start) << "-" << niceInt(rgn->end);
win_title.assign(os.str());
XStoreName(this->display,this->window,win_title.c_str());
}
{
ostringstream os;
os << win_title
<< " maxDepth:"<< max_depth << " length: "<< niceInt(rgn->length())
<< " \"" << rgn->label << "\" "
<< " (" << niceInt(this->region_idx+1) << "/"
<< niceInt((int)this->regions.size()) << ")"
;
string title= os.str();
int title_width= title.size()*12;
hershey.paint(this->display,this->window, gc,title.c_str(),
this->window_width/2 - title_width/2,
1,
title_width,
MARGIN_TOP-2
);
}
for(auto bam: this->bams) {
int ruledy=1.0;
if(bam->max_depth>100) {
ruledy=100;
} if(bam->max_depth>50) {
ruledy=10;
} else if(bam->max_depth>10) {
ruledy=5;
}else
{
ruledy=1;
}
vector<XPoint> points;
XPoint pt1={(pixel_t)bam->bounds.x,(pixel_t)(bam->bounds.y+bam->bounds.height)};
points.push_back(pt1);
for(size_t i=0;i< bam->coverage.size();i++)
{
double h = (bam->coverage[i]/bam->max_depth)*bam->bounds.height;
XPoint pt;
pt.x = (pixel_t)(bam->bounds.x+i);
pt.y = (pixel_t)(bam->bounds.y+bam->bounds.height - h);
points.push_back(pt);
}
XPoint pt2={
(pixel_t)(bam->bounds.width+bam->bounds.x),
(pixel_t)(bam->bounds.y+bam->bounds.height)
};
points.push_back(pt2);
points.push_back(pt1);
if(rgn->start!=rgn->original_start || rgn->end!=rgn->original_end) {
pixel_t x1 = (pixel_t)(bam->bounds.x + ((rgn->original_start-rgn->start)/(double)rgn->length())*bam->bounds.width);
pixel_t x2 = (pixel_t)(bam->bounds.x + ((rgn->original_end-rgn->start)/(double)rgn->length())*bam->bounds.width);
XSetForeground(this->display, gc,palette->gray(0.9).pixel);
::XFillRectangle(this->display,this->window, gc,x1,bam->bounds.y,(x2-x1),bam->bounds.height);
}
// print ruler
double curr_depth = ruledy;
while(curr_depth <= bam->max_depth) {
double y = bam->bounds.y + bam->bounds.height- ((curr_depth/bam->max_depth) * bam->bounds.height);
if(y < bam->bounds.y) break;
XSetForeground(this->display, gc,palette->gray(0.8).pixel);
XDrawLine(this->display, this->window, gc, (int)bam->bounds.x, (int)y,(int)(bam->bounds.x+bam->bounds.width), (int)y);
curr_depth+=ruledy;
}
XSetForeground(this->display, gc,palette->dark_slate_gray.pixel);
::XFillPolygon(this->display,this->window, gc, &points[0], (int)points.size(), Complex,CoordModeOrigin);
curr_depth = ruledy;
while(curr_depth <= bam->max_depth) {
double y = bam->bounds.y + bam->bounds.height- ((curr_depth/bam->max_depth) * bam->bounds.height);
if(y < bam->bounds.y) break;
XSetForeground(this->display, gc,palette->gray(0.8).pixel);
XSetFunction(this->display, gc, GXxor);
XDrawLine(this->display, this->window, gc, (int)bam->bounds.x, (int)y,(int)(bam->bounds.x+bam->bounds.width), (int)y);
XSetFunction(this->display, gc, GXcopy);
XSetForeground(this->display, gc,palette->gray(0.5).pixel);
char tmp[20];
sprintf(tmp,"%d",(int)curr_depth);
if(y-7 > bam->bounds.y) {
hershey.paint(this->display,this->window,gc,
tmp,
bam->bounds.x+1,
(int)y-7,
(int)7*strlen(tmp),
7
);
}
curr_depth+=ruledy;
}
if(this->show_sample_name) {
XSetForeground(this->display, gc, palette->gray(0.1).pixel);
hershey.paint(this->display,this->window, gc,bam->sample.c_str(),
bam->bounds.x,
bam->bounds.y+1,
std::min((int)bam->bounds.width,12*(int)bam->sample.size()),
std::min(20,(int)(bam->bounds.height/10))
);
}
XSetForeground(this->display, gc, palette->gray(0.0).pixel);
::XDrawRectangle(this->display,this->window, gc,
bam->bounds.x,
bam->bounds.y,
bam->bounds.width,
bam->bounds.height
);
}
XFlush(this->display);
}
void X11BamCov::repaint() {
int ret = 0;
ChromStartEnd* rgn = this->regions[this->region_idx];
vector<int> coverage;
coverage.resize(rgn->length(),0);
int curr_x=0;
int curr_y=0;
int n_rows = (int) ceil(this->bams.size()/(double)this->num_columns);
if(n_rows<0) n_rows=1;
int rect_w = (this->window_width / this->num_columns);
if(rect_w< 1) return;
int rect_h = ((this->window_height-MARGIN_TOP) /n_rows);
if(rect_h< 1) return;
vector<int> counts;
bam1_t *b = ::bam_init1();
//reload data for each bam
for(auto bam: this->bams) {
counts.clear();
bam->bad_flag = false;
bam->max_depth = 1.0;
bam->bounds.y = MARGIN_TOP + curr_y*rect_h;
bam->bounds.x = curr_x*rect_w;
bam->bounds.width = rect_w;
bam->bounds.height = rect_h;
curr_x++;
if(curr_x>=this->num_columns)
{
curr_x=0;
curr_y++;
}
bam->coverage.clear();
bam->coverage.resize(bam->bounds.width,0);
std::fill(coverage.begin(),coverage.end(),0);
int tid = ::bam_name2id(bam->hdr, rgn->chrom.c_str());
if(tid<0 && starts_with(rgn->chrom,"chr"))
{
string ctg2 = rgn->chrom.substr(3);
tid = ::bam_name2id(bam->hdr, ctg2.c_str());
}
if(tid<0 && !starts_with(rgn->chrom,"chr"))
{
string ctg2 = "chr";
ctg2.append(rgn->chrom);
tid = ::bam_name2id(bam->hdr, ctg2.c_str());
}
if(tid<0) {
bam->bad_flag = true;
cerr << "[WARN] No chromosome " << rgn->chrom << " in "<< bam ->filename << endl;
continue;
}
hts_itr_t *iter = ::sam_itr_queryi(bam->idx, tid,rgn->start,rgn->end);
while ((ret = bam_itr_next(bam->fp, iter, b)) >= 0)
{
const bam1_core_t *c = &b->core;
if ( c->flag & (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) ) continue;
uint32_t *cigar = bam_get_cigar(b);
if(cigar==NULL) continue;
int ref1 = c->pos + 1;
for (unsigned int icig=0; icig< c->n_cigar && ref1 < rgn->end; icig++)
{
int op = bam_cigar_opchr(cigar[icig]);
int len = bam_cigar_oplen(cigar[icig]);
switch(op)
{
case 'P': break;
case 'I': break;
case 'D': case 'N' : ref1+=len; break;
case 'S': case 'H':break;
case 'M': case '=' : case 'X':
{
for(int x=0;x< len && ref1 < rgn->end ;++x) {
int idx1 = ref1 - rgn->start;
ref1++;
if(idx1< 0 || idx1 >= (int)coverage.size()) continue;
coverage[idx1]++;
bam->max_depth = std::max(bam->max_depth,(double)coverage[idx1]);
}
break;
}
default: cerr << "boum ??" <<(char) op<<" " <<(char) BAM_CMATCH << endl;break;
}
}
}
::hts_itr_destroy(iter);
if(this->cap_depth>0) bam->max_depth=std::min(bam->max_depth,(double)this->cap_depth);
int smooth=0;
if(smooth_factor>1) smooth = (int)(coverage.size()/(double)this->smooth_factor);
if(smooth>0) {
vector<int> smoothed;
smoothed.resize(coverage.size(),0);
std::fill(smoothed.begin(),smoothed.end(),0);
for(int i=0;i< (int)coverage. size();i++)
{
double total=0;
int count=0;
for(int j=std::max(0,i-smooth);j<i+smooth;++j)
{
if(j<0 || j>= (int)coverage.size()) continue;
total += coverage[j];
count++;
}
if(count==0) continue;
smoothed[i]=(int)(total/count);
}
for(int i=0;i< (int)coverage. size();i++)
{
coverage[i]=smoothed[i];
}
}
for(int i=0;i< (int)bam->coverage.size();i++)
{
int g1 = (i/(double)bam->coverage.size())*coverage.size();
int g2 = ((i+1)/(double)bam->coverage.size())*coverage.size();
double total=0;
int count=0;
for(int x=g1;x<=g2 && x < (int)coverage.size();++x)
{
total+= coverage[x];
count++;
}
if(count==0) continue;
bam->coverage[i]= total/count;
if(this->cap_depth>0) bam->coverage[i] = std::min(bam->coverage[i],(float)this->cap_depth);
}
}
::bam_destroy1(b);
paint();
}
void X11BamCov::resized() {
//int x,y,wr;
//unsigned int w,h,bw, d;
XWindowAttributes att;
::XGetWindowAttributes(display, window, &att);
if(att.width!=this->window_width || att.height!=this->window_height) {
this->window_width = att.width;
this->window_height = att.height;
repaint();
}
}
void X11BamCov::usage(std::ostream& out)
{
out << "cnv" << endl;
out << "Motivation:\n Displays Bam coverage" << endl;
out << "Keys:\n";
out << " 'S' save current segment in output file. See option '-o'.\n";
out << " '<-' previous interval\n";
out << " '->' next interval\n";
out << " 'R'/'T' change column number\n";
out << " 'Q'/'Esc' exit\n";
out << " 'N' toggle show/hide sample name\n";
out << "Options:\n";
out << " -h print help and exit\n";
out << " -v print version and exit\n";
out << " -o (FILE) save BED segment in that bed file (use key 'S')\n";
out << " -D (int) cap depth to that value. Negative=ignore [-1]\n";
out << " -B (FILE) list of path to indexed bam files\n";
out << " -R (FILE) bed file of regions of interest. optional 4th column is used as a label\n";
out << " -f (float) extend the regions by this factor. e.g: 0.3 [" << extend_factor << "]\n";
out << " -s (int) smooth factor. Smooth using a sliding window of 'region-length'/'s'. 0=ignore. [" << smooth_factor<<"]\n";
}
int X11BamCov::doWork(int argc,char** argv) {
char* bam_list = NULL;
char* region_list = NULL;
char *file_out = NULL;
int opt;
if(argc<=1) {
usage(cerr);
return EXIT_FAILURE;
}
while ((opt = getopt(argc, argv, "B:R:f:D:o:vhs:")) != -1) {
switch (opt) {
case 'h':
usage(cout);
return 0;
case 'v':
cout << "cnv\nAuthor: Pierre Lindenbaum PhD.\nCompilation: " << __DATE__ << endl;
return 0;
case 'o':
file_out = optarg;
break;
case 'D':
this->cap_depth = atoi(optarg);
break;
case 'B':
bam_list = optarg;
break;
case 'R':
region_list = optarg;
break;
case 'f':
this->extend_factor = atof(optarg);
break;
case 's':
this->smooth_factor = atof(optarg);
break;
case '?':
cerr << "unknown option -"<< (char)optopt << endl;
return EXIT_FAILURE;
default: /* '?' */
cerr << "unknown option" << endl;
return EXIT_FAILURE;
}
}
if(optind!=argc) {
cerr << "Illegal number of arguments." << endl;
return EXIT_FAILURE;
}
//
if(bam_list == NULL) {
cerr << "List of bams is undefined." << endl;
return EXIT_FAILURE;
}
ifstream bamin(bam_list);
if(!bamin.is_open()) {
cerr << "Cannot open " << bam_list << endl;
return EXIT_FAILURE;
}
string line;
while(getline(bamin,line)) {
if(line.empty() || line[0]=='#') continue;
BamW* bamFile = new BamW(this,line);
this->bams.push_back(bamFile);
}
bamin.close();
if(this->bams.empty()) {
cerr << "List of bams is empty." << endl;
return EXIT_FAILURE;
}
this->num_columns = (int)std::ceil(::sqrt(this->bams.size()));
if( this->num_columns <= 0 ) this->num_columns = 1;
//cerr << "[DEBUG]ncols " << num_columns << endl;
//
if(region_list == NULL) {
cerr << "List of regions is undefined." << endl;
return EXIT_FAILURE;
}
ifstream regionin(region_list);
if(!regionin.is_open()) {
cerr << "Cannot open " << region_list << endl;
return EXIT_FAILURE;
}
while(getline(regionin,line)) {
if(line.empty() || line[0]=='#') continue;
ChromStartEnd* rgn = new ChromStartEnd(line);
if(this->extend_factor != 0.0)
{
int L = rgn->length();
int L2 = (int)(L*(1.0+extend_factor));
int mid = rgn->start + L/2;
rgn->start = std::max(1,mid - L2);
rgn->end = mid + L2;
//cerr << "[DEBUG]" << rgn->start << "-" << rgn->end << endl;
}
this->regions.push_back(rgn);
}
regionin.close();
if(this->regions.empty()) {
cerr << "[FAILURE] List of regions is empty." << endl;
return EXIT_FAILURE;
}
//
FILE* saveOut=NULL;
if(file_out!=NULL)
{
saveOut = fopen(file_out,"w");
if(saveOut==NULL) {
cerr << "Cannot open " << file_out << endl;
return EXIT_FAILURE;
}
}
//
this->display = ::XOpenDisplay(NULL);
if (this->display == NULL) {
cerr<< "[FAILURE] Cannot open display." << endl;
return(EXIT_FAILURE);
}
this->screen_number = DefaultScreen(this->display);
this->palette = new Palette(this->display, this->screen_number);
this->screen = ::XScreenOfDisplay(this->display, this->screen_number);
this->window = ::XCreateSimpleWindow(
display,
RootWindow(this->display, this->screen_number),
150, 150,
screen->width-300,
screen->height-300,
1,
BlackPixel(display, this->screen_number),
WhitePixel(display, this->screen_number)
);
::XSelectInput(display, window, ExposureMask | KeyPressMask);
::XMapWindow(display, window);
//main loop
XEvent evt;
bool done=false;
while(!done) {
::XNextEvent(this->display, &evt);
if(evt.type == KeyPress)
{
if (evt.xkey.keycode == XKeysymToKeycode(this->display, XK_Q) ||
evt.xkey.keycode == XKeysymToKeycode(this->display, XK_Escape))
{
done = true;
}
else if (evt.xkey.keycode == XKeysymToKeycode(this->display, XK_Left))
{
region_idx = (region_idx==0UL?regions.size()-1:region_idx-1);
repaint();
}
else if (evt.xkey.keycode == XKeysymToKeycode(this->display, XK_Right))
{
region_idx = (region_idx+1>=regions.size()?0:region_idx+1);
repaint();
}
else if (evt.xkey.keycode == XKeysymToKeycode(this->display, XK_S) && saveOut!=NULL)
{
ChromStartEnd* rgn = this->regions[this->region_idx];
fprintf(saveOut,"%s\t%d\t%d\n",
rgn->chrom.c_str(),
rgn->original_start-1,
rgn->original_end
);
cerr << "[INFO] SAVED" << endl;
}
else if (evt.xkey.keycode == XKeysymToKeycode(this->display, XK_R) && num_columns>1)
{
num_columns--;
repaint();
}
else if (evt.xkey.keycode == XKeysymToKeycode(this->display, XK_T) && num_columns+1<= (int)this->bams.size())
{
num_columns++;
repaint();
}
else if (evt.xkey.keycode == XKeysymToKeycode(this->display, XK_N))
{
show_sample_name = !show_sample_name;
repaint();
}
}
else if(evt.type == Expose)
{
resized();
}
}//end while
::XCloseDisplay(display);
display=NULL;
if(saveOut!=NULL)
{
fclose(saveOut);
}
return 0;
}
int main_cnv(int argc,char** argv) {
X11BamCov app;
return app.doWork(argc,argv);
}