or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-algorithms.mdanalysis.mdcentrality.mdcore-classes.mdgenerators.mdindex.mdlayouts.mdshortest-paths.mdtraversal.mdvisualization.md

generators.mddocs/

0

# Graph Generators

1

2

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.

3

4

## Capabilities

5

6

### Classic Graph Structures

7

8

Standard graph topologies commonly used in graph theory and applications.

9

10

```python { .api }

11

def cycle_graph(num_nodes: int, weights = None, multigraph: bool = True):

12

"""

13

Generate undirected cycle graph (ring topology).

14

15

Parameters:

16

- num_nodes (int): Number of nodes in cycle

17

- weights (list, optional): Node weights, default uses node indices

18

- multigraph (bool): Allow parallel edges

19

20

Returns:

21

PyGraph: Cycle graph with nodes connected in ring

22

"""

23

24

def directed_cycle_graph(num_nodes: int, weights = None, multigraph: bool = True):

25

"""

26

Generate directed cycle graph.

27

28

Parameters:

29

- num_nodes (int): Number of nodes in cycle

30

- weights (list, optional): Node weights

31

- multigraph (bool): Allow parallel edges

32

33

Returns:

34

PyDiGraph: Directed cycle graph

35

"""

36

37

def path_graph(num_nodes: int, weights = None, multigraph: bool = True):

38

"""

39

Generate undirected path graph (linear chain).

40

41

Parameters:

42

- num_nodes (int): Number of nodes in path

43

- weights (list, optional): Node weights

44

- multigraph (bool): Allow parallel edges

45

46

Returns:

47

PyGraph: Path graph with linear connectivity

48

"""

49

50

def directed_path_graph(num_nodes: int, weights = None, multigraph: bool = True):

51

"""

52

Generate directed path graph.

53

54

Parameters:

55

- num_nodes (int): Number of nodes in path

56

- weights (list, optional): Node weights

57

- multigraph (bool): Allow parallel edges

58

59

Returns:

60

PyDiGraph: Directed path graph

61

"""

62

63

def star_graph(num_nodes: int, weights = None, multigraph: bool = True):

64

"""

65

Generate undirected star graph (hub-and-spoke topology).

66

67

Parameters:

68

- num_nodes (int): Total number of nodes (including central hub)

69

- weights (list, optional): Node weights

70

- multigraph (bool): Allow parallel edges

71

72

Returns:

73

PyGraph: Star graph with central hub connected to all other nodes

74

"""

75

76

def directed_star_graph(num_nodes: int, weights = None, multigraph: bool = True):

77

"""

78

Generate directed star graph.

79

80

Parameters:

81

- num_nodes (int): Total number of nodes

82

- weights (list, optional): Node weights

83

- multigraph (bool): Allow parallel edges

84

85

Returns:

86

PyDiGraph: Directed star graph with hub as source

87

"""

88

89

def complete_graph(num_nodes: int, weights = None, multigraph: bool = True):

90

"""

91

Generate complete graph (all nodes connected to all others).

92

93

Parameters:

94

- num_nodes (int): Number of nodes

95

- weights (list, optional): Node weights

96

- multigraph (bool): Allow parallel edges

97

98

Returns:

99

PyGraph: Complete graph with all possible edges

100

"""

101

102

def directed_complete_graph(num_nodes: int, weights = None, multigraph: bool = True):

103

"""

104

Generate directed complete graph.

105

106

Parameters:

107

- num_nodes (int): Number of nodes

108

- weights (list, optional): Node weights

109

- multigraph (bool): Allow parallel edges

110

111

Returns:

112

PyDiGraph: Directed complete graph

113

"""

114

115

def empty_graph(num_nodes: int, weights = None, multigraph: bool = True):

116

"""

117

Generate empty graph (nodes only, no edges).

118

119

Parameters:

120

- num_nodes (int): Number of isolated nodes

121

- weights (list, optional): Node weights

122

- multigraph (bool): Allow parallel edges

123

124

Returns:

125

PyGraph: Graph with nodes but no edges

126

"""

127

128

def directed_empty_graph(num_nodes: int, weights = None, multigraph: bool = True):

129

"""

130

Generate directed empty graph.

131

132

Parameters:

133

- num_nodes (int): Number of isolated nodes

134

- weights (list, optional): Node weights

135

- multigraph (bool): Allow parallel edges

136

137

Returns:

138

PyDiGraph: Directed graph with nodes but no edges

139

"""

140

```

