-
Notifications
You must be signed in to change notification settings - Fork 3
/
UnitigGraph.cpp
2039 lines (1971 loc) · 72 KB
/
UnitigGraph.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "UnitigGraph.h"
// so we can use range-based for loops on BGL graphs
namespace std
{
template <typename A> A begin(const pair<A, A>& s)
{
return s.first;
}
template <typename A> A end(const pair<A, A>& s)
{
return s.second;
}
}
// unitig graph for debugging purposes
UnitigGraph::UnitigGraph() : cc_(1)
{
}
// constructor of the so-called UnitigGraph
// unifies all simple paths in the deBruijnGraph to a single source->sink path
// all remaining nodes have either indegree != outdegree or indegree == outdegree > 1
UnitigGraph::UnitigGraph(deBruijnGraph& dbg, std::string p, std::string logf, float error_rate, unsigned int strict, unsigned int filter, int thresh, bool l, bool debug) : cc_(1), logfile_(logf), filter_length_(filter), thresh_(thresh), long_(l), true_(false), debug_(debug)
{
std::ofstream log;
log.open(logfile_, std::ofstream::out | std::ofstream::app);
log << "deBruijnGraph has " << dbg.getSize() << " vertices" << std::endl;
log << "Building unitig graph from deBruijn graph..." << std::endl;
log.close();
clock_t t = clock();
auto&& junc = dbg.getJunctions();
unsigned int index = 1;
auto&& out_unbalanced = junc.first;
auto&& in_unbalanced = junc.second;
auto&& thresholds = calculate_thresholds(dbg, p, strict);
thresholds_ = thresholds;
graph_map_.resize(thresholds.size());
graphs_.resize(thresholds.size());
for (auto&& g : graphs_)
{
g = new UGraph;
}
// starting from the sources, we build the unitig graph
for (auto& v : out_unbalanced)
{
std::string curr = v.get_kmer();
Vertex* source = dbg.getVertex(curr);
unsigned int cc = source->cc - 1; // cc start at 1
float threshold = thresholds.at(cc);
// make a guess whether we are relevant already
if (!source->is_flagged() and threshold > 0 and source->get_total_out_coverage() >= threshold)
{
connectUnbalanced(source, &index, curr, dbg, error_rate, threshold);
cc_++; // new connected component found
}
else
{
source->flag();
}
}
for (auto& v : in_unbalanced)
{
std::string curr = v.get_kmer();
Vertex* source = dbg.getVertex(curr);
unsigned int cc = source->cc - 1;
float threshold = thresholds.at(cc);
if (!source->is_flagged() and threshold > 0 and source->get_total_in_coverage() >= threshold)
{
connectUnbalanced(source, &index, curr, dbg, error_rate, threshold);
cc_++; // new connected component found
}
else
{
source->flag();
}
}
log.open(logfile_, std::ofstream::out | std::ofstream::app);
log << "Unitig graph successfully build in " << (clock() - t)/1000000. << " seconds." << std::endl;
unsigned int total_size = 0;
for (unsigned int cc = 0; cc < graphs_.size(); cc++)
{
total_size += boost::num_vertices(*(graphs_.at(cc)));
}
log << "Unitig graph has " << total_size << " vertices" << std::endl;
log.close();
}
UnitigGraph::~UnitigGraph()
{
for (auto&& g : graphs_)
{
delete g;
}
}
void UnitigGraph::set_debug()
{
true_ = true;
}
std::vector<float> UnitigGraph::calculate_thresholds(deBruijnGraph& dbg, std::string path, unsigned int strict)
{
std::ofstream log;
log.open(logfile_, std::ofstream::out | std::ofstream::app);
log << "Getting connected components" << std::endl;
log.close();
auto t = clock();
auto dbgs = dbg.split_ccs();
//delete dbg; // we split it up and can delete the original
log.open(logfile_, std::ofstream::out | std::ofstream::app);
log << "Getting CCs took " << (clock() - t)/1000000. << " seconds" << std::endl;
t = clock();
log << "Calculating coverage distribution" << std::endl;
log.close();
auto&& cov_distr = dbg.coverageDistribution(dbgs);
log.open(logfile_, std::ofstream::out | std::ofstream::app);
log << "Calculating coverage distribution took " << (clock() - t)/1000000. << " seconds" << std::endl;
log.close();
if (thresh_ < 0)
return get_thresholds(cov_distr, path, strict);
else
{
std::vector<float> thresholds;
for (auto& cov : cov_distr)
{
thresholds.push_back(thresh_);
}
return thresholds;
}
}
std::vector<float> UnitigGraph::get_thresholds(std::vector<std::map<unsigned int, unsigned int>>& cov_distr, std::string path, unsigned int strict)
{
std::vector<float> thresholds;
unsigned int i = 0;
unsigned int max_pos = 0;
unsigned int max_members = 0;
for (auto& covs : cov_distr)
{
if (covs.empty())
{
continue;
}
unsigned int members = 0;
std::vector<float> sorted_coverage;
sorted_coverage.resize(covs.rbegin()->first, 0.f); // get last (= biggest) element of map
std::string filename = path + "Cov" + std::to_string(i) + ".tsv";
if (debug_)
{
std::ofstream outfile (filename);
for (auto&& cov : covs)
{
auto pos = cov.first - 1;
auto val = cov.second;
members += val;
sorted_coverage[pos] = val;
outfile << pos << '\t' << val << std::endl;
}
}
else
{
for (auto&& cov : covs)
{
auto pos = cov.first - 1;
auto val = cov.second;
members += val;
sorted_coverage[pos] = val;
}
}
if (members > max_members)
{
max_members = members;
max_pos = i;
}
if (members < 150) //less than 500 kmers
{
i++;
thresholds.push_back(std::numeric_limits<float>::max()); // skip graph in creation
continue;
}
if (strict == 0)
{
auto diffs = finite_difference(sorted_coverage);
float turning_point = diffs.first;
float inflexion_point = diffs.second;
if (inflexion_point > 1 and turning_point > 1 and debug_)
{
std::ofstream log;
log.open(logfile_, std::ofstream::out | std::ofstream::app);
log << "Graph " << i << " threshold set to " << std::max(1.f, std::min(turning_point, inflexion_point)) << std::endl;
log.close();
}
thresholds.push_back(std::max(1.f, std::min(turning_point, inflexion_point))); // the threshold should never be less than 1
i++;
}
else
{
if (strict == 1)
{
unsigned int pos = 0;
for (auto& j : sorted_coverage)
{
if (pos > 0 and sorted_coverage[pos - 1] < j)
{
break;
}
pos++;
}
std::ofstream log;
if (pos > 1 and debug_)
{
log.open(logfile_, std::ofstream::out | std::ofstream::app);
log << "Graph " << i << " threshold set to " << pos - 1 << std::endl;
log.close();
}
thresholds.push_back(float(pos - 1));
i++;
}
else
{
auto&& window = rolling(sorted_coverage, strict);
int pos = 0;
for (auto& v : window)
{
if (!std::isnan(v) and window[pos - 1] < v)
{
break;
}
pos++;
}
std::ofstream log;
if (pos > 1 and debug_)
{
log.open(logfile_, std::ofstream::out | std::ofstream::app);
log << "Graph " << i << " threshold set to " << pos - 1 << std::endl;
log.close();
}
thresholds.push_back(float(pos - 1));
i++;
}
}
}
if (!debug_)
{
std::ofstream log;
log.open(logfile_, std::ofstream::out | std::ofstream::app);
log << "Printing the biggest graph with " << max_members << " k-mers" << std::endl;
log.close();
std::string filename = path + "/Cov.tsv";
std::ofstream outfile (filename);
for (auto&& cov : cov_distr.at(max_pos))
{
auto pos = cov.first - 1;
auto val = cov.second;
outfile << pos << '\t' << val << std::endl;
}
}
return thresholds;
}
// calculating finite differences, can only to 1st (false) and 2nd (true) order
std::pair<float, float> UnitigGraph::finite_difference(std::vector<float> input)
{
if (input.size() < 3)
{
return std::make_pair(1.f, 1.f);
}
float inflexion1 = 0;
float inflexion2 = 0;
for (unsigned int i = 2; i < input.size(); i++)
{
float diff1 = 0.f;
float diff2 = 0.f;
diff1 = input[i - 1] - input[i]; //1st finite difference
diff2 = input[i - 2] - 2 * input[i - 1] + input[i]; // 2nd finite derivative
if (diff1 < 0 and inflexion1 == 0)
{
inflexion1 = float(i - 1);// first diff is shifted by 1
}
if (diff2 < 0 and inflexion2 == 0)
{
inflexion2 = float(i - 2);// second diff is shifted by 2
}
}
if (inflexion1 == 0)
{
inflexion1 = 1.f;
}
if (inflexion2 == 0)
{
inflexion2 = 1.f;
}
return std::make_pair(inflexion1, inflexion2);
}
// calculates cumulative minimum of in
std::vector<float> UnitigGraph::cummin(std::vector<float>& in, unsigned int pos)
{
std::vector<float> cummin;
cummin.reserve(in.size());
float curr = in[pos];
for (unsigned int i = 0; i < pos; i++)
{
cummin.push_back(0);
}
for (auto it = in.begin() + pos; it != in.end(); ++it)
{
auto val = *it;
if (std::isnan(curr) or (val < curr and !std::isnan(val)))
{
curr = val;
}
cummin.push_back(curr);
}
return cummin;
}
// calculates rolling average over window size "len"
std::vector<float> UnitigGraph::rolling(std::vector<float>& in, unsigned int len)
{
std::vector<float> rolling;
rolling.resize(in.size());
float total = 0.0;
for (unsigned int i = 0; i < in.size() ; i++)
{
total += float(in.at(i));
if (i >= len)
{
total -= in.at(i - len);
}
if (i >= (len - 1))
{
rolling.at(i) = total/float(len);
}
else
{
rolling.at(i) = std::nanf(""); //add nan values for first len - 1 elements
}
}
return rolling;
}
// adds a vertex to the unitig graph: adds it to the boost graph, as well as to the mapping from index to vertex
UVertex UnitigGraph::addVertex(unsigned int* index, std::string name, unsigned int ccc)
{
UGraph* g = graphs_.at(ccc - 1);
UVertex uv = boost::add_vertex(*g);
(*index)++;
// set vertex properties
(*g)[uv].name = name;
(*g)[uv].index = *index;
(*g)[uv].scc = 1;
(*g)[uv].tarjan_index = 0; // needs to be 0 to find out whether it has been set
(*g)[uv].onStack = false;
(*g)[uv].cc = ccc - 1; // set cc to current CC (startin*(g) with 0 here)
(*g)[uv].visiting_time = 0;
auto&& ins = std::make_pair(*index,uv);
graph_map_.at(ccc - 1).insert(ins);
return uv;
}
// function for connecting a given source/sink vertex to all its unbalanced successors/predecessors
void UnitigGraph::connectUnbalanced(Vertex* source, unsigned int* index, std::string curr, deBruijnGraph& dbg, float error_rate, float threshold)
{
// FIFO queue for the vertices, so we do not find a reverse complement before the original vertex
std::queue<std::pair<Vertex*,std::string> > todo;
todo.push(std::make_pair(source,curr));
do //we don't necessarily need a do-while anymore
{
auto next = todo.front();
todo.pop();
Vertex* junction = next.first;
std::string seq = next.second;
std::vector<char> succ = junction->get_successors();
std::vector<char> pred = junction->get_predecessors();
bool to_search = false;
// check if there might be valid paths
for (const char& c : succ)
{
if (junction->get_out_coverage(c) > error_rate * junction->get_total_out_coverage()/* and junction->get_out_coverage(c) > threshold_*/)
{
to_search = true; break;
}
}
if (!to_search)
{
for (const char& c : pred)
{
if (junction->get_in_coverage(c) > error_rate * junction->get_total_in_coverage()/* and junction->get_in_coverage(c) > threshold_*/)
{
to_search = true; break;
}
}
}
UVertex uv;
// a junction is flagged if it has been in the queue before and does not need to be searched again
if (junction->is_flagged())
{
continue;
}
// if the source is not yet a vertex of the graph, add it
if (!junction->is_visited() and to_search)
{
junction->visit();
uv = addVertex(index, seq, junction->cc);
junction->index = *index;
}
else if (!junction->is_visited()) // this vertex is considered to be an erroneous kmer
{
junction->visit();
junction->flag();
continue;
}
else
{ //this vertex has already been found as the next junction of some other vertex, do not add again
unsigned int idx = junction->index;
uv = graph_map_.at(junction->cc - 1).at(idx);
}
junction->visit(); // make sure the next time we find it we dont add it another time
auto&& following = addNeighbours(seq, succ, pred, dbg, index, uv, threshold, error_rate); // finding the next unbalanced vertices
for (auto v : following)
{
// if no sequence is returned, no vertex was added, so we do not need to continue on this vertex
if (v.second != "")
todo.push(v);
}
} while (!todo.empty());
}
// iterating over all neighbours of current node, build the different sequences to the next unbalanced node
std::vector<std::pair<Vertex*,std::string> > UnitigGraph::addNeighbours(std::string& curr, const std::vector<char>& succ, const std::vector<char>& pred, deBruijnGraph& dbg, unsigned int* index, UVertex& uv, float threshold, float error_rate)
{
std::vector<std::pair<Vertex*,std::string> > following;
Vertex* currV = dbg.getVertex(curr);
unsigned int total_out = currV->get_total_out_coverage();
unsigned int total_in = currV->get_total_in_coverage();
Sequence src = *dbg.getSequence(curr);
// this is for checking whether the reverse complement is in the debruijn graph
bool reverse = (src != curr); // true, if reverse complement, i.e. src and curr are not the same
if (total_out) // out_degree >= 1
{
for (const auto& n : succ)
{
std::string sequence("");
std::string next;
float coverage = currV->get_out_coverage(n);
float pcov = coverage/float(total_out); // percentage of coverage
if (!reverse)
{
float curr_start = 0.f;
if (currV->get_total_out_coverage() != 0)
curr_start = currV->get_read_starts() * currV->get_out_coverage(n)/total_out;
next = curr.substr(1) + n;
Vertex* nextV = dbg.getVertex(next);
Sequence s = *dbg.getSequence(next);
sequence += n;
if (!nextV->is_flagged() and currV->get_out_coverage(n) > error_rate * total_out)
{
following.push_back(buildEdge(uv, nextV, next, sequence, index, coverage, pcov, dbg, curr_start, threshold));
}
}
// if we are a reverse complement, we actually want to add the path in reverse order
else
{
float curr_end = 0.f;
if (currV->get_total_in_coverage() != 0)
curr_end = currV->get_read_ends() * currV->get_in_coverage(deBruijnGraph::complement(n))/total_in;
next = deBruijnGraph::complement(n) + curr.substr(0,curr.length() - 1);
Vertex* nextV = dbg.getVertex(next);
Sequence s = *dbg.getSequence(next);
sequence += curr.back(); // the predecessor points to the current vertex with the last char of curr (by definition)
if (!nextV->is_flagged() and currV->get_out_coverage(n) > error_rate * total_out)
{
following.push_back(buildEdgeReverse(uv, nextV, next, sequence, index, coverage, pcov, dbg, curr_end, threshold));
}
}
}
}
// finding the predecessing unbalanced vertices
if (total_in)
{
for (const auto& n : pred)
{
std::string sequence("");
std::string prev;
float coverage = currV->get_in_coverage(n);
float pcov = coverage/float(total_in);
if (!reverse)
{
float curr_end = 0.f;
if (currV->get_total_in_coverage() != 0)
curr_end = currV->get_read_ends() * currV->get_in_coverage(n)/total_in;
prev = n + curr.substr(0,curr.length() - 1);
Vertex* nextV = dbg.getVertex(prev);
Sequence s = *dbg.getSequence(prev);
sequence += curr.back(); // the predecessor points to the current vertex with the last char of curr
if (!nextV->is_flagged() and currV->get_in_coverage(n) > error_rate * total_in)
{
following.push_back(buildEdgeReverse(uv, nextV, prev, sequence, index, coverage, pcov, dbg, curr_end, threshold));
}
}
else
{
float curr_start = 0.f;
if (currV->get_total_out_coverage() != 0)
curr_start = currV->get_read_starts() * currV->get_out_coverage(deBruijnGraph::complement(n))/total_out;
prev = curr.substr(1) + deBruijnGraph::complement(n);
Vertex* nextV = dbg.getVertex(prev);
Sequence s = *dbg.getSequence(prev);
sequence += deBruijnGraph::complement(n);
if (!nextV->is_flagged() and currV->get_in_coverage(n) > error_rate * total_in)
{
following.push_back(buildEdge(uv, nextV, prev, sequence, index, coverage, pcov, dbg, curr_start, threshold));
}
}
}
}
currV->flag(); // this vertex is done
return following;
}
// go back through the graph until the next unbalanced node is found and add an ("reversed") edge
std::pair<Vertex*,std::string> UnitigGraph::buildEdgeReverse(UVertex trg, Vertex* nextV, std::string prev, std::string& sequence, unsigned int* index, float coverage, float pcov, deBruijnGraph& dbg, float curr_end, float threshold)
{
unsigned int cc = nextV->cc - 1;
UGraph* g_ = graphs_.at(cc);
char lastchar = (*g_)[trg].name.back(); //char with which we are pointing to trg
float total_out = nextV->get_total_out_coverage();
if (total_out == 0)
{
unsigned int comp = 1;
total_out = std::max(nextV->get_out_coverage(lastchar), comp);
}
// total_out is >= 1
float starts_with = nextV->get_read_starts() * nextV->get_out_coverage(lastchar)/total_out; // number of reads starts within this edge, normalized by total flow through this edge
float ends_with = curr_end; // number of reads ends within this edge
auto&& succ = nextV->get_successors();
auto&& pred = nextV->get_predecessors();
// DEBUG
float min = coverage; // TODO
float max = coverage;
float avg = coverage;
float first = coverage; // first out-coverage
float last = coverage;
unsigned int length = 1;
// loop until the next unbalanced node is found, which is either visited (has been added) or will be added
while (!nextV->is_visited() and succ.size() == 1 and pred.size() == 1)
{
nextV->visit();
Sequence tmp = *dbg.getSequence(prev); // check for reverse complimentarity
unsigned int cov;
char c;
lastchar = prev.back(); // this will be added to the sequence
if (tmp != prev) // we are a reverse complement
{
/* if Z<-Y, Y on the complementary strand of Z and Y->X with character c:
then \overline{Y}<-\overline{X} with character \overline{c} */
c = deBruijnGraph::complement(succ[0]);
cov = nextV->get_out_coverage(succ[0]); //percentage will always be 100% on single path
}
else
{
c = pred[0];
cov = nextV->get_in_coverage(pred[0]); // see above
}
prev = c + prev.substr(0, prev.length() - 1);
// update the coverage of the path
if (cov < min)
min = cov;
if (cov > max)
max = cov;
avg += cov;
first = cov;
length++; // used for the coverage caluclations of the path later on
nextV = dbg.getVertex(prev);
pred = nextV->get_predecessors();
succ = nextV->get_successors();
sequence += lastchar;
starts_with += nextV->get_read_starts();
ends_with += nextV->get_read_ends();
}
avg /= float(length); // average coverage over the path
if (!nextV->is_visited() and (avg > threshold or sequence.length() > 150)) // TODO if coverage is low but the (unique) sequence is long, still add
{// if the next vertex has been visited it already is part of the unitiggraph, otherwise add it
nextV->visit();
addVertex(index, prev, nextV->cc); // the vertex is new and found to be relevant
nextV->index = *index;
}
else if (!nextV->is_visited() or (avg <= threshold and sequence.length() <= 150) or nextV->index == 0)
{
return std::make_pair(nextV,""); // path has too low coverage
}
UVertex src = graph_map_.at(nextV->cc - 1).at(nextV->index);
auto e = boost::edge(src,trg,*g_);
// if edge has been added or the immediate neighbour is an unbalanced vertex, do not add edge
if ((!e.second or (e.second and (*g_)[e.first].name != sequence)))
{
//set new edge's information
e = boost::add_edge(src,trg,*g_);
std::reverse(sequence.begin(), sequence.end()); // we add the path from the found node to trg, the sequence was added in reverse order
std::string old_name = (*g_)[e.first].name;
if (e.second) // TODO v-S->w-T->v is treated like v<-S-w<-T-v (should be ST self-loop and TS self-loop)
{
(*g_)[e.first].name = old_name + sequence;
}
else
{
(*g_)[e.first].name = sequence;
}
(*g_)[e.first].last_visit = 0;
(*g_)[e.first].capacity = avg;
(*g_)[e.first].residual_capacity = avg;
(*g_)[e.first].cap_info.avg = avg;
(*g_)[e.first].cap_info.max = max;
(*g_)[e.first].cap_info.min = min;
(*g_)[e.first].cap_info.first = first;
(*g_)[e.first].cap_info.last = last;
(*g_)[e.first].cap_info.length = (*g_)[e.first].name.length();
(*g_)[e.first].residual_cap_info.avg = avg;
(*g_)[e.first].residual_cap_info.max = max;
(*g_)[e.first].residual_cap_info.min = min;
(*g_)[e.first].residual_cap_info.first = first;
(*g_)[e.first].residual_cap_info.last = last;
(*g_)[e.first].residual_cap_info.length = (*g_)[e.first].name.length();
(*g_)[e.first].visited = false;
}
return std::make_pair(nextV,prev);
}
// same function like the reverse one, but going forward and finding successors
std::pair<Vertex*,std::string> UnitigGraph::buildEdge(UVertex src, Vertex* nextV, std::string next, std::string& sequence, unsigned int* index, float coverage, float pcov, deBruijnGraph& dbg, float curr_start, float threshold)
{
// with a little effort this can be moved inside the while loop for efficiency reasons
unsigned int cc = nextV->cc - 1;
UGraph* g_ = graphs_.at(cc);
float first_char = (*g_)[src].name.front();
float starts_with = curr_start; // number of reads starts within this edge, normalized by total flow through this edge
float total_in = nextV->get_total_in_coverage();
if (total_in == 0)
{
unsigned int comp = 1;
total_in = std::max(nextV->get_in_coverage(first_char), comp);
} // total_in >= 1
float ends_with = nextV->get_read_ends() * nextV->get_in_coverage(first_char)/total_in; // number of reads ends within this edge
auto&& succ = nextV->get_successors();
auto&& pred = nextV->get_predecessors();
// DEBUG, coverage information
float min = coverage; // TODO
float max = coverage;
float avg = coverage;
float first = coverage;
float last = coverage;
unsigned int length = 1;
while (!nextV->is_visited() and succ.size() == 1 and pred.size() == 1)
{
nextV->visit();
Sequence tmp = *dbg.getSequence(next);
unsigned int cov;
char c;
if (tmp != next) // we are a reverse complement
{
/* if X->Y, Y on the complementary strand of X and Y<-Z with character c:
then \overline{Y}->\overline{Z} with character \overline{c} */
c = deBruijnGraph::complement(pred[0]);
cov = nextV->get_in_coverage(pred[0]);
}
else
{
c = succ[0];
cov = nextV->get_out_coverage(succ[0]);
}
if (cov < min)
min = cov;
if (cov > max)
max = cov;
avg += cov;
last = cov;
length++;
next = next.substr(1) + c;
nextV = dbg.getVertex(next);
pred = nextV->get_predecessors();
succ = nextV->get_successors();
sequence += c;
starts_with += nextV->get_read_starts();
ends_with += nextV->get_read_ends();
}
/*
if nextV is visited then nextV may either be a junction, in which case it should have been
added as a vertex to the graph and will receive an edge. Or the path we are starting to build has already
been found having the target of the path to be found as source. This means we can break now.
If nextV still isn't visited we found a junction which has not been considered before
*/
avg /= float(length);
if (!nextV->is_visited() and (avg > threshold or sequence.length() > 150))
{
nextV->visit();
addVertex(index, next, nextV->cc);
nextV->index = *index;
}
else if (!nextV->is_visited() or (avg <= threshold and sequence.length() <= 150) or nextV->index == 0)
{
return std::make_pair(nextV,"");
}
UVertex trg = graph_map_.at(nextV->cc - 1).at(nextV->index);
auto e = boost::edge(src,trg,*g_);
if ((!e.second or (e.second and (*g_)[e.first].name != sequence)))
{
e = boost::add_edge(src,trg,*g_);
auto old_name = (*g_)[e.first].name;
if (e.second) // TODO v-S->w-T->v is treated like v<-S-w<-T-v (should be ST self-loop and TS self-loop)
{
(*g_)[e.first].name = sequence + old_name;
}
else
{
(*g_)[e.first].name = sequence;
}
(*g_)[e.first].last_visit = 0;
(*g_)[e.first].capacity = avg;
(*g_)[e.first].residual_capacity = avg;
(*g_)[e.first].cap_info.avg = avg;
(*g_)[e.first].cap_info.max = max;
(*g_)[e.first].cap_info.min = min;
(*g_)[e.first].cap_info.first = first;
(*g_)[e.first].cap_info.last = last;
(*g_)[e.first].cap_info.length = (*g_)[e.first].name.length();
(*g_)[e.first].residual_cap_info.avg = avg;
(*g_)[e.first].residual_cap_info.max = max;
(*g_)[e.first].residual_cap_info.min = min;
(*g_)[e.first].residual_cap_info.first = first;
(*g_)[e.first].residual_cap_info.last = last;
(*g_)[e.first].residual_cap_info.length = (*g_)[e.first].name.length();
(*g_)[e.first].visited = false;
}
return std::make_pair(nextV,next);
}
// contracts all simple paths in graph to a single source-sink connection
void UnitigGraph::contractPaths(unsigned int cc)
{
UGraph* g_ = graphs_.at(cc);
boost::graph_traits<UGraph>::vertex_iterator vi, vi_end, next;
boost::tie(vi, vi_end) = boost::vertices(*g_);
for (next = vi; vi != vi_end; vi = next)
{
++next;
unsigned int indegree = boost::in_degree(*vi, *g_);
unsigned int outdegree = boost::out_degree(*vi, *g_);
// if in and outdegree is 1, we are on a simple path and can contract again
if (outdegree == 1 and indegree == 1)
{
auto&& ie = boost::in_edges(*vi,*g_);
auto&& oe = boost::out_edges(*vi,*g_);
auto&& new_source = boost::source(*ie.first,*g_);
auto&& new_target = boost::target(*oe.first,*g_);
if (new_source == new_target)
{
continue; // do not contract to single vertex (which might get deleted)
}
auto&& e = boost::edge(new_source,*vi,*g_);
auto&& f = boost::edge(*vi, new_target,*g_); // coverage etc of second edge to be contracted
std::string seq = (*g_)[e.first].name;
unsigned int w = seq.length();
Capacity cap_info_e = (*g_)[e.first].cap_info;
Capacity cap_info_f = (*g_)[f.first].cap_info;
float max = std::max(cap_info_e.max, cap_info_f.max);
float min = std::min(cap_info_e.min, cap_info_f.min);
float first = cap_info_e.first;
float last = cap_info_f.last;
// TODO temporarily disabled to study effect of not contracting
//if (std::abs(cap_info_f.first - cap_info_e.last) > thresholds_.at(cc) or std::abs(cap_info_f.first - cap_info_e.last) > thresholds_.at(cc)) // do not contract paths which have high divergence in capacity
// continue;
float capacity = (*g_)[e.first].capacity * w;
e = boost::edge(*vi,new_target,*g_);
seq += (*g_)[e.first].name; // append the sequence
capacity += (*g_)[e.first].capacity * (seq.length() - w);
if (seq.length() > 0)
capacity /= seq.length(); // currently using the average coverage on the contracted path
auto&& new_e = boost::add_edge(new_source,new_target,*g_);
(*g_)[new_e.first].last_visit = 0;
(*g_)[new_e.first].name = seq;
(*g_)[new_e.first].capacity = capacity;
(*g_)[new_e.first].residual_capacity = capacity;
(*g_)[new_e.first].cap_info.avg = capacity;
(*g_)[new_e.first].cap_info.max = max;
(*g_)[new_e.first].cap_info.min = min;
(*g_)[new_e.first].cap_info.first = first;
(*g_)[new_e.first].cap_info.last = last;
(*g_)[new_e.first].cap_info.length = (*g_)[new_e.first].name.length();
(*g_)[new_e.first].residual_cap_info.avg = capacity;
(*g_)[new_e.first].residual_cap_info.max = max;
(*g_)[new_e.first].residual_cap_info.min = min;
(*g_)[new_e.first].residual_cap_info.first = first;
(*g_)[new_e.first].residual_cap_info.last = last;
(*g_)[new_e.first].residual_cap_info.length = (*g_)[e.first].name.length();
(*g_)[new_e.first].visited = false;
boost::clear_vertex(*vi,*g_);
boost::remove_vertex(*vi,*g_);
}
}
}
void UnitigGraph::removeStableSets(unsigned int cc)
{
UGraph* g_ = graphs_.at(cc);
boost::graph_traits<UGraph>::vertex_iterator vi, vi_end, next;
boost::tie(vi, vi_end) = boost::vertices(*g_);
for (next = vi; vi != vi_end; vi = next) {
++next;
unsigned int indegree = boost::in_degree(*vi, *g_);
unsigned int outdegree = boost::out_degree(*vi,*g_);
if (outdegree == 0 and indegree == 0)
{
boost::remove_vertex(*vi,*g_);
}
}
}
bool UnitigGraph::hasRelevance(unsigned int cc)
{
UGraph* g_ = graphs_.at(cc);
unsigned int length = 0;
for (auto&& e : boost::edges(*g_))
{
length += (*g_)[e].name.size();
}
if (length <= 150)
{
std::ofstream log;
log.open(logfile_, std::ofstream::out | std::ofstream::app);
log << "Graph undercutting threshold of 150 characters (" << length << ")" << std::endl;
log.close();
}
return length > 150;
}
// the graph might contain some unconnected vertices, clean up
void UnitigGraph::cleanGraph(unsigned int cc, float error_rate)
{
UGraph* g_ = graphs_.at(cc);
for (auto e : boost::edges(*g_))
{
(*g_)[e].last_visit = 0; // reusing for number of allowed paths
}
removeLowEdges(cc, error_rate);
removeEmpty(cc);
removeStableSets(cc);
contractPaths(cc);
removeShortPaths(cc);
removeEmpty(cc);
removeStableSets(cc);
contractPaths(cc);
}
void UnitigGraph::removeShortPaths(unsigned int cc)
{
UGraph* g_ = graphs_.at(cc);
std::vector<UEdge> toDelete;
for (auto&& e : boost::edges(*g_))
{
auto source = boost::source(e, *g_);
auto target = boost::target(e, *g_);
// we are a simple edge between two vertices, unconnected to the rest
if ((boost::out_degree(target, *g_) == 0 and boost::in_degree(source, *g_) == 0
and boost::out_degree(source, *g_) == 1 and boost::in_degree(target, *g_) == 1))
{
if ((*g_)[e].name.size() < 150)
{
toDelete.push_back(e);
}
}
else if ((boost::out_degree(target, *g_) == 1 and boost::in_degree(source, *g_) == 1
and boost::out_degree(source, *g_) == 1 and boost::in_degree(target, *g_) == 1))
{
float length = (*g_)[e].name.size();
auto rev_e = boost::edge(target, source, *g_);
if (rev_e.second)
{
length += (*g_)[rev_e.first].name.size();
if (length < 150)
{
toDelete.push_back(e);
}
}
}
}
for (auto&& e : toDelete)
{
boost::remove_edge(e, *g_);
}
}
void UnitigGraph::removeLowEdges(unsigned int cc, float error_rate)
{
UGraph* g_ = graphs_.at(cc);
std::set<UEdge> toDelete;
for (auto v : boost::vertices(*g_))
{
auto out_edges = boost::out_edges(v, *g_);
auto in_edges = boost::in_edges(v, *g_);
float out_degree = 0.f;
float in_degree = 0.f;
for (auto&& oe : out_edges)
{
out_degree += (*g_)[oe].capacity;
}
for (auto&& ie : in_edges)
{
in_degree += (*g_)[ie].capacity;
}
for (auto&& oe : out_edges)
{
if ((*g_)[oe].capacity < error_rate * out_degree)
{
toDelete.insert(oe);
}
}
for (auto&& ie : in_edges)
{
if ((*g_)[ie].capacity < error_rate * in_degree)
{
toDelete.insert(ie);
}
}
}
for (auto&& e : toDelete)
{
boost::remove_edge(e, *g_);
}
}
// Tests whether two percentages "belong together"
bool UnitigGraph::test_hypothesis(float to_test_num, float to_test_denom, float h0, float threshold)
{
float diff = std::abs(to_test_num - h0 * to_test_denom); // the absolute difference between num and expected num
//bool less = to_test_num < to_test_denom * h0;
//float perc = to_test_num/to_test_denom; //currently unused
return (/*less or*/ diff < threshold); // they differ by less than threshold
}
float UnitigGraph::in_capacity(UVertex source, unsigned int cc)
{
UGraph* g_ = graphs_.at(cc);
float capacity = 0;
for (auto ie : boost::in_edges(source, *g_))
{
capacity += (*g_)[ie].capacity;
}
return capacity;
}
float UnitigGraph::out_capacity(UVertex target, unsigned int cc)
{
UGraph* g_ = graphs_.at(cc);
float capacity = 0;
for (auto oe : boost::out_edges(target, *g_))
{
capacity += (*g_)[oe].capacity;
}
return capacity;
}
// for two strains no dijkstra is needed - use greedy instead
std::vector<UEdge> UnitigGraph::greedy(UEdge seed, bool init, bool local, unsigned int cc)
{
UGraph* g_ = graphs_.at(cc);
std::vector<UEdge> path = {seed};
(*g_)[seed].visited = true;
while (true)
{
auto target = boost::target(path.back(), *g_);
float max = 0.;
UEdge max_edge;
float sum = 0.;
for (auto oe : boost::out_edges(target, *g_))
{
float cap = (*g_)[oe].capacity;
if (cap > max)
{
max = cap;
max_edge = oe;
}
sum += cap;
}
if (max > 0 and !(*g_)[max_edge].visited and (max/sum > 0.55 or !test_hypothesis(2*max, sum, 1, 100))) //TODO thresholds
{
(*g_)[max_edge].visited = true;
path.push_back(max_edge);
}