Search code examples
pythonigraph

Find diameter and average shortest path length of a graph's giant component using igraph python


I want to calculate the average shortest path length and diameter of a graph's giant component. The files are represented in .mat format.Is there any built-in function to do so?

data = loadmat("filename.mat")
data=coo_matrix(data.get('A'))
graph= igraph.Graph(zip(data.row.tolist(), data.col.tolist()))

Solution

  • Diameter of giant components

    As per this answer, we can find the giant component with the following function.

    def giant_component(graph):
        """Compute giant component.
    
        Returns:
            The giant component of `graph` as an `igraph.Graph`.
    
        """
        vc = graph.components()
        vc_sizes = vc.sizes()
        return vc.subgraph(vc_sizes.index(max(vc_sizes)))
    

    Its diameter can be found as giant_component(graph).diameter().

    Average shortest path

    The Graph.shortest_paths function will return a matrix containing all shortest path lengths, of which you can then compute the average.

    np.mean(graph.shortest_paths())