Algorithm Search⌘K

Algorithmresearch

Hypertableau calculus

Also called Motik-Shearer-Horrocks hypertableau.

Turns a TBox into DL-clauses and builds a model with hyperresolution-like steps that branch only on real disjunctions, with anywhere blocking to stop.

Time
2^2^2^O(n) worst
Space
2^2^O(n) extra
Where
n = the size of the concept and the TBox
Properties
backtrackingbuilds modeldeterministicexact
Origin
Boris Motik, Rob Shearer, Ian Horrocks, 2009

The hypertableau calculus decides satisfiability of a concept with respect to a general TBox by first turning every axiom into DL-clauses, rules of the form "if these atoms hold, then one of those atoms holds", and then building a model by applying the clauses forward. A clause fires only when its whole body is already true, as in hyperresolution, so an inclusion such as A⊑BA \sqsubseteq B adds BB only where AA holds, and the search branches only when a clause with two or more head atoms fires. New nodes come from existential atoms, and anywhere blocking stops the tree from growing forever. Motik, Shearer and Horrocks introduced it in 2009 to cut the nondeterminism of the ALC tableau.

In plain words

A tableau reasoner checks whether a description can be met by building an example step by step. The plain method turns each rule of the form "every A is a B" into a choice at every element: either it is not an A, or it is a B. With many rules, it makes many choices that do not matter and then undoes them. The hypertableau method writes each rule as "if A holds here, then B holds here" and uses it only when A is already known. A rule that says "if a child has A, then the parent has A" also becomes a plain forward step, with no guess at all. Choices are left only for rules that really say "one of these". To stop making new elements forever, an element that looks exactly like an earlier one is not expanded; it reuses the earlier one instead.

The problem

The input is an ALC concept CC and a TBox TT of general concept inclusions; the output is whether some model of TT puts an element in CC (concept satisfiability). Subsumption C⊑TDC \sqsubseteq_T D is the unsatisfiability of C⊓¬DC \sqcap \neg D (concept subsumption). The problem is EXPTIME-complete (ALC with general TBoxes). This page and its code treat ALC without inverse roles; the paper covers much larger logics with inverse roles, nominals and number restrictions.

The algorithm

DL-clauses. Each inclusion D1⊑D2D_1 \sqsubseteq D_2 becomes ⊤⊑nnf(¬D1⊔D2)\top \sqsubseteq \mathrm{nnf}(\neg D_1 \sqcup D_2), and each disjunction is read as a clause over a center variable xx and one variable yiy_i for each value restriction:

disjunct goes to as
AA head A(x)A(x)
¬A\neg A body A(x)A(x)
∃r.D\exists r.D head (∃r.QD)(x)(\exists r.Q_D)(x)
∀r.¬A\forall r.\neg A body r(x,yi)∧A(yi)r(x, y_i) \wedge A(y_i)
∀r.D\forall r.D body and head r(x,yi)r(x, y_i) in the body, QD(yi)Q_D(y_i) in the head
D1⊓D2D_1 \sqcap D_2 head QD(x)Q_D(x)

Here QDQ_D is DD when DD is a name and otherwise a fresh name with the clauses of QD⊑DQ_D \sqsubseteq D. So A⊑BA \sqsubseteq B is A(x)→B(x)A(x) \to B(x), A⊑∃r.BA \sqsubseteq \exists r.B is A(x)→(∃r.B)(x)A(x) \to (\exists r.B)(x), and ∃r.A⊑B\exists r.A \sqsubseteq B is r(x,y)∧A(y)→B(x)r(x, y) \wedge A(y) \to B(x), with no disjunction in any of them. The input concept gets a fresh name Q0Q_0 with the clauses of Q0⊑CQ_0 \sqsubseteq C.

  1. HYPERTABLEAU(C, T)
  2. 1Γ ← the DL-clauses of T and of Q0 ⊑ C; start with one node n0 and L(n0) = {Q0}
  3. 2repeat
  4. 3if a clause of Γ with at most one head atom has an instance σ whose body holds and whose head does not
  5. 4if the head is empty: return clash, with the branch points the body depends on
  6. 5add the head atom under σ; continue
  7. 6if a node x that is not BLOCKED has (∃r.A)(x) and no r-child with A: add a child w, r(x, w), A(w); continue
  8. 7if a clause with two or more head atoms has such an instance σ
  9. 8for each head atom V: try the branch with σ(V) added; stop on success; backjump past this point if the clash does not use V
  10. 9return clash, with the union of the branch points of the failed branches, without this one
  11. 10return satisfiable ▷ no rule applies: the nodes that are not blocked form a model
  12. BLOCKED(w)
  13. 11w is blocked if its parent is blocked, or if some earlier node that is not blocked has the same label

Lines L3 to L5 are the deterministic part of the Hyp-rule: a body that matches the current nodes forces its only head atom, or a clash when the head is empty. The body may look at the children of xx, so facts flow up the tree as well as down. Line L6 is the existential rule, applied before any branching so that clashes that need no choice are found first. Line L7 is the Hyp-rule with a real disjunction; line L8 tries each head atom in turn. Every fact carries the set of branch points it depends on, so a branch that fails for a reason that has nothing to do with the current choice returns at once to the choice that caused it, as in conflict-directed backjumping. Line L11 is anywhere blocking with equality: the blocker may sit anywhere in the tree, not only on the path to the root.

Example

Let T={∃r.A⊑A}T = \{\exists r.A \sqsubseteq A\} and C=¬A⊓∃r.∃r.AC = \neg A \sqcap \exists r.\exists r.A. The four clauses are (1) r(x,y)∧A(y)→A(x)r(x, y) \wedge A(y) \to A(x), (2) Q0(x)∧A(x)→⊥Q_0(x) \wedge A(x) \to \bot, (3) Q0(x)→(∃r.Q1)(x)Q_0(x) \to (\exists r.Q_1)(x) and (4) Q1(x)→(∃r.A)(x)Q_1(x) \to (\exists r.A)(x), where Q1Q_1 stands for ∃r.A\exists r.A.

step line clause or rule result
1 L1 start L(n0)={Q0}L(n_0) = \{Q_0\}
2 L3, L5 clause 3 at n0n_0 (∃r.Q1)(n0)(\exists r.Q_1)(n_0)
3 L6 existential rule new node n1n_1, r(n0,n1)r(n_0, n_1), Q1(n1)Q_1(n_1)
4 L3, L5 clause 4 at n1n_1 (∃r.A)(n1)(\exists r.A)(n_1)
5 L6 existential rule new node n2n_2, r(n1,n2)r(n_1, n_2), A(n2)A(n_2)
6 L3, L5 clause 1 with x=n1x = n_1, y=n2y = n_2 A(n1)A(n_1)
7 L3, L5 clause 1 with x=n0x = n_0, y=n1y = n_1 A(n0)A(n_0)
8 L3, L4 clause 2 at n0n_0 clash: CC is unsatisfiable

The run makes 2 nodes and 5 Hyp-rule steps and never branches. A plain tableau with subset blocking and no optimizations, the reference of the tests, reads the axiom as ∀r.¬A⊔A\forall r.\neg A \sqcup A at every node and, on the same input, expands 3 nodes and tries 7 completions.

