Add order details for logic board order.
[trinary.git] / tools / Expr.py
blob086e59462d791b366d8c037e83c866738ac547c0
1 #!/usr/bin/python
2 # vim: set fileencoding=utf8
3 # Created:20080216
4 # By Jeff Connelly
6 # Trinary expression evaluator
8 from Symbols import *
9 from Trits import Trits
11 DEBUG = False
13 unary_functions = {
14 # Everyone agrees on
15 u"/": Trits("10i"),
17 # Mouftah-based
18 u"∇": Trits("1ii"), u"└": Trits("1ii"),
19 u"∆": Trits("11i"), u"┘": Trits("11i"),
20 u"¬": Trits("001"),
21 u"⌐": Trits("i00"),
23 # Grubb-based
24 u"↘": Trits("ii0"),
25 u"↗": Trits("011"),
26 u"∩": Trits("01i"),
27 u"∪": Trits("10i"),
29 # Ternary-logic-minimization-literature-based
30 u"♨": Trits("01i")
33 def evaluate_unary(function, inputs):
34 """Given a unary function number in a Trits object, f, pass
35 all the trits in the inputs object through the function."""
37 assert isinstance(function, Trits), \
38 "Need to pass a Trits object as function"
39 assert isinstance(inputs, Trits), \
40 "You must pass a Trits object in inputs"
42 outputs = []
43 for t in inputs:
44 outputs.append({
45 False: function[0],
46 None: function[1],
47 True: function[2]
48 }[t])
50 return Trits(outputs)
52 class Expr(object):
53 def __init__(self, s):
54 assert len(s) > 0, "Empty string can't evaluate"
56 variable = s[-1]
57 assert variable.isalpha(), "Only accept expressions of form xxxxA, where x=unary operators, A=variable"
58 if DEBUG: print "Variable:", variable
60 # Evaluate gates from right-to-left
61 unary_gates = reversed(s[:-1])
63 # Start with identity function
64 total_unary = Trits("i01")
66 # Evaluate with unary function on the identity
67 for gate in unary_gates:
68 if DEBUG: print "Gate:", gate.encode('utf8')
69 total_unary = evaluate_unary(unary_functions[gate], total_unary)
71 # Now total_unary is the function# of all the unary gates
72 self.total_unary = total_unary
74 def evaluate(self, inputs):
75 return evaluate_unary(self.total_unary, inputs)
77 if __name__ == "__main__":
78 s = u"⌐∇a"
79 print "Expression:", s.encode('utf8')
80 e = Expr(s)
81 print "Total unary function is:", e.total_unary
82 print
84 ins = Trits("iiiiiiiii00000001111111")
85 print "Passing in trit vector as 'a':"
86 print "a:\t", ins
87 print s.encode('utf8') + ":\t", e.evaluate(ins)