use alloc::collections::VecDeque;
use alloc::vec::Vec;
use sas_plus::{Fact, OpId, State, Task, VarId};
use crate::Relaxation;
const NODE_BUDGET: usize = 4096;
pub(super) enum Outcome {
Plan(Vec<OpId>, u64),
Unsolvable,
Exhausted,
}
#[derive(Clone, Debug)]
pub(super) struct Product {
is_black_fact: Vec<bool>,
red_pre: Vec<Vec<usize>>,
cost: Vec<u64>,
matching: Vec<Vec<u32>>,
next: Vec<Vec<u32>>,
out: Vec<Vec<(OpId, u32)>>,
goal_values: Vec<bool>,
red_goal: Vec<usize>,
strides: Vec<(VarId, u32)>,
}
#[derive(Clone, Debug)]
struct Node {
holds: Vec<bool>,
plan: Vec<OpId>,
cost: u64,
groups: Vec<Vec<u32>>,
group_of: Vec<Option<usize>>,
current: u32,
}
impl Product {
pub fn new(task: &Task, relaxation: &Relaxation, black: &[VarId]) -> Self {
let encoding = Encoding::new(task, black);
let (matching, next) = encoding.transitions();
let out = out_edges(encoding.size, &matching, &next);
let goal_values = (0..encoding.size)
.map(|x| encoding.allows(x, &task.goal))
.collect();
Self {
is_black_fact: super::tables::black_fact_mask(task, relaxation, black),
red_pre: task
.operators
.iter()
.map(|op| encoding.red_fact_ids(relaxation, &op.pre))
.collect(),
cost: task.operators.iter().map(|op| u64::from(op.cost)).collect(),
matching,
next,
out,
goal_values,
red_goal: encoding.red_fact_ids(relaxation, &task.goal),
strides: encoding.strides,
}
}
pub fn search(&self, relaxation: &Relaxation, state: &State) -> Outcome {
let mut holds = alloc::vec![false; relaxation.num_facts()];
for fact in relaxation
.state_facts(state)
.chain(relaxation.free_facts().iter().copied())
{
holds[fact as usize] = true;
}
super::repair::close_axioms(relaxation, &mut holds);
let current = self
.strides
.iter()
.map(|&(v, stride)| state.0[v] * stride)
.sum();
let mut group_of = alloc::vec![None; self.out.len()];
group_of[current as usize] = Some(0);
let root = Node {
holds,
plan: Vec::new(),
cost: 0,
groups: alloc::vec![alloc::vec![current]],
group_of,
current,
};
let mut expanded = 0;
match self.expand(relaxation, root, &mut expanded) {
Some(node) => Outcome::Plan(node.plan, node.cost),
None if expanded > NODE_BUDGET => Outcome::Exhausted,
None => Outcome::Unsolvable,
}
}
fn expand(
&self,
relaxation: &Relaxation,
mut node: Node,
expanded: &mut usize,
) -> Option<Node> {
*expanded += 1;
if *expanded > NODE_BUDGET {
return None;
}
self.close(relaxation, &mut node);
if let Some(goal) = self.goal_value(&node) {
self.move_within(relaxation, &mut node, goal);
return Some(node);
}
let last = node.groups.len() - 1;
for op in 0..self.matching.len() {
if self.next[op].is_empty() || !self.red_pre_holds(&node, op) {
continue;
}
for (&x, &y) in self.matching[op].iter().zip(&self.next[op]) {
if node.group_of[x as usize] != Some(last)
|| node.group_of[y as usize] == Some(last)
{
continue;
}
let mut child = node.clone();
self.move_within(relaxation, &mut child, x);
self.apply(relaxation, &mut child, op, Some(y));
enter(&mut child, y);
if let Some(found) = self.expand(relaxation, child, expanded) {
return Some(found);
}
if *expanded > NODE_BUDGET {
return None;
}
}
}
None
}
fn close(&self, relaxation: &Relaxation, node: &mut Node) {
let mut changed = true;
while changed {
changed = false;
for op in 0..self.matching.len() {
if !self.red_pre_holds(node, op) || !self.adds_red(relaxation, node, op) {
continue;
}
let Some((from, to)) = self.usable_in_group(node, op) else {
continue;
};
self.move_within(relaxation, node, from);
self.apply(relaxation, node, op, to);
changed = true;
}
}
}
fn usable_in_group(&self, node: &Node, op: OpId) -> Option<(u32, Option<u32>)> {
let last = Some(node.groups.len() - 1);
let in_group = |x: u32| node.group_of[x as usize] == last;
let candidates = self.matching[op]
.iter()
.enumerate()
.filter(|&(i, &x)| in_group(x) && self.next[op].get(i).is_none_or(|&y| in_group(y)));
let pick = candidates
.clone()
.find(|&(_, &x)| x == node.current)
.or_else(|| candidates.clone().next())?;
Some((*pick.1, self.next[op].get(pick.0).copied()))
}
fn goal_value(&self, node: &Node) -> Option<u32> {
if !self.red_goal.iter().all(|&f| node.holds[f]) {
return None;
}
node.groups
.last()
.expect("there is a group")
.iter()
.copied()
.find(|&x| self.goal_values[x as usize])
}
fn move_within(&self, relaxation: &Relaxation, node: &mut Node, target: u32) {
if node.current == target {
return;
}
let last = Some(node.groups.len() - 1);
let mut via: Vec<Option<(u32, OpId)>> = alloc::vec![None; self.out.len()];
let mut queue = VecDeque::from([node.current]);
while let Some(x) = queue.pop_front() {
if x == target {
break;
}
for &(op, y) in &self.out[x as usize] {
let fresh = y != node.current && via[y as usize].is_none();
if fresh && node.group_of[y as usize] == last && self.red_pre_holds(node, op) {
via[y as usize] = Some((x, op));
queue.push_back(y);
}
}
}
let mut path = Vec::new();
let mut value = target;
while value != node.current {
let (from, op) = via[value as usize].expect("groups are strongly connected");
path.push((op, value));
value = from;
}
for &(op, to) in path.iter().rev() {
self.apply(relaxation, node, op, Some(to));
}
}
fn apply(&self, relaxation: &Relaxation, node: &mut Node, op: OpId, to: Option<u32>) {
let fired: Vec<usize> = relaxation
.op_rules(op)
.iter()
.filter(|rule| !self.is_black_fact[rule.head])
.filter(|rule| self.red_conditions_hold(node, &rule.conditions))
.map(|rule| rule.head)
.collect();
for head in fired {
node.holds[head] = true;
}
if let Some(to) = to {
node.current = to;
}
super::repair::close_axioms(relaxation, &mut node.holds);
node.plan.push(op);
node.cost = node.cost.saturating_add(self.cost[op]);
}
fn adds_red(&self, relaxation: &Relaxation, node: &Node, op: OpId) -> bool {
relaxation.op_rules(op).iter().any(|rule| {
!self.is_black_fact[rule.head]
&& !node.holds[rule.head]
&& self.red_conditions_hold(node, &rule.conditions)
})
}
fn red_conditions_hold(&self, node: &Node, conditions: &[usize]) -> bool {
conditions
.iter()
.all(|&c| self.is_black_fact[c] || node.holds[c])
}
fn red_pre_holds(&self, node: &Node, op: OpId) -> bool {
self.red_pre[op].iter().all(|&f| node.holds[f])
}
}
fn enter(node: &mut Node, value: u32) {
if let Some(i) = node.group_of[value as usize] {
let merged: Vec<u32> = node.groups.drain(i..).flatten().collect();
for &x in &merged {
node.group_of[x as usize] = Some(i);
}
node.groups.push(merged);
} else {
node.group_of[value as usize] = Some(node.groups.len());
node.groups.push(alloc::vec![value]);
}
}
struct Encoding<'t> {
task: &'t Task,
strides: Vec<(VarId, u32)>,
size: u32,
}
impl<'t> Encoding<'t> {
fn new(task: &'t Task, black: &[VarId]) -> Self {
let mut strides = Vec::with_capacity(black.len());
let mut size: u32 = 1;
for &v in black {
strides.push((v, size));
size = size
.checked_mul(task.variables[v].domain_size)
.expect("the product fits u32");
}
Self {
task,
strides,
size,
}
}
fn stride(&self, v: VarId) -> Option<u32> {
self.strides
.binary_search_by_key(&v, |&(var, _)| var)
.ok()
.map(|i| self.strides[i].1)
}
fn digit(&self, x: u32, v: VarId) -> u32 {
let stride = self.stride(v).expect("a black variable");
x / stride % self.task.variables[v].domain_size
}
fn allows(&self, x: u32, facts: &[Fact]) -> bool {
facts
.iter()
.all(|f| self.stride(f.var).is_none() || self.digit(x, f.var) == f.value)
}
fn red_fact_ids(&self, relaxation: &Relaxation, facts: &[Fact]) -> Vec<usize> {
facts
.iter()
.filter(|f| self.stride(f.var).is_none())
.map(|&f| relaxation.fact_id(f))
.collect()
}
fn apply(&self, x: u32, black_eff: &[&Fact]) -> u32 {
black_eff.iter().fold(x, |y, f| {
let stride = self.stride(f.var).expect("a black variable");
y - self.digit(y, f.var) * stride + f.value * stride
})
}
fn transitions(&self) -> (Vec<Vec<u32>>, Vec<Vec<u32>>) {
let operators = &self.task.operators;
let mut matching = Vec::with_capacity(operators.len());
let mut next = Vec::with_capacity(operators.len());
for op in operators {
let values: Vec<u32> = (0..self.size)
.filter(|&x| self.allows(x, &op.pre))
.collect();
let black_eff: Vec<&Fact> = op
.eff
.iter()
.map(|e| &e.fact)
.filter(|f| self.stride(f.var).is_some())
.collect();
let moved = if black_eff.is_empty() {
Vec::new()
} else {
values.iter().map(|&x| self.apply(x, &black_eff)).collect()
};
matching.push(values);
next.push(moved);
}
(matching, next)
}
}
fn out_edges(size: u32, matching: &[Vec<u32>], next: &[Vec<u32>]) -> Vec<Vec<(OpId, u32)>> {
let mut out = alloc::vec![Vec::new(); size as usize];
for (op, (from, to)) in matching.iter().zip(next).enumerate() {
for (&x, &y) in from.iter().zip(to) {
if x != y {
out[x as usize].push((op, y));
}
}
}
out
}