mod forward;
mod painting;
mod product;
mod repair;
mod tables;
use alloc::borrow::Cow;
use alloc::vec::Vec;
use sas_plus::{OpId, State, Task, VarId};
pub use painting::{CausalLevel, Fragment, MAX_BOUNDED_PRODUCT, Painting, PaintingError, Strategy};
use product::{Outcome, Product};
use repair::Repair;
use tables::Tables;
use crate::relaxation::Workspace;
use crate::{Heuristic, Relaxation};
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct RedBlackPlan {
ops: Vec<OpId>,
cost: u64,
repaired: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub struct RedBlackOptions {
pub forward: bool,
pub follow: bool,
pub prefer_executable: bool,
}
impl RedBlackPlan {
#[must_use]
pub fn is_plan_for(&self, task: &Task, state: &State) -> bool {
let mut current = state.clone();
for &op in &self.ops {
if !task.is_applicable(op, ¤t) {
return false;
}
current = task.apply(op, ¤t);
}
task.is_goal(¤t)
}
#[must_use]
pub fn ops(&self) -> &[OpId] {
&self.ops
}
#[must_use]
pub fn cost(&self) -> u64 {
self.cost
}
#[must_use]
pub fn is_repaired(&self) -> bool {
self.repaired
}
}
#[derive(Clone, Debug)]
pub struct RedBlack<'r> {
relaxation: Cow<'r, Relaxation>,
black: Vec<VarId>,
tables: Tables,
workspace: Workspace,
repair: Repair,
options: RedBlackOptions,
relaxed: Vec<OpId>,
product: Option<Product>,
op_of: Option<Vec<OpId>>,
}
impl RedBlack<'static> {
#[must_use]
pub fn new(task: &Task) -> Self {
Self::with_painting(task, &Painting::greedy(task))
}
#[must_use]
pub fn with_painting(task: &Task, painting: &Painting) -> Self {
Self::build(task, Cow::Owned(Relaxation::new(task)), painting)
}
}
impl<'r> RedBlack<'r> {
#[must_use]
pub fn with_relaxation(task: &Task, relaxation: &'r Relaxation, painting: &Painting) -> Self {
Self::build(task, Cow::Borrowed(relaxation), painting)
}
fn build(task: &Task, relaxation: Cow<'r, Relaxation>, painting: &Painting) -> Self {
let split = in_conditional_effect(task, painting.black())
.then(|| painting::split(task))
.flatten();
let (task, relaxation, op_of) = match &split {
Some(s) => (
&s.task,
Cow::Owned(Relaxation::new(&s.task)),
Some(s.op_of.clone()),
),
None => (task, relaxation, None),
};
let tables = Tables::new(task, &relaxation, painting.black());
let product = painting
.is_bounded()
.then(|| Product::new(task, &relaxation, painting.black()));
Self {
relaxation,
black: painting.black().to_vec(),
tables,
workspace: Workspace::default(),
repair: Repair::default(),
options: RedBlackOptions::default(),
relaxed: Vec::new(),
product,
op_of,
}
}
#[must_use]
pub fn with_options(mut self, options: RedBlackOptions) -> Self {
self.options = options;
self
}
#[must_use]
pub fn options(&self) -> RedBlackOptions {
self.options
}
#[must_use]
pub fn black_variables(&self) -> &[VarId] {
&self.black
}
#[must_use]
pub fn value(&mut self, state: &State) -> Option<u64> {
self.run(state).map(|(cost, _)| cost)
}
#[must_use]
pub fn plan(&mut self, state: &State) -> Option<RedBlackPlan> {
let (cost, repaired) = self.run(state)?;
let mut ops = if repaired {
self.repair.plan.clone()
} else {
self.workspace.plan.clone()
};
if let Some(op_of) = &self.op_of {
for op in &mut ops {
*op = op_of[*op];
}
}
Some(RedBlackPlan {
ops,
cost,
repaired,
})
}
fn run(&mut self, state: &State) -> Option<(u64, bool)> {
let ff = self
.relaxation
.relaxed_plan_in(state, &mut self.workspace)?;
if let Some(product) = &self.product {
return match product.search(&self.relaxation, state) {
Outcome::Plan(plan, cost) => {
self.repair.plan = plan;
Some((cost, true))
}
Outcome::Unsolvable => None,
Outcome::Exhausted => Some((ff, false)),
};
}
self.relaxed.clone_from(&self.workspace.plan);
if self.options.forward && !self.options.follow {
forward::forward(&self.tables, &mut self.relaxed);
}
self.repair.prefer_executable = self.options.prefer_executable;
let repaired = if self.options.follow {
self.repair
.follow(&self.relaxation, &self.tables, state, &self.relaxed)
} else {
self.repair
.run(&self.relaxation, &self.tables, state, &self.relaxed)
};
Some(repaired.map_or((ff, false), |cost| (cost, true)))
}
}
fn in_conditional_effect(task: &Task, black: &[VarId]) -> bool {
task.operators
.iter()
.flat_map(|op| &op.eff)
.filter(|e| !e.conditions.is_empty())
.any(|e| {
core::iter::once(&e.fact)
.chain(&e.conditions)
.any(|f| black.binary_search(&f.var).is_ok())
})
}
impl Heuristic<State> for RedBlack<'_> {
fn estimate(&mut self, state: &State) -> Option<u32> {
self.value(state)
.map(|v| u32::try_from(v).unwrap_or(u32::MAX))
}
}
#[cfg(test)]
mod tests {
use alloc::vec::Vec;
use sas_plus::Task;
use sas_plus::fdr::SasFile;
use sas_plus::random::{RandomTaskParams, random_task};
use super::{CausalLevel, Fragment, Painting, RedBlack, in_conditional_effect, painting};
use crate::HFf;
const FIXTURES: [&str; 3] = [
include_str!("../tests/fixtures/conditional-effects/output.sas"),
include_str!("../tests/fixtures/translated-courier/output.sas"),
include_str!("../tests/fixtures/translated-wiring/output.sas"),
];
fn paintings(task: &Task) -> Vec<Painting> {
let mut all = alloc::vec![Painting::greedy(task), Painting::greedy_dag(task)];
for fragment in [Fragment::Arcless, Fragment::Dag] {
for level in [CausalLevel::Top, CausalLevel::Bottom] {
all.push(Painting::causal_graph_level(task, level, fragment));
}
all.push(Painting::incident_arcs(task, fragment));
all.push(Painting::conflict_directed(
task,
&task.initial_state(),
fragment,
));
}
all
}
#[test]
fn conditional_effect_variables_matter_when_black() {
let params = RandomTaskParams {
max_conditions: 2,
..RandomTaskParams::default()
};
let tasks = FIXTURES
.iter()
.map(|text| SasFile::parse(text).expect("fixture parses").to_task())
.chain((0..32).map(|seed| random_task(seed, params)));
let (mut painted, mut above) = (0, 0);
for task in tasks {
let Some(split) = painting::split(&task) else {
continue;
};
let mut h_ff = HFf::new(&split.task);
for painting in paintings(&task) {
if !in_conditional_effect(&task, painting.black()) {
continue;
}
painted += 1;
let mut h_rb = RedBlack::with_painting(&task, &painting);
let mut stack = alloc::vec![task.initial_state()];
let mut seen = alloc::collections::BTreeSet::from([task.initial_state().0]);
while let Some(state) = stack.pop() {
if let Some(plan) = h_rb.plan(&state) {
let ff = h_ff.value(&state).expect("same dead ends");
assert!(plan.cost() >= ff || !plan.is_repaired());
above += usize::from(plan.is_repaired() && plan.cost() > ff);
}
for op in task.applicable_operators(&state) {
let next = task.apply(op, &state);
if seen.len() < 2048 && seen.insert(next.0.clone()) {
stack.push(next);
}
}
}
}
}
assert!(
painted > 0,
"no strategy paints a conditional effect variable black"
);
assert!(
above > 0,
"black conditional effect variables never raise h_RB"
);
}
}