From fe08e83ce82bcbf60b55b5a49d4b3983cee9aaa9 Mon Sep 17 00:00:00 2001 From: Henry Wallace Date: Wed, 4 Nov 2026 02:41:59 -0500 Subject: [PATCH] graphops: move the uniform PageRank oracles into tests and data-gate the Cora run examples/pagerank_validation.rs mixed exact checks (a directed cycle and a complete graph must give uniform PageRank) with a Cora run that unwrapped the data file. The exact checks are now tests/pagerank_uniform.rs (max |score - 1/n| < 1e-6 and sum within 1e-6 of 1); flipping the teleport term's sign fails both. The example keeps only the Cora eval: without the file it prints a skip message and exits 0, and a bad file or a failed sum or positivity check still exits 1. The examples index now lists lazy_frontier and the data-gated eval. --- examples/README.md | 22 +++++ examples/pagerank_validation.rs | 140 ++++++++++++-------------------- tests/pagerank_uniform.rs | 59 ++++++++++++++ 3 files changed, 135 insertions(+), 86 deletions(-) create mode 100644 tests/pagerank_uniform.rs diff --git a/examples/README.md b/examples/README.md index e79e212..b757f51 100644 --- a/examples/README.md +++ b/examples/README.md @@ -8,12 +8,14 @@ | Split a graph into communities | `community_detection` | | Generate walks for embedding pipelines | `random_walks` | | Score plausible missing edges with regions | `ellipsoidal_link_prediction` | +| Expand a graph lazily from a query node | `lazy_frontier` | ```sh cargo run --example pagerank cargo run --example community_detection cargo run --example random_walks cargo run --example ellipsoidal_link_prediction +cargo run --example lazy_frontier ``` ## What to inspect @@ -22,3 +24,23 @@ cargo run --example ellipsoidal_link_prediction - `community_detection` compares Louvain with a variant that splits disconnected communities. It does not implement Leiden's refinement phase. - `random_walks` prints uniform walks and node2vec-style walks with `q < 1`, which biases walks outward from the previous node. - `ellipsoidal_link_prediction` embeds nodes as ellipsoids, ranks non-edges by overlap, and compares intra-cluster vs. inter-cluster distance. +- `lazy_frontier` expands the most promising frontier edge first and stops once the evidence threshold is met, then compares how many nodes it visited with an eager expansion to the same depth. + +## Real-data eval + +| Data | Example | What to read from the output | +|---|---|---| +| Cora citation network (2708 nodes) | `pagerank_validation` | node count, score sum, positivity, and the top-3 scores | + +Cora is not checked in. Without it the example prints a skip message and exits 0. + +```sh +./scripts/fetch_cora_cites.sh +cargo run --release --example pagerank_validation +``` + +## Correctness checks + +Checks against a known answer live in `tests/`, not here, so `cargo test` runs +them. For example, `tests/pagerank_uniform.rs` checks that PageRank is exactly +uniform on a directed cycle and a complete graph. diff --git a/examples/pagerank_validation.rs b/examples/pagerank_validation.rs index ec5b855..5cd6967 100644 --- a/examples/pagerank_validation.rs +++ b/examples/pagerank_validation.rs @@ -1,18 +1,16 @@ -//! Validate graphops PageRank against exact references, plus a real graph. +//! PageRank on the real Cora citation network: a scale and sanity eval. //! -//! Two graphs have a provably uniform stationary distribution regardless of the -//! damping/dangling convention: a directed cycle and a complete graph. PageRank -//! on either must return 1/n for every node; deviation is a bug. Then it runs on -//! the real Cora citation network (fetch first) as a sanity + scale check. +//! Reports node count, score sum, positivity, and the top-3 scores. The exact +//! checks (uniform PageRank on a directed cycle and a complete graph) live in +//! `tests/pagerank_uniform.rs` and run under `cargo test`. +//! +//! Cora is not checked in. Without it this prints a skip message and exits 0. //! //! ```sh -//! ./scripts/fetch_cora_cites.sh # optional; the exact checks run without it +//! ./scripts/fetch_cora_cites.sh //! cargo run --release --example pagerank_validation //! ``` -// Index loops are the clearest form for dense adjacency-matrix construction. -#![allow(clippy::needless_range_loop)] - use std::collections::HashMap; use std::path::Path; use std::process::ExitCode; @@ -28,94 +26,64 @@ fn config() -> PageRankConfig { } } -/// Max absolute deviation of `scores` from the uniform distribution 1/n. -fn max_dev_from_uniform(scores: &[f64]) -> f64 { - let u = 1.0 / scores.len() as f64; - scores.iter().map(|&s| (s - u).abs()).fold(0.0, f64::max) -} - -fn directed_cycle(n: usize) -> Vec> { - let mut adj = vec![vec![0.0; n]; n]; - for i in 0..n { - adj[i][(i + 1) % n] = 1.0; - } - adj -} - -fn complete(n: usize) -> Vec> { - let mut adj = vec![vec![0.0; n]; n]; - for i in 0..n { - for j in 0..n { - if i != j { - adj[i][j] = 1.0; - } - } - } - adj -} - fn main() -> ExitCode { - let mut ok = true; - - println!("=== exact references (uniform stationary distribution) ==="); - for (name, adj) in [ - ("directed cycle n=64", directed_cycle(64)), - ("complete graph n=30", complete(30)), - ] { - let scores = pagerank(&AdjacencyMatrix(&adj), config()); - let dev = max_dev_from_uniform(&scores); - let sum: f64 = scores.iter().sum(); - let pass = dev < 1e-6 && (sum - 1.0).abs() < 1e-6; - ok &= pass; + let cites = Path::new(env!("CARGO_MANIFEST_DIR")).join("data/cora/cora.cites"); + if !cites.exists() { println!( - " {name}: max|score - 1/n| = {dev:.2e} sum = {sum:.6} [{}]", - if pass { "PASS" } else { "FAIL" } + "skip: {} not found; run ./scripts/fetch_cora_cites.sh first", + cites.display() ); + return ExitCode::SUCCESS; } - let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("data/cora"); - let cites = dir.join("cora.cites"); - if cites.exists() { - println!("\n=== real graph: Cora citation network ==="); - let content = std::fs::read_to_string(&cites).unwrap(); - let mut id_to_idx: HashMap = HashMap::new(); - let mut edges: Vec<(usize, usize)> = Vec::new(); - for line in content.lines().filter(|l| !l.trim().is_empty()) { - let mut it = line.split_whitespace(); - let (a, b) = (it.next().unwrap(), it.next().unwrap()); - let mut idx = |k: &str| -> usize { - let n = id_to_idx.len(); - *id_to_idx.entry(k.to_string()).or_insert(n) - }; - // cora.cites is "cited citing"; PageRank flows along citing -> cited. - let (cited, citing) = (idx(a), idx(b)); - edges.push((citing, cited)); + let content = match std::fs::read_to_string(&cites) { + Ok(c) => c, + Err(e) => { + eprintln!("cannot read {}: {e}", cites.display()); + return ExitCode::FAILURE; } - let n = id_to_idx.len(); - let mut adj = vec![vec![0.0; n]; n]; - for (s, d) in edges { - adj[s][d] = 1.0; + }; + let mut id_to_idx: HashMap = HashMap::new(); + let mut edges: Vec<(usize, usize)> = Vec::new(); + for (lineno, line) in content.lines().enumerate() { + if line.trim().is_empty() { + continue; } - let scores = pagerank(&AdjacencyMatrix(&adj), config()); - let sum: f64 = scores.iter().sum(); - let all_pos = scores.iter().all(|&s| s > 0.0); - let mut ranked: Vec<(usize, f64)> = scores.iter().copied().enumerate().collect(); - ranked.sort_by(|a, b| b.1.total_cmp(&a.1)); - println!( - " nodes = {n} sum = {sum:.6} all positive = {all_pos} top-3 scores = {:.4?}", - ranked.iter().take(3).map(|(_, s)| *s).collect::>() - ); - ok &= (sum - 1.0).abs() < 1e-4 && all_pos; - } else { - println!( - "\n(Cora not fetched; run ./scripts/fetch_cora_cites.sh for the real-graph check)" - ); + let mut it = line.split_whitespace(); + let (Some(a), Some(b)) = (it.next(), it.next()) else { + eprintln!("{}:{}: expected two ids", cites.display(), lineno + 1); + return ExitCode::FAILURE; + }; + let mut idx = |k: &str| -> usize { + let n = id_to_idx.len(); + *id_to_idx.entry(k.to_string()).or_insert(n) + }; + // cora.cites is "cited citing"; PageRank flows along citing -> cited. + let (cited, citing) = (idx(a), idx(b)); + edges.push((citing, cited)); } + let n = id_to_idx.len(); + let mut adj = vec![vec![0.0; n]; n]; + for (s, d) in edges { + adj[s][d] = 1.0; + } + + let scores = pagerank(&AdjacencyMatrix(&adj), config()); + let sum: f64 = scores.iter().sum(); + let all_pos = scores.iter().all(|&s| s > 0.0); + let mut ranked: Vec<(usize, f64)> = scores.iter().copied().enumerate().collect(); + ranked.sort_by(|a, b| b.1.total_cmp(&a.1)); + println!("Cora citation network"); + println!( + " nodes = {n} sum = {sum:.6} all positive = {all_pos} top-3 scores = {:.4?}", + ranked.iter().take(3).map(|(_, s)| *s).collect::>() + ); - if ok { + // A probability vector with teleportation is strictly positive and sums to 1. + if (sum - 1.0).abs() < 1e-4 && all_pos { ExitCode::SUCCESS } else { - eprintln!("\nVALIDATION FAILED"); + eprintln!("PageRank on Cora is not a positive probability vector"); ExitCode::FAILURE } } diff --git a/tests/pagerank_uniform.rs b/tests/pagerank_uniform.rs new file mode 100644 index 0000000..67640c6 --- /dev/null +++ b/tests/pagerank_uniform.rs @@ -0,0 +1,59 @@ +//! PageRank on graphs whose stationary distribution is exactly uniform. +//! +//! A directed cycle and a complete graph are both regular, so PageRank returns +//! 1/n for every node regardless of the damping and dangling convention. Any +//! deviation is a bug. + +// Index loops are the clearest form for dense adjacency-matrix construction. +#![allow(clippy::needless_range_loop)] + +use graphops::graph::AdjacencyMatrix; +use graphops::{pagerank, PageRankConfig}; + +fn config() -> PageRankConfig { + PageRankConfig { + damping: 0.85, + max_iterations: 200, + tolerance: 1e-10, + } +} + +fn directed_cycle(n: usize) -> Vec> { + let mut adj = vec![vec![0.0; n]; n]; + for i in 0..n { + adj[i][(i + 1) % n] = 1.0; + } + adj +} + +fn complete(n: usize) -> Vec> { + let mut adj = vec![vec![0.0; n]; n]; + for i in 0..n { + for j in 0..n { + if i != j { + adj[i][j] = 1.0; + } + } + } + adj +} + +fn assert_uniform(name: &str, adj: &[Vec]) { + let scores = pagerank(&AdjacencyMatrix(adj), config()); + assert_eq!(scores.len(), adj.len(), "{name}: score length"); + let u = 1.0 / scores.len() as f64; + let dev = scores.iter().map(|&s| (s - u).abs()).fold(0.0, f64::max); + let sum: f64 = scores.iter().sum(); + assert!(dev < 1e-6, "{name}: max |score - 1/n| = {dev:.2e}"); + assert!((sum - 1.0).abs() < 1e-6, "{name}: sum = {sum}"); +} + +#[test] +fn directed_cycle_is_uniform() { + assert_uniform("directed cycle n=64", &directed_cycle(64)); +} + +#[test] +fn complete_graph_is_uniform() { + assert_uniform("complete graph n=30", &complete(30)); +}