Search code examples
pythongraphnetworkxsocial-networking

python: How to get second moment of degree distribution by NetworkX


How can I get second moment (<k^2>) of degree distribution of an un-directed graph by NetworkX?


Solution

  • I'm not sure if you found the answer already but here is some great documentation on network science.

    For your question in particular check Chapter 4, Section: "The Meaning of Scale-Free":

    Equation

    As stated in the comments the 2nd moment can be calculated by dividing the sum of the degrees squared by the number of nodes (assuming that every node exists only once and all have the same probability).

    Here is the generalized form of this calculation to calculate the n_th moment:

    def nth_moment(g,n):
        s = 0
        for node in g.nodes:
            s += g.degree[node] ** n
        return (s/len(g))
    

    An example of usage of the function to calculate the second moment:

    some_graph = nx.barabasi_albert_graph(10000, 2, seed=1)
    print(nth_moment(some_graph, 2))
    

    Faster - Numpy

    import numpy as np
    import networkx as nx
    
    g = nx.barabasi_albert_graph(10000, 2, seed=1)
    def nth_moment_v2(g,n):
        degree_np = np.array(list(dict(g.degree).values()))
        return (sum(degree_np**n)/len(g))
    

    Times:

    st = time.time()         
    print(nth_moment(g,2))
    print(time.time()-st)
    
    st = time.time()          
    print(nth_moment_v2(g,2))
    print(time.time()-st)
    

    58.3626
    0.017042160034179688
    58.3626
    0.005998849868774414