def plot_graphs(self,path,count): '''Save graphs''' Gs=nx.to_agraph(self.gS) Gm=nx.to_agraph(self.gM) Gs_w=nx.to_agraph(self.gS_w) #add color to main nodes for node in self.gM.nodes(): n=Gs.get_node(node) n.attr['shape']='box' n.attr['style']='filled' n.attr['fillcolor']='turquoise' #add weight to edges for edge in self.gS_w.edges(data=True): ed=Gs_w.get_edge(edge[0],edge[1]) ed.attr['label']=edge[2]['weight'] loc= os.getcwd()+path+'/spanning/gS' + str(count)+'.png' loc1= os.getcwd()+path+'/projection/gM' + str(count)+'.png' loc2= os.getcwd()+path+'/spanning_w/gS_w' + str(count)+'.png' Gs.layout(prog='dot') # use dot Gm.layout(prog='dot') # use dot Gs_w.layout(prog='dot') Gs.draw(loc) Gm.draw(loc1) Gs_w.draw(loc2) return
def draw_graph(graph, output_path): """ Draws a networkx graph to disk using the `dot` format. ``graph``: networkx graph ``output_path``: Location to store the rendered output. """ nx.to_agraph(graph).draw(output_path, prog="dot") log.info("Wrote output to `%s'" % output_path)
def __generar_imagenes(self): A = nx.to_agraph(self.DRPC) # convert to a graphviz graph A.layout(prog='dot') # neato layout A.draw("DRPC.png", prog='dot') A = nx.to_agraph(self.DAPC) # convert to a graphviz graph A.layout() A.draw("DAPC.png", prog='dot') A = nx.to_agraph(self.DRPCP) # convert to a graphviz graph A.layout(prog='dot') # neato layout A.draw("DRPCP.png", prog='dot') A = nx.to_agraph(self.DAPCP) # convert to a graphviz graph A.layout() A.draw("DAPCP.png", prog='dot')
def setAgraph(self): self.A = x.to_agraph(self.network) self.A.graph_attr["viewport"] = "500,500,.03" self.edges = self.A.edges() self.nodes = self.A.nodes() self.cm = p.cm.Reds(range(2**10)) # color table self.clustering = x.clustering(self.network)
def view_spec_svg(request, spec_id, fullsize=False): spec = get_object_or_404(approval_models.WorkflowSpec, id=spec_id) graph = spec.to_coloured_graph() agraph = nx.to_agraph(graph) for nodename in agraph.nodes(): node = agraph.get_node(nodename) if 'task_data' in node.attr['data']: node.attr.update({ 'URL': reverse('task_dict', kwargs={ 'spec_id': spec.id, 'task_name': str(node)}), 'fontcolor': '#0000FF', 'target': '_parent', }) del node.attr['data'] # IE9 (+others?) fix: they don't have "Times Roman", only "Times # New Roman" TODO REFACTOR agraph.node_attr['fontname'] = "Times New Roman" agraph.edge_attr['fontname'] = "Times New Roman" svg = agraph.draw(None, 'svg', 'dot') # http://www.graphviz.org/content/percentage-size-svg-output if not fullsize: svg = re.sub(r'<svg width="[0-9]+pt" height="[0-9]+pt"', r'<svg width="100%" height="100%"', svg) response = HttpResponse(svg, content_type="image/svg+xml") return response
def make_pdf(dg): agraph = networkx.to_agraph(dg) agraph.graph_attr['overlap'] = 'false' agraph.graph_attr['splines'] = 'true' agraph.graph_attr['rankdir'] = 'LR' agraph.graph_attr['ranksep'] = '.1' agraph.draw('test.pdf', prog='dot')
def make_pdf(dg): agraph = networkx.to_agraph(dg) agraph.graph_attr['overlap']='false' agraph.graph_attr['splines']='true' agraph.graph_attr['rankdir']='LR' agraph.graph_attr['ranksep']='.1' agraph.draw('test.pdf',prog='dot')
def main(): parser = argparse.ArgumentParser() parser.add_argument('path', help = "target file or directory for summarization") parser.add_argument("--posseed", help="boosting seed for biased LexRank", default = None) parser.add_argument("--negseed", help="blocking seed for biased LexRank", default = None) parser.add_argument("--stopfile", help="file containing custom stopwords") parser.add_argument("-o", "--output", help = "output file name") parser.add_argument("-l", "--length", help = "summary length in lines", default = 10) parser.add_argument("--seed_posweight", help = "Weight for positive seed", default = 3) parser.add_argument("--seed_negweight", help = "Weight for negative seed", default = .0001) parser.add_argument("--ngrams", help = "N-gram number", default = 1) #normalization doesn't work due to being inherent within scoring method parser.add_argument("-n", "--is_norm", help = "Boolean flag for normalization", default = True) args = parser.parse_args() input_text = args.path pos_seed = args.posseed neg_seed = args.negseed stopfile = args.stopfile out_file = args.output sum_length = int(args.length) norm_flag = args.is_norm pos_weight = float(args.seed_posweight) neg_weight = float(args.seed_negweight) ngram = int(args.ngrams) corpus = Corpus(input_text).documents output_checker(out_file) if pos_seed == None and neg_seed == None: LR_method = 'unbiased' print LR_method [term_matrix, normalized] = TDM(corpus, pos_seed, neg_seed, stopfile, norm_flag, ngram).matrix pos_seed_vector = [] neg_seed_vector = [] else: LR_method = 'biased' if pos_seed == None: pos_seed = '' if neg_seed == None: neg_seed = '' [term_matrix, normalized, pos_seed_vector, neg_seed_vector] = TDM(corpus, pos_seed, neg_seed, stopfile, norm_flag, ngram).matrix corpus = corpus[2:] [scores,graph] = Graph(normalized, LR_method, pos_seed_vector, neg_seed_vector, pos_weight, neg_weight).sim_scores #embed() largest = networkx.strongly_connected_component_subgraphs(graph)[0] A = networkx.to_agraph(largest) #A.node_attr.update(shape='point') A.node_attr.update(overlap='voronoi') A.layout(prog='sfdp') networkx.write_dot(largest, 'testgraph.gv') A.draw('butterflyv2.png') print_summary(corpus, scores, out_file, sum_length)
def creatdepgraphplot(somedoc): newname = "dp_" + creatname(somedoc) + ".png" #draws the dependency graph pos = nx.graphviz_layout(dep_graph, prog='fdp') nx.draw_networkx_edge_labels(dep_graph, pos, dep_edges, font_size=7) nx.draw(dep_graph, pos, node_size=250, node_color='#A0CBE2', arrows=True, with_labels=True, font_size=7) A = nx.to_agraph(dep_graph) A.edge_attr.update(len=5) A.layout() A.draw(newname) plt.figure(1, figsize=(2000, 2000)) plt.savefig(newname, dpi=1000) plt.show() #plt.title('Dependency Graph of ' + findtheory(somedoc) ) #plt.axis('off') #plt.savefig(newname) #plt.close() return plt
def show_pygraphviz(g, prog='dot', graph_attr={}, node_attr={}, edge_attr={}): """ Display a networkx graph using pygraphviz. Parameters ---------- g : networkx.Graph Graph to visualize. prog : str Executable for generating the image. graph_attr : dict Global graph display attributes. node_attr : dict Global node display attributes. edge_attr : dict Global edge display attributes. See Also -------- pygraphviz """ fd = tempfile.NamedTemporaryFile(suffix='.jpg') fd.close() p = nx.to_agraph(g) p.graph_attr.update(graph_attr) p.node_attr.update(node_attr) p.edge_attr.update(edge_attr) p.draw(fd.name, prog=prog) imdisp(fd.name) os.remove(fd.name)
def graphviz_layout_with_rank(G, prog = "neato", root = None, sameRank = [], args = ""): ## See original import of pygraphviz in try-except block ## See original identification of root through command line try: import pygraphviz except ImportError: raise ImportError('requires pygraphviz ', 'http://networkx.lanl.gov/pygraphviz ', '(not available for Python3)') if root is not None: args+="-Groot=%s"%root args+="-Eweight=10000" A = nx.to_agraph(G) for sameNodeHeight in sameRank: if type(sameNodeHeight) == str: print("node \"%s\" has no peers in its rank group" %sameNodeHeight) A.add_subgraph(sameNodeHeight, rank="same") A.layout(prog=prog, args=args) ## See original saving of each node location to node_pos node_pos={} for n in G: node=pygraphviz.Node(A,n) try: xx,yy=node.attr["pos"].split(',') node_pos[n]=(float(xx),float(yy)) except: print("no position for node",n) node_pos[n]=(0.0,0.0) return node_pos
def main(): args = parse_args(sys.argv) graph = nx.read_dot(args.infile) droppers = [re.compile(pattern) for pattern in args.drop] keepers = [re.compile(pattern) for pattern in args.keep] rm_nodes = [] num_parents = graph.out_degree() degree = graph.degree() for node in graph.nodes(): if matches_any(node, droppers) and not matches_any(node, keepers): rm_nodes.append(node) elif degree[node] == 0: rm_nodes.append(node) elif num_parents[node] == 0: graph.node[node]['shape'] = 'hexagon' else: pass # Node will not be changed. detours = get_detours(graph, rm_nodes) graph.remove_nodes_from(rm_nodes) graph.add_edges_from(detours, style='dashed') graph.graph = {} # Clear all graph, edge, and node attributes # nx.write_dot(graph) should work, # but doesn't, because it calls nx.to_agraph(graph).clear() a = nx.to_agraph(graph) # print(graph.edge, file=sys.stderr) a.write(sys.stdout)
def Graph_draw (G_in, G_name): default_attributes={'graph':{},'node':{},'edge':{}} #default_attributes['graph']['label']='pygraphviz graph' default_attributes['node']['shape']='box' for u,v,d in G_in.edges(data=True): d['label'] = d.get('weight','') A = nx.to_agraph(G_in) # A.edge_attr['constraint']='false' # A.edge_attr['labeldistance']='1' # A.edge_attr['forcelabels']='true' #A.edge_attr['decorate']='true' # A.graph_attr['ranksep']='equally' A.graph_attr['rankdir']='LR' # A.graph_attr['splines']='line' # A.node_attr['shape']='oval' A.add_subgraph(('X'), name = 'cluster_1',style='invis', rank=1) A.add_subgraph((1,2,3), name = 'cluster_2',style='invis', rank =2) A.add_subgraph((10,20,30,40), name = 'cluster_3',style='invis', rank=3) A.add_subgraph(('Y'), name = 'cluster_4',style='invis', rank=4) A.add_subgraph(('X',3,30,'Y'), name='path') A.layout(prog='dot') A.draw(G_name+'.png') A.write('G1.dot') return
def convert_graph(graph): """ Convert graph to graphviz format. :param `DiGraph` graph: the graph :returns: a graphviz graph Designate its general layout and mark or rearrange nodes as appropriate. """ dot_graph = networkx.to_agraph(graph) # pylint: disable=no-member dot_graph.graph_attr.update(rankdir="LR") dot_graph.layout(prog="dot") xformers = [ _display.SpindleTransformer, _display.PartitionTransformer, _display.PartitionEdgeTransformer, _display.CongruenceEdgeTransformer, _display.EnclosureBayTransformer, _display.EnclosureTransformer, _display.AddedNodeTransformer, _display.RemovedNodeTransformer, _display.AddedEdgeTransformer, _display.RemovedEdgeTransformer ] _display.GraphTransformers.xform(dot_graph, xformers) return dot_graph
def corner_network(ant, data): #G = nx.cubical_graph() G = nx.Graph() #無向グラフ tmp1 = [] tmp2 = [] tmp3 = [] tmp4 = [] #for i in range(len(data)): #if data[i][2] == 'lu': #tmp1.append(str(i)) #elif data[i][2] == 'ld': #tmp2.append(str(i)) #elif data[i][2] == 'ru': #tmp3.append(str(i)) #elif data[i][2] == 'rd' : #tmp4.append(str(i)) for i in range(len(data)): if len(ant[i].parent) == 0 : pass else : dest = ant[i].parent[0] G.add_edge(str(data[i]), str(data[dest])) pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos, nodelist=tmp1, node_size=30, node_color="r") #nx.draw_networkx_nodes(G, pos, nodelist=tmp2, node_size=30, node_color="b") #nx.draw_networkx_nodes(G, pos, nodelist=tmp3, node_size=30, node_color="g") #nx.draw_networkx_nodes(G, pos, nodelist=tmp4, node_size=30, node_color="y") #nx.draw_networkx_nodes(G, pos, node_size=20, node_color="blue") nx.draw_networkx_edges(G, pos, width=1) A = nx.to_agraph(G) A.layout() A.draw("file.png")
def show_pygraphviz(g, prog='dot', graph_attr={}, node_attr={}, edge_attr={}): """ Display a networkx graph using pygraphviz. Parameters ---------- prog : str Executable for generating the image. graph_attr : dict Global graph display attributes. node_attr : dict Global node display attributes. edge_attr : dict Global edge display attributes. """ fd = tempfile.NamedTemporaryFile(suffix='.jpg') fd.close() p = nx.to_agraph(g) p.graph_attr.update(graph_attr) p.node_attr.update(node_attr) p.edge_attr.update(edge_attr) p.draw(fd.name, prog=prog) imdisp(fd.name) os.remove(fd.name)
def export_digraph(self, G, fn): '''Draws a digraph to a file. ''' if 'pygraphviz' in sys.modules: agraph = nx.to_agraph(G) agraph.draw(fn, format='eps', prog='neato')
def write_graph_to_file(graph, file_path, format='dot'): A = nx.to_agraph(graph) set_same_rank([ node.name for node in A.nodes() if node.name in [ 'NOUN_ROOT', 'VERB_ROOT', 'PRONOUN_ROOT', 'PROPER_NOUN_ROOT', 'NOUN_COMPOUND_ROOT' ] ], A, 'source') set_same_rank([ node.name for node in A.nodes() if node.name in ['ADJECTIVE_ROOT', 'ADVERB_ROOT'] ], A, 'same') # set_same_rank(['VERB_WITH_POLARITY', 'VERB_COPULA_WITHOUT_TENSE'], A) # # set_same_rank([node.name for node in filter(lambda node : node.name.endswith('ROOT'), A.nodes())], A, 'source') set_same_rank([ node.name for node in filter( lambda node: node.name.endswith('TERMINAL_TRANSFER'), A.nodes()) ], A) set_same_rank([ node.name for node in filter(lambda node: node.name.endswith('COPULA'), A.nodes()) ], A) set_same_rank([ node.name for node in filter( lambda node: node.name.endswith('TERMINAL'), A.nodes()) ], A, 'sink') A.layout(prog='dot') A.draw(file_path, format)
def plot_graph(self): G = self.graph() nstates = len(self.states) path = nx.shortest_path(G, source=self.start, target=self.end) tm, eigenvals = self.transition_matrix(end_links=True) G1 = nx.to_agraph(G) G1.graph_attr['label'] = str(self.totals) + \ ' State Space\nNum. States = {}\n' \ 'Shortest Path = {} steps\n2nd e.v. ' \ 'of Transition Matrix = {}' \ .format(nstates, len(path)-1, np.round(eigenvals[1].real, 5)) for idx in xrange(len(path)-1): edge = G1.get_edge(str(path[idx]), str(path[idx+1])) edge.attr['color'] = 'red1' start = G1.get_node(str(self.start)) start.attr['color'] = 'forestgreen' start.attr['shape'] = 'box' end = G1.get_node(str(self.end)) end.attr['color'] = 'red1' end.attr['shape'] = 'box' fileid = '-'.join([str(i) for i in self.totals]) + '.png' G1.draw('./plots/state_spaces/' + fileid, prog='circo')
def draw(self): A = nx.to_agraph(self.Graph) A.add_subgraph([root],rank='same') for level in self.levels: A.add_subgraph(level,rank='same') A.draw(self.filen, prog='dot')
def to_graphviz(G, gvfile, graph_label='', **kwargs): """ export graph of signifcant findings to dot file. A png can be generated from the commandline using graphviz >>> import subprocess >>> subprocess.call(['dot', '-Tpng', 'filpath.dot', '>', 'filepath.png']) :param G: the graph to be exported :param gvfile: file or filepath :param graph_label: For empty label pass graph_label=''. """ for n in G: node = G.node[n] attr = {} attr['shape'] = 'record' if not np.isnan(node.get('q', float('NaN'))): attr['color'] = 'red' if node['significant'] else 'black' attr['label'] = "{name}\\n{x} / {n} genes\\nq = {q:E}".format(name=node['name'], q=node['q'], x=node['x'], n=node['n']) else: attr['color'] = 'black' attr['label'] = """{name}""".format(name=node['name']) G.node[n] = attr A = nx.to_agraph(G) A.graph_attr['label'] = graph_label A.graph_attr['labelloc'] = 't' if hasattr(gvfile, 'write'): A.write(gvfile) else: with open(gvfile, 'w') as f: A.write(f)
def aGraphObject(G_in, types = [], color = 'black', layout = 'neato') : G0 = nx.DiGraph() for node in G_in.nodes() : lbl = G_in.node[node]['number'] G0.add_node(node, number = lbl, fontsize = 32, fixedsize='true') # , shape='circle' for (u,v) in G_in.edges() : type = int(G_in[u][v]['type']) if types.count(type) > 0: G0.add_edge(u,v, style = 'bold', color = color, minlen='3') G = nx.to_agraph(G0) G.graph_attr.update(splines='true', overlap='false', ratio='fill', size='21,21') for node in G.nodes() : size = 0.7 + 0.1*(G.in_degree(node)) node.attr['width'] = size node.attr['height'] = size G = makeLayout(G, layout) for node in G.nodes() : node.attr['label'] = node.attr['number'] if node.attr['number'] == '1' : node.attr['style'] = 'filled' node.attr['fillcolor'] = '#FFFAAA' return G
def aSymGraphObject(G_in, types, color = 'black') : G1 = symSubGraphFromTypes(G_in, types, color) G = nx.to_agraph(G1) G.graph_attr.update(splines='true', overlap='false', ratio='fill', size='15,15') for node in G.nodes() : w = 0.3*(G.in_degree(node) + G.out_degree(node)) w = 0.4 + int(w*10)/10.0 size = str(w) print node, 'degrees', G.in_degree(node), G.out_degree(node),' width ', size node.attr['width'] = size node.attr['height'] = size node.attr['fontsize'] = '32' node.attr['fixedsize'] = 'true' G = makeLayout(G) for node in G.nodes() : node.attr['label'] = node.attr['number'] if (G.out_degree(node) == 0) & (G.in_degree(node) == 0) : G.remove_node(node) if node.attr['number'] == '1' : node.attr['style'] = 'filled' node.attr['fillcolor'] = '#FFFAAA' for node in G.nodes() : print '(Sym. final) Degree of', node, '-', G.in_degree(node), G.out_degree(node), 'width', node.attr['width'] return G
def save_plot(graph, track_a, track_b, name="graph.png"): """save plot with index numbers rather than timing""" edges = graph.edges(data=True) e = [edge[2]['source'] for edge in edges] order = np.argsort(e) edges = [edges[i] for i in order.tolist()] nodes = graph.nodes(data=True) DG = nx.DiGraph() for edge in edges: source = edge[2]['source'] target = edge[2]['target'] v = target-source-1 # A if nodes[source][1]['song'] == 'a': DG.add_node(source, color = 'red', song = 'a', nearest = nodes[source][1]['nearest'], dist = nodes[source][1]['dist']) DG.add_edge(source, target) # B if nodes[source][1]['song'] == 'b': DG.add_node(source, color = 'blue', song = 'b', nearest = nodes[source][1]['nearest'], dist = nodes[source][1]['dist']) DG.add_edge(source, target) A = nx.to_agraph(DG) A.layout() A.draw(name) return DG
def draw(self, name = None): if not name: name = "ast" name = "%s.png"%name A = nx.to_agraph(self.net) A.layout(prog = 'dot') print "drawing ..." A.draw(name)
def render(self, filepath, format='svg', prog='dot', attributes={}): """Renders the tree into the file at `filepath`.""" agraph = nx.to_agraph(self) for key, value in attributes.iteritems(): agraph.node_attr[key] = value agraph.draw(filepath, format=format, prog=prog)
def drawNeato(sim,media): # http://www.graphviz.org/pdf/neatoguide.pdf G = nx.from_numpy_matrix(sim) G = nx.relabel_nodes(G, dict(zip(range(len(G.nodes())),media))) G = nx.to_agraph(G) G.node_attr.update(shape="plaintext",width=.5) G.graph_attr.update(splines=None,overlap="scale") G.draw('out.png', format='png', prog='neato',args='-Gepsilon=0.001')
def drawPlot(self): a = nx.to_agraph(self.g) self.g = nx.from_agraph(a) self.fig = pylab.figure() nx.draw_graphviz(self.g, prog='neato') plt.savefig("path.png") self.image.set_from_file("path.png")
def get_hacked_pos(netx_graph, name_nodes=None, prog='dot'): import pygraphviz import networkx as netx # Add "invisible" edges to induce an ordering # Hack for layout (ordering of top level nodes) netx_graph2 = netx_graph.copy() if getattr(netx_graph, 'ttype2_cpds', None) is not None: grouped_nodes = [] for ttype in netx_graph.ttype2_cpds.keys(): ttype_cpds = netx_graph.ttype2_cpds[ttype] # use defined ordering ttype_nodes = ut.list_getattr(ttype_cpds, 'variable') # ttype_nodes = sorted(ttype_nodes) invis_edges = list(ut.itertwo(ttype_nodes)) netx_graph2.add_edges_from(invis_edges) grouped_nodes.append(ttype_nodes) A = netx.to_agraph(netx_graph2) for nodes in grouped_nodes: A.add_subgraph(nodes, rank='same') else: A = netx.to_agraph(netx_graph2) # if name_nodes is not None: # #netx.set_node_attributes(netx_graph, name='label', values={n: {'label': n} for n in all_nodes}) # invis_edges = list(ut.itertwo(name_nodes)) # netx_graph2.add_edges_from(invis_edges) # A.add_subgraph(name_nodes, rank='same') # else: # A = netx.to_agraph(netx_graph2) args = '' G = netx_graph A.layout(prog=prog, args=args) # A.draw('example.png', prog='dot') node_pos = {} for n in G: node_ = pygraphviz.Node(A, n) try: xx, yy = node_.attr['pos'].split(',') node_pos[n] = (float(xx), float(yy)) except Exception: logger.info('no position for node', n) node_pos[n] = (0.0, 0.0) return node_pos
def show_graph(self, fn, graph=None, eflag=False): if graph is None: graph = self.graph if eflag: graph = graph_no_orphan(graph) rgraph = self.relabel_graph(graph) g = nx.to_agraph(rgraph) g.draw(fn, prog='circo') print ">", fn
def show_graph(self, fn, graph = None, eflag = False): if graph is None: graph = self.graph if eflag: graph = graph_no_orphan(graph) rgraph = self.relabel_graph(graph) g = nx.to_agraph(rgraph) g.draw(fn, prog='circo') print ">", fn
def draw_graphviz(self, path, layout_prog="dot"): #TODO:WAIT # Suppress warning of using os.popen3 due to old pygraphviz A = nx.to_agraph(self.g) A.layout("dot") # Setting nodes attributes for n in A.nodes(): if n[0] == 'f': n.attr["shape"] = "box" # following shape will increase rending effort # n.attr["style"] = "rounded,filled" n.attr["style"] = "filled" n.attr["color"] = "sienna1" elif n[0] == 'p': n.attr["shape"] = "ellipse" n.attr["color"] = "powderblue" n.attr["style"] = "filled" try: n.attr["label"] = str(self.paras["labels"][n]) except KeyError: pass for e in A.edges(): attr = self.g.get_edge_data(e[0], e[1]) # graphviz add a head by default # clear default head first, otherwise it will confuse # read-only path e.attr["arrowhead"] = "none" if attr.has_key("write"): e.attr["arrowhead"] = "normal" if attr.has_key("read"): e.attr["arrowhead"] = "onormal" if attr.has_key("creat") and not attr.has_key("write"): e.attr["arrowhead"] = "onormal" if attr.has_key("fork"): e.attr["style"] = "dotted" e.attr["arrowhead"] = "dot" # Draw dot file for further usage and user convenience fprefix, fsuffix = path.rsplit('.', 1) dotfile = "%s.dot" % fprefix A.draw(dotfile) #TODO:WAIT # draw() of graphviz generates mis-calculated box size # A.draw(path) # Directly call "dot" program as a workaround import subprocess cmd = ["%s" % layout_prog, "-T%s" % fsuffix, dotfile, "-o%s" % path] res = subprocess.call(cmd, shell=False) # Hacking svg file # Depends on who wrote svg files if fsuffix.lower() == "svg": self.mark_workflow_svg(path)
def graph_to_graphviz(G, labels=False): A = nx.to_agraph(nx.Graph()) if labels: format_graphviz_labels(A) else: format_graphviz(A) for n1, n2, data in G.edges_iter(data=True): A.add_edge(n1, n2, style="setlinewidth(1)", color=get_color(data['weight'], "green"), arrowsize=0.0) return A
def get_hacked_pos(netx_graph, name_nodes=None, prog='dot'): import pygraphviz import networkx as netx # Add "invisible" edges to induce an ordering # Hack for layout (ordering of top level nodes) netx_graph2 = netx_graph.copy() if getattr(netx_graph, 'ttype2_cpds', None) is not None: grouped_nodes = [] for ttype in netx_graph.ttype2_cpds.keys(): ttype_cpds = netx_graph.ttype2_cpds[ttype] # use defined ordering ttype_nodes = ut.list_getattr(ttype_cpds, 'variable') # ttype_nodes = sorted(ttype_nodes) invis_edges = list(ut.itertwo(ttype_nodes)) netx_graph2.add_edges_from(invis_edges) grouped_nodes.append(ttype_nodes) A = netx.to_agraph(netx_graph2) for nodes in grouped_nodes: A.add_subgraph(nodes, rank='same') else: A = netx.to_agraph(netx_graph2) #if name_nodes is not None: # #netx.set_node_attributes(netx_graph, 'label', {n: {'label': n} for n in all_nodes}) # invis_edges = list(ut.itertwo(name_nodes)) # netx_graph2.add_edges_from(invis_edges) # A.add_subgraph(name_nodes, rank='same') #else: # A = netx.to_agraph(netx_graph2) args = '' G = netx_graph A.layout(prog=prog, args=args) #A.draw('example.png', prog='dot') node_pos = {} for n in G: node_ = pygraphviz.Node(A, n) try: xx, yy = node_.attr["pos"].split(',') node_pos[n] = (float(xx), float(yy)) except: print("no position for node", n) node_pos[n] = (0.0, 0.0) return node_pos
def main(): # set up seaborn plotting environment sns.set_style("white") #{'axes.linewidth': 5.0}) sns.color_palette("hls", 6) print "starting parsing" dataFile = "data/Nov09JnyExport.csv" journeys = parseData(dataFile) for startStation in sorted(journeys.keys()): print "%s: %s" % (startStation, len(journeys[startStation])) print len(journeys.keys()) plotHistogram(journeys) G = plotNetwork(journeys) G2 = nx.DiGraph() for (u, v) in G.edges(): w = G[u][v]['weight'] if w > 300: G2.add_edge(u, v, weight=w) for k, v, a in G2.edges(data=True): print k, v, a['weight'] pos=nx.to_agraph(G2) pos.graph_attr['size']='10,10!' pos.graph_attr['ratio']='fill' pos.layout(prog='neato') pos.draw("hairyballs.png") for startStation, journeyList in journeys.iteritems(): Gs= plotDestinations(journeyList, startStation) Gme = nx.MultiDiGraph() if len(list(Gs.edges())) > 10: for (u, v) in Gs.edges(): w = Gs[u][v]['weight'] for i in range(int(ma.ceil(w / 50)) + 1): Gme.add_edge(u, v) pos=nx.to_agraph(Gme) #pos.graph_attr['size']='10,10!' #pos.graph_attr['ratio']='fill' pos.graph_attr['repulsiveforce'] = 5 pos.graph_attr['K'] = 1.5 pos.layout(prog='fdp') pos.draw("hairyballs_%s.png" % startStation)
def main(): # set up seaborn plotting environment sns.set_style("white") #{'axes.linewidth': 5.0}) sns.color_palette("hls", 6) print "starting parsing" dataFile = "data/Nov09JnyExport.csv" journeys = parseData(dataFile) for startStation in sorted(journeys.keys()): print "%s: %s" % (startStation, len(journeys[startStation])) print len(journeys.keys()) plotHistogram(journeys) G = plotNetwork(journeys) G2 = nx.DiGraph() for (u, v) in G.edges(): w = G[u][v]['weight'] if w > 300: G2.add_edge(u, v, weight=w) for k, v, a in G2.edges(data=True): print k, v, a['weight'] pos = nx.to_agraph(G2) pos.graph_attr['size'] = '10,10!' pos.graph_attr['ratio'] = 'fill' pos.layout(prog='neato') pos.draw("hairyballs.png") for startStation, journeyList in journeys.iteritems(): Gs = plotDestinations(journeyList, startStation) Gme = nx.MultiDiGraph() if len(list(Gs.edges())) > 10: for (u, v) in Gs.edges(): w = Gs[u][v]['weight'] for i in range(int(ma.ceil(w / 50)) + 1): Gme.add_edge(u, v) pos = nx.to_agraph(Gme) #pos.graph_attr['size']='10,10!' #pos.graph_attr['ratio']='fill' pos.graph_attr['repulsiveforce'] = 5 pos.graph_attr['K'] = 1.5 pos.layout(prog='fdp') pos.draw("hairyballs_%s.png" % startStation)
def drawGraph(G,words,layout): A = nx.to_agraph(G) for n in A.nodes(): if str(n).lower() in words: n.attr['color']='green' A.layout(layout, args='-Nfontsize=10 -Nwidth=".2" -Nheight=".2" -Nmargin=0 -Gfontsize=8') A.draw('graph_'+str(layout)+'.png')
def print_graph(self,filename): graph = nx.to_agraph(self.molecular_graph) for n in graph.nodes(): try: colour = graph_colours[self.get_atom(n)].type except: colour = 'black' graph.get_node(n).attr['color'] = colour graph.layout() graph.draw('{0}.png'.format(filename))
def render(self, filepath, format="svg", prog="dot", attributes={}): """Renders the tree into the file at `filepath`. `filepath` may also be a File-like object.""" agraph = nx.to_agraph(self) for key, value in attributes.iteritems(): agraph.node_attr[key] = value agraph.draw(filepath, format=format, prog=prog)
def draw(self, file_name='pipeline.png'): if not self.nx: self.validate() try: agr = nx.to_agraph(self.nx) except ImportError: log.error('Failed to import pygraphviz, cannot draw.') return agr.layout() agr.draw(file_name if file_name.endswith('png') else file_name+'.png')
def print_graph(self, filename): graph = nx.to_agraph(self.molecular_graph) for n in graph.nodes(): try: colour = graph_colours[self.get_atom(n)].type except: colour = 'black' graph.get_node(n).attr['color'] = colour graph.layout() graph.draw('{0}.png'.format(filename))
def statePlot(self, bucketwidth, offsets, filename='state.dot', display=True): ''' bucketwidth is the number of bytes in each section of the packet. Offset selects which section is of interest. The result of this function is a graph where the nodes are packet states and the directed arcs show numbered transitions between states. Beware, if there are a large number of states and indices the graph will likely be indecipherable if it even generates. Choose the values wisely. In future this will be more useful, based on multiple lengths using a scapy dissection definition. For now a spec for byte samples and offsets is all you get. Tools will be included to look at bit patterns in order to determine the existence and properties of individual flags. However, at this stage, that should be both trivial and irrelevant.''' statesamples = Samples(self, bucketwidth * (np.array(offsets).max() + 1), bucketwidth) valuesetlist = [] valueslist = [] for o in offsets: valueset = statesamples.asHexSet(o) print valueset valuesetlist.append(valueset) valueslist.append(statesamples.asHex(o)) nodelist = [n for n in it.product(*valuesetlist)] G = nx.MultiDiGraph() G.add_nodes_from(nodelist) for i in range(len(valueslist[0]) - 1): nodetuple = [] for j in range(len(offsets)): nodetuple.append(valueslist[j][i]) thisnodetuple = tuple(nodetuple) nodetuple = [] for j in range(len(offsets)): nodetuple.append(valueslist[j][i + 1]) nextnodetuple = tuple(nodetuple) # before adding edge, color according to local or remote origin if self.pktlist[i][UDP].sport == self.lport: edgecolour = 'green' if self.pktlist[i][UDP].sport == self.rport: edgecolour = 'blue' G.add_edge(thisnodetuple, nextnodetuple, label=i, color=edgecolour) # clean out unused states from graph for n in G.nodes(): if G.neighbors(n) == []: G.remove_node(n) GA = nx.to_agraph(G) GA.edge_attr['penwidth'] = 3.0 GA.layout() GA.write(filename) if display: Popen(['xdot', filename]) return
def xlang_main(args): """ Disagreement graphs for aligned cross-language language. """ src_amr_fh = codecs.open(args.src_amr, encoding='utf8') tgt_amr_fh = codecs.open(args.tgt_amr, encoding='utf8') gold_aligned_fh = None if args.align_in: gold_aligned_fh = codecs.open(args.align_in, encoding='utf8') (json_fh, align_fh) = open_output_files(args) amrs_same_sent = [] aligner = Amr2AmrAligner(num_best=args.num_align_read, num_best_in_file=args.num_aligned_in_file) while True: (src_amr_line, src_comments) = amr_metadata.get_amr_line(src_amr_fh) if src_amr_line == "": break (tgt_amr_line, tgt_comments) = amr_metadata.get_amr_line(tgt_amr_fh) src_amr = amr_metadata.AmrMeta.from_parse(src_amr_line, src_comments, xlang=True) tgt_amr = amr_metadata.AmrMeta.from_parse(tgt_amr_line, tgt_comments, xlang=True) (cur_id, src_sent) = get_sent_info(src_amr.metadata) (tgt_id, tgt_sent) = get_sent_info(tgt_amr.metadata, dflt_id=cur_id) assert cur_id == tgt_id (amr_graphs, smatchgraphs) = hilight_disagreement([tgt_amr], src_amr, args.num_restarts, aligner=aligner, gold_aligned_fh=gold_aligned_fh) if json_fh: json_fh.write(json.dumps(amr_graphs[0]) + '\n') if align_fh: align_fh.write("""# ::id %s\n# ::src_snt %s\n# ::tgt_snt %s\n""" % (cur_id, src_sent, tgt_sent)) align_fh.write('\n'.join(smatchgraphs[0].get_text_alignments()) + '\n\n') if (args.verbose): print("ID: %s\n Sentence: %s\n Sentence: %s\n Score: %f" % (cur_id, src_sent, tgt_sent, amr_graphs[0][1])) #raw_input("Press enter to continue: ") ag = nx.to_agraph(amr_graphs[0][0]) ag.graph_attr['label'] = "%s\n%s" % (src_sent, tgt_sent) ag.layout(prog=args.layout) ag.draw('%s/%s.png' % (args.outdir, cur_id)) src_amr_fh.close() tgt_amr_fh.close() gold_aligned_fh and gold_aligned_fh.close() close_output_files(json_fh, align_fh)
def draw(self, file_name='pipeline.png'): if not self.nx: self.validate() try: agr = nx.to_agraph(self.nx) except ImportError: log.error('Failed to import pygraphviz, cannot draw.') return agr.layout() agr.draw(file_name if file_name.endswith('png') else file_name + '.png')
def draw_bird_taxonomy(filename, graph=None): """Draws the bird taxonomy. If graph is None, the code loads the data from the json file. """ import pygraphviz as pgv if graph is None: graph = get_bird_taxonomy() agraph = nx.to_agraph(graph) agraph.graph_attr['rankdir'] = 'LR' agraph.layout('dot') agraph.draw(filename)
def dot_string(self): self._prepare_draw(resolveDynamic=True) #import StringIO #stringBuffer = StringIO.StringIO() A = nx.to_agraph(self._G) #nx.write_dot(self._G, stringBuffer) #return stringBuffer.getvalue() return A.to_string()
def caseset_query_to_html(query, filename='cases.html'): # get case data as serialized json string q_str = StringIO.StringIO() query.write(q_str) case_data = q_str.getvalue() json_data = json.loads(case_data) # get dependency graph from case data and render it to SVG graph = json_data['simulation_info']['graph'] G = nx.readwrite.json_graph.loads(graph) agraph = nx.to_agraph(G) svg_dep_graph = agraph.draw(format='svg', prog='dot') # get component graph from case data and render it to SVG if 'comp_graph' in json_data['simulation_info'].keys(): graph = json_data['simulation_info']['comp_graph'] G = nx.readwrite.json_graph.loads(graph) agraph = nx.to_agraph(G) svg_comp_graph = agraph.draw(format='svg', prog='dot') else: # old case data file may not have comp_graph svg_comp_graph = '<svg></svg>' # Setup Jinja2 templating cds_visualizer_dir_path = os.path.join(os.path.dirname(__file__), 'visual_post_processing') env = Environment(loader=FileSystemLoader(cds_visualizer_dir_path)) template = env.get_template('case_dataset_visualizer.html') if os.path.isfile(filename): os.remove(filename) # use the existing template to write out the html file outputText = template.render( case_data=case_data, svg_dep_graph=svg_dep_graph, svg_comp_graph=svg_comp_graph ) with open(filename, "wb") as fh: fh.write(outputText)
def save_plot(graph, name="graph.png"): """save plot with index numbers rather than timing""" edges = graph.edges(data=True) nodes = [edge[2]['source'] for edge in edges] order = np.argsort(nodes) edges = [edges[i] for i in order.tolist()] new_edges = [] for edge in edges: v = edge[2]['target'] - edge[2]['source'] - 1 new_edges.append((edge[2]['source'], edge[2]['target'])) DG = nx.DiGraph() DG.add_edges_from(new_edges) A = nx.to_agraph(DG) A.layout() A.draw(name)
def draw(self, outfile=None, matplotlib=True, notebook=False): agraph = nx.to_agraph(self) agraph.has_layout = self.has_layout if outfile is None: pngstr = self._get_agraph_pngstr(agraph) if matplotlib and not notebook: import matplotlib.pyplot as plt import matplotlib.image as mpimg plt.imshow(mpimg.imread(pngstr), aspect='equal') plt.axis('off') if notebook: from IPython.display import Image, display display(Image(data=pngstr)) else: agraph.draw(outfile)
def to_abigraph(self, styles, type=None, max_label=4, name2URL=None): """ Converts graph to the graphvis format """ graph = self.clone(type) mgraph = BrownieCallBiGraph(styles, max_label=max_label, name2URL=name2URL) for classCaller, classCallee, attribs in graph.edges_iter(data=True): if attribs['type'] == 'inheritance': mgraph.add_inheritance(classCaller, classCallee) elif attribs['type'] == 'brownie': mgraph.add_calls(classCaller, classCallee, graph[classCaller][classCallee]['call'] | \ graph[classCaller][classCallee]['notification']) from networkx import to_agraph return to_agraph(mgraph)
def render_graph(request, graph_id, subgraph_id): import pygraphviz as P import networkx as N graph = Graph.objects.get(pk=graph_id) dot_path = graph.dot_file.storage.location + '/' + graph.dot_file.name G = P.AGraph() # init empty graph try: G.read(dot_path) #read file NG = N.Graph(G) #pyGraphViz to networkX; full graph except: pass if subgraph_id <> '0': #render subgraph svg SG = N.Graph() #subgraph networkX nodes = Node.objects.filter(subgraph__id=subgraph_id) #nodes in db for node in nodes: new_node = NG.node['name'] = node.name SG.add_node(new_node) nodes = SG.nodes() edges = shortest_path_rec(NG, nodes, 0) SG.add_edges_from(edges) NSG = N.Graph() nodes = Node.objects.filter(graph__id=graph_id) for node in nodes: if SG.has_node(node.name): NSG.add_node(node.name, label=node.label, color='red') NSG.add_edges_from(edges, color='red') NG = N.Graph(G) FG = N.compose(NSG, NG) FG.name = 'test' FG = N.to_agraph(FG) #NEW_GRAPH = funcao de colorir(AGraph(), AGraph.edges()):retorna AGraph() #SG = N.to_agraph(NSG) #NG.graph.update(NSG.graph) #NG.name = 'test' #FG = N.to_agraph(NG) FG.layout(prog='dot') #dot language graphView = FG.draw(format='svg') # draw svg else: G.layout(prog='dot') #dot language graphView = G.draw(format='svg') # draw svg return HttpResponse(graphView, mimetype='image/svg+xml') #response
def draw(self, filename=None, transition_labels=False): """ TODO: draw initial state """ A = networkx.to_agraph(self) if filename is None: output = util.file_in_temp('temp.png') seen_edges = {} for source, target, attributes in self.edges(data=True): channel = attributes['channel'] channel_expression = attributes['channel_expression'] guard = attributes['guard'] update = attributes['update'] label = None if channel in self.input_channels: label = '{}?'.format(channel) elif channel in self.output_channels: if channel.sort() == util.UNIT_SORT: label = '{}!'.format(channel) else: label = '{}({})!'.format(channel, channel_expression) if not z3p.is_true(guard): if label: label += '\n{}'.format(guard) else: label = '{}'.format(guard) if update: if label: label += '\n{}'.format(update) else: label = '{}'.format(update) if transition_labels: label = attributes['name'] + ':' + label if (source, target) not in seen_edges: key = 0 seen_edges[(source, target)] = 1 else: key = seen_edges[(source, target)] seen_edges[(source, target)] += 1 A.get_edge(source, target, key).attr['label'] = label A.layout(prog='dot') A.draw(output, format='png') output.close()
def output_graph(graph, output_dir, only_predicted): subgraphs = nx.connected_component_subgraphs(graph) for comp_id, subgr in enumerate(subgraphs): if len(subgr) == 2: continue if only_predicted: to_show = False for v1, v2, data in subgr.edges_iter(data=True): if data.get("style") == "dashed": to_show = True break if not to_show: continue comp_file = os.path.join(output_dir, "comp{0}-bg.png".format(comp_id)) agraph = nx.to_agraph(subgr) agraph.layout(prog="dot") agraph.draw(comp_file)
def draw_graph(graph, name, horizontal=False): """ Draws a graph to file with label and filename taken from name argument. Note: Graphviz binaries cannot be easily installed on Windows (you must build it from source), therefore you shouldn't bother trying to draw_graph unless you've done so! :param graph: Dependency graph to draw :type graph: nx.DiGraph :param name: Name of graph being drawn. Added to filename: graph_[name].ps :type name: String :param horizontal: Draw graph from left to right. Default: False (top to bottom) :type horizontal: Boolean """ # hint: change filename extension to change type (.png .pdf .ps) file_path = 'graph_%s.ps' % name.lower().replace(' ', '_') # TODO: Set the number of pages #page="8.5,11"; # Trying to get matplotlib to install nicely # Warning: pyplot does not render the graphs well! ##import matplotlib.pyplot as plt ##nx.draw(graph) ##plt.show() ##plt.savefig(file_path) try: ##import pygraphviz as pgv # sudo apt-get install graphviz libgraphviz-dev # pip install pygraphviz #Note: nx.to_agraph performs pygraphviz import if horizontal: # set layout left to right before converting all nodes to new format graph.graph['graph'] = {'rankdir': 'LR'} G = nx.to_agraph(graph) except ImportError: logger.exception("Unable to import pygraphviz to draw graph '%s'", name) return G.layout(prog='dot') G.graph_attr['label'] = name G.draw(file_path) logger.info("Dependency tree drawn: %s", os.path.abspath(file_path))
def saveGraph(S, name): filename = name + '.png' path = os.path.join(cfg['outputdir'], filename) thumbSize = (200, 200) thumbFilename = name + '_thumb' + '.png' thumbPath = os.path.join(cfg['outputdir'], thumbFilename) # Drawing of the subgraph T = nx.to_agraph(S) T.node_attr['labelfontsize'] = '18.0' T.node_attr['style'] = 'filled' T.node_attr['color'] = '#000000' T.node_attr['fillcolor'] = '#ffffff' T.edge_attr['color'] = '#6A6A8D' T.edge_attr['fontsize'] = '10.0' T.edge_attr['fontcolor'] = '#6A6A8D' T.edge_attr['len'] = '5.0' oid = cfg['objecttag'] sid = cfg['subjecttag'] if T.has_node(oid): T.get_node(oid).attr['fillcolor'] = '#B4CDCD' T.get_node(oid).attr['shape'] = 'egg' if T.has_node(sid): T.get_node(sid).attr['fillcolor'] = '#B4CDCD' T.get_node(sid).attr['shape'] = 'egg' T.layout(prog='dot') T.draw(path) im = Image.open(path) im.thumbnail(thumbSize) im.save("%s" % thumbPath)
def main(): # 1.0 Data on the expansion of network data sizes over time d = [("Sampson\n(1975)", 18), ("Zachary\n(1977)", 34), ("Neural nets\n(1986)", 296), ("Power grid\n(1998)", 4940), ("Actor collaboration\n(1999)", 212250), ("Twitter scrape\n(2008)", 2700000)] bar_plot_1(d) # 2.0 Create NetowrkX objects with time-series data g1 = time_series(100, .25) nx.write_edgelist(g1, '../../data/time_series.txt', data=True) # 3.0 Load Sampson monastery data and output as DOT g2 = nx.read_edgelist("../../data/samp_like_el.txt", delimiter="\t", create_using=nx.DiGraph()) nx.info(g2) # Convert to pygraphviz type g2_gv = nx.to_agraph(g2) # Output DOT file and draw using dot layout g2_gv.write("../../data/samp_like_dot.dot") g2_gv.draw('../../images/networks/samp_like.png', prog='dot')
def agraph_checks(self, G): G = self.build_graph(G) A = nx.to_agraph(G) H = nx.from_agraph(A) self.assert_equal(G, H) fname = tempfile.mktemp() nx.drawing.nx_agraph.write_dot(H, fname) Hin = nx.drawing.nx_agraph.read_dot(fname) os.unlink(fname) self.assert_equal(H, Hin) (fd, fname) = tempfile.mkstemp() fh = open(fname, 'w') nx.drawing.nx_agraph.write_dot(H, fh) fh.close() fh = open(fname, 'r') Hin = nx.drawing.nx_agraph.read_dot(fh) fh.close() os.unlink(fname) self.assert_equal(H, Hin)
def to_abigraph(self, uml_diag, styles=default_styles, type=None, max_label=4, name2URL=None): """ Converts graph to the graphvis format """ graph = UMLAGraph( uml_diag, styles, # name2URL = name2URL, max_label = max_label, ) # for classCaller, classCallee, attribs in graph.edges_iter(data=True): # if attribs['type'] == 'inheritance': mgraph.add_inheritance(classCaller, classCallee) # elif attribs['type'] == 'brownie' : # mgraph.add_calls(classCaller, classCallee, # graph[classCaller][classCallee]['call'] | \ # graph[classCaller][classCallee]['notification']) from networkx import to_agraph return to_agraph(graph)