Algorithm Search⌘K

Algorithmcore

Tableau algorithm for ALC

Also called Schmidt-Schauss-Smolka tableau, DL tableau.

Tries to build a model of a concept in negation normal form by expansion rules for and, or, some and all, and reports a clash if none exists.

Time
2^O(n^2) worst2^2^O(n) general_tbox
Space
O(n^3) extra2^O(n) general_tbox
Where
n = the size of the concept and the TBox
Properties
builds modeldeterministicexactrecursive
Origin
Manfred Schmidt Schauß, Gert Smolka, 1991

The tableau algorithm for ALC decides whether an ALC concept is satisfiable with respect to a TBox by trying to build a tree-shaped model of it. It works on concepts in negation normal form, has one rule for each constructor, and backtracks over the choices of the ⊔-rule. Without a TBox it runs in polynomial space, and with a general TBox it needs blocking to stop. Most reasoners for expressive description logics use a form of it.

In plain words

You want to know if a description can be true of anything. The method tries to build an example. It starts with one object and writes down what the description says about it. For "this or that", it tries "this" first, and comes back to try "that" if the first try fails. If the object must have a link to some object of a kind, the method makes a new object at the end of a new link. If all linked objects must have a property, each new object gets it. A list with a fact and its opposite is a failure. If one try ends with no failure, it is an example, and the answer is yes. If all tries fail, the answer is no. Background rules can ask for an endless chain of objects. Then the method stops at an object that repeats an earlier one.

The problem

The input is an ALC concept CC and a TBox TT, a finite set of general concept inclusions D⊑ED \sqsubseteq E. The TBox can be empty. The question is whether some interpretation I=(ΔI,⋅I)I = (\Delta^I, \cdot^I) is a model of TT and has CI≠∅C^I \neq \emptyset. This is concept satisfiability. Concept subsumption reduces to it: C⊑TDC \sqsubseteq_T D holds if and only if C⊓¬DC \sqcap \neg D is not satisfiable with respect to TT.

A concept is in negation normal form (NNF) when ¬\neg occurs only in front of concept names. Each concept has an equivalent one in NNF of linear size: push ¬\neg inward with the De Morgan laws, ¬∃r.C≡∀r.¬C\neg \exists r.C \equiv \forall r.\neg C and ¬∀r.C≡∃r.¬C\neg \forall r.C \equiv \exists r.\neg C. For example, ¬(A⊓∃r.(B⊔¬∀s.C))\neg(A \sqcap \exists r.(B \sqcup \neg \forall s.C)) becomes ¬A⊔∀r.(¬B⊓∀s.C)\neg A \sqcup \forall r.(\neg B \sqcap \forall s.C).

The algorithm

Each node of the tree has a label, a set of concepts in NNF. The search is depth first. It first completes the label of a node with the ⊓-rule and the ⊔-rule, then makes one child for each ∃r.D\exists r.D in the label (the ∃-rule), and gives the child each EE with ∀r.E\forall r.E in the label (the ∀-rule). A label has a clash when it holds ⊥\bot, or AA and ¬A\neg A for a concept name AA. Each inclusion D⊑ED \sqsubseteq E of TT becomes the concept nnf(¬D⊔E)\mathrm{nnf}(\neg D \sqcup E), which goes into every label.

  1. SAT(C, T)
  2. 1C_T ← {nnf(¬D ⊔ E) : D ⊑ E in T}
  3. 2return NODE({nnf(C)} ∪ C_T, [])
  4. NODE(S, P) ▷ P is the list of the completed labels of the ancestors
  5. 3for each L in COMPLETIONS(S) do
  6. 4ok ← true
  7. 5for each ∃r.D in L do
  8. 6S′ ← {D} ∪ {E : ∀r.E in L} ∪ C_T
  9. 7if T is not empty and S′ ⊆ L″ for some L″ in P + [L] then continue ▷ blocked
  10. 8if NODE(S′, P + [L]) is false then ok ← false, and leave this loop
  11. 9if ok then return true
  12. 10return false
  13. COMPLETIONS(S) ▷ yields the clash-free completions of S, one at a time
  14. 11L ← the closure of S under the ⊓-rule: with D ⊓ E, add D and E
  15. 12if ⊥ is in L, or A and ¬A are in L for some A, then return
  16. 13if some D ⊔ E in L has D not in L and E not in L then
  17. 14yield each label of COMPLETIONS(L ∪ {D}), then each label of COMPLETIONS(L ∪ {E})
  18. 15else yield L

The ⊔-rule is the only choice point. COMPLETIONS returns the completions lazily, so NODE tries the next one only when a child of the current one fails. A node is blocked at line L7 when an ancestor, or the node itself, already holds every concept that the child would get. Then the child is not built, and the edge goes to that ancestor. Without a TBox, line L7 never blocks. The labels of the ancestors are final when line L7 tests them, because each label is complete before its children are made.

When SAT returns true, the successful calls give a model. The elements are the nodes, AIA^I is the set of nodes whose label holds AA, and rIr^I is the set of rr-edges, with each blocked edge sent to its blocking node.

Example

Take the concept (A⊔∃r.B)⊓¬A⊓∀r.(¬B⊔C)(A \sqcup \exists r.B) \sqcap \neg A \sqcap \forall r.(\neg B \sqcup C) with the empty TBox. It is already in NNF.

step node label and action
1 root ⊓-rule: {A⊔∃r.B, ¬A, ∀r.(¬B⊔C)}\{A \sqcup \exists r.B,\ \neg A,\ \forall r.(\neg B \sqcup C)\}
2 root ⊔-rule, first choice AA: clash with ¬A\neg A, backtrack
3 root second choice ∃r.B\exists r.B: the label is complete
4 child ∃-rule and ∀-rule: {B, ¬B⊔C}\{B,\ \neg B \sqcup C\}
5 child first choice ¬B\neg B: clash with BB, backtrack
6 child second choice CC: complete, no ∃, return true

