use alloc::borrow::Cow;
use alloc::vec::Vec;
use sas_plus::{Fact, OpId, State, Task};
use super::heuristics::{round_up_admissible, to_f64};
use super::ordered::{OrderedLandmarks, OrderingKind};
use crate::{PathHeuristic, Relaxation};
const WORD: usize = 64;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TrackingMode {
Count,
UniformCost,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct AcceptedLandmarks {
bits: Vec<u64>,
}
impl AcceptedLandmarks {
#[must_use]
pub fn is_accepted(&self, i: usize) -> bool {
self.bits
.get(i / WORD)
.is_some_and(|w| w & (1 << (i % WORD)) != 0)
}
#[must_use]
pub fn len(&self) -> usize {
self.bits.iter().map(|w| w.count_ones() as usize).sum()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.bits.iter().all(|&w| w == 0)
}
fn accept(&mut self, i: usize) {
self.bits[i / WORD] |= 1 << (i % WORD);
}
}
#[derive(Clone, Debug)]
pub struct LandmarkTracker<'r> {
relaxation: Cow<'r, Relaxation>,
mode: TrackingMode,
landmarks: Vec<Vec<usize>>,
facts: Vec<Vec<Fact>>,
parents: Vec<Vec<usize>>,
greedy_children: Vec<Vec<usize>>,
goal: Vec<bool>,
pub(super) by_axiom: Vec<bool>,
pub(super) achievers: Vec<Vec<OpId>>,
pub(super) costs: Vec<u64>,
shares: Vec<u32>,
pub(super) pending: Vec<usize>,
}
impl LandmarkTracker<'static> {
#[must_use]
pub fn for_task(task: &Task, mode: TrackingMode) -> Option<Self> {
let relaxation = Relaxation::new(task);
let state = task.initial_state();
let mut graph = relaxation.rhw_landmarks(&state)?;
graph.add_reasonable_orderings(&relaxation, &state);
Some(Self::build(Cow::Owned(relaxation), &graph, mode))
}
}
impl<'r> LandmarkTracker<'r> {
#[must_use]
pub fn new(relaxation: &'r Relaxation, graph: &OrderedLandmarks, mode: TrackingMode) -> Self {
Self::build(Cow::Borrowed(relaxation), graph, mode)
}
fn build(
relaxation: Cow<'r, Relaxation>,
graph: &OrderedLandmarks,
mode: TrackingMode,
) -> Self {
let n = graph.landmarks().len();
let mut parents = alloc::vec![Vec::new(); n];
let mut greedy_children = alloc::vec![Vec::new(); n];
for o in graph.orderings() {
parents[o.after].push(o.before);
if o.kind == OrderingKind::GreedyNecessary {
greedy_children[o.before].push(o.after);
}
}
let mut fact_ops = alloc::vec![Vec::new(); relaxation.num_facts()];
let mut fact_axiom = alloc::vec![false; relaxation.num_facts()];
for rule in relaxation.rules() {
match rule.op {
Some(op) => fact_ops[rule.head].push(op),
None => fact_axiom[rule.head] = true,
}
}
let landmarks: Vec<Vec<usize>> = graph.landmarks().to_vec();
let facts = landmarks
.iter()
.map(|l| l.iter().map(|&f| relaxation.fact(f)).collect())
.collect();
let achievers = landmarks
.iter()
.map(|l| {
let mut ops: Vec<OpId> = l
.iter()
.flat_map(|&f| fact_ops[f].iter().copied())
.collect();
ops.sort_unstable();
ops.dedup();
ops
})
.collect();
let goal = landmarks
.iter()
.map(|l| l.len() == 1 && relaxation.goal_facts().binary_search(&l[0]).is_ok())
.collect();
let by_axiom = landmarks
.iter()
.map(|l| l.iter().any(|&f| fact_axiom[f]))
.collect();
let costs = (0..relaxation.num_operators())
.map(|op| relaxation.op_rules(op).first().map_or(0, |r| r.cost))
.collect();
Self {
relaxation,
mode,
landmarks,
facts,
parents,
greedy_children,
goal,
by_axiom,
achievers,
costs,
shares: Vec::new(),
pending: Vec::new(),
}
}
fn holds(&self, i: usize, state: &State) -> bool {
self.facts[i].iter().any(|f| state.0[f.var] == f.value)
}
fn empty(&self) -> AcceptedLandmarks {
AcceptedLandmarks {
bits: alloc::vec![0; self.landmarks.len().div_ceil(WORD)],
}
}
fn collect_pending(&mut self, state: &State, info: &AcceptedLandmarks) {
let mut pending = core::mem::take(&mut self.pending);
pending.clear();
for i in 0..self.landmarks.len() {
let needed =
!info.is_accepted(i) || (!self.holds(i, state) && self.required_again(i, info));
if needed {
pending.push(i);
}
}
self.pending = pending;
}
fn required_again(&self, i: usize, info: &AcceptedLandmarks) -> bool {
self.goal[i]
|| self.greedy_children[i]
.iter()
.any(|&c| !info.is_accepted(c))
}
fn unachievable(&self, i: usize) -> bool {
let free = self.relaxation.free_facts();
self.achievers[i].is_empty()
&& !self.by_axiom[i]
&& !self.landmarks[i]
.iter()
.any(|&f| free.iter().any(|&x| x as usize == f))
}
fn uniform_cost(&mut self) -> u64 {
self.shares.clear();
self.shares.resize(self.costs.len(), 0);
for &i in &self.pending {
for &op in &self.achievers[i] {
self.shares[op] += 1;
}
}
let sum: f64 = self
.pending
.iter()
.filter(|&&i| !self.by_axiom[i])
.map(|&i| {
self.achievers[i]
.iter()
.map(|&op| to_f64(self.costs[op]) / f64::from(self.shares[op]))
.fold(f64::INFINITY, f64::min)
})
.filter(|share| share.is_finite())
.sum();
round_up_admissible(sum)
}
}
impl PathHeuristic<State, OpId, u32> for LandmarkTracker<'_> {
type Info = AcceptedLandmarks;
fn root(&mut self, state: &State) -> AcceptedLandmarks {
let mut accepted = self.empty();
for i in 0..self.landmarks.len() {
if self.holds(i, state) {
accepted.accept(i);
}
}
accepted
}
fn on_expand(
&mut self,
_parent: &State,
parent_info: &AcceptedLandmarks,
_op: OpId,
child: &State,
) -> AcceptedLandmarks {
let mut accepted = parent_info.clone();
for i in 0..self.landmarks.len() {
if accepted.is_accepted(i) || !self.holds(i, child) {
continue;
}
let ready = self.mode == TrackingMode::UniformCost
|| self.parents[i].iter().all(|&p| parent_info.is_accepted(p));
if ready {
accepted.accept(i);
}
}
accepted
}
fn merge(&mut self, kept: &mut AcceptedLandmarks, other: &AcceptedLandmarks) {
for (k, &o) in kept.bits.iter_mut().zip(&other.bits) {
*k &= o;
}
}
fn estimate(&mut self, state: &State, info: &AcceptedLandmarks) -> Option<u32> {
self.collect_pending(state, info);
let value = match self.mode {
TrackingMode::Count => self.pending.len() as u64,
TrackingMode::UniformCost => {
if self.pending.iter().any(|&i| self.unachievable(i)) {
return None;
}
self.uniform_cost()
}
};
Some(u32::try_from(value).unwrap_or(u32::MAX))
}
}