OSMNX 最短路径 - 如果无法访问,如何跳过节点并采用下一个最近的节点

OSMNX Shortest Path - How to skip node if not reachable and take the next nearest

我在 python 上使用 OSMNX 库。 我正在从一个坐标点创建一个 'drive' 街道网络 我将参数 '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

你的图是弱连接的。因此,某些节点可能无法从某些其他节点访问。这里有几个选项。 1,你可以复制你的图并从中递归地删除无法解决的origins/destinations,直到你得到一个可解决的路径。 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')