Algorithm Search⌘K

Algorithmadvanced

EL classification by completion rules

Also called CEL algorithm, Baader-Brandt-Lutz algorithm.

Puts an EL TBox in a normal form, then fills the set of subsumers of every concept name with five completion rules. It classifies the whole TBox in polynomial time.

Time
O(n^3) worst
Space
O(n^2) extra
Where
n = the size of the TBox
Properties
builds modeldeterministicexactsaturation
Origin
Franz Baader, Sebastian Brandt, Carsten Lutz, 2005

EL classification by completion rules computes all subsumptions between the concept names of a TBox in the description logic EL. It first rewrites the TBox into a normal form with four kinds of axioms. Then it fills, for each concept name XX, a set S(X)S(X) of names known to subsume XX, and for each role a set of known links, with five rules until nothing changes. The whole run takes polynomial time, and it gives every subsumption at once, which is what ontology classification needs.

In plain words

Think of a large list of medical terms with rules such as "every inflammation is a disease". You want the full table of which term falls under which. The method keeps, for each term, a list of the terms known to be above it. At the start each list holds only the term itself. Then the rules add terms to lists. If a list holds a term with a rule "this is always that", the list gets "that". If the rule says "this always has a link to something of a kind", the method draws a link to that kind. Facts about the far end of a link can then add terms at the near end. Nothing is ever taken back, so the lists only grow, and they stop growing after a number of steps that is small compared with the size of the list of rules.

The problem

The input is a TBox TT, a finite set of general concept inclusions C⊑DC \sqsubseteq D between EL concepts. EL concepts are built from concept names AA, ⊤\top, conjunction C⊓DC \sqcap D and existential restriction ∃r.C\exists r.C; the code and the proof also allow ⊥\bot. The TBox may be cyclic. The output is, for all concept names AA and BB of TT, whether A⊑TBA \sqsubseteq_T B, that is, whether AI⊆BIA^I \subseteq B^I in every model II of TT. A name with A⊑T⊥A \sqsubseteq_T \bot is unsatisfiable. A subsumption C⊑TDC \sqsubseteq_T D between complex concepts reduces to the same question for two fresh names Q⊑CQ \sqsubseteq C and D⊑PD \sqsubseteq P.

Concept subsumption in EL with a general TBox is decidable in polynomial time. In ALC the same question is EXPTIME-complete (ALC with general TBoxes), because ALC has disjunction and value restrictions.

The algorithm

Normal form. Each inclusion is split, with fresh concept names, into axioms of four forms, where A,A1,A2A, A_1, A_2 are names or ⊤\top and BB is a name, ⊤\top or ⊥\bot:

A⊑B,A1⊓A2⊑B,A⊑∃r.B,∃r.A⊑B.A \sqsubseteq B, \qquad A_1 \sqcap A_2 \sqsubseteq B, \qquad A \sqsubseteq \exists r.B, \qquad \exists r.A \sqsubseteq B.

For example, Disease⊓∃loc.∃part.Heart⊑HeartDisease\mathit{Disease} \sqcap \exists \mathit{loc}.\exists \mathit{part}.\mathit{Heart} \sqsubseteq \mathit{HeartDisease} becomes ∃part.Heart⊑X\exists \mathit{part}.\mathit{Heart} \sqsubseteq X, ∃loc.X⊑Y\exists \mathit{loc}.X \sqsubseteq Y and Disease⊓Y⊑HeartDisease\mathit{Disease} \sqcap Y \sqsubseteq \mathit{HeartDisease}. The new TBox has linear size and the same subsumptions between the old names.

Completion. The rules work on the sets S(X)S(X) and on a relation R(r)R(r) for each role rr. The invariant is that B∈S(X)B \in S(X) implies X⊑TBX \sqsubseteq_T B, and (X,Y)∈R(r)(X, Y) \in R(r) implies X⊑T∃r.YX \sqsubseteq_T \exists r.Y.

  1. CLASSIFY(T) ▷ T in normal form; ADD(X, B): if B ∉ S(X), add B to S(X) and queue (X, B)
  2. 1for each name X and X = ⊤: S(X) ← ∅, then ADD(X, X), ADD(X, ⊤); R(r) ← ∅ for each role r
  3. 2while the queue is not empty do
  4. 3take (X, A) from the queue ▷ A is new in S(X)
  5. 4for each A ⊑ B in T: ADD(X, B) ▷ CR1
  6. 5for each A ⊓ A′ ⊑ B in T (either order) with A′ in S(X): ADD(X, B) ▷ CR2
  7. 6for each A ⊑ ∃r.B in T: ADD-EDGE(r, X, B) ▷ CR3
  8. 7for each (W, X) in R(r): for each ∃r.A ⊑ B in T, ADD(W, B); if A = ⊥, ADD(W, ⊥) ▷ CR4, CR5
  9. ADD-EDGE(r, X, Y)
  10. 8if (X, Y) is not in R(r) then add it to R(r)
  11. 9for each A in S(Y) and each ∃r.A ⊑ B in T: ADD(X, B) ▷ CR4
  12. 10if ⊥ is in S(Y) then ADD(X, ⊥) ▷ CR5
  13. SUBSUMES(A, B)
  14. 11return B ∈ S(A) or ⊥ ∈ S(A)

The queue holds the pairs that still have to be matched against the axioms. A new element of S(X)S(X) fires the axioms that have it on the left (lines L4 to L6), and the existential axioms of the nodes that point to XX (line L7). A new edge looks at what is already known about its target (lines L9 and L10). This is the same forward chaining as Horn-SAT by forward chaining, with the edges as an extra kind of fact.

