sas_plus/causal_graph.rs
1//! The causal graph of a task ([`CausalGraph`]).
2
3use alloc::vec;
4use alloc::vec::Vec;
5
6use crate::{Task, VarId};
7
8/// The causal graph of a task: an arc `u → v` means that changing `v` may
9/// depend on `u`, or that `u` and `v` change together.
10///
11/// As in Fast Downward, arcs run from every precondition and effect condition
12/// variable of an operator to each variable it sets, between every two
13/// variables one operator sets, and from every condition of an axiom to the
14/// variable it derives. Self-loops are left out.
15#[derive(Clone, Debug, PartialEq, Eq)]
16#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
17pub struct CausalGraph {
18 /// Per variable, the variables it has an arc to; sorted, no duplicates.
19 successors: Vec<Vec<VarId>>,
20 /// Per variable, the variables with an arc to it; sorted, no duplicates.
21 predecessors: Vec<Vec<VarId>>,
22}
23
24impl CausalGraph {
25 /// Builds the causal graph of `task`.
26 ///
27 /// # Panics
28 ///
29 /// If a fact of `task` names a variable it does not have; a task that
30 /// passes [`Task::validate`] never does.
31 #[must_use]
32 pub fn new(task: &Task) -> Self {
33 let mut arcs = Vec::new();
34 for op in &task.operators {
35 for e in &op.eff {
36 let v = e.fact.var;
37 arcs.extend(op.pre.iter().map(|f| (f.var, v)));
38 arcs.extend(e.conditions.iter().map(|f| (f.var, v)));
39 arcs.extend(op.eff.iter().map(|other| (other.fact.var, v)));
40 }
41 }
42
43 for a in &task.axioms {
44 arcs.extend(a.conditions.iter().map(|f| (f.var, a.head.var)));
45 }
46 arcs.retain(|(u, v)| u != v);
47 arcs.sort_unstable();
48 arcs.dedup();
49
50 let n = task.num_variables();
51 let mut successors = vec![Vec::new(); n];
52 let mut predecessors = vec![Vec::new(); n];
53 for &(u, v) in &arcs {
54 successors[u].push(v);
55 predecessors[v].push(u);
56 }
57
58 Self {
59 successors,
60 predecessors,
61 }
62 }
63
64 /// Variables with an arc from `var`, sorted.
65 ///
66 /// # Panics
67 ///
68 /// If `var` is not a variable of the task.
69 #[must_use]
70 pub fn successors(&self, var: VarId) -> &[VarId] {
71 &self.successors[var]
72 }
73
74 /// Variables with an arc to `var`, sorted.
75 ///
76 /// # Panics
77 ///
78 /// If `var` is not a variable of the task.
79 #[must_use]
80 pub fn predecessors(&self, var: VarId) -> &[VarId] {
81 &self.predecessors[var]
82 }
83}