learnedbf 0.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,551 @@
1
+ import abc
2
+ import logging
3
+ from random import randint
4
+ import mmh3
5
+ import math
6
+ import time
7
+ import numpy as np
8
+ from bitarray import bitarray
9
+ import pybloom_live
10
+ from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
11
+ from sklearn.base import BaseEstimator, ClassifierMixin
12
+
13
+ def check_params_(n, epsilon, m):
14
+ """Check the consistency of the arguments passed to the constructor.
15
+
16
+ :param n: number of keys, defaults to `None`.
17
+ :type n: `int`
18
+ :param epsilon: expected false positive rate, defaults to `None`.
19
+ :type epsilon: `float`
20
+ :param m: size (in bits) of the bitmap, defaults to `None`.
21
+ :type m: `int`
22
+
23
+ :return: a tuple (n, epsilon, m) containing the values of the three
24
+ parameters once consistency has been verified or enforced.
25
+ :type: `tuple`
26
+
27
+ Note: the three parameters are linked by the following relation:
28
+
29
+ .. math::
30
+ m = -(n \\cdot \\log epsilon) / ((\\log 2)^2)
31
+
32
+ thus if they are all specified, the function will verify that this
33
+ relation holds, rasing ValueError otherwise; when two out of three
34
+ parameters are specified, the unspecified one will be obtained by
35
+ enforcing this relation; in all other cases, a ValueError will be
36
+ raised.
37
+
38
+
39
+ """
40
+ num_specified = sum([x is not None for x in (n, epsilon, m)])
41
+ if num_specified == 3:
42
+ if abs(m * np.log(2)**2 + n * np.log(epsilon)) < 10e-6:
43
+ return n, epsilon, m
44
+ else:
45
+ raise ValueError(f'n={n!r}, epsilon={epsilon!r} and '
46
+ f'm={m!r} are not consistent for the '
47
+ 'creation of a Bloom filter')
48
+
49
+ if num_specified != 2:
50
+ raise ValueError('At least two values between n, epsilon, and m '
51
+ 'have to be specified for creating a Bloom filter'
52
+ f' (provided n={n!r}, epsilon={epsilon!r}, '
53
+ f'm={m!r})')
54
+
55
+ if n is None:
56
+ return -m * np.log(2)**2 / np.log(epsilon), epsilon, m
57
+
58
+ if epsilon is None:
59
+ guessed_epsilon = np.exp(-np.log(2)**2 * m / n)
60
+ if guessed_epsilon > 1:
61
+ raise ValueError(f'Inconsistent values (n={n!r}, m={m!r}), '
62
+ 'leading to FPR > 1')
63
+ if guessed_epsilon < 1e-9:
64
+ guessed_epsilon = 1e-9
65
+ return n, guessed_epsilon, m
66
+
67
+ if m is None:
68
+ return n, epsilon, -n * np.log(epsilon) / np.log(2)**2
69
+
70
+ class BloomFilter:
71
+ """Base BloomFilter class."""
72
+
73
+ __metaclass__ = abc.ABCMeta
74
+
75
+ def __init__(self, n=None, epsilon=None):
76
+ """Create an instance of :class:`BloomFilter`.
77
+
78
+ :param n: number of keys, defaults to 10.
79
+ :type n: `int`
80
+ :param epsilon: expected false positive rate, defaults to 0.1.
81
+ :type epsilon: `float`
82
+ """
83
+
84
+ self.n = n
85
+ self.epsilon = epsilon
86
+
87
+ @abc.abstractclassmethod
88
+ def fit(self, X, y=None):
89
+ """Build the Bloom Filter. Abstract method implemented in
90
+ subclasses.
91
+ """
92
+
93
+ return
94
+
95
+ @abc.abstractclassmethod
96
+ def predict(self, X):
97
+ """Computes predictions for a set of queries, each to be checked
98
+ for inclusion in the Bloom Filter. Abstract method implemented
99
+ in subclasses.
100
+ """
101
+
102
+ return
103
+
104
+ def estimate_FPR(self, X, y=None):
105
+ """Compute the empirical false positive rate of the Bloom Filter
106
+ on a set of queries.
107
+
108
+ :param X: queries to be checked.
109
+ :type X: array of numerical arrays
110
+ :param y: labels for the elements in `X`, defaults to `None`.
111
+ :type y: array of `bool`
112
+ :return: empirical false positive rate.
113
+ :rtype: `float`
114
+
115
+ Note: the rate is computed only on non-key values. Thus, if y is
116
+ provided, all true labels (that is, keys) are removed; otherwise,
117
+ all elements in X are assumed to be non-key values. When dealing with
118
+ learned filters, it is important that X does not contain any non-key used to build the filter, in order to avoid overfitting in the
119
+ empirical FPR estimate.
120
+ """
121
+
122
+ check_is_fitted(self, 'is_fitted_')
123
+ if y is not None:
124
+ X, y = check_X_y(X, y)
125
+ X = X[~y]
126
+ X = check_array(X)
127
+ else:
128
+ X = check_array(X)
129
+
130
+ return self.predict(X).sum() / len(X)
131
+
132
+ @abc.abstractclassmethod
133
+ def get_size(self):
134
+ """Return the Bloom Filter size (in bits). Abstract method implemented in
135
+ subclasses.
136
+ """
137
+
138
+ return
139
+
140
+
141
+
142
+ class ClassicalBloomFilterImpl():
143
+
144
+ def __init__(self, n=None, epsilon=None, m=None):
145
+ """
146
+ :param n: number of keys.
147
+ :type n: `int`
148
+ :param epsilon: expected false positive rate.
149
+ :type epsilon: `float`
150
+ """
151
+
152
+ self.n, self.epsilon, self.m = check_params_(n, epsilon, m)
153
+
154
+ # Size of bit array to use
155
+ self.m = self.get_size()
156
+
157
+ # number of hash functions to use
158
+ self.k = self.get_hash_count(self.m, self.n)
159
+
160
+ # Bit array of given size
161
+ self.bit_array = bitarray(self.m)
162
+
163
+ # initialize all bits as 0
164
+ self.bit_array.setall(0)
165
+
166
+ def add(self, item):
167
+ '''
168
+ Add an item in the filter
169
+ '''
170
+ digests = []
171
+ for i in range(self.k):
172
+ # i works as seed to mmh3.hash() function
173
+ digest = mmh3.hash(item, i) % self.m
174
+ digests.append(digest)
175
+
176
+ # set the bit True in bit_array
177
+ self.bit_array[digest] = True
178
+
179
+ def check(self, item):
180
+ '''
181
+ Check for existence of an item in filter
182
+ '''
183
+ for i in range(self.k):
184
+ digest = mmh3.hash(item, i) % self.m
185
+ if not self.bit_array[digest]:
186
+ # if any of bit is False then,its not present
187
+ # in filter
188
+ # else there is probability that it exist
189
+ return False
190
+ return True
191
+
192
+ def get_size(self):
193
+ return int(self.m)
194
+
195
+ @classmethod
196
+ def get_hash_count(self, m, n):
197
+ '''
198
+ Return the hash function(k) to be used using
199
+ following formula
200
+ k = (m/n) *)
201
+
202
+ m : int
203
+ size of(k)ar
204
+ n : int
205
+ number (k)ems exped to be stored in filter
206
+ '''
207
+
208
+ k = (m/n) * math.log(2)
209
+ return int(k)
210
+
211
+ class hashfunc():
212
+
213
+ def __init__(self, m):
214
+ self.m = m
215
+ self.seed = randint(1, 99999999)
216
+
217
+ def __call__(self, x):
218
+ return mmh3.hash(x, self.seed) % self.m
219
+
220
+ class VarhashBloomFilter(BaseEstimator, ClassifierMixin, BloomFilter):
221
+
222
+ def __init__(self, m, k_max):
223
+ """Ada-BF implementation
224
+
225
+ This code is adapted from the repository associated with the paper "Adaptive Learned Bloom Filter (Ada-BF)"
226
+ Repository link: https://github.com/DAIZHENWEI/Ada-BF
227
+
228
+ :param m: the length of the bit array.
229
+ :type key: `int`
230
+ :param k_max: the maximum number of hash function to use.
231
+ :type k_max: `int`
232
+ """
233
+ self.k_max = k_max
234
+ self.m = int(m)
235
+ self.h = [hashfunc(self.m) for _ in range(int(k_max))]
236
+ self.bit_array = bitarray(self.m)
237
+ self.bit_array.setall(0)
238
+
239
+ def add(self, key, k):
240
+ """Adds a key to the filter using a specified number of hash functions.
241
+
242
+ :param key: the key to add.
243
+ :type key: `int`
244
+ :param k: the number of hash function to use.
245
+ :type k: `int`
246
+ """
247
+ for hf in self.h[:int(k)]:
248
+ self.bit_array[hf(key)] = True
249
+
250
+ def check(self, key, k):
251
+ """Test the key membership using a specified number of hash functions.
252
+
253
+ :param key: the key to be checked.
254
+ :type key: `int`
255
+ :param k: the number of hash function to use.
256
+ :type k: `int`
257
+ """
258
+ test_result = False
259
+ match = 0
260
+
261
+ for hf in self.h[:int(k)]:
262
+ match += 1*(self.bit_array[hf(key)] == 1)
263
+ if match == k:
264
+ test_result = True
265
+ return test_result
266
+
267
+ def fit(self, X, y=None, K=None):
268
+ """Build the Bloom Filter.
269
+
270
+ :param X: array containing keys.
271
+ :type X: array of numbers
272
+ :param y: array containing labels for X's elements, defaults to
273
+ `None`.
274
+ :type y: array of `bool`
275
+ :param K: array containing the number of hash functions to be used
276
+ for each element, defaults to`None`.
277
+ :type K: array of `int`
278
+ :return: the fit Varhash Bloom Filter instance.
279
+ :rtype: :class:`VarhashBloomFilter`
280
+ :raises: `ValueError` if `X` is empty.
281
+ :raises: `ValueError` if `K` is `None` or `X` and `K` lengths don't match.
282
+ """
283
+
284
+ if y is None:
285
+ y = [True] * len(X)
286
+
287
+ X, y = check_X_y(X, y)
288
+
289
+ if (~y).any():
290
+ logging.warn('non-keys were removed')
291
+ X = X[y]
292
+ y = y[y]
293
+
294
+ if len(X) == 0:
295
+ raise ValueError('Empty set of keys')
296
+
297
+ if K is None or len(K) != len(X):
298
+ raise ValueError(f'Inconsistent K size passed, '
299
+ f'required {len(X)!r}')
300
+
301
+ #Se passo una lista python trasformo in ndarray
302
+ K = np.array(K)
303
+ if K.dtype not in ['int32', 'int64']:
304
+ raise ValueError(f'Inconsistent K type passed {len(K)!r}, '
305
+ f'required array of `int`')
306
+
307
+ for x, k in zip(X, K):
308
+ self.add(x, k)
309
+
310
+ self.is_fitted_ = True
311
+ self.n_features_in_ = X.shape[1]
312
+
313
+ return self
314
+
315
+ def predict(self, X, K=None):
316
+ """Computes predictions for a set of queries, each to be checked
317
+ for inclusion in the Bloom Filter.
318
+
319
+ :param X: queries to be checked.
320
+ :type X: array of numerical arrays
321
+ :param K: array containing the number of hash functions to be used
322
+ for each element, defaults to`None`.
323
+ :type K: array of `int`
324
+ :return: prediction for each value in `X`.
325
+ :rtype: array of `bool`
326
+ :raises: `ValueError` if `K` is `None` or `X` and `K` lengths don't match.
327
+ """
328
+
329
+ check_is_fitted(self, 'is_fitted_')
330
+ X = check_array(X)
331
+
332
+ if K is None or len(K) != len(X):
333
+ raise ValueError(f'Inconsistent K size passed, '
334
+ f'required {len(X)!r}')
335
+
336
+ K = np.array(K)
337
+ if K.dtype not in ['int32', 'int64']:
338
+ raise ValueError(f'Inconsistent K type passed {len(K)!r}, '
339
+ f'required array of `int`')
340
+
341
+
342
+ return np.array([self.check(x, k) for x,k in zip(X, K)])
343
+
344
+ def get_size(self):
345
+ return int(self.m)
346
+
347
+
348
+ class PyBloomLiveAdapter:
349
+ """Adapter allowing to use objects of
350
+ :class:`pybloom_live.BloomFilter` using the same interface of
351
+ :class:`pybloom.BloomFilter`."""
352
+
353
+ def __init__(self, n=None, epsilon=None, m=None):
354
+ """Create an instance of the adapter.
355
+
356
+ :param n: number of keys, defaults to None.
357
+ :type n: `int`
358
+ :param epsilon: expected false positive rate, defaults to None.
359
+ :type epsilon: `float`
360
+ :param m: size (in bits) of the bitmap, defaults to None.
361
+ :type m: `int`
362
+
363
+ Note: if two out of the three parameters are specified, the remaining
364
+ one will be obtained accordingly. If all the values are specified,
365
+ their consistency will be verified, throwing a ValueError in case of
366
+ failure. In all other cases, a ValueError will be thrown.
367
+ """
368
+
369
+ self.n, self.epsilon, self.m = check_params_(n, epsilon, m)
370
+ self.filter = pybloom_live.BloomFilter(self.n, self.epsilon)
371
+
372
+ def __repr__(self):
373
+ return f'PyBloomLiveAdapter(n={self.n!r}, epsilon={self.epsilon!r})'
374
+
375
+ def add(self, x):
376
+ """Delegate `add` method to :class:`pybloom_live.BloomFilter`
377
+
378
+ :param x: key to be added to the filter.
379
+ :type x: numerical array
380
+ """
381
+
382
+ self.filter.add(x)
383
+
384
+ def check(self, x):
385
+ """Implements `check` of :class:`pybloom.BloomFilter` interface
386
+ in terms of the implementation of operator `in` in
387
+ :class:`pybloom_live.BloomFilter`.
388
+
389
+
390
+ :param x: query to be checked for inclusion in the filter.
391
+ :type x: numerical array
392
+ :return: True if the query is predicted to be in the filter,
393
+ False otherwise.
394
+ :type: `bool`
395
+ """
396
+
397
+ return x in self.filter
398
+
399
+ def get_size(self):
400
+ """Return the size of the Bloom Filter (in bits).
401
+
402
+ :return: size of the bit array (in bits)
403
+ :rtype: `int`
404
+ """
405
+
406
+ return int(self.m) + 1
407
+
408
+
409
+ class ClassicalBloomFilter(BloomFilter, BaseEstimator, ClassifierMixin):
410
+ """Implementation of a classical Bloom Filter."""
411
+
412
+ def __init__(self, n=None, epsilon=None, m=None,
413
+ filter_class=ClassicalBloomFilterImpl):
414
+ """Create an instance of :class:`ClassicalBloomFilter`.
415
+
416
+ :param n: number of keys, defaults to `None`.
417
+ :type n: `int`
418
+ :param epsilon: expected false positive rate, defaults to `None`.
419
+ :type epsilon: `float`
420
+ :param m: size of the bitmap (in bits), defaults to `None`.
421
+ :type m: `int`
422
+
423
+ :param filter_class: used Bloom Filter class, defaults to
424
+ :class:'ClassicalBloomFilterImpl'.
425
+ :type filter_class: `class`
426
+ """
427
+
428
+ self.filter_class = filter_class
429
+ self.bf_ = filter_class(n, epsilon, m)
430
+ self.n, self.epsilon, self.m = self.bf_.n, self.bf_.epsilon, self.bf_.m
431
+
432
+ def __repr__(self):
433
+ args = []
434
+ args.append(f'n={self.n!r}')
435
+ args.append(f'epsilon={self.epsilon!r}')
436
+ if self.filter_class != ClassicalBloomFilter:
437
+ args.append(f'filter_class={self.filter_class!r}')
438
+
439
+ args = ', '.join(args)
440
+ return f'BloomFilter({args})'
441
+
442
+ def add(self, x):
443
+ """Delegate `add` method to the bloom filter implementation
444
+
445
+ :param x: key to be added to the filter.
446
+ """
447
+ self.bf_.add(x)
448
+
449
+ def check(self, x):
450
+ """Delegate `check` method to the bloom filter implementation
451
+
452
+ :param x: key to be added to the filter.
453
+ """
454
+ return self.bf_.check(x)
455
+
456
+
457
+ def fit(self, X, y=None):
458
+ """Build the Bloom Filter.
459
+
460
+ :param X: array containing keys.
461
+ :type X: array of numbers
462
+ :param y: array containing labels for X's elements, defaults to
463
+ `None`.
464
+ :type y: array of `bool`
465
+ :return: the fit Bloom Filter instance.
466
+ :rtype: :class:`BloomFilter`
467
+ :raises: `ValueError` if `X` is empty.
468
+ """
469
+
470
+ if y is None:
471
+ y = [True] * len(X)
472
+
473
+ X, y = check_X_y(X, y)
474
+
475
+ if (~y).any():
476
+ logging.warn('non-keys were removed')
477
+ X = X[y]
478
+ y = y[y]
479
+
480
+ if len(X) == 0:
481
+ raise ValueError('Empty set of keys')
482
+
483
+ if len(X) != self.n:
484
+ raise ValueError(f'Inconsistent set of keys: passed {len(X)!r}, '
485
+ f'required {self.n!r}')
486
+
487
+ for x in X:
488
+ self.add(x)
489
+
490
+ self.is_fitted_ = True
491
+ self.n_features_in_ = X.shape[1]
492
+
493
+ return self
494
+
495
+ def predict(self, X):
496
+ """Computes predictions for a set of queries, each to be checked
497
+ for inclusion in the Bloom Filter.
498
+
499
+ :param X: queries to be checked.
500
+ :type X: array of numerical arrays
501
+ :return: prediction for each value in `X`.
502
+ :rtype: array of `bool`
503
+ """
504
+
505
+ check_is_fitted(self, 'is_fitted_')
506
+ X = check_array(X)
507
+
508
+ return np.array([self.check(x) for x in X])
509
+
510
+ def get_size(self):
511
+ """Return the Bloom Filter size.
512
+
513
+ :return: dictionary describing the overall size of the Bloom Filter,
514
+ in which the key `'bitmap'` is associated to the number of bits
515
+ required by the bitmap of the filter.
516
+ :rtype: `dict`
517
+ """
518
+
519
+ return self.bf_.get_size()
520
+
521
+
522
+ def run_BF(FPR, key_set, testing_list):
523
+ '''
524
+ Crea un BF con key-set = key_set e target fpr = FPR
525
+ e ritorna FPR empirico, dimensione del BF e tempo di accesso medio per
526
+ elemento calcolati testando la struttura su testing_list.
527
+ '''
528
+
529
+ BF = BloomFilter(len(key_set), FPR)
530
+ for url in key_set:
531
+ BF.add(url)
532
+
533
+ fps = 0
534
+ total = 0
535
+ total_time = 0
536
+
537
+ for urlt in testing_list:
538
+ total += 1
539
+ start = time.time()
540
+ result = BF.check(urlt)
541
+ end = time.time()
542
+ total_time += (end-start)
543
+ if result:
544
+ fps += 1
545
+
546
+ avg_fp = fps/total
547
+ # print(f"avg fp : {fps/total} , fps :{fps}, total: {total},
548
+ # {BF.check(testing_list[2])}")
549
+
550
+ # returns empirical FPR, BF size in bytes, and access time per element
551
+ return avg_fp, BF.size/8, (total_time)/len(testing_list)