def run_tests(min_n, max_n, seed_range, output_file="result.txt"): checked = 0 errors = 0 with open(output_file, 'a') as f: for n in range(min_n, max_n): print("n={}\n".format(n)) for m in range(n - 1, int(n * (n - 1) / 2) + 1): for sid in range(seed_range): checked += 1 G = nx.gnm_random_graph(n, m, seed=sid) matrix = nx.to_numpy_matrix(G) GS = [] for v in G.nodes: GS.append(set(G.adj[v].keys())) T = set(G.nodes()) ind_set, comb = colorize_numpy(GS, T) #J = alg_try.Colorize(matrix) J = colorize_true(GS, T) if len(J) != sum(comb): #if len(J) != len(res): errors += 1 f.write( "incorrect results for n = {} and m = {} (seed = {})\n" .format(n, m, sid)) if (m + 1) % 10 == 0: print("m = {} from {}".format(m, int(n * (n - 1) / 2))) pass if errors != 0: print("{} ERRORS".format(errors)) print("From {} graphs {} errors".format(checked, errors))
def random_graph_generator(nodes, edges, num): graph = nx.gnm_random_graph(nodes, edges) path = "Datasets/rnd_graph_" + num + ".txt" fh = open(path, 'wb') nx.write_edgelist(graph, fh, encoding="utf-8") g = create_graph(path)
def run_test(n, m, seed): G = nx.gnm_random_graph(n, m, seed=seed) matrix = nx.to_numpy_matrix(G) GS = [] for v in G.nodes: GS.append(set(G.adj[v].keys())) T = set(G.nodes()) start_time = timer() ind_set, comb = colorize_numpy(GS, T) numpy_time = timer() - start_time start_time = timer() J = alg_try.Colorize(matrix) print(J) alg_time = timer() - start_time print("numpy time: %.4f,\t alg time: %.4f" % (numpy_time, alg_time)) print("alr res: {} \nnumpy res: {}".format(len(J), sum(comb))) colors = [ 1, ] * n for idx, ind in enumerate(ind_set): if comb[idx] == 1: print(ind_set[idx]) for i in ind_set[idx]: colors[i] = idx nx.draw(G, node_color=colors, pos=nx.drawing.layout.kamada_kawai_layout(G), with_labels=True, node_size=1000, cmap='Paired') #nx.draw(G, node_color=colors, pos=nx.drawing.layout.spiral_layout(G), with_labels=True, node_size=1000, cmap='Paired') #nx.draw(G, node_color=colors, pos=nx.drawing.layout.spring_layout(G, seed=3), with_labels=True, node_size=1000, cmap='Paired') plt.show()
def randomGraphW(self, directed=True): nxG = nx.gnm_random_graph(self.n, self.n - 1, directed=directed, seed=random.getrandbits(20)) #nxG = nx.balanced_tree(self.n,m) inp = "" out = "" mst = 0 q = 0 G = [[] for i in range(self.n)] W = [[] for i in range(self.n)] for i, j in nxG.edges: w = random.randrange(9000, 10000) G[i].append(j) inp += "{} {} {}".format(i + 1, j + 1, w) + '\n' mst += w q += 1 out += "{} {}".format(i + 1, j + 1) + '\n' W[i].append(w) if not directed: G[j].append(i) W[j].append(w) inp += "{}".format(q) + '\n' inp += out self.showGraph(G, W)
def load_graph(ifilename=None): """Load graph from file """ G = None # Testing mode if ifilename is None: n = 10 # 10 nodes m = 20 # 20 edges G = nx.gnm_random_graph(n, m) # some properties print("node degree clustering") for v in nx.nodes(G): print(f"{v} {nx.degree(G, v)} {nx.clustering(G, v)}") print() print("the adjacency list") for line in nx.generate_adjlist(G): print(line) else: try: G = networkx.read_graphml(open(ifilename, 'r')) except Exception as ifile_err: print(f"Unable to load graph from {ifilename}: {ifile_err}") return G
def random_dag(n, p=None, m_n_ratio=None, seed=None, model='np'): """ Creates random Erdős-Rényi graph from G(size, p) sem (see https://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93R%C3%A9nyi_model) Args: seed: Random mc_seed n: Number of nodes p: Probability of creating an edge in 'np' model m_n_ratio: m/n ratio, m is the number of edges in 'nm' model model: 'np' - G(n, p) / 'nm' - G(n, m) Returns: DirectedAcyclicGraph instance """ if model == 'np': G = nx.gnp_random_graph(n, p, seed, directed=True) elif model == 'nm': G = nx.gnm_random_graph(n, int(m_n_ratio * n), seed, directed=True) else: raise NotImplementedError('Unknown model type') G.remove_edges_from([(u, v) for (u, v) in G.edges() if u > v]) adjacency_matrix = nx.linalg.graphmatrix.adjacency_matrix( G).todense().astype(int) var_names = [f'x{i}' for i in range(n)] return DirectedAcyclicGraph(adjacency_matrix, var_names)
def ErdosRenyi(n, m, d): while True: G = nx.gnm_random_graph(n, m, seed=None, directed=False) degrees = dict(G.degree()) maxDegree = max([item for item in degrees.values()]) if nx.is_connected(G) and maxDegree <= d: break adj_dict = nx.convert.to_dict_of_lists(G) return (adj_dict)
def test_01(self): G = nx.gnm_random_graph(10, 22) edge_weights = { v: dict(weight=random.randint(4, 20)) for v in G.edges } nx.set_edge_attributes(G, edge_weights) d_path = nx.dijkstra_path(G, 0, 3, weight='weight') print(d_path) print(G.edges.data())
def calculate_avg_sp_length(n): p = find_p(n) m = math.ceil(n * (n - 1) / 2 * p) while True: try: G = nx.gnm_random_graph(n, m) sp = nx.average_shortest_path_length(G) except nx.NetworkXError: continue break print("{:>12} {:>12} {:12.6f} {:12.6f}".format(n, m, p, sp)) return sp
def generate_data(min_n, max_n, sections, seeds, alg="Olemskoy"): out_file = "time_data/" + "{}_{}_".format(min_n, max_n) + alg full_data = np.empty((max_n - min_n, max_n * (max_n - 1) // 2 + 1, seeds)) plot_data = np.empty((max_n - min_n, sections + 1)) full_data[:, :, :] = np.nan plot_data[:, :] = np.nan x_data = np.arange(min_n, max_n, dtype=int) y_data = np.arange(sections + 1, dtype=int) for n in range(min_n, max_n): max_m = n * (n - 1) // 2 prev_section = -1 section_data = 1 for m in range(max_m + 1): for seed in range(seeds): G = nx.gnm_random_graph(n, m, seed=seed) T = set(G.nodes()) GS = [] for v in G.nodes: GS.append(set(G.adj[v].keys())) matrix = nx.to_numpy_matrix(G) #start = timer() if alg == "Olemskoy": func = wrapper(Colorize, matrix) elif alg == "Novikov": func = wrapper(colorize_true, GS, T) elif alg == "NovikovOpt": func = wrapper(colorize_true_1, GS, T) elif alg == "NovikovMatr": func = wrapper(colorize_numpy, GS, T) time = timeit.timeit(func, 'gc.enable()', number=1) #res = colorize_true_1(GS, T) #time = timer() - start full_data[n - min_n, m, seed] = time section = int(m / max_m * sections) if prev_section == section: section_data += 1 plot_data[n - min_n, section] += np.mean(full_data[n - min_n, m]) else: plot_data[n - min_n, section] = np.mean(full_data[n - min_n, m]) plot_data[n - min_n, prev_section] /= section_data prev_section = section section_data = 1 print(alg + "finished n = {}".format(n)) np.save(out_file, full_data) np.save(out_file + "_plot", plot_data) np.save(out_file + "_x", x_data) np.save(out_file + "_y", y_data)
def randomGraphW(n, m, directed=True): nxG = nx.gnm_random_graph(n, m, directed=directed, seed=random.getrandbits(20)) G = [[] for i in range(n)] W = [[] for i in range(n)] for i, j in nxG.edges: print(i + 1, j + 1, end=" ") G[i].append(j) w = random.randrange(80231, 893320068) c = random.randrange(1, 100) print(w) W[i].append(w) if not directed: G[j].append(i) W[j].append(w) return G, W
def randomGraphW(n, m, directed=True, show=True): nxG = nx.gnm_random_graph(n, m, directed=directed, seed=random.getrandbits(20)) G = [[] for i in range(n)] W = [[] for i in range(n)] if show: print(n, m) for i, j in nxG.edges: G[i].append(j) if show: print(i + 1, j + 1) w = random.randrange(1, 20) W[i].append(w) if not directed: G[j].append(i) #if show: # print(j+1,i+1) W[j].append(w) return G, W
def compare_time(min_n, max_n, seed_range, output_file="result.txt"): time_difference = 0 alg_all_time = 0 try_all_time = 0 with open(output_file, 'a') as f: for n in range(min_n, max_n): print("n={}\n".format(n)) for m in range(n - 1, int(n * (n - 1) / 2) + 1): for sid in range(seed_range): G = nx.gnm_random_graph(n, m, seed=sid) matrix = nx.to_numpy_matrix(G) GS = [] for v in G.nodes: GS.append(set(G.adj[v].keys())) T = set(G.nodes()) start_time = timer() alg_J = alg.Colorize(matrix) alg_time = timer() - start_time start_time = timer() try_J = alg_try.Colorize(matrix) try_time = timer() - start_time alg_all_time += alg_time try_all_time += try_time #print("numpy time: %.4f,\t alg time: %.4f"%(numpy_time, alg_time)) if len(alg_J) != len(try_J): print("ERROR {}-{}-{}".format(n, m, sid)) f.write( "incorrect results for n = {} and m = {} (seed = {})\n" .format(n, m, sid)) if (m + 1) % 10 == 0: print("m = {} from {}".format(m, int(n * (n - 1) / 2))) pass print("alg time: {}".format(alg_all_time)) print("try time: {}".format(try_all_time))
def load_data(output_dir): NetGAN_network = None generated_network = np.load('{}/output_network.npy'.format(output_dir)) original_network = np.load('{}/org_network.npy'.format(output_dir)) GAE_network = np.load('{}/GAE_network.npy'.format(output_dir)) # NetGAN_network = np.load('{}/netgan_network.npy'.format(output_dir))[1] n = original_network.shape[0] generated_network = generated_network + np.identity(n) original_network = original_network + np.identity(n) original_network[original_network > 2] = 1 generated_network[generated_network > 2] = 1 GAE_network = GAE_network + np.identity(n) m = int(np.sum(original_network)) random_G = nx.gnm_random_graph(n, m) random_bara_G = nx.generators.random_graphs.barabasi_albert_graph(n, 800) GAE_network = nx.from_numpy_matrix(GAE_network) generated_network = nx.from_numpy_matrix(generated_network) original_network = nx.from_numpy_matrix(original_network) # if NetGAN_network.shape[0] < n: # Net = np.zeros((n, n)) # Net[:NetGAN_network.shape[0], :NetGAN_network.shape[1]] = NetGAN_network # NetGAN_network = Net # NetGAN_network = nx.from_numpy_matrix(NetGAN_network[:n, :n]) return random_G, random_bara_G, generated_network, original_network, GAE_network, NetGAN_network
'''產生隨機拓撲''' from networkx import nx import matplotlib.pyplot as plt #draw graph import random node_degree = {} # key:node, value:degree degree_node = {} # key:degree, value:node leaf = [] # node of degree 1 max_deg = 0 n = 100 e = 150 #connetced topology generate G = nx.gnm_random_graph(n, e) while not nx.is_connected(G): G = nx.gnm_random_graph(n, e) ''' for i in G.edges: G[i[0]][i[1]]['weight']=random.randint(1,15) ''' with open('ER_graph.txt', 'wt') as f: f.write(str(n) + ' ' + str(e) + '\n') for i in G.edges: f.write(str(i[0] + 1) + ' ' + str(i[1] + 1) + '\n') #f.write(str(i[0]+1)+' '+str(i[1]+1)+' '+str(G[i[0]][i[1]]['weight'])+'\n') f.close() print("graph generated") nx.draw(G, with_labels=True, font_weight='bold') plt.show() #degree_list
parser.add_argument( "-o", "--output", help="Arquivo de saída", default='topo.txt') parser.add_argument("-v", "--view", help="visualizar a rede", dest="view", action="store_true", default=False) args = parser.parse_args() # realiza o parse print ("### Gerando Topologia Genérica com %s switches e %s links ###" % (args.s, args.l)) switches = args.s # é a quantidade de switches # é quantidade de enlaces ou o dobro de switches links = args.l if args.l else 2*switches output = args.output # arquivo de saida view = args.view # indica se quer visualizar a rede # manipulando o grafo G = nx.gnm_random_graph(switches, links) # grapho aleatório edges = [] # lista de arestas for line in nx.generate_adjlist(G): # para cada linha das adjascentes nodes = line.split() # quebra por espaços first = int(nodes[0]) # pega o primeiro for node in nodes[1:]: # para cada node restante edges.append([first, int(node)]) # adiciona na lista o parte de node # manipulando arquivo with open(output, "w") as f: # abre o arquivo para escrita dump(edges, f) # escreve o arquivo if view: nx.draw(G, with_labels=True, font_weight='bold')
def play_many_games_semisupervised(num_agents, num_episodes, inner_speech, learning_rate, punishment_weight, punishment_talk, agents_memory, replay, beta_1, p_peek, num_choose_act, network_type, verbose=False): '''Run the game for many episodes to obtain simulation results''' # Parameters fixed throughout simulations num_choices = num_choose_act num_talking_symbols = num_choose_act winning_reward = 1 mean_sample = 100 punishment_weight = punishment_weight num_agents = num_agents n_type = network_type # Initialize environment and agents env = Two_Roles_Game_Many_Agents(num_choices, winning_reward, mean_sample, num_talking_symbols, num_agents, punishment_talk, punishment_weight) agents = [] scores = [] talks = [] acts = [] samples = [] m = 20 for i in range(num_agents): x = DQNAgent_student_teacher(num_talking_symbols, num_choices, beta_1, agents_memory) x.learning_rate = learning_rate agents.append(x) talks.append([]) acts.append([]) scores.append([]) if n_type == 0: #random G = nx.gnm_random_graph(num_agents, m) elif n_type == 1: #fully connected G = nx.complete_graph(num_agents) elif n_type == 2: #small-world G = nx.connected_watts_strogatz_graph(num_agents, 2, 0.2) elif n_type == 3: #ring G = nx.connected_watts_strogatz_graph(num_agents, 2, 0) # Iterate the game episodes = num_episodes for e in range(episodes): # Selecting agents to play in the spisode my_sample1 = random.sample(range(num_agents), 1)[0] my_sample2 = random.choice(list(G.neighbors(my_sample1))) my_sample = [my_sample1, my_sample2] agent1 = agents[my_sample[0]] # agent1 is always the speaker agent2 = agents[my_sample[1]] # agent2 is always the listener # Initialize the scores score1 = 0 score2 = 0 state1, state2, _, _ = env.step( 0, 0, 0, my_sample) # initialize the environment # agent 1 talks action1 = agent1.act(state1) # update environment based on agent1's speech and actions state1, state2, reward1, reward2 = env.step(action1[0], 0, 0, my_sample) score1 += reward1 # Agent 2 acts based on agent 1's message action2 = agent2.act(state2) # Update the environment and coompute coordination rewards next_state1, next_state2, reward1, reward2 = env.step( action1[1], action2[1], 1, my_sample) score1 += reward1 score2 += reward2 # Save the transition to memory agents[my_sample[1]].remember(state2, action2, reward2, next_state2) # Semi-supervised updates: if random.random( ) < p_peek: # peek another's action 20% of times: mimiking agents[my_sample[1]].remember(state2, action1, winning_reward, next_state2) agents[my_sample[0]].remember(state1, action1, reward1, next_state1) if random.random() < p_peek: agents[my_sample[0]].remember(state1, action2, winning_reward, next_state1) # Monitor progress if e % 100 == 0 and verbose: print("episode: {}/{}, score1: {}, score2: {}".format( e, episodes, score1, score2)) # Train agents if len(agent1.memory) >= replay and len(agent2.memory) >= replay: agents[my_sample[0]].replay(replay) agents[my_sample[1]].replay(replay) else: print("replay more than memory") # Save data for later analysis talks[my_sample[0]].append(action1[0]) talks[my_sample[1]].append(-1) #didn't talk acts[my_sample[0]].append(action1[1]) acts[my_sample[1]].append(action2[1]) scores[my_sample[0]].append(score1) scores[my_sample[1]].append(score2) samples.append(my_sample) return [talks, acts, scores, samples]
# Copyright (C) 2004-2017 by # Aric Hagberg <*****@*****.**> # Dan Schult <*****@*****.**> # Pieter Swart <*****@*****.**> # All rights reserved. # BSD license. import sys import matplotlib.pyplot as plt from networkx import nx n = 10 # 10 nodes m = 20 # 20 edges G = nx.gnm_random_graph(n, m) # some properties print("node degree clustering") for v in nx.nodes(G): print('%s %d %f' % (v, nx.degree(G, v), nx.clustering(G, v))) # print the adjacency list to terminal try: nx.write_adjlist(G, sys.stdout) except TypeError: # Python 3.x nx.write_adjlist(G, sys.stdout.buffer) nx.draw(G) plt.show()
import matplotlib.pyplot as plt from networkx import nx nodes = 20 edges = 30 G = nx.gnm_random_graph(nodes, edges) # some properties print("node degree clustering") for v in nx.nodes(G): print('%s %d %f' % (v, nx.degree(G, v), nx.clustering(G, v))) # print the adjacency list for line in nx.generate_adjlist(G): print(line) nx.draw(G) plt.show()
and report some properties. This graph is sometimes called the Erdős-Rényi graph but is different from G{n,p} or binomial_graph which is also sometimes called the Erdős-Rényi graph. """ import matplotlib.pyplot as plt from networkx import nx n = 10 # 10 nodes m = 20 # 20 edges seed = 20160 # seed random number generators for reproducibility # Use seed for reproducibility G = nx.gnm_random_graph(n, m, seed=seed) # some properties print("node degree clustering") for v in nx.nodes(G): print(f"{v} {nx.degree(G, v)} {nx.clustering(G, v)}") print() print("the adjacency list") for line in nx.generate_adjlist(G): print(line) pos = nx.spring_layout(G, seed=seed) # Seed for reproducible layout nx.draw(G, pos=pos) plt.show()