News

New paper! in the American Naturalist

Friday, June 28, 2019

Topology measures



For simple graphs. Mathematical definitions are here.
import numpy as np
import networkx as nx
import community

def Assortativity(ug):
    # eij: fraction of edges in a network that connect a node with degree i to one of degree j.
    d = max(dict(ug.degree()).values())
    e = np.zeros([d,d])
    n_edges = len(ug.edges())
    for i,j in ug.edges():
        d1 = ug.degree(i) # degree of node i
        d2 = ug.degree(j) # degree of node j
        e[d1-1,d2-1] += 1
        e[d2-1,d1-1] += 1
    e /= e.sum()
    a = e.sum(axis=0)
    b = e.sum(axis=1)
    ab = np.dot(a,b)
    r = (np.diag(e).sum() - ab) / (1. - ab)
    return r

def Modularity(ug):
 # required packages: community, python-louvain
 # commnity detection with louvain algorithm
 part = community.best_partition(subg)
 Q = community.modularity(part,subg)
 return Q

def NormalizedDegreeVariance(ug):
    # Keith Smith
    n = len(ug.nodes())
    m = len(ug.edges())
    d = 2.*m / (n*(n-1)) # density: the nubmer of edges divided by tot. possible number of edges
    v = np.var(list(dict(ug.degree).values())) # variance in degrees
    return v*(n-1.) / (n*m*(1.-d))

def AverageClusteringCoefficient(ug):
 return nx.average_clustering(ug)

def Efficiency(ug):
    n = len(ug)
    denom = n * (n - 1.)
    if denom != 0:
        g_eff = 0
        for i in nx.all_pairs_shortest_path_length(ug):
            x = i[1].values()
            for j in x:
                if j != 0:
                    g_eff += 1./float(j)
        return g_eff / denom
    else:
        return 0.