OSMNX not choosing shorter route

Question:

I’m using OSMnx to do routing between two nodes in a graph and an obvious route is not being returned as one of the shortest.

The relevant code:

start = (42.73843806388065, -84.51908658324757) 
distance_max = 3163.834987247283
G = ox.graph_from_point(start, network_type="drive", dist=distance_max, simplify=False)#, truncate_by_edge=True)
G = ox.utils_graph.get_undirected(G)

lng_orig = -84.51858078986406
lat_orig = 42.73524265064318
lng_dest = -84.51910484455361
lat_dest = 42.753847179060145

orig = ox.distance.nearest_nodes(G, X=lng_orig, Y=lat_orig)
dest = ox.distance.nearest_nodes(G, X=lng_dest, Y=lat_dest)

k_routes = ox.k_shortest_paths(G, orig, dest, 30, weight="distance")

fig, ax = ox.plot_graph_routes(G, list(k_routes), route_colors='r', route_linewidth=5, node_size=20)
plt.show()

The top 30 routes are shown in the image below, I expected a best route to be the road to the right of the long north-south road in the top half of the image. The nodes appear to be connected.

top 30 routes shown in red

Asked By: Mike Dombrowski

||

Answers:

Fix

You want to use a weight of length, not distance.

k_routes = ox.k_shortest_paths(G, orig, dest, 30, weight="length")

routes with length metric

Explanation

This problem is caused by a weird interaction between the OSMnx and networkx libraries.

If you read the docs for k_shortest_paths(), it never mentions that you can pass weight="distance". It turns out that you get the behavior you’re seeing if you pass any invalid weight.

k_routes = ox.k_shortest_paths(G, orig, dest, 30, weight="blah")

If you do this, the weight value put on every graph edge becomes None. OSMnx then calls networkx.shortest_simple_paths(). The docs for that function say that if every weight is None, then the graph is treated as if every edge has unit weight:

If None all edges are considered to have unit weight.

The kind of distance it’s optimizing for here is graph distance. In graph distance, all of the edges between each point have distance one. A road with a curve in it has a distance equal to the number of points used to represent the curve. A long straight road has a distance of one.

Answered By: Nick ODell
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.