Debian Codegraph @

src/C++/Poa/PoaGraphImpl.cpp

raw
1 #include "PoaGraphImpl.hpp"
2
3 #include <ConsensusCore/Align/AlignConfig.hpp>
4 #include <ConsensusCore/Interval.hpp>
5 #include <ConsensusCore/Poa/PoaConsensus.hpp>
6 #include <ConsensusCore/Poa/PoaGraph.hpp>
7 #include <ConsensusCore/Poa/RangeFinder.hpp>
8 #include <ConsensusCore/Utils.hpp>
9
10 #include <boost/graph/copy.hpp>
11 #include <boost/graph/graphviz.hpp>
12 #include <boost/graph/topological_sort.hpp>
13
14 #include <iostream>
15 #include <set>
16
17 namespace boost {
18 using ConsensusCore::detail::VertexInfoMap;
19 using ConsensusCore::PoaConsensus;
20 using ConsensusCore::PoaGraph;
21 using ConsensusCore::detail::VD;
22 using boost::format;
23
24 class my_label_writer
25 {
26 public:
27 my_label_writer(VertexInfoMap map, bool color, bool verbose, const PoaConsensus* pc = NULL)
28 : map_(map), cssVtxs_(), color_(color), verbose_(verbose)
29 {
30 if (pc != NULL) {
31 cssVtxs_.insert(pc->Path.begin(), pc->Path.end());
32 }
33 }
34
35 template <class descriptor>
36 void operator()(std::ostream& out, const descriptor& v) const
37 {
38 PoaGraph::Vertex vertexId = map_[v].Id;
39
40 std::string nodeColoringAttribute =
41 (color_ && isInConsensus(vertexId) ? " style=\"filled\", fillcolor=\"lightblue\" ,"
42 : "");
43
44 if (!verbose_) {
45 out << format("[shape=Mrecord,%s label=\"{ %c | %d }\"]") % nodeColoringAttribute %
46 map_[v].Base % map_[v].Reads;
47 } else {
48 out << format(
49 "[shape=Mrecord,%s label=\"{ "
50 "{ %d | %c } |"
51 "{ %d | %d } |"
52 "{ %0.2f | %0.2f } }\"]") %
53 nodeColoringAttribute % vertexId % map_[v].Base % map_[v].Reads %
54 map_[v].SpanningReads % map_[v].Score % map_[v].ReachingScore;
55 }
56 }
57
58 private:
59 bool isInConsensus(PoaGraph::Vertex v) const { return cssVtxs_.find(v) != cssVtxs_.end(); }
60
61 VertexInfoMap map_;
62 std::set<PoaGraph::Vertex> cssVtxs_;
63 bool color_;
64 bool verbose_;
65 };
66 }
67
68 namespace ConsensusCore {
69 namespace detail {
70
71 // ----------------- PoaAlignmentMatrixImpl ---------------------
72
73 PoaAlignmentMatrixImpl::~PoaAlignmentMatrixImpl()
74 {
75 foreach (AlignmentColumnMap::value_type& kv, columns_) {
76 delete kv.second;
77 }
78 }
79
80 float PoaAlignmentMatrixImpl::Score() const { return score_; }
81
82 // ----------------- PoaGraphImpl ---------------------
83
84 PoaGraphImpl::PoaGraphImpl()
85 : g_(), vertexInfoMap_(get(vertex_info, g_)), numReads_(0), totalVertices_(0), liveVertices_(0)
86 {
87 enterVertex_ = addVertex('^', 0);
88 exitVertex_ = addVertex('$', 0);
89 }
90
91 PoaGraphImpl::PoaGraphImpl(const PoaGraphImpl& other)
92 : g_(other.g_)
93 , vertexInfoMap_(get(vertex_info, g_))
94 , enterVertex_(other.enterVertex_)
95 , exitVertex_(other.exitVertex_)
96 , numReads_(other.numReads_)
97 {
98 }
99
100 PoaGraphImpl::~PoaGraphImpl() {}
101
102 void PoaGraphImpl::repCheck() const
103 {
104 // assert the representation invariant for the object
105 foreach (VD v, vertices(g_)) {
106 if (v == enterVertex_) {
107 assert(in_degree(v, g_) == 0);
108 assert(out_degree(v, g_) > 0 || NumReads() == 0);
109 } else if (v == exitVertex_) {
110 assert(in_degree(v, g_) > 0 || NumReads() == 0);
111 assert(out_degree(v, g_) == 0);
112 } else {
113 assert(in_degree(v, g_) > 0);
114 assert(out_degree(v, g_) > 0);
115 }
116 }
117 }
118
119 static inline vector<const AlignmentColumn*> getPredecessorColumns(const BoostGraph& g, VD v,
120 const AlignmentColumnMap& colMap)
121 {
122 vector<const AlignmentColumn*> predecessorColumns;
123 const AlignmentColumn* predCol;
124 foreach (ED e, inEdges(v, g)) {
125 VD u = source(e, g);
126 predCol = colMap.at(u);
127 assert(predCol != NULL);
128 predecessorColumns.push_back(predCol);
129 }
130 return predecessorColumns;
131 }
132
133 PoaConsensus* PoaGraphImpl::FindConsensus(const AlignConfig& config, int minCoverage)
134 {
135 std::vector<VD> bestPath = consensusPath(config.Mode, minCoverage);
136 std::string consensusSequence = sequenceAlongPath(g_, vertexInfoMap_, bestPath);
137 PoaConsensus* pc = new PoaConsensus(consensusSequence, *this, externalizePath(bestPath));
138 return pc;
139 }
140
141 const AlignmentColumn* PoaGraphImpl::makeAlignmentColumnForExit(VD v,
142 const AlignmentColumnMap& colMap,
143 const std::string& sequence,
144 const AlignConfig& config) const
145 {
146 assert(out_degree(v, g_) == 0);
147
148 // this is kind of unnecessary as we are only actually using one entry in this
149 // column
150 int I = sequence.length();
151 AlignmentColumn* curCol = new AlignmentColumn(v, I + 1);
152
153 float bestScore = -FLT_MAX;
154 VD prevVertex = null_vertex;
155
156 // Under local or semiglobal alignment the vertex $ can be
157 // "reached" in the dynamic programming from any other vertex
158 // in one step via the End move--not just its predecessors in
159 // the graph. In local alignment, it may have been from any
160 // row, not necessarily I.
161 if (config.Mode == SEMIGLOBAL || config.Mode == LOCAL) {
162 foreach (VD u, vertices(g_)) {
163 if (u != exitVertex_) {
164 const AlignmentColumn* predCol = colMap.at(u);
165 int prevRow = (config.Mode == LOCAL ? ArgMax(predCol->Score) : I);
166
167 if (predCol->Score[prevRow] > bestScore) {
168 bestScore = predCol->Score[prevRow];
169 prevVertex = predCol->CurrentVertex;
170 }
171 }
172 }
173 } else {
174 // regular predecessors
175 vector<const AlignmentColumn*> predecessorColumns = getPredecessorColumns(g_, v, colMap);
176 foreach (const AlignmentColumn* predCol, predecessorColumns) {
177 if (predCol->Score[I] > bestScore) {
178 bestScore = predCol->Score[I];
179 prevVertex = predCol->CurrentVertex;
180 }
181 }
182 }
183 assert(prevVertex != null_vertex);
184 curCol->Score[I] = bestScore;
185 curCol->PreviousVertex[I] = prevVertex;
186 curCol->ReachingMove[I] = EndMove;
187 return curCol;
188 }
189
190 const AlignmentColumn* PoaGraphImpl::makeAlignmentColumn(VD v, const AlignmentColumnMap& colMap,
191 const std::string& sequence,
192 const AlignConfig& config, int, int) const
193 {
194 AlignmentColumn* curCol = new AlignmentColumn(v, sequence.length() + 1);
195 const PoaNode& vertexInfo = vertexInfoMap_[v];
196 vector<const AlignmentColumn*> predecessorColumns = getPredecessorColumns(g_, v, colMap);
197
198 //
199 // handle row 0 separately:
200 //
201 if (predecessorColumns.size() == 0) {
202 // if this vertex doesn't have any in-edges it is ^; has
203 // no reaching move
204 assert(v == enterVertex_);
205 curCol->Score[0] = 0;
206 curCol->ReachingMove[0] = InvalidMove;
207 curCol->PreviousVertex[0] = null_vertex;
208 } else if (config.Mode == SEMIGLOBAL || config.Mode == LOCAL) {
209 // under semiglobal or local alignment, we use the Start move
210 curCol->Score[0] = 0;
211 curCol->ReachingMove[0] = StartMove;
212 curCol->PreviousVertex[0] = enterVertex_;
213 } else {
214 // otherwise it's a deletion
215 float candidateScore;
216 float bestScore = -FLT_MAX;
217 VD prevVertex = null_vertex;
218 MoveType reachingMove = InvalidMove;
219
220 foreach (const AlignmentColumn* prevCol, predecessorColumns) {
221 candidateScore = prevCol->Score[0] + config.Params.Delete;
222 if (candidateScore > bestScore) {
223 bestScore = candidateScore;
224 prevVertex = prevCol->CurrentVertex;
225 reachingMove = DeleteMove;
226 }
227 }
228 assert(reachingMove != InvalidMove);
229 curCol->Score[0] = bestScore;
230 curCol->ReachingMove[0] = reachingMove;
231 curCol->PreviousVertex[0] = prevVertex;
232 }
233
234 //
235 // tackle remainder of read.
236 //
237 // i represents position in array
238 // readPos=i-1 represents position in read
239 for (unsigned int i = 1, readPos = 0; i <= sequence.length(); i++, readPos++) {
240 float candidateScore, bestScore;
241 VD prevVertex;
242 MoveType reachingMove;
243
244 if (config.Mode == LOCAL) {
245 bestScore = 0;
246 prevVertex = enterVertex_;
247 reachingMove = StartMove;
248 } else {
249 bestScore = -FLT_MAX;
250 prevVertex = null_vertex;
251 reachingMove = InvalidMove;
252 }
253
254 foreach (const AlignmentColumn* prevCol, predecessorColumns) {
255 // Incorporate (Match or Mismatch)
256 bool isMatch = sequence[readPos] == vertexInfo.Base;
257 candidateScore =
258 prevCol->Score[i - 1] + (isMatch ? config.Params.Match : config.Params.Mismatch);
259 if (candidateScore > bestScore) {
260 bestScore = candidateScore;
261 prevVertex = prevCol->CurrentVertex;
262 reachingMove = (isMatch ? MatchMove : MismatchMove);
263 }
264 // Delete
265 candidateScore = prevCol->Score[i] + config.Params.Delete;
266 if (candidateScore > bestScore) {
267 bestScore = candidateScore;
268 prevVertex = prevCol->CurrentVertex;
269 reachingMove = DeleteMove;
270 }
271 }
272 // Extra
273 candidateScore = curCol->Score[i - 1] + config.Params.Insert;
274 if (candidateScore > bestScore) {
275 bestScore = candidateScore;
276 prevVertex = v;
277 reachingMove = ExtraMove;
278 }
279 assert(reachingMove != InvalidMove);
280 curCol->Score[i] = bestScore;
281 curCol->ReachingMove[i] = reachingMove;
282 curCol->PreviousVertex[i] = prevVertex;
283 }
284
285 return curCol;
286 }
287
288 void PoaGraphImpl::AddRead(const std::string& readSeq, const AlignConfig& config,
289 SdpRangeFinder* rangeFinder, std::vector<Vertex>* readPathOutput)
290 {
291 if (NumReads() == 0) {
292 AddFirstRead(readSeq, readPathOutput);
293 } else {
294 PoaAlignmentMatrixImpl* mat = TryAddRead(readSeq, config, rangeFinder);
295 CommitAdd(mat, readPathOutput);
296 delete mat;
297 }
298 }
299
300 void PoaGraphImpl::AddFirstRead(const std::string& readSeq, std::vector<Vertex>* readPathOutput)
301 {
302 DEBUG_ONLY(repCheck());
303 assert(readSeq.length() > 0);
304 assert(numReads_ == 0);
305
306 threadFirstRead(readSeq, readPathOutput);
307 numReads_++;
308
309 DEBUG_ONLY(repCheck());
310 }
311
312 PoaAlignmentMatrixImpl* PoaGraphImpl::TryAddRead(const std::string& readSeq,
313 const AlignConfig& config,
314 SdpRangeFinder* rangeFinder) const
315 {
316 DEBUG_ONLY(repCheck());
317 assert(readSeq.length() > 0);
318 assert(numReads_ > 0);
319
320 // Prepare the range finder, if applicable
321 if (rangeFinder != NULL) {
322 // NB: no minCoverage applicable here; this
323 // "intermediate" consensus may include extra sequence
324 // at either end
325 std::vector<VD> cssPath = consensusPath(config.Mode);
326 std::string cssSeq = sequenceAlongPath(g_, vertexInfoMap_, cssPath);
327 rangeFinder->InitRangeFinder(*this, externalizePath(cssPath), cssSeq, readSeq);
328 }
329
330 // Calculate alignment columns of sequence vs. graph, using sparsity if
331 // we have a range finder.
332 PoaAlignmentMatrixImpl* mat = new PoaAlignmentMatrixImpl();
333 mat->readSequence_ = readSeq;
334 mat->mode_ = config.Mode;
335
336 vector<VD> sortedVertices(num_vertices(g_));
337 topological_sort(g_, sortedVertices.rbegin());
338 const AlignmentColumn* curCol;
339 foreach (VD v, sortedVertices) {
340 if (v != exitVertex_) {
341 Interval rowRange;
342 if (rangeFinder) {
343 rowRange = rangeFinder->FindAlignableRange(externalize(v));
344 } else {
345 rowRange = Interval(0, readSeq.size());
346 }
347 curCol = makeAlignmentColumn(v, mat->columns_, readSeq, config, rowRange.Begin,
348 rowRange.End);
349 } else {
350 curCol = makeAlignmentColumnForExit(v, mat->columns_, readSeq, config);
351 }
352 mat->columns_[v] = curCol;
353 }
354
355 mat->score_ = mat->columns_[exitVertex_]->Score[readSeq.size()];
356 DEBUG_ONLY(repCheck());
357
358 return mat;
359 }
360
361 void PoaGraphImpl::CommitAdd(PoaAlignmentMatrix* mat_, std::vector<Vertex>* readPathOutput)
362 {
363 DEBUG_ONLY(repCheck());
364
365 PoaAlignmentMatrixImpl* mat = static_cast<PoaAlignmentMatrixImpl*>(mat_);
366 tracebackAndThread(mat->readSequence_, mat->columns_, mat->mode_, readPathOutput);
367 numReads_++;
368
369 DEBUG_ONLY(repCheck());
370 }
371
372 size_t PoaGraphImpl::NumReads() const { return numReads_; }
373
374 string PoaGraphImpl::ToGraphViz(int flags, const PoaConsensus* pc) const
375 {
376 std::stringstream ss;
377 write_graphviz(ss, g_, my_label_writer(vertexInfoMap_, flags & PoaGraph::COLOR_NODES,
378 flags & PoaGraph::VERBOSE_NODES, pc));
379 return ss.str();
380 }
381
382 void PoaGraphImpl::WriteGraphVizFile(string filename, int flags, const PoaConsensus* pc) const
383 {
384 std::ofstream outfile(filename.c_str());
385 outfile << ToGraphViz(flags, pc);
386 outfile.close();
387 }
388 }
389 } // ConsensusCore::detail