When the run ends with ⊥∉S(⊤)\bot \notin S(\top), the sets give a model of TT: one element dXd_X for each name XX with ⊥∉S(X)\bot \notin S(X), the name AA holds at dXd_X when A∈S(X)A \in S(X), and the rr-edges are those of R(r)R(r). The element dAd_A is in exactly the names of S(A)S(A), so it is a counter-example to every subsumption that line L11 rejects.

Example

The TBox has four inclusions:

  • Pericarditis⊑Inflammation⊓∃loc.Pericardium\mathit{Pericarditis} \sqsubseteq \mathit{Inflammation} \sqcap \exists \mathit{loc}.\mathit{Pericardium}
  • Inflammation⊑Disease\mathit{Inflammation} \sqsubseteq \mathit{Disease}
  • Pericardium⊑∃part.Heart\mathit{Pericardium} \sqsubseteq \exists \mathit{part}.\mathit{Heart}
  • Disease⊓∃loc.∃part.Heart⊑HeartDisease\mathit{Disease} \sqcap \exists \mathit{loc}.\exists \mathit{part}.\mathit{Heart} \sqsubseteq \mathit{HeartDisease}

The normal form has 7 axioms: the first inclusion splits into Pericarditis⊑Inflammation\mathit{Pericarditis} \sqsubseteq \mathit{Inflammation} and Pericarditis⊑∃loc.Pericardium\mathit{Pericarditis} \sqsubseteq \exists \mathit{loc}.\mathit{Pericardium}, and the last one into the three axioms with XX and YY shown above. The facts that lead to the answer for Pericarditis\mathit{Pericarditis}, in an order in which they can be derived, are:

fact line rule new fact
1 L1 start S(Pericarditis)={Pericarditis,⊤}S(\mathit{Pericarditis}) = \{\mathit{Pericarditis}, \top\}
2 L4 CR1 Inflammation∈S(Pericarditis)\mathit{Inflammation} \in S(\mathit{Pericarditis})
3 L6, L8 CR3 (Pericarditis,Pericardium)∈R(loc)(\mathit{Pericarditis}, \mathit{Pericardium}) \in R(\mathit{loc})
4 L4 CR1 Disease∈S(Pericarditis)\mathit{Disease} \in S(\mathit{Pericarditis})
5 L6, L8 CR3 (Pericardium,Heart)∈R(part)(\mathit{Pericardium}, \mathit{Heart}) \in R(\mathit{part})
6 L9 CR4 Heart∈S(Heart)\mathit{Heart} \in S(\mathit{Heart}) and ∃part.Heart⊑X\exists \mathit{part}.\mathit{Heart} \sqsubseteq X, so X∈S(Pericardium)X \in S(\mathit{Pericardium})
7 L7 CR4 X∈S(Pericardium)X \in S(\mathit{Pericardium}), the loc\mathit{loc}-edge, and ∃loc.X⊑Y\exists \mathit{loc}.X \sqsubseteq Y, so Y∈S(Pericarditis)Y \in S(\mathit{Pericarditis})
8 L5 CR2 Disease,Y∈S(Pericarditis)\mathit{Disease}, Y \in S(\mathit{Pericarditis}), so HeartDisease∈S(Pericarditis)\mathit{HeartDisease} \in S(\mathit{Pericarditis})

At the end S(Pericarditis)={Pericarditis,Inflammation,Disease,Y,HeartDisease,⊤}S(\mathit{Pericarditis}) = \{\mathit{Pericarditis}, \mathit{Inflammation}, \mathit{Disease}, Y, \mathit{HeartDisease}, \top\}, so Pericarditis⊑THeartDisease\mathit{Pericarditis} \sqsubseteq_T \mathit{HeartDisease}. S(Inflammation)={Inflammation,Disease,⊤}S(\mathit{Inflammation}) = \{\mathit{Inflammation}, \mathit{Disease}, \top\}, so an inflammation in general is not a heart disease. Over the 9 names, with ⊤\top, XX and YY, the run adds 25 facts in total.

Correctness

Each rule adds a fact that follows from earlier facts and one axiom, so the invariant above holds and every "yes" is right. When the queue is empty, the sets are closed under all five rules. Then the interpretation built from SS and RR is a model of the normalized TBox, and the element dAd_A lies in BB only if B∈S(A)B \in S(A), so every "no" is right too. Normalization keeps the subsumptions between the old names, because each model of the old TBox becomes a model of the new one when each fresh name gets the extension of the subconcept it stands for. The full proof is in proofs/correctness.md.

Proof: The completion rules for EL with bottom are sound and complete and run in polynomial timefull

We use the pseudocode of the page, lines L1 to L11. The logic is EL with ⊥\bot: concepts are built from concept names, ⊤\top, ⊥\bot, C⊓DC \sqcap D and ∃r.C\exists r.C. The TBox TT is a finite set of general concept inclusions. The proof follows Baader, Brandt and Lutz (2005), restricted to these constructors.

Normal form

