I am using the OSMNX library on python. I am creating a 'drive' street network from a coordinate point I am setting the parameter 'retain_all' to False (I am assuming it should only bring connected nodes) However when i am running the shortest path function, i get the error "Node 7079214188 not reachable from 5636337791"
I know i can use 'try' and 'except' but i am looking for a way to adjust the shortest path function and skip to next nearest node that can be reachable.
Kindly find below the code to reproduce the problem :
import networkx as nx
import osmnx as ox
import plotly.graph_objects as go
import numpy as np
RDC_Coordinates = (27.4757976,-82.4192142)
X = ox.graph_from_point(RDC_Coordinates,distance=32186,network_type='drive',retain_all=False)
#Plot map
#fig, ax = ox.plot_graph(X)
# define origin and desination locations
origin_point = (27.4289, -82.388) #Blue Runner
destination_point = (27.476, -82.4192) # Terracota
# get the nearest network node to each point
orig_node = ox.get_nearest_node(X, origin_point)
dest_node = ox.get_nearest_node(X, destination_point)
# how long is our route in miles?
nx.shortest_path_length(X, orig_node, dest_node, weight='length')/1609
Your graph is weakly connected. Thus, some nodes may be unreachable from certain other nodes. Here are a couple of options. 1, you could copy your graph and recursively remove unsolvable origins/destinations from it until you get a solvable path. 2, you could use a strongly connected graph instead.
import networkx as nx
import osmnx as ox
ox.config(use_cache=True, log_console=True)
center_point = (27.4757976, -82.4192142)
orig_point = (27.4289, -82.388)
dest_point = (27.476, -82.4192)
G = ox.graph_from_point(center_point, dist=1000, network_type='drive', retain_all=False)
# FAILS due to unsolvable path
orig_node = ox.get_nearest_node(G, orig_point)
dest_node = ox.get_nearest_node(G, dest_point)
nx.shortest_path_length(G, orig_node, dest_node, weight='length')
# OPTION 1: recursively remove unsolvable origin/destination nodes and re-try
G2 = G.copy()
solved = False
while not solved:
try:
orig_node = ox.get_nearest_node(G2, orig_point)
dest_node = ox.get_nearest_node(G2, dest_point)
print(nx.shortest_path_length(G2, orig_node, dest_node, weight='length'))
solved = True
except nx.exception.NetworkXNoPath:
G2.remove_nodes_from([orig_node, dest_node])
# OPTION 2: use a strongly (instead of weakly) connected graph
Gs = ox.utils_graph.get_largest_component(G, strongly=True)
orig_node = ox.get_nearest_node(Gs, orig_point)
dest_node = ox.get_nearest_node(Gs, dest_point)
nx.shortest_path_length(Gs, orig_node, dest_node, weight='length')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With