Search code examples
pythonnetworkxosmnx

How is the shortest path computed with Osmnx and NetworkX?


When trying to compute the shortest path with various methods, I don't get the same result (which you could expect) but I can't tell how each one is working...

For instance, when working with the French city Annecy here are the results when applying Dijkstra algorithm from NetworkX or from OSMnx

import osmnx as ox
import networkx as nx


Cities = ['Annecy, France','Epagny Metz-Tessy, France']
graph_city = ox.graph_from_place(Cities, network_type='drive', simplify=True, truncate_by_edge=False, clean_periphery =True)
graph_city = ox.project_graph(graph_city)
graph_city = ox.consolidate_intersections(graph_city, rebuild_graph=True, tolerance=15, dead_ends=True)


graph_city = ox.add_edge_speeds(graph_city)
graph_city = ox.add_edge_travel_times(graph_city)


DEP_node = 530
ARR_node  = 549


path_NX = nx.dijkstra_path(graph_city, DEP_node, ARR_node)
path_OX_L = ox.shortest_path(graph_city, DEP_node, ARR_node, weight='length')
path_OX_T = ox.shortest_path(graph_city, DEP_node, ARR_node, weight='time')

fig, ax = ox.plot_graph_routes(graph_city, [path_NX,path_OX_L,path_OX_T], route_colors=['r','g','y'], route_linewidth=4,node_size=1, figsize=(7,7), bgcolor='#FFFFFF', node_color='#111111')

Then to access the time or the length of each path, I apply those lines :

Time = int(sum(ox.utils_graph.get_route_edge_attributes(graph_city,path, 'travel_time')))
Length = int(sum(ox.utils_graph.get_route_edge_attributes(graph_city, path, 'length')))

And here are my results :

             path_NX         path_OX_L          path_OX_T
TIME           238              211                238
LENGTH        2136             1959               2136

So it appears that path_OX_L (using OSMnx to compute the shortest path with the length) is not only the shortest in length but also the quicker. Then, what is the aim of having a path that should be quicker :path_OX_T which clearly is not ?


Solution

  • path_OX_T = ox.shortest_path(graph_city, DEP_node, ARR_node, weight='time')
    

    The attribute time does not exist, and osmnx therefore minimizes graph distance. See here.

    Change it to this:

    path_OX_T = ox.shortest_path(graph_city, DEP_node, ARR_node, weight='travel_time')