forked from aquaskyline/SOAPcoverage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoap.coverage.cpp
More file actions
executable file
·2646 lines (2531 loc) · 69 KB
/
soap.coverage.cpp
File metadata and controls
executable file
·2646 lines (2531 loc) · 69 KB
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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Enchantez!
Soap.Coverage
Author: Aqua Lo
E-mail: luoruibang@genomics.org.cn
This utility if a component of SOAP.
*/
#define _REENTRANT
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cassert>
#include <limits>
#include <pthread.h>
#include <boost/lexical_cast.hpp>
#include <boost/progress.hpp>
#include <boost/regex.hpp>
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include "gzstream.h"
#include "threadmanager.h"
//Namespace Declaration
using namespace std;
using namespace boost;
//Constant
#define DEPTH_SINGLE_LENGTH_PER_ROW 100 //Columns per row in -depthsingle
#define WINDOW_SIZE_LOWER_LIMIT 100 //The lowest threshold of window_size
//Debug Preparations
#define DEBUG false;
#define DB(...) if(DEBUG) cerr<<"Debug:"<<'\t'<<__FILE__<<'\t'<<__LINE__<<'\t'<<(__VA_ARGS__)<<end;
//Input Method
typedef igzstream imethod;
//Program Label
#define PROGRAM_NAME "SOAP.coverage"
#define PROGRAM_COMPILE_DATE __DATE__
#define PROGRAM_COMPILE_TIME __TIME__
// Define version number
#define VERSION_MAJOR 2
#define VERSION_MINOR 7
#define VERSION_PATCHLEVEL 9
#define VERSION_STRING "2.7.9"
// Macros dealing with VERSION
#define VERSION_NUM(a,b,c) (((a) << 16L) | ((b) << 8) | (c))
#define VERSION \
VERSION_NUM(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCHLEVEL)
#define README \
"This utility can calculate sequencing coverage or physical coverage as well as duplication rate\n"\
"and details of specific block for each segments and whole genome by using SOAP, Blat, Blast, BlastZ,\n"\
"mummer and MAQ aligement results with multi-thread. Gzip file supported.\n"
#define USAGE \
"Parameters:\n"\
" -cvg or -phy or -tag Selector for sequencing coverage mode, physical coverage mode or reads tag mode\n"\
" At least and only one should be selected!\n"\
" -refsingle [filename] Input reference fasta file used in SOAP\n"\
" -i [soap-file1 soap-file2 ...]\n"\
" Input several soap or soap gziped results by filenames.\n"\
" -il [soap-list] Input several soap or soap gziped results (absolute path!) with a soap-list file\n"\
" Caution: Only PE aligned results can be used in physical coverage!\n"\
" -il_single [SE aligned results list]\n"\
" -il_soap [PE aligned results list]\n"\
" -o [file-name] Results output with details\n"\
" -depth [directory] Output coverage of each bp in seperate files, a directory should be given\n"\
" -depthsingle [filename] Output coverage of each bp in a single file (text, fasta like)\n"\
" -nospace No space between plain depthsingle site depths\n"\
" -depthsinglebin [fn] Output coverage of each bp in a single file (Binary mode)\n"\
" -addn [filename] Input N block data for exclusion (marked as 65535 in depthsingle output)\n"\
" Input format: <segment_name> <start (leftmost as 1)> <end (half close)>\n"\
" -depthinput [filename] Input previous coverage data (Both Text or Binary) for faster accumulation\n"\
" -depthinputsam [filename]\n"\
" Input previous coverage data from Samtools\n"\
" -cdsinput [filename] Input specific block range for calculating coverage\n"\
" Input format: <segment_name> <start (leftmost as 1)> <end (half close)>\n"\
" -plot [filename] [x-axis lower] [x-axis upper]\n"\
" Output overall distribution of coverage of all segments\n"\
" -cdsplot [filename] [x-axis lower] [x-axis upper]\n"\
" Output distribution of coverage of specific blocks\n"\
" -cdsdetail [filename]\n"\
" Output coverage of each bp of each specific blocks in a single file\n"\
" -window [filename] [length]\n"\
" Output coverage averaged in a [length] long window to [filename]\n"\
" -p [num] Number of processors [Default:4]\n"\
" -trim [num] Exclude [num] bp(s) from head & tail of each segments\n"\
" -precisionOffset [num] Set the precision offset [Default:2]\n"\
" -minimumDepth [num] Set the minimum depth to take into consideration [Default:0]\n"\
" -maximumDepth [num] Set the maximum depth to take into consideration [Default:65535]\n"\
"\n"\
"Input format seletors:\n"\
" -general [id column] [start position column] [end position column]\n"\
" -generallen [id column] [start position column] [len]\n"\
" Specify column's (leftmost 1 based, right half close) for necessary informations\n"\
" Warning: Inputs with /^#/ are recognized as comments and ignored\n"\
" -plain Input is a three column list\n"\
" -sam Input is a standard SAM input file\n"\
" -pslquery Input is Blat for alculating query coverage.\n"\
" -pslsub Input is Blat for calculating subject coverage.\n"\
" -maq Input is MAQ output file.\n"\
" -m8subject Input is Blast m8 file for calculating subject coverage (reference should be subject).\n"\
" -m8query Input is Blast m8 file for calculating query coverage (reference should be query).\n"\
" -mummerquery [limit] Input mummer result file for calculating query coverage.\n"\
" -axtoitg Input Blastz axt file for calculating target coverage.\n"\
" -axtoiq Input Blastz axt file for calculating query coverage.\n"\
" -qmap Input qmap of bisulfite sequencing.\n"\
"\n"\
"Special functions:\n"\
" -sp [filename_in] [filename_out]\n"\
" Output S/P ratio data for post processing.\n"\
" Column:\n"\
" ref start end name\n"\
" -pesupport [filename_in] [filename_out]\n"\
" Output pair-end reads on specific areas.\n"\
" Column:\n"\
" ref start end name\n"\
" -onlyuniq Use reads those are uniquely mapped (column 4 in soap == 1).\n"\
" -precise Omit mismatched bp in soap results.\n"\
" -nowarning Cancel all possible warning.\n"\
" -nocalc Do not perform depth calculation.\n"\
" -onlycover Only output 0 or 1 for coverage calculation.\n"\
"\n"\
"Physical Coverage Specified Parameters:\n"\
" -duplicate [num] Exclude duplications, and gives the percentage of duplication. [num]=readlength\n"\
" -insertupper [num] Insert larger than num will be abandon [Default: 15000]\n"\
" -insertlower [num] Insert shorter thab num will be abandon [Default: 0]\n"\
"\n"\
"Example:\n"\
" 1. Calculate several files of SOAP results.\n"\
" soap.coverage -cvg -i *.soap *.single -refsingle human.fa -o result.txt \n"\
"\n"\
" 2. Calculate a list of SOAP results, exclude Ns blocks, output depth to\n"\
" a file and plot coverage form depth 0 to 1000.\n"\
" soap.coverage -cvg -il soap.list -refsingle human.fa -o result.txt -depthsingle all.coverage -addn n.gap -plot distribution.txt 0 1000\n"\
"\n"\
" 3. Calculate a list of SOAP results, use only uniquely mapped reads, exclude Ns blocks\n"\
" , output depth to a file and plot coverage form depth 0 to 1000.\n"\
" soap.coverage -cvg -il soap.list -onlyuniq -refsingle human.fa -o result.txt -depthsingle all.coverage -addn n.gap -plot distribution.txt 0 1000\n"\
"\n"\
" 4. Add new SOAP results to depth(-depthsingle) already calculated &\n"\
" plot all data and specific blocks from depth 0 to 150, with 6 processors.\n"\
" soap.coverage -cvg -depthinput all.coverage -refsingle human.fa -il soap.list -p 6 -o result.txt -cdsinput cds.list -plot distribution.txt 0 150 -cdsplot distribution_cds.txt 0 150\n"\
"\n"\
" 5. Calculate physical coverage and duplication rate(read length=44) with\n"\
" insert between (avg-3SD, avg+SD)[avg=197, SD=9], with 8 processors\n"\
" soap.coverage -phy -il soap_without_single.list -refsingle human.fa -p 8 -o result.txt -duplicate 44 -insertlower 170 -insertupper 224\n"\
//Typedef
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;
typedef unordered_set<string> strsets;
typedef unordered_map<string,int> strmaps;
typedef unordered_map<string,pthread_mutex_t*> semaphore_maps;
typedef vector<ushort> vs;
typedef vector<uint> vi;
typedef vector<pair<string, uint> > vpsu;
//Functions Declaration
void Intro(); //Program Head
void ParaDeal(int&, char**); //Dealing with parameters
void MakeMaps(); //Segments Shadowing form sets to maps
void BuildMemory(); //Alloc Memory
inline ulong AddTotalBP(); //Use by BuildMemory(), cumulate quantity info in ref.
inline ulong AddTotalBP_refsingle(); //Use by BuildMemory(), cumulate quantity info in refsingle.
void AddCover(); //-cvg
void Physical_AddCover(); //-phy
void CalcCoverage();
void OutputCoverage(); //-depthsingle
void OutputCoverageBin(); //-depthsinglebin
void OutputDistribution(); //-plot
void OutputWindow(); //-window
void AddN(); //-addn
void CalcCDS(); //-cdsplot
void CalcPoint(); //-point
void SP(); //-sp
void SPOutput();
void PESupportOutput(); //-pesupport
void AddCvg(); //-depthinput
void AddCvgFromSamtools(); //-depthinputsam
void AddRefSingle(); //-refsingle
void AddFastat(); //-reffastat
void Output_list(); //Sub of result illustration
void ComfirmAllDigit(const char*); //Sub of ParaDeal()
inline uint SeperateCigar(string &, vector<uint> &); //Sub of _AddCover_Sub
//Global vars
bool cvg(false), phy(false), tag(false);
bool depth(false), depthsingle(false), nospace(false), depthsinglebin(false), ref(false), refsingle(false), reffastat(false),depthinput(false),depthinputsam(false),\
cdsinput(false), cdsplot(false), addon(false), addN(false), plot(false),cdsdetail(false), sam(false),\
window(false), pslsub(false), pslquery(false), maq(false), m8subject(false), m8query(false), axtoitg(false), axtoiq(false),\
nowarning(false), sp(false), il_single(false), il_soap(false), pesupport(false), onlyuniq(false),\
precise(false), gz(false), mummerquery(false), nocalc(false), onlycover(false), plain(false), qmap(false), general(false),\
generalLen(false);
map<string, ulong> refsingle_marker;
int trim(0), sprd_length(0), mummer_limit(0);
uint length(0);
vector<string> iPos, isPos, ipPos;
string oPos, rPos, dPos, cPos, cdsPos, cdsPos_out, cdsdetailPos, pointPos, pointOut, nPos, plotPos, windowPos_out, spIn, spOut;
uint plot_upper(0), plot_lower(0), cds_plot_upper(0), cds_plot_lower(0);
uint window_size(0);
ulong totalBP(0),countBP(0);
uint insert_Limit(15000);
uint insert_LowerLimit(0);
uint duplicate(0), useful_data(0), useless_data(0);
uint precisionOffset(6);
ushort minimumDepth(0);
ushort maximumDepth(65535);
string temp; //Quick inter-funtions messenger for BuildMemory().
ofstream OutData; //Global output handler
strsets chr;
strmaps chrmaps;
semaphore_maps chr_sema;
vector<vs> vector_vs;
vector<vi> sp_vvs;
vpsu sp_sui_single;
vpsu sp_sui_soap;
vector<int> distribution(65536,0);
uint intmax(numeric_limits<int>::max());
uint idCol(1), startCol(2), endCol(3);
//Multi-Thread global var
int NUM_THREADS(4);
void* _AddCover_general(void*);
void* _AddCover_plain(void*);
void* _AddCover_sam(void*);
void* _AddCover_Sub(void*);
void* _AddCover_pslsub(void*);
void* _AddCover_pslquery(void*);
void* _AddCover_maq(void*);
void* _AddCover_m8subject(void*);
void* _AddCover_m8query(void*);
void* _AddCover_mummerquery(void*);
void* _AddCover_axtoitg(void*);
void* _AddCover_axtoiq(void*);
void* _AddCover_qmap(void*);
void* _Physical_AddCover_Sub(void*);
struct param_struct
{
string pos;
};
int main(int argc, char ** argv)
{
timer elapsedtime;
Intro();
ParaDeal(argc, argv);
MakeMaps();
BuildMemory();
if(sp) SP();
if(depthinput) AddCvg();
if(depthinputsam) AddCvgFromSamtools();
if(addN) AddN();
if(addon && cvg) AddCover();
if(addon && phy) Physical_AddCover();
if(sp && !pesupport) SPOutput();
if(sp && pesupport) PESupportOutput();
if(!nocalc) CalcCoverage();
OutData<<"Overall:"<<endl
<<"Total:"<<totalBP<<endl
<<"Covered:"<<countBP<<endl
<<"Percentage:"<<(double)countBP/totalBP*100<<endl<<endl;
if(duplicate)
OutData<<"Duplication rate:"<<(double)useless_data/(useful_data+useless_data)*100<<'%'<<endl;
if(plot) OutputDistribution();
if(window) OutputWindow();
if(depth || depthsingle) OutputCoverage();
if(depthsinglebin) OutputCoverageBin();
if(cdsinput) CalcCDS();
if(!pointPos.empty() && !pointOut.empty()) CalcPoint();
cout<<"Overall:"<<endl
<<"Total:"<<totalBP<<endl
<<"Covered:"<<countBP<<endl
<<"Percentage:"<<(double)countBP/totalBP*100<<endl;
if(duplicate)
cout<<"Duplication rate:"<<(double)useless_data/(useful_data+useless_data)*100<<'%'<<endl;
Output_list();
cout<<(elapsedtime.elapsed())<<"s Elapsed!"<<endl;
return EXIT_SUCCESS;
}
void Intro()
{
cerr<<endl;
cerr<<PROGRAM_NAME<<endl;
cerr<<" Version: "<<VERSION_STRING<<endl;
cerr<<"Complied at: "<<PROGRAM_COMPILE_DATE<<' '<<PROGRAM_COMPILE_TIME<<endl;
cerr<<" Author: RuiBang Luo"<<endl;
cerr<<" E-mail: luoruibang@genomics.org.cn"<<endl<<endl;
cerr<<README<<endl;
}
void OutputWindow()
{
if(window_size < WINDOW_SIZE_LOWER_LIMIT)
{
cerr<<"User defined window length is lower than the lowest threshold "<<WINDOW_SIZE_LOWER_LIMIT<<endl
<<"Window length will set to "<<WINDOW_SIZE_LOWER_LIMIT<<endl;
window_size = WINDOW_SIZE_LOWER_LIMIT;
}
progress_display ptcount(chrmaps.size(), cout, "Calculating Coverage in window...\n");
ofstream O(windowPos_out.c_str());
if(!O)
{
cerr<<"Error opening window output file: "<<windowPos_out<<endl;
return;
}
strmaps::iterator mpos;
for(mpos = chrmaps.begin(); mpos != chrmaps.end(); ++mpos)
{
++ptcount;
for(register int i(1),limit(vector_vs[mpos->second].size()); i<limit;)
{
register int BPTotal(0);
register int BPCount(0);
register int j( (i+window_size) < limit ? i+window_size : limit);
if(j - i < window_size * 0.5)
break;
for(; i<j ; ++i)
{
if(vector_vs[mpos->second][i]==65535)
continue;
if(vector_vs[mpos->second][i] < minimumDepth)
continue;
if(vector_vs[mpos->second][i] > maximumDepth)
continue;
BPTotal += vector_vs[mpos->second][i];
++BPCount;
}
O<<mpos->first<<'\t'<<i-window_size<<'\t'<<j-1<<'\t'<<BPCount<<'\t'<<(double)BPTotal / BPCount<<endl;
}
}
}
void Physical_AddCover()
{
cout<<"Summarizing Physical Coverage..."<<endl;
CThreadManager threadMgr(NUM_THREADS);
threadMgr.SetTimer(0.5);
vector<param_struct> vparam(iPos.size());
for(register uint i(0); i<iPos.size(); ++i)
{
vparam[i].pos = iPos[i];
threadMgr.AddThread( _Physical_AddCover_Sub, (void*)&vparam[i]);
}
threadMgr.Run();
}
void* _Physical_AddCover_Sub(void* param)
{
param_struct* pParam = (param_struct*) param;
static ushort progress(1);
cout<<progress++<<'/'<<iPos.size()<<": "<<pParam->pos;
if((pParam->pos).find(".single") != string::npos)
{
cout<<" Omitted!"<<endl;
return (void *) NULL;
}
else
cout<<endl;
string temp;
string ctemp, ctemp1, ctemp2, ctemp3, ctemp4, ctemp5, ctemp6, ctemp_pos;
strmaps::iterator mpos;
semaphore_maps::iterator semapos;
imethod InData_Sub;
InData_Sub.open(pParam->pos.c_str());
//Var for duplication
multimap<uint,uint> dup_atom;
vector<multimap<uint,uint> > dup_vector(chrmaps.size());
//multimap<uint,uint>::iterator p_dup_atom;
pair<multimap<uint,uint>::iterator , multimap<uint,uint>::iterator > p_dup_atom_pair;
//***************************************
while(InData_Sub)
{
register uint end(0),start(0),read_length_neg(0),read_length_pos(0), start_dup(0), end_dup(0);
strmaps::iterator mpos;
for(;InData_Sub;)
{
++useful_data;
bool continue_mark(false);
//- 6 for length
InData_Sub>>ctemp;InData_Sub>>ctemp;InData_Sub>>ctemp;InData_Sub>>ctemp;InData_Sub>>ctemp;InData_Sub>>ctemp5;
//- 7 for strand
InData_Sub>>ctemp_pos;
//- 8 for chr
InData_Sub>>ctemp1;
//- 9 for position
InData_Sub>>ctemp2;InData_Sub.ignore(100000,'\n');
//+ 6 for length
InData_Sub>>ctemp;InData_Sub>>ctemp;InData_Sub>>ctemp;InData_Sub>>ctemp;InData_Sub>>ctemp;InData_Sub>>ctemp6;
//+ 8 for chr
InData_Sub>>ctemp;InData_Sub>>ctemp3;
//+ 9 for position
InData_Sub>>ctemp4;InData_Sub.ignore(100000,'\n');
//Judgement
if(ctemp1 != ctemp3)
{
getline(InData_Sub, ctemp, '\n');
cerr<<"Unmatched chromosome context!"<<"\t"<<ctemp1<<"\t"<<ctemp3<<endl;
continue;
}
if(atoi(ctemp2.c_str()) > atoi(ctemp4.c_str()))
{
swap(ctemp5, ctemp6);
swap(ctemp2, ctemp4);
}
read_length_neg = atoi(ctemp6.c_str());
read_length_pos = atoi(ctemp5.c_str());
if(read_length_neg == 0 || read_length_pos == 0 || ctemp2.size() > 9 || ctemp4.size() > 9)
{
cerr<<"One row bypassed!"<<endl;
continue;
}
start = atoi(ctemp2.c_str());
end = atoi(ctemp4.c_str()) + read_length_neg - 1;
if(end<=start)
{
cerr<<"end<=start"<<endl;
continue;
}
if((end-start)>insert_Limit || (end-start)<insert_LowerLimit) continue;
temp = ctemp1;
mpos = chrmaps.find(temp); semapos = chr_sema.find(temp);
if(mpos == chrmaps.end()) continue;
if (duplicate)
{
start_dup = start; end_dup = end;
if(read_length_neg < duplicate)
{
start_dup = start_dup - (duplicate - read_length_neg -1);
}
if(read_length_pos < duplicate)
{
end_dup = atoi(ctemp4.c_str()) + duplicate - 2;
}
p_dup_atom_pair = dup_vector[mpos->second].equal_range(start_dup);
if (p_dup_atom_pair.first == p_dup_atom_pair.second)
{
dup_vector[mpos->second].insert(make_pair<uint, uint>(start_dup, end_dup));
}
else
{
for(;p_dup_atom_pair.first != p_dup_atom_pair.second; ++p_dup_atom_pair.first)
{
if(p_dup_atom_pair.first->second == end_dup)
{
++useless_data;
continue_mark = true;
break;
}
}
if (!continue_mark) dup_vector[mpos->second].insert(make_pair<uint, uint>(start_dup, end_dup));
}
}
if (continue_mark) continue;
break;
}
if(start >= vector_vs[mpos->second].size()) continue;
if(end >= vector_vs[mpos->second].size()) end = vector_vs[mpos->second].size() - 1;
if(pesupport)
{
int cache(0);
for(register size_t i(start); i <= end; ++i)
{
if(sp_vvs[mpos->second][i] == 0)
continue;
if(sp_vvs[mpos->second][i] == cache)
continue;
cache = sp_vvs[mpos->second][i];
++(sp_sui_soap[sp_vvs[mpos->second][i]].second);
sp_sui_soap[sp_vvs[mpos->second][i]].first += ("\t" + lexical_cast<string>(end - start + 1 - read_length_neg - read_length_pos));
}
}
if(!InData_Sub) break;
if(start >= vector_vs[mpos->second].size()) continue;
if(end >= vector_vs[mpos->second].size()) end = vector_vs[mpos->second].size()-1;
for(register uint j(start),k(end); j<=k; ++j)
++(vector_vs[mpos->second][j]);
}
}
void OutputDistribution()
{
ofstream O(plotPos.c_str());
if(!O)
{
cerr<<"Error opening plot output file: "<<plotPos<<endl;
exit(EXIT_FAILURE);
}
for(register int i(plot_lower); i<=plot_upper; ++i)
//if(distribution[i])
O<<setw(5)<<i<<setw(12)<<distribution[i]<<endl;
}
void OutputCoverage()
{
progress_display ptcount(chrmaps.size(), cout, "Output Coverage to files (Text)...\n");
string temp;
strmaps::iterator mpos;
string delim = nospace ? "": " ";
if (depth)
{
for(mpos = chrmaps.begin(); mpos != chrmaps.end(); ++mpos)
{
++ptcount;
temp = dPos + '/'+ mpos->first + ".coverage";
ofstream depthData(temp.c_str());
depthData<<'>'<<mpos->first<<"\n";
//Determine Length
length = DEPTH_SINGLE_LENGTH_PER_ROW;
if(onlycover)
{
for(register unsigned long i(1),limit(vector_vs[mpos->second].size()); i<limit; ++i)
{
if(vector_vs[mpos->second][i])
depthData<<1<<delim;
else
depthData<<0<<delim;
if (i && i%length == 0) depthData<<'\n';
}
}
else
{
for(register unsigned long i(1),limit(vector_vs[mpos->second].size()); i<limit; ++i)
{
depthData<<vector_vs[mpos->second][i]<<delim;
if (i && i%length == 0) depthData<<'\n';
}
}
}
}
else if(depthsingle)
{
length = DEPTH_SINGLE_LENGTH_PER_ROW;
temp = dPos;
ofstream depthData(temp.c_str());
for(mpos = chrmaps.begin(); mpos != chrmaps.end(); ++mpos)
{
++ptcount;
depthData<<'>'<<mpos->first<<"\n";
if(onlycover)
{
for(register unsigned long i(1),limit(vector_vs[mpos->second].size()); i<limit; ++i)
{
if(vector_vs[mpos->second][i])
depthData<<1<<delim;
else
depthData<<0<<delim;
if (i && i%length == 0) depthData<<'\n';
}
}
else
{
for(register unsigned long i(1),limit(vector_vs[mpos->second].size()); i<limit; ++i)
{
depthData<<vector_vs[mpos->second][i]<<delim;
if (i && i%length == 0) depthData<<'\n';
}
}
depthData<<endl;
}
}
}
void OutputCoverageBin()
{
progress_display ptcount(chrmaps.size(), cout, "Output Coverage to files (Binary)...\n");
strmaps::iterator mpos;
ofstream depthData(dPos.c_str(), ios_base::binary | ios_base::out | ios_base::trunc);
ulong len_tmp(vector_vs.size());
//Output the quantity of segments
depthData.write((char*)(&len_tmp), sizeof(ulong));
for(mpos = chrmaps.begin(); mpos != chrmaps.end(); ++mpos)
{
++ptcount;
//Output the length of the name
len_tmp = mpos->first.size();
depthData.write((char*)(&len_tmp), sizeof(ulong));
//Output the name
depthData.write(mpos->first.c_str(), mpos->first.size());
//Output the length of the segment
len_tmp = (vector_vs[mpos->second].size()-1);
depthData.write((char*)(&len_tmp), sizeof(ulong));
if(onlycover)
{
ushort s1(1);
ushort s0(0);
for(register unsigned long i(1),limit(vector_vs[mpos->second].size()); i<limit; ++i)
//Output the single point detail
{
if(vector_vs[mpos->second][i])
depthData.write((char*)(&s1), sizeof(ushort));
else
depthData.write((char*)(&s0), sizeof(ushort));
}
}
else
{
for(register unsigned long i(1),limit(vector_vs[mpos->second].size()); i<limit; ++i)
//Output the single point detail
depthData.write((char*)(&vector_vs[mpos->second][i]), sizeof(ushort));
}
}
}
void CalcCoverage()
{
progress_display ptcount(chrmaps.size(), cout, "Calculating Coverage...\n");
//OutData<<"Coverage of each:\n";
strmaps::iterator mpos;
for(mpos = chrmaps.begin(); mpos != chrmaps.end(); ++mpos)
{
OutData<<mpos->first<<": ";
int singleBP(0);
int effectiveBP(0);
ulong depth_of_seq(0);
for(register int i(1),limit(vector_vs[mpos->second].size()); i<limit; ++i)
{
if(i<trim && i>=(limit-trim))
continue;
if(vector_vs[mpos->second][i]==65535)
continue;
++effectiveBP;
if(vector_vs[mpos->second][i] < minimumDepth)
continue;
if(vector_vs[mpos->second][i] > maximumDepth)
continue;
if(vector_vs[mpos->second][i])
{
depth_of_seq += vector_vs[mpos->second][i];
++singleBP;
}
++distribution[vector_vs[mpos->second][i]];
}
countBP += singleBP;
OutData<<singleBP<<'/'<<effectiveBP<<"\t"<<setprecision(precisionOffset)<<((double)singleBP/effectiveBP*100)<<"\t"<<setprecision(precisionOffset)<<depth_of_seq/(double)singleBP<<endl;
++ptcount;
}
OutData<<endl;
}
void SP()
{
cout<<"Marking S/P ratio area..."<<endl;
//cout<<"Int Max: "<<intmax<<endl;
strmaps::iterator mpos;
ifstream SPIN(spIn.c_str());
if(!SPIN)
{
cerr<<"Error opening S/P ratio input file: "<<spIn<<endl;
exit(EXIT_FAILURE);
}
string stemp;
int mark(1);
if(!pesupport) sp_sui_single.push_back(make_pair<string, uint>("", 0));
sp_sui_soap.push_back(make_pair<string, uint>("", 0));
for(;;)
{
assert(mark == sp_sui_soap.size());
string stemp1;
uint itemp2(0),itemp3(0);
SPIN>>stemp1>>itemp2>>itemp3;
if(!SPIN) break;
mpos = chrmaps.find(stemp1);
if(mpos == chrmaps.end())
{
cerr<<stemp1<<" from S/P ratio input not found in reference!"<<endl;
exit(EXIT_FAILURE);
}
if(!(mark == sp_sui_single.size() && sp_sui_single.size() == sp_sui_soap.size()) && !pesupport)
{
cerr<<"!(mark == sp_sui_single.size() && sp_sui_single.size() == sp_sui_soap.size() && !pesupport)"<<endl;
exit(EXIT_FAILURE);
}
if(!pesupport) sp_sui_single.push_back(make_pair<string, uint>(stemp1 + "\t" + lexical_cast<string>(itemp2) + "\t" + lexical_cast<string>(itemp3), 0));
sp_sui_soap.push_back(make_pair<string, uint>(stemp1 + "\t" + lexical_cast<string>(itemp2) + "\t" + lexical_cast<string>(itemp3), 0));
if(itemp3 >= sp_vvs[mpos->second].size())
itemp3 = sp_vvs[mpos->second].size() - 1;
for(register uint j(itemp2); j<=itemp3; ++j)
sp_vvs[mpos->second][j] = mark;
++mark;
}
cerr<<"Size of S/P ratio segments: "<<sp_sui_soap.size()<<endl;
cerr<<"Size of S/P ratio scaffolds: "<<sp_vvs.size()<<endl;
}
void SPOutput()
{
ofstream O(spOut.c_str());
if(!O)
{
cerr<<"Error opening S/P ratio output file!"<<endl;
exit(EXIT_FAILURE);
}
for(register size_t i(1); i < sp_sui_single.size(); ++i)
O<<sp_sui_single[i].first<<'\t'<<sp_sui_single[i].second<<'\t'<<sp_sui_soap[i].second<<'\t'<<(sp_sui_soap[i].second?(double)sp_sui_single[i].second/sp_sui_soap[i].second:0)<<endl;
}
void PESupportOutput()
{
ofstream O(spOut.c_str());
if(!O)
{
cerr<<"Error opening SPE support output file!"<<endl;
exit(EXIT_FAILURE);
}
for(register size_t i(1); i < sp_sui_soap.size(); ++i)
O<<sp_sui_soap[i].second<<'\t'<<sp_sui_soap[i].first<<endl;
}
void CalcCDS()
{
cout<<"Summarizing CDS Coverage..."<<endl;
strmaps::iterator mpos;
ifstream CDS(cdsPos.c_str());
if(!CDS)
{
cerr<<"Error opening cds input file: "<<cdsPos<<endl;
exit(EXIT_FAILURE);
}
ofstream CDSO;
if(cdsplot)
{
CDSO.open(cdsPos_out.c_str());
if(!CDSO)
{
cerr<<"Error opening cds output file: "<<cdsPos_out<<endl;
exit(EXIT_FAILURE);
}
}
ofstream CDS_DETAIL;
if(cdsdetail)
CDS_DETAIL.open(cdsdetailPos.c_str());
if(cdsdetail && !CDS_DETAIL)
{
cerr<<"Error opening cds details output file: "<<cdsdetailPos<<endl;
exit(EXIT_FAILURE);
}
string stemp;
vector<int> cds_distribution(65536,0);
int cds_total(0);
int cds_covered(0);
string stemp1,stemp2,stemp3,name;
for(;;)
{
CDS>>stemp1>>stemp2>>stemp3;
if(!CDS) break;
name = stemp1 + "\t" + stemp2 + "\t" + stemp3;
int itemp2(0),itemp3(0);
itemp2 = atoi(stemp2.c_str());
itemp3 = atoi(stemp3.c_str());
mpos = chrmaps.find(stemp1);
if(mpos == chrmaps.end()) continue;
stringstream ss;
//int count(0);
int cvg_total(0);
int cvs_covered_sub(0);
for(register uint j(itemp2); j<=itemp3; ++j)
{
if(j < 1 || j>= vector_vs[mpos->second].size())
{
cerr<<stemp1<<'\t'<<stemp2<<'\t'<<stemp3<<'\t'<<" Overflow! Omitted."<<endl;
break;
}
if(vector_vs[mpos->second][j] != 65535 && vector_vs[mpos->second][j] > minimumDepth && vector_vs[mpos->second][j] < maximumDepth)
{
cvg_total+=vector_vs[mpos->second][j];
++cds_total;
if(vector_vs[mpos->second][j])
{
++cvs_covered_sub;
++cds_covered;
}
//vector_vs[mpos->second][j] = 65535;
}
if(cdsdetail) ss<<vector_vs[mpos->second][j]<<' ';
++cds_distribution[vector_vs[mpos->second][j]];
}
if(cdsdetail)
{
CDS_DETAIL<<">"<<name<<'\t'<<itemp3-itemp2+1<<'\t'<<cvs_covered_sub<<'\t'<<setprecision(6)<<((double)cvg_total/cvs_covered_sub)<<endl;
CDS_DETAIL<<ss.str()<<endl;
}
}
cout<<"Coverage of specific regions: "<<(double)cds_covered/cds_total*100<<"%"<<endl;
OutData<<"Coverage of specific regions: "<<(double)cds_covered/cds_total*100<<"%"<<endl;
if(cdsplot)
for(register int i(cds_plot_lower) ; i<=cds_plot_upper; ++i)
if(cds_distribution[i])
CDSO<<setw(5)<<i<<setw(12)<<cds_distribution[i]<<endl;
}
void CalcPoint()
{
cout<<"Summarizing Point Coverage..."<<endl;
strmaps::iterator mpos;
ifstream CDS(pointPos.c_str());
if(!CDS)
{
cerr<<"Error opening point input file: "<<pointPos<<endl;
exit(EXIT_FAILURE);
}
ofstream CDSO(pointOut.c_str());
if(!CDSO)
{
cerr<<"Error opening point output file: "<<pointOut<<endl;
exit(EXIT_FAILURE);
}
string stemp;
string stemp1,stemp2,name;
for(;;)
{
CDS>>stemp1>>stemp2;
if(!CDS) break;
int j(0);
j = atoi(stemp2.c_str());
mpos = chrmaps.find(stemp1);
if(mpos == chrmaps.end() || j < 1 || j>= vector_vs[mpos->second].size())
{
CDSO << stemp1 << "\t" << stemp2 << "\t-1\n";
continue;
}
CDSO << stemp1 << "\t" << stemp2 << "\t" << vector_vs[mpos->second][j] << "\n";
}
}
void AddCvg()
{
strmaps::iterator mpos;
ifstream CVG(cPos.c_str());
if(!CVG)
{
cerr<<"Error opening Coverage file: "<<cPos<<endl;
exit(EXIT_FAILURE);
}
//Judge what kind of file (text or binary)
char firstChar(0);
CVG.read(&firstChar, 1);
if(firstChar == '>')
{
CVG.seekg(0);
progress_display ptcount(chrmaps.size(), cout, "Importing Coverage (Text)...\n");
string cdstemp;
for(register unsigned long i(1);;++i)
{
CVG>>cdstemp;
if(!CVG) break;
if(cdstemp[0] == '>')
{
++ptcount;
i = 0;
cdstemp = cdstemp.substr(1, string::npos);
mpos = chrmaps.find(cdstemp);
if(mpos == chrmaps.end())
{
cerr<<"Sequence "<<cdstemp<<" missing!"<<endl;
cerr<<"Wrong input depth file or reference file?"<<endl;
exit(EXIT_FAILURE);
}
continue;
}
else
vector_vs[mpos->second][i] = atoi(cdstemp.c_str());
}
}
else
{
CVG.close();
CVG.clear();
CVG.open(cPos.c_str(), ios_base::in | ios_base::binary);
ulong chr_quantity(0);
ulong len_tmp(0);
CVG.read((char*)(&chr_quantity), sizeof(ulong));
if(chr_quantity != chrmaps.size())
{
cerr<<"Segment quantity in reference file is different from depthinput file!"<<endl
<<" Reference: "<<chrmaps.size()<<endl
<<"Depthinput: "<<chr_quantity<<endl;
exit(EXIT_FAILURE);
}
progress_display ptcount(chrmaps.size(), cout, "Importing Coverage (Binary)...\n");
string cdstemp;
for(int x(0); x < chr_quantity; ++x,++ptcount)
{
CVG.read((char*)(&len_tmp), sizeof(ulong));
char* name_tmp = new char[len_tmp+1];
name_tmp[len_tmp] = '\0';
CVG.read(name_tmp, len_tmp);
cdstemp = name_tmp;
delete[] name_tmp;
mpos = chrmaps.find(cdstemp);
if(mpos == chrmaps.end())
{
cerr<<"Sequence "<<cdstemp<<" missing!"<<endl;
cerr<<"Wrong input depth file or reference file?"<<endl;
exit(EXIT_FAILURE);
}
CVG.read((char*)(&len_tmp), sizeof(ulong));
++len_tmp;
for(register int i(1); i < len_tmp; ++i)
CVG.read((char*)(&vector_vs[mpos->second][i]), sizeof(ushort));
}
}
}
void AddCvgFromSamtools()
{
strmaps::iterator mpos;
igzstream CVG(cPos.c_str());
if(!CVG)
{
cerr<<"Error opening Samtools Coverage file: "<<cPos<<endl;
exit(EXIT_FAILURE);
}
//Judge what kind of file (text or binary)
progress_display ptcount(chrmaps.size(), cout, "Importing Coverage (Samtools)...\n");
string prevChr;
string chr; size_t pos, depth;
while(true)
{
CVG >> chr >> pos >> depth;
if(!CVG) break;
if(chr != prevChr)
{
prevChr = chr;
++ptcount;
mpos = chrmaps.find(chr);
if(mpos == chrmaps.end())
{
cerr<<"Sequence "<<chr<<" missing!"<<endl;
cerr<<"Wrong input depth file or reference file?"<<endl;
exit(EXIT_FAILURE);
}
}
if(depth >= 65534)
depth = 65534;
vector_vs[mpos->second][pos] = depth;
}
}
void AddN()
{
ifstream N(nPos.c_str());
if(!N)
{
cerr<<"Error opening Gap file: "<<nPos<<endl;
exit(EXIT_FAILURE);
}
cerr<<"Masking N gaps..."<<endl;