How does random graph generator work in networkx?
I used the source code of Networkx to generate a random graph with Poisson degree distribution.
I change some parts of codes that I need as follows:
import random
import networkx
import math
from networkx.generators.classic import empty_graph
def gnp_random_graph(n, p, seed=None):
"""Return a random graph G_{n,p}.
Parameters
----------
n : int
The number of nodes.
p : float
Probability for edge creation.
possible edges: n[n-1]/2
seed : int, optional
Seed for random number generator (default=None).
"""
#My sample
z = 4 #mean degree
n = 10 #Number of nodes
p = math.exp**(-z)*z**(k)/(math.factorial(k)) ##I add this myself #k is missing
#This part is from the source
G=empty_graph(n)
if not seed is None:
random.seed(seed)
for u in xrange(n):
for v in xrange(u+1,n):
if random.random() < p:
G.add_edge(u,v)
return G
In the last part for generating edges, I don't understand how it count degree a开发者_StackOverflow社区nd compare with p(Probability distribution of degree(k))? For me it looks like it generate a random number btw (0,1). But how one should use domain for p and compare the random number with p(k)?
Unless the number of nodes/edges are large, this gives a bernoulli distribution. You can get networkx to give you a poisson degree distribution easily.
import numpy as np
from scipy.stats import poisson
def poissongraph(n,mu):
z= np.zeros(n) #n is number of nodes
for i in range(n):
z[i]=poisson.rvs(mu) #mu is the expected value
G=expected_degree_graph(z)
return G
This works, because generating a graph this way (using Brenoulli-sampling), will result in a graph with a Poisson degree-distribution (explained in detail here (pdf)).
精彩评论