-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboolean.py
1248 lines (1088 loc) · 39.4 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 Algebra.
This module defines a Boolean Algebra over the set {TRUE, FALSE} with boolean
variables and the boolean functions AND, OR, NOT. For extensive documentation
look either into the docs directory or view it online at
https://booleanpy.readthedocs.org/en/latest/.
Copyright (c) 2009-2010 Sebastian Kraemer, [email protected]
Released under revised BSD license.
Copyright (c) 2015 Qi-rui Chen, [email protected]
- Function parse now supports more notation including prime NOT notation
- Supports prime notation printing (eg: A')
- Prints ∙ instead of * for AND
- Fixed NOT.eval to literalize instead of just attempting to cancel
- Fixed printing extra brackets around NOT eg: A+(~(A+B))
- Added truth_table function
"""
import itertools
import collections
# A boolean algebra is defined by its base elements (=domain), its operations
# (in this case only NOT, AND and OR) and an additional "symbol" type.
Algebra = collections.namedtuple("Algebra",
("domain", "operations", "symbol"))
# Defines the two base elements TRUE and FALSE for the algebra.
BooleanDomain = collections.namedtuple("BooleanDomain",
("TRUE", "FALSE"))
# Defines the basic boolean operations NOT, AND and OR.
BooleanOperations = collections.namedtuple("BooleanOperations",
("NOT", "AND", "OR"))
class Expression(object):
"""
Base class for all boolean expressions.
"""
# Used to store subterms. Can be empty.
_args = None
# Defines order relation between different classes.
_cls_order = None
# Stores if an expression is already canonical.
_iscanonical = False
# Cashes the hash value for an expression. (Expressions are immutable)
_hash = None
# Stores an object associated to this boolean expression.
_obj = None
# Holds an Algebra tuple which defines the boolean algebra.
algebra = None
def __new__(cls, arg, *, eval=True):
if isinstance(arg, Expression):
return arg
if isinstance(arg, str):
return parse(arg, eval=eval)
elif arg in (0, False):
return cls.algebra.domain.FALSE
elif arg in (1, True):
return cls.algebra.domain.TRUE
raise TypeError("Wrong argument for Expression.")
@property
def args(self):
"""
Return a tuple of all subterms.
"""
return self._args
@property
def obj(self):
"""
Return the associated object of this object.
Might be None.
"""
return self._obj
@property
def objects(self):
"""
Return a set off all associated objects in this expression.
Might be an empty set.
"""
s = set() if self.obj is None else set([self.obj])
if self.args is not None:
for arg in self.args:
s |= arg.objects
return s
@property
def isliteral(self):
"""
Return True if object is a literal otherwise False.
"""
return False # This is overriden in all Literals.
@property
def literals(self):
"""
Return a set of all literals contained in this or any subexpression.
"""
if self.isliteral:
return set((self,))
if self.args is None:
return set()
else:
s = set()
for arg in self.args:
s |= arg.literals
return s
def literalize(self):
"""
Return an expression where NOTs are only occuring as literals.
"""
if self.isliteral or self.args is None:
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
else:
return self.__class__(*args, eval=False)
@property
def symbols(self):
"""
Return a set of all symbols contained in this or any subexpression.
"""
if isinstance(self, Symbol):
return set((self,))
if self.args is None:
return set()
else:
s = set()
for arg in self.args:
s |= arg.symbols
return s
def subs(self, subs_dict, *, eval=True):
"""
Return an expression where all subterms equal to a key are substituted.
"""
for expr, substitution in subs_dict.items():
if expr == self:
return substitution
expr = self._subs(subs_dict, eval=eval)
return self if expr is None else expr
def _subs(self, subs_dict, eval):
new_args = []
changed_something = False
for arg in self.args:
matched = False
for expr, substitution in subs_dict.items():
if arg == expr:
new_args.append(substitution)
changed_something = matched = True
break
if not matched:
new_arg = None if arg.args is None else\
arg._subs(subs_dict, eval)
if new_arg is None:
new_args.append(arg)
else:
changed_something = True
new_args.append(new_arg)
if changed_something:
return self.__class__(*new_args, eval=eval)
else:
return None
@property
def iscanonical(self):
"""
Return True if the boolean object is in canonical form.
"""
return self._iscanonical
def eval(self, **evalkwargs):
"""
Return a possibly simplified, canonical form of the boolean object.
"""
return self
def __hash__(self):
"""
Calculate a hash respecting the structure of the whole expression.
This is done by using as first part the classname and as second
the hash of the arguments stored in a frozenset.
For more information about equality and hashes, look into the
documentation.
# TODO: Add entry about hashes into documentation.
"""
# The hash consists of two parts, the hash of the class name and the
# hash of the subterms (stored in args). If the object has no subterms,
# the id of the object is used instead.
# Since all boolean objects are immutable the hash only has to be
# computed once.
if self._hash is None:
if self.args is None:
arghash = id(self)
else:
arghash = hash(frozenset(self.args))
self._hash = hash(self.__class__.__name__) ^ arghash
return self._hash
else:
return self._hash
def __eq__(self, other):
"""
Test if other element is structurally the same as itself.
This method doesn't try any transformations, so it will return
False although terms are mathematically equal. It only uses the fact
that all operations are commutative and considers different ordering as
equal. Actually also idempotence is used, so args can appear more often
in one term than in the other.
"""
if self is other:
return True
if not isinstance(other, self.__class__):
return NotImplemented
if self.args is None or other.args is None:
return False
if frozenset(self.args) == frozenset(other.args):
return True
return False
def __ne__(self, other):
return not self == other
def __lt__(self, other):
if self._cls_order is not None and other._cls_order is not None:
if self._cls_order == other._cls_order:
return NotImplemented
else:
return self._cls_order < other._cls_order
return NotImplemented
def __gt__(self, other):
lt = other.__lt__(self)
if lt is NotImplemented:
return not self.__lt__(other)
else:
return lt
def __mul__(self, other):
return self.algebra.operations.AND(self, other)
def __invert__(self):
return self.algebra.operations.NOT(self)
def __add__(self, other):
return self.algebra.operations.OR(self, other)
class BaseElement(Expression):
"""
Base class for the base elements TRUE and FALSE of the boolean algebra.
"""
_cls_order = 0
_iscanonical = True
# The following two attributes define the output of __str__ and __repr__
# respectively. They are overwritten in the classes TRUE and FALSE.
_str = None
_repr = None
def __new__(cls, arg=None, *, eval=False):
if arg is not None:
if isinstance(arg, BaseElement):
return arg
elif arg in (0, False):
return cls.algebra.domain.FALSE
elif arg in (1, True):
return cls.algebra.domain.TRUE
else:
raise TypeError("Bad argument: %s" % arg)
elif cls is BaseElement:
raise TypeError("BaseElement can't be created without argument.")
if cls.algebra is None:
return object.__new__(cls)
elif isinstance(cls.algebra.domain.TRUE, cls):
return cls.algebra.domain.TRUE
elif isinstance(cls.algebra.domain.FALSE, cls):
return cls.algebra.domain.FALSE
else:
raise TypeError("BaseElement can only create objects in the\
current domain.")
@property
def dual(self):
"""
Return the dual Base Element.
That means TRUE.dual will return FALSE and FALSE.dual will return
TRUE.
"""
domain = self.algebra.domain
if self is domain.TRUE:
return domain.FALSE
elif self is domain.FALSE:
return domain.TRUE
else:
raise AttributeError("Class should be TRUE or FALSE but is %s."
% self.cls.__name__)
def __lt__(self, other):
cmp = Expression.__lt__(self, other)
if cmp is not NotImplemented:
return cmp
if isinstance(other, BaseElement):
if self is self.algebra.domain.FALSE:
return True
return False
return NotImplemented
def __str__(self):
if self._str is not None:
return self._str
def __repr__(self):
if self._repr is not None:
return self._repr
def __bool__(self):
if self._bool is not None:
return self._bool
class _TRUE(BaseElement):
"""
Boolean base element TRUE.
This is one of the two elements of the boolean algebra.
"""
_str = "1"
_repr = "TRUE"
_bool = True
class _FALSE(BaseElement):
"""
Boolean base element FALSE.
This is one of the two elements of the boolean algebra.
"""
_str = "0"
_repr = "FALSE"
_bool = False
# Initialize two singletons which will be used as base elements for the
# default boolean algebra.
TRUE = _TRUE()
FALSE = _FALSE()
class Symbol(Expression):
"""
Boolean variable.
Symbols (also called boolean variables) can only take on the values TRUE
or FALSE. They can hold an object that will be used to determine equality.
These are called "named symbols". Alternatively it's possible to create
symbols without any argument (or the argument None). That will result in
"anonymous symbols", which will always be unequal to any other symbol but
themselfs.
"""
_cls_order = 5
_iscanonical = True
_obj = None
def __new__(cls, obj=None, *, eval=False):
return object.__new__(cls)
def __init__(self, obj=None, *, eval=False):
self._obj = obj
@property
def obj(self):
"""
Return the object associated with this symbol.
"""
return self._obj
@property
def isliteral(self):
"""
Return True if object is a literal otherwise False.
"""
return True
def __hash__(self):
"""
Calculate a hash considering eventually associated objects.
"""
if self._hash is not None:
return self._hash # Return cached hash.
else:
if self.obj is None: # Anonymous symbol.
myhash = id(self)
else: # Hash of associated object.
myhash = hash(self.obj)
self._hash = myhash
return myhash
def __eq__(self, other):
"""
Test if other element equals to this symbol.
"""
if self is other:
return True
if not isinstance(other, self.__class__):
return NotImplemented
if self.obj is None or other.obj is None:
return False
else:
return self.obj == other.obj
def __lt__(self, other):
cmp = Expression.__lt__(self, other)
if cmp is not NotImplemented:
return cmp
if isinstance(other, Symbol):
if self.obj is None:
if other.obj is None:
return hash(self) < hash(other) # 2 anonymous symbols.
else:
return False # Anonymous-Symbol < Named-Symbol.
else:
if other.obj is None:
return True # Named-Symbol < Anonymous-Symbol.
else:
return self.obj.__lt__(other.obj) # 2 named symbols.
return NotImplemented
def __str__(self):
if self.obj is None:
return "S<%s>" % str(hash(self))
else:
return str(self.obj)
def __repr__(self):
if self.obj is not None:
obj = repr(self.obj)
else:
obj = hash(self)
return "%s(%s)" % (self.__class__.__name__, obj)
class Function(Expression):
"""
Boolean function.
A boolean function takes n boolean expressions as arguments (n is called
the order of the function) and maps them to one of the base elements.
Typical examples for implemented functions are AND and OR.
"""
# Specifies how many arguments a function takes. the first number gives a
# lower limit, the second an upper limit.
order = (2, float("inf"))
# Specifies an infix notation of an operator for printing.
operator = None
def __new__(cls, *args, eval=True):
length = len(args)
order = cls.order
if eval:
return cls(*args, eval=False).eval()
if order[0] > length:
raise TypeError("Too few arguments. Got %s, but need at least %s."
% (length, order[0]))
if order[1] < length:
raise TypeError("Too many arguments. Got %s, but need at most %s."
% (length, order[1]))
return object.__new__(cls)
def __init__(self, *args, eval=True):
# If a function in the __new__ method is evaluated the __init__ method
# will be called twice. First with the simplified then with original
# arguments. The following "if" prevents that the simplified ones are
# overwritten.
if self._args:
return
_args = [None] * len(args)
# Make sure all arguments are boolean expressions.
for i, arg in enumerate(args):
if isinstance(arg, Expression):
_args[i] = arg
elif isinstance(arg, str):
_args[i] = parse(arg)
elif arg in (0, False):
_args[i] = FALSE
elif arg in (1, True):
_args[i] = TRUE
else:
raise TypeError("Bad argument: %s" % arg)
self._args = tuple(_args)
def __str__(self):
args = self.args
if self.operator is None:
return "%s(%s)" % (self.__class__.__name__,
", ".join(str(arg) for arg in args))
elif len(args) == 1:
if self.isliteral:
return self.operator + str(args[0])
else:
return "%s(%s)" % (self.operator, str(args[0]))
else:
return self.operator.join(str(arg)
if arg.isliteral
or isinstance(arg, BaseElement)
or arg.order == (1, 1)
else "(%s)" % arg
for arg in args)
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__,
", ".join(repr(arg) for arg in self.args))
class NOT(Function):
"""
Boolean NOT operation.
The NOT operation takes exactly one argument. If this argument is a Symbol
the resulting expression is also called a literal.
The operator "'" can be used as abbrevation for NOT, e.g. instead of
NOT(x) one can write x' (where x is some boolean expression). Also for
printing "'" is used for better readability.
"""
order = (1, 1)
#"~", "¬", "!" are prefix operators
#"'" is the only postfix operator
operator = "'"
@property
def isliteral(self):
"""
Return True if object is a literal otherwise False.
"""
if isinstance(self.args[0], Symbol):
return True
else:
return False
def literalize(self):
"""
Return an expression where NOTs are only occuring as literals.
"""
# Not that important, to be consistent with Expression.literalize
if self.isliteral:
return self
expr = self.demorgan()
if isinstance(expr, self.__class__):
return expr
return expr.literalize()
def eval(self, **evalkwargs):
"""
Return a simplified term in canonical form.
This means double negations are canceled out and all contained boolean
objects are in their canonical form.
"""
if self.iscanonical:
return self
# self.literalize calls self.cancel which calls self.demorgan
term = self.literalize()
if not isinstance(term, self.__class__):
return term.eval()
elif term.args[0] in self.algebra.domain:
return term.args[0].dual
else:
expr = self.__class__(term.args[0].eval(**evalkwargs),
eval=False)
expr._iscanonical = True
return expr
def cancel(self):
"""
Cancel itself and following NOTs as far as possible.
Returns the simplified expression.
"""
term = self
while True:
arg = term.args[0]
if not isinstance(arg, self.__class__):
return term
term = arg.args[0]
if not isinstance(term, self.__class__):
return term
def demorgan(self):
"""
Return a term where the NOT function is moved inward.
This is achieved by canceling double NOTs and using de Morgan laws.
"""
term = self.cancel()
if term.isliteral or\
not isinstance(term.args[0], self.algebra.operations):
return term
op = term.args[0]
return op.dual(*tuple(self.__class__(arg, eval=False).cancel()
for arg in op.args), eval=False)
# TODO: Consider A+C+~B+~E vs A+~B+C+~E, does NOT(Symbol) need to be less
# than Symbol?
def __lt__(self, other):
if self.args[0] == other:
return False
return self.args[0].__lt__(other)
# Overwrites __str__ to allow for prime style printing
def __str__(self):
args = self.args
if self.isliteral:
if self.operator == "'":
return str(args[0]) + self.operator # A'
else:
return self.operator + str(args[0]) # ~A
else:
if isinstance(args[0], BaseElement) or args[0].order == (1, 1):
if self.operator == "'":
return "%s%s" % (str(args[0]), self.operator) # (A+B)''
else:
return "%s%s" % (self.operator, str(args[0])) # ~~(A+B)
else:
if self.operator == "'":
return "(%s)%s" % (str(args[0]), self.operator) # (A+B)'
else:
return "%s(%s)" % (self.operator, str(args[0])) # ~(A+B)
class DualBase(Function):
"""
Base class for AND and OR function.
This class uses the duality principle to combine similar methods of AND
and OR. Both operations take 2 or more arguments and can be created using
"+" for OR and "*" for AND.
"""
# Specifies the identity element for the specific operation. (TRUE for
# AND and FALSE for OR).
_identity = None
@property
def identity(self):
"""
Return the identity element for this function.
This will be TRUE for the AND operation and FALSE for the OR operation.
"""
return BaseElement(self._identity)
@property
def annihilator(self):
"""
Return the annihilator element for this function.
This will be FALSE for the AND operation and TRUE for the OR operation.
"""
return BaseElement(not self._identity)
@property
def dual(self):
"""
Return the dual class of this function.
This means OR.getdual() returns AND and AND.getdual() returns OR.
This is just a convenient shortcut for getdual()
"""
return self.getdual()
@classmethod
def getdual(cls):
"""
Return the dual class of this function.
This means OR.getdual() returns AND and AND.getdual() returns OR.
"""
ops = cls.algebra.operations
if issubclass(cls, ops.OR):
return ops.AND
elif issubclass(cls, ops.AND):
return ops.OR
else:
raise AttributeError("Class must be in algebra.operations.")
def __contains__(self, expr):
"""
Tests if expr is a subterm.
"""
if expr in self.args:
return True
if isinstance(expr, self.__class__):
if all(arg in self.args for arg in expr.args):
return True
return False
def eval(self, **evalkwargs):
"""
Return a simplified expression in canonical form.
For simplification of AND and OR following rules are used
recursively bottom up:
- Idempotence
- Commutivity (output is always sorted)
- Associativity (output doesn't contain same operations nested)
- Annihilation
- Identity
- Complementation
- Absorption
Other boolean objects are also in their canonical form.
"""
# TODO: Refactor DualBase.eval into different "sub-evals".
# attempt to unliteralize terms
# If self is already canonical do nothing.
if self.iscanonical:
return self
ops = self.algebra.operations
# Otherwise bring arguments into canonical form.
args = tuple(arg.eval() for arg in self.args)
# Create new instance of own class with canonical args. "eval" has to
# be set False - otherwise infinite recursion!
# TODO: Only create new class if some args changed.
term = self.__class__(*args, eval=False)
# Associativity:
# (A * B) * C = A * (B * C) = A * B * C
# (A + B) + C = A + (B + C) = A + B + C
term = term.flatten()
# Annihilation: A * 0 = 0, A + 1 = 1
if self.annihilator in term.args:
return self.annihilator
# Idempotence: A * A = A, A + A = A
args = []
for arg in term.args:
if arg not in args:
args.append(arg)
if len(args) == 1:
return args[0]
# Identity: A * 1 = A, A + 0 = A
if self.identity in args:
args.remove(self.identity)
if len(args) == 1:
return args[0]
# Complementation: A * ~A = 0, A + ~A = 1
for arg in args:
if ops.NOT(arg) in args:
return self.annihilator
# Elimination: (A * B) + (A * ~B) = A, (A + B) * (A + ~B) = A
i = 0
while i < len(args) - 1:
j = i + 1
ai = args[i]
if not isinstance(ai, self.dual):
i += 1
continue
while j < len(args):
aj = args[j]
if not isinstance(aj, self.dual) or \
len(ai.args) != len(aj.args):
j += 1
continue
# Find terms where only one arg is different.
negated = None
for arg in ai.args:
if arg in aj.args:
pass
elif ops.NOT(arg, eval=False).cancel() in aj.args:
if negated is None:
negated = arg
else:
negated = None
break
else:
negated = None
break
# If the different arg is a negation simplify the term.
if negated is not None:
# Cancel out one of the two terms.
del args[j]
aiargs = list(ai.args)
aiargs.remove(negated)
if len(aiargs) == 1:
args[i] = aiargs[0]
else:
args[i] = self.dual(*aiargs, eval=False)
if len(args) == 1:
return args[0]
else:
# Now the other simplifications have to be
# redone.
return self.__class__(*args, eval=True)
j += 1
i += 1
# Absorption: A * (A + B) = A, A + (A * B) = A
# Negative absorption: A * (~A + B) = A * B, A + (~A * B) = A + B
args = self.absorb(args)
if len(args) == 1:
return args[0]
# Commutivity: A * B = B * A, A + B = B + A
args.sort()
# Create new (now canonical) expression.
term = self.__class__(*args, eval=False)
term._iscanonical = True
return term
def flatten(self):
"""
Return a term where nested terms are flattened as far as possible.
E.g. A * (B * C) becomes A * B * C.
"""
args = list(self.args)
i = 0
for arg in self.args:
if isinstance(arg, self.__class__):
args[i:i + 1] = arg.args
i += len(arg.args)
else:
i += 1
return self.__class__(*args, eval=False)
def absorb(self, useargs=None):
# Absorption: A * (A + B) = A, A + (A * B) = A
# Negative absorption: A * (~A + B) = A * B, A + (~A * B) = A + B
args = list(self.args) if useargs is None else list(useargs)
ops = self.algebra.operations
i = 0
while i < len(args):
absorber = args[i]
j = 0
while j < len(args):
if j == i:
j += 1
continue
target = args[j]
if not isinstance(target, self.dual):
j += 1
continue
# Absorption
if absorber in target:
del args[j]
if j < i:
i -= 1
continue
# Negative absorption
neg_absorber = ops.NOT(absorber, eval=False).cancel()
if neg_absorber in target:
b = target.remove(neg_absorber, eval=False)
if b is None:
del args[j]
if j < i:
i -= 1
continue
else:
args[j] = b
j += 1
continue
if isinstance(absorber, self.dual):
remove = None
for arg in absorber.args:
narg = ops.NOT(arg, eval=False).cancel()
if arg in target.args:
pass
elif narg in target.args:
if remove is None:
remove = narg
else:
remove = None
break
else:
remove = None
break
if remove is not None:
args[j] = target.remove(remove)
j += 1
i += 1
if useargs:
return args
if len(args) == 1:
return args[0]
else:
return self.__class__(*args, eval=False)
def remove(self, expr, eval=True):
args = self.args
if expr in self.args:
args = list(self.args)
args.remove(expr)
elif isinstance(expr, self.__class__):
if all(arg in self.args for arg in expr.args):
args = tuple(arg for arg in self.args if arg not in expr)
if len(args) == 0:
return None
elif len(args) == 1:
return args[0]
else:
return self.__class__(*args, eval=eval)
def distributive(self):
"""
Return a term where the leading AND or OR terms are switched.
This is done by applying the distributive laws:
A * (B+C) = (A*B) + (A*C)
A + (B*C) = (A+B) * (A+C)
"""
dual = self.dual
args = list(self.args)
for i, arg in enumerate(args):
if isinstance(arg, dual):
args[i] = arg.args
else:
args[i] = (arg,)
prod = itertools.product(*args)
args = tuple(self.__class__(*arg) for arg in prod)
if len(args) == 1:
return args[0]
else:
return dual(*args, eval=False)
def __lt__(self, other):
cmp = Expression.__lt__(self, other)
if cmp is not NotImplemented:
return cmp
if isinstance(other, self.__class__):
lenself = len(self.args)
lenother = len(other.args)
for i in range(min(lenself, lenother)):
if self.args[i] == other.args[i]:
continue
cmp = self.args[i].__lt__(other.args[i])
if cmp is not NotImplemented:
return cmp
if lenself != lenother:
return lenself < lenother
return NotImplemented
class AND(DualBase):
"""
Boolean AND operation.
The AND operation takes 2 or more arguments and can also be created by
using "*" between two boolean expressions.
"""
_cls_order = 10
_identity = True
operator = "∙"
class OR(DualBase):
"""
Boolean OR operation.
The OR operation takes 2 or more arguments and can also be created by
using "+" between two boolean expressions.
"""
_cls_order = 25
_identity = False
operator = "+"
# Create a default algebra.
DOMAIN = BooleanDomain(TRUE=TRUE, FALSE=FALSE)
OPERATIONS = BooleanOperations(NOT=NOT, AND=AND, OR=OR)
ALGEBRA = Algebra(DOMAIN, OPERATIONS, Symbol)
Expression.algebra = ALGEBRA
def normalize(operation, expr):
"""