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.
- Solves
- Concept satisfiability
- 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
- Model
- Word RAM
- Properties
- builds modeldeterministicexactrecursive
- Evidence
- Proof sketchCode in 1 languages
- 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 and a TBox , a finite set of general concept inclusions . The TBox can be empty. The question is whether some interpretation is a model of and has . This is concept satisfiability. Concept subsumption reduces to it: holds if and only if is not satisfiable with respect to .
A concept is in negation normal form (NNF) when occurs only in front of concept names. Each concept has an equivalent one in NNF of linear size: push inward with the De Morgan laws, and . For example, becomes .
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 in the label (the ∃-rule), and gives the child each with in the label (the ∀-rule). A label has a clash when it holds , or and for a concept name . Each inclusion of becomes the concept , which goes into every label.
SAT(C, T)- 1
C_T ← {nnf(¬D ⊔ E) : D ⊑ E in T} - 2
return NODE({nnf(C)} ∪ C_T, []) NODE(S, P) ▷ P is the list of the completed labels of the ancestors- 3
for each L in COMPLETIONS(S) do - 4
ok ← true - 5
for each ∃r.D in L do - 6
S′ ← {D} ∪ {E : ∀r.E in L} ∪ C_T - 7
if T is not empty and S′ ⊆ L″ for some L″ in P + [L] then continue ▷ blocked - 8
if NODE(S′, P + [L]) is false then ok ← false, and leave this loop - 9
if ok then return true - 10
return false COMPLETIONS(S) ▷ yields the clash-free completions of S, one at a time- 11
L ← the closure of S under the ⊓-rule: with D ⊓ E, add D and E - 12
if ⊥ is in L, or A and ¬A are in L for some A, then return - 13
if some D ⊔ E in L has D not in L and E not in L then - 14
yield each label of COMPLETIONS(L ∪ {D}), then each label of COMPLETIONS(L ∪ {E}) - 15
else 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, is the set of nodes whose label holds , and is the set of -edges, with each blocked edge sent to its blocking node.
Example
Take the concept with the empty TBox. It is already in NNF.
| step | node | label and action |
|---|---|---|
| 1 | root | ⊓-rule: |
| 2 | root | ⊔-rule, first choice : clash with , backtrack |
| 3 | root | second choice : the label is complete |
| 4 | child | ∃-rule and ∀-rule: |
| 5 | child | first choice : clash with , backtrack |
| 6 | child | second choice : complete, no ∃, return true |
The run expands 2 nodes and meets 2 clashes. The model has , , and , and the root 0 is an instance of the input concept.
With the TBox and the concept , the root gets . The choice clashes, so the root label becomes . The child would get , which is a subset of the root label, so line L7 blocks it. The model has one element in with an -edge to itself. Without line L7 the search would make an endless chain of -successors.
Correctness
The algorithm is sound: when it returns true, the interpretation above is a model of and the root is in . 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 in some model of , then the choices that satisfies lead to a run that returns true, and each is matched by an -successor of in . 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 . 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). is a TBox, and (line L1). Blocking is on when .
Let be the set of all subconcepts of and of the concepts in , and let . Then is at most the sum of the sizes of these concepts, so for an input of size .
Lemma 0 (NNF). For every concept and every interpretation , .
Proof. By induction on the size of . The rules of nnf are the identities , , , , , and . Each one follows from the semantics: for example, if and only if no -successor of is in , if and only if every -successor of is in . Each rule calls nnf on smaller concepts, so the induction hypothesis applies.
Lemma 1 (labels stay in cl). Every label that the algorithm builds is a subset of .
Proof. The root label is . Lines L11 and L14 add only a direct subconcept of a concept of the label. Line L6 puts in a child the subconcepts of and of , and the concepts of . Since is closed under subconcepts, induction on the steps gives the claim.
Termination
Lemma 2 (COMPLETIONS stops). A call COMPLETIONS makes at most recursive calls in total.
Proof. Line L14 makes a call only on with , so each nested call has a label with at least one more element of than its caller. Labels have at most elements (Lemma 1), so the nesting depth is at most , and each call makes at most 2 calls.
Lemma 3 (depth without a TBox). If , a node at depth has a label of role depth at most . So the depth of the tree is at most .
Proof. The ⊓-rule and the ⊔-rule add subconcepts, which do not have a larger role depth. A child label (line L6, with ) holds only concepts with or 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 , so line L5 makes no child.
Lemma 4 (depth with blocking). If blocking is on, every path from the root has at most nodes that are expanded.
Proof. Let be a node that line L8 expands, with initial label , and let be an ancestor of with initial label and completed label . Line L7 did not block , so . COMPLETIONS only adds concepts, so , and so . Thus the initial labels on one path are pairwise different subsets of , and there are at most of them. The number of subsets of that are not yet used on the path drops by exactly 1 at each level.
Theorem 1 (termination). SAT stops. With the run takes at most steps. With blocking it takes at most steps.
Proof. A completed label has at most concepts of the form , so line L5 makes at most calls for one completion. By Lemma 2 there are at most completions of one label, each built in time polynomial in . Let be the largest number of steps of a call of NODE whose subtree has height at most . Then for a polynomial , so . With , Lemma 3 gives , so the time is . With blocking, Lemma 4 gives , so the time is . Both bounds are finite.
Soundness
Theorem 2 (soundness). If SAT returns true, then the interpretation built from the successful calls is a model of in which the root is an instance of .
Proof. A call of NODE that returns true does so at line L9 for one completion , its last one, and each call that line L8 made for 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 in it was called with the last completions of all its ancestors in , 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 has a label , its last completion, that COMPLETIONS yielded. So has no clash (line L12): , and no with . It is closed under ⊓: if then (line L11). It is complete for ⊔: if then or (lines L13 and L15).
- (P2) for each node , because each initial label holds (lines L2 and L6) and COMPLETIONS only adds concepts.
- (P3) For each , line L7 or line L8 gives an edge , where is the child call of line L8, or the node whose label blocks the child at line L7. In both cases for the set of line L6. Every edge comes from this step.
A blocking label is in , so it is the label of or of an ancestor of , and by the remark above it is the last completion of that node. So is a node of the tree, and . Let be the set of nodes, and the set of -edges.
Claim: for every node and every , . The proof is by induction on the size of .
- : true. : impossible by (P1). : by the definition of . : by (P1), so .
- : both are in by (P1), and the induction hypothesis applies.
- : one of them is in by (P1).
- : by (P3) there is an edge with , so by the induction hypothesis, and .
- : each -successor of in comes from an edge of (P3), made for some . Its set holds every with , so , and by the induction hypothesis.
The root label holds , so the root is in (Lemma 0). For an inclusion of and any node , (P2) and the claim give . So , and is a model of .
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 has an instance in some model of , then SAT returns true.
Proof. Say that an element satisfies a set when for all . Every element of satisfies : for , , so each element is in (Lemma 0).
Step 1. If satisfies , then COMPLETIONS yields at least one label that 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 gives and . Then line L12 finds no clash, because and cannot be in both and . If line L13 picks , then or , so one of the two calls of line L14 gets a set that satisfies, and the induction hypothesis gives a label. Otherwise line L15 yields itself.
Step 2. If satisfies , then NODE returns true, for every list 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 that satisfies, unless it returned true for an earlier completion, and then we are done. For each , has an -successor in . Then is in for every , and satisfies , so satisfies the set of line L6. If line L7 blocks the child, the loop goes on. Otherwise the induction hypothesis says that NODE returns true. So no call fails, the loop of line L5 ends with $ok = $ true, and line L9 returns true.
The element of in satisfies (Lemma 0), so line L2 returns true.
Corollary. SAT returns true if and only if is satisfiable with respect to . So holds if and only if SAT returns false.
Space with an empty TBox
With the recursion has depth at most (Lemma 3). Each level of NODE holds its list of ancestors, one completed label of at most concepts, and the stack of COMPLETIONS, which has at most open calls (Lemma 2), each with a label of at most concepts. A concept in a label is a reference to a subtree of the input. So the space is 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 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 time on such inputs (Theorem 1), so it is not worst-case optimal. Global caching of labels brings it to (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 be the size of the input, and the number of its subconcepts. A label has at most concepts, and one label has at most completions.
- Empty TBox. The tree has depth at most the role depth of . The search keeps only the current path, so the space is words. The time is 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 nodes before blocking stops it, so the time is in the worst case and the space is . 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 , which is worst-case optimal (Donini and Massacci 2000, Goré and Nguyen 2013).
- Optimizations in reasoners. Absorption moves inclusions 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 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 .
- 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.
# 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
- 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)
- 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)
- 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)
- 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)
- 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)
- 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
- 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)
- 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.
| 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 W9NV76 Edit this page History Report an error Markdown