Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
bloom-filter.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
101# ifndef BLOOM_FILTER_H
102# define BLOOM_FILTER_H
103
104# include <cstddef>
105# include <memory>
106# include <tuple>
107# include <vector>
108# include <limits>
109# include <ctime>
110# include <cmath>
111# include <ahFunctional.H>
112# include <bitArray.H>
113# include <hash-fct.H>
114# include <tpl_dynSetHash.H>
115# include <ah-errors.H>
116# include <ah-random.H>
117
118namespace Aleph
119{
135 template <typename T>
137 {
138 public:
139 using Hash_Fct = size_t (*)(const T &, unsigned long seed);
140
141 private:
143
145 size_t num_hash = 0;
146 std::vector<unsigned long> seeds;
147 size_t num_ins = 0;
148
149 bool have_same_hashes(const Bloom_Filter & f) const noexcept
150 {
151 return get_m() == f.get_m() and get_k() == f.get_k() and
152 hash_fct == f.hash_fct and seeds == f.seeds;
153 }
154
156 Bloom_Filter(std::tuple<size_t, size_t> mk,
157 Hash_Fct hash_fn, unsigned long seed)
158 : Bloom_Filter(std::get<0>(mk), std::get<1>(mk), hash_fn, seed)
159 {
160 }
161
162 public:
179 [[nodiscard]] static std::tuple<size_t, size_t> estimate(const size_t n, const double p)
180 {
181 ah_invalid_argument_if(n == 0) << "n must be > 0";
182 // written so that a p that is not a number is refused too
183 ah_invalid_argument_if(not (p > 0 and p < 1)) << "p must be in (0, 1)";
184 const double log2 = std::log(2);
185 // the bits as a double first: for a count next to the largest size_t
186 // they are more than a size_t counts, and the conversion of such a
187 // double is undefined. The limit is one past the largest size_t, of
188 // whatever width, which a double holds exactly
189 constexpr double limit = 2.0 * static_cast<double>(std::numeric_limits<size_t>::max() / 2 + 1);
190 const double bits = std::ceil(-(n * std::log(p)) / (log2 * log2));
191 ah_overflow_error_if(bits >= limit) << n << " items at a probability of " << p
192 << " ask for more bits than a size_t counts";
193 const auto m = static_cast<size_t>(bits);
194 const auto k = static_cast<size_t>(std::ceil((1.0 * m / n) * log2));
195 return std::make_tuple(m, k);
196 }
197
203 [[nodiscard]] size_t get_m() const noexcept { return bits.size(); }
204
210 [[nodiscard]] size_t get_k() const noexcept { return num_hash; }
211
217 [[nodiscard]] size_t get_n() const noexcept { return num_ins; }
218
224 [[nodiscard]] size_t get_x() const noexcept
225 {
226 size_t x = 0;
227 for (size_t i = 0; i < bits.size(); ++i)
228 if (bits(i) == 1)
229 ++x;
230 return x;
231 }
232
240 [[nodiscard]] size_t size() const noexcept { return get_n(); }
241
249 [[nodiscard]] size_t capacity() const noexcept { return get_m(); }
250
263 Bloom_Filter(const size_t dim, size_t num_hashes,
264 Hash_Fct hash_fn = dft_seed_hash_ptr_fct<T>,
265 const unsigned long seed = static_cast<unsigned long>(std::time(nullptr)))
266 : bits(0), hash_fct(hash_fn), num_hash(num_hashes),
267 seeds(num_hashes)
268 {
269 ah_invalid_argument_if(dim == 0) << "Bloom filter dimension must be > 0";
270 ah_invalid_argument_if(num_hash == 0) << "Bloom filter number of hashes must be > 0";
271 ah_invalid_argument_if(hash_fct == nullptr) << "Bloom filter hash function is null";
272
275 for (auto & s: seeds)
276 s = r.get();
277 }
278
289 Bloom_Filter(const size_t n, const double p,
290 unsigned long seed = static_cast<unsigned long>(std::time(nullptr)),
291 Hash_Fct hash_fn = dft_seed_hash_ptr_fct<T>)
292 : Bloom_Filter(estimate(n, p), hash_fn, seed)
293 {
294 }
295
301 void swap(Bloom_Filter & f) noexcept
302 {
303 bits.swap(f.bits);
304 std::swap(hash_fct, f.hash_fct);
305 std::swap(num_hash, f.num_hash);
306 seeds.swap(f.seeds);
307 std::swap(num_ins, f.num_ins);
308 }
309
319 {
320 // empty
321 }
322
329 {
330 swap(f);
331 }
332
338 auto &operator =(const Bloom_Filter & f)
339 {
340 Bloom_Filter tmp(f);
341 swap(tmp);
342 return *this;
343 }
344
350 auto &operator =(Bloom_Filter && f) noexcept
351 {
352 swap(f);
353 return *this;
354 }
355
357 ~Bloom_Filter() = default;
358
365 auto &insert(const T & item)
366 {
367 const size_t m = bits.size();
368 for (const auto & seed: seeds)
369 bits.fast_write((*hash_fct)(item, seed) % m, 1);
370
371 ++num_ins;
372
373 return *this;
374 }
375
382 auto &append(const T & item) { return insert(item); }
383
389 [[nodiscard]] bool contains(const T & item) const
390 {
391 const size_t m = bits.size();
392 for (const auto & seed: seeds)
393 if (not bits.fast_read((*hash_fct)(item, seed) % m))
394 return false;
395
396 return true;
397 }
398
404 [[nodiscard]] DynList<size_t> hash_seeds() const
405 {
406 DynList<size_t> ret;
407 for (const auto & seed: seeds)
408 ret.append(seed);
409 return ret;
410 }
411
417 [[nodiscard]] DynList<size_t> hashes(const T & item) const
418 {
419 DynList<size_t> ret;
420 const size_t m = bits.size();
421 for (const auto & seed: seeds)
422 ret.append((*hash_fct)(item, seed) % m);
423 return ret;
424 }
425
433 [[nodiscard]] DynList<size_t> common_hashes(const T & i1, const T & i2) const
434 {
435 return intercept(hashes(i1), hashes(i2));
436 }
437
443 [[nodiscard]] DynList<size_t> set_bits() const
444 {
445 DynList<size_t> ret;
446 for (size_t i = 0; i < bits.size(); ++i)
447 if (bits(i) == 1)
448 ret.append(i);
449
450 return ret;
451 }
452
462 [[nodiscard]] size_t expected_size(const size_t x) const noexcept
463 {
464 const auto m = static_cast<double>(capacity());
465 const auto k = static_cast<double>(get_k());
466 if (m == 0 or k == 0)
467 return 0;
468
469 const double p0 = 1.0 - (static_cast<double>(x) / m);
470 if (p0 <= 0)
471 return std::numeric_limits<size_t>::max();
472
473 const double n = std::ceil(-(m * std::log(p0)) / k);
474 if (not std::isfinite(n) or n < 0)
475 return std::numeric_limits<size_t>::max();
476
477 return static_cast<size_t>(n);
478 }
479
485 [[nodiscard]] size_t expected_size() const noexcept
486 {
487 return expected_size(get_x());
488 }
489
496 auto &operator |=(const Bloom_Filter & f)
497 {
499 << "Bloom filter have different hashes";
500
501 bits |= f.bits;
502
503 const auto x = get_x();
504
506
507 return *this;
508 }
509
515 auto &operator &=(const Bloom_Filter & f)
516 {
518 << "Bloom filter have different hashes";
519
520 bits &= f.bits;
521
523
524 return *this;
525 }
526
528 friend Bloom_Filter
529 operator |(const Bloom_Filter & f1, const Bloom_Filter & f2)
530 {
531 Bloom_Filter ret = f1;
532 ret |= f2;
533 return ret;
534 }
535
537 friend Bloom_Filter
538 operator &(const Bloom_Filter & f1, const Bloom_Filter & f2)
539 {
540 Bloom_Filter ret = f1;
541 ret &= f2;
542 return ret;
543 }
544 };
545} // end namespace Aleph
546
547# endif // BLOOM_FILTER_H
Exception handling system with formatted messages for Aleph-w.
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
The random number generators of Aleph: the one that gives the numbers of the gsl_rng_mt19937 of GSL,...
Functional programming utilities for Aleph-w containers.
Space-efficient bit array implementation.
Contiguous array of bits.
Definition bitArray.H:201
void fast_write(const size_t i, const unsigned int value)
Write bit i without checking i.
Definition bitArray.H:498
int fast_read(const size_t i) const noexcept
Read bit i without any check.
Definition bitArray.H:482
void reserve(const size_t dim)
Reserve memory in advance for the bit array dim dimension.
Definition bitArray.H:344
constexpr size_t size() const noexcept
Returns the dimension of the bit array.
Definition bitArray.H:350
void swap(BitArray &array) noexcept
Definition bitArray.H:541
Bloom filter implementation.
friend Bloom_Filter operator|(const Bloom_Filter &f1, const Bloom_Filter &f2)
Return the union of two compatible Bloom filters.
~Bloom_Filter()=default
Destructor.
size_t size() const noexcept
Return the number of insertions.
auto & operator&=(const Bloom_Filter &f)
In-place intersection.
DynList< size_t > common_hashes(const T &i1, const T &i2) const
Return the intersection of hashes(i1) and hashes(i2).
Bloom_Filter(const size_t n, const double p, unsigned long seed=static_cast< unsigned long >(std::time(nullptr)), Hash_Fct hash_fn=dft_seed_hash_ptr_fct< T >)
Construct a Bloom filter using a desired capacity in insertions.
friend Bloom_Filter operator&(const Bloom_Filter &f1, const Bloom_Filter &f2)
Return the intersection of two compatible Bloom filters.
size_t expected_size() const noexcept
Convenience overload.
bool have_same_hashes(const Bloom_Filter &f) const noexcept
static std::tuple< size_t, size_t > estimate(const size_t n, const double p)
Estimate the parameters of a Bloom filter.
size_t expected_size(const size_t x) const noexcept
Estimate the number of inserted items from the number of bits set.
auto & append(const T &item)
Alias of insert().
std::vector< unsigned long > seeds
Bloom_Filter(const size_t dim, size_t num_hashes, Hash_Fct hash_fn=dft_seed_hash_ptr_fct< T >, const unsigned long seed=static_cast< unsigned long >(std::time(nullptr)))
Construct a Bloom filter with explicit parameters.
size_t get_n() const noexcept
Return the number of insertions performed on the filter.
DynList< size_t > set_bits() const
Return the indexes of bits set to 1.
size_t get_m() const noexcept
Return the number of bits of the filter.
auto & operator|=(const Bloom_Filter &f)
In-place union.
size_t(*)(const T &, unsigned long seed) Hash_Fct
bool contains(const T &item) const
Test membership.
DynList< size_t > hash_seeds() const
Return the internally generated per-hash seeds.
auto & insert(const T &item)
Insert an item.
Bloom_Filter(std::tuple< size_t, size_t > mk, Hash_Fct hash_fn, unsigned long seed)
Private delegating constructor to avoid calling estimate() twice.
Bloom_Filter(const Bloom_Filter &f)
Copy constructor.
Bloom_Filter(Bloom_Filter &&f) noexcept
Move constructor.
size_t capacity() const noexcept
Return the capacity in bits.
DynList< size_t > hashes(const T &item) const
Return the bit positions used by item.
void swap(Bloom_Filter &f) noexcept
Swap this with f in O(1).
size_t get_k() const noexcept
Return the number of hash functions used by the filter.
size_t get_x() const noexcept
Return the number of bits set to 1.
auto & operator=(const Bloom_Filter &f)
Copy assignment.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
A random number generator with the sequences of GSL's gsl_rng_mt19937.
Definition ah-random.H:147
static constexpr result_type max() noexcept
The greatest number of operator()(): 2^32 - 1.
Definition ah-random.H:259
unsigned long get() noexcept
The next number, as operator()().
Definition ah-random.H:289
__gmp_expr< T, __gmp_unary_expr< __gmp_expr< T, U >, __gmp_log2_function > > log2(const __gmp_expr< T, U > &expr)
Definition gmpfrxx.h:4142
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_dim_function > > dim(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4130
Standard hash functions for Aleph types.
Main namespace for Aleph-w library functions.
DynList< T > intercept(const Container< T > &c1, const Container< T > &c2)
Return intersection of two containers as a DynList.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
STL namespace.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Gsl_Compatible_Rng r
Dynamic set implementations based on hash tables.