Source

pyarith / logics / prop.py

Full commit
  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
#!/usr/local/bin/python
# -*- coding: utf-8 -*-

"""A module providing functions and classes to represent and manipulate
propositional logic.
"""

from abc import ABCMeta, abstractmethod
import base
from six import with_metaclass

def pretty_print(prop):

    if type(prop) == Var:
        return [str(prop)]
    elif type(prop) == Not:
        return ['Not'] + \
            ['  {0}'.format(line) for line in pretty_print(prop.child)]
    else:
        return [prop.__class__.__name__] + \
            ['  {0}'.format(line) for line in pretty_print(prop.left)] + \
            ['  {0}'.format(line) for line in pretty_print(prop.right)]


def eval(prop, variables):
    return prop._eval(variables)


def equivalent_DNF(prop1, prop2):
    return canonicalize_DNF(prop1) == canonicalize_DNF(prop2)


def equivalent_CNF(prop1, prop2):
    return canonicalize_CNF(prop1) == canonicalize_CNF(prop2)


equivalent = equivalent_DNF


def replace_with_And_Or_Not(prop):
    if type(prop) == Constant:
        return prop
    elif type(prop) == Var:
        return prop
    elif type(prop) == Not:
        return Not(replace_with_And_Or_Not(prop.child))
    elif type(prop) == And:
        return And(replace_with_And_Or_Not(prop.left),
                   replace_with_And_Or_Not(prop.right))
    elif type(prop) == Or:
        return Or(replace_with_And_Or_Not(prop.left),
                  replace_with_And_Or_Not(prop.right))
    elif type(prop) == IfThen:
        return Or(Not(replace_with_And_Or_Not(prop.left)),
                  replace_with_And_Or_Not(prop.right))
    elif type(prop) == Iff:
        left = replace_with_And_Or_Not(prop.left)
        right = replace_with_And_Or_Not(prop.right)
        return Or(And(left, right),
                  And(Not(left), Not(right)))
    elif type(prop) == Xor:
        left = replace_with_And_Or_Not(prop.left)
        right = replace_with_And_Or_Not(prop.right)
        return Or(And(left, Not(right)),
                  And(Not(left), right))
    else:
        raise TypeError('type "{0}({1}, {2})" is not supported.'
                        .format(type(prop), type(prop.left), type(prop.right)))


def sink_Not(prop):
    """prop should not include node of type IfThen, Iff or Xor"""
    if type(prop) == Constant:
        return prop
    elif type(prop) == Var:
        return prop
    elif type(prop) == Not:
        child = sink_Not(prop.child)
        if type(child) == Constant: #1
            if child:
                return F
            else:
                return T
        elif type(child) == Var: #2
            return Not(child)
        elif type(child) == Not: #3
            return child.child
        elif type(child) == Or: #4
            return And(sink_Not(Not(child.left)),
                       sink_Not(Not(child.right)))
        elif type(child) == And: #5
            return Or(sink_Not(Not(child.left)),
                      sink_Not(Not(child.right)))
        else:
            raise TypeError('type "Not({0})" is not supported.'
                            .format(type(child)))
    elif type(prop) == Or:
        return Or(sink_Not(prop.left), sink_Not(prop.right))
    elif type(prop) == And:
        return And(sink_Not(prop.left), sink_Not(prop.right))
    else:
        raise TypeError('type "{0}" is not supported.'
                        .format(type(prop)))


def _is_primitive(prop):
    """Constant, Var or Not(Var)"""
    if type(prop) == Constant:
        return True
    elif type(prop) == Var:
        return True
    elif type(prop) == Not:
        return type(prop.child) == Var
    else:
        return False


def _is_single(prop):
    if type(prop) == Constant:
        return True
    elif type(prop) == Var:
        return True
    elif type(prop) == Not:
        return _is_single(prop.child)
    else:
        return False


