forked from navidadkhah/Graph_Simulation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
4.py
378 lines (310 loc) · 12.3 KB
/
4.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import networkx as nx
import numpy as np
import random
import matplotlib.pyplot as plt
import math
from collections import defaultdict
def uniform_random():
return random.random()
def choose_node(G):
nodes = list(G.nodes())
return random.choice(nodes)
# RSRG (Random Scale-Free Recursive Graph) model
def generate_rsr_graph(num_nodes, p):
G = nx.Graph()
G.add_node(1)
for i in range(2, num_nodes+1):
u = i
v = nx.utils
v = choose_node(G)
while v == u:
v = nx.utils
v = choose_node(G)
G.add_edge(u, v)
for node in G.neighbors(v):
if node != u and uniform_random() < p:
G.add_edge(u, node)
return G
# RSRBG (Random Scale-Free Recursive Bipartite Graph) model
def generate_rsr_bipartite_graph(num_left_nodes, num_right_nodes, p):
G = nx.Graph()
G.add_nodes_from(range(1, num_left_nodes+1), bipartite=0)
G.add_nodes_from(range(num_left_nodes+1, num_left_nodes+num_right_nodes+1), bipartite=1)
for i in range(1, num_left_nodes+1):
u = i
v = nx.utils
v = choose_node(G)
while v == u or G.nodes[v]['bipartite'] != 1:
v = nx.utils
v = choose_node(G)
G.add_edge(u, v)
for node in G.neighbors(v):
if G.nodes[node]['bipartite'] != 0 and nx.utils.uniform_random() < p:
G.add_edge(u, node)
return G
# WS (Watts-Strogatz) model
def generate_ws_graph(num_nodes, k, p):
return nx.watts_strogatz_graph(num_nodes, k, p)
# SF (Scale-Free) model
def generate_sf_graph(num_nodes, m):
return nx.barabasi_albert_graph(num_nodes, m)
# ER (Erdos-Renyi) model
def generate_er_graph(num_nodes, p):
return nx.erdos_renyi_graph(num_nodes, p)
# Draw the graph using NetworkX and Matplotlib
def draw_graph(G, title):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_size=200, font_size=8)
plt.title(title)
plt.show()
# Example usage
num_nodes = 50
p = 0.3
k = 4
m = 2
rsrg_graph = generate_rsr_graph(num_nodes, p)
draw_graph(rsrg_graph, "RSRG Model")
rsrbg_graph = generate_rsr_bipartite_graph(num_nodes, num_nodes, p)
draw_graph(rsrbg_graph, "RSRBG Model")
ws_graph = generate_ws_graph(num_nodes, k, p)
draw_graph(ws_graph, "WS Model")
sf_graph = generate_sf_graph(num_nodes, m)
draw_graph(sf_graph, "SF Model")
er_graph = generate_er_graph(num_nodes, p)
draw_graph(er_graph, "ER Model")
# RSRG (Random Scale-Free Recursive Graph) model
def generate_rsr_graph(num_nodes, p):
G = nx.path_graph(num_nodes)
for i in range(2, num_nodes+1):
u = i
v = choose_node(G)
while v == u:
v = choose_node(G)
G.add_edge(u, v)
for node in G.neighbors(v):
if node != u and uniform_random() < p:
G.add_edge(u, node)
return G
# RSRBG (Random Scale-Free Recursive Bipartite Graph) model
def generate_rsr_bipartite_graph(num_left_nodes, num_right_nodes, p):
G = nx.Graph()
G.add_nodes_from(range(1, num_left_nodes+1), bipartite=0)
G.add_nodes_from(range(num_left_nodes+1, num_left_nodes+num_right_nodes+1), bipartite=1)
for i in range(1, num_left_nodes+1):
u = i
v = choose_node(G)
while v == u or G.nodes[v]['bipartite'] != 1:
v = choose_node(G)
G.add_edge(u, v)
for node in G.neighbors(v):
if G.nodes[node]['bipartite'] != 0 and nx.utils.uniform_random() < p:
G.add_edge(u, node)
return G
# WS (Watts-Strogatz) model
def generate_ws_graph(num_nodes, k, p):
return nx.random_graphs.random_regular_graph(k, num_nodes, p)
# SF (Scale-Free) model
def generate_sf_graph(num_nodes, m):
return nx.random_graphs.barabasi_albert_graph(num_nodes, m)
# ER (Erdos-Renyi) model
def generate_er_graph(num_nodes, p):
return nx.random_graphs.erdos_renyi_graph(num_nodes, p)
# Draw the graph using NetworkX and Matplotlib
def draw_graph(G, title):
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos, with_labels=True, node_size=200, font_size=8, node_color='lightblue', edge_color='gray')
plt.title(title)
plt.show()
# Example usage
num_nodes = 50
p = 0.3
q = 1
k = 4
m = 2
rsrg_graph = generate_rsr_graph(num_nodes, p)
draw_graph(rsrg_graph, "RSRG Model (Linear)")
rsrbg_graph = generate_rsr_bipartite_graph(num_nodes, num_nodes, p)
draw_graph(rsrbg_graph, "RSRBG Model (Linear)")
ws_graph = generate_ws_graph(num_nodes, k, q)
draw_graph(ws_graph, "WS Model (Linear)")
sf_graph = generate_sf_graph(num_nodes, m)
draw_graph(sf_graph, "SF Model (Linear)")
er_graph = generate_er_graph(num_nodes, p)
draw_graph(er_graph, "ER Model (Linear)")
# Function to plot the degree distribution PDF
def plot_degree_distribution_pdf(graph_type, graph, title):
degrees = [degree for node, degree in graph.degree()]
degree_count = np.bincount(degrees)
pdf = degree_count / len(degrees)
plt.bar(range(len(pdf)), pdf, width=0.8, color='b')
plt.title(title)
plt.xlabel('Degree')
plt.ylabel('Probability Density')
plt.xticks(np.arange(0, max(degrees)+1, 1))
plt.xlim([-0.5, max(degrees)+0.5])
plt.show()
# Generate RSRG graph
n = 1000 # Number of nodes
p = 0.05 # Probability of adding an edge between two nodes
rsrg_graph = nx.random_regular_graph(int(np.log(n)), n)
plot_degree_distribution_pdf("RSRG", rsrg_graph, "RSRG Degree Distribution PDF")
# Generate RSRBG graph
m1 = 500 # Number of nodes in set A
m2 = 500 # Number of nodes in set B
p_in = 0.1 # Probability of adding an edge between nodes in the same set
p_out = 0.01 # Probability of adding an edge between nodes in different sets
rsrbg_graph = nx.random_partition_graph([m1, m2], p_in, p_out)
plot_degree_distribution_pdf("RSRBG", rsrbg_graph, "RSRBG Degree Distribution PDF")
# Generate Watts-Strogatz graph
n = 1000 # Number of nodes
k = 10 # Each node is connected to k nearest neighbors
p = 0.1 # Probability of rewiring each edge
ws_graph = nx.watts_strogatz_graph(n, k, p)
plot_degree_distribution_pdf("WS", ws_graph, "WS Degree Distribution PDF")
# Generate Scale-Free graph
n = 1000 # Number of nodes
m = 10 # Number of edges to attach from a new node to existing nodes
sf_graph = nx.barabasi_albert_graph(n, m)
plot_degree_distribution_pdf("SF", sf_graph, "SF Degree Distribution PDF")
# Generate Erdős-Rényi graph
n = 1000 # Number of nodes
p = 0.01 # Probability of adding an edge between two nodes
er_graph = nx.erdos_renyi_graph(n, p)
plot_degree_distribution_pdf("ER", er_graph, "ER Degree Distribution PDF")
# Custom function to generate a random recursive tree
def generate_random_recursive_tree(n, m):
if n <= 0:
return nx.Graph()
root = 0
tree = nx.Graph()
tree.add_node(root)
def add_recursive_edges(node, remaining):
if remaining <= 0:
return
children = np.random.choice(remaining, size=min(remaining, m), replace=False)
for child in children:
tree.add_edge(node, root + child + 1)
add_recursive_edges(root + child + 1, remaining - child - 1)
add_recursive_edges(root, n - 1)
return tree
####
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
# Function to plot the degree distribution PDF
def plot_degree_distribution_pdf(graph_type, graph, title, ax):
degrees = [degree for node, degree in graph.degree()]
degree_count = np.bincount(degrees)
pdf = degree_count / len(degrees)
ax.bar(range(len(pdf)), pdf, width=0.8, alpha=0.7, label=graph_type)
ax.set_title(title)
ax.set_xlabel('Degree')
ax.set_ylabel('Probability Density')
ax.set_xticks(np.arange(0, max(degrees)+1, 1))
ax.set_xlim([-0.5, max(degrees)+0.5])
# Generate RSRG graph
n = 1000 # Number of nodes
p = 0.05 # Probability of adding an edge between two nodes
rsrg_graph = nx.random_regular_graph(int(np.log(n)), n)
# Generate RSRBG graph
m1 = 500 # Number of nodes in set A
m2 = 500 # Number of nodes in set B
p_in = 0.1 # Probability of adding an edge between nodes in the same set
p_out = 0.01 # Probability of adding an edge between nodes in different sets
rsrbg_graph = nx.random_partition_graph([m1, m2], p_in, p_out)
# Generate Watts-Strogatz graph
n = 1000 # Number of nodes
k = 10 # Each node is connected to k nearest neighbors
p = 0.1 # Probability of rewiring each edge
ws_graph = nx.watts_strogatz_graph(n, k, p)
# Generate Scale-Free graph
n = 1000 # Number of nodes
m = 10 # Number of edges to attach from a new node to existing nodes
sf_graph = nx.barabasi_albert_graph(n, m)
# Generate Erdős-Rényi graph
n = 1000 # Number of nodes
p = 0.01 # Probability of adding an edge between two nodes
er_graph = nx.erdos_renyi_graph(n, p)
# Generate Random Recursive Tree
rrt_graph = generate_random_recursive_tree(n, m)
# Create subplots
fig, ax = plt.subplots()
# Plotting degree distribution PDFs for all graphs
plot_degree_distribution_pdf("RSRG", rsrg_graph, "RSRG Degree Distribution PDF", ax)
plot_degree_distribution_pdf("RSRBG", rsrbg_graph, "RSRBG Degree Distribution PDF", ax)
plot_degree_distribution_pdf("WS", ws_graph, "WS Degree Distribution PDF", ax)
plot_degree_distribution_pdf("SF", sf_graph, "SF Degree Distribution PDF", ax)
plot_degree_distribution_pdf("ER", er_graph, "ER Degree Distribution PDF", ax)
plot_degree_distribution_pdf("RRT", rrt_graph, "Random Recursive Tree Degree Distribution PDF", ax)
# Set plot properties
ax.legend()
ax.grid(True)
# Display the plot
plt.show()
import networkx as nx
import numpy as np
import random
import matplotlib.pyplot as plt
import math
from collections import defaultdict
# Function to plot the degree distribution PDF
def plot_degree_distribution_pdf(graph_type, degrees, title):
degree_count = np.bincount(degrees)
pdf = degree_count / len(degrees)
plt.bar(range(len(pdf)), pdf, width=0.8, color='b')
plt.title(title)
plt.xlabel('Degree')
plt.ylabel('Probability Density')
plt.xticks(np.arange(0, max(degrees)+1, 1))
plt.xlim([-0.5, max(degrees)+0.5])
plt.show()
# Random Scale-Free Recursive Graph (RSRG)
def plot_rsr_graph():
graph = nx.barabasi_albert_graph(100, 3, seed=42)
degrees = [degree for _, degree in graph.degree()]
degree_hist = np.histogram(degrees, bins=range(max(degrees) + 2))[0]
degree_pdf = degree_hist / sum(degree_hist)
plt.plot(range(len(degree_pdf)), degree_pdf, label='RSRG')
# Random Scale-Free Recursive Bipartite Graph (RSRBG)
def plot_rsr_bipartite_graph():
graph = nx.bipartite.random_graph(10, 5, 0.5, seed=42)
projection = nx.bipartite.projected_graph(graph, list(range(10)))
degrees = [degree for _, degree in projection.degree()]
degree_hist = np.histogram(degrees, bins=range(max(degrees) + 2))[0]
degree_pdf = degree_hist / sum(degree_hist)
plt.plot(range(len(degree_pdf)), degree_pdf, label='RSRBG')
# Watts-Strogatz (WS)
def plot_ws_graph():
graph = nx.watts_strogatz_graph(100, 4, 0.3, seed=42)
degrees = [degree for _, degree in graph.degree()]
degree_hist = np.histogram(degrees, bins=range(max(degrees) + 2))[0]
degree_pdf = degree_hist / sum(degree_hist)
plt.plot(range(len(degree_pdf)), degree_pdf, label='WS')
# Scale-Free (SF)
def plot_sf_graph():
graph = nx.scale_free_graph(100, seed=42)
degrees = [degree for _, degree in graph.degree()]
degree_hist = np.histogram(degrees, bins=range(max(degrees) + 2))[0]
degree_pdf = degree_hist / sum(degree_hist)
plt.plot(range(len(degree_pdf)), degree_pdf, label='SF')
# Erdos-Renyi (ER)
def plot_er_graph():
graph = nx.erdos_renyi_graph(100, 0.15, seed=42)
degrees = [degree for _, degree in graph.degree()]
degree_hist = np.histogram(degrees, bins=range(max(degrees) + 2))[0]
degree_pdf = degree_hist / sum(degree_hist)
plt.plot(range(len(degree_pdf)), degree_pdf, label='ER')
# Plotting all graphs
plot_rsr_graph()
plot_rsr_bipartite_graph()
plot_ws_graph()
plot_sf_graph()
plot_er_graph()
# Setting plot properties
plt.xlabel('Degree')
plt.ylabel('Probability Density')
plt.title('Degree Distribution PDF')
plt.legend()
plt.grid(True)
# Display the plot
plt.show()