mod follow;
use alloc::vec::Vec;
use sas_plus::{OpId, State};
use super::tables::{Tables, Transition};
use crate::Relaxation;
#[derive(Clone, Debug, Default)]
pub(super) struct Repair {
holds: Vec<bool>,
black: Vec<u32>,
allowed: Vec<bool>,
real: Vec<u32>,
real_fired: Vec<sas_plus::Fact>,
pub prefer_executable: bool,
pub plan: Vec<OpId>,
cost: u64,
fired: Vec<usize>,
dist: Vec<Option<u64>>,
via: Vec<Option<(u32, OpId)>>,
done: Vec<bool>,
path: Vec<OpId>,
steps: usize,
budget: usize,
following: follow::Buffers,
}
impl Repair {
pub fn run(
&mut self,
relaxation: &Relaxation,
tables: &Tables,
state: &State,
relaxed_plan: &[OpId],
) -> Option<u64> {
self.start(relaxation, tables, state);
self.budget = budget(relaxed_plan);
for &op in relaxed_plan {
self.satisfy_black_pre(relaxation, tables, op, None)?;
if !tables.red_pre[op].iter().all(|&f| self.holds[f]) {
return None;
}
self.apply(relaxation, tables, op);
}
self.finish(relaxation, tables)
}
fn finish(&mut self, relaxation: &Relaxation, tables: &Tables) -> Option<u64> {
for &(b, value) in &tables.black_goal {
self.move_black(relaxation, tables, b, value)?;
}
if !tables
.black_goal
.iter()
.all(|&(b, value)| self.black[b] == value)
{
return None;
}
tables
.red_goal
.iter()
.all(|&f| self.holds[f])
.then_some(self.cost)
}
fn start(&mut self, relaxation: &Relaxation, tables: &Tables, state: &State) {
self.holds.clear();
self.holds.resize(relaxation.num_facts(), false);
for fact in relaxation
.state_facts(state)
.chain(relaxation.free_facts().iter().copied())
{
self.holds[fact as usize] = true;
}
self.black.clear();
self.black.extend(
tables
.black_offsets
.iter()
.zip(&tables.domain)
.map(|(&offset, &n)| value_of(&self.holds, offset, n)),
);
self.allowed.clone_from(&self.holds);
self.real.clone_from(&state.0);
self.plan.clear();
self.cost = 0;
self.steps = 0;
close_axioms(relaxation, &mut self.holds);
}
fn satisfy_black_pre(
&mut self,
relaxation: &Relaxation,
tables: &Tables,
op: OpId,
skip: Option<usize>,
) -> Option<()> {
let required = tables.black_pre[op]
.iter()
.filter(|&&(b, _)| Some(b) != skip);
for &(b, value) in required.clone() {
self.move_black(relaxation, tables, b, value)?;
}
required
.into_iter()
.all(|&(b, value)| self.black[b] == value)
.then_some(())
}
fn apply(&mut self, relaxation: &Relaxation, tables: &Tables, op: OpId) {
self.fired.clear();
self.fired.extend(
relaxation
.op_rules(op)
.iter()
.filter(|rule| !tables.is_black_fact[rule.head])
.filter(|rule| rule.conditions.iter().all(|&c| self.holds[c]))
.map(|rule| rule.head),
);
for &(b, value) in &tables.black_eff[op] {
let offset = tables.black_offsets[b];
self.holds[offset + self.black[b] as usize] = false;
self.holds[offset + value as usize] = true;
self.allowed[offset + value as usize] = true;
self.black[b] = value;
}
for &head in &self.fired {
self.holds[head] = true;
}
if self.prefer_executable {
self.apply_real(relaxation, tables, op);
}
close_axioms(relaxation, &mut self.holds);
self.plan.push(op);
self.cost = self.cost.saturating_add(tables.cost[op]);
}
fn apply_real(&mut self, relaxation: &Relaxation, tables: &Tables, op: OpId) {
let (real, holds) = (&self.real, &self.holds);
let holds_real = |c: &sas_plus::Fact| {
if tables.derived[c.var] {
holds[relaxation.fact_id(*c)]
} else {
real[c.var] == c.value
}
};
self.real_fired.clear();
self.real_fired.extend(
tables.real_eff[op]
.iter()
.filter(|(conditions, _)| conditions.iter().all(holds_real))
.map(|&(_, fact)| fact),
);
for fact in &self.real_fired {
self.real[fact.var] = fact.value;
}
}
fn move_black(
&mut self,
relaxation: &Relaxation,
tables: &Tables,
b: usize,
target: u32,
) -> Option<()> {
if self.black[b] == target {
return Some(());
}
self.cheapest_paths(relaxation, tables, b, self.prefer_executable);
if self.prefer_executable && self.dist[target as usize].is_none() {
self.cheapest_paths(relaxation, tables, b, false);
}
let mut path = core::mem::take(&mut self.path);
path.clear();
let mut value = target;
while value != self.black[b] {
let (from, op) = self.via[value as usize]?;
path.push(op);
value = from;
}
for i in (0..path.len()).rev() {
let op = path[i];
if tables.linked {
self.steps += 1;
if self.steps > self.budget {
return None;
}
self.satisfy_black_pre(relaxation, tables, op, Some(b))?;
}
self.apply(relaxation, tables, op);
}
path.clear();
self.path = path;
Some(())
}
fn cheapest_paths(
&mut self,
relaxation: &Relaxation,
tables: &Tables,
b: usize,
active_only: bool,
) {
let n = tables.domain[b] as usize;
refill(&mut self.dist, n, None);
refill(&mut self.via, n, None);
refill(&mut self.done, n, false);
self.dist[self.black[b] as usize] = Some(0);
while let Some(x) = self.closest_open() {
self.done[x] = true;
let d = self.dist[x].expect("open values have a distance");
for t in &tables.transitions[b] {
let usable = t.from.is_none_or(|from| from as usize == x)
&& t.to as usize != x
&& tables.red_pre[t.op].iter().all(|&f| {
self.holds[f] && (!active_only || self.is_active(relaxation, tables, f))
})
&& (!tables.linked || self.usable_in_dag(tables, b, t));
let next = d.saturating_add(tables.cost[t.op]);
let to = t.to as usize;
if usable && self.dist[to].is_none_or(|old| next < old) {
self.dist[to] = Some(next);
self.via[to] = Some((u32::try_from(x).expect("u32 values"), t.op));
}
}
}
}
fn is_active(&self, relaxation: &Relaxation, tables: &Tables, f: usize) -> bool {
let fact = relaxation.fact(f);
tables.derived[fact.var] || self.real[fact.var] == fact.value
}
fn usable_in_dag(&self, tables: &Tables, b: usize, t: &Transition) -> bool {
let fact = |b: usize, value: u32| tables.black_offsets[b] + value as usize;
self.allowed[fact(b, t.to)]
&& tables.black_pre[t.op]
.iter()
.all(|&(c, value)| self.allowed[fact(c, value)])
}
fn closest_open(&self) -> Option<usize> {
(0..self.dist.len())
.filter(|&x| !self.done[x])
.filter_map(|x| self.dist[x].map(|d| (d, x)))
.min()
.map(|(_, x)| x)
}
}
fn budget(relaxed_plan: &[OpId]) -> usize {
1024 + 64 * relaxed_plan.len()
}
fn value_of(holds: &[bool], offset: usize, n: u32) -> u32 {
(0..n)
.find(|&v| holds[offset + v as usize])
.expect("a state assigns every variable")
}
pub(super) fn close_axioms(relaxation: &Relaxation, holds: &mut [bool]) {
let mut changed = true;
while changed {
changed = false;
for rule in relaxation.axiom_rules() {
if !holds[rule.head] && rule.conditions.iter().all(|&c| holds[c]) {
holds[rule.head] = true;
changed = true;
}
}
}
}
fn refill<T: Clone>(buffer: &mut Vec<T>, len: usize, value: T) {
buffer.clear();
buffer.resize(len, value);
}