141

142

### Grid and Lattice Graphs

143

144

Regular grid structures and lattice topologies for spatial and geometric applications.

145

146

```python { .api }

147

def grid_graph(rows: int, cols: int = None, weights = None, multigraph: bool = True):

148

"""

149

Generate 2D grid graph with rectangular topology.

150

151

Parameters:

152

- rows (int): Number of rows in grid

153

- cols (int, optional): Number of columns, defaults to rows (square grid)

154

- weights (list, optional): Node weights

155

- multigraph (bool): Allow parallel edges

156

157

Returns:

158

PyGraph: 2D grid graph with nodes at lattice points

159

"""

160

161

def directed_grid_graph(rows: int, cols: int = None, weights = None, multigraph: bool = True):

162

"""

163

Generate directed 2D grid graph.

164

165

Parameters:

166

- rows (int): Number of rows

167

- cols (int, optional): Number of columns

168

- weights (list, optional): Node weights

169

- multigraph (bool): Allow parallel edges

170

171

Returns:

172

PyDiGraph: Directed 2D grid graph

173

"""

174

175

def mesh_graph(num_nodes: int, multigraph: bool = True):

176

"""

177

Generate mesh graph (complete graph topology).

178

179

Parameters:

180

- num_nodes (int): Number of nodes in mesh

181

- multigraph (bool): Allow parallel edges

182

183

Returns:

184

PyGraph: Fully connected mesh topology

185

"""

186

187

def directed_mesh_graph(num_nodes: int, multigraph: bool = True):

188

"""

189

Generate directed mesh graph.

190

191

Parameters:

192

- num_nodes (int): Number of nodes

193

- multigraph (bool): Allow parallel edges

194

195

Returns:

196

PyDiGraph: Directed mesh graph

197

"""

198

199

def hexagonal_lattice_graph(rows: int, cols: int, multigraph: bool = True, with_positions: bool = False, periodic: bool = False):

200

"""

201

Generate hexagonal lattice graph.

202

203

Parameters:

204

- rows (int): Number of rows in lattice

205

- cols (int): Number of columns in lattice

206

- multigraph (bool): Allow parallel edges

207

- with_positions (bool): Include node position data

208

- periodic (bool): Create periodic boundary conditions

209

210

Returns:

211

PyGraph: Hexagonal lattice with 6-neighbor connectivity

212

"""

213

214

def heavy_square_graph(d: int, multigraph: bool = True):

215

"""

216

Generate heavy square lattice graph.

217

218

Parameters:

219

- d (int): Lattice dimension parameter

220

- multigraph (bool): Allow parallel edges

221

222

Returns:

223

PyGraph: Heavy square lattice topology

224

"""

225

226

def heavy_hex_graph(d: int, multigraph: bool = True):

227

"""

228

Generate heavy hexagonal lattice graph.

229

230

Parameters:

231

- d (int): Lattice dimension parameter

232

- multigraph (bool): Allow parallel edges

233

234

Returns:

235

PyGraph: Heavy hexagonal lattice topology

236

"""

237

238

def directed_heavy_square_graph(d: int, multigraph: bool = True):

239

"""

240

Generate directed heavy square lattice graph.

241

242

Parameters:

243

- d (int): Lattice dimension parameter

244

- multigraph (bool): Allow parallel edges

245

246

Returns:

247

PyDiGraph: Directed heavy square lattice topology

248

"""

249

250

def directed_heavy_hex_graph(d: int, multigraph: bool = True):

251

"""

252

Generate directed heavy hexagonal lattice graph.

253

254

Parameters:

255

- d (int): Lattice dimension parameter

256

- multigraph (bool): Allow parallel edges

257

258

Returns:

259

PyDiGraph: Directed heavy hexagonal lattice topology

260

"""

261

262

def directed_hexagonal_lattice_graph(rows: int, cols: int, multigraph: bool = True, with_positions: bool = False, periodic: bool = False):

263

"""

264

Generate directed hexagonal lattice graph.

265

266

Parameters:

267

- rows (int): Number of rows in lattice

268

- cols (int): Number of columns in lattice

269

- multigraph (bool): Allow parallel edges

270

- with_positions (bool): Include node position data

271

- periodic (bool): Create periodic boundary conditions

272

273

Returns:

274

PyDiGraph: Directed hexagonal lattice with 6-neighbor connectivity

275

"""

276

```

