Skip to main content

temporal_control/
stnu.rs

1//! Simple Temporal Networks with Uncertainty (STNU) and dynamic controllability.
2//!
3//! An STNU is an [`Stn`] of *requirement* constraints plus *contingent links* `(A, lo, hi, C)`:
4//! once the activation point `A` happens at `a`, nature makes the contingent point `C` happen at
5//! some time in `[a + lo, a + hi]`, and the agent learns it only then. An STNU is *dynamically
6//! controllable* (DC) if the agent can execute its points, reacting to observations as they
7//! arrive, so that every requirement holds for every outcome of the contingent links.
8//!
9//! # Reaction-time semantics
10//!
11//! Time is integer [`Ticks`]. An observation at tick `t` may influence decisions at the same
12//! tick `t` (*instantaneous reaction at tick granularity*): within one tick, nature's contingent
13//! events come first, then the agent acts. This is the semantics under which the edge-generation
14//! rules used here are exact; the integration tests check it against a brute-force game solver.
15//! It requires the executive to deliver observations before it asks for executions in a tick,
16//! as [`Dispatcher::step`](crate::Dispatcher::step) does. It is the variant Morris (CPAIOR
17//! 2014) uses: time-based histories as fixed by Hunsberger (TIME 2009), but including the
18//! present. A system that can only react one tick later needs the stricter variant, the
19//! discrete analogue of Hunsberger's DES* (decisions at `t` see contingent events strictly
20//! before `t`): check [`Stnu::with_reaction`] with [`Reaction::NextTick`] instead.
21//!
22//! ```mermaid
23//! graph LR
24//!     stnu["Stnu"] -->|"dispatchable (Morris 2014 dispatchable, minimised)"| v["Controllable(DispatchableNetwork) or Uncontrollable"]
25//!     stnu -->|"check_controllability (Morris 2014, O(n^3))"| c["Controllable or Uncontrollable"]
26//!     stnu -->|"check_controllability_with (RUL-minus, per-label backprop)"| c
27//!     v --> d["Dispatcher (onboard)"]
28//!     c -->|"Uncontrollable"| e["SemiReducibleCycle"]
29//! ```
30//!
31//! Every checker explains a negative verdict with a [`SemiReducibleCycle`]. The checkers other
32//! than [`DcAlgorithm::Morris2014`] take it from that checker, and report [`Error::Internal`]
33//! if it disagrees, so a negative verdict is always confirmed by two algorithms.
34
35mod backprop;
36mod closure;
37mod estnu;
38mod explanation;
39mod min_disp;
40mod morris;
41mod reaction;
42mod rul;
43
44pub use explanation::{CycleStep, DerivedEdge, LabelledEdge, SemiReducibleCycle};
45pub use reaction::Reaction;
46
47use alloc::vec::Vec;
48
49use crate::dispatch::DispatchableNetwork;
50use crate::stn::{ConstraintId, Stn};
51use crate::{Budget, Error, Ticks, TimePoint};
52
53/// Handle of a contingent link inside one [`Stnu`], in insertion order starting at zero.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
55pub struct ContingentId(pub usize);
56
57/// A contingent link: `contingent` happens between `lo` and `hi` ticks after `activation`.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59pub struct ContingentLink {
60    /// The point that starts the uncontrollable duration. Any time point, contingent ones
61    /// included.
62    pub activation: TimePoint,
63    /// The point nature executes. Created together with the link; no other link targets it.
64    pub contingent: TimePoint,
65    /// Shortest duration. Positive.
66    pub lo: Ticks,
67    /// Longest duration. At least `lo`.
68    pub hi: Ticks,
69}
70
71/// Outcome of a dynamic-controllability check that answered the question.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub enum Controllability<T> {
74    /// The network is dynamically controllable; the payload is a derived structure.
75    Controllable(T),
76    /// No dynamic strategy satisfies every requirement in every situation; the payload names
77    /// the requirements and contingent extremes that conflict.
78    Uncontrollable(SemiReducibleCycle),
79}
80
81/// Which dynamic-controllability checker [`Stnu::check_controllability_with`] runs.
82///
83/// All of them decide the same question under the same (instantaneous-reaction) semantics;
84/// they differ in cost and serve as cross-checks for each other.
85#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
86pub enum DcAlgorithm {
87    /// Morris (2014): backpropagation from negative nodes, one propagation per node,
88    /// explains negative verdicts itself.
89    ///
90    /// Time `O(n m + n^3)` for `n` points, `k` links and `m` requirement bounds, i.e. Morris's
91    /// `O(n^3)` when `m = O(n^2)`. Proof sketch: in Morris's normal form there are
92    /// `n' = n + k <= 2n` nodes; each runs at most one backward Dijkstra; a linear-scan
93    /// extract-min makes that `O(n'^2)` plus one scan of each node's incoming edges; derived
94    /// edges are non-negative and at most one per (node, source) pair, so all incoming lists
95    /// together hold `O(m + n'^2)` edges, each scanned at its final length because a node's
96    /// own propagation (the only one adding edges into it) finishes before anyone extends
97    /// through it. Explaining a negative verdict adds `O(n^3)` for the compact cycle (see
98    /// [`SemiReducibleCycle`]).
99    #[default]
100    Morris2014,
101    /// RUL⁻ (Cairo, Hunsberger and Rizzi 2018): backpropagation from contingent points with a
102    /// potential function, at most `2k` rounds, `O(n m + k (m + k n) log n)`. Fastest on
103    /// sparse networks with few links.
104    RulMinus,
105    /// RUL2021 (Hunsberger and Posenato, AAAI 2022): RUL⁻ processing each upper-case edge once,
106    /// recursively, inserting only length-preserving edges and checking non-negative loops by
107    /// a forward propagation instead. Same bound as RUL⁻, much less work in practice.
108    Rul2021,
109    /// Morris-style backpropagation without the normal form: one propagation per kind of
110    /// negative incoming edge, `O(n (k + 1) (m + n^2) log n)`. Kept as an independent
111    /// cross-check.
112    PerLabelBackprop,
113}
114
115/// Which algorithm [`Stnu::dispatchable_with`] uses to build the dispatchable network.
116///
117/// For `n` points, `k` links and `m` requirement bounds.
118#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
119pub enum DispatchAlgorithm {
120    /// [`DispatchAlgorithm::Morris2014`] followed by the `minDispESTNU` minimisation of
121    /// Hunsberger and Posenato (ICAPS 2024): stand-in edges, STN dispatchability filtering of
122    /// the ordinary edges, and removal of dominated waits. Without the paper's diamond
123    /// stand-ins, which only its `RTE*` executor can rely on, so the result is smaller than
124    /// Morris's but not proven minimal. `O(n m + k n^3)` time, `O(n^2)` cells.
125    #[default]
126    Minimal,
127    /// Morris's dispatchable variant of his 2014 algorithm: inserts every ordinary edge and
128    /// wait the backpropagation derives. `O((n + k)(m + n^2 + n k))` time, `n^2 + n k` cells.
129    Morris2014,
130    /// Closure of the labelled distance graph under the Morris-Muscettola rules, all-pairs.
131    /// `O(n^3 + n^2 k)` per round; the number of rounds is not proven (the budget bounds it).
132    /// Kept as the reference the others are checked against.
133    Closure,
134}
135
136/// A Simple Temporal Network with Uncertainty.
137///
138/// # Examples
139///
140/// ```
141/// use temporal_control::{Budget, Controllability, Stnu, Ticks};
142///
143/// // Warm-up takes 5..15 ticks; analysis must start within 2 ticks of its end.
144/// let mut stnu = Stnu::new();
145/// let start = stnu.add_time_point().expect("fits");
146/// let warm = stnu.add_contingent_link(start, Ticks(5), Ticks(15)).expect("valid");
147/// let analysis = stnu.add_time_point().expect("fits");
148/// stnu.add_constraint(warm, analysis, Some(Ticks(0)), Some(Ticks(2))).expect("exists");
149///
150/// let verdict = stnu.dispatchable(&Budget::UNLIMITED).expect("within budget");
151/// assert!(matches!(verdict, Controllability::Controllable(_)));
152/// ```
153#[derive(Debug, Clone, Default)]
154pub struct Stnu {
155    /// Time points and requirement constraints.
156    requirements: Stn,
157    /// Contingent links in insertion order; index is the [`ContingentId`].
158    links: Vec<ContingentLink>,
159}
160
161impl Stnu {
162    /// Creates an empty network.
163    #[must_use]
164    pub fn new() -> Self {
165        Self::default()
166    }
167
168    /// Adds an executable time point.
169    ///
170    /// # Errors
171    ///
172    /// [`Error::Overflow`] if the number of time points would exceed `usize::MAX`.
173    pub fn add_time_point(&mut self) -> Result<TimePoint, Error> {
174        self.requirements.add_time_point()
175    }
176
177    /// Adds a contingent link from `activation` and returns its new contingent time point.
178    ///
179    /// # Errors
180    ///
181    /// - [`Error::UnknownTimePoint`] if `activation` is not in this network.
182    /// - [`Error::InvalidContingentLink`] unless `0 < lo <= hi`.
183    /// - [`Error::Overflow`] if the number of time points would exceed `usize::MAX`.
184    pub fn add_contingent_link(
185        &mut self,
186        activation: TimePoint,
187        lo: Ticks,
188        hi: Ticks,
189    ) -> Result<TimePoint, Error> {
190        if activation.0 >= self.requirements.time_point_count() {
191            return Err(Error::UnknownTimePoint);
192        }
193
194        if lo <= Ticks::ZERO || hi < lo {
195            return Err(Error::InvalidContingentLink);
196        }
197
198        let contingent = self.requirements.add_time_point()?;
199        self.links.push(ContingentLink {
200            activation,
201            contingent,
202            lo,
203            hi,
204        });
205        Ok(contingent)
206    }
207
208    /// Adds the requirement `lo <= t_to - t_from <= hi`. See [`Stn::add_constraint`].
209    ///
210    /// # Errors
211    ///
212    /// As for [`Stn::add_constraint`].
213    pub fn add_constraint(
214        &mut self,
215        from: TimePoint,
216        to: TimePoint,
217        lo: Option<Ticks>,
218        hi: Option<Ticks>,
219    ) -> Result<ConstraintId, Error> {
220        self.requirements.add_constraint(from, to, lo, hi)
221    }
222
223    /// Time points and requirement constraints, without the contingent links.
224    #[must_use]
225    pub fn requirements(&self) -> &Stn {
226        &self.requirements
227    }
228
229    /// All contingent links, indexed by [`ContingentId`].
230    #[must_use]
231    pub fn links(&self) -> &[ContingentLink] {
232        &self.links
233    }
234
235    /// Number of time points, executable and contingent.
236    #[must_use]
237    pub fn time_point_count(&self) -> usize {
238        self.requirements.time_point_count()
239    }
240
241    /// Checks dynamic controllability with Morris's `O(n^3)` backpropagation from negative
242    /// nodes ([`DcAlgorithm::Morris2014`]).
243    ///
244    /// Independent of [`Stnu::dispatchable`]; both must agree, which the tests check. Use this
245    /// when only the verdict (and an explanation) is needed: it keeps `O(m + n^2)` memory in
246    /// the worst case instead of dense matrices. See the `morris` module docs for the
247    /// algorithm and the proof of its bound.
248    ///
249    /// [`Budget::max_cells`] must admit `(n + k)^2` cells, the worst case of derived edges.
250    /// shortcut: the allocations themselves (adjacency lists, derived edges, search state)
251    /// abort on allocator failure; make them fallible before running this onboard.
252    ///
253    /// # Examples
254    ///
255    /// ```
256    /// use temporal_control::{Budget, Controllability, Stnu, Ticks};
257    ///
258    /// // X must precede the end of a [1, 10] activity by 1..2 ticks: impossible to schedule.
259    /// let mut stnu = Stnu::new();
260    /// let a = stnu.add_time_point().expect("fits");
261    /// let c = stnu.add_contingent_link(a, Ticks(1), Ticks(10)).expect("valid");
262    /// let x = stnu.add_time_point().expect("fits");
263    /// stnu.add_constraint(x, c, Some(Ticks(1)), Some(Ticks(2))).expect("exists");
264    ///
265    /// let verdict = stnu.check_controllability(&Budget::UNLIMITED).expect("within budget");
266    /// let Controllability::Uncontrollable(cycle) = verdict else {
267    ///     panic!("not DC");
268    /// };
269    /// // X -> C: 2 (requirement), C -> A: -10 (C may take 10), A -> C: 1 (C may take 1),
270    /// // C -> X: -1 (requirement): the agent would have to know C before it happens.
271    /// assert!(cycle.weight() < Ticks::ZERO);
272    /// assert!(!cycle.contingent_links().is_empty());
273    /// ```
274    ///
275    /// # Errors
276    ///
277    /// - [`Error::MemoryBudgetExceeded`] if `(n + k)^2` exceeds [`Budget::max_cells`].
278    /// - [`Error::BudgetExhausted`] if the step budget runs out.
279    /// - [`Error::Overflow`] if a path weight overflows `i64`.
280    pub fn check_controllability(&self, budget: &Budget) -> Result<Controllability<()>, Error> {
281        morris::run(self, budget)
282    }
283
284    /// Checks dynamic controllability with the chosen `algorithm`.
285    ///
286    /// Every algorithm returns the same verdict. A negative verdict carries the explanation of
287    /// [`DcAlgorithm::Morris2014`], which then also runs (against a fresh copy of `budget`).
288    ///
289    /// # Examples
290    ///
291    /// ```
292    /// use temporal_control::{Budget, Controllability, DcAlgorithm, Stnu, Ticks};
293    ///
294    /// let mut stnu = Stnu::new();
295    /// let a = stnu.add_time_point().expect("fits");
296    /// let c = stnu.add_contingent_link(a, Ticks(1), Ticks(10)).expect("valid");
297    /// let x = stnu.add_time_point().expect("fits");
298    /// // X within 2 ticks after C: wait for C, then execute.
299    /// stnu.add_constraint(c, x, Some(Ticks(0)), Some(Ticks(2))).expect("exists");
300    ///
301    /// for algorithm in [DcAlgorithm::Morris2014, DcAlgorithm::RulMinus] {
302    ///     let verdict = stnu.check_controllability_with(algorithm, &Budget::UNLIMITED);
303    ///     assert_eq!(verdict, Ok(Controllability::Controllable(())));
304    /// }
305    /// ```
306    ///
307    /// # Errors
308    ///
309    /// - [`Error::MemoryBudgetExceeded`] if an explanation is needed and `(n + k)^2` exceeds
310    ///   [`Budget::max_cells`] (or, for [`DcAlgorithm::Morris2014`], always in that case).
311    /// - [`Error::BudgetExhausted`] if the step budget runs out.
312    /// - [`Error::Overflow`] if a path weight overflows `i64`.
313    /// - [`Error::Internal`] if the explaining checker disagrees with the chosen one.
314    pub fn check_controllability_with(
315        &self,
316        algorithm: DcAlgorithm,
317        budget: &Budget,
318    ) -> Result<Controllability<()>, Error> {
319        match algorithm {
320            DcAlgorithm::Morris2014 => morris::run(self, budget),
321            DcAlgorithm::RulMinus => rul::run(self, budget),
322            DcAlgorithm::Rul2021 => rul::run_2021(self, budget),
323            DcAlgorithm::PerLabelBackprop => backprop::run(self, budget),
324        }
325    }
326
327    /// Checks dynamic controllability and derives a dispatchable extended STNU with few edges
328    /// ([`DispatchAlgorithm::Minimal`]).
329    ///
330    /// The result keeps the ordinary edges and *waits* (conditional upper-case edges) that a
331    /// [`Dispatcher`](crate::Dispatcher) executes. See [`DispatchAlgorithm`] for the cost.
332    ///
333    /// A negative verdict carries the explanation of [`Stnu::check_controllability`].
334    ///
335    /// # Errors
336    ///
337    /// As for [`Stnu::dispatchable_with`].
338    pub fn dispatchable(
339        &self,
340        budget: &Budget,
341    ) -> Result<Controllability<DispatchableNetwork>, Error> {
342        self.dispatchable_with(DispatchAlgorithm::default(), budget)
343    }
344
345    /// Checks dynamic controllability and derives a dispatchable extended STNU with the chosen
346    /// `algorithm`.
347    ///
348    /// Every algorithm returns the same verdict, and every dispatchable network satisfies all
349    /// requirements under every dispatch the [`Dispatcher`](crate::Dispatcher) allows (checked
350    /// by simulation in the tests). A negative verdict carries the explanation of
351    /// [`Stnu::check_controllability`], which then also runs against a fresh copy of `budget`
352    /// (except for [`DispatchAlgorithm::Morris2014`] and [`DispatchAlgorithm::Minimal`], whose
353    /// verdict comes from the same propagation).
354    ///
355    /// # Examples
356    ///
357    /// ```
358    /// use temporal_control::{Budget, Controllability, DispatchAlgorithm, Stnu, Ticks};
359    ///
360    /// // Analysis must start within 2 ticks after a 5..15 tick warm-up ends.
361    /// let mut stnu = Stnu::new();
362    /// let start = stnu.add_time_point().expect("fits");
363    /// let warm = stnu.add_contingent_link(start, Ticks(5), Ticks(15)).expect("valid");
364    /// let analysis = stnu.add_time_point().expect("fits");
365    /// stnu.add_constraint(warm, analysis, Some(Ticks(0)), Some(Ticks(2))).expect("exists");
366    ///
367    /// let size = |algorithm| match stnu.dispatchable_with(algorithm, &Budget::UNLIMITED) {
368    ///     Ok(Controllability::Controllable(net)) => net.edges().len() + net.waits().len(),
369    ///     other => panic!("DC: {other:?}"),
370    /// };
371    /// assert!(size(DispatchAlgorithm::Minimal) <= size(DispatchAlgorithm::Closure));
372    /// ```
373    ///
374    /// # Errors
375    ///
376    /// - [`Error::MemoryBudgetExceeded`] if the matrices exceed [`Budget::max_cells`].
377    /// - [`Error::OutOfMemory`] if the allocator refuses them.
378    /// - [`Error::BudgetExhausted`] if the step budget runs out.
379    /// - [`Error::Overflow`] if a path weight overflows `i64`.
380    /// - [`Error::Internal`] if the explaining checker disagrees, or the minimisation finds an
381    ///   inconsistency in a network the check found DC.
382    pub fn dispatchable_with(
383        &self,
384        algorithm: DispatchAlgorithm,
385        budget: &Budget,
386    ) -> Result<Controllability<DispatchableNetwork>, Error> {
387        let estnu = match algorithm {
388            DispatchAlgorithm::Closure => return closure::run(self, budget),
389            DispatchAlgorithm::Morris2014 | DispatchAlgorithm::Minimal => estnu::run(self, budget)?,
390        };
391
392        let Some(estnu) = estnu else {
393            return morris::explain(self, budget).map(Controllability::Uncontrollable);
394        };
395
396        let net = match algorithm {
397            DispatchAlgorithm::Minimal => min_disp::run(self, estnu, budget)?,
398            _ => estnu.into_network(self)?,
399        };
400
401        Ok(Controllability::Controllable(net))
402    }
403}