Sort multi edge nodes with networkx in python
import
import networkx as nx import numpy as np
Create multi graph
G = nx.MultiGraph() G.add_nodes_from(["A", "B", "C", "D", "E", "F"]) G.add_edges_from([("A", "B"), ("B", "C"), ("B", "D"), ("C", "D"), ("A", "E"), ("C", "E"), ("C", "F"), ("C", "F"), ("F", "F")])
- this graph has multi edge in between node C and F
- in this case, we want to visualize its multi edges in matplotlib
Approach1. Convert data structure G to Adjacency matrix
- "Adjacency matrix" is the way to describe network data structure by using matrix.
- It is described as below
A = (nx.adjacency_matrix(G)).todense() // output of A matrix([[0., 1., 0., 0., 1., 0.], [1., 0., 1., 1., 0., 0.], [0., 1., 0., 1., 1., 2.], [0., 1., 1., 0., 0., 0.], [1., 0., 1., 0., 0., 0.], [0., 0., 2., 0., 0., 1.]])
- next, we want to sort its matrix with the filter.
- The filter serves some nodes which have multi edges.
- How to generate the filter
- Flatten A to one dimension array or list
- get index number from it by sorting
- get node value from origin node list by using above index number
node_list = list(G) A_flatten = np.ravel(A) idx_sorted_list = np.where(A_flatten >= 2)[0] # return value is tuple [node_list[(I % len(G.nodes))] for I in idx_sorted_list] // ['F', 'C']
Then after, let's try to apply this way to existed dataset. In this time, we use zachary's karate club graph.
import networkx as nx import numpy as np import matplotlib.pyplot as plt def get_multi_edge_nodes(G, threshold): node_list = list(G) A = nx.adjacency_matrix(G) A_flatten = np.ravel(A.todense()) idx_sorted_list = np.where(A_flatten >= threshold)[0] # return value is tuple node_multi_edge_list = [node_list[(I % len(G.nodes))] for I in idx_sorted_list] return set(node_multi_edge_list) def rand_edges(node_num, edge_num): def randint(low, high, size): return np.random.randint(low, high, size) return [(s, t) for s, t in zip(randint(0, node_num, edge_num), randint(0, node_num, edge_num))] G_01 = nx.karate_club_graph() G_02 = nx.MultiGraph() G_02.add_edges_from(G_01.edges) G_02.add_edges_from(rand_edges(len(G_02), 20)) ret1 = get_multi_edge_nodes(G_01, 2) ret2 = get_multi_edge_nodes(G_02, 2) G_02_sub = G_02.subgraph(ret2) fig, (ax1, ax2) = plt.subplots(1, 2) nx.draw_networkx(G_01, ax=ax1) nx.draw_networkx(G_02_sub, ax=ax2) plt.savefig('test.png')