Skill Tracer
Skills › Scientific Agent Skills › networkx › generators.md

generators.md

397 lines · skills/networkx/references/generators.md at 5f2bc03

Open on GitHub
1# NetworkX Graph Generators
2
3API patterns assume `import networkx as nx`. A generated model is a hypothesis about a graph, not evidence that observed data follow that model. Preserve direction, loops, multiplicity, size, degree constraints and seed/version provenance when constructing null ensembles. See [review.md](review.md).
4

NetworkX Graph Generators

API patterns assume import networkx as nx. A generated model is a hypothesis about a graph, not evidence that observed data follow that model. Preserve direction, loops, multiplicity, size, degree constraints and seed/version provenance when constructing null ensembles. See review.md.

Raw lines 1 to 4
5## Classic Graphs
6

Classic Graphs

Raw lines 5 to 6
7### Complete Graphs
8```python
9# Complete graph (all nodes connected to all others)
10G = nx.complete_graph(n=10)
12# Complete bipartite graph
13G = nx.complete_bipartite_graph(n1=5, n2=7)
15# Complete multipartite graph
16G = nx.complete_multipartite_graph(3, 4, 5) # Three partitions
17```

Complete Graphs

# Complete graph (all nodes connected to all others)
G = nx.complete_graph(n=10)

# Complete bipartite graph
G = nx.complete_bipartite_graph(n1=5, n2=7)

# Complete multipartite graph
G = nx.complete_multipartite_graph(3, 4, 5)  # Three partitions
Raw lines 7 to 18
19### Cycle and Path Graphs
20```python
21# Cycle graph (nodes arranged in circle)
22G = nx.cycle_graph(n=20)
24# Path graph (linear chain)
25G = nx.path_graph(n=15)
27# Circular ladder graph
28G = nx.circular_ladder_graph(n=10)
29```

Cycle and Path Graphs

# Cycle graph (nodes arranged in circle)
G = nx.cycle_graph(n=20)

# Path graph (linear chain)
G = nx.path_graph(n=15)

# Circular ladder graph
G = nx.circular_ladder_graph(n=10)
Raw lines 19 to 30
31### Regular Graphs
32```python
33# Empty graph (no edges)
34G = nx.empty_graph(n=10)
36# Null graph (no nodes)
37G = nx.null_graph()
39# Star graph (one central node connected to all others)
40G = nx.star_graph(n=19) # Creates 20-node star
42# Wheel graph (cycle with central hub)
43G = nx.wheel_graph(n=10)
44```

Regular Graphs

# Empty graph (no edges)
G = nx.empty_graph(n=10)

# Null graph (no nodes)
G = nx.null_graph()

# Star graph (one central node connected to all others)
G = nx.star_graph(n=19)  # Creates 20-node star

# Wheel graph (cycle with central hub)
G = nx.wheel_graph(n=10)
Raw lines 31 to 45
46### Special Named Graphs
47```python
48# Bull graph
49G = nx.bull_graph()
51# Chvatal graph
52G = nx.chvatal_graph()
54# Cubical graph
55G = nx.cubical_graph()
57# Diamond graph
58G = nx.diamond_graph()
60# Dodecahedral graph
61G = nx.dodecahedral_graph()
63# Heawood graph
64G = nx.heawood_graph()
66# House graph
67G = nx.house_graph()
69# Petersen graph
70G = nx.petersen_graph()
72# Karate club graph (classic social network)
73G = nx.karate_club_graph()
74```

Special Named Graphs

# Bull graph
G = nx.bull_graph()

# Chvatal graph
G = nx.chvatal_graph()

# Cubical graph
G = nx.cubical_graph()

# Diamond graph
G = nx.diamond_graph()

# Dodecahedral graph
G = nx.dodecahedral_graph()

# Heawood graph
G = nx.heawood_graph()

# House graph
G = nx.house_graph()

# Petersen graph
G = nx.petersen_graph()

# Karate club graph (classic social network)
G = nx.karate_club_graph()
Raw lines 46 to 75
76## Random Graphs

Random Graphs

