Debian Codegraph @

src/dagcon/AlignmentGraph.cpp

raw
1 #include <pbcopper/dagcon/AlignmentGraph.h>
2
3 #include <pbcopper/dagcon/Alignment.h>
4 #include <pbcopper/utility/Ssize.h>
5
6 #include <boost/range/iterator_range.hpp>
7 #include <boost/utility/value_init.hpp>
8
9 #include <algorithm>
10 #include <map>
11 #include <queue>
12 #include <string>
13 #include <vector>
14
15 #include <cassert>
16 #include <cfloat>
17 #include <cstdint>
18
19 namespace PacBio {
20 namespace Dagcon {
21
22 AlignmentGraph::AlignmentGraph(const std::string& backbone) : backboneLength_{backbone.length()}
23 {
24 // initialize the graph structure with the backbone length + enter/exit vertex
25 graph_ = GraphType{backboneLength_ + 2};
26 for (size_t i = 0; i < backboneLength_ + 1; ++i) {
27 boost::add_edge(i, i + 1, graph_);
28 }
29
30 VertexIterator curr;
31 VertexIterator last;
32 boost::tie(curr, last) = boost::vertices(graph_);
33
34 // enter vertex
35 enterVertex_ = *curr;
36 graph_[enterVertex_].Base = '^';
37 graph_[enterVertex_].Backbone = true;
38 ++curr;
39
40 // internal vertices
41 for (size_t i = 0; i < backboneLength_; ++i) {
42 VertexIndex v = *curr;
43 graph_[v].Backbone = true;
44 graph_[v].Weight = 1;
45 graph_[v].Base = backbone[i];
46 bbMap_[v] = v;
47 ++curr;
48 }
49
50 // ext vertex
51 exitVertex_ = *curr;
52 graph_[exitVertex_].Base = '$';
53 graph_[exitVertex_].Backbone = true;
54 }
55
56 AlignmentGraph::AlignmentGraph(const size_t backboneLength)
57 : AlignmentGraph{std::string(backboneLength, 'N')}
58 {}
59
60 void AlignmentGraph::AddAlignment(Alignment& alignment, bool useLocalMerge)
61 {
62 const IndexMap index = boost::get(boost::vertex_index, graph_);
63 // tracks the position on the backbone
64 uint32_t bbPos = alignment.Start;
65 VertexIndex prevVtx = enterVertex_;
66
67 if (useLocalMerge) {
68 prevVtx = (alignment.Start <= 1) ? enterVertex_ : index[alignment.Start - 1];
69 }
70
71 for (size_t i = 0; i < alignment.Query.length(); i++) {
72 const char queryBase = alignment.Query[i];
73 const char targetBase = alignment.Target[i];
74 assert(queryBase != '.');
75 assert(targetBase != '.');
76
77 VertexIndex currVtx = index[bbPos];
78 // match
79 if (queryBase == targetBase) {
80 graph_[bbMap_[currVtx]].Coverage++;
81
82 // NOTE: for empty backbones
83 graph_[bbMap_[currVtx]].Base = targetBase;
84
85 graph_[currVtx].Weight++;
86 AddEdge(prevVtx, currVtx);
87 bbPos++;
88 prevVtx = currVtx;
89 // query deletion
90 } else if (queryBase == '-' && targetBase != '-') {
91 graph_[bbMap_[currVtx]].Coverage++;
92
93 // NOTE: for empty backbones
94 graph_[bbMap_[currVtx]].Base = targetBase;
95
96 bbPos++;
97 // query insertion
98 } else if (queryBase != '-' && targetBase == '-') {
99 // create new node and edge
100 const VertexIndex newVtx = boost::add_vertex(graph_);
101 graph_[newVtx].Base = queryBase;
102 graph_[newVtx].Weight++;
103 graph_[newVtx].Backbone = false;
104 graph_[newVtx].Deleted = false;
105 bbMap_[newVtx] = bbPos;
106 AddEdge(prevVtx, newVtx);
107 prevVtx = newVtx;
108 }
109 }
110
111 AddEdge(prevVtx, exitVertex_);
112
113 if (useLocalMerge) {
114 prevVtx = (alignment.End < backboneLength_) ? index[alignment.Start + 1] : exitVertex_;
115 }
116 }
117
118 void AlignmentGraph::AddEdge(VertexIndex u, VertexIndex v)
119 {
120 // Check if edge exists with prev node. If it does, increment edge counter,
121 // otherwise add a new edge.
122 bool edgeExists = false;
123
124 for (const auto e : boost::make_iterator_range(boost::in_edges(v, graph_))) {
125 if (boost::source(e, graph_) == u) {
126 // increment edge count
127 graph_[e].Count++;
128 edgeExists = true;
129 }
130 }
131 if (!edgeExists) {
132 // add new edge
133 const auto p = boost::add_edge(u, v, graph_);
134 graph_[p.first].Count++;
135 }
136 }
137
138 void AlignmentGraph::MergeNodes()
139 {
140 std::queue<VertexIndex> seedNodes;
141 seedNodes.push(enterVertex_);
142
143 while (true) {
144 if (seedNodes.empty()) {
145 break;
146 }
147
148 const VertexIndex u = seedNodes.front();
149 seedNodes.pop();
150 MergeInNodes(u);
151 MergeOutNodes(u);
152
153 for (const auto e : boost::make_iterator_range(boost::out_edges(u, graph_))) {
154 graph_[e].Visited = true;
155
156 int notVisited = 0;
157 const VertexIndex v = boost::target(e, graph_);
158 for (const auto inEdge : boost::make_iterator_range(boost::in_edges(v, graph_))) {
159 if (graph_[inEdge].Visited == false) {
160 ++notVisited;
161 }
162 }
163
164 // move onto the boost::target node after we visit all incoming edges for
165 // the boost::target node
166 if (notVisited == 0) {
167 seedNodes.push(v);
168 }
169 }
170 }
171 }
172
173 void AlignmentGraph::MergeInNodes(VertexIndex n)
174 {
175 std::map<char, std::vector<VertexIndex>> nodeGroups;
176
177 for (const auto inEdge : boost::make_iterator_range(boost::in_edges(n, graph_))) {
178 const VertexIndex inNode = boost::source(inEdge, graph_);
179 if (out_degree(inNode, graph_) == 1) {
180 nodeGroups[graph_[inNode].Base].push_back(inNode);
181 }
182 }
183
184 // iterate over node groups, merge an accumulate information
185 for (const auto& kvp : nodeGroups) {
186 const auto& nodes = kvp.second;
187 if (nodes.size() <= 1) {
188 continue;
189 }
190
191 auto ni = nodes.cbegin();
192 const VertexIndex an = *ni++;
193
194 // Accumulate out edge information
195 // IS: This iterates over all alternate nodes with the same base.
196 // It only looks at the initial iterator position instead of having
197 // another loop from oi to oe. This is fine because there is exactly
198 // 1 out edge for each of these nodes.
199 OutEdgeIterator anoi;
200 OutEdgeIterator anoe;
201 boost::tie(anoi, anoe) = boost::out_edges(an, graph_);
202 for (; ni != nodes.cend(); ++ni) {
203
204 OutEdgeIterator oi;
205 OutEdgeIterator oe;
206 boost::tie(oi, oe) = boost::out_edges(*ni, graph_);
207
208 graph_[*anoi].Count += graph_[*oi].Count; // IS: This sums the EDGE counts.
209 graph_[an].Weight += graph_[*ni].Weight; // IS: This sums the NODE weights.
210 }
211
212 // Accumulate in edge information, merges nodes
213 ni = nodes.cbegin();
214 ++ni;
215 for (; ni != nodes.cend(); ++ni) {
216 const VertexIndex vtx = *ni;
217 for (const auto newEdge : boost::make_iterator_range(boost::in_edges(vtx, graph_))) {
218 const VertexIndex n1 = boost::source(newEdge, graph_);
219
220 EdgeIndex e;
221 bool exists;
222 boost::tie(e, exists) = edge(n1, an, graph_);
223 if (exists) {
224 #if __GNUC__ >= 6
225 #pragma GCC diagnostic ignored "-Wnull-dereference"
226 #endif
227 graph_[e].Count += graph_[newEdge].Count;
228 #if __GNUC__ >= 6
229 #pragma GCC diagnostic pop
230 #endif
231 } else {
232 const auto p = boost::add_edge(n1, an, graph_);
233 graph_[p.first].Count = graph_[newEdge].Count;
234 graph_[p.first].Visited = graph_[newEdge].Visited;
235 }
236 }
237 MarkForReaper(vtx);
238 }
239 MergeInNodes(an);
240 }
241 }
242
243 void AlignmentGraph::MergeOutNodes(VertexIndex n)
244 {
245 std::map<char, std::vector<VertexIndex>> nodeGroups;
246
247 for (const auto outEdge : boost::make_iterator_range(boost::out_edges(n, graph_))) {
248 const VertexIndex outNode = boost::target(outEdge, graph_);
249 if (in_degree(outNode, graph_) == 1) {
250 nodeGroups[graph_[outNode].Base].push_back(outNode);
251 }
252 }
253
254 for (const auto& kvp : nodeGroups) {
255 const auto& nodes = kvp.second;
256 if (nodes.size() <= 1) {
257 continue;
258 }
259
260 auto nodeIter = nodes.cbegin();
261 const VertexIndex an = *nodeIter;
262 ++nodeIter;
263
264 // Accumulate inner edge information
265 InEdgeIterator anii;
266 InEdgeIterator anie;
267 boost::tie(anii, anie) = boost::in_edges(an, graph_);
268 for (; nodeIter != nodes.cend(); ++nodeIter) {
269 InEdgeIterator ii;
270 InEdgeIterator ie;
271 boost::tie(ii, ie) = boost::in_edges(*nodeIter, graph_);
272 graph_[*anii].Count += graph_[*ii].Count;
273 graph_[an].Weight += graph_[*nodeIter].Weight;
274 }
275
276 // Accumulate and merge outer edge information
277 nodeIter = nodes.cbegin();
278 ++nodeIter;
279 for (; nodeIter != nodes.cend(); ++nodeIter) {
280 VertexIndex vtx = *nodeIter;
281 for (const auto newEdge : boost::make_iterator_range(boost::out_edges(vtx, graph_))) {
282 const VertexIndex n2 = boost::target(newEdge, graph_);
283
284 EdgeIndex e;
285 bool exists;
286 boost::tie(e, exists) = edge(an, n2, graph_);
287 if (exists) {
288 #if __GNUC__ >= 6
289 #pragma GCC diagnostic ignored "-Wnull-dereference"
290 #endif
291 graph_[e].Count += graph_[newEdge].Count;
292 #if __GNUC__ >= 6
293 #pragma GCC diagnostic pop
294 #endif
295 } else {
296 const auto p = boost::add_edge(an, n2, graph_);
297 graph_[p.first].Count = graph_[newEdge].Count;
298 graph_[p.first].Visited = graph_[newEdge].Visited;
299 }
300 }
301 MarkForReaper(vtx);
302 }
303 }
304 }
305
306 void AlignmentGraph::MarkForReaper(VertexIndex node)
307 {
308 graph_[node].Deleted = true;
309 clear_vertex(node, graph_);
310 reaperBag_.push_back(node);
311 }
312
313 void AlignmentGraph::ReapNodes()
314 {
315 int reapCount = 0;
316 std::sort(reaperBag_.begin(), reaperBag_.end());
317 for (auto& node : reaperBag_) {
318 assert(graph_[node].Backbone == false);
319 remove_vertex(node - reapCount, graph_);
320 ++reapCount;
321 }
322 }
323
324 std::string AlignmentGraph::Consensus(int minWeight)
325 {
326 // consensus sequence
327 std::string cns;
328
329 // track the longest consensus path meeting minimum weight
330 int offs = 0;
331 int bestOffs = 0;
332 int length = 0;
333 int idx = 0;
334 bool metWeight = false;
335 for (const auto& n : BestPath()) {
336 if (n.Base == graph_[enterVertex_].Base || n.Base == graph_[exitVertex_].Base) {
337 continue;
338 }
339
340 cns += n.Base;
341
342 // initial beginning of minimum weight section
343 if (!metWeight && n.Weight >= minWeight) {
344 offs = idx;
345 metWeight = true;
346 } else if (metWeight && n.Weight < minWeight) {
347 // concluded minimum weight section, update if longest seen so far
348 if ((idx - offs) > length) {
349 bestOffs = offs;
350 length = idx - offs;
351 }
352 metWeight = false;
353 }
354 idx++;
355 }
356
357 // include end of sequence
358 if (metWeight && (idx - offs) > length) {
359 bestOffs = offs;
360 length = idx - offs;
361 }
362
363 return cns.substr(bestOffs, length);
364 }
365
366 void AlignmentGraph::Consensus(std::vector<ConsensusResult>& seqs, int minWeight, size_t minLen)
367 {
368 seqs.clear();
369
370 // consensus sequence
371 std::string cns;
372
373 // track the longest consensus path meeting minimum weight
374 int offs = 0;
375 int idx = 0;
376 bool metWeight = false;
377 for (const auto& n : BestPath()) {
378 if (n.Base == graph_[enterVertex_].Base || n.Base == graph_[exitVertex_].Base) {
379 continue;
380 }
381
382 cns += n.Base;
383
384 // initial beginning of minimum weight section
385 if (!metWeight && n.Weight >= minWeight) {
386 offs = idx;
387 metWeight = true;
388 } else if (metWeight && n.Weight < minWeight) {
389 // concluded minimum weight section, add sequence to supplied vector
390 metWeight = false;
391 const size_t length = idx - offs;
392 if (length >= minLen) {
393 seqs.emplace_back(ConsensusResult{{offs, idx}, cns.substr(offs, length)});
394 }
395 }
396 idx++;
397 }
398
399 // include end of sequence
400 if (metWeight) {
401 const size_t length = idx - offs;
402 if (length >= minLen) {
403 seqs.emplace_back(ConsensusResult{{offs, idx}, cns.substr(offs, length)});
404 }
405 }
406 }
407
408 void AlignmentGraph::ConsensusWithMinFlankCoverage(std::vector<ConsensusResult>& seqs,
409 int minWeight, int minFlankCoverage,
410 size_t minLen)
411 {
412 seqs.clear();
413
414 // get the best scoring path
415 const auto path = BestPath();
416 const auto pathLength = Utility::Ssize(path);
417 if (pathLength == 0) {
418 return;
419 }
420
421 int64_t numClippedFront = 0;
422 auto startNode = path.begin();
423 for (; startNode != path.end(); ++startNode, ++numClippedFront) {
424 const AlignmentNode& n = *startNode;
425 if (n.Coverage >= minFlankCoverage) {
426 break;
427 }
428 }
429
430 auto endNode = path.end();
431 int64_t numClippedBack = 0;
432 for (int64_t i = pathLength - 1; i >= 0; --i, ++numClippedBack) {
433 if (path[i].Coverage >= minFlankCoverage) {
434 break;
435 }
436 --endNode;
437 }
438
439 if (numClippedFront >= (pathLength - numClippedBack)) {
440 return;
441 }
442
443 // consensus sequence
444 std::string cns;
445
446 // track the longest consensus path meeting minimum weight
447 int offs = 0;
448 int idx = 0;
449 bool metWeight = false;
450 auto curr = startNode;
451 for (; curr != endNode; ++curr) {
452 const AlignmentNode& n = *curr;
453 if (n.Base == graph_[enterVertex_].Base || n.Base == graph_[exitVertex_].Base) {
454 continue;
455 }
456
457 cns += n.Base;
458
459 // initial beginning of minimum weight section
460 if (!metWeight && n.Weight >= minWeight) {
461 offs = idx;
462 metWeight = true;
463 } else if (metWeight && n.Weight < minWeight) {
464 // concluded minimum weight section, add sequence to supplied vector
465 metWeight = false;
466 const size_t length = idx - offs;
467 if (length >= minLen) {
468 seqs.emplace_back(ConsensusResult{{offs, idx}, cns.substr(offs, length)});
469 }
470 }
471 idx++;
472 }
473 // include end of sequence
474 if (metWeight) {
475 const size_t length = idx - offs;
476 if (length >= minLen) {
477 seqs.emplace_back(ConsensusResult{{offs, idx}, cns.substr(offs, length)});
478 }
479 }
480 }
481
482 std::vector<AlignmentNode> AlignmentGraph::BestPath()
483 {
484 for (const auto edge : boost::make_iterator_range(edges(graph_))) {
485 graph_[edge].Visited = false;
486 }
487
488 std::map<VertexIndex, EdgeIndex> bestNodeScoreEdge;
489 std::map<VertexIndex, float> nodeScore;
490 std::queue<VertexIndex> seedNodes;
491
492 // start at the end and make our way backwards
493 seedNodes.push(exitVertex_);
494 nodeScore[exitVertex_] = 0.0f;
495
496 while (true) {
497 if (seedNodes.empty()) {
498 break;
499 }
500
501 const VertexIndex n = seedNodes.front();
502 seedNodes.pop();
503
504 bool bestEdgeFound = false;
505 float bestScore = -FLT_MAX;
506 EdgeIndex bestEdgeD = boost::initialized_value;
507
508 for (const auto outEdgeD : boost::make_iterator_range(boost::out_edges(n, graph_))) {
509 const VertexIndex outNodeD = boost::target(outEdgeD, graph_);
510 const AlignmentNode& outNode = graph_[outNodeD];
511
512 float score = nodeScore[outNodeD];
513 float newScore = 0.0f;
514 if (outNode.Backbone && outNode.Weight == 1) {
515 newScore = score - 10.0f;
516 } else {
517 const AlignmentNode& bbNode = graph_[bbMap_[outNodeD]];
518 newScore = graph_[outEdgeD].Count - bbNode.Coverage * 0.5f + score;
519 }
520
521 if (newScore > bestScore) {
522 bestScore = newScore;
523 bestEdgeD = outEdgeD;
524 bestEdgeFound = true;
525 }
526 }
527
528 if (bestEdgeFound) {
529 nodeScore[n] = bestScore;
530 bestNodeScoreEdge[n] = bestEdgeD;
531 }
532
533 for (const auto inEdge : boost::make_iterator_range(boost::in_edges(n, graph_))) {
534 graph_[inEdge].Visited = true;
535 const VertexIndex inNode = boost::source(inEdge, graph_);
536 int notVisited = 0;
537
538 for (const auto newOutEdge :
539 boost::make_iterator_range(boost::out_edges(inNode, graph_))) {
540 if (graph_[newOutEdge].Visited == false) {
541 notVisited++;
542 }
543 }
544
545 // move onto the target node after we visit all incoming edges for
546 // the target node
547 if (notVisited == 0) {
548 seedNodes.push(inNode);
549 }
550 }
551 }
552
553 // construct the final best path
554 VertexIndex prev = enterVertex_;
555 VertexIndex next;
556 std::vector<AlignmentNode> bpath;
557 while (true) {
558 bpath.push_back(graph_[prev]);
559 if (bestNodeScoreEdge.count(prev) == 0) {
560 break;
561 } else {
562 const EdgeIndex bestOutEdge = bestNodeScoreEdge[prev];
563 graph_[prev].BestOutEdge = bestOutEdge;
564 next = boost::target(bestOutEdge, graph_);
565 graph_[next].BestInEdge = bestOutEdge;
566 prev = next;
567 }
568 }
569
570 return bpath;
571 }
572
573 bool AlignmentGraph::DanglingNodes()
574 {
575 for (const auto vertex : boost::make_iterator_range(boost::vertices(graph_))) {
576 if (graph_[vertex].Deleted) {
577 continue;
578 }
579 if (graph_[vertex].Base == graph_[enterVertex_].Base ||
580 graph_[vertex].Base == graph_[exitVertex_].Base) {
581 continue;
582 }
583
584 const int indeg = out_degree(vertex, graph_);
585 const int outdeg = in_degree(vertex, graph_);
586 if (outdeg > 0 && indeg > 0) {
587 continue;
588 }
589
590 return true;
591 }
592 return false;
593 }
594
595 } // namespace Dagcon
596 } // namespace PacBio