Algorithm Search⌘K

Algorithmadvanced

Regression in the situation calculus

Also called Reiter's regression operator.

Rewrites a query about the situation after a sequence of actions into an equivalent query about the initial situation, using successor state axioms.

Time
O(2^k (q + n m)) entail_brute_forceO(n p + n^2 m) executable_expectedO(n q + n^2 m) regress_expected
Space
O(q + n m) regressed_formula
Where
k = the number of fluents; m = the largest total size of the successor state formulas of one action; n = the number of actions in the sequence; p = the number of nodes of the largest precondition; q = the number of nodes of the query
Properties
deterministicexactnot needs complete initial database
Origin
Raymond Reiter, 1991

Regression is Reiter's method for the projection problem of the situation calculus: to decide whether a formula holds in the situation do([α1,…,αn],S0)\mathit{do}([\alpha_1, \ldots, \alpha_n], S_0), it replaces each fluent by the right side of its successor state axiom, one action at a time from the last to the first, until the formula speaks only about S0S_0. Then a theorem prover checks the result against the initial database alone, with no axioms about actions or situations. Goal regression does the same for a set of STRIPS facts and one action; this page treats arbitrary formulas and whole action sequences, and gives the regression theorem that makes the method complete. The code on this page handles a ground, finite, propositional fragment with no sensing actions, while the regression theorem of Pirri and Reiter (1999) is first order.

In plain words

You know some things about the world now, and you plan to do a list of actions. You want to know whether some fact will be true at the end. One way is to run the actions forward in your head from every world you think possible. Regression goes the other way. Take the question about the end and ask: what must be true one step before, so that the last action makes the fact true? Each action has a rule that says exactly when it makes a fact true and when it leaves it alone, so that question has an exact answer. Repeat this for each action, back to the start. Now the question is about the present only, and you can check it against what you know now. The rules are used, but never the full history of possible worlds.

The problem

A basic action theory (Reiter 2001, Section 4.4) is D=Σ∪Dss∪Dap∪Duna∪DS0\mathcal{D} = \Sigma \cup \mathcal{D}_{ss} \cup \mathcal{D}_{ap} \cup \mathcal{D}_{una} \cup \mathcal{D}_{S_0}: the foundational axioms Σ\Sigma for situations, one successor state axiom for each fluent,

F(x⃗,do(a,s))↔ΦF(x⃗,a,s),F(\vec x, \mathit{do}(a, s)) \leftrightarrow \Phi_F(\vec x, a, s),

one precondition axiom Poss(A(x⃗),s)↔ΠA(x⃗,s)\mathit{Poss}(A(\vec x), s) \leftrightarrow \Pi_A(\vec x, s) for each action function AA, unique names axioms for actions, and the initial database DS0\mathcal{D}_{S_0}, a set of first-order sentences about S0S_0 only. A formula WW is regressable when every situation term in it has the form do([α1,…,αn],S0)\mathit{do}([\alpha_1, \ldots, \alpha_n], S_0), every Poss\mathit{Poss} atom has an action term of the form A(t⃗)A(\vec t), and it does not quantify over situations, compare situations with ⊏\sqsubset or equate two situations.

  • Projection. Given D\mathcal{D} and a regressable sentence WW, decide D⊨W\mathcal{D} \models W.
  • Executability. Given ground actions α1,…,αn\alpha_1, \ldots, \alpha_n, decide whether D⊨⋀i=1nPoss(αi,do([α1,…,αi−1],S0))\mathcal{D} \models \bigwedge_{i=1}^{n} \mathit{Poss}(\alpha_i, \mathit{do}([\alpha_1, \ldots, \alpha_{i-1}], S_0)).

The regression operator R\mathcal{R} is defined on regressable formulas by: R[W]=W\mathcal{R}[W] = W if WW mentions no situation term other than S0S_0; R[Poss(A(t⃗),σ)]=R[ΠA(t⃗,σ)]\mathcal{R}[\mathit{Poss}(A(\vec t), \sigma)] = \mathcal{R}[\Pi_A(\vec t, \sigma)]; R[F(t⃗,do(α,σ))]=R[ΦF(t⃗,α,σ)]\mathcal{R}[F(\vec t, \mathit{do}(\alpha, \sigma))] = \mathcal{R}[\Phi_F(\vec t, \alpha, \sigma)] after a renaming of the bound variables of ΦF\Phi_F; and R\mathcal{R} commutes with ¬\neg, ∧\wedge and ∃\exists. Each rewrite of a fluent removes one do\mathit{do} from its situation term, so the recursion stops.

Regression theorem (Pirri and Reiter 1999; Reiter 2001, Section 4.5). If WW is regressable, then R[W]\mathcal{R}[W] is a formula about S0S_0 only, and

D⊨W  ⟺  DS0∪Duna⊨R[W].\mathcal{D} \models W \iff \mathcal{D}_{S_0} \cup \mathcal{D}_{una} \models \mathcal{R}[W].

The foundational axioms, the successor state axioms and the precondition axioms are used up by the rewriting; the final test is an ordinary first-order entailment.

The fragment of the code. Fluents are ground atoms with no object arguments, the actions are a finite set of ground names, and no action senses. A state is then a truth assignment to the kk fluents. For each action aa and fluent FF the successor state axiom is F(do(a,s))↔γF,a+(s)∨(F(s)∧¬γF,a−(s))F(\mathit{do}(a, s)) \leftrightarrow \gamma^+_{F,a}(s) \vee (F(s) \wedge \neg \gamma^-_{F,a}(s)), where γF,a±\gamma^\pm_{F,a} are propositional formulas over the fluents, and ΦF,a\Phi_{F,a} is its right side. The unique names axioms are built into the action names, and DS0\mathcal{D}_{S_0} is a set of propositional formulas, which may leave fluents unknown.

