-
Notifications
You must be signed in to change notification settings - Fork 11
/
minimizer.h
1820 lines (1523 loc) · 64 KB
/
minimizer.h
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef GBWTGRAPH_MINIMIZER_H
#define GBWTGRAPH_MINIMIZER_H
#include <algorithm>
#include <cstdint>
#include <functional>
#include <iostream>
#include <limits>
#include <unordered_set>
#include <utility>
#include <type_traits>
#include <vector>
#include <gbwt/utils.h>
#include <gbwtgraph/io.h>
#include <gbwtgraph/utils.h>
/*
minimizer.h: Kmer indexes and minimizer indexes.
*/
namespace gbwtgraph
{
//------------------------------------------------------------------------------
/*
Kmer encoding using 2 bits per base in 64-bit integers. If two kmers have the
same length, comparing the integers or tuples of integers gives the same
result as lexicographic comparison of the kmers.
*/
struct KmerEncoding {
typedef std::uint64_t value_type;
// Conversion from characters to packed characters.
const static std::vector<unsigned char> CHAR_TO_PACK;
// Conversion from packed characters to upper-case characters.
const static std::vector<char> PACK_TO_CHAR;
// Masks for the bits used in the encoding. If kmer length is `k`,
// `LOW_MASK[k]` marks the bits that are in use in the least significant word
// of the encoding. `HIGH_MASK[k]` marks the bits that are in use in the
// penultimate word of the encoding.
const static std::vector<value_type> LOW_MASK;
const static std::vector<value_type> HIGH_MASK;
// Constants used in the encoding.
constexpr static size_t FIELD_BITS = sizeof(value_type) * gbwt::BYTE_BITS;
constexpr static size_t PACK_WIDTH = 2;
constexpr static size_t PACK_OVERFLOW = FIELD_BITS - PACK_WIDTH;
constexpr static size_t FIELD_CHARS = FIELD_BITS / PACK_WIDTH;
constexpr static value_type PACK_MASK = 0x3;
};
//------------------------------------------------------------------------------
/*
A graph position encoded as a 64-bit integer. Uses the lowest 10 bits for
node offset, limiting node length to 1024 bp. The next bit is used for node
orientation and the remaining bits for node id.
NOTE: This encoding must be consistent with the top-level MAX_NODE_LENGTH.
*/
struct Position
{
typedef std::uint64_t code_type;
code_type value;
// Constants that define the encoding.
constexpr static size_t OFFSET_BITS = 10;
constexpr static size_t ID_OFFSET = OFFSET_BITS + 1;
constexpr static code_type REV_MASK = static_cast<code_type>(1) << OFFSET_BITS;
constexpr static code_type OFF_MASK = REV_MASK - 1;
// This is not a constructor in order to have default constructors and operators in
// objects containing Position.
constexpr static Position create(code_type value) { return { value }; }
// Converts pos_t to Position.
static Position encode(pos_t pos)
{
return
{
(static_cast<code_type>(gbwtgraph::id(pos)) << ID_OFFSET) |
(static_cast<code_type>(gbwtgraph::is_rev(pos)) << OFFSET_BITS) |
(static_cast<code_type>(gbwtgraph::offset(pos)) & OFF_MASK)
};
}
// Basic comparisons.
bool operator==(Position another) const { return (this->value == another.value); }
bool operator!=(Position another) const { return (this->value != another.value); }
bool operator<(Position another) const { return (this->value < another.value); }
bool operator>(Position another) const { return (this->value > another.value); }
// Is the offset small enough to fit in the low-order bits of the encoding?
static bool valid_offset(const pos_t& pos) { return (gbwtgraph::offset(pos) <= OFF_MASK); }
// Returns the node identifier.
nid_t id() const { return this->value >> ID_OFFSET; }
// Returns the orientation.
bool is_rev() const { return this->value & REV_MASK; }
// Returns the node offset.
size_t offset() const { return this->value & OFF_MASK; }
// Decodes the position as pos_t.
pos_t decode() const { return make_pos_t(this->id(), this->is_rev(), this->offset()); }
// Returns an empty position corresponding to the unused 0 node.
// Allows using this as a value in a kmer index.
constexpr static Position no_value() { return { 0 }; }
};
// Arbitrary 128-bit payload for each graph position.
struct Payload
{
std::uint64_t first, second;
// This is not a constructor in order to have default constructors and operators in
// objects containing Payload.
constexpr static Payload create(std::uint64_t value)
{
return { value, 0 };
}
bool operator==(Payload another) const
{
return (this->first == another.first && this->second == another.second);
}
bool operator!=(Payload another) const
{
return !(*this == another);
}
bool operator<(Payload another) const
{
return (this->first < another.first) || (this->first == another.first && this->second < another.second);
}
// Returns an empty payload.
constexpr static Payload default_payload() { return { 0, 0 }; }
};
// A combination of a graph position and a payload.
struct PositionPayload
{
Position position;
Payload payload;
// Payload is irrelevant for comparisons.
bool operator==(const PositionPayload& another) const { return (this->position == another.position); }
bool operator!=(const PositionPayload& another) const { return (this->position != another.position); }
bool operator<(const PositionPayload& another) const { return (this->position < another.position); }
bool operator>(const PositionPayload& another) const { return (this->position > another.position); }
// Returns a pair consisting of an empty position and a default payload.
// Allows using this as a value in a kmer index.
constexpr static PositionPayload no_value() { return { Position::no_value(), Payload::default_payload() }; }
};
//------------------------------------------------------------------------------
/*
A kmer encoded using 2 bits/character in a 64-bit integer. The encoding is only
defined if all characters in the kmer are valid. The highest bit indicates
whether the corresponding value in the hash table is a position or a pointer.
*/
struct Key64
{
public:
// Internal representation.
typedef KmerEncoding::value_type code_type;
typedef code_type value_type;
code_type key;
// Empty key.
constexpr Key64() : key(EMPTY_KEY) {}
// No key, with 63 set bits.
constexpr static Key64 no_key() { return Key64(NO_KEY & KEY_MASK); }
// Implicit conversion.
constexpr Key64(code_type key) : key(key) {}
// Get a representation of the actual key.
value_type get_key() const { return (this->key & KEY_MASK); }
// Comparisons.
bool operator==(Key64 another) const { return (this->get_key() == another.get_key()); }
bool operator!=(Key64 another) const { return (this->get_key() != another.get_key()); }
bool operator<(Key64 another) const { return (this->get_key() < another.get_key()); }
// Is the corresponding value a pointer?
bool is_pointer() const { return (this->key & IS_POINTER); }
void clear_pointer() { this->key &= ~IS_POINTER; }
void set_pointer() { this->key |= IS_POINTER; }
// Hash of the key. Do not call this directly, as the index may use a derived
// hash function.
size_t hash() const { return wang_hash_64(this->key & KEY_MASK); }
// Move the kmer forward, with c as the next character. Update the key, assuming that
// it encodes the kmer in forward orientation.
void forward(size_t k, unsigned char c, size_t& valid_chars)
{
code_type packed = KmerEncoding::CHAR_TO_PACK[c];
if(packed > KmerEncoding::PACK_MASK) { this->key = EMPTY_KEY; valid_chars = 0; }
else
{
this->key = ((this->key << KmerEncoding::PACK_WIDTH) | packed) & KmerEncoding::LOW_MASK[k];
valid_chars++;
}
}
// Move the kmer forward, with c as the next character. Update the key, assuming that
// it encodes the kmer in reverse orientation.
void reverse(size_t k, unsigned char c)
{
code_type packed = KmerEncoding::CHAR_TO_PACK[c];
if(packed > KmerEncoding::PACK_MASK) { this->key = EMPTY_KEY; }
else
{
packed ^= KmerEncoding::PACK_MASK; // The complement of the base.
this->key = (packed << ((k - 1) * KmerEncoding::PACK_WIDTH)) | (this->key >> KmerEncoding::PACK_WIDTH);
}
}
/// Encode a string of size k to a key.
static Key64 encode(const std::string& sequence);
/// Decode the key back to a string, given the kmer size used.
std::string decode(size_t k) const;
/// Returns the packed character value for kmer[i].
code_type access_raw(size_t k, size_t i) const
{
size_t offset = (k - 1 - i) * KmerEncoding::PACK_WIDTH;
return (this->key >> offset) & KmerEncoding::PACK_MASK;
}
/// Returns kmer[i].
char access(size_t k, size_t i) const
{
return KmerEncoding::PACK_TO_CHAR[this->access_raw(k, i)];
}
/// Returns the reverse complement of the kmer.
Key64 reverse_complement(size_t k) const;
// Required numeric constants.
constexpr static std::size_t KEY_BITS = KmerEncoding::FIELD_BITS;
constexpr static std::size_t KMER_LENGTH = 29;
constexpr static std::size_t WINDOW_LENGTH = 11;
constexpr static std::size_t SMER_LENGTH = KMER_LENGTH - WINDOW_LENGTH;
constexpr static std::size_t KMER_MAX_LENGTH = 31;
private:
// Specific key values. Note that the highest bit is not a part of the key.
constexpr static code_type EMPTY_KEY = 0;
constexpr static code_type NO_KEY = std::numeric_limits<code_type>::max();
constexpr static code_type KEY_MASK = NO_KEY >> 1;
constexpr static code_type IS_POINTER = NO_KEY ^ KEY_MASK; // High bit.
};
// Required for printing keys.
std::ostream& operator<<(std::ostream& out, Key64 value);
//------------------------------------------------------------------------------
/*
A kmer encoded using 2 bits/character in a pair of 64-bit integers. The encoding is
only defined if all characters in the kmer are valid. The highest bit indicates
whether the corresponding value in the hash table is a position or a pointer.
*/
struct Key128
{
public:
// Internal representation.
typedef KmerEncoding::value_type code_type;
typedef std::pair<code_type, code_type> value_type;
code_type high, low;
// Empty key.
constexpr Key128() : high(EMPTY_KEY), low(EMPTY_KEY) {}
// No key, with 127 set bits.
constexpr static Key128 no_key() { return Key128(NO_KEY & KEY_MASK, NO_KEY); }
// Implicit conversion.
constexpr Key128(code_type key) : high(EMPTY_KEY), low(key) {}
// For testing.
constexpr Key128(code_type high, code_type low) : high(high), low(low) {}
// Get a representation of the actual key.
value_type get_key() const { return value_type(this->high & KEY_MASK, this->low); }
// Comparisons.
bool operator==(Key128 another) const { return (this->get_key() == another.get_key()); }
bool operator!=(Key128 another) const { return (this->get_key() != another.get_key()); }
bool operator<(Key128 another) const { return (this->get_key() < another.get_key()); }
// Is the corresponding value a pointer?
bool is_pointer() const { return (this->high & IS_POINTER); }
void clear_pointer() { this->high &= ~IS_POINTER; }
void set_pointer() { this->high |= IS_POINTER; }
// Hash of the key. Essentially boost::hash_combine. Do not call this directly,
// as the index may use a derived hash function.
size_t hash() const
{
size_t result = wang_hash_64(this->high & KEY_MASK);
result ^= wang_hash_64(this->low) + 0x9e3779b9 + (result << 6) + (result >> 2);
return result;
}
// Move the kmer forward, with c as the next character. Update the key, assuming that
// it encodes the kmer in forward orientation.
void forward(size_t k, unsigned char c, size_t& valid_chars)
{
code_type packed = KmerEncoding::CHAR_TO_PACK[c];
if(packed > KmerEncoding::PACK_MASK) { this->high = EMPTY_KEY; this->low = EMPTY_KEY; valid_chars = 0; }
else
{
this->high = ((this->high << KmerEncoding::PACK_WIDTH) | (this->low >> KmerEncoding::PACK_OVERFLOW)) & KmerEncoding::HIGH_MASK[k];
this->low = ((this->low << KmerEncoding::PACK_WIDTH) | packed) & KmerEncoding::LOW_MASK[k];
valid_chars++;
}
}
// Move the kmer forward, with c as the next character. Update the key, assuming that
// it encodes the kmer in reverse orientation.
void reverse(size_t k, unsigned char c)
{
code_type packed = KmerEncoding::CHAR_TO_PACK[c];
if(packed > KmerEncoding::PACK_MASK) { this->high = EMPTY_KEY; this->low = EMPTY_KEY; }
else
{
packed ^= KmerEncoding::PACK_MASK; // The complement of the base.
if(k > KmerEncoding::FIELD_CHARS)
{
this->low = ((this->high & KmerEncoding::PACK_MASK) << KmerEncoding::PACK_OVERFLOW) | (this->low >> KmerEncoding::PACK_WIDTH);
this->high = (packed << ((k - KmerEncoding::FIELD_CHARS - 1) * KmerEncoding::PACK_WIDTH)) | (this->high >> KmerEncoding::PACK_WIDTH);
}
else // The entire kmer is in the lower part of the key.
{
this->low = (packed << ((k - 1) * KmerEncoding::PACK_WIDTH)) | (this->low >> KmerEncoding::PACK_WIDTH);
}
}
}
/// Encode a string of size k to a key.
static Key128 encode(const std::string& sequence);
/// Decode the key back to a string, given the kmer size used.
std::string decode(size_t k) const;
/// Returns the packed character value for kmer[i].
code_type access_raw(size_t k, size_t i) const
{
size_t offset = (k - 1 - i) * KmerEncoding::PACK_WIDTH;
code_type shifted;
if(offset >= KmerEncoding::FIELD_BITS) { shifted = this->high >> (offset - KmerEncoding::FIELD_BITS); }
else { shifted = this->low >> offset; }
return shifted & KmerEncoding::PACK_MASK;
}
/// Returns kmer[i].
char access(size_t k, size_t i) const
{
return KmerEncoding::PACK_TO_CHAR[this->access_raw(k, i)];
}
/// Returns the reverse complement of the kmer.
Key128 reverse_complement(size_t k) const;
// Required numeric constants.
constexpr static std::size_t KEY_BITS = 2 * KmerEncoding::FIELD_BITS;
constexpr static std::size_t KMER_LENGTH = 39;
constexpr static std::size_t WINDOW_LENGTH = 15;
constexpr static std::size_t SMER_LENGTH = KMER_LENGTH - WINDOW_LENGTH;
constexpr static std::size_t KMER_MAX_LENGTH = 63;
private:
// Specific key values. Note that the highest bit is not a part of the key.
constexpr static code_type EMPTY_KEY = 0;
constexpr static code_type NO_KEY = std::numeric_limits<code_type>::max();
constexpr static code_type KEY_MASK = NO_KEY >> 1;
constexpr static code_type IS_POINTER = NO_KEY ^ KEY_MASK; // High bit.
};
// Required for printing keys.
std::ostream& operator<<(std::ostream& out, Key128 value);
//------------------------------------------------------------------------------
// Sequence offset in kmer extraction.
typedef std::uint32_t offset_type;
/*
The sequence offset of a kmer is the base that corresponds to the start of
the kmer. If the kmer is a reverse complement, that means the last base of
the substring covered by the kmer.
Values stored in a kmer index are graph positions for the start of the kmer
used as the key. The kmer always extends forward from the position. When a
kmer is in reverse orientation in the query sequence, the graph positions
from the index must be flipped with reverse_base_pos(). The last base of the
forward orientation of the query sequence covered by the kmer then matches
the flipped graph position.
*/
template<class KeyType>
struct Kmer
{
typedef KeyType key_type;
key_type key; // Encoded kmer.
size_t hash; // Hash of the kmer.
offset_type offset; // Sequence offset.
bool is_reverse; // The kmer is a reverse complement.
// Is the kmer empty?
bool empty() const { return (this->key == key_type::no_key()); }
// Sort by (offset, !is_reverse). When the offsets are equal, a reverse complement
// kmer is earlier in the sequence than a forward kmer.
bool operator<(const Kmer& another) const
{
return ((this->offset < another.offset) ||
(this->offset == another.offset && this->is_reverse > another.is_reverse));
}
bool operator==(const Kmer& another) const
{
return (this->key == another.key && this->offset == another.offset && this->is_reverse == another.is_reverse);
}
bool operator!=(const Kmer& another) const
{
return !(this->operator==(another));
}
};
template<class KeyType>
std::ostream&
operator<<(std::ostream& out, const Kmer<KeyType>& kmer)
{
out << "(" << kmer.key << ", " << (kmer.is_reverse ? "-" : "+") << kmer.offset << ")";
return out;
}
//------------------------------------------------------------------------------
class MinimizerHeader;
template<class KeyType, class ValueType>
class MinimizerIndex;
/*
This is a general-purpose kmer index parameterized with a key type and a value
type. The key can be either Key64 (64 bits, up to 31 bp) or Key128 (128 bits,
up to 63 bp), while the value can be either Position (graph position encoded
in 64 bits) or PositionPayload (a Position with 128 bits of arbitray payload).
The kmers are stored in a hash table of size 2^n that uses quadratic probing.
If a kmer is associated with a single value, it is stored directly within the
hash table. When there are multiple values, the hash table stores a pointer
to a sorted vector of values.
Limitations:
* The index does not support serialization.
* Any key not equal to KeyType::no_key() can be inserted into the index.
There are no guarantees that all kmers have the same length.
*/
template<class KeyType, class ValueType>
class KmerIndex
{
public:
typedef KeyType key_type;
typedef ValueType value_type;
// Public constants.
constexpr static size_t INITIAL_CAPACITY = 1024;
constexpr static double MAX_LOAD_FACTOR = 0.77;
union Values
{
value_type value;
std::vector<value_type>* pointer;
};
typedef std::pair<key_type, Values> cell_type;
constexpr static cell_type empty_cell() { return cell_type(key_type::no_key(), { value_type::no_value() }); }
// Returns the size of the smallest hash table that can hold this many keys.
static size_t minimum_size(size_t keys)
{
size_t bound = std::ceil(keys / MAX_LOAD_FACTOR);
size_t capacity = INITIAL_CAPACITY;
while(capacity < bound) { capacity *= 2; }
return capacity;
}
//------------------------------------------------------------------------------
/*
Constructors, destructors, and object handling.
*/
KmerIndex() :
keys(0), max_keys(INITIAL_CAPACITY * MAX_LOAD_FACTOR),
values(0), unique(0),
hash_table(INITIAL_CAPACITY, empty_cell()),
downweight(0), frequent_kmers()
{
}
// Hash table size must be a power of 2 and at least INITIAL_CAPACITY.
explicit KmerIndex(size_t hash_table_size) :
keys(0), values(0), unique(0),
downweight(0), frequent_kmers()
{
if(sdsl::bits::cnt(hash_table_size) != 1)
{
std::cerr << "KmerIndex::KmerIndex(): Hash table size (" << hash_table_size << ") must be a power of 2; reverting to " << INITIAL_CAPACITY << std::endl;
hash_table_size = INITIAL_CAPACITY;
}
if(hash_table_size < INITIAL_CAPACITY)
{
std::cerr << "KmerIndex::KmerIndex(): Hash table size (" << hash_table_size << ") is too small; reverting to " << INITIAL_CAPACITY << std::endl;
hash_table_size = INITIAL_CAPACITY;
}
this->max_keys = hash_table_size * MAX_LOAD_FACTOR;
this->hash_table = std::vector<cell_type>(hash_table_size, empty_cell());
}
KmerIndex(const KmerIndex& source)
{
this->copy(source);
}
KmerIndex(KmerIndex&& source)
{
*this = std::move(source);
}
~KmerIndex()
{
this->clear();
}
void swap(KmerIndex& another)
{
if(&another == this) { return; }
std::swap(this->keys, another.keys);
std::swap(this->max_keys, another.max_keys);
std::swap(this->values, another.values);
std::swap(this->unique, another.unique);
this->hash_table.swap(another.hash_table);
std::swap(this->downweight, another.downweight);
this->frequent_kmers.swap(another.frequent_kmers);
}
KmerIndex& operator=(const KmerIndex& source)
{
if(&source != this) { this->copy(source); }
return *this;
}
KmerIndex& operator=(KmerIndex&& source)
{
if(&source != this)
{
this->keys = std::move(source.keys);
this->max_keys = std::move(source.max_keys);
this->values = std::move(source.values);
this->unique = std::move(source.unique);
this->hash_table = std::move(source.hash_table);
this->downweight = std::move(source.downweight);
this->frequent_kmers = std::move(source.frequent_kmers);
}
return *this;
}
// For testing.
bool operator==(const KmerIndex& another) const
{
if(this->keys != another.keys) { return false; }
if(this->max_keys != another.max_keys) { return false; }
if(this->values != another.values) { return false; }
if(this->unique != another.unique) { return false; }
if(this->hash_table.size() != another.hash_table.size()) { return false; }
for(size_t i = 0; i < this->hash_table.size(); i++)
{
cell_type a = this->hash_table[i], b = another.hash_table[i];
if(a.first != b.first) { return false; }
if(a.first.is_pointer() != b.first.is_pointer()) { return false; }
if(a.first.is_pointer())
{
if(*(a.second.pointer) != *(b.second.pointer)) { return false; }
}
else
{
if(a.second.value != b.second.value) { return false; }
}
}
if(this->downweight != another.downweight) { return false; }
if(this->frequent_kmers != another.frequent_kmers) { return false; }
return true;
}
bool operator!=(const KmerIndex& another) const { return !(this->operator==(another)); }
//------------------------------------------------------------------------------
/*
Statistics and iteration.
*/
// Number of keys in the index.
size_t size() const { return this->keys; }
// Is the index empty?
bool empty() const { return (this->size() == 0); }
// Number of values (kmer occurrences) in the index.
size_t number_of_values() const { return this->values; }
// Size of the hash table.
size_t hash_table_size() const { return this->hash_table.size(); }
// Number of keys that can fit into the hash table. Exceeding it will initiate rehashing.
size_t capacity() const { return this->max_keys; }
// Current load factor of the hash table.
double load_factor() const { return static_cast<double>(this->size()) / static_cast<double>(this->hash_table_size()); }
// Number of kmers with a single occurrence.
size_t unique_keys() const { return this->unique; }
// Call `callback` for every non-empty hash table cell.
void for_each_kmer(const std::function<void(const cell_type&)>& callback) const
{
for(const cell_type& cell : this->hash_table)
{
if(cell.first != key_type::no_key()) { callback(cell); }
}
}
// Call `callback` for every non-empty hash table cell.
// If callback returns false, then stop iterating.
// Returns false if the iteration stopped early, true otherwise.
bool for_each_kmer(const std::function<bool(const cell_type&)>& callback) const
{
for(const cell_type& cell : this->hash_table)
{
if(cell.first != key_type::no_key())
{
if(!callback(cell))
{
return false;
}
}
}
return true;
}
//------------------------------------------------------------------------------
/*
Operations.
*/
/*
Inserts (key, value) into the index if it is not already there.
Does not insert keys equal to key_type::no_key() or values equal to
value_type::no_value().
*/
void insert(key_type key, value_type value)
{
this->insert(key, value, this->hash(key));
}
/*
Inserts (key, value) into the index if it is not already there using the given
hash value. Does not insert keys equal to key_type::no_key() or values equal
to value_type::no_value().
*/
void insert(key_type key, value_type value, size_t hash)
{
if(key == key_type::no_key() || value == value_type::no_value()) { return; }
size_t offset = this->find_offset(key, hash);
if(this->hash_table[offset].first == key_type::no_key())
{
this->insert_new(key, value, offset);
}
else if(this->hash_table[offset].first == key)
{
this->append(value, offset);
}
}
// Returns the occurrence count for the kmer.
size_t count(key_type key) const
{
return this->count(key, this->hash(key));
}
// Returns the occurrence count for the kmer with the given hash value.
size_t count(key_type key, size_t hash) const
{
if(key == key_type::no_key()) { return 0; }
size_t offset = this->find_offset(key, hash);
const cell_type& cell = this->hash_table[offset];
if(cell.first == key)
{
return (cell.first.is_pointer() ? cell.second.pointer->size() : 1);
}
return 0;
}
/*
Returns the sorted list of the occurrences for the given kmer and the
number of occurrences. Any insertions into the index may invalidate the
returned pointer.
*/
std::pair<const value_type*, size_t> find(key_type key) const
{
return this->find(key, this->hash(key));
}
/*
Returns the sorted list of the occurrences for the kmer with the given hash
value and the number of occurrences. Any insertions into the index may
invalidate the returned pointer.
*/
std::pair<const value_type*, size_t> find(key_type key, size_t hash) const
{
std::pair<const value_type*, size_t> result(nullptr, 0);
if(key == key_type::no_key()) { return result; }
size_t offset = this->find_offset(key, hash);
if(this->hash_table[offset].first == key)
{
const cell_type& cell = this->hash_table[offset];
if(cell.first.is_pointer())
{
result.first = cell.second.pointer->data();
result.second = cell.second.pointer->size();
}
else
{
result.first = &(cell.second.value); result.second = 1;
}
}
return result;
}
//------------------------------------------------------------------------------
/*
Internal implementation.
*/
private:
size_t keys, max_keys;
size_t values, unique;
std::vector<cell_type> hash_table;
// Downweight hashes for frequent kmers.
size_t downweight;
std::vector<key_type> frequent_kmers;
// Needed for serialization.
friend class MinimizerHeader;
friend class MinimizerIndex<KeyType, ValueType>;
void copy(const KmerIndex& source)
{
this->clear();
this->keys = source.keys;
this->max_keys = source.max_keys;
this->values = source.values;
this->unique = source.unique;
// First make a shallow copy and then copy the occurrence lists.
this->hash_table = source.hash_table;
for(cell_type& cell : this->hash_table)
{
if(cell.first.is_pointer())
{
cell.second.pointer = new std::vector<value_type>(*cell.second.pointer);
}
}
this->downweight = source.downweight;
this->frequent_kmers = source.frequent_kmers;
}
// Delete all pointers in the hash table.
void clear()
{
for(cell_type& cell : this->hash_table)
{
if(cell.first.is_pointer())
{
delete cell.second.pointer;
cell.second.value = value_type::no_value();
cell.first.clear_pointer();
}
}
}
// Find the hash table offset for the key with the given hash value.
size_t find_offset(key_type key, size_t hash) const
{
size_t offset = hash & (this->hash_table.size() - 1);
for(size_t attempt = 0; attempt < this->hash_table.size(); attempt++)
{
if(this->hash_table[offset].first == key_type::no_key() || this->hash_table[offset].first == key) { return offset; }
// Quadratic probing with triangular numbers.
offset = (offset + attempt + 1) & (this->hash_table.size() - 1);
}
// This should not happen.
std::cerr << "KmerIndex::find_offset(): Cannot find the offset for key " << key << std::endl;
assert(false);
return 0;
}
// Insert (key, value) into hash_table[offset], which is assumed to be empty.
// Rehashing may be necessary.
void insert_new(key_type key, value_type value, size_t offset)
{
this->hash_table[offset].first = key;
this->hash_table[offset].second.value = value;
this->keys++;
this->values++;
this->unique++;
if(this->size() > this->capacity()) { this->rehash(); }
}
// Add the value to the list of occurrences at hash_table[offset].
void append(value_type value, size_t offset)
{
if(this->contains(offset, value)) { return; }
cell_type& cell = this->hash_table[offset];
if(cell.first.is_pointer())
{
std::vector<value_type>* occs = cell.second.pointer;
occs->push_back(value);
size_t offset = occs->size() - 1;
while(offset > 0 && occs->at(offset - 1) > occs->at(offset))
{
std::swap(occs->at(offset - 1), occs->at(offset));
offset--;
}
}
else
{
std::vector<value_type>* occs = new std::vector<value_type>(2);
occs->at(0) = cell.second.value;
occs->at(1) = value;
if(occs->at(0) > occs->at(1)) { std::swap(occs->at(0), occs->at(1)); }
cell.second.pointer = occs;
cell.first.set_pointer();
this->unique--;
}
this->values++;
}
// Does the list of occurrences at hash_table[offset] contain the value?
bool contains(size_t offset, value_type value) const
{
const cell_type& cell = this->hash_table[offset];
if(cell.first.is_pointer())
{
const std::vector<value_type>* occs = cell.second.pointer;
return std::binary_search(occs->begin(), occs->end(), value);
}
else
{
return (cell.second.value == value);
}
}
// Get the hash value for the key. If downweighting is not in use, or
// the kmer is not frequent, the hash value reported by the key is used
// directly. Otherwise we downweight the hash value by the specified
// number of iterations.
size_t hash(key_type key) const
{
if(this->frequent_kmers.empty()) { return key.hash(); }
size_t h = key.hash();
size_t offset = h & (this->frequent_kmers.size() - 1);
for(size_t attempt = 0; attempt < this->frequent_kmers.size(); attempt++)
{
if(this->frequent_kmers[offset] == key_type::no_key()) { break; }
if(this->frequent_kmers[offset] == key)
{
h = std::numeric_limits<size_t>::max() - h;
for(size_t i = 0; i < this->downweight; i++)
{
h = h >> 32; h = h * h;
}
return std::numeric_limits<size_t>::max() - h;
}
// Quadratic probing with triangular numbers.
offset = (offset + attempt + 1) & (this->frequent_kmers.size() - 1);
}
return h;
}
// Double the size of the hash table.
void rehash()
{
// Reinitialize with a larger hash table.
std::vector<cell_type> old_hash_table(2 * this->hash_table.size(), empty_cell());
this->hash_table.swap(old_hash_table);
this->max_keys = this->hash_table.size() * MAX_LOAD_FACTOR;
// Move the keys to the new hash table.
for(size_t i = 0; i < old_hash_table.size(); i++)
{
const cell_type& source = old_hash_table[i];
if(source.first == key_type::no_key()) { continue; }
size_t offset = this->find_offset(source.first, this->hash(source.first));
this->hash_table[offset] = source;
}
}
// Inserts a key into the frequent kmers hash table.
void insert_frequent(key_type key)
{
size_t h = key.hash();
size_t offset = h & (this->frequent_kmers.size() - 1);
for(size_t attempt = 0; attempt < this->frequent_kmers.size(); attempt++)
{
if(this->frequent_kmers[offset] == key) { return; }
if(this->frequent_kmers[offset] == key_type::no_key())
{
this->frequent_kmers[offset] = key;
return;
}
// Quadratic probing with triangular numbers.
offset = (offset + attempt + 1) & (this->frequent_kmers.size() - 1);
}
// This should not happen.
std::cerr << "KmerIndex::insert_frequent(): Cannot find the offset for key " << key << std::endl;
assert(false);
}
};
//------------------------------------------------------------------------------
struct MinimizerHeader
{
std::uint32_t tag, version;
std::uint64_t k, w_or_s; // Minimizer parameters.
std::uint64_t keys; // Number of keys in the hash table.
std::uint64_t unused; // Currently unused.
std::uint64_t capacity; // Number of keys that can fit in the hash table without initiating rehashing.
std::uint64_t values; // Number of values in the index.
std::uint64_t unique; // Number of keys with a single value.
std::uint64_t flags;
constexpr static std::uint32_t TAG = 0x31513151;
constexpr static std::uint32_t VERSION = Version::MINIMIZER_VERSION;
constexpr static std::uint64_t FLAG_MASK = 0x0FFF;
constexpr static std::uint64_t FLAG_KEY_MASK = 0x00FF;
constexpr static size_t FLAG_KEY_OFFSET = 0;
constexpr static std::uint64_t FLAG_SYNCMERS = 0x0100;
constexpr static std::uint64_t FLAG_WEIGHT_MASK = 0x0E00;
constexpr static size_t FLAG_WEIGHT_OFFSET = 9;
// For older compatible versions.
constexpr static std::uint32_t V8_VERSION = 8;
constexpr static std::uint64_t V8_FLAG_MASK = 0x1FFF;