def ws_gen(n, k, p): """ Given some parameterization n, k, p, generate a random WS network and calucualte C(p) and L(p) """ G=nx.watts_strogatz_graph(n, k, p) while nx.number_connected_components(G)>1: G=nx.watts_strogatz_graph(n, k, p) return({'p':p, 'cc':nx.average_clustering(G), 'avg.pl':nx.average_shortest_path_length(G)})
def create_network(self): if self.network_topology == "small-world": G = nx.watts_strogatz_graph(self.number_of_agents, self.mean_degree, self.watts_strogatz_rewiring_probability) elif self.network_topology == "scale-free": G = nx.barabasi_albert_graph(self.number_of_agents, int(self.mean_degree/2)) elif self.network_topology == "ring": G = nx.watts_strogatz_graph(self.number_of_agents, self.mean_degree, 0) elif self.network_topology == "random": G = nx.watts_strogatz_graph(self.number_of_agents, self.mean_degree, 1) mapping = dict(enumerate(self.agents_list)) self.agents_network = nx.relabel_nodes(G, mapping)
def compare_graphs(graph): n = nx.number_of_nodes(graph) m = nx.number_of_edges(graph) k = np.mean(list(nx.degree(graph).values())) erdos = nx.erdos_renyi_graph(n, p=m/float(n*(n-1)/2)) barabasi = nx.barabasi_albert_graph(n, m=int(k)-7) small_world = nx.watts_strogatz_graph(n, int(k), p=0.04) print(' ') print('Compare the number of edges') print(' ') print('My network: ' + str(nx.number_of_edges(graph))) print('Erdos: ' + str(nx.number_of_edges(erdos))) print('Barabasi: ' + str(nx.number_of_edges(barabasi))) print('SW: ' + str(nx.number_of_edges(small_world))) print(' ') print('Compare average clustering coefficients') print(' ') print('My network: ' + str(nx.average_clustering(graph))) print('Erdos: ' + str(nx.average_clustering(erdos))) print('Barabasi: ' + str(nx.average_clustering(barabasi))) print('SW: ' + str(nx.average_clustering(small_world))) print(' ') print('Compare average path length') print(' ') print('My network: ' + str(nx.average_shortest_path_length(graph))) print('Erdos: ' + str(nx.average_shortest_path_length(erdos))) print('Barabasi: ' + str(nx.average_shortest_path_length(barabasi))) print('SW: ' + str(nx.average_shortest_path_length(small_world))) print(' ') print('Compare graph diameter') print(' ') print('My network: ' + str(nx.diameter(graph))) print('Erdos: ' + str(nx.diameter(erdos))) print('Barabasi: ' + str(nx.diameter(barabasi))) print('SW: ' + str(nx.diameter(small_world)))
def __init__(self, iter_count, step_count, G=None, **kwargs): ''' Set up a new batch runner. Args: iter_count: Number of model instances to create and run step_count: How many steps to run each model for. G: If not None, initialize all models on the same graph. **kwargs: Any model parameters to set. ''' self.model_outputs = [] self.models = [] self.outputs = [] self.step_count = step_count # Prepare models while len(self.models) < iter_count: if G is None: # Here comes the hard-coded bit G = nx.watts_strogatz_graph(10, 3, 0.2) if not nx.is_connected(G): continue m = Model(G) # Set the parameters: for attr, val in kwargs.items(): if hasattr(m, attr): setattr(m, attr, val) # Coerce minimum and maximum depth # TODO: Better solution for this for agent in m.agents.values(): agent.max_depth = random.randint(m.min_depth, m.max_depth) self.models.append(m)
def q1(): # given in question infection_rate = 0.25 recovery_rate = 0.30 # from NetLogo model file (may be incorrect!) num_nodes = 200 num_neighbors = 4 xvals = range(0, 20000) for p_rewire in [0.0, 1.0]: G = nx.watts_strogatz_graph(num_nodes, num_neighbors, p_rewire) infected = np.zeros(num_nodes, dtype=int) # randomly infect one of the nodes random_node = random.uniform(0, num_nodes) infected[random_node] = 1 yvals = [] for xval in xvals: for node in range(0, num_nodes): if infected[node] == 1: if random.uniform(0, 1) <= recovery_rate: infected[node] = 0 continue if random.uniform(0, 1) <= infection_rate: neighbors = G[node].keys() for neighbor in neighbors: infected[neighbor] = 1 num_infected = len(infected[infected == 1]) print("For p=%f, timeunit=%d, #-infected=%d" % (p_rewire, xval, num_infected)) yvals.append(num_infected) plt.plot(xvals, yvals, color='b' if p_rewire == 0 else 'r') plt.show()
def get_graph(objects, properties): graph_type = properties['graph_type'] n = len(objects)-1 if 'num_nodes_to_attach' in properties.keys(): k = properties['num_nodes_to_attach'] else: k = 3 r = properties['connection_probability'] tries = 0 while(True): if graph_type == 'random': x = nx.fast_gnp_random_graph(n,r) elif graph_type == 'erdos_renyi_graph': x = nx.erdos_renyi_graph(n,r) elif graph_type == 'watts_strogatz_graph': x = nx.watts_strogatz_graph(n, k, r) elif graph_type == 'newman_watts_strogatz_graph': x = nx.newman_watts_strogatz_graph(n, k, r) elif graph_type == 'barabasi_albert_graph': x = nx.barabasi_albert_graph(n, k, r) elif graph_type == 'powerlaw_cluster_graph': x = nx.powerlaw_cluster_graph(n, k, r) elif graph_type == 'cycle_graph': x = nx.cycle_graph(n) else: ##Star by default x = nx.star_graph(len(objects)-1) tries += 1 cc_conn = nx.connected_components(x) if len(cc_conn) == 1 or tries > 5: ##best effort to create a connected graph! break return x, cc_conn
def patch_nx(): """Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3 """ import networkx as nx # Quick test to see if we get the broken version g = nx.watts_strogatz_graph(2, 0, 0) if g.number_of_nodes() != 2: # Buggy version detected. Create a patched version and apply it to nx nx._watts_strogatz_graph_ori = nx.watts_strogatz_graph def patched_ws(n, k, p, seed=None): if k<2: g = nx.Graph() g.add_nodes_from(range(n)) return g else: return nx._watts_strogatz_graph_ori(n, k, p, seed) patched_ws.__doc__ = nx._watts_strogatz_graph_ori.__doc__ # Applying monkeypatch now import warnings warnings.warn("Monkeypatching NetworkX's Watts-Strogatz routine") nx.watts_strogatz_graph = patched_ws
def generateRandomNetworks(randomSeed=622527): seed(randomSeed) # Network size will be 10^1, 10 ^2, 10^3, 10^4 for exponent in range(1, 4): # 1 .. 4 n = 10 ** exponent for p in [0.1, 0.3, 0.5, 0.7, 0.9]: m = round(n * p) # Generate erdos Renyi networks graph = nx.erdos_renyi_graph(n, p, randomNum()) graphName = "erdos_renyi_n{}_p{}.graph6".format(n, p) nx.write_graph6(graph, directory + graphName) # Generate Barabasi Albert networks graph = nx.barabasi_albert_graph(n, m, randomNum()) graphName = "barabasi_albert_n{}_m{}.graph6".format(n, m) nx.write_graph6(graph, directory + graphName) for k in [0.1, 0.3, 0.5, 0.7, 0.9]: k = round(n * k) # Generate Watts Strogatz networks graph = nx.watts_strogatz_graph(n, k, p, randomNum()) graphName = "watts_strogatz_n{}_k{}_p{}.graph6".format(n, k, p) nx.write_graph6(graph, directory + graphName)
def __init__(self, n=1000, k=10, p=0.02947368): self.n = n self.k = k self.p = p self.ws = nx.watts_strogatz_graph(self.n, self.k, self.p, seed='nsll') nx.set_node_attributes(self.ws, 'SIR', 'S') self.clustering = nx.clustering(self.ws) self.betweenness = nx.betweenness_centrality(self.ws) p_r_0 = 0.001 r_0 = int(self.n * p_r_0) if r_0 < 1: r_0 = 1 random.seed('nsll') self.r = random.sample(self.ws.nodes(), r_0) i_0 = 4 if i_0 < r_0: i_0 += 1 random.seed('nsll') self.infected = random.sample(self.ws.nodes(), i_0) for n in self.infected: self.ws.node[n]['SIR'] = 'I' for n in self.r: self.ws.node[n]['SIR'] = 'R' self.s = self.n - len(self.infected) - len(self.r) print(self.r) print(self.infected)
def correlation_betweenness_degree_on_WS(): n = 1000 k = 4 p = 0.01 G = nx.watts_strogatz_graph(n, k, p) print nx.info(G) ND, ND_lambda = ECT.get_number_of_driver_nodes(G) ND, driverNodes = ECT.get_driver_nodes(G) degrees = [] betweenness = [] tot_degree = nx.degree_centrality(G) tot_betweenness = nx.betweenness_centrality(G,weight=None) for node in driverNodes: degrees.append(tot_degree[node]) betweenness.append(tot_betweenness[node]) with open("results/driver_degree_WS.txt", "w") as f: for x in degrees: print >> f, x with open("results/driver_betweenness_WS.txt", "w") as f: for x in betweenness: print >> f, x with open("results/tot_degree_WS.txt", "w") as f: for key, value in tot_degree.iteritems(): print >> f, value with open("results/tot_betweenness_WS.txt", "w") as f: for key, value in tot_betweenness.iteritems(): print >> f, value
def test__init__(self): from social_meaning.agent import Agent society = nx.watts_strogatz_graph(10, 2, 0) a = Agent(mental_graph=nx.fast_gnp_random_graph(10, .1), social_network=society, node_name=society.nodes()[0]) repr(a)
def playwithkmeans(n=50,k=3,p=0.6,save=False): '''randomly generate a random Watts-Strogatz graph with n - nodes k - connected to k neighbors p - rewiring from base NN ring with prob b. Labeled graph is plotted according to kmeans clust=3 to see by eye how "well" it does WH StatConn HW 1 ''' G = nx.watts_strogatz_graph(n,k,p) pos = nx.random_layout(G) adjmat = nx.to_numpy_matrix(G) km = KMeans(n_clusters=3) kmfit = km.fit(adjmat) l = kmfit.labels_ c1 = [] c2 = [] c3 = [] for i,x in enumerate(l): if x == 0: c1.append(i) if x == 1: c2.append(i) if x == 2: c3.append(i) nx.draw_networkx_nodes(G,pos,nodelist=c1,node_color='r',node_size=500,alpha=0.8) nx.draw_networkx_nodes(G,pos,nodelist=c2,node_color='g',node_size=500,alpha=0.8) nx.draw_networkx_nodes(G,pos,nodelist=c3,node_color='b',node_size=500,alpha=0.8) nx.draw_networkx_edges(G,pos) plt.title('Random Graph G with color-coded overlay of kmeans clustering k=3') if save: plt.savefig('C:\\Users\Will\\Pictures\\graph-%s.pdf'%date.today(),format='pdf') plt.show()
def edge_attachment_test(seed=None): import math if seed==None: seed = npr.randint(1E6) print('rnd seed: %d'%seed) npr.seed(seed) random.seed(seed) nn = 30 G = nx.watts_strogatz_graph(n=nn, k=4, p=0.0) print('All new edges should lie close to the cycle') pos = {node:(math.cos(float(node)/nn * math.pi * 2),math.sin(float(node)/nn * math.pi * 2)) for node in G} def visualize_rewiring(G, added_edges_set, deled_edges_set, tpl_data): old_G = G.copy() old_G.remove_edges_from(added_edges_set) old_G.add_edges_from(deled_edges_set) print('added edges: ') print(added_edges_set) print('deled edges: ') print(deled_edges_set) benchmarks.editing_demo_draw(G=old_G, new_G=G, seed=1, pos=pos) print(tpl_data) pylab.show() params = {} params['edit_edges_tester'] = visualize_rewiring params['edge_edit_rate'] = [0.10] params['node_edit_rate'] = [0.] params['node_growth_rate'] = [0.] params['verbose'] = True algorithms.generate_graph(G, params=params)
def generate_graph(n, expected_degree, model="ba"): """ Generates a graph with a given model and expected_mean degree :param n: int Number of nodes of the graph :param expected_degree: int Expected mean degree :param model: string Model (ba, er, or ws) :return: networkx graph """ global m global ws_p g = None if model == "ba": # BA expected avg. degree? m = ba_mean_degrees() if m is None: m = ba_mean_degrees(n, expected_degree) g = nx.barabasi_albert_graph(n, m, seed=None) if model == "er": # ER expected avg. degree: d = p*(n-1) p = float(expected_degree) / float(n - 1) g = nx.erdos_renyi_graph(n, p, seed=None, directed=False) if model == "ws": # WS expected degree == k g = nx.watts_strogatz_graph(n, expected_degree, ws_p) return g
def create_small_world_graph(N_nodes,p_edge,n_infected): n = N_nodes k = int(p_edge*N_nodes) p = 0.5 #Random graph #p_coop is the fraction of cooperators G = nx.watts_strogatz_graph(n,k,p) return set_graph_strategies(G, n_infected)
def connect_watts_strogatz(self,N,k,p): """ Watts-Strogatz graph starting with a k-nearest neighbor ring. Edges are then rewired with probability p. This differs from the NWS graph in that (1) it may not be connected and (2) the mean degree will be fixed at k. """ self.connect_empty(N) self.add_edges_from(nx.watts_strogatz_graph(N,k,p).edges())
def create_WS_graphs(N, betas): """Creates list of Newman W-S graphs with N nodes and rewiring probabilities corresponding to the values in betas""" NUM_NEIGHBORS = 2 graphs = [] for beta in betas: graphs.append(networkx.watts_strogatz_graph(N, NUM_NEIGHBORS, beta)) return graphs
def generate_network(self): net_type_dict = dict( complete=nx.complete_graph(self.N), barabasi_albert=nx.barabasi_albert_graph(self.N,self.k), watts_strogatz=nx.watts_strogatz_graph(self.N,self.k, self.rewiring_prob), ) return net_type_dict[self.net_type]
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 get_ws_graph(n, p): """ Function to get a WS graph with 4 k-nearest-neighbors :param n: number of nodes :param p: probability of connection between the nodes :return: WS graph """ return nx.watts_strogatz_graph(n, 4, p)
def watts_strogatz(n, k, p): g = None for i in range(MAX_ITERATION): g = nx.watts_strogatz_graph(n, k, p) if nx.algorithms.components.is_connected(g) == True: break else: g = None return g
def test_clustering(size): print("Barabasi-Albert:") ba = networkx.barabasi_albert_graph(1000, 4) print("Clustering: ", networkx.average_clustering(ba)) print("Average length: ", networkx.average_shortest_path_length(ba)) print("Watts-Strogatz:") ws = networkx.watts_strogatz_graph(size, 4, 0.001) print("Clustering: ", networkx.average_clustering(ws)) print("Average length: ", networkx.average_shortest_path_length(ws))
def watts_strogatz_replicate(original, params=None): #warning: for simplicity of coding, the replica uses nodes labeled 0..n-1 if params == None: params = {} n = nx.number_of_nodes(original) k = params.get('k', 4) p = nx.density(original) return nx.watts_strogatz_graph(n, k, p)
def generate_network(mem_pars, net_pars): if net_pars['type']==graph_type[1]: G = nx.watts_strogatz_graph(net_pars['N'],net_pars['k'],net_pars['p']) elif net_pars['type']==graph_type[2]: G = nx.random_regular_graph(net_pars['degree'], net_pars['N']) cir = Circuit('Memristor network test') # assign dictionary with terminals and memristors memdict = {} w = mem_pars['w'] D = mem_pars['D'] Roff = mem_pars['Roff'] Ron = mem_pars['Ron'] mu = mem_pars['mu'] Tao = mem_pars['Tao'] for e in G.edges_iter(): rval = round(Roff + 0.01 * Roff * (random.random() - 0.5), 2) key = 'R' + str(e[0]) + str(e[1]) [v1, v2] = [e[0], e[1]] memdict[key] = [v1, v2, memristor.memristor(w, D, Roff, Ron, mu, Tao, 0.0)] # we set v=0.0 value in the beginning cir.add_resistor(key, 'n' + str(v1), 'n' + str(v2), rval) G[e[0]][e[1]]['weight'] = rval # edge_labels[e]=rval; for n in G.nodes_iter(): G.node[n]['number'] = n # Add random ground and voltage terminal nodes [v1, gnd] = random.sample(xrange(0, len(G.nodes())), 2) lastnode = len(G.nodes()) G.add_edge(v1, lastnode) G.node[lastnode]['number'] = 'V1' lastnode += 1 G.add_edge(gnd, lastnode) G.node[lastnode]['number'] = 'gnd' plot_graph(G) export_graph(G,'/Users/nfrik/CloudStation/Research/LaBean/ESN/FalstadSPICE/test.txt') cir.add_resistor("RG", 'n' + str(gnd), cir.gnd, 0.001) cir.add_vsource("V1", 'n' + str(v1), cir.gnd, 1000) opa = new_op() # netdict contains setup graph and circuit networkdict = {} networkdict['Graph'] = G networkdict['Circuit'] = cir networkdict['Memristors'] = memdict networkdict['Opa']=opa return networkdict
def WattsStrogatz(self, nei = 4, p = 0.2): """create Watts Strogatz graph""" # test input if type(nei) is not int: raise ValueError("Number of neigbors nei must be integer") # main procedure N = self.PopulationSize graph = nx.watts_strogatz_graph(n = N, k = nei, p = p) self.graph = graph self.adjacencyList = graph.adjacency_list()
def gen_graph(self): if self.network_structure == 'small_world': nx_graph = nx.watts_strogatz_graph(self.num_nodes, self.graph_args['k'], self.graph_args['p']) return nx_graph, self.convert_nx_graph(nx_graph) elif self.network_structure == 'erdos_renyi': nx_graph = nx.fast_gnp_random_graph(self.num_nodes, self.graph_args['p']) return nx_graph, self.convert_nx_graph(nx_graph) elif self.network_structure == 'preferential_attachment': nx_graph = nx.barabasi_albert_graph(self.num_nodes, self.graph_args['m']) return nx_graph, self.convert_nx_graph(nx_graph)
def main(): graphs = { 'star_graph': nx.star_graph(1000), 'ba_graph': nx.barabasi_albert_graph(1000, 2), 'watts_strogatz': nx.watts_strogatz_graph(1000, 4, p=0.3), 'random_regular': nx.random_regular_graph(4, 1000), } folder = 'resources/' for name, graph in graphs.iteritems(): create_graph_file(graph, folder + name)
def topo_sw(nodes): # small world bws = [1,2,3,4,5,6,7,8,9,10] network = nx.watts_strogatz_graph(nodes,2,0.3) # (n, alpha=0.4, beta=0.1, L=None, domain=(0, 0, 1, 1)): g = nx.Graph() g.add_nodes_from(network.nodes()) for link in network.edges(): bw = random.choice(bws) g.add_edge(link[0],link[1],{'weight':bw}) g.add_edge(link[1],link[0],{'weight':bw}) return g
def build_watts_strogatz_network(n=100, k=5, p=0.5, directed=False): """ Builds a Watts-Strogatz network with n nodes (default n=100) where each node is joined with its k nearest neighbors in a ring topology (default k=5) and the probability of rewiring each edge is p (default p=0.5). """ network = nx.watts_strogatz_graph(n, k, p, directed=directed) return network
def directed_watts_strogatz_graph(n, k, p, seed=None): G = nx.watts_strogatz_graph(n, k, p, seed) DG = nx.DiGraph() DG.add_nodes_from(G.nodes()) for (u, v) in G.edges_iter(): r = random.randint(0, 1) if r == 0: DG.add_edge(u, v) else: DG.add_edge(v, u) return DG
''' import matplotlib.pyplot as plt import networkx as nx from Organization_Model import Individual from Organization_Model import Organization import numpy as np #demonstrating that clustering coefficient increases with k neighbors ring lattic parameters organization_size = 200 rewiring_probability = .3 clustering_coefficients = [] for neighboring_connections in range(2, int(organization_size / 2)): K_coefficients = [] for i in range(5): graph = nx.watts_strogatz_graph(organization_size, neighboring_connections, rewiring_probability) clustering_coefficient = nx.average_clustering(graph) K_coefficients.append(clustering_coefficient) print("K = ", neighboring_connections, ": ", K_coefficients) avg_K_clustering = sum(K_coefficients)/len(K_coefficients) clustering_coefficients.append(avg_K_clustering) plt.plot(clustering_coefficients) plt.xlabel("K") plt.ylabel("Average Clustering Coefficient") plt.title("Watts-Strogatz Small World Networks: K vs Clustering Coefficient") plt.show()
open("movieLensPickleFiles/barabasiAlbert.pickle", "wb")) userToGraphNode = {} graphNodeToUser = {} j = 0 for i in G.nodes(): userToGraphNode[userIds[j]] = i graphNodeToUser[i] = userIds[j] j += 1 print(j) pickle.dump([userToGraphNode, graphNodeToUser], open("movieLensPickleFiles/mappingBarabasiAlbert.pickle", "wb")) k = 60 p = 0.15 #given that we took an average degree of 250 in Erdos Renyi we take k as 250 G = nx.watts_strogatz_graph(numberOfNodes, k, p, seed=None) print(nx.info(G)) info = nx.info(G) graphToBeUsed = [G, info] pickle.dump(graphToBeUsed, open("movieLensPickleFiles/graphWattsStrogatz.pickle", "wb")) userToGraphNode = {} graphNodeToUser = {} j = 0 for i in G.nodes(): userToGraphNode[userIds[j]] = i graphNodeToUser[i] = userIds[j] j += 1 print(j) pickle.dump([userToGraphNode, graphNodeToUser], open("movieLensPickleFiles/mappingWattsStrogatz.pickle", "wb"))
def graph_init( n=26, # number of nodes k=5, # number of single node neighbours before rewriting # edges rewire_prob=0.1, # probability of node rewrite initiation_perc=0.1, # percent of randomly informed nodes show_attr=True, # show node weights and attributes draw_graph=True): # probability of rewrite edge # in random place """ Graph initialization with watts_strogatz_graph() function. Create a graph with added weights as edges attributes, and the following nodes attributes: extraversion, receptiveness, engagement. The graph is ready to perform simulation in difpy package. Parameters ---------- n : integer Nodes number of the graph. k : integer number of single node neighbours before rewriting edges rewire_prob : float probability of rewrite edge in random place initiation_perc : float Percent of randomly aware nodes. show_attr : bool, optional Show list of wages and other generated attributes of nodes. draw_graph : bool, optional Draw graph. Returns ------- G : graph A networkx graph object. pos : dictionary with 2 element ndarrays as values Object contains positions of nodes in the graph chart. Pos is used to draw the graph after simulation step. """ #==============# # Create graph # #==============# # Create basic watts-strogatz graph G = nx.watts_strogatz_graph(n=n, k=k, p=rewire_prob, seed=None) # Compute a position of graph elements pos = nx.spring_layout(G) #======================# # Add weights to graph # #======================# # Weights - are probabilities of contact between nodes of given social # network. # Weights are randomly sampled from exponential distribution. # Values have to be scaled so we cannot add it directly to graph, # but after generation and scaling, and filling zeros with 0.000001 # for computation purposes # Create ndarray of weights weights = np.round( np.random.exponential(scale=0.1, size=G.number_of_edges()), 6).reshape(G.number_of_edges(), 1) # Scale weights to [0,1] range scaler = MinMaxScaler() scaler.fit(weights) scaled_weights = scaler.transform(weights) scaled_weights = np.round(scaled_weights, 6) # eliminate zeros for computation purposes for (x, y), i in np.ndenumerate(scaled_weights): if i == 0: scaled_weights[x, y] = 0.000001 # Add weights to the graph for i, (u, v) in enumerate(G.edges()): G[u][v]['weight'] = scaled_weights[i, 0] #============================# # Set node attribute - state # #============================# # "State" Variable levels: # * Unaware - is actor who did not internalized the information and # is not able to pass it down. Initially, all nodes are # in state: Unaware. # * Aware - is the actor who internalized the information and is able # to pass it down. nx.set_node_attributes(G, 'unaware', 'state') # (G, value, key) #====================================# # Set node attribute - receptiveness # #====================================# # Receptiveness - general parameter of each node, expressing how much # in general the actor is receptive in context of given social network. # Receptiveness is randomly sampled from normal distribution. # Create ndarray of receptiveness receptiveness = np.round(np.random.normal(size=G.number_of_edges()), 6).reshape(G.number_of_edges(), 1) # Scale weights to [0,1] range scaler = MinMaxScaler() scaler.fit(receptiveness) scaled_receptiveness = scaler.transform(receptiveness) scaled_receptiveness = np.round(scaled_receptiveness, 6) # eliminate zeros for computation purposes for (x, y), i in np.ndenumerate(scaled_receptiveness): if i == 0: scaled_receptiveness[x, y] = 0.000001 # Add receptiveness parameter to nodes for v in G.nodes(): G.nodes[v]['receptiveness'] = scaled_receptiveness[v, 0] #===================================# # Set node attribute - extraversion # #===================================# # Extraversion is agent eagerness to express itself to other agents # Extraversion is randomly sampled from normal distribution. # Create ndarray of extraversion extraversion = np.round(np.random.normal(size=G.number_of_edges()), 6).reshape(G.number_of_edges(), 1) # Scale weights to [0,1] range scaler = MinMaxScaler() scaler.fit(extraversion) scaled_extraversion = scaler.transform(extraversion) scaled_extraversion = np.round(scaled_extraversion, 6) # eliminate zeros for computation purposes for (x, y), i in np.ndenumerate(scaled_extraversion): if i == 0: scaled_extraversion[x, y] = 0.000001 # Add receptiveness parameter to nodes for v in G.nodes(): G.nodes[v]['extraversion'] = scaled_extraversion[v, 0] #=================================# # Set node attribute - engagement # #=================================# # Engagement - engagement with the information related topic, # strengthness of the experiences connected with information topic. # How much the information is objectivly relevant for actor. # Engagement is randomly sampled from exponential distribution. # Create ndarray of engagement engagement = np.round(np.random.exponential(size=G.number_of_edges()), 6).reshape(G.number_of_edges(), 1) # Scale weights to [0,1] range scaler = MinMaxScaler() scaler.fit(engagement) scaled_engagement = scaler.transform(engagement) scaled_engagement = np.round(scaled_engagement, 6) # eliminate zeros for computation purposes for (x, y), i in np.ndenumerate(scaled_engagement): if i == 0: scaled_engagement[x, y] = 0.000001 # Add receptiveness parameter to nodes for v in G.nodes(): G.nodes[v]['engagement'] = scaled_engagement[v, 0] #===================# # Random initiation # #===================# # Compute number of nodes N = G.number_of_nodes() # Return list of numbers of randomly aware agents infected_agents_id = random.sample(population=range(0, N), k=int(N * initiation_perc)) # Set those nodes as aware for v in infected_agents_id: G.nodes[v]['state'] = 'aware' #=======================# # Show nodes attributes # #=======================# if show_attr == True: print("Node attributes:") for (u, v) in G.nodes.data(): print(u, v) # Check how scaled weights looks like x = list(range(len(scaled_weights))) scaled_weights = np.sort(scaled_weights, axis=0) # show numbered values dict_0 = dict(zip(x, scaled_weights)) print("Wages:") for u, v in dict_0.items(): print(u, v) #============# # Draw graph # #============# if draw_graph == True: dp.draw_graph(G=G, pos=pos) # draw_colored_graph_2 return G, pos
def WS_graph(node_num, neighbor_num, prop): G = nx.watts_strogatz_graph(node_num, neighbor_num, prop) adj = nx.to_numpy_matrix(G) adj = np.asarray(adj) return adj
from keras.layers.core import Dense from keras.models import Sequential from keras.optimizers import SGD # List of features used in this model feature_list = [features.CompareNumOfNodes, features.CompareNumOfEdges, features.CompareDirected, features.CompareDegreeDistribution, features.CompareLSpectrum, features.CompareASpectrum] # All graph pairs are contained in this list graphPairs = [] # Base graph for all isomorphic graphs g_base_nodes = 10 g_base = nx.watts_strogatz_graph(g_base_nodes, 5, 0.1) # Create a list of isomorphic graph pairs print "Creating list of isomorphic graph pairs..." for _ in xrange(100): g = permute_graph.permute_graph(g_base, random.randint(1,g_base_nodes)) graphPair = graph_pair_class.GraphPair(g_base, g) for f in feature_list: graphPair.add_feature(f) graphPairs += [graphPair] print "Done!" # Create a list of random graph pairs print "Creating list of random graph pairs..." for _ in xrange(100): g = nx.watts_strogatz_graph(g_base_nodes, 5, 0.1)
def make_smallworld_graph(): initial_node_num = 100 #ノード数 k = 4 #エッジ数 probability = 0.1 #エッジのつなぎかえ確率 G = nx.watts_strogatz_graph(initial_node_num, k, probability) return G
import networkx as nx import matplotlib.pyplot as plt import numpy numpy.random.seed(121) er = nx.erdos_renyi_graph(100, 0.15) ws = nx.watts_strogatz_graph(30, 3, 0.1) ba = nx.barabasi_albert_graph(100, 5) red = nx.random_lobster(100, 0.9, 0.9) nx.draw(er) plt.show() nx.draw(ws) plt.show() nx.draw(ba) plt.show() nx.draw(red) plt.show()
else: continue else: next_g.nodes[node]['state'] = 0 if random() < p_r else 1 g = next_g import pycxsimulator pycxsimulator.GUI().start(func=[initialize, observe, update]) ### Friendship paradox G1 = nx.erdos_renyi_graph(1000, 0.04) G2 = nx.barabasi_albert_graph(1000, 20) G3 = nx.watts_strogatz_graph(1000, 40, p=0.05) def avg_degree(graph): tot_deg = 0 for n in graph.nodes: tot_deg += len(list(graph.neighbors(n))) return tot_deg / len(graph.nodes) def avg_neighbor_deg(graph): tot_deg = 0 for e in graph.edges: tot_deg += (len(list(graph.neighbors(e[0]))) + len(list(graph.neighbors(e[1]))))
# -*- encoding: utf-8 -*- # -*- coding: utf-8 -*- import sys import networkx from matplotlib import pylab N = int(sys.argv[1]) K = int(sys.argv[2]) graph = networkx.watts_strogatz_graph(n=N, k=K, p=0.8, seed=32) networkx.draw_spring(graph) degrees = graph.degree(graph.nodes()).values() distrib = {} for k in degrees: try: distrib[k] += 1 except KeyError: distrib[k] = 1 for k in distrib: distrib[k] = float(distrib[k]) / len(graph.nodes()) plot = distrib.items() fig = pylab.figure()
for b in tqdm(range(ensembleCount)): u = [] u = MemoryMatrix[target].copy() # copy target M to initial state Y = [] X = [] n_init = 0 n_fin = n_init + flip for count in range( n_init, n_fin): # sequentially pick up 25% of bits and flip them u[count] = (MemoryMatrix[target][count] * -1) g = nx.watts_strogatz_graph(n, k, p) st = 0 for st in range(0, n): g.nodes[st]['state'] = u[st] X.append(st) # train the network for i, j in g.edges: weight = 0 alpha = 0 for alpha in range(0, m): weight = weight + (MemoryMatrix[alpha][i] * MemoryMatrix[alpha][j]) g.edges[i, j]['weight'] = (weight / n) # evolve according to hopfield dynamics, n_i iterations
def createWattsStrogatzGraph(numNodes, numEdges): #http://networkx.readthedocs.io/en/stable/reference/generated/networkx.generators.random_graphs.watts_strogatz_graph.html?highlight=watts return nx.watts_strogatz_graph(numNodes, numEdges, 0.5, seed=random.randint(1, 1000))
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
if __name__ == '__main__': NUM_NODES = 10 MIN_SCORE = 4 NUM_TXS = 30 # TODO # transaction finality # leader election # setup network nodes = [] for k, i in enumerate(range(NUM_NODES)): n = Node(label=k) nodes.append(n) network = nx.watts_strogatz_graph(NUM_NODES, 2, 0.1) # nx.draw(network, with_labels=True, font_weight='bold') # plt.show() # connect nodes as in graph for i in range(NUM_NODES): neigh_i = list(network[i].keys()) # connect i to j connect_to = [nodes[j] for j in neigh_i] nodes[i].connect(connect_to) log.debug('node %s connected to %s', nodes[i], str(connect_to)) # propose new transactions for i in range(NUM_TXS): nodes[0].propose()
"""Common neighbor aware random walk sampler example""" import networkx as nx from littleballoffur.exploration_sampling import CommonNeighborAwareRandomWalkSampler graph = nx.watts_strogatz_graph(1000, 10, 0) sampler = CommonNeighborAwareRandomWalkSampler() new_graph = sampler.sample(graph)
# set params # n: The number of nodes # k: Each node is connected to k nearest neighbors in ring topology # ... The number of edges will same to 'n * (k // 2)'. # p: The probability of rewiring each edge N = [25, 100] K = [4, 16] P = [0.1, 0.25, 0.5, 1] # generate random grahp objects graphs = [] for i in range(100): n = random.randint(N[0], N[1]) k = random.randint(K[0], K[1]) p = P[random.randint(0, 3)] g = nx.watts_strogatz_graph(n, k, p).edges() graphs.append(g) # # make csv string files = [] for g in graphs: csv = '' for e in g: csv += str(e[0]) + ',' + str(e[1]) + '\n' files.append(csv) # # write as a csv file for (i, csv) in enumerate(files): filename = 'network(' + str(i + 1) + ').csv' f = open(filename, 'w') f.write(csv)
ephPopHistory = (epop[1].lower() == "true") elif "--ephTime" in arg: ephtime = arg.split("=") ephTime = int(ephtime[1]) elif "--graphFile" in arg: gfile = arg.split("=") graphFile = gfile[1] if operation == "newGraph": #Generate graph according to type if graphtype == "ba": newGraph = nx.barabasi_albert_graph(numNodes, numEdges) elif graphtype == "complete": newGraph = nx.complete_graph(numNodes) elif graphtype == "ws-20p": newGraph = nx.watts_strogatz_graph(numNodes, int(numEdges), 0.2) elif graphtype == "er": newGraph = nx.erdos_renyi_graph(numNodes, numEdges) while not nx.is_connected(newGraph): newGraph = nx.erdos_renyi_graph(numNodes, numEdges) else: newGraph = nx.barabasi_albert_graph(numNodes, numEdges) #print(newGraph.number_of_nodes()) #Write base graph to file nx.write_adjlist(newGraph, graphFile) file = open("opts_" + graphFile, "w") file.write(str(numNodes)) file.close()
def _init_graph(self): return nx.watts_strogatz_graph(self.stu_num, self.K, self.R, self.seed)
def main(): parser = argparse.ArgumentParser() parser.add_argument('--credit_type', help='uniform or random or lnd credit on links') parser.add_argument('--graph_type', help='small_world or scale_free or lnd graph types') parser.add_argument('--path_type', help='ksp_yen or ksp_edge_disjoint or kwp_edge_disjoint') args = parser.parse_args() n = 50 CREDIT_AMT = 100.0 RAND_SEED = 23 delay = 1 """ construct graph """ if args.graph_type == 'scale_free': graph = nx.barabasi_albert_graph(n, 8, seed=23) graph = nx.Graph(graph) graph.remove_edges_from(graph.selfloop_edges()) elif args.graph_type == 'small_world': graph = nx.watts_strogatz_graph(n, k=8, p=0.25, seed=23) graph = nx.Graph(graph) graph.remove_edges_from(graph.selfloop_edges()) elif args.graph_type == 'lnd': graph = nx.read_edgelist("../oblivious_routing/lnd_dec4_2018_reducedsize.edgelist") rename_dict = {v: int(str(v)) for v in graph.nodes()} graph = nx.relabel_nodes(graph, rename_dict) for e in graph.edges(): graph.edges[e]['capacity'] = int(str(graph.edges[e]['capacity'])) graph = nx.Graph(graph) graph.remove_edges_from(graph.selfloop_edges()) n = nx.number_of_nodes(graph) elif args.graph_type == 'sw_50_random_capacity': graph = nx.read_edgelist("../oblivious_routing/sw_50_random_capacity.edgelist") rename_dict = {v: int(str(v)) for v in graph.nodes()} graph = nx.relabel_nodes(graph, rename_dict) for e in graph.edges(): graph.edges[e]['capacity'] = int(graph.edges[e]['capacity']) graph = nx.Graph(graph) graph.remove_edges_from(graph.selfloop_edges()) n = nx.number_of_nodes(graph) else: print "Error! Graph type invalid." assert nx.is_connected(graph) """ construct credit matrix """ if args.credit_type == 'uniform': credit_mat = np.ones([n, n])*CREDIT_AMT elif args.credit_type == 'random': np.random.seed(RAND_SEED) credit_mat = np.triu(np.random.rand(n, n), 1) * 2 * CREDIT_AMT credit_mat += credit_mat.transpose() credit_mat = credit_mat.astype(int) elif args.credit_type == 'lnd': credit_mat = np.zeros([n, n]) for e in graph.edges(): credit_mat[e[0], e[1]] = graph.edges[e]['capacity']/1000 credit_mat[e[1], e[0]] = graph.edges[e]['capacity']/1000 elif args.credit_type == 'sw_50_random_capacity': credit_mat = np.zeros([n, n]) for e in graph.edges(): credit_mat[e[0], e[1]] = graph.edges[e]['capacity'] credit_mat[e[1], e[0]] = graph.edges[e]['capacity'] else: print "Error! Credit matrix type invalid." """ get paths and store in dict """ paths = {} for i in range(n): for j in range(n): if i != j: if args.path_type == 'ksp_yen': ret_paths = ksp_yen(graph, i, j, 4) elif args.path_type == 'ksp_edge_disjoint': ret_paths = ksp_edge_disjoint(graph, i, j, 4) elif args.path_type == 'kwp_edge_disjoint': ret_paths = kwp_edge_disjoint(graph, i, j, 4, credit_mat) else: print "Error! Path type invalid." new_paths = [] for ret_path in ret_paths: new_path = [] new_path.append(i) new_path = new_path + [u + n for u in ret_path] new_path.append(j) new_paths.append(new_path) paths[i, j] = new_paths print paths with open(args.graph_type + '_' + args.path_type + '.pkl', 'wb') as output: pickle.dump(paths, output, pickle.HIGHEST_PROTOCOL)
def basic_operation_tutorial(): # Create a graph. G = nx.Graph() # Nodes. G.add_node(1) G.add_nodes_from([2, 3]) H = nx.path_graph(10) # Creates a graph. G.add_nodes_from(H) G.add_node(H) #print('G.nodes = {}.'.format(G.nodes)) print('G.nodes = {}.'.format(list(G.nodes))) # Edges. G.add_edge(1, 2) e = (2, 3) G.add_edge(*e) # Unpack edge tuple. G.add_edges_from([(1, 2), (1, 3)]) G.add_edges_from(H.edges) #print('G.edges = {}.'.format(G.edges)) print('G.edges = {}.'.format(list(G.edges))) # Remove all nodes and edges. G.clear() #-------------------- G.add_edges_from([(1, 2), (1, 3)]) G.add_node(1) G.add_edge(1, 2) G.add_node('spam') # Adds node 'spam'. G.add_nodes_from('spam') # Adds 4 nodes: 's', 'p', 'a', 'm'. G.add_edge(3, 'm') print('G.number_of_nodes() = {}.'.format(G.number_of_nodes())) print('G.number_of_edges() = {}.'.format(G.number_of_edges())) # Set-like views of the nodes, edges, neighbors (adjacencies), and degrees of nodes in a graph. print('G.adj[1] = {}.'.format(list(G.adj[1]))) # or G.neighbors(1). print('G.degree[1] = {}.'.format( G.degree[1])) # The number of edges incident to 1. # Report the edges and degree from a subset of all nodes using an nbunch. # An nbunch is any of: None (meaning all nodes), a node, or an iterable container of nodes that is not itself a node in the graph. print("G.edges([2, 'm']) = {}.".format(G.edges([2, 'm']))) print('G.degree([2, 3]) = {}.'.format(G.degree([2, 3]))) # Remove nodes and edges from the graph in a similar fashion to adding. G.remove_node(2) G.remove_nodes_from('spam') print('G.nodes = {}.'.format(list(G.nodes))) G.remove_edge(1, 3) # When creating a graph structure by instantiating one of the graph classes you can specify data in several formats. G.add_edge(1, 2) H = nx.DiGraph(G) # Creates a DiGraph using the connections from G. print('H.edges() = {}.'.format(list(H.edges()))) edgelist = [(0, 1), (1, 2), (2, 3)] H = nx.Graph(edgelist) #-------------------- # Access edges and neighbors. print('G[1] = {}.'.format(G[1])) # Same as G.adj[1]. print('G[1][2] = {}.'.format(G[1][2])) # Edge 1-2. print('G.edges[1, 2] = {}.'.format(G.edges[1, 2])) # Get/set the attributes of an edge using subscript notation if the edge already exists. G.add_edge(1, 3) G[1][3]['color'] = 'blue' G.edges[1, 2]['color'] = 'red' # Fast examination of all (node, adjacency) pairs is achieved using G.adjacency(), or G.adj.items(). # Note that for undirected graphs, adjacency iteration sees each edge twice. FG = nx.Graph() FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)]) for n, nbrs in FG.adj.items(): for nbr, eattr in nbrs.items(): wt = eattr['weight'] if wt < 0.5: print(f'({n}, {nbr}, {wt:.3})') # Convenient access to all edges is achieved with the edges property. for (u, v, wt) in FG.edges.data('weight'): if wt < 0.5: print(f'({u}, {v}, {wt:.3})') #-------------------- # Attributes. # Graph attributes. G = nx.Graph(day='Friday') print('G.graph = {}.'.format(G.graph)) G.graph['day'] = 'Monday' # Node attributes: add_node(), add_nodes_from(), or G.nodes. G.add_node(1, time='5pm') G.add_nodes_from([3], time='2pm') print('G.nodes[1] = {}.'.format(G.nodes[1])) G.nodes[1]['room'] = 714 print('G.nodes.data() = {}.'.format(G.nodes.data())) print('G.nodes[1] = {}.'.format( G.nodes[1])) # List the attributes of a node. print('G.nodes[1].keys() = {}.'.format(G.nodes[1].keys())) #print('G[1] = {}.'.format(G[1])) # G[1] = G.adj[1]. # Edge attributes: add_edge(), add_edges_from(), or subscript notation. G.add_edge(1, 2, weight=4.7) G.add_edges_from([(3, 4), (4, 5)], color='red') G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})]) G[1][2]['weight'] = 4.7 G.edges[3, 4]['weight'] = 4.2 print('G.edges.data() = {}.'.format(G.edges.data())) print('G.edges[3, 4] = {}.'.format( G.edges[3, 4])) # List the attributes of an edge. print('G.edges[3, 4].keys() = {}.'.format(G.edges[3, 4].keys())) #-------------------- # Directed graphs. DG = nx.DiGraph() DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)]) print("DG.out_degree(1, weight='weight') = {}.".format( DG.out_degree(1, weight='weight'))) print("DG.degree(1, weight='weight') = {}.".format( DG.degree( 1, weight='weight'))) # The sum of in_degree() and out_degree(). print('DG.successors(1) = {}.'.format(list(DG.successors(1)))) print('DG.neighbors(1) = {}.'.format(list(DG.neighbors(1)))) # Convert G to undirected graph. #H = DG.to_undirected() H = nx.Graph(DG) #-------------------- # Multigraphs: Graphs which allow multiple edges between any pair of nodes. MG = nx.MultiGraph() #MDG = nx.MultiDiGraph() MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)]) print("MG.degree(weight='weight') = {}.".format( dict(MG.degree(weight='weight')))) GG = nx.Graph() for n, nbrs in MG.adjacency(): for nbr, edict in nbrs.items(): minvalue = min([d['weight'] for d in edict.values()]) GG.add_edge(n, nbr, weight=minvalue) print('nx.shortest_path(GG, 1, 3) = {}.'.format(nx.shortest_path(GG, 1, 3))) #-------------------- # Classic graph operations: """ subgraph(G, nbunch): induced subgraph view of G on nodes in nbunch union(G1,G2): graph union disjoint_union(G1,G2): graph union assuming all nodes are different cartesian_product(G1,G2): return Cartesian product graph compose(G1,G2): combine graphs identifying nodes common to both complement(G): graph complement create_empty_copy(G): return an empty copy of the same graph class to_undirected(G): return an undirected representation of G to_directed(G): return a directed representation of G """ #-------------------- # Graph generators. # Use a call to one of the classic small graphs: petersen = nx.petersen_graph() tutte = nx.tutte_graph() maze = nx.sedgewick_maze_graph() tet = nx.tetrahedral_graph() # Use a (constructive) generator for a classic graph: K_5 = nx.complete_graph(5) K_3_5 = nx.complete_bipartite_graph(3, 5) barbell = nx.barbell_graph(10, 10) lollipop = nx.lollipop_graph(10, 20) # Use a stochastic graph generator: er = nx.erdos_renyi_graph(100, 0.15) ws = nx.watts_strogatz_graph(30, 3, 0.1) ba = nx.barabasi_albert_graph(100, 5) red = nx.random_lobster(100, 0.9, 0.9) #-------------------- # Read a graph stored in a file using common graph formats, such as edge lists, adjacency lists, GML, GraphML, pickle, LEDA and others. nx.write_gml(red, './test.gml') mygraph = nx.read_gml('./test.gml')
import networkx as nx if __name__ == '__main__': n = int(input()) G = nx.watts_strogatz_graph(n, 4, 0.5) f = open('watts_strogatz_graph/watts_strogatz_graph_' + str(n) + '.txt', 'w') f.write(str(n) + ' ' + str(G.number_of_edges()) + '\n') for i, j in G.edges(): f.write(str(i) + ' ' + str(j) + '\n') print(nx.is_connected(G))
#%% # WS small world network import networkx as nx nx.draw_spring(nx.watts_strogatz_graph(10,4,0)) #%%
def refresh_network(self): self.memo_uncertainty_history = [] # memorizes only one generation self.fitness_history = [] if (self.network_methode[0] == 'M1' or self.network_methode[0] == 'M2'): self.graphs.append(nx.MultiGraph()) # graph for the new generation elif (self.network_methode[0] == 'M3'): if (self.network_methode[1] == 'Erdos-Renyi'): self.graphs.append(nx.gnm_random_graph( self.num_nodes, self.Max_edges)) if (self.network_methode[1] == 'Small-world'): self.graphs.append(nx.watts_strogatz_graph( self.num_nodes, self.network_methode[2], self.network_methode[3])) if (self.network_methode[1] == 'Regular-lattice'): self.graphs = [nx.watts_strogatz_graph( self.num_nodes, self.network_methode[2], 0)] (self.min_centrality, self.max_centrality) = extremum_centrality( self.graphs[0]) # create new Nodes to fully replace the existing network # get fitness of Nodes fitness = np.array([node.fitness for node in self.nodes]) mean_fitness = np.mean(fitness) fitness = fitness/np.sum(fitness) # fitness values are now normalized # random weighted choice based on fitness, select num_nodes nodes each having a probability egal to the normalized fitness reproducing_node_index = np.random.choice( self.num_nodes, self.num_nodes, p=fitness) # memory of new nodes is same as parent reproducing_node_memory = np.array( [len(self.nodes[index].size_memory) for index in reproducing_node_index]) # aggression of new nodes, same as parent reproducing_node_aggression = np.array( [self.nodes[index].aggression for index in reproducing_node_index]) # record means to see results self.history.append([mean_fitness, np.mean( reproducing_node_memory), np.mean(reproducing_node_aggression)]) # add mutations memory_mutations = np.random.standard_normal(self.num_nodes).astype( int) # mutation offsets for memory, integers from Gaussian(0,1) aggression_mutations = np.random.normal(0, 0.01, self.num_nodes).astype( 'float64') # mutation offsets for aggression, Gaussian(0, 0.05) values reproducing_node_memory += memory_mutations # mutate memory reproducing_node_aggression += aggression_mutations # mutate aggression # sizes = np.random.random_sample(self.num_nodes) #generate uniform sample of sizes del self.nodes[:] # clear current nodes for i in range(self.num_nodes): # create new nodes if (self.network_methode[0] != 'M3'): self.graphs[len(self.graphs)-1].add_node(i, key=i) #self.nodes.append(Node(sizes[i], reproducing_node_memory[i], reproducing_node_aggression[i])) # the size is: i/(self.num_nodes-1) self.nodes.append(Node( i/(self.num_nodes-1), reproducing_node_memory[i], reproducing_node_aggression[i])) # fill the initial fitness of each fish (0) self.fitness_history.append([self.nodes[i].fitness]) self.memo_uncertainty_history.append( [self.nodes[i].max_size-self.nodes[i].min_size]) self.aggression = reproducing_node_aggression self.memory = reproducing_node_memory self.graphs[0]
if __name__ == '__main__': # seeds seed = 200494 # creating path data_path = "results/WS.csv" create_data_path_file(data_path) # experiments for n in graph_sizes: # iterations for k_fraction in fractions: # determining k k = int(n * k_fraction) for p in fractions: for r in fractions: # setting seeds for reproducibility random.seed(seed) numpy.random.seed(seed) experiment_name = f"WS_{n}_{k_fraction}_{p}_{r}" graph = nx.watts_strogatz_graph(n=n, k=k, p=p) perform_experiment(original_graph=graph, ftrp=r, exp_name=experiment_name, data_path=data_path)
def generate_network(n, k, p): global G G = nx.watts_strogatz_graph(n, k, p) pos = nx.circular_layout(G)
if len(network.nodes()) > 0: giant = len( sorted(nx.connected_components(network), key=len, reverse=True)[0]) results.append((f / size, giant / giantP)) else: results.append((1, 0)) with open(file_name + 'random.txt', 'w') as file: for (x, y) in results: print(str(x) + " " + str(y), file=file) for N in [1000, 10000, 100000]: er = nx.erdos_renyi_graph(N, 0.0005) random_attack(er, "ERk05N" + str(N)) er1 = nx.erdos_renyi_graph(N, 0.002) random_attack(er1, "ERk2N" + str(N)) ba = nx.barabasi_albert_graph(N, 1) random_attack(ba, "BAk2N" + str(N)) ba1 = nx.barabasi_albert_graph(N, 2) random_attack(ba1, "BAk4N" + str(N)) ws = nx.watts_strogatz_graph(N, 2, 0.01) random_attack(ws, "WSk2N" + str(N)) ws1 = nx.watts_strogatz_graph(N, 4, 0.01) random_attack(ws1, "WSk4N" + str(N))
statistics.mean([int(v) for v in pathLength[1].values()])) print("Diameter: ", nx.diameter(ws)) ############################################################################################ import networkx as nx import matplotlib.pyplot as plt averagePathList = [] averageClusteringCoeffc = [] dataList = [ 0.0001, 0.0005, 0.001, 0.0025, 0.005, 0.010, 0.025, 0.050, 0.1, 0.15, 0.25, 0.35, 0.5, 0.65, 0.85, 1 ] for data in dataList: ws1 = nx.watts_strogatz_graph(1000, 8, data) averagePathList.append(nx.average_shortest_path_length(ws1)) averageClusteringCoeffc.append(nx.average_clustering(ws1)) averagePathList1 = [] for item in averagePathList: averagePathList1.append(item / averagePathList[0]) averageClusteringCoeffc1 = [] for item in averageClusteringCoeffc: averageClusteringCoeffc1.append(item / averageClusteringCoeffc[0]) #p1 = plt.scatter(dataList, averageClusteringCoeffc1, color='seagreen') #p2 = plt.scatter(dataList, averagePathList1, color='brown') #plt.title("Increasing randomness")
def run(self): self.G = networkx.watts_strogatz_graph(self.parameters['nodes'], self.parameters['k'], self.parameters['probability'], seed=1234)
def __init__(self): n = 400 g = nx.watts_strogatz_graph(n, 2, 0.02) cfg = { 'utility': False, } self.model = Model(g, ModelConfiguration(cfg)) constants = { 'dt': 0.01, 'A_min': -0.5, 'A_star': 1, 's_O': 0.01, 's_I': 0, 'd_A': 0, 'p': 1, 'r_min': 0, 't_O': np.inf, 'N': n } def initial_I(constants): return np.random.normal(0, 0.3, constants['N']) def initial_O(constants): return np.random.normal(0, 0.2, constants['N']) initial_state = { 'I': initial_I, 'O': initial_O, 'A': 1 } def update_I_A(nodes, constants): node = nodes[0] nb = np.random.choice(self.model.get_neighbors(node)) if abs(self.model.get_node_state(node, 'O') - self.model.get_node_state(nb, 'O')) > constants['t_O']: return {'I': self.model.get_node_state(node, 'I')} else: # Update information r = constants['r_min'] + (1 - constants['r_min']) / (1 + np.exp(-1 * constants['p'] * (self.model.get_node_state(node, 'O') - self.model.get_node_state(nb, 'O')))) inf = r * self.model.get_node_state(node, 'I') + (1-r) * self.model.get_node_state(nb, 'I') + np.random.normal(0, constants['s_I']) # Update attention node_A = self.model.get_node_state(node, 'A') + constants['d_A'] * (2 * constants['A_star'] - self.model.get_node_state(node, 'A')) nb_A = self.model.get_node_state(nb, 'A') + constants['d_A'] * (2 * constants['A_star'] - self.model.get_node_state(nb, 'A')) return {'I': [inf], 'A': {node: node_A, nb: nb_A}} def update_A(constants): return {'A': self.model.get_state('A') - 2 * constants['d_A'] * self.model.get_state('A')/constants['N']} def update_O(constants): noise = np.random.normal(0, constants['s_O'], constants['N']) x = self.model.get_state('O') - constants['dt'] * (self.model.get_state('O')**3 - (self.model.get_state('A') + constants['A_min']) * self.model.get_state('O') - self.model.get_state('I')) + noise return {'O': x} def shrink_I(): return {'I': self.model.get_state('I') * 0.999} def shrink_A(): return {'A': self.model.get_state('A') * 0.999} def sample_attention_weighted(graph): probs = [] A = self.model.get_state('A') factor = 1.0/sum(A) for a in A: probs.append(a * factor) return np.random.choice(graph.nodes, size=1, replace=False, p=probs) # Model definition self.model.constants = constants self.model.set_states(['I', 'A', 'O']) update_cfg = UpdateConfiguration({ 'arguments': {'constants': self.model.constants}, 'get_nodes': True }) up_I_A = Update(update_I_A, update_cfg) s_I = Update(shrink_I) s_A = Update(shrink_A) self.model.add_scheme(Scheme(sample_attention_weighted, {'args': {'graph': self.model.graph}, 'updates': [up_I_A]})) self.model.add_scheme(Scheme(lambda graph: graph.nodes, {'args': {'graph': self.model.graph}, 'lower_bound': 5000, 'updates': [s_I]})) self.model.add_scheme(Scheme(lambda graph: graph.nodes, {'args': {'graph': self.model.graph}, 'lower_bound': 10000, 'updates': [s_A]})) self.model.add_update(update_A, {'constants': self.model.constants}) self.model.add_update(update_O, {'constants': self.model.constants}) self.model.set_initial_state(initial_state, {'constants': self.model.constants})
print nNodes nRingNeighbors = ( np.arange(nLevels) + 1 ) * 2 #Number of neighbors per node in the ring. Example with 3 levels: [2,4,6] 'Graph is defined' G = nx.Graph() 'Cones are created' for level in reversed( range(nLevels) ): #Building it level by level, from the lowest level to the highest 'The seperate rings are build' #Making the 'blueprint' of the Watts-Strogatz ring for this level: ringlevel = nx.watts_strogatz_graph(nNodes[level], nRingNeighbors[level], 0) #Implementing this blueprint for every cone for cone in range(nCones): mapping = {} for node in range(nNodes[level]): mapping.update( {node: labelNode(cone, level, node)} ) #Making a map for relabeling the node names as conenr_levelnr_nodenr ring = nx.relabel_nodes( ringlevel, mapping ) #Applying map on ring for this cone - this relabels the node names G.add_nodes_from(ring) #Adding the nodes from the ring to the graph G.add_edges_from( ring.edges()) #Adding the edges from the ring to the graph
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 26 20:38:21 2020 @author: Sneha Kachhara """ import basic_FHN_ring as fhn import networkx as nx #you can give a custom adjacency matrix as well. Num = 100 #number of oscillators nbrs = 4 #number of neighbours for Watts-Strogatz graph prob = 0.2 #probability of rewiring for Watts-Strogatz graph gr = nx.watts_strogatz_graph(100, 4, 0.1) A = nx.to_numpy_matrix(gr) coupling_strength = 0.1 fhn.create_system(A, e=coupling_strength) fhn.see_graphs(gr)