4

I have the following graph

import networkx as nx

g = nx.MultiGraph()

#link 0
g.add_edge("A","B",cost=20,index=0)

#link 1
g.add_edge("A","C",cost=20,index=1)

#link 2
g.add_edge("B","C",cost=10,index=2)

#link 3
g.add_edge("B","D",cost=150,index=3)

#link 4
g.add_edge("C","D",cost=150,index=5)
g.add_edge("C","D",cost=200,index=6)

I'm trying to find the shortest path between A and D and that works

path=nx.dijkstra_path(g,"A","D",weight='cost')
->['A', 'C', 'D']

What i need is to get the edges info ( more specific the index) in this path.

Tryied to far :

edgesinpath=zip(path[0:],path[1:])
for (u,v ) in edgesinpath:
    print u,v,g[u][v]

but of course this will out all the edges , that math the u,v in the path:

A C {0: {'index': 1, 'cost': 20}}
C D {0: {'index': 5, 'cost': 150}, 1: {'index': 6, 'cost': 200}}

Any idea how to get the correct information ? Is this available via networkx?

Thx.

Cmarv
  • 141
  • 9

1 Answers1

1

One possible solution:

edges_ids = []
for u,v in edgesinpath:
    edge = sorted(g[u][v], key=lambda x:g[u][v][x]['cost'])[0]
    edges_ids.append(g[u][v][edge]['index'])

This choses for each multi-edge, the edge in your shortest path with a minimal cost.

rodgdor
  • 2,530
  • 1
  • 19
  • 26