qbiocode.apps.quvine.data.random_graphs module#
Random Graph Generator for QuVINE
This module provides functions to generate various types of random graphs with known structures or specific key elements that are suitable for testing embedding algorithms. Includes both classical graph models and biologically-inspired structures.
Summary#
Functions:
Add hub nodes to an existing graph. |
|
Generate a Barabási-Albert scale-free network using preferential attachment. |
|
Generate a random bipartite graph. |
|
Generate a comprehensive dataset of random graphs for embedding analysis. |
|
Generate a simple graph from a configuration model with power-law, log-normal, or Poisson degree sequence. |
|
Generate a core-periphery network structure. |
|
Generate a degree-corrected SBM. |
|
Generate an Erdős-Rényi random graph. |
|
Generate a random graph with designated seed and target nodes for embedding evaluation. |
|
Generate a regular grid or torus lattice. |
|
Generate an SBM where p_out / p_in is controlled. |
|
Generate a hierarchical network with tree-like structure plus random edges. |
|
Generate a modular network with clear community structure. |
|
Generate a random graph with powerlaw degree distribution and clustering. |
|
Generate a random geometric graph in the unit cube. |
|
Generate a random d-regular graph. |
|
Generate a stochastic block model graph with community structure. |
|
Generate a Watts-Strogatz small-world network. |
|
Compute comprehensive statistics for a graph. |
|
Load a previously saved comprehensive dataset. |
|
Sample a degree sequence and rescale it to target average degree. |
|
Generate sweep of configuration model graphs. |
|
Generate sweep of degree-corrected SBM graphs. |
|
Generate sweep of grid/torus lattice graphs. |
|
Generate sweep of heterophilic SBM graphs. |
|
Generate sweep of random regular graphs. |
Reference#
- generate_erdos_renyi(n, p=None, m=None, seed=None, directed=False)[source]#
Generate an Erdős-Rényi random graph.
- Parameters:
n (int) – Number of nodes
p (float, optional) – Probability of edge creation (G(n,p) model)
m (int, optional) – Number of edges (G(n,m) model)
seed (int, optional) – Random seed for reproducibility
directed (bool, default=False) – If True, generate a directed graph
- Returns:
Random graph
- Return type:
nx.Graph or nx.DiGraph
- generate_barabasi_albert(n, m, seed=None, initial_graph=None)[source]#
Generate a Barabási-Albert scale-free network using preferential attachment.
- Parameters:
n (int) – Number of nodes
m (int) – Number of edges to attach from a new node to existing nodes
seed (int, optional) – Random seed for reproducibility
initial_graph (nx.Graph, optional) – Initial connected graph with at least m nodes
- Returns:
Scale-free network
- Return type:
nx.Graph
- generate_watts_strogatz(n, k, p, seed=None)[source]#
Generate a Watts-Strogatz small-world network.
- Parameters:
n (int) – Number of nodes
k (int) – Each node is connected to k nearest neighbors in ring topology
p (float) – Probability of rewiring each edge
seed (int, optional) – Random seed for reproducibility
- Returns:
Small-world network
- Return type:
nx.Graph
- generate_powerlaw_cluster(n, m, p, seed=None)[source]#
Generate a random graph with powerlaw degree distribution and clustering.
- Parameters:
n (int) – Number of nodes
m (int) – Number of random edges to add for each new node
p (float) – Probability of adding a triangle after adding a random edge
seed (int, optional) – Random seed for reproducibility
- Returns:
Powerlaw cluster graph
- Return type:
nx.Graph
- generate_stochastic_block_model(sizes, p_matrix, seed=None, directed=False, selfloops=False)[source]#
Generate a stochastic block model graph with community structure.
- Parameters:
sizes (list of int) – Sizes of blocks (communities)
p_matrix (list of list of float) – Matrix of edge probabilities between and within blocks
seed (int, optional) – Random seed for reproducibility
directed (bool, default=False) – If True, generate a directed graph
selfloops (bool, default=False) – If True, allow self-loops
- Returns:
Stochastic block model graph with community structure
- Return type:
nx.Graph or nx.DiGraph
- generate_random_geometric(n, radius, dim=2, seed=None, pos=None)[source]#
Generate a random geometric graph in the unit cube.
- Parameters:
n (int) – Number of nodes
radius (float) – Distance threshold for edge creation
dim (int, default=2) – Dimension of the space
seed (int, optional) – Random seed for reproducibility
pos (dict, optional) – Dictionary of node positions
- Returns:
Random geometric graph with ‘pos’ node attribute
- Return type:
nx.Graph
- generate_modular_network(num_communities, nodes_per_community, p_intra, p_inter, seed=None)[source]#
Generate a modular network with clear community structure.
- Parameters:
num_communities (int) – Number of communities
nodes_per_community (int) – Number of nodes in each community
p_intra (float) – Probability of edges within communities
p_inter (float) – Probability of edges between communities
seed (int, optional) – Random seed for reproducibility
- Return type:
Tuple[Graph,Dict[int,int]]- Returns:
G (nx.Graph) – Modular network
communities (dict) – Mapping from node to community ID
- generate_hierarchical_network(levels, branching_factor, p_level=0.1, seed=None)[source]#
Generate a hierarchical network with tree-like structure plus random edges.
- Parameters:
levels (int) – Number of hierarchy levels
branching_factor (int) – Number of children per parent node
p_level (float, default=0.1) – Probability of random edges within same level
seed (int, optional) – Random seed for reproducibility
- Return type:
Tuple[Graph,Dict[int,int]]- Returns:
G (nx.Graph) – Hierarchical network
node_levels (dict) – Mapping from node to hierarchy level
- generate_core_periphery(n_core, n_periphery, p_core, p_core_periphery, p_periphery=0.01, seed=None)[source]#
Generate a core-periphery network structure.
- Parameters:
n_core (int) – Number of core nodes
n_periphery (int) – Number of periphery nodes
p_core (float) – Edge probability within core
p_core_periphery (float) – Edge probability between core and periphery
p_periphery (float, default=0.01) – Edge probability within periphery
seed (int, optional) – Random seed for reproducibility
- Return type:
Tuple[Graph,Set[int],Set[int]]- Returns:
G (nx.Graph) – Core-periphery network
core_nodes (set) – Set of core node IDs
periphery_nodes (set) – Set of periphery node IDs
- generate_bipartite_random(n1, n2, p=None, m=None, seed=None)[source]#
Generate a random bipartite graph.
- Parameters:
n1 (int) – Number of nodes in first partition
n2 (int) – Number of nodes in second partition
p (float, optional) – Probability of edge creation
m (int, optional) – Number of edges
seed (int, optional) – Random seed for reproducibility
- Return type:
Tuple[Graph,Set[int],Set[int]]- Returns:
G (nx.Graph) – Bipartite graph
set1 (set) – First partition node IDs
set2 (set) – Second partition node IDs
- add_hub_nodes(G, num_hubs, hub_degree, seed=None)[source]#
Add hub nodes to an existing graph.
- Parameters:
G (nx.Graph) – Input graph
num_hubs (int) – Number of hub nodes to add
hub_degree (int) – Degree of each hub node
seed (int, optional) – Random seed for reproducibility
- Return type:
Tuple[Graph,List[int]]- Returns:
G (nx.Graph) – Graph with added hubs
hub_nodes (list) – List of hub node IDs
- generate_graph_with_seeds_and_targets(n, num_seeds, num_targets, graph_type='barabasi_albert', seed=None, **kwargs)[source]#
Generate a random graph with designated seed and target nodes for embedding evaluation.
- Parameters:
n (int) – Total number of nodes
num_seeds (int) – Number of seed nodes
num_targets (int) – Number of target nodes
graph_type (str, default='barabasi_albert') – Type of graph: ‘erdos_renyi’, ‘barabasi_albert’, ‘watts_strogatz’, ‘powerlaw_cluster’, ‘modular’
seed (int, optional) – Random seed for reproducibility
**kwargs – Additional parameters for specific graph types
- Return type:
Tuple[Graph,List[int],List[int]]- Returns:
G (nx.Graph) – Generated graph
seeds (list) – List of seed node IDs
targets (list) – List of target node IDs
- get_graph_statistics(G)[source]#
Compute comprehensive statistics for a graph.
- Parameters:
G (nx.Graph) – Input graph
- Returns:
Dictionary of graph statistics
- Return type:
dict
- generate_comprehensive_dataset(n_instances=30, base_seed=42, n_nodes=200, save_dir=None)[source]#
Generate a comprehensive dataset of random graphs for embedding analysis.
This function generates multiple instances of each graph type with varying random seeds to capture natural parameter variations.
Graph types included: - Erdős-Rényi (random) - Barabási-Albert (scale-free) - Watts-Strogatz (small-world) - Powerlaw Cluster (scale-free with clustering) - Stochastic Block Model (modular/community structure) - Random Geometric (spatial networks) - Hierarchical (tree-like structure) - Core-Periphery (hub-spoke structure) - Bipartite Random (two-mode networks)
- Parameters:
n_instances (int, default=30) – Number of instances to generate for each graph type
base_seed (int, default=42) – Base random seed (each instance uses base_seed + instance_id)
n_nodes (int, default=200) – Target number of nodes for each graph
save_dir (str, optional) – If provided, save graphs to this directory
- Returns:
Dictionary mapping graph type names to lists of (graph, metadata) tuples
- Return type:
dict
Examples
>>> dataset = generate_comprehensive_dataset(n_instances=30, n_nodes=200) >>> print(f"Generated {sum(len(v) for v in dataset.values())} graphs") >>> print(f"Graph types: {list(dataset.keys())}")
- load_comprehensive_dataset(load_dir)[source]#
Load a previously saved comprehensive dataset.
- Parameters:
load_dir (str) – Directory containing saved graphs
- Returns:
Dictionary mapping graph type names to lists of (graph, metadata) tuples
- Return type:
dict
- generate_random_regular_expander_like(n, d, seed=None, make_connected=True, max_tries=25)[source]#
Generate a random d-regular graph. Random regular graphs are a practical expander-like family for QuVINE sweeps.
- Parameters:
n (int) – Number of nodes.
d (int) – Regular degree. Must satisfy 0 <= d < n and n*d even.
seed (int, optional) – Random seed.
make_connected (bool) – If True, retry until connected; if retries fail, connect components.
max_tries (int) – Number of random draws before bridge-connecting components.
- Return type:
Graph
- sweep_random_regular_expander_like(n_values=(1000, 2000, 5000), d_values=(3, 6, 10, 20), seeds=(0, 1, 2), make_connected=True)[source]#
Generate sweep of random regular graphs.
- Return type:
List[Tuple[Graph,Dict[str,Any]]]
- generate_heterophilic_sbm(n, n_blocks, target_avg_degree, out_in_ratio, seed=None, make_connected=True, selfloops=False)[source]#
Generate an SBM where p_out / p_in is controlled. For out_in_ratio > 1, between-block edges are more likely than within-block edges, producing a heterophilic/disassortative block structure.
- Return type:
Tuple[Graph,Dict[int,int]]
- sweep_heterophilic_sbm(n_values=(1000, 2000, 5000), n_blocks_values=(2, 4, 8), avg_degree_values=(4, 8, 16), out_in_ratios=(1.0, 2.0, 4.0, 8.0), seeds=(0, 1, 2), make_connected=True)[source]#
Generate sweep of heterophilic SBM graphs.
- Return type:
List[Tuple[Graph,Dict[str,Any]]]
- generate_degree_corrected_sbm(n, n_blocks, target_avg_degree, out_in_ratio=0.1, degree_distribution='powerlaw', gamma=2.5, lognormal_sigma=1.0, seed=None, max_prob=0.95, make_connected=True)[source]#
Generate a degree-corrected SBM.
Edge probabilities are:
P_ij = scale * R_{b_i,b_j} * theta_i * theta_j
where theta values are normalized to have mean 1 within each block.
- Return type:
Tuple[Graph,Dict[int,int]]
- sweep_degree_corrected_sbm(n_values=(1000, 2000, 5000), n_blocks_values=(4, 8), avg_degree_values=(4, 8, 16), out_in_ratios=(0.1, 0.5, 1.0, 2.0, 4.0), degree_distributions=('powerlaw', 'lognormal'), seeds=(0, 1, 2), make_connected=True)[source]#
Generate sweep of degree-corrected SBM graphs.
- Return type:
List[Tuple[Graph,Dict[str,Any]]]
- generate_grid_torus_lattice(n=None, side_lengths=None, dim=2, periodic=True, add_diagonals=False, seed=None)[source]#
Generate a regular grid or torus lattice. If periodic=True, this is a torus.
- Parameters:
n (int, optional) – Approximate target number of nodes. Ignored if side_lengths is provided.
side_lengths (sequence of int, optional) – Grid shape, e.g. (50, 50) for 2500 nodes.
dim (int) – Dimension used when side_lengths is not provided.
periodic (bool) – If True, use periodic boundary conditions.
add_diagonals (bool) – For 2D grids only, add diagonal lattice edges to increase local cycles.
- Return type:
Graph
- sweep_grid_torus_lattice(n_values=(1024, 2025, 4900), dims=(2,), periodic_values=(False, True), diagonal_values=(False, True), seeds=(0,))[source]#
Generate sweep of grid/torus lattice graphs.
- Return type:
List[Tuple[Graph,Dict[str,Any]]]
- sample_degree_sequence(n, distribution, target_avg_degree, seed=None, gamma=2.5, lognormal_sigma=1.0, max_degree_fraction=0.1)[source]#
Sample a degree sequence and rescale it to target average degree.
- Return type:
ndarray
- generate_configuration_model_graph(n, distribution='powerlaw', target_avg_degree=8, seed=None, gamma=2.5, lognormal_sigma=1.0, max_degree_fraction=0.1, make_connected=True)[source]#
Generate a simple graph from a configuration model with power-law, log-normal, or Poisson degree sequence.
- Return type:
Graph
- sweep_configuration_model_graphs(n_values=(1000, 2000, 5000), distributions=('powerlaw', 'lognormal'), avg_degree_values=(4, 8, 16), gamma_values=(2.2, 2.5, 3.0), lognormal_sigma_values=(0.75, 1.0, 1.5), seeds=(0, 1, 2), make_connected=True)[source]#
Generate sweep of configuration model graphs.
- Return type:
List[Tuple[Graph,Dict[str,Any]]]