def normalize_DNF(prop):
    """transform proposition into disjunction normal form (DNF).

    This function is ideompotent.

    Normal form
    ===========
    (p_1 and p_2 and...and p_n) or...or (q_1 and q_2 and...and q_m)

    p_i is a variable or variable with a single nagation.

    Algorithm
    =========

    1st step. removing "IfThen", "Iff" and "Xor"
    --------------------------------------------

    - IfThen(p, q) -> Or(Not(p), q)
    - Iff(p, q) -> Or(And(p, q), And(Not(p), Not(q)))
    - Xor(p, q) -> Or(And(left, Not(right)), And(Not(left), right))

    2nd step. sinking "Not"
    -----------------------

    1. Not(T), Not(F) -> F, T
    2. Not(Var) -> do nothing
    3. Not(Not(p)) -> p
    4. Not(And(p, q)) -> Or(Not(p), Not(q))
    5. Not(Or(p, q)) -> And(Not(p), Not(q))

    3rd step. sinking "And"
    -----------------------

    A, B,...: T, F, Var, Not(Var)
    p, q,...: T, F, Var, Not, And, Or

    1. And(A, B) -> do nothing
    2. And(A, And(p, q)) -> do nothing
    3. And(A, Or(p, q)) -> Or(And(A, p), And(A, q))

    4. And(And(p, q), A) -> And(p, And(q, A))
    5. And(And(p, q), And(r, s)) -> And(p, And(q, And(r, s)))
    6. And(And(p, q), Or(r, s)) -> Or(And(And(p, q), r), And(And(p, q), s))

    7. And(Or(p, q), A) -> Or(And(p, A), And(q, A))
    8. And(Or(p, q), And(r, s)) -> Or(And(p, And(r, s)), And(q, And(r, s)))
    9. And(Or(p, q), Or(r, s)) -> Or(And(p, Or(r, s)), And(q, Or(r, s)))

    Pattern #7, #8 and #9 are unified into

    10. And(Or(p, q), r) -> Or(And(p, r), And(q, r)).

    Pattern #3 and #6 are unified into

    11. And(p, Or(q, r)) -> Or(And(p, q), And(p, r)).

    Pattern #4 and #5 are unified into

    12. And(And(p, q), r) -> And(p, And(q, r)).

    Finally, we need transformation rules #1, #2, #10, #11 and #12.

    4th step. well-ordering "Or"
    ----------------------------

    A, B,...: T, F, Var, Not, And (= anything except Or)
    p, q,...: T, F, Var, Not, And, Or (= anything)

    1. Or(A, B) -> do nothing
    2. Or(Or(p, q), A) -> Or(p, Or(q, A))
    3. Or(A, Or(p, q)) -> do nothing
    4. Or(Or(p, q), Or(r, s)) -> Or(p, Or(q, Or(r, s)))

    Pattern #1 and #3 are unified into

    5. Or(A, p) -> do nothing.

    Pattern #2 and #4 are unified into

    6. Or(Or(p, q), r) -> Or(p, Or(q, r)).

    Finally, we need transform rules #5 and #6.

    """

    def sink_And(prop):
        if _is_primitive(prop):
            return prop
        elif type(prop) == And:
            left = sink_And(prop.left)
            right = sink_And(prop.right)
            if type(left) == Or: #10
                return Or(sink_And(And(left.left, right)),
                          sink_And(And(left.right, right)))
            elif type(right) == Or: #11
                return Or(sink_And(And(left, right.left)),
                          sink_And(And(left, right.right)))
            elif type(left) == And: #12
                return And(left.left, sink_And(And(left.right, right)))
            else:
                return And(left, right)
        elif type(prop) == Or:
            return Or(sink_And(prop.left), sink_And(prop.right))
        else: #1, #2
            raise TypeError('type "{0}" is not supported.'
                            .format(type(prop)))

    def order_Or(prop):
        if _is_primitive(prop):
            return prop
        elif type(prop) == And:
            return prop
        elif type(prop) == Or:
            left = order_Or(prop.left)
            right = order_Or(prop.right)
            if _is_primitive(left):
                return Or(left, right)
            elif type(left) == And:
                return Or(left, right)
            elif type(left) == Or:
                return Or(left.left, order_Or(Or(left.right, right)))
            else:
                raise TypeError('type "Or({0}, {1})" is not supported.'
                                .format(type(prop.left), type(prop.right)))
        else:
            raise TypeError('type "{0}" is not supported.'
                            .format(type(prop)))

    return order_Or(sink_And(sink_Not(replace_with_And_Or_Not(prop))))


