def graph_data(pkg_name): if not pkg_name: abort(404) filepath = os.path.join(cache_dir, pkg_name.lower()) if not os.path.exists(filepath + '.png'): nodes, edges = reqs_graph(pkg_name) if not nodes: return redirect(url_for('static', filename='img/blank.png')) dot = Graph() dot.format = 'png' dot.node('0', nodes[0], fillcolor='#fbb4ae', style='filled', shape='box') for i, pkg_name in enumerate(nodes[1:]): dot.node(str(i+1), pkg_name, fillcolor='#ccebc5', style='filled') dot.edges([ [str(i[0]), str(i[1])] for i in edges ]) dot.render(filepath) return send_file(filepath + '.png')
def rna_structure_to_graphviz(rna, structure): """ Produce graphviz graph for rna structure visualization :Note: Use "neato" engine for better look """ dot = Graph() for i, letter in enumerate(rna): dot.node(str(i), letter) dot.edges((str(i - 1), str(i)) for i in range(1, len(rna))) for start, end in structure: dot.edge(str(start), str(end), style="dashed") return dot
def rand_edges(graph: Graph, rm_ratio: float = 0.2) -> tuple: """ 从双向图graph中以rm_ratio的概率选出链路 """ if len(graph.edges()) is 0: raise ValueError("empty graph!") else: rm_edges = [] for edge in graph.edges(): if random.random() < rm_ratio: rm_edges.append(edge) return tuple(rm_edges)
def draw_graph(topology): # Create directed graph (Digraph) dot = Graph(format='pdf', comment='Network Topology', strict=True) # Flatten topology (list of tuples) nodes = list(sum(topology, ())) # Get unique nodes nodes = set(nodes) for x in nodes: dot.node(repr(x)) ed = [''.join((repr(e[0]), repr(e[1]))) for e in topology] dot.edges(ed) dot.render('topology.gv', view=True) # doctest: +SKIP
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 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 render_graph(maze: List[List[int]], file_name): """ Generate a PDF file showing the maze as an undirected graph. Uses GraphViz, which must be installed and on the PATH. Note that the resulting graph shows only the nodes and their connections. The ordering of edges around each node is determined by GraphViz itself. You therefore cannot rely on this rendering to tell you whether to turn left or right at each node. """ if len(maze) > 26: raise Exception("render_graph can only handle up to 26 nodes") dot = Graph() this = 0 edges = [] unknowns = 0 A = ord('A') a = ord('a') for node in maze: id = str(chr(A + this)) if this == 0: dot.node(id, "Start (A)") else: dot.node(id, id) for edge in node: # avoid duplicating edges by only showing to > from if edge > this: edge_str = id + str(chr(A + edge)) edges.append(edge_str) elif edge < 0: unknown_id = str(chr(a + unknowns)) unknowns = unknowns + 1 edge_str = id + unknown_id edges.append(edge_str) dot.node(unknown_id, "Unknown") this = this + 1 # The final node is not in the list, as it exists only as the destination # of one or more edge id = str(chr(A + len(maze))) dot.node(id, "End (%s)" % id) #print(edges) dot.edges(edges) #print(dot.source) dot.render(file_name, view=True)
def main(data_dir: str): nodes = file_io.read_nodes(data_dir) edges = file_io.read_edges(data_dir) groups = file_io.read_communities(data_dir) graph = Graph() for node in nodes: graph.node(node) graph.edges(edges) colors = get_colors(len(groups)) for i in range(len(groups)): group = groups[i] color = colors[i] with graph.subgraph(name='cluster-' + str(i)) as subgraph: subgraph.attr(color=color) for node in group: subgraph.node(node, color=color, style='filled') graph.format = 'png' graph.render(data_dir + '\\graph.gv') graph.view()
class AST: def __init__(self, tree): self.aux_node_list = [] self.second_aux = [] self.parser_tree = tree self.count = 0 self.dot = Graph('AST') self.shape_parser_tree(self.parser_tree) # self.bonsai_to_pdf(self.parser_tree, 0) # self.dot.render('ast.gv', view=True) def handle_expressions(self, node): #almost all if len(node.children) == 3 and not node.type == 'factor': left = self.handle_expressions(node.children[0]) operator = self.handle_expressions(node.children[1]) right = self.handle_expressions(node.children[2]) operator.children = [left, right] return operator elif node.type[-8:] == 'operator': operator = node.children[0] return operator elif node.type == 'var' and len(node.children[0].children) == 0: var_node = node.children[0] return var_node elif node.type == 'factor': factor_node = node.children[0] factor = node.children[0].type if len(node.children) == 3: factor_node = node.children[1] factor = node.children[1].type if factor == 'number': number = factor_node.children[0] print(number.type) return number elif factor == 'function_call': return factor_node elif factor == 'var': if len(factor_node.children) == 2: self.second_aux = [] self.extract_indexes(factor_node.children[1]) factor_node.children[0].children = self.second_aux var = factor_node.children[0] return var else: return self.handle_expressions(factor_node) elif len(node.children) == 1: return self.handle_expressions(node.children[0]) elif len(node.children) == 2: left = self.handle_expressions(node.children[0]) left.children = [self.handle_expressions(node.children[1])] return left else: return node def extract_argument_list(self, node): if len(node.children) == 3: self.aux_node_list.append(self.handle_expressions( node.children[2])) elif len(node.children) == 1 and node.children[0].type != 'Empty': self.aux_node_list.append(self.handle_expressions( node.children[0])) if node.children[0].type == 'argument_list': self.extract_argument_list(node.children[0]) def extract_indexes(self, index_node): if len(index_node.children) == 4: self.second_aux.append( self.handle_expressions(index_node.children[3])) elif len(index_node.children) == 3: self.second_aux.append( self.handle_expressions(index_node.children[1])) if index_node.children[0].type == 'index': self.extract_indexes(index_node.children[0]) def extract_variable_list(self, node): var_node = None if len(node.children) == 3: var_node = node.children[2] var_key = var_node.children[0] if len(var_node.children) == 2: self.extract_indexes(var_node.children[1]) self.second_aux.reverse() var_key.children = self.second_aux self.aux_node_list.append(var_key) elif len(node.children) == 1 and node.children[0].type != 'Empty': var_node = node.children[0] var_key = var_node.children[0] if len(var_node.children) == 2: self.extract_indexes(var_node.children[1]) self.second_aux.reverse() var_key.children = self.second_aux self.aux_node_list.append(var_key) if node.children[0].type == 'variable_list': self.extract_variable_list(node.children[0]) def extract_actions(self, node): if len(node.children) == 2: aux_node = node.children[1].children[0] if aux_node.type == 'expression': if aux_node.children[0].type[-11:] == '_expression': self.aux_node_list.append( self.handle_expressions(node.children[1].children[0])) else: self.aux_node_list.append( node.children[1].children[0].children[0]) else: self.aux_node_list.append(node.children[1].children[0]) if node.children[0].type == 'body': self.extract_actions(node.children[0]) def extract_declarations(self, node): if len(node.children) == 2: self.aux_node_list.append(node.children[1].children[0]) elif len(node.children) == 1: self.aux_node_list.append(node.children[0].children[0]) if node.children[0].type == 'declaration_list': self.extract_declarations(node.children[0]) def extract_parameter_list(self, node): #adicionar suporte para vetores if len(node.children) == 3: node.children[2].children[2].children = [ node.children[2].children[0].children[0] ] self.aux_node_list.append(node.children[2].children[2]) elif len(node.children) == 1 and node.children[0].type != 'Empty': node.children[0].children[2].children = [ node.children[0].children[0].children[0] ] self.aux_node_list.append(node.children[0].children[2]) if node.children[0].type == 'parameter_list': self.extract_parameter_list(node.children[0]) def shape_parser_tree(self, node): for child in node.children: self.shape_parser_tree(child) if node: self.aux_node_list = [] #list of actions if node.type == 'function_call': self.extract_argument_list(node.children[2]) self.aux_node_list.reverse() node.children[0].children = self.aux_node_list node.children = [node.children[0]] elif node.type == 'attribution': if len(node.children[0].children) == 2: self.second_aux = [] self.extract_indexes(node.children[0].children[1]) node.children[0].children[0].children = self.second_aux node.children[0] = node.children[0].children[0] node.children[2] = self.handle_expressions(node.children[2]) node.children = [node.children[0], node.children[2]] elif node.type == 'return' or node.type == 'write' or node.type == 'read': node.children[2] = self.handle_expressions(node.children[2]) node.children = [node.children[2]] elif node.type == 'if': node.children[1] = self.handle_expressions(node.children[1]) if len(node.children) == 7: self.extract_actions(node.children[5]) self.aux_node_list.reverse() node.children[5].children = self.aux_node_list self.aux_node_list = [] self.extract_actions(node.children[3]) self.aux_node_list.reverse() node.children[3].children = self.aux_node_list node.children[0].children = [node.children[1]] node.children[2].children = [node.children[3]] if len(node.children) == 7: node.children[4].children = [node.children[5]] node.children = [ node.children[0], node.children[2], node.children[4] ] else: node.children = [node.children[0], node.children[2]] elif node.type == 'repeat': node.children[3] = self.handle_expressions(node.children[3]) self.extract_actions(node.children[1]) self.aux_node_list.reverse() node.children[1].children = self.aux_node_list node.children[0].children = [node.children[1]] node.children[2].children = [node.children[3]] node.children = [node.children[0], node.children[2]] elif node.type == 'variable_declaration': #adicionar suporte aos indexes self.aux_node_list = [] self.second_aux = [] self.extract_variable_list(node.children[2]) self.aux_node_list.reverse() node.children[2].children = self.aux_node_list node.children = [ node.children[0].children[0], node.children[2] ] elif node.type == 'header': #body precisa de action self.extract_actions(node.children[4]) self.aux_node_list.reverse() node.children[4].children = self.aux_node_list self.aux_node_list = [] self.extract_parameter_list(node.children[2]) self.aux_node_list.reverse() node.children[2].children = self.aux_node_list node.type = node.children[0].type node.children = [node.children[2], node.children[4]] elif node.type == 'program': self.extract_declarations(node.children[0]) self.aux_node_list.reverse() node.children = self.aux_node_list elif node.type == 'function_declaration': if len(node.children) == 2: node.children = [ node.children[0].children[0], node.children[1] ] else: node.children = [Node('void'), node.children[0]] def print_node(self, node): for n in node.children: print(str(n.type)) def bonsai_to_pdf(self, node, count_node): self.dot.node(str(count_node), str(node.type)) for children in node.children: if children: self.count = self.count + 1 self.dot.edges([(str(count_node), str(self.count))]) self.bonsai_to_pdf(children, self.count)
# import networkx as nx # import matplotlib.pyplot as plt # from networkx.drawing.nx_agraph import graphviz_layout from graphviz import Graph dot = Graph(comment="The Roundtable", format="png") dot.node('A', 'King Arthur', style="filled", fillcolor="#373737") dot.node('B', 'Sir Bedevere the Wise', shape="square") dot.node('L', 'Sir Lancelot the Brave') dot.edges(['AB', 'AL']) dot.edge('B', 'L', constraint='false') print(dot.source) dot.render('round-table.gv') # g = nx.OrderedGraph() # edgelist = [(1, 2), (2, 3), (1, 4), (3, 4), (1, 5)] # g.add_edges_from(edgelist) # nx.draw(g) # plt.show() # G = nx.Graph() # G.add_node("ROOT") # for i in range(5): # G.add_node("Child_%i" % i)
# @Time : 2020/2/2 13:31 # @Software: PyCharm # @File : g-4.py # @Author : DezeZhao from graphviz import Graph g = Graph( name='tree', comment=None, filename='tree_graph.gv', directory=None, format='pdf', engine=None, encoding='utf-8', graph_attr={'rankdir': 'TB'}, node_attr={'shape': 'circle'} # edge_attr为默认 ) g.node('0', '000') g.node('1', '111') g.node('2', '222') g.node('3', '333') # g.edge('0', '1') # g.edge('0', '2') a = set(['01', '02']) # 等同于以上 b = set(['13', '14']) c = set(['25', '26']) d = set(['39', '3a']) g.edges(a | b | c | d) g.view()
def create_family_tree(persons, families): dot = Graph(edge_attr={'arrowhead': 'none'}, graph_attr={'splines':'ortho', }, node_attr={'shape': 'box'}) # create origins parents and marriages for family_id in families: family = families[family_id] if not has_ancestors(family): create_family_graph(dot, family, persons) # create kids for family_id in families: family = families[family_id] if family.kids: kids_point = '' for kid in family.kids: kids_point += kid.id + '_' with dot.subgraph(name=kids_point) as s: s.attr(rank='same') counter = 0 previous_pre = None for kid in family.kids: counter += 1 pre_point = "pre_" + kid.id pre_point_s = "" s.node(pre_point, shape='point', width='0', style='invis') if kid.s_id: pre_point_s = "pre_" + kid.s_id pre_point_w = "pre_" + get_marriage_id(kid, families) s.node(pre_point_s, shape='point', width='0', style='invis') s.node(pre_point_w, shape='point', width='0', style='invis') if len(family.kids) % 2 == 0: if counter == len(family.kids) / 2: s.node(kids_point, shape='point', width='0', style='invis') if len(family.kids) > 2: if kid.s_id: dot.edge(previous_pre, kids_point) if kid.sex == 'M': dot.edges([ (kids_point, pre_point_s), (pre_point_s, pre_point_w), (pre_point_w, pre_point), ]) else: dot.edges([ (kids_point, pre_point), (pre_point, pre_point_w), (pre_point_w, pre_point_s), ]) else: dot.edges([ (previous_pre, kids_point), (kids_point, pre_point), ]) previous_pre = None else: if kid.s_id: if kid.sex == 'M': dot.edges([ (pre_point, pre_point_w), (pre_point_w, pre_point_s), (pre_point_s, kids_point) ]) else: edges_invisible(dot, [pre_point_s, pre_point_w, pre_point]) dot.edge(pre_point, kids_point) else: dot.edge(pre_point, kids_point) kid_2 = family.kids[1] pre_point_2 = "pre_" + kid_2.id s.node(pre_point_2, shape='point', width='0', style='invis') if kid_2.s_id: pre_point_s_2 = "pre_" + kid_2.s_id pre_point_w_2 = "pre_" + get_marriage_id(kid_2, families) s.node(pre_point_s_2, shape='point', width='0', style='invis') s.node(pre_point_w_2, shape='point', width='0', style='invis') if kid_2.sex == 'M': dot.edge(kids_point, pre_point_2) edges_invisible(dot, [pre_point_2, pre_point_w_2, pre_point_s_2]) else: dot.edges([ (kids_point, pre_point_s_2), (pre_point_s_2, pre_point_w_2), (pre_point_w_2, pre_point_2), ]) else: dot.edge(kids_point, pre_point_2) break if previous_pre: if kid.s_id: if kid.sex == 'M': dot.edge(previous_pre, pre_point) if counter == len(family.kids): edges_invisible(dot, [pre_point, pre_point_w, pre_point_s]) else: dot.edges([ (pre_point, pre_point_w), (pre_point_w, pre_point_s), ]) pre_point = pre_point_s else: dot.edges([ (previous_pre, pre_point_s), (pre_point_s, pre_point_w), (pre_point_w, pre_point) ]) else: dot.edge(previous_pre, pre_point) else: if kid.s_id: if kid.sex == 'M': if len(family.kids) == 1: edges_invisible(dot, [pre_point, pre_point_w, pre_point_s]) else: dot.edges([ (pre_point, pre_point_w), (pre_point_w, pre_point_s) ]) pre_point = pre_point_s else: edges_invisible(dot, [pre_point_s, pre_point_w, pre_point]) previous_pre = pre_point # create marriages and kids points connection for family_id in families: family = families[family_id] marriage_id = get_marriage_id(family) if family.kids: kids_point = '' for kid in family.kids: kids_point += kid.id + '_' if len(family.kids) % 2 == 1: kids_point = "pre_" + family.kids[math.ceil(len(family.kids)/2)-1].id dot.edge(marriage_id, kids_point) # create kids and kids points connection for family_id in families: family = families[family_id] if family.kids: with dot.subgraph() as s: s.attr(rank='same') for kid in family.kids: counter += 1 pre_point = "pre_" + kid.id s.node(kid.id, create_label(persons, kid.id)) dot.edge(pre_point, kid.id) if kid.s_id: marriage_id = get_marriage_id(kid, families) pre_point_s = "pre_" + kid.s_id pre_point_w = "pre_" + marriage_id s.node(kid.s_id, create_label(persons, kid.s_id)) s.node(marriage_id, shape='point', width='0', style='invis') dot.edge(pre_point_s, kid.s_id, style='invis') dot.edge(pre_point_w, marriage_id, style='invis') if kid.sex == 'M': dot.edges([(kid.id, marriage_id), (marriage_id, kid.s_id)]) else: dot.edges([(kid.s_id, marriage_id), (marriage_id, kid.id)]) dot.render('output.png') return dot.source
denom = reduce(mul, range(1, r + 1), 1) return numer // denom def combs(n): # calculate number of possibilites for an n-cycle return sum(ncr(n - i + 1, i) - ncr(n - i - 1, i - 2) for i in range(n)) inputs = list(product([False, True], repeat=6)) # Generate and render graph of input transformations to observe that they form disjoint cycles dot = Graph() for i in range(64): dot.node(str(i)) dot.edges( (str(inputs.index(p)), str(inputs.index(transform(p)))) for p in inputs) dot.render('graph') # Count cycle lengths cycles = [] while inputs: t = inputs.pop() n = transform(t) length = 1 while n != t: inputs.remove(n) n = transform(n) length += 1 cycles.append(length) # Calculate answer by multiplying together number of possiblities for each cycle
# pip install graphviz from graphviz import Graph # Instantiate a new Graph object dot = Graph('Data Science Process', format='png') # Add nodes dot.node('A', 'Get Data') dot.node('B', 'Clean, Prepare, & Manipulate Data') dot.node('C', 'Train Model') dot.node('D', 'Test Data') dot.node('E', 'Improve') # Connect these nodes dot.edges(['AB', 'BC', 'CD', 'DE']) # Save chart dot.render('data_science_flowchart', view=True)
colors = 3 #0 1 2 3 4 5 graph_ = [[0,1,0,0,1,0],#0 [1,0,1,0,1,0],#1 [0,1,0,1,0,0],#2 [0,0,1,0,1,1],#3 [1,1,0,1,0,0],#4 [0,0,0,1,0,0]]#5 m = len(graph_) colors_m = [0] * m nodo = 0 GiveColor(graph_, colors, colors_m, 0) print (colors_m) dot = Graph(comment='Coloring ..') for i in colors_m: coloring = str(nodo) + '[color="' + colorsRGB[i]+'"]' print coloring nodo=nodo+1 dot.node(coloring) dot.edges(['01','04','12','14','23','34','35']) print(dot.source) dot.format='svg' dot.render()
def CEKBUTTON(self): if self.CekButton['text'] == "Check": if self.MyEntry.get() == "": self.tulisan2["text"] = "The input is blank" self.tulisan2["fg"] = "red" self.tulisan3["text"] = "" return testing = eval(self.MyEntry.get()) for i in testing: try: eval(str(i)) except: self.tulisan2["text"] = "Tidak semuanya angka" self.tulisan2["fg"] = "red" self.tulisan3["text"] = "" return if not self.ischecked: for i in testing: if testing.count(i) > 1: self.tulisan2["text"] = "Angka-angka tidak unique" self.tulisan2["fg"] = "red" self.tulisan3["text"] = "" return nodes = [] if not self.ischecked: dot = Graph(format='png') somevar1 = {} somevar2 = {} for i in range(len(testing)): somevar1[chr(65 + i)] = str(testing[i]) somevar2[str(testing[i])] = chr(65 + i) for i in range(len(testing)): dot.node(somevar2[str(testing[i])], str(testing[i])) for i in testing: nodes.append(Node(i)) track = DLL() for i in nodes: track.push_back(i) if self.ischecked: track.sort() self.hasil = str(track.print_list()) self.tulisan2['text'] = "Input valid" self.tulisan2['fg'] = "green" self.tulisan3['text'] = "" self.MyEntry['state'] = tk.DISABLED else: BT = BinaryTree() self.hasil = BT.insert(track) somecon = [] for i in range(len(track)): current_pointer = self.hasil.search(eval(str(testing[i]))) if isinstance(current_pointer.left, BinaryTree): if isinstance(current_pointer.right, BinaryTree): somecon.append( somevar2[str(current_pointer.root)] + somevar2[str(current_pointer.left.root)]) somecon.append( somevar2[str(current_pointer.root)] + somevar2[str(current_pointer.right.root)]) else: somecon.append( somevar2[str(current_pointer.root)] + somevar2[str(current_pointer.left.root)]) dot.edges( somecon ) #Look at this https://pypi.org/project/graphviz/ and https://stackoverflow.com/questions/26653929/pdf-viewer-for-python-tkinter dot.render('tree-output/BinaryTree') self.tulisan2['text'] = "Input sebuah angka" self.tulisan2['fg'] = "SystemButtonText" self.tulisan3['text'] = str(self.hasil) self.CheckBox['state'] = tk.DISABLED self.CekButton['text'] = "Batal" self.FindButton['state'] = tk.NORMAL self.MyEntry.delete(0, 'end') if not self.ischecked: load = Image.open('tree-output/BinaryTree.png') load = load.resize((350, 350), Image.ANTIALIAS) render = ImageTk.PhotoImage(load) self.top1 = tk.Toplevel() self.top1.geometry("400x400") self.top1.minsize(350, 350) img = tk.Label(self.top1, image=render) img.image = render img.pack() self.top1.protocol("WM_DELETE_WINDOW", self.CommandTop2) else: self.CekButton['text'] = "Check" self.tulisan2['text'] = "Is it really a set of numbers?" self.tulisan2['fg'] = "SystemButtonText" self.tulisan3['text'] = "" self.MyEntry['state'] = tk.NORMAL self.CheckBox['state'] = tk.NORMAL self.FindButton['state'] = tk.DISABLED self.MyEntry.delete(0, 'end') try: self.top1.destroy() except: pass try: self.top.destroy() except: pass