Search code examples
python-3.xgraphgraph-tool

How can I calculate the average path length of the graph efficiently in graph-tool?


I am dealing with networks of the order of 10000 vertices and I am using graph-tool to analyze them. One of the things that I want to calculate for each of these graphs is the average path length which is defined as the average of the shortest distances over all the pairs of nodes in the graph. So I tried this:

ave_path_length = 0
tot = 0

for v1 in G.vertices():
    print(v1)
    for v2 in G.vertices():
        if v1 != v2 :
            tot += 1
            ave_path_length += gt.shortest_distance(G, v1, v2)

ave_path_length /= tot

However, this is taking eternity. Is there a better method to achieve the task? Thanks in advance.


Solution

  • I found a much efficient way to achieve this. One can do this:

    import graph_tool.all as gt
    dist = gt.shortest_distance(G)
    ave_path_length = sum([sum(i) for i in dist])/(G.num_vertices()**2-G.num_vertices())
    

    This takes only few seconds for sparse networks of size 10000. However, I am still curious as whether a better method exists.