def normalize_CNF(prop):
    """transform proposition into conjunction normal form (CNF).

    This function is ideompotent.

    Normal form
    ===========
    (p_1 or p_2 or...or p_n) and...and (q_1 or q_2 or...or q_m)

    p_i is a variable or variable with a single nagation.

    Algorithm
    =========

    1st step. removing "IfThen"
    ---------------------------

    - IfThen(p, q) -> Or(Not(p), q)
    - Iff(p, q) -> Or(And(p, q), And(Not(p), Not(q)))
    - Xor(p, q) -> Or(And(left, Not(right)), And(Not(left), right))

    2nd step. sinking "Not"
    -----------------------

    1. Not(T), Not(F) -> F, T
    2. Not(Var) -> do nothing
    3. Not(Not(p)) -> p
    4. Not(Or(p, q)) -> And(Not(p), Not(q))
    5. Not(And(p, q)) -> Or(Not(p), Not(q))

    3rd step. sinking "Or"
    ----------------------
    A, B,...: T, F, Var, Not(Var)
    p, q,...: T, F, Var, Not, And, Or

    1. Or(A, B) -> do nothing
    2. Or(A, Or(p, q)) -> do nothing
    3. Or(A, And(p, q)) -> And(Or(A, p), Or(A, q))

    4. Or(Or(p, q), A) -> Or(p, Or(q, A))
    5. Or(Or(p, q), Or(r, s)) -> Or(p, Or(q, Or(r, s)))
    6. Or(Or(p, q), And(r, s)) -> And(Or(Or(p, q), r), Or(Or(p, q), s))

    7. Or(And(p, q), A) -> And(Or(p, A), Or(q, A))
    8. Or(And(p, q), Or(r, s)) -> And(Or(p, Or(r, s)), Or(q, Or(r, s)))
    9. Or(And(p, q), And(r, s)) -> And(Or(p, And(r, s)), Or(q, And(r, s)))

    Pattern #7, #8 and #9 are unified into

    10. Or(And(p, q), r) -> And(Or(p, r), Or(q, r)).

    Pattern #3 and #6 are unified into

    11. Or(p, And(q, r)) -> And(Or(p, q), Or(p, r)).

    Pattern #4 and #5 are unified into

    12. Or(Or(p, q), r) -> Or(p, Or(q, r)).

    Finally, we need transformation rules #1, #2, #10, #11 and #12.

    4th step. well-ordering "And"
    -----------------------------

    A, B,...: T, F, Var, Not, Or (= anything except And)
    p, q,...: T, F, Var, Not, And, Or (= anything)

    1. And(A, B) -> do nothing
    2. And(And(p, q), A) -> And(p, And(q, A))
    3. And(A, And(p, q)) -> do nothing
    4. And(And(p, q), And(r, s)) -> And(p, And(q, And(r, s)))

    Pattern #1 and #3 are unified into

    5. And(A, p) -> do nothing.

    Pattern #2 and #4 are unified into

    6. And(And(p, q), r) -> And(p, And(q, r)).

    Finally, we need transform rules #5 and #6.

    """

    def sink_Or(prop):
        if _is_primitive(prop):
            return prop
        elif type(prop) == Or:
            left = sink_Or(prop.left)
            right = sink_Or(prop.right)
            if type(left) == And: #10
                return And(sink_Or(Or(left.left, right)),
                           sink_Or(Or(left.right, right)))
            elif type(right) == And: #11
                return And(sink_Or(Or(left, right.left)),
                           sink_Or(Or(left, right.right)))
            elif type(left) == Or: #12
                return Or(left.left, sink_Or(Or(left.right, right)))
            else: #1, #2
                return Or(left, right)
        elif type(prop) == And:
            return And(sink_Or(prop.left), sink_Or(prop.right))
        else:
            raise TypeError('type "{0}" is not supported.'
                            .format(type(prop)))


    def order_And(prop):
        if _is_primitive(prop):
            return prop
        elif type(prop) == Or:
            return prop
        elif type(prop) == And:
            left = order_And(prop.left)
            right = order_And(prop.right)
            if _is_primitive(left):
                return And(left, right)
            elif type(left) == Or:
                return And(left, right)
            elif type(left) == And:
                return And(left.left, order_And(And(left.right, right)))
            else:
                raise TypeError('type "And({0}, {1})" is not supported.'
                                .format(type(prop.left), type(prop.right)))
        else:
            raise TypeError('type "{0}" is not supported.'
                            .format(type(prop)))
            
    return order_And(sink_Or(sink_Not(replace_with_And_Or_Not(prop))))


