CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-networkx

Python package for creating and manipulating graphs and networks

Pending
Overview
Eval results
Files

generators.mddocs/

Graph Generators

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.

Capabilities

Classic Graphs

Well-known graph structures that appear frequently in graph theory and applications.

def complete_graph(n, create_using=None):
    """
    Create a complete graph with n nodes.
    
    Parameters:
    - n: Number of nodes or iterable of nodes
    - create_using: Graph constructor (default: Graph())
    
    Returns:
    Complete graph where every pair of nodes is connected
    """

def path_graph(n, create_using=None):
    """Create a path graph with n nodes."""

def cycle_graph(n, create_using=None):
    """Create a cycle graph with n nodes."""

def wheel_graph(n, create_using=None):
    """Create a wheel graph with n nodes."""

def star_graph(n, create_using=None):
    """Create a star graph with n+1 nodes."""

def complete_bipartite_graph(n1, n2, create_using=None):
    """Create a complete bipartite graph."""

def empty_graph(n=0, create_using=None, default=None):
    """Create an empty graph with n nodes and no edges."""

def null_graph(create_using=None):
    """Create the null graph (no nodes, no edges)."""

Random Graphs

Algorithms for generating random graphs with various probability models.

def erdos_renyi_graph(n, p, seed=None, directed=False):
    """
    Generate Erdős–Rényi random graph.
    
    Parameters:
    - n: Number of nodes
    - p: Probability of edge creation between any pair of nodes
    - seed: Random seed for reproducibility
    - directed: Create directed graph if True
    
    Returns:
    Random graph with n nodes and edges created with probability p
    """

def gnm_random_graph(n, m, seed=None, directed=False):
    """Generate random graph with n nodes and m edges."""

def barabasi_albert_graph(n, m, seed=None, initial_graph=None):
    """Generate Barabási–Albert preferential attachment graph."""

def watts_strogatz_graph(n, k, p, seed=None):
    """Generate Watts–Strogatz small-world graph."""

def newman_watts_strogatz_graph(n, k, p, seed=None):
    """Generate Newman–Watts–Strogatz small-world graph."""

def random_regular_graph(d, n, seed=None):
    """Generate random d-regular graph with n nodes."""

def powerlaw_cluster_graph(n, m, p, seed=None):
    """Generate graph with powerlaw degree distribution and clustering."""

Tree Generators

Functions for creating various types of tree structures.

def random_tree(n, seed=None, create_using=None):
    """
    Generate uniformly random tree with n nodes.
    
    Parameters:
    - n: Number of nodes
    - seed: Random seed
    - create_using: Graph constructor
    
    Returns:
    Random tree with n nodes
    """

def full_rary_tree(r, n, create_using=None):
    """Create full r-ary tree with n nodes."""

def balanced_tree(r, h, create_using=None):
    """Create balanced r-ary tree of height h."""

def binomial_tree(n, create_using=None):
    """Create binomial tree of order n."""

def prefix_tree(paths):
    """Create prefix tree from paths."""

Lattice Graphs

Regular grid and lattice structures commonly used in spatial analysis.

def grid_2d_graph(m, n, periodic=False, create_using=None):
    """
    Create 2D grid graph.
    
    Parameters:
    - m, n: Grid dimensions
    - periodic: Create periodic boundary conditions (torus)
    - create_using: Graph constructor
    
    Returns:
    Grid graph with m×n nodes
    """

def grid_graph(dim, periodic=False, create_using=None):
    """Create n-dimensional grid graph."""

def hypercube_graph(n, create_using=None):
    """Create n-dimensional hypercube graph."""

def triangular_lattice_graph(m, n, periodic=False, with_positions=True, create_using=None):
    """Create triangular lattice graph."""

def hexagonal_lattice_graph(m, n, periodic=False, with_positions=True, create_using=None):
    """Create hexagonal lattice graph."""

Social Network Graphs

Graph models commonly used to represent social networks and relationships.

def karate_club_graph():
    """
    Return Zachary's karate club graph.
    
    Returns:
    Famous social network graph with 34 nodes representing members
    of a karate club, with edges representing friendships
    """