After the simplification (C⊓⊥C \sqcap \bot and ∃r.⊥\exists r.\bot become ⊥\bot, and ⊤\top is dropped from conjunctions), each inclusion C⊑DC \sqsubseteq D with C≠⊥C \neq \bot and D≠⊤D \neq \top is replaced as follows. For the left side, LEFT(C)(C) returns CC when it is a name or ⊤\top; for C=C1⊓C2C = C_1 \sqcap C_2 it returns a fresh name XX and adds LEFT(C1)⊓LEFT(C2)⊑X\mathrm{LEFT}(C_1) \sqcap \mathrm{LEFT}(C_2) \sqsubseteq X; for C=∃r.C1C = \exists r.C_1 it returns a fresh XX and adds ∃r.LEFT(C1)⊑X\exists r.\mathrm{LEFT}(C_1) \sqsubseteq X. For the right side, RIGHT(D)(D) returns DD when it is a name, ⊤\top or ⊥\bot; for D1⊓D2D_1 \sqcap D_2 it returns a fresh XX and adds X⊑RIGHT(D1)X \sqsubseteq \mathrm{RIGHT}(D_1) and X⊑RIGHT(D2)X \sqsubseteq \mathrm{RIGHT}(D_2); for ∃r.D1\exists r.D_1 it returns a fresh XX and adds X⊑∃r.RIGHT(D1)X \sqsubseteq \exists r.\mathrm{RIGHT}(D_1). Then it adds LEFT(C)⊑RIGHT(D)\mathrm{LEFT}(C) \sqsubseteq \mathrm{RIGHT}(D). The result T′T' has only the four forms A⊑BA \sqsubseteq B, A1⊓A2⊑BA_1 \sqcap A_2 \sqsubseteq B, A⊑∃r.BA \sqsubseteq \exists r.B and ∃r.A⊑B\exists r.A \sqsubseteq B, where A,A1,A2A, A_1, A_2 are names or ⊤\top and BB is a name, ⊤\top or ⊥\bot.

