def render_graph(): user_coords = str(request.data) user_coords = user_coords.split('&') user_latitude = float(user_coords[0][6:]) user_longitude = float(user_coords[1][5:-1]) chart_data = Graph() items = Trash.query.all() chart_data.node('U', 'USER') prev_egde_id = 'U' start_item = find_closest(items, lat=user_latitude, long=user_longitude) cl_item_id = str(start_item.id) chart_data.node(cl_item_id, cl_item_id) chart_data.edge(prev_egde_id, cl_item_id) prev_egde_id = cl_item_id while items: closest_item = find_closest(items, start_item) cl_item_id = str(closest_item.id) chart_data.node(cl_item_id, cl_item_id) chart_data.edge(prev_egde_id, cl_item_id) prev_egde_id = cl_item_id start_item = closest_item chart_output = chart_data.pipe(format='png') chart_output = base64.b64encode(chart_output).decode('utf-8') return chart_output
def consult_notebook(self, current_cave_id): """ Produces an svg representation of the explored portions of the cavern system along with warnings relevant to certain caves. :param: current_cave_id - where the hunter is currently located. :return: string reprsentation of svg based cavern map (using graphviz) """ tunnels = self.find_tunnels() dot = Graph(comment='Your notebook - explored caves') for mapped_cave in self.cavern_map: warning_sources = "" if mapped_cave.warnings: dot.attr('node', color='yellow') warning_sources = ",".join( [warning.source for warning in mapped_cave.warnings]) else: dot.attr('node', color='green') current_location = '*' if mapped_cave.cave.id == current_cave_id else '' dot.node(f'{mapped_cave.cave.id}', f'{mapped_cave.cave.id} {current_location}', _attributes=[('tooltip', f'{warning_sources}')]) for tunnel in tunnels: dot.attr('node', color='black') dot.edge(f'{tunnel[0]}', f'{tunnel[1]}') svg_data = dot.pipe(format='svg') return "".join(chr(datum) for datum in svg_data)
def dump_graph(self): """ Use graphviz to dump into an image. Return the base64-encoded string of a png file. """ dot = Graph(format='png') self.root.dump_graph(dot) return b64encode(dot.pipe()).decode('utf-8')
def svgtest(): chart_data = Graph() chart_data.node('H', 'Hello') chart_data.node('W', 'World') chart_data.edge('H', 'W') chart_output = chart_data.pipe(format='png') chart_output = base64.b64encode(chart_output).decode('utf-8') return render_template('poc_flask_graphviz.html', chart_output=chart_output)
Wed May 9 17:58:19 2018: Dhiraj """ #http://graphviz.readthedocs.io/en/stable/manual.html #working now : had to restart Spyder and PC after installing and configuring path for graphviz from graphviz import Digraph dot = Digraph(comment='The Round Table') dot print(dot) # dot.node('A', 'King Arthur') dot.node('B', 'Sir Bedevere the Wise') dot.node('L', 'Sir Lancelot the Brave') dot.edges(['AB', 'AL']) dot.edge('B', 'L', constraint='false') print(dot.source) dot.render('test-output/round-table.gv', view=True) # from graphviz import Graph g = Graph(format='png') dot.format = 'svg' dot.render() #Piped Output h = Graph('hello', format='svg') h.edge('Hello', 'World') print(h.pipe().decode('utf-8'))
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)
def build_network(self): if not self.jaccard_dict: return 'No_dict' # networkxで計算 G = nx.Graph() # 接点/単語(node)の追加 nodes = set([j for pair in self.jaccard_dict.keys() for j in pair]) G.add_nodes_from(nodes) # 線(edge)の追加 for pair, coef in self.jaccard_dict.items(): G.add_edge(pair[0], pair[1], weight=coef) # focusの場合 if self.focus: try: keepnodes = list((G[self.focus]).keys()) except KeyError: return 'No_focus' else: keepnodes = list((G[self.focus]).keys()) keepnodes.append(self.focus) print(f'🟦{keepnodes}') #ノード削除 rm_nodes = set(nodes) ^ set(keepnodes) G.remove_nodes_from(rm_nodes) G.remove_nodes_from(list(isolates(G))) print('Number of nodes =', G.number_of_nodes()) print('Number of edges =', G.number_of_edges()) # graphviz.pyで描写 g = Graph(engine='neato') g.attr(overlap='false') g.attr(size='800,500') g.attr(outputorder="edgesfirst") # networkxのpagerankを活用して色やノードサイズを変化させる pagerank = nx.pagerank(G) print(pagerank) cm = plt.get_cmap('rainbow') for node, rank in pagerank.items(): ncm = cm(rank * 15) colorhex = mcolors.to_hex(ncm) if node in self.emojidict.keys(): g.attr('node', shape='circle', color=str(colorhex), style='filled', fixedsize='True', height=20, imagescale='both', margin=' 0.001,0.001') emojivalue = self.emojidict[node] emoji_img = Image.open( requests.get(emojivalue[1], stream=True).raw) bytes = io.BytesIO() emoji_img.save(bytes, format='PNG') g.node(bytes) bytes.close() else: g.attr('node', shape='circle', color=str(colorhex), style='filled', fontsize='22', fontpath='SourceHanSansHW-Bold.otf', fixedsize='True', height=str(len(node) / 3.3 + 10 * rank)) g.node(node) edges = [] for source in G.edges(data=True): edges.append([source[0], source[1], source[2]['weight']]) print(edges) for edge in edges: g.attr('edge', weight=str(min(edge[2] * 10, 30))) g.edge(edge[0], edge[1]) g.format = 'png' datastream = io.BytesIO(g.pipe()) datastream.seek(0) pngimage = discord.File(datastream, filename=f'discord_network_graph.png') datastream.close() return pngimage
def general_graph(self, timeline: Iterable[Optional[List[int]]], edges: Iterable[Iterable[int]], extra_nodes: Iterable[int] = tuple(), view: bool = False, fontsize: int = 20, fontcolor: str = 'black', penwidth: float = 2.2, first_color: str = 'yellow', first_style: str = 'filled', second_color: str = 'green', second_style: str = 'dotted,filled', third_color: str = 'red', graph_name: str = 'graph', file_basename: str = 'graph', do_sort_nodes: bool = True, do_adj_nodes: bool = True, var_name: str = '') -> None: """ Creates one graph emphasized for the given timeline. Parameters ---------- edges : Iterable of: {int, int} All edges between nodes in the graph. Should NOT contain self-edges! BOTH edges (x, y) and (y, x) could be in the edgelist. extra_nodes : Iterable of int Nodes that are probably not in the edges, but should be rendered. TIMELINE : Iterable of: None | [int...] None if no variables get highlighted in this step. Else the 'timeline' provides the set of variables that are in the bag(s) under consideration. This function computes all other variables that are involved in this timestep using the 'edgelist'. colors : Iterable of color Colors to use for the graph parts. Returns ------- None, but outputs the files with the graph for each timestep. """ _filename = self.outfolder / file_basename LOGGER.info("Generating general-graph for '%s'", file_basename) vartag_n: str = var_name + '%d' # sfdp http://yifanhu.net/SOFTWARE/SFDP/index.html default_engine = 'sfdp' graph = Graph(graph_name, strict=True, engine=default_engine, graph_attr={ 'fontsize': str(fontsize), 'overlap': 'false', 'outputorder': 'edgesfirst', 'K': '2' }, node_attr={ 'fontcolor': str(fontcolor), 'penwidth': str(penwidth), 'style': 'filled', 'fillcolor': 'white' }) if do_sort_nodes: bodybaselen = len(graph.body) # 1: layout with circo graph.engine = 'circo' # 2: nodes in edges+extra_nodes make a circle nodes = sorted([ vartag_n % n for n in set(itertools.chain(flatten(edges), extra_nodes)) ], key=lambda x: (len(x), x)) for i, node in enumerate(nodes): graph.edge(str(nodes[i - 1]), str(node)) # 3: reads in bytes! code_lines = graph.pipe('plain').splitlines() # 4: save the (sorted) positions assert code_lines[0].startswith(b'graph') node_positions = [ line.split()[1:4] for line in code_lines[1:] if line.startswith(b'node') ] # 5: cut layout graph.body = graph.body[:bodybaselen] for line in node_positions: graph.node(line[0].decode(), pos='%f,%f!' % (float(line[1]), float(line[2]))) # 6: Engine uses previous positions graph.engine = 'neato' for (src, tar) in edges: graph.edge(vartag_n % src, vartag_n % tar) for nodeid in extra_nodes: graph.node(vartag_n % nodeid) bodybaselen = len(graph.body) for i, variables in enumerate(timeline, start=1): # all timesteps # reset highlighting graph.body = graph.body[:bodybaselen] if variables is None: graph.render(view=view, format='svg', filename=str(_filename) + str(i)) continue for var in variables: graph.node(vartag_n % var, fillcolor=first_color, style=first_style) # highlight edges between variables for (s, t) in edges: if s in variables and t in variables: graph.edge(vartag_n % s, vartag_n % t, color=third_color, penwidth=str(penwidth)) if do_adj_nodes: # set.difference accepts list as argument, "-" does not. edges = [set(edge) for edge in edges] adjacent = { edge.difference(variables).pop() for edge in edges if len(edge.difference(variables)) == 1 } for var in adjacent: graph.node(vartag_n % var, color=second_color, style=second_style) graph.render(view=view, format='svg', filename=str(_filename) + str(i))