-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathgenerators.rs
More file actions
624 lines (574 loc) · 19.6 KB
/
generators.rs
File metadata and controls
624 lines (574 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
/*!
# Graph Generators
Graph generators for classic graphs:
Erdős–Rényi, complete, bipartite, star, cycle, Watts–Strogatz small-world, and
Barabási–Albert scale-free graphs. Each generator is generic over the graph type
(directed or undirected) using the `GraphConstructor` trait. Node attributes are fixed
to `u32` and edge weights to `f32`.
Most generators use a seeded random number generator for reproducibility. In case of
invalid parameters (e.g. probability out of [0, 1] or insufficient nodes), functions
return a `Result` with a relevant error from `graphina::core::error::GraphinaError`.
# Examples
Generating an Erdős–Rényi graph:
```rust
use graphina::core::generators::erdos_renyi_graph;
use graphina::core::types::Directed;
let graph = erdos_renyi_graph::<Directed>(100, 0.1, 42)
.expect("Failed to generate Erdős–Rényi graph");
```
Generating a Watts–Strogatz graph:
```rust
use graphina::core::generators::watts_strogatz_graph;
use graphina::core::types::Undirected;
let ws = watts_strogatz_graph::<Undirected>(100, 6, 0.3, 42)
.expect("Failed to generate Watts–Strogatz graph");
```
*/
use crate::core::error::GraphinaError;
use crate::core::types::{BaseGraph, GraphConstructor};
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
/// Generates an Erdős–Rényi graph.
///
/// # Arguments
///
/// * `n` - The number of nodes (must be > 0).
/// * `p` - The probability of edge creation (must be in [0.0, 1.0]).
/// * `seed` - The seed for the random number generator.
///
/// # Type Parameters
///
/// * `Ty` - The graph type (directed or undirected) implementing `GraphConstructor<u32, f32>`.
///
/// # Returns
///
/// * `Result<BaseGraph<u32, f32, Ty>, GraphinaError>` - The generated graph, or an error if parameters are invalid.
pub fn erdos_renyi_graph<Ty: GraphConstructor<u32, f32>>(
n: usize,
p: f64,
seed: u64,
) -> Result<BaseGraph<u32, f32, Ty>, GraphinaError> {
if n == 0 {
return Err(GraphinaError::InvalidArgument(
"Number of nodes must be greater than zero.".into(),
));
}
if !(0.0..=1.0).contains(&p) {
return Err(GraphinaError::InvalidArgument(
"Probability p must be in the range [0.0, 1.0].".into(),
));
}
let mut graph = BaseGraph::<u32, f32, Ty>::new();
let mut nodes = Vec::with_capacity(n);
for i in 0..n {
nodes.push(graph.add_node(i as u32));
}
let mut rng = StdRng::seed_from_u64(seed);
if <Ty as GraphConstructor<u32, f32>>::is_directed() {
for i in 0..n {
for j in 0..n {
if i != j && rng.random_bool(p) {
graph.add_edge(nodes[i], nodes[j], 1.0);
}
}
}
} else {
for i in 0..n {
for j in (i + 1)..n {
if rng.random_bool(p) {
graph.add_edge(nodes[i], nodes[j], 1.0);
}
}
}
}
Ok(graph)
}
/// Generates a complete graph.
///
/// # Arguments
///
/// * `n` - The number of nodes (must be > 0).
///
/// # Type Parameters
///
/// * `Ty` - The graph type implementing `GraphConstructor<u32, f32>`.
///
/// # Returns
///
/// * `Result<BaseGraph<u32, f32, Ty>, GraphinaError>` - The complete graph.
pub fn complete_graph<Ty: GraphConstructor<u32, f32>>(
n: usize,
) -> Result<BaseGraph<u32, f32, Ty>, GraphinaError> {
if n == 0 {
return Err(GraphinaError::InvalidArgument(
"Number of nodes must be greater than zero.".into(),
));
}
let mut graph = BaseGraph::<u32, f32, Ty>::new();
let mut nodes = Vec::with_capacity(n);
for i in 0..n {
nodes.push(graph.add_node(i as u32));
}
if <Ty as GraphConstructor<u32, f32>>::is_directed() {
for i in 0..n {
for j in 0..n {
if i != j {
graph.add_edge(nodes[i], nodes[j], 1.0);
}
}
}
} else {
for i in 0..n {
for j in (i + 1)..n {
graph.add_edge(nodes[i], nodes[j], 1.0);
}
}
}
Ok(graph)
}
/// Generates a bipartite graph.
///
/// # Arguments
///
/// * `n1` - The number of nodes in the first set (must be > 0).
/// * `n2` - The number of nodes in the second set (must be > 0).
/// * `p` - The probability of edge creation (must be in [0.0, 1.0]).
/// * `seed` - The seed for the random number generator.
///
/// # Type Parameters
///
/// * `Ty` - The graph type implementing `GraphConstructor<u32, f32>`.
///
/// # Returns
///
/// * `Result<BaseGraph<u32, f32, Ty>, GraphinaError>` - The generated bipartite graph.
pub fn bipartite_graph<Ty: GraphConstructor<u32, f32>>(
n1: usize,
n2: usize,
p: f64,
seed: u64,
) -> Result<BaseGraph<u32, f32, Ty>, GraphinaError> {
if n1 == 0 || n2 == 0 {
return Err(GraphinaError::InvalidArgument(
"Both partitions must have at least one node.".into(),
));
}
if !(0.0..=1.0).contains(&p) {
return Err(GraphinaError::InvalidArgument(
"Probability p must be in the range [0.0, 1.0].".into(),
));
}
let mut graph = BaseGraph::<u32, f32, Ty>::new();
let mut group1 = Vec::with_capacity(n1);
let mut group2 = Vec::with_capacity(n2);
for i in 0..n1 {
group1.push(graph.add_node(i as u32));
}
for j in 0..n2 {
group2.push(graph.add_node((n1 + j) as u32));
}
let mut rng = StdRng::seed_from_u64(seed);
for &u in &group1 {
for &v in &group2 {
if rng.random_bool(p) {
graph.add_edge(u, v, 1.0);
}
}
}
Ok(graph)
}
/// Generates a star graph.
///
/// # Arguments
///
/// * `n` - The total number of nodes (must be > 0).
///
/// # Type Parameters
///
/// * `Ty` - The graph type implementing `GraphConstructor<u32, f32>`.
///
/// # Returns
///
/// * `Result<BaseGraph<u32, f32, Ty>, GraphinaError>` - The generated star graph.
pub fn star_graph<Ty: GraphConstructor<u32, f32>>(
n: usize,
) -> Result<BaseGraph<u32, f32, Ty>, GraphinaError> {
let mut graph = BaseGraph::<u32, f32, Ty>::new();
if n == 0 {
return Err(GraphinaError::InvalidArgument(
"Star graph must have at least one node.".into(),
));
}
let center = graph.add_node(0);
for i in 1..n {
let node = graph.add_node(i as u32);
graph.add_edge(center, node, 1.0);
}
Ok(graph)
}
/// Generates a cycle graph.
///
/// # Arguments
///
/// * `n` - The number of nodes (must be > 0).
///
/// # Type Parameters
///
/// * `Ty` - The graph type implementing `GraphConstructor<u32, f32>`.
///
/// # Returns
///
/// * `Result<BaseGraph<u32, f32, Ty>, GraphinaError>` - The generated cycle graph.
pub fn cycle_graph<Ty: GraphConstructor<u32, f32>>(
n: usize,
) -> Result<BaseGraph<u32, f32, Ty>, GraphinaError> {
if n < 3 {
return Err(GraphinaError::InvalidArgument(
"Cycle graph must have at least three nodes.".into(),
));
}
let mut graph = BaseGraph::<u32, f32, Ty>::new();
let mut nodes = Vec::with_capacity(n);
for i in 0..n {
nodes.push(graph.add_node(i as u32));
}
for i in 0..n {
let j = (i + 1) % n;
graph.add_edge(nodes[i], nodes[j], 1.0);
}
Ok(graph)
}
/// Generates a Watts–Strogatz small-world graph.
///
/// # Arguments
///
/// * `n` - The number of nodes (must be > 0).
/// * `k` - Each node is joined with its `k` nearest neighbors in a ring topology (must be even and less than n).
/// * `beta` - The probability of rewiring each edge (must be in [0.0, 1.0]).
/// * `seed` - The seed for the random number generator.
///
/// # Type Parameters
///
/// * `Ty` - The graph type implementing `GraphConstructor<u32, f32>`. This generator is typically used with undirected graphs.
///
/// # Returns
///
/// * `Result<BaseGraph<u32, f32, Ty>, GraphinaError>` - The generated Watts–Strogatz graph.
///
/// # Notes
///
/// In the rewiring phase, each eligible edge is removed with probability `beta` and replaced by a new edge
/// from the source node to a randomly chosen target (avoiding self-loops). This implementation uses the public
/// API method `find_edge` to locate and remove an existing edge.
pub fn watts_strogatz_graph<Ty: GraphConstructor<u32, f32>>(
n: usize,
k: usize,
beta: f64,
seed: u64,
) -> Result<BaseGraph<u32, f32, Ty>, GraphinaError> {
if n == 0 {
return Err(GraphinaError::InvalidArgument(
"Number of nodes must be greater than zero.".into(),
));
}
if k % 2 != 0 || k >= n {
return Err(GraphinaError::InvalidArgument(
"k must be even and less than n.".into(),
));
}
if !(0.0..=1.0).contains(&beta) {
return Err(GraphinaError::InvalidArgument(
"Beta must be in the range [0.0, 1.0].".into(),
));
}
let mut graph = BaseGraph::<u32, f32, Ty>::new();
let mut nodes = Vec::with_capacity(n);
for i in 0..n {
nodes.push(graph.add_node(i as u32));
}
let mut rng = StdRng::seed_from_u64(seed);
let half_k = k / 2;
// Create ring lattice.
for i in 0..n {
for j in 1..=half_k {
let neighbor = (i + j) % n;
graph.add_edge(nodes[i], nodes[neighbor], 1.0);
}
}
// Rewire edges: for each edge in the original lattice, with probability beta, remove it and add a new edge.
for i in 0..n {
for j in 1..=half_k {
if rng.random_bool(beta) {
let neighbor = (i + j) % n;
// Use the public API method `find_edge` to locate the edge.
if let Some(eid) = graph.find_edge(nodes[i], nodes[neighbor]) {
let _ = graph.remove_edge(eid);
// Choose a new target at random (avoiding self-loop and existing edges).
let max_attempts = n * 2; // Prevent infinite loop
let mut attempts = 0;
let mut found_valid_target = false;
let new_target = loop {
let target = rng.random_range(0..n);
attempts += 1;
// Check: not self-loop, not the original neighbor, and edge doesn't already exist (in either direction for undirected graphs)
let edge_exists = graph.find_edge(nodes[i], nodes[target]).is_some()
|| graph.find_edge(nodes[target], nodes[i]).is_some();
if target != i && target != neighbor && !edge_exists {
found_valid_target = true;
break target;
}
// Fallback: if we've tried many times, skip this rewiring
if attempts >= max_attempts {
break neighbor; // Use original neighbor as fallback
}
};
if found_valid_target {
graph.add_edge(nodes[i], nodes[new_target], 1.0);
} else {
// Re-add the original edge if rewiring failed
graph.add_edge(nodes[i], nodes[neighbor], 1.0);
}
}
}
}
}
Ok(graph)
}
/// Generates a Barabási–Albert scale-free graph.
///
/// # Arguments
///
/// * `n` - The total number of nodes (must be >= m).
/// * `m` - The number of edges to attach from a new node to existing nodes (must be > 0).
/// * `seed` - The seed for the random number generator.
///
/// # Type Parameters
///
/// * `Ty` - The graph type implementing `GraphConstructor<u32, f32>`. Typically used with undirected graphs.
///
/// # Returns
///
/// * `Result<BaseGraph<u32, f32, Ty>, GraphinaError>` - The generated Barabási–Albert graph.
///
/// # Notes
///
/// The algorithm starts with a complete graph of m nodes, then each new node attaches to m existing nodes
/// with probability proportional to their degree (preferential attachment). This implementation uses a simple
/// linear scan for degree selection and may be less efficient for very large graphs.
pub fn barabasi_albert_graph<Ty: GraphConstructor<u32, f32>>(
n: usize,
m: usize,
seed: u64,
) -> Result<BaseGraph<u32, f32, Ty>, GraphinaError> {
if m == 0 || n < m {
return Err(GraphinaError::InvalidArgument(
"n must be at least m and m must be > 0.".into(),
));
}
let mut graph = BaseGraph::<u32, f32, Ty>::new();
// Start with a complete graph of m nodes.
let mut nodes = Vec::with_capacity(n);
for i in 0..m {
nodes.push(graph.add_node(i as u32));
}
for i in 0..m {
for j in (i + 1)..m {
graph.add_edge(nodes[i], nodes[j], 1.0);
}
}
let mut rng = StdRng::seed_from_u64(seed);
// Preferential attachment for remaining nodes.
for i in m..n {
let new_node = graph.add_node(i as u32);
// Attach to m existing nodes, sampling without replacement and with guard rails
let mut attached = 0usize;
let mut chosen_indices: std::collections::HashSet<usize> = std::collections::HashSet::new();
let max_attempts = nodes.len().saturating_mul(10).max(m * 5).max(50);
let mut attempts = 0usize;
while attached < m && chosen_indices.len() < nodes.len() {
attempts += 1;
// Compute a fresh total degree for weighted sampling
let current_total_degree: usize =
nodes.iter().map(|&u| graph.degree(u).unwrap_or(0)).sum();
// Fallback path if degrees are all zero (e.g., degenerate cases)
let candidate_idx = if current_total_degree == 0 {
rng.random_range(0..nodes.len())
} else {
let r = rng.random_range(0..current_total_degree);
let mut cumulative = 0usize;
let mut idx = 0usize;
for (j, &u) in nodes.iter().enumerate() {
cumulative += graph.degree(u).unwrap_or(0);
if r < cumulative {
idx = j;
break;
}
}
idx
};
if !chosen_indices.insert(candidate_idx) {
// already picked in this round; try again
if attempts >= max_attempts {
break;
}
continue;
}
let target = nodes[candidate_idx];
if graph.find_edge(new_node, target).is_none() {
graph.add_edge(new_node, target, 1.0);
attached += 1;
}
if attempts >= max_attempts {
break;
}
}
// If we failed to reach m attachments due to unlucky sampling, connect greedily to remaining nodes
if attached < m {
for (idx, &u) in nodes.iter().enumerate() {
if attached >= m {
break;
}
if chosen_indices.contains(&idx) {
continue;
}
if graph.find_edge(new_node, u).is_none() {
graph.add_edge(new_node, u, 1.0);
attached += 1;
}
}
}
nodes.push(new_node);
}
Ok(graph)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::types::{Directed, Undirected};
#[test]
fn test_erdos_renyi_directed() {
let graph = erdos_renyi_graph::<Directed>(3, 1.0, 42)
.expect("Failed to generate directed Erdős–Rényi graph");
assert_eq!(graph.node_count(), 3);
assert_eq!(graph.edge_count(), 6);
}
#[test]
fn test_erdos_renyi_undirected() {
let graph = erdos_renyi_graph::<Undirected>(3, 1.0, 42)
.expect("Failed to generate undirected Erdős–Rényi graph");
assert_eq!(graph.node_count(), 3);
assert_eq!(graph.edge_count(), 3);
}
#[test]
fn test_complete_graph_directed() {
let graph =
complete_graph::<Directed>(4).expect("Failed to generate directed complete graph");
assert_eq!(graph.node_count(), 4);
assert_eq!(graph.edge_count(), 12);
}
#[test]
fn test_complete_graph_undirected() {
let graph =
complete_graph::<Undirected>(4).expect("Failed to generate undirected complete graph");
assert_eq!(graph.node_count(), 4);
assert_eq!(graph.edge_count(), 6);
}
#[test]
fn test_bipartite_graph() {
let graph = bipartite_graph::<Undirected>(3, 2, 1.0, 42)
.expect("Failed to generate bipartite graph");
assert_eq!(graph.node_count(), 5);
assert_eq!(graph.edge_count(), 6);
}
#[test]
fn test_star_graph() {
let graph = star_graph::<Undirected>(5).expect("Failed to generate star graph");
assert_eq!(graph.node_count(), 5);
assert_eq!(graph.edge_count(), 4);
}
#[test]
fn test_cycle_graph() {
let graph = cycle_graph::<Undirected>(5).expect("Failed to generate cycle graph");
assert_eq!(graph.node_count(), 5);
assert_eq!(graph.edge_count(), 5);
}
#[test]
fn test_cycle_graph_invalid_n() {
assert!(cycle_graph::<Undirected>(0).is_err());
assert!(cycle_graph::<Undirected>(1).is_err());
assert!(cycle_graph::<Undirected>(2).is_err());
}
#[test]
fn test_watts_strogatz_graph() {
let n = 10;
let k = 4;
let beta = 0.5;
let seed = 42;
let graph = watts_strogatz_graph::<Undirected>(n, k, beta, seed)
.expect("Failed to generate Watts–Strogatz graph");
assert_eq!(graph.node_count(), n);
assert!(graph.edge_count() >= n * k / 2);
}
#[test]
fn test_barabasi_albert_graph() {
let n = 20;
let m = 3;
let seed = 42;
let graph = barabasi_albert_graph::<Undirected>(n, m, seed)
.expect("Failed to generate Barabási–Albert graph");
assert_eq!(graph.node_count(), n);
let expected_edges = (m * (m - 1) / 2) + (n - m) * m;
assert_eq!(graph.edge_count(), expected_edges);
}
#[test]
fn invalid_erdos_params_rejected() {
assert!(matches!(
erdos_renyi_graph::<Undirected>(0, 0.5, 1),
Err(GraphinaError::InvalidArgument(_))
));
assert!(matches!(
erdos_renyi_graph::<Undirected>(10, 1.5, 1),
Err(GraphinaError::InvalidArgument(_))
));
}
#[test]
fn invalid_ws_params_rejected() {
assert!(matches!(
watts_strogatz_graph::<Undirected>(0, 2, 0.1, 1),
Err(GraphinaError::InvalidArgument(_))
));
assert!(matches!(
watts_strogatz_graph::<Undirected>(10, 3, 0.1, 1),
Err(GraphinaError::InvalidArgument(_))
));
assert!(matches!(
watts_strogatz_graph::<Undirected>(10, 2, 1.5, 1),
Err(GraphinaError::InvalidArgument(_))
));
}
#[test]
fn invalid_cycle_rejected() {
assert!(matches!(
cycle_graph::<Undirected>(2),
Err(GraphinaError::InvalidArgument(_))
));
}
#[test]
fn invalid_star_rejected() {
assert!(matches!(
star_graph::<Directed>(0),
Err(GraphinaError::InvalidArgument(_))
));
}
#[test]
fn invalid_ba_params_rejected() {
assert!(matches!(
barabasi_albert_graph::<Undirected>(5, 0, 1),
Err(GraphinaError::InvalidArgument(_))
));
assert!(matches!(
barabasi_albert_graph::<Undirected>(3, 4, 1),
Err(GraphinaError::InvalidArgument(_))
));
}
}