Search code examples
pythongraphnetworkxshortest-pathstandard-deviation

Standard Deviation of shortest path lengths in networkx


networkx.average_shortest_path_length(G) gives the average of shortest paths between all pairs of nodes in a graph G. I want the standard deviation of all these shortest path lengths. Is there an inbuilt method in the networkx package?

I am aware of using nx.all_pairs_shortest_path_length(G), which gives a dictionary of all the shortest path length. I was hoping that networkx has some inbuilt method instead, since it already has a method to calculate average.


Solution

  • The current version of the software (2,4rc1 as of writing) does not have such a method.

    You can check the list of methods available within this context here: https://networkx.github.io/documentation/latest/reference/algorithms/shortest_paths.html#module-networkx.algorithms.shortest_paths.unweighted

    Due to the fact that shortest path length calculation can be done with a multitude of algorithmic means, and each of them have a list of their own peculiar disadvantages, such a method would not really make sense in terms of what NetworkX is meant to do, or aims to achieve. Depending on how you aim to calculate the shortest path you should implement your own function for that, which can then circumvent these limitations within the specific graph you are working with.

    You can easily calculate it from the dictionary NetworkX is already providing.

    import numpy as np
    import networkx as nx
    
    Pairs = nx.all_pairs_shortest_path_length(G)
    np.std(Pairs)
    

    More about numpy.std here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html