Lemma 1. For concept names A,BA, B of TT: A⊑TBA \sqsubseteq_T B if and only if A⊑T′BA \sqsubseteq_{T'} B. The same holds for satisfiability.

Proof. Every model of T′T' is a model of TT: by induction on the structure, CI⊆LEFT(C)IC^I \subseteq \mathrm{LEFT}(C)^I and RIGHT(D)I⊆DI\mathrm{RIGHT}(D)^I \subseteq D^I, so CI⊆LEFT(C)I⊆RIGHT(D)I⊆DIC^I \subseteq \mathrm{LEFT}(C)^I \subseteq \mathrm{RIGHT}(D)^I \subseteq D^I. Every model II of TT becomes a model of T′T' when each fresh name XX made by LEFT(C)(C) or RIGHT(D)(D) gets XI=CIX^I = C^I or XI=DIX^I = D^I: each added axiom then reads C1I∩C2I⊆(C1⊓C2)IC_1^I \cap C_2^I \subseteq (C_1 \sqcap C_2)^I, (∃r.C1)I⊆(∃r.C1)I(\exists r.C_1)^I \subseteq (\exists r.C_1)^I, and so on, and the last one is CI⊆DIC^I \subseteq D^I. Fresh names do not occur in TT, so the extensions of the old names do not change. Hence the two TBoxes have the same models up to the fresh names, and they agree on all questions about old names. □\square

Each constructor of TT gives at most one fresh name and at most two axioms, so ∣T′∣=O(∣T∣)|T'| = O(|T|).

Termination

Let kk be the number of names of T′T', with ⊤\top. Every set S(X)S(X) is a subset of these names and ⊥\bot, and every R(r)R(r) is a set of pairs of names. The procedure ADD puts a pair (X,B)(X, B) on the queue only when BB is new in S(X)S(X), and line L8 adds an edge only when it is new. Nothing is ever removed. So there are at most k(k+1)k(k+1) queue items and at most k2k^2 edges for each role, and the loop of line L2 stops.

Soundness

Lemma 2 (invariant). At every moment, B∈S(X)B \in S(X) implies X⊑T′BX \sqsubseteq_{T'} B, and (X,Y)∈R(r)(X, Y) \in R(r) implies X⊑T′∃r.YX \sqsubseteq_{T'} \exists r.Y.

Proof. At line L1, X⊑XX \sqsubseteq X and X⊑⊤X \sqsubseteq \top hold. Each later addition follows from earlier facts and one axiom of T′T', in every model II of T′T':

  • L4 (CR1): X⊑AX \sqsubseteq A and A⊑BA \sqsubseteq B give X⊑BX \sqsubseteq B.
  • L5 (CR2): X⊑AX \sqsubseteq A, X⊑A′X \sqsubseteq A' and A⊓A′⊑BA \sqcap A' \sqsubseteq B give X⊑BX \sqsubseteq B.
  • L6 and L8 (CR3): X⊑AX \sqsubseteq A and A⊑∃r.BA \sqsubseteq \exists r.B give X⊑∃r.BX \sqsubseteq \exists r.B.
  • L7 and L9 (CR4): X⊑∃r.YX \sqsubseteq \exists r.Y, Y⊑AY \sqsubseteq A and ∃r.A⊑B\exists r.A \sqsubseteq B give X⊑∃r.A⊑BX \sqsubseteq \exists r.A \sqsubseteq B.
  • L7 and L10 (CR5): X⊑∃r.YX \sqsubseteq \exists r.Y and Y⊑⊥Y \sqsubseteq \bot give X⊑∃r.⊥≡⊥X \sqsubseteq \exists r.\bot \equiv \bot. □\square

So when line L11 answers yes, either A⊑T′BA \sqsubseteq_{T'} B, or A⊑T′⊥⊑BA \sqsubseteq_{T'} \bot \sqsubseteq B. By Lemma 1 the answer is right for TT.

Completeness

Lemma 3 (closure). When the loop of line L2 stops, the sets are closed under the five rules: no rule can add anything.

Proof. Every element AA of S(X)S(X) went through the queue once, and at that time lines L4 to L7 applied every axiom with AA on the left. CR1 and CR3 depend only on A∈S(X)A \in S(X), so they were applied. For CR2 with A,A′∈S(X)A, A' \in S(X), the one of the two that came second off the queue found the other in S(X)S(X) at line L5. For CR4 and CR5 with (X,Y)∈R(r)(X, Y) \in R(r) and A∈S(Y)A \in S(Y): if AA was in S(Y)S(Y) when the edge was added, lines L9 and L10 applied the rule; otherwise the edge was there when (Y,A)(Y, A) came off the queue, and line L7 applied it. □\square

Assume ⊥∉S(⊤)\bot \notin S(\top). Build the canonical interpretation II: the domain has one element dXd_X for each name XX (with ⊤\top) such that ⊥∉S(X)\bot \notin S(X); AI={dX:A∈S(X)}A^I = \{d_X : A \in S(X)\}; and rI={(dX,dY):(X,Y)∈R(r)}r^I = \{(d_X, d_Y) : (X, Y) \in R(r)\} for elements of the domain. The domain holds d⊤d_\top, so it is not empty.

Lemma 4. II is a model of T′T'.

Proof. Take an element dXd_X, so ⊥∉S(X)\bot \notin S(X), and recall ⊤∈S(X)\top \in S(X), so dX∈AId_X \in A^I if and only if A∈S(X)A \in S(X) also for A=⊤A = \top.

  • A⊑BA \sqsubseteq B: if A∈S(X)A \in S(X), CR1 gives B∈S(X)B \in S(X). B≠⊥B \neq \bot, because ⊥∉S(X)\bot \notin S(X). So dX∈BId_X \in B^I.
  • A1⊓A2⊑BA_1 \sqcap A_2 \sqsubseteq B: in the same way with CR2.
  • A⊑∃r.BA \sqsubseteq \exists r.B: CR3 gives (X,B)∈R(r)(X, B) \in R(r). If ⊥∈S(B)\bot \in S(B), CR5 would put ⊥\bot in S(X)S(X), so dBd_B is in the domain, and dB∈BId_B \in B^I because B∈S(B)B \in S(B). So dX∈(∃r.B)Id_X \in (\exists r.B)^I.
  • ∃r.A⊑B\exists r.A \sqsubseteq B: if (dX,dY)∈rI(d_X, d_Y) \in r^I and dY∈AId_Y \in A^I, then (X,Y)∈R(r)(X, Y) \in R(r) and A∈S(Y)A \in S(Y), and CR4 gives B∈S(X)B \in S(X), with B≠⊥B \neq \bot as before. □\square

Lemma 5. At the end, S(⊤)⊆S(X)S(\top) \subseteq S(X) for every name XX.

Proof. We show, by induction on the order in which the run added facts about ⊤\top, that B∈S(⊤)B \in S(\top) implies B∈S(X)B \in S(X), and that (⊤,Y)∈R(r)(\top, Y) \in R(r) implies (X,Y)∈R(r)(X, Y) \in R(r). We use that the final sets are closed (Lemma 3). The first fact ⊤∈S(⊤)\top \in S(\top) holds for XX by line L1. If BB came into S(⊤)S(\top) by CR1 or CR2 from elements of S(⊤)S(\top), those elements are in S(X)S(X) by induction, and closure under the same rule puts BB in S(X)S(X). If (⊤,Y)(\top, Y) came into R(r)R(r) by CR3 from A∈S(⊤)A \in S(\top), then A∈S(X)A \in S(X) and closure gives (X,Y)∈R(r)(X, Y) \in R(r). If BB came into S(⊤)S(\top) by CR4 or CR5 from an edge (⊤,Y)(\top, Y), then (X,Y)∈R(r)(X, Y) \in R(r) by induction, and closure gives B∈S(X)B \in S(X). □\square

Theorem. For concept names AA and BB of TT, line L11 answers yes if and only if A⊑TBA \sqsubseteq_T B.

Proof. "Only if" is soundness. For "if", suppose the answer is no: B∉S(A)B \notin S(A) and ⊥∉S(A)\bot \notin S(A). By Lemma 5, ⊥∉S(⊤)\bot \notin S(\top), so II is defined. By Lemma 4 it is a model of T′T', and dA∈AId_A \in A^I because A∈S(A)A \in S(A), while dA∉BId_A \notin B^I. So A̸⊑T′BA \not\sqsubseteq_{T'} B, and by Lemma 1, A̸⊑TBA \not\sqsubseteq_T B. ■\blacksquare

For a subsumption C⊑TDC \sqsubseteq_T D between EL concepts, add two fresh names QQ and PP with Q⊑CQ \sqsubseteq C and D⊑PD \sqsubseteq P. Then C⊑TDC \sqsubseteq_T D holds if and only if Q⊑PQ \sqsubseteq P holds for the larger TBox: one direction is the chain Q⊑C⊑D⊑PQ \sqsubseteq C \sqsubseteq D \sqsubseteq P, and for the other, a model of TT with an element in CC and not in DD becomes a model of the larger TBox with QI=CIQ^I = C^I and PI=DIP^I = D^I.

Running time