def canonicalize_DNF(prop):

    def compress_conj(conj):
        """Remove terms which is redundant or can be reduced into T or F
        in conjugate form. Additionally, ordering terms for performance.

        Algorithm is a modified insertion sort.

        A, B,...: Constant, Var, Not(Var)
        p, q,...: any term

        1. A -> do nothing
        2. Constant

           1. And(T, p) -> p
           2. And(F, p) -> F
           3. And(A, T) -> A
           4. And(A, F) -> F

        3. Var, Not(Var)

           1. And(A, A) -> A
           2. And(A, Not(A)) -> F
           3. And(Not(A), Not(A)) -> Not(A)
           4. And(Not(A), A) -> F
           5. And(A, B) -> And(B, A) (A.varnames[0] > B.varnames[0])

        4. p: prop

           1. And(A, And(A, p)) -> And(A, p)
           2. And(A, And(Not(A), p)) -> F
           3. And(Not(A), And(Not(A), p)) -> And(Not(A), p)
           4. And(Not(A), And(A, p)) -> F
           5. And(A, And(B, p)) -> And(B, And(A, p))
              (A.varnames[0] > B.varnames[0])

        """

        if _is_primitive(conj): # 1
            return conj

        assert type(conj) == And

        if conj.left == T: # 2-1
            return compress_conj(conj.right)
        elif conj.left == F: # 2-2
            return F

        right = compress_conj(conj.right)

        if right == T: # 2-3
            return conj.left
        elif right == F: # 2-4
            return F

        if _is_primitive(right):
            if conj.left == right: # 3-1, 3-3
                return conj.left
            elif Not(conj.left) == right or conj.left == Not(right): # 3-2, 3-4
                return F
            elif conj.left.varnames[0] > right.varnames[0]: # 3-5
                return And(right, conj.left)
        else:
            if conj.left == right.left: # 4-1, 4-3
                return right
            elif Not(conj.left) == right.left or \
                    conj.left == Not(right.left): # 4-2, 4-4
                return F
            elif conj.left.varnames[0] > right.left.varnames[0]: # 4-5
                return compress_conj(And(right.left,
                                         And(conj.left, right.right)))

        return And(conj.left, right)

    def rec_compress(dnf):
        """apply function 'compress_conj' recursively'"""
        if _is_primitive(dnf):
            return dnf
        elif type(dnf) == And:
            return compress_conj(dnf)
        else:
            assert type(dnf) == Or
            return Or(compress_conj(dnf.left), rec_compress(dnf.right))

    def filter_literal(literal, dnf):
        if _is_primitive(dnf):
            if dnf == literal:
                return T
            elif dnf == Not(literal) or Not(dnf) == literal:
                return F
            else:
                return dnf
        elif type(dnf) == And:
            if dnf.left == literal:
                return dnf.right
            elif dnf.left == Not(literal) or Not(dnf.left) == literal:
                return F
            else:
                return dnf
        else:
            assert type(dnf) == Or

            left = filter_literal(literal, dnf.left)
            right = filter_literal(literal, dnf.right)

            if left == T or right == T:
                return T
            elif left == F:
                return right
            elif right == F:
                return left
            else:
                return Or(left, right)

    def canonicalize(dnf):
        """Canonical form: (A & f(B, C,...)) | (~A & g(B, C,...)) (f ≠ g)"""
        if _is_primitive(dnf):
            return dnf
        elif type(dnf) == And:
            return dnf
        else:
            assert type(dnf) == Or

            if len(dnf.varnames) == 0:
                if dnf.left == T:
                    return canonicalize(cnf.right)
                elif dnf.left == F:
                    return F
                else:
                    raise ValueError('Prop: {0} is not acceptable.'.format(dnf))

            var = Var(dnf.varnames[0])
            positive = canonicalize(filter_literal(var, dnf))
            negative = canonicalize(filter_literal(Not(var), dnf))

            if positive == negative:
                return positive

            if positive == T:
                left = var
            elif positive == F:
                left = F
            else:
                left = And(var, positive)

            if negative == T:
                right = Not(var)
            elif negative == F:
                right = F
            else:
                right = And(Not(var), negative)

            if left == T or right == T:
                return T
            elif left == F:
                return right
            elif right == F:
                return left
            elif left == Not(right) or Not(left) == right:
                return T
            else:
                return Or(left, right)

    return canonicalize(rec_compress(normalize_DNF(prop)))


