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
22 changes: 22 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
140 changes: 54 additions & 86 deletions examples/pagerank_validation.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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<Vec<f64>> {
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<Vec<f64>> {
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<String, usize> = 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<String, usize> = 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::<Vec<_>>()
);
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::<Vec<_>>()
);

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
}
}
59 changes: 59 additions & 0 deletions tests/pagerank_uniform.rs
Original file line number Diff line number Diff line change
@@ -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<Vec<f64>> {
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<Vec<f64>> {
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<f64>]) {
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));
}
Loading