Skip to main content

mapf_search/
path.rs

1//! Single-agent paths over discrete time and the joint objectives over them
2//! ([`Objective`]): [`sum_of_costs`] and [`makespan`].
3//!
4//! A path lists the vertex an agent occupies at each time step, so `path[t]` is the
5//! position at time `t`. After its last entry the agent stays at that vertex forever
6//! (goal-stay semantics), see [`position_at`].
7
8use alloc::vec::Vec;
9
10use crate::graph::Vertex;
11
12/// A time step. Time starts at `0`.
13pub type Time = u32;
14
15/// The positions of one agent at `t = 0, 1, ...`. Never empty in a solution.
16pub type Path = Vec<Vertex>;
17
18/// What a multi-agent search minimizes.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum Objective {
21    /// The sum over agents of the final arrival time at the goal ([`sum_of_costs`]).
22    SumOfCosts,
23    /// The time the last agent arrives at its goal for good ([`makespan`]).
24    Makespan,
25}
26
27/// The vertex `path` occupies at `time`, counting the stay at the last vertex.
28///
29/// # Panics
30///
31/// Panics if `path` is empty.
32#[must_use]
33pub fn position_at(path: &[Vertex], time: Time) -> Vertex {
34    let index = usize::try_from(time).unwrap_or(usize::MAX);
35
36    path.get(index)
37        .or(path.last())
38        .copied()
39        .expect("a path has at least one position")
40}
41
42/// What a path holds under goal-stay semantics, for building obstacles from it.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub(crate) enum Reservation {
45    /// The path is at `vertex` at `time`, before its final position.
46    Visit {
47        /// The occupied vertex.
48        vertex: Vertex,
49        /// The time step.
50        time: Time,
51    },
52    /// The path moves `from -> to` between `time` and `time + 1`; `from != to`. Another
53    /// agent moving `to -> from` then swaps with it.
54    Move {
55        /// The vertex the path leaves.
56        from: Vertex,
57        /// The vertex the path enters.
58        to: Vertex,
59        /// The time step the move starts at.
60        time: Time,
61    },
62    /// The path ends at `vertex` at `time` and stays there for good.
63    Park {
64        /// The last vertex.
65        vertex: Vertex,
66        /// The time of the last position.
67        time: Time,
68    },
69}
70
71/// Every [`Reservation`] of `path`: its visits before the last position, its moves (not
72/// its waits), and its park at the last position.
73///
74/// # Panics
75///
76/// Panics if `path` is empty or has more than `u32::MAX` positions.
77pub(crate) fn reservations(path: &[Vertex]) -> impl Iterator<Item = Reservation> + '_ {
78    let time = |index: usize| Time::try_from(index).expect("path lengths fit in u32 time steps");
79    let last = path.len() - 1;
80
81    let visits = path[..last]
82        .iter()
83        .enumerate()
84        .map(move |(index, &vertex)| Reservation::Visit {
85            vertex,
86            time: time(index),
87        });
88    let moves = path
89        .windows(2)
90        .enumerate()
91        .filter(|(_, step)| step[0] != step[1])
92        .map(move |(index, step)| Reservation::Move {
93            from: step[0],
94            to: step[1],
95            time: time(index),
96        });
97    let park = Reservation::Park {
98        vertex: path[last],
99        time: time(last),
100    };
101
102    visits.chain(moves).chain(core::iter::once(park))
103}
104
105/// Drops the waits at the end of `path`, keeping its last vertex: after that, goal-stay
106/// semantics put the agent there anyway.
107pub(crate) fn trim_trailing_waits(path: &mut Path) {
108    while path.len() > 1 && path[path.len() - 2] == path[path.len() - 1] {
109        path.pop();
110    }
111}
112
113/// The cost of one path: the time of its final arrival at its last vertex.
114///
115/// Waits before the final arrival count, also waits at the goal before leaving it again.
116/// Trailing waits at the last vertex do not. An empty path costs `0`.
117///
118/// # Panics
119///
120/// Panics if a path has more than `u32::MAX` positions.
121#[must_use]
122pub fn path_cost(path: &[Vertex]) -> u32 {
123    let Some(&last) = path.last() else {
124        return 0;
125    };
126
127    let trailing = path.iter().rev().take_while(|&&v| v == last).count();
128    let arrival = path.len() - trailing;
129
130    u32::try_from(arrival).expect("path lengths fit in u32 time steps")
131}
132
133/// The sum of the [`path_cost`]s of all paths.
134///
135/// # Panics
136///
137/// Panics if a path has more than `u32::MAX` positions.
138#[must_use]
139pub fn sum_of_costs<P: AsRef<[Vertex]>>(paths: &[P]) -> u32 {
140    paths.iter().map(|path| path_cost(path.as_ref())).sum()
141}
142
143/// The largest [`path_cost`] of all paths: when the last agent arrives for good. `0` for
144/// no paths.
145///
146/// # Panics
147///
148/// Panics if a path has more than `u32::MAX` positions.
149#[must_use]
150pub fn makespan<P: AsRef<[Vertex]>>(paths: &[P]) -> u32 {
151    paths
152        .iter()
153        .map(|path| path_cost(path.as_ref()))
154        .max()
155        .unwrap_or(0)
156}
157
158#[cfg(test)]
159mod tests {
160    //! Unit tests for path costs.
161
162    use super::*;
163    use alloc::vec;
164
165    /// Trailing waits are free; waits before the final arrival are not.
166    #[test]
167    fn cost_counts_until_final_arrival() {
168        assert_eq!(path_cost(&[3]), 0);
169        assert_eq!(path_cost(&[0, 1, 2]), 2);
170        assert_eq!(path_cost(&[0, 1, 1, 2, 2, 2]), 3);
171        assert_eq!(path_cost(&[2, 1, 2]), 2);
172        assert_eq!(sum_of_costs(&[vec![0, 1], vec![5, 5, 4]]), 3);
173        assert_eq!(makespan(&[vec![0, 1], vec![5, 5, 4]]), 2);
174    }
175
176    /// A path reserves its visits, its moves without waits, and its park.
177    #[test]
178    fn reserves_visits_moves_and_park() {
179        let reserved: Vec<Reservation> = reservations(&[3, 3, 4]).collect();
180
181        assert_eq!(
182            reserved,
183            [
184                Reservation::Visit { vertex: 3, time: 0 },
185                Reservation::Visit { vertex: 3, time: 1 },
186                Reservation::Move {
187                    from: 3,
188                    to: 4,
189                    time: 1
190                },
191                Reservation::Park { vertex: 4, time: 2 },
192            ]
193        );
194    }
195
196    /// Only the waits at the end go; a single position stays.
197    #[test]
198    fn trims_only_trailing_waits() {
199        let mut path = vec![1, 1, 2, 2, 2];
200        trim_trailing_waits(&mut path);
201        assert_eq!(path, [1, 1, 2]);
202
203        let mut single = vec![4, 4];
204        trim_trailing_waits(&mut single);
205        assert_eq!(single, [4]);
206    }
207
208    /// The last position holds forever.
209    #[test]
210    fn position_stays_at_goal() {
211        assert_eq!(position_at(&[0, 1, 2], 1), 1);
212        assert_eq!(position_at(&[0, 1, 2], 10), 2);
213    }
214}