-
Notifications
You must be signed in to change notification settings - Fork 39
/
bdd.py
3399 lines (3176 loc) · 88.4 KB
/
bdd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Ordered binary decision diagrams.
References
==========
Randal E. Bryant
"Graph-based algorithms for Boolean function manipulation"
IEEE Transactions on Computers
Volume C-35, No. 8, August, 1986, pages 677--690
Karl S. Brace, Richard L. Rudell, Randal E. Bryant
"Efficient implementation of a BDD package"
27th ACM/IEEE Design Automation Conference (DAC), 1990
pages 40--45
Richard Rudell
"Dynamic variable ordering for
ordered binary decision diagrams"
IEEE/ACM International Conference on
Computer-Aided Design (ICCAD), 1993
pages 42--47
Christel Baier and Joost-Pieter Katoen
"Principles of model checking"
MIT Press, 2008
Section 6.7, pages 381--421
Fabio Somenzi
"Binary decision diagrams"
Calculational system design, Vol.173
NATO Science Series F: Computer and systems sciences
pages 303--366, IOS Press, 1999
Henrik R. Andersen
"An introduction to binary decision diagrams"
Lecture notes for "Efficient Algorithms and Programs", 1999
The IT University of Copenhagen
"""
# Copyright 2014 by California Institute of Technology
# All rights reserved. Licensed under BSD-3.
#
import collections.abc as _abc
import functools as _ft
import inspect
import logging
import pickle
import pprint as _pp
import sys
import typing as _ty
import warnings
import dd._abc
import dd._parser as _parser
import dd._utils as _utils
logger = logging.getLogger(__name__)
REORDER_STARTS = 100
REORDER_FACTOR = 2
GROWTH_FACTOR = 2
def _request_reordering(
bdd:
'BDD'
) -> None:
"""Raise `NeedsReordering` if `len(bdd)` >= threshold."""
if bdd._last_len is None:
return
if len(bdd) >= REORDER_FACTOR * bdd._last_len:
raise _NeedsReordering()
_Ret = _ty.TypeVar('_Ret')
_CallablePR: _ty.TypeAlias = _abc.Callable[..., _Ret]
def _try_to_reorder(
func:
_CallablePR
) -> _CallablePR:
"""Decorator that serves reordering requests."""
@_ft.wraps(func)
def _wrapper(
bdd:
'BDD',
*args,
**kwargs
) -> _Ret:
with _ReorderingContext(bdd):
return func(
bdd,
*args,
**kwargs)
logger.info('Reordering needed...')
# disable reordering requests while swapping
bdd._last_len = None
reorder(bdd)
len_after = len(bdd)
# try again,
# reordering disabled to avoid livelock
with _ReorderingContext(bdd):
r = func(
bdd,
*args, **kwargs)
# enable reordering requests
bdd._last_len = GROWTH_FACTOR * len_after
return r
return _wrapper
class _ReorderingContext:
"""Context manager that tracks decorator nesting."""
def __init__(
self,
bdd:
'BDD'
) -> None:
self.bdd = bdd
self.nested = None
def __enter__(
self):
self.nested = self.bdd._reordering_context
self.bdd._reordering_context = True
def __exit__(
self,
ex_type,
ex_value,
tb):
self.bdd._reordering_context = self.nested
not_nested = (
ex_type is _NeedsReordering and
not self.nested)
if not_nested:
return True
class _NeedsReordering(Exception):
"""Raise this to request reordering."""
_Yes: _ty.TypeAlias = dd._abc.Yes
_Nat: _ty.TypeAlias = dd._abc.Nat
_Cardinality: _ty.TypeAlias = dd._abc.Cardinality
_VariableName: _ty.TypeAlias = dd._abc.VariableName
_Level: _ty.TypeAlias = dd._abc.Level
_VariableLevels: _ty.TypeAlias = dd._abc.VariableLevels
_Assignment: _ty.TypeAlias = dd._abc.Assignment
_Renaming: _ty.TypeAlias = dd._abc.Renaming
_Node: _ty.TypeAlias = _Nat
_Ref: _ty.TypeAlias = int
# ```tla
# ASSUME
# _Ref \neq 0
# ```
_Fork: _ty.TypeAlias = tuple[
_Level,
_Ref | None,
_Node | None]
_Formula: _ty.TypeAlias = dd._abc.Formula
class BDD(dd._abc.BDD[_Ref]):
"""Shared ordered binary decision diagram.
The terminal node is 1.
Nodes are positive integers,
edges signed integers.
Complemented edges are represented as
negative integers.
Values returned by methods are edges,
possibly complemented.
Attributes:
- `vars`:
`dict` mapping `variables` to `int` levels
- `roots`:
(optional) edges
- `max_nodes`:
raise `Exception` if this limit is reached.
The default value is `sys.maxsize` in Python 3.
Increase it if needed.
To ensure that the target node of a returned edge
is not garbage collected during reordering,
increment its reference counter:
`bdd.incref(edge)`
To ensure that `ite` maintains reducedness add new
nodes using `find_or_add` to keep the table updated,
or call `update_predecessors` prior to calling `ite`.
"""
# omitted docstrings are inheritted from `super()`
def __init__(
self,
levels:
_VariableLevels |
None=None
) -> None:
if levels is None:
levels = dict()
_assert_valid_ordering(levels)
self._pred: dict[
_Fork,
_Node
] = dict()
self._succ: dict[
_Node,
_Fork
] = dict()
self._ref: dict[
_Node,
_Nat
] = dict()
# all smaller positive integers
# are used as node indices, and
# no larger integers are used
# as node indices
self._min_free: _Nat = 2
# minimum number unused as BDD index
self._ite_table: dict[
tuple[_Ref, _Ref, _Ref],
_Ref
] = dict()
# `(predicate, then, else) |-> edge`
# cache for ternary conditional
# ("ite" means "if-then-else")
self.vars: _VariableLevels = dict()
self._level_to_var: dict[
_Level,
_VariableName
] = dict()
# inverse of `self.vars`
# handle no vars
self._init_terminal(len(self.vars))
# for decorator nesting
self._reordering_context: _Yes = False
# after last reordering
self._last_len: _Nat | None = None
for var, level in levels.items():
self.add_var(var, level)
# set of edges
# optional
self.roots: set = set()
self.max_nodes: _Nat = sys.maxsize
def __copy__(
self
) -> 'BDD':
bdd = BDD(self.vars)
bdd._pred = dict(self._pred)
bdd._succ = dict(self._succ)
bdd._ref = dict(self._ref)
bdd._min_free = self._min_free
bdd.roots = set(self.roots)
bdd.max_nodes = self.max_nodes
return bdd
def __del__(
self
) -> None:
"""Assert that all remaining nodes are garbage."""
if self._ref[1] > 0:
self.decref(1)
# free ref from `self._init_terminal()`
self.collect_garbage()
refs_exist = any(
v != 0
for v in self._ref.values())
if not refs_exist:
return
stack = inspect.stack()
stack_str = _pp.pformat(stack)
raise AssertionError(
'There are nodes still referenced '
'upon shutdown. Details:\n'
f'{self._ref}\n'
f'{self._succ}\n'
f'{self.vars}\n'
f'{self._ite_table}\n'
f'{type(self)}\n'
f'{stack_str}')
def __len__(
self
) -> _Cardinality:
return len(self._succ)
def __contains__(
self,
u:
_Ref
) -> _Yes:
return abs(u) in self._succ
def __iter__(
self):
return iter(self._succ)
def __str__(
self
) -> str:
return (
'Binary decision diagram:\n'
'------------------------\n'
f'var levels: {self.vars}\n'
f'roots: {self.roots}\n')
def configure(
self,
**kw
) -> dict[
str,
_ty.Any]:
"""Read and apply parameter values.
First read parameter values (returned as `dict`),
then apply `kw`. Available keyword arguments:
- `'reordering'`:
if `True` then enable, else disable
"""
d = dict(
reordering=(self._last_len is not None))
for k, v in kw.items():
if k == 'reordering':
if v:
self._last_len = max(
REORDER_STARTS, len(self))
else:
self._last_len = None
else:
raise ValueError(
f'Unknown parameter "{k}"')
return d
@property
def ordering(
self):
raise DeprecationWarning(
'use `dd.bdd.BDD.vars` '
'instead of `.ordering`')
def _init_terminal(
self,
level:
_Level
) -> None:
"""Place constant node `1`.
Used for initialization and to shift node `1` to
lower levels, as fresh variables are being added.
"""
u = 1
t = (level, None, None)
told = self._succ.setdefault(u, t)
self._pred.pop(told, None)
self._succ[u] = t
self._pred[t] = u
self._ref.setdefault(u, 1)
def succ(
self,
u:
_Ref
) -> _Fork:
"""Return `(level, low, high)` for `abs(u)`."""
return self._succ[abs(u)]
def incref(
self,
u:
_Ref
) -> None:
"""Increment reference count of node `u`."""
self._ref[abs(u)] += 1
def decref(
self,
u:
_Ref
) -> None:
"""Decrement reference count of node `u`,
with 0 as minimum value.
"""
if self._ref[abs(u)] <= 0:
n = self._ref[abs(u)]
warnings.warn(
'The method `dd.bdd.BDD.decref` was called '
f'for BDD node {u} with reference count {n}. '
'This call has no effect. Calling `decref` '
'for a node with nonpositive reference count '
'may indicate a programming error.',
UserWarning)
return
self._ref[abs(u)] -= 1
def ref(
self,
u:
_Ref
) -> _Nat:
"""Return reference count of edge `u`."""
return self._ref[abs(u)]
def declare(
self,
*variables:
_VariableName
) -> None:
for var in variables:
self.add_var(var)
def add_var(
self,
var:
_VariableName,
level:
_Level |
None=None
) -> _Level:
"""Declare a variable named `var` at `level`.
The new variable is Boolean-valued.
If `level` is absent, then add the new variable
at the bottom level.
Raise `ValueError` if:
- `var` already exists at a level
different than the given `level`, or
- the given `level` is already used by
another variable
- `level` is not given and `var` does not exist,
and the next level larger than the
current bottom level is already used by
another variable.
If `var` already exists, and either `level`
is not given, or `var` has `level`,
then return without raising exceptions.
@param var:
name of new variable to declare
@param level:
level of new variable to declare
@return:
level of variable `var`
"""
# var already exists ?
if var in self.vars:
return self._check_var(var, level)
# level already used ?
level = self._next_free_level(var, level)
# update the mappings between
# vars and levels
self.vars[var] = level
self._level_to_var[level] = var
# move the leaf node to
# the new bottom level
self._init_terminal(len(self.vars))
return level
def _check_var(
self,
var:
_VariableName,
level:
_Level |
None
) -> _Level:
"""Assert that `var` has `level`.
Return the level of `var`.
Exceptions:
- raise `ValueError` if:
- `var` is not a declared variable, or
- `level is not None` and
`level` is not the level of variable `var`
- raise `RuntimeError` if an unexpected
value of level is found in `self.vars[var]`
@param var:
name of variable
@param level:
level of variable
"""
if var not in self.vars:
raise ValueError(
f'"{var}" is not the name of '
'a declared variable')
var_level = self.vars[var]
if var_level is None or var_level < 0:
raise RuntimeError(
f'`{self.vars[var] = }` '
'(expected integer >= 0)')
if level is None or level == var_level:
return var_level
raise ValueError(
f'for variable "{var}": '
f'{level} = level != '
f'level of "{var}" = {var_level}')
def _next_free_level(
self,
var,
level:
_Level |
None
) -> _Nat:
"""Return a free level.
Raise `ValueError`:
- if the given `level` is already used by
a variable, or
- if `level is None` and the next level is
used by a variable.
If `level is None`, then return the
next level after the current largest level.
Otherwise, return the given `level`.
@param var:
name of intended new variable,
used only to form the `ValueError` message
@param level:
level of intended new variable
"""
# assume next level is unoccupied
if level is None:
level = len(self.vars)
if level < 0:
raise AssertionError(
f'`{level = } < 0')
# level already used ?
other = self._level_to_var.get(level)
if other is None:
return level
raise ValueError(
f'level {level} is already '
f'used by variable "{other}", '
'choose another level for the '
f'new variable "{var}"')
@_try_to_reorder
def var(
self,
var:
_VariableName
) -> _Ref:
if var not in self.vars:
raise ValueError(
f'undeclared variable "{var}", '
'the declared variables are:\n'
f' {self.vars}')
j = self.vars[var]
u = self.find_or_add(j, -1, 1)
return u
def var_at_level(
self,
level:
_Level
) -> _VariableName:
if level not in self._level_to_var:
raise ValueError(
f'no variable has level: {level}, '
'the current levels of all variables '
f'are: {self.vars}')
return self._level_to_var[level]
def level_of_var(
self,
var:
_VariableName
) -> _Level:
if var not in self.vars:
raise ValueError(
f'name "{var}" is not '
'a declared variable, '
'the declared variables are:'
f' {self.vars}')
return self.vars[var]
@property
def var_levels(
self
) -> _VariableLevels:
return dict(self.vars)
@_ty.overload
def _map_to_level(
self,
d:
_abc.Mapping[
_VariableName,
_ty.Any] |
_abc.Mapping[
_Level,
_ty.Any]
) -> dict[_Level, bool]:
...
@_ty.overload
def _map_to_level(
self,
d:
_abc.Set[
_VariableName] |
_abc.Set
[_Level]
) -> set[_Level]:
...
def _map_to_level(
self,
d:
_abc.Mapping[
_VariableName,
_ty.Any] |
_abc.Mapping[
_Level,
_ty.Any] |
_abc.Set[
_VariableName] |
_abc.Set[
_Level]
) -> (
dict[_Level, bool] |
set[_Level]):
"""Map keys of `d` to variable levels.
Uses `self.vars` to map the keys to levels.
If `d` is an iterable but not a mapping,
then an iterable is returned.
"""
match d:
case _abc.Mapping():
d = dict(d)
case _abc.Set():
d = set(d)
case _:
raise TypeError(d)
if not d:
match d:
case dict():
return dict()
case set():
return set()
case _:
raise TypeError(d)
# are keys variable names ?
u = next(iter(d))
if u not in self.vars:
self._assert_keys_are_levels(d)
match d:
case dict():
return {
int(k): v
for k, v in d.items()}
case set():
return set(map(int, d))
case _:
raise ValueError(d)
if isinstance(d, _abc.Mapping):
return {
self.vars[var]: bool(val)
for var, val in
d.items()}
else:
return {
self.vars[k]
for k in d}
def _assert_keys_are_levels(
self,
kv:
_abc.Iterable
) -> None:
"""Assert that `kv` values are levels.
Raise `ValueError` if not.
"""
not_levels = set()
def key_is_level(
key
) -> _Yes:
is_level = (
key in self._level_to_var)
if not is_level:
not_levels.add(key)
return is_level
keys_are_levels = all(map(
key_is_level, kv))
if keys_are_levels:
return
def fmt(key):
return (
f'key `{key}` '
'is not a level')
errors = ',\n'.join(map(
fmt, not_levels))
raise ValueError(
f'{errors},\n'
'currently the levels are:\n'
f'{self._level_to_var = }')
def _top_var(
self,
*nodes:
_Ref
) -> _Level:
def level_of(node):
level, *_ = self._succ[abs(node)]
return level
return min(map(level_of, nodes))
def copy(
self,
u:
_Ref,
other:
'BDD'
) -> _Ref:
"""Transfer BDD with root `u` to `other`."""
return copy_bdd(u, self, other)
def descendants(
self,
roots:
_abc.Iterable[_Ref]
) -> set[_Ref]:
"""Return nodes reachable from `roots`.
Nodes pointed to by references in
`roots` are included.
Nodes are represented as positive integers.
"""
abs_roots = set(map(abs, roots))
visited = set()
for u in abs_roots:
visited.add(1)
self._descendants(u, visited)
if not abs_roots.issubset(visited):
raise AssertionError(
(abs_roots, visited))
return visited
def _descendants(
self,
u:
_Ref,
visited:
set[_Node]
) -> None:
r = abs(u)
if r == 1 or r in visited:
return
_, v, w = self._succ[r]
if not v:
raise AssertionError(v)
if not w:
raise AssertionError(w)
self._descendants(v, visited)
self._descendants(w, visited)
visited.add(r)
def is_essential(
self,
u:
_Ref,
var:
_VariableName
) -> _Yes:
"""Return `True` if `var` is essential for node `u`.
If `var` is a name undeclared in
`self.vars`, return `False`.
"""
i = self.vars.get(var)
if i is None:
return False
iu, v, w = self._succ[abs(u)]
# var above node u ?
if i < iu:
return False
if i == iu:
return True
# u depends on node labeled with var ?
if not v:
raise AssertionError(v)
if not w:
raise AssertionError(w)
if self.is_essential(v, var):
return True
if self.is_essential(w, var):
return True
return False
def support(
self,
u:
_Ref,
as_levels:
_Yes=False
) -> set[
_VariableName]:
levels = set()
nodes = set()
self._support(u, levels, nodes)
if as_levels:
return levels
return {self.var_at_level(i) for i in levels}
def _support(
self,
u:
_Ref,
levels:
set[_Level],
nodes:
set[_Ref]):
"""Recurse to collect variables in support."""
# exhausted all vars ?
if len(levels) == len(self.vars):
return
# visited ?
r = abs(u)
if r in nodes:
return
nodes.add(r)
# terminal ?
if r == 1:
return
# add var
i, v, w = self._succ[r]
if not v:
raise AssertionError(v)
if not w:
raise AssertionError(w)
levels.add(i)
# recurse
self._support(v, levels, nodes)
self._support(w, levels, nodes)
def levels(
self,
skip_terminals:
_Yes=False
) -> _abc.Iterable[
tuple[
_Ref,
_Level,
_Ref,
_Node]]:
"""Return generator of tuples `(u, i, v, w)`.
Where `i` ranges from terminals to root.
@param skip_terminals:
if `True`, then omit
terminal nodes.
"""
if skip_terminals:
n = len(self.vars) - 1
else:
n = len(self.vars)
for i in range(n, -1, -1):
for u, (j, v, w) in self._succ.items():
if i != j:
continue
yield u, i, v, w
def _levels(
self
) -> dict[
_Level,
set[_Node]]:
"""Return mapping from levels to nodes."""
n = len(self.vars)
levels = {
i: set()
for var, i in
self.vars.items()}
levels[n] = set()
for u, (i, v, w) in self._succ.items():
levels[i].add(u)
levels.pop(n)
return levels
@_try_to_reorder
def reduction(
self):
"""Return copy reduced with respect to `self.vars`.
This function has educational value.
"""
# terminals
bdd = BDD(self.vars)
umap = {1: 1}
# non-terminals
levels = self.levels(
skip_terminals=True)
for u, i, v, w in levels:
if u <= 0:
raise AssertionError(u)
p, q = umap[abs(v)], umap[abs(w)]
p = _flip(p, v)
q = _flip(q, w)
r = bdd.find_or_add(i, p, q)
if r <= 0:
raise AssertionError(r)
umap[u] = r
for v in self.roots:
p = umap[abs(v)]
p = _flip(p, v)
bdd.roots.add(p)
return bdd
def undeclare_vars(
self,
*vrs
) -> set[str]:
"""Remove unused variables `vrs` from `self.vars`.
Asserts that each variable in `vrs` corresponds to
an empty level.
If `vrs` is empty, then remove all unused variables.
Garbage collection may need to be called before
calling `undeclare_vars`, in order to collect
unused nodes to obtain empty levels.
"""
for var in vrs:
if var not in self.vars:
raise ValueError(
f'name "{var}" is not '
'a declared variable. '
'The declared variables are:\n'
f'{self.vars}')
full_levels = {
i
for i, _, _ in
self._succ.values()}
# remove only unused variables
for var in vrs:
level = self.level_of_var(var)
if level in full_levels:
raise ValueError(
f'the given variable "{var}" is not '
'at an empty level (i.e., there still '
f'exist BDD nodes at level {level}, '
f'where variable "{var}" is)')
# keep unused variables not in `vrs`
if vrs:
full_levels |= {
level
for var, level in
self.vars.items()
if var not in vrs}
# map old to new levels
n = 1 + len(self.vars)
# include terminal
new_levels = [
i
for i in range(n)
if i in full_levels]
new_levels = {
i: new
for new, i in
enumerate(new_levels)}
# update variables and level declarations
rm_vars = {
var for var, level in
self.vars.items()
if level not in full_levels}
self.vars = {
var: new_levels[old]
for var, old in self.vars.items()
if old in full_levels}
self._level_to_var = {
k: var
for var, k in self.vars.items()}
# update node levels
self._succ = {
u: (new_levels[i], v, w)
for u, (i, v, w) in
self._succ.items()}
self._pred = {
v: k