bloom_filter_mod.py 5.9 KB

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