def tree_pretty_print(tree): """Pretty-print a tree of python objects. Examples:: >>> from pptree import Node >>> users = Node("users") >>> group = Node("group", users) >>> _ = Node("roles", group) >>> _ = Node("permissions", group) >>> _ = Node("comments", users) >>> print(tree_pretty_print(users).strip()) ┌comments users┤ │ ┌roles └group┤ └permissions Include 5 tables """ with redirect_stdout() as stream: print_tree(tree) def flatten(node): yield node.name for child in node.children: yield from flatten(child) # noqa flat = list(flatten(tree)) return stream.getvalue() + "\n\n" + "Include %s tables\n" % len(flat)
def main(): """Go go go!""" #<<< test() tree = build_tree(ISLANDERS) pptree.print_tree(tree)
def showTree(): """ Shows the Device Tree as ASCII Tree """ try: import pptree pptree.print_tree(Devices,"Modules") except: pass
def pretty_print_tree(tree): """ Print a tree out with a visualized tree structure. :param tree: the tree to print """ pptree.print_tree(map_tree(lambda val: str(get_val(val)), tree), nameattr="value")
def mostrarArvore(self): # Montando os segmentos para utilizar o PPTREEE nos = [] nos.append(Node('0')) for key in self.arvore.keys(): if(key != 0): nos.append(Node(str(key), nos[self.arvore[key][0]])) print('\r\nArvore de segmentos do job ' + str(self.nome)) print_tree(nos[0])
def echo(self): """ Print the current tree :return: None """ pptree.print_tree(self.out_pptree()) print("Size of the tree : %d" % self.get_size()) print("Height of the tree : %d" % self.get_height())
def tree_printer(sentence: Sentence, tag_type: str): tree: List[NodeToken] = [NodeToken(token, tag_type) for token in sentence] for x in tree: if x.token.head_id != 0: head_token = x.token.get_head() for y in tree: if y.token == head_token: x.set_haed(y) else: root_node = x print_tree(root_node, "children")
def simple_view(tree): old_stdout = sys.stdout new_stdout = StringIO() sys.stdout = new_stdout print_tree(tree.root, 'childrenArray') output = new_stdout.getvalue() sys.stdout = old_stdout return output
def main(): if len(sys.argv[1:]) == 0: args = sys.stdin else: args = sys.argv[1:] for line in args: line = line.strip() root = Node(line) file = h5py.File(line, "r") traverse(root, file) print_tree(root)
def main(): grammar = (("<E>", "<E>", "**", "<E>"), ("<E>", "<E>", "*", "<E>"), ("<E>", "<E>", "+", "<E>"), ("<E>", "(", "<E>", ")"), ("<E>", "<N>"), ("<N>", "0", "<N>"), ("<N>", "1", "<N>"), ("<N>", "0"), ("<N>", "1")) parser = Parser(grammar) i = input() print(parser.valid(i)) if parser.valid(i): print_tree(parser.parse(i), childattr='children', nameattr='name')
def list_snapshots(si, stack_name): vms = filter(lambda vm: vm.name.startswith(stack_name), get_vms(si)) for vm in vms: currentSnapshotTree = _get_vm_snapshot_recursively( vm.snapshot.rootSnapshotList, lambda snapshotTree: snapshotTree. snapshot == vm.snapshot.currentSnapshot) print("'%s' current snapshot '%s'" % (vm.name, currentSnapshotTree.name)) for rootSnapshot in vm.snapshot.rootSnapshotList: pptree.print_tree(rootSnapshot, "childSnapshotList", "name", last="down")
def CallDepthFirstSearchRecurs(): dataTable,mapPoints = marios.CreateMapDataTable(fileName) root,goal = Node(mapPoints['p']),mapPoints['g'] def DepthFirstSearchRecurs(subRoot=None,visitedNodes=None,meta=None,metaNodes=None,itter=1): if visitedNodes is None: visitedNodes = set() if metaNodes is None: metaNodes=set() if subRoot is None: subRoot=Node(mapPoints['p']) meta=subRoot else: if meta is None: meta=subRoot else: pass visitedNodes.add(subRoot) meta=subRoot if(subRoot.data==goal): return subRoot for(action,child) in marios.ClosebyDataPoints(subRoot,dataTable).items(): if(child not in visitedNodes): t = visitedNodes.copy() if(child not in metaNodes): #print(child.data,"child.data") metaNodes.add(child) meta.AddChild(child) if(itter!=1): ans = DepthFirstSearchRecurs(child,visitedNodes,meta,metaNodes,itter+1) if((not type(ans)==tuple)and(ans is not None)): return ans elif(itter==1): ans = DepthFirstSearchRecurs(child,visitedNodes,meta,metaNodes,itter+1) if((not type(ans)==tuple)and(ans is not None)): return visitedNodes,ans,meta return None print("ya") ty,tx,tz = DepthFirstSearchRecurs() print_tree(tz,nameattr='data') trx = FindPath(tx,tz) print("Lisi Depth First Search!") marios.PrintFinishedMap(dataTable,trx)
def recursive(args): """ Recursive method for computing anagrams. Prints the result as either JSON or a tree. Args: args.words (list(strings)): the input phrase args.json (boolean): flag that determines output format """ prepare_data(args.words) if args.json: anagrams = factor(base_signature, perms) print(json.dumps(anagrams, indent=2)) else: anagrams = Node(base,factor_to_tree(base_signature, perms)) # third-party library for printing trees in a human-friendly format pptree.print_tree(anagrams)
def main(): for i, (lexicon, sequence) in enumerate(zip(lexicons, sequences)): print() print("Test case {}:".format(i+1)) print() print("*"*50) print() print("Sentence:", " ".join(sequence)) print("Parse result(s):") trees = parse_Earley(lexicon, sequence) if trees: for idx, tree in enumerate(trees): print("Parse result {}:".format(idx+1)) print_tree(tree) else: print("failed to parse")
def printLabelTree(tree): def inorder(node, nnode): if node.isLeaf: newnode = pptree.Node('H', nnode) wnode = pptree.Node(node.word, newnode) elif nnode is not None: newnode = pptree.Node('H', nnode) inorder(node.left, newnode) inorder(node.right, newnode) elif node.isRoot(): newnode = pptree.Node('H') inorder(node.left, newnode) inorder(node.right, newnode) return newnode return None pptree.print_tree(inorder(tree.root, None))
def main(): filename = input("Input name of the file with the expression:\t") tree = Parser().parse(filename) if not tree: print("File is empty") exit(0) try: import pptree pptree.print_tree(tree) except ImportError: print( "You can use module \'pptree\' to visualize ast tree.\nUse pip to install it\n\n" ) res = calculator.evaluate_tree(tree) print("Result:", res)
def render(self, return_value=False): with redirect_stdout() as stream: print_tree(self, childattr="children", nameattr="repr_name") tables = self.flatten value = ( stream.getvalue() + "\n\n" + "%s table" % len(tables) + ("s" if len(tables) > 1 else "") + " loaded\n" ) if return_value: return value else: print(value)
def print_network( self ): self.title( 'S U M M A R Y', bar = '=' ) if False: self.title( 'Raw Inventory') self.show_inventory() # Step 0: The network (tm); it's own parent, not it's own child # network = Node( 'network' ) self.resolve_unspecified() network = self.node( '<network>', None ) # root, branches = self.build_loopbacks( network ) # BRIDGES candidates = self.choose( None, attr = 'TYPE', value = 'Bridge' ) if len( candidates ): root = self.node( '<bridges>', network ) for candidate in candidates: _, _ = self.build_bridge( candidate, root ) # TEAMS candidates = self.choose( None, attr = 'DEVICETYPE', value = 'Team' ) if len( candidates ): root = self.node( '<teams>', root ) for candidate in candidates: _, _ = self.build_team( candidate, root ) # BONDS candidates = self.choose( None, attr = 'TYPE', value = 'Bond' ) if len( candidates ): root = self.node( '<bonds>', network ) for candidate in candidates: _, _ = self.build_bond( candidate, root ) # candidates = self.choose( None, attr = 'TYPE', value = 'Ethernet' ) if len( candidates ): root = self.node( '<ethernets>', network ) for candidate in candidates: _, _ = self.build_ethernet( candidate, root ) # # _, _ = self.build_orphans( network ) # self.title( 'NETWORK DIAGRAM' ) self.println() print_tree( network, ) return
def print_tree(current_node: Node, parent_node: Optional[Node] = None): """Prints the node-tree of ``current_node`` and its descendents. Utilizes `pptree <https://pypi.org/project/pptree/>`_ to print a tree of nodes, which requires a list of children elements per node. Since the node-tree is semi-directional (the root can be any element in the tree), we need to traverse the node-tree from ``current_node`` in all directions except for the ``parent_node`` to find the children attributes for the current direction. Parameters ---------- current_node Current root of the node-tree to print. parent_node Parent node which will not be printed. s """ def get_children(node, parent=None): node.children = [child for child, _ in node.neighbors if child is not parent] for child in node.children: get_children(child, node) get_children(current_node, parent_node) pptree.print_tree(current_node, childattr="children", nameattr="_repr_status", horizontal=False)
def main(): for i, (lexicon, sequence) in enumerate(zip(lexicons, sequences)): print() print("Test case {}:".format(i + 1)) print() print("*" * 50) print() print("Sentence:", " ".join(sequence)) print("Original Parse result(s):") trees = parse_Earley(lexicon, sequence) for idx, tree in enumerate(trees): print("Parse result {}:".format(idx + 1)) print_tree(tree) print() print("CNF parse result(s):") rules = Rules().fromLexicon(lexicon) cnfRules = convertCNF(rules) cnfLexicon = cnfRules.getLexicon(lexicon.name) trees = parse_Earley(cnfLexicon, sequence) for idx, tree in enumerate(trees): print("CNF result {}:".format(idx + 1)) print_tree(tree) print() print("Deconverted CNF result(s):") for tree in trees: print("Deconverted result {}:".format(idx + 1)) deconvertCNF(tree) print_tree(tree) print()
def exec(fileName): lexer = Lexer.Lexer() parser = Parser.Parser() f = open(fileName) s = f.read() tokens = lexer.lex(s) i = 0 statements = [] while (i < len(tokens)): stack = [] if (tokens[i].tokenType == "IDENTIFIER" or tokens[i].tokenType == "KEYWORD"): while (tokens[i].tokenType != "SEPARATOR" and i < len(tokens)): stack.append(tokens[i]) i += 1 stack.append(tokens[i]) statements.append(stack) i += 1 for statement in statements: print_tree(parser.parse(statement), nameattr="grammarType")
def AStartSearch(): dataTable,mapPoints = marios.CreateMapDataTable(fileName) root,goal = Node(mapPoints['p']),mapPoints['g'] searchPriorityQueue = [] visitedNodes = set() metaNodes = set() heappush(searchPriorityQueue,[0+marios.ManhattanPointDistance(root,goal),0,root]) while searchPriorityQueue: _, cost,subRoot = heappop(searchPriorityQueue) if(subRoot not in metaNodes): metaNodes.add(subRoot) if subRoot.parent is not None: meta = subRoot.parent meta.AddChildOnce(subRoot) if(subRoot.data == goal): t = FindPath(meta,root) print("A Star Search") marios.PrintFinishedMap(dataTable,t) print_tree(root,nameattr='data') return visitedNodes if subRoot in visitedNodes: continue visitedNodes.add(subRoot) #t = VisitedNodesToDataForDisplaying(visitedNodes) #marios.PrintFinishedMap(dataTable,t) for(action,child) in marios.ClosebyDataPoints(subRoot,dataTable).items(): if(child not in searchPriorityQueue): if(child.parent is None): child.AddParentOnly(subRoot) heappush(searchPriorityQueue,[cost + marios.ManhattanPointDistance(root,goal),cost + 1,child])
def pretty_print_attention_tree(attention_list, input_tree, parent, write_index, curr_index): """ Display the parts of the tree focused on by the attention while a particular node is being generated. This function was designed for the identity dataset, where the input and target trees are identical. :param attention_list: a list of indices the attention focused on (preorder traversal order) :param input_tree: subtree we're currently processing :param parent: parent of the node we're currently processing :param write_index: node currently being created during this iteration :param curr_index: index of the node we're currently processing :returns index of one past the last node in our subtree. """ # If the current node was being generated or was focused on by the attention, mark it root_val = str(int(target_tree.value)) if curr_index == write_index: root_val = "*" + root_val + "*" if curr_index in attention_list: root_val = "(" + root_val + ")" # Create new node root_node = pptree.Node(root_val, parent) curr_index += 1 # Recursively add the child subtrees to the tree. for child in target_tree.children: curr_index = pretty_print_attention_tree(attention_list, child, root_node, write_index, curr_index) if parent is None: pptree.print_tree(root_node) return curr_index
def main(): ### load data ### datafile_dir = '../rsrc/titanic.csv' data = pd.read_csv(datafile_dir, sep=',', header=0) data = data.fillna(data.mean()).fillna("") ### train model ### # X and Y contain unsplitted data X, Y, X_train, X_test, y_train, y_test = seperate_split_data(data, label_col=1, test_size=.4) clf = DecisionTree(X_train, y_train, max_depth=10) clf.fit() # fixme: debug # https://github.com/clemtoy/pptree import pptree as ppt ppt.print_tree(clf.root, childattr='children', nameattr='feature') ### test model ### clf.predict(X_train) print(clf.score(X_train, y_train.values)) print(clf.score(X_test, y_test.values))
def print(self): """Prints entire tree, from this node as the root.""" print_tree(self, childattr='branches', nameattr='name')
SubjectNoun = Lexicon("SubjectNoun") SubjectNoun.addRule(Pronoun) SubjectNoun.addRule(ProperNoun) ObjectNoun = Lexicon("ObjectNoun") ObjectNoun.addRules("flight", "book") Noun = Lexicon("Noun") Noun.addRule(SubjectNoun) Noun.addRule(ObjectNoun) Article = Lexicon("Article").addRules("the", "a") Verb = Lexicon("Verb") Verb.addRules("book", "carry") VerbPhrase = Lexicon("VerbPhrase") VerbPhrase.addRule(Verb, Article, ObjectNoun) VerbPhrase.addRule(Verb, "and", Verb) VerbPhrase.addRule(Verb) Sentence = Lexicon("Sentence") Sentence.addRule(SubjectNoun, VerbPhrase) if __name__ == "__main__": tree = randomTree(Sentence) print_tree(tree) sequence = tree2Sequence(tree) print(" ".join(sequence))
def print(self): """ Print the tree using pptree's print_tree. """ print_tree(self.root, "children")
def __str__(self): # if self.categorical == False: # self.print_recursive(self.tree) # else: # self.print_level(self.tree) pptree.print_tree(d.tree)
def describe(self): pp.print_tree(self.root)
def pprint(self): pptree.print_tree(self, childattr='children', nameattr='name')