class render: def __init__(self,our_graph,wt_dist,colour_list,tup=[-1,-1]): self.G = Graph(format='png') self.edgeList = [] #i=0 for vertex in our_graph.vertList: self.G.node(str(vertex),label='INF' if wt_dist[vertex]==10000000 else str(wt_dist[vertex]),color='red' if colour_list[vertex] else 'black') for adjvertices in our_graph.vertList[vertex].connectedTo: if tup==[vertex,adjvertices] or tup==[adjvertices,vertex]: cl='green' else: cl='black' #print vertex.connectedTo[adjvertices] if our_graph.vertList[vertex].connectedTo[adjvertices][1] in self.edgeList: pass else: self.G.edge(str(vertex),str(adjvertices),str(our_graph.vertList[vertex].connectedTo[adjvertices][0]),color=cl) self.edgeList.append(our_graph.vertList[vertex].connectedTo[adjvertices][1]) #self.G.edge(str(vertex),str((vertex+1)%10),label='edge',color='green') self.G.view()
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 create_interactions_graph(clauses, f): dot = GGraph(comment='Interactions graph', engine='sfdp') seen_vars = set() edges_between_vars = defaultdict(int) for clause in clauses: for lit in clause: var = f(lit) if var not in seen_vars: seen_vars.add(var) dot.node(str(var), label=str(var)) for clause in clauses: l = len(clause) for i in xrange(l): for j in xrange(i+1, l): edges_between_vars[(str(f(clause[i])), str(f(clause[j])))] += 1 for interacting_vars, weight in edges_between_vars.iteritems(): dot.edge(interacting_vars[0], interacting_vars[1], weight=str(weight)) print edges_between_vars dot = _apply_styles(dot, styles) # print dot.source dot.render(os.path.join('images', 'interactions_graph.gv'), view=True)
def visualize_countries_together_in_item(data, start_time_str=None, end_time_str=None, newspaper_str='*'): countries_together_dict = _get_countries_together_in_items(data) # print 'countries_together_dict:', countries_together_dict dot = Graph(comment='Countries together in item graph', engine='sfdp') seen_countries = set() edges_between_countries = defaultdict(int) ## Building the graph for ID_and_feed, countries in countries_together_dict.iteritems(): countries_list = list(countries) for country in countries_list: if country != '' and country not in seen_countries: dot.node(country, label=country) seen_countries.add(country) for i in xrange(len(countries)): for j in xrange(i+1, len(countries)): fst = min(countries_list[i], countries_list[j]) snd = max(countries_list[i], countries_list[j]) edges_between_countries[(fst, snd)] += 1 for edge_endpoints, edge_weight in edges_between_countries.iteritems(): dot.edge(edge_endpoints[0], edge_endpoints[1], weight=str(edge_weight)) print 'seen_countries:', seen_countries print 'edges_between_countries:', edges_between_countries dot = _apply_styles(dot, styles) # print dot.source out_dirname = newspaper_str.replace('*', '').replace('!', '').replace('[', '').replace(']', '') out_filename = ('countries_together_in_item_%s_%s.gv' % (start_time_str, end_time_str)).replace(':', '-') dot.render(os.path.join('images', out_dirname, out_filename), view=False)
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 visualize(self): l = len(self.top_result) connections = dict() tags = dict() for i in range(l - 1): for j in range(1, l): if i != j: key = (i, j) message_list = self.get_message_list_between(self.top_result[i], self.top_result[j]) tag_cloud = self.subject.calculate_tag_cloud(message_list) tags[key] = self.get_top_tag_cloud(tag_cloud, 5) # DOT language dot = GraphV(comment = "Information Flow - Enron") for i in range(l): dot.node(str(i), self.top_result[i] + " - " + self.company.get_role(self.top_result[i])) for (edge, tag) in tags.iteritems(): node_1 = edge[0] node_2 = edge[1] note = ", ".join(tag) print note dot.edge(str(node_1), str(node_2), label=note) dot.render('test-output/round-table.gv', view=False)
def graph_draw(nodes, edges, name): g = Graph(name, format="png") for node in nodes: g.node(str(node)) for edge in edges: x = edge.split(' ')[0] y = edge.split(' ')[1] g.edge(x, y) g.view()
def __str__(self): A = Graph() for vertice in self.meuGrafo.nodes_iter(data=False): A.node(vertice.encode("utf8")) for aresta_A, aresta_B, dados_aresta in self.meuGrafo.edges_iter(data=True): peso_aresta = dict((chave, str(valor)) for chave, valor in dados_aresta.items()) peso_aresta['label'] = peso_aresta['weight'] del peso_aresta['weight'] A.edge(aresta_A.encode("utf8"), aresta_B.encode("utf8"), **peso_aresta) return A.source
def renderiza_grafo(self, lugar_para_gerar, nome_grafo): A = Graph(comment=nome_grafo, filename=(lugar_para_gerar + '/Grafo.gv'), engine='dot') for vertice in self.meuGrafo.nodes_iter(data=False): A.node(vertice.encode("utf8")) for aresta_A, aresta_B, dados_aresta in self.meuGrafo.edges_iter(data=True): peso_aresta = dict((chave, str(valor)) for chave, valor in dados_aresta.items()) peso_aresta['label'] = peso_aresta['weight'] del peso_aresta['weight'] A.edge(aresta_A, aresta_B, **peso_aresta) A.view()
def plot(graph, engine='dot', filename='output/test'): """Possible engines: dot, neato, fdp, sfdp, twopi, circo""" g = Graph(format='png', engine=engine) for v in graph: g.node(str(index(v))) for v, w in graph.edges: g.edge(str(index(v)), str(index(w))) g.render(filename)
def getDot(self, color): dot = Graph(graph_attr = {'size':'3.5'}) for node in self.G: if not node in color: dot.node(node) else: dot.node(node, style = 'filled', color = color[node]) for n1 in self.G: for n2 in self.G[n1]: if n1 < n2: dot.edge(n1, n2) return dot
def generateGraph(): G = Graph( engine = 'dot', filename = 'Btrfs-Graph.dot', name = 'BRTFS-Browser', comment = 'https://github.com/Zo0MER/BRTFS-Browser.git', graph_attr = {'rankdir': 'RL', 'charset':'utf-8', 'bgcolor':'#eeeeee', 'labelloc':'t', 'splines':'compound', 'nodesep':'0.7', 'ranksep':'5' }, node_attr = {'fontsize': '18.0', 'shape':'box' } ) #node with title and hyperlink on github G.node('meta', label = 'Btrfs-debug-tree \nhttps://github.com/Zo0MER/BRTFS-Browser.git', href = 'https://github.com/Zo0MER/BRTFS-Browser.git', fontcolor = '#4d2600', fontsize = '30.0' ) first = inode[0] inode.remove(inode[0]) if (inode): #link first item ROOT_TREE_DIR INODE_ITEM, INODE_REF with all INODE_ITEM EXTEND_DATA for pair in inode: G.edge(''.join([str(x) for x in first]), ''.join([str(x) for x in pair])) else: G.node(first) #save *.dot and others pathout = enterPath.get() filenameout = enterFilename.get() if (filenameout): filenameout = filenameout + '.gv.dot' else: filenameout = "btrfs-graph" G.filename = filenameout + '.gv.dot' G.directory = pathout G.save() for t in types: G.format = t G.render()
def plot(graph, engine='dot', filename='output/test', vertex_names={}): """ Possible engines: dot, neato, fdp, sfdp, twopi, circo Vertex_names is an optional dict from vertices to strings. """ g = Graph(format='png', engine=engine) def vertex_to_string(v): return (vertex_names[v] if v in vertex_names else '') + ' ({})'.format(str(index(v))) for v in graph: g.node(vertex_to_string(v)) for v, w in graph.edges: g.edge(vertex_to_string(v), vertex_to_string(w)) g.render(filename)
def visualize_topics(quora_data): dot = Graph(comment='Topics graph', engine='sfdp') seen_topics = set() for document in quora_data: question = _get_question(document) topics = document[question]['topics'] # Iterating over topics and adding nodes for topics if necessary for topic in topics: if topic not in seen_topics: dot.node(topic, label=topic) seen_topics.add(topic) # Iterating over topics and adding edges between topics belonging to the same question for i in xrange(len(topics)): for j in xrange(i+1, len(topics)): dot.edge(topics[i], topics[j]) # topic1, topic2 in product(topics, topics): # dot.edge(topic1, topic2) dot = _apply_styles(dot, styles) # print dot.source dot.render(os.path.join('images', 'topics.gv'), view=True)
def create_conflicts_graph(clauses): dot = GGraph(comment='Conflicts graph', engine='sfdp') for i in xrange(len(clauses)): dot.node(str(i), label=str(i)) for i in xrange(len(clauses)): for j in xrange(i+1, len(clauses)): clause_i = clauses[i] clause_j = clauses[j] edge_labels = [] for lit in clause_i: if -lit in clause_j: var = abs(lit) edge_labels.append(str(var)) if len(edge_labels) > 0: dot.edge(str(i), str(j), label=','.join(edge_labels)) dot = _apply_styles(dot, styles) dot.render(os.path.join('images', 'conflicts_graph.gv'), view=True)
def render(self, filename): """ Renders the graph to a file. Args: filename (str): Filename of the map file. """ dot = Graph(comment='ISTravel graph', engine='fdp') for city in self.cities: dot.node(str(city)) ploted = [] for node in self.connections: for edge in self.connections[node]: if edge not in ploted: ploted.append(edge) dot.edge( str(edge.nodes[0]), str(edge.nodes[1]), label=edge.transport[:2] ) dot.render(filename[:filename.rfind('.')]+".gv")
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()
def main(): source = sys.argv[1] with open(source, 'r') as infile: regions = json.load(infile) g = Graph('chroma', filename='chroma.graphview', format='png') for region in regions: name = region['name'] style = {"style": "filled"} if "owner" in region: owner = region["owner"] if owner == 0: style["color"] = "orange" else: style["color"] = "blue" style["fontcolor"] = "white" g.node(name, **style) for conn in region['connections']: g.edge(name, conn) g.render()
def save_nodes(self, filename="graph", nodes = None): print "Saving graph..." from graphviz import Graph dot = Graph(comment='Dungeon Example') if nodes == None: nodes = self.linear_nodes(self.nodes) #else: #max_appeared = appeared.values() #if max_appeared == []: start = 0 #else: start = max(max_appeared) + 1 #print start #for node in nodes: # if node.id not in appeared: # appeared[node.id] = start for node in nodes: name = node.name if hasattr(node, "replace_on_room_clear"): replace = node.replace_on_room_clear[0] name += "\n" try: name += replace.name except AttributeError: name += replace amount = 255 #60+(appeared[node.id]*64) fill = "#%02x%02xFF"%(amount, amount) #print fill shape = "oval" if node is self.entrance: shape = "box" dot.node(str(node.id), name, style="filled", fillcolor=fill, shape=shape) done_edges = [] for node in nodes: for edge in node.connections: if sorted([node.id, edge.id]) in done_edges: continue dot.edge(str(node.id), str(edge.id)) done_edges.append(sorted([node.id, edge.id])) dot.render(filename) print "Graph saved"
def gen_graph_from_nodes(nodes, type_fail=None): graph = Graph(format='png', strict=True) graph.node_attr['fontname'] = 'Courier New' graph.edge_attr['fontname'] = 'Courier New' for node in nodes: graph.node(_type_str(node.type), '{type: %s|ast_node: %s|parent\'s type: %s}' % (_type_str(node.type), node.ast_node.as_string().replace('<', '\\<').replace('>', '\\>') if node.ast_node else 'None', _type_str(node.parent.type) if node.parent else 'NA'), shape='record', style='rounded') for neighb, ctx_node in node.adj_list: graph.edge(_type_str(node.type), _type_str(neighb.type), label=(f' {ctx_node.as_string()}' if ctx_node else '')) if type_fail: graph.node('tf', '{TypeFail|src_node: %s}' % (type_fail.src_node.as_string().replace('<', '\\<').replace('>', '\\>') if type_fail.src_node else 'None'), shape='record') graph.edge('tf', _type_str(type_fail.tnode1.type), style='dashed') graph.edge('tf', _type_str(type_fail.tnode2.type), style='dashed') graph.view('tnode_graph')
def create_graph(topology_array, link_a): dot = Graph(node_attr={'shape': 'record'}) for topo in topology_array: hostname = topo.keys()[0] if topo[hostname]["root"] == True: dot.node(hostname, build_graph_label(topo), URL="ssh://" + str(topo[hostname]["ip_address"]), style="filled", fillcolor="lightgreen") elif topo[hostname]["stp_active"] != "enabled": dot.node(hostname, build_graph_label(topo), URL="ssh://" + str(topo[hostname]["ip_address"]), xlabel="STP Disabled", style="filled", fillcolor="darkgray") else: dot.node(hostname, build_graph_label(topo), URL="ssh://" + str(topo[hostname]["ip_address"])) # dot.source are the nodes, and ends with a }, so we limit that # using create links we're able to put together the links and attributes # in the graphviz format, which are unsupported by the Graph library graphtext = dot.source[:-1] + create_links(link_a) + "}" return graphtext
class VisitorGraph(Visitor): """this class implement a tree visitor for our form""" def __init__(self): self.handler_dict = {Form.OperatorForm:(self.func_op_fo,{Form.D: (self.diff, {})\ , Form.Wedge: (self.wed, {}), Form.Add: (self.add,{}), \ Form.Hodge: (self.hod, {}),Form.Pullback: (self.pull, {}) }),\ Form.TerminalForm:(self.func_term_fo,{})} self.dot = Graph(comment='Tree of our form')#Digraph(comment='Tree of our form') #to store the dot for vizgraph self.edges = [] #to store the edge for the graph self.post = [] #to store the post order traversal self.pre = [] # to store the pre order traversal self.comp = 0 #to differentiate the edge #D form def diff(self, form, children=None): """function when a diff operation is made""" if form.scalar == 1: return( 'd') elif form.scalar == -1: return( "-d" ) else: return( "{}d ".format(form.scalar) ) #Wedge def wed(self, form, children=None): """function when a wedge operation is made""" if form.scalar == 1: return( '^') elif form.scalar == -1: return( "-^" ) else: return( "{}^ ".format(form.scalar) ) #Add def add(self, form, children=None): """function when a add operation is made""" if form.scalar == 1: return( '+') elif form.scalar == -1: return( "-+" ) else: return( "{}+ ".format(form.scalar) ) #Hodge def hod(self, form, children=None): """function when a hodge star operation is made""" if form.scalar == 1: return( '*') elif form.scalar == -1: return( "-*" ) else: return( "{}* ".format(form.scalar) ) #Pullback def pull(self, form, children=None): """function when a hodge star operation is made""" if form.scalar == 1: return("phi") else: return( "{}phi ".format(form.scalar) ) #TerminalForm def func_term_fo(self, form): """function that print a terminal Form""" if form.scalar == 1: return( form.name) elif form.scalar == -1: return( "-{} ".format(form.name) ) else: return( "{}{} ".format(form.scalar, form.name) ) def _visit_preorder(self, form): """the intern preorder method for visiting the tree""" if not isinstance(form,Form.TerminalForm): children=form.forms inter = self.find_method(form)(form) self.pre.append(inter) for fo in children: self._visit_preorder(fo) #in post order the find_method will be there else: inter = self.find_method(form)(form) self.pre.append(inter) def visit_preorder(self, form): """the preorder method for visiting the tree""" self.pre=[] self._visit_preorder(form) return self.pre def _visit_postorder(self, form): """the intern postorder method for visiting the tree""" if not isinstance(form,Form.TerminalForm): children=form.forms for fo in children: self._visit_postorder(fo) inter = self.find_method(form)(form) self.post.append(inter) else: inter = self.find_method(form)(form) self.post.append(inter) def visit_postorder(self, form): """the postorder method for visiting the tree""" self.post=[] self._visit_postorder(form) return self.post def _create_graph(self, form, parent_name=""): """the method for creating a graph of the tree, the edges are store inside the edges attribute""" if not isinstance(form,Form.TerminalForm): children = form.forms node = (self.find_method(form)(form)) nbr1 = str(self.comp) self.comp+=1 name = nbr1 self.dot.node(name, node) if parent_name is not "": inter=parent_name+name self.edges.append(inter) self.dot.edge(parent_name, name) parent_name=name for fo in children: self._create_graph(fo,parent_name) else: node = (self.find_method(form)(form)) nbr1 = str(self.comp) self.comp+=1 name = nbr1 #~ print(name) self.dot.node(name,node) if parent_name is not "": inter = parent_name+name self.edges.append(inter) self.dot.edge(parent_name, name) def draw_graph(self, form, name='sample'): """the method for drawing a graph of the tree, name is the file name under which we want to save it""" self.dot = Graph(comment='Tree of our form')#Digraph(comment='Tree of our form') self.edges = [] self.comp = 0 self._create_graph(form) namefile='drawing/'+name+'.gv' self.dot.render(namefile, view=True)
#!/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')
class VisitorGraph(Visitor): """this class implement a tree visitor for our form""" def __init__(self): self.handler_dict = {Form.OperatorForm:(self.func_op_fo,{Form.D: (self.diff, {})\ , Form.Wedge: (self.wed, {}), Form.Add: (self.add,{}), \ Form.Hodge: (self.hod, {}),Form.Pullback: (self.pull, {}) }),\ Form.TerminalForm:(self.func_term_fo,{})} self.dot = Graph( comment='Tree of our form' ) #Digraph(comment='Tree of our form') #to store the dot for vizgraph self.edges = [] #to store the edge for the graph self.post = [] #to store the post order traversal self.pre = [] # to store the pre order traversal self.comp = 0 #to differentiate the edge #D form def diff(self, form, children=None): """function when a diff operation is made""" if form.scalar == 1: return ('d') elif form.scalar == -1: return ("-d") else: return ("{}d ".format(form.scalar)) #Wedge def wed(self, form, children=None): """function when a wedge operation is made""" if form.scalar == 1: return ('^') elif form.scalar == -1: return ("-^") else: return ("{}^ ".format(form.scalar)) #Add def add(self, form, children=None): """function when a add operation is made""" if form.scalar == 1: return ('+') elif form.scalar == -1: return ("-+") else: return ("{}+ ".format(form.scalar)) #Hodge def hod(self, form, children=None): """function when a hodge star operation is made""" if form.scalar == 1: return ('*') elif form.scalar == -1: return ("-*") else: return ("{}* ".format(form.scalar)) #Pullback def pull(self, form, children=None): """function when a hodge star operation is made""" if form.scalar == 1: return ("phi") else: return ("{}phi ".format(form.scalar)) #TerminalForm def func_term_fo(self, form): """function that print a terminal Form""" if form.scalar == 1: return (form.name) elif form.scalar == -1: return ("-{} ".format(form.name)) else: return ("{}{} ".format(form.scalar, form.name)) def _visit_preorder(self, form): """the intern preorder method for visiting the tree""" if not isinstance(form, Form.TerminalForm): children = form.forms inter = self.find_method(form)(form) self.pre.append(inter) for fo in children: self._visit_preorder(fo) #in post order the find_method will be there else: inter = self.find_method(form)(form) self.pre.append(inter) def visit_preorder(self, form): """the preorder method for visiting the tree""" self.pre = [] self._visit_preorder(form) return self.pre def _visit_postorder(self, form): """the intern postorder method for visiting the tree""" if not isinstance(form, Form.TerminalForm): children = form.forms for fo in children: self._visit_postorder(fo) inter = self.find_method(form)(form) self.post.append(inter) else: inter = self.find_method(form)(form) self.post.append(inter) def visit_postorder(self, form): """the postorder method for visiting the tree""" self.post = [] self._visit_postorder(form) return self.post def _create_graph(self, form, parent_name=""): """the method for creating a graph of the tree, the edges are store inside the edges attribute""" if not isinstance(form, Form.TerminalForm): children = form.forms node = (self.find_method(form)(form)) nbr1 = str(self.comp) self.comp += 1 name = nbr1 self.dot.node(name, node) if parent_name is not "": inter = parent_name + name self.edges.append(inter) self.dot.edge(parent_name, name) parent_name = name for fo in children: self._create_graph(fo, parent_name) else: node = (self.find_method(form)(form)) nbr1 = str(self.comp) self.comp += 1 name = nbr1 #~ print(name) self.dot.node(name, node) if parent_name is not "": inter = parent_name + name self.edges.append(inter) self.dot.edge(parent_name, name) def draw_graph(self, form, name='sample'): """the method for drawing a graph of the tree, name is the file name under which we want to save it""" self.dot = Graph( comment='Tree of our form') #Digraph(comment='Tree of our form') self.edges = [] self.comp = 0 self._create_graph(form) namefile = 'drawing/' + name + '.gv' self.dot.render(namefile, view=True)
x, y = cell_positions[0, i], cell_positions[1, i] position = str(x * scale) + ',' + str(y * scale * -1) if options.cluster: note = '\nC' + str(db.labels_[i]) if labels[i] == 0: fill = 'white' else: fill = str(labels[i]) else: note = '' fill = cell_type(i, 'hex') g.node(cell_name(i), label=cell_name(i) + note, pos=position, color=cell_type(i, 'hex'), fillcolor=fill) for ni in cell_neighbours[i]: if cell_type(i) == cell_type(ni): lcolor = cell_type(i, 'hex') else: lcolor = 'black' label = '' if printdist: label = str(round(distance, 2)) g.edge(cell_name(i), cell_name(ni), color=lcolor, label=label) i += 1
from graphviz import Graph # simple graph with manually designed edges edges = [(7, 2), (3, 4), (4, 5), (5, 6), (5, 7), (8, 3), (6, 3), (2, 4), (1, 8), (6, 1), (7, 11), (7, 4), (2, 5), (10, 5), (10, 4), (1, 5), (4, 11), (10, 11), (6, 2), (5, 7), (9, 8)] # save the graph dot = Graph(comment='Graph 3 : Clique') for edge in edges: dot.edge(str(edge[0]), str(edge[1]), color='cornflowerblue', penwidth='1.1') graph_name = 'graphs/clique_3' dot.render(graph_name) clique = [3, 8] for node in clique: dot.node(str(node), color='crimson', penwidth='3.5') # visualize the graph graph_name = 'images/clique_3' dot.render(graph_name)
class threatDigger: def __init__(self, args): self.args = args self.target = self.args.target self.work_file = '' self.displaylist = [] self.entityDic = {} self.graph = Graph('G', filename='threatDigger.gv', engine='sfdp') #sfdp, circo #f.node_attr.update(color='lightblue2', style='filled') self.graph.attr(rankdir='LR', size='8,5', rank='source', splines='spline', overlap='false') #self.graph.graph_attr.update(rank='same') self.varInit() def varInit(self): self.filename = '-' self.md5 = '' self.buildtime = '-' self.internalName = '-' self.companyName = '-' self.richHeaderXorkey = '-' self.richHeaderCleardata = '-' self.richHeaderDansAnchor = '-' self.richHeaderClearDataMD5 = '-' self.imphash = '-' self.exportName = '' def display(self): # Display result with stdout print( tabulate(self.displaylist, headers=[ 'Filename', 'MD5', 'Buildtime', "Export Function", 'InternalName', 'CompanyName', 'RHXorkey', 'DansAnchor', 'RHCleardataMD5', 'Imphash' ])) def displayAppend(self): buildtime = self.buildtime.split(" ")[0].split( ".")[0] + "." + self.buildtime.split(" ")[0].split(".")[1] tempDic = { 'MD5': self.md5, 'Buildtime': buildtime, 'Export Function': self.exportName, 'Internal Name': self.internalName, 'Company Name': self.companyName, 'Richheader Xorkey': self.richHeaderXorkey, 'RH Cleardata MD5': self.richHeaderClearDataMD5, 'Imphash': self.imphash } self.entityDic[self.filename] = tempDic #print (self.entityDic) if len(self.filename) > 40: self.displaylist.append([ self.filename[:40] + "...", self.md5, self.buildtime, self.exportName, self.internalName, self.companyName, self.richHeaderXorkey, self.richHeaderDansAnchor, self.richHeaderClearDataMD5, self.imphash ]) else: self.displaylist.append([ self.filename, self.md5, self.buildtime, self.exportName, self.internalName, self.companyName, self.richHeaderXorkey, self.richHeaderDansAnchor, self.richHeaderClearDataMD5, self.imphash ]) def exportGraphviz(self): self.graph.attr('node', shape='box') #print ("graphviz: ", self.entityDic) for filename, y in self.entityDic.items(): for entityName, value in y.items(): if (value == "-"): continue #print (filename, entityName, value) self.graph.node(value, color='red', style='filled', fontcolor='white') self.graph.attr('node', shape='circle') for filename, y in self.entityDic.items(): for entityName, value in y.items(): self.graph.edge(filename, value, label=entityName) self.graph.view() def csvAppend(self): self.writer.writerow({ 'Filename': self.filename, 'MD5': self.md5, 'Buildtime': self.buildtime, 'Export Function': self.exportName, 'Internal Name': self.internalName, 'Company Name': self.companyName, 'Richheader Xorkey': self.richHeaderXorkey, 'Richheader DansAnchor': self.richHeaderDansAnchor, 'RH Cleardata MD5': self.richHeaderClearDataMD5, 'Imphash': self.imphash }) return def getBinaryContent(self): fh = open(self.work_file, "rb") content = bytearray() for i in fh: content += i fh.close() self.md5 = hashlib.md5(content).hexdigest() return content def xorDans(self, key): l = len(key) data = "DanS" bytedata = str.encode(data) return bytearray( ((bytedata[i] ^ key[i % l]) for i in range(0, len(bytedata)))) def xorDec(self, rhData, xorKey): # Decode every four bytes with XOR key clearData = bytes() for i in range(0, len(rhData)): clearData += bytes([rhData[i] ^ xorKey[i % len(xorKey)]]) self.richHeaderClearDataMD5 = hashlib.md5(clearData).hexdigest() return clearData def parseRichheader(self): #print (self.work_file) content = self.getBinaryContent() try: xorKey = re.search(b"\x52\x69\x63\x68....\x00", content).group(0)[4:8] dansAnchor = self.xorDans(xorKey) richStart = re.search(re.escape(dansAnchor), content).start(0) richEnd = re.search(b'\x52\x69\x63\x68' + re.escape(xorKey), content).start(0) if richStart < richEnd: rhData = content[richStart:richEnd] else: raise Exception("WTF") raw_clearData = self.xorDec(rhData, xorKey) clearData = binascii.hexlify( binascii.unhexlify( binascii.hexlify(raw_clearData).decode("utf-8"))).decode( "utf-8") xorKey = binascii.hexlify( bytearray(xorKey)).decode("utf-8").upper() dansAnchor = binascii.hexlify( bytearray(dansAnchor)).decode("utf-8").upper() return "0x" + xorKey, "0x" + dansAnchor, "0x" + clearData except: return "-", "-", "-" def processing(self): result, type = self.isPe() if (result): #if target file is PE try: self.richHeaderXorkey, self.richHeaderDansAnchor, self.richHeaderCleardata = self.parseRichheader( ) #get Richheader Parsing Result pe = pefile.PE(self.work_file) try: self.internalName = pe.FileInfo[0][0].StringTable[ 0].entries[b'InternalName'].decode("UTF-8") except: pass try: self.companyName = pe.FileInfo[0][0].StringTable[ 0].entries[b'CompanyName'].decode("UTF-8") except: pass try: self.buildtime = time.strftime( "%Y.%m.%d %H:%M:%S", time.localtime(pe.FILE_HEADER.TimeDateStamp)) except: pass try: self.imphash = pe.get_imphash() except: pass try: for exp in pe.DIRECTORY_ENTRY_EXPORT.symbols: exportName = exp.name.decode("utf-8") if (len(exportName) > 1): self.exportName += exportName + " " else: continue except: self.exportName = "-" pass self.displayAppend() if self.args.csv: self.csvAppend() except Exception as e: print(self.work_file) print("Error has been occured: ", e) return else: return def checkFileType(self): if (self.isDir()): for root, directories, files in os.walk(self.target): for self.filename in files: self.work_file = os.path.join(root, self.filename) self.processing() self.varInit() else: self.work_file = self.target self.filename = self.target[self.target.rfind("/"):] self.processing() self.varInit() def entry(self): if self.args.csv: self.csvFilename = "threatDigger_result.csv" with open(self.csvFilename, "w") as self.csvfile: fieldnames = [ 'Filename', 'MD5', 'Buildtime', 'Export Function', 'Internal Name', 'Company Name', 'Richheader Xorkey', 'Richheader DansAnchor', 'RH Cleardata MD5', 'Imphash' ] self.writer = csv.DictWriter(self.csvfile, fieldnames=fieldnames) self.writer.writeheader() self.checkFileType() else: self.checkFileType() def isPe(self): with magic.Magic() as m: try: filetype = m.id_filename(self.work_file) if (filetype.find("exe") > -1): if ((filetype.find("Python") > -1) or (filetype.find("Bourne-Again") > -1) or (filetype.find("PDP-11") > -1)): return 0, filetype else: return 1, filetype else: return 0, filetype except Exception as e: return 0, None def isDir(self): if os.path.isdir(self.target): return 1 else: return 0
def solve(cls, expression, graphviz=False, graph_filename='tableau'): if graphviz is True: graph = Graph(format="png") graph.attr("node", color='white') else: graph = None def delta(nodes, exprs, values): if len(nodes) == 0: nodes.append(([], copy.copy(values))) if len(exprs) == 1: for node in nodes: node[0].append(exprs[0]) return nodes elif len(exprs) >= 2: ret_nodes = [] for i in range(len(exprs) - 1): tmp_nodes = [(copy.copy(n[0]), copy.copy(n[1])) for n in nodes] for tmp_node in tmp_nodes: tmp_node[0].append(exprs[i]) ret_nodes += tmp_nodes for node in nodes: node[0].append(exprs[len(exprs) - 1]) ret_nodes += nodes return ret_nodes start_expr = copy.deepcopy(expression) nodes = [([start_expr], {})] no_counter = 0 while len(nodes) > 0: exprs, values = nodes.pop(0) new_nodes = [] is_paradox = False for expr in exprs: if type(expr) == scrt.logic.LogicalNot: not_expr = expr.target if type(not_expr) == scrt.logic.LogicalAtom: if not_expr.name in values and values[ not_expr.name] is True: is_paradox = True break elif not_expr.name not in values: values[not_expr.name] = False elif type(expr) == scrt.logic.LogicalAtom: if expr.name in values and values[expr.name] is False: is_paradox = True break elif expr.name not in values: values[expr.name] = True # print(", ".join([str(expr) for expr in exprs]), values) for expr in exprs: if type(expr) == scrt.logic.LogicalNot: not_expr = expr.target if type(not_expr) == scrt.logic.LogicalNot: new_nodes = delta(new_nodes, [not_expr.target], values) elif type(not_expr) == scrt.logic.LogicalAnd: new_nodes = delta(new_nodes, [~not_expr.left, ~not_expr.right], values) elif type(not_expr) == scrt.logic.LogicalOr: new_nodes = delta(new_nodes, [~not_expr.left], values) new_nodes = delta(new_nodes, [~not_expr.right], values) elif type(not_expr) == scrt.logic.LogicalImplies: new_nodes = delta(new_nodes, [not_expr.left], values) new_nodes = delta(new_nodes, [~not_expr.right], values) elif type(not_expr) != scrt.logic.LogicalAtom: raise ValueError() elif type(expr) == scrt.logic.LogicalAnd: new_nodes = delta(new_nodes, [expr.left], values) new_nodes = delta(new_nodes, [expr.right], values) elif type(expr) == scrt.logic.LogicalOr: new_nodes = delta(new_nodes, [expr.left, expr.right], values) elif type(expr) == scrt.logic.LogicalImplies: new_nodes = delta(new_nodes, [~expr.left, expr.right], values) elif type(expr) != scrt.logic.LogicalAtom: raise ValueError() if is_paradox is False: if len(new_nodes) > 0: for new_node in new_nodes: if graphviz is True: graph.edge( "\n".join([str(expr) for expr in exprs]), "\n".join([str(expr) for expr in new_node[0]])) # print("ADD NODE: " + (", ".join([str(expr) for expr in new_node[0]])), str(new_node[1])) nodes += new_nodes else: if graphviz is True: graph.edge("\n".join([str(expr) for expr in exprs]), "yes") graph.render(graph_filename) return True else: if graphviz is True: no_counter += 1 graph.node("no_" + str(no_counter), "no") graph.edge("\n".join([str(expr) for expr in exprs]), "no_" + str(no_counter)) # print() if graphviz is True: graph.render(graph_filename) return False
def draw(self, mode, user_info, graphStyle=[]): output = user_info.fileName + "-20000-SM-M-01_picture" data = user_info.depStruct edgeList = [] nodeDict = {} structDict = {} colorDict = {} # deal with data temp = data.splitlines() subCount = 0 for item in temp: if (";" in item or ";" in item) and "#" not in item: s_item = item.strip(" ") temp_list = re.split("[;;]", s_item) temp_list = list( filter(lambda x: x != '' and x != ' ', temp_list)) for item_t in temp_list: edge = item_t.replace(";", "").replace(";", "") t = re.split("[,,]", edge) t = sorted(set(t), key=t.index) for i in range(len(t)): t[i] = t[i].strip(" ") structDict["cluster{:0>5d}".format(subCount)] = t colorDict["cluster{:0>5d}_style".format( subCount)] = graphStyle[subCount] if subCount < len( graphStyle) else {} subCount += 1 elif "#" in item and ";" not in item and ";" not in item: temp_list1 = re.split("[#]", item) temp_list1 = list( filter(lambda x: x != '' and x != ' ', temp_list1)) for item_t in temp_list1: edge = item.replace("#", "") edgeList.append(edge) else: return "" edgeList = list(filter(lambda x: x != '', edgeList)) #print(structDict) #print(nodeDict) # draw graph subG = [] linkPoint = [] graph = Graph(comment="graph", format="png", graph_attr={'rank': 'max'}) graph.attr(_attributes={ 'compound': 'true', 'rankdir': 'TB', 'center': 'true' }) for sub, content in structDict.items(): subg = Graph(name=sub, graph_attr={ 'center': 'true', 'rankdir': 'LR', 'rank': 'max', 'ordering': 'out' }, node_attr={ 'fontname': 'KaiTi', 'shape': 'box' }) subg.attr(_attributes={'compound': 'true', 'color': 'black'}) nodes = [] for i in range(len(content) - 1, -1, -1): subg.node( content[i], self.formatContent(content[i], colorDict[sub + "_style"]["lineLen"])) nodes.append(content[i]) if len(content) % 2 == 0 and i == len(content) / 2: subg.node(sub + "e", "", { 'height': '0', 'width': '0', 'color': 'white' }) linkPoint.append(sub + "e") nodes.append(sub + "e") if len(content) % 2 == 1 and i == (len(content) - 1) / 2: linkPoint.append(content[i]) #for i in range(1, len(nodes)): #subg.edge(nodes[i-1], nodes[i]) subg = self.apply_styles(subg, colorDict[sub + "_style"]) graph.subgraph(subg) subG.append(sub) for i in range(1, len(subG)): graph.edge(linkPoint[i - 1], linkPoint[i], _attributes={ 'ltail': subG[i - 1], 'lhead': subG[i] }) # single arrow for edge in edgeList: nodes = edge.split("-") node1 = nodes[0].strip(" ") node2 = nodes[1].strip(" ") if node1 in nodeDict: nodeDict[node1].append(node2) else: nodeDict[node1] = [node2] for node, children in nodeDict.items(): for child in children: graph.edge(node, child) #print(graph.source) if mode == "preview": self.preview(graph) else: filename = output if output != "" else self.genName() self.save(graph, filename) user_info.picPath = self.saveDir + filename + ".png" return user_info
phile.write(json.dumps(brit_dict)) ## upload the data back to the drive import json import os import graphviz from graphviz import Graph, Digraph with open("biochem_network_graph.json","r") as phile: brit_dict = json.loads(phile.read()) dot = Graph(comment="Brittany vis") for node in brit_dict: dot.node(node,node) for other_node in brit_dict[node]["edges"]: for edge in brit_dict[node]["edges"][other_node]: dot.edge(node,other_node,edge,concentrate="true") ## get the graphviz in path os.environ["PATH"]+=os.pathsep + "/home/user/miniconda3/pkgs/graphviz-2.40.1-h21bd128_2/bin" dot.render("test.gv",format="svg") ##make a test brit_dict = dict(cat1 = dict(proteins=[2,5]),cat2 = dict(proteins=[4,2,8,5]),cat3 =dict(proteins=[8,4,1])) brit_dict_copy = brit_dict.copy() ##set overlap counter for i,current_node in enumerate(brit_dict_copy):
from graphviz import Graph #these are undirected import sqlite3 #open up the db, pull everything conn = sqlite3.connect('../db/prot.db') c = conn.cursor() c.execute('SELECT * from protein') proids = {x[0]:x[1] for x in c.fetchall()} c.execute('SELECT * from tags') tagids = {x[0]:x[1] for x in c.fetchall()} c.execute('SELECT * from ptag') matches = c.fetchall() graph = Graph('All protein tags', engine='neato') for key in proids: graph.node(proids[key]) for key in tagids: graph.node(tagids[key]) for x,y in matches: graph.edge(proids[x],tagids[y],len="10.0") graph.render('tag.gv') conn.close()
import matplotlib.pyplot as plt import networkx as nx from graphviz import Graph import sys f = CNF.from_file(sys.argv[1]) a_pos, a_neg = adj(f) a_pos = a_pos.todense() a_neg = a_neg.todense() n, m = a_pos.shape g = Graph('G', filename=sys.argv[2], format='pdf', engine='neato') for x in range(1, n + 1): g.node(f'x{x}', label='x', color='blue', fillcolor='blue', shape='point') for c in range(1, m + 1): g.node(f'c{c}', label='y', color='red', fillcolor='red', shape='point') pw = sys.argv[3] for x in range(n): for c in range(m): var = f'x{x + 1}' cl = f'c{c + 1}' if a_pos[x, c] == 1: # g.edge(var, cl, color='#ff0000', penwidth='0.001') g.edge(var, cl, color='#ff0000', penwidth=pw) if a_neg[x, c] == 1: # g.edge(var, cl, color='#0000ff', penwidth='0.001')
# coding=gbk from graphviz import Graph A = Graph("G", engine="sfdp", format="jpg") A.node('1', 'ÓåÈÙ', fontname='FangSong') A.node('2', 'ÈÙ¡', fontname='FangSong') A.node('3', 'ÈÙ²ý', fontname='FangSong') A.node('4', 'ÈÙ²ý¶«', fontname='FangSong') A.node('5', 'ÓÊͤ', fontname='FangSong') A.node('6', 'ÓÀ´¨', fontname='FangSong') A.node('7', '´ó°²', color='blue', fontname='FangSong') A.node('8', 'Çà¸Ü', fontname='FangSong') A.node('9', '¶¡¼Ò', fontname='FangSong') A.node('10', '×ßÂí', fontname='FangSong') A.node('11', 'Êé·¿°Ó', fontname='FangSong') A.node('12', 'Ë«½', fontname='FangSong') A.node('13', 'äüÄÏ', fontname='FangSong') A.node('14', 'Ìï¼Ò', fontname='FangSong') A.node('15', 'ÉÙÔÆ', fontname='FangSong') A.node('16', 'ÍÁº', color='green', fontname='FangSong') A.node('17', 'ÆÑÂÀ', fontname='FangSong') A.node('18', '´ó·', color='green', fontname='FangSong') A.node('19', 'èµÉ½', fontname='FangSong') A.node('20', '°×ɳ', color='green', fontname='FangSong') A.node('21', 'µó¼Ò', fontname='FangSong') A.node('22', '½½ò', color='blue', fontname='FangSong') A.node('23', 'ÐËɽ', fontname='FangSong') A.node('24', 'ÌúÌÁ', color='green', fontname='FangSong') A.node('25', 'ÔÆÃÅ', color='blue', fontname='FangSong') A.node('26', 'ºÏÑô', fontname='FangSong') A.node('27', 'ºÏ´¨', fontname='FangSong')
def render_graph(nodes): import sys, os, json from pprint import pprint edges = [] for n in nodes: for sg in n["stargazers"]["nodes"]: for n2 in sg["starredRepositories"]["nodes"]: if n["url"] != n2["url"]: edges.append((n["url"], sg["login"], n2["url"])) print(len(edges)) from collections import Counter ct = Counter([(x[0], x[-1]) for x in edges]) pprint(ct.most_common(10)) from graphviz import Digraph, Graph from graphviz import escape, nohtml #### control graph layout # g = Graph('G',strict=True,engine="neato",graph_attr=dict(nodesep="1.")) # g.attr(overlap="scalexy") # # g.attr(overlap="compress") # # g.attr(overlap="false") # g.attr(overlap="ipsep") # g.attr(sep="0.1") # g.attr(nodesep='1.') # # g.attr(sep="+1") # # g.attr(sep="+1") g = Graph('G', strict=True, engine="dot") # g.attr(rankdir='TB') g.attr(rankdir='LR') def _label(x): # x = r'\l'.join(textwrap.wrap(repr(x),width=50)) # x = x.replace(':','_') # x = x.replace(':','_') x = x.split('://', 1)[-1] return x def is_included(n1, sg, n2): return (ct[(n1, n2)] >= 3) _inced = [tuple(x[0]) for x in ct.most_common(10)] def is_included(n1, sg, n2): return tuple((n1, n2)) in _inced if 1: i = -1 n1 = nodes[0]['url'] g.node(_label(n1), href=n1) for n1, sg, n2 in edges: if not is_included(n1, sg, n2): continue i += 1 # user = str(i) # user = "******"%(i,sg) user = "******" % sg # user = sg g.edge(_label(n1), user) g.edge(user, _label(n2)) g.node(_label(n1), href=n1) g.node(_label(n2), href=n2) g.node(user, href="https://github.com/%s" % sg) else: for (n1, n2), ct in ct.most_common(): # if ct >= 3: if ct >= 3: g.edge(_label(n1), _label(n2), weight=str(ct)) g.render('temp.dot.txt', format='svg') with open('temp.dot.txt.svg', 'r') as f: svg = f.read() return svg
def incidence(self, timeline: Iterable[Optional[List[int]]], num_vars: int, colors: List, edges: List, inc_file: str = 'IncidenceGraphStep', view: bool = False, fontsize: Union[str, int] = 16, penwidth: float = 2.2, basefill: str = 'white', sndshape: str = 'diamond', neg_tail: str = 'odot', var_name_one: str = '', var_name_two: str = '', column_distance: float = 0.5) -> None: """ Creates the incidence graph emphasized for the given timeline. Parameters ---------- 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'. num_vars : int Count of variables that are used in the clauses. colors : Iterable of color Colors to use for the graph parts. inc_file : string Basis for the file created, gets appended with the step number. view : bool If true opens the created file after creation. Default is false. basefill : color Background color of all nodes. Default is 'white'. sndshape : string Description of the shape for nodes with the variables. Default diamond. neg_tail : string Description of the shape of the edge-tail indicating a negated variable. Default is 'odot'. column_distance : float Changes the distance between both partitions, measured in image-units. Default is 0.5 Returns ------- None, but outputs the files with the graph for each timestep. """ _filename = self.outfolder / inc_file clausetag_n = var_name_one + '%d' vartag_n = var_name_two + '%d' g_incid = Graph(inc_file, strict=True, graph_attr={ 'splines': 'false', 'ranksep': '0.2', 'nodesep': str(float(column_distance)), 'fontsize': str(int(fontsize)), 'compound': 'true' }, edge_attr={ 'penwidth': str(float(penwidth)), 'dir': 'back', 'arrowtail': 'none' }) with g_incid.subgraph(name='cluster_clause', edge_attr={'style': 'invis'}, node_attr={ 'style': 'rounded,filled', 'fillcolor': basefill }) as clauses: clauses.attr(label='clauses') clauses.edges([(clausetag_n % (i + 1), clausetag_n % (i + 2)) for i in range(len(edges) - 1)]) g_incid.attr('node', shape=sndshape, penwidth=str(float(penwidth)), style='dotted') with g_incid.subgraph(name='cluster_ivar', edge_attr={'style': 'invis'}) as ivars: ivars.attr(label='variables') ivars.edges([(vartag_n % (i + 1), vartag_n % (i + 2)) for i in range(num_vars - 1)]) for i in range(num_vars): g_incid.node(vartag_n % (i + 1), vartag_n % (i + 1), color=colors[(i + 1) % len(colors)]) g_incid.attr('edge', constraint='false') for clause in edges: for var in clause[1]: if var >= 0: g_incid.edge(clausetag_n % clause[0], vartag_n % var, color=colors[var % len(colors)]) else: g_incid.edge(clausetag_n % clause[0], vartag_n % -var, color=colors[-var % len(colors)], arrowtail=neg_tail) # make edgelist variable-based (varX, clauseY), ... # var_cl_iter [(1, 1), (4, 1), ... var_cl_iter = tuple(flatten([[(x, y[0]) for x in y[1]] for y in edges])) bodybaselen = len(g_incid.body) for i, variables in enumerate(timeline, start=1): # all timesteps # reset highlighting g_incid.body = g_incid.body[:bodybaselen] if variables is None: g_incid.render(view=view, format='svg', filename=str(_filename) + str(i)) continue emp_clause = { var_cl[1] for var_cl in var_cl_iter if abs(var_cl[0]) in variables } emp_var = { abs(var_cl[0]) for var_cl in var_cl_iter if var_cl[1] in emp_clause } for var in emp_var: _vartag = vartag_n % abs(var) _style = 'solid,filled' if var in variables else 'dotted,filled' g_incid.node(_vartag, _vartag, style=_style, fillcolor='yellow') for clause in emp_clause: g_incid.node(clausetag_n % clause, clausetag_n % clause, fillcolor='yellow') for edge in var_cl_iter: (var, clause) = edge _style = 'solid' if clause in emp_clause else 'dotted' _vartag = vartag_n % abs(var) if var >= 0: g_incid.edge(clausetag_n % clause, _vartag, color=colors[var % len(colors)], style=_style) else: # negated variable g_incid.edge(clausetag_n % clause, _vartag, color=colors[-var % len(colors)], arrowtail='odot', style=_style) g_incid.render(view=view, format='svg', filename=str(_filename) + str(i))
table = '<TABLE><TR><TD COLSPAN="2"><B>Hypernyms</B></TD></TR>%s</TABLE>' % table_rows avg_C = nx.average_clustering(G, weight='weight') gv = Graph(comment='Cluster {:s} for {:s}'.format(cid, ', '.join(hypernyms[cid])), encoding='utf-8', engine='sfdp', format='svg') gv.body.append('label="Graph for {:s}, average C={:.4f}"'.format(cid, avg_C)) gv.body.append('size="10,10"') gv.body.append('outputorder=edgesfirst') gv.body.append('overlap=false') gv.body.append('splines=true') gv.node_attr.update(color='#ffffff', margin='0') gv.edge_attr.update(color='#666666') gv.node('Legend', label='<{:s}>'.format(table), shape='none', margin='0') for n in G: gv.node(n) for e1, e2, data in G.edges(data=True): gv.edge(e1, e2, weight=str(data['weight'])) if len(G.edges()) > 5000: logging.warn('No reason to render such a big graph, so I will not') gv_path = gv.save(prefix + '.gv') logging.info('Graph is saved: %s', gv_path) else: gv_path = gv.render(prefix + '.gv') logging.info('Graph is rendered: %s', gv_path)
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') ##Initialising subgraphs based on classed
from slideshow import slideshow from graphviz import Graph count=1 gv = Graph('G', filename='heading',format="png") gv.node_attr.update(color='white', style='filled',fontsize="50") gv.node("Reverse Delete Algorithm") gv.render(str(count)) count+=1 gv = Graph('G', filename='Description',format="png") gv.node_attr.update(color='white', style='filled',fontsize="25") gv.edge("Start with graph G, which contains a list of edges E.","Go through E in decreasing order of edge weights.",color="white") gv.edge("Go through E in decreasing order of edge weights.","For each edge, check if deleting the edge will further disconnect the graph.",color="white") gv.edge("For each edge, check if deleting the edge will further disconnect the graph.","Perform any deletion that does not lead to additional disconnection.",color="white") gv.render(str(count)) count+=1 gv = Graph('G', filename='Legend',format="png") gv.node_attr.update(color='white', style='filled',fontsize="30") gv.body.extend(['rankdir=LR', 'size="8,5"']) gv.node("green",color="green") gv.node("red",color="red") gv.node("blue",color="blue") gv.edge("Current edge:","green",color="green") gv.edge("Deleted edge/Edge not in Spanning Tree:","red",color="red") gv.edge("Edge present in Spanning Tree:","blue",color="blue") gv.node('Legend:', shape='Mdiamond',color="yellow") gv.render(str(count)) count+=1
def visualize_by_collapsedNodes(summary, attr_M, store, A, N): current_blocks, cuttingPoint_list, block_descrips = get_information_for_blocks( summary, attr_M, store, N) # # filter out groups with less than 10 members # updated_blocks = [] # updated_descrips = [] # # for i in range(len(current_blocks)): # if len(current_blocks[i]) > 10: # updated_blocks.append(current_blocks[i]) # updated_descrips.append(block_descrips[i]) # # current_blocks = updated_blocks # block_descrips = updated_descrips # descrips_list = ['I1: against or abstention'+'\n'+'I10 V3: against or abstention' # +'\n'+'I10 V4: against or abstention', 'I1: against or abstention'+'\n'+'I10 V3: against or abstention' # +'\n'+'I10 V4: in favour','I1: against or abstention'+'\n'+'I10 V3: in favour', # 'I1: in favour'+'\n'+'I7 V4: in favour or abstention', 'I1: in favour'+'\n'+'I7 V4: against'] descrips_list = [ 'I1 = -1 or 0' + '\n' + 'I10 V3 = -1 or 0' + '\n' + 'I10 V4 = -1 or 0', 'I1 = -1 or 0' + '\n' + 'I10 V3 = -1 or 0' + '\n' + 'I10 V4 = 1', 'I1 = -1 or 0' + '\n' + 'I10 V3 = 1', 'I1 = 1' + '\n' + 'I7 V4 = 1 or 0', 'I1 = 1' + '\n' + 'I7 V4 = -1' ] # compute the connectivity density between each pair of blocks density_M = get_density_matrix(current_blocks, A) # a circular layout visualization # g = Digraph('G','collapsedNetwork_dblp.gv') g = Graph('G', 'collapsedNetwork_MP.gv') n = len(current_blocks) widths = [0.07 * len(current_blocks[i])**(1 / 2) + .1 for i in range(n)] g.attr(layout='circo', splines='spline', nodesep='2.', mindist='4.5') for i in range(n): # g.attr('node', shape='circle', fixedsize='true', fontsize='20',fontcolor='{h:} 0.8 0.8'.format(h=i/n),style='filled',\ # fillcolor='{h:} 0.6 0.8'.format(h=i/n),width=str(widths[i]),\ # xlabel=descrip_list[i]+str(len(current_blocks[i]))) g.attr('node', shape='circle', fixedsize='true', fontsize='30',style='filled',\ fillcolor='#9ecae1',width=str(widths[i]),\ xlabel=descrips_list[i]) # pos='1,str(sum(widths[:i+1])+1.*i)') # g.node('cluster %d'% i) g.node(str(i + 1), label='') for i in range(n): for j in range(n): g.attr('edge', penwidth=str(20 * density_M[i][j]), color='#7d7d7d50', arrowsize=str(1), arrowhead='normal') # g.edge('cluster %d'% i, 'cluster %d'% j) g.edge(str(i + 1), str(j + 1)) g.view()
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 ins: list variable que simulará el funcionamiento de una pila para almacenar los tokens Métodos ------- inc() Incrementa el índice del nodo usando la variable i """ def __init__(self, ins_): self.id = None self.i = 0 self.dot = Graph('AST', format='png') self.dot.attr('node', shape='box') self.ins = [";", "usuario", "from", "nombre", "select"] 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 graficar_select(self, ins_): self.inc() self.dot.node(str(self.id), 'CONSULTA: SELECT') self.inc() def graficar_ast(self): padre = self.id self.dot.node(str(self.id), 'INICIO') for i in range(0, len(self.ins)): self.inc() self.dot.edge(str(padre), str(self.id + 1)) if isinstance(self.ins[i], select): self.graficar_select(self.ins[i]) self.dot.view()
def graphs_visualisation(graph, obligationSet, solution, title="new_graph_view", view=False, save=True): """ Take an instance : a graph (dictionnary) and an obligation set, a PIDO solution (set of vertices) and a title Generate a graphic representation of the graph and the solution print it if view, save it if save (the name of the file will be the title) """ includedEdges = set() includedVertices = dict() verticesColor = dict() for obligation in obligationSet: obligationColor = randomColor() for vertex in obligation: verticesColor[vertex] = obligationColor for vertex in graph.keys(): includedVertices[vertex] = False g = Graph('G', filename=SAVE_PATH + title + '.gv', engine='sfdp') for vertex in solution: g.node(str(vertex), fillcolor=DOMINANT_COLOR, style="filled", color=verticesColor[vertex], penwidth="2") includedVertices[vertex] = True for neihbourg in graph[vertex]: g.node(str(neihbourg), fillcolor=DOMNINATED_COLOR, style="filled", color=verticesColor[neihbourg], penwidth="2") includedVertices[neihbourg] = True for vertex in graph.keys(): if not (includedVertices[vertex]): g.node(str(vertex), fillcolor="white", style="filled", color=verticesColor[vertex], penwidth="2") includedVertices[vertex] = True for vertex in graph.keys(): for neihbourg in graph[vertex]: if not ((vertex, neihbourg) in includedEdges): g.edge(str(vertex), str(neihbourg)) includedEdges.add((vertex, neihbourg)) includedEdges.add((neihbourg, vertex)) g.render(SAVE_PATH + title + ".gv", view=view) if not (save): print("unsave") os.remove(SAVE_PATH + title + ".gv") os.remove(SAVE_PATH + title + ".gv.pdf")
from graphviz import Graph from graphviz import Digraph hola = '<<TABLE>"\n<TR>""\n<TD>left</TD>""\n</TR>"\n</TABLE>>' hola1 = "\n<TR>" hola2 = "\n<TD>left</TD>" hola3 = "\n</TR>" hola4 = "\n</TABLE>>'''" print(hola) h = Graph('html_table', format='png') h.node('tab', label=hola) #h.view() h.render()
cCluster[clusterCounter].body.append('style=filled') cCluster[clusterCounter].body.append("color=lightgrey") cCluster[clusterCounter].body.append('label = "' + ins +'"') cCluster[clusterCounter].node_attr.update(style="filled") for iA in insAu: if ins == iA[1]: cCluster[clusterCounter].node(iA[0], fontsize = "13") clusterCounter += 1 aCluster = Graph("cluster_"+ str(clusterCounter+1)) aCluster.body.append('style=filled') aCluster.body.append("color=orange") aCluster.body.append('label = "Author"') aCluster.node(search) aCluster.node_attr.update(style="filled") for num in range(0,clusterCounter): g.subgraph(cCluster[num]) #g.subgraph(aCluster) for cAR in coAuthorR: g.edge(cAR[0], cAR[1], penwidth="2") g.body.append('ratio = compress') g.body.append('size = "13,30"') g.body.append(' rankdir="BT"') g.body.append('splines=ortho') #g.body.append('nodesep="0.3"')
from graphviz import Graph g = Graph(format='png') # attr will add attribute directly to the source? # and node or edge or graph create after that will be create with default value of attr g.attr('node', shape='circle') # first argument can also be graph or edge g.node('0') g.node('1') g.attr('node', shape='square') g.node('2') g.attr('node', shape='star') g.node('3') g.node('4', shape='circle') g.view()
def graph(data): dot = Graph(comment='Kanjis', strict=True) dot.engine = 'neato' dot.format = 'svg' dot.attr(rankdir='TB', overlap="false") dot.attr('node', fontsize='30') similaredges = defaultdict(set) for kanji in data.kanjis: #try: k = kanji #.decode('utf-8') label = ("<b>" + kanji + "</b>\n " + data.descriptions[kanji] ) #.decode('utf-8') shape = "circle" fcolor = "0 0 " + str(1 - (0.2 + 0.8 * data.ease[kanji])) color = fcolor if (kanji in Similarity.dangerzones): shape = "doublecircle" color = "red" node = dot.node(data.descriptions[kanji], label=kanji, shape=shape, color=color, fontcolor=fcolor, fillcolor=data.colors[kanji], style='filled') # constraint='true' # color = "black" # for similar in data.similars[kanji]: # color = "black" # if (similar in dangerzones or kanji in dangerzones): # color = "red" # if not similaredges[kanji] or not similar in similaredges[kanji]: # if random.random() < 0.2 and color != "red": # Random dropoff # color= "lightgrey" # constraint='false' # dot.edge(data.descriptions[kanji], data.descriptions[similar], color=color, constraint=constraint)#.decode('utf-8') # similaredges[kanji].add(similar) # similaredges[similar].add(kanji) for similar in data.similars[kanji]: color = "black" style = "invis" if (similar in Similarity.dangerzones or kanji in Similarity.dangerzones): color = "red" style = "" if not similaredges[kanji] or not similar in similaredges[ kanji]: dot.edge(data.descriptions[kanji], data.descriptions[similar], color=color, constraint="true", style=style) #.decode('utf-8') similaredges[kanji].add(similar) similaredges[similar].add(kanji) for similar in data.semilars[kanji]: color = "lightgrey" if (similar in Similarity.dangerzones or kanji in Similarity.dangerzones): color = "red" if not similaredges[kanji] or not similar in similaredges[ kanji]: if random.random() >= 0.3: # random dropoff dot.edge(data.descriptions[kanji], data.descriptions[similar], color=color, constraint="false") #.decode('utf-8') similaredges[kanji].add(similar) similaredges[similar].add(kanji) #except Exception: # print("encoding fial") return dot
def Generate(self, file_format): #生成file_format类型的思维导图并展示 sum_list = [[], [], [], [], []] branch_dict = {} last_content = ['', '', '', '', ''] content_dict = {} # 再次进行文件格式筛查,实际上没必要,选择文件步骤已经做过 try: print(self.exts) print(self.Files) if self.exts[0] == 'txt' or self.exts[0] == 'TXT': f = open(self.Files[0], 'r', encoding='utf-8') context = f.readlines() else: context = [] for i in range(len(self.Files)): print(self.Files[i]) temp_list = BaiduOCR.detect_image(self.Files[i]) for j in range(len(temp_list)): context.append(temp_list[j]) print(context) except: QMessageBox.question( self, "File information.", "You can select one txt file or several images", QMessageBox.Yes) return None # 分析笔记结构 for i in range(len(context)): depth_num, content = self.depth(context[i]) if depth_num == []: if i == 0: sum_list[0].append(content) last_depth = [] last_content[0] = content else: if content == "": pass else: if last_content[len( last_depth)] not in content_dict.keys(): content_dict[last_content[len( last_depth)]] = content else: content_dict[last_content[len(last_depth)]] += ( "\n" + content) else: sum_list[len(depth_num)].append(content) last_depth = depth_num if last_content[len(depth_num) - 1] not in branch_dict.keys(): branch_dict[last_content[len(depth_num) - 1]] = [] branch_dict[last_content[len(depth_num) - 1]].append(content) last_content[len(depth_num)] = content print(sum_list) print("aaaaaaaaaa") print(branch_dict) print("bbbbbbbbbb") print(content_dict) # 生成思维导图实例,并设置导图属性 if self.typegraph == self.TypeGraph_List[0]: g = Graph('G', format=file_format, engine=self.engine) else: g = Digraph('G', format=file_format, engine=self.engine) print(self.TypeTree_Decision()) g.graph_attr['rankdir'] = self.TypeTree_Decision() g.attr(rank='same') g.node_attr['shape'] = self.TypeBbox_Decision() g.node_attr['fontname'] = self.TypeFace_Decision() g.node_attr['color'] = self.BboxColor_Decision() g.node_attr['fontcolor'] = self.CharColor_Decision() g.node_attr['fontsize'] = str(self.fontsize) g.edge_attr['color'] = self.EdgeColor_Decision() g.edge_attr['style'] = self.typeedge # 创建标题节点,并连接有归属关系的标题节点 for i in range(5): if len(sum_list[i]) == 0: pass else: for j in range(len(sum_list[i])): g.node(sum_list[i][j], sum_list[i][j]) if sum_list[i][j] in branch_dict.keys(): for k in range(len(branch_dict[sum_list[i][j]])): g.edge(sum_list[i][j], branch_dict[sum_list[i][j]][k]) # 创建内容节点,并连接有归属关系的标题节点与内容节点 for i in content_dict.keys(): if i not in branch_dict.keys(): if self.TypeNote_Decision() == "None": pass else: if self.TypeNote_Decision() == "All": temp = content_dict[i] print(self.fontsize) g.node(name=temp, label=temp, fontcolor=self.NoteColor_Decision(), shape='none') else: temp = content_dict[i][:10] + "……" g.node(name=temp, label=temp, fontcolor=self.NoteColor_Decision(), shape='none') g.edge(i, temp, color=self.NoteColor_Decision()) print("yoyoyoyoyoyoyyoyoyo") g.view("G")
from graphviz import Graph e = Graph('ER', filename='er.gv', engine='neato') e.node('h1') e.node('h2')
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 plot_figure2(ratio, width, height): dot = Graph(name="Figure 2") dot.attr(ratio=f"{ratio}", size=f"{width}, {height}!", label="Figure 2") # dot.node_attr.update(color='deepskyblue3', style='filled') dot.node("root", "x1 <= 0") dot.node("lc", "0") dot.node("rc", "x2 <= 0") dot.node("rlc", "x1 <= 2") dot.node("rrc", "5") dot.node("rllc", "2") dot.node("rlrc", "x2 <= -2") dot.node("rlrlc", "2") dot.node("rlrrc", "4") dot.edge("root", "lc") dot.edge("root", "rc") dot.edge("rc", "rlc") dot.edge("rc", "rrc") dot.edge("rlc", "rllc") dot.edge("rlc", "rlrc") dot.edge("rlrc", "rlrlc") dot.edge("rlrc", "rlrrc") return dot
def create_graph(self) -> Graph: dot = Graph() dot.body.append(f'// Graph generated by {APP_NAME} {__version__}') dot.body.append(f'// {APP_URL}') font = 'arial' dot.attr('graph', rankdir='LR', ranksep='2', bgcolor='white', nodesep='0.33', fontname=font) dot.attr('node', shape='record', style='filled', fillcolor='white', fontname=font) dot.attr('edge', style='bold', fontname=font) # prepare ports on connectors depending on which side they will connect for _, cable in self.cables.items(): for connection_color in cable.connections: if connection_color.from_port is not None: # connect to left self.connectors[connection_color.from_name].ports_right = True if connection_color.to_port is not None: # connect to right self.connectors[connection_color.to_name].ports_left = True for connector in self.connectors.values(): html = [] rows = [[connector.name if connector.show_name else None], [f'P/N: {connector.pn}' if connector.pn else None, html_line_breaks(manufacturer_info_field(connector.manufacturer, connector.mpn))], [html_line_breaks(connector.type), html_line_breaks(connector.subtype), f'{connector.pincount}-pin' if connector.show_pincount else None, connector.color, html_colorbar(connector.color)], '<!-- connector table -->' if connector.style != 'simple' else None, [html_image(connector.image)], [html_caption(connector.image)], [html_line_breaks(connector.notes)]] html.extend(nested_html_table(rows)) if connector.style != 'simple': pinhtml = [] pinhtml.append('<table border="0" cellspacing="0" cellpadding="3" cellborder="1">') for pin, pinlabel in zip(connector.pins, connector.pinlabels): if connector.hide_disconnected_pins and not connector.visible_pins.get(pin, False): continue pinhtml.append(' <tr>') if connector.ports_left: pinhtml.append(f' <td port="p{pin}l">{pin}</td>') if pinlabel: pinhtml.append(f' <td>{pinlabel}</td>') if connector.ports_right: pinhtml.append(f' <td port="p{pin}r">{pin}</td>') pinhtml.append(' </tr>') pinhtml.append(' </table>') html = [row.replace('<!-- connector table -->', '\n'.join(pinhtml)) for row in html] html = '\n'.join(html) dot.node(connector.name, label=f'<\n{html}\n>', shape='none', margin='0', style='filled', fillcolor='white') if len(connector.loops) > 0: dot.attr('edge', color='#000000:#ffffff:#000000') if connector.ports_left: loop_side = 'l' loop_dir = 'w' elif connector.ports_right: loop_side = 'r' loop_dir = 'e' else: raise Exception('No side for loops') for loop in connector.loops: dot.edge(f'{connector.name}:p{loop[0]}{loop_side}:{loop_dir}', f'{connector.name}:p{loop[1]}{loop_side}:{loop_dir}') # determine if there are double- or triple-colored wires in the harness; # if so, pad single-color wires to make all wires of equal thickness pad = any(len(colorstr) > 2 for cable in self.cables.values() for colorstr in cable.colors) for cable in self.cables.values(): html = [] awg_fmt = '' if cable.show_equiv: # Only convert units we actually know about, i.e. currently # mm2 and awg --- other units _are_ technically allowed, # and passed through as-is. if cable.gauge_unit =='mm\u00B2': awg_fmt = f' ({awg_equiv(cable.gauge)} AWG)' elif cable.gauge_unit.upper() == 'AWG': awg_fmt = f' ({mm2_equiv(cable.gauge)} mm\u00B2)' rows = [[cable.name if cable.show_name else None], [f'P/N: {cable.pn}' if (cable.pn and not isinstance(cable.pn, list)) else None, html_line_breaks(manufacturer_info_field( cable.manufacturer if not isinstance(cable.manufacturer, list) else None, cable.mpn if not isinstance(cable.mpn, list) else None))], [html_line_breaks(cable.type), f'{cable.wirecount}x' if cable.show_wirecount else None, f'{cable.gauge} {cable.gauge_unit}{awg_fmt}' if cable.gauge else None, '+ S' if cable.shield else None, f'{cable.length} mm' if cable.length > 0 else None, cable.color, html_colorbar(cable.color)], '<!-- wire table -->', [html_image(cable.image)], [html_caption(cable.image)], [html_line_breaks(cable.notes)]] html.extend(nested_html_table(rows)) wirehtml = [] wirehtml.append('<table border="0" cellspacing="0" cellborder="0">') # conductor table wirehtml.append(' <tr><td> </td></tr>') for i, connection_color in enumerate(cable.colors, 1): wirehtml.append(' <tr>') wirehtml.append(f' <td><!-- {i}_in --></td>') wirehtml.append(f' <td>{wv_colors.translate_color(connection_color, self.color_mode)}</td>') wirehtml.append(f' <td><!-- {i}_out --></td>') wirehtml.append(' </tr>') bgcolors = ['#000000'] + get_color_hex(connection_color, pad=pad) + ['#000000'] wirehtml.append(f' <tr>') wirehtml.append(f' <td colspan="3" border="0" cellspacing="0" cellpadding="0" port="w{i}" height="{(2 * len(bgcolors))}">') wirehtml.append(' <table cellspacing="0" cellborder="0" border="0">') for j, bgcolor in enumerate(bgcolors[::-1]): # Reverse to match the curved wires when more than 2 colors wirehtml.append(f' <tr><td colspan="3" cellpadding="0" height="2" bgcolor="{bgcolor if bgcolor != "" else wv_colors.default_color}" border="0"></td></tr>') wirehtml.append(' </table>') wirehtml.append(' </td>') wirehtml.append(' </tr>') if(cable.category == 'bundle'): # for bundles individual wires can have part information # create a list of wire parameters wireidentification = [] if isinstance(cable.pn, list): wireidentification.append(f'P/N: {cable.pn[i - 1]}') manufacturer_info = manufacturer_info_field( cable.manufacturer[i - 1] if isinstance(cable.manufacturer, list) else None, cable.mpn[i - 1] if isinstance(cable.mpn, list) else None) if manufacturer_info: wireidentification.append(html_line_breaks(manufacturer_info)) # print parameters into a table row under the wire if(len(wireidentification) > 0): wirehtml.append(' <tr><td colspan="3">') wirehtml.append(' <table border="0" cellspacing="0" cellborder="0"><tr>') for attrib in wireidentification: wirehtml.append(f' <td>{attrib}</td>') wirehtml.append(' </tr></table>') wirehtml.append(' </td></tr>') if cable.shield: wirehtml.append(' <tr><td> </td></tr>') # spacer wirehtml.append(' <tr>') wirehtml.append(' <td><!-- s_in --></td>') wirehtml.append(' <td>Shield</td>') wirehtml.append(' <td><!-- s_out --></td>') wirehtml.append(' </tr>') if isinstance(cable.shield, str): # shield is shown with specified color and black borders shield_color_hex = wv_colors.get_color_hex(cable.shield)[0] attributes = f'height="6" bgcolor="{shield_color_hex}" border="2" sides="tb"' else: # shield is shown as a thin black wire attributes = f'height="2" bgcolor="#000000" border="0"' wirehtml.append(f' <tr><td colspan="3" cellpadding="0" {attributes} port="ws"></td></tr>') wirehtml.append(' <tr><td> </td></tr>') wirehtml.append(' </table>') html = [row.replace('<!-- wire table -->', '\n'.join(wirehtml)) for row in html] # connections for connection_color in cable.connections: if isinstance(connection_color.via_port, int): # check if it's an actual wire and not a shield dot.attr('edge', color=':'.join(['#000000'] + wv_colors.get_color_hex(cable.colors[connection_color.via_port - 1], pad=pad) + ['#000000'])) else: # it's a shield connection # shield is shown with specified color and black borders, or as a thin black wire otherwise dot.attr('edge', color=':'.join(['#000000', shield_color_hex, '#000000']) if isinstance(cable.shield, str) else '#000000') if connection_color.from_port is not None: # connect to left from_port = f':p{connection_color.from_port}r' if self.connectors[connection_color.from_name].style != 'simple' else '' code_left_1 = f'{connection_color.from_name}{from_port}:e' code_left_2 = f'{cable.name}:w{connection_color.via_port}:w' dot.edge(code_left_1, code_left_2) from_string = f'{connection_color.from_name}:{connection_color.from_port}' if self.connectors[connection_color.from_name].show_name else '' html = [row.replace(f'<!-- {connection_color.via_port}_in -->', from_string) for row in html] if connection_color.to_port is not None: # connect to right code_right_1 = f'{cable.name}:w{connection_color.via_port}:e' to_port = f':p{connection_color.to_port}l' if self.connectors[connection_color.to_name].style != 'simple' else '' code_right_2 = f'{connection_color.to_name}{to_port}:w' dot.edge(code_right_1, code_right_2) to_string = f'{connection_color.to_name}:{connection_color.to_port}' if self.connectors[connection_color.to_name].show_name else '' html = [row.replace(f'<!-- {connection_color.via_port}_out -->', to_string) for row in html] html = '\n'.join(html) dot.node(cable.name, label=f'<\n{html}\n>', shape='box', style='filled,dashed' if cable.category == 'bundle' else '', margin='0', fillcolor='white') return dot
print(df) import matplotlib.pyplot as plt from graphviz import Graph,render import tempfile G = Graph(name='Network Topology for vsan ' + vsan) for i in range(df.shape[0]): print('Entered in switch : ', df['Name'][i]) if df['Password'][i].strip(): client = get_client(df['Mgmt IP'][i], 'admin', df['Password'][i]) cmd = 'show topology vsan ' + vsan stdin, stdout, stderr = client.exec_command(cmd) df1 = get_topology(stdout) print(df1) G.node(df['Name'][i], _attributes={'shape':'box'}) for j in range(df1.shape[0]): G.node(df1['Switch Name'][j]) tail = df1['Switch Name'][j] if len(tail.split('-' or '_')) > 1: tail = '"' + df1['Switch Name'][j] + '"' head = df['Name'][i] if len(head.split('-' or '_')) > 1: head = '"' + df['Name'][i] + '"' label = tail + ' -- ' + head + ' [headlabel="{0}" labelfontsize=4 taillabel="{1}"]'.format(df1['Interface'][j], df1['Peer Interface'][j]) print('checking if this link already exists ....... ',label) if label not in [x.strip() for x in G.body]: G.edge( df['Name'][i], df1['Switch Name'][j], headlabel=df1['Peer Interface'][j], taillabel=df1['Interface'][j], labelfontsize="4" ) else: print('redundant link found, no need to add it')
def showHeatMap(self, db, question, answer, resultsToBoost1, resultsToBoost2, vars, nentities, levelsToDraw=2): # Extract a subgraph idcount = 0 node2id = {} id2node = {} #Add the question node2id[question] = idcount id2node[idcount] = question idcount += 1 #Add the answer node2id[answer] = idcount id2node[idcount] = answer idcount += 1 edges = set() level = 0 queries = [question] while level < levelsToDraw and len(queries) > 0: newqueries = set() for q in queries: idq = node2id[q] results = db.ps(q) for r in results: n = r[1] if n not in node2id: node2id[n] = idcount id2node[idcount] = n idcount += 1 idnode = node2id[n] edges.add((idnode, idq)) newqueries.add(n) queries = newqueries level += 1 # TODO Add all the connections on the last level # Add all the variables varNodes = set() for idvar in vars: pvar, ovar, tvar = self.getPEnt(idvar - nentities) pvar_db = db.lookup_id(self.dictr[pvar]) instancesVar = db.s(pvar_db, ovar) # Add the object if ovar not in node2id: node2id[ovar] = idcount id2node[idcount] = ovar idcount += 1 idnode = node2id[ovar] varNodes.add(idnode) #Render the graph dot = Graph(comment='') for id, nodeLabel in id2node.items(): c = (1 << 24) - 1 label = '' height = '0.3cm' width = '0.3cm' if id in varNodes: label = 'V' if nodeLabel in resultsToBoost1: c -= 127 << 8 c -= 127 if nodeLabel in resultsToBoost2: c -= 127 << 8 c -= 127 if nodeLabel in resultsToBoost1 and nodeLabel in resultsToBoost2: c -= 127 << 16 if id == 0: # question node label = 'Q' height = '0.7cm' width = '0.7cm' if id == 1: # answer node label = 'A' height = '0.7cm' width = '0.7cm' c = '#' + hex(c)[2:] dot.node(str(id), label=label, fillcolor=c, style='filled', height=height, width=width) for edg in edges: dot.edge(str(edg[0]), str(edg[1])) dot.render(view=True)
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))
from graphviz import Graph # 无向图 # 设置节点形状 f = Graph(name='example0', filename='example0.dot') f.attr('node', shape='circle') # 圆 f.node('圆', fontname='SimHei') f.attr('node', shape='doublecircle') # 双圆 f.node('双圆', fontname='SimHei') f.attr('node', shape='egg') # 蛋状 f.node('蛋状', fontname='SimHei') f.attr('node', shape='point') # 点 f.node('点', fontname='SimHei') f.attr('node', shape='oval') # 椭圆 f.node('椭圆', fontname='SimHei') f.attr('node', shape='box') # 方框 f.node('方框', fontname='SimHei') f.attr('node', shape='polygon') # 多边形 f.node('多边形', fontname='SimHei') f.attr('node', shape='diamond') # 菱形 f.node('菱形', fontname='SimHei') f.attr('node', shape='trapezium') # 梯形 f.node('梯形', fontname='SimHei')
"return-stmt-1", "selection-stmt", "selection-stmt-1", "simple-expression", "simple-expression-1", "statement", "statement-list", "statement-list-1", "term", "term-1", "type-specifier", "var-1", "var-declaration", "var-declaration-1", "ID", "NUM" ] input_txt = "producer2.txt" with open(input_txt) as f: # 读取推导的产生式 lines = f.readlines() queue = [] temp = [] dot = Graph(comment='The Syntax Analysis Tree') root = dot.node('program', 'program') queue.append('program') for index, line in enumerate(lines[:-1]): left_right = line.split('->') # 产生式的左部 left = left_right[0] right = left_right[1].split(' ')[:-1] # 产生式的右部 left_root = queue.pop() # 产生式的左部所在结点出栈 for right_item in right: right_new_name = right_item + str(index) dot.node(right_new_name, right_item) # 画点 dot.edge(left_root, right_new_name) # 画边 temp.append((right_new_name, right_item)) temp.reverse()
except: sys.stderr.write("Couldn't find appropriate links data in "+section+". Aborting.\n") for link in ibdiag_info[section][1]: # my_graph.edge(link[NodeGUID1],link[NodeGUID2]) try: the_links[tuple(sorted([link[NodeGUID1],link[NodeGUID2]]))] += 1 except: the_links[tuple(sorted([link[NodeGUID1],link[NodeGUID2]]))] = 1 the_nodes[link[NodeGUID1]][2] += 1 the_nodes[link[NodeGUID2]][2] += 1 # print(ibdiag_info[section]) nodes_list=[] for NodeGUID in the_nodes.keys(): node_graph_id, nodeDesc, link_count = the_nodes[NodeGUID] nodes_list.append((link_count, nodeDesc, node_graph_id, NodeGUID)) nodes_list.sort(reverse=True) for link_count, NodeDesc, node_graph_id, NodeGUID in nodes_list: my_graph.node(str(node_graph_id), NodeDesc) for node1, node2 in the_links: my_graph.edge(str(the_nodes[node1][0]),str(the_nodes[node2][0]), str(the_links[(node1, node2)])) #print(nodes_list) print(my_graph) #my_graph.render(filename='delme.png', view=True,format="PNG")
def visualize_patient(input_data, tree, tree_nbr): set_color(tree_nbr) pat_nbr = 1 patient = input_data.iloc[pat_nbr] target = -1 done = False while not done: set_i() u = Graph('G', filename='trees/patients/{}/tree_{}/patient_depth_{' '}'.format(pat_nbr, tree_nbr, target + 1), format='png') u.graph_attr.update(outputorder='edgesfirst', smoothing='triangle', colors='whitesmoke', fontcolor='gray') u.edge_attr.update(arrowhead='vee', arrowsize='2', tailclip='false', headclip='false', color='whitesmoke', fontcolor='gray') u.node_attr.update(style='filled, rounded', outputorder='edgesfirst', smoothing='triangle', color='whitesmoke', fontcolor='gray') done = tree.visiulize_base(u, patient, 0, target) u.render() target += 1 if done: ll = tree.left.find_leaf(tree.name, patient, 0, target) lr = tree.right.find_leaf(tree.name, patient, 0, target) u = Graph('G', filename='trees/patients/{}/tree_{}/patient_depth_{' '}'.format(pat_nbr, tree_nbr, target + 1), format='png') u.graph_attr.update(outputorder='edgesfirst', smoothing='triangle', colors='whitesmoke', fontcolor='gray') u.edge_attr.update(arrowhead='vee', arrowsize='2', tailclip='false', headclip='false', color='whitesmoke', fontcolor='gray') u.node_attr.update(style='filled, rounded', outputorder='edgesfirst', smoothing='triangle', color='whitesmoke', fontcolor='gray') if ll is not None: leaf = ll else: leaf = lr label = ( str(int(np.round(leaf.good / leaf.nbr_samples, 2) * 100)) + "%") u.node(str(i), label=label, fillcolor='{},{},{}'.format( 120 * (leaf.good / leaf.nbr_samples) / 360, 1, 1), color='{},{},{}'.format( 120 * (leaf.good / leaf.nbr_samples) / 360, 1, 1), fontcolor='black', width='7', height='5', fontsize='20') u.render() print(target) return
def create_graph(self): dot = Graph() dot.body.append('// Graph generated by WireViz') dot.body.append('// https://github.com/formatc1702/WireViz') font = 'arial' dot.attr('graph', rankdir='LR', ranksep='2', bgcolor='white', nodesep='0.33', fontname=font) dot.attr('node', shape='record', style='filled', fillcolor='white', fontname=font) dot.attr('edge', style='bold', fontname=font) # prepare ports on connectors depending on which side they will connect for _, cable in self.cables.items(): for connection in cable.connections: if connection.from_port is not None: # connect to left self.connectors[connection.from_name].ports_right = True if connection.to_port is not None: # connect to right self.connectors[connection.to_name].ports_left = True for key, connector in self.connectors.items(): if connector.category == 'ferrule': subtype = f', {connector.subtype}' if connector.subtype else '' color = wv_colors.translate_color( connector.color, self.color_mode) if connector.color else '' infostring = f'{connector.type}{subtype} {color}' infostring_l = infostring if connector.ports_right else '' infostring_r = infostring if connector.ports_left else '' # INFO: Leaving this one as a string.format form because f-strings do not work well with triple quotes colorbar = f'<TD BGCOLOR="{wv_colors.translate_color(connector.color, "HEX")}" BORDER="1" SIDES="LR" WIDTH="4"></TD>' if connector.color else '' dot.node(key, shape='none', style='filled', margin='0', orientation='0' if connector.ports_left else '180', label='''< <TABLE BORDER="1" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2"><TR> <TD PORT="p1l"> {infostring_l} </TD> {colorbar} <TD PORT="p1r"> {infostring_r} </TD> </TR></TABLE> >'''.format(infostring_l=infostring_l, infostring_r=infostring_r, colorbar=colorbar)) else: # not a ferrule attributes = [ connector.type, connector.subtype, f'{connector.pincount}-pin' if connector.show_pincount else '' ] pinouts = [[], [], []] for pinnumber, pinname in zip(connector.pinnumbers, connector.pinout): if connector.hide_disconnected_pins and not connector.visible_pins.get( pinnumber, False): continue pinouts[1].append(pinname) if connector.ports_left: pinouts[0].append(f'<p{pinnumber}l>{pinnumber}') if connector.ports_right: pinouts[2].append(f'<p{pinnumber}r>{pinnumber}') label = [ connector.name if connector.show_name else '', attributes, pinouts, connector.notes ] dot.node(key, label=nested(label)) if len(connector.loops) > 0: dot.attr('edge', color='#000000:#ffffff:#000000') if connector.ports_left: loop_side = 'l' loop_dir = 'w' elif connector.ports_right: loop_side = 'r' loop_dir = 'e' else: raise Exception('No side for loops') for loop in connector.loops: dot.edge( f'{connector.name}:p{loop[0]}{loop_side}:{loop_dir}', f'{connector.name}:p{loop[1]}{loop_side}:{loop_dir}' ) for _, cable in self.cables.items(): awg_fmt = '' if cable.show_equiv: # Only convert units we actually know about, i.e. currently # mm2 and awg --- other units _are_ technically allowed, # and passed through as-is. if cable.gauge_unit == 'mm\u00B2': awg_fmt = f' ({awg_equiv(cable.gauge)} AWG)' elif cable.gauge_unit.upper() == 'AWG': awg_fmt = f' ({mm2_equiv(cable.gauge)} mm\u00B2)' attributes = [ f'{len(cable.colors)}x' if cable.show_wirecount else '', f'{cable.gauge} {cable.gauge_unit}{awg_fmt}' if cable.gauge else '', '+ S' if cable.shield else '', f'{cable.length} m' if cable.length > 0 else '' ] attributes = list(filter(None, attributes)) html = '<table border="0" cellspacing="0" cellpadding="0"><tr><td>' # main table html = f'{html}<table border="0" cellspacing="0" cellpadding="3" cellborder="1">' # name+attributes table if cable.show_name: html = f'{html}<tr><td colspan="{len(attributes)}">{cable.name}</td></tr>' html = f'{html}<tr>' # attribute row for attrib in attributes: html = f'{html}<td>{attrib}</td>' html = f'{html}</tr>' # attribute row html = f'{html}</table></td></tr>' # name+attributes table html = f'{html}<tr><td> </td></tr>' # spacer between attributes and wires html = f'{html}<tr><td><table border="0" cellspacing="0" cellborder="0">' # conductor table for i, connection in enumerate(cable.colors, 1): p = [] p.append(f'<!-- {i}_in -->') p.append(wv_colors.translate_color(connection, self.color_mode)) p.append(f'<!-- {i}_out -->') html = f'{html}<tr>' for bla in p: html = f'{html}<td>{bla}</td>' html = f'{html}</tr>' bgcolor = wv_colors.translate_color(connection, 'hex') bgcolor = bgcolor if bgcolor != '' else '#ffffff' html = f'{html}<tr><td colspan="{len(p)}" cellpadding="0" height="6" bgcolor="{bgcolor}" border="2" sides="tb" port="w{i}"></td></tr>' if cable.shield: p = ['<!-- s_in -->', 'Shield', '<!-- s_out -->'] html = f'{html}<tr><td> </td></tr>' # spacer html = f'{html}<tr>' for bla in p: html = html + f'<td>{bla}</td>' html = f'{html}</tr>' html = f'{html}<tr><td colspan="{len(p)}" cellpadding="0" height="6" border="2" sides="b" port="ws"></td></tr>' html = f'{html}<tr><td> </td></tr>' # spacer at the end html = f'{html}</table>' # conductor table html = f'{html}</td></tr>' # main table if cable.notes: html = f'{html}<tr><td cellpadding="3">{cable.notes}</td></tr>' # notes table html = f'{html}<tr><td> </td></tr>' # spacer at the end html = f'{html}</table>' # main table # connections for connection in cable.connections: if isinstance( connection.via_port, int): # check if it's an actual wire and not a shield search_color = cable.colors[connection.via_port - 1] if search_color in wv_colors.color_hex: dot.attr( 'edge', color= f'#000000:{wv_colors.color_hex[search_color]}:#000000' ) else: # color name not found dot.attr('edge', color='#000000:#ffffff:#000000') else: # it's a shield connection dot.attr('edge', color='#000000') if connection.from_port is not None: # connect to left from_ferrule = self.connectors[ connection.from_name].category == 'ferrule' port = f':p{connection.from_port}r' if not from_ferrule else '' code_left_1 = f'{connection.from_name}{port}:e' code_left_2 = f'{cable.name}:w{connection.via_port}:w' dot.edge(code_left_1, code_left_2) from_string = f'{connection.from_name}:{connection.from_port}' if not from_ferrule else '' html = html.replace(f'<!-- {connection.via_port}_in -->', from_string) if connection.to_port is not None: # connect to right to_ferrule = self.connectors[ connection.to_name].category == 'ferrule' code_right_1 = f'{cable.name}:w{connection.via_port}:e' to_port = f':p{connection.to_port}l' if not to_ferrule else '' code_right_2 = f'{connection.to_name}{to_port}:w' dot.edge(code_right_1, code_right_2) to_string = f'{connection.to_name}:{connection.to_port}' if not to_ferrule else '' html = html.replace(f'<!-- {connection.via_port}_out -->', to_string) dot.node( cable.name, label=f'<{html}>', shape='box', style='filled,dashed' if cable.category == 'bundle' else '', margin='0', fillcolor='white') return dot
print("compute dissimilarities") for player_1_id in range(nb_players): for player_2_id in range(nb_players): dissimilarity = compute_dissimilarity(player_1_id, player_2_id) dissimilarity_matrix[player_1_id, player_2_id] = dissimilarity print("dissimilarity matrix") print(dissimilarity_matrix) threshold = 15 # build a graph from the dissimilarity dot = Graph(comment='Graph created from complex data', strict=True) for player_id in range(nb_players): player_name = dataframe.loc[player_id][0] dot.node(player_name) for player_1_id in range(nb_players): # we use an undirected graph so we do not need # to take the potential reciprocal edge # into account for player_2_id in range(nb_players): # no self loops if not player_1_id == player_2_id: player_1_name = dataframe.loc[player_1_id][0] player_2_name = dataframe.loc[player_2_id][0] # use the threshold condition # EDIT THIS LINE if dissimilarity_matrix[player_1_id, player_2_id] > threshold: dot.edge(player_1_name, player_2_name,
class SNAnalyzer(object): def __init__(self,inPath,outPath,engine,analyzeType): self.network = {} self.nameIndex = {} self.inPath = inPath self.outPath = outPath self.engine = engine self.aType = analyzeType self.networkFileParse(self.inPath) def random_id(self,len): alpha = 'abcdefghijklmnopqrstuvwxyz' id = '' for i in range(0,len): id += random.choice(alpha) return id def networkFileParse(self,path): f = open(path, 'r') for line in f: line = line.replace("\n","") self.nameIndex.update({line.split(":")[0]:self.random_id(3)}) self.network.update({line.split(":")[0]:e.split(",") for e in line.split(":")[1:]}) f.close() def graphUpdate(self): if self.aType == "tw": self.graph = Digraph() elif self.aType == "fb": self.graph = Graph() else: exit("Invalid Analyze Type") for key in self.nameIndex.keys(): self.graph.node(self.nameIndex[key], key) for key in self.network.keys(): for friend in self.network[key]: if friend != "": self.graph.edge(self.nameIndex[key],self.nameIndex[friend]) def generateGraphCode(self): self.graphUpdate() return self.graph.source def renderGraph(self): self.graphUpdate() self.graph.engine = self.engine self.graph.render(self.outPath, view=True) def addNode(self,newNode): if newNode not in self.nameIndex.keys(): self.nameIndex[newNode] = self.random_id(3) self.network[newNode] = [] else: print("Error: Network already has that {} named Node !".format(newNode)) def removeNode(self,targetNode): if targetNode in self.nameIndex.keys(): del self.nameIndex[targetNode] del self.network[targetNode] for key in self.network.keys(): if targetNode in self.network[key]: self.network[key].remove(targetNode) else: print("Error: Network not has that {} named Node !".format(targetNode)) def hasRelation(self,sourceNode,targetNode): friends = self.network[sourceNode] if targetNode in friends: return True else: return False def addRelation(self,sourceNode,targetNode): if not self.hasRelation(sourceNode,targetNode): self.network[sourceNode].append(targetNode) else: print("Error: The Node {} is already related to {} !".format(sourceNode, targetNode)) def removeRelation(self,sourceNode,targetNode): if self.hasRelation(sourceNode,targetNode): self.network[sourceNode].remove(targetNode) else: print("Error: The Node {} is not related with {} !".format(sourceNode, targetNode))