Correctness

The clauses have the same models as the TBox once each fresh name QDQ_D is read as DD. Each rule step is a consequence of the clauses, with the new nodes read as Skolem terms, so a clash that depends on a set of choices shows that those choices cannot hold together; this is also why backjumping is safe. The search stops: a node has at most one child for each existential atom, and the nodes on any path that still grows are not blocked and so have pairwise different labels, which bounds the depth by the number of possible labels. When no rule applies, the nodes that are not blocked form a model: an edge to a blocked node is sent to its blocker, which has the same label, so every clause instance in the model has a copy in the branch, where it already holds. The full proof, with the counterexample to subset blocking, is in proofs/correctness.md.

Proof: The hypertableau search for ALC with anywhere equality blocking terminates and is sound and completefull

We use the pseudocode of the page, lines L1 to L11. The logic is ALC with a general TBox TT and no inverse roles. The input is a concept CC, and the question is whether CC is satisfiable with respect to TT. The proof follows the structure of Motik, Shearer and Horrocks (2009), restricted to this setting, with the rule order, the blocking condition and the backjumping of the implementation.

DL-clauses

A DL-clause is a formula ∀x∀y1…∀yk (U1∧⋯∧Um→V1∨⋯∨Vn)\forall x \forall y_1 \dots \forall y_k\, (U_1 \wedge \dots \wedge U_m \to V_1 \vee \dots \vee V_n). Body atoms are A(x)A(x), r(x,yi)r(x, y_i) and A(yi)A(y_i); every yiy_i occurs in exactly one body atom ri(x,yi)r_i(x, y_i). Head atoms are A(x)A(x), A(yi)A(y_i) and (∃r.A)(x)(\exists r.A)(x), with AA a concept name. With n=0n = 0 the head is false.

Line L1 builds the clauses as follows. A concept EE in negation normal form gives the clauses of ⊤⊑E\top \sqsubseteq E: for E=E1⊓E2E = E_1 \sqcap E_2 the clauses of both parts; otherwise one clause from the disjuncts of EE. A disjunct AA gives the head atom A(x)A(x); ¬A\neg A gives the body atom A(x)A(x); ∃r.D\exists r.D gives the head atom (∃r.QD)(x)(\exists r.Q_D)(x); ∀r.D\forall r.D gives a new variable yy, the body atom r(x,y)r(x, y), and either the body atom A(y)A(y) when D=¬AD = \neg A, or the head atom QD(y)Q_D(y); a conjunction DD gives the head atom QD(x)Q_D(x). Here QDQ_D is DD itself when DD is a name, and otherwise a fresh name with the clauses of ⊤⊑¬QD⊔D\top \sqsubseteq \neg Q_D \sqcup D (for D=D1⊓D2D = D_1 \sqcap D_2, those of ¬QD⊔D1\neg Q_D \sqcup D_1 and ¬QD⊔D2\neg Q_D \sqcup D_2). A disjunct ⊤\top or ∀r.⊤\forall r.\top drops the clause; ⊥\bot and ∃r.⊥\exists r.\bot are left out. The clauses are those of ⊤⊑nnf(¬D1⊔D2)\top \sqsubseteq \mathrm{nnf}(\neg D_1 \sqcup D_2) for each D1⊑D2D_1 \sqsubseteq D_2 in TT, and those of Q0⊑CQ_0 \sqsubseteq C for the root name Q0=Qnnf(C)Q_0 = Q_{\mathrm{nnf}(C)}. Call the set Γ\Gamma.

Lemma 1. (a) In every model II of Γ\Gamma, QDI⊆DIQ_D^I \subseteq D^I for every fresh name, II is a model of TT, and Q0I⊆CIQ_0^I \subseteq C^I. (b) If CC is satisfiable with respect to TT, then Γ\Gamma has a model with Q0I≠∅Q_0^I \neq \emptyset.

Proof. (a) By induction on the size of DD. The clause made from ¬QD⊔D\neg Q_D \sqcup D reads ⊤⊑¬QD⊔D′\top \sqsubseteq \neg Q_D \sqcup D', where D′D' is DD with some subconcepts D′′D'' replaced by QD′′Q_{D''}; by induction QD′′I⊆D′′IQ_{D''}^I \subseteq D''^I. In negation normal form every such D′′D'' occurs positively, so D′I⊆DID'^I \subseteq D^I, and QDI⊆D′I⊆DIQ_D^I \subseteq D'^I \subseteq D^I. The same argument applied to the clauses of the inclusions of TT and of Q0⊑CQ_0 \sqsubseteq C gives the rest. The translation of each disjunct is equivalent to it: for example ∀y (r(x,y)→Q(y))\forall y\,(r(x, y) \to Q(y)) is (∀r.Q)(x)(\forall r.Q)(x), and ∀y (r(x,y)∧A(y)→⊥)\forall y\,(r(x, y) \wedge A(y) \to \bot) is (∀r.¬A)(x)(\forall r.\neg A)(x); several ∀\forall-disjuncts use different variables, so the prenex form is still their disjunction. (b) Take a model II of TT with CI≠∅C^I \ne \emptyset, and set QDI=DIQ_D^I = D^I for every fresh name. Each clause then states a valid inclusion or an inclusion of TT. □\square

The rules and the dependency sets

A branch is a tree of nodes. Each node xx has a label L(x)L(x), a set of names and existential atoms; each node other than the root n0n_0 was made at line L6 from an existential atom (∃r.A)(x)(\exists r.A)(x) of its parent, and the edge carries the role rr. Line L1 starts with L(n0)={Q0}L(n_0) = \{Q_0\}. A clause instance is a map σ\sigma of xx to a node and of each yiy_i to an rir_i-child of σ(x)\sigma(x); it is applicable when every body atom is in the branch and no head atom is. Lines L3 to L5 apply instances with at most one head atom; line L6 applies the existential rule at a node that is not blocked; line L7 branches on an instance with two or more head atoms, one branch for each head atom.

Nodes are numbered in the order they are made. A node ww is blocked if its parent is blocked, or if some node v<wv < w that is not blocked has L(v)=L(w)L(v) = L(w) (anywhere blocking with equality); in the second case ww is directly blocked by the least such vv. The status of ww depends only on nodes before ww, so it is well defined.

Every atom and every edge carries a set of branch levels. The root atom has the empty set. An atom added at line L5 gets the union of the sets of the body atoms and edges of the instance; at line L7 the alternative at level ℓ\ell gets that union plus {ℓ}\{\ell\}. A node made at line L6 and its edge get the set of the existential atom. An atom that is already present keeps its first set.

Read the node made from (∃r.A)(x)(\exists r.A)(x) as the term fr,A(x)f_{r,A}(x) of a Skolem function, and let Σ\Sigma be the formulas (∃r.A)(x)→r(x,fr,A(x))∧A(fr,A(x))(\exists r.A)(x) \to r(x, f_{r,A}(x)) \wedge A(f_{r,A}(x)). A model of Γ\Gamma extends to a model of Γ∪Σ\Gamma \cup \Sigma by choosing witnesses, so Γ∪{Q0(n0)}\Gamma \cup \{Q_0(n_0)\} and Γ∪Σ∪{Q0(n0)}\Gamma \cup \Sigma \cup \{Q_0(n_0)\} are satisfiable together.