277

278

### Tree Structures

279

280

Hierarchical tree topologies for representing structured data and algorithms.

281

282

```python { .api }

283

def binomial_tree_graph(order: int, multigraph: bool = True):

284

"""

285

Generate binomial tree graph.

286

287

Parameters:

288

- order (int): Order of binomial tree

289

- multigraph (bool): Allow parallel edges

290

291

Returns:

292

PyGraph: Binomial tree with specified order

293

"""

294

295

def directed_binomial_tree_graph(order: int, multigraph: bool = True):

296

"""

297

Generate directed binomial tree graph.

298

299

Parameters:

300

- order (int): Order of binomial tree

301

- multigraph (bool): Allow parallel edges

302

303

Returns:

304

PyDiGraph: Directed binomial tree with specified order

305

"""

306

307

def full_rary_tree(branching_factor: int, num_levels: int, weights = None, multigraph: bool = True):

308

"""

309

Generate complete r-ary tree.

310

311

Parameters:

312

- branching_factor (int): Number of children per internal node

313

- num_levels (int): Number of levels in tree (including root)

314

- weights (list, optional): Node weights

315

- multigraph (bool): Allow parallel edges

316

317

Returns:

318

PyGraph: Complete r-ary tree structure

319

"""

320

```

321

322

### Special Graph Topologies

323

324

Unique graph structures with specific properties and applications.

325

326

```python { .api }

327

def lollipop_graph(num_complete: int, num_path: int, weights = None, multigraph: bool = True):

328

"""

329

Generate lollipop graph (complete graph connected to path).

330

331

Parameters:

332

- num_complete (int): Size of complete graph component

333

- num_path (int): Length of path component

334

- weights (list, optional): Node weights

335

- multigraph (bool): Allow parallel edges

336

337

Returns:

338

PyGraph: Lollipop graph topology

339

"""

340

341

def barbell_graph(num_complete: int, num_path: int, weights = None, multigraph: bool = True):

342

"""

343

Generate barbell graph (two complete graphs connected by path).

344

345

Parameters:

346

- num_complete (int): Size of each complete graph component

347

- num_path (int): Length of connecting path

348

- weights (list, optional): Node weights

349

- multigraph (bool): Allow parallel edges

350

351

Returns:

352

PyGraph: Barbell graph topology

353

"""

354

355

def generalized_petersen_graph(n: int, k: int, multigraph: bool = True):

356

"""

357

Generate generalized Petersen graph.

358

359

Parameters:

360

- n (int): Number of vertices in each ring

361

- k (int): Connection parameter

362

- multigraph (bool): Allow parallel edges

363

364

Returns:

365

PyGraph: Generalized Petersen graph

366

"""

367

368

def dorogovtsev_goltsev_mendes_graph(n: int, multigraph: bool = True):

369

"""

370

Generate Dorogovtsev-Goltsev-Mendes fractal graph.

371

372

Parameters:

373

- n (int): Number of iterations for fractal construction

374

- multigraph (bool): Allow parallel edges

375

376

Returns:

377

PyGraph: DGM fractal graph structure

378

"""

379

380

def karate_club_graph(multigraph: bool = True):

381

"""

382

Generate Zachary's karate club graph (classic social network).

383

384

Parameters:

385

- multigraph (bool): Allow parallel edges

386

387

Returns:

388

PyGraph: Karate club social network with 34 nodes

389

"""

390

```

