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
- Model
- Word RAM
- Properties
- builds modeldeterministicexactsaturation
- Evidence
- Proof sketchCode in 1 languages
- 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 , a set of names known to subsume , 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 , a finite set of general concept inclusions between EL concepts. EL concepts are built from concept names , , conjunction and existential restriction ; the code and the proof also allow . The TBox may be cyclic. The output is, for all concept names and of , whether , that is, whether in every model of . A name with is unsatisfiable. A subsumption between complex concepts reduces to the same question for two fresh names and .
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 are names or and is a name, or :
For example, becomes , and . The new TBox has linear size and the same subsumptions between the old names.
Completion. The rules work on the sets and on a relation for each role . The invariant is that implies , and implies .
CLASSIFY(T) ▷ T in normal form; ADD(X, B): if B ∉ S(X), add B to S(X) and queue (X, B)- 1
for each name X and X = ⊤: S(X) ← ∅, then ADD(X, X), ADD(X, ⊤); R(r) ← ∅ for each role r - 2
while the queue is not empty do - 3
take (X, A) from the queue ▷ A is new in S(X) - 4
for each A ⊑ B in T: ADD(X, B) ▷ CR1 - 5
for each A ⊓ A′ ⊑ B in T (either order) with A′ in S(X): ADD(X, B) ▷ CR2 - 6
for each A ⊑ ∃r.B in T: ADD-EDGE(r, X, B) ▷ CR3 - 7
for each (W, X) in R(r): for each ∃r.A ⊑ B in T, ADD(W, B); if A = ⊥, ADD(W, ⊥) ▷ CR4, CR5 ADD-EDGE(r, X, Y)- 8
if (X, Y) is not in R(r) then add it to R(r) - 9
for each A in S(Y) and each ∃r.A ⊑ B in T: ADD(X, B) ▷ CR4 - 10
if ⊥ is in S(Y) then ADD(X, ⊥) ▷ CR5 SUBSUMES(A, B)- 11
return B ∈ S(A) or ⊥ ∈ S(A)
The queue holds the pairs that still have to be matched against the axioms. A new element of fires the axioms that have it on the left (lines L4 to L6), and the existential axioms of the nodes that point to (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 , the sets give a model of : one element for each name with , the name holds at when , and the -edges are those of . The element is in exactly the names of , so it is a counter-example to every subsumption that line L11 rejects.
Example
The TBox has four inclusions:
The normal form has 7 axioms: the first inclusion splits into and , and the last one into the three axioms with and shown above. The facts that lead to the answer for , in an order in which they can be derived, are:
| fact | line | rule | new fact |
|---|---|---|---|
| 1 | L1 | start | |
| 2 | L4 | CR1 | |
| 3 | L6, L8 | CR3 | |
| 4 | L4 | CR1 | |
| 5 | L6, L8 | CR3 | |
| 6 | L9 | CR4 | and , so |
| 7 | L7 | CR4 | , the -edge, and , so |
| 8 | L5 | CR2 | , so |
At the end , so . , so an inflammation in general is not a heart disease. Over the 9 names, with , and , 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 and is a model of the normalized TBox, and the element lies in only if , 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 : concepts are built from concept names, , , and . The TBox 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 ( and become , and is dropped from conjunctions), each inclusion with and is replaced as follows. For the left side, LEFT returns when it is a name or ; for it returns a fresh name and adds ; for it returns a fresh and adds . For the right side, RIGHT returns when it is a name, or ; for it returns a fresh and adds and ; for it returns a fresh and adds . Then it adds . The result has only the four forms , , and , where are names or and is a name, or .
Lemma 1. For concept names of : if and only if . The same holds for satisfiability.
Proof. Every model of is a model of : by induction on the structure, and , so . Every model of becomes a model of when each fresh name made by LEFT or RIGHT gets or : each added axiom then reads , , and so on, and the last one is . Fresh names do not occur in , 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.
Each constructor of gives at most one fresh name and at most two axioms, so .
Termination
Let be the number of names of , with . Every set is a subset of these names and , and every is a set of pairs of names. The procedure ADD puts a pair on the queue only when is new in , and line L8 adds an edge only when it is new. Nothing is ever removed. So there are at most queue items and at most edges for each role, and the loop of line L2 stops.
Soundness
Lemma 2 (invariant). At every moment, implies , and implies .
Proof. At line L1, and hold. Each later addition follows from earlier facts and one axiom of , in every model of :
- L4 (CR1): and give .
- L5 (CR2): , and give .
- L6 and L8 (CR3): and give .
- L7 and L9 (CR4): , and give .
- L7 and L10 (CR5): and give .
So when line L11 answers yes, either , or . By Lemma 1 the answer is right for .
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 of went through the queue once, and at that time lines L4 to L7 applied every axiom with on the left. CR1 and CR3 depend only on , so they were applied. For CR2 with , the one of the two that came second off the queue found the other in at line L5. For CR4 and CR5 with and : if was in when the edge was added, lines L9 and L10 applied the rule; otherwise the edge was there when came off the queue, and line L7 applied it.
Assume . Build the canonical interpretation : the domain has one element for each name (with ) such that ; ; and for elements of the domain. The domain holds , so it is not empty.
Lemma 4. is a model of .
Proof. Take an element , so , and recall , so if and only if also for .
- : if , CR1 gives . , because . So .
- : in the same way with CR2.
- : CR3 gives . If , CR5 would put in , so is in the domain, and because . So .
- : if and , then and , and CR4 gives , with as before.
Lemma 5. At the end, for every name .
Proof. We show, by induction on the order in which the run added facts about , that implies , and that implies . We use that the final sets are closed (Lemma 3). The first fact holds for by line L1. If came into by CR1 or CR2 from elements of , those elements are in by induction, and closure under the same rule puts in . If came into by CR3 from , then and closure gives . If came into by CR4 or CR5 from an edge , then by induction, and closure gives .
Theorem. For concept names and of , line L11 answers yes if and only if .
Proof. "Only if" is soundness. For "if", suppose the answer is no: and . By Lemma 5, , so is defined. By Lemma 4 it is a model of , and because , while . So , and by Lemma 1, .
For a subsumption between EL concepts, add two fresh names and with and . Then holds if and only if holds for the larger TBox: one direction is the chain , and for the other, a model of with an element in and not in becomes a model of the larger TBox with and .
Running time
Let , so names and axioms after normalization. With the axioms indexed by their left side, an item costs for each axiom with on the left at lines L4 to L6, and at line L7, where is the set of edges into . Edges into come only from axioms , so the total number of edges is at most . Over all items:
- Lines L4 to L6: each of the names meets each axiom at most once, .
- Line L7: .
- Lines L8 to L10: each of the edges scans once, .
The time is and the space for and is .
Complexity
Let be the size of . The normal form has axioms and names. Each set has at most elements and each relation at most pairs, but edges into come only from axioms , so there are edges in all. With the axioms indexed by their left side, line L7 costs for each name over its whole life, times , and line L9 costs for each edge. The time is and the space is .
The problem is also hard for polynomial time: propositional Horn clauses are the axioms , 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 and 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 , 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 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 , 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 with a name . An axiom such as must first get a fresh name , , ; otherwise the edge has no target node and CR4 at line L9 cannot look inside it.
- Forgetting the backward direction. A new name in can fire at every node with an edge into . If line L7 is left out and only line L9 handles CR4, the facts that reach 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, with does not make unsatisfiable, and line L11 misses for every .
- Extending with value restrictions. Adding an axiom form with a rule "for each edge , add to " is unsound: is shared by every node that points to . 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.
# 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
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag JW3S50 Edit this page History Report an error Markdown