[英]network x graph and floyd warshall
我是Python的新手。 我有一个像这样的地图 ,我想使用网络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()
在调用floyd warshall的结果之前,我想先看看图表。 原来这样的图形返回: 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()
结果: 第二个代码的结果
它是正常图吗? 有人可以就如何计算最短路径给出一些见解吗?
networkx floyd_warshall计算图中所有节点对的最短路径,并根据文档返回字典。
distance(dict)–字典,由源和目标作为键,节点之间的最短路径距离。
该算法不会以任何方式更改图形,因此通过不将返回的字典存储在变量中将不会执行任何操作。
对于您的问题,您已经计算出了最短的路径,您对它们根本不做任何事情。 如果您希望根据某个路径长度在图中放置节点,那么我认为您使用的算法不正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.