-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
655 lines (608 loc) · 30.8 KB
/
main.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
#include <iomanip>
#include <limits.h>
#include <unistd.h>
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <ostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include "reads.h"
#include "refbase.h"
#include "align.h"
#include "param.h"
#include "pairs.h"
#include "utilities.h"
#ifdef THREAD
#include <pthread.h>
#endif
using namespace std;
//global variables
Param param;
string query_a_file;
string query_b_file;
string ref_file;
string out_align_file;
string command_line;
string conversion_rule;
ifstream fin_db; igzstream gzfin_db;
ifstream fin_a; igzstream gzfin_a;
ifstream fin_b; igzstream gzfin_b;
ofstream fout;
FILE *pout;
ReadClass read_a, read_b;
RefSeq refseq_ref;
bit32_t n_aligned=0, n_unique=0, n_multiple=0; //number of reads aligned
bit32_t n_aligned_pairs=0, n_unique_pairs=0, n_multiple_pairs=0; //number of pairs aligned
bit32_t n_aligned_a=0, n_unique_a=0, n_multiple_a=0; //number of a reads aligned
bit32_t n_aligned_b=0, n_unique_b=0, n_multiple_b=0; //number of b reads aligned
bit32_t ref_time, read_time;
bit16_t tid[64];
char version[] = "1.8.1";
ostringstream message;
void info(int level) {
if(level<=param.verbose_level) cerr<<message.str();
message.str("");
}
#ifdef THREAD
pthread_mutex_t mutex_fin=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_fout=PTHREAD_MUTEX_INITIALIZER;
void *t_SingleAlign(void *tid) {
SingleAlign a;
int n;
bit32_t cur_at;
while(1) {
pthread_mutex_lock(&mutex_fin);
n=read_a.LoadBatchReads(fin_a,gzfin_a,0);
cur_at=read_a._index;
a.ImportBatchReads(read_a.num, read_a.mreads);
pthread_mutex_unlock(&mutex_fin);
if(!n) break;
a.Do_Batch(refseq_ref);
pthread_mutex_lock(&mutex_fout);
if(param.stdout) cout<<a._str_align;
else if(param.pipe_out) {fwrite(a._str_align.c_str(),1,a._str_align.size(),pout); fflush(pout);}
else fout<<a._str_align;
message<<"[BASAL @"<<Curr_Time()<<"] "<<cur_at-param.read_start+1<<" reads finished. "<<Cal_AllTime()<<" secs passed"<<endl; info(2);
pthread_mutex_unlock(&mutex_fout);
}
pthread_mutex_lock(&mutex_fout);
n_aligned+=a.n_aligned; n_unique+=a.n_unique; n_multiple+=a.n_multiple;
pthread_mutex_unlock(&mutex_fout);
read_time+=Cal_AllTime()-ref_time;
return NULL;
};
void Do_SingleAlign() {
vector<pthread_t> pthread_ids(param.num_procs);
for(int i=0; i<param.num_procs; i++) {
tid[i]=i; pthread_create(&pthread_ids[i], NULL, t_SingleAlign, (void*)&tid[i]);
}
for(int i=0; i<param.num_procs; i++) pthread_join(pthread_ids[i], NULL);
};
void *t_PairAlign(void *tid) {
PairAlign a;
int n1, n2;
bit32_t cur_at;
while(1) {
pthread_mutex_lock(&mutex_fin);
n1=read_a.LoadBatchReads(fin_a,gzfin_a,1);
n2=read_b.LoadBatchReads(fin_b,gzfin_b,2);
cur_at=read_a._index;
a.ImportBatchReads(n1, read_a.mreads, read_b.mreads);
pthread_mutex_unlock(&mutex_fin);
if(!n1||(n1!=n2)) break;
a.Do_Batch(refseq_ref);
pthread_mutex_lock(&mutex_fout);
if(param.stdout) cout<<a._str_align;
else if(param.pipe_out) {fwrite(a._str_align.c_str(),1,a._str_align.size(),pout); fflush(pout);}
else fout<<a._str_align;
message<<"[BASAL @"<<Curr_Time()<<"] "<<cur_at-param.read_start+1<<" read pairs finished. "<<Cal_AllTime()<<" secs passed"<<endl;info(2);
pthread_mutex_unlock(&mutex_fout);
}
pthread_mutex_lock(&mutex_fout);
n_aligned_pairs+=a.n_aligned_pairs; n_unique_pairs+=a.n_unique_pairs; n_multiple_pairs+=a.n_multiple_pairs;
n_aligned_a+=a.n_aligned_a; n_unique_a+=a.n_unique_a; n_multiple_a+=a.n_multiple_a;
n_aligned_b+=a.n_aligned_b; n_unique_b+=a.n_unique_b; n_multiple_b+=a.n_multiple_b;
pthread_mutex_unlock(&mutex_fout);
read_time+=Cal_AllTime()-ref_time;
return NULL;
};
void Do_PairAlign() {
vector<pthread_t> pthread_ids(param.num_procs);
for(int i=0; i<param.num_procs; i++) {
tid[i]=i; pthread_create(&pthread_ids[i], NULL, t_PairAlign, (void*)&tid[i]);
}
for(int i=0; i<param.num_procs; i++) pthread_join(pthread_ids[i], NULL);
};
void* wrapper_CalKmerFreq0(void*) {refseq_ref.t_CalKmerFreq(0); return NULL;}
void* wrapper_CalKmerFreq1(void*) {refseq_ref.t_CalKmerFreq(1); return NULL;}
void* wrapper_FillIndex0(void*) {refseq_ref.t_FillIndex(0); return NULL;}
void* wrapper_FillIndex1(void*) {refseq_ref.t_FillIndex(1); return NULL;}
void Do_Formatdb() {
if(param.RRBS_flag) refseq_ref.CreateIndex();
else {
pthread_t t0, t1;
refseq_ref.InitialIndex();
pthread_create(&t0, NULL, wrapper_CalKmerFreq0, NULL);
pthread_create(&t1, NULL, wrapper_CalKmerFreq1, NULL);
pthread_join(t0, NULL); pthread_join(t1, NULL);
refseq_ref.AllocIndex();
pthread_create(&t0, NULL, wrapper_FillIndex0, NULL);
pthread_create(&t1, NULL, wrapper_FillIndex1, NULL);
pthread_join(t0, NULL); pthread_join(t1, NULL);
refseq_ref.FinishIndex();
}
message<<"[BASAL @"<<Curr_Time()<<"] create seed table. "<<Cal_AllTime()<<" secs passed\n"; info(1);
};
#else
void Do_SingleAlign() {
SingleAlign a;
while(read_a.LoadBatchReads(fin_a,gzfin_a,0)) {
a.ImportBatchReads(read_a.num, read_a.mreads);
a.Do_Batch(refseq_ref);
if(param.stdout) cout<<a._str_align;
else if(param.pipe_out) {fwrite(a._str_align.c_str(),1,a._str_align.size(),pout); fflush(pout);}
else fout<<a._str_align;
message<<"[BASAL @"<<Curr_Time()<<"] "<<read_a._index-param.read_start+1<<" reads finished. "<<Cal_AllTime()<<" secs passed"<<endl; info(2);
}
n_aligned=a.n_aligned; n_unique=a.n_unique; n_multiple=a.n_multiple;
read_time+=Cal_AllTime()-ref_time;
};
void Do_PairAlign() {
PairAlign a;
int n1, n2;
while(1) {
n1=read_a.LoadBatchReads(fin_a,gzfin_a,1);
n2=read_b.LoadBatchReads(fin_b,gzfin_b,2);
if(!n1||(n1!=n2))
break;
a.ImportBatchReads(n1, read_a.mreads, read_b.mreads);
a.Do_Batch(refseq_ref);
if(param.stdout) cout<<a._str_align;
else if(param.pipe_out) {fwrite(a._str_align.c_str(),1,a._str_align.size(),pout); fflush(pout);}
else fout<<a._str_align;
message<<"[BASAL @"<<Curr_Time()<<"] "<<read_a._index-param.read_start+1<<" read pairs finished. "<<Cal_AllTime()<<" secs passed"<<endl; info(2);
}
n_aligned_pairs+=a.n_aligned_pairs; n_unique_pairs+=a.n_unique_pairs; n_multiple_pairs+=a.n_multiple_pairs;
n_aligned_a+=a.n_aligned_a; n_unique_a+=a.n_unique_a; n_multiple_a+=a.n_multiple_a;
n_aligned_b+=a.n_aligned_b; n_unique_b+=a.n_unique_b; n_multiple_b+=a.n_multiple_b;
read_time+=Cal_AllTime()-ref_time;
};
void Do_Formatdb() {
refseq_ref.CreateIndex();
message<<"[BASAL @"<<Curr_Time()<<"] create seed table. "<<Cal_AllTime()<<" secs passed\n"; info(1);
};
#endif
//usage
void usage(void)
{
cerr<<" ___ __ __ __ _ \n"
<<" | |_) / /\\ ( (` / /\\ | | \n"
<<" |_|_) /_/--\\ _)_) /_/--\\ |_|__ \n"
<<"\nWelcome to use BASAL [Version "<<version<<"]\n"
<<"BASAL is designed for reads mapping of nucleotide Base-Conversion(BC) sequencing. It is conversion-sensitive and\n"
<<"supports most kinds of RNA/DNA modification detecting techniques based on BC (Please check the option -M).\n"
<<"Its versatile bitwise operations make it compatible with both one-way and multi-way conversion data. \n"
<<"Moreover, it doesn't require pre-built index files of reference sequences, thus conserving space and memory.\n"
<<"\nUsage: basal [options]"
<<"\n Options for input/output files:\n"
<<" -a <str> input reads in FASTA/FASTQ/BAM format [Required option]\n"
<<" -b <str> input reads which is paired with -a, (default: none, single-end)\n"
<<" -d <str> reference sequences in FASTA format [Required option]\n"
<<" -o <str> output alignment in SAM/BAM format, if omitted, the output will be written to STDOUT in SAM format.\n"
<<"\n Options for base-conversion:\n"
<<" -M <str> the convert-from and convert-to base(s) seperated by ':' [Required option] \n"
<<" the convert-from base must be single letter from [A,T,C,G], \n"
<<" the convert-to base(s) can be single or multiple letters from [A,T,C,G,-], '-' represents deletion. \n"
<<" Note that U in RNA is represented by T. \n"
<<" examples:\n"
<<" -M C:T can detect C>T conversion(e.g. DNA bisulfite seq) \n"
<<" -M A:G can detect A>G conversion in RNA m6A seq(e.g. GLORI) or DNA 6mA seq(e.g. NT-seq) \n"
<<" -M A:CGT can detect RNA m1A in m1A-IP-seq, which convert A to C/G/T \n"
<<" -M T:- can detect pseudouridine in BID-seq, which convert pseudouridine to deletion \n"
<<" -M G:ACT- can detect RNA m7G in m7G-quant-seq, which convert G to A/C/T/deletion \n"
<<"\n Options for alignment:\n"
<<" -v <float> maximum percentage/number of mismatch bases in each read. (default: "<<(param.max_snp_num-100)/100.0<<") \n"
<<" The float value(between 0 and 1) is interpreted as the percentage of read length.\n"
<<" The integer value is interpreted as absolute number of mismatches.\n"
<<" The maximum mismatches will be reduced to "<<MAXSNPS<<" if it exceed "<<MAXSNPS<<".\n"
<<" -g <int> maximum size of gap (deletion/insertion), <="<<MAXGAPS<<" bp. default: "<<param.gap<<"\n"
<<" -w <int> maximum number of equal best hits to count, <="<<MAXHITS<<"\n"
<<" -B <int> start from the Nth read or read pair, default: 1\n"
<<" -E <int> end at the Nth read or read pair, default: 4,294,967,295\n"
<<" -I <int> index interval (1~16), the reference genome will be indexed every Nbp, default: "<<param.index_interval<<". Larger -I uses less memory.\n"
<<" -k <float> the cut-off ratio for over-represented kmers, default: "<<param.max_kmer_ratio<<"\n"
<<" example: -k 1e-6 means the top 0.0001\% over-represented kmer will be skipped in alignment\n"
<<" -s <int> seed size (8~16), default: 16.\n"
<<" -S <int> seed for random number generation used in selecting multiple hits\n"
<<" set identical values to allow reproducible mapping results. \n"
<<" (default: "<<param.randseed<<", get seed from system clock, mapping results not reproducible)\n"
#ifdef THREAD
<<" -p <int> number of processors to use, default: "<<param.num_procs<<"\n"
#endif
<<"\n Options for pair-end alignment:\n"
<<" -m <int> minimal insert size allowed, default: "<<param.min_insert<<"\n"
<<" -x <int> maximal insert size allowed, default: "<<param.max_insert<<"\n"
<<"\n Options for reads trimming:\n"
<<" -q <int> quality threshold in trimming, 0-40, default: 0\n"
<<" -z <int> base quality, default: "<<(int) param.zero_qual<<" [set 64 for Illumina, 33 for Sanger]\n"
<<" -f <int> reads containing more than this number of Ns will be skipped, default="<<param.max_ns<<"\n"
<<" -A <str> 3' end adapter sequence to be trimmed, default: none\n"
<<" -L <int> map the first N bases of the read, the max is "<<param.max_readlen<<" (default).\n"
<<"\n Options for mapping strand:\n"
<<" -n [0,1,2] -n 0: directional protocol, map single-end(SE) reads to forward strands, \n"
<<" i.e. ++(OT in bismark) and -+(OB in bismark). \n"
<<" For pair-end(PE), map read#1 to ++ and -+, map read#2 to +-(CTOT \n"
<<" in bismark) and --(CTOB in bismark).\n"
<<" -n 1: non-directional protocol, map reads to all 4 strands. \n"
<<" -n 2: PBAT protocol, map SE reads to reverse strands, i.e. +- and --. \n"
<<" For PE, map read#1 to +- and --, read#2 to ++ and -+.\n"
<<" default: "<<param.chains<<"\n"
<<"\n Options for reporting:\n"
<<" -r [0,1,2] how to report repeat hits, 0=none(unique hit/pair); 1=random one; 2=all, default:"<<param.report_repeat_hits<<".\n"
<<" -R print corresponding reference sequences in SAM output, default: off\n"
<<" -u report unmapped reads, default: off\n"
<<" -H do not print header information in SAM format output\n"
<<" -V [0,1,2] verbose level: 0=quiet mode; 1=major message (default); 2=detailed message.\n"
<<" -h help\n\n";
exit(1);
};
int mGetOptions(int rgc, char *rgv[])
{
int i;
for(i=1,command_line=rgv[0];i<rgc;i++) command_line=command_line+" "+rgv[i];
for(i=1; i<rgc; i++) {
if(rgv[i][0]!='-') return i;
switch(rgv[i][1]) {
case 'a': if(rgv[i][2]==0) query_a_file = rgv[++i]; else if(rgv[i][2]=='=') query_a_file=rgv[i]+3; else return i; break;
case 'b': if(rgv[i][2]==0) query_b_file = rgv[++i]; else if(rgv[i][2]=='=') query_b_file=rgv[i]+3; else return i;
param.pairend=1; break;
case 'd': if(rgv[i][2]==0) ref_file = rgv[++i]; else if(rgv[i][2]=='=') ref_file=rgv[i]+3; else return i; break;
case 's': if(rgv[i][2]==0)
param.SetSeedSize(atoi(rgv[++i])); else if(rgv[i][2]=='=') param.SetSeedSize(atoi(rgv[i]+3)); else return i;
break;
case 'o':
if(rgv[i][2]==0) out_align_file = rgv[++i];
else if(rgv[i][2]=='=') out_align_file=rgv[i]+3;
else return i;
param.stdout=0;
break;
case 'M': if(rgv[i][2]==0){conversion_rule=rgv[++i];}
else if(rgv[i][2]=='='){conversion_rule=rgv[i]+3;}
else return i;
break;
case 'm': if(rgv[i][2]==0) param.min_insert = atoi(rgv[++i]); else if(rgv[i][2]=='=') param.min_insert=atoi(rgv[i]+3); else return i; break;
case 'n': if(rgv[i][2]==0) param.chains=atoi(rgv[++i]); else if(rgv[i][2]=='=') param.chains=atoi(rgv[i]+3); else return i; break;
case 'g': if(rgv[i][2]==0) param.gap=atoi(rgv[++i]); else if(rgv[i][2]=='=') param.gap=atoi(rgv[i]+3); else return i;
if(param.gap>MAXGAPS) {
cerr<<"warning: gap length exceeds max value:"<<MAXGAPS<<endl;
param.gap=MAXGAPS;
}
break;
case 'x': if(rgv[i][2]==0) param.max_insert = atoi(rgv[++i]); else if(rgv[i][2]=='=') param.max_insert=atoi(rgv[i]+3); else return i; break;
case 'r': if(rgv[i][2]==0) param.report_repeat_hits = atoi(rgv[++i]); else if(rgv[i][2]=='=') param.report_repeat_hits=atoi(rgv[i]+3); else return i;
if(param.report_repeat_hits>2||param.report_repeat_hits<0) {
cerr<<"invalid -r value: "<<param.report_repeat_hits<<", must be 0, 1, or 2.\n";
exit(1);
}
break;
case 'V': if(rgv[i][2]==0) param.verbose_level = atoi(rgv[++i]); else if(rgv[i][2]=='=') param.verbose_level=atoi(rgv[i]+3); else return i;
if(param.verbose_level>2||param.verbose_level<0) {
cerr<<"invalid -V value: "<<param.verbose_level<<", must be 0, 1, or 2.\n";
exit(1);
}
break;
case 'I': if(rgv[i][2]==0) param.index_interval = atoi(rgv[++i]); else if(rgv[i][2]=='=') param.index_interval=atoi(rgv[i]+3); else return i;
if(param.RRBS_flag) param.index_interval=1;
if(param.index_interval>16) {cerr<<"index interval exceeds max value:16\n"; exit(1);}
break;
case 'k': if(rgv[i][2]==0) param.max_kmer_ratio=atof(rgv[++i]); else if(rgv[i][2]=='=') param.max_kmer_ratio=atof(rgv[i]+3); else return i; break;
case 'v':
double tmp_max_snp;
if(rgv[i][2]==0) tmp_max_snp = atof(rgv[++i]); else if(rgv[i][2]=='=') tmp_max_snp=atof(rgv[i]+3); else return i;
if(tmp_max_snp<1.0) {
param.max_snp_num=(int)(tmp_max_snp*100+0.5)+100;
if(param.max_snp_num==100) param.max_snp_num=0;
}
else{
param.max_snp_num=(int)(tmp_max_snp+0.5);
if(param.max_snp_num>MAXSNPS) {
cerr<<"warning: number of mismatches exceeds max value:"<<MAXSNPS<<endl;
param.max_snp_num=MAXSNPS;
}
}
break;
case 'w': if(rgv[i][2]==0) param.max_num_hits = atoi(rgv[++i]); else if(rgv[i][2]=='=') param.max_num_hits=atoi(rgv[i]+3); else return i;
if(param.max_num_hits>MAXHITS) {cerr<<"number of multi-hits exceeds max value:"<<MAXHITS<<endl; exit(1);}
break;
case 'q': if(rgv[i][2]==0) param.qual_threshold = atoi(rgv[++i]); else if(rgv[i][2]=='=') param.qual_threshold = atoi(rgv[i]+3); else return i; break;
case 'f': if(rgv[i][2]==0) param.max_ns=atoi(rgv[++i]); else if(rgv[i][2]=='=') param.max_ns=atoi(rgv[i]+3); else return i; break;
case 'z': if(rgv[i][2]==0) param.zero_qual=atoi(rgv[++i]); else if(rgv[i][2]=='=') param.zero_qual=atoi(rgv[i]+3); else return i; break;
case 'p': if(rgv[i][2]==0) param.num_procs=atoi(rgv[++i]); else if(rgv[i][2]=='=') param.num_procs=atoi(rgv[i]+3); else return i; break;
case 'A': if(rgv[i][2]==0) param.adapter[param.n_adapter++]=rgv[++i]; else if(rgv[i][2]=='=') param.adapter[param.n_adapter++]=rgv[i]+3; else return i;
break;
case 'R': if(rgv[i][2]==0) param.out_ref=1; else return i; break;
case '3': if(rgv[i][2]==0) param.nt3=1; else return i; break;
case 'H': if(rgv[i][2]==0) param.sam_header=0; else return i; break;
case 'u': if(rgv[i][2]==0) param.out_unmap=1; else return i; break;
case 'B': if(rgv[i][2]==0) param.read_start = max(atoi(rgv[++i]),1); else if(rgv[i][2]=='=') param.read_start=max(atoi(rgv[i]+3),1); else return i; break;
case 'E': if(rgv[i][2]==0) param.read_end = atoi(rgv[++i]); else if(rgv[i][2]=='=') param.read_end=atoi(rgv[i]+3); else return i; break;
case 'D': if(rgv[i][2]==0) param.SetDigestionSite(rgv[++i]); else if(rgv[i][2]=='=') param.SetDigestionSite(rgv[i]+3); else return i; break;
case 'L': if(rgv[i][2]==0) param.max_readlen = atoi(rgv[++i]); else if(rgv[i][2]=='=') param.max_readlen = atoi(rgv[i]+3); else return i; break;
case 'N': if(rgv[i][2]==0) param.N_mis=1; else return i; break;
case 'S': if(rgv[i][2]==0) param.randseed = atoi(rgv[++i]); else if(rgv[i][2]=='=') param.randseed = atoi(rgv[i]+3); else return i; break;
case 'h':usage(); //usage information
default: return i;
}
}
param.InitMapping();
return 0;
}
void check_ofile(string &filename, string &err_msg) {
ofstream ff;
ff.open(filename.c_str()); cerr.flush();
if(!ff) {
cerr<<endl<<err_msg<<filename<<endl;
exit(1);
}
}
int check_ifile(string &filename, string &err_msg) {
int byte1, byte2; ifstream ff;
ff.open(filename.c_str()); cerr.flush();
if(!ff) {
cerr<<endl<<err_msg<<filename<<endl;
exit(1);
}
byte1=ff.get(); byte2=ff.get();
return ((byte1==0x1f)&&(byte2==0x8b)); // if input is gzip file or not
}
int check_ifile_format(string &filename, int gz_flag) {
ifstream ff; igzstream gg;
string s1,s2,s3,s4; char ch[1000];
if(gz_flag) {
gg.open(filename.c_str());
gg>>s1; gg.getline(ch, 1000);
if(s1[0]=='>') {message<<" \t(format: gzipped FASTA)\n"; info(1); return 0;} //fasta
if(s1[0]=='@') {message<<" \t(format: gzipped FASTQ)\n"; info(1); return 1;} //fastq
if(samopen(filename.c_str(), "rb", 0)!=0) {message<<" \t(format: BAM)\n"; info(1); return 3;} //BAM
if(samopen(filename.c_str(), "r", 0)!=0) {message<<" \t(format: SAM)\n"; info(1); return 2;} //SAM
}
else {
ff.open(filename.c_str());
ff>>s1; ff.getline(ch, 1000);
if(s1[0]=='>') {message<<" \t(format: FASTA)\n"; info(1); return 0;} //fasta
if(s1[0]=='@') {message<<" \t(format: FASTQ)\n"; info(1); return 1;} //fastq
if(samopen(filename.c_str(), "rb", 0)!=0) {message<<" \t(format: BAM)\n"; info(1); return 3;} //BAM
if(samopen(filename.c_str(), "r", 0)!=0) {message<<" \t(format: SAM)\n"; info(1); return 2;} //SAM
}
cerr<<"\t(format: unknown)\nUnknown input format.\n";
exit(1);
}
void RunProcess(void) {
char _ch[256]; string _str="@HD\tVN:1.0\n";
if(out_align_file.size()>4){
if(out_align_file.compare(out_align_file.size()-4,4,".sam")==0) param.out_sam=1;
else if (out_align_file.compare(out_align_file.size()-4,4,".bam")==0) param.out_sam=2;
}
else param.out_sam=1;
if(param.max_snp_num<100) message<<"\tmax number of mismatches: "<<param.max_snp_num;
else message<<"\tmax number of mismatches: read_length * "<<param.max_snp_num-100<<"% ";
message<<" \tmax gap size: "<<param.gap<<" \tkmer cut-off ratio: "<<param.max_kmer_ratio<<" \tmax multi-hits: "<<param.max_num_hits<<endl;
message<<"\tquality cutoff: "<<(int)param.qual_threshold<<" \tbase quality char: '"<<param.zero_qual<<"'"<<" \tmax Ns: "<<param.max_ns;
if(param.max_readlen<(FIXELEMENT-1)*SEGLEN) message<<" \thard clip length: "<<param.max_readlen; message<<endl;
if(param.pairend||param.RRBS_flag) message<<"\tmin fragment size: "<<param.min_insert<<" \tmax fragemt size: "<<param.max_insert<<endl;
if(param.nt3) message<<"\t3-nucleotide mapping approach";
else message<<"\twildcard mapping approach";
message<<" \tseed size: "<<param.seed_size<<" \tindex interval: "<<param.index_interval<<endl;
message<<"\talignment report: ";
if(param.report_repeat_hits==0) message<<"unique alignments only";
if(param.report_repeat_hits==1) message<<"unique + one random multiple alignments";
if(param.report_repeat_hits==2) message<<"unique + all multiple alignments"; message<<endl;
if(param.pairend){
message<<"\tmapping strand (read_1): ";
if(param.chains==0){
message<< "++,-+";
}else if(param.chains==1){
message<< "++,-+,+-,--";
}else{
message<< "+-,--";
}
message<<"\tmapping strand (read_2): ";
if(param.chains==0){
message<< "+-,--";
}else if(param.chains==1){
message<< "+-,--,++,-+";
}else{
message<< "++,-+";
}
}
else {
message<<"\tmapping strand: ";
if(param.chains==0){
message<< "++,-+";
}else if(param.chains==1){
message<< "++,-+,+-,--";
}else{
message<< "+-,--";
}
}
message<<endl;
for(bit32_t i=0; i<param.n_adapter;i++) message<<"\tadapter sequence #"<<i+1<<": "<<param.adapter[i]<<endl;
if(param.RRBS_flag) {
message<<"\tRRBS digestion site: ";
for(bit32_t i=0; i<param.digest_site.size(); i++)
message<<param.digest_site[i].substr(0,param.digest_pos[i])<<'-'<<param.digest_site[i].substr(param.digest_pos[i])<<" ";
message<<endl;
}
info(2);
string err_msg;
//pair-end alignment
if(param.pairend) {
message<<"[BASAL @"<<Curr_Time()<<"] Pair-end alignment("<<param.num_procs<<" threads),"; info(1);
message<<" \tstart from read pair #"<<param.read_start;
if(~param.read_end) message<<" \tend at read pair #"<<param.read_end; info(2); message<<endl; info(1);
err_msg="failed to open read file #1 (check -a option): ";
message<<"\tInput read file #1: "<<query_a_file;
param.gz_input=check_ifile(query_a_file, err_msg);
param.input_format=check_ifile_format(query_a_file, param.gz_input);
read_a.InitIndex(fin_a, gzfin_a, query_a_file);
err_msg="failed to open read file #2 (check -b option): ";
message<<"\tInput read file #2: "<<query_b_file;
if(param.gz_input!=check_ifile(query_b_file, err_msg)) {
cerr<<"Input read file #1 and #2 should be both regular files or gzip files."<<endl;
exit(1);
}
if(param.input_format!=check_ifile_format(query_b_file, param.gz_input)) {
cerr<<"Input read file #1 and #2 should be in same format."<<endl;
exit(1);
}
read_b.InitIndex(fin_b, gzfin_b, query_b_file);
if(param.stdout) message<<"\tOutput: STDOUT\t (format: SAM)\n";
else {
cerr<<"\tOutput file: "<<out_align_file;
switch(param.out_sam) {
case 1: message<<"\t (format: SAM)\n"; break;
case 2: message<<"\t (format: SAM, automatically convert to BAM)\n"; break;
}
err_msg="failed to open output file (check -o option): ";
check_ofile(out_align_file, err_msg);
if(param.out_sam==2) {
string samtools_command="samtools view -bS - >"+out_align_file;
if((pout=popen(samtools_command.c_str(),"w"))==NULL) {
cerr.flush();
message<<"unable to creat samtools pipe, using post alignment conversion instead.\n";
fout.open(out_align_file.c_str());
}
else param.pipe_out=1;
}
else fout.open(out_align_file.c_str());
}
if(param.out_sam&¶m.sam_header) {
for(bit32_t i=0;i<refseq_ref.total_num;i++){
sprintf(_ch,"@SQ\tSN:%s\tLN:%u\n",refseq_ref.title[i<<1].name.c_str(),refseq_ref.title[i<<1].size);
_str.append(_ch);
}
sprintf(_ch,"@PG\tID:BASAL\tVN:%s\tCL:\"%s\"\n",version,command_line.c_str()); _str.append(_ch);
if(param.stdout) cout<<_str;
else if(param.pipe_out) fwrite(_str.c_str(),1,_str.size(),pout);
else fout<<_str;
}
n_aligned_pairs=n_aligned_a=n_aligned_b=0; info(1);
Do_PairAlign();
if(param.pipe_out) pclose(pout); else fout.close();
if(param.input_format==3) {
bam_destroy1(read_a.SAM_b); samclose(read_a.SAM_fp);
bam_destroy1(read_b.SAM_b); samclose(read_b.SAM_fp);
}
message<<fixed<<setw(4)<<setprecision(1);
message<<"[BASAL @"<<Curr_Time()<<"] total read pairs: "<<read_a._index-param.read_start+1<<" \ttotal time consumed: "<<Cal_AllTime()<<" secs\n";
message<<"\taligned pairs: "<<n_aligned_pairs<<" ("<<100.0*n_aligned_pairs/(read_a._index-param.read_start+1)<<"%), ";
message<<"unique pairs: "<<n_unique_pairs<<" ("<<100.0*n_unique_pairs/(read_a._index-param.read_start+1)<<"%), ";
if(param.report_repeat_hits==0) message<<"suppressed ";
message<<"non-unique pairs: "<<n_multiple_pairs<<" ("<<100.0*n_multiple_pairs/(read_a._index-param.read_start+1)<<"%)\n";
message<<"\tunpaired read #1: "<<n_aligned_a<<" ("<<100.0*n_aligned_a/(read_a._index-param.read_start+1)<<"%), ";
message<<"unique reads: "<<n_unique_a<<" ("<<100.0*n_unique_a/(read_a._index-param.read_start+1)<<"%), ";
if(param.report_repeat_hits==0) message<<"suppressed ";
message<<"non-unique reads: "<<n_multiple_a<<" ("<<100.0*n_multiple_a/(read_a._index-param.read_start+1)<<"%)\n";
message<<"\tunpaired read #2: "<<n_aligned_b<<" ("<<100.0*n_aligned_b/(read_b._index-param.read_start+1)<<"%), ";
message<<"unique reads: "<<n_unique_b<<" ("<<100.0*n_unique_b/(read_b._index-param.read_start+1)<<"%), ";
if(param.report_repeat_hits==0) message<<"suppressed ";
message<<"non-unique reads: "<<n_multiple_b<<" ("<<100.0*n_multiple_b/(read_b._index-param.read_start+1)<<"%)\n";
info(1);
}
//single-read alignment
else {
message<<"[BASAL @"<<Curr_Time()<<"] Single-end alignment("<<param.num_procs<<" threads),"; info(1);
message<<" \tstart from read #"<<param.read_start;
if(~param.read_end) message<<" \tend at read #"<<param.read_end; info(2); cerr<<endl; info(1);
err_msg="failed to open read file (check -a option): ";
message<<"\tInput read file: "<<query_a_file;
param.gz_input=check_ifile(query_a_file, err_msg);
param.input_format=check_ifile_format(query_a_file, param.gz_input);
read_a.InitIndex(fin_a, gzfin_a, query_a_file);
if(param.stdout) message<<"\tOutput: STDOUT\t (format: SAM)\n";
else {
message<<"\tOutput file: "<<out_align_file;
switch(param.out_sam) {
case 1: message<<"\t (format: SAM)\n"; break;
case 2: message<<"\t (format: SAM, automatically convert to BAM)\n"; break;
}
err_msg="failed to open output file (check -o option): ";
check_ofile(out_align_file, err_msg);
if(param.out_sam==2) {
string samtools_command="samtools view -bS - >"+out_align_file;
if((pout=popen(samtools_command.c_str(),"w"))==NULL) {
message.flush();
message<<"unable to creat samtools pipe, using post alignment conversion instead.\n";
fout.open(out_align_file.c_str());
}
else param.pipe_out=1;
}
else fout.open(out_align_file.c_str());
}
if(param.out_sam&¶m.sam_header) {
char _ch[1000];
for(bit32_t i=0;i<refseq_ref.total_num;i++) {
sprintf(_ch,"@SQ\tSN:%s\tLN:%u\n",refseq_ref.title[i<<1].name.c_str(),refseq_ref.title[i<<1].size);
_str.append(_ch);
}
sprintf(_ch,"@PG\tID:BASAL\tVN:%s\tCL:\"%s\"\n",version,command_line.c_str()); _str.append(_ch);
if(param.stdout) cout<< _str;
else if(param.pipe_out) fwrite(_str.c_str(),1,_str.size(),pout);
else fout<<_str;
}
n_aligned=0;
info(1);
Do_SingleAlign();
if(param.pipe_out) pclose(pout); else fout.close();
if(param.input_format==3) {
bam_destroy1(read_a.SAM_b);
samclose(read_a.SAM_fp);
}
message<<fixed<<setw(4)<<setprecision(1);
message<<"[BASAL @"<<Curr_Time()<<"] total reads: "<<read_a._index-param.read_start+1<<" \ttotal time: "<<Cal_AllTime()<<" secs\n";
message<<"\taligned reads: "<<n_aligned<<" ("<<100.0*n_aligned/(read_a._index-param.read_start+1)<<"%), ";
message<<"unique reads: "<<n_unique<<" ("<<100.0*n_unique/(read_a._index-param.read_start+1)<<"%), ";
if(param.report_repeat_hits==0) message<<"suppressed ";
message<<"non-unique reads: "<<n_multiple<<" ("<<100.0*n_multiple/(read_a._index-param.read_start+1)<<"%)\n";
info(1);
}
};
int main(int argc, char *argv[]) {
//print usage
if (argc == 1) usage();
Initial_Time();
int noptions=mGetOptions(argc, argv);
if(noptions) {
cerr<<"unknown option: "<<argv[noptions]<<endl;
exit(noptions);
}
if(conversion_rule.empty()){
cerr<<endl<<"-M option is required"<<endl;
exit(1);
}else{
param.SetAlign(conversion_rule);
}
if(param.nt3==1 && param.readnt_cnt>1){
cerr<<"3-nucleotide mapping approach is only valid for single convert-to base. But "<< param.readnt_cnt <<" convert-to bases are detected in -M. Remove -3 and try again." << endl;exit(1);
}
message<<"\nBASAL v"<<version<<endl; info(2); srand(time(NULL));
string err_msg="failed to open reference file (check -d option): ";
message<<"[BASAL @"<<Curr_Time()<<"] loading reference file: "<<ref_file; info(1);
param.gz_ref=check_ifile(ref_file, err_msg);
if(check_ifile_format(ref_file, param.gz_ref)) {
cerr<<"reference must be in FASTA format.\n";
exit(1);
}
if(param.gz_ref) gzfin_db.open(ref_file.c_str());
else fin_db.open(ref_file.c_str());
refseq_ref.Run_ConvertBinseq(fin_db, gzfin_db);
message<<"[BASAL @"<<Curr_Time()<<"] "<<refseq_ref.total_num<<" reference seqs loaded, total size "<<refseq_ref.sum_length<<" bp. "<<Cal_AllTime()<<" secs passed"<<endl;
info(1);
Do_Formatdb(); ref_time=Cal_AllTime(); read_time=0;
RunProcess();
refseq_ref.ReleaseIndex();
return 0;
}