sas_plus/projection.rs
1//! Projections of a task onto a pattern of variables ([`Projection`]).
2
3use alloc::vec;
4use alloc::vec::Vec;
5
6use crate::ranking::Ranking;
7use crate::{
8 Abstraction, Fact, LabeledTransitionSystem, Operator, State, Task, Transition, Value, VarId,
9};
10
11/// Projection of a task onto a subset of variables (a "pattern"); the
12/// abstraction underlying pattern databases.
13///
14/// Derived variables are dropped from the pattern, so conditions on them are
15/// treated as satisfiable. A conditional effect whose conditions mention
16/// variables outside the pattern may or may not fire, and both outcomes get a
17/// transition. Both keep the abstraction admissible.
18///
19/// An operator gets one transition per abstract state matching its
20/// precondition, times the product, over the pattern variables it may set
21/// through such uncertain effects, of the number of values each may end with.
22/// That is never more than the number of abstract states, but on a large
23/// pattern the transition list can grow toward
24/// `operators × abstract states × abstract states`; size patterns accordingly.
25#[derive(Clone, Debug)]
26pub struct Projection {
27 /// The perfect hash of the pattern's assignments, i.e. the abstract states.
28 ranking: Ranking,
29 /// The abstract transition system, labeled by operator id.
30 lts: LabeledTransitionSystem,
31}
32
33impl Projection {
34 /// Projects `task` onto `pattern`. Derived variables and duplicates are
35 /// dropped from the pattern, which is then sorted.
36 ///
37 /// # Panics
38 ///
39 /// If `pattern` names a variable `task` does not have, or the abstract
40 /// state space has more than `usize::MAX` states.
41 #[must_use]
42 pub fn new(task: &Task, mut pattern: Vec<VarId>) -> Self {
43 pattern.retain(|&v| !task.variables[v].is_derived());
44 pattern.sort_unstable();
45 pattern.dedup();
46 let ranking = Ranking::new(task, pattern);
47
48 let mut builder = TransitionBuilder::new(&ranking);
49 for (label, op) in task.operators.iter().enumerate() {
50 builder.add_operator(label, op);
51 }
52
53 let transitions = builder.transitions;
54 let mut goal = vec![false; ranking.num_states];
55 ranking.matching(&task.goal).for_each(|s| goal[s] = true);
56 let lts = LabeledTransitionSystem {
57 num_states: ranking.num_states,
58 num_labels: task.operators.len(),
59 transitions,
60 goal,
61 initial: Some(ranking.rank(&task.initial)),
62 };
63
64 Self { ranking, lts }
65 }
66
67 /// The pattern: the projected state variables, sorted.
68 #[must_use]
69 pub fn pattern(&self) -> &[VarId] {
70 &self.ranking.vars
71 }
72
73 /// Index of the abstract state that `state` projects to.
74 ///
75 /// # Panics
76 ///
77 /// If `state` lacks a pattern variable.
78 #[must_use]
79 pub fn rank(&self, state: &State) -> usize {
80 self.ranking.rank(state)
81 }
82}
83
84impl Abstraction for Projection {
85 fn lts(&self) -> &LabeledTransitionSystem {
86 &self.lts
87 }
88
89 fn abstract_state(&self, state: &State) -> Option<usize> {
90 Some(self.rank(state))
91 }
92}
93
94/// An effect of an operator on a pattern variable.
95struct PatternEffect<'a> {
96 /// Position of the effect's variable in the pattern.
97 position: usize,
98 /// The value the effect sets.
99 value: Value,
100 /// The effect's conditions, inside and outside the pattern.
101 conditions: &'a [Fact],
102 /// Sure to fire when its pattern conditions hold, i.e. it has no
103 /// conditions outside the pattern.
104 sure: bool,
105}
106
107/// The effects of `op` on pattern variables, in effect order.
108fn pattern_effects<'a>(ranking: &Ranking, op: &'a Operator) -> Vec<PatternEffect<'a>> {
109 op.eff
110 .iter()
111 .filter_map(|e| {
112 let position = ranking.position(e.fact.var)?;
113 let sure = e
114 .conditions
115 .iter()
116 .all(|c| ranking.position(c.var).is_some());
117
118 Some(PatternEffect {
119 position,
120 value: e.fact.value,
121 conditions: e.conditions.as_slice(),
122 sure,
123 })
124 })
125 .collect()
126}
127
128/// Collects the abstract transitions of a projection, with scratch buffers
129/// reused across abstract states and operators.
130struct TransitionBuilder<'r> {
131 /// The abstract states.
132 ranking: &'r Ranking,
133 /// The transitions collected so far, in operator and source order.
134 transitions: Vec<Transition>,
135 /// Per pattern position, the values it may end with in the current
136 /// source state; non-empty only for positions in `touched`.
137 outcomes: Vec<Vec<Value>>,
138 /// The positions with outcomes in the current source state, in the order
139 /// their first effect appears.
140 touched: Vec<usize>,
141 /// Odometer over the outcomes of the touched positions.
142 digits: Vec<usize>,
143}
144
145impl<'r> TransitionBuilder<'r> {
146 /// An empty builder for the abstract states of `ranking`.
147 fn new(ranking: &'r Ranking) -> Self {
148 Self {
149 ranking,
150 transitions: Vec::new(),
151 outcomes: vec![Vec::new(); ranking.vars.len()],
152 touched: Vec::new(),
153 digits: Vec::new(),
154 }
155 }
156
157 /// Adds the transitions of operator `op` (with id `label`) from every
158 /// abstract state consistent with its precondition.
159 fn add_operator(&mut self, label: usize, op: &Operator) {
160 let ranking = self.ranking;
161 let effects = pattern_effects(ranking, op);
162 let unconditional = effects.iter().all(|e| e.conditions.is_empty());
163
164 for src in ranking.matching(&op.pre) {
165 if unconditional {
166 let dst = effects
167 .iter()
168 .fold(src, |d, e| ranking.set(d, e.position, e.value));
169 self.transitions.push(Transition { src, label, dst });
170 continue;
171 }
172
173 self.collect_outcomes(src, &effects);
174 self.push_combinations(src, label);
175 }
176 }
177
178 /// Fills `outcomes` and `touched` with the values each pattern variable
179 /// may end with when the operator is applied in `src`.
180 ///
181 /// Effects apply in order, so a variable ends with the value of its last
182 /// firing effect. A sure effect fixes that value; a maybe effect adds an
183 /// alternative.
184 fn collect_outcomes(&mut self, src: usize, effects: &[PatternEffect<'_>]) {
185 for &i in &self.touched {
186 self.outcomes[i].clear();
187 }
188
189 self.touched.clear();
190 for e in effects {
191 if !self.ranking.holds(src, e.conditions) {
192 continue;
193 }
194
195 let values = &mut self.outcomes[e.position];
196 if values.is_empty() {
197 self.touched.push(e.position);
198 values.push(self.ranking.value(src, e.position));
199 }
200
201 if e.sure {
202 values.clear();
203 values.push(e.value);
204 } else if !values.contains(&e.value) {
205 values.push(e.value);
206 }
207 }
208 }
209
210 /// Pushes one transition from `src` per combination of the collected
211 /// outcomes. Each effect sets one variable, so the variables are
212 /// independent and the successors are all combinations.
213 fn push_combinations(&mut self, src: usize, label: usize) {
214 self.digits.clear();
215 self.digits.resize(self.touched.len(), 0);
216 loop {
217 let dst = self
218 .touched
219 .iter()
220 .zip(&self.digits)
221 .fold(src, |d, (&i, &k)| {
222 self.ranking.set(d, i, self.outcomes[i][k])
223 });
224 self.transitions.push(Transition { src, label, dst });
225
226 let Some(j) = (0..self.touched.len())
227 .find(|&j| self.digits[j] + 1 < self.outcomes[self.touched[j]].len())
228 else {
229 break;
230 };
231 self.digits[j] += 1;
232 self.digits[..j].fill(0);
233 }
234 }
235}