Lemma 2. Let HDH_D be the set of the atoms chosen at line L7 on the current branch at the levels in DD. Every atom or edge with dependency set DD is a consequence of Γ∪Σ∪{Q0(n0)}∪HD\Gamma \cup \Sigma \cup \{Q_0(n_0)\} \cup H_D. A call at level ℓ\ell that returns a set DD (a clash) returns D⊆{0,…,ℓ−1}D \subseteq \{0, \dots, \ell - 1\}, and Γ∪Σ∪{Q0(n0)}∪HD\Gamma \cup \Sigma \cup \{Q_0(n_0)\} \cup H_D is unsatisfiable.

Proof. The first part is by induction on the order of the steps: a step at line L5 is an instance of a clause of Γ\Gamma whose body facts are consequences of the sets they carry, and the union of those sets is the set of the new atom; a step at line L6 is an instance of Σ\Sigma; an alternative at line L7 is in HDH_D itself.

For the second part, use induction on the depth of the recursion. A clash at line L4 is an instance with an empty head whose body facts carry sets with union DD; all of them were made below the current level, so D⊆{0,…,ℓ−1}D \subseteq \{0, \dots, \ell - 1\}, and by the first part the set is unsatisfiable. At a branch point at level ℓ\ell with alternatives α1,…,αn\alpha_1, \dots, \alpha_n and body set BB, the call for αi\alpha_i returns Di⊆{0,…,ℓ}D_i \subseteq \{0, \dots, \ell\} with Γ∪Σ∪{Q0(n0)}∪HDi\Gamma \cup \Sigma \cup \{Q_0(n_0)\} \cup H_{D_i} unsatisfiable. If ℓ∉Di\ell \notin D_i, then HDiH_{D_i} uses only choices made above this branch point, and the call returns DiD_i (backjumping). Otherwise every atom that carries ℓ\ell was derived from αi\alpha_i, so its set contains the set B∪{ℓ}B \cup \{\ell\} of αi\alpha_i, and hence B⊆Di∖{ℓ}B \subseteq D_i \setminus \{\ell\}. Let D=⋃i(Di∖{ℓ})D = \bigcup_i (D_i \setminus \{\ell\}). Then Γ∪Σ∪{Q0(n0)}∪HD\Gamma \cup \Sigma \cup \{Q_0(n_0)\} \cup H_D implies the body of the instance, so it implies α1∨⋯∨αn\alpha_1 \vee \dots \vee \alpha_n, and with each αi\alpha_i it is unsatisfiable. So it is unsatisfiable, and D⊆{0,…,ℓ−1}D \subseteq \{0, \dots, \ell - 1\}. □\square

Soundness. If the search answers "unsatisfiable", the top call at level 0 returned a set D⊆∅D \subseteq \emptyset, so Γ∪Σ∪{Q0(n0)}\Gamma \cup \Sigma \cup \{Q_0(n_0)\} is unsatisfiable, so Γ\Gamma has no model with Q0I≠∅Q_0^I \ne \emptyset, and by Lemma 1(b) CC is unsatisfiable with respect to TT.

Termination

Let NN be the set of names of Γ\Gamma and XX the set of existential atoms in the heads of Γ\Gamma, and let K=∣N∣+∣X∣K = |N| + |X|. Labels are subsets of N∪XN \cup X, and they only grow along a branch; edges are never removed.

  • Out-degree. Line L6 makes a child for (∃r.A)(x)(\exists r.A)(x) only when xx has no rr-child with AA, and after that it always has one. So a node has at most ∣X∣|X| children.
  • Depth. Two nodes v<wv < w that are both not blocked never have the same label, because then ww would be directly blocked. When line L6 makes a child of a node pjp_j at depth jj, pjp_j is not blocked, so none of its ancestors p0,…,pj−1p_0, \dots, p_{j - 1} is blocked either. These j+1j + 1 nodes have pairwise different labels, so j+1≤2Kj + 1 \le 2^K, and every node has depth at most 2K2^K.

So a branch has at most ∣X∣2K+1|X|^{2^K + 1} nodes and at most KK atoms on each, every step of lines L5 and L6 adds an atom or a node, and every branch point creates at most max⁡∣head∣\max |{\rm head}| branches that are each longer by one atom. The search tree is finite, and the search stops.

Completeness

Lemma 3. If line L10 is reached, the following interpretation MM is a model of Γ\Gamma with n0∈Q0Mn_0 \in Q_0^M. The domain is the set of nodes that are not blocked. A name AA holds at xx when A∈L(x)A \in L(x). For each node xx of the domain and each child ww of xx with role rr, MM has the edge (x,t(w))(x, t(w)) in rr, where t(w)=wt(w) = w if ww is not blocked and t(w)t(w) is the blocker of ww otherwise.

Proof. The root is never blocked, and Q0∈L(n0)Q_0 \in L(n_0). A child ww of a node xx that is not blocked is either not blocked or directly blocked, so t(w)t(w) is defined, it is in the domain, and L(t(w))=L(w)L(t(w)) = L(w).

Take a clause and a map σ′\sigma' of its variables into the domain that makes the body true in MM. Then σ′(yi)=t(wi)\sigma'(y_i) = t(w_i) for some rir_i-child wiw_i of x=σ′(x)x = \sigma'(x). Let σ\sigma map xx to xx and yiy_i to wiw_i. The body holds under σ\sigma in the branch: the edges are there, the names at xx are the same, and the names at wiw_i are those at t(wi)t(w_i). Lines L3 and L7 found no applicable instance, so some head atom holds under σ\sigma in the branch. If it is A(x)A(x), it holds in MM. If it is A(yi)A(y_i), then A∈L(wi)=L(t(wi))A \in L(w_i) = L(t(w_i)). If it is (∃r.A)(x)(\exists r.A)(x), then xx is not blocked and line L6 did not apply, so xx has an rr-child ww with A∈L(w)A \in L(w), and MM has the edge (x,t(w))(x, t(w)) with A∈L(t(w))A \in L(t(w)). In every case the clause holds under σ′\sigma'. □\square

Theorem. The search returns "satisfiable" if and only if CC is satisfiable with respect to TT, and then the interpretation of Lemma 3 is a model of TT in which the root is in CC.

Proof. The search stops. If it answers "unsatisfiable", CC is unsatisfiable by the soundness argument. If it answers "satisfiable", Lemma 3 gives a model of Γ\Gamma with n0∈Q0Mn_0 \in Q_0^M, and by Lemma 1(a) it is a model of TT with n0∈CMn_0 \in C^M. ■\blacksquare

Subset blocking is not sound here

