我正在python上使用OSMNX库。 我正在从协调点创建“行车”街道网络 我将参数'retain_all'设置为False(我假设它只应带动连接的节点) 但是,当我运行最短路径功能时,出现错误“无法从5636337791到达节点7079214188”
我知道我可以使用'try'和'except',但是我正在寻找一种方法来调整最短路径功能并跳到可以到达的下一个最近节点。
请在下面的代码中重现该问题:
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
答案 0 :(得分:2)
您的图形连接弱。因此,某些节点可能与某些其他节点不可访问。这里有几个选择。 1,您可以复制图形并从中递归地删除无法解决的起点/终点,直到获得可求解的路径。 2,您可以改用强连接图。
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')