Skip to content

Commit f52e9b8

Browse files
authored
Make Barabasi-Albert's generator return the same graph for the same seed (#1481)
* Make barabasi_albert's only source of determinism be the seed * Add bug fix note
1 parent 1a2baf6 commit f52e9b8

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
fixes:
3+
- |
4+
Fixed a bug where the random graph generator functions,
5+
:func:`.directed_barabasi_albert_graph` and :func:`.barabasi_albert_graph`
6+
would generate different graphs when the same input seed was used.

rustworkx-core/src/generators/random_graph.rs

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ use petgraph::visit::{
2424
};
2525
use petgraph::{Incoming, Outgoing};
2626

27-
use hashbrown::HashSet;
2827
use rand::prelude::*;
2928
use rand_distr::{Distribution, Uniform};
3029
use rand_pcg::Pcg64;
@@ -814,7 +813,8 @@ where
814813
let mut source = graph.node_count();
815814
while source < n {
816815
let source_index = graph.add_node(default_node_weight());
817-
let mut targets: HashSet<G::NodeId> = HashSet::with_capacity(m);
816+
let mut targets: IndexSet<G::NodeId, foldhash::fast::RandomState> =
817+
IndexSet::with_capacity_and_hasher(m, foldhash::fast::RandomState::default());
818818
while targets.len() < m {
819819
targets.insert(*repeated_nodes.choose(&mut rng).unwrap());
820820
}
@@ -1402,6 +1402,27 @@ mod tests {
14021402
};
14031403
}
14041404

1405+
#[test]
1406+
fn test_barabasi_albert_graph_seeding() {
1407+
use petgraph::visit::EdgeRef;
1408+
let g1: petgraph::graph::UnGraph<(), ()> =
1409+
barabasi_albert_graph(7, 2, Some(42), None, || (), || ()).unwrap();
1410+
let g2: petgraph::graph::UnGraph<(), ()> =
1411+
barabasi_albert_graph(7, 2, Some(42), None, || (), || ()).unwrap();
1412+
// Same seeds should yield the same graph
1413+
let edges1: std::collections::BTreeSet<_> = g1
1414+
.edge_references()
1415+
.map(|e| (e.source(), e.target()))
1416+
.collect();
1417+
let edges2: std::collections::BTreeSet<_> = g2
1418+
.edge_references()
1419+
.map(|e| (e.source(), e.target()))
1420+
.collect();
1421+
for (e1, e2) in edges1.iter().zip(edges2.iter()) {
1422+
assert_eq!(e1, e2);
1423+
}
1424+
}
1425+
14051426
#[test]
14061427
fn test_barabasi_albert_graph_starting_graph() {
14071428
let starting_graph: petgraph::graph::UnGraph<(), ()> =

0 commit comments

Comments
 (0)