def canonicalize_CNF(prop):
    """dual of canonicalize_DNF"""

    def compress_disj(disj):

        if _is_primitive(disj):
            return disj

        assert type(disj) == Or

        if disj.left == T:
            return T
        elif disj.left == F:
            return compress_disj(disj.right)

        right = compress_disj(disj.right)

        if right == T:
            return T
        elif right == F:
            return disj.left

        if _is_primitive(right):
            if disj.left == right:
                return disj.left
            elif Not(disj.left) == right or disj.left == Not(right):
                return T
            elif disj.left.varnames[0] > right.varnames[0]:
                return Or(right, disj.left)
        else:
            if disj.left == right.left:
                return right
            elif Not(disj.left) == right.left or \
                    disj.left == Not(right.left):
                return T
            elif disj.left.varnames[0] > right.left.varnames[0]:
                return compress_disj(Or(right.left,
                                        Or(disj.left, right.right)))

        return Or(disj.left, right)

    def rec_compress(cnf):
        if _is_primitive(cnf):
            return cnf
        elif type(cnf) == Or:
            return compress_disj(cnf)
        else:
            assert type(cnf) == And
            return And(compress_disj(cnf.left), rec_compress(cnf.right))

    def filter_literal(literal, cnf):
        if _is_primitive(cnf):
            if cnf == literal:
                return F
            elif cnf == Not(literal) or Not(cnf) == literal:
                return T
            else:
                return cnf
        elif type(cnf) == Or:
            if cnf.left == literal:
                return cnf.right
            elif cnf.left == Not(literal) or Not(cnf.left) == literal:
                return T
            else:
                return cnf
        else:
            assert type(cnf) == And

            left = filter_literal(literal, cnf.left)
            right = filter_literal(literal, cnf.right)

            if left == F or right == F:
                return F
            elif left == T:
                return right
            elif right == T:
                return left
            else:
                return And(left, right)

    def canonicalize(cnf):
        if _is_primitive(cnf):
            return cnf
        elif type(cnf) == Or:
            return cnf
        else:
            assert type(cnf) == And

            if len(cnf.varnames) == 0:
                if cnf.left == T:
                    return canonicalize(cnf.right)
                elif cnf.left == F:
                    return F
                else:
                    raise ValueError('Prop: {0} is not acceptable.'.format(cnf))

            var = Var(cnf.varnames[0])
            positive = canonicalize(filter_literal(var, cnf))
            negative = canonicalize(filter_literal(Not(var), cnf))

            if positive == negative:
                return positive

            if positive == T:
                left = T
            elif positive == F:
                left = var
            else:
                left = Or(var, positive)

            if negative == T:
                right = T
            elif negative == F:
                right = Not(var)
            else:
                right = Or(Not(var), negative)

            if left == F or right == F:
                return F
            elif left == T:
                return right
            elif right == T:
                return left
            elif left == Not(right) or Not(left) == right:
                return F
            else:
                return And(left, right)

    return canonicalize(rec_compress(normalize_CNF(prop)))


