Debian Codegraph @

src/align/BandedChainAlignment.cpp

raw
1 #include <pbcopper/align/BandedChainAlignment.h>
2
3 #include <cassert>
4 #include <cfloat>
5
6 #include <algorithm>
7 #include <array>
8 #include <limits>
9 #include <stdexcept>
10 #include <utility>
11 #include <vector>
12
13 #include <pbcopper/align/internal/BCAlignBlocks.h>
14 #include <pbcopper/align/internal/BCAlignImpl.h>
15 #include <pbcopper/utility/MinMax.h>
16
17 namespace PacBio {
18 namespace Align {
19 namespace {
20
21 float score(const char t, const char q, const BandedChainAlignConfig& config)
22 {
23 return (t == q ? config.matchScore_ : config.mismatchPenalty_);
24 }
25
26 void addAlignmentOp(std::string* transcript, const char c) { transcript->push_back(c); }
27
28 } // namespace
29
30 namespace Internal {
31
32 // ------------------------
33 // BandedGlobalAlignBlock
34 // ------------------------
35
36 std::string BandedGlobalAlignBlock::Align(const char* target, const char* query, Align::Seed seed)
37 {
38
39 // ensure horizontal sequence length is >= vertical
40 // (simplifies band calculations)
41 const size_t qLen = seed.EndPositionV() - seed.BeginPositionV();
42 const size_t tLen = seed.EndPositionH() - seed.BeginPositionH();
43 if (qLen == 0) {
44 return std::string(tLen, 'D');
45 } else if (tLen == 0) {
46 return std::string(qLen, 'I');
47 }
48
49 std::string result;
50
51 const bool seqsFlipped = (qLen > tLen);
52 const char* seq1 =
53 (seqsFlipped ? (target + seed.BeginPositionH()) : (query + seed.BeginPositionV()));
54 const char* seq2 =
55 (seqsFlipped ? (query + seed.BeginPositionV()) : (target + seed.BeginPositionH()));
56 const size_t seq1Len = (seqsFlipped ? tLen : qLen);
57 const size_t seq2Len = (seqsFlipped ? qLen : tLen);
58
59 // Initialize space & scores
60 Init(seq2Len, seq1Len);
61
62 // for each row
63 for (size_t i = 1; i <= seq1Len; ++i) {
64
65 // foreach column within band
66 const auto& e = lookup_[i];
67 for (size_t j = e.jBegin_; j <= e.jEnd_; ++j) {
68
69 if (j == 0) {
70 continue;
71 }
72
73 const auto currentIdx = IndexFor(i, j);
74 const auto diagIdx = IndexFor(i - 1, j - 1);
75 const auto upIdx = IndexFor(i - 1, j);
76 const auto leftIdx = IndexFor(i, j - 1);
77 const bool upAllowed = (upIdx != std::string::npos);
78 const bool leftAllowed = (leftIdx != std::string::npos);
79
80 const auto s = score(seq2[j - 1], seq1[i - 1], config_);
81
82 matchScores_[currentIdx] = (std::max(matchScores_[diagIdx], gapScores_[diagIdx]) + s);
83
84 gapScores_[currentIdx] = Utility::Max(
85 (leftAllowed ? matchScores_[leftIdx] + config_.gapOpenPenalty_ : -FLT_MAX),
86 (leftAllowed ? gapScores_[leftIdx] + config_.gapExtendPenalty_ : -FLT_MAX),
87 (upAllowed ? matchScores_[upIdx] + config_.gapOpenPenalty_ : -FLT_MAX),
88 (upAllowed ? gapScores_[upIdx] + config_.gapExtendPenalty_ : -FLT_MAX));
89 }
90 }
91
92 // Traceback
93 const size_t MATCH_MATRIX = 1;
94 const size_t GAP_MATRIX = 2;
95
96 // find traceback start
97 const auto btStart = BacktraceStart(seq2Len, seq1Len);
98 size_t i = btStart.first;
99 size_t j = btStart.second;
100 const size_t backtraceStartIdx = IndexFor(btStart.first, btStart.second);
101
102 size_t mat = (matchScores_[backtraceStartIdx] >= gapScores_[backtraceStartIdx] ? MATCH_MATRIX
103 : GAP_MATRIX);
104 size_t iPrev;
105 size_t jPrev;
106 size_t matPrev;
107
108 // if not beginning at bottom right)
109 if (i < seq1Len) {
110 const auto op = (seqsFlipped ? 'D' : 'I');
111 for (size_t k = seq1Len - i; k > 0; --k) {
112 addAlignmentOp(&result, op);
113 }
114 } else if (j < seq2Len) {
115 const auto op = (seqsFlipped ? 'I' : 'D');
116 for (size_t k = seq2Len - j; k > 0; --k) {
117 addAlignmentOp(&result, op);
118 }
119 }
120
121 while (i > 0 || j > 0) {
122
123 if (mat == MATCH_MATRIX) {
124
125 const auto diagIdx = IndexFor(i - 1, j - 1);
126 matPrev = (matchScores_[diagIdx] >= gapScores_[diagIdx] ? MATCH_MATRIX : GAP_MATRIX);
127 iPrev = i - 1;
128 jPrev = j - 1;
129 const auto op = (seq1[iPrev] == seq2[jPrev] ? 'M' : 'R');
130 addAlignmentOp(&result, op);
131
132 } else {
133 assert(mat == GAP_MATRIX);
134
135 const auto upIdx = IndexFor(i - 1, j);
136 const auto leftIdx = IndexFor(i, j - 1);
137 const auto upAllowed = (upIdx != std::string::npos);
138 const auto leftAllowed = (leftIdx != std::string::npos);
139
140 const std::array<float, 4> s{
141 {(j > 0 && leftAllowed ? matchScores_[leftIdx] + config_.gapOpenPenalty_
142 : -FLT_MAX),
143 (j > 0 && leftAllowed ? gapScores_[leftIdx] + config_.gapExtendPenalty_
144 : -FLT_MAX),
145 (i > 0 && upAllowed ? matchScores_[upIdx] + config_.gapOpenPenalty_ : -FLT_MAX),
146 (i > 0 && upAllowed ? gapScores_[upIdx] + config_.gapExtendPenalty_ : -FLT_MAX)}};
147 const auto argMax = std::distance(s.cbegin(), std::max_element(s.cbegin(), s.cend()));
148
149 matPrev = ((argMax == 0 || argMax == 2) ? MATCH_MATRIX : GAP_MATRIX);
150 if (argMax == 0 || argMax == 1) {
151
152 iPrev = i;
153 jPrev = j - 1;
154 const auto op = (seqsFlipped ? 'I' : 'D');
155 addAlignmentOp(&result, op);
156 } else {
157
158 iPrev = i - 1;
159 jPrev = j;
160 const auto op = (seqsFlipped ? 'D' : 'I');
161 addAlignmentOp(&result, op);
162 }
163 }
164
165 // step back one
166 i = iPrev;
167 j = jPrev;
168 mat = matPrev;
169
170 // if at edge, force gap moves from here on
171 if (i == 0 || j == 0) {
172 mat = GAP_MATRIX;
173 }
174 }
175
176 // reverse transcript & return
177 std::reverse(result.begin(), result.end());
178 return result;
179 }
180
181 std::pair<size_t, size_t> BandedGlobalAlignBlock::BacktraceStart(const size_t tLen,
182 const size_t qLen) const
183 {
184 // NOTE: Finding backtrace start this way allows us to not penalize end-gaps.
185 const size_t maxIndex = std::min(qLen, tLen);
186
187 // find max score in last column
188 std::pair<size_t, size_t> maxCellRight{maxIndex, maxIndex};
189 float maxScoreRight = -FLT_MAX;
190 {
191 for (size_t i = 1; i <= maxIndex; ++i) {
192 const auto& e = lookup_[i];
193 const size_t lastColumn = e.jEnd_;
194 const auto idx = IndexFor(i, lastColumn);
195 if (matchScores_[idx] > maxScoreRight) {
196 maxScoreRight = matchScores_[idx];
197 maxCellRight = std::make_pair(i, lastColumn);
198 }
199 }
200 }
201
202 // find max score in last row
203 std::pair<size_t, size_t> maxCellBottom{maxIndex, maxIndex};
204 float maxScoreBottom = -FLT_MAX;
205 {
206 const size_t lastRow = maxIndex;
207 const auto& lookupElement = lookup_[lastRow];
208 for (size_t j = lookupElement.jBegin_; j < lookupElement.jEnd_; ++j) {
209 const auto idx = IndexFor(lastRow, j);
210 if (matchScores_[idx] > maxScoreBottom) {
211 maxScoreBottom = matchScores_[idx];
212 maxCellBottom = std::make_pair(lastRow, j);
213 }
214 }
215 }
216
217 return (maxScoreBottom > maxScoreRight ? maxCellBottom : maxCellRight);
218 }
219
220 size_t BandedGlobalAlignBlock::IndexFor(const size_t i, const size_t j) const
221 {
222 // if in matrix
223 if (i != std::string::npos && j != std::string::npos) {
224 const auto& e = lookup_[i];
225 // hand array index back to caller for (i,j) if in-band
226 if (j >= e.jBegin_ && j <= e.jEnd_) {
227 return e.arrayStart_ + (j - e.jBegin_);
228 }
229 }
230
231 // (i,j) either out of matrix bounds, or out-of-band
232 return std::string::npos;
233 }
234
235 void BandedGlobalAlignBlock::Init(const size_t tLen, const size_t qLen)
236 {
237 const auto numElements = InitLookup(tLen, qLen);
238 InitScores(tLen, qLen, numElements);
239 }
240
241 size_t BandedGlobalAlignBlock::InitLookup(const size_t tLen, const size_t qLen)
242 {
243 // ensure space
244 lookup_.clear();
245 lookup_.reserve(qLen + 1);
246
247 const auto t = static_cast<int64_t>(tLen);
248 const auto q = static_cast<int64_t>(qLen);
249 const auto k = static_cast<int64_t>(config_.bandExtend_);
250 assert(t >= q);
251
252 size_t arrayStart = 0;
253 int64_t jBegin = 0;
254 int64_t jEnd = 0;
255 for (int64_t i = 0; i < q + 1; ++i) {
256
257 // jBegin
258 jBegin = i - k;
259 if (jBegin < 0) {
260 jBegin = 0;
261 }
262
263 // jEnd
264 jEnd = i + k;
265 if (jEnd > t) {
266 jEnd = t;
267 }
268
269 // sanity checks
270 assert(jBegin >= 0);
271 assert(jEnd >= 0);
272 assert(jEnd >= jBegin);
273
274 // store lookup values
275 lookup_.emplace_back(arrayStart, static_cast<size_t>(jBegin), static_cast<size_t>(jEnd));
276
277 // update arrayStart for next row (or 'numElements' on exit)
278 const auto rowElements = static_cast<size_t>(jEnd - jBegin) + 1;
279 arrayStart += (rowElements);
280 }
281
282 return arrayStart;
283 }
284
285 void BandedGlobalAlignBlock::InitScores(const size_t tLen, const size_t qLen, const size_t n)
286 {
287 matchScores_.resize(n);
288 gapScores_.resize(n);
289
290 matchScores_[0] = 0;
291 gapScores_[0] = -FLT_MAX;
292
293 const auto maxQ = std::min(qLen, config_.bandExtend_);
294 const auto maxT = std::min(tLen, config_.bandExtend_);
295
296 for (size_t i = 1; i <= maxQ; ++i) {
297 const auto idx = IndexFor(i, 0);
298 matchScores_[idx] = -FLT_MAX;
299 gapScores_[idx] = config_.gapOpenPenalty_ + (i - 1) * config_.gapExtendPenalty_;
300 }
301
302 for (size_t j = 1; j <= maxT; ++j) {
303 const auto idx = IndexFor(0, j);
304 matchScores_[idx] = -FLT_MAX;
305 gapScores_[idx] = config_.gapOpenPenalty_ + (j - 1) * config_.gapExtendPenalty_;
306 }
307 }
308
309 // --------------------------
310 // StandardGlobalAlignBlock
311 // --------------------------
312
313 std::string StandardGlobalAlignBlock::Align(const char* target, const size_t tLen,
314 const char* query, const size_t qLen)
315 {
316 // Initialize space & scores
317 Init(tLen, qLen);
318
319 // Main loop
320 for (size_t i = 1; i <= qLen; ++i) {
321 for (size_t j = 1; j <= tLen; ++j) {
322 const auto s = score(target[j - 1], query[i - 1], config_);
323 matchScores_[i][j] =
324 (std::max(matchScores_[i - 1][j - 1], gapScores_[i - 1][j - 1]) + s);
325 gapScores_[i][j] = Utility::Max(matchScores_[i][j - 1] + config_.gapOpenPenalty_,
326 gapScores_[i][j - 1] + config_.gapExtendPenalty_,
327 matchScores_[i - 1][j] + config_.gapOpenPenalty_,
328 gapScores_[i - 1][j] + config_.gapExtendPenalty_);
329 }
330 }
331
332 // Traceback
333 const size_t MATCH_MATRIX = 1;
334 const size_t GAP_MATRIX = 2;
335
336 // find traceback start
337 const auto btStart = BacktraceStart(tLen, qLen);
338 size_t i = btStart.first;
339 size_t j = btStart.second;
340 size_t mat =
341 (matchScores_[btStart.first][btStart.second] >= gapScores_[btStart.first][btStart.second]
342 ? MATCH_MATRIX
343 : GAP_MATRIX);
344 size_t iPrev;
345 size_t jPrev;
346 size_t matPrev;
347
348 std::string result;
349
350 // if not beginning at bottom right, add corresponding indel
351 if (i < qLen) {
352 for (size_t k = qLen - i; k > 0; --k) {
353 addAlignmentOp(&result, 'I');
354 }
355 } else if (j < tLen) {
356 for (size_t k = tLen - j; k > 0; --k) {
357 addAlignmentOp(&result, 'D');
358 }
359 }
360
361 // traceback remaining sequence
362 while (i > 0 || j > 0) {
363
364 if (mat == MATCH_MATRIX) {
365 matPrev = (matchScores_[i - 1][j - 1] >= gapScores_[i - 1][j - 1] ? MATCH_MATRIX
366 : GAP_MATRIX);
367 iPrev = i - 1;
368 jPrev = j - 1;
369 const auto op = (query[iPrev] == target[jPrev] ? 'M' : 'R');
370 addAlignmentOp(&result, op);
371
372 } else {
373 assert(mat == GAP_MATRIX);
374
375 const std::array<float, 4> s{
376 {(j > 0 ? matchScores_[i][j - 1] + config_.gapOpenPenalty_ : -FLT_MAX),
377 (j > 0 ? gapScores_[i][j - 1] + config_.gapExtendPenalty_ : -FLT_MAX),
378 (i > 0 ? matchScores_[i - 1][j] + config_.gapOpenPenalty_ : -FLT_MAX),
379 (i > 0 ? gapScores_[i - 1][j] + config_.gapExtendPenalty_ : -FLT_MAX)}};
380 const auto argMax = std::distance(s.cbegin(), std::max_element(s.cbegin(), s.cend()));
381
382 matPrev = ((argMax == 0 || argMax == 2) ? MATCH_MATRIX : GAP_MATRIX);
383 if (argMax == 0 || argMax == 1) {
384 iPrev = i;
385 jPrev = j - 1;
386 addAlignmentOp(&result, 'D');
387 } else {
388 iPrev = i - 1;
389 jPrev = j;
390 addAlignmentOp(&result, 'I');
391 }
392 }
393
394 // step back one
395 i = iPrev;
396 j = jPrev;
397 mat = matPrev;
398 }
399
400 // reverse tanscript & return
401 std::reverse(result.begin(), result.end());
402 return result;
403 }
404
405 std::pair<size_t, size_t> StandardGlobalAlignBlock::BacktraceStart(const size_t tLen,
406 const size_t qLen) const
407 {
408 // NOTE: Finding backtrace start this way allows us to not penalize end-gaps.
409
410 // find max score in last column
411 std::pair<size_t, size_t> maxCellRight{qLen, tLen};
412 float maxScoreRight = -FLT_MAX;
413 const size_t lastColumn = tLen;
414 for (size_t i = 1; i <= qLen; ++i) {
415 if (matchScores_[i][lastColumn] > maxScoreRight) {
416 maxScoreRight = matchScores_[i][lastColumn];
417 maxCellRight = std::make_pair(i, lastColumn);
418 }
419 }
420
421 // find max score in last row
422 std::pair<size_t, size_t> maxCellBottom{qLen, tLen};
423 float maxScoreBottom = -FLT_MAX;
424 const size_t lastRow = qLen;
425 for (size_t j = 1; j <= tLen; ++j) {
426 if (matchScores_[lastRow][j] > maxScoreBottom) {
427 maxScoreBottom = matchScores_[lastRow][j];
428 maxCellBottom = std::make_pair(lastRow, j);
429 }
430 }
431
432 return (maxScoreBottom > maxScoreRight ? maxCellBottom : maxCellRight);
433 }
434
435 void StandardGlobalAlignBlock::Init(const size_t tLen, const size_t qLen)
436 {
437 // ensure space
438 matchScores_.resize(qLen + 1);
439 gapScores_.resize(qLen + 1);
440
441 assert(matchScores_.size() == qLen + 1);
442 assert(gapScores_.size() == qLen + 1);
443
444 for (size_t i = 0; i < qLen + 1; ++i) {
445 matchScores_[i].resize(tLen + 1);
446 gapScores_[i].resize(tLen + 1);
447 }
448
449 // fill out initial scores
450 matchScores_[0][0] = 0;
451 gapScores_[0][0] = -FLT_MAX;
452 for (size_t i = 1; i <= qLen; ++i) {
453 matchScores_[i][0] = -FLT_MAX;
454 gapScores_[i][0] = config_.gapOpenPenalty_ + (i - 1) * config_.gapExtendPenalty_;
455 }
456 for (size_t j = 1; j <= tLen; ++j) {
457 matchScores_[0][j] = -FLT_MAX;
458 gapScores_[0][j] = config_.gapOpenPenalty_ + (j - 1) * config_.gapExtendPenalty_;
459 }
460 }
461
462 // ------------------------
463 // BandedChainAlignerImpl
464 // ------------------------
465
466 static std::vector<Align::Seed>::const_iterator FirstAnchorSeed(
467 const std::vector<Align::Seed>& seeds, const size_t band)
468 {
469 return std::find_if(seeds.cbegin(), seeds.cend(), [band](const Align::Seed& seed) {
470 return seed.BeginPositionH() >= band && seed.BeginPositionV() >= band;
471 });
472 }
473
474 static std::vector<Align::Seed>::const_iterator LastAnchorSeed(
475 const std::vector<Align::Seed>& seeds, const size_t tLen, const size_t qLen, const size_t band)
476 {
477 return std::find_if(seeds.crbegin(), seeds.crend(),
478 [tLen, qLen, band](const Align::Seed& seed) {
479 return seed.EndPositionH() + band < tLen &&
480 seed.EndPositionV() + band < qLen;
481 })
482 .base(); // convert reverse_iterator -> iterator
483 }
484
485 BandedChainAlignerImpl::BandedChainAlignerImpl(const BandedChainAlignConfig& config)
486 : config_(config), gapBlock_(config), seedBlock_(config), gapBlockBeginH_(0), gapBlockBeginV_(0)
487 {}
488
489 BandedChainAlignment BandedChainAlignerImpl::Align(const char* target, const size_t targetLen,
490 const char* query, const size_t queryLen,
491 const std::vector<Align::Seed>& seeds)
492 {
493 // return empty alignment on empty seeds
494 if (seeds.empty()) {
495 return BandedChainAlignment{};
496 }
497
498 // reset state & store input sequence info
499 Initialize(target, targetLen, query, queryLen);
500
501 // step through merged seeds (all overlaps collapsed)
502 // 1 - align gap region before current seed, and then
503 // 2 - align current seed
504 const auto mergedSeeds = MergeSeeds(seeds);
505 const auto band = config_.bandExtend_;
506 auto it = FirstAnchorSeed(mergedSeeds, band);
507 const auto end = LastAnchorSeed(mergedSeeds, targetLen, queryLen, band);
508 for (; it != end; ++it) {
509 AlignGapBlock(*it);
510 AlignSeedBlock(*it);
511 }
512
513 // finally align last gap region after last seed & return result
514 AlignLastGapBlock();
515 return Result();
516 }
517
518 void BandedChainAlignerImpl::AlignGapBlock(const size_t hLength, const size_t vLength)
519 {
520 // do 'standard' DP align
521 auto transcript = gapBlock_.Align(sequences_.target + gapBlockBeginH_, hLength,
522 sequences_.query + gapBlockBeginV_, vLength);
523
524 // incorporate alignment into total result
525 StitchTranscripts(&globalTranscript_, std::move(transcript));
526 }
527
528 void BandedChainAlignerImpl::AlignGapBlock(const Align::Seed& nextSeed)
529 {
530 const size_t hLength = nextSeed.BeginPositionH() - gapBlockBeginH_;
531 const size_t vLength = nextSeed.BeginPositionV() - gapBlockBeginV_;
532 AlignGapBlock(hLength, vLength);
533 }
534
535 void BandedChainAlignerImpl::AlignLastGapBlock()
536 {
537 const size_t hLength = sequences_.targetLen - gapBlockBeginH_;
538 const size_t vLength = sequences_.queryLen - gapBlockBeginV_;
539 AlignGapBlock(hLength, vLength);
540 }
541
542 void BandedChainAlignerImpl::AlignSeedBlock(const Align::Seed& seed)
543 {
544 // do seed-guided, banded align
545 auto transcript = seedBlock_.Align(sequences_.target, sequences_.query, seed);
546
547 // incorporate alignment into total result
548 StitchTranscripts(&globalTranscript_, std::move(transcript));
549
550 // see if we ended with an indel, if so remove that and try re-aligning that
551 // portion in the next alignment phase
552 size_t hOffset = 0;
553 size_t vOffset = 0;
554 const auto& lastOp = globalTranscript_.back();
555 if (lastOp == 'D') {
556 while (globalTranscript_.back() == 'D') {
557 ++hOffset;
558 globalTranscript_.pop_back();
559 }
560 } else if (lastOp == 'I') {
561 while (globalTranscript_.back() == 'I') {
562 ++vOffset;
563 globalTranscript_.pop_back();
564 }
565 }
566
567 // update offsets for next alignment block
568 gapBlockBeginH_ = seed.EndPositionH() - hOffset;
569 gapBlockBeginV_ = seed.EndPositionV() - vOffset;
570 }
571
572 void BandedChainAlignerImpl::Initialize(const char* target, const size_t targetLen,
573 const char* query, const size_t queryLen)
574 {
575 globalTranscript_.clear();
576 globalScore_ = std::numeric_limits<int64_t>::min();
577 gapBlockBeginH_ = 0;
578 gapBlockBeginV_ = 0;
579
580 sequences_ = Sequences{target, targetLen, query, queryLen};
581 }
582
583 std::vector<Align::Seed> BandedChainAlignerImpl::MergeSeeds(const std::vector<Align::Seed>& seeds)
584 {
585 // no merging needed on empty or single-element containers
586 if (seeds.size() <= 1) {
587 return seeds;
588 }
589
590 // push first seed into output container
591 std::vector<Align::Seed> mergedSeeds;
592 mergedSeeds.reserve(seeds.size());
593 mergedSeeds.push_back(seeds.front());
594 auto currentSeed = mergedSeeds.begin();
595
596 // iterate over remaining seeds
597 auto inputIter = seeds.cbegin() + 1;
598 auto inputEnd = seeds.cend();
599 for (; inputIter != inputEnd; ++inputIter) {
600
601 // if input seed starts after current seed
602 if (inputIter->BeginPositionH() > currentSeed->EndPositionH() &&
603 inputIter->BeginPositionV() > currentSeed->EndPositionV()) {
604 mergedSeeds.push_back(*inputIter);
605 currentSeed = mergedSeeds.end() - 1;
606 }
607
608 // else contiguous or overlapping
609 else {
610 currentSeed->BeginPositionH(
611 std::min(inputIter->BeginPositionH(), currentSeed->BeginPositionH()));
612 currentSeed->EndPositionH(
613 std::max(inputIter->EndPositionH(), currentSeed->EndPositionH()));
614 currentSeed->BeginPositionV(
615 std::min(inputIter->BeginPositionV(), currentSeed->BeginPositionV()));
616 currentSeed->EndPositionV(
617 std::max(inputIter->EndPositionV(), currentSeed->EndPositionV()));
618 }
619 }
620 return mergedSeeds;
621 }
622
623 BandedChainAlignment BandedChainAlignerImpl::Result()
624 {
625 return BandedChainAlignment{config_, sequences_.target, sequences_.targetLen,
626 sequences_.query, sequences_.queryLen, globalTranscript_};
627 }
628
629 void BandedChainAlignerImpl::StitchTranscripts(std::string* global, std::string&& local)
630 {
631 assert(global);
632
633 // quick checks if either transcript is empty
634 if (local.empty()) {
635 return;
636 }
637 if (global->empty()) {
638 *global = std::move(local);
639 return;
640 }
641
642 global->reserve(global->size() + local.size());
643 *global += local;
644 }
645
646 } // namespace Internal
647
648 // ------------------------
649 // BandedChainAlignment
650 // ------------------------
651
652 BandedChainAlignment::BandedChainAlignment(const BandedChainAlignConfig& config, std::string target,
653 std::string query, const std::string& transcript)
654 : config_(config)
655 , target_{std::move(target)}
656 , query_{std::move(query)}
657 , transcript_{std::move(transcript)}
658 {
659 alignedTarget_.reserve(target_.size());
660 alignedQuery_.reserve(query_.size());
661
662 enum class TranscriptState : uint8_t
663 {
664 Match_Mismatch,
665 Insertion,
666 Deletion
667 };
668
669 score_ = 0;
670 TranscriptState state = TranscriptState::Match_Mismatch;
671 size_t tPos = 0;
672 size_t qPos = 0;
673 for (const auto& c : transcript_) {
674 switch (c) {
675 case 'M': {
676 // update aligned seqs
677 alignedQuery_.push_back(query_[qPos]);
678 ++qPos;
679 alignedTarget_.push_back(target_[tPos]);
680 ++tPos;
681
682 // update score & current state
683 score_ += config_.matchScore_;
684 state = TranscriptState::Match_Mismatch;
685 break;
686 }
687 case 'R': {
688 // update aligned seqs
689 alignedQuery_.push_back(query_[qPos]);
690 ++qPos;
691 alignedTarget_.push_back(target_[tPos]);
692 ++tPos;
693
694 // update score & current state
695 score_ += config_.mismatchPenalty_;
696 state = TranscriptState::Match_Mismatch;
697 break;
698 }
699 case 'I': {
700 // update aligned seqs
701 alignedQuery_.push_back(query_[qPos]);
702 ++qPos;
703 alignedTarget_.push_back('-');
704
705 // update score (do not penalize end gaps) & current state
706 if (tPos != 0 && tPos < target_.size()) {
707 if (state != TranscriptState::Insertion) {
708 score_ += config_.gapOpenPenalty_;
709 } else {
710 score_ += config_.gapExtendPenalty_;
711 }
712 }
713 state = TranscriptState::Insertion;
714 break;
715 }
716 case 'D': {
717 // update aligned seqs
718 alignedQuery_.push_back('-');
719 alignedTarget_.push_back(target_[tPos]);
720 ++tPos;
721
722 // update score (do not penalize end gaps) & current state
723 if (qPos != 0 && qPos < query_.size()) {
724 if (state != TranscriptState::Deletion) {
725 score_ += config_.gapOpenPenalty_;
726 } else {
727 score_ += config_.gapExtendPenalty_;
728 }
729 }
730 state = TranscriptState::Deletion;
731 break;
732 }
733 default:
734 throw std::runtime_error{
735 "[pbcopper] banded chain alignment ERROR: unknown transcript code: " +
736 std::string(1, c)};
737 }
738 }
739 }
740
741 BandedChainAlignment::BandedChainAlignment(const BandedChainAlignConfig& config, const char* target,
742 const size_t targetLen, const char* query,
743 const size_t queryLen, const std::string& transcript)
744 : BandedChainAlignment(config, std::string{target, targetLen}, std::string{query, queryLen},
745 transcript)
746 {}
747
748 float BandedChainAlignment::Identity() const
749 {
750 assert(alignedQuery_.length() == alignedTarget_.length());
751
752 size_t numMatches = 0;
753 const size_t len = alignedQuery_.length();
754 for (size_t i = 0; i < len; ++i) {
755 if (alignedQuery_[i] == alignedTarget_[i]) {
756 ++numMatches;
757 }
758 }
759 return (100.0F * static_cast<float>(numMatches) / len);
760 }
761
762 int64_t BandedChainAlignment::Score() const { return score_; }
763
764 // ------------------------
765 // BandedChainAlignConfig
766 // ------------------------
767
768 BandedChainAlignConfig BandedChainAlignConfig::Default()
769 {
770 // match, mismatch, gapOpen, gapExtend, band
771 return BandedChainAlignConfig{2.0F, -1.0F, -2.0F, -1.0F, 15};
772 }
773
774 // --------------------------
775 // alignment free functions
776 // --------------------------
777
778 BandedChainAlignment BandedChainAlign(const char* target, const size_t targetLen, const char* query,
779 const size_t queryLen, const std::vector<Align::Seed>& seeds,
780 const BandedChainAlignConfig& config)
781 {
782 Internal::BandedChainAlignerImpl impl{config};
783 return impl.Align(target, targetLen, query, queryLen, seeds);
784 }
785
786 BandedChainAlignment BandedChainAlign(const std::string& target, const std::string& query,
787 const std::vector<PacBio::Align::Seed>& seeds,
788 const BandedChainAlignConfig& config)
789 {
790 return BandedChainAlign(target.c_str(), target.size(), query.c_str(), query.size(), seeds,
791 config);
792 }
793
794 } // namespace Align
795 } // namespace PacBio