如何解决如何解决NetworkX错误NoPath:无法从Y
Im将最近的节点附加到OSMNX绘制的每个公司,然后创建基于网络的距离矩阵,以便从此TUTORIAL
复制基于网络的空间聚类加快距离矩阵的计算速度,而不是计算每个公司到每个公司的距离,而是找到每个至少附着一个公司的节点,然后计算每个这样的节点到每个这样的节点距离。一旦有了节点到节点的距离,就可以重新索引它,以利用这些距离来确定企业。
这是代码:
# attach nearest network node to each firm --APPLY SOLUTION B HERE
firms['nn'] = ox.get_nearest_nodes(G,X=firms['x'],Y=firms['y'],method='balltree')
print(len(firms['nn']))
# we'll get distances for each pair of nodes that have firms attached to them
nodes_unique = pd.Series(firms['nn'].unique())
nodes_unique.index = nodes_unique.values
print(len(nodes_unique))
# convert MultiDiGraph to DiGraph for simpler faster distance matrix computation
G_dm = nx.DiGraph(G)
输出:
269
230
time: 2.74 s
之后
# calculate network-based distance between each node --APPLY SOLUTION A HERE
def network_distance_matrix(u,G,vs=nodes_unique):
dists = [nx.dijkstra_path_length(G,source=u,target=v,weight='length') for v in vs]
return pd.Series(dists,index=vs)
最后
%%time
from tqdm._tqdm_notebook import tqdm_notebook
tqdm_notebook.pandas()
# create node-based distance matrix called node_dm
node_dm = nodes_unique.progress_apply(network_distance_matrix,G=G_dm)
node_dm = node_dm.astype(int)
print(node_dm.size)
解决方案A和B特别要感谢gboeing:
# OPTION A: recursively remove unsolvable origin/destination nodes and re-try
def network_distance_matrix(u,vs=nodes_unique):
G2 = G.copy()
solved = False
while not solved:
try:
dists = [nx.dijkstra_path_length(G,index=vs)
solved = True
except nx.exception.NetworkXNoPath:
G2.remove_nodes_from([dist])
# OPTION B: Use a strongly (instead of weakly) connected graph
Gs = ox.utils_graph.get_largest_component(G,strongly=True)
# attach nearest network node to each firm
firms['nn'] = ox.get_nearest_nodes(Gs,method='balltree')
print(len(firms['nn']))
# we'll get distances for each pair of nodes that have firms attached to them
nodes_unique = pd.Series(firms['nn'].unique())
nodes_unique.index = nodes_unique.values
print(len(nodes_unique))
# convert MultiDiGraph to DiGraph for simpler faster distance matrix computation
G_dm = nx.DiGraph(Gs)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。