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    /// The agents whose paths in `paths`, indexed by agent, must be replanned once this
201    /// constraint is added: its own agent for a negative constraint, every other agent
202    /// whose path breaks what a positive one implies for it.
203    pub(crate) fn affected<P: AsRef<[Vertex]>>(&self, paths: &[P]) -> Vec<AgentId> {
204        if !self.is_positive() {
205            return Vec::from([self.agent()]);
206        }
207
208        (0..paths.len())
209            .filter(|&agent| agent != self.agent())
210            .filter(|&agent| {
211                self.implied_for(agent)
212                    .iter()
213                    .any(|implied| implied.is_violated_by(paths[agent].as_ref()))
214            })
215            .collect()
216    }
217}
218
219/// The constraints of one agent, indexed for the checks of a space-time search.
220#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
221pub struct ConstraintSet {
222    /// Forbidden `(time, vertex)` pairs.
223    vertices: BTreeSet<(Time, Vertex)>,
224    /// Forbidden `(time, from, to)` moves.
225    edges: BTreeSet<(Time, Vertex, Vertex)>,
226    /// Required `(time, vertex)` pairs: at such a time, every other vertex is forbidden.
227    /// Two different vertices at one time make the set unsatisfiable.
228    required: BTreeSet<(Time, Vertex)>,
229    /// Vertices forbidden from a time on, forever: where another agent stays for good
230    /// ([`ConstraintSet::block_from`]). The earliest such time per vertex.
231    blocked_from: BTreeMap<Vertex, Time>,
232    /// The latest time step any constraint touches; an edge constraint at `t` touches
233    /// `t + 1`, a permanent block touches its first time. `0` while empty.
234    latest_step: Time,
235}
236
237impl ConstraintSet {
238    /// Creates an empty set.
239    #[must_use]
240    pub fn new() -> Self {
241        Self::default()
242    }
243
244    /// The set of what `constraints` mean for `agent`: those that name it, and the
245    /// negative constraints implied by the positive ones on other agents
246    /// ([`Constraint::implied_for`]).
247    ///
248    /// # Examples
249    ///
250    /// ```
251    /// use mapf_search::{Constraint, ConstraintSet};
252    ///
253    /// // Agent 0 must be at vertex 4 at time 2, so agent 1 must not.
254    /// let positive = Constraint::PositiveVertex { agent: 0, vertex: 4, time: 2 };
255    /// let first = ConstraintSet::for_agent(0, &[positive]);
256    /// let second = ConstraintSet::for_agent(1, &[positive]);
257    ///
258    /// assert!(!first.allows_vertex(3, 2));
259    /// assert!(first.allows_vertex(4, 2));
260    /// assert!(!second.allows_vertex(4, 2));
261    /// assert!(second.allows_vertex(3, 2));
262    /// ```
263    #[must_use]
264    pub fn for_agent(agent: AgentId, constraints: &[Constraint]) -> Self {
265        let mut set = Self::new();
266        for constraint in constraints {
267            if constraint.agent() == agent {
268                set.insert(constraint);
269            } else {
270                constraint
271                    .implied_for(agent)
272                    .iter()
273                    .for_each(|implied| set.insert(implied));
274            }
275        }
276
277        set
278    }
279
280    /// Adds `constraint`, ignoring which agent it names.
281    pub fn insert(&mut self, constraint: &Constraint) {
282        match *constraint {
283            Constraint::Vertex { vertex, time, .. } => {
284                self.vertices.insert((time, vertex));
285                self.latest_step = self.latest_step.max(time);
286            }
287            Constraint::Edge { from, to, time, .. } => {
288                self.edges.insert((time, from, to));
289                self.latest_step = self.latest_step.max(time.saturating_add(1));
290            }
291            Constraint::PositiveVertex { vertex, time, .. } => self.require(vertex, time),
292            Constraint::PositiveEdge { from, to, time, .. } => {
293                self.require(from, time);
294                self.require(to, time.saturating_add(1));
295            }
296        }
297    }
298
299    /// Requires `vertex` at `time`.
300    fn require(&mut self, vertex: Vertex, time: Time) {
301        self.required.insert((time, vertex));
302        self.latest_step = self.latest_step.max(time);
303    }
304
305    /// The required `(time, vertex)` pairs ([`Constraint::PositiveVertex`] and both ends of
306    /// a [`Constraint::PositiveEdge`]), sorted by time.
307    pub(crate) fn landmarks(&self) -> impl Iterator<Item = (Time, Vertex)> + '_ {
308        self.required.iter().copied()
309    }
310
311    /// Forbids `vertex` at `time` and at every later time, as for a vertex where another
312    /// agent stays for good after arriving at `time`.
313    ///
314    /// # Examples
315    ///
316    /// ```
317    /// use mapf_search::ConstraintSet;
318    ///
319    /// let mut constraints = ConstraintSet::new();
320    /// constraints.block_from(4, 2);
321    ///
322    /// assert!(constraints.allows_vertex(4, 1));
323    /// assert!(!constraints.allows_vertex(4, 9));
324    /// assert_eq!(constraints.blocked_until(4), Some(u32::MAX));
325    /// ```
326    pub fn block_from(&mut self, vertex: Vertex, time: Time) {
327        let from = self.blocked_from.entry(vertex).or_insert(time);
328        *from = (*from).min(time);
329        self.latest_step = self.latest_step.max(time);
330    }
331
332    /// Returns `true` if the agent may move (or wait, when `from == to`) from `from` at
333    /// `time` to `to` at `time + 1`.
334    #[must_use]
335    pub fn allows(&self, from: Vertex, to: Vertex, time: Time) -> bool {
336        let next = time.saturating_add(1);
337
338        self.allows_vertex(to, next) && !self.edges.contains(&(time, from, to))
339    }
340
341    /// Returns `true` if the agent may occupy `vertex` at `time`.
342    #[must_use]
343    pub fn allows_vertex(&self, vertex: Vertex, time: Time) -> bool {
344        let blocked = self
345            .blocked_from
346            .get(&vertex)
347            .is_some_and(|&from| from <= time);
348
349        let elsewhere = self
350            .required
351            .range((time, 0)..=(time, Vertex::MAX))
352            .any(|&(_, required)| required != vertex);
353
354        !blocked && !elsewhere && !self.vertices.contains(&(time, vertex))
355    }
356
357    /// The latest time step any constraint touches; `0` while empty.
358    ///
359    /// After this step the constraints no longer change: the agent is free except for the
360    /// vertices blocked forever ([`ConstraintSet::block_from`]).
361    #[must_use]
362    pub fn latest_step(&self) -> Time {
363        self.latest_step
364    }
365
366    /// The first time an agent may arrive at `goal` for good: one after the latest time
367    /// the goal is forbidden ([`ConstraintSet::blocked_until`]), `0` if never.
368    pub(crate) fn earliest_finish(&self, goal: Vertex) -> Time {
369        self.blocked_until(goal).map_or(0, |t| t.saturating_add(1))
370    }
371
372    /// The latest time a search under these constraints on a graph of `vertex_count`
373    /// vertices needs to reach: after [`ConstraintSet::latest_step`] nothing changes any
374    /// more, and from there every reachable goal is at most `vertex_count - 1` steps away.
375    pub(crate) fn horizon(&self, vertex_count: usize) -> Time {
376        let vertices = Time::try_from(vertex_count).unwrap_or(Time::MAX);
377
378        self.latest_step.saturating_add(vertices)
379    }
380
381    /// The latest time `vertex` is forbidden, if ever: by a negative constraint, or by a
382    /// positive one that requires another vertex then.
383    ///
384    /// For the goal vertex, an agent must not finish at or before this time: goal-stay
385    /// semantics would put it there. [`Time::MAX`] if the vertex is blocked forever
386    /// ([`ConstraintSet::block_from`]).
387    #[must_use]
388    pub fn blocked_until(&self, vertex: Vertex) -> Option<Time> {
389        if self.blocked_from.contains_key(&vertex) {
390            return Some(Time::MAX);
391        }
392
393        let forbidden = self
394            .vertices
395            .iter()
396            .rev()
397            .find(|&&(_, v)| v == vertex)
398            .map(|&(time, _)| time);
399        let elsewhere = self
400            .required
401            .iter()
402            .rev()
403            .find(|&&(_, v)| v != vertex)
404            .map(|&(time, _)| time);
405
406        forbidden.max(elsewhere)
407    }
408}
409
410#[cfg(test)]
411mod tests {
412    //! Unit tests for positive constraints.
413
414    use super::*;
415    use alloc::vec;
416
417    /// A positive edge requires both ends and implies three negatives for the others.
418    #[test]
419    fn positive_edges_require_both_ends() {
420        let positive = Constraint::PositiveEdge {
421            agent: 0,
422            from: 1,
423            to: 2,
424            time: 3,
425        };
426        let own = ConstraintSet::for_agent(0, &[positive]);
427
428        assert!(own.allows(1, 2, 3));
429        assert!(!own.allows(1, 1, 3), "must leave 1");
430        assert!(!own.allows_vertex(0, 3));
431        assert_eq!(own.latest_step(), 4);
432        assert_eq!(own.blocked_until(2), Some(3), "elsewhere at 3");
433        assert_eq!(own.blocked_until(9), Some(4));
434
435        let other = ConstraintSet::for_agent(1, &[positive]);
436        assert!(!other.allows_vertex(1, 3));
437        assert!(!other.allows_vertex(2, 4));
438        assert!(!other.allows(2, 1, 3));
439        assert!(other.allows(0, 0, 3));
440    }
441
442    /// Two different required vertices at one time forbid everything then.
443    #[test]
444    fn conflicting_requirements_forbid_everything() {
445        let at = |vertex| Constraint::PositiveVertex {
446            agent: 0,
447            vertex,
448            time: 2,
449        };
450        let set = ConstraintSet::for_agent(0, &[at(1), at(2)]);
451
452        assert!((0..4).all(|vertex| !set.allows_vertex(vertex, 2)));
453    }
454
455    /// Violation checks follow goal-stay, for negative and positive constraints alike.
456    #[test]
457    fn violations_follow_goal_stay() {
458        let path = vec![0, 1, 2];
459        let vertex = |vertex, time| Constraint::Vertex {
460            agent: 0,
461            vertex,
462            time,
463        };
464
465        assert!(vertex(2, 7).is_violated_by(&path));
466        assert!(!vertex(1, 7).is_violated_by(&path));
467        assert!(vertex(1, 7).positive().is_violated_by(&path));
468        assert!(!vertex(2, 7).positive().is_violated_by(&path));
469
470        let swap = Constraint::Edge {
471            agent: 0,
472            from: 1,
473            to: 2,
474            time: 1,
475        };
476        assert!(swap.is_violated_by(&path));
477        assert!(!swap.positive().is_violated_by(&path));
478    }
479
480    /// Disjoint splitting yields the negative and the positive constraint on one agent.
481    #[test]
482    fn disjoint_split_constrains_one_agent() {
483        let conflict = Conflict::Edge {
484            agents: (3, 5),
485            from: 1,
486            to: 2,
487            time: 4,
488        };
489        let [negative, positive] = Constraint::disjoint(conflict, 1);
490
491        assert_eq!(
492            negative,
493            Constraint::Edge {
494                agent: 5,
495                from: 2,
496                to: 1,
497                time: 4
498            }
499        );
500        assert_eq!(positive, negative.positive());
501        assert!(positive.is_positive() && !negative.is_positive());
502        assert_eq!(negative.implied_for(3), []);
503    }
504}