def davis_southern_women_graph():
    """Return Davis Southern women social network."""

def florentine_families_graph():
    """Return Florentine families graph."""

def les_miserables_graph():
    """Return Les Misérables character network."""

def caveman_graph(l, k):
    """Generate caveman graph with l cliques of size k."""

def relaxed_caveman_graph(l, k, p, seed=None):
    """Generate relaxed caveman graph with rewiring probability p."""

Small Named Graphs

Collection of small, well-known graphs used in graph theory.

def petersen_graph(create_using=None):
    """Create Petersen graph."""

def tutte_graph(create_using=None):
    """Create Tutte graph."""

def sedgewick_maze_graph(create_using=None):
    """Create Sedgewick maze graph."""

def tetrahedral_graph(create_using=None):
    """Create tetrahedral graph (complete graph K4)."""

def octahedral_graph(create_using=None):
    """Create octahedral graph."""

def dodecahedral_graph(create_using=None):
    """Create dodecahedral graph."""

def icosahedral_graph(create_using=None):
    """Create icosahedral graph."""

Geometric Graphs

Graphs embedded in geometric spaces with proximity-based connections.

def random_geometric_graph(n, radius, dim=2, pos=None, p=2, seed=None):
    """
    Generate random geometric graph.
    
    Parameters:
    - n: Number of nodes
    - radius: Connection radius
    - dim: Dimension of space
    - pos: Node positions (generated if None)
    - p: Minkowski distance parameter
    - seed: Random seed
    
    Returns:
    Graph where nodes are connected if within radius distance
    """

def unit_disk_graph(nodes, radius, p=2):
    """Create unit disk graph from node positions."""

def gabriel_graph(G, pos=None):
    """Create Gabriel graph from geometric graph."""

def relative_neighborhood_graph(G, pos=None):
    """Create relative neighborhood graph."""

Directed Graph Generators

Generators specifically for creating directed graphs.

def gn_graph(n, seed=None, create_using=None):
    """Generate growing network (GN) directed graph."""

def gnr_graph(n, p, seed=None, create_using=None):
    """Generate growing network with redirection (GNR) graph."""

def gnc_graph(n, seed=None, create_using=None):
    """Generate growing network with copying (GNC) graph."""

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):
    """Generate scale-free directed graph."""

def random_k_out_graph(n, k, alpha, self_loops=True, seed=None):
    """Generate random k-out graph."""

Degree Sequence Graphs

Generate graphs with specified degree sequences.

def configuration_model(deg_sequence, seed=None, create_using=None):
    """
    Generate graph from degree sequence using configuration model.
    
    Parameters:
    - deg_sequence: List of node degrees
    - seed: Random seed
    - create_using: Graph constructor
    
    Returns:
    Random graph with specified degree sequence
    """

def directed_configuration_model(in_deg_sequence, out_deg_sequence, seed=None, create_using=None):
    """Generate directed graph from in/out degree sequences."""

def expected_degree_graph(w, seed=None, selfloops=True):
    """Generate graph from expected degree sequence."""

def havel_hakimi_graph(deg_sequence, create_using=None):
    """Generate graph using Havel-Hakimi algorithm."""

def degree_sequence_tree(deg_sequence, create_using=None):
    """Generate tree with specified degree sequence."""

Community Structure Generators

Generate graphs with built-in community structure for testing community detection algorithms.

def planted_partition_graph(l, k, p_in, p_out, seed=None, directed=False):
    """
    Generate planted partition graph with community structure.
    
    Parameters:
    - l: Number of communities
    - k: Number of nodes per community
    - p_in: Intra-community edge probability
    - p_out: Inter-community edge probability
    - seed: Random seed
    - directed: Create directed graph
    
    Returns:
    Graph with l communities of k nodes each
    """

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):
    """Generate LFR benchmark graph with community structure."""

def gaussian_random_partition_graph(n, s, v, p_in, p_out, directed=False, seed=None):
    """Generate Gaussian random partition graph."""