The algorithm

Formulas are nodes of a hash-consed DAG: MAKE returns the existing node for a formula that is already built, and folds the constants true and false.

  1. REGRESS(φ, [a_1, ..., a_n]) ▷ φ is about do([a_1, ..., a_n], S0)
  2. 1for i ← n down to 1 do
  3. 2M ← an empty memo table
  4. 3φ ← STEP(φ, a_i, M) ▷ now φ is about do([a_1, ..., a_{i-1}], S0)
  5. 4return φ ▷ a formula about S0
  6. STEP(u, a, M) ▷ the formula u with each fluent F replaced by Φ_{F,a}
  7. 5if u is in M then return M[u]
  8. 6if u is true or false then r ← u
  9. 7else if u is a fluent F then r ← Φ_{F,a}
  10. 8else if u = ¬v then r ← MAKE(¬, STEP(v, a, M))
  11. 9else u = v ∘ w with ∘ in {∧, ∨}: r ← MAKE(∘, STEP(v, a, M), STEP(w, a, M))
  12. 10M[u] ← r; return r
  13. EXECUTABLE-FORMULA([a_1, ..., a_n])
  14. 11χ ← true
  15. 12for i ← n down to 1 do
  16. 13χ ← MAKE(∧, Π_{a_i}, STEP(χ, a_i, an empty memo table))
  17. 14return χ
  18. PROJECT(D, φ, [a_1, ..., a_n])
  19. 15return ENTAILS(D_S0, REGRESS(φ, [a_1, ..., a_n]))

ENTAILS(DS0,ψ)(\mathcal{D}_{S_0}, \psi) decides DS0⊨ψ\mathcal{D}_{S_0} \models \psi. The code tries all 2k2^k states; a real system gives DS0∧¬ψ\mathcal{D}_{S_0} \wedge \neg \psi to a SAT solver after the Tseitin transformation of the DAG. Line L13 keeps the invariant that χ\chi, after the step for aia_i, is about do([a1,…,ai−1],S0)\mathit{do}([a_1, \ldots, a_{i-1}], S_0) and says that ai,…,ana_i, \ldots, a_n can run in order from there. So one backward pass regresses every precondition through all the actions before it.

Example

Take the Yale shooting domain with the fluents loaded\mathit{loaded} and alive\mathit{alive}. The action load\mathit{load} has Πload=¬loaded\Pi_{\mathit{load}} = \neg \mathit{loaded} and γloaded+=true\gamma^+_{\mathit{loaded}} = \mathit{true}; wait\mathit{wait} has no effects; shoot\mathit{shoot} has γalive−=loaded\gamma^-_{\mathit{alive}} = \mathit{loaded} and γloaded−=true\gamma^-_{\mathit{loaded}} = \mathit{true}. Both wait\mathit{wait} and shoot\mathit{shoot} are always possible. The right sides of the successor state axioms are:

action Φloaded,a\Phi_{\mathit{loaded}, a} Φalive,a\Phi_{\mathit{alive}, a}
load\mathit{load} true\mathit{true} alive\mathit{alive}
wait\mathit{wait} loaded\mathit{loaded} alive\mathit{alive}
shoot\mathit{shoot} false\mathit{false} alive∧¬loaded\mathit{alive} \wedge \neg \mathit{loaded}

Regress ¬alive\neg \mathit{alive} through [load,wait,shoot][\mathit{load}, \mathit{wait}, \mathit{shoot}]:

step action φ\varphi after line L3
start ¬alive\neg \mathit{alive}
i=3i = 3 shoot\mathit{shoot} ¬(alive∧¬loaded)\neg(\mathit{alive} \wedge \neg \mathit{loaded})
i=2i = 2 wait\mathit{wait} ¬(alive∧¬loaded)\neg(\mathit{alive} \wedge \neg \mathit{loaded})
i=1i = 1 load\mathit{load} ¬(alive∧¬true)\neg(\mathit{alive} \wedge \neg \mathit{true}), which MAKE folds to true\mathit{true}

The result is true\mathit{true}, so every initial database entails that the victim is dead after the sequence. EXECUTABLE-FORMULA gives χ=true\chi = \mathit{true} after shoot\mathit{shoot} and wait\mathit{wait}, and ¬loaded\neg \mathit{loaded} after load\mathit{load}. With DS0={alive}\mathcal{D}_{S_0} = \{\mathit{alive}\} the sequence is not known to be executable, since the state with loaded\mathit{loaded} true is a model, and with DS0={alive,¬loaded}\mathcal{D}_{S_0} = \{\mathit{alive}, \neg \mathit{loaded}\} it is. The query alive\mathit{alive} after [wait,shoot][\mathit{wait}, \mathit{shoot}] regresses to alive∧¬loaded\mathit{alive} \wedge \neg \mathit{loaded}: the first database does not entail it and the second does.

Sharing matters. Let one action set pp to p↔qp \leftrightarrow q, with γp+=¬p∧¬q\gamma^+_p = \neg p \wedge \neg q and γp−=¬q\gamma^-_p = \neg q, so that Φp,a=(¬p∧¬q)∨(p∧q)\Phi_{p,a} = (\neg p \wedge \neg q) \vee (p \wedge q). Regressing pp through nn copies of aa gives a formula whose tree has 2n+3−72^{n+3} - 7 nodes for n≥1n \ge 1 (9, 25, 57, ..., 2041 for n=8n = 8), because pp occurs twice in Φp,a\Phi_{p,a}. The DAG has 4n+34n + 3 nodes (7, 11, 15, ..., 35).