The run expands 2 nodes and meets 2 clashes. The model has ΔI={0,1}\Delta^I = \{0, 1\}, rI={(0,1)}r^I = \{(0, 1)\}, BI=CI={1}B^I = C^I = \{1\} and AI=∅A^I = \emptyset, and the root 0 is an instance of the input concept.

With the TBox T={A⊑∃r.A}T = \{A \sqsubseteq \exists r.A\} and the concept AA, the root gets {A, ¬A⊔∃r.A}\{A,\ \neg A \sqcup \exists r.A\}. The choice ¬A\neg A clashes, so the root label becomes {A, ¬A⊔∃r.A, ∃r.A}\{A,\ \neg A \sqcup \exists r.A,\ \exists r.A\}. The child would get {A, ¬A⊔∃r.A}\{A,\ \neg A \sqcup \exists r.A\}, which is a subset of the root label, so line L7 blocks it. The model has one element in AIA^I with an rr-edge to itself. Without line L7 the search would make an endless chain of rr-successors.

Correctness

The algorithm is sound: when it returns true, the interpretation above is a model of TT and the root is in CIC^I. The proof is an induction on the concepts of each label, and it uses that each label is clash-free and complete for the ⊓-rule and the ⊔-rule. A blocked edge is safe because the blocking label holds all that the child would need. It is complete: if x∈CJx \in C^J in some model JJ of TT, then the choices that xx satisfies lead to a run that returns true, and each ∃r.D\exists r.D is matched by an rr-successor of xx in JJ. It terminates: without a TBox the role depth drops at each level, and with blocking the initial labels on one path are different subsets of a set of size O(n)O(n). The full proof is below.

Proof: The ALC tableau is sound, complete and terminates, with and without a general TBoxfull

We use the pseudocode of the page, lines L1 to L15. All concepts are in negation normal form (NNF). TT is a TBox, and CT={nnf(¬D⊔E):D⊑E∈T}\mathcal{C}_T = \{\mathrm{nnf}(\neg D \sqcup E) : D \sqsubseteq E \in T\} (line L1). Blocking is on when T≠∅T \neq \emptyset.

Let cl\mathrm{cl} be the set of all subconcepts of nnf(C)\mathrm{nnf}(C) and of the concepts in CT\mathcal{C}_T, and let m=∣cl∣m = |\mathrm{cl}|. Then mm is at most the sum of the sizes of these concepts, so m=O(n)m = O(n) for an input of size nn.

Lemma 0 (NNF). For every concept DD and every interpretation II, nnf(D)I=DI\mathrm{nnf}(D)^I = D^I.

Proof. By induction on the size of DD. The rules of nnf are the identities (¬¬D)I=DI(\neg \neg D)^I = D^I, (¬(D⊓E))I=(¬D⊔¬E)I(\neg(D \sqcap E))^I = (\neg D \sqcup \neg E)^I, (¬(D⊔E))I=(¬D⊓¬E)I(\neg(D \sqcup E))^I = (\neg D \sqcap \neg E)^I, (¬∃r.D)I=(∀r.¬D)I(\neg \exists r.D)^I = (\forall r.\neg D)^I, (¬∀r.D)I=(∃r.¬D)I(\neg \forall r.D)^I = (\exists r.\neg D)^I, (¬⊤)I=⊥I(\neg \top)^I = \bot^I and (¬⊥)I=⊤I(\neg \bot)^I = \top^I. Each one follows from the semantics: for example, x∉(∃r.D)Ix \notin (\exists r.D)^I if and only if no rr-successor of xx is in DID^I, if and only if every rr-successor of xx is in (¬D)I(\neg D)^I. Each rule calls nnf on smaller concepts, so the induction hypothesis applies. □\square

Lemma 1 (labels stay in cl). Every label that the algorithm builds is a subset of cl\mathrm{cl}.

Proof. The root label is {nnf(C)}∪CT⊆cl\{\mathrm{nnf}(C)\} \cup \mathcal{C}_T \subseteq \mathrm{cl}. Lines L11 and L14 add only a direct subconcept of a concept of the label. Line L6 puts in a child the subconcepts DD of ∃r.D\exists r.D and EE of ∀r.E\forall r.E, and the concepts of CT\mathcal{C}_T. Since cl\mathrm{cl} is closed under subconcepts, induction on the steps gives the claim. □\square

Termination

Lemma 2 (COMPLETIONS stops). A call COMPLETIONS(S)(S) makes at most 2m2^{m} recursive calls in total.

Proof. Line L14 makes a call only on L∪{D}L \cup \{D\} with D∉LD \notin L, so each nested call has a label with at least one more element of cl\mathrm{cl} than its caller. Labels have at most mm elements (Lemma 1), so the nesting depth is at most mm, and each call makes at most 2 calls. □\square

Lemma 3 (depth without a TBox). If T=∅T = \emptyset, a node at depth dd has a label of role depth at most rd(nnf(C))−d\mathrm{rd}(\mathrm{nnf}(C)) - d. So the depth of the tree is at most rd(nnf(C))\mathrm{rd}(\mathrm{nnf}(C)).

Proof. The ⊓-rule and the ⊔-rule add subconcepts, which do not have a larger role depth. A child label (line L6, with CT=∅\mathcal{C}_T = \emptyset) holds only concepts DD with ∃r.D\exists r.D or ∀r.D\forall r.D in the parent label, and each has a role depth at least 1 smaller than the parent concept. So the largest role depth drops by at least 1 at each level. A label with role depth 0 has no ∃r.D\exists r.D, so line L5 makes no child. □\square

Lemma 4 (depth with blocking). If blocking is on, every path from the root has at most 2m2^{m} nodes that are expanded.