def ring_of_cliques(num_cliques, clique_size):
    """Generate ring of cliques graph."""

def connected_caveman_graph(l, k):
    """Generate connected caveman graph."""

Usage Examples

Creating Classic Graphs

import networkx as nx
import matplotlib.pyplot as plt

# Complete graph
K5 = nx.complete_graph(5)
print(f"K5 has {K5.number_of_nodes()} nodes and {K5.number_of_edges()} edges")

# Path and cycle graphs
path = nx.path_graph(6)
cycle = nx.cycle_graph(6)

# Wheel and star graphs
wheel = nx.wheel_graph(8)
star = nx.star_graph(5)

# Visualize
fig, axes = plt.subplots(2, 2, figsize=(10, 10))
nx.draw(K5, ax=axes[0,0], with_labels=True, title="Complete Graph K5")
nx.draw(cycle, ax=axes[0,1], with_labels=True, title="Cycle Graph C6")
nx.draw(wheel, ax=axes[1,0], with_labels=True, title="Wheel Graph W8")
nx.draw(star, ax=axes[1,1], with_labels=True, title="Star Graph S5")
plt.tight_layout()
plt.show()

Random Graph Models

# Erdős–Rényi random graph
G_er = nx.erdos_renyi_graph(100, 0.05, seed=42)

# Barabási–Albert preferential attachment
G_ba = nx.barabasi_albert_graph(100, 3, seed=42)

# Watts–Strogatz small-world
G_ws = nx.watts_strogatz_graph(100, 6, 0.1, seed=42)

# Compare properties
graphs = [("Erdős–Rényi", G_er), ("Barabási–Albert", G_ba), ("Watts–Strogatz", G_ws)]

for name, G in graphs:
    clustering = nx.average_clustering(G)
    path_length = nx.average_shortest_path_length(G)
    print(f"{name}: clustering={clustering:.3f}, path_length={path_length:.3f}")

Social Network Data

# Load famous social network datasets
karate = nx.karate_club_graph()
families = nx.florentine_families_graph()
women = nx.davis_southern_women_graph()

# Analyze karate club
print(f"Karate club: {karate.number_of_nodes()} members, {karate.number_of_edges()} friendships")

# Find most connected person
degrees = dict(karate.degree())
most_connected = max(degrees, key=degrees.get)
print(f"Most connected member: {most_connected} with {degrees[most_connected]} connections")

# Compute centrality
centrality = nx.betweenness_centrality(karate)
most_central = max(centrality, key=centrality.get)
print(f"Most central member: {most_central}")

Lattice and Grid Graphs

# 2D grid graph
grid = nx.grid_2d_graph(5, 5)
print(f"5×5 grid: {grid.number_of_nodes()} nodes, {grid.number_of_edges()} edges")

# Periodic grid (torus)
torus = nx.grid_2d_graph(5, 5, periodic=True)
print(f"5×5 torus: {torus.number_of_nodes()} nodes, {torus.number_of_edges()} edges")

# Triangular and hexagonal lattices
triangular = nx.triangular_lattice_graph(4, 4)
hexagonal = nx.hexagonal_lattice_graph(3, 3)

# Draw with positions
pos_grid = dict((n, n) for n in grid.nodes())
pos_tri = nx.get_node_attributes(triangular, 'pos')
pos_hex = nx.get_node_attributes(hexagonal, 'pos')

fig, axes = plt.subplots(1, 3, figsize=(15, 5))
nx.draw(grid, pos=pos_grid, ax=axes[0], node_size=50, title="Grid")
nx.draw(triangular, pos=pos_tri, ax=axes[1], node_size=50, title="Triangular")
nx.draw(hexagonal, pos=pos_hex, ax=axes[2], node_size=50, title="Hexagonal")
plt.tight_layout()
plt.show()

Install with Tessl CLI

npx tessl i tessl/pypi-networkx

docs

algorithms.md

conversion.md

drawing.md

generators.md

graph-classes.md

graph-io.md

index.md

linear-algebra.md

tile.json