def make_graph(edge_list, 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]) graph.add_node( pydot.Node(id1, label='<<font face="MS Gothic">%s</font>>' % label1.rstrip("\r\n"))) graph.add_node( pydot.Node(id2, label='<<font face="MS Gothic">%s</font>>' % label2.rstrip("\r\n"))) graph.add_edge(pydot.Edge(id1, id2)) return graph
def to_pydot(N, strict=True): """Return a pydot graph from a NetworkX graph N. Parameters ---------- N : NetworkX graph A graph created with NetworkX Examples -------- >>> import networkx as nx >>> K5 = nx.complete_graph(5) >>> P = nx.to_pydot(K5) Notes ----- """ # set Graphviz graph type if N.is_directed(): graph_type = 'digraph' else: graph_type = 'graph' strict = N.number_of_selfloops() == 0 and not N.is_multigraph() name = N.graph.get('name') graph_defaults = N.graph.get('graph', {}) if name is None: P = pydot.Dot(graph_type=graph_type, strict=strict, **graph_defaults) else: P = pydot.Dot('"%s"' % name, graph_type=graph_type, strict=strict, **graph_defaults) try: P.set_node_defaults(**N.graph['node']) except KeyError: pass try: P.set_edge_defaults(**N.graph['edge']) except KeyError: pass for n, nodedata in N.nodes_iter(data=True): str_nodedata = dict((k, make_str(v)) for k, v in nodedata.items()) p = pydot.Node(make_str(n), **str_nodedata) P.add_node(p) if N.is_multigraph(): for u, v, key, edgedata in N.edges_iter(data=True, keys=True): str_edgedata = dict((k, make_str(v)) for k, v in edgedata.items()) edge = pydot.Edge(make_str(u), make_str(v), key=make_str(key), **str_edgedata) P.add_edge(edge) else: for u, v, edgedata in N.edges_iter(data=True): str_edgedata = dict((k, make_str(v)) for k, v in edgedata.items()) edge = pydot.Edge(make_str(u), make_str(v), **str_edgedata) P.add_edge(edge) return P
def graph_from_edges_ex(edge_list, 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]) graph.add_node(pydot.Node(id1, label=label1)) graph.add_node(pydot.Node(id2, label=label2)) graph.add_edge(pydot.Edge(id1, id2)) return graph
def test_quoting(): import string g = pydot.Dot() g.add_node(pydot.Node("test", label=string.printable)) data = g.create(format="jpe") assert len(data) > 0
def main_run(): genome = GTree.GTreeGP() root = GTree.GTreeNodeGP('a', Consts.nodeType["TERMINAL"]) genome.setRoot(root) genome.setParams(max_depth=2, method="ramped") genome.evaluator += eval_func genome.mutator.set(Mutators.GTreeGPMutatorSubtree) ga = GSimpleGA.GSimpleGA(genome) ga.setParams(gp_terminals=['a', 'b'], gp_function_prefix="gp") ga.setMinimax(Consts.minimaxType["maximize"]) ga.setGenerations(500) ga.setCrossoverRate(1.0) ga.setMutationRate(0.08) ga.setPopulationSize(80) ga(freq_stats=1) print(ga.bestIndividual()) graph = pydot.Dot() try: ga.bestIndividual().writeDotGraph(graph) graph.write_jpeg('tree.png', prog='dot') except pydot_ng.InvocationException: # TODO We need to detect pydot presense # noqa print('Graphviz not installed')
def _check_pydot(): try: # Attempt to create an image of a blank graph to check the pydot/graphviz installation. pydot.Dot.create(pydot.Dot()) except Exception: # pydot raises a generic Exception here, so no specific class can be caught. raise ImportError('Failed to import pydot. You must install pydot' ' and graphviz for `pydotprint` to work.')
def create_graph(graph_info): dot = pydot.Dot() for node in graph_info['nodes']: dot.add_node(pydot.Node(node)) for node1, node2 in graph_info['edges']: dot.add_edge(pydot.Edge(node1, node2)) return dot
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 __call__(self, model, recursive=True, show_shape=False, connect_to=None): self.idgen = 0 # Maps keras layer to the pydot.Node representing them self.layer_to_pydotnode = {} self.recursive = recursive self.show_shape = show_shape self.g = pydot.Dot() self.g.set('rankdir', 'TB') self.g.set('concentrate', True) self.g.set_node_defaults(shape='record') if hasattr(model, 'outputs'): # Graph for name, l in model.outputs.items(): self._process_layer(l, get_layer_to_name(model), connect_to=connect_to) else: # Sequential container self._process_layer(model.layers[-1], {}, connect_to=connect_to) return self.g
def plot(root, to_file='vct_tree.png'): dot = pydot.Dot() dot.set('rankdir', 'TB') dot.set('concentrate', True) dot.set_node_defaults(shape='record') root.id = 0 label = 'root\nproof:{:d} disproof:{:d}'.format(root.proof, root.disproof) dot.add_node(pydot.Node(root.id, label=label)) node_stack = [] node_stack.append(root) count = 0 while len(node_stack): node = node_stack.pop() if node.parent is not None: parent_id = node.parent.id node_id = node.id dot.add_edge(pydot.Edge(parent_id, node_id)) for position, child_node in node.children.items(): count += 1 child_node.id = count label = str(position) + '\nproof:{:d} disproof:{:d}'.format( child_node.proof, child_node.disproof) dot.add_node(pydot.Node(child_node.id, label=label)) node_stack.append(child_node) _, extension = os.path.splitext(to_file) if not extension: extension = 'png' else: extension = extension[1:] dot.write(to_file, format=extension)
def plot_net(net, file_name='net.png', show_shapes=False, rankdir="TB"): dot = pydot.Dot() dot.set('rankdir', rankdir) dot.set('concentrate', True) dot.set_node_defaults(shape='recodr') id_layer_name_pair = dict() for i, layer in enumerate(net.all_layers): layer_name = layer.name layer_shape = layer.get_shape() if show_shapes: label = "%s\n %s" % (layer_name, str(layer_shape)) else: label = layer_name node = pydot.Node(i, label=label) dot.add_node(node) id_layer_name_pair[layer_name] = i for key in net.net_tree: if key in id_layer_name_pair.keys(): parent_id = id_layer_name_pair[key] else: continue for child in net.net_tree[key]: if child in id_layer_name_pair.keys(): child_id = id_layer_name_pair[child] dot.add_edge(pydot.Edge(parent_id,child_id)) _, extension = os.path.splitext(file_name) if not extension: extension = 'png' else: extension = extension[1:] dot.write(file_name, format=extension)
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: Util.raiseException("You must install Pydot to use this feature !") pop = ga_engine.getPopulation() graph = pydot.Dot(graph_type="digraph") if not isinstance(pop[0], GTreeGP): Util.raiseException("The population must have individuals of the GTreeGP chromosome !") n = 0 end_index = len(pop) if end == 0 else end for i in range(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 test_executable_not_found_exception(): graph = pydot.Dot("graphname", graph_type="digraph") paths = {"dot": "invalid_executable_path"} graph.set_graphviz_executables(paths) with pytest.raises(pydot.InvocationException): graph.create()
def main(): graph = pydot.Dot(graph_type='digraph') graph.set_node_defaults(fontname='Meiryo UI', fontsize='10') article = analyze() for s, t in toDot(article[4]): graph.add_edge(pydot.Edge(s, t)) graph.write_png('result44.png')
def graph_from_edges_ex(edge_list, directed=False): ''' pydot_ng.graph_from_edges()のノード識別子への対応版 graph_from_edges()のedge_listで指定するタプルは 識別子とグラフ表示時のラベルが同一のため、 ラベルが同じだが実体が異なるノードを表現することができない。 例えば文の係り受けをグラフにする際、文の中に同じ単語が 複数出てくると、それらのノードが同一視されて接続されてしまう。 この関数ではedge_listとして次の書式のタプルを受け取り、 ラベルが同一でも識別子が異なるノードは別ものとして扱う。 edge_list = [((識別子1,ラベル1),(識別子2,ラベル2)), ...] 識別子はノードを識別するためのもので表示されない。 ラベルは表示用で、同じでも識別子が異なれば別のノードになる。 なお、オリジナルの関数にあるnode_prefixは未実装。 戻り値: pydot.Dotオブジェクト ''' 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]) # ノード追加 graph.add_node(pydot.Node(id1, label=label1)) graph.add_node(pydot.Node(id2, label=label2)) # エッジ追加 graph.add_edge(pydot.Edge(id1, id2)) return graph
def model_to_dot2(model, show_shapes=False, show_layer_names=True, layer_names=[], keep_layers=[]): dot = pydot.Dot() dot.set('rankdir', 'TB') dot.set('concentrate', True) dot.set_node_defaults(shape='record')
def toGraph(dot, filepath): #os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/' graph = pydot.Dot(graph_type='digraph') graph.set_node_defaults(fontname='Meiryo UI', fontsize='10') for s, t in dot: graph.add_edge(pydot.Edge(s, t)) graph.write_png(filepath)
def makeGraph(sentence, outputFileName): g = pydot.Dot(graph_type='digraph') # g.add_node(pydot.Node()) chunkPairs = [(chunk.getSurface(), sentence[chunk.dst].getSurface()) for chunk in sentence if chunk.dst >= 0 and not chunk.isSymbol()] for chunkPair in chunkPairs: g.add_edge(pydot.Edge(chunkPair[0], chunkPair[1])) g.write_png(outputFileName)
def mnn_to_dot(mnn_file): "load a mnn file and create a dot file" if not os.path.exists(mnn_file): return None dot = pydot.Dot() dot.set('rankdir', 'TB') dot.set('concentrate', True) dot.set_node_defaults(shape='record') with open(mnn_file, 'rb') as f: buf = f.read() f.close() buf = bytearray(buf) net = Net.Net.GetRootAsNet(buf, 0) op_num = net.OplistsLength() for idx in range(op_num): op = net.Oplists(idx) name = "op_" + str(idx) op_type = op.Type() label = OpName.optype_to_name(op_type) main_type = op.MainType() if main_type == OpParameter.OpParameter.Convolution2D: union_conv2d = Convolution2D.Convolution2D() union_conv2d.Init(op.Main().Bytes, op.Main().Pos) common = union_conv2d.Common() KernelX = common.KernelX() KernelY = common.KernelY() input_channels = common.InputCount() output_channels = common.OutputCount() label += "\nshape:" + str(input_channels) + "*" + str(output_channels) \ + "*" + str(KernelX) + "*" + str(KernelY) if op_type != OpType.OpType.Input: node = pydot.Node(name, label=label, shape="egg", color='blue') dot.add_node(node) ts_num = net.TensorNameLength() for idx in range(ts_num): ts_name = net.TensorName(idx) name = "tensor_" + str(idx) label = ts_name node = dot.get_node(name) node = pydot.Node(name, label=label, shape="record", color='red') dot.add_node(node) for idx in range(op_num): op = net.Oplists(idx) name_op = "op_" + str(idx) input_len = op.InputIndexesLength() output_len = op.OutputIndexesLength() for idx_ts in range(input_len): name_tensor = "tensor_" + str(op.InputIndexes(idx_ts)) add_edge(dot, name_tensor, name_op) for idx_ts in range(output_len): name_tensor = "tensor_" + str(op.OutputIndexes(idx_ts)) add_edge(dot, name_op, name_tensor) return dot
def _check_pydot(): try: # Attempt to create an image of a blank graph # to check the pydot/graphviz installation. pydot.Dot.create(pydot.Dot()) return True except Exception: # pylint: disable=broad-except # pydot raises a generic Exception here, # so no specific class can be caught. return False
def test_create_simple_graph_with_node(self): g = pydot.Dot() g.set_type('digraph') node = pydot.Node('legend') node.set("shape", 'box') g.add_node(node) node.set('label', 'mine') self.assertEqual(g.to_string(), 'digraph G {\nlegend [label=mine, shape=box];\n}\n')
def check_graphviz(): """Returns True if both PyDot and Graphviz are available.""" if not check_pydot(): return False try: # Attempt to create an image of a blank graph # to check the pydot/graphviz installation. pydot.Dot.create(pydot.Dot()) return True except (OSError, pydot.InvocationException): return False
def check_pydot(): """Returns True if PyDot and Graphviz are available.""" if pydot is None: return False try: # Attempt to create an image of a blank graph # to check the pydot/graphviz installation. pydot.Dot.create(pydot.Dot()) return True except OSError: return False
def writeDotImage(self, filename): """ Writes a image representation of the individual :param filename: the output file image """ if not HAVE_PYDOT: Util.raiseException("You must install Pydot to use this feature !") graph = pydot.Dot() self.writeDotGraph(graph) graph.write_jpeg(filename, prog='dot')
def check_pydot(): """check whehter pydot is ready or not""" if pydot is None: return False try: # Attempt to create an image of a blank graph # to check the pydot/graphviz installation. pydot.Dot.create(pydot.Dot()) return True except OSError: return False
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: Util.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 dfs(initial_state): graph = pydot.Dot(graph_type='digraph', label="8 Puzzle State Space (" "DFS) \n Aashish Jangam \n " "CE 4th Year \n Roll: 17", fontsize="30", color="red", fontcolor="black", style="filled", fillcolor="black") start_node = Puzzle(initial_state, None, None, 0) if start_node.goal_test(): return start_node.find_solution() s = Stack() s.push(start_node) explored = [] print("The starting node is \ndepth=%d\n" % start_node.depth) print(start_node.display()) while not (s.isEmpty()): node = s.pop() print("the node selected to expand is\n") print("depth=%d\n" % node.depth) print(node.display()) explored.append(node.state) graph.add_node(node.graph_node) if node.parent: graph.add_edge( pydot.Edge(node.parent.graph_node, node.graph_node, label=str(node.action))) if node.depth < 5: children = node.generate_child() print("the children nodes of this node are\n") for child in children: if child.state not in explored: print("depth=%d\n" % child.depth) print(child.display()) if child.goal_test(): print("This is the goal state") graph.add_node(child.graph_node) graph.add_edge( pydot.Edge(child.parent.graph_node, child.graph_node, label=str(child.action))) draw_legend(graph) graph.write_png('solution.png') return child.find_solution() s.push(child) else: print( "the depth has exceeded its limit, so we don't expand this node.\n" ) return
def model_to_dot(model, rankdir='TB'): """I stole this from Keras, then hacked Returns: A `pydot.Dot` instance representing the lwtnn model. """ dot = pydot.Dot() dot.set('rankdir', rankdir) dot.set('concentrate', True) dot.set_node_defaults(shape='record') nodes = model['nodes'] layers = model['layers'] # Create graph nodes. for num, lwtnn_node in enumerate(nodes): layer_type = lwtnn_node['type'] shape = 'ellipse' if layer_type in ['feed_forward', 'time_distributed', 'sequence']: layer = layers[lwtnn_node['layer_index']] label = layer['architecture'] if label == 'dense': if layer['bias']: label += ' ({})'.format(len(layer['bias'])) label += '\n {}'.format(str_from_activation(layer)) else: label = str_from_activation(layer) elif label in ['lstm', 'gru']: label += ' ({})'.format(comps_as_string(layer)) elif layer_type == 'input': shape = 'rectangle' in_node = model['inputs'][lwtnn_node['sources'][0]] label = '{}\n({})'.format(in_node['name'], len(in_node['variables'])) elif layer_type == 'input_sequence': shape = 'rectangle' in_node = model['input_sequences'][lwtnn_node['sources'][0]] label = '{}\n({})'.format(in_node['name'], len(in_node['variables'])) else: label = layer_type dot_node = pydot.Node(str(num), label=label, shape=shape) dot.add_node(dot_node) # Connect nodes with edges. for dest_node, node in enumerate(nodes): if node['type'] in ['input_sequence', 'input']: continue for source_node in node['sources']: dot.add_edge(pydot.Edge(str(source_node), str(dest_node))) return dot
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
def makegraphicaltree(self, dot=None, edgeLabels=True): if not dot: dot = pydot.Dot() dot.add_node(pydot.Node(self.ID, label=repr(self), shape=self.shape)) label = edgeLabels and len(self.children) - 1 for i, c in enumerate(self.children): c.makegraphicaltree(dot, edgeLabels) edge = pydot.Edge(self.ID, c.ID) if label: edge.set_label(str(i)) dot.add_edge(edge) #Workaround for a bug in pydot 1.0.2 on Windows: #dot.set_graphviz_executables({'dot': r'C:\Program Files\Graphviz2.38\bin\dot.exe'}) return dot