use crate::iw::iw_plus_from;
use crate::{GoalCount, RelaxedPlan, SearchResult, WidthProblem};
pub fn siw<P: GoalCount>(problem: &P, max_k: usize) -> SearchResult<P::Action> {
serialize(
problem,
max_k,
None::<fn(&P::State, &mut Vec<u32>)>,
GoalCountDrop(problem),
)
}
pub fn siw_plus<P: RelaxedPlan>(problem: &P, max_k: usize) -> SearchResult<P::Action> {
serialize(
problem,
max_k,
Some(|s: &P::State, out: &mut Vec<u32>| problem.relaxed_plan_features(s, out)),
GoalCountDrop(problem),
)
}
pub(crate) trait Subgoals<S> {
type Anchor;
fn anchor(&mut self, from: &S) -> Self::Anchor;
fn reached(&self, anchor: &Self::Anchor, state: &S) -> bool;
fn advance(&mut self, _state: &S) -> bool {
true
}
}
struct GoalCountDrop<'p, P>(&'p P);
impl<P: GoalCount> Subgoals<P::State> for GoalCountDrop<'_, P> {
type Anchor = usize;
fn anchor(&mut self, from: &P::State) -> usize {
self.0.unsatisfied_goals(from)
}
fn reached(&self, g: &usize, state: &P::State) -> bool {
self.0.is_goal(state) || self.0.unsatisfied_goals(state) < *g
}
}
pub(crate) fn serialize<P, F, G>(
problem: &P,
max_k: usize,
mut oracle: Option<F>,
mut subgoals: G,
) -> SearchResult<P::Action>
where
P: WidthProblem,
F: FnMut(&P::State, &mut Vec<u32>),
G: Subgoals<P::State>,
{
let mut total = SearchResult {
plan: None,
expanded: 0,
generated: 0,
};
let mut state = problem.initial_state();
if problem.is_goal(&state) {
total.generated = 1;
}
let mut plan = Vec::new();
while !problem.is_goal(&state) {
let anchor = subgoals.anchor(&state);
let is_subgoal = |s: &P::State| subgoals.reached(&anchor, s);
let Some((subplan, next)) = reach_subgoal(
problem,
&state,
max_k,
oracle.as_mut(),
is_subgoal,
&mut total,
) else {
return total;
};
if !subgoals.advance(&next) {
return total;
}
plan.extend(subplan);
state = next;
}
total.plan = Some(plan);
total
}
fn reach_subgoal<P, F>(
problem: &P,
state: &P::State,
max_k: usize,
mut oracle: Option<&mut F>,
is_subgoal: impl Fn(&P::State) -> bool + Copy,
total: &mut SearchResult<P::Action>,
) -> Option<(Vec<P::Action>, P::State)>
where
P: WidthProblem,
F: FnMut(&P::State, &mut Vec<u32>),
{
for k in 1..=max_k {
let run_oracle = oracle.as_deref_mut();
let (r, end) = iw_plus_from(problem, state.clone(), k, is_subgoal, run_oracle);
total.expanded += r.expanded;
total.generated += r.generated;
if let (Some(subplan), Some(end)) = (r.plan, end) {
return Some((subplan, end));
}
}
None
}