-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathParsingBam.cpp
1608 lines (1391 loc) · 61.4 KB
/
ParsingBam.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
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
#include "ParsingBam.h"
#include <string.h>
#include <sstream>
// vcf parser modify from
// http://wresch.github.io/2014/11/18/process-vcf-file-with-htslib.html
// bam parser modify from
// https://github.com/whatshap/whatshap/blob/9882248c722b1020321fea6e9491c1cc5b75354b/whatshap/variants.py
// FASTA
FastaParser::FastaParser(std::string fastaFile, std::vector<std::string> chrName, std::vector<int> last_pos, int numThreads):
fastaFile(fastaFile),
chrName(chrName),
last_pos(last_pos)
{
// init map
for(std::vector<std::string>::iterator iter = chrName.begin() ; iter != chrName.end() ; iter++)
chrString.insert(std::make_pair( (*iter) , ""));
// load reference index
faidx_t *fai = NULL;
fai = fai_load(fastaFile.c_str());
// iterating all chr
#pragma omp parallfel for schedule(dynamic) num_threads(numThreads)
for(std::vector<std::string>::iterator iter = chrName.begin() ; iter != chrName.end() ; iter++){
int index = iter - chrName.begin();
// Do not extract references without SNP coverage.
if( last_pos.at(index) == -1){
chrString[(*iter)]="";
continue;
}
// ref_len is a return value that is length of retrun string
int ref_len = 0;
// read file
std::string chr_info(faidx_fetch_seq(fai , (*iter).c_str() , 0 , last_pos.at(index)+5 , &ref_len));
if(ref_len == 0){
std::cout<<"nothing in reference file \n";
}
// update map
chrString[(*iter)] = chr_info;
}
}
FastaParser::~FastaParser(){
}
void BaseVairantParser::compressParser(std::string &variantFile){
gzFile file = gzopen(variantFile.c_str(), "rb");
if(variantFile=="")
return;
if(!file){
std::cout<< "Fail to open vcf: " << variantFile << "\n";
}
else{
int buffer_size = 1048576; // 1M
char* buffer = (char*) malloc(buffer_size);
if(!buffer){
std::cerr<<"Failed to allocate buffer\n";
exit(EXIT_FAILURE);
}
char* offset = buffer;
while(true) {
int len = buffer_size - (offset - buffer);
if (len == 0){
buffer_size *= 2; // Double the buffer size
char* new_buffer = (char*) realloc(buffer, buffer_size);
if(!new_buffer){
std::cerr<<"Failed to allocate buffer\n";
free(buffer);
exit(EXIT_FAILURE);
}
buffer = new_buffer;
offset = buffer + buffer_size / 2; // Update the offset pointer to the end of the old buffer
len = buffer_size - (offset - buffer);
}
len = gzread(file, offset, len);
if (len == 0) break;
if (len < 0){
int err;
fprintf (stderr, "Error: %s.\n", gzerror(file, &err));
exit(EXIT_FAILURE);
}
char* cur = buffer;
char* end = offset+len;
for (char* eol; (cur<end) && (eol = std::find(cur, end, '\n')) < end; cur = eol + 1)
{
std::string input = std::string(cur, eol);
parserProcess(input);
}
// any trailing data in [eol, end) now is a partial line
offset = std::copy(cur, end, buffer);
}
gzclose (file);
free(buffer);
}
}
void BaseVairantParser::unCompressParser(std::string &variantFile){
std::ifstream originVcf(variantFile);
if(variantFile=="")
return;
if(!originVcf.is_open()){
std::cout<< "Fail to open vcf: " << variantFile << "\n";
exit(1);
}
else{
std::string input;
while(! originVcf.eof() ){
std::getline(originVcf, input);
parserProcess(input);
}
}
}
void BaseVairantParser::compressInput(std::string variantFile, std::string resultFile, PhasingResult phasingResult){
gzFile file = gzopen(variantFile.c_str(), "rb");
std::ofstream resultVcf(resultFile);
if(!resultVcf.is_open()){
std::cout<< "Fail to open write file: " << resultFile << "\n";
}
else if(!file){
std::cout<< "Fail to open vcf: " << variantFile << "\n";
}
else{
bool ps_def = false;
int buffer_size = 1048576; // 1M
char* buffer = (char*) malloc(buffer_size);
if(!buffer){
std::cerr<<"Failed to allocate buffer\n";
exit(EXIT_FAILURE);
}
char* offset = buffer;
while(true) {
int len = buffer_size - (offset - buffer);
if (len == 0){
buffer_size *= 2; // Double the buffer size
char* new_buffer = (char*) realloc(buffer, buffer_size);
if(!new_buffer){
std::cerr<<"Failed to allocate buffer\n";
free(buffer);
exit(EXIT_FAILURE);
}
buffer = new_buffer;
offset = buffer + buffer_size / 2; // Update the offset pointer to the end of the old buffer
len = buffer_size - (offset - buffer);
}
len = gzread(file, offset, len);
if (len == 0) break;
if (len < 0){
int err;
fprintf (stderr, "Error: %s.\n", gzerror(file, &err));
exit(EXIT_FAILURE);
}
char* cur = buffer;
char* end = offset+len;
for (char* eol; (cur<end) && (eol = std::find(cur, end, '\n')) < end; cur = eol + 1)
{
std::string input = std::string(cur, eol);
//parserProcess(input);
writeLine(input, ps_def, resultVcf, phasingResult);
}
// any trailing data in [eol, end) now is a partial line
offset = std::copy(cur, end, buffer);
}
gzclose (file);
free(buffer);
}
}
void BaseVairantParser::unCompressInput(std::string variantFile, std::string resultFile, PhasingResult phasingResult){
std::ifstream originVcf(variantFile);
std::ofstream resultVcf(resultFile);
if(!resultVcf.is_open()){
std::cout<< "Fail to open write file: " << resultFile << "\n";
}
else if(!originVcf.is_open()){
std::cout<< "Fail to open vcf: " << variantFile << "\n";
}
else{
bool ps_def = false;
std::string input;
while(! originVcf.eof() ){
std::getline(originVcf, input);
if( input != "" ){
writeLine(input, ps_def, resultVcf, phasingResult);
}
}
}
}
// SNP
SnpParser::SnpParser(PhasingParameters &in_params):commandLine(false){
chrVariant = new std::map<std::string, std::map<int, RefAlt> >;
params = &in_params;
// open vcf file
htsFile * inf = bcf_open(params->snpFile.c_str(), "r");
// read header
bcf_hdr_t *hdr = bcf_hdr_read(inf);
// counters
int nseq = 0;
// report names of all the sequences in the VCF file
const char **seqnames = NULL;
// chromosome idx and name
seqnames = bcf_hdr_seqnames(hdr, &nseq);
// store chromosome
for (int i = 0; i < nseq; i++) {
// bcf_hdr_id2name is another way to get the name of a sequence
chrName.push_back(seqnames[i]);
}
// set all sample string
std::string allSmples = "-";
// limit the VCF data to the sample name passed in
int is_file = bcf_hdr_set_samples(hdr, allSmples.c_str(), 0);
if( is_file != 0 ){
std::cout << "error or a positive integer if the list contains samples not present in the VCF header\n";
}
// struct for storing each record
bcf1_t *rec = bcf_init();
int ngt_arr = 0;
int ngt = 0;
int *gt = NULL;
// loop vcf line
while (bcf_read(inf, hdr, rec) == 0) {
// snp
if (bcf_is_snp(rec)) {
ngt = bcf_get_format_int32(hdr, rec, "GT", >, &ngt_arr);
if(ngt<0){
std::cerr<< "pos " << rec->pos << " missing GT value" << "\n";
exit(1);
}
// just phase hetero SNP
if ( (gt[0] == 2 && gt[1] == 4) || // 0/1
(gt[0] == 4 && gt[1] == 2) || // 1/0
(gt[0] == 2 && gt[1] == 5) || // 0|1
(gt[0] == 4 && gt[1] == 3) // 1|0
) {
// get chromosome string
std::string chr = seqnames[rec->rid];
// position is 0-base
int variantPos = rec->pos;
// get r alleles
RefAlt tmp;
tmp.Ref = rec->d.allele[0];
tmp.Alt = rec->d.allele[1];
//prevent the MAVs calling error which makes the GT=0/1
if ( rec->d.allele[1][2] != '\0' ){
continue;
}
// record
(*chrVariant)[chr][variantPos] = tmp;
}
}
// indel
else if ( params->phaseIndel ){
ngt = bcf_get_format_int32(hdr, rec, "GT", >, &ngt_arr);
if(ngt<0){
std::cerr<< "pos " << rec->pos << " missing GT value" << "\n";
exit(1);
}
if ( (gt[0] == 2 && gt[1] == 4) || // 0/1
(gt[0] == 4 && gt[1] == 2) || // 1/0
(gt[0] == 2 && gt[1] == 5) || // 0|1
(gt[0] == 4 && gt[1] == 3) // 1|0
) {
// get chromosome string
std::string chr = seqnames[rec->rid];
// position is 0-base
int variantPos = rec->pos;
// get r alleles
RefAlt tmp;
tmp.Ref = rec->d.allele[0];
tmp.Alt = rec->d.allele[1];
//prevent the MAVs calling error which makes the GT=0/1
if ( rec->d.allele[1][tmp.Alt.size()+1] != '\0' ){
continue ;
}
// record
(*chrVariant)[chr][variantPos] = tmp;
}
}
}
}
SnpParser::~SnpParser(){
delete chrVariant;
}
std::map<int, RefAlt> SnpParser::getVariants(std::string chrName){
std::map<int, RefAlt> targetVariants;
std::map<std::string, std::map<int, RefAlt> >::iterator chrIter = chrVariant->find(chrName);
if( chrIter != chrVariant->end() )
targetVariants = (*chrIter).second;
return targetVariants;
}
std::vector<std::string> SnpParser::getChrVec(){
return chrName;
}
/*bool SnpParser::findChromosome(std::string chrName){
std::map<std::string, std::map< int, RefAlt > >::iterator chrVariantIter = chrVariant->find(chrName);
// this chromosome not exist in this file.
if(chrVariantIter == chrVariant->end())
return false;
return true;
}*/
int SnpParser::getLastSNP(std::string chrName){
std::map<std::string, std::map< int, RefAlt > >::iterator chrVariantIter = chrVariant->find(chrName);
// this chromosome not exist in this file.
if(chrVariantIter == chrVariant->end())
return -1;
// get last SNP
std::map< int, RefAlt >::reverse_iterator lastVariantIter = (*chrVariantIter).second.rbegin();
// there are no SNPs on this chromosome
if(lastVariantIter == (*chrVariantIter).second.rend())
return -1;
return (*lastVariantIter).first;
}
void SnpParser::writeResult(PhasingResult phasingResult){
if( params->snpFile.find("gz") != std::string::npos ){
// .vcf.gz
compressInput(params->snpFile, params->resultPrefix+".vcf", phasingResult);
}
else if( params->snpFile.find("vcf") != std::string::npos ){
// .vcf
unCompressInput(params->snpFile, params->resultPrefix+".vcf", phasingResult);
}
return;
}
void SnpParser::parserProcess(std::string &input){
}
void SnpParser::writeLine(std::string &input, bool &ps_def, std::ofstream &resultVcf, PhasingResult &phasingResult){
// header
if( input.substr(0, 2) == "##" ){
// avoid double definition
if( input.substr(0, 16) == "##FORMAT=<ID=PS," ){
ps_def = true;
}
resultVcf << input << "\n";
}
else if ( input.substr(0, 6) == "#CHROM" || input.substr(0, 6) == "#chrom" ){
// format line
if( commandLine == false ){
if(ps_def == false){
resultVcf << "##FORMAT=<ID=PS,Number=1,Type=Integer,Description=\"Phase set identifier\">\n";
ps_def = true;
}
resultVcf << "##longphaseVersion=" << params->version << "\n";
resultVcf << "##commandline=\"" << params->command << "\"\n";
commandLine = true;
}
resultVcf << input << "\n";
}
else{
std::istringstream iss(input);
std::vector<std::string> fields((std::istream_iterator<std::string>(iss)),std::istream_iterator<std::string>());
if( fields.size() == 0 )
return;
int pos = std::stoi( fields[1] );
int posIdx = pos - 1 ;
std::string key = fields[0] + "_" + std::to_string(posIdx);
PhasingResult::iterator psElementIter = phasingResult.find(key);
// PS flag already exist, erase PS info
if( fields[8].find("PS")!= std::string::npos ){
// find PS flag
int colon_pos = 0;
int ps_pos = fields[8].find("PS");
for(int i =0 ; i< ps_pos ; i++){
if(fields[8][i]==':')
colon_pos++;
}
// erase PS flag
if( fields[8].find(":",ps_pos+1) != std::string::npos ){
fields[8].erase(ps_pos, 3);
}
else{
fields[8].erase(ps_pos - 1, 3);
}
// find PS value start
int current_colon = 0;
int ps_start = 0;
for(unsigned int i =0; i < fields[9].length() ; i++){
if( current_colon >= colon_pos )
break;
if(fields[9][i]==':')
current_colon++;
ps_start++;
}
// erase PS value
if( fields[9].find(":",ps_start+1) != std::string::npos ){
int ps_end_pos = fields[9].find(":",ps_start+1);
fields[9].erase(ps_start, ps_end_pos - ps_start + 1);
}
else{
fields[9].erase(ps_start-1, fields[9].length() - ps_start + 1);
}
}
// reset GT flag
if( fields[8].find("GT")!= std::string::npos ){
// find GT flag
int colon_pos = 0;
int gt_pos = fields[8].find("GT");
for(int i =0 ; i< gt_pos ; i++){
if(fields[8][i]==':')
colon_pos++;
}
// find GT value start
int current_colon = 0;
int modify_start = 0;
for(unsigned int i =0; i < fields[9].length() ; i++){
if( current_colon >= colon_pos )
break;
if(fields[9][i]==':')
current_colon++;
modify_start++;
}
if(fields[9][modify_start+1] == '|'){
// direct modify GT value
if(fields[9][modify_start] > fields[9][modify_start+2]){
fields[9][modify_start+1] = fields[9][modify_start];
fields[9][modify_start] = fields[9][modify_start+2];
fields[9][modify_start+2] =fields[9][modify_start+1];
}
fields[9][modify_start+1] = '/';
}
}
// Check if the variant is extracted from this VCF
auto posIter = (*chrVariant)[fields[0]].find(posIdx);
// this pos is phase
if( psElementIter != phasingResult.end() && posIter != (*chrVariant)[fields[0]].end() ){
// add PS flag and value
fields[8] = fields[8] + ":PS";
fields[9] = fields[9] + ":" + std::to_string((*psElementIter).second.block);
// find GT flag
int colon_pos = 0;
int gt_pos = fields[8].find("GT");
for(int i =0 ; i< gt_pos ; i++){
if(fields[8][i]==':')
colon_pos++;
}
// find GT value start
int current_colon = 0;
int modify_start = 0;
for(unsigned int i =0; i < fields[9].length() ; i++){
if( current_colon >= colon_pos )
break;
if(fields[9][i]==':')
current_colon++;
modify_start++;
}
// direct modify GT value
fields[9][modify_start] = (*psElementIter).second.RAstatus[0];
fields[9][modify_start+1] = '|';
fields[9][modify_start+2] = (*psElementIter).second.RAstatus[2];
}
// this pos has not been phased
else{
// add PS flag and value
fields[8] = fields[8] + ":PS";
fields[9] = fields[9] + ":.";
}
for(std::vector<std::string>::iterator fieldIter = fields.begin(); fieldIter != fields.end(); ++fieldIter){
if( fieldIter != fields.begin() )
resultVcf<< "\t";
resultVcf << (*fieldIter);
}
resultVcf << "\n";
}
}
bool SnpParser::findSNP(std::string chr, int position){
std::map<std::string, std::map<int, RefAlt> >::iterator chrIter = chrVariant->find(chr);
// empty chromosome
if( chrIter == chrVariant->end() )
return false;
std::map<int, RefAlt>::iterator posIter = (*chrVariant)[chr].find(position);
// empty position
if( posIter == (*chrVariant)[chr].end() )
return false;
return true;
}
void SnpParser::filterSNP(std::string chr, std::vector<ReadVariant> &readVariantVec, std::string &chr_reference){
// pos, <allele, <strand, True>
std::map<int, std::map<int, std::map<int, bool> > > posAlleleStrand;
std::map< int, bool > methylation;
/*
// iter all variant, record the strand contained in each SNP
for( auto readSNPVecIter : readVariantVec ){
// tag allele on forward or reverse strand
for(auto variantIter : readSNPVecIter.variantVec ){
posAlleleStrand[variantIter.position][variantIter.allele][readSNPVecIter.is_reverse] = true;
}
}
// iter all SNP, both alleles that require SNP need to appear in the two strand
for(auto pos: posAlleleStrand){
// this position contain two allele, REF allele appear in the two strand, ALT allele appear in the two strand
if(pos.second.size() == 2 && pos.second[0].size() == 2 && pos.second[1].size() == 2 ){
// high confident SNP
}
else{
//methylation[pos.first] = true;
}
}
*/
// Filter SNPs that are not easy to phasing due to homopolymer
// get variant list
std::map<std::string, std::map<int, RefAlt> >::iterator chrIter = chrVariant->find(chr);
std::map< int, bool > errorProneSNP;
if( chrIter != chrVariant->end() ){
std::map<int, int> consecutiveAllele;
// iter all SNP and tag homopolymer
for(std::map<int, RefAlt>::iterator posIter = (*chrIter).second.begin(); posIter != (*chrIter).second.end(); posIter++ ){
consecutiveAllele[(*posIter).first] = homopolymerLength((*posIter).first, chr_reference);
}
std::map<int, RefAlt>::iterator currSNPIter = (*chrIter).second.begin();
std::map<int, RefAlt>::iterator nextSNPIter = std::next(currSNPIter,1);
// check whether each SNP pair falls in an area that is not easy to phasing
while( currSNPIter != (*chrIter).second.end() && nextSNPIter != (*chrIter).second.end() ){
int currPos = (*currSNPIter).first;
int nextPos = (*nextSNPIter).first;
// filter one of SNP if this SNP pair falls in homopolymer and distance<=2
if( consecutiveAllele[currPos] >= 3 && consecutiveAllele[nextPos] >= 3 && std::abs(currPos-nextPos)<=2 ){
errorProneSNP[nextPos]=true;
nextSNPIter = (*chrIter).second.erase(nextSNPIter);
continue;
}
currSNPIter++;
nextSNPIter++;
}
}
// iter all reads
for( std::vector<ReadVariant>::iterator readSNPVecIter = readVariantVec.begin() ; readSNPVecIter != readVariantVec.end() ; readSNPVecIter++ ){
// iter all SNPs in this read
for(std::vector<Variant>::iterator variantIter = (*readSNPVecIter).variantVec.begin() ; variantIter != (*readSNPVecIter).variantVec.end() ; ){
std::map< int, bool >::iterator delSNPIter = methylation.find((*variantIter).position);
std::map< int, bool >::iterator homoIter = errorProneSNP.find((*variantIter).position);
if( delSNPIter != methylation.end() ){
variantIter = (*readSNPVecIter).variantVec.erase(variantIter);
}
else if( homoIter != errorProneSNP.end() ){
variantIter = (*readSNPVecIter).variantVec.erase(variantIter);
}
else{
variantIter++;
}
}
}
}
// SV
SVParser::SVParser(PhasingParameters &in_params, SnpParser &in_snpFile):commandLine(false){
params = &in_params;
snpFile = &in_snpFile;
chrVariant = new std::map<std::string, std::map<int, std::map<std::string ,bool> > >;
if( params->svFile.find("gz") != std::string::npos ){
// .vcf.gz
compressParser(params->svFile);
}
else if( params->svFile.find("vcf") != std::string::npos ){
// .vcf
unCompressParser(params->svFile);
}
// erase SV pos if this pos appear two or more times
for(std::map<std::string, std::map<int, bool> >::iterator chrIter = posDuplicate.begin(); chrIter != posDuplicate.end() ; chrIter++){
for(std::map<int, bool>::iterator posIter = (*chrIter).second.begin() ; posIter != (*chrIter).second.end() ; posIter++ ){
if( (*posIter).second == true){
std::map<int, std::map<std::string ,bool> >::iterator erasePosIter = (*chrVariant)[(*chrIter).first].find((*posIter).first);
if(erasePosIter != (*chrVariant)[(*chrIter).first].end()){
(*chrVariant)[(*chrIter).first].erase(erasePosIter);
}
}
}
}
}
SVParser::~SVParser(){
delete chrVariant;
}
void SVParser::parserProcess(std::string &input){
if( input.substr(0, 2) == "##" ){
}
else if ( input.substr(0, 1) == "#" ){
}
else{
std::istringstream iss(input);
std::vector<std::string> fields((std::istream_iterator<std::string>(iss)),std::istream_iterator<std::string>());
if( fields.size() == 0 )
return;
// trans to 0-base
int pos = std::stoi( fields[1] ) - 1;
std::string chr = fields[0];
// find GT flag
int colon_pos = 0;
int gt_pos = fields[8].find("GT");
for(int i =0 ; i< gt_pos ; i++){
if(fields[8][i]==':')
colon_pos++;
}
// find GT value start
int current_colon = 0;
int modify_start = 0;
for(unsigned int i =0; i < fields[9].length() ; i++){
if( current_colon >= colon_pos )
break;
if(fields[9][i]==':')
current_colon++;
modify_start++;
}
bool filter = false;
// homo GT
if(fields[9][modify_start]==fields[9][modify_start+2]){
filter = true;
}
// conflict pos with SNP
if( (*snpFile).findSNP(chr,pos) ){
filter = true;
}
std::map<int, bool>::iterator posIter = posDuplicate[chr].find(pos);
// conflict pos with SV
if( posIter == posDuplicate[chr].end() )
posDuplicate[chr][pos] = false;
else{
posDuplicate[chr][pos] = true;
filter = true;
}
if(filter){
return;
}
// get read INFO
int read_pos = fields[7].find("RNAMES=");
// detected RNAMES included in INFO
if( read_pos != -1 ){
// Extract the position of "=" in "RNAMES="
read_pos = fields[7].find("=",read_pos);
read_pos++;
// Capture the position of the ";" symbol at the end of the information in "RNAMES="
int next_field = fields[7].find(";",read_pos);
// Capture the range of read IDs included in the entire RNAMES
std::string totalRead = fields[7].substr(read_pos,next_field-read_pos);
std::stringstream totalReadStream(totalRead);
// Extract each read ID individually
std::string read;
while(std::getline(totalReadStream, read, ','))
{
(*chrVariant)[chr][pos][read]= true;
}
}
}
}
std::map<int, std::map<std::string ,bool> > SVParser::getVariants(std::string chrName){
std::map<int, std::map<std::string ,bool> > targetVariants;
std::map<std::string, std::map<int, std::map<std::string ,bool> > >::iterator chrIter = chrVariant->find(chrName);
if( chrIter != chrVariant->end() )
targetVariants = (*chrIter).second;
return targetVariants;
}
void SVParser::writeResult(PhasingResult phasingResult){
if( params->svFile.find("gz") != std::string::npos ){
// .vcf.gz
compressInput(params->svFile, params->resultPrefix+"_SV.vcf", phasingResult);
}
else if( params->svFile.find("vcf") != std::string::npos ){
// .vcf
unCompressInput(params->svFile, params->resultPrefix+"_SV.vcf", phasingResult);
}
return;
}
void SVParser::writeLine(std::string &input, bool &ps_def, std::ofstream &resultVcf, PhasingResult &phasingResult){
// header
if( input.substr(0, 2) == "##" ){
// avoid double definition
if( input.substr(0, 16) == "##FORMAT=<ID=PS," ){
ps_def = true;
}
resultVcf << input << "\n";
}
else if ( input.substr(0, 6) == "#CHROM" || input.substr(0, 6) == "#chrom" ){
// format line
if( commandLine == false ){
if(ps_def == false){
resultVcf << "##FORMAT=<ID=PS,Number=1,Type=Integer,Description=\"Phase set identifier\">\n";
ps_def = true;
}
resultVcf << "##longphaseVersion=" << params->version << "\n";
resultVcf << "##commandline=\"" << params->command << "\"\n";
commandLine = true;
}
resultVcf << input << "\n";
}
else{
std::istringstream iss(input);
std::vector<std::string> fields((std::istream_iterator<std::string>(iss)),std::istream_iterator<std::string>());
std::string chr = fields[0];
if( fields.size() == 0 )
return;
int pos = std::stoi( fields[1] );
int posIdx = pos - 1 ;
std::string key = fields[0] + "_" + std::to_string(posIdx);
PhasingResult::iterator psElementIter = phasingResult.find(key);
// PS flag already exist, erase PS info
if( fields[8].find("PS")!= std::string::npos ){
// find PS flag
int colon_pos = 0;
int ps_pos = fields[8].find("PS");
for(int i =0 ; i< ps_pos ; i++){
if(fields[8][i]==':')
colon_pos++;
}
// erase PS flag
if( fields[8].find(":",ps_pos+1) != std::string::npos ){
fields[8].erase(ps_pos, 3);
}
else{
fields[8].erase(ps_pos - 1, 3);
}
// find PS value start
int current_colon = 0;
int ps_start = 0;
for(unsigned int i =0; i < fields[9].length() ; i++){
if( current_colon >= colon_pos )
break;
if(fields[9][i]==':')
current_colon++;
ps_start++;
}
// erase PS value
if( fields[9].find(":",ps_start+1) != std::string::npos ){
int ps_end_pos = fields[9].find(":",ps_start+1);
fields[9].erase(ps_start, ps_end_pos - ps_start + 1);
}
else{
fields[9].erase(ps_start-1, fields[9].length() - ps_start + 1);
}
}
// reset GT flag
if( fields[8].find("GT")!= std::string::npos ){
// find GT flag
int colon_pos = 0;
int gt_pos = fields[8].find("GT");
for(int i =0 ; i< gt_pos ; i++){
if(fields[8][i]==':')
colon_pos++;
}
// find GT value start
int current_colon = 0;
int modify_start = 0;
for(unsigned int i =0; i < fields[9].length() ; i++){
if( current_colon >= colon_pos )
break;
if(fields[9][i]==':')
current_colon++;
modify_start++;
}
if(fields[9][modify_start+1] == '|'){
// direct modify GT value
if(fields[9][modify_start] > fields[9][modify_start+2]){
fields[9][modify_start+1] = fields[9][modify_start];
fields[9][modify_start] = fields[9][modify_start+2];
fields[9][modify_start+2] =fields[9][modify_start+1];
}
fields[9][modify_start+1] = '/';
}
}
// Check if the variant is extracted from this VCF
auto posIter = (*chrVariant)[fields[0]].find(posIdx);
// this pos is phase and exist in map
if( psElementIter != phasingResult.end() && posIter != (*chrVariant)[fields[0]].end() ){
// add PS flag and value
fields[8] = fields[8] + ":PS";
fields[9] = fields[9] + ":" + std::to_string((*psElementIter).second.block);
// find GT flag
int colon_pos = 0;
int gt_pos = fields[8].find("GT");
for(int i =0 ; i< gt_pos ; i++){
if(fields[8][i]==':')
colon_pos++;
}
// find GT value start
int current_colon = 0;
int modify_start = 0;
for(unsigned int i =0; i < fields[9].length() ; i++){
if( current_colon >= colon_pos )
break;
if(fields[9][i]==':')
current_colon++;
modify_start++;
}
// direct modify GT value
fields[9][modify_start] = (*psElementIter).second.RAstatus[0];
fields[9][modify_start+1] = '|';
fields[9][modify_start+2] = (*psElementIter).second.RAstatus[2];
}
// this pos has not been phased
else{
// add PS flag and value
fields[8] = fields[8] + ":PS";
fields[9] = fields[9] + ":.";
}
for(std::vector<std::string>::iterator fieldIter = fields.begin(); fieldIter != fields.end(); ++fieldIter){
if( fieldIter != fields.begin() )
resultVcf<< "\t";
resultVcf << (*fieldIter);
}
resultVcf << "\n";
}
}
bool SVParser::findSV(std::string chr, int position){
std::map<std::string, std::map<int, std::map<std::string ,bool> > >::iterator chrIter = chrVariant->find(chr);
// empty chromosome
if( chrIter == chrVariant->end() )
return false;
std::map<int, std::map<std::string ,bool>>::iterator posIter = (*chrVariant)[chr].find(position);
// empty position
if( posIter == (*chrVariant)[chr].end() )
return false;
return true;
}
BamParser::BamParser(std::string inputChrName, std::vector<std::string> inputBamFileVec, SnpParser &snpMap, SVParser &svFile, METHParser &modFile):chrName(inputChrName),BamFileVec(inputBamFileVec){
currentVariants = new std::map<int, RefAlt>;
currentSV = new std::map<int, std::map<std::string ,bool> >;
currentMod = new std::map<int, std::map<std::string ,RefAlt> >;
// use chromosome to find recorded snp map
(*currentVariants) = snpMap.getVariants(chrName);
// set skip variant start iterator
firstVariantIter = currentVariants->begin();
if( firstVariantIter == currentVariants->end() ){
std::cerr<< "error chromosome name or empty map.\n";
exit(1);
}
// set current chromosome SV map
(*currentSV) = svFile.getVariants(chrName);
firstSVIter = currentSV->begin();
// set current chromosome MOD map
(*currentMod) = modFile.getVariants(chrName);
firstModIter = currentMod->begin();
}
BamParser::~BamParser(){
delete currentVariants;
delete currentSV;
delete currentMod;
}
void BamParser::direct_detect_alleles(int lastSNPPos, htsThreadPool &threadPool, PhasingParameters params, std::vector<ReadVariant> &readVariantVec, const std::string &ref_string){
// record SNP start iter
std::map<int, RefAlt>::iterator tmpFirstVariantIter = firstVariantIter;
// record SV start iter
std::map<int, std::map<std::string ,bool> >::iterator tmpFirstSVIter = firstSVIter;
// record MOD start iter
std::map<int, std::map<std::string ,RefAlt> >::iterator tmpFirstModIter = firstModIter;
for( auto bamFile: BamFileVec ){
firstVariantIter = tmpFirstVariantIter;
firstSVIter = tmpFirstSVIter;
firstModIter = tmpFirstModIter;
// open bam file
samFile *fp_in = hts_open(bamFile.c_str(),"r");
// load reference file
hts_set_fai_filename(fp_in, params.fastaFile.c_str() );
// read header
bam_hdr_t *bamHdr = sam_hdr_read(fp_in);
// initialize an alignment
bam1_t *aln = bam_init1();
hts_idx_t *idx = NULL;
if ((idx = sam_index_load(fp_in, bamFile.c_str())) == 0) {
std::cout<<"ERROR: Cannot open index for bam file\n";
exit(1);
}
std::string range = chrName + ":1-" + std::to_string(lastSNPPos);
hts_itr_t* iter = sam_itr_querys(idx, bamHdr, range.c_str());
hts_set_opt(fp_in, HTS_OPT_THREAD_POOL, &threadPool);
int result;
while ((result = sam_itr_multi_next(fp_in, iter, aln)) >= 0) {
int flag = aln->core.flag;
if ( aln->core.qual < params.mappingQuality // mapping quality
|| (flag & 0x4) != 0 // read unmapped
|| (flag & 0x100) != 0 // secondary alignment. repeat.
// A secondary alignment occurs when a given read could align reasonably well to more than one place.
|| (flag & 0x400) != 0 // duplicate
// (flag & 0x800) != 0 // supplementary alignment
// A chimeric alignment is represented as a set of linear alignments that do not have large overlaps.
){
continue;
}
get_snp(*bamHdr,*aln,readVariantVec, ref_string, params.isONT);
}
hts_idx_destroy(idx);
bam_hdr_destroy(bamHdr);
bam_destroy1(aln);