/
fol.py
1403 lines (1179 loc) · 38.4 KB
/
fol.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
"""First-order wrapper for BDDs.
References
==========
Leslie Lamport, Lawrence C. Paulson
"Should your specification language be typed?"
ACM Transactions on Programming Languages and Systems
Vol.21, No.3, pp.502--526, 1999
Kenneth Kunen
"The foundations of mathematics"
College Publications, 2009
"""
# Copyright 2016 by California Institute of Technology
# All rights reserved. Licensed under 3-clause BSD.
#
# other places where relevant functions exist:
# `dd.mdd`
# `omega.logic.bitvector`
# `omega.symbolic.enumeration`
#
# `examples/interleaving`
# `symbolic_transducers`
# `simulate`
import logging
import pprint
try:
import dd.cudd as _bdd
except ImportError:
import dd.autoref as _bdd
import omega.logic.bitvector as bv
import omega.logic.lexyacc as _lexyacc
import omega.logic.syntax as stx
import omega.symbolic.bdd as sym_bdd
import omega.symbolic.cover as cov
import omega.symbolic.enumeration as enum
import omega.symbolic.orthotopes as lat
log = logging.getLogger(__name__)
_parser = _lexyacc.Parser()
TYPE_HINTS = {'int', 'saturating', 'modwrap'}
class Context:
"""First-order interface to a binary decision diagram.
All operations assume that integer-valued variables
take only values that correspond to the Boolean-valued
variables that refine them.
Quantification is implicitly bounded.
In the future, the bound will be made explicit
in the syntax.
"Context" alludes to extension of a formal theory
by definitions [Kunen, Sec.II.15].
The attributes of this class are considered to
be internal.
Attributes:
- `vars`: mapping from variable names to
useful information about what values are
represented for the variable
- `bdd`: `dd.autoref.BDD` or `dd.cudd.BDD`,
depending on whether the Cython module `dd.cudd`
is installed.
You can assign to the attribute `Context.bdd`,
but that assignment must happen immediately
after instantiating the `Context` object,
before the context is used in any way.
The assignment must be an object of the
type `dd.autoref.BDD`, `dd.cudd.BDD`,
or any other type that has the same interface
(e.g., methods) as these classes.
"""
def __init__(self):
"""Instantiate first-order context."""
self.vars = dict()
self.bdd = _bdd.BDD()
self.op = dict() # operator name -> `str`
self.op_bdd = dict() # operator name -> bdd
def __str__(self):
"""Return `str` description of `self`."""
return (
'Refinement of variables by '
'Boolean-valued variables:\n\n'
f'{pprint.pformat(self.vars)}')
def declare(self, **vrs):
r"""Declare variable identifiers.
The variable identifiers are given as
keyword parameters, and the corresponding
keyword arguments are the type hints for
those variables.
Example:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(
x=(2, 15),
y='bool',
z=(-3, 4))
# create a BDD over the declared variables
u = ctx.add_expr(r' (x <= 4) /\ y /\ (z = -2) ')
print(u)
```
Wrapper of `Context.add_vars()`.
@param vrs:
`dict` that maps each variable name
to a type hint. A type hint is either:
- the string `'bool'`, or
- a pair of `int` (intended min and max values
to represent: the actual range can be larger,
because the representation of integer values
is in two's complement
@type vrs:
`dict` with `str` keys,
read above for value types
"""
d = bv.make_symbol_table(vrs)
self.add_vars(d)
def add_vars(self, dvars):
r"""Refine variables in `dvars`.
The variables in `dvars` should have type hints.
A Boolean-valued variable remains so.
An integer-valued variable is assumed to take the
value resulting as a function of some (fresh)
Boolean-valued variables.
Sometimes these variables are called "bits".
The function is based on two's complement,
see `omega.logic.bitvector` for details.
In other words, type hints are used to pick
a refinement of integers by finitely many bits.
A sufficient number of bits is selected,
and operations assume this as type invariant,
*not* the exact type hint given.
For example, an integer `x` with
type hint `x \in 0..2`
will be refined using 2 Boolean-valued variables
`x_0` and `x_1`. All operations and quantification
will assume that `x \in 0..3`.
Mind the extra value (3) allowed,
compared to the hint (0..2).
Attention:
- Fine-grained type predicates
(`n..m` with `n` and `m` other than powers of 2)
are not managed here.
- Priming is not reasoned about here.
Priming is cared for by other modules.
The method `add_vars()` adds to
`vars[var]` the keys:
- `"bitnames"`: `list`
- `"signed"`: `True` if signed integer
- `"width"`: `len(bitnames)`
`add_vars()` is considered internal.
The interface is `Context.declare()`.
"""
assert dvars, dvars
self._avoid_redeclaration(dvars)
vrs = {k: v for k, v in dvars.items()
if k not in self.vars}
if not vrs:
return
t = bv.bitblast_table(vrs)
self.vars.update(t)
bits = bv.bit_table(t, t)
for bit in bits:
self.bdd.add_var(bit)
def _avoid_redeclaration(self, dvars):
"""Raise `ValueError` if types would change."""
# if any `dvars` not fresh, then must be same
gen = (var for var in dvars if var in self.vars)
for var in gen:
old = self.vars[var]
for k, v in dvars[var].items():
if k in old and v == old[k]:
continue
raise ValueError(
f'attempted to redeclare "{var}" '
f'where old: {old} and '
f'new: {dvars[var]}')
def support(self, u):
r"""Return FOL variables that `u` depends on.
For example:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(
x='bool',
y=(0, 5))
u = ctx.add_expr(
r' x /\ (y = 5) ')
support = ctx.support(u)
assert support == {'x', 'y'}
# BEWARE
support_bits = ctx.bdd.support(u)
assert support_bits == {'x', 'y_0', 'y_1', 'y_2'}
support_bits = u.support
assert support_bits == {'x', 'y_0', 'y_1', 'y_2'}
```
The names of bits (`'y_0', 'y_1'` etc) are
considered an implementation detail,
and may change.
Compare with `self.bdd.support()`,
which returns bits.
@param u:
reference to root of BDD,
@type u:
`dd.autoref.Function` or
`dd.cudd.Function`,
must be the root of a BDD in `self.bdd`
@return:
set of variable names
@type:
`set` of `str`
"""
supp = self.bdd.support(u)
bit2int = bv.map_bits_to_integers(self.vars)
return set(map(bit2int.__getitem__, supp))
def let(self, defs, u):
r"""Substitute variables in `u`.
This method performs substitution in the
way that `LET` expressions work:
```tla
LET
x == 1
y == TRUE
IN
(x = 2) \/ y
```
For example:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(
x=(0, 7),
y='bool')
u = ctx.add_expr(
r' (x = 2) \/ y ')
defs = dict(x=1, y=True)
v = ctx.let(defs, u)
assert v == ctx.true
```
The argument `defs` is a `dict` with keys that are
variable names (each name is a `str`), and values
as follows, either:
- all `dict` values are variable names
(each name a `str`), or
- all `dict` values are Python values,
each value either a `bool` or an `int`.
The values need to align with the set of
values that are represented for each variable,
which depend on what was given to
`Context.declare()`.
So:
- when substituting variables for variables,
substitute:
- Boolean-valued variables for
Boolean-valued variables
- integer-valued variables for
integer-valued variables
- when substituting Python values for variables,
substitute:
- Python `int` values for
integer-valued variables
- Python `bool` values for
Boolean-valued variables
To substitute BDDs for variable names,
use `Context.replace_with_bdd()`.
Partial substitutions are possible too:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(
x=(-15, 20),
y=(0, 10))
u = ctx.add_expr(
r'(x < 5) /\ (y >= 2)')
defs = dict(x=1)
v = ctx.let(defs, u)
assert v == ctx.add_expr('y >= 2')
```
@param defs:
`dict` that maps variable names to
BDDs or values
@type defs:
one of:
- `dict[str, str]`
- `dict[str, bool | int]`
@param u:
reference to BDD root
@type u:
`dd.autoref.Function` or
`dd.cudd.Function`,
must be the root of a BDD in `self.bdd`
@return:
result of substitution
@rtype:
same as the type of `u`
"""
return self.replace(u, defs)
def replace(self, u, vars_to_new):
"""Substitute variables by values or variables.
This method is considered internal.
The interface is `Context.let()`.
@param u:
reference to BDD root
@type u:
`dd.autoref.Function` or
`dd.cudd.Function`,
must be the root of a BDD in `self.bdd`
@param vars_to_new:
`dict` that maps
each variable name to:
- a variable name (as `str`), or
- a value (as `bool` or `int`).
@return:
result of substitution
@rtype:
same as the type of `u`
"""
# `vars_to_new` must be mapping, not `None`
if len(vars_to_new) == 0:
return u
assert vars_to_new, vars_to_new
for k in vars_to_new:
rename = stx.isinstance_str(vars_to_new[k])
break
if rename:
d = _refine_renaming(vars_to_new, self.vars)
else:
d = _refine_assignment(vars_to_new, self.vars)
return self.bdd.let(d, u)
def replace_with_bdd(self, u, var_subs):
r"""Substitute Boolean-valued variables with BDDs.
This method performs substitution in the
way that `LET` expressions work:
```tla
LET
a == (x = 5) /\ (y = 2)
b == ~ a
IN
(a = TRUE) /\ ~ b
```
The argument `var_subs` is a `dict` with
keys that are variable names
(each name is a `str`),
and values that are BDDs (specifically
each value is a reference to
the root of a BDD in `self.bdd`).
For example, the above expression as:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(
a='bool',
b='bool',
x=(0, 15),
y=(0, 7))
u = ctx.add_expr(
r' (a = TRUE) /\ ~ b ')
a_rep = ctx.add_expr(
r' (x = 5) /\ (y = 2) ')
b_rep = ctx.add_expr(
r' ~ a ')
var_subs = dict(a=a_rep, b=b_rep)
v = ctx.replace_with_bdd(u, var_subs)
assert v == ctx.add_expr(
r' (x = 5) /\ (y = 2) /\ a ')
```
To substitute variable names for variable names,
or Python values for variable names,
use `Context.let()`.
@param u:
reference to BDD root
@type u:
`dd.autoref.Function` or
`dd.cudd.Function`,
must be the root of a BDD in `self.bdd`
@return:
result of substitution
@rtype:
same as the type of `u`
"""
# this method is for now distinct from
# `Context.replace()` due to the restriction
# of the variables that are keys of `var_subs`
# to be declared as Boolean-valued
return self.bdd.let(var_subs, u)
def forall(self, qvars, u):
r"""Universally quantify `qvars` in `u`.
This function applies universal quantification to
the expression represented by the BDD `u`.
For example, the expression:
```tla
\A x \in {1, 2}: (x = 1) => (x > 0)
```
can be computed with:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(x=(0, 3))
predicate = ctx.add_expr(
r'(x \in 1..2) => ((x = 1) => (x > 0))')
qvars = {'x'}
u = ctx.forall(qvars, predicate)
assert u == ctx.true
```
Calling the method `Context.forall()`
does not call the parser. The same result can
be computed with:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(x=(0, 3))
u = ctx.add_expr(r'''
\A x:
(x \in 1..2) => ((x = 1) => (x > 0))
''')
assert u == ctx.true
```
WARNING:
Make sure to use large enough type hints
when declaring variables with `Context.declare()`,
because otherwise the results can be surprising.
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(x=(-1, 1))
print(ctx.vars)
u = ctx.add_expr(
r'\A x: (x = -2) => (x = 0)')
assert u == ctx.false
u = ctx.add_expr(
r'\A x: (x = -3) => (x = 0)')
assert u == ctx.true # because `-3` is too small
# for what values are represented for `'x'`
```
For existential quantification,
use `Context.exist()`.
@param qvars:
set of variable names
@type qvars:
`set[str]`
@param u:
reference to BDD root
@type u:
`dd.autoref.Function` or
`dd.cudd.Function`,
must be the root of a BDD in `self.bdd`
@rtype:
same as the type of `u`
"""
r = self.apply('not', u)
r = self.exist(qvars, r)
r = self.apply('not', r)
return r
def exist(self, qvars, u):
r"""Existentially quantify `qvars` in `u`.
For example, the expression:
```tla
\E x \in {1, 2}: x = 1
```
can be computed with:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(x=(0, 3))
predicate = ctx.add_expr(
r'(x \in 1..2) /\ (x = 1)')
qvars = {'x'}
u = ctx.exist(qvars, predicate)
assert u == ctx.true
```
Read the docstring of `Context.forall()`.
"""
if len(qvars) == 0:
return u
qbits = bv.bit_table(qvars, self.vars)
return self.bdd.exist(qbits, u)
def count(self, u, care_vars=None):
r"""Return number of satisfying assignments.
For example:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(
x='bool',
y=(0, 3),
z=(0, 7))
n = ctx.count(ctx.false)
assert n == 0
n = ctx.count(ctx.true)
assert n == 1
n = ctx.count(ctx.true, care_vars=['x'])
assert n == 2
n = ctx.count(ctx.true, care_vars=['y'])
assert n == 4
n = ctx.count(ctx.true, care_vars=['x', 'y'])
assert n == 8
u = ctx.add_expr(r' x /\ y >= 1 ')
n = ctx.count(u)
assert n == 3
n = ctx.count(u, care_vars=['x', 'y', 'z'])
assert n == 3 * 8
```
Use the methods `Context.pick()` and
`Context.pick_iter()` for constructing
satisfying assignments (each assignment
is a `dict`).
@param u:
reference to root of BDD
@type u:
`dd.autoref.Function` or
`dd.cudd.Function`,
must be the root of a BDD in `self.bdd`
@param care_vars:
variables that
the assignments should contain.
Should be `support(u) <= care_vars`
If `care_vars is None`,
then uses `support(u)`.
@type care_vars:
`set` of `str`
@return:
integer >= 0
@rtype:
`int`
"""
# We could allow `support(u) > care_vars`.
# But that needs a dedicated BDD traversal
# (to avoid enumeration).
# Deferred until needed.
support = self.support(u)
if care_vars is None:
care_vars = support
assert set(care_vars) >= support, (
care_vars, support)
bits = _refine_vars(care_vars, self.vars)
n = len(bits)
c = self.bdd.count(u, n)
assert c == int(c), c
assert c >= 0, c
return int(c)
def pick(self, u, care_vars=None):
r"""Return a satisfying assignment, or `None`.
Examples:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
assert ctx.pick(ctx.false) is None
assert ctx.pick(ctx.true) == dict()
```
and:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(
x='bool',
y=(-5, 10))
assert ctx.pick(ctx.false) is None
assert ctx.pick(ctx.true) == dict()
d = ctx.pick(ctx.false, care_vars=['x'])
assert d is None
d = ctx.pick(ctx.true, care_vars=['x'])
assert len(d) == 1
assert d['x'] in {False, True}
d = ctx.pick(ctx.true, care_vars=['x', 'y'])
assert len(d) == 2
assert d['x'] in {False, True}
# y \in -16 .. 15
assert d['y'] in set(range(-16, 16))
```
Use the method `Context.pick_iter()` for
iterating over all satisfying assignments.
Use the method `Context.count()` to find
the number of all satisfying assignments.
@param u:
reference to root of BDD
@type u:
`dd.autoref.Function` or
`dd.cudd.Function`,
must be the root of a BDD in `self.bdd`
@param care_vars:
variables that the
assignments should contain;
the assignment can contain more variables
than these, depending on the support of `u`
@type care_vars:
`set[str]`
@return:
assignment of values to variables,
i.e., `dict` that maps each variable name to
a Python value
@rtype:
`dict | None`,
if `dict` then:
- `str` keys
- each value is `int` or `bool`,
depending on the type hint of
the corresponding variable (key of `dict`)
"""
return next(self.pick_iter(u, care_vars), None)
def pick_iter(self, u, care_vars=None):
r"""Generate first-order satisfying assignments.
This method returns a generator.
Examples:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(
x=(0, 10),
y=(3, 20),
z='bool',
w=(-1, 1))
# without specifying `care_vars`
u = ctx.add_expr(
r' x = 2 /\ y \in 4..5 /\ ~ z ')
gen = ctx.pick_iter(u)
assignments = list(gen)
assert len(assignments) == 2
assert dict(x=2, y=4, z=False) in assignments
assert dict(x=2, y=5, z=False) in assignments
# with `care_vars`
care_vars = ['x', 'y', 'z', 'w']
gen = ctx.pick_iter(u, care_vars)
assignments = list(gen)
assert len(assignments) == 8
for y in [4, 5]:
for w in [-2, -1, 0, 1]:
d = dict(
x=2, y=y, z=False, w=w)
assert d in assignments
```
Read the docstring of `Context.pick()`.
@return:
iterator over satisfying assignments
@rtype:
`collections.abc.Generator[dict]`,
an empty generator if `u == self.false`
"""
if care_vars is None:
care_bits = None
elif care_vars:
care_bits = bv.bit_table(
care_vars, self.vars)
else:
care_bits = set()
vrs = self.support(u)
if care_vars:
vrs.update(care_vars)
for bit_assignment in self.bdd.pick_iter(
u, care_vars=care_bits):
for d in enum._bitfields_to_int_iter(
bit_assignment, self.vars):
assert set(d).issubset(vrs), (
d, vrs, bit_assignment)
yield d
def define(self, definitions):
r"""Register operator definitions.
The string `definitions` must
contain definitions. Example:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(
x=(0, 10),
y=(0, 10),
z=(0, 10))
definitions = r'''
a == x + y > 3
b == z - x <= 0
c == a /\ b
'''
ctx.define(definitions)
#
# definitions can then be used in
# expressions, as follows:
u = ctx.add_expr(
' ~ c ',
with_ops=True)
assert u == ctx.add_expr(
r' (x + y <= 3) \/ (z > x) ')
```
@param definitions:
TLA+ definitions
@type definitions:
`str`
"""
assert stx.isinstance_str(
definitions), definitions
bv_defs = bv._parser.parse(definitions)
defs = _parser.parse(definitions)
for opdef, bv_opdef in zip(defs, bv_defs):
assert opdef.operator == '==', opdef
name_ast, expr_ast = opdef.operands
_, bv_ast = bv_opdef.operands
name = name_ast.value
if name in self.vars:
raise ValueError(
'Attempted to define '
f'operator "{name}", '
f'but "{name}" already '
'declared as variable: '
f'{self.vars[name]}')
if name in self.op:
raise ValueError(
'Attempted to redefine the '
f'operator "{name}". '
f'Previous definition '
f'as: "{self.op[name]}"')
s = bv_ast.flatten(
t=self.vars, defs=self.op_bdd)
# sensitive point:
# operator expressions are stored
# before substitutions
# operator BDDs are stored after
# operator substitutions
# operator definitions cannot change,
# so this should
# not cause problems as currently arranged.
self.op[name] = expr_ast.flatten()
if stx.isinstance_str(s):
self.op_bdd[name] = sym_bdd.add_expr(
s, self.bdd)
else:
# operator with non-BDD value
self.op_bdd[name] = s
def to_bdd(self, expr):
"""Return BDD for the formula `expr`.
This method is synonymous to the
method `Context.add_expr()`.
Read the docstring of `Context.add_expr()`.
@param expr:
expression that is Boolean-valued
@type expr:
`str`
@return:
reference to root of BDD
@rtype:
`dd.autoref.Function` or
`dd.cudd.Function`,
is the root of a BDD in `self.bdd`
"""
return self.add_expr(expr)
def bdds_from(self, *expressions):
"""Return `list` of BDDs for the `expressions`.
This method calls the method `Context.to_bdd()`
for each item of the argument `expressions`.
Example:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(x=(0, 10))
u, v = ctx.bdds_from('x < 5', 'x > 7')
# check the results
assert u == ctx.add_expr('x < 5')
assert v == ctx.add_expr('x > 7')
```
@param expressions:
`list` of formulas
@type expressions:
`list` of `str`
@return:
`list` of references to BDD roots
@rtype:
either:
- `list` of `dd.autoref.Function`, or
- `list` of `dd.cudd.Function`,
depending on the type of `self.bdd`
"""
return [self.to_bdd(e) for e in expressions]
def add_expr(self, expr, with_ops=False):
r"""Add first-order predicate.
A predicate is a Boolean-valued formula.
Examples:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(x=(0, 3), y='bool')
# `u` points to the root of a BDD
u = ctx.add_expr(r' (x = 1) /\ ~ y ')
print(type(u))
# `v` points to the root of another BDD
v = ctx.add_expr(r' (x # 2) /\ y ')
# `w` is the disjunction of u and v
expr = rf'{u} \/ {v}'
w = ctx.add_expr(expr)
assert w == (u | v)
print(expr)
```
Use `Context.to_expr()` to convert
BDD references to expressions.
@param expr:
Boolean-valued expression
@type expr:
`str`
@return:
reference to root of BDD that
represents expression `expr`
@rtype:
`dd.autoref.Function` or
`dd.cudd.Function`,
is the root of a BDD in `self.bdd`
"""
assert stx.isinstance_str(expr), expr
# optional because current implementation is slow
if with_ops:
defs = self.op
else:
defs = None
s = bv.bitblast(expr, vrs=self.vars, defs=defs)
# was `expr` a predicate ?
assert stx.isinstance_str(s), s
return sym_bdd.add_expr(s, self.bdd)
def to_expr(self, u, care=None, **kw):
r"""Return minimal DNF of integer inequalities.
DNF abbreviates the phrase
"Disjunctive Normal Form".
For now, this method requires that
all variables in `support(u)` be integer-valued.
Example:
```python
import omega.symbolic.fol as _fol
ctx = _fol.Context()
ctx.declare(
x=(0, 7),
y=(0, 15))
u = ctx.add_expr(r'(x = 4) /\ (y < 3)')
expr = ctx.to_expr(u)
print(expr)
```
Use `Context.add_expr()` to
create BDDs from expressions.
@param u:
reference to root of BDD
@type u:
`dd.autoref.Function` or
`dd.cudd.Function`,
must be the root of a BDD in `self.bdd`
@param care:
BDD of care set,
specifically reference to
root of BDD of care set
@type care:
same as the type of `u`