def random_graphs(): print("Random graphs") print("fast GNP random graph") G = nx.fast_gnp_random_graph(n=9, p=0.4) draw_graph(G) print("GNP random graph") G = nx.gnp_random_graph(n=9, p=0.1) draw_graph(G) print("Dense GNM random graph") G = nx.dense_gnm_random_graph(n=19, m=28) draw_graph(G) print("GNM random graph") G = nx.gnm_random_graph(n=11, m=14) draw_graph(G) print("Erdős Rényi graph") G = nx.erdos_renyi_graph(n=11, p=0.4) draw_graph(G) print("Binomial graph") G = nx.binomial_graph(n=45, p=0.4) draw_graph(G) print("Newman Watts Strogatz") G = nx.newman_watts_strogatz_graph(n=9, k=5, p=0.4) draw_graph(G) print("Watts Strogatz") G = nx.watts_strogatz_graph(n=9, k=2, p=0.4) draw_graph(G) print("Watts Strogatz") G = nx.watts_strogatz_graph(n=9, k=2, p=0.4) draw_graph(G) print("Connected Watts Strogatz") G = nx.connected_watts_strogatz_graph(n=8, k=2, p=0.1) draw_graph(G) print("Random Regular Graph") G = nx.random_regular_graph(d=2, n=9) draw_graph(G) print("Barabasi Albert Graph") G = nx.barabasi_albert_graph(n=10, m=2) draw_graph(G) print("Powerlow Cluster Graph") G = nx.powerlaw_cluster_graph(n=10, m=2, p=0.2) draw_graph(G) print("Duplication Divergence Graph") G = nx.duplication_divergence_graph(n=10, p=0.2) draw_graph(G) print("Random lobster Graph") G = nx.random_lobster(n=10, p1=0.2, p2=0.8) draw_graph(G) print("Random shell Graph") constructor = [(10, 20, 0.8), (20, 40, 0.8)] G = nx.random_shell_graph(constructor) draw_graph(G) print("Random Powerlow Tree") G = nx.random_powerlaw_tree(n=24, gamma=3) draw_graph(G) print("Random Powerlow Tree Sequence") G = nx.random_powerlaw_tree(n=13, gamma=3) draw_graph(G)
def gen_rand_tree(self, weighted=False, is_weights_int=True): if self.E != None: print('Number of edges will be changed') # Make tree tries = max(1000, self.N**2) g = nx.random_powerlaw_tree(self.N, tries=tries) relabel_map = {i: i + 1 for i in range(self.N)} nx.relabel_nodes(g, relabel_map) # Store data to self. fields self.E = len(g.edges()) self.nodes = [ Node(i) for i in range(self.OFFSET, self.N + self.OFFSET) ] for nx_e in g.edges(): i, j = nx_e[0], nx_e[1] ni, nj = self.nodes[i], self.nodes[j] e = ni.add_neigh(nj) self.edges.append(e) # Set random weights if weighted: for e in self.edges: w = randint(0, 10) if is_weights_int else round( random() * 10, 1) e.weight = w
def make_random_tree_graph(N_nodes, gamma_powerlaw=3, N_tries=1000): """random tree graph with exponentially distributed potentials""" # initialize and add nodes graph_name = nx.random_powerlaw_tree( N_nodes, gamma=gamma_powerlaw, tries=N_tries) node_state_sizes = np.random.randint( 2, high=5, size=graph_name.number_of_nodes()) # add indices of node state -- seems like there should be a slick way to # avoid this but can't figure it out for n in graph_name.nodes_iter(): graph_name.node[n]['node_state_indices'] = [ i for i in xrange(node_state_sizes[n])] # add potentials to graph for n in graph_name.nodes_iter(): node_potential = np.random.exponential(1, [node_state_sizes[n], 1]) graph_name.node[n]['node_potential'] = node_potential for i, edge in enumerate(graph_name.edges_iter()): n_a, n_b = edge len_n_a = len(graph_name.node[n_a]['node_potential']) len_n_b = len(graph_name.node[n_b]['node_potential']) edge_potential = np.random.exponential(1, [len_n_a, len_n_b]) graph_name.edge[n_a][n_b]['edge_potential'] = edge_potential return graph_name
def create_graph(self, params): # case statements on type of graph if self.type == 'small_world': self.graph = nx.watts_strogatz_graph( int(params[0]), int(params[1]), float(params[2]), None if len(params) < 4 else int(params[3])) cg.SWC += 1 self.idx = cg.SWC self.path = 'smallWorldGraphs' elif self.type == 'small_world_connected': self.graph = nx.connected_watts_strogatz_graph( int(params[0]), int(params[1]), float(params[2]), 100 if len(params) < 4 else int(params[3]), None if len(params) < 5 else int(params[4])) cg.SWCC += 1 self.idx = cg.SWCC self.path = 'smallWorldConnectedGraphs' elif self.type == 'small_world_newman': self.graph = nx.newman_watts_strogatz_graph( int(params[0]), int(params[1]), float(params[2]), None if len(params) < 4 else int(params[3])) cg.SWNC += 1 self.idx = cg.SWNC self.path = 'smallWorldNewmanGraphs' elif self.type == 'power_law': self.graph = nx.powerlaw_cluster_graph( int(params[0]), int(params[1]), float(params[2]), None if len(params) < 4 else int(params[3])) cg.PLC += 1 self.idx = cg.PLC self.path = 'powerLawGraphs' elif self.type == 'power_law_tree': self.graph = nx.random_powerlaw_tree( int(params[0]), 3 if len(params) < 2 else float(params[1]), None if len(params) < 3 else int(params[2]), 100 if len(params) < 4 else int(params[3])) cg.PLTC += 1 self.idx = cg.PLTC self.path = 'powerLawTreeGraphs' elif self.type == 'random_graph': self.graph = nx.gnm_random_graph( int(params[0]), int(params[1]), None if len(params) < 3 else int(params[2]), False if len(params) < 4 else bool(params[3])) cg.RGC += 1 self.idx = cg.RGC self.path = 'randomGraphs' elif self.type == 'erdos_renyi_random': self.graph = nx.erdos_renyi_graph( int(params[0]), float(params[1]), None if len(params) < 3 else int(params[2]), False if len(params) < 4 else bool(params[3])) cg.ERRC += 1 self.idx = cg.ERRC self.path = 'erdosRenyiRandomGraphs' else: print 'GRAPH TYPE:', self.type raise Exception('Invalid Type of Graph input into argv[2]')
def generate_graph(num_nodes, p, k=None, m=None, gamma=3, graph_type=1): if graph_type == 1: G = nx.fast_gnp_random_graph(n=num_nodes, p=p) elif graph_type == 2: G = nx.watts_strogatz_graph(n=num_nodes, k=k, p=p) elif graph_type == 3: G = nx.newman_watts_strogatz_graph(n=num_nodes, k=k, p=p) elif graph_type == 4: G = nx.connected_watts_strogatz_graph(n=num_nodes, k=k, p=p) elif graph_type == 5: G = nx.barabasi_albert_graph(n=num_nodes, m=m) elif graph_type == 6: G = nx.powerlaw_cluster_graph(n=num_nodes, m=m, p=p) elif graph_type == 7: G = nx.random_powerlaw_tree(n=num_nodes, gamma=gamma) return G
def generate_powerlaw(self, n, gamma=3): "Generates a random powerlaw tree using nx.random_powerlaw_tree" done = False tries = 1000 while(tries < 10000000 and not done): try: self.G = nx.random_powerlaw_tree(n, gamma, tries=10000, create_using=nx.DiGraph) self.G = nx.DiGraph(self.G) done = True except nx.NetworkXError: done = False tries *= 10 if not done: print("Unable to generate such powerlaw tree. Try a smaller graph") print("Aborting") sys.exit(1)
def RandomTreePowerlaw(n, gamma=3, tries=100, seed=None): """ Returns a tree with a power law degree distribution. Returns False on failure. From the NetworkX documentation: A trial power law degree sequence is chosen and then elements are swapped with new elements from a power law distribution until the sequence makes a tree (size = order - 1). INPUT: - ``n`` - number of vertices - ``gamma`` - exponent of power law - ``tries`` - number of attempts to adjust sequence to make a tree - ``seed`` - for the random number generator EXAMPLE: We show the edge list of a random graph with 10 nodes and a power law exponent of 2. :: sage: graphs.RandomTreePowerlaw(10, 2).edges(labels=False) [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (6, 8), (6, 9)] :: sage: G = graphs.RandomTreePowerlaw(15, 2) sage: if G: ... G.show() # random output, long time """ if seed is None: seed = current_randstate().long_seed() import networkx try: return graph.Graph( networkx.random_powerlaw_tree(n, gamma, seed=seed, tries=tries)) except networkx.NetworkXError: return False
def graphGenerator(): if args.graph_type == "erdos_renyi": return networkx.erdos_renyi_graph(args.graph_size,args.graph_p) if args.graph_type == "balanced_tree": ndim = int(np.ceil(np.log(args.graph_size)/np.log(args.graph_degree))) return networkx.balanced_tree(args.graph_degree,ndim) if args.graph_type == "cicular_ladder": ndim = int(np.ceil(args.graph_size*0.5)) return networkx.circular_ladder_graph(ndim) if args.graph_type == "cycle": return networkx.cycle_graph(args.graph_size) if args.graph_type == 'grid_2d': ndim = int(np.ceil(np.sqrt(args.graph_size))) return networkx.grid_2d_graph(ndim,ndim) if args.graph_type == 'lollipop': ndim = int(np.ceil(args.graph_size*0.5)) return networkx.lollipop_graph(ndim,ndim) if args.graph_type =='expander': ndim = int(np.ceil(np.sqrt(args.graph_size))) return networkx.margulis_gabber_galil_graph(ndim) if args.graph_type =="hypercube": ndim = int(np.ceil(np.log(args.graph_size)/np.log(2.0))) return networkx.hypercube_graph(ndim) if args.graph_type =="star": ndim = args.graph_size-1 return networkx.star_graph(ndim) if args.graph_type =='barabasi_albert': return networkx.barabasi_albert_graph(args.graph_size,args.graph_degree) if args.graph_type =='watts_strogatz': return networkx.connected_watts_strogatz_graph(args.graph_size,args.graph_degree,args.graph_p) if args.graph_type =='regular': return networkx.random_regular_graph(args.graph_degree,args.graph_size) if args.graph_type =='powerlaw_tree': return networkx.random_powerlaw_tree(args.graph_size) if args.graph_type =='small_world': ndim = int(np.ceil(np.sqrt(args.graph_size))) return networkx.navigable_small_world_graph(ndim) if args.graph_type =='geant': return topologies.GEANT() if args.graph_type =='dtelekom': return topologies.Dtelekom() if args.graph_type =='abilene': return topologies.Abilene() if args.graph_type =='servicenetwork': return topologies.ServiceNetwork()
def RandomTreePowerlaw(n, gamma=3, tries=100, seed=None): """ Returns a tree with a power law degree distribution. Returns False on failure. From the NetworkX documentation: A trial power law degree sequence is chosen and then elements are swapped with new elements from a power law distribution until the sequence makes a tree (size = order - 1). INPUT: - ``n`` - number of vertices - ``gamma`` - exponent of power law - ``tries`` - number of attempts to adjust sequence to make a tree - ``seed`` - for the random number generator EXAMPLE: We show the edge list of a random graph with 10 nodes and a power law exponent of 2. :: sage: graphs.RandomTreePowerlaw(10, 2).edges(labels=False) [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (6, 8), (6, 9)] :: sage: G = graphs.RandomTreePowerlaw(15, 2) sage: if G: ... G.show() # random output, long time """ if seed is None: seed = current_randstate().long_seed() import networkx try: return graph.Graph(networkx.random_powerlaw_tree(n, gamma, seed=seed, tries=tries)) except networkx.NetworkXError: return False
def generate_powerlaw(self, n, gamma=3): "Generates a random powerlaw tree using nx.random_powerlaw_tree" done = False tries = 1000 while (tries < 10000000 and not done): try: self.G = nx.random_powerlaw_tree(n, gamma, tries=10000, create_using=nx.DiGraph) self.G = nx.DiGraph(self.G) done = True except nx.NetworkXError: done = False tries *= 10 if not done: print("Unable to generate such powerlaw tree. Try a smaller graph") print("Aborting") sys.exit(1)
def create_random_graph(model_name, node_count, terminal_count=5): """Creates a random graph according to some model. Args: model_name: which model to use for the random graph node_count: number of nodes in the graph terminal_count: number of terminals in the graph Returns: graph: the graph in networkx format terminals: the terminals in a list Raises: ValueError: if model_name is not a valid model name """ if model_name == "gnp": graph = nx.gnp_random_graph(node_count, 0.01) elif model_name == "lobster": graph = nx.random_lobster(node_count, 0.1, 0.1) elif model_name == "powerlaw_tree": graph = nx.random_powerlaw_tree(node_count) elif model_name == "powerlaw_cluster": # n = the number of nodes # m = the number of random edges to add for each new node # p = probability of adding a triangle after adding a random edge graph = nx.powerlaw_cluster_graph(node_count, 10, 0.1) elif model_name == "barabasi_albert": graph = nx.barabasi_albert_graph(node_count, 3) elif model_name == "connected_watts_strogatz": graph = nx.connected_watts_strogatz_graph(node_count, 10, 0.1) elif model_name == "newman_watts_strogatz": graph = nx.newman_watts_strogatz_graph(node_count, 10, 0.1) else: raise ValueError("") for edge in graph.edges(): graph[edge[0]][edge[1]]["capacity"] = random.randint(1, 11) terminals = range(terminal_count) return graph, terminals
def create_graph(self, params): # case statements on type of graph if self.type == 'small_world': self.graph = nx.watts_strogatz_graph(int(params[0]), int(params[1]), float(params[2]), None if len(params) < 4 else int(params[3])) cg.SWC += 1 self.idx = cg.SWC self.path = 'smallWorldGraphs' elif self.type == 'small_world_connected': self.graph = nx.connected_watts_strogatz_graph(int(params[0]), int(params[1]), float(params[2]), 100 if len(params) < 4 else int(params[3]), None if len(params) < 5 else int(params[4])) cg.SWCC += 1 self.idx = cg.SWCC self.path = 'smallWorldConnectedGraphs' elif self.type == 'small_world_newman': self.graph = nx.newman_watts_strogatz_graph(int(params[0]), int(params[1]), float(params[2]), None if len(params) < 4 else int(params[3])) cg.SWNC += 1 self.idx = cg.SWNC self.path = 'smallWorldNewmanGraphs' elif self.type == 'power_law': self.graph = nx.powerlaw_cluster_graph(int(params[0]), int(params[1]), float(params[2]), None if len(params) < 4 else int(params[3])) cg.PLC += 1 self.idx = cg.PLC self.path = 'powerLawGraphs' elif self.type == 'power_law_tree': self.graph = nx.random_powerlaw_tree(int(params[0]), 3 if len(params) < 2 else float(params[1]), None if len(params) < 3 else int(params[2]), 100 if len(params) < 4 else int(params[3])) cg.PLTC += 1 self.idx = cg.PLTC self.path = 'powerLawTreeGraphs' elif self.type == 'random_graph': self.graph = nx.gnm_random_graph(int(params[0]), int(params[1]), None if len(params) < 3 else int(params[2]), False if len(params) < 4 else bool(params[3])) cg.RGC += 1 self.idx = cg.RGC self.path = 'randomGraphs' elif self.type == 'erdos_renyi_random': self.graph = nx.erdos_renyi_graph(int(params[0]), float(params[1]), None if len(params) < 3 else int(params[2]), False if len(params) < 4 else bool(params[3])) cg.ERRC += 1 self.idx = cg.ERRC self.path = 'erdosRenyiRandomGraphs' else: print 'GRAPH TYPE:', self.type raise Exception('Invalid Type of Graph input into argv[2]')
def gen_laplacian(data_num=DATA_NUM, opt=27, cache=False): label = None if cache: print('Loading cached graph') graph = pk.load(open('tmp/g.pk', 'rb')) else: print('Generating graph opt {}'.format(opt)) if 1 == opt: graph = gen_rand_graph(data_num=data_num) if 2 == opt: top_num = random.randint(1, data_num) bottom_num = data_num - top_num graph = nx.bipartite.random_graph(top_num, bottom_num, 0.9) label = [d['bipartite'] for n, d in graph.nodes(data=True)] elif 3 == opt: graph = nx.balanced_tree(4, 5) elif 4 == opt: graph = nx.complete_graph(data_num) elif 5 == opt: no1 = random.randint(1, data_num) no2 = random.randint(1, int(data_num / no1)) no3 = data_num / no1 / no2 graph = nx.complete_multipartite_graph(no1, no2, no3) elif 6 == opt: graph = nx.circular_ladder_graph(data_num) elif 7 == opt: graph = nx.cycle_graph(data_num) elif 8 == opt: graph = nx.dorogovtsev_goltsev_mendes_graph(5) elif 9 == opt: top_num = int(random.random() * data_num) bottom_num = data_num / top_num graph = nx.grid_2d_graph(top_num, bottom_num) elif 10 == opt: no1 = random.randint(1, data_num) no2 = random.randint(1, int(data_num / no1)) no3 = data_num / no1 / no2 graph = nx.grid_graph([no1, no2, no3]) elif 11 == opt: graph = nx.hypercube_graph(10) elif 12 == opt: graph = nx.ladder_graph(data_num) elif 13 == opt: top_num = int(random.random() * data_num) bottom_num = data_num - top_num graph = nx.lollipop_graph(top_num, bottom_num) elif 14 == opt: graph = nx.path_graph(data_num) elif 15 == opt: graph = nx.star_graph(data_num) elif 16 == opt: graph = nx.wheel_graph(data_num) elif 17 == opt: graph = nx.margulis_gabber_galil_graph(35) elif 18 == opt: graph = nx.chordal_cycle_graph(data_num) elif 19 == opt: graph = nx.fast_gnp_random_graph(data_num, random.random()) elif 20 == opt: # jump eigen value graph = nx.gnp_random_graph(data_num, random.random()) elif 21 == opt: # disconnected graph graph = nx.dense_gnm_random_graph(data_num, data_num / 2) elif 22 == opt: # disconnected graph graph = nx.gnm_random_graph(data_num, data_num / 2) elif 23 == opt: graph = nx.erdos_renyi_graph(data_num, data_num / 2) elif 24 == opt: graph = nx.binomial_graph(data_num, data_num / 2) elif 25 == opt: graph = nx.newman_watts_strogatz_graph(data_num, 5, random.random()) elif 26 == opt: graph = nx.watts_strogatz_graph(data_num, 5, random.random()) elif 26 == opt: # smooth eigen graph = nx.connected_watts_strogatz_graph(data_num, 5, random.random()) elif 27 == opt: # smooth eigen graph = nx.random_regular_graph(5, data_num) elif 28 == opt: # smooth eigen graph = nx.barabasi_albert_graph(data_num, 5) elif 29 == opt: # smooth eigen graph = nx.powerlaw_cluster_graph(data_num, 5, random.random()) elif 30 == opt: # smooth eigen graph = nx.duplication_divergence_graph(data_num, random.random()) elif 31 == opt: p = random.random() q = random.random() graph = nx.random_lobster(data_num, p, q) elif 32 == opt: p = random.random() q = random.random() k = random.random() graph = nx.random_shell_graph([(data_num / 3, 50, p), (data_num / 3, 40, q), (data_num / 3, 30, k)]) elif 33 == opt: # smooth eigen top_num = int(random.random() * data_num) bottom_num = data_num - top_num graph = nx.k_random_intersection_graph(top_num, bottom_num, 3) elif 34 == opt: graph = nx.random_geometric_graph(data_num, .1) elif 35 == opt: graph = nx.waxman_graph(data_num) elif 36 == opt: graph = nx.geographical_threshold_graph(data_num, .5) elif 37 == opt: top_num = int(random.random() * data_num) bottom_num = data_num - top_num graph = nx.uniform_random_intersection_graph( top_num, bottom_num, .5) elif 39 == opt: graph = nx.navigable_small_world_graph(data_num) elif 40 == opt: graph = nx.random_powerlaw_tree(data_num, tries=200) elif 41 == opt: graph = nx.karate_club_graph() elif 42 == opt: graph = nx.davis_southern_women_graph() elif 43 == opt: graph = nx.florentine_families_graph() elif 44 == opt: graph = nx.complete_multipartite_graph(data_num, data_num, data_num) # OPT 1 # norm_lap = nx.normalized_laplacian_matrix(graph).toarray() # OPT 2: renormalized # pk.dump(graph, open('tmp/g.pk', 'wb')) # plot_graph(graph, label) # note difference: normalized laplacian and normalzation by eigenvalue norm_lap, eigval, eigvec = normalize_lap(graph) return graph, norm_lap, eigval, eigvec
def tree(N, seed): """ Creates a tree of size N with a power law degree distribution """ return nx.random_powerlaw_tree(N, seed=seed, tries=10000)
import networkx as nx import random n = input() m = input() n = int(n) m = int(m) G = nx.random_powerlaw_tree(n, tries=999999) edges = set(G.edges()) nodelist = list(G.nodes()) while (G.number_of_edges() < m): u, v = random.choices(nodelist, k=2) if (u, v) not in edges and (v, u) not in edges: G.add_edge(u, v) edges.add((u, v)) G = nx.connected_component_subgraphs(G).__next__() print(n, m) print(*random.choices(nodelist, k=2)) for u, v in G.edges(): print(u, v, random.randrange(n))
def random_powerlaw_tree(N): G = nx.random_powerlaw_tree(N,tries=10000) return G
def random_powerlaw(): g = networkx.DiGraph() t = networkx.random_powerlaw_tree(500, gamma=3, tries=1000, seed=160290) return networkx.compose(g, t)
#!/usr/bin/python3 # -*- coding: utf-8 -*- import networkx as nx import random for i in range(100, 1001, 100): n = i G = nx.random_powerlaw_tree(n, tries=1000000) for (u, v, w) in G.edges(data=True): w['weight'] = random.randint(0, 10) m = G.number_of_edges() tamanios = "{}\n{}\n".format(n, m) tamaniosBytes = bytes(tamanios, "utf-8") with open("experimentacion/arbol/arbol" + str(i) + ".txt", "wb") as file: # te hace el open y el close file.write(tamaniosBytes) nx.write_weighted_edgelist(G, file)
# print (str(G.edges)) # print (visited) # print ("::::::::::::::::::::::::::::::-----------------") break print(complex) return M # generate the tree graph # n = 4000 # G = nx.empty_graph(n) # G.add_edges_from(list(_tree_edges(n,3))) # G = nx.balanced_tree(2,5) G = nx.random_powerlaw_tree(n=7, gamma=3, seed=None, tries=1000000) H = G.copy() nx.write_adjlist(G, "test.adjlist") start_time = time.time() # IM = induced_matching(H) # print(str(len(G.nodes()))+"---"+str(len(G.edges()))+"---" + # str(len(IM))+"--- %s seconds ---" % (time.time() - start_time)) k = 2 DkM = distancekmatching(H, k) print( str(len(G.nodes())) + "---" + str(len(G.edges())) + "---" + str(len(DkM)) + "--- %s seconds ---" % (time.time() - start_time)) Try = BreadthFirstKLevels(G, 0, k - 1) #Testing
fig = plt.figure(figsize=(fig_width / flp.DPI, fig_height / flp.DPI), dpi=flp.DPI) gs = mpl.gridspec.GridSpec(1, 5, width_ratios=[1, 3, 3, 1, 3]) # plot heatmap on 15 nodes ax = plt.subplot(gs[0, 0]) ax.invert_yaxis() data = np.array([ 0.5, 0.6, 0.5, 0.7, 0.6, 0.8, 0.7, 0.9, 0.5, 0.6, 0.2, 0.1, 0.05, 0.2, 0.1 ]) flp.plot_vec(data, ax, vmin=0.0, vmax=1.0) inds = [1, 2, 4] for i, ind in enumerate(inds): mapping = {} for j, k in enumerate(range(i * 5, (i + 1) * 5)): mapping[j] = k ax = plt.subplot(gs[0, ind]) n_nodes = 5 G = nx.random_powerlaw_tree(n_nodes) G = nx.relabel_nodes(G, mapping) flp.plot_graph(G, ax) ax = plt.subplot(gs[0, 3]) ax.axis('off') ax.axvline(x=0.5, linewidth=4, color='black') plt.savefig(args.outfile, bbox_inches='tight')
def make_graph(self, dimension): sys.setrecursionlimit(1500) return nx.random_powerlaw_tree(dimension, seed=self.data_random_seed, tries=dimension**2)
def test_random_graph(self): seed = 42 G = nx.gnp_random_graph(100, 0.25, seed) G = nx.gnp_random_graph(100, 0.25, seed, directed=True) G = nx.binomial_graph(100, 0.25, seed) G = nx.erdos_renyi_graph(100, 0.25, seed) G = nx.fast_gnp_random_graph(100, 0.25, seed) G = nx.fast_gnp_random_graph(100, 0.25, seed, directed=True) G = nx.gnm_random_graph(100, 20, seed) G = nx.gnm_random_graph(100, 20, seed, directed=True) G = nx.dense_gnm_random_graph(100, 20, seed) G = nx.watts_strogatz_graph(10, 2, 0.25, seed) assert len(G) == 10 assert G.number_of_edges() == 10 G = nx.connected_watts_strogatz_graph(10, 2, 0.1, tries=10, seed=seed) assert len(G) == 10 assert G.number_of_edges() == 10 pytest.raises(nx.NetworkXError, nx.connected_watts_strogatz_graph, 10, 2, 0.1, tries=0) G = nx.watts_strogatz_graph(10, 4, 0.25, seed) assert len(G) == 10 assert G.number_of_edges() == 20 G = nx.newman_watts_strogatz_graph(10, 2, 0.0, seed) assert len(G) == 10 assert G.number_of_edges() == 10 G = nx.newman_watts_strogatz_graph(10, 4, 0.25, seed) assert len(G) == 10 assert G.number_of_edges() >= 20 G = nx.barabasi_albert_graph(100, 1, seed) G = nx.barabasi_albert_graph(100, 3, seed) assert G.number_of_edges() == (97 * 3) G = nx.barabasi_albert_graph(100, 3, seed, nx.complete_graph(5)) assert G.number_of_edges() == (10 + 95 * 3) G = nx.extended_barabasi_albert_graph(100, 1, 0, 0, seed) assert G.number_of_edges() == 99 G = nx.extended_barabasi_albert_graph(100, 3, 0, 0, seed) assert G.number_of_edges() == 97 * 3 G = nx.extended_barabasi_albert_graph(100, 1, 0, 0.5, seed) assert G.number_of_edges() == 99 G = nx.extended_barabasi_albert_graph(100, 2, 0.5, 0, seed) assert G.number_of_edges() > 100 * 3 assert G.number_of_edges() < 100 * 4 G = nx.extended_barabasi_albert_graph(100, 2, 0.3, 0.3, seed) assert G.number_of_edges() > 100 * 2 assert G.number_of_edges() < 100 * 4 G = nx.powerlaw_cluster_graph(100, 1, 1.0, seed) G = nx.powerlaw_cluster_graph(100, 3, 0.0, seed) assert G.number_of_edges() == (97 * 3) G = nx.random_regular_graph(10, 20, seed) pytest.raises(nx.NetworkXError, nx.random_regular_graph, 3, 21) pytest.raises(nx.NetworkXError, nx.random_regular_graph, 33, 21) constructor = [(10, 20, 0.8), (20, 40, 0.8)] G = nx.random_shell_graph(constructor, seed) def is_caterpillar(g): """ A tree is a caterpillar iff all nodes of degree >=3 are surrounded by at most two nodes of degree two or greater. ref: http://mathworld.wolfram.com/CaterpillarGraph.html """ deg_over_3 = [n for n in g if g.degree(n) >= 3] for n in deg_over_3: nbh_deg_over_2 = [ nbh for nbh in g.neighbors(n) if g.degree(nbh) >= 2 ] if not len(nbh_deg_over_2) <= 2: return False return True def is_lobster(g): """ A tree is a lobster if it has the property that the removal of leaf nodes leaves a caterpillar graph (Gallian 2007) ref: http://mathworld.wolfram.com/LobsterGraph.html """ non_leafs = [n for n in g if g.degree(n) > 1] return is_caterpillar(g.subgraph(non_leafs)) G = nx.random_lobster(10, 0.1, 0.5, seed) assert max([G.degree(n) for n in G.nodes()]) > 3 assert is_lobster(G) pytest.raises(nx.NetworkXError, nx.random_lobster, 10, 0.1, 1, seed) pytest.raises(nx.NetworkXError, nx.random_lobster, 10, 1, 1, seed) pytest.raises(nx.NetworkXError, nx.random_lobster, 10, 1, 0.5, seed) # docstring says this should be a caterpillar G = nx.random_lobster(10, 0.1, 0.0, seed) assert is_caterpillar(G) # difficult to find seed that requires few tries seq = nx.random_powerlaw_tree_sequence(10, 3, seed=14, tries=1) G = nx.random_powerlaw_tree(10, 3, seed=14, tries=1)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import networkx as nx import sys from numpy.random import * args = sys.argv seed(114) a = int(args[1]) # T = nx.random_powerlaw_tree(50, 2, 14, 10) for i in range(1, 11): T = nx.random_powerlaw_tree(a, tries=4000) n, m = len(list(T.nodes)), len(list(T.edges)) name = "PowerLawTree" + str(n) + "_" + str('{0:02d}'.format(i)) + ".in" file = open(name, 'w') print(n, m) file.write(str(n) + " " + str(m) + "\n") for e in list(T.edges): print(e[0], " ", end="") print(e[1]) file.write(str(e[0]) + " " + str(e[1]) + "\n")
@author: croncaioli """ import networkx as nx from random import randint, sample import matplotlib.pyplot as plt #Feed in values numNodes = 25 #population of random graph initInfected = 1 #num initial infected # G = nx.random_powerlaw_tree(numNodes,gamma=2.5, tries = 10000) for i in G.nodes(): G.nodes[i]['bool'] = False for i in sample(G.nodes(),initInfected): G.nodes[i]['bool'] = True #node walking algorithm for network def randFriendIter(network): iterNodes = [] for i in network: if network.nodes[i]['bool']:
def run_simulation(args): p_other_pathways = 970 pathway_order = 300 k_latent = 30 m_samples = 1000 n_genes = 20000 alpha = 5 # parameter for gamma distribution dirichlet_param = np.ones(k_latent) / k_latent np.random.seed(args.seed) pathways = [] all_pathway_members = [] for k in range(k_latent): pathway_members = np.random.randint(0, n_genes, size=pathway_order) # TODO raises NetworkXError # TODO the tree model is easy to work with but is not realistic because a gene's expression # may be regulated by many proteins which would require a node to have multiple parents G = nx.random_powerlaw_tree(pathway_order, gamma=3, seed=args.seed, tries=100000) mapping = {} for i in range(len(pathway_members)): mapping[i] = pathway_members[i] H = nx.relabel_nodes(G, mapping) pathways.append(H) all_pathway_members.append(pathway_members) # generate other pathways that the data is not generated from other_pathways = [] for p in range(p_other_pathways): pathway_members = np.random.randint(0, n_genes, size=pathway_order) G = nx.random_powerlaw_tree(pathway_order, gamma=3, seed=args.seed, tries=100000) mapping = {} for i in range(len(pathway_members)): mapping[i] = pathway_members[i] H = nx.relabel_nodes(G, mapping) other_pathways.append(H) # use the defined pathways to latent vectors # TODO if k_latent is different than p_pathways V_cols = [] for k in range(k_latent): pathway = pathways[k] pathway_members = all_pathway_members[k] root = pathway_members[0] node_to_val = {} node_to_val[root] = gamma.rvs(alpha, size=1)[0] # NOTE tree assumptions in this loop for edge in nx.bfs_edges(pathway, root): parent_val = node_to_val[edge[0]] node_to_val[edge[1]] = gamma.rvs(parent_val + alpha, size=1)[0] # generate off-pathway data avg_pathway_val = np.mean(list(node_to_val.values())) print(avg_pathway_val) V_col = gamma.rvs(avg_pathway_val, size=n_genes) for node, val in node_to_val.items(): V_col[node] = val V_col = V_col.reshape(n_genes, 1) V_cols.append(V_col) V = np.concatenate(V_cols, axis=1) # model mixtures of latent vectors with Dirichlet U = dirichlet.rvs(dirichlet_param, size=m_samples) X = np.dot(U, V.transpose()) return X, U, V, pathways, other_pathways
def random_powerlaw(): g = networkx.DiGraph() t = networkx.random_powerlaw_tree(500, gamma=3, tries=1000, seed=160290) graph = networkx.compose(g, t) mapping = {n: to_node_id(n) for n in graph.nodes} return networkx.relabel_nodes(graph, mapping)
# %% # for demo purpose we plot a few other network types fig, ax = plt.subplots(3, 4, figsize=(15,12)) G = nx.scale_free_graph(50) nx.draw(nx.complete_graph(50), ax=ax[0,0]) nx.draw(nx.star_graph(50), ax=ax[0,1]) nx.draw(nx.circular_ladder_graph(50), ax=ax[0,2]) nx.draw(nx.ladder_graph(50), ax=ax[0,3]) nx.draw(nx.path_graph(50), ax=ax[1,0]) nx.draw(nx.wheel_graph(50), ax=ax[1,1]) nx.draw(nx.erdos_renyi_graph(50, 0.3), ax=ax[1,2]) nx.draw(nx.barabasi_albert_graph(50, 5), ax=ax[1,3]) nx.draw(nx.random_powerlaw_tree(10), ax=ax[2,0]) nx.draw(nx.scale_free_graph(50), ax=ax[2,1]) nx.draw(nx.karate_club_graph(), ax=ax[2,2]) nx.draw(nx.les_miserables_graph(), ax=ax[2,3]) # %% [markdown] # ## Network Statistics # Calculate basic network statistics # %% # import an edgelist as a weighted directed graph filepath = r"data/sample.edgelist" G = nx.read_edgelist(filepath, create_using=nx.DiGraph,data=(('weight', int),), delimiter=' ') # %% [markdown]
import networkx as nx import numpy as np G = nx.random_powerlaw_tree(2) G.graph['K'] = 2 G.nodes[0]["unary_potential"] = np.array([2, 2]) G.nodes[1]["unary_potential"] = np.array([1, 5]) G.edges[(0, 1)]["binary_potential"] = np.array([[4, 1], [1, 3]]) G.nodes[0]['assignment'] = 0 G.nodes[1]['assignment'] = 1 nx.write_gpickle(G, "./test_graph.pickle")
print('Generating [Powerlaw Cluster Graph]') n = 100 m = 5 powerlaw_cluster_graph = nx.powerlaw_cluster_graph(n, m, 0.7) outpath = 'powerlaw_cluster_graph_' + str(n) + '_' + str(m) + '.txt' nx.write_edgelist(powerlaw_cluster_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath) print('Generating [Random Lobster]') n = 100 lobster_graph = nx.random_lobster(n, 0.7, 0.7) outpath = 'random_lobster_graph_' + str(n) + '.txt' nx.write_edgelist(lobster_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath) print('Generating [Powerlaw Tree]') n = 100 powerlaw_tree = nx.random_powerlaw_tree(n, 3, None, 10000) outpath = 'powerlaw_tree_' + str(n) + '.txt' nx.write_edgelist(powerlaw_cluster_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath) print('Generating [Bipartite Random Graph]') n = 100 m = 20 bipartite_random_graph = nx.bipartite_random_graph(n, m, 0.7) outpath = 'bipartite_random_graph_' + str(n) + '_' + str(m) + '.txt' nx.write_edgelist(bipartite_random_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath)
from sensor_placement import prob_err from sensor_placement import utilities COMPARE_EPSILON = 0.000000001 TEST_CASES = 100000 MIN_NUMBER_OF_NODES = 10 MAX_NUMBER_OF_NODES = 25 RANDOM_SEED = 14052015 random.seed(RANDOM_SEED) for test_case in xrange(TEST_CASES): n = random.randint(MIN_NUMBER_OF_NODES, MAX_NUMBER_OF_NODES) try: tree = nx.random_powerlaw_tree(n, seed=test_case, tries=100) except: print "Generating tree failed (this is due to how networkx.random_powerlaw_tree works and is OK), skipping test #%d." % test_case continue leaves = utilities.find_leaves(tree) k = random.randint(2, len(leaves)) (perr, sensors) = prob_err.optimal_placement(tree, k) (brute_perr, brute_sensors) = utilities.prob_err(tree, leaves, k) assert abs(perr - brute_perr) < COMPARE_EPSILON print "Test #%d passed!" % test_case
def create_graph(n, gtype=None, seed=None, params={}): """ Generate graph on n nodes of given type. """ total_iter = 100 cnt = 0 while True: if gtype == 'block': if params['n_blocks'] == 3: m = n // 3 g = nx.stochastic_block_model( [m, m, n - 2 * m], [[0.98, 0.01, .01], [0.01, 0.98, .01], [0.01, .01, .98]], seed=seed) elif params['n_blocks'] == 4: m = n // 4 g = nx.stochastic_block_model( [m, m, m, n - 3 * m], [[.97, 0.01, 0.01, .01], [.01, 0.97, 0.01, .01], [.01, 0.01, 0.97, .01], [.01, 0.01, 0.01, .97]], seed=seed) else: m = n // 2 g = nx.stochastic_block_model([m, n - m], [[0.99, 0.01], [0.01, 0.99]], seed=seed) elif gtype == 'strogatz': g = nx.connected_watts_strogatz_graph(n, max(n // 4, 3), p=.05, seed=seed) elif gtype == 'random_regular': #d = max(n//4, 2) d*n must be even d = max(n // 8, 2) if n * d % 2 == 1: n += 1 g = nx.random_regular_graph(d, n, seed=seed) elif gtype == 'binomial': #also erdos renyi graph prob = params['prob'] g = nx.binomial_graph(n, prob, seed=seed) elif gtype == 'barabasi': d = max(4, n // 6) g = nx.barabasi_albert_graph(n, d, seed=seed) elif gtype == 'powerlaw_tree': g = nx.random_powerlaw_tree(n, gamma=3, tries=1300, seed=seed) elif gtype == 'caveman': n_cliques = params['n_cliques'] clique_sz = params['clique_sz'] assert n_cliques * clique_sz == n g = nx.connected_caveman_graph(n_cliques, clique_sz) #elif gtype == 'binomial': # prob = params['prob'] # g = nx.binomial_graph(n, prob, seed=seed) elif gtype == 'random_geometric': radius = params['radius'] g = nx.random_geometric_graph(n, radius, seed=seed) elif gtype == 'barbell': #note these are not numbers of nodes! g = nx.barbell_graph(n // 2, 1) elif gtype == 'ladder': g = nx.ladder_graph(n) elif gtype == 'grid': g = nx.grid_graph([n, n]) elif gtype == 'hypercube': g = nx.hypercube_graph(n) elif gtype == 'pappus': g = nx.pappus_graph() elif gtype == 'star': g = nx.star_graph(n) elif gtype == 'cycle': g = nx.cycle_graph(n) elif gtype == 'wheel': g = nx.wheel_graph(n) elif gtype == 'lollipop': g = nx.lollipop_graph(n // 2, 1) else: raise Exception('graph type not supported ', gtype) remove_isolates(g) cnt += 1 if nx.is_connected(g) or cnt > total_iter: if cnt > total_iter: g = g.subgraph( sorted(nx.connected_components(g), key=len)[-1]).copy() break return g