def test_degree_mixing_matrix_directed(self): a_result = np.array([[0, 0, 0, 0], [0, 0, 0, 2], [0, 1, 0, 1], [0, 0, 0, 0]]) a = nx.degree_mixing_matrix(self.D, normalized=False) npt.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.D) npt.assert_equal(a, a_result / float(a_result.sum()))
def test_degree_mixing_matrix_multigraph(self): a_result = np.array([[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 3], [0, 0, 3, 0]]) a = nx.degree_mixing_matrix(self.M, normalized=False) npt.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.M) npt.assert_equal(a, a_result / float(a_result.sum()))
def test_degree_mixing_matrix_undirected(self): # fmt: off a_result = np.array([[0, 0, 0], [0, 0, 2], [0, 2, 2]]) # fmt: on a = nx.degree_mixing_matrix(self.P4, normalized=False) np.testing.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.P4) np.testing.assert_equal(a, a_result / float(a_result.sum()))
def test_degree_mixing_matrix_selfloop(self): # fmt: off a_result = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 2]]) # fmt: on a = nx.degree_mixing_matrix(self.S, normalized=False) npt.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.S) npt.assert_equal(a, a_result / float(a_result.sum()))
def test_degree_mixing_matrix_undirected(self): a_result=np.array([[0,0,0], [0,0,2], [0,2,2]] ) a=nx.degree_mixing_matrix(self.P4,normalized=False) npt.assert_equal(a,a_result) a=nx.degree_mixing_matrix(self.P4) npt.assert_equal(a,a_result/float(a_result.sum()))
def test_degree_mixing_matrix_selfloop(self): a_result=np.array([[0,0,0], [0,0,0], [0,0,2]] ) a=nx.degree_mixing_matrix(self.S,normalized=False) npt.assert_equal(a,a_result) a=nx.degree_mixing_matrix(self.S) npt.assert_equal(a,a_result/float(a_result.sum()))
def test_degree_mixing_matrix_multigraph(self): a_result=np.array([[0,0,0,0], [0,0,1,0], [0,1,0,3], [0,0,3,0]] ) a=nx.degree_mixing_matrix(self.M,normalized=False) npt.assert_equal(a,a_result) a=nx.degree_mixing_matrix(self.M) npt.assert_equal(a,a_result/float(a_result.sum()))
def calculate_ass(G, p, Iteration): i = 0 while i < Iteration: #print(i) edge = list(G.edges()) degree = nx.degree(G) index1 = random.randint(0, len(G.edges) - 1) ##随机获取第一条边 index2 = random.randint(0, len(G.edges) - 1) ##随机获取第二条边 edge1 = edge[index1] edge2 = edge[index2] k1 = degree[edge1[0]] k2 = degree[edge1[1]] k3 = degree[edge2[0]] k4 = degree[edge2[1]] tag = 0 ####################选择的两条边的四个节点中不能有相同的节点################## if edge1[0] != edge2[0] and edge1[0] != edge2[1] and edge1[1] != edge2[ 0] and edge1[1] != edge2[1]: tag = 1 order_arr = [[edge1[0], edge1[1], edge2[0], edge2[1]], [k1, k2, k3, k4]] order_arr = np.array(order_arr) order_arr = order_arr[:, order_arr[1].argsort()] p1 = random.random() ############在网络中移除原来的边并加上新的边########## if p1 < p and tag == 1: judge_tag = Judge_in_graph(G, order_arr[0][0], order_arr[0][1], order_arr[0][2], order_arr[0][3]) if judge_tag: G.add_edge(order_arr[0][0], order_arr[0][1]) G.add_edge(order_arr[0][2], order_arr[0][3]) G.remove_edge(edge1[0], edge1[1]) G.remove_edge(edge2[0], edge2[1]) i = i + 1 #r1 = round(nx.degree_assortativity_coefficient(G), 6) #print(r1) #print(len(list(G.edges()))) if p1 >= p and tag == 1: #################随机重连#################### rand_index = random.sample(range(0, 4), 4) judge_tag = Judge_in_graph(G, order_arr[0][rand_index[0]], order_arr[0][rand_index[1]], order_arr[0][rand_index[2]], order_arr[0][rand_index[3]]) if judge_tag: G.remove_edge(edge1[0], edge1[1]) G.remove_edge(edge2[0], edge2[1]) G.add_edge(order_arr[0][rand_index[0]], order_arr[0][rand_index[1]]) G.add_edge(order_arr[0][rand_index[2]], order_arr[0][rand_index[3]]) i = i + 1 ##############计算两种同配性系数############### r1 = round(nx.degree_assortativity_coefficient(G), 6) M = nx.degree_mixing_matrix(G) M2 = M * M #print(np.sum(M2)) r2 = (M.trace() - np.sum(M2)) / (1 - np.sum(M2)) return r1, r2
def test_degree_mixing_matrix_mapping(self): a_result = np.array([[6.0, 1.0], [1.0, 0.0]]) mapping = {0.5: 1, 1.5: 0} a = nx.degree_mixing_matrix(self.W, weight="weight", normalized=False, mapping=mapping) np.testing.assert_equal(a, a_result)
def get_assortativity_coeff(G): a = nx.degree_mixing_matrix(G) # a: assortativity matrix M = np.matrix(a) sum_rows = np.add.reduce(M,axis=0) sum_lines = np.add.reduce(M,axis=1) sum_rows_sq = sum_rows * np.transpose(sum_lines) sum_sq = np.add.reduce(sum_rows_sq).item(0) d = (np.trace(M) - sum_sq) / (1 - sum_sq) return d
def two_reg_edge_rewiring(n1, k1, n2, k2, rat): G1 = nx.random_regular_graph(k1, n1) G2 = nx.random_regular_graph(k2, n2) #~ print len(G1.edges()) #~ print len(G2.edges()) H = nx.union(G1, G2, rename=['G1-', 'G2-']) mix_mat = nx.degree_mixing_matrix(H) mix_mat[k1, k2] = rat mix_mat[k2, k1] = mix_mat[k1, k2] mix_mat[k1, k1] -= rat mix_mat[k2, k2] -= rat print mix_mat for i in range((n1 * k1 + n2 * k2)): selected_H1_edge = H.edges()[rd.randint(0, (n1 * k1 + n2 * k2) / 2 - 1)] H1_edge_ele_1 = selected_H1_edge[0] H1_edge_ele_2 = selected_H1_edge[1] #~ print len(H.edges()) while 1: selected_H2_edge = H.edges()[rd.randint( 0, (n1 * k1 + n2 * k2) / 2 - 1)] #~ print selected_H1_edge #~ print selected_H2_edge H2_edge_ele_1 = selected_H2_edge[0] H2_edge_ele_2 = selected_H2_edge[1] if H1_edge_ele_1 != H2_edge_ele_1 and H1_edge_ele_2 != H2_edge_ele_2 and H1_edge_ele_1 != H2_edge_ele_2 and H1_edge_ele_2 != H2_edge_ele_1 and H1_edge_ele_1 not in H[ H2_edge_ele_1] and H1_edge_ele_2 not in H[H2_edge_ele_2]: break if (mix_mat[len(H[H1_edge_ele_1]), len(H[H2_edge_ele_1])] * mix_mat[len(H[H1_edge_ele_2]), len(H[H2_edge_ele_2])] ) / (mix_mat[len(H[H1_edge_ele_1]), len(H[H1_edge_ele_2])] * mix_mat[len(H[H2_edge_ele_1]), len(H[H2_edge_ele_2])]) > rd.random(): H.add_edge(H1_edge_ele_1, H2_edge_ele_1) H.add_edge(H1_edge_ele_2, H2_edge_ele_2) #~ elist = [] #~ elist.append((H1_edge_ele_1, H2_edge_ele_1)) #~ elist.append((H1_edge_ele_2, H2_edge_ele_2)) #~ H.add_edges_from(elist) #~ print elist H.remove_edge(H1_edge_ele_1, H1_edge_ele_2) H.remove_edge(H2_edge_ele_1, H2_edge_ele_2) #~ print selected_H1_edge #~ print selected_H2_edge #~ print len(H.edges()) return H
def synthetic(n, connectedDegree = True, keepConnected = True): F = data.readFeederData(n); dh = nx.degree_histogram(F) mat = nx.degree_mixing_matrix(F) dd = utils.degreehisto_to_degreeseq(dh) if connectedDegree: G = havel_hakimi_custom_graph(dd) else: G = nx.random_degree_sequence_graph(dd) """print("Degree distribution : " + str(dh)) print("Nb cc : " + str(nx.number_connected_components(G))) dh2 = nx.degree_histogram(G) print("Result Degree distribution : " + str(dh2))""" G = transform_graph_assortativity_coef(G,mat,keepConnected) return G
import networkx as nx G = nx.read_edgelist('soc-sign-bitcoinotc.csv', delimiter=',', nodetype=int, data=(('weight', int), ('timestamp', float)), encoding="utf-8") jaccard_coefficient = nx.jaccard_coefficient(G) degree_assortativity_coefficient = nx.degree_assortativity_coefficient(G) degree_mixing_matrix = nx.degree_mixing_matrix(G) print("Degree assortativity coefficient: ", degree_assortativity_coefficient) print("Degree mixing matrix: ", degree_mixing_matrix) print("Jaccard coefficients between each node (u and v): ") for u, v, p in jaccard_coefficient: print(u, v, p)
' edges: %d' % len(G_Voxel_conn.edges())) ##### Assortativity coefficients print('Assortativity coefficients') print('Brain (ROI): %5.3f' % nx.degree_assortativity_coefficient(G_ROI)) print('Brain (Voxel): %5.3f' % nx.degree_assortativity_coefficient(G_Voxel)) print('Brain (ROI, connected): %5.3f' % nx.degree_assortativity_coefficient(G_ROI_conn)) print('Brain (Voxel, connected): %5.3f' % nx.degree_assortativity_coefficient(G_Voxel_conn)) ##### Assorativity mixing matrix plt.figure(figsize=[9, 9]) plt.subplot(221) M_ROI = nx.degree_mixing_matrix(G_ROI) plt.imshow(M_ROI) plt.colorbar() plt.title('Mixing matrix, brain (ROI)') plt.xlabel('Terminus degree') plt.ylabel('Origin degree') plt.subplot(222) M_Voxel = nx.degree_mixing_matrix(G_Voxel) plt.imshow(M_Voxel) plt.colorbar() plt.title('Mixing matrix, brain (voxel)') plt.xlabel('Terminus degree') plt.ylabel('Origin degree') plt.subplot(223)
def test_degree_mixing_matrix_weighted(self): a_result = np.array([[0.0, 1.0], [1.0, 6.0]]) a = nx.degree_mixing_matrix(self.W, weight="weight", normalized=False) np.testing.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.W, weight="weight") np.testing.assert_equal(a, a_result / float(a_result.sum()))
def graph_tools(G): tic = time.perf_counter() print("Graph analysis started...") G.nn = len(list(G.nodes)) G.nl = len(list(G.edges)) print(" [1/4] Calculating connectivity...") k = G.degree() G.degree_list = [d for n, d in k] G.k_avg = np.mean(G.degree_list) G.k_std = np.std(G.degree_list) G.k_var = np.var(G.degree_list) G.degree_sequence = sorted(G.degree_list, reverse=True) G.k_max = np.max(G.degree_list) # G.degree_sequence[0] G.k_min = np.min(G.degree_list) # G.degree_sequence[-1] G.k_histD = np.array(nx.degree_histogram(G)) / G.nn # Prima correzione per non avere matrice singolare G.kx = np.array(range(len(G.k_histD)), ndmin=2) + 1e-10 G.kfm = np.dot(G.kx, G.k_histD).item() G.ksm = np.dot(G.kx**2, G.k_histD).item() G.Lma = G.ksm / G.kfm - 1 G.Crita = G.k_avg / G.Lma G.ktilde = np.transpose((G.kx - 1) / G.kx) # Seconda correzione per non avere matrice singolare G.Mix = nx.degree_mixing_matrix(G)[G.k_min:, G.k_min:] + 1e-10 G.P = 1 / sum(G.Mix) * G.Mix G.Ckk = G.kx[:, G.k_min:] * G.P * G.ktilde[G.k_min:, :] G.w, G.v = np.linalg.eig(G.Ckk) G.Lm = np.real(np.nanmax(G.w)) G.Crit = G.k_avg / G.Lm print(" Lm: " + str(np.round([G.Lma, G.Lm], 2))) print(" Connectivity degree histogram completed.") print(" [2/4] Calculating betweenness centrality...") BC = nx.betweenness_centrality(G) # , normalized = False) G.BC_list = [bc for bc in BC.values()] print(" Betweenness centrality list completed.") # Cl = nx.closeness_centrality(G) # Cl_list = [cl for cl in Cl.values()] # G.eig_list = nx.adjacency_spectrum(G) # # eig_sequence = sorted(eig_list, reverse=True) # G.A = nx.adj_matrix(G) # create a sparse adjacency matrix # G.A = G.A.asfptype() # convert the sparse values from int to float # # plt.spy(A) # G.eig_val, G.eig_vec = sp.sparse.linalg.eigs(G.A) print(" [3/4] Calculating clustering...") C = nx.clustering(G) G.C_list = [c for c in C.values()] G.C_avg = nx.average_clustering(G) print(" Clustering list completed.") print(" [4/4] Calculating shortest path lengths...") G.L_avg = nx.average_shortest_path_length(G) print(" Average shortest path lengt estimated.") toc = time.perf_counter() print(f'--> graph_tools() completed in {toc - tic:0.0f} seconds.\n') return G
def calculate_disass(G, p, Iteration): i = 0 while i < Iteration: print(i) edge = list(G.edges()) degree = nx.degree(G) index1 = random.randint(0, len(G.edges) - 1) ##随机获取第一条边 index2 = random.randint(0, len(G.edges) - 1) ##随机获取第二条边 edge1 = edge[index1] edge2 = edge[index2] k1 = degree[edge1[0]] k2 = degree[edge1[1]] k3 = degree[edge2[0]] k4 = degree[edge2[1]] tag = 0 if edge1[0] != edge2[0] and edge1[0] != edge2[1] and edge1[1] != edge2[ 0] and edge1[1] != edge2[1]: tag = 1 order_arr = [[edge1[0], edge1[1], edge2[0], edge2[1]], [k1, k2, k3, k4]] order_arr = np.array(order_arr) order_arr = order_arr[:, order_arr[1].argsort()] p1 = random.random() ############在网络中移除原来的边并加上新的边########## if p1 < p and tag == 1: judge_tag = Judge_in_graph(G, order_arr[0][0], order_arr[0][3], order_arr[0][1], order_arr[0][2]) if judge_tag: G.add_edge(order_arr[0][0], order_arr[0][3]) G.add_edge(order_arr[0][1], order_arr[0][2]) G.remove_edge(edge1[0], edge1[1]) G.remove_edge(edge2[0], edge2[1]) i = i + 1 if p1 >= p and index1 != index2 and tag == 1: #################随机重连#################### rand_index = random.sample(range(0, 4), 4) judge_tag = Judge_in_graph(G, order_arr[0][rand_index[0]], order_arr[0][rand_index[1]], order_arr[0][rand_index[2]], order_arr[0][rand_index[3]]) if judge_tag: G.remove_edge(edge1[0], edge1[1]) G.remove_edge(edge2[0], edge2[1]) G.add_edge(order_arr[0][rand_index[0]], order_arr[0][rand_index[1]]) G.add_edge(order_arr[0][rand_index[2]], order_arr[0][rand_index[3]]) i = i + 1 #r1 = round(nx.degree_assortativity_coefficient(G),6) M = nx.degree_mixing_matrix(G) M2 = M * M r1 = (M.trace() - np.sum(M2)) / (1 - np.sum(M2)) conncected = nx.is_connected(G) if conncected: r2 = round(nx.average_shortest_path_length(G), 6) else: sv = 0 coun = 0 for C in (G.subgraph(c).copy() for c in nx.connected_components(G)): v = nx.average_shortest_path_length(C) sv = sv + v coun = coun + 1 r2 = sv / coun return r1, r2
print('Formato %s no aceptado' % args.format) sys.exit(1) filename = '-'.join(args.file.split('/')[-1].split('.')) ############################################################################### # Creacion del grafo a partir del archivo de entrada ############################################################################### import igraph import networkx as nx import numpy as np igrafo = igraph.read(args.file, format=args.format) grafo = nx.Graph(igrafo.get_edgelist()) # matriz de probabilidad de interaccion entre nodos de grado k_i y k_j mixing = np.rot90(nx.degree_mixing_matrix(grafo, normalized=True)) for i in range(mixing.shape[0]): for j in range(mixing.shape[1]): if mixing[i, j] == 0: mixing[i, j] = -3e-3 k_nn = nx.average_neighbor_degree(grafo) degrees = list(k_nn.keys()) ############################################################################### # Ploteo ############################################################################### import matplotlib.pyplot as plt import seaborn as sns plt.style.use(['seaborn-talk', 'seaborn-whitegrid'])
def get_example_assortativity_matrices(): l = [] for k in examples_list: G = msd.readFeederData(k) l += [nx.degree_mixing_matrix(G)] return l
def update_graph(self, chosen_nt_node: int, chosen_rule: VRGRule, node_correspondence: Union[None, Dict] = None) -> None: """ Update the current graph by - removing the node corresponding to the NonTerminal - replacing that with the RHS graph of the rule - rewiring the broken edges - node labels are carried """ existing_node = chosen_nt_node logging.debug(f'Replacing node: {existing_node} with rule {chosen_rule}') chosen_nt: NonTerminal = self._gen_graph.nodes[chosen_nt_node]['nt'] assert self._gen_graph.degree_(existing_node) == chosen_nt.size, 'Degree of non-terminal must match its size' broken_edges = find_boundary_edges(self._gen_graph, {existing_node}) # find the broken edges broken_edges: Counter[tuple, int] = CustomCounter(broken_edges) # TODO change to a Counter object to speed things up assert sum(broken_edges.values()) == chosen_nt.size, f'Incorrect #broken edges: {len(broken_edges)} != {chosen_nt.size}' self.total_rewirings += broken_edges.positive_values_len() # all the broken edges need to be rewired node_count = max(self._gen_graph.nodes) + 1 # number of nodes in the present graph self._gen_graph.remove_node(existing_node) # remove the existing node from the graph node_label = {} # empty dictionary b_degs = {} # this is needed to not modify the boundary degrees of rules in place for node, d in chosen_rule.graph.nodes(data=True): # add the nodes from rule node_label[node] = node_count b_degs[node] = d['b_deg'] if 'nt' in d: self.current_non_terminal_nodes.add(node_label[node]) # add the nonterminal node to the set if 'attr_dict' in d: d = d['attr_dict'] self._gen_graph.add_node(node_label[node], **d) node_count += 1 for u, v, d in chosen_rule.graph.edges(data=True): # add edges from rule self._gen_graph.add_edge(node_label[u], node_label[v], **d) if broken_edges.positive_values_len() != 0: if self.use_fancy_rewiring: # Figure out if there are terminal nodes on both RULE and the current graph rule_terminals = [node for node, d in chosen_rule.graph.nodes(data=True) if 'nt' not in d] graph_terminal_ctr = CustomCounter() # for u, v in broken_edges: for u, v in broken_edges.elements(): node = v if u == existing_node else u if 'nt' not in self._gen_graph.nodes[node]: graph_terminal_ctr[node] += 1 # .append(node) if len(rule_terminals) > 0 and len(graph_terminal_ctr) > 0: # this is where the probabilistic matching needs to happen # rule_terminal_list = [] # we need b_deg copies of each terminal in the rules rule_terminal_ctr = CustomCounter() # we need b_deg copies of each terminal in the rules # TODO changed for rule_t in rule_terminals: b_deg = b_degs[rule_t] if b_deg > 0: rule_terminal_ctr[rule_t] = b_deg # assert graph_terminal_ctr.positive_values_len() <= rule_terminal_ctr.positive_values_len() # do the matching up while True: if graph_terminal_ctr.positive_values_len() == 0 or rule_terminal_ctr.positive_values_len() == 0: break # 1. pick a graph terminal at random and remove it graph_t = random.choice(list(graph_terminal_ctr.keys())) graph_terminal_ctr[graph_t] -= 1 # 2. pick a rule terminal based on incremental assortativity best_rule_terminal = None, np.inf # we actually dont need to calculate assortativity mixing mat from scratch here # TODO attr_mixing_mat = nx.attribute_mixing_matrix(self._gen_graph, attribute=self.attr_name, mapping=self.mapping, normalized=False) deg_mixing_mat = nx.degree_mixing_matrix(self._gen_graph, normalized=False) ###### for rule_t in rule_terminal_ctr: # calculate degree and attribute ast after edge (graph_t, node_label[rule_t]) u, v = graph_t, node_label[rule_t] attr_u, attr_v = self._gen_graph.nodes[u][self.attr_name], self._gen_graph.nodes[v][self.attr_name] new_deg_ast, new_deg_mixing_mat = incremental_degree_assortativity(g=self._gen_graph, u=u, v=v, M_curr=deg_mixing_mat) new_attr_ast, new_attr_mixing_mat = incremental_attr_assortativity(g=self._gen_graph, attr_name=self.attr_name, attr_u=attr_u, attr_v=attr_v, mapping=self.mapping, M=attr_mixing_mat) deg_ast_diff = np.abs(self.inp_deg_ast - new_deg_ast) attr_ast_diff = np.abs(self.inp_attr_ast - new_attr_ast) cost = -1 if np.isnan(deg_ast_diff) else self.alpha * deg_ast_diff if not np.isnan(attr_ast_diff): cost += (1 - self.alpha) * attr_ast_diff if cost < best_rule_terminal[1]: best_rule_terminal = rule_t, cost best_deg_mixing_mat = new_deg_mixing_mat best_attr_mixing_mat = new_attr_mixing_mat rule_t = best_rule_terminal[0] assert rule_t is not None rule_terminal_ctr[rule_t] -= 1 # .remove(rule_t) logging.debug(f'Best rule terminal {node_label[rule_t]} cost = {best_rule_terminal[1]}') # 3. Add the edge to gen_graph logging.debug(f'Adding broken edge {(node_label[rule_t], graph_t)} the fancy way') self._gen_graph.add_edge(graph_t, node_label[rule_t]) # node_label stores the actual label in gen_graph # update the mixing matrices # deg_mixing_mat = best_deg_mixing_mat.copy() # attr_mixing_mat = best_attr_mixing_mat.copy() # assert np.allclose(nx.degree_mixing_matrix(self._gen_graph, normalized=False), deg_mixing_mat) self.fancy_rewirings += 1 # fancy rewiring # 3. update b_deg for the rule terminal b_degs[rule_t] -= 1 # 4. Remove the boundary edge from list of boundary edges if (graph_t, existing_node) in broken_edges: # broken_edges.remove((graph_t, existing_node)) broken_edges[(graph_t, existing_node)] -= 1 else: # broken_edges.remove((existing_node, graph_t)) broken_edges[(existing_node, graph_t)] -= 1 # continue the regular random rewiring with the remaining broken edges broken_edges: list = list(broken_edges.elements()) # turn broken edges back into a list random.shuffle(broken_edges) # shuffle the broken edges # randomly joining the new boundary edges from the RHS to the rest of the graph - uniformly at random for node, d in chosen_rule.graph.nodes(data=True): num_boundary_edges = b_degs[node] if num_boundary_edges == 0: # there are no boundary edges incident to that node continue assert len(broken_edges) >= num_boundary_edges edge_candidates = broken_edges[: num_boundary_edges] # picking the first num_broken edges broken_edges = broken_edges[num_boundary_edges:] # removing them from future consideration for u, v in edge_candidates: # each edge is either (node_sample, v) or (u, node_sample) if u == existing_node: # u is the existing node, rewire it to node u = node_label[node] else: v = node_label[node] logging.debug(f'adding broken edge ({u}, {v})') self._gen_graph.add_edge(u, v) return
rank_netsci = np.arange(len(sk_netsci)) + 1 plt.plot(sk_netsci,rank_netsci,'b-') plt.xscale('log') plt.yscale('log') plt.xlabel('Degree') plt.ylabel('Rank') plt.title('Degree distribution, netsci') plt.show() # Connection probability matrix fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.xaxis.set_ticks_position('top') ax.xaxis.set_label_position('top') Rjk_karate = nx.degree_mixing_matrix(G_karate) plt.imshow(Rjk_karate) plt.xlabel('Node 1 degree') plt.ylabel('Node 2 degree') plt.colorbar() plt.show() fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.xaxis.set_ticks_position('top') ax.xaxis.set_label_position('top') Rjk_netsci = nx.degree_mixing_matrix(G_netsci) plt.imshow(Rjk_netsci) plt.xlabel('Node 1 degree') plt.ylabel('Node 2 degree')
G_ROI = nx.read_adjlist('DataNetStats/Oxford_sub16112_aal90_d5.adjlist') # Brain (Voxel) G_Voxel = nx.read_adjlist('DataNetStats/Oxford_sub16112_voxel_d20.adjlist') ##### Assortativity coefficients print('Assortativity coefficients') print('C. Elegans: %5.3f' % nx.degree_assortativity_coefficient(G_CEleg)) print('Power grid: %5.3f' % nx.degree_assortativity_coefficient(G_Power)) print('Brain (ROI): %5.3f' % nx.degree_assortativity_coefficient(G_ROI)) print('Brain (Voxel): %5.3f' % nx.degree_assortativity_coefficient(G_Voxel)) ##### Assorativity mixing matrix plt.figure(figsize=[9, 9]) plt.subplot(221) M_CEleg = nx.degree_mixing_matrix(G_CEleg) plt.imshow(M_CEleg) plt.colorbar() plt.title('Mixing matrix, C Elegan') plt.xlabel('Terminus degree') plt.ylabel('Origin degree') plt.subplot(222) M_Power = nx.degree_mixing_matrix(G_Power) plt.imshow(M_Power) plt.colorbar() plt.title('Mixing matrix, power grid') plt.xlabel('Terminus degree') plt.ylabel('Origin degree') plt.subplot(223)
def transform_graph_assortativity_coef(G,A,limitateConnComp = True): ### G: graph to rewire for desired assortativity coeff (at constant degree distribution) ### A: desired assortativity matrix coeff_d = numeric_ac(A) ### resize matrix of desired assortativity with zeros if actual is bigger assortativity_actual = nx.degree_mixing_matrix(G) epsilon = len(assortativity_actual) - len(A) if epsilon > 0: for j in range(len(A)): A[j] += [0]*epsilon for k in range(epsilon): A.append([0]*(len(A)+epsilon)) k = 0 print("Desired assortativity coefficient : " + str(coeff_d)) print("Actual before : " + str(nx.degree_assortativity_coefficient(G))) nb_identical = 0 prev_delta = 0.2 delta = 0.2 nb_swaps = 0 window = 1 nb_undo_window = 0 number_cc_prev = nx.number_connected_components(G) while abs(delta) > 0.01 and nb_identical < 400: swapped = [] countw = 0 save_nb_identical = nb_identical save_delta = delta save_prev_delta = prev_delta save_nb_swaps = nb_swaps while countw < window and delta > 0.01 and nb_identical < 400: nodes = nx.nodes(G) ### choose two random edges u1 = random.choice(nodes) neighb = G.neighbors(u1) if len(neighb) == 0: continue v1 = random.choice(neighb) j1 = G.degree(u1) k1 = G.degree(v1) u2 = random.choice(nodes) neighb = G.neighbors(u2) if len(neighb) == 0: continue v2 = random.choice(neighb) j2 = G.degree(u2) k2 = G.degree(v2) if (u1 == u2 or v1 == v2 or u1 == v2 or u2 == v1): continue if (G.has_edge(u1,u2) or G.has_edge(v1,v2)): continue ### compute rewiring probability denom = A[j1][k1]*A[j2][k2] p = 1 if denom != 0: p = A[j1][j2]*A[k1][k2]/denom ### rewire if denom == 0 or p > 1 or p >= random.random(): G.remove_edge(u1,v1) G.remove_edge(u2,v2) G.add_edge(u1,u2) G.add_edge(v1,v2) countw += 1 nb_swaps += 1 swapped.append((u1,v1,u2,v2)) # actual_coeff = get_assortativity_coeff(nx.degree_mixing_matrix(G)) actual_coeff = nx.degree_assortativity_coefficient(G) delta = abs(actual_coeff - coeff_d) if abs(prev_delta - delta) < 0.001: nb_identical += 1 else: nb_identical = 0 prev_delta = delta k+= 1 if limitateConnComp or save_delta < delta: nb_cc = nx.number_connected_components(G) if nb_cc <= number_cc_prev and save_delta >= delta: #window += 1 number_cc_prev = nb_cc else: # undo changes from previous window, decrease window #print("undo " + str(window) +" " + str(countw)) while swapped: (u,v,x,y)=swapped.pop() G.add_edge(u,v) G.add_edge(x,y) G.remove_edge(u,x) G.remove_edge(v,y) nb_swaps -= 1 window = max(int(ceil(float(window)/2)),1) # restore values from the beginning of the past window nb_identical = save_nb_identical prev_delta = save_prev_delta delta = save_delta nb_swaps = save_nb_swaps nb_undo_window += 1 if nb_undo_window >= 1000: break print("Actual after : " + str(nx.degree_assortativity_coefficient(G))) print(str(k) + " turn(s), " + str(nb_swaps) + " swap(s), " + str(nb_undo_window) + " undo_windows") return G