crates/kleene-plan/src/ids.rs
//! The vertex numbering of a graph stratum. A matrix, a frontier or a level vector is as
//! long as the number of vertices, so it is never sized by the largest id read from the
//! data: when the ids are dense enough, they are the vertices themselves (no copy, no
//! cost); else the distinct ids, sorted, are numbered `0..d` for the run and every answer
//! and proof is mapped back to them.
//!
//! The rule: the ids index directly when the largest is below `u32::MAX` and one past it
//! is at most `4 * cells + 65536`, `cells` the number of id values read (a bound on the
//! distinct ids that costs one pass for the largest); the matrix is then at most a few
//! times the input. Otherwise (a sentinel at `u32::MAX`, ids spread over the `u32` range,
//! typed codes past it) the ids are renumbered by rank, which keeps their order.
use std::borrow::Cow;
use std::sync::Arc;
use crate::error::PlanError;
use crate::facts::{Column, Facts};
use crate::rules::Value;
use crate::{Result, cols::narrow};
/// Room the direct numbering may take past four vertices per id read.
const SLACK: usize = 1 << 16;
/// How a graph stratum numbers its vertices.
#[derive(Clone, Debug)]
pub(crate) enum Ids {
/// The ids are the vertices `0..n`.
Direct(usize),
/// Vertex `k` is the id `ids[k]` (rising).
Ranked(Arc<[Value]>),
/// Vertex `k` is the id `base + k`, for `k` in `0..n` (a graph of one vertex type in a
/// set's id space, [`crate::Source::GraphAt`]).
Shifted { base: Value, n: usize },
}
impl Ids {
/// The numbering of the ids in `cols`, with vertices `0..min_n` kept when direct.
pub(crate) fn of(cols: &[&Column], min_n: usize) -> Result<Ids> {
let cells: usize = cols.iter().map(|c| c.len()).sum();
let max = cols.iter().filter(|c| !c.is_empty()).map(|c| c.max()).max();
let Some(max) = max else {
return Ok(Ids::Direct(min_n));
};
if max < u32::MAX as Value {
let n = (max as usize + 1).max(min_n);
if n <= 4 * cells + SLACK {
return Ok(Ids::Direct(n));
}
}
let mut ids: Vec<Value> = Vec::with_capacity(cells);
for c in cols {
ids.extend(c.iter());
}
ids.sort_unstable();
ids.dedup();
if ids.len() >= u32::MAX as usize {
return Err(PlanError::Program(format!(
"a graph stratum over {} distinct vertex ids (at most {} fit)",
ids.len(),
u32::MAX - 1
)));
}
Ok(Ids::Ranked(ids.into()))
}
/// The direct numbering `0..n` (a graph given whole).
pub(crate) fn direct(n: usize) -> Ids {
Ids::Direct(n)
}
/// Whether the ids were renumbered.
pub(crate) fn ranked(&self) -> bool {
matches!(self, Ids::Ranked(_))
}
/// Whether the ids are the vertices themselves.
fn direct_ids(&self) -> bool {
matches!(self, Ids::Direct(_))
}
/// The number of vertices.
pub(crate) fn n(&self) -> usize {
match self {
Ids::Direct(n) | Ids::Shifted { n, .. } => *n,
Ids::Ranked(ids) => ids.len(),
}
}
/// The vertex of id `v`, if it is one.
pub(crate) fn vertex(&self, v: Value) -> Option<u32> {
match self {
Ids::Direct(n) => (v < *n as Value).then_some(v as u32),
Ids::Ranked(ids) => ids.binary_search(&v).ok().map(|k| k as u32),
Ids::Shifted { base, n } => v
.checked_sub(*base)
.filter(|&k| k < *n as Value)
.map(|k| k as u32),
}
}
/// The id of vertex `k`.
pub(crate) fn id(&self, k: u32) -> Value {
match self {
Ids::Direct(_) => Value::from(k),
Ids::Ranked(ids) => ids[k as usize],
Ids::Shifted { base, .. } => base + Value::from(k),
}
}
/// The vertices of a column of ids (each one an id of the numbering).
pub(crate) fn vertices<'c>(&self, c: &'c Column) -> Result<Cow<'c, [u32]>> {
match self {
Ids::Direct(_) => c.to_u32(),
Ids::Ranked(_) | Ids::Shifted { .. } => c
.iter()
.map(|v| {
self.vertex(v).ok_or_else(|| {
PlanError::Program(format!("{v} is no vertex of the stratum"))
})
})
.collect::<Result<Vec<u32>>>()
.map(Cow::Owned),
}
}
/// A column of vertices as ids.
pub(crate) fn column(&self, vs: Vec<u32>) -> Column {
match self {
Ids::Direct(_) => Column::from(vs),
Ids::Ranked(ids) => narrow(vs.iter().map(|&k| ids[k as usize]), vs.len()),
Ids::Shifted { base, .. } => {
narrow(vs.iter().map(|&k| base + Value::from(k)), vs.len())
}
}
}
/// Facts of vertices as facts of ids, column by column.
pub(crate) fn facts(&self, f: Facts) -> Result<Facts> {
if self.direct_ids() {
return Ok(f);
}
let cols: Vec<Column> = (0..f.arity())
.map(|i| {
let c = f.column(i);
let v: Vec<Value> = c.iter().map(|k| self.id(k as u32)).collect();
narrow(v.iter().copied(), v.len())
})
.collect();
if cols.is_empty() {
return Ok(f);
}
Facts::from_columns(cols)
}
}