Proof. Let vv be a node that line L8 expands, with initial label SvS_v, and let uu be an ancestor of vv with initial label SuS_u and completed label LuL_u. Line L7 did not block vv, so Sv⊈LuS_v \not\subseteq L_u. COMPLETIONS only adds concepts, so Su⊆LuS_u \subseteq L_u, and so Sv≠SuS_v \neq S_u. Thus the initial labels on one path are pairwise different subsets of cl\mathrm{cl}, and there are at most 2m2^m of them. The number of subsets of cl\mathrm{cl} that are not yet used on the path drops by exactly 1 at each level. □\square

Theorem 1 (termination). SAT(C,T)(C, T) stops. With T=∅T = \emptyset the run takes at most 2O(n2)2^{O(n^2)} steps. With blocking it takes at most 22O(n)2^{2^{O(n)}} steps.

Proof. A completed label has at most mm concepts of the form ∃r.D\exists r.D, so line L5 makes at most mm calls for one completion. By Lemma 2 there are at most 2m2^m completions of one label, each built in time polynomial in mm. Let N(h)N(h) be the largest number of steps of a call of NODE whose subtree has height at most hh. Then N(h)≤2m⋅(p(m)+m⋅N(h−1))N(h) \le 2^m \cdot (p(m) + m \cdot N(h - 1)) for a polynomial pp, so N(h)≤(2m(p(m)+m))h+1N(h) \le (2^m (p(m) + m))^{h + 1}. With T=∅T = \emptyset, Lemma 3 gives h≤rd(nnf(C))≤mh \le \mathrm{rd}(\mathrm{nnf}(C)) \le m, so the time is 2O(m2)=2O(n2)2^{O(m^2)} = 2^{O(n^2)}. With blocking, Lemma 4 gives h≤2mh \le 2^m, so the time is 2O(m⋅2m)=22O(n)2^{O(m \cdot 2^m)} = 2^{2^{O(n)}}. Both bounds are finite. □\square

Soundness

Theorem 2 (soundness). If SAT(C,T)(C, T) returns true, then the interpretation II built from the successful calls is a model of TT in which the root is an instance of CC.

Proof. A call of NODE that returns true does so at line L9 for one completion LL, its last one, and each call that line L8 made for LL returned true. Take as nodes the root call and, below each node, the calls of line L8 made for its last completion. Call this the tree of successful calls. Each node uu in it was called with the last completions of all its ancestors in PP, because a call for an earlier completion of an ancestor is not in the tree. The tree has these properties, by lines L3 to L9:

  • (P1) Each node uu has a label LuL_u, its last completion, that COMPLETIONS yielded. So LuL_u has no clash (line L12): ⊥∉Lu\bot \notin L_u, and no AA with A,¬A∈LuA, \neg A \in L_u. It is closed under ⊓: if D⊓E∈LuD \sqcap E \in L_u then D,E∈LuD, E \in L_u (line L11). It is complete for ⊔: if D⊔E∈LuD \sqcup E \in L_u then D∈LuD \in L_u or E∈LuE \in L_u (lines L13 and L15).
  • (P2) CT⊆Lu\mathcal{C}_T \subseteq L_u for each node uu, because each initial label holds CT\mathcal{C}_T (lines L2 and L6) and COMPLETIONS only adds concepts.
  • (P3) For each ∃r.D∈Lu\exists r.D \in L_u, line L7 or line L8 gives an edge u→rtu \xrightarrow{r} t, where tt is the child call of line L8, or the node whose label blocks the child at line L7. In both cases S⊆LtS \subseteq L_t for the set SS of line L6. Every edge comes from this step.

A blocking label is in P+[Lu]P + [L_u], so it is the label of uu or of an ancestor of uu, and by the remark above it is the last completion of that node. So tt is a node of the tree, and S⊆LtS \subseteq L_t. Let ΔI\Delta^I be the set of nodes, AI={u:A∈Lu}A^I = \{u : A \in L_u\} and rIr^I the set of rr-edges.

Claim: for every node uu and every D∈LuD \in L_u, u∈DIu \in D^I. The proof is by induction on the size of DD.

  • D=⊤D = \top: true. D=⊥D = \bot: impossible by (P1). D=AD = A: by the definition of AIA^I. D=¬AD = \neg A: A∉LuA \notin L_u by (P1), so u∉AIu \notin A^I.
  • D=D1⊓D2D = D_1 \sqcap D_2: both are in LuL_u by (P1), and the induction hypothesis applies.
  • D=D1⊔D2D = D_1 \sqcup D_2: one of them is in LuL_u by (P1).
  • D=∃r.ED = \exists r.E: by (P3) there is an edge u→rtu \xrightarrow{r} t with E∈S⊆LtE \in S \subseteq L_t, so t∈EIt \in E^I by the induction hypothesis, and u∈DIu \in D^I.
  • D=∀r.ED = \forall r.E: each rr-successor tt of uu in II comes from an edge of (P3), made for some ∃r.D′∈Lu\exists r.D' \in L_u. Its set SS holds every E′E' with ∀r.E′∈Lu\forall r.E' \in L_u, so E∈S⊆LtE \in S \subseteq L_t, and t∈EIt \in E^I by the induction hypothesis.

The root label holds nnf(C)\mathrm{nnf}(C), so the root is in nnf(C)I=CI\mathrm{nnf}(C)^I = C^I (Lemma 0). For an inclusion D⊑ED \sqsubseteq E of TT and any node uu, (P2) and the claim give u∈nnf(¬D⊔E)I=ΔI∖DI∪EIu \in \mathrm{nnf}(\neg D \sqcup E)^I = \Delta^I \setminus D^I \cup E^I. So DI⊆EID^I \subseteq E^I, and II is a model of TT. □\square

The model has as many elements as the tree of successful calls has nodes, so it is finite. This also proves the finite model property of ALC with general TBoxes.

Completeness

Theorem 3 (completeness). If CC has an instance in some model JJ of TT, then SAT(C,T)(C, T) returns true.

