【问题标题】:Missing distances when using igraph shortest distance使用 igraph 最短距离时缺少距离
【发布时间】:2020-09-21 04:18:45
【问题描述】:

我正在尝试计算我的网络节点与两个源之间的距离。然后我将最短距离保存在列表中(称为route_length)。但是我的网络有9693 节点在运行我的代码并计算出我仅有的最短路径之后 9602 距离。我不明白为什么我的距离比节点少,而且如果在循环中我将节点保存在一个列表中并在最后打印它的长度,它也会给我一个 9602 个节点的结果,这是不正确的。

这是我的代码:

import networkx as nx
import matplotlib.pyplot as plt
import osmnx as ox
import pandas as pd
from shapely.wkt import loads as load_wkt
import numpy as np
import matplotlib.cm as cm
import igraph as ig
import matplotlib as mpl
import random as rd
ox.config(log_console=True, use_cache=True)


city = 'Portugal, Lisbon'
G = ox.graph_from_place(city, network_type='drive')

G_nx = nx.relabel.convert_node_labels_to_integers(G)

ox.speed.add_edge_speeds(G_nx, hwy_speeds=20, fallback=20)

ox.speed.add_edge_travel_times(G_nx)

weight = 'travel_time'

coord_1 = (38.74817825481225, -9.160815118526642)  # Coordenada Hospital Santa Maria
coord_2 = (38.74110711410615, -9.152159572392323)  # Coordenada Hopstial Curry Cabral
coord_3 = (38.7287248180068, -9.139114834357233) # Hospital Dona Estefania
coord_4 = (38.71814053423293, -9.137885476529883) # Hospital Sao Jose 
target_1 = ox.get_nearest_node(G_nx, coord_1)
target_2 = ox.get_nearest_node(G_nx, coord_2)
target_3 = ox.get_nearest_node(G_nx, coord_3)
target_4 = ox.get_nearest_node(G_nx, coord_4)


G_ig = ig.Graph(directed=True)
G_ig.add_vertices(list(G_nx.nodes()))
G_ig.add_edges(list(G_nx.edges()))
G_ig.vs['osmid'] = list(nx.get_node_attributes(G_nx, 'osmid').values())
G_ig.es[weight] = list(nx.get_edge_attributes(G_nx, weight).values())

assert len(G_nx.nodes()) == G_ig.vcount()
assert len(G_nx.edges()) == G_ig.ecount()

route_length=[]
list_nodes=[]

for node in G_nx.nodes:
    length_1 = G_ig.shortest_paths(source=node, target=target_1, weights=weight)[0][0]
    length_2 = G_ig.shortest_paths(source=node, target=target_2, weights=weight)[0][0]

    if length_1<length_2:
       route_length.append(length_1)
       list_nodes.append(node)

   elif length_2 < length_1:
       route_length.append(length_2)
       list_nodes.append(node)

print(len(route_length))
print(len(list_nodes))

如果节点断开连接,最短路径应该是inf。我在route_length 列表中没有任何 inf 值。

提前谢谢你。

【问题讨论】:

  • 我首先想到的是length_1 == length_2的情况呢?对于缺少的 91 个案例,是否满足条件(因此不考虑 if 和 life 并且未附加在列表 route_length 中)?
  • len(list_nodes) = 9602 也一样吗?
  • 是的 len(list_nodes) 也是 9602。我最终删除了第二个条件并将其替换为“else”。你说得对!我的条件消除了长度相同的可能性。我忘记了这一点,因为它们只有在节点断开连接时才能相同。这意味着长度将为 inf。在这种情况下,长度只能相同,因为网络是定向的。
  • 您可以创建一个与您的评论内容相同的答案,我会将其作为正确答案进行检查,以便您获得代表点。
  • 好的。我去做。谢谢! :)

标签: python networkx igraph osmnx


【解决方案1】:

我脑海中闪现的第一件事是 length_1 == length_2?

我相信这是缺失的 91 个案例满足的条件(因此不包含在 ifelif 中,也未添加到列表 route_length 和列表 list_nodes 中)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    相关资源
    最近更新 更多