use relate_ir::{Direction, Expr, NodePattern, PatternElement, RelPattern};
use relate_planner::{endpoint_estimate, seed_rows, DegreeMoments, PatternStats};
const WALKER_NS_PER_TRAIL: f64 = 1490.0;
const FRONTIER_NS_PER_PAIR: f64 = 2240.0;
const FRONTIER_NS_PER_PROBE: f64 = 65.0;
pub(super) const MAX_ESTIMATE_HOPS: usize = 1024;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct CostEstimate {
pub(super) trails: f64,
pub(super) pairs: f64,
pub(super) probes: f64,
}
impl CostEstimate {
pub(super) fn frontier_wins(self) -> bool {
WALKER_NS_PER_TRAIL * self.trails
> FRONTIER_NS_PER_PAIR * self.pairs + FRONTIER_NS_PER_PROBE * self.probes
}
}
pub(super) fn frontier_engages(
stats: &dyn PatternStats,
population: u128,
conjuncts: &[Expr],
start: &NodePattern,
target: &NodePattern,
elements: &[PatternElement],
) -> bool {
let Some(hops) = expand_max_hops(elements) else {
return true;
};
let unbound = |_: &str| false;
let seeds = seed_rows(endpoint_estimate(start, &unbound, conjuncts.iter(), stats));
let endpoints =
seed_rows(endpoint_estimate(target, &unbound, conjuncts.iter(), stats)).min(population);
estimate(stats, population, seeds, endpoints, start, &hops)
.is_some_and(CostEstimate::frontier_wins)
}
pub(super) fn estimate(
stats: &dyn PatternStats,
population: u128,
seeds: u128,
endpoints: u128,
start: &NodePattern,
hops: &Expansion<'_>,
) -> Option<CostEstimate> {
let (&first, rest) = hops.sequence.split_first()?;
let first = hops.distinct[first];
let start_population = start
.labels
.iter()
.filter_map(|label| stats.label_rows(label))
.min()
.map_or(population, u128::from);
let first_degrees = first_hop_degree_sum(stats, start, first)?;
let seeds = seeds as f64;
let mut level = seeds * mean_degree(first_degrees, start_population);
let mut trails = level;
let mut fanouts: Vec<Option<f64>> = vec![None; hops.distinct.len()];
for &index in rest {
let fanout = match fanouts[index] {
Some(fanout) => fanout,
None => {
let rel = hops.distinct[index];
let landing = stats.degree_moments(&[], &rel.types)?;
let fanout = excess_degree(landing) * sides(rel);
fanouts[index] = Some(fanout);
fanout
}
};
level *= fanout;
trails += level;
}
let adjacency = stats.degree_moments(&[], &first.types)?.sum as f64 * sides(first);
Some(CostEstimate {
trails,
pairs: trails.min(seeds * endpoints as f64),
probes: trails.min(seeds * adjacency),
})
}
fn first_hop_degree_sum(
stats: &dyn PatternStats,
start: &NodePattern,
first: &RelPattern,
) -> Option<u128> {
let out = || {
stats
.degree_moments(&start.labels, &first.types)
.map(|moments| moments.sum)
};
let inbound = || stats.in_degree_sum(&start.labels, &first.types);
match first.direction {
Direction::Outgoing => out(),
Direction::Incoming => inbound(),
Direction::Both => Some(out()?.saturating_add(inbound()?)),
}
}
fn sides(rel: &RelPattern) -> f64 {
match rel.direction {
Direction::Both => 2.0,
Direction::Outgoing | Direction::Incoming => 1.0,
}
}
pub(super) fn mean_degree(degree_sum: u128, nodes: u128) -> f64 {
if nodes == 0 {
return 0.0;
}
degree_sum as f64 / nodes as f64
}
pub(super) fn excess_degree(moments: DegreeMoments) -> f64 {
if moments.sum == 0 {
return 0.0;
}
(moments.sum_sq as f64 / moments.sum as f64 - 1.0).max(0.0)
}
#[derive(Debug, Default)]
pub(super) struct Expansion<'a> {
distinct: Vec<&'a RelPattern>,
sequence: Vec<usize>,
}
impl<'a> Expansion<'a> {
#[cfg(test)]
pub(super) fn chain(rels: &[&'a RelPattern]) -> Self {
Expansion {
distinct: rels.to_vec(),
sequence: (0..rels.len()).collect(),
}
}
#[cfg(test)]
pub(super) fn repeat(rel: &'a RelPattern, count: usize) -> Self {
Expansion {
distinct: vec![rel],
sequence: vec![0; count],
}
}
#[cfg(test)]
pub(super) fn hops(&self) -> usize {
self.sequence.len()
}
fn reserve(&self, extra: usize) -> Option<()> {
if self.sequence.len().checked_add(extra)? > MAX_ESTIMATE_HOPS {
return None;
}
Some(())
}
fn push(&mut self, index: usize) -> Option<()> {
self.reserve(1)?;
self.sequence.push(index);
Some(())
}
fn push_rel(&mut self, rel: &'a RelPattern) -> Option<()> {
let index = self.distinct.len();
self.push(index)?;
self.distinct.push(rel);
Some(())
}
fn repeat_from(&mut self, start: usize, times: u32) -> Option<()> {
let end = self.sequence.len();
let times = times as usize;
if times == 0 {
self.sequence.truncate(start);
return Some(());
}
self.reserve((end - start).checked_mul(times - 1)?)?;
for _ in 1..times {
self.sequence.extend_from_within(start..end);
}
Some(())
}
}
pub(super) fn expand_max_hops(elements: &[PatternElement]) -> Option<Expansion<'_>> {
let mut hops = Expansion::default();
expand_into(elements, &mut hops)?;
Some(hops)
}
fn expand_into<'a>(elements: &'a [PatternElement], hops: &mut Expansion<'a>) -> Option<()> {
for element in elements {
match element {
PatternElement::Node(_) => {}
PatternElement::Relationship(rel) => hops.push_rel(rel)?,
PatternElement::Quantified(qpp) => {
let max = qpp.max?;
let start = hops.sequence.len();
expand_into(&qpp.elements, hops)?;
hops.repeat_from(start, max)?;
}
}
}
Some(())
}