Let n=∣T∣n = |T|, so k=O(n)k = O(n) names and O(n)O(n) axioms after normalization. With the axioms indexed by their left side, an item (X,A)(X, A) costs O(1)O(1) for each axiom with AA on the left at lines L4 to L6, and O(∣pred(X)∣)O(|\mathrm{pred}(X)|) at line L7, where pred(X)\mathrm{pred}(X) is the set of edges into XX. Edges into XX come only from axioms A⊑∃r.XA \sqsubseteq \exists r.X, so the total number of edges is at most k⋅nk \cdot n. Over all items:

  • Lines L4 to L6: each of the kk names XX meets each axiom at most once, O(k⋅n)=O(n2)O(k \cdot n) = O(n^2).
  • Line L7: ∑X∣S(X)∣⋅∣pred(X)∣≤(k+1)⋅kn=O(n3)\sum_X |S(X)| \cdot |\mathrm{pred}(X)| \le (k + 1) \cdot k n = O(n^3).
  • Lines L8 to L10: each of the O(n2)O(n^2) edges scans S(Y)S(Y) once, O(n3)O(n^3).

The time is O(n3)O(n^3) and the space for SS and RR is O(n2)O(n^2).

Complexity

Let nn be the size of TT. The normal form has O(n)O(n) axioms and k=O(n)k = O(n) names. Each set S(X)S(X) has at most k+1k + 1 elements and each relation R(r)R(r) at most k2k^2 pairs, but edges into XX come only from axioms A⊑∃r.XA \sqsubseteq \exists r.X, so there are O(n2)O(n^2) edges in all. With the axioms indexed by their left side, line L7 costs O(n2)O(n^2) for each name XX over its whole life, times ∣S(X)∣|S(X)|, and line L9 costs ∣S(Y)∣|S(Y)| for each edge. The time is O(n3)O(n^3) and the space is O(n2)O(n^2).

The problem is also hard for polynomial time: propositional Horn clauses p1∧p2→qp_1 \wedge p_2 \to q are the axioms P1⊓P2⊑QP_1 \sqcap P_2 \sqsubseteq Q, so Horn-SAT reduces to EL subsumption, and subsumption in EL with general TBoxes is P-complete.

Properties

  • One pass, all answers. The run gives the whole subsumption hierarchy at once, not one test at a time.
  • No search. There is no choice and no backtracking. The result does not depend on the order of the queue.
  • Monotone. Facts are only added. A new axiom can be handled by adding it and running the loop again from the current sets.
  • A small model. The model built from SS and RR has at most one element for each name of the normal form.

Variants and improvements

  • Larger EL logics. Baader, Brandt and Lutz (2005) added rules for nominals, concrete domains with a convexity condition, and role inclusions r1∘⋯∘rk⊑sr_1 \circ \dots \circ r_k \sqsubseteq s, and kept the polynomial bound. This extension underlies the OWL 2 EL profile.
  • Goal-directed rules. The ELK reasoner (Kazakov, Krötzsch and Simančík 2014) computes S(X)S(X) only for names that are needed, with rules on the original concepts instead of a full normal form, and runs the saturation of different names in parallel.
  • Datalog. The rules are a fixed Datalog program over the normalized axioms, so Datalog evaluation with semi-naive evaluation also classifies EL.
  • Query answering. The same idea with ABox individuals as extra nodes decides instance checking in polynomial time; ontology-mediated query answering for EL builds on it.

When to use it

Use it for ontologies that stay inside EL with ⊥\bot, such as many large medical and biological ontologies, where a tableau reasoner is too slow because it tests the pairs one at a time. Do not use it as a general reasoner: with value restrictions, disjunction, negation or number restrictions, subsumption is EXPTIME-complete or worse, and the rules are not complete for those constructors. For DL-Lite ontologies over large data, query rewriting fits better.

Pitfalls

  • Skipping the normal form. Line L6 matches only an axiom A⊑∃r.BA \sqsubseteq \exists r.B with a name BB. An axiom such as A⊑∃r.(B⊓C)A \sqsubseteq \exists r.(B \sqcap C) must first get a fresh name Z⊑BZ \sqsubseteq B, Z⊑CZ \sqsubseteq C, A⊑∃r.ZA \sqsubseteq \exists r.Z; otherwise the edge has no target node and CR4 at line L9 cannot look inside it.
  • Forgetting the backward direction. A new name in S(X)S(X) can fire ∃r.A⊑B\exists r.A \sqsubseteq B at every node with an edge into XX. If line L7 is left out and only line L9 handles CR4, the facts that reach XX after the edge was made are lost, and some subsumptions are missed.
  • Forgetting ⊥ along edges. If line L10 and the ⊥ case of line L7 are left out, A⊑∃r.BA \sqsubseteq \exists r.B with B⊑⊥B \sqsubseteq \bot does not make AA unsatisfiable, and line L11 misses A⊑TCA \sqsubseteq_T C for every CC.
  • Extending with value restrictions. Adding an axiom form A⊑∀r.BA \sqsubseteq \forall r.B with a rule "for each edge (X,Y)(X, Y), add BB to S(Y)S(Y)" is unsound: S(Y)S(Y) is shared by every node that points to YY. EL with value restrictions is EXPTIME-complete with general TBoxes.

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)
el_classification.py 239 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/el-classification/. The authors are listed in prov/JW3S50.jsonl.
"""Classification of an EL TBox with bottom by completion rules (Baader, Brandt and Lutz 2005).

Concepts are the tuples of dl.py, built from top, bottom, concept names, conjunction and existential
restriction. The TBox is a list of general concept inclusions (C, D). The algorithm first puts the
TBox in normal form, with fresh names that start with "_", then saturates the sets S(X) of
subsumers of each name X and the relations R(r) with five completion rules.
"""

