-
Notifications
You must be signed in to change notification settings - Fork 19
/
graphdigger.hpp
3306 lines (2932 loc) · 162 KB
/
graphdigger.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 _GraphDigger_
#define _GraphDigger_
#include <stack>
#include <deque>
#include <forward_list>
#include <unordered_set>
#include "glb_align.hpp"
#include "DBGraph.hpp"
namespace DeBruijn {
/************************
General description
Class CDBGraphDigger, defined in this file, performs most of the actual assembling work.
struct SContig is used to hold assembled sequences. Members are
deque<char> m_seq; // sequence representing contig
deque<CDBGraph::Node> m_kmers; // all kmers of this contig sequence
int m_kmer_len; // size of kmers used for building the contig
CDBGraph::Node m_next_left; // denied left kmer (connection possible but it is already owned)
CDBGraph::Node m_next_right; // denied right kmer (connection possible but it is already owned)
SContig* m_left_link; // if set points to 'left' contig
SContig* m_right_link; // if set points to 'right' contig
int m_left_shift; // shift+1 for m_next_left in this contig (positive for the right end)
int m_right_shift; // shift+1 for m_next_right in this contig (positive for the right end)
int m_left_extend; // number of newly assembled bases which could be clipped
int m_right_extend; // number of newly assembled bases which could be clipped
SAtomic<uint8_t> m_is_taken;
There are three main scenarios how this structure may be created
1) From a previously assembled contig represented by a c++ string.
In this case, no members other than m_seq, m_kmers, and m_kmer_len change their default zero value.
2) Assembled starting from one of the kmers which has not been used so far. Because assembly is done in multiple threads,
two or more threads could start assembling the same contig from different starting kmers. At some point they will
collide with each other and will try to obtain a kmer which has already been used by the other contig in a different
thread. When this happens, the thread stops extending the contig and assigns the denied kmer to m_next_left or m_next_right.
These partially assembled contigs (which internally are called fragments) could be connected to each other using
m_next_left/m_next_right. It is done in ConnectFragments().
3) When we increase the kmer size, some previously assembled contigs could be extended or connected because
the longer kmer could resolve some repeats. To achieve this, we assemble new contigs starting from each of the
flank kmers. When these contigs are started, m_left_link/m_right_link are assigned to point to the
parent contig and m_left_shift/m_right_shift are assigned to indicate the start position. Because the work is done
in mutiple threads, the contigs could come in two fragments if they started from different contigs and come together.
The connected fragments will have links on both sides. These contigs are 'connectors'. The rest of contigs are
'extenders'. They are used by ConnectAndExtendContigs() to form a new contig set. There is an important corner case
for connectors. A thread could start from contig A and finish assembling a connector all the way to contig B before
some other threads starts dealing with B. In this case the sequence starting from B will not contain any real bases
but will only have m_next_left/m_next_right and a link. Those are mentioned in the code as 'empty linkers' and should
be treated as special cases.
A note about multiprocessing in 2) and 3): In both cases, the threads should be able to decide which kmers or contigs are
still available for work. For communicating this information between the threads, the code uses lock-free c++ atomic
variables. For the kmers, this is stored in m_visited vector in CDBGraph. For the contigs, this is stored in m_is_taken.
The length of newly assembled sequence is stored in m_left_extend/m_right_extend.
************************/
mutex out_mutex;
enum EForkType { eNoFork = 0, eLeftFork = 1, eRightFork = 2, eLeftBranch = 4, eRightBranch = 8, eSecondaryKmer = 16 };
typedef vector<char> TVariation;
struct SeqInterval {
SeqInterval(TVariation::iterator b, TVariation::iterator e) : begin(b), end(e) {}
bool operator<(const SeqInterval& other) const { return lexicographical_compare(begin, end, other.begin, other.end); }
bool operator==(const SeqInterval& other) const { return equal(begin, end, other.begin); }
TVariation::iterator begin;
TVariation::iterator end;
};
typedef forward_list<TVariation> TLocalVariants;
class CContigSequence : public vector<TLocalVariants> {
public:
int m_left_repeat = 0; // number of bases which COULD be in repeat
int m_right_repeat = 0; // number of bases which COULD be in repeat
bool m_circular = false;
size_t MemoryFootprint() const {
size_t total = sizeof(CContigSequence)+sizeof(TLocalVariants)*capacity();
for(auto& lst : *this) {
for(auto& v : lst)
total += sizeof(TVariation)+sizeof(TVariation*)+v.capacity();
}
return total;
}
int VariantsNumber(int chunk) { return distance((*this)[chunk].begin(), (*this)[chunk].end()); }
bool UniqueChunk(int chunk) const {
auto it = (*this)[chunk].begin();
return (it != (*this)[chunk].end() && ++it == (*this)[chunk].end());
}
bool VariableChunk(int chunk) const {
auto it = (*this)[chunk].begin();
return (it != (*this)[chunk].end() && ++it != (*this)[chunk].end());
}
size_t ChunkLenMax(int chunk) const {
size_t mx = 0;
for(auto& seq : (*this)[chunk])
mx = max(mx, seq.size());
return mx;
}
size_t ChunkLenMin(int chunk) const {
size_t mn = numeric_limits<size_t>::max();
for(auto& seq : (*this)[chunk])
mn = min(mn, seq.size());
return mn;
}
size_t LenMax() const {
size_t len = 0;
for(unsigned chunk = 0; chunk < size(); ++chunk)
len += ChunkLenMax(chunk);
return len;
}
size_t LenMin() const {
size_t len = 0;
for(unsigned chunk = 0; chunk < size(); ++chunk)
len += ChunkLenMin(chunk);
return len;
}
void InsertNewVariant() { back().emplace_front(); }
void InsertNewVariant(char c) { back().emplace_front(1, c); }
template <typename ForwardIterator>
void InsertNewVariant(ForwardIterator b, ForwardIterator e) { back().emplace_front(b, e); }
void ExtendTopVariant(char c) { back().front().push_back(c); }
template <typename ForwardIterator>
void ExtendTopVariant(ForwardIterator b, ForwardIterator e) { back().front().insert(back().front().end(), b, e); }
void InsertNewChunk() { emplace_back(); }
template <typename ForwardIterator>
void InsertNewChunk(ForwardIterator b, ForwardIterator e) {
InsertNewChunk();
InsertNewVariant(b, e);
}
void StabilizeVariantsOrder() {
for(auto& chunk : *this)
chunk.sort();
}
void ReverseComplement() {
std::swap(m_left_repeat, m_right_repeat);
reverse(begin(), end());
for(auto& chunk : *this) {
for(auto& seq : chunk)
ReverseComplementSeq(seq.begin(), seq.end());
}
StabilizeVariantsOrder();
}
bool RemoveShortUniqIntervals(int min_uniq_len) {
if(size() >= 5) {
for(unsigned i = 2; i < size()-2; ) {
if((int)ChunkLenMax(i) < min_uniq_len) {
auto& new_chunk = *insert(begin()+i+2, TLocalVariants()); // empty chunk
for(auto& var1 : (*this)[i-1]) {
for(auto& var2 : (*this)[i+1]) {
new_chunk.push_front(var1);
auto& seq = new_chunk.front();
seq.insert(seq.end(), (*this)[i].front().begin(), (*this)[i].front().end());
seq.insert(seq.end(), var2.begin(), var2.end());
}
}
//erase i-1, i, i+1
erase(begin()+i-1, begin()+i+2);
} else {
i += 2;
}
}
}
if(m_circular && size() >= 5 && (int)(ChunkLenMax(0)+ChunkLenMax(size()-1)) < min_uniq_len) {
// rotate contig so that short interval is in the middle
ExtendTopVariant(front().front().begin(), front().front().end()); // add first chunk to the last
erase(begin());
rotate(begin(), begin()+1, end()); // move first variable chunk to end
InsertNewChunk();
auto& seq = front().front();
ExtendTopVariant(seq[0]); // move first base to the end
seq.erase(seq.begin());
RemoveShortUniqIntervals(min_uniq_len);
return true;
}
return false;
}
void ContractVariableIntervals() {
if(size() > 2) {
for(unsigned i = 1; i < size()-1; ++i) {
if(VariableChunk(i)) {
auto& fseq = (*this)[i].front();
unsigned len = 0;
while(true) {
bool all_same = true;
for(auto& seq : (*this)[i]) {
if(seq.size() == len || seq[len] != fseq[len]) {
all_same = false;
break;
}
}
if(all_same)
++len;
else
break;
}
if(len > 0) {
(*this)[i-1].front().insert((*this)[i-1].front().end(), fseq.begin(), fseq.begin()+len);
for(auto& seq : (*this)[i])
seq.erase(seq.begin(), seq.begin()+len);
}
len = 0;
while(true) {
bool all_same = true;
for(auto& seq : (*this)[i]) {
if(seq.size() == len || *(seq.rbegin()+len) != *(fseq.rbegin()+len)) {
all_same = false;
break;
}
}
if(all_same)
++len;
else
break;
}
if(len > 0) {
(*this)[i+1].front().insert((*this)[i+1].front().begin(), fseq.end()-len, fseq.end());
for(auto& seq : (*this)[i])
seq.erase(seq.end()-len, seq.end());
}
}
}
}
}
bool AllSameL(int chunk, int shift) const {
if(!VariableChunk(chunk))
return false;
auto Symbol_i = [](const TVariation& seq, const TVariation& next, unsigned i) {
if(i < seq.size())
return seq[i];
else if(i < seq.size()+next.size()-1 ) // -1 - we don't want to absorb all next
return next[i-seq.size()];
else
return char(0);
};
char symb = Symbol_i((*this)[chunk].front(), (*this)[chunk+1].front(), shift);
if(!symb)
return false;
auto it = (*this)[chunk].begin();
for(++it; it != (*this)[chunk].end(); ++it) {
if(Symbol_i(*it, (*this)[chunk+1].front(), shift) != symb)
return false;
}
return true;
}
bool AllSameR(int chunk, int shift) const {
if(!VariableChunk(chunk))
return false;
auto Symbol_i = [](const TVariation& seq, const TVariation& prev, unsigned i) {
if(i < seq.size())
return seq[seq.size()-1-i];
else if(i < seq.size()+prev.size()-1) // -1 - we don't want to absorb all prev
return prev[prev.size()+seq.size()-1-i];
else
return char(0);
};
char symb = Symbol_i((*this)[chunk].front(), (*this)[chunk-1].front(), shift);
if(!symb)
return false;
auto it = (*this)[chunk].begin();
for(++it; it != (*this)[chunk].end(); ++it) {
if(Symbol_i(*it, (*this)[chunk-1].front(), shift) != symb)
return false;
}
return true;
}
void IncludeRepeatsInVariableIntervals() {
for(unsigned chunk = 1; chunk < size()-1; chunk += 2) {
int min_len = ChunkLenMin(chunk);
int len = 0;
for(int shift = 0; AllSameL(chunk, shift); ++shift) {
if(shift >= min_len)
++len;
}
if(len > 0) {
min_len += len;
auto& nseq = (*this)[chunk+1].front();
for(auto& seq : (*this)[chunk])
seq.insert(seq.end(), nseq.begin(), nseq.begin()+len);
nseq.erase(nseq.begin(), nseq.begin()+len);
}
len = 0;
for(int shift = 0; AllSameR(chunk, shift); ++shift) {
if(shift >= min_len)
++len;
}
if(len > 0) {
auto& pseq = (*this)[chunk-1].front();
for(auto& seq : (*this)[chunk])
seq.insert(seq.begin(), pseq.end()-len, pseq.end());
pseq.erase(pseq.end()-len, pseq.end());
}
}
}
};
typedef list<CContigSequence> TContigSequenceList;
void CombineSimilarContigs(TContigSequenceList& contigs) {
int match = 1;
int mismatch = 2;
int gap_open = 5;
int gap_extend = 2;
SMatrix delta(match, mismatch);
list<string> all_variants;
for(auto& contig : contigs) {
list<string> variants;
for(auto& seq : contig[0])
variants.emplace_back(seq.begin(), seq.end());
for(unsigned l = 1; l < contig.size(); ++l) {
if(contig.UniqueChunk(l)) {
for(auto& seq : variants)
seq.insert(seq.end(), contig[l].front().begin(), contig[l].front().end());
} else {
list<string> new_variants;
for(auto& seq : variants) {
for(auto& var : contig[l]) {
new_variants.push_back(seq);
new_variants.back().insert(new_variants.back().end(), var.begin(), var.end());
}
}
swap(variants, new_variants);
}
}
all_variants.splice(all_variants.end(), variants);
}
all_variants.sort([](const string& a, const string& b) { return a.size() > b.size(); });
list<list<TVariation>> all_groups;
while(!all_variants.empty()) {
string& query = all_variants.front();
list<TVariation> group;
auto it_loop = all_variants.begin();
for(++it_loop; it_loop != all_variants.end(); ) {
auto it = it_loop++;
string& subject = *it;
if(query.size()-subject.size() > 0.1*query.size())
continue;
// CCigar cigar = LclAlign(query.c_str(), query.size(), subject.c_str(), subject.size(), gap_open, gap_extend, delta.matrix);
CCigar cigar = BandAlign(query.c_str(), query.size(), subject.c_str(), subject.size(), gap_open, gap_extend, delta.matrix, 0.1*query.size());
if(cigar.QueryRange().first != 0 || cigar.QueryRange().second != (int)query.size()-1)
continue;
if(cigar.SubjectRange().first != 0 || cigar.SubjectRange().second != (int)subject.size()-1)
continue;
if(cigar.Matches(query.c_str(), subject.c_str()) < 0.9*query.size())
continue;
TCharAlign align = cigar.ToAlign(query.c_str(), subject.c_str());
if(group.empty()) {
group.emplace_back(align.first.begin(), align.first.end());
group.emplace_back(align.second.begin(), align.second.end());
} else {
TVariation& master = group.front();
int mpos = 0;
TVariation new_member;
for(unsigned i = 0; i < align.first.size(); ++i) {
if(align.first[i] == master[mpos]) {
new_member.push_back(align.second[i]);
++mpos;
} else if(master[mpos] == '-') {
while(master[mpos] == '-') {
new_member.push_back('-');
++mpos;
}
new_member.push_back(align.second[i]);
++mpos;
} else { // align.first[i] == '-'
for(TVariation& seq : group)
seq.insert(seq.begin()+mpos, '-');
new_member.push_back(align.second[i]);
++mpos;
}
}
group.push_back(new_member);
}
all_variants.erase(it);
}
if(group.empty())
group.emplace_back(query.begin(), query.end());
all_groups.push_back(move(group));
all_variants.pop_front();
}
TContigSequenceList new_contigs;
for(auto& group : all_groups) {
if(group.size() == 1) {
new_contigs.push_back(CContigSequence());
new_contigs.back().InsertNewChunk(group.front().begin(), group.front().end());
continue;
}
auto NextMismatch = [&](unsigned pos) {
for( ; pos < group.front().size(); ++pos) {
for(auto& seq : group) {
if(seq[pos] != group.front()[pos])
return pos;
}
}
return pos;
};
CContigSequence combined_seq;
int min_uniq_len = 21;
for(unsigned mism = NextMismatch(0); mism < group.front().size(); mism = NextMismatch(0)) {
if(mism > 0) {
combined_seq.InsertNewChunk(group.front().begin(), group.front().begin()+mism);
for(auto& seq : group)
seq.erase(seq.begin(), seq.begin()+mism);
}
for(unsigned len = 1; len <= group.front().size(); ) {
unsigned next_mism = NextMismatch(len);
if(next_mism >= len+min_uniq_len || next_mism == group.front().size()) {
map<SeqInterval,set<SeqInterval>> varmap;
for(auto& seq : group)
varmap[SeqInterval(seq.begin(), seq.begin()+len)].emplace(seq.begin()+len, seq.end());
bool all_same = true;
for(auto it = varmap.begin(); all_same && ++it != varmap.end(); ) {
if(varmap.begin()->second != it->second)
all_same = false;
}
if(all_same) {
combined_seq.InsertNewChunk(varmap.begin()->first.begin, varmap.begin()->first.end);
for(auto it = varmap.begin(); ++it != varmap.end(); )
combined_seq.InsertNewVariant(it->first.begin, it->first.end);
for(auto& seq : group)
seq.erase(seq.begin(), seq.begin()+len);
group.sort();
group.erase(unique(group.begin(),group.end()), group.end());
break;
}
}
len = next_mism+1;
}
}
if(!group.front().empty())
combined_seq.InsertNewChunk(group.front().begin(), group.front().end());
for(auto& chunk : combined_seq) {
for(auto& seq : chunk)
seq.erase(remove(seq.begin(),seq.end(),'-'), seq.end());
}
new_contigs.push_back(move(combined_seq));
}
swap(contigs, new_contigs);
}
typedef list<string> TStrList;
template<class DBGraph> using TBases = deque<typename DBGraph::Successor>;
template<class DBGraph> struct SContig;
template<class DBGraph> using TContigList = list<SContig<DBGraph>>;
template<class DBGraph>
struct SContig {
typedef typename DBGraph::Node Node;
typedef forward_list<Node> TNodeList;
SContig(DBGraph& graph) :m_graph(graph), m_kmer_len(graph.KmerLen()) {}
SContig(const CContigSequence& contig, DBGraph& graph) : m_seq(contig), m_graph(graph), m_kmer_len(graph.KmerLen()) { GenerateKmersAndCleanSNPs(); }
void GenerateKmersAndCleanSNPs() {
if(m_seq.RemoveShortUniqIntervals(m_kmer_len))
RotateCircularToMinKmer();
int rotation = 0;
bool extended = false;
auto& first_chunk = m_seq.front().front();
auto& last_chunk = m_seq.back().front();
if(m_seq.m_circular && (int)(last_chunk.size()+first_chunk.size()) >= m_kmer_len-1) {
extended = true;
if((int)first_chunk.size() < m_kmer_len-1) {
rotation = m_kmer_len-1-first_chunk.size();
first_chunk.insert(first_chunk.begin(), last_chunk.end()-rotation, last_chunk.end());
last_chunk.erase(last_chunk.end()-rotation, last_chunk.end());
}
last_chunk.insert(last_chunk.end(), first_chunk.begin(), first_chunk.begin()+m_kmer_len-1);
}
for(int i = m_seq.size()-1; i >= 0; ) {
if(i == (int)m_seq.size()-1) {
if((int)m_seq.ChunkLenMax(i) >= m_kmer_len) { // last chunk size >= kmer_len
CReadHolder rh(false);
rh.PushBack(m_seq.back().front());
for(CReadHolder::kmer_iterator ik = rh.kbegin(m_kmer_len) ; ik != rh.kend(); ++ik) {
Node node = m_graph.GetNode(*ik);
if(node.isValid() && !m_graph.SetVisited(node))
m_graph.SetMultContig(node);
}
}
--i;
} else { // all uniq chunks >= kmer_len-1
if((int)m_seq.ChunkLenMax(i-1) >= m_kmer_len) {
CReadHolder rh(false);
rh.PushBack(m_seq[i-1].front());
for(CReadHolder::kmer_iterator ik = rh.kbegin(m_kmer_len); ik != rh.kend(); ++ik) {
Node node = m_graph.GetNode(*ik);
if(node.isValid() && !m_graph.SetVisited(node))
m_graph.SetMultContig(node);
}
}
unordered_set<Node, typename Node::Hash> kmers;
list<deque<Node>> failed_nodes;
list<TLocalVariants::iterator> failed_variants;
for(auto prev = m_seq[i].before_begin(); ;++prev) {
auto current = prev;
if(++current == m_seq[i].end())
break;
auto& variant = *current;
int left = min(m_kmer_len-1, (int)m_seq.ChunkLenMax(i-1));
TVariation var_seq(m_seq[i-1].front().end()-left, m_seq[i-1].front().end());
var_seq.insert(var_seq.end(), variant.begin(), variant.end());
int right = min(m_kmer_len-1, (int)m_seq.ChunkLenMax(i+1));
var_seq.insert(var_seq.end(), m_seq[i+1].front().begin(), m_seq[i+1].front().begin()+right);
if(i == 1 && m_seq.m_circular && !extended) { // can happen only if there is one long varianle chunk and short ends
if(m_seq.size() != 3)
throw runtime_error("Error in circular extension");
var_seq.insert(var_seq.end(), var_seq.begin(), var_seq.begin()+m_kmer_len-1);
}
CReadHolder rh(false);
rh.PushBack(var_seq);
deque<Node> var_nodes;
bool failed = false;
for(CReadHolder::kmer_iterator ik = rh.kbegin(m_kmer_len) ; ik != rh.kend(); ++ik) {
var_nodes.emplace_back(m_graph.GetNode(*ik));
if(!var_nodes.back().isValid())
failed = true;
}
if(failed) {
failed_nodes.push_back(move(var_nodes));
failed_variants.push_front(prev); // reverse order for deleting
} else {
kmers.insert(var_nodes.begin(), var_nodes.end());
}
}
if((int)failed_variants.size() == m_seq.VariantsNumber(i)) { // all failed
for(auto& nodes : failed_nodes)
kmers.insert(nodes.begin(), nodes.end());
} else { // some are good
for(auto prev : failed_variants)
m_seq[i].erase_after(prev);
if(m_seq.UniqueChunk(i)) { // only one left
m_seq[i-1].front().insert(m_seq[i-1].front().end(), m_seq[i].front().begin(), m_seq[i].front().end());
m_seq[i-1].front().insert(m_seq[i-1].front().end(), m_seq[i+1].front().begin(), m_seq[i+1].front().end());
m_seq.erase(m_seq.begin()+i, m_seq.begin()+i+2);
}
}
for(auto& node : kmers) {
if(node.isValid() && !m_graph.SetVisited(node))
m_graph.SetMultContig(node);
}
i -= 2;
}
}
if(m_seq.m_circular && extended) {
last_chunk.erase(last_chunk.end()-m_kmer_len+1, last_chunk.end());
if(rotation > 0) {
last_chunk.insert(last_chunk.end(), first_chunk.begin(), first_chunk.begin()+rotation);
first_chunk.erase(first_chunk.begin(), first_chunk.begin()+rotation);
}
}
m_seq.ContractVariableIntervals();
m_seq.IncludeRepeatsInVariableIntervals();
if(m_seq.RemoveShortUniqIntervals(m_kmer_len))
RotateCircularToMinKmer();
m_seq.StabilizeVariantsOrder();
}
SContig(const SContig& to_left, const SContig& to_right, const Node& initial_node, const Node& lnode, const Node& rnode, DBGraph& graph) :
m_next_left(lnode), m_next_right(rnode), m_graph(graph), m_kmer_len(graph.KmerLen()) {
// initial_node - the starting kmer
// to_left - left extension of the starting kmer
// to_right - right extension of the starting kmer
// lnode - left denied node
// rnode - right denied node
// graph - de Bruijn graph
// take parts of the assembled sequence and put them together in SContig
if(!to_left.m_seq.empty()) {
m_seq = to_left.m_seq;
ReverseComplement();
}
// could be changed by ReverseComplement
m_next_left = lnode;
m_next_right = rnode;
string ikmer = graph.GetNodeSeq(initial_node);
if(m_seq.empty() || m_seq.VariableChunk(m_seq.size()-1)) // empty or variant
m_seq.InsertNewChunk(ikmer.begin(), ikmer.end());
else
m_seq.ExtendTopVariant(ikmer.begin(), ikmer.end());
if(!to_right.m_seq.empty()) {
if(to_right.m_seq.UniqueChunk(0)) {
m_seq.ExtendTopVariant(to_right.m_seq.front().front().begin(), to_right.m_seq.front().front().end());
m_seq.insert(m_seq.end(), to_right.m_seq.begin()+1, to_right.m_seq.end());
} else {
m_seq.insert(m_seq.end(), to_right.m_seq.begin(), to_right.m_seq.end());
}
}
m_seq.StabilizeVariantsOrder();
m_left_extend = m_right_extend = LenMax();
}
SContig(SContig* link, int shift, const Node& takeoff_node, const SContig& extension, const Node& rnode, DBGraph& graph) :
m_next_left(takeoff_node), m_next_right(rnode), m_left_link(link), m_left_shift(shift), m_graph(graph), m_kmer_len(graph.KmerLen()) {
string kmer = graph.GetNodeSeq(takeoff_node);
m_seq.InsertNewChunk(kmer.begin()+1, kmer.end()); // don't include first base
if(!extension.m_seq.empty()) {
if(extension.m_seq.UniqueChunk(0)) {
m_seq.ExtendTopVariant(extension.m_seq.front().front().begin(), extension.m_seq.front().front().end());
m_seq.insert(m_seq.end(), extension.m_seq.begin()+1, extension.m_seq.end());
} else {
m_seq.insert(m_seq.end(), extension.m_seq.begin(), extension.m_seq.end());
}
}
m_seq.StabilizeVariantsOrder();
m_left_extend = m_right_extend = LenMax();
}
Node FrontKmer() const {
if(m_seq.VariableChunk(0) || (int)m_seq.ChunkLenMax(0) < m_kmer_len)
return Node();
string kmer_seq(m_seq.front().front().begin(), m_seq.front().front().begin()+m_kmer_len);
TKmer kmer(kmer_seq); // front must be unambiguous
return m_graph.GetNode(kmer);
}
Node BackKmer() const {
int last = m_seq.size()-1;
if(m_seq.VariableChunk(last) || (int)m_seq.ChunkLenMax(last) < m_kmer_len)
return Node();
string kmer_seq(m_seq.back().front().end()-m_kmer_len, m_seq.back().front().end());
TKmer kmer(kmer_seq);
return m_graph.GetNode(kmer);
}
// don't 'own' any kmers
bool EmptyLinker() const { return ((int)max(m_seq.ChunkLenMax(0), m_seq.ChunkLenMax(m_seq.size()-1)) < m_kmer_len && m_seq.size() <= 3); }
bool RightSNP() const { return (m_seq.size() >= 3 && m_seq.UniqueChunk(m_seq.size()-1) && (int)m_seq.ChunkLenMax(m_seq.size()-1) < m_kmer_len); }
bool LeftSNP() const { return (m_seq.size() >= 3 && m_seq.UniqueChunk(0) && (int)m_seq.ChunkLenMax(0) < m_kmer_len); }
Node RightConnectingNode() const {
int last_index = m_seq.size()-1;
if((int)m_seq.ChunkLenMax(last_index) >= m_kmer_len) { // normal end
return BackKmer();
} else if(m_seq.size() >= 3) { // snp
if((int)m_seq.ChunkLenMax(last_index-2) >= m_kmer_len) {
string kmer_seq(m_seq[last_index-2].front().end()-m_kmer_len, m_seq[last_index-2].front().end());
TKmer kmer(kmer_seq);
return m_graph.GetNode(kmer);
}
}
return m_next_left; // empty linker
}
Node LeftConnectingNode() const {
if((int)m_seq.ChunkLenMax(0) >= m_kmer_len) { // normal end
return FrontKmer();
} else if(m_seq.size() >= 3) { // snp
if((int)m_seq.ChunkLenMax(2) >= m_kmer_len) {
string kmer_seq(m_seq[2].front().begin(), m_seq[2].front().begin()+m_kmer_len);
TKmer kmer(kmer_seq); // front must be unambiguous
return m_graph.GetNode(kmer);
}
}
return m_next_right; // empty linker
}
void ReverseComplement() {
m_seq.ReverseComplement();
swap(m_next_left, m_next_right);
m_next_left = DBGraph::ReverseComplement(m_next_left);
m_next_right = DBGraph::ReverseComplement(m_next_right);
swap(m_left_link, m_right_link);
swap(m_left_shift, m_right_shift);
swap(m_left_extend, m_right_extend);
}
void AddToRight(const SContig& other) {
m_seq.m_circular = false;
m_next_right = other.m_next_right;
m_right_link = other.m_right_link;
m_right_shift = other.m_right_shift;
if(EmptyLinker() && other.EmptyLinker())
return;
auto& last_chunk = m_seq.back().front();
int last_chunk_len = last_chunk.size();
int overlap = m_kmer_len-1;
auto first_other_chunk_it = other.m_seq.begin();
if(RightSNP() && other.LeftSNP()) { // skip snp chunk
overlap = last_chunk_len+other.m_seq.ChunkLenMax(1)+first_other_chunk_it->front().size();
first_other_chunk_it += 2;
}
if(other.m_right_extend < (int)other.LenMax()) {
m_right_extend = other.m_right_extend;
} else {
m_right_extend += other.m_right_extend-overlap;
if(m_left_extend == (int)LenMax())
m_left_extend = m_right_extend;
}
auto& first_other_chunk = first_other_chunk_it->front();
last_chunk.insert(last_chunk.end(), first_other_chunk.begin()+min(m_kmer_len-1,last_chunk_len), first_other_chunk.end()); // combine overlapping chunks
m_seq.insert(m_seq.end(), first_other_chunk_it+1, other.m_seq.end()); // insert remaining chunks
}
void AddToLeft(const SContig& other) {
m_seq.m_circular = false;
m_next_left = other.m_next_left;
m_left_link = other.m_left_link;
m_left_shift = other.m_left_shift;
if(EmptyLinker() && other.EmptyLinker())
return;
auto& first_chunk = m_seq.front().front();
int first_chunk_len = first_chunk.size();
int overlap = m_kmer_len-1;
auto last_other_chunk_it = other.m_seq.end()-1;
if(LeftSNP() && other.RightSNP()) { // skip snp chunk
overlap = first_chunk_len+other.m_seq.ChunkLenMax(other.m_seq.size()-2)+last_other_chunk_it->front().size();
last_other_chunk_it -= 2;
}
if(other.m_left_extend < (int)other.LenMax()) {
m_left_extend = other.m_left_extend;
} else {
m_left_extend += other.m_left_extend-overlap;
if(m_right_extend == (int)LenMax())
m_right_extend = m_left_extend;
}
auto& last_other_chunk = last_other_chunk_it->front();
first_chunk.insert(first_chunk.begin(),last_other_chunk.begin(), last_other_chunk.end()-min(m_kmer_len-1,first_chunk_len)); // combine overlapping chunks
m_seq.insert(m_seq.begin(), other.m_seq.begin(), last_other_chunk_it); // insert remaining chunks
}
void ClipRight(int clip) {
if(clip <= 0)
return;
m_seq.m_circular = false;
m_next_right = Node();
m_right_link = nullptr;
m_right_shift = 0;
while(!m_seq.empty() && (m_seq.VariableChunk(m_seq.size()-1) || (int)m_seq.ChunkLenMax(m_seq.size()-1) <= clip)) {
int chunk_len = m_seq.ChunkLenMax(m_seq.size()-1);
clip -= chunk_len;
m_right_extend = max(0, m_right_extend-chunk_len);
m_seq.pop_back();
}
if(clip > 0 && !m_seq.empty()) {
m_right_extend = max(0, m_right_extend-clip);
m_seq.back().front().erase(m_seq.back().front().end()-clip, m_seq.back().front().end());
}
if((int)LenMin() < m_kmer_len-1)
m_seq.clear();
}
void ClipLeft(int clip) {
if(clip <= 0)
return;
m_seq.m_circular = false;
m_next_left = Node();
m_left_link = nullptr;
m_left_shift = 0;
while(!m_seq.empty() && (m_seq.VariableChunk(0) || (int)m_seq.ChunkLenMax(0) <= clip)) {
int chunk_len = m_seq.ChunkLenMax(0);
clip -= chunk_len;
m_left_extend = max(0, m_left_extend-chunk_len);
m_seq.erase(m_seq.begin());
}
if(clip > 0 && !m_seq.empty()) {
m_left_extend = max(0, m_left_extend-clip);
m_seq.front().front().erase(m_seq.front().front().begin(), m_seq.front().front().begin()+clip);
}
if((int)LenMin() < m_kmer_len-1)
m_seq.clear();
}
size_t LenMax() const { return m_seq.LenMax(); }
size_t LenMin() const { return m_seq.LenMin(); }
tuple<int, int, int> MinKmerPosition() const { //chunk, position in chunk, strand
int kmer_len = min(21, m_kmer_len); // duplicated in RotateCircularToMinKmer()
typedef LargeInt<1> large_t;
unordered_map<large_t, tuple<int, int, int>, SKmerHash> kmers; // [kmer], chunk, position in chunk, strand/notvalid
for(int i = m_seq.size()-1; i >= 0; i -= 2) {
deque<forward_list<LargeInt<1>>> chunk_kmers;
if(i == (int)m_seq.size()-1) {
if((int)m_seq.ChunkLenMax(i) >= kmer_len) { // last chunk could be short
chunk_kmers.resize(m_seq.ChunkLenMax(i)-kmer_len+1);
CReadHolder rh(false);
rh.PushBack(m_seq.back().front());
int pos = chunk_kmers.size();
for(CReadHolder::kmer_iterator ik = rh.kbegin(kmer_len) ; ik != rh.kend(); ++ik) // iteration from last kmer to first
chunk_kmers[--pos].push_front(get<large_t>(TKmer::Type(*ik)));
}
} else { // all uniq chunks in the middle >= kmer_len-1; first/last could be short
chunk_kmers.resize(m_seq.ChunkLenMax(i)+m_seq.ChunkLenMax(i+1));
if((int)m_seq.ChunkLenMax(i) >= kmer_len) {
TVariation seq(m_seq[i].front().begin(), m_seq[i].front().end());
CReadHolder rh(false);
rh.PushBack(seq);
int pos = seq.size()-kmer_len+1;
for(CReadHolder::kmer_iterator ik = rh.kbegin(kmer_len) ; ik != rh.kend(); ++ik) // iteration from last kmer to first
chunk_kmers[--pos].push_front(get<large_t>(TKmer::Type(*ik)));
}
for(auto& variant : m_seq[i+1]) {
TVariation seq;
if((int)m_seq.ChunkLenMax(i) >= kmer_len-1)
seq.insert(seq.end(), m_seq[i].front().end()-kmer_len+1, m_seq[i].front().end());
else
seq.insert(seq.end(), m_seq[i].front().begin(), m_seq[i].front().end());
seq.insert(seq.end(), variant.begin(), variant.end());
if((int)m_seq.ChunkLenMax(i+2) >= kmer_len-1)
seq.insert(seq.end(), m_seq[i+2].front().begin(), m_seq[i+2].front().begin()+kmer_len-1);
else
seq.insert(seq.end(), m_seq[i+2].front().begin(), m_seq[i+2].front().end());
CReadHolder rh(false);
rh.PushBack(seq);
int pos = seq.size()-kmer_len+1;
for(CReadHolder::kmer_iterator ik = rh.kbegin(kmer_len) ; ik != rh.kend(); ++ik) // iteration from last kmer to first
chunk_kmers[--pos].push_front(get<large_t>(TKmer::Type(*ik)));
}
}
for(unsigned pos = 0; pos < chunk_kmers.size(); ++pos) {
int k = pos;
int chunk = i;
if(pos >= m_seq.ChunkLenMax(i)) {
k = pos-m_seq.ChunkLenMax(i);
chunk = i+1;
}
for(auto& kmer : chunk_kmers[pos]) {
int strand = 1;
large_t* min_kmerp = &kmer;
large_t rkmer = revcomp(kmer, kmer_len);
if(rkmer < kmer) {
strand = -1;
min_kmerp = &rkmer;
}
auto rslt = kmers.insert(make_pair(*min_kmerp, make_tuple(chunk, k, strand)));
if(!rslt.second)
get<2>(rslt.first->second) = 0;
}
}
}
tuple<int, int, int> rslt(0, 0, 0);
large_t min_kmer;
for(auto& elem : kmers) {
if(get<2>(elem.second)) { // not a repeat
if(!get<2>(rslt) || elem.first < min_kmer) {
min_kmer = elem.first;
rslt = elem.second;
}
}
}
return rslt;
}
// stabilize contig orientation using minimal kmer in the contig
void SelectMinDirection() {
int strand = get<2>(MinKmerPosition());
if(strand < 0)
ReverseComplement();
}
// finds stable origin for circular contigs by placing minimal kmer at the beginning of the sequence
void RotateCircularToMinKmer() { // assumes that the next extension of sequence would give the first kmer (m_next_right == m_kmers.front())
int kmer_len = min(21, m_kmer_len);
m_seq.back().front().erase(m_seq.back().front().end()-(m_kmer_len-kmer_len), m_seq.back().front().end()); // clip extra portion of overlap
auto rslt = MinKmerPosition();
if(get<2>(rslt) == 0)
return;
m_seq.back().front().erase(m_seq.back().front().end()-kmer_len+1, m_seq.back().front().end()); // clip remaining overlap
size_t first_chunk = get<0>(rslt);
size_t first_base = get<1>(rslt);
if(get<2>(rslt) < 0) {
first_base += min(21, m_kmer_len);
while(first_base >= m_seq.ChunkLenMax(first_chunk)) {
first_base -= m_seq.ChunkLenMax(first_chunk);
first_chunk = (first_chunk+1)%m_seq.size();
}
if(m_seq.VariableChunk(first_chunk)) { // ambiguous interval - we don't want to cut it
++first_chunk; // variable chunk cant be last
first_base = 1;
} else if(first_chunk > 0 && first_base == 0) { // we want some uniq intervals on both ends
first_base = 1;
}
} else {
if(m_seq.VariableChunk(first_chunk)) { // ambiguous interval - we don't want to cut it
--first_chunk; // variable chunk cant be first
first_base = m_seq.ChunkLenMax(first_chunk)-1; // leave one base
} else if(first_chunk > 0 && first_base == 0) { // we want some uniq intervals on both ends
first_chunk -= 2;
first_base = m_seq.ChunkLenMax(first_chunk)-1; // leave one base
}
}
if(m_seq.size() == 1) {
rotate(m_seq.front().front().begin(), m_seq.front().front().begin()+first_base, m_seq.front().front().end());
} else {
if(first_chunk > 0) {
auto& last_seq = m_seq.back().front();
last_seq.insert(last_seq.end(), m_seq.front().front().begin(), m_seq.front().front().end());
m_seq.erase(m_seq.begin());
rotate(m_seq.begin(), m_seq.begin()+first_chunk-1, m_seq.end());
}
if(first_base > 0) {
if(m_seq.VariableChunk(m_seq.size()-1)) {
m_seq.InsertNewChunk();
m_seq.InsertNewVariant();
}
auto& last_seq = m_seq.back().front();
last_seq.insert(last_seq.end(), m_seq.front().front().begin(), m_seq.front().front().begin()+first_base);
m_seq.front().front().erase(m_seq.front().front().begin(), m_seq.front().front().begin()+first_base);
}
}