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

nordisk/kleene

crates/kleene-datalog/tests/sssp_weights.rs

//! Shortest paths with a weight key from the Datalog side: the edges and their weights read
//! by name from a catalog (`road`, `road.len`: the weight key as the core's catalog gives
//! it), the procedure over them; against a plain Dijkstra.

use std::collections::BTreeMap;
use std::sync::Arc;

use arrow_array::{ArrayRef, UInt64Array};
use kleene_datalog::{Catalog, Engine, Inputs, Procedure, Program, Source};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, Csr};

const ROADS: [(u32, u32, u64); 7] = [
    (0, 1, 4),
    (0, 2, 1),
    (2, 1, 2),
    (1, 3, 1),
    (2, 3, 5),
    (3, 4, 3),
    (4, 0, 1),
];
const N: usize = 6;

fn dijkstra(s: u32) -> BTreeMap<u64, u64> {
    let mut d: BTreeMap<u64, u64> = BTreeMap::from([(s as u64, 0)]);
    loop {
        let mut changed = false;
        for &(a, b, w) in &ROADS {
            if let Some(&da) = d.get(&(a as u64)) {
                let nd = da + w;
                if d.get(&(b as u64)).is_none_or(|&x| nd < x) {
                    d.insert(b as u64, nd);
                    changed = true;
                }
            }
        }
        if !changed {
            return d;
        }
    }
}

#[tokio::test]
async fn shortest_paths_by_a_weight_key_of_the_catalog() {
    let (s, d): (Vec<u32>, Vec<u32>) = ROADS.iter().map(|r| (r.0, r.1)).unzip();
    let out = Csr::from_edges(N, N, &s, &d, None, BoolOrAnd).unwrap();
    let u = |v: Vec<u64>| -> ArrayRef { Arc::new(UInt64Array::from(v)) };
    let mut c = Catalog::new();
    c.edge(
        "road",
        Source::Graph {
            inn: Some(out.transpose()),
            out,
        },
    )
    .edge_property(
        "road",
        "len",
        Source::Columns(vec![
            u(ROADS.iter().map(|r| r.0 as u64).collect()),
            u(ROADS.iter().map(|r| r.1 as u64).collect()),
            u(ROADS.iter().map(|r| r.2).collect()),
        ]),
    );
    let mut p = Program::new();
    let road = p.input_from::<2>(&c, "road").unwrap();
    let len = p.input_from::<3>(&c, "road.len").unwrap();
    let dist = p.derived::<2>("dist");
    p.procedure(
        &dist,
        &road,
        Procedure::Sssp {
            source: 0,
            weights: Some(len.id()),
        },
    )
    .unwrap();
    let mut inputs = Inputs::new();
    inputs.bind(&p, &c).unwrap();
    let got: BTreeMap<u64, u64> = Engine::<CpuBackend>::new(CpuDevice::new(2))
        .run(&p, &inputs)
        .await
        .unwrap()
        .get(&dist)
        .unwrap()
        .rows()
        .map(|r| (r[0], r[1]))
        .collect();
    assert_eq!(got, dijkstra(0));
}