def SwapNodes(self, swapNodes): for (nodeX, nodeY) in swapNodes: self.amends += 1 self.partition[0].remove(nodeX) self.partition[0].append(nodeY) self.partition[1].remove(nodeY) self.partition[1].append(nodeX) #print(self.partition) #time.sleep(20) #self.G=nx.relabel_nodes(self.G, #mapping={nodeX:nodeY,nodeY:nodeX}) self.components[0] = self.G.subgraph(self.partition[0]).copy() self.components[1] = self.G.subgraph(self.partition[1]).copy() self.spectrum = nx.laplacian_spectrum(self.G) self.algebraic_connectivity = nx.algebraic_connectivity(self.G) self.components_spectrum[0] = nx.laplacian_spectrum( self.components[0]) self.components_spectrum[1] = nx.laplacian_spectrum( self.components[1]) self.components_ac[0] = nx.algebraic_connectivity( self.components[0]) self.components_ac[1] = nx.algebraic_connectivity( self.components[1]) self.history.append([ self.algebraic_connectivity, self.components_ac[0], self.components_ac[1] ]) logging.info("Changes appended to history succesfully.")
def base_experiment_compare(graph, P, W): print('#' * 10) for i in range(10): t = ComputeCoverTime(graph) print('Number of Options', i) print('CoverTime ', t) lb = nx.algebraic_connectivity(nx.to_networkx_graph(graph)) print('lambda ', lb) print() avg_dist = average_shortest_distance(graph, W) graph_alg, options_alg = AverageShortestOptions(graph, P, 1) lb_alg = nx.algebraic_connectivity(nx.to_networkx_graph(graph_alg)) avg_dist_alg = average_shortest_distance(graph_alg, W) graph_brute, options_brute = BruteOptions(graph, P, 1) lb_brute = nx.algebraic_connectivity(nx.to_networkx_graph(graph_brute)) avg_dist_brute = average_shortest_distance(graph_brute, W) print('avg_shortest_dist: ', "alg:", avg_dist_alg, "brute:", avg_dist_brute) #print('lambda: ',"alg:", lb_alg,"brute:",lb_brute) print(options_alg, options_brute) graph = graph_alg
def test_disconnected(self, method): G = nx.Graph() G.add_nodes_from(range(2)) assert nx.algebraic_connectivity(G) == 0 pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method) G.add_edge(0, 1, weight=0) assert nx.algebraic_connectivity(G) == 0 pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method)
def test_disconnected(self): G = nx.Graph() G.add_nodes_from(range(2)) for method in self._methods: assert_equal(nx.algebraic_connectivity(G), 0) assert_raises(nx.NetworkXError, nx.fiedler_vector, G, method=method) G.add_edge(0, 1, weight=0) for method in self._methods: assert_equal(nx.algebraic_connectivity(G), 0) assert_raises(nx.NetworkXError, nx.fiedler_vector, G, method=method)
def swap_nodes(g, swap_nodes_list, partition, components): swap_history = [] for (node_x, node_y) in swap_nodes_list: partition[0].remove(node_x) partition[0].append(node_y) partition[1].remove(node_y) partition[1].append(node_x) components[0] = g.subgraph(partition[0]).copy() components[1] = g.subgraph(partition[1]).copy() swap_history.append((nx.algebraic_connectivity(components[0]), nx.algebraic_connectivity(components[1]))) return swap_history
def random_graph(n, l): r = 0.5 g = nx.random_geometric_graph(n, r) l2 = nx.algebraic_connectivity(g) while np.abs(l2 - l) > 0.2: if l2 > l: r = r * 0.9 else: r = r * 1.1 g = nx.random_geometric_graph(n, r) l2 = nx.algebraic_connectivity(g) return nx.adjacency_matrix(g).todense()
def maximum_fiedler_value_swaps(g, swap_vertices, binary_part, recursive_fiedler_values): (max_x, max_y) = recursive_fiedler_values for idx, (u, v) in enumerate(swap_vertices): binary_part[u] = 1 binary_part[v] = 0 part_x = [idx for idx, i in enumerate(binary_part) if i == 0] part_y = [idx for idx, i in enumerate(binary_part) if i == 1] # print(nx.algebraic_connectivity(g.subgraph(part_x)), nx.algebraic_connectivity(g.subgraph(part_y))) if nx.algebraic_connectivity( g.subgraph(part_x)) > max_x and nx.algebraic_connectivity( g.subgraph(part_y)) > max_y: max_x = nx.algebraic_connectivity(g.subgraph(part_x)) max_y = nx.algebraic_connectivity(g.subgraph(part_y)) return max_x, max_y
def data_pack_define(adj_data_pack,disweight_data_pack,disMatrix,adjMatrix,time,runs): G_disweight = nx.from_numpy_matrix(np.matrix(disMatrix)) G_adj = nx.from_numpy_matrix(np.matrix(adjMatrix)) no_nodes = len(G_adj) no_edges = G_adj.size() norm_alg_con = nx.algebraic_connectivity(G_adj, weight='weight', normalized=False, tol=1e-08, method='tracemin_pcg') norm_avg_clu = nx.average_clustering(G_adj,weight='weight') norm_closeness = np.mean(list(nx.closeness_centrality(G_adj,u=None,distance='weight'))) norm_deg = np.mean(list(nx.degree_centrality(G_adj).values())) if no_nodes >= 1: norm_n_betweenness = np.mean(list(nx.betweenness_centrality(G_adj,normalized=True,weight='weight').values())) else: norm_n_betweenness = 0 if no_edges >= 1: norm_e_betweenness = np.mean(list(nx.edge_betweenness_centrality(G_adj, normalized=True, weight='weight').values())) else: norm_e_betweenness = 0 norm_arr = [norm_alg_con,norm_avg_clu,norm_closeness,norm_deg,norm_n_betweenness,norm_e_betweenness] counter = 0 if runs == 0: for items in norm_arr: adj_data_pack[time][1].append([]) adj_data_pack[time][1][counter].append(norm_arr[counter]) counter = counter + 1 else: for items in norm_arr: adj_data_pack[time][1][counter].append(norm_arr[counter]) counter = counter + 1 return
def print_metrics(g): # Number of nodes n = g.number_of_nodes() print("Number of nodes: ", n) # Number of links li = g.number_of_edges() print("Number of links: ", li) # Link density p = nx.density(g) print("Link density: ", p) # Average degree print("Average degree: ", 2 * li / n) # Degree variance print("Degree variance: ", get_degree_variance(g)) # Plot degree distribution plot_degree_distribution(dict(g.degree).values()) # Degree correlation (assortativity) r = nx.degree_assortativity_coefficient(g) print("Degree correlation (assortativity): ", r) # Clustering coeffcient c = nx.average_clustering(g) print("Clustering coeffcient: ", c) # Algebraic connectivity ac = nx.algebraic_connectivity(g) print("Algebraic connectivity: ", ac)
def test_two_nodes(self, method): G = nx.Graph() G.add_edge(0, 1, weight=1) A = nx.laplacian_matrix(G) assert almost_equal(nx.algebraic_connectivity(G, tol=1e-12, method=method), 2) x = nx.fiedler_vector(G, tol=1e-12, method=method) check_eigenvector(A, 2, x)
def network_metrics(network, network_red, n_fibres, tag=''): """Analyse networkx Graph object""" database = pd.Series(dtype=object) database['No. Fibres'] = n_fibres cross_links = np.array([degree[1] for degree in network.degree], dtype=int) database[f"{tag} Network Cross-Link Density"] = ((cross_links > 2).sum() / n_fibres) try: value = nx.degree_pearson_correlation_coefficient(network, weight='r')**2 except Exception as err: logger.debug(f'Network Degree calculation failed: {str(err)}') value = None database[f"{tag} Network Degree"] = value try: value = np.real(nx.adjacency_spectrum(network_red).max()) except Exception as err: logger.debug(f'Network Eigenvalue calculation failed: {str(err)}') value = None database[f"{tag} Network Eigenvalue"] = value try: value = nx.algebraic_connectivity(network_red, weight='r') except Exception as err: logger.debug(f'Network Connectivity calculation failed: {str(err)}') value = None database[f"{tag} Network Connectivity"] = value return database
def calc_network_params(graph): ''' Calculate many indicators and structual parameters of the network. Graph must have weight! ''' clustering_coeff = nx.algorithms.average_clustering(graph, weight='weight') # Shortest path length is undefined if the graph is disconnected. if not nx.is_weakly_connected(graph): shortest_path = np.inf else: shortest_path = nx.algorithms.average_shortest_path_length( graph, weight='weight') A = nx.adjacency_matrix(graph, weight='weight') e = np.linalg.eigvals(A.todense()) largest_eigenvalue = np.real(max(e)) # The paper-1 doesn't use normalized algebraic connectivity algebraic_conn = nx.algebraic_connectivity(graph.to_undirected(), weight='weight') eg_cen = list( nx.algorithms.eigenvector_centrality(graph, weight='weight').values()) eigen_centrality_dict = { 'max': np.max(eg_cen), 'std': np.std(eg_cen, ddof=1) } network_params = {} network_params['clustering_coeff'] = clustering_coeff network_params['shortest_path'] = shortest_path network_params['largest_eigenvalue'] = largest_eigenvalue network_params['algebraic_conn'] = algebraic_conn network_params['eigen_cen_max'] = eigen_centrality_dict['max'] network_params['eigen_cen_std'] = eigen_centrality_dict['std'] return network_params
def test_seed_argument(self, method): G = nx.cycle_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2) ac = nx.algebraic_connectivity(G, tol=1e-12, method=method, seed=1) assert almost_equal(ac, sigma) x = nx.fiedler_vector(G, tol=1e-12, method=method, seed=1) check_eigenvector(A, sigma, x)
def test_abbreviation_of_method(self): G = nx.path_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2 + sqrt(2)) ac = nx.algebraic_connectivity(G, tol=1e-12, method='tracemin') assert_almost_equal(ac, sigma) x = nx.fiedler_vector(G, tol=1e-12, method='tracemin') check_eigenvector(A, sigma, x)
def main(args): data = [] for _ in tqdm.tqdm(xrange(args.n_graphs)): graph = random_graph(args.min_nodes, args.max_nodes) target = nx.algebraic_connectivity(graph, method='lobpcg') data.append(jsonify(graph, target)) with open(args.output_file, 'w') as fp: json.dump(data, fp)
def calculateSpectrum(self): self.components_spectrum = {} self.components_ac = {} self.spectrum = None self.algebraic_connectivity = 0 self.spectrum = nx.laplacian_spectrum(self.G) self.algebraic_connectivity = nx.algebraic_connectivity(self.G) self.components_spectrum[0] = nx.laplacian_spectrum(self.components[0]) self.components_spectrum[1] = nx.laplacian_spectrum(self.components[1]) self.components_ac[0] = nx.algebraic_connectivity(self.components[0]) self.components_ac[1] = nx.algebraic_connectivity(self.components[1]) logging.info("Spectrum and algebraic connectivity values calculated.") self.history.append([ self.algebraic_connectivity, self.components_ac[0], self.components_ac[1] ]) logging.info("Appened to history succesfully.")
def test_path(self, method): G = nx.path_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2 + sqrt(2)) ac = nx.algebraic_connectivity(G, tol=1e-12, method=method) assert almost_equal(ac, sigma) x = nx.fiedler_vector(G, tol=1e-12, method=method) check_eigenvector(A, sigma, x)
def test_abbreviation_of_method(self): G = nx.path_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2 + sqrt(2)) ac = nx.algebraic_connectivity(G, tol=1e-12, method="tracemin") assert almost_equal(ac, sigma) x = nx.fiedler_vector(G, tol=1e-12, method="tracemin") check_eigenvector(A, sigma, x)
def clustering_analys(DF_adj, re_type): #测试参数的函数。re_type是返回值的类型 labels = list(DF_adj.index) #print(DF_adj_1,DF_adj) #Network graph G = nx.Graph() G_i = nx.DiGraph() G.add_nodes_from(labels) G_i.add_nodes_from(labels) #Connect nodes for i in range(DF_adj.shape[0]): col_label = DF_adj.columns[i] for j in range(DF_adj.shape[1]): row_label = DF_adj.index[j] node = DF_adj.iloc[i,j] if node != 0: #print(node,DF_adj[labels[i]][labels[j]]) #print(node) G.add_edge(col_label,row_label,weight = node) G_i.add_edge(col_label,row_label,weight = node) if(re_type == 1): return dict_avg(nx.clustering(G))#取平均,队伍或者队员都可以 elif(re_type == 2): L = nx.normalized_laplacian_matrix(G) e = np.linalg.eigvals(L.A) #print("Largest eigenvalue:", max(e))#衡量什么同行网络 return max(e) elif(re_type == 3): return nx.algebraic_connectivity(G) elif(re_type == 4): return(nx.reciprocity(G_i)) elif(re_type == 5): return(nx.transitivity(G_i)) elif(re_type == 6): return(dict_max(nx.in_degree_centrality(G_i))) elif(re_type == 7): return(dict_max(nx.out_degree_centrality(G_i))) elif(re_type == 8): try: return(dict_avg(nx.pagerank(G, alpha=0.9))) except: return(0.01) elif(re_type == 9): try: return(dict_avg(nx.eigenvector_centrality(G))) except: return(0.25) elif(re_type == 10): return(dict_avg(nx.average_neighbor_degree(G_i))) print("-----------------") print(nx.closeness_centrality(G))#衡量星际球员 print("-----------------") print(nx.pagerank(G, alpha=0.9))#衡量球员 print("-----------------") print(nx.eigenvector_centrality(G))#衡量球员 print("-----------------") print()#宏观的连通性 print("-----------------")
def test_cycle(self, method): pytest.importorskip("scipy") G = nx.cycle_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2) ac = nx.algebraic_connectivity(G, tol=1e-12, method=method) assert almost_equal(ac, sigma) x = nx.fiedler_vector(G, tol=1e-12, method=method) check_eigenvector(A, sigma, x)
def test_cycle(self): G = nx.cycle_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2) for method in self._methods: ac = nx.algebraic_connectivity(G, tol=1e-12, method=method) assert_almost_equal(ac, sigma) x = nx.fiedler_vector(G, tol=1e-12, method=method) check_eigenvector(A, sigma, x)
def test_seed_argument(self, method): pytest.importorskip("scipy") G = nx.cycle_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2) ac = nx.algebraic_connectivity(G, tol=1e-12, method=method, seed=1) assert ac == pytest.approx(sigma, abs=1e-7) x = nx.fiedler_vector(G, tol=1e-12, method=method, seed=1) check_eigenvector(A, sigma, x)
def test_abbreviation_of_method(self): pytest.importorskip("scipy") G = nx.path_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2 + sqrt(2)) ac = nx.algebraic_connectivity(G, tol=1e-12, method="tracemin") assert ac == pytest.approx(sigma, abs=1e-7) x = nx.fiedler_vector(G, tol=1e-12, method="tracemin") check_eigenvector(A, sigma, x)
def test_two_nodes(self, method): pytest.importorskip("scipy") G = nx.Graph() G.add_edge(0, 1, weight=1) A = nx.laplacian_matrix(G) assert nx.algebraic_connectivity( G, tol=1e-12, method=method) == pytest.approx(2, abs=1e-7) x = nx.fiedler_vector(G, tol=1e-12, method=method) check_eigenvector(A, 2, x)
def test_problematic_graph_issue_2381(self, method): G = nx.path_graph(4) G.add_edges_from([(4, 2), (5, 1)]) A = nx.laplacian_matrix(G) sigma = 0.438447187191 ac = nx.algebraic_connectivity(G, tol=1e-12, method=method) assert almost_equal(ac, sigma) x = nx.fiedler_vector(G, tol=1e-12, method=method) check_eigenvector(A, sigma, x)
def test_problematic_graph_issue_2381(self, method): pytest.importorskip("scipy") G = nx.path_graph(4) G.add_edges_from([(4, 2), (5, 1)]) A = nx.laplacian_matrix(G) sigma = 0.438447187191 ac = nx.algebraic_connectivity(G, tol=1e-12, method=method) assert ac == pytest.approx(sigma, abs=1e-7) x = nx.fiedler_vector(G, tol=1e-12, method=method) check_eigenvector(A, sigma, x)
def test_problematic_graph_issue_2381(self): G = nx.path_graph(4) G.add_edges_from([(4, 2), (5, 1)]) A = nx.laplacian_matrix(G) sigma = 0.438447187191 for method in self._methods: ac = nx.algebraic_connectivity(G, tol=1e-12, method=method) assert_almost_equal(ac, sigma) x = nx.fiedler_vector(G, tol=1e-12, method=method) check_eigenvector(A, sigma, x)
def test_two_nodes(self): G = nx.Graph() G.add_edge(0, 1, weight=1) A = nx.laplacian_matrix(G) for method in self._methods: assert_almost_equal(nx.algebraic_connectivity( G, tol=1e-12, method=method), 2) x = nx.fiedler_vector(G, tol=1e-12, method=method) check_eigenvector(A, 2, x) G = nx.MultiGraph() G.add_edge(0, 0, spam=1e8) G.add_edge(0, 1, spam=1) G.add_edge(0, 1, spam=-2) A = -3 * nx.laplacian_matrix(G, weight='spam') for method in self._methods: assert_almost_equal(nx.algebraic_connectivity( G, weight='spam', tol=1e-12, method=method), 6) x = nx.fiedler_vector(G, weight='spam', tol=1e-12, method=method) check_eigenvector(A, 6, x)
def draw_graph(g): weight = [g[u][v]['weight'] / 5 for u, v in g.edges()] # pos = nx.kamada_kawai_layout(g) pos = nx.spring_layout(g) # plt.subplot(111) # nx.draw(g, pos, with_labels=True, width=weight) # plt.show() connectivity = nx.algebraic_connectivity(g) centrality = nx.global_reaching_centrality(g) # print(f'density = {nx.density(g):.4f}') return connectivity, centrality
def test_two_nodes_multigraph(self, method): G = nx.MultiGraph() G.add_edge(0, 0, spam=1e8) G.add_edge(0, 1, spam=1) G.add_edge(0, 1, spam=-2) A = -3 * nx.laplacian_matrix(G, weight="spam") assert almost_equal( nx.algebraic_connectivity(G, weight="spam", tol=1e-12, method=method), 6 ) x = nx.fiedler_vector(G, weight="spam", tol=1e-12, method=method) check_eigenvector(A, 6, x)
def random_graph(n): # Generates adjacency matrix of random disconnected graph r = 0.5 while True: g = nx.random_geometric_graph(n, r) l2 = nx.algebraic_connectivity(g) lap = nx.normalized_laplacian_matrix(g) if 2 <= sum(x == 0 for x in np.linalg.eigvals(lap.A)) < n: return nx.adjacency_matrix(g).todense() elif l2 > 0: r = r * 0.9 else: r = r * 1.1
def test_two_nodes_multigraph(self, method): pytest.importorskip("scipy") G = nx.MultiGraph() G.add_edge(0, 0, spam=1e8) G.add_edge(0, 1, spam=1) G.add_edge(0, 1, spam=-2) A = -3 * nx.laplacian_matrix(G, weight="spam") assert nx.algebraic_connectivity(G, weight="spam", tol=1e-12, method=method) == pytest.approx( 6, abs=1e-7) x = nx.fiedler_vector(G, weight="spam", tol=1e-12, method=method) check_eigenvector(A, 6, x)
def get_metrics(challenges, graph, ac_metric= True, time_metric=True, degree_metrics=False): """ For a given network of characters and list of challenges completed by these characters, this function computes the algebraic connectivity for each group that played together and extracts the time taken by the team to complete challenge. :param: challenges: list of dict containing Challenge info graph: NetworkX graph of characters ac_metric: Boolean. Default True. Function returns algebraic connectivity if set to True. time_metric: Boolean. Default True. Function returns challenge completion time if set to True. degree_metrics: Boolean. Default False. Function returns :return: tuple of two lists: algebraic connectivity and Challenge completion time """ if ac_metric: ac = [] if time_metric: time = [] for challenge in challenges: for group in challenge['groups']: names = [] # List of node names to add to graph for member in group['members']: if member.has_key('character'): # Only add if character info is available name = member['character']['name'] names += [name] g_team = graph.subgraph(names) if len(g_team.nodes()) > 1: if ac_metric: ac += [nx.algebraic_connectivity(g_team)] if time_metric: time += [group['time']['time']] # r = return ac, time
def test_buckminsterfullerene(self): G = nx.Graph( [(1, 10), (1, 41), (1, 59), (2, 12), (2, 42), (2, 60), (3, 6), (3, 43), (3, 57), (4, 8), (4, 44), (4, 58), (5, 13), (5, 56), (5, 57), (6, 10), (6, 31), (7, 14), (7, 56), (7, 58), (8, 12), (8, 32), (9, 23), (9, 53), (9, 59), (10, 15), (11, 24), (11, 53), (11, 60), (12, 16), (13, 14), (13, 25), (14, 26), (15, 27), (15, 49), (16, 28), (16, 50), (17, 18), (17, 19), (17, 54), (18, 20), (18, 55), (19, 23), (19, 41), (20, 24), (20, 42), (21, 31), (21, 33), (21, 57), (22, 32), (22, 34), (22, 58), (23, 24), (25, 35), (25, 43), (26, 36), (26, 44), (27, 51), (27, 59), (28, 52), (28, 60), (29, 33), (29, 34), (29, 56), (30, 51), (30, 52), (30, 53), (31, 47), (32, 48), (33, 45), (34, 46), (35, 36), (35, 37), (36, 38), (37, 39), (37, 49), (38, 40), (38, 50), (39, 40), (39, 51), (40, 52), (41, 47), (42, 48), (43, 49), (44, 50), (45, 46), (45, 54), (46, 55), (47, 54), (48, 55)]) for normalized in (False, True): if not normalized: A = nx.laplacian_matrix(G) sigma = 0.2434017461399311 else: A = nx.normalized_laplacian_matrix(G) sigma = 0.08113391537997749 for method in methods: try: assert_almost_equal(nx.algebraic_connectivity( G, normalized=normalized, tol=1e-12, method=method), sigma) x = nx.fiedler_vector(G, normalized=normalized, tol=1e-12, method=method) check_eigenvector(A, sigma, x) except nx.NetworkXError as e: if e.args not in (('Cholesky solver unavailable.',), ('LU solver unavailable.',)): raise
paths = nx.all_simple_paths(g, start, stop, cutoff = size) # purge all paths smaller than "size" and closed loops paths = [sorted(p) for p in paths if (len(p) == size and len(p) == len(sp.unique(p)))] try: # purge all paths that contain the same atoms remove_repeated_vectors_from_matrix(sp.array(paths)) except: pass # print "only loops found, carrying on..." # add all the new connected subsets of atoms # allpaths += [p for p in paths if p not in allpaths] for p in paths: if p not in allpaths: allpaths.append(p) choices = [] n_choices = 0 for it in itertools.combinations(allpaths, parts): if not matching_elements(it): n_choices += 1 # choices.append(it) # print it try: algebraic_connectivity = my_algebraic_connectivity(g, normalise=normalise) except: print "CAUGHT" algebraic_connectivity = nx.algebraic_connectivity(g, normalized=normalise) print n_choices, algebraic_connectivity, nx.average_clustering(g) results.append([n_choices, edge_creation_probability, algebraic_connectivity, nx.average_clustering(g)]) sp.save("results_%dx%d_%s.npy" % (parts,size, label), sp.array(results))