Debian Codegraph @

src/algorithm/KMerIndex.cpp

raw
1 #include <pbcopper/algorithm/KMerIndex.h>
2
3 #include <pbcopper/container/Unordered.h>
4 #include <pbcopper/utility/Intrinsics.h>
5 #include <pbcopper/utility/Random.h>
6
7 #include <iomanip>
8 #include <numeric>
9 #include <random>
10
11 #include <cinttypes>
12 #include <climits>
13
14 namespace PacBio {
15
16 namespace Algorithm {
17
18 std::vector<SubMerSelection> GenerateContiguous(const int k, const int subK)
19 {
20 if (subK > k) {
21 throw std::invalid_argument(
22 "[pbcopper] generate contiguous submers ERROR: subK must be <= k");
23 }
24 const uint64_t completePattern = (1ull << k) - 1;
25 const int diff = k - subK;
26 const uint64_t subPattern = completePattern >> diff;
27 std::vector<SubMerSelection> ret;
28 ret.reserve(diff + 1);
29 for (int i = 0; i < diff + 1; ++i) {
30 ret.emplace_back(k, subPattern << i);
31 }
32 return ret;
33 }
34
35 std::vector<SubMerSelection> GenerateRandomSubsequences(const int k, const int subK,
36 int64_t numSequences, uint64_t seed)
37 {
38 seed = std::mt19937_64(seed)();
39 if (numSequences > MaxNumSpacings(k, subK)) {
40 throw std::invalid_argument(
41 std::string(
42 "[pbcopper] kmer index ERROR: Cannot generate random subsequences with k = ") +
43 std::to_string(k) + " and subK = " + std::to_string(subK) + " and make " +
44 std::to_string(numSequences));
45 }
46 if (numSequences == 0) {
47 numSequences = std::max(int64_t((1LL << (k - subK)) / 20 * 5), int64_t(1));
48 }
49 Container::UnorderedSet<uint64_t> keys;
50 const uint64_t randomValueMask = (uint64_t(1) << k) - 1;
51 for (;;) {
52 //This RNG is not as fast as possible, uses rejection sampling.
53 //And we randomly generate bit-strings until we have
54 uint64_t randomValue = Utility::WyHash64Step(seed);
55 uint64_t rmask = randomValue & randomValueMask;
56 auto popCount = Utility::PopCount(rmask);
57 if (popCount != subK) {
58 // if the number of 1s is wrong, flip. Otherwise we'll have to generate more numbers.
59 rmask = ~randomValue & randomValueMask;
60 popCount = Utility::PopCount(rmask);
61 }
62 if (popCount == subK && keys.find(rmask) == keys.end()) {
63 keys.emplace(rmask);
64 if (Utility::Ssize(keys) >= numSequences) {
65 break;
66 }
67 }
68 }
69 std::vector<SubMerSelection> ret;
70 std::transform(keys.begin(), keys.end(), std::back_inserter(ret),
71 [k](const uint64_t x) { return SubMerSelection(k, x); });
72 return ret;
73 }
74
75 SubMerSelection FlatSubMer(const int k, const int subK)
76 {
77 if (subK > k) {
78 throw std::invalid_argument(
79 std::string("[pbcopper] kmer index ERROR: FlatSubMer expects subK to be >= k. k = ") +
80 std::to_string(k) + ", subk = " + std::to_string(subK));
81 }
82 return {k, (uint64_t(1) << subK) - 1};
83 }
84
85 uint64_t SubMerSelection::SelectSubseq(uint64_t kmer) const noexcept { return kmer & pattern_; }
86
87 uint64_t SubMerSelection::SelectSubseq(uint64_t kmer, int position) const noexcept
88 {
89 const int bitshift = position * 2;
90 return (kmer & (pattern_ << bitshift)) >> bitshift;
91 }
92
93 int SubMerSelection::NumberOfKernels(int k) const noexcept { return k - KernelWidth() + 1; }
94
95 int SubMerSelection::KernelWidth() const noexcept
96 {
97 const int lastSetPos = (sizeof(pattern_) * CHAR_BIT - Utility::CountLeadingZeros(pattern_));
98 const int firstSetPos = Utility::CountTrailingZeros(pattern_);
99 return (lastSetPos - firstSetPos) / 2;
100 }
101
102 SubMerSelection& SubMerSelection::Normalize() noexcept
103 {
104 pattern_ >>= Utility::CountTrailingZeros(pattern_);
105 return *this;
106 }
107
108 uint64_t SubMerSelection::HashedSubseq(uint64_t kmer) const noexcept
109 {
110 return WangHash(SelectSubseq(kmer));
111 }
112
113 uint64_t SubMerSelection::Subseq(uint64_t kmer) const noexcept { return SelectSubseq(kmer); }
114
115 uint64_t SubMerSelection::HashedSubseq(uint64_t kmer, int pos) const noexcept
116 {
117 return WangHash(SelectSubseq(kmer, pos));
118 }
119
120 std::string SubMerSelection::ToString() const
121 {
122 constexpr size_t BUFFER_SIZE = 128;
123
124 std::string ret(BUFFER_SIZE, '\0');
125 const int rc = std::snprintf(ret.data(), BUFFER_SIZE, "%" PRIu64 "\n", pattern_);
126 ret.resize(rc);
127 for (uint64_t cv = pattern_; cv;) {
128 const int ind = Utility::CountTrailingZeros(cv);
129 int kmerIndex = ind >> 1;
130 ret += "Pos";
131 ret += std::to_string(kmerIndex);
132 ret += ';';
133 cv ^= (3ull << ind);
134 }
135 return ret;
136 }
137
138 uint64_t SubMerSelection::MakePattern(uint64_t bitPattern) noexcept
139 {
140 uint64_t ret = 0;
141 for (int i = 0; i < 32; ++i) {
142 if ((bitPattern >> i) & 1) {
143 ret |= 0x3ull << (i * 2);
144 }
145 }
146 return ret;
147 }
148
149 int SubMerSelection::PopCount() const noexcept { return Utility::PopCount(pattern_) >> 1; }
150
151 SubMerSelection::SubMerSelection(int k, uint64_t bitPattern) : pattern_(MakePattern(bitPattern))
152 {
153 if (k > 32) {
154 throw std::invalid_argument(
155 std::string("[pbcopper] submer selection ERROR: k must be <= 32;") + std::to_string(k) +
156 " is invalid.");
157 }
158 if (const int popCount = PopCount(); popCount > k || popCount <= 0) {
159 throw std::invalid_argument(
160 std::string("[pbcopper] kmer index ERROR: Invalid bitPattern: PopCount of ") +
161 std::to_string(popCount) + " out of range");
162 }
163 }
164
165 SubMerSelection::operator uint64_t() const noexcept { return this->pattern_; }
166
167 SubMerSelection::SubMerSelection(uint64_t x) noexcept : pattern_(x) {}
168
169 bool SubMerSelection::operator<(const SubMerSelection o) const noexcept
170 {
171 // Higher-weight, longer-kernel, and lower bit value, in that order,
172 // define lexicographic order
173 // We then iterate in order from most specific to least specific
174 // This way, k-mers occurring earlier in the string as considered less
175 const int myPopCount = PopCount();
176 const int otherPopCount = o.PopCount();
177 const int myKernelWidth = KernelWidth();
178 const int otherKernelWidth = KernelWidth();
179 const uint64_t myInvertedN = uint64_t(-1) - *this;
180 const uint64_t otherInvertedN = uint64_t(-1) - o;
181 return std::tie(myPopCount, myKernelWidth, myInvertedN) >
182 std::tie(otherPopCount, otherKernelWidth, otherInvertedN);
183 }
184
185 bool SubMerSelection::operator==(const SubMerSelection o) const noexcept
186 {
187 return pattern_ == o.pattern_;
188 }
189
190 void BottomKKmerQ::Update(uint64_t item) noexcept
191 {
192 if (const std::ptrdiff_t osize = Utility::Ssize(*this); osize < nitems_) {
193 return Super::push(item);
194 }
195 if (item < Super::top()) {
196 Super::pop();
197 Super::push(item);
198 }
199 }
200
201 std::vector<uint64_t>&& BottomKKmerQ::ToVec() noexcept { return std::move(this->c); }
202
203 void BottomKKmerQ::Sort() noexcept { std::sort(this->c.begin(), this->c.end()); }
204
205 std::vector<uint64_t>&& BottomKKmerQ::ToSortedVec() noexcept
206 {
207 Sort();
208 return ToVec();
209 }
210
211 BottomKKmerQ::BottomKKmerQ(int nitems) : nitems_(nitems) { this->c.reserve(nitems); }
212
213 long double MaxNumSpacings(int superK, int subK) noexcept
214 {
215 long double frac = 1L;
216 for (int i = subK; i < superK; ++i) {
217 frac *= i;
218 }
219 for (int i = 1; i < (superK - subK); ++i) {
220 frac /= i;
221 }
222 return std::max(std::floor(frac), 1.L);
223 }
224
225 } // namespace Algorithm
226 } // namespace PacBio