bloom_filter_mod.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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. import os
  9. #mport sys
  10. import math
  11. import mmap as mmap_mod
  12. import array
  13. import random
  14. #mport bufsock
  15. #mport hashlib
  16. #mport numbers
  17. import python2x3
  18. # In the literature:
  19. # k is the number of probes - we call this num_probes_k
  20. # m is the number of bits in the filter - we call this num_bits_m
  21. # n is the ideal number of elements to eventually be stored in the filter - we call this ideal_num_elements_n
  22. # p is the desired error rate when full - we call this error_rate_p
  23. def my_range(num_values):
  24. '''Generate numbers from 0..num_values-1'''
  25. value = 0
  26. while value < num_values:
  27. yield value
  28. value += 1
  29. # In the abstract, this is what we want &= and |= to do, but especially for disk-based filters, this is extremely slow
  30. #class Backend_set_operations:
  31. # '''Provide &= and |= for backends'''
  32. # # pylint: disable=W0232
  33. # # W0232: We don't need an __init__ method; we're never instantiated directly
  34. # def __iand__(self, other):
  35. # assert self.num_bits == other.num_bits
  36. #
  37. # for bitno in my_range(num_bits):
  38. # if self.is_set(bitno) and other.is_set(bitno):
  39. # self[bitno].set()
  40. # else:
  41. # self[bitno].clear()
  42. #
  43. # def __ior__(self, other):
  44. # assert self.num_bits == other.num_bits
  45. #
  46. # for bitno in xrange(num_bits):
  47. # if self[bitno] or other[bitno]:
  48. # self[bitno].set()
  49. # else:
  50. # self[bitno].clear()
  51. class Mmap_backend:
  52. '''
  53. Backend storage for our "array of bits" using an mmap'd file.
  54. Please note that this has only been tested on Linux so far: 2011-11-01.
  55. '''
  56. effs = 2^8 - 1
  57. def __init__(self, num_bits, filename):
  58. self.num_bits = num_bits
  59. self.num_chars = (self.num_bits + 7) // 8
  60. flags = os.O_RDWR | os.O_CREAT
  61. if hasattr(os, 'O_BINARY'):
  62. flags |= getattr(os, 'O_BINARY')
  63. self.file_ = os.open(filename, flags)
  64. os.lseek(self.file_, self.num_chars + 1, os.SEEK_SET)
  65. os.write(self.file_, python2x3.null_byte)
  66. self.mmap = mmap_mod.mmap(self.file_, self.num_chars)
  67. def is_set(self, bitno):
  68. '''Return true iff bit number bitno is set'''
  69. byteno, bit_within_wordno = divmod(bitno, 8)
  70. mask = 1 << bit_within_wordno
  71. char = self.mmap[byteno]
  72. if isinstance(char, str):
  73. byte = ord(char)
  74. else:
  75. byte = int(char)
  76. return byte & mask
  77. def set(self, bitno):
  78. '''set bit number bitno to true'''
  79. byteno, bit_within_byteno = divmod(bitno, 8)
  80. mask = 1 << bit_within_byteno
  81. char = self.mmap[byteno]
  82. byte = ord(char)
  83. byte |= mask
  84. self.mmap[byteno] = chr(byte)
  85. def clear(self, bitno):
  86. '''clear bit number bitno - set it to false'''
  87. byteno, bit_within_byteno = divmod(bitno, 8)
  88. mask = 1 << bit_within_byteno
  89. char = self.mmap[byteno]
  90. byte = ord(char)
  91. byte &= Mmap_backend.effs - mask
  92. self.mmap[byteno] = chr(byte)
  93. def __iand__(self, other):
  94. assert self.num_bits == other.num_bits
  95. for byteno in my_range(self.num_chars):
  96. self.mmap[byteno] = chr(ord(self.mmap[byteno]) & ord(other.mmap[byteno]))
  97. return self
  98. def __ior__(self, other):
  99. assert self.num_bits == other.num_bits
  100. for byteno in my_range(self.num_chars):
  101. self.mmap[byteno] = chr(ord(self.mmap[byteno]) | ord(other.mmap[byteno]))
  102. return self
  103. def close(self):
  104. '''Close the file'''
  105. os.close(self.file_)
  106. class File_seek_backend:
  107. '''Backend storage for our "array of bits" using a file in which we seek'''
  108. effs = 2 ^ 8 - 1
  109. def __init__(self, num_bits, filename):
  110. self.num_bits = num_bits
  111. self.num_chars = (self.num_bits + 7) // 8
  112. flags = os.O_RDWR | os.O_CREAT
  113. if hasattr(os, 'O_BINARY'):
  114. flags |= getattr(os, 'O_BINARY')
  115. self.file_ = os.open(filename, flags)
  116. os.lseek(self.file_, self.num_chars + 1, os.SEEK_SET)
  117. os.write(self.file_, python2x3.null_byte)
  118. def is_set(self, bitno):
  119. '''Return true iff bit number bitno is set'''
  120. byteno, bit_within_wordno = divmod(bitno, 8)
  121. mask = 1 << bit_within_wordno
  122. os.lseek(self.file_, byteno, os.SEEK_SET)
  123. char = os.read(self.file_, 1)
  124. if isinstance(char, str):
  125. byte = ord(char)
  126. else:
  127. byte = int(char)
  128. return byte & mask
  129. def set(self, bitno):
  130. '''set bit number bitno to true'''
  131. byteno, bit_within_byteno = divmod(bitno, 8)
  132. mask = 1 << bit_within_byteno
  133. os.lseek(self.file_, byteno, os.SEEK_SET)
  134. char = os.read(self.file_, 1)
  135. if isinstance(char, str):
  136. byte = ord(char)
  137. was_char = True
  138. else:
  139. byte = char
  140. was_char = False
  141. byte |= mask
  142. os.lseek(self.file_, byteno, os.SEEK_SET)
  143. if was_char:
  144. os.write(self.file_, chr(byte))
  145. else:
  146. os.write(self.file_, byte)
  147. def clear(self, bitno):
  148. '''clear bit number bitno - set it to false'''
  149. byteno, bit_within_byteno = divmod(bitno, 8)
  150. mask = 1 << bit_within_byteno
  151. os.lseek(self.file_, byteno, os.SEEK_SET)
  152. char = os.read(self.file_, 1)
  153. if isinstance(char, str):
  154. byte = ord(char)
  155. was_char = True
  156. else:
  157. byte = int(char)
  158. was_char = False
  159. byte &= File_seek_backend.effs - mask
  160. os.lseek(self.file_, byteno, os.SEEK_SET)
  161. if was_char:
  162. os.write(chr(byte))
  163. else:
  164. os.write(byte)
  165. # These are quite slow ways to do iand and ior, but they should work, and a faster version is going to take more time
  166. def __iand__(self, other):
  167. assert self.num_bits == other.num_bits
  168. for bitno in my_range(self.num_bits):
  169. if self.is_set(bitno) and other.is_set(bitno):
  170. self.set(bitno)
  171. else:
  172. self.clear(bitno)
  173. return self
  174. def __ior__(self, other):
  175. assert self.num_bits == other.num_bits
  176. for bitno in my_range(self.num_bits):
  177. if self.is_set(bitno) or other.is_set(bitno):
  178. self.set(bitno)
  179. else:
  180. self.clear(bitno)
  181. return self
  182. def close(self):
  183. '''Close the file'''
  184. os.close(self.file_)
  185. class Array_then_file_seek_backend:
  186. # pylint: disable=R0902
  187. # R0902: We kinda need a bunch of instance attributes
  188. '''
  189. Backend storage for our "array of bits" using a python array of integers up to some maximum number of bytes, then spilling over to a file.
  190. This is -not- a cache; we instead save the leftmost bits in RAM, and the rightmost bits (if necessary) in a file.
  191. On open, we read from the file to RAM. On close, we write from RAM to the file.
  192. '''
  193. effs = 2^8 - 1
  194. def __init__(self, num_bits, filename, max_bytes_in_memory):
  195. self.num_bits = num_bits
  196. num_chars = (self.num_bits + 7) // 8
  197. self.filename = filename
  198. self.max_bytes_in_memory = max_bytes_in_memory
  199. self.bits_in_memory = min(num_bits, self.max_bytes_in_memory * 8)
  200. self.bits_in_file = max(self.num_bits - self.bits_in_memory, 0)
  201. self.bytes_in_memory = (self.bits_in_memory + 7) // 8
  202. self.bytes_in_file = (self.bits_in_file + 7) // 8
  203. self.array_ = array.array('B', [0]) * self.bytes_in_memory
  204. flags = os.O_RDWR | os.O_CREAT
  205. if hasattr(os, 'O_BINARY'):
  206. flags |= getattr(os, 'O_BINARY')
  207. self.file_ = os.open(filename, flags)
  208. os.lseek(self.file_, num_chars + 1, os.SEEK_SET)
  209. os.write(self.file_, python2x3.null_byte)
  210. os.lseek(self.file_, 0, os.SEEK_SET)
  211. offset = 0
  212. intended_block_len = 2**17
  213. while True:
  214. if offset + intended_block_len < self.bytes_in_memory:
  215. block = os.read(self.file_, intended_block_len)
  216. elif offset < self.bytes_in_memory:
  217. block = os.read(self.file_, self.bytes_in_memory - offset)
  218. else:
  219. break
  220. for index_in_block, character in enumerate(block):
  221. self.array_[offset + index_in_block] = ord(character)
  222. offset += intended_block_len
  223. def is_set(self, bitno):
  224. '''Return true iff bit number bitno is set'''
  225. byteno, bit_within_byteno = divmod(bitno, 8)
  226. mask = 1 << bit_within_byteno
  227. if byteno < self.bytes_in_memory:
  228. return self.array_[byteno] & mask
  229. else:
  230. os.lseek(self.file_, byteno, os.SEEK_SET)
  231. char = os.read(self.file_, 1)
  232. if isinstance(char, str):
  233. byte = ord(char)
  234. else:
  235. byte = int(char)
  236. return byte & mask
  237. def set(self, bitno):
  238. '''set bit number bitno to true'''
  239. byteno, bit_within_byteno = divmod(bitno, 8)
  240. mask = 1 << bit_within_byteno
  241. if byteno < self.bytes_in_memory:
  242. self.array_[byteno] |= mask
  243. else:
  244. os.lseek(self.file_, byteno, os.SEEK_SET)
  245. char = os.read(self.file_, 1)
  246. if isinstance(char, str):
  247. byte = ord(char)
  248. was_char = True
  249. else:
  250. byte = char
  251. was_char = False
  252. byte |= mask
  253. os.lseek(self.file_, byteno, os.SEEK_SET)
  254. if was_char:
  255. os.write(self.file_, chr(byte))
  256. else:
  257. os.write(self.file_, byte)
  258. def clear(self, bitno):
  259. '''clear bit number bitno - set it to false'''
  260. byteno, bit_within_byteno = divmod(bitno, 8)
  261. mask = Array_backend.effs - (1 << bit_within_byteno)
  262. if byteno < self.bytes_in_memory:
  263. self.array_[byteno] &= mask
  264. else:
  265. os.lseek(self.file_, byteno, os.SEEK_SET)
  266. char = os.read(self.file_, 1)
  267. if isinstance(char, str):
  268. byte = ord(char)
  269. was_char = True
  270. else:
  271. byte = int(char)
  272. was_char = False
  273. byte &= File_seek_backend.effs - mask
  274. os.lseek(self.file_, byteno, os.SEEK_SET)
  275. if was_char:
  276. os.write(chr(byte))
  277. else:
  278. os.write(byte)
  279. # These are quite slow ways to do iand and ior, but they should work, and a faster version is going to take more time
  280. def __iand__(self, other):
  281. assert self.num_bits == other.num_bits
  282. for bitno in my_range(self.num_bits):
  283. if self.is_set(bitno) and other.is_set(bitno):
  284. self.set(bitno)
  285. else:
  286. self.clear(bitno)
  287. return self
  288. def __ior__(self, other):
  289. assert self.num_bits == other.num_bits
  290. for bitno in my_range(self.num_bits):
  291. if self.is_set(bitno) or other.is_set(bitno):
  292. self.set(bitno)
  293. else:
  294. self.clear(bitno)
  295. return self
  296. def close(self):
  297. '''Write the in-memory portion to disk, leave the already-on-disk portion unchanged'''
  298. os.lseek(self.file_, 0, os.SEEK_SET)
  299. for index in my_range(self.bytes_in_memory):
  300. self.file_.write(self.array_[index])
  301. os.close(self.file_)
  302. class Array_backend:
  303. '''Backend storage for our "array of bits" using a python array of integers'''
  304. effs = 2 ^ 32 - 1
  305. def __init__(self, num_bits):
  306. self.num_bits = num_bits
  307. self.num_words = (self.num_bits + 31) // 32
  308. self.array_ = array.array('L', [0]) * self.num_words
  309. def is_set(self, bitno):
  310. '''Return true iff bit number bitno is set'''
  311. wordno, bit_within_wordno = divmod(bitno, 32)
  312. mask = 1 << bit_within_wordno
  313. return self.array_[wordno] & mask
  314. def set(self, bitno):
  315. '''set bit number bitno to true'''
  316. wordno, bit_within_wordno = divmod(bitno, 32)
  317. mask = 1 << bit_within_wordno
  318. self.array_[wordno] |= mask
  319. def clear(self, bitno):
  320. '''clear bit number bitno - set it to false'''
  321. wordno, bit_within_wordno = divmod(bitno, 32)
  322. mask = Array_backend.effs - (1 << bit_within_wordno)
  323. self.array_[wordno] &= mask
  324. # It'd be nice to do __iand__ and __ior__ in a base class, but that'd be Much slower
  325. def __iand__(self, other):
  326. assert self.num_bits == other.num_bits
  327. for wordno in my_range(self.num_words):
  328. self.array_[wordno] &= other.array_[wordno]
  329. return self
  330. def __ior__(self, other):
  331. assert self.num_bits == other.num_bits
  332. for wordno in my_range(self.num_words):
  333. self.array_[wordno] |= other.array_[wordno]
  334. return self
  335. def close(self):
  336. '''Noop for compatibility with the file+seek backend'''
  337. pass
  338. def get_bitno_seed_rnd(bloom_filter, key):
  339. '''Apply num_probes_k hash functions to key. Generate the array index and bitmask corresponding to each result'''
  340. # We're using key as a seed to a pseudorandom number generator
  341. hasher = random.Random(key).randrange
  342. for dummy in range(bloom_filter.num_probes_k):
  343. bitno = hasher(bloom_filter.num_bits_m)
  344. yield bitno % bloom_filter.num_bits_m
  345. MERSENNES1 = [ 2 ** x - 1 for x in [ 17, 31, 127 ] ]
  346. MERSENNES2 = [ 2 ** x - 1 for x in [ 19, 67, 257 ] ]
  347. def simple_hash(int_list, prime1, prime2, prime3):
  348. '''Compute a hash value from a list of integers and 3 primes'''
  349. result = 0
  350. for integer in int_list:
  351. result += ((result + integer + prime1) * prime2) % prime3
  352. return result
  353. def hash1(int_list):
  354. '''Basic hash function #1'''
  355. return simple_hash(int_list, MERSENNES1[0], MERSENNES1[1], MERSENNES1[2])
  356. def hash2(int_list):
  357. '''Basic hash function #2'''
  358. return simple_hash(int_list, MERSENNES2[0], MERSENNES2[1], MERSENNES2[2])
  359. def get_bitno_lin_comb(bloom_filter, key):
  360. '''Apply num_probes_k hash functions to key. Generate the array index and bitmask corresponding to each result'''
  361. # This one assumes key is either bytes or str (or other list of integers)
  362. # 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
  363. if hasattr(key, '__divmod__'):
  364. int_list = []
  365. temp = key
  366. while temp:
  367. quotient, remainder = divmod(temp, 256)
  368. int_list.append(remainder)
  369. temp = quotient
  370. elif hasattr(key[0], '__divmod__'):
  371. int_list = key
  372. elif isinstance(key[0], str):
  373. int_list = [ ord(char) for char in key ]
  374. else:
  375. raise TypeError('Sorry, I do not know how to hash this type')
  376. hash_value1 = hash1(int_list)
  377. hash_value2 = hash2(int_list)
  378. # We're using linear combinations of hash_value1 and hash_value2 to obtain num_probes_k hash functions
  379. for probeno in range(1, bloom_filter.num_probes_k + 1):
  380. bit_index = hash_value1 + probeno * hash_value2
  381. yield bit_index % bloom_filter.num_bits_m
  382. def try_unlink(filename):
  383. '''unlink a file. Don't complain if it's not there'''
  384. try:
  385. os.unlink(filename)
  386. except OSError:
  387. pass
  388. return
  389. class Bloom_filter:
  390. '''Probabilistic set membership testing for large sets'''
  391. #def __init__(self, ideal_num_elements_n, error_rate_p, probe_offsetter=get_index_bitmask_seed_rnd):
  392. def __init__(self, ideal_num_elements_n, error_rate_p, probe_bitnoer=get_bitno_lin_comb, filename=None, start_fresh=False):
  393. # pylint: disable=R0913
  394. # R0913: We want a few arguments
  395. if ideal_num_elements_n <= 0:
  396. raise ValueError('ideal_num_elements_n must be > 0')
  397. if not (0 < error_rate_p < 1):
  398. raise ValueError('error_rate_p must be between 0 and 1 inclusive')
  399. self.error_rate_p = error_rate_p
  400. # With fewer elements, we should do very well. With more elements, our error rate "guarantee"
  401. # drops rapidly.
  402. self.ideal_num_elements_n = ideal_num_elements_n
  403. numerator = -1 * self.ideal_num_elements_n * math.log(self.error_rate_p)
  404. denominator = math.log(2) ** 2
  405. #self.num_bits_m = - int((self.ideal_num_elements_n * math.log(self.error_rate_p)) / (math.log(2) ** 2))
  406. real_num_bits_m = numerator / denominator
  407. self.num_bits_m = int(math.ceil(real_num_bits_m))
  408. if filename is None:
  409. self.backend = Array_backend(self.num_bits_m)
  410. elif isinstance(filename, tuple) and isinstance(filename[1], int):
  411. if start_fresh:
  412. try_unlink(filename[0])
  413. if filename[1] == -1:
  414. self.backend = Mmap_backend(self.num_bits_m, filename[0])
  415. else:
  416. self.backend = Array_then_file_seek_backend(self.num_bits_m, filename[0], filename[1])
  417. else:
  418. if start_fresh:
  419. try_unlink(filename)
  420. self.backend = File_seek_backend(self.num_bits_m, filename)
  421. #array.array('L', [0]) * ((self.num_bits_m + 31) // 32)
  422. # AKA num_offsetters
  423. # Verified against http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives
  424. real_num_probes_k = (self.num_bits_m / self.ideal_num_elements_n) * math.log(2)
  425. self.num_probes_k = int(math.ceil(real_num_probes_k))
  426. # This comes close, but often isn't the same value
  427. # alternative_real_num_probes_k = -math.log(self.error_rate_p) / math.log(2)
  428. #
  429. # if abs(real_num_probes_k - alternative_real_num_probes_k) > 1e-6:
  430. # sys.stderr.write('real_num_probes_k: %f, alternative_real_num_probes_k: %f\n' %
  431. # (real_num_probes_k, alternative_real_num_probes_k)
  432. # )
  433. # sys.exit(1)
  434. self.probe_bitnoer = probe_bitnoer
  435. def __repr__(self):
  436. return 'Bloom_filter(ideal_num_elements_n=%d, error_rate_p=%f, num_bits_m=%d)' % (
  437. self.ideal_num_elements_n,
  438. self.error_rate_p,
  439. self.num_bits_m,
  440. )
  441. def add(self, key):
  442. '''Add an element to the filter'''
  443. for bitno in self.probe_bitnoer(self, key):
  444. self.backend.set(bitno)
  445. def __iadd__(self, key):
  446. self.add(key)
  447. return self
  448. def _match_template(self, bloom_filter):
  449. '''Compare a sort of signature for two bloom filters. Used in preparation for binary operations'''
  450. return (self.num_bits_m == bloom_filter.num_bits_m \
  451. and self.num_probes_k == bloom_filter.num_probes_k \
  452. and self.probe_bitnoer == bloom_filter.probe_bitnoer)
  453. def union(self, bloom_filter):
  454. '''Compute the set union of two bloom filters'''
  455. self.backend |= bloom_filter.backend
  456. def __ior__(self, bloom_filter):
  457. self.union(bloom_filter)
  458. return self
  459. def intersection(self, bloom_filter):
  460. '''Compute the set intersection of two bloom filters'''
  461. self.backend &= bloom_filter.backend
  462. def __iand__(self, bloom_filter):
  463. self.intersection(bloom_filter)
  464. return self
  465. def __contains__(self, key):
  466. for bitno in self.probe_bitnoer(self, key):
  467. #wordno, bit_within_word = divmod(bitno, 32)
  468. #mask = 1 << bit_within_word
  469. #if not (self.array_[wordno] & mask):
  470. if not self.backend.is_set(bitno):
  471. return False
  472. return True
  473. #return all(self.array_[i] & mask for i, mask in self.probe_bitnoer(self, key))