Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,23 @@
self-loops, as networkx does. A self-loop counted toward the degree, so a
triangle with a self-loop on node 0 gave C(0) = 1/3 instead of 1.

- `newman_betweenness` excludes each pair's source and sink from that pair's
contribution, as networkx `current_flow_betweenness_centrality` does, so
scores lie in the documented [0, 1]. Endpoints received 1/2 per pair: a
6-node star scored 1.25 at the centre and 0.25 at each leaf instead of 1 and
0. Scores change on every graph.

- The parallel walk generators (`generate_walks_ref_parallel*`,
`generate_biased_walks_ref_parallel*`,
`generate_biased_walks_precomp_ref_parallel_from_nodes`) give each walk its
own ChaCha stream. Per-walk seeds mixed from `node ^ index` collided, so
distinct walks repeated the same steps (33 identical pairs among 64 walks
on a 64-cycle). Walks for a given seed change; they remain independent of
the Rayon thread count.

- The rejection-sampling biased walk generators panic when `p` or `q` is
zero, negative, infinite or NaN instead of looping forever.

## [0.5.3] - 2026-10-30

### Fixed
Expand Down
14 changes: 11 additions & 3 deletions src/betweenness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,10 @@ pub struct NewmanBetweennessRun {
/// current and contribute 0.
///
/// The edge current on \\((i,j)\\) is \\(|v_i - v_j|\\), and the contribution
/// to node \\(k\\)'s betweenness is
/// \\(\\tfrac{1}{2} \\sum_{j \\in N(k)} |v_k - v_j|\\).
/// to node \\(k \\notin \\{s, t\\}\\)'s betweenness is
/// \\(\\tfrac{1}{2} \\sum_{j \\in N(k)} |v_k - v_j|\\). The source and sink
/// themselves get nothing from their own pair, matching networkx
/// `current_flow_betweenness_centrality`.
///
/// After summing over all pairs the result is divided by
/// \\(\\tfrac{(n-1)(n-2)}{2}\\) to normalize into \\([0, 1]\\).
Expand Down Expand Up @@ -357,8 +359,14 @@ pub fn newman_betweenness_run<G: GraphRef>(
all_converged = false;
}

// Accumulate betweenness: for each node k, add (1/2) * sum_{j in N(k)} |v[k] - v[j]|.
// Accumulate betweenness: for each node k other than the source and
// sink, add (1/2) * sum_{j in N(k)} |v[k] - v[j]|. Endpoints are
// excluded, as in networkx and Brandes-Fleischer (2005); counting
// them adds 1/2 per pair and breaks the [0, 1] normalization.
for k in 0..n {
if k == s || k == t {
continue;
}
let mut flow_k = 0.0f64;
for &j in neighbors[k] {
flow_k += (v[k] - v[j]).abs();
Expand Down
18 changes: 5 additions & 13 deletions src/node2vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -494,19 +494,11 @@ pub fn generate_biased_walks_precomp_ref_parallel_from_nodes(

jobs.par_iter()
.enumerate()
.map(|(i, (epoch, node))| {
fn mix64(mut x: u64) -> u64 {
x ^= x >> 30;
x = x.wrapping_mul(0xbf58476d1ce4e5b9);
x ^= x >> 27;
x = x.wrapping_mul(0x94d049bb133111eb);
x ^= x >> 31;
x
}

let seed = mix64(config.seed ^ ((*epoch as u64) << 32) ^ (*node as u64) ^ (i as u64));
let mut rng = ChaCha8Rng::seed_from_u64(seed);
biased_walk_precomp(pre, *node, config.length, &mut rng)
.map(|(i, &(_, node))| {
// One ChaCha stream per job index: distinct for every walk.
let mut rng = ChaCha8Rng::seed_from_u64(config.seed);
rng.set_stream(i as u64);
biased_walk_precomp(pre, node, config.length, &mut rng)
})
.collect()
}
Expand Down
29 changes: 21 additions & 8 deletions src/random_walk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,13 @@ pub struct WalkConfig {
pub walks_per_node: usize,
/// node2vec return parameter. `p < 1` biases walks toward revisiting
/// the previous node (local exploration); `p > 1` discourages returning.
/// Must be finite and > 0: the `generate_biased_walks*` functions in this
/// module panic otherwise.
pub p: f32,
/// node2vec in-out parameter. `q < 1` biases walks outward (DFS-like);
/// `q > 1` keeps walks close to the origin (BFS-like).
/// Must be finite and > 0: the `generate_biased_walks*` functions in this
/// module panic otherwise.
pub q: f32,
/// Seed for the deterministic RNG. Same seed + same graph + same config
/// always produces identical walks.
Expand Down Expand Up @@ -448,6 +452,12 @@ fn sample_biased_rejection<R: Rng>(
p: f32,
q: f32,
) -> usize {
// With p or q zero, infinite or NaN, some step has acceptance ratio 0 or
// NaN for every candidate and the loop below never exits.
assert!(
p.is_finite() && p > 0.0 && q.is_finite() && q > 0.0,
"node2vec p and q must be finite and > 0 (got p = {p}, q = {q})"
);
let max_prob = (1.0 / p).max(1.0).max(1.0 / q);
loop {
let candidate = *neighbors.choose(rng).unwrap();
Expand Down Expand Up @@ -514,10 +524,12 @@ pub fn generate_walks_ref_parallel_from_nodes<G: GraphRef + Sync>(

jobs.par_iter()
.enumerate()
.map(|(i, (epoch, node))| {
let seed = mix64(config.seed ^ ((*epoch as u64) << 32) ^ (*node as u64) ^ (i as u64));
let mut rng = ChaCha8Rng::seed_from_u64(seed);
unbiased_walk_ref(graph, *node, config.length, &mut rng)
.map(|(i, &(_, node))| {
// One ChaCha stream per job index: distinct for every walk. Seeds
// mixed from `node ^ i` collided and gave walks identical steps.
let mut rng = ChaCha8Rng::seed_from_u64(config.seed);
rng.set_stream(i as u64);
unbiased_walk_ref(graph, node, config.length, &mut rng)
})
.collect()
}
Expand Down Expand Up @@ -559,10 +571,11 @@ pub fn generate_biased_walks_ref_parallel_from_nodes<G: GraphRef + Sync>(

jobs.par_iter()
.enumerate()
.map(|(i, (epoch, node))| {
let seed = mix64(config.seed ^ ((*epoch as u64) << 32) ^ (*node as u64) ^ (i as u64));
let mut rng = ChaCha8Rng::seed_from_u64(seed);
biased_walk_ref(graph, *node, config, &mut rng)
.map(|(i, &(_, node))| {
// One ChaCha stream per job index, as in `generate_walks_ref_parallel_from_nodes`.
let mut rng = ChaCha8Rng::seed_from_u64(config.seed);
rng.set_stream(i as u64);
biased_walk_ref(graph, node, config, &mut rng)
})
.collect()
}
138 changes: 138 additions & 0 deletions tests/regressions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
//! Regression tests for fixed bugs. Each test states the correct behavior and
//! the reference it comes from.

use graphops::graph::GraphRef;
use graphops::{newman_betweenness, NewmanBetweennessConfig};

struct VG(Vec<Vec<usize>>);
impl GraphRef for VG {
fn node_count(&self) -> usize {
self.0.len()
}
fn neighbors_ref(&self, n: usize) -> &[usize] {
&self.0[n]
}
}

fn path(n: usize) -> VG {
VG((0..n)
.map(|k| {
let mut v = Vec::new();
if k > 0 {
v.push(k - 1);
}
if k + 1 < n {
v.push(k + 1);
}
v
})
.collect())
}

fn close(got: &[f64], want: &[f64], tol: f64) -> bool {
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g - w).abs() <= tol)
}

/// Current-flow betweenness excludes the source and sink of each pair, so the
/// `(n-1)(n-2)` normalizer maps scores into [0, 1]. Reference values from
/// networkx 3.7 `current_flow_betweenness_centrality`.
#[test]
fn newman_betweenness_excludes_endpoints_like_networkx() {
let star = VG(vec![
vec![1, 2, 3, 4, 5],
vec![0],
vec![0],
vec![0],
vec![0],
vec![0],
]);
let s = newman_betweenness(&star, NewmanBetweennessConfig::default());
let want = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0];
assert!(close(&s, &want, 1e-6), "star: got {s:?}, networkx {want:?}");

let s = newman_betweenness(&path(4), NewmanBetweennessConfig::default());
let want = [0.0, 2.0 / 3.0, 2.0 / 3.0, 0.0];
assert!(close(&s, &want, 1e-6), "P4: got {s:?}, networkx {want:?}");
}

/// node2vec requires p, q > 0 (Grover and Leskovec 2016). With p or q zero,
/// infinite or NaN, the rejection sampler's acceptance ratio is 0 or NaN for
/// every candidate on some step, so it would loop forever; the call must
/// return or panic instead.
#[test]
fn biased_walk_rejects_non_positive_or_non_finite_p_q() {
use graphops::{generate_biased_walks_ref, WalkConfig};
for (p, q) in [
(0.0, 1.0),
(1.0, 0.0),
(f32::NAN, 1.0),
(f32::INFINITY, 1.0),
] {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let r = std::panic::catch_unwind(|| {
let cfg = WalkConfig {
length: 4,
walks_per_node: 1,
p,
q,
..WalkConfig::default()
};
generate_biased_walks_ref(&path(3), cfg).len()
});
let _ = tx.send(r.is_err());
});
let panicked = rx.recv_timeout(std::time::Duration::from_secs(5));
assert_eq!(
panicked,
Ok(true),
"p = {p}, q = {q}: expected a panic, got {panicked:?} (timeout means the sampler looped)"
);
}
}

/// Each parallel walk gets its own RNG stream. Seeds built as
/// `seed ^ node ^ index` collide whenever `node ^ index` matches, which gave
/// distinct walks identical step sequences. On a 64-cycle, two independent
/// 30-step direction sequences agree with probability 2^-30.
#[cfg(feature = "parallel")]
#[test]
fn parallel_walks_use_independent_streams() {
use graphops::{
generate_biased_walks_precomp_ref_parallel_from_nodes, generate_biased_walks_ref_parallel,
generate_walks_ref_parallel, PrecomputedBiasedWalks, WalkConfig,
};
let n = 64;
let g = VG((0..n).map(|k| vec![(k + n - 1) % n, (k + 1) % n]).collect());
let cfg = WalkConfig {
length: 31,
walks_per_node: 1,
seed: 3,
..WalkConfig::default()
};
let pre = PrecomputedBiasedWalks::new(&g, cfg.p, cfg.q);
let starts: Vec<usize> = (0..n).collect();
for (name, walks) in [
("unbiased", generate_walks_ref_parallel(&g, cfg)),
("biased", generate_biased_walks_ref_parallel(&g, cfg)),
(
"precomputed",
generate_biased_walks_precomp_ref_parallel_from_nodes(&pre, &starts, cfg),
),
] {
let dirs: Vec<Vec<bool>> = walks
.iter()
.map(|w| w.windows(2).map(|p| p[1] == (p[0] + 1) % n).collect())
.collect();
let mut same = 0;
for a in 0..dirs.len() {
for b in (a + 1)..dirs.len() {
same += usize::from(dirs[a] == dirs[b]);
}
}
assert_eq!(
same, 0,
"{name}: {same} pairs of walks share a step sequence"
);
}
}
Loading