Module contents
Lesson 19 of 23Core 105 min

Knowledge representation: ontologies, description logics and nonmonotonic reasoning

Knowledge representation chooses what can be expressed and inferred efficiently. Survey semantic networks and frames, formalize them using description logics and their tableaux algorithm in OWL ontologies, study nonmonotonic reasoning for exceptions and defaults, and represent actions and the frame problem as a bridge to planning.

After this lesson you can

  • Analyze the expressivity–tractability tradeoff in representation languages.
  • Formalize knowledge in description logics and decide subsumption with tableaux.
  • Use OWL ontologies with reasoners and SPARQL queries, distinguishing open and closed worlds.
  • Model exceptions and defaults using nonmonotonic reasoning.
  • Formalize actions in situation calculus and solve the frame problem with successor-state axioms.

Before you start

Motivation: what can be said and inferred

Imagine a company’s security inventory: servers, databases, services each runs, known vulnerabilities and protective controls. The important question is rarely written in a table: “which assets are internet-exposed and have a critical vulnerability?” Answering requires inference: a web server runs a web service, a web service is public, an asset running something public is exposed, remote code execution is a critical vulnerability. A database returns only stored data; a language model answers fluently without guaranteeing its answer follows from anything. A knowledge representation system is a third route: a formal language for what you know and a reasoner obtaining what follows with guarantees.

This idea, seen in the knowledge-based agent, immediately faces a tradeoff. With full first-order logic you can say almost anything, but inference is undecidable and resolution may not terminate. With Datalog everything terminates in polynomial time, but you cannot say “every web server runs some web service” without naming it. Knowledge representation chooses what can be said knowing what can be inferred and at what cost. The tradeoff has major successes: clinical terminology SNOMED CT is written in a description logic designed to be tractable, and ELK classifies it entirely, about 300,000 classes, in seconds on a laptop (Kazakov, Krötzsch and Simančík, ELK 0.1.0 announcement, 2011). The Gene Ontology, with 38,560 terms in its March 2026 version according to release statistics, annotates over 1.7 million gene products from thousands of species in the same kind of language.

This lesson follows the historical and technical path: semantic networks and frames, which gave intuition but not semantics; description logics, which supplied it, with their tableau algorithm, implemented from scratch; OWL ontologies used in practice and their open-world versus closed-world distinction; nonmonotonic reasoning for exceptions and defaults classical logic cannot express; and representation of actions, where the famous frame problem connects to planning in subsequent lessons.

What knowledge representation means

Davis, Shrobe and Szolovits (1993) proposed a useful answer separating five simultaneous roles. A representation is a surrogate for the world inside a program, allowing reasoning without touching it. It is a set of ontological commitments, deciding what exists and can be named. It is a partial theory of reasoning, deciding which conclusions are legitimate. It is a medium for efficient computation, organizing information so those conclusions are affordable. It is a medium of human expression: someone must be able to write and read it.

Russell and Norvig formulate the two most important commitments as follows:

LanguageOntological commitment (what exists)Epistemological commitment (what the agent can believe)
Propositional logicfactstrue, false, unknown
First-order logicfacts, objects, relationstrue, false, unknown
Temporal logicfacts, objects, relations, timestrue, false, unknown
Probability theoryfactsdegree of belief in [0,1][0, 1]
Fuzzy logicfacts with degree of truth in [0,1][0, 1]known interval of values

This lesson’s description logics commit to objects, classes of objects (concepts) and binary relations (roles), and three-valued beliefs: something may be proved, refuted, or neither. That “neither” is the heart of open versus closed world.

Expressiveness versus tractability

The third role clashes with the fourth. Levesque and Brachman (1987) made it a thesis: the more expressive a language, the costlier inference, an unavoidable tradeoff. Their foundational example (Brachman and Levesque, 1984) is absurdly small. In description language FL−\mathcal{FL}^-, with conjunction, universal restriction ∀R.C\forall R.C and unqualified existential ∃R\exists R, deciding whether one concept subsumes another is polynomial. Add just one construction, role restriction R∣CR|_C (“RR successors that are CC”), and the problem becomes co-NP-hard. An innocent-looking construction turns a toy algorithm into an intractable problem.

The table places this topic’s languages on that scale. Complexity is each central problem’s worst case relative to full input size.

LanguageWhat it can sayProblemComplexity
Propositional Horn clausesrules without disjunctionsatisfiabilitylinear (Dowling and Gallier, 1984)
Propositional logicany formulasatisfiabilityNP-complete
Datalogrules with variables, no functionsentailmentP in data; EXPTIME-complete combined
EL\mathcal{EL} (OWL 2 EL profile)⊓\sqcap, ∃R.C\exists R.C, general TBoxsubsumptionP
ALC\mathcal{ALC}additionally ¬\neg, ⊔\sqcup, ∀R.C\forall R.Csatisfiability without / with TBoxPSPACE / EXPTIME-complete
SROIQ\mathcal{SROIQ} (OWL 2 DL)additionally inverse and transitive roles, cardinalities, nominalssatisfiabilityN2EXPTIME-complete (Kazakov, 2008)
First-order logicall the above and morevalidityundecidable (semidecidable)

Semantic networks and frames

The first structured representation was a graph. Quillian (1968) proposed modeling semantic memory as a network with concepts as nodes and relations as edges: “canary is-a bird”, “bird has wings”, “bird can fly”. Properties are stored at the most general node and inherited along is-a edges. Collins and Quillian (1969) measured that people took longer to verify “a canary has skin” (inherited from “animal”, two hops) than “a canary can sing” (its own node’s property), interpreting this as evidence that human memory works this way. For a program the advantage is economy: write a property once and it holds for the hierarchy.

Minsky (1974) went further with frames. A frame describes a situation or typical object with slots holding default values, restrictions on contents and procedures triggered when a slot is read or written. A “room” frame, for example, would have wall, door and ceiling slots with typical values; entering a particular room, the system assumes them until perception contradicts them. Frames led to frame languages and, by another route, object-oriented programming; the previous lesson’s production systems often stored facts in them. Together these ideas are semantic networks and frames: knowledge organized as a class hierarchy with inheritable properties and defaults.

Exceptions create trouble. Birds fly, penguins are birds, penguins do not fly. Does a penguin fly? The paths “penguin ⇒ bird ⇝ flies” and “penguin ⇝ does not fly” disagree. Intuition favors the more specific (Touretzky, 1986, formalized this as inferential distance), but early systems resolved conflict by traversal order: conclusion depended on an implementation detail. When neither class is more specific, as in the Nixon diamond below, intuition cannot decide.

Woods (1975), in a paper tellingly titled “What’s in a link”, identified the root problem: edges had no semantics. “Is-a” meant individual membership, class inclusion and typical resemblance at once, with each system deciding what followed. Brachman’s “I lied about the trees” (1985) sharpened the criticism: if any frame property can be overridden by default, the frame defines nothing, because an object without any typical property would still belong, making classification impossible. Two research programs emerged. One removed defaults and gave definitions first-order semantics: KL-ONE (Brachman and Schmolze, 1985), ancestor of description logics. The other studied defaults as a logical phenomenon: nonmonotonic reasoning. This lesson follows both.

Description logics: concepts, roles, TBox and ABox

A description logic describes a domain of objects using three kinds of symbol: concept names (Servidor\mathsf{Servidor}, Activo\mathsf{Activo}), denoting sets of objects; role names (ejecuta\mathsf{ejecuta}, tieneVuln\mathsf{tieneVuln}), denoting binary relations; and individual names (web01\mathsf{web01}). Constructors form complex concepts. The base logic is ALC\mathcal{ALC} (Schmidt-Schauß and Smolka, 1991); others are named for their additions.

These are familiar set operations plus two quantifiers over relations. Read ∃ejecuta.ServicioWeb\exists \mathsf{ejecuta}.\mathsf{ServicioWeb} as “those running some web service” and ∀ejecuta.¬ServicioPublico\forall \mathsf{ejecuta}.\neg\mathsf{ServicioPublico} as “those running nothing public”. Notice the empty case: an object with no RR successor belongs to ∀R.C\forall R.C for any CC, and to no ∃R.C\exists R.C.

This language family, with set semantics and separation of terminology from facts, is called description logics. Several reasoning problems arise, all relative to a TBox T\mathcal{T}:

  • Satisfiability: is there a model of T\mathcal{T} with CI≠∅C^{\mathcal{I}} \neq \varnothing? An unsatisfiable ontology concept is almost always a modeling error.
  • Subsumption: T⊨C⊑D\mathcal{T} \models C \sqsubseteq D if CI⊆DIC^{\mathcal{I}} \subseteq D^{\mathcal{I}} in every model of T\mathcal{T}. Classifying an ontology computes all subsumptions between concept names.
  • Consistency of K\mathcal{K}: does it have a model?
  • Instance checking: K⊨C(a)\mathcal{K} \models C(a) if aI∈CIa^{\mathcal{I}} \in C^{\mathcal{I}} in every model of K\mathcal{K}.

All reduce to one because ALC\mathcal{ALC} has negation:

T⊨C⊑D  ⟺  C⊓¬D es insatisfacible respecto a T,K⊨C(a)  ⟺  (T,A∪{¬C(a)}) es inconsistente.\mathcal{T} \models C \sqsubseteq D \iff C \sqcap \neg D \text{ es insatisfacible respecto a } \mathcal{T}, \qquad \mathcal{K} \models C(a) \iff (\mathcal{T}, \mathcal{A} \cup \{\neg C(a)\}) \text{ es inconsistente}.

The first equivalence is familiar: CI⊆DIC^{\mathcal{I}} \subseteq D^{\mathcal{I}} if and only if CI∩(ΔI∖DI)=∅C^{\mathcal{I}} \cap (\Delta^{\mathcal{I}} \setminus D^{\mathcal{I}}) = \varnothing. Thus a description-logic reasoner is fundamentally a satisfiability checker.

Inside first-order logic, with two variables

Description logics are not a new logic but a carefully chosen fragment of first-order logic: concept names as unary predicates, roles as binary predicates.

Proof

By induction on CC. Atomic and Boolean cases are first-order semantic definitions. For ∃R.C\exists R.C: d∈(∃R.C)Id \in (\exists R.C)^{\mathcal{I}} if and only if some ee satisfies (d,e)∈RI(d, e) \in R^{\mathcal{I}} and e∈CIe \in C^{\mathcal{I}}, which by induction (applied to πy(C)\pi_y(C), with yy as its only free variable) is I⊨πy(C)[y↦e]\mathcal{I} \models \pi_y(C)[y \mapsto e]; that is exactly I⊨∃y (R(x,y)∧πy(C))[x↦d]\mathcal{I} \models \exists y\,(R(x, y) \wedge \pi_y(C))[x \mapsto d]. Case ∀\forall is symmetric. The only variables are xx and yy: each quantifier binds the variable not currently free, and the name reused inside is no longer needed outside.

∎

For example, πx(∃R.(A⊓∃R.B))=∃y (R(x,y)∧A(y)∧∃x (R(y,x)∧B(x)))\pi_x(\exists R.(A \sqcap \exists R.B)) = \exists y\,(R(x, y) \wedge A(y) \wedge \exists x\,(R(y, x) \wedge B(x))): inner xx is another bound variable reusing the name. This has fundamental consequences. FO2\mathrm{FO}^2 is decidable (Mortimer, 1975) and satisfiability is NEXPTIME-complete (Grädel, Kolaitis and Vardi, 1997), so ALC\mathcal{ALC} is decidable without its own algorithm. Translation also shows what ALC\mathcal{ALC} cannot say: “RR is transitive” or “xx has at least two distinct RR successors” need three variables; “xx is the RR successor of some AA”, ∃y (R(y,x)∧A(y))\exists y\,(R(y, x) \wedge A(y)), is in FO2\mathrm{FO}^2 but not ALC\mathcal{ALC} because it follows the role backward (the inverse role, I in the names below). Schild (1991) also observed ALC\mathcal{ALC} is a notational variant of multimodal logic Kn\mathbf{K}_n: ∃R.C\exists R.C is ◊RC\Diamond_R C and ∀R.C\forall R.C is □RC\Box_R C. From modal logic it inherits the tree model property: every satisfiable concept has a tree-shaped model. Tableaux exploit exactly this.

