A high-performance graph library for Python implemented in Rust, providing fast graph algorithms and data structures for computational tasks
—
Comprehensive collection of graph generation algorithms for creating various graph types including classic graphs, random graphs, lattice structures, and special topologies. All generators support both directed and undirected variants with customizable parameters.
Standard graph topologies commonly used in graph theory and applications.
def cycle_graph(num_nodes: int, weights = None, multigraph: bool = True):
"""
Generate undirected cycle graph (ring topology).
Parameters:
- num_nodes (int): Number of nodes in cycle
- weights (list, optional): Node weights, default uses node indices
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Cycle graph with nodes connected in ring
"""
def directed_cycle_graph(num_nodes: int, weights = None, multigraph: bool = True):
"""
Generate directed cycle graph.
Parameters:
- num_nodes (int): Number of nodes in cycle
- weights (list, optional): Node weights
- multigraph (bool): Allow parallel edges
Returns:
PyDiGraph: Directed cycle graph
"""
def path_graph(num_nodes: int, weights = None, multigraph: bool = True):
"""
Generate undirected path graph (linear chain).
Parameters:
- num_nodes (int): Number of nodes in path
- weights (list, optional): Node weights
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Path graph with linear connectivity
"""
def directed_path_graph(num_nodes: int, weights = None, multigraph: bool = True):
"""
Generate directed path graph.
Parameters:
- num_nodes (int): Number of nodes in path
- weights (list, optional): Node weights
- multigraph (bool): Allow parallel edges
Returns:
PyDiGraph: Directed path graph
"""
def star_graph(num_nodes: int, weights = None, multigraph: bool = True):
"""
Generate undirected star graph (hub-and-spoke topology).
Parameters:
- num_nodes (int): Total number of nodes (including central hub)
- weights (list, optional): Node weights
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Star graph with central hub connected to all other nodes
"""
def directed_star_graph(num_nodes: int, weights = None, multigraph: bool = True):
"""
Generate directed star graph.
Parameters:
- num_nodes (int): Total number of nodes
- weights (list, optional): Node weights
- multigraph (bool): Allow parallel edges
Returns:
PyDiGraph: Directed star graph with hub as source
"""
def complete_graph(num_nodes: int, weights = None, multigraph: bool = True):
"""
Generate complete graph (all nodes connected to all others).
Parameters:
- num_nodes (int): Number of nodes
- weights (list, optional): Node weights
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Complete graph with all possible edges
"""
def directed_complete_graph(num_nodes: int, weights = None, multigraph: bool = True):
"""
Generate directed complete graph.
Parameters:
- num_nodes (int): Number of nodes
- weights (list, optional): Node weights
- multigraph (bool): Allow parallel edges
Returns:
PyDiGraph: Directed complete graph
"""
def empty_graph(num_nodes: int, weights = None, multigraph: bool = True):
"""
Generate empty graph (nodes only, no edges).
Parameters:
- num_nodes (int): Number of isolated nodes
- weights (list, optional): Node weights
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Graph with nodes but no edges
"""
def directed_empty_graph(num_nodes: int, weights = None, multigraph: bool = True):
"""
Generate directed empty graph.
Parameters:
- num_nodes (int): Number of isolated nodes
- weights (list, optional): Node weights
- multigraph (bool): Allow parallel edges
Returns:
PyDiGraph: Directed graph with nodes but no edges
"""Regular grid structures and lattice topologies for spatial and geometric applications.
def grid_graph(rows: int, cols: int = None, weights = None, multigraph: bool = True):
"""
Generate 2D grid graph with rectangular topology.
Parameters:
- rows (int): Number of rows in grid
- cols (int, optional): Number of columns, defaults to rows (square grid)
- weights (list, optional): Node weights
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: 2D grid graph with nodes at lattice points
"""
def directed_grid_graph(rows: int, cols: int = None, weights = None, multigraph: bool = True):
"""
Generate directed 2D grid graph.
Parameters:
- rows (int): Number of rows
- cols (int, optional): Number of columns
- weights (list, optional): Node weights
- multigraph (bool): Allow parallel edges
Returns:
PyDiGraph: Directed 2D grid graph
"""
def mesh_graph(num_nodes: int, multigraph: bool = True):
"""
Generate mesh graph (complete graph topology).
Parameters:
- num_nodes (int): Number of nodes in mesh
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Fully connected mesh topology
"""
def directed_mesh_graph(num_nodes: int, multigraph: bool = True):
"""
Generate directed mesh graph.
Parameters:
- num_nodes (int): Number of nodes
- multigraph (bool): Allow parallel edges
Returns:
PyDiGraph: Directed mesh graph
"""
def hexagonal_lattice_graph(rows: int, cols: int, multigraph: bool = True, with_positions: bool = False, periodic: bool = False):
"""
Generate hexagonal lattice graph.
Parameters:
- rows (int): Number of rows in lattice
- cols (int): Number of columns in lattice
- multigraph (bool): Allow parallel edges
- with_positions (bool): Include node position data
- periodic (bool): Create periodic boundary conditions
Returns:
PyGraph: Hexagonal lattice with 6-neighbor connectivity
"""
def heavy_square_graph(d: int, multigraph: bool = True):
"""
Generate heavy square lattice graph.
Parameters:
- d (int): Lattice dimension parameter
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Heavy square lattice topology
"""
def heavy_hex_graph(d: int, multigraph: bool = True):
"""
Generate heavy hexagonal lattice graph.
Parameters:
- d (int): Lattice dimension parameter
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Heavy hexagonal lattice topology
"""
def directed_heavy_square_graph(d: int, multigraph: bool = True):
"""
Generate directed heavy square lattice graph.
Parameters:
- d (int): Lattice dimension parameter
- multigraph (bool): Allow parallel edges
Returns:
PyDiGraph: Directed heavy square lattice topology
"""
def directed_heavy_hex_graph(d: int, multigraph: bool = True):
"""
Generate directed heavy hexagonal lattice graph.
Parameters:
- d (int): Lattice dimension parameter
- multigraph (bool): Allow parallel edges
Returns:
PyDiGraph: Directed heavy hexagonal lattice topology
"""
def directed_hexagonal_lattice_graph(rows: int, cols: int, multigraph: bool = True, with_positions: bool = False, periodic: bool = False):
"""
Generate directed hexagonal lattice graph.
Parameters:
- rows (int): Number of rows in lattice
- cols (int): Number of columns in lattice
- multigraph (bool): Allow parallel edges
- with_positions (bool): Include node position data
- periodic (bool): Create periodic boundary conditions
Returns:
PyDiGraph: Directed hexagonal lattice with 6-neighbor connectivity
"""Hierarchical tree topologies for representing structured data and algorithms.
def binomial_tree_graph(order: int, multigraph: bool = True):
"""
Generate binomial tree graph.
Parameters:
- order (int): Order of binomial tree
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Binomial tree with specified order
"""
def directed_binomial_tree_graph(order: int, multigraph: bool = True):
"""
Generate directed binomial tree graph.
Parameters:
- order (int): Order of binomial tree
- multigraph (bool): Allow parallel edges
Returns:
PyDiGraph: Directed binomial tree with specified order
"""
def full_rary_tree(branching_factor: int, num_levels: int, weights = None, multigraph: bool = True):
"""
Generate complete r-ary tree.
Parameters:
- branching_factor (int): Number of children per internal node
- num_levels (int): Number of levels in tree (including root)
- weights (list, optional): Node weights
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Complete r-ary tree structure
"""Unique graph structures with specific properties and applications.
def lollipop_graph(num_complete: int, num_path: int, weights = None, multigraph: bool = True):
"""
Generate lollipop graph (complete graph connected to path).
Parameters:
- num_complete (int): Size of complete graph component
- num_path (int): Length of path component
- weights (list, optional): Node weights
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Lollipop graph topology
"""
def barbell_graph(num_complete: int, num_path: int, weights = None, multigraph: bool = True):
"""
Generate barbell graph (two complete graphs connected by path).
Parameters:
- num_complete (int): Size of each complete graph component
- num_path (int): Length of connecting path
- weights (list, optional): Node weights
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Barbell graph topology
"""
def generalized_petersen_graph(n: int, k: int, multigraph: bool = True):
"""
Generate generalized Petersen graph.
Parameters:
- n (int): Number of vertices in each ring
- k (int): Connection parameter
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Generalized Petersen graph
"""
def dorogovtsev_goltsev_mendes_graph(n: int, multigraph: bool = True):
"""
Generate Dorogovtsev-Goltsev-Mendes fractal graph.
Parameters:
- n (int): Number of iterations for fractal construction
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: DGM fractal graph structure
"""
def karate_club_graph(multigraph: bool = True):
"""
Generate Zachary's karate club graph (classic social network).
Parameters:
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Karate club social network with 34 nodes
"""Probabilistic graph generation models for simulation and analysis.
def directed_gnm_random_graph(num_nodes: int, num_edges: int, seed: int = None, multigraph: bool = True):
"""
Generate directed G(n,m) random graph with fixed edge count.
Parameters:
- num_nodes (int): Number of nodes
- num_edges (int): Number of edges to add randomly
- seed (int, optional): Random seed for reproducibility
- multigraph (bool): Allow parallel edges
Returns:
PyDiGraph: Random directed graph with specified edge count
"""
def undirected_gnm_random_graph(num_nodes: int, num_edges: int, seed: int = None, multigraph: bool = True):
"""
Generate undirected G(n,m) random graph with fixed edge count.
Parameters:
- num_nodes (int): Number of nodes
- num_edges (int): Number of edges to add randomly
- seed (int, optional): Random seed
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Random undirected graph with specified edge count
"""
def directed_gnp_random_graph(num_nodes: int, probability: float, seed: int = None, multigraph: bool = True):
"""
Generate directed G(n,p) random graph with edge probability.
Parameters:
- num_nodes (int): Number of nodes
- probability (float): Probability of edge between any two nodes (0.0 to 1.0)
- seed (int, optional): Random seed
- multigraph (bool): Allow parallel edges
Returns:
PyDiGraph: Random directed graph with probabilistic edges
"""
def undirected_gnp_random_graph(num_nodes: int, probability: float, seed: int = None, multigraph: bool = True):
"""
Generate undirected G(n,p) random graph with edge probability.
Parameters:
- num_nodes (int): Number of nodes
- probability (float): Edge probability (0.0 to 1.0)
- seed (int, optional): Random seed
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Random undirected graph with probabilistic edges
"""
def barabasi_albert_graph(n: int, m: int, seed: int = None, initial_graph = None, multigraph: bool = True):
"""
Generate Barabási-Albert preferential attachment graph.
Creates scale-free network where new nodes preferentially
attach to existing nodes with higher degree.
Parameters:
- n (int): Final number of nodes
- m (int): Number of edges added per new node
- seed (int, optional): Random seed
- initial_graph (PyGraph, optional): Starting graph structure
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Scale-free network with power-law degree distribution
"""
def directed_barabasi_albert_graph(n: int, m: int, seed: int = None, initial_graph = None, multigraph: bool = True):
"""
Generate directed Barabási-Albert preferential attachment graph.
Creates directed scale-free network where new nodes preferentially
attach to existing nodes with higher in-degree or out-degree.
Parameters:
- n (int): Final number of nodes
- m (int): Number of edges added per new node
- seed (int, optional): Random seed
- initial_graph (PyDiGraph, optional): Starting directed graph structure
- multigraph (bool): Allow parallel edges
Returns:
PyDiGraph: Directed scale-free network with power-law degree distribution
"""
def random_geometric_graph(num_nodes: int, radius: float, dim: int = 2, pos = None, p: float = 2, seed: int = None, multigraph: bool = True):
"""
Generate random geometric graph in d-dimensional space.
Nodes are placed randomly in unit cube and connected if
their distance is less than the specified radius.
Parameters:
- num_nodes (int): Number of nodes
- radius (float): Connection radius
- dim (int): Spatial dimension (default 2)
- pos (dict, optional): Predefined node positions
- p (float): Distance metric parameter (2 for Euclidean)
- seed (int, optional): Random seed
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Geometric graph with spatial connectivity
"""
def hyperbolic_random_graph(n: int, alpha: float, beta: float, gamma: float, seed: int = None, multigraph: bool = True):
"""
Generate hyperbolic random graph.
Creates graphs with specified clustering and degree distribution
properties using hyperbolic geometry.
Parameters:
- n (int): Number of nodes
- alpha (float): Power-law exponent for degree distribution
- beta (float): Clustering parameter
- gamma (float): Temperature parameter
- seed (int, optional): Random seed
- multigraph (bool): Allow parallel edges
Returns:
PyGraph: Hyperbolic random graph with tunable properties
"""
def directed_sbm_random_graph(num_nodes: int, block_sizes: list, edge_probs: list, seed: int = None, multigraph: bool = True):
"""
Generate directed stochastic block model (SBM) random graph.
Creates a directed graph using the stochastic block model where nodes
are divided into blocks (communities) and edge probabilities depend
on block membership. This model is useful for generating graphs with
community structure and varying connectivity patterns between groups.
Parameters:
- num_nodes (int): Total number of nodes
- block_sizes (list): List of block sizes, must sum to num_nodes
- edge_probs (list): 2D list/matrix of edge probabilities between blocks
- seed (int, optional): Random seed for reproducibility
- multigraph (bool): Allow parallel edges
Returns:
PyDiGraph: Directed stochastic block model graph with community structure
"""import rustworkx.generators as rx_gen
# Generate classic structures
cycle = rx_gen.cycle_graph(6)
path = rx_gen.path_graph(10)
star = rx_gen.star_graph(7) # 1 hub + 6 spokes
complete = rx_gen.complete_graph(5)
print(f"Cycle nodes: {cycle.num_nodes()}, edges: {cycle.num_edges()}")
print(f"Complete graph edges: {complete.num_edges()}") # Should be n(n-1)/2 = 10# Create 2D grids for spatial algorithms
square_grid = rx_gen.grid_graph(4, 4) # 4x4 grid
rectangular_grid = rx_gen.grid_graph(3, 5) # 3x5 grid
# Hexagonal lattice for certain applications
hex_lattice = rx_gen.hexagonal_lattice_graph(
rows=5, cols=5,
with_positions=True # Include coordinate data
)
print(f"4x4 grid: {square_grid.num_nodes()} nodes, {square_grid.num_edges()} edges")
print(f"Hex lattice: {hex_lattice.num_nodes()} nodes")# Generate hierarchical structures
binary_tree = rx_gen.full_rary_tree(
branching_factor=2,
num_levels=4 # 4 levels: root + 3 more
)
ternary_tree = rx_gen.full_rary_tree(
branching_factor=3,
num_levels=3
)
binomial = rx_gen.binomial_tree_graph(order=3)
print(f"Binary tree: {binary_tree.num_nodes()} nodes")
print(f"Ternary tree: {ternary_tree.num_nodes()} nodes")import rustworkx as rx
# Erdős-Rényi random graphs
# G(n,m) model: fixed number of edges
gnm_graph = rx_gen.undirected_gnm_random_graph(
num_nodes=20,
num_edges=30,
seed=42 # For reproducibility
)
# G(n,p) model: probabilistic edges
gnp_graph = rx_gen.undirected_gnp_random_graph(
num_nodes=20,
probability=0.15,
seed=42
)
print(f"G(n,m): {gnm_graph.num_edges()} edges (should be exactly 30)")
print(f"G(n,p): {gnp_graph.num_edges()} edges (probabilistic)")# Barabási-Albert preferential attachment
scale_free = rx_gen.barabasi_albert_graph(
n=100, # Final size
m=3, # Edges added per new node
seed=42
)
# Analyze degree distribution
degrees = [scale_free.degree(node) for node in scale_free.node_indices()]
max_degree = max(degrees)
avg_degree = sum(degrees) / len(degrees)
print(f"Scale-free network: max degree {max_degree}, avg degree {avg_degree:.2f}")# Random geometric graph
geometric = rx_gen.random_geometric_graph(
num_nodes=50,
radius=0.3, # Connection radius in unit square
dim=2, # 2D space
seed=42
)
# Hyperbolic random graph with specific properties
hyperbolic = rx_gen.hyperbolic_random_graph(
n=100,
alpha=2.5, # Power-law exponent
beta=0.8, # Clustering parameter
gamma=2.0, # Temperature
seed=42
)
print(f"Geometric graph: {geometric.num_edges()} edges")
print(f"Hyperbolic graph: {hyperbolic.num_edges()} edges")# Create compound structures
lollipop = rx_gen.lollipop_graph(
num_complete=5, # Complete K5
num_path=3 # Path of length 3
)
barbell = rx_gen.barbell_graph(
num_complete=4, # Two K4 components
num_path=2 # Connected by path of length 2
)
# Famous graph datasets
karate = rx_gen.karate_club_graph()
print(f"Lollipop: {lollipop.num_nodes()} nodes, {lollipop.num_edges()} edges")
print(f"Karate club: {karate.num_nodes()} nodes, {karate.num_edges()} edges")# Generate directed variants
directed_cycle = rx_gen.directed_cycle_graph(8)
directed_complete = rx_gen.directed_complete_graph(4)
directed_random = rx_gen.directed_gnp_random_graph(
num_nodes=15,
probability=0.2,
seed=42
)
# Check strong connectivity
is_strongly_connected = rx.is_strongly_connected(directed_cycle)
print(f"Directed cycle strongly connected: {is_strongly_connected}")# Generate with custom node weights
node_weights = [f"Node_{i}" for i in range(10)]
weighted_cycle = rx_gen.cycle_graph(
num_nodes=10,
weights=node_weights
)
# Verify weights are applied
nodes_data = weighted_cycle.nodes()
print(f"Node weights: {nodes_data[:5]}") # First 5 nodes
# Generate empty graph and add custom edges
base_graph = rx_gen.empty_graph(5, weights=['A', 'B', 'C', 'D', 'E'])
base_graph.add_edges_from([
(0, 1, 1.5),
(1, 2, 2.3),
(2, 3, 0.8),
(3, 4, 3.1)
])
print(f"Custom graph: {base_graph.num_edges()} edges with weights")Install with Tessl CLI
npx tessl i tessl/pypi-rustworkx