def visualize_tree(node, depth=np.inf): from graphviz import Digraph dot = Digraph(comment='Alpha Beta graph', format='png') dot.node_attr.update(style='filled', fontsize='15', fixedsize='false', fontcolor='blue') edges = [] node_counter = [0] def node_to_graph_node(node, dot): dot.node(str(node.counter), 'alpha:{0} beta:{1}, move:{2}'.format(node.alpha, node.beta, str(node.move)), shape='box' if node.board.turn else 'oval', color='black' if node.board.turn else 'white') def helper(node, node_counter, edges, dot, depth): if depth <= 0: return for n in node.child_nodes: n.counter = node_counter[0] node_counter[0] += 1 node_to_graph_node(n, dot) edges.append((str(node.counter), str(n.counter))) helper(n, node_counter, edges, dot, depth - 1) node.counter = node_counter[0] node_to_graph_node(node, dot) node_counter[0] += 1 helper(node, node_counter, edges, dot, depth) dot.edges(edges) print(dot.source) dot.render('test-output/round-table.gv', view=True)
def _build_graph(config, data): g = Digraph() g.graph_attr["rankdir"] = "LR" g.graph_attr["splines"] = "polyline" g.graph_attr["fontsize"] = "32.0" graph_nodes = [] graph_edges = [] for item in data: for key, value in item.dict().items(): g.node(value, **config.style[key]) values = list(item.dict().values()) graph_edges.extend(list(zip(values, values[1:]))) graph_nodes = list(set(graph_nodes)) for node in graph_nodes: g.node(node) graph_edges = list(set(graph_edges)) g.edges(graph_edges) g.edge_attr["arrowhead"] = "none" return g.unflatten()
def draw_map(cls, clsinfo, filename="map.gv", format="png", with_mro=False): if not ClsMap.__is_cls(clsinfo): return clsinfo_name = ClsMap.__cls_name(clsinfo) dot = Digraph(comment='Class %s inherit relationship map' % clsinfo_name) if clsinfo == object: edges = [["object", "NUL"]] else: edges = cls.inherit_edges(clsinfo) dot.node(edges[0][0], style="filled") if not with_mro: dot.edges(edges) else: mro_edges = cls.mro_edges(clsinfo) for i in edges: if i in mro_edges: mro_edges.remove(i) dot.edge(i[0], i[1], color='red') else: dot.edge(i[0], i[1]) for i in mro_edges: dot.edge(i[0], i[1], color='red') dot.render(filename, format=format, view=False)
def Generar_Grafo(): w = Digraph() w.edges((restaurante, str(seccion[0])) for seccion in datosRestaurante) w.view() '''
def __repr__(self): # Empty tree is represented by an empty string if self.root is None: return "" # Create directed graph object dot = Digraph(comment=f"{self.order}-ary tree", format='png') # Queue for traversing through the tree one level at a time queue = deque() queue.append(self.root) # Build a graph node by node until all nodes are recreated dot.node(f"{self.root.value}", f"{self.root.value}") while queue: current = queue.popleft() queue.extend(current.children) # Create child nodes and then connect them to their parent through edges for child in current.children: dot.node(f"{child.value}", f"{child.value}") dot.edges([f"{current.value}{child.value}"]) # Visualized graph dot.render(f"{self.order}-ary tree", view=True) # Graph in a text format return dot.source
def plot(doid, ontology): dot = Digraph(comment='Neighborhood') term_doid = ontology.get_term(doid) label_doid = term_doid.name dot.node('A', label_doid) letter = 'A' if check_parent(doid, ontology) > 0: dict = {term.name: term.id for term in ontology.get_terms()} father = dict[term_doid.relationships[0][2]] term_father = ontology.get_term(father) label_father = term_father.name letter = 'B' dot.node(letter, label_father) dot.edges([''.join(['B', 'A'])]) children = [ term.id for term in ontology.get_terms() if len(term.relationships) > 0 and term.relationships[0][1] == doid ] #print children if len(children) > 0: for child in children: term_child = ontology.get_term(child) label_child = term_child.name letter = chr(ord(letter) + 1) dot.node(letter, label_child) dot.edges([''.join(['A', letter])]) return dot
def print_graph(self, transpose: bool = False, view_img: bool = True) -> None: """prints the graph pretty""" # requires graphviz, install using # python3.7 -m pip install graphviz try: from graphviz import Digraph dot = Digraph() for i in range(self.nodes): dot.node(str(i), get_pml_node_name(i)) edges = [] for i in range(self.nodes): for j in range(self.nodes): if transpose: if self.trans_ad_mat[i][j] == 1: edges.append(str(i) + str(j)) else: if self.ad_mat[i][j] == 1: edges.append(str(i) + str(j)) dot.edges(edges) if transpose: dot.render('reverse_graph', view=view_img) else: dot.render('graph', view=view_img) except: pass
def render_graph_with_graphviz(g, filename): """manual hack to render graph because graphtool's graphviz rendering is broken""" edgelist = [] for i in g.edges(): edgelist.append([g.vp.id[i.source()], g.vp.id[i.target()]]) dot = Digraph() dot.engine = 'sfdp' dot.node_attr = {'shape': "point"} dot.edge_attr = {'arrowsize': "0.1", 'penwidth':'0.1'} dot.graph_attr = {'outputorder':'edgesfirst', 'overlap':'false'} size = g.degree_property_map('out') label_size_scaler = graph_tool.draw.prop_to_size(size, mi=2, ma=6, log=False, power=0.5) node_size_scaler = graph_tool.draw.prop_to_size(size, mi=0.005, ma=0.1, log=False, power=1) # https://github.com/xflr6/graphviz/issues/85 for i in flatten_list(edgelist): gt_node = graph_tool.util.find_vertex(g, g.vp.id, i)[0] # gt_node = g_kld2.vertex(vd_kld2[i]) label_size =label_size_scaler[gt_node] node_size = node_size_scaler[gt_node] dot.node(i, xlabel=i, width=str(node_size), fontsize=str(label_size)) dot.edges(edgelist) dot.render(filename = filename)
def graph(flows, b): """ flows is the matrix with the net flows, and b3.2 Methodology 75 is a string describing the net flow """ s = Digraph('Actions', node_attr={'shape': 'plaintext'}) s.body.extend(['rankdir = LR']) x = sort(flows) y = argsort(flows) l = [] for i in y: s.node( 'action' + str(i), '''< <TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="4"> <TR> <TD COLSPAN="2" bgcolor="grey" >Action ''' + str(y[i] + 1) + '''</TD> </TR> <TR> <TD>''' + b + '''</TD> <TD>''' + str(x[i]) + '''</TD> </TR> </TABLE>>''') k = [] for q in range(len(flows) - 1): k.append(['action' + str(q + 1), 'action' + str(q)]) print(k) s.edges(k) s.view()
def draw_subclasses(cls, clsinfo, filename="subclasses.gv", format="png"): if not ClsMap.__is_cls(clsinfo): return edges = cls.subclasses_edges(clsinfo) if not len(edges): return multiple_modules = True if ClsMap.__edges_in_same_module(edges): edges = ClsMap.__edges_rm_module_name(edges) multiple_modules = False clsinfo_name = ClsMap.__cls_name(clsinfo) dot = Digraph(comment='Class %s subclasses tree' % clsinfo_name) dot.attr(rankdir='LR') dot.attr(splines="polyline") dot.node(edges[0][1], style="filled") if multiple_modules: # add node color for different modules color_plate = {} for edge in edges: for node in edge: module_name = ClsMap.__node_module_name(node) if not color_plate.__contains__(module_name): color_plate[module_name] = CPicker.picker() dot.node(node, style='filled', fillcolor=color_plate[module_name]) dot.edges(edges) dot.render(filename, format=format, view=False)
def showCourseGraph(self): """ Visualizes the course graph to show course dependencies """ visualGraph = Digraph() nodeChar = 'A' dictCourseToNode = {} # initialize nodes for key in self.courseGraph: corequisites = self.courseGraph[key]['co'] prerequisites = self.courseGraph[key]['pre'] dictCourseToNode[key] = nodeChar if (corequisites is None): visualGraph.node(nodeChar, key) else: visualGraph.node(nodeChar, key + str(corequisites).replace("'", "")) nodeChar = chr(ord(nodeChar) + 1) # build edges edges = [] for key in self.courseGraph: if (self.courseGraph[key]['pre'] == None): continue else: prerequisites = self.courseGraph[key]['pre'] for pre in prerequisites: edges.append(dictCourseToNode[pre] + dictCourseToNode[key]) visualGraph.edges(edges) return visualGraph
def output_parent_function_graph(rule_classification_data_bundle): report_dict, reference_dict = rule_classification_data_bundle identifier_dict = { parent: f"p{index}" for index, parent in enumerate(report_dict.keys()) } dot = Digraph(**_GRAPH_SETTINGS) for parent, identifier in identifier_dict.items(): descriptions = "\l".join(report_dict[parent]) + "\l" with dot.subgraph( name=f"cluster_{identifier}", graph_attr={ "label": _get_function_display_name(parent), "fontsize": "16", }, ) as sub: sub.node(identifier, label=descriptions) edge_list = [] for parent, identifier in identifier_dict.items(): edge_list.extend([(identifier, identifier_dict[function]) for function in reference_dict[parent]]) dot.edges(edge_list) dot.render()
def draw_graph(cur_commit_id: str, master_id: str, parent_commit_id) -> None: g = Digraph('G', filename='commit-graph.gv') g.graph_attr['rankdir'] = 'RL' g.node('H', 'HEAD') g.node('C', cur_commit_id) nodes = ['HC'] if parent_commit_id != 'None': g.node('P', parent_commit_id) nodes.append('CP') if master_id == cur_commit_id: g.node('M', 'master') nodes.append('MC') elif master_id == parent_commit_id: g.node('M', 'master') nodes.append('MP') g.edges(nodes) g.view()
def result(): c = m = 0 arr = [] pTree.displayTree1(arr) array = arr from graphviz import Digraph, nohtml, render s = Digraph(name='structs', filename='static/result/structs.gv', node_attr={'shape': 'record'}, format='png') for i in range(len(array)): if m < array[i][0]: m = array[i][0] if len(array[i][2]) == 3: s.node('struct{}{}{}'.format(array[i][0], array[i][1], array[i][3]), '<f0> {}|<f1> {}|<f2> {}'.format(array[i][2][0], array[i][2][1], array[i][2][2])) c += 1 if len(array[i][2]) == 2: s.node('struct{}{}{}'.format(array[i][0], array[i][1], array[i][3]), '<f0> {}|<f1> {}'.format(array[i][2][0], array[i][2][1])) c += 1 if len(array[i][2]) == 1: s.node('struct{}{}{}'.format(array[i][0], array[i][1], array[i][3]), '<f0> {}'.format(array[i][2][0])) c += 1 # for i in range(m): # s.edges([('struct{}{}:f0'.format(i,0), 'struct{}{}:f0'.format(i+1,0)), ('struct{}{}:f0'.format(i,0), 'struct{}{}:f0'.format(i+1,1))]) # s.edges([('struct{}{}:f0'.format(i,1), 'struct{}{}:f0'.format(i+1,0)), ('struct{}{}:f0'.format(i,1), 'struct{}{}:f0'.format(i+1,1))]) stack = [] stack.append(array[0]) for i in range(1, len(array)): while len(stack) != 0 and stack[-1][2] != array[i][3]: tmp = stack.pop() s.edges([('struct{}{}{}:f0'.format(stack[-1][0], stack[-1][1], stack[-1][3]), 'struct{}{}{}:f0'.format(array[i][0], array[i][1], array[i][3]))]) stack.append(array[i]) # print(stack) s.render(filename="static/result/structs", view=False)
def build_graph(edges): fc = nn.Linear(768, 2) net = nn.Sequential(mac, fc) # fails b/c tuple input # hl.build_graph(net, tuple(mac.mac.saved_inp)) # graph = hl.build_graph(mac.mac, tuple(mac.mac.saved_inp)) # graph.build_dot().render('visuals/mac-hl', format='png') g = nx.DiGraph() g.add_edges_from(filter_edges(edges)) g.remove_edges_from(g.selfloop_edges()) # nx.drawing.nx_pydot.write_dot(G, "visuals/mac-nx.dot") # !dot -Tpng visuals/mac-nx.dot -o visuals/mac-nx.png node_attr = dict(style='filled', shape='box', align='left', fontsize='12', ranksep='0.1', height='0.2') graph_attr = dict(size="12,12") dot = Digraph(node_attr=node_attr, graph_attr=graph_attr) dot.edges(g.edges()) dot.render('visuals/mac-nx', format='png') return g
class TreePainter(): def __init__(self): self._dot = Digraph(comment='Sample', graph_attr={ 'rankdir': 'LR', 'fontname': 'Segoe UI' }, edge_attr={'dir': 'none'}) builder = PartsStructuresBuilder() # アイテムを追加 self._addNode(builder.get_rawData()) # アイテム間で線をひく self._addEdges(builder.get_Structure()) def get_dot(self): return self._dot def _addNode(self, structure): for part in structure: self._dot.node(part['PartNumber'], label=part['PartNumber'], shape='box') def _addEdges(self, structure): edge = [] edge = self._makeEdge(structure, edge) self._dot.edges(edge) def _makeEdge(self, structure, edge): for part in structure['child']: edge.append(structure['PartNumber'] + part['PartNumber']) if len(part['child']) > 0: edge = self._makeEdge(part, edge) return edge
def assembleKnights(): roundTable = Digraph(comment="The Round Table") roundTable.node('A', 'King Arthur') roundTable.node('B', 'Sir Bedevere the Wise') roundTable.node('L', 'Sir Lancelot the Brave') roundTable.edges(['AB', 'AL']) roundTable.edge('B', 'L', constraint='false') return roundTable
def test(self): dot = Digraph(comment='The Round Table') dot.node('A', 'King Arthur') dot.node('B', 'Sir Bedevere the Wise') dot.node('L', 'Sir Lancelot the Brave') dot.edges(['AB', 'AL']) dot.edge('B', 'L', constraint='false') dot.render('output/test.gv', view=True)
def drawGraph(self): f = Digraph('graph', filename='static/fsm.gv', node_attr={'color': 'lightblue2', 'style': 'filled', 'shape': 'circle'}) f.attr(rankdir='A', size='1000') f.edges(self.bridges) return f
def graphviz_try(): dot = Digraph(comment='The Round Table') dot.node('A', 'ROOT') dot.node('B', 'LEFT') dot.node('L', 'RIGHT') dot.edges(['AB', 'AL']) dot.edge('B', 'L', constraint='false') dot.view()
def greedyColoring(adj, V, v_list, w_list, edges): result = [-1] * V # Assign the first color to first vertex result[0] = 0; # A temporary array to store the available colors. # True value of available[cr] would mean that the # color cr is assigned to one of its adjacent vertices available = [False] * V # Assign colors to remaining V-1 vertices for u in range(1, V): # Process all adjacent vertices and # flag their colors as unavailable for i in adj[u]: if (result[i] != -1): available[result[i]] = True # Find the first available color cr = 0 while cr < V: if (available[cr] == False): break cr += 1 # Assign the found color result[u] = cr # Reset the values back to false # for the next iteration for i in adj[u]: if (result[i] != -1): available[result[i]] = False color_for_node="" g = Digraph('G') # Pint the result for u in range(V): print("Vertex", u, " ---> Color", result[u]) if (result[u] == 0): color_for_node = "red" if (result[u] == 1): color_for_node = "yellow" if (result[u] == 2): color_for_node = "purple" if (result[u] == 3): color_for_node = "blue" if (result[u] == 4): color_for_node = "gray" if (result[u] == 5): color_for_node = "green" g.attr('node', style='filled', color=color_for_node) g.node(str(u)) g.edges(edges) g.render(filename='g1.dot')
def inheritance_hierarchy(cls): # pragma: no cover (for visualization only) try: from graphviz import Digraph as Dot except ImportError: raise ImportError( "visualization of inheritance hierarchies requires graphviz") d = Dot("Inheritance hierarchy for {}".format(classpath(cls))) d.edges((classpath(c1), classpath(c2)) for c1, c2 in inheritances(cls)) return d
def main(): g = Digraph('passes', filename='passes', format='png') g.node('a', 'src') g.node('b', 'ast') g.node('c', 'simplified ast') g.node('e', 'inter-procedure relations') g.node('d', 'global name bindings') g.edges(['ab', 'bc', 'cd', 'de']) g.render('passes', view=True, cleanup=True)
def print_course_dot(*courseinfo): dot = Digraph(name='G') dot.attr(rankdir='LR') dot.attr('node', width='5', height='1') node_names, labels, edges = courseinfo for i in range(len(node_names)): dot.node(name=node_names[i], label=labels[i]) dot.edges(edges) print(dot.source)
def generateTree(grammar, string): dot = Digraph(comment=f"{grammar.getName()}", format="png") dot.attr(rankdir='TB', size='8,5') dot.attr('node', shape='circle') # dot.node(grammar.getNTInitial()) nodes = grammar.generateAP(string) arrayEdges = [] print(nodes) # ['S', 'z', 'M', 'a', 'M', 'z', 'a', 'N', 'b', 'N', 'z', 'b', 'z'] i = 65 nodeTemp = '' relation = {} relations = [] marker = False for node in nodes: dot.node(chr(i), node) if nodeTemp != '': arrayEdges.append(nodeTemp + chr(i)) if node in grammar.getNonTerminals(): if nodeTemp != '': arrayEdges.append(nodeTemp + chr(i)) pushRelations(relation, i, node, relations) relation = {} nodeTemp = chr(i) if node in grammar.getTerminals(): for production in grammar.getProductions(): if production["prod"][0] == node: for rel in relations: if rel['value'] == production['NT']: arrayEdges.append(rel['key'] + chr(i)) marker = True break if not marker: arrayEdges.append(nodeTemp + chr(i)) pushRelations(relation, i, node, relations) relation = {} break break else: if chr(i) != nodeTemp: arrayEdges.append(nodeTemp + chr(i)) i = i + 1 # dot.edges(['AB', 'AC', 'CD', 'CE', 'EF', 'CG', 'AH', 'HI', 'HJ', 'JK', 'HL', 'AM']) dot.edges(arrayEdges) dot.render(filename="three")
def test1(): dot = Digraph(comment='The Round Table') dot.node('A', 'King Arthur') dot.node('B', 'Sir Bedevere the Wise') dot.node('L', 'Sir Lancelot the Brave') dot.edges(['AB', 'AL']) dot.edge('B', 'L', constraint='false') createDotFile(dot, "test1")
def graph(): wit_folder_path = does_wit_folder_exists() if not wit_folder_path: print( "The folder '.wit' does not exists in any of the parent folders and thus the function can not operate." ) else: rfr_path = os.path.join(wit_folder_path, 'references.txt') rfr = open(rfr_path, 'r') rfr_lines = rfr.readlines() head = rfr_lines[0].split('=')[1].strip() parent_path = head branches_dict = {} commit_id_dict = {} descriptor = ord('A') b_descriptor = ord('a') while parent_path != 'None' and parent_path is not None: if ',' in parent_path: right_parent_path = parent_path.split(',')[1] branches_dict[right_parent_path] = b_descriptor parent_path = parent_path.split(',')[0] b_descriptor = b_descriptor + 1 commit_id_dict[parent_path] = descriptor descriptor = descriptor + 1 parent_path = get_parent_id(parent_path) dot = Digraph('Commit Id Tree', filename='graph_tree', format='png') for commit_id in commit_id_dict: dot.node(chr(commit_id_dict[commit_id]), commit_id) src = ord('A') dst = ord('B') edges_list = [] for _ in range(len(commit_id_dict) - 1): edges_list.append(f'{chr(src)}{chr(dst)}') src = src + 1 dst = dst + 1 for branch in branches_dict: descriptor = branches_dict[branch] dot.node(chr(descriptor), branch) branch_parent = get_parent_id(branch) branch_parent_descriptor = commit_id_dict[branch_parent] edges_list.append( f'{chr(descriptor)}{chr(branch_parent_descriptor)}') descriptor = descriptor + 1 for commit in commit_id_dict: f = open(index_path(commit) + '.txt', 'r') f_data = f.readlines() is_parent_merged = f_data[0].split('=')[1] if ',' in is_parent_merged: p = is_parent_merged.split(',')[1].strip() if p == branch: commit_string = commit_id_dict[commit] branch_string = branches_dict[branch] edges_list.append( f'{chr(commit_string)}{chr(branch_string)}') dot.edges(edges_list) dot.view()
def draw_graph(l: List[dict], filename: Optional[str] = None, view: bool = False) -> str: """ Draw a graph from a list of dicts. :param l: list of dicts :type l: List[dict] :param filename: full path for storing the draw graph pdf file :type filename: Optional[str] :param view: view the graph in the system's default pdf reader after it is rendered :type view: Optional[bool] :return: full path to the graph pdf file :rtype: str """ if filename is None: workdir = make_workdir(prefix='graph_') filename = os.path.join(workdir, 'graph') g = Digraph('G', filename=filename, format='pdf', node_attr={'shape': 'record'}) o_encounters = [] o_n_l = [] for op in l: o = list(op.keys())[0] params = op[o] s = [] for k in params.keys(): p = str(params[k]).replace("{", "\\n --\> ").replace( "}", "").replace( "|", "\|" ) # .replace("[", " ").replace("(", " ").replace(")", " ") s.append(f"{k}: {p}") o_n = f"{o}.{o_encounters.count(o)}" o_n_l.append(o_n) s = '{ ' + o_n + ' | ' + '\\n'.join(s) + ' }' g.node(o_n, s) o_encounters.append(o) es = [] for i in range(1, len(o_n_l)): es.append((o_n_l[i - 1], o_n_l[i])) g.edges(es) g.render(view=view) return filename
def first_graph(): dot = Digraph(comment='The Round Table', engine='neato') dot.node('A', 'King Arthur', pos='1,2!') dot.node('Bc', 'Sir Bedevere the Wise', pos='2,2.5!') dot.node('L', 'Sir Lancelot the Brave', pose='0,0!') dot.edges([('A', 'Bc'), 'AL']) dot.edge('Bc', 'L', constraint='false') print(dot.source) dot.render('visuals/round-table.gv', view=True)
def show_graph(self): dot = Digraph() for v in self.rvs: dot.node(str(v), str(v)) edges = [] # for vi, vfs dot.edges(f"{vi}{vf}" for vi, vf in self.G) print(dot.source) file_name = "myplot" dot.render(file_name, view=True)
def main(): # test sql query test_cases = open('test_cases.txt', 'r') for test in test_cases: statements = Translator.separate_statements(test) for statement in statements: T = Translator(statement) T.Translate() #print T, '\n' dot = Digraph(comment='query tree') dot.node('A', "<Π<SUB>" + ' '.join(T.Parsed.select_clause) + "</SUB>>") # make projection, selection, and join nodes using unicode symbol and subscript HTML tags dot.node('B', "<σ<SUB>" + ' '.join(T.Parsed.where_clause) + "</SUB>>") dot.node('L', "×") # cross product node for x in xrange(len(T.Parsed.from_clause)): symbol = str(x) dot.node(symbol, T.Parsed.from_clause[x]) dot.edge('L', symbol, constraint='true') dot.edges(['AB', 'BL']) print dot """ tree = QueryTree() print test for statement in statements: T = Translator(statement) T.Translate() print T, '\n' if len(T.Parsed.from_clause) > 1: join = tree.Node('X', [tree.Node(x) for x in T.Parsed.from_clause]) select = tree.Node(' '.join(T.Parsed.where_clause), [join]) else: select = tree.Node(' '.join(T.Parsed.where_clause), [tree.Node(i) for i in T.Parsed.from_clause]) project = tree.Node(' '.join(T.Parsed.select_clause), [select]) tree.output() print """ print '-'*80
from graphviz import Digraph from datos import data d=data('mtcars') subset1= d[d.cyl==6] dot = Digraph(comment='Tree Diagram', format='png') dot.attr('node', shape='box') dot.node_attr.update(color='lightblue2', style='filled') dot.node('A', 'Car Distribution by Cylindres') dot.node('B', '6 cylindres') j=67; for i in subset1.index: dot.node(unichr(j), str(i)) j=j+1 dot.edge('A', 'B') dot.edges(['BC','BD','BE','BF','BG','BH','BI']) dot.body.append(r'label = "\n\nTree Diagram"') dot.body.append('fontsize=20') dot.render('diagram')
#!/usr/bin/env python # cluster.py - http://www.graphviz.org/content/cluster from graphviz import Digraph g = Digraph('G', filename='cluster.gv') c0 = Digraph('cluster_0') c0.body.append('style=filled') c0.body.append('color=lightgrey') c0.node_attr.update(style='filled', color='white') c0.edges([('a0', 'a1'), ('a1', 'a2'), ('a2', 'a3')]) c0.body.append('label = "process #1"') c1 = Digraph('cluster_1') c1.node_attr.update(style='filled') c1.edges([('b0', 'b1'), ('b1', 'b2'), ('b2', 'b3')]) c1.body.append('label = "process #2"') c1.body.append('color=blue') g.subgraph(c0) g.subgraph(c1) g.edge('start', 'a0') g.edge('start', 'b0') g.edge('a1', 'b3') g.edge('b2', 'a3') g.edge('a3', 'a0') g.edge('a3', 'end') g.edge('b3', 'end')
from graphviz import Digraph dot = Digraph(comment="The Round Table") dot.node("A", "King Arthur") dot.node("B", "Sir Bedevere the Wise") dot.node("L", "Sir Lancelot the Brave") dot.edges(["AB", "AL"]) dot.edge("B", "L", constraint="false") print(dot.source) dot.render("test-output/round-table.gv", view=True)
from graphviz import Digraph import pydot dot = Digraph(comment='The Round Table') dot.node('A', 'King Arthur') dot.node('B', 'Sir Bedevere the Wise') dot.node('L', 'Sir Lancelot the Brave') dot.edges(['AB', 'AL']) dot.edge('B', 'L', constraint='false') print dot.source dot.view()
# testoutput.py - Dana Oira from graphviz import Digraph c = Digraph('testoutput', filename='testoutput.gv') c.attr('node', shape='box') c.attr('graph', rank='same') c.body.append('{rank=same; "complete"; "1";}') # c.body.append('{rank=same; "complete"; "1";}') c.body.append('{ rank=same; "a"; "2" }') c.body.append('{ rank=same; "b"; "3" }') c.body.append('{ rank=same; "c"; "4" }') c.body.append('{ rank=same; "d"; "5" }') c.body.append('{ rank=same; "e"; "6" }') c.edges([('complete', 'a'), ('a', 'b'), ('b', 'c'), ('c', 'd')]) c.edge('d', 'e', '', dir='both') c.node('1') c.node('2') c.node('3') c.node('4') c.node('5') c.node('6') c.node('7') c.node('8') print(c.source) c.view()
from graphviz import Digraph dot = Digraph() strict_wfq='static std::map<uint32_t, uint32_t> last_fin_time = {{1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}}; auto ret = last_fin_time.at(static_cast<uint32_t>(x("class"))); last_fin_time.at(static_cast<uint32_t>(x("class"))) += 1; return ret;' stopandgo='uint32_t now = (uint32_t) x("time");\n' stopandgo+='static uint32_t frame_end_time=1;\nstatic uint32_t frame_begin_time;' stopandgo+='if (now > frame_end_time){\nframe_begin_time= frame_end_time;\nframe_end_time= frame_begin_time+1;\n}\n' stopandgo+= 'return frame_end_time;\n' txn = header= open("tbfRight.txt",'r') tbfRight= txn.read() strict_wfq='static std::map<uint32_t, uint32_t> last_fin_time = {{1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}}; auto ret = last_fin_time.at(static_cast<uint32_t>(x("arrival_time")%2)); last_fin_time.at(static_cast<uint32_t>(x("arrival_time")%2)) += 1; return ret;' lstf="return (uint32_t) x(\"slack\");" dot.node('Root', "Name: Root\nPredicate: True \nSchedule: WFQ_Root \nShaping: NULL", predicate="True", schedule=strict_wfq, shaping="NULL" ) dot.node("Left", "Name: Left\nPredicate: True \nSchedule: WFQ_Left \nShaping: NULL", predicate="p.arrival_time==Left", schedule=strict_wfq, shaping="NULL") dot.node("Right", "Name: Right \nPredicate: True \nSchedule: WFQ_Right \nShaping: TBF_RIGHT", predicate = "p.arrival_time==Right", schedule=strict_wfq, shaping="NULL") dot.edges([("Root","Left"),("Root","Right")]) print dot.source dot.render('TBFPaper.gv',view=True) dot.save('TBFPaper.dot')
</TR> </TABLE>>''') s.node('struct2', '''< <TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0"> <TR> <TD PORT="f0">one</TD> <TD>two</TD> </TR> </TABLE>>''') s.node('struct3', '''< <TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="4"> <TR> <TD ROWSPAN="3">hello<BR/>world</TD> <TD COLSPAN="3">b</TD> <TD ROWSPAN="3">g</TD> <TD ROWSPAN="3">h</TD> </TR> <TR> <TD>c</TD> <TD PORT="here">d</TD> <TD>e</TD> </TR> <TR> <TD COLSPAN="3">f</TD> </TR> </TABLE>>''') s.edges([('struct1:f1', 'struct2:f0'), ('struct1:f2', 'struct3:here')]) s.view()
def graph(self, file): dot = Digraph(comment="LDFI", format='png') edges = self.edgeset() dot.edges(edges) dot.render(file)
# Generate Interaction Schematic Image dot = Digraph(comment='Interaction Schematic') # Nodes dot.node('A', '{0}: {1}-{2}'.format(uni_gene[cplx1_uni], cplx1_start, int(cplx1_from) - 1), shape='box') dot.node('B', '{0}: {1}-{2}'.format(uni_gene[cplx1_uni], cplx1_from, cplx1_to), color='yellow', shape='box') dot.node('C', '{0}: {1}-{2}'.format(uni_gene[cplx1_uni], int(cplx1_to) + 1, cplx1_end), shape='box') dot.node('E', '{0} Chain {1}'.format(intrcn_cplx, cplx1_chain), color='yellow', shape='box') dot.node('F', '{0} Chain {1}'.format(intrcn_cplx, cplx2_chain), color='cyan', shape='box') dot.node('G', '{0}: {1}-{2}'.format(uni_gene[cplx2_uni], cplx2_start, int(cplx2_from) - 1), shape='box') dot.node('H', '{0}: {1}-{2}'.format(uni_gene[cplx2_uni], cplx2_from, cplx2_to), color='cyan', shape='box') dot.node('I', '{0}: {1}-{2}'.format(uni_gene[cplx2_uni], int(cplx2_to) + 1, cplx2_end), shape='box') # Edges dot.edges(['AB', 'BC', 'GH', 'HI', 'EF']) dot.edge('B', 'E', constraint='false', color='gray') dot.edge('H', 'F', constraint='false', color='gray') dot.format = 'png' intrcn_schematic_png_path = '{0}/{1}_scheme'.format(PNG_DIR, intrcn_cplx) dot.render(intrcn_schematic_png_path, view=False) intrcn_schematic_png_path = '{0}.png'.format(intrcn_schematic_png_path) # Generate Fusion Effect Schematic Image style = {} style = defaultdict(lambda: '',style) fillcolor = {} fillcolor = defaultdict(lambda: 'lightgrey',fillcolor) # Interaction Complex 1