def json2dot(direction, color='green', view=True, DOTfileName="Metro-scheme", JSONfileName="graph.json"): src = json.load(open(JSONfileName)) dot = Graph(DOTfileName, format='png') dot.attr('node', shape='circle') for station in src["station"]: if direction != None and station in set(direction): dot.node(station, fillcolor=color, style='filled') elif station in set(src["pausing"]): dot.node(station, fillcolor='gray', style='filled') else: dot.node(station) for i in range(len(src["station"])): paths = list( filter(lambda j: (src["link"][i][j] > 0) and (j > i), range(len(src["link"][i])))) for path in paths: dot.edge(src["station"][i], src["station"][path]) return dot.render(view=view)
def render_dungeon(dungeon: Dungeon, session_id: str, rogue_position: int): filename = f'./dungeons/d-{session_id}.gv' g = Graph('Dungeon_graph', filename=filename, format='png', engine='fdp') for room in dungeon.rooms: contains_key = any(key.room_id == room.id for key in dungeon.keys) shape = 'circle' if rogue_position == room.id: shape = 'triangle' elif contains_key: shape = 'doublecircle' elif room.id == dungeon.finish_room_id: shape = 'star' g.attr('node', color=str(room.color), shape=shape) g.node(str(room.id)) for door in dungeon.doors: if door.is_closed: style = 'dashed' else: style = 'solid' g.attr('edge', color=str(door.color), style=style) g.edge(str(door.first_room_id), str(door.second_room_id)) g.render() return f'{filename}.png'
def draw_clusters(_json_data, _graph): """ Function to generate cluster in cluster graph based on DOT language. """ sub_graph = None if type(_json_data) is dict: for dict_name in _json_data: if check_hidden(dict_name): if check_status(_json_data, _graph): if type(_json_data[dict_name]) is dict: # determine if a dict as dict child # if the dict include other dict, it is a cluster if check_dict_child(_json_data[dict_name]): sub_graph = Graph('cluster_' + dict_name) sub_graph.attr( label='<<B>' + dict_name + '</B>>', color='black', style='filled', #~ ranktype = 'min', #~ rankdir = 'TB', fillcolor=rand_color()) draw_clusters(_json_data=_json_data[dict_name], _graph=sub_graph) _graph.subgraph(sub_graph) # if the dict as no child, it is a node else: _graph.attr('node', shape='record') # shape='box' _graph.node(dict_name) return 0
def gen_img(graph: Graph, node_num, rm_ratio: float = 0.2, root_folder='train', source_folder='', source_file='train.txt'): """ 在graph上,以rm_ratio的概率随机删除一些链路,然后用随机选取的一对节点作为源宿点,判断其是否联通。并将生成的图像放到root_folder目录中, 对应的文件名称和标签放到source_folder目录下的train.txt文件中。 """ # 生成原始数据 rds = rand_edges(graph, rm_ratio) graph.remove_edges_from(rds) src, dst = gen_src_dst(0, node_num) label = get_label(src, dst, graph) # 构造graphviz对象 name = str(time.time()) g = Graph(format='jpeg', engine='neato') g.attr('node', shape='circle') g.attr('edge') for node in graph.nodes(): g.node(name=str(node)) g.node(name=str(src), shape='triangle') g.node(name=str(dst), shape='triangle') for edge in graph.edges(): g.edge(str(edge[0]), str(edge[1])) for edge in rds: g.edge(str(edge[0]), str(edge[1]), color='white') g.render(filename=name, directory=root_folder, view=False, cleanup=True) # 存储到文件中去 file = open(os.path.join(source_folder, source_file), 'a') file.write(name + '.jpeg ' + str(label) + '\n') file.flush() file.close()
def render_graph(graph, name=None, directory=None, fill_infected='green3'): """ Render a user graph to an SVG file. Infected nodes are colored appropriately. Parameters: ----------- graph : UserGraph The graph to render. name : str A name for the graph. directory : str The directory to render to. fill_infected : str The fill color for infected nodes. """ dot = Graph(name=name, format='svg', strict=True) for user in graph.users(): if user.metadata.get('infected', False): dot.attr('node', style='filled', fillcolor=fill_infected) dot.node(unicode(user.tag)) dot.attr('node', style='') for user in graph.users(): for neighbor in user.neighbors: dot.edge(unicode(user.tag), unicode(neighbor.tag)) dot.render(directory=directory, cleanup=True)
def color(self): # Dict to save color color = defaultdict(list) for node in self.graph: if (len(color) == 0): color[0].append(node) continue else: for i in range(len(color)): temp = 0 for colored_node in color[i]: if (node in self.graph[colored_node]): temp = 1 break if (temp == 1): continue else: color[i].append(node) break if (node not in color[i]): color[len(color)].append(node) # Out put file output_file = Graph('Coloring graph', filename='Greedy Coloring Graph.gv',strict="True") output_file.attr( shape="circle", size='1') list_color=["red","blue", "yellow","green","gray","snow","DarkOrange1","MediumPurple1","khaki4","orchid", "cyan2", "blue violet", "GreenYellow", "HotPink", "LightGoldenrod4","DarkSeaGreen", "sienna","brown"] for i in range (len(color)): for node in color[i]: output_file.node(str(node),fillcolor=list_color[i],style="filled") for opp_node in self.graph[node]: output_file.edge(str(node),str(opp_node)) output_file.view()
def draw_expr(expr, title="Standard Expression"): from graphviz import Graph graph = Graph(title, filename=title) graph.attr(rankdir="TD", size="50") typeMapper = { OPType.Star: "*", OPType.Plus: "+", OPType.Concat: "@", OPType.Union: "|", OPType.Symbol: "S", OPType.Questionmark: "?" } counter = 0 def inner(expr): nonlocal counter label_ = "" color_ = "red" if expr.isSymbol(): label_ = expr.getSymbol() color_ = "blue" else: label_ = typeMapper[expr.opType] graph.node(str(counter), shape="circle", label=label_, color=color_) expr.name = str(counter) # Monkey patching !! counter += 1 if expr.lhs != None: inner(expr.lhs) graph.edge(expr.name, expr.lhs.name) if expr.rhs != None: inner(expr.rhs) graph.edge(expr.name, expr.rhs.name) inner(expr) graph.view()
def make_graph_mst(): g = Graph(format='png', comment='undirected graph that contains no negative weight path') g.attr('node', shape='circle') n = 9 for i in range(n): g.node(str(i), label=str(i)) edges = ((0, 1), (0, 7), (1, 2), (1, 7), (2, 3), (2, 5), (2, 8), (3, 4), (3, 5), (4, 5), (5, 6), (6, 7), (6, 8), (7, 8)) edge_labels = [4, 8, 8, 11, 7, 4, 2, 9, 14, 10, 2, 1, 6, 7] for i, e in enumerate(edges): g.edge(str(e[0]), str(e[1]), label=str(edge_labels[i])) g.render('graph_mst', view=True, cleanup=True)
def draw_pats_tree_colored(pkl, out, col_style='contact', **kwarg): with open(pkl, 'rb') as f: var_list = pickle.load(f) rootnode = var_list[0] if col_style == 'order': num_state = dfs(rootnode) print('num_state ' + str(num_state)) values = np.arange(num_state) elif col_style == 'rmsd': values = None elif col_style == 'contact': native = kwarg['native'] traj = kwarg['traj'] values = frac_native_contacts(native, traj) elif col_style == 'f1': native = kwarg['native'] traj = kwarg['traj'] values = calc_f1(native, traj) else: print('Error!: you can not use such color style ' + col_style) exit(1) if values is not None: make_colorbar(min(values), max(values), out + '_colorbar') else: make_colorbar(0, rootnode.childNodes[0].rmsd, out + '_colorbar') # G = Graph(format='pdf') G = Graph(format='svg') G.attr("node", shape="circle", style="filled") G.graph_attr.update(size="30") make_graph(G, rootnode, values) G.render(out)
def make_graph_dijkstra(): g = Graph(format='png', comment='undirected graph that contains no negative weight path') g.attr('node', shape='circle') n = 10 for i in range(n): g.node(str(i), label=str(i)) edges = ((0, 1), (2, 0), (2, 3), (1, 4), (4, 5), (5, 2), (3, 6), (4, 7), (5, 8), (8, 9)) edge_labels = [5, 6, 2, 2, 3, 4, 1, 7, 1, 1, 1] for i, e in enumerate(edges): g.edge(str(e[0]), str(e[1]), label=str(edge_labels[i])) g.render('graph_dijkstra', view=True, cleanup=True)
def make_bipartite_graph(): g = Graph(format='png', comment='undirected graph that contains no negative weight path', engine='dot') g.attr('node', shape='circle') n = 10 with g.subgraph(name='cluster_0') as c: c.attr(label='process #1') for i in range(0, n, 2): c.node(str(i), label=str(i), color='blue') with g.subgraph(name='cluster_1') as c: c.attr(label='process #2') for i in range(1, n, 2): c.node(str(i), label=str(i), color='red') edges = ((0, 1), (1, 2), (1, 4), (2, 9), (3, 4), (4, 5), (4, 9), (5, 6), (6, 7), (6, 9), (8, 9)) for e in edges: g.edge(str(e[0]), str(e[1])) g.render('graph_bipartite', view=True, cleanup=True)
def constGraph(): for i in range(0, len(atom_id_input_arr)): atom_id_row = atom_id_input_arr[i] atom_output_row = atom_output_arr[i] orange_indices_row = orange_indices_arr[i] neighbour_row = neighbour_list[i] print(cod[i]) g = Graph('G', filename=str(cod[i]) + '.gv') for j in range(0, len(atom_id_row)): # print(j) if j in orange_indices_row: g.attr('node', style='filled', color='orange') else: g.attr('node', style='filled', color='white') g.node(str(j), label=atom_id_row[j]) for j in range(0, len(atom_id_row)): # print(j) for k in range(0, len(neighbour_row[j])): if not neighbour_row[j][k] == -1: g.edge(str(j), str(neighbour_row[j][k])) # g.view() g.save(filename='./' + str(cod[i]) + '.dot')
def draw_pacs_tree_colored(log_file, out): log = pd.read_csv(log_file, header=None) log = np.array(log) n_cycles = log.shape[0] # G = Graph(format='pdf') G = Graph(format='svg') G.attr('node', shape='circle', style='filled') G.graph_attr.update(size="30") color_hex = value2hex(0) G.node('0-0', '0', fillcolor=color_hex) # G.node('0-0', '', fillcolor=color_hex, color='white', width='12') color_hex = value2hex(255 / n_cycles * 1) for i in range(len(log[0])): state = '1-' + str(i) G.node(state, str(state), fillcolor=color_hex) # G.node(state, '', fillcolor=color_hex, color='white', width='12') G.edge('0-0', state, color='black') for i in range(1, len(log) + 1): log_i = log[i - 1] color_hex = value2hex(255 / n_cycles * (i + 1)) for j, l in enumerate(log_i): state = str(i + 1) + '-' + str(j) pstate = str(i) + '-' + str(int(l)) G.node(state, str(state), fillcolor=color_hex) # G.node(state, '', fillcolor=color_hex, color='white', width='12') G.edge(pstate, state, color='black') G.render(out) make_colorbar(0, n_cycles * 5, out + '_colorbar')
class GraphvizVisitor(Visitor): def __init__(self): self._graph = Graph('equation') self._subgraph_terms = Graph('terms') self._terms = {} self._graph.attr(rankdir='BT', ordering='out') #, splines='false') self._subgraph_terms.attr(rank='same', rankdir='LR') def visit(self, node: 'Node') -> Graph: node.accept(self) self._graph.subgraph(self._subgraph_terms) return self._graph def visit_equation(self, node: Equation): uid = str(uuid4()) child_uid = node.child.accept(self) self._graph.node(uid, label='F', shape='square') self._graph.edge(uid, child_uid, penwidth='3') return uid def visit_unary_op(self, node: UnaryOperationExpression) -> str: uid = str(uuid4()) child_uid = node.child.accept(self) self._graph.node(uid, label=OPERATION_SYMBOLS[node.op], shape='invtriangle') self._graph.edge(uid, child_uid, penwidth='3') return uid def visit_binary_op(self, node: BinaryOperationExpression) -> str: uid = str(uuid4()) left_uid = node.left.accept(self) right_uid = node.right.accept(self) self._graph.node(uid, label=OPERATION_SYMBOLS[node.op], shape='invtriangle') self._graph.edge(uid, left_uid, penwidth='3') self._graph.edge(uid, right_uid, penwidth='3') return uid def visit_term(self, node: Term): name = node.name uid = self._terms[name] if name in self._terms else str(uuid4()) self._terms[node.name] = uid self._subgraph_terms.node(uid, label=name, shape='circle') # shape='point') return uid
def word_to_graph(inp, out_name): idd = 0 branch_list = list() operator = ['sequence', 'xor', 'xorLoop', 'and'] split_word = inp.split(' ') G = Graph(format='eps') G.attr('node', shape='circle') G.attr('graph', pad='0', margin='0', ratio='auto', size='8.3,11!', layout='dot', overlap='prism', fixedsize='true') for now in split_word: print(branch_list) if now in operator and not branch_list: if now == 'sequence': oper = 'seq' elif now == 'xorLoop': oper = 'loop' else: oper = now G.node('0', label=oper) branch_list.append(idd) idd += 1 elif now in operator and branch_list: if now == 'sequence': oper = 'seq' elif now == 'xorLoop': oper = 'loop' else: oper = now G.node(str(idd), label=oper) G.edge(str(branch_list[-1]), str(idd)) branch_list.append(idd) idd += 1 elif now == '(': pass elif now == ')' and branch_list: branch_list.pop(-1) elif now == 'tau' and branch_list: G.node(str(idd), shape='box', label='T') G.edge(str(branch_list[-1]), str(idd)) idd += 1 elif branch_list: G.node(str(idd), shape='box', label=now) G.edge(str(branch_list[-1]), str(idd)) idd += 1 else: pass G.render(out_name) os.remove(out_name)
def apply( tree: ProcessTree, parameters: Optional[Dict[Union[str, Parameters], Any]] = None ) -> graphviz.Graph: """ Obtain a Process Tree representation through GraphViz Parameters ----------- tree Process tree parameters Possible parameters of the algorithm Returns ----------- gviz GraphViz object """ if parameters is None: parameters = {} parameters = copy(parameters) parameters[ROOT_NODE_PARAMETER] = tree filename = tempfile.NamedTemporaryFile(suffix='.gv') bgcolor = exec_utils.get_param_value(Parameters.BGCOLOR, parameters, "transparent") viz = Graph("pt", filename=filename.name, engine='dot', graph_attr={'bgcolor': bgcolor}) viz.attr('node', shape='ellipse', fixedsize='false') image_format = exec_utils.get_param_value(Parameters.FORMAT, parameters, "png") enable_deepcopy = exec_utils.get_param_value(Parameters.ENABLE_DEEPCOPY, parameters, False) if enable_deepcopy: # since the process tree object needs to be sorted in the visualization, make a deepcopy of it before # proceeding tree = deepcopy(tree) generic.tree_sort(tree) repr_tree_2(tree, viz, parameters) viz.attr(overlap='false') viz.attr(splines='false') viz.format = image_format return viz
def gen_img(graph: nxGraph, node_num, min_rm_ratio: float = 0.2, max_rm_ratio: float = 0.5, root_folder='train', source_folder='', source_file='train.txt', channel_num=40): """ 在graph上,以[min_rm_ratio, max_rm_ratio)区间的概率随机删除一些链路,然后用随机选取的一对节点作为源宿点,判断其是否连通。 并将生成的图像放到root_folder目录中,对应的文件名称和标签放到source_folder目录下的train.txt文件中。 :param graph: 输入的图 :param node_num: 图的节点数 :param root_folder: 根目录,存放图片文件 :param source_folder: 存放图片名和label的目录 :param source_file: 存放文件名和label的文件名 :param channel_num: 表示图片的通道数 :param min_rm_ratio: 删除链路的最小概率 :param max_rm_ratio: 删除链路的最大概率 """ # 首先把文件前缀确定下来。 name = str(time.time()) total_label = 0 src, dst = gen_src_dst(0, node_num) for channel in range(channel_num): rm_ratio = random.uniform(min_rm_ratio, max_rm_ratio) # 随机从[min,max]中生成一个随机数 # 生成原始数据 rds = rand_edges(graph, rm_ratio) graph.remove_edges_from(rds) total_label += get_label(src, dst, graph) # 构造graphviz对象 g = Graph(format='jpeg', engine='neato') g.attr('node', shape='circle') g.attr('edge') for node in graph.nodes(): g.node(name=str(node)) g.node(name=str(src), shape='triangle') g.node(name=str(dst), shape='triangle') for edge in graph.edges(): g.edge(str(edge[0]), str(edge[1])) for edge in rds: g.edge(str(edge[0]), str(edge[1]), color='white') g.render(filename=name + '-' + str(channel), directory=root_folder, view=False, cleanup=True) graph.add_edges_from(rds) # 恢复刚才删掉的边。 # 存储到文件中去 file = open(os.path.join(source_folder, source_file), 'a') file.write(name + '.jpeg ' + str(total_label) + '\n') file.flush() file.close()
def showFamilyTree(root_child_elements): """US52 - Displays a GEDCOM file as a family tree and saves as a PDF""" family = Graph('Family Tree', comment="family tree") family.attr(rankdir='TB') cluster = 0 for element in root_child_elements: if isinstance(element, FamilyElement): husband = gedcom_parser.get_family_members(element, members_type='HUSB')[0] wife = gedcom_parser.get_family_members(element, 'WIFE')[0] children = gedcom_parser.get_family_members(element, members_type='CHIL') with family.subgraph(name=f'cluster_{cluster}') as graphGroup: graphGroup.attr(label=element.get_pointer()) with graphGroup.subgraph() as s: s.attr(rank='same') s.node(husband.get_pointer(), label=husband.get_name()[0], color='blue', style='filled', fillcolor='red' if listErrors(husband) else 'white') s.node(str(cluster), shape='point') s.node(wife.get_pointer(), label=wife.get_name()[0], color='lightpink', style='filled', fillcolor='red' if listErrors(wife) else 'white') family.edge(husband.get_pointer(), str(cluster), label='husband') family.edge(str(cluster), wife.get_pointer(), label='wife') with graphGroup.subgraph() as s: s.attr(rank='same') s.node(str(cluster) + "_1", shape='point') family.edge(str(cluster), str(cluster) + "_1", label='children') for child in children: s.node( child.get_pointer(), label=child.get_name()[0], color='black', style='filled', fillcolor='red' if listErrors(child) else 'white') family.edge(str(cluster) + "_1", child.get_pointer()) cluster += 1 family.view() return
def paint_the_root(jumper_list): dot = Graph('G', filename='recommendationNodes.gv') dot.attr('node', shape='doublecircle') dot.attr('node', shape='circle') node_before = jumper_list[0] for branch in set(jumper_list): dot.node(str(branch), str(branch)) for branch in jumper_list[1:]: dot.edge(str(node_before), str(branch)) node_before = str(branch) dot.view()
def draw_topic_link_graph(topic_links, filename): g = Graph('G', filename, engine='sfdp') g.attr(overlap='prism') g.attr(outputorder='edgesfirst') nodes_added = set() edgelist = [] for tweet in tqdm(topic_links.keys()): topic_link = topic_links[tweet]['topic_links'] nodes_in_tweet = set() for link in topic_link: if len(link[2]) == 0: node_name = link[1] + '####' + link[4].rstrip('+-') nodes_in_tweet.add(node_name.replace(':', '')) else: node_name = link[2] + '####' + link[4].rstrip('+-') nodes_in_tweet.add(node_name.replace(':', '')) edges = itertools.combinations(nodes_in_tweet, 2) for edge in edges: edgelist.append(edge) node1_name = edge[0] node2_name = edge[1] if node1_name not in nodes_added: g.node(node1_name, label=node1_name, style='filled', fontcolor='white', fontsize=str(40), fillcolor='black', overlap="false", height='5', width='5') nodes_added.add(node1_name) if node2_name not in nodes_added: g.node(node2_name, label=node1_name, style='filled', fontcolor='white', fontsize=str(40), fillcolor='black', overlap="false", height='5', width='5') nodes_added.add(node1_name) g.edge(node1_name, node2_name, style='solid', color="#000000") edgelist.append(edge) return g, edgelist
def graphGrammar(self): if self.gramatica != None: dot = Graph() dot.attr(splines = 'false') dot.node_attr.update(shape = 'record') dot.node_attr.update(center = 'false') dot.node(str(0), '{'+ self.gramatica.replace('\n', '\\l |')[:-1] +'}') try: dot.view() except: self.textEdit_2.setText('ERROR: No fue posible realizar el reporte gramatical por algun error desconocido.')
def graphSimbolos(gramatica): if gramatica != None: dot = Graph() dot.attr(splines='false') dot.node_attr.update(shape='record') dot.node_attr.update(center='true') dot.node(str(0), '{' + gramatica.replace('\n', '|')[:-1] + '}') try: dot.view() except: print( 'ERROR: No fue posible realizar el reporte gramatical por algun error desconocido.' )
def plot_mst(G, MST): dot = Graph(comment="Matrix graph", engine=graphviz_engine, format='png') dot.attr(size='6,6') #dot.attr(overlap='false') #dot.attr(fontsize='12') is_bin = is_binary(G) for i in range(G.shape[0]): dot.node(str(i), str(i)) for j in range(i, G.shape[1]): if G[i,j] != 0: if is_bin: dot.edge(str(i), str(j), color='red' if MST[i, j] != 0 else 'black') else: dot.edge(str(i), str(j), str(G[i,j]), color='red' if MST[i, j] != 0 else 'black') return dot
class Ast: """ Esta clase permitirá la creación de un árbol AST mediante graphviz ... Atributos ---------- i : int variable que servirá como índice para el ordenamiento de los nodos dot : any variable que generará la imagen png del dot creado Métodos ------- inc() Incrementa el índice del nodo usando la variable i """ def __init__(self): self.i = 0 self.dot = Graph('AST', format='png') self.dot.attr('node', shape='box') def inc(self): self.i += 1 def graficar_drop(self, expresion): """Prints what the animals name is and what sound it makes. If the argument `sound` isn't passed in, the default Animal sound is used. Parameters ---------- sound : str, optional The sound the animal makes (default is None) Raises ------ NotImplementedError If no sound is set for the animal or passed in as a parameter. """ self.inc() self.dot.node(str(self.id), 'DROP') self.inc() self.dot.node(str(self.id), 'id') self.dot.edge(str(self.id - 1), str(self.id)) self.inc() self.dot.node(str(self.id), str(expresion.id)) self.dot.edge(str(self.id - 1), str(self.id))
def main(): SIZE = 20 PLOIDY = 2 MUTATIONS = 2 indices = range(SIZE) # Build fake data seqA = list("0" * SIZE) allseqs = [seqA[:] for x in range(PLOIDY)] # Hexaploid for s in allseqs: for i in [choice(indices) for x in range(MUTATIONS)]: s[i] = "1" allseqs = [make_sequence(s, name=name) for (s, name) in \ zip(allseqs, [str(x) for x in range(PLOIDY)])] # Build graph structure G = Graph("Assembly graph", filename="graph") G.attr(rankdir="LR", fontname="Helvetica", splines="true") G.attr(ranksep=".2", nodesep="0.02") G.attr('node', shape='point') G.attr('edge', dir='none', penwidth='4') colorset = get_map('Set2', 'qualitative', 8).mpl_colors colorset = [to_hex(x) for x in colorset] colors = sample(colorset, PLOIDY) for s, color in zip(allseqs, colors): sequence_to_graph(G, s, color=color) zip_sequences(G, allseqs) # Output graph G.view()
def graphColorFinal(): global l2 global listNoeud global photo1 nodes = l2 global maxi value = getOperation() if (getOperation() == 'Manuel'): nodes = maxi if value == "MPSO": color = graphColorAlgorithmMPSO() else: color = graphColorAlgorithm() g1 = Graph('G', filename='process2.png', format='png') if (getOperation() != 'MPSO'): for i in range(len(color)): color[i] = nodes - color[i] listcolor = {} s = max(color) for i in range(s + 1): x = webcolors.rgb_to_hex( (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))) listcolor[i] = x for line in listNoeud: x = line.split() g1.edge(x[0], x[1]) for j in range(len(color)): g1.node(str(j + 1), style='filled', fillcolor=listcolor[color[j]]) g1.attr(fill="#d9d9d9", style="filled") filename = g1.render(filename='img/graph2') pylab.savefig('graph2.png') image1 = Image.open('img/graph2.png') if (image1.size[0] > image1.size[1]): au = image1.size[0] au1 = image1.size[1] v = int((400 / au) * au1) image1 = image1.resize((400, v)) else: au = image1.size[0] au1 = image1.size[1] v = int((400 / au1) * au) image1 = image1.resize((v, 400)) #image = image.resize((750, 700)) canvas = Canvas(frame32, width=500, height=500) canvas.pack() photo1 = ImageTk.PhotoImage(image1) canvas.create_image(0, 0, anchor=NW, image=photo1) insertHint("Nombre chromatique = " + str(len(set(color))))
def graphic(node_list, tuple_list): nodes_to = str(node_list) tuple_number = len(tuple_list) counter = 0 print(nodes_to) e = Graph('ER', filename='my_file.gv', engine='neato') e.attr('node', shape='ellipse') for n in node_list: e.node(n) while counter < tuple_number: actual_tuple = tuple(i for i in tuple_list[counter]) e.edge(str("" + actual_tuple[0] + ""), str("" + actual_tuple[1] + "")) counter += 1 return e.view()
def main(): SIZE = 20 PLOIDY = 2 MUTATIONS = 2 indices = range(SIZE) # Build fake data seqA = list("0" * SIZE) allseqs = [seqA[:] for x in range(PLOIDY)] # Hexaploid for s in allseqs: for i in [choice(indices) for x in range(MUTATIONS)]: s[i] = "1" allseqs = [make_sequence(s, name=name) for (s, name) in \ zip(allseqs, [str(x) for x in range(PLOIDY)])] # Build graph structure G = Graph("Assembly graph", filename="graph") G.attr(rankdir="LR", fontname="Arial", splines="true") G.attr(ranksep=".2", nodesep="0.02") G.attr('node', shape='point') G.attr('edge', dir='none', penwidth='4') colorset = get_map('Set2', 'qualitative', 8).mpl_colors colorset = [to_hex(x) for x in colorset] colors = sample(colorset, PLOIDY) for s, color in zip(allseqs, colors): sequence_to_graph(G, s, color=color) zip_sequences(G, allseqs) # Output graph G.view()
def make_graph(self, name: str, description: str) -> None: g = Graph('World', filename='world.gv', engine='neato') g.attr(label=description) g.attr('node', colorscheme="pastel19", style="filled") for t in self.territories: assert t.owner g.node(t.name, "{} ({:4d})".format(t.name, t.armies), fillcolor=str(t.owner.index + 1), pos=t.get_coordinates()) for i in t.connections: g.edge(t.name, self.territories[i - 1].name) g.format = 'svg' g.render('outputs/{}'.format(name), view=False) if os.path.exists('outputs/{}'.format(name)): os.remove('outputs/{}'.format(name))
def get_data2(): dot = Graph('G', format="pdf") dot.graph_attr['rankdir '] = 'TB' dot.attr(compound='true', fixedsize='false') data = json.loads(request.get_data().decode('UTF-8')) for key in data.keys(): with dot.subgraph(name='cluster_' + key) as c: for aa, bb in data[key].items(): c.attr(label=key, bgcolor='#FFEFD5', fontname='Microsoft YaHei', fontcolor='red', style='rounded',gradientangle='270') with c.subgraph(name='cluster_' + aa) as d: d.attr(label=aa, color='white', bgcolor='#CCCC99', style='rounded', gradientangle='270',fontname="Microsoft YaHei") d.attr('node', shape='box', style='filled', gradientangle='90') for cc in bb: d.node(cc) dot.render(filename="/tmp/tuopu_"+str(today_time()), view=False) return data
def create_graphviz(components, config): graph = Graph( name=config["name"], engine=config["engine"], directory=config["output_path"] ) if config.get("horizontal"): rankdir = "TB" else: rankdir = "LR" graph.attr(rankdir="LR", overlap="false") add_subgraphs(graph, components["subgraphs"]) add_records(graph, components["records"]) add_nodes(graph, components["nodes"]) add_edges(graph, components["edges"]) return graph
def hasse_diagram(op,rel,dual,unary=[]): A = range(len(op)) G = nx.DiGraph() if rel: G.add_edges_from([(x,y) for x in A for y in A if (op[y][x] if dual else op[x][y]) and x!=y]) else: G.add_edges_from([(x,y) for x in A for y in A if op[x][y]==(y if dual else x) and x!=y]) try: G = nx.algorithms.dag.transitive_reduction(G) except: pass P = Graph() P.attr('node', shape='circle', width='.15', height='.15', fixedsize='true', fontsize='10') for x in A: P.node(str(x), color='red' if unary[x] else 'black') P.edges([(str(x[0]),str(x[1])) for x in G.edges]) return P
def outputToPdf(graph, fileName,sourceLables): e = Graph('NYC', filename=fileName, engine='dot') e.body.extend(['rankdir=LR', 'size="100,100"']) e.attr('node', shape='ellipse') e.attr("node",color='green', style='filled') edgeExists={} for label in sourceLables: e.node(str(label)) e.attr("node",color='lightblue2', style='filled') for node in graph.nodeIter(): for edge in node.neighborsIter(): if not edge[1] in edgeExists: e.attr("edge",labelcolor="blue") e.edge(str(node.label()),edge[1],str(int(edge[0]))+"m") edgeExists[node.label()]=1 edgeExists=None e.body.append(r'label = "\nIntersections in New York City\n"') e.body.append('fontsize=100') e.view()
class Draw(Toplevel): "draw the tree to picture" def __init__(self, parent): """ @ brief initializa the Draw class @ params self -- new instance """ super(Draw, self).__init__(parent) self.transient(parent) self.title("current view") self.grab_set() def initDot(self): "init the pane" self.__dot = Graph() self.__dot.format = "gif" self.__dot.filename = "instance" self.__dot.attr('node', shape="circle") def setSource(self, source, with_label): "set the source text" self.node_suffix = 0 self.__tree = ast.literal_eval(source) if with_label: self.draw = self.__drawHasLabel else: self.draw = self.__drawNoLabel def getTree(self): "return the tree" return self.__tree def __drawNoLabel(self, tree, root="tree"): "draw the tree without label on edge" self.__dot.body.extend(["rank=same", "rankdir=TD"]) for key in tree.keys(): self.__dot.edge(root, key) if type(tree[key]) is dict: self.__drawNoLabel(tree[key], str(key)) else: node_name = str(key) + str(self.node_suffix) self.__dot.node(node_name, str(tree[key])) self.__dot.edge(str(key), node_name) self.node_suffix += 1 return self.__dot.pipe(format="gif") def __drawHasLabel(self, tree): "draw the tree with label on edge" self.__dot.body.extend(["rank=same", "rankdir=TD"]) for key in tree.keys(): if type(tree[key]) is dict: for key_ in tree[key]: if type(tree[key][key_]) is dict: child = next(iter(tree[key][key_].keys())) self.__dot.edge(key, child, str(key_)) self.__drawHasLabel(tree[key][key_]) else: node_name = str(key) + str(self.node_suffix) self.__dot.node(node_name, tree[key][key_]) self.__dot.edge(key, node_name, str(key_)) self.node_suffix += 1 return self.__dot.pipe(format="gif") def show(self): "show the image" tree = self.getTree() image = self.draw(tree) if image is not None: label_image = PhotoImage(data=base64.b64encode(image)) image_label = Label(self, image=label_image) image_label.photo = label_image else: image_label = Label(self, text="no image view") image_label.pack() self.wait_window(self)
#!/usr/bin/env python # http://www.graphviz.org/Gallery/gradient/g_c_n.html from graphviz import Graph g = Graph('G', filename='g_c_n.gv') g.attr(bgcolor='purple:pink', label='agraph', fontcolor='white') with g.subgraph(name='cluster1') as c: c.attr(fillcolor='blue:cyan', label='acluster', fontcolor='white', style='filled', gradientangle='270') c.attr('node', shape='box', fillcolor='red:yellow', style='filled', gradientangle='90') c.node('anode') g.view()
#!/usr/bin/env python # er.py - http://www.graphviz.org/content/ER from graphviz import Graph e = Graph('ER', filename='er.gv', engine='neato') e.attr('node', shape='box') e.node('course') e.node('institute') e.node('student') e.attr('node', shape='ellipse') e.node('name0', label='name') e.node('name1', label='name') e.node('name2', label='name') e.node('code') e.node('grade') e.node('number') e.attr('node', shape='diamond', style='filled', color='lightgrey') e.node('C-I') e.node('S-C') e.node('S-I') e.edge('name0', 'course') e.edge('code', 'course') e.edge('course', 'C-I', label='n', len='1.00') e.edge('C-I', 'institute', label='1', len='1.00') e.edge('institute', 'name1') e.edge('institute', 'S-I', label='1', len='1.00')
dot.node('dead') dot.edge('parrot', 'dead') dot.graph_attr['rankdir'] = 'LR' dot.edge_attr.update(arrowhead='vee', arrowsize='2') dot.render(view=True) ################################################ ### question c) and d) ################################################ ## Shape corresponds to those used in previous tasks g = Graph(name = 'mouse_cluster') key_list = mids.keys() ## list of mouse IDs for key in key_list: g.attr('node', color=col[class_list.index(m_class[key])], shape = shp[class_list.index(m_class[key])]) ## setting node properties based of mouse class g.node(key) ## Initialising node for x in combinations(key_list,2): if pearsonr(m_ave_values[x[0]],m_ave_values[x[1]])[0] > 0.98: ## Check for correlation score g.edge(x[0], x[1], penwidth = str(0.03/float(1-pearsonr(m_ave_values[x[0]],m_ave_values[x[1]])[0]))) ## setting up edge, if the condition satisfies, to express the correlation score g.view() ################################################ ### question e) ################################################ ## initialising graph g = Graph(name = 'Alternate Mouse Cluster')
from graphviz import Graph import pandas as pd from os.path import join my_dir = 'C:\\Users\\John\\Documents\\2016\\Python\\JiraStates' full_jira_df = pd.read_csv(join(my_dir, 'jira_states.csv')) # print(df) issue_list = pd.Series.unique(full_jira_df["IssueNo"]) print(issue_list) mygraph = Graph('ER', filename='test.gv', engine='circo') # FIRST SET UP THE NODES mygraph.attr('node', shape='ellipse', width='10') mygraph.node('name0', label='name', color='red', width='10') mygraph.node('name1', label='name') #NOW JOIN THE NODES WITH EDGES mygraph.edge('name0', 'name1', color='blue', dir='forward', edgetooltip='a tool tip') #FINALLY DISPLAY THE GRAPH mygraph.view()