Correctness

The proofs are in the correctness proof. For a state ss and an action aa, let succ(s,a)\mathrm{succ}(s, a) be the state with succ(s,a)(F)=s(ΦF,a)\mathrm{succ}(s, a)(F) = s(\Phi_{F,a}) for each fluent FF; this is what the successor state axioms force.

  1. One step. For every formula uu and state ss, s⊨STEP(u,a,M)  ⟺  succ(s,a)⊨us \models \mathrm{STEP}(u, a, M) \iff \mathrm{succ}(s, a) \models u. The proof is an induction on uu; the case of a fluent is the successor state axiom, and the memo table only returns values that were computed by the same rule.
  2. Whole sequence. By induction on nn, s⊨REGRESS(φ,[a1,…,an])s \models \mathrm{REGRESS}(\varphi, [a_1, \ldots, a_n]) if and only if φ\varphi holds in the state reached from ss by a1,…,ana_1, \ldots, a_n.
  3. Projection. In the fragment, a model of D\mathcal{D} is fixed by its initial state, which is any model of DS0\mathcal{D}_{S_0}, since the successor state axioms determine every later state. So D⊨φ(do([a1,…,an],S0))\mathcal{D} \models \varphi(\mathit{do}([a_1, \ldots, a_n], S_0)) if and only if DS0⊨REGRESS(φ,[a1,…,an])\mathcal{D}_{S_0} \models \mathrm{REGRESS}(\varphi, [a_1, \ldots, a_n]), which is the regression theorem for this fragment.
  4. Executability. By induction from i=ni = n down to 1, χ\chi after line L13 holds at ss if and only if ai,…,ana_i, \ldots, a_n are possible in order from ss.
Proof: Regression in the ground propositional situation calculus is sound and complete for projection and executabilityfull

We use the pseudocode of the page, lines L1 to L15, and the fragment of the page: kk ground fluents, a finite set of ground actions, no sensing. A state is a map ss from the fluents to {0,1}\{0, 1\}, extended to formulas in the usual way; we write s⊨us \models u when uu is true in ss. For an action aa, ΦF,a=γF,a+∨(F∧¬γF,a−)\Phi_{F,a} = \gamma^+_{F,a} \vee (F \wedge \neg \gamma^-_{F,a}) is the right side of the successor state axiom of FF, and succ(s,a)\mathrm{succ}(s, a) is the state with succ(s,a)(F)=1\mathrm{succ}(s, a)(F) = 1 if and only if s⊨ΦF,as \models \Phi_{F,a}. For a sequence, succ(s,[])=s\mathrm{succ}(s, []) = s and succ(s,[a1,…,an])=succ(succ(s,[a1,…,an−1]),an)\mathrm{succ}(s, [a_1, \ldots, a_n]) = \mathrm{succ}(\mathrm{succ}(s, [a_1, \ldots, a_{n-1}]), a_n).

Semantics of the fragment. A model of the theory assigns a state to every situation. The successor state axioms say that the state of do(a,σ)\mathit{do}(a, \sigma) is succ(state of σ,a)\mathrm{succ}(\text{state of } \sigma, a), so by induction on the length of the action list the state of do([a1,…,an],S0)\mathit{do}([a_1, \ldots, a_n], S_0) is succ(s0,[a1,…,an])\mathrm{succ}(s_0, [a_1, \ldots, a_n]), where s0s_0 is the state of S0S_0. The only other axioms on states are those of DS0\mathcal{D}_{S_0}, so the possible values of s0s_0 are exactly the models of DS0\mathcal{D}_{S_0}, and each of them extends to a model of the whole theory by this rule. Poss(a,σ)\mathit{Poss}(a, \sigma) is true if and only if Πa\Pi_a is true in the state of σ\sigma.

Lemma 0 (MAKE). MAKE(¬,v)(\neg, v), MAKE(∧,v,w)(\wedge, v, w) and MAKE(∨,v,w)(\vee, v, w) return a node that is true in each state ss exactly when ¬v\neg v, v∧wv \wedge w or v∨wv \vee w is.

Proof. MAKE either returns a stored node built from the same operator and the same children, or applies one of the identities ¬true=false\neg \mathit{true} = \mathit{false}, ¬¬v=v\neg \neg v = v, v∧false=falsev \wedge \mathit{false} = \mathit{false}, v∧true=vv \wedge \mathit{true} = v, v∧v=vv \wedge v = v and their duals for ∨\vee, each of which holds in every state. □\square

Lemma 1 (one step). Fix an action aa and a memo table MM such that every entry M[u]=rM[u] = r satisfies: for every state ss, s⊨r  ⟺  succ(s,a)⊨us \models r \iff \mathrm{succ}(s, a) \models u. Then STEP(u,a,M)(u, a, M) returns a node rr with the same property, and every entry it adds to MM has it.

Proof. By induction on the number of nodes below uu. If uu is in MM (line L5), the claim is the assumption on MM. If uu is a constant (line L6), r=ur = u and a constant has the same value in every state. If uu is a fluent FF (line L7), r=ΦF,ar = \Phi_{F,a}, and s⊨ΦF,as \models \Phi_{F,a} if and only if succ(s,a)(F)=1\mathrm{succ}(s, a)(F) = 1, by the definition of succ. If u=¬vu = \neg v (line L8), the call on vv returns rvr_v with s⊨rv  ⟺  succ(s,a)⊨vs \models r_v \iff \mathrm{succ}(s, a) \models v by the induction hypothesis, since vv has fewer nodes below it than uu; by Lemma 0, s⊨r  ⟺  s⊭rv  ⟺  succ(s,a)⊭v  ⟺  succ(s,a)⊨us \models r \iff s \not\models r_v \iff \mathrm{succ}(s, a) \not\models v \iff \mathrm{succ}(s, a) \models u. The case u=v∘wu = v \circ w (line L9) is the same with two calls; the call on ww may use entries that the call on vv added, and these have the property by the induction hypothesis. Line L10 adds the entry (u,r)(u, r), which has the property by the case analysis. □\square

