sas_plus/lts.rs
1//! Explicit labeled transition systems and their goal distances.
2
3use alloc::collections::BinaryHeap;
4use alloc::vec;
5use alloc::vec::Vec;
6use core::cmp::Reverse;
7
8/// A transition `src --label--> dst` of a [`LabeledTransitionSystem`].
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11pub struct Transition {
12 /// The source state, in `0..num_states`.
13 pub src: usize,
14 /// The label, in `0..num_labels`; for abstractions of a task, the
15 /// operator id.
16 pub label: usize,
17 /// The destination state, in `0..num_states`.
18 pub dst: usize,
19}
20
21/// An explicit labeled transition system. Self-loops are kept: they matter
22/// for synchronized products (merge-and-shrink), and are ignored where they
23/// are irrelevant (distances, saturated costs).
24#[derive(Clone, Debug, PartialEq, Eq)]
25#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
26pub struct LabeledTransitionSystem {
27 /// The number of states; states are `0..num_states`.
28 pub num_states: usize,
29 /// The number of labels; labels are `0..num_labels`.
30 pub num_labels: usize,
31 /// The transitions, in no particular order unless [`normalize`d](Self::normalize).
32 pub transitions: Vec<Transition>,
33 /// Whether each state is a goal state; `num_states` entries.
34 pub goal: Vec<bool>,
35 /// The initial state, if there is one.
36 pub initial: Option<usize>,
37}
38
39impl LabeledTransitionSystem {
40 /// Cheapest cost to reach a goal state from each state, under `costs`
41 /// (indexed by label). `None` = no goal reachable. Sums saturate at
42 /// `u64::MAX`.
43 ///
44 /// # Panics
45 ///
46 /// If `costs` does not have one entry per label, or a transition or goal
47 /// flag refers to a state outside `0..num_states`.
48 #[must_use]
49 pub fn goal_distances(&self, costs: &[u64]) -> Vec<Option<u64>> {
50 dijkstra(
51 &self.adjacency(costs, true),
52 self.goal.iter().enumerate().filter(|g| *g.1).map(|g| g.0),
53 )
54 }
55
56 /// Cheapest cost from the initial state to each state; all `None`
57 /// without an initial state.
58 ///
59 /// # Panics
60 ///
61 /// If `costs` does not have one entry per label, or a transition or the
62 /// initial state refers to a state outside `0..num_states`.
63 #[must_use]
64 pub fn init_distances(&self, costs: &[u64]) -> Vec<Option<u64>> {
65 dijkstra(&self.adjacency(costs, false), self.initial)
66 }
67
68 /// Weighted edges per state, without self-loops; `reverse` follows
69 /// transitions backwards.
70 fn adjacency(&self, costs: &[u64], reverse: bool) -> Vec<Vec<(usize, u64)>> {
71 assert_eq!(costs.len(), self.num_labels, "one cost per label");
72 let mut adj = vec![Vec::new(); self.num_states];
73 for t in self.transitions.iter().filter(|t| t.src != t.dst) {
74 let (from, to) = if reverse {
75 (t.dst, t.src)
76 } else {
77 (t.src, t.dst)
78 };
79 adj[from].push((to, costs[t.label]));
80 }
81
82 adj
83 }
84
85 /// Sorts transitions and removes duplicates.
86 pub fn normalize(&mut self) {
87 self.transitions.sort_unstable();
88 self.transitions.dedup();
89 }
90}
91
92/// Multi-source Dijkstra: the cheapest distance from the nearest of
93/// `sources` to each node of the weighted adjacency list `adj`.
94fn dijkstra(
95 adj: &[Vec<(usize, u64)>],
96 sources: impl IntoIterator<Item = usize>,
97) -> Vec<Option<u64>> {
98 let mut dist = vec![None; adj.len()];
99 let mut heap = BinaryHeap::new();
100 for s in sources {
101 dist[s] = Some(0);
102 heap.push(Reverse((0u64, s)));
103 }
104
105 while let Some(Reverse((d, s))) = heap.pop() {
106 if dist[s].is_some_and(|best| d > best) {
107 continue;
108 }
109 for &(t, c) in &adj[s] {
110 // Saturate, so an "infinite" cost of u64::MAX cannot wrap to a short path.
111 let candidate = d.saturating_add(c);
112 if dist[t].is_none_or(|old| candidate < old) {
113 dist[t] = Some(candidate);
114 heap.push(Reverse((candidate, t)));
115 }
116 }
117 }
118
119 dist
120}