Source code for networkx.algorithms.smallworld

# Copyright (C) 2017 by# Romain Fontugne <romain@iij.ad.jp># All rights reserved.# BSD license.## Author: Romain Fontugne (romain@iij.ad.jp)"""Functions for estimating the small-world-ness of graphs.A small world network is characterized by a small average shortest path length,and a large clustering coefficient.Small-worldness is commonly measured with the coefficient sigma or omega.Both coefficients compare the average clustering coefficient and shortest pathlength of a given graph against the same quantities for an equivalent randomor lattice graph.For more information, see the Wikipedia article on small-world network [1]_... [1] Small-world network:: https://en.wikipedia.org/wiki/Small-world_network"""importnetworkxasnxfromnetworkx.utilsimportnot_implemented_forfromnetworkx.utilsimportpy_random_state__all__=['random_reference','lattice_reference','sigma','omega']

[docs]@py_random_state(3)@not_implemented_for('directed')@not_implemented_for('multigraph')defrandom_reference(G,niter=1,connectivity=True,seed=None):"""Compute a random graph by swapping edges of a given graph. Parameters ---------- G : graph An undirected graph with 4 or more nodes. niter : integer (optional, default=1) An edge is rewired approximately `niter` times. connectivity : boolean (optional, default=True) When True, ensure connectivity for the randomized graph. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- G : graph The randomized graph. Notes ----- The implementation is adapted from the algorithm by Maslov and Sneppen (2002) [1]_. References ---------- .. [1] Maslov, Sergei, and Kim Sneppen. "Specificity and stability in topology of protein networks." Science 296.5569 (2002): 910-913. """ifG.is_directed():msg="random_reference() not defined for directed graphs."raisenx.NetworkXError(msg)iflen(G)<4:raisenx.NetworkXError("Graph has less than four nodes.")fromnetworkx.utilsimportcumulative_distribution,discrete_sequencelocal_conn=nx.connectivity.local_edge_connectivityG=G.copy()keys,degrees=zip(*G.degree())# keys, degreecdf=nx.utils.cumulative_distribution(degrees)# cdf of degreennodes=len(G)nedges=nx.number_of_edges(G)niter=niter*nedgesntries=int(nnodes*nedges/(nnodes*(nnodes-1)/2))swapcount=0foriinrange(niter):n=0whilen<ntries:# pick two random edges without creating edge list# choose source node indices from discrete distribution(ai,ci)=discrete_sequence(2,cdistribution=cdf,seed=seed)ifai==ci:continue# same source, skipa=keys[ai]# convert index to labelc=keys[ci]# choose target uniformly from neighborsb=seed.choice(list(G.neighbors(a)))d=seed.choice(list(G.neighbors(c)))bi=keys.index(b)di=keys.index(d)ifbin[a,c,d]ordin[a,b,c]:continue# all vertices should be different# don't create parallel edgesif(dnotinG[a])and(bnotinG[c]):G.add_edge(a,d)G.add_edge(c,b)G.remove_edge(a,b)G.remove_edge(c,d)# Check if the graph is still connectedifconnectivityandlocal_conn(G,a,b)==0:# Not connected, revert the swapG.remove_edge(a,d)G.remove_edge(c,b)G.add_edge(a,b)G.add_edge(c,d)else:swapcount+=1breakn+=1returnG

[docs]@py_random_state(4)@not_implemented_for('directed')@not_implemented_for('multigraph')deflattice_reference(G,niter=1,D=None,connectivity=True,seed=None):"""Latticize the given graph by swapping edges. Parameters ---------- G : graph An undirected graph with 4 or more nodes. niter : integer (optional, default=1) An edge is rewired approximatively niter times. D : numpy.array (optional, default=None) Distance to the diagonal matrix. connectivity : boolean (optional, default=True) Ensure connectivity for the latticized graph when set to True. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- G : graph The latticized graph. Notes ----- The implementation is adapted from the algorithm by Sporns et al. [1]_. which is inspired from the original work by Maslov and Sneppen(2002) [2]_. References ---------- .. [1] Sporns, Olaf, and Jonathan D. Zwi. "The small world of the cerebral cortex." Neuroinformatics 2.2 (2004): 145-162. .. [2] Maslov, Sergei, and Kim Sneppen. "Specificity and stability in topology of protein networks." Science 296.5569 (2002): 910-913. """importnumpyasnpfromnetworkx.utilsimportcumulative_distribution,discrete_sequencelocal_conn=nx.connectivity.local_edge_connectivityifG.is_directed():msg="lattice_reference() not defined for directed graphs."raisenx.NetworkXError(msg)iflen(G)<4:raisenx.NetworkXError("Graph has less than four nodes.")# Instead of choosing uniformly at random from a generated edge list,# this algorithm chooses nonuniformly from the set of nodes with# probability weighted by degree.G=G.copy()keys,degrees=zip(*G.degree())# keys, degreecdf=cumulative_distribution(degrees)# cdf of degreennodes=len(G)nedges=nx.number_of_edges(G)ifDisNone:D=np.zeros((nnodes,nnodes))un=np.arange(1,nnodes)um=np.arange(nnodes-1,0,-1)u=np.append((0,),np.where(un<um,un,um))forvinrange(int(np.ceil(nnodes/2))):D[nnodes-v-1,:]=np.append(u[v+1:],u[:v+1])D[v,:]=D[nnodes-v-1,:][::-1]niter=niter*nedgesntries=int(nnodes*nedges/(nnodes*(nnodes-1)/2))swapcount=0foriinrange(niter):n=0whilen<ntries:# pick two random edges without creating edge list# choose source node indices from discrete distribution(ai,ci)=discrete_sequence(2,cdistribution=cdf,seed=seed)ifai==ci:continue# same source, skipa=keys[ai]# convert index to labelc=keys[ci]# choose target uniformly from neighborsb=seed.choice(list(G.neighbors(a)))d=seed.choice(list(G.neighbors(c)))bi=keys.index(b)di=keys.index(d)ifbin[a,c,d]ordin[a,b,c]:continue# all vertices should be different# don't create parallel edgesif(dnotinG[a])and(bnotinG[c]):ifD[ai,bi]+D[ci,di]>=D[ai,ci]+D[bi,di]:# only swap if we get closer to the diagonalG.add_edge(a,d)G.add_edge(c,b)G.remove_edge(a,b)G.remove_edge(c,d)# Check if the graph is still connectedifconnectivityandlocal_conn(G,a,b)==0:# Not connected, revert the swapG.remove_edge(a,d)G.remove_edge(c,b)G.add_edge(a,b)G.add_edge(c,d)else:swapcount+=1breakn+=1returnG