def main(): iterations = 1000000 n = 1000 c = 1 results = [] graph: Graph = Graph.Erdos_Renyi(n, c / n) randomize = True for i in range(iterations): np_graph = graph_to_numpy(graph) cover_group = shaked_algo_impl_v2.shaked_algo_impl_v2(np_graph, randomize=randomize) cover_group_size = len(cover_group) if i % 100 == 0: print(f'iteration {i}') results.append(cover_group_size) results = np.array(results) print('=========') avg = results.mean() print(f'average: {avg}') variance = results.var() print(f'variance: {variance}') np.save('theorem5.npy', results) bins = np.max(results)-np.min(results) results = (results - avg)/np.sqrt(variance) plot_hist(results, bins) return results
def create_graph(named: bool = False): g: Graph = Graph.Erdos_Renyi(n=50, p=0.2) if named: for v in g.vs: v["name"] = "Node-{}".format(v.index) v["external_id"] = "Node-Ext-{}".format(v.index) return IGraphWrapper(g)
def test_rich_club_coefficient(self): print """Testing rich_club_coefficient""" self.assertTrue(True) ns = [ 60, ] ms = [60, 10, 600] directeds = [True, False] highests = [True, False] scoress = [None, 'r'] test_cases = [(n, m, directed, highest, score) for n in ns for m in ms for directed in directeds for highest in highests for score in scoress] rc_properties = [ 'intensity_P_wm', 'intensity_L_wm', 'intensity_P_local', 'intensity_L_local', 'intensity_L_global', 'intensity_P_global' ] for n, m, directed, highest, score in test_cases: g = Graph.Erdos_Renyi(n=n, m=m, directed=directed) # print "%i nodes, %i links, directed: %i, highest: %i, "\ # "score: %s"\ for p in rc_properties: print p rc = richclub.rich_club_coefficient(g, club_property=p) self.assertTrue(True)
def test_algorithm(self): graph = Graph.Erdos_Renyi(10, 0.3) cover = most_neighbors_with_minimal_degree.most_neighbors_with_minimal_degree_algo( None, graph) assert_equal( graph_utils.check_if_legal_vertex_cover( graph_utils.graph_to_numpy(graph), cover), True)
def run_reduce_graph_all(graph=None): graph: Graph = graph or Graph.Erdos_Renyi(100, 3 / 100) set_name(graph) print_graph_info(graph, leaves=True, zero_degree=True, connected_components=True, label='start') added_to_cover, counter_of_removed = reduce_graph(graph, do_reduce_1=True, do_reduce_2=True, do_reduce_3=True) print(f'size of cover: {len(added_to_cover) + counter_of_removed}') print_graph_info(graph, leaves=True, zero_degree=True, connected_components=True, label='end')
def sample_bottlenecks_and_variance(n_nodes=100, p=.1, n_iterations=100): max_d_mins = empty(n_iterations) var_d_mins = empty(n_iterations) for i in range(n_iterations): g = Graph.Erdos_Renyi(n_nodes, p, directed=True) d_mins = list(map(lambda n: d_min(g, n), range(len(g.vs)))) max_d_mins[i] = nanmax(d_mins) var_d_mins[i] = nanvar(d_mins) return max_d_mins, var_d_mins
def run_reduce_1_by_iteration(graph=None): n = 1000 c = 3 graph: Graph = graph or Graph.Erdos_Renyi(n, c / n) set_name(graph) print_theoretical_number_of_leaves(n, c) print_graph_info(graph, leaves=True, zero_degree=True, connected_components=True, label='initial graph') added_to_cover = remove_parents_of_leaves(graph, log=True, one_time=False) print(f'how many added to cover: {len(added_to_cover)}')
def pyth_wrapper(N, p, q, avg_d, c): # Create graph and needed adj_list g = Graph.Erdos_Renyi(N, avg_d/(N-1)) logger.info(f"Generating adj list for N={N}, p={p}, init_c = {c}, q={q}...") adj_l = [] for x in g.get_adjlist(): adj_l.append(np.array(x)) logger.info("Creting adj list is done!!") states = gen_states(N, c) logger.info("Starting simulation...") return simulate(adj_l, states, N, p, q, MCS_STEPS)
def _do_test(): vertex_count = 50 max_steps = [vertex_count * 2] graph = Graph.Erdos_Renyi(vertex_count, 0.5) lambds = [0.01, 0.02, 0.04, 0.08] mus = [0.01, 0.02, 0.04, 0.08] start_time = datetime.now() ctmc_sis_multiple(graph, lambds, mus, max_steps) print("Time passed: ", datetime.now() - start_time)
def pyth_wrapper(N, p, q, avg_d, c): # Create graph and needed adj_list g = Graph.Erdos_Renyi(N, avg_d / (N - 1)) logger.info(f"Generating adj list for N={N} ...") adj_l = List() for x in g.get_adjlist(): adj_l.append(np.array(x)) logger.info("Creting adj list is done!!") states = gen_states(N, c) logger.info("Starting simulation...") result = simulate(adj_l, states, N, p, q, MCS_STEPS) logger.info("Saving results...") save_results(N, p, q, c, result)
def main(): # Create a random Graph g = Graph.Erdos_Renyi(n=10, m=20, directed=True) # Return a minimum spanning tree for a graph agm = g.spanning_tree(weights=None, return_tree=True) kr = kruskal(g) agmk = Graph(n=10, edges=list(kr)) # plot Graph plot(g) plot(agm) plot(agmk)
def main(arguments): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--plot', action='store_true', help="Plot graph (visual map of the test case)", required=False) parser.add_argument( '-f', '--file', help= "Print testcase details in files starting with this suffix + (_graph.txt, _data.txt, _plot.png)", required=False) parser.add_argument('-s', '--size', default=10, help="Size of graph", required=False) parser.add_argument('-e', '--edges', default=9, help="Number of edges", required=False) args = parser.parse_args(arguments) # generate graph g = Graph.Erdos_Renyi(n=int(args.size), m=int(args.edges), directed=False, loops=False) # g = Graph.Degree_Sequence([1, 3, 1, 1], method="vl") # print to file(s) if args.file: with open(args.file + '_graph.txt', 'w+') as f: for line in g.get_adjacency(): print >> f, ', '.join(map(str, line)) with open(args.file + '_data.txt', 'w+') as f: for _ in range(int(args.size)): print >> f, uuid.uuid4() if args.plot: plot(g, args.file + '_plot.png') else: for line in g.get_adjacency(): print ', '.join(map(str, line)) for _ in range(args.size): print uuid.uuid4() if args.plot: plot(g)
def run_reduce_graph_compare(graph=None): graph: Graph = graph or Graph.Erdos_Renyi(10000, 2.8 / 10000) copy1 = graph.copy() copy2 = graph.copy() set_name(copy1) set_name(copy2) print_graph_info(graph, leaves=True, zero_degree=True, connected_components=True, label='initial graph') reduce_graph(copy1, do_reduce_1=True, do_reduce_2=False, do_reduce_3=False) print_graph_info(copy1, leaves=True, zero_degree=True, connected_components=True, label='copy1: after only reduce 1') reduce_graph(copy2, do_reduce_1=True, do_reduce_2=True, do_reduce_3=False) print_graph_info(copy2, leaves=True, zero_degree=True, connected_components=True, label='copy2: after reduce 1 + 2')
def main(): n = 1000 c = 1 p = c / n initial_b = 10 graph: Graph = Graph.Erdos_Renyi(n=n, p=p) # graph = king_graph(n=10, m=10) graph = rook_graph(n=30, m=30) graph, C = bwc_algo(graph, initial_b) print(f'n={len(graph.vs)}') print(f'C = {len(C)}') print(f'w = {len(graph.vs) - len(C)}')
def test_rich_nodes(self): print """Testing rich/poor node selection on directed and undirected graphs.""" ns = [ 60, ] ms = [60, 10, 600] directeds = [True, False] highests = [True, False] scoress = [None, 'r'] test_cases = [(n, m, directed, highest, score) for n in ns for m in ms for directed in directeds for highest in highests for score in scoress] for n, m, directed, highest, score in test_cases: g = Graph.Erdos_Renyi(n=n, m=m, directed=directed) print "%i nodes, %i links, directed: %i, highest: %i, "\ "score: %s"\ % (n, m, directed, highest, score) #Returns all nodes self.assertEqual( len(richclub.rich_nodes(g, rank=0, highest=highest)), len(g.vs)) if score == 'r': from numpy.random import rand from numpy import delete, greater, less score = rand(n) if highest: op = greater else: op = less for i in range(0, n - 1): percentile = 100.0 * i / n rnodes = richclub.rich_nodes(g, rank=percentile, highest=highest, scores=score) rscores = score[rnodes] poorscores = delete(score, rnodes) self.assertEqual(len(rnodes), n - i) self.assertTrue( all([op(a, b) for a in rscores for b in poorscores]))
def make_g(t): if t == 1: ws1, ws2, ws3, ws4 = 1, randrange(50, 250), randrange(2, 10), random() b = Graph.Watts_Strogatz(ws1, ws2, ws3, ws4) name = 'WS_' + '_'.join(map(str, [ws1, ws2, ws3, ws4])) if t == 2: bar1 = randrange(500, 1000) bar2 = int(round(bar1 * 0.01 * random())) + 1 b = Graph.Barabasi(bar1, [randrange(bar2) for i in range(bar1)]) name = 'BAR_' + '_'.join(map(str, [bar1, bar2])) if t == 3: er1 = randrange(50, 500) er2 = randrange(er1, 1000) b = Graph.Erdos_Renyi(n=er1, m=er2, directed=False, loops=False) name = 'ER_' + '_'.join(map(str, [er1, er2])) if t == 4: nnn = randrange(50, 500) gamma = randrange(200, 300) / 100.0 ok = 'no' while ok == 'no': try: b = config(nnn, gamma) ok = 'yes' except: pass if gamma > 2.5: name = 'CONF1_' + '_'.join(map(str, [nnn, gamma])) else: name = 'CONF2_' + '_'.join(map(str, [nnn, gamma])) # la1,la2,la3=randrange(5,25),randrange(5,25),randrange(1,5) # b=Graph.Lattice([la1,la2], nei=la3, directed=True, mutual=True, circular=True) # name='LAT_'+'_'.join(map(str,[la1,la2,la3])) if t != 4: g = [list(i.tuple) for i in b.es] else: g = [list(i) for i in b.edges()] #print len(g) rec = round(random(), 1) gg = make_rec(g, rec) b = Graph.TupleList(gg, directed=True) vvv, eee, diam, clust = b.vcount(), b.ecount(), b.diameter( ), b.transitivity_undirected() eig = GH(b) rob, rob_max = R_pr(g) return g, name.split('_')[0], '_'.join(name.split('_')[1:]), float( eig), vvv, eee, diam, clust, rob, rob_max, rec
def show_diam(vn,con,name): g = Graph.Erdos_Renyi(vn,con) g.vs['size'] = 10 g.vs['color'] = 'darkblue' g.es['color'] = 'black' d = g.get_diameter(directed=False) lay = g.layout_fruchterman_reingold() plot(g,'./images/'+name,layout = lay,dpi = 600) g.es['color'] = '#00000020' dpath = g.es.select(_within=d) for e in dpath: g.es[e.index]['width'] = 2 g.es[e.index]['color'] = 'darkblue' #lay = g.layout_reingold_tilford() #lay = g.layout_kamada_kawai() plot(g,'./images/diam_'+name,layout = lay,dpi = 600)
def plot_er(): """Plots a visualization of an E-R random graph""" g = Graph.Erdos_Renyi(n=100, m=100) visual_style = { "bbox": (3000, 3000), "margin": 100, "vertex_color": 'orange', "vertex_size": 50, "vertex_label_size": 10, "edge_curved": False, "edge_color": 'black', "edge_width": 7 } layout = g.layout("fr") visual_style["layout"] = layout save_name = f'er_layout.png' plot(g, SAVE_PATH + save_name, **visual_style)
def theorem4(): results = {} for c in cs: c_results = [] print(f'c {c}') for i in range(iterations): if i % 10 == 0: print(f'iteration {i}') graph: Graph = Graph.Erdos_Renyi(n, c / n) np_graph = graph_to_numpy(graph) cover_group = shaked_algo_impl_v2.shaked_algo_impl_v2(np_graph, randomize=True) cover_group_size = len(cover_group) c_results.append(cover_group_size) results[c] = c_results return results
def theorem5(): results = {} for c in cs: c_results = [] print(f'c {c}') for i in range(iterations): if i % 10 == 0: print(f'graph iteration {i}') graph_results = [] graph: Graph = Graph.Erdos_Renyi(n, c / n) orig = graph_to_numpy(graph) for j in range(iterations): np_graph = orig.copy() cover_group = shaked_algo_impl_v2.shaked_algo_impl_v2(np_graph, randomize=True) cover_group_size = len(cover_group) graph_results.append(cover_group_size) c_results.append(np.array(graph_results)) results[c] = np.array(c_results) return results
def main(): iterations = 200 n = 1000 cs = np.arange(0.5, 0.75, 0.25) # c = [0.25..10] results = {} for c in cs: c_results = [] print(f'c {c}') for i in range(iterations): if i % 10 == 0: print(f'iteration {i}') graph: Graph = Graph.Erdos_Renyi(n, c / n) np_graph = graph_to_numpy(graph) cover_group = degree(np_graph) #cover_group = shaked_algo_impl_v2.shaked_algo_impl_v2(np_graph, randomize=True) cover_group_size = len(cover_group) c_results.append(cover_group_size) results[c] = c_results return results
def test_richness_scores(self): print """Testing richness score identification on directed and undirected graphs.""" ns = [ 60, ] ms = [60, 10, 600] directeds = [True, False] test_cases = [(n, m, directed) for n in ns for m in ms for directed in directeds] for n, m, directed in test_cases: g = Graph.Erdos_Renyi(n=n, m=m, directed=directed) print "%i nodes, %i links, directed: %i" % (n, m, directed) g.es["weight"] = rand(m) ins = richclub.richness_scores(g, richness='in_strength') outs = richclub.richness_scores(g, richness='out_strength') s = richclub.richness_scores(g, richness='strength') if directed: assert_allclose( asarray(ins) + asarray(outs), asarray(s), err_msg="Identified strength sequence not the sum of the " "out and in strength sequences") else: assert_allclose( asarray(ins), asarray(s), err_msg="In and total strength sequences not equal") assert_allclose( asarray(outs), asarray(s), err_msg="Out and total strength sequences not equal")
def __experiment(self): for p in self.__prange: self.__graph = Graph.Erdos_Renyi(self.__vcount, p) self.__analyze()
def test_algorithm(): graph = Graph.Erdos_Renyi(100, 0.05) cover = first_vertex_with_degree.first_vertex_with_degree_algo(None, graph) assert_equal( graph_utils.check_if_legal_vertex_cover( graph_utils.graph_to_numpy(graph), cover), True)
eigvals = [] measures = [ {"func": lambda graph: Graph.average_path_length(graph, unconn = False), "result" : [], "name" : "Average Path Length"}, {"func": lambda graph: sum(Graph.degree(graph))/len(Graph.degree(graph)), "result" : [], "name" : "Average Degree"}, #{"func": lambda graph: max(Graph.degree(graph)), "result" : [], "name" : "Maximum Degree"}, {"func": lambda graph: sum(Graph.betweenness(graph))/len(Graph.betweenness(graph)), "result" : [], "name" : "Average Betweenness"}, #{"func": lambda graph: max(Graph.betweenness(graph)), "result" : [], "name" : "Maximum Betweenness"}, {"func": lambda graph: len(Graph.cliques(graph)), "result" : [], "name" : "Number of Cliques"}, #{"func": lambda graph: Graph.clique_number(graph), "result" : [], "name" : "Largest Clique"}, {"func": lambda graph: Graph.transitivity_undirected(graph, mode="zero"), "result" : [], "name" : "Global Clustering Coefficient"}, #{"func": lambda graph: Graph.transitivity_avglocal_undirected(graph, mode="nan"), "result" : [], "name" : "Averega Local Clustering Coefficient"}, {"func": lambda graph: shieldvalue(list(range(0,nrvertex)), graph), "result" : [], "name" : "Shield Value"},] for i in range(0, number): print("Graph: ", i) graph = Graph.Erdos_Renyi(nrvertex, 0.5) adj = np.array(graph.get_adjacency()._get_data()) eigv = np.linalg.eigvals(adj) x = np.real(max(eigv)) eigvals.append(x) for measure in measures: measure["result"].append(measure["func"](graph)) for measure in measures: (pearson, pv) = scipy.stats.pearsonr(measure["result"], eigvals) print(measure["name"], pearson) plt.plot(measure["result"], eigvals, 'o') plt.ylabel("Max eigen value") plt.xlabel(measure["name"]) plt.title(measure["name"]) plt.savefig(dirname + "/" + measure["name"] + ".png", dpi=200)
def test_algorithm(): graph = Graph.Erdos_Renyi(100, 0.05) cover = neighbors_algo.neighbors_algo(None, graph) assert_equal( graph_utils.check_if_legal_vertex_cover( graph_utils.graph_to_numpy(graph), cover), True)
# Lásd. halozatok_segedlet.tex from igraph import Graph, summary from igraph import plot as iplot # iplot néven, hogy ne keveredjen a pylab.plot függvénnyel # Programfájlban kellene még ez a sor is a -pylab opció helyett: from pylab import plot, average, array, grid, xlabel, ylabel, legend, show # vagy egyszerűen from pylab import * # és minden plot függvény után kellene # show() függvény. import pylab # esetén pedig pylab.függvény() alakban hívhatóak a pylab függvényei. net = Graph.Erdos_Renyi(1000, .001) summary(net) M=net.ecount() N = net.vcount() Mmax = N*(N-1)/2 Mmax M/Mmax p = 1.*M/Mmax net.diameter() net.components() cc=net.components() # (összefüggő) komponensek, (connected) components ccs = cc.sizes()
text(10, 20, "Average Speed Slow/Fast: %.2f"%(mean(y_slow)/mean(y_fast))) #text(10, 10, "Hazard Ratio Fast (relative to slow): 2.0) #text(10, 5, "Hazard Ratio Slow (relative to fast): %.2f"%(slow_slope/fast_slope)) # In[3]: get_ipython().magic('pylab inline') # In[12]: import igraph from igraph import Graph g = Graph.Erdos_Renyi(n=50,p=.1) g.es['weight']= rand(g.vcount()) print(g.spanning_tree()) # In[2]: get_ipython().magic('matplotlib inline') # In[3]: from pylab import *
from sys import argv from igraph import Graph import exrex if __name__ == "__main__": numVertices = int(argv[1]) numEdges = int(argv[2]) powerIterations = int(argv[3]) g = Graph.Erdos_Renyi(numVertices, m=numEdges, directed=True) edges = g.get_edgelist() nodeNames = {} vert = g.vs for vertex in vert: name = exrex.getone("[a-z0-9]{3,10}\.[a-z]{3}") nodeNames[vertex.index] = name file = open("results.txt", "w") file.write("{} {}\n".format(numEdges, powerIterations)) for edge in edges: v1 = nodeNames[edge[0]] v2 = nodeNames[edge[1]] file.write("{v1} {v2}\n".format(v1=v1, v2=v2)) file.close()
def main(argv=None): #TASK 1 clustering_coefficients = [] #Clustering coefficients avg_shortest_paths = [] #Avg shortest paths aux = [ i / 5 for i in range(20, -1, -1)] probabilities = [10 ** -i for i in aux] firstCC = 0 firstASP = 0 for i in range(0,21): watts = Graph.Watts_Strogatz(1, 1000, 4, probabilities[i]) #Calcular global transitivity aka clustering coefficient clustering_coefficients.append(watts.transitivity_undirected()) if(i == 0): firstCC = clustering_coefficients[0] clustering_coefficients[i] /= firstCC #normalizar #Calcular average shortest path avg_shortest_paths.append(watts.average_path_length(unconn=True)) if(i == 0): firstASP = avg_shortest_paths[0] avg_shortest_paths[i] /= firstASP #normalizar print("Clustering Coefficients") print("--------------------------------------") print(clustering_coefficients) print("Avg Shortest Paths") print("--------------------------------------") print(avg_shortest_paths) print("") plt.plot(probabilities, clustering_coefficients, 's', probabilities, avg_shortest_paths, 'o') plt.xlabel('Probability') plt.xscale('log') plt.savefig('plot_task_1.png', bbox_inches='tight') plt.show() #TASK 2 #Parte 1 global graphArray readGraph('edges.txt') g = Graph() g.add_vertices(nodeCount+1) g.add_edges(graphArray) print("Edge count: " + repr(edgeCount)) print("Node count: " + repr(nodeCount)) print("Diameter: " + repr(g.diameter(directed=False))) print("Clustering Coeffiecient: " + repr(g.transitivity_undirected())) # Degree distribution print("\nDegree distribution: ") print(g.degree_distribution()) print(g.degree()) # Plotear con tamaño de nodos en función de PageRank print("PageRank:") graphPageRank = g.pagerank() prPlot = plot(g, vertex_size = [graphPageRank[i]*500 for i in range(0,len(g.vs))]) #Parte 2 communityGraph = Graph.Erdos_Renyi(20,0.3) comGraphPlot = plot(communityGraph, layout = communityGraph.layout_kamada_kawai(),target="./comGraph.png") comGraphPlot.show() #Elegir algoritmo com = communityGraph.community_edge_betweenness() #Mostrar nodos comunidad más grande comCluster = com.as_clustering() comSizes = comCluster.sizes() print("Max community size: " + repr(max(comSizes))) #Plot histograma tamaños comunidad plt.hist(comSizes, bins=range(min(comSizes),max(comSizes) + 2, 1), align='left') plt.ylabel('Number of communities') plt.xlabel('Community size') plt.savefig('plot_hist_communities.png') plt.show() #Plot grafo comunidades communitiesPlot = plot(com.as_clustering(), layout = communityGraph.layout_kamada_kawai(),target="./com-comGraph.png") communitiesPlot.show()