Lemma 2 (REGRESS). For every formula φ\varphi, every action list [a1,…,an][a_1, \ldots, a_n] and every state ss,

s⊨REGRESS(φ,[a1,…,an])  ⟺  succ(s,[a1,…,an])⊨φ.s \models \mathrm{REGRESS}(\varphi, [a_1, \ldots, a_n]) \iff \mathrm{succ}(s, [a_1, \ldots, a_n]) \models \varphi.

Proof. Let φn=φ\varphi_n = \varphi and let φi−1\varphi_{i-1} be the value of φ\varphi after the loop body for ii (lines L2 and L3). We show by induction on j=n,n−1,…,0j = n, n - 1, \ldots, 0 that for every state ss, s⊨φj  ⟺  succ(s,[aj+1,…,an])⊨φs \models \varphi_j \iff \mathrm{succ}(s, [a_{j+1}, \ldots, a_n]) \models \varphi. For j=nj = n the list is empty and both sides are s⊨φs \models \varphi. For the step from jj to j−1j - 1, line L2 makes an empty table, which satisfies the assumption of Lemma 1 for a=aja = a_j. By Lemma 1, s⊨φj−1  ⟺  succ(s,aj)⊨φjs \models \varphi_{j-1} \iff \mathrm{succ}(s, a_j) \models \varphi_j, and by the induction hypothesis applied to the state succ(s,aj)\mathrm{succ}(s, a_j) this holds if and only if succ(succ(s,aj),[aj+1,…,an])⊨φ\mathrm{succ}(\mathrm{succ}(s, a_j), [a_{j+1}, \ldots, a_n]) \models \varphi, which is succ(s,[aj,…,an])⊨φ\mathrm{succ}(s, [a_j, \ldots, a_n]) \models \varphi. For j=0j = 0 this is the claim. □\square

Theorem 1 (projection). PROJECT returns true if and only if φ\varphi holds in do([a1,…,an],S0)\mathit{do}([a_1, \ldots, a_n], S_0) in every model of the theory.

Proof. By the semantics of the fragment, φ\varphi holds in do([a1,…,an],S0)\mathit{do}([a_1, \ldots, a_n], S_0) in every model if and only if succ(s0,[a1,…,an])⊨φ\mathrm{succ}(s_0, [a_1, \ldots, a_n]) \models \varphi for every model s0s_0 of DS0\mathcal{D}_{S_0}. By Lemma 2 this holds if and only if every model of DS0\mathcal{D}_{S_0} satisfies REGRESS(φ,[a1,…,an])(\varphi, [a_1, \ldots, a_n]), that is, if and only if DS0\mathcal{D}_{S_0} entails it, which is what line L15 tests. □\square

Theorem 2 (executability). EXECUTABLE-FORMULA([a1,…,an])([a_1, \ldots, a_n]) returns a formula χ0\chi_0 such that, for every state ss, s⊨χ0s \models \chi_0 if and only if for each ii from 1 to nn, succ(s,[a1,…,ai−1])⊨Πai\mathrm{succ}(s, [a_1, \ldots, a_{i-1}]) \models \Pi_{a_i}. So DS0⊨χ0\mathcal{D}_{S_0} \models \chi_0 if and only if the sequence is executable in every model.

Proof. Let χn=true\chi_n = \mathit{true} and let χi−1\chi_{i-1} be the value after line L13 for ii. We show by induction on j=n,…,0j = n, \ldots, 0: for every state ss, s⊨χjs \models \chi_j if and only if succ(s,[aj+1,…,ai−1])⊨Πai\mathrm{succ}(s, [a_{j+1}, \ldots, a_{i-1}]) \models \Pi_{a_i} for each ii with j<i≤nj < i \le n. For j=nj = n there is no such ii and χn=true\chi_n = \mathit{true}. For the step, χj−1=Πaj∧STEP(χj,aj,∅)\chi_{j-1} = \Pi_{a_j} \wedge \mathrm{STEP}(\chi_j, a_j, \emptyset), so by Lemmas 0 and 1, s⊨χj−1s \models \chi_{j-1} if and only if s⊨Πajs \models \Pi_{a_j} and succ(s,aj)⊨χj\mathrm{succ}(s, a_j) \models \chi_j. By the induction hypothesis at the state succ(s,aj)\mathrm{succ}(s, a_j), the second part says that succ(s,[aj,aj+1,…,ai−1])⊨Πai\mathrm{succ}(s, [a_j, a_{j+1}, \ldots, a_{i-1}]) \models \Pi_{a_i} for each ii with j<i≤nj < i \le n, and the first part is the case i=ji = j. For j=0j = 0 this is the claim. The second sentence follows from the semantics of Poss\mathit{Poss} and of S0S_0, as in Theorem 1. □\square

