defgeographical_threshold_edges(G,theta,alpha=2):# generate edges for a geographical threshold graph given a graph # with positions and weights assigned as node attributes 'pos' and 'weight'.nodes=G.nodes(data=True)whilenodes:u,du=nodes.pop()wu=du['weight']pu=du['pos']forv,dvinnodes:wv=dv['weight']pv=dv['pos']r=math.sqrt(sum(((a-b)**2fora,binzip(pu,pv))))ifwu+wv>=theta*r**alpha:yield(u,v)

[docs]defnavigable_small_world_graph(n,p=1,q=1,r=2,dim=2,seed=None):r"""Return a navigable small-world graph. A navigable small-world graph is a directed grid with additional long-range connections that are chosen randomly. From [1]_: Begin with a set of nodes that are identified with the set of lattice points in an `n \times n` square, `{(i,j): i\in {1,2,\ldots,n}, j\in {1,2,\ldots,n}}` and define the lattice distance between two nodes `(i,j)` and `(k,l)` to be the number of "lattice steps" separating them: `d((i,j),(k,l)) = |k-i|+|l-j|`. For a universal constant `p`, the node `u` has a directed edge to every other node within lattice distance `p` (local contacts) . For universal constants `q\ge 0` and `r\ge 0` construct directed edges from `u` to `q` other nodes (long-range contacts) using independent random trials; the i'th directed edge from `u` has endpoint `v` with probability proportional to `d(u,v)^{-r}`. Parameters ---------- n : int The number of nodes. p : int The diameter of short range connections. Each node is connected to every other node within lattice distance p. q : int The number of long-range connections for each node. r : float Exponent for decaying probability of connections. The probability of connecting to a node at lattice distance d is 1/d^r. dim : int Dimension of grid seed : int, optional Seed for random number generator (default=None). References ---------- .. [1] J. Kleinberg. The small-world phenomenon: An algorithmic perspective. Proc. 32nd ACM Symposium on Theory of Computing, 2000. """if(p<1):raisenx.NetworkXException("p must be >= 1")if(q<0):raisenx.NetworkXException("q must be >= 0")if(r<0):raisenx.NetworkXException("r must be >= 1")ifnotseedisNone:random.seed(seed)G=nx.DiGraph()nodes=list(product(range(n),repeat=dim))forp1innodes:probs=[0]forp2innodes:ifp1==p2:continued=sum((abs(b-a)fora,binzip(p1,p2)))ifd<=p:G.add_edge(p1,p2)probs.append(d**-r)cdf=list(nx.utils.cumulative_sum(probs))for_inrange(q):target=nodes[bisect_left(cdf,random.uniform(0,cdf[-1]))]G.add_edge(p1,target)returnG