Skip to main content

mapf_search/
constraint.rs

1//! Constraints on one agent ([`Constraint`]), negative (forbid a vertex or move) and
2//! positive (require one, for disjoint splitting), and the per-agent lookup structure the
3//! low-level search uses ([`ConstraintSet`]).
4//!
5//! A positive constraint on one agent implies negative ones on every other agent: if `a`
6//! must be at `v` at `t`, nobody else may be. [`ConstraintSet::for_agent`] adds those.
7
8use alloc::collections::{BTreeMap, BTreeSet};
9use alloc::vec::Vec;
10
11use crate::conflict::Conflict;
12use crate::graph::Vertex;
13use crate::instance::AgentId;
14use crate::path::{Time, position_at};
15
16/// Forbids or requires one agent one vertex or one move at one time.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
18pub enum Constraint {
19    /// `agent` must not occupy `vertex` at `time`.
20    Vertex {
21        /// The constrained agent.
22        agent: AgentId,
23        /// The forbidden vertex.
24        vertex: Vertex,
25        /// The time step at which it is forbidden.
26        time: Time,
27    },
28    /// `agent` must not move `from -> to` between `time` and `time + 1`.
29    Edge {
30        /// The constrained agent.
31        agent: AgentId,
32        /// The vertex the forbidden move leaves.
33        from: Vertex,
34        /// The vertex the forbidden move enters.
35        to: Vertex,
36        /// The time step at which the forbidden move starts.
37        time: Time,
38    },
39    /// `agent` must occupy `vertex` at `time`; no other agent may (disjoint splitting, Li
40    /// et al. 2019).
41    PositiveVertex {
42        /// The constrained agent.
43        agent: AgentId,
44        /// The required vertex.
45        vertex: Vertex,
46        /// The time step at which it is required.
47        time: Time,
48    },
49    /// `agent` must move `from -> to` between `time` and `time + 1`, with `from != to`; no
50    /// other agent may be at `from` at `time` or at `to` at `time + 1`, or move `to -> from`
51    /// then.
52    PositiveEdge {
53        /// The constrained agent.
54        agent: AgentId,
55        /// The vertex the required move leaves.
56        from: Vertex,
57        /// The vertex the required move enters.
58        to: Vertex,
59        /// The time step at which the required move starts.
60        time: Time,
61    },
62}
63
64impl Constraint {
65    /// The two constraints that resolve `conflict`, one per agent.
66    pub(crate) fn resolving(conflict: Conflict) -> [Self; 2] {
67        match conflict {
68            Conflict::Vertex {
69                agents: (a, b),
70                vertex,
71                time,
72            } => [a, b].map(|agent| Self::Vertex {
73                agent,
74                vertex,
75                time,
76            }),
77            Conflict::Edge {
78                agents: (a, b),
79                from,
80                to,
81                time,
82            } => [
83                Self::Edge {
84                    agent: a,
85                    from,
86                    to,
87                    time,
88                },
89                Self::Edge {
90                    agent: b,
91                    from: to,
92                    to: from,
93                    time,
94                },
95            ],
96        }
97    }
98
99    /// The two children of disjoint splitting (Li et al. 2019) for `conflict`, split on
100    /// the agent at `side` (`0` for the conflict's first agent, else its second): the
101    /// negative constraint on it, then the positive one.
102    pub(crate) fn disjoint(conflict: Conflict, side: usize) -> [Self; 2] {
103        let negative = Self::resolving(conflict)[usize::from(side != 0)];
104
105        [negative, negative.positive()]
106    }
107
108    /// The positive counterpart of a negative constraint; positive ones stay as they are.
109    fn positive(self) -> Self {
110        match self {
111            Self::Vertex {
112                agent,
113                vertex,
114                time,
115            } => Self::PositiveVertex {
116                agent,
117                vertex,
118                time,
119            },
120            Self::Edge {
121                agent,
122                from,
123                to,
124                time,
125            } => Self::PositiveEdge {
126                agent,
127                from,
128                to,
129                time,
130            },
131            positive => positive,
132        }
133    }
134
135    /// The constrained agent.
136    #[must_use]
137    pub fn agent(&self) -> AgentId {
138        match *self {
139            Self::Vertex { agent, .. }
140            | Self::Edge { agent, .. }
141            | Self::PositiveVertex { agent, .. }
142            | Self::PositiveEdge { agent, .. } => agent,
143        }
144    }
145
146    /// Returns `true` for [`Constraint::PositiveVertex`] and [`Constraint::PositiveEdge`].
147    #[must_use]
148    pub fn is_positive(&self) -> bool {
149        matches!(
150            self,
151            Self::PositiveVertex { .. } | Self::PositiveEdge { .. }
152        )
153    }
154
155    /// The negative constraints that this positive constraint implies for `other`, an
156    /// agent other than the constrained one; nothing for a negative constraint.
157    #[must_use]
158    pub fn implied_for(&self, other: AgentId) -> Vec<Self> {
159        match *self {
160            Self::PositiveVertex { vertex, time, .. } => Vec::from([Self::Vertex {
161                agent: other,
162                vertex,
163                time,
164            }]),
165            Self::PositiveEdge { from, to, time, .. } => Vec::from([
166                Self::Vertex {
167                    agent: other,
168                    vertex: from,
169                    time,
170                },
171                Self::Vertex {
172                    agent: other,
173                    vertex: to,
174                    time: time.saturating_add(1),
175                },
176                Self::Edge {
177                    agent: other,
178                    from: to,
179                    to: from,
180                    time,
181                },
182            ]),
183            Self::Vertex { .. } | Self::Edge { .. } => Vec::new(),
184        }
185    }
186
187    /// Returns `true` if `path` (with goal-stay) breaks this constraint, whichever agent it
188    /// names.
189    #[must_use]
190    pub fn is_violated_by(&self, path: &[Vertex]) -> bool {
191        let at = |time: Time| position_at(path, time);
192
193        match *self {
194            Self::Vertex { vertex, time, .. } => at(time) == vertex,
195            Self::Edge { from, to, time, .. } => at(time) == from && at(time + 1) == to,
196            Self::PositiveVertex { vertex, time, .. } => at(time) != vertex,
197            Self::PositiveEdge { from, to, time, .. } => at(time) != from || at(time + 1) != to,
198        }
199    }
200}
201
202/// The constraints of one agent, indexed for the checks of a space-time search.
203#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
204pub struct ConstraintSet {
205    /// Forbidden `(time, vertex)` pairs.
206    vertices: BTreeSet<(Time, Vertex)>,
207    /// Forbidden `(time, from, to)` moves.
208    edges: BTreeSet<(Time, Vertex, Vertex)>,
209    /// Required `(time, vertex)` pairs: at such a time, every other vertex is forbidden.
210    /// Two different vertices at one time make the set unsatisfiable.
211    required: BTreeSet<(Time, Vertex)>,
212    /// Vertices forbidden from a time on, forever: where another agent stays for good
213    /// ([`ConstraintSet::block_from`]). The earliest such time per vertex.
214    blocked_from: BTreeMap<Vertex, Time>,
215    /// The latest time step any constraint touches; an edge constraint at `t` touches
216    /// `t + 1`, a permanent block touches its first time. `0` while empty.
217    latest_step: Time,
218}
219
220impl ConstraintSet {
221    /// Creates an empty set.
222    #[must_use]
223    pub fn new() -> Self {
224        Self::default()
225    }
226
227    /// The set of what `constraints` mean for `agent`: those that name it, and the
228    /// negative constraints implied by the positive ones on other agents
229    /// ([`Constraint::implied_for`]).
230    ///
231    /// # Examples
232    ///
233    /// ```
234    /// use mapf_search::{Constraint, ConstraintSet};
235    ///
236    /// // Agent 0 must be at vertex 4 at time 2, so agent 1 must not.
237    /// let positive = Constraint::PositiveVertex { agent: 0, vertex: 4, time: 2 };
238    /// let first = ConstraintSet::for_agent(0, &[positive]);
239    /// let second = ConstraintSet::for_agent(1, &[positive]);
240    ///
241    /// assert!(!first.allows_vertex(3, 2));
242    /// assert!(first.allows_vertex(4, 2));
243    /// assert!(!second.allows_vertex(4, 2));
244    /// assert!(second.allows_vertex(3, 2));
245    /// ```
246    #[must_use]
247    pub fn for_agent(agent: AgentId, constraints: &[Constraint]) -> Self {
248        let mut set = Self::new();
249        for constraint in constraints {
250            if constraint.agent() == agent {
251                set.insert(constraint);
252            } else {
253                constraint
254                    .implied_for(agent)
255                    .iter()
256                    .for_each(|implied| set.insert(implied));
257            }
258        }
259
260        set
261    }
262
263    /// Adds `constraint`, ignoring which agent it names.
264    pub fn insert(&mut self, constraint: &Constraint) {
265        match *constraint {
266            Constraint::Vertex { vertex, time, .. } => {
267                self.vertices.insert((time, vertex));
268                self.latest_step = self.latest_step.max(time);
269            }
270            Constraint::Edge { from, to, time, .. } => {
271                self.edges.insert((time, from, to));
272                self.latest_step = self.latest_step.max(time.saturating_add(1));
273            }
274            Constraint::PositiveVertex { vertex, time, .. } => self.require(vertex, time),
275            Constraint::PositiveEdge { from, to, time, .. } => {
276                self.require(from, time);
277                self.require(to, time.saturating_add(1));
278            }
279        }
280    }
281
282    /// Requires `vertex` at `time`.
283    fn require(&mut self, vertex: Vertex, time: Time) {
284        self.required.insert((time, vertex));
285        self.latest_step = self.latest_step.max(time);
286    }
287
288    /// The required `(time, vertex)` pairs ([`Constraint::PositiveVertex`] and both ends of
289    /// a [`Constraint::PositiveEdge`]), sorted by time.
290    pub(crate) fn landmarks(&self) -> impl Iterator<Item = (Time, Vertex)> + '_ {
291        self.required.iter().copied()
292    }
293
294    /// Forbids `vertex` at `time` and at every later time, as for a vertex where another
295    /// agent stays for good after arriving at `time`.
296    ///
297    /// # Examples
298    ///
299    /// ```
300    /// use mapf_search::ConstraintSet;
301    ///
302    /// let mut constraints = ConstraintSet::new();
303    /// constraints.block_from(4, 2);
304    ///
305    /// assert!(constraints.allows_vertex(4, 1));
306    /// assert!(!constraints.allows_vertex(4, 9));
307    /// assert_eq!(constraints.blocked_until(4), Some(u32::MAX));
308    /// ```
309    pub fn block_from(&mut self, vertex: Vertex, time: Time) {
310        let from = self.blocked_from.entry(vertex).or_insert(time);
311        *from = (*from).min(time);
312        self.latest_step = self.latest_step.max(time);
313    }
314
315    /// Returns `true` if the agent may move (or wait, when `from == to`) from `from` at
316    /// `time` to `to` at `time + 1`.
317    #[must_use]
318    pub fn allows(&self, from: Vertex, to: Vertex, time: Time) -> bool {
319        let next = time.saturating_add(1);
320
321        self.allows_vertex(to, next) && !self.edges.contains(&(time, from, to))
322    }
323
324    /// Returns `true` if the agent may occupy `vertex` at `time`.
325    #[must_use]
326    pub fn allows_vertex(&self, vertex: Vertex, time: Time) -> bool {
327        let blocked = self
328            .blocked_from
329            .get(&vertex)
330            .is_some_and(|&from| from <= time);
331
332        let elsewhere = self
333            .required
334            .range((time, 0)..=(time, Vertex::MAX))
335            .any(|&(_, required)| required != vertex);
336
337        !blocked && !elsewhere && !self.vertices.contains(&(time, vertex))
338    }
339
340    /// The latest time step any constraint touches; `0` while empty.
341    ///
342    /// After this step the constraints no longer change: the agent is free except for the
343    /// vertices blocked forever ([`ConstraintSet::block_from`]).
344    #[must_use]
345    pub fn latest_step(&self) -> Time {
346        self.latest_step
347    }
348
349    /// The latest time `vertex` is forbidden, if ever: by a negative constraint, or by a
350    /// positive one that requires another vertex then.
351    ///
352    /// For the goal vertex, an agent must not finish at or before this time: goal-stay
353    /// semantics would put it there. [`Time::MAX`] if the vertex is blocked forever
354    /// ([`ConstraintSet::block_from`]).
355    #[must_use]
356    pub fn blocked_until(&self, vertex: Vertex) -> Option<Time> {
357        if self.blocked_from.contains_key(&vertex) {
358            return Some(Time::MAX);
359        }
360
361        let forbidden = self
362            .vertices
363            .iter()
364            .rev()
365            .find(|&&(_, v)| v == vertex)
366            .map(|&(time, _)| time);
367        let elsewhere = self
368            .required
369            .iter()
370            .rev()
371            .find(|&&(_, v)| v != vertex)
372            .map(|&(time, _)| time);
373
374        forbidden.max(elsewhere)
375    }
376}
377
378#[cfg(test)]
379mod tests {
380    //! Unit tests for positive constraints.
381
382    use super::*;
383    use alloc::vec;
384
385    /// A positive edge requires both ends and implies three negatives for the others.
386    #[test]
387    fn positive_edges_require_both_ends() {
388        let positive = Constraint::PositiveEdge {
389            agent: 0,
390            from: 1,
391            to: 2,
392            time: 3,
393        };
394        let own = ConstraintSet::for_agent(0, &[positive]);
395
396        assert!(own.allows(1, 2, 3));
397        assert!(!own.allows(1, 1, 3), "must leave 1");
398        assert!(!own.allows_vertex(0, 3));
399        assert_eq!(own.latest_step(), 4);
400        assert_eq!(own.blocked_until(2), Some(3), "elsewhere at 3");
401        assert_eq!(own.blocked_until(9), Some(4));
402
403        let other = ConstraintSet::for_agent(1, &[positive]);
404        assert!(!other.allows_vertex(1, 3));
405        assert!(!other.allows_vertex(2, 4));
406        assert!(!other.allows(2, 1, 3));
407        assert!(other.allows(0, 0, 3));
408    }
409
410    /// Two different required vertices at one time forbid everything then.
411    #[test]
412    fn conflicting_requirements_forbid_everything() {
413        let at = |vertex| Constraint::PositiveVertex {
414            agent: 0,
415            vertex,
416            time: 2,
417        };
418        let set = ConstraintSet::for_agent(0, &[at(1), at(2)]);
419
420        assert!((0..4).all(|vertex| !set.allows_vertex(vertex, 2)));
421    }
422
423    /// Violation checks follow goal-stay, for negative and positive constraints alike.
424    #[test]
425    fn violations_follow_goal_stay() {
426        let path = vec![0, 1, 2];
427        let vertex = |vertex, time| Constraint::Vertex {
428            agent: 0,
429            vertex,
430            time,
431        };
432
433        assert!(vertex(2, 7).is_violated_by(&path));
434        assert!(!vertex(1, 7).is_violated_by(&path));
435        assert!(vertex(1, 7).positive().is_violated_by(&path));
436        assert!(!vertex(2, 7).positive().is_violated_by(&path));
437
438        let swap = Constraint::Edge {
439            agent: 0,
440            from: 1,
441            to: 2,
442            time: 1,
443        };
444        assert!(swap.is_violated_by(&path));
445        assert!(!swap.positive().is_violated_by(&path));
446    }
447
448    /// Disjoint splitting yields the negative and the positive constraint on one agent.
449    #[test]
450    fn disjoint_split_constrains_one_agent() {
451        let conflict = Conflict::Edge {
452            agents: (3, 5),
453            from: 1,
454            to: 2,
455            time: 4,
456        };
457        let [negative, positive] = Constraint::disjoint(conflict, 1);
458
459        assert_eq!(
460            negative,
461            Constraint::Edge {
462                agent: 5,
463                from: 2,
464                to: 1,
465                time: 4
466            }
467        );
468        assert_eq!(positive, negative.positive());
469        assert!(positive.is_positive() && !negative.is_positive());
470        assert_eq!(negative.implied_for(3), []);
471    }
472}