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 add_edges(self, parent, children): for child in children: if isinstance(child, list): self.graph.add_edge(pydot.Edge(parent, child[0])) self.add_edges(child[0], child[1:]) # first item of tuple is root of subtree else: self.graph.add_edge(pydot.Edge(parent, child))
def visit_TypeNode(self, node): target = self.new_node(node) self.dot.add_node(target) if not self.InFuncDefn: self.DatGlobDic[node.ID] = node.typ for field in getattr(node, "_fields"): value = getattr(node, field, None) if isinstance(value, list): for item in value: if isinstance(item, ast.AST): self.visit(item) self.dot.add_edge(pgv.Edge(target, self.stack.pop())) elif (item is not None): #caso de ramas targetHijo = self.new_node(None, item, 'diamond') self.dot.add_node(targetHijo) self.dot.add_edge(pgv.Edge(target, targetHijo)) elif isinstance(value, ast.AST): self.visit(value) self.dot.add_edge(pgv.Edge(target, self.stack.pop())) elif (value is not None): #ramas... targetHijo = self.new_node(None, value, 'diamond') self.dot.add_node(targetHijo) self.dot.add_edge(pgv.Edge(target, targetHijo)) self.stack.append(target)
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 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 visit_Assign(self, node): target = self.new_node(node) self.dot.add_node(target) self.InAssign = True for field in getattr(node, "_fields"): value = getattr(node, field, None) #print("Field: ", field) #print("Value: ", value) if (field == "ID"): if self.InFuncDefn: if value not in self.DatFuncDic: print("Error Semantico!!! En la linea", node.lineno, "La variable ", value, " no está definida.") else: if value not in self.DatGlobDic: print("Error semantico!!! En la linea", node.lineno, "La variable ", value, " no está definida.") if isinstance(value, ast.AST): self.visit(value) self.dot.add_edge(pgv.Edge(target, self.stack.pop())) elif (value is not None): #ramas... targetHijo = self.new_node(None, value, 'diamond') self.dot.add_node(targetHijo) self.dot.add_edge(pgv.Edge(target, targetHijo)) self.InAssign = False self.stack.append(target)
def _add_actioncondition(self, state, conditionset, action_type, new_y, cond1, cond2): 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 \ (action_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 \ (action_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 action_type == 'actions_enter' else 'staying at state' position = '{},{}!'.format(0.63, new_y) color = color_enter if label == 'first enter' else color_stay self.__nodes['{}_{}_state_{}'.format(state, conditionset, action_type)] = \ pydotplus.Node('{}_{}_state_{}'.format(state, conditionset, action_type), style="filled", fillcolor=color, shape="diamond", label=label, pos=position) self.__graph.add_node(self.__nodes['{}_{}_state_{}'.format( state, conditionset, action_type)]) if self.__nodes.get('{}_{}_state_actions_enter_edge'.format( state, conditionset)) is None: self.__nodes['{}_{}_state_{}_edge'.format(state, conditionset, action_type)] = \ pydotplus.Edge(self.__nodes['{}_{}'.format(state, conditionset)], self.__nodes['{}_{}_state_{}'.format( state, conditionset, action_type)], style='bold', taillabel=" True", tooltip='first enter') self.__graph.add_edge(self.__nodes['{}_{}_state_{}_edge'.format( state, conditionset, action_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', label="False ")) self.__graph.add_edge( pydotplus.Edge( self.__nodes['{}_{}_state_{}'.format(state, conditionset, action_type)], self.__nodes['{}_{}_{}'.format(state, conditionset, action_type)], style='bold', taillabel=" True")) try: if action_type == 'actions_enter': self.__nodes['{}_{}_actions_enter'.format( state, conditionset)].obj_dict['attributes']['fillcolor'] = color except Exception: pass try: if action_type == 'actions_stay': self.__nodes['{}_{}_actions_stay'.format( state, conditionset)].obj_dict['attributes']['fillcolor'] = color except Exception: pass
def add_nodes_edges(self): i = 0 edge_seen_dict = {} # key = edge1_edge2 logger.info('[2] adding nodes, edges, #ofnodes={}'.format( len(self.parsed_frame_dict))) for fn in self.parsed_frame_dict: print('Frame# [{}]\r'.format(i), end='') i += 1 frame = self.parsed_frame_dict[fn] new_element_name = '\"{}\"'.format(frame.fn_name) tooltip_str = '{}{}{}{}'.format(frame.file_name, HTML_SEP, frame.fn_args, HTML_SEP) logger.debug('adding node={}'.format(new_element_name)) self.g.add_node( pydotplus.Node( new_element_name, id=new_element_name, penwidth=0, tooltip=tooltip_str, style="filled", fillcolor='cornflowerblue', #bgcolor='cornflowerblue', shape='box', margin=0, fontname="Consolas", #fontname="Courier New", fontsize=12.0, fontcolor='white')) for callee in frame.callees: if callee: new_tuple = ('\"{}\"'.format(frame.fn_name), '\"{}\"'.format(callee.fn_name)) key = '{}_{}'.format(frame.fn_name, callee.fn_name) if key not in edge_seen_dict: logger.debug('adding edge={}'.format(new_tuple)) self.g.add_edge( pydotplus.Edge( new_tuple, id='\"{}|{}\"'.format(new_tuple[0].strip('"'), new_tuple[1].strip('"')), color='grey', )) edge_seen_dict[key] = True for caller in frame.callers: new_tuple = ('\"{}\"'.format(caller.fn_name), '\"{}\"'.format(frame.fn_name)) key = '{}_{}'.format(caller.fn_name, frame.fn_name) if key not in edge_seen_dict: logger.debug('adding edge={}'.format(new_tuple)) self.g.add_edge( pydotplus.Edge( new_tuple, id='\"{}|{}\"'.format(new_tuple[0].strip('"'), new_tuple[1].strip('"')), color='grey', )) edge_seen_dict[key] = True
def visit_Retexp(self, node): target = self.new_node(node) self.dot.add_node(target) self.InRetex = True if not self.InFuncDefn: print("Error semantico!!!En la linea", node.lineno, " No se puede retornar un valor por fuera de una función.") for field in getattr(node, "_fields"): value = getattr(node, field, None) if isinstance(value, list): for item in value: if isinstance(item, ast.AST): self.visit(item) self.dot.add_edge(pgv.Edge(target, self.stack.pop())) elif (item is not None): #caso de ramas targetHijo = self.new_node(None, item, 'diamond') self.dot.add_node(targetHijo) self.dot.add_edge(pgv.Edge(target, targetHijo)) elif isinstance(value, ast.AST): self.visit(value) self.dot.add_edge(pgv.Edge(target, self.stack.pop())) elif (value is not None): #ramas... if value in self.DatFuncDic: if not ((self.DatFuncDic.get(value) == self.TipoFuncion)): print( "Error!!! Está intentando devolver un tipo de dato inválido en la función", self.nombrefuncion) if str.isdigit(str(value)) and self.TipoFuncion == "string": print( "Error semantico!!!En la linea", node.lineno, " Está intentando devolver un tipo de dato inválido en la función", self.nombrefuncion) if str.isdigit(str(value)) and self.TipoFuncion == "float": print( "Error semantico!!!En la linea", node.lineno, " Está intentando devolver un tipo de dato inválido en la función", self.nombrefuncion) temp = re.search( '((\d*\.\d+)|(\d+\.\d*)|([1-9]e\d+))(e[-+]?\d+)?', str(value)) if (temp is not None and self.TipoFuncion == "int"): print( "Error semantico!!!En la linea", node.lineno, "Está intentando devolver un tipo de dato inválido en la función", self.nombrefuncion) targetHijo = self.new_node(None, value, 'diamond') self.dot.add_node(targetHijo) self.dot.add_edge(pgv.Edge(target, targetHijo)) self.InRetex = False self.stack.append(target)
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 gen_connection_graph(file_graph, hblock_name, connection_obj): hblock_port_name = None sblock_name = None sblock_port_name = None link_name = None link_port_name = None 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 gen_link_graph(link_port_obj): nonlocal link_name, link_port_name link_name = link_port_obj[0].local.name link_port_name = link_name + '_' + link_port_obj[1].local.name link_port_label = link_port_obj[1].local.name gen_sub_block_graph(connection_obj.block_port.steps) gen_link_graph(connection_obj.link_port.steps) print('link name is: ', link_name) print('link port name is: ', link_port_name) if hblock_port_name: connection = pydotplus.Edge(hblock_port_name, link_port_name) else: connection = pydotplus.Edge(sblock_port_name, link_port_name) file_graph.add_edge(connection)
def __init__(self, root): os.environ[ "PATH"] += os.pathsep + GRAPHVIZ_BIN_PATH # allow for usage oh graphviz self.tree = pydot.Dot(graph_type='digraph') self.root = root self.tree.add_node(pydot.Node(self.root.value)) self.tree.add_edge( pydot.Edge(self.root.value, self.root.children[0].value)) self.tree.add_edge( pydot.Edge(self.root.value, self.root.children[1].value)) self.tree.write_png('output/test.png')
def test_graph_pickling(self): import pickle g = pydotplus.Graph() s = pydotplus.Subgraph("foo") g.add_subgraph(s) g.add_edge(pydotplus.Edge('A', 'B')) g.add_edge(pydotplus.Edge('A', 'C')) g.add_edge(pydotplus.Edge(('D', 'E'))) g.add_node(pydotplus.Node('node!')) self.assertEqual(type(pickle.dumps(g)), bytes)
def export_dot_node(graph, node): this = node.dot_node() graph.add_node(this) if node.left: left = export_dot_node(graph, node.left) graph.add_edge(pydot.Edge(this, left)) if node.right: right = export_dot_node(graph, node.right) graph.add_edge(pydot.Edge(this, right)) return this
def push_edge_stmt(str, loc, toks): tok_attrs = [a for a in toks if isinstance(a, P_AttrList)] attrs = {} for a in tok_attrs: attrs.update(a.attrs) e = [] if isinstance(toks[0][0], pydotplus.Graph): n_prev = pydotplus.frozendict(toks[0][0].obj_dict) else: n_prev = toks[0][0] + do_node_ports(toks[0]) if isinstance(toks[2][0], ParseResults): n_next_list = [[n.get_name()] for n in toks[2][0]] for n_next in [n for n in n_next_list]: n_next_port = do_node_ports(n_next) e.append(pydotplus.Edge(n_prev, n_next[0] + n_next_port, **attrs)) elif isinstance(toks[2][0], pydotplus.Graph): e.append( pydotplus.Edge(n_prev, pydotplus.frozendict(toks[2][0].obj_dict), **attrs)) elif isinstance(toks[2][0], pydotplus.Node): node = toks[2][0] if node.get_port() is not None: name_port = node.get_name() + ":" + node.get_port() else: name_port = node.get_name() e.append(pydotplus.Edge(n_prev, name_port, **attrs)) elif isinstance(toks[2][0], type('')): for n_next in [n for n in tuple(toks)[2::2]]: if isinstance(n_next, P_AttrList) or \ not isinstance(n_next[0], type('')): continue n_next_port = do_node_ports(n_next) e.append(pydotplus.Edge(n_prev, n_next[0] + n_next_port, **attrs)) n_prev = n_next[0] + n_next_port else: # UNEXPECTED EDGE TYPE pass return e
def visit_ExprLparen(self, node): target = self.new_node(node) self.dot.add_node(target) for field in getattr(node, "_fields"): value = getattr(node, field, None) temp = re.search('((\d*\.\d+)|(\d+\.\d*)|([1-9]e\d+))(e[-+]?\d+)?', str(value)) if isinstance(value, list): for item in value: if isinstance(item, ast.AST): self.visit(item) self.dot.add_edge(pgv.Edge(target, self.stack.pop())) elif (item is not None): #caso de ramas targetHijo = self.new_node(None, item, 'diamond') self.dot.add_node(targetHijo) self.dot.add_edge(pgv.Edge(target, targetHijo)) elif isinstance(value, ast.AST): self.visit(value) self.dot.add_edge(pgv.Edge(target, self.stack.pop())) elif (value is not None): #ramas... if self.InRetex: if value in self.DatFuncDic: if not (self.DatFuncDic.get(value) == self.TipoFuncion): print( "Error semantico!!!En la linea", node.lineno, "Está intentando devolver un tipo de dato inválido en la función", self.nombrefuncion) elif str.isdigit(str(value)): if not (self.TipoFuncion == "int"): print( "Error semantico!!!En la linea", node.lineno, "Está intentando devolver un tipo de dato inválido en la función", self.nombrefuncion) elif temp is not None: if not (self.TipoFuncion == "float"): print( "Error semantico!!!En la linea", node.lineno, "Está intentando devolver un tipo de dato inválido en la función", self.nombrefuncion) else: print("Error semantico!!! En la linea", node.lineno, "La variable ", value, " no está definida.") targetHijo = self.new_node(None, value, 'diamond') self.dot.add_node(targetHijo) self.dot.add_edge(pgv.Edge(target, targetHijo)) self.stack.append(target)
def create_model_image(di_graph, name, likelihood_function): """ Using a networkx's DAG (created based on the composite model or the amalgamated model), this function creates an image of the result of the Simple Genetic Algorithm using 'pydotplus' library. Args: di_graph : nx.DiGraph() It's a networkx's digraph representing the composite model or the amalgamated model name : STRING The name given in the variable 'a_name' on 'data_logic.data_input.py' likelihood_function: INT Indicates the likelihood function that is going to be used 1 = cotemporal, 2 = next_step_one, 3 = next_step_one_two Returns: PNG IMAGE An image with the result of the problem, saved on the root file """ if likelihood_function == 1: display_graph = pydot.Dot(graph_type='graph') else: display_graph = pydot.Dot(graph_type='digraph') nodes = di_graph.nodes() for node in nodes: display_graph.add_node( pydot.Node(node, penwidth="1.5", fontname="times-bold")) edges = di_graph.edges() if likelihood_function == 1: for edge in edges: if edge[0] < edge[1]: display_graph.add_edge( pydot.Edge(edge[0], edge[1], label=" " + str(di_graph[edge[0]][edge[1]]['weight']), color="black", penwidth="1.5")) else: for edge in edges: display_graph.add_edge( pydot.Edge(edge[0], edge[1], label=" " + str(di_graph[edge[0]][edge[1]]['weight']), color="black", penwidth="1.5")) display_graph.write_png("../" + name + ".png")
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 visit_Listaprograma(self, node): target = self.new_node(node) self.dot.add_node(target) for field in getattr(node, "_fields"): value = getattr(node, field, None) if isinstance(value, list): for item in value: if isinstance(item, ast.AST): self.visit(item) self.dot.add_edge(pgv.Edge(target, self.stack.pop())) elif (item is not None): #caso de ramas targetHijo = self.new_node(None, item, 'diamond') self.dot.add_node(targetHijo) self.dot.add_edge(pgv.Edge(target, targetHijo))
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 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 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 add_edges(self, parent, children, node_attributes): # TODO convert all items in children set to objects (with value + node_attributes attributes) # TODO convert children set to list (as order matters in left leaning red black BSTs) for child, attributes in zip_longest(children, node_attributes): if isinstance(child, tuple): color = attributes[0].edge_color if isinstance( attributes, tuple) else 'black' self.graph.add_edge(pydot.Edge(parent, child[0], color=color)) self.add_edges(child[0], child[1:], attributes[1:] if attributes else ()) # first item of tuple is root of subtree else: color = attributes.edge_color if attributes else 'black' self.graph.add_edge(pydot.Edge(parent, child, color=color))
def visit_IdList(self, node): target = self.new_node(node) self.dot.add_node(target) for field in getattr(node, "_fields"): value = getattr(node, field, None) if isinstance(value, list): for i in value: if (i is not None): if (self.pasecommandread): print("estoy en writeRead de read con:", i) existe = False if i in self.valoresEnteros: for j in self.valoresInt: if (j[0] == i): existe = True j[1] = "Read" elif i in self.valoresFlotantes: for k in self.valoresFloat: if (k[0] == i): existe = True k[1] = "Read" if not existe: if i[0] in self.valoresEnteros: self.valoresInt.append([i, "Read"]) existe = True if i[0] in self.valoresFlotantes: self.valoresFloat.append([i, "Read"]) existe = True # if(self.pasecommandwrite): targetHijo = self.new_node(label=i, shape="circle") self.dot.add_node(targetHijo) self.dot.add_edge(pgv.Edge(target, targetHijo)) self.stack.append(target)
def render_graph(bb_graph, filename): """ Renders a basic block graph to file :param bb_graph: The Graph to render :type bb_graph: networkx.DiGraph """ graph = pydotplus.Dot(graph_type='digraph', rankdir='TB') entryblock = nx.get_node_attributes(bb_graph, 'isEntry').keys()[0] returnblocks = nx.get_node_attributes(bb_graph, 'isTerminal').keys() nodedict = {} for bb in bb_graph.nodes.iterkeys(): node = render_bb(bb, bb == entryblock, bb in returnblocks) if bb == entryblock: sub = pydotplus.Subgraph('sub', rank='source') sub.add_node(node) graph.add_subgraph(sub) else: graph.add_node(node) nodedict[bb] = node for edge in bb_graph.edges.iteritems(): edge = (edge[0][0], edge[0][1], edge[1]) src = nodedict[edge[0]] dest = nodedict[edge[1]] e_style = 'dashed' if edge[2]['edge_type'] == 'implicit' else 'solid' graph.add_edge(pydotplus.Edge(src, dest, style=e_style)) # graph.set('splines', 'ortho') # graph.set_prog('neato') # graph.set('dpi', '100') graph.write(filename, format='svg')
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))
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 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 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 breadth_first_search(root): print("Starting Node(root) : %s" % root) graph = pydotplus.Dot(graph_type='digraph') queue = deque([root]) visited = [] expansion = 0 while True: node = queue.popleft() print("\n Parent Node : %s ,Currently popped node %s at depth %s" % (node.parent, node.state, node.depth)) if str(node) in visited: continue visited.append(str(node)) graph.add_node(node.dot) if node.parent: graph.add_edge(pydotplus.Edge(node.parent.dot, node.dot)) if node.state.is_goal(): graph.write_png('solution.png') print("\nReached Goal State at %s" % node.state) # print("Total no. of expansion is %d" % expansion) solution = node.get_solution() return solution expansion += 1 queue.extend(node.successor_node())