Compute shortest paths in the graph.
# Software for Complex Networks. NetworkX has 12 repositories available. Follow their code on GitHub.
import networkx as nx
# OSMnx: New Methods for Acquiring, Constructing, Analyzing, and Visualizing Complex Street Networks
import osmnx as ox
ox.config(use_cache=True, log_console=False)
ox.__version__
'1.1.2'
Create a graph from OSM within some distance of some (lat, lng) point.
center_point = (37.5661, 126.9783) # (lat, lng) Seoul, South Korea
dist = 1000
dist_type = 'bbox' # "network", "bbox"
network_type = 'drive' # "all_private", "all", "bike", "drive", "drive_service", "walk"
# Create a graph from OSM within some distance of some (lat, lng) point.
G = ox.graph_from_point(
center_point,
dist=dist,
dist_type=dist_type,
network_type=network_type)
# Plot a graph.
fig, ax = ox.plot_graph(G)
Compute shortest paths in the graph.
# Set origin and destination node ID
source, target = list(G)[0], list(G)[-1]
# Solve shortest path from origin node(s) to destination node(s).
route = nx.shortest_path(G, source=source, target=target, weight=None, method='dijkstra')
# Plot a route along a graph.
fig, ax = ox.plot_graph_route(G, route)
Compute all shortest simple paths in the graph.
import random
# Set origin and destination node ID
source, target = list(G)[0], list(G)[-1]
# Solve shortest path from origin node(s) to destination node(s).
paths = nx.all_shortest_paths(G, source, target, weight=None, method='dijkstra')
# routes as a list of lists of node IDs
route = list(paths)
# get node colors by linearly mapping an attribute's values to a colormap
route_colors = ["#"+''.join([random.choice('0123456789ABCDEF') for j in range(6)]) for i in range(len(route))]
# Plot several routes along a graph.
fig, ax = ox.plot_graph_routes(G, route, route_colors=route_colors)
Compute shortest path lengths in the graph.
# Compute shortest path lengths in the graph.
shortest_path_length = nx.shortest_path_length(G, source=source, target=target, weight=None, method='dijkstra')
print(shortest_path_length)
23
Returns the average shortest path length.
# Returns the average shortest path length.
average_shortest_path_length = nx.average_shortest_path_length(G, weight=None, method=None)
print(average_shortest_path_length)
18.003037081648454
Returns True if G has a path from source to target.
# Set origin and destination node ID
source, target = list(G)[0], list(G)[-1]
# Returns True if G has a path from source to target.
has_path = nx.has_path(G, source, target)
print(has_path)
True