class TotallyOrderedSet(tuple):
    """http://www.python.jp/doc/nightly/library/stdtypes.html#typesseq"""

    def __new__(cls, *args, **kwargs):
        if len(args) == 0:
            return tuple.__new__(cls)
        else:
            import collections
            if not isinstance(args[0], collections.Iterable):
                return tuple.__new__(cls, args[0])
            else:
                return tuple.__new__(cls, sorted(set(args[0])))

    def __add__(self, other):
        result = tuple.__add__(self, other)
        return TotallyOrderedSet(result)

    def __mul__(self, other):
        result = tuple.__mul__(self, other)
        return TotallyOrderedSet(result)

    def __rmul__(self, other):
        result = tuple.__rmul__(self, other)
        return TotallyOrderedSet(result)


class Prop(with_metaclass(ABCMeta, base=base.Element)):

    @abstractmethod
    def _eval(self, variables):
        pass

    def __and__(self, other):
        assert isinstance(other, Prop)
        return And(self, other)

    def __or__(self, other):
        assert isinstance(other, Prop)
        return Or(self, other)

    def __invert__(self):
        return Not(self)

    def __xor__(self, other):
        assert isinstance(other, Prop)
        return Xor(self, other)


class Constant(Prop):
    """2-singletons"""

    _True = None
    _False = None

    def __new__(cls, value):
        if value:
            if cls._True is None:
                cls._True = object.__new__(cls)
                cls._True.name = 'T'
                cls._True.varnames = TotallyOrderedSet()
            return cls._True
        else:
            if cls._False is None:
                cls._False = object.__new__(cls)
                cls._False.name = 'F'
                cls._False.varnames = TotallyOrderedSet()
            return cls._False

    def __init__(self, value):
        self.value = value

    def _eval(self):
        return self.value

    def __eq__(self, other):
        return id(self) == id(other)

    def __str__(self):
        return self.name

    def __repr__(self):
        return '<logics.prop.Constant {0}>'.format(self.name)

    def __bool__(self):
        return self.value

    def __nonzero__(self):
        return self.__bool__()


T = Constant(True)
F = Constant(False)


class Var(Prop):

    def __init__(self, name):
        self.name = name
        self.varnames = TotallyOrderedSet([name])

    def _eval(self, variables):
        if self.name in variables:
            return variables[self.name]
        else:
            raise UndefinedVariableError(self)

    def __str__(self):
        return self.name

    def __repr__(self):
        return '<logics.prop.Var name: {0}>'.format(self.name)

    def __lt__(self, other):
        if type(self) == type(other):
            return self.name.__lt__(other.name)
        return False

    def __le__(self, other):
        if type(self) == type(other):
            return self.name.__le__(other.name)
        return False

    def __eq__(self, other):
        if type(self) == type(other):
            return self.name.__eq__(other.name)
        return False

    def __ne__(self, other):
        if type(self) == type(other):
            return self.name.__ne__(other.name)
        return False

    def __gt__(self, other):
        if type(self) == type(other):
            return self.name.__gt__(other.name)
        return False

    def __ge__(self, other):
        if type(self) == type(other):
            return self.name.__ge__(other.name)
        return False


