Debian Codegraph @

scripts/perfect_hash.py

raw
1 # Derived from: https://github.com/ilanschnell/perfect-hash
2 # Commit: 6b7dd80a525dbd4349ea2c69f04a9c96f3c2fd54
3
4 # BSD 3-Clause License
5 #
6 # Copyright (c) 2019 - 2021, Ilan Schnell
7 # All rights reserved.
8 #
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions are met:
11 # * Redistributions of source code must retain the above copyright
12 # notice, this list of conditions and the following disclaimer.
13 # * Redistributions in binary form must reproduce the above copyright
14 # notice, this list of conditions and the following disclaimer in the
15 # documentation and/or other materials provided with the distribution.
16 # * Neither the name of the Ilan Schnell nor the
17 # names of its contributors may be used to endorse or promote products
18 # derived from this software without specific prior written permission.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
21 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23 # DISCLAIMED. IN NO EVENT SHALL ILAN SCHNELL BE LIABLE FOR ANY
24 # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 """
32 Generate a minimal perfect hash function for the keys in a file,
33 desired hash values may be specified within this file as well.
34 A given code template is filled with parameters, such that the
35 output is code which implements the hash function.
36 Templates can easily be constructed for any programming language.
37
38 The code is based on an a program A.M. Kuchling wrote:
39 http://www.amk.ca/python/code/perfect-hash
40
41 The algorithm the program uses is described in the paper
42 'Optimal algorithms for minimal perfect hashing',
43 Z. J. Czech, G. Havas and B.S. Majewski.
44 http://citeseer.ist.psu.edu/122364.html
45
46 The algorithm works like this:
47
48 1. You have K keys, that you want to perfectly hash against some
49 desired hash values.
50
51 2. Choose a number N larger than K. This is the number of
52 vertices in a graph G, and also the size of the resulting table G.
53
54 3. Pick two random hash functions f1, f2, that return values from 0..N-1.
55
56 4. Now, for all keys, you draw an edge between vertices f1(key) and f2(key)
57 of the graph G, and associate the desired hash value with that edge.
58
59 5. If G is cyclic, go back to step 2.
60
61 6. Assign values to each vertex such that, for each edge, you can add
62 the values for the two vertices and get the desired (hash) value
63 for that edge. This task is easy, because the graph is acyclic.
64 This is done by picking a vertex, and assigning it a value of 0.
65 Then do a depth-first search, assigning values to new vertices so that
66 they sum up properly.
67
68 7. f1, f2, and vertex values of G now make up a perfect hash function.
69
70
71 For simplicity, the implementation of the algorithm combines steps 5 and 6.
72 That is, we check for loops in G and assign the vertex values in one procedure.
73 If this procedure succeeds, G is acyclic and the vertex values are assigned.
74 If the procedure fails, G is cyclic, and we go back to step 2, replacing G
75 with a new graph, and thereby discarding the vertex values from the failed
76 attempt.
77 """
78
79 from __future__ import absolute_import, division, print_function
80
81 import random
82 import shutil
83 import string
84 import subprocess
85 import sys
86 import tempfile
87 from collections import defaultdict
88 from optparse import Values
89 from os.path import join
90 from typing import Any, Sequence, TypeVar
91
92 if sys.version_info[0] == 2:
93 from cStringIO import StringIO
94 else:
95 from io import StringIO
96
97
98 __version__ = "0.4.2"
99
100
101 verbose = False
102 trials = 150
103
104
105 class Graph(object):
106 """
107 Implements a graph with 'N' vertices. First, you connect the graph with
108 edges, which have a desired value associated. Then the vertex values
109 are assigned, which will fail if the graph is cyclic. The vertex values
110 are assigned such that the two values corresponding to an edge add up to
111 the desired edge value (mod N).
112 """
113
114 def __init__(self, N: int):
115 self.N = N # number of vertices
116
117 # maps a vertex number to the list of tuples (vertex, edge value)
118 # to which it is connected by edges.
119 self.adjacent: dict[int, list[tuple[int, int]]] = defaultdict(list)
120
121 def connect(self, vertex1: int, vertex2: int, edge_value: int) -> None:
122 """
123 Connect 'vertex1' and 'vertex2' with an edge, with associated
124 value 'value'
125 """
126 # Add vertices to each other's adjacent list
127 self.adjacent[vertex1].append((vertex2, edge_value))
128 self.adjacent[vertex2].append((vertex1, edge_value))
129
130 def assign_vertex_values(self) -> bool:
131 """
132 Try to assign the vertex values, such that, for each edge, you can
133 add the values for the two vertices involved and get the desired
134 value for that edge, i.e. the desired hash key.
135 This will fail when the graph is cyclic.
136
137 This is done by a Depth-First Search of the graph. If the search
138 finds a vertex that was visited before, there's a loop and False is
139 returned immediately, i.e. the assignment is terminated.
140 On success (when the graph is acyclic) True is returned.
141 """
142 self.vertex_values = self.N * [-1] # -1 means unassigned
143
144 visited = self.N * [False]
145
146 # Loop over all vertices, taking unvisited ones as roots.
147 for root in range(self.N):
148 if visited[root]:
149 continue
150
151 # explore tree starting at 'root'
152 self.vertex_values[root] = 0 # set arbitrarily to zero
153
154 # Stack of vertices to visit, a list of tuples (parent, vertex)
155 tovisit: list[tuple[int | None, int]] = [(None, root)]
156 while tovisit:
157 parent, vertex = tovisit.pop()
158 visited[vertex] = True
159
160 # Loop over adjacent vertices, but skip the vertex we arrived
161 # here from the first time it is encountered.
162 skip = True
163 for neighbor, edge_value in self.adjacent[vertex]:
164 if skip and neighbor == parent:
165 skip = False
166 continue
167
168 if visited[neighbor]:
169 # We visited here before, so the graph is cyclic.
170 return False
171
172 tovisit.append((vertex, neighbor))
173
174 # Set new vertex's value to the desired edge value,
175 # minus the value of the vertex we came here from.
176 self.vertex_values[neighbor] = (
177 edge_value - self.vertex_values[vertex]
178 ) % self.N
179
180 # check if all vertices have a valid value
181 for vertex in range(self.N):
182 assert self.vertex_values[vertex] >= 0
183
184 # We got though, so the graph is acyclic,
185 # and all values are now assigned.
186 return True
187
188
189 class StrSaltHash:
190 """
191 Random hash function generator.
192 Simple byte level hashing: each byte is multiplied to another byte from
193 a random string of characters, summed up, and finally modulo NG is
194 taken.
195 """
196
197 chars = string.ascii_letters + string.digits
198
199 def __init__(self, N: int):
200 self.N = N
201 self.salt = ""
202
203 def __call__(self, key: Sequence[str]) -> int:
204 # XXX: xkbcommon modification: make the salt length a power of 2
205 # so that the % operation in the hash is fast.
206 while len(self.salt) < max(len(key), 32): # add more salt as necessary
207 self.salt += random.choice(self.chars)
208
209 return sum(ord(self.salt[i]) * ord(c) for i, c in enumerate(key)) % self.N
210
211 template = """
212 def hash_f(key, T):
213 return sum(ord(T[i % $NS]) * ord(c) for i, c in enumerate(key)) % $NG
214
215 def perfect_hash(key):
216 return (G[hash_f(key, "$S1")] +
217 G[hash_f(key, "$S2")]) % $NG
218 """
219
220
221 class IntSaltHash:
222 """
223 Random hash function generator.
224 Simple byte level hashing, each byte is multiplied in sequence to a table
225 containing random numbers, summed tp, and finally modulo NG is taken.
226 """
227
228 def __init__(self, N: int):
229 self.N: int = N
230 self.salt: list[int] = []
231
232 def __call__(self, key: Sequence[str]) -> int:
233 while len(self.salt) < len(key): # add more salt as necessary
234 self.salt.append(random.randint(1, self.N - 1))
235
236 return sum(self.salt[i] * ord(c) for i, c in enumerate(key)) % self.N
237
238 template = """
239 S1 = [$S1]
240 S2 = [$S2]
241 assert len(S1) == len(S2) == $NS
242
243 def hash_f(key, T):
244 return sum(T[i % $NS] * ord(c) for i, c in enumerate(key)) % $NG
245
246 def perfect_hash(key):
247 return (G[hash_f(key, S1)] + G[hash_f(key, S2)]) % $NG
248 """
249
250
251 H = TypeVar("H", StrSaltHash, IntSaltHash)
252
253
254 def builtin_template(Hash: type[H]) -> str:
255 return (
256 """\
257 # =======================================================================
258 # ================= Python code for perfect hash function ===============
259 # =======================================================================
260
261 G = [$G]
262 """
263 + Hash.template
264 + """
265 # ============================ Sanity check =============================
266
267 K = [$K]
268 assert len(K) == $NK
269
270 for h, k in enumerate(K):
271 assert perfect_hash(k) == h
272 """
273 )
274
275
276 class TooManyInterationsError(Exception):
277 pass
278
279
280 # NOTE: as of mypy 1.13, it is not possible to specify a default value for a generic
281 # parameter, so `Hash: type[H] = StrSaltHash` will raise a type error. See:
282 # • https://github.com/python/mypy/issues/3737
283 # • https://github.com/python/mypy/issues/18017
284 def generate_hash(
285 keys: list[str], Hash: type[H] = StrSaltHash
286 ) -> tuple[H, H, list[int]]:
287 """
288 Return hash functions f1 and f2, and G for a perfect minimal hash.
289 Input is an iterable of 'keys', whos indicies are the desired hash values.
290 'Hash' is a random hash function generator, that means Hash(N) returns a
291 returns a random hash function which returns hash values from 0..N-1.
292 """
293 if not isinstance(keys, (list, tuple)):
294 raise TypeError("list or tuple expected")
295 NK = len(keys)
296 if NK != len(set(keys)):
297 raise ValueError("duplicate keys")
298 for key in keys:
299 if not isinstance(key, str):
300 raise TypeError("key a not string: %r" % key)
301 if NK > 10000 and Hash == StrSaltHash:
302 print(
303 """\
304 WARNING: You have %d keys.
305 Using --hft=1 is likely to fail for so many keys.
306 Please use --hft=2 instead.
307 """
308 % NK
309 )
310
311 # the number of vertices in the graph G
312 NG = NK + 1
313 if verbose:
314 print("NG = %d" % NG)
315
316 trial = 0 # Number of trial graphs so far
317 while True:
318 if (trial % trials) == 0: # trials failures, increase NG slightly
319 if trial > 0:
320 NG = max(NG + 1, int(1.05 * NG))
321 if verbose:
322 sys.stdout.write("\nGenerating graphs NG = %d " % NG)
323 trial += 1
324
325 if NG > 100 * (NK + 1):
326 raise TooManyInterationsError("%d keys" % NK)
327
328 if verbose:
329 sys.stdout.write(".")
330 sys.stdout.flush()
331
332 G = Graph(NG) # Create graph with NG vertices
333 f1 = Hash(NG) # Create 2 random hash functions
334 f2 = Hash(NG)
335
336 # Connect vertices given by the values of the two hash functions
337 # for each key. Associate the desired hash value with each edge.
338 for hashval, key in enumerate(keys):
339 G.connect(f1(key), f2(key), hashval)
340
341 # Try to assign the vertex values. This will fail when the graph
342 # is cyclic. But when the graph is acyclic it will succeed and we
343 # break out, because we're done.
344 if G.assign_vertex_values():
345 break
346
347 if verbose:
348 print("\nAcyclic graph found after %d trials." % trial)
349 print("NG = %d" % NG)
350
351 # Sanity check the result by actually verifying that all the keys
352 # hash to the right value.
353 for hashval, key in enumerate(keys):
354 assert hashval == (G.vertex_values[f1(key)] + G.vertex_values[f2(key)]) % NG
355
356 if verbose:
357 print("OK")
358
359 return f1, f2, G.vertex_values
360
361
362 class Format(object):
363 def __init__(self, width: int = 76, indent: int = 4, delimiter: str = ", "):
364 self.width = width
365 self.indent = indent
366 self.delimiter = delimiter
367
368 def print_format(self) -> None:
369 print("Format options:")
370 for name in "width", "indent", "delimiter":
371 print(" %s: %r" % (name, getattr(self, name)))
372
373 def __call__(self, data: Any, quote: bool = False) -> str:
374 if not isinstance(data, (list, tuple)):
375 return str(data)
376
377 lendel = len(self.delimiter)
378 aux = StringIO()
379 pos = 20
380 for i, elt in enumerate(data):
381 last = bool(i == len(data) - 1)
382
383 s = ('"%s"' if quote else "%s") % elt
384
385 if pos + len(s) + lendel > self.width:
386 aux.write("\n" + (self.indent * " "))
387 pos = self.indent
388
389 aux.write(s)
390 pos += len(s)
391 if not last:
392 aux.write(self.delimiter)
393 pos += lendel
394
395 return "\n".join(l.rstrip() for l in aux.getvalue().split("\n"))
396
397
398 def generate_code(
399 keys: list[str],
400 Hash: type[H] = StrSaltHash,
401 template: str | None = None,
402 options: Values | None = None,
403 ) -> str:
404 """
405 Takes a list of key value pairs and inserts the generated parameter
406 lists into the 'template' string. 'Hash' is the random hash function
407 generator, and the optional keywords are formating options.
408 The return value is the substituted code template.
409 """
410 f1, f2, G = generate_hash(keys, Hash)
411
412 assert f1.N == f2.N == len(G)
413 try:
414 salt_len = len(f1.salt)
415 assert salt_len == len(f2.salt)
416 except TypeError:
417 salt_len = None
418
419 if template is None:
420 template = builtin_template(Hash)
421
422 if options is None:
423 fmt = Format()
424 else:
425 fmt = Format(
426 width=options.width, indent=options.indent, delimiter=options.delimiter
427 )
428
429 if verbose:
430 fmt.print_format()
431
432 return string.Template(template).substitute(
433 NS=salt_len,
434 S1=fmt(f1.salt),
435 S2=fmt(f2.salt),
436 NG=len(G),
437 G=fmt(G),
438 NK=len(keys),
439 K=fmt(list(keys), quote=True),
440 )
441
442
443 def read_table(filename: str, options: Values) -> list[str]:
444 """
445 Reads keys and desired hash value pairs from a file. If no column
446 for the hash value is specified, a sequence of hash values is generated,
447 from 0 to N-1, where N is the number of rows found in the file.
448 """
449 if verbose:
450 print("Reading table from file `%s' to extract keys." % filename)
451 try:
452 fi = open(filename)
453 except IOError:
454 sys.exit("Error: Could not open `%s' for reading." % filename)
455
456 keys = []
457
458 if verbose:
459 print("Reader options:")
460 for name in "comment", "splitby", "keycol":
461 print(" %s: %r" % (name, getattr(options, name)))
462
463 for n, line in enumerate(fi):
464 line = line.strip()
465 if not line or line.startswith(options.comment):
466 continue
467
468 if line.count(options.comment): # strip content after comment
469 line = line.split(options.comment)[0].strip()
470
471 row = [col.strip() for col in line.split(options.splitby)]
472
473 try:
474 key: str = row[options.keycol - 1]
475 except IndexError:
476 sys.exit(
477 "%s:%d: Error: Cannot read key, not enough columns." % (filename, n + 1)
478 )
479
480 keys.append(key)
481
482 fi.close()
483
484 if not keys:
485 exit("Error: no keys found in file `%s'." % filename)
486
487 return keys
488
489
490 def read_template(filename: str) -> str:
491 if verbose:
492 print("Reading template from file `%s'" % filename)
493 try:
494 with open(filename, "r") as fi:
495 return fi.read()
496 except IOError:
497 sys.exit("Error: Could not open `%s' for reading." % filename)
498
499
500 def run_code(code: str) -> None:
501 tmpdir = tempfile.mkdtemp()
502 path = join(tmpdir, "t.py")
503 with open(path, "w") as fo:
504 fo.write(code)
505 try:
506 subprocess.check_call([sys.executable, path])
507 except subprocess.CalledProcessError as e:
508 raise AssertionError(e)
509 finally:
510 shutil.rmtree(tmpdir)
511
512
513 def main() -> None:
514 from optparse import OptionParser
515
516 usage = "usage: %prog [options] KEYS_FILE [TMPL_FILE]"
517
518 description = """\
519 Generates code for perfect hash functions from
520 a file with keywords and a code template.
521 If no template file is provided, a small built-in Python template
522 is processed and the output code is written to stdout.
523 """
524
525 parser = OptionParser(
526 usage=usage,
527 description=description,
528 prog=sys.argv[0],
529 version="%prog: " + __version__,
530 )
531
532 parser.add_option(
533 "--delimiter",
534 action="store",
535 default=", ",
536 help="Delimiter for list items used in output, "
537 "the default delimiter is '%default'",
538 metavar="STR",
539 )
540
541 parser.add_option(
542 "--indent",
543 action="store",
544 default=4,
545 type="int",
546 help="Make INT spaces at the beginning of a "
547 "new line when generated list is wrapped. "
548 "Default is %default",
549 metavar="INT",
550 )
551
552 parser.add_option(
553 "--width",
554 action="store",
555 default=76,
556 type="int",
557 help="Maximal width of generated list when wrapped. Default width is %default",
558 metavar="INT",
559 )
560
561 parser.add_option(
562 "--comment",
563 action="store",
564 default="#",
565 help="STR is the character, or sequence of "
566 "characters, which marks the beginning "
567 "of a comment (which runs till "
568 "the end of the line), in the input "
569 "KEYS_FILE. "
570 "Default is '%default'",
571 metavar="STR",
572 )
573
574 parser.add_option(
575 "--splitby",
576 action="store",
577 default=",",
578 help="STR is the character by which the columns "
579 "in the input KEYS_FILE are split. "
580 "Default is '%default'",
581 metavar="STR",
582 )
583
584 parser.add_option(
585 "--keycol",
586 action="store",
587 default=1,
588 type="int",
589 help="Specifies the column INT in the input "
590 "KEYS_FILE which contains the keys. "
591 "Default is %default, i.e. the first column.",
592 metavar="INT",
593 )
594
595 parser.add_option(
596 "--trials",
597 action="store",
598 default=5,
599 type="int",
600 help="Specifies the number of trials before "
601 "NG is increased. A small INT will give "
602 "compute faster, but the array G will be "
603 "large. A large INT will take longer to "
604 "compute but G will be smaller. "
605 "Default is %default",
606 metavar="INT",
607 )
608
609 parser.add_option(
610 "--hft",
611 action="store",
612 default=1,
613 type="int",
614 help="Hash function type INT. Possible values "
615 "are 1 (StrSaltHash) and 2 (IntSaltHash). "
616 "The default is %default",
617 metavar="INT",
618 )
619
620 parser.add_option(
621 "-e",
622 "--execute",
623 action="store_true",
624 help="Execute the generated code within the Python interpreter.",
625 )
626
627 parser.add_option(
628 "-o",
629 "--output",
630 action="store",
631 help="Specify output FILE explicitly. "
632 "`-o std' means standard output. "
633 "`-o no' means no output. "
634 "By default, the file name is obtained "
635 "from the name of the template file by "
636 "substituting `tmpl' to `code'.",
637 metavar="FILE",
638 )
639
640 parser.add_option("-v", "--verbose", action="store_true", help="verbosity")
641
642 options, args = parser.parse_args()
643
644 if options.trials <= 0:
645 parser.error("trials before increasing N has to be larger than zero")
646
647 global trials
648 trials = options.trials
649
650 global verbose
651 verbose = options.verbose
652
653 if len(args) not in (1, 2):
654 parser.error("incorrect number of arguments")
655
656 if len(args) == 2 and not args[1].count("tmpl"):
657 parser.error("template filename does not contain 'tmpl'")
658
659 if options.hft == 1:
660 Hash: type = StrSaltHash
661 elif options.hft == 2:
662 Hash = IntSaltHash
663 else:
664 parser.error("Hash function %s not implemented." % options.hft)
665
666 # --------------------- end parsing and checking --------------
667
668 keys_file = args[0]
669
670 if verbose:
671 print("keys_file = %r" % keys_file)
672
673 keys = read_table(keys_file, options)
674
675 if verbose:
676 print("Number os keys: %d" % len(keys))
677
678 tmpl_file = args[1] if len(args) == 2 else None
679
680 if verbose:
681 print("tmpl_file = %r" % tmpl_file)
682
683 template = read_template(tmpl_file) if tmpl_file else None
684
685 if options.output:
686 outname = options.output
687 else:
688 if tmpl_file:
689 if "tmpl" not in tmpl_file:
690 sys.exit("Hmm, template filename does not contain 'tmpl'")
691 outname = tmpl_file.replace("tmpl", "code")
692 else:
693 outname = "std"
694
695 if verbose:
696 print("outname = %r\n" % outname)
697
698 if outname == "std":
699 outstream = sys.stdout
700 elif outname == "no":
701 outstream = None
702 else:
703 try:
704 outstream = open(outname, "w")
705 except IOError:
706 sys.exit("Error: Could not open `%s' for writing." % outname)
707
708 code = generate_code(keys, Hash, template, options)
709
710 if options.execute or template == builtin_template(Hash):
711 if verbose:
712 print("Executing code...\n")
713 run_code(code)
714
715 if outstream:
716 outstream.write(code)
717 if not outname == "std":
718 outstream.close()
719
720
721 if __name__ == "__main__":
722 main()