Algorithmresearch
Hypertableau calculus
Also called Motik-Shearer-Horrocks hypertableau.
Turns a TBox into DL-clauses and builds a model with hyperresolution-like steps that branch only on real disjunctions, with anywhere blocking to stop.
- Time
- 2^2^2^O(n) worst
- Space
- 2^2^O(n) extra
- Where
- n = the size of the concept and the TBox
- Model
- Word RAM
- Properties
- backtrackingbuilds modeldeterministicexact
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Boris Motik, Rob Shearer, Ian Horrocks, 2009
The hypertableau calculus decides satisfiability of a concept with respect to a general TBox by first turning every axiom into DL-clauses, rules of the form "if these atoms hold, then one of those atoms holds", and then building a model by applying the clauses forward. A clause fires only when its whole body is already true, as in hyperresolution, so an inclusion such as adds only where holds, and the search branches only when a clause with two or more head atoms fires. New nodes come from existential atoms, and anywhere blocking stops the tree from growing forever. Motik, Shearer and Horrocks introduced it in 2009 to cut the nondeterminism of the ALC tableau.
In plain words
A tableau reasoner checks whether a description can be met by building an example step by step. The plain method turns each rule of the form "every A is a B" into a choice at every element: either it is not an A, or it is a B. With many rules, it makes many choices that do not matter and then undoes them. The hypertableau method writes each rule as "if A holds here, then B holds here" and uses it only when A is already known. A rule that says "if a child has A, then the parent has A" also becomes a plain forward step, with no guess at all. Choices are left only for rules that really say "one of these". To stop making new elements forever, an element that looks exactly like an earlier one is not expanded; it reuses the earlier one instead.
The problem
The input is an ALC concept and a TBox of general concept inclusions; the output is whether some model of puts an element in (concept satisfiability). Subsumption is the unsatisfiability of (concept subsumption). The problem is EXPTIME-complete (ALC with general TBoxes). This page and its code treat ALC without inverse roles; the paper covers much larger logics with inverse roles, nominals and number restrictions.
The algorithm
DL-clauses. Each inclusion becomes , and each disjunction is read as a clause over a center variable and one variable for each value restriction:
| disjunct | goes to | as |
|---|---|---|
| head | ||
| body | ||
| head | ||
| body | ||
| body and head | in the body, in the head | |
| head |
Here is when is a name and otherwise a fresh name with the clauses of . So is , is , and is , with no disjunction in any of them. The input concept gets a fresh name with the clauses of .
HYPERTABLEAU(C, T)- 1
Γ ← the DL-clauses of T and of Q0 ⊑ C; start with one node n0 and L(n0) = {Q0} - 2
repeat - 3
if a clause of Γ with at most one head atom has an instance σ whose body holds and whose head does not - 4
if the head is empty: return clash, with the branch points the body depends on - 5
add the head atom under σ; continue - 6
if a node x that is not BLOCKED has (∃r.A)(x) and no r-child with A: add a child w, r(x, w), A(w); continue - 7
if a clause with two or more head atoms has such an instance σ - 8
for each head atom V: try the branch with σ(V) added; stop on success; backjump past this point if the clash does not use V - 9
return clash, with the union of the branch points of the failed branches, without this one - 10
return satisfiable ▷ no rule applies: the nodes that are not blocked form a model BLOCKED(w)- 11
w is blocked if its parent is blocked, or if some earlier node that is not blocked has the same label
Lines L3 to L5 are the deterministic part of the Hyp-rule: a body that matches the current nodes forces its only head atom, or a clash when the head is empty. The body may look at the children of , so facts flow up the tree as well as down. Line L6 is the existential rule, applied before any branching so that clashes that need no choice are found first. Line L7 is the Hyp-rule with a real disjunction; line L8 tries each head atom in turn. Every fact carries the set of branch points it depends on, so a branch that fails for a reason that has nothing to do with the current choice returns at once to the choice that caused it, as in conflict-directed backjumping. Line L11 is anywhere blocking with equality: the blocker may sit anywhere in the tree, not only on the path to the root.
Example
Let and . The four clauses are (1) , (2) , (3) and (4) , where stands for .
| step | line | clause or rule | result |
|---|---|---|---|
| 1 | L1 | start | |
| 2 | L3, L5 | clause 3 at | |
| 3 | L6 | existential rule | new node , , |
| 4 | L3, L5 | clause 4 at | |
| 5 | L6 | existential rule | new node , , |
| 6 | L3, L5 | clause 1 with , | |
| 7 | L3, L5 | clause 1 with , | |
| 8 | L3, L4 | clause 2 at | clash: is unsatisfiable |
The run makes 2 nodes and 5 Hyp-rule steps and never branches. A plain tableau with subset blocking and no optimizations, the reference of the tests, reads the axiom as at every node and, on the same input, expands 3 nodes and tries 7 completions.
Correctness
The clauses have the same models as the TBox once each fresh name is read as . Each rule step is a consequence of the clauses, with the new nodes read as Skolem terms, so a clash that depends on a set of choices shows that those choices cannot hold together; this is also why backjumping is safe. The search stops: a node has at most one child for each existential atom, and the nodes on any path that still grows are not blocked and so have pairwise different labels, which bounds the depth by the number of possible labels. When no rule applies, the nodes that are not blocked form a model: an edge to a blocked node is sent to its blocker, which has the same label, so every clause instance in the model has a copy in the branch, where it already holds. The full proof, with the counterexample to subset blocking, is in proofs/correctness.md.
Proof: The hypertableau search for ALC with anywhere equality blocking terminates and is sound and completefull
We use the pseudocode of the page, lines L1 to L11. The logic is ALC with a general TBox and no inverse roles. The input is a concept , and the question is whether is satisfiable with respect to . The proof follows the structure of Motik, Shearer and Horrocks (2009), restricted to this setting, with the rule order, the blocking condition and the backjumping of the implementation.
DL-clauses
A DL-clause is a formula . Body atoms are , and ; every occurs in exactly one body atom . Head atoms are , and , with a concept name. With the head is false.
Line L1 builds the clauses as follows. A concept in negation normal form gives the clauses of : for the clauses of both parts; otherwise one clause from the disjuncts of . A disjunct gives the head atom ; gives the body atom ; gives the head atom ; gives a new variable , the body atom , and either the body atom when , or the head atom ; a conjunction gives the head atom . Here is itself when is a name, and otherwise a fresh name with the clauses of (for , those of and ). A disjunct or drops the clause; and are left out. The clauses are those of for each in , and those of for the root name . Call the set .
Lemma 1. (a) In every model of , for every fresh name, is a model of , and . (b) If is satisfiable with respect to , then has a model with .
Proof. (a) By induction on the size of . The clause made from reads , where is with some subconcepts replaced by ; by induction . In negation normal form every such occurs positively, so , and . The same argument applied to the clauses of the inclusions of and of gives the rest. The translation of each disjunct is equivalent to it: for example is , and is ; several -disjuncts use different variables, so the prenex form is still their disjunction. (b) Take a model of with , and set for every fresh name. Each clause then states a valid inclusion or an inclusion of .
The rules and the dependency sets
A branch is a tree of nodes. Each node has a label , a set of names and existential atoms; each node other than the root was made at line L6 from an existential atom of its parent, and the edge carries the role . Line L1 starts with . A clause instance is a map of to a node and of each to an -child of ; it is applicable when every body atom is in the branch and no head atom is. Lines L3 to L5 apply instances with at most one head atom; line L6 applies the existential rule at a node that is not blocked; line L7 branches on an instance with two or more head atoms, one branch for each head atom.
Nodes are numbered in the order they are made. A node is blocked if its parent is blocked, or if some node that is not blocked has (anywhere blocking with equality); in the second case is directly blocked by the least such . The status of depends only on nodes before , so it is well defined.
Every atom and every edge carries a set of branch levels. The root atom has the empty set. An atom added at line L5 gets the union of the sets of the body atoms and edges of the instance; at line L7 the alternative at level gets that union plus . A node made at line L6 and its edge get the set of the existential atom. An atom that is already present keeps its first set.
Read the node made from as the term of a Skolem function, and let be the formulas . A model of extends to a model of by choosing witnesses, so and are satisfiable together.
Lemma 2. Let be the set of the atoms chosen at line L7 on the current branch at the levels in . Every atom or edge with dependency set is a consequence of . A call at level that returns a set (a clash) returns , and is unsatisfiable.
Proof. The first part is by induction on the order of the steps: a step at line L5 is an instance of a clause of whose body facts are consequences of the sets they carry, and the union of those sets is the set of the new atom; a step at line L6 is an instance of ; an alternative at line L7 is in itself.
For the second part, use induction on the depth of the recursion. A clash at line L4 is an instance with an empty head whose body facts carry sets with union ; all of them were made below the current level, so , and by the first part the set is unsatisfiable. At a branch point at level with alternatives and body set , the call for returns with unsatisfiable. If , then uses only choices made above this branch point, and the call returns (backjumping). Otherwise every atom that carries was derived from , so its set contains the set of , and hence . Let . Then implies the body of the instance, so it implies , and with each it is unsatisfiable. So it is unsatisfiable, and .
Soundness. If the search answers "unsatisfiable", the top call at level 0 returned a set , so is unsatisfiable, so has no model with , and by Lemma 1(b) is unsatisfiable with respect to .
Termination
Let be the set of names of and the set of existential atoms in the heads of , and let . Labels are subsets of , and they only grow along a branch; edges are never removed.
- Out-degree. Line L6 makes a child for only when has no -child with , and after that it always has one. So a node has at most children.
- Depth. Two nodes that are both not blocked never have the same label, because then would be directly blocked. When line L6 makes a child of a node at depth , is not blocked, so none of its ancestors is blocked either. These nodes have pairwise different labels, so , and every node has depth at most .
So a branch has at most nodes and at most atoms on each, every step of lines L5 and L6 adds an atom or a node, and every branch point creates at most branches that are each longer by one atom. The search tree is finite, and the search stops.
Completeness
Lemma 3. If line L10 is reached, the following interpretation is a model of with . The domain is the set of nodes that are not blocked. A name holds at when . For each node of the domain and each child of with role , has the edge in , where if is not blocked and is the blocker of otherwise.
Proof. The root is never blocked, and . A child of a node that is not blocked is either not blocked or directly blocked, so is defined, it is in the domain, and .
Take a clause and a map of its variables into the domain that makes the body true in . Then for some -child of . Let map to and to . The body holds under in the branch: the edges are there, the names at are the same, and the names at are those at . Lines L3 and L7 found no applicable instance, so some head atom holds under in the branch. If it is , it holds in . If it is , then . If it is , then is not blocked and line L6 did not apply, so has an -child with , and has the edge with . In every case the clause holds under .
Theorem. The search returns "satisfiable" if and only if is satisfiable with respect to , and then the interpretation of Lemma 3 is a model of in which the root is in .
Proof. The search stops. If it answers "unsatisfiable", is unsatisfiable by the soundness argument. If it answers "satisfiable", Lemma 3 gives a model of with , and by Lemma 1(a) it is a model of with .
Subset blocking is not sound here
Blocking by an earlier node with is sound for the plain ALC tableau, where information only flows from a node to its children. A clause such as , from , sends information from a child to its parent, and then the proof of Lemma 3 fails: the edge to makes more body atoms true than the edge to . Take and . The -child made for has the label , a subset of the root label. Subset blocking stops there and answers "satisfiable". But that child needs a -successor, so it is in , which at the root forbids, and is unsatisfiable. Equality blocking does not block the child, and the search finds the clash.
Running time
The number of names and existential atoms is for an input of size . One branch has at most nodes, and the search tree has at most choices at each of at most branch points along a path, which bounds the time by . The space is one branch for each open branch point on the path, . These are coarse bounds for this simple search, not the complexity of the problem, which is EXPTIME-complete.
Complexity
Let be the size of and , so there are names and existential atoms. A branch has depth at most and out-degree , so it has at most nodes, and the depth-first search over the branch points is bounded by steps and space. These are coarse bounds for this search; satisfiability in ALC with a general TBox is EXPTIME-complete, and worst-case optimal methods use global caching or type elimination instead.
The gain is in the nondeterminism. For and the concept , the hypertableau makes 1 node, takes 3 Hyp-rule steps and never branches, because no node has any . The same plain tableau adds to every node and tries every combination at the root:
| plain tableau: nodes | plain tableau: completions tried | |
|---|---|---|
| 0 | 2 | 20 |
| 2 | 5 | 221 |
| 4 | 17 | 3185 |
| 6 | 65 | 49601 |
| 8 | 257 | 788225 |
Tableau reasoners with absorption, which turns into a rule that fires only on , also avoid this blow-up; the DL-clauses give the same effect for every inclusion whose left side is a conjunction of names and existential restrictions on names.
Properties
- Branching only on disjunctions. An inclusion with a conjunction of names and existential restrictions on names on the left, and no disjunction on the right, gives clauses with at most one head atom, and these never branch. When all clauses are of this kind, the search is deterministic.
- Facts flow both ways. A body atom lets a child change its parent, which is what makes deterministic.
- Builds a model. An open branch gives a finite model of with the root in .
- Exact. It answers both "yes" and "no" correctly for every ALC input.
Variants and improvements
- Expressive logics. Motik, Shearer and Horrocks (2009) extend the clauses with inverse roles, number restrictions, nominals and equality atoms between successors, with pairwise anywhere blocking for inverse roles.
- Blocking variants. Anywhere blocking lets the blocker be any earlier node, not only an ancestor, so trees stop earlier. Single blocking with equality, as here, suffices without inverse roles; pairwise blocking compares a node and its parent with another such pair.
- Absorption and caching. Reasoners combine the calculus with absorption of axioms into the clause bodies, caching of results for labels, and individual reuse between subsumption tests during ontology classification.
- Simple search. Without the dependency sets, chronological backtracking is correct too, but it can retry the same failing expansion under every combination of earlier, unrelated choices.
When to use it
Use it for satisfiability, subsumption and classification in expressive description logics, up to the SROIQ logic of OWL 2, especially for ontologies with many general concept inclusions whose left sides are conjunctions, where a plain tableau branches on every axiom at every node. For ontologies that stay inside the EL family, completion rules classify in polynomial time and are much faster. For query answering over large data in DL-Lite, query rewriting fits better.
Pitfalls
- Subset blocking. Line L11 must ask for an equal label. With "subset of an earlier label", the concept with and is reported satisfiable: the child for is blocked by the root, its -successor is never made, and the it would force upward is never seen. Subset blocking is sound only when facts flow downward, as in the plain tableau.
- A blocked blocker. At line L11, the earlier node must not be blocked itself. A blocked node does not expand its existential atoms, so redirecting edges to it builds an interpretation in which those atoms fail.
- Backjumping without the body set. At line L8, the head atom chosen at a branch point must carry the branch points of the clause body as well as its own. If it carries only its own, a clash that comes from the body is blamed on nothing, the search jumps over a choice that matters, and a satisfiable concept can be reported unsatisfiable.
- Clauses that guess. Line L1 must put into the body as . Writing it into the head through a fresh name with is still correct, but then becomes a clause with two head atoms, and line L7 branches at every node with an -successor, much as the plain tableau does.
- Branching first. If line L7 runs before line L6, a clash that needs no choice, deep in the tree, is found only after every choice above it, and without backjumping the search repeats it for each combination.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Test helper of the description logic pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A small reference decision procedure for ALC concept satisfiability with a general TBox.
The tests use it as an independent oracle. It is the plain tableau: depth first, a label is a set
of concepts in negation normal form, every node gets the concept nnf(not C or D) of each inclusion
C subsumed by D, and a new node is not made when its label is a subset of the label of an ancestor
(subset blocking, which is sound for ALC). Disjunctions are split in a fixed order with no
heuristics, so the node count shows how much search the plain method does.
"""
from typing import Iterator, Sequence
from dl import BOTTOM, GCI, Concept, conj, disj, neg, nnf
class Counter:
def __init__(self) -> None:
self.nodes = 0 # labels that were completed and expanded
self.branches = 0 # completions tried, clash-free or not
def _completions(s: frozenset, cnt: Counter) -> Iterator[frozenset]:
lab: set = set()
stack = list(s)
while stack:
c = stack.pop()
if c in lab:
continue
lab.add(c)
if c[0] == "and":
stack.append(c[1])
stack.append(c[2])
cnt.branches += 1
if BOTTOM in lab or any(c[0] == "not" and c[1] in lab for c in lab):
return
pending = sorted(repr(c) for c in lab if c[0] == "or" and c[1] not in lab and c[2] not in lab)
if not pending:
yield frozenset(lab)
return
c = next(c for c in lab if repr(c) == pending[0])
yield from _completions(frozenset(lab | {c[1]}), cnt)
yield from _completions(frozenset(lab | {c[2]}), cnt)
def _sat(label: frozenset, ancestors: tuple, tc: frozenset, cnt: Counter) -> bool:
cnt.nodes += 1
for lab in _completions(label, cnt):
path = ancestors + (lab,)
ok = True
for c in sorted((c for c in lab if c[0] == "some"), key=repr):
child = frozenset({c[2]} | {d[2] for d in lab if d[0] == "all" and d[1] == c[1]}) | tc
if tc and any(child <= a for a in path):
continue # blocked: the ancestor's label serves as the successor
if not _sat(child, path, tc, cnt):
ok = False
break
if ok:
return True
return False
def satisfiable_count(c: Concept, tbox: Sequence[GCI] = ()) -> tuple[bool, Counter]:
"""Decide whether c is satisfiable with respect to the TBox; also return the work counter."""
tc = frozenset(nnf(disj(neg(x), y)) for x, y in tbox)
cnt = Counter()
return _sat(frozenset({nnf(c)}) | tc, (), tc, cnt), cnt
def satisfiable(c: Concept, tbox: Sequence[GCI] = ()) -> bool:
return satisfiable_count(c, tbox)[0]
def subsumes(c: Concept, d: Concept, tbox: Sequence[GCI] = ()) -> bool:
"""True when c is subsumed by d with respect to the TBox."""
return not satisfiable(conj(c, neg(d)), tbox)
dl.py 232 lines
# SPDX-License-Identifier: MIT
# Shared helper of the description logic pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""ALC concepts as syntax trees, negation normal form, and evaluation in a finite interpretation.
A concept is a tuple:
TOP = ("top",) BOTTOM = ("bottom",)
("atom", "A") ("not", C)
("and", C, D) ("or", C, D)
("some", "r", C) ("all", "r", C)
A TBox is a sequence of general concept inclusions (C, D), read C is subsumed by D.
An interpretation has a nonempty finite domain, a set for each concept name and a set of pairs
for each role name. Names that an interpretation does not list are empty.
This file holds only the syntax and the semantics. No reasoning algorithm goes here.
"""
from itertools import product
from typing import Iterable, Iterator, Sequence
Concept = tuple
GCI = tuple[Concept, Concept]
TOP: Concept = ("top",)
BOTTOM: Concept = ("bottom",)
def atom(name: str) -> Concept:
return ("atom", name)
def neg(c: Concept) -> Concept:
return ("not", c)
def conj(*cs: Concept) -> Concept:
"""The conjunction of the arguments, nested to the right. conj() is TOP."""
if not cs:
return TOP
out = cs[-1]
for c in reversed(cs[:-1]):
out = ("and", c, out)
return out
def disj(*cs: Concept) -> Concept:
"""The disjunction of the arguments, nested to the right. disj() is BOTTOM."""
if not cs:
return BOTTOM
out = cs[-1]
for c in reversed(cs[:-1]):
out = ("or", c, out)
return out
def exists(r: str, c: Concept) -> Concept:
return ("some", r, c)
def forall(r: str, c: Concept) -> Concept:
return ("all", r, c)
def nnf(c: Concept) -> Concept:
"""Negation normal form: an equivalent concept with negation only in front of concept names."""
op = c[0]
if op in ("top", "bottom", "atom"):
return c
if op in ("and", "or"):
return (op, nnf(c[1]), nnf(c[2]))
if op in ("some", "all"):
return (op, c[1], nnf(c[2]))
d = c[1] # op == "not"
dop = d[0]
if dop == "top":
return BOTTOM
if dop == "bottom":
return TOP
if dop == "atom":
return c
if dop == "not":
return nnf(d[1])
if dop == "and":
return ("or", nnf(neg(d[1])), nnf(neg(d[2])))
if dop == "or":
return ("and", nnf(neg(d[1])), nnf(neg(d[2])))
if dop == "some":
return ("all", d[1], nnf(neg(d[2])))
return ("some", d[1], nnf(neg(d[2]))) # dop == "all"
def is_nnf(c: Concept) -> bool:
op = c[0]
if op in ("top", "bottom", "atom"):
return True
if op == "not":
return c[1][0] == "atom"
if op in ("and", "or"):
return is_nnf(c[1]) and is_nnf(c[2])
return is_nnf(c[2])
def subconcepts(c: Concept) -> set[Concept]:
"""All subconcepts of c, c included."""
out = {c}
op = c[0]
if op == "not":
out |= subconcepts(c[1])
elif op in ("and", "or"):
out |= subconcepts(c[1]) | subconcepts(c[2])
elif op in ("some", "all"):
out |= subconcepts(c[2])
return out
def size(c: Concept) -> int:
"""The number of constructors and names in c."""
op = c[0]
if op in ("top", "bottom", "atom"):
return 1
if op == "not":
return 1 + size(c[1])
if op in ("and", "or"):
return 1 + size(c[1]) + size(c[2])
return 2 + size(c[2])
def role_depth(c: Concept) -> int:
"""The largest number of nested role restrictions in c."""
op = c[0]
if op in ("top", "bottom", "atom"):
return 0
if op == "not":
return role_depth(c[1])
if op in ("and", "or"):
return max(role_depth(c[1]), role_depth(c[2]))
return 1 + role_depth(c[2])
def names(cs: Iterable[Concept]) -> tuple[list[str], list[str]]:
"""The sorted concept names and role names that occur in the given concepts."""
cn: set[str] = set()
rn: set[str] = set()
for c in cs:
for s in subconcepts(c):
if s[0] == "atom":
cn.add(s[1])
elif s[0] in ("some", "all"):
rn.add(s[1])
return sorted(cn), sorted(rn)
def show(c: Concept) -> str:
"""The concept in the usual notation, with full parentheses."""
op = c[0]
if op == "top":
return "⊤"
if op == "bottom":
return "⊥"
if op == "atom":
return c[1]
if op == "not":
return "¬" + show(c[1])
if op == "and":
return "(" + show(c[1]) + " ⊓ " + show(c[2]) + ")"
if op == "or":
return "(" + show(c[1]) + " ⊔ " + show(c[2]) + ")"
q = "∃" if op == "some" else "∀"
return q + c[1] + "." + show(c[2])
class Interpretation:
"""A finite interpretation. domain is a nonempty list; concepts maps a name to a set of elements;
roles maps a name to a set of pairs of elements."""
def __init__(self, domain: Sequence, concepts: dict, roles: dict) -> None:
if not domain:
raise ValueError("the domain of an interpretation is not empty")
self.domain = list(domain)
self.concepts = {a: frozenset(s) for a, s in concepts.items()}
self.roles = {r: frozenset(p) for r, p in roles.items()}
self._succ: dict[str, dict] = {}
def successors(self, r: str, x) -> list:
if r not in self._succ:
m: dict = {y: [] for y in self.domain}
for (u, v) in self.roles.get(r, ()):
m[u].append(v)
self._succ[r] = m
return self._succ[r][x]
def __repr__(self) -> str:
return f"Interpretation({self.domain!r}, {self.concepts!r}, {self.roles!r})"
def evaluate(c: Concept, i: Interpretation) -> frozenset:
"""The extension of c in the interpretation i, by the semantics of ALC."""
op = c[0]
if op == "top":
return frozenset(i.domain)
if op == "bottom":
return frozenset()
if op == "atom":
return i.concepts.get(c[1], frozenset())
if op == "not":
return frozenset(i.domain) - evaluate(c[1], i)
if op == "and":
return evaluate(c[1], i) & evaluate(c[2], i)
if op == "or":
return evaluate(c[1], i) | evaluate(c[2], i)
ext = evaluate(c[2], i)
if op == "some":
return frozenset(x for x in i.domain if any(y in ext for y in i.successors(c[1], x)))
return frozenset(x for x in i.domain if all(y in ext for y in i.successors(c[1], x)))
def is_model_of_tbox(i: Interpretation, tbox: Iterable[GCI]) -> bool:
"""True when i satisfies every inclusion C subsumed by D of the TBox."""
return all(evaluate(c, i) <= evaluate(d, i) for c, d in tbox)
def interpretations(concept_names: Sequence[str], role_names: Sequence[str], max_size: int) -> Iterator[Interpretation]:
"""Every interpretation of the given names over the domains [0], [0, 1], ..., [0, ..., max_size - 1].
There are sum over n of 2^(n * |concept_names| + n^2 * |role_names|) of them."""
for n in range(1, max_size + 1):
dom = list(range(n))
pairs = [(x, y) for x in dom for y in dom]
cbits = list(product((False, True), repeat=n * len(concept_names)))
rbits = list(product((False, True), repeat=n * n * len(role_names)))
for rb in rbits:
roles = {r: {pairs[k] for k in range(n * n) if rb[j * n * n + k]} for j, r in enumerate(role_names)}
for cb in cbits:
conc = {a: {x for x in dom if cb[j * n + x]} for j, a in enumerate(concept_names)}
yield Interpretation(dom, conc, roles)
hypertableau.py 295 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hypertableau/. The authors are listed in prov/974KXE.jsonl.
"""The hypertableau calculus for ALC concept satisfiability with a general TBox.
The TBox and the input concept are first turned into DL-clauses
U_1 and ... and U_m -> V_1 or ... or V_n
over a center variable x and successor variables y_1, ..., y_k. Body atoms are A(x), r(x, y_i)
and A(y_i); head atoms are A(x), A(y_i) and the existential atom (some r.A)(x). An empty head
means a clash. Negative literals go to the body, so labels hold only names and existential atoms.
A clause is a tuple (bx, roles, by, head):
bx frozenset of concept names that must hold at x
roles tuple of role names; y_i is an r_i-successor of x
by tuple of frozensets; by[i] is the set of names that must hold at y_i
head tuple of atoms ("x", A), ("y", i, A) or ("some", r, A)
Fresh concept names start with "_Q". The search works on a tree of nodes; node 0 is the root.
Every atom and every edge carries the set of branch points it depends on, so that a clash can
jump back over branch points that did not take part in it (backjumping).
"""
from itertools import product
from typing import Optional, Sequence
from dl import BOTTOM, TOP, GCI, Concept, Interpretation, disj, neg, nnf
class Clausifier:
"""The structural transformation of NNF concepts into DL-clauses."""
def __init__(self) -> None:
self.clauses: list[tuple] = []
self.fresh: dict[Concept, str] = {}
def name_for(self, c: Concept) -> str:
"""A concept name Q with the clauses of Q subsumed by c. Reused for equal concepts."""
if c[0] == "atom":
return c[1]
if c not in self.fresh:
q = f"_Q{len(self.fresh) + 1}"
self.fresh[c] = q
self.define(q, c)
return self.fresh[c]
def define(self, q: str, c: Concept) -> None:
if c[0] == "and":
self.define(q, c[1])
self.define(q, c[2])
else:
self.axiom(("or", ("not", ("atom", q)), c))
def axiom(self, e: Concept) -> None:
"""Add the clauses of top subsumed by e, for e in NNF."""
if e[0] == "and":
self.axiom(e[1])
self.axiom(e[2])
return
stack, disjuncts = [e], []
while stack:
d = stack.pop()
if d[0] == "or":
stack += [d[2], d[1]]
else:
disjuncts.append(d)
bx: set[str] = set()
roles: list[str] = []
by: list[frozenset] = []
head: list[tuple] = []
for d in disjuncts:
op = d[0]
if op == "top" or (op == "all" and d[2] == TOP):
return # the clause holds everywhere
if op == "bottom" or (op == "some" and d[2] == BOTTOM):
continue
if op == "atom":
head.append(("x", d[1]))
elif op == "not":
bx.add(d[1][1])
elif op == "some":
head.append(("some", d[1], self.name_for(d[2])))
elif op == "all":
i = len(roles)
roles.append(d[1])
inner = d[2]
if inner == BOTTOM:
by.append(frozenset())
elif inner[0] == "not":
by.append(frozenset({inner[1][1]}))
else:
by.append(frozenset())
head.append(("y", i, self.name_for(inner)))
else: # a conjunction inside a disjunction gets a fresh name
head.append(("x", self.name_for(d)))
self.clauses.append((frozenset(bx), tuple(roles), tuple(by), tuple(dict.fromkeys(head))))
def clausify(c: Concept, tbox: Sequence[GCI] = ()) -> tuple[str, list[tuple]]:
"""The DL-clauses of the TBox and of Q0 subsumed by c, and the name Q0 that the root gets."""
cl = Clausifier()
for x, y in tbox:
cl.axiom(nnf(disj(neg(x), y)))
root = cl.name_for(nnf(c))
return root, cl.clauses
class Counter:
def __init__(self) -> None:
self.nodes = 0 # nodes made by the existential rule, over all branches
self.branches = 0 # alternatives tried at nondeterministic Hyp-rule steps
self.hyp = 0 # Hyp-rule steps
NODEPS: frozenset = frozenset()
class State:
"""One branch: a tree of nodes. labels[x] maps each atom of node x to the branch points it
depends on; edge[w] is the same for the edge from the parent of w to w. Node ids follow the
order of creation."""
def __init__(self, root: str) -> None:
self.labels: list[dict] = [{root: NODEPS}]
self.parent: list[Optional[int]] = [None]
self.role: list[Optional[str]] = [None]
self.edge: list[frozenset] = [NODEPS]
self.children: list[list[int]] = [[]]
def copy(self) -> "State":
s = State.__new__(State)
s.labels = [dict(lab) for lab in self.labels]
s.parent = list(self.parent)
s.role = list(self.role)
s.edge = list(self.edge)
s.children = [list(ch) for ch in self.children]
return s
def blocking(s: State, mode: str = "equal") -> tuple[list[bool], dict[int, int]]:
"""Which nodes are blocked, and the blocker of each directly blocked node. A node is blocked
when its parent is blocked, or when an earlier node that is not blocked has the same label
(mode "equal", anywhere blocking) or a superset of its label (mode "subset", unsound here)."""
status: list[bool] = []
blocker: dict[int, int] = {}
first: dict[frozenset, int] = {}
open_labels: list[tuple[int, frozenset]] = []
for w in range(len(s.labels)):
p = s.parent[w]
if p is not None and status[p]:
status.append(True)
continue
key = frozenset(s.labels[w])
if mode == "equal":
v = first.get(key)
else:
v = next((u for u, lab in open_labels if key <= lab), None)
if v is None:
first[key] = w
open_labels.append((w, key))
status.append(False)
else:
blocker[w] = v
status.append(True)
return status, blocker
def _holds(s: State, x: int, sigma: tuple, atom: tuple) -> bool:
if atom[0] == "x":
return atom[1] in s.labels[x]
if atom[0] == "y":
return atom[2] in s.labels[sigma[atom[1]]]
return atom in s.labels[x]
def _find_hyp(s: State, clauses: Sequence[tuple], deterministic: bool):
"""The first clause instance whose body holds and whose head has no atom that holds, with the
branch points that its body depends on."""
for x in range(len(s.labels)):
lab = s.labels[x]
for cl in clauses:
bx, roles, by, head = cl
if (len(head) <= 1) != deterministic or not bx <= lab.keys():
continue
cands = [[w for w in s.children[x] if s.role[w] == r and by[i] <= s.labels[w].keys()] for i, r in enumerate(roles)]
for sigma in product(*cands):
if not any(_holds(s, x, sigma, a) for a in head):
deps = set().union(*(lab[a] for a in bx))
for i, w in enumerate(sigma):
deps |= s.edge[w]
deps = deps.union(*(s.labels[w][a] for a in by[i]))
return x, sigma, head, frozenset(deps)
return None
def _add(s: State, x: int, sigma: tuple, atom: tuple, deps: frozenset) -> None:
if atom[0] == "x":
s.labels[x].setdefault(atom[1], deps)
elif atom[0] == "y":
s.labels[sigma[atom[1]]].setdefault(atom[2], deps)
else:
s.labels[x].setdefault(atom, deps)
def _exists_rule(s: State, mode: str, cnt: Counter) -> bool:
"""Apply the existential rule once, at the first node that is not blocked and has an
existential atom without a witness. Return False when there is no such node."""
status, _ = blocking(s, mode) # @line L11
for x in range(len(s.labels)):
if status[x]:
continue
for atom in sorted(a for a in s.labels[x] if isinstance(a, tuple)):
_, r, a = atom
if not any(s.role[w] == r and a in s.labels[w] for w in s.children[x]):
deps = s.labels[x][atom]
w = len(s.labels)
s.labels.append({a: deps})
s.parent.append(x)
s.role.append(r)
s.edge.append(deps)
s.children.append([])
s.children[x].append(w)
cnt.nodes += 1
return True
return False
def _search(s: State, clauses: Sequence[tuple], mode: str, cnt: Counter, out: list, level: int):
"""Return None when the branch has a clash-free completion (stored in out), and otherwise the
set of branch points that the clashes depend on."""
while True: # @line L2
app = _find_hyp(s, clauses, True) # @line L3
if app is not None:
cnt.hyp += 1
x, sigma, head, deps = app
if not head: # @line L4
return deps
_add(s, x, sigma, head[0], deps) # @line L5
continue
if _exists_rule(s, mode, cnt): # @line L6
continue
app = _find_hyp(s, clauses, False)
if app is not None: # @line L7
cnt.hyp += 1
x, sigma, head, deps = app
clash: set = set()
for atom in head:
cnt.branches += 1
s2 = s.copy()
_add(s2, x, sigma, atom, deps | {level})
d = _search(s2, clauses, mode, cnt, out, level + 1) # @line L8
if d is None:
return None
if level not in d:
return d # backjump: this choice took no part in the clash
clash |= d - {level}
return frozenset(clash) # @line L9
out.append(s)
return None # @line L10
def satisfiable_count(c: Concept, tbox: Sequence[GCI] = (), mode: str = "equal") -> tuple[bool, Counter, Optional[State]]:
"""Decide satisfiability of c with respect to the TBox. Also return the work counter and the
final state of the open branch, if there is one."""
root, clauses = clausify(c, tbox) # @line L1
cnt = Counter()
out: list = []
ok = _search(State(root), clauses, mode, cnt, out, 0) is None
return ok, cnt, (out[0] if out else None)
def satisfiable(c: Concept, tbox: Sequence[GCI] = ()) -> bool:
return satisfiable_count(c, tbox)[0]
def subsumes(c: Concept, d: Concept, tbox: Sequence[GCI] = ()) -> bool:
return not satisfiable(("and", c, neg(d)), tbox)
def model_of(s: State) -> Interpretation:
"""The model of an open branch (equality blocking): the nodes that are not blocked, with each
edge to a directly blocked node sent to its blocker. The root is element 0."""
status, blocker = blocking(s, "equal")
dom = [x for x in range(len(s.labels)) if not status[x]]
concepts: dict[str, set] = {}
roles: dict[str, set] = {}
for x in dom:
for a in s.labels[x]:
if isinstance(a, str):
concepts.setdefault(a, set()).add(x)
for w in s.children[x]:
roles.setdefault(s.role[w], set()).add((x, blocker.get(w, w)))
return Interpretation(dom, concepts, roles)
def model(c: Concept, tbox: Sequence[GCI] = ()) -> Optional[Interpretation]:
ok, _, s = satisfiable_count(c, tbox)
return model_of(s) if ok else None
test_hypertableau.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hypertableau/. The authors are listed in prov/974KXE.jsonl.
"""Tests of the hypertableau calculus against the plain ALC tableau of alc_reference.py.
Every "satisfiable" answer is also checked on its own: the model built from the open branch must
put the root in the concept and satisfy every inclusion of the TBox, by the semantics in dl.py.
"""
import random
import alc_reference as ref
from dl import BOTTOM, atom, conj, disj, evaluate, exists, forall, is_model_of_tbox, neg
from hypertableau import clausify, model_of, satisfiable, satisfiable_count, subsumes
A, B, C, D, E, W = (atom(x) for x in "ABCDEW")
def check(c, tbox) -> bool:
ok, _, s = satisfiable_count(c, tbox)
assert ok == ref.satisfiable(c, tbox)
if ok:
m = model_of(s)
assert 0 in evaluate(c, m) and is_model_of_tbox(m, tbox)
return ok
def test_page_example() -> None:
# not A and some r.some r.A, with some r.A subsumed by A: unsatisfiable without any choice.
c = conj(neg(A), exists("r", exists("r", A)))
tbox = [(exists("r", A), A)]
root, clauses = clausify(c, tbox)
assert len(clauses) == 4
assert (frozenset(), ("r",), (frozenset({"A"}),), (("x", "A"),)) in clauses
ok, cnt, _ = satisfiable_count(c, tbox)
assert not ok and cnt.nodes == 2 and cnt.branches == 0 and cnt.hyp == 5
r_ok, r_cnt = ref.satisfiable_count(c, tbox)
assert not r_ok and r_cnt.nodes == 3 and r_cnt.branches == 7
def test_clause_shapes() -> None:
# A and B subsumed by C or for all r.D: one clause, two head atoms, one successor variable.
_, clauses = clausify(A, [(conj(A, B), disj(C, forall("r", D)))])
assert (frozenset({"A", "B"}), ("r",), (frozenset(),), (("x", "C"), ("y", 0, "D"))) in clauses
# for all r.not A in a head goes to the body as A(y).
_, clauses = clausify(A, [(B, forall("r", neg(A)))])
assert (frozenset({"B"}), ("r",), (frozenset({"A"}),), ()) in clauses
def test_cyclic_tbox_needs_blocking() -> None:
ok, cnt, s = satisfiable_count(A, [(A, exists("r", A))])
assert ok and cnt.nodes == 1
m = model_of(s)
assert m.domain == [0] and m.roles["r"] == {(0, 0)}
assert check(A, [(A, exists("r", A))])
def test_subset_blocking_is_unsound() -> None:
# The child made for some r.W has the label {W, some r.B}, a subset of the root label. Subset
# blocking stops there and misses that its B-successor forces A, which the root forbids.
c = conj(A, W, exists("r", W), forall("r", neg(A)))
tbox = [(W, exists("r", B)), (exists("r", B), A)]
assert not ref.satisfiable(c, tbox)
assert not satisfiable_count(c, tbox, "equal")[0]
assert satisfiable_count(c, tbox, "subset")[0]
def test_backjumping() -> None:
# m independent choices, then a choice whose both sides clash on their own.
for m in range(1, 9):
c = conj(*[disj(atom(f"B{i}"), atom(f"C{i}")) for i in range(m)], disj(D, E), neg(D), neg(E))
ok, cnt, _ = satisfiable_count(c)
assert not ok and cnt.branches == m + 2
def test_or_branching_family() -> None:
# B_i subsumed by C_i for i < m, and A subsumed by some r.D with D unsatisfiable. The plain
# tableau adds not B_i or C_i to every node and tries 2^m completions of the root; the
# clauses B_i(x) -> C_i(x) never fire.
last = 0
for m in range(0, 6):
tbox = [(atom(f"B{i}"), atom(f"C{i}")) for i in range(m)] + [(A, exists("r", D)), (D, E), (E, BOTTOM)]
ok, cnt, _ = satisfiable_count(A, tbox)
assert not ok and cnt.nodes == 1 and cnt.branches == 0 and cnt.hyp == 3
r_ok, r_cnt = ref.satisfiable_count(A, tbox)
assert not r_ok and r_cnt.nodes == 2 ** m + 1 and r_cnt.branches > last
last = r_cnt.branches
def rand_concept(rng: random.Random, d: int, cn, rn):
if d == 0 or rng.random() < 0.3:
a = atom(rng.choice(cn))
return neg(a) if rng.random() < 0.4 else a
k = rng.random()
if k < 0.25:
return conj(rand_concept(rng, d - 1, cn, rn), rand_concept(rng, d - 1, cn, rn))
if k < 0.5:
return disj(rand_concept(rng, d - 1, cn, rn), rand_concept(rng, d - 1, cn, rn))
if k < 0.75:
return exists(rng.choice(rn), rand_concept(rng, d - 1, cn, rn))
if k < 0.9:
return forall(rng.choice(rn), rand_concept(rng, d - 1, cn, rn))
return neg(rand_concept(rng, d - 1, cn, rn))
def run_random(seed: int, count: int, cn, rn) -> list[int]:
rng = random.Random(seed)
seen = [0, 0]
for _ in range(count):
c = rand_concept(rng, 3, cn, rn)
tbox = [(rand_concept(rng, 2, cn, rn), rand_concept(rng, 2, cn, rn)) for _ in range(rng.randint(0, 3))]
seen[check(c, tbox)] += 1
return seen
def test_random_one_role() -> None:
unsat, sat = run_random(1, 2000, ["A", "B"], ["r"])
assert unsat >= 150 and sat >= 1500
def test_random_two_roles() -> None:
unsat, sat = run_random(6, 1000, ["A", "B", "C"], ["r", "s"])
assert unsat >= 40 and sat >= 800
def test_subsumption() -> None:
tbox = [(exists("r", A), A)]
assert subsumes(exists("r", exists("r", A)), A, tbox)
assert not subsumes(A, exists("r", A), tbox)
History
Hyperresolution is due to Robinson (1965); hyper tableaux for first-order clauses were studied by Baumgartner, Furbach and Niemelä in the 1990s. Motik, Shearer and Horrocks (2009) adapted the idea to description logics: they defined DL-clauses, the Hyp-rule and anywhere pairwise blocking, proved the calculus correct for expressive logics with inverse roles, nominals and number restrictions, and showed with the HermiT reasoner that it classifies many ontologies faster than tableau reasoners of the time. HermiT is one of the standard reasoners for OWL 2.
References
- Boris Motik, Rob Shearer and Ian Horrocks, Hypertableau reasoning for description logics, Journal of Artificial Intelligence Research 36, 2009, pages 165 to 228 (Table 4 on page 192 for the translation into DL-clauses, Definition 7 on page 193 and Table 5 on page 196 for the rules, Section 3.1.1 for the example with some R.A subsumed by A, Section 3.2.2 for anywhere blocking)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 974KXE Edit this page History Report an error Markdown