Algorithm Search⌘K

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.

Time
O(n log n) worstO(n) expected
Space
O(n) extra
Where
n = the total size of the two concepts
Properties
builds counter modeldeterministicexactrecursive
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 CC and DD of FL-, and there is no TBox. FL- concepts are built from concept names AA, the top concept ⊤\top, conjunction C⊓DC \sqcap D, value restriction ∀r.C\forall r.C and unqualified existential restriction ∃r.⊤\exists r.\top, written ∃r\exists r. The question is concept subsumption: does CI⊆DIC^I \subseteq D^I hold in every interpretation I=(ΔI,⋅I)I = (\Delta^I, \cdot^I)? We write C⊑DC \sqsubseteq D.

FL- has no ⊥\bot 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 ∃r\exists r, and the same method works for it.

The algorithm

The normal form of a concept is a tree. Each node xx has a set NxN_x of concept names, a set ExE_x of roles with ∃r\exists r, and at most one child Vx(r)V_x(r) for each role rr, which collects the fillers of all value restrictions on rr at that place. The equivalences ∀r.(C⊓D)≡∀r.C⊓∀r.D\forall r.(C \sqcap D) \equiv \forall r.C \sqcap \forall r.D and ∀r.⊤≡⊤\forall r.\top \equiv \top justify the merge and the removal of empty children.

  1. NORMALIZE(C)
  2. 1root ← a new node with N = ∅, E = ∅ and no children
  3. 2INSERT(root, C)
  4. 3remove every child V_x(r) whose subtree has no names and no roles ▷ ∀r.⊤ is ⊤
  5. 4return root
  6. INSERT(x, C)
  7. 5if C is a concept name A then add A to N_x
  8. 6if C is ∃r then add r to E_x
  9. 7if C is C1 ⊓ C2 then INSERT(x, C1); INSERT(x, C2)
  10. 8if C is ∀r.C1 then if V_x(r) is undefined, set V_x(r) ← a new empty node; INSERT(V_x(r), C1)
  11. ▷ C = ⊤ adds nothing
  12. SUBSUMES(c, d) ▷ c, d: normal forms of C and D; true iff C ⊑ D
  13. 9if N_d ⊄ N_c or E_d ⊄ E_c then return false
  14. 10for each role r with V_d(r) defined do
  15. 11if V_c(r) is undefined or SUBSUMES(V_c(r), V_d(r)) is false then return false
  16. 12return true

INSERT walks the concept once. Line L8 sends every value restriction on rr at the same place to the same child, so ∀r.A⊓∀r.B\forall r.A \sqcap \forall r.B and ∀r.(A⊓B)\forall r.(A \sqcap B) get the same tree. Line L3 runs bottom up, so a chain such as ∀r.∀s.⊤\forall r.\forall s.\top disappears completely.

SUBSUMES then reads the conjuncts of DD off its tree. A name or an ∃r\exists r of DD must be a conjunct of CC at the same place (line L9). A value restriction ∀r.D′\forall r.D' of DD needs a value restriction ∀r.C′\forall r.C' of CC with C′⊑D′C' \sqsubseteq D' (line L11). If CC has no value restriction on rr, then CC says nothing about its rr-successors, and since Vd(r)V_d(r) 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 CC with one rr-successor for each r∈Ecr \in E_c. At the node where line L9 fails, the missing name or the missing successor already makes the element fail DD. Where line L11 fails for rr, give the element one rr-successor that is, recursively, in C′C' but not in D′D'.

Example

Take C=A⊓∃r⊓∀r.A⊓∀r.(B⊓∀s.A)C = A \sqcap \exists r \sqcap \forall r.A \sqcap \forall r.(B \sqcap \forall s.A) and D=∃r⊓∀r.(A⊓B)⊓∀r.∀s.⊤D = \exists r \sqcap \forall r.(A \sqcap B) \sqcap \forall r.\forall s.\top.