Termination and size. The loop of line L1 runs nn times. Each call of STEP on a node not in MM adds that node to MM before it returns, and it calls STEP only on the children of the node, so each node of the current DAG is expanded at most once per step. The nodes that step ii creates are the nodes of the formulas ΦF,ai\Phi_{F,a_i} (these exist before the step) and at most one node from line L8 or L9 for each node of φi\varphi_i. So ∣φi−1∣≤∣φi∣+∑F∣ΦF,ai∣|\varphi_{i-1}| \le |\varphi_i| + \sum_F |\Phi_{F,a_i}|, and by induction ∣φ0∣≤∣φ∣+∑i=1n∑F∣ΦF,ai∣≤q+nm|\varphi_0| \le |\varphi| + \sum_{i=1}^{n} \sum_F |\Phi_{F,a_i}| \le q + n m. □\square

Complexity

  • Size. Line L7 adds the nodes of ΦF,a\Phi_{F,a} and lines L8 and L9 add at most one node for each node of φ\varphi. So the DAG after the step for aia_i has at most ∣φi∣+∑F∣ΦF,ai∣|\varphi_i| + \sum_F |\Phi_{F,a_i}| nodes, and the result has at most q+nmq + n m nodes. The tree form has no such bound, as the example shows.
  • Time. Step ii visits each node of the current DAG once, with one expected O(1)O(1) hash lookup per node, so the total is ∑iO(q+(n−i)m)=O(nq+n2m)\sum_i O(q + (n - i) m) = O(n q + n^2 m) expected. EXECUTABLE-FORMULA has the same bound with qq replaced by the size pp of the largest precondition, because χ\chi grows by at most one precondition and one round of Φ\Phi formulas per step.
  • Entailment. In the fragment, projection with an arbitrary propositional DS0\mathcal{D}_{S_0} is coNP-complete. It is in coNP because the regressed DAG has polynomial size, and a model of DS0\mathcal{D}_{S_0} that falsifies it is a short certificate. It is coNP-hard already for n=0n = 0, where it is propositional entailment. If DS0\mathcal{D}_{S_0} fixes every fluent, ENTAILS is one evaluation and projection takes polynomial time. In the first-order case regression still terminates, but the final test DS0∪Duna⊨R[W]\mathcal{D}_{S_0} \cup \mathcal{D}_{una} \models \mathcal{R}[W] is first-order entailment, which is undecidable in general.

Properties

  • Exact. The answer is the same as the answer from the whole theory, not an approximation.
  • Works with incomplete knowledge. DS0\mathcal{D}_{S_0} may leave fluents open; the answer is "entailed" only when every possible initial state gives the same answer.
  • Query-driven. Only the fluents that the query reaches are rewritten. Regression never builds a state.
  • Leaves the database unchanged. Many queries over different histories use the same DS0\mathcal{D}_{S_0}.

Variants and improvements

  • Composition forward. In the propositional fragment, compute for each fluent FF a formula θi(F)\theta_i(F) about S0S_0 that gives FF after a1,…,aia_1, \ldots, a_i: θ0(F)=F\theta_0(F) = F and θi(F)=ΦF,ai[G:=θi−1(G)]\theta_i(F) = \Phi_{F,a_i}[G := \theta_{i-1}(G)]. Then R[φ]=φ[G:=θn(G)]\mathcal{R}[\varphi] = \varphi[G := \theta_n(G)]. With sharing this takes O(q+nm)O(q + n m) expected time, at the cost of computing all fluents, also those that the query does not need.
  • Progression (Lin and Reiter 1997). Update DS0\mathcal{D}_{S_0} to a database about the current situation, and answer later queries against it. Lin and Reiter show that the progressed database is not always first-order definable, and they give classes where it is.
  • Knowledge and sensing. With a knowledge fluent and sensing actions, regression extends to formulas about what the agent knows (Reiter 2001, Section 11.6).
  • Goal regression for STRIPS. When each γF,a+\gamma^+_{F,a} and γF,a−\gamma^-_{F,a} is true\mathit{true} or false\mathit{false} and the query is a conjunction of fluents, R\mathcal{R} is the set formula of goal regression, and regressing through a plan is backward state-space search read as logic. The weakest precondition of an assignment is the same substitution idea for programs.

When to use it

Use regression for a few queries about hypothetical action sequences over an initial database that changes rarely, for example in an interpreter that must check that each step of a candidate plan is possible. Use progression when an agent acts for a long time and asks many questions about the current state: the regressed formulas then grow with the length of the history, while a progressed database does not.

Pitfalls

  • Projection is not executability. A query can hold after a sequence in every model even when the sequence cannot run. In the example, ¬alive\neg \mathit{alive} after [load,wait,shoot][\mathit{load}, \mathit{wait}, \mathit{shoot}] is entailed by {alive}\{\mathit{alive}\}, but the sequence is not known to be executable there. Check Poss\mathit{Poss} separately, or conjoin it to the query.
  • Exponential growth without sharing. A successor state formula that mentions a fluent twice doubles the tree at each step, as in the example. Keep the formula as a DAG and pass it to the prover in a form that keeps the sharing.
  • Non-regressable queries. "The light is on in every situation reachable from S0S_0" quantifies over situations, and R\mathcal{R} is not defined on it. Such properties need induction on situations, which Σ\Sigma provides but regression does not use.
  • Variable capture and unique names. In the first-order case, rename the bound variables of ΦF\Phi_F before the substitution. A formula such as a=shoota = \mathit{shoot} inside ΦF\Phi_F simplifies to false\mathit{false} for a=loada = \mathit{load} only with the unique names axioms, so leaving Duna\mathcal{D}_{una} out of the final test gives wrong answers.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

