def main(): if len(sys.argv) < 4: print('Usage:') print('python graphmaker.py [<input> Newick tree file] [<input> cutoff] [<output> DOT file]') treefile = sys.argv[1] cutoff = sys.argv[2] dotfile = sys.argv[3] try: cutoff = float(cutoff) except: print('ERROR: expecting a float value for [cutoff]') sys.exit() try: tree = Phylo.read(treefile, 'newick') except: print('ERROR: tree must be in Newick format') sys.exit() GM = GraphMaker(tree) edges = GM.cluster(cutoff) # generate networkx object g = nx.Graph() for tip1, neighbours in edges.iteritems(): for tip2, dist in neighbours.iteritems(): g.add_edge(tip1, tip2, dist=dist) # each cluster can be examined using networkx functions; for example, # clusters = nx.connected_components(g) # export as GraphViz file nx.write_dot(g, dotfile)
def main( size, **args ): network = create_transition_graph( size ) # Add interaction and return the matrix assert args['pUp'] > 0.0 assert args['pDown'] > 0.0 T = add_interaction( network , args['pUp'] , args['pDown'] , args.get('excitation', 0.0) , args.get('inhibition', 0.0) ) print( "Running with parameters : %s" % args ) if args.get('plot', False): transitionMatFile = 'transition_matrix_%d.csv' % size np.savetxt( transitionMatFile, T ) matImgFile = 'transition_mat_%04d.png' % size plt.figure() # create a binary image out of T. tImg = np.copy(T) tImg[ np.where( tImg != 0 ) ] = 1.0 plt.figure( ) plt.imshow( tImg, interpolation = 'none' ) plt.title( 'Transition matrix. Zero and non-zero entries' ) # plt.colorbar( ) plt.savefig( matImgFile ) plt.close( ) dotFile = 'network_%d.dot' % size nx.write_dot( network, dotFile ) print( '[INFO] Graph is written to dot file %s' % dotFile ) # subprocess.call( [ "neato", "-Tpng", dotFile, "-O" ] ) # Once I have the transition matrix, I now use markov module to solve it. s = markov.MarkovChain( T ) ss = s.find_steady_state( method = args['method'] ) return get_effects( ss, size )
def visualize(event, outputname): import networkx as nx import pypdt import tex2pix import subprocess g = nx.DiGraph() for i, p in enumerate(event.particles): g.add_node(i, attr_dict=p.__dict__) name = pypdt.particle(p.id).name greek = [ 'gamma', 'nu', 'mu', 'tau', 'rho', 'Xi', 'Sigma', 'Lambda', 'omega', 'Omega', 'Alpha', 'psi', 'phi', 'pi', 'chi' ] for greekname in greek: if greekname in name: name = name.replace(greekname, '\\' + greekname) if 'susy-' in name: name = name.replace('susy-', '\\tilde ') g.node[i].update(texlbl="${}$".format(name)) for i, p in enumerate(event.particles): for mom in p.mothers(): g.add_edge(event.particles.index(mom), i) nx.write_dot(g, 'event.dot') p = subprocess.Popen(['dot2tex', 'event.dot'], stdout=subprocess.PIPE) tex2pix.Renderer(texfile=p.stdout).mkpdf(outputname) subprocess.check_call(['pdfcrop', outputname, outputname]) # shutil.move('event-cropped.pdf','event.pdf') os.remove('event.dot')
def to_dot_file(self, filename): '''把图写入到dot文件中,不对原图做什么改变 新图的节点只是字符串。 ''' new_graph = nx.DiGraph() for start, end, data in self.edges_iter(data = True): port_pair = data['port_pair'] connection = data['connection'] edge = [start, end] # 存储边的起点和终点 node_id =['',''] # 存储节点的名称 node_data =[{},{}] # 存储要打印到dot中的信息 for i in range(2): # 当前节点是prim 或者是 port is_prim = True if isinstance(edge[i], cc.circut_module) else False # prim和port的数据属性不同,根据判断为生成dot节点的名称,和节点附属的['shape']数据 node_name = '_d_'+edge[i].name[1:] if edge[i].name[0]=='\\' else edge[i].name node_id[i] = edge[i].cellref+node_name if is_prim else\ edge[i].port_type+node_name # prim为box形状(盒子),port为invtriangle形状(倒三角) node_data[i]['shape'] = 'box' if is_prim else 'invtriangle' new_graph.add_node(node_id[i],node_data[i]) new_graph.add_edge(node_id[0], node_id[1]) try: nx.write_dot(new_graph, filename) except Exception, e: print "Warning: Cannot write dot file", e
def testDot(self): self.assertEqual( self.g.number_of_edges(), 4 ) self.assertEqual( self.g.number_of_edges(), 4 ) nx.write_dot( self.g, './test.dot' ) g1 = nx.read_dot( './test.dot' ) self.assertEqual( g1.number_of_edges(), self.g.number_of_edges() ) self.assertEqual( g1.number_of_edges(), 4 )
def debug_mro_failure(name, bases): graph = build_linearization_graph(name, bases) cycles = sorted(nx.cycles.simple_cycles(graph), key=len) cycle = cycles[0] if os.environ.get('DRAW_MRO_FAILURES'): output_file = name + '.dot' else: output_file = None # Return a nicely formatted error describing the cycle. lines = ["Cycle found when trying to compute MRO for {}:\n".format(name)] for source, dest in list(zip(cycle, cycle[1:])) + [(cycle[-1], cycle[0])]: label = verbosify_label(graph.get_edge_data(source, dest)['label']) lines.append("{} comes before {}: cause={}".format( source, dest, label)) # Either graphviz graph and tell the user where it went, or tell people how # to enable that feature. lines.append('') if output_file is None: lines.append("Set the DRAW_MRO_FAILURES environment variable to" " render a GraphViz graph of this cycle.") else: try: nx.write_dot(graph.subgraph(cycle), output_file) subprocess.check_call(['dot', '-T', 'svg', '-O', output_file]) lines.append("GraphViz rendering written to " + output_file + '.svg') except Exception as e: lines.append( "Failed to write GraphViz graph. Error was {}".format(e)) return '\n'.join(lines)
def optimal_substemma(inputfile, w1, suffix=''): """ Create an image for the optimal substemma of a particular witness. """ output_file = 'optimal_substemma_{}{}.svg'.format(w1, suffix) populate_db.populate(inputfile, DEFAULT_DB_FILE, force=True) optsub = load(inputfile) comb_anc = optsub[w1] print("{}: {}".format(w1, comb_anc)) if len(comb_anc) > 1: raise ValueError("Can't draw a single optimal substemma") nodes, edges = nodes_and_edges(w1, comb_anc[0], optsub) G = networkx.DiGraph() G.add_nodes_from(nodes) for pri, post in edges: G.add_edge(pri, post) print("Creating graph with {} nodes and {} edges".format(G.number_of_nodes(), G.number_of_edges())) with NamedTemporaryFile() as dotfile: networkx.write_dot(G, dotfile.name) subprocess.check_call(['dot', '-Tsvg', dotfile.name, '-o', output_file]) print("Written diagram to {}".format(output_file))
def test(): # A() | B() | C() # A() & B() | C() # A() | (B() & C()) # ((A() & B()) | C()) & (D() | F()) (A() | B() | C()) & (D() | F()) H, N, E = clean(G) evaluate(G) # O = Graph() # order = nx.topological_sort(H) # s = order[0] # O.add_node(s, label=G.node[s]['label']) # for t in order[1:]: # O.add_node(t, label=G.node[t]['label']) # O.add_edge(s, t) # s = t # p = nx.spring_layout(H) # nx.draw_networkx(H, p, with_labels=False) # nx.draw_networkx_labels(H, p, N) # nx.draw_networkx_edge_labels(H, p, edge_labels=E) # import matplotlib.pyplot as plt # plt.savefig('/tmp/test.png') nx.write_dot(H, '/tmp/test.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 plot_call_graph(self, g): for n, d in g.nodes(data=True): d["label"] = "{} {} {} ({})".format(n, d["_name"], d["_self_coverage"], d["_coverage"]) if not d["_valid"] or d["_small"]: d["style"] = "dotted" else: d["style"] = "solid" if d["_tested"]: d["style"] = "solid" if not d["_matching"]: d["color"] = "red" else: d["color"] = "green" if d["_to_test"]: d["color"] = "orange" if d["_name"] == self._name: d["style"] = "filled" nx.write_dot(g, "{0}/graph_{1}.dot".format(var.CERE_PLOTS_PATH, self._name)) try: subprocess.check_output( "dot -Tpng {0}/graph_{1}.dot -o {0}/graph_{1}.png".format(var.CERE_PLOTS_PATH, self._name), stderr=subprocess.STDOUT, shell=True, ) except subprocess.CalledProcessError as err: logger.error(str(err)) logger.error(err.output) logger.warning("Can't create call graph fo region {0}".format(self._name))
def graph(start_with, end_with, details): g = signals.detailed_connection_graph(start_with=start_with, end_with=end_with, details=details) nx.write_dot(g, 'graph.dot') fabric_api.local('dot -Tsvg graph.dot -o graph.svg')
def write_color_dot_file(G, color_att=None, del_atts=None, dot_file='dot_graph.dot', node_color=None, color_seq=None, val_seq=None, label=True): if del_atts is None: del_atts = [] if node_color is None: color_dict = assign_colors(G, color_att, color_seq, val_seq, integers_ok=False) else: assert color_att is None, 'Please do not specify a color attribute and a single node color at the same time' for (n, ndict) in G.node.items(): ndict['style'] = 'filled' if node_color: ndict['fillcolor'] = node_color else: ndict['fillcolor'] = color_dict[ndict[color_att]] if not label: ndict['label'] = '""' for del_att in del_atts: try: del ndict[del_att] except KeyError: continue nx.write_dot(G, dot_file)
def traceroute_plot_from_db(targets): '''Assumes that if a target is in the db then the traceroute has already been run The targets input is a list of dictionaries from the db instead of IPs only. ''' g=nx.Graph() source=socket.gethostbyname(socket.gethostname()) for t in targets: hops=t['traceroute'] print hops g.add_node(t['ip']) g.add_edge(source,hops[0]) if len(hops) >= 1: for hop in hops: next_hop_index=hops.index(hop)+1 if next_hop_index != len(hops): g.add_edge(hop,hops[next_hop_index]) else: g.add_edge(hop,t['ip']) nx.draw(g,with_labels=False) plt.savefig("/Users/runseb/Desktop/481_f2011/trace.png") nx.write_dot(g,"/Users/runseb/Desktop/481_f2011/trace.dot")
def traceroute_plot(targets): '''Plots the graph of the traceroutes for a list of IP targets Calls the scapytraceroute. ''' g=nx.Graph() source=socket.gethostbyname(socket.gethostname()) for t in targets: hops=scapytraceroute(t) print hops g.add_node(t) g.add_edge(source,hops[0]) if len(hops) >= 1: for hop in hops: next_hop_index=hops.index(hop)+1 if next_hop_index != len(hops): g.add_edge(hop,hops[next_hop_index]) else: g.add_edge(hop,t) nx.draw(g,with_labels=False) plt.savefig("/Users/runseb/Desktop/481_f2011/trace.png") nx.write_dot(g,"/Users/runseb/Desktop/481_f2011/trace.dot")
def graph(end_with, start_with): #g = xs.connection_graph() g = signals.detailed_connection_graph(start_with=start_with, end_with=end_with) nx.write_dot(g, 'graph.dot') fabric_api.local('dot -Tpng graph.dot -o graph.png')
def write_dot(self, filename): """docstring for write_dot""" try: nx.write_dot(self._nx_graph, filename) except Exception, e: print e raise e
def create_phylo_tree(fname, save=False, dotfile='philo.dot', xover=False, prune=False): colors = ['chartreuse', 'chocolate', 'cadetblue', 'cornflowerblue', 'cyan', 'darkorange', 'darkviolet', 'deeppink'] #TODO check how to define hexadecimal colors for GraphViz colorsH = ["#7FFF00", "#D2691E", "#5F9EA0", "#6495ED", "#00FFFF", "#FF8C00", "#9400D3", "#F1493"] # create a graph G=nx.MultiDiGraph() # fill the lists with all the genes gl = process_file(fname) # create the phylo-tree for n in gl.keys(): G.add_node(n) # the root node (the initial genome) G.node[n]['agent'] = n G.node[n]['id'] = n G.node[n]['color'] = colors[n%len(colors)] trac_genome(gl, n, G, colors) if xover: G=add_dad_links(G,gl) if prune: id_last_epoch= max(G.nodes()) - len(gl.keys()) + 1 nb_epochs= len(G.nodes())/len(gl.keys()) G=prune_tree(G,id_last_epoch,nb_epochs) # write the file if save : nx.write_dot(G, dotfile) return G
def export(self, name=None, valuation=None): tmpdir = 'tmp/' # dotpgm = 'dot' filename = tmpdir + self.automaton.graph['name'] if name: filename = tmpdir + name dotfile = filename + '.dot' # pngfile = filename + '.png' if valuation: # We now want to remove any edges that are not in the valuation for fv, tv, key, dct in self.get_transitions(keys=True): if valuation.get_var_val(dct['f_var']) == 0: self.automaton.remove_edge(fv, tv, key=key) else: fvar = str(valuation.get_var_val(dct['f_var'])) self.automaton.edge[fv][tv][key]['label'] = fvar # Now we want to remove any orphaned nodes for node, deg in self.automaton.degree().iteritems(): if deg == 0: self.automaton.remove_node(node) networkx.write_dot(self.automaton, dotfile)
def write_graph_to_dot(self, graph, file, label="", dpi=72, node_sep=None): """ Write and edit a dot file. Implements the pydot and dot_parser modules. Based on code by Anders Holden Deleuran. """ nx.write_dot(graph, file) # Get the lines in the dot file df = open(file, 'r') df_lines = df.readlines() df.close() # Add additional properties to the dot file df_lines.insert( 1, 'label="' + str(label) + '" dpi=' + str(dpi) + ' overlap=scalexy nodesep=' + str(node_sep) + ' rankdir=BT' + ';\n') df_string = ''.join(df_lines) # Open and overwrite dot file df = open(file, 'w') df.write(df_string) df.close()
def build_network(self, nodes, nodesizes, weights, outfile = 'network.dot', nodeprop=None): ''' Not working yet Nodes represents the states ''' nodes=np.array(nodes) import networkx as nx G = nx.Graph() if nodeprop is not None: for i in range(nodes.size): G.add_node(int(nodes[i]), size=int(nodesizes[i]), label=int(nodes[i]), prop=nodeprop[i]) else: for i in range(nodes.size): G.add_node(int(nodes[i]), size=int(nodesizes[i]), label=int(nodes[i])) for i in range(weights.shape[0]): w = weights[i, 2] G.add_edge(int(weights[i, 0]), int(weights[i, 1]), weight=float(w)) nx.write_dot(G, outfile) outfile1 = outfile.replace('.dot', '.gml') nx.write_gml(G, outfile1)
def test_A(): g = nx.DiGraph() g.add_nodes_from("ABCD", label='input') g.add_nodes_from("XY", label='output') g.add_nodes_from(["FF1", "FF2", "FF3", "FF4"], label=Primitives.dffkeyword) g.add_nodes_from(range(1, 8), label="comb") g.add_edge("A", 1) g.add_edges_from([("B", 1), ("B", 3)]) g.add_edge("C", 3) g.add_edge("D", 2) g.add_edge("FF1", 4) g.add_edges_from([("FF2", 5), ("FF2", 6)]) g.add_edge("FF3", 7) g.add_edge("FF4", "Y") g.add_edge(1, "FF2") g.add_edge(2, "FF1") g.add_edge(3, 4) g.add_edge(4, 6) g.add_edge(5, "FF3") g.add_edges_from([(6, 7), (6, "FF4")]) g.add_edge(7, "X") nx.write_dot(g, "bench.dot") print nx.info(g) #plt.figure("Before") #nx.draw_networkx(g) #plt.show() getSgraph(g) nx.write_dot(g, "benchSgraph.dot") print nx.info(g)
def main(): files = [] for i in range(1,26): files.append("db/Minna_no_nihongo_1.%02d.txt" % i) for i in range(26,51): files.append("db/Minna_no_nihongo_2.%02d.txt" % i) data = get_words_from_files(files) words = [w for w in data] #print words G=nx.Graph() for word1, word2 in itertools.combinations(words,2): for w1 in word1[:-1]: #print w1.encode('utf-8') #print ud.name(w1) if "CJK UNIFIED" in ud.name(w1) and w1 in word2: #print word1.encode('utf-8'), word2.encode('utf-8') G.add_edge(word1, word2) break nx.draw(G) nx.write_dot(G, "kanjis.dot") nx.write_graphml(G, "kanjis.graphml") #plt.show() words = G.nodes() with open('kanjis.json', 'w') as f: json.dump({'nodes': [{'name': i.encode('utf-8'), 'kana': data[i]['kana'], 'chapter': data[i]['chapter'], 'meaning': data[i]['meaning']} for i in G.nodes()], 'links': list(map(lambda u: {'source': words.index(u[0]), 'target': words.index(u[1])}, G.edges()))}, f, indent=2,)
def to_dot_file(self, filename): '''把图写入到dot文件中,不对原图做什么改变 新图的节点只是字符串。 ''' new_graph = nx.DiGraph() for start, end, data in self.edges_iter(data=True): port_pair = data['port_pair'] connection = data['connection'] edge = [start, end] # 存储边的起点和终点 node_id = ['', ''] # 存储节点的名称 node_data = [{}, {}] # 存储要打印到dot中的信息 for i in range(2): # 当前节点是prim 或者是 port is_prim = True if isinstance(edge[i], cc.circut_module) else False # prim和port的数据属性不同,根据判断为生成dot节点的名称,和节点附属的['shape']数据 node_name = '_d_' + edge[i].name[1:] if edge[i].name[ 0] == '\\' else edge[i].name node_id[i] = edge[i].cellref+node_name if is_prim else\ edge[i].port_type+node_name # prim为box形状(盒子),port为invtriangle形状(倒三角) node_data[i]['shape'] = 'box' if is_prim else 'invtriangle' new_graph.add_node(node_id[i], node_data[i]) new_graph.add_edge(node_id[0], node_id[1]) try: nx.write_dot(new_graph, filename) except Exception, e: print "Warning: Cannot write dot file", e
def iterate(n_iters): for i in tqdm(xrange(n_iters)): sampler.sample() likelihoods.append(sampler.tree.marg_log_likelihood()) plt.figure() plt.xlabel("Iterations", fontsize=fontsize) plt.ylabel("Data Log Likelihood", fontsize=fontsize) plt.plot(likelihoods) plt.legend(loc='best', fontsize=12) plt.savefig('unconstrained-likelihoods.png', bbox_inches='tight') final_tree = sampler.tree.copy() plt.figure() plot_tree_2d(final_tree, X, pca) for node in final_tree.dfs(): if node.is_leaf(): node.point = y[node.point] plt.figure() newick = final_tree.to_newick() tree = Phylo.read(StringIO(newick), 'newick') Phylo.draw_graphviz(tree, prog='neato') plt.savefig('unconstrained-tree.png', bbox_inches='tight') graph = Phylo.to_networkx(tree) with open('unconstrained-tree.nwk', 'w') as fp: print >>fp, newick, nx.write_dot(graph, 'unconstrained-tree.dot') plt.show()
def draw_graph(graph, filename): if config["paths"]["graphviz"]: # neither pydot nor pygraphviz reliably find graphviz on windows. gotta do everything myself... from subprocess import call graph_file_name = os.path.join(tempfile.gettempdir(), "graph.dot") nx.write_dot(graph, graph_file_name) call( [ config["paths"]["graphviz"], "-Tpng", "-Edir=back", "-Gsplines=ortho", "-Grankdir=BT", "-Gconcentrate=true", "-Nshape=box", "-Gdpi=192", graph_file_name, "-o", "{}.png".format(filename), ] ) else: print("graphviz path not set")
def sampleNodesFromGraph(inputGraph, proportionToKeep): # 0.9 ... keep 90% of the nodes, remove the rest along with incident edges filename = inputGraph+'_sampled_'+str(proportionToKeep) if os.path.isfile(filename): G = nx.read_dot(filename) print "Cached %s loaded." % filename return G Gorig = nx.read_dot(inputGraph) G = nx.read_dot(inputGraph) #G = nx.Graph(Gorig) print "%s loaded." % inputGraph nodes = Gorig.nodes() random.shuffle(nodes) N = len(nodes) # keep k nodes k = int(round(N*(1-proportionToKeep))) for n in range(0,k): G.remove_node(nodes[n]) nx.write_dot(G, filename) print "\tGraph sampled. Original graph had %d nodes, sampled graph has %d nodes." % (len(Gorig.nodes()), len(G.nodes())) return G
def write_graph(self, filename, problem_edges=[], max_edge=0.99): G = nx.DiGraph() print 'writing graph!' print 'internal edges', self.directed_edges for o in self.observations: if o in self.anchors.values(): G.add_node(o, style='filled', color='red') else: G.add_node(o, style='filled', color='gray') for e in self.directed_edges: i = e[0] j = e[1] print '' if e in problem_edges: G.add_edge(i, j, color='red') else: G.add_edge(i, j, color='blue') for e in self.failures: i = e[0] j = e[1] if self.failures[e] < max_edge: G.add_edge(i, j, color='green', weight=(1 - self.failures[e]) * 10) nx.write_dot(G, filename)
def sampleNodesFromGraph(inputGraph, proportionToKeep): # 0.9 ... keep 90% of the nodes, remove the rest along with incident edges filename = inputGraph + '_sampled_' + str(proportionToKeep) if os.path.isfile(filename): G = nx.read_dot(filename) print "Cached %s loaded." % filename return G Gorig = nx.read_dot(inputGraph) G = nx.read_dot(inputGraph) #G = nx.Graph(Gorig) print "%s loaded." % inputGraph nodes = Gorig.nodes() random.shuffle(nodes) N = len(nodes) # keep k nodes k = int(round(N * (1 - proportionToKeep))) for n in range(0, k): G.remove_node(nodes[n]) nx.write_dot(G, filename) print "\tGraph sampled. Original graph had %d nodes, sampled graph has %d nodes." % ( len(Gorig.nodes()), len(G.nodes())) return G
def main(): """ Application entry point """ args = process_arguments() print('Loading data...') data = load_data(args.infile) people = list(set(m['sender'] for m in data) | set(r for m in data for r in m['recipients'])) counts = defaultdict(Counter) for message in data: counts[message['sender']].update(message['recipients']) for person in people: counts[person][person]=0 df = pd.DataFrame(counts) connections = (df * df.T).stack().to_frame() connections.index.names=['sender', 'recipient'] connections.reset_index(inplace=True) subset = connections[connections['sender'] < connections['recipient']].copy() subset.columns = ['sender', 'recipient', 'product'] subset['rank'] = subset['product'].rank(method='first', ascending=False) ranking = subset.sort_values(by='rank').set_index(['rank']) ranking.to_csv(args.outfile) gr = nx.Graph() for sender, recipient in zip(ranking['sender'], ranking['recipient']): gr.add_edge(sender, recipient) nx.write_dot(gr, 'thing.dot') args.infile.close() args.outfile.close()
def create_phylo_tree(fname, dotfile=None, pngfile=None, genpath=None): colors = ['chartreuse', 'chocolate', 'cadetblue', 'cornflowerblue', 'cyan', 'darkorange', 'darkviolet', 'deeppink'] # create a graph G=nx.DiGraph() # fill the lists with all the genes gl = process_file(fname) # create the phylo-tree pbar = progressbar.ProgressBar(maxval=len(gl.keys())).start() i=0 for n in gl.keys(): pbar.update(i+1) i = i+1 G.add_node(n) # the root node (the initial gene) G.node[n]['agent'] = n G.node[n]['id'] = n G.node[n]['color'] = colors[n%len(colors)] trac_genome(gl, n, G, colors, genpath) pbar.finish() # write the file if dotfile != None : print 'Writing %s ...'%(dotfile) nx.write_dot(G, dotfile) print 'done' if pngfile != None : print 'Writing %s ...'%(pngfile) dot2png(dotfile, pngfile) print 'done' return G
def save(G, name): f = open("%s.txt" % name, "w") for v in G.nodes_iter(): neighbors = " ".join([str(w) for w in G.neighbors_iter(v)]) f.write("%s\t%s\n" % (v, neighbors)) f.close() nx.write_dot(G, "%s.dot" % name)
def ministro_ministro(G): """ Cria um grafo de ministros conectados de acordo com a sobreposição de seu uso da legislação Construido a partir to grafo ministro_lei """ GM = nx.Graph() for m in G: try: int(m) except ValueError:# Add only if node is a minister if m != "None": GM.add_node(m.decode('utf-8')) # Add edges for n in GM: for m in GM: if n == m: continue if GM.has_edge(n,m) or GM.has_edge(m,n): continue # Edge weight is the cardinality of the intersection each node neighbor set. w = len(set(nx.neighbors(G,n.encode('utf-8'))) & set(nx.neighbors(G,m.encode('utf-8')))) #encode again to allow for matches if w > 5: GM.add_edge(n,m,{'weight':w}) # abreviate node names GMA = nx.Graph() GMA.add_weighted_edges_from([(o.replace('MIN.','').strip(),d.replace('MIN.','').strip(),di['weight']) for o,d,di in GM.edges_iter(data=True)]) P.figure() nx.draw_spectral(GMA) nx.write_graphml(GMA,'ministro_ministro.graphml') nx.write_gml(GMA,'ministro_ministro.gml') nx.write_pajek(GMA,'ministro_ministro.pajek') nx.write_dot(GMA,'ministro_ministro.dot') return GMA
def printDecoder(self, fileName): try: NX.write_dot(self.decodingTree, fileName) except: import traceback traceback.print_exc() print ('Error in printing the decoding tree on file ' + fileName)
def lei_vs_lei(nedges=None): """ Grafo de todas com todas (leis) """ # Verão original Flávio comentada # curgrafo.execute('select lei_id_1,esfera_1,lei_1,lei_id_2,esfera_2, lei_2, peso from vw_gr_lei_lei where peso >300 and lei_id_2>2') # curgrafo.execute('select lei_id_1,lei_tipo_1,lei_nome_1,lei_id_2,lei_tipo_2, lei_nome_2, peso from vw_gr_lei_lei where lei_count <= 20 and lei_id_1 = 1 and lei_id_2 <= 20 limit 0,1000') # curgrafo.execute('select lei_id_1,lei_tipo_1,lei_nome_1,lei_id_2,lei_tipo_2, lei_nome_2, peso from vw_gr_lei_lei where lei_count <= 8 and lei_id_1 <= 20 and lei_id_2 <= 20 limit 0,1000') curgrafo.execute('select lei_id_1,esfera_1,lei_1,lei_id_2,esfera_2, lei_2, peso from vw_gr_lei_lei where lei_count <= 10 and lei_id_1 <= 50 and lei_id_2 <= 200 limit 0,10000') if not nedges: res = curgrafo.fetchall() nedges = len(res) else: res = curgrafo.fetchmany(nedges) eds = [(i[0],i[3],i[6]) for i in res] G = nx.Graph() #eds = [i[:3] for i in res] G.add_weighted_edges_from(eds) print "== Grafo Lei_Lei ==" print "==> Order: ",G.order() print "==> # Edges: ",len(G.edges()) # Adding attributes to nodes for i in res: G.node[i[0]]['esfera'] = i[1] G.node[i[0]]['lei'] = i[2] G.node[i[3]]['esfera'] = i[4] G.node[i[3]]['lei'] = i[5] nx.write_graphml(G,'lei_lei.graphml') nx.write_gml(G,'lei_lei.gml') nx.write_pajek(G,'lei_lei.pajek') nx.write_dot(G,'lei_lei.dot') return G,res
def render(): e = sqlalchemy.create_engine('postgresql://127.0.0.1/holborn') i = sqlalchemy.inspect(e) fkg = nx.DiGraph() for name in i.get_table_names(): for fk in i.get_foreign_keys(name): fkg.add_node(name, URL='"{}.svg"'.format(name), shape='rect') fkg.add_node(fk['referred_table'], URL='"{}.svg"'.format(fk['referred_table']), path=fk['referred_table'], shape='rect') fkg.add_edge(fk['referred_table'], name, arrowhead='dot', color='gray') fkg.add_edge(name, fk['referred_table']) for node in fkg.nodes_iter(): sg = fkg.subgraph( nx.single_source_shortest_path_length(fkg, node, 1).keys() + [node]) sg.graph['graph'] = {'rankdir': 'LR', 'ratio': 'compress'} path = 'tmp/{}.dot'.format(node) out_path = 'db-graph/{}.svg'.format(node) nx.write_dot(sg, path) subprocess.check_output(['dot', '-Tsvg', path, '-o', out_path])
def writeExprTree(G,filename='ExprTree.dot'): """ Writes a tree in the DOT format: - http://en.wikipedia.org/wiki/DOT_language - http://www.graphviz.org/ """ nx.write_dot(G,filename)
def plot(g, step): import os for n, d in g.nodes(data=True): d["label"] = "{} {} {} ({})".format(n, d['_name'], d['_self_coverage'], d['_coverage']) if not d['_valid'] or not d['_tested']: d["style"] = "dotted" else: d["style"] = "solid" if d['_tested']: d["style"] = "solid" if not d['_matching']: d['color'] = "red" else: d['color'] = "green" if d['_to_test']: d['color'] = "orange" for u, v, d in g.edges(data=True): d["label"] = round(d["weight"], 2) nx.write_dot(g, "{0}/graph_{1}.dot".format(var.CERE_PROFILE_PATH, step)) try: logger.debug( subprocess.check_output( "dot -Tpdf {0}/graph_{1}.dot -o {0}/graph_{1}.pdf".format( var.CERE_PROFILE_PATH, step), stderr=subprocess.STDOUT, shell=True)) except subprocess.CalledProcessError as err: logger.error(str(err)) logger.error(err.output) logger.error("Cannot create the pdf")
def draw_network_from_cells(cells, output_dir, output_format, dot, neato, draw_graphs): cells = list(cells.values()) colorscheme = 'set15' colours = {'A': '1', 'B': '2', 'G': '3', 'D': '5', 'mean_both': '#a8a8a8bf'} network, draw_tool, component_groups = make_cell_network_from_dna(cells, colorscheme, colours, False, "box", dot, neato) network_file = "{}/clonotype_network_with_identifiers.dot".format(output_dir) try: nx.write_dot(network, network_file) except AttributeError: import pydotplus nx.drawing.nx_pydot.write_dot(network, network_file) if draw_graphs: command = draw_tool + ['-o', "{output_dir}/clonotype_network_with_identifiers.{output_format}".format( output_dir=output_dir, output_format=output_format), "-T", output_format, network_file] subprocess.check_call(command) network, draw_tool, cgx = make_cell_network_from_dna(cells, colorscheme, colours, False, "circle", dot, neato) network_file = "{}/clonotype_network_without_identifiers.dot".format(output_dir) try: nx.write_dot(network, network_file) except AttributeError: import pydotplus nx.drawing.nx_pydot.write_dot(network, network_file) if draw_graphs: command = draw_tool + ['-o', "{output_dir}/clonotype_network_without_identifiers.{output_format}".format( output_dir=output_dir, output_format=output_format), "-T", output_format, network_file] subprocess.check_call(command) return (component_groups)
def plot_call_graph(self, g): for n, d in g.nodes(data=True): d["label"] = "{} {} {} ({})".format(n, d['_name'], d['_self_coverage'], d['_coverage']) if not d['_valid'] or d['_small']: d["style"] = "dotted" else: d["style"] = "solid" if d['_tested']: d["style"] = "solid" if not d['_matching']: d['color'] = "red" else: d['color'] = "green" if d['_to_test']: d['color'] = "orange" if d['_name'] == self._name: d['style'] = "filled" nx.write_dot( g, "{0}/graph_{1}.dot".format(var.CERE_PLOTS_PATH, self._name)) try: subprocess.check_output( "dot -Tpng {0}/graph_{1}.dot -o {0}/graph_{1}.png".format( var.CERE_PLOTS_PATH, self._name), stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as err: logger.error(str(err)) logger.error(err.output) logger.warning("Can't create call graph fo region {0}".format( self._name))
def genome_animation(genomes_files, indir, outdir=None): # by default the same if outdir == None: outdir = indir # create dot files last_genome_file = genomes_files[-1] last_genome = process_graph(indir + '/' + last_genome_file) for gf in genomes_files: graph_of_g = graph_from_graph(last_genome, indir + '/' + gf) nx.write_dot(graph_of_g, outdir + '/' + gf[:-4] + '.dot') # create png files png_filenames = generate_fname_seq(len(genomes_files), 'png') i = 0 for gf in genomes_files: dot2png(outdir + '/' + gf[:-4] + '.dot', outdir + '/' + png_filenames[i]) i = i + 1 # print the command line to create the movie zpad = len(str(i)) cmd_line = 'ffmpeg -framerate 1 -i ' + outdir + '/' + '%0' + str( zpad) + 'd.png -c:v libx264 -pix_fmt yuv420p ' + outdir + '/out.mp4' print('To create the movies run the following command:') print(cmd_line)
def genome_animation(genomes_files, indir, outdir=None): # by default the same if outdir == None : outdir = indir # create dot files last_genome_file = genomes_files[-1] last_genome = process_graph(indir+'/'+last_genome_file) for gf in genomes_files : graph_of_g = graph_from_graph(last_genome, indir+'/'+gf) nx.write_dot(graph_of_g, outdir+'/'+gf[:-4]+'.dot') # create png files png_filenames = generate_fname_seq(len(genomes_files), 'png') i=0 for gf in genomes_files : dot2png(outdir+'/'+gf[:-4]+'.dot', outdir+'/'+png_filenames[i]) i=i+1 # print the command line to create the movie zpad = len(str(i)) cmd_line = 'ffmpeg -framerate 1 -i '+outdir+'/'+'%0'+str(zpad)+'d.png -c:v libx264 -pix_fmt yuv420p '+outdir+'/out.mp4'; print 'To create the movies run the following command:' print cmd_line
def runPRN(): #DG = readDotFile('/home/loenix/Documents/advogato_graph/advogato-graph-2014-03-16.dot') DG = readDotFile('advogato-graph-latest.dot') #DG = nx.DiGraph(nx.read_dot('/home/loenix/Documents/advogato_graph/advogato-graph-2014-03-16.dot')) Eps = 0.000001 #set up epsilon alpha = 0.15 # set alpha #pick up a nodes far enough from the seed #so that the subgraph on which APPR run will #will be large enough numHops = 4 rand = random.randint(0,len(DG.nodes())-1) Seed = DG.nodes()[rand] remoteSeed = getTrustorsOfExactHop(DG, Seed, numHops) while remoteSeed == 0 : Seed = DG.nodes()[rand] remoteSeed = getTrustorsOfExactHop(DG, Seed, numHops) #now got a seed which has 4 hop neighbor, run APPR #print('seed is:' + Seed) #print('nb of seed is: ' + str(DG.neighbors(Seed))) #since the algr works on undirected graph DG.to_undirected() PR = PageRankNibble(DG, Seed, alpha, Eps) #using the ranked nodes to form a subgraph. H = DG.subgraph(PR) nx.write_dot(H, 'pprResult.dot') return H
def write_graph(self, filename, problem_edges=[], max_edge=0.99): G = nx.DiGraph() print 'writing graph!' print 'internal edges', self.directed_edges for o in self.observations: if o in self.anchors.values(): G.add_node(o, style='filled', color='red') else: G.add_node(o, style='filled', color='gray') for e in self.directed_edges: i = e[0] j = e[1] print '' if e in problem_edges: G.add_edge(i, j, color='red') else: G.add_edge(i, j, color='blue') for e in self.failures: i = e[0] j = e[1] if self.failures[e] < max_edge: G.add_edge(i, j, color='green', weight=(1-self.failures[e])*10) nx.write_dot(G, filename)
def draw_graph(mst, mst_a, mol_names, dir_names, method): import networkx as nx G = nx.from_scipy_sparse_matrix(mst) if method == 'mcs': corr = 1 else: corr = 0 for i, j in zip(mst.nonzero()[0], mst.nonzero()[1]): G.edge[i][j]['label'] = '%.1f' % (mst_a[i][j] - corr) G.edge[i][j]['len'] = '3.0' for n in G.nodes(): G.node[n]['shape'] = 'box' G.node[n]['label'] = ( '<' '<table border="0" cellspacing="-20" cellborder="0">' '<tr><td><img src="%s"/></td></tr>' '<tr><td bgcolor="#F0F0F0">%s</td></tr>' '</table>>' % (os.path.join( dir_names[n], mol_names[n] + os.extsep + 'svg'), mol_names[n])) print('Writing networkx graph pickle file %s...' % GPICKLE_FILE) nx.write_gpickle(G, GPICKLE_FILE) print('Writing DOT file %s...' % DOT_FILE) nx.write_dot(G, DOT_FILE)
def printDecoder(self, filename): try: NX.write_dot(self.decodingTree, filename) except: import traceback traceback.print_exc() print ('Error in printing the decoding tree on file ' + filename)
def write_dot_graph(self, dot_adr): for n in self.GRAPH.nodes() : self.GRAPH.node[n]["label"] = self.GRAPH.node[n]["contig"]+"_"+str(n)+"_"+self.GRAPH.node[n]["sens"]+"_"+self.GRAPH.node[n]["bi"]+"_"+str(self.GRAPH.node[n]["coords"]) if self.GRAPH.node[n]["bi"] == "b" : self.GRAPH.node[n]["shape"] = "box" if self.GRAPH.node[n]["sens"] == "f" : self.GRAPH.node[n]["color"] = "green" elif self.GRAPH.node[n]["sens"] == "r" : self.GRAPH.node[n]["color"] = "red" if "selected" in self.GRAPH.node[n].keys() : self.GRAPH.node[n]["style"] = "filled" for e in self.GRAPH.edges() : self.GRAPH.edge[e[0]][e[1]]["label"] = self.GRAPH.edge[e[0]][e[1]]["length"] if ((e[0] == "In" or e[0] == "Out") or (e[1] == "Out" or e[1] == "In")) and (self.GRAPH.edge[e[0]][e[1]]["length"] == 0): self.GRAPH.edge[e[0]][e[1]]["style"] = "dashed" self.GRAPH.edge[e[0]][e[1]]["color"] = "grey" elif self.GRAPH.node[e[0]]["contig"] == self.GRAPH.node[e[1]]["contig"] and self.GRAPH.node[e[0]]["sens"] == "f" : self.GRAPH.edge[e[0]][e[1]]["color"] = "green" elif self.GRAPH.node[e[0]]["contig"] == self.GRAPH.node[e[1]]["contig"] and self.GRAPH.node[e[0]]["sens"] == "r" : self.GRAPH.edge[e[0]][e[1]]["color"] = "red" elif ((e[0] == "In" or e[0] == "Out") and self.GRAPH.node[e[1]]["sens"] == "f") or ((e[1] == "In" or e[1] == "Out") and self.GRAPH.node[e[0]]["sens"] == "f") : self.GRAPH.edge[e[0]][e[1]]["color"] = "green" elif ((e[0] == "In" or e[0] == "Out") and self.GRAPH.node[e[1]]["sens"] == "r") or ((e[1] == "In" or e[1] == "Out") and self.GRAPH.node[e[0]]["sens"] == "r") : self.GRAPH.edge[e[0]][e[1]]["color"] = "red" nx.write_dot(self.GRAPH, dot_adr)
def export_graph( graph_in, base_dir=None, show=False, use_execgraph=False, show_connectinfo=False, dotfilename="graph.dot", format="png", simple_form=True, ): """ Displays the graph layout of the pipeline This function requires that pygraphviz and matplotlib are available on the system. Parameters ---------- show : boolean Indicate whether to generate pygraphviz output fromn networkx. default [False] use_execgraph : boolean Indicates whether to use the specification graph or the execution graph. default [False] show_connectioninfo : boolean Indicates whether to show the edge data on the graph. This makes the graph rather cluttered. default [False] """ graph = deepcopy(graph_in) if use_execgraph: graph = generate_expanded_graph(graph) logger.debug("using execgraph") else: logger.debug("using input graph") if base_dir is None: base_dir = os.getcwd() if not os.path.exists(base_dir): os.makedirs(base_dir) outfname = fname_presuffix(dotfilename, suffix="_detailed.dot", use_ext=False, newpath=base_dir) logger.info("Creating detailed dot file: %s" % outfname) _write_detailed_dot(graph, outfname) cmd = "dot -T%s -O %s" % (format, outfname) res = CommandLine(cmd, terminal_output="allatonce").run() if res.runtime.returncode: logger.warn("dot2png: %s", res.runtime.stderr) pklgraph = _create_dot_graph(graph, show_connectinfo, simple_form) outfname = fname_presuffix(dotfilename, suffix=".dot", use_ext=False, newpath=base_dir) nx.write_dot(pklgraph, outfname) logger.info("Creating dot file: %s" % outfname) cmd = "dot -T%s -O %s" % (format, outfname) res = CommandLine(cmd, terminal_output="allatonce").run() if res.runtime.returncode: logger.warn("dot2png: %s", res.runtime.stderr) if show: pos = nx.graphviz_layout(pklgraph, prog="dot") nx.draw(pklgraph, pos) if show_connectinfo: nx.draw_networkx_edge_labels(pklgraph, pos)
def salva_grafoNX_imagem(G): """ Salva grafos em formato png e dot """ nx.draw_graphviz(G) nx.write_dot(G, 'relatorios/grafo_lei_vs_lei.dot') P.savefig('relatorios/grafo_lei_vs_lei.png')
def iterate(n_iters): for i in tqdm(xrange(n_iters)): sampler.sample() likelihoods.append(sampler.tree.marg_log_likelihood()) plt.figure() plt.xlabel("Iterations", fontsize=fontsize) plt.ylabel("Data Log Likelihood", fontsize=fontsize) plt.plot(likelihoods) plt.legend(loc='best', fontsize=12) plt.savefig('unconstrained-likelihoods.png', bbox_inches='tight') final_tree = sampler.tree.copy() plt.figure() plot_tree_2d(final_tree, X, pca) for node in final_tree.dfs(): if node.is_leaf(): node.point = y[node.point] plt.figure() newick = final_tree.to_newick() tree = Phylo.read(StringIO(newick), 'newick') Phylo.draw_graphviz(tree, prog='neato') plt.savefig('unconstrained-tree.png', bbox_inches='tight') graph = Phylo.to_networkx(tree) with open('unconstrained-tree.nwk', 'w') as fp: print >> fp, newick, nx.write_dot(graph, 'unconstrained-tree.dot') plt.show()
def export_graph(graph_in, base_dir=None, show=False, use_execgraph=False, show_connectinfo=False, dotfilename='graph.dot', format='png', simple_form=True): """ Displays the graph layout of the pipeline This function requires that pygraphviz and matplotlib are available on the system. Parameters ---------- show : boolean Indicate whether to generate pygraphviz output fromn networkx. default [False] use_execgraph : boolean Indicates whether to use the specification graph or the execution graph. default [False] show_connectioninfo : boolean Indicates whether to show the edge data on the graph. This makes the graph rather cluttered. default [False] """ graph = deepcopy(graph_in) if use_execgraph: graph = generate_expanded_graph(graph) logger.debug('using execgraph') else: logger.debug('using input graph') if base_dir is None: base_dir = os.getcwd() if not os.path.exists(base_dir): os.makedirs(base_dir) outfname = fname_presuffix(dotfilename, suffix='_detailed.dot', use_ext=False, newpath=base_dir) logger.info('Creating detailed dot file: %s' % outfname) _write_detailed_dot(graph, outfname) cmd = 'dot -T%s -O %s' % (format, outfname) res = CommandLine(cmd, terminal_output='allatonce').run() if res.runtime.returncode: logger.warn('dot2png: %s', res.runtime.stderr) pklgraph = _create_dot_graph(graph, show_connectinfo, simple_form) outfname = fname_presuffix(dotfilename, suffix='.dot', use_ext=False, newpath=base_dir) nx.write_dot(pklgraph, outfname) logger.info('Creating dot file: %s' % outfname) cmd = 'dot -T%s -O %s' % (format, outfname) res = CommandLine(cmd, terminal_output='allatonce').run() if res.runtime.returncode: logger.warn('dot2png: %s', res.runtime.stderr) if show: pos = nx.graphviz_layout(pklgraph, prog='dot') nx.draw(pklgraph, pos) if show_connectinfo: nx.draw_networkx_edge_labels(pklgraph, pos)
def array_to_dot(ary): g = array_to_graph(ary) g.name = 'G' with tempfile.TemporaryFile() as tf: nx.write_dot(g, tf) tf.seek(0) return tf.read()
def make_png(graph, path): fd, dotfile = tempfile.mkstemp(prefix="graph", suffix=".dot") try: dfile = dotfile nx.write_dot(graph, dfile) subprocess.call(['neato', '-n2', '-Tpng', '-o', path, dfile]) finally: os.remove(dotfile)
def show_graph(graph): m = graph.copy() pos = nx.graphviz_layout(m) nx.draw_networkx_edge_labels(m, pos) nx.draw_networkx_nodes(m, pos) nx.draw_networkx_labels(m, pos) nx.write_dot(m, "m.dot") os.system("dot -Tps m.dot -o m.ps") nx.draw(m, pos)
def render_graph(self, output_file): """ This method is used to render graph of Job Descriptions """ global X for k, v in G.items(): a, b = k.split("\t") X.add_weighted_edges_from([(a, b, v)]) nx.write_dot(X, output_file)