The next cell fixes the representation used throughout: concepts as tuples, a parser for symbolic or word syntax, semantics over finite interpretations, negation normal form (needed by tableaux and defined next) and translation to FO2\mathrm{FO}^2.

[ ]ALC concepts: parser, semantics, NNF and translation to FO²Browser
import itertools, random, re

# Conceptos ALC como tuplas:
#   ('top',) ('bot',) ('atom', 'A') ('not', C) ('and', C, D) ('or', C, D) ('some', 'R', C) ('all', 'R', C)
TOP, BOT = ('top',), ('bot',)

def parse(texto):
    """Lee ⊓ ⊔ ¬ ∃R.C ∀R.C ⊤ ⊥ (o and, or, not, some R.C, all R.C, top, bot).
    ¬, ∃ y ∀ ligan más que ⊓, y ⊓ más que ⊔."""
    toks = re.findall(r"[⊓⊔¬∃∀⊤⊥().]|[A-Za-z_][A-Za-z0-9_]*", texto)
    pal = {'and': '⊓', 'or': '⊔', 'not': '¬', 'some': '∃', 'all': '∀', 'top': '⊤', 'bot': '⊥'}
    toks = [pal.get(t, t) for t in toks]
    pos = 0
    def ver():
        return toks[pos] if pos < len(toks) else None
    def tomar(esperado=None):
        nonlocal pos
        t = ver()
        if t is None or (esperado and t != esperado):
            raise SyntaxError(f"esperaba {esperado or 'algo'} y encontré {t}")
        pos += 1
        return t
    def disy():
        c = conj()
        while ver() == '⊔':
            tomar(); c = ('or', c, conj())
        return c
    def conj():
        c = unario()
        while ver() == '⊓':
            tomar(); c = ('and', c, unario())
        return c
    def unario():
        t = tomar()
        if t == '¬': return ('not', unario())
        if t in '∃∀':
            r = tomar(); tomar('.')
            return ('some' if t == '∃' else 'all', r, unario())
        if t == '⊤': return TOP
        if t == '⊥': return BOT
        if t == '(':
            c = disy(); tomar(')'); return c
        return ('atom', t)
    c = disy()
    if pos != len(toks): raise SyntaxError(f"sobra {toks[pos:]}")
    return c

def show(c, prec=0):
    k = c[0]
    if k == 'top': return '⊤'
    if k == 'bot': return '⊥'
    if k == 'atom': return c[1]
    if k == 'not': return '¬' + show(c[1], 3)
    if k in ('some', 'all'): return ('∃' if k == 'some' else '∀') + c[1] + '.' + show(c[2], 3)
    p = 2 if k == 'and' else 1
    s = show(c[1], p) + (' ⊓ ' if k == 'and' else ' ⊔ ') + show(c[2], p)
    return f'({s})' if p < prec else s

def nnf(c):
    """Forma normal de negación: ¬ solo delante de nombres de concepto."""
    k = c[0]
    if k in ('top', 'bot', 'atom'): return c
    if k in ('and', 'or'): return (k, nnf(c[1]), nnf(c[2]))
    if k in ('some', 'all'): return (k, c[1], nnf(c[2]))
    d = c[1]; j = d[0]                       # c = ¬d
    if j == 'top': return BOT
    if j == 'bot': return TOP
    if j == 'atom': return c
    if j == 'not': return nnf(d[1])
    if j == 'and': return ('or', nnf(('not', d[1])), nnf(('not', d[2])))
    if j == 'or': return ('and', nnf(('not', d[1])), nnf(('not', d[2])))
    if j == 'some': return ('all', d[1], nnf(('not', d[2])))
    if j == 'all': return ('some', d[1], nnf(('not', d[2])))

def ext(c, I):
    """Extensión C^I en una interpretación finita I = (dominio, conceptos, roles)."""
    dom, conc, rol = I
    k = c[0]
    if k == 'top': return set(dom)
    if k == 'bot': return set()
    if k == 'atom': return set(conc.get(c[1], ()))
    if k == 'not': return set(dom) - ext(c[1], I)
    if k == 'and': return ext(c[1], I) & ext(c[2], I)
    if k == 'or': return ext(c[1], I) | ext(c[2], I)
    R, D = rol.get(c[1], set()), ext(c[2], I)
    if k == 'some': return {x for x in dom if any((x, y) in R for y in D)}
    return {x for x in dom if all(y in D for (z, y) in R if z == x)}

def fo2(c, x='x', y='y'):
    """Traducción estándar a primer orden reutilizando solo dos variables."""
    k = c[0]
    if k == 'top': return '⊤'
    if k == 'bot': return '⊥'
    if k == 'atom': return f'{c[1]}({x})'
    if k == 'not': return '¬' + fo2(c[1], x, y)
    if k in ('and', 'or'):
        return '(' + fo2(c[1], x, y) + (' ∧ ' if k == 'and' else ' ∨ ') + fo2(c[2], x, y) + ')'
    if k == 'some': return f'∃{y}.({c[1]}({x},{y}) ∧ {fo2(c[2], y, x)})'
    return f'∀{y}.({c[1]}({x},{y}) → {fo2(c[2], y, x)})'

def interpretacion_aleatoria(rng, n, nombres, roles, p=0.35):
    dom = list(range(n))
    conc = {A: {x for x in dom if rng.random() < 0.5} for A in nombres}
    rol = {R: {(x, y) for x in dom for y in dom if rng.random() < p} for R in roles}
    return dom, conc, rol

ejemplos = ["¬(∃R.A ⊓ ∀R.¬A)", "¬∀R.(A ⊔ ∃S.¬B)", "¬(A ⊔ ¬∃R.(B ⊓ ⊤))", "∃R.A ⊓ ∃R.B ⊓ ¬∃R.(A ⊓ B)"]
for e in ejemplos:
    c = parse(e)
    print(f"{e:32s} NNF: {show(nnf(c))}")
print()
print("FO²:", fo2(parse("∃R.(A ⊓ ∃R.B)")))
print("FO²:", fo2(parse("∀R.∃S.∀R.A")))

rng = random.Random(0)
fallos = 0
for _ in range(300):
    I = interpretacion_aleatoria(rng, 5, 'AB', 'RS')
    for e in ejemplos:
        c = parse(e)
        fallos += ext(c, I) != ext(nnf(c), I)
print("\nNNF frente al original en 300 interpretaciones aleatorias de 5 elementos: discrepancias =", fallos)

Translation of ∀R.∃S.∀R.A\forall R.\exists S.\forall R.A uses three nested quantifiers and still has only xx and yy. The final check proves nothing (300 five-element interpretations are not all interpretations), but is useful: mistakes in De Morgan rules or ¬∃R.C≡∀R.¬C\neg\exists R.C \equiv \forall R.\neg C duality appear quickly. The code exercise tests use the same technique.

The tableau algorithm

To decide whether C0C_0 is satisfiable, tableaux try to build a model. Start with object x0x_0 required to belong to C0C_0 and apply rules making requirements explicit: if x0x_0 is in C⊓DC \sqcap D, it is in CC and DD; if in ∃R.C\exists R.C, it needs an RR successor in CC; continue until no requirements remain (the tree is a model) or an obvious contradiction, a clash, appears. Disjunction forces a choice; if all choices clash, the concept is unsatisfiable. This resembles the refutation method, organized around a candidate model rather than a clause set.

Negation normal form and rules

Quantifier duality is first-order duality: no RR successor is in CC if and only if every RR successor is outside CC. With concepts in NNF, the algorithm works on a completion tree: nodes xx with a label L(x)\mathcal{L}(x), a set of concepts xx must satisfy, and role-labeled edges.

RuleConditionAction
⊓\sqcapC⊓D∈L(x)C \sqcap D \in \mathcal{L}(x) and {C,D}⊈L(x)\{C, D\} \not\subseteq \mathcal{L}(x)add CC and DD to L(x)\mathcal{L}(x)
⊔\sqcupC⊔D∈L(x)C \sqcup D \in \mathcal{L}(x) and C,D∉L(x)C, D \notin \mathcal{L}(x)branch: add CC in one branch and DD in the other
∃\exists∃R.C∈L(x)\exists R.C \in \mathcal{L}(x), xx unblocked and no RR successor yy has C∈L(y)C \in \mathcal{L}(y)create fresh RR successor yy with L(y)={C}\mathcal{L}(y) = \{C\}
∀\forall∀R.C∈L(x)\forall R.C \in \mathcal{L}(x), yy is an RR successor of xx and C∉L(y)C \notin \mathcal{L}(y)add CC to L(y)\mathcal{L}(y)

A node has a clash if its label contains ⊥\bot or a pair A,¬AA, \neg A. A branch is closed if it has a clash and open and complete if clash-free and no rule applies. The concept is satisfiable if and only if some branch remains open and complete.

General TBoxes and internalization

A general TBox uses a trick: axiom C⊑DC \sqsubseteq D says every object is in ¬C⊔D\neg C \sqcup D. Add CT=\bigsqcap(C⊑D)∈Tnnf(¬C⊔D)C_{\mathcal{T}} = \bigsqcap_{(C \sqsubseteq D) \in \mathcal{T}} \mathrm{nnf}(\neg C \sqcup D) to every node label, including those created by rule ∃\exists. This is TBox internalization. It is costly: each axiom introduces a disjunction at each node, and with kk axioms a node may have 2k2^k combinations to explore.

A more serious problem appears: nontermination. With T={A⊑∃R.A}\mathcal{T} = \{A \sqsubseteq \exists R.A\}, concept AA requires an RR successor in AA, which by the axiom requires another, indefinitely. A model exists (an x0→Rx0x_0 \xrightarrow{R} x_0 cycle suffices), but rule ∃\exists builds an infinite chain.

The idea: xx requires nothing yy does not already require, so the model can “reuse” yy‘s successors: the edge to xx is redirected to yy, turning the tree into a finite cyclic graph. The builder below reproduces this step by step.

InteractiveTableau builder
complete tree. No rule applies and there are no clashes: the tree is complete and defines a model.
RRx0∃R.A ⊓ ∃R.B ⊓ ∀R.(¬A ⊔ ¬B)∃R.A ⊓ ∃R.B∀R.(¬A ⊔ ¬B)∃R.A∃R.Bx1A¬A ⊔ ¬B¬Bx2B¬A ⊔ ¬B¬A
Search branches: each ⊔ branches; ✗ is a branch closed by a clash
¬A¬B¬A✗
  • added in this step
  • clash
  • open branch or tree
  • blocking
step 12 of 12
Rule at this stepcomplete tree
Nodes in tree3
Branches closed so far1
Satisfiable: an open, complete branch yields a model.
Each step applies a rule to the completion tree. Newly added concepts are blue, clashes red, and branches opened by ⊔ appear below (✗ if closed). In the initial example the first successor chooses ¬A, clashes with A and backtracks to choose ¬B. Try the cyclic TBox with and without blocking, and the security example: why is an isolated web server impossible? You can write your own concepts and axioms.

In the initial example, ∃R.A⊓∃R.B⊓∀R.(¬A⊔¬B)\exists R.A \sqcap \exists R.B \sqcap \forall R.(\neg A \sqcup \neg B), the algorithm creates two successors, one with AA and one with BB, and ∀\forall passes the disjunction to both. In the first, branch ¬A\neg A clashes with AA and ¬B\neg B must be tried; in the second, ¬A\neg A works immediately. The final tree is a three-element model. With the cyclic TBox, successor x1x_1 gets exactly what x0x_0 has, is blocked and the algorithm stops with two nodes; without blocking the chain grows to the drawing limit. In the security example, isolated-server definition gives ∀ejecuta.¬ServicioPublico\forall \mathsf{ejecuta}.\neg\mathsf{ServicioPublico}, the web server requires an ServicioWeb\mathsf{ServicioWeb} successor, the axiom makes it ServicioPublico\mathsf{ServicioPublico} and ∀\forall adds ¬ServicioPublico\neg\mathsf{ServicioPublico}: clash without exploring disjunctions.

Soundness, completeness and termination

Proof

Let cl\mathrm{cl} be the set of subconcepts of C0C_0 and CTC_{\mathcal{T}}, of size nn linear in the input. All labels are subsets of cl\mathrm{cl} because each rule adds a subconcept of something already present.

