Skip to main content

temporal_control/stn/
p3c.rs

1//! Partial path consistency with P³C (Planken, de Weerdt and van der Krogt, ICAPS 2008).
2//!
3//! The *constraint graph* has an undirected edge per pair of time points that share a
4//! constraint. P³C makes it chordal and labels every edge of the chordal graph with its
5//! minimal constraint, the same bounds the [`MinimalNetwork`](super::MinimalNetwork) has for
6//! that pair, without computing the other pairs. On sparse networks the chordal graph has far
7//! fewer than `n^2` edges.
8//!
9//! # Algorithm
10//!
11//! 1. **Triangulation and DPC (one pass).** Time points are eliminated one by one, always one
12//!    with the fewest remaining neighbours (the minimum-degree heuristic the paper cites from
13//!    Kjærulff; lowest index on ties). Eliminating `k` connects its remaining neighbours
14//!    pairwise (fill edges) and tightens each pair `i, j` of them to
15//!    `w(i, j) = min(w(i, j), w(i, k) + w(k, j))`. This is directional path consistency (DPC)
16//!    of Dechter, Meiri and Pearl (1991, Fig. 9) along the elimination order, whose induced
17//!    graph is the triangulation; P³C's Algorithm 3 runs DPC on a graph that is already chordal
18//!    along a simplicial order, which the elimination order is for the filled graph.
19//! 2. **Consistency.** When `k` is eliminated, each pair `i, k` with a remaining neighbour `i`
20//!    has received every DPC tightening it will get; if `w(i, k) + w(k, i) < 0` the network is
21//!    inconsistent. Every pair is checked once, when its first endpoint is eliminated. DMP's
22//!    DPC checks the pair it just tightened, and its Theorem 5.11 (DPC detects every
23//!    inconsistency) assumes non-empty input intervals; checking every pair also catches
24//!    `lo > hi` and conflicting parallel constraints. Negative self-loops are rejected first.
25//! 3. **Backward sweep.** In reverse elimination order, every `k` and every ordered pair `i, j`
26//!    of the neighbours that remained when `k` was eliminated: `w(i, k) = min(w(i, k),
27//!    w(i, j) + w(j, k))` and `w(k, j) = min(w(k, j), w(k, i) + w(i, j))` (Algorithm 3, lines
28//!    3-8). By the paper's Theorem 3 every edge then carries its shortest-path distance.
29//!
30//! To get the minimal constraint of a pair that shares no constraint, add one without bounds
31//! (`Stn::add_constraint(a, b, None, None)`): it adds the pair to the constraint graph but no
32//! distance-graph edge, which is how the paper suggests making "all information of interest"
33//! available.
34//!
35//! # Cost
36//!
37//! The paper's `Θ(t)` for `t` triangles of the chordal graph (`O(n w*^2)` for induced width
38//! `w*`) assumes constant-time edge lookups. Here every edge weight lives in an ordered map per
39//! node, and the elimination queue is an ordered set, so the cost is
40//! `O((n + m + t) log n)` steps for `m` constraints, with `O(n + m + f)` memory for `f` fill
41//! edges. A *step* is one triangle visit (one per sweep) or one constraint or node handled;
42//! [`Budget::max_cells`] bounds the number of directed edges of the chordal graph (two per
43//! undirected edge). The map nodes are allocated infallibly, like the other `O(n + m)`
44//! structures (design section 6).
45
46use alloc::collections::{BTreeMap, BTreeSet};
47use alloc::vec;
48use alloc::vec::Vec;
49
50use super::{Stn, TimePoint, steps};
51use crate::budget::Meter;
52use crate::{Budget, Error, Ticks};
53
54/// The minimal constraints of a consistent STN on the edges of a chordal supergraph of its
55/// constraint graph, as computed by [`Stn::partial_path_consistency`].
56///
57/// For every pair in the graph ([`Self::contains`]), [`Self::upper`] and [`Self::lower`] equal
58/// the bounds of the [`MinimalNetwork`](super::MinimalNetwork); other pairs are not computed.
59/// The graph holds every constrained pair (bounded or not) plus the fill edges of the
60/// triangulation.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct ChordalNetwork {
63    /// Number of time points.
64    n: usize,
65    /// `adj[i][j]` is the tightest upper bound on `t_j - t_i`, `None` if unbounded. An entry
66    /// `(i, j)` exists iff `(j, i)` does. No weight is `i64::MIN`, so every weight negates.
67    adj: Vec<BTreeMap<usize, Option<Ticks>>>,
68}
69
70impl ChordalNetwork {
71    /// Number of time points.
72    #[must_use]
73    pub fn time_point_count(&self) -> usize {
74        self.n
75    }
76
77    /// Whether the minimal constraint between `a` and `b` was computed: `a == b`, or the pair
78    /// is an edge of the chordal graph. False for unknown handles.
79    #[must_use]
80    pub fn contains(&self, a: TimePoint, b: TimePoint) -> bool {
81        a.0 < self.n && b.0 < self.n && (a == b || self.adj[a.0].contains_key(&b.0))
82    }
83
84    /// Tightest upper bound on `t_to - t_from`; `None` if unbounded, or if the pair is not in
85    /// the graph (see [`Self::contains`]) or a handle is unknown.
86    #[must_use]
87    pub fn upper(&self, from: TimePoint, to: TimePoint) -> Option<Ticks> {
88        if from.0 >= self.n || to.0 >= self.n {
89            return None;
90        }
91
92        if from == to {
93            return Some(Ticks::ZERO);
94        }
95
96        self.adj[from.0].get(&to.0).copied().flatten()
97    }
98
99    /// Tightest lower bound on `t_to - t_from`; `None` as for [`Self::upper`].
100    #[must_use]
101    pub fn lower(&self, from: TimePoint, to: TimePoint) -> Option<Ticks> {
102        self.upper(to, from).and_then(Ticks::checked_neg)
103    }
104
105    /// The edges of the chordal graph, each once as `(a, b)` with `a < b`, ascending.
106    pub fn pairs(&self) -> impl Iterator<Item = (TimePoint, TimePoint)> + '_ {
107        self.adj.iter().enumerate().flat_map(|(a, row)| {
108            row.keys()
109                .filter(move |&&b| a < b)
110                .map(move |&b| (TimePoint(a), TimePoint(b)))
111        })
112    }
113}
114
115/// Runs P³C; `None` if the network is inconsistent.
116///
117/// # Errors
118///
119/// [`Error::MemoryBudgetExceeded`], [`Error::BudgetExhausted`], or [`Error::Overflow`] if an
120/// intermediate path length overflows `i64` (on an inconsistent network this can happen before
121/// the inconsistency is seen; the caller then lets Bellman-Ford decide).
122pub(super) fn run(
123    stn: &Stn,
124    budget: &Budget,
125    meter: &mut Meter,
126) -> Result<Option<ChordalNetwork>, Error> {
127    let Some(mut graph) = Graph::new(stn, budget, meter)? else {
128        return Ok(None);
129    };
130
131    let Some(order) = graph.eliminate(meter)? else {
132        return Ok(None);
133    };
134
135    graph.backward_sweep(&order, meter)?;
136    graph.finish().map(Some)
137}
138
139/// The chordal graph being built, with its edge weights.
140struct Graph<'b> {
141    /// As [`ChordalNetwork::adj`], growing with fill edges.
142    adj: Vec<BTreeMap<usize, Option<Ticks>>>,
143    /// Directed edges so far, checked against the budget's cells.
144    cells: usize,
145    /// The budget, for the cell limit.
146    budget: &'b Budget,
147}
148
149/// One eliminated time point and the neighbours it still had: they form a clique.
150struct Eliminated {
151    /// The time point.
152    point: usize,
153    /// Its neighbours not eliminated before it.
154    later: Vec<usize>,
155}
156
157impl<'b> Graph<'b> {
158    /// The constraint graph of `stn` with the tightest bound per pair; `None` if a self-loop
159    /// is negative.
160    ///
161    /// # Errors
162    ///
163    /// [`Error::MemoryBudgetExceeded`] or [`Error::BudgetExhausted`].
164    fn new(stn: &Stn, budget: &'b Budget, meter: &mut Meter) -> Result<Option<Self>, Error> {
165        meter.spend(steps(stn.constraints.len())?.saturating_add(steps(stn.edges.len())?))?;
166        let mut graph = Self {
167            adj: vec![BTreeMap::new(); stn.time_points],
168            cells: 0,
169            budget,
170        };
171
172        for c in &stn.constraints {
173            if c.from != c.to {
174                graph.link(c.from.0, c.to.0)?;
175            }
176        }
177
178        for e in &stn.edges {
179            if e.from != e.to {
180                graph.tighten(e.from, e.to, e.weight);
181            } else if e.weight < Ticks::ZERO {
182                return Ok(None);
183            }
184        }
185
186        Ok(Some(graph))
187    }
188
189    /// Adds the undirected edge `{i, j}` with unbounded weights if it is new; returns whether
190    /// it was.
191    ///
192    /// # Errors
193    ///
194    /// [`Error::MemoryBudgetExceeded`] if the graph outgrows [`Budget::max_cells`].
195    fn link(&mut self, i: usize, j: usize) -> Result<bool, Error> {
196        if self.adj[i].contains_key(&j) {
197            return Ok(false);
198        }
199
200        self.cells = self
201            .cells
202            .checked_add(2)
203            .ok_or(Error::MemoryBudgetExceeded)?;
204        self.budget.check_cells(self.cells)?;
205        self.adj[i].insert(j, None);
206        self.adj[j].insert(i, None);
207        Ok(true)
208    }
209
210    /// The weight of the existing edge `i -> j`; `None` if unbounded.
211    fn weight(&self, i: usize, j: usize) -> Option<Ticks> {
212        self.adj[i].get(&j).copied().flatten()
213    }
214
215    /// Lowers the weight of the existing edge `i -> j` to `w` if that is tighter.
216    fn tighten(&mut self, i: usize, j: usize, w: Ticks) {
217        if let Some(cell) = self.adj[i].get_mut(&j) {
218            if cell.is_none_or(|old| w < old) {
219                *cell = Some(w);
220            }
221        }
222    }
223
224    /// Lowers `i -> j` to the length of `i -> k -> j` if both edges are bounded and that is
225    /// tighter.
226    ///
227    /// # Errors
228    ///
229    /// [`Error::Overflow`] if the path length overflows.
230    fn relax(&mut self, i: usize, k: usize, j: usize) -> Result<(), Error> {
231        if let (Some(a), Some(b)) = (self.weight(i, k), self.weight(k, j)) {
232            self.tighten(i, j, a.checked_add(b).ok_or(Error::Overflow)?);
233        }
234
235        Ok(())
236    }
237
238    /// Triangulates by minimum-degree elimination while enforcing DPC along the elimination
239    /// order. Returns the eliminated points in order, or `None` if the network is
240    /// inconsistent.
241    ///
242    /// # Errors
243    ///
244    /// [`Error::MemoryBudgetExceeded`], [`Error::BudgetExhausted`] or [`Error::Overflow`].
245    fn eliminate(&mut self, meter: &mut Meter) -> Result<Option<Vec<Eliminated>>, Error> {
246        let n = self.adj.len();
247        let mut degree: Vec<usize> = self.adj.iter().map(BTreeMap::len).collect();
248        let mut queue: BTreeSet<(usize, usize)> = degree.iter().copied().zip(0..n).collect();
249        let mut done = vec![false; n];
250        let mut order = Vec::with_capacity(n);
251
252        while let Some((_, k)) = queue.pop_first() {
253            meter.spend(1)?;
254            done[k] = true;
255            let later: Vec<usize> = self.adj[k].keys().copied().filter(|&i| !done[i]).collect();
256
257            for &i in &later {
258                requeue(&mut queue, &mut degree, i, |d| d - 1);
259            }
260
261            if !self.eliminate_one(k, &later, &mut queue, &mut degree, meter)? {
262                return Ok(None);
263            }
264
265            order.push(Eliminated { point: k, later });
266        }
267
268        Ok(Some(order))
269    }
270
271    /// Eliminates `k` with remaining neighbours `later`: checks each pair `i, k`, then fills
272    /// and tightens every pair of `later`. Returns false if the network is inconsistent.
273    ///
274    /// # Errors
275    ///
276    /// [`Error::MemoryBudgetExceeded`], [`Error::BudgetExhausted`] or [`Error::Overflow`].
277    fn eliminate_one(
278        &mut self,
279        k: usize,
280        later: &[usize],
281        queue: &mut BTreeSet<(usize, usize)>,
282        degree: &mut [usize],
283        meter: &mut Meter,
284    ) -> Result<bool, Error> {
285        if later.iter().any(|&i| self.is_negative_pair(i, k)) {
286            return Ok(false);
287        }
288
289        for &i in later {
290            meter.spend(steps(later.len())?)?;
291
292            for &j in later.iter().filter(|&&j| j != i) {
293                if self.link(i, j)? {
294                    requeue(queue, degree, i, |d| d + 1);
295                    requeue(queue, degree, j, |d| d + 1);
296                }
297
298                self.relax(i, k, j)?;
299            }
300        }
301
302        Ok(true)
303    }
304
305    /// Whether `w(i, k) + w(k, i) < 0`, an inconsistent pair.
306    fn is_negative_pair(&self, i: usize, k: usize) -> bool {
307        match (self.weight(i, k), self.weight(k, i)) {
308            (Some(a), Some(b)) => i128::from(a.0) + i128::from(b.0) < 0,
309            _ => false,
310        }
311    }
312
313    /// The backward sweep of P³C (Algorithm 3, lines 3-8), in reverse elimination order.
314    ///
315    /// # Errors
316    ///
317    /// [`Error::BudgetExhausted`] or [`Error::Overflow`].
318    fn backward_sweep(&mut self, order: &[Eliminated], meter: &mut Meter) -> Result<(), Error> {
319        for Eliminated { point: k, later } in order.iter().rev() {
320            for &i in later {
321                meter.spend(steps(later.len())?)?;
322
323                for &j in later.iter().filter(|&&j| j != i) {
324                    self.relax(i, j, *k)?;
325                    self.relax(*k, i, j)?;
326                }
327            }
328        }
329
330        Ok(())
331    }
332
333    /// The finished network.
334    ///
335    /// # Errors
336    ///
337    /// [`Error::Overflow`] if a weight is `i64::MIN`, whose negation is not representable.
338    fn finish(self) -> Result<ChordalNetwork, Error> {
339        let rows = self.adj.iter().flat_map(BTreeMap::values);
340
341        if rows.flatten().any(|w| w.0 == i64::MIN) {
342            return Err(Error::Overflow);
343        }
344
345        Ok(ChordalNetwork {
346            n: self.adj.len(),
347            adj: self.adj,
348        })
349    }
350}
351
352/// Moves `v` in the elimination queue after changing its degree with `change`.
353fn requeue(
354    queue: &mut BTreeSet<(usize, usize)>,
355    degree: &mut [usize],
356    v: usize,
357    change: impl FnOnce(usize) -> usize,
358) {
359    if queue.remove(&(degree[v], v)) {
360        degree[v] = change(degree[v]);
361        queue.insert((degree[v], v));
362    }
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368    use crate::Verdict;
369
370    /// An STN with `n` points and the given `(from, to, lo, hi)` constraints.
371    fn stn(n: usize, constraints: &[(usize, usize, Option<i64>, Option<i64>)]) -> Stn {
372        let mut stn = Stn::new();
373
374        for _ in 0..n {
375            stn.add_time_point().unwrap();
376        }
377
378        for &(from, to, lo, hi) in constraints {
379            let (lo, hi) = (lo.map(Ticks), hi.map(Ticks));
380            stn.add_constraint(TimePoint(from), TimePoint(to), lo, hi)
381                .unwrap();
382        }
383
384        stn
385    }
386
387    /// The chordal network of `stn`; panics if inconsistent.
388    fn ppc(stn: &Stn) -> ChordalNetwork {
389        match stn.partial_path_consistency(&Budget::UNLIMITED).unwrap() {
390            Verdict::Consistent(net) => net,
391            Verdict::Inconsistent(_) => panic!("expected consistent"),
392        }
393    }
394
395    /// Whether `stn` is inconsistent according to P³C.
396    fn inconsistent(stn: &Stn) -> bool {
397        let verdict = stn.partial_path_consistency(&Budget::UNLIMITED).unwrap();
398        matches!(verdict, Verdict::Inconsistent(_))
399    }
400
401    /// A pair of interest without bounds gets the implied interval of a chain.
402    #[test]
403    fn unbounded_pair_of_interest_is_computed() {
404        let net = ppc(&stn(
405            3,
406            &[
407                (0, 1, Some(2), Some(5)),
408                (1, 2, Some(2), Some(5)),
409                (0, 2, None, None),
410            ],
411        ));
412
413        assert_eq!(net.upper(TimePoint(0), TimePoint(2)), Some(Ticks(10)));
414        assert_eq!(net.lower(TimePoint(0), TimePoint(2)), Some(Ticks(4)));
415    }
416
417    /// A 4-cycle is not chordal: it gets one fill edge, and every edge, the fill edge
418    /// included, carries the minimal constraint.
419    #[test]
420    fn four_cycle_gets_a_minimal_fill_edge() {
421        // 0 -> 1 -> 2 -> 3 each [1, 2] and 0 -> 3 in [0, 4], which tightens to [3, 4].
422        let stn = stn(
423            4,
424            &[
425                (0, 1, Some(1), Some(2)),
426                (1, 2, Some(1), Some(2)),
427                (2, 3, Some(1), Some(2)),
428                (0, 3, Some(0), Some(4)),
429            ],
430        );
431        let net = ppc(&stn);
432        let Verdict::Consistent(min) = stn.minimal_network(&Budget::UNLIMITED).unwrap() else {
433            panic!("consistent");
434        };
435
436        assert_eq!(net.pairs().count(), 5);
437
438        for (a, b) in net.pairs() {
439            assert_eq!(net.upper(a, b), min.upper(a, b), "{a:?} -> {b:?}");
440            assert_eq!(net.upper(b, a), min.upper(b, a), "{b:?} -> {a:?}");
441        }
442
443        assert_eq!(net.lower(TimePoint(0), TimePoint(3)), Some(Ticks(3)));
444        assert_eq!(net.upper(TimePoint(1), TimePoint(2)), Some(Ticks(2)));
445    }
446
447    /// Contradictions on a single pair, which DPC's triangle updates never touch.
448    #[test]
449    fn single_pair_contradictions_are_found() {
450        assert!(inconsistent(&stn(2, &[(0, 1, Some(5), Some(3))])));
451        assert!(inconsistent(&stn(
452            2,
453            &[(0, 1, Some(5), None), (0, 1, None, Some(3))]
454        )));
455        assert!(inconsistent(&stn(1, &[(0, 0, Some(1), None)])));
456        assert!(!inconsistent(&stn(1, &[(0, 0, Some(0), Some(0))])));
457    }
458
459    /// A negative cycle over three points is found by the DPC pass.
460    #[test]
461    fn triangle_negative_cycle_is_found() {
462        let stn = stn(
463            3,
464            &[
465                (0, 1, Some(2), None),
466                (1, 2, Some(2), None),
467                (0, 2, None, Some(3)),
468            ],
469        );
470        assert!(inconsistent(&stn));
471    }
472
473    /// The pathological instances `P_t` of the paper (Definition 2), on which `ΔSTP` processes
474    /// `Ω(t^2)` triangles: a zero-weight cycle filled with chords whose weights make longer
475    /// paths shorter. Every minimal weight is zero.
476    #[test]
477    fn pathological_instances_have_zero_minimal_weights() {
478        for t in 1..=8usize {
479            let mut constraints = Vec::new();
480            let w = |x: usize| Some(i64::try_from(x).unwrap());
481
482            for i in 0..t + 2 {
483                constraints.push((i, (i + 1) % (t + 2), None, Some(0)));
484            }
485
486            for i in 1..=t {
487                for j in i + 2..=t + 1 {
488                    if matches!((i + j).checked_sub(t), Some(1 | 2)) {
489                        constraints.push((i, j, None, w(j - i - 1)));
490                        constraints.push((j, i, None, w(t - (j - i - 1))));
491                    }
492                }
493            }
494
495            let net = ppc(&stn(t + 2, &constraints));
496
497            for (a, b) in net.pairs() {
498                assert_eq!(
499                    net.upper(a, b),
500                    Some(Ticks::ZERO),
501                    "t = {t}, {a:?} -> {b:?}"
502                );
503                assert_eq!(
504                    net.upper(b, a),
505                    Some(Ticks::ZERO),
506                    "t = {t}, {b:?} -> {a:?}"
507                );
508            }
509        }
510    }
511
512    /// The cell budget bounds the chordal graph, fill edges included.
513    #[test]
514    fn cell_budget_is_enforced() {
515        let stn = stn(
516            4,
517            &[
518                (0, 1, None, Some(1)),
519                (1, 2, None, Some(1)),
520                (2, 3, None, Some(1)),
521                (3, 0, None, Some(1)),
522            ],
523        );
524        let tight = Budget {
525            max_steps: u64::MAX,
526            max_cells: 8,
527        };
528        let enough = Budget {
529            max_steps: u64::MAX,
530            max_cells: 10,
531        };
532
533        assert_eq!(
534            stn.partial_path_consistency(&tight),
535            Err(Error::MemoryBudgetExceeded)
536        );
537        assert!(stn.partial_path_consistency(&enough).is_ok());
538    }
539}