-
Notifications
You must be signed in to change notification settings - Fork 0
/
KmerHash.cpp
111 lines (105 loc) · 2.83 KB
/
KmerHash.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "KmerHash.h"
#include <stdexcept>
#include <algorithm>
unsigned long KmerHash::hash(const std::string &kmer) {
unsigned long hashValue = 0;
for (char nucleotide : kmer) {
hashValue <<= 2;
switch (nucleotide) {
case 'A':
hashValue |= 0;
break;
case 'C':
hashValue |= 1;
break;
case 'G':
hashValue |= 2;
break;
case 'T':
hashValue |= 3;
break;
default:
throw std::invalid_argument("Invalid nucleotide character in k-mer");
}
}
return hashValue;
}
std::string KmerHash::reverseHash(unsigned long hashValue, int kmerLength) {
std::string kmer(kmerLength, 'A');
for (int i = kmerLength - 1; i >= 0; --i) {
switch (hashValue & 3) {
case 0:
kmer[i] = 'A';
break;
case 1:
kmer[i] = 'C';
break;
case 2:
kmer[i] = 'G';
break;
case 3:
kmer[i] = 'T';
break;
}
hashValue >>= 2;
}
return kmer;
}
unsigned long KmerHash::kmerToBits(const std::string &kmer) {
unsigned long bits = 0;
for (char nucleotide : kmer) {
bits <<= 2;
switch (nucleotide) {
case 'A':
bits |= 0;
break;
case 'C':
bits |= 1;
break;
case 'G':
bits |= 2;
break;
case 'T':
bits |= 3;
break;
default:
throw std::invalid_argument("Invalid nucleotide character in k-mer");
}
}
return bits;
}
std::string KmerHash::bitsToKmer(unsigned long bits, int kmerLength) {
std::string kmer(kmerLength, 'A');
for (int i = kmerLength - 1; i >= 0; --i) {
switch (bits & 3) {
case 0:
kmer[i] = 'A';
break;
case 1:
kmer[i] = 'C';
break;
case 2:
kmer[i] = 'G';
break;
case 3:
kmer[i] = 'T';
break;
}
bits >>= 2;
}
return kmer;
}
unsigned long KmerHash::reverseComplementBits(unsigned long bits, int kmerLength) {
unsigned long revComp = 0;
for (int i = 0; i < kmerLength; ++i) {
revComp <<= 2;
revComp |= (~bits & 3);
bits >>= 2;
}
return revComp;
}
std::string KmerHash::reverseComplement(const std::string &kmer) {
unsigned long bits = kmerToBits(kmer);
unsigned long revCompBits = reverseComplementBits(bits, kmer.size());
return bitsToKmer(revCompBits, kmer.size());
}