Skip to main content

mapf_search/
pibt_turns.rs

1//! PIBT*_T ([`pibt_turns`], Tao, Yu and Hu 2026): PIBT for agents that face a heading,
2//! move only forward, and need time to turn in place, on any [`OrientedGraph`].
3//!
4//! Plain PIBT ([`pibt`](crate::pibt())) assumes that an agent that accepts a push leaves its
5//! vertex at the next step. With turns it may first have to rotate, and still stand there.
6//! PIBT*_T keeps PIBT's priority inheritance and backtracking and adds:
7//!
8//! - **Turn-aware choices.** An agent requests the neighbour (or its own vertex) with the
9//!   least `TC`: the turns and the move to get there plus the exact remaining time from the
10//!   state it arrives in (`costs`); `Compute_action` then moves forward if it faces the
11//!   request, else turns once towards it.
12//! - **Staying behind a turning agent.** An agent whose requested vertex stays occupied,
13//!   because its occupant only turns, waits instead of moving in.
14//! - **Cycles.** When a chain of requests closes back on the agent that started it, the
15//!   agents of the cycle all move at once if each faces its request, else the misaligned
16//!   ones turn and the others wait (the paper's Definition 1 and Proposition 2). It cannot
17//!   close on a later agent of the chain: each of those stands on the vertex its pusher
18//!   has claimed.
19//! - **Swaps** (`swap`): in a corridor where two agents must pass each other, the pusher
20//!   reverses its preferences and pulls the other agent into its vertex.
21//! - **The k-push escape trigger.** An agent pushed by the same agent `k = 2` times shuffles
22//!   its preferences the next time, which breaks livelocks of repeated pushing.
23//! - **Remembered requests.** An agent that turned (or waited) towards a vertex requests it
24//!   first again at the next step, so it finishes the turn instead of changing its mind.
25//!
26//! The run ends at the first step at which every agent stands at its goal, facing any way.
27
28mod costs;
29mod swap;
30
31use alloc::collections::BTreeMap;
32use alloc::vec;
33use alloc::vec::Vec;
34
35use heuristic_search::{Budget, Stats};
36
37use self::costs::Costs;
38use crate::graph::{Heading, OrientedGraph, Vertex};
39use crate::instance::{AgentId, Instance};
40use crate::path::Path;
41use crate::pibt::{Priorities, all_at_goals};
42use crate::random::Random;
43use crate::solution::{MapfResult, Outcome, Solution};
44
45/// How often the same pusher may push an agent before the agent shuffles its preferences:
46/// the paper's `k`.
47const PUSH_LIMIT: u32 = 2;
48
49/// The result of a [`pibt_turns`] run.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct TurnResult {
52    /// How the run ended, and its counters. A solution's paths hold each agent's vertex at
53    /// every step of the run, turns as waits, so [`first_conflict`](crate::first_conflict)
54    /// and the costs apply as for any plan.
55    pub result: MapfResult,
56    /// Each agent's heading at every step of the run, indexed like the paths: the same
57    /// length as its path in a solution, empty otherwise.
58    pub headings: Vec<Vec<Heading>>,
59}
60
61/// Finds a conflict-free plan for agents that need time to turn, with PIBT*_T: one step
62/// for all agents at a time, by priority, with priority inheritance, backtracking, cycle
63/// handling, swaps and the push escape trigger.
64///
65/// `headings[i]` is the heading agent `i` starts with. Every random choice comes from
66/// `seed`. The plan has no quality guarantee, and the method is not complete: on an
67/// unsolvable instance it runs until its budget, so always pass one. The result is
68/// [`Outcome::Unsolvable`] only if an agent cannot reach its goal even alone, and never
69/// [`Outcome::Exhausted`].
70///
71/// `budget` is asked before every step; [`MapfResult::stats`] counts steps in
72/// [`Stats::expanded`] and per-agent decisions in [`Stats::generated`].
73///
74/// # Panics
75///
76/// Panics if `headings` does not hold one heading below
77/// [`OrientedGraph::heading_count`] per agent, or if turning cannot reach every heading.
78///
79/// # Examples
80///
81/// ```
82/// use mapf_search::{Agent, Grid, Instance, Limits, first_conflict, pibt_turns};
83///
84/// // Two robots swap the ends of the top row of a free 3x2 grid, both facing east.
85/// let grid = Grid::new(3, 2);
86/// let agents = vec![Agent { start: 0, goal: 2 }, Agent { start: 2, goal: 0 }];
87/// let instance = Instance::new(grid, agents)?;
88///
89/// let run = pibt_turns(&instance, &[Grid::EAST, Grid::EAST], 0, Limits::expansions(200));
90/// let solution = run.result.solution().expect("one robot goes around");
91/// assert_eq!(first_conflict(&solution.paths), None);
92/// assert_eq!(run.headings[1][0], Grid::EAST);
93/// # Ok::<(), mapf_search::InstanceError>(())
94/// ```
95pub fn pibt_turns<G: OrientedGraph>(
96    instance: &Instance<G>,
97    headings: &[Heading],
98    seed: u64,
99    mut budget: impl Budget<Stats>,
100) -> TurnResult {
101    let graph = instance.graph();
102    let agents = instance.agents();
103    assert_eq!(headings.len(), agents.len(), "one heading per agent");
104    assert!(
105        headings
106            .iter()
107            .all(|&heading| heading < graph.heading_count()),
108        "headings are below the heading count"
109    );
110
111    let costs = Costs::new(graph, agents);
112    let start_distance: Option<Vec<u32>> = agents
113        .iter()
114        .zip(headings)
115        .enumerate()
116        .map(|(index, (agent, &heading))| costs.remaining(index, agent.start, heading))
117        .collect();
118    let Some(start_distance) = start_distance else {
119        return TurnResult {
120            result: MapfResult {
121                outcome: Outcome::Unsolvable,
122                stats: Stats::default(),
123            },
124            headings: Vec::new(),
125        };
126    };
127
128    let mut run = Run::new(instance, costs, headings, start_distance, seed);
129    let outcome = run.solve(&mut budget);
130    let headings = if matches!(outcome, Outcome::Solved(_)) {
131        run.heading_paths
132    } else {
133        Vec::new()
134    };
135
136    TurnResult {
137        result: MapfResult {
138            outcome,
139            stats: run.stats,
140        },
141        headings,
142    }
143}
144
145/// The state of one [`pibt_turns`] run.
146struct Run<'a, G> {
147    /// The instance being solved.
148    instance: &'a Instance<G>,
149    /// The turn-aware cost tables.
150    costs: Costs<'a, G>,
151    /// Each agent's vertex at the current step.
152    here: Vec<Vertex>,
153    /// Each agent's heading at the current step.
154    heading: Vec<Heading>,
155    /// The vertex each agent has claimed while its decision is in progress.
156    claim: Vec<Option<Vertex>>,
157    /// Each agent's decided vertex and heading for the next step.
158    decided: Vec<Option<(Vertex, Heading)>>,
159    /// The agent holding each vertex for the next step, by vertex.
160    reserved: Vec<Option<AgentId>>,
161    /// The agent at each vertex at the current step, by vertex.
162    occupant: Vec<Option<AgentId>>,
163    /// The vertex each agent turned or waited towards last, requested first next time.
164    intent: Vec<Option<Vertex>>,
165    /// The agents' priorities.
166    priorities: Priorities,
167    /// How often an agent (first) was pushed into a new vertex by another (second).
168    pushes: BTreeMap<(AgentId, AgentId), u32>,
169    /// The requests of the current inheritance chain: each agent on it and the vertex it
170    /// requests, from the agent planned first.
171    chain: Vec<(AgentId, Vertex)>,
172    /// The source of the random tie-breaks and shuffles.
173    random: Random,
174    /// Each agent's vertex at every step so far.
175    paths: Vec<Path>,
176    /// Each agent's heading at every step so far.
177    heading_paths: Vec<Vec<Heading>>,
178    /// Counters reported in [`MapfResult::stats`].
179    stats: Stats,
180}
181
182impl<'a, G: OrientedGraph> Run<'a, G> {
183    /// A run from the starts of `instance`, facing `headings`, each `start_distance[agent]`
184    /// steps from its goal.
185    fn new(
186        instance: &'a Instance<G>,
187        costs: Costs<'a, G>,
188        headings: &[Heading],
189        start_distance: Vec<u32>,
190        seed: u64,
191    ) -> Self {
192        let agents = instance.agents().len();
193        let vertices = instance.graph().vertex_count();
194        let here: Vec<Vertex> = instance.agents().iter().map(|agent| agent.start).collect();
195
196        Self {
197            instance,
198            costs,
199            paths: here.iter().map(|&vertex| vec![vertex]).collect(),
200            heading_paths: headings.iter().map(|&heading| vec![heading]).collect(),
201            heading: headings.to_vec(),
202            here,
203            claim: vec![None; agents],
204            decided: vec![None; agents],
205            reserved: vec![None; vertices],
206            occupant: vec![None; vertices],
207            intent: vec![None; agents],
208            priorities: Priorities::new(start_distance),
209            pushes: BTreeMap::new(),
210            chain: Vec::new(),
211            random: Random::new(seed),
212            stats: Stats::default(),
213        }
214    }
215
216    /// Takes steps until every agent stands at its goal or the budget ends.
217    fn solve(&mut self, budget: &mut impl Budget<Stats>) -> Outcome {
218        loop {
219            if all_at_goals(&self.here, self.instance.agents()) {
220                return Outcome::Solved(Solution::new(self.paths.clone()));
221            }
222
223            if budget.exhausted(&self.stats) {
224                return Outcome::LimitReached;
225            }
226
227            self.step();
228        }
229    }
230
231    /// One step: updates the priorities, decides every agent by decreasing priority, then
232    /// carries the decisions out.
233    fn step(&mut self) {
234        self.stats.expanded += 1;
235
236        for (agent, &here) in self.here.iter().enumerate() {
237            self.occupant[here] = Some(agent);
238        }
239
240        for agent in self.priorities.update(&self.here, self.instance.agents()) {
241            if self.decided[agent].is_none() {
242                self.chain.clear();
243                self.plan(agent, None);
244            }
245        }
246
247        self.advance();
248    }
249
250    /// Carries out every decision and clears the step's bookkeeping.
251    fn advance(&mut self) {
252        for agent in 0..self.here.len() {
253            let (vertex, heading) = self.decided[agent].take().expect("every agent decided");
254            self.occupant[self.here[agent]] = None;
255            self.reserved[vertex] = None;
256            self.claim[agent] = None;
257            self.here[agent] = vertex;
258            self.heading[agent] = heading;
259            self.paths[agent].push(vertex);
260            self.heading_paths[agent].push(heading);
261        }
262    }
263
264    /// The recursive procedure: decides `agent`, which inherited its priority from
265    /// `pusher` if any. Returns `false` if it is stuck and stays put.
266    fn plan(&mut self, agent: AgentId, pusher: Option<AgentId>) -> bool {
267        self.stats.generated += 1;
268
269        let mut candidates = self.candidates(agent);
270        if let Some(pusher) = pusher {
271            self.escape(&mut candidates, agent, pusher);
272        }
273
274        let partner = self.swap_partner(agent, &candidates);
275        if partner.is_some() {
276            candidates.reverse();
277        }
278
279        self.request_first(agent, &mut candidates);
280
281        for (skipped, &target) in candidates.iter().enumerate() {
282            if self.reserved[target].is_some() || pusher.is_some_and(|p| self.here[p] == target) {
283                continue;
284            }
285
286            self.claim(agent, target);
287            if self
288                .chain
289                .first()
290                .is_some_and(|&(first, _)| self.here[first] == target)
291            {
292                self.chain.push((agent, target));
293                self.resolve_cycle();
294                self.chain.pop();
295                return true;
296            }
297
298            if !self.clear_way(agent, target) {
299                self.unclaim(agent, target);
300                continue;
301            }
302
303            if self.decided[agent].is_none() {
304                self.decide(agent, target, pusher);
305                if skipped == 0 {
306                    if let Some(partner) = partner {
307                        self.pull(agent, partner);
308                    }
309                }
310            }
311
312            return true;
313        }
314
315        self.stay(agent, self.heading[agent]);
316
317        false
318    }
319
320    /// Lets the agent standing at `target`, if it is still undecided, decide first with the
321    /// priority of `agent`. Returns `false` if that agent is stuck.
322    fn clear_way(&mut self, agent: AgentId, target: Vertex) -> bool {
323        let Some(other) = self.occupant[target] else {
324            return true;
325        };
326
327        if other == agent || self.claim[other].is_some() || self.decided[other].is_some() {
328            return true;
329        }
330
331        self.chain.push((agent, target));
332        let moved = self.plan(other, Some(agent));
333        self.chain.pop();
334
335        moved
336    }
337
338    /// Decides `agent`, which holds the claim on `target`: `Compute_action` towards it,
339    /// except that it waits if the vertex stays occupied by an agent that only turns.
340    fn decide(&mut self, agent: AgentId, target: Vertex, pusher: Option<AgentId>) {
341        let (here, heading) = (self.here[agent], self.heading[agent]);
342        let (vertex, next_heading) = self.costs.action(here, heading, target);
343
344        if vertex != here && self.stays_occupied(agent, target) {
345            self.unclaim(agent, target);
346            self.intent[agent] = Some(target);
347            self.stay(agent, heading);
348            return;
349        }
350
351        if vertex == here {
352            self.unclaim(agent, target);
353            self.intent[agent] = (next_heading != heading).then_some(target);
354            self.stay(agent, next_heading);
355            return;
356        }
357
358        self.decided[agent] = Some((vertex, next_heading));
359        self.reserved[vertex] = Some(agent);
360        self.intent[agent] = None;
361        if let Some(pusher) = pusher {
362            *self.pushes.entry((agent, pusher)).or_default() += 1;
363        }
364    }
365
366    /// Returns `true` if another agent stands at `vertex` and stays there at the next step.
367    fn stays_occupied(&self, agent: AgentId, vertex: Vertex) -> bool {
368        self.occupant[vertex].is_some_and(|other| {
369            other != agent && self.decided[other].is_some_and(|(next, _)| next == vertex)
370        })
371    }
372
373    /// The paper's cycle handling for the chain, which closes on the agent that started it:
374    /// everyone moves into their request if all face it, else the misaligned agents turn
375    /// towards it and the others wait.
376    fn resolve_cycle(&mut self) {
377        let cycle: Vec<(AgentId, Vertex)> = self.chain.clone();
378        let aligned = cycle.iter().all(|&(agent, target)| {
379            self.instance
380                .graph()
381                .forward(self.here[agent], self.heading[agent])
382                == Some(target)
383        });
384
385        for &(agent, target) in &cycle {
386            self.unclaim(agent, target);
387        }
388
389        for &(agent, target) in &cycle {
390            let heading = self.heading[agent];
391            if aligned {
392                self.decided[agent] = Some((target, heading));
393                self.reserved[target] = Some(agent);
394                self.intent[agent] = None;
395            } else {
396                let (_, turned) = self.costs.action(self.here[agent], heading, target);
397                self.intent[agent] = (turned != heading).then_some(target);
398                self.stay(agent, turned);
399            }
400        }
401    }
402
403    /// Pulls the swap `partner` of `agent` into the vertex `agent` leaves, turning it first
404    /// if it does not face it; neither moves if `agent` stays.
405    fn pull(&mut self, agent: AgentId, partner: AgentId) {
406        let vacated = self.here[agent];
407        let free = self.reserved[vacated].is_none_or(|holder| holder == agent);
408        if self.claim[partner].is_some() || self.decided[partner].is_some() || !free {
409            return;
410        }
411
412        let (here, heading) = (self.here[partner], self.heading[partner]);
413        let (vertex, next_heading) = self.costs.action(here, heading, vacated);
414        let agent_stays = self.decided[agent].is_some_and(|(next, _)| next == vacated);
415
416        if vertex == here || agent_stays {
417            self.intent[partner] = Some(vacated);
418            self.stay(partner, if agent_stays { heading } else { next_heading });
419        } else {
420            self.decided[partner] = Some((vertex, next_heading));
421            self.reserved[vertex] = Some(partner);
422            self.intent[partner] = None;
423        }
424    }
425
426    /// Decides that `agent` stays at its vertex, facing `heading`.
427    fn stay(&mut self, agent: AgentId, heading: Heading) {
428        let here = self.here[agent];
429        self.decided[agent] = Some((here, heading));
430        self.reserved[here] = Some(agent);
431    }
432
433    /// Claims `vertex` for `agent` while its decision is in progress.
434    fn claim(&mut self, agent: AgentId, vertex: Vertex) {
435        self.claim[agent] = Some(vertex);
436        self.reserved[vertex] = Some(agent);
437    }
438
439    /// Releases the claim of `agent` on `vertex`, if it still holds it.
440    fn unclaim(&mut self, agent: AgentId, vertex: Vertex) {
441        if self.reserved[vertex] == Some(agent) {
442            self.reserved[vertex] = None;
443        }
444    }
445
446    /// The vertices `agent` may request, best first: its own and its neighbours from which
447    /// the goal is reachable, by `TC`, unoccupied ones first among equals, random otherwise.
448    fn candidates(&mut self, agent: AgentId) -> Vec<Vertex> {
449        let here = self.here[agent];
450        let heading = self.heading[agent];
451        let mut candidates = vec![here];
452        self.instance
453            .graph()
454            .neighbors(here, |next| candidates.push(next));
455        self.random.shuffle(&mut candidates);
456
457        let mut ranked: Vec<(u32, bool, Vertex)> = candidates
458            .into_iter()
459            .filter_map(|vertex| {
460                let rank = self.costs.rank(agent, here, heading, vertex)?;
461                Some((rank, self.occupant[vertex].is_some(), vertex))
462            })
463            .collect();
464        ranked.sort_by_key(|&(rank, occupied, _)| (rank, occupied));
465
466        ranked.into_iter().map(|(_, _, vertex)| vertex).collect()
467    }
468
469    /// The k-push escape trigger: if `pusher` has pushed `agent` [`PUSH_LIMIT`] times,
470    /// shuffles its preferences and starts counting again.
471    fn escape(&mut self, candidates: &mut [Vertex], agent: AgentId, pusher: AgentId) {
472        let count = self.pushes.entry((agent, pusher)).or_default();
473        if *count >= PUSH_LIMIT && candidates.len() > 1 {
474            *count = 0;
475            self.random.shuffle(candidates);
476        }
477    }
478
479    /// Moves the vertex `agent` turned or waited towards last to the front, if still a
480    /// candidate.
481    fn request_first(&self, agent: AgentId, candidates: &mut Vec<Vertex>) {
482        let Some(intent) = self.intent[agent] else {
483            return;
484        };
485
486        if let Some(index) = candidates.iter().position(|&vertex| vertex == intent) {
487            let vertex = candidates.remove(index);
488            candidates.insert(0, vertex);
489        }
490    }
491}
492
493#[cfg(test)]
494mod tests {
495    //! PIBT*_T plans checked by a validator that knows only the graph's moves and turns.
496
497    use super::*;
498
499    use heuristic_search::Limits;
500    use proptest::prelude::*;
501
502    use crate::conflict::first_conflict;
503    use crate::graph::{Graph, Grid};
504    use crate::instance::Agent;
505
506    /// Checks that a solved `run` is a valid plan for `instance` from `headings`, ending at
507    /// the goals.
508    fn assert_valid<G: OrientedGraph>(
509        instance: &Instance<G>,
510        headings: &[Heading],
511        run: &TurnResult,
512    ) {
513        let solution = run.result.solution().expect("solved");
514        assert_steps(instance, headings, &solution.paths, &run.headings);
515        for (path, agent) in solution.paths.iter().zip(instance.agents()) {
516            assert_eq!(path.last(), Some(&agent.goal));
517        }
518    }
519
520    /// Checks the steps taken so far, `paths` and `turns` per agent, from the starts of
521    /// `instance` facing `headings`: every step of every agent waits, turns once, or moves
522    /// forward without turning; all lists have the same length; no two agents conflict.
523    fn assert_steps<G: OrientedGraph>(
524        instance: &Instance<G>,
525        headings: &[Heading],
526        paths: &[Path],
527        turns: &[Vec<Heading>],
528    ) {
529        let graph = instance.graph();
530        let steps = paths[0].len();
531
532        assert_eq!(first_conflict(paths), None);
533        for (agent, ((path, turns), start)) in
534            paths.iter().zip(turns).zip(instance.agents()).enumerate()
535        {
536            assert_eq!(
537                (path.len(), turns.len()),
538                (steps, steps),
539                "agent {agent}: lengths"
540            );
541            assert_eq!(path.first(), Some(&start.start));
542            assert_eq!(turns[0], headings[agent]);
543            for t in 1..steps {
544                let (from, to, before, after) = (path[t - 1], path[t], turns[t - 1], turns[t]);
545                if from == to {
546                    let mut one_turn = false;
547                    graph.turns(before, |next| one_turn |= next == after);
548                    assert!(
549                        after == before || one_turn,
550                        "agent {agent} at {t}: not a single turn"
551                    );
552                } else {
553                    assert_eq!(after, before, "agent {agent} at {t}: turned while moving");
554                    assert_eq!(
555                        graph.forward(from, before),
556                        Some(to),
557                        "agent {agent} at {t}: not forward"
558                    );
559                }
560            }
561        }
562    }
563
564    /// The four cells of a free 2x2 grid in clockwise order, each agent's goal the next one.
565    fn carousel() -> Instance<Grid> {
566        let agents = [(0, 1), (1, 3), (3, 2), (2, 0)]
567            .map(|(start, goal)| Agent { start, goal })
568            .to_vec();
569
570        Instance::new(Grid::new(2, 2), agents).expect("valid")
571    }
572
573    /// Facing their goals, the four agents of a full carousel move at once: a cycle.
574    #[test]
575    fn aligned_cycle_moves_at_once() {
576        let instance = carousel();
577        let headings = [Grid::EAST, Grid::SOUTH, Grid::WEST, Grid::NORTH];
578
579        let run = pibt_turns(&instance, &headings, 0, Limits::expansions(10));
580
581        assert_valid(&instance, &headings, &run);
582        assert_eq!(run.result.stats.expanded, 1);
583    }
584
585    /// All facing east, the carousel agents first turn towards their goals, then move.
586    #[test]
587    fn misaligned_cycle_turns_first() {
588        let instance = carousel();
589        let headings = [Grid::EAST; 4];
590
591        let run = pibt_turns(&instance, &headings, 0, Limits::expansions(50));
592
593        assert_valid(&instance, &headings, &run);
594        assert!(run.result.stats.expanded > 1);
595    }
596
597    /// An agent facing away from its goal in a corridor must turn twice before moving.
598    #[test]
599    fn turns_before_moving() {
600        let instance =
601            Instance::new(Grid::new(3, 1), vec![Agent { start: 0, goal: 2 }]).expect("valid");
602
603        let run = pibt_turns(&instance, &[Grid::WEST], 0, Limits::expansions(50));
604
605        assert_valid(&instance, &[Grid::WEST], &run);
606        assert_eq!(
607            run.headings[0],
608            [Grid::WEST, Grid::SOUTH, Grid::EAST, Grid::EAST, Grid::EAST]
609        );
610    }
611
612    /// An unreachable goal is proven at once.
613    #[test]
614    fn proves_an_unreachable_goal() {
615        let instance =
616            Instance::new(Grid::parse(&[".@."]), vec![Agent { start: 0, goal: 2 }]).expect("valid");
617
618        let run = pibt_turns(&instance, &[Grid::EAST], 0, Limits::NONE);
619
620        assert_eq!(run.result.outcome, Outcome::Unsolvable);
621        assert_eq!(run.headings, Vec::<Vec<Heading>>::new());
622    }
623
624    /// A missing heading is a caller error.
625    #[test]
626    #[should_panic(expected = "one heading per agent")]
627    fn needs_a_heading_per_agent() {
628        let _ = pibt_turns(&carousel(), &[Grid::EAST], 0, Limits::NONE);
629    }
630
631    /// A one-way ring with a single heading: an oriented graph that is not a grid.
632    struct Ring(usize);
633
634    impl Graph for Ring {
635        fn vertex_count(&self) -> usize {
636            self.0
637        }
638
639        fn neighbors(&self, vertex: Vertex, mut emit: impl FnMut(Vertex)) {
640            emit((vertex + 1) % self.0);
641        }
642    }
643
644    impl OrientedGraph for Ring {
645        fn heading_count(&self) -> usize {
646            1
647        }
648
649        fn forward(&self, vertex: Vertex, _: Heading) -> Option<Vertex> {
650            Some((vertex + 1) % self.0)
651        }
652
653        fn turns(&self, _: Heading, _: impl FnMut(Heading)) {}
654    }
655
656    /// On a one-way ring, agents follow each other round to their goals.
657    #[test]
658    fn works_on_other_oriented_graphs() {
659        let agents = vec![Agent { start: 0, goal: 2 }, Agent { start: 1, goal: 3 }];
660        let instance = Instance::new(Ring(5), agents).expect("valid");
661
662        let run = pibt_turns(&instance, &[0, 0], 0, Limits::expansions(50));
663
664        assert_valid(&instance, &[0, 0], &run);
665    }
666
667    /// A directed graph whose heading `h` faces vertex `h`, one turn from every other.
668    struct Directed(Vec<Vec<Vertex>>);
669
670    impl Graph for Directed {
671        fn vertex_count(&self) -> usize {
672            self.0.len()
673        }
674
675        fn neighbors(&self, vertex: Vertex, emit: impl FnMut(Vertex)) {
676            self.0[vertex].iter().copied().for_each(emit);
677        }
678    }
679
680    impl OrientedGraph for Directed {
681        fn heading_count(&self) -> usize {
682            self.0.len()
683        }
684
685        fn forward(&self, vertex: Vertex, heading: Heading) -> Option<Vertex> {
686            self.0[vertex].contains(&heading).then_some(heading)
687        }
688
689        fn turns(&self, heading: Heading, mut emit: impl FnMut(Heading)) {
690            (0..self.0.len())
691                .filter(|&h| h != heading)
692                .for_each(&mut emit);
693        }
694    }
695
696    /// No swap with a neighbour that has no edge back: agent 1 at 0 must not pull agent 0
697    /// at 2 into 0, as there is no edge `2 -> 0` (that pull used to panic). Agent 0, the
698    /// farther from its goal, goes first, through 1 into the dead end 4, before agent 1
699    /// parks on 1 and would block it for good.
700    #[test]
701    fn swaps_only_along_edges_back() {
702        let graph = Directed(vec![vec![1, 2, 3], vec![4], vec![1], vec![0], vec![]]);
703        let agents = vec![Agent { start: 2, goal: 4 }, Agent { start: 0, goal: 1 }];
704        let instance = Instance::new(graph, agents).expect("valid");
705
706        let run = pibt_turns(&instance, &[1, 1], 0, Limits::expansions(20));
707
708        assert_valid(&instance, &[1, 1], &run);
709    }
710
711    /// A grid of 3-4 by 3-4 cells with walls, 2-5 agents on distinct free starts and goals,
712    /// random headings and a seed.
713    fn case() -> impl Strategy<Value = (Instance<Grid>, Vec<Heading>, u64)> {
714        (
715            3_usize..=4,
716            3_usize..=4,
717            prop::collection::vec(prop::bool::weighted(0.15), 16),
718            2_usize..=5,
719            any::<u64>(),
720        )
721            .prop_flat_map(|(width, height, blocked, agents, seed)| {
722                let free: Vec<Vertex> = (0..width * height).filter(|&v| !blocked[v]).collect();
723                let headings = prop::collection::vec(0_usize..4, agents);
724                (
725                    Just((width, height, blocked, agents, seed)),
726                    Just(free.clone()).prop_shuffle(),
727                    Just(free).prop_shuffle(),
728                    headings,
729                )
730            })
731            .prop_filter_map(
732                "enough free cells",
733                |((width, height, blocked, agents, seed), starts, goals, headings)| {
734                    if starts.len() < agents {
735                        return None;
736                    }
737
738                    let mut grid = Grid::new(width, height);
739                    for vertex in (0..width * height).filter(|&v| blocked[v]) {
740                        let (x, y) = grid.cell(vertex);
741                        grid.block(x, y);
742                    }
743
744                    let agents = (0..agents)
745                        .map(|i| Agent {
746                            start: starts[i],
747                            goal: goals[i],
748                        })
749                        .collect();
750
751                    Some((Instance::new(grid, agents).ok()?, headings, seed))
752                },
753            )
754    }
755
756    proptest! {
757        #![proptest_config(ProptestConfig::with_cases(512))]
758
759        /// Every step PIBT*_T takes is valid and conflict-free, solved or not; every plan
760        /// it returns ends at the goals; and the same seed gives the same run.
761        #[test]
762        fn plans_are_valid((instance, headings, seed) in case()) {
763            let costs = Costs::new(instance.graph(), instance.agents());
764            let start_distance: Option<Vec<u32>> = instance.agents().iter().zip(&headings).enumerate()
765                .map(|(i, (a, &h))| costs.remaining(i, a.start, h)).collect();
766            if let Some(start_distance) = start_distance {
767                let mut run = Run::new(&instance, costs, &headings, start_distance, seed);
768                for _ in 0..100 {
769                    run.step();
770                }
771
772                assert_steps(&instance, &headings, &run.paths, &run.heading_paths);
773            }
774
775            let run = pibt_turns(&instance, &headings, seed, Limits::expansions(300));
776            if run.result.solution().is_some() {
777                assert_valid(&instance, &headings, &run);
778            }
779
780            prop_assert_eq!(&run, &pibt_turns(&instance, &headings, seed, Limits::expansions(300)));
781        }
782    }
783}