-
Notifications
You must be signed in to change notification settings - Fork 28
/
BooPHF.h
1566 lines (1198 loc) · 40.8 KB
/
BooPHF.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
// BooPHF library
// intended to be a minimal perfect hash function with fast and low memory construction, at the cost of (slightly) higher bits/elem than other state of the art libraries once built.
// should work with arbitray large number of elements, based on a cascade of "collision-free" bit arrays
#pragma once
#include <stdio.h>
#include <climits>
#include <stdlib.h>
#include <iostream>
#include <math.h>
#include <array>
#include <unordered_map>
#include <vector>
#include <assert.h>
#include <sys/time.h>
#include <string.h>
#include <memory> // for make_shared
#include <unistd.h>
#include <inttypes.h>
namespace boomphf {
inline uint64_t printPt( pthread_t pt) {
unsigned char *ptc = (unsigned char*)(void*)(&pt);
uint64_t res =0;
for (size_t i=0; i<sizeof(pt); i++) {
res+= (unsigned)(ptc[i]);
}
return res;
}
////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark utils
////////////////////////////////////////////////////////////////
// iterator from disk file of uint64_t with buffered read, todo template
template <typename basetype>
class bfile_iterator : public std::iterator<std::forward_iterator_tag, basetype>{
public:
bfile_iterator()
: _is(nullptr)
, _pos(0) ,_inbuff (0), _cptread(0)
{
_buffsize = 10000;
_buffer = (basetype *) malloc(_buffsize*sizeof(basetype));
}
bfile_iterator(const bfile_iterator& cr)
{
_buffsize = cr._buffsize;
_pos = cr._pos;
_is = cr._is;
_buffer = (basetype *) malloc(_buffsize*sizeof(basetype));
memcpy(_buffer,cr._buffer,_buffsize*sizeof(basetype) );
_inbuff = cr._inbuff;
_cptread = cr._cptread;
_elem = cr._elem;
}
bfile_iterator(FILE* is): _is(is) , _pos(0) ,_inbuff (0), _cptread(0)
{
//printf("bf it %p\n",_is);
_buffsize = 10000;
_buffer = (basetype *) malloc(_buffsize*sizeof(basetype));
int reso = fseek(_is,0,SEEK_SET);
advance();
}
~bfile_iterator()
{
if(_buffer!=NULL)
free(_buffer);
}
basetype const& operator*() { return _elem; }
bfile_iterator& operator++()
{
advance();
return *this;
}
friend bool operator==(bfile_iterator const& lhs, bfile_iterator const& rhs)
{
if (!lhs._is || !rhs._is) { if (!lhs._is && !rhs._is) { return true; } else { return false; } }
assert(lhs._is == rhs._is);
return rhs._pos == lhs._pos;
}
friend bool operator!=(bfile_iterator const& lhs, bfile_iterator const& rhs) { return !(lhs == rhs); }
private:
void advance()
{
//printf("_cptread %i _inbuff %i \n",_cptread,_inbuff);
_pos++;
if(_cptread >= _inbuff)
{
int res = fread(_buffer,sizeof(basetype),_buffsize,_is);
//printf("read %i new elem last %llu %p\n",res,_buffer[res-1],_is);
_inbuff = res; _cptread = 0;
if(res == 0)
{
_is = nullptr;
_pos = 0;
return;
}
}
_elem = _buffer[_cptread];
_cptread ++;
}
basetype _elem;
FILE * _is;
unsigned long _pos;
basetype * _buffer; // for buffered read
int _inbuff, _cptread;
int _buffsize;
};
template <typename type_elem>
class file_binary{
public:
file_binary(const char* filename)
{
_is = fopen(filename, "rb");
if (!_is) {
throw std::invalid_argument("Error opening " + std::string(filename));
}
}
~file_binary()
{
fclose(_is);
}
bfile_iterator<type_elem> begin() const
{
return bfile_iterator<type_elem>(_is);
}
bfile_iterator<type_elem> end() const {return bfile_iterator<type_elem>(); }
size_t size () const { return 0; }//todo ?
private:
FILE * _is;
};
inline unsigned int popcount_32(unsigned int x)
{
unsigned int m1 = 0x55555555;
unsigned int m2 = 0x33333333;
unsigned int m4 = 0x0f0f0f0f;
unsigned int h01 = 0x01010101;
x -= (x >> 1) & m1; /* put count of each 2 bits into those 2 bits */
x = (x & m2) + ((x >> 2) & m2); /* put count of each 4 bits in */
x = (x + (x >> 4)) & m4; /* put count of each 8 bits in partie droite 4bit piece*/
return (x * h01) >> 24; /* returns left 8 bits of x + (x<<8) + ... */
}
inline unsigned int popcount_64(uint64_t x)
{
unsigned int low = x & 0xffffffff ;
unsigned int high = ( x >> 32LL) & 0xffffffff ;
return (popcount_32(low) + popcount_32(high));
}
///// progress bar
class Progress
{
public:
int timer_mode;
struct timeval timestamp;
double heure_debut, heure_actuelle ;
std::string message;
uint64_t done;
uint64_t todo;
int subdiv ; // progress printed every 1/subdiv of total to do
double partial;
int _nthreads;
std::vector<double > partial_threaded;
std::vector<uint64_t > done_threaded;
double steps ; //steps = todo/subidv
void init(uint64_t ntasks, const char * msg,int nthreads =1)
{
_nthreads = nthreads;
message = std::string(msg);
gettimeofday(×tamp, NULL);
heure_debut = timestamp.tv_sec +(timestamp.tv_usec/1000000.0);
//fprintf(stderr,"| %-*s |\n",98,msg);
todo= ntasks;
done = 0;
partial =0;
partial_threaded.resize(_nthreads);
done_threaded.resize(_nthreads);
for (int ii=0; ii<_nthreads;ii++) partial_threaded[ii]=0;
for (int ii=0; ii<_nthreads;ii++) done_threaded[ii]=0;
subdiv= 1000;
steps = (double)todo / (double)subdiv;
if(!timer_mode)
{
fprintf(stderr,"[");fflush(stderr);
}
}
void finish()
{
set(todo);
if(timer_mode)
fprintf(stderr,"\n");
else
fprintf(stderr,"]\n");
fflush(stderr);
todo= 0;
done = 0;
partial =0;
}
void finish_threaded()// called by only one of the threads
{
done = 0;
double rem = 0;
for (int ii=0; ii<_nthreads;ii++) done += (done_threaded[ii] );
for (int ii=0; ii<_nthreads;ii++) partial += (partial_threaded[ii] );
finish();
}
void inc(uint64_t ntasks_done)
{
done += ntasks_done;
partial += ntasks_done;
while(partial >= steps)
{
if(timer_mode)
{
gettimeofday(×tamp, NULL);
heure_actuelle = timestamp.tv_sec +(timestamp.tv_usec/1000000.0);
double elapsed = heure_actuelle - heure_debut;
double speed = done / elapsed;
double rem = (todo-done) / speed;
if(done>todo) rem=0;
int min_e = (int)(elapsed / 60) ;
elapsed -= min_e*60;
int min_r = (int)(rem / 60) ;
rem -= min_r*60;
fprintf(stderr,"%c[%s] %-5.3g%% elapsed: %3i min %-2.0f sec remaining: %3i min %-2.0f sec",13,
message.c_str(),
100*(double)done/todo,
min_e,elapsed,min_r,rem);
}
else
{
fprintf(stderr,"-");fflush(stderr);
}
partial -= steps;
}
}
void inc(uint64_t ntasks_done, int tid) //threads collaborate to this same progress bar
{
partial_threaded[tid] += ntasks_done;
done_threaded[tid] += ntasks_done;
while(partial_threaded[tid] >= steps)
{
if(timer_mode)
{
struct timeval timet;
double now;
gettimeofday(&timet, NULL);
now = timet.tv_sec +(timet.tv_usec/1000000.0);
uint64_t total_done = 0;
for (int ii=0; ii<_nthreads;ii++) total_done += (done_threaded[ii] );
double elapsed = now - heure_debut;
double speed = total_done / elapsed;
double rem = (todo-total_done) / speed;
if(total_done > todo) rem =0;
int min_e = (int)(elapsed / 60) ;
elapsed -= min_e*60;
int min_r = (int)(rem / 60) ;
rem -= min_r*60;
fprintf(stderr,"%c[%s] %-5.3g%% elapsed: %3i min %-2.0f sec remaining: %3i min %-2.0f sec",13,
message.c_str(),
100*(double)total_done/todo,
min_e,elapsed,min_r,rem);
}
else
{
fprintf(stderr,"-");fflush(stderr);
}
partial_threaded[tid] -= steps;
}
}
void set(uint64_t ntasks_done)
{
if(ntasks_done > done)
inc(ntasks_done-done);
}
Progress () : timer_mode(0) {}
//include timer, to print ETA ?
};
////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark hasher
////////////////////////////////////////////////////////////////
typedef std::array<uint64_t,10> hash_set_t;
typedef std::array<uint64_t,2> hash_pair_t;
template <typename Item> class HashFunctors
{
public:
/** Constructor.
* \param[in] nbFct : number of hash functions to be used
* \param[in] seed : some initialization code for defining the hash functions. */
HashFunctors ()
{
_nbFct = 7; // use 7 hash func
_user_seed = 0;
generate_hash_seed ();
}
//return one hash
uint64_t operator () (const Item& key, size_t idx) const { return hash64 (key, _seed_tab[idx]); }
uint64_t hashWithSeed(const Item& key, uint64_t seed) const { return hash64 (key, seed); }
//this one returns all the 7 hashes
//maybe use xorshift instead, for faster hash compute
hash_set_t operator () (const Item& key)
{
hash_set_t hset;
for(size_t ii=0;ii<10; ii++)
{
hset[ii] = hash64 (key, _seed_tab[ii]);
}
return hset;
}
private:
inline static uint64_t hash64 (Item key, uint64_t seed)
{
uint64_t hash = seed;
hash ^= (hash << 7) ^ key * (hash >> 3) ^ (~((hash << 11) + (key ^ (hash >> 5))));
hash = (~hash) + (hash << 21);
hash = hash ^ (hash >> 24);
hash = (hash + (hash << 3)) + (hash << 8);
hash = hash ^ (hash >> 14);
hash = (hash + (hash << 2)) + (hash << 4);
hash = hash ^ (hash >> 28);
hash = hash + (hash << 31);
return hash;
}
/* */
void generate_hash_seed ()
{
static const uint64_t rbase[MAXNBFUNC] =
{
0xAAAAAAAA55555555ULL, 0x33333333CCCCCCCCULL, 0x6666666699999999ULL, 0xB5B5B5B54B4B4B4BULL,
0xAA55AA5555335533ULL, 0x33CC33CCCC66CC66ULL, 0x6699669999B599B5ULL, 0xB54BB54B4BAA4BAAULL,
0xAA33AA3355CC55CCULL, 0x33663366CC99CC99ULL
};
for (size_t i=0; i<MAXNBFUNC; ++i) { _seed_tab[i] = rbase[i]; }
for (size_t i=0; i<MAXNBFUNC; ++i) { _seed_tab[i] = _seed_tab[i] * _seed_tab[(i+3) % MAXNBFUNC] + _user_seed ; }
}
size_t _nbFct;
static const size_t MAXNBFUNC = 10;
uint64_t _seed_tab[MAXNBFUNC];
uint64_t _user_seed;
};
/* alternative hash functor based on xorshift, taking a single hash functor as input.
we need this 2-functors scheme because HashFunctors won't work with unordered_map.
(rayan)
*/
// wrapper around HashFunctors to return only one value instead of 7
template <typename Item> class SingleHashFunctor
{
public:
uint64_t operator () (const Item& key, uint64_t seed=0xAAAAAAAA55555555ULL) const { return hashFunctors.hashWithSeed(key, seed); }
private:
HashFunctors<Item> hashFunctors;
};
template <typename Item, class SingleHasher_t> class XorshiftHashFunctors
{
/* Xorshift128*
Written in 2014 by Sebastiano Vigna (vigna@acm.org)
To the extent possible under law, the author has dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.
See <http://creativecommons.org/publicdomain/zero/1.0/>. */
/* This is the fastest generator passing BigCrush without
systematic failures, but due to the relatively short period it is
acceptable only for applications with a mild amount of parallelism;
otherwise, use a xorshift1024* generator.
The state must be seeded so that it is not everywhere zero. If you have
a nonzero 64-bit seed, we suggest to pass it twice through
MurmurHash3's avalanching function. */
// uint64_t s[ 2 ];
uint64_t next(uint64_t * s) {
uint64_t s1 = s[ 0 ];
const uint64_t s0 = s[ 1 ];
s[ 0 ] = s0;
s1 ^= s1 << 23; // a
return ( s[ 1 ] = ( s1 ^ s0 ^ ( s1 >> 17 ) ^ ( s0 >> 26 ) ) ) + s0; // b, c
}
public:
uint64_t h0(hash_pair_t & s, const Item& key )
{
s[0] = singleHasher (key, 0xAAAAAAAA55555555ULL);
return s[0];
}
uint64_t h1(hash_pair_t & s, const Item& key )
{
s[1] = singleHasher (key, 0x33333333CCCCCCCCULL);
return s[1];
}
//return next hash an update state s
uint64_t next(hash_pair_t & s ) {
uint64_t s1 = s[ 0 ];
const uint64_t s0 = s[ 1 ];
s[ 0 ] = s0;
s1 ^= s1 << 23; // a
return ( s[ 1 ] = ( s1 ^ s0 ^ ( s1 >> 17 ) ^ ( s0 >> 26 ) ) ) + s0; // b, c
}
//this one returns all the hashes
hash_set_t operator () (const Item& key)
{
uint64_t s[ 2 ];
hash_set_t hset;
hset[0] = singleHasher (key, 0xAAAAAAAA55555555ULL);
hset[1] = singleHasher (key, 0x33333333CCCCCCCCULL);
s[0] = hset[0];
s[1] = hset[1];
for(size_t ii=2;ii< 10 /* it's much better have a constant here, for inlining; this loop is super performance critical*/; ii++)
{
hset[ii] = next(s);
}
return hset;
}
private:
SingleHasher_t singleHasher;
};
////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark iterators
////////////////////////////////////////////////////////////////
template <typename Iterator>
struct iter_range
{
iter_range(Iterator b, Iterator e)
: m_begin(b)
, m_end(e)
{}
Iterator begin() const
{ return m_begin; }
Iterator end() const
{ return m_end; }
Iterator m_begin, m_end;
};
template <typename Iterator>
iter_range<Iterator> range(Iterator begin, Iterator end)
{
return iter_range<Iterator>(begin, end);
}
////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark BitVector
////////////////////////////////////////////////////////////////
class bitVector {
public:
bitVector() : _size(0)
{
_bitArray = nullptr;
}
bitVector(uint64_t n) : _size(n)
{
_nchar = (1ULL+n/64ULL);
_bitArray = (uint64_t *) calloc (_nchar,sizeof(uint64_t));
}
~bitVector()
{
if(_bitArray != nullptr)
free(_bitArray);
}
//copy constructor
bitVector(bitVector const &r)
{
_size = r._size;
_nchar = r._nchar;
_ranks = r._ranks;
_bitArray = (uint64_t *) calloc (_nchar,sizeof(uint64_t));
memcpy(_bitArray, r._bitArray, _nchar*sizeof(uint64_t) );
}
// Copy assignment operator
bitVector &operator=(bitVector const &r)
{
if (&r != this)
{
_size = r._size;
_nchar = r._nchar;
_ranks = r._ranks;
if(_bitArray != nullptr)
free(_bitArray);
_bitArray = (uint64_t *) calloc (_nchar,sizeof(uint64_t));
memcpy(_bitArray, r._bitArray, _nchar*sizeof(uint64_t) );
}
return *this;
}
// Move assignment operator
bitVector &operator=(bitVector &&r)
{
//printf("bitVector move assignment \n");
if (&r != this)
{
if(_bitArray != nullptr)
free(_bitArray);
_size = std::move (r._size);
_nchar = std::move (r._nchar);
_ranks = std::move (r._ranks);
_bitArray = r._bitArray;
r._bitArray = nullptr;
}
return *this;
}
// Move constructor
bitVector(bitVector &&r) : _bitArray ( nullptr),_size(0)
{
*this = std::move(r);
}
void resize(uint64_t newsize)
{
//printf("bitvector resize from %llu bits to %llu \n",_size,newsize);
_nchar = (1ULL+newsize/64ULL);
_bitArray = (uint64_t *) realloc(_bitArray,_nchar*sizeof(uint64_t));
_size = newsize;
}
size_t size() const
{
return _size;
}
uint64_t bitSize() const {return (_nchar*64ULL + _ranks.capacity()*64ULL );}
//clear whole array
void clear()
{
memset(_bitArray,0,_nchar*sizeof(uint64_t));
}
//clear collisions in interval, only works with start and size multiple of 64
void clearCollisions(uint64_t start, size_t size, bitVector * cc)
{
assert( (start & 63) ==0);
assert( (size & 63) ==0);
uint64_t ids = (start/64ULL);
for(uint64_t ii =0; ii< (size/64ULL); ii++ )
{
_bitArray[ids+ii] = _bitArray[ids+ii] & (~ (cc->get64(ii)) );
}
cc->clear();
}
//clear interval, only works with start and size multiple of 64
void clear(uint64_t start, size_t size)
{
assert( (start & 63) ==0);
assert( (size & 63) ==0);
memset(_bitArray + (start/64ULL),0,(size/64ULL)*sizeof(uint64_t));
}
//for debug purposes
void print() const
{
printf("bit array of size %lli: \n",(long long int)_size);
for(uint64_t ii = 0; ii< _size; ii++)
{
if(ii%10==0)
printf(" (%llu) ",(long long unsigned int)ii);
int val = (_bitArray[ii >> 6] >> (ii & 63 ) ) & 1;
printf("%i",val);
}
printf("\n");
printf("rank array : size %lu \n",_ranks.size());
for (uint64_t ii = 0; ii< _ranks.size(); ii++)
{
printf("%llu : %lli, ",(long long unsigned int)ii,(long long int)_ranks[ii]);
}
printf("\n");
}
//return value at pos
uint64_t operator[](uint64_t pos) const
{
//unsigned char * _bitArray8 = (unsigned char *) _bitArray;
//return (_bitArray8[pos >> 3ULL] >> (pos & 7 ) ) & 1;
return (_bitArray[pos >> 6ULL] >> (pos & 63 ) ) & 1;
}
//atomically return old val and set to 1
uint64_t atomic_test_and_set(uint64_t pos)
{
uint64_t oldval = __sync_fetch_and_or (_bitArray + (pos >> 6), (uint64_t) (1ULL << (pos & 63)) );
return ( oldval >> (pos & 63 ) ) & 1;
}
uint64_t get(uint64_t pos) const
{
return (*this)[pos];
}
uint64_t get64(uint64_t cell64) const
{
return _bitArray[cell64];
}
//set bit pos to 1
void set(uint64_t pos)
{
assert(pos<_size);
//_bitArray [pos >> 6] |= (1ULL << (pos & 63) ) ;
__sync_fetch_and_or (_bitArray + (pos >> 6ULL), (1ULL << (pos & 63)) );
}
//set bit pos to 0
void reset(uint64_t pos)
{
//_bitArray [pos >> 6] &= ~(1ULL << (pos & 63) ) ;
__sync_fetch_and_and (_bitArray + (pos >> 6ULL), ~(1ULL << (pos & 63) ));
}
//return value of last rank
// add offset to all ranks computed
uint64_t build_ranks(uint64_t offset =0)
{
_ranks.reserve(2+ _size/_nb_bits_per_rank_sample);
uint64_t curent_rank = offset;
for (size_t ii = 0; ii < _nchar; ii++) {
if (((ii*64) % _nb_bits_per_rank_sample) == 0) {
_ranks.push_back(curent_rank);
}
curent_rank += popcount_64(_bitArray[ii]);
}
return curent_rank;
}
uint64_t rank(uint64_t pos) const
{
uint64_t word_idx = pos / 64ULL;
uint64_t word_offset = pos % 64;
uint64_t block = pos / _nb_bits_per_rank_sample;
uint64_t r = _ranks[block];
for (uint64_t w = block * _nb_bits_per_rank_sample / 64; w < word_idx; ++w) {
r += popcount_64( _bitArray[w] );
}
uint64_t mask = (uint64_t(1) << word_offset ) - 1;
r += popcount_64( _bitArray[word_idx] & mask);
return r;
}
void save(std::ostream& os) const
{
os.write(reinterpret_cast<char const*>(&_size), sizeof(_size));
os.write(reinterpret_cast<char const*>(&_nchar), sizeof(_nchar));
os.write(reinterpret_cast<char const*>(_bitArray), (std::streamsize)(sizeof(uint64_t) * _nchar));
size_t sizer = _ranks.size();
os.write(reinterpret_cast<char const*>(&sizer), sizeof(size_t));
os.write(reinterpret_cast<char const*>(_ranks.data()), (std::streamsize)(sizeof(_ranks[0]) * _ranks.size()));
}
void load(std::istream& is)
{
is.read(reinterpret_cast<char*>(&_size), sizeof(_size));
is.read(reinterpret_cast<char*>(&_nchar), sizeof(_nchar));
this->resize(_size);
is.read(reinterpret_cast<char *>(_bitArray), (std::streamsize)(sizeof(uint64_t) * _nchar));
size_t sizer;
is.read(reinterpret_cast<char *>(&sizer), sizeof(size_t));
_ranks.resize(sizer);
is.read(reinterpret_cast<char*>(_ranks.data()), (std::streamsize)(sizeof(_ranks[0]) * _ranks.size()));
}
protected:
uint64_t* _bitArray;
//uint64_t* _bitArray;
uint64_t _size;
uint64_t _nchar;
// epsilon = 64 / _nb_bits_per_rank_sample bits
// additional size for rank is epsilon * _size
static const uint64_t _nb_bits_per_rank_sample = 512; //512 seems ok
std::vector<uint64_t> _ranks;
};
////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark level
////////////////////////////////////////////////////////////////
static inline uint64_t fastrange64(uint64_t word, uint64_t p) {
//return word % p;
return (uint64_t)(((__uint128_t)word * (__uint128_t)p) >> 64);
}
class level{
public:
level(){ }
~level() {
}
uint64_t get(uint64_t hash_raw)
{
// uint64_t hashi = hash_raw % hash_domain; //
//uint64_t hashi = (uint64_t)( ((__uint128_t) hash_raw * (__uint128_t) hash_domain) >> 64ULL);
uint64_t hashi = fastrange64(hash_raw,hash_domain);
return bitset.get(hashi);
}
uint64_t idx_begin;
uint64_t hash_domain;
bitVector bitset;
};
////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark mphf
////////////////////////////////////////////////////////////////
#define NBBUFF 10000
//#define NBBUFF 2
template<typename Range,typename Iterator>
struct thread_args
{
void * boophf;
Range const * range;
std::shared_ptr<void> it_p; /* used to be "Iterator it" but because of fastmode, iterator is polymorphic; TODO: think about whether it should be a unique_ptr actually */
std::shared_ptr<void> until_p; /* to cache the "until" variable */
int level;
};
//forward declaration
template <typename elem_t, typename Hasher_t, typename Range, typename it_type>
void * thread_processLevel(void * args);
/* Hasher_t returns a single hash when operator()(elem_t key) is called.
if used with XorshiftHashFunctors, it must have the following operator: operator()(elem_t key, uint64_t seed) */
template <typename elem_t, typename Hasher_t>
class mphf {
/* this mechanisms gets P hashes out of Hasher_t */
typedef XorshiftHashFunctors<elem_t,Hasher_t> MultiHasher_t ;
// typedef HashFunctors<elem_t> MultiHasher_t; // original code (but only works for int64 keys) (seems to be as fast as the current xorshift)
//typedef IndepHashFunctors<elem_t,Hasher_t> MultiHasher_t; //faster than xorshift
public:
mphf() : _built(false)
{}
~mphf()
{
}
// allow perc_elem_loaded elements to be loaded in ram for faster construction (default 3%), set to 0 to desactivate
template <typename Range>
mphf( size_t n, Range const& input_range,int num_thread = 1, double gamma = 2.0 , bool writeEach = true, bool progress =true, float perc_elem_loaded = 0.03) :
_gamma(gamma), _hash_domain(size_t(ceil(double(n) * gamma))), _nelem(n), _num_thread(num_thread), _percent_elem_loaded_for_fastMode (perc_elem_loaded), _withprogress(progress)
{
if(n ==0) return;
_fastmode = false;
if(_percent_elem_loaded_for_fastMode > 0.0 )
_fastmode =true;
if(writeEach)
{
_writeEachLevel =true;
_fastmode = false;
}
else
{
_writeEachLevel = false;
}
setup();
if(_withprogress)
{
_progressBar.timer_mode=1;
double total_raw = _nb_levels;
double sum_geom_read = ( 1.0 / (1.0 - _proba_collision));
double total_writeEach = sum_geom_read + 1.0;
double total_fastmode_ram = (_fastModeLevel+1) + ( pow(_proba_collision,_fastModeLevel)) * (_nb_levels-(_fastModeLevel+1)) ;
printf("for info, total work write each : %.3f total work inram from level %i : %.3f total work raw : %.3f \n",total_writeEach,_fastModeLevel,total_fastmode_ram,total_raw);
if(writeEach)
{
_progressBar.init(_nelem * total_writeEach,"Building BooPHF",num_thread);
}
else if(_fastmode)
_progressBar.init( _nelem * total_fastmode_ram ,"Building BooPHF",num_thread);
else
_progressBar.init( _nelem * _nb_levels ,"Building BooPHF",num_thread);
}
uint64_t offset = 0;
for(int ii = 0; ii< _nb_levels; ii++)
{
_tempBitset = new bitVector(_levels[ii].hash_domain); // temp collision bitarray for this level
processLevel(input_range,ii);
_levels[ii].bitset.clearCollisions(0 , _levels[ii].hash_domain , _tempBitset);
offset = _levels[ii].bitset.build_ranks(offset);
delete _tempBitset;
}
if(_withprogress)
_progressBar.finish_threaded();
_lastbitsetrank = offset ;
//printf("used temp ram for construction : %lli MB \n",setLevelFastmode.capacity()* sizeof(elem_t) /1024ULL/1024ULL);
std::vector<elem_t>().swap(setLevelFastmode); // clear setLevelFastmode reallocating
pthread_mutex_destroy(&_mutex);
_built = true;
}
uint64_t lookup(const elem_t &elem)
{
if(! _built) return ULLONG_MAX;
//auto hashes = _hasher(elem);
uint64_t non_minimal_hp,minimal_hp;
hash_pair_t bbhash; int level;
uint64_t level_hash = getLevel(bbhash,elem,&level);
if( level == (_nb_levels-1))
{
auto in_final_map = _final_hash.find (elem);
if ( in_final_map == _final_hash.end() )
{
//elem was not in orignal set of keys
return ULLONG_MAX; // means elem not in set
}
else
{
minimal_hp = in_final_map->second + _lastbitsetrank;
//printf("lookup %llu level %i --> %llu \n",elem,level,minimal_hp);
return minimal_hp;
}
// minimal_hp = _final_hash[elem] + _lastbitsetrank;
// return minimal_hp;
}
else