-
Notifications
You must be signed in to change notification settings - Fork 19
/
concurrenthash.hpp
1525 lines (1374 loc) · 69.3 KB
/
concurrenthash.hpp
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
/*===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
*/
#ifndef _Concurrent_Hash_
#define _Concurrent_Hash_
#include <functional> // std::bind
#include "Integer.hpp"
#include "common_util.hpp"
// This file contains classes which facilitate basic operation of storing reads, counting kmers,
// and creating and traversing a de Bruijn graph
using namespace std;
namespace DeBruijn {
template<int BlockSize> // in bytes
class CConcurrentBlockedBloomFilter {
public:
enum EInsertResult {eNewKmer = 0, eAboveThresholdKmer = 1, eExistingKmer = 2};
// table_size - number of counting elements in bloom filter
// counter_bit_size - number of bith per counter (2, 4, 8)
// hash_num - number of has functions (generated from two)
CConcurrentBlockedBloomFilter(size_t table_size, int counter_bit_size, int hash_num, int min_count) {
Reset(table_size, counter_bit_size, hash_num, min_count);
}
void Reset(size_t table_size, int counter_bit_size, int hash_num, int min_count) {
assert(counter_bit_size <= 8);
m_counter_bit_size = counter_bit_size;
m_hash_num = hash_num;
m_max_element = (1 << m_counter_bit_size) - 1;
m_min_count = min(min_count, m_max_element);
m_elements_in_block = 8*BlockSize/m_counter_bit_size;
m_blocks = ceil((double)table_size/m_elements_in_block);
m_table_size = m_blocks*m_elements_in_block;
m_count_table.clear();
m_status.clear();
m_count_table.resize(m_blocks);
m_status.resize(m_blocks);
}
EInsertResult Insert(size_t hashp, size_t hashm) {
size_t ind = hashp%m_blocks;
auto& block = m_count_table[ind];
if(Test(hashp, hashm) >= m_min_count)
return eExistingKmer;
while(!m_status[ind].Set(1));
int count = Test(hashp, hashm);
if(count >= m_min_count) {
m_status[ind] = 0;
return eExistingKmer;
}
for(int h = 1; h < m_hash_num; ++h) {
hashp += hashm;
size_t pos = (hashp&(m_elements_in_block-1))*m_counter_bit_size; // bit position of the counting element in block
auto& cell = block.m_data[pos >> m_bits_in_cell_log];
int shift = pos&(m_bits_in_cell-1);
int cnt = (cell >> shift)&m_max_element;
if(cnt <= count)
cell += ((TCell)1 << shift);
}
m_status[ind] = 0;
if(count == 0)
return eNewKmer;
else if(count == m_min_count-1)
return eAboveThresholdKmer;
else
return eExistingKmer;
}
int Test(size_t hashp, size_t hashm) const {
auto& block = m_count_table[hashp%m_blocks];
int count = m_max_element;
for(int h = 1; h < m_hash_num; ++h) {
hashp += hashm;
size_t pos = (hashp&(m_elements_in_block-1))*m_counter_bit_size; // bit position of the counting element in block
auto& cell = block.m_data[pos >> m_bits_in_cell_log];
int shift = pos&(m_bits_in_cell-1);
int cnt = (cell >> shift)&m_max_element;
if(cnt < count)
count = cnt;
}
return count;
}
int MaxElement() const { return m_max_element; }
int HashNum() const { return m_hash_num; }
size_t TableSize() const { return m_table_size; } // number of counters
size_t TableFootPrint() const { return (sizeof(SBloomBlock)+1)*m_count_table.size(); } // bytes
int MinCount() const { return m_min_count; }
void Save(ostream& out) const {
out.write(reinterpret_cast<const char*>(&m_table_size), sizeof m_table_size);
out.write(reinterpret_cast<const char*>(&m_counter_bit_size), sizeof m_counter_bit_size);
out.write(reinterpret_cast<const char*>(&m_hash_num), sizeof m_hash_num);
out.write(reinterpret_cast<const char*>(&m_min_count), sizeof m_min_count);
out.write(reinterpret_cast<const char*>(&m_count_table[0]), m_blocks*(sizeof m_count_table[0]));
if(!out)
throw runtime_error("Error in CConcurrentBlockedBloomFilter write");
}
CConcurrentBlockedBloomFilter(istream& in) {
size_t table_size;
int counter_bit_size;
int hash_num;
int min_count;
if(!in.read(reinterpret_cast<char*>(&table_size), sizeof table_size))
throw runtime_error("Error in CConcurrentBlockedBloomFilter read");
if(!in.read(reinterpret_cast<char*>(&counter_bit_size), sizeof counter_bit_size))
throw runtime_error("Error in CConcurrentBlockedBloomFilter read");
if(!in.read(reinterpret_cast<char*>(&hash_num), sizeof hash_num))
throw runtime_error("Error in CConcurrentBlockedBloomFilter read");
if(!in.read(reinterpret_cast<char*>(&min_count), sizeof min_count))
throw runtime_error("Error in CConcurrentBlockedBloomFilter read");
Reset(table_size, counter_bit_size, hash_num, min_count);
if(!in.read(reinterpret_cast<char*>(&m_count_table[0]), m_blocks*(sizeof m_count_table[0])))
throw runtime_error("Error in CConcurrentBlockedBloomFilter read");
}
private:
typedef uint64_t TCell;
struct alignas(64) SBloomBlock {
SBloomBlock() { memset(m_data.data(), 0, BlockSize); }
array<TCell, BlockSize/sizeof(TCell)> m_data;
};
vector<SBloomBlock> m_count_table;
vector<SAtomic<uint8_t>> m_status;
size_t m_elements_in_block;
size_t m_blocks;
size_t m_table_size;
int m_counter_bit_size;
int m_hash_num;
int m_min_count;
int m_max_element;
int m_bits_in_cell = 8*sizeof(TCell);
int m_bits_in_cell_log = log2(m_bits_in_cell)+0.5; //log(m_bits_in_cell)/log(2);
};
typedef CConcurrentBlockedBloomFilter<128> TConcurrentBlockedBloomFilter;
// minimalistic multithread safe forward list
// allows reading and inserts in the beginning
// reading thread will not see new entries inserted after reading started
template <typename E>
class CForwardList {
public:
struct SNode {
E m_data = E();
SNode* m_next = nullptr;
};
template<bool is_const>
class iterator : public std::iterator<forward_iterator_tag, E> {
public:
template <bool flag, class IsTrue, class IsFalse> struct choose;
template <class IsTrue, class IsFalse> struct choose<true, IsTrue, IsFalse> { typedef IsTrue type; };
template <class IsTrue, class IsFalse> struct choose<false, IsTrue, IsFalse> { typedef IsFalse type; };
typedef typename choose<is_const, const E&, E&>::type reference;
typedef typename choose<is_const, const E*, E*>::type pointer;
typedef typename choose<is_const, const SNode*, SNode*>::type node_pointer;
iterator(SNode* node = nullptr) : m_node(node) {};
iterator& operator++() {
m_node = m_node->m_next;
return *this;
}
reference& operator*() { return m_node->m_data; }
pointer operator->() { return &m_node->m_data; }
node_pointer NodePointer() { return m_node; }
bool operator!=(const iterator& i) const { return i.m_node != m_node; }
private:
friend class CForwardList;
SNode* m_node;
};
iterator<false> begin() { return iterator<false>(m_head.load()); }
iterator<false> end() { return iterator<false>(); }
iterator<true> begin() const { return iterator<true>(m_head.load()); }
iterator<true> end() const { return iterator<true>(); }
CForwardList() { m_head.store(nullptr); }
// not mutithread safe
CForwardList& operator=(const CForwardList& other) {
Clear();
for(auto it = other.begin(); it != other.end(); ++it)
PushFront(*it);
return *this;
}
CForwardList(const CForwardList& other) {
m_head.store(nullptr);
for(auto it = other.begin(); it != other.end(); ++it)
PushFront(*it);
}
~CForwardList() { Clear(); }
E& front() { return m_head.load()->m_data; }
SNode* Head() const { return m_head; }
SNode* NewNode(const E& e) {
SNode* p = new SNode;
p->m_data = e;
p->m_next = m_head;
return p;
}
SNode* NewNode() {
SNode* p = new SNode;
p->m_next = m_head;
return p;
}
bool TryPushFront(SNode* nodep) { return m_head.compare_exchange_strong(nodep->m_next, nodep); }
E* Emplace() {
SNode* p = NewNode();
while (!m_head.compare_exchange_strong(p->m_next, p));
return &(p->m_data);
}
void PushFront(const E& e) {
SNode* p = NewNode(e);
while (!m_head.compare_exchange_strong(p->m_next, p));
}
// not mutithread safe
template <typename P> void remove_if(const P& prob) {
while(m_head.load() != nullptr && prob(m_head.load()->m_data)) {
SNode* p = m_head;
m_head = p->m_next;
delete p;
}
for(SNode* p = m_head; p != nullptr; ) {
SNode* after = p->m_next;
if(after != nullptr && prob(after->m_data)) {
p->m_next = after->m_next;
delete after;
} else {
p = p->m_next;
}
}
}
void Save(ostream& os) const {
size_t vsize = sizeof(E);
os.write(reinterpret_cast<const char*>(&vsize), sizeof vsize);
size_t elements = distance(begin(), end());
os.write(reinterpret_cast<const char*>(&elements), sizeof elements);
for(auto& elem : *this)
os.write(reinterpret_cast<const char*>(&elem), sizeof elem);
if(!os)
throw runtime_error("Error in CForwardList write");
}
void Load(istream& is) {
Clear();
size_t vsize;
if(!is.read(reinterpret_cast<char*>(&vsize), sizeof vsize))
throw runtime_error("Error in CForwardList read");
if(vsize != sizeof(E))
throw runtime_error("Wrong format for CForwardList load");
size_t elements;
if(!is.read(reinterpret_cast<char*>(&elements), sizeof elements))
throw runtime_error("Error in CForwardList read");
for( ; elements > 0; --elements) {
E* p = Emplace();
if(!is.read(reinterpret_cast<char*>(p), sizeof *p))
throw runtime_error("Error in CForwardList read");
}
}
void Clear() {
for(SNode* p = m_head; p != nullptr; ) {
auto tmp = p->m_next;
delete p;
p = tmp;
}
m_head.store(nullptr);
}
void Init() { m_head.store(nullptr); }
private:
atomic<SNode*> m_head;
};
// minimalistic deque-type container allowing multithread initialization of a large hash_table
template <typename E>
class CDeque {
public:
typedef E value_type;
CDeque(size_t size = 0) : m_chunks(1) {
m_data.resize(m_chunks);
Reset(size, m_chunks);
}
~CDeque() {
if(m_chunks > 1) {
list<function<void()>> jobs;
for(unsigned chunk = 0; chunk < m_chunks; ++chunk)
jobs.push_back(bind(&CDeque::ReleaseChunk, this, chunk));
RunThreads(m_chunks, jobs);
}
}
E& operator[](size_t index) { return m_data[index/m_chunk_size][index%m_chunk_size]; }
const E& operator[](size_t index) const { return m_data[index/m_chunk_size][index%m_chunk_size]; }
size_t Size() const { return m_size; }
void Reset(size_t size, size_t chunks) {
m_chunks = chunks;
m_data.resize(m_chunks);
m_size = size;
m_chunk_size = (size+m_chunks-1)/m_chunks;
if(m_chunks == 1) {
ResetChunk(0, m_chunk_size);
} else {
list<function<void()>> jobs;
for(unsigned chunk = 0; chunk < m_chunks; ++chunk) {
size_t chunk_size = min(m_chunk_size, size);
jobs.push_back(bind(&CDeque::ResetChunk, this, chunk, chunk_size));
size -= min(m_chunk_size, size);
}
RunThreads(m_chunks, jobs);
}
}
void Swap(CDeque& other) {
swap(m_chunks, other.m_chunks);
swap(m_size, other.m_size);
swap(m_chunk_size, other.m_chunk_size);
swap(m_data, other.m_data);
}
void Save(ostream& os) const {
size_t vsize = sizeof(E);
os.write(reinterpret_cast<const char*>(&vsize), sizeof vsize);
os.write(reinterpret_cast<const char*>(&m_chunks), sizeof m_chunks);
os.write(reinterpret_cast<const char*>(&m_size), sizeof m_size);
os.write(reinterpret_cast<const char*>(&m_chunk_size), sizeof m_chunk_size);
for(auto& chunk : m_data) {
size_t num = chunk.size();
os.write(reinterpret_cast<const char*>(&num), sizeof num);
os.write(reinterpret_cast<const char*>(chunk.data()), num*vsize);
}
if(!os)
throw runtime_error("Error in CDeque write");
}
void Load(istream& is) {
size_t vsize;
if(!is.read(reinterpret_cast<char*>(&vsize), sizeof vsize))
throw runtime_error("Error in CDeque read");
if(vsize != sizeof(E))
throw runtime_error("Wrong format for CDeque load");
if(!is.read(reinterpret_cast<char*>(&m_chunks), sizeof m_chunks))
throw runtime_error("Error in CDeque read");
if(!is.read(reinterpret_cast<char*>(&m_size), sizeof m_size))
throw runtime_error("Error in CDeque read");
if(!is.read(reinterpret_cast<char*>(&m_chunk_size), sizeof m_chunk_size))
throw runtime_error("Error in CDeque read");
m_data.clear();
m_data.resize(m_chunks);
for(auto& chunk : m_data) {
size_t num;
if(!is.read(reinterpret_cast<char*>(&num), sizeof num))
throw runtime_error("Error in CDeque read");
chunk.resize(num);
if(!is.read(reinterpret_cast<char*>(chunk.data()), num*vsize))
throw runtime_error("Error in CDeque read");
}
}
private:
void ResetChunk(size_t chunk, size_t chunk_size) {
m_data[chunk].clear();
m_data[chunk].resize(chunk_size);
}
void ReleaseChunk(size_t chunk) { vector<E>().swap(m_data[chunk]); }
size_t m_chunks = 0;
size_t m_size = 0;
size_t m_chunk_size = 0;
vector<vector<E>> m_data;
};
// BucketBlock <= 32
// Moderate value of BucketBlock will improve memory cache use
// Larger values will reduce the number of entries in the spillover lists but eventually will increase the search time
// 0 (all entries in the lists) is permitted and could be used for reduction of the table size for large sizeof(V)
template<class Key, class V, int BucketBlock>
struct SHashBlock {
static_assert(BucketBlock <= 32, "");
typedef Key large_t;
typedef V mapped_t;
typedef pair<large_t,V> element_t;
typedef CForwardList<element_t> list_t;
typedef typename list_t::SNode snode_t;
enum States : uint64_t {eAssigned = 1, eKeyExists = 2};
enum { eBucketBlock = BucketBlock };
SHashBlock() : m_status(0) {}
SHashBlock(const SHashBlock& other) : m_data(other.m_data), m_extra(other.m_extra), m_status(other.m_status.load()) {} // used for table initialisation only
SHashBlock& operator=(const SHashBlock& other) {
m_data = other.m_data;
m_extra = other.m_extra;
m_status.store(other.m_status.load());
return *this;
}
pair<int, typename list_t::SNode*> Find(const large_t& k, int hint) {
if(BucketBlock > 0) {
//try exact position first
if(isEmpty(hint)) {
return make_pair(BucketBlock+1, nullptr);
} else {
Wait(hint);
if(m_data[hint].first == k)
return make_pair(hint, nullptr);
}
//scan array
for(int shift = 0; shift < BucketBlock; ++shift) {
if(shift != hint) {
if(isEmpty(shift)) {
return make_pair(BucketBlock+1, nullptr);
} else {
Wait(shift);
if(m_data[shift].first == k)
return make_pair(shift, nullptr);
}
}
}
}
//scan spillover list
for(auto it = m_extra.begin(); it != m_extra.end(); ++it) {
auto& cell = *it;
if(cell.first == k)
return make_pair(BucketBlock, it.NodePointer());
}
return make_pair(BucketBlock+1, nullptr);
}
// 1. Try to put to exact position prescribed by hash
// 2. Put in the lowest available array element
// 3. Put in the spillover list
mapped_t* FindOrInsert(const large_t& k, int hint) {
auto TryCell = [&](int shift) {
auto& cell = m_data[shift];
//try to grab
if(Lock(shift, k))
return &cell.second;
//already assigned to some kmer
//wait if kmer is not stored yet
Wait(shift);
if(cell.first == k) // kmer matches
return &cell.second;
else
return (mapped_t*)nullptr; // other kmer
};
if(BucketBlock > 0) {
//try exact position first
auto rslt = TryCell(hint);
if(rslt != nullptr)
return rslt;
//scan remaining array
for(int shift = 0; shift < BucketBlock; ++shift) {
if(shift != hint) {
auto rslt = TryCell(shift);
if(rslt != nullptr)
return rslt;
}
}
}
//scan spillover list
auto existing_head = m_extra.Head();
for(auto p = existing_head; p != nullptr; p = p->m_next) {
if(p->m_data.first == k)
return &(p->m_data.second);
}
typename list_t::SNode* nodep = new typename list_t::SNode;
nodep->m_data.first = k;
nodep->m_next = existing_head;
while(!m_extra.TryPushFront(nodep)) {
//check if a new elemet matches
for(auto p = nodep->m_next; p != existing_head; p = p->m_next) {
if(p->m_data.first == k) {
delete nodep;
return &(p->m_data.second);
}
}
existing_head = nodep->m_next;
}
return &(nodep->m_data.second);
}
element_t* IndexGet(int shift, void* lstp) {
if(shift < BucketBlock) { // array element
return &m_data[shift];
} else { //list element
snode_t* ptr = reinterpret_cast<snode_t*>(lstp);
return &(ptr->m_data);
}
}
bool Lock(int shift, const large_t& kmer) {
uint64_t assigned = eAssigned << 2*shift;
uint64_t expected = m_status;
do { if(expected&assigned) return false; }
while(!m_status.compare_exchange_strong(expected, expected|assigned));
m_data[shift].first = kmer;
m_status |= eKeyExists << 2*shift;
return true;
}
void Wait(int shift) {
uint64_t keyexists = eKeyExists << 2*shift;
while(!(m_status&keyexists));
}
bool isEmpty(int shift) const {
uint64_t assigned = eAssigned << 2*shift;
return (!(m_status&assigned));
}
void Move(element_t& cell, int to) {
m_data[to] = cell;
m_status |= (eAssigned|eKeyExists) << 2*to;
cell.second = V();
}
void Move(int from, int to) {
Move(m_data[from], to);
m_status &= ~((eAssigned|eKeyExists) << 2*from); // clear bits
}
void Clear(int shift) {
m_data[shift].second = V();
m_status &= ~((uint64_t)(eAssigned|eKeyExists) << 2*shift); // clear bits
}
//assumes that cel is not assigned; not mutithread safe
mapped_t* InitCell(const large_t& kmer, int shift) {
if(shift < BucketBlock) {
m_status |= (eAssigned|eKeyExists) << 2*shift;
m_data[shift].first = kmer;
return &(m_data[shift].second);
}
auto nodep = m_extra.NewNode();
nodep->m_data.first = kmer;
return &(nodep->m_data.second);
}
array<element_t, BucketBlock> m_data;
list_t m_extra;
atomic<uint64_t> m_status;
};
template<typename Key, class MappedV, int BucketBlock, class Hash = std::hash<Key>>
class CHashMap {
public:
CHashMap(size_t size) {
size_t blocks = size/max(1,BucketBlock);
if(size%max(1,BucketBlock))
++blocks;
m_table_size = max(1,BucketBlock)*blocks;
m_hash_table.Reset(blocks,1);
}
MappedV* Find(const Key& k) {
if(m_table_size == 0) {
return nullptr;
} else {
size_t pos = Hash()(k)%m_table_size;
auto& bucket = m_hash_table[pos/max(1,BucketBlock)];
int hint = pos%max(1,BucketBlock);
auto rslt = bucket.Find(k, hint);
if(rslt.first < BucketBlock) // found in array
return &bucket.m_data[rslt.first].second;
else if(rslt.first == BucketBlock) // found in list
return &rslt.second->m_data.second;
else // not found
return nullptr;
}
}
MappedV* FindOrInsert(const Key& k) {
size_t index = Hash()(k)%m_table_size;
size_t bucket_num = index/max(1,BucketBlock);
int hint = index%max(1,BucketBlock);
return m_hash_table[bucket_num].FindOrInsert(k, hint);
}
size_t TableSize() const { return m_table_size; }
private:
CDeque<SHashBlock<Key, MappedV, BucketBlock>> m_hash_table;
size_t m_table_size;
};
template <typename MappedV, int BucketBlock>
class CKmerHashMap {
public:
CKmerHashMap(int kmer_len = 0, size_t size = 0) : m_kmer_len(kmer_len) {
if(m_kmer_len > 0)
m_hash_table = CreateVariant<TKmerHashTable<MappedV>, THashBlockVec, MappedV>((m_kmer_len+31)/32);
Reset(size, 1);
}
void Reset(size_t size, size_t chunks) {
size_t blocks = size/max(1,BucketBlock);
if(size%max(1,BucketBlock))
++blocks;
m_table_size = max(1,BucketBlock)*blocks;
apply_visitor(resize(blocks, chunks), m_hash_table);
}
class Index {
public:
Index(size_t ind = 0, void* ptr = nullptr) : m_index(ind), m_lstp(ptr) {}
void Advance(CKmerHashMap& hash) { apply_visitor(CKmerHashMap::index_advance(*this), hash.m_hash_table); }
pair<TKmer, MappedV*> GetElement(CKmerHashMap& hash) const { return apply_visitor(CKmerHashMap::index_get(*this), hash.m_hash_table); };
pair<TKmer, const MappedV*> GetElement(const CKmerHashMap& hash) const { return apply_visitor(CKmerHashMap::index_get(*this), const_cast<CKmerHashMap&>(hash).m_hash_table); };
MappedV* GetMapped(CKmerHashMap& hash) const { return apply_visitor(CKmerHashMap::index_get_mapped(*this), hash.m_hash_table); };
const MappedV* GetMapped(const CKmerHashMap& hash) const { return apply_visitor(CKmerHashMap::index_get_mapped(*this), const_cast<CKmerHashMap&>(hash).m_hash_table); };
const uint64_t* GetKeyPointer(const CKmerHashMap& hash) const { return apply_visitor(CKmerHashMap::index_get_keyp(*this), const_cast<CKmerHashMap&>(hash).m_hash_table); };
bool operator==(const Index& other) const { return m_index == other.m_index && m_lstp == other.m_lstp; }
bool operator!=(const Index& other) const { return !operator==(other); }
bool operator<(const Index& other) const {
if(m_index == other.m_index)
return m_lstp < other.m_lstp;
else
return m_index < other.m_index;
}
bool operator>(const Index& other) const {
if(m_index == other.m_index)
return m_lstp > other.m_lstp;
else
return m_index > other.m_index;
}
struct Hash { size_t operator()(const Index& index) const { return std::hash<size_t>()(index.m_index)^std::hash<void*>()(index.m_lstp); } };
protected:
friend class CKmerHashMap;
size_t m_index; // index; list considered a single entry
void* m_lstp; // pointer to list element
};
Index EndIndex() const { return Index((BucketBlock+1)*BucketsNum(), nullptr); }
class Iterator : public Index {
public:
Iterator(const Index& index, CKmerHashMap* hp) : Index(index), hashp(hp) {}
Iterator(size_t ind, void* ptr, CKmerHashMap* hp) : Index(ind, ptr), hashp(hp) {}
Iterator& operator++() {
this->Advance(*hashp);
return *this;
}
pair<TKmer, MappedV*> GetElement() { return Index::GetElement(*hashp); }
MappedV* GetMapped() { return Index::GetMapped(*hashp); }
const uint64_t* GetKeyPointer() { return Index::GetKeyPointer(*hashp); }
size_t HashPosition() const { return Index::m_index; }
private:
CKmerHashMap* hashp;
};
Iterator Begin() { return Iterator(apply_visitor(hash_begin(0), m_hash_table), this); }
Iterator End() { return Iterator((BucketBlock+1)*BucketsNum(), nullptr, this); }
Iterator FirstForBucket(size_t bucket) { return Iterator(apply_visitor(hash_begin(bucket), m_hash_table), this); }
vector<Iterator> Chunks(int desired_num) {
vector<Iterator> chunks;
if(BucketsNum() == 0)
return chunks;
size_t step = BucketsNum()/desired_num+1;
for(size_t bucket = 0; bucket < BucketsNum(); ) {
chunks.push_back(FirstForBucket(bucket));
bucket = chunks.back().m_index/(BucketBlock+1)+step;
}
if(chunks.back() != End())
chunks.push_back(End());
return chunks;
}
//returns pointer to mapped value if exists, otherwise nullptr
MappedV* Find(const TKmer& kmer) {
if(m_table_size == 0)
return nullptr;
else
return apply_visitor(find(kmer), m_hash_table);
}
//returns index in hash table
Index FindIndex(const TKmer& kmer) {
if(m_table_size == 0)
return EndIndex();
else
return apply_visitor(find_index(kmer), m_hash_table);
}
// if kmer already included returns pointer to mapped value
// if not inserts a new entry and returns pointer to default value
// caller MUST update the mapped value
// assumes that any updates will be atomic
MappedV* FindOrInsert(const TKmer& kmer) {
size_t index = kmer.oahash()%m_table_size;
return FindOrInsertInBucket(kmer, index);
}
MappedV* FindOrInsertInBucket(const TKmer& kmer, size_t index) {return apply_visitor(find_or_insert(kmer,index), m_hash_table); }
MappedV* InitCell(const TKmer& kmer, size_t index) { return apply_visitor(init_cell(kmer,index), m_hash_table); }
void Swap(CKmerHashMap& other) {
apply_visitor(swap_with_other(), m_hash_table, other.m_hash_table);
swap(m_table_size, other.m_table_size);
swap(m_kmer_len, other.m_kmer_len);
}
int KmerLen() const { return m_kmer_len; }
size_t TableSize() const { return m_table_size; }
size_t TableFootPrint() const { return apply_visitor(hash_footprint(), m_hash_table); }
size_t BucketsNum() const { return m_table_size/max(1,BucketBlock); }
void Info() const { apply_visitor(info(), m_hash_table); }
void Save(ostream& os) const {
os.write(reinterpret_cast<const char*>(&m_table_size), sizeof m_table_size);
os.write(reinterpret_cast<const char*>(&m_kmer_len), sizeof m_kmer_len);
apply_visitor(save(os), m_hash_table);
if(!os)
throw runtime_error("Error in CKmerHashMap write");
}
void Load(istream& is) {
if(!is.read(reinterpret_cast<char*>(&m_table_size), sizeof m_table_size))
throw runtime_error("Error in CKmerHashMap read");
if(!is.read(reinterpret_cast<char*>(&m_kmer_len), sizeof m_kmer_len))
throw runtime_error("Error in CKmerHashMap read");
m_hash_table = CreateVariant<TKmerHashTable<MappedV>, THashBlockVec, MappedV>((m_kmer_len+31)/32);
apply_visitor(load(is), m_hash_table);
}
protected:
friend class Index;
template<int N, class V> using THashBlockVec = CDeque<SHashBlock<LargeInt<N>,V,BucketBlock>>;
template<class V> using TKmerHashTable = BoostVariant<THashBlockVec,V>;
struct save : public boost::static_visitor<void> {
save(ostream& out) : os(out) {}
template <typename T>
void operator()(const T& v) const {
v.Save(os);
size_t list_num = 0;
for(size_t i = 0; i < v.Size(); ++i) {
if(v[i].m_extra.Head() != nullptr)
++list_num;
}
os.write(reinterpret_cast<const char*>(&list_num), sizeof list_num);
for(size_t i = 0; i < v.Size(); ++i) {
if(v[i].m_extra.Head() != nullptr) {
os.write(reinterpret_cast<const char*>(&i), sizeof i);
v[i].m_extra.Save(os);
}
}
}
ostream& os;
};
struct load : public boost::static_visitor<void> {
load(istream& in) : is(in) {}
template <typename T>
void operator()(T& v) const {
v.Load(is);
size_t list_num;
if(!is.read(reinterpret_cast<char*>(&list_num), sizeof list_num))
throw runtime_error("Error in CKmerHashMap read");
for( ; list_num > 0; --list_num) {
size_t i;
if(!is.read(reinterpret_cast<char*>(&i), sizeof i))
throw runtime_error("Error in CKmerHashMap read");
v[i].m_extra.Init();
v[i].m_extra.Load(is);
}
}
istream& is;
};
struct swap_with_other : public boost::static_visitor<> {
template <typename T> void operator() (T& a, T& b) const { a.Swap(b); }
template <typename T, typename U> void operator() (T& , U& ) const { throw runtime_error("Can't swap different type containers"); }
};
struct index_get : public boost::static_visitor<pair<TKmer, MappedV*>> {
index_get(const Index& ind) : index(ind) {}
template <typename T>
pair<TKmer, MappedV*> operator()(T& v) const {
auto elemp = v[index.m_index/(BucketBlock+1)].IndexGet(index.m_index%(BucketBlock+1), index.m_lstp);
return make_pair(TKmer(elemp->first), &(elemp->second));
}
const Index& index;
};
struct index_get_mapped : public boost::static_visitor<MappedV*> {
index_get_mapped(const Index& ind) : index(ind) {}
template <typename T>
MappedV* operator()(T& v) const {
auto elemp = v[index.m_index/(BucketBlock+1)].IndexGet(index.m_index%(BucketBlock+1), index.m_lstp);
return &(elemp->second);
}
const Index& index;
};
struct index_get_keyp : public boost::static_visitor<const uint64_t*> {
index_get_keyp(const Index& ind) : index(ind) {}
template <typename T>
const uint64_t* operator()(T& v) const {
auto elemp = v[index.m_index/(BucketBlock+1)].IndexGet(index.m_index%(BucketBlock+1), index.m_lstp);
return elemp->first.getPointer();
}
const Index& index;
};
template <typename T>
static Index next_available(T& v, size_t from) {
for(size_t i = from; i < v.Size(); ++i) {
auto& bucket = v[i];
for(int shift = 0; shift < BucketBlock; ++shift) {
if(!bucket.isEmpty(shift))
return Index(i*(BucketBlock+1)+shift, nullptr);
}
if(bucket.m_extra.Head() != nullptr)
return Index(i*(BucketBlock+1)+BucketBlock, bucket.m_extra.Head());
}
return Index((BucketBlock+1)*v.Size(), nullptr);
}
struct index_advance : public boost::static_visitor<> {
index_advance(Index& ind) : index(ind) {}
template <typename T>
void operator()(T& v) const {
typedef typename T::value_type::list_t::SNode snode_t;
size_t ind = index.m_index;
size_t i = ind/(BucketBlock+1);
auto& bucket = v[i];
int shift = ind%(BucketBlock+1);
if(shift < BucketBlock-1) { // not last array element - check all next elements
while(++shift < BucketBlock) {
if(!bucket.isEmpty(shift)) {
index.m_index = i*(BucketBlock+1)+shift;
return;
}
}
} else if(shift == BucketBlock-1) { // last array element - check spillover list
if(bucket.m_extra.Head() != nullptr) {
++index.m_index;
index.m_lstp = bucket.m_extra.Head();
return;
}
} else { // spillover list - check next list element
snode_t* ptr = reinterpret_cast<snode_t*>(index.m_lstp);
if(ptr->m_next != nullptr) {
index.m_lstp = ptr->m_next;
return;
}
}
index = next_available(v, i+1); // look for next bucket
}
Index& index;
};
struct hash_begin : public boost::static_visitor<Index> {
hash_begin(size_t fr) : from(fr) {}
template <typename T>
Index operator()(T& v) const { return next_available(v, from); }
size_t from;
};
struct hash_footprint : public boost::static_visitor<size_t> {
template <typename T> size_t operator()(T& v) const { return sizeof(typename T::value_type)*v.Size(); }
};
//returns pointer to mapped value if exists, otherwise nullptr
struct find : public boost::static_visitor<MappedV*> {
find(const TKmer& k) : kmer(k) {}
template <typename T> MappedV* operator()(T& v) const {
auto& k = kmer.get<typename T::value_type::large_t>();
size_t pos = k.oahash()%(v.Size()*max(1,BucketBlock));
auto& bucket = v[pos/max(1,BucketBlock)];
int hint = pos%max(1,BucketBlock);
auto rslt = bucket.Find(k, hint);
if(rslt.first < BucketBlock) // found in array
return &bucket.m_data[rslt.first].second;
else if(rslt.first == BucketBlock) // found in list
return &rslt.second->m_data.second;
else // not found
return nullptr;
}
const TKmer& kmer;
};
//returns Index
struct find_index : public boost::static_visitor<Index> {
find_index(const TKmer& k) : kmer(k) {}
template <typename T> Index operator()(T& v) const {
typedef typename T::value_type::large_t large_t;
const large_t& k = kmer.get<large_t>();
size_t pos = k.oahash()%(v.Size()*max(1,BucketBlock));
size_t bucket_num = pos/max(1,BucketBlock);
int hint = pos%max(1,BucketBlock);
auto rslt = v[bucket_num].Find(k, hint);
if(rslt.first <= BucketBlock) // found in array
return Index(bucket_num*(BucketBlock+1)+rslt.first, rslt.second);
else // not found
return Index((BucketBlock+1)*v.Size(), nullptr);
}
const TKmer& kmer;
};
// if kmer already included returns pointer to mapped value
// if not inserts a new entry and returns pointer to default value
// caller MUST update the mapped value
// assumes that any updated will be atomic
struct find_or_insert : public boost::static_visitor<MappedV*> {
find_or_insert(const TKmer& k, size_t i) : kmer(k), index(i) {}
template <typename T> MappedV* operator()(T& v) const {
typedef typename T::value_type::large_t large_t;
const large_t& k = kmer.get<large_t>();
size_t bucket_num = index/max(1,BucketBlock);
int hint = index%max(1,BucketBlock);
return v[bucket_num].FindOrInsert(k, hint);
}
const TKmer& kmer;
size_t index;
};
struct init_cell : public boost::static_visitor<MappedV*> {
init_cell(const TKmer& k, size_t i) : kmer(k), index(i) {}
template <typename T> MappedV* operator()(T& v) const {
typedef typename T::value_type::large_t large_t;
const large_t& k = kmer.get<large_t>();
size_t bucket_num = index/(BucketBlock+1);
int shift = index%(BucketBlock+1);
return v[bucket_num].InitCell(k, shift);
}
const TKmer& kmer;
size_t index;
};
struct info : public boost::static_visitor<> {
template <typename T> void operator()(T& v) const {
map<int,int> numbers;
for(size_t i = 0; i < v.Size(); ++i) {
auto& bucket= v[i];
int num = distance(bucket.m_extra.begin(), bucket.m_extra.end());
for(int shift = 0; shift < BucketBlock; ++shift) {
if(!bucket.isEmpty(shift))
++num;
}
++numbers[num];
}
for(auto& rslt : numbers)
cerr << "Bucket:\t" << rslt.first << "\t" << rslt.second << endl;
}
};
struct resize : public boost::static_visitor<> {
resize(size_t s, size_t c) : size(s), chunks(c) {}
template <typename T> void operator()(T& v) const { v.Reset(size, chunks); }
size_t size;
size_t chunks;
};
TKmerHashTable<MappedV> m_hash_table;
size_t m_table_size;
int m_kmer_len;
};
struct SKmerCounter {
SKmerCounter() : m_data(0) {}
bool operator==(const SKmerCounter& kc) const { return kc.m_data == m_data; }
uint32_t Increment(bool is_plus) { return (m_data.m_atomic += (is_plus ? 0x100000001 : 1)); }
uint32_t Count() const { return m_data; } // clips plus part
SAtomic<uint64_t> m_data;
};
class CKmerHashCount : public CKmerHashMap<SKmerCounter, 8> {
public:
CKmerHashCount(int kmer_len = 0, size_t size = 0) : CKmerHashMap(kmer_len, size) {}
// returns true if kmer was new
bool UpdateCount(const TKmer& kmer, bool is_plus) {