def render_bb(bb, is_entry, is_terminal): dot = hex(id(bb)) + ':\l\l' for ins in bb.instruction_iter(): dot += ins.mnemonic.ljust(22) if ins.is_control_flow() or ins.has_xref(): dot += hex(id(ins.argval)) elif ins.arg is not None: dot += str(ins.arg) dot += '\l' if not is_entry and not is_terminal: return pydotplus.Node(hex(id(bb)), label=dot, shape='box', fontname='Consolas') if is_entry: return pydotplus.Node(hex(id(bb)), label=dot, shape='box', style='filled', color='cyan', fontname='Consolas') return pydotplus.Node(hex(id(bb)), label=dot, shape='box', style='filled', color='orange', fontname='Consolas')
def Visualize_Optimal_Partitions(Partitions,edge_list,node_list): global colors graph = pydot.Dot(graph_type = 'digraph', nodesep = .5) graph.set_node_defaults(style = "filled",shape = "rect",fontsize = "20.0") graph.set_edge_defaults(color = 'blue', arrowhead = "vee") temp_dict = {} count = 0 #Highlight Groups of Two Input Gates mapped to same LUT for i in Partitions: for j in i: temp_dict[j] = pydot.Node(j, color = colors[count]) graph.add_node(temp_dict[j]) count+= 1 #base/input nodes highlighted in grey color for i in node_list: if i[:3] not in Operators and i[:2] not in Operators: temp_dict[i] = pydot.Node(i, color= u'#DCDCDC') graph.add_node(temp_dict[i]) #Add edges for i in edge_list: graph.add_edge(pydot.Edge(temp_dict[i[0]],temp_dict[i[1]])) #Store result in a file graph.write_png('partion_graph.png')
def bpmn_diagram_to_png(bpmn_diagram, file_name): """ Create a png picture for given diagram :param bpmn_diagram: an instance of BPMNDiagramGraph class, :param file_name: name of generated file. """ g = bpmn_diagram.diagram_graph graph = pydotplus.Dot() for node in g.nodes(data=True): if node[1].get(consts.Consts.type) == consts.Consts.task: n = pydotplus.Node(name=node[0], shape="box", style="rounded", label=node[1].get(consts.Consts.node_name)) elif node[1].get(consts.Consts.type) == consts.Consts.exclusive_gateway: n = pydotplus.Node(name=node[0], shape="diamond", label=node[1].get(consts.Consts.node_name)) else: n = pydotplus.Node(name=node[0], label=node[1].get(consts.Consts.node_name)) graph.add_node(n) for edge in g.edges(data=True): e = pydotplus.Edge(src=edge[2].get(consts.Consts.source_ref), dst=edge[2].get(consts.Consts.target_ref), label=edge[2].get(consts.Consts.name)) graph.add_edge(e) graph.write(file_name + ".png", format='png')
def visiualization(lists): g = pydotplus.Dot(graph_type='digraph') i = 0 for item in lists: #不同node强制用不同的名字 node_name = item.name if 'leaf' in node_name and item.node['val'] != -1: node_name = "leaf" + str(i) + "\n" + str(item.node['val']) i += 1 node = pydotplus.Node(node_name) if item.node['property'] == 'internal': node.set('shape', 'diamond') else: node.set('shape', 'box') father_node_name = item.node['father'] if father_node_name != 'root': father_node_name = item.node['father'].name father_node = pydotplus.Node(father_node_name) edge = pydotplus.Edge(father_node_name, node_name) if 'ft_val' in list(item.node.keys()): edge.set('label', item.node['ft_val']) g.add_node(node) g.add_node(father_node) g.add_edge(edge) g.write("dt-tree.png", format='png') import os os.system("eog dt-tree.png")
def render_to_graphviz(self, background_graph=None): if background_graph is None: graph = pydotplus.graphviz.Dot(graph_type='digraph', rankdir='LR') else: graph = pydotplus.graphviz.graph_from_dot_data(background_graph.render_to_graphviz()) for node in graph.get_nodes(): node.set_color('#cccccc') node.set_fontcolor('#cccccc') for edge in graph.get_edges(): edge.set_color('#cccccc') edge.set_fontcolor('#cccccc') edge.set_label(' ') for edge in self.edges: node_0 = edge.node_0 nodes = graph.get_node(node_0.address_id) if len(nodes) > 0: graph_node_0 = nodes[0] else: graph_node_0 = pydotplus.Node(node_0.address_id) graph.add_node(graph_node_0) graph_node_0.set_style('filled') graph_node_0.set_fillcolor(node_0.color) graph_node_0.set_color('black') graph_node_0.set_fontcolor('black') color_factor = 0.75 * (math.exp(1. - node_0.weight) - 1.) / (math.e - 1.) graph_node_0.set_penwidth(max(0.1, 4 * (1 - color_factor))) node_1 = edge.node_1 nodes = graph.get_node(node_1.address_id) if len(nodes) > 0: graph_node_1 = nodes[0] else: graph_node_1 = pydotplus.Node(node_1.address_id) graph.add_node(graph_node_1) graph_node_1.set_style('filled') graph_node_1.set_fillcolor(node_1.color) graph_node_1.set_color('black') graph_node_1.set_fontcolor('black') color_factor = 0.75 * (math.exp(1. - node_1.weight) - 1.) / (math.e - 1.) graph_node_1.set_penwidth(max(0.25, 5 * (1 - color_factor))) edges = graph.get_edge(node_0.address_id, node_1.address_id) if len(edges) > 0: graph_edge = edges[0] else: graph_edge = pydotplus.Edge(graph_node_0, graph_node_1, weight=max(edge.weight, 1e-3)) # pydotplus fails with extremely small weights graph.add_edge(graph_edge) # if background_graph is None: graph_edge.set_label('\"{:,.3f}\"'.format(edge.weight)) color_factor = 0.75 * (math.exp(1. - edge.weight) - 1.) / (math.e - 1.) graph_edge.set_color(util.rgb_to_hex((color_factor, color_factor, color_factor))) graph_edge.set_fontcolor('black') # else: # graph_edge.set_color('black') # graph_edge.set_fontcolor('black') return graph.to_string()
def get_pydot_graph(caffe_net, rankdir, label_edges=True): """Create a data structure which represents the `caffe_net`. Parameters ---------- caffe_net : object rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. label_edges : boolean, optional Label the edges (default is True). Returns ------- pydot graph object """ pydot_graph = pydot.Dot(caffe_net.name, graph_type='digraph', rankdir=rankdir) pydot_nodes = {} pydot_edges = [] for layer in caffe_net.layer: node_label = get_layer_label(layer, rankdir) node_name = "%s_%s" % (layer.name, layer.type) if (len(layer.bottom) == 1 and len(layer.top) == 1 and layer.bottom[0] == layer.top[0]): # We have an in-place neuron layer. pydot_nodes[node_name] = pydot.Node(node_label, **NEURON_LAYER_STYLE) else: layer_style = LAYER_STYLE_DEFAULT layer_style['fillcolor'] = choose_color_by_layertype(layer.type) pydot_nodes[node_name] = pydot.Node(node_label, **layer_style) for bottom_blob in layer.bottom: pydot_nodes[bottom_blob + '_blob'] = pydot.Node('%s' % bottom_blob, **BLOB_STYLE) edge_label = '""' pydot_edges.append({'src': bottom_blob + '_blob', 'dst': node_name, 'label': edge_label}) for top_blob in layer.top: pydot_nodes[top_blob + '_blob'] = pydot.Node('%s' % (top_blob)) if label_edges: edge_label = get_edge_label(layer) else: edge_label = '""' pydot_edges.append({'src': node_name, 'dst': top_blob + '_blob', 'label': edge_label}) # Now, add the nodes and edges to the graph. for node in pydot_nodes.values(): pydot_graph.add_node(node) for edge in pydot_edges: pydot_graph.add_edge( pydot.Edge(pydot_nodes[edge['src']], pydot_nodes[edge['dst']], label=edge['label'])) return pydot_graph
def to_pydot(viz_dag, graph_attr=None, node_attr=None, edge_attr=None): node_groups = {} for name, data in viz_dag.nodes(data=True): group = data.get('_group') node_groups.setdefault(group, []).append(name) edge_groups = {} for name1, name2, data in viz_dag.edges(data=True): group = data.get('_group') edge_groups.setdefault(group, []).append((name1, name2)) viz_dot = pydotplus.Dot() if graph_attr is not None: for k, v in six.iteritems(graph_attr): viz_dot.set(k, v) if node_attr is not None: viz_dot.set_node_defaults(**node_attr) if edge_attr is not None: viz_dot.set_edge_defaults(**edge_attr) for group, names in six.iteritems(node_groups): if group is None: continue c = pydotplus.Subgraph('cluster_' + str(group)) for name in names: node = pydotplus.Node(name) for k, v in six.iteritems(viz_dag.node[name]): if not k.startswith("_"): node.set(k, v) c.add_node(node) for name1, name2 in edge_groups.get(group, []): edge = pydotplus.Edge(name1, name2) c.add_edge(edge) c.obj_dict['label'] = str(group) viz_dot.add_subgraph(c) for name in node_groups.get(None, []): node = pydotplus.Node(name) for k, v in six.iteritems(viz_dag.nodes[name]): if not k.startswith("_"): node.set(k, v) viz_dot.add_node(node) for name1, name2 in edge_groups.get(None, []): edge = pydotplus.Edge(name1, name2) viz_dot.add_edge(edge) return viz_dot
def bpmn_to_graph(bpmn_graph): """ Transform given bpmn graph to a graph object that can be visualized. Parameters ---------- bpmn_graph: Graph BPMN graph. Returns ---------- pydot_plus_graph: pydotplus.Dot Representation of the graph that can be visualized. """ pydot_plus_graph = pydotplus.Dot() pydot_plus_node_id_dict = dict() for node in bpmn_graph.get_nodes(): id_with_space = add_last_space(node.id) if node.type == NodeType.START_EVENT: n = pydotplus.Node(name=id_with_space, label=add_last_space(''), shape='circle', fillcolor='green') elif node.type == NodeType.END_EVENT: n = pydotplus.Node(name=id_with_space, label=add_last_space(''), shape='circle', fillcolor='red') elif node.type == NodeType.TASK: n = pydotplus.Node(name=id_with_space, label=add_last_space(node.label), shape='box') elif node.type == NodeType.PARALLEL_GATEWAY: n = pydotplus.Node(name=id_with_space, label=add_last_space('+'), shape='diamond') elif node.type == NodeType.EXCLUSIVE_GATEWAY: n = pydotplus.Node(name=id_with_space, label=add_last_space('x'), shape='diamond') else: raise TypeError( f'Node of type "{node.type}" is not expected to be in a BPMN graph.' ) pydot_plus_node_id_dict[node.id] = n pydot_plus_graph.add_node(n) for edge in bpmn_graph.get_edges(): e = pydotplus.Edge(src=pydot_plus_node_id_dict[edge.source_node.id], dst=pydot_plus_node_id_dict[edge.target_node.id]) pydot_plus_graph.add_edge(e) return pydot_plus_graph
def plot(self): fig = pydotplus.Dot(graph_name=self.conf['pipeline']['name'], rankdir="LR", labelloc='b', labeljust='r', ranksep=1) fig.set_node_defaults(shape='square') modules = [] for module in self.conf['modules']: if 'input_file' in module: modules.append( pydotplus.Node( name='input_file', texlbl='Input file\n' + module['input_file'], label='Input file\n' + module['input_file'])) label = '' if 'params' in module: for param in module['params']: if param['type'] == 'collection': label += 'param ' + param[ 'name'] + ' values: [' + ','.join( param['values']) + ']\n' else: label += 'param ' + param['name'] + ' range: [' + str( param['start']) + ', ' + str( param['step_size']) + ', ' + str( param['end']) + ']\n' modules.append( pydotplus.Node(name=module['name'], texlbl=module['name'], label=module['name'] + '\ntype: ' + module['type'] + '\n' + label + 'instances: ' + str(module['instances']))) if 'output_file' in module: modules.append( pydotplus.Node( name='output_file', texlbl='Output file' + module['output_file'], label='Output file\n' + module['output_file'])) for node in modules: fig.add_node(node) for i in range(len(modules) - 1): fig.add_edge(pydotplus.Edge(modules[i], modules[i + 1])) fig.write_png(self.conf['pipeline']['name'] + '.png')
def add_elements(g, toks, defaults_graph=None, defaults_node=None, defaults_edge=None): if defaults_graph is None: defaults_graph = {} if defaults_node is None: defaults_node = {} if defaults_edge is None: defaults_edge = {} for elm_idx, element in enumerate(toks): if isinstance(element, (pydotplus.Subgraph, pydotplus.Cluster)): add_defaults(element, defaults_graph) g.add_subgraph(element) elif isinstance(element, pydotplus.Node): add_defaults(element, defaults_node) g.add_node(element) elif isinstance(element, pydotplus.Edge): add_defaults(element, defaults_edge) g.add_edge(element) elif isinstance(element, ParseResults): for e in element: add_elements(g, [e], defaults_graph, defaults_node, defaults_edge) elif isinstance(element, DefaultStatement): if element.default_type == 'graph': default_graph_attrs = pydotplus.Node('graph', **element.attrs) g.add_node(default_graph_attrs) elif element.default_type == 'node': default_node_attrs = pydotplus.Node('node', **element.attrs) g.add_node(default_node_attrs) elif element.default_type == 'edge': default_edge_attrs = pydotplus.Node('edge', **element.attrs) g.add_node(default_edge_attrs) defaults_edge.update(element.attrs) else: raise ValueError("Unknown DefaultStatement: %s " % element.default_type) elif isinstance(element, P_AttrList): g.obj_dict['attributes'].update(element.attrs) else: raise ValueError("Unknown element statement: %r" % element)
def plot_tree(self,plot_name): graph = pydot.Dot(graph_type='graph') for parent_node in self.nodes: # if i see each node as parent, i need to find its children for child_node in self.nodes: if parent_node.name == child_node.parent: # less than is always on the left p = pydot.Node(name = parent_node.name,label = self.__make_text(parent_node), style="filled", fillcolor=self.__get_color(parent_node)) c = pydot.Node(name = child_node.name,label = self.__make_text(child_node), style="filled",fillcolor=self.__get_color(child_node)) graph.add_node(p) graph.add_node(c) graph.add_edge(pydot.Edge(p,c)) graph.write_pdf(plot_name + '.pdf')
def _tree_to_graph(t, G, ids, token_ids, parent=None): ids.append(ids[-1] + 1 if ids else 0) this_id = ids[-1] if parent is not None: G.add_edge(pdp.Edge(parent, this_id)) if is_tree(t): label = escape_label(str(t.label())) tooltip = '"%s"' % t.pformat(margin=30) G.add_node(pdp.Node(this_id, label=label, tooltip=tooltip)) for st in t[:]: _tree_to_graph(st, G, ids, token_ids, parent=this_id) else: label = escape_label(str(t)) G.add_node(pdp.Node(this_id, label=label, tooltip=label, shape='box')) token_ids.append(this_id)
def get_rdf_neighbors_as_dot(preds, succs, source): graph = pydotplus.Dot(graph_type='digraph') s = pydotplus.Node(source, label=source) for succ in succs: t = pydotplus.Node(str(succ), label=succ) e = pydotplus.Edge(source, t) graph.add_edge(e) for pred in preds: t = pydotplus.Node(str(pred), label=pred) e = pydotplus.Edge(t, source) graph.add_edge(e) return graph
def isCyclicUtil(self, v, visited, recStack, graph): # Mark current node as visited and # adds to recursion stack visited[v] = True recStack[v] = True global cycleAt # Recur for all neighbours # if any neighbour is visited and in # recStack then graph is cyclic for neighbour in self.graph[v]: if visited[neighbour] == False: if self.isCyclicUtil(neighbour, visited, recStack, graph) == True: if cycleAt != -1: graph.del_edge(v + 1, neighbour + 1) graph.add_edge(pydotplus.Edge(v + 1 , neighbour + 1 , color = 'red')) graph.add_node(pydotplus.Node(neighbour + 1 , label = "Transaction_" + str(neighbour + 1) , shape = 'ellipse' , color = 'black' , style = 'filled' , fillcolor = 'magenta' , fontname = 'Consolas' , fontcolor = 'black')) if cycleAt == v: cycleAt = -1 return True elif recStack[neighbour] == True: cycleAt = neighbour graph.del_edge(v + 1, neighbour + 1) graph.add_edge(pydotplus.Edge(v + 1 , neighbour + 1 , color = 'red')) graph.add_node(pydotplus.Node(neighbour + 1 , label = "Transaction_" + str(neighbour + 1) , shape = 'ellipse' , color = 'black' , style = 'filled' , fillcolor = 'magenta' , fontname = 'Consolas' , fontcolor = 'black')) return True # The node needs to be poped from # recursion stack before function ends recStack[v] = False return False
def write_dot(self, output_path): """Write a graphviz .dot representation of the graph to output_path. """ # Write the graph ourselves to output statements as edge labels dot = pydotplus.Dot('', graph_type='digraph', strict=False) dot.set_edge_defaults(labeljust='l') added_nodes = set() scope_colors = defaultdict(lambda: node_scope_colors[len( scope_colors) % len(node_scope_colors)]) for src, dest, data in self.graph.edges_iter(data=True): src_id = str(id(src)) dest_id = str(id(dest)) if src_id not in added_nodes: added_nodes.add(src_id) dot.add_node( pydotplus.Node(src_id, label=str(src), color=scope_colors[src.scope])) if dest_id not in added_nodes: added_nodes.add(dest_id) dot.add_node( pydotplus.Node(dest_id, label=str(dest), color=scope_colors[src.scope])) stmts = data['stmts'] condition = data.get('condition') label = '' if condition is not None: label = 'if {}:\n'.format(condition) label += '\n'.join((str(s) for s in stmts)) if label: dot.add_edge(pydotplus.Edge(src_id, dest_id, label=label)) else: dot.add_edge(pydotplus.Edge(src_id, dest_id)) with open(output_path, mode='wt', encoding='utf-8') as f: f.write(dot.to_string())
def threadTree(self, graph, seen=None, col=0): colors = ('red', 'green', 'blue', 'yellow', 'magenta', 'cyan') if not seen: seen = [] if self in seen: return seen.append(self) new = not graph.get_node(self.ID) if new: graphnode = pydot.Node(self.ID, label=repr(self), shape=self.shape) graphnode.set_style('dotted') graph.add_node(graphnode) label = len(self.next) - 1 for i, c in enumerate(self.next): if not c: return col = (col + 1) % len(colors) col = 0 # FRT pour tout afficher en rouge color = colors[col] c.threadTree(graph, seen, col) edge = pydot.Edge(self.ID, c.ID) edge.set_color(color) edge.set_arrowsize('.5') # Les arrêtes correspondant aux coutures ne sont pas prises en compte # pour le layout du graphe. Ceci permet de garder l'arbre dans sa représentation # "standard", mais peut provoquer des surprises pour le trajet parfois un peu # tarabiscoté des coutures... # En commantant cette ligne, le layout sera bien meilleur, mais l'arbre nettement # moins reconnaissable. edge.set_constraint('false') if label: edge.set_taillabel(str(i)) edge.set_labelfontcolor(color) graph.add_edge(edge) return graph
def ExportGraphFunc(): global G, TransformationNumber if G == None: return Nodes = G.get_node_list() Edges = G.get_edge_list() GExport = pydotplus.Dot(graph_type="graph") for N in Nodes: name = N.get_name() lbl = N.get("label") newnode = pydotplus.Node(name, label=lbl) GExport.add_node(newnode) for E in Edges: sorc = E.get_source() dest = E.get_destination() newedge = pydotplus.Edge(sorc, dest) GExport.add_edge(newedge) GExport.write("{}.{}".format("Exported" + str(TransformationNumber), 'dot'), format='dot')
def gen_sub_block_graph(block_port_obj): nonlocal hblock_port_name, sblock_name, sblock_port_name if len(block_port_obj) == 2: sblock_name = block_port_obj[0].local.name sblock_port_name = sblock_name + '_' + block_port_obj[1].local.name sblock_port_label = block_port_obj[1].local.name if not file_graph.get_subgraph('cluster_' + sblock_name): sblock_graph = pydotplus.Cluster(graph_name=sblock_name, graph_type='digraph', label=sblock_name) file_graph.add_subgraph(sblock_graph) sblock_graph = file_graph.get_subgraph('cluster_' + sblock_name)[0] if not sblock_graph.get_node(sblock_port_name): sblock_port = pydotplus.Node(name=sblock_port_name, label=sblock_port_label, shape='circle') sblock_graph.add_node( sblock_port ) # Hopefully, this updates the file_graph as well? Yes, seems to. else: hblock_port_name = block_port_obj[0].local.name
def visit_non_leaf(self, node): print("---visit_non_leaf---") node_id = "%s %s" % (self.name_node(), node.__class__.__name__) parent_node = pydotplus.Node(node_id, label=node.__class__.__name__ + " " + node.__repr__(), style="filled", fillcolor="#55B7C2") print("agrega : ", node_id) for field in getattr(node, "_fields"): value = getattr(node, field, None) if isinstance(value, list): for item in value: if isinstance(item, AST): child_node = self.visit(item) print("nombresito : ", child_node.get_name()) #self.graph.del_node(child_node) #if (child_node.get_name().split(" ")[1][:-1] not in self.excluidos): self.graph.add_edge( pydotplus.Edge(parent_node, child_node)) elif isinstance(value, AST): child_node = self.visit(value) print("arco : ", child_node.__repr__()) #if (child_node.get_name().split(" ")[1][:-1] not in self.excluidos): self.graph.add_edge(pydotplus.Edge(parent_node, child_node)) print("returning!!") return parent_node
def _create_base_dot(self, subheading): dot = pydot.Dot("NOC", graph_type="digraph", strict=True) dot.set_prog("neato") dot.set_node_defaults(shape="none", fontsize=14, margin=0, fontname="Arial") dot.set_edge_defaults(fontsize=13, fontname="Arial") # dot.set_page('11.7,8.3!') # dot.set_margin(0.5) # dot.set_ratio('fill') dot.set_rankdir("LR") dot.set_fontname("Arial") dot.set_nodesep(0.3) dot.set_splines("spline") sg = pydot.Cluster() # 'physical', label='Physical') # sg.set_color('gray80') sg.set_style("invis") # sg.set_labeljust('l') dot.add_subgraph(sg) title = pydot.Node( "title", shape="none", label=self._title_label(self.opts.get("name"), subheading), ) title.set_pos("0,0!") title.set_fontsize(18) dot.add_node(title) return dot, sg
def test_numeric_node_id(self): # 重设图 self._reset_graphs() # 添加节点 self.graph_directed.add_node(pydotplus.Node(1)) # 验证图的节点的第一个元素名称是1 self.assertEqual(self.graph_directed.get_nodes()[0].get_name(), '1')
def _attach_attribute_annotation(node, record): # Adding a node to show all attributes attributes = list((attr_name, value) for attr_name, value in record.attributes if attr_name not in PROV_ATTRIBUTE_QNAMES) if not attributes: return # No attribute to display # Sort the attributes. attributes = sorted_attributes(record.get_type(), attributes) ann_rows = [ANNOTATION_START_ROW] ann_rows.extend( ANNOTATION_ROW_TEMPLATE % (attr.uri, escape(six.text_type(attr)), ' href=\"%s\"' % value.uri if isinstance(value, Identifier) else '', escape( six.text_type(value) if not isinstance(value, datetime) else six.text_type(value.isoformat()))) for attr, value in attributes) ann_rows.append(ANNOTATION_END_ROW) count[3] += 1 annotations = pydot.Node('ann%d' % count[3], label='\n'.join(ann_rows), **ANNOTATION_STYLE) dot.add_node(annotations) dot.add_edge(pydot.Edge(annotations, node, **ANNOTATION_LINK_STYLE))
def _add_node(record): count[0] += 1 node_id = 'n%d' % count[0] if use_labels: if record.label == record.identifier: node_label = '"%s"' % six.text_type(record.label) else: # Fancier label if both are different. The label will be # the main node text, whereas the identifier will be a # kind of suptitle. node_label = ('<%s<br />' '<font color="#333333" point-size="10">' '%s</font>>') node_label = node_label % (six.text_type( record.label), six.text_type(record.identifier)) else: node_label = '"%s"' % six.text_type(record.identifier) uri = record.identifier.uri style = DOT_PROV_STYLE[record.get_type()] node = pydot.Node(node_id, label=node_label, URL='"%s"' % uri, **style) node_map[uri] = node dot.add_node(node) if show_element_attributes: _attach_attribute_annotation(node, rec) return node
async def gold_exchange(self): channel = self.get_channel(channel_id) for elem in self.players: if len(elem.thieves) > 0: elem.gold = elem.gold // 2 incomes = [] for i in range(len(self.players)): incomes.append(0) for i in range(len(self.players)): for thief in self.players[i].thieves: incomes[thief.id - 1] = self.players[i].gold // len(self.players[i].thieves) for i in range(len(self.players)): self.players[i].gold += incomes[i] graph = pydotplus.Dot(graph_type="digraph") for elem in self.players: node = pydotplus.Node(elem.user.name, style="filled", fillcolor="blue") graph.add_node(node) for elem in self.players: for thief in elem.thieves: edge = pydotplus.Edge(thief.user.name, elem.user.name) graph.add_edge(edge) graph.write_png('day' + str(self.day) + '.png') await channel.send(file=discord.File('day' + str(self.day) + '.png')) for elem in self.players: elem.thieves = []
def test_numeric_node_id(self): self._reset_graphs() self.graph_directed.add_node(pydotplus.Node(1)) self.assertEqual(self.graph_directed.get_nodes()[0].get_name(), '1')
def test_keyword_node_id(self): self._reset_graphs() self.graph_directed.add_node(pydotplus.Node('node')) self.assertEqual(self.graph_directed.get_nodes()[0].get_name(), 'node')
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 -------- >>> K5 = nx.complete_graph(5) >>> P = nx.nx_pydot.to_pydot(K5) Notes ----- """ import pydotplus # 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.name graph_defaults=N.graph.get('graph',{}) if name is '': P = pydotplus.Dot('', graph_type=graph_type, strict=strict, **graph_defaults) else: P = pydotplus.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(data=True): str_nodedata=dict((k,make_str(v)) for k,v in nodedata.items()) p=pydotplus.Node(make_str(n),**str_nodedata) P.add_node(p) if N.is_multigraph(): for u,v,key,edgedata in N.edges(data=True,keys=True): str_edgedata=dict((k,make_str(v)) for k,v in edgedata.items()) edge=pydotplus.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(data=True): str_edgedata=dict((k,make_str(v)) for k,v in edgedata.items()) edge=pydotplus.Edge(make_str(u),make_str(v),**str_edgedata) P.add_edge(edge) return P
def _add_actioncondition(self, state, conditionset, type, new_y, cond1, cond2): #cond1 = i >= list(self.__states.keys()).index(self.__active_state) #cond2 = j > list(self.__states[state]['conditionsets'].keys()).index(self.__active_conditionset) or i > list(self.__states.keys()).index(self.__active_state) cond4 = conditionset == self.__active_conditionset and state == self.__active_state cond5 = self.__states[state]['conditionsets'].get(conditionset) is not None color_enter = "gray" if (cond1 and cond2 and cond5) or (type == 'actions_enter' and self.__states[state].get('enter') is False and cond4 and cond5)\ else "chartreuse3" if cond4 else "indianred2" color_stay = "gray" if (cond1 and cond2 and cond5) or (type == 'actions_stay' and self.__states[state].get('stay') is False and cond4 and cond5)\ else "chartreuse3" if cond4 else "indianred2" label = 'first enter' if type == 'actions_enter' else 'staying at state' position = '{},{}!'.format(0.65, new_y) color = color_enter if label == 'first enter' else color_stay #self._log_debug('adding enterstate for state {}/set {}: {}. Enter = {}, Stay = {}. Cond 1 {}, 2 {}, 4 {}. Color: {}', state, conditionset, type, self.__states[state].get('enter'), self.__states[state].get('stay'), cond1, cond2, cond4, color) self.__nodes['{}_{}_state_{}'.format(state, conditionset, type)] = pydotplus.Node('{}_{}_state_{}'.format(state, conditionset, type), style="filled", fillcolor=color, shape="diamond", label=label, pos=position) self.__graph.add_node(self.__nodes['{}_{}_state_{}'.format(state, conditionset, type)]) if self.__nodes.get('{}_{}_state_actions_enter_edge'.format(state, conditionset)) is None: self.__nodes['{}_{}_state_{}_edge'.format(state, conditionset, type)] = pydotplus.Edge(self.__nodes['{}_{}'.format(state, conditionset)], self.__nodes['{}_{}_state_{}'.format(state, conditionset, type)], style='bold', color='blue', taillabel=" True") self.__graph.add_edge(self.__nodes['{}_{}_state_{}_edge'.format(state, conditionset, type)]) else: self.__graph.add_edge(pydotplus.Edge(self.__nodes['{}_{}_state_actions_enter'.format(state, conditionset)], self.__nodes['{}_{}_state_actions_stay'.format(state, conditionset)], style='bold', color='blue', label="False ")) self.__graph.add_edge(pydotplus.Edge(self.__nodes['{}_{}_state_{}'.format(state, conditionset, type)], self.__nodes['{}_{}_{}'.format(state, conditionset, type)], style='bold', color='blue', taillabel=" True")) try: if type == 'actions_enter': self.__nodes['{}_{}_actions_enter'.format(state, conditionset)].obj_dict['attributes']['fillcolor'] = color except Exception: pass try: if type == 'actions_stay': self.__nodes['{}_{}_actions_stay'.format(state, conditionset)].obj_dict['attributes']['fillcolor'] = color except Exception: pass
def test_keyword_node_id_to_string_no_attributes(self): self._reset_graphs() self.graph_directed.add_node(pydotplus.Node('node')) self.assertEqual(self.graph_directed.get_nodes()[0].to_string(), '')
def plot(cls, root: BiNode, path): ''' 打印单颗树 (pydotplus + graphviz) brew install graphviz graphviz文档 https://graphviz.readthedocs.io/en/stable/manual.html graphviz官网 https://graphviz.gitlab.io/documentation/ pydotplus https://github.com/carlos-jenkins/pydotplus ''' if not root: return dot = pdp.Dot(graph_type='digraph') # graph = pdp.Graph(graph_type='digraph') dot.set_node_defaults(shape='box') # 遍历获取决策树的父子节点关系 nodes = cls.level_traversal(root) edges = cls.level_traversal(root, get_rel_pair=True) # 添加节点 for tree_node in nodes: node = pdp.Node(name=tree_node.id, label=tree_node.kwargs_to_str()) dot.add_node(node) # 添加边 for pair in edges: label='Y' if pair[0].left == pair[1] else 'N' edge = pdp.Edge(src=pair[0].id, dst=pair[1].id, label=label) dot.add_edge(edge) if path: dot.write(path, format='png') return dot.to_string()