我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pygraphviz.AGraph()。
def graphviz(elem, doc): if type(elem) == CodeBlock and 'graphviz' in elem.classes: code = elem.text caption = "caption" G = pygraphviz.AGraph(string=code) G.layout() filename = sha1(code) filetype = {'html': 'png', 'latex': 'pdf'}.get(doc.format, 'png') alt = Str(caption) src = imagedir + '/' + filename + '.' + filetype if not os.path.isfile(src): try: os.mkdir(imagedir) sys.stderr.write('Created directory ' + imagedir + '\n') except OSError: pass G.draw(src) sys.stderr.write('Created image ' + src + '\n') return Para(Image(alt, url=source, title=''))
def __init__(self, _parser, _lst_obj_ast, is_dominator=True): self._parser = _parser self._lst_obj_ast = _lst_obj_ast self._name = os.path.split(_parser.working_path)[1] self.is_dominator = is_dominator if is_dominator: self.file_path = os.path.join(_parser.graph_path, self._name + ".dom.dot") self.file_path_svg = os.path.join(_parser.graph_path, self._name + ".dom.dot.svgz") self._cfg_name = "DOMINATOR " + self._name self.stmt_ref = statement.ref_stmt["dominator"] else: self.file_path = os.path.join(_parser.graph_path, self._name + ".post_dom.dot") self.file_path_svg = os.path.join(_parser.graph_path, self._name + ".post_dom.dot.svgz") self._cfg_name = "POST-DOMINATOR " + self._name self.stmt_ref = statement.ref_stmt["post_dominator"] self.g = pgv.AGraph(name=self._cfg_name, directed=True)
def get_graph(self, title=None): """ Generate a DOT graph with pygraphviz, returns an AGraph object Args: title (string): Optional title for the graph. """ if not pgv: raise Exception('AGraph diagram requires pygraphviz') if title is None: title = self.__class__.__name__ elif title is False: title = '' fsm_graph = pgv.AGraph(label=title, compound=True, **self.machine_attributes) fsm_graph.node_attr.update(self.style_attributes['node']['default']) # For each state, draw a circle self._add_nodes(self.machine.states, fsm_graph) self._add_edges(self.machine.events, fsm_graph) setattr(fsm_graph, 'style_attributes', self.style_attributes) return fsm_graph
def plot_similarity_graph(self, show_edges=False): '''(trial) visualize similarity using GraphViz''' g = pygraphviz.AGraph(directed=False, overlap='scale', splines=True) g.node_attr['shape'] = 'plaintext' g.node_attr['fontsize'] = '12' if show_edges: g.edge_attr['color'] = 'lightgrey' g.edge_attr['fontcolor'] = 'grey' g.edge_attr['fontsize'] = '8' else: g.edge_attr['style'] = 'invis' for crawl1 in sorted(self.similarity['url']): for crawl2 in sorted(self.similarity['url'][crawl1]): similarity = self.similarity['url'][crawl1][crawl2] distance = 1.0 - similarity g.add_edge(MonthlyCrawl.short_name(crawl1), MonthlyCrawl.short_name(crawl2), len=(distance), label='{0:.2f}'.format(distance)) g.write(os.path.join(PLOTDIR, 'crawlsimilarity_url.dot')) g.draw(os.path.join(PLOTDIR, 'crawlsimilarity_url.svg'), prog='fdp')
def graphviz(self, root_id=None): g = pgv.AGraph(directed='True') # Breadth-first traversal from root visited_ids = Set() curr_id = root_id q = Queue() q.put(curr_id) while not q.empty(): curr_id = q.get() visited_ids.add(curr_id) for sub_id in self.id_to_term[curr_id].inv_is_a(): if not sub_id in visited_ids: g.add_edge(self.id_to_term[curr_id].name, self.id_to_term[sub_id].name) q.put(sub_id) print str(g)
def layout(self, prog='dot', factor=8, offset=0): """Use GraphViz to auto-layout modules.""" if pgv is not None: g = pgv.AGraph(self.graph(), directed=True, strict=False) g.layout(prog=prog) for node in g.nodes(): x, y = node.attr['pos'].split(',') x, y = int(float(x)), int(float(y)) idx = int(node) mod = self.modules[idx] if isinstance(factor, int): xfactor, yfactor = factor, factor else: xfactor, yfactor = factor if isinstance(offset, int): xoffset, yoffset = offset, offset else: xoffset, yoffset = offset mod.x = x * xfactor + xoffset mod.y = y * yfactor + yoffset return True else: logging.warning('GraphViz not available; could not auto-layout.') return False
def visualize(graph, output_path="a.png"): """visualize(graph, **kwargs) -> None Graph/Merger graph -> the graph/Merger that will be visualized string output_path-> the output path of the image """ if isinstance(graph, Merger): graph = Merger.G G = pgv.AGraph(directed=graph.directed) G.add_nodes_from([i for i in xrange(1, len(graph.edges))]) for edge in graph.iterate_edges(): G.add_edge(edge.start, edge.end, label=edge.weight) G.node_attr['shape'] = 'egg' G.node_attr['width'] = '0.25' G.node_attr['height'] = '0.25' G.edge_attr['arrowhead'] = 'open' G.layout(prog='dot') G.draw(output_path)
def main(): for gate_name, gate_f in ( ("nor", lambda a, b: not (a or b)), ("nand", lambda a, b: not (a and b)) ): for in1, in2 in ((False, False), (False, True), (True, True)): result = gate_f(in1, in2) g = pgv.AGraph(directed=True) g.add_node("in1", label=str(in1).upper(), **params[in1]) g.add_node("in2", label=str(in2).upper(), **params[in2]) g.add_node("gate", label="{}\n{}".format(gate_name, str(result).upper()), **params[result]) g.add_node("result", style="invis") g.add_edge("in1", "gate", **params[in1]) g.add_edge("in2", "gate", **params[in2]) g.add_edge("gate", "result", **params[result]) g.layout(prog='dot') g.draw("logic_example_autogen_{}_{}_{}.pdf".format(gate_name, in1, in2))
def __init__(self, seed, enabled=True): self.enabled = enabled if self.enabled: import pygraphviz as pgv self.file = FuzzerConfiguration().argument_values['work_dir'] + "/graph.dot" self.dot = pgv.AGraph(directed=True, strict=True) self.dot.graph_attr['epsilon'] = '0.0008' self.dot.graph_attr['defaultdist'] = '2' self.dot.write(self.file) for data in seed: self.dot.add_edge(None, str(data))
def processLines(self): if len(self.lines) == 0: return self.identifier = self.lines[0][2:] s = '\n'.join(self.lines) A = AGraph() G = A.from_string(s) self.processGraph(G)
def _render(self, costs=False, word_probs=False, highlight_best=False): from pygraphviz import AGraph graph = AGraph(directed=True) for node_id, node_label in self.nodes.iteritems(): attributes = self._node_attr(node_id, costs=costs, word_probs=word_probs) graph.add_node(node_id, **attributes) for (parent_node_id, child_node_id) in self.edges: graph.add_edge(parent_node_id, child_node_id) self.graph = graph if highlight_best: self._highlight_best()
def draw(self, nth=None): if self.get_root() is None: with open("test_dot.dot", "w") as dfile: dfile.write("strict digraph {\n\tnode [shape = record,height=.1];\n}") pgv.AGraph("test_dot.dot").draw(self.file_path, prog="dot", format="png") else: code = lambda x: "n" + str(abs(x)) if x < 0 else "p" + str(abs(x)) self.graph = {} self.get_graph(self.get_root()) dfile = open("test_dot.dot", "w") dfile.write("strict digraph {\n\tnode [shape = record,height=.1];\n") for key in self.graph: if nth is not None and nth == key: dfile.write( "\tnode{0} [label = \"<f0> |<f1> {1}|<f2> \"] [style=filled ,fillcolor = green];\n".format( code(key), key)) else: dfile.write("\tnode{0} [label = \"<f0> |<f1> {1}|<f2> \"];\n".format(code(key), key)) for key in self.graph: for value in self.graph[key]: dfile.write("\t\"node{0}\":{1}->\"node{2}\":f1;\n".format(code(key), "f0" if self.graph[key][value]['child_status'] == 'left' else "f2", code(value))) dfile.write("}") dfile.close() pgv.AGraph("test_dot.dot").draw(self.file_path, prog="dot", format="png")
def load_automata(path): graph_file = open(path, 'ro'); G = pgv.AGraph("".join(graph_file.readlines())) graph_file.close() return G
def transform(): graph = pgv.AGraph(directed=True, strict=True) with open("test.json", "r") as f: json_data = json.loads(f.read()) # print(json.dumps(json_data, indent=2)) travel_json(json_data, graph) # A.add_edge(1, 2) print(graph.string()) graph.layout('dot') graph.draw('test.png')
def graphviz(key, value, format, meta): if key == 'CodeBlock': [[ident, classes, keyvals], code] = value caption = "caption" if "graphviz" in classes: G = pygraphviz.AGraph(string=code) layout = "dot" for elem in keyvals: if elem[0] == "layout": layout = elem[1] G.layout(layout) filename = sha1(code) if format == "html": filetype = "png" elif format == "latex": filetype = "png" else: filetype = "png" alt = Str(caption) src = imagedir + '/' + filename + '.' + filetype if not os.path.isfile(src): try: os.mkdir(imagedir) except OSError: pass G.draw(src) out(src) tit = "" return Para([Image(['', [], []], [alt], [src, tit])])
def get_graph(string): """ Create a graph from a DOT string """ dot = pg.AGraph(string) return nx.drawing.nx_agraph.from_agraph(dot)
def to_dot(self, filename, edges): from pygraphviz import AGraph dot = AGraph(directed=True) for n in edges.keys(): dot.add_node(str(n)) if lib.qcgc_arena_get_blocktype(ffi.cast("cell_t *", n)) not in [ lib.BLOCK_BLACK, lib.BLOCK_WHITE]: node = dot.get_node(str(n)) node.attr['color'] = 'red' for n in edges.keys(): if edges[n] is not None: dot.add_edge(str(n), str(edges[n])) dot.layout(prog='dot') dot.draw(filename)
def generate_process_flowchart(process): file_template = """ strict digraph { rankdir=TB; graph [ratio="auto" label="{{ name }}" labelloc=t ]; node [shape = ellipse]; { node [shape=diamond label="Router"]; {% for node in router_nodes %} {{ node.name }}; {% endfor %} } edge [fontsize=14] {% for transition in transitions %} "{{ transition.input_node.name }}" -> "{{ transition.output_node.name }}" [label="{{ transition.name }} {% if transition.get_condition_descn %}: {% endif %} {{ transition.get_condition_descn }}"] ; {% endfor %} } """ # NOQA transitions = process.transition_set.all() router_nodes = process.node_set.filter(node_type='router') request = Context( { 'name': process.name, 'router_nodes': router_nodes, 'transitions': transitions } ) t = Template(file_template) G = pgv.AGraph(string=t.render(request)) return G
def node_data_call_back(self,nodeDataArray): graph = pygr.AGraph() show_name = self.show_node_name for node in nodeDataArray.nodes: my_color,my_shape = self.read_attributes(node) my_label = node.myName + "\n" + "("+node.myType+")" if node.myStatus != 3 \ or self.draw_all_nodes == True \ or node.myName == show_name \ or node.parentName == show_name: # avoid an overwrinting of inactive node on an active node if graph.has_node(node.myName) == False \ or node.myStatus != 3: graph.add_node(node.myName, style="filled", fillcolor=my_color, shape=my_shape, label=my_label) graph.add_edge(node.myName,node.parentName) dot_string = graph.to_string() # use same sentences to correct centering if self.centering == True: self._widget.xdot_widget.set_dotcode(dot_string, center=True) self.centering = False else: self._widget.xdot_widget.set_dotcode(dot_string, center=False)
def graphviz(key, value, format, meta): if key == 'CodeBlock': [[ident, classes, keyvals], code] = value caption = "caption" if "graphviz" in classes: G = pygraphviz.AGraph(string=code) G.layout() filename = sha1(code) if format == "html": filetype = "png" elif format == "latex": filetype = "pdf" else: filetype = "png" alt = Str(caption) src = imagedir + '/' + filename + '.' + filetype if not os.path.isfile(src): try: os.mkdir(imagedir) sys.stderr.write('Created directory ' + imagedir + '\n') except OSError: pass G.draw(src) sys.stderr.write('Created image ' + src + '\n') tit = "" return Para([Image(['', [], []], [alt], [src, tit])])
def draw_graph(digraph): def name(p): return "%r" % p G = pgz.AGraph(directed=True) for x in digraph: for y in digraph.parent_nodes(x): G.add_edge(name(y), name(x)) G.layout('dot') G.draw("ewrap.png")
def __init__(self, _parser, _lst_obj_ast): self._parser = _parser self._lst_obj_ast = _lst_obj_ast self._name = os.path.split(_parser.working_path)[1] self.file_path = os.path.join(_parser.graph_path, self._name + ".dot") self._cfg_name = "CFG " + self._name self.g = pgv.AGraph(name=self._cfg_name, directed=True)
def __init__(self, _parser, _lst_obj_ast): self._parser = _parser self._lst_obj_ast = _lst_obj_ast self._name = os.path.split(_parser.working_path)[1] self.file_path = os.path.join(_parser.graph_path, self._name + ".dot") self._uml_name = "UML " + self._name file_path = os.path.join(_parser.graph_path, self._uml_name) self.g = pgv.AGraph(name=file_path, directed=True)
def visualization(metadata, filename): print "--- VISUALIZATION ---" g = graph.AGraph(directed=True) for k, v in metadata.items(): for x in xrange(len(v)): node, zf = v[x].split('^') g.add_edge(k, node, len="2.1", label=zf, rankdir="LR") filename = os.path.basename(filename) g.layout(prog='dot') picture = "%s-%s.png" % (filename, "image") print "[+] Generating %s" % picture g.draw(picture)
def visualization(metadata, filename): print "--- VISUALIZATION ---" g = graph.AGraph(directed=True) for k, v in metadata.items(): for x in xrange(len(v)): node, zf = v[x].split('^') g.add_edge(k, node, len="2.1", label=zf, rankdir="LR") #print "adding %s -> %s" % (k, node) filename = os.path.basename(filename) g.layout(prog='dot') picture = "%s-%s.png" % (filename, "image") print "[+] Generating %s" % picture g.draw(picture)
def execute(self, *args, **kwargs): try: import pygraphviz as pgv except ImportError: print "This command requires pygraphviz" return if len(args) == 0: resources = ResourceQuery().get_all_resources() else: resources = [] def iterate(record): res = record.to_resource() resources.append(res) for p in record.parents.all(): p_res = iterate(p) res._parents.append(p_res) return res start_id = int(args[0]) start_record = StorageResourceRecord.objects.get(pk = start_id) iterate(start_record) G = pgv.AGraph(directed=True) for r in resources: G.add_node(r._handle, label="%s:%s:%s" % (r._handle, r._meta.label, r.get_label())) for r in resources: for p in r.get_parents(): G.add_edge(r._handle, p._handle) G.layout(prog='dot') output_file = 'resources.png' G.draw(output_file) print "Wrote graph to %s" % output_file
def __init__(self, *args, **kwargs): self.seen = [] super(AGraph, self).__init__(*args, **kwargs)
def get_graph(self, title=None, force_new=False): if title is None: title = self.title if not hasattr(self, 'graph') or force_new: self.graph = AGraph(self).get_graph(title) return self.graph
def graphviz_export(self, filename, dpi = 300): import pygraphviz as pgv G = pgv.AGraph(directed=True) G.node_attr['shape'] = 'box' # G.graph_attr['size'] = '2!,2!' # use for animations only # G.graph_attr['dpi'] = str(dpi) parent = self.root G.add_node(str(parent)) S = [] while parent.is_feature or len(S) > 0: if parent.is_feature: S.append(parent) child = parent.l label = 'T' else: parent = S.pop() child = parent.r label = 'F' G.add_node(str(child)) G.add_edge(str(parent), str(child), label=label) parent = child G.layout(prog='dot') G.draw(filename)
def output_clustered_graph(graph, name, clustering): """Will ommit edge labels """ # Create AGraph via networkx G = nx.DiGraph() G.add_nodes_from(graph.nodes()) G.add_edges_from(graph.edges()) A = to_agraph(G) tableau20 = [ '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5' ] clist = [ tableau20[i*2] for i in range(0, len(tableau20)/2)] i = 0 for c in clustering: A.add_subgraph(c, name='cluster_%d' % i, color=clist[i % len(clist)]) i += 1 name = 'graphs/%s.png' % name A.write(name + '.dot') A.draw(name, prog="dot")
def _profile_from_parser( parser, graph_filename=DEFAULT_GRAPH_FILENAME, node_threshold=DEFAULT_NODE_THRESHOLD, edge_threshold=DEFAULT_EDGE_THRESHOLD, view=DEFAULT_VIEW, colour_nodes_by_selftime=DEFAULT_COLOUR_NODES_BY_SELFTIME): # Parse pstats and prune graph based on thresholds profile = parser.parse() profile.prune( node_threshold, edge_threshold, colour_nodes_by_selftime=colour_nodes_by_selftime) # Convert graph to dot format dot_file = StringIO() dot = gprof2dot.DotWriter(dot_file) dot.graph(profile, theme=gprof2dot.themes['color']) # Convert dot to image graph = pygraphviz.AGraph(string=dot_file.getvalue()) graph.draw(graph_filename, prog='dot') # Open image if view: _view_file(graph_filename)
def buildGraph(tn,entityname): A=pgv.AGraph(directed=True,strict=True) entities=tn.Entities; entity= entities[entityname]; nodes={}; addNode(A,entity,nodes); A.graph_attr['epsilon']='0.001' print (A.string()) # print dot file to standard output A.write('foo.dot') A.layout('dot') # layout with dot A.draw('foo.png') # write to file
def draw_binary_tree(Tree, correlation, c='none'): A = pg.AGraph(directed=True, strict=True) level = 0 queue = [Tree.tree] while queue: node = queue.pop(0) #node_string = str(node.label) + '\n' + str(Tree.generate_bt_stats(node)) node_string = str(node.ground_truth) + '\n' + str(Tree.generate_bt_stats(node)) level += 1 if node.get_left() is not None: queue.append(node.get_left()) child_string = str(node.get_left().ground_truth) + '\n' + str(Tree.generate_bt_stats(node.get_left())) A.add_edge(node_string, child_string) if node.get_right() is not None: queue.append(node.get_right()) child_string = str(node.get_right().ground_truth) + '\n' + str(Tree.generate_bt_stats(node.get_right())) A.add_edge(node_string, child_string) if level >= cfg.max_tree_size: break dot_path = util.generate_meta_path(Tree.system_name, 'dot', c) util.ensure_path_exists(dot_path) A.write('{}{} BT.dot'.format(dot_path, Tree.system_name)) A.layout(prog='dot') A.draw('{}{} BT Score={}.png'.format(dot_path, Tree.system_name, correlation)) print "[clustering] : Created n-ary tree at path {}.".format('{}{} BT Score={}.png'.format(dot_path, Tree.system_name, correlation))
def generate_dot(fab_dims, CLBs, CBr, CBb, SB, paths, filename): G = pgv.AGraph(name=filename, directed=True) #G.node_attr['fixedsize']='true' G.node_attr['shape'] = 'box' create_all_CLBs(fab_dims, CLBs, G) for cb in CBr: pos, name = parse_name(cb, (__bias_amount,0)) G.add_node(name) n = G.get_node(name) n.attr['pos'] = '{},{}!'.format(__scale_factor*pos[0], __scale_factor*pos[1]) for cb in CBb: pos, name = parse_name(cb, (0,__bias_amount)) G.add_node(name) n = G.get_node(name) n.attr['pos'] = '{},{}!'.format(__scale_factor*pos[0], __scale_factor*pos[1]) for s in SB: pos, name = parse_name(s, (__bias_amount,__bias_amount)) G.add_node(name) n = G.get_node(name) n.attr['pos'] = '{},{}!'.format(__scale_factor*pos[0], __scale_factor*pos[1]) #now make connections for path in paths: for i in range(0, len(path)-1): if len(path[i]) > __cutoff: n1 = path[i][0:__cutoff+1] else: n1 = path[i] if len(path[i+1]) > __cutoff: n2 = path[i+1][0:__cutoff+1] else: n2 = path[i+1] G.add_edge(n1, n2) #write to file G.write(filename)
def from_file(file_name): return from_graph(pg.AGraph(file_name))
def graphviz(self, root_id=None): g = pgv.AGraph(directed='True') for o_node in self.ontology_term_nodes: g.add_node(o_node.term_id, shape='polygon') #g.add_edge(self.id_to_term[curr_id].name, self.id_to_term[sub_id].name) return str(g)
def dict_to_dot(dict_G, name=''): dict_G = dict(dict_G) name = str(name) nodes = dict_G.keys() G = pgv.AGraph(name=name, label=name, strict=False, directed=True, rankdir="LR") x_dim, y_dim = 0.1, 0.1 tail,adir,ahlen = 'dot','both',0.62 arc_descriptor_shape = 'plain' node_shape = 'egg' arc_shape = 'plain' arc_arrow_head = 'normal' arc_arrow_tail = 'dot' arc_mid = 'none' arc_dir = 'both' for node in nodes: G.add_node(node.uid,label=node_to_label(node)) arcs = dict_G[node] for arc in arcs: arc_id = arc_to_id(arc) G.add_node(arc_id,shape=arc_descriptor_shape,label=arc_to_label(arc),width=x_dim,height=y_dim) G.add_edge(node.uid,arc_id,len=ahlen,dir=arc_dir,arrowtail=arc_arrow_tail,arrowhead=arc_mid) G.add_edge(arc_id,arc.toNode.uid,shape=arc_shape,arrowtail=arc_mid,arrowhead=arc_arrow_head) return G
def dot_to_file(dot_G, name='out', env='./env'): G = dot_G.copy() env = os.path.abspath(env) env_dot = os.path.join(env,'dot') env_img = os.path.join(env,'img') layout_prog = 'dot' dot_suffix = 'dot' img_suffix = 'png' dot_G.graph_attr.update(name = name) dot_G.graph_attr.update(label = name) if (debug): # print to screen print(G.string()) if not os.path.exists(env_dot): os.makedirs(env_dot) if not os.path.exists(env_img): os.makedirs(env_img) G.layout(prog=layout_prog) dot_fname = os.path.join(env_dot, name +'.' + str(dot_suffix)) img_fname = os.path.join(env_img, name + '.' + str(img_suffix)) G.write(dot_fname) if (debug): print("Wrote " + str(dot_fname)) # create a new graph from file G = pgv.AGraph(dot_fname) G.layout(prog=layout_prog) G.draw(img_fname) if(debug): print("Wrote " + str(img_fname))
def build_with_parents(self, envos=None): """Given a list of ENVO terms, build a simple network with all the keys and all the parents.""" # Testing mode # if envos is None: envos = onotology.test_envos # New graph # g = pygraphviz.AGraph(directed=True) # Main loop # for e in envos: g.add_node(e) # Return # return g
def print_tree(self, node = None): if node is None: #????? import pygraphviz self.printer = pygraphviz.AGraph(directed = True, strict = False) #???? self.printer.node_attr['shape'] = 'circle' self.printer.node_attr['color'] = 'red' self.printer.node_attr['fontcolor'] = 'white' self.printer.node_attr['style'] = 'filled' #????? node = self.tree self.printer.add_node(node.data, color = node.colour) if node.Lchild or node.Rchild: if node.Lchild: #????????????????? self.printer.add_node(node.Lchild.data, color = node.Lchild.colour) #????? self.printer.add_edge(node.data, node.Lchild.data, label = str(node.Lchild.father)) #????? self.print_tree(node.Lchild) else: #????????????? self.printer.add_node('Lchild ' + str(node.data), style = 'invis') self.printer.add_edge(node.data, 'Lchild ' + str(node.data), style = 'invis') if node.Rchild: #????????????????? self.printer.add_node(node.Rchild.data, color = node.Rchild.colour) #????? self.printer.add_edge(node.data, node.Rchild.data, label = str(node.Rchild.father)) #????? self.print_tree(node.Rchild) else: #????????????? self.printer.add_node('Rchild ' + str(node.data), style = 'invis') self.printer.add_edge(node.data, 'Rchild ' + str(node.data), style = 'invis')
def main(): with open(GATE_FILE, "rb") as f: gates_per_config = pickle.load(f) for config_number, config in enumerate(configs): gates = gates_per_config[config_number] g = pgv.AGraph(directed=True) for gate in gates: gate.put_to_graph(g) g.layout(prog='dot') g.draw("wires_autogen_{}.pdf".format(config_number))
def __init__(self): super(GraphvizWalker, self).__init__() self.top_graph = pgv.AGraph(directed=True, rankdir='LR', packMode='clust', splines='true' ) self.stack = [self.top_graph] self.node_count = 0
def bg_graph_model(): graph = pgv.AGraph(layout='dot', directed=True, strict=False, rankdir='LR') subgraphs = dict() for tablename in db.tables: if hasattr(db[tablename],'_meta_graphmodel'): meta_graphmodel = db[tablename]._meta_graphmodel else: meta_graphmodel = dict(group=request.application, color='#ECECEC') group = meta_graphmodel['group'].replace(' ', '') if group not in subgraphs: subgraphs[group] = dict(meta=meta_graphmodel, tables=[]) subgraphs[group]['tables'].append(tablename) graph.add_node(tablename, name=tablename, shape='plaintext', label=table_template(tablename)) for n, key in enumerate(subgraphs.iterkeys()): graph.subgraph(nbunch=subgraphs[key]['tables'], name='cluster%d' % n, style='filled', color=subgraphs[key]['meta']['color'], label=subgraphs[key]['meta']['group']) for tablename in db.tables: for field in db[tablename]: f_type = field.type if isinstance(f_type,str) and ( f_type.startswith('reference') or f_type.startswith('list:reference')): referenced_table = f_type.split()[1].split('.')[0] n1 = graph.get_node(tablename) n2 = graph.get_node(referenced_table) graph.add_edge(n1, n2, color="#4C4C4C", label='') graph.layout() if not request.args: response.headers['Content-Type'] = 'image/png' return graph.draw(format='png', prog='dot') else: response.headers['Content-Disposition']='attachment;filename=graph.%s'%request.args(0) if request.args(0) == 'dot': return graph.string() else: return graph.draw(format=request.args(0), prog='dot')