python - How to find the number of edges bewteen any two nodes using networkx? -
exist form count number of edges separe 2 nodes, example if have nodes "a", "b", "c" , "d" form "a"-"b"-"c"-"d" (where "-" edge) need count edges between "a" , "d".
the real example follow. have big graph, in link can see image https://drive.google.com/file/d/0b7gayk8mggtccvhrmncym0vmc2c/view?usp=sharing
graph have 2806 nodes in case, , need know example how many edges separe node 608 of 616. thought number_of_edges function can me, think returns if 2 nodes connected or not (because returns 1 or 0 in code this)
k in id1: #id1 list of nodes l in id2: #id2 list of nodes print graph.number_of_edges(k,l)
without knowing have attempted , without example graph give simple example. might clear things you.
i make 4 node, 4 edge graph adjacency matrix using newtworkx , numpy.
import matplotlib.pyplot plt import networkx nx import numpy np adjacency_matrix = np.array([[0,1,0,1], [1,0,1,0], [0,1,0,1], [1,0,1,0]]) print adjacency_matrix
this prints our graph:
[[0 1 0 1] [1 0 1 0] [0 1 0 1] [1 0 1 0]]
now feed adjacency matrix networkx such:
rows, cols = np.where(adjacency_matrix == 1) edges = zip(rows.tolist(), cols.tolist()) gr = nx.graph() gr.add_edges_from(edges)
plot it:
nx.draw_networkx(gr) plt.show()
now can @ nodes connected 1 by:
print gr.number_of_edges(0, 1) # has edge print gr.number_of_edges(2, 0) # no edge between 2 , 0
and expected prints:
1 0
so if getting 0
number_of_edges(a, b)
, b not adjacent (not edge between them).
[edit: if want find paths between 2 , 0 can following
for path in nx.all_simple_paths(gr, source=2, target=0): print(path) # prints # [2, 1, 0] # [2, 3, 0]
or find shortest path:
p = nx.shortest_path(gr,source=2, target=0) # [2, 1, 0]
in case say:
num_edges = len(p) - 1 # num_edges = 2
]
Comments
Post a Comment