1use 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#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct UaSolution {
28 pub assigned: Solution,
31 pub unassigned: Vec<Path>,
35 pub unassigned_moves: u32,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum UaOutcome {
43 Solved(UaSolution),
45 Unsolvable,
48 LimitReached,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct UaResult {
55 pub outcome: UaOutcome,
57 pub stats: Stats,
60}
61
62impl UaResult {
63 #[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
73pub fn focbs<G: Graph>(instance: &UaInstance<G>, budget: impl Budget<Stats>) -> UaResult {
97 focbs_with(instance, CbsConfig::improved(Objective::SumOfCosts), budget)
98}
99
100pub 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
165pub(super) struct Unassigned {
167 starts: Vec<Vertex>,
169 routing: Option<Routing>,
171}
172
173impl<G: Graph> Search<'_, G> {
174 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 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 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
219fn 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 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 const BUDGET: u64 = 5_000;
271
272 const UNSOLVABLE_BUDGET: u64 = 60;
276
277 type Joint = (Vec<(Vertex, bool)>, Vec<Vertex>);
280
281 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 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 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 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 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 #[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 #[test]
509 fn branches_on_blockers() {
510 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 #[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 #[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 #[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 #[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}