use alloc::vec;
use alloc::vec::Vec;
use alloc::collections::BinaryHeap;
use core::cmp::Reverse;
use crate::decoupled::{Leaf, LeafPart, Price, View};
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Bits(Vec<u64>);
impl Bits {
fn empty(n: usize) -> Self {
Self(vec![0; n.div_ceil(64)])
}
pub(crate) fn contains(&self, i: usize) -> bool {
self.0[i / 64] >> (i % 64) & 1 == 1
}
fn remove(&mut self, i: usize) {
self.0[i / 64] &= !(1 << (i % 64));
}
fn insert(&mut self, i: usize) {
self.0[i / 64] |= 1 << (i % 64);
}
}
struct Transitions {
leaf: Vec<Vec<(usize, usize)>>,
global: Vec<Vec<Option<usize>>>,
actions: usize,
}
pub(crate) fn simulators(leaf: &Leaf, parts: &[&LeafPart]) -> Vec<Bits> {
let view = leaf.static_view();
let transitions = transitions(&view, parts);
let weaker = weaker_actions(leaf);
let mut rel = initial_relation(&view, &transitions);
let predecessors = predecessors(&transitions, leaf.size);
let mut work: Vec<(usize, usize)> = (0..leaf.size)
.flat_map(|x| (0..leaf.size).map(move |y| (x, y)))
.filter(|&(x, y)| x != y && rel[x].contains(y))
.collect();
while let Some((x, y)) = work.pop() {
if !rel[x].contains(y) || simulates(&rel, &transitions, &weaker, x, y) {
continue;
}
rel[x].remove(y);
for &px in &predecessors[x] {
let ys = core::iter::once(y).chain(predecessors[y].iter().copied());
work.extend(
ys.filter(|&py| px != py && rel[px].contains(py))
.map(|py| (px, py)),
);
}
}
rel
}
fn predecessors(transitions: &Transitions, size: usize) -> Vec<Vec<usize>> {
let mut predecessors = vec![Vec::new(); size];
for x in 0..size {
let leaf = transitions.leaf[x].iter().map(|&(_, next)| next);
for next in leaf.chain(transitions.global[x].iter().flatten().copied()) {
predecessors[next].push(x);
}
}
for p in &mut predecessors {
p.sort_unstable();
p.dedup();
}
predecessors
}
pub(crate) fn redundant_transitions(
leaf: &Leaf,
parts: &[&LeafPart],
rel: &[Bits],
) -> (Vec<bool>, usize) {
let view = leaf.static_view();
let transitions = transitions(&view, parts);
let weaker = weaker_actions(leaf);
let count = leaf.actions.len();
let replaces = |(b, y): (usize, usize), (a, target): (usize, usize)| {
weaker[a * count + b] && rel[target].contains(y)
};
let mut disabled = vec![false; leaf.size * count];
for (x, out) in transitions.leaf.iter().enumerate() {
for &(a, nx) in out {
let stays = rel[nx].contains(x);
let superseded = out.iter().any(|&(b, ny)| {
b != a && replaces((b, ny), (a, nx)) && (b < a || !replaces((a, nx), (b, ny)))
});
disabled[x * count + a] = stays || superseded;
}
}
let before = reachable(&transitions, leaf, &[]);
let after = reachable(&transitions, leaf, &disabled);
let lost = before
.iter()
.zip(&after)
.filter(|&(&b, &a)| b && !a)
.count();
(disabled, lost)
}
pub(crate) fn live_actions(leaf: &Leaf, parts: &[&LeafPart]) -> Vec<bool> {
let view = leaf.static_view();
let transitions = transitions(&view, parts);
let seen = reachable(&transitions, leaf, &leaf.disabled);
let count = leaf.actions.len();
let mut live = vec![false; count];
for (x, out) in transitions
.leaf
.iter()
.enumerate()
.filter(|&(x, _)| seen[x])
{
for &(a, _) in out {
live[a] |= !leaf.disabled.get(x * count + a).is_some_and(|&d| d);
}
}
live
}
pub(crate) fn cheapest_goal(leaf: &Leaf, parts: &[&LeafPart]) -> Option<Price> {
let view = leaf.static_view();
let transitions = transitions(&view, parts);
let count = leaf.actions.len();
let mut distance = vec![Price::MAX; leaf.size];
let mut open = BinaryHeap::new();
distance[leaf.initial] = 0;
open.push(Reverse((0, leaf.initial)));
while let Some(Reverse((d, x))) = open.pop() {
if d > distance[x] {
continue;
}
if view.is_goal(x) {
return Some(d);
}
let kept = transitions.leaf[x]
.iter()
.filter(|&&(a, _)| !leaf.disabled.get(x * count + a).is_some_and(|&off| off))
.map(|&(a, next)| (next, leaf.actions[a].cost));
let global = transitions.global[x]
.iter()
.flatten()
.map(|&next| (next, 0));
for (next, cost) in kept.chain(global) {
let through = d.saturating_add(cost);
if through < distance[next] {
distance[next] = through;
open.push(Reverse((through, next)));
}
}
}
None
}
fn reachable(transitions: &Transitions, leaf: &Leaf, disabled: &[bool]) -> Vec<bool> {
let mut seen = vec![false; leaf.size];
let mut stack = vec![leaf.initial];
seen[leaf.initial] = true;
while let Some(x) = stack.pop() {
let local = transitions.leaf[x]
.iter()
.filter(|&&(a, _)| {
!disabled
.get(x * transitions.actions + a)
.is_some_and(|&d| d)
})
.map(|&(_, next)| next);
for next in local.chain(transitions.global[x].iter().flatten().copied()) {
if !core::mem::replace(&mut seen[next], true) {
stack.push(next);
}
}
}
seen
}
fn transitions(view: &View<'_>, parts: &[&LeafPart]) -> Transitions {
let leaf = view.leaf;
let apply = |rank: usize, part: &LeafPart| {
view.satisfies(rank, &part.pre)
.then(|| view.apply(rank, &part.eff))
};
Transitions {
leaf: (0..leaf.size)
.map(|rank| {
leaf.actions
.iter()
.enumerate()
.filter_map(|(i, a)| apply(rank, &a.part).map(|next| (i, next)))
.collect()
})
.collect(),
global: (0..leaf.size)
.map(|rank| parts.iter().map(|part| apply(rank, part)).collect())
.collect(),
actions: leaf.actions.len(),
}
}
fn weaker_actions(leaf: &Leaf) -> Vec<bool> {
let actions = &leaf.actions;
actions
.iter()
.flat_map(|a| {
actions
.iter()
.map(|b| b.cost <= a.cost && b.center_pre.iter().all(|f| a.center_pre.contains(f)))
})
.collect()
}
fn initial_relation(view: &View<'_>, transitions: &Transitions) -> Vec<Bits> {
let n = view.leaf.size;
(0..n)
.map(|x| {
let mut simulators = Bits::empty(n);
for y in 0..n {
let goal = !view.is_goal(x) || view.is_goal(y);
let pre = transitions.global[x]
.iter()
.zip(&transitions.global[y])
.all(|(gx, gy)| gx.is_none() || gy.is_some());
if goal && pre {
simulators.insert(y);
}
}
simulators
})
.collect()
}
fn simulates(rel: &[Bits], transitions: &Transitions, weaker: &[bool], x: usize, y: usize) -> bool {
let global = transitions.global[x]
.iter()
.zip(&transitions.global[y])
.all(|(gx, gy)| match (gx, gy) {
(Some(nx), Some(ny)) => rel[*nx].contains(*ny),
(Some(_), None) => false,
(None, _) => true,
});
let count = transitions.actions;
global
&& transitions.leaf[x].iter().all(|&(a, nx)| {
rel[nx].contains(y)
|| transitions.leaf[y]
.iter()
.any(|&(b, ny)| weaker[a * count + b] && rel[nx].contains(ny))
})
}
#[cfg(test)]
mod tests {
use alloc::vec;
use alloc::vec::Vec;
use sas_plus::{Effect, Fact, OpId, Operator, State, Task, Variable};
use super::*;
use crate::Factoring;
use crate::decoupled::DecoupledTask;
fn logistics() -> DecoupledTask {
let op = |pre: Vec<Fact>, eff: Fact| Operator {
name: "op".into(),
pre,
eff: vec![Effect::new(eff)],
cost: 1,
};
let mut operators = Vec::new();
for x in 0..3 {
for y in (0..3).filter(|&y| y != x) {
operators.push(op(vec![Fact::new(0, x)], Fact::new(0, y)));
}
operators.push(op(vec![Fact::new(0, x), Fact::new(1, x)], Fact::new(1, 3)));
operators.push(op(vec![Fact::new(0, x), Fact::new(1, 3)], Fact::new(1, x)));
}
let task = Task {
variables: vec![Variable::new("truck", 3), Variable::new("pkg", 4)],
operators,
initial: State(vec![0, 0]),
goal: vec![Fact::new(1, 1)],
axioms: vec![],
};
DecoupledTask::new(&task, &Factoring::fork(&task)).expect("supported")
}
#[test]
fn truck_simulates_the_other_locations() {
let task = logistics();
let rel = simulators(&task.leaves[0], &[]);
let simulators_of =
|x: usize| -> Vec<usize> { (0..4).filter(|&y| rel[x].contains(y)).collect() };
assert_eq!(simulators_of(0), [0, 1, 3]);
assert_eq!(simulators_of(2), [1, 2, 3]);
assert_eq!(simulators_of(1), [1]);
assert_eq!(simulators_of(3), [1, 3]);
}
fn shortcut() -> DecoupledTask {
let op = |name: &str, pre: Vec<Fact>, eff: Fact, cost| Operator {
name: name.into(),
pre,
eff: vec![Effect::new(eff)],
cost,
};
let task = Task {
variables: vec![Variable::new("c", 2), Variable::new("v", 3)],
operators: vec![
op("a", vec![Fact::new(1, 0)], Fact::new(1, 1), 1),
op("b", vec![Fact::new(1, 0)], Fact::new(1, 2), 1),
op(
"d",
vec![Fact::new(0, 1), Fact::new(1, 1)],
Fact::new(1, 2),
0,
),
op("on", vec![], Fact::new(0, 1), 1),
],
initial: State(vec![0, 0]),
goal: vec![Fact::new(1, 2)],
axioms: vec![],
};
DecoupledTask::new(&task, &Factoring::fork(&task)).expect("supported")
}
#[test]
fn one_directional_replacement_removes_the_dominated_transition() {
let task = shortcut();
let leaf = &task.leaves[0];
let rel = simulators(leaf, &[]);
assert!(rel[1].contains(2) && !rel[2].contains(1) && !rel[0].contains(1));
let (disabled, lost) = redundant_transitions(leaf, &[], &rel);
let count = leaf.actions.len();
let removed: Vec<(usize, OpId)> = (0..leaf.size)
.flat_map(|x| (0..count).map(move |a| (x, a)))
.filter(|&(x, a)| disabled[x * count + a])
.map(|(x, a)| (x, leaf.actions[a].op))
.collect();
assert_eq!(removed, [(0, 0)], "only a, from 0");
assert_eq!(lost, 1, "1 was reachable only through a");
}
#[test]
fn duplicate_actions_keep_one_copy() {
let op = |name: &str| Operator {
name: name.into(),
pre: vec![Fact::new(1, 0)],
eff: vec![Effect::new(Fact::new(1, 1))],
cost: 1,
};
let task = Task {
variables: vec![Variable::new("c", 2), Variable::new("v", 2)],
operators: vec![
op("first"),
op("second"),
Operator {
name: "on".into(),
pre: vec![],
eff: vec![Effect::new(Fact::new(0, 1))],
cost: 1,
},
],
initial: State(vec![0, 0]),
goal: vec![Fact::new(1, 1)],
axioms: vec![],
};
let factoring = Factoring::new(&task, vec![vec![1]]).expect("valid");
let task = DecoupledTask::new(&task, &factoring).expect("supported");
let leaf = &task.leaves[0];
let rel = simulators(leaf, &[]);
let (disabled, lost) = redundant_transitions(leaf, &[], &rel);
let count = leaf.actions.len();
assert_eq!(count, 2);
assert_eq!(
(disabled[0], disabled[1]),
(false, true),
"the later copy goes"
);
assert_eq!(lost, 0);
}
}