-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathgfa.hpp
4992 lines (4595 loc) · 239 KB
/
gfa.hpp
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
/*===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
*/
#ifndef _GFA_
#define _GFA_
#include "DBGraph.hpp"
#include "graphdigger.hpp"
#include "genetic_code.hpp"
#include <random>
using namespace std;
namespace DeBruijn {
typedef CDBHashGraph DBGraph;
typedef DBGraph::Node Node;
typedef DBGraph::Successor Successor;
typedef CDBGraphDigger<DBGraph> GraphDigger;
// unlimited counter
struct SVarNum {
SVarNum(uint32_t n = 0) : m_data(1, n) {}
SVarNum& operator+=(const SVarNum& other) {
uint64_t overflow = 0;
for(unsigned i = 0; i < other.m_data.size() || overflow > 0; ++i) {
if(i == m_data.size())
m_data.push_back(0);
overflow += m_data[i];
if(i < other.m_data.size())
overflow += other.m_data[i];
m_data[i] = overflow;
overflow >>= 32;
}
return *this;
}
bool operator<(const SVarNum& other) const {
int n = m_data.size();
while(m_data[n-1] == 0 && n > 1)
--n;
int othern = other.m_data.size();
while(other.m_data[othern-1] == 0 && othern > 1)
--othern;
if(n != othern) {
return n < othern;
} else {
for(int i = n-1; i >= 0; --i) {
if(m_data[i] != other.m_data[i])
return m_data[i] < other.m_data[i];
}
return false;
}
}
string ToString() const {
// double dabble
int nbits = 32*m_data.size();
int nbcd = nbits/3;
int smin = nbcd-2;
vector<uint8_t> bcd(nbcd);
for(int i = m_data.size()-1; i >= 0; --i) {
for(int j = 0; j < 32; ++j) {
for(int k = smin; k < nbcd; ++k)
bcd[k] += (bcd[k] >= 5) ? 3 : 0;
if(bcd[smin] >= 8)
smin -= 1;
for(int k = smin; k < nbcd-1; ++k) {
bcd[k] <<= 1;
bcd[k] &= 0xF;
bcd[k] |= (bcd[k+1] >= 8);
}
int shifted_in = (m_data[i] & (1 << (31-j))) ? 1 : 0;
bcd[nbcd-1] <<= 1;
bcd[nbcd-1] &= 0xF;
bcd[nbcd-1] |= shifted_in;
}
}
auto first = find_if(bcd.begin(), bcd.end(), [](uint8_t c) { return c != 0; });
if(first == bcd.end())
return "0";
int prec = 6;
int num = bcd.end()-first;
string txt;
if(num <= prec) {
for(auto p = first; p != bcd.end(); ++p)
txt.push_back(*p+'0');
} else {
txt.push_back(*first+'0');
txt.push_back('.');
for(auto p = first+1; p < first+prec; ++p)
txt.push_back(*p+'0');
txt += "e+"+to_string(num-1);
}
return txt;
}
vector<uint32_t> m_data;
};
struct SegBase {
forward_list<Node> m_left_kmers; // kmers which left ends are at this position
forward_list<Node> m_right_kmers; // kmer(s) which right ends are at this position
int m_fork = eNoFork;
char m_nt;
bool operator==(const SegBase& other) const { return m_nt == other.m_nt; }
bool operator!=(const SegBase& other) const { return m_nt != other.m_nt; }
bool operator<(const SegBase& other) const { return m_nt < other.m_nt; }
};
class SegSeq : public deque<SegBase> {
public:
SegSeq() {}
template <typename Base>
SegSeq(const vector<Base>& seq) {
for(auto& base : seq) {
emplace_back();
back().m_nt = base.m_nt;
}
}
void RightExtend(char c, const Node& node) {
SegBase base;
base.m_nt = c;
base.m_right_kmers.push_front(node);
push_back(base);
}
void LeftExtend(char c, const Node& node) {
SegBase base;
base.m_nt = c;
base.m_left_kmers.push_front(node);
push_front(base);
}
void ClipLeft(int len) { erase(begin(), begin()+len); }
void ClipRight(int len) { erase(end()-len, end()); }
void SplitForksAndKmersFrom(SegSeq& other) {
if(size() != other.size())
throw runtime_error("Can't SplitForksAndKmersFrom from different size SegSeq");
for(size_t p = 0; p < size(); ++p) {
auto& base = (*this)[p];
auto& other_base = other[p];
base.m_fork |= other_base.m_fork;
base.m_left_kmers.splice_after(base.m_left_kmers.before_begin(), other_base.m_left_kmers);
base.m_left_kmers.sort();
base.m_left_kmers.unique();
base.m_right_kmers.splice_after(base.m_right_kmers.before_begin(), other_base.m_right_kmers);
base.m_right_kmers.sort();
base.m_right_kmers.unique();
}
}
void ReverseComplement() {
reverse(this->begin(), this->end());
for(auto& base : *this) {
base.m_nt = Complement(base.m_nt);
base.m_left_kmers.swap(base.m_right_kmers);
for(Node& node : base.m_left_kmers)
node = DBGraph::ReverseComplement(node);
for(Node& node : base.m_right_kmers)
node = DBGraph::ReverseComplement(node);
}
}
SegSeq substr(int pos, int len = numeric_limits<int>::max()) const {
SegSeq x;
x.insert(x.end(), this->begin()+pos, this->begin()+pos+min(len,(int)this->size()-pos));
return x;
}
SegSeq& operator+=(const SegSeq& other) {
insert(this->end(), other.begin(), other.end());
return *this;
}
SegSeq operator+(const SegSeq& other) const {
SegSeq x = *this;
x += other;
return x;
}
string ToString() const {
string s;
for(auto& base : *this)
s.push_back(base.m_nt);
return s;
}
};
struct GFASegment;
typedef typename list<GFASegment>::iterator GFAIterator;
struct SGFAIteratorHash { size_t operator()(const GFAIterator& i) const { return std::hash<void*>()(&*i); }};
typedef unordered_set<GFAIterator, SGFAIteratorHash> GFAIteratorUSet;
struct GFASegment {
GFASegment(const SegSeq& seq = SegSeq()) : m_seq(seq) {}
bool operator==(const GFASegment& other) const { return m_seq == other.m_seq; }// lexigraphical order, nothing else
bool operator!=(const GFASegment& other) const { return m_seq != other.m_seq; }// lexigraphical order, nothing else
bool operator<(const GFASegment& other) const { return m_seq < other.m_seq; } // lexigraphical order, nothing else
//during graph cleaning paths are aften copied; this hash is going to be used for identifying paths consisting of the 'same' segments
size_t Hash() const { return std::hash<const void*>()(m_copy_of == nullptr ? this : m_copy_of); }
bool LeftSingle() const { return !m_left_connections.empty() && next(m_left_connections.begin()) == m_left_connections.end(); }
bool LeftFork() const { return !m_left_connections.empty() && next(m_left_connections.begin()) != m_left_connections.end(); }
int LeftConnectionsNum() const { return distance(m_left_connections.begin(), m_left_connections.end()); }
bool RightSingle() const { return !m_right_connections.empty() && next(m_right_connections.begin()) == m_right_connections.end(); }
bool RightFork() const { return !m_right_connections.empty() && next(m_right_connections.begin()) != m_right_connections.end(); }
int RightConnectionsNum() const { return distance(m_right_connections.begin(), m_right_connections.end()); }
void ReverseComplement() {
m_seq.ReverseComplement();
swap(m_left_connections, m_right_connections);
swap(m_left_kmer_count, m_right_kmer_count);
swap(m_left_len, m_right_len);
swap(m_left_check, m_right_check);
}
SegSeq m_seq;
forward_list<GFAIterator> m_left_connections;
forward_list<GFAIterator> m_right_connections;
GFASegment* m_copy_of = nullptr;
GFAIterator m_copy_ofi;
size_t m_kmer_count = 0;
size_t m_left_kmer_count = 0;
size_t m_right_kmer_count = 0;
int m_num = 0;
int m_group = 0;
int m_left_len = 0; // reused for not aligned and extension length
int m_right_len = 0;
bool m_left_check = false;
bool m_right_check = false;
bool m_marked_for_erase = false;
bool m_cyclical = false;
int m_frame = -1; // frame of the left end (0-based position%3); used only for protein targets in which case it is >= 0
};
struct Position {
Position() {}
Position(GFAIterator segmp, int pos) : m_segmp(segmp), m_pos(pos) {}
GFAIterator m_segmp;
int m_pos;
};
struct Path {
//paths including differnt copies of the same sements are equal
bool operator==(const Path& other) const {
if(m_len != other.m_len || m_left != other.m_left || m_right != other.m_right || m_segments.size() != other.m_segments.size())
return false;
for(unsigned i = 0; i < m_segments.size(); ++i) {
auto ptr = m_segments[i]->m_copy_of == nullptr ? &(*m_segments[i]) : m_segments[i]->m_copy_of;
auto other_ptr = other.m_segments[i]->m_copy_of == nullptr ? &(*other.m_segments[i]) : other.m_segments[i]->m_copy_of;
if(ptr != other_ptr)
return false;
}
return true;
}
struct Hash {
size_t operator()(const Path& path) const {
size_t h = 0;
for(auto segi : path.m_segments)
h ^= segi->Hash();
return h;
}
};
const Position* CurrentPosition() const {
if(m_segments.empty() || (m_current_seg == 0 && m_current_pos.m_pos < m_left) ||
(m_current_seg == (int)m_segments.size()-1 && m_current_pos.m_pos > m_right)) {
return nullptr;
} else {
return &m_current_pos;
}
}
const Position* StepRight() {
if(m_segments.empty() || CurrentPosition() == nullptr)
return nullptr;
if(++m_current_pos.m_pos == (int)m_current_pos.m_segmp->m_seq.size() && m_current_seg < (int)m_segments.size()-1) {
m_current_pos.m_segmp = m_segments[++m_current_seg];
m_current_pos.m_pos = 0;
}
return CurrentPosition();
}
const Position* StepLeft() {
if(m_segments.empty() || CurrentPosition() == nullptr)
return nullptr;
if(--m_current_pos.m_pos < 0 && m_current_seg > 0) {
m_current_pos.m_segmp = m_segments[--m_current_seg];
m_current_pos.m_pos = m_current_pos.m_segmp->m_seq.size()-1;
}
return CurrentPosition();
}
const Position* JumpToRightEnd() {
if(m_segments.empty())
return nullptr;
m_current_seg = m_segments.size()-1;
m_current_pos.m_segmp = m_segments.back();
m_current_pos.m_pos = m_right;
return CurrentPosition();
}
const Position* JumpToLeftEnd() {
if(m_segments.empty())
return nullptr;
m_current_seg = 0;
m_current_pos.m_segmp = m_segments.front();
m_current_pos.m_pos = m_left;
return CurrentPosition();
}
string Sequence() const {
string seq;
for(unsigned i = 0; i < m_segments.size(); ++i) {
int left = (i == 0) ? m_left : 0;
int right = (i == m_segments.size()-1) ? m_right : m_segments[i]->m_seq.size()-1;
for(int j = left; j <= right; ++j)
seq.push_back(m_segments[i]->m_seq[j].m_nt);
}
return seq;
}
int Length() const { return m_len; }
Position LeftEnd() const {
Position l;
l.m_segmp = m_segments.front();
l.m_pos = m_left;
return l;
}
Position RightEnd() const {
Position r;
r.m_segmp = m_segments.back();
r.m_pos = m_right;
return r;
}
void ClipRight(int clip) {
m_len -= clip;
while(clip > 0) {
if(m_right+1 <= clip) {
clip -= m_right+1;
m_segments.pop_back();
m_right = m_segments.back()->m_seq.size()-1;
if(m_current_seg == (int)m_segments.size()) {
--m_current_seg;
m_current_pos.m_segmp = m_segments.back();
m_current_pos.m_pos = m_right;
}
} else {
m_right -= clip;
clip = 0;
if(m_current_seg == (int)m_segments.size()-1)
m_current_pos.m_pos = min(m_right, m_current_pos.m_pos);
}
}
}
void ClipLeft(int clip) {
m_len -= clip;
while(clip > 0) {
int slen = m_segments.front()->m_seq.size()-m_left;
if(slen <= clip) {
clip -= slen;
m_segments.pop_front();
m_left = 0;
if(m_current_seg == 0) {
m_current_pos.m_segmp = m_segments.front();
m_current_pos.m_pos = 0;
} else {
--m_current_seg;
}
} else {
m_left += clip;
clip = 0;
if(m_current_seg == 0)
m_current_pos.m_pos = max(m_left, m_current_pos.m_pos);
}
}
}
bool IntactPath() const {
for(auto it = m_segments.begin(); it != prev(m_segments.end()); ++it) {
if(find((*it)->m_right_connections.begin(), (*it)->m_right_connections.end(), *next(it)) == (*it)->m_right_connections.end())
return false;
}
return true;
}
deque<GFAIterator> m_segments; // all segments included in path (deque because we want a simple copy constructor)
int m_left; // starting position in leftmost segment
int m_right; // ending position in rigthmost segment (included)
Position m_current_pos; // current point
int m_current_seg; // segment for current point
int m_len;
};
typedef deque<uint64_t> TReadPosInfo;
typedef CKmerHashMap<tuple<TReadPosInfo, TReadPosInfo, SAtomic<uint8_t>>, 8> TReadPos;
typedef unordered_map<const GFAIterator, tuple<list<GFAIterator>,list<GFAIterator>>, SGFAIteratorHash> TCopyInfo;
void RecalculateCopyInfo(TCopyInfo& copies, const GFAIteratorUSet& erased) {
for(auto icopy = copies.begin(); icopy != copies.end(); ) {
auto& checked = get<0>(icopy->second);
auto& not_checked = get<1>(icopy->second);
checked.erase(remove_if(checked.begin(), checked.end(), [&](GFAIterator p) { return erased.count(p); }), checked.end()); // remove erased from list
not_checked.erase(remove_if(not_checked.begin(), not_checked.end(), [&](GFAIterator p) { return erased.count(p); }), not_checked.end()); // remove erased from list
if(checked.empty() && not_checked.empty()) { // remove empty entry
icopy = copies.erase(icopy);
} else if(erased.count(icopy->first)) { // remove erased from keys
GFAIterator firstp;
if(checked.empty()) {
firstp = not_checked.front();
not_checked.pop_front();
} else {
firstp = checked.front();
checked.pop_front();
}
firstp->m_copy_of = nullptr;
for(GFAIterator p : checked) {
p->m_copy_of = &(*firstp);
p->m_copy_ofi = firstp;
}
for(GFAIterator p : not_checked) {
p->m_copy_of = &(*firstp);
p->m_copy_ofi = firstp;
}
if(!checked.empty() || !not_checked.empty()) {
if(copies.size() == copies.max_load_factor()*copies.bucket_count())
throw runtime_error("Unexpected rehash");
auto& rslt = copies[firstp];
get<0>(rslt).splice(get<0>(rslt).end(), checked);
get<1>(rslt).splice(get<1>(rslt).end(), not_checked);
}
icopy = copies.erase(icopy);
} else {
++icopy;
}
}
}
class GFAGraph;
typedef list<GFAGraph> TGFACollection;
typedef map<string, tuple<string, int, unordered_set<uint32_t>, SAtomic<uint8_t>>> TTargets; // [accession], seq, min_len, words, centinel
class GFAGraph : public list<GFASegment> {
protected:
string m_acc;
deque<CKmerHashCount::Index> m_ksignature;
size_t m_size = 0;
int m_score = 0;
int m_kmer_len;
int m_max_num = 0;
int m_id = 0;
SAtomic<uint8_t> m_sentinel = 0;
bool m_is_aa = false;
// new members have to be added to operatpr=
public:
GFAGraph(const string& acc, int kmer_len) : m_acc(acc), m_kmer_len(kmer_len) {}
void ReverseComplement() {
for(auto& seg : *this)
seg.ReverseComplement();
}
deque<CKmerHashCount::Index>& KSignature() { return m_ksignature; }
const deque<CKmerHashCount::Index>& KSignature() const { return m_ksignature; }
int& Score() { return m_score; }
int Score() const { return m_score; }
SAtomic<uint8_t>& Sentinel() { return m_sentinel; }
int& ID() { return m_id; }
size_t& Size() { return m_size; }
int MaxNum() const { return m_max_num; }
GFAGraph& operator=(const GFAGraph& other) { //custom copy operator recreates segment links as needed
if(this != &other) {
clear();
map<const GFASegment*, GFAIterator> other_to_copy;
for(auto& seg : other) {
push_back(seg);
other_to_copy[&seg] = prev(end());
}
m_acc = other.m_acc;
m_ksignature = other.m_ksignature;
m_size = other.m_size;
m_score = other.m_score;
m_kmer_len = other.m_kmer_len;
m_max_num = other.m_max_num;
m_id = other.m_id;
m_sentinel = other.m_sentinel;
m_is_aa = other.m_is_aa;
for(auto& seg : *this) {
seg.m_num = ++m_max_num;
for(auto& lc : seg.m_left_connections)
lc = other_to_copy[&(*lc)];
for(auto& rc : seg.m_right_connections)
rc = other_to_copy[&(*rc)];
if(seg.m_copy_of != nullptr) {
seg.m_copy_ofi = other_to_copy[seg.m_copy_of];
seg.m_copy_of = &(*seg.m_copy_ofi);
}
}
}
return *this;
}
GFAGraph(const GFAGraph& other) : list<GFASegment>() { //has to use custom copy operator to recreate segment links as needed
*this = other;
}
//checks only ksignature
bool IsSubGraphOf(const GFAGraph& other) const {
if(KSignature().size() > other.KSignature().size())
return false;
deque<CKmerHashCount::Index> intersect(KSignature().size());
auto iend = set_intersection (KSignature().begin(), KSignature().end(),
other.KSignature().begin(), other.KSignature().end(),
intersect.begin());
return (iend == intersect.end());
}
void CutToChunks() {
for(auto& segm : *this) {
if(segm.m_seq.back().m_fork & eRightFork) {
for(auto rc : segm.m_right_connections)
rc->m_seq.front().m_fork |= eRightBranch;
}
if(segm.m_seq.front().m_fork & eLeftFork) {
for(auto lc : segm.m_left_connections)
lc->m_seq.back().m_fork |= eLeftBranch;
}
}
for(auto it = begin(); it != end(); ++it) {
auto& segm = *it;
auto& seq = segm.m_seq;
for(auto ib_loop = seq.begin(); ib_loop != seq.end(); ) {
auto ib = ib_loop++;
if(ib != seq.begin() && (ib->m_fork & eLeftFork)) { // not first and left fork
int len = ib-seq.begin();
push_front(seq.substr(0, len));
++m_size;
seq.erase(seq.begin(), seq.begin()+len);
front().m_seq.back().m_fork |= eLeftBranch;
front().m_group = segm.m_group;
front().m_cyclical = segm.m_cyclical;
front().m_num = ++m_max_num;
if(segm.m_frame >= 0) {
front().m_frame = segm.m_frame;
segm.m_frame = (segm.m_frame+len)%3;
}
TransferLeftLinks(it, begin());
LinkSegments(begin(), it);
}
if(ib_loop != seq.end() && (ib->m_fork & eRightFork)) { // not last and right fork
int len = ib-seq.begin()+1;
push_front(seq.substr(0, len));
++m_size;
seq.erase(seq.begin(), seq.begin()+len);
seq.front().m_fork |= eRightBranch;
front().m_group = segm.m_group;
front().m_cyclical = segm.m_cyclical;
front().m_num = ++m_max_num;
if(segm.m_frame >= 0) {
front().m_frame = segm.m_frame;
segm.m_frame = (segm.m_frame+len)%3;
}
TransferLeftLinks(it, begin());
LinkSegments(begin(), it);
}
}
}
}
void RemovePath(Path& path, bool toright, TCopyInfo& copies) {
int segn = path.m_segments.size();
GFAIteratorUSet erased;
SplitInletsBeforeClip(path, toright, copies);
if(toright) {
int clip = path.m_right+1;
for(int j = segn-2; j > 0; --j) {
auto& segi = path.m_segments[j];
auto& connections = segi->m_right_connections;
if(distance(connections.begin(), connections.end()) < 2) {
erased.insert(segi);
clip += segi->m_seq.size();
} else {
break;
}
}
UnLinkSegments(path.m_segments[segn-2], path.m_segments[segn-1]);
path.ClipRight(clip);
} else {
int clip = path.m_segments.front()->m_seq.size()-path.m_left;
for(int j = 1; j < segn-1; ++j) {
auto& segi = path.m_segments[j];
auto& connections = segi->m_left_connections;
if(distance(connections.begin(), connections.end()) < 2) {
erased.insert(segi);
clip += segi->m_seq.size();
} else {
break;
}
}
UnLinkSegments(path.m_segments[0], path.m_segments[1]);
path.ClipLeft(clip);
}
for(auto segi : erased) {
if(!segi->m_marked_for_erase) {
RemoveLinksToSegment(segi);
segi->m_left_connections.clear();
segi->m_right_connections.clear();
segi->m_marked_for_erase = true;
}
}
}
//path includes first base after clip
void SplitInletsBeforeClip(Path& path, bool toright, TCopyInfo& copies) {
int segn = path.m_segments.size();
unordered_map<GFAIterator, GFAIterator, SGFAIteratorHash> copy_info; // iterator to orig -> iterator to copy
if(toright) {
int left_inlet = find_if(path.m_segments.begin()+1, path.m_segments.end()-1, [](GFAIterator i) {return i->LeftFork();}) - path.m_segments.begin(); //ends not included
if(left_inlet >= segn-1)
return;
// copy segments; remember iterator; change num of copy (main graph)
for(int i = left_inlet; i < segn-1; ++i) {
auto iorig = path.m_segments[i];
copy_info[iorig] = PushSegmentBack(*iorig);
if(back().m_copy_of == nullptr) {
back().m_copy_of = &(*iorig);
back().m_copy_ofi = iorig;
}
if(back().m_left_check && back().m_right_check)
get<1>(copies[back().m_copy_ofi]).push_back(prev(end()));
else
get<0>(copies[back().m_copy_ofi]).push_back(prev(end()));
}
//remove left connection to copy subpath
copy_info[path.m_segments[left_inlet]]->m_left_connections.remove(path.m_segments[left_inlet-1]);
//fix connections
for(int i = left_inlet; i < segn-1; ++i) {
auto iorig = path.m_segments[i];
auto iprev_orig = path.m_segments[i-1];
auto icpy = copy_info[iorig];
//strip orig from all left connections not directly in path
for(auto& lc : icpy->m_left_connections) {
if(lc != iprev_orig)
UnLinkSegments(lc, iorig); // unlink orig if not directly in path
auto rslt = copy_info.find(lc);
if(rslt == copy_info.end()) { //from outside
lc->m_right_connections.push_front(icpy); // link copy
} else { //from copied
if(lc != iprev_orig) {
lc->m_right_connections.push_front(icpy); // relink orig to copy
icpy->m_left_connections.push_front(rslt->second); // create same link in copied path (this copied segment is now connected to both paths)
} else {
lc = rslt->second; // link copy to previous copied segment
}
}
}
//duplicate all right connections in copy
for(auto& rc : icpy->m_right_connections) {
auto rslt = copy_info.find(rc);
if(rslt != copy_info.end()) // link to copied segment
rc = rslt->second;
else
rc->m_left_connections.push_front(icpy); // connect to copy
}
}
} else {
int right_inlet = find_if(path.m_segments.rbegin()+1, path.m_segments.rend()-1, [](GFAIterator i) {return i->RightFork();}) - path.m_segments.rbegin(); //ends not included
right_inlet = segn-1-right_inlet; //in left to right direction
if(right_inlet < 1)
return;
// copy segments; remember iterator; change num of copy (main graph)
for(int i = 1; i <= right_inlet; ++i) {
auto iorig = path.m_segments[i];
copy_info[iorig] = PushSegmentBack(*iorig);
if(back().m_copy_of == nullptr) {
back().m_copy_of = &(*iorig);
back().m_copy_ofi = iorig;
}
if(back().m_left_check && back().m_right_check)
get<1>(copies[back().m_copy_ofi]).push_back(prev(end()));
else
get<0>(copies[back().m_copy_ofi]).push_back(prev(end()));
}
//remove right connection to copy subpath
copy_info[path.m_segments[right_inlet]]->m_right_connections.remove(path.m_segments[right_inlet+1]);
//fix connections
for(int i = 1; i <= right_inlet; ++i) {
auto iorig = path.m_segments[i];
auto inext_orig = path.m_segments[i+1];
auto icpy = copy_info[iorig];
//strip orig from all right connections not in path
for(auto& rc : icpy->m_right_connections) {
if(rc != inext_orig)
UnLinkSegments(iorig, rc); // unlink orig if not in path
auto rslt = copy_info.find(rc);
if(rslt == copy_info.end()) {
rc->m_left_connections.push_front(icpy);
} else {
if(rc != inext_orig){
rc->m_left_connections.push_front(icpy);
icpy->m_right_connections.push_front(rslt->second);
} else {
rc = rslt->second;
}
}
/*
if(rc != inext_orig)
UnLinkSegments(iorig, rc); // unlink orig if not in path
auto rslt = copy_info.find(rc);
if(rslt != copy_info.end()) // link to copied segment
rc = rslt->second;
else // transfer right link to copy
rc->m_left_connections.push_front(icpy);
*/
}
//duplicate all left connections in copy
for(auto& lc : icpy->m_left_connections) {
auto rslt = copy_info.find(lc);
if(rslt != copy_info.end()) // link to copied segment
lc = rslt->second;
else
lc->m_right_connections.push_front(icpy); // connect to copy
}
}
}
}
void GenerateKmers(DBGraph& dbg_graph) {
m_ksignature.clear();
int kmer_len = dbg_graph.KmerLen();
for(auto it = begin(); it != end(); ++it) {
auto& segm = *it;
auto& seq = segm.m_seq;
int seq_len = seq.size();
string s;
for(auto& base : seq) {
base.m_left_kmers.clear();
base.m_right_kmers.clear();
s.push_back(base.m_nt);
}
if(seq_len >= kmer_len) {
CReadHolder rh(false);
rh.PushBack(s);
int lpos = seq_len-kmer_len;
for(CReadHolder::kmer_iterator ik = rh.kbegin(kmer_len); ik != rh.kend(); ++ik, --lpos) { // iteration from last kmer to first
auto kmer = dbg_graph.GetNode(*ik);
if(kmer.isValid()) {
auto& lk = seq[lpos].m_left_kmers;
auto& rk = seq[lpos+kmer_len-1].m_right_kmers;
lk.push_front(kmer);
rk.push_front(kmer);
m_ksignature.push_back(kmer);
}
}
}
if(!segm.m_left_connections.empty()) {
int l = min(kmer_len-1, seq_len);
list<Path> lpaths = Expand(it, 0, kmer_len-1, l-1);
for(auto& path : lpaths) {
if(path.Length() >= kmer_len) {
CReadHolder rh(false);
rh.PushBack(path.Sequence());
int rpos = l-1;
for(CReadHolder::kmer_iterator ik = rh.kbegin(kmer_len); ik != rh.kend(); ++ik, --rpos) { // iteration from last kmer to first
auto kmer = dbg_graph.GetNode(*ik);
if(kmer.isValid()) {
auto& rk = seq[rpos].m_right_kmers;
if(find(rk.begin(), rk.end(), kmer) == rk.end()) {
rk.push_front(kmer);
m_ksignature.push_back(kmer);
}
}
}
}
}
}
if(!segm.m_right_connections.empty()) {
int l = min(kmer_len-1, seq_len);
list<Path> rpaths = Expand(it, seq_len-1, l-1, kmer_len-1);
for(auto& path : rpaths) {
if(path.Length() >= kmer_len) {
CReadHolder rh(false);
rh.PushBack(path.Sequence());
int lpos = seq_len-l+path.Length()-kmer_len;
for(CReadHolder::kmer_iterator ik = rh.kbegin(kmer_len); ik != rh.kend(); ++ik, --lpos) { // iteration from last kmer to first
auto kmer = dbg_graph.GetNode(*ik);
if(kmer.isValid()) {
auto& lk = seq[lpos].m_left_kmers;
if(find(lk.begin(), lk.end(), kmer) == lk.end()) {
lk.push_front(kmer);
m_ksignature.push_back(kmer);
}
}
}
}
}
}
}
std::sort(m_ksignature.begin(), m_ksignature.end());
m_ksignature.erase(std::unique(m_ksignature.begin(),m_ksignature.end()), m_ksignature.end());
//calculate coverage;
for(auto& seg : *this) {
vector<size_t> counts;
for(auto& base : seg.m_seq) {
size_t lcount = 0;
size_t rcount = 0;
for(Node& node : base.m_left_kmers)
lcount += dbg_graph.Abundance(node);
for(Node& node : base.m_right_kmers)
rcount += dbg_graph.Abundance(node);
counts.push_back(max(lcount, rcount));
}
std::sort(counts.begin(), counts.end());
unsigned last_chunk = counts.size()/20;
size_t count1 = 0;
for(unsigned p = 0; p < counts.size()-last_chunk; ++p)
count1 += counts[p];
size_t count2 = 0;
for(unsigned p = counts.size()-last_chunk; p < counts.size(); ++p)
count2 += counts[p];
if(count2 >= count1)
seg.m_kmer_count = count1;
else
seg.m_kmer_count = count1+count2;
}
EnumerateSegments();
}
void GenerateKmersAndScores(DBGraph& dbg_graph) {
GenerateKmers(dbg_graph);
CalculateChainLength();
CalculateCoverageAndEnumerateSegments();
}
Path ExpandEdgeToMax(GFAIterator left, GFAIterator right) {
Path path;
path.m_segments.push_back(left);
path.m_segments.push_back(right);
int len = left->m_seq.size()+right->m_seq.size();
//expand to right
while(!path.m_segments.back()->m_right_connections.empty()) {
auto& last = path.m_segments.back();
GFAIterator imax = last->m_right_connections.front();
int maxlen = imax->m_right_len+imax->m_seq.size();
size_t maxkmer = imax->m_right_kmer_count+imax->m_kmer_count;
for(auto it = next(last->m_right_connections.begin()); it != last->m_right_connections.end(); ++it) {
GFAIterator i = *it;
int ilen = i->m_right_len+i->m_seq.size();
size_t ikmer = i->m_right_kmer_count+i->m_kmer_count;
if(ikmer < maxkmer) {
continue;
} else if(ikmer > maxkmer) { //maxcount
imax = i;
maxlen = ilen;
maxkmer = ikmer;
} else if(ilen < maxlen) {
continue;
} else if(ilen > maxlen) { //longest
imax = i;
maxlen = ilen;
maxkmer = ikmer;
} else if(i->m_seq < imax->m_seq) { //alphabetical
imax = i;
maxlen = ilen;
maxkmer = ikmer;
}
}
path.m_segments.push_back(imax);
len += imax->m_seq.size();
}
//expand to left
while(!path.m_segments.front()->m_left_connections.empty()) {
auto& first = path.m_segments.front();
GFAIterator imax = first->m_left_connections.front();
int maxlen = imax->m_left_len+imax->m_seq.size();
size_t maxkmer = imax->m_left_kmer_count+imax->m_kmer_count;
for(auto it = next(first->m_left_connections.begin()); it != first->m_left_connections.end(); ++it) {
GFAIterator i = *it;
int ilen = i->m_left_len+i->m_seq.size();
size_t ikmer = i->m_left_kmer_count+i->m_kmer_count;
if(ikmer < maxkmer) {
continue;
} else if(ikmer > maxkmer) { //maxcount
imax = i;
maxlen = ilen;
maxkmer = ikmer;
} else if(ilen < maxlen) {
continue;
} else if(ilen > maxlen) { //longest
imax = i;
maxlen = ilen;
maxkmer = ikmer;
} else if(i->m_seq < imax->m_seq) { //alphabetical
imax = i;
maxlen = ilen;
maxkmer = ikmer;
}
}
path.m_segments.push_front(imax);
len += imax->m_seq.size();
}
path.m_left = 0;
path.m_right = path.m_segments.back()->m_seq.size()-1;
path.m_current_pos.m_segmp = path.m_segments.front();
path.m_current_pos.m_pos = 0;
path.m_current_seg = 0;
path.m_len = len;
return path;
}
Path ExpandToMax(GFAIterator start) {
Path path;
path.m_segments.push_back(start);
int len = start->m_seq.size();
//expand to right
while(!path.m_segments.back()->m_right_connections.empty()) {
auto& last = path.m_segments.back();
GFAIterator imax = last->m_right_connections.front();
int maxlen = imax->m_right_len+imax->m_seq.size();
size_t maxkmer = imax->m_right_kmer_count+imax->m_kmer_count;
for(auto it = next(last->m_right_connections.begin()); it != last->m_right_connections.end(); ++it) {
GFAIterator i = *it;
int ilen = i->m_right_len+i->m_seq.size();
size_t ikmer = i->m_right_kmer_count+i->m_kmer_count;
if(ikmer < maxkmer) {
continue;
} else if(ikmer > maxkmer) { //maxcount
imax = i;
maxlen = ilen;
maxkmer = ikmer;
} else if(ilen < maxlen) {
continue;
} else if(ilen > maxlen) { //longest
imax = i;
maxlen = ilen;
maxkmer = ikmer;
} else if(i->m_seq < imax->m_seq) { //alphabetical
imax = i;
maxlen = ilen;
maxkmer = ikmer;
}
}
path.m_segments.push_back(imax);
len += imax->m_seq.size();
}
//expand to left
while(!path.m_segments.front()->m_left_connections.empty()) {
auto& first = path.m_segments.front();
GFAIterator imax = first->m_left_connections.front();
int maxlen = imax->m_left_len+imax->m_seq.size();
size_t maxkmer = imax->m_left_kmer_count+imax->m_kmer_count;
for(auto it = next(first->m_left_connections.begin()); it != first->m_left_connections.end(); ++it) {
GFAIterator i = *it;