situation_calculus_regression.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/situation-calculus-regression/. The authors are listed in prov/A4NKPR.jsonl.
"""Regression for a ground, finite, propositional fragment of the situation calculus.

This module is not the first-order regression operator of Reiter. It covers
the case where every fluent is a ground atom with no situation-independent
arguments, there are finitely many ground actions, and no action senses
anything. In that case a situation is a truth assignment to the fluents,
and the successor state axiom of a fluent F for an action a reads

    F(do(a, s))  <->  gamma_plus(s)  or  (F(s) and not gamma_minus(s)),

where gamma_plus and gamma_minus are formulas over the fluents at s. The
precondition axiom of a is Poss(a, s) <-> pi_a(s). The general regression
theorem (Pirri and Reiter, JACM 46(3), 1999) is first order and needs the
foundational axioms and unique names axioms for actions; none of that
appears here.

Formulas are nodes of a hash-consed DAG (class Formulas). Node ids are
integers and equal formulas built twice get the same id, so a regression
step that replaces each fluent by its successor state formula shares every
common subformula. The size of the regressed DAG grows by at most the size
of the successor state formulas at each step.
"""

from __future__ import annotations

import itertools

FALSE, TRUE = 0, 1


class Formulas:
    """A hash-consed DAG of propositional formulas over named fluents."""

    def __init__(self) -> None:
        self.nodes: list[tuple] = [("const", False), ("const", True)]
        self.unique: dict[tuple, int] = {}

    def _make(self, key: tuple) -> int:
        u = self.unique.get(key)
        if u is None:
            u = len(self.nodes)
            self.nodes.append(key)
            self.unique[key] = u
        return u

    def fluent(self, name: str) -> int:
        return self._make(("fluent", name))

    def neg(self, a: int) -> int:
        if a in (FALSE, TRUE):
            return TRUE - a
        key = self.nodes[a]
        if key[0] == "not":
            return key[1]
        return self._make(("not", a))

    def conj(self, a: int, b: int) -> int:
        if a == FALSE or b == FALSE:
            return FALSE
        if a == TRUE:
            return b
        if b == TRUE or a == b:
            return a
        return self._make(("and", min(a, b), max(a, b)))

    def disj(self, a: int, b: int) -> int:
        if a == TRUE or b == TRUE:
            return TRUE
        if a == FALSE:
            return b
        if b == FALSE or a == b:
            return a
        return self._make(("or", min(a, b), max(a, b)))

    def evaluate(self, root: int, state: dict[str, bool]) -> bool:
        memo: dict[int, bool] = {}

        def ev(u: int) -> bool:
            if u in memo:
                return memo[u]
            key = self.nodes[u]
            if key[0] == "const":
                r = key[1]
            elif key[0] == "fluent":
                r = state[key[1]]
            elif key[0] == "not":
                r = not ev(key[1])
            elif key[0] == "and":
                r = ev(key[1]) and ev(key[2])
            else:
                r = ev(key[1]) or ev(key[2])
            memo[u] = r
            return r

        return ev(root)

    def dag_size(self, root: int) -> int:
        """The number of distinct nodes below the root."""
        seen = set()
        stack = [root]
        while stack:
            u = stack.pop()
            if u in seen:
                continue
            seen.add(u)
            key = self.nodes[u]
            if key[0] in ("not", "and", "or"):
                stack.extend(key[1:])
        return len(seen)

    def tree_size(self, root: int) -> int:
        """The number of nodes of the formula written out as a tree, with no sharing."""
        memo: dict[int, int] = {}

        def ts(u: int) -> int:
            if u in memo:
                return memo[u]
            key = self.nodes[u]
            r = 1 + sum(ts(c) for c in key[1:]) if key[0] in ("not", "and", "or") else 1
            memo[u] = r
            return r

        return ts(root)

    def show(self, root: int) -> str:
        key = self.nodes[root]
        if key[0] == "const":
            return "true" if key[1] else "false"
        if key[0] == "fluent":
            return key[1]
        if key[0] == "not":
            return "not " + self.show(key[1])
        return "(" + self.show(key[1]) + " " + key[0] + " " + self.show(key[2]) + ")"


class Action:
    """A ground action: a precondition and, per fluent, the formulas gamma_plus and gamma_minus."""

    def __init__(self, name: str, poss: int, plus: dict[str, int], minus: dict[str, int]) -> None:
        self.name = name
        self.poss = poss
        self.plus = plus
        self.minus = minus


