Debian Codegraph @

src/C++/Poa/PoaGraphImpl.hpp

raw
1
2 #pragma once
3 // This header is internal, not part of the API! ConsensusCore doesn't have a
4 // good directory-level separation of internal-vs-API, but we can at least
5 // prevent
6 // SWIG export
7 #ifdef SWIG
8 #error "PoaGraphImpl.hpp is not an API-facing header!"
9 #endif // SWIG
10
11 #include <ConsensusCore/Align/AlignConfig.hpp>
12 #include <ConsensusCore/Matrix/VectorL.hpp>
13 #include <ConsensusCore/Poa/PoaGraph.hpp>
14
15 #include <boost/config.hpp>
16 #include <boost/format.hpp>
17 #include <boost/graph/adjacency_list.hpp>
18 #include <boost/static_assert.hpp>
19 #include <boost/tuple/tuple.hpp>
20 #include <boost/type_traits.hpp>
21 #include <boost/utility.hpp>
22 #include <cfloat>
23 #include <climits>
24 #include <vector>
25
26 using std::string;
27 using std::vector;
28
29 ///
30 /// Boost graph library typedefs, properties, and graphviz output.
31 ///
32 using namespace boost; // NOLINT
33
34 namespace boost {
35 enum vertex_info_t
36 {
37 vertex_info = 424
38 }; // a unique #
39 BOOST_INSTALL_PROPERTY(vertex, info);
40 }
41
42 namespace ConsensusCore {
43 namespace detail {
44
45 class SdpRangeFinder;
46
47 enum MoveType
48 {
49 InvalidMove, // Invalid move reaching ^ (start)
50 StartMove, // Start move: ^ -> vertex in row 0 of local alignment
51 EndMove, // End move: vertex -> $ in row 0 of local alignment, or
52 // in global alignment, terminal vertex -> $
53 MatchMove,
54 MismatchMove,
55 DeleteMove,
56 ExtraMove
57 };
58
59 struct PoaNode
60 {
61 size_t Id; // This is the external-facing identifier we use to represent the
62 // vertex
63 char Base;
64 int Reads;
65 // move the below out of here?
66 int SpanningReads;
67 float Score;
68 float ReachingScore;
69
70 void Init(size_t id, char base, int reads)
71 {
72 this->Id = id;
73 this->Base = base;
74 this->Reads = reads;
75 this->SpanningReads = 0;
76 this->Score = 0;
77 this->ReachingScore = 0;
78 }
79
80 PoaNode() { Init(0, 'N', 0); }
81
82 PoaNode(size_t id, char base) { Init(id, base, 1); }
83
84 PoaNode(size_t id, char base, int reads) { Init(id, base, reads); }
85 };
86
87 // BGL is intimidating, and it *deserves* your hatred. But it's
88 // the only game in town!
89 typedef property<vertex_info_t, PoaNode, property<vertex_index_t, size_t>> vertex_property_t;
90 typedef adjacency_list<setS, listS, bidirectionalS, vertex_property_t> BoostGraph;
91
92 // Descriptor types used internally
93 typedef graph_traits<BoostGraph>::edge_descriptor ED;
94 typedef graph_traits<BoostGraph>::vertex_descriptor VD;
95
96 // External-facing vertex id type
97 typedef size_t Vertex;
98
99 typedef property_map<BoostGraph, vertex_info_t>::type VertexInfoMap;
100 typedef property_map<BoostGraph, vertex_index_t>::type index_map_t;
101 static const VD null_vertex = graph_traits<BoostGraph>::null_vertex();
102
103 struct EdgeComparator
104 {
105 EdgeComparator(const BoostGraph& g) : g_(g) {}
106
107 // want lex. comparison... just using pair to get it..
108 bool operator()(ED e1, ED e2)
109 {
110 std::pair<int, int> vt1, vt2;
111 vt1 = std::make_pair(get(vertex_index, g_, source(e1, g_)),
112 get(vertex_index, g_, target(e1, g_)));
113 vt2 = std::make_pair(get(vertex_index, g_, source(e2, g_)),
114 get(vertex_index, g_, target(e2, g_)));
115 return (vt1 < vt2);
116 }
117
118 private:
119 const BoostGraph& g_;
120 };
121
122 inline std::vector<ED> inEdges(VD v, const BoostGraph& g)
123 {
124 // This is a sad workaround the nondeterministic order of iteration
125 // from BGL's in_edges. (see: http://stackoverflow.com/questions/30968690/)
126
127 // Unfortunately, we can't just use the boost::sort range adapter
128 // because it requires an underlying random access iterator, which
129 // we can't get from the std::set container.
130 graph_traits<BoostGraph>::in_edge_iterator begin, end;
131 tie(begin, end) = in_edges(v, g);
132 std::vector<ED> tmp(begin, end);
133 std::sort(tmp.begin(), tmp.end(), EdgeComparator(g));
134 return tmp;
135 }
136
137 struct AlignmentColumn : noncopyable
138 {
139 VD CurrentVertex;
140 VectorL<float> Score;
141 VectorL<MoveType> ReachingMove;
142 VectorL<VD> PreviousVertex;
143
144 AlignmentColumn(VD vertex, int len)
145 : CurrentVertex(vertex)
146 , Score(0, len, -FLT_MAX)
147 , ReachingMove(0, len, InvalidMove)
148 , PreviousVertex(0, len, null_vertex)
149 {
150 }
151
152 AlignmentColumn(VD vertex, int beginRow, int endRow)
153 : CurrentVertex(vertex)
154 , Score(beginRow, endRow, -FLT_MAX)
155 , ReachingMove(beginRow, endRow, InvalidMove)
156 , PreviousVertex(beginRow, endRow, null_vertex)
157 {
158 }
159
160 ~AlignmentColumn() {}
161
162 int BeginRow() const { return Score.BeginRow(); }
163 int EndRow() const { return Score.EndRow(); }
164 };
165
166 typedef unordered_map<VD, const AlignmentColumn*> AlignmentColumnMap;
167
168 class PoaAlignmentMatrixImpl : public PoaAlignmentMatrix
169 {
170 public:
171 virtual ~PoaAlignmentMatrixImpl();
172 virtual float Score() const;
173
174 public:
175 AlignmentColumnMap columns_;
176 std::string readSequence_;
177 AlignMode mode_;
178 float score_;
179 };
180
181 class PoaGraphImpl
182 {
183 friend class SdpRangeFinder;
184
185 BoostGraph g_;
186 VertexInfoMap vertexInfoMap_; // NB: this is a reference type and refers to an
187 // "internal" property map
188 index_map_t indexMap_;
189 VD enterVertex_;
190 VD exitVertex_;
191 size_t numReads_;
192 size_t totalVertices_; // includes "ex"-vertices which have since been removed
193 size_t liveVertices_; // vertices that are in the graph. this is needed for
194 // algorithms.
195 std::map<Vertex, VD> vertexLookup_; // external ID -> internal ID
196
197 void repCheck() const;
198
199 Vertex externalize(VD vd) const { return vertexInfoMap_[vd].Id; }
200 VD internalize(Vertex vertex) const { return vertexLookup_.at(vertex); }
201
202 std::vector<Vertex> externalizePath(const std::vector<VD>& vds) const
203 {
204 std::vector<Vertex> out(vds.size(), 0);
205 for (size_t i = 0; i < vds.size(); i++) {
206 out[i] = externalize(vds[i]);
207 }
208 return out;
209 }
210
211 std::vector<VD> internalizePath(const std::vector<Vertex>& vertices) const
212 {
213 std::vector<VD> out(vertices.size(), null_vertex);
214 for (size_t i = 0; i < vertices.size(); i++) {
215 out[i] = internalize(vertices[i]);
216 }
217 return out;
218 }
219
220 VD addVertex(char base, int nReads = 1)
221 {
222 VD vd = add_vertex(g_);
223 Vertex vExt = totalVertices_++;
224 vertexInfoMap_[vd] = PoaNode(vExt, base, nReads);
225 vertexLookup_[vExt] = vd;
226 indexMap_[vd] = liveVertices_++;
227 return vd;
228 }
229
230 //
231 // utility routines
232 //
233 const AlignmentColumn* makeAlignmentColumn(VD v,
234 const AlignmentColumnMap& alignmentColumnForVertex,
235 const std::string& sequence,
236 const AlignConfig& config, int beginRow,
237 int endRow) const;
238
239 const AlignmentColumn* makeAlignmentColumnForExit(
240 VD v, const AlignmentColumnMap& alignmentColumnForVertex, const std::string& sequence,
241 const AlignConfig& config) const;
242
243 public:
244 //
245 // Graph traversal functions, defined in PoaGraphTraversals
246 //
247 void tagSpan(VD start, VD end);
248
249 std::vector<VD> consensusPath(AlignMode mode, int minCoverage = -INT_MAX) const;
250
251 void threadFirstRead(std::string sequence, std::vector<Vertex>* readPathOutput = NULL);
252
253 void tracebackAndThread(std::string sequence,
254 const AlignmentColumnMap& alignmentColumnForVertex, AlignMode mode,
255 std::vector<Vertex>* readPathOutput = NULL);
256
257 vector<ScoredMutation>* findPossibleVariants(const std::vector<Vertex>& bestPath) const;
258
259 public:
260 PoaGraphImpl();
261 PoaGraphImpl(const PoaGraphImpl& other);
262 ~PoaGraphImpl();
263
264 void AddRead(const std::string& sequence, const AlignConfig& config,
265 SdpRangeFinder* rangeFinder = NULL, std::vector<Vertex>* readPathOutput = NULL);
266
267 void AddFirstRead(const std::string& sequence, std::vector<Vertex>* readPathOutput = NULL);
268
269 PoaAlignmentMatrixImpl* TryAddRead(const std::string& sequence, const AlignConfig& config,
270 SdpRangeFinder* rangeFinder = NULL) const;
271
272 void CommitAdd(PoaAlignmentMatrix* mat, std::vector<Vertex>* readPathOutput = NULL);
273
274 PoaConsensus* FindConsensus(const AlignConfig& config, int minCoverage = -INT_MAX);
275
276 size_t NumReads() const;
277 string ToGraphViz(int flags, const PoaConsensus* pc) const;
278 void WriteGraphVizFile(string filename, int flags, const PoaConsensus* pc) const;
279 };
280
281 // free functions, we should put these all in traversals
282 std::string sequenceAlongPath(const BoostGraph& g, const VertexInfoMap& vertexInfoMap,
283 const std::vector<VD>& path);
284 }
285 } // ConsensusCore::detail