diff --git a/cfg_utils.py b/cfg_utils.py index 74be234d654c635b197c395e4de5f9c4822812c4..a04bc79ca1f43d93e6052abd5e6b62e1797cede1 100644 --- a/cfg_utils.py +++ b/cfg_utils.py @@ -10,7 +10,16 @@ class TreeNode: self.subnodes = subnodes def __str__(self): - return str(self.language_element) + str(self.subnodes) + return str(self.language_element) + " " + str(self.subnodes) + + +def walk_the_tree(tree, level = 1): + if tree == None: + return + + print(" " * (level -1) + "|---" + hex(tree.language_element) + " with " + str(len(tree.subnodes)) + " subnodes") + for subnode in tree.subnodes: + walk_the_tree(subnode, level + 1) @@ -45,7 +54,7 @@ CFG = collections.namedtuple("CFG", "nonterminals terminals rules start") # FACTOR -> INTEGER symbols = Enum("Symbols", "EXPRESSION TERM FACTOR INTEGER ADDOP MULTOP OPENPAREN CLOSEPAREN") -start = nonterminals.EXPRESSION +start = symbols.EXPRESSION # The rules are a list of tuples, each of which represents a rule, as follows: @@ -60,7 +69,7 @@ rules = [ (symbols.FACTOR, [symbols.INTEGER ]) ] -print(rules) +#print(rules) @@ -70,7 +79,7 @@ print(rules) # This, however, is not Boltzmann sampling. -# We examine all the leaves on the current derivationt tree. Those mark where we possibly could apply a rule. +# We examine all the leaves on the current derivation tree. Those mark where we possibly could apply a rule. # We then determine which leaves are amenable to rule application, and then we randomly select a leaf and for # that leaf, we randomly select a rule, and apply it. @@ -78,11 +87,34 @@ print(rules) # the generated string (in order to do pseudo-Boltzmann sampling). -def next_stage(derivation_tree_with_cached, language_definition): + +def apply_rule(tree, location, rule_number, ruleset): + # first, we isolate the place on the tree that we are going to do the graft. + opsite = tree + + for depth_index in location: + opsite = opsite.subnodes[depth_index] + print("TMP index ", depth_index, " gives ",opsite) + + print(opsite) + walk_the_tree(opsite) + + + +test_tree = TreeNode(0, [ + TreeNode(1,[]), + TreeNode(2,[ + TreeNode(3,[]), TreeNode(4,[]),TreeNode(5,[]) + ]) + ]) + +walk_the_tree(test_tree) +#def next_stage(derivation_tree_with_cached, language_definition): +apply_rule(test_tree,[1,1],None,None) # Furthermore, we also note that the description of a context-free grammar is *itself* context-free # so if we take the CFG-description grammar (BNF or something isomorphic to it), and use Boltzmann