Skip to main content

mapf_search/cbs/
ua.rs

1//! FOCBS (Jin et al. 2026): flow-oracle conflict-based search for MAPF with unassigned
2//! agents, over a [`UaInstance`] whose agents either have a goal (*assigned*) or only a
3//! start (*unassigned*).
4//!
5//! CBS searches the paths of the assigned agents alone, ordered by their sum of costs. At
6//! every conflict-free node a flow oracle ([`route`]) routes the unassigned agents around
7//! those paths at the fewest moves, up to the latest arrival. If no routing exists, the
8//! oracle's minimum cut names the reservations of assigned agents that block it, and the
9//! node gets one child per blocker that forbids it to its agent (*flow-conflict
10//! branching*): every plan below the node must release one of them.
11
12use alloc::vec::Vec;
13
14use heuristic_search::{Budget, Stats};
15
16use super::{CbsConfig, Node, Search};
17use crate::constraint::Constraint;
18use crate::flow::{Blocker, Routing, route};
19use crate::graph::{Graph, Vertex};
20use crate::instance::UaInstance;
21use crate::low_level::distance_tables;
22use crate::path::{Objective, Path};
23use crate::solution::{Outcome, Solution};
24
25/// A plan for a [`UaInstance`].
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct UaSolution {
28    /// The paths of the assigned agents, indexed like [`UaInstance::assigned`]; its sum of
29    /// costs is the objective FOCBS minimizes.
30    pub assigned: Solution,
31    /// The paths of the unassigned agents, indexed like [`UaInstance::unassigned`], each up
32    /// to the latest arrival of an assigned agent, trimmed of trailing waits; the agent
33    /// stays at its last vertex.
34    pub unassigned: Vec<Path>,
35    /// The number of moves of the unassigned agents, the least possible for these assigned
36    /// paths.
37    pub unassigned_moves: u32,
38}
39
40/// How a [`focbs`] run ended.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum UaOutcome {
43    /// A conflict-free plan for every agent.
44    Solved(UaSolution),
45    /// Proven unsolvable: an assigned agent cannot reach its goal even alone, or the search
46    /// ran out of options.
47    Unsolvable,
48    /// The [`Budget`] stopped the search; the instance may be unsolvable.
49    LimitReached,
50}
51
52/// The result of a [`focbs`] run.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct UaResult {
55    /// How the run ended.
56    pub outcome: UaOutcome,
57    /// High-level counters, as for [`cbs_with`](crate::cbs_with); blocker splits count as
58    /// expansions.
59    pub stats: Stats,
60}
61
62impl UaResult {
63    /// The plan, if one was found.
64    #[must_use]
65    pub fn solution(&self) -> Option<&UaSolution> {
66        match &self.outcome {
67            UaOutcome::Solved(solution) => Some(solution),
68            UaOutcome::Unsolvable | UaOutcome::LimitReached => None,
69        }
70    }
71}
72
73/// Plans the assigned agents of `instance` with the least sum of costs that still lets the
74/// unassigned agents get out of the way, and routes those at the fewest moves, with FOCBS
75/// and every improvement of [`CbsConfig::improved`].
76///
77/// See [`focbs_with`] for the guarantee and the budget.
78///
79/// # Examples
80///
81/// ```
82/// use mapf_search::{Agent, Grid, Limits, UaInstance, focbs};
83///
84/// // An idle robot waits in a corridor with a side pocket; the other one must pass.
85/// let grid = Grid::parse(&["...", "@.@"]);
86/// let crossing = Agent { start: grid.vertex(0, 0), goal: grid.vertex(2, 0) };
87/// let instance = UaInstance::new(grid.clone(), vec![crossing], vec![grid.vertex(1, 0)])?;
88///
89/// let result = focbs(&instance, Limits::expansions(1_000));
90/// let solution = result.solution().expect("the idle robot steps into the pocket");
91/// assert_eq!(solution.assigned.sum_of_costs, 2);
92/// assert_eq!(solution.unassigned, [vec![grid.vertex(1, 0), grid.vertex(1, 1)]]);
93/// assert_eq!(solution.unassigned_moves, 1);
94/// # Ok::<(), mapf_search::InstanceError>(())
95/// ```
96pub fn focbs<G: Graph>(instance: &UaInstance<G>, budget: impl Budget<Stats>) -> UaResult {
97    focbs_with(instance, CbsConfig::improved(Objective::SumOfCosts), budget)
98}
99
100/// Plans the assigned agents of `instance` with the least sum of costs that still lets the
101/// unassigned agents get out of the way, and routes those at the fewest moves, with FOCBS
102/// and the improvements `config` selects.
103///
104/// The guarantee is the paper's *sequential* optimality: the assigned paths have the least
105/// sum of costs among all that leave a conflict-free routing for the unassigned agents, and
106/// the routing has the fewest moves *for those paths* (not necessarily over all plans with
107/// that sum of costs). The unassigned agents only need to be conflict-free until the
108/// latest arrival of an assigned agent; after it nobody moves.
109///
110/// `budget` is asked before every constraint-tree expansion and before every oracle call.
111/// On an unsolvable instance the search may run until its budget, as CBS does.
112///
113/// # Panics
114///
115/// Panics if `config.objective` is [`Objective::Makespan`]: FOCBS minimizes the sum of
116/// costs.
117pub fn focbs_with<G: Graph>(
118    instance: &UaInstance<G>,
119    config: CbsConfig,
120    mut budget: impl Budget<Stats>,
121) -> UaResult {
122    assert_eq!(
123        config.objective,
124        Objective::SumOfCosts,
125        "FOCBS minimizes the sum of costs"
126    );
127
128    let assigned = instance.assigned();
129    let mut search = Search::forest(
130        instance.graph(),
131        assigned.iter().map(|agent| agent.start).collect(),
132        assigned.iter().map(|agent| agent.goal).collect(),
133        distance_tables(instance.graph(), assigned),
134        None,
135        config,
136    );
137    search.trees.push((0..assigned.len()).collect());
138    search.unassigned = Some(Unassigned {
139        starts: instance.unassigned().to_vec(),
140        routing: None,
141    });
142
143    let outcome = match search.run(&mut budget) {
144        Outcome::Solved(solution) => {
145            let routing = search
146                .unassigned
147                .and_then(|unassigned| unassigned.routing)
148                .expect("a solved node was routed");
149            UaOutcome::Solved(UaSolution {
150                assigned: solution,
151                unassigned: routing.paths,
152                unassigned_moves: routing.moves,
153            })
154        }
155        Outcome::Unsolvable => UaOutcome::Unsolvable,
156        Outcome::LimitReached | Outcome::Exhausted => UaOutcome::LimitReached,
157    };
158
159    UaResult {
160        outcome,
161        stats: search.stats,
162    }
163}
164
165/// The unassigned agents of a FOCBS run.
166pub(super) struct Unassigned {
167    /// Their starts.
168    starts: Vec<Vertex>,
169    /// The routing of the node that solved the instance, once found.
170    routing: Option<Routing>,
171}
172
173impl<G: Graph> Search<'_, G> {
174    /// Returns `true` if popping `node` ends the search without further work: it is
175    /// conflict-free and there are no unassigned agents to route (the oracle still runs for
176    /// an empty set, trivially, to record its routing).
177    pub(super) fn is_final(&self, node: &Node) -> bool {
178        let nobody = self
179            .unassigned
180            .as_ref()
181            .is_none_or(|unassigned| unassigned.starts.is_empty());
182
183        node.conflict.is_none() && nobody
184    }
185
186    /// Routes the unassigned agents around the paths of the conflict-free `node`: `None`
187    /// if that works (or there are none), else the blockers of the oracle's cut.
188    pub(super) fn route_unassigned(&mut self, node: &Node) -> Option<Vec<Blocker>> {
189        let unassigned = self.unassigned.as_mut()?;
190        match route(self.graph, &node.paths, &unassigned.starts) {
191            Ok(routing) => {
192                unassigned.routing = Some(routing);
193                None
194            }
195            Err(blockers) => Some(blockers),
196        }
197    }
198
199    /// Flow-conflict branching: one child of `parent` per blocker, each forbidding the
200    /// blocker to its agent; without any child, the node is dropped.
201    ///
202    /// Every blocker is a reservation of a path of `parent`, which satisfies its
203    /// constraints, so none is forbidden already.
204    pub(super) fn expand_blockers(&mut self, parent: &Node, blockers: &[Blocker]) {
205        self.stats.expanded += 1;
206
207        for constraint in blockers.iter().map(|&blocker| releasing(blocker)) {
208            debug_assert!(
209                !parent.constraints.contains(&constraint),
210                "a blocker is a reservation the node allows"
211            );
212            if let Some(child) = self.child(parent, constraint) {
213                self.push(child.node);
214            }
215        }
216    }
217}
218
219/// The constraint that releases `blocker`.
220///
221/// Never a vertex at step 0: the only arcs into the first layer leave the source towards
222/// the unassigned starts, which no path holds, so no cut separates a fixed start.
223fn releasing(blocker: Blocker) -> Constraint {
224    match blocker {
225        Blocker::Vertex {
226            agent,
227            vertex,
228            time,
229        } => {
230            debug_assert!(time > 0, "the starts are never cut");
231            Constraint::Vertex {
232                agent,
233                vertex,
234                time,
235            }
236        }
237        Blocker::Move {
238            agent,
239            from,
240            to,
241            time,
242        } => Constraint::Edge {
243            agent,
244            from,
245            to,
246            time,
247        },
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    //! FOCBS against a brute-force joint search over all agents.
254
255    use super::*;
256    use alloc::collections::{BTreeMap, BinaryHeap};
257    use alloc::vec;
258    use core::cmp::Reverse;
259
260    use heuristic_search::Limits;
261    use proptest::prelude::*;
262
263    use crate::cbs::cbs_with;
264    use crate::conflict::first_conflict;
265    use crate::graph::Grid;
266    use crate::instance::{Agent, Instance};
267    use crate::path::{Time, path_cost, position_at};
268
269    /// The expansion budget of the runs in these tests.
270    const BUDGET: u64 = 5_000;
271
272    /// The expansion budget on instances the joint search proves unsolvable. On those FOCBS
273    /// can only run into its budget, and each expansion routes a flow, so the full budget
274    /// made the property test take minutes. As in the integration tests' property tests.
275    const UNSOLVABLE_BUDGET: u64 = 60;
276
277    /// A joint state: each assigned agent's vertex and finished flag, then each unassigned
278    /// agent's vertex.
279    type Joint = (Vec<(Vertex, bool)>, Vec<Vertex>);
280
281    /// The least sum of costs of the assigned agents over all conflict-free joint plans, by
282    /// Dijkstra over joint states with goal-stay pricing (an unfinished assigned agent pays
283    /// 1 per step, finishing at its goal is free, unassigned agents move for free); `None`
284    /// if no plan exists.
285    fn optimal_sst(instance: &UaInstance<Grid>) -> Option<u32> {
286        let start: Joint = (
287            instance
288                .assigned()
289                .iter()
290                .map(|a| (a.start, false))
291                .collect(),
292            instance.unassigned().to_vec(),
293        );
294        let mut best = BTreeMap::from([(start.clone(), 0_u32)]);
295        let mut open = BinaryHeap::from([Reverse((0_u32, start))]);
296        while let Some(Reverse((cost, state))) = open.pop() {
297            if best.get(&state).is_some_and(|&known| known < cost) {
298                continue;
299            }
300
301            if state.0.iter().all(|&(_, finished)| finished) {
302                return Some(cost);
303            }
304
305            for (next, step) in successors(instance, &state) {
306                let total = cost + step;
307                if best.get(&next).is_none_or(|&known| total < known) {
308                    best.insert(next.clone(), total);
309                    open.push(Reverse((total, next)));
310                }
311            }
312        }
313
314        None
315    }
316
317    /// The conflict-free joint steps from `state`, each with its cost.
318    fn successors(instance: &UaInstance<Grid>, state: &Joint) -> Vec<(Joint, u32)> {
319        let grid = instance.graph();
320        let options = |vertex: Vertex| {
321            let mut next = vec![vertex];
322            grid.neighbors(vertex, |n| next.push(n));
323            next
324        };
325
326        let mut choices: Vec<Vec<(Vertex, bool, u32)>> = Vec::new();
327        for (&(vertex, finished), agent) in state.0.iter().zip(instance.assigned()) {
328            choices.push(if finished {
329                vec![(vertex, true, 0)]
330            } else {
331                let mut list: Vec<_> = options(vertex).into_iter().map(|n| (n, false, 1)).collect();
332                if vertex == agent.goal {
333                    list.push((vertex, true, 0));
334                }
335                list
336            });
337        }
338
339        for &vertex in &state.1 {
340            choices.push(options(vertex).into_iter().map(|n| (n, false, 0)).collect());
341        }
342
343        let from: Vec<Vertex> = state
344            .0
345            .iter()
346            .map(|&(v, _)| v)
347            .chain(state.1.iter().copied())
348            .collect();
349        let mut found = Vec::new();
350        let mut pick = vec![0; choices.len()];
351        loop {
352            let to: Vec<Vertex> = pick
353                .iter()
354                .zip(&choices)
355                .map(|(&i, list)| list[i].0)
356                .collect();
357            if is_free(&from, &to) {
358                let assigned = instance.assigned().len();
359                let next = (
360                    (0..assigned)
361                        .map(|a| (to[a], choices[a][pick[a]].1))
362                        .collect(),
363                    to[assigned..].to_vec(),
364                );
365                let cost = (0..assigned).map(|a| choices[a][pick[a]].2).sum();
366                found.push((next, cost));
367            }
368
369            let Some(position) = (0..pick.len()).find(|&k| pick[k] + 1 < choices[k].len()) else {
370                break;
371            };
372            pick[position] += 1;
373            pick[..position].fill(0);
374        }
375
376        found
377    }
378
379    /// Returns `true` if moving every agent `from -> to` has no vertex conflict and no swap.
380    fn is_free(from: &[Vertex], to: &[Vertex]) -> bool {
381        (0..to.len()).all(|a| {
382            (a + 1..to.len()).all(|b| {
383                to[a] != to[b] && !(from[a] == to[b] && from[b] == to[a] && from[a] != to[a])
384            })
385        })
386    }
387
388    /// The fewest moves the unassigned agents need around the fixed `assigned` paths until
389    /// the latest arrival, by Dijkstra over their joint positions and the step.
390    fn fewest_moves(instance: &UaInstance<Grid>, assigned: &[Path]) -> Option<u32> {
391        let horizon: Time = assigned.iter().map(|p| path_cost(p)).max().unwrap_or(0);
392        let idle = |here: &[Vertex]| {
393            UaInstance::new(instance.graph().clone(), Vec::new(), here.to_vec()).expect("valid")
394        };
395        let start = (0, instance.unassigned().to_vec());
396        let mut best = BTreeMap::from([(start.clone(), 0_u32)]);
397        let mut open = BinaryHeap::from([Reverse((0_u32, start))]);
398        while let Some(Reverse((cost, (time, here)))) = open.pop() {
399            if time == horizon {
400                return Some(cost);
401            }
402
403            let fixed = |at: Time| assigned.iter().map(move |p| position_at(p, at));
404            let from: Vec<Vertex> = fixed(time).chain(here.iter().copied()).collect();
405            for ((_, next), _) in successors(&idle(&here), &(Vec::new(), here.clone())) {
406                let to: Vec<Vertex> = fixed(time + 1).chain(next.iter().copied()).collect();
407                if !is_free(&from, &to) {
408                    continue;
409                }
410
411                let moves = here.iter().zip(&next).filter(|(a, b)| a != b).count();
412                let total = cost + u32::try_from(moves).expect("few agents");
413                let key = (time + 1, next);
414                if best.get(&key).is_none_or(|&known| total < known) {
415                    best.insert(key.clone(), total);
416                    open.push(Reverse((total, key)));
417                }
418            }
419        }
420
421        None
422    }
423
424    /// Up to 3 agents on a grid of 2-3 by 2-3 cells with walls, 1-2 of them assigned.
425    fn instance() -> impl Strategy<Value = UaInstance<Grid>> {
426        (
427            2_usize..=3,
428            2_usize..=3,
429            prop::collection::vec(prop::bool::weighted(0.15), 9),
430            1_usize..=2,
431            0_usize..=2,
432        )
433            .prop_flat_map(|(width, height, blocked, assigned, unassigned)| {
434                let cells = width * height;
435                let free: Vec<Vertex> = (0..cells).filter(|&v| !blocked[v]).collect();
436                (
437                    Just((width, height, blocked)),
438                    Just(free.clone()).prop_shuffle(),
439                    Just(free).prop_shuffle(),
440                    Just((assigned, unassigned)),
441                )
442            })
443            .prop_filter_map(
444                "enough free cells",
445                |((width, height, blocked), starts, goals, (assigned, unassigned))| {
446                    if starts.len() < assigned + unassigned || assigned + unassigned > 3 {
447                        return None;
448                    }
449
450                    let mut grid = Grid::new(width, height);
451                    for vertex in (0..width * height).filter(|&v| blocked[v]) {
452                        let (x, y) = grid.cell(vertex);
453                        grid.block(x, y);
454                    }
455
456                    let agents = (0..assigned)
457                        .map(|i| Agent {
458                            start: starts[i],
459                            goal: goals[i],
460                        })
461                        .collect();
462                    let idle = starts[assigned..assigned + unassigned].to_vec();
463
464                    UaInstance::new(grid, agents, idle).ok()
465                },
466            )
467    }
468
469    proptest! {
470        #![proptest_config(ProptestConfig::with_cases(256))]
471
472        /// FOCBS finds the least assigned sum of costs over all joint plans, with plain and
473        /// improved CBS; its plan is conflict-free; and its unassigned routing has the
474        /// fewest moves for its assigned paths.
475        #[test]
476        fn matches_a_joint_search(instance in instance(), improved in any::<bool>()) {
477            let soc = Objective::SumOfCosts;
478            let config = if improved { CbsConfig::improved(soc) } else { CbsConfig::plain(soc) };
479            let expected = optimal_sst(&instance);
480            let budget = if expected.is_some() { BUDGET } else { UNSOLVABLE_BUDGET };
481            let result = focbs_with(&instance, config, Limits::expansions(budget));
482
483            match (&result.outcome, expected) {
484                (UaOutcome::Solved(solution), Some(cost)) => {
485                    prop_assert_eq!(solution.assigned.sum_of_costs, cost);
486                    let mut all = solution.assigned.paths.clone();
487                    all.extend(solution.unassigned.iter().cloned());
488                    prop_assert_eq!(first_conflict(&all), None);
489                    for (path, agent) in solution.assigned.paths.iter().zip(instance.assigned()) {
490                        prop_assert_eq!((path.first(), path.last()), (Some(&agent.start), Some(&agent.goal)));
491                    }
492
493                    for (path, &start) in solution.unassigned.iter().zip(instance.unassigned()) {
494                        prop_assert_eq!(path.first(), Some(&start));
495                    }
496
497                    prop_assert_eq!(Some(solution.unassigned_moves), fewest_moves(&instance, &solution.assigned.paths));
498                }
499                (UaOutcome::Unsolvable | UaOutcome::LimitReached, None) | (UaOutcome::LimitReached, Some(_)) => {}
500                (outcome, cost) => prop_assert!(false, "{outcome:?}, expected {cost:?}"),
501            }
502        }
503    }
504
505    /// The idle robot sits on the goal at the end of a corridor with a pocket. The
506    /// conflict-free path alone (sum of costs 2) leaves it no way out, so the oracle's
507    /// blockers force the assigned agent to wait once while the robot slips into the pocket.
508    #[test]
509    fn branches_on_blockers() {
510        // `0 1 2` over `@ 4 @`; the assigned agent runs 0 -> 2, the robot sits at 2.
511        let grid = Grid::parse(&["...", "@.@"]);
512        let instance =
513            UaInstance::new(grid, vec![Agent { start: 0, goal: 2 }], vec![2]).expect("valid");
514
515        for config in [
516            CbsConfig::plain(Objective::SumOfCosts),
517            CbsConfig::improved(Objective::SumOfCosts),
518        ] {
519            let result = focbs_with(&instance, config, Limits::expansions(BUDGET));
520            let solution = result.solution().expect("solvable");
521
522            assert_eq!(Some(solution.assigned.sum_of_costs), optimal_sst(&instance));
523            assert_eq!(solution.assigned.sum_of_costs, 3);
524            assert_eq!(solution.unassigned, [vec![2, 1, 4]]);
525            assert_eq!(solution.unassigned_moves, 2);
526        }
527    }
528
529    /// On a one-way ring the robot can only move along; it leaves as the assigned agent
530    /// arrives behind it.
531    #[test]
532    fn follows_directed_edges() {
533        let ring = crate::graph::AdjacencyList::directed(3, &[(0, 1), (1, 2), (2, 0)]);
534        let instance =
535            UaInstance::new(ring, vec![Agent { start: 0, goal: 1 }], vec![1]).expect("valid");
536
537        let result = focbs(&instance, Limits::expansions(BUDGET));
538        let solution = result.solution().expect("solvable");
539
540        assert_eq!(solution.assigned.paths, [vec![0, 1]]);
541        assert_eq!(solution.unassigned, [vec![1, 2]]);
542    }
543
544    /// Without unassigned agents, FOCBS is CBS, with the same statistics, also when the
545    /// budget runs out exactly as the solution is popped.
546    #[test]
547    fn without_unassigned_agents_is_cbs() {
548        let grid = Grid::parse(&["...", "@.@"]);
549        let agents = vec![Agent { start: 0, goal: 2 }, Agent { start: 2, goal: 0 }];
550        let ua = UaInstance::new(grid.clone(), agents.clone(), Vec::new()).expect("valid");
551        let plain = Instance::new(grid, agents).expect("valid");
552
553        for config in [
554            CbsConfig::plain(Objective::SumOfCosts),
555            CbsConfig::improved(Objective::SumOfCosts),
556        ] {
557            let needed = cbs_with(&plain, config, Limits::NONE).stats.expanded;
558            for budget in 0..=needed {
559                let focbs = focbs_with(&ua, config, Limits::expansions(budget));
560                let cbs = cbs_with(&plain, config, Limits::expansions(budget));
561
562                assert_eq!(
563                    focbs.solution().map(|s| &s.assigned),
564                    cbs.solution(),
565                    "budget {budget}"
566                );
567                assert_eq!(focbs.stats, cbs.stats);
568            }
569        }
570    }
571
572    /// No agents at all, and only unassigned ones, are solved without moves.
573    #[test]
574    fn trivial_instances() {
575        let empty = UaInstance::new(Grid::new(2, 2), Vec::new(), Vec::new()).expect("valid");
576        let idle = UaInstance::new(Grid::new(2, 2), Vec::new(), vec![0, 3]).expect("valid");
577
578        let none = focbs(&empty, Limits::NONE);
579        let parked = focbs(&idle, Limits::NONE);
580
581        assert_eq!(none.solution().map(|s| s.unassigned_moves), Some(0));
582        assert_eq!(
583            parked.solution().map(|s| s.unassigned.clone()),
584            Some(vec![vec![0], vec![3]])
585        );
586    }
587
588    /// `Objective::Makespan` is rejected.
589    #[test]
590    #[should_panic(expected = "FOCBS minimizes the sum of costs")]
591    fn rejects_makespan() {
592        let instance = UaInstance::new(Grid::new(2, 1), Vec::new(), Vec::new()).expect("valid");
593
594        let _ = focbs_with(
595            &instance,
596            CbsConfig::plain(Objective::Makespan),
597            Limits::NONE,
598        );
599    }
600}