Skip to main content

temporal_control/
stn.rs

1//! Simple Temporal Networks (STN).
2//!
3//! An STN is a set of time points and binary constraints `lo <= t_j - t_i <= hi`. Its distance
4//! graph has an edge `i -> j` with weight `hi` and an edge `j -> i` with weight `-lo` per
5//! constraint. The network is consistent iff the distance graph has no negative cycle
6//! (Dechter, Meiri and Pearl 1991).
7//!
8//! ```mermaid
9//! graph LR
10//!     stn["Stn"] -->|"check_consistency (Bellman-Ford)"| v1["Verdict: Schedule or NegativeCycle"]
11//!     stn -->|"minimal_network (Floyd-Warshall)"| v2["Verdict: MinimalNetwork or NegativeCycle"]
12//!     stn -->|"partial_path_consistency (P3C)"| v4["Verdict: ChordalNetwork or NegativeCycle"]
13//!     inc["IncrementalStn"] -->|"add_constraint, O(n^2)"| v3["Verdict: ConstraintId or NegativeCycle"]
14//! ```
15
16mod bellman_ford;
17mod dispatchable;
18mod explanation;
19pub(crate) mod floyd_warshall;
20mod incremental;
21mod minimal;
22mod p3c;
23
24use alloc::vec::Vec;
25
26pub use crate::TimePoint;
27use crate::dispatch::DispatchableNetwork;
28use crate::{Budget, Error, Ticks};
29
30pub use explanation::{Bound, CycleEdge, NegativeCycle};
31pub use incremental::IncrementalStn;
32pub use minimal::MinimalNetwork;
33pub use p3c::ChordalNetwork;
34
35/// Handle of a constraint inside one [`Stn`], in insertion order starting at zero.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
37pub struct ConstraintId(pub usize);
38
39/// A binary constraint `lo <= t_to - t_from <= hi`.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41pub struct Constraint {
42    /// The time point subtracted (`t_i`).
43    pub from: TimePoint,
44    /// The time point the difference is measured to (`t_j`).
45    pub to: TimePoint,
46    /// Lower bound on `t_to - t_from`; `None` means unbounded below.
47    pub lo: Option<Ticks>,
48    /// Upper bound on `t_to - t_from`; `None` means unbounded above.
49    pub hi: Option<Ticks>,
50}
51
52/// Outcome of a check that answered the question.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub enum Verdict<T> {
55    /// The network is consistent; the payload is a certificate or derived structure.
56    Consistent(T),
57    /// The network is inconsistent; the payload names the constraints forming a negative cycle.
58    Inconsistent(NegativeCycle),
59}
60
61/// One assignment of a time to every time point that satisfies all constraints.
62///
63/// Serves as a checkable certificate of consistency.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct Schedule {
66    /// Time of each time point, indexed by [`TimePoint`] index.
67    times: Vec<Ticks>,
68}
69
70impl Schedule {
71    /// Time assigned to `tp`, or `None` if `tp` is not part of the network.
72    #[must_use]
73    pub fn time(&self, tp: TimePoint) -> Option<Ticks> {
74        self.times.get(tp.0).copied()
75    }
76
77    /// All times, indexed by time point.
78    #[must_use]
79    pub fn times(&self) -> &[Ticks] {
80        &self.times
81    }
82}
83
84/// A directed, weighted distance-graph edge `from -> to` meaning `t_to - t_from <= weight`.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86struct Edge {
87    /// Tail time point index.
88    from: usize,
89    /// Head time point index.
90    to: usize,
91    /// Edge weight, already negated for lower bounds.
92    weight: Ticks,
93    /// The constraint bound this edge encodes, for explanations.
94    source: CycleEdge,
95}
96
97/// A Simple Temporal Network.
98///
99/// Construction only fails on handle validation and checked arithmetic.
100/// Algorithms are read-only and take an explicit [`Budget`].
101#[derive(Debug, Clone, Default)]
102pub struct Stn {
103    /// Number of time points.
104    time_points: usize,
105    /// Constraints in insertion order; index is the [`ConstraintId`].
106    constraints: Vec<Constraint>,
107    /// Distance-graph edges derived from `constraints`, one per finite bound.
108    edges: Vec<Edge>,
109}
110
111impl Stn {
112    /// Creates an empty network.
113    #[must_use]
114    pub fn new() -> Self {
115        Self::default()
116    }
117
118    /// Adds a time point and returns its handle.
119    ///
120    /// # Errors
121    ///
122    /// [`Error::Overflow`] if the number of time points would exceed `usize::MAX`.
123    pub fn add_time_point(&mut self) -> Result<TimePoint, Error> {
124        let tp = TimePoint(self.time_points);
125        self.time_points = self.time_points.checked_add(1).ok_or(Error::Overflow)?;
126        Ok(tp)
127    }
128
129    /// Number of time points.
130    #[must_use]
131    pub fn time_point_count(&self) -> usize {
132        self.time_points
133    }
134
135    /// All constraints, indexed by [`ConstraintId`].
136    #[must_use]
137    pub fn constraints(&self) -> &[Constraint] {
138        &self.constraints
139    }
140
141    /// Looks up one constraint.
142    #[must_use]
143    pub fn constraint(&self, id: ConstraintId) -> Option<&Constraint> {
144        self.constraints.get(id.0)
145    }
146
147    /// Adds the constraint `lo <= t_to - t_from <= hi`.
148    ///
149    /// Either bound may be `None` (unbounded). `lo > hi` is accepted and makes the network
150    /// inconsistent, which the checks then explain.
151    ///
152    /// # Errors
153    ///
154    /// - [`Error::UnknownTimePoint`] if `from` or `to` is not in this network.
155    /// - [`Error::Overflow`] if `lo` is `i64::MIN`, whose negation is not representable.
156    pub fn add_constraint(
157        &mut self,
158        from: TimePoint,
159        to: TimePoint,
160        lo: Option<Ticks>,
161        hi: Option<Ticks>,
162    ) -> Result<ConstraintId, Error> {
163        if from.0 >= self.time_points || to.0 >= self.time_points {
164            return Err(Error::UnknownTimePoint);
165        }
166
167        let neg_lo = lo
168            .map(|l| l.checked_neg().ok_or(Error::Overflow))
169            .transpose()?;
170        let id = ConstraintId(self.constraints.len());
171
172        if let Some(w) = hi {
173            self.push_edge(from, to, w, CycleEdge::new(id, Bound::Upper));
174        }
175
176        if let Some(w) = neg_lo {
177            self.push_edge(to, from, w, CycleEdge::new(id, Bound::Lower));
178        }
179
180        self.constraints.push(Constraint { from, to, lo, hi });
181        Ok(id)
182    }
183
184    /// Checks consistency with Bellman-Ford from a virtual source.
185    ///
186    /// Runs in `O(n * m)` steps and `O(n + m)` memory. A consistent verdict carries a
187    /// [`Schedule`] that satisfies every constraint; an inconsistent verdict carries a
188    /// [`NegativeCycle`].
189    ///
190    /// # Errors
191    ///
192    /// - [`Error::BudgetExhausted`] if the step budget runs out.
193    /// - [`Error::Overflow`] if a path weight overflows `i64`.
194    /// - [`Error::Internal`] if cycle extraction breaks an invariant (a bug).
195    pub fn check_consistency(&self, budget: &Budget) -> Result<Verdict<Schedule>, Error> {
196        let mut meter = budget.meter();
197        bellman_ford::run(self, &mut meter)
198    }
199
200    /// Computes the minimal network (all-pairs shortest paths) with Floyd-Warshall.
201    ///
202    /// Runs in `O(n^3)` steps and `n^2` cells. On inconsistency, the explanation is extracted
203    /// with Bellman-Ford using the remaining budget; if Bellman-Ford disagrees, the result is
204    /// [`Error::Internal`].
205    ///
206    /// # Errors
207    ///
208    /// - [`Error::MemoryBudgetExceeded`] if `n^2` exceeds [`Budget::max_cells`].
209    /// - [`Error::OutOfMemory`] if the allocator refuses the matrix.
210    /// - [`Error::BudgetExhausted`] if the step budget runs out.
211    /// - [`Error::Overflow`] if a path weight, or the negation of one, overflows `i64`.
212    /// - [`Error::Internal`] on disagreement between the two algorithms (a bug).
213    pub fn minimal_network(&self, budget: &Budget) -> Result<Verdict<MinimalNetwork>, Error> {
214        let mut meter = budget.meter();
215
216        if let Some(dist) = floyd_warshall::run(self, budget, &mut meter)? {
217            return MinimalNetwork::new(self.time_points, dist).map(Verdict::Consistent);
218        }
219
220        match bellman_ford::run(self, &mut meter)? {
221            Verdict::Inconsistent(cycle) => Ok(Verdict::Inconsistent(cycle)),
222            Verdict::Consistent(_) => Err(Error::Internal),
223        }
224    }
225
226    /// Computes the minimal constraints of every constrained pair with P³C (Planken, de Weerdt
227    /// and van der Krogt, ICAPS 2008), without the full `n^2` minimal network.
228    ///
229    /// The result covers a chordal supergraph of the constraint graph: every pair that shares a
230    /// constraint, plus the fill edges of a minimum-degree triangulation. For each of those
231    /// pairs the bounds equal [`Stn::minimal_network`]'s. To include a pair that shares no
232    /// constraint, add one without bounds. Runs in `O((n + m + t) log n)` steps for `m`
233    /// constraints and `t` triangles of the chordal graph (`O(n w*^2)` for induced width `w*`,
234    /// at most `O(n^3)`); see the `p3c` module docs. On inconsistency the explanation comes
235    /// from Bellman-Ford using the remaining budget, which also decides the verdict if P³C
236    /// overflows first.
237    ///
238    /// # Errors
239    ///
240    /// - [`Error::MemoryBudgetExceeded`] if the chordal graph has more than
241    ///   [`Budget::max_cells`] directed edges (two per pair).
242    /// - [`Error::BudgetExhausted`] if the step budget runs out.
243    /// - [`Error::Overflow`] if a path length, or the negation of a bound, overflows `i64` on a
244    ///   consistent network.
245    /// - [`Error::Internal`] if Bellman-Ford finds consistent a network P³C rejected (a bug).
246    ///
247    /// # Examples
248    ///
249    /// ```
250    /// use temporal_control::{Budget, Stn, Ticks, TimePoint, Verdict};
251    ///
252    /// // A chain a -> b -> c of 2..5 ticks each; the pair (a, c) is of interest.
253    /// let mut stn = Stn::new();
254    /// let [a, b, c] = [(); 3].map(|()| stn.add_time_point().expect("fits"));
255    /// stn.add_constraint(a, b, Some(Ticks(2)), Some(Ticks(5))).expect("exists");
256    /// stn.add_constraint(b, c, Some(Ticks(2)), Some(Ticks(5))).expect("exists");
257    /// stn.add_constraint(a, c, None, None).expect("exists");
258    ///
259    /// let Verdict::Consistent(net) = stn.partial_path_consistency(&Budget::UNLIMITED).expect("fits")
260    /// else {
261    ///     panic!("consistent");
262    /// };
263    /// assert_eq!((net.lower(a, c), net.upper(a, c)), (Some(Ticks(4)), Some(Ticks(10))));
264    /// assert!(!net.contains(TimePoint(0), TimePoint(7)));
265    /// ```
266    pub fn partial_path_consistency(
267        &self,
268        budget: &Budget,
269    ) -> Result<Verdict<ChordalNetwork>, Error> {
270        let mut meter = budget.meter();
271        let overflowed = match p3c::run(self, budget, &mut meter) {
272            Ok(Some(net)) => return Ok(Verdict::Consistent(net)),
273            Ok(None) => false,
274            Err(Error::Overflow) => true,
275            Err(e) => return Err(e),
276        };
277
278        match bellman_ford::run(self, &mut meter)? {
279            Verdict::Inconsistent(cycle) => Ok(Verdict::Inconsistent(cycle)),
280            Verdict::Consistent(_) if overflowed => Err(Error::Overflow),
281            Verdict::Consistent(_) => Err(Error::Internal),
282        }
283    }
284
285    /// Computes the minimal network and filters it into a dispatchable network.
286    ///
287    /// Costs `O(n^3)` steps and `n^2` cells. See [`MinimalNetwork::dispatchable`].
288    ///
289    /// # Errors
290    ///
291    /// As for [`Stn::minimal_network`] and [`MinimalNetwork::dispatchable`]. Each phase is
292    /// metered against the full `budget`, so the total can reach twice its step limit.
293    ///
294    /// # Examples
295    ///
296    /// ```
297    /// use temporal_control::{Budget, Dispatcher, Stn, Ticks, TimePoint, Verdict};
298    ///
299    /// // A chain a -> b -> c, each step 2..5 ticks: the implied a -> c edges are filtered out.
300    /// let mut stn = Stn::new();
301    /// let [a, b, c] = [(); 3].map(|()| stn.add_time_point().expect("fits"));
302    /// stn.add_constraint(a, b, Some(Ticks(2)), Some(Ticks(5))).expect("exists");
303    /// stn.add_constraint(b, c, Some(Ticks(2)), Some(Ticks(5))).expect("exists");
304    ///
305    /// let Verdict::Consistent(net) = stn.dispatchable(&Budget::UNLIMITED).expect("fits") else {
306    ///     panic!("consistent");
307    /// };
308    /// assert_eq!(net.edges().len(), 4);
309    ///
310    /// let mut d: Dispatcher<3, 8> = net.dispatcher().expect("fits");
311    /// let mut out = [TimePoint(0); 3];
312    /// assert_eq!(d.step(Ticks(0), &[], &mut out), Ok(1));
313    /// assert_eq!(d.next_wakeup(), Some(Ticks(2)));
314    /// ```
315    pub fn dispatchable(&self, budget: &Budget) -> Result<Verdict<DispatchableNetwork>, Error> {
316        match self.minimal_network(budget)? {
317            Verdict::Consistent(min) => min.dispatchable(budget).map(Verdict::Consistent),
318            Verdict::Inconsistent(cycle) => Ok(Verdict::Inconsistent(cycle)),
319        }
320    }
321
322    /// Appends one distance-graph edge.
323    fn push_edge(&mut self, from: TimePoint, to: TimePoint, weight: Ticks, source: CycleEdge) {
324        self.edges.push(Edge {
325            from: from.0,
326            to: to.0,
327            weight,
328            source,
329        });
330    }
331}
332
333/// Converts a collection length into a step count.
334///
335/// # Errors
336///
337/// [`Error::Overflow`] if the length does not fit `u64`.
338pub(crate) fn steps(len: usize) -> Result<u64, Error> {
339    u64::try_from(len).map_err(|_| Error::Overflow)
340}