pythonigraphdistance-matrix

Does the igraph package for python contain a method to compute the distance matrix of a graph?


The R version of the igraph package contains the distances function which, according to the documentation, returns the distance matrix of the graph passed to it.

However, I couldn't find this function or a similar one in the python version of the package. The only provided function I could find is Point.distance which in my understanding of the documentation only calculates distances of two points in a 2D plane but not a network graph.

Is there a function that returns the distance matrix of a graph in the python version of this package?

Essentially, what I am looking for is the following:

# create the graph
graph = Graph(n=5, edges=[(0,1), (1,4), (2,3), (2,4), (2,5) , (3,5), (4,0)], directed=False)

# pseudo code to calculate distance
dist_matrix = distances(graph)

Any help is much appreciated.


Solution

  • One of the ways is to use g.get_all_shortest_paths(m)

    import igraph as ig
    g = ig.Graph(n=5, edges=[(0,1), (1,4), (2,3), (2,4), (2,5) , (3,5), (4,0)], directed=False)
    >>> [[len(n) for n in g.get_all_shortest_paths(m)] for m in g.vs]
    [[1, 2, 3, 4, 2, 4], [2, 1, 3, 4, 2, 4], [3, 3, 1, 2, 2, 2], [4, 4, 2, 1, 3, 2], [2, 2, 2, 3, 1, 3], [4, 4, 2, 2, 3, 1]]
    

    Another options is much easier and faster:

    >>> g.shortest_paths()
    [[0, 1, 2, 3, 1, 3], [1, 0, 2, 3, 1, 3], [2, 2, 0, 1, 1, 1], [3, 3, 1, 0, 2, 1], [1, 1, 1, 2, 0, 2], [3, 3, 1, 1, 2, 0]]