learnedbf 0.6.2__tar.gz → 1.1.0__tar.gz

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.
Files changed (57) hide show
  1. learnedbf-1.1.0/PKG-INFO +194 -0
  2. learnedbf-1.1.0/README.md +170 -0
  3. learnedbf-1.1.0/docs/conf.py +34 -0
  4. {learnedbf-0.6.2 → learnedbf-1.1.0}/learnedbf/BF/__init__.py +179 -39
  5. learnedbf-1.1.0/learnedbf/BF/fast_plbf_bloom_filter_adapter.py +15 -0
  6. {learnedbf-0.6.2 → learnedbf-1.1.0}/learnedbf/__init__.py +1280 -238
  7. learnedbf-1.1.0/learnedbf/classifiers/__init__.py +743 -0
  8. learnedbf-1.1.0/learnedbf/fastPLBF/FastPLBF.py +122 -0
  9. learnedbf-1.1.0/learnedbf/fastPLBF/FastPLBF_M.py +124 -0
  10. learnedbf-1.1.0/learnedbf/fastPLBF/FastPLBFpp.py +124 -0
  11. learnedbf-1.1.0/learnedbf/fastPLBF/FastPLBFpp_M.py +126 -0
  12. learnedbf-1.1.0/learnedbf/fastPLBF/PLBF.py +189 -0
  13. learnedbf-1.1.0/learnedbf/fastPLBF/PLBF_M.py +199 -0
  14. learnedbf-1.1.0/learnedbf/fastPLBF/utils/ExpectedFPR.py +27 -0
  15. learnedbf-1.1.0/learnedbf/fastPLBF/utils/OptimalFPR.py +87 -0
  16. learnedbf-1.1.0/learnedbf/fastPLBF/utils/OptimalFPR_M.py +93 -0
  17. learnedbf-1.1.0/learnedbf/fastPLBF/utils/SpaceUsed.py +33 -0
  18. learnedbf-1.1.0/learnedbf/fastPLBF/utils/ThresMaxDivDP.py +124 -0
  19. learnedbf-1.1.0/learnedbf/fastPLBF/utils/calc_DPKL.py +47 -0
  20. learnedbf-1.1.0/learnedbf/fastPLBF/utils/const.py +3 -0
  21. learnedbf-1.1.0/learnedbf/fastPLBF/utils/fast_calc_DPKL.py +65 -0
  22. learnedbf-1.1.0/learnedbf/fastPLBF/utils/matrix_problem_on_monotone_matrix.py +40 -0
  23. learnedbf-1.1.0/learnedbf/fastPLBF/utils/prList.py +125 -0
  24. learnedbf-1.1.0/learnedbf.egg-info/PKG-INFO +194 -0
  25. learnedbf-1.1.0/learnedbf.egg-info/SOURCES.txt +48 -0
  26. learnedbf-1.1.0/learnedbf.egg-info/requires.txt +6 -0
  27. {learnedbf-0.6.2 → learnedbf-1.1.0}/learnedbf.egg-info/top_level.txt +1 -0
  28. {learnedbf-0.6.2 → learnedbf-1.1.0}/pyproject.toml +10 -7
  29. {learnedbf-0.6.2 → learnedbf-1.1.0}/tests/test_AdaBF.py +38 -8
  30. {learnedbf-0.6.2 → learnedbf-1.1.0}/tests/test_BloomFilter.py +16 -1
  31. learnedbf-1.1.0/tests/test_FastPLBF.py +98 -0
  32. learnedbf-1.1.0/tests/test_FastPLBF_M.py +102 -0
  33. learnedbf-1.1.0/tests/test_FastPLBFpp.py +98 -0
  34. learnedbf-1.1.0/tests/test_FastPLBFpp_M.py +100 -0
  35. learnedbf-1.1.0/tests/test_LBF.py +72 -0
  36. learnedbf-1.1.0/tests/test_PLBF.py +99 -0
  37. learnedbf-1.1.0/tests/test_PLBF_M.py +102 -0
  38. learnedbf-1.1.0/tests/test_SLBF.py +131 -0
  39. {learnedbf-0.6.2 → learnedbf-1.1.0}/tests/test_ScoredLinearSVC.py +21 -0
  40. {learnedbf-0.6.2 → learnedbf-1.1.0}/tests/test_ScoredRF.py +11 -0
  41. {learnedbf-0.6.2 → learnedbf-1.1.0}/tests/test_UntrainedClassifiers.py +3 -3
  42. learnedbf-1.1.0/tests/test_VarHashBloomFilter.py +45 -0
  43. learnedbf-0.6.2/PKG-INFO +0 -26
  44. learnedbf-0.6.2/README.md +0 -2
  45. learnedbf-0.6.2/learnedbf/classifiers/__init__.py +0 -329
  46. learnedbf-0.6.2/learnedbf.egg-info/PKG-INFO +0 -26
  47. learnedbf-0.6.2/learnedbf.egg-info/SOURCES.txt +0 -22
  48. learnedbf-0.6.2/learnedbf.egg-info/requires.txt +0 -6
  49. learnedbf-0.6.2/tests/test_SLBF.py +0 -82
  50. {learnedbf-0.6.2 → learnedbf-1.1.0}/LICENSE +0 -0
  51. {learnedbf-0.6.2 → learnedbf-1.1.0}/MANIFEST.in +0 -0
  52. {learnedbf-0.6.2 → learnedbf-1.1.0}/learnedbf/complexity_measures.py +0 -0
  53. {learnedbf-0.6.2 → learnedbf-1.1.0}/learnedbf.egg-info/dependency_links.txt +0 -0
  54. {learnedbf-0.6.2 → learnedbf-1.1.0}/setup.cfg +0 -0
  55. {learnedbf-0.6.2 → learnedbf-1.1.0}/tests/test_ClassicalBloomFilter.py +0 -0
  56. {learnedbf-0.6.2 → learnedbf-1.1.0}/tests/test_ScoredDT.py +0 -0
  57. {learnedbf-0.6.2 → learnedbf-1.1.0}/tests/test_ScoredMLP.py +0 -0