Termination. Each node has at most nn successors (one per ∃R.C\exists R.C concept of cl\mathrm{cl}) and labels only grow. On a root-to-leaf path a node whose label is contained in an ancestor’s is blocked and has no successors, so unblocked nodes on a path have pairwise distinct labels, and there are at most 2n2^n subsets of cl\mathrm{cl}: depth is bounded by 2n+12^n + 1 and the tree finite. Each rule grows it, so cannot apply indefinitely.

A complete clash-free tree gives a model. Define I\mathcal{I} with domain nodes neither blocked nor descendants of blocked nodes, AI={x:A∈L(x)}A^{\mathcal{I}} = \{x : A \in \mathcal{L}(x)\} and (x,y)∈RI(x, y) \in R^{\mathcal{I}} if yy is an unblocked RR successor of xx, or if xx has an RR successor blocked by yy. Induction on DD proves D∈L(x)D \in \mathcal{L}(x) implies x∈DIx \in D^{\mathcal{I}}. For AA it is the definition; for ¬A\neg A, no clash gives A∉L(x)A \notin \mathcal{L}(x) and x∉AIx \notin A^{\mathcal{I}}; ⊓\sqcap and ⊔\sqcup follow from label completeness. For ∃R.C\exists R.C: rule ∃\exists is inapplicable, so an RR successor zz has C∈L(z)C \in \mathcal{L}(z); if zz is unblocked it works; if blocked by yy, then (x,y)∈RI(x, y) \in R^{\mathcal{I}} and C∈L(z)⊆L(y)C \in \mathcal{L}(z) \subseteq \mathcal{L}(y). For ∀R.C\forall R.C: every RIR^{\mathcal{I}} successor of xx is an zz successor with C∈L(z)C \in \mathcal{L}(z) by rule ∀\forall, or its blocker yy with C∈L(z)⊆L(y)C \in \mathcal{L}(z) \subseteq \mathcal{L}(y). Since CTC_{\mathcal{T}} is in all labels, I\mathcal{I} models T\mathcal{T}, and x0∈C0Ix_0 \in C_0^{\mathcal{I}}.

A model gives an execution without clashes. Let J\mathcal{J} model T\mathcal{T} with d0∈C0Jd_0 \in C_0^{\mathcal{J}}. Maintain a mapping π\pi from nodes to the domain of J\mathcal{J} with π(x)∈DJ\pi(x) \in D^{\mathcal{J}} for all D∈L(x)D \in \mathcal{L}(x) and (π(x),π(y))∈RJ(\pi(x), \pi(y)) \in R^{\mathcal{J}} if yy is an RR successor of xx. Each rule preserves it: in ⊔\sqcup choose a disjunct satisfied by π(x)\pi(x); in ∃\exists map the new node to a witness of J\mathcal{J}; ⊓\sqcap and ∀\forall are immediate, and CTC_{\mathcal{T}} holds for every element because J\mathcal{J} models T\mathcal{T}. A label containing AA and ¬A\neg A or ⊥\bot cannot have an image, so that execution never clashes.

∎

NNF, these four rules, clash detection, internalization and blocking together form the tableau algorithm for description logics. Note blocking’s exact role: termination (depth bound) and model construction (edges to blocked nodes redirect), nowhere else. Without a TBox it is unnecessary because each ∃\exists application reduces quantifier depth of the new node’s concept and tree depth is bounded by C0C_0.

Complexity and optimizations

Without a TBox, satisfiability of ALC\mathcal{ALC} is PSPACE-complete (Schmidt-Schauß and Smolka, 1991), and tableaux can use polynomial space: explore a node’s successors one at a time depth-first, discard each subtree after checking, because in ALC\mathcal{ALC} no successor influences its parent. With a general TBox the problem is EXPTIME-complete (the lower bound comes from propositional dynamic logic; see Baader, Horrocks, Lutz and Sattler, 2017). Blocking tableaux are not worst-case optimal: the proof bounds depth only by 2n2^n, so paths can be exponentially long and the tree doubly exponential. Exponential-time procedures exist, but optimized tableaux win in practice because worst cases rarely occur in real ontologies. A few decisive optimizations make this possible:

  • Lazy unfolding and absorption (Horrocks and Tobies, 2000). An axiom A⊑DA \sqsubseteq D with a name on the left need not be internalized: add DD to nodes containing AA. An axiom A⊓E⊑DA \sqcap E \sqsubseteq D rewrites without meaning change as A⊑¬E⊔DA \sqsubseteq \neg E \sqcup D. A disjunction per node becomes one only in nodes containing AA.
  • Dependency-directed backtracking. Each concept remembers the ⊔\sqcup choices it depends on, and a clash jumps to the latest responsible choice, like SAT solvers’ nonchronological backjumping.
  • Caching refuted or satisfied labels, and model merging to rule out subsumptions without building anything.

FaCT (Horrocks, 1998), FaCT++ and Pellet are tableaux with these optimizations; HermiT uses hypertableaux reducing nondeterminism (Motik, Shearer and Horrocks, 2009); and for EL\mathcal{EL}, without disjunction or negation, consequence-based reasoners such as ELK saturate rules in polynomial time without building models.

A reasoner from scratch

The next cell implements the recursive algorithm used by depth-first reasoners: satisfy a node by saturating its label with ⊓\sqcap and lazy unfolding, checking clashes, choosing a disjunct for the first pending disjunction (the other on failure), checking blocking, and finally requiring all successors requested by ∃\exists to be satisfiable. It is an AND–OR tree: disjunctions are OR nodes and successors AND nodes. Absorption makes any axiom with a name or conjunction containing a name on the left lazy; the rest is internalized.

Why does lazy unfolding preserve the proof? There AIA^{\mathcal{I}} is defined as nodes whose labels contain AA. If x∈AIx \in A^{\mathcal{I}}, the lazy rule has added DD to L(x)\mathcal{L}(x), and the proof’s lemma gives x∈DIx \in D^{\mathcal{I}}: axiom A⊑DA \sqsubseteq D holds without internalization. It is not enough, however, to handle definition A≡CA \equiv C by unfolding AA toward CC and ¬A\neg A toward ¬C\neg C: a node satisfying CC without containing either AA or ¬A\neg A would remain outside AIA^{\mathcal{I}} and violate C⊑AC \sqsubseteq A in the constructed model. Thus the definition becomes two inclusions, and direction C⊑AC \sqsubseteq A is absorbed or internalized.

[ ]A tableau reasoner for ALCBrowser
class TBox:
    """Axiomas C ⊑ D y A ≡ C. Los de lado izquierdo atómico se despliegan de forma perezosa;
    los demás se absorben si su lado izquierdo es una conjunción con un nombre, o se internalizan."""
    def __init__(self, axiomas=(), absorber=True):
        self.perezosos = {}      # A -> [conceptos en NNF que se añaden cuando A aparece en una etiqueta]
        self.generales = []      # ¬C ⊔ D en NNF, que se añade a TODOS los nodos
        for texto in axiomas:
            if '≡' in texto:
                izq, der = (parse(t) for t in texto.split('≡'))
                self.incluir(izq, der, absorber); self.incluir(der, izq, absorber)
            else:
                izq, der = (parse(t) for t in texto.split('⊑'))
                self.incluir(izq, der, absorber)

    def incluir(self, C, D, absorber):
        if C[0] == 'atom':
            self.perezosos.setdefault(C[1], []).append(nnf(D)); return
        if absorber and C[0] == 'and':
            partes = aplanar(C, 'and')
            for i, p in enumerate(partes):
                if p[0] == 'atom':                  # B ⊓ E ⊑ D  ⟺  B ⊑ ¬E ⊔ D
                    resto = partes[:i] + partes[i + 1:]
                    E = resto[0]
                    for r in resto[1:]: E = ('and', E, r)
                    self.perezosos.setdefault(p[1], []).append(nnf(('or', ('not', E), D))); return
        self.generales.append(nnf(('or', ('not', C), D)))

def aplanar(c, k):
    return aplanar(c[1], k) + aplanar(c[2], k) if c[0] == k else [c]

def choque(L):
    return BOT in L or any(c[0] == 'atom' and ('not', c) in L for c in L)

class Tableau:
    """Satisfacibilidad de un concepto ALC respecto a una TBox, con bloqueo por inclusión."""
    def __init__(self, tbox=None, bloqueo=True, prof_max=60):
        self.T = tbox or TBox()
        self.bloqueo, self.prof_max = bloqueo, prof_max
        self.stats = dict(nodos=0, ramas=0, choques=0, bloqueos=0)
        self.insat = set()   # etiquetas ya refutadas: refutar no depende del contexto

    def saturar(self, L):
        """Reglas deterministas en un nodo: ⊓ y despliegue perezoso. Devuelve la etiqueta cerrada."""
        L, pend = set(L), list(L)
        while pend:
            c = pend.pop()
            nuevos = []
            if c[0] == 'and': nuevos = [c[1], c[2]]
            elif c[0] == 'atom': nuevos = self.T.perezosos.get(c[1], [])
            for d in nuevos:
                if d not in L:
                    L.add(d); pend.append(d)
        return frozenset(L)

    def sat(self, L, ancestros=()):
        L = self.saturar(L)
        if L in self.insat: return False
        if choque(L):
            self.stats['choques'] += 1; self.insat.add(L); return False
        # regla ⊔: la primera disyunción sin ningún disyunto en la etiqueta (nodo O)
        for c in sorted((c for c in L if c[0] == 'or'), key=show):
            if c[1] not in L and c[2] not in L:
                for d in (c[1], c[2]):
                    self.stats['ramas'] += 1
                    if self.sat(L | {d}, ancestros): return True
                self.insat.add(L); return False
        # bloqueo: un antepasado cuya etiqueta contiene a esta
        if self.bloqueo and any(L <= A for A in ancestros):
            self.stats['bloqueos'] += 1; return True
        if len(ancestros) >= self.prof_max:
            raise RecursionError(f"profundidad {self.prof_max} sin terminar")
        # reglas ∃ y ∀ (nodo Y): un sucesor por cada ∃R.C, que recibe C y cada D de los ∀R.D
        for c in sorted((c for c in L if c[0] == 'some'), key=show):
            R, C = c[1], c[2]
            hijo = {C} | {d[2] for d in L if d[0] == 'all' and d[1] == R} | set(self.T.generales)
            self.stats['nodos'] += 1
            if not self.sat(hijo, ancestros + (L,)):
                self.insat.add(L); return False
        return True

    def satisfacible(self, C):
        C = parse(C) if isinstance(C, str) else C
        return self.sat({nnf(C)} | set(self.T.generales))

    def subsume(self, C, D):
        """¿C ⊑ D respecto a la TBox?  ⟺  C ⊓ ¬D es insatisfacible."""
        C = parse(C) if isinstance(C, str) else C
        D = parse(D) if isinstance(D, str) else D
        return not self.satisfacible(('and', C, ('not', D)))

for e in ["∃R.A ⊓ ∀R.¬A", "∃R.A ⊓ ∃R.B ⊓ ∀R.(¬A ⊔ ¬B)", "(A ⊔ B) ⊓ ¬A ⊓ ¬B", "∃R.(A ⊓ B) ⊓ ∀R.(¬A ⊔ ∃S.⊥)"]:
    t = Tableau()
    print(f"{e:34s} satisfacible: {t.satisfacible(e)!s:5s}  {t.stats}")

print("\n∃R.(A ⊔ B) ⊑ ∃R.A ⊔ ∃R.B ?", Tableau().subsume("∃R.(A ⊔ B)", "∃R.A ⊔ ∃R.B"))
print("∃R.A ⊓ ∃R.B ⊑ ∃R.(A ⊓ B) ?", Tableau().subsume("∃R.A ⊓ ∃R.B", "∃R.(A ⊓ B)"))

# Una TBox cíclica: todo nodo con A necesita un sucesor con A
T = TBox(["A ⊑ ∃R.A ⊓ B"])
t = Tableau(T)
print("\nCon A ⊑ ∃R.A ⊓ B, ¿es A satisfacible?", t.satisfacible("A"), t.stats)
try:
    Tableau(T, bloqueo=False, prof_max=60).satisfacible("A")
except RecursionError as e:
    print("Sin bloqueo:", e)