Raw lines 76 to 77
78### Erdős-Rényi Graphs
79```python
80# G(n, p) model: n nodes, edge probability p
81G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)
83# G(n, m) model: n nodes, exactly m edges
84G = nx.gnm_random_graph(n=100, m=500, seed=42)
86# Fast version (for large sparse graphs)
87G = nx.fast_gnp_random_graph(n=10000, p=0.0001, seed=42)
88```

Erdős-Rényi Graphs

# G(n, p) model: n nodes, edge probability p
G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)

# G(n, m) model: n nodes, exactly m edges
G = nx.gnm_random_graph(n=100, m=500, seed=42)

# Fast version (for large sparse graphs)
G = nx.fast_gnp_random_graph(n=10000, p=0.0001, seed=42)
Raw lines 78 to 89
90### Watts-Strogatz Small-World
91```python
92# Small-world network with rewiring
93# n nodes, k nearest neighbors, rewiring probability p
94G = nx.watts_strogatz_graph(n=100, k=6, p=0.1, seed=42)
96# Returns a connected sample or raises after tries attempts
97G = nx.connected_watts_strogatz_graph(n=100, k=6, p=0.1, tries=100, seed=42)
98```

Watts-Strogatz Small-World

# Small-world network with rewiring
# n nodes, k nearest neighbors, rewiring probability p
G = nx.watts_strogatz_graph(n=100, k=6, p=0.1, seed=42)

# Returns a connected sample or raises after tries attempts
G = nx.connected_watts_strogatz_graph(n=100, k=6, p=0.1, tries=100, seed=42)
Raw lines 90 to 99
100### Barabási-Albert Preferential Attachment
101```python
102# Preferential-attachment model; finite samples do not establish a power law
103# n nodes, m edges to attach from new node
104G = nx.barabasi_albert_graph(n=100, m=3, seed=42)
106# Extended version with parameters
107G = nx.extended_barabasi_albert_graph(n=100, m=3, p=0.5, q=0.2, seed=42)
108```

Barabási-Albert Preferential Attachment

# Preferential-attachment model; finite samples do not establish a power law
# n nodes, m edges to attach from new node
G = nx.barabasi_albert_graph(n=100, m=3, seed=42)

# Extended version with parameters
G = nx.extended_barabasi_albert_graph(n=100, m=3, p=0.5, q=0.2, seed=42)
Raw lines 100 to 109
110### Power Law Degree Sequence
111```python
112# Power law cluster graph
113G = nx.powerlaw_cluster_graph(n=100, m=3, p=0.1, seed=42)
115# Random power law tree
116G = nx.random_powerlaw_tree(n=100, gamma=3, seed=42, tries=1000)
117```

Power Law Degree Sequence

# Power law cluster graph
G = nx.powerlaw_cluster_graph(n=100, m=3, p=0.1, seed=42)

# Random power law tree
G = nx.random_powerlaw_tree(n=100, gamma=3, seed=42, tries=1000)
Raw lines 110 to 118
119### Configuration Model
120```python
121# Graph with specified degree sequence
122degree_sequence = [3, 3, 2, 2, 2, 2] # Even sum required
123G = nx.configuration_model(degree_sequence, seed=42)
124assert [G.degree(i) for i in range(len(degree_sequence))] == degree_sequence
126# Optional simplification changes the degree sequence and null model
127H = nx.Graph(G)
128H.remove_edges_from(list(nx.selfloop_edges(H)))
129```
131The configuration model is a stub-matching **multigraph** with possible self-loops. Removing loops/parallel edges does not preserve the specified degrees. `havel_hakimi_graph` gives one simple realization of a graphical sequence, not a uniform random sample. Degree-preserving swaps need adequate mixing and convergence checks; neither a single sample nor a fixed seed establishes null-model validity.

Configuration Model

# Graph with specified degree sequence
degree_sequence = [3, 3, 2, 2, 2, 2]  # Even sum required
G = nx.configuration_model(degree_sequence, seed=42)
assert [G.degree(i) for i in range(len(degree_sequence))] == degree_sequence

