use alloc::vec::Vec;
use crate::Relaxation;
use crate::rng::SplitMix64;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Label {
Root,
Fact(u32),
Rule(u32),
}
#[derive(Clone, Copy, Debug)]
pub(super) struct Node {
pub label: Label,
pub parent: u32,
pub first_child: u32,
pub num_children: u32,
pub expanded: bool,
pub xi: f64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RelevanceParams {
pub min_nodes: usize,
pub rho: f64,
pub max_nodes: usize,
pub seed: u64,
}
impl Default for RelevanceParams {
fn default() -> Self {
Self {
min_nodes: 100_000,
rho: 0.2,
max_nodes: 400_000,
seed: 0,
}
}
}
#[derive(Clone, Debug)]
pub(super) struct Tree {
pub nodes: Vec<Node>,
pub complete: bool,
}
impl Tree {
pub fn explore(relaxation: &Relaxation, params: &RelevanceParams) -> Self {
let by_head = rules_by_head(relaxation);
let mut tree = Self {
nodes: alloc::vec![Node {
label: Label::Root,
parent: u32::MAX,
first_child: 0,
num_children: 0,
expanded: false,
xi: 1.0,
}],
complete: false,
};
let mut frontier = Frontier::default();
frontier.insert(0, 1.0);
let mut rng = SplitMix64(params.seed);
let mut total = 1.0;
while !frontier.is_empty() && tree.nodes.len() < params.max_nodes {
if tree.nodes.len() >= params.min_nodes && frontier.mass() <= params.rho * total {
break;
}
let start = frontier.choose(&mut rng);
let before = tree.nodes.len();
tree.dive(relaxation, &by_head, &mut frontier, &mut rng, start);
total += tree.nodes[before..].iter().map(|n| n.xi).sum::<f64>();
}
tree.complete = frontier.is_empty();
tree
}
fn dive(
&mut self,
relaxation: &Relaxation,
by_head: &[Vec<u32>],
frontier: &mut Frontier,
rng: &mut SplitMix64,
mut n: u32,
) {
loop {
frontier.remove(n);
let children = self.expand(relaxation, by_head, n);
if children.is_empty() {
return;
}
let mass: f64 = children.clone().map(|c| self.nodes[c as usize].xi).sum();
for c in children.clone() {
frontier.insert(c, self.nodes[c as usize].xi);
}
let mut pick = f64::from(u32::try_from(rng.next() >> 40).expect("24 bits"))
/ f64::from(1_u32 << 24)
* mass;
n = children.clone().last().expect("not empty");
for c in children {
pick -= self.nodes[c as usize].xi;
if pick < 0.0 {
n = c;
break;
}
}
}
}
fn expand(
&mut self,
relaxation: &Relaxation,
by_head: &[Vec<u32>],
n: u32,
) -> core::ops::Range<u32> {
let node = self.nodes[n as usize];
let labels = self.child_labels(relaxation, by_head, n);
let first = u32::try_from(self.nodes.len()).expect("fewer than 2^32 nodes");
let k = u32::try_from(labels.len()).expect("fewer than 2^32 children");
let xi = match node.label {
Label::Fact(_) => node.xi / f64::from(k.max(1)),
Label::Root | Label::Rule(_) => node.xi,
};
self.nodes.extend(labels.into_iter().map(|label| Node {
label,
parent: n,
first_child: 0,
num_children: 0,
expanded: false,
xi,
}));
let node = &mut self.nodes[n as usize];
node.expanded = true;
node.first_child = first;
node.num_children = k;
first..first + k
}
fn child_labels(&self, relaxation: &Relaxation, by_head: &[Vec<u32>], n: u32) -> Vec<Label> {
let to_fact = |f: usize| Label::Fact(u32::try_from(f).expect("fewer than 2^32 facts"));
match self.nodes[n as usize].label {
Label::Root => relaxation
.goal_facts()
.iter()
.map(|&g| to_fact(g))
.collect(),
Label::Rule(r) => {
let mut conditions = relaxation.rules()[r as usize].conditions.clone();
conditions.sort_unstable();
conditions.dedup();
conditions.into_iter().map(to_fact).collect()
}
Label::Fact(f) => {
let path = self.path_facts(n);
by_head[f as usize]
.iter()
.filter(|&&r| {
relaxation.rules()[r as usize]
.conditions
.iter()
.all(|c| path.binary_search(c).is_err())
})
.map(|&r| Label::Rule(r))
.collect()
}
}
}
fn path_facts(&self, mut n: u32) -> Vec<usize> {
let mut facts = Vec::new();
while n != u32::MAX {
let node = &self.nodes[n as usize];
if let Label::Fact(f) = node.label {
facts.push(f as usize);
}
n = node.parent;
}
facts.sort_unstable();
facts
}
}
fn rules_by_head(relaxation: &Relaxation) -> Vec<Vec<u32>> {
let mut by_head = alloc::vec![Vec::new(); relaxation.num_facts()];
for (r, rule) in relaxation.rules().iter().enumerate() {
by_head[rule.head].push(u32::try_from(r).expect("fewer than 2^32 rules"));
}
by_head
}
#[derive(Debug, Default)]
struct Frontier {
fenwick: Vec<f64>,
weight: Vec<f64>,
len: usize,
}
impl Frontier {
fn is_empty(&self) -> bool {
self.len == 0
}
fn mass(&self) -> f64 {
self.prefix(self.weight.len())
}
fn insert(&mut self, n: u32, w: f64) {
let i = n as usize;
if i >= self.weight.len() {
self.grow(i + 1);
}
self.add(i, w - self.weight[i]);
if self.weight[i] == 0.0 {
self.len += 1;
}
self.weight[i] = w;
}
fn remove(&mut self, n: u32) {
let i = n as usize;
if i < self.weight.len() && self.weight[i] != 0.0 {
self.add(i, -self.weight[i]);
self.weight[i] = 0.0;
self.len -= 1;
}
}
fn choose(&self, rng: &mut SplitMix64) -> u32 {
let total = self.prefix(self.weight.len());
let mut pick = f64::from(u32::try_from(rng.next() >> 40).expect("24 bits"))
/ f64::from(1_u32 << 24)
* total;
let mut pos = 0;
let mut step = self.fenwick.len().next_power_of_two();
while step > 0 {
let next = pos + step;
if next < self.fenwick.len() && self.fenwick[next] <= pick {
pick -= self.fenwick[next];
pos = next;
}
step /= 2;
}
let found = (pos..self.weight.len())
.chain(0..pos)
.find(|&i| self.weight[i] != 0.0)
.expect("the frontier is not empty");
u32::try_from(found).expect("fewer than 2^32 nodes")
}
fn add(&mut self, i: usize, delta: f64) {
let mut j = i + 1;
while j < self.fenwick.len() {
self.fenwick[j] += delta;
j += j & j.wrapping_neg();
}
}
fn prefix(&self, i: usize) -> f64 {
let mut sum = 0.0;
let mut j = i;
while j > 0 {
sum += self.fenwick[j];
j -= j & j.wrapping_neg();
}
sum
}
fn grow(&mut self, len: usize) {
let capacity = len.next_power_of_two().max(16);
self.weight.resize(capacity, 0.0);
self.fenwick = alloc::vec![0.0; capacity + 1];
for i in 0..capacity {
let w = self.weight[i];
if w != 0.0 {
self.add(i, w);
}
}
}
}