Blocking ww by an earlier node vv with L(w)⊆L(v)L(w) \subseteq L(v) is sound for the plain ALC tableau, where information only flows from a node to its children. A clause such as r(x,y)∧A(y)→A(x)r(x, y) \wedge A(y) \to A(x), from ∃r.A⊑A\exists r.A \sqsubseteq A, sends information from a child to its parent, and then the proof of Lemma 3 fails: the edge to t(w)t(w) makes more body atoms true than the edge to ww. Take C=A⊓W⊓∃r.W⊓∀r.¬AC = A \sqcap W \sqcap \exists r.W \sqcap \forall r.\neg A and T={W⊑∃r.B, ∃r.B⊑A}T = \{W \sqsubseteq \exists r.B,\ \exists r.B \sqsubseteq A\}. The rr-child made for WW has the label {W,∃r.B}\{W, \exists r.B\}, a subset of the root label. Subset blocking stops there and answers "satisfiable". But that child needs a BB-successor, so it is in AA, which ∀r.¬A\forall r.\neg A at the root forbids, and CC is unsatisfiable. Equality blocking does not block the child, and the search finds the clash.

Running time

The number of names and existential atoms is K=O(n)K = O(n) for an input of size nn. One branch has at most ∣X∣2K+1=22O(n)|X|^{2^K + 1} = 2^{2^{O(n)}} nodes, and the search tree has at most (max⁡∣head∣)(\max |{\rm head}|) choices at each of at most 22O(n)2^{2^{O(n)}} branch points along a path, which bounds the time by 222O(n)2^{2^{2^{O(n)}}}. The space is one branch for each open branch point on the path, 22O(n)2^{2^{O(n)}}. These are coarse bounds for this simple search, not the complexity of the problem, which is EXPTIME-complete.

Complexity

Let nn be the size of CC and TT, so there are O(n)O(n) names and existential atoms. A branch has depth at most 2O(n)2^{O(n)} and out-degree O(n)O(n), so it has at most 22O(n)2^{2^{O(n)}} nodes, and the depth-first search over the branch points is bounded by 222O(n)2^{2^{2^{O(n)}}} steps and 22O(n)2^{2^{O(n)}} space. These are coarse bounds for this search; satisfiability in ALC with a general TBox is EXPTIME-complete, and worst-case optimal methods use global caching or type elimination instead.

The gain is in the nondeterminism. For Tm={Bi⊑Ci:1≤i≤m}∪{A⊑∃r.D, D⊑E, E⊑⊥}T_m = \{B_i \sqsubseteq C_i : 1 \le i \le m\} \cup \{A \sqsubseteq \exists r.D,\ D \sqsubseteq E,\ E \sqsubseteq \bot\} and the concept AA, the hypertableau makes 1 node, takes 3 Hyp-rule steps and never branches, because no node has any BiB_i. The same plain tableau adds ¬Bi⊔Ci\neg B_i \sqcup C_i to every node and tries every combination at the root:

mm plain tableau: nodes plain tableau: completions tried
0 2 20
2 5 221
4 17 3185
6 65 49601
8 257 788225

Tableau reasoners with absorption, which turns Bi⊑CiB_i \sqsubseteq C_i into a rule that fires only on BiB_i, also avoid this blow-up; the DL-clauses give the same effect for every inclusion whose left side is a conjunction of names and existential restrictions on names.

Properties

  • Branching only on disjunctions. An inclusion with a conjunction of names and existential restrictions on names on the left, and no disjunction on the right, gives clauses with at most one head atom, and these never branch. When all clauses are of this kind, the search is deterministic.
  • Facts flow both ways. A body atom A(y)A(y) lets a child change its parent, which is what makes ∃r.A⊑A\exists r.A \sqsubseteq A deterministic.
  • Builds a model. An open branch gives a finite model of TT with the root in CC.
  • Exact. It answers both "yes" and "no" correctly for every ALC input.

Variants and improvements

  • Expressive logics. Motik, Shearer and Horrocks (2009) extend the clauses with inverse roles, number restrictions, nominals and equality atoms between successors, with pairwise anywhere blocking for inverse roles.
  • Blocking variants. Anywhere blocking lets the blocker be any earlier node, not only an ancestor, so trees stop earlier. Single blocking with equality, as here, suffices without inverse roles; pairwise blocking compares a node and its parent with another such pair.
  • Absorption and caching. Reasoners combine the calculus with absorption of axioms into the clause bodies, caching of results for labels, and individual reuse between subsumption tests during ontology classification.
  • Simple search. Without the dependency sets, chronological backtracking is correct too, but it can retry the same failing expansion under every combination of earlier, unrelated choices.

When to use it

Use it for satisfiability, subsumption and classification in expressive description logics, up to the SROIQ logic of OWL 2, especially for ontologies with many general concept inclusions whose left sides are conjunctions, where a plain tableau branches on every axiom at every node. For ontologies that stay inside the EL family, completion rules classify in polynomial time and are much faster. For query answering over large data in DL-Lite, query rewriting fits better.

Pitfalls

  • Subset blocking. Line L11 must ask for an equal label. With "subset of an earlier label", the concept A⊓W⊓∃r.W⊓∀r.¬AA \sqcap W \sqcap \exists r.W \sqcap \forall r.\neg A with W⊑∃r.BW \sqsubseteq \exists r.B and ∃r.B⊑A\exists r.B \sqsubseteq A is reported satisfiable: the child for WW is blocked by the root, its BB-successor is never made, and the AA it would force upward is never seen. Subset blocking is sound only when facts flow downward, as in the plain tableau.
  • A blocked blocker. At line L11, the earlier node must not be blocked itself. A blocked node does not expand its existential atoms, so redirecting edges to it builds an interpretation in which those atoms fail.
  • Backjumping without the body set. At line L8, the head atom chosen at a branch point must carry the branch points of the clause body as well as its own. If it carries only its own, a clash that comes from the body is blamed on nothing, the search jumps over a choice that matters, and a satisfiable concept can be reported unsatisfiable.
  • Clauses that guess. Line L1 must put ∀r.¬A\forall r.\neg A into the body as r(x,y)∧A(y)r(x, y) \wedge A(y). Writing it into the head through a fresh name QQ with Q⊑¬AQ \sqsubseteq \neg A is still correct, but ∃r.A⊑B\exists r.A \sqsubseteq B then becomes a clause with two head atoms, and line L7 branches at every node with an rr-successor, much as the plain tableau does.
  • Branching first. If line L7 runs before line L6, a clash that needs no choice, deep in the tree, is found only after every choice above it, and without backjumping the search repeats it for each combination.

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.

alc_reference.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Test helper of the description logic pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A small reference decision procedure for ALC concept satisfiability with a general TBox.