# Optional simplification changes the degree sequence and null model
H = nx.Graph(G)
H.remove_edges_from(list(nx.selfloop_edges(H)))

The configuration model is a stub-matching multigraph with possible self-loops. Removing loops/parallel edges does not preserve the specified degrees. havel_hakimi_graph gives one simple realization of a graphical sequence, not a uniform random sample. Degree-preserving swaps need adequate mixing and convergence checks; neither a single sample nor a fixed seed establishes null-model validity.

Raw lines 119 to 132
133### Random Geometric Graphs
134```python
135# Nodes in unit square, edges if distance < radius
136G = nx.random_geometric_graph(n=100, radius=0.2, seed=42)
138# With positions
139pos = nx.get_node_attributes(G, 'pos')
140```

Random Geometric Graphs

# Nodes in unit square, edges if distance < radius
G = nx.random_geometric_graph(n=100, radius=0.2, seed=42)

# With positions
pos = nx.get_node_attributes(G, 'pos')
Raw lines 133 to 141
142### Random Regular Graphs
143```python
144# Every node has exactly d neighbors
145G = nx.random_regular_graph(d=3, n=100, seed=42)
146```

Random Regular Graphs

# Every node has exactly d neighbors
G = nx.random_regular_graph(d=3, n=100, seed=42)
Raw lines 142 to 147
148### Stochastic Block Model
149```python
150# Community structure model
151sizes = [50, 50, 50] # Three communities
152probs = [[0.25, 0.05, 0.02], # Within and between community probabilities
153 [0.05, 0.35, 0.07],
154 [0.02, 0.07, 0.40]]
155G = nx.stochastic_block_model(sizes, probs, seed=42)
156```

Stochastic Block Model

# Community structure model
sizes = [50, 50, 50]  # Three communities
probs = [[0.25, 0.05, 0.02],  # Within and between community probabilities
         [0.05, 0.35, 0.07],
         [0.02, 0.07, 0.40]]
G = nx.stochastic_block_model(sizes, probs, seed=42)
Raw lines 148 to 157
158## Lattice and Grid Graphs

Lattice and Grid Graphs

Raw lines 158 to 159
160### Grid Graphs
161```python
162# 2D grid
163G = nx.grid_2d_graph(m=5, n=7) # 5x7 grid
165# 3D grid
166G = nx.grid_graph(dim=[5, 7, 3]) # 5x7x3 grid
168# Hexagonal lattice
169G = nx.hexagonal_lattice_graph(m=5, n=7)
171# Triangular lattice
172G = nx.triangular_lattice_graph(m=5, n=7)
173```

Grid Graphs

# 2D grid
G = nx.grid_2d_graph(m=5, n=7)  # 5x7 grid

# 3D grid
G = nx.grid_graph(dim=[5, 7, 3])  # 5x7x3 grid

# Hexagonal lattice
G = nx.hexagonal_lattice_graph(m=5, n=7)

# Triangular lattice
G = nx.triangular_lattice_graph(m=5, n=7)
Raw lines 160 to 174
175### Hypercube
176```python
177# n-dimensional hypercube
178G = nx.hypercube_graph(n=4)
179```

Hypercube

# n-dimensional hypercube
G = nx.hypercube_graph(n=4)
Raw lines 175 to 180
181## Tree Graphs
183### Random Trees
184```python
185# Random labeled tree with n nodes, sampled uniformly over labeled trees
186# (nx.random_tree was removed in NetworkX 3.4)
187G = nx.random_labeled_tree(100, seed=42)
189# Sample uniformly over isomorphism classes instead
190G = nx.random_unlabeled_tree(100, seed=42)
192# Rooted variant is still an undirected Graph, with G.graph["root"]
193G = nx.random_labeled_rooted_tree(100, seed=42)
195# Prefix tree (tries)
196G = nx.prefix_tree([[0, 1, 2], [0, 1, 3], [0, 4]])
197```

Random Trees

# Random labeled tree with n nodes, sampled uniformly over labeled trees
# (nx.random_tree was removed in NetworkX 3.4)
G = nx.random_labeled_tree(100, seed=42)

