-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhasingGraph.cpp
More file actions
1964 lines (1764 loc) · 85.4 KB
/
PhasingGraph.cpp
File metadata and controls
1964 lines (1764 loc) · 85.4 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
#include "PhasingGraph.h"
//SubEdge
SubEdge::SubEdge():readCount(0){
refRead = new std::map<int, std::vector<std::string> >;
altRead = new std::map<int, std::vector<std::string> >;
refQuality = new std::map<int, int>;
altQuality = new std::map<int, int>;
refReadCount = new std::map<int, float>;
altReadCount = new std::map<int, float>;
}
SubEdge::~SubEdge(){
}
void SubEdge::destroy(){
delete refRead;
delete altRead;
delete refQuality;
delete altQuality;
delete refReadCount;
delete altReadCount;
}
void SubEdge::addSubEdge(Variant ¤tNode, Variant &connectNode, std::string readName, int conditionQuality, double lowQualityWeight, bool fakeRead){
double edgeWeight = 1;
//if the base quality on both snps is high enough and didn't be marked as fakeRead, the edge has normal weight
if(fakeRead){
edgeWeight = 0.01;
}
else if( (currentNode.quality > VARIANT_UNDEFINED && currentNode.quality < conditionQuality ) || (connectNode.quality > VARIANT_UNDEFINED && connectNode.quality < conditionQuality ) ){
edgeWeight = lowQualityWeight;
}
// target noded is REF allele
if(connectNode.allele == 0 ){
// debug, this parameter will record the names of all reads between two podoubles
//(*refRead)[connectNode.position].push_back(readName);
// quality sum
// (*refQuality)[connectNode.position] += currentQuality + connectNode.quality;
(*refReadCount)[connectNode.position] += edgeWeight;
}
// target noded is ALT allele
else if(connectNode.allele == 1 ){
// debug, this parameter will record the names of all reads between two points
// (*altRead)[connectNode.position].push_back(readName);
// quality sum
// (*refQuality)[connectNode.position] += currentQuality + connectNode.quality;
(*altReadCount)[connectNode.position] += edgeWeight;
}
// readCount++;
}
std::pair<float,float> SubEdge::BestPair(int targetPos){
return std::make_pair( getRefReadCount(targetPos), getAltReadCount(targetPos) );
}
float SubEdge::getRefReadCount(int targetPos){
std::map<int, float>::iterator posIter = refReadCount->find(targetPos);
if( posIter != refReadCount->end() ){
return posIter->second;
}
return 0.0f;
}
float SubEdge::getAltReadCount(int targetPos){
std::map<int, float>::iterator posIter = altReadCount->find(targetPos);
if( posIter != altReadCount->end() ){
return posIter->second;
}
return 0.0f;
}
std::vector<std::string> SubEdge::showEdge(std::string message){
std::vector<std::string> result;
for(std::map<int, float >::iterator edgeIter = refReadCount->begin() ; edgeIter != refReadCount->end() ; edgeIter++ ){
result.push_back(message +" -> ref_" + std::to_string((*edgeIter).first) + "[label=" + std::to_string((*edgeIter).second) + "];");
}
for(std::map<int, float >::iterator edgeIter = altReadCount->begin() ; edgeIter != altReadCount->end() ; edgeIter++ ){
result.push_back(message +" -> alt_" + std::to_string((*edgeIter).first) + "[label=" + std::to_string((*edgeIter).second) + "];");
}
return result;
}
std::vector<std::pair<int,int>> SubEdge::getConnectPos(){
std::vector<std::pair<int,int>> result;
for(std::map<int, float >::iterator edgeIter = refReadCount->begin() ; edgeIter != refReadCount->end() ; edgeIter++ ){
result.push_back( std::make_pair( (*edgeIter).first, 0 ) );
}
for(std::map<int, float >::iterator edgeIter = altReadCount->begin() ; edgeIter != altReadCount->end() ; edgeIter++ ){
result.push_back( std::make_pair( (*edgeIter).first, 1 ) );
}
return result;
}
int SubEdge::getQuality(PosAllele targetPos){
// target is Ref allele
if( targetPos.second == 1 ){
std::map<int, int>::iterator qIter = refQuality->find(targetPos.first);
if( qIter == refQuality->end() )
return 0;
else
return (*refQuality)[targetPos.first];
}
// target is Alt allele
if( targetPos.second == 2 ){
std::map<int, int>::iterator qIter = altQuality->find(targetPos.first);
if( qIter == altQuality->end() )
return 0;
else
return (*altQuality)[targetPos.first];
}
return 0;
}
int SubEdge::getAvgQuality(PosAllele targetPos){
// target is Ref allele
if( targetPos.second == 1 ){
std::map<int, int>::iterator qIter = refQuality->find(targetPos.first);
if( qIter == refQuality->end() )
return 0;
else
return (*refQuality)[targetPos.first]/(*refReadCount)[targetPos.first];
}
// target is Alt allele
if( targetPos.second == 2 ){
std::map<int, int>::iterator qIter = altQuality->find(targetPos.first);
if( qIter == altQuality->end() )
return 0;
else
return (*altQuality)[targetPos.first]/(*altReadCount)[targetPos.first];
}
return 0;
}
VoteResult::VoteResult( int currPos, float variantweight ) {
Pos = currPos ;
weight = variantweight ;
}
VariantEdge::VariantEdge(int inCurrPos){
currPos = inCurrPos;
alt = new SubEdge();
ref = new SubEdge();
edgeCount = new std::map<int, std::map<int, ThreePointEdge>>;
refcnt = 0;
altcnt = 0;
coverage = 0;
}
void VariantEdge::addSegmentEdge(Variant ¤tNode, Variant &connectNode, Variant &connectSecondNode){
int alleleCombination = (currentNode.allele << 2) | (connectNode.allele << 1) | connectSecondNode.allele;
(*edgeCount)[connectNode.position][connectSecondNode.position][alleleCombination]++;
}
ThreePointEdge VariantEdge::findThreePointEdge(int pos, int nextPos){
auto iter = edgeCount->find(pos);
if(iter != edgeCount->end()){
auto innerIter = iter->second.find(nextPos);
if(innerIter != iter->second.end()){
return innerIter->second;
}
}
return ThreePointEdge();
}
//to get the value of fakeSnp
bool VariantEdge::get_fakeSnp(){
bool fakeSnp;
if(vaf == 0 || vaf == 1)
fakeSnp = true;
else
fakeSnp = false;
return fakeSnp;
}
//VariantEdge
std::pair<PosAllele,PosAllele> VariantEdge::findBestEdgePair(std::map<int, VariantInfo>::iterator currNodeIter, std::map<int, VariantInfo>::iterator nextNodeIter, double edgeThreshold, VoteResult &vote, bool debug){
int targetPos = nextNodeIter->first;
std::pair<float,float> refBestPair = ref->BestPair(targetPos);
std::pair<float,float> altBestPair = alt->BestPair(targetPos);
// get the weight of each pair
float rr = refBestPair.first;
float ra = refBestPair.second;
float ar = altBestPair.first;
float aa = altBestPair.second;
float para;
float cross;
if(currNodeIter->second.origin != SOMATIC && nextNodeIter->second.origin != SOMATIC){
para = rr + aa;
cross = ra + ar;
}else if(currNodeIter->second.origin == SOMATIC && nextNodeIter->second.origin != SOMATIC){
para = aa;
cross = ar;
}else if(currNodeIter->second.origin != SOMATIC && nextNodeIter->second.origin == SOMATIC){
para = aa;
cross = ra;
}else if(currNodeIter->second.origin == SOMATIC && nextNodeIter->second.origin == SOMATIC){
para = aa;
cross = 0;
}
// initialize the edge connection
// -1 : not connect
int refAllele = -1;
int altAllele = -1;
double edgeSimilarRatio = (double)std::min((para),(cross)) / (double)std::max((para),(cross));
vaf = (float)altcnt/(refcnt+altcnt);
//std::cout << currPos+1 << "\t" << altcnt << "\t" << refcnt << "\t" << vaf << "\n" ;
if( para > cross ){
// RR conect
refAllele = 1;
altAllele = 2;
}
else if( para < cross ){
// RA connect
refAllele = 2;
altAllele = 1;
}
else if( para == cross ){
// no connect
// not sure which is better
}
if((currNodeIter->second.type == SNP && (nextNodeIter->second.type == MOD_FORWARD_STRAND || nextNodeIter->second.type == MOD_REVERSE_STRAND)) ||
((currNodeIter->second.type == MOD_FORWARD_STRAND || currNodeIter->second.type == MOD_REVERSE_STRAND) && nextNodeIter->second.type == SNP)){
edgeThreshold = 0.3;
if((para+cross) < 1){
edgeThreshold = -1;
}
}
if( edgeSimilarRatio > edgeThreshold ){
refAllele = -1;
altAllele = -1;
}
if(debug){
std::cout << currPos << "\t->\t" << targetPos << "\t|rr aa | ra ar\t" << "\t" << rr << "\t" << aa << "\t" << ra << "\t" << ar << "\n";
}
// if the vaf is 0 or 1, we think this variant is a fake variant and we lower its weight
if ( vaf == 0 || vaf == 1 ) {
vote.weight = 0.01 ;
//std::cout<< "fakesnp\t" << currPos+1 << "->" << targetPos+1 << "\t" << vote.weight << "\n";
}
// the lower the edgeSimilarRatio means the higher reads consistency, and we will make the weight bigger if the reads consistency is high enough
else if ( (edgeSimilarRatio <= 0.1 && (para + cross) >= 1) || ((para)<1&&(cross)>=1) || ((para)>=1&&(cross)<1) ) {
vote.weight = 20 ;
}
vote.para = para ;
vote.cross = cross ;
vote.ESR = edgeSimilarRatio ;
// create edge pairs
PosAllele refEdge = std::make_pair( targetPos, refAllele );
PosAllele altEdge = std::make_pair( targetPos, altAllele );
// return edge pair
return std::make_pair( refEdge, altEdge );
}
SomaticVote VairiantGraph::patternMining(ThreePointEdge threePointEdge, bool leftPosIndel, bool middlePosIndel, bool rightPosIndel){
constexpr float condition = 2;
SomaticVote vote = VOTE_UNDEFINED;
float largest = -1;
float secondLargest = -1;
float thirdLargest = -1;
for (float value : threePointEdge) {
if (value > largest) {
thirdLargest = secondLargest;
secondLargest = largest;
largest = value;
} else if (value > secondLargest) {
thirdLargest = secondLargest;
secondLargest = value;
} else if (value > thirdLargest) {
thirdLargest = value;
}
}
if (secondLargest == 0.0f) {
return VOTE_UNDEFINED;
}
// find the vote of the third path
if (thirdLargest > 0.0f) {
for (auto &pattern : highSomaticPatterns) {
const auto &edge = pattern.edges;
float x = threePointEdge[edge[0]];
float y = threePointEdge[edge[1]];
float z = threePointEdge[edge[2]];
float score;
float VH_threshold = 0.5;
if (x >= thirdLargest && y >= thirdLargest &&
x >= condition && y >= condition &&
z >= thirdLargest) {
// check if this somatic position is an indel
if (params->phaseIndel && (
(pattern.vote >= 2 && pattern.vote <= 5 && middlePosIndel) ||
(pattern.vote >= 6 && pattern.vote <= 9 && rightPosIndel) ||
(pattern.vote >= 10 && pattern.vote <= 13 && leftPosIndel)
)) {
// indel VH regression
score = -0.2337f + 0.7643f * x + 0.7979f * y - 0.7473f * z;
}
else {
// snv VH regression
score = +0.003754 +0.014223*x +0.015017*y +0.011169*z -0.000769*x*x +0.000674*x*y +0.007199*x*z -0.004500*y*y +0.041002*y*z -0.009079*z*z +0.000015*x*x*x +0.000010*x*x*y -0.000177*x*x*z -0.000033*x*y*y -0.000075*x*y*z -0.000055*x*z*z +0.000111*y*y*y -0.000754*y*y*z -0.000201*y*z*z +0.000092*z*z*z;
}
float p = 1.0f / (1.0f + std::exp(-score));
if (p >= VH_threshold){
vote = pattern.vote;
break;
}
}
}
}
// find the vote of the second path
if(vote == VOTE_UNDEFINED && secondLargest/2 > thirdLargest){
for(auto &pattern : lowSomaticPatterns){
const auto &edge = pattern.edges;
if (threePointEdge[edge[0]] >= secondLargest &&
threePointEdge[edge[1]] >= secondLargest &&
threePointEdge[edge[2]] >= thirdLargest) {
vote = pattern.vote;
break;
}
}
}
// else if the vote is still undefined, we think the third path is disagree
if(vote == VOTE_UNDEFINED && secondLargest >= condition){
vote = DISAGREE;
}
return vote;
}
std::pair<float,float> VariantEdge::findNumberOfRead(int targetPos){
std::pair<float,float> refBestPair = ref->BestPair(targetPos);
std::pair<float,float> altBestPair = alt->BestPair(targetPos);
// get the weight of each pair
float rr = refBestPair.first;
float ra = refBestPair.second;
float ar = altBestPair.first;
float aa = altBestPair.second;
return std::make_pair( rr + aa , ra +ar );
}
//BlockRead
void BlockRead::recordRead(std::string readName){
std::map<std::string,int>::iterator readIter = readVec.find(readName);
if( readIter == readVec.end() )
readVec[readName] = 1;
else
readVec[readName]++;
}
//Handle the special case which One Long Read provides wrong info repeatedly
std::pair<float,float> VairiantGraph::Onelongcase( std::vector<VoteResult> vote ){
int counter = 0 ;
float h1 = 0 ;
float h2 = 0 ;
// iterate all the voting that previous variants provide
for ( size_t i = 0 ; i < vote.size() ; i++ ) {
// count the votes that refer to only one read
if ( (vote[i].para+vote[i].cross) <= 1 ) {
counter++ ;
}
// we will only count the votes that is not INDEL and have lower ESR beacause the INDEL is the variant has higher error rate and the lower ESR means higher reads consistency,
else if ( vote[i].ESR < 0.2 && vote[i].weight >= 1 && (*variantPosType)[vote[i].Pos].type != INDEL ) {
if ( vote[i].hap == 1 ) {
h1+=vote[i].weight ;
}
else if ( vote[i].hap == 2 ) {
h2+=vote[i].weight ;
}
}
}
//if there has less than three variants use one read to vote we cancel the mechanism
if ( counter <= 3 || (h1==0&&h2==0) ) {
return std::make_pair( -1 , -1 ) ;
}
else {
return std::make_pair( h1 , h2 ) ;
}
}
//VairiantGraph
void VairiantGraph::edgeConnectResult(std::vector<LOHSegment> &LOHSegments){
// current snp, haplotype (1 or 2), support snp
// std::map<int, std::map<int,std::vector<int> > > *hpCountMap = new std::map<int, std::map<int,std::vector<int> > >;
// current variant position, haplotype (1 or 2), previous variants' voting result
std::map<int, std::map<int,float> > *hpCountMap2 = new std::map<int, std::map<int,float> > ;
//current variant position, haplotype (1 or 2), previous variants' voting information
std::map<int, std::vector<VoteResult> > *hpCountMap3 = new std::map<int, std::vector<VoteResult> > ;
int blockStart = -1;
int currPos = -1;
int nextPos = -1;
int lastConnectPos = -1;
auto lohIter = LOHSegments.begin();
bool inLOHRegion = false;
bool genomicEventChange = false;
int prevPhasedNode = -1;
int lohStart = -1;
int lohEnd = -1;
Haplotype connectHP = HAPLOTYPE2;
// Visit all position and assign SNPs to haplotype.
// Avoid recording duplicate information,
// only one of the two alleles needs to be used for each SNP
for(auto variantIter = variantPosType->begin() ; variantIter != variantPosType->end() ; variantIter++ ){
// check next position
auto nextNodeIter = std::next(variantIter, 1);
if( nextNodeIter == variantPosType->end() ){
break;
}
currPos = variantIter->first;
nextPos = nextNodeIter->first;
// There should not be a large distance between any two variants,
// with the default being a distance of 300000bp, equivalent to one centromere length.
if(std::abs(nextPos-currPos) > params->distance ){
continue;
}
Haplotype currHP = HAPLOTYPE1;
while (lohIter != LOHSegments.end() && currPos > lohIter->end){
lohIter++;
if(lohIter != LOHSegments.end()){
lohStart = lohIter->start;
lohEnd = lohIter->end;
}
}
bool backLOHRegion = inLOHRegion;
inLOHRegion = lohStart <= currPos && currPos <= lohEnd;
if(backLOHRegion != inLOHRegion){
genomicEventChange = true;
}
if(genomicEventChange && variantIter->second.homozygous == inLOHRegion){
float haplotype1 = 0;
float haplotype2 = 0;
auto extendIter = variantIter;
while(extendIter != variantPosType->begin() && extendIter->first > prevPhasedNode){
extendIter--;
}
for(int j = 0 ; j < params->connectAdjacent && extendIter != variantPosType->begin(); ){
if (extendIter->second.homozygous != inLOHRegion) {
j++;
std::map<int,VariantEdge*>::iterator edgeIter = edgeList->find(extendIter->first);
if(edgeIter!=edgeList->end()){
float ra = edgeIter->second->ref->getAltReadCount(currPos);
float ar = edgeIter->second->alt->getRefReadCount(currPos);
float aa = edgeIter->second->alt->getAltReadCount(currPos);
float connectRef = inLOHRegion ? ra : ar;
float connectAlt = aa;
bool connect = false;
if(connectRef + connectAlt > 0 && std::max(connectRef, connectAlt) / (connectRef + connectAlt) >= 0.8){
bool isRefDominant = (connectRef > connectAlt);
if(inLOHRegion) {
auto posPhasingResultIter = posPhasingResult->find(extendIter->first);
if(posPhasingResultIter != posPhasingResult->end()) {
if(isRefDominant) {
connectHP = posPhasingResultIter->second.refHaplotype == HAPLOTYPE1 ? HAPLOTYPE2 : HAPLOTYPE1;
}else{
connectHP = posPhasingResultIter->second.refHaplotype == HAPLOTYPE2 ? HAPLOTYPE2 : HAPLOTYPE1;
}
connect = true;
}
}else{
if((lohIter-1) != LOHSegments.begin() && (lohIter-1)->startHapPos != -1){
connectHP = isRefDominant ? (connectHP == HAPLOTYPE1 ? HAPLOTYPE2 : HAPLOTYPE1) : connectHP;
}else{
connectHP = isRefDominant ? HAPLOTYPE2 : HAPLOTYPE1;
}
connect = true;
}
}
if(connect){
if(connectHP == HAPLOTYPE1){
haplotype1++;
}else{
haplotype2++;
}
}
}
if(!inLOHRegion){
break;
}
}
extendIter--;
}
if(haplotype1 != haplotype2){
if (inLOHRegion){
connectHP = haplotype1 > haplotype2 ? HAPLOTYPE1 : HAPLOTYPE2;
PhasingResult phasingResult(connectHP, blockStart, variantIter->second.type, variantIter->second.origin == SOMATIC);
posPhasingResult->emplace(currPos, phasingResult);
lohIter->startHapPos = currPos;
}else{
currHP = connectHP;
(lohIter - 1)->endHaplotype = connectHP;
}
hpCountMap2->clear();
hpCountMap3->clear();
lastConnectPos = currPos;
}else{
if(inLOHRegion){
connectHP = HAPLOTYPE2;
}else{
currHP = HAPLOTYPE1;
}
}
genomicEventChange = false;
}
if(variantIter->second.homozygous){
if(inLOHRegion){
prevPhasedNode = currPos;
}
continue;
}
// get the number of HP1 and HP2 supported reference allele
//int h1 = (*hpCountMap)[currPos][HAPLOTYPE1].size();
//int h2 = (*hpCountMap)[currPos][HAPLOTYPE2].size();
float h1 = (*hpCountMap2)[currPos][HAPLOTYPE1] ;
float h2 = (*hpCountMap2)[currPos][HAPLOTYPE2] ;
//Handle the special case which One Long Read provides wrong info repeatedly
std::pair<float, float> special = Onelongcase( (*hpCountMap3)[currPos] ) ;
if ( special.first != -1 ) {
h1 = special.first ;
h2 = special.second ;
}
// new block, set this position as block start
if( h1 == h2 ){
// No new blocks should be created if the next SNP has already been picked up
if( currPos < lastConnectPos ){
if( variantIter->second.origin == SOMATIC ){
PhasingResult phasingResult(HAPLOTYPE_UNDEFINED, blockStart, variantIter->second.type, variantIter->second.origin == SOMATIC);
posPhasingResult->emplace(currPos, phasingResult);
}
continue;
}
blockStart = currPos;
}
else{
currHP = ( h1 > h2 ? HAPLOTYPE1 : HAPLOTYPE2 );
}
// If 'continue' is not executed, a phasing result is created for the current position
PhasingResult phasingResult(currHP, blockStart, variantIter->second.type, variantIter->second.origin == SOMATIC);
posPhasingResult->emplace(currPos, phasingResult);
if(!inLOHRegion){
prevPhasedNode = currPos;
}
// Check if there is no edge from current node
std::map<int,VariantEdge*>::iterator edgeIter = edgeList->find( currPos );
if( edgeIter==edgeList->end() ){
continue;
}
// check connect between surrent SNP and next n SNPs
for(int i = 0 ; i < params->connectAdjacent;){
if(nextNodeIter->second.homozygous == false){
i++;
VoteResult vote(currPos, 1); //used to store previous 20 variants' voting information
// consider reads from the currnt SNP and the next (i+1)'s SNP
std::pair<PosAllele,PosAllele> tmp = edgeIter->second->findBestEdgePair(variantIter, nextNodeIter, params->edgeThreshold, vote, false);
// if the target is a danger indel change its weight to 0.1
if ( (*variantPosType)[currPos].type == DANGER_INDEL ) {
vote.weight = 0.1 ;
}
// -1 : no connect
// 1 : the haplotype of next (i+1)'s SNP are same as previous
// 2 : the haplotype of next (i+1)'s SNP are different as previous
if( tmp.first.second != -1 ){
// record the haplotype resut of next (i+1)'s SNP
if( (*posPhasingResult)[currPos].refHaplotype == HAPLOTYPE1 ){
if( tmp.first.second == 1 ){
// (*hpCountMap)[nextNodeIter->first][HAPLOTYPE1].push_back(currPos);
(*hpCountMap2)[nextNodeIter->first][HAPLOTYPE1] += vote.weight;
vote.hap = 1 ;
}
if( tmp.first.second == 2 ){
// (*hpCountMap)[nextNodeIter->first][HAPLOTYPE2].push_back(currPos);
(*hpCountMap2)[nextNodeIter->first][HAPLOTYPE2] += vote.weight;
vote.hap = 2 ;
}
}
if( (*posPhasingResult)[currPos].refHaplotype == HAPLOTYPE2 ){
if( tmp.first.second == 1 ){
// (*hpCountMap)[nextNodeIter->first][HAPLOTYPE2].push_back(currPos);
(*hpCountMap2)[nextNodeIter->first][HAPLOTYPE2] += vote.weight;
vote.hap = 2 ;
}
if( tmp.first.second == 2 ){
// (*hpCountMap)[nextNodeIter->first][HAPLOTYPE1].push_back(currPos);
(*hpCountMap2)[nextNodeIter->first][HAPLOTYPE1] += vote.weight;
vote.hap = 1 ;
}
}
(*hpCountMap3)[nextNodeIter->first].push_back( vote );
if( params->generateDot ){
std::string e1 = std::to_string(currPos+1) + ".1\t->\t" + std::to_string(tmp.first.first+1) + "." + std::to_string(tmp.first.second);
std::string e2 = std::to_string(currPos+1) + ".2\t->\t" + std::to_string(tmp.second.first+1) + "." + std::to_string(tmp.second.second);
dotResult.push_back(e1);
dotResult.push_back(e2);
}
lastConnectPos = nextNodeIter->first;
}
}
nextNodeIter++;
if( nextNodeIter == variantPosType->end() ){
break;
}
}
}
// delete hpCountMap;
delete hpCountMap2;
delete hpCountMap3;
}
VairiantGraph::VairiantGraph(std::string &in_ref, PhasingParameters &in_params, std::string &in_chr){
params=&in_params;
ref=&in_ref;
chr = in_chr;
variantPosType = new std::map<int,VariantInfo>;
edgeList = new std::map<int,VariantEdge*>;
readHpMap = new std::map<std::string,int>;
}
VairiantGraph::~VairiantGraph(){
}
void VairiantGraph::destroy(){
dotResult.clear();
dotResult.shrink_to_fit();
if(readVariant != nullptr){
delete readVariant;
readVariant = nullptr;
}
for( auto edgeIter = edgeList->begin() ; edgeIter != edgeList->end() ; edgeIter++ ){
edgeIter->second->ref->destroy();
edgeIter->second->alt->destroy();
edgeIter->second->edgeCount->clear();
delete edgeIter->second->ref;
delete edgeIter->second->alt;
delete edgeIter->second->edgeCount;
delete edgeIter->second;
}
edgeList->clear();
delete variantPosType;
delete edgeList;
delete readHpMap;
}
void VairiantGraph::addEdge(std::vector<ReadVariant> *in_readVariant, std::vector<LOHSegment> &LOHSegments){
readVariant = in_readVariant;
std::map<std::string,ReadVariant> mergeReadMap;
// each read will record fist and list variant posistion
std::map<std::string, std::pair<int,int>> alignRange;
// record an iterator for all alignments of a read.
std::map<std::string, std::vector<int>> readIdxVec;
// record need del read index
std::vector<int> delReadIdx;
// Check for overlaps among different alignments of a read and filter out the shorter overlapping alignments.
for (int readIter = 0; readIter < (int)in_readVariant->size(); readIter++) {
int is_toDelete = 0;
std::string readName = (*in_readVariant)[readIter].read_name;
if((*in_readVariant)[readIter].variantVec.empty())continue;
int firstVariantPos = (*in_readVariant)[readIter].variantVec.front().position;
int lastVariantPos = (*in_readVariant)[readIter].variantVec.back().position;
auto& readRange = alignRange[readName];
auto& readIdxVecRef = readIdxVec[readName];
// Initialize readRange if it's the first appearance
if (alignRange.find(readName) == alignRange.end()) {
readRange = {firstVariantPos,lastVariantPos};
} else {
// Check for overlaps
while (readRange.first <= firstVariantPos && firstVariantPos <= readRange.second) {
if (lastVariantPos < readRange.second) {
is_toDelete = 1;
delReadIdx.push_back(readIter);
break;
}
int preAlignIdx = readIdxVecRef.size() - 1;
if (preAlignIdx < 0 ) break;
const auto& previousAlignment = (*in_readVariant)[readIdxVecRef[preAlignIdx]];
const auto& prevVariantVec = previousAlignment.variantVec;
int prevStart = prevVariantVec.front().position;
int prevEnd = prevVariantVec.back().position;
double overlapStart = std::max(prevStart, firstVariantPos);
double overlapEnd = std::min(prevEnd, lastVariantPos);
if (overlapStart > overlapEnd) break; // No overlap
double overlapLen = overlapEnd - overlapStart + 1;
double alignStart = std::max(prevEnd, lastVariantPos);
double alignEnd = std::min(prevStart, firstVariantPos);
double alignSpan = alignStart - alignEnd + 1;
double overlapRatio = overlapLen / alignSpan;
// Filtering highly overlapping alignments
if (overlapRatio >= params->overlapThreshold) {
int alignLen1 = prevEnd - prevStart + 1;
int alignLen2 = lastVariantPos - firstVariantPos + 1;
if (alignLen2 <= alignLen1) {
is_toDelete = 1;
delReadIdx.push_back(readIter); // Current alignment is shorter
break;
} else {
delReadIdx.push_back(readIdxVecRef[preAlignIdx]); // Previous alignment is shorter
readIdxVecRef.pop_back();
readRange.second = (preAlignIdx > 0) ? (*in_readVariant)[readIdxVecRef[preAlignIdx - 1]].variantVec.back().position : firstVariantPos;
}
} else {
break;
}
}
// update range
readRange.second = lastVariantPos;
}
if (is_toDelete == 0 )
readIdxVecRef.push_back(readIter);
}
// sort read index
std::sort(delReadIdx.begin(), delReadIdx.end());
// remove overlap alignment
delReadIdx.push_back((int)in_readVariant->size());
int saveIter = *(delReadIdx.begin());
for (auto delIter = delReadIdx.begin(), nextdelIter = std::next(delReadIdx.begin(), 1); nextdelIter != delReadIdx.end(); delIter++ , nextdelIter++) {
auto nowDelIter = *delIter+1;
while (nowDelIter<*nextdelIter){
(*in_readVariant)[saveIter++]=(*in_readVariant)[nowDelIter++];
}
}
in_readVariant->erase( std::next(in_readVariant->begin(), saveIter), in_readVariant->end());
//position, allele, VariantBases
std::map<int, std::array<VariantBases, 2>> posAlleleCount;
for(std::vector<ReadVariant>::iterator readIter = in_readVariant->begin() ; readIter != in_readVariant->end() ; readIter++ ){
for( auto variant : (*readIter).variantVec ){
posAlleleCount[variant.position][variant.allele].targetCount++;
for(auto offsetBaseIter : variant.offsetBase){
posAlleleCount[variant.position][variant.allele].offsetDiffRefCount[offsetBaseIter.first]++;
}
}
}
std::vector<int> delPos;
for(const auto& posAlleleCountIter : posAlleleCount) {
const auto& alleleIter = posAlleleCountIter.second;
const auto& refOffsetMap = alleleIter[REF_ALLELE].offsetDiffRefCount;
const auto& altOffsetMap = alleleIter[ALT_ALLELE].offsetDiffRefCount;
int targetAltCount = alleleIter[ALT_ALLELE].targetCount;
int sameCount = 0;
for (const auto& altOffsetMapIter : altOffsetMap) {
int ra = 0;
if (refOffsetMap.count(altOffsetMapIter.first)) {
ra = refOffsetMap.at(altOffsetMapIter.first);
}
int aa = altOffsetMapIter.second;
double condition1 = (double)aa / targetAltCount;
double condition2 = (double)aa / (ra + aa);
if(condition1 >= 0.5 && condition2 >= 0.6){
sameCount++;
if(sameCount == 2){
break;
}
}
}
if(sameCount >= 2){
delPos.push_back(posAlleleCountIter.first);
}
}
int readCount=0;
// merge alignment
for(std::vector<ReadVariant>::iterator readIter = in_readVariant->begin() ; readIter != in_readVariant->end() ; readIter++ ){
std::map<std::string,ReadVariant>::iterator posIter = mergeReadMap.find((*readIter).read_name) ;
// fakeRead is initialize as fake
if ( posIter == mergeReadMap.end() ) {
mergeReadMap[(*readIter).read_name].fakeRead = false ;
}
//std::cout << (*readIter).mm_rate << "\n";
//if the mmrate too high we think it's a fake read
if( (*readIter).fakeRead == true ){
mergeReadMap[(*readIter).read_name].fakeRead = true ;
}
// Creating a pseudo read which allows filtering out variants that should not be phased
//ReadVariant tmpRead;
// Visiting all the variants on the read
for( auto variant : (*readIter).variantVec ){
readCount++;
if(std::binary_search(delPos.begin(), delPos.end(), variant.position)){
continue;
}
if( variant.quality <= VARIANT_UNDEFINED ){
(*variantPosType)[variant.position].type = static_cast<VariantType>(variant.quality);
}
else{
(*variantPosType)[variant.position].type = SNP;
}
(*variantPosType)[variant.position].homozygous = variant.homozygous;
mergeReadMap[(*readIter).read_name].variantVec.push_back(variant);
}
}
for(std::map<std::string,ReadVariant>::iterator readIter = mergeReadMap.begin() ; readIter != mergeReadMap.end() ; readIter++){
(*readIter).second.sort();
// iter all pair of snp and construct initial graph
std::vector<Variant>::iterator variant1Iter = readIter->second.variantVec.begin();
std::vector<Variant>::iterator variant2Iter = std::next(variant1Iter,1);
std::vector<Variant>::iterator variant3Iter = std::next(variant2Iter,1);
while(variant1Iter != readIter->second.variantVec.end() && variant2Iter != readIter->second.variantVec.end() ){
// create new edge if not exist
std::map<int,VariantEdge*>::iterator posIter = edgeList->find(variant1Iter->position);
if( posIter == edgeList->end() )
(*edgeList)[variant1Iter->position] = new VariantEdge(variant1Iter->position);
//count the ref and alt base amount on the variant
if( (*variant1Iter).allele == 0 && (*readIter).second.fakeRead == false ) {
(*edgeList)[(*variant1Iter).position]->refcnt++ ;
}
if( (*variant1Iter).allele == 1 && (*readIter).second.fakeRead == false ) {
(*edgeList)[(*variant1Iter).position]->altcnt++ ;
}
(*edgeList)[(*variant1Iter).position]->coverage++;
auto node = (*edgeList)[(*variant1Iter).position];
auto lohIter = LOHSegments.begin();
bool variant1InLOH = checkLOHRegion(lohIter, variant1Iter->position, LOHSegments);
bool stopTransition = false;
bool stateTransition = false;
int addHetCount = 0, addHomCount = 0;
for(; addHetCount < params->connectAdjacent;){
bool variant2InLOH = checkLOHRegion(lohIter, variant2Iter->position, LOHSegments);
if(variant1InLOH != variant2InLOH){
stateTransition = true;
}
if(stateTransition && !stopTransition && variant1InLOH == variant2InLOH){
stopTransition = true;
addHomCount = params->connectAdjacent+1;
}
bool addHom = variant1Iter->homozygous != variant2Iter->homozygous && stateTransition && !stopTransition && addHomCount <= 1;
bool addHet = variant1Iter->homozygous == false && variant2Iter->homozygous == false;
if(addHom){
addHomCount++;
}
if(addHet){
addHetCount++;
for(int nextNextNode = 0 ; nextNextNode < params->somaticConnectAdjacent && addHetCount < params->somaticConnectAdjacent;){
if( variant3Iter == readIter->second.variantVec.end() ){
break;
}
if(variant3Iter->homozygous == false){
nextNextNode++;
node->addSegmentEdge((*variant1Iter), (*variant2Iter), (*variant3Iter));
}
variant3Iter++;
}
}
if(addHom || addHet){
// this allele support ref
if( variant1Iter->allele == 0 )
node->ref->addSubEdge((*variant1Iter), (*variant2Iter), readIter->first, params->baseQuality, params->edgeWeight, (*readIter).second.fakeRead);
// this allele support alt
if( (*variant1Iter).allele == 1 )
node->alt->addSubEdge((*variant1Iter), (*variant2Iter), readIter->first, params->baseQuality, params->edgeWeight, (*readIter).second.fakeRead);
}
// next snp
variant2Iter++;
variant3Iter = std::next(variant2Iter,1);
if( variant2Iter == readIter->second.variantVec.end() ){
break;
}
}
variant1Iter++;
variant2Iter = std::next(variant1Iter,1);
variant3Iter = std::next(variant2Iter,1);
}
//count the ref and alt base amount of the last variant on the read
if ( variant1Iter != (*readIter).second.variantVec.end() && variant2Iter == (*readIter).second.variantVec.end() ) {
std::map<int,VariantEdge*>::iterator posIter = edgeList->find((*variant1Iter).position);
if( posIter == edgeList->end() ) {
(*edgeList)[(*variant1Iter).position] = new VariantEdge((*variant1Iter).position);
//(*edgeList)[(*variant1Iter).position]->vaf = (*currentVariants)[(*variant1Iter).position].vaf ;
}
if( (*variant1Iter).allele == 0 && (*readIter).second.fakeRead == false)
(*edgeList)[(*variant1Iter).position]->refcnt++ ;
if( (*variant1Iter).allele == 1 && (*readIter).second.fakeRead == false)
(*edgeList)[(*variant1Iter).position]->altcnt++ ;
(*edgeList)[(*variant1Iter).position]->coverage++;
}
}
}
bool VairiantGraph::checkLOHRegion(std::vector<LOHSegment>::iterator &lohIter, int pos, const std::vector<LOHSegment> &LOHSegments){
// Advance iterator if current position is beyond the current LOH segment's end
while (lohIter != LOHSegments.end() && pos > lohIter->end) {
lohIter++;
}
// Check if pos is within the current LOH segment
return (lohIter != LOHSegments.end() && pos >= lohIter->start && pos <= lohIter->end);
}
void VairiantGraph::somaticCalling(std::map<int, RefAlt>* variants){
std::map<int, std::array<int, 25>> voteResult;
std::map<int, double> totalArtifactPathRatio;
std::map<int, VariantInfo>::iterator nodeIter;
std::map<int, VariantInfo>::iterator nextNodeIter;
std::map<int, VariantInfo>::iterator nextNextNodeIter;
for(nodeIter = variantPosType->begin() ; nodeIter != variantPosType->end() ; nodeIter++ ){
auto variantIter = variants->find(nodeIter->first);
if(variantIter->second.originType == PON){
nodeIter->second.origin = PON;
}
if (nodeIter->second.homozygous) {
continue;
}
// check next position
nextNodeIter = std::next(nodeIter, 1);
if( nextNodeIter == variantPosType->end() ){
break;
}
// There should not be a large distance between any two variants,
// with the default being a distance of 300000bp, equivalent to one centromere length.
if(std::abs(nextNodeIter->first - nodeIter->first) > params->distance ){
continue;
}
// Check if there is no edge from current node
std::map<int,VariantEdge*>::iterator edgeIter = edgeList->find(nodeIter->first);
if( edgeIter == edgeList->end() ){
continue;
}
VariantEdge *edge = edgeIter->second;
// check connect between surrent SNP and next n SNPs
for(int i = 0 ; i < params->somaticConnectAdjacent;){
if( nextNodeIter == variantPosType->end() ){
break;
}
if (!nextNodeIter->second.homozygous) {
i++;
nextNextNodeIter = std::next(nextNodeIter, 1);
for(int j = 0 ; j < params->somaticConnectAdjacent;){
if( nextNextNodeIter == variantPosType->end() ){
break;
}
if (!nextNextNodeIter->second.homozygous) {
j++;
ThreePointEdge threePointEdge = edge->findThreePointEdge(nextNodeIter->first,nextNextNodeIter->first);
bool leftPosIndel = variantPosType->find(nodeIter->first)->second.type == INDEL;