temporal_control/stn/incremental.rs
1//! Incremental consistency: keep the all-pairs distance matrix closed while constraints arrive.
2//!
3//! Adding the distance-graph edge `u -> v` with weight `w` to a consistent network with closed
4//! distance matrix `D` creates a negative cycle iff `D[v][u] + w < 0`. Otherwise the new closed
5//! matrix is `D'[a][b] = min(D[a][b], D[a][u] + w + D[v][b])`. Row `u` and column `v` do not
6//! change under this update (that would need `D[v][u] + w < 0`), so it can run in place.
7//!
8//! A constraint has up to two edges. If both are added, the second sees `D'[u][v] =
9//! min(D[u][v], hi)`, so the pair is rejected iff `D[v][u] + hi < 0`, `D[u][v] - lo < 0` or
10//! `hi - lo < 0`. All three are checked before anything changes, so a rejected constraint leaves
11//! the network untouched. The update itself runs on a copy of the matrix that replaces the
12//! original only on success, so overflow or budget exhaustion leave it untouched as well.
13
14use alloc::vec::Vec;
15
16use super::{ConstraintId, MinimalNetwork, Stn, TimePoint, Verdict, bellman_ford, steps};
17use crate::{Budget, Error, Ticks};
18
19/// An STN that keeps its minimal network up to date as constraints are added.
20///
21/// Each [`IncrementalStn::add_constraint`] costs `O(n^2)` steps instead of the `O(n^3)` of a
22/// full [`Stn::minimal_network`] recomputation. A constraint that would make the network
23/// inconsistent is rejected: the network stays as it was and the verdict explains why.
24///
25/// # Examples
26///
27/// ```
28/// use temporal_control::{Budget, IncrementalStn, Ticks, Verdict};
29///
30/// let mut stn = IncrementalStn::new();
31/// let budget = Budget::UNLIMITED;
32/// let a = stn.add_time_point(&budget).expect("fits");
33/// let b = stn.add_time_point(&budget).expect("fits");
34///
35/// let ok = stn.add_constraint(a, b, Some(Ticks(5)), Some(Ticks(15)), &budget).expect("ok");
36/// assert!(matches!(ok, Verdict::Consistent(_)));
37///
38/// // 20 <= t_b - t_a contradicts t_b - t_a <= 15 and is rejected.
39/// let bad = stn.add_constraint(a, b, Some(Ticks(20)), None, &budget).expect("ok");
40/// assert!(matches!(bad, Verdict::Inconsistent(_)));
41/// assert_eq!(stn.stn().constraints().len(), 1);
42/// assert_eq!(stn.upper(a, b), Some(Ticks(15)));
43/// ```
44#[derive(Debug, Clone, Default)]
45pub struct IncrementalStn {
46 /// The accepted constraints. Always consistent.
47 stn: Stn,
48 /// Row-major `n * n` closed distance matrix of `stn`; `None` is `+infinity`.
49 dist: Vec<Option<Ticks>>,
50}
51
52impl IncrementalStn {
53 /// Creates an empty network.
54 #[must_use]
55 pub fn new() -> Self {
56 Self::default()
57 }
58
59 /// Adds an unconstrained time point.
60 ///
61 /// Costs `O(n^2)` steps to grow the matrix.
62 ///
63 /// # Errors
64 ///
65 /// - [`Error::MemoryBudgetExceeded`] if `(n + 1)^2` exceeds [`Budget::max_cells`].
66 /// - [`Error::OutOfMemory`] if the allocator refuses the new matrix.
67 /// - [`Error::BudgetExhausted`] if the step budget cannot cover the copy.
68 /// - [`Error::Overflow`] if the time point count overflows.
69 pub fn add_time_point(&mut self, budget: &Budget) -> Result<TimePoint, Error> {
70 let n = self.stn.time_points;
71 let m = n.checked_add(1).ok_or(Error::Overflow)?;
72 let cells = m.checked_mul(m).ok_or(Error::MemoryBudgetExceeded)?;
73 budget.check_cells(cells)?;
74 budget.meter().spend(steps(cells)?)?;
75
76 let mut dist = Vec::new();
77 dist.try_reserve_exact(cells)
78 .map_err(|_| Error::OutOfMemory)?;
79
80 for row in self.dist.chunks(n.max(1)).take(n) {
81 dist.extend_from_slice(row);
82 dist.push(None);
83 }
84
85 dist.extend(core::iter::repeat_n(None, n));
86 dist.push(Some(Ticks::ZERO));
87
88 let tp = self.stn.add_time_point()?;
89 self.dist = dist;
90 Ok(tp)
91 }
92
93 /// Adds `lo <= t_to - t_from <= hi` if the network stays consistent.
94 ///
95 /// Returns the new [`ConstraintId`] on success. On inconsistency the constraint is not
96 /// added and the verdict carries a negative cycle through the rejected constraint, whose id
97 /// in the cycle is the one it would have received.
98 ///
99 /// # Errors
100 ///
101 /// - [`Error::UnknownTimePoint`] if `from` or `to` is not in this network.
102 /// - [`Error::Overflow`] if `lo` is `i64::MIN` or a path length overflows. The network is
103 /// unchanged.
104 /// - [`Error::BudgetExhausted`] if the `O(n^2)` update, or the explanation search after a
105 /// rejection, does not fit the step budget. The network is unchanged.
106 /// - [`Error::Internal`] if the explanation search disagrees with the matrix (a bug).
107 pub fn add_constraint(
108 &mut self,
109 from: TimePoint,
110 to: TimePoint,
111 lo: Option<Ticks>,
112 hi: Option<Ticks>,
113 budget: &Budget,
114 ) -> Result<Verdict<ConstraintId>, Error> {
115 let n = self.stn.time_points;
116
117 if from.0 >= n || to.0 >= n {
118 return Err(Error::UnknownTimePoint);
119 }
120
121 let neg_lo = lo
122 .map(|l| l.checked_neg().ok_or(Error::Overflow))
123 .transpose()?;
124 let mut meter = budget.meter();
125
126 if self.closes_negative_cycle(from.0, to.0, hi, neg_lo)? {
127 return self.explain_rejection(from, to, lo, hi, budget);
128 }
129
130 let mut dist = copy_matrix(&self.dist)?;
131
132 for (u, v, w) in [(from.0, to.0, hi), (to.0, from.0, neg_lo)] {
133 if let Some(w) = w {
134 meter.spend(steps(n * n)?)?;
135 close_after_edge(&mut dist, n, u, v, w)?;
136 }
137 }
138
139 let id = self.stn.add_constraint(from, to, lo, hi)?;
140 self.dist = dist;
141 Ok(Verdict::Consistent(id))
142 }
143
144 /// Tightest upper bound on `t_to - t_from`; `None` if unbounded or a handle is unknown.
145 #[must_use]
146 pub fn upper(&self, from: TimePoint, to: TimePoint) -> Option<Ticks> {
147 let n = self.stn.time_points;
148
149 if from.0 >= n || to.0 >= n {
150 return None;
151 }
152
153 self.dist[from.0 * n + to.0]
154 }
155
156 /// Tightest lower bound on `t_to - t_from`; `None` if unbounded or a handle is unknown.
157 #[must_use]
158 pub fn lower(&self, from: TimePoint, to: TimePoint) -> Option<Ticks> {
159 self.upper(to, from).and_then(Ticks::checked_neg)
160 }
161
162 /// The accepted constraints as a plain [`Stn`].
163 #[must_use]
164 pub fn stn(&self) -> &Stn {
165 &self.stn
166 }
167
168 /// A snapshot of the current minimal network.
169 ///
170 /// # Errors
171 ///
172 /// [`Error::Overflow`] if an entry is `i64::MIN`; [`Error::OutOfMemory`] if the copy fails.
173 pub fn minimal_network(&self) -> Result<MinimalNetwork, Error> {
174 MinimalNetwork::new(self.stn.time_points, copy_matrix(&self.dist)?)
175 }
176
177 /// Whether adding the edges `u -> v` (`hi`) and `v -> u` (`neg_lo`) closes a negative cycle.
178 ///
179 /// # Errors
180 ///
181 /// [`Error::Overflow`] if a cycle length overflows.
182 fn closes_negative_cycle(
183 &self,
184 u: usize,
185 v: usize,
186 hi: Option<Ticks>,
187 neg_lo: Option<Ticks>,
188 ) -> Result<bool, Error> {
189 let n = self.stn.time_points;
190 let negative = |path: Option<Ticks>, edge: Option<Ticks>| -> Result<bool, Error> {
191 match (path, edge) {
192 (Some(dist), Some(weight)) => {
193 Ok(dist.checked_add(weight).ok_or(Error::Overflow)? < Ticks::ZERO)
194 }
195 _ => Ok(false),
196 }
197 };
198
199 Ok(negative(self.dist[v * n + u], hi)?
200 || negative(self.dist[u * n + v], neg_lo)?
201 || negative(hi, neg_lo)?)
202 }
203
204 /// Builds the negative-cycle explanation for a rejected constraint.
205 ///
206 /// # Errors
207 ///
208 /// [`Error::BudgetExhausted`], [`Error::Overflow`], or [`Error::Internal`] if Bellman-Ford
209 /// finds the extended network consistent.
210 fn explain_rejection(
211 &self,
212 from: TimePoint,
213 to: TimePoint,
214 lo: Option<Ticks>,
215 hi: Option<Ticks>,
216 budget: &Budget,
217 ) -> Result<Verdict<ConstraintId>, Error> {
218 let mut extended = self.stn.clone();
219 extended.add_constraint(from, to, lo, hi)?;
220
221 match bellman_ford::run(&extended, &mut budget.meter())? {
222 Verdict::Inconsistent(cycle) => Ok(Verdict::Inconsistent(cycle)),
223 Verdict::Consistent(_) => Err(Error::Internal),
224 }
225 }
226}
227
228/// Copies a distance matrix with a fallible allocation.
229///
230/// # Errors
231///
232/// [`Error::OutOfMemory`] if the allocation fails.
233fn copy_matrix(dist: &[Option<Ticks>]) -> Result<Vec<Option<Ticks>>, Error> {
234 let mut copy = Vec::new();
235 copy.try_reserve_exact(dist.len())
236 .map_err(|_| Error::OutOfMemory)?;
237 copy.extend_from_slice(dist);
238 Ok(copy)
239}
240
241/// Adds edge `u -> v` with weight `w` to the closed matrix `dist` and re-closes it in place.
242///
243/// The caller has ruled out a negative cycle through the edge, so row `u` and column `v` are
244/// fixed points of the update and reading them while writing is sound.
245///
246/// # Errors
247///
248/// [`Error::Overflow`] if a candidate path length overflows; `dist` is then partially updated
249/// and must be discarded.
250fn close_after_edge(
251 dist: &mut [Option<Ticks>],
252 n: usize,
253 u: usize,
254 v: usize,
255 w: Ticks,
256) -> Result<(), Error> {
257 for a in 0..n {
258 let Some(d_au) = dist[a * n + u] else {
259 continue;
260 };
261
262 let via = d_au.checked_add(w).ok_or(Error::Overflow)?;
263
264 for b in 0..n {
265 let Some(d_vb) = dist[v * n + b] else {
266 continue;
267 };
268
269 let candidate = via.checked_add(d_vb).ok_or(Error::Overflow)?;
270 let cell = &mut dist[a * n + b];
271
272 if cell.is_none_or(|d| candidate < d) {
273 *cell = Some(candidate);
274 }
275 }
276 }
277
278 Ok(())
279}