391

392

### Random Graph Models

393

394

Probabilistic graph generation models for simulation and analysis.

395

396

```python { .api }

397

def directed_gnm_random_graph(num_nodes: int, num_edges: int, seed: int = None, multigraph: bool = True):

398

"""

399

Generate directed G(n,m) random graph with fixed edge count.

400

401

Parameters:

402

- num_nodes (int): Number of nodes

403

- num_edges (int): Number of edges to add randomly

404

- seed (int, optional): Random seed for reproducibility

405

- multigraph (bool): Allow parallel edges

406

407

Returns:

408

PyDiGraph: Random directed graph with specified edge count

409

"""

410

411

def undirected_gnm_random_graph(num_nodes: int, num_edges: int, seed: int = None, multigraph: bool = True):

412

"""

413

Generate undirected G(n,m) random graph with fixed edge count.

414

415

Parameters:

416

- num_nodes (int): Number of nodes

417

- num_edges (int): Number of edges to add randomly

418

- seed (int, optional): Random seed

419

- multigraph (bool): Allow parallel edges

420

421

Returns:

422

PyGraph: Random undirected graph with specified edge count

423

"""

424

425

def directed_gnp_random_graph(num_nodes: int, probability: float, seed: int = None, multigraph: bool = True):

426

"""

427

Generate directed G(n,p) random graph with edge probability.

428

429

Parameters:

430

- num_nodes (int): Number of nodes

431

- probability (float): Probability of edge between any two nodes (0.0 to 1.0)

432

- seed (int, optional): Random seed

433

- multigraph (bool): Allow parallel edges

434

435

Returns:

436

PyDiGraph: Random directed graph with probabilistic edges

437

"""

438

439

def undirected_gnp_random_graph(num_nodes: int, probability: float, seed: int = None, multigraph: bool = True):

440

"""

441

Generate undirected G(n,p) random graph with edge probability.

442

443

Parameters:

444

- num_nodes (int): Number of nodes

445

- probability (float): Edge probability (0.0 to 1.0)

446

- seed (int, optional): Random seed

447

- multigraph (bool): Allow parallel edges

448

449

Returns:

450

PyGraph: Random undirected graph with probabilistic edges

451

"""

452

453

def barabasi_albert_graph(n: int, m: int, seed: int = None, initial_graph = None, multigraph: bool = True):

454

"""

455

Generate Barabási-Albert preferential attachment graph.

456

457

Creates scale-free network where new nodes preferentially

458

attach to existing nodes with higher degree.

459

460

Parameters:

461

- n (int): Final number of nodes

462

- m (int): Number of edges added per new node

463

- seed (int, optional): Random seed

464

- initial_graph (PyGraph, optional): Starting graph structure

465

- multigraph (bool): Allow parallel edges

466

467

Returns:

468

PyGraph: Scale-free network with power-law degree distribution

469

"""

470

471

def directed_barabasi_albert_graph(n: int, m: int, seed: int = None, initial_graph = None, multigraph: bool = True):

472

"""

473

Generate directed Barabási-Albert preferential attachment graph.

474

475

Creates directed scale-free network where new nodes preferentially

476

attach to existing nodes with higher in-degree or out-degree.

477

478

Parameters:

479

- n (int): Final number of nodes

480

- m (int): Number of edges added per new node

481

- seed (int, optional): Random seed

482

- initial_graph (PyDiGraph, optional): Starting directed graph structure

483

- multigraph (bool): Allow parallel edges

484

485

Returns:

486

PyDiGraph: Directed scale-free network with power-law degree distribution

487

"""

488

489

def random_geometric_graph(num_nodes: int, radius: float, dim: int = 2, pos = None, p: float = 2, seed: int = None, multigraph: bool = True):

490

"""

491

Generate random geometric graph in d-dimensional space.

492

493

Nodes are placed randomly in unit cube and connected if

494

their distance is less than the specified radius.

495

496

Parameters:

497

- num_nodes (int): Number of nodes

498

- radius (float): Connection radius

499

- dim (int): Spatial dimension (default 2)

500

- pos (dict, optional): Predefined node positions

501

- p (float): Distance metric parameter (2 for Euclidean)

502

- seed (int, optional): Random seed

503

- multigraph (bool): Allow parallel edges

504

505

Returns:

506

PyGraph: Geometric graph with spatial connectivity

507

"""

508

509

def hyperbolic_random_graph(n: int, alpha: float, beta: float, gamma: float, seed: int = None, multigraph: bool = True):

510

"""

511

Generate hyperbolic random graph.

512

513

Creates graphs with specified clustering and degree distribution

514

properties using hyperbolic geometry.

515

516

Parameters:

517

- n (int): Number of nodes

518

- alpha (float): Power-law exponent for degree distribution

519

- beta (float): Clustering parameter

520

- gamma (float): Temperature parameter

521

- seed (int, optional): Random seed

522

- multigraph (bool): Allow parallel edges

523

524

Returns:

525

PyGraph: Hyperbolic random graph with tunable properties

526

"""

527

528

def directed_sbm_random_graph(num_nodes: int, block_sizes: list, edge_probs: list, seed: int = None, multigraph: bool = True):

529

"""

530

Generate directed stochastic block model (SBM) random graph.

531

532

Creates a directed graph using the stochastic block model where nodes

533

are divided into blocks (communities) and edge probabilities depend

534

on block membership. This model is useful for generating graphs with

535

community structure and varying connectivity patterns between groups.

536

537

Parameters:

538

- num_nodes (int): Total number of nodes

539

- block_sizes (list): List of block sizes, must sum to num_nodes

540

- edge_probs (list): 2D list/matrix of edge probabilities between blocks

541

- seed (int, optional): Random seed for reproducibility

542

- multigraph (bool): Allow parallel edges

543

544

Returns:

545

PyDiGraph: Directed stochastic block model graph with community structure

546

"""

547

```

