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:
| Language | Ontological commitment (what exists) | Epistemological commitment (what the agent can believe) |
|---|---|---|
| Propositional logic | facts | true, false, unknown |
| First-order logic | facts, objects, relations | true, false, unknown |
| Temporal logic | facts, objects, relations, times | true, false, unknown |
| Probability theory | facts | degree of belief in |
| Fuzzy logic | facts with degree of truth in | 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 , with conjunction, universal restriction and unqualified existential , deciding whether one concept subsumes another is polynomial. Add just one construction, role restriction (“ successors that are ”), 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.
| Language | What it can say | Problem | Complexity |
|---|---|---|---|
| Propositional Horn clauses | rules without disjunction | satisfiability | linear (Dowling and Gallier, 1984) |
| Propositional logic | any formula | satisfiability | NP-complete |
| Datalog | rules with variables, no functions | entailment | P in data; EXPTIME-complete combined |
| (OWL 2 EL profile) | , , general TBox | subsumption | P |
| additionally , , | satisfiability without / with TBox | PSPACE / EXPTIME-complete | |
| (OWL 2 DL) | additionally inverse and transitive roles, cardinalities, nominals | satisfiability | N2EXPTIME-complete (Kazakov, 2008) |
| First-order logic | all the above and more | validity | undecidable (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 (, ), denoting sets of objects; role names (, ), denoting binary relations; and individual names (). Constructors form complex concepts. The base logic is (Schmidt-Schauß and Smolka, 1991); others are named for their additions.
These are familiar set operations plus two quantifiers over relations. Read as “those running some web service” and as “those running nothing public”. Notice the empty case: an object with no successor belongs to for any , and to no .
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 :
- Satisfiability: is there a model of with ? An unsatisfiable ontology concept is almost always a modeling error.
- Subsumption: if in every model of . Classifying an ontology computes all subsumptions between concept names.
- Consistency of : does it have a model?
- Instance checking: if in every model of .
All reduce to one because has negation:
The first equivalence is familiar: if and only if . 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 . Atomic and Boolean cases are first-order semantic definitions. For : if and only if some satisfies and , which by induction (applied to , with as its only free variable) is ; that is exactly . Case is symmetric. The only variables are and : each quantifier binds the variable not currently free, and the name reused inside is no longer needed outside.
∎For example, : inner is another bound variable reusing the name. This has fundamental consequences. is decidable (Mortimer, 1975) and satisfiability is NEXPTIME-complete (Grädel, Kolaitis and Vardi, 1997), so is decidable without its own algorithm. Translation also shows what cannot say: “ is transitive” or “ has at least two distinct successors” need three variables; “ is the successor of some ”, , is in but not because it follows the role backward (the inverse role, I in the names below). Schild (1991) also observed is a notational variant of multimodal logic : is and is . 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 .
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 uses three nested quantifiers and still has only and . The final check proves nothing (300 five-element interpretations are not all interpretations), but is useful: mistakes in De Morgan rules or duality appear quickly. The code exercise tests use the same technique.
The tableau algorithm
To decide whether is satisfiable, tableaux try to build a model. Start with object required to belong to and apply rules making requirements explicit: if is in , it is in and ; if in , it needs an successor in ; 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 successor is in if and only if every successor is outside . With concepts in NNF, the algorithm works on a completion tree: nodes with a label , a set of concepts must satisfy, and role-labeled edges.
| Rule | Condition | Action |
|---|---|---|
| and | add and to | |
| and | branch: add in one branch and in the other | |
| , unblocked and no successor has | create fresh successor with | |
| , is an successor of and | add to |
A node has a clash if its label contains or a pair . 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 says every object is in . Add to every node label, including those created by rule . This is TBox internalization. It is costly: each axiom introduces a disjunction at each node, and with axioms a node may have combinations to explore.
A more serious problem appears: nontermination. With , concept requires an successor in , which by the axiom requires another, indefinitely. A model exists (an cycle suffices), but rule builds an infinite chain.
The idea: requires nothing does not already require, so the model can “reuse” ‘s successors: the edge to is redirected to , turning the tree into a finite cyclic graph. The builder below reproduces this step by step.
In the initial example, , the algorithm creates two successors, one with and one with , and passes the disjunction to both. In the first, branch clashes with and must be tried; in the second, works immediately. The final tree is a three-element model. With the cyclic TBox, successor gets exactly what 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 , the web server requires an successor, the axiom makes it and adds : clash without exploring disjunctions.
Soundness, completeness and termination
Proof
Let be the set of subconcepts of and , of size linear in the input. All labels are subsets of because each rule adds a subconcept of something already present.
Termination. Each node has at most successors (one per concept of ) 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 subsets of : depth is bounded by and the tree finite. Each rule grows it, so cannot apply indefinitely.
A complete clash-free tree gives a model. Define with domain nodes neither blocked nor descendants of blocked nodes, and if is an unblocked successor of , or if has an successor blocked by . Induction on proves implies . For it is the definition; for , no clash gives and ; and follow from label completeness. For : rule is inapplicable, so an successor has ; if is unblocked it works; if blocked by , then and . For : every successor of is an successor with by rule , or its blocker with . Since is in all labels, models , and .
A model gives an execution without clashes. Let model with . Maintain a mapping from nodes to the domain of with for all and if is an successor of . Each rule preserves it: in choose a disjunct satisfied by ; in map the new node to a witness of ; and are immediate, and holds for every element because models . A label containing and or 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 application reduces quantifier depth of the new node’s concept and tree depth is bounded by .
Complexity and optimizations
Without a TBox, satisfiability of 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 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 , 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 with a name on the left need not be internalized: add to nodes containing . An axiom rewrites without meaning change as . A disjunction per node becomes one only in nodes containing .
- Dependency-directed backtracking. Each concept remembers the 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 , 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 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 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 is defined as nodes whose labels contain . If , the lazy rule has added to , and the proof’s lemma gives : axiom holds without internalization. It is not enough, however, to handle definition by unfolding toward and toward : a node satisfying without containing either or would remain outside and violate in the constructed model. Thus the definition becomes two inclusions, and direction is absorbed or internalized.
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: distributes over but not (two successors, one in and another in , do not yield one in ). 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.
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: (every web server runs a web service, which is public, and is an asset) and , requiring case analysis: the control is a WAF or segmentation, both an . It detects 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 is ), 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 serialized in the same graph: owl:someValuesFrom is , owl:allValuesFrom is , owl:unionOf is , owl:complementOf is . 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):
| Profile | Basis | Guarantee | Intended for |
|---|---|---|---|
| OWL 2 EL | : , , without or | polynomial-time reasoning in ontology size (PTIME-complete) | huge terminologies: SNOMED CT |
| OWL 2 QL | DL-Lite | query answering in AC⁰ (LOGSPACE) in data size, by rewriting to SQL | ontologies over relational databases |
| OWL 2 RL | rules | polynomial-time rule application, implementable in a rule engine | reasoning 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 , 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.
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: guarantees one exists, even without knowing which. The open world can know something exists without naming it.
- Yes versus unknown in . 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 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 , axiom and , the ontology concludes carla does not have that permission. 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, and 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.
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"]))npm run lab and open the connection link.The comparison precisely separates what RL captures from what it does not:
- They agree on and . RL inferring is less obvious than it seems: rule
scm-svf1concludes that restriction “runs some ” is a subclass of “runs some ” because , thencls-int1recognizes the intersection in the individual. RL cannot create the anonymous web service, but can reason about restrictions as classes. - They differ on : inferring it is protected requires reasoning by cases over union within an existential in a superclass, precisely what RL’s grammar excludes.
- They differ on for a distinct practical reason: the universal restriction of its assertion and that in ‘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 () but not the two tableau subsumptions because no rule concludes a class is contained in an intersection, and it does not detect is empty. RL materializes individual facts; classifying an expressive TBox needs a DL reasoner.
- Conversely, RL concludes
ana owl:sameAs agarciabecausetieneResponsableis functional. 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 EXISTSquery lists all four assets as “without control”, including , which the reasoner knows is protected by some control. The query asks about triples, not models.
Nonmonotonic reasoning
Classical logic is monotone: if , then for any . 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 , 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 for subsets , which this section’s cell brute-forces.
Three properties characterize behavior:
- There may be no extension. has none: if , justification is inconsistent with and ; if , the default applies and .
- 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 -complete and skeptical -complete (Gottlob, 1992), one step above SAT in the polynomial hierarchy.
The figure shows three phenomena the theory must explain. First, nonmonotonicity: with the strict exception, learning pingu is a penguin withdraws and , which was in the extension without that fact. The second is surprising but correct: with “penguins do not fly” in and concluded by default, classical logic deduces by contraposition that it is not a penguin. Extensions are closed under , 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 ), 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.
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: 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,
and circumscription of in theory is the second-order formula
where means and : the theory cannot be satisfied with fewer abnormalities. Its models are models of with minimal (letting vary). If only is known, the minimal model has empty and Tweety flies; add and 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 , 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 with default , where is the complementary literal. A normal default is written vuela(X) :- ave(X), not -vuela(X)., and clingo directly computes credulous (--enum-mode=brave) and skeptical (--enum-mode=cautious) consequences.
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))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 , 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 , not formula in . 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. is initial and results from doing in . A situation is not a state: and differ even if the world ends identically.
- Actions: terms such as (put block on ) or .
- Fluents: relations whose truth depends on the situation, with situation as last argument: , , .
Preconditions say when an action is possible:
Effect axioms say what changes. In the blocks world eight suffice, four positive and four negative:
The frame problem
With only this, start at with on and and on the table, and do . Effect axioms say is on the table, no longer on , and is clear. Is 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.
The direct solution is frame axioms: for each action and unaffected fluent, one axiom preserving truth and another falsity, such as . With actions and fluents, on the order of are needed (Reiter, 1991). Our domain needs schemas plus 8 effect axioms, and instantiated for blocks ( actions and fluents), : 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 in normal form:
where disjoins all conditions under which an action makes true, and those making it false. For , for example, and . Causal completeness says these are all ways to change : if changes false to true, held, and if true to false, held. These are Schubert’s explanatory closure axioms. Combining effects with closure and assuming and cannot both hold yields one equivalence per fluent:
Proof
() If holds, the positive effect axiom gives . If and hold and were false in , negative explanatory closure would give : contradiction. () Suppose and . Positive explanatory closure gives , so . If held, the negative effect axiom would give ; therefore . Conversely the successor-state axiom directly implies effect and closure axioms using consistency.
∎Read as a sentence: is true after if made it true, or it already was true and 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:
For , is strictly , but condition can be removed: if , the first disjunct already makes the right side true. Condition of , however, ensures consistency : 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: axioms instead of , plus one precondition per action. Being equivalences expressing truth in in terms of , they give a reasoning method: regression. Rewrite a question about using the axioms, step by step, into one about , 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.
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 on on . With only effect axioms, at the second action the theory does not know whether is clear: the precondition is undecided, and at the end 8 of 12 fluents are indeterminate, including , 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 as true if 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 must hold for several distinct with the same and , those 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 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
Step 1 of 5. Which concept, already in negation normal form, must the tableau refute?
More than one answer may be correct.
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 cMore than one answer may be correct.
Summary
- 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 to shows.
- Semantic networks and frames contributed inheritance and defaults without semantics; that criticism led to description logics and nonmonotonic reasoning.
- is an 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 , , , , internalize the TBox and use subset blocking to terminate; absorption and other optimizations determine practical performance.
- OWL 2 is 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 ; 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.