The tests use it as an independent oracle. It is the plain tableau: depth first, a label is a set
of concepts in negation normal form, every node gets the concept nnf(not C or D) of each inclusion
C subsumed by D, and a new node is not made when its label is a subset of the label of an ancestor
(subset blocking, which is sound for ALC). Disjunctions are split in a fixed order with no
heuristics, so the node count shows how much search the plain method does.
"""

from typing import Iterator, Sequence

from dl import BOTTOM, GCI, Concept, conj, disj, neg, nnf


class Counter:
    def __init__(self) -> None:
        self.nodes = 0  # labels that were completed and expanded
        self.branches = 0  # completions tried, clash-free or not


def _completions(s: frozenset, cnt: Counter) -> Iterator[frozenset]:
    lab: set = set()
    stack = list(s)
    while stack:
        c = stack.pop()
        if c in lab:
            continue
        lab.add(c)
        if c[0] == "and":
            stack.append(c[1])
            stack.append(c[2])
    cnt.branches += 1
    if BOTTOM in lab or any(c[0] == "not" and c[1] in lab for c in lab):
        return
    pending = sorted(repr(c) for c in lab if c[0] == "or" and c[1] not in lab and c[2] not in lab)
    if not pending:
        yield frozenset(lab)
        return
    c = next(c for c in lab if repr(c) == pending[0])
    yield from _completions(frozenset(lab | {c[1]}), cnt)
    yield from _completions(frozenset(lab | {c[2]}), cnt)


def _sat(label: frozenset, ancestors: tuple, tc: frozenset, cnt: Counter) -> bool:
    cnt.nodes += 1
    for lab in _completions(label, cnt):
        path = ancestors + (lab,)
        ok = True
        for c in sorted((c for c in lab if c[0] == "some"), key=repr):
            child = frozenset({c[2]} | {d[2] for d in lab if d[0] == "all" and d[1] == c[1]}) | tc
            if tc and any(child <= a for a in path):
                continue  # blocked: the ancestor's label serves as the successor
            if not _sat(child, path, tc, cnt):
                ok = False
                break
        if ok:
            return True
    return False


def satisfiable_count(c: Concept, tbox: Sequence[GCI] = ()) -> tuple[bool, Counter]:
    """Decide whether c is satisfiable with respect to the TBox; also return the work counter."""
    tc = frozenset(nnf(disj(neg(x), y)) for x, y in tbox)
    cnt = Counter()
    return _sat(frozenset({nnf(c)}) | tc, (), tc, cnt), cnt


def satisfiable(c: Concept, tbox: Sequence[GCI] = ()) -> bool:
    return satisfiable_count(c, tbox)[0]


def subsumes(c: Concept, d: Concept, tbox: Sequence[GCI] = ()) -> bool:
    """True when c is subsumed by d with respect to the TBox."""
    return not satisfiable(conj(c, neg(d)), tbox)
dl.py 232 lines
# SPDX-License-Identifier: MIT
# Shared helper of the description logic pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""ALC concepts as syntax trees, negation normal form, and evaluation in a finite interpretation.

A concept is a tuple:
    TOP = ("top",)            BOTTOM = ("bottom",)
    ("atom", "A")             ("not", C)
    ("and", C, D)             ("or", C, D)
    ("some", "r", C)          ("all", "r", C)
A TBox is a sequence of general concept inclusions (C, D), read C is subsumed by D.
An interpretation has a nonempty finite domain, a set for each concept name and a set of pairs
for each role name. Names that an interpretation does not list are empty.
This file holds only the syntax and the semantics. No reasoning algorithm goes here.
"""

from itertools import product
from typing import Iterable, Iterator, Sequence

Concept = tuple
GCI = tuple[Concept, Concept]

TOP: Concept = ("top",)
BOTTOM: Concept = ("bottom",)


def atom(name: str) -> Concept:
    return ("atom", name)


def neg(c: Concept) -> Concept:
    return ("not", c)


def conj(*cs: Concept) -> Concept:
    """The conjunction of the arguments, nested to the right. conj() is TOP."""
    if not cs:
        return TOP
    out = cs[-1]
    for c in reversed(cs[:-1]):
        out = ("and", c, out)
    return out


def disj(*cs: Concept) -> Concept:
    """The disjunction of the arguments, nested to the right. disj() is BOTTOM."""
    if not cs:
        return BOTTOM
    out = cs[-1]
    for c in reversed(cs[:-1]):
        out = ("or", c, out)
    return out


def exists(r: str, c: Concept) -> Concept:
    return ("some", r, c)


def forall(r: str, c: Concept) -> Concept:
    return ("all", r, c)


def nnf(c: Concept) -> Concept:
    """Negation normal form: an equivalent concept with negation only in front of concept names."""
    op = c[0]
    if op in ("top", "bottom", "atom"):
        return c
    if op in ("and", "or"):
        return (op, nnf(c[1]), nnf(c[2]))
    if op in ("some", "all"):
        return (op, c[1], nnf(c[2]))
    d = c[1]  # op == "not"
    dop = d[0]
    if dop == "top":
        return BOTTOM
    if dop == "bottom":
        return TOP
    if dop == "atom":
        return c
    if dop == "not":
        return nnf(d[1])
    if dop == "and":
        return ("or", nnf(neg(d[1])), nnf(neg(d[2])))
    if dop == "or":
        return ("and", nnf(neg(d[1])), nnf(neg(d[2])))
    if dop == "some":
        return ("all", d[1], nnf(neg(d[2])))
    return ("some", d[1], nnf(neg(d[2])))  # dop == "all"


def is_nnf(c: Concept) -> bool:
    op = c[0]
    if op in ("top", "bottom", "atom"):
        return True
    if op == "not":
        return c[1][0] == "atom"
    if op in ("and", "or"):
        return is_nnf(c[1]) and is_nnf(c[2])
    return is_nnf(c[2])


def subconcepts(c: Concept) -> set[Concept]:
    """All subconcepts of c, c included."""
    out = {c}
    op = c[0]
    if op == "not":
        out |= subconcepts(c[1])
    elif op in ("and", "or"):
        out |= subconcepts(c[1]) | subconcepts(c[2])
    elif op in ("some", "all"):
        out |= subconcepts(c[2])
    return out


def size(c: Concept) -> int:
    """The number of constructors and names in c."""
    op = c[0]
    if op in ("top", "bottom", "atom"):
        return 1
    if op == "not":
        return 1 + size(c[1])
    if op in ("and", "or"):
        return 1 + size(c[1]) + size(c[2])
    return 2 + size(c[2])


def role_depth(c: Concept) -> int:
    """The largest number of nested role restrictions in c."""
    op = c[0]
    if op in ("top", "bottom", "atom"):
        return 0
    if op == "not":
        return role_depth(c[1])
    if op in ("and", "or"):
        return max(role_depth(c[1]), role_depth(c[2]))
    return 1 + role_depth(c[2])


def names(cs: Iterable[Concept]) -> tuple[list[str], list[str]]:
    """The sorted concept names and role names that occur in the given concepts."""
    cn: set[str] = set()
    rn: set[str] = set()
    for c in cs:
        for s in subconcepts(c):
            if s[0] == "atom":
                cn.add(s[1])
            elif s[0] in ("some", "all"):
                rn.add(s[1])
    return sorted(cn), sorted(rn)


def show(c: Concept) -> str:
    """The concept in the usual notation, with full parentheses."""
    op = c[0]
    if op == "top":
        return "⊤"
    if op == "bottom":
        return "⊥"
    if op == "atom":
        return c[1]
    if op == "not":
        return "¬" + show(c[1])
    if op == "and":
        return "(" + show(c[1]) + " ⊓ " + show(c[2]) + ")"
    if op == "or":
        return "(" + show(c[1]) + " ⊔ " + show(c[2]) + ")"
    q = "∃" if op == "some" else "∀"
    return q + c[1] + "." + show(c[2])


