我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pydot.Dot()。
def draw(self, name, dname, draw_branches=True): from pydot import Dot, Edge g = Dot() g.set_node_defaults(color='lightgray', style='filled', shape='box', fontname='Courier', fontsize='10') for node in sorted(self.nodes, key=lambda x: x.num): if draw_branches and node.type.is_cond: g.add_edge(Edge(str(node), str(node.true), color='green')) g.add_edge(Edge(str(node), str(node.false), color='red')) else: for suc in self.sucs(node): g.add_edge(Edge(str(node), str(suc), color='blue')) for except_node in self.catch_edges.get(node, []): g.add_edge(Edge(str(node), str(except_node), color='black', style='dashed')) g.write_png('%s/%s.png' % (dname, name))
def execute(cls, ids, data): import pydot pool = Pool() Model = pool.get('ir.model') ActionReport = pool.get('ir.action.report') if not data['filter']: filter = None else: filter = re.compile(data['filter'], re.VERBOSE) action_report_ids = ActionReport.search([ ('report_name', '=', cls.__name__) ]) if not action_report_ids: raise Exception('Error', 'Report (%s) not find!' % cls.__name__) action_report = ActionReport(action_report_ids[0]) models = Model.browse(ids) graph = pydot.Dot(fontsize="8") graph.set('center', '1') graph.set('ratio', 'auto') cls.fill_graph(models, graph, level=data['level'], filter=filter) data = graph.create(prog='dot', format='png') return ('png', fields.Binary.cast(data), False, action_report.name)
def debugPlot(self, outfile): graph = pydot.Dot(graph_type='digraph') nodes = dict() for layerCfg in self.layerCfgs: node = pydot.Node(layerCfg.name) graph.add_node(node) nodes[layerCfg.name] = node for inp in layerCfg._inputs: if isinstance(inp,int): node = pydot.Node("input[{}]".format(inp)) graph.add_node(node) nodes[str(inp)] = node for layerCfg in self.layerCfgs: for inp in layerCfg._inputs: if isinstance(inp,int): inp = str(inp) edge = pydot.Edge(nodes[inp],nodes[layerCfg.name]) graph.add_edge(edge) graph.write_png(outfile)
def make_corenlp_tree(data_in_path, data_out_path, num_sentence): tree = ET.parse(data_in_path) root = tree.getroot() i = 0 for dependencies in root.findall(".//dependencies"): if dependencies.get('type') != 'collapsed-dependencies': continue i += 1 if i != num_sentence: continue graph = pydot.Dot() graph.set_type('digraph') for dep in dependencies.findall('dep'): from_edge = dep.find('governor').text + ' _ ' + dep.find('governor').get('idx') to_edge = dep.find('dependent').text + ' _ ' + dep.find('dependent').get('idx') if to_edge in ',': to_edge = r'\,' graph.add_edge(pydot.Edge(from_edge, to_edge)) graph.write_jpeg(data_out_path) break
def graph_from_idx_edges(edges): graph = pydot.Dot(graph_type = 'digraph') for edge in edges: idx1 = str(edge[0][0]) label1 = str(edge[0][1]) idx2 = str(edge[1][0]) label2 = str(edge[1][1]) graph.add_node(pydot.Node(idx1, label=label1)) graph.add_node(pydot.Node(idx2, label=label2)) graph.add_edge(pydot.Edge(idx1, idx2)) return graph
def render_graph_graphviz (self): ''' Render the graphviz graph structure. @rtype: pydot.Dot @return: Pydot object representing entire graph ''' import pydot dot_graph = pydot.Dot() for node in self.nodes.values(): dot_graph.add_node(node.render_node_graphviz(self)) for edge in self.edges.values(): dot_graph.add_edge(edge.render_edge_graphviz(self)) return dot_graph ####################################################################################################################
def to_pydot(self): """Return a pydot digraph from a StepTree.""" graph = pydot.Dot(graph_type='digraph') # make sure Root shows up in single node trees if self.root_name: graph.add_node(pydot.Node(self._step_graph_label(self.root_name))) for parent, children in self.children.items(): for child in children: graph.add_edge(pydot.Edge( self._step_graph_label(parent), self._step_graph_label(child) )) return graph
def drawGraphFromSM2(SM, names, outFile, Cut): graph = pydot.Dot(graph_type='graph') # THRESHOLD SM: nonZeroMean = np.mean(SM[SM.nonzero()]) if Cut: T = 5.0 * nonZeroMean else: T = 0.0; for i in range(SM.shape[0]): for j in range(SM.shape[0]): if SM[i,j] <= T: SM[i,j] = 0.0 else: SM[i,j] = 1.0 numOfConnections = sum(SM, axis = 0) #fig = plt.figure(1) #plot1 = plt.imshow(SM, origin='upper', cmap=cm.gray, interpolation='nearest') #plt.show() numOfConnections = 9*numOfConnections / max(numOfConnections) for i,f in enumerate(names): if sum(SM[i,:])>0: fillColorCurrent = "{0:d}".format(int(ceil(numOfConnections[i]))) # NOTE: SEE http://www.graphviz.org/doc/info/colors.html for color schemes node = pydot.Node(f, style="filled", fontsize="8", shape="egg", fillcolor=fillColorCurrent, colorscheme = "reds9") graph.add_node(node) for i in range(len(names)): for j in range(len(names)): if i<j: if SM[i][j] > 0: #gr.add_edge((names[i], names[j])) edge = pydot.Edge(names[i], names[j]) graph.add_edge(edge) graph.write_png(outFile)
def __init__(self): self.seen = set() self.dot = pydot.Dot("resnet", graph_type="digraph", rankdir="TB") self.style_params = {"shape": "octagon", "fillcolor": "gray", "style": "filled", "label": "", "color": "none"} self.style_layers = {"shape": "box", "fillcolor": "blue", "style": "filled", "label": "", "color": "none"}
def writeDotImage(self, filename): """ Writes a image representation of the individual :param filename: the output file image """ if not HAVE_PYDOT: utils.raiseException("You must install Pydot to use this feature !") graph = pydot.Dot() self.writeDotGraph(graph) graph.write_jpeg(filename, prog='dot') # -----------------------------------------------------------------
def writeDotRaw(self, filename): """ Writes the raw dot file (text-file used by dot/neato) with the representation of the individual :param filename: the output file, ex: individual.dot """ if not HAVE_PYDOT: utils.raiseException("You must install Pydot to use this feature !") graph = pydot.Dot(graph_type="digraph") self.writeDotGraph(graph) graph.write(filename, prog='dot', format="raw") # -----------------------------------------------------------------
def writePopulationDot(ga_engine, filename, format="jpeg", start=0, end=0): """ Writes to a graphical file using pydot, the population of trees Example: >>> GTreeGP.writePopulationDot(ga_engine, "pop.jpg", "jpeg", 0, 10) This example will draw the first ten individuals of the population into the file called "pop.jpg". :param ga_engine: the GA Engine :param filename: the filename, ie. population.jpg :param start: the start index of individuals :param end: the end index of individuals """ if not HAVE_PYDOT: utils.raiseException("You must install Pydot to use this feature !") pop = ga_engine.get_population() graph = pydot.Dot(graph_type="digraph") if not isinstance(pop[0], GTreeGP): utils.raiseException("The population must have individuals of the GTreeGP chromosome !") n = 0 end_index = len(pop) if end == 0 else end for i in xrange(start, end_index): ind = pop[i] subg = pydot.Cluster( "cluster_%d" % i, label="\"Ind. #%d - Score Raw/Fit.: %.4f/%.4f\"" % (i, ind.getRawScore(), ind.getFitnessScore()) ) n = ind.writeDotGraph(subg, n) graph.add_subgraph(subg) graph.write(filename, prog='dot', format=format) # -----------------------------------------------------------------
def writePopulationDotRaw(ga_engine, filename, start=0, end=0): """ Writes to a raw dot file using pydot, the population of trees Example: >>> GTreeGP.writePopulationDotRaw(ga_engine, "pop.dot", 0, 10) This example will draw the first ten individuals of the population into the file called "pop.dot". :param ga_engine: the GA Engine :param filename: the filename, ie. population.dot :param start: the start index of individuals :param end: the end index of individuals """ if not HAVE_PYDOT: utils.raiseException("You must install Pydot to use this feature !") pop = ga_engine.get_population() graph = pydot.Dot(graph_type="digraph") if not isinstance(pop[0], GTreeGP): utils.raiseException("The population must have individuals of the GTreeGP chromosome !") n = 0 end_index = len(pop) if end == 0 else end for i in xrange(start, end_index): ind = pop[i] subg = pydot.Cluster( "cluster_%d" % i, label="\"Ind. #%d - Score Raw/Fit.: %.4f/%.4f\"" % (i, ind.getRawScore(), ind.getFitnessScore()) ) n = ind.writeDotGraph(subg, n) graph.add_subgraph(subg) graph.write(filename, prog='dot', format="raw") # -----------------------------------------------------------------
def plot(self, model, to_file): """ creates a graph visualizing the structure of `model` and writes it to `to_file` """ graph = pydot.Dot(graph_type='graph') self.add_model(model, graph) graph.write_png(to_file)
def to_png_with_pydot(self, filename): import pydot graph = pydot.Dot(graph_type='digraph', rankdir="LR") self._to_pydot(graph) graph.write_png(filename)
def graph_from_edges_ex(edge_list, title, directed=False): if directed: graph = pydot.Dot(graph_type='digraph') else: graph = pydot.Dot(graph_type='graph') for edge in edge_list: id1 = str(edge[0][0]) label1 = str(edge[0][1]) id2 = str(edge[1][0]) label2 = str(edge[1][1]) # add node graph.add_node(pydot.Node(id1, label=label1)) graph.add_node(pydot.Node(id2, label=label2)) # add edege graph.add_edge(pydot.Edge(id1, id2)) graph.set_label( title ) return graph
def knock_44(Sent): tree_graph=pydot.Dot(graph_type='digraph',fontname="Microsoft YaHei") nodes=[] for ind, p in enumerate(Sent.phrases): nodes.append(pydot.Node(p.str,fontname="Microsoft YaHei")) tree_graph.add_node(nodes[ind]) for ind, p in enumerate(Sent.phrases): if p.father!=-1: tree_graph.add_edge(pydot.Edge(nodes[ind],nodes[p.father])) tree_graph.write_png("knock_44.png") # In[152]:
def visualize_tree(f_name,number_trees=3): tree = etree.parse(f_name) root = tree.getroot() sentences = root.xpath("/root/document/sentences/sentence") for idx, sentence in enumerate(sentences): tree_graph = pydot.Dot(graph_type='digraph') basic_dependencies = sentence.xpath( "./dependencies[@type='basic-dependencies']/dep") for dep in basic_dependencies: father = "{no}_{word}".format( no=dep[0].get("idx"), word=dep[0].text) child = "{no}_{word}".format( no=dep[1].get("idx"), word=dep[1].text) tree_graph.add_node(pydot.Node(father)) tree_graph.add_node(pydot.Node(child)) tree_graph.add_edge(pydot.Edge(child, father)) tree_graph.write_png("sentence_{no}.png".format(no=idx)) if idx > number_trees-1: break # In[91]:
def __init__(self, deps, no_leafs=False): # create a graph object self.graph = pydot.Dot(graph_type='digraph') self.nodes = None self.no_leafs = no_leafs # add nodes and edges to the root node sys.stdout.write("Creating graph") self.add_nodes(deps) sys.stdout.write("Done\n")
def pydot__tree_to_png(tree, filename): import pydot graph = pydot.Dot(graph_type='digraph', rankdir="LR") i = [0] def new_leaf(leaf): node = pydot.Node(i[0], label=repr(leaf)) i[0] += 1 graph.add_node(node) return node def _to_pydot(subtree): color = hash(subtree.data) & 0xffffff color |= 0x808080 subnodes = [_to_pydot(child) if isinstance(child, Tree) else new_leaf(child) for child in subtree.children] node = pydot.Node(i[0], style="filled", fillcolor="#%x"%color, label=subtree.data) i[0] += 1 graph.add_node(node) for subnode in subnodes: graph.add_edge(pydot.Edge(node, subnode)) return node _to_pydot(tree) graph.write_png(filename)
def plot(model, to_file='model.png'): graph = pydot.Dot(graph_type='digraph') if type(model) == Sequential: previous_node = None written_nodes = [] n = 1 for node in model.get_config()['layers']: # append number in case layers have same name to differentiate if (node['name'] + str(n)) in written_nodes: n += 1 current_node = pydot.Node(node['name'] + str(n)) written_nodes.append(node['name'] + str(n)) graph.add_node(current_node) if previous_node: graph.add_edge(pydot.Edge(previous_node, current_node)) previous_node = current_node graph.write_png(to_file) elif type(model) == Graph: # don't need to append number for names since all nodes labeled for input_node in model.input_config: graph.add_node(pydot.Node(input_node['name'])) # intermediate and output nodes have input defined for layer_config in [model.node_config, model.output_config]: for node in layer_config: graph.add_node(pydot.Node(node['name'])) # possible to have multiple 'inputs' vs 1 'input' if node['inputs']: for e in node['inputs']: graph.add_edge(pydot.Edge(e, node['name'])) else: graph.add_edge(pydot.Edge(node['input'], node['name'])) graph.write_png(to_file)
def createModulesGraph(moddb): graph = pydot.Dot(graph_type='digraph') nodes = dict() # add modules as nodes for mod in moddb.getModules(): tt = ", ".join(mod.provides) + " " node = pydot.Node(mod.name, tooltip=tt) nodes[mod.name] = node graph.add_node(node) # add directed edges from modules to modules that satisfy at least one dependency for src in moddb.getModules(): dstmods = moddb.getSolutionCandidates(src) for dst in dstmods: tt = ", ".join(dstmods[dst]) + " " edge = pydot.Edge(src.name, dst.name, tooltip=tt) graph.add_edge(edge) # add special directed edges for "modules" inclusion for src in moddb.getModules(): for dstname in src.modules: dst = moddb[dstname] edge = pydot.Edge(src.name, dst.name, color="green") graph.add_edge(edge) # add undirected edges for conflicts for src in moddb.getModules(): conflicts = moddb.getConflictingModules(src) for dst in conflicts: if (dst.name < src.name): tt = ", ".join(conflicts[dst]) + " " edge = pydot.Edge(src.name, dst.name, color="red", dir="none", tooltip=tt) graph.add_edge(edge) graph.write('dependencies.dot') # TODO rewrite as mako template and drop pydot dependency
def model_picture(model, to_file='local/model.png'): graph = pydot.Dot(graph_type='digraph') if isinstance(model,Sequential): previous_node = None written_nodes = [] n = 1 for node in model.get_config()['layers']: # append number in case layers have same name to differentiate if (node['name'] + str(n)) in written_nodes: n += 1 current_node = pydot.Node(node['name'] + str(n)) written_nodes.append(node['name'] + str(n)) graph.add_node(current_node) if previous_node: graph.add_edge(pydot.Edge(previous_node, current_node)) previous_node = current_node graph.write_png(to_file) elif isinstance(model,Graph): # don't need to append number for names since all nodes labeled for input_node in model.input_config: graph.add_node(pydot.Node(input_node['name'])) # intermediate and output nodes have input defined for layer_config in [model.node_config, model.output_config]: for node in layer_config: graph.add_node(pydot.Node(node['name'])) # possible to have multiple 'inputs' vs 1 'input' if node['inputs']: for e in node['inputs']: graph.add_edge(pydot.Edge(e, node['name'])) else: graph.add_edge(pydot.Edge(node['input'], node['name'])) graph.write_png(to_file)
def create_schema_graph(tables=None, metadata=None, show_indexes=True, show_datatypes=True, font="Bitstream-Vera Sans", concentrate=True, relation_options={}, rankdir='TB'): relation_kwargs = { 'fontsize':"7.0" } relation_kwargs.update(relation_options) if metadata is None and tables is not None and len(tables): metadata = tables[0].metadata elif tables is None and metadata is not None: if not len(metadata.tables): metadata.reflect() tables = list(metadata.tables.values()) else: raise ValueError("You need to specify at least tables or metadata") graph = pydot.Dot(prog="dot",mode="ipsep",overlap="ipsep",sep="0.01",concentrate=str(concentrate), rankdir=rankdir) for table in tables: graph.add_node(pydot.Node(str(table.name), shape="plaintext", label=_render_table_html(table, metadata, show_indexes, show_datatypes), fontname=font, fontsize="7.0" )) for table in tables: for fk in table.foreign_keys: if fk.column.table not in tables: continue edge = [table.name, fk.column.table.name] is_inheritance = fk.parent.primary_key and fk.column.primary_key if is_inheritance: edge = edge[::-1] graph_edge = pydot.Edge( headlabel="+ %s"%fk.column.name, taillabel='+ %s'%fk.parent.name, arrowhead=is_inheritance and 'none' or 'odot' , arrowtail=(fk.parent.primary_key or fk.parent.unique) and 'empty' or 'crow' , fontname=font, #samehead=fk.column.name, sametail=fk.parent.name, *edge, **relation_kwargs ) graph.add_edge(graph_edge) # not sure what this part is for, doesn't work with pydot 1.0.2 # graph_edge.parent_graph = graph.parent_graph # if table.name not in [e.get_source() for e in graph.get_edge_list()]: # graph.edge_src_list.append(table.name) # if fk.column.table.name not in graph.edge_dst_list: # graph.edge_dst_list.append(fk.column.table.name) # graph.sorted_graph_elements.append(graph_edge) return graph
def model_to_dot(model, show_shapes=False, show_layer_names=True): dot = pydot.Dot() dot.set('rankdir', 'TB') dot.set('concentrate', True) dot.set_node_defaults(shape='record') if isinstance(model, Sequential): if not model.built: model.build() model = model.model layers = model.layers # Create graph nodes. for layer in layers: layer_id = str(id(layer)) # Append a wrapped layer's label to node's label, if it exists. layer_name = layer.name class_name = layer.__class__.__name__ if isinstance(layer, Wrapper): layer_name = '{}({})'.format(layer_name, layer.layer.name) child_class_name = layer.layer.__class__.__name__ class_name = '{}({})'.format(class_name, child_class_name) # Create node's label. if show_layer_names: label = '{}: {}'.format(layer_name, class_name) else: label = class_name # Rebuild the label as a table including input/output shapes. if show_shapes: try: outputlabels = str(layer.output_shape) except: outputlabels = 'multiple' if hasattr(layer, 'input_shape'): inputlabels = str(layer.input_shape) elif hasattr(layer, 'input_shapes'): inputlabels = ', '.join( [str(ishape) for ishape in layer.input_shapes]) else: inputlabels = 'multiple' label = '%s\n|{input:|output:}|{{%s}|{%s}}' % (label, inputlabels, outputlabels) node = pydot.Node(layer_id, label=label) dot.add_node(node) # Connect nodes with edges. for layer in layers: layer_id = str(id(layer)) for i, node in enumerate(layer.inbound_nodes): node_key = layer.name + '_ib-' + str(i) if node_key in model.container_nodes: for inbound_layer in node.inbound_layers: inbound_layer_id = str(id(inbound_layer)) layer_id = str(id(layer)) dot.add_edge(pydot.Edge(inbound_layer_id, layer_id)) return dot
def read(string): """ Read a graph from a string in Dot language and return it. Nodes and edges specified in the input will be added to the current graph. @type string: string @param string: Input string in Dot format specifying a graph. @rtype: graph @return: Graph """ dotG = pydot.graph_from_dot_data(string) if (dotG.get_type() == "graph"): G = graph() elif (dotG.get_type() == "digraph"): G = digraph() elif (dotG.get_type() == "hypergraph"): return read_hypergraph(string) else: raise InvalidGraphType # Read nodes... # Note: If the nodes aren't explicitly listed, they need to be for each_node in dotG.get_nodes(): G.add_node(each_node.get_name()) for each_attr_key, each_attr_val in each_node.get_attributes().items(): G.add_node_attribute(each_node.get_name(), (each_attr_key, each_attr_val)) # Read edges... for each_edge in dotG.get_edges(): # Check if the nodes have been added if not G.has_node(each_edge.get_source()): G.add_node(each_edge.get_source()) if not G.has_node(each_edge.get_destination()): G.add_node(each_edge.get_destination()) # See if there's a weight if 'weight' in each_edge.get_attributes().keys(): _wt = each_edge.get_attributes()['weight'] else: _wt = 1 # See if there is a label if 'label' in each_edge.get_attributes().keys(): _label = each_edge.get_attributes()['label'] else: _label = '' G.add_edge((each_edge.get_source(), each_edge.get_destination()), wt = _wt, label = _label) for each_attr_key, each_attr_val in each_edge.get_attributes().items(): if not each_attr_key in ['weight', 'label']: G.add_edge_attribute((each_edge.get_source(), each_edge.get_destination()), \ (each_attr_key, each_attr_val)) return G
def write_hypergraph(hgr, colored = False): """ Return a string specifying the given hypergraph in DOT Language. @type hgr: hypergraph @param hgr: Hypergraph. @type colored: boolean @param colored: Whether hyperedges should be colored. @rtype: string @return: String specifying the hypergraph in DOT Language. """ dotG = pydot.Dot() if not 'name' in dir(hgr): dotG.set_name('hypergraph') else: dotG.set_name(hgr.name) colortable = {} colorcount = 0 # Add all of the nodes first for node in hgr.nodes(): newNode = pydot.Node(str(node), hyper_node_type = 'hypernode') dotG.add_node(newNode) for hyperedge in hgr.hyperedges(): if (colored): colortable[hyperedge] = colors[colorcount % len(colors)] colorcount += 1 newNode = pydot.Node(str(hyperedge), hyper_node_type = 'hyperedge', \ color = str(colortable[hyperedge]), \ shape = 'point') else: newNode = pydot.Node(str(hyperedge), hyper_node_type = 'hyperedge') dotG.add_node(newNode) for link in hgr.links(hyperedge): newEdge = pydot.Edge(str(hyperedge), str(link)) dotG.add_edge(newEdge) return dotG.to_string()
def create_graph(self): g = pydot.Dot(graph_type='digraph') node_map = {} for h in self.network.topology.hosts: label = "<<B>%s</B><br/>%d %d<br/>%d>" % (h.name, h.receiving_cap, h.sending_cap, h.amp_factor) n = pydot.Node(h.name, label=label, style='filled', margin=-0.8, width=0.5, height=0.5, fontname=self.font_name, fontsize=self.node_fontsize) if type(h) is Server: if self.network.victims and h in self.network.victims: n.set_shape('doublecircle') else: n.set_shape('Mcircle') n.set_fillcolor(self.server_color) elif type(h) is Router: if self.network.victims and h in self.network.victims: n.set_shape('doubleoctagon') else: n.set_shape('octagon') n.set_fillcolor(self.server_color) else: if self.network.victims and h in self.network.victims: n.set_shape('doublecircle') else: n.set_shape('circle') if self.network.attackers and h in self.network.attackers: n.set_fillcolor(self.attacker_color) else: n.set_fillcolor(self.host_color) g.add_node(n) node_map[h] = n for l in self.network.topology.links: v1 = node_map[l.h1] v2 = node_map[l.h2] e = pydot.Edge(v1, v2, dir='none', label=str(l.capacity), color=self.link_color, fontcolor=self.link_color, fontname=self.font_name, fontsize=self.label_size) g.add_edge(e) if self.network.flows: f1 = sum([f.get(l.h1, l.h2) for f in self.network.flows]) f2 = sum([f.get(l.h2, l.h1) for f in self.network.flows]) if f1 > 0: g.add_edge(self.__create_link_flow(v1, v2, f1)) if f2 > 0: g.add_edge(self.__create_link_flow(v2, v1, f2)) return g
def reduce_graph(self, threshold=0): if len(self.edges.keys()) == 0: print "Run first create_graph()" return False self.edges_reduced = {} self.graph = pydot.Dot(graph_type='digraph') # iterate through nodes and edges and filter by value for key in self.edges.keys(): # check for most visited nodes if self.tree[key][1] > threshold * self.total: # iterate over edges and connect most visited nodes for parent_key in self.edges[key]: if parent_key != "Last" and self.tree[parent_key][1] > threshold * self.total: edge_label = "" for grandparent_key in self.edges[key][parent_key].keys(): n = self.edges[key][parent_key][grandparent_key] if self.tree[parent_key][1] > threshold * self.total and self.edges[key][parent_key][grandparent_key][1] > threshold * self.total: if key not in self.edges_reduced: self.edges_reduced[key] = { parent_key: { grandparent_key: n } } if parent_key not in self.edges_reduced[key]: self.edges_reduced[key].update({ parent_key: { grandparent_key: n } }) if grandparent_key not in self.edges_reduced[key][parent_key]: self.edges_reduced[key][parent_key].update({ grandparent_key: n }) else: self.edges_reduced[key][parent_key][grandparent_key] = n edge_counter = self.edges[key][parent_key][grandparent_key][1] edge_label = edge_label + "\n" + str(edge_counter) + " " + str(grandparent_key[0]) + "_" + str(grandparent_key[1]) + "_" + str(grandparent_key[2]) if edge_label != "": new_edge = pydot.Edge(self.tree[parent_key][0], self.tree[key][0]) self.graph.add_node(self.tree[parent_key][0]) self.graph.add_node(self.tree[key][0]) self.graph.add_edge( new_edge ) new_edge.set_label( edge_label )
def main(gviz_path, layer_only=False): graphviz_setup(gviz_path) graph = pydot.Dot(graph_type='digraph', rankdir="TB") layer_children = {'CLASS': {'LABEL': {'STYLE': {}}, 'LEADER': {'STYLE': {}}, 'STYLE': {}, 'VALIDATION': {}}, 'CLUSTER': {}, 'COMPOSITE': {}, 'FEATURE': {'POINTS': {}}, 'GRID': {}, 'JOIN': {}, 'METADATA': {}, 'PROJECTION': {}, 'SCALETOKEN': {'VALUES': {}}, 'VALIDATION': {}} #pprint.pprint(layer_children) classes = { "MAP": {"LAYER": layer_children, 'LEGEND': {'LABEL': {}}, 'PROJECTION': {}, 'QUERYMAP': {}, 'REFERENCE': {}, 'SCALEBAR': {'LABEL': {}}, 'SYMBOL': {}, 'WEB': {'METADATA': {}, 'VALIDATION': {}}}} if layer_only: root = "LAYER" classes = classes["MAP"] fn = "layer_classes" else: fn = "map_classes" root, = classes.keys() node = pydot.Node(root, style="filled", fillcolor="#33a333", label=root, fontname=FONT, shape="polygon") graph.add_node(node) add_children(graph, root, classes[root]) save_file(graph, fn)
def render(self, filename, label='', labelloc='t', labeljust='c', rankdir="TB", ranksep=0.7, fontname='Arial', fontsize=24, use_urls=False, node_fixedsize='true', nodesep=0.1, node_width=0.85, node_height=0.85, node_fontsize=15, include_ids=False): import pydot # Graph graph_args = { "rankdir": rankdir, "ranksep": ranksep, "nodesep": nodesep, "fontname": fontname, "fontsize": fontsize, } if label: graph_args.update({ "labelloc": labelloc, "labeljust": labeljust, "label": label }) graph = pydot.Dot(**graph_args) # Node node_args = { "fontsize": node_fontsize, } if use_urls: node_seed_shape = 'rectangle' node_shape = 'oval' else: node_seed_shape = 'square' node_shape = 'circle' node_args.update({ "fixedsize": node_fixedsize, "width": node_width, "height": node_height, }) graph.set_node_defaults(**node_args) for page in self.pages: graph.add_node(pydot.Node(name=self._clean_page_name(page, include_id=include_ids), fontname=fontname, fontsize=node_fontsize, shape=node_seed_shape if page.is_seed else node_shape)) for link in page.links: graph.add_edge(pydot.Edge(self._clean_page_name(page, include_id=include_ids), self._clean_page_name(link, include_id=include_ids))) graph.write_png(filename)
def createConfigurationGraph(modules, selectedmods, moddb, filename): graph = pydot.Dot(graph_name="G", graph_type='digraph') nodes = dict() # add modules as nodes for mod in modules: tt = ", ".join(mod.provides) + " " if mod.name in selectedmods: fc = "#BEF781" else: fc = "white" if moddb.getConflictingModules(mod): nc = "#DF0101" else: nc = "black" node = pydot.Node(mod.name, tooltip=tt, style='filled', fillcolor=fc, color=nc, fontcolor=nc) # node = pydot.Node(mod.name) nodes[mod.name] = node graph.add_node(node) # add directed edges from modules to modules that satisfy at least one dependency for src in modules: dstmods = moddb.getSolutionCandidates(src) #print(str(src) + ' --> ' + str(dstmods)) # don't show modules that are not in 'modules' for dst in dstmods: if dst not in modules: continue tt = ", ".join(dstmods[dst]) + " " edge = pydot.Edge(src.name, dst.name, tooltip=tt) # edge = pydot.Edge(src.name, dst.name) graph.add_edge(edge) # add special directed edges for "modules" inclusion for src in modules: for dstname in src.modules: dst = moddb[dstname] edge = pydot.Edge(src.name, dst.name, color="green") graph.add_edge(edge) graph.write(filename)
def push_top_graph_stmt(str, loc, toks): attrs = {} g = None for element in toks: if( isinstance(element, (ParseResults, tuple, list)) and len(element) == 1 and isinstance(element[0], basestring) ): element = element[0] if element == 'strict': attrs['strict'] = True elif element in ['graph', 'digraph']: attrs = {} g = pydot.Dot(graph_type=element, **attrs) attrs['type'] = element top_graphs.append( g ) elif isinstance( element, basestring): g.set_name( element ) elif isinstance(element, pydot.Subgraph): g.obj_dict['attributes'].update( element.obj_dict['attributes'] ) g.obj_dict['edges'].update( element.obj_dict['edges'] ) g.obj_dict['nodes'].update( element.obj_dict['nodes'] ) g.obj_dict['subgraphs'].update( element.obj_dict['subgraphs'] ) g.set_parent_graph(g) elif isinstance(element, P_AttrList): attrs.update(element.attrs) elif isinstance(element, (ParseResults, list)): add_elements(g, element) else: raise ValueError, "Unknown element statement: %r " % element for g in top_graphs: update_parent_graph_hierarchy(g) if len( top_graphs ) == 1: return top_graphs[0] return top_graphs
def model_to_dot(model, show_shapes=False, show_layer_names=True): dot = pydot.Dot() dot.set('rankdir', 'TB') dot.set('concentrate', True) dot.set_node_defaults(shape='record') if model.__class__.__name__ == 'Sequential': if not model.built: model.build() model = model.model layers = model.layers # first, populate the nodes of the graph for layer in layers: layer_id = str(id(layer)) if show_layer_names: label = str(layer.name) + ' (' + layer.__class__.__name__ + ')' else: label = layer.__class__.__name__ if show_shapes: # Build the label that will actually contain a table with the # input/output try: outputlabels = str(layer.output_shape) except: outputlabels = 'multiple' if hasattr(layer, 'input_shape'): inputlabels = str(layer.input_shape) elif hasattr(layer, 'input_shapes'): inputlabels = ', '.join( [str(ishape) for ishape in layer.input_shapes]) else: inputlabels = 'multiple' label = '%s\n|{input:|output:}|{{%s}|{%s}}' % (label, inputlabels, outputlabels) node = pydot.Node(layer_id, label=label) dot.add_node(node) # second, add the edges for layer in layers: layer_id = str(id(layer)) for i, node in enumerate(layer.inbound_nodes): node_key = layer.name + '_ib-' + str(i) if node_key in model.container_nodes: # add edges for inbound_layer in node.inbound_layers: inbound_layer_id = str(id(inbound_layer)) layer_id = str(id(layer)) dot.add_edge(pydot.Edge(inbound_layer_id, layer_id)) return dot