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

nordisk/kleene

crates/kleene-gql/tests/structure.rs

//! The CALL procedures on graph structure, each against a plain reference on a small graph:
//! harmonic centrality, the k-truss, the truss numbers, a maximal independent set.

use std::collections::VecDeque;

use kleene_gql::{Catalog, GqlError, Table, lower, parse, query};
use kleene_plan::{Engine, Facts, Source};
use kleene_sparse::{CpuBackend, CpuDevice};

/// Two triangles 0-1-2 and 2-3-4 sharing vertex 2 (some edges one way), a 4-clique 5..8
/// (both ways), a self-loop at 9, the pair 10 -> 11 and 12 alone (an edge to nowhere
/// else: 12 -> 12 is its only edge).
const E: [(u64, u64); 23] = [
    (0, 1),
    (1, 2),
    (2, 0),
    (2, 3),
    (3, 4),
    (4, 2),
    (3, 2),
    (5, 6),
    (6, 5),
    (5, 7),
    (7, 5),
    (5, 8),
    (8, 5),
    (6, 7),
    (7, 6),
    (6, 8),
    (8, 6),
    (7, 8),
    (8, 7),
    (9, 9),
    (10, 11),
    (12, 12),
    (0, 1),
];
const N: usize = 13;

fn catalog() -> Catalog {
    let mut c = Catalog::new();
    c.label(
        "V",
        Source::Facts(Facts::from_rows(1, (0..N as u64).map(|v| [v])).unwrap()),
    )
    .edge(
        "E",
        Source::Facts(Facts::from_rows(2, E.iter().map(|&(a, b)| [a, b])).unwrap()),
    );
    c
}

async fn run(q: &str) -> Table {
    let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(3));
    query(&engine, &catalog(), q)
        .await
        .unwrap_or_else(|e| panic!("{q}: {e}"))
}

fn out(v: u64) -> Vec<u64> {
    E.iter().filter(|e| e.0 == v).map(|e| e.1).collect()
}

/// The sum of 1 / hops over the vertices `s` reaches, level by level.
fn harmonic(s: u64) -> f64 {
    let mut d = [u64::MAX; N];
    d[s as usize] = 0;
    let mut at = [0u64; N];
    let mut q = VecDeque::from([s]);
    while let Some(v) = q.pop_front() {
        for w in out(v) {
            if d[w as usize] == u64::MAX {
                d[w as usize] = d[v as usize] + 1;
                at[d[w as usize] as usize - 1] += 1;
                q.push_back(w);
            }
        }
    }
    at.iter()
        .enumerate()
        .fold(0.0, |sum, (i, &c)| sum + c as f64 / (i + 1) as f64)
}

#[tokio::test]
async fn harmonic_centrality() {
    let t = run("CALL harmonic(E) YIELD node, score RETURN node, score").await;
    assert_eq!(t.float_columns, [1]);
    assert_eq!(t.rows.len(), N);
    for r in 0..N {
        assert_eq!(t.rows[r][0], r as u64);
        assert_eq!(t.float(r, 1), Some(harmonic(r as u64)), "{r}");
    }
    // 0 reaches 1, 2, 3 and 4 at 1, 2, 3 and 4 hops.
    assert_eq!(harmonic(0), 1.0 + 0.5 + 1.0 / 3.0 + 0.25);
    assert_eq!(harmonic(5), 3.0);
    // The other spellings, a WHERE on the score and a MATCH on the node.
    for name in ["harmonicCentrality", "gds.closeness.harmonic.stream"] {
        let t = run(&format!(
            "CALL {name}(E) YIELD node, score WHERE score > 2.5 RETURN node"
        ))
        .await;
        let want: Vec<Vec<u64>> = (0..N as u64)
            .filter(|&v| harmonic(v) > 2.5)
            .map(|v| vec![v])
            .collect();
        assert!(!want.is_empty() && want.len() < N);
        assert_eq!(t.rows, want, "{name}");
    }
    let t =
        run("CALL harmonic(E) YIELD node, score MATCH (node)-[:E]->(m) WHERE m = 9 RETURN node")
            .await;
    assert_eq!(t.rows, vec![vec![9]]);
    // The modes: exact, auto (exact on a graph this small), estimate (HyperBall; with
    // 2^10 registers sets this small are counted almost exactly).
    for q in ["CALL harmonic(E, exact)", "CALL harmonic(E, auto)"] {
        let t = run(q).await;
        for r in 0..N {
            assert_eq!(t.float(r, 1), Some(harmonic(r as u64)), "{q} {r}");
        }
    }
    for q in [
        "CALL harmonic(E, estimate, 10)",
        "CALL harmonic(E, hyperball, 10)",
    ] {
        let t = run(q).await;
        for r in 0..N {
            let (g, w) = (t.float(r, 1).unwrap(), harmonic(r as u64));
            assert!((g - w).abs() <= 0.05 * w + 1e-9, "{q} {r}: {g} for {w}");
        }
    }
    // Refused.
    for q in [
        "CALL harmonic(E, fast)",
        "CALL harmonic(E, exact, 8)",
        "CALL harmonic(E, estimate, 3)",
        "CALL harmonic(E, estimate, 8, 1)",
        "CALL harmonic(E, 3)",
        "CALL harmonic()",
        "CALL harmonic(NOPE)",
        "CALL harmonic(E) YIELD rank",
    ] {
        assert!(
            matches!(
                lower(&parse(q).unwrap(), &catalog()).err(),
                Some(GqlError::Semantic(_))
            ),
            "{q}"
        );
    }
}

