mod tree;
use alloc::borrow::Cow;
use alloc::vec::Vec;
use sas_plus::{Fact, State, Task};
use crate::{Combine, Heuristic, Relaxation};
pub use tree::RelevanceParams;
use tree::{Label, Tree};
#[derive(Clone, Debug)]
pub struct RelevanceScore<'r> {
relaxation: Cow<'r, Relaxation>,
tree: Tree,
work: Work,
}
#[derive(Clone, Debug, Default)]
struct Work {
holds: Vec<bool>,
stack: Vec<(u32, u32)>,
done: Vec<(u32, Vec<(u32, f64)>)>,
acc: Vec<f64>,
touched: Vec<u32>,
is_touched: Vec<bool>,
}
impl RelevanceScore<'static> {
#[must_use]
pub fn new(task: &Task) -> Self {
Self::with_params(task, &RelevanceParams::default())
}
#[must_use]
pub fn with_params(task: &Task, params: &RelevanceParams) -> Self {
let relaxation = Relaxation::new(task);
let tree = Tree::explore(&relaxation, params);
Self {
relaxation: Cow::Owned(relaxation),
tree,
work: Work::default(),
}
}
}
impl<'r> RelevanceScore<'r> {
#[must_use]
pub fn with_relaxation(relaxation: &'r Relaxation, params: &RelevanceParams) -> Self {
Self {
tree: Tree::explore(relaxation, params),
relaxation: Cow::Borrowed(relaxation),
work: Work::default(),
}
}
#[must_use]
pub fn num_nodes(&self) -> usize {
self.tree.nodes.len()
}
#[must_use]
pub fn is_complete(&self) -> bool {
self.tree.complete
}
#[must_use]
pub fn scores(&mut self, state: &State) -> Vec<(Fact, f64)> {
self.root_scores(state)
.into_iter()
.map(|(f, s)| (self.relaxation.fact(f as usize), s))
.collect()
}
#[must_use]
pub fn value(&mut self, state: &State) -> Option<f64> {
self.relaxation.explore(state, Combine::Max).goal_cost()?;
Some(self.root_scores(state).iter().map(|&(_, s)| s).sum())
}
fn root_scores(&mut self, state: &State) -> Vec<(u32, f64)> {
let relaxation = &*self.relaxation;
let work = &mut self.work;
work.holds.clear();
work.holds.resize(relaxation.num_facts(), false);
for fact in relaxation
.state_facts(state)
.chain(relaxation.free_facts().iter().copied())
{
work.holds[fact as usize] = true;
}
work.acc.clear();
work.acc.resize(relaxation.num_facts(), 0.0);
work.is_touched.clear();
work.is_touched.resize(relaxation.num_facts(), false);
evaluate(&self.tree, work)
}
}
fn evaluate(tree: &Tree, work: &mut Work) -> Vec<(u32, f64)> {
work.stack.clear();
work.done.clear();
work.stack.push((0, 0));
while let Some(&mut (n, ref mut next)) = work.stack.last_mut() {
let node = &tree.nodes[n as usize];
let present = node.expanded && *next < node.num_children;
if present {
let child = node.first_child + *next;
*next += 1;
if !is_removed(tree, work, child) {
work.stack.push((child, 0));
}
continue;
}
work.stack.pop();
let scores = combine(tree, work, n);
work.done.push((n, scores));
}
work.done.pop().map(|(_, s)| s).unwrap_or_default()
}
fn is_removed(tree: &Tree, work: &Work, n: u32) -> bool {
matches!(tree.nodes[n as usize].label, Label::Fact(f) if work.holds[f as usize])
}
fn combine(tree: &Tree, work: &mut Work, n: u32) -> Vec<(u32, f64)> {
let node = tree.nodes[n as usize];
let split = work
.done
.iter()
.rposition(|&(c, _)| tree.nodes[c as usize].parent != n)
.map_or(0, |i| i + 1);
let children: Vec<(u32, Vec<(u32, f64)>)> = work.done.drain(split..).collect();
let fact_node = matches!(node.label, Label::Fact(_));
let k = f64::from(node.num_children.max(1));
for (_, scores) in &children {
for &(f, s) in scores {
touch(work, f);
let a = &mut work.acc[f as usize];
if fact_node {
*a += s / k;
} else {
*a = 1.0 - (1.0 - *a) * (1.0 - s);
}
}
}
if let Label::Fact(f) = node.label {
touch(work, f);
work.acc[f as usize] = 1.0;
}
work.touched.sort_unstable();
let Work {
touched,
is_touched,
acc,
..
} = work;
touched
.drain(..)
.map(|f| {
is_touched[f as usize] = false;
(f, core::mem::take(&mut acc[f as usize]))
})
.filter(|&(_, s)| s > 0.0)
.collect()
}
fn touch(work: &mut Work, f: u32) {
if !core::mem::replace(&mut work.is_touched[f as usize], true) {
work.touched.push(f);
}
}
impl Heuristic<State> for RelevanceScore<'_> {
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "a sum of probabilities, non-negative and far below u32::MAX"
)]
fn estimate(&mut self, state: &State) -> Option<u32> {
self.value(state).map(|v| (v + 0.5) as u32)
}
}