from collections import deque
from typing import Optional, Sequence

from dl import BOTTOM, TOP, GCI, Concept, Interpretation, names

TOPN = "⊤"  # the name used for top inside the completion
BOTN = "⊥"  # the name used for bottom inside the completion


class NotEL(ValueError):
    """Raised for a concept that is not in EL with bottom."""


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


def simplify(c: Concept) -> Concept:
    """Remove top from conjunctions, and turn every part that contains bottom in a conjunction or an
    existential restriction into bottom. The result is equivalent to c."""
    op = c[0]
    if op == "and":
        a, b = simplify(c[1]), simplify(c[2])
        if BOTTOM in (a, b):
            return BOTTOM
        if a == TOP:
            return b
        if b == TOP:
            return a
        return ("and", a, b)
    if op == "some":
        f = simplify(c[2])
        return BOTTOM if f == BOTTOM else ("some", c[1], f)
    return c


class Normalizer:
    """Builds the normal form. Each axiom is one of
    ("sub", A, B)        A subsumed by B
    ("conj", A1, A2, B)  A1 and A2 subsumed by B
    ("ex_r", A, r, B)    A subsumed by some r.B
    ("ex_l", r, A, B)    some r.A subsumed by B
    where A, A1, A2 are names or top and B is a name, top or bottom."""

    def __init__(self) -> None:
        self.axioms: list[tuple] = []
        self.fresh = 0

    def _new(self) -> str:
        self.fresh += 1
        return f"_N{self.fresh}"

    @staticmethod
    def _base(c: Concept) -> Optional[str]:
        if c == TOP:
            return TOPN
        if c == BOTTOM:
            return BOTN
        if c[0] == "atom":
            return c[1]
        return None

    def left(self, c: Concept) -> str:
        """A name X with c subsumed by X, by new axioms that follow the structure of c."""
        b = self._base(c)
        if b is not None:
            return b
        x = self._new()
        if c[0] == "and":
            self.axioms.append(("conj", self.left(c[1]), self.left(c[2]), x))
        else:
            self.axioms.append(("ex_l", c[1], self.left(c[2]), x))
        return x

    def right(self, c: Concept) -> str:
        """A name X with X subsumed by c, by new axioms that follow the structure of c."""
        b = self._base(c)
        if b is not None:
            return b
        x = self._new()
        if c[0] == "and":
            self.axioms.append(("sub", x, self.right(c[1])))
            self.axioms.append(("sub", x, self.right(c[2])))
        else:
            self.axioms.append(("ex_r", x, c[1], self.right(c[2])))
        return x

    def add(self, c: Concept, d: Concept) -> None:
        c, d = simplify(c), simplify(d)
        if c == BOTTOM or d == TOP:
            return  # holds in every interpretation
        self.axioms.append(("sub", self.left(c), self.right(d)))


def normalize(tbox: Sequence[GCI]) -> list[tuple]:
    nz = Normalizer()
    for c, d in tbox:
        if not (is_el(c) and is_el(d)):
            raise NotEL(repr((c, d)))
        nz.add(c, d)
    return nz.axioms


class Completion:
    """The saturated sets S(X) and relations R(r) of a normalized TBox."""

    def __init__(self, axioms: Sequence[tuple], extra_names: Sequence[str] = ()) -> None:
        self.axioms = list(axioms)
        nm = {TOPN} | set(extra_names)
        sub: dict[str, list] = {}
        conj: dict[str, list] = {}
        ex_r: dict[str, list] = {}
        ex_l: dict[tuple, list] = {}
        for ax in self.axioms:
            if ax[0] == "sub":
                sub.setdefault(ax[1], []).append(ax[2])
                nm |= {ax[1], ax[2]}
            elif ax[0] == "conj":
                conj.setdefault(ax[1], []).append((ax[2], ax[3]))
                conj.setdefault(ax[2], []).append((ax[1], ax[3]))
                nm |= {ax[1], ax[2], ax[3]}
            elif ax[0] == "ex_r":
                ex_r.setdefault(ax[1], []).append((ax[2], ax[3]))
                nm |= {ax[1], ax[3]}
            else:
                ex_l.setdefault((ax[1], ax[2]), []).append(ax[3])
                nm |= {ax[2], ax[3]}
        nm.discard(BOTN)
        self.names = sorted(nm)
        self.S: dict[str, set] = {x: set() for x in self.names}
        self.R: dict[str, set] = {}
        self.pred: dict[str, set] = {x: set() for x in self.names}  # pairs (r, W) with (W, X) in R(r)
        self.steps = 0  # rule applications that added something
        queue: deque = deque()

        def add(x: str, a: str) -> None:
            if a not in self.S[x]:
                self.S[x].add(a)
                self.steps += 1
                queue.append((x, a))

        def add_edge(r: str, x: str, y: str) -> None:
            pairs = self.R.setdefault(r, set())
            if (x, y) in pairs:
                return
            pairs.add((x, y))  # @line L8
            self.steps += 1
            self.pred[y].add((r, x))
            for a in list(self.S[y]):
                for b in ex_l.get((r, a), ()):
                    add(x, b)  # @line L9
            if BOTN in self.S[y]:
                add(x, BOTN)  # @line L10

        for x in self.names:
            add(x, x)  # @line L1
            add(x, TOPN)
        while queue:  # @line L2
            x, a = queue.popleft()  # @line L3
            for b in sub.get(a, ()):
                add(x, b)  # @line L4
            for a2, b in conj.get(a, ()):
                if a2 in self.S[x]:
                    add(x, b)  # @line L5
            for r, b in ex_r.get(a, ()):
                add_edge(r, x, b)  # @line L6
            for r, w in list(self.pred[x]):
                for b in ex_l.get((r, a), ()):
                    add(w, b)  # @line L7
                if a == BOTN:
                    add(w, BOTN)  # @line L7

    def subsumes(self, a: str, b: str) -> bool:
        """True when the name a is subsumed by the name b (or b is top)."""
        if b == TOPN:
            return True
        return b in self.S[a] or BOTN in self.S[a]  # @line L11

    def unsatisfiable(self, a: str) -> bool:
        return BOTN in self.S[a]

    def canonical_model(self) -> Optional[Interpretation]:
        """The model built from S and R: one element for each name X without bottom in S(X), the
        names of S(X) hold at it, and the edges are those of R. None if the TBox has no model."""
        if BOTN in self.S[TOPN]:
            return None
        live = [x for x in self.names if BOTN not in self.S[x]]
        ids = {x: k for k, x in enumerate(live)}
        conc: dict[str, set] = {}
        for x in live:
            for a in self.S[x]:
                if a not in (TOPN, BOTN):
                    conc.setdefault(a, set()).add(ids[x])
        roles = {r: {(ids[x], ids[y]) for x, y in pairs if x in ids and y in ids} for r, pairs in self.R.items()}
        return Interpretation(list(range(len(live))), conc, roles)

    def element(self, a: str) -> int:
        """The element of the canonical model for the name a."""
        live = [x for x in self.names if BOTN not in self.S[x]]
        return live.index(a)


