-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdemo.py
76 lines (66 loc) · 2.11 KB
/
demo.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
""" Text based demo of parse tree generation for convex optimization expressions. """
from dcp_parser.parser import Parser
def main():
welcome()
parser = Parser()
parse_file(parser)
explore_parse_trees(parser)
def welcome():
print "This is a demo of parse tree navigation."
def get_filename():
return raw_input('Name of the convex optimization script file: ')
def parse_file(parser):
while True:
try:
filename = get_filename()
f = open(filename, 'r')
break
except Exception as e:
print "Invalid filename"
for line in f.readlines():
try:
parser.parse(line)
except Exception as e:
print "Error parsing " + line
def select_expression(expressions):
for i in range(len(expressions)):
print "Expression %i: %s" % (i, str(expressions[i]))
index = int(raw_input('Select an expression by index: '))
return expressions[index]
def explore_parse_trees(parser):
parent_stack = []
exp = select_expression(parser.statements)
while True:
display_root(exp)
exp = select_child(exp, parent_stack)
def display_root(exp):
print
print "Current expression: %s" % exp
try:
print "Curvature: %s, Sign: %s" % (exp.curvature, exp.sign)
except Exception as e: # exp is a Constraint
pass
for error in exp.errors:
if error.is_indexed():
print "Argument %i:" % error.index
print str(error)
def select_child(exp, parent_stack):
num_children = len(exp.subexpressions)
if num_children > 0:
print "Child expressions:"
for i in range(num_children):
child = exp.subexpressions[i]
print "Expression %i: %s" % (i, child)
index = int(raw_input('Select a child expression by index (-1 for parent): '))
if index == -1:
if len(parent_stack) == 0:
return exp
else:
return parent_stack.pop()
elif num_children == 0:
return exp
else:
parent_stack.append(exp)
return exp.subexpressions[index]
if __name__ == "__main__":
main()