use std::cell::RefCell;
use std::collections::HashSet;
use std::hash::Hash;
use crate::siw::{Subgoals, serialize};
use crate::{SearchResult, WidthProblem};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Condition {
Zero(usize),
Positive(usize),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Effect {
Positive(usize),
Zero(usize),
Increase(usize),
Decrease(usize),
Any(usize),
}
impl Effect {
fn feature(self) -> usize {
match self {
Self::Positive(f)
| Self::Zero(f)
| Self::Increase(f)
| Self::Decrease(f)
| Self::Any(f) => f,
}
}
fn allows(self, from: u64, to: u64) -> bool {
match self {
Self::Positive(_) => to > 0,
Self::Zero(_) => to == 0,
Self::Increase(_) => to > from,
Self::Decrease(_) => to < from,
Self::Any(_) => true,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Rule {
pub conditions: Vec<Condition>,
pub effects: Vec<Effect>,
}
impl Rule {
fn allows(&self, from: &[u64], to: &[u64]) -> bool {
let conditions = self.conditions.iter().all(|c| match *c {
Condition::Zero(f) => value(from, f) == 0,
Condition::Positive(f) => value(from, f) > 0,
});
if !conditions {
return false;
}
let effects = self
.effects
.iter()
.all(|e| e.allows(value(from, e.feature()), value(to, e.feature())));
let others_unchanged = (0..from.len())
.filter(|&f| self.effects.iter().all(|e| e.feature() != f))
.all(|f| from[f] == to[f]);
effects && others_unchanged
}
}
fn value(values: &[u64], f: usize) -> u64 {
*values.get(f).unwrap_or_else(|| {
panic!(
"sketch rule names feature {f}, but only {} features are defined",
values.len()
)
})
}
pub fn siw_r<P, F>(
problem: &P,
rules: &[Rule],
features: F,
max_k: usize,
) -> SearchResult<P::Action>
where
P: WidthProblem,
P::State: Hash + Eq,
F: Fn(&P::State, &mut Vec<u64>),
{
let subgoals = SketchSubgoals {
problem,
rules,
features,
passed: HashSet::from([problem.initial_state()]),
buf: RefCell::new(Vec::new()),
};
serialize(
problem,
max_k,
None::<fn(&P::State, &mut Vec<u32>)>,
subgoals,
)
}
struct SketchSubgoals<'p, P: WidthProblem, F> {
problem: &'p P,
rules: &'p [Rule],
features: F,
passed: HashSet<P::State>,
buf: RefCell<Vec<u64>>,
}
impl<P, F> SketchSubgoals<'_, P, F>
where
P: WidthProblem,
F: Fn(&P::State, &mut Vec<u64>),
{
fn values(&self, state: &P::State) -> Vec<u64> {
let mut out = Vec::new();
(self.features)(state, &mut out);
out
}
fn allows(&self, from_values: &[u64], state: &P::State) -> bool {
let mut buf = self.buf.borrow_mut();
buf.clear();
(self.features)(state, &mut buf);
allowed(self.rules, from_values, &buf)
}
}
impl<P, F> Subgoals<P::State> for SketchSubgoals<'_, P, F>
where
P: WidthProblem,
P::State: Hash + Eq,
F: Fn(&P::State, &mut Vec<u64>),
{
type Anchor = (P::State, Vec<u64>);
fn anchor(&mut self, from: &P::State) -> Self::Anchor {
(from.clone(), self.values(from))
}
fn reached(&self, (from, from_values): &Self::Anchor, state: &P::State) -> bool {
self.problem.is_goal(state) || (state != from && self.allows(from_values, state))
}
fn advance(&mut self, state: &P::State) -> bool {
self.passed.insert(state.clone())
}
}
fn allowed(rules: &[Rule], from: &[u64], to: &[u64]) -> bool {
assert_eq!(
from.len(),
to.len(),
"sketch features must push the same number of values for every state"
);
rules.iter().any(|r| r.allows(from, to))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_problems::Line;
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "matches the sketch feature closure signature"
)]
fn position(s: &u32, out: &mut Vec<u64>) {
out.push(u64::from(*s));
}
#[test]
fn an_increasing_sketch_steps_to_the_goal() {
let rules = [Rule {
conditions: vec![],
effects: vec![Effect::Increase(0)],
}];
let r = siw_r(&Line { len: 6 }, &rules, position, 1);
assert_eq!(r.plan.as_deref(), Some(&[1; 6][..]));
}
#[test]
fn a_cycling_sketch_gives_up() {
let rules = [Rule {
conditions: vec![],
effects: vec![Effect::Any(0)],
}];
let r = siw_r(&Line { len: 6 }, &rules, position, 1);
assert!(r.plan.is_none());
}
#[test]
fn unmet_conditions_leave_only_the_goal() {
let rules = [Rule {
conditions: vec![Condition::Zero(0), Condition::Positive(0)],
effects: vec![Effect::Any(0)],
}];
let r = siw_r(&Line { len: 4 }, &rules, position, 1);
assert_eq!(r.plan.as_deref(), Some(&[1; 4][..]));
}
#[test]
fn rule_compatibility() {
let rule = |effects| Rule {
conditions: vec![],
effects,
};
assert!(rule(vec![Effect::Positive(0)]).allows(&[0, 5], &[2, 5]));
assert!(!rule(vec![Effect::Positive(0)]).allows(&[0, 5], &[2, 6]));
assert!(rule(vec![Effect::Zero(0)]).allows(&[3], &[0]));
assert!(rule(vec![Effect::Decrease(0)]).allows(&[3], &[2]));
assert!(!rule(vec![Effect::Decrease(0)]).allows(&[3], &[3]));
assert!(rule(vec![]).allows(&[3, 1], &[3, 1]));
}
#[test]
#[should_panic(expected = "names feature 3")]
fn rejects_unknown_features() {
let rules = [Rule {
conditions: vec![Condition::Positive(3)],
effects: vec![],
}];
siw_r(&Line { len: 2 }, &rules, position, 1);
}
}