comparison python/tree.py @ 320:84d67cce67b7

Working burg
author Windel Bouwman
date Sun, 19 Jan 2014 16:09:44 +0100
parents 8d07a4254f04
children 44f336460c2a
comparison
equal deleted inserted replaced
319:8d07a4254f04 320:84d67cce67b7
12 else: 12 else:
13 return '{}'.format(self.name) 13 return '{}'.format(self.name)
14 14
15 15
16 class State: 16 class State:
17 """ State used to label tree nodes """
17 def __init__(self): 18 def __init__(self):
18 self.labels = {} 19 self.labels = {}
20
19 def has_goal(self, goal): 21 def has_goal(self, goal):
20 return goal in self.labels 22 return goal in self.labels
23
21 def get_cost(self, goal): 24 def get_cost(self, goal):
22 if not self.has_goal(goal): return 999999
23 return self.labels[goal][0] 25 return self.labels[goal][0]
26
24 def get_rule(self, goal): 27 def get_rule(self, goal):
25 return self.labels[goal][1] 28 return self.labels[goal][1]
29
26 def set_cost(self, goal, cost, rule): 30 def set_cost(self, goal, cost, rule):
27 if self.has_goal(goal): 31 if self.has_goal(goal):
28 if self.get_cost(goal) > cost: 32 if self.get_cost(goal) > cost:
29 self.labels[goal] = (cost, rule) 33 self.labels[goal] = (cost, rule)
30 else: 34 else:
31 self.labels[goal] = (cost, rule) 35 self.labels[goal] = (cost, rule)
32 36
37
33 class BaseMatcher: 38 class BaseMatcher:
39 """ Base class for matcher objects. """
34 def kids(self, tree, rule): 40 def kids(self, tree, rule):
35 return self.kid_functions[rule](tree) 41 return self.kid_functions[rule](tree)
36 42
37 def nts(self, rule): 43 def nts(self, rule):
38 return self.nts_map[rule] 44 return self.nts_map[rule]
39 45
40 def burm_label(self, tree): 46 def burm_label(self, tree):
47 """ Label all nodes in the tree bottom up """
41 for c in tree.children: 48 for c in tree.children:
42 self.burm_label(c) 49 self.burm_label(c)
43 self.burm_state(tree) 50 self.burm_state(tree)
44 51
45 def apply_rules(self, tree, goal): 52 def apply_rules(self, tree, goal):
46 print(tree.state.get_rule(goal))
47 rule = tree.state.get_rule(goal) 53 rule = tree.state.get_rule(goal)
48 for kid_tree, kid_goal in zip(self.kids(tree, rule), self.nts(rule)): 54 results = [self.apply_rules(kid_tree, kid_goal)
49 self.apply_rules(kid_tree, kid_goal) 55 for kid_tree, kid_goal in zip(self.kids(tree, rule), self.nts(rule))]
56 self.pat_f[rule](*results)