def test_tree2(): """Tree2.""" root = Node("root") s0 = Node("sub0", parent=root, edge=2) Node("sub0B", parent=s0, foo=4, edge=109) Node("sub0A", parent=s0, edge="") s1 = Node("sub1", parent=root, edge="") Node("sub1A", parent=s1, edge=7) Node("sub1B", parent=s1, edge=8) s1c = Node("sub1C", parent=s1, edge=22) Node("sub1Ca", parent=s1c, edge=42) def nodenamefunc(node): return '%s:%s' % (node.name, node.depth) def edgeattrfunc(node, child): return 'label="%s:%s"' % (node.name, child.name) r = RenderTreeGraph(root, options=["rankdir=LR;"], nodenamefunc=nodenamefunc, nodeattrfunc=lambda node: "shape=box", edgeattrfunc=edgeattrfunc) r.to_dotfile(join(GENPATH, "tree2.dot")) assert cmp(join(GENPATH, "tree2.dot"), join(REFPATH, "tree2.dot"))
def plot_tree(self, filepath, edge_prop_metric=None, node_label_func=None, node_shape_func=None): """ Function that is returning the dotprogram and saving the png in filepath. :param filepath: Path of the file :param node_metric_col_print_dict: Dict of what we want to print in the node and in which format. The structure of the Dict is: {'metric_name': {'type': type, 'digits': digits}} type must be in ['float', 'percent', 'int'] :param edge_prop_metric: Metric to compute the proportion on each edge :param node_label_func: Function to be apply to each node to get the label :param node_shape_func: Function to be apply to each node to get the shape :return: dotprogram in a string format """ render_tree = \ RenderTreeGraph(node=self.tree, nodeattrfunc=lambda node: self._get_node_attr(node, node_label_func, node_shape_func), edgeattrfunc=lambda node, child: self._get_edge_attr(node, child, edge_prop_metric)) render_tree.to_picture(filepath) return self._to_dot(render_tree)
def get_category(save_img=None): url = f'{trace_parts_url}/en/search/traceparts-classification-mechanical-components?CatalogPath=TRACEPARTS%3ATP01' r = requests.get(url) if r.status_code == 200: soup = BeautifulSoup(r.text, 'html.parser') root = Node('Mechanical components') node = root prev_level = 1 for cat in soup.find_all('span', {'class': 'treeview-node-title'}): levels = cat.get('title').split('>') levels = [c.strip() for c in levels] if levels[0] == 'Mechanical components' and len(levels) > 1: depth = len(levels) - prev_level prev_level = len(levels) if depth <= 0: for i in range(abs(depth) + 1): node = node.parent node = Node(levels[-1], parent=node) for pre, fill, node in RenderTree(root): print("%s%s" % (pre, node.name)) if save_img: RenderTreeGraph(root).to_picture(save_img) else: raise ConnectionError
def __init__(self, ast, filename=None): self.root_node = None self.keys = {} self.nodes = deque([]) self.nodes_keys = {} self.built(ast) RenderTreeGraph(self.nodes[0]).to_picture(filename=filename)
def run(): hero = [CARDS['Ah'], CARDS['Qd']] villain = [CARDS['2s'], CARDS['2d']] board_test = [CARDS['Ad'], CARDS['Ac'], CARDS['As']] root = Node('Root') initial_game_state = { 'pot_size': 2, 'betting_lead': True, 'hero_stack': 97, 'last_bet': 0, 'raised': False, 'reraised': False, 'folded': False, 'villain_folded': False, 'line': [] } game = PokerGame(None, hero, villain, None, board=board_test) for i in range(N): game.set_board(board_test) game_state = copy.deepcopy(initial_game_state) game.simulate_round(FLOP, game_state, root, initial=True) RenderTreeGraph(root).to_picture("tree.png") for pre, fill, node in RenderTree(root): print("%s%s (%s) (%s) (%s) (%s)" % (pre, str(node.name).split(":")[-1], node.get_value(), node.get_value("regret"), node.get_value("regretSum"), node.get_value("strategyNOT")))
def dot_render(self): Nodes = [Node(self._nodes[0]._long_description)] for i in range(len(self._nodes) - 1): Nodes.append( Node(self._nodes[i + 1]._long_description, parent=Nodes[self._parents[i]])) for Line in RenderTreeGraph(Nodes[0]): print(Line)
def img_tree_visualize(data): ''' Render tree to filename :filename: data['config']['review_base_filename'] + tree :format: png ''' directory = data['config']['report_directory'] + "/img/" filename = directory + "%s_%s.png" % ( data['config']['review_base_filename'], "tree") RenderTreeGraph(data['tree']).to_picture(filename)
def test_tree_png(): """Tree to png.""" root = Node("root") s0 = Node("sub0", parent=root) Node("sub0B", parent=s0) Node("sub0A", parent=s0) s1 = Node("sub1", parent=root) Node("sub1A", parent=s1) Node("sub1B", parent=s1) s1c = Node("sub1C", parent=s1) Node("sub1Ca", parent=s1c) RenderTreeGraph(root).to_picture(join(GENPATH, "tree1.png"))
def test_tree1(): """Tree1.""" root = Node("root") s0 = Node("sub0", parent=root) Node("sub0B", parent=s0) Node("sub0A", parent=s0) s1 = Node("sub1", parent=root) Node("sub1A", parent=s1) Node("sub1B", parent=s1) s1c = Node("sub1C", parent=s1) Node(99, parent=s1c) RenderTreeGraph(root).to_dotfile(join(GENPATH, "tree1.dot")) assert cmp(join(GENPATH, "tree1.dot"), join(REFPATH, "tree1.dot"))
def plot_BKtree(tree, pic_path: str = ""): try: from anytree import Node, RenderTree except: raise ImportError( "The anytree module seems to not be installed in your environment.\nTo be able to use this method, you'll have to install it." ) check_types([( "pic_path", pic_path, [str], )]) try: import shutil screen_columns = shutil.get_terminal_size().columns except: import os screen_rows, screen_columns = os.popen("stty size", "r").read().split() print("-" * int(screen_columns)) print("Bisection Levels: {}".format(max(tree["bisection_level"]))) print("Number of Centers: {}".format(len(tree["center_id"]))) print("Total Size: {}".format(max(tree["cluster_size"]))) print("-" * int(screen_columns)) tree_nodes = {} for idx in range(len(tree["center_id"])): tree_nodes[tree["center_id"][idx]] = Node( "[{}] (Size = {} | Score = {})".format( tree["center_id"][idx], tree["cluster_size"][idx], round(tree["withinss"][idx] / tree["totWithinss"][idx], 2), )) for idx, node_id in enumerate(tree["center_id"]): if (tree["left_child"][idx] in tree_nodes and tree["right_child"][idx] in tree_nodes): tree_nodes[node_id].children = [ tree_nodes[tree["left_child"][idx]], tree_nodes[tree["right_child"][idx]], ] for pre, fill, node in RenderTree(tree_nodes[0]): print("%s%s" % (pre, node.name)) if pic_path: from anytree.dotexport import RenderTreeGraph RenderTreeGraph(tree_nodes[0]).to_picture(pic_path) if isnotebook(): from IPython.core.display import HTML, display display(HTML("<img src='{}'>".format(pic_path)))
def plot_tree(tree, metric: str = "probability", pic_path: str = ""): try: from anytree import Node, RenderTree except: raise Exception( "You must install the anytree module to be able to plot trees.") check_types([("metric", metric, [str], False), ("pic_path", pic_path, [str], False)]) try: import shutil screen_columns = shutil.get_terminal_size().columns except: import os screen_rows, screen_columns = os.popen('stty size', 'r').read().split() tree_id, nb_nodes, tree_depth, tree_breadth = tree["tree_id"][0], len( tree["node_id"]), max(tree["node_depth"]), sum( [1 if item else 0 for item in tree["is_leaf"]]) print("-" * int(screen_columns)) print("Tree Id: {}".format(tree_id)) print("Number of Nodes: {}".format(nb_nodes)) print("Tree Depth: {}".format(tree_depth)) print("Tree Breadth: {}".format(tree_breadth)) print("-" * int(screen_columns)) tree_nodes = {} for idx in range(nb_nodes): op = "<" if not (tree["is_categorical_split"][idx]) else "=" if (tree["is_leaf"][idx]): tree_nodes[tree["node_id"][idx]] = Node( '[{}] => {} ({} = {})'.format( tree["node_id"][idx], tree["prediction"][idx], metric, tree["probability/variance"][idx])) else: tree_nodes[tree["node_id"][idx]] = Node('[{}] ({} {} {} ?)'.format( tree["node_id"][idx], tree["split_predictor"][idx], op, tree["split_value"][idx])) for idx, node_id in enumerate(tree["node_id"]): if not (tree["is_leaf"][idx]): tree_nodes[node_id].children = [ tree_nodes[tree["left_child_id"][idx]], tree_nodes[tree["right_child_id"][idx]] ] for pre, fill, node in RenderTree(tree_nodes[1]): print("%s%s" % (pre, node.name)) if (pic_path): from anytree.dotexport import RenderTreeGraph RenderTreeGraph(tree_nodes[1]).to_picture(pic_path) if (isnotebook()): from IPython.core.display import HTML, display display(HTML("<img src='{}'>".format(pic_path)))
def printTree(edges_list): # create root root = Node("Root") for (node1, node2) in edges_list: Node(node2, parent=find_by_attr(root, node1)) for pre, _, node in RenderTree(root): print("%s%s" % (pre, node.name)) # Print to file --- GRAPVIZ MUST BE INSTALLED!!! installed_packages = [ "%s" % i.key for i in pip.get_installed_distributions() ] if 'graphviz' in installed_packages: RenderTreeGraph(root).to_picture("../Outputs/Part3/tree.png") print('Tree generated correctly')
def buildMap(bnde, resources): #print "ENtre a buildMap con ",bnde #print bnde #print "tipo ",type(bnde) bnode = simplenode(bnde, parent=None) bnode.setFPath() #print "<resources>\n",'\n'.join(resources),'\n</resources>' for res in resources: resource = res.split('//')[1] # Que pasa cuando no tiene el protocolo? tengo que ver si se realizo lo anterior dirlist = resource.split('/')[1:] agrega(bnode, dirlist) dom = ''.join(parseurls.getDomain(bnode.getUrl()).split('://')[1]).replace( 'www.', '') try: RenderTreeGraph(bnode).to_picture(dom + '.jpg') except: print 'Cant write sitemap imagefile' return bnode
def main(argv): inputUrl = '' inputDepth = 0 try: opts, args = getopt.getopt(argv, "hu:d:", ["rootUrl=", "depth="]) except getopt.GetoptError: print('index.py -u <url> -d <depth>') sys.exit(2) for opt, arg in opts: if opt == '-h': print('index.py -u <url> -d <depth>') sys.exit() elif opt in ("-u", "--rootUrl"): inputUrl = arg elif opt in ("-d", "--depth"): inputDepth = int(arg) print('Input url --> ', inputUrl) print('Depth --> ', inputDepth) rootNode = Node(inputUrl) iterative_deepening_search(rootNode, inputDepth) print("--------------------------------------------") print("Finalizando com >>>Iterative Deepening Search<<<<!") print("--------------------------------------------") print("Estrutura da árvore") print("--------------------------------------------") print(RenderTree(rootNode, style=DoubleStyle()).by_attr()) # # for pre, fill, node in RenderTree(rootNode): # print("%s%s" % (pre, node.name)) # # RenderTreeGraph(rootNode).to_picture("tree.png")
def render_tree(tree, filepath): """Wrapper around rendering trees into `png` or `dot` formats. Tree are rendered from the root node. Args: tree (NodeMixin): filepath (str|Path): """ from anytree.dotexport import RenderTreeGraph tree = RenderTreeGraph(tree.root) base, ext = os.path.splitext(filepath) if ext == '.png': tree.to_picture(filename=filepath) elif ext == '.dot': tree.to_dotfile(filename=filepath) else: raise Exception
def save_to_file(self, filename): def edgeattrfunc(node, child): return 'label=' + str(child.value) def nodeattrfunc(node): attr = 'shape=' if node.is_leaf: attr += 'ellipse' else: attr += 'rectangle' return attr def nodenamefunc(node): name = node.name if node.is_root: name += '\n' + 'Height(%d)' % node.height name += '\n' + 'id(%d)' % node._id return name RenderTreeGraph(self.tree, nodeattrfunc=nodeattrfunc, edgeattrfunc=edgeattrfunc, nodenamefunc=nodenamefunc).to_picture(filename)
def render_image(self, name): RenderTreeGraph(self.root).to_picture(name)
# We define the impurity degree of a node u as: ImpurityDeg(u) = |L(v) : v ∈ N(u), L(u) 6= L(v)| # where L(u) is the label, and N(u) is the neighborhood of (the nodes adjacent to) node u. def neighborhood_impurity(node, data): return # Main program if len(sys.argv) < 3: sys.stderr.write("Syntax : python %s json_file function_name\n" % sys.argv[0]) else: with open(sys.argv[1]) as data_file: data = json.load(data_file) requested_node = find_node(data, sys.argv[2]) entry_node = find_node(data, "external node") root = Node("Entry node") tree = generate_tree(entry_node, data, root) for pre, fill, node in RenderTree(tree): print("%s%s" % (pre, node.name)) from anytree.dotexport import RenderTreeGraph RenderTreeGraph(tree).to_picture("Callgraph.png") print("\nThe results for node", sys.argv[2], "are:") print("Node degree (out, in):", node_degree(requested_node, data)) print("Node path length:", node_path_length(tree))
dot_graph = nx.drawing.nx_agraph.read_dot(sys.argv[1]) data = json_graph.node_link_data(dot_graph) data['links'] = [{ 'source': data['nodes'][link['source']]['id'], 'target': data['nodes'][link['target']]['id'] } for link in data['links']] with open(sys.argv[2]) as cvss3_file: cvss3_data = json.load(cvss3_file) interface = sys.argv[3] if len(sys.argv) > 3 else "external node" entry_node = find_node(data, interface) root = Node(interface) tree = generate_tree(entry_node, root) results_json = {} RenderTreeGraph(tree).to_picture(sys.argv[1] + "_callgraph.png") # For testing purposes only -- Displays the current tree # for pre, fill, node in RenderTree(tree): # print("%s%s" % (pre, node.name)) for node in data["nodes"]: if "label" in node: node_name = node['label'] else: node_name = node['id'] generate_json(node['id']) with open(sys.argv[1] + '_node_attributes.json', 'w') as fp: json.dump(results_json, fp)
#for pre, _, node in RenderTree(top): # treestr = u"%s%s" % (pre, node.name) # print(treestr.ljust(8), node.state_number) def print_as_tabs(prev_state,next_state,input_label,output_label): print(str(prev_state) + "\t" + str(next_state) + "\t"+ str(input_label) + "\t" + str(output_label)) # In[222]: p=PreOrderIter(top) p=itertools.islice(p,1,None) #pass root print_as_tabs(0,1,"<s>","<s>") print_as_tabs(1,0,"<eps>","<eps>") print_as_tabs(0,2,"</s>","</s>") print_as_tabs(2,0,"<eps>","<eps>") print_as_tabs(0,3,"<unk>","<unk>") print_as_tabs(3,0,"<eps>","<eps>") for n in p: parent_state_number=n.parent.state_number if n.parent.state_number!=0: parent_state_number+=3 print_as_tabs(parent_state_number,n.state_number+3,n.name,n.name) if n.is_leaf: print_as_tabs(n.state_number+3,0,"+PRN","#") print("0") RenderTreeGraph(top).to_picture("udo.png")
if isSafe(tup, pos - 1): subNode = Node(tup, parent=initial_node, depth=pos) if pos < len(initial_node.name): generate_children(subNode, pos + 1) # generate_tree creates the initial node specified by length and creates the children def generate_tree(length): initial_tuple = (-1, ) * length initial_node = Node(initial_tuple, depth=0) generate_children(initial_node) return initial_node def solutions(root): for child in root.children: if child.depth == len(root.name): solution.append(child.name) solutions(child) test_tree = generate_tree(8) solutions(test_tree) print solution print boardIsSafe((0, 2, 4, 1, 3)) # for pre,fill, node in RenderTree(test_tree): # print("%s%s" % (pre,node.name)) RenderTreeGraph(test_tree).to_picture("state_tree_3.png")
# Hit rock bottom, node does not contain text # Record this node, then return if v: print("_0_\nheading: {}\t level:{}".format(nodeHead(node),node.level)) newNode = Node(nodeHead(node), parent=lastNode) else: # Node has something which could be children. Recursively call this function for all legitimate node-children lastNode = Node(nodeHead(node), parent=lastNode) for nextNode in node.content: if isNode(nextNode) and isinstance(nextNode, PyOrgMode.OrgElement): gobbleBranch(nextNode,lastNode) return # Traverse the tree gobbleBranch(trunk,lastNode) # The location of the root node is a bit off actualRoot = root.children[0] actualRoot.name = "Org File Root" # Render the tree in text for pre, fill, node in RenderTree(actualRoot): # two ways to do the same thing #print("{}{}".format(pre.encode('utf-8'), node.name.encode('utf-8'))) print("%s%s" % (pre, node.name)) # Render the tree as an image from anytree.dotexport import RenderTreeGraph RenderTreeGraph(actualRoot).to_picture(args.image) # Source tangled from org_tree.org
#plt.show() plt.savefig('outputs/maptile.png') if __name__ == '__main__': REGIONS_URI = './data/bounds_coahuila.tsv' FOSAS_URI = './data/OperativosdeCampo2017-2020.xlsx' geodf = build_geodf(REGIONS_URI) ### creating a geographic tree from geo-data frame geotree = build_geotree(geodf) ### initial tree RenderTreeGraph(geotree).to_picture("outputs/inittree.png") ### loading findings data geotree.load_findings(FOSAS_URI) ### query geoparser ws with findings data geotree.geoparse_findings() ### final tree RenderTreeGraph(geotree).to_picture("outputs/finaltree.png") ### save new data tree_df = tree_as_df(geotree) tree_df.to_file('outputs/spatial_data.json', driver="GeoJSON") ### save map
error() check_point(FACTOR[1], followset=FACTOR[0], patron_follow=ID_NUM) return temp # PROGRAMA PRINCIPAL actualizar_token() raiz = programa() if not os.path.exists(directorio_sintactico): os.makedirs(directorio_sintactico) with open(directorio_sintactico + os.path.sep + ARBOL_TXT, "w") as archivo_arbol: archivo_arbol.write(str(RenderTree(raiz, style=AsciiStyle()))) if os.name == 'posix': RenderTreeGraph(raiz, nodeattrfunc=lambda node: "shape = box").to_picture( directorio_sintactico + os.path.sep + ARBOL_PNG) elif os.name == 'nt': RenderTreeGraph(raiz, nodeattrfunc=lambda node: "shape = box").to_dotfile( directorio_sintactico + os.path.sep + ARBOL_DOT) comando = "dot " + directorio_sintactico + os.path.sep + ARBOL_DOT + " -T png -o " + directorio_sintactico + os.path.sep + ARBOL_PNG startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW subprocess.call(comando, startupinfo=startupinfo) with open(directorio_sintactico + os.path.sep + "errores_sintacticos.txt", "w") as archivo_errores_sintacticos: for error in errores: archivo_errores_sintacticos.write(error + '\n')
def renderTreeGraph(self): # graphic needs to be installed for the next line! RenderTreeGraph(self.root).to_picture("tree.png")
soup = drink_soup(url) #common_classes,class_to_class_list_map = find_common_classes(url) #common_ids = find_common_id_bases(soup) #common_classes.sort(key=lambda x: x[1], reverse=True) #single_parent_classes = OrderedDict() #for common_class in common_classes: # parent_classes = find_common_parent_classes(soup, class_to_class_list_map[common_class[0]]) # if len(parent_classes)==1: # single_parent_classes[common_class] = parent_classes[0][0] homes = soup.find_all(class_="HomeCardV2 card-frame") home_ex = homes[0] home_tree = find_base_info(home_ex, "--") print_tree(home_tree) RenderTreeGraph(home_tree).to_picture("test.png") def get_facts(tree): facts = [] for pre, fill, node in RenderTree(home_tree): if node.name != "": for sibling in node.siblings: if sibling.name != "": facts.append( tuple( sorted((node.name, sibling.name), cmp=locale.strcoll, reverse=True))) facts = list(set(facts)) return facts
def generate_dotfile(self, name): RenderTreeGraph(self.root).to_dotfile(name)
for course in coursesInFile: courses[course['course_code']] = course selectedCourse = '' print('--------------Welcome to the UCalgary Prerequisites Wizard!-----------') selectedCourse = input( 'Select a UCalgary course you want to generate a prerequisites-tree from:') prerequisitesTree = getPrerequisites(selectedCourse, courses) importer = DictImporter() root = importer.import_(prerequisitesTree) RenderTreeGraph(root).to_picture("tree.png") print('`tree.png` has been generated.') if sys.platform == 'win32': subprocess.Popen(['start', 'tree.png'], shell=True) elif sys.platform == 'darwin': subprocess.Popen(['open', 'tree.png']) else: try: subprocess.Popen(['xdg-open', 'tree.png']) except OSError: print('Can\'t open file in system.') # er, think of something else to try # xdg-open *should* be supported by recent Gnome, KDE, Xfce
# H(y_col) - H(y_col|column) d[c] = h - self.get_info_gain_byc(c) return max(d, key=d.get) ## Generate Decision Tree def train_decision_tree(self,node): c = self.get_max_info_gain() for v in pd.unique(self.dataset[c]): gb = self.dataset[self.dataset[c] == v].groupby(self.label) curr_node = Node('%s-%s' % (c, v), parent=node) if len(self.dataset.columns) > 2: if len(gb) == 1: Node(self.dataset[self.dataset[c] == v].groupby(c)[self.label].first().iloc[0], parent=curr_node) else: self.dataset = self.dataset[self.dataset[c] == v].drop(c, axis=1) self.train_decision_tree(curr_node) else: Node(self.dataset[self.dataset[c] == v].groupby(self.label).size().idxmax(), parent=curr_node) if __name__ == "__main__": df = pd.read_csv('Decision Tree\Dataset\dataset_training.csv') print(df) Decision_Tree = Decision_Tree(df,'Infected') root_node = Decision_Tree.create() for pre, fill, node in RenderTree(root_node): print("%s%s" % (pre, node.name)) RenderTreeGraph(root_node).to_picture("decision_tree_id3.png")
parent=node) print('bot', next_node.name) explore_frontier(next_node, 'Top') if left == ' ' and direction != 'Left': next_node = Node('(' + str(yCord) + ',' + str(xCord - 1) + ')', parent=node) print('left', next_node.name) explore_frontier(next_node, 'Right') if right == ' ' and direction != 'Right': next_node = Node('(' + str(yCord) + ',' + str(xCord + 1) + ')', parent=node) print('right', next_node.name) explore_frontier(next_node, 'Left') if __name__ == "__main__": #sys.setrecursionlimit(1000) medium_maze = input_to_array('./Inputs/mediumMaze.txt') for line in medium_maze: print(line) start = find_starting_position(medium_maze) print(start) start_node = Node(str(start)) visitedNodes = [] explore_frontier(start_node, 'None') for pre, fill, node in RenderTree(start_node): print("%s%s" % (pre, node.name)) RenderTreeGraph(start_node).to_picture("tree.png")