mod invertible;
mod strategy;
use alloc::borrow::Cow;
use alloc::vec::Vec;
use core::fmt;
use sas_plus::{CausalGraph, State, Task, VarId};
use crate::lm_cut::contexts::{self, Split};
use invertible::is_rse_invertible;
pub use strategy::Strategy;
#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct Painting {
black: Vec<VarId>,
bounded: bool,
}
pub const MAX_BOUNDED_PRODUCT: usize = 256;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CausalLevel {
Top,
Bottom,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Fragment {
Arcless,
Dag,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PaintingError {
UnknownVariable(VarId),
Derived(VarId),
InAxiom(VarId),
ConditionalEffect(VarId),
Dependent(VarId, VarId),
Cyclic(VarId, VarId),
TooLarge,
}
impl fmt::Display for PaintingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::UnknownVariable(v) => write!(f, "variable {v} does not exist"),
Self::Derived(v) => write!(f, "variable {v} is derived"),
Self::InAxiom(v) => write!(f, "variable {v} appears in an axiom"),
Self::ConditionalEffect(v) => {
write!(
f,
"variable {v} appears in a conditional effect with too many contexts to compile"
)
}
Self::Dependent(u, v) => {
write!(f, "variables {u} and {v} are linked in the causal graph")
}
Self::Cyclic(u, v) => {
write!(
f,
"variables {u} and {v} lie on a cycle of the black causal graph"
)
}
Self::TooLarge => write!(
f,
"the black domain sizes multiply to more than {MAX_BOUNDED_PRODUCT}"
),
}
}
}
impl core::error::Error for PaintingError {}
impl Painting {
#[must_use]
pub fn all_red() -> Self {
Self::default()
}
pub fn new(task: &Task, black: Vec<VarId>) -> Result<Self, PaintingError> {
let task = &*compiled(task);
let black = eligible(task, black)?;
let graph = CausalGraph::new(task);
for (i, &u) in black.iter().enumerate() {
if let Some(&v) = black[i + 1..].iter().find(|&&v| linked(&graph, u, v)) {
return Err(PaintingError::Dependent(u, v));
}
}
Ok(Self {
black,
bounded: false,
})
}
pub fn dag(task: &Task, black: Vec<VarId>) -> Result<Self, PaintingError> {
let task = &*compiled(task);
let black = eligible(task, black)?;
match cycle_arc(&CausalGraph::new(task), &black) {
Some((u, v)) => Err(PaintingError::Cyclic(u, v)),
None => Ok(Self {
black,
bounded: false,
}),
}
}
#[must_use]
pub fn greedy_dag(task: &Task) -> Self {
let task = &*compiled(task);
let mut candidates = repairable(task);
candidates.sort_by_key(|&v| (task.variables[v].domain_size, v));
let graph = CausalGraph::new(task);
let mut black: Vec<VarId> = Vec::new();
for v in candidates {
let pos = black.binary_search(&v).unwrap_err();
black.insert(pos, v);
if cycle_arc(&graph, &black).is_some() {
black.remove(pos);
}
}
Self {
black,
bounded: false,
}
}
#[must_use]
pub fn greedy(task: &Task) -> Self {
let task = &*compiled(task);
let mut candidates = repairable(task);
candidates.sort_by_key(|&v| (task.variables[v].domain_size, v));
Self::independent(&CausalGraph::new(task), candidates)
}
#[must_use]
pub fn causal_graph_level(task: &Task, keep: CausalLevel, fragment: Fragment) -> Self {
Self::with_strategy(task, &task.initial_state(), Strategy::Level(keep), fragment)
}
#[must_use]
pub fn incident_arcs(task: &Task, fragment: Fragment) -> Self {
Self::with_strategy(task, &task.initial_state(), Strategy::MostArcs, fragment)
}
#[must_use]
pub fn conflict_directed(task: &Task, state: &State, fragment: Fragment) -> Self {
Self::with_strategy(task, state, Strategy::FewestConflicts, fragment)
}
#[must_use]
pub fn with_strategy(
task: &Task,
state: &State,
strategy: Strategy,
fragment: Fragment,
) -> Self {
Self {
black: strategy::paint_with(&compiled(task), state, strategy, fragment),
bounded: false,
}
}
fn independent(graph: &CausalGraph, candidates: Vec<VarId>) -> Self {
let mut black: Vec<VarId> = Vec::new();
for v in candidates {
if !black.iter().any(|&u| linked(graph, u, v)) {
black.push(v);
}
}
black.sort_unstable();
Self {
black,
bounded: false,
}
}
pub fn bounded(task: &Task, black: Vec<VarId>) -> Result<Self, PaintingError> {
let black = eligible(&compiled(task), black)?;
let mut product: usize = 1;
for &v in &black {
let size = task.variables[v].domain_size as usize;
product = product
.checked_mul(size)
.filter(|&p| p <= MAX_BOUNDED_PRODUCT)
.ok_or(PaintingError::TooLarge)?;
}
Ok(Self {
black,
bounded: true,
})
}
#[must_use]
pub fn is_bounded(&self) -> bool {
self.bounded
}
#[must_use]
pub fn black(&self) -> &[VarId] {
&self.black
}
}
const MAX_CONTEXTS: usize = 64;
pub(super) fn split(task: &Task) -> Option<Split> {
contexts::split_exact(task, MAX_CONTEXTS)
}
fn compiled(task: &Task) -> Cow<'_, Task> {
split(task).map_or(Cow::Borrowed(task), |s| Cow::Owned(s.task))
}
fn eligible(task: &Task, mut black: Vec<VarId>) -> Result<Vec<VarId>, PaintingError> {
black.sort_unstable();
black.dedup();
let excluded = ineligible(task);
for &v in &black {
if v >= task.num_variables() {
return Err(PaintingError::UnknownVariable(v));
}
if let Some(reason) = excluded[v] {
return Err(reason);
}
}
Ok(black)
}
fn ineligible(task: &Task) -> Vec<Option<PaintingError>> {
let mut reason: Vec<Option<PaintingError>> = (0..task.num_variables())
.map(|v| {
task.variables[v]
.is_derived()
.then_some(PaintingError::Derived(v))
})
.collect();
let mut exclude = |v: VarId, why: PaintingError| {
reason[v].get_or_insert(why);
};
for axiom in &task.axioms {
for c in &axiom.conditions {
exclude(c.var, PaintingError::InAxiom(c.var));
}
}
for effect in task.operators.iter().flat_map(|op| &op.eff) {
if !effect.conditions.is_empty() {
let v = effect.fact.var;
exclude(v, PaintingError::ConditionalEffect(v));
for c in &effect.conditions {
exclude(c.var, PaintingError::ConditionalEffect(c.var));
}
}
}
reason
}
fn repairable(task: &Task) -> Vec<VarId> {
let excluded = ineligible(task);
(0..task.num_variables())
.filter(|&v| excluded[v].is_none() && is_rse_invertible(task, v))
.collect()
}
fn max_by_key<K: Ord>(candidates: &[VarId], key: impl Fn(VarId) -> K) -> VarId {
candidates
.iter()
.copied()
.max_by_key(|&v| key(v))
.expect("there are candidates")
}
pub(super) fn levels<'g>(n: usize, successors: impl Fn(usize) -> &'g [usize]) -> Vec<usize> {
let component = components(n, &successors);
let count = component.iter().max().map_or(0, |&c| c + 1);
let mut arcs: Vec<(usize, usize)> = (0..n)
.flat_map(|u| successors(u).iter().map(move |&v| (u, v)))
.map(|(u, v)| (component[u], component[v]))
.filter(|(a, b)| a != b)
.collect();
arcs.sort_unstable();
arcs.dedup();
let mut level = alloc::vec![0; count];
for c in (0..count).rev() {
for &(a, b) in arcs.iter().filter(|(a, _)| *a == c) {
level[b] = level[b].max(level[a] + 1);
}
}
component.iter().map(|&c| level[c]).collect()
}
fn components<'g>(n: usize, successors: &impl Fn(usize) -> &'g [usize]) -> Vec<usize> {
struct Tarjan {
index: Vec<usize>,
low: Vec<usize>,
on_stack: Vec<bool>,
stack: Vec<usize>,
component: Vec<usize>,
next: usize,
count: usize,
}
let mut t = Tarjan {
index: alloc::vec![usize::MAX; n],
low: alloc::vec![0; n],
on_stack: alloc::vec![false; n],
stack: Vec::new(),
component: alloc::vec![usize::MAX; n],
next: 0,
count: 0,
};
for root in 0..n {
if t.index[root] != usize::MAX {
continue;
}
let mut work = alloc::vec![(root, 0)];
t.index[root] = t.next;
t.low[root] = t.next;
t.next += 1;
t.stack.push(root);
t.on_stack[root] = true;
while let Some(&mut (u, ref mut pos)) = work.last_mut() {
if let Some(&v) = successors(u).get(*pos) {
*pos += 1;
if t.index[v] == usize::MAX {
t.index[v] = t.next;
t.low[v] = t.next;
t.next += 1;
t.stack.push(v);
t.on_stack[v] = true;
work.push((v, 0));
} else if t.on_stack[v] {
t.low[u] = t.low[u].min(t.index[v]);
}
continue;
}
work.pop();
if let Some(&(parent, _)) = work.last() {
t.low[parent] = t.low[parent].min(t.low[u]);
}
if t.low[u] == t.index[u] {
while let Some(w) = t.stack.pop() {
t.on_stack[w] = false;
t.component[w] = t.count;
if w == u {
break;
}
}
t.count += 1;
}
}
}
t.component
}
fn cycle_arc(graph: &CausalGraph, black: &[VarId]) -> Option<(VarId, VarId)> {
let successors: Vec<Vec<usize>> = black
.iter()
.map(|&v| {
graph
.successors(v)
.iter()
.filter_map(|w| black.binary_search(w).ok())
.collect()
})
.collect();
let component = components(black.len(), &|b| successors[b].as_slice());
(0..black.len())
.flat_map(|u| successors[u].iter().map(move |&v| (u, v)))
.find(|&(u, v)| component[u] == component[v])
.map(|(u, v)| (black[u], black[v]))
}
fn linked(graph: &CausalGraph, u: VarId, v: VarId) -> bool {
graph.successors(u).binary_search(&v).is_ok() || graph.successors(v).binary_search(&u).is_ok()
}
#[cfg(test)]
mod tests {
use alloc::vec::Vec;
use super::levels;
fn of(successors: &[&[usize]]) -> Vec<usize> {
levels(successors.len(), |v| successors[v])
}
#[test]
fn levels_of_chains_and_cycles() {
assert_eq!(of(&[&[1], &[2], &[]]), [0, 1, 2]);
assert_eq!(of(&[&[1], &[2], &[1], &[]]), [0, 1, 1, 0]);
assert_eq!(of(&[&[2], &[2], &[3], &[]]), [0, 0, 1, 2]);
assert_eq!(of(&[&[1, 2], &[3], &[], &[]]), [0, 1, 1, 2]);
}
}