Proof. Say that an element x∈ΔJx \in \Delta^J satisfies a set SS when x∈DJx \in D^J for all D∈SD \in S. Every element of JJ satisfies CT\mathcal{C}_T: for D⊑E∈TD \sqsubseteq E \in T, DJ⊆EJD^J \subseteq E^J, so each element is in (¬D⊔E)J=nnf(¬D⊔E)J(\neg D \sqcup E)^J = \mathrm{nnf}(\neg D \sqcup E)^J (Lemma 0).

Step 1. If xx satisfies SS, then COMPLETIONS(S)(S) yields at least one label that xx satisfies. By induction on the depth of recursion that is left, which is finite by Lemma 2. The closure of line L11 keeps the property, since x∈(D⊓E)Jx \in (D \sqcap E)^J gives x∈DJx \in D^J and x∈EJx \in E^J. Then line L12 finds no clash, because x∉⊥Jx \notin \bot^J and xx cannot be in both AJA^J and (¬A)J(\neg A)^J. If line L13 picks D⊔ED \sqcup E, then x∈DJx \in D^J or x∈EJx \in E^J, so one of the two calls of line L14 gets a set that xx satisfies, and the induction hypothesis gives a label. Otherwise line L15 yields LL itself.

Step 2. If xx satisfies SS, then NODE(S,P)(S, P) returns true, for every list PP of ancestors. By induction on the height of the recursion below this call, which is finite by Theorem 1. By Step 1 the loop of line L3 reaches a completion LL that xx satisfies, unless it returned true for an earlier completion, and then we are done. For each ∃r.D∈L\exists r.D \in L, xx has an rr-successor yy in DJD^J. Then yy is in EJE^J for every ∀r.E∈L\forall r.E \in L, and yy satisfies CT\mathcal{C}_T, so yy satisfies the set S′S' of line L6. If line L7 blocks the child, the loop goes on. Otherwise the induction hypothesis says that NODE(S′,…)(S', \ldots) returns true. So no call fails, the loop of line L5 ends with $ok = $ true, and line L9 returns true.

The element of JJ in CJC^J satisfies {nnf(C)}∪CT\{\mathrm{nnf}(C)\} \cup \mathcal{C}_T (Lemma 0), so line L2 returns true. □\square

Corollary. SAT(C,T)(C, T) returns true if and only if CC is satisfiable with respect to TT. So C⊑TDC \sqsubseteq_T D holds if and only if SAT(C⊓¬D,T)(C \sqcap \neg D, T) returns false.

Space with an empty TBox

With T=∅T = \emptyset the recursion has depth at most rd(nnf(C))≤m\mathrm{rd}(\mathrm{nnf}(C)) \le m (Lemma 3). Each level of NODE holds its list of ancestors, one completed label of at most mm concepts, and the stack of COMPLETIONS, which has at most mm open calls (Lemma 2), each with a label of at most mm concepts. A concept in a label is a reference to a subtree of the input. So the space is O(m3)=O(n3)O(m^3) = O(n^3) words, and the procedure runs in polynomial space. This gives the upper bound of the theorem that ALC concept satisfiability without a TBox is PSPACE-complete (Schmidt-Schauß and Smolka 1991; see ALC is PSPACE-complete). With blocking, the list of ancestors can hold 2m2^m labels, so this bound does not hold.

The bounds of the problem

The bounds above are bounds of this algorithm. The problem has these exact bounds.

  • Empty TBox: PSPACE-complete. The upper bound is the space bound above. Schmidt-Schauß and Smolka (1991) also prove the lower bound, and it also follows from the PSPACE-hardness of the modal logic K (Ladner 1977) by the correspondence of Schild (1991). See ALC is PSPACE-complete.
  • General TBox: EXPTIME-complete (Schild 1991, from the EXPTIME-hardness of propositional dynamic logic by Fischer and Ladner 1979, and the EXPTIME upper bound of Pratt 1979). See ALC with general TBoxes is EXPTIME-complete. The search of this page takes 22O(n)2^{2^{O(n)}} time on such inputs (Theorem 1), so it is not worst-case optimal. Global caching of labels brings it to 2O(n)2^{O(n)} (Donini and Massacci 2000, Goré and Nguyen 2013). The Description Logic Handbook (second edition, Chapter 2, Section 2.3, and Chapter 3) and Baader, Horrocks, Lutz and Sattler (2017, Chapter 4, Section 4.2, and Chapter 5) give both results.

Complexity

Let nn be the size of the input, and m=O(n)m = O(n) the number of its subconcepts. A label has at most mm concepts, and one label has at most 2m2^m completions.

  • Empty TBox. The tree has depth at most the role depth of CC. The search keeps only the current path, so the space is O(n3)O(n^3) words. The time is 2O(n2)2^{O(n^2)} in the worst case. Concept satisfiability in ALC without a TBox is PSPACE-complete (ALC is PSPACE-complete), and this search meets that upper bound.
  • General TBox. A path can have 2m2^m nodes before blocking stops it, so the time is 22O(n)2^{2^{O(n)}} in the worst case and the space is 2O(n)2^{O(n)}. The problem is EXPTIME-complete (ALC with general TBoxes is EXPTIME-complete), so this form of the algorithm is not worst-case optimal. It is a double exponential bound for a deterministic search.

Properties

  • Builds a model. A run that returns true gives a finite model with at most one element for each expanded node. So ALC with a general TBox has the finite model property.
  • Tree models. Without blocking the model is a tree. With blocking it is a tree with some edges back to ancestors.
  • One kind of choice. Only the ⊔-rule branches, and the search must undo it on failure. The order of the other rules does not change the answer.
  • One branch at a time. The search works on one path of the tree at a time, which is why the empty TBox case fits in polynomial space.
  • Modal logic view. ALC is a notational variant of the modal logic K with many modalities (see ALC and modal logic K), and the model is a Kripke structure. The algorithm is then a tableau for K.