step line state
1 L5 to L8 root of CC: N={A}N = \{A\}, E={r}E = \{r\}; child for rr: N={A,B}N = \{A, B\}; its child for ss: N={A}N = \{A\}
2 L5 to L8 root of DD: N=∅N = \emptyset, E={r}E = \{r\}; child for rr: N={A,B}N = \{A, B\}; its child for ss is empty
3 L3 the empty child for ss in DD is removed
4 L9 root: ∅⊆{A}\emptyset \subseteq \{A\} and {r}⊆{r}\{r\} \subseteq \{r\}, pass
5 L11 role rr: compare the two children
6 L9 {A,B}⊆{A,B}\{A, B\} \subseteq \{A, B\} and ∅⊆∅\emptyset \subseteq \emptyset, pass; DD has no child here
7 L12 return true, so C⊑DC \sqsubseteq D

The normal forms print as A⊓∃r⊓∀r.(A⊓B⊓∀s.A)A \sqcap \exists r \sqcap \forall r.(A \sqcap B \sqcap \forall s.A) and ∃r⊓∀r.(A⊓B)\exists r \sqcap \forall r.(A \sqcap B).

Now take D′=∀r.∀s.BD' = \forall r.\forall s.B. Its tree has a child for rr with a child for ss that holds {B}\{B\}. At that depth line L9 finds {B}⊈{A}\{B\} \not\subseteq \{A\} and returns false. The counter-model has 3 elements: element 0 in AA, an rr-edge to element 1 in AA and BB, and an ss-edge from 1 to element 2 in AA only. Element 0 is in CC, and it is not in D′D' because element 2 is not in BB.

Correctness

