-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgraph_generators.py
49 lines (42 loc) · 1.5 KB
/
graph_generators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Utility to generate connected random graphs via Networkx, https://networkx.github.io/documentation/stable/reference/generators.html
import networkx as nx
import random
# Generates a connected ER graph
def er(n, k, with_random_weights=False):
while True:
G = nx.erdos_renyi_graph(n, k/n)
if nx.is_connected(G):
if with_random_weights:
for (u, v) in G.edges():
G.edges[u,v]['weight'] = random.random()
else:
for (u, v) in G.edges():
G.edges[u,v]['weight'] = 1
break
return G
# Generates a connected Watts-Strogatz graph
def ws(n, k, with_random_weights=False):
while True:
G = nx.connected_watts_strogatz_graph(n, k, 0.3)
if nx.is_connected(G):
if with_random_weights:
for (u, v) in G.edges():
G.edges[u,v]['weight'] = random.random()
else:
for (u, v) in G.edges():
G.edges[u,v]['weight'] = 1
break
return G
# Generates a connected Barabasi-Albert graph
def ba(n, k, with_random_weights=False):
while True:
G = nx.barabasi_albert_graph(n, k)
if nx.is_connected(G):
if with_random_weights:
for (u, v) in G.edges():
G.edges[u,v]['weight'] = random.random()
else:
for (u, v) in G.edges():
G.edges[u,v]['weight'] = 1
break
return G