class Interpretation:
    """A finite interpretation. domain is a nonempty list; concepts maps a name to a set of elements;
    roles maps a name to a set of pairs of elements."""

    def __init__(self, domain: Sequence, concepts: dict, roles: dict) -> None:
        if not domain:
            raise ValueError("the domain of an interpretation is not empty")
        self.domain = list(domain)
        self.concepts = {a: frozenset(s) for a, s in concepts.items()}
        self.roles = {r: frozenset(p) for r, p in roles.items()}
        self._succ: dict[str, dict] = {}

    def successors(self, r: str, x) -> list:
        if r not in self._succ:
            m: dict = {y: [] for y in self.domain}
            for (u, v) in self.roles.get(r, ()):
                m[u].append(v)
            self._succ[r] = m
        return self._succ[r][x]

    def __repr__(self) -> str:
        return f"Interpretation({self.domain!r}, {self.concepts!r}, {self.roles!r})"


def evaluate(c: Concept, i: Interpretation) -> frozenset:
    """The extension of c in the interpretation i, by the semantics of ALC."""
    op = c[0]
    if op == "top":
        return frozenset(i.domain)
    if op == "bottom":
        return frozenset()
    if op == "atom":
        return i.concepts.get(c[1], frozenset())
    if op == "not":
        return frozenset(i.domain) - evaluate(c[1], i)
    if op == "and":
        return evaluate(c[1], i) & evaluate(c[2], i)
    if op == "or":
        return evaluate(c[1], i) | evaluate(c[2], i)
    ext = evaluate(c[2], i)
    if op == "some":
        return frozenset(x for x in i.domain if any(y in ext for y in i.successors(c[1], x)))
    return frozenset(x for x in i.domain if all(y in ext for y in i.successors(c[1], x)))


def is_model_of_tbox(i: Interpretation, tbox: Iterable[GCI]) -> bool:
    """True when i satisfies every inclusion C subsumed by D of the TBox."""
    return all(evaluate(c, i) <= evaluate(d, i) for c, d in tbox)


def interpretations(concept_names: Sequence[str], role_names: Sequence[str], max_size: int) -> Iterator[Interpretation]:
    """Every interpretation of the given names over the domains [0], [0, 1], ..., [0, ..., max_size - 1].
    There are sum over n of 2^(n * |concept_names| + n^2 * |role_names|) of them."""
    for n in range(1, max_size + 1):
        dom = list(range(n))
        pairs = [(x, y) for x in dom for y in dom]
        cbits = list(product((False, True), repeat=n * len(concept_names)))
        rbits = list(product((False, True), repeat=n * n * len(role_names)))
        for rb in rbits:
            roles = {r: {pairs[k] for k in range(n * n) if rb[j * n * n + k]} for j, r in enumerate(role_names)}
            for cb in cbits:
                conc = {a: {x for x in dom if cb[j * n + x]} for j, a in enumerate(concept_names)}
                yield Interpretation(dom, conc, roles)
hypertableau.py 295 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hypertableau/. The authors are listed in prov/974KXE.jsonl.
"""The hypertableau calculus for ALC concept satisfiability with a general TBox.

The TBox and the input concept are first turned into DL-clauses
    U_1 and ... and U_m  ->  V_1 or ... or V_n
over a center variable x and successor variables y_1, ..., y_k. Body atoms are A(x), r(x, y_i)
and A(y_i); head atoms are A(x), A(y_i) and the existential atom (some r.A)(x). An empty head
means a clash. Negative literals go to the body, so labels hold only names and existential atoms.

A clause is a tuple (bx, roles, by, head):
    bx     frozenset of concept names that must hold at x
    roles  tuple of role names; y_i is an r_i-successor of x
    by     tuple of frozensets; by[i] is the set of names that must hold at y_i
    head   tuple of atoms ("x", A), ("y", i, A) or ("some", r, A)
Fresh concept names start with "_Q". The search works on a tree of nodes; node 0 is the root.
Every atom and every edge carries the set of branch points it depends on, so that a clash can
jump back over branch points that did not take part in it (backjumping).
"""

from itertools import product
from typing import Optional, Sequence

from dl import BOTTOM, TOP, GCI, Concept, Interpretation, disj, neg, nnf


class Clausifier:
    """The structural transformation of NNF concepts into DL-clauses."""

    def __init__(self) -> None:
        self.clauses: list[tuple] = []
        self.fresh: dict[Concept, str] = {}

    def name_for(self, c: Concept) -> str:
        """A concept name Q with the clauses of Q subsumed by c. Reused for equal concepts."""
        if c[0] == "atom":
            return c[1]
        if c not in self.fresh:
            q = f"_Q{len(self.fresh) + 1}"
            self.fresh[c] = q
            self.define(q, c)
        return self.fresh[c]

    def define(self, q: str, c: Concept) -> None:
        if c[0] == "and":
            self.define(q, c[1])
            self.define(q, c[2])
        else:
            self.axiom(("or", ("not", ("atom", q)), c))

    def axiom(self, e: Concept) -> None:
        """Add the clauses of top subsumed by e, for e in NNF."""
        if e[0] == "and":
            self.axiom(e[1])
            self.axiom(e[2])
            return
        stack, disjuncts = [e], []
        while stack:
            d = stack.pop()
            if d[0] == "or":
                stack += [d[2], d[1]]
            else:
                disjuncts.append(d)
        bx: set[str] = set()
        roles: list[str] = []
        by: list[frozenset] = []
        head: list[tuple] = []
        for d in disjuncts:
            op = d[0]
            if op == "top" or (op == "all" and d[2] == TOP):
                return  # the clause holds everywhere
            if op == "bottom" or (op == "some" and d[2] == BOTTOM):
                continue
            if op == "atom":
                head.append(("x", d[1]))
            elif op == "not":
                bx.add(d[1][1])
            elif op == "some":
                head.append(("some", d[1], self.name_for(d[2])))
            elif op == "all":
                i = len(roles)
                roles.append(d[1])
                inner = d[2]
                if inner == BOTTOM:
                    by.append(frozenset())
                elif inner[0] == "not":
                    by.append(frozenset({inner[1][1]}))
                else:
                    by.append(frozenset())
                    head.append(("y", i, self.name_for(inner)))
            else:  # a conjunction inside a disjunction gets a fresh name
                head.append(("x", self.name_for(d)))
        self.clauses.append((frozenset(bx), tuple(roles), tuple(by), tuple(dict.fromkeys(head))))


def clausify(c: Concept, tbox: Sequence[GCI] = ()) -> tuple[str, list[tuple]]:
    """The DL-clauses of the TBox and of Q0 subsumed by c, and the name Q0 that the root gets."""
    cl = Clausifier()
    for x, y in tbox:
        cl.axiom(nnf(disj(neg(x), y)))
    root = cl.name_for(nnf(c))
    return root, cl.clauses


class Counter:
    def __init__(self) -> None:
        self.nodes = 0  # nodes made by the existential rule, over all branches
        self.branches = 0  # alternatives tried at nondeterministic Hyp-rule steps
        self.hyp = 0  # Hyp-rule steps


