bloom_filter_mod.py 20 KB

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