Variants and improvements

  • ABox consistency. Start with one node for each individual of the ABox, with its assertions, and the role assertions as edges. The rules are the same. Blocking applies only to the new nodes.
  • Acyclic TBoxes. Replace a defined name by its definition only when it appears in a label (lazy unfolding). This keeps the polynomial space bound, while a full unfolding first can make the concept exponentially larger.
  • Exponential time. Cache the result for each label that was seen, or let all nodes with the same label share one node. With such global caching the time is 2O(n)2^{O(n)}, which is worst-case optimal (Donini and Massacci 2000, Goré and Nguyen 2013).
  • Optimizations in reasoners. Absorption moves inclusions A⊑EA \sqsubseteq E with a concept name on the left into lazy unfolding, so the large disjunctions of line L1 do not come up at each node. Semantic branching adds ¬D\neg D in the second branch of a choice. Backjumping goes back to the last choice that caused the clash, as in conflict-directed backjumping.
  • More expressive logics. Number restrictions, inverse roles, role hierarchies and nominals each add rules and change the blocking condition. This leads to the tableaux for SHIQ and SROIQ. The hypertableau calculus makes less nondeterminism from the TBox.

When to use it

Use it for an expressive description logic with disjunction and full negation, where you need satisfiability, subsumption or consistency, and where a model is a useful output. For the EL family, EL classification runs in polynomial time and is much faster. For logics without disjunction and negation, structural subsumption can be enough.

Pitfalls

  • Forgetting NNF. The ⊔-rule and the clash test are correct only on concepts in NNF. Convert the concept and each TBox concept first.
  • No blocking with a TBox. With a cyclic or general TBox, the search without blocking does not stop on an input such as T={A⊑∃r.A}T = \{A \sqsubseteq \exists r.A\}.
  • Subset blocking in larger logics. With inverse roles, a child can change the label of its parent, and subset blocking is not sound. Such logics need equality, dynamic or pairwise blocking (see blocking).
  • Keeping the whole tree. A program that keeps every node to return a model, as the code here does, can use exponential memory even with an empty TBox. Keep only the current path when you only need the answer.

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_tableau_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alc-tableau-algorithm/. The authors are listed in prov/W9NV76.jsonl.
"""The tableau algorithm for ALC concept satisfiability, with an optional general TBox.

The search builds a tree of nodes depth first. Each node has a label, a set of concepts in negation
normal form. The and-rule and the or-rule complete the label of one node (the or-rule with
backtracking), then the exists-rule makes one child for each existential restriction, and the
all-rule puts the matching universal restrictions into the child. With a nonempty TBox, every node
also gets the concept nnf(not C or D) of each inclusion C subsumed by D, and subset blocking against
the ancestors stops the search. When the answer is yes, the result holds a finite model.
"""

from dataclasses import dataclass, field
from typing import Iterator, Optional, Sequence

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


class NonTermination(Exception):
    """Raised when a search without blocking passes the depth limit."""


@dataclass
class Stats:
    nodes: int = 0  # calls of NODE, one for each node that is expanded
    blocked: int = 0  # children that were not created because an ancestor blocks them
    clashes: int = 0  # completions that ended in a clash
    depth: int = 0  # the largest depth of a node, the root has depth 0


@dataclass
class Result:
    satisfiable: bool
    model: Optional[Interpretation] = None  # when satisfiable: a model, and element 0 is in the concept
    stats: Stats = field(default_factory=Stats)


class _Node:
    __slots__ = ("label", "edges")

    def __init__(self, label: frozenset) -> None:
        self.label = label
        self.edges: list[tuple[str, "_Node"]] = []


def _completions(s: frozenset, st: Stats) -> Iterator[frozenset]:
    """Yield the clash-free completions of the label s under the and-rule and the or-rule."""
    lab: set = set()
    stack = list(s)
    while stack:
        c = stack.pop()
        if c in lab:
            continue
        lab.add(c)
        if c[0] == "and":  # @line L11
            stack.append(c[1])
            stack.append(c[2])
    if BOTTOM in lab or any(c[0] == "not" and c[1] in lab for c in lab):  # @line L12
        st.clashes += 1
        return
    pending = [c for c in lab if c[0] == "or" and c[1] not in lab and c[2] not in lab]
    if pending:  # @line L13
        # Any choice of the disjunction is correct. Take first a disjunction with a disjunct that
        # clashes at once (bottom, or a literal whose complement is in the label), so that only one
        # branch is left. Break ties by the printed form, so that runs are repeatable.
        def dead(d: Concept) -> bool:
            return d == BOTTOM or (d[0] == "not" and d[1] in lab) or (d[0] == "atom" and ("not", d) in lab)

        c = min(pending, key=lambda c: (not (dead(c[1]) or dead(c[2])), show(c)))
        yield from _completions(frozenset(lab | {c[1]}), st)  # @line L14
        yield from _completions(frozenset(lab | {c[2]}), st)
    else:
        yield frozenset(lab)  # @line L15


def _node(s: frozenset, path: list, tc: frozenset, blocking: bool, max_depth: int, st: Stats) -> Optional[_Node]:
    """NODE(S, P): return the root of a model piece for the label s, or None when there is none."""
    st.nodes += 1
    st.depth = max(st.depth, len(path))
    if not blocking and len(path) > max_depth:
        raise NonTermination(f"depth {len(path)} without blocking")
    for lab in _completions(s, st):  # @line L3
        node = _Node(lab)
        ok = True  # @line L4
        for c in sorted((c for c in lab if c[0] == "some"), key=show):  # @line L5
            r = c[1]
            child = frozenset({c[2]} | {d[2] for d in lab if d[0] == "all" and d[1] == r}) | tc  # @line L6
            if blocking:
                blocker = next((a for a in path + [node] if child <= a.label), None)  # @line L7
                if blocker is not None:
                    st.blocked += 1
                    node.edges.append((r, blocker))
                    continue
            sub = _node(child, path + [node], tc, blocking, max_depth, st)  # @line L8
            if sub is None:
                ok = False
                break
            node.edges.append((r, sub))
        if ok:
            return node  # @line L9
    return None  # @line L10


