Algorithmcore
Structural subsumption algorithm
Also called normalize-compare subsumption.
Normalizes two concepts of a small description logic and compares them part by part. It is sound and complete for FL-, but it fails once role restrictions or full negation are added.
- Solves
- Concept subsumption
- Time
- O(n log n) worstO(n) expected
- Space
- O(n) extra
- Where
- n = the total size of the two concepts
- Model
- Word RAM
- Properties
- builds counter modeldeterministicexactrecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ronald J. Brachman, Hector J. Levesque, 1984
Structural subsumption decides whether one concept of a small description logic is subsumed by another. It puts both concepts in a normal form and then compares the normal forms part by part, with no search. For the language FL- it is sound and complete and runs in linear time. Early frame-based systems used it, and it fails as soon as the language has role restrictions, disjunction or full negation.
In plain words
You have two descriptions, and you want to know if everything that fits the first one must fit the second. First you tidy each description: you collect the plain properties, the kinds of links that must exist, and, for each kind of link, everything that all linked objects must satisfy. Then you go through the second description piece by piece. Each property it asks for must be in the first one. Each link it asks for must be there too. For each kind of link, the demands on the linked objects must again pass the same test, one level down. If one piece is missing, the answer is no, and the missing piece shows how to build an object that fits the first description and not the second.
The problem
The input is two concepts and of FL-, and there is no TBox. FL- concepts are built from concept names , the top concept , conjunction , value restriction and unqualified existential restriction , written . The question is concept subsumption: does hold in every interpretation ? We write .
FL- has no and no negation, so every concept is satisfiable, and no part of a concept can make another part true by a contradiction. This is why a comparison of parts is enough. FL0 is the part of FL- without , and the same method works for it.
The algorithm
The normal form of a concept is a tree. Each node has a set of concept names, a set of roles with , and at most one child for each role , which collects the fillers of all value restrictions on at that place. The equivalences and justify the merge and the removal of empty children.
NORMALIZE(C)- 1
root ← a new node with N = ∅, E = ∅ and no children - 2
INSERT(root, C) - 3
remove every child V_x(r) whose subtree has no names and no roles ▷ ∀r.⊤ is ⊤ - 4
return root INSERT(x, C)- 5
if C is a concept name A then add A to N_x - 6
if C is ∃r then add r to E_x - 7
if C is C1 ⊓ C2 then INSERT(x, C1); INSERT(x, C2) - 8
if C is ∀r.C1 then if V_x(r) is undefined, set V_x(r) ← a new empty node; INSERT(V_x(r), C1) ▷ C = ⊤ adds nothingSUBSUMES(c, d) ▷ c, d: normal forms of C and D; true iff C ⊑ D- 9
if N_d ⊄ N_c or E_d ⊄ E_c then return false - 10
for each role r with V_d(r) defined do - 11
if V_c(r) is undefined or SUBSUMES(V_c(r), V_d(r)) is false then return false - 12
return true
INSERT walks the concept once. Line L8 sends every value restriction on at the same place to the same child, so and get the same tree. Line L3 runs bottom up, so a chain such as disappears completely.
SUBSUMES then reads the conjuncts of off its tree. A name or an of must be a conjunct of at the same place (line L9). A value restriction of needs a value restriction of with (line L11). If has no value restriction on , then says nothing about its -successors, and since is not empty after line L3, the answer is no.
When the answer is no, the failing test gives a counter-model. Build a tree for with one -successor for each . At the node where line L9 fails, the missing name or the missing successor already makes the element fail . Where line L11 fails for , give the element one -successor that is, recursively, in but not in .
Example
Take and .
| step | line | state |
|---|---|---|
| 1 | L5 to L8 | root of : , ; child for : ; its child for : |
| 2 | L5 to L8 | root of : , ; child for : ; its child for is empty |
| 3 | L3 | the empty child for in is removed |
| 4 | L9 | root: and , pass |
| 5 | L11 | role : compare the two children |
| 6 | L9 | and , pass; has no child here |
| 7 | L12 | return true, so |
The normal forms print as and .
Now take . Its tree has a child for with a child for that holds . At that depth line L9 finds and returns false. The counter-model has 3 elements: element 0 in , an -edge to element 1 in and , and an -edge from 1 to element 2 in only. Element 0 is in , and it is not in because element 2 is not in .
Correctness
The invariant of NORMALIZE is that after each call INSERT the concept read off the tree at is equivalent to the old one conjoined with . Line L3 keeps the equivalence because . Soundness of SUBSUMES is an induction on the depth of : each conjunct of is a conjunct of , or follows from a value restriction of by induction. Completeness is the counter-model construction above, which is a finite tree. With one role name the counter-model is a path, so it has at most one more element than the larger role depth of and . The full proof is in proofs/correctness.md.
Proof: Structural subsumption is sound and complete for FL- and runs in linear timefull
We use the pseudocode of the page, lines L1 to L12. FL- concepts are built from concept names, , , and (written ). There is no TBox. A normal form node has a set of concept names, a set of roles and a partial map from roles to nodes. The concept of a node is
with the empty conjunction equal to . A node is empty when , and are all empty; then .
Termination
INSERT (lines L5 to L8) calls itself only on direct subconcepts, so it makes one call for each occurrence of a subconcept of . PRUNE visits each node once. SUBSUMES (lines L9 to L12) calls itself only on , one level deeper in both trees, so it stops after at most levels, where is the role depth. All three procedures stop.
Lemma 1 (the normal form is equivalent)
For every FL- concept , .
Proof. Before PRUNE, we show by induction on the INSERT calls that after INSERT the concept is equivalent to the old . For a name (L5) and for (L6) this is the definition of con. For (L7) it follows from two applications of the induction hypothesis. For (L8), the call changes only the child , and by induction becomes (a new child starts empty, with concept ). The equivalence holds in every interpretation: an element has all its -successors in exactly when it has them all in and all in . For nothing changes and . The root starts empty (L1), so after L2 the root has concept equivalent to .
PRUNE removes a child only when its subtree is empty, so its concept is . Since (every successor is in the domain), the removal does not change the concept of up to equivalence.
From now on and are the pruned normal forms of and . After PRUNE, every child is nonempty.
Lemma 2 (soundness)
If SUBSUMES returns true, then .
Proof. By induction on the depth of . Take an interpretation and . Line L9 passed, so and ; each name of and each with is a conjunct of , so is in it. For each , line L11 passed, so exists and SUBSUMES is true. Each -successor of is in , because is a conjunct of . By induction . So . All conjuncts of hold at .
Lemma 3 (completeness, with a counter-model)
Let TREE make an element with the names and, for each , one -successor TREE, or TREE of an empty node when is undefined. Then in the interpretation that is built.
If SUBSUMES returns false, then COUNTER of the implementation builds a finite tree interpretation with an element in and not in . So .
Proof. For TREE, by induction on the depth of : has the names of ; it has an -successor for each ; and for each , every -successor of is TREE (when ) or there is none (when ), and in both cases every -successor is in . Elements get no other names or edges, and the tree has no edges back, so the evaluation of each subtree does not change.
For COUNTER, by induction on the depth of . Case 1: line L9 fails. COUNTER returns TREE, which is in . Either a name , and is not in , or a role , and has no -successor, so . Case 2: line L11 fails for a role . Let , or an empty node if it is undefined, and , which is nonempty after PRUNE. SUBSUMES is false. When is defined, this is what L11 found. When it is undefined, is empty and is not: if has a name or a role, L9 fails; otherwise has a child, and L11 fails because has none. COUNTER makes with the names , one -successor TREE for each with , and exactly one -successor $f = $ COUNTER. By induction and . So : the names hold, each holds (for the successor is ), and every successor satisfies the matching value restriction. And , so .
Theorem
SUBSUMES(NORMALIZE, NORMALIZE) returns true if and only if .
Proof. By Lemma 1, and . If the answer is true, Lemma 2 gives . If it is false, Lemma 3 gives an interpretation with an element in and not in .
Size of the counter-model
With one role name, the element of TREE has at most one successor, so TREE builds a path with at most elements. COUNTER also gives each element at most one successor, and each step goes one level deeper in or in . So a counter-model exists with at most elements. The tests use this bound: for one role and role depth at most 2, a search over all interpretations with at most 3 elements decides subsumption.
Running time
INSERT does a constant number of set or map operations for each occurrence of a constructor or name in , so NORMALIZE takes operations and makes at most nodes. SUBSUMES visits each node of at most once and pairs it with one node of ; the inclusion tests of L9 cost lookups for that node. The total is hash set operations, so expected time, and space.
Complexity
NORMALIZE does a constant number of set and map operations for each name and constructor of the concept, and SUBSUMES visits each node of the tree of once and pairs it with one node of the tree of . With hash sets the expected time is , where . With sorted sets the time is in the worst case. The space is . Brachman and Levesque (1984) stated a polynomial bound for FL-.
Properties
- Deterministic. There is no choice and no backtracking.
- Exact for FL- and FL0. The answer is right in both directions, and a "no" comes with a counter-model.
- Syntax directed. The test compares conjuncts at the same role path, so it is easy to explain which part of is missing in .
- Normal form is canonical. Two FL- concepts are equivalent if and only if they have the same normal form, up to the order of names and roles.
Variants and improvements
- CLASSIC. Borgida and Patel-Schneider (1994) gave a normalize and compare algorithm for the CLASSIC language, with number restrictions and other constructors, and proved it complete with respect to a semantics they defined for it.
- ALN and languages with ⊥. With , atomic negation or number restrictions, the normal form must first find the parts that are unsatisfiable, such as or , and replace them by . Then the comparison works again for such small languages.
- Acyclic TBoxes. Unfold the defined names first and then compare. The unfolding can be exponentially large, and Nebel (1990) showed that subsumption with respect to acyclic TBoxes is coNP-hard even for very small languages.
- Larger languages. For ALC, use the tableau algorithm. For the EL family with a TBox, use EL classification.
When to use it
Use it when the language has only conjunction, value restrictions and unqualified existentials, possibly with simple number restrictions, and you need many subsumption tests, for example to classify the concepts of a small frame-based knowledge base. It is fast and easy to explain. Do not use it for a language with disjunction, full negation or qualified existentials together with value restrictions; there it gives wrong "no" answers.
Pitfalls
- Keeping empty value restrictions. If line L3 is left out, keeps an empty child for , and line L11 returns false for , although holds. Remove empty children at line L3 before any comparison.
- Not merging value restrictions. If line L8 makes a new child for each instead of reusing , then has two children for , and no one of them is below . The test then says no to , which holds. Line L8 must reuse the child.
- Adding role restrictions. FL adds the restricted role , the -successors that are in . Then holds, because the -successor in must also be in . A part-by-part test at line L9 sees that the role is not among the roles of the left side and says no. The correct answer needs reasoning by cases, and subsumption in FL is coNP-hard (Brachman and Levesque 1984).
- Qualified existentials with value restrictions. In a language with both and , the concept is subsumed by . A comparison that matches only with misses this. The value restrictions must first be pushed into each existential of the normal form.
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)
structural_subsumption.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/structural-subsumption/. The authors are listed in prov/DQ8M2F.jsonl.
"""Structural subsumption for FL-: bring both concepts to a normal form, then compare the parts.
FL- has concept names, top, conjunction, value restriction (all r.C) and unqualified existential
restriction (some r.top). Concepts are the tuples of dl.py. The normal form of a concept is a tree:
each node holds a set of concept names, a set of roles r with some r.top, and at most one child for
each role r, which holds the merged fillers of all value restrictions on r. Children whose subtree
is empty are removed, because all r.top is equivalent to top.
"""
from typing import Optional
from dl import TOP, Concept, Interpretation
class NotFLMinus(ValueError):
"""Raised for a concept that is not in FL-."""
class Normal:
"""A node of the normal form tree."""
__slots__ = ("names", "roles", "child")
def __init__(self) -> None:
self.names: set[str] = set() # N: concept names that hold here
self.roles: set[str] = set() # E: roles r with some r.top here
self.child: dict[str, "Normal"] = {} # V: for role r, the merged value restriction on r
def is_empty(self) -> bool:
return not self.names and not self.roles and not self.child
def show(self) -> str:
parts = sorted(self.names) + ["∃" + r for r in sorted(self.roles)]
parts += ["∀" + r + "." + self.child[r].show() for r in sorted(self.child)]
if not parts:
return "⊤"
return parts[0] if len(parts) == 1 else "(" + " ⊓ ".join(parts) + ")"
def is_fl_minus(c: Concept) -> bool:
op = c[0]
if op in ("top", "atom"):
return True
if op == "and":
return is_fl_minus(c[1]) and is_fl_minus(c[2])
if op == "some":
return c[2] == TOP
if op == "all":
return is_fl_minus(c[2])
return False
def _insert(x: Normal, c: Concept) -> None:
op = c[0]
if op == "atom":
x.names.add(c[1]) # @line L5
elif op == "some":
x.roles.add(c[1]) # @line L6
elif op == "and":
_insert(x, c[1]) # @line L7
_insert(x, c[2])
elif op == "all":
if c[1] not in x.child: # @line L8
x.child[c[1]] = Normal()
_insert(x.child[c[1]], c[2])
def _prune(x: Normal) -> None:
for r in list(x.child):
_prune(x.child[r])
if x.child[r].is_empty():
del x.child[r]
def normalize(c: Concept) -> Normal:
"""The normal form of an FL- concept."""
if not is_fl_minus(c):
raise NotFLMinus(repr(c))
root = Normal() # @line L1
_insert(root, c) # @line L2
_prune(root) # @line L3
return root # @line L4
def subsumes_normal(c: Normal, d: Normal) -> bool:
"""SUBSUMES(c, d): True when the concept with normal form c is subsumed by the one with normal form d."""
if not d.names <= c.names or not d.roles <= c.roles: # @line L9
return False
for r, dr in d.child.items(): # @line L10
if r not in c.child or not subsumes_normal(c.child[r], dr): # @line L11
return False
return True # @line L12
def subsumes(c: Concept, d: Concept) -> bool:
"""True when c is subsumed by d (every model puts c inside d). Both must be FL- concepts."""
return subsumes_normal(normalize(c), normalize(d))
class _Builder:
def __init__(self) -> None:
self.n = 0
self.conc: dict[str, set] = {}
self.roles: dict[str, set] = {}
def new(self, x: Normal) -> int:
e = self.n
self.n += 1
for a in x.names:
self.conc.setdefault(a, set()).add(e)
return e
def edge(self, r: str, u: int, v: int) -> None:
self.roles.setdefault(r, set()).add((u, v))
def tree(self, x: Normal) -> int:
"""An element in the concept of x: one successor for each role of x.roles."""
e = self.new(x)
for r in sorted(x.roles):
self.edge(r, e, self.tree(x.child.get(r, Normal())))
return e
def counter(self, c: Normal, d: Normal) -> int:
"""An element in the concept of c but not in the concept of d. Needs: c is not subsumed by d."""
if not d.names <= c.names or not d.roles <= c.roles:
return self.tree(c)
r = next(r for r in sorted(d.child) if not subsumes_normal(c.child.get(r, Normal()), d.child[r]))
e = self.new(c)
for s in sorted(c.roles):
if s != r:
self.edge(s, e, self.tree(c.child.get(s, Normal())))
# The one r-successor is in the concept of c.child[r] but not in the one of d.child[r].
self.edge(r, e, self.counter(c.child.get(r, Normal()), d.child[r]))
return e
def counter_model(c: Concept, d: Concept) -> Optional[Interpretation]:
"""None when c is subsumed by d. Otherwise a finite tree model where element 0 is in c and not in d."""
nc, nd = normalize(c), normalize(d)
if subsumes_normal(nc, nd):
return None
b = _Builder()
b.counter(nc, nd)
return Interpretation(list(range(b.n)), b.conc, b.roles)
test_structural_subsumption.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/structural-subsumption/. The authors are listed in prov/DQ8M2F.jsonl.
"""Tests of structural subsumption for FL- against the semantics.
1. Brute force: with one role, when c is not subsumed by d there is a counter-model that is a path
with at most (larger role depth + 1) elements (proofs/correctness.md, size of the counter-model).
So for one role and role depth at most k, a search over every interpretation with at most k + 1
elements decides subsumption. The tests use k = 1 (all 32 normal forms over two names) and
k = 2 (random concepts).
2. The ALC tableau of alc_reference.py on c and not d, for random FL- concepts with two roles.
3. Every counter-model that the algorithm returns is checked by evaluation.
4. The example where a role restriction breaks the method.
"""
import random
from itertools import product
import alc_reference
import dl
from dl import TOP, atom, conj, disj, exists, forall, neg
from structural_subsumption import NotFLMinus, counter_model, is_fl_minus, normalize, subsumes
A, B = atom("A"), atom("B")
def some(r: str) -> tuple:
return exists(r, TOP)
def rand_fl(rng: random.Random, depth: int, names=("A", "B"), roles=("r",)) -> tuple:
if depth == 0 or rng.random() < 0.3:
return TOP if rng.random() < 0.1 else atom(rng.choice(names))
op = rng.choice(["and", "and", "some", "all", "all"])
if op == "and":
return conj(rand_fl(rng, depth, names, roles), rand_fl(rng, depth - 1, names, roles))
if op == "some":
return some(rng.choice(roles))
return forall(rng.choice(roles), rand_fl(rng, depth - 1, names, roles))
def check_counter(c: tuple, d: tuple) -> None:
i = counter_model(c, d)
if subsumes(c, d):
assert i is None
else:
assert i is not None
assert 0 in dl.evaluate(c, i) and 0 not in dl.evaluate(d, i)
def test_page_example() -> None:
c = conj(A, some("r"), forall("r", A), forall("r", conj(B, forall("s", A))))
d = conj(some("r"), forall("r", conj(A, B)), forall("r", forall("s", TOP)))
assert normalize(c).show() == "(A ⊓ ∃r ⊓ ∀r.(A ⊓ B ⊓ ∀s.A))"
assert normalize(d).show() == "(∃r ⊓ ∀r.(A ⊓ B))"
assert subsumes(c, d)
d2 = forall("r", forall("s", B))
assert not subsumes(c, d2)
i = counter_model(c, d2)
assert len(i.domain) == 3
assert 0 in dl.evaluate(c, i) and 0 not in dl.evaluate(d2, i)
def test_value_restriction_on_top_is_dropped() -> None:
# Without line L3, the right side keeps an empty child for r and the answer is wrong.
assert subsumes(A, forall("r", TOP))
assert subsumes(TOP, conj(forall("r", forall("s", TOP)), TOP))
assert normalize(forall("r", conj(TOP, forall("s", TOP)))).is_empty()
def test_value_restrictions_are_merged() -> None:
# Without the merge of line L8, all r.(A and B) is not found below all r.A and all r.B.
c = conj(forall("r", A), forall("r", B))
assert subsumes(c, forall("r", conj(A, B)))
assert subsumes(forall("r", conj(A, B)), c)
def test_rejects_other_constructors() -> None:
for c in (neg(A), disj(A, B), exists("r", A), dl.BOTTOM):
assert not is_fl_minus(c)
try:
normalize(c)
except NotFLMinus:
pass
else:
raise AssertionError("expected NotFLMinus")
def _small_extensions(concepts: list, cn: list, rn: list, max_size: int) -> list:
"""For each concept, the list of its extensions in every interpretation with at most max_size elements."""
exts: list[list] = [[] for _ in concepts]
for i in dl.interpretations(cn, rn, max_size):
for k, c in enumerate(concepts):
exts[k].append(dl.evaluate(c, i))
return exts
def _brute_subsumes(ec: list, ed: list) -> bool:
return all(x <= y for x, y in zip(ec, ed))
def all_depth1_concepts() -> list:
out = []
subsets = [(), ("A",), ("B",), ("A", "B")]
for top_names, e, filler in product(subsets, (False, True), subsets):
parts = [atom(a) for a in top_names]
if e:
parts.append(some("r"))
if filler:
parts.append(forall("r", conj(*[atom(a) for a in filler])))
out.append(conj(*parts))
return out
def test_all_depth1_pairs_against_brute_force() -> None:
cs = all_depth1_concepts()
assert len(cs) == 32
exts = _small_extensions(cs, ["A", "B"], ["r"], 2)
agree = holds = 0
for x, c in enumerate(cs):
for y, d in enumerate(cs):
want = _brute_subsumes(exts[x], exts[y])
assert subsumes(c, d) == want, (dl.show(c), dl.show(d))
agree += 1
holds += want
check_counter(c, d)
assert agree == 1024
assert 0 < holds < 1024
def test_random_depth2_against_brute_force() -> None:
rng = random.Random(7)
cs = []
while len(cs) < 24:
c = rand_fl(rng, 2, names=("A",), roles=("r",))
if dl.role_depth(c) <= 2:
cs.append(c)
exts = _small_extensions(cs, ["A"], ["r"], 3)
holds = 0
for x, c in enumerate(cs):
for y, d in enumerate(cs):
want = _brute_subsumes(exts[x], exts[y])
assert subsumes(c, d) == want, (dl.show(c), dl.show(d))
holds += want
assert 0 < holds < len(cs) ** 2
def test_random_against_alc_tableau() -> None:
rng = random.Random(11)
yes = no = 0
for _ in range(300):
c = rand_fl(rng, 3, roles=("r", "s"))
d = rand_fl(rng, 3, roles=("r", "s"))
if rng.random() < 0.5:
c = conj(c, d, rand_fl(rng, 2, roles=("r", "s"))) # make "yes" answers common
got = subsumes(c, d)
assert got == alc_reference.subsumes(c, d), (dl.show(c), dl.show(d))
check_counter(c, d)
yes += got
no += not got
assert yes > 50 and no > 50
def test_role_restriction_breaks_it() -> None:
# FL adds the restricted role (r : C), the r-successors that are in C.
# C = some (r : A) and all (r : A).B, D = some (r : B). In ALC: some r.A and all r.(not A or B), some r.B.
c_alc = conj(exists("r", A), forall("r", disj(neg(A), B)))
d_alc = exists("r", B)
assert alc_reference.subsumes(c_alc, d_alc)
exts = _small_extensions([c_alc, d_alc], ["A", "B"], ["r"], 2)
assert _brute_subsumes(exts[0], exts[1])
# Comparing part by part treats (r : A) and (r : B) as two unrelated roles and says no.
c_naive = conj(some("r:A"), forall("r:A", B))
d_naive = some("r:B")
assert not subsumes(c_naive, d_naive)
History
Brachman and Levesque (1984) studied the language FL-, a part of the KL-ONE family, and gave a polynomial algorithm for its subsumption problem. In the same paper they showed that adding role restrictions makes the problem coNP-hard, and Levesque and Brachman (1987) put this into a general trade-off between expressive power and tractability. Nebel (1990) showed that TBoxes add their own source of hardness. Systems of the late 1980s and early 1990s, such as CLASSIC, used normalize and compare methods. For CLASSIC, Borgida and Patel-Schneider (1994) proved the method complete with respect to a semantics they defined for the language. Later systems for expressive logics moved to tableau algorithms, which handle disjunction and negation.
References
- Ronald J. Brachman and Hector J. Levesque, The tractability of subsumption in frame-based description languages, Proceedings of the 4th National Conference on Artificial Intelligence (AAAI-84), AAAI Press, 1984, pages 34 to 37 (FL- with a polynomial subsumption test, and the coNP-hardness of FL)
- Hector J. Levesque and Ronald J. Brachman, Expressiveness and tractability in knowledge representation and reasoning, Computational Intelligence 3, 1987, pages 78 to 93 (the trade-off between expressive power and tractable reasoning, general locator)
- 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 (structural subsumption algorithms, general locator)
- Alexander Borgida and Peter F. Patel-Schneider, A semantics and complete algorithm for subsumption in the CLASSIC description logic, Journal of Artificial Intelligence Research 1, 1994, pages 277 to 308 (normalization and structural comparison for the CLASSIC language)
- Bernhard Nebel, Terminological reasoning is inherently intractable, Artificial Intelligence 43(2), 1990, subsumption with respect to acyclic TBoxes is coNP-hard already for very small languages (general locator)
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 DQ8M2F Edit this page History Report an error Markdown