1use crate::rng::SplitMix64;
2use crate::{Node, SearchResult, WidthProblem, extract_plan};
3
4pub fn rollout_iw<P: WidthProblem>(problem: &P, seed: u64) -> SearchResult<P::Action> {
26 search(problem, None::<Weights<P>>, seed)
27}
28
29pub fn pi_iw<P, F>(problem: &P, policy: F, seed: u64) -> SearchResult<P::Action>
50where
51 P: WidthProblem,
52 F: FnMut(&P::State, &[(P::Action, P::State)], &mut Vec<f64>),
53{
54 search(problem, Some(policy), seed)
55}
56
57type Weights<P> = fn(
59 &<P as WidthProblem>::State,
60 &[(<P as WidthProblem>::Action, <P as WidthProblem>::State)],
61 &mut Vec<f64>,
62);
63
64fn search<P, F>(problem: &P, policy: Option<F>, seed: u64) -> SearchResult<P::Action>
67where
68 P: WidthProblem,
69 F: FnMut(&P::State, &[(P::Action, P::State)], &mut Vec<f64>),
70{
71 let mut tree = Tree::new(problem, policy, seed, None);
72 let root = problem.initial_state();
73 if problem.is_goal(&root) {
74 tree.result.plan = Some(Vec::new());
75 return tree.result;
76 }
77
78 tree.add_root(root);
79 while !tree.is_exhausted() {
80 if let Outcome::Goal(goal) = tree.rollout() {
81 tree.result.plan = Some(extract_plan(&tree.nodes, goal));
82 break;
83 }
84 }
85
86 tree.result
87}
88
89struct Meta {
91 depth: usize,
93 children: Option<Vec<usize>>,
95 solved: bool,
97 visited: bool,
99 weight: f64,
102}
103
104pub(crate) enum Outcome {
106 Goal(usize),
108 Boundary(usize),
111 Solved,
113}
114
115pub(crate) type Partition<'a, S> = (&'a dyn Fn(&S, &mut Vec<u32>), Vec<u32>);
118
119enum Verdict {
121 Continue,
123 Prune,
125}
126
127pub(crate) struct Tree<'p, P: WidthProblem, F> {
129 problem: &'p P,
131 partition: Option<Partition<'p, P::State>>,
134 policy: Option<F>,
136 weights: Vec<f64>,
138 pub nodes: Vec<Node<P::State, P::Action>>,
140 meta: Vec<Meta>,
142 depth_of: Vec<usize>,
144 rng: SplitMix64,
146 feats: Vec<u32>,
148 succ: Vec<(P::Action, P::State)>,
150 pub result: SearchResult<P::Action>,
152}
153
154impl<'p, P, F> Tree<'p, P, F>
155where
156 P: WidthProblem,
157 F: FnMut(&P::State, &[(P::Action, P::State)], &mut Vec<f64>),
158{
159 pub fn new(
162 problem: &'p P,
163 policy: Option<F>,
164 seed: u64,
165 partition: Option<Partition<'p, P::State>>,
166 ) -> Self {
167 Self {
168 problem,
169 partition,
170 policy,
171 weights: Vec::new(),
172 nodes: Vec::new(),
173 meta: Vec::new(),
174 depth_of: vec![usize::MAX; problem.num_features()],
175 rng: SplitMix64::new(seed),
176 feats: Vec::new(),
177 succ: Vec::new(),
178 result: SearchResult {
179 plan: None,
180 expanded: 0,
181 generated: 1,
182 },
183 }
184 }
185
186 pub fn add_root(&mut self, root: P::State) {
188 self.feats.clear();
189 self.problem.features(&root, &mut self.feats);
190 for &f in &self.feats {
191 self.depth_of[f as usize] = 0;
192 }
193
194 self.push(root, None, None, 0, 0.0);
195 self.meta[0].visited = true;
196 }
197
198 pub fn is_exhausted(&self) -> bool {
200 self.meta[0].solved
201 }
202
203 pub fn rollout(&mut self) -> Outcome {
206 let mut n = 0;
207 loop {
208 if self.meta[n].children.is_none() {
209 if let Some(goal) = self.expand(n) {
210 return Outcome::Goal(goal);
211 }
212 }
213
214 let Some(child) = self.pick_unsolved_child(n) else {
215 self.solve(n);
217 return Outcome::Solved;
218 };
219
220 n = child;
221 if self.is_boundary(n) {
222 self.solve(n);
223 return Outcome::Boundary(n);
224 }
225
226 if let Verdict::Prune = self.novelty(n) {
227 self.solve(n);
228 return Outcome::Solved;
229 }
230 }
231 }
232
233 fn is_boundary(&mut self, n: usize) -> bool {
235 let Some((high, root_features)) = &self.partition else {
236 return false;
237 };
238
239 self.feats.clear();
240 high(&self.nodes[n].state, &mut self.feats);
241 self.feats.sort_unstable();
242 self.feats.dedup();
243 self.feats != *root_features
244 }
245
246 fn expand(&mut self, n: usize) -> Option<usize> {
248 self.result.expanded += 1;
249 let mut succ = std::mem::take(&mut self.succ);
250 succ.clear();
251 self.problem.successors(&self.nodes[n].state, &mut succ);
252 self.ask_policy(n, &succ);
253
254 let depth = self.meta[n].depth + 1;
255 let mut children = Vec::with_capacity(succ.len());
256 let mut goal = None;
257 for (i, (action, state)) in succ.drain(..).enumerate() {
258 self.result.generated += 1;
259 let is_goal = self.problem.is_goal(&state);
260 let weight = self.weights.get(i).copied().unwrap_or(1.0);
261 let child = self.push(state, Some(n), Some(action), depth, weight);
262 children.push(child);
263 if is_goal {
264 goal.get_or_insert(child);
265 }
266 }
267
268 self.succ = succ;
269 self.meta[n].children = Some(children);
270 goal
271 }
272
273 fn ask_policy(&mut self, n: usize, succ: &[(P::Action, P::State)]) {
280 self.weights.clear();
281 let Some(policy) = self.policy.as_mut() else {
282 return;
283 };
284
285 policy(&self.nodes[n].state, succ, &mut self.weights);
286 assert_eq!(
287 self.weights.len(),
288 succ.len(),
289 "policy must push one weight per successor"
290 );
291 assert!(
292 self.weights.iter().all(|w| w.is_finite() && *w >= 0.0),
293 "policy weights must be finite and non-negative"
294 );
295 assert!(
297 self.weights.iter().sum::<f64>().is_finite(),
298 "policy weights must have a finite sum"
299 );
300 }
301
302 fn novelty(&mut self, n: usize) -> Verdict {
305 let depth = self.meta[n].depth;
306 self.feats.clear();
307 self.problem.features(&self.nodes[n].state, &mut self.feats);
308
309 if self.meta[n].visited {
310 let kept = self
311 .feats
312 .iter()
313 .any(|&f| self.depth_of[f as usize] == depth);
314 return if kept {
315 Verdict::Continue
316 } else {
317 Verdict::Prune
318 };
319 }
320
321 self.meta[n].visited = true;
322 let mut novel = false;
323 for &f in &self.feats {
324 let d = &mut self.depth_of[f as usize];
325 if depth < *d {
326 *d = depth;
327 novel = true;
328 }
329 }
330
331 if novel {
332 Verdict::Continue
333 } else {
334 Verdict::Prune
335 }
336 }
337
338 fn pick_unsolved_child(&mut self, n: usize) -> Option<usize> {
342 if self.policy.is_some() {
343 if let Some(child) = self.pick_weighted_child(n) {
344 return Some(child);
345 }
346 }
347
348 self.pick_uniform_child(n)
349 }
350
351 fn pick_weighted_child(&mut self, n: usize) -> Option<usize> {
354 let unit = self.rng.unit();
355 let meta = &self.meta;
356 let candidates = || {
357 meta[n]
358 .children
359 .as_deref()
360 .unwrap_or_default()
361 .iter()
362 .copied()
363 .filter(|&c| !meta[c].solved && meta[c].weight > 0.0)
364 };
365 let total: f64 = candidates().map(|c| meta[c].weight).sum();
366 let last = candidates().next_back()?;
367
368 let mut target = unit * total;
369 for c in candidates() {
370 target -= meta[c].weight;
371 if target < 0.0 {
372 return Some(c);
373 }
374 }
375
376 Some(last)
378 }
379
380 fn pick_uniform_child(&mut self, n: usize) -> Option<usize> {
382 let count_unsolved = |t: &Self| {
383 let children = t.meta[n].children.as_deref().unwrap_or_default();
384 children.iter().filter(|&&c| !t.meta[c].solved).count()
385 };
386 let unsolved = count_unsolved(self);
387 if unsolved == 0 {
388 return None;
389 }
390
391 let pick = self.rng.below(unsolved);
392 self.meta[n]
393 .children
394 .as_deref()
395 .unwrap_or_default()
396 .iter()
397 .copied()
398 .filter(|&c| !self.meta[c].solved)
399 .nth(pick)
400 }
401
402 fn solve(&mut self, mut n: usize) {
405 self.meta[n].solved = true;
406 while let Some(p) = self.nodes[n].parent {
407 let children = self.meta[p].children.as_deref().unwrap_or_default();
408 if !children.iter().all(|&c| self.meta[c].solved) {
409 return;
410 }
411
412 self.meta[p].solved = true;
413 n = p;
414 }
415 }
416
417 fn push(
419 &mut self,
420 state: P::State,
421 parent: Option<usize>,
422 action: Option<P::Action>,
423 depth: usize,
424 weight: f64,
425 ) -> usize {
426 self.nodes.push(Node {
427 state,
428 parent,
429 action,
430 });
431 self.meta.push(Meta {
432 depth,
433 children: None,
434 solved: false,
435 visited: false,
436 weight,
437 });
438
439 self.nodes.len() - 1
440 }
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
446 use crate::test_problems::Line;
447
448 #[test]
451 fn reaches_a_width_one_goal_for_every_seed() {
452 let line = Line { len: 6 };
453 for seed in 0..50 {
454 let plan = rollout_iw(&line, seed).plan.expect("width-1 goal");
455 assert_eq!(plan, [1; 6], "seed {seed}");
456 }
457 }
458
459 #[test]
462 fn a_greedy_policy_walks_straight_to_the_goal() {
463 let line = Line { len: 6 };
464 let towards_goal = |_: &u32, succ: &[(i8, u32)], out: &mut Vec<f64>| {
465 out.extend(succ.iter().map(|&(a, _)| if a > 0 { 1.0 } else { 0.0 }));
466 };
467 for seed in 0..20 {
468 let r = pi_iw(&line, towards_goal, seed);
469 assert_eq!(r.plan.as_deref(), Some(&[1; 6][..]), "seed {seed}");
470 assert_eq!(r.expanded, 6, "seed {seed}");
471 }
472 }
473
474 #[test]
477 fn zero_weight_children_are_tried_last() {
478 let line = Line { len: 6 };
479 let away = |_: &u32, succ: &[(i8, u32)], out: &mut Vec<f64>| {
480 out.extend(succ.iter().map(|&(a, _)| if a < 0 { 1.0 } else { 0.0 }));
481 };
482 for seed in 0..20 {
483 let plan = pi_iw(&line, away, seed).plan.expect("width-1 goal");
484 assert_eq!(plan, [1; 6], "seed {seed}");
485 }
486 }
487
488 #[test]
490 #[should_panic(expected = "finite and non-negative")]
491 fn rejects_negative_weights() {
492 let negative = |_: &u32, succ: &[(i8, u32)], out: &mut Vec<f64>| {
493 out.extend(succ.iter().map(|_| -1.0));
494 };
495 pi_iw(&Line { len: 3 }, negative, 0);
496 }
497
498 #[test]
501 #[should_panic(expected = "finite sum")]
502 fn rejects_weights_with_an_infinite_sum() {
503 let huge = |_: &u32, succ: &[(i8, u32)], out: &mut Vec<f64>| {
504 out.extend(succ.iter().map(|_| f64::MAX));
505 };
506 pi_iw(&Line { len: 3 }, huge, 0);
507 }
508
509 #[test]
511 #[should_panic(expected = "one weight per successor")]
512 fn rejects_a_missing_weight() {
513 pi_iw(
514 &Line { len: 3 },
515 |_: &u32, _: &[(i8, u32)], _: &mut Vec<f64>| {},
516 0,
517 );
518 }
519
520 #[test]
522 fn gives_up_when_the_root_is_solved() {
523 let r = rollout_iw(&NoGoal(Line { len: 6 }), 3);
524 assert!(r.plan.is_none());
525 assert_eq!(r.expanded, 7, "every position expanded once");
526 }
527
528 struct NoGoal(Line);
530
531 impl WidthProblem for NoGoal {
532 type State = u32;
533 type Action = i8;
534
535 fn initial_state(&self) -> u32 {
536 self.0.initial_state()
537 }
538 fn successors(&self, s: &u32, out: &mut Vec<(i8, u32)>) {
539 self.0.successors(s, out);
540 }
541 fn features(&self, s: &u32, out: &mut Vec<u32>) {
542 self.0.features(s, out);
543 }
544 fn num_features(&self) -> usize {
545 self.0.num_features()
546 }
547 fn is_goal(&self, _: &u32) -> bool {
548 false
549 }
550 }
551}