NODEPS: frozenset = frozenset()


class State:
    """One branch: a tree of nodes. labels[x] maps each atom of node x to the branch points it
    depends on; edge[w] is the same for the edge from the parent of w to w. Node ids follow the
    order of creation."""

    def __init__(self, root: str) -> None:
        self.labels: list[dict] = [{root: NODEPS}]
        self.parent: list[Optional[int]] = [None]
        self.role: list[Optional[str]] = [None]
        self.edge: list[frozenset] = [NODEPS]
        self.children: list[list[int]] = [[]]

    def copy(self) -> "State":
        s = State.__new__(State)
        s.labels = [dict(lab) for lab in self.labels]
        s.parent = list(self.parent)
        s.role = list(self.role)
        s.edge = list(self.edge)
        s.children = [list(ch) for ch in self.children]
        return s


def blocking(s: State, mode: str = "equal") -> tuple[list[bool], dict[int, int]]:
    """Which nodes are blocked, and the blocker of each directly blocked node. A node is blocked
    when its parent is blocked, or when an earlier node that is not blocked has the same label
    (mode "equal", anywhere blocking) or a superset of its label (mode "subset", unsound here)."""
    status: list[bool] = []
    blocker: dict[int, int] = {}
    first: dict[frozenset, int] = {}
    open_labels: list[tuple[int, frozenset]] = []
    for w in range(len(s.labels)):
        p = s.parent[w]
        if p is not None and status[p]:
            status.append(True)
            continue
        key = frozenset(s.labels[w])
        if mode == "equal":
            v = first.get(key)
        else:
            v = next((u for u, lab in open_labels if key <= lab), None)
        if v is None:
            first[key] = w
            open_labels.append((w, key))
            status.append(False)
        else:
            blocker[w] = v
            status.append(True)
    return status, blocker


def _holds(s: State, x: int, sigma: tuple, atom: tuple) -> bool:
    if atom[0] == "x":
        return atom[1] in s.labels[x]
    if atom[0] == "y":
        return atom[2] in s.labels[sigma[atom[1]]]
    return atom in s.labels[x]


def _find_hyp(s: State, clauses: Sequence[tuple], deterministic: bool):
    """The first clause instance whose body holds and whose head has no atom that holds, with the
    branch points that its body depends on."""
    for x in range(len(s.labels)):
        lab = s.labels[x]
        for cl in clauses:
            bx, roles, by, head = cl
            if (len(head) <= 1) != deterministic or not bx <= lab.keys():
                continue
            cands = [[w for w in s.children[x] if s.role[w] == r and by[i] <= s.labels[w].keys()] for i, r in enumerate(roles)]
            for sigma in product(*cands):
                if not any(_holds(s, x, sigma, a) for a in head):
                    deps = set().union(*(lab[a] for a in bx))
                    for i, w in enumerate(sigma):
                        deps |= s.edge[w]
                        deps = deps.union(*(s.labels[w][a] for a in by[i]))
                    return x, sigma, head, frozenset(deps)
    return None


def _add(s: State, x: int, sigma: tuple, atom: tuple, deps: frozenset) -> None:
    if atom[0] == "x":
        s.labels[x].setdefault(atom[1], deps)
    elif atom[0] == "y":
        s.labels[sigma[atom[1]]].setdefault(atom[2], deps)
    else:
        s.labels[x].setdefault(atom, deps)


def _exists_rule(s: State, mode: str, cnt: Counter) -> bool:
    """Apply the existential rule once, at the first node that is not blocked and has an
    existential atom without a witness. Return False when there is no such node."""
    status, _ = blocking(s, mode)  # @line L11
    for x in range(len(s.labels)):
        if status[x]:
            continue
        for atom in sorted(a for a in s.labels[x] if isinstance(a, tuple)):
            _, r, a = atom
            if not any(s.role[w] == r and a in s.labels[w] for w in s.children[x]):
                deps = s.labels[x][atom]
                w = len(s.labels)
                s.labels.append({a: deps})
                s.parent.append(x)
                s.role.append(r)
                s.edge.append(deps)
                s.children.append([])
                s.children[x].append(w)
                cnt.nodes += 1
                return True
    return False


def _search(s: State, clauses: Sequence[tuple], mode: str, cnt: Counter, out: list, level: int):
    """Return None when the branch has a clash-free completion (stored in out), and otherwise the
    set of branch points that the clashes depend on."""
    while True:  # @line L2
        app = _find_hyp(s, clauses, True)  # @line L3
        if app is not None:
            cnt.hyp += 1
            x, sigma, head, deps = app
            if not head:  # @line L4
                return deps
            _add(s, x, sigma, head[0], deps)  # @line L5
            continue
        if _exists_rule(s, mode, cnt):  # @line L6
            continue
        app = _find_hyp(s, clauses, False)
        if app is not None:  # @line L7
            cnt.hyp += 1
            x, sigma, head, deps = app
            clash: set = set()
            for atom in head:
                cnt.branches += 1
                s2 = s.copy()
                _add(s2, x, sigma, atom, deps | {level})
                d = _search(s2, clauses, mode, cnt, out, level + 1)  # @line L8
                if d is None:
                    return None
                if level not in d:
                    return d  # backjump: this choice took no part in the clash
                clash |= d - {level}
            return frozenset(clash)  # @line L9
        out.append(s)
        return None  # @line L10


def satisfiable_count(c: Concept, tbox: Sequence[GCI] = (), mode: str = "equal") -> tuple[bool, Counter, Optional[State]]:
    """Decide satisfiability of c with respect to the TBox. Also return the work counter and the
    final state of the open branch, if there is one."""
    root, clauses = clausify(c, tbox)  # @line L1
    cnt = Counter()
    out: list = []
    ok = _search(State(root), clauses, mode, cnt, out, 0) is None
    return ok, cnt, (out[0] if out else None)


def satisfiable(c: Concept, tbox: Sequence[GCI] = ()) -> bool:
    return satisfiable_count(c, tbox)[0]


def subsumes(c: Concept, d: Concept, tbox: Sequence[GCI] = ()) -> bool:
    return not satisfiable(("and", c, neg(d)), tbox)


def model_of(s: State) -> Interpretation:
    """The model of an open branch (equality blocking): the nodes that are not blocked, with each
    edge to a directly blocked node sent to its blocker. The root is element 0."""
    status, blocker = blocking(s, "equal")
    dom = [x for x in range(len(s.labels)) if not status[x]]
    concepts: dict[str, set] = {}
    roles: dict[str, set] = {}
    for x in dom:
        for a in s.labels[x]:
            if isinstance(a, str):
                concepts.setdefault(a, set()).add(x)
        for w in s.children[x]:
            roles.setdefault(s.role[w], set()).add((x, blocker.get(w, w)))
    return Interpretation(dom, concepts, roles)


def model(c: Concept, tbox: Sequence[GCI] = ()) -> Optional[Interpretation]:
    ok, _, s = satisfiable_count(c, tbox)
    return model_of(s) if ok else None