# Sample uniformly over isomorphism classes instead
G = nx.random_unlabeled_tree(100, seed=42)

# Rooted variant is still an undirected Graph, with G.graph["root"]
G = nx.random_labeled_rooted_tree(100, seed=42)

# Prefix tree (tries)
G = nx.prefix_tree([[0, 1, 2], [0, 1, 3], [0, 4]])
Raw lines 183 to 198
199### Balanced Trees
200```python
201# Balanced r-ary tree of height h
202G = nx.balanced_tree(r=2, h=5) # Binary tree, height 5
204# Full r-ary tree with n nodes
205G = nx.full_rary_tree(r=3, n=100) # Ternary tree
206```

Balanced Trees

# Balanced r-ary tree of height h
G = nx.balanced_tree(r=2, h=5)  # Binary tree, height 5

# Full r-ary tree with n nodes
G = nx.full_rary_tree(r=3, n=100)  # Ternary tree
Raw lines 199 to 207
208### Barbell and Lollipop Graphs
209```python
210# Two complete graphs connected by path
211G = nx.barbell_graph(m1=5, m2=3) # Two K_5 graphs with 3-node path
213# Complete graph connected to path
214G = nx.lollipop_graph(m=7, n=5) # K_7 with 5-node path
215```

Barbell and Lollipop Graphs

# Two complete graphs connected by path
G = nx.barbell_graph(m1=5, m2=3)  # Two K_5 graphs with 3-node path

# Complete graph connected to path
G = nx.lollipop_graph(m=7, n=5)  # K_7 with 5-node path
Raw lines 208 to 216
217## Social Network Models

Social Network Models

Raw lines 217 to 218
219### Karate Club
220```python
221# Zachary's karate club (classic social network)
222G = nx.karate_club_graph()
223```

Karate Club

# Zachary's karate club (classic social network)
G = nx.karate_club_graph()
Raw lines 219 to 224
225### Davis Southern Women
226```python
227# Bipartite social network
228G = nx.davis_southern_women_graph()
229```

Davis Southern Women

# Bipartite social network
G = nx.davis_southern_women_graph()
Raw lines 225 to 230
231### Florentine Families
232```python
233# Historical marriage network (this generator does not add business ties)
234G = nx.florentine_families_graph()
235```

Florentine Families

# Historical marriage network (this generator does not add business ties)
G = nx.florentine_families_graph()
Raw lines 231 to 236
237### Les Misérables
238```python
239# Character co-occurrence network
240G = nx.les_miserables_graph()
241```

Les Misérables

# Character co-occurrence network
G = nx.les_miserables_graph()
Raw lines 237 to 242
243## Directed Graph Generators

Directed Graph Generators

Raw lines 243 to 244
245### Random Directed Graphs
246```python
247# Directed Erdős-Rényi
248G = nx.gnp_random_graph(n=100, p=0.1, directed=True, seed=42)
250# Directed MultiDiGraph; parallel edges and self-loops can occur
251G = nx.scale_free_graph(n=100, seed=42)
252```

Random Directed Graphs

# Directed Erdős-Rényi
G = nx.gnp_random_graph(n=100, p=0.1, directed=True, seed=42)

# Directed MultiDiGraph; parallel edges and self-loops can occur
G = nx.scale_free_graph(n=100, seed=42)
Raw lines 245 to 253
254### DAG (Directed Acyclic Graph)
255```python
256# Ordered random DAG; this is not uniform over all DAGs
257R = nx.gnp_random_graph(n=20, p=0.2, directed=True, seed=42)
258G = nx.DiGraph()
259G.add_nodes_from(R) # Preserve isolates
260G.add_edges_from((u, v) for u, v in R.edges() if u < v)
261assert len(G) == 20 and nx.is_directed_acyclic_graph(G)
262```

DAG (Directed Acyclic Graph)