The invariant of NORMALIZE is that after each call INSERT(x,C′)(x, C') the concept read off the tree at xx is equivalent to the old one conjoined with C′C'. Line L3 keeps the equivalence because ∀r.⊤≡⊤\forall r.\top \equiv \top. Soundness of SUBSUMES is an induction on the depth of dd: each conjunct of DD is a conjunct of CC, or follows from a value restriction of CC 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 CC and DD. 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, ⊤\top, C⊓DC \sqcap D, ∀r.C\forall r.C and ∃r.⊤\exists r.\top (written ∃r\exists r). There is no TBox. A normal form node xx has a set NxN_x of concept names, a set ExE_x of roles and a partial map VxV_x from roles to nodes. The concept of a node is

con(x)=⊓A∈NxA  ⊓  ⊓r∈Ex∃r  ⊓  ⊓r∈dom(Vx)∀r.con(Vx(r)),\mathrm{con}(x) = \mathop{\large\sqcap}_{A \in N_x} A \;\sqcap\; \mathop{\large\sqcap}_{r \in E_x} \exists r \;\sqcap\; \mathop{\large\sqcap}_{r \in \mathrm{dom}(V_x)} \forall r.\mathrm{con}(V_x(r)),

with the empty conjunction equal to ⊤\top. A node is empty when NxN_x, ExE_x and VxV_x are all empty; then con(x)=⊤\mathrm{con}(x) = \top.

Termination

INSERT (lines L5 to L8) calls itself only on direct subconcepts, so it makes one call for each occurrence of a subconcept of CC. PRUNE visits each node once. SUBSUMES (lines L9 to L12) calls itself only on (Vc(r),Vd(r))(V_c(r), V_d(r)), one level deeper in both trees, so it stops after at most rd(D)+1\mathrm{rd}(D) + 1 levels, where rd\mathrm{rd} is the role depth. All three procedures stop.

Lemma 1 (the normal form is equivalent)

For every FL- concept CC, con(NORMALIZE(C))≡C\mathrm{con}(\mathrm{NORMALIZE}(C)) \equiv C.

Proof. Before PRUNE, we show by induction on the INSERT calls that after INSERT(x,C′)(x, C') the concept con(x)\mathrm{con}(x) is equivalent to the old con(x)⊓C′\mathrm{con}(x) \sqcap C'. For a name (L5) and for ∃r\exists r (L6) this is the definition of con. For C1⊓C2C_1 \sqcap C_2 (L7) it follows from two applications of the induction hypothesis. For ∀r.D\forall r.D (L8), the call changes only the child y=Vx(r)y = V_x(r), and by induction con(y)\mathrm{con}(y) becomes con(y)⊓D\mathrm{con}(y) \sqcap D (a new child starts empty, with concept ⊤\top). The equivalence ∀r.(Y⊓D)≡∀r.Y⊓∀r.D\forall r.(Y \sqcap D) \equiv \forall r.Y \sqcap \forall r.D holds in every interpretation: an element has all its rr-successors in Y∩DY \cap D exactly when it has them all in YY and all in DD. For ⊤\top nothing changes and X⊓⊤≡XX \sqcap \top \equiv X. The root starts empty (L1), so after L2 the root has concept equivalent to CC.

PRUNE removes a child Vx(r)V_x(r) only when its subtree is empty, so its concept is ⊤\top. Since ∀r.⊤≡⊤\forall r.\top \equiv \top (every successor is in the domain), the removal does not change the concept of xx up to equivalence. □\square

From now on cc and dd are the pruned normal forms of CC and DD. After PRUNE, every child is nonempty.

Lemma 2 (soundness)

If SUBSUMES(c,d)(c, d) returns true, then con(c)⊑con(d)\mathrm{con}(c) \sqsubseteq \mathrm{con}(d).

Proof. By induction on the depth of dd. Take an interpretation II and e∈con(c)Ie \in \mathrm{con}(c)^I. Line L9 passed, so Nd⊆NcN_d \subseteq N_c and Ed⊆EcE_d \subseteq E_c; each name of NdN_d and each ∃r\exists r with r∈Edr \in E_d is a conjunct of con(c)\mathrm{con}(c), so ee is in it. For each r∈dom(Vd)r \in \mathrm{dom}(V_d), line L11 passed, so Vc(r)V_c(r) exists and SUBSUMES(Vc(r),Vd(r))(V_c(r), V_d(r)) is true. Each rr-successor ff of ee is in con(Vc(r))I\mathrm{con}(V_c(r))^I, because ∀r.con(Vc(r))\forall r.\mathrm{con}(V_c(r)) is a conjunct of con(c)\mathrm{con}(c). By induction f∈con(Vd(r))If \in \mathrm{con}(V_d(r))^I. So e∈(∀r.con(Vd(r)))Ie \in (\forall r.\mathrm{con}(V_d(r)))^I. All conjuncts of con(d)\mathrm{con}(d) hold at ee. □\square

Lemma 3 (completeness, with a counter-model)

Let TREE(x)(x) make an element ee with the names NxN_x and, for each r∈Exr \in E_x, one rr-successor TREE(Vx(r))(V_x(r)), or TREE of an empty node when Vx(r)V_x(r) is undefined. Then e∈con(x)e \in \mathrm{con}(x) in the interpretation that is built.

If SUBSUMES(c,d)(c, d) returns false, then COUNTER(c,d)(c, d) of the implementation builds a finite tree interpretation with an element ee in con(c)\mathrm{con}(c) and not in con(d)\mathrm{con}(d). So C⋢DC \not\sqsubseteq D.

Proof. For TREE, by induction on the depth of xx: ee has the names of NxN_x; it has an rr-successor for each r∈Exr \in E_x; and for each r∈dom(Vx)r \in \mathrm{dom}(V_x), every rr-successor of ee is TREE(Vx(r))(V_x(r)) (when r∈Exr \in E_x) or there is none (when r∉Exr \notin E_x), and in both cases every rr-successor is in con(Vx(r))\mathrm{con}(V_x(r)). 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 dd. Case 1: line L9 fails. COUNTER returns TREE(c)(c), which is in con(c)\mathrm{con}(c). Either a name A∈Nd∖NcA \in N_d \setminus N_c, and ee is not in AA, or a role r∈Ed∖Ecr \in E_d \setminus E_c, and ee has no rr-successor, so e∉∃re \notin \exists r. Case 2: line L11 fails for a role rr. Let c′=Vc(r)c' = V_c(r), or an empty node if it is undefined, and d′=Vd(r)d' = V_d(r), which is nonempty after PRUNE. SUBSUMES(c′,d′)(c', d') is false. When Vc(r)V_c(r) is defined, this is what L11 found. When it is undefined, c′c' is empty and d′d' is not: if d′d' has a name or a role, L9 fails; otherwise d′d' has a child, and L11 fails because c′c' has none. COUNTER makes ee with the names NcN_c, one ss-successor TREE(Vc(s))(V_c(s)) for each s∈Ecs \in E_c with s≠rs \neq r, and exactly one rr-successor $f = $ COUNTER(c′,d′)(c', d'). By induction f∈con(c′)f \in \mathrm{con}(c') and f∉con(d′)f \notin \mathrm{con}(d'). So e∈con(c)e \in \mathrm{con}(c): the names hold, each ∃s\exists s holds (for s=rs = r the successor is ff), and every successor satisfies the matching value restriction. And e∉∀r.con(d′)e \notin \forall r.\mathrm{con}(d'), so e∉con(d)e \notin \mathrm{con}(d). □\square

Theorem

SUBSUMES(NORMALIZE(C)(C), NORMALIZE(D)(D)) returns true if and only if C⊑DC \sqsubseteq D.

Proof. By Lemma 1, C≡con(c)C \equiv \mathrm{con}(c) and D≡con(d)D \equiv \mathrm{con}(d). If the answer is true, Lemma 2 gives C⊑DC \sqsubseteq D. If it is false, Lemma 3 gives an interpretation with an element in CC and not in DD. ■\blacksquare

Size of the counter-model

With one role name, the element of TREE(x)(x) has at most one successor, so TREE builds a path with at most rd(con(x))+1\mathrm{rd}(\mathrm{con}(x)) + 1 elements. COUNTER also gives each element at most one successor, and each step goes one level deeper in cc or in dd. So a counter-model exists with at most max⁡(rd(C),rd(D))+1\max(\mathrm{rd}(C), \mathrm{rd}(D)) + 1 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 CC, so NORMALIZE takes O(∣C∣)O(|C|) operations and makes at most ∣C∣|C| nodes. SUBSUMES visits each node of dd at most once and pairs it with one node of cc; the inclusion tests of L9 cost O(∣Nd∣+∣Ed∣)O(|N_d| + |E_d|) lookups for that node. The total is O(∣C∣+∣D∣)O(|C| + |D|) hash set operations, so O(∣C∣+∣D∣)O(|C| + |D|) expected time, and O(∣C∣+∣D∣)O(|C| + |D|) 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 DD once and pairs it with one node of the tree of CC. With hash sets the expected time is O(n)O(n), where n=∣C∣+∣D∣n = |C| + |D|. With sorted sets the time is O(nlog⁡n)O(n \log n) in the worst case. The space is O(n)O(n). 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 DD is missing in CC.
  • 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 ⊥\bot, atomic negation or number restrictions, the normal form must first find the parts that are unsatisfiable, such as A⊓¬AA \sqcap \neg A or (≥2 r)⊓(≤1 r)(\geq 2\, r) \sqcap (\leq 1\, r), and replace them by ⊥\bot. 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, D=∀r.⊤D = \forall r.\top keeps an empty child for rr, and line L11 returns false for C=AC = A, although A⊑∀r.⊤A \sqsubseteq \forall r.\top holds. Remove empty children at line L3 before any comparison.
  • Not merging value restrictions. If line L8 makes a new child for each ∀r.C1\forall r.C_1 instead of reusing Vx(r)V_x(r), then C=∀r.A⊓∀r.BC = \forall r.A \sqcap \forall r.B has two children for rr, and no one of them is below A⊓BA \sqcap B. The test then says no to C⊑∀r.(A⊓B)C \sqsubseteq \forall r.(A \sqcap B), which holds. Line L8 must reuse the child.
  • Adding role restrictions. FL adds the restricted role (r:C)(r : C), the rr-successors that are in CC. Then ∃(r:A)⊓∀(r:A).B⊑∃(r:B)\exists (r : A) \sqcap \forall (r : A).B \sqsubseteq \exists (r : B) holds, because the rr-successor in AA must also be in BB. A part-by-part test at line L9 sees that the role (r:B)(r : B) 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 ∃r.C\exists r.C and ∀r.C\forall r.C, the concept ∃r.A⊓∀r.B\exists r.A \sqcap \forall r.B is subsumed by ∃r.(A⊓B)\exists r.(A \sqcap B). A comparison that matches ∃r.(A⊓B)\exists r.(A \sqcap B) only with ∃r.A\exists r.A 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.

alc_reference.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Test helper of the description logic pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A small reference decision procedure for ALC concept satisfiability with a general TBox.

The tests use it as an independent oracle. It is the plain tableau: depth first, a label is a set
of concepts in negation normal form, every node gets the concept nnf(not C or D) of each inclusion
C subsumed by D, and a new node is not made when its label is a subset of the label of an ancestor
(subset blocking, which is sound for ALC). Disjunctions are split in a fixed order with no
heuristics, so the node count shows how much search the plain method does.
"""

from typing import Iterator, Sequence

from dl import BOTTOM, GCI, Concept, conj, disj, neg, nnf


class Counter:
    def __init__(self) -> None:
        self.nodes = 0  # labels that were completed and expanded
        self.branches = 0  # completions tried, clash-free or not


def _completions(s: frozenset, cnt: Counter) -> Iterator[frozenset]:
    lab: set = set()
    stack = list(s)
    while stack:
        c = stack.pop()
        if c in lab:
            continue
        lab.add(c)
        if c[0] == "and":
            stack.append(c[1])
            stack.append(c[2])
    cnt.branches += 1
    if BOTTOM in lab or any(c[0] == "not" and c[1] in lab for c in lab):
        return
    pending = sorted(repr(c) for c in lab if c[0] == "or" and c[1] not in lab and c[2] not in lab)
    if not pending:
        yield frozenset(lab)
        return
    c = next(c for c in lab if repr(c) == pending[0])
    yield from _completions(frozenset(lab | {c[1]}), cnt)
    yield from _completions(frozenset(lab | {c[2]}), cnt)


def _sat(label: frozenset, ancestors: tuple, tc: frozenset, cnt: Counter) -> bool:
    cnt.nodes += 1
    for lab in _completions(label, cnt):
        path = ancestors + (lab,)
        ok = True
        for c in sorted((c for c in lab if c[0] == "some"), key=repr):
            child = frozenset({c[2]} | {d[2] for d in lab if d[0] == "all" and d[1] == c[1]}) | tc
            if tc and any(child <= a for a in path):
                continue  # blocked: the ancestor's label serves as the successor
            if not _sat(child, path, tc, cnt):
                ok = False
                break
        if ok:
            return True
    return False


def satisfiable_count(c: Concept, tbox: Sequence[GCI] = ()) -> tuple[bool, Counter]:
    """Decide whether c is satisfiable with respect to the TBox; also return the work counter."""
    tc = frozenset(nnf(disj(neg(x), y)) for x, y in tbox)
    cnt = Counter()
    return _sat(frozenset({nnf(c)}) | tc, (), tc, cnt), cnt


def satisfiable(c: Concept, tbox: Sequence[GCI] = ()) -> bool:
    return satisfiable_count(c, tbox)[0]


def subsumes(c: Concept, d: Concept, tbox: Sequence[GCI] = ()) -> bool:
    """True when c is subsumed by d with respect to the TBox."""
    return not satisfiable(conj(c, neg(d)), tbox)
dl.py 232 lines
# SPDX-License-Identifier: MIT
# Shared helper of the description logic pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""ALC concepts as syntax trees, negation normal form, and evaluation in a finite interpretation.

A concept is a tuple:
    TOP = ("top",)            BOTTOM = ("bottom",)
    ("atom", "A")             ("not", C)
    ("and", C, D)             ("or", C, D)
    ("some", "r", C)          ("all", "r", C)
A TBox is a sequence of general concept inclusions (C, D), read C is subsumed by D.
An interpretation has a nonempty finite domain, a set for each concept name and a set of pairs
for each role name. Names that an interpretation does not list are empty.
This file holds only the syntax and the semantics. No reasoning algorithm goes here.
"""

from itertools import product
from typing import Iterable, Iterator, Sequence

Concept = tuple
GCI = tuple[Concept, Concept]

TOP: Concept = ("top",)
BOTTOM: Concept = ("bottom",)


def atom(name: str) -> Concept:
    return ("atom", name)


def neg(c: Concept) -> Concept:
    return ("not", c)


def conj(*cs: Concept) -> Concept:
    """The conjunction of the arguments, nested to the right. conj() is TOP."""
    if not cs:
        return TOP
    out = cs[-1]
    for c in reversed(cs[:-1]):
        out = ("and", c, out)
    return out


def disj(*cs: Concept) -> Concept:
    """The disjunction of the arguments, nested to the right. disj() is BOTTOM."""
    if not cs:
        return BOTTOM
    out = cs[-1]
    for c in reversed(cs[:-1]):
        out = ("or", c, out)
    return out


def exists(r: str, c: Concept) -> Concept:
    return ("some", r, c)


def forall(r: str, c: Concept) -> Concept:
    return ("all", r, c)


def nnf(c: Concept) -> Concept:
    """Negation normal form: an equivalent concept with negation only in front of concept names."""
    op = c[0]
    if op in ("top", "bottom", "atom"):
        return c
    if op in ("and", "or"):
        return (op, nnf(c[1]), nnf(c[2]))
    if op in ("some", "all"):
        return (op, c[1], nnf(c[2]))
    d = c[1]  # op == "not"
    dop = d[0]
    if dop == "top":
        return BOTTOM
    if dop == "bottom":
        return TOP
    if dop == "atom":
        return c
    if dop == "not":
        return nnf(d[1])
    if dop == "and":
        return ("or", nnf(neg(d[1])), nnf(neg(d[2])))
    if dop == "or":
        return ("and", nnf(neg(d[1])), nnf(neg(d[2])))
    if dop == "some":
        return ("all", d[1], nnf(neg(d[2])))
    return ("some", d[1], nnf(neg(d[2])))  # dop == "all"


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


def subconcepts(c: Concept) -> set[Concept]:
    """All subconcepts of c, c included."""
    out = {c}
    op = c[0]
    if op == "not":
        out |= subconcepts(c[1])
    elif op in ("and", "or"):
        out |= subconcepts(c[1]) | subconcepts(c[2])
    elif op in ("some", "all"):
        out |= subconcepts(c[2])
    return out


def size(c: Concept) -> int:
    """The number of constructors and names in c."""
    op = c[0]
    if op in ("top", "bottom", "atom"):
        return 1
    if op == "not":
        return 1 + size(c[1])
    if op in ("and", "or"):
        return 1 + size(c[1]) + size(c[2])
    return 2 + size(c[2])


def role_depth(c: Concept) -> int:
    """The largest number of nested role restrictions in c."""
    op = c[0]
    if op in ("top", "bottom", "atom"):
        return 0
    if op == "not":
        return role_depth(c[1])
    if op in ("and", "or"):
        return max(role_depth(c[1]), role_depth(c[2]))
    return 1 + role_depth(c[2])


def names(cs: Iterable[Concept]) -> tuple[list[str], list[str]]:
    """The sorted concept names and role names that occur in the given concepts."""
    cn: set[str] = set()
    rn: set[str] = set()
    for c in cs:
        for s in subconcepts(c):
            if s[0] == "atom":
                cn.add(s[1])
            elif s[0] in ("some", "all"):
                rn.add(s[1])
    return sorted(cn), sorted(rn)


def show(c: Concept) -> str:
    """The concept in the usual notation, with full parentheses."""
    op = c[0]
    if op == "top":
        return "⊤"
    if op == "bottom":
        return "⊥"
    if op == "atom":
        return c[1]
    if op == "not":
        return "¬" + show(c[1])
    if op == "and":
        return "(" + show(c[1]) + " ⊓ " + show(c[2]) + ")"
    if op == "or":
        return "(" + show(c[1]) + " ⊔ " + show(c[2]) + ")"
    q = "∃" if op == "some" else "∀"
    return q + c[1] + "." + show(c[2])


class Interpretation:
    """A finite interpretation. domain is a nonempty list; concepts maps a name to a set of elements;
    roles maps a name to a set of pairs of elements."""

    def __init__(self, domain: Sequence, concepts: dict, roles: dict) -> None:
        if not domain:
            raise ValueError("the domain of an interpretation is not empty")
        self.domain = list(domain)
        self.concepts = {a: frozenset(s) for a, s in concepts.items()}
        self.roles = {r: frozenset(p) for r, p in roles.items()}
        self._succ: dict[str, dict] = {}

    def successors(self, r: str, x) -> list:
        if r not in self._succ:
            m: dict = {y: [] for y in self.domain}
            for (u, v) in self.roles.get(r, ()):
                m[u].append(v)
            self._succ[r] = m
        return self._succ[r][x]

    def __repr__(self) -> str:
        return f"Interpretation({self.domain!r}, {self.concepts!r}, {self.roles!r})"


def evaluate(c: Concept, i: Interpretation) -> frozenset:
    """The extension of c in the interpretation i, by the semantics of ALC."""
    op = c[0]
    if op == "top":
        return frozenset(i.domain)
    if op == "bottom":
        return frozenset()
    if op == "atom":
        return i.concepts.get(c[1], frozenset())
    if op == "not":
        return frozenset(i.domain) - evaluate(c[1], i)
    if op == "and":
        return evaluate(c[1], i) & evaluate(c[2], i)
    if op == "or":
        return evaluate(c[1], i) | evaluate(c[2], i)
    ext = evaluate(c[2], i)
    if op == "some":
        return frozenset(x for x in i.domain if any(y in ext for y in i.successors(c[1], x)))
    return frozenset(x for x in i.domain if all(y in ext for y in i.successors(c[1], x)))


def is_model_of_tbox(i: Interpretation, tbox: Iterable[GCI]) -> bool:
    """True when i satisfies every inclusion C subsumed by D of the TBox."""
    return all(evaluate(c, i) <= evaluate(d, i) for c, d in tbox)


def interpretations(concept_names: Sequence[str], role_names: Sequence[str], max_size: int) -> Iterator[Interpretation]:
    """Every interpretation of the given names over the domains [0], [0, 1], ..., [0, ..., max_size - 1].
    There are sum over n of 2^(n * |concept_names| + n^2 * |role_names|) of them."""
    for n in range(1, max_size + 1):
        dom = list(range(n))
        pairs = [(x, y) for x in dom for y in dom]
        cbits = list(product((False, True), repeat=n * len(concept_names)))
        rbits = list(product((False, True), repeat=n * n * len(role_names)))
        for rb in rbits:
            roles = {r: {pairs[k] for k in range(n * n) if rb[j * n * n + k]} for j, r in enumerate(role_names)}
            for cb in cbits:
                conc = {a: {x for x in dom if cb[j * n + x]} for j, a in enumerate(concept_names)}
                yield Interpretation(dom, conc, roles)
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

  1. 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)
  2. 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)
  3. 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)
  4. 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)
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example