def complete(tbox: Sequence[GCI]) -> Completion:
    """Normalize the TBox and saturate it. Every concept name of the TBox gets a set S."""
    cn, _ = names([c for gci in tbox for c in gci])
    return Completion(normalize(tbox), cn)


def classify(tbox: Sequence[GCI]) -> dict[str, set[str]]:
    """For each concept name A of the TBox, the set of concept names B of the TBox with A subsumed by B.
    An unsatisfiable name is subsumed by every name."""
    cn, _ = names([c for gci in tbox for c in gci])
    comp = Completion(normalize(tbox), cn)
    return {a: {b for b in cn if comp.subsumes(a, b)} for a in cn}


def subsumes(tbox: Sequence[GCI], c: Concept, d: Concept) -> bool:
    """True when c is subsumed by d with respect to the TBox, for EL concepts c and d.
    Uses fresh names Q and P with Q subsumed by c and d subsumed by P."""
    q, p = ("atom", "_Q"), ("atom", "_P")
    comp = complete(list(tbox) + [(q, c), (d, p)])
    return comp.subsumes("_Q", "_P")
test_el_classification.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/el-classification/. The authors are listed in prov/JW3S50.jsonl.
"""Tests of EL classification against the semantics.

1. "No" answers: the canonical model built from S and R must be a model of the TBox (checked by
   evaluation with dl.py), and its element for A must not be in B. This check is exact.
2. "Yes" answers and unsatisfiable names: the ALC tableau of alc_reference.py must agree. EL with
   bottom is a part of ALC, so the tableau decides the same question by a different method.
3. Brute force over every interpretation with at most 2 elements: a small model of the TBox with an
   element in A and not in B would refute a "yes". This direction is sound; a failed search cannot
   confirm a "no", so the canonical model does that.
"""

import random

import alc_reference
import dl
from dl import BOTTOM, TOP, atom, conj, exists, neg
from el_classification import BOTN, NotEL, classify, complete, normalize, subsumes

NAMES = ["A", "B", "C"]
ROLES = ["r", "s"]


def rand_el(rng: random.Random, depth: int, names=NAMES, roles=ROLES) -> tuple:
    if depth == 0 or rng.random() < 0.35:
        x = rng.random()
        if x < 0.08:
            return TOP
        if x < 0.11:
            return BOTTOM
        return atom(rng.choice(names))
    if rng.random() < 0.5:
        return conj(rand_el(rng, depth - 1, names, roles), rand_el(rng, depth - 1, names, roles))
    return exists(rng.choice(roles), rand_el(rng, depth - 1, names, roles))


def rand_tbox(rng: random.Random, k: int, names=NAMES, roles=ROLES) -> list:
    return [(rand_el(rng, 2, names, roles), rand_el(rng, 2, names, roles)) for _ in range(k)]


def check_against_semantics(tbox: list, small: bool) -> tuple[int, int]:
    cn = NAMES
    comp = complete(tbox + [(atom(a), atom(a)) for a in cn])
    model = comp.canonical_model()
    small_models = []
    if small:
        rn = sorted({c[1] for gci in tbox for x in gci for c in dl.subconcepts(x) if c[0] == "some"})
        small_models = [i for i in dl.interpretations(cn, rn, 2) if dl.is_model_of_tbox(i, tbox)]
    if model is None:
        assert not alc_reference.satisfiable(TOP, tbox)
        return 0, 0
    assert dl.is_model_of_tbox(model, tbox)
    yes = no = 0
    for a in cn:
        if comp.unsatisfiable(a):
            assert not alc_reference.satisfiable(atom(a), tbox)
        for b in cn:
            if comp.subsumes(a, b):
                yes += 1
                assert alc_reference.subsumes(atom(a), atom(b), tbox), (a, b, tbox)
                for i in small_models:
                    assert dl.evaluate(atom(a), i) <= dl.evaluate(atom(b), i)
            else:
                no += 1
                x = comp.element(a)
                assert x in dl.evaluate(atom(a), model) and x not in dl.evaluate(atom(b), model)
    return yes, no


