bloom_filter.html
001|
002| from sys import argv
003| from os import path
004| import hashlib
005| from files import datafile, textfile, linefile
006|
007| BasePath = r'C:\CJS\prj\Python\blog\hcc\source'
008|
009| CMND = ''
010| ARGS = ['1024']
011|
012|
013| Text = '''\
013| The question, when it comes to morals or ethics, is how to construct a moral platform. \
013| If we look to nature, we see a world based on survival of the fittest, which is a \
013| possible approach, but not one that most feel resonates with moral authority.
013|
013| [Notice that, if moral law is contrary to how nature behaves, then it is necessarily an \
013| artificial construct we determine and build through some process. The entire legal \
013| profession, along with most of politics, is devoted to this.]
013|
013| We might steal a page from Immanuel Kant's notion of a Categorical Imperative and insist \
013| that, contrary to fitness, moral law should be a universal proposition.
013|
013| This suggests we ground moral worth on a notion of parity and sovereignty, that we're all \
013| the same and all free with rights, but what are these grounded on? I see three possibilities:
013|
013| We're all God's children. God made us equivalent.
013| We're all conscious beings, and consciousness is special.
013| No real grounding but suggested by game theory.
013|
013| In the last case, humanity declares equivalence as a principle by fiat based on logic, \
013| practicality, or game theory. Traditionally, this has been the option for atheists who \
013| naturally reject the first option.
013|
013| That first option is easy and accessible but viewed by many as a cop-out. "God said." \
013| How do we know what God said? Do we presume to know the mind of God? We're left with \
013| trying to figure it out based on clues. But some clues seem pretty strong.
013|
013| It may not be a matter of "God said," if we see God as the laws of physics or otherwise \
013| distant. In that case, things may be closer to the second option, which sees us as the \
013| high-odds-against result of evolution and luck.
013|
013| The second option raises questions about the moral worth of animals because we're pretty \
013| sure many of them have some form of consciousness. If having consciousness is the grounding \
013| for our moral platform, then it seems we must include at least some of the animal kingdom.
013|
013| The third option is the last refuge for those ascribing to materialism, although even they \
013| might admit consciousness is special just based on the odds against it happening. It's tough \
013| building a moral platform from a strictly materialist point of view.
013| '''
014| def clean_text (st):
015| buf = [ch for ch in st if ch.isalnum() or ch in ['\n',' ',"'",'_','$','#']]
016| return ''.join(buf)
017|
018| Inputs = list(sorted({word.lower() for word in clean_text(Text).split()}))
019|
020|
021|
022|
023| class BloomFilterBase:
024| '''Bloom Filter Base class.'''
025|
026| def __init__(self, size:int, nhash:int=5):
027| '''New BloomFilterBase instance.'''
028| self.size:int = size
029| self.nhash:int = nhash
030|
031| self.hash_functions = [hashlib.md5,
032| hashlib.sha1,
033| hashlib.sha384,
034| hashlib.sha256,
035| hashlib.sha512]
036|
037| def _hash(self, data:str, which:int) -> int:
038| '''Return a hash of data.'''
039| hasher = self.hash_functions[which % len(self.hash_functions)]()
040| hasher.update(data.encode('utf-8'))
041| digest = int(hasher.hexdigest(), 16)
042| return digest % self.size
043|
044|
045| class BloomFilter (BloomFilterBase):
046| '''Basic Bloom Filter.'''
047|
048| def __init__(self, size:int, nhash:int=5):
049| '''New BloomFilter instance.'''
050| super().__init__(size, nhash)
051|
052|
053| self.nbytes:int = (size + 7) // 8
054|
055|
056| self.bit_vector = bytearray(([0] * self.nbytes))
057|
058| def query(self, item:str) -> bool:
059| '''Test filter to see if item exists.'''
060| for ix in range(self.nhash):
061| index = self._hash(item, ix)
062| byte_index, bit_index = divmod(index, 8)
063| mask = 1 << bit_index
064| if (self.bit_vector[byte_index] & mask) == 0:
065| return False
066| return True
067|
068| def add(self, item:str) -> None:
069| '''Add an item to the filter.'''
070| for ix in range(self.nhash):
071| index = self._hash(item, ix)
072| byte_index, bit_index = divmod(index, 8)
073| mask = 1 << bit_index
074|
075| self.bit_vector[byte_index] |= mask
076|
077| def blanks (self) -> int:
078| '''Return number of unused vector slots.'''
079| func = lambda b:sum(0 if b & pow(2,bx) else 1 for bx in range(8))
080| return sum(func(b) for b in self.bit_vector)
081|
082| def __len__ (self) -> int: return self.bit_vector
083| def __getitem__ (self, ix) -> bytes: return self.bit_vector[ix]
084| def __iter__ (self): return iter(self.bit_vector)
085|
086| def __str__ (self) -> str:
087| return self._vector2bits()
088|
089| def _byte2bits (self, b) -> str:
090| bs = [('1' if b & pow(2,bx) else '0') for bx in range(8)]
091| return ''.join(reversed(bs))
092|
093| def _vector2bits (self) -> str:
094| bs = [self._byte2bits(b) for b in reversed(self.bit_vector)]
095| return '.'.join(bs)
096|
097|
098|
099| class BloomFilterCounting:
100| '''Counting Bloom Filter.'''
101|
102| def __init__ (self, size:int, nhash:int=5):
103| '''New BloomFilterCounting instance.'''
104| super().__init__(size, nhash)
105|
106|
107| self.nbr_vector = [0]*self.size
108|
109| def query (self, item:str) -> bool:
110| '''Test filter to see if item exists.'''
111| for ix in range(self.nhash):
112| index = self._hash(item, ix)
113| if self.nbr_vector[index] == 0:
114| return False
115| return True
116|
117| def add (self, item:str) -> None:
118| '''Add an item to the filter.'''
119| for ix in range(self.nhash):
120| index = self._hash(item, ix)
121| self.nbr_vector[index] += 1
122|
123| def delete (self, item:str) -> None:
124| '''Remove an item from the filter.'''
125| if not self.query(item):
126| raise RuntimeError('Item to be deleted not found in filter!')
127| for ix in range(self.nhash):
128| index = self._hash(item, ix)
129| self.nbr_vector[index] -= 1
130| if self.nbr_vector[index] < 0:
131| raise RuntimeError('Item being deleted underflowed counter!')
132|
133| def blanks (self) -> int:
134| '''Return number of unused vector slots.'''
135| return int(sum(1 if n==0 else 0 for n in self.nbr_vector))
136|
137| def __len__ (self) -> int: return self.nbr_vector
138| def __getitem__ (self, ix) -> bytes: return self.nbr_vector[ix]
139| def __iter__ (self): return iter(self.nbr_vector)
140|
141| def __str__ (self) -> str:
142| return ','.join([str(n) for n in self.nbr_vector])
143|
144|
145|
146| def demo_BloomFilter (size=64):
147| bf = BloomFilter(size)
148| for w in Inputs:
149| bf.add(w)
150| print(f'{bf=!s}')
151| print(f'> blanks={bf.blanks()}')
152| print()
153| print(f'word[ 3]: {bf.query(Inputs[3])}')
154| print(f'word[13]: {bf.query(Inputs[13])}')
155| print()
156| return bf
157|
158|
159| def demo_BloomFilterCounting (size=64):
160| bf = BloomFilterCounting(size)
161| for w in Inputs:
162| bf.add(w)
163| print(f'{bf=!s}')
164| print(f'> blanks={bf.blanks()}')
165| print()
166| print(f'word[ 3]: {bf.query(Inputs[3])}')
167| print(f'word[13]: {bf.query(Inputs[13])}')
168| print()
169| print('delete(word[3])')
170| bf.delete(Inputs[3])
171| print(f'word[ 3]: {bf.query(Inputs[3])}')
172| print()
173| return bf
174|
175|
176| def bloom_filter_character (size=64, charset='Chris Sonnack'):
177| assert size in [32,64], ValueError('Size can only be 32 or 64.')
178| vec = [0]*size
179| mask = size-1
180| for ch in charset:
181| cx = ord(ch) & mask
182| vec[cx] = 1
183| return vec
184|
185|
186| def main (cmd, *args):
187| size = int(args[0]) if 0 < len(args) else 64
188|
189| if cmd == 'bf1': return demo_BloomFilter(size)
190| if cmd == 'bf2': return demo_BloomFilterCounting(size)
191| if cmd == 'bfc': return bloom_filter_character(size)
192| if cmd == 'wls': return ', '.join(Inputs)
193| return None
194|
195| if __name__ == '__main__':
196| print(argv[0])
197| print()
198| cmnd = argv[1] if 1 < len(argv) else CMND
199| args = argv[2:] if 2 < len(argv) else ARGS
200| rv = main(cmnd, *args)
201| print(rv)
202| print()
203|
204| '''eof'''
205|