Debian Codegraph @

src/poa/PoaGraphImpl.cpp

raw
1 #include "PoaGraphImpl.h"
2
3 #include <pbcopper/align/AlignConfig.h>
4 #include <pbcopper/poa/PoaConsensus.h>
5 #include <pbcopper/poa/PoaGraph.h>
6 #include <pbcopper/poa/RangeFinder.h>
7
8 #include <boost/foreach.hpp>
9 #include <boost/graph/copy.hpp>
10 #include <boost/graph/graphviz.hpp>
11 #include <boost/graph/topological_sort.hpp>
12
13 #include <fstream>
14 #include <ostream>
15 #include <set>
16 #include <sstream>
17
18 namespace boost {
19
20 class my_label_writer
21 {
22 public:
23 explicit my_label_writer(PacBio::Poa::detail::VertexInfoMap map, bool color, bool verbose,
24 const PacBio::Poa::PoaConsensus* pc = nullptr)
25 : map_(map), cssVtxs_(), color_(color), verbose_(verbose)
26 {
27 if (pc != nullptr) {
28 cssVtxs_.insert(pc->Path.begin(), pc->Path.end());
29 }
30 }
31
32 template <class descriptor>
33 void operator()(std::ostream& out, const descriptor& v) const
34 {
35 PacBio::Poa::PoaGraph::Vertex vertexId = map_[v].Id;
36
37 std::string nodeColoringAttribute =
38 (color_ && isInConsensus(vertexId) ? R"( style="filled", fillcolor="lightblue" ,)"
39 : "");
40
41 if (!verbose_) {
42 out << format("[shape=Mrecord,%s label=\"{ %c | %d }\"]") % nodeColoringAttribute %
43 map_[v].Base % map_[v].Reads;
44 } else {
45 out << format(
46 "[shape=Mrecord,%s label=\"{ "
47 "{ %d | %c } | "
48 "{ %d | %d } | "
49 "{ %0.2f | %0.2f } }\"]") %
50 nodeColoringAttribute % vertexId % map_[v].Base % map_[v].Reads %
51 map_[v].SpanningReads % map_[v].Score % map_[v].ReachingScore;
52 }
53 }
54
55 private:
56 bool isInConsensus(PacBio::Poa::PoaGraph::Vertex v) const
57 {
58 return cssVtxs_.find(v) != cssVtxs_.end();
59 }
60 PacBio::Poa::detail::VertexInfoMap map_;
61 std::set<PacBio::Poa::PoaGraph::Vertex> cssVtxs_;
62 bool color_;
63 bool verbose_;
64 };
65
66 class my_graph_writer
67 {
68 public:
69 explicit my_graph_writer(bool leftToRight = false) : leftToRight_(leftToRight) {}
70 void operator()(std::ostream& out) const
71 {
72 if (leftToRight_) {
73 out << "rankdir=\"LR\";" << std::endl;
74 }
75 }
76
77 private:
78 bool leftToRight_;
79 };
80
81 } // namespace boost
82
83 namespace PacBio {
84 namespace Poa {
85 namespace detail {
86
87 // ----------------- PoaGraphImpl ---------------------
88
89 PoaGraphImpl::PoaGraphImpl()
90 : g_()
91 , vertexInfoMap_(get(boost::vertex_info, g_))
92 , numReads_(0)
93 , totalVertices_(0)
94 , liveVertices_(0)
95 {
96 enterVertex_ = addVertex('^', 0);
97 exitVertex_ = addVertex('$', 0);
98 }
99
100 PoaGraphImpl::PoaGraphImpl(const PoaGraphImpl& other)
101 : g_(other.g_)
102 , vertexInfoMap_(get(boost::vertex_info, g_))
103 , enterVertex_(other.enterVertex_)
104 , exitVertex_(other.exitVertex_)
105 , numReads_(other.numReads_)
106 {}
107
108 void PoaGraphImpl::repCheck() const
109 {
110 #ifndef NDEBUG
111 // assert the representation invariant for the object
112 BOOST_FOREACH (const VD v, vertices(g_)) {
113 if (v == enterVertex_) {
114 assert(in_degree(v, g_) == 0);
115 assert(out_degree(v, g_) > 0 || NumReads() == 0);
116 } else if (v == exitVertex_) {
117 assert(in_degree(v, g_) > 0 || NumReads() == 0);
118 assert(out_degree(v, g_) == 0);
119 } else {
120 assert(in_degree(v, g_) > 0);
121 assert(out_degree(v, g_) > 0);
122 }
123 }
124 #endif
125 }
126
127 namespace {
128
129 std::vector<const AlignmentColumn*> getPredecessorColumns(const BoostGraph& g, VD v,
130 const AlignmentColumnMap& colMap)
131 {
132 std::vector<const AlignmentColumn*> predecessorColumns;
133 for (auto e : inEdges(v, g)) {
134 VD u = source(e, g);
135 const AlignmentColumn* const predCol = colMap.at(u).get();
136 assert(predCol != nullptr);
137 predecessorColumns.push_back(predCol);
138 }
139 return predecessorColumns;
140 }
141
142 } // namespace
143
144 std::unique_ptr<PoaConsensus> PoaGraphImpl::FindConsensus(const Align::AlignConfig& config,
145 int minCoverage)
146 {
147 std::vector<VD> bestPath = consensusPath(config.Mode, minCoverage);
148 std::string consensusSequence = sequenceAlongPath(g_, vertexInfoMap_, bestPath);
149 return std::make_unique<PoaConsensus>(consensusSequence, *this, externalizePath(bestPath));
150 }
151
152 std::unique_ptr<const AlignmentColumn> PoaGraphImpl::makeAlignmentColumnForExit(
153 VD v, const AlignmentColumnMap& colMap, const std::string& sequence,
154 const Align::AlignConfig& config) const
155 {
156 assert(out_degree(v, g_) == 0);
157
158 // this is kind of unnecessary as we are only actually using one entry in
159 // this column
160 int I = sequence.length();
161
162 float bestScore = -FLT_MAX;
163 VD prevVertex = null_vertex;
164
165 // Under local or semiglobal alignment the vertex $ can be
166 // "reached" in the dynamic programming from any other vertex
167 // in one step via the End move--not just its predecessors in
168 // the graph. In local alignment, it may have been from any
169 // row, not necessarily I.
170 if (config.Mode == Align::AlignMode::SEMIGLOBAL || config.Mode == Align::AlignMode::LOCAL) {
171 BOOST_FOREACH (const VD u, vertices(g_)) {
172 if (u != exitVertex_) {
173 const AlignmentColumn* const predCol = colMap.at(u).get();
174 int prevRow = (config.Mode == Align::AlignMode::LOCAL ? ArgMax(predCol->Score) : I);
175 if (predCol->HasRow(prevRow) && predCol->Score[prevRow] > bestScore) {
176 bestScore = predCol->Score[prevRow];
177 prevVertex = predCol->CurrentVertex;
178 }
179 }
180 }
181 } else {
182 // regular predecessors
183 std::vector<const AlignmentColumn*> predecessorColumns =
184 getPredecessorColumns(g_, v, colMap);
185 for (const AlignmentColumn* predCol : predecessorColumns) {
186 if (predCol->HasRow(I) && predCol->Score[I] > bestScore) {
187 bestScore = predCol->Score[I];
188 prevVertex = predCol->CurrentVertex;
189 }
190 }
191 }
192
193 assert(prevVertex != null_vertex);
194 AlignmentColumn curCol{v, 0, I + 1};
195 curCol.Score[I] = bestScore;
196 curCol.PreviousVertex[I] = prevVertex;
197 curCol.ReachingMove[I] = EndMove;
198 return std::make_unique<const AlignmentColumn>(std::move(curCol));
199 }
200
201 std::unique_ptr<const AlignmentColumn> PoaGraphImpl::makeAlignmentColumn(
202 VD v, const AlignmentColumnMap& colMap, const std::string& sequence,
203 const Align::AlignConfig& config, int beginRow, int endRow) const
204 {
205 if (beginRow > endRow) {
206 // This happens when there are no anchors in the read. We
207 // want this read to be threaded onto the graph as a singleton
208 // path. We use the START move.
209
210 // This is only going to work in LOCAL aln, assert on that
211
212 AlignmentColumn col{v, 0, 1};
213 col.ReachingMove[0] = StartMove;
214 col.PreviousVertex[0] = enterVertex_;
215 col.Score[0] = 0; // > -FLT_MAX;
216 return std::make_unique<const AlignmentColumn>(std::move(col));
217 }
218
219 assert(beginRow < endRow || beginRow == 0 || beginRow == static_cast<int>(sequence.length()));
220
221 AlignmentColumn curCol{v, beginRow, endRow};
222
223 const PoaNode& vertexInfo = vertexInfoMap_[v];
224 std::vector<const AlignmentColumn*> predecessorColumns = getPredecessorColumns(g_, v, colMap);
225
226 // i represents position in array
227 // readPos=i-1 represents position in read
228 for (int i = beginRow; i < endRow; i++) {
229 assert(curCol.HasRow(i));
230
231 float candidateScore;
232 float bestScore;
233 VD prevVertex;
234 MoveType reachingMove;
235
236 if (config.Mode == Align::AlignMode::LOCAL) {
237 bestScore = 0;
238 prevVertex = enterVertex_;
239 reachingMove = StartMove;
240 } else {
241 bestScore = -FLT_MAX;
242 prevVertex = null_vertex;
243 reachingMove = InvalidMove;
244 }
245
246 // Special-case the first row, this could probably be factored
247 // more cleanly
248 if (i == 0) {
249 if (predecessorColumns.size() == 0) {
250 // if this vertex doesn't have any in-edges it is ^; has
251 // no reaching move
252 assert(v == enterVertex_);
253 curCol.Score[0] = 0;
254 curCol.ReachingMove[0] = InvalidMove;
255 curCol.PreviousVertex[0] = null_vertex;
256 } else if (config.Mode == Align::AlignMode::SEMIGLOBAL ||
257 config.Mode == Align::AlignMode::LOCAL) {
258 // under semiglobal or local alignment, we use the Start move
259 curCol.Score[0] = 0;
260 curCol.ReachingMove[0] = StartMove;
261 curCol.PreviousVertex[0] = enterVertex_;
262 } else {
263 // otherwise it's a deletion
264 for (const AlignmentColumn* prevCol : predecessorColumns) {
265 candidateScore = prevCol->Score[0] + config.Params.Delete;
266 if (candidateScore > bestScore) {
267 bestScore = candidateScore;
268 prevVertex = prevCol->CurrentVertex;
269 reachingMove = DeleteMove;
270 }
271 }
272 assert(reachingMove != InvalidMove);
273 curCol.Score[0] = bestScore;
274 curCol.ReachingMove[0] = reachingMove;
275 curCol.PreviousVertex[0] = prevVertex;
276 }
277 } else {
278 for (const AlignmentColumn* prevCol : predecessorColumns) {
279 // Incorporate (Match or Mismatch)
280 if (prevCol->HasRow(i - 1)) {
281 bool isMatch = sequence[i - 1] == vertexInfo.Base;
282 candidateScore = prevCol->Score[i - 1] +
283 (isMatch ? config.Params.Match : config.Params.Mismatch);
284 if (candidateScore > bestScore) {
285 bestScore = candidateScore;
286 prevVertex = prevCol->CurrentVertex;
287 reachingMove = (isMatch ? MatchMove : MismatchMove);
288 }
289 }
290 // Delete
291 if (prevCol->HasRow(i)) {
292 candidateScore = prevCol->Score[i] + config.Params.Delete;
293 if (candidateScore > bestScore) {
294 bestScore = candidateScore;
295 prevVertex = prevCol->CurrentVertex;
296 reachingMove = DeleteMove;
297 }
298 }
299 }
300 // Extra
301 if (curCol.HasRow(i - 1)) {
302 candidateScore = curCol.Score[i - 1] + config.Params.Insert;
303 if (candidateScore > bestScore) {
304 bestScore = candidateScore;
305 prevVertex = v;
306 reachingMove = ExtraMove;
307 }
308 }
309 assert(reachingMove != InvalidMove);
310 curCol.Score[i] = bestScore;
311 curCol.ReachingMove[i] = reachingMove;
312 curCol.PreviousVertex[i] = prevVertex;
313 }
314 }
315
316 return std::make_unique<const AlignmentColumn>(std::move(curCol));
317 }
318
319 void PoaGraphImpl::AddRead(const std::string& readSeq, const Align::AlignConfig& config,
320 SdpRangeFinder* rangeFinder, std::vector<Vertex>* readPathOutput)
321 {
322 if (NumReads() == 0) {
323 AddFirstRead(readSeq, readPathOutput);
324 } else {
325 std::unique_ptr<PoaAlignmentMatrix> mat{TryAddRead(readSeq, config, rangeFinder)};
326 CommitAdd(mat.get(), readPathOutput);
327 }
328 }
329
330 void PoaGraphImpl::AddFirstRead(const std::string& readSeq, std::vector<Vertex>* readPathOutput)
331 {
332 repCheck();
333 assert(readSeq.length() > 0);
334 assert(numReads_ == 0);
335
336 threadFirstRead(readSeq, readPathOutput);
337 numReads_++;
338 repCheck();
339 }
340
341 std::unique_ptr<PoaAlignmentMatrix> PoaGraphImpl::TryAddRead(
342 const std::string& readSeq, const Align::AlignConfig& config,
343 SdpRangeFinder* const rangeFinder) const
344 {
345 repCheck();
346 assert(readSeq.length() > 0);
347 assert(numReads_ > 0);
348
349 // Prepare the range finder, if applicable
350 if (rangeFinder != nullptr) {
351 // NB: no minCoverage applicable here; this
352 // "intermediate" consensus may include extra sequence
353 // at either end
354 std::vector<VD> cssPath = consensusPath(config.Mode);
355 std::string cssSeq = sequenceAlongPath(g_, vertexInfoMap_, cssPath);
356 rangeFinder->InitRangeFinder(*this, externalizePath(cssPath), cssSeq, readSeq);
357 }
358
359 // Calculate alignment columns of sequence vs. graph, using sparsity if
360 // we have a range finder.
361 auto mat = std::make_unique<PoaAlignmentMatrixImpl>();
362 mat->readSequence_ = readSeq;
363 mat->mode_ = config.Mode;
364 mat->graph_ = this;
365
366 std::vector<VD> sortedVerticesLocal(num_vertices(g_));
367 topological_sort(g_, sortedVerticesLocal.rbegin());
368 std::unique_ptr<const AlignmentColumn> curCol;
369 for (const auto& v : sortedVerticesLocal) {
370 if (v != exitVertex_) {
371 size_t startRow = 0;
372 size_t endRow = readSeq.size() + 1;
373 if (rangeFinder) {
374 // FindAlignableRange returns an alignable sequence range, which is not the same as
375 // the alignable rows (the end is off-by-one, for a normal interval).
376 int startRange;
377 int endRange;
378 std::tie(startRange, endRange) = rangeFinder->FindAlignableRange(externalize(v));
379 startRow = startRange;
380 endRow = (endRange == -INT_MAX / 2 ? endRange : endRange + 1);
381 }
382 /* Vertex vExt = */ externalize(v); // DEBUGGING
383 curCol = makeAlignmentColumn(v, mat->columns_, readSeq, config, startRow, endRow);
384 } else {
385 curCol = makeAlignmentColumnForExit(v, mat->columns_, readSeq, config);
386 }
387 mat->columns_[v] = std::move(curCol);
388 }
389
390 mat->score_ = mat->columns_[exitVertex_]->Score[readSeq.size()];
391 repCheck();
392
393 PoaAlignmentMatrix* base = mat.release();
394 std::unique_ptr<PoaAlignmentMatrix> result;
395 result.reset(base);
396 return result;
397 }
398
399 void PoaGraphImpl::CommitAdd(const PoaAlignmentMatrix* const mat_,
400 std::vector<Vertex>* readPathOutput)
401 {
402 repCheck();
403
404 const auto* mat = static_cast<const PoaAlignmentMatrixImpl*>(mat_);
405 tracebackAndThread(mat->readSequence_, mat->columns_, mat->mode_, readPathOutput);
406 numReads_++;
407
408 repCheck();
409 }
410
411 class VertexComparator
412 {
413 public:
414 explicit VertexComparator(const BoostGraph& g) : g_(g) {}
415
416 // Use existing indices to provide a stable memory-agnostic ordering
417 bool operator()(VD v1, VD v2) const
418 {
419 const int vi1 = get(boost::vertex_index, g_, v1);
420 const int vi2 = get(boost::vertex_index, g_, v2);
421 return (vi1 < vi2);
422 }
423
424 private:
425 const BoostGraph& g_;
426 };
427
428 void PoaGraphImpl::PruneGraph(const int minCoverage)
429 {
430 // We have to use an iterator since we're modifying the graph as we go
431 boost::graph_traits<BoostGraph>::vertex_iterator vi, vi_end, next;
432 std::tie(vi, vi_end) = vertices(g_);
433 for (next = vi; vi != vi_end; vi = next) {
434 ++next;
435 if (vertexInfoMap_[*vi].Reads < minCoverage) {
436 clear_vertex(*vi, g_);
437 remove_vertex(*vi, g_);
438 }
439 }
440
441 // This is a workaround for the non-deterministic order of iteration
442 // from BGL's vertices, which like edges also appear to be ordered
443 // by memory address (see: http://stackoverflow.com/questions/30968690/)
444
445 // We can't use topological sort here, since having a vertex index greater
446 // than num_vertices(g_) causes a crash. Instead we sort the vertices by
447 // their existing index. This should still be very fast, as the underlying
448 // collection should be mostly sorted already.
449 std::vector<VD> sortedVerticesLocal;
450 BGL_FORALL_VERTICES(v, g_, BoostGraph) sortedVerticesLocal.push_back(v);
451 std::sort(sortedVerticesLocal.begin(), sortedVerticesLocal.end(), VertexComparator(g_));
452
453 // Finally, re-index all vertices to the range [0, num_vertices(g_)]
454 boost::graph_traits<BoostGraph>::vertices_size_type current_index = 0;
455 index_map_t index_map = get(boost::vertex_index, g_);
456 for (const VD& v : sortedVerticesLocal) {
457 index_map[v] = current_index++;
458 }
459 }
460
461 size_t PoaGraphImpl::NumReads() const { return numReads_; }
462
463 std::string PoaGraphImpl::ToGraphViz(int flags, const PoaConsensus* pc) const
464 {
465 std::ostringstream ss;
466 write_graphviz(ss, g_,
467 boost::my_label_writer(vertexInfoMap_, flags & PoaGraph::COLOR_NODES,
468 flags & PoaGraph::VERBOSE_NODES, pc),
469 boost::default_writer(), // edge writer
470 boost::my_graph_writer(true));
471
472 return ss.str();
473 }
474
475 void PoaGraphImpl::WriteGraphVizFile(const std::filesystem::path& filename, int flags,
476 const PoaConsensus* pc) const
477 {
478 std::ofstream outfile{filename};
479 outfile << ToGraphViz(flags, pc);
480 }
481
482 void PoaGraphImpl::WriteGraphCsvFile(const std::filesystem::path& filename) const
483 {
484 std::ofstream outfile{filename};
485
486 std::list<VD> sortedVerticesLocal(num_vertices(g_));
487 topological_sort(g_, sortedVerticesLocal.rbegin());
488
489 outfile << "Id,Base,Reads,SpanningReads,Score,ReachingScore" << std::endl;
490 for (const VD v : sortedVerticesLocal) {
491 PoaNode& vi = vertexInfoMap_[v];
492 outfile << vi.Id << ',' << vi.Base << ',' << vi.Reads << ',' << vi.SpanningReads << ','
493 << vi.Score << ',' << vi.ReachingScore << std::endl;
494 }
495 }
496
497 } // namespace detail
498 } // namespace Poa
499 } // namespace PacBio