def _model(root: _Node) -> Interpretation:
    ids: dict[int, int] = {id(root): 0}
    order = [root]
    k = 0
    while k < len(order):
        for _, t in order[k].edges:
            if id(t) not in ids:
                ids[id(t)] = len(order)
                order.append(t)
        k += 1
    conc: dict[str, set] = {}
    roles: dict[str, set] = {}
    for x, n in enumerate(order):
        for c in n.label:
            if c[0] == "atom":
                conc.setdefault(c[1], set()).add(x)
        for r, t in n.edges:
            roles.setdefault(r, set()).add((x, ids[id(t)]))
    return Interpretation(list(range(len(order))), conc, roles)


def tbox_concepts(tbox: Sequence[GCI]) -> frozenset:
    """The concepts nnf(not C or D), one for each inclusion C subsumed by D."""
    return frozenset(nnf(disj(neg(c), d)) for c, d in tbox)  # @line L1


def tableau(c: Concept, tbox: Sequence[GCI] = (), blocking: Optional[bool] = None, max_depth: int = 60) -> Result:
    """SAT(C, T). Decide whether c is satisfiable with respect to the TBox.

    Blocking is on by default when the TBox is not empty. With blocking off and a cyclic TBox the
    search need not stop; it raises NonTermination at max_depth.
    """
    tc = tbox_concepts(tbox)
    if blocking is None:
        blocking = bool(tc)
    st = Stats()
    root = _node(frozenset({nnf(c)}) | tc, [], tc, blocking, max_depth, st)  # @line L2
    if root is None:
        return Result(False, None, st)
    return Result(True, _model(root), st)


def is_satisfiable(c: Concept, tbox: Sequence[GCI] = ()) -> bool:
    return tableau(c, tbox).satisfiable


def subsumes(c: Concept, d: Concept, tbox: Sequence[GCI] = ()) -> bool:
    """True when c is subsumed by d with respect to the TBox: c and not d is unsatisfiable."""
    return not tableau(conj(c, neg(d)), tbox).satisfiable
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)
test_alc_tableau_algorithm.py 264 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alc-tableau-algorithm/. The authors are listed in prov/W9NV76.jsonl.
"""Tests of the ALC tableau against the semantics.

Two kinds of reference are used.
1. Evaluation over every interpretation with at most 3 elements (dl.interpretations). When the
   tableau says "satisfiable", the test checks the model that the tableau returns, by evaluation.
   When the tableau says "unsatisfiable", the test checks that no interpretation with at most 3
   elements is a model. A failed search over small domains is not a proof of unsatisfiability: a
   satisfiable ALC concept can need more elements (test_small_search_is_not_a_proof). So this check
   can catch a wrong "unsatisfiable", but it cannot confirm a right one. The proof is in
   proofs/correctness.md.
2. Known subsumptions from the textbooks, with and without a general TBox.
"""

import random
from itertools import permutations

import pytest

import dl
from alc_tableau_algorithm import NonTermination, is_satisfiable, subsumes, tableau
from dl import TOP, BOTTOM, atom, conj, disj, exists, forall, neg

A, B, C = atom("A"), atom("B"), atom("C")


def rand_concept(rng: random.Random, depth: int, atoms=("A", "B"), roles=("r",)) -> tuple:
    if depth == 0 or rng.random() < 0.25:
        x = rng.random()
        if x < 0.06:
            return TOP
        if x < 0.09:
            return BOTTOM
        a = atom(rng.choice(atoms))
        return neg(a) if rng.random() < 0.4 else a
    op = rng.choice(["not", "and", "and", "or", "or", "some", "some", "all"])
    if op == "not":
        return neg(rand_concept(rng, depth - 1, atoms, roles))
    if op in ("and", "or"):
        f = conj if op == "and" else disj
        return f(rand_concept(rng, depth - 1, atoms, roles), rand_concept(rng, depth - 1, atoms, roles))
    q = exists if op == "some" else forall
    return q(rng.choice(roles), rand_concept(rng, depth - 1, atoms, roles))


def _canonical(i: dl.Interpretation, cn, rn) -> tuple:
    n = len(i.domain)
    best = None
    for p in permutations(range(n)):
        key = (n,
               tuple(tuple(sorted(p[x] for x in i.concepts.get(a, ()))) for a in cn),
               tuple(tuple(sorted((p[x], p[y]) for x, y in i.roles.get(r, ()))) for r in rn))
        if best is None or key < best:
            best = key
    return best


_SMALL: dict = {}


def small_interpretations(cn=("A", "B"), rn=("r",), max_size=3) -> list:
    """All interpretations with at most max_size elements, one from each isomorphism class.
    ALC concepts and inclusions do not change under a renaming of the elements."""
    key = (cn, rn, max_size)
    if key not in _SMALL:
        seen = set()
        out = []
        for i in dl.interpretations(cn, rn, max_size):
            k = _canonical(i, cn, rn)
            if k not in seen:
                seen.add(k)
                out.append(i)
        _SMALL[key] = out
    return _SMALL[key]


def small_model_exists(c, tbox=(), cn=("A", "B"), rn=("r",), max_size=3) -> bool:
    return any(dl.evaluate(c, i) and dl.is_model_of_tbox(i, tbox) for i in small_interpretations(cn, rn, max_size))


def check_result(c, tbox=(), cn=("A", "B"), rn=("r",), max_size=3) -> bool:
    res = tableau(c, tbox)
    if res.satisfiable:
        m = res.model
        assert 0 in dl.evaluate(c, m), dl.show(c)
        assert dl.is_model_of_tbox(m, tbox), dl.show(c)
    else:
        assert not small_model_exists(c, tbox, cn, rn, max_size), dl.show(c)
    return res.satisfiable


