bloom_filter_mod.py 20 KB

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