548

549

## Usage Examples

550

551

### Basic Graph Generation

552

553

```python

554

import rustworkx.generators as rx_gen

555

556

# Generate classic structures

557

cycle = rx_gen.cycle_graph(6)

558

path = rx_gen.path_graph(10)

559

star = rx_gen.star_graph(7) # 1 hub + 6 spokes

560

complete = rx_gen.complete_graph(5)

561

562

print(f"Cycle nodes: {cycle.num_nodes()}, edges: {cycle.num_edges()}")

563

print(f"Complete graph edges: {complete.num_edges()}") # Should be n(n-1)/2 = 10

564

```

565

566

### Grid and Lattice Generation

567

568

```python

569

# Create 2D grids for spatial algorithms

570

square_grid = rx_gen.grid_graph(4, 4) # 4x4 grid

571

rectangular_grid = rx_gen.grid_graph(3, 5) # 3x5 grid

572

573

# Hexagonal lattice for certain applications

574

hex_lattice = rx_gen.hexagonal_lattice_graph(

575

rows=5, cols=5,

576

with_positions=True # Include coordinate data

577

)

578

579

print(f"4x4 grid: {square_grid.num_nodes()} nodes, {square_grid.num_edges()} edges")

580

print(f"Hex lattice: {hex_lattice.num_nodes()} nodes")

581

```

582

583

### Tree Structure Generation

584

585

```python

586

# Generate hierarchical structures

587

binary_tree = rx_gen.full_rary_tree(

588

branching_factor=2,

589

num_levels=4 # 4 levels: root + 3 more

590

)

591

592

ternary_tree = rx_gen.full_rary_tree(

593

branching_factor=3,

594

num_levels=3

595

)

596

597

binomial = rx_gen.binomial_tree_graph(order=3)

598

599

print(f"Binary tree: {binary_tree.num_nodes()} nodes")

600

print(f"Ternary tree: {ternary_tree.num_nodes()} nodes")

601

```

602

603

### Random Graph Generation

604

605