@@ -0,0 +1,194 @@
1
+ Metadata-Version: 2.4
2
+ Name: learnedbf
3
+ Version: 1.1.0
4
+ Summary: A python package for Learned Bloom Filters
5
+ Author-email: SLIMlaboratory <slim@di.unimi.it>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/SLIMlaboratory/learnedbf
8
+ Project-URL: Documentation, https://learnedbf.readthedocs.io/
9
+ Project-URL: Issues, https://github.com/SLIMlaboratory/learnedbf/issues
10
+ Keywords: Bloom filters,Learned Bloom filters,machine learning
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: mmh3>=5.2
18
+ Requires-Dist: numpy>=1.22
19
+ Requires-Dist: packaging>=26
20
+ Requires-Dist: problexity>=0.5.8
21
+ Requires-Dist: pybloom_live>=4
22
+ Requires-Dist: scikit-learn>=1.8
23
+ Dynamic: license-file
24
+
25
+ # learnedbf
26
+
27
+
28
+ <p align="center">
29
+ <a href="https://www.python.org"><img alt="Python version"
30
+ src="https://img.shields.io/badge/Python-3.11%20%7C%203.12-3776AB.svg?style=flat&logo=python&logoColor=white"></a>
31
+ <a href="https://github.com/SLIMlaboratory/learnedbf/actions"><img alt="Actions Status" src="https://github.com/psf/black/workflows/Test/badge.svg"></a>
32
+ <a href="https://learnedbf.readthedocs.io/en/latest/?badge=latest"><img alt="Documentation Status" src="https://readthedocs.org/projects/learnedbf/badge/?version=latest"></a>
33
+ <a href="https://pypi.org/project/learnedbf/"><img alt="PyPI" src="https://img.shields.io/pypi/v/learnedbf"></a>
34
+ <a href="https://github.com/SLIMlaboratory/learnedbf/blob/main/LICENSE"><img alt="License: Apache2.0" src="https://img.shields.io/badge/license-Apache%202.0-blue.svg"></a>
35
+
36
+ </p>
37
+
38
+ A python package for Learned Bloom Filters
39
+
40
+ `learnedbf` is a Python package for Learned Bloom Filters (LBF), intended as
41
+ [Bloom Filters](https://en.wikipedia.org/wiki/Bloom_filter) learned from
42
+ data, as originally proposed by
43
+ [Kraska et al., 2018](https://arxiv.org/abs/1712.01208).
44
+
45
+ This page provides a quick start guide. For more comprehensive information,
46
+ please refer to the [documentation](https://learned.readthedocs.io/en/latest/).
47
+
48
+ ## Installation
49
+
50
+ The package is available on pypi:
51
+
52
+ ```shell
53
+ pip install learnedbf
54
+ ```
55
+
56
+ ## Usage
57
+
58
+ ### Library import
59
+
60
+ The following code imports all libraries used in the subsequent snippets.
61
+
62
+ ```pycon
63
+ >>> import numpy as np
64
+ >>>
65
+ >>> from sklearn.datasets import make_classification
66
+ >>> from sklearn.metrics import accuracy_score
67
+ >>> from sklearn.model_selection import train_test_split
68
+ >>>
69
+ >>> import learnedbf as lbf
70
+ >>> from learnedbf.classifiers import ScoredLinearSVC, ScoredMLP
71
+ >>> from learnedbf import complexity_measures as cpl
72
+ ```
73
+
74
+ ### Evaluating the complexity of a dataset
75
+
76
+ The following code generates datasets of decrerasing complexity using the
77
+ `make_classification` function available in Scikit-learn, evaluating for each
78
+ the corresponding F1v measure.
79
+
80
+ ```pycon
81
+ >>> f1v = cpl.F1v()
82
+ >>>
83
+ >>> sep = np.linspace(0.001, 1.5, 10)
84
+ >>> for s in sep:
85
+ ... X, y = make_classification(n_samples=20000, n_features=2, n_redundant=0,
86
+ ... class_sep=s)
87
+ ... c = f1v.compute(X, y)
88
+ ... print(f'class separation {s:.2f}, F1V {c:.2f}')
89
+ ...
90
+ class separation 0.00, F1V 1.00
91
+ class separation 0.17, F1V 0.86
92
+ class separation 0.33, F1V 0.59
93
+ class separation 0.50, F1V 0.33
94
+ class separation 0.67, F1V 0.27
95
+ class separation 0.83, F1V 0.20
96
+ class separation 1.00, F1V 0.11
97
+ class separation 1.17, F1V 0.11
98
+ class separation 1.33, F1V 0.10
99
+ class separation 1.50, F1V 0.08
100
+ ```
101
+
102
+ ### Training classifiers
103
+
104
+ The following code generates the dataset used in the rest of the examples,
105
+ dividing it in three splits. The first two ones will be used for training a
106
+ classifier and evaluating its performance; the third one will be used afterwards
107
+ to estimate the FPR of the built filters.
108
+
109
+ ```pycon
110
+ >>> X, y = make_classification(n_samples=20000, n_features=2, n_redundant=0,
111
+ >>> class_sep=0.5)
112
+ >>> y = y.astype(bool)
113
+ >>> X_build, X_evaluate, y_build, y_evaluate = train_test_split(X, y,
114
+ ... test_size=0.1)
115
+ >>> X_train, X_test, y_train, y_test = train_test_split(X_build, y_build,
116
+ ... test_size=0.1)
117
+ ```
118
+
119
+ The following code trains a linear SVC and a multi-layer perceptron, comparing
120
+ their performance on the test set using accuracy.
121
+
122
+ ```pycon
123
+ >>> svc = ScoredLinearSVC()
124
+ >>> svc.fit(X_train, y_train)
125
+ >>>
126
+ >>> mlp = ScoredMLP()
127
+ >>> mlp.fit(X_train, y_train)
128
+ >>>
129
+ >>> threshold = 0.65
130
+ >>>
131
+ >>> svc_pred = (svc.predict_score(X_test) > threshold).astype(int)
132
+ >>> mlp_pred = (mlp.predict_score(X_test) > threshold).astype(int)
133
+ >>>
134
+ >>> svc_score = accuracy_score(y_test, svc_pred)
135
+ >>> mlp_score = accuracy_score(y_test, mlp_pred)
136
+ >>>
137
+ >>> print(f'SVC score = {svc_score:.2f}, MLP score = {mlp_score:.2f}')
138
+ SVC score = 0.56, MLP score = 0.85
139
+ ```
140
+
141
+ ### Building a learned Bloom filter
142
+
143
+ The following code builds a LBF using the previously learned MLP, and estimates
144
+ its empirical FPR.
145
+
146
+ ```pycon
147
+ >>> filter = lbf.LBF(epsilon=0.01, classifier=mlp, threshold_test_size = 0.2)
148
+ >>> filter.fit(X_build, y_build)
149
+ LBF(epsilon=0.01, classifier=ScoredMLP(), threshold=0.7520010828581488)
150
+ >>> print(f"FPR:{filter.estimate_FPR(X_evaluate[y_evaluate==0]):.3f}")
151
+ FPR:0.009
152
+ ```
153
+
154
+ The following code builds a LBF backed by a multi-layer perceptron, now training
155
+ the latter on the provided data.
156
+
157
+ ```pycon
158
+ >>> mlp = ScoredMLP()
159
+ >>> filter = lbf.LBF(epsilon=0.01, classifier=mlp, threshold_test_size=0.2)
160
+ >>> filter.fit(X_build, y_build)
161
+ LBF(epsilon=0.01, classifier=ScoredMLP(), threshold=0.7239171235297011)
162
+ >>> print(f"FPR:{filter.estimate_FPR(X_evaluate[y_evaluate==0]):.3f}")
163
+ FPR:0.009
164
+ ```
165
+
166
+ The following code repeats the previous operation, now also performing a model
167
+ selection on the learning rate of the multi-layer perceptron.
168
+
169
+ ```pycon
170
+ >>> mlp = ScoredMLP()
171
+ >>> filter = lbf.LBF(epsilon=0.01, classifier=mlp,
172
+ ... threshold_test_size=0.2,
173
+ ... hyperparameters={
174
+ ... 'learning_rate_init':[0.01, 0.005, 0.001, 0.0005]})
175
+ >>> filter.fit(X_build, y_build)
176
+ LBF(epsilon=0.01, classifier=ScoredMLP(), hyperparameters={'learning_rate_init': [0.01, 0.005, 0.001, 0.0005]}, threshold=0.741263017250332)
177
+ >>> print(f"FPR:{filter.estimate_FPR(X_evaluate[y_evaluate==0]):.3f}")
178
+ FPR:0.009
179
+ ```
180
+
181
+ ## License
182
+
183
+ The library is distributed under the
184
+ [Apache 2.0](https://github.com/SLIMlaboratory/learnedbf/blob/master/LICENSE)
185
+ license. This project includes portions of code from
186
+ [FastPLBF] (https://github.com/atsukisato/FastPLBF), under the MIT License.
187
+ See THIRD_PARTY_LICENSES for details.
188
+
189
+
190
+
191
+ ## Authors
192
+
193
+ `learnedbf` has been designed and implemented by D. Malchiodi, M. Frasca, N. Rinaldi and R. Giancarlo.
194
+
@@ -0,0 +1,170 @@
1
+ # learnedbf
2
+
3
+
4
+ <p align="center">
5
+ <a href="https://www.python.org"><img alt="Python version"
6
+ src="https://img.shields.io/badge/Python-3.11%20%7C%203.12-3776AB.svg?style=flat&logo=python&logoColor=white"></a>
7
+ <a href="https://github.com/SLIMlaboratory/learnedbf/actions"><img alt="Actions Status" src="https://github.com/psf/black/workflows/Test/badge.svg"></a>
8
+ <a href="https://learnedbf.readthedocs.io/en/latest/?badge=latest"><img alt="Documentation Status" src="https://readthedocs.org/projects/learnedbf/badge/?version=latest"></a>
9
+ <a href="https://pypi.org/project/learnedbf/"><img alt="PyPI" src="https://img.shields.io/pypi/v/learnedbf"></a>
10
+ <a href="https://github.com/SLIMlaboratory/learnedbf/blob/main/LICENSE"><img alt="License: Apache2.0" src="https://img.shields.io/badge/license-Apache%202.0-blue.svg"></a>
11
+
12
+ </p>
13
+
14
+ A python package for Learned Bloom Filters
15
+
16
+ `learnedbf` is a Python package for Learned Bloom Filters (LBF), intended as
17
+ [Bloom Filters](https://en.wikipedia.org/wiki/Bloom_filter) learned from
18
+ data, as originally proposed by
19
+ [Kraska et al., 2018](https://arxiv.org/abs/1712.01208).
20
+
21
+ This page provides a quick start guide. For more comprehensive information,
22
+ please refer to the [documentation](https://learned.readthedocs.io/en/latest/).
23
+
24
+ ## Installation
25
+
26
+ The package is available on pypi:
27
+
28
+ ```shell
29
+ pip install learnedbf
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ### Library import
35
+
36
+ The following code imports all libraries used in the subsequent snippets.
37
+
38
+ ```pycon
39
+ >>> import numpy as np
40
+ >>>
41
+ >>> from sklearn.datasets import make_classification
42
+ >>> from sklearn.metrics import accuracy_score
43
+ >>> from sklearn.model_selection import train_test_split
44
+ >>>
45
+ >>> import learnedbf as lbf
46
+ >>> from learnedbf.classifiers import ScoredLinearSVC, ScoredMLP
47
+ >>> from learnedbf import complexity_measures as cpl
48
+ ```
49
+
50
+ ### Evaluating the complexity of a dataset
51
+
52
+ The following code generates datasets of decrerasing complexity using the
53
+ `make_classification` function available in Scikit-learn, evaluating for each
54
+ the corresponding F1v measure.
55
+
56
+ ```pycon
57
+ >>> f1v = cpl.F1v()
58
+ >>>
59
+ >>> sep = np.linspace(0.001, 1.5, 10)
60
+ >>> for s in sep:
61
+ ... X, y = make_classification(n_samples=20000, n_features=2, n_redundant=0,
62
+ ... class_sep=s)
63
+ ... c = f1v.compute(X, y)
64
+ ... print(f'class separation {s:.2f}, F1V {c:.2f}')
65
+ ...
66
+ class separation 0.00, F1V 1.00
67
+ class separation 0.17, F1V 0.86
68
+ class separation 0.33, F1V 0.59
69
+ class separation 0.50, F1V 0.33
70
+ class separation 0.67, F1V 0.27
71
+ class separation 0.83, F1V 0.20
72
+ class separation 1.00, F1V 0.11
73
+ class separation 1.17, F1V 0.11
74
+ class separation 1.33, F1V 0.10
75
+ class separation 1.50, F1V 0.08
76
+ ```
77
+
78
+ ### Training classifiers
79
+
80
+ The following code generates the dataset used in the rest of the examples,
81
+ dividing it in three splits. The first two ones will be used for training a
82
+ classifier and evaluating its performance; the third one will be used afterwards
83
+ to estimate the FPR of the built filters.
84
+
85
+ ```pycon
86
+ >>> X, y = make_classification(n_samples=20000, n_features=2, n_redundant=0,
87
+ >>> class_sep=0.5)
88
+ >>> y = y.astype(bool)
89
+ >>> X_build, X_evaluate, y_build, y_evaluate = train_test_split(X, y,
90
+ ... test_size=0.1)
91
+ >>> X_train, X_test, y_train, y_test = train_test_split(X_build, y_build,
92
+ ... test_size=0.1)
93
+ ```
94
+
95
+ The following code trains a linear SVC and a multi-layer perceptron, comparing
96
+ their performance on the test set using accuracy.
97
+
98
+ ```pycon
99
+ >>> svc = ScoredLinearSVC()
100
+ >>> svc.fit(X_train, y_train)
101
+ >>>
102
+ >>> mlp = ScoredMLP()
103
+ >>> mlp.fit(X_train, y_train)
104
+ >>>
105
+ >>> threshold = 0.65
106
+ >>>
107
+ >>> svc_pred = (svc.predict_score(X_test) > threshold).astype(int)
108
+ >>> mlp_pred = (mlp.predict_score(X_test) > threshold).astype(int)
109
+ >>>
110
+ >>> svc_score = accuracy_score(y_test, svc_pred)
111
+ >>> mlp_score = accuracy_score(y_test, mlp_pred)
112
+ >>>
113
+ >>> print(f'SVC score = {svc_score:.2f}, MLP score = {mlp_score:.2f}')
114
+ SVC score = 0.56, MLP score = 0.85
115
+ ```
116
+
117
+ ### Building a learned Bloom filter
118
+
119
+ The following code builds a LBF using the previously learned MLP, and estimates
120
+ its empirical FPR.
121
+
122
+ ```pycon
123
+ >>> filter = lbf.LBF(epsilon=0.01, classifier=mlp, threshold_test_size = 0.2)
124
+ >>> filter.fit(X_build, y_build)
125
+ LBF(epsilon=0.01, classifier=ScoredMLP(), threshold=0.7520010828581488)
126
+ >>> print(f"FPR:{filter.estimate_FPR(X_evaluate[y_evaluate==0]):.3f}")
127
+ FPR:0.009
128
+ ```
129
+
130
+ The following code builds a LBF backed by a multi-layer perceptron, now training
131
+ the latter on the provided data.
132
+
133
+ ```pycon
134
+ >>> mlp = ScoredMLP()
135
+ >>> filter = lbf.LBF(epsilon=0.01, classifier=mlp, threshold_test_size=0.2)
136
+ >>> filter.fit(X_build, y_build)
137
+ LBF(epsilon=0.01, classifier=ScoredMLP(), threshold=0.7239171235297011)
138
+ >>> print(f"FPR:{filter.estimate_FPR(X_evaluate[y_evaluate==0]):.3f}")
139
+ FPR:0.009
140
+ ```
141
+
142
+ The following code repeats the previous operation, now also performing a model
143
+ selection on the learning rate of the multi-layer perceptron.
144
+
145
+ ```pycon
146
+ >>> mlp = ScoredMLP()
147
+ >>> filter = lbf.LBF(epsilon=0.01, classifier=mlp,
148
+ ... threshold_test_size=0.2,
149
+ ... hyperparameters={
150
+ ... 'learning_rate_init':[0.01, 0.005, 0.001, 0.0005]})
151
+ >>> filter.fit(X_build, y_build)
152
+ LBF(epsilon=0.01, classifier=ScoredMLP(), hyperparameters={'learning_rate_init': [0.01, 0.005, 0.001, 0.0005]}, threshold=0.741263017250332)
153
+ >>> print(f"FPR:{filter.estimate_FPR(X_evaluate[y_evaluate==0]):.3f}")
154
+ FPR:0.009
155
+ ```
156
+
157
+ ## License
158
+
159
+ The library is distributed under the
160
+ [Apache 2.0](https://github.com/SLIMlaboratory/learnedbf/blob/master/LICENSE)
161
+ license. This project includes portions of code from
162
+ [FastPLBF] (https://github.com/atsukisato/FastPLBF), under the MIT License.
163
+ See THIRD_PARTY_LICENSES for details.
164
+
165
+
166
+
167
+ ## Authors
168
+
169
+ `learnedbf` has been designed and implemented by D. Malchiodi, M. Frasca, N. Rinaldi and R. Giancarlo.
170
+
@@ -0,0 +1,34 @@
1
+ # Configuration file for the Sphinx documentation builder.
2
+ #
3
+ # For the full list of built-in configuration values, see the documentation:
4
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html
5
+
6
+ # -- Project information -----------------------------------------------------
7
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
8
+
9
+ import os
10
+ import sys
11
+ sys.path.insert(0, os.path.abspath('..'))
12
+
13
+ project = 'learnedbf'
14
+ copyright = '2025, SLIM laboratory'
15
+ author = 'SLIM laboratory'
16
+ release = '1.0.0'
17
+
18
+ # -- General configuration ---------------------------------------------------
19
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
20
+
21
+ extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon',
22
+ 'sphinx_autodoc_typehints']
23
+
24
+
25
+ templates_path = ['_templates']
26
+ exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
27
+
28
+
29
+
30
+ # -- Options for HTML output -------------------------------------------------
31
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
32
+
33
+ html_theme = 'sphinx_rtd_theme'
34
+ html_static_path = ['_static']
@@ -1,4 +1,5 @@
1
1
  import abc
2
+ import json
2
3
  import logging
3
4
  from random import randint
4
5
  import mmh3
@@ -10,6 +11,14 @@ import pybloom_live
10
11
  from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
11
12
  from sklearn.base import BaseEstimator, ClassifierMixin
12
13
 
14
+
15
+ def _numpy_default(o):
16
+ if isinstance(o, np.generic):
17
+ return o.item()
18
+ if isinstance(o, np.ndarray):
19
+ return o.tolist()
20
+ raise TypeError(f"Object of type {o.__class__.__name__} is not JSON serializable")
21
+
13
22
  def check_params_(n, epsilon, m):
14
23
  """Check the consistency of the arguments passed to the constructor.
15
24
 
@@ -84,7 +93,7 @@ class BloomFilter:
84
93
  self.n = n
85
94
  self.epsilon = epsilon
86
95
 
87
- @abc.abstractclassmethod
96
+ @abc.abstractmethod
88
97
  def fit(self, X, y=None):
89
98
  """Build the Bloom Filter. Abstract method implemented in
90
99
  subclasses.
@@ -92,7 +101,7 @@ class BloomFilter:
92
101
 
93
102
  return
94
103
 
95
- @abc.abstractclassmethod
104
+ @abc.abstractmethod
96
105
  def predict(self, X):
97
106
  """Computes predictions for a set of queries, each to be checked
98
107
  for inclusion in the Bloom Filter. Abstract method implemented
@@ -129,7 +138,7 @@ class BloomFilter:
129
138
 
130
139
  return self.predict(X).sum() / len(X)
131
140
 
132
- @abc.abstractclassmethod
141
+ @abc.abstractmethod
133
142
  def get_size(self):
134
143
  """Return the Bloom Filter size (in bits). Abstract method implemented in
135
144
  subclasses.
@@ -137,6 +146,46 @@ class BloomFilter:
137
146
 
138
147
  return
139
148
 
149
+ @abc.abstractmethod
150
+ def to_json(self, force=False):
151
+ """Export the filter to a JSON representation.
152
+
153
+ :param force: if True, the export will be forced even if the size of
154
+ the filter is too large.
155
+ :type force: bool
156
+ """
157
+ return
158
+
159
+ def export(self, path):
160
+ """Export the filter to a file.
161
+
162
+ :param path: path to the file where the filter will be exported.
163
+ :type path: str
164
+ """
165
+ with open(path, 'w') as f:
166
+ json.dump(self.to_json(), f, default=_numpy_default)
167
+
168
+ @abc.abstractmethod
169
+ def from_json(self, repr):
170
+ """Import the filter from a JSON representation.
171
+
172
+ :param repr: JSON representation of the filter.
173
+ :type repr: dict
174
+ """
175
+ return
176
+
177
+ def import_(self, path):
178
+ """Import the filter from a file.
179
+
180
+ :param path: path to the file where the filter will be imported
181
+ from.
182
+ :type path: str
183
+ """
184
+ with open(path, 'r') as f:
185
+ repr = json.load(f)
186
+
187
+ self.from_json(repr)
188
+
140
189
 
141
190
 
142
191
  class ClassicalBloomFilterImpl():
@@ -167,10 +216,11 @@ class ClassicalBloomFilterImpl():
167
216
  '''
168
217
  Add an item in the filter
169
218
  '''
219
+ item_bytes = item if isinstance(item, bytes) else item.tobytes()
170
220
  digests = []
171
221
  for i in range(self.k):
172
222
  # i works as seed to mmh3.hash() function
173
- digest = mmh3.hash(item, i) % self.m
223
+ digest = mmh3.hash(item_bytes, i) % self.m
174
224
  digests.append(digest)
175
225
 
176
226
  # set the bit True in bit_array
@@ -180,8 +230,9 @@ class ClassicalBloomFilterImpl():
180
230
  '''
181
231
  Check for existence of an item in filter
182
232
  '''
233
+ item_bytes = item if isinstance(item, bytes) else item.tobytes()
183
234
  for i in range(self.k):
184
- digest = mmh3.hash(item, i) % self.m
235
+ digest = mmh3.hash(item_bytes, i) % self.m
185
236
  if not self.bit_array[digest]:
186
237
  # if any of bit is False then,its not present
187
238
  # in filter
@@ -206,16 +257,19 @@ class ClassicalBloomFilterImpl():
206
257
  '''
207
258
 
208
259
  k = (m/n) * math.log(2)
209
- return int(k)
260
+ return math.ceil(k)
210
261
 
211
262
  class hashfunc():
212
263
 
213
- def __init__(self, m):
264
+ def __init__(self, m, seed=None):
214
265
  self.m = m
215
- self.seed = randint(1, 99999999)
266
+ if seed is None:
267
+ self.seed = randint(1, 99999999)
268
+ else:
269
+ self.seed = seed
216
270
 
217
271
  def __call__(self, x):
218
- return mmh3.hash(x, self.seed) % self.m
272
+ return mmh3.hash(x.tobytes(), self.seed) % self.m
219
273
 
220
274
  class VarhashBloomFilter(BaseEstimator, ClassifierMixin, BloomFilter):
221
275
 
@@ -232,6 +286,7 @@ class VarhashBloomFilter(BaseEstimator, ClassifierMixin, BloomFilter):
232
286
  """
233
287
  self.k_max = k_max
234
288
  self.m = int(m)
289
+ self.seed = randint(1, 99999999)
235
290
  self.h = [hashfunc(self.m) for _ in range(int(k_max))]
236
291
  self.bit_array = bitarray(self.m)
237
292
  self.bit_array.setall(0)
@@ -344,6 +399,64 @@ class VarhashBloomFilter(BaseEstimator, ClassifierMixin, BloomFilter):
344
399
  def get_size(self):
345
400
  return int(self.m)
346
401
 
402
+ def to_json(self):
403
+ """Return a JSON representation of the VarHashBloom Filter.
404
+
405
+ :return: dictionary containing the JSON representation of the
406
+ Bloom Filter.
407
+ :rtype: `dict`
408
+ """
409
+
410
+ check_is_fitted(self, 'is_fitted_')
411
+ repr = {}
412
+ repr['m'] = self.m
413
+ repr['k_max'] = self.k_max
414
+ repr['bitmap'] = self.bit_array.tolist()
415
+ repr['seeds'] = [_.seed for _ in self.h]
416
+
417
+ repr['is_fitted_'] = self.is_fitted_
418
+
419
+ return repr
420
+
421
+ def from_json(self, repr):
422
+ """Load a VarHash Bloom Filter from its JSON representation.
423
+
424
+ :param repr: dictionary containing the JSON representation of the
425
+ Bloom Filter.
426
+ :type repr: `dict`
427
+ """
428
+
429
+ self.m = repr['m']
430
+ self.k_max = repr['k_max']
431
+ self.bit_array = bitarray(repr['bitmap'])
432
+ seeds = repr['seeds']
433
+ self.h = [hashfunc(self.m, seed) for seed in seeds]
434
+
435
+ self.is_fitted_ = repr['is_fitted_']
436
+
437
+ def __eq__(self, other):
438
+ if not isinstance(other, VarhashBloomFilter):
439
+ return NotImplemented
440
+
441
+ if self.get_params(deep=False) != other.get_params(deep=False):
442
+ return False
443
+
444
+ self_fitted = (hasattr(self, "is_fitted_")
445
+ and hasattr(self, "bit_array"))
446
+ other_fitted = (hasattr(other, "is_fitted_")
447
+ and hasattr(other, "bit_array"))
448
+
449
+ if self_fitted != other_fitted:
450
+ return False
451
+
452
+ if self.m != other.m or self.k_max != other.k_max:
453
+ return False
454
+
455
+ if self_fitted and other_fitted:
456
+ return self.bit_array == other.bit_array
457
+
458
+ return True
459
+
347
460
 
348
461
  class PyBloomLiveAdapter:
349
462
  """Adapter allowing to use objects of
@@ -517,35 +630,62 @@ class ClassicalBloomFilter(BloomFilter, BaseEstimator, ClassifierMixin):
517
630
  """
518
631
 
519
632
  return self.bf_.get_size()
633
+
634
+ def to_json(self):
635
+ """Return a JSON representation of the Bloom Filter.
636
+
637
+ :return: dictionary containing the JSON representation of the
638
+ Bloom Filter.
639
+ :rtype: `dict`
640
+ """
520
641
 
642
+ check_is_fitted(self, 'is_fitted_')
643
+ repr = {}
644
+ repr['n'] = self.n
645
+ repr['epsilon'] = self.epsilon
646
+ repr['m'] = self.m
647
+ repr['filter_class'] = self.filter_class.__name__
648
+ repr['bitmap'] = self.bf_.bit_array.tolist()
649
+ repr['is_fitted_'] = self.is_fitted_
650
+
651
+ return repr
652
+
653
+ def from_json(self, repr):
654
+ """Load a Bloom Filter from its JSON representation.
655
+
656
+ :param repr: dictionary containing the JSON representation of the
657
+ Bloom Filter.
658
+ :type repr: `dict`
659
+ """
660
+
661
+ self.n = repr['n']
662
+ self.epsilon = repr['epsilon']
663
+ self.m = repr['m']
664
+ self.filter_class = globals()[repr['filter_class']]
665
+ self.bf_ = self.filter_class(self.n, self.epsilon)
666
+ self.bf_.bit_array = bitarray(repr['bitmap'])
667
+ self.is_fitted_ = repr['is_fitted_']
668
+
669
+ def __eq__(self, other):
670
+ if not isinstance(other, ClassicalBloomFilter):
671
+ return NotImplemented
672
+
673
+ if self.get_params(deep=False) != other.get_params(deep=False):
674
+ return False
675
+
676
+ self_fitted = (hasattr(self, "bf_")
677
+ and hasattr(self.bf_, "bit_array"))
678
+ other_fitted = (hasattr(other, "bf_")
679
+ and hasattr(other.bf_, "bit_array"))
680
+
681
+ if self_fitted != other_fitted:
682
+ return False
683
+
684
+ if self.n != other.n or self.epsilon != other.epsilon or self.m != other.m:
685
+ return False
686
+
687
+ if self_fitted and other_fitted:
688
+ return self.bf_.bit_array == other.bf_.bit_array
689
+
690
+ return True
521
691
 
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)