t = Tableau(TBox(["A ⊑ ∃R.A ⊓ B", "B ⊑ ∀R.¬B"]))
print("Con además B ⊑ ∀R.¬B:", t.satisfacible("A"), t.stats)

Results match the builder above, although counts do not: the recursive reasoner explores depth-first and the builder applies rules globally, but both decide the same. Two subsumptions show quantifier asymmetry: ∃\exists distributes over ⊔\sqcup but not ⊓\sqcap (two successors, one in AA and another in BB, do not yield one in A⊓BA \sqcap B). With the cyclic TBox blocking stops at one node; without it the reasoner descends to your depth limit. Caching refuted labels is correct for a subtle reason: False arises only from clashes in every branch, never from blocking, the only ancestor-dependent operation.

Classifying a security ontology

Now the reasoner handles a realistic-looking small ontology of assets, services, vulnerabilities and controls, with defined concepts and a deliberate modeling error. Brute-force classification costs one subsumption test per ordered pair of names. The cell separates written subsumptions (transitive closure of name inclusions) from those only the reasoner finds, comparing cost with and without absorption.

[ ]Classifying a security ontologyBrowser
import time

ONTOLOGIA = [
    # activos y servicios
    "Servidor ⊑ Activo",
    "BaseDeDatos ⊑ Activo",
    "ServidorWeb ⊑ Servidor ⊓ ∃ejecuta.ServicioWeb",
    "ServidorProd ⊑ Servidor ⊓ ∃protegidoPor.(WAF ⊔ Segmentacion)",
    "ServicioWeb ⊑ ServicioPublico",
    # vulnerabilidades y controles
    "RCE ⊑ VulnCritica",
    "VulnCritica ⊑ Vulnerabilidad",
    "WAF ⊑ Control",
    "Segmentacion ⊑ Control",
    # conceptos definidos
    "ActivoExpuesto ≡ Activo ⊓ ∃ejecuta.ServicioPublico",
    "ActivoEnRiesgo ≡ ActivoExpuesto ⊓ ∃tieneVuln.VulnCritica",
    "ActivoProtegido ≡ Activo ⊓ ∃protegidoPor.Control",
    "ServidorAislado ≡ Servidor ⊓ ∀ejecuta.¬ServicioPublico",
    # un error de modelado: lo que pide es imposible
    "ServidorWebAislado ⊑ ServidorWeb ⊓ ServidorAislado",
]
nombres = sorted({n for ax in ONTOLOGIA for n in re.findall(r"\b[A-Z]\w*", ax)})

def clasificar(T, nombres):
    """Jerarquía completa por fuerza bruta: una prueba de subsunción por cada par ordenado."""
    t = Tableau(T)
    insat = [A for A in nombres if not t.satisfacible(('atom', A))]
    sub = {A: {B for B in nombres if B != A and A not in insat and t.subsume(('atom', A), ('atom', B))} for A in nombres}
    return insat, sub, t.stats

for absorber in (True, False):
    T = TBox(ONTOLOGIA, absorber=absorber)
    t0 = time.perf_counter()
    insat, sub, st = clasificar(T, nombres)
    print(f"{'con' if absorber else 'sin'} absorción: {len(T.generales)} axiomas internalizados, "
          f"{len(nombres) * (len(nombres) - 1)} pruebas, {time.perf_counter() - t0:.2f} s, {st}")
T = TBox(ONTOLOGIA)
insat, sub, _ = clasificar(T, nombres)
print("insatisfacibles:", insat)

# lo que el modelador escribió: cierre transitivo de las inclusiones entre nombres
dichos = {A: set() for A in nombres}
for ax in ONTOLOGIA:
    izq, der = (parse(s) for s in re.split('⊑|≡', ax))
    dichos[izq[1]] |= {p[1] for p in aplanar(der, 'and') if p[0] == 'atom'}
cambio = True
while cambio:
    cambio = False
    for A in nombres:
        nuevo = set().union(*(dichos[B] for B in dichos[A])) - dichos[A]
        if nuevo: dichos[A] |= nuevo; cambio = True
print("subsunciones que no estaban escritas:")
for A in nombres:
    for B in sorted(sub[A] - dichos[A]): print(f"  {A} ⊑ {B}")
t = Tableau(T)
print("ServidorAislado ⊑ ¬ActivoExpuesto:", t.subsume(parse("ServidorAislado"), parse("¬ActivoExpuesto")))

# instancias: cada individuo se «enrolla» en un concepto (la ABox es un árbol)
ABOX = {
    "web01": "ServidorWeb",
    "db01":  "BaseDeDatos ⊓ ∃ejecuta.ServicioPublico ⊓ ∃tieneVuln.RCE",
    "app01": "ServidorProd",
    "fw01":  "Servidor ⊓ ∀ejecuta.¬ServicioPublico",
}
tipos_alc = {a: sorted(B for B in nombres if t.subsume(parse(C), ('atom', B))) for a, C in ABOX.items()}
print()
for a, tipos in tipos_alc.items(): print(f"{a}: {tipos}")

Three results matter. The reasoner finds two unwritten subsumptions: ServidorWeb⊑ActivoExpuesto\mathsf{ServidorWeb} \sqsubseteq \mathsf{ActivoExpuesto} (every web server runs a web service, which is public, and is an asset) and ServidorProd⊑ActivoProtegido\mathsf{ServidorProd} \sqsubseteq \mathsf{ActivoProtegido}, requiring case analysis: the control is a WAF or segmentation, both an Control\mathsf{Control}. It detects ServidorWebAislado\mathsf{ServidorWebAislado} is unsatisfiable, what a reasoner in an ontology editor such as Protégé does by marking uninstantiable classes red. Absorption matters even here: with it no axioms remain internalized and classification explores 523 branches; without it the four definition axioms go to every node and the count rises to 3984.

Instances use a trick valid because each individual’s ABox is a tree: “roll it up” into a concept (what is known of db01\mathsf{db01} is BaseDeDatos⊓∃ejecuta.ServicioPublico⊓∃tieneVuln.RCE\mathsf{BaseDeDatos} \sqcap \exists\mathsf{ejecuta}.\mathsf{ServicioPublico} \sqcap \exists\mathsf{tieneVuln}.\mathsf{RCE}), turning instance checking into subsumption. With arbitrary ABoxes, cycles or shared individuals, tableaux work directly on the individual graph, as the open-world interactive below does.

Ontologies in practice: RDF, OWL 2 and SPARQL

On the semantic web, knowledge is written in RDF: a graph of subject–predicate–object triples, with IRIs as global names (:web01 :ejecuta :pg .). RDFS adds minimal vocabulary (rdfs:subClassOf, rdfs:domain, rdfs:range), and OWL 2 (W3C, 2009, second edition 2012) is description logic SROIQ(D)\mathcal{SROIQ}(\mathbf{D}) serialized in the same graph: owl:someValuesFrom is ∃\exists, owl:allValuesFrom is ∀\forall, owl:unionOf is ⊔\sqcup, owl:complementOf is ¬\neg. OWL 2 has two semantics: direct, description-logic semantics for ontologies meeting OWL 2 DL restrictions; and RDF-based, assigning meaning to any graph and undecidable.

As OWL 2 DL is N2EXPTIME-complete, the specification defines three profiles, each for a use case with its own guarantee (W3C, OWL 2 Profiles, 2012):

ProfileBasisGuaranteeIntended for
OWL 2 ELEL++\mathcal{EL}^{++}: ⊓\sqcap, ∃\exists, without ∀\forall or ⊔\sqcuppolynomial-time reasoning in ontology size (PTIME-complete)huge terminologies: SNOMED CT
OWL 2 QLDL-Litequery answering in AC⁰ (LOGSPACE) in data size, by rewriting to SQLontologies over relational databases
OWL 2 RLrulespolynomial-time rule application, implementable in a rule enginereasoning over large RDF data

Each profile’s grammar imposes restrictions. In OWL 2 RL, for example, a superclass cannot be owl:someValuesFrom or owl:unionOf (specification table 2): rules cannot invent anonymous individuals or reason by cases. In return everything reduces to Horn rules over triples (tables 4–9: cax-sco propagates rdfs:subClassOf to individuals, cls-int1 recognizes intersections, prp-fp concludes owl:sameAs with functional properties), applied to a fixed point by a forward-chaining engine.

SPARQL queries the graph: triple patterns with variables, filters, OPTIONAL, FILTER NOT EXISTS and aggregation. By default it queries the graph as-is without reasoning; SPARQL 1.1 entailment regimes or prior closure materialization let it see consequences.

Large real ontologies choose profiles. SNOMED CT, the reference clinical terminology, uses fragment EL\mathcal{EL}, so ELK classifies it in seconds. The Gene Ontology describes molecular functions, biological processes and cellular components with relations such as part_of and regulates, annotating genes of thousands of species. OWL ontologies covers all this: formal RDF vocabularies with description-logic semantics, profiles and query tools.

Open world versus closed world

The most important difference between ontology and database is not syntax. A database, and Datalog with negation as failure, uses the closed-world assumption: what is absent is false, and the database describes one concrete interpretation. An ontology uses the open-world assumption: facts describe what is known, and the answer is “yes” only if true in all models, “no” only if true in none, and “unknown” otherwise.

InteractiveOpen world versus closed world
TBox
Admin ⊑ Empleado
Auditor ⊑ Empleado
Becario ⊑ Empleado
Externo ⊑ ¬Empleado
Becario ⊑ ∀tienePermiso.¬Critico
Admin ⊑ ∃tienePermiso.Critico
Facts (ABox)
Admin(ana) · Auditor(beto) · Empleado(carla) · Externo(dani) · Critico(borrarProd) · Lectura(leerLogs) · tienePermiso(beto, leerLogs)
QuestionClosedOpen
Closed world (Datalog). Neither the facts nor the rules give that type to beto: the answer is no.
Open world (description logic). There are models of both kinds. In one, beto is {Auditor, Admin, Empleado, ∃tienePermiso.Critico}; in another, {Auditor, ¬Admin, Empleado}.
  • yes
  • no
  • unknown
  • inconsistent
Add to the base
Questions with different answers5 of 7
Open worldconsistent base
Closed world, violated constraints: ana is Admin with no recorded critical permission.
The same employee-and-permission base read as a database (closed world: query evaluated in the single interpretation of facts and rules) and an ontology (open world: tableaux decide whether the answer holds in every model, none or some). Click each question to see why. Then add Becario(carla): one open-world answer changes from unknown to no without a negative fact. Add the auditor axiom and then Externo(beto).

With the initial base, five of seven questions get different answers. There are three types of difference:

  • No versus unknown. Is beto an administrator? The database says no because it is absent. The ontology does not know: nothing prevents it. Likewise “is carla an intern?” or “does carla have permission borrarProd?”.
  • No versus yes. Does ana have some critical permission? The database has no witnessing row and says no (and, reading the axiom as an integrity constraint, warns of a violation). The ontology says yes: Admin⊑∃tienePermiso.Critico\mathsf{Admin} \sqsubseteq \exists\mathsf{tienePermiso}.\mathsf{Critico} guarantees one exists, even without knowing which. The open world can know something exists without naming it.
  • Yes versus unknown in ∀\forall. Are all beto’s permissions read-only? In the database yes: the only one is. In the ontology unknown: beto may have other unstated permissions. Adding Auditor⊑∀tienePermiso.Lectura\mathsf{Auditor} \sqsubseteq \forall\mathsf{tienePermiso}.\mathsf{Lectura} changes the open answer to yes: close the world in an ontology by saying so in axioms.

Open-world reasoning also infers negations, but only entailed ones. With Becario(carla)\mathsf{Becario}(\mathsf{carla}), axiom Becario⊑∀tienePermiso.¬Critico\mathsf{Becario} \sqsubseteq \forall\mathsf{tienePermiso}.\neg\mathsf{Critico} and Critico(borrarProd)\mathsf{Critico}(\mathsf{borrarProd}), the ontology concludes carla does not have that permission. Externo(beto)\mathsf{Externo}(\mathsf{beto}) makes the open base inconsistent, because beto is an auditor, hence an employee, and external people are not: it has no models and classical logic entails anything. The closed base keeps answering and flags the violated constraint.

