def make_dot(name, url, label, nodes, edges): dot = Digraph(name=name, comment=url) dot.graph_attr.update({ 'label': label, 'overlap': 'scalexy' }) subgraphs = {} for node in nodes: if node.sensor not in subgraphs: url = url_for('sensor', id=node.sensor, _external=True) name = "cluster_sensor_{}".format(node.sensor) label = "Sensor {type}: {sname} ({sensor})".format_map( node._asdict()) subgraphs[node.sensor] = Digraph(name=name, comment=url) subgraphs[node.sensor].graph_attr.update({'label': label}) label = '{name}\\n({id})'.format_map(node._asdict()) subgraphs[node.sensor].node(str(node.id), label=label, color='black') for sensor in subgraphs: dot.subgraph(subgraphs[sensor]) for edge in edges: label = '{tname}\\n({id})'.format_map(edge._asdict()) dot.edge(str(edge.source), str(edge.target), label=label) dot.engine = 'dot' return dot
def render(self, filename, comment, render="content"): dot = Digraph(comment=comment,edge_attr={'len': '6', 'weight':'0.00001'}) dot.engine = 'dot' # add nodes to dot graph for node_key in self.nodes.keys(): node_content = "nil" # either use id or content to mark graph nodes if render == "id": node_content = str(self.nodes[node_key].id) elif render == "content": if len(self.nodes[node_key].content) > 0: node_content = ', '.join(str(x) for x in self.nodes[node_key].content) else: node_content = str(self.nodes[node_key].id) + ":" if len(self.nodes[node_key].content) > 0: node_content += ', '.join(str(x) for x in self.nodes[node_key].content) + ":" else: node_content += "nil:" if len(self.nodes[node_key].meta) > 0: node_content += self.nodes[node_key].meta else: node_content += "nil" dot.node(str(self.nodes[node_key].id), node_content) #add edges to dot graph for edge_key in self.edges.keys(): for dest_node in self.edges[edge_key]: dot.edge(str(edge_key), str(dest_node)) if not os.path.exists("graph"): os.makedirs("graph") dot.render("graph/" + filename + ".gv")
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 draw(FA, adj, output): newAlpha = list(FA[1]) if newAlpha[-1] == EPS: newAlpha.pop(); sigma = ', '.join(newAlpha) gr = Digraph(); gr.engine = 'dot' gr.format = 'pdf' gr.attr('node', style = 'invis'); gr.node('myStarting'); gr.attr('node', style = '', shape = 'doublecircle'); for u in FA[-1]: gr.node(str(u)); gr.attr('node', shape = 'circle'); for u in FA[0]: if u not in FA[-1]: gr.node(str(u)) gr.edge('myStarting', str(FA[2]), 'Start'); for u, v in adj.keys(): if adj[u, v] == sigma: gr.edge(str(u), str(v), 'Sigma') else: gr.edge(str(u), str(v), adj[u, v]) gr.render(output, view = True);
def plotDomGraph(m, filename): # plot dominance matrices as directed graphs N_nodes = m.shape[0] node_strengths = np.sum(m, axis=1) / (m.shape[0] - 1) node_strengths = (node_strengths + 1) / 2 node_colors = [ mpl.colors.rgb2hex([1 - s, 1 - s, 1]) for s in node_strengths ] node_names = list(string.ascii_uppercase[0:N_nodes]) foodwebgraph = Digraph() foodwebgraph.rankdir = 'BT' foodwebgraph.engine = GRAPHVIZENGINE foodwebgraph.format = "pdf" # add nodes for idx, node_name in enumerate(node_names): nodecolor = node_colors[idx] foodwebgraph.node(node_name, style="filled", color='#000000', fillcolor=nodecolor, fontcolor='#000000') # add edges for i, i_name in enumerate(node_names): for j, j_name in enumerate(node_names): edgecolor = '#000000' preflength = str(1.0) if m[i, j] == 1: foodwebgraph.edge(i_name, j_name, color=edgecolor, len=preflength) # save filepath = os.path.join(GRAPHSAVEDIR, filename) foodwebgraph.render(filepath, cleanup=True)
def draw_combined(ast_root, cfg_root, reduced=True, only_blocks=False, format='png', highlight=None): ast_dot = ASTVisualiser(ast_root).start(combined=True, reduced=reduced, highlight=highlight) cfg_dot = CFGVisualiser(cfg_root).start(only_blocks=only_blocks, combined=True) dot = Digraph(strict=True) dot.attr('graph', fontname='helvetica') dot.attr('graph', splines='polyline') dot.attr('graph', compound='true') dot.attr('node', fontname='helvetica') dot.attr('node', style='filled', fillcolor='white') dot.attr('edge', fontname='helvetica') dot.subgraph(ast_dot) dot.subgraph(cfg_dot) dot.format = format dot.engine = 'dot' dot.render(view=True, cleanup=True, filename='Combined')
def graph(data): dot = Digraph(comment='Roots') dot.engine = 'dot' dot.format = 'svg' dot.attr(rankdir='BT', nodesep='1.0', ranksep='0.1', overlap="false") dot.attr('node', fontsize='40') for kanji in data.kanjis: if float(data.colors[kanji].split(" ")[1]) < 0.8: continue #try: k = kanji#.decode('utf-8') label = ("" + kanji + "\n " + data.descriptions[kanji])#.decode('utf-8') color = data.colors[kanji] dot.node(data.descriptions[kanji], label=kanji, fontsize="40", fillcolor=color, style='filled') ORoots.printComponents(dot, kanji, data.descriptions[kanji], 25, data) #except Exception: # print("encoding fial") return dot
def visualize_edges(graph, out_file, control_edges, dep_edges): nodes = graph.nodes dot = Digraph(comment='Graph') #nodes = [] row_height = 50 indent_len = 50 max_height = len(nodes) * row_height known_nodes = [] def get_height(row_num): return max_height - row_num * row_height for edges, is_control in [(graph.control_edges, True), (graph.dep_edges, False)]: for edge in edges: if (is_control and control_edges) or (not is_control and dep_edges): x, y = edge.from_, edge.to # x_node = pydot.Node("Node B", style="filled", fillcolor="green") if x not in known_nodes: dot.node(str(x), nodes[x].statement, color="black", pos="%d,%d" % (nodes[x].indent * indent_len, get_height(x))) # print nodes[x].statement if y < len(nodes): if y not in known_nodes: dot.node(str(y), nodes[y].statement, pos="%d,%d" % (nodes[y].indent * indent_len, get_height(y))) if not is_control: dot.edge(str(x), str(y), color="green", style="dashed") elif edge.jmp_true is None: dot.edge(str(x), str(y), color="black") elif edge.jmp_true is True: dot.edge(str(x), str(y), color="blue") else: dot.edge(str(x), str(y), color="red") # apply_styles(dot, styles) dot.engine = "neato" dot.save(out_file, None) cmd = "neato.exe -Tpdf -O -n2 -Goverlap=false -Gsplines=true " + out_file try: returncode = subprocess.Popen(cmd).wait() except OSError as e: if e.errno == errno.ENOENT: raise RuntimeError('failed to execute %r, ' 'make sure the Graphviz executables ' 'are on your systems\' path' % cmd) else: raise
def bstviz(tree, just_keys=False, padding=0.6): """ Create a dot object to visualize a binary search tree. Assumes tree is a class that has a root member. This is a node of the tree. Also assumes each node has: - left: left child in the bst - right: right child in the bst - key: key of the node - item: item held at the key The returned dot object, say "treedot", can be viewed the usual way: treedot.render(view=True) """ dot = Digraph() dot.attr("node", fontname="helvetica-bold", fontsize="20") if len(tree) == 0: dot.node("empty tree", style="dashed") return dot def gen_drawing(node, depth): nonlocal nodes_seen if node is None or node.key is None: return -1 l_index = gen_drawing(node.left, depth+1) index = nodes_seen nodes_seen += 1 pos_str = str(index*padding)+','+str(-depth)+'!' key_str = str(node.key) label = key_str if not just_keys: label += ','+str(node.item) dot.node(key_str, label, pos=pos_str) r_index = gen_drawing(node.right, depth+1) if l_index != -1: dot.edge(key_str, str(node.left.key)) if r_index != -1: dot.edge(key_str, str(node.right.key)) return index nodes_seen = 0 root_id = gen_drawing(tree.root, 0) dot.node("__root", "root", pos=str(root_id*padding)+",1!", color="white") dot.edge("__root", str(tree.root.key)) dot.engine = "neato" return dot
def plotgraph(a, filepath, ref_a=None): N_sp = a.shape[0] sp_names = list(string.ascii_uppercase[0:N_sp]) # (directed) connectedness numpy array: [i,j] element is True if j eats i, else False connected = np.logical_and(a > 0, np.transpose(a) < 0) if ref_a is None: ref_connected = connected else: ref_connected = np.logical_and(ref_a > 0, np.transpose(ref_a) < 0) # preferred edge lengths = 1 for all edges preflengths = np.where(connected, np.ones_like(a), np.zeros_like(a)) # connection weights numpy array: product of mutual effect strengths for directed edges w = np.where(connected, np.abs(a * np.transpose(a)), np.zeros_like(a)) w = w / np.max(w) # colors array vectorized_to_hex = np.vectorize(mpl.colors.to_hex) edgecolors = vectorized_to_hex((1 - w).astype(str)) edgecolors = np.where(connected, edgecolors, np.NAN) foodwebgraph = Digraph() foodwebgraph.rankdir = 'BT' #foodwebgraph.engine = 'neato' #foodwebgraph.engine = 'fdp' #foodwebgraph.engine = 'circo' foodwebgraph.engine = 'dot' foodwebgraph.format = "pdf" # add nodes for idx, sp_name in enumerate(sp_names): if np.array_equal(connected[idx], ref_connected[idx]) and np.array_equal( connected[:, idx], ref_connected[:, idx]): mistake = False else: mistake = True if mistake: nodecolor = '#ff0000' else: nodecolor = '#000000' foodwebgraph.node(sp_name, style="filled", color=nodecolor, fillcolor=nodecolor, fontcolor='#ffffff') # add edges for idx_j, sp_j in enumerate(sp_names): for idx_i, sp_i in enumerate(sp_names): mycolor = edgecolors[idx_i, idx_j] preflength = str(preflengths[idx_i, idx_j]) if connected[idx_i, idx_j]: foodwebgraph.edge(sp_i, sp_j, color=mycolor, len=preflength) foodwebgraph.render(filepath + '_graph', cleanup=True)
def graph(data): dot = Digraph(comment='Kanjis') dot.engine = 'neato' dot.format = 'svg' dot.attr(rankdir='TB', nodesep='5.0', ranksep='5.0', overlap="false") dot.attr('node', fontsize='30') allkanjis = [] for kanji in data.kanjis: if kanji in data.spotlight or random.random() < 0.1: allkanjis.append(kanji) modif = True while modif: modif = False for kanji in allkanjis: for newkanji in data.components[kanji]: if newkanji not in allkanjis: allkanjis.append(newkanji) modif = True for kanji in allkanjis: if kanji in data.radicals: continue #try: k = kanji #.decode('utf-8') label = ("" + kanji + "\n " + data.descriptions[kanji] ) #.decode('utf-8') color = data.colors[kanji] if (len(data.components[kanji]) == 0 and data.colors[kanji] != '0.6 0.8 1.0'): color = "lightgrey" if not (len(data.anticomponents[kanji]) == 0): shape = "circle" else: shape = "doublecircle" dot.node(data.descriptions[kanji], label=kanji, fillcolor=color, style='filled', shape=shape) for component in data.components[kanji]: if component not in data.radicals and component in allkanjis: source = component if component in data.descriptions: source = data.descriptions[component] dot.edge(source, data.descriptions[kanji], constraint='true') #.decode('utf-8') #except Exception: # print("encoding fial") return dot
def do_network_graph(lots_in_system, outfile): """Creates a network graph of dependencies between job cards. """ dot = Digraph(comment='Job Cards') # Generally these graphs work well if the following are excluded: exclude = ["GoodsIn", "Void"] nodes_in_system = [ l for l in lots_in_system if not (l["workstation"] in exclude) and not ("-" in str(l["lots_consumed"])) ] # See: https://www.graphviz.org/doc/info/colors.html colour_scheme = { "GoodsIn": 'darkseagreen', "LaserCutShield": 'darkseagreen1', "CutFoam": 'darkseagreen2', "CutElastic": 'darkseagreen3', "StapleElasticToShield": 'darkseagreen4', "StickFoamToShield": 'aquamarine', "QualityControlPass": '******', "QualityControlFail": 'aquamarine2', "Boxing": 'aquamarine3', "GoodsOut": 'aquamarine4' } # Format nodes for output. for node in nodes_in_system: label = "" + node["lot_no"] + "\n" + node["workstation"] + "\n" + node[ "workers"][0] if node["workstation"] in colour_scheme.keys(): dot.attr('node', style='filled', color=colour_scheme[node["workstation"]]) else: dot.attr('node', style='filled', color='white') dot.node(node["lot_no"], label) for l in reduce((lambda a, c: a + c), [[[node["lot_no"], target] for target in node["lots_consumed"]] for node in nodes_in_system]): print(l) dot.edge(l[0], l[1], "") # "neato" is another good option here. dot.engine = "sfdp" dot.attr(overlap='false') # Using splines would be easier to follow but it requires a lot of processing. #dot.attr(splines="true") dot.render(outfile + ".gv", view=True)
def graph(data): dot = Digraph(comment='Kanjis') dot.engine = 'neato' dot.format = 'svg' dot.attr(rankdir='TB', nodesep='5.0', ranksep='5.0', overlap="false") dot.attr('node', fontsize='30') kanjispresent = set() for radical in data.radicals: if radical in data.spotlight or random.random() < 0.02: kanjispresent.add(radical) for kanji in data.kanjis: if kanji in data.spotlight or random.random() < 0.02: kanjispresent.add(kanji) for kanji in data.spotlight: for component in data.components[kanji]: kanjispresent.add(component) for kanji in kanjispresent: #try: k = kanji #.decode('utf-8') description = Components.get(data.descriptions, kanji, kanji) if not (len(data.anticomponents[kanji]) == 0): dot.node(description, label=kanji, fontsize=Components.fontsize(kanji, data), fillcolor=Components.color(kanji, data), style='filled', shape=Components.shape(kanji, data)) for component in data.anticomponents[kanji]: kanjicomponode = kanji + " -> " + Components.get( data.descriptions, component, component) dot.node(kanjicomponode, label=component, fillcolor=Components.color(component, data), fontsize=Components.fontsize(component, data), style='filled', shape=Components.shape(component, data)) #if component in radicals or len(components[component]) == 0: source = Components.get(data.descriptions, component, component) dot.edge(description, kanjicomponode, constraint='true') #.decode('utf-8') #except Exception: # print("encoding fial") return dot
def generate_job_graph(network, path): from graphviz import Digraph print("Generating graph...") g = Digraph("Network") # , node_attr={'shape': 'record', 'height': '.1'}) g.engine = "circo" for job in network.jobs.values(): g.node(repr(job), fillcolor="deepskyblue1", style="filled") for pipe in PIPES.values(): g.edge(repr(pipe.source), repr(pipe.destination), f"{pipe.id}", fontcolor="crimson", style="dashed") print(f"Saving to {path}...") g.render(path) subprocess.Popen(['xdg-open', f'{path}.pdf'])
def output_graph(self): from graphviz import Digraph dot = Digraph(comment='Associados e Padawans do Garoa Hacker Clube') dot.engine = "neato" dot.attr('graph', overlap="false") # dot.attr('node', shape='circle') dot.attr('node', labelloc='c') dot.attr('node', fontsize='12') dot.attr('node', style='filled') dot.attr('node', fontcolor="#eeffee") pessoas = self.associados + self.padawans + self.ex_associados dot.attr('node', color='black') dot.node( "Pre_sistema_de_padawanice", "Primeiros associados\nantes da criação\ndo sistema\nde padawanice" ) for p in pessoas: if p.cofundador: dot.attr('node', color='black') elif p in self.ex_associados: dot.attr('node', color='gray') elif p.associacao == []: # é padawan if menos_de_6_meses(p.apresentacao): # é padawan recente dot.attr('node', color='#cccc00') else: # provavelmente é um padawan abandonado # ou com muito pouca chance de se efetivar associado dot.attr('node', color='#cc7777') else: # atualmente é associado dot.attr('node', color='#559955') nome = '\n'.join(p.nome.split()) if p.apelido: nome += '\n({})'.format(p.apelido) dot.node("Pessoa_{}".format(pessoas.index(p)), nome) for p in pessoas: if p.endosso == "HACK": dot.edge("Pre_sistema_de_padawanice", "Pessoa_{}".format(pessoas.index(p))) for padawan in p.padawans: dot.edge("Pessoa_{}".format(pessoas.index(p)), "Pessoa_{}".format(pessoas.index(padawan))) dot.render('garoa-associados', view=True) os.rename('garoa-associados', 'garoa-associados.gv')
def graph(data, name, engine=None, inv=False): g = Digraph() g.attr('graph', fontname='mono') g.attr('node', fontname='mono') g.attr('node', shape='box') if engine: g.engine = engine for next, prev in data: if inv: g.edge(next.strip(), prev.strip()) else: g.edge(prev.strip(), next.strip()) g.render("out/" + name, format="png", cleanup=True)
def graph_by_epics(self) -> None: output = self.config['output']['epics'] graph_file = output['graph'] logger.info(f"generating {graph_file}") graph = Digraph(comment = f"Generated on {self.config['generated']}", graph_attr = {'rankdir': 'LR', 'splines': 'ortho'}, node_attr = {'shape': 'none'}) for epic in self.jira.sorted_by_key(self.jira.epics.values()): self.add_node(graph, epic) for story in self.jira.sorted_by_key(epic.stories): self.add_node(graph, story) self.add_edge(graph, epic, story) for risk in self.jira.sorted_by_key(story.risks): self.add_node(graph, risk) self.add_edge(graph, story, risk) for test in self.jira.sorted_by_key(story.tests): self.add_node(graph, test) self.add_edge(graph, story, test) graph.engine = output['engine'] graph.format = output['format'] graph.render(filename = graph_file, cleanup = False, view = False)
remote_conn_pre, remote_conn = sshconnect(ip, username, password, 'ios', '') allitems[ip] = {} for tracehost in hostlist: content = ssh_runcommand(remote_conn, "traceroute " + tracehost) # print content hops = parsetraceroute(content) allitems[ip][tracehost] = hops dot = Digraph(comment='The Network') # UnDirected Graph # dot = Graph(comment='The Network') for device in allitems: dot.node(device) for entry in allitems[device]: # neighborhostname = allitems[device][entry] hop1 = device allitems[device][entry].append(entry) for hop in allitems[device][entry]: hop2 = hop dot.edge(hop1,hop2) hop1 = hop2 dot.engine = 'circo' print dot.source dot.render(filename=graphfilename)
from graphviz import Digraph import os NUM = 123 NAME = 'mod_' + str(NUM) mod = Digraph(NAME) mod.background = 'black' #Phase one: render the main mod using 'circo' engine mod.node('0', style='filled') for i in range(NUM): mod.edge(str(i), str((i + 1) % NUM), color='blue') #Save the result of the graphviz rendering command to the file 'mod.gv' mod.engine = 'circo' mod.format = 'gv' mod.render(NAME) #Phase One point Five: Do some processing to extract the positioned vertices and edges with open(NAME + '.gv') as f: circo_src = f.read() circo_src = circo_src.split('\n') #You don't want the first and last line circo_src = circo_src[1:len(circo_src) - 2] #You don't want the semicolons for i in range(len(circo_src)): circo_src[i] = circo_src[i].replace(';', '') for item in circo_src: print(item)
# so draw the edges in that direction. b2 = Bill.from_congressproject_id(rec["other"]) if bill.is_success() and not b2.is_success(): continue elif not bill.is_success() and b2.is_success(): pass else: raise ValueError() g.edge( bill.congressproject_id, rec["other"], label="%d%%" % int(round(rec["my_ratio"]*100)), ) g.engine = 'twopi' svg = g.pipe(format='svg') print(svg) elif __name__ == "__main__" and sys.argv[1] == "extract-text": print extract_text(sys.argv[2]).encode("utf8") elif __name__ == "__main__" and len(sys.argv) == 3: # Compare two bills by database numeric ID. from bill.models import * b1 = Bill.objects.get(id=sys.argv[1]) b2 = Bill.objects.get(id=sys.argv[2]) compare_bills(b1, b2) elif __name__ == "__main__":
body = re.findall("\[\[.+?\]\]", node.string, re.DOTALL) nodes[pid] = {"name": name, "body": body} # hahaha efficiency is for suckers! for key, node in nodes.iteritems(): connections = list() for link in node["body"]: for nodeKey, iNode in nodes.iteritems(): if iNode["name"] in link: connections.append(nodeKey) if len(connections) > 0: nodes[key]["links"] = connections # creating the graph dot = Digraph(name='Twine Story') dot.engine = engine dot.format = "plain" for key, node in nodes.iteritems(): dot.node(str(key), node["name"]) if "links" in node: for link in node["links"]: dot.edge(str(key), str(link)) # exporting the whole thing to twine.dot.plain dot.render('twine.dot') # modifying the twine file to have the new positions with open('twine.dot.plain') as file: for line in file: chunks = line.split() if chunks[0] == "node": pid = chunks[1]
if line[0] == '>': cur_scaffold = line.split("|")[0][1:] scaffolds[cur_scaffold] = [] elif line[0] != '\n': contig = line.split("|") scaffolds[cur_scaffold].append(contig) #Plot each scaffold in seperate svg files for key in scaffolds: print(key) print(len(scaffolds[key])) if len(scaffolds[key]) == 1: continue dot = Digraph(comment="SSPACE assembly", format='svg') dot.body.extend(['rankdir=LR', 'size="6,6"']) dot.engine = 'neato' dot.attr('node', shape='circle') edge_list = [] links_list = [] label_list = [] prev_node = None i = 0 for contigs in scaffolds[key]: dot.node(contigs[0] + str(i), label=contigs[0] + '\n' + contigs[1][4:]) label_list.append(contigs[0]) cur_node = contigs[0] + str(i) if prev_node is None: prev_node = contigs[0] + str(i) links = contigs[2][5:] links_list.append(links)
from os import environ from graphviz import Digraph from extradata import ExtraData, CollisionMeta from utils import filename_from_argv fn = filename_from_argv() ed = ExtraData.load(fn) dot = Digraph(comment='Collisions') dot.engine = "neato" if dot.engine == "neato": dot.attr("graph", overlap="false") interacting_objects = set() for merged, originals in ed.tree.get_tree().items(): first_parent = True for parent in originals["parents"]: meta: CollisionMeta = originals["meta"] water_ret = meta.water_retention mantle_ret = meta.mantle_retention core_ret = meta.core_retention if first_parent: label = f"{water_ret:.2f}/{mantle_ret:.2f}/{core_ret:.2f}" first_parent = False else: label = None dot.edge(str(parent), str(merged), xlabel=label)
def optimize(): # This is somewhat complex with many cases, pylint: disable=R0912 # We maintain this globally to make it accessible, pylint: disable=W0603 global graph if Options.shouldCreateGraph(): try: from graphviz import Digraph # pylint: disable=F0401,I0021 graph = Digraph('G') except ImportError: warning("Cannot import graphviz module, no graphing capability.") while True: finished = True ModuleRegistry.startTraversal() while True: current_module = ModuleRegistry.nextModule() if current_module is None: break if _progress: printLine( """\ Optimizing module '{module_name}', {remaining:d} more modules to go \ after that. Memory usage {memory}:""".format( module_name = current_module.getFullName(), remaining = ModuleRegistry.remainingCount(), memory = MemoryUsage.getHumanReadableProcessMemoryUsage() ) ) if current_module.isPythonShlibModule(): optimizeShlibModule(current_module) else: changed = optimizePythonModule(current_module) if changed: finished = False # Unregister collection traces from now unused code. for current_module in ModuleRegistry.getDoneModules(): if not current_module.isPythonShlibModule(): for function in current_module.getUnusedFunctions(): VariableRegistry.updateFromCollection( old_collection = function.constraint_collection, new_collection = None ) function.constraint_collection = None if VariableRegistry.considerCompletion(): finished = False for current_module in ModuleRegistry.getDoneModules(): if not current_module.isPythonShlibModule(): optimizeVariables(current_module) if finished: break if graph is not None: graph.engine = "dot" graph.graph_attr["rankdir"] = "TB" graph.render("something.dot") printLine(graph.source)
for item in ignore_list: links.pop(item) class_names.remove(item) fields.pop(item) dot = Digraph(comment='Reviewer') dot.attr("node", shape="ellipse") dot.attr(overlap='false') for cls, field_list in fields.items(): label = cls for field in field_list: label += r"\n" + field dot.node(cls, label) for main, refs in links.items(): for r in refs: dot.edge(main, r) #dot.attr("node", shape="rectangle") #dot.node("legend", r"* - required\n? - allow blank") dot.engine = "dot" dot.format = "svg" dot.render('../db_model/drawer_output/schema', view=False) dot.format = "png" dot.render('../db_model/drawer_output/schema', view=False) # for eng in ENGINES: # dot.engine=eng # dot.render('test-output/schema_'+eng, view=True)
from graphviz import Digraph import pydot import os import pdb # root_dir = os.getcwd() root_dir = '/home/avi/REPO/mydocs/docs' print(root_dir) dot = Digraph(comment='The Round Table', filename='cluster.dot') dot.format = 'svg' dot.engine = 'circo' # dot.engine = 'neato' dot.node_attr.update(style='filled', colorscheme='paired12') # dot.node('A', color="1") # dot.node('B', color="2") # dot.node('L', 'Gallahad', color="3") # dot.edge('A', 'B') # dot.edge('A', 'L') # dot.edge('B', 'L') counter = 1 counter_stop = 12 nodes = [] def increment(): global counter
for sig in dev['signals']: n_sig = n_sig+1 if sig['observed_device_name'] == 'FIXED_VALUE': cmder = dev['name'] if 'cmd_field_name' in sig: field = sig['cmd_field_name'] else: field = str(n_sig) val = str(sig['fixed_value']) from_node_str = cmder+'_'+field dot.node(from_node_str, label=val) #label_str = from_node_str + " = " + val label_str = '' to_node_str = dev['name'] + ':' + field elif dev['device_class'] == 'Commander': from_node_str = sig['observed_device_name'] + ':' + sig['request_signal_name'] label_str = sig['request_signal_name'] to_node_str = dev['name'] + ':' + sig['cmd_field_name'] else: from_node_str = sig['observed_device_name'] + ':' + sig['request_signal_name'] label_str = sig['request_signal_name'] to_node_str = dev['name'] + ':' + dev['name'] print('from: %s; to: %s' % (from_node_str, to_node_str)) dot.edge(from_node_str, to_node_str, label=label_str) dot.engine = 'dot' print(dot.source) dot.render('fcviz_out.png', view=True)
i = 0 for host in ips: if ping(host) == 'up': graph.node(host, hostnames[i], style="filled", fillcolor="#00ff00") graph.edge(host, 'OpenWRT', constraint='false') else: graph.node(host, hostnames[i], style="filled", fillcolor="#ff0000") graph.edge(host, 'OpenWRT', constraint='false') i = i + 1 #custom edges for static router entry graph.edge('OpenWRT', finalresultarr[1].upper(), constraint='false') graph.edge('OpenWRT', finalresultarr2[1].upper(), constraint='false') graph.edge('OpenWRT', 'Indra', constraint='false') graph.edge('Indra', 'Indra Gateway', constraint='false') graph.edge('Indra Gateway', 'Internet', constraint='false') graph.edge('Indra', '10.0.1.3', constraint='false') graph.edge('10.0.1.3', 'Indra Gateway', constraint='false') graph.edge('VPS', '10.0.1.3', constraint='false') graph.edge('VPS', 'Internet', constraint='false') graph.edge('Internet', 'VPS', constraint='false') graph.edge('10.0.1.3', 'VPS', constraint='false') graph.edge('WAN', 'Internet', constraint='false') graph.edge('WWAN', 'Internet', constraint='false') #set format png and generate diagram, general graph settings graph.format = 'png' graph.node_attr['shape']='box' graph.engine = 'circo' graph.render('graph', view=False)
# so draw the edges in that direction. b2 = Bill.from_congressproject_id(rec["other"]) if bill.is_success() and not b2.is_success(): continue elif not bill.is_success() and b2.is_success(): pass else: raise ValueError() g.edge( bill.congressproject_id, rec["other"], label="%d%%" % int(round(rec["my_ratio"] * 100)), ) g.engine = 'twopi' svg = g.pipe(format='svg') print(svg) elif __name__ == "__main__" and sys.argv[1] == "extract-text": print extract_text(sys.argv[2]).encode("utf8") elif __name__ == "__main__" and len(sys.argv) == 3: # Compare two bills by database numeric ID. from bill.models import * b1 = Bill.objects.get(id=sys.argv[1]) b2 = Bill.objects.get(id=sys.argv[2]) compare_bills(b1, b2) elif __name__ == "__main__": # Look at all enacted bills that had a companion.
def optimize(): # This is somewhat complex with many cases, pylint: disable=R0912 # We maintain this globally to make it accessible, pylint: disable=W0603 global graph if Options.shouldCreateGraph(): try: from graphviz import Digraph # pylint: disable=F0401,I0021 graph = Digraph('G') except ImportError: warning("Cannot import graphviz module, no graphing capability.") while True: finished = True ModuleRegistry.startTraversal() while True: current_module = ModuleRegistry.nextModule() if current_module is None: break if _progress: printLine("""\ Optimizing module '{module_name}', {remaining:d} more modules to go \ after that. Memory usage {memory}:""".format( module_name=current_module.getFullName(), remaining=ModuleRegistry.remainingCount(), memory=Utils.getHumanReadableProcessMemoryUsage())) if current_module.isPythonShlibModule(): optimizeShlibModule(current_module) else: changed = optimizePythonModule(current_module) if changed: finished = False # Unregister collection traces from now unused code. for current_module in ModuleRegistry.getDoneModules(): if not current_module.isPythonShlibModule(): for function in current_module.getUnusedFunctions(): VariableRegistry.updateFromCollection( old_collection=function.constraint_collection, new_collection=None) function.constraint_collection = None if not VariableRegistry.complete: VariableRegistry.complete = True finished = False for current_module in ModuleRegistry.getDoneModules(): if not current_module.isPythonShlibModule(): optimizeVariables(current_module) if finished: break if graph is not None: graph.engine = "dot" graph.graph_attr["rankdir"] = "TB" graph.render("something.dot") printLine(graph.source)
# parse the scaffold evidence file. path = './test_112/scaffold_evidence.txt' with open(path, 'r') as scaffold_evidence: scaffolds = {} for line in scaffold_evidence: if line[0] == '>': cur_scaffold = line.split("|")[0][1:] scaffolds[cur_scaffold] = [] elif line[0] != '\n': contig = line.split("|") scaffolds[cur_scaffold].append(contig) dot = Digraph(comment="SSPACE assembly", format='svg') dot.body.extend(['rankdir=LR', 'size="6,6"']) dot.engine = 'neato' # dot.node_attr.update(color='lightblue2', style='filled') dot.attr('node', shape='circle') edge_list = [] links_list = [] label_list = [] prev_node = None for contigs in scaffolds['scaffold1']: dot.node(contigs[0], label = contigs[0] + '\n' + contigs[1][4:]) label_list.append(contigs[0]) cur_node = contigs[0] if prev_node is None: prev_node = contigs[0] links = contigs[2][5:] links_list.append(links)