def render(self, img_format='png'): from circuits.models import CircuitTermination from dcim.models import CONNECTION_STATUS_CONNECTED, Device, InterfaceConnection # Construct the graph graph = graphviz.Graph() graph.graph_attr['ranksep'] = '1' seen = set() for i, device_set in enumerate(self.device_sets): subgraph = graphviz.Graph(name='sg{}'.format(i)) subgraph.graph_attr['rank'] = 'same' # Add a pseudonode for each device_set to enforce hierarchical layout subgraph.node('set{}'.format(i), label='', shape='none', width='0') if i: graph.edge('set{}'.format(i - 1), 'set{}'.format(i), style='invis') # Add each device to the graph devices = [] for query in device_set.strip(';').split(';'): # Split regexes on semicolons devices += Device.objects.filter(name__regex=query).select_related('device_role') # Remove duplicate devices devices = [d for d in devices if d.id not in seen] seen.update([d.id for d in devices]) for d in devices: bg_color = '#{}'.format(d.device_role.color) fg_color = '#{}'.format(foreground_color(d.device_role.color)) subgraph.node(d.name, style='filled', fillcolor=bg_color, fontcolor=fg_color, fontname='sans') # Add an invisible connection to each successive device in a set to enforce horizontal order for j in range(0, len(devices) - 1): subgraph.edge(devices[j].name, devices[j + 1].name, style='invis') graph.subgraph(subgraph) # Compile list of all devices device_superset = Q() for device_set in self.device_sets: for query in device_set.split(';'): # Split regexes on semicolons device_superset = device_superset | Q(name__regex=query) # Add all interface connections to the graph devices = Device.objects.filter(*(device_superset,)) connections = InterfaceConnection.objects.filter( interface_a__device__in=devices, interface_b__device__in=devices ) for c in connections: style = 'solid' if c.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed' graph.edge(c.interface_a.device.name, c.interface_b.device.name, style=style) # Add all circuits to the graph for termination in CircuitTermination.objects.filter(term_side='A', interface__device__in=devices): peer_termination = termination.get_peer_termination() if (peer_termination is not None and peer_termination.interface is not None and peer_termination.interface.device in devices): graph.edge(termination.interface.device.name, peer_termination.interface.device.name, color='blue') return graph.pipe(format=img_format)
def get_relationship_graph(codename, acquaintances, relationships): """ codename: main codename we are interested in acquaintances: list of codename:str relationships: list of ((codename:str, codename:str): (relationship:str, level:int, accuracy:int, valid:bool)) """ path = os.path.join(tempfile.mkdtemp(), 'network') g = gv.Graph(filename=path, format='png', engine='circo') g = gv.Graph(filename=path, format='png', engine='sfdp') # g.node(codename) node_fontsize = '10' edge_fontsize = '8' g.node(codename, fontsize=node_fontsize, fontname='Helvetica') for node in acquaintances: g.node(node, fontsize=node_fontsize, fontname='Helvetica') for (a, b), (relationship, level, accuracy, valid) in relationships: """swap relationship if necessary""" if codename == a: relationship = opposites.get(relationship) or relationship g.edge(a, b, label=relationship + ' ' * 10, color=get_relationship_color(relationship), alpha='0.8', penwidth=str((level or 1) * (accuracy or 1) / 20), fontsize=edge_fontsize, fontname='Helvetica', style='solid' if valid else 'dotted') # g.view() g.render() with open(path + '.png', 'rb') as f: network_str = BytesIO(f.read()) return network_str
def test_set_jupyter_format(monkeypatch, *, jupyter_format='jpg', expected_old_format='svg', expected_normalized_format='jpeg', expected_mimetype='image/jpeg'): assert len({DEFAULT_JUPYTER_MIMETYPE, jupyter_format}) == 2 from graphviz import jupyter_integration assert (jupyter_integration.JupyterIntegration._jupyter_mimetype == DEFAULT_JUPYTER_MIMETYPE) # isolate the test monkeypatch.setattr('graphviz.jupyter_integration.JupyterIntegration._jupyter_mimetype', DEFAULT_JUPYTER_MIMETYPE) assert (jupyter_integration.JupyterIntegration._jupyter_mimetype == DEFAULT_JUPYTER_MIMETYPE) g1 = graphviz.Graph() assert g1._jupyter_mimetype == DEFAULT_JUPYTER_MIMETYPE old = graphviz.set_jupyter_format(jupyter_format) assert old == jupyter_integration.DEFAULT_JUPYTER_FORMAT assert g1._jupyter_mimetype == expected_mimetype g2 = graphviz.Graph() assert g2._jupyter_mimetype == expected_mimetype old = graphviz.set_jupyter_format(DEFAULT_JUPYTER_FORMAT) assert old == expected_normalized_format assert g1._jupyter_mimetype == DEFAULT_JUPYTER_MIMETYPE assert g2._jupyter_mimetype == DEFAULT_JUPYTER_MIMETYPE
def test_set_default_format(monkeypatch, *, format='png', explicit_format='jpeg'): assert len({DEFAULT_FORMAT, format, explicit_format}) == 3 from graphviz.parameters import Parameters assert Parameters._format == DEFAULT_FORMAT # isolate the test monkeypatch.setattr('graphviz.parameters.Parameters._format', DEFAULT_FORMAT) assert Parameters._format == DEFAULT_FORMAT g1 = graphviz.Graph() assert g1.format == DEFAULT_FORMAT g2 = graphviz.Graph(format=explicit_format) assert g2.format == explicit_format old = graphviz.set_default_format(format) assert old == DEFAULT_FORMAT assert g1.format == format assert g2.format == explicit_format g3 = graphviz.Graph() assert g3.format == format g4 = graphviz.Graph(format=explicit_format) assert g4.format == explicit_format old = graphviz.set_default_format(DEFAULT_FORMAT) assert old == format assert g1.format == DEFAULT_FORMAT assert g2.format == explicit_format assert g3.format == DEFAULT_FORMAT assert g4.format == explicit_format
def test_set_default_engine(monkeypatch, *, engine='neato', explicit_engine='sfdp'): assert len({DEFAULT_ENGINE, engine, explicit_engine}) == 3 from graphviz.parameters import Parameters assert Parameters._engine == DEFAULT_ENGINE # isolate the test monkeypatch.setattr('graphviz.parameters.Parameters._engine', DEFAULT_ENGINE) assert Parameters._engine == DEFAULT_ENGINE g1 = graphviz.Graph() assert g1.engine == DEFAULT_ENGINE g2 = graphviz.Graph(engine=explicit_engine) assert g2.engine == explicit_engine old = graphviz.set_default_engine(engine) assert old == DEFAULT_ENGINE assert g1.engine == engine assert g2.engine == explicit_engine g3 = graphviz.Graph() assert g3.engine == engine g4 = graphviz.Graph(engine=explicit_engine) assert g4.engine == explicit_engine old = graphviz.set_default_engine(DEFAULT_ENGINE) assert old == engine assert g1.engine == DEFAULT_ENGINE assert g2.engine == explicit_engine assert g3.engine == DEFAULT_ENGINE assert g4.engine == explicit_engine
def __create_dot_file(self, instances): graph = graphviz.Graph("Principal") graph1 = graphviz.Graph() graph2 = graphviz.Graph() for instance in instances: if INSTANCE_NAME_TAG in instance.tags: graph.node(instance.tags[INSTANCE_NAME_TAG], _attributes=NODE_ATTRIBUTES) #if instance.vpc_id not in vpcs.keys(): # vpcs[instance.vpc_id] = [] #else: # vpcs[instance.vpc_id].append(instance) else: eprint(ERROR_NO_INSTANCE_NAME_TAG) for instance_a in instances: for instance_b in instances: if INSTANCE_NAME_TAG in instance_a.tags and INSTANCE_NAME_TAG in instance_b.tags: graph.edge(instance_a.tags[INSTANCE_NAME_TAG], instance_b.tags[INSTANCE_NAME_TAG]) graph1.node("otro nodo 1") graph2.node("otro nodo 2") graph.subgraph(graph1) graph.subgraph(graph2) graph.edge("otro nodo 1", "otro nodo 2") print(graph._subgraph) graph.save(FULL_FILE_RESULT_PATH) return FULL_FILE_RESULT_PATH
def get(self, request, slug): tmap = get_object_or_404(TopologyMap, slug=slug) # Construct the graph graph = graphviz.Graph() graph.graph_attr['ranksep'] = '1' for i, device_set in enumerate(tmap.device_sets): subgraph = graphviz.Graph(name='sg{}'.format(i)) subgraph.graph_attr['rank'] = 'same' # Add a pseudonode for each device_set to enforce hierarchical layout subgraph.node('set{}'.format(i), label='', shape='none', width='0') if i: graph.edge('set{}'.format(i - 1), 'set{}'.format(i), style='invis') # Add each device to the graph devices = [] for query in device_set.split(','): devices += Device.objects.filter(name__regex=query) for d in devices: subgraph.node(d.name) # Add an invisible connection to each successive device in a set to enforce horizontal order for j in range(0, len(devices) - 1): subgraph.edge(devices[j].name, devices[j + 1].name, style='invis') graph.subgraph(subgraph) # Compile list of all devices device_superset = Q() for device_set in tmap.device_sets: for query in device_set.split(','): device_superset = device_superset | Q(name__regex=query) # Add all connections to the graph devices = Device.objects.filter(*(device_superset, )) connections = InterfaceConnection.objects.filter( interface_a__device__in=devices, interface_b__device__in=devices) for c in connections: graph.edge(c.interface_a.device.name, c.interface_b.device.name) # Get the image data and return try: topo_data = graph.pipe(format='png') except: return HttpResponse( "There was an error generating the requested graph. Ensure that the GraphViz " "executables have been installed correctly.") response = HttpResponse(topo_data, content_type='image/png') return response
def _build_graph(self, req, tkt_id): links = TicketLinks(self.env, tkt_id) g = graphviz.Graph() node_default = g['node'] node_default['style'] = 'filled' edge_default = g['edge'] edge_default['style'] = '' # Force this to the top of the graph g[tkt_id] links = sorted(links.walk(), key=lambda link: link.tkt.id) for link in links: tkt = link.tkt node = g[tkt.id] node['label'] = u'#%s' % tkt.id node['fillcolor'] = tkt['status'] == 'closed' and 'green' or 'red' node['URL'] = req.href.ticket(tkt.id) node['alt'] = u'Ticket #%s' % tkt.id node['tooltip'] = tkt['summary'] for n in link.blocking: node > g[n] return g
def draw_alignment(inst: Instance): """ Represent the instance with a png graph """ dot = graphviz.Graph(engine='fdp') def phrase_to_subgraph(p: Phrase, v_level): with dot.subgraph(name=p.id) as sg: for i, word in enumerate(p): sg.node(word.id, label=word.hyphenated, shape='plaintext', pos='{0},{1}!'.format(i, v_level)) # Attempt to space the vertical distance between trans/gloss # proportional to the length of the gloss tier, otherwise # it is hard to read. height_sep = max(1, len(inst.gloss) / 10) phrase_to_subgraph(inst.lang, height_sep + 1) phrase_to_subgraph(inst.gloss, height_sep * 1) phrase_to_subgraph(inst.trans, 0) for tw, gw in inst.trans.aligned_words(): # type: Word, Word dot.edge(tw.id, gw.id) for lw, gw in inst.lang.aligned_words(): # type: Word, Word dot.edge(lw.id, gw.id) dot.attr(overlap='false', sep='1') png = dot.pipe(format='png') return png
def add_domtree_leaf(self, instance, tree, dtleaf): g = gv.Graph() self.index += 1 stack = [(tree.root(), False)] while len(stack) > 0: node, marked = stack.pop() is_reachable = dtleaf.is_reachable(instance, tree.index(), node) marked |= not is_reachable c = "darkgreen" if not marked else "gray" s = "bold" if not marked else "" if not is_reachable: c = "red" if tree.is_leaf(node): g.node(self.name(node), "{:.3f}".format(tree.get_leaf_value(node)), style=s, color=c, fontcolor=c) else: label = self.get_split_label(tree.get_split(node)) g.node(self.name(node), label, style=s, color=c, fontcolor=c) stack.append((tree.right(node), marked)) stack.append((tree.left(node), marked)) if not tree.is_root(node): g.edge(self.name(tree.parent(node)), self.name(node), color=c) self.g.subgraph(g)
def render_steiner(g, terminals, tree_edges): terminal_style = {'color': 'blue'} steiner_style = {'color': 'red'} def get_steiner_nodes(terminals, tree_edges): ns = set() for e0, e1 in tree_edges: ns.add(e0) ns.add(e1) return ns - set(terminals) def get_node_style(v, terminals, steiner_nodes): if v in terminals: return terminal_style elif v in steiner_nodes: return steiner_style return {} def get_edge_style(e, tree_edges): if e in tree_edges: return steiner_style return {} dot = graphviz.Graph() steiner_nodes = get_steiner_nodes(terminals, tree_edges) for v, es in g.items(): dot.node(v, **get_node_style(v, terminals, steiner_nodes)) for v0, v1 in get_edges_from_graph(g): dot.edge(v0, v1, **get_edge_style(frozenset((v0, v1)), tree_edges)) dot.render('graph.gv')
def draw_coarse_cluster_graph(top_actions, highlight_top=True, highlight_last_actions=False, rankdir="BT"): g = gv.Graph("g") g.attr(rankdir=rankdir) flat_actions, flat_clusters = flatten(top_actions) colors = action_color_dict(flat_actions) if highlight_last_actions else {} middle_actions = [act for act in flat_actions if act not in top_actions] g.attr("node", **COARSE_ACTION_NODE_STYLE) with g.subgraph(name="cluster_actionlib") as s: s.attr(rank="same") for action in top_actions: s.node(action.name, label="", fillcolor=colors.get(action.name, "white"), penwidth="4" if highlight_top else "1") for action in middle_actions: g.node(action.name, label="", fillcolor=colors.get(action.name, "white")) g.attr("node", **COARSE_CLUSTER_NODE_STYLE) for cluster in flat_clusters: g.node(cluster.name, label="") for action in flat_actions: if action.parent: g.edge(action.parent.name, action.name) for cluster in flat_clusters: g.edge(cluster.left_parent.name, cluster.name) g.edge(cluster.right_parent.name, cluster.name) return g
def __init__(self, named_param_shapes: Iterable[Tuple], timer: BatchTimer, history_heatmap=False): """ :param named_param_shapes: named binary parameters shape :param timer: timer to schedule updates :param history_heatmap: draw history heatmap of all iterations? """ self.param_nodes = self.parse_parameters( named_param_shapes, history_heatmap=history_heatmap) self.with_history_heatmap = history_heatmap self.timer = timer self.graph = graphviz.Graph(name='graph_mcmc', directory='graphs', format='png', graph_attr=dict(rankdir='LR', color='white', splines='line', nodesep='0.04'), node_attr=dict(label='', shape='circle'), edge_attr=dict(constraint='false')) try: self.graph.pipe(format='svg') self.graphviz_installed = True except graphviz.backend.ExecutableNotFound: self.graphviz_installed = False warnings.warn( "To use graphviz features run 'sudo apt-get install graphviz'")
def printCLC(clc, customName=None): global clcCounter, hashclcCounter clcCopy = copy.deepcopy(clc) figuur = gv.Graph(format='png') figuur.node("Root", label="Root", style="solid", shape="circle") startNode = clcCopy.root if clcCopy.isEmpty(): pass else: figuur.node(str(startNode.searchkey), label=str(startNode.searchkey), style="solid", shape="circle") figuur.edge("Root", str(startNode.searchkey)) while startNode.next != clcCopy.root: figuur.node(str(startNode.next.searchkey), label=str(startNode.next.searchkey), style="solid", shape="circle") figuur.edge(str(startNode.searchkey), str(startNode.next.searchkey), arrowhead="normal", dir="forward") startNode = startNode.next figuur.edge(str(startNode.searchkey), str(clcCopy.root.searchkey), arrowhead="normal", dir="forward") if not customName: figuur.render(filename='DotFiles/cll-' + str(clcCounter) + '.dot') clcCounter += 1 else: figuur.render(filename='DotFiles/' + customName + '/' + customName + str(hashclcCounter) + '.dot') hashclcCounter += 1 return
def diagramSplit(self, pathResult): tree = gp.Graph(format='png') if (self.top != None): self.draw(self.top, tree) # formatear pathResult quitando ultimo slash pathResult = pathResult[0:(len(pathResult) - 1)] filename = tree.render(filename='tree', directory=pathResult)
def render(node, settings): """ Given an AST node and settings, return a displayable object. """ graph = graphviz.Graph(format='svg') names = (str(x) for x in itertools.count()) handle_ast( node, parent_node=None, graph=graph, names=names, omit_docstrings=settings['omit_docstrings'], terminal_color=settings['terminal_color'], nonterminal_color=settings['nonterminal_color'], ) graph.node_attr.update( dict( fontname=settings['font'], shape=settings['shape'], #height='0.25', # TODO: how to incorporate with scale param? #fixedsize='true', )) return SVG(graph.pipe(format='svg'))
def printQueue(queue): queueCopy = copy.deepcopy(queue) figuur = gv.Graph(format='png') figuur.node('Front', label="Front", style="solid", shape="circle") figuur.node('Back', label="Back", style="solid", shape="circle") count = 0 while not queueCopy.isEmpty(): figuur.node(str(count), label=str(queueCopy.getFront()), style="solid", shape="box") queueCopy.deQueue() count += 1 if count > 1: figuur.edge('Front', str(0)) for i in range(0, count - 1): figuur.edge(str(i), str(i + 1), arrowhead="normal", dir="back") figuur.edge(str(count - 1), 'Back') if count == 1: figuur.edge('Front', str(0)) figuur.edge(str(0), 'Back') if count == 0: figuur.edge('Front', 'Back') global queueCounter figuur.render(filename='DotFiles/queue-' + str(queueCounter) + '.dot') queueCounter += 1 return
def save_graph_image(name, pairs, directed=True, filename='png', view=True, **options): try: import graphviz except Exception as error: raise RuntimeError( f"graphviz cannot be imported to save graph image: {error}") file_parts = filename.rsplit('.', 1) if len(file_parts) == 1: # just an extension filename = name else: filename = file_parts[0] if directed: dot = graphviz.Digraph(comment=name, format=file_parts[-1], node_attr=options) else: dot = graphviz.Graph(comment=name, format=file_parts[-1], node_attr=options) for label1, label2 in pairs: dot.edge(label1, label2) dot.render(filename, view=view) return dot
def show_graph(self): nodes = self.arvore.keys() for i in nodes: if i == self.raiz: nodes.remove(i) nodes.insert(0, i) edges = list() self.g = gv.Graph(format='svg') self.g.graph_attr['rankdir'] = 'LR' self.g.node_attr['penwidth'] = '2.0' self.g.edge_attr['penwidth'] = '2.0' for i in nodes: self.g.node(i) for j in self.arvore[i]: ij = set((i, j)) if ij not in edges: edges.append(ij.copy()) n1 = ij.pop() n2 = ij.pop() p1 = self._busca_prof(n1)[0] p2 = self._busca_prof(n2)[0] if p1 < p2: self.g.edge(n1, n2) else: self.g.edge(n2, n1) return self.g
def plot_graph(G: Graph, with_labels=True, node_label="node_num", core_same_rank=True, nice_core=False): dot = graphviz.Graph() # dot.graph_attr['rankdir'] = 'LR' # dot.graph_attr['ratio'] = '0.95' delta = max_degree(G) nodes = set(G.nodes()) degrees = {x: G.degree(x) for x in G.nodes()} core = {x for x in degrees if degrees[x] == delta} def get_label(node): if node_label == "node_num": return str(node) return str(degrees[node]) if nice_core: core_nodes = set(core) adj = {x: set(G.neighbours(x)) & set(core_nodes) for x in core} values = set(len(adj[x]) for x in adj) for deg in sorted(values): with dot.subgraph() as s: s.attr(rank='same') s.attr('node', style='solid,filled', color='black', fillcolor='grey') for node in core: if len(adj[node]) == deg: s.node(str(node), get_label(node)) else: with dot.subgraph() as s: if core_same_rank: s.attr(rank='same') s.attr('node', style='solid,filled', color='black', fillcolor='grey') for node in core: s.node(str(node), get_label(node)) for node in nodes - core: dot.node(str(node), get_label(node)) for u, v in G.edges(): if with_labels: dot.edge(str(u), str(v), label=str(G[u, v])) else: dot.edge(str(u), str(v)) colours = colours_used(G) graph_class = 1 if colours == delta else (2 if colours == delta + 1 else '?') deg_seq = sorted(degrees.values()) dot.attr(label=rf'Δ = {delta}\nClass {graph_class}\n{deg_seq}') return dot
def visualizeGraph(graph, filename): if graph.directed != True: visualGraph = graphviz.Graph('G', node_attr={ 'shape': 'circle', 'color': 'lightblue2', 'style': 'filled' }) else: visualGraph = graphviz.Digraph('G', node_attr={ 'shape': 'circle', 'color': 'lightblue2', 'style': 'filled' }) for gNode in graph.get_allNodes(): visualGraph.node(str(gNode.index), str(gNode.index)) for (u, v, w) in graph.get_allEdges(): visualGraph.edge(str(u), str(v), label=str(w)) visualGraph.save(filename=os.path.abspath(os.getcwd() + "/graphFiles/" + filename + ".gv")) return graphviz.Source(visualGraph)
def nx2gv(G, weighted=False, params={ 'rankdir': 'LR', 'size': '6' }, path=None, pathparams={'color': 'orangered'}, nodeinfo=False): if G.is_directed(): g = gv.Digraph('G') else: g = gv.Graph('G') g.attr(**params) for u in G.nodes: if nodeinfo: g.node(str(u), **dict(G.nodes[u])) else: g.node(str(u)) for u, v in G.edges(): pp = pathparams if path and path[v] == u else {} if weighted: g.edge(str(u), str(v), f"{G.edges[u, v]['weight']}", **pp) else: g.edge(str(u), str(v), **pp) return g
def adjlShow(L, labels=None, directed=False, weighted=False, path=[], layout="sfdp"): g = gv.Digraph("G") if directed else gv.Graph("G") g.graph_attr["layout"] = layout g.edge_attr["color"] = "gray" g.node_attr["color"] = "orangered" g.node_attr["width"] = "0.1" g.node_attr["height"] = "0.1" g.node_attr["fontsize"] = "8" g.node_attr["fontcolor"] = "mediumslateblue" g.node_attr["fontname"] = "monospace" g.edge_attr["fontsize"] = "8" g.edge_attr["fontname"] = "monospace" n = len(L) for u in range(n): g.node(str(u), labels[u] if labels else str(u)) added = set() for v, u in enumerate(path): if u != None and u >= 0: if weighted: for vi, w in L[u]: if vi == v: break g.edge(str(u), str(v), str(w), dir="forward", penwidth="2", color="orange") else: g.edge(str(u), str(v), dir="forward", penwidth="2", color="orange") added.add(f"{u},{v}") added.add(f"{v},{u}") if weighted: for u in range(n): for v, w in L[u]: if not directed and not f"{u},{v}" in added: added.add(f"{u},{v}") added.add(f"{v},{u}") g.edge(str(u), str(v), str(w)) elif directed: g.edge(str(u), str(v), str(w)) else: for u in range(n): for v in L[u]: if not directed and not f"{u},{v}" in added: added.add(f"{u},{v}") added.add(f"{v},{u}") g.edge(str(u), str(v)) elif directed: g.edge(str(u), str(v)) return g
def adjlist2gv(G, type='digraph', weighted=False, params={'rankdir': 'LR'}): digraph = type == 'digraph' if digraph: g = gv.Digraph('G') else: g = gv.Graph('G') Gv.attr(**params) n = len(G) for i in range(n): g.node(str(i)) for u in range(n): if weighted: for v, w in range(n): g.edge(str(u), str(v), str(w)) if digraph: g.edge(str(v), str(u), str(w)) else: for v in range(n): g.edge(str(u), str(v)) if digraph: g.edge(str(v), str(u)) return g
def draw_topology(topology_dict, dest_filename='img/topology'): ''' topology_dict - словарь с описанием топологии Этот словарь {('R4', 'Fa0/1'): ('R5', 'Fa0/1'), ('R4', 'Fa0/2'): ('R6', 'Fa0/0')} соответствует топологии: [ R5 ]-Fa0/1 --- Fa0/1-[ R4 ]-Fa0/2---Fa0/0-[ R6 ] Функция генерирует топологию, в формате svg. И записывает файл topology.svg в каталог img. ''' nodes = set([item[0] for item in list(topology_dict.keys()) + list(topology_dict.values())]) g1 = gv.Graph(format='svg') for node in nodes: g1.node(node) for key, value in topology_dict.items(): head, t_label = key tail, h_label = value g1.edge(head, tail, headlabel=h_label, taillabel=t_label, label=" "*12) g1 = apply_styles(g1, styles) filename = g1.render(filename=dest_filename) print( "Graph saved in", dest_filename)
def show_graph(pairs, save='tree_graph'): """ 根据树枝对打印树 """ if pairs: pic = gv.Graph(filename=save) for pair in pairs: pic.edge(*pair) pic.view(cleanup=True)
def make_spoiler_graph(door_connections, spoiler_filename): # make a set of all the rooms rooms = set() for ldoor, rdoor in door_connections: rooms.add(get_room_name(ldoor)) rooms.add(get_room_name(rdoor)) dot = graphviz.Graph() for room_name in rooms: if room_name == "Landing Site": dot.node(room_name, room_name, color='blue', style='filled') elif room_name in boss_rooms: dot.node(room_name, room_name, color='red', style='filled') elif room_name in miniboss_rooms: dot.node(room_name, room_name, color='green', style='filled') elif room_name == "Statues": dot.node(room_name, room_name, color='yellow', style='filled') elif room_name == "Escape 4": dot.node(room_name, room_name, color='purple', style='filled') else: dot.node(room_name, room_name) for ldoor, rdoor in door_connections: dot.edge(get_room_name(ldoor), get_room_name(rdoor), label=(ldoor.split("_")[-1] + " to " + rdoor.split("_")[-1])) dot.render(spoiler_filename + ".graph")
def _build_graph(self, req, tkt_ids, label_summary=0): g = graphviz.Graph() g.label_summary = label_summary g.attributes['rankdir'] = self.graph_direction node_default = g['node'] node_default['style'] = 'filled' edge_default = g['edge'] edge_default['style'] = '' # Force this to the top of the graph for id in tkt_ids: g[id] links = TicketLinks.walk_tickets(self.env, tkt_ids) links = sorted(links, key=lambda link: link.tkt.id) for link in links: tkt = link.tkt node = g[tkt.id] if label_summary: node['label'] = u'#%s %s' % (tkt.id, tkt['summary']) else: node['label'] = u'#%s' % tkt.id node['fillcolor'] = tkt[ 'status'] == 'closed' and self.closed_color or self.opened_color node['URL'] = req.href.ticket(tkt.id) node['alt'] = u'Ticket #%s' % tkt.id node['tooltip'] = tkt['summary'] for n in link.blocking: node > g[n] return g
def __init__(self, args): self.graph = graphviz.Graph(format='svg') self.args = args self.smali_db = SmaliDatabase() self.smali_parser = SmaliParser(smali_dir=self.args.smali_sources, smali_database=self.smali_db, graph=self.graph) self.smali_scanner = SmaliScanner(smali_database=self.smali_db) if self.args.db_write: if not self.args.smali_sources: print 'no smali_sources argument. exiting.' return self.smali_db.set_db_path(self.args.db_write) self.smali_db.create_tables() self.smali_parser.parse_smali_files() elif self.args.db_read: self.smali_db.set_db_path(self.args.db_read) if self.args.reverse_method: self.build_called_from_method(self.args.reverse_method) if self.args.scan: self.scan_for_vulns() self.smali_db.conn.close()
def visualize(data, out_file): g = gv.Graph() queue = ['home'] visited = set('home') g.node('home') prev = {} prev['home'] = None while queue: node = queue.pop() if node[0] == '.': print('hidden') continue for neighbor in traverse_to_dict(data, get_path(prev, node)): if neighbor not in visited: queue.append(neighbor) visited.add(neighbor) prev[neighbor] = node if check_encode(neighbor): print(node) g.node(neighbor) g.edge(node, neighbor) g.save(out_file) os.system('dot -Tsvg -Ksfdp {0} > {1}'.format(out_file, out_file + '.svg')) os.system('rm {0}'.format(out_file))