Debian Codegraph @

src/pbmer/DnaBit.cpp

raw
1 #include <pbcopper/pbmer/DnaBit.h>
2
3 #include <pbcopper/align/EdlibAlign.h>
4 #include <pbcopper/container/Unordered.h>
5 #include <pbcopper/pbmer/Parser.h>
6 #include <pbcopper/utility/Intrinsics.h> // PopCount
7 #include <pbcopper/utility/MinMax.h>
8
9 #include <array>
10 #include <iostream>
11 #include <limits>
12 #include <memory> // std::unique_ptr<[]>
13 #include <numeric>
14 #include <tuple>
15 #include <vector>
16
17 #include <cassert>
18 #include <cstdint>
19
20 namespace PacBio {
21 namespace Pbmer {
22
23 // all bits set to one for a uint64_t
24 constexpr uint64_t ALL_BITS_ON = std::numeric_limits<uint64_t>::max();
25
26 void DnaBit::SetBase(const char c, const int position)
27 {
28 assert(position >= 0);
29 assert(position < msize);
30
31 const uint64_t base = ASCII_TO_DNA[c];
32 const int step = position * 2;
33
34 mer = (mer & ~(0b11ULL << step)) | (base << step);
35 }
36
37 // use a lower and (implicit) upper bitmask to squeeze out a base.
38 void DnaBit::DeleteBase(const int position)
39 {
40 assert(position >= 0);
41 assert(position < msize);
42
43 // example position = 1 ─┐
44 // v
45 // 4 3 2 1 0
46 // mer: T C A T G
47 // binary: 11'01'00'11'10
48 //
49 // lowerBitMask: 00'00'00'00'11
50 //
51 // bases before position:
52 // (mer & lowerBitMask): 00'00'00'00'10 (lower)
53 //
54 // bases past position:
55 // (mer >> 2): 00'11'01'00'11
56 // (~lowerBitMask): 11'11'11'11'00
57 // bit-&: 00'11'01'00'00 (upper)
58 //
59 // 3 2 1 0
60 // lower | upper: 00'11'01'00'10
61 // T C A G
62 const uint64_t lowerBitMask{(1ull << (2 * position)) - 1};
63
64 mer = (mer & lowerBitMask) | ((mer >> 2) & (~lowerBitMask));
65 --msize;
66 }
67
68 void DnaBit::InsertBase(const char c, const int position)
69 {
70 assert(position >= 0);
71 assert(position <= msize);
72 assert(position < 32);
73
74 const uint64_t lowerBitMask{(1ull << (2 * position)) - 1};
75
76 mer = (mer & lowerBitMask) | ((mer & ~lowerBitMask) << 2);
77 ++msize;
78
79 SetBase(c, position);
80 }
81
82 // https://gist.github.com/badboy/6267743
83 // This is a multiplication method for hashing. Minimap2 uses this function, but
84 // this function does not mask, no constraining the bitrange.
85 uint64_t Hash64shift(uint64_t key)
86 {
87 key = (~key) + (key << 21); // key = (key << 21) - key - 1;
88 key = key ^ (key >> 24);
89 key = (key + (key << 3)) + (key << 8); // key * 265
90 key = key ^ (key >> 14);
91 key = (key + (key << 2)) + (key << 4); // key * 21
92 key = key ^ (key >> 28);
93 key = key + (key << 31);
94 return key;
95 }
96
97 uint64_t Mix64Masked(const uint64_t key, const uint8_t kmerSize) noexcept
98 {
99 uint64_t res = key;
100 res = (~res + (res << 21)) & ((1ull << 2 * kmerSize) - 1); // key = (key << 21) - key - 1;
101 res = res ^ (res >> 24);
102 res = ((res + (res << 3)) + (res << 8)) & ((1ull << 2 * kmerSize) - 1); // key * 265
103 res = res ^ (res >> 14);
104 res = ((res + (res << 2)) + (res << 4)) & ((1ull << 2 * kmerSize) - 1); // key * 21
105 res = res ^ (res >> 28);
106 res = (res + (res << 31)) & ((1ull << 2 * kmerSize) - 1);
107 return res;
108 }
109
110 // thanks to https://www.biostars.org/p/113640/ <- and a slight mod!
111 uint64_t ReverseComp64(const uint64_t mer, const uint8_t kmerSize)
112 {
113 assert((0 < kmerSize) && (kmerSize <= 32));
114
115 uint64_t res = ~mer;
116
117 res = ((res >> 2 & 0x3333333333333333) | (res & 0x3333333333333333) << 2);
118 res = ((res >> 4 & 0x0F0F0F0F0F0F0F0F) | (res & 0x0F0F0F0F0F0F0F0F) << 4);
119 res = ((res >> 8 & 0x00FF00FF00FF00FF) | (res & 0x00FF00FF00FF00FF) << 8);
120 res = ((res >> 16 & 0x0000FFFF0000FFFF) | (res & 0x0000FFFF0000FFFF) << 16);
121 res = ((res >> 32 & 0x00000000FFFFFFFF) | (res & 0x00000000FFFFFFFF) << 32);
122
123 return (res >> (2 * (32 - kmerSize)));
124 }
125
126 DnaBit::DnaBit() = default;
127
128 DnaBit::DnaBit(uint64_t k, uint8_t t, uint8_t i) : mer{k}, strand{t}, msize{i} {}
129
130 bool DnaBit::operator<(const DnaBit& b) const noexcept
131 {
132 return Mix64Masked(mer, msize) < Mix64Masked(b.mer, msize);
133 }
134
135 bool DnaBit::operator>(const DnaBit& b) const noexcept { return b < *this; }
136
137 bool DnaBit::operator>=(const DnaBit& b) const noexcept { return !(*this < b); }
138
139 bool DnaBit::operator<=(const DnaBit& b) const noexcept { return !(*this > b); }
140
141 bool DnaBit::operator==(const DnaBit& b) const noexcept
142 {
143 return std::tie(mer, strand) == std::tie(b.mer, b.strand);
144 }
145
146 bool DnaBit::operator!=(const DnaBit& b) const noexcept { return !(*this == b); }
147
148 void DnaBit::AppendBase(const uint8_t b)
149 {
150 mer = ((mer << 2) & (ALL_BITS_ON >> (64 - (2 * msize)))) | (b % 4);
151 }
152
153 void DnaBit::AppendBase(const char b)
154 {
155 mer = ((mer << 2) & (ALL_BITS_ON >> (64 - (2 * msize)))) | ASCII_TO_DNA[b];
156 }
157
158 void DnaBit::Bin2DnaBit(BI bin)
159 {
160 msize = static_cast<uint8_t>(bin >> 48);
161 strand = static_cast<uint8_t>(bin >> 56);
162 mer = static_cast<uint64_t>(bin >> 64);
163 }
164
165 BI DnaBit::DnaBit2Bin() const
166 {
167 BI rv = 0;
168 rv |= mer;
169 rv <<= 8;
170 rv |= strand;
171 rv <<= 8;
172 rv |= msize;
173 rv <<= 48;
174
175 return rv;
176 }
177
178 uint8_t DnaBit::FirstBaseIdx() const
179 {
180 return static_cast<uint8_t>(((mer >> ((2 * msize) - 2)) & 3));
181 }
182 uint8_t DnaBit::FirstBaseRCIdx() const { return 3 & ~LastBaseIdx(); }
183
184 uint8_t DnaBit::LastBaseIdx() const { return static_cast<uint8_t>(mer & 3); }
185
186 uint8_t DnaBit::LastBaseRCIdx() const { return 3 & ~FirstBaseIdx(); }
187
188 uint64_t DnaBit::HashedKmer() const { return Hash64shift(mer); }
189
190 uint64_t DnaBit::RCHashedKmer() const { return Mix64Masked(ReverseComp64(mer, msize), msize); }
191
192 std::string DnaBit::KmerToStr(void) const
193 {
194 std::string bases;
195 bases.resize(msize);
196
197 constexpr std::array<char, 4> LOOKUP_TABLE{'A', 'C', 'G', 'T'};
198 uint8_t i = 0;
199 uint64_t tmp = 0;
200 uint64_t offset = 0;
201
202 while (i < msize) {
203 tmp = mer;
204 offset = (msize - i - 1) * 2;
205 tmp >>= offset;
206 bases[i] = LOOKUP_TABLE[3ull & tmp];
207 ++i;
208 }
209
210 return bases;
211 }
212
213 DnaBit DnaBit::LexSmallerEq(void) const
214 {
215 DnaBit rc = *this;
216 rc.ReverseComp();
217 if (rc.mer <= mer) {
218 return rc;
219 }
220 return *this;
221 }
222
223 DnaBit DnaBit::LexSmallerEqHashed(void) const
224 {
225 DnaBit rc = *this;
226 rc.ReverseComp();
227 if (rc <= *this) {
228 return rc;
229 }
230 return *this;
231 }
232
233 uint64_t DnaBit::LexSmallerEq64() const
234 {
235 uint64_t rc = ReverseComp64(mer, msize);
236 if (rc < mer) {
237 return rc;
238 }
239 return mer;
240 }
241
242 uint64_t DnaBit::LexSmallerEq64Hashed() const
243 {
244 uint64_t rc = ReverseComp64(mer, msize);
245 if (Mix64Masked(rc, msize) <= Mix64Masked(mer, msize)) {
246 return rc;
247 }
248 return mer;
249 }
250
251 void DnaBit::MakeLexSmaller()
252 {
253 uint64_t rc = ReverseComp64(mer, msize);
254 if (rc <= mer) {
255 mer = rc;
256 strand = !strand;
257 }
258 }
259
260 void DnaBit::MakeLexSmallerHashed()
261 {
262 DnaBit test = *this;
263 test.ReverseComp();
264 if (test <= *this) {
265 *this = test;
266 }
267 }
268
269 uint8_t DnaBit::LongestDiNucRun() const
270 {
271 if (msize <= 1) {
272 return 0;
273 }
274 if (msize <= 3) {
275 return 1;
276 }
277
278 uint8_t runLength = 0;
279 uint8_t tmpRun = 1;
280
281 // four bit mask
282 constexpr uint8_t MASK = 0b1111;
283 uint8_t i = 0;
284 uint64_t tmp1 = 0;
285 uint64_t tmp2 = 0;
286 uint8_t upperBound = (msize * 2) - 4;
287
288 //first frame
289 while (i < upperBound) {
290 tmp1 = mer;
291 tmp2 = mer;
292
293 tmp1 = (tmp1 >> i);
294 tmp2 = (tmp2 >> (i + 4));
295
296 if ((tmp1 & MASK) == (tmp2 & MASK)) {
297 ++tmpRun;
298 if (tmpRun > runLength) {
299 runLength = tmpRun;
300 }
301 } else {
302 tmpRun = 1;
303 }
304 i += 4;
305 }
306
307 tmpRun = 1;
308
309 //second frame
310 while (i < upperBound) {
311 tmp1 = (mer >> 2);
312 tmp2 = (mer >> 2);
313
314 tmp1 = (tmp1 >> i);
315 tmp2 = (tmp2 >> (i + 4));
316
317 if ((tmp1 & MASK) == (tmp2 & MASK)) {
318 ++tmpRun;
319 if (tmpRun > runLength) {
320 runLength = tmpRun;
321 }
322 } else {
323 tmpRun = 1;
324 }
325 i += 4;
326 }
327
328 return runLength;
329 }
330
331 void DnaBit::PrependBase(const uint8_t b)
332 {
333 mer = (uint64_t(b % 4) << 2 * (msize - 1)) | (mer >> 2);
334 }
335
336 void DnaBit::PrependBase(const char b)
337 {
338 assert(msize > 0);
339 mer = (uint64_t(ASCII_TO_DNA[b]) << 2 * (msize - 1)) | (mer >> 2);
340 }
341
342 void DnaBit::ReverseComp(void)
343 {
344 mer = ReverseComp64(mer, msize);
345 strand = !strand;
346 }
347
348 std::string DnaBitVec2String(const std::vector<DnaBit>& bits)
349 {
350
351 std::string rv;
352 if (bits.empty()) {
353 return rv;
354 }
355 rv = bits.front().KmerToStr();
356 if (bits.size() == 1) {
357 return rv;
358 }
359 const uint8_t lastStrand = bits.front().strand;
360 for (size_t i = 1; i < bits.size(); ++i) {
361 DnaBit d = bits[i];
362 if (d.strand != lastStrand) {
363 d.ReverseComp();
364 }
365 if (!d.KmerToStr().empty()) {
366 rv += d.KmerToStr().back();
367 }
368 }
369 return rv;
370 }
371
372 std::vector<DnaBit> DnaBit::Neighbors() const
373 {
374 std::vector<DnaBit> results;
375 results.reserve(4 * msize);
376 Container::UnorderedSet<uint64_t> seen;
377
378 for (int i = 0; i < msize; ++i) {
379 for (int j = 0; j < 4; ++j) {
380 DnaBit currentMer = *this;
381 currentMer.SetBase(j, i);
382 const auto insertResult = seen.insert(currentMer.mer);
383 if (insertResult.second) {
384 results.emplace_back(currentMer);
385 }
386 }
387 }
388 return results;
389 }
390 uint64_t DnaBit::BitMask() const noexcept { return uint64_t(-1) >> (64 - 2 * msize); }
391
392 int DnaBit::HammingDistance(const DnaBit other) const noexcept
393 {
394 if (other.msize != msize) {
395 return -1;
396 }
397 // You can speed this up a bit by caching the bitmask
398 // and anding it with 0x5555555555555555,
399 // but that requires storing in memory.
400 // I would hope that the compiler can do this for us. - DB
401 uint64_t x0 = ~(mer ^ other.mer);
402 // Now we want to find bit pairs of 0 in x ^ y
403 uint64_t x1 = (x0 >> 1);
404 uint64_t x2 = x1 & (0x5555555555555555);
405 return msize - Utility::PopCount(x0 & x2 & BitMask());
406 }
407
408 int HammingDistance(const uint64_t x, const uint64_t y, int k) noexcept
409 {
410 const uint64_t bitMask = (uint64_t(0x5555555555555555) >> (2 * k));
411 const uint64_t x0 = ~(x ^ y);
412 return k - Utility::PopCount(x0 & (x0 >> 1) & bitMask);
413 }
414
415 int DnaBit::EditDistance(const DnaBit other) const noexcept
416 {
417 #if 0
418 // This edit distance code seems to be slightly off.
419 // We have to pay a little cost to convert the DnaBits to std::strings
420 // but then we have the
421 const int m = msize, n = other.msize;
422 auto scratch = std::make_unique<int8_t[]>((n + 1) * 2);
423 int8_t* row1 = scratch.get();
424 int8_t* row2 = row1 + n + 1;
425 std::iota(row1, row1 + n + 1, 0);
426 for (int i = 0; i < m; ++i) {
427 row2[i] = i + 1;
428 const int leftHandValue = (mer >> (i * 2)) & 3;
429 for (int j = 0; j < n; ++j) {
430 const int rightHandValue = (other.mer >> (j * 2)) & 3;
431 const int deleteCost = row1[j + 1] + 1;
432 const int insertionCost = row2[j] + 1;
433 const int substitutionCost = row1[j] + (rightHandValue != leftHandValue);
434 row2[j + 1] = Utility::Min(deleteCost, insertionCost, substitutionCost);
435 }
436 std::swap(row1, row2);
437 }
438 return row1[msize];
439 #else
440 const std::string myStr = KmerToStr();
441 const std::string oStr = other.KmerToStr();
442 EdlibAlignConfig conf{int(std::max(oStr.size(), myStr.size())), EDLIB_MODE_NW,
443 EDLIB_TASK_DISTANCE, nullptr, 0};
444 return Align::EdlibAlign(myStr, oStr, conf).Data.editDistance;
445 #endif
446 }
447
448 } // namespace Pbmer
449 } // namespace PacBio