# Ordered random DAG; this is not uniform over all DAGs
R = nx.gnp_random_graph(n=20, p=0.2, directed=True, seed=42)
G = nx.DiGraph()
G.add_nodes_from(R)  # Preserve isolates
G.add_edges_from((u, v) for u, v in R.edges() if u < v)
assert len(G) == 20 and nx.is_directed_acyclic_graph(G)
Raw lines 254 to 263
264### Tournament Graphs
265```python
266# Random tournament (complete directed graph); lives in the tournament module
267G = nx.tournament.random_tournament(n=10, seed=42)
268```

Tournament Graphs

# Random tournament (complete directed graph); lives in the tournament module
G = nx.tournament.random_tournament(n=10, seed=42)
Raw lines 264 to 269
270## Duplication-Divergence Models

Duplication-Divergence Models

Raw lines 270 to 271
272### Duplication Divergence Graph
273```python
274# Biological network model (protein interaction networks)
275G = nx.duplication_divergence_graph(n=100, p=0.5, seed=42)
276```

Duplication Divergence Graph

# Biological network model (protein interaction networks)
G = nx.duplication_divergence_graph(n=100, p=0.5, seed=42)
Raw lines 272 to 277
278## Degree Sequence Generators

Degree Sequence Generators

Raw lines 278 to 279
280### Valid Degree Sequences
281```python
282# Check if degree sequence is valid (graphical)
283sequence = [3, 3, 2, 2, 2, 2]
284is_valid = nx.is_graphical(sequence)
286# For directed graphs
287in_sequence = [2, 2, 2, 1, 1]
288out_sequence = [2, 2, 1, 2, 1]
289is_valid = nx.is_digraphical(in_sequence, out_sequence)
290```

Valid Degree Sequences

# Check if degree sequence is valid (graphical)
sequence = [3, 3, 2, 2, 2, 2]
is_valid = nx.is_graphical(sequence)

# For directed graphs
in_sequence = [2, 2, 2, 1, 1]
out_sequence = [2, 2, 1, 2, 1]
is_valid = nx.is_digraphical(in_sequence, out_sequence)
Raw lines 280 to 291
292### Creating from Degree Sequence
293```python
294# Havel-Hakimi algorithm
295G = nx.havel_hakimi_graph(degree_sequence)
297# Configuration model (allows multi-edges/self-loops)
298G = nx.configuration_model(degree_sequence, seed=42)
300# Directed configuration model: sums must match
301G = nx.directed_configuration_model(in_sequence, out_sequence, seed=42)
302```

Creating from Degree Sequence

# Havel-Hakimi algorithm
G = nx.havel_hakimi_graph(degree_sequence)

# Configuration model (allows multi-edges/self-loops)
G = nx.configuration_model(degree_sequence, seed=42)

# Directed configuration model: sums must match
G = nx.directed_configuration_model(in_sequence, out_sequence, seed=42)
Raw lines 292 to 303
304## Bipartite Graphs

Bipartite Graphs

Raw lines 304 to 305
306### Random Bipartite
307```python
308# Random bipartite with two node sets
309G = nx.bipartite.random_graph(n=50, m=30, p=0.1, seed=42)
311# Configuration model for bipartite
312G = nx.bipartite.configuration_model(aseq=[3, 3, 2], bseq=[2, 2, 2, 2], seed=42)
313```

Random Bipartite

# Random bipartite with two node sets
G = nx.bipartite.random_graph(n=50, m=30, p=0.1, seed=42)

# Configuration model for bipartite
G = nx.bipartite.configuration_model(aseq=[3, 3, 2], bseq=[2, 2, 2, 2], seed=42)
Raw lines 306 to 314
315### Bipartite Generators
316```python
317# Complete bipartite
318G = nx.complete_bipartite_graph(n1=5, n2=7)
320# Gnmk random bipartite (n, m nodes, k edges)
321G = nx.bipartite.gnmk_random_graph(n=10, m=8, k=20, seed=42)
322```

Bipartite Generators

# Complete bipartite
G = nx.complete_bipartite_graph(n1=5, n2=7)

# Gnmk random bipartite (n, m nodes, k edges)
G = nx.bipartite.gnmk_random_graph(n=10, m=8, k=20, seed=42)
Raw lines 315 to 323
324## Operators on Graphs