def test_small_search_is_not_a_proof() -> None:
    # Four elements with four different types along an r-chain: satisfiable, but no model has 3 elements.
    c = conj(A, neg(B), exists("r", conj(neg(A), B, exists("r", conj(neg(A), neg(B), exists("r", conj(A, B)))))))
    res = tableau(c)
    assert res.satisfiable and len(res.model.domain) == 4
    assert not small_model_exists(c)


def test_helper_counts_and_nnf() -> None:
    # 2^(n*2 + n*n) interpretations for each n: 8 + 256 + 32768.
    assert sum(1 for _ in dl.interpretations(("A", "B"), ("r",), 3)) == 8 + 256 + 32768
    rng = random.Random(7)
    small = small_interpretations(max_size=2)
    for _ in range(200):
        c = rand_concept(rng, 4)
        n = dl.nnf(c)
        assert dl.is_nnf(n)
        assert all(dl.evaluate(c, i) == dl.evaluate(n, i) for i in small)


def test_basic_cases() -> None:
    assert is_satisfiable(A)
    assert not is_satisfiable(conj(A, neg(A)))
    assert not is_satisfiable(BOTTOM)
    assert is_satisfiable(TOP)
    assert not is_satisfiable(conj(exists("r", A), forall("r", neg(A))))
    assert is_satisfiable(conj(exists("r", A), forall("r", B)))
    assert is_satisfiable(conj(forall("r", BOTTOM), A))  # no successor at all
    assert not is_satisfiable(conj(exists("r", TOP), forall("r", BOTTOM)))
    # The worked example of the page: one or-choice fails, the other succeeds.
    ex = conj(exists("r", A), forall("r", disj(neg(A), B)), forall("r", neg(B)))
    assert not is_satisfiable(ex)
    ex2 = conj(disj(A, exists("r", B)), neg(A), forall("r", disj(neg(B), C)))
    res = tableau(ex2)
    assert res.satisfiable and len(res.model.domain) == 2


def test_textbook_subsumptions_empty_tbox() -> None:
    # Equivalences and subsumptions of ALC (Baader et al. 2017, chapter 2; Handbook, chapter 2).
    def equiv(x, y):
        return subsumes(x, y) and subsumes(y, x)

    assert equiv(forall("r", conj(A, B)), conj(forall("r", A), forall("r", B)))
    assert equiv(exists("r", disj(A, B)), disj(exists("r", A), exists("r", B)))
    assert equiv(neg(exists("r", A)), forall("r", neg(A)))
    assert subsumes(conj(exists("r", A), forall("r", B)), exists("r", conj(A, B)))
    assert subsumes(exists("r", conj(A, B)), exists("r", A))
    assert not subsumes(exists("r", A), exists("r", conj(A, B)))
    assert not subsumes(forall("r", A), exists("r", A))  # an element with no successor
    assert subsumes(conj(forall("r", A), exists("r", TOP)), exists("r", A))
    assert subsumes(disj(forall("r", A), forall("r", B)), forall("r", disj(A, B)))
    assert not subsumes(forall("r", disj(A, B)), disj(forall("r", A), forall("r", B)))
    assert subsumes(BOTTOM, A) and subsumes(A, TOP)


FAMILY_NAMES = ["Person", "Female", "Woman", "Man", "Mother", "Father", "Parent", "Grandmother", "MotherWithoutDaughter", "Wife"]
P = {n: atom(n) for n in FAMILY_NAMES}


def family_tbox() -> list:
    """The family TBox of the Description Logic Handbook, chapter 2, without the number restriction.
    Each definition A = D gives two inclusions."""
    hc = "hasChild"
    defs = [
        ("Woman", conj(P["Person"], P["Female"])),
        ("Man", conj(P["Person"], neg(P["Woman"]))),
        ("Mother", conj(P["Woman"], exists(hc, P["Person"]))),
        ("Father", conj(P["Man"], exists(hc, P["Person"]))),
        ("Parent", disj(P["Father"], P["Mother"])),
        ("Grandmother", conj(P["Mother"], exists(hc, P["Parent"]))),
        ("MotherWithoutDaughter", conj(P["Mother"], forall(hc, neg(P["Woman"])))),
        ("Wife", conj(P["Woman"], exists("hasHusband", P["Man"]))),
    ]
    out = []
    for a, d in defs:
        out.append((P[a], d))
        out.append((d, P[a]))
    return out


def test_family_tbox() -> None:
    t = family_tbox()
    yes = [("Woman", "Person"), ("Mother", "Person"), ("Mother", "Parent"), ("Father", "Parent"),
           ("Grandmother", "Parent"), ("Grandmother", "Mother"), ("Parent", "Person"),
           ("MotherWithoutDaughter", "Mother"), ("Wife", "Woman")]
    no = [("Person", "Woman"), ("Parent", "Mother"), ("Mother", "Grandmother"), ("Man", "Father"),
          ("Wife", "Mother"), ("Mother", "MotherWithoutDaughter")]
    for x, y in yes:
        assert subsumes(P[x], P[y], t), (x, y)
    for x, y in no:
        res = tableau(conj(P[x], neg(P[y])), t)
        assert res.satisfiable, (x, y)
        m = res.model
        assert dl.is_model_of_tbox(m, t)
        assert 0 in dl.evaluate(P[x], m) and 0 not in dl.evaluate(P[y], m)
    assert not is_satisfiable(conj(P["Man"], P["Woman"]), t)
    assert subsumes(P["Parent"], exists("hasChild", P["Person"]), t)
    assert subsumes(P["Grandmother"], exists("hasChild", exists("hasChild", P["Person"])), t)
    # Without the TBox the names are unrelated.
    assert not subsumes(P["Mother"], P["Person"])