When to use each? Closed world suits information complete by construction: your company’s payroll, your maintained inventory, enforced access rules (ungranted permission is denied). Open world suits partial information from many sources: the web, catalog integration, clinical knowledge. Security uses both: access policy is closed-world, known attack surface open-world, and confusion is costly.

Databases silently make a second assumption OWL does not: unique names. In SQL, distinct keys are distinct rows. In OWL, ana\mathsf{ana} and agarcia\mathsf{agarcia} may denote the same object unless declared distinct with owl:differentFrom or owl:AllDifferent. If a property is functional (each asset has one owner) and two names appear as values, OWL does not complain: it concludes they are the same person, as the cell shows.

OWL ontologies with rdflib and owlrl

The next cell is local (requires pip install rdflib owlrl). It writes the security ontology in Turtle, materializes OWL 2 RL closure with owlrl, queries the graph with SPARQL and compares each individual’s types with your tableau reasoner’s deductions from “Classifying a security ontology”, copied at the start. Finally it repeats with one modeling difference.

[ ]OWL 2 RL with rdflib and owlrl versus tableauxLocal GPU
import rdflib, owlrl
from rdflib import Namespace, OWL, RDFS

PREFIJOS = """
@prefix :     <http://ejemplo.org/sec#> .
@prefix owl:  <http://www.w3.org/2002/07/owl#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
"""
TBOX = """
:ejecuta a owl:ObjectProperty .   :tieneVuln a owl:ObjectProperty .   :protegidoPor a owl:ObjectProperty .
:tieneResponsable a owl:ObjectProperty, owl:FunctionalProperty .

:Servidor     rdfs:subClassOf :Activo .
:BaseDeDatos  rdfs:subClassOf :Activo .
:ServicioWeb  rdfs:subClassOf :ServicioPublico .
:RCE          rdfs:subClassOf :VulnCritica .
:VulnCritica  rdfs:subClassOf :Vulnerabilidad .
:WAF          rdfs:subClassOf :Control .
:Segmentacion rdfs:subClassOf :Control .

:ServidorWeb  rdfs:subClassOf :Servidor ,
    [ a owl:Restriction ; owl:onProperty :ejecuta ; owl:someValuesFrom :ServicioWeb ] .
:ServidorProd rdfs:subClassOf :Servidor ,
    [ a owl:Restriction ; owl:onProperty :protegidoPor ;
      owl:someValuesFrom [ owl:unionOf ( :WAF :Segmentacion ) ] ] .

:ActivoExpuesto  owl:equivalentClass [ owl:intersectionOf ( :Activo
    [ a owl:Restriction ; owl:onProperty :ejecuta ; owl:someValuesFrom :ServicioPublico ] ) ] .
:ActivoEnRiesgo  owl:equivalentClass [ owl:intersectionOf ( :ActivoExpuesto
    [ a owl:Restriction ; owl:onProperty :tieneVuln ; owl:someValuesFrom :VulnCritica ] ) ] .
:ActivoProtegido owl:equivalentClass [ owl:intersectionOf ( :Activo
    [ a owl:Restriction ; owl:onProperty :protegidoPor ; owl:someValuesFrom :Control ] ) ] .
:ServidorAislado owl:equivalentClass [ owl:intersectionOf ( :Servidor
    [ a owl:Restriction ; owl:onProperty :ejecuta ;
      owl:allValuesFrom [ owl:complementOf :ServicioPublico ] ] ) ] .
:ServidorWebAislado rdfs:subClassOf :ServidorWeb , :ServidorAislado .
"""
ABOX = """
:web01 a :ServidorWeb .
:db01  a :BaseDeDatos ; :ejecuta :pg ; :tieneVuln :cve1 .
:pg    a :ServicioPublico .
:cve1  a :RCE .
:app01 a :ServidorProd ; :tieneResponsable :ana , :agarcia .
:fw01  a :Servidor , [ a owl:Restriction ; owl:onProperty :ejecuta ;
                       owl:allValuesFrom [ owl:complementOf :ServicioPublico ] ] .
"""
S = Namespace("http://ejemplo.org/sec#")

def cerrar(ttl):
    g = rdflib.Graph()
    g.parse(data=ttl, format="turtle")
    n0 = len(g)
    owlrl.DeductiveClosure(owlrl.OWLRL_Semantics).expand(g)   # materializa las reglas OWL 2 RL
    return g, n0

def local(u):
    return str(u).split("#")[-1] if str(u).startswith(str(S)) else None

def tipos(g):
    q = """PREFIX : <http://ejemplo.org/sec#>
           SELECT ?x ?c WHERE { ?x a ?c . FILTER(?x IN (:web01, :db01, :app01, :fw01)) }"""
    out = {a: set() for a in ["web01", "db01", "app01", "fw01"]}
    for x, c in g.query(q):
        if local(c): out[local(x)].add(local(c))
    return out

# lo que dedujo el razonador de tableaux en la celda «Clasificar una ontología de seguridad»
tipos_alc = {
    "web01": {"Activo", "ActivoExpuesto", "Servidor", "ServidorWeb"},
    "db01":  {"Activo", "ActivoEnRiesgo", "ActivoExpuesto", "BaseDeDatos"},
    "app01": {"Activo", "ActivoProtegido", "Servidor", "ServidorProd"},
    "fw01":  {"Activo", "Servidor", "ServidorAislado"},
}

g, n0 = cerrar(PREFIJOS + TBOX + ABOX)
print(f"tripletas: {n0} asertadas, {len(g)} tras el cierre OWL 2 RL")
tipos_rl = tipos(g)
print("\nindividuo  solo tableaux ALC             solo OWL 2 RL")
for a in tipos_alc:
    print(f"{a:10s} {str(sorted(tipos_alc[a] - tipos_rl[a])):30s} {sorted(tipos_rl[a] - tipos_alc[a])}")

sub_rl = {(local(a), local(b)) for a, b in g.subject_objects(RDFS.subClassOf) if local(a) and local(b) and a != b}
print("\n¿Materializa OWL 2 RL estas subsunciones entre clases?")
for par in [("ServidorWeb", "Activo"), ("ServidorWeb", "ActivoExpuesto"), ("ServidorProd", "ActivoProtegido")]:
    print(f"  {par[0]} ⊑ {par[1]}: {par in sub_rl}")
print("  ¿ServidorWebAislado ⊑ owl:Nothing?", (S.ServidorWebAislado, RDFS.subClassOf, OWL.Nothing) in g)

print("\nnombres únicos: ¿ana owl:sameAs agarcia?", (S.ana, OWL.sameAs, S.agarcia) in g)

SIN_CONTROL = """PREFIX : <http://ejemplo.org/sec#>
SELECT ?a WHERE { ?a a :Activo . FILTER NOT EXISTS { ?a :protegidoPor ?c } } ORDER BY ?a"""
print("SPARQL, activos sin ningún protegidoPor en el grafo:", [local(r.a) for r in g.query(SIN_CONTROL)])

# la misma ontología nombrando el complemento: NoPublico ≡ ¬ServicioPublico
nombrado = (TBOX + ABOX).replace("[ owl:complementOf :ServicioPublico ]", ":NoPublico") + \
           ":NoPublico owl:equivalentClass [ owl:complementOf :ServicioPublico ] ."
g2, _ = cerrar(PREFIJOS + nombrado)
print("\ncon el complemento nombrado, tipos de fw01 en OWL 2 RL:", sorted(tipos(g2)["fw01"]))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The comparison precisely separates what RL captures from what it does not:

  • They agree on web01\mathsf{web01} and db01\mathsf{db01}. RL inferring ActivoExpuesto(web01)\mathsf{ActivoExpuesto}(\mathsf{web01}) is less obvious than it seems: rule scm-svf1 concludes that restriction “runs some ServicioWeb\mathsf{ServicioWeb}” is a subclass of “runs some ServicioPublico\mathsf{ServicioPublico}” because ServicioWeb⊑ServicioPublico\mathsf{ServicioWeb} \sqsubseteq \mathsf{ServicioPublico}, then cls-int1 recognizes the intersection in the individual. RL cannot create the anonymous web service, but can reason about restrictions as classes.
  • They differ on app01\mathsf{app01}: inferring it is protected requires reasoning by cases over union WAF⊔Segmentacion\mathsf{WAF} \sqcup \mathsf{Segmentacion} within an existential in a superclass, precisely what RL’s grammar excludes.
  • They differ on fw01\mathsf{fw01} for a distinct practical reason: the universal restriction of its assertion and that in ServidorAislado\mathsf{ServidorAislado}‘s definition are distinct anonymous graph nodes, and no RL rule concludes separately written complements equal. With the complement named, the last line shows RL does infer it. In RL, axiom wording changes deductions; in direct semantics it does not.
  • At class level, RL materializes the declared hierarchy (ServidorWeb⊑Activo\mathsf{ServidorWeb} \sqsubseteq \mathsf{Activo}) but not the two tableau subsumptions because no rule concludes a class is contained in an intersection, and it does not detect ServidorWebAislado\mathsf{ServidorWebAislado} is empty. RL materializes individual facts; classifying an expressive TBox needs a DL reasoner.
  • Conversely, RL concludes ana owl:sameAs agarcia because tieneResponsable is functional. ALC\mathcal{ALC} tableaux lack functional properties and miss it. This warns about unique names: if the names were two people, the error is in the ontology, and OWL will not tell you unless declared distinct (making the base inconsistent).
  • SPARQL is closed-world over the graph: the FILTER NOT EXISTS query lists all four assets as “without control”, including app01\mathsf{app01}, which the reasoner knows is protected by some control. The query asks about triples, not models.

Nonmonotonic reasoning

Classical logic is monotone: if Γ⊨φ\Gamma \models \varphi, then Γ∪Δ⊨φ\Gamma \cup \Delta \models \varphi for any Δ\Delta. Adding information never removes conclusions. Common sense differs: conclude Tweety flies because it is a bird, then withdraw that on learning it is a penguin. Frame defaults, negation as failure and closed world all reason this way: draw conclusions in the absence of contrary information. Formal study is nonmonotonic reasoning, born as a discipline in the 1980 Artificial Intelligence special issue with Reiter’s default logic, McCarthy’s circumscription and McDermott and Doyle’s nonmonotonic logic.

Default logic

