Stopping algorithm from braking on error

50 views
Skip to first unread message

PeteB

unread,
Feb 9, 2012, 6:23:14 PM2/9/12
to networkx-discuss
Hi all

I have a network on which I am running a shortest path dijkstra.

I am interested in how the shortest path changes when a subset of
vertices is removed from the network. In some cases this may mean that
a node is completely isolated from the rest of the network (not
connected to any other node). When the script tries to get to this
node, it breaks with an error.

My question is, is it possible to stop this occurring/have the script
return some kind of message and yet continue with the rest of the
algorithm?

Many thanks

Aric Hagberg

unread,
Feb 9, 2012, 9:25:29 PM2/9/12
to networkx...@googlegroups.com

Yes, you can use a try/except clause, e.g.:
In [1]: import networkx as nx

In [2]: G=nx.Graph()

In [3]: G.add_nodes_from([1,2,3])

In [4]: nx.dijkstra_path(G,1,2)
---------------------------------------------------------------------------
NetworkXNoPath Traceback (most recent call last)

/home/aric/<ipython console> in <module>()

...networkx/algorithms/shortest_paths/weighted.pyc in dijkstra_path(G,
source, target, weight)
74 return path[target]
75 except KeyError:
---> 76 raise nx.NetworkXNoPath("node %s not reachable from
%s"%(source,target))
77
78

NetworkXNoPath: node 1 not reachable from 2

In [5]: try:
...: nx.dijkstra_path(G,1,2)
...: except nx.NetworkXNoPath:
...: print "no path" # use pass to do nothing
...:
...:
no path

Aric

Reply all
Reply to author
Forward
0 new messages