| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
from __future__ import print_function |
| 14 |
|
| 15 |
from pprint import pprint |
| 16 |
from collections import defaultdict |
| 17 |
import sys |
| 18 |
import time |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
class DawgNode(object): |
| 29 |
|
| 30 |
def __init__(self, dawg): |
| 31 |
self.id = dawg.next_id |
| 32 |
dawg.next_id += 1 |
| 33 |
self.final = False |
| 34 |
self.edges = {} |
| 35 |
|
| 36 |
|
| 37 |
self.count = 0 |
| 38 |
|
| 39 |
self.linear_edges = None |
| 40 |
|
| 41 |
def __str__(self): |
| 42 |
if self.final: |
| 43 |
arr = ["1"] |
| 44 |
else: |
| 45 |
arr = ["0"] |
| 46 |
|
| 47 |
for (label, node) in sorted(self.edges.items()): |
| 48 |
arr.append(label) |
| 49 |
arr.append(str(node.id)) |
| 50 |
|
| 51 |
return "_".join(arr) |
| 52 |
__repr__ = __str__ |
| 53 |
|
| 54 |
def __hash__(self): |
| 55 |
return self.__str__().__hash__() |
| 56 |
|
| 57 |
def __eq__(self, other): |
| 58 |
return self.__str__() == other.__str__() |
| 59 |
|
| 60 |
def num_reachable_linear(self): |
| 61 |
|
| 62 |
if self.count: |
| 63 |
return self.count |
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
count = 0 |
| 68 |
if self.final: |
| 69 |
count += 1 |
| 70 |
for label, node in self.linear_edges: |
| 71 |
count += node.num_reachable_linear() |
| 72 |
|
| 73 |
self.count = count |
| 74 |
return count |
| 75 |
|
| 76 |
|
| 77 |
class Dawg(object): |
| 78 |
def __init__(self): |
| 79 |
self.previous_word = "" |
| 80 |
self.next_id = 0 |
| 81 |
self.root = DawgNode(self) |
| 82 |
|
| 83 |
|
| 84 |
self.unchecked_nodes = [] |
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
self.minimized_nodes = {} |
| 89 |
|
| 90 |
|
| 91 |
self.data = {} |
| 92 |
self.inverse = {} |
| 93 |
|
| 94 |
def insert(self, word, data): |
| 95 |
assert [0 <= ord(c) < 128 for c in word] |
| 96 |
if word <= self.previous_word: |
| 97 |
raise Exception("Error: Words must be inserted in alphabetical order.") |
| 98 |
if data in self.inverse: |
| 99 |
raise Exception("data %s is duplicate, got it for word %s and now %s" % (data, self.inverse[data], word)) |
| 100 |
|
| 101 |
|
| 102 |
common_prefix = 0 |
| 103 |
for i in range(min(len(word), len(self.previous_word))): |
| 104 |
if word[i] != self.previous_word[i]: |
| 105 |
break |
| 106 |
common_prefix += 1 |
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
self._minimize(common_prefix) |
| 112 |
|
| 113 |
self.data[word] = data |
| 114 |
self.inverse[data] = word |
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
if len(self.unchecked_nodes) == 0: |
| 119 |
node = self.root |
| 120 |
else: |
| 121 |
node = self.unchecked_nodes[-1][2] |
| 122 |
|
| 123 |
for letter in word[common_prefix:]: |
| 124 |
next_node = DawgNode(self) |
| 125 |
node.edges[letter] = next_node |
| 126 |
self.unchecked_nodes.append((node, letter, next_node)) |
| 127 |
node = next_node |
| 128 |
|
| 129 |
node.final = True |
| 130 |
self.previous_word = word |
| 131 |
|
| 132 |
def finish(self): |
| 133 |
|
| 134 |
self._minimize(0) |
| 135 |
|
| 136 |
self._linearize_edges() |
| 137 |
|
| 138 |
topoorder, linear_data, inverse = self._topological_order() |
| 139 |
return self.compute_packed(topoorder), linear_data, inverse |
| 140 |
|
| 141 |
def _minimize(self, down_to): |
| 142 |
|
| 143 |
for i in range(len(self.unchecked_nodes) - 1, down_to - 1, -1): |
| 144 |
(parent, letter, child) = self.unchecked_nodes[i] |
| 145 |
if child in self.minimized_nodes: |
| 146 |
|
| 147 |
parent.edges[letter] = self.minimized_nodes[child] |
| 148 |
else: |
| 149 |
|
| 150 |
self.minimized_nodes[child] = child |
| 151 |
self.unchecked_nodes.pop() |
| 152 |
|
| 153 |
def _lookup(self, word): |
| 154 |
node = self.root |
| 155 |
skipped = 0 |
| 156 |
index = 0 |
| 157 |
while index < len(word): |
| 158 |
for label, child in node.linear_edges: |
| 159 |
if word[index] == label[0]: |
| 160 |
if word[index:index + len(label)] == label: |
| 161 |
if node.final: |
| 162 |
skipped += 1 |
| 163 |
index += len(label) |
| 164 |
node = child |
| 165 |
break |
| 166 |
else: |
| 167 |
return None |
| 168 |
skipped += child.count |
| 169 |
else: |
| 170 |
return None |
| 171 |
return skipped |
| 172 |
|
| 173 |
def enum_all_nodes(self): |
| 174 |
stack = [self.root] |
| 175 |
done = set() |
| 176 |
while stack: |
| 177 |
node = stack.pop() |
| 178 |
if node.id in done: |
| 179 |
continue |
| 180 |
yield node |
| 181 |
done.add(node.id) |
| 182 |
for label, child in sorted(node.edges.items()): |
| 183 |
stack.append(child) |
| 184 |
|
| 185 |
def prettyprint(self): |
| 186 |
for node in sorted(self.enum_all_nodes(), key=lambda e: e.id): |
| 187 |
print("{}: ({}) {}{}".format(node.id, node, node.count, " final" if node.final else "")) |
| 188 |
for label, child in sorted(node.edges.items()): |
| 189 |
print(" {} goto {}".format(label, child.id)) |
| 190 |
|
| 191 |
def _inverse_lookup(self, number): |
| 192 |
assert 0, "not working in the current form, but keep it as the pure python version of compact lookup" |
| 193 |
result = [] |
| 194 |
node = self.root |
| 195 |
while 1: |
| 196 |
if node.final: |
| 197 |
if pos == 0: |
| 198 |
return "".join(result) |
| 199 |
pos -= 1 |
| 200 |
for label, child in sorted(node.edges.items()): |
| 201 |
nextpos = pos - child.count |
| 202 |
if nextpos < 0: |
| 203 |
result.append(label) |
| 204 |
node = child |
| 205 |
break |
| 206 |
else: |
| 207 |
pos = nextpos |
| 208 |
else: |
| 209 |
assert 0 |
| 210 |
|
| 211 |
def _linearize_edges(self): |
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
incoming = defaultdict(list) |
| 218 |
nodes = sorted(self.enum_all_nodes(), key=lambda e: e.id) |
| 219 |
for node in nodes: |
| 220 |
for label, child in sorted(node.edges.items()): |
| 221 |
incoming[child].append(node) |
| 222 |
for node in nodes: |
| 223 |
node.linear_edges = [] |
| 224 |
for label, child in sorted(node.edges.items()): |
| 225 |
s = [label] |
| 226 |
while len(child.edges) == 1 and len(incoming[child]) == 1 and not child.final: |
| 227 |
(c, child), = child.edges.items() |
| 228 |
s.append(c) |
| 229 |
node.linear_edges.append((''.join(s), child)) |
| 230 |
|
| 231 |
def _topological_order(self): |
| 232 |
|
| 233 |
order = [] |
| 234 |
stack = [self.root] |
| 235 |
seen = set() |
| 236 |
while stack: |
| 237 |
|
| 238 |
node = stack.pop() |
| 239 |
if node.id in seen: |
| 240 |
continue |
| 241 |
seen.add(node.id) |
| 242 |
order.append(node) |
| 243 |
for label, child in node.linear_edges: |
| 244 |
stack.append(child) |
| 245 |
|
| 246 |
|
| 247 |
incoming = defaultdict(set) |
| 248 |
for node in order: |
| 249 |
for label, child in node.linear_edges: |
| 250 |
incoming[child].add((label, node)) |
| 251 |
no_incoming = [order[0]] |
| 252 |
topoorder = [] |
| 253 |
positions = {} |
| 254 |
while no_incoming: |
| 255 |
node = no_incoming.pop() |
| 256 |
topoorder.append(node) |
| 257 |
positions[node] = len(topoorder) |
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
for label, child in reversed(node.linear_edges): |
| 262 |
incoming[child].discard((label, node)) |
| 263 |
if not incoming[child]: |
| 264 |
no_incoming.append(child) |
| 265 |
del incoming[child] |
| 266 |
|
| 267 |
assert set(topoorder) == set(order) |
| 268 |
assert len(set(topoorder)) == len(topoorder) |
| 269 |
|
| 270 |
for node in order: |
| 271 |
node.linear_edges.sort(key=lambda element: positions[element[1]]) |
| 272 |
|
| 273 |
for node in order: |
| 274 |
for label, child in node.linear_edges: |
| 275 |
assert positions[child] > positions[node] |
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
topoorder[0].num_reachable_linear() |
| 280 |
linear_data = [None] * len(self.data) |
| 281 |
inverse = {} |
| 282 |
for word, value in self.data.items(): |
| 283 |
index = self._lookup(word) |
| 284 |
linear_data[index] = value |
| 285 |
inverse[value] = index |
| 286 |
|
| 287 |
return topoorder, linear_data, inverse |
| 288 |
|
| 289 |
def compute_packed(self, order): |
| 290 |
|
| 291 |
for i, node in enumerate(order): |
| 292 |
|
| 293 |
|
| 294 |
|
| 295 |
node.packed_offset = 2 ** 30 + i * 2 ** 10 |
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
last_result = None |
| 300 |
while 1: |
| 301 |
result = bytearray() |
| 302 |
result_pp = bytearray() |
| 303 |
for node in order: |
| 304 |
offset = node.packed_offset = len(result) |
| 305 |
encode_varint_unsigned(number_add_bits(node.count, node.final), result) |
| 306 |
if len(node.linear_edges) == 0: |
| 307 |
assert node.final |
| 308 |
encode_varint_unsigned(0, result) |
| 309 |
|
| 310 |
result_pp.extend("%r\n" % (bytes(result[offset:]), )) |
| 311 |
prev_printed = len(result) |
| 312 |
prev_child_offset = len(result) |
| 313 |
for edgeindex, (label, targetnode) in enumerate(node.linear_edges): |
| 314 |
child_offset = targetnode.packed_offset |
| 315 |
child_offset_difference = child_offset - prev_child_offset |
| 316 |
|
| 317 |
info = number_add_bits(child_offset_difference, len(label) == 1, edgeindex == len(node.linear_edges) - 1) |
| 318 |
if edgeindex == 0: |
| 319 |
assert info != 0 |
| 320 |
encode_varint_unsigned(info, result) |
| 321 |
prev_child_offset = child_offset |
| 322 |
if len(label) > 1: |
| 323 |
encode_varint_unsigned(len(label), result) |
| 324 |
result.extend(label) |
| 325 |
result_pp.extend(" %r\n" % (bytes(result[prev_printed:]), )) |
| 326 |
prev_printed = len(result) |
| 327 |
node.packed_size = len(result) - node.packed_offset |
| 328 |
if result == last_result: |
| 329 |
break |
| 330 |
last_result = result |
| 331 |
self.packed = result |
| 332 |
self.packed_pp = result_pp |
| 333 |
return bytes(result) |
| 334 |
|
| 335 |
|
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
from rpython.rlib import objectmodel |
| 341 |
|
| 342 |
def number_add_bits(x, *bits): |
| 343 |
for bit in bits: |
| 344 |
assert bit == 0 or bit == 1 |
| 345 |
x = (x << 1) | bit |
| 346 |
return x |
| 347 |
|
| 348 |
@objectmodel.specialize.arg(1) |
| 349 |
@objectmodel.always_inline |
| 350 |
def number_split_bits(x, n, acc=()): |
| 351 |
if n == 1: |
| 352 |
return x >> 1, x & 1 |
| 353 |
if n == 2: |
| 354 |
return x >> 2, (x >> 1) & 1, x & 1 |
| 355 |
assert 0, "implement me!" |
| 356 |
|
| 357 |
def encode_varint_unsigned(i, res): |
| 358 |
|
| 359 |
more = True |
| 360 |
startlen = len(res) |
| 361 |
if i < 0: |
| 362 |
raise ValueError("only positive numbers supported", i) |
| 363 |
while more: |
| 364 |
lowest7bits = i & 0b1111111 |
| 365 |
i >>= 7 |
| 366 |
if i == 0: |
| 367 |
more = False |
| 368 |
else: |
| 369 |
lowest7bits |= 0b10000000 |
| 370 |
res.append(chr(lowest7bits)) |
| 371 |
return len(res) - startlen |
| 372 |
|
| 373 |
@objectmodel.always_inline |
| 374 |
def decode_varint_unsigned(b, index=0): |
| 375 |
res = 0 |
| 376 |
shift = 0 |
| 377 |
while True: |
| 378 |
byte = ord(b[index]) |
| 379 |
res = res | ((byte & 0b1111111) << shift) |
| 380 |
index += 1 |
| 381 |
shift += 7 |
| 382 |
if not (byte & 0b10000000): |
| 383 |
return res, index |
| 384 |
|
| 385 |
@objectmodel.always_inline |
| 386 |
def decode_node(packed, node): |
| 387 |
x, node = decode_varint_unsigned(packed, node) |
| 388 |
node_count, final = number_split_bits(x, 1) |
| 389 |
return node_count, final, node |
| 390 |
|
| 391 |
@objectmodel.always_inline |
| 392 |
def decode_edge(packed, edgeindex, prev_child_offset, offset): |
| 393 |
x, offset = decode_varint_unsigned(packed, offset) |
| 394 |
if x == 0 and edgeindex == 0: |
| 395 |
raise KeyError |
| 396 |
child_offset_difference, len1, final_edge = number_split_bits(x, 2) |
| 397 |
child_offset = prev_child_offset + child_offset_difference |
| 398 |
if len1: |
| 399 |
size = 1 |
| 400 |
else: |
| 401 |
size, offset = decode_varint_unsigned(packed, offset) |
| 402 |
return child_offset, final_edge, size, offset |
| 403 |
|
| 404 |
@objectmodel.always_inline |
| 405 |
def _match_edge(packed, s, size, node_offset, stringpos): |
| 406 |
if size > 1 and stringpos + size > len(s): |
| 407 |
|
| 408 |
return False |
| 409 |
for i in range(size): |
| 410 |
if packed[node_offset + i] != s[stringpos + i]: |
| 411 |
|
| 412 |
|
| 413 |
if i > 0: |
| 414 |
raise KeyError |
| 415 |
return False |
| 416 |
return True |
| 417 |
|
| 418 |
def lookup(packed, data, s): |
| 419 |
return data[_lookup(packed, s)] |
| 420 |
|
| 421 |
def _lookup(packed, s): |
| 422 |
stringpos = 0 |
| 423 |
node_offset = 0 |
| 424 |
skipped = 0 |
| 425 |
while stringpos < len(s): |
| 426 |
node_count, final, edge_offset = decode_node(packed, node_offset) |
| 427 |
if final: |
| 428 |
skipped += 1 |
| 429 |
prev_child_offset = edge_offset |
| 430 |
edgeindex = 0 |
| 431 |
while 1: |
| 432 |
child_offset, final_edge, size, edgelabel_chars_offset = decode_edge(packed, edgeindex, prev_child_offset, edge_offset) |
| 433 |
edgeindex += 1 |
| 434 |
prev_child_offset = child_offset |
| 435 |
if _match_edge(packed, s, size, edgelabel_chars_offset, stringpos): |
| 436 |
|
| 437 |
stringpos += size |
| 438 |
node_offset = child_offset |
| 439 |
break |
| 440 |
if final_edge: |
| 441 |
raise KeyError |
| 442 |
child_count, _, _ = decode_node(packed, child_offset) |
| 443 |
skipped += child_count |
| 444 |
edge_offset = edgelabel_chars_offset + size |
| 445 |
node_count, final, _ = decode_node(packed, node_offset) |
| 446 |
if final: |
| 447 |
return skipped |
| 448 |
raise KeyError |
| 449 |
|
| 450 |
def inverse_lookup(packed, inverse, x): |
| 451 |
pos = inverse[x] |
| 452 |
return _inverse_lookup(packed, pos) |
| 453 |
|
| 454 |
def _inverse_lookup(packed, pos): |
| 455 |
from rpython.rlib import rstring |
| 456 |
result = rstring.StringBuilder(42) |
| 457 |
node_offset = 0 |
| 458 |
while 1: |
| 459 |
node_count, final, edge_offset = decode_node(packed, node_offset) |
| 460 |
if final: |
| 461 |
if pos == 0: |
| 462 |
return result.build() |
| 463 |
pos -= 1 |
| 464 |
prev_child_offset = edge_offset |
| 465 |
edgeindex = 0 |
| 466 |
while 1: |
| 467 |
child_offset, final_edge, size, edgelabel_chars_offset = decode_edge(packed, edgeindex, prev_child_offset, edge_offset) |
| 468 |
edgeindex += 1 |
| 469 |
prev_child_offset = child_offset |
| 470 |
child_count, _, _ = decode_node(packed, child_offset) |
| 471 |
nextpos = pos - child_count |
| 472 |
if nextpos < 0: |
| 473 |
assert edgelabel_chars_offset >= 0 |
| 474 |
result.append_slice(packed, edgelabel_chars_offset, edgelabel_chars_offset + size) |
| 475 |
node_offset = child_offset |
| 476 |
break |
| 477 |
elif not final_edge: |
| 478 |
pos = nextpos |
| 479 |
edge_offset = edgelabel_chars_offset + size |
| 480 |
else: |
| 481 |
raise KeyError |
| 482 |
else: |
| 483 |
raise KeyError |
| 484 |
|
| 485 |
|
| 486 |
|
| 487 |
|
| 488 |
|
| 489 |
MAXBLANK = 8 |
| 490 |
MINLIST = 5 |
| 491 |
|
| 492 |
def findranges(d): |
| 493 |
ranges = [] |
| 494 |
for i in range(max(d)+1): |
| 495 |
if i in d: |
| 496 |
if not ranges: |
| 497 |
ranges.append((i,i)) |
| 498 |
last = i |
| 499 |
continue |
| 500 |
if last + 1 == i: |
| 501 |
ranges[-1] = (ranges[-1][0], i) |
| 502 |
else: |
| 503 |
ranges.append((i,i)) |
| 504 |
last = i |
| 505 |
return ranges |
| 506 |
|
| 507 |
def collapse_ranges(ranges): |
| 508 |
collapsed = [ranges[0]] |
| 509 |
for i in range(1, len(ranges)): |
| 510 |
lows, lowe = collapsed[-1] |
| 511 |
highs, highe = ranges[i] |
| 512 |
if highs - lowe < MAXBLANK: |
| 513 |
collapsed[-1] = (lows, highe) |
| 514 |
else: |
| 515 |
collapsed.append(ranges[i]) |
| 516 |
|
| 517 |
return collapsed |
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
|
| 523 |
empty_functions = """ |
| 524 |
def dawg_lookup(name): |
| 525 |
raise KeyError |
| 526 |
def lookup_charcode(code): |
| 527 |
raise KeyError |
| 528 |
""" |
| 529 |
|
| 530 |
def build_compression_dawg(outfile, ucdata): |
| 531 |
outfile.print_comment("_" * 60) |
| 532 |
outfile.print_comment("output from build_compression_dawg") |
| 533 |
outfile.print_code('from rpython.rlib.rarithmetic import intmask, r_int32') |
| 534 |
outfile.print_code('from rpython.rlib.unicodedata.supportcode import signed_ord, _all_short, _all_ushort, _all_int32, _all_uint32') |
| 535 |
|
| 536 |
if not ucdata: |
| 537 |
outfile.print_code(empty_functions) |
| 538 |
return |
| 539 |
|
| 540 |
d = Dawg() |
| 541 |
for name, value in sorted(ucdata.items()): |
| 542 |
d.insert(name, value) |
| 543 |
packed, pos_to_code, reversedict = d.finish() |
| 544 |
|
| 545 |
outfile.print_code("from rpython.rlib.unicodedata.dawg import _lookup as _dawg_lookup, _inverse_lookup") |
| 546 |
outfile.print_code("packed_dawg = (") |
| 547 |
outfile.print_uncounted(d.packed_pp) |
| 548 |
outfile.print_code(")") |
| 549 |
outfile._estimate_string("dawg", bytes(d.packed)) |
| 550 |
outfile.print_listlike("pos_to_code", pos_to_code, "dawg pos_to_code") |
| 551 |
|
| 552 |
outfile.print_code(""" |
| 553 |
def lookup_charcode(c): |
| 554 |
pos = _charcode_to_pos(c) |
| 555 |
return _inverse_lookup(packed_dawg, pos) |
| 556 |
|
| 557 |
def dawg_lookup(n): |
| 558 |
return pos_to_code(_dawg_lookup(packed_dawg, n)) |
| 559 |
""") |
| 560 |
|
| 561 |
|
| 562 |
function = ["def _charcode_to_pos(code):", " res = -1"] |
| 563 |
ranges = collapse_ranges(findranges(reversedict)) |
| 564 |
prefix = "" |
| 565 |
for low, high in ranges: |
| 566 |
if high - low <= 5: |
| 567 |
for code in range(low, high + 1): |
| 568 |
if code in reversedict: |
| 569 |
function.append( |
| 570 |
" %sif code == %d: res = %s" % |
| 571 |
(prefix, code, reversedict[code])) |
| 572 |
prefix = "el" |
| 573 |
continue |
| 574 |
|
| 575 |
name = "_charcode_to_pos_%d" % (low,) |
| 576 |
lst = [] |
| 577 |
for code in range(low, high + 1): |
| 578 |
if code in reversedict: |
| 579 |
lst.append(reversedict[code]) |
| 580 |
else: |
| 581 |
lst.append(-1) |
| 582 |
outfile.print_listlike(name, lst, "dawg inverse") |
| 583 |
function.append( |
| 584 |
" %sif %d <= code <= %d: res = %s(code-%d)" % ( |
| 585 |
prefix, low, high, name, low)) |
| 586 |
prefix = "el" |
| 587 |
|
| 588 |
|
| 589 |
function.append(" if res == -1:") |
| 590 |
function.append(" raise KeyError(code)") |
| 591 |
function.append(" return res") |
| 592 |
outfile.print_code('\n'.join(function)) |
| 593 |
outfile.print_comment("end output from build_compression_dawg") |
| 594 |
return d |