mod dominance;
mod reconstruct;
mod stubborn;
use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::vec;
use alloc::vec::Vec;
use core::cmp::Reverse;
use sas_plus::{Task, Value};
use crate::decoupled::{DecoupledState, DecoupledTask, Price};
use crate::{DecoupledHeuristic, Error, Factoring, Plan};
use dominance::{Bounds, Dominance, simulation};
use stubborn::StubbornSets;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Order {
Cost,
Greedy,
Anytime,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Pruning {
Basic,
Frontier,
EffectivePrices,
Simulation,
EffectiveSimulation,
#[default]
Adaptive,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Leaves {
#[default]
Priced,
Reachability,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Config {
pub pruning: Pruning,
pub fold_g: bool,
pub leaves: Leaves,
pub max_analysis_states: usize,
pub reduce_leaves: bool,
pub stubborn_sets: bool,
}
impl Default for Config {
fn default() -> Self {
Self {
pruning: Pruning::default(),
fold_g: true,
leaves: Leaves::default(),
max_analysis_states: 256,
reduce_leaves: false,
stubborn_sets: false,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Statistics {
pub expanded: u64,
pub generated: u64,
pub dominated: u64,
pub dead_ends: u64,
pub stored: u64,
pub simulated_leaves: u64,
pub reduced_leaf_transitions: u64,
pub bound_pruned: u64,
pub unreachable_leaf_states: u64,
pub stubborn_pruned: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Outcome {
pub plan: Option<Plan>,
pub statistics: Statistics,
}
#[derive(Debug)]
struct Node {
state: DecoupledState,
g: Price,
parent: Option<(usize, usize)>,
bounds: Option<Bounds>,
}
struct Search<'t> {
task: &'t DecoupledTask,
heuristic: Option<&'t dyn DecoupledHeuristic>,
root: Option<&'t dyn DecoupledHeuristic>,
min_goal_price: Price,
order: Order,
dominance: Dominance,
nodes: Vec<Node>,
open: BinaryHeap<Reverse<(Price, usize)>>,
by_center: BTreeMap<Vec<Value>, Vec<usize>>,
best: Option<(Price, usize)>,
statistics: Statistics,
limit: Option<u64>,
probe: Probe,
stubborn: Option<StubbornSets>,
}
pub fn search(task: &Task, factoring: &Factoring) -> Result<Option<Plan>, Error> {
Config::default()
.search(task, factoring)
.map(|outcome| outcome.plan)
}
pub fn astar(
task: &Task,
factoring: &Factoring,
heuristic: &(impl DecoupledHeuristic + ?Sized),
) -> Result<Option<Plan>, Error> {
Config::default()
.astar(task, factoring, heuristic)
.map(|outcome| outcome.plan)
}
pub fn gbfs(
task: &Task,
factoring: &Factoring,
heuristic: &(impl DecoupledHeuristic + ?Sized),
) -> Result<Option<Plan>, Error> {
Config::default()
.gbfs(task, factoring, heuristic)
.map(|outcome| outcome.plan)
}
impl Config {
pub fn search(&self, task: &Task, factoring: &Factoring) -> Result<Outcome, Error> {
self.run(task, factoring, (None, None), Order::Cost)
}
pub fn astar(
&self,
task: &Task,
factoring: &Factoring,
heuristic: &(impl DecoupledHeuristic + ?Sized),
) -> Result<Outcome, Error> {
self.run(task, factoring, (Some(&heuristic), None), Order::Cost)
}
pub fn gbfs(
&self,
task: &Task,
factoring: &Factoring,
heuristic: &(impl DecoupledHeuristic + ?Sized),
) -> Result<Outcome, Error> {
self.run(task, factoring, (Some(&heuristic), None), Order::Greedy)
}
pub fn anytime_astar(
&self,
task: &Task,
factoring: &Factoring,
root: &(impl DecoupledHeuristic + ?Sized),
fork: &(impl DecoupledHeuristic + ?Sized),
) -> Result<Outcome, Error> {
self.run(task, factoring, (Some(&fork), Some(&root)), Order::Anytime)
}
fn run(
&self,
task: &Task,
factoring: &Factoring,
(heuristic, root): (
Option<&dyn DecoupledHeuristic>,
Option<&dyn DecoupledHeuristic>,
),
order: Order,
) -> Result<Outcome, Error> {
self.probe(task, factoring, (heuristic, root), order, None)
.map(|(outcome, _)| outcome)
}
fn probe(
&self,
task: &Task,
factoring: &Factoring,
(heuristic, root): (
Option<&dyn DecoupledHeuristic>,
Option<&dyn DecoupledHeuristic>,
),
order: Order,
limit: Option<u64>,
) -> Result<(Outcome, Probe), Error> {
let mut decoupled = DecoupledTask::new(task, factoring)?;
if self.leaves == Leaves::Reachability {
if order != Order::Greedy {
return Err(Error::ReachabilityNotOptimal);
}
decoupled = decoupled.into_reachability_only();
}
let dominance = Dominance::new(&decoupled, self, order == Order::Greedy);
let mut statistics = Statistics::default();
if self.reduce_leaves {
reduce_leaves(&mut decoupled, &dominance, &mut statistics);
}
let min_goal_price = if order == Order::Anytime {
min_goal_price(&decoupled)
} else {
0
};
let stubborn = self
.stubborn_sets
.then(|| StubbornSets::new(task, &decoupled))
.flatten();
let mut search = Search {
task: &decoupled,
heuristic,
root,
min_goal_price,
order,
dominance,
nodes: Vec::new(),
open: BinaryHeap::new(),
by_center: BTreeMap::new(),
best: None,
statistics,
limit,
probe: Probe::default(),
stubborn,
};
search.run();
search.statistics.simulated_leaves = search.dominance.simulated_leaves();
let plan = search.best.map(|(cost, id)| {
let plan = reconstruct::plan(&decoupled, &search.path(id), cost);
with_true_cost(task, plan, decoupled.is_reachability_only())
});
let outcome = Outcome {
plan,
statistics: search.statistics,
};
Ok((outcome, search.probe))
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Probe {
pub(crate) cut_off: bool,
pub(crate) work: u64,
pub(crate) initial_h: Option<Price>,
pub(crate) best_h: Option<Price>,
}
pub(crate) fn sample(
task: &Task,
factoring: &Factoring,
optimal: bool,
expansions: u64,
) -> Result<(Probe, u64), Error> {
let config = Config::default();
let (outcome, probe) = if optimal {
let h = crate::HMax::new(task);
config.probe(
task,
factoring,
(Some(&h), None),
Order::Cost,
Some(expansions),
)?
} else {
let h = crate::HFf::new(task);
config.probe(
task,
factoring,
(Some(&h), None),
Order::Greedy,
Some(expansions),
)?
};
Ok((probe, outcome.statistics.expanded))
}
impl Config {
pub fn reduced_task(&self, task: &Task, factoring: &Factoring) -> Result<Task, Error> {
let mut decoupled = DecoupledTask::new(task, factoring)?;
let config = Config {
reduce_leaves: true,
..*self
};
let dominance = Dominance::new(&decoupled, &config, false);
reduce_leaves(&mut decoupled, &dominance, &mut Statistics::default());
let mut removed = vec![false; task.operators.len()];
for (index, leaf) in decoupled.leaves.iter().enumerate() {
if dominance.simulators(index).is_none() {
continue;
}
let parts: Vec<_> = decoupled
.globals
.iter()
.filter_map(|g| g.parts[index].as_ref())
.collect();
let live = simulation::live_actions(leaf, &parts);
for (action, live) in leaf.actions.iter().zip(live) {
removed[action.op] |= !live;
}
}
let mut reduced = task.clone();
let mut keep = removed.iter().map(|&r| !r);
reduced.operators.retain(|_| keep.next().unwrap_or(true));
Ok(reduced)
}
}
fn min_goal_price(task: &DecoupledTask) -> Price {
task.leaves
.iter()
.enumerate()
.map(|(index, leaf)| {
let parts: Vec<_> = task
.globals
.iter()
.filter_map(|g| g.parts[index].as_ref())
.collect();
if leaf.reads_center(parts.iter().copied()) {
return 0;
}
simulation::cheapest_goal(leaf, &parts).unwrap_or(Price::MAX)
})
.fold(0, Price::saturating_add)
}
fn reduce_leaves(task: &mut DecoupledTask, dominance: &Dominance, statistics: &mut Statistics) {
let widen = |n: usize| u64::try_from(n).unwrap_or(u64::MAX);
for leaf in 0..task.leaves.len() {
let Some(rel) = dominance.simulators(leaf) else {
continue;
};
let parts: Vec<_> = task
.globals
.iter()
.filter_map(|g| g.parts[leaf].as_ref())
.collect();
let (disabled, lost) = simulation::redundant_transitions(&task.leaves[leaf], &parts, rel);
statistics.reduced_leaf_transitions += widen(disabled.iter().filter(|&&d| d).count());
statistics.unreachable_leaf_states += widen(lost);
task.leaves[leaf].disabled = disabled;
}
}
fn with_true_cost(task: &Task, mut plan: Plan, reachability_only: bool) -> Plan {
let summed = plan
.ops
.iter()
.map(|&op| u64::from(task.operators[op].cost))
.sum();
debug_assert!(
reachability_only || summed == plan.cost,
"search cost {} differs from plan cost {summed}",
plan.cost
);
plan.cost = summed;
plan
}
impl Search<'_> {
fn run(&mut self) {
self.insert(self.task.initial(), 0, None);
while let Some(Reverse((key, id))) = self.open.pop() {
if self.is_done(key) {
break;
}
if self
.limit
.is_some_and(|limit| self.statistics.expanded >= limit)
{
self.probe.cut_off = true;
break;
}
self.statistics.expanded += 1;
let node = &self.nodes[id];
let g = node.g;
let successors = match self.stubborn.as_mut() {
None => self.task.successors(&node.state),
Some(stubborn) => {
let (allowed, pruned) = stubborn.allowed(self.task, &node.state);
self.statistics.stubborn_pruned += pruned;
(0..allowed.len())
.filter(|&i| allowed[i])
.filter_map(|i| self.task.successor(i, &node.state).map(|s| (i, s)))
.collect()
}
};
for (action, state) in successors {
let g = g.saturating_add(self.task.globals[action].cost);
self.insert(state, g, Some((id, action)));
}
}
}
fn is_done(&self, key: Price) -> bool {
match self.order {
Order::Cost => self.best.is_some_and(|(cost, _)| key >= cost),
Order::Anytime => self
.best
.is_some_and(|(cost, _)| key.saturating_add(self.min_goal_price) >= cost),
Order::Greedy => self.best.is_some(),
}
}
fn estimate(&self, state: &DecoupledState) -> Option<Price> {
self.heuristic
.map_or(Some(0), |h| h.estimate(&self.task.fact_prices(state)))
}
fn key(&self, state: &DecoupledState, g: Price, h: Price) -> Option<Price> {
match self.order {
Order::Cost => Some(g.saturating_add(h)),
Order::Greedy => Some(h),
Order::Anytime => {
let root = self.root.map_or(Some(0), |r| {
r.estimate(&self.task.fact_prices(state).reached_for_free())
})?;
Some(g.saturating_add(root))
}
}
}
fn insert(&mut self, state: DecoupledState, g: Price, parent: Option<(usize, usize)>) {
self.statistics.generated += 1;
let work = self.task.leaves.iter().map(|l| l.size).sum::<usize>() + 1;
let work = u64::try_from(work).unwrap_or(u64::MAX);
self.probe.work = self.probe.work.saturating_add(work);
if self.dominance.record_work(self.task, work) {
for node in &mut self.nodes {
node.bounds = None;
}
}
if self.is_dominated(&state, g) {
self.statistics.dominated += 1;
return;
}
let Some(h) = self.estimate(&state) else {
self.statistics.dead_ends += 1;
return;
};
self.probe.initial_h.get_or_insert(h);
let Some(key) = self.key(&state, g, h) else {
self.statistics.dead_ends += 1;
return;
};
if self.order == Order::Anytime
&& self
.best
.is_some_and(|(best, _)| g.saturating_add(h) >= best)
{
self.statistics.bound_pruned += 1;
return;
}
let id = self.nodes.len();
if let Some(rest) = self.task.goal_price(&state) {
let cost = g.saturating_add(rest);
if self.best.is_none_or(|(best, _)| cost < best) {
self.best = Some((cost, id));
}
}
self.by_center
.entry(state.center.clone())
.or_default()
.push(id);
self.probe.best_h = Some(self.probe.best_h.map_or(h, |b| b.min(h)));
self.open.push(Reverse((key, id)));
self.nodes.push(Node {
state,
g,
parent,
bounds: None,
});
self.statistics.stored += 1;
}
fn is_dominated(&mut self, state: &DecoupledState, g: Price) -> bool {
let Some(ids) = self.by_center.get(&state.center) else {
return false;
};
let frontier = self.dominance.frontier(self.task, state);
for &id in ids {
let node = &mut self.nodes[id];
let bounds = node
.bounds
.get_or_insert_with(|| self.dominance.bounds(self.task, &node.state));
if self
.dominance
.dominates((&node.state, node.g, bounds), (state, g, &frontier))
{
return true;
}
}
false
}
fn path(&self, mut id: usize) -> Vec<(Option<usize>, &DecoupledState)> {
let mut path = Vec::new();
loop {
let node = &self.nodes[id];
path.push((node.parent.map(|(_, a)| a), &node.state));
match node.parent {
Some((parent, _)) => id = parent,
None => break,
}
}
path.reverse();
path
}
}