Debian Codegraph @

src/align/PairwiseAlignment.cpp

raw
1 #include <pbcopper/align/PairwiseAlignment.h>
2
3 #include <cassert>
4
5 #include <algorithm>
6 #include <string>
7 #include <utility>
8 #include <vector>
9
10 #include <boost/container/flat_set.hpp>
11 #include <boost/numeric/ublas/matrix.hpp>
12
13 #include <pbcopper/utility/MinMax.h>
14 #include <pbcopper/utility/SequenceUtils.h>
15
16 namespace PacBio {
17 namespace Align {
18 namespace {
19
20 constexpr int ArgMax3(int a, int b, int c)
21 {
22 if (a >= b && a >= c) {
23 return 0;
24 } else if (b >= c) {
25 return 1;
26 } else {
27 return 2;
28 }
29 }
30
31 } // namespace
32
33 namespace internal {
34
35 bool Rewrite2L(std::string* target, std::string* query, std::string* transcript, const size_t i)
36 {
37 char& t0 = (*target)[i];
38 char& t1 = (*target)[i + 1];
39 char& q0 = (*query)[i];
40 char& q1 = (*query)[i + 1];
41 char& x0 = (*transcript)[i];
42 char& x1 = (*transcript)[i + 1];
43
44 // t: XX XX
45 // |* -> *|
46 // q: X- -X
47 if (q1 == '-' && t0 == t1 && t1 == q0) {
48 std::swap(q0, q1);
49 std::swap(x0, x1);
50 return true;
51 }
52 // t: X- -X
53 // |* -> *|
54 // q: XX XX
55 else if (t1 == '-' && q0 == q1 && q1 == t0) {
56 std::swap(t0, t1);
57 std::swap(x0, x1);
58 return true;
59 }
60 return false;
61 }
62
63 bool Rewrite3L(std::string* target, std::string* query, std::string* transcript, const size_t i)
64 {
65 char& t0 = (*target)[i];
66 char& t2 = (*target)[i + 2];
67 char& q0 = (*query)[i];
68 char& q2 = (*query)[i + 2];
69 char& x0 = (*transcript)[i];
70 char& x2 = (*transcript)[i + 2];
71
72 // t: X-- --X
73 // |** -> **|
74 // q: XYX XYX
75 if (t0 == q2 && transcript->substr(i, 3) == "MII") {
76 std::swap(t0, t2);
77 std::swap(x0, x2);
78 return true;
79 }
80 // t: XYX XYX
81 // |** -> **|
82 // q: X-- --X
83 else if (q0 == t2 && transcript->substr(i, 3) == "MDD") {
84 std::swap(q0, q2);
85 std::swap(x0, x2);
86 return true;
87 }
88 return false;
89 }
90
91 bool Rewrite2R(std::string* target, std::string* query, std::string* transcript, const size_t i)
92 {
93 char& t0 = (*target)[i];
94 char& t1 = (*target)[i + 1];
95 char& q0 = (*query)[i];
96 char& q1 = (*query)[i + 1];
97 char& x0 = (*transcript)[i];
98 char& x1 = (*transcript)[i + 1];
99
100 // t: XX XX
101 // *| -> |*
102 // q: -X X-
103 if (q0 == '-' && t0 == t1 && t1 == q1) {
104 std::swap(q0, q1);
105 std::swap(x0, x1);
106 return true;
107 }
108 // t: -X X-
109 // *| -> |*
110 // q: XX XX
111 else if (t0 == '-' && q0 == q1 && q1 == t1) {
112 std::swap(t0, t1);
113 std::swap(x0, x1);
114 return true;
115 }
116 return false;
117 }
118
119 bool Rewrite3R(std::string* target, std::string* query, std::string* transcript, const size_t i)
120 {
121 char& t0 = (*target)[i];
122 char& t2 = (*target)[i + 2];
123 char& q0 = (*query)[i];
124 char& q2 = (*query)[i + 2];
125 char& x0 = (*transcript)[i];
126 char& x2 = (*transcript)[i + 2];
127
128 // t: --X X--
129 // **| -> |**
130 // q: XYX XYX
131 if (q0 == t2 && transcript->substr(i, 3) == "IIM") {
132 std::swap(t0, t2);
133 std::swap(x0, x2);
134 return true;
135 }
136 // t: XYX XYX
137 // **| -> |**
138 // q: --X X--
139 else if (t0 == q2 && transcript->substr(i, 3) == "DDM") {
140 std::swap(q0, q2);
141 std::swap(x0, x2);
142 return true;
143 }
144 return false;
145 }
146
147 } // namespace internal
148
149 std::string PairwiseAlignment::Target() const { return target_; }
150
151 std::string PairwiseAlignment::Query() const { return query_; }
152
153 size_t PairwiseAlignment::ReferenceStart() const { return refStart_; }
154
155 size_t PairwiseAlignment::ReferenceEnd() const { return refEnd_; }
156
157 float PairwiseAlignment::Accuracy() const { return (static_cast<float>(Matches())) / Length(); }
158
159 std::string PairwiseAlignment::Transcript() const { return transcript_; }
160
161 int PairwiseAlignment::Matches() const
162 {
163 return std::count(transcript_.begin(), transcript_.end(), 'M');
164 }
165
166 int PairwiseAlignment::Errors() const { return Length() - Matches(); }
167
168 int PairwiseAlignment::Mismatches() const
169 {
170 return std::count(transcript_.begin(), transcript_.end(), 'R');
171 }
172
173 int PairwiseAlignment::Insertions() const
174 {
175 return std::count(transcript_.begin(), transcript_.end(), 'I');
176 }
177
178 int PairwiseAlignment::Deletions() const
179 {
180 return std::count(transcript_.begin(), transcript_.end(), 'D');
181 }
182
183 void PairwiseAlignment::Justify(const LRType lr)
184 {
185 const size_t L = Length();
186
187 if (L < 2) {
188 return;
189 }
190
191 while (true) {
192 bool goAgain = false;
193 if (lr == LRType::LEFT) {
194 goAgain |= internal::Rewrite2L(&target_, &query_, &transcript_, L - 2);
195 for (size_t i = L - 2; i > 0; --i) {
196 goAgain |= internal::Rewrite2L(&target_, &query_, &transcript_, i - 1);
197 goAgain |= internal::Rewrite3L(&target_, &query_, &transcript_, i - 1);
198 }
199 } else {
200 for (size_t i = 0; i < L - 2; ++i) {
201 goAgain |= internal::Rewrite2R(&target_, &query_, &transcript_, i);
202 goAgain |= internal::Rewrite3R(&target_, &query_, &transcript_, i);
203 }
204 goAgain |= internal::Rewrite2R(&target_, &query_, &transcript_, L - 2);
205 }
206 if (!goAgain) {
207 break;
208 }
209 }
210 }
211
212 int PairwiseAlignment::Length() const { return target_.length(); }
213
214 PairwiseAlignment::PairwiseAlignment(std::string target, std::string query, const size_t refStart,
215 const size_t refEnd)
216 : target_(std::move(target))
217 , query_(std::move(query))
218 , transcript_(target_.length(), 'Z')
219 , refStart_(refStart)
220 , refEnd_(refEnd)
221 {
222 if (target_.length() != query_.length()) {
223 throw std::invalid_argument(
224 "[pbcopper] pairwise alignment ERROR: target length must equal query length");
225 }
226 for (unsigned int i = 0; i < target_.length(); i++) {
227 char t = target_[i];
228 char q = query_[i];
229 char tr;
230
231 if (t == '-' && q == '-') {
232 throw std::invalid_argument{
233 "[pbcopper] pairwise alignment ERROR: invalid target and query transcript"};
234 } else if (t == q) {
235 tr = 'M';
236 } else if (t == '-') {
237 tr = 'I';
238 } else if (q == '-') {
239 tr = 'D';
240 } else {
241 tr = 'R';
242 } // NOLINT
243
244 transcript_[i] = tr;
245 }
246 }
247
248 std::vector<int> PairwiseAlignment::TargetPositions() const
249 {
250 std::vector<int> pos;
251 pos.reserve(transcript_.size());
252
253 int refPos = refStart_;
254 for (const char c : transcript_) {
255 if (c == 'M' || c == 'R' || c == 'D') {
256 pos.push_back(refPos);
257 refPos++;
258 } else if (c == 'I') {
259 pos.push_back(refPos);
260 } else {
261 throw std::runtime_error{
262 "[pbcopper] pairwise alignment ERROR: unknown transcript code: " +
263 std::string(1, c)};
264 }
265 }
266
267 assert(pos.size() == transcript_.size());
268 return pos;
269 }
270
271 PairwiseAlignment PairwiseAlignment::ClippedTo(const size_t refStart, const size_t refEnd)
272 {
273 if (refStart >= refEnd || refStart >= ReferenceEnd() || refEnd <= ReferenceStart()) {
274 throw std::runtime_error{
275 "[pbcopper] pairwise alignment ERROR: requested clip range does not overlap alignment"};
276 }
277
278 const size_t clipRefStart = std::max(refStart, ReferenceStart());
279 const size_t clipRefEnd = std::min(refEnd, ReferenceEnd());
280
281 const std::vector<int> pos = TargetPositions();
282 size_t clipStart =
283 std::distance(pos.begin(), std::upper_bound(pos.begin(), pos.end(), clipRefStart));
284 clipStart = clipStart > 0 ? clipStart - 1 : 0;
285 const size_t clipEnd =
286 std::distance(pos.begin(), std::lower_bound(pos.begin(), pos.end(), clipRefEnd));
287 const size_t clipLength = clipEnd - clipStart;
288
289 const std::string& clippedQuery = Query().substr(clipStart, clipLength);
290 const std::string& clippedTarget = Target().substr(clipStart, clipLength);
291
292 return PairwiseAlignment(clippedTarget, clippedQuery, clipRefStart, clipRefEnd);
293 }
294
295 PairwiseAlignment* Align(const std::string& target, const std::string& query, int* score,
296 AlignConfig config)
297 {
298 using boost::numeric::ublas::matrix;
299
300 const AlignParams& params = config.Params;
301 if (config.Mode != AlignMode::GLOBAL && config.Mode != AlignMode::SEMIGLOBAL) {
302 throw std::invalid_argument{
303 "[pbcopper] pairwise alignment ERROR: only GLOBAL and SEMIGLOBAL alignments supported "
304 "at present"};
305 }
306
307 #ifndef NDEBUG
308 // we can only align IUPAC bases, not gaps or any other characters
309 const static boost::container::flat_set<char> validBases{
310 'A', 'B', 'C', 'D', 'G', 'H', 'K', 'M', 'N', 'R', 'S', 'T', 'V', 'W', 'Y',
311 'a', 'b', 'c', 'd', 'g', 'h', 'k', 'm', 'n', 'r', 's', 't', 'v', 'w', 'y'};
312
313 for (char c : target) {
314 assert(validBases.find(c) != validBases.cend());
315 }
316
317 for (char c : query) {
318 assert(validBases.find(c) != validBases.cend());
319 }
320 #endif
321
322 int I = query.length();
323 int J = target.length();
324 matrix<int> Score(I + 1, J + 1);
325
326 Score(0, 0) = 0;
327 for (int i = 1; i <= I; i++) {
328 Score(i, 0) = i * params.Insert;
329 }
330 if (config.Mode == AlignMode::GLOBAL) {
331 for (int j = 1; j <= J; j++) {
332 Score(0, j) = j * params.Delete;
333 }
334 } else {
335 for (int j = 1; j <= J; j++) {
336 Score(0, j) = 0;
337 }
338 }
339 for (int i = 1; i <= I; i++) {
340 for (int j = 1; j <= J; j++) {
341 bool isMatch = (query[i - 1] == target[j - 1]);
342 Score(i, j) =
343 Utility::Max(Score(i - 1, j - 1) + (isMatch ? params.Match : params.Mismatch),
344 Score(i - 1, j) + params.Insert, Score(i, j - 1) + params.Delete);
345 }
346 }
347 if (score != nullptr) {
348 *score = Score(I, J);
349 }
350
351 // Find the alignment end coordinate in the reference
352 // This is J if Global and the maximum scoring position if not
353 int maxJ = J;
354 if (config.Mode == AlignMode::SEMIGLOBAL) {
355 int maxScore = std::numeric_limits<int>::min();
356 for (int j = 1; j <= J; ++j) {
357 if (Score(I, j) >= maxScore) {
358 maxScore = Score(I, j);
359 maxJ = j;
360 }
361 }
362 }
363
364 // Traceback, build up reversed aligned query, aligned target
365 int i = I;
366 int j = maxJ;
367 std::string raQuery;
368 std::string raTarget;
369 while (i > 0 || (config.Mode == AlignMode::GLOBAL && j > 0)) {
370 int move;
371 if (i == 0) {
372 move = 2; // only deletion is possible
373 } else if (j == 0) {
374 move = 1; // only insertion is possible
375 } else {
376 bool isMatch = (query[i - 1] == target[j - 1]);
377 move = ArgMax3(Score(i - 1, j - 1) + (isMatch ? params.Match : params.Mismatch),
378 Score(i - 1, j) + params.Insert, Score(i, j - 1) + params.Delete);
379 }
380 // Incorporate:
381 if (move == 0) {
382 i--;
383 j--;
384 raQuery.push_back(query[i]);
385 raTarget.push_back(target[j]);
386 }
387 // Insert:
388 else if (move == 1) {
389 i--;
390 raQuery.push_back(query[i]);
391 raTarget.push_back('-');
392 }
393 // Delete:
394 else if (move == 2) {
395 j--;
396 raQuery.push_back('-');
397 raTarget.push_back(target[j]);
398 }
399 }
400
401 return new PairwiseAlignment(Utility::Reversed(raTarget), Utility::Reversed(raQuery),
402 std::max(0, j - 1), maxJ - 1);
403 }
404
405 PairwiseAlignment* Align(const std::string& target, const std::string& query, AlignConfig config)
406 {
407 return Align(target, query, nullptr, config);
408 }
409
410 //
411 // Code for lifting target coordinates into query coordinates.
412 //
413
414 static bool addsToTarget(char transcriptChar)
415 {
416 return (transcriptChar == 'M' || transcriptChar == 'R' || transcriptChar == 'D');
417 }
418
419 static int targetLength(const std::string& alignmentTranscript)
420 {
421 return std::count_if(alignmentTranscript.begin(), alignmentTranscript.end(), addsToTarget);
422 }
423
424 #ifndef NDEBUG
425 static bool addsToQuery(char transcriptChar)
426 {
427 return (transcriptChar == 'M' || transcriptChar == 'R' || transcriptChar == 'I');
428 }
429
430 static int queryLength(const std::string& alignmentTranscript)
431 {
432 return std::count_if(alignmentTranscript.begin(), alignmentTranscript.end(), addsToQuery);
433 }
434 #endif // !NDEBUG
435
436 // TargetPositionsInQuery:
437 // * Returns a vector of targetLength(transcript) + 1, which,
438 // roughly speaking, indicates the positions in the query string of the
439 // the characters in the target, as induced by an alignment with the
440 // given transcript string.
441 // * More precisely, given an alignment (T, Q, X) (x=transcript),
442 // letting T[s, e) denote any slice of T,
443 // - [s',e') denote the subslice of indices of Q aligned to T[s, e),
444 // - ntp = NewTargetPositions(X)
445 // we have
446 // [s', e') = [ntp(s), ntp(e))
447 //
448 // * Ex:
449 // MMM -> 0123
450 // DMM -> 0012, MMD -> 0122, MDM -> 0112
451 // IMM -> 123, MMI -> 013, MIM -> 023
452 // MRM, MIDM, MDIM -> 0123
453 std::vector<int> TargetToQueryPositions(const std::string& transcript)
454 {
455 std::vector<int> ntp;
456 ntp.reserve(targetLength(transcript) + 1);
457
458 int queryPos = 0;
459 for (const char c : transcript) {
460 if (c == 'M' || c == 'R') {
461 ntp.push_back(queryPos);
462 queryPos++;
463 } else if (c == 'D') {
464 ntp.push_back(queryPos);
465 } else if (c == 'I') {
466 queryPos++;
467 } else {
468 throw std::runtime_error{
469 "[pbcopper] pairwise alignment ERROR: unknown transcript code: " +
470 std::string(1, c)};
471 }
472 }
473 ntp.push_back(queryPos);
474
475 assert(static_cast<int>(ntp.size()) == targetLength(transcript) + 1);
476 assert(ntp[targetLength(transcript)] == queryLength(transcript));
477 return ntp;
478 }
479
480 std::vector<int> TargetToQueryPositions(const PairwiseAlignment& aln)
481 {
482 return TargetToQueryPositions(aln.Transcript());
483 }
484
485 // Build the alignment given the unaligned sequences and the transcript
486 // Returns NULL if transcript does not map unalnTarget into unalnQuery.
487 PairwiseAlignment* PairwiseAlignment::FromTranscript(const std::string& transcript,
488 const std::string& unalnTarget,
489 const std::string& unalnQuery)
490 {
491 std::string alnTarget;
492 std::string alnQuery;
493 int tPos;
494 int qPos;
495 int tLen;
496 int qLen;
497
498 tLen = unalnTarget.length();
499 qLen = unalnQuery.length();
500 tPos = 0;
501 qPos = 0;
502 for (const char x : transcript) {
503 if (tPos > tLen || qPos > qLen) {
504 return nullptr;
505 }
506
507 char t = (tPos < tLen ? unalnTarget[tPos] : '\0');
508 char q = (qPos < qLen ? unalnQuery[qPos] : '\0');
509
510 switch (x) {
511 case 'M':
512 if (t != q) {
513 return nullptr;
514 }
515 alnTarget.push_back(t);
516 alnQuery.push_back(q);
517 tPos++;
518 qPos++;
519 break;
520 case 'R':
521 if (t == q) {
522 return nullptr;
523 }
524 alnTarget.push_back(t);
525 alnQuery.push_back(q);
526 tPos++;
527 qPos++;
528 break;
529 case 'I':
530 alnTarget.push_back('-');
531 alnQuery.push_back(q);
532 qPos++;
533 break;
534 case 'D':
535 alnTarget.push_back(t);
536 alnQuery.push_back('-');
537 tPos++;
538 break;
539 default:
540 return nullptr;
541 }
542 }
543 // Didn't consume all of one of the strings
544 if (tPos != tLen || qPos != qLen) {
545 return nullptr;
546 }
547
548 // Provide another constructor to inject transcript? Calculate transcript on the fly?
549 return new PairwiseAlignment(alnTarget, alnQuery);
550 }
551
552 } // namespace Align
553 } // namespace PacBio