Skip to main content

temporal_control/stnu/
explanation.rs

1//! Explanations of non-controllability: semi-reducible negative cycles.
2
3use alloc::vec;
4use alloc::vec::Vec;
5
6use super::{ContingentId, Stnu};
7use crate::stn::{Bound, CycleEdge};
8use crate::{Error, Ticks, TimePoint};
9
10/// One edge of the labelled distance graph of an [`Stnu`], named by what supplied it.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum LabelledEdge {
13    /// A requirement bound, as in an STN [`NegativeCycle`](crate::NegativeCycle).
14    Requirement(CycleEdge),
15    /// The lower-case edge `A -> C` of weight `lo` of a contingent link: the possibility that
16    /// the duration takes its minimum.
17    LowerCase(ContingentId),
18    /// The upper-case edge `C -> A` of weight `-hi` of a contingent link: the possibility that
19    /// the duration takes its maximum.
20    UpperCase(ContingentId),
21}
22
23impl LabelledEdge {
24    /// The edge as `(tail, head, weight)` in `stnu`, meaning `t_head - t_tail <= weight` for
25    /// requirements and the extreme durations for the labelled edges.
26    ///
27    /// # Errors
28    ///
29    /// - [`Error::UnknownTimePoint`] if the constraint or link does not belong to `stnu`.
30    /// - [`Error::Overflow`] if a bound cannot be negated.
31    pub fn resolve(self, stnu: &Stnu) -> Result<(TimePoint, TimePoint, Ticks), Error> {
32        match self {
33            Self::Requirement(edge) => {
34                let c = stnu
35                    .requirements()
36                    .constraint(edge.constraint)
37                    .ok_or(Error::UnknownTimePoint)?;
38                let missing = Error::UnknownTimePoint;
39
40                match edge.bound {
41                    Bound::Upper => Ok((c.from, c.to, c.hi.ok_or(missing)?)),
42                    Bound::Lower => {
43                        let lo = c.lo.ok_or(missing)?;
44                        Ok((c.to, c.from, lo.checked_neg().ok_or(Error::Overflow)?))
45                    }
46                }
47            }
48            Self::LowerCase(id) => {
49                let link = stnu.links().get(id.0).ok_or(Error::UnknownTimePoint)?;
50                Ok((link.activation, link.contingent, link.lo))
51            }
52            Self::UpperCase(id) => {
53                let link = stnu.links().get(id.0).ok_or(Error::UnknownTimePoint)?;
54                let weight = link.hi.checked_neg().ok_or(Error::Overflow)?;
55                Ok((link.contingent, link.activation, weight))
56            }
57        }
58    }
59}
60
61/// One step of a [`SemiReducibleCycle`] or of a [`DerivedEdge`] in compact form.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63pub enum CycleStep {
64    /// An original edge of the labelled distance graph.
65    Edge(LabelledEdge),
66    /// A derived ordinary edge, by index into [`SemiReducibleCycle::derived`].
67    Derived(usize),
68}
69
70/// An ordinary edge the checker derived (`t_to - t_from <= weight` in every dynamic execution),
71/// with the path of steps it summarises.
72///
73/// Derived edges only refer to derived edges with smaller indices, so expanding one always
74/// terminates.
75#[derive(Debug, Clone, PartialEq, Eq, Hash)]
76pub struct DerivedEdge {
77    /// Tail.
78    pub from: TimePoint,
79    /// Head.
80    pub to: TimePoint,
81    /// Sum of the expanded path's weights.
82    pub weight: Ticks,
83    /// The summarised path from `from` to `to`, in traversal order. Never empty.
84    pub steps: Vec<CycleStep>,
85}
86
87/// A semi-reducible negative cycle: requirement bounds and contingent extremes that no
88/// dynamic strategy can satisfy together.
89///
90/// Stored in compact form: the top-level [`Self::steps`] chain like an STN cycle, and each
91/// [`CycleStep::Derived`] stands for a [`DerivedEdge`] listed once in [`Self::derived`], whose
92/// own steps may again be derived. The compact form has at most one entry per derived edge,
93/// so it stays polynomial (`O(n^3)` steps for `n` points); [`Self::edges`] expands it lazily
94/// into original edges, which can be exponentially many: an indivisible cycle can need
95/// `3 * 2^k - 2` edges for `k` links (the *magic loops* of Hunsberger, ICAART 2013), with
96/// repetitions.
97///
98/// In the expansion the head of each edge is the tail of the next, and the head of the last is
99/// the tail of the first. Summing the edge weights (lower-case edges at the minimum duration,
100/// upper-case edges at minus the maximum) gives [`Self::weight`], which is strictly negative.
101/// Morris (2006) showed that an STNU is dynamically controllable iff its labelled distance
102/// graph has no such cycle: the lower-case edges on it can be reduced away (the agent cannot
103/// exploit an early end it has not seen yet), which leaves a negative cycle of requirements
104/// and waits.
105///
106/// The cycle is a certificate in the sense of [`NegativeCycle`](crate::NegativeCycle): keeping
107/// only the requirement bounds it names (and all contingent links) still gives a network that
108/// is not dynamically controllable, which the tests check against independent checkers. It is
109/// not necessarily simple or minimal.
110#[derive(Debug, Clone, PartialEq, Eq, Hash)]
111pub struct SemiReducibleCycle {
112    /// Top-level steps in traversal order. Never empty.
113    steps: Vec<CycleStep>,
114    /// Derived edges referenced by the steps, each once, inner ones first.
115    derived: Vec<DerivedEdge>,
116    /// Total weight of the cycle. Always negative.
117    weight: Ticks,
118}
119
120impl SemiReducibleCycle {
121    /// Creates a cycle from its compact parts and total weight.
122    pub(crate) fn new(steps: Vec<CycleStep>, derived: Vec<DerivedEdge>, weight: Ticks) -> Self {
123        Self {
124            steps,
125            derived,
126            weight,
127        }
128    }
129
130    /// Top-level steps in traversal order.
131    #[must_use]
132    pub fn steps(&self) -> &[CycleStep] {
133        &self.steps
134    }
135
136    /// The derived edges [`CycleStep::Derived`] refers to.
137    #[must_use]
138    pub fn derived(&self) -> &[DerivedEdge] {
139        &self.derived
140    }
141
142    /// Total cycle weight; negative.
143    #[must_use]
144    pub fn weight(&self) -> Ticks {
145        self.weight
146    }
147
148    /// The original edges in traversal order, expanding derived edges lazily (memory
149    /// proportional to the nesting depth).
150    ///
151    /// The count can be exponential in the number of links; see [`Self::expanded_len`].
152    pub fn edges(&self) -> impl Iterator<Item = LabelledEdge> + '_ {
153        let mut stack = vec![self.steps.iter()];
154
155        core::iter::from_fn(move || {
156            loop {
157                let top = stack.last_mut()?;
158
159                match top.next() {
160                    None => {
161                        stack.pop();
162                    }
163                    Some(CycleStep::Edge(e)) => return Some(*e),
164                    Some(CycleStep::Derived(i)) => stack.push(self.derived[*i].steps.iter()),
165                }
166            }
167        })
168    }
169
170    /// Number of original edges [`Self::edges`] yields, or `None` if it exceeds `usize`.
171    #[must_use]
172    pub fn expanded_len(&self) -> Option<usize> {
173        let mut lens: Vec<usize> = Vec::with_capacity(self.derived.len());
174
175        for d in &self.derived {
176            let len = steps_len(&d.steps, &lens)?;
177            lens.push(len);
178        }
179
180        steps_len(&self.steps, &lens)
181    }
182
183    /// The distinct contingent links whose extreme durations the cycle relies on, ascending.
184    #[must_use]
185    pub fn contingent_links(&self) -> Vec<ContingentId> {
186        let all = self.derived.iter().flat_map(|d| d.steps.iter());
187        let mut links: Vec<ContingentId> = self
188            .steps
189            .iter()
190            .chain(all)
191            .filter_map(|s| match *s {
192                CycleStep::Edge(LabelledEdge::LowerCase(id) | LabelledEdge::UpperCase(id)) => {
193                    Some(id)
194                }
195                _ => None,
196            })
197            .collect();
198        links.sort_unstable();
199        links.dedup();
200        links
201    }
202}
203
204/// Expanded length of `steps`, given the expanded lengths of the derived edges before them.
205fn steps_len(steps: &[CycleStep], lens: &[usize]) -> Option<usize> {
206    steps.iter().try_fold(0usize, |acc, s| match *s {
207        CycleStep::Edge(_) => acc.checked_add(1),
208        CycleStep::Derived(i) => acc.checked_add(*lens.get(i)?),
209    })
210}