calculating graph weight in python with NetworkX

2.2k views Asked by At

I'm using networkx to calculate the shortest distance(in terms of weight) between two vertexes in a directed, weighted graph. I think that the dijkstra_path_length algorithm is the right one to use here, but I don't understand what I have to put as a default parameter for the weight in order to get the results I want.

import networkx as nx
G = nx.MultiDiGraph()
G.add_nodes_from(['A', 'B', 'C', 'D', 'E'])
G.add_edge('A', 'B', 5)
G.add_edge('B', 'C', 4)
G.add_edge('C', 'D', 8)
G.add_edge('D', 'C', 8)
G.add_edge('D', 'E', 6)
G.add_edge('A', 'D', 5)
G.add_edge('C', 'E', 2)
G.add_edge('E', 'B', 3)
G.add_edge('A', 'E', 7)

Here is the graph I input. I have to calculate the shortest path (in terms of weight) from A to C (its A-B-C with weight=9) but whatever I do the only answer I get is 2 (the number of edges, as if the graph has no weight). The correct answer should be 9.

3

There are 3 answers

0
ivangtorre On BEST ANSWER

The problem is that you have to write the word "weight" for assigning it to an edge. You are giving labels to the edges but no weights.

The next code works printing 9 when you calculate the distance between nodes A and C.

import networkx as nx
G = nx.MultiDiGraph()
G.add_nodes_from(['A', 'B', 'C', 'D', 'E'])

G.add_edge('A', 'B', weight=5)
G.add_edge('B', 'C', weight=4)
G.add_edge('C', 'D', weight=8)
G.add_edge('D', 'C', weight=8)
G.add_edge('D', 'E', weight=6)
G.add_edge('A', 'D', weight=5)
G.add_edge('C', 'E', weight=2)
G.add_edge('E', 'B', weight=3)
G.add_edge('A', 'E', weight=7)

print nx.dijkstra_path_length(G, source = 'A', target = 'C')
0
Shantanu Deshpande On

Remove this line from your code

G.add_nodes_from(['A', 'B', 'C', 'D', 'E'])
0
Jing On

may be you can try to use nx.shortest_path()