class BasicActionTheory:
    """Fluents, actions with successor state axioms, and an initial database D_S0.

    D_S0 is a list of formulas over the fluents. It may leave some fluents
    unknown, so the initial situation can have many models.
    """

    def __init__(self, f: Formulas, fluents: list[str], actions: dict[str, Action], initial: list[int]) -> None:
        self.f = f
        self.fluents = fluents
        self.actions = actions
        self.initial = initial
        # Phi[a][F] is the right side of the successor state axiom of F for a.
        self.phi: dict[str, dict[str, int]] = {}
        for a in actions.values():
            row = {}
            for name in fluents:
                gp = a.plus.get(name, FALSE)
                gm = a.minus.get(name, FALSE)
                row[name] = f.disj(gp, f.conj(f.fluent(name), f.neg(gm)))
            self.phi[a.name] = row

    # ------------------------------------------------------------ regression

    def regress_step(self, phi: int, action: str) -> int:
        """R_a(phi): replace each fluent F of phi by Phi_{F,a}; the result is about the earlier situation."""
        f = self.f
        row = self.phi[action]
        memo: dict[int, int] = {}  # @line L2

        def r(u: int) -> int:
            if u in memo:  # @line L5
                return memo[u]
            key = f.nodes[u]
            if key[0] == "const":  # @line L6
                out = u
            elif key[0] == "fluent":  # @line L7
                out = row[key[1]]
            elif key[0] == "not":  # @line L8
                out = f.neg(r(key[1]))
            else:  # @line L9
                make = f.conj if key[0] == "and" else f.disj
                out = make(r(key[1]), r(key[2]))
            memo[u] = out  # @line L10
            return out

        return r(phi)

    def regress(self, phi: int, actions: list[str]) -> int:
        """R[phi(do([a1, ..., an], S0))]: a formula about S0 with the same truth value."""
        for a in reversed(actions):  # @line L1
            phi = self.regress_step(phi, a)  # @line L3
        return phi  # @line L4

    def executable_formula(self, actions: list[str]) -> int:
        """The regression of: each a_i is possible in the situation reached by a_1 to a_{i-1}.

        One backward pass: chi_n = true and chi_{i-1} = pi_{a_i} and R_{a_i}(chi_i), so chi_0
        is the conjunction of each precondition regressed through the actions before it.
        """
        f = self.f
        chi = TRUE  # @line L11
        for a in reversed(actions):  # @line L12
            chi = f.conj(self.actions[a].poss, self.regress_step(chi, a))  # @line L13
        return chi  # @line L14

    def entails_initially(self, phi: int) -> bool:
        """Does D_S0 entail phi? Brute force over the assignments to the fluents."""
        for state in self.initial_models():
            if not self.f.evaluate(phi, state):
                return False
        return True

    def initial_models(self):
        for bits in itertools.product([False, True], repeat=len(self.fluents)):
            state = dict(zip(self.fluents, bits))
            if all(self.f.evaluate(g, state) for g in self.initial):
                yield state

    def project_by_regression(self, phi: int, actions: list[str]) -> bool:
        """Is phi true in do(actions, S0) in every model of the theory?"""
        return self.entails_initially(self.regress(phi, actions))  # @line L15

    def executable_by_regression(self, actions: list[str]) -> bool:
        return self.entails_initially(self.executable_formula(actions))

    # ------------------------------------------------- progression (reference)

    def step(self, state: dict[str, bool], action: str) -> dict[str, bool]:
        """The successor state, by evaluating each successor state axiom at the current state."""
        row = self.phi[action]
        return {name: self.f.evaluate(row[name], state) for name in self.fluents}

    def project_by_simulation(self, phi: int, actions: list[str]) -> bool:
        for state in self.initial_models():
            for a in actions:
                state = self.step(state, a)
            if not self.f.evaluate(phi, state):
                return False
        return True

    def executable_by_simulation(self, actions: list[str]) -> bool:
        for state in self.initial_models():
            for a in actions:
                if not self.f.evaluate(self.actions[a].poss, state):
                    return False
                state = self.step(state, a)
        return True


def yale_shooting(initial_alive_only: bool = True) -> tuple[BasicActionTheory, Formulas]:
    """The Yale shooting domain: fluents loaded and alive; actions load, wait and shoot."""
    f = Formulas()
    loaded, alive = f.fluent("loaded"), f.fluent("alive")
    actions = {
        "load": Action("load", f.neg(loaded), {"loaded": TRUE}, {}),
        "wait": Action("wait", TRUE, {}, {}),
        "shoot": Action("shoot", TRUE, {}, {"alive": loaded, "loaded": TRUE}),
    }
    initial = [alive] if initial_alive_only else [alive, f.neg(loaded)]
    return BasicActionTheory(f, ["loaded", "alive"], actions, initial), f
test_situation_calculus_regression.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/situation-calculus-regression/. The authors are listed in prov/A4NKPR.jsonl.
"""Regression against progression by simulation, on random ground domains."""

import itertools
import random

from situation_calculus_regression import (
    FALSE,
    TRUE,
    Action,
    BasicActionTheory,
    Formulas,
    yale_shooting,
)


def random_formula(f: Formulas, rng: random.Random, fluents, depth: int) -> int:
    if depth == 0 or rng.random() < 0.3:
        r = rng.random()
        if r < 0.08:
            return TRUE
        if r < 0.16:
            return FALSE
        return f.fluent(rng.choice(fluents))
    op = rng.choice(["not", "and", "or"])
    if op == "not":
        return f.neg(random_formula(f, rng, fluents, depth - 1))
    a = random_formula(f, rng, fluents, depth - 1)
    b = random_formula(f, rng, fluents, depth - 1)
    return f.conj(a, b) if op == "and" else f.disj(a, b)


def random_theory(rng: random.Random) -> BasicActionTheory:
    f = Formulas()
    k = rng.randint(1, 6)
    fluents = ["F%d" % i for i in range(k)]
    actions = {}
    for j in range(rng.randint(1, 4)):
        name = "a%d" % j
        poss = TRUE if rng.random() < 0.5 else random_formula(f, rng, fluents, 2)
        plus, minus = {}, {}
        for fl in fluents:
            if rng.random() < 0.5:
                plus[fl] = random_formula(f, rng, fluents, 2)
            if rng.random() < 0.5:
                minus[fl] = random_formula(f, rng, fluents, 2)
        actions[name] = Action(name, poss, plus, minus)
    initial = [random_formula(f, rng, fluents, 2) for _ in range(rng.randint(0, 3))]
    return BasicActionTheory(f, fluents, actions, initial)


def all_states(fluents):
    for bits in itertools.product([False, True], repeat=len(fluents)):
        yield dict(zip(fluents, bits))