The definition is deliberately circular: justification consistency is checked against EE, the final result, not what has been derived so far. This prevents applying a default before knowing another blocks it. An extension is a stable belief set: applying permitted defaults reproduces it exactly. For finite theories it suffices to try candidates of form E=Th(W∪{γ:d∈D′})E = \mathrm{Th}(W \cup \{\gamma : d \in D'\}) for subsets D′⊆DD' \subseteq D, which this section’s cell brute-forces.

Three properties characterize behavior:

  • There may be no extension. (∅,{:¬pp})(\varnothing, \{\frac{: \neg p}{p}\}) has none: if p∈Ep \in E, justification ¬p\neg p is inconsistent with EE and Γ(E)=Th(∅)∌p\Gamma(E) = \mathrm{Th}(\varnothing) \not\ni p; if p∉Ep \notin E, the default applies and Γ(E)∋p\Gamma(E) \ni p.
  • Normal theories always have one (Reiter, 1980) and are semimonotone: adding normal defaults does not destroy extensions, only expands them.
  • There may be several, with two kinds of conclusion: skeptical (in every extension) and credulous (in some). Credulous consequence is Σ2p\Sigma_2^p-complete and skeptical Π2p\Pi_2^p-complete (Gottlob, 1992), one step above SAT in the polynomial hierarchy.
InteractiveInheritance with exceptions
¬BirdPenguinFlies
In extension E1birdpenguinflies
tweetyyesnoyes
pinguyesyesno
  • strict rule
  • default
  • red and ¬: negative conclusion
  • depends on extension
Dimmed cells are facts; the others are conclusions.
Network
Facts
Exception type
Semantics
Extensions1
Skeptical (in all extensions)¬penguin(tweety), flies(tweety), ¬flies(pingu)
Credulous only (in some, not all)nothing
Withdrawn compared with not knowing selected facts¬penguin(pingu), flies(pingu)
Solid edges: strict rules; dashed: defaults; red with ¬: negative conclusions. The table shows each individual's conclusions in the selected extension (dim cells: facts). Start with birds: uncheck and check ‘pingu is a penguin’ and observe ‘withdrawn’. Change the exception to ‘another default’: two extensions appear. Try the exception in the justification, Nixon diamond and finally naive inheritance with both rule orders.

The figure shows three phenomena the theory must explain. First, nonmonotonicity: with the strict exception, learning pingu is a penguin withdraws vuela(pingu)\mathsf{vuela}(\mathsf{pingu}) and ¬pinguino(pingu)\neg\mathsf{pinguino}(\mathsf{pingu}), which was in the extension without that fact. The second is surprising but correct: with “penguins do not fly” in WW and vuela\mathsf{vuela} concluded by default, classical logic deduces by contraposition that it is not a penguin. Extensions are closed under Th\mathrm{Th}, contraposition included.

Second, specificity. If the exception is another default, the bird theory behaves like Nixon’s diamond: two extensions, one with pingu flying. Reiter gives no automatic priority to specificity. Two standard fixes: put the exception in the justification (a seminormal default ave(x):vuela(x)∧¬pinguino(x)vuela(x)\frac{\mathsf{ave}(x) : \mathsf{vuela}(x) \wedge \neg\mathsf{pinguino}(x)}{\mathsf{vuela}(x)}), restoring one extension at the cost of manually listing exceptions; or use prioritized default logics (such as Brewka’s) ordering defaults by specificity.

Third, the danger of lacking semantics: naive inheritance, applying rules in a fixed order and adding each conclusion if it does not contradict what is already obtained, concludes pingu flies if it visits the general rule first, even with the strict exception, violating a rule declared exceptionless. The other order succeeds. This is the lesson’s first common mistake, and why frame systems ultimately needed underlying logic. The cell reproduces the calculations.

[ ]Extensions of a default theoryBrowser
import itertools

# Lógica por defecto proposicional (instancias cerradas), por fuerza bruta.
# Literal: 'p' o '-p'. W: lista de cláusulas (listas de literales). Un default es (prerrequisitos, justificaciones, conclusión).
def neg(l): return l[1:] if l.startswith('-') else '-' + l
def atomo(l): return l.lstrip('-')

class Teoria:
    def __init__(self, W, D):
        self.W, self.D = W, D
        self.atomos = sorted({atomo(l) for c in W for l in c} | {atomo(l) for d in D for l in d[0] + d[1] + [d[2]]})
        self.mundos = [dict(zip(self.atomos, v)) for v in itertools.product([False, True], repeat=len(self.atomos))]

    def vale(self, l, m): return m[atomo(l)] != l.startswith('-')
    def modelos(self, lits):
        """Índices de los mundos que satisfacen W y los literales dados: identifican Th(W ∪ lits)."""
        return frozenset(i for i, m in enumerate(self.mundos)
                         if all(any(self.vale(l, m) for l in c) for c in self.W) and all(self.vale(l, m) for l in lits))
    def implica(self, M, l): return all(self.vale(l, self.mundos[i]) for i in M)

    def gamma(self, E):
        """Γ(E): el menor conjunto cerrado que aplica los defaults cuyas justificaciones son consistentes con E."""
        S, cambio = set(), True
        while cambio:
            cambio = False
            M = self.modelos(S)
            for pre, just, concl in self.D:
                if concl not in S and all(self.implica(M, p) for p in pre) and not any(self.implica(E, neg(j)) for j in just):
                    S.add(concl); cambio = True
        return self.modelos(S)

    def extensiones(self):
        """E es extensión si y solo si E = Γ(E). Basta probar E = Th(W ∪ conclusiones de un subconjunto de D)."""
        ext = {}
        for k in range(len(self.D) + 1):
            for sub in itertools.combinations(self.D, k):
                E = self.modelos({d[2] for d in sub})
                if E and E not in ext and self.gamma(E) == E:
                    ext[E] = sorted(d[2] for d in sub)
        return ext

    def informe(self, nombre, consultas):
        ext = self.extensiones()
        print(f"{nombre}: {len(ext)} extensión(es)")
        for E, concl in ext.items(): print("   generada por los defaults que concluyen", concl)
        for q in consultas:
            esc = all(self.implica(E, q) for E in ext)
            cre = any(self.implica(E, q) for E in ext)
            print(f"   {q:18s} escéptico: {esc!s:5s}  crédulo: {cre}")

aves = lambda x: ([f'ave({x})'], [f'vuela({x})'], f'vuela({x})')                    # ave : vuela / vuela
W = [['-pinguino(pingu)', 'ave(pingu)'], ['-pinguino(pingu)', '-vuela(pingu)'],    # estrictas
     ['-pinguino(tweety)', 'ave(tweety)'], ['-pinguino(tweety)', '-vuela(tweety)'],
     ['ave(tweety)'], ['pinguino(pingu)']]
Teoria(W, [aves('tweety'), aves('pingu')]).informe("Tweety y pingu", ['vuela(tweety)', '-vuela(pingu)', '-pinguino(tweety)'])

W2 = [['-pinguino(pingu)', 'ave(pingu)'], ['pinguino(pingu)']]
D2 = [aves('pingu'), (['pinguino(pingu)'], ['-vuela(pingu)'], '-vuela(pingu)')]   # la excepción, ahora también por defecto
Teoria(W2, D2).informe("Excepción por defecto", ['vuela(pingu)', '-vuela(pingu)'])

D3 = [(['ave(pingu)'], ['vuela(pingu)', '-pinguino(pingu)'], 'vuela(pingu)'), D2[1]]   # seminormal: la excepción en la justificación
Teoria(W2, D3).informe("Excepción en la justificación", ['vuela(pingu)', '-vuela(pingu)'])

W4 = [['cuaquero(nixon)'], ['republicano(nixon)']]
D4 = [(['cuaquero(nixon)'], ['pacifista(nixon)'], 'pacifista(nixon)'),
      (['republicano(nixon)'], ['-pacifista(nixon)'], '-pacifista(nixon)')]
Teoria(W4, D4).informe("Diamante de Nixon", ['pacifista(nixon)', '-pacifista(nixon)', 'republicano(nixon)'])

# no monotonía: añadir un hecho retira una conclusión
W5 = [['-pinguino(opus)', 'ave(opus)'], ['-pinguino(opus)', '-vuela(opus)'], ['ave(opus)']]
for extra in ([], [['pinguino(opus)']]):
    Teoria(W5 + extra, [aves('opus')]).informe("Opus" + (" tras saber que es pingüino" if extra else ""), ['vuela(opus)'])

The first theory shows contraposition: ¬pinguino(tweety)\neg\mathsf{pinguino}(\mathsf{tweety}) is a skeptical consequence. The second and fourth give two extensions, with both conclusions credulous and neither skeptical; the third restores one by putting the exception in the justification. The last is nonmonotonicity in pure form: same default, one more premise, one less conclusion.

Circumscription

McCarthy (1980) approached models rather than rules: conclude what holds in models where certain predicates are minimal. Exceptions use an abnormality predicate,

∀x (Ave(x)∧¬Ab(x)→Vuela(x)),∀x (Pinguino(x)→Ab(x)),\forall x\,\big(\mathsf{Ave}(x) \wedge \neg\mathsf{Ab}(x) \rightarrow \mathsf{Vuela}(x)\big), \qquad \forall x\,\big(\mathsf{Pinguino}(x) \rightarrow \mathsf{Ab}(x)\big),

and circumscription of Ab\mathsf{Ab} in theory AA is the second-order formula

Circ(A;Ab)  =  A(Ab)∧¬∃P (A(P)∧P<Ab),\mathrm{Circ}(A; \mathsf{Ab}) \;=\; A(\mathsf{Ab}) \wedge \neg\exists P\,\big(A(P) \wedge P < \mathsf{Ab}\big),

where P<AbP < \mathsf{Ab} means P⊆AbP \subseteq \mathsf{Ab} and P≠AbP \neq \mathsf{Ab}: the theory cannot be satisfied with fewer abnormalities. Its models are models of AA with minimal Ab\mathsf{Ab} (letting Vuela\mathsf{Vuela} vary). If only Ave(tweety)\mathsf{Ave}(\mathsf{tweety}) is known, the minimal model has empty Ab\mathsf{Ab} and Tweety flies; add Pinguino(tweety)\mathsf{Pinguino}(\mathsf{tweety}) and Ab\mathsf{Ab} must contain it, removing the conclusion. In Nixon’s diamond, with one abnormality predicate per default, there are two classes of minimal models and circumscription concludes only what holds in both: like skeptical reasoning. Its advantage is classical (second-order) logic with clean model semantics; its drawback is that the second-order formula does not always reduce to first order.

ASP as a practical tool

Today’s practical tool for default reasoning at scale is answer set programming. Gelfond and Lifschitz (1991) added classical negation −p-p, distinct from negation as failure not p, to logic programs and showed answer sets of an extended program correspond to extensions of the default theory associating each rule L0←L1,…,Lm,not Lm+1,…,not LnL_0 \leftarrow L_1, \dots, L_m, \mathtt{not}\ L_{m+1}, \dots, \mathtt{not}\ L_n with default L1∧⋯∧Lm:Lm+1‾,…,Ln‾L0\frac{L_1 \wedge \dots \wedge L_m : \overline{L_{m+1}}, \dots, \overline{L_n}}{L_0}, where L‾\overline{L} is the complementary literal. A normal default ave(x):vuela(x)vuela(x)\frac{\mathsf{ave}(x) : \mathsf{vuela}(x)}{\mathsf{vuela}(x)} is written vuela(X) :- ave(X), not -vuela(X)., and clingo directly computes credulous (--enum-mode=brave) and skeptical (--enum-mode=cautious) consequences.

[ ]Defaults in ASP: answer sets, credulous and skepticalLocal GPU
import clingo

def consecuencias(programa, modo):
    """modo 'auto': todos los conjuntos respuesta; 'brave': lo que está en alguno; 'cautious': lo que está en todos."""
    ctl = clingo.Control(["0", f"--enum-mode={modo}"])
    ctl.add("base", [], programa)
    ctl.ground([("base", [])])
    modelos = []
    with ctl.solve(yield_=True) as h:
        for m in h:
            modelos.append(sorted(str(s) for s in m.symbols(shown=True)))
    return modelos if modo == "auto" else modelos[-1]   # en brave y cautious, el último modelo es el resultado final

NIXON = """
cuaquero(nixon). republicano(nixon).
pacifista(X)  :- cuaquero(X),    not -pacifista(X).   % cuáquero : pacifista / pacifista
-pacifista(X) :- republicano(X), not pacifista(X).    % republicano : ¬pacifista / ¬pacifista
#show pacifista/1. #show -pacifista/1.
"""
print("Nixon, conjuntos respuesta:", consecuencias(NIXON, "auto"))
print("   crédulo (brave):     ", consecuencias(NIXON, "brave"))
print("   escéptico (cautious):", consecuencias(NIXON, "cautious"))

AVES = """
ave(tweety). pinguino(pingu).
ave(X) :- pinguino(X).
-vuela(X) :- pinguino(X).
vuela(X) :- ave(X), not -vuela(X).
"""
modelo = consecuencias(AVES, "auto")
print("\nAves:", modelo)
print("¿Contiene -pinguino(tweety)?", any("-pinguino(tweety)" in m for m in modelo))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Nixon yields two answer sets; credulous consequences are their union and skeptical ones empty, as in default logic. The birds give one answer set, with Tweety flying and pingu not. But notice the last line: the answer set does not contain ¬pinguino(tweety)\neg\mathsf{pinguino}(\mathsf{tweety}), present in Reiter’s extension. This is not a translation error: ASP rules are inference rules, not material implications, and do not contrapose. Gelfond and Lifschitz translate rule -vuela(X) :- pinguino(X) as default pinguino(x):¬vuela(x)\frac{\mathsf{pinguino}(x) :}{\neg\mathsf{vuela}(x)}, not formula pinguino(x)→¬vuela(x)\mathsf{pinguino}(x) \rightarrow \neg\mathsf{vuela}(x) in WW. For almost any application that is desired: access-control or configuration rules read in one direction.

Actions and change: situation calculus

So far the world was static. An acting agent must represent change: what holds after moving a block, applying a patch, opening a port. McCarthy and Hayes (1969) proposed situation calculus, a first-order theory with three object types:

  • Situations: finite action histories. S0S_0 is initial and do(a,s)do(a, s) results from doing aa in ss. A situation is not a state: do(a,do(b,S0))do(a, do(b, S_0)) and do(b,do(a,S0))do(b, do(a, S_0)) differ even if the world ends identically.
  • Actions: terms such as mover(x,y)\mathsf{mover}(x, y) (put block xx on yy) or aMesa(x)\mathsf{aMesa}(x).
  • Fluents: relations whose truth depends on the situation, with situation as last argument: Sobre(x,y,s)\mathsf{Sobre}(x, y, s), EnMesa(x,s)\mathsf{EnMesa}(x, s), Libre(x,s)\mathsf{Libre}(x, s).

Preconditions say when an action is possible:

Poss(mover(x,y),s)↔Libre(x,s)∧Libre(y,s)∧x≠y∧¬Sobre(x,y,s),Poss(aMesa(x),s)↔Libre(x,s)∧¬EnMesa(x,s).\mathsf{Poss}(\mathsf{mover}(x, y), s) \leftrightarrow \mathsf{Libre}(x, s) \wedge \mathsf{Libre}(y, s) \wedge x \neq y \wedge \neg\mathsf{Sobre}(x, y, s), \qquad \mathsf{Poss}(\mathsf{aMesa}(x), s) \leftrightarrow \mathsf{Libre}(x, s) \wedge \neg\mathsf{EnMesa}(x, s).

Effect axioms say what changes. In the blocks world eight suffice, four positive and four negative:

Sobre(x,y,do(mover(x,y),s)),EnMesa(x,do(aMesa(x),s)),Sobre(x,z,s)∧z≠y→Libre(z,do(mover(x,y),s)),Sobre(x,z,s)→Libre(z,do(aMesa(x),s)),z≠y→¬Sobre(x,z,do(mover(x,y),s)),¬Sobre(x,z,do(aMesa(x),s)),¬EnMesa(x,do(mover(x,y),s)),¬Libre(y,do(mover(x,y),s)).\begin{aligned} &\mathsf{Sobre}(x, y, do(\mathsf{mover}(x, y), s)), \qquad \mathsf{EnMesa}(x, do(\mathsf{aMesa}(x), s)), \\ &\mathsf{Sobre}(x, z, s) \wedge z \neq y \rightarrow \mathsf{Libre}(z, do(\mathsf{mover}(x, y), s)), \qquad \mathsf{Sobre}(x, z, s) \rightarrow \mathsf{Libre}(z, do(\mathsf{aMesa}(x), s)), \\ &z \neq y \rightarrow \neg\mathsf{Sobre}(x, z, do(\mathsf{mover}(x, y), s)), \qquad \neg\mathsf{Sobre}(x, z, do(\mathsf{aMesa}(x), s)), \\ &\neg\mathsf{EnMesa}(x, do(\mathsf{mover}(x, y), s)), \qquad \neg\mathsf{Libre}(y, do(\mathsf{mover}(x, y), s)). \end{aligned}

The frame problem

With only this, start at S0S_0 with CC on AA and AA and BB on the table, and do aMesa(C)\mathsf{aMesa}(C). Effect axioms say CC is on the table, no longer on AA, and AA is clear. Is BB still on the table? Still clear? The theory does not say: nothing states that things the action does not mention remain unchanged. Worse, after a second action you cannot even prove its preconditions. This is the frame problem (McCarthy and Hayes, 1969): describing what does not change.

InteractiveThe frame problem
s = do(mover(B,C), do(aMesa(C), S0))
The world (simulated)
ACB
What the theory proves in s
Sobre(A,B) ?Sobre(A,C) ?¬Sobre(B,A)Sobre(B,C)Sobre(C,A) ?Sobre(C,B) ?EnMesa(A) ?¬EnMesa(B)EnMesa(C) ?Libre(A) ?Libre(B) ?¬Libre(C)
  • proven true
  • proven false
  • undecided
Theory
Actions possible in the world
3
Undecided fluents8 of 12
Written schemas: effect8
Without frame axioms, the theory knows nothing about what the last action does not mention: it cannot even prove the preconditions of the next one (marked ?).
Blocks world in situation calculus. The drawing is the simulated world; the grid shows what each theory proves in the current situation (green: true, red: false, gray: undecided). The initial state has already done aMesa(C) and mover(B, C). With only effect axioms, count undecided fluents and notice actions marked ?: the theory cannot prove they are possible. Switch to ‘effects + frame’ and ‘successor state’, compare axiom counts, and increase the block count.

The direct solution is frame axioms: for each action and unaffected fluent, one axiom preserving truth and another falsity, such as EnMesa(z,s)∧z≠x→EnMesa(z,do(mover(x,y),s))\mathsf{EnMesa}(z, s) \wedge z \neq x \rightarrow \mathsf{EnMesa}(z, do(\mathsf{mover}(x, y), s)). With AA actions and FF fluents, on the order of 2⋅A⋅F2 \cdot A \cdot F are needed (Reiter, 1991). Our domain needs 2⋅2⋅3=122 \cdot 2 \cdot 3 = 12 schemas plus 8 effect axioms, and instantiated for nn blocks (n2n^2 actions and n2+nn^2 + n fluents), 2n2(n2+n)2 n^2 (n^2 + n): 216 for three blocks and 22,000 for ten. This is the representational frame problem. There is also an inferential one: even when written, a reasoner must apply one per persisting fluent at each step. Two relatives: the qualification problem (McCarthy, 1980), enumerating every condition that could prevent an action, and the ramification problem, indirect effects of an action.

The first response used nonmonotonic reasoning: “fluents persist by default”, minimizing change by circumscription. Hanks and McDermott (1987) showed with the Yale shooting problem that this alone fails: load a gun, wait, then shoot Fred. Minimizing abnormalities permits an anomalous model in which the gun unloads during the wait without cause and Fred survives, with the same number of changes as the expected model. Minimizing change does not capture causation.

Successor-state axioms

Reiter (1991), building on Haas (1987), Pednault (1989) and Schubert (1990), gave a monotone, simple and complete solution under an explicit assumption. Write all effect axioms of fluent FF in normal form:

γF+(x⃗,a,s)→F(x⃗,do(a,s)),γF−(x⃗,a,s)→¬F(x⃗,do(a,s)),\gamma_F^+(\vec{x}, a, s) \rightarrow F(\vec{x}, do(a, s)), \qquad \gamma_F^-(\vec{x}, a, s) \rightarrow \neg F(\vec{x}, do(a, s)),

where γF+\gamma_F^+ disjoins all conditions under which an action makes FF true, and γF−\gamma_F^- those making it false. For Libre\mathsf{Libre}, for example, γLibre+(z,a,s)=∃x,y (a=mover(x,y)∧Sobre(x,z,s)∧z≠y)∨∃x (a=aMesa(x)∧Sobre(x,z,s))\gamma^+_{\mathsf{Libre}}(z, a, s) = \exists x, y\,(a = \mathsf{mover}(x, y) \wedge \mathsf{Sobre}(x, z, s) \wedge z \neq y) \vee \exists x\,(a = \mathsf{aMesa}(x) \wedge \mathsf{Sobre}(x, z, s)) and γLibre−(z,a,s)=∃x (a=mover(x,z))\gamma^-_{\mathsf{Libre}}(z, a, s) = \exists x\,(a = \mathsf{mover}(x, z)). Causal completeness says these are all ways to change FF: if FF changes false to true, γF+\gamma_F^+ held, and if true to false, γF−\gamma_F^- held. These are Schubert’s explanatory closure axioms. Combining effects with closure and assuming γF+\gamma_F^+ and γF−\gamma_F^- cannot both hold yields one equivalence per fluent:

Proof

(⇐\Leftarrow) If γF+\gamma_F^+ holds, the positive effect axiom gives F(x⃗,do(a,s))F(\vec{x}, do(a, s)). If F(x⃗,s)F(\vec{x}, s) and ¬γF−\neg\gamma_F^- hold and FF were false in do(a,s)do(a, s), negative explanatory closure F(x⃗,s)∧¬F(x⃗,do(a,s))→γF−F(\vec{x}, s) \wedge \neg F(\vec{x}, do(a, s)) \rightarrow \gamma_F^- would give γF−\gamma_F^-: contradiction. (⇒\Rightarrow) Suppose F(x⃗,do(a,s))F(\vec{x}, do(a, s)) and ¬γF+\neg\gamma_F^+. Positive explanatory closure gives ¬F(x⃗,s)∧F(x⃗,do(a,s))→γF+\neg F(\vec{x}, s) \wedge F(\vec{x}, do(a, s)) \rightarrow \gamma_F^+, so F(x⃗,s)F(\vec{x}, s). If γF−\gamma_F^- held, the negative effect axiom would give ¬F(x⃗,do(a,s))\neg F(\vec{x}, do(a, s)); therefore ¬γF−\neg\gamma_F^-. Conversely the successor-state axiom directly implies effect and closure axioms using consistency.

∎

Read as a sentence: FF is true after aa if aa made it true, or it already was true and aa did not make it false. This is the core of situation calculus and the frame problem, and its solution costs exactly one axiom per fluent. In the blocks world:

Sobre(x,y,do(a,s))↔a=mover(x,y)∨(Sobre(x,y,s)∧a≠aMesa(x)∧¬∃z a=mover(x,z)),EnMesa(x,do(a,s))↔a=aMesa(x)∨(EnMesa(x,s)∧¬∃z a=mover(x,z)),Libre(x,do(a,s))↔∃y (Sobre(y,x,s)∧(∃z (a=mover(y,z)∧z≠x)∨a=aMesa(y)))∨(Libre(x,s)∧¬∃y a=mover(y,x)).\begin{aligned} \mathsf{Sobre}(x, y, do(a, s)) &\leftrightarrow a = \mathsf{mover}(x, y) \vee \big(\mathsf{Sobre}(x, y, s) \wedge a \neq \mathsf{aMesa}(x) \wedge \neg\exists z\, a = \mathsf{mover}(x, z)\big), \\ \mathsf{EnMesa}(x, do(a, s)) &\leftrightarrow a = \mathsf{aMesa}(x) \vee \big(\mathsf{EnMesa}(x, s) \wedge \neg\exists z\, a = \mathsf{mover}(x, z)\big), \\ \mathsf{Libre}(x, do(a, s)) &\leftrightarrow \exists y\,\big(\mathsf{Sobre}(y, x, s) \wedge (\exists z\,(a = \mathsf{mover}(y, z) \wedge z \neq x) \vee a = \mathsf{aMesa}(y))\big) \vee \big(\mathsf{Libre}(x, s) \wedge \neg\exists y\, a = \mathsf{mover}(y, x)\big). \end{aligned}

For Sobre\mathsf{Sobre}, γ−\gamma^- is strictly a=aMesa(x)∨∃z (a=mover(x,z)∧z≠y)a = \mathsf{aMesa}(x) \vee \exists z\,(a = \mathsf{mover}(x, z) \wedge z \neq y), but condition z≠yz \neq y can be removed: if a=mover(x,y)a = \mathsf{mover}(x, y), the first disjunct already makes the right side true. Condition z≠xz \neq x of Libre\mathsf{Libre}, however, ensures consistency ¬(γ+∧γ−)\neg(\gamma^+ \wedge \gamma^-): without it, moving a block onto its current support would make the support both free and occupied. Preconditions forbid that action, but effect axioms hold for all actions, possible or not.

Successor-state axioms solve the representational problem: FF axioms instead of 2AF2AF, plus one precondition per action. Being equivalences expressing truth in do(a,s)do(a, s) in terms of ss, they give a reasoning method: regression. Rewrite a question about do(an,…do(a1,S0))do(a_n, \dots do(a_1, S_0)) using the axioms, step by step, into one about S0S_0, answered by initial facts. This is exactly what the next cell’s recursive function holds does, and is the mechanism of GOLOG (Levesque et al., 1997), an agent programming language built on situation calculus.

[ ]Situation calculus: effects alone versus successor stateBrowser
BLOQUES = ['A', 'B', 'C']
S0 = ()                                         # una situación es la secuencia de acciones desde S0
def do(a, s): return s + (a,)
INICIAL = {('Sobre', 'C', 'A'), ('EnMesa', 'A'), ('EnMesa', 'B'), ('Libre', 'C'), ('Libre', 'B')}

# ---- axiomas de estado sucesor: la verdad en do(a, s) en función de s (regresión) ----
def holds(f, s):
    if not s: return f in INICIAL
    *pre, a = s; s = tuple(pre)
    if f[0] == 'Sobre':
        x, y = f[1], f[2]
        return a == ('mover', x, y) or (holds(f, s) and a != ('aMesa', x) and not (a[0] == 'mover' and a[1] == x))
    if f[0] == 'EnMesa':
        x = f[1]
        return a == ('aMesa', x) or (holds(f, s) and not (a[0] == 'mover' and a[1] == x))
    if f[0] == 'Libre':
        x = f[1]
        quita = holds(('Sobre', a[1], x), s) and not (a[0] == 'mover' and a[2] == x)   # γ⁺ con z ≠ x
        return quita or (holds(f, s) and not (a[0] == 'mover' and a[2] == x))

def poss(a, s):
    if a[0] == 'mover':
        return a[1] != a[2] and holds(('Libre', a[1]), s) and holds(('Libre', a[2]), s) and not holds(('Sobre', a[1], a[2]), s)
    return holds(('Libre', a[1]), s) and not holds(('EnMesa', a[1]), s)

# ---- solo los ocho axiomas de efecto: True, False o None (la teoría no lo decide) ----
def holds_efectos(f, s):
    if not s: return f in INICIAL
    *pre, a = s; s = tuple(pre)
    t, x = a[0], a[1]
    if f[0] == 'Sobre':
        if a == ('mover', f[1], f[2]): return True
        if f[1] == x: return False                    # x deja de estar sobre lo que estuviera
    if f[0] == 'EnMesa':
        if a == ('aMesa', f[1]): return True
        if t == 'mover' and f[1] == x: return False
    if f[0] == 'Libre':
        if t == 'mover' and f[1] == a[2]: return False
        if holds_efectos(('Sobre', x, f[1]), s): return True   # efecto condicional: lo que estaba debajo de x queda libre
    return None

def fluentes(bloques):
    return [('Sobre', x, y) for x in bloques for y in bloques if x != y] + \
           [('EnMesa', x) for x in bloques] + [('Libre', x) for x in bloques]

plan = [('aMesa', 'C'), ('mover', 'B', 'C'), ('mover', 'A', 'B')]
s = S0
for a in plan:
    print(f"Poss({a}) con estado sucesor: {poss(a, s)!s:5s}", end="   ")
    print(f"¿Libre({a[1]}) solo con efectos?: {holds_efectos(('Libre', a[1]), s)}")
    s = do(a, s)
print("\nen la situación final, con estado sucesor:", sorted(f for f in fluentes(BLOQUES) if holds(f, s)))
desc = [f for f in fluentes(BLOQUES) if holds_efectos(f, s) is None]
print(f"solo con efectos: {len(desc)} de {len(fluentes(BLOQUES))} fluentes sin decidir, entre ellos {desc[:3]}")
print("meta Sobre(A,B) ∧ Sobre(B,C):", holds(('Sobre', 'A', 'B'), s) and holds(('Sobre', 'B', 'C'), s),
      "  solo con efectos, Sobre(B,C):", holds_efectos(('Sobre', 'B', 'C'), s))

print("\n  n   acciones   fluentes   axiomas de marco 2·|A|·|F|   estado sucesor |F|")
for n in (3, 5, 10, 20):
    na, nf = n * (n - 1) + n, n * (n - 1) + 2 * n
    print(f"{n:3d} {na:10d} {nf:10d} {2 * na * nf:28d} {nf:18d}")

With successor state, the three-action plan is executable and reaches the tower AA on BB on CC. With only effect axioms, at the second action the theory does not know whether BB is clear: the precondition is undecided, and at the end 8 of 12 fluents are indeterminate, including Sobre(B,C)\mathsf{Sobre}(B, C), made true by the penultimate action and unmentioned by the last. The final table reproduces the interactive’s count.

The next lesson connects directly. A STRIPS action (Fikes and Nilsson, 1971) is precondition, add and delete lists, with the convention that everything else persists: causal completeness written as data structure, with successor-state axioms its logical semantics. There you will see STRIPS representation and how planners exploit it in heuristic search.

Symbolic versus distributed representations

Everything above is symbolic: every concept is named, every conclusion follows auditable rules. Machine learning’s dominant alternative is distributed representation: every entity and relation is a vector, and knowledge is geometry. Knowledge-graph embeddings are the canonical example. TransE (Bordes et al., 2013) represents a triple (h,r,t)(h, r, t) as true if eh+r≈et\vb{e}_h + \vb{r} \approx \vb{e}_t and learns vectors by minimizing margin loss on observed versus corrupted triples. You will see them in knowledge graphs with graph networks.

The gains are real. Embeddings generalize by similarity: they predict missing links that an open-world ontology leaves “unknown”. They tolerate noise and inconsistencies that explode a classical reasoner, where one contradiction implies everything. And they are learned from data without anyone writing axioms.

So are the losses. There is no logical entailment: an embedding may score a triple contradicting an axiom highly and one inferred from two others poorly. Negation and universal quantification lack natural geometric readings, and there is no way to request “all answers” with completeness guaranteed. Geometric constraints limit representation: if eh+r=et\vb{e}_h + \vb{r} = \vb{e}_t must hold for several distinct tt with the same hh and rr, those tt are forced to one point, so TransE poorly represents one-to-many relations, motivating variants like TransH (Wang et al., 2014). Work seeking both benefits includes geometric embeddings respecting a TBox EL\mathcal{EL} by representing each concept as a region (Kulmanov et al., 2019).

Language models take the question further. Petroni et al. (2019) showed a pretrained model answers factual fill-in-the-blank questions without access to a knowledge base, as if it were one. But that knowledge is implicit: it cannot be queried exhaustively, a fact cannot be updated without side effects (see knowledge editing), and it comes without proof. Systems needing verifiability combine approaches: retrieve from a structured base (GraphRAG), use an ontology to validate model output, or let a symbolic reasoner check conclusions. This topic’s last lesson studies such neurosymbolic patterns.

Common mistakes

Exercises

ProofA subsumption by tableaux
Prove: Use the tableau algorithm to prove ∀R.A⊓∃R.B⊑∃R.(A⊓B)\forall R.A \sqcap \exists R.B \sqsubseteq \exists R.(A \sqcap B) (without a TBox).
0
Subsumption C⊑DC \sqsubseteq D holds if and only if C⊓¬DC \sqcap \neg D is unsatisfiable.

Step 1 of 5. Which concept, already in negation normal form, must the tableau refute?

QuizTranslation to two variables
What is the standard translation πx\pi_x of concept ∃R.(A⊓∀S.B)\exists R.(A \sqcap \forall S.B)?
QuizWhat fits in ALC
Which properties of object xx (or axioms) can be expressed in ALC\mathcal{ALC} as a concept or TBox axiom?

More than one answer may be correct.

CodeNegation normal form with implication and equivalence
Ontology editors permit C→DC \rightarrow D (abbreviating ¬C⊔D\neg C \sqcup D) and C↔DC \leftrightarrow D within concepts. Implement nnf(c) for concepts in the lesson's tuple representation plus two new constructors, ('imp', C, D) and ('iff', C, D). The result must be equivalent, contain neither imp nor iff, and have not only before atoms. Tests check equivalence in random finite interpretations.
def nnf(c):
  """Forma normal de negación de un concepto ALC con abreviaturas 'imp' e 'iff'."""
  k = c[0]
  if k in ('top', 'bot', 'atom'):
      return c
  if k in ('and', 'or'):
      return (k, nnf(c[1]), nnf(c[2]))
  if k in ('some', 'all'):
      return (k, c[1], nnf(c[2]))
  # tu código: 'imp', 'iff' y 'not' (con todos los casos de lo que hay debajo)
  return c
Shift+Enter to run
QuizA diamond with more defaults
Let W={c,r}W = \{c, r\} (Nixon is a Quaker and Republican) and D={c:pp,r:¬p¬p,p:mm,r:¬m¬m}D = \left\{\frac{c : p}{p}, \frac{r : \neg p}{\neg p}, \frac{p : m}{m}, \frac{r : \neg m}{\neg m}\right\}, where pp is ‘pacifist’ and mm ‘protests the war’. Which statement is correct?
QuizUndeclared permissions
TBox: Contratista⊑∀tienePermiso.Lectura\mathsf{Contratista} \sqsubseteq \forall\mathsf{tienePermiso}.\mathsf{Lectura} and Escritura⊑¬Lectura\mathsf{Escritura} \sqsubseteq \neg\mathsf{Lectura}. Facts: Contratista(eva)\mathsf{Contratista}(\mathsf{eva}), tienePermiso(eva,p1)\mathsf{tienePermiso}(\mathsf{eva}, p_1), Lectura(p1)\mathsf{Lectura}(p_1), Escritura(p2)\mathsf{Escritura}(p_2); nothing is known of p3p_3. Questions: (1) are all eva's permissions read-only, (2) does eva have permission p2p_2, (3) does eva have permission p3p_3? What do closed-world (Datalog over facts) and open-world (description logic) systems answer?
QuizWhat OWL 2 RL infers
Ontology: Gato⊑∃come.Pescado\mathsf{Gato} \sqsubseteq \exists\mathsf{come}.\mathsf{Pescado}, Pescado⊑Alimento\mathsf{Pescado} \sqsubseteq \mathsf{Alimento}, Alimentado≡∃come.Alimento\mathsf{Alimentado} \equiv \exists\mathsf{come}.\mathsf{Alimento}, Mascota⊑Gato⊔Perro\mathsf{Mascota} \sqsubseteq \mathsf{Gato} \sqcup \mathsf{Perro}, Perro⊑Alimentado\mathsf{Perro} \sqsubseteq \mathsf{Alimentado}. Facts: Gato(tom)\mathsf{Gato}(\mathsf{tom}), Mascota(rex)\mathsf{Mascota}(\mathsf{rex}), come(fido,salmon)\mathsf{come}(\mathsf{fido}, \mathsf{salmon}), Pescado(salmon)\mathsf{Pescado}(\mathsf{salmon}). Under direct semantics (a DL reasoner), all three individuals are Alimentado\mathsf{Alimentado}. Which triples does owlrl's OWL 2 RL closure materialize?

More than one answer may be correct.

NumericThe cost of frame axioms
Add action pintar(x,c)\mathsf{pintar}(x, c) and fluent Color(x,c,s)\mathsf{Color}(x, c, s) with 3 colors to the blocks world. With n=4n = 4 blocks and counting as in the lesson (two frame axioms per instantiated action–fluent pair, and one successor-state axiom per instantiated fluent), how many times more instantiated axioms does the explicit-frame approach require than successor state?

Summary

Key idea
Knowledge representation chooses a language knowing what can be inferred and at what cost: description logics find a decidable point between Datalog and first-order logic, tableaux decide it by constructing models, and exceptions and change require their own formalisms, default logic and successor-state axioms.
  • A representation is a surrogate for the world, ontological and epistemological commitment, theory of reasoning and computation medium; expressiveness costs complexity (Levesque and Brachman), as the jump from FL−\mathcal{FL}^- to FL\mathcal{FL} shows.
  • Semantic networks and frames contributed inheritance and defaults without semantics; that criticism led to description logics and nonmonotonic reasoning.
  • ALC\mathcal{ALC} is an FO2\mathrm{FO}^2 fragment with TBox and ABox; all problems reduce to satisfiability, PSPACE-complete without a TBox and EXPTIME-complete with a general TBox.
  • Tableaux use NNF with rules ⊓\sqcap, ⊔\sqcup, ∃\exists, ∀\forall, internalize the TBox and use subset blocking to terminate; absorption and other optimizations determine practical performance.
  • OWL 2 is SROIQ\mathcal{SROIQ} over RDF; EL, QL and RL profiles trade expressiveness for cost guarantees. OWL uses open world and assumes no unique names; SPARQL queries the graph under closed world.
  • Default logic defines extensions as fixed points Γ(E)=E\Gamma(E) = E; there may be several (Nixon), with skeptical or credulous conclusions. Circumscription minimizes abnormalities and ASP is the practical tool.
  • Situation calculus describes actions with preconditions and effects; one successor-state axiom per fluent solves the frame problem, provides regression and gives STRIPS semantics.