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/mis.rs

//! The maximal independent set: independent (no two members neighbours) and maximal (every
//! other vertex has a neighbour in it), whatever the number of workers and the seed, and
//! for a seed the same set at every worker count: the one the plain greedy pass by falling
//! priority gives. Hand-made and generated graphs and the edge cases (no vertices, isolated
//! vertices, self-loops, both ways of an edge, a clique, a star).

use std::collections::BTreeSet;

use kleene_graph::{mis, mis_priority, undirected};
use kleene_sparse::{BoolOrAnd, CpuDevice, Csr};

fn und(n: usize, edges: &[(u32, u32)]) -> Csr<u8> {
    let (s, d): (Vec<u32>, Vec<u32>) = edges.iter().copied().unzip();
    let a = Csr::from_edges(n, n, &s, &d, None, BoolOrAnd).unwrap();
    undirected(&a, &a.transpose()).unwrap()
}

/// Skewed edges from a fixed seed: a quarter from the eight lowest numbers (hubs), some
/// both ways, self-loops and repeats in.
fn skewed(n: u32, m: usize, seed: u64) -> Vec<(u32, u32)> {
    let mut x = seed;
    let mut next = || {
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        x
    };
    let mut e = Vec::with_capacity(m + m / 8);
    for _ in 0..m {
        let a = (next() % u64::from(n)) as u32;
        let b = (next() % u64::from(n)) as u32;
        let (a, b) = if next() % 4 == 0 { (a % 8, b) } else { (a, b) };
        e.push((a, b));
        if next() % 8 == 0 {
            e.push((b, a));
        }
    }
    e
}

/// The two properties, checked by hand.
fn check(u: &Csr<u8>, members: &[u32], what: &str) {
    let set: BTreeSet<u32> = members.iter().copied().collect();
    assert_eq!(set.len(), members.len(), "{what}: repeats");
    assert!(members.windows(2).all(|w| w[0] < w[1]), "{what}: rising");
    for v in 0..u.nrows() as u32 {
        let near = u.row(v as usize).iter().any(|w| *w != v && set.contains(w));
        if set.contains(&v) {
            assert!(!near, "{what}: {v} and a neighbour both in");
        } else {
            assert!(near, "{what}: {v} could be added");
        }
    }
}

/// The greedy pass on one thread: the vertices by falling priority, each taken when no
/// neighbour was.
fn greedy(u: &Csr<u8>, seed: u64) -> Vec<u32> {
    let mut order: Vec<u32> = (0..u.nrows() as u32).collect();
    order.sort_by_key(|&v| std::cmp::Reverse(mis_priority(seed, v)));
    let mut taken = vec![false; u.nrows()];
    for v in order {
        if !u.row(v as usize).iter().any(|&w| taken[w as usize]) {
            taken[v as usize] = true;
        }
    }
    (0..u.nrows() as u32)
        .filter(|&v| taken[v as usize])
        .collect()
}

fn devices() -> Vec<CpuDevice> {
    vec![
        CpuDevice::new(1),
        CpuDevice::new(2).with_grain(1),
        CpuDevice::new(5).with_grain(16),
        CpuDevice::new(12).with_grain(64),
    ]
}

fn fixtures() -> Vec<(&'static str, Csr<u8>)> {
    let side = 30u32;
    let mut grid = Vec::new();
    for r in 0..side {
        for c in 0..side {
            let v = r * side + c;
            if c + 1 < side {
                grid.push((v, v + 1));
            }
            if r + 1 < side && (r + 2 * c) % 4 != 0 {
                grid.push((v, v + side));
            }
        }
    }
    let clique: Vec<(u32, u32)> = (0..30u32)
        .flat_map(|a| (0..30u32).map(move |b| (a, b)))
        .collect();
    let star: Vec<(u32, u32)> = (1..500u32).map(|v| (0, v)).collect();
    let path: Vec<(u32, u32)> = (0..999u32).map(|v| (v + 1, v)).collect();
    vec![
        ("skewed", und(5000, &skewed(5000, 40000, 11))),
        ("sparse", und(3000, &skewed(3000, 1000, 2))),
        ("grid", und((side * side) as usize, &grid)),
        ("clique", und(30, &clique)),
        ("star", und(500, &star)),
        ("path", und(1000, &path)),
    ]
}

#[test]
fn mis_is_independent_maximal_and_the_greedy_set_at_any_worker_count() {
    for (name, u) in fixtures() {
        for seed in [0u64, 1, 42, u64::MAX] {
            let want = greedy(&u, seed);
            for cpu in devices() {
                let m = mis(&u, seed, &cpu).unwrap();
                let what = format!("{name} seed {seed} on {}", cpu.threads());
                check(&u, &m.members, &what);
                assert_eq!(m.members, want, "{what}");
                assert!(m.rounds >= 1, "{what}");
            }
        }
    }
}

#[test]
fn mis_by_hand_and_edge_cases() {
    let cpu = CpuDevice::new(3).with_grain(1);
    // No vertices: no set, no rounds.
    let m = mis(&und(0, &[]), 7, &cpu).unwrap();
    assert!(m.members.is_empty());
    assert_eq!(m.rounds, 0);
    // Isolated vertices and self-loops only: every vertex is in, in one round.
    let m = mis(&und(6, &[(2, 2), (4, 4)]), 7, &cpu).unwrap();
    assert_eq!(m.members, [0, 1, 2, 3, 4, 5]);
    assert_eq!(m.rounds, 1);
    // A self-loop left in the matrix (not through `undirected`) is not a neighbour.
    let a = Csr::from_edges(3, 3, &[0, 1, 1, 1, 2], &[1, 0, 1, 2, 1], None, BoolOrAnd).unwrap();
    let m = mis(&a, 3, &cpu).unwrap();
    check(&und(3, &[(0, 1), (1, 2)]), &m.members, "self-loop kept");
    // An edge both ways is one edge: one end of it.
    let m = mis(&und(2, &[(0, 1), (1, 0)]), 5, &cpu).unwrap();
    assert_eq!(m.members.len(), 1);
    // A clique: one vertex, the one of the highest priority.
    let clique: Vec<(u32, u32)> = (0..10u32)
        .flat_map(|a| (a + 1..10).map(move |b| (a, b)))
        .collect();
    let m = mis(&und(10, &clique), 9, &cpu).unwrap();
    let top = (0..10u32).max_by_key(|&v| mis_priority(9, v)).unwrap();
    assert_eq!(m.members, [top]);
    // Other seeds give other sets, each a maximal independent set.
    let u = und(400, &skewed(400, 1200, 5));
    let sets: BTreeSet<Vec<u32>> = (0..8).map(|s| mis(&u, s, &cpu).unwrap().members).collect();
    assert!(sets.len() > 1);
    for s in &sets {
        check(&u, s, "seeds");
    }
    // Not square.
    let r = Csr::from_edges(2, 3, &[0], &[2], None, BoolOrAnd).unwrap();
    assert!(mis(&r, 1, &cpu).is_err());
}