#[tokio::test]
async fn ktruss() {
    let clique: Vec<Vec<u64>> = (5..9u64)
        .flat_map(|a| (a + 1..9).map(move |b| vec![a, b, 2]))
        .collect();
    let t =
        run("CALL ktruss(E, 4) YIELD source, target, support RETURN source, target, support").await;
    assert_eq!(t.rows, clique);
    // 3: the two triangles too (each edge in one), the edges taken both ways
    let mut want = clique.clone();
    for (a, b) in [(0, 1), (0, 2), (1, 2), (2, 3), (2, 4), (3, 4)] {
        want.push(vec![a, b, 1]);
    }
    want.sort();
    let t = run("CALL truss(E, 3)").await;
    assert_eq!(t.rows, want);
    // source and target are nodes: the kept edges that run from source to target
    let t = run("CALL ktruss(E, 3) YIELD source, target MATCH (source)-[:E]->(target) RETURN source, target").await;
    let mut one_way: Vec<Vec<u64>> = want
        .iter()
        .filter(|r| E.contains(&(r[0], r[1])))
        .map(|r| r[..2].to_vec())
        .collect();
    one_way.dedup();
    assert_eq!(one_way.len(), 10);
    assert_eq!(t.rows, one_way);
    assert!(run("CALL ktruss(E, 5)").await.rows.is_empty());
    for q in [
        "CALL ktruss(E)",
        "CALL ktruss(E, 3, 4)",
        "CALL ktruss(3)",
        "CALL ktruss(E, 3) YIELD node",
    ] {
        assert!(
            matches!(
                lower(&parse(q).unwrap(), &catalog()).err(),
                Some(GqlError::Semantic(_))
            ),
            "{q}"
        );
    }
}

#[tokio::test]
async fn maximal_independent_set() {
    let near = |a: u64, b: u64| a != b && (E.contains(&(a, b)) || E.contains(&(b, a)));
    for (q, seed) in [
        ("CALL mis(E)", 0u64),
        ("CALL mis(E, 7) YIELD node", 7),
        ("CALL maximalIndependentSet(E, 7) YIELD node RETURN node", 7),
    ] {
        let t = run(q).await;
        let set: Vec<u64> = t.rows.iter().map(|r| r[0]).collect();
        // vertices 0..13: every one either in or next to one in (9 and 12 have only
        // self-loops: in)
        for &a in &set {
            assert!(!set.iter().any(|&b| near(a, b)), "{q}: {set:?}");
        }
        for v in (0..N as u64).filter(|v| !set.contains(v)) {
            assert!(
                set.iter().any(|&b| near(v, b)),
                "{q}: {v} could join {set:?}"
            );
        }
        assert!(set.contains(&9) && set.contains(&12), "{q}");
        // the same set again for the seed
        let again: Vec<u64> = run(&format!("CALL mis(E, {seed})"))
            .await
            .rows
            .iter()
            .map(|r| r[0])
            .collect();
        assert_eq!(again, set);
    }
    // the node is a node: its edges
    let t = run("CALL mis(E, 3) YIELD node MATCH (node)-[:E]->(m) WHERE m = 11 RETURN node").await;
    assert_eq!(
        t.rows.len(),
        usize::from(run("CALL mis(E, 3)").await.rows.contains(&vec![10]))
    );
    for q in [
        "CALL mis()",
        "CALL mis(E, 1, 2)",
        "CALL mis(E, weight)",
        "CALL mis(E) YIELD score",
    ] {
        assert!(
            matches!(
                lower(&parse(q).unwrap(), &catalog()).err(),
                Some(GqlError::Semantic(_))
            ),
            "{q}"
        );
    }
}

#[tokio::test]
async fn truss_numbers() {
    // every edge once (source below target), self-loops out: the clique's 4, the two
    // triangles' 3, the pair's 2
    let mut want: Vec<Vec<u64>> = (5..9u64)
        .flat_map(|a| (a + 1..9).map(move |b| vec![a, b, 4]))
        .collect();
    for (a, b) in [(0, 1), (0, 2), (1, 2), (2, 3), (2, 4), (3, 4)] {
        want.push(vec![a, b, 3]);
    }
    want.push(vec![10, 11, 2]);
    want.sort();
    for q in [
        "CALL trussNumbers(E) YIELD source, target, truss RETURN source, target, truss",
        "CALL gds.trussDecomposition.stream(E)",
    ] {
        let mut t = run(q).await;
        t.rows.sort();
        assert_eq!(t.rows, want, "{q}");
    }
    // each edge's truss number is the largest k whose k-truss holds it
    for k in 2..6u64 {
        let q = format!("CALL ktruss(E, {k}) YIELD source, target RETURN source, target");
        let mut kept = run(&q).await.rows;
        kept.sort();
        let held: Vec<Vec<u64>> = want
            .iter()
            .filter(|r| r[2] >= k)
            .map(|r| r[..2].to_vec())
            .collect();
        assert_eq!(kept, held, "k {k}");
    }
    for q in [
        "CALL trussNumbers(E, 3)",
        "CALL trussNumbers()",
        "CALL trussNumbers(E) YIELD support",
    ] {
        assert!(
            matches!(
                lower(&parse(q).unwrap(), &catalog()).err(),
                Some(GqlError::Semantic(_))
            ),
            "{q}"
        );
    }
}