bloom_filter_mod.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. '''Bloom Filter: Probabilistic set membership testing for large sets'''
  2. # Shamelessly borrowed (under MIT license) from http://code.activestate.com/recipes/577686-bloom-filter/
  3. # About Bloom Filters: http://en.wikipedia.org/wiki/Bloom_filter
  4. # Tweaked a bit by Daniel Richard Stromberg, mostly to make it pass pylint and give it a little nicer
  5. # __init__ parameters.
  6. #mport sys
  7. import math
  8. import array
  9. import random
  10. #mport hashlib
  11. # In the literature:
  12. # k is the number of probes - we call this num_probes_k
  13. # m is the number of bits in the filter - we call this num_bits_m
  14. # n is the ideal number of elements to eventually be stored in the filter - we call this ideal_num_elements_n
  15. # p is the desired error rate when full - we call this error_rate_p
  16. def get_index_bitmask_seed_rnd(bloom_filter, key):
  17. '''Apply num_probes_k hash functions to key. Generate the array index and bitmask corresponding to each result'''
  18. # We're using key as a seed to a pseudorandom number generator
  19. hasher = random.Random(key).randrange
  20. for _ in range(bloom_filter.num_probes_k):
  21. array_index = hasher(bloom_filter.num_words)
  22. bit_within_word_index = hasher(32)
  23. yield array_index, 1 << bit_within_word_index
  24. MERSENNES1 = [ 2**x - 1 for x in 17, 31, 127 ]
  25. MERSENNES2 = [ 2**x - 1 for x in 19, 67, 257 ]
  26. def simple_hash(int_list, prime1, prime2, prime3):
  27. '''Compute a hash value from a list of integers and 3 primes'''
  28. result = 0
  29. for integer in int_list:
  30. result += ((result + integer + prime1) * prime2) % prime3
  31. return result
  32. def hash1(int_list):
  33. '''Basic hash function #1'''
  34. return simple_hash(int_list, MERSENNES1[0], MERSENNES1[1], MERSENNES1[2])
  35. def hash2(int_list):
  36. '''Basic hash function #2'''
  37. return simple_hash(int_list, MERSENNES2[0], MERSENNES2[1], MERSENNES2[2])
  38. def get_index_bitmask_lin_comb(bloom_filter, key):
  39. '''Apply num_probes_k hash functions to key. Generate the array index and bitmask corresponding to each result'''
  40. # This one assumes key is either bytes or str (or other list of integers)
  41. if isinstance(key[0], int):
  42. int_list = key
  43. elif isinstance(key[0], str):
  44. int_list = [ ord(char) for char in key ]
  45. else:
  46. raise TypeError
  47. hash_value1 = hash1(int_list)
  48. hash_value2 = hash2(int_list)
  49. # We're using linear combinations of hash_value1 and hash_value2 to obtain num_probes_k hash functions
  50. for probeno in range(1, bloom_filter.num_probes_k + 1):
  51. bit_index = hash_value1 + probeno * hash_value2
  52. bit_within_word_index = bit_index % 32
  53. array_index = (bit_index // 32) % bloom_filter.num_words
  54. yield array_index, 1 << bit_within_word_index
  55. class Bloom_filter:
  56. '''Probabilistic set membership testing for large sets'''
  57. #def __init__(self, ideal_num_elements_n, error_rate_p, probe_offsetter=get_index_bitmask_seed_rnd):
  58. def __init__(self, ideal_num_elements_n, error_rate_p, probe_offsetter=get_index_bitmask_lin_comb):
  59. if ideal_num_elements_n <= 0:
  60. raise ValueError('ideal_num_elements_n must be > 0')
  61. if not (0 < error_rate_p < 1):
  62. raise ValueError('error_rate_p must be between 0 and 1 inclusive')
  63. self.error_rate_p = error_rate_p
  64. # With fewer elements, we should do very well. With more elements, our error rate "guarantee"
  65. # drops rapidly.
  66. self.ideal_num_elements_n = ideal_num_elements_n
  67. numerator = -1 * self.ideal_num_elements_n * math.log(self.error_rate_p)
  68. denominator = math.log(2) ** 2
  69. #self.num_bits_m = - int((self.ideal_num_elements_n * math.log(self.error_rate_p)) / (math.log(2) ** 2))
  70. real_num_bits_m = numerator / denominator
  71. self.num_bits_m = int(math.ceil(real_num_bits_m))
  72. self.num_words = int((self.num_bits_m + 31) / 32)
  73. self.array_ = array.array('L', [0]) * self.num_words
  74. # AKA num_offsetters
  75. # Verified against http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives
  76. real_num_probes_k = (self.num_bits_m / self.ideal_num_elements_n) * math.log(2)
  77. self.num_probes_k = int(math.ceil(real_num_probes_k))
  78. # This comes close, but often isn't the same value
  79. # alternative_real_num_probes_k = -math.log(self.error_rate_p) / math.log(2)
  80. #
  81. # if abs(real_num_probes_k - alternative_real_num_probes_k) > 1e-6:
  82. # sys.stderr.write('real_num_probes_k: %f, alternative_real_num_probes_k: %f\n' %
  83. # (real_num_probes_k, alternative_real_num_probes_k)
  84. # )
  85. # sys.exit(1)
  86. self.probe_offsetter = probe_offsetter
  87. def __repr__(self):
  88. return 'Bloom_filter(ideal_num_elements_n=%d, error_rate_p=%f, num_bits_m=%d)' % (
  89. self.ideal_num_elements_n,
  90. self.error_rate_p,
  91. self.num_bits_m,
  92. )
  93. def add(self, key):
  94. '''Add an element to the filter'''
  95. for index, mask in self.probe_offsetter(self, key):
  96. self.array_[index] |= mask
  97. def __iadd__(self, key):
  98. self.add(key)
  99. return self
  100. def _match_template(self, bloom_filter):
  101. '''Compare a sort of signature for two bloom filters. Used in preparation for binary operations'''
  102. return (self.num_bits_m == bloom_filter.num_bits_m \
  103. and self.num_probes_k == bloom_filter.num_probes_k \
  104. and self.probe_offsetter == bloom_filter.probe_offsetter)
  105. def union(self, bloom_filter):
  106. '''Compute the set union of two bloom filters'''
  107. if self._match_template(bloom_filter):
  108. self.array_ = [a | b for a, b in zip(self.array_, bloom_filter.array_)]
  109. else:
  110. # Union b/w two unrelated bloom filter raises this
  111. raise ValueError("Mismatched bloom filters")
  112. def __ior__(self, bloom_filter):
  113. self.union(bloom_filter)
  114. return self
  115. def intersection(self, bloom_filter):
  116. '''Compute the set intersection of two bloom filters'''
  117. if self._match_template(bloom_filter):
  118. self.array_ = [a & b for a, b in zip(self.array_, bloom_filter.array_)]
  119. else:
  120. # Intersection b/w two unrelated bloom filter raises this
  121. raise ValueError("Mismatched bloom filters")
  122. def __iand__(self, bloom_filter):
  123. self.intersection(bloom_filter)
  124. return self
  125. def __contains__(self, key):
  126. return all(self.array_[i] & mask for i, mask in self.probe_offsetter(self, key))