class Not(Prop):

    def __init__(self, prop):
        self.child = prop
        self.varnames = prop.varnames

    def _eval(self, variables):
        return not eval(self.child, variables)

    def __str__(self):
        if _is_single(self):
            return '~{0}'.format(self.child)
        else:
            return '~({0})'.format(self.child)

    def __repr__(self):
        return '<logics.prop.Not expr: {0}>'.format(self)

    def __eq__(self, other):
        if type(self) == type(other):
            return self.child == other.child
        return False


class And(Prop):

    def __init__(self, left, right):
        self.left = left
        self.right = right
        self.varnames = left.varnames + right.varnames

    def _eval(self, variables):
        return eval(self.left, variables) and eval(self.right, variables)

    def __str__(self):
        if _is_single(self.left):
            left = str(self.left)
        else:
            left = '({0})'.format(self.left)

        if _is_single(self.right):
            right = str(self.right)
        else:
            right = '({0})'.format(self.right)

        return '{0} & {1}'.format(left, right)

    def __repr__(self):
        return '<logics.prop.And expr: {0}>'.format(self)

    def __eq__(self, other):
        if type(self) == type(other):
            return self.left == other.left and self.right == other.right
        return False


class Or(Prop):

    def __init__(self, left, right):
        self.left = left
        self.right = right
        self.varnames = left.varnames + right.varnames

    def _eval(self, variables):
        return eval(self.left, variables) or eval(self.right, variables)

    def __str__(self):
        if _is_single(self.left):
            left = str(self.left)
        else:
            left = '({0})'.format(self.left)

        if _is_single(self.right):
            right = str(self.right)
        else:
            right = '({0})'.format(self.right)

        return '{0} | {1}'.format(left, right)

    def __repr__(self):
        return '<logics.prop.Or expr: {0}>'.format(str(self))

    def __eq__(self, other):
        if type(self) == type(other):
            return self.left == other.left and self.right == other.right
        return False


class IfThen(Prop):

    def __init__(self, left, right):
        self.left = left
        self.right = right
        self.varnames = left.varnames + right.varnames

    def _eval(self, variables):
        return not eval(self.left, variables) or eval(self.right, variables)

    def __str__(self):
        return '({0}) => ({1})'.format(str(self.left), str(self.right))

    def __repr__(self):
        return '<logics.prop.IfThen expr: {0}>'.format(str(self))

    def __eq__(self, other):
        if type(self) == type(other):
            return self.left == other.left and self.right == other.right
        return False


class Iff(Prop):

    def __init__(self, left, right):
        self.left = left
        self.right = right
        self.varnames = left.varnames + right.varnames

    def _eval(self, variables):
        return eval(self.left, variables) == eval(self.right, variables)

    def __str__(self):
        return '({0}) <=> ({1})'.format(str(self.left), str(self.right))

    def __repr__(self):
        return '<logics.prop.Iff expr: {0}>'.format(str(self))

    def __eq__(self, other):
        if type(self) == type(other):
            return self.left == other.left and self.right == other.right
        return False


class Xor(Prop):

    def __init__(self, left, right):
        self.left = left
        self.right = right
        self.varnames = left.varnames + right.varnames

    def _eval(self, variables):
        return eval(self.left, variables) ^ eval(self.right, variables)

    def __str__(self):
        return '({0}) ^ ({1})'.format(str(self.left), str(self.right))

    def __repr__(self):
        return '<logics.prop.Xor expr: {0}>'.format(str(self))

    def __eq__(self):
        if type(self) == type(other):
            return self.left == other.left and self.right == other.right
        return False


class UndefinedVariableError(Exception):

    def __init__(self, variable):
        self.variable = variable

    def __str__(self):
        return 'a propositional variable "{0}"' \
            ' is not bound to a boolean value.'.format(self.variable)