-
Notifications
You must be signed in to change notification settings - Fork 0
/
boolean.py
1652 lines (1334 loc) · 53.1 KB
/
boolean.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
"""
Boolean expressions algebra.
This module defines a Boolean algebra over the set {TRUE, FALSE} with boolean
variables called Symbols and the boolean functions AND, OR, NOT.
Some basic logic comparison is supported: two expressions can be
compared for equivalence or containment. Furthermore you can simplify
an expression and obtain its normal form.
You can create expressions in Python using familiar boolean operators
or parse expressions from strings. The parsing can be extended with
your own tokenizer. You can also customize how expressions behave and
how they are presented.
For extensive documentation look either into the docs directory or view it
online, at https://booleanpy.readthedocs.org/en/latest/.
Copyright (c) Sebastian Kraemer, basti.kr@gmail.com and others
SPDX-License-Identifier: BSD-2-Clause
"""
import inspect
import itertools
from functools import reduce # NOQA
from operator import and_ as and_operator
from operator import or_ as or_operator
# Set to True to enable tracing for parsing
TRACE_PARSE = False
# Token types for standard operators and parens
TOKEN_AND = 1
TOKEN_OR = 2
TOKEN_NOT = 3
TOKEN_LPAR = 4
TOKEN_RPAR = 5
TOKEN_TRUE = 6
TOKEN_FALSE = 7
TOKEN_SYMBOL = 8
TOKEN_TYPES = {
TOKEN_AND: "AND",
TOKEN_OR: "OR",
TOKEN_NOT: "NOT",
TOKEN_LPAR: "(",
TOKEN_RPAR: ")",
TOKEN_TRUE: "TRUE",
TOKEN_FALSE: "FALSE",
TOKEN_SYMBOL: "SYMBOL",
}
# parsing error code and messages
PARSE_UNKNOWN_TOKEN = 1
PARSE_UNBALANCED_CLOSING_PARENS = 2
PARSE_INVALID_EXPRESSION = 3
PARSE_INVALID_NESTING = 4
PARSE_INVALID_SYMBOL_SEQUENCE = 5
PARSE_INVALID_OPERATOR_SEQUENCE = 6
PARSE_ERRORS = {
PARSE_UNKNOWN_TOKEN: "Unknown token",
PARSE_UNBALANCED_CLOSING_PARENS: "Unbalanced parenthesis",
PARSE_INVALID_EXPRESSION: "Invalid expression",
PARSE_INVALID_NESTING: "Invalid expression nesting such as (AND xx)",
PARSE_INVALID_SYMBOL_SEQUENCE: "Invalid symbols sequence such as (A B)",
PARSE_INVALID_OPERATOR_SEQUENCE: "Invalid operator sequence without symbols such as AND OR or OR OR",
}
class ParseError(Exception):
"""
Raised when the parser or tokenizer encounters a syntax error. Instances of
this class have attributes token_type, token_string, position, error_code to
access the details of the error. str() of the exception instance returns a
formatted message.
"""
def __init__(self, token_type=None, token_string="", position=-1, error_code=0):
self.token_type = token_type
self.token_string = token_string
self.position = position
self.error_code = error_code
def __str__(self, *args, **kwargs):
emsg = PARSE_ERRORS.get(self.error_code, "Unknown parsing error")
tstr = ""
if self.token_string:
tstr = f' for token: "{self.token_string}"'
pos = ""
if self.position > 0:
pos = f" at position: {self.position}"
return f"{emsg}{tstr}{pos}"
class BooleanAlgebra(object):
"""
An algebra is defined by:
- the types of its operations and Symbol.
- the tokenizer used when parsing expressions from strings.
This class also serves as a base class for all boolean expressions,
including base elements, functions and variable symbols.
"""
def __init__(
self,
TRUE_class=None,
FALSE_class=None,
Symbol_class=None,
NOT_class=None,
AND_class=None,
OR_class=None,
allowed_in_token=(".", ":", "_"),
):
"""
The types for TRUE, FALSE, NOT, AND, OR and Symbol define the boolean
algebra elements, operations and Symbol variable. They default to the
standard classes if not provided.
You can customize an algebra by providing alternative subclasses of the
standard types.
"""
# TRUE and FALSE base elements are algebra-level "singleton" instances
self.TRUE = TRUE_class or _TRUE
self.TRUE = self.TRUE()
self.FALSE = FALSE_class or _FALSE
self.FALSE = self.FALSE()
# they cross-reference each other
self.TRUE.dual = self.FALSE
self.FALSE.dual = self.TRUE
# boolean operation types, defaulting to the standard types
self.NOT = NOT_class or NOT
self.AND = AND_class or AND
self.OR = OR_class or OR
# class used for Symbols
self.Symbol = Symbol_class or Symbol
tf_nao = {
"TRUE": self.TRUE,
"FALSE": self.FALSE,
"NOT": self.NOT,
"AND": self.AND,
"OR": self.OR,
"Symbol": self.Symbol,
}
# setup cross references such that all algebra types and
# objects hold a named attribute for every other types and
# objects, including themselves.
for obj in tf_nao.values():
for name, value in tf_nao.items():
setattr(obj, name, value)
# Set the set of characters allowed in tokens
self.allowed_in_token = allowed_in_token
def definition(self):
"""
Return a tuple of this algebra defined elements and types as:
(TRUE, FALSE, NOT, AND, OR, Symbol)
"""
return self.TRUE, self.FALSE, self.NOT, self.AND, self.OR, self.Symbol
def symbols(self, *args):
"""
Return a tuple of symbols building a new Symbol from each argument.
"""
return tuple(map(self.Symbol, args))
def parse(self, expr, simplify=False):
"""
Return a boolean expression parsed from `expr` either a unicode string
or tokens iterable.
Optionally simplify the expression if `simplify` is True.
Raise ParseError on errors.
If `expr` is a string, the standard `tokenizer` is used for tokenization
and the algebra configured Symbol type is used to create Symbol
instances from Symbol tokens.
If `expr` is an iterable, it should contain 3-tuples of: (token_type,
token_string, token_position). In this case, the `token_type` can be
a Symbol instance or one of the TOKEN_* constant types.
See the `tokenize()` method for detailed specification.
"""
precedence = {self.NOT: 5, self.AND: 10, self.OR: 15, TOKEN_LPAR: 20}
if isinstance(expr, str):
tokenized = self.tokenize(expr)
else:
tokenized = iter(expr)
if TRACE_PARSE:
tokenized = list(tokenized)
print("tokens:")
for t in tokenized:
print(t)
tokenized = iter(tokenized)
# the abstract syntax tree for this expression that will be build as we
# process tokens
# the first two items are None
# symbol items are appended to this structure
ast = [None, None]
def is_sym(_t):
return isinstance(_t, Symbol) or _t in (TOKEN_TRUE, TOKEN_FALSE, TOKEN_SYMBOL)
def is_operator(_t):
return _t in (TOKEN_AND, TOKEN_OR)
prev_token = None
for token_type, token_string, token_position in tokenized:
if TRACE_PARSE:
print(
"\nprocessing token_type:",
repr(token_type),
"token_string:",
repr(token_string),
"token_position:",
repr(token_position),
)
if prev_token:
prev_token_type, _prev_token_string, _prev_token_position = prev_token
if TRACE_PARSE:
print(" prev_token:", repr(prev_token))
if is_sym(prev_token_type) and (
is_sym(token_type)
): # or token_type == TOKEN_LPAR) :
raise ParseError(
token_type, token_string, token_position, PARSE_INVALID_SYMBOL_SEQUENCE
)
if is_operator(prev_token_type) and (
is_operator(token_type) or token_type == TOKEN_RPAR
):
raise ParseError(
token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE
)
else:
if is_operator(token_type):
raise ParseError(
token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE
)
if token_type == TOKEN_SYMBOL:
ast.append(self.Symbol(token_string))
if TRACE_PARSE:
print(" ast: token_type is TOKEN_SYMBOL: append new symbol", repr(ast))
elif isinstance(token_type, Symbol):
ast.append(token_type)
if TRACE_PARSE:
print(" ast: token_type is Symbol): append existing symbol", repr(ast))
elif token_type == TOKEN_TRUE:
ast.append(self.TRUE)
if TRACE_PARSE:
print(" ast: token_type is TOKEN_TRUE:", repr(ast))
elif token_type == TOKEN_FALSE:
ast.append(self.FALSE)
if TRACE_PARSE:
print(" ast: token_type is TOKEN_FALSE:", repr(ast))
elif token_type == TOKEN_NOT:
ast = [ast, self.NOT]
if TRACE_PARSE:
print(" ast: token_type is TOKEN_NOT:", repr(ast))
elif token_type == TOKEN_AND:
ast = self._start_operation(ast, self.AND, precedence)
if TRACE_PARSE:
print(" ast:token_type is TOKEN_AND: start_operation", ast)
elif token_type == TOKEN_OR:
ast = self._start_operation(ast, self.OR, precedence)
if TRACE_PARSE:
print(" ast:token_type is TOKEN_OR: start_operation", ast)
elif token_type == TOKEN_LPAR:
if prev_token:
# Check that an opening parens is preceded by a function
# or an opening parens
if prev_token_type not in (TOKEN_NOT, TOKEN_AND, TOKEN_OR, TOKEN_LPAR):
raise ParseError(
token_type, token_string, token_position, PARSE_INVALID_NESTING
)
ast = [ast, TOKEN_LPAR]
elif token_type == TOKEN_RPAR:
while True:
if ast[0] is None:
raise ParseError(
token_type,
token_string,
token_position,
PARSE_UNBALANCED_CLOSING_PARENS,
)
if ast[1] is TOKEN_LPAR:
ast[0].append(ast[2])
if TRACE_PARSE:
print("ast9:", repr(ast))
ast = ast[0]
if TRACE_PARSE:
print("ast10:", repr(ast))
break
if isinstance(ast[1], int):
raise ParseError(
token_type,
token_string,
token_position,
PARSE_UNBALANCED_CLOSING_PARENS,
)
# the parens are properly nested
# the top ast node should be a function subclass
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
raise ParseError(
token_type, token_string, token_position, PARSE_INVALID_NESTING
)
subex = ast[1](*ast[2:])
ast[0].append(subex)
if TRACE_PARSE:
print("ast11:", repr(ast))
ast = ast[0]
if TRACE_PARSE:
print("ast12:", repr(ast))
else:
raise ParseError(token_type, token_string, token_position, PARSE_UNKNOWN_TOKEN)
prev_token = (token_type, token_string, token_position)
try:
while True:
if ast[0] is None:
if TRACE_PARSE:
print("ast[0] is None:", repr(ast))
if ast[1] is None:
if TRACE_PARSE:
print(" ast[1] is None:", repr(ast))
if len(ast) != 3:
raise ParseError(error_code=PARSE_INVALID_EXPRESSION)
parsed = ast[2]
if TRACE_PARSE:
print(" parsed = ast[2]:", repr(parsed))
else:
# call the function in ast[1] with the rest of the ast as args
parsed = ast[1](*ast[2:])
if TRACE_PARSE:
print(" parsed = ast[1](*ast[2:]):", repr(parsed))
break
else:
if TRACE_PARSE:
print("subex = ast[1](*ast[2:]):", repr(ast))
subex = ast[1](*ast[2:])
ast[0].append(subex)
if TRACE_PARSE:
print(" ast[0].append(subex):", repr(ast))
ast = ast[0]
if TRACE_PARSE:
print(" ast = ast[0]:", repr(ast))
except TypeError:
raise ParseError(error_code=PARSE_INVALID_EXPRESSION)
if simplify:
return parsed.simplify()
if TRACE_PARSE:
print("final parsed:", repr(parsed))
return parsed
def _start_operation(self, ast, operation, precedence):
"""
Return an AST where all operations of lower precedence are finalized.
"""
if TRACE_PARSE:
print(" start_operation:", repr(operation), "AST:", ast)
op_prec = precedence[operation]
while True:
if ast[1] is None:
# [None, None, x]
if TRACE_PARSE:
print(" start_op: ast[1] is None:", repr(ast))
ast[1] = operation
if TRACE_PARSE:
print(" --> start_op: ast[1] is None:", repr(ast))
return ast
prec = precedence[ast[1]]
if prec > op_prec: # op=&, [ast, |, x, y] -> [[ast, |, x], &, y]
if TRACE_PARSE:
print(" start_op: prec > op_prec:", repr(ast))
ast = [ast, operation, ast.pop(-1)]
if TRACE_PARSE:
print(" --> start_op: prec > op_prec:", repr(ast))
return ast
if prec == op_prec: # op=&, [ast, &, x] -> [ast, &, x]
if TRACE_PARSE:
print(" start_op: prec == op_prec:", repr(ast))
return ast
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
# the top ast node should be a function subclass at this stage
raise ParseError(error_code=PARSE_INVALID_NESTING)
if ast[0] is None: # op=|, [None, &, x, y] -> [None, |, x&y]
if TRACE_PARSE:
print(" start_op: ast[0] is None:", repr(ast))
subexp = ast[1](*ast[2:])
new_ast = [ast[0], operation, subexp]
if TRACE_PARSE:
print(" --> start_op: ast[0] is None:", repr(new_ast))
return new_ast
else: # op=|, [[ast, &, x], ~, y] -> [ast, &, x, ~y]
if TRACE_PARSE:
print(" start_op: else:", repr(ast))
ast[0].append(ast[1](*ast[2:]))
ast = ast[0]
if TRACE_PARSE:
print(" --> start_op: else:", repr(ast))
def tokenize(self, expr):
"""
Return an iterable of 3-tuple describing each token given an expression
unicode string.
This 3-tuple contains (token, token string, position):
- token: either a Symbol instance or one of TOKEN_* token types.
- token string: the original token unicode string.
- position: some simple object describing the starting position of the
original token string in the `expr` string. It can be an int for a
character offset, or a tuple of starting (row/line, column).
The token position is used only for error reporting and can be None or
empty.
Raise ParseError on errors. The ParseError.args is a tuple of:
(token_string, position, error message)
You can use this tokenizer as a base to create specialized tokenizers
for your custom algebra by subclassing BooleanAlgebra. See also the
tests for other examples of alternative tokenizers.
This tokenizer has these characteristics:
- The `expr` string can span multiple lines,
- Whitespace is not significant.
- The returned position is the starting character offset of a token.
- A TOKEN_SYMBOL is returned for valid identifiers which is a string
without spaces.
- These are valid identifiers:
- Python identifiers.
- a string even if starting with digits
- digits (except for 0 and 1).
- dotted names : foo.bar consist of one token.
- names with colons: foo:bar consist of one token.
- These are not identifiers:
- quoted strings.
- any punctuation which is not an operation
- Recognized operators are (in any upper/lower case combinations):
- for and: '*', '&', 'and'
- for or: '+', '|', 'or'
- for not: '~', '!', 'not'
- Recognized special symbols are (in any upper/lower case combinations):
- True symbols: 1 and True
- False symbols: 0, False and None
"""
if not isinstance(expr, str):
raise TypeError(f"expr must be string but it is {type(expr)}.")
# mapping of lowercase token strings to a token type id for the standard
# operators, parens and common true or false symbols, as used in the
# default tokenizer implementation.
TOKENS = {
"*": TOKEN_AND,
"&": TOKEN_AND,
"and": TOKEN_AND,
"+": TOKEN_OR,
"|": TOKEN_OR,
"or": TOKEN_OR,
"~": TOKEN_NOT,
"!": TOKEN_NOT,
"not": TOKEN_NOT,
"(": TOKEN_LPAR,
")": TOKEN_RPAR,
"[": TOKEN_LPAR,
"]": TOKEN_RPAR,
"true": TOKEN_TRUE,
"1": TOKEN_TRUE,
"false": TOKEN_FALSE,
"0": TOKEN_FALSE,
"none": TOKEN_FALSE,
}
position = 0
length = len(expr)
while position < length:
tok = expr[position]
sym = tok.isalnum() or tok == "_"
if sym:
position += 1
while position < length:
char = expr[position]
if char.isalnum() or char in self.allowed_in_token:
position += 1
tok += char
else:
break
position -= 1
try:
yield TOKENS[tok.lower()], tok, position
except KeyError:
if sym:
yield TOKEN_SYMBOL, tok, position
elif tok not in (" ", "\t", "\r", "\n"):
raise ParseError(
token_string=tok, position=position, error_code=PARSE_UNKNOWN_TOKEN
)
position += 1
def _recurse_distributive(self, expr, operation_inst):
"""
Recursively flatten, simplify and apply the distributive laws to the
`expr` expression. Distributivity is considered for the AND or OR
`operation_inst` instance.
"""
if expr.isliteral:
return expr
args = (self._recurse_distributive(arg, operation_inst) for arg in expr.args)
args = tuple(arg.simplify() for arg in args)
if len(args) == 1:
return args[0]
flattened_expr = expr.__class__(*args)
dualoperation = operation_inst.dual
if isinstance(flattened_expr, dualoperation):
flattened_expr = flattened_expr.distributive()
return flattened_expr
def normalize(self, expr, operation):
"""
Return a normalized expression transformed to its normal form in the
given AND or OR operation.
The new expression arguments will satisfy these conditions:
- ``operation(*args) == expr`` (here mathematical equality is meant)
- the operation does not occur in any of its arg.
- NOT is only appearing in literals (aka. Negation normal form).
The operation must be an AND or OR operation or a subclass.
"""
# Ensure that the operation is not NOT
assert operation in (
self.AND,
self.OR,
)
# Move NOT inwards.
expr = expr.literalize()
# Simplify first otherwise _recurse_distributive() may take forever.
expr = expr.simplify()
operation_example = operation(self.TRUE, self.FALSE)
# For large dual operations build up from normalized subexpressions,
# otherwise we can get exponential blowup midway through
expr.args = tuple(self.normalize(a, operation) for a in expr.args)
if len(expr.args) > 1 and (
(operation == self.AND and isinstance(expr, self.OR))
or (operation == self.OR and isinstance(expr, self.AND))
):
args = expr.args
expr_class = expr.__class__
expr = args[0]
for arg in args[1:]:
expr = expr_class(expr, arg)
expr = self._recurse_distributive(expr, operation_example)
# Canonicalize
expr = expr.simplify()
else:
expr = self._recurse_distributive(expr, operation_example)
# Canonicalize
expr = expr.simplify()
return expr
def cnf(self, expr):
"""
Return a conjunctive normal form of the `expr` expression.
"""
return self.normalize(expr, self.AND)
conjunctive_normal_form = cnf
def dnf(self, expr):
"""
Return a disjunctive normal form of the `expr` expression.
"""
return self.normalize(expr, self.OR)
disjunctive_normal_form = dnf
class Expression(object):
"""
Abstract base class for all boolean expressions, including functions and
variable symbols.
"""
# these class attributes are configured when a new BooleanAlgebra is created
TRUE = None
FALSE = None
NOT = None
AND = None
OR = None
Symbol = None
def __init__(self):
# Defines sort and comparison order between expressions arguments
self.sort_order = None
# Store arguments aka. subterms of this expressions.
# subterms are either literals or expressions.
self.args = tuple()
# True is this is a literal expression such as a Symbol, TRUE or FALSE
self.isliteral = False
# True if this expression has been simplified to in canonical form.
self.iscanonical = False
@property
def objects(self):
"""
Return a set of all associated objects with this expression symbols.
Include recursively subexpressions objects.
"""
return set(s.obj for s in self.symbols)
def get_literals(self):
"""
Return a list of all the literals contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
"""
if self.isliteral:
return [self]
if not self.args:
return []
return list(itertools.chain.from_iterable(arg.get_literals() for arg in self.args))
@property
def literals(self):
"""
Return a set of all literals contained in this expression.
Include recursively subexpressions literals.
"""
return set(self.get_literals())
def literalize(self):
"""
Return an expression where NOTs are only occurring as literals.
Applied recursively to subexpressions.
"""
if self.isliteral:
return self
args = tuple(arg.literalize() for arg in self.args)
if all(arg is self.args[i] for i, arg in enumerate(args)):
return self
return self.__class__(*args)
def get_symbols(self):
"""
Return a list of all the symbols contained in this expression.
Include subexpressions symbols recursively.
This includes duplicates.
"""
return [s if isinstance(s, Symbol) else s.args[0] for s in self.get_literals()]
@property
def symbols(
self,
):
"""
Return a list of all the symbols contained in this expression.
Include subexpressions symbols recursively.
This includes duplicates.
"""
return set(self.get_symbols())
def subs(self, substitutions, default=None, simplify=False):
"""
Return an expression where all subterms of this expression are
by the new expression using a `substitutions` mapping of:
{expr: replacement}
Return the provided `default` value if this expression has no elements,
e.g. is empty.
Simplify the results if `simplify` is True.
Return this expression unmodified if nothing could be substituted. Note
that a possible usage of this function is to check for expression
containment as the expression will be returned unmodified if if does not
contain any of the provided substitutions.
"""
# shortcut: check if we have our whole expression as a possible
# subsitution source
for expr, substitution in substitutions.items():
if expr == self:
return substitution
# otherwise, do a proper substitution of subexpressions
expr = self._subs(substitutions, default, simplify)
return self if expr is None else expr
def _subs(self, substitutions, default, simplify):
"""
Return an expression where all subterms are substituted by the new
expression using a `substitutions` mapping of: {expr: replacement}
"""
# track the new list of unchanged args or replaced args through
# a substitution
new_arguments = []
changed_something = False
# shortcut for basic logic True or False
if self is self.TRUE or self is self.FALSE:
return self
# if the expression has no elements, e.g. is empty, do not apply
# substitutions
if not self.args:
return default
# iterate the subexpressions: either plain symbols or a subexpressions
for arg in self.args:
# collect substitutions for exact matches
# break as soon as we have a match
for expr, substitution in substitutions.items():
if arg == expr:
new_arguments.append(substitution)
changed_something = True
break
# this will execute only if we did not break out of the
# loop, e.g. if we did not change anything and did not
# collect any substitutions
else:
# recursively call _subs on each arg to see if we get a
# substituted arg
new_arg = arg._subs(substitutions, default, simplify)
if new_arg is None:
# if we did not collect a substitution for this arg,
# keep the arg as-is, it is not replaced by anything
new_arguments.append(arg)
else:
# otherwise, we add the substitution for this arg instead
new_arguments.append(new_arg)
changed_something = True
if not changed_something:
return
# here we did some substitution: we return a new expression
# built from the new_arguments
newexpr = self.__class__(*new_arguments)
return newexpr.simplify() if simplify else newexpr
def simplify(self):
"""
Return a new simplified expression in canonical form built from this
expression. The simplified expression may be exactly the same as this
expression.
Subclasses override this method to compute actual simplification.
"""
return self
def __hash__(self):
"""
Expressions are immutable and hashable. The hash of Functions is
computed by respecting the structure of the whole expression by mixing
the class name hash and the recursive hash of a frozenset of arguments.
Hash of elements is based on their boolean equivalent. Hash of symbols
is based on their object.
"""
if not self.args:
arghash = id(self)
else:
arghash = hash(frozenset(map(hash, self.args)))
return hash(self.__class__.__name__) ^ arghash
def __eq__(self, other):
"""
Test if other element is structurally the same as itself.
This method does not make any simplification or transformation, so it
will return False although the expression terms may be mathematically
equal. Use simplify() before testing equality to check the mathematical
equality.
For literals, plain equality is used.
For functions, equality uses the facts that operations are:
- commutative: order does not matter and different orders are equal.
- idempotent: so args can appear more often in one term than in the other.
"""
if self is other:
return True
if isinstance(other, self.__class__):
return frozenset(self.args) == frozenset(other.args)
return NotImplemented
def __ne__(self, other):
return not self == other
def __lt__(self, other):
if self.sort_order is not None and other.sort_order is not None:
if self.sort_order == other.sort_order:
return NotImplemented
return self.sort_order < other.sort_order
return NotImplemented
def __gt__(self, other):
lt = other.__lt__(self)
if lt is NotImplemented:
return not self.__lt__(other)
return lt
def __and__(self, other):
return self.AND(self, other)
__mul__ = __and__
def __invert__(self):
return self.NOT(self)
def __or__(self, other):
return self.OR(self, other)
__add__ = __or__
def __bool__(self):
raise TypeError("Cannot evaluate expression as a Python Boolean.")
__nonzero__ = __bool__
class BaseElement(Expression):
"""
Abstract base class for the base elements TRUE and FALSE of the boolean
algebra.
"""
def __init__(self):
super(BaseElement, self).__init__()
self.sort_order = 0
self.iscanonical = True
# The dual Base Element class for this element: TRUE.dual returns
# _FALSE() and FALSE.dual returns _TRUE(). This is a cyclic reference
# and therefore only assigned after creation of the singletons,
self.dual = None
def __lt__(self, other):
if isinstance(other, BaseElement):
return self == self.FALSE
return NotImplemented
__nonzero__ = __bool__ = lambda s: None
def pretty(self, indent=0, debug=False):
"""
Return a pretty formatted representation of self.
"""
return (" " * indent) + repr(self)
class _TRUE(BaseElement):
"""
Boolean base element TRUE.
Not meant to be subclassed nor instantiated directly.
"""
def __init__(self):
super(_TRUE, self).__init__()
# assigned at singleton creation: self.dual = FALSE
def __hash__(self):
return hash(True)
def __eq__(self, other):
return self is other or other is True or isinstance(other, _TRUE)
def __str__(self):
return "1"
def __repr__(self):
return "TRUE"
def __call__(self):
return self
__nonzero__ = __bool__ = lambda s: True
class _FALSE(BaseElement):
"""
Boolean base element FALSE.
Not meant to be subclassed nor instantiated directly.
"""
def __init__(self):
super(_FALSE, self).__init__()
# assigned at singleton creation: self.dual = TRUE
def __hash__(self):
return hash(False)
def __eq__(self, other):
return self is other or other is False or isinstance(other, _FALSE)
def __str__(self):
return "0"
def __repr__(self):
return "FALSE"
def __call__(self):
return self
__nonzero__ = __bool__ = lambda s: False
class Symbol(Expression):
"""
Boolean variable.
A Symbol can hold an object used to determine equality between symbols.
"""
def __init__(self, obj):
super(Symbol, self).__init__()
self.sort_order = 5
# Store an associated object. This object determines equality
self.obj = obj
self.iscanonical = True
self.isliteral = True
def __call__(self, **kwargs):
"""
Return the evaluated value for this symbol from kwargs
"""
return kwargs[self.obj]
def __hash__(self):
if self.obj is None: # Anonymous Symbol.
return id(self)
return hash(self.obj)