carltron4000
carltron4000

Reputation: 51

In python-igraph, find the number and mode of edges between two vertices

In a directed python-igraph, I can find the paths between two vertices as follows:

g=ig.Graph(directed=True)
g.add_vertices(range(4))
g.add_edges([(0,1),(0,2),(1,3)])

The graph produced by the above code

paths=g.get_all_shortest_paths(3,2,mode='all')
paths

[[3, 1, 0, 2]]

Is there a simple way to get the modes (in or out) of the edges along the path?

I've tried looking at the induced subgraph, and using the 'in' and 'out' modes instead of 'all'. I could manually walk the tree, but I'm looking for something more compact and pythonic.

Ideally there would be a method that would return the following for the above scenario:

[['out','out','in']]

Upvotes: 2

Views: 200

Answers (1)

Tamás
Tamás

Reputation: 48071

Something like this should do the trick:

def consecutive_pairs(items):
    return zip(items, items[1:])


def classify_edges_in_path(path, graph):
    return [
        "in" if graph.get_eid(u, v, error=False) >= 0 else "out"
        for u, v in consecutive_pairs(path)
    ]

The trick here is that graph.get_eid(u, v, error=False) will return -1 if the u-v edge does not exist. Since the path itself exists, you can then know that it must be the v-u edge that is in the path.

consecutive_pairs() is only for readability; you can inline it if you want.

Upvotes: 2

Related Questions