def test_page_example() -> None:
    P, I, D, Pc, H, HD = (atom(x) for x in ("Pericarditis", "Inflammation", "Disease", "Pericardium", "Heart", "HeartDisease"))
    tbox = [
        (P, conj(I, exists("loc", Pc))),
        (I, D),
        (Pc, exists("part", H)),
        (conj(D, exists("loc", exists("part", H))), HD),
    ]
    got = classify(tbox)
    assert got["Pericarditis"] == {"Pericarditis", "Inflammation", "Disease", "HeartDisease"}
    assert got["Inflammation"] == {"Inflammation", "Disease"}
    assert got["Pericardium"] == {"Pericardium"}
    assert not subsumes(tbox, I, HD)
    assert subsumes(tbox, conj(I, exists("loc", Pc)), HD)
    assert alc_reference.subsumes(P, HD, tbox)
    comp = complete(tbox)
    assert dl.is_model_of_tbox(comp.canonical_model(), tbox)


def test_normal_form_shapes() -> None:
    A, B, C = atom("A"), atom("B"), atom("C")
    axioms = normalize([(conj(A, exists("r", conj(B, C))), exists("s", conj(A, exists("r", TOP))))])
    for ax in axioms:
        assert ax[0] in ("sub", "conj", "ex_r", "ex_l")
        for x in ax[1:]:
            assert isinstance(x, str)
    assert len(axioms) == 8


def test_bottom_propagates_back() -> None:
    A, B = atom("A"), atom("B")
    tbox = [(A, exists("r", B)), (B, BOTTOM)]
    got = classify(tbox)
    assert got["A"] == {"A", "B"}  # A is unsatisfiable, so it is below every name
    comp = complete(tbox)
    assert BOTN in comp.S["A"]
    assert not alc_reference.satisfiable(A, tbox)


def test_inconsistent_tbox() -> None:
    A = atom("A")
    tbox = [(TOP, exists("r", A)), (A, BOTTOM)]
    comp = complete(tbox)
    assert comp.canonical_model() is None
    assert not alc_reference.satisfiable(TOP, tbox)


def test_rejects_other_constructors() -> None:
    for c in (neg(atom("A")), dl.disj(atom("A"), atom("B")), dl.forall("r", atom("A"))):
        try:
            normalize([(c, atom("B"))])
        except NotEL:
            pass
        else:
            raise AssertionError("expected NotEL")


def test_random_tboxes_brute_force_and_tableau() -> None:
    rng = random.Random(2024)
    yes = no = 0
    for _ in range(40):
        tbox = rand_tbox(rng, rng.randint(2, 4), roles=["r"])
        y, n = check_against_semantics(tbox, small=True)
        yes += y
        no += n
    assert yes > 120 and no > 60


def test_random_tboxes_two_roles() -> None:
    rng = random.Random(99)
    yes = no = 0
    for _ in range(80):
        tbox = rand_tbox(rng, rng.randint(2, 6))
        y, n = check_against_semantics(tbox, small=False)
        yes += y
        no += n
    assert yes > 250 and no > 150


def test_complex_subsumption_against_tableau() -> None:
    rng = random.Random(5)
    yes = 0
    for _ in range(150):
        tbox = rand_tbox(rng, rng.randint(1, 4))
        c, d = rand_el(rng, 3), rand_el(rng, 2)
        got = subsumes(tbox, c, d)
        assert got == alc_reference.subsumes(c, d, tbox), (dl.show(c), dl.show(d), tbox)
        yes += got
    assert 20 < yes < 130

History

Early work on EL studied subsumption without a TBox and with acyclic or cyclic TBoxes. Brandt (2004) showed that subsumption stays polynomial with general concept inclusions and role hierarchies. Baader, Brandt and Lutz (2005) gave the algorithm in its present form, with the normal form and the completion rules, extended it with nominals, concrete domains and role inclusions, and showed that most other extensions make the problem EXPTIME-complete. The OWL 2 EL profile is based on this logic. Kazakov, Krötzsch and Simančík (2014) turned the rules into the concurrent reasoner ELK, which classifies very large medical ontologies in seconds.

References

  1. Franz Baader, Sebastian Brandt and Carsten Lutz, Pushing the EL envelope, Proceedings of the 19th International Joint Conference on Artificial Intelligence (IJCAI), 2005, pages 364 to 369 (normal form, completion rules, polynomial time, and the EXPTIME-complete extensions)
  2. Sebastian Brandt, Polynomial time reasoning in a description logic with existential restrictions, GCI axioms, and what else?, Proceedings of the 16th European Conference on Artificial Intelligence (ECAI), IOS Press, 2004, pages 298 to 302 (EL with general TBoxes and role hierarchies stays polynomial)
  3. Franz Baader, Ian Horrocks, Carsten Lutz and Ulrike Sattler, An Introduction to Description Logic, Cambridge University Press, 2017, Chapter 6 (reasoning in the EL family, general locator)
  4. Yevgeny Kazakov, Markus Krötzsch and František Simančík, The incredible ELK, from polynomial procedures to efficient reasoning with EL ontologies, Journal of Automated Reasoning 53(1), 2014, pages 1 to 61 (goal-directed rules, the saturation loop and concurrent classification)

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
  • a scene preset for the example