I am a newbie in Python. I have a map like this map, and I want to create the shortest paths from each node to every other nodes using network x. I've tried to write a simple code like this:
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()
Prior to calling the result of floyd warshall, I'd like to see the graph first. Turns out the graph return like this:result. I don't think that graph is similar to the input (or is it?).
Anyhow, I've also tried to manually append the points with this code:
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()
and the result: Result of second code
Is it a normal graph? And can anybody give some insights on how to calculate the shortest path right?
The networkx floyd_warshall calculates the shortest path for all pair of node in a graph and returns a dictionary as per the documentation.
distance (dict) – A dictionary, keyed by source and target, of shortest paths distances between nodes.
The algorithm does not change the graph in any way so by not storing the returned dictionary in a variable will do nothing.
To your question, you've already calculated the shortest paths, you simple doesn't do anything with them. If you wish to position the nodes in the plot according to some path length I don't think you're using an appropriate algorithm.