Debian Codegraph @

src/align/ChainSeeds.cpp

raw
1 #include <pbcopper/align/ChainSeeds.h>
2
3 #include <algorithm>
4 #include <limits>
5 #include <tuple>
6
7 namespace PacBio {
8 namespace Align {
9
10 SDPHit::SDPHit(const Seed& seed, const size_t index) : Seed{seed}, Index{index} {}
11
12 bool SDPHit::operator<(const SDPHit& other) const noexcept { return DiagonalCompare(*this, other); }
13
14 SDPColumn::SDPColumn(size_t column, const std::optional<SDPHit> seed) : Seed{seed}, Column{column}
15 {}
16
17 bool SDPColumn::operator<(const SDPColumn& other) const noexcept { return Column < other.Column; }
18
19 bool ChainHitCompare::operator()(const ChainHit& lhs, const ChainHit& rhs) const noexcept
20 {
21 return lhs.score > rhs.score;
22 }
23
24 long Diagonal(const Seed& seed)
25 {
26 const auto v = seed.BeginPositionV();
27 const auto h = seed.BeginPositionH();
28
29 if (v > h) {
30 return -static_cast<long>(v - h);
31 }
32
33 return static_cast<long>(h - v);
34 }
35
36 bool HVCompare(const Seed& lhs, const Seed& rhs)
37 {
38 const auto leftH = lhs.BeginPositionH();
39 const auto rightH = rhs.BeginPositionH();
40
41 if (leftH < rightH) {
42 return true;
43 }
44
45 if (leftH == rightH) {
46 return lhs.EndPositionV() < rhs.EndPositionV();
47 }
48
49 return false;
50 }
51
52 bool VHCompare(const Seed& lhs, const Seed& rhs)
53 {
54 const auto leftV = lhs.BeginPositionV();
55 const auto rightV = rhs.BeginPositionV();
56
57 if (leftV < rightV) {
58 return true;
59 }
60
61 if (leftV == rightV) {
62 return lhs.EndPositionH() < rhs.EndPositionH();
63 }
64
65 return false;
66 }
67
68 bool DiagonalCompare(const Seed& lhs, const Seed& rhs) noexcept
69 {
70 return std::make_tuple(lhs.BeginDiagonal(), lhs.BeginPositionH()) <
71 std::make_tuple(rhs.BeginDiagonal(), rhs.BeginPositionH());
72 }
73
74 long LinkScore(const Seed& lhs, const Seed& rhs, const ChainSeedsConfig& config)
75 {
76 const auto lH = static_cast<long>(lhs.BeginPositionH());
77 const auto lV = static_cast<long>(lhs.BeginPositionV());
78 const auto rH = static_cast<long>(rhs.BeginPositionH());
79 const auto rV = static_cast<long>(rhs.BeginPositionV());
80 const auto k = std::min(static_cast<long>(lhs.Size()), static_cast<long>(rhs.Size()));
81 const auto fwd = std::min(lH - rH, lV - rV);
82
83 // matchReward = # of anchor bases * matchScore;
84 const auto matches = k - std::max(0l, k - fwd);
85 const auto matchReward = matches * config.matchScore;
86
87 // nonMatchPenalty = # of non-anchor, on-diagonal bases * nonMatchPenalty
88 const auto nonMatches = fwd - matches;
89 const auto nonMatchScorePenalty = nonMatches * config.nonMatchPenalty;
90
91 // Ignore any linkage over a certain size, no matter the score
92 if (nonMatches > config.maxSeedGap) {
93 return -1;
94 }
95
96 // indelPenalty = difference in the seed diagonals * indelScore
97 const auto diagL = lhs.Diagonal();
98 const auto diagR = rhs.Diagonal();
99 const auto drift = diagL - diagR;
100 long indelScorePenalty = 0;
101 if (drift > 0) {
102 indelScorePenalty = drift * config.insertionPenalty;
103 } else if (drift < 0) {
104 indelScorePenalty = -drift * config.deletionPenalty;
105 }
106
107 return matchReward + indelScorePenalty + nonMatchScorePenalty;
108 }
109
110 bool IndexCompare(const SDPHit& lhs, const SDPHit& rhs) { return lhs.Index < rhs.Index; }
111
112 std::vector<std::optional<SDPHit>> ComputeVisibilityLeft(const std::vector<SDPHit>& seeds,
113 std::set<SDPHit>& sweepSet)
114 {
115 std::vector<std::optional<SDPHit>> visible(seeds.size()); // Output
116
117 auto toRemove = seeds.begin();
118 for (auto it = seeds.begin(); it != seeds.end();) {
119 const auto col = (*it).BeginPositionH();
120 const auto start = it;
121
122 // Advance the iterator to the end of the current column in our
123 // column-sorted vector of seeds
124 for (; it != seeds.end() && col == (*it).BeginPositionH(); ++it) {
125 // For each seed, record in the output vector, record the first
126 // seed after it in the sweepSet (if any). Since the sweepSet
127 // only contains seeds from previous columns and is sorted by
128 // their diagonals, this means the seeds found in this way will
129 // all (A) Start to the left and (B) Start on a higher diagonal
130 auto succ = sweepSet.upper_bound(*it);
131 if (succ != sweepSet.end()) {
132 visible[it->Index] = *succ;
133 }
134 }
135
136 // Add all seeds to the sweepSet that start in the current column
137 sweepSet.insert(start, it);
138
139 // Remove all seeds from the sweepSet that end before the current column
140 for (; toRemove != seeds.end() && (*toRemove).EndPositionH() < col; ++toRemove) {
141 sweepSet.erase(*toRemove);
142 }
143 }
144
145 // clear the sweepSet after use
146 sweepSet.clear();
147
148 return visible;
149 }
150
151 void InitializeSeedsAndScores(const Seeds& seedSet, std::vector<SDPHit>* seeds,
152 std::vector<long>* scores)
153 {
154 size_t i = 0;
155 for (const auto& seed : seedSet) {
156 seeds->push_back(SDPHit(seed, i));
157 (*scores)[i] = seed.Size();
158 ++i;
159 }
160 }
161
162 void ChainSeedsImpl(
163 std::priority_queue<ChainHit, std::vector<ChainHit>, ChainHitCompare>* chainHits,
164 std::vector<std::optional<size_t>>* chainPred, std::vector<SDPHit>* seeds,
165 std::vector<long>& scores, const size_t seedSetIdx, const ChainSeedsConfig& config)
166 {
167 // compute visibility left, requires H-sorted seeds
168 std::set<SDPHit> sweepSet;
169 sort(seeds->begin(), seeds->end(), HVCompare);
170 auto visible = ComputeVisibilityLeft(*seeds, sweepSet);
171
172 // compute the visibility above, requires V-sorted seeds
173 sort(seeds->begin(), seeds->end(), VHCompare);
174 auto toRemove = seeds->begin();
175 std::set<SDPColumn> colSet;
176
177 auto zScore = [&scores](const SDPHit& seed) {
178 return scores[seed.Index] + seed.BeginPositionH() + seed.BeginPositionV();
179 };
180
181 for (auto it = seeds->begin(); it != seeds->end();) {
182 const size_t row = (*it).BeginPositionV();
183 const auto start = it;
184
185 for (; it != seeds->end() && row == (*it).BeginPositionV(); ++it) {
186 long bestScore = -std::numeric_limits<long>::max();
187 std::optional<SDPHit> bestSeed;
188
189 // find the previous column and best fragment from it
190 {
191 SDPColumn col((*it).BeginPositionH());
192 auto pred = colSet.lower_bound(col);
193
194 if (pred != colSet.begin()) {
195 pred = prev(pred);
196 long s = scores[pred->Seed->Index] + LinkScore(*it, *(pred->Seed), config);
197
198 if (s > bestScore) {
199 bestScore = s;
200 bestSeed = pred->Seed;
201 }
202 }
203 }
204
205 // search visible fragments (above)
206 {
207 auto visa = sweepSet.lower_bound(*it);
208
209 if (visa != sweepSet.begin()) {
210 visa = prev(visa);
211 long s = scores[visa->Index] + LinkScore(*it, *visa, config);
212
213 if (s > bestScore) {
214 bestScore = s;
215 bestSeed = *visa;
216 }
217 }
218 }
219
220 // search visible fragments (left)
221 if (auto visl = visible[it->Index]) {
222 long s = scores[visl->Index] + LinkScore(*it, *visl, config);
223
224 if (s > bestScore) {
225 bestScore = s;
226 bestSeed = visl;
227 }
228 }
229
230 if (bestSeed && bestScore >= config.minScore) {
231 scores[it->Index] = bestScore;
232 (*chainPred)[it->Index] = bestSeed->Index;
233
234 if (chainHits->size() < config.numCandidates) {
235 chainHits->push({seedSetIdx, it->Index, bestScore});
236 } else if (bestScore > chainHits->top().score) {
237 chainHits->pop();
238 chainHits->push({seedSetIdx, it->Index, bestScore});
239 }
240 } else if (scores[it->Index] >= config.minScore) {
241 // PLEASE NOTE: these have already been done at creation time
242 // scores[it->Index] = seedSize(*it);
243 // chainPred[it->Index] = std::nullopt;
244 //
245
246 if (chainHits->size() < config.numCandidates) {
247 chainHits->push({seedSetIdx, it->Index, bestScore});
248 } else if (bestScore > chainHits->top().score) {
249 chainHits->pop();
250 chainHits->push({seedSetIdx, it->Index, bestScore});
251 }
252 }
253 }
254
255 sweepSet.insert(start, it);
256
257 // remove all seeds from the sweepSet with end position less than the current row,
258 // and ensure the colSet invariant is kept:
259 // that all columns greater than our current
260 for (; toRemove != seeds->end() && (*toRemove).EndPositionV() < row; ++toRemove) {
261 SDPColumn col((*toRemove).EndPositionH(), std::make_optional(*toRemove));
262
263 auto myIt = colSet.find(col);
264
265 // update the column if it doesn't exist
266 // or if its score is less than the fragment we're removing from consideration
267 if (myIt == colSet.end() || zScore(*(myIt->Seed)) < zScore(*toRemove)) {
268 // insert the updated column, get successor
269 myIt = std::next(colSet.insert(col).first);
270
271 // keep removing columns long as the scores are less than
272 while (myIt != colSet.end() && zScore(*(myIt->Seed)) < zScore(*toRemove)) {
273 myIt = colSet.erase(myIt);
274 }
275 }
276
277 sweepSet.erase(*toRemove);
278 }
279 }
280
281 // seeds need to be sorted by Index to ... index into it properly
282 std::sort(seeds->begin(), seeds->end(), IndexCompare);
283 }
284
285 std::vector<std::vector<Seed>> ChainSeeds(const Seeds& seedSet, const ChainSeedsConfig& config)
286 {
287 // Initialize the work-horse vectors we will actually work with
288 std::priority_queue<ChainHit, std::vector<ChainHit>, ChainHitCompare> chainHits;
289 std::vector<std::optional<size_t>> chainPred(seedSet.size());
290 std::vector<SDPHit> seeds;
291 std::vector<long> scores(seedSet.size(), 0L);
292 InitializeSeedsAndScores(seedSet, &seeds, &scores);
293
294 // Call the main function
295 ChainSeedsImpl(&chainHits, &chainPred, &seeds, scores, 0, config);
296
297 // Empty and resize the result vector
298 std::vector<std::vector<Seed>> chains;
299 chains.resize(chainHits.size());
300
301 // Pop our results from our queue and convert them into Seed Chains / Sets
302 int i = chainHits.size() - 1;
303 while (!chainHits.empty()) {
304 const auto hit = chainHits.top();
305 //std::cout << "b(" << hit.reference << ", " << hit.endIndex << ", " << hit.score << ')' << std::endl;
306
307 // While there are additional links in the chain, append them
308 std::optional<size_t> chainEnd = hit.endIndex;
309 while (chainEnd) {
310 chains[i].push_back(seeds[*chainEnd]);
311 chainEnd = chainPred[*chainEnd];
312 }
313
314 // We appended seeds back-to-front, so reverse the current order in place
315 std::reverse(chains[i].begin(), chains[i].end());
316
317 chainHits.pop();
318 --i;
319 }
320
321 return chains;
322 }
323
324 std::vector<Seeds> ChainedSeedSets(const Seeds& seedSet, const ChainSeedsConfig& config)
325 {
326 // Initialize the work-horse vectors we will actually work with
327 std::priority_queue<ChainHit, std::vector<ChainHit>, ChainHitCompare> chainHits;
328 std::vector<std::optional<size_t>> chainPred(seedSet.size());
329 std::vector<SDPHit> seeds;
330 std::vector<long> scores(seedSet.size(), 0L);
331 InitializeSeedsAndScores(seedSet, &seeds, &scores);
332
333 // Call the main function
334 ChainSeedsImpl(&chainHits, &chainPred, &seeds, scores, 0, config);
335
336 // Empty and resize the result vector
337 std::vector<Seeds> chains;
338 chains.resize(chainHits.size());
339
340 // Pop our results from our queue and convert them into Seed Chains / Sets
341 int i = chainHits.size() - 1;
342 while (!chainHits.empty()) {
343 const auto hit = chainHits.top();
344
345 // While there are additional links in the chain, append them
346 std::optional<size_t> chainEnd = hit.endIndex;
347 while (chainEnd) {
348 auto seed = seeds[*chainEnd];
349 chains[i].AddSeed(seed);
350 chainEnd = chainPred[*chainEnd];
351 }
352
353 chainHits.pop();
354 --i;
355 }
356 return chains;
357 }
358
359 std::vector<std::pair<size_t, Seeds>> ChainSeeds(const std::map<size_t, Seeds> seedSets,
360 const ChainSeedsConfig config)
361 {
362 // The queue will accumulat results across SeedSets
363 std::priority_queue<ChainHit, std::vector<ChainHit>, ChainHitCompare> chainHits;
364
365 // Our vectors of seeds and chain-links need to persist for eventual
366 // use reconstructing our chains, so we initialize them as
367 // vectors-of-vectors here, 1 per seedSet we will analyze
368 size_t numSeedSets = seedSets.size();
369 std::vector<std::vector<std::optional<size_t>>> chainPred(numSeedSets);
370 std::vector<std::vector<SDPHit>> seeds(numSeedSets);
371
372 // We also need to record which seedSet came from which reference
373 std::vector<size_t> references(numSeedSets);
374
375 // Iterate over the multiple SeedSets once to search for chains
376 int i = 0;
377 for (auto it = seedSets.begin(); it != seedSets.end(); ++it, ++i) {
378 // Extract the contents of our K/V pair
379 references[i] = it->first;
380 const auto& seedSet = it->second;
381
382 // Initialize the work-horse vectors we will actually work with
383 chainPred[i] = std::vector<std::optional<size_t>>(seedSet.size());
384 std::vector<long> scores(seedSet.size(), 0L);
385 InitializeSeedsAndScores(seedSet, &seeds[i], &scores);
386
387 // Call the main function on the current seedSet
388 ChainSeedsImpl(&chainHits, &chainPred[i], &seeds[i], scores, i, config);
389 }
390
391 // Empty and resize the result vector
392 std::vector<std::pair<size_t, Seeds>> chains;
393 chains.resize(chainHits.size());
394
395 // Pop our results from our queue and convert them into Seed Chains / Sets
396 int j = chainHits.size() - 1;
397 while (!chainHits.empty()) {
398 // Take our next hit and extract the relevant indices ...
399 const auto hit = chainHits.top();
400 chains[j].first = references[hit.seedSetIdx];
401
402 // While there are additional links in the chain, append them
403 std::optional<size_t> chainEnd = hit.endIndex;
404 while (chainEnd) {
405 auto seed = seeds[hit.seedSetIdx][*chainEnd];
406 chains[j].second.AddSeed(seed);
407 chainEnd = chainPred[hit.seedSetIdx][*chainEnd];
408 }
409
410 chainHits.pop();
411 --j;
412 }
413
414 return chains;
415 }
416
417 } // namespace Align
418 } // namespace PacBio