bloom_filter_mod.py 6.2 KB

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