def test_regression_agrees_with_progression_on_every_state():
    """For every initial state s, R[phi] holds at s iff phi holds after simulating the actions from s."""
    rng = random.Random(1)
    for _ in range(300):
        bat = random_theory(rng)
        names = sorted(bat.actions)
        seq = [rng.choice(names) for _ in range(rng.randint(0, 8))]
        phi = random_formula(bat.f, rng, bat.fluents, 3)
        reg = bat.regress(phi, seq)
        for s in all_states(bat.fluents):
            t = dict(s)
            for a in seq:
                t = bat.step(t, a)
            assert bat.f.evaluate(reg, s) == bat.f.evaluate(phi, t)


def test_projection_and_executability_match_simulation():
    rng = random.Random(2)
    for _ in range(400):
        bat = random_theory(rng)
        names = sorted(bat.actions)
        seq = [rng.choice(names) for _ in range(rng.randint(0, 8))]
        phi = random_formula(bat.f, rng, bat.fluents, 3)
        assert bat.project_by_regression(phi, seq) == bat.project_by_simulation(phi, seq)
        assert bat.executable_by_regression(seq) == bat.executable_by_simulation(seq)


def test_regressed_dag_grows_linearly():
    """dag_size(R[phi]) <= dag_size(phi) + sum over the steps of the sizes of the successor state formulas."""
    rng = random.Random(3)
    for _ in range(100):
        bat = random_theory(rng)
        names = sorted(bat.actions)
        seq = [rng.choice(names) for _ in range(rng.randint(0, 12))]
        phi = random_formula(bat.f, rng, bat.fluents, 3)
        bound = bat.f.dag_size(phi)
        for a in seq:
            bound += sum(bat.f.dag_size(bat.phi[a][fl]) for fl in bat.fluents)
        assert bat.f.dag_size(bat.regress(phi, seq)) <= bound


def test_tree_blows_up_but_dag_does_not():
    """An action that sets p to (p iff q) doubles the tree at each step, while the DAG grows by a constant."""
    f = Formulas()
    p, q = f.fluent("p"), f.fluent("q")
    same = f.disj(f.conj(p, q), f.conj(f.neg(p), f.neg(q)))
    # p(do(a, s)) <-> gamma_plus or (p and not gamma_minus), with gamma_plus = not p and not q, gamma_minus = not q.
    act = Action("a", TRUE, {"p": f.conj(f.neg(p), f.neg(q))}, {"p": f.neg(q)})
    bat = BasicActionTheory(f, ["p", "q"], {"a": act}, [])
    for s in all_states(["p", "q"]):
        assert bat.step(s, "a")["p"] == f.evaluate(same, s)
    trees, dags = [], []
    for n in range(1, 9):
        r = bat.regress(p, ["a"] * n)
        trees.append(f.tree_size(r))
        dags.append(f.dag_size(r))
    assert all(trees[i + 1] > 2 * trees[i] for i in range(len(trees) - 1))
    assert all(dags[i + 1] - dags[i] <= f.dag_size(bat.phi["a"]["p"]) for i in range(len(dags) - 1))


def test_yale_shooting():
    bat, f = yale_shooting(initial_alive_only=True)
    alive, loaded = f.fluent("alive"), f.fluent("loaded")
    assert bat.regress(f.neg(alive), ["load", "wait", "shoot"]) == TRUE
    assert bat.regress(alive, ["wait", "shoot"]) == f.conj(alive, f.neg(loaded))
    assert not bat.project_by_regression(alive, ["wait", "shoot"])
    assert bat.executable_formula(["load", "wait", "shoot"]) == f.neg(loaded)
    assert not bat.executable_by_regression(["load", "wait", "shoot"])
    bat2, f2 = yale_shooting(initial_alive_only=False)
    assert bat2.project_by_regression(f2.fluent("alive"), ["wait", "shoot"])
    assert bat2.project_by_regression(f2.neg(f2.fluent("alive")), ["load", "wait", "shoot"])
    assert bat2.executable_by_regression(["load", "wait", "shoot"])
    assert not bat2.executable_by_regression(["load", "load"])

History

Reiter (1991) gave successor state axioms, built from effect axioms and the causal completeness assumption, and proved that goal regression with them is complete. Pirri and Reiter (1999) gave the metatheory of basic action theories, including the regression theorem and the result that such a theory is satisfiable if and only if its initial database together with the unique names axioms is satisfiable. Lin and Reiter (1997) studied progression as the alternative. Reiter (2001) collected the theory, an implementation in Prolog and the extension to knowledge.

References

  1. Raymond Reiter, Knowledge in Action, Logical Foundations for Specifying and Implementing Dynamical Systems, MIT Press, 2001, Chapter 4, Section 4.4 (basic action theories), Section 4.5 (regression, the regression operator and the regression theorem), Section 4.6 (using regression for executability and projection); Section 11.6 (regression with knowledge-producing actions)
  2. Fiora Pirri and Raymond Reiter, Some contributions to the metatheory of the situation calculus, Journal of the ACM 46(3), 1999, pages 325 to 361 (basic action theories, relative satisfiability, regressable formulas and the soundness and completeness of regression)
  3. Raymond Reiter, The frame problem in the situation calculus: A simple solution (sometimes) and a completeness result for goal regression, in V. Lifschitz (editor), Artificial Intelligence and Mathematical Theory of Computation, Academic Press, 1991, pages 359 to 380 (successor state axioms and the completeness of goal regression)
  4. Fangzhen Lin and Raymond Reiter, How to progress a database, Artificial Intelligence 92(1-2), 1997, pages 131 to 167 (progression as the alternative to regression, and the result that progression is not always first-order definable; general locator)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.entail_brute_force
  • a full proof of time.executable_expected
  • a full proof of time.regress_expected
  • a full proof of space.regressed_formula
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example