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

//! Shortest paths as vertex lists against a plain reference: every walk of each length,
//! level by level, the shortest kept per (source, end); on small graphs with cycles, a
//! random graph and a grid (many equal shortest paths).

use std::collections::BTreeMap;

use kleene_graph::{Graph, Hops, Shortest, shortest_paths};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, Csr};

/// Every shortest walk from each source (with `min` 0 or 1 edges, at most `max`), by
/// growing all walks a level at a time until no new (source, end) pair appears.
fn plain(edges: &[(u32, u32)], sources: &[u32], min: u64, max: Option<u64>) -> Vec<Vec<u32>> {
    let mut best: BTreeMap<(u32, u32), Vec<Vec<u32>>> = BTreeMap::new();
    for &s in sources {
        let mut level: Vec<Vec<u32>> = vec![vec![s]];
        let mut found: BTreeMap<u32, usize> = BTreeMap::new();
        let mut depth = 0u64;
        loop {
            let mut new = false;
            if depth >= min {
                for w in &level {
                    let t = *w.last().unwrap();
                    match found.get(&t) {
                        None => {
                            found.insert(t, w.len());
                            best.entry((s, t)).or_default().push(w.clone());
                            new = true;
                        }
                        Some(&l) if l == w.len() => {
                            best.entry((s, t)).or_default().push(w.clone());
                        }
                        _ => {}
                    }
                }
            }
            if max.is_some_and(|m| depth >= m) || (depth >= min && !new) {
                break;
            }
            // Only walks whose end is not yet found by a shorter walk can lead to new ends
            // by a shortest walk; past `min`, drop the rest.
            let keep: Vec<Vec<u32>> = level
                .into_iter()
                .filter(|w| depth < min || found.get(w.last().unwrap()) == Some(&w.len()))
                .collect();
            level = keep
                .iter()
                .flat_map(|w| {
                    let t = *w.last().unwrap();
                    edges.iter().filter(move |e| e.0 == t).map(move |e| {
                        let mut x = w.clone();
                        x.push(e.1);
                        x
                    })
                })
                .collect();
            level.sort();
            level.dedup();
            depth += 1;
        }
    }
    let mut out: Vec<Vec<u32>> = best.into_values().flatten().collect();
    out.sort_by(|a, b| (a[0], a.last(), a).cmp(&(b[0], b.last(), b)));
    out
}

fn any_of(all: &[Vec<u32>]) -> Vec<Vec<u32>> {
    // Through the lowest vertex at each step back from the end: the least reversed list.
    let mut by: BTreeMap<(u32, u32), Vec<u32>> = BTreeMap::new();
    for p in all {
        let key = (p[0], *p.last().unwrap());
        let rev: Vec<u32> = p.iter().rev().copied().collect();
        let e = by.entry(key).or_insert_with(|| p.clone());
        let cur: Vec<u32> = e.iter().rev().copied().collect();
        if rev < cur {
            *e = p.clone();
        }
    }
    by.into_values().collect()
}

fn run(
    n: usize,
    edges: &[(u32, u32)],
    sources: &[u32],
    hops: Hops,
    which: Shortest,
) -> Vec<Vec<u32>> {
    let (s, d): (Vec<u32>, Vec<u32>) = edges.iter().copied().unzip();
    let a = Csr::from_edges(n, n, &s, &d, None, BoolOrAnd).unwrap();
    let dev = CpuDevice::new(2);
    let g = Graph::<CpuBackend>::new(a.clone(), &dev).unwrap();
    shortest_paths(&g, &a, sources, hops, which, 1_000_000, &dev)
        .unwrap()
        .paths
}

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)
    };
    let mut e: Vec<(u32, u32)> = (0..m)
        .map(|_| ((next() % n as u64) as u32, (next() % n as u64) as u32))
        .collect();
    e.sort_unstable();
    e.dedup();
    e
}

#[test]
fn any_and_all_shortest_equal_a_plain_search() {
    let small: Vec<(u32, u32)> = vec![
        (0, 1),
        (1, 2),
        (2, 0),
        (2, 3),
        (0, 3),
        (3, 4),
        (4, 4),
        (1, 4),
        (5, 6),
        (6, 5),
    ];
    let mut grid = Vec::new();
    for r in 0..5u32 {
        for c in 0..5u32 {
            let v = r * 5 + c;
            if c + 1 < 5 {
                grid.push((v, v + 1));
            }
            if r + 1 < 5 {
                grid.push((v, v + 5));
            }
        }
    }
    let rnd = random(40, 90, 5);
    for (n, edges, sources) in [
        (7usize, small.clone(), vec![0u32]),
        (7, small.clone(), vec![5, 2, 4]),
        (25, grid.clone(), vec![0, 6]),
        (40, rnd.clone(), vec![1, 2, 3, 30]),
    ] {
        for (min, max) in [
            (0, None),
            (1, None),
            (0, Some(2)),
            (1, Some(3)),
            (1, Some(1)),
            (0, Some(0)),
        ] {
            let hops = Hops::new(min, max);
            let want = plain(&edges, &sources, min, max);
            let all = run(n, &edges, &sources, hops, Shortest::All);
            assert_eq!(all, want, "all n {n} {sources:?} {min}..{max:?}");
            let any = run(n, &edges, &sources, hops, Shortest::Any);
            assert_eq!(any, any_of(&want), "any n {n} {sources:?} {min}..{max:?}");
        }
    }
    // The grid: C(8, 4) = 70 shortest paths corner to corner.
    let all = run(25, &grid, &[0], Hops::new(0, None), Shortest::All);
    assert_eq!(all.iter().filter(|p| *p.last().unwrap() == 24).count(), 70);
    // With min 1 the source is an end only on a cycle: 0 -> 1 -> 2 -> 0.
    let any = run(7, &small, &[0], Hops::new(1, None), Shortest::Any);
    assert!(any.contains(&vec![0, 1, 2, 0]));
    // Refused: min over 1, too many paths, a source out of range.
    let (s, d): (Vec<u32>, Vec<u32>) = grid.iter().copied().unzip();
    let a = Csr::from_edges(25, 25, &s, &d, None, BoolOrAnd).unwrap();
    let dev = CpuDevice::new(1);
    let g = Graph::<CpuBackend>::new(a.clone(), &dev).unwrap();
    assert!(shortest_paths(&g, &a, &[0], Hops::new(2, None), Shortest::Any, 10, &dev).is_err());
    assert!(shortest_paths(&g, &a, &[0], Hops::new(0, None), Shortest::All, 50, &dev).is_err());
    assert!(shortest_paths(&g, &a, &[25], Hops::new(0, None), Shortest::Any, 10, &dev).is_err());
}