def permute_network(G, Q): """Permutes the given graph G=(V, E) by performing | E | * Q edge swaps. :type G: NetworkX Graph :param G: PPI network. :type Q: int :type Q: int :param Q: constant multiplier for number Q * | E | of edge swaps to perform (default and suggested value: 100). See `Milo et al. (2003) <http://goo.gl/d723i>`_ for details on choosing Q. :returns: a permuted version of H (G is not modified) **Examples:** A view of example input: >>> import networkx as nx >>> G = nx.Graph() >>> G.add_edges_from([["G1", "G2"], ["G2", "G3"], ["G2", "G4"], ["G1", "G4"], ["G2", "G5"], ["G5", "G6"], ["G5", "G7"]]) >>> nx.draw_spectral(G, node_size=125, font_size=8) .. image:: /_static/ppi_network.* Permuting the network by performing | E | * 10 edge swaps. >>> permute_network(G, 10) .. image:: /_static/permuted_ppi_network.* **See also:** :func:`load_network`, :func:`multi_dendrix.permute.mutation_data.permute_mutation_data`. **Notes:** Uses the NetworkX `double_edge_swap <http://goo.gl/wWxBD>`_ function. """ H = G.copy() nx.double_edge_swap(H, nswap=Q*len( G.edges() ), max_tries=1e75) return H
def permute_network(G, Q): """Permutes the given graph G=(V, E) by performing | E | * Q edge swaps. :type G: NetworkX Graph :param G: PPI network. :type Q: int :type Q: int :param Q: constant multiplier for number Q * | E | of edge swaps to perform (default and suggested value: 100). See `Milo et al. (2003) <http://goo.gl/d723i>`_ for details on choosing Q. :returns: a permuted version of H (G is not modified) **Examples:** A view of example input: >>> import networkx as nx >>> G = nx.Graph() >>> G.add_edges_from([["G1", "G2"], ["G2", "G3"], ["G2", "G4"], ["G1", "G4"], ["G2", "G5"], ["G5", "G6"], ["G5", "G7"]]) >>> nx.draw_spectral(G, node_size=125, font_size=8) .. image:: /_static/ppi_network.* Permuting the network by performing | E | * 10 edge swaps. >>> permute_network(G, 10) .. image:: /_static/permuted_ppi_network.* **See also:** :func:`load_network`, :func:`multi_dendrix.permute.mutation_data.permute_mutation_data`. **Notes:** Uses the NetworkX `double_edge_swap <http://goo.gl/wWxBD>`_ function. """ H = G.copy() nx.double_edge_swap(H, nswap=Q * len(G.edges()), max_tries=1e75) return H
def main(): gDat = open("orig_graphs/rt-assad.mtx", 'rb') # Read the node and edge numbers firstLine = gDat.readline().split() # Load the rest of the data into a networkx network graph = nx.read_edgelist(gDat) for i in range(1000): # Shuffle the network nx.double_edge_swap(graph, nswap=10000, max_tries=1000000) # Load the network into another file with proper formatting filename = "graphs/socfb_cal_" + str(i) + ".dat" # g_filename = "global_graphs/socfb_cal_" + str(i) + ".dat" output = [firstLine] # g_output = [] for line in nx.generate_edgelist(graph): vals = line.split() output.append([int(vals[0]), int(vals[1])]) # g_output.append([int(vals[0]), int(vals[1])]) np.savetxt(open(filename, "wb"), output, fmt="%s") # np.savetxt(open(g_filename, "wb"), g_output, delimiter='\t', fmt="%s") print(filename)
def rand_perm(G, var, permutation=10): '''Randomly reconnect a network then calculate the proportion of edges between the nodes of interest using the edge_counter function. NOTE: not implemented for directed or weighted networks currently G -NetworkX graph object var -variable of interest to calculate proportion for. Currently only implemented for a binary node attritube permutations -Number of graph rewirings to complete. Default is set to 10 ''' true_value = edge_counter(G, var, print_result=False) numb = len(G.edges()) simulist = [] G_copy = G.copy() for i in range(permutation): nx.double_edge_swap(G_copy, nswap=(numb / 2), max_tries=numb * 100) sim_value = edge_counter(G_copy, var, print_result=False) simulist.append(sim_value) df = pd.DataFrame() df['simu'] = simulist return df
def randomize_edges(g): """randomize a network using double-edged swaps. Note: This is used to randomize only the within-edges. A separate algorithm (randomize_graph_outedges) is used to randomize between-edges""" size = g.size() # number of edges in graph nx.double_edge_swap(g, nswap=100 * size, max_tries=10000000 * size)
def random_graph(G, Q=10): ''' Create a random graph that preserves degree distribution by swapping pairs of edges (double edge swap). Inputs: G: networkx graph Q: constant that determines how many swaps to conduct for every edge in the graph Default Q =10 Returns: R: networkx graph CAVEAT: If it is not possible in 15 attempts to create a connected random graph then this code will just return the original graph (G). This means that if you come to look at the values that are an output of calculate_global_measures and see that the values are the same for the random graph as for the main graph it is not necessarily the case that the graph is random, it may be that the graph was so low cost (density) that this code couldn't create an appropriate random graph! This should only happen for ridiculously low cost graphs that wouldn't make all that much sense to investigate anyway... so if you think carefully it shouldn't be a problem.... I hope! ''' import networkx as nx # Copy the graph R = G.copy() # Calculate the number of edges and set a constant # as suggested in the nx documentation E = R.number_of_edges() # Start with assuming that the random graph is not connected # (because it might not be after the first permuatation!) connected=False attempt=0 # Keep making random graphs until they are connected! while not connected and attempt < 15: # Now swap some edges in order to preserve the degree distribution print 'Creating random graph - may take a little while!' nx.double_edge_swap(R,Q*E,max_tries=Q*E*10) # Check that this graph is connected! If not, start again connected = nx.is_connected(R) if not connected: attempt +=1 if attempt == 15: print 'Giving up - can not randomise graph' print '===================================' R = G.copy() return R
def random_graph(G, Q=10): ''' Create a random graph that preserves degree distribution by swapping pairs of edges (double edge swap). Inputs: G: networkx graph Q: constant that determines how many swaps to conduct for every edge in the graph Default Q =10 Returns: R: networkx graph CAVEAT: If it is not possible in 15 attempts to create a connected random graph then this code will just return the original graph (G). This means that if you come to look at the values that are an output of calculate_global_measures and see that the values are the same for the random graph as for the main graph it is not necessarily the case that the graph is random, it may be that the graph was so low cost (density) that this code couldn't create an appropriate random graph! This should only happen for ridiculously low cost graphs that wouldn't make all that much sense to investigate anyway... so if you think carefully it shouldn't be a problem.... I hope! ''' import networkx as nx # Copy the graph R = G.copy() # Calculate the number of edges and set a constant # as suggested in the nx documentation E = R.number_of_edges() # Start with assuming that the random graph is not connected # (because it might not be after the first permuatation!) connected = False attempt = 0 # Keep making random graphs until they are connected! while not connected and attempt < 15: # Now swap some edges in order to preserve the degree distribution print 'Creating random graph - may take a little while!' nx.double_edge_swap(R, Q * E, max_tries=Q * E * 10) # Check that this graph is connected! If not, start again connected = nx.is_connected(R) if not connected: attempt += 1 if attempt == 15: print 'Giving up - can not randomise graph' print '===================================' R = G.copy() return R
def rewiringNX(Network, Probf): if len(Network.edges) != 0: nx.double_edge_swap(Network, Probf * len(Network.edges) * 0.5, max_tries=len(Network.edges)) else: pass return Network
def randomize_graph(G): """randomize a network using double-edged swaps. Note: This is used to randomize only the within-edges. A separate algorithm (randomize_graph_outedges) is used to randomize between-edges""" size = G.size() # number of edges in graph its = 1 for counter in range(its): nx.double_edge_swap(G, nswap=5 * size, max_tries=10000 * size)
def rewire_random_edges_preserving_degree(self, layer_tries): # TODO add connected_double_edge_swap in the future :) rewired_net = copy.deepcopy(self._network) layers_to_rewire = list(rewired_net.layers_names) layers_to_rewire = random.choices(layers_to_rewire, k=layer_tries) for layer_name in layers_to_rewire: nx.double_edge_swap(rewired_net.specified_layer(layer_name)) return rewired_net
def dpr_rewire(G, nswap, max_tries, num_graphs, path): new_G = G.copy() i = 0 while i < num_graphs: nx.write_edgelist(new_G, data=False, path=path+'_rewired%d.txt' % (i)) i += 1 nx.double_edge_swap(new_G, nswap=nswap, max_tries=max_tries) return
def rewiring_easy(G): #Funcion de grafo G que toma un grafo y realiza un recableado #manteniendo el grado de cada nodo. numero_enlaces = G.number_of_edges() #Realizamos un numero de swaps del orden de los nodos de la red for i in range(0, int(numero_enlaces)): nx.double_edge_swap(G, nswap=1) return (G)
def getThetaDist(G, num_shuffles, num_graphs, debug=False): data = [] for i in range(num_graphs): nx.double_edge_swap(G, nswap=num_shuffles, max_tries=(10 * num_shuffles)) data.append(getCritTheta(G)) if debug: print i return data
def watts_2D(Nh, Nv, pr): Gw=nx.grid_2d_graph(Nh, Nv, periodic=False) nx.double_edge_swap(Gw, nswap=pr*Nh*Nv*4, max_tries=100) Gs=nx.Graph() Gs.add_nodes_from(Gw.nodes(),state=1.0) Gs.add_edges_from(Gw.edges(),weight=1.0) ##remove self-edges Gs.remove_edges_from(Gs.selfloop_edges()) return Gs
def watts_2D(Nh, Nv, pr): Gw = nx.grid_2d_graph(Nh, Nv, periodic=False) nx.double_edge_swap(Gw, nswap=pr * Nh * Nv * 4, max_tries=100) Gs = nx.Graph() Gs.add_nodes_from(Gw.nodes(), state=1.0) Gs.add_edges_from(Gw.edges(), weight=1.0) ##remove self-edges Gs.remove_edges_from(Gs.selfloop_edges()) return Gs
def degree_shuffNet(network): shuff_time = time.time() edge_len=len(network.edges()) shuff_net=network.copy() try: nx.double_edge_swap(shuff_net, nswap=edge_len, max_tries=edge_len*10) except: print 'Note: Maximum number of swap attempts ('+repr(edge_len*10)+') exceeded before desired swaps achieved ('+repr(edge_len)+').' # Evaluate Network Similarity shared_edges = len(set(network.edges()).intersection(set(shuff_net.edges()))) print 'Network shuffled:', time.time()-shuff_time, 'seconds. Edge similarity:', shared_edges/float(edge_len) return shuff_net
def gen_dpr_exact_maxgen_all(G, nswap, max_tries, num_graphs, theta, max_gen, path): new_G = G.copy() T = [] # a list of event counts node_list = [] # a list of init nodes i = 0 while i < num_graphs: nx.write_edgelist(new_G, data=False, path=path+'_rewired%d.txt' % (i)) T_i = exact_hawkes_maxgen_all(new_G, max_gen, theta) nodes = [np.int(e) for e in list(new_G.nodes)] i += 1 T.append(T_i) node_list.append(nodes) nx.double_edge_swap(new_G, nswap=nswap, max_tries=max_tries) return np.array(T), np.array(node_list)
def randomize_network(G, times=100, seed=9999): ''' Randomizes an undirected, unweighted network using the algorithm from rgraph input: output: ''' #Set the seed random.seed(seed) #Calculate the number of iterations num_edges = G.number_of_edges() niter = int(times * (num_edges + random.random())) #Swap with the networkx method nx.double_edge_swap(G, nswap=niter, max_tries=10 * niter) return G
def gen_rand_matrix(seed): # Network size = 20 #! Note: directed = False produces a symmetric matrix random.seed(seed) L = 20 K = 4 p0 = K / (L - 1) regular = watts_strogatz(beta=0, directed=False, L=L, p0=p0) G = nx.Graph() G.add_nodes_from(np.arange(0, 20)) for i in np.arange(0, 20): for j in np.arange(0, 20): if regular[i, j] == 1: G.add_edge(i, j) reg_G = nx.to_numpy_matrix(G) di = np.diag_indices(20) random_G = nx.double_edge_swap(nx.from_numpy_matrix(reg_G), nswap=20, max_tries=1000) random_G2 = nx.to_numpy_matrix(random_G) di = np.diag_indices(20) random_G2[di] = 1 random_G2_revised = np.asarray(preserve_self_loops(random_G2, edges=5)) random_G2_norm = D_norm(random_G2_revised) return random_G2_norm
def _update_one_step(self, G): max_trials = self._config['max_trials'] n_attacks = self._config['n_attacks'] success = False Gorig, Rorig = G, R(G, n=n_attacks) Gnew, Rnew = Gorig, Rorig trials = 0 while trials != max_trials: trials += 1 Gnew = nx.double_edge_swap(Gorig.copy()) Rnew = R(Gnew, n=n_attacks) self.log_v( 'compare R ({0:3f} and {1:3f} at {2:d} trial)' .format(Rorig, Rnew, trials) ) if Rnew > Rorig: success = True break if success: self.log_v( 'optimize success R = {0:3f} -> {1:3f} after {2:d} trials' .format(Rorig, Rnew, trials) ) else: self.log_v( 'optimize failed after {0:d} trials' .format(trials) ) return success, Gnew
def rich_club_coefficient_vic(G, normalized=True, Q=100): if nx.number_of_selfloops(G) > 0: raise Exception('rich_club_coefficient is not implemented for ' 'graphs with self loops.') rc = _compute_rc_vic(G) if normalized: R = G.copy() E = R.number_of_edges() nx.double_edge_swap(R, Q * E, max_tries=Q * E * 10) rcran = _compute_rc_vic(R) for it in range(len(rcran)): if rcran[it] == 0: rcran[it] = 1 rc = {k: v / rcran[k] for k, v in rc.items()} return rc
def init_graph(self): """Improve the functionality of our graph """ one_percent_of_nodes = self.network.number_of_nodes() * .01 num_swaps = round(one_percent_of_nodes * (self.density / 10)) self.network = nx.double_edge_swap(self.network, nswap=num_swaps, max_tries=num_swaps * 10)
def run(args): # Load unpermuted network. edge_list = load_edge_list(args.edge_list_file, unweighted=True) # Permute network. G = nx.Graph() G.add_edges_from(edge_list) if args.seed is not None: random.seed(args.seed) minimum_swaps = int(math.ceil(args.Q*G.number_of_edges())) if not args.connected: G = nx.double_edge_swap(G, minimum_swaps, 2**30) else: # If G is not connected, then we perform the connected double edge swap algorithm on a # largest connected component of G. if not nx.is_connected(G): G = max(nx.connected_component_subgraphs(G), key=len) # The current connected double edge swap algorithm does not guarantee a minimum number of # successful edge swaps, so we enforce it. current_swaps = 0 while current_swaps<minimum_swaps: remaining_swaps = max(minimum_swaps-current_swaps, 100) additional_swaps = nx.connected_double_edge_swap(G, remaining_swaps) current_swaps += additional_swaps permuted_edge_list = G.edges() # Save permuted_network. save_edge_list(args.permuted_edge_list_file, permuted_edge_list)
def random_graph(G, Q=10, seed=None): ''' Return a connected random graph that preserves degree distribution by swapping pairs of edges, using :func:`networkx.double_edge_swap`. Parameters ---------- G : :class:`networkx.Graph` Q : int, optional constant that specifies how many swaps to conduct for each edge in G seed : int, random_state or None (default) Indicator of random state to pass to networkx Returns ------- :class:`networkx.Graph` Raises ------ Exception if it is not possible in 15 attempts to create a connected random graph. ''' R = anatomical_copy(G) # Calculate the number of edges and set a constant # as suggested in the nx documentation E = R.number_of_edges() # Start the counter for randomisation attempts and set connected to False attempt = 0 connected = False # Keep making random graphs until they are connected while not connected and attempt < 15: # Now swap some edges in order to preserve the degree distribution nx.double_edge_swap(R, Q * E, max_tries=Q * E * 10, seed=seed) # Check that this graph is connected! If not, start again connected = nx.is_connected(R) if not connected: attempt += 1 if attempt == 15: raise Exception("** Failed to randomise graph in first 15 tries -\ Attempt aborted. Network is likely too sparse **") return R
def watts_new(n,nb,pr,double_swap=False): Gs=nx.Graph() if double_swap==False: Gw=nx.watts_strogatz_graph(n, nb, pr) else: Gw=nx.watts_strogatz_graph(n, nb, 0.0) nx.double_edge_swap(Gw, nswap=int(pr*n*nb/2.), max_tries=10000) Gs.add_nodes_from(Gw.nodes(),state=1.0,parameters={}) Gs.add_edges_from(Gw.edges(),weight=1.0) ##remove self-edges Gs.remove_edges_from(Gs.selfloop_edges()) return Gs
def watts_hex(Ny, Nx, pr=0.5): Gs = nx.Graph() Gs.add_nodes_from(range(0, Nx * Ny), state=1.0) for iy in range(0, Ny): for ix in range(0, Nx): ni = iy * Nx + ix nj1 = iy * Nx + sp.mod(ix + 1, Nx) nj2 = sp.mod(iy + 1, Ny) * Nx + ix nj3 = sp.mod(iy + 1, Ny) * Nx + sp.mod(ix + 1, Nx) Gs.add_edges_from(((ni, nj1), (ni, nj2), (ni, nj3)), weight=1.0) nx.double_edge_swap(Gs, nswap=int(pr * Nx * Ny * 3), max_tries=10000) ##remove self-edges Gs.remove_edges_from(Gs.selfloop_edges()) return Gs
def watts_new(n, nb, pr, double_swap=False): Gs = nx.Graph() if double_swap == False: Gw = nx.watts_strogatz_graph(n, nb, pr) else: Gw = nx.watts_strogatz_graph(n, nb, 0.0) nx.double_edge_swap(Gw, nswap=int(pr * n * nb / 2.), max_tries=10000) Gs.add_nodes_from(Gw.nodes(), state=1.0, parameters={}) Gs.add_edges_from(Gw.edges(), weight=1.0) ##remove self-edges Gs.remove_edges_from(Gs.selfloop_edges()) return Gs
def watts_hex(Ny,Nx,pr=0.5): Gs=nx.Graph() Gs.add_nodes_from(range(0,Nx*Ny),state=1.0) for iy in range(0,Ny): for ix in range(0,Nx): ni = iy*Nx+ix nj1 = iy*Nx+sp.mod(ix+1,Nx) nj2 = sp.mod(iy+1,Ny)*Nx+ix nj3 = sp.mod(iy+1,Ny)*Nx+sp.mod(ix+1,Nx) Gs.add_edges_from(((ni,nj1),(ni,nj2),(ni,nj3)),weight=1.0) nx.double_edge_swap(Gs, nswap=int(pr*Nx*Ny*3), max_tries=10000) ##remove self-edges Gs.remove_edges_from(Gs.selfloop_edges()) return Gs
def gen_ddm(self): for i in range(1, self.seed + 1): g = self.duplication_divergence_model(0.5) for j in range(10, self.rewire + 1, 10): num_rewire = int(j * self.edges / 100) g_tmp = nx.double_edge_swap(g, num_rewire, self.edges) self.graphs_rewire.append(g_tmp) self.labels_rewire.append(4) self.graphs.append(g) self.labels.append(4)
def gen_geo(self): for i in range(1, self.seed + 1): g = nx.random_geometric_graph(self.nodes, 0.042) for j in range(10, self.rewire + 1, 10): num_rewire = int(j * self.edges / 100) g_tmp = nx.double_edge_swap(g, num_rewire, self.edges) self.graphs_rewire.append(g_tmp) self.labels_rewire.append(3) self.graphs.append(g) self.labels.append(3)
def gen_pam(self): for i in range(1, self.seed + 1): g = nx.barabasi_albert_graph(self.nodes, self.avg_deg, seed=i) for j in range(10, self.rewire + 1, 10): num_rewire = int(j * self.edges / 100) g_tmp = nx.double_edge_swap(g, num_rewire, self.edges) self.graphs_rewire.append(g_tmp) self.labels_rewire.append(1) self.graphs.append(g) self.labels.append(1)
def swap_edges(self): # Random small world # Random mix of edges # Reverso of edges logging.info('Starting Edge Swap') self.G = nx.double_edge_swap(self.G, 50, 150) logging.info('Finished Edge Swap') return self
def gen_er(self): for i in range(1, self.seed + 1): g = nx.erdos_renyi_graph(self.nodes, self.density, seed=i, directed=False) for j in range(10, self.rewire + 1, 10): num_rewire = int(j * self.edges / 100) g_tmp = nx.double_edge_swap(g, num_rewire, self.edges) self.graphs_rewire.append(g_tmp) self.labels_rewire.append(2) self.graphs.append(g) self.labels.append(2)
def gen_pam(self): for i in range(1, self.seed + 1): g = nx.barabasi_albert_graph(self.nodes, self.avg_deg, seed=i) for j in range(10, self.rewire + 1, 10): num_rewire = int(j*self.edges/100) g_tmp = nx.double_edge_swap(g, num_rewire, self.edges) self.graphs_rewire.append(g_tmp) self.labels_rewire.append(1) self.graphs.append(g) self.labels.append(1)
def get_random_graph_d(B): G = nx.from_numpy_matrix(B) L = nx.number_of_edges(G) trial = L*(L-1.)/2 swap_num = L; if L >2: RG = nx.double_edge_swap(G,nswap=swap_num,max_tries=trial) return RG else: print "No swap possible for number of edges", L return G
def get_random_graph_d(B): G = nx.from_numpy_matrix(B) L = nx.number_of_edges(G) trial = L * (L - 1.) / 2 swap_num = L if L > 2: RG = nx.double_edge_swap(G, nswap=swap_num, max_tries=trial) return RG else: print "No swap possible for number of edges", L return G
def doSwap(graph): edges = random.sample(graph.edges(), 2) g = nx.Graph() g.add_edges_from(edges) while edges[0] == edges[1] or len(g.nodes()) < 4: edges = random.sample(graph.edges(), 2) g = nx.Graph() g.add_edges_from(edges) gCopy = nx.double_edge_swap(g) swap = list(gCopy.edges()) return edges, swap
def watts_truss(Ny, Nx, pr=0.1, double_swap=True): #,tri_swap=False): Gs = nx.Graph() for iy in range(0, Ny): for ix in range(0, Nx): Gs.add_node(iy * Nx + ix, state=1.0, xloc=ix, yloc=iy) for iy in range(0, Ny): for ix in range(0, Nx): ni = iy * Nx + ix nj1 = iy * Nx + sp.mod(ix + 1, Nx) nj2 = sp.mod(iy + 1, Ny) * Nx + ix nj3 = sp.mod(iy + 1, Ny) * Nx + sp.mod(ix + 1, Nx) Gs.add_edges_from(((ni, nj1), (ni, nj2), (ni, nj3), (nj1, nj2)), weight=1.0) #if tri_swap==True: # triad_swap(Gs, nswap=int(pr*Nx*Ny*4)) if double_swap == True: nx.double_edge_swap(Gs, nswap=int(pr * Nx * Ny * 4), max_tries=10000) else: nodes = list(Gs) for sw in range(int(pr * Nx * Ny * 4)): edges = Gs.edges() re = int(len(edges) * sp.random.random()) Gs.remove_edge(edges[re][0], edges[re][1]) nodes = list(Gs) n1 = int(len(nodes) * sp.random.random()) for tries in range(0, int(1e6)): n2 = int(len(nodes) * sp.random.random()) if n2 != n1 and (n1, n2) not in edges and (n2, n1) not in edges: break Gs.add_edge(n1, n2, weight=1.0) ##remove self-edges Gs.remove_edges_from(Gs.selfloop_edges()) return Gs
def watts_truss(Ny,Nx,pr=0.1,double_swap=True): #,tri_swap=False): Gs=nx.Graph() for iy in range(0,Ny): for ix in range(0,Nx): Gs.add_node(iy*Nx+ix,state=1.0,xloc=ix,yloc=iy) for iy in range(0,Ny): for ix in range(0,Nx): ni = iy*Nx+ix nj1 = iy*Nx+sp.mod(ix+1,Nx) nj2 = sp.mod(iy+1,Ny)*Nx+ix nj3 = sp.mod(iy+1,Ny)*Nx+sp.mod(ix+1,Nx) Gs.add_edges_from(((ni,nj1),(ni,nj2),(ni,nj3),(nj1,nj2)),weight=1.0) #if tri_swap==True: # triad_swap(Gs, nswap=int(pr*Nx*Ny*4)) if double_swap==True: nx.double_edge_swap(Gs, nswap=int(pr*Nx*Ny*4), max_tries=10000) else: nodes=list(Gs) for sw in range(int(pr*Nx*Ny*4)): edges=Gs.edges() re=int(len(edges)*sp.random.random()) Gs.remove_edge(edges[re][0],edges[re][1]) nodes=list(Gs) n1=int(len(nodes)*sp.random.random()) for tries in range(0,int(1e6)): n2=int(len(nodes)*sp.random.random()) if n2!=n1 and (n1,n2) not in edges and (n2,n1) not in edges: break Gs.add_edge(n1,n2,weight=1.0) ##remove self-edges Gs.remove_edges_from(Gs.selfloop_edges()) return Gs
def random_network(graph, dirwrite, start=0, end=0, weighted=False): import os #dirn = 'rand' if not os.path.exists(dirwrite): os.mkdir(dirwrite) todo = range(1000) if start > 0: todo = range(start, end) for i in todo: towrite = dirwrite + '/' + str(i) + '.net' if os.path.exists(towrite): continue rnd = graph if not weighted: rnd = networkx.double_edge_swap(graph, nswap=graph.number_of_edges()*4,max_tries = graph.number_of_edges()*8) else: rnd = double_edge_swap_weighted(graph, nswap=graph.number_of_edges()*4,max_tries = graph.number_of_edges()*8) networkx.write_edgelist(rnd, towrite, data=weighted,delimiter="\t")
def _find_best(self): GList, RList = [], [] n = 0 self.log_v( 'generating neighbor solution from <{:X}>' .format(id(self.Gc)) ) while n <= self.Ng: n += 1 G1 = nx.double_edge_swap(self.Gc.copy()) if self._is_matches_to_tabu(G1): continue R1 = R(G1) GList.append(G1) RList.append(R1) # findbest in the paper return max(zip(GList, RList), key=lambda t: t[1])[0]
def swap_edges(self): # Random small world # Random mix of edges # Reverso of edges self.G = nx.double_edge_swap(self.G, 50, 150) return self
def rich_club_coefficient(G, normalized=True, Q=100): """Return the rich-club coefficient of the graph G. The rich-club coefficient is the ratio, for every degree k, of the number of actual to the number of potential edges for nodes with degree greater than k: .. math:: \\phi(k) = \\frac{2 Ek}{Nk(Nk-1)} where Nk is the number of nodes with degree larger than k, and Ek be the number of edges among those nodes. Parameters ---------- G : NetworkX graph normalized : bool (optional) Normalize using randomized network (see [1]_) Q : float (optional, default=100) If normalized=True build a random network by performing Q*M double-edge swaps, where M is the number of edges in G, to use as a null-model for normalization. Returns ------- rc : dictionary A dictionary, keyed by degree, with rich club coefficient values. Examples -------- >>> G = nx.Graph([(0,1),(0,2),(1,2),(1,3),(1,4),(4,5)]) >>> rc = nx.rich_club_coefficient(G,normalized=False) >>> rc[0] # doctest: +SKIP 0.4 Notes ----- The rich club definition and algorithm are found in [1]_. This algorithm ignores any edge weights and is not defined for directed graphs or graphs with parallel edges or self loops. Estimates for appropriate values of Q are found in [2]_. References ---------- .. [1] Julian J. McAuley, Luciano da Fontoura Costa, and Tibério S. Caetano, "The rich-club phenomenon across complex network hierarchies", Applied Physics Letters Vol 91 Issue 8, August 2007. http://arxiv.org/abs/physics/0701290 .. [2] R. Milo, N. Kashtan, S. Itzkovitz, M. E. J. Newman, U. Alon, "Uniform generation of random graphs with arbitrary degree sequences", 2006. http://arxiv.org/abs/cond-mat/0312028 """ if G.is_multigraph() or G.is_directed(): raise Exception('rich_club_coefficient is not implemented for ', 'directed or multiedge graphs.') if G.number_of_selfloops() > 0: raise Exception('rich_club_coefficient is not implemented for ', 'graphs with self loops.') rc=_compute_rc(G) if normalized: # make R a copy of G, randomize with Q*|E| double edge swaps # and use rich_club coefficient of R to normalize R = G.copy() E = R.number_of_edges() nx.double_edge_swap(R,Q*E,max_tries=Q*E*10) rcran=_compute_rc(R) for d in rc: # if rcran[d] > 0: rc[d]/=rcran[d] return rc
def main(args): #model_name = args.model Nodes = args.N rho = args.rho Edges = int(rho * Nodes * (Nodes -1) / 2) seed = args.seed seq = args.num max_rewire = args.rewire folder = './'+'dataset_'+str(seq)+'/' folder_rewire = './'+'dataset_rewire_'+str(seq) os.system("mkdir "+folder) density = rho os.system("mkdir "+folder_rewire) avg_deg = int(2*Edges / Nodes) print avg_deg ''' if model_name=='PAM': for i in range(1,seed+1): file_name = folder+'PAM_'+str(Nodes)+'_'+str(Edges)+'_'+str(i)+'.txt' G = nx.barabasi_albert_graph(Nodes,avg_deg,seed=i) nx.write_edgelist(G,file_name) if model_name=='ER': for i in range(1,seed+1): file_name = folder+'ER_'+str(Nodes)+'_'+str(Edges)+'_'+str(i)+'.txt' G = nx.erdos_renyi_graph(Nodes, density,seed=i, directed=False ) nx.write_edgelist(G,file_name) if model_name=='GEO': for i in range(1,seed+1): file_name = folder+'GEO_'+str(Nodes)+'_'+str(Edges)+'_'+str(i)+'.txt' G = nx.random_geometric_graph(Nodes, seed=i) nx.write_edgelist(G,file_name) if model_name == 'DDM': for i in range(1,seed+1): file_name = folder+'DDM_'+str(Nodes)+'_'+str(Edges)+'_'+str(i)+'.txt' sigma = 0.5 G = duplication_divergence_model(Nodes,Edges,sigma) nx.write_edgelist(G,file_name) ''' for i in xrange(10,max_rewire,10): folder_tmp = folder_rewire + '/'+'dataset_rewirerate_'+str(i) os.system('mkdir '+folder_tmp) for i in range(1,seed+1): file_name = folder+'PAM_'+str(Nodes)+'_'+str(rho)+'_'+str(i)+'.txt' G = nx.barabasi_albert_graph(Nodes,avg_deg,seed=i) for j in xrange(10,max_rewire,10): num_rewire = int(j*Edges/100) print num_rewire G_tmp = nx.double_edge_swap(G,num_rewire,Edges) folder_tmp = folder_rewire + '/'+'dataset_rewirerate_'+str(j) file_name_rewire = folder_tmp +'/'+'R_PAM_'+str(Nodes)+'_'+str(rho)+'_'+str(i)+'.txt' nx.write_edgelist(G_tmp,file_name_rewire) nx.write_edgelist(G,file_name) for i in range(1,seed+1): file_name = folder+'ER_'+str(Nodes)+'_'+str(rho)+'_'+str(i)+'.txt' G = nx.erdos_renyi_graph(Nodes, density,seed=i, directed=False ) for j in xrange(10,max_rewire,10): num_rewire = int(j*Edges/100) print num_rewire G_tmp = nx.double_edge_swap(G,num_rewire,Edges) folder_tmp = folder_rewire + '/'+'dataset_rewirerate_'+str(j) file_name_rewire = folder_tmp +'/'+'R_ER_'+str(Nodes)+'_'+str(rho)+'_'+str(i)+'.txt' nx.write_edgelist(G_tmp,file_name_rewire) nx.write_edgelist(G,file_name) for i in range(1,seed+1): file_name = folder+'GEO_'+str(Nodes)+'_'+str(rho)+'_'+str(i)+'.txt' G = nx.random_geometric_graph(Nodes, 0.042) print nx.density(G) nx.write_edgelist(G,file_name) for j in xrange(10,max_rewire,10): num_rewire = int(j*Edges/100) print num_rewire G_tmp = nx.double_edge_swap(G,num_rewire,Edges) folder_tmp = folder_rewire + '/'+'dataset_rewirerate_'+str(j) file_name_rewire = folder_tmp +'/'+'R_GEO_'+str(Nodes)+'_'+str(rho)+'_'+str(i)+'.txt' nx.write_edgelist(G_tmp,file_name_rewire) for i in range(1,seed+1): file_name = folder+'DDM_'+str(Nodes)+'_'+str(rho)+'_'+str(i)+'.txt' sigma = 0.5 G = duplication_divergence_model(Nodes,Edges,sigma) for j in xrange(10,max_rewire,10): num_rewire = int(j*Edges/100) print num_rewire G_tmp = nx.double_edge_swap(G,num_rewire,Edges) folder_tmp = folder_rewire + '/'+'dataset_rewirerate_'+str(j) file_name_rewire = folder_tmp +'/'+'R_DDM_'+str(Nodes)+'_'+str(rho)+'_'+str(i)+'.txt' nx.write_edgelist(G_tmp,file_name_rewire) nx.write_edgelist(G,file_name)
def rich_club_coefficient(G, normalized=True, Q=100): """Return the rich-club coefficient of the graph G. The rich-club coefficient is the ratio, for every degree k, of the actual to the potential edges for nodes with degree greater than k. If Nk is the number of nodes with degree larger than k, and Ek be the number of edges among those nodes, the rich club coefficient is .. math:: \\phi(k) = \\frac{2 Ek}{Nk(Nk-1)} Parameters ---------- G : NetworkX graph The graph used to compute the rich-club coefficient normalized : bool (optional) Normalize using randomized network (see [1]_) Q : float (optional) If normalized=True build a random network by performing Q*M double-edge swaps, where M is the number of edges in G, to use as a null-model for normalization. Returns ------- rc : dictionary A dictionary keyed by degree with rich club coefficient values. Notes ------ The definition and algorithm are found in [1]_. This algorithm ignores self-loop edges and edge weights and is not defined for directed graphs or graphs with parallel edges. Estimates for appropriate values of Q are found in [2]_. References ---------- .. [1] Julian J. McAuley, Luciano da Fontoura Costa, and Tiberio S. Caetano, 'The rich-club phenomenon across complex network hierarchies', Applied Physics Letters Vol 91 Issue 8, August 2007. http://arxiv.org/abs/physics/0701290 .. [2] R. Milo, N. Kashtan, S. Itzkovitz, M. E. J. Newman, U. Alon, 'Uniform generation of random graphs with arbitrary degree sequences', 2006. http://arxiv.org/abs/cond-mat/0312028 """ if G.is_directed(): raise Exception('rich_club_coefficient is not implemented for ', 'directed or multiedge graphs.') if len(G.selfloop_edges()) > 0: raise Exception('rich_club_coefficient is not implemented for ', 'graphs with self loops.') rc=_compute_rc(G) if normalized: # make R a copy of G, randomize with Q*|E| double edge swaps # and use rich_club coefficient of R to normalize R = G.copy() E = R.number_of_edges() nx.double_edge_swap(R,Q*E) rcran=_compute_rc(R) for d in rc: if rcran[d] > 0: rc[d]/=rcran[d] else: rc[d] = float('infinity') return rc
def rich_club_coefficient(G, normalized=True, Q=100, seed=None): r"""Returns the rich-club coefficient of the graph `G`. For each degree *k*, the *rich-club coefficient* is the ratio of the number of actual to the number of potential edges for nodes with degree greater than *k*: .. math:: \phi(k) = \frac{2 E_k}{N_k (N_k - 1)} where `N_k` is the number of nodes with degree larger than *k*, and `E_k` is the number of edges among those nodes. Parameters ---------- G : NetworkX graph Undirected graph with neither parallel edges nor self-loops. normalized : bool (optional) Normalize using randomized network as in [1]_ Q : float (optional, default=100) If `normalized` is True, perform `Q * m` double-edge swaps, where `m` is the number of edges in `G`, to use as a null-model for normalization. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- rc : dictionary A dictionary, keyed by degree, with rich-club coefficient values. Examples -------- >>> G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)]) >>> rc = nx.rich_club_coefficient(G, normalized=False) >>> rc[0] # doctest: +SKIP 0.4 Notes ----- The rich club definition and algorithm are found in [1]_. This algorithm ignores any edge weights and is not defined for directed graphs or graphs with parallel edges or self loops. Estimates for appropriate values of `Q` are found in [2]_. References ---------- .. [1] Julian J. McAuley, Luciano da Fontoura Costa, and Tibério S. Caetano, "The rich-club phenomenon across complex network hierarchies", Applied Physics Letters Vol 91 Issue 8, August 2007. https://arxiv.org/abs/physics/0701290 .. [2] R. Milo, N. Kashtan, S. Itzkovitz, M. E. J. Newman, U. Alon, "Uniform generation of random graphs with arbitrary degree sequences", 2006. https://arxiv.org/abs/cond-mat/0312028 """ if nx.number_of_selfloops(G) > 0: raise Exception('rich_club_coefficient is not implemented for ' 'graphs with self loops.') rc = _compute_rc(G) if normalized: # make R a copy of G, randomize with Q*|E| double edge swaps # and use rich_club coefficient of R to normalize R = G.copy() E = R.number_of_edges() nx.double_edge_swap(R, Q * E, max_tries=Q * E * 10, seed=seed) rcran = _compute_rc(R) rc = {k: v / rcran[k] for k, v in rc.items()} return rc
import networkx as nx import matplotlib.pyplot as plt import numpy as np filename = "CA-CondMat.txt" RN = nx.read_edgelist(filename) n_RN = nx.number_of_edges(RN) RN_list = [RN] for i in range(4): RN_list.append(nx.double_edge_swap(RN.copy(), nswap = int(n_RN*(i+1)*0.1), max_tries = 2*(i+1)*n_RN)) nx.write_edgelist(RN_list[i],'RN_' + str(i+1) + '.txt', data = False) nn_RN = nx.number_of_nodes(RN) avg_deg_of_node = np.mean((RN.degree()).values()) GN_list = [] for i in range(5): GN_list.append(nx.barabasi_albert_graph(nn_RN+1000*i, int(avg_deg_of_node))) nx.write_edgelist(GN_list[i],'GN_'+str(i+1)+'.txt', data = False)