0
# Graph Generators
1
2
Functions to create various types of graphs including classic graphs, random graphs, social networks, lattices, trees, and specialized network structures. NetworkX provides comprehensive graph generation capabilities for research, testing, and modeling.
3
4
## Capabilities
5
6
### Classic Graphs
7
8
Well-known graph structures that appear frequently in graph theory and applications.
9
10
```python { .api }
11
def complete_graph(n, create_using=None):
12
"""
13
Create a complete graph with n nodes.
14
15
Parameters:
16
- n: Number of nodes or iterable of nodes
17
- create_using: Graph constructor (default: Graph())
18
19
Returns:
20
Complete graph where every pair of nodes is connected
21
"""
22
23
def path_graph(n, create_using=None):
24
"""Create a path graph with n nodes."""
25
26
def cycle_graph(n, create_using=None):
27
"""Create a cycle graph with n nodes."""
28
29
def wheel_graph(n, create_using=None):
30
"""Create a wheel graph with n nodes."""
31
32
def star_graph(n, create_using=None):
33
"""Create a star graph with n+1 nodes."""
34
35
def complete_bipartite_graph(n1, n2, create_using=None):
36
"""Create a complete bipartite graph."""
37
38
def empty_graph(n=0, create_using=None, default=None):
39
"""Create an empty graph with n nodes and no edges."""
40
41
def null_graph(create_using=None):
42
"""Create the null graph (no nodes, no edges)."""
43
```
44
45
### Random Graphs
46
47
Algorithms for generating random graphs with various probability models.
48
49
```python { .api }
50
def erdos_renyi_graph(n, p, seed=None, directed=False):
51
"""
52
Generate Erdős–Rényi random graph.
53
54
Parameters:
55
- n: Number of nodes
56
- p: Probability of edge creation between any pair of nodes
57
- seed: Random seed for reproducibility
58
- directed: Create directed graph if True
59
60
Returns:
61
Random graph with n nodes and edges created with probability p
62
"""
63
64
def gnm_random_graph(n, m, seed=None, directed=False):
65
"""Generate random graph with n nodes and m edges."""
66
67
def barabasi_albert_graph(n, m, seed=None, initial_graph=None):
68
"""Generate Barabási–Albert preferential attachment graph."""
69
70
def watts_strogatz_graph(n, k, p, seed=None):
71
"""Generate Watts–Strogatz small-world graph."""
72
73
def newman_watts_strogatz_graph(n, k, p, seed=None):
74
"""Generate Newman–Watts–Strogatz small-world graph."""
75
76
def random_regular_graph(d, n, seed=None):
77
"""Generate random d-regular graph with n nodes."""
78
79
def powerlaw_cluster_graph(n, m, p, seed=None):
80
"""Generate graph with powerlaw degree distribution and clustering."""
81
```
82
83
### Tree Generators
84
85
Functions for creating various types of tree structures.
86
87
```python { .api }
88
def random_tree(n, seed=None, create_using=None):
89
"""
90
Generate uniformly random tree with n nodes.
91
92
Parameters:
93
- n: Number of nodes
94
- seed: Random seed
95
- create_using: Graph constructor
96
97
Returns:
98
Random tree with n nodes
99
"""
100
101
def full_rary_tree(r, n, create_using=None):
102
"""Create full r-ary tree with n nodes."""
103
104
def balanced_tree(r, h, create_using=None):
105
"""Create balanced r-ary tree of height h."""
106
107
def binomial_tree(n, create_using=None):
108
"""Create binomial tree of order n."""
109
110
def prefix_tree(paths):
111
"""Create prefix tree from paths."""
112
```
113
114
### Lattice Graphs
115
116
Regular grid and lattice structures commonly used in spatial analysis.
117
118
```python { .api }
119
def grid_2d_graph(m, n, periodic=False, create_using=None):
120
"""
121
Create 2D grid graph.
122
123
Parameters:
124
- m, n: Grid dimensions
125
- periodic: Create periodic boundary conditions (torus)
126
- create_using: Graph constructor
127
128
Returns:
129
Grid graph with m×n nodes
130
"""
131
132
def grid_graph(dim, periodic=False, create_using=None):
133
"""Create n-dimensional grid graph."""
134
135
def hypercube_graph(n, create_using=None):
136
"""Create n-dimensional hypercube graph."""
137
138
def triangular_lattice_graph(m, n, periodic=False, with_positions=True, create_using=None):
139
"""Create triangular lattice graph."""
140
141
def hexagonal_lattice_graph(m, n, periodic=False, with_positions=True, create_using=None):
142
"""Create hexagonal lattice graph."""
143
```
144
145
### Social Network Graphs
146
147
Graph models commonly used to represent social networks and relationships.
148
149
```python { .api }
150
def karate_club_graph():
151
"""
152
Return Zachary's karate club graph.
153
154
Returns:
155
Famous social network graph with 34 nodes representing members
156
of a karate club, with edges representing friendships
157
"""
158
159
def davis_southern_women_graph():
160
"""Return Davis Southern women social network."""
161
162
def florentine_families_graph():
163
"""Return Florentine families graph."""
164
165
def les_miserables_graph():
166
"""Return Les Misérables character network."""
167
168
def caveman_graph(l, k):
169
"""Generate caveman graph with l cliques of size k."""
170
171
def relaxed_caveman_graph(l, k, p, seed=None):
172
"""Generate relaxed caveman graph with rewiring probability p."""
173
```
174
175
### Small Named Graphs
176
177
Collection of small, well-known graphs used in graph theory.
178
179
```python { .api }
180
def petersen_graph(create_using=None):
181
"""Create Petersen graph."""
182
183
def tutte_graph(create_using=None):
184
"""Create Tutte graph."""
185
186
def sedgewick_maze_graph(create_using=None):
187
"""Create Sedgewick maze graph."""
188
189
def tetrahedral_graph(create_using=None):
190
"""Create tetrahedral graph (complete graph K4)."""
191
192
def octahedral_graph(create_using=None):
193
"""Create octahedral graph."""
194
195
def dodecahedral_graph(create_using=None):
196
"""Create dodecahedral graph."""
197
198
def icosahedral_graph(create_using=None):
199
"""Create icosahedral graph."""
200
```
201
202
### Geometric Graphs
203
204
Graphs embedded in geometric spaces with proximity-based connections.
205
206
```python { .api }
207
def random_geometric_graph(n, radius, dim=2, pos=None, p=2, seed=None):
208
"""
209
Generate random geometric graph.
210
211
Parameters:
212
- n: Number of nodes
213
- radius: Connection radius
214
- dim: Dimension of space
215
- pos: Node positions (generated if None)
216
- p: Minkowski distance parameter
217
- seed: Random seed
218
219
Returns:
220
Graph where nodes are connected if within radius distance
221
"""
222
223
def unit_disk_graph(nodes, radius, p=2):
224
"""Create unit disk graph from node positions."""
225
226
def gabriel_graph(G, pos=None):
227
"""Create Gabriel graph from geometric graph."""
228
229
def relative_neighborhood_graph(G, pos=None):
230
"""Create relative neighborhood graph."""
231
```
232
233
### Directed Graph Generators
234
235
Generators specifically for creating directed graphs.
236
237
```python { .api }
238
def gn_graph(n, seed=None, create_using=None):
239
"""Generate growing network (GN) directed graph."""
240
241
def gnr_graph(n, p, seed=None, create_using=None):
242
"""Generate growing network with redirection (GNR) graph."""
243
244
def gnc_graph(n, seed=None, create_using=None):
245
"""Generate growing network with copying (GNC) graph."""
246
247
def scale_free_graph(n, alpha=0.41, beta=0.54, gamma=0.05, delta_in=0.2, delta_out=0, seed=None, create_using=None):
248
"""Generate scale-free directed graph."""
249
250
def random_k_out_graph(n, k, alpha, self_loops=True, seed=None):
251
"""Generate random k-out graph."""
252
```
253
254
### Degree Sequence Graphs
255
256
Generate graphs with specified degree sequences.
257
258
```python { .api }
259
def configuration_model(deg_sequence, seed=None, create_using=None):
260
"""
261
Generate graph from degree sequence using configuration model.
262
263
Parameters:
264
- deg_sequence: List of node degrees
265
- seed: Random seed
266
- create_using: Graph constructor
267
268
Returns:
269
Random graph with specified degree sequence
270
"""
271
272
def directed_configuration_model(in_deg_sequence, out_deg_sequence, seed=None, create_using=None):
273
"""Generate directed graph from in/out degree sequences."""
274
275
def expected_degree_graph(w, seed=None, selfloops=True):
276
"""Generate graph from expected degree sequence."""
277
278
def havel_hakimi_graph(deg_sequence, create_using=None):
279
"""Generate graph using Havel-Hakimi algorithm."""
280
281
def degree_sequence_tree(deg_sequence, create_using=None):
282
"""Generate tree with specified degree sequence."""
283
```
284
285
### Community Structure Generators
286
287
Generate graphs with built-in community structure for testing community detection algorithms.
288
289
```python { .api }
290
def planted_partition_graph(l, k, p_in, p_out, seed=None, directed=False):
291
"""
292
Generate planted partition graph with community structure.
293
294
Parameters:
295
- l: Number of communities
296
- k: Number of nodes per community
297
- p_in: Intra-community edge probability
298
- p_out: Inter-community edge probability
299
- seed: Random seed
300
- directed: Create directed graph
301
302
Returns:
303
Graph with l communities of k nodes each
304
"""
305
306
def LFR_benchmark_graph(n, tau1, tau2, mu, average_degree=None, min_degree=None, max_degree=None, min_community=None, max_community=None, tol=1e-07, max_iters=500, seed=None):
307
"""Generate LFR benchmark graph with community structure."""
308
309
def gaussian_random_partition_graph(n, s, v, p_in, p_out, directed=False, seed=None):
310
"""Generate Gaussian random partition graph."""
311
312
def ring_of_cliques(num_cliques, clique_size):
313
"""Generate ring of cliques graph."""
314
315
def connected_caveman_graph(l, k):
316
"""Generate connected caveman graph."""
317
```
318
319
## Usage Examples
320
321
### Creating Classic Graphs
322
323
```python
324
import networkx as nx
325
import matplotlib.pyplot as plt
326
327
# Complete graph
328
K5 = nx.complete_graph(5)
329
print(f"K5 has {K5.number_of_nodes()} nodes and {K5.number_of_edges()} edges")
330
331
# Path and cycle graphs
332
path = nx.path_graph(6)
333
cycle = nx.cycle_graph(6)
334
335
# Wheel and star graphs
336
wheel = nx.wheel_graph(8)
337
star = nx.star_graph(5)
338
339
# Visualize
340
fig, axes = plt.subplots(2, 2, figsize=(10, 10))
341
nx.draw(K5, ax=axes[0,0], with_labels=True, title="Complete Graph K5")
342
nx.draw(cycle, ax=axes[0,1], with_labels=True, title="Cycle Graph C6")
343
nx.draw(wheel, ax=axes[1,0], with_labels=True, title="Wheel Graph W8")
344
nx.draw(star, ax=axes[1,1], with_labels=True, title="Star Graph S5")
345
plt.tight_layout()
346
plt.show()
347
```
348
349
### Random Graph Models
350
351
```python
352
# Erdős–Rényi random graph
353
G_er = nx.erdos_renyi_graph(100, 0.05, seed=42)
354
355
# Barabási–Albert preferential attachment
356
G_ba = nx.barabasi_albert_graph(100, 3, seed=42)
357
358
# Watts–Strogatz small-world
359
G_ws = nx.watts_strogatz_graph(100, 6, 0.1, seed=42)
360
361
# Compare properties
362
graphs = [("Erdős–Rényi", G_er), ("Barabási–Albert", G_ba), ("Watts–Strogatz", G_ws)]
363
364
for name, G in graphs:
365
clustering = nx.average_clustering(G)
366
path_length = nx.average_shortest_path_length(G)
367
print(f"{name}: clustering={clustering:.3f}, path_length={path_length:.3f}")
368
```
369
370
### Social Network Data
371
372
```python
373
# Load famous social network datasets
374
karate = nx.karate_club_graph()
375
families = nx.florentine_families_graph()
376
women = nx.davis_southern_women_graph()
377
378
# Analyze karate club
379
print(f"Karate club: {karate.number_of_nodes()} members, {karate.number_of_edges()} friendships")
380
381
# Find most connected person
382
degrees = dict(karate.degree())
383
most_connected = max(degrees, key=degrees.get)
384
print(f"Most connected member: {most_connected} with {degrees[most_connected]} connections")
385
386
# Compute centrality
387
centrality = nx.betweenness_centrality(karate)
388
most_central = max(centrality, key=centrality.get)
389
print(f"Most central member: {most_central}")
390
```
391
392
### Lattice and Grid Graphs
393
394
```python
395
# 2D grid graph
396
grid = nx.grid_2d_graph(5, 5)
397
print(f"5×5 grid: {grid.number_of_nodes()} nodes, {grid.number_of_edges()} edges")
398
399
# Periodic grid (torus)
400
torus = nx.grid_2d_graph(5, 5, periodic=True)
401
print(f"5×5 torus: {torus.number_of_nodes()} nodes, {torus.number_of_edges()} edges")
402
403
# Triangular and hexagonal lattices
404
triangular = nx.triangular_lattice_graph(4, 4)
405
hexagonal = nx.hexagonal_lattice_graph(3, 3)
406
407
# Draw with positions
408
pos_grid = dict((n, n) for n in grid.nodes())
409
pos_tri = nx.get_node_attributes(triangular, 'pos')
410
pos_hex = nx.get_node_attributes(hexagonal, 'pos')
411
412
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
413
nx.draw(grid, pos=pos_grid, ax=axes[0], node_size=50, title="Grid")
414
nx.draw(triangular, pos=pos_tri, ax=axes[1], node_size=50, title="Triangular")
415
nx.draw(hexagonal, pos=pos_hex, ax=axes[2], node_size=50, title="Hexagonal")
416
plt.tight_layout()
417
plt.show()
418
```