Debian Codegraph @

src/C++/Align/PairwiseAlignment.cpp

raw
1 // Author: David Alexander
2
3 #include <ConsensusCore/Align/PairwiseAlignment.hpp>
4
5 #include <algorithm>
6 #include <boost/numeric/ublas/matrix.hpp>
7 #include <string>
8 #include <vector>
9
10 #include <ConsensusCore/Sequence.hpp>
11 #include <ConsensusCore/Types.hpp>
12 #include <ConsensusCore/Utils.hpp>
13
14 namespace ConsensusCore {
15
16 std::string PairwiseAlignment::Target() const { return target_; }
17
18 std::string PairwiseAlignment::Query() const { return query_; }
19
20 float PairwiseAlignment::Accuracy() const { return (static_cast<float>(Matches())) / Length(); }
21
22 std::string PairwiseAlignment::Transcript() const { return transcript_; }
23
24 int PairwiseAlignment::Matches() const
25 {
26 return std::count(transcript_.begin(), transcript_.end(), 'M');
27 }
28
29 int PairwiseAlignment::Errors() const { return Length() - Matches(); }
30
31 int PairwiseAlignment::Mismatches() const
32 {
33 return std::count(transcript_.begin(), transcript_.end(), 'R');
34 }
35
36 int PairwiseAlignment::Insertions() const
37 {
38 return std::count(transcript_.begin(), transcript_.end(), 'I');
39 }
40
41 int PairwiseAlignment::Deletions() const
42 {
43 return std::count(transcript_.begin(), transcript_.end(), 'D');
44 }
45
46 int PairwiseAlignment::Length() const { return target_.length(); }
47
48 PairwiseAlignment::PairwiseAlignment(const std::string& target, const std::string& query)
49 : target_(target), query_(query), transcript_(target_.length(), 'Z')
50 {
51 if (target_.length() != query_.length()) {
52 throw InvalidInputError();
53 }
54 for (unsigned int i = 0; i < target_.length(); i++) {
55 char t = target_[i];
56 char q = query_[i];
57 char tr;
58
59 if (t == '-' && q == '-') {
60 throw InvalidInputError();
61 } else if (t == q) {
62 tr = 'M';
63 } else if (t == '-') {
64 tr = 'I';
65 } else if (q == '-') {
66 tr = 'D';
67 } else {
68 tr = 'R';
69 } // NOLINT
70
71 transcript_[i] = tr;
72 }
73 }
74
75 PairwiseAlignment* Align(const std::string& target, const std::string& query, int* score,
76 AlignConfig config)
77 {
78 using boost::numeric::ublas::matrix;
79
80 const AlignParams& params = config.Params;
81 if (config.Mode != GLOBAL) {
82 throw UnsupportedFeatureError("Only GLOBAL alignment supported at present");
83 }
84
85 int I = query.length();
86 int J = target.length();
87 matrix<int> Score(I + 1, J + 1);
88
89 Score(0, 0) = 0;
90 for (int i = 1; i <= I; i++) {
91 Score(i, 0) = i * params.Insert;
92 }
93 for (int j = 1; j <= J; j++) {
94 Score(0, j) = j * params.Delete;
95 }
96 for (int i = 1; i <= I; i++) {
97 for (int j = 1; j <= J; j++) {
98 bool isMatch = (query[i - 1] == target[j - 1]);
99 Score(i, j) = Max3(Score(i - 1, j - 1) + (isMatch ? params.Match : params.Mismatch),
100 Score(i - 1, j) + params.Insert, Score(i, j - 1) + params.Delete);
101 }
102 }
103 if (score != NULL) {
104 *score = Score(I, J);
105 }
106
107 // Traceback, build up reversed aligned query, aligned target
108 std::string raQuery, raTarget;
109 int i = I, j = J;
110 while (i > 0 || j > 0) {
111 int move;
112 if (i == 0) {
113 move = 2; // only deletion is possible
114 } else if (j == 0) {
115 move = 1; // only insertion is possible
116 } else {
117 bool isMatch = (query[i - 1] == target[j - 1]);
118 move = ArgMax3(Score(i - 1, j - 1) + (isMatch ? params.Match : params.Mismatch),
119 Score(i - 1, j) + params.Insert, Score(i, j - 1) + params.Delete);
120 }
121 // Incorporate:
122 if (move == 0) {
123 i--;
124 j--;
125 raQuery.push_back(query[i]);
126 raTarget.push_back(target[j]);
127 }
128 // Insert:
129 else if (move == 1) {
130 i--;
131 raQuery.push_back(query[i]);
132 raTarget.push_back('-');
133 }
134 // Delete:
135 else if (move == 2) {
136 j--;
137 raQuery.push_back('-');
138 raTarget.push_back(target[j]);
139 }
140 }
141
142 return new PairwiseAlignment(Reverse(raTarget), Reverse(raQuery));
143 }
144
145 PairwiseAlignment* Align(const std::string& target, const std::string& query, AlignConfig config)
146 {
147 return Align(target, query, NULL, config);
148 }
149
150 //
151 // Code for lifting target coordinates into query coordinates.
152 //
153
154 static bool addsToTarget(char transcriptChar)
155 {
156 return (transcriptChar == 'M' || transcriptChar == 'R' || transcriptChar == 'D');
157 }
158
159 static int targetLength(const std::string& alignmentTranscript)
160 {
161 return std::count_if(alignmentTranscript.begin(), alignmentTranscript.end(), addsToTarget);
162 }
163
164 #ifndef NDEBUG
165 static bool addsToQuery(char transcriptChar)
166 {
167 return (transcriptChar == 'M' || transcriptChar == 'R' || transcriptChar == 'I');
168 }
169
170 static int queryLength(const std::string& alignmentTranscript)
171 {
172 return std::count_if(alignmentTranscript.begin(), alignmentTranscript.end(), addsToQuery);
173 }
174 #endif // !NDEBUG
175
176 // TargetPositionsInQuery:
177 // * Returns a vector of targetLength(transcript) + 1, which,
178 // roughly speaking, indicates the positions in the query string of the
179 // the characters in the target, as induced by an alignment with the
180 // given transcript string.
181 // * More precisely, given an alignment (T, Q, X) (x=transcript),
182 // letting T[s, e) denote any slice of T,
183 // - [s',e') denote the subslice of indices of Q aligned to T[s, e),
184 // - ntp = NewTargetPositions(X)
185 // we have
186 // [s', e') = [ntp(s), ntp(e))
187 //
188 // * Ex:
189 // MMM -> 0123
190 // DMM -> 0012, MMD -> 0122, MDM -> 0112
191 // IMM -> 123, MMI -> 013, MIM -> 023
192 // MRM, MIDM, MDIM -> 0123
193 std::vector<int> TargetToQueryPositions(const std::string& transcript)
194 {
195 std::vector<int> ntp;
196 ntp.reserve(targetLength(transcript) + 1);
197
198 int targetPos = 0;
199 int queryPos = 0;
200 foreach (char c, transcript) {
201 if (c == 'M' || c == 'R') {
202 ntp.push_back(queryPos);
203 targetPos++;
204 queryPos++;
205 } else if (c == 'D') {
206 ntp.push_back(queryPos);
207 targetPos++;
208 } else if (c == 'I') {
209 queryPos++;
210 } else {
211 ShouldNotReachHere();
212 }
213 }
214 ntp.push_back(queryPos);
215
216 assert(static_cast<int>(ntp.size()) == targetLength(transcript) + 1);
217 assert(ntp[targetLength(transcript)] == queryLength(transcript));
218 return ntp;
219 }
220
221 std::vector<int> TargetToQueryPositions(const PairwiseAlignment& aln)
222 {
223 return TargetToQueryPositions(aln.Transcript());
224 }
225
226 // Build the alignment given the unaligned sequences and the transcript
227 // Returns NULL if transcript does not map unalnTarget into unalnQuery.
228 PairwiseAlignment* PairwiseAlignment::FromTranscript(const std::string& transcript,
229 const std::string& unalnTarget,
230 const std::string& unalnQuery)
231 {
232 std::string alnTarget;
233 std::string alnQuery;
234 int tPos, qPos;
235 int tLen, qLen;
236
237 tLen = unalnTarget.length();
238 qLen = unalnQuery.length();
239 tPos = 0;
240 qPos = 0;
241 foreach (char x, transcript) {
242 if (tPos > tLen || qPos > qLen) {
243 return NULL;
244 }
245
246 char t = (tPos < tLen ? unalnTarget[tPos] : '\0');
247 char q = (qPos < qLen ? unalnQuery[qPos] : '\0');
248
249 switch (x) {
250 case 'M':
251 if (t != q) {
252 return NULL;
253 }
254 alnTarget.push_back(t);
255 alnQuery.push_back(q);
256 tPos++;
257 qPos++;
258 break;
259 case 'R':
260 if (t == q) {
261 return NULL;
262 }
263 alnTarget.push_back(t);
264 alnQuery.push_back(q);
265 tPos++;
266 qPos++;
267 break;
268 case 'I':
269 alnTarget.push_back('-');
270 alnQuery.push_back(q);
271 qPos++;
272 break;
273 case 'D':
274 alnTarget.push_back(t);
275 alnQuery.push_back('-');
276 tPos++;
277 break;
278 default:
279 return NULL;
280 }
281 }
282 // Didn't consume all of one of the strings
283 if (tPos != tLen || qPos != qLen) {
284 return NULL;
285 }
286
287 // Provide another constructor to inject transcript? Calculate transcript on
288 // the fly?
289 return new PairwiseAlignment(alnTarget, alnQuery);
290 }
291 }