def draw_clusters(self, pydot_graph): clusters = {} for node_name, pydot_node in self.pydot_nodes.items(): separator = self.__prefs['cluster_name_separator'] if node_name.find(separator) > 0: cluster_name = node_name[0:node_name.find(separator)] else: cluster_name = node_name # Dot doesn't handle well clusters with names that contain '-' cluster_name = cluster_name.replace('-', '_') is_new_cluster = True for name, cluster in clusters.items(): if name == cluster_name: is_new_cluster = False cluster.add_node(pydot_node) break if is_new_cluster: cluster = pydot.Cluster(cluster_name, label=cluster_name) clusters[cluster_name] = cluster # print("creating cluster: ", cluster_name) cluster.add_node(pydot_node) for cluster in clusters.values(): # for clusters of size 1, we don't want to draw a cluster box if len(cluster.get_nodes()) == 1: pydot_graph.add_node(cluster.get_nodes()[0]) else: pydot_graph.add_subgraph(cluster)
def _create_base_dot(self, subheading): dot = pydot.Dot("NOC", graph_type="digraph", strict=True) dot.set_prog("neato") dot.set_node_defaults(shape="none", fontsize=14, margin=0, fontname="Arial") dot.set_edge_defaults(fontsize=13, fontname="Arial") # dot.set_page('11.7,8.3!') # dot.set_margin(0.5) # dot.set_ratio('fill') dot.set_rankdir("LR") dot.set_fontname("Arial") dot.set_nodesep(0.3) dot.set_splines("spline") sg = pydot.Cluster() # 'physical', label='Physical') # sg.set_color('gray80') sg.set_style("invis") # sg.set_labeljust('l') dot.add_subgraph(sg) title = pydot.Node( "title", shape="none", label=self._title_label(self.opts.get("name"), subheading), ) title.set_pos("0,0!") title.set_fontsize(18) dot.add_node(title) return dot, sg
def _add_bundle(bundle): count[2] += 1 subdot = pydot.Cluster( graph_name='c%d' % count[2], URL='"%s"' % bundle.identifier.uri ) if use_labels: if bundle.label == bundle.identifier: bundle_label = '"%s"' % six.text_type(bundle.label) else: # Fancier label if both are different. The label will be # the main node text, whereas the identifier will be a # kind of suptitle. bundle_label = ('<%s<br />' '<font color="#333333" point-size="10">' '%s</font>>') bundle_label = bundle_label % ( six.text_type(bundle.label), six.text_type(bundle.identifier) ) subdot.set_label('"%s"' % six.text_type(bundle_label)) else: subdot.set_label('"%s"' % six.text_type(bundle.identifier)) _bundle_to_dot(subdot, bundle) dot.add_subgraph(subdot) return subdot
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 draw_subgraphs(self, tplgy, pydot_graph): nodes = [] tplgy.traverse(lambda node: nodes.append(node)) clusters = {} for node in nodes: pydot_node = self.pydot_nodes[node.name] if not hasattr(node, 'subgraph'): pydot_graph.add_node(pydot_node) continue cluster_name = str(node.subgraph) if cluster_name in clusters: cluster = clusters[cluster_name] else: # New subgraph cluster = pydot.Cluster(cluster_name, label=cluster_name, style="filled") clusters[cluster_name] = cluster cluster.add_node(pydot_node) for _, cluster in clusters.items(): pydot_graph.add_subgraph(cluster) pydot_graph.write_raw('debug.dot')
def _get_subgraph(plan: Plan): dot = pydot.Cluster(_sanitise_name(plan.name), label="Grid %s" % plan.name) for n in plan.nodes(): if n.name is None: raise Exception( "Nodes must all be named! {} is missing a name".format(n)) node = pydot.Node(n.name, label=_node_label(n)) dot.add_node(node) for u, v, edgedata in plan.edges(): edge = pydot.Edge(u.name, v.name) label = "{}A".format(edgedata["current"]) if edgedata["phases"] == 3: colour = COLOUR_THREEPHASE label += " 3ϕ" else: colour = COLOUR_SINGLEPHASE if edgedata.get("csa"): label += " {}mm²".format(edgedata["csa"]) if edgedata.get("cable_lengths"): label += "\n{} ({}m spare)".format( " + ".join(str(l) + "m" for l in edgedata["cable_lengths"]), sum(edgedata["cable_lengths"]) - edgedata["length"], ) if not edgedata.get("logical"): edge.set_label(label) edge.set_tailport("{}-{}".format(edgedata["current"], edgedata["phases"])) edge.set_headport("input") edge.set_color(colour) dot.add_edge(edge) return dot
def draw_tree(): from PIL import ImageTk, Image as Image_PIL class ResizingCanvas(Canvas): def __init__(self,parent,**kwargs): Canvas.__init__(self,parent,**kwargs) self.bind("<Configure>", self.on_resize) self.height = self.winfo_reqheight() self.width = self.winfo_reqwidth() # self.bind_all("<MouseWheel>", self.on_mousewheel) def on_resize(self,event): new_width = self.master.winfo_width() new_height = self.master.winfo_height() #colors col_f='#ff4e5c' col_m='#1c3144' col_w='#9d7a7d' # top = tk.Tk() top.iconbitmap(f'{main_f}2683232.ico') Grid.rowconfigure(top, 0, weight=1) Grid.columnconfigure(top, 0, weight=1) top.geometry("900x480") top.wm_title("Tree") frame = tk.Frame(top) frame.grid(row=0, column=0, sticky=N+S+E+W) #scrollbars xscrollbar = tk.Scrollbar(frame, orient=tk.HORIZONTAL) xscrollbar.grid(row=1, column=0, sticky="EW") yscrollbar = tk.Scrollbar(frame) yscrollbar.grid(row=0, column=1, sticky="NS") canvas = ResizingCanvas(frame, xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set) canvas.grid(row=0, column=0, sticky="EWNS") canvas.configure(bg='white') # Image import pydotplus as pdt import time df=pddf(backend_app.view(), columns=c_header) for c in ['id', 'mother_id', 'father_id', 'spouse_id', 'generation', 'cluster', 'gender' ]: df[c]=to_numeric(df[c], downcast='integer',errors='coerce') min_level=int(df['generation'].min()) max_level=int(df['generation'].max()) g = pdt.Dot(graph_type='digraph', compound='true', rankdir='TB',newrank = 'true') i=0 edges = [] nodes=[] # create all edges from ast import literal_eval as make_tuple nl=max_level-min_level+1 s=[None]*(max_level+1) for i in range(min_level,max_level+1): s = pdt.Subgraph(i,rank='same') for j in df.loc[df['generation']==i, 'id'].values : s.add_node(pdt.Node(f"{df.loc[df['id']==j, 'id'].values[0]}")) g.add_subgraph(s) min_cl=int(df['cluster'].min()) max_cl=int(df['cluster'].max()) nl=max_cl-min_cl+1 ss=[None]*(max_cl+1) for i in range(min_cl,max_cl+1): ss = pdt.Cluster(f'c1_{i}', color="white",rankdir="TB") for j in df.loc[df['cluster']==i, 'id'].values : ss.add_node(pdt.Node(f"{df.loc[df['id']==j, 'id'].values[0]}")) g.add_subgraph(ss) for i in range(df.shape[0]): m=df.loc[i, 'mother_id'] f=df.loc[i, 'father_id'] nod=pdt.Node(f"{df.loc[i, 'id']}", shape='record', color=col_m, style='rounded') if m in df['id'].values: g.add_edge(pdt.Edge(pdt.Node(f"{df.loc[df['id']==m, 'id'].values[0]}"), nod, color=col_f)) if f in df['id'].values: g.add_edge(pdt.Edge(pdt.Node(f"{df.loc[df['id']==f, 'id'].values[0]}"), nod, color=col_m)) if notnull(df.loc[i, 'spouse_id']): who=to_numeric(df.loc[i, 'spouse_id'], downcast='integer', errors='coerce') if who in df['id'].values: g.add_edge(pdt.Edge(pdt.Node(f"{df.loc[df['id']==who, 'id'].values[0]}"), nod, dir='none',color=col_w)) #label='m', for i in range(df.shape[0]): cc=col_f if df.loc[i, 'gender']==1: cc=col_m sstr=f"{df.loc[i, 'name']}" if notnull(df.loc[i, 'surname']): sstr=f"{sstr} {df.loc[i, 'surname']}" if notnull(df.loc[i, 'date_birth']): if isinstance(df.loc[i, 'date_birth'], int) or isinstance(df.loc[i, 'date_birth'], str): sstr=f"{sstr}\nB: {df.loc[i, 'date_birth']}" else: sstr=f"{sstr}\nB: {df.loc[i, 'date_birth'].strftime('%d %b %Y') }" # %H:%M:%S d=df.loc[i, 'date_death'] # import numpy as np if notnull(d): # print("ddd" , isna(d), isnull(d), d, type(d) ) sstr=f"{sstr}\nD: {d}" if notnull(df.loc[i, 'place_birth']): sstr=f"{sstr}\nPoB: {df.loc[i, 'place_birth']} ({df.loc[i, 'country_birth']})" if not (isnull(df.loc[i, 'comments']) or df.loc[i, 'comments']==''): sstr=f"{sstr}\nComments: {df.loc[i, 'comments']}" nod=pdt.Node(f"{df.loc[i, 'id']}", label=sstr, shape='box', color=cc, style='rounded') g.add_node(nod) import io buf = io.BytesIO() g.write_png(buf) # plt.savefig(buf, format='png') buf.seek(0) img_g = Image_PIL.open(buf) img = ImageTk.PhotoImage(img_g, master=frame) canvas.create_image(0, 0, image=img) #scrollconfig canvas.config(scrollregion=canvas.bbox(tk.ALL)) xscrollbar.config(command=canvas.xview) yscrollbar.config(command=canvas.yview) frame.grid(row=0, column=0) frame.grid_rowconfigure(0, weight=1) frame.grid_columnconfigure(0, weight=1) #menu menubar = Menu(top) top.config(menu=menubar) menu = Menu(menubar) def file_save(): from tkinter.filedialog import asksaveasfilename f = asksaveasfilename(title = "Select file",filetypes = (("png files","*.png"),("all files","*.*")), defaultextension='.png') if f is None: # asksaveasfile return `None` if dialog closed with "cancel". return img_g.save(f) menu.add_command(label='Save',command=file_save) menu.add_command(label='Close',command=top.destroy) # menu.add_command(label="Exit", command=window.quit) menubar.add_cascade(label="File", menu=menu) top.mainloop()
def draw_words(G, words, chainWords, filename): func.print_info("drawing words onto graph") colours = ["blue", "yellow", "seagreen", "crimson", "magenta", "cyan","darkorchid4", "peru", "cadetblue1", "magenta", "indianred2", "plum", "brown", "skyblue", "darkgreen", "darkolivegreen2", "darkslategray1", "dodgerblue", "gold", "green", "hotpink1", "indianred2", "maroon3","plum", "yellow", "tan1", "steelblue1", "violetred", "blueviolet", "darkgoldenrod", "darkorange", "olivedrab3", "palevioletred", "skyblue", "yellowgreen", "seagreen", "peru", "moccasin", "cadetblue","burlywood1", "chartreuse3", "darksalmon", "blue", "aquamarine", "brown", "blueviolet", "cadetblue1", "chocolate", "crimson", "darkgreen", "darkolivegreen2", "darkslategray1", "deeppink", "dodgerblue", "gold", "green", "hotpink1", "maroon3", "yellow", "tan1", "steelblue1", "violetred", "blueviolet", "darkgoldenrod", "darkorange", "olivedrab3", "palevioletred", "yellowgreen", "seagreen", "magenta", "peru", "moccasin", "lightpink", "darkslategray1","cadetblue","burlywood1", "chartreuse3", "darksalmon","blue", "aquamarine", "brown", "blueviolet", "cadetblue1", "chocolate", "crimson", "cyan", "darkgreen", "darkolivegreen2", "darkorchid4", "deeppink", "dodgerblue", "gold", "green", "hotpink1", "cyan","indianred2", "maroon3","plum", "yellow", "tan1", "steelblue1", "violetred", "blueviolet", "darkgoldenrod", "darkorange", "olivedrab3", "palevioletred", "skyblue", "yellowgreen", "moccasin", "lightpink", "cadetblue","burlywood1", "chartreuse3", "blueviolet", "darksalmon","blue", "brown", "blueviolet", "cadetblue1", "chocolate","chocolate", "darkorchid4", "crimson", "cyan", "darkgreen", "darkolivegreen2", "darkorchid4", "darkslategray1", "deeppink", "dodgerblue", "gold", "green", "hotpink1", "indianred2", "maroon3","plum", "aquamarine","tan1", "steelblue1", "violetred", "blueviolet", "darkgoldenrod", "darkorange", "olivedrab3", "palevioletred", "skyblue", "yellowgreen", "seagreen", "magenta", "peru", "moccasin", "lightpink", "cadetblue","burlywood1", "chartreuse3", "darksalmon","blue", "aquamarine", "brown", "blueviolet", "cadetblue1", "chocolate", "crimson", "cyan", "darkgreen", "darkolivegreen2", "darkorchid4", "darkslategray1", "deeppink", "deeppink", "lightpink", "dodgerblue", "gold", "green", "hotpink1", "indianred2", "maroon3","plum", "yellow", "tan1", "steelblue1", "violetred", "blueviolet", "darkgoldenrod", "darkorange", "olivedrab3", "palevioletred", "skyblue", "yellowgreen", "seagreen", "magenta", "peru", "moccasin", "lightpink", "cadetblue","burlywood1", "chartreuse3", "darksalmon",] subsets = [x for x in words for y in words if y is not x and set(x).issubset(y)] words_clean = [] for word in words: if word not in subsets: words_clean.append(word) words_clean.append(func.control_wires) if len(words_clean) <= len(colours): H = nx.nx_pydot.to_pydot(G) P = nx.nx_pydot.to_pydot(G) counter = 0 I = pydotplus.Cluster("Inputs") O = pydotplus.Cluster("Outputs") for word in words_clean: S = pydotplus.Cluster("word" + str(counter), style="filled", color=colours[counter]) for node in word: S.add_node(pydotplus.Node(node)) if node.startswith("INPUT"): I.add_node(pydotplus.Node(node)) if node.startswith("OUTPUT"): O.add_node(pydotplus.Node(node)) if node not in [x.get_name() for x in P.get_nodes()]: n = P.get_node("\"" + node + "\"")[0] else: n = P.get_node(node)[0] n.set_style("filled") n.set_color(colours[counter]) H.add_subgraph(S) #~ H.add_subgraph(O) #~ H.add_subgraph(I) #~ P.add_subgraph(I) #~ P.add_subgraph(O) #@todo: fix clustering of primary inputs and outputs... counter = counter +1 for word in chainWords: for node in word: if node not in [x.get_name() for x in P.get_nodes()]: n = P.get_node("\"" + node + "\"")[0] else: n = P.get_node(node)[0] #~ n.set_style("filled") n.set_color(colours[counter]) counter = counter +1 H.write_raw("wordGraphs/" + filename + ".dot") P.write_raw("wordGraphs/" +filename + "2.dot") else: print("Not enough colors to properly draw word Graph") input() func.print_info("Finished drawring words onto graph") return
def make_graph(data, show_edge_labels=True, vertical=True, orthogonal_lines=False): """ Returns the visualization object of the imported bpmn-graph. Parameters ---------- data: DataContainer Object that contains a graph read from the file. show_edge_labels: boolean, default=False If True, edges' labels are displayed in the graph. vertical: boolean, default=True If True, the direction from the first to the last nodes goes from up to down. orthogonal_lines: boolean, default=False If true, draws edges that can bend at 90 degrees only, uses splines otherwise. Returns ------- pydotplus_graph: pydotplus.Dot Graph that can be visualized. """ pydot_node_id_dict = {} # {id: pydotplus.Node(), ...} all_local_nodes = [ obj for obj in data.all_objects.values() if isinstance(obj, LocalNode) ] all_local_edges = [ obj for obj in data.all_objects.values() if isinstance(obj, LocalEdge) ] pydot_graph = pydotplus.Dot(strict=True) cluster_dict = { obj.id: pydotplus.Cluster(obj.id, color='lightblue') for obj in all_local_nodes if not obj.is_separate_node } # Adding normal (separate) nodes to clusters (subgraphs) for node in all_local_nodes: if node.is_separate_node: node_graph = cluster_dict[ node.parent_node. id] if node.parent_node.id in cluster_dict else pydot_graph PydotPlusGraphMaker._create_pydot_node(node, node_graph, pydot_node_id_dict) # Adding subgraphs to each other (in case one subgraph is inside another) proc_list = list(data.all_objects[k] for k in cluster_dict.keys()) ready_subgraphs = set() while len(proc_list) != 0: proc = proc_list.pop(0) subgraph_list = proc.get_subgraph_objects() if not set(subgraph_list).issubset(ready_subgraphs): proc_list.append(proc) # work on it later else: # add it to upper pydot_graph upper_proc = proc.parent_node upper_graph = pydot_graph if upper_proc is None else cluster_dict[ upper_proc.id] upper_graph.add_subgraph(cluster_dict[proc.id]) ready_subgraphs.add(proc) # Modify names because graphviz can work incorrectly with specific symbols for graph in [pydot_graph] + list(cluster_dict.values()): graph.set_name(PydotPlusGraphMaker._modify_id(graph.get_name())) for n in graph.get_nodes(): n.set_name(PydotPlusGraphMaker._modify_id(n.get_name())) # Create pydotplus.Edges for edge in all_local_edges: if edge.type == 'attachedToRef': color = 'pink' else: color = 'black' e = pydotplus.Edge(pydot_node_id_dict[edge.source_node.id], pydot_node_id_dict[edge.target_node.id], color=color) if show_edge_labels: e.set('label', '\n'.join(edge.get_object_names())) pydot_graph.add_edge(e) if not vertical: pydot_graph.set('rankdir', 'LR') if orthogonal_lines: pydot_graph.set('splines', 'ortho') return pydot_graph
def draw_tree(): from PIL import ImageTk, Image as Image_PIL c_header=['id', 'name', 'surname', 'date_birth', 'date_death', 'mother_id', 'father_id', 'spouse_id', 'generation', 'cluster', 'gender', 'place_birth', 'country_birth', 'country', 'comments' ] # Image import pydotplus as pdt import time # import pandas as pd df=pddf(backend.view(), columns=c_header) for c in ['id', 'mother_id', 'father_id', 'spouse_id', 'generation', 'cluster', 'gender' ]: df[c]=to_numeric(df[c], downcast='integer',errors='coerce') # df[c]=df[c].astype(int) # df=pd.read_excel('c:/a_tree/gen_tree.xlsx', sheet_name=nn) # print(df) min_level=int(df['generation'].min()) max_level=int(df['generation'].max()) g = pdt.Dot(graph_type='digraph', compound='true', rankdir='TB',newrank = 'true') i=0 edges = [] nodes=[] # create all edges #edges = [(1,2), (1,3), (2,4), (2,5), (3,5)] #nodes = [(1, "A", "r"), (2, "B", "g"), (3, "C", "g"), (4, "D", "r"), (5, "E", "g")] #for e in edges: # g.add_edge(pdt.Edge(e[0], e[1], color=e[2])) # #for n in nodes: # node = pdt.Node(name=n[0], label= n[1], fillcolor=n[2], style="filled" ) # g.add_node(node) # # from ast import literal_eval as make_tuple nl=max_level-min_level+1 s=[None]*(max_level+1) for i in range(min_level,max_level+1): s = pdt.Subgraph(i,rank='same') for j in df.loc[df['generation']==i, 'id'].values : # s.add_node(pdt.Node(f"{df.loc[df['id']==j, 'Name'].values[0]} {df.loc[df['id']==j, 'Surname'].values[0]}")) s.add_node(pdt.Node(f"{df.loc[df['id']==j, 'id'].values[0]}")) g.add_subgraph(s) #min_cl=df['Cluster2'].min() #max_cl=df['Cluster2'].max() #nl=max_cl-min_cl+1 #ss=[None]*(max_cl+1) #for i in range(min_cl,max_cl+1): # if i>0: # ss = pdt.Cluster(f'c2_{i}', color="blue",rankdir="TB") # for j in df.loc[df['Cluster2']==i, 'id'].values : # # s.add_node(pdt.Node(f"{df.loc[df['id']==j, 'Name'].values[0]} {df.loc[df['id']==j, 'Surname'].values[0]}")) # ss.add_node(pdt.Node(f"{df.loc[df['id']==j, 'id'].values[0]}")) # g.add_subgraph(ss) min_cl=int(df['cluster'].min()) max_cl=int(df['cluster'].max()) nl=max_cl-min_cl+1 ss=[None]*(max_cl+1) for i in range(min_cl,max_cl+1): ss = pdt.Cluster(f'c1_{i}', color="white",rankdir="TB") for j in df.loc[df['cluster']==i, 'id'].values : # s.add_node(pdt.Node(f"{df.loc[df['id']==j, 'Name'].values[0]} {df.loc[df['id']==j, 'Surname'].values[0]}")) ss.add_node(pdt.Node(f"{df.loc[df['id']==j, 'id'].values[0]}")) g.add_subgraph(ss) for i in range(df.shape[0]): m=df.loc[i, 'mother_id'] f=df.loc[i, 'father_id'] # if m in df['id'].values: edges.append((i,df.loc[df['id']==m, 'Name'].index[0],'orange')) # if f in df['id'].values: edges.append((i,df.loc[df['id']==f, 'Name'].index[0],'blue')) # nodes.append((i, df.loc[i, 'Name'], 'blue')) # nod=pdt.Node(f"{df.loc[i, 'id']}",label=f"{df.loc[i, 'Name']} {df.loc[i, 'Surname']}", shape='record', color="blue", style='rounded') nod=pdt.Node(f"{df.loc[i, 'id']}", shape='record', color="blue", style='rounded') if m in df['id'].values: g.add_edge(pdt.Edge(pdt.Node(f"{df.loc[df['id']==m, 'id'].values[0]}"), nod, color='orange')) if f in df['id'].values: g.add_edge(pdt.Edge(pdt.Node(f"{df.loc[df['id']==f, 'id'].values[0]}"), nod, color='#066dba')) if notnull(df.loc[i, 'spouse_id']): # rel=df.loc[i, 'relation to'] # # tuple(map(int, re.findall(r'[0-9]+', rel))) # rel=rel.replace('(','').replace(')','').split(',') # who=pd.to_numeric(rel[0]).astype(int) who=to_numeric(df.loc[i, 'spouse_id'], downcast='integer', errors='coerce') # how=rel[1] # g.add_edge(pdt.Edge(pdt.Node(f"{df.loc[df['id']==who, 'Name'].values[0]} {df.loc[df['id']==who, 'Surname'].values[0]}"), nod, dir='none',color='#bf3fbf')) #label='m', if who in df['id'].values: # print('yes') g.add_edge(pdt.Edge(pdt.Node(f"{df.loc[df['id']==who, 'id'].values[0]}"), nod, dir='none',color='#bf3fbf')) #label='m', for i in range(df.shape[0]): cc='orange' if df.loc[i, 'gender']==1: cc='#066dba' sstr=f"{df.loc[i, 'name']}" if notnull(df.loc[i, 'surname']): sstr=f"{sstr} {df.loc[i, 'surname']}" if notnull(df.loc[i, 'date_birth']): if isinstance(df.loc[i, 'date_birth'], int) or isinstance(df.loc[i, 'date_birth'], str): sstr=f"{sstr}\nB: {df.loc[i, 'date_birth']}" else: sstr=f"{sstr}\nB: {df.loc[i, 'date_birth'].strftime('%d %b %Y') }" # %H:%M:%S d=df.loc[i, 'date_death'] # import numpy as np if notnull(d): # print("ddd" , isna(d), isnull(d), d, type(d) ) sstr=f"{sstr}\nD: {d}" if notnull(df.loc[i, 'place_birth']): sstr=f"{sstr}\nPoB: {df.loc[i, 'place_birth']} ({df.loc[i, 'country_birth']})" if not (isnull(df.loc[i, 'comments']) or df.loc[i, 'comments']==''): sstr=f"{sstr}\nComments: {df.loc[i, 'comments']}" nod=pdt.Node(f"{df.loc[i, 'id']}", label=sstr, shape='box', color=cc, style='rounded') # nod=pdt.Node(f"{df.loc[i, 'id']}", label=f"{df.loc[i, 'Name']} {df.loc[i, 'Surname']}\nB: {df.loc[i, 'DoB']}\nD: {df.loc[i, 'DoD']}\nPoB: {df.loc[i, 'Place of Birth']} ({df.loc[i, 'Country of Birth']})", shape='box', color=cc, style='rounded') g.add_node(nod) import io buf = io.BytesIO() g.write_png(buf) # plt.savefig(buf, format='png') buf.seek(0) import base64 buf_img64 = base64.b64encode(buf.getvalue()) # buf_im_str= u'data:img/jpeg;base64,'+buf_img64.decode('utf-8') buf_im_str=buf_img64.decode("utf-8") # img_g = Image_PIL.open(buf) # img=Img_IP(g.create_png()) # img=g.create_png() # return send_file(buf, mimetype='image/PNG') # print (buf_img64) # return render_template('image.html' , img= buf_img64.decode('ascii')) return render_template('image.html' , img= buf_im_str)
if __name__ == '__main__': # Generate library from file lib = gen_library("libs.edg") file_graph = pydotplus.Dot() # Find hierarchy blocks in the library for name, elt in lib.root.members.items(): # If hierarchy block, then generate a visualizer file. if elt.HasField('hierarchy_block'): for hport_name, _ in elt.hierarchy_block.ports.items(): hport = pydotplus.Node(name=hport_name, shape='circle') file_graph.add_node(hport) for link_name, _ in elt.hierarchy_block.links.items(): if not file_graph.get_subgraph('cluster_' + link_name): link_graph = pydotplus.Cluster(graph_name=link_name, graph_type='graph', label=link_name) source = pydotplus.Node(name=link_name + '_source', label='source', shape='circle') sink = pydotplus.Node(name=link_name + '_sinks', label='sinks', shape='circle') link_graph.add_node(source) link_graph.add_node(sink) file_graph.add_subgraph(link_graph) gen_visualizer(elt, name)