【问题标题】:network x graph and floyd warshall网络 x 图和弗洛伊德 Warshall
【发布时间】:2018-11-23 14:26:36
【问题描述】:

我是 Python 的新手。我有一张像map 这样的地图,我想使用网络 x 创建从每个节点到每个其他节点的最短路径。我试着写一个像这样的简单代码:

shp = nx.read_shp("../Shapefiles/Shapefiles/Station_in_Corridors/Group_1.shp")

G = nx.DiGraph()
for data in shp.edges(data = True):
   G.add_edge(data[0],data[1],weight = data[2]["Length_Km"])

nx.floyd_warshall(G)
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos = pos, node_size=100)
nx.draw_networkx_edges(G, pos = pos)
plt.show()

在调用弗洛伊德战争的结果之前,我想先看一下图表。结果图形返回如下:result。我不认为该图与输入相似(或者是吗?)。

无论如何,我也尝试使用此代码手动附加点:

cor1 = driver.Open(cor1Data)
cor2 = driver.Open(cor2Data)

ly1 = cor1.GetLayer()
ly2 = cor2.GetLayer()

allpoints = {}
kreuz = []
arcs = {}
for i in range(ly1.GetFeatureCount()):
  for j in range(ly2.GetFeatureCount()): #Create road
    feat1 = ly1.GetFeature(i)
    geom1 = feat1.GetGeometryRef()
    points1 = geom1.GetPoints()
    feat2 = ly2.GetFeature(j)
    geom2 = feat2.GetGeometryRef()
    points2 = geom2.GetPoints()
    arcs[i] = [(points1[0],points1[1],geom1.Length()),feat1]
    arcs[len(ly1)+j] = [(points2[0],points2[1],geom2.Length()),feat2]
    #Create OD trips
    if not points1[0] in allpoints.values():
        allpoints[i] = [points1[0],geom1.Length(),feat1]
    else:
        allpoints[i] = [points1[1],geom1.Length(),feat1]
    if not points2[0] in allpoints.values():
        allpoints[len(ly1)+j] = [points2[0],geom1.Length(),feat1]
    else:
        allpoints[len(ly1)+j] = [points2[1],geom1.Length(),feat1]
    #append kreuz
    if points1[0] == points2[0] or points1[0] == points2[1]:
        kreuz.append(points1[0])
    elif points1[1] == points2[0] or points1[1] == points2[1]:
        kreuz.append(points1[1])

G = nx.DiGraph() #Set a directed graph
for k,v in arcs.items():
  G.add_edge(v[0][0],v[0][1], weight = v[0][2])

G.add_nodes_from(allpoints.values())

nx.floyd_warshall(G)
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos = pos, node_size=100)
nx.draw_networkx_edges(G, pos = pos)
plt.show()

结果: Result of second code

它是一个正常的图形吗?任何人都可以提供一些关于如何计算最短路径的见解吗?

【问题讨论】:

  • 您没有将nx.floyd_warshall(G) 的输出分配给任何东西。你现在期望这条线做什么?就地修改G
  • 是的,我只想先看看 G,然后再进一步使用 floyd warshall 算法。它对 G 有任何影响还是应该将其分配给绘图功能?

标签: python graph networkx shortest-path floyd-warshall


【解决方案1】:

networkx floyd_warshall 计算图中所有节点对的最短路径,并根据documentation 返回一个字典。

distance (dict) – 一个字典,由源和目标键控,表示节点之间的最短路径距离。

该算法不会以任何方式更改图形,因此不将返回的字典存储在变量中将无济于事。

对于您的问题,您已经计算出最短路径,您根本不会对它们做任何事情。如果您希望根据某个路径长度在图中定位节点,我认为您使用的算法不合适。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 2011-04-22
    • 2013-03-28
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多