Operators on Graphs

Raw lines 324 to 325
326### Graph Operations
327```python
328# Union requires disjoint node labels (or supply rename prefixes)
329G = nx.union(G1, G2)
331# Disjoint union
332G = nx.disjoint_union(G1, G2)
334# Compose (overlay)
335G = nx.compose(G1, G2)
337# Complement
338G = nx.complement(G1)
340# Cartesian product
341G = nx.cartesian_product(G1, G2)
343# Tensor (Kronecker) product
344G = nx.tensor_product(G1, G2)
346# Strong product
347G = nx.strong_product(G1, G2)
348```

Graph Operations

# Union requires disjoint node labels (or supply rename prefixes)
G = nx.union(G1, G2)

# Disjoint union
G = nx.disjoint_union(G1, G2)

# Compose (overlay)
G = nx.compose(G1, G2)

# Complement
G = nx.complement(G1)

# Cartesian product
G = nx.cartesian_product(G1, G2)

# Tensor (Kronecker) product
G = nx.tensor_product(G1, G2)

# Strong product
G = nx.strong_product(G1, G2)
Raw lines 326 to 349
350## Customization and Seeding

Customization and Seeding

Raw lines 350 to 351
352### Setting Random Seed
353Set a seed and record NetworkX/Python versions and generation parameters. A seed does not promise identical graphs across releases/backends:
354```python
355G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)
356```

Setting Random Seed

Set a seed and record NetworkX/Python versions and generation parameters. A seed does not promise identical graphs across releases/backends:

G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)
Raw lines 352 to 357
358### Converting Graph Types
359```python
360# Convert to specific type
361G_directed = G.to_directed()
362G_undirected = G.to_undirected()
363G_multi = nx.MultiGraph(G)
364```

Converting Graph Types

# Convert to specific type
G_directed = G.to_directed()
G_undirected = G.to_undirected()
G_multi = nx.MultiGraph(G)
Raw lines 358 to 365
366## Performance Considerations

Performance Considerations

Raw lines 366 to 367
368### Fast Generators
369For large graphs, use optimized generators:
370```python
371# Fast ER graph (sparse)
372G = nx.fast_gnp_random_graph(n=10000, p=0.0001, seed=42)
373```

Fast Generators

For large graphs, use optimized generators:

# Fast ER graph (sparse)
G = nx.fast_gnp_random_graph(n=10000, p=0.0001, seed=42)
Raw lines 368 to 374
375### Memory Efficiency
376Some generators create graphs incrementally to save memory. For very large graphs, consider:
377- Using sparse representations
378- Generating subgraphs as needed
379- Working with adjacency lists or edge lists instead of full graphs

Memory Efficiency

Some generators create graphs incrementally to save memory. For very large graphs, consider:

  • Using sparse representations
  • Generating subgraphs as needed
  • Working with adjacency lists or edge lists instead of full graphs
Raw lines 375 to 380
381## Validation and Properties

Validation and Properties

Raw lines 381 to 382
383### Checking Generated Graphs
384```python
385# Verify properties
386print(f"Nodes: {G.number_of_nodes()}")
387print(f"Edges: {G.number_of_edges()}")
388print(f"Density: {nx.density(G)}")
389if len(G):
390 connected = nx.is_weakly_connected(G) if G.is_directed() else nx.is_connected(G)
391 print(f"Connected (weak if directed): {connected}")
392else:
393 print("Connectivity undefined for the null graph")
395# Degree distribution
396degree_sequence = sorted([d for n, d in G.degree()], reverse=True)
397```

Checking Generated Graphs

# Verify properties
print(f"Nodes: {G.number_of_nodes()}")
print(f"Edges: {G.number_of_edges()}")
print(f"Density: {nx.density(G)}")
if len(G):
    connected = nx.is_weakly_connected(G) if G.is_directed() else nx.is_connected(G)
    print(f"Connected (weak if directed): {connected}")
else:
    print("Connectivity undefined for the null graph")

# Degree distribution
degree_sequence = sorted([d for n, d in G.degree()], reverse=True)
Raw lines 383 to 397