use std::collections::VecDeque;
use crate::{Node, NoveltyTable, SearchResult, WidthProblem, extract_plan, sorted_set};
mod incremental;
mod policy;
pub use incremental::ihiw;
pub use policy::pi_hiw;
pub fn hiw<P, H>(
problem: &P,
high: H,
num_high: usize,
w_high: usize,
w_low: usize,
) -> SearchResult<P::Action>
where
P: WidthProblem,
H: Fn(&P::State, &mut Vec<u32>),
{
run(problem, high, num_high, w_high, w_low, false).result
}
pub(crate) struct Run<P: WidthProblem> {
pub result: SearchResult<P::Action>,
pub nodes: Vec<Node<P::State, P::Action>>,
pub pruned: Vec<(usize, P::State)>,
}
pub(crate) fn run<P, H>(
problem: &P,
high: H,
num_high: usize,
w_high: usize,
w_low: usize,
log_pruned: bool,
) -> Run<P>
where
P: WidthProblem,
H: Fn(&P::State, &mut Vec<u32>),
{
assert!(w_high >= 1 && w_low >= 1, "width bound must be at least 1");
let mut search = Search {
problem,
high,
high_table: NoveltyTable::new(num_high, w_high),
w_low,
nodes: Vec::new(),
log_pruned,
pruned: Vec::new(),
feats: Vec::new(),
result: SearchResult {
plan: None,
expanded: 0,
generated: 1,
},
};
let root = problem.initial_state();
let root_high = sorted_set(|out| (search.high)(&root, out));
search.high_table.evaluate_and_insert(&root_high);
if problem.is_goal(&root) {
search.result.plan = Some(Vec::new());
return search.finish();
}
search.nodes.push(Node {
state: root,
parent: None,
action: None,
});
let mut open = VecDeque::from([LowSearch::new(&mut search, 0, root_high)]);
while let Some(mut low) = open.pop_front() {
match low.next_high(&mut search) {
Step::Goal(goal) => {
search.result.plan = Some(extract_plan(&search.nodes, goal));
break;
}
Step::High(node, features) => {
open.push_back(LowSearch::new(&mut search, node, features));
open.push_back(low);
}
Step::Done => {}
}
}
search.finish()
}
struct Search<'p, P: WidthProblem, H> {
problem: &'p P,
high: H,
high_table: NoveltyTable,
w_low: usize,
nodes: Vec<Node<P::State, P::Action>>,
log_pruned: bool,
pruned: Vec<(usize, P::State)>,
feats: Vec<u32>,
result: SearchResult<P::Action>,
}
impl<P, H> Search<'_, P, H>
where
P: WidthProblem,
H: Fn(&P::State, &mut Vec<u32>),
{
fn finish(self) -> Run<P> {
Run {
result: self.result,
nodes: self.nodes,
pruned: self.pruned,
}
}
fn classify(
&mut self,
state: &P::State,
features: &[u32],
table: &mut NoveltyTable,
) -> Option<Next> {
if self.problem.is_goal(state) {
return Some(Next::Goal);
}
let high = sorted_set(|out| (self.high)(state, out));
if high != features {
return self
.high_table
.evaluate_and_insert(&high)
.map(|_| Next::High(high));
}
self.feats.clear();
self.problem.features(state, &mut self.feats);
table.evaluate_and_insert(&self.feats).map(|_| Next::Low)
}
fn push(&mut self, state: P::State, parent: usize, action: P::Action) -> usize {
self.nodes.push(Node {
state,
parent: Some(parent),
action: Some(action),
});
self.nodes.len() - 1
}
}
struct LowSearch<P: WidthProblem> {
features: Vec<u32>,
table: NoveltyTable,
open: VecDeque<usize>,
parent: usize,
pending: Vec<(P::Action, P::State)>,
}
impl<P: WidthProblem> LowSearch<P> {
fn new<H>(search: &mut Search<'_, P, H>, root: usize, features: Vec<u32>) -> Self {
let mut table = NoveltyTable::new(search.problem.num_features(), search.w_low);
search.feats.clear();
search
.problem
.features(&search.nodes[root].state, &mut search.feats);
table.evaluate_and_insert(&search.feats);
Self {
features,
table,
open: VecDeque::from([root]),
parent: root,
pending: Vec::new(),
}
}
fn next_high<H>(&mut self, search: &mut Search<'_, P, H>) -> Step
where
H: Fn(&P::State, &mut Vec<u32>),
{
loop {
if self.pending.is_empty() && !self.expand_next(search) {
return Step::Done;
}
while let Some((action, state)) = self.pending.pop() {
search.result.generated += 1;
let Some(next) = search.classify(&state, &self.features, &mut self.table) else {
if search.log_pruned {
search.pruned.push((self.parent, state));
}
continue;
};
let j = search.push(state, self.parent, action);
match next {
Next::Goal => return Step::Goal(j),
Next::Low => self.open.push_back(j),
Next::High(features) => return Step::High(j, features),
}
}
}
}
fn expand_next<H>(&mut self, search: &mut Search<'_, P, H>) -> bool {
let Some(i) = self.open.pop_front() else {
return false;
};
search.result.expanded += 1;
self.parent = i;
search
.problem
.successors(&search.nodes[i].state, &mut self.pending);
self.pending.reverse();
true
}
}
enum Step {
Goal(usize),
High(usize, Vec<u32>),
Done,
}
enum Next {
Goal,
Low,
High(Vec<u32>),
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
pub(crate) struct Corridor {
pub len: u32,
pub key_at: u32,
pub key_feature: bool,
}
impl Corridor {
pub fn new(len: u32) -> Self {
Self {
len,
key_at: len,
key_feature: false,
}
}
}
impl WidthProblem for Corridor {
type State = (u32, bool);
type Action = i8;
fn initial_state(&self) -> (u32, bool) {
(0, false)
}
fn successors(&self, &(p, key): &(u32, bool), out: &mut Vec<(i8, (u32, bool))>) {
if p > 0 {
out.push((-1, (p - 1, key || p - 1 == self.key_at)));
}
if p < self.len {
out.push((1, (p + 1, key || p + 1 == self.key_at)));
}
}
fn features(&self, &(p, key): &(u32, bool), out: &mut Vec<u32>) {
out.push(p);
if key && self.key_feature {
out.push(self.len + 1);
}
}
fn num_features(&self) -> usize {
self.len as usize + 2
}
fn is_goal(&self, &(p, key): &(u32, bool)) -> bool {
p == 0 && key
}
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "matches the high-level feature closure signature"
)]
fn key(&(_, key): &(u32, bool), out: &mut Vec<u32>) {
if key {
out.push(0);
}
}
#[test]
fn the_key_splits_the_corridor() {
let corridor = Corridor::new(5);
let r = hiw(&corridor, key, 1, 1, 1);
assert!(crate::iw(&corridor, 1).plan.is_none());
assert_eq!(
r.plan.as_deref(),
Some(&[1, 1, 1, 1, 1, -1, -1, -1, -1, -1][..])
);
assert_eq!(r.expanded, 10, "positions 0..5 without, 5..1 with the key");
}
#[test]
fn low_level_searches_pause_at_new_high_level_states() {
let corridor = Corridor {
len: 10,
key_at: 2,
key_feature: false,
};
let r = hiw(&corridor, key, 1, 1, 1);
assert_eq!(r.plan.as_deref(), Some(&[1, 1, -1, -1][..]));
assert_eq!(
r.expanded, 4,
"positions 0 and 1, then 2 and 1 with the key"
);
}
#[test]
fn a_constant_high_level_feature_is_iw() {
let corridor = Corridor::new(3);
let constant = |_: &(u32, bool), out: &mut Vec<u32>| out.push(0);
let r = hiw(&corridor, constant, 1, 1, 1);
let iw = crate::iw(&corridor, 1);
assert!(r.plan.is_none());
assert_eq!((r.expanded, r.generated), (iw.expanded, iw.generated));
}
#[test]
#[should_panic(expected = "width bound must be at least 1")]
fn rejects_high_width_zero() {
hiw(&Corridor::new(0), key, 1, 0, 1);
}
#[test]
#[should_panic(expected = "width bound must be at least 1")]
fn rejects_low_width_zero() {
hiw(&Corridor::new(0), key, 1, 1, 0);
}
}