Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-graph/tests/walks.rs

//! Walks of bounded length against a plain reference: the set of vertices at each walk
//! length, level by level with no visited set, on small graphs with cycles, an R-MAT-like
//! random graph and a grid; ends and (source, end) pairs.

use std::collections::BTreeSet;

use kleene_graph::{Graph, Hops, walk_ends, walk_pairs};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, Csr};

/// The vertices at the end of a walk from `sources` of a length in `min..=max` (`max`
/// capped at `cap` steps when absent: enough for the small graphs here to saturate).
fn plain(edges: &[(u32, u32)], sources: &[u32], min: u64, max: Option<u64>, cap: u64) -> Vec<u32> {
    let mut level: BTreeSet<u32> = sources.iter().copied().collect();
    let mut out = BTreeSet::new();
    let last = max.unwrap_or(cap);
    for depth in 0..=last {
        if depth >= min {
            out.extend(level.iter().copied());
        }
        level = edges
            .iter()
            .filter(|e| level.contains(&e.0))
            .map(|e| e.1)
            .collect();
    }
    out.into_iter().collect()
}

fn graph(n: usize, edges: &[(u32, u32)]) -> (Csr<u8>, Graph<CpuBackend>) {
    let (s, d): (Vec<u32>, Vec<u32>) = edges.iter().copied().unzip();
    let a = Csr::from_edges(n, n, &s, &d, None, BoolOrAnd).unwrap();
    let g = Graph::with_transpose(a.clone(), a.transpose(), &CpuDevice::new(3)).unwrap();
    (a, g)
}

/// A seeded pseudo-random edge list (SplitMix64), targets skewed towards low ids.
fn random(n: u32, m: usize, seed: u64) -> Vec<(u32, u32)> {
    let mut x = seed;
    let mut next = || {
        x = x.wrapping_add(0x9E3779B97F4A7C15);
        let mut z = x;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
        z ^ (z >> 31)
    };
    (0..m)
        .map(|_| {
            let a = (next() % n as u64) as u32;
            // skewed: the product of two draws favours low ids
            let b = ((next() % n as u64) * (next() % n as u64) / n as u64) as u32;
            (a, b)
        })
        .collect()
}

fn ranges() -> Vec<(u64, Option<u64>)> {
    vec![
        (0, Some(0)),
        (1, Some(1)),
        (2, Some(2)),
        (10, Some(10)),
        (1, Some(3)),
        (2, Some(5)),
        (0, Some(4)),
        (3, None),
        (0, None),
        (1, None),
        (5, Some(2)),
    ]
}

#[test]
fn ends_equal_a_level_walk() {
    // A cycle of three with a tail, a self-loop, a second cycle of length two.
    let small: Vec<(u32, u32)> = vec![
        (0, 1),
        (1, 2),
        (2, 0),
        (2, 3),
        (3, 4),
        (4, 4),
        (5, 6),
        (6, 5),
        (4, 5),
    ];
    let rnd = random(300, 900, 7);
    let mut grid = Vec::new();
    for r in 0..12u32 {
        for c in 0..12u32 {
            let v = r * 12 + c;
            if c + 1 < 12 {
                grid.push((v, v + 1));
            }
            if r + 1 < 12 {
                grid.push((v, v + 12));
            }
        }
    }
    for (n, edges, sources) in [
        (7usize, small.clone(), vec![0u32]),
        (7, small.clone(), vec![5, 3]),
        (300, rnd.clone(), vec![1, 2, 3]),
        (144, grid.clone(), vec![0]),
    ] {
        let (_, g) = graph(n, &edges);
        let dev = CpuDevice::new(3);
        for (min, max) in ranges() {
            let w = walk_ends(&g, &sources, Hops::new(min, max), &dev).unwrap();
            let want = plain(&edges, &sources, min, max, 3 * n as u64 + min);
            assert_eq!(w.vertices, want, "n {n} sources {sources:?} {min}..{max:?}");
        }
    }
    // The cycle of three: exactly 3, 6 and 9 edges come back to the start; 10 edges do not.
    let (_, g) = graph(7, &small);
    let dev = CpuDevice::new(1);
    let ends = |m, x| {
        walk_ends(&g, &[0], Hops::new(m, Some(x)), &dev)
            .unwrap()
            .vertices
    };
    assert!(ends(9, 9).contains(&0));
    assert!(!ends(10, 10).contains(&0));
    // Saturation: a long range stops early once a step adds nothing.
    let w = walk_ends(&g, &[0], Hops::new(1, Some(1_000_000)), &dev).unwrap();
    assert!(w.steps < 50, "{}", w.steps);
    assert!(walk_ends(&g, &[7], Hops::new(1, Some(2)), &dev).is_err());
}

#[test]
fn pairs_equal_ends_per_source() {
    let edges = random(120, 300, 11);
    let (a, g) = graph(120, &edges);
    let dev = CpuDevice::new(3);
    let sources: Vec<u32> = (0..120).step_by(7).collect();
    for (min, max) in ranges() {
        let hops = Hops::new(min, max);
        let (pairs, _) = walk_pairs::<CpuBackend>(&a, &sources, hops, &dev).unwrap();
        for s in 0..120u32 {
            let want = if sources.contains(&s) {
                walk_ends(&g, &[s], hops, &dev).unwrap().vertices
            } else {
                Vec::new()
            };
            assert_eq!(
                pairs.row(s as usize),
                &want[..],
                "source {s} {min}..{max:?}"
            );
        }
    }
}