Skip to main content

temporal_control/stn/
dispatchable.rs

1//! Dispatchable STNs by dominated-edge filtering (Muscettola, Morris and Tsamardinos, KR 1998).
2//!
3//! The KR 1998 paper was not available. The filtering rules and the minimality claim are taken
4//! from its summary by Morris (CPAIOR 2014, section 5 and the proof of Theorem 5): the minimum
5//! dispatchable network keeps the all-pairs edges that are not dominated, and one edge of each
6//! group of mutually dominating edges; a negative edge `A -> B` is lower-dominated if a
7//! shortest path `A ~> C ~> B` has a negative prefix `A -> C`, a non-negative one
8//! upper-dominated if it has a non-negative suffix `C -> B`. If that summary is complete, the
9//! result is the minimum dispatchable network, except that points at offset zero from their
10//! rigid-component leader carry copies of the leader's edges (see step 1). The tests check
11//! that it is dispatchable and equivalent, not that it is minimum.
12//!
13//! The minimal network (all-pairs shortest paths) is dispatchable but dense. Filtering keeps a
14//! subset of its edges that is still dispatchable:
15//!
16//! 1. **Rigid components.** Points `i, j` with `D[i][j] + D[j][i] = 0` have a fixed offset.
17//!    Each component gets a leader, its earliest member (lowest index on ties). Every other
18//!    member is tied to the leader by the two edges `leader -> m` and `m -> leader`, and all
19//!    other constraints are expressed between leaders only. A member strictly after its leader
20//!    waits for it through the negative edge `m -> leader` and learns its exact time from it.
21//!    A member at offset zero has no negative edge to its leader, so it could run first with an
22//!    unconstrained window; it therefore receives a copy of every leader edge (step 2), which
23//!    keeps its window equal to the leader's. This is the dispatcher-level equivalent of
24//!    collapsing simultaneous points into one node.
25//! 2. **Dominance among leaders.** For leaders `a, b, c` (pairwise distinct):
26//!    - a non-negative edge `a -> c` is *upper-dominated* by a non-negative edge `b -> c` if
27//!      `D[a][b] + D[b][c] = D[a][c]`;
28//!    - a negative edge `a -> c` is *lower-dominated* by a negative edge `a -> b` if
29//!      `D[a][b] + D[b][c] = D[a][c]`.
30//!
31//!    Dominated edges are dropped. Leaders are pairwise non-rigid, so no two edges dominate
32//!    each other and all dominated edges can be dropped at once.
33//!
34//! Cost: `O(n^3)` steps, `O(n)` extra memory plus the output. Copies for simultaneous members
35//! add `O(s^2)` edges per kept leader edge, `s` being the larger number of simultaneous points.
36
37use alloc::vec::Vec;
38
39use super::{MinimalNetwork, TimePoint, steps};
40use crate::budget::Meter;
41use crate::dispatch::{DispatchEdge, DispatchableNetwork, PointKind};
42use crate::{Budget, Error, Ticks};
43
44impl MinimalNetwork {
45    /// Derives a dispatchable network by dominated-edge filtering.
46    ///
47    /// The result is equivalent to this network (same all-pairs distances) and dispatchable by
48    /// a [`Dispatcher`](crate::Dispatcher).
49    ///
50    /// # Errors
51    ///
52    /// - [`Error::BudgetExhausted`] if the `O(n^3)` filtering does not fit the step budget.
53    /// - [`Error::OutOfMemory`] if the output cannot be allocated.
54    /// - [`Error::Overflow`] if a distance sum overflows.
55    pub fn dispatchable(&self, budget: &Budget) -> Result<DispatchableNetwork, Error> {
56        let mut meter = budget.meter();
57        let leaders = self.rigid_leaders(&mut meter)?;
58        let mut edges = Vec::new();
59
60        self.push_rigid_edges(&leaders, &mut edges)?;
61        self.push_undominated_edges(&leaders, &mut meter, &mut edges)?;
62
63        let mut points = Vec::new();
64        points
65            .try_reserve_exact(self.n)
66            .map_err(|_| Error::OutOfMemory)?;
67        points.resize(self.n, PointKind::Executable);
68
69        Ok(DispatchableNetwork::new(points, edges, Vec::new()))
70    }
71
72    /// Distance `i -> j` by index.
73    fn d(&self, i: usize, j: usize) -> Option<Ticks> {
74        self.dist[i * self.n + j]
75    }
76
77    /// Whether `i` and `j` have a fixed offset.
78    fn rigid(&self, i: usize, j: usize) -> bool {
79        matches!((self.d(i, j), self.d(j, i)), (Some(a), Some(b)) if a.0.checked_add(b.0) == Some(0))
80    }
81
82    /// Leader of each point's rigid component: its earliest member, lowest index on ties.
83    ///
84    /// # Errors
85    ///
86    /// [`Error::BudgetExhausted`] or [`Error::OutOfMemory`].
87    fn rigid_leaders(&self, meter: &mut Meter) -> Result<Vec<usize>, Error> {
88        let n = self.n;
89        let mut leaders = Vec::new();
90        leaders
91            .try_reserve_exact(n)
92            .map_err(|_| Error::OutOfMemory)?;
93
94        for i in 0..n {
95            meter.spend(steps(n)?)?;
96            let leader = (0..n)
97                .filter(|&j| self.rigid(i, j))
98                .min_by_key(|&j| (self.d(i, j).map(|o| o.0), j))
99                .unwrap_or(i);
100            leaders.push(leader);
101        }
102
103        Ok(leaders)
104    }
105
106    /// Ties every non-leader to its leader with the two rigid edges.
107    ///
108    /// # Errors
109    ///
110    /// [`Error::OutOfMemory`].
111    fn push_rigid_edges(
112        &self,
113        leaders: &[usize],
114        edges: &mut Vec<DispatchEdge>,
115    ) -> Result<(), Error> {
116        for (m, &l) in leaders.iter().enumerate() {
117            if m == l {
118                continue;
119            }
120
121            for (from, to) in [(l, m), (m, l)] {
122                if let Some(weight) = self.d(from, to) {
123                    push_edge(edges, from, to, weight)?;
124                }
125            }
126        }
127
128        Ok(())
129    }
130
131    /// Adds every finite edge between distinct leaders that no third leader dominates.
132    ///
133    /// # Errors
134    ///
135    /// [`Error::BudgetExhausted`], [`Error::Overflow`] or [`Error::OutOfMemory`].
136    fn push_undominated_edges(
137        &self,
138        leaders: &[usize],
139        meter: &mut Meter,
140        edges: &mut Vec<DispatchEdge>,
141    ) -> Result<(), Error> {
142        let mut heads = Vec::new();
143        heads
144            .try_reserve_exact(self.n)
145            .map_err(|_| Error::OutOfMemory)?;
146        heads.extend((0..self.n).filter(|&i| leaders[i] == i));
147
148        for &a in &heads {
149            meter.spend(steps(heads.len())?.saturating_mul(steps(heads.len())?))?;
150
151            for &c in &heads {
152                let Some(w) = self.d(a, c) else {
153                    continue;
154                };
155
156                if a != c && !self.dominated(&heads, a, c, w)? {
157                    self.push_with_simultaneous(leaders, a, c, w, edges)?;
158                }
159            }
160        }
161
162        Ok(())
163    }
164
165    /// Adds `a -> c` with weight `w` between every member at offset zero from leader `a` and
166    /// every member at offset zero from leader `c` (the leaders included).
167    ///
168    /// # Errors
169    ///
170    /// [`Error::OutOfMemory`].
171    fn push_with_simultaneous(
172        &self,
173        leaders: &[usize],
174        a: usize,
175        c: usize,
176        w: Ticks,
177        edges: &mut Vec<DispatchEdge>,
178    ) -> Result<(), Error> {
179        let simultaneous = |l: usize| {
180            (0..self.n).filter(move |&i| leaders[i] == l && self.d(l, i) == Some(Ticks::ZERO))
181        };
182
183        for x in simultaneous(a) {
184            for y in simultaneous(c) {
185                push_edge(edges, x, y, w)?;
186            }
187        }
188
189        Ok(())
190    }
191
192    /// Whether edge `a -> c` with weight `w` is dominated through some other leader.
193    ///
194    /// # Errors
195    ///
196    /// [`Error::Overflow`] if a distance sum overflows.
197    fn dominated(&self, heads: &[usize], a: usize, c: usize, w: Ticks) -> Result<bool, Error> {
198        for &b in heads {
199            if b == a || b == c {
200                continue;
201            }
202
203            let (Some(ab), Some(bc)) = (self.d(a, b), self.d(b, c)) else {
204                continue;
205            };
206
207            let through_b = ab.checked_add(bc).ok_or(Error::Overflow)? == w;
208            let dominating = if w >= Ticks::ZERO { bc } else { ab };
209            let same_sign = (dominating >= Ticks::ZERO) == (w >= Ticks::ZERO);
210
211            if through_b && same_sign {
212                return Ok(true);
213            }
214        }
215
216        Ok(false)
217    }
218}
219
220/// Appends an edge with a fallible allocation.
221///
222/// # Errors
223///
224/// [`Error::OutOfMemory`].
225fn push_edge(
226    edges: &mut Vec<DispatchEdge>,
227    from: usize,
228    to: usize,
229    weight: Ticks,
230) -> Result<(), Error> {
231    edges.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
232    edges.push(DispatchEdge {
233        from: TimePoint(from),
234        to: TimePoint(to),
235        weight,
236    });
237    Ok(())
238}