test_hypertableau.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hypertableau/. The authors are listed in prov/974KXE.jsonl.
"""Tests of the hypertableau calculus against the plain ALC tableau of alc_reference.py.

Every "satisfiable" answer is also checked on its own: the model built from the open branch must
put the root in the concept and satisfy every inclusion of the TBox, by the semantics in dl.py.
"""

import random

import alc_reference as ref
from dl import BOTTOM, atom, conj, disj, evaluate, exists, forall, is_model_of_tbox, neg
from hypertableau import clausify, model_of, satisfiable, satisfiable_count, subsumes

A, B, C, D, E, W = (atom(x) for x in "ABCDEW")


def check(c, tbox) -> bool:
    ok, _, s = satisfiable_count(c, tbox)
    assert ok == ref.satisfiable(c, tbox)
    if ok:
        m = model_of(s)
        assert 0 in evaluate(c, m) and is_model_of_tbox(m, tbox)
    return ok


def test_page_example() -> None:
    # not A and some r.some r.A, with some r.A subsumed by A: unsatisfiable without any choice.
    c = conj(neg(A), exists("r", exists("r", A)))
    tbox = [(exists("r", A), A)]
    root, clauses = clausify(c, tbox)
    assert len(clauses) == 4
    assert (frozenset(), ("r",), (frozenset({"A"}),), (("x", "A"),)) in clauses
    ok, cnt, _ = satisfiable_count(c, tbox)
    assert not ok and cnt.nodes == 2 and cnt.branches == 0 and cnt.hyp == 5
    r_ok, r_cnt = ref.satisfiable_count(c, tbox)
    assert not r_ok and r_cnt.nodes == 3 and r_cnt.branches == 7


def test_clause_shapes() -> None:
    # A and B subsumed by C or for all r.D: one clause, two head atoms, one successor variable.
    _, clauses = clausify(A, [(conj(A, B), disj(C, forall("r", D)))])
    assert (frozenset({"A", "B"}), ("r",), (frozenset(),), (("x", "C"), ("y", 0, "D"))) in clauses
    # for all r.not A in a head goes to the body as A(y).
    _, clauses = clausify(A, [(B, forall("r", neg(A)))])
    assert (frozenset({"B"}), ("r",), (frozenset({"A"}),), ()) in clauses


def test_cyclic_tbox_needs_blocking() -> None:
    ok, cnt, s = satisfiable_count(A, [(A, exists("r", A))])
    assert ok and cnt.nodes == 1
    m = model_of(s)
    assert m.domain == [0] and m.roles["r"] == {(0, 0)}
    assert check(A, [(A, exists("r", A))])


def test_subset_blocking_is_unsound() -> None:
    # The child made for some r.W has the label {W, some r.B}, a subset of the root label. Subset
    # blocking stops there and misses that its B-successor forces A, which the root forbids.
    c = conj(A, W, exists("r", W), forall("r", neg(A)))
    tbox = [(W, exists("r", B)), (exists("r", B), A)]
    assert not ref.satisfiable(c, tbox)
    assert not satisfiable_count(c, tbox, "equal")[0]
    assert satisfiable_count(c, tbox, "subset")[0]


def test_backjumping() -> None:
    # m independent choices, then a choice whose both sides clash on their own.
    for m in range(1, 9):
        c = conj(*[disj(atom(f"B{i}"), atom(f"C{i}")) for i in range(m)], disj(D, E), neg(D), neg(E))
        ok, cnt, _ = satisfiable_count(c)
        assert not ok and cnt.branches == m + 2


def test_or_branching_family() -> None:
    # B_i subsumed by C_i for i < m, and A subsumed by some r.D with D unsatisfiable. The plain
    # tableau adds not B_i or C_i to every node and tries 2^m completions of the root; the
    # clauses B_i(x) -> C_i(x) never fire.
    last = 0
    for m in range(0, 6):
        tbox = [(atom(f"B{i}"), atom(f"C{i}")) for i in range(m)] + [(A, exists("r", D)), (D, E), (E, BOTTOM)]
        ok, cnt, _ = satisfiable_count(A, tbox)
        assert not ok and cnt.nodes == 1 and cnt.branches == 0 and cnt.hyp == 3
        r_ok, r_cnt = ref.satisfiable_count(A, tbox)
        assert not r_ok and r_cnt.nodes == 2 ** m + 1 and r_cnt.branches > last
        last = r_cnt.branches


def rand_concept(rng: random.Random, d: int, cn, rn):
    if d == 0 or rng.random() < 0.3:
        a = atom(rng.choice(cn))
        return neg(a) if rng.random() < 0.4 else a
    k = rng.random()
    if k < 0.25:
        return conj(rand_concept(rng, d - 1, cn, rn), rand_concept(rng, d - 1, cn, rn))
    if k < 0.5:
        return disj(rand_concept(rng, d - 1, cn, rn), rand_concept(rng, d - 1, cn, rn))
    if k < 0.75:
        return exists(rng.choice(rn), rand_concept(rng, d - 1, cn, rn))
    if k < 0.9:
        return forall(rng.choice(rn), rand_concept(rng, d - 1, cn, rn))
    return neg(rand_concept(rng, d - 1, cn, rn))


def run_random(seed: int, count: int, cn, rn) -> list[int]:
    rng = random.Random(seed)
    seen = [0, 0]
    for _ in range(count):
        c = rand_concept(rng, 3, cn, rn)
        tbox = [(rand_concept(rng, 2, cn, rn), rand_concept(rng, 2, cn, rn)) for _ in range(rng.randint(0, 3))]
        seen[check(c, tbox)] += 1
    return seen


def test_random_one_role() -> None:
    unsat, sat = run_random(1, 2000, ["A", "B"], ["r"])
    assert unsat >= 150 and sat >= 1500


def test_random_two_roles() -> None:
    unsat, sat = run_random(6, 1000, ["A", "B", "C"], ["r", "s"])
    assert unsat >= 40 and sat >= 800


def test_subsumption() -> None:
    tbox = [(exists("r", A), A)]
    assert subsumes(exists("r", exists("r", A)), A, tbox)
    assert not subsumes(A, exists("r", A), tbox)

History

Hyperresolution is due to Robinson (1965); hyper tableaux for first-order clauses were studied by Baumgartner, Furbach and Niemelä in the 1990s. Motik, Shearer and Horrocks (2009) adapted the idea to description logics: they defined DL-clauses, the Hyp-rule and anywhere pairwise blocking, proved the calculus correct for expressive logics with inverse roles, nominals and number restrictions, and showed with the HermiT reasoner that it classifies many ontologies faster than tableau reasoners of the time. HermiT is one of the standard reasoners for OWL 2.

References

  1. Boris Motik, Rob Shearer and Ian Horrocks, Hypertableau reasoning for description logics, Journal of Artificial Intelligence Research 36, 2009, pages 165 to 228 (Table 4 on page 192 for the translation into DL-clauses, Definition 7 on page 193 and Table 5 on page 196 for the rules, Section 3.1.1 for the example with some R.A subsumed by A, Section 3.2.2 for anywhere blocking)

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.worst
  • a full proof of space.extra
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
  • at least three sources
  • a scene preset for the example