def test_general_tbox_needs_blocking() -> None:
    t = [(A, exists("r", A))]
    res = tableau(A, t)
    assert res.satisfiable and res.stats.blocked >= 1
    assert dl.is_model_of_tbox(res.model, t) and 0 in dl.evaluate(A, res.model)
    with pytest.raises(NonTermination):
        tableau(A, t, blocking=False)
    # A is subsumed by C. The first inclusion is cyclic, so the search for A and not C needs blocking.
    t2 = [(A, exists("r", A)), (A, B), (exists("r", B), C)]
    assert subsumes(A, C, t2)
    assert not subsumes(C, A, t2)
    # Every A has an A-successor that is not A: A is unsatisfiable.
    t3 = [(A, exists("r", A)), (A, forall("r", neg(A)))]
    assert not is_satisfiable(A, t3)
    assert is_satisfiable(neg(A), t3)
    # The universal TBox axiom top subsumed by all r.A.
    t4 = [(TOP, forall("r", A))]
    assert subsumes(exists("r", TOP), exists("r", A), t4)
    assert subsumes(exists("r", exists("r", TOP)), exists("r", conj(A, exists("r", A))), t4)
    # A cycle through two names: A needs a B-successor and B needs an A-successor.
    t5 = [(A, exists("r", B)), (B, exists("r", A)), (A, neg(B))]
    res = tableau(A, t5)
    assert res.satisfiable and dl.is_model_of_tbox(res.model, t5)
    assert subsumes(A, exists("r", exists("r", exists("r", B))), t5)


def test_empty_tbox_random_against_semantics() -> None:
    rng = random.Random(2024)
    seen = {True: 0, False: 0}
    for _ in range(300):
        c = rand_concept(rng, 4)
        res = tableau(c)
        seen[check_result(c)] += 1
        # Without a TBox the tree is no deeper than the role depth of the concept.
        assert res.stats.depth <= dl.role_depth(dl.nnf(c))
        assert res.stats.blocked == 0
    assert seen[True] > 50 and seen[False] > 20, seen


def test_general_tbox_random_against_semantics() -> None:
    rng = random.Random(99)
    seen = {True: 0, False: 0}
    for _ in range(150):
        tbox = [(rand_concept(rng, 2), rand_concept(rng, 2)) for _ in range(rng.randint(1, 2))]
        c = rand_concept(rng, 3)
        seen[check_result(c, tbox)] += 1
    assert seen[True] > 20 and seen[False] > 20, seen


def test_subsumption_by_reduction() -> None:
    rng = random.Random(5)
    for k in range(100):
        tbox = [] if k % 2 == 0 else [(rand_concept(rng, 2), rand_concept(rng, 2))]
        c, d = rand_concept(rng, 3), rand_concept(rng, 3)
        res = tableau(conj(c, neg(d)), tbox)
        assert subsumes(c, d, tbox) == (not res.satisfiable)
        if res.satisfiable:  # a countermodel: element 0 is in c and not in d
            m = res.model
            assert 0 in dl.evaluate(c, m) and 0 not in dl.evaluate(d, m)
        else:
            small = small_interpretations()
            assert all(dl.evaluate(c, i) <= dl.evaluate(d, i) for i in small if dl.is_model_of_tbox(i, tbox))


def test_two_roles() -> None:
    # With two roles the brute force uses domains of at most 2 elements (1024 interpretations for n = 2).
    rng = random.Random(11)
    for _ in range(120):
        c = rand_concept(rng, 3, atoms=("A",), roles=("r", "s"))
        check_result(c, (), cn=("A",), rn=("r", "s"), max_size=2)

History

Schmidt-Schauß and Smolka (1991) defined ALC and gave the first decision procedure for its satisfiability and subsumption, as rules that complete a set of constraints. They proved that a depth-first form of it uses polynomial space, and that the problem is PSPACE-complete. Schild (1991) saw that ALC is a notational variant of the modal logic K, so their procedure is a tableau in the sense of modal logic, and the name stayed. Buchheit, Donini and Schaerf (1993) gave a terminating calculus for general inclusions. In the late 1990s Horrocks and others built fast reasoners on tableaux with many optimizations.

References

  1. Manfred Schmidt-Schauß and Gert Smolka, Attributive concept descriptions with complements, Artificial Intelligence 48(1), 1991, pages 1 to 26 (the completion rules for constraint systems, and the polynomial space bound of the depth-first search)
  2. Franz Baader, Ian Horrocks, Carsten Lutz and Ulrike Sattler, An Introduction to Description Logic, Cambridge University Press, 2017, Chapter 4, Section 4.2 (the tableau algorithm for ALC, for ABoxes, acyclic TBoxes and general TBoxes with blocking)
  3. Franz Baader, Diego Calvanese, Deborah L. McGuinness, Daniele Nardi and Peter F. Patel-Schneider (eds.), The Description Logic Handbook, second edition, Cambridge University Press, 2007, Chapter 2, Basic Description Logics, by Franz Baader and Werner Nutt, Section 2.3 (tableau algorithms)
  4. Klaus Schild, A correspondence theory for terminological logics: preliminary report, Proceedings of the 12th International Joint Conference on Artificial Intelligence (IJCAI), 1991, ALC as a notational variant of the multimodal logic K (general locator)
  5. Martin Buchheit, Francesco M. Donini and Andrea Schaerf, Decidable reasoning in terminological knowledge representation systems, Journal of Artificial Intelligence Research 1, 1993, pages 109 to 138 (a calculus for general inclusions and the test that stops it, general locator)
  6. Francesco M. Donini and Fabio Massacci, EXPTIME tableaux for ALC, Artificial Intelligence 124(1), 2000, pages 87 to 138, tableau calculi for ALC with general TBoxes that run in exponential time
  7. Rajeev Goré and Linh Anh Nguyen, ExpTime tableaux for ALC using sound global caching, Journal of Automated Reasoning 50(4), 2013, pages 355 to 381 (global caching of node labels, and the exponential time bound)
  8. Ian Horrocks and Peter F. Patel-Schneider, Optimizing description logic subsumption, Journal of Logic and Computation 9(3), 1999, lazy unfolding, absorption, semantic branching, backjumping and caching (general locator)

Where this leads

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.general_tbox
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of space.general_tbox
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