CF84 CF84 - 6 months ago 23
Python Question

Python: all shortest paths in disconnected components of a graph

I am computing all the possible shortest paths between any two nodes in a regular network. If the network is connected (e.g., largest component = entire network), I have no problems.

The problem arises when I have disconnected components: given that there is no path between node

n
and node
j
, a
NetworkXNoPath
error is raised.

My problem: I want to skip all pairs of nodes that are not connected. I know I need an
if
to check for the presence of the error being raised, but I don't know how to add it to my code.

My code for computing all the possible shortest paths between any two nodes in the graph:

import networkx as nx
counts=OrderedDict()
for n in F.nodes(): counts[n]=0
for n in F.nodes():
for j in F.nodes():
if (n!=j):
gener=nx.all_shortest_paths(F,source=n,target=j)
for p in gener:
for v in p: counts[v]+=1


To recap: I can use
nx.bidirectional_dijkstra(F, n, j)
to check for the existence of an edge between node
n
and node
j
, and it raises the
NetworkXNoPath
error if such edge is missing, but how can I check for this error so to skip a pair of non-connected nodes?

Answer

you can use error handling in python for this.

try:
  nx.bidirectional_dijkstra(F, n, j)
except NetworkXNoPath:
  # do whatever you want

you can use this link for more help

Comments