```python

606

import rustworkx as rx

607

608

# Erdős-Rényi random graphs

609

# G(n,m) model: fixed number of edges

610

gnm_graph = rx_gen.undirected_gnm_random_graph(

611

num_nodes=20,

612

num_edges=30,

613

seed=42 # For reproducibility

614

)

615

616

# G(n,p) model: probabilistic edges

617

gnp_graph = rx_gen.undirected_gnp_random_graph(

618

num_nodes=20,

619

probability=0.15,

620

seed=42

621

)

622

623

print(f"G(n,m): {gnm_graph.num_edges()} edges (should be exactly 30)")

624

print(f"G(n,p): {gnp_graph.num_edges()} edges (probabilistic)")

625

```

626

627

### Scale-Free Networks

628

629

```python

630

# Barabási-Albert preferential attachment

631

scale_free = rx_gen.barabasi_albert_graph(

632

n=100, # Final size

633

m=3, # Edges added per new node

634

seed=42

635

)

636

637

# Analyze degree distribution

638

degrees = [scale_free.degree(node) for node in scale_free.node_indices()]

639

max_degree = max(degrees)

640

avg_degree = sum(degrees) / len(degrees)

641

642

print(f"Scale-free network: max degree {max_degree}, avg degree {avg_degree:.2f}")

643

```

644

645

### Geometric Graphs

646

647

```python

648

# Random geometric graph

649

geometric = rx_gen.random_geometric_graph(

650

num_nodes=50,

651

radius=0.3, # Connection radius in unit square

652

dim=2, # 2D space

653

seed=42

654

)

655

656

# Hyperbolic random graph with specific properties

657

hyperbolic = rx_gen.hyperbolic_random_graph(

658

n=100,

659

alpha=2.5, # Power-law exponent

660

beta=0.8, # Clustering parameter

661

gamma=2.0, # Temperature

662

seed=42

663

)

664

665

print(f"Geometric graph: {geometric.num_edges()} edges")

666

print(f"Hyperbolic graph: {hyperbolic.num_edges()} edges")

667

```

668

669

### Special Structures

670

671

```python

672

# Create compound structures

673

lollipop = rx_gen.lollipop_graph(

674

num_complete=5, # Complete K5

675

num_path=3 # Path of length 3

676

)

677

678

barbell = rx_gen.barbell_graph(

679

num_complete=4, # Two K4 components

680

num_path=2 # Connected by path of length 2

681

)

682

683

# Famous graph datasets

684

karate = rx_gen.karate_club_graph()

685

686

print(f"Lollipop: {lollipop.num_nodes()} nodes, {lollipop.num_edges()} edges")

687

print(f"Karate club: {karate.num_nodes()} nodes, {karate.num_edges()} edges")

688

```

689

690

### Directed Graph Generation

691

692

```python

693

# Generate directed variants

694

directed_cycle = rx_gen.directed_cycle_graph(8)

695

directed_complete = rx_gen.directed_complete_graph(4)

696

directed_random = rx_gen.directed_gnp_random_graph(

697

num_nodes=15,

698

probability=0.2,

699

seed=42

700

)

701

702

# Check strong connectivity

703

is_strongly_connected = rx.is_strongly_connected(directed_cycle)

704

print(f"Directed cycle strongly connected: {is_strongly_connected}")

705

```

706

707

### Custom Weighted Graphs

708

709

```python

710

# Generate with custom node weights

711

node_weights = [f"Node_{i}" for i in range(10)]

712

weighted_cycle = rx_gen.cycle_graph(

713

num_nodes=10,

714

weights=node_weights

715

)

716

717

# Verify weights are applied

718

nodes_data = weighted_cycle.nodes()

719

print(f"Node weights: {nodes_data[:5]}") # First 5 nodes

720

721

# Generate empty graph and add custom edges

722

base_graph = rx_gen.empty_graph(5, weights=['A', 'B', 'C', 'D', 'E'])

723

base_graph.add_edges_from([

724

(0, 1, 1.5),

725

(1, 2, 2.3),

726

(2, 3, 0.8),

727

(3, 4, 3.1)

728

])

729

730

print(f"Custom graph: {base_graph.num_edges()} edges with weights")

731

```