2) these graphs don't have any random aspects to their generation, so there isn't any point in accepting a seed as far as I can tell.
1) is more tricky. It seems that networkx uses a combination of random
and numpy.random
libraries for random number generation. The graph generators, e.g. watts_strogatz_graph
use the former, while layout uses the latter.
Short answer: just set seeds for both libraries:
import random
import numpy as np
seed = 123
random.seed(seed)
np.random.seed(seed)
Explanation for what is going on
Anyway, here is a simple example showing that the seed is taken into account for graphs like the watts-strogatz generator (but you must have p>0
otherwise there is no re-wiring and hence no random component!).
The edges differ between G2 and G3 because they used different seeds, but G1 and G2 are identical.
import networkx as nx
seed = 123
G1 = nx.watts_strogatz_graph(30, 3, 0.1, seed=seed)
G2 = nx.watts_strogatz_graph(30, 3, 0.1, seed=seed)
G3 = nx.watts_strogatz_graph(30, 3, 0.1, seed=seed+1)
G1.edge == G2.edge
>>> True
G3.edge == G2.edge
>>> False
To make sure the layout is the same each time, you could use a call to np.random.seed(myseed)
. This is different than using np.random.RandomState
, which is creating a new instance of a random number stream, and would not be used by the nx layout functions. (though in your own random streams it is good practice to use an independent stream).
import numpy as np
np.random.seed(seed)
pos1 = nx.spring_layout(G1, scale=len(G.nodes()))
pos1b = nx.spring_layout(G1, scale=len(G.nodes()))
# should differ! same graph, but the rng has been called
np.random.seed(seed) #reset seed
pos2 = nx.spring_layout(G2, scale=len(G.nodes()))
# should be same as p1! G1==G2 (from above), and seed for layout
# is the same.
diffs = 0
for node in pos1:
if np.all(pos1[node] != pos1b[node]):
diffs += 1
print diffs
>>> 30
diffs2 = 0
for node in pos1:
if np.all(pos1[node] != pos2[node]):
diffs2 += 1
print diffs2
>>> 0
This question/answer Differences between numpy.random and random.random in Python has some description of the two random libraries.