Noortjeee
Noortjeee

Reputation: 1

Edge attributes of multiple shortest paths (in dictionary) using networkx

I have an additional question to the problem, which is solved here: Edge attributes of shortest path using networkx

I want to have the attributes of all shortest paths in a transport network. So in the case described above, @swatchai answered how to get attributes of one path. But in my network, I have from Amsterdam to the rest of the world 300 shortest paths. The script looks like this:

sp2 = nx.shortest_path(g, source='NLAMS', weight='weight')
for key, value in sp2.items():
    print(key, ' : ', value)

It works till here! In the answer of @swatchai he suggested the following script as answer, but I think it doesn't work for me because it is a dictionary instead of a list.

pathGraph2 = nx.path_graph(sp2)  # does not pass edges attributes

for edgeatr in pathGraph2.edges(): #print from_node, to_node, edge's attributes
    print(edgeatr, g.edges[edgeatr[0], edgeatr[1]])

Thank you in advance!

Upvotes: 0

Views: 292

Answers (1)

willcrack
willcrack

Reputation: 1852

I believe that you may be confused between what you obtain when you do:

>>> nx.shortest_path(g, source=1, target=2, weight='weight')
[1, 7, 2]

versus

>>> nx.shortest_path(g, source=1, weight='weight')
{1: [1], 0: [1, 0], 5: [1, 5], 7: [1, 7], 4: [1, 0, 4], 2: [1, 0, 2], 6: [1, 5, 6], 3: [1, 0, 4, 3]}

As you can see the second one gives you all targets from source plus all paths.

To create the path_graph you can only use the path.

Here is an example:

# Create a random graph with 8 nodes, with degree=3
g = nx.random_regular_graph(3, 8, seed=None)

# Add 'cost' attributes to the edges
for (start, end) in g.edges:
    g.edges[start, end]['cost'] = np.random.randint(1,10)

SOURCE = 1
sp_SOURCE = nx.shortest_path(g, source=SOURCE, weight='weight')

for target, path in sp_SOURCE.items(): 
    print("Shortest path from SOURCE to {} is {}".format(target,path))
    pathGraph = nx.path_graph(path)   # for each target we create a path_graph
    for ea in pathGraph.edges():
        #print from_node, to_node, edge's attributes
        print("\t", ea, g.edges[ea[0], ea[1]])

Upvotes: 1

Related Questions