First-order inference: unification and resolution
From knowledge-based agents to automated theorem proving. Starting with first-order semantics, reduce logical consequence to refutation through clausal form and Skolemization, Herbrand’s theorem, unification and resolution with refutational completeness, and the given-clause loop used by modern provers such as Vampire and E.
After this lesson you can
- Describe a knowledge-based agent architecture and logical consequence as a decision mechanism.
- Convert first-order formulas to clausal form with Skolemization.
- Implement unification with an occurs check and resolution with factoring.
- Explain Herbrand’s theorem and the semidecidability of first-order logic.
- Build a prover with the given-clause loop and compare selection strategies.
Before you start
- 10SAT preprocessing: subsumption and bounded variable elimination
- 01ResolutionRefutational completeness of resolutionDPLL algorithmConjunctive and disjunctive normal formsFirst-order syntaxTarskian semanticsQuantifier laws and prenex formSoundness and completenessHalting problemDecidable and semidecidable languages
Motivation: an agent that decides by proving
Earlier lessons in this topic solved problems whose structure was fixed in advance: a state graph, a game tree, a finite set of variables with domains. This lesson asks a different question. A system has knowledge written as formulas (access-control rules, simplified physics of a video game, axioms of a mathematical theory) and wants to know whether something follows from it. We are not looking for a path or assignment: we are looking for a proof.
The classic architecture is the knowledge-based agent (Russell and Norvig, chapter 7). It has a knowledge base , a set of formulas, and two operations:
- adds formula : a domain rule or percept (“square is breezy”).
- asks whether is a logical consequence of the base, : whether is true in every model of .
At each instant the agent performs with what it perceives, about a useful action (“is square safe?”), and acts on the answer. The separation matters: knowledge is declarative and the decision mechanism is general. Changing behavior means changing formulas, not code. The idea reappears in expert systems, Prolog, ontologies and, with another engine, the previous lesson’s program verifiers.
AIMA’s testbed is the wumpus world: a cave of squares with pits and a monster. The agent sees nothing; it perceives a breeze if a neighboring square has a pit and a stench if the wumpus is in a neighbor. World rules are formulas, for example
and “may I step on ?” is . In a finite cave the answer can be computed by model checking: enumerate all worlds compatible with the percepts and see whether holds in all. This is AIMA’s example after two percepts: no breeze at , breeze at .
from itertools import product
# El mundo de wumpus de AIMA tras dos percepciones: sin brisa en (1,1), brisa en (2,1).
# Variables: P[c] = hay pozo en la casilla c. Solo importan las casillas de la frontera.
frontera = [(1, 2), (2, 2), (3, 1)]
vecinas = {(1, 1): [(1, 2), (2, 1)], (2, 1): [(1, 1), (2, 2), (3, 1)]}
def kb(P):
brisa = lambda c: any(P.get(v, False) for v in vecinas[c])
# TELL: reglas de la brisa en las dos casillas visitadas + percepciones + (1,1) y (2,1) sin pozo
return (not brisa((1, 1))) and brisa((2, 1))
modelos = []
for valores in product([False, True], repeat=len(frontera)):
P = dict(zip(frontera, valores))
if kb(P):
modelos.append(P)
print(f"{2 ** len(frontera)} mundos posibles, {len(modelos)} modelos de KB:")
for P in modelos:
print(" pozos en", [c for c in frontera if P[c]])
def ask(alfa):
"""KB |= alfa si y solo si alfa es cierta en todos los modelos de KB."""
return all(alfa(P) for P in modelos)
print("KB |= ¬P(1,2):", ask(lambda P: not P[(1, 2)]))
print("KB |= ¬P(2,2):", ask(lambda P: not P[(2, 2)]), " KB |= P(2,2):", ask(lambda P: P[(2, 2)]))
print("KB |= P(2,2) ∨ P(3,1):", ask(lambda P: P[(2, 2)] or P[(3, 1)]))Of 8 possible worlds, 3 models remain. In all three is clear, so ; neither nor follows, because the base does not know where the pit causing the breeze is, though it knows it is at or .
If you continue with the logical agent, eventually no frontier square is guaranteed safe: logic does not decide which risk is smaller, and the agent gets stuck. Probability handles that limit (AIMA devotes chapter 12 to the same world). But there is an earlier, more serious problem: model checking works only when models can be enumerated. With infinite domains (natural numbers, lists, program states) or simply large ones, enumeration is impossible. We need a syntactic procedure manipulating first-order formulas and guaranteed by semantics: sound (what it derives follows) and complete (it derives everything that follows). Propositional logic already provides it: resolution and its refutational completeness. This lesson lifts it to first order.
Entailment as refutation
The first step turns “does follow?” into “is this set contradictory?”.
Proof
If and were a model of , then because it models and : impossible. Conversely, if has no models, every model of makes false, that is, true.
∎A refutation prover therefore negates the conjecture, adds it to the axioms and seeks an explicit contradiction: the empty clause . The rest of the lesson builds the pieces: turn formulas into clauses, understand why looking at “instances” suffices (Herbrand), find suitable instances without guessing (unification), combine them (resolution) and organize the search (the given-clause loop).
From formulas to clauses
Resolution works on clauses: disjunctions of literals, with all variables implicitly universally quantified. A clause like means . A set of clauses is read as their conjunction. Getting there from any formula takes five steps.
- Eliminate and : becomes .
- Negation normal form (NNF): push negations to atoms using De Morgan and the quantifier laws and .
- Rename bound variables so each quantifier has its own.
- Skolemize: eliminate each by replacing its variable with a new term.
- Conjunctive normal form: remove (now implicit) and distribute over , as in propositional CNF.
Steps 1 through 3 and 5 produce equivalent formulas. Step 4 does not, and is the interesting one.
Skolemization
In (“everyone has someone who loves them”), the that exists depends on . If we name that dependency with a new function symbol , “the one who loves ”, formula has no existential quantifiers.
The proof is short and you will reconstruct it in the guided exercise at the end: in one direction the Skolem term is a witness; in the other, interpret as a function choosing a witness for each value of (the axiom of choice if the domain is infinite). Lack of equivalence is no obstacle: the refutation theorem asks only whether is unsatisfiable, which Skolemization preserves. What matters is negating before Skolemizing: existential quantifiers in the conjecture become universal when negated.
Take the first sentence of the AIMA problem used as an example: “anyone who loves all animals is loved by someone”.
To fit the formulas, abbreviate as and as .
is “an animal that does not love” (if one exists) and is “someone who loves ”. The lab’s clausal-form cell does exactly this and returns the same two clauses, with and named sk2 and sk3; when the loop cell clausifies the problem again, they are named sk14 and sk15 because the fresh-name counter is global. Those are the names in the interactives.
Step 5 has a known trap: distribution can multiply size. produces clauses. Real clausifiers name subformulas with new predicates, the same idea as Tseitin encoding in SAT, obtaining linear size while again preserving only satisfiability (Nonnengart and Weidenbach, Computing small clause normal forms, in the Handbook of Automated Reasoning, 2001). They then apply simplifications like SAT preprocessing: remove tautologies, subsumed clauses and pure literals.
The Herbrand universe: reducing to infinitely many propositional problems
We have a set of clauses and want to know whether it is unsatisfiable. By definition we must check that no structure satisfies it, and structures are infinite in number and can have domains of any size. Jacques Herbrand (1930 thesis) observed that a very specific kind of structure, built from the syntax itself, suffices.
A Herbrand interpretation is thus a propositional valuation of ground atoms. With the chain , , , the universe is , and ground instances of the second clause are , , and so on.
Proof
A Herbrand model is a model. Conversely, let . Define the Herbrand interpretation making a ground atom true exactly when (evaluating its ground terms in ). Take a clause with variables and an assignment of ground terms to those variables. Since satisfies , it particularly satisfies instance (with values ), so some literal of that instance is true in , and by construction also in . Since the domain of is exactly , this says .
∎The proof uses two things worth noticing: clauses are universal (hence Skolemization was needed) and there is no equality (with , atom could be true in and the Herbrand interpretation, treating and as distinct terms, would not respect it; quotienting by a congruence fixes this, as the equality calculi below do).
Proof
Let be the set of all ground instances of over . A Herbrand interpretation satisfies if and only if, viewed as a valuation of the base, it satisfies all propositional clauses of : the final line of the preceding proof. By the previous theorem, is unsatisfiable if and only if it has no Herbrand model, that is, if and only if is propositionally unsatisfiable. By the compactness theorem of propositional logic (a possibly infinite set is unsatisfiable if and only if some finite subset is), this occurs if and only if some finite subset of is unsatisfiable.
∎This is Herbrand’s theorem in the form used by provers. It suggests an immediate procedure, proposed by Gilmore (1960) and, with a much better propositional algorithm, Davis and Putnam (1960), the direct predecessor of DPLL: for , generate all ground instances over and pass them to a propositional solver; if they are ever unsatisfiable, stop.
Semidecidability
Gilmore’s procedure terminates with “unsatisfiable” exactly when is unsatisfiable. If is satisfiable and has a function symbol, the universe is infinite, every level is satisfiable and the procedure never stops. This proves part of a central result:
Semidecidability is what you just saw: clausify and saturate by levels. Undecidability is the undecidability of first-order logic seen in computability, by reduction from the halting problem. The practical consequence is that a first-order prover cannot guarantee termination on a false conjecture: silence means nothing. There are decidable islands. The most useful is the Bernays–Schönfinkel class (prefix , no functions), which after Skolemization has no functions, has a finite Herbrand universe, and is the EPR class recognized and decided by provers, as in the figure’s “no functions” example.
Gilmore quickly bogs down, as the figure shows: Schubert’s steamroller, a lab problem, needs 23,742 ground instances at level 1, while resolution proves it by generating 215 clauses. The flaw is fundamental: the procedure guesses terms (all of ) instead of calculating which are needed. In AIMA, only 8 of the 768 level-1 instances are needed, and they contain very specific terms, such as or . Robinson’s idea (1965) was never to instantiate more than needed: defer term choice until an inference needs it, then choose the most general possible instance. That operation is unification.
Unification
and have many unifiers: is one; is most general, and the former is obtained by composing it with . The mgu is unique up to variable renaming. Unification calculates that mgu or establishes that none exists.
The Martelli–Montanari algorithm
Robinson gave the first algorithm in 1965, recursive on terms. Martelli and Montanari (1982) reformulated it as a system of rules on an equation set transformed until in solved form , with distinct and none appearing in any . That solved form, read as a substitution, is the mgu. There are six rules:
| Rule | If contains | Replace with |
|---|---|---|
| Delete trivial | nothing | |
| Decompose | ||
| Conflict | with or different arities | failure |
| Orient | with not a variable | |
| Occurs | with in and | failure |
| Eliminate variable | with not in and in the rest of | and in the rest |
Proof
The rules preserve unifiers. Call the set of substitutions unifying every equation in . Delete trivial, decompose and orient do not change it, since is equivalent to for every . Nor does variable elimination: if , then for every term , so unifies the rest before substitution if and only if it does afterward. Conflict rightly fails because terms with different heads cannot be made equal by any substitution. So does occurs: if occurs strictly inside , the size of exceeds that of for every .
Termination. Associate with the triple : number of unsolved variables (those appearing in without being left side of a solved equation), total symbol count of and number of equations with not a variable. Variable elimination solves and creates no new variables: it reduces . Decomposition and trivial deletion add no variables and remove symbols: they reduce without increasing . Orientation leaves and equal and reduces . Lexicographic order on is well founded.
The result is an mgu. When no rule applies and there is no failure, is in solved form and unifies it ( do not appear in ). If , then , and for other variables : hence . Since , is more general than any unifier of and .
∎The occurs check
The occurs rule is most often forgotten and causes most damage. Without it, is “solved” with , meaningful only if is the infinite term . Worse, it produces false proofs. Clauses and are jointly satisfiable (in the naturals, with equality and successor: every number equals itself and none equals its successor). Without an occurs check, and “unify” by accepting cyclic binding , and resolution derives : an unsound prover. The lab’s unification cell and the interactive below show this with “p(X, X) and p(Y, f(Y))”.
Prolog omits the check by default for efficiency: unifying a variable with a term takes constant instead of linear time. The ISO standard offers unify_with_occurs_check/2 to those needing it, and serious provers, which cannot afford incorrect answers, always perform it.
Cost
The naive recursive algorithm can take exponential time. The classic example is
whose mgu binds to a complete tree of depth with nodes. If terms are represented as trees, merely writing the result is exponential. With directed acyclic graphs sharing subterms, the same result uses nodes: the figure’s “distinct subterms” reading shows this. Paterson and Wegman (1978) gave a linear-time algorithm over that representation, and Martelli and Montanari a practically efficient one based on multiequations. Real provers use shared representations and triangular substitutions (bindings are stored unapplied and followed when read, as in the lab’s unificar), and above all index terms to avoid attempting unifications that will fail.
First-order resolution
With unification, the propositional resolution rule lifts without changing form.
First-order resolution is the calculus with those two rules. Robinson formulated one rule unifying several literals from each premise at once; today’s usual presentation separates it into binary resolution and factoring, equivalent and easier to implement.
Proof
Clauses are universally quantified, so also satisfies their instances and , in which . For each variable assignment, either is true and some literal of is true, or it is false and some literal of is true. Factoring is an instance of its premise with two literals merged. has no models.
∎The two conditions in the definition are not details: without either, the calculus ceases to be complete.
- Rename variables. and form an unsatisfiable set (the first says everything satisfies ; the second, nothing of form does). But without separating variables one must unify with , prevented by the occurs check. Renaming the second to , mgu yields in one step. The of one clause and another’s are distinct variables because each clause has its own .
- Factor. is unsatisfiable (the first implies and the second ). But every binary resolvent between two-literal clauses has two literals: never appears. Factoring the first into and the second into produces it in one step. The lab saturates the set without factoring and checks this: it stays with two-literal clauses.
Refutational completeness
The argument has two parts and is the model for almost all completeness proofs in automated deduction.
- Ground level. By Herbrand’s theorem, some finite set of ground instances of is propositionally unsatisfiable. By completeness of propositional resolution, there is a refutation of .
- Lifting lemma. If and are instances of and , and is a propositional resolvent of and , then there is a resolvent of and (perhaps after factoring either) of which is an instance. The reason: the literal resolved upon in comes from one or more literals of made equal by instantiation; a factor of merges them, and the resolution mgu is more general than the substitution producing and , so that substitution factors through it.
Applying the lemma step by step to the ground refutation, from leaves to root, yields a first-order refutation of which the ground one is an instance; and the only clause of which is an instance is . Notice each condition’s role: renaming allows and to be instantiated independently, as at ground level, and factoring is necessary because a ground instance can merge literals distinct in .
There is a delicate moment in the AIMA base. Resolving with and then with produces : the same literal twice, a single literal as a set. This is “trivial” factoring (with the empty unifier), always done when clauses are treated as sets. The result is exactly instance that appeared in the Herbrand core: resolution found on its own the terms Gilmore had to guess.
Strategies and the given-clause loop
Completeness is not efficiency. Brute-force saturation (all resolvents of all pairs, repeatedly) generates enormous amounts of useless clauses. Three families of ideas control this, and all three have completeness traps.
Restrict inferences.
- Set of support (Wos, Robinson and Carson, 1965): divide into axioms and a support (usually the negated conjecture), and forbid resolving two clauses not descended from . If is satisfiable, it remains complete: the contradiction must pass through . This focuses search on the conjecture instead of exploring consequences of axioms.
- Ordered resolution with selection (Bachmair and Ganzinger, in the Handbook of Automated Reasoning, 2001): resolve only on certain literals of each clause. A selection function may choose a negative literal of each clause having one; then that clause resolves only on it, and clauses without negative literals only on maximal literals for a fixed term order. Selecting all negatives gives Robinson’s positive resolution. The lab version selects the heaviest negative literal and leaves all literals of positive clauses eligible (equivalent to an empty order, which only adds inferences relative to any admissible order), and factors only positive clauses. It is complete and prunes heavily: with one selected literal, the steamroller’s 8-literal clause resolves on one instead of eight.
Delete redundancy. A clause is a tautology if it contains and : it adds nothing. Clause subsumes if for some (as literal sets) and has no more literals than : then follows from and is weaker, so it can be deleted. Forward subsumption discards new clauses subsumed by old ones; backward subsumption, old clauses subsumed by a new one. The size condition is not cosmetic: subsumes as a set (with ), its own factor; if allowed, factoring would be useless and completeness lost.
Order the search. This is the given-clause loop.
The loop
The given-clause algorithm, popularized by William McCune’s Otter prover and used with variations by E and Vampire, maintains two lists:
- Processed : clauses that have already made all inferences among themselves.
- Pending : generated clauses not yet involved in any inference.
Initially everything is in (or, with set of support, axioms in and the negated conjecture in ). Each iteration:
- Choose the given clause from using a heuristic.
- If one of subsumes , discard it and return to 1. Otherwise delete from those subsumed by .
- Move to and generate all inferences between and clauses of (including itself), and factors of .
- For each new clause: if , finish with a proof; if a tautology or subsumed by one of , discard it; otherwise add it to .
If empties without , the set is saturated: with a complete calculus this proves satisfiability. The key invariant is that all inferences between clauses in have already been made, avoiding repeated work. There are two variants: in Otter, pending clauses also simplify and subsume new ones; in DISCOUNT (Denzinger, Kronenburg and Schulz, 1997), used by E, pending clauses are passive and only processed ones are used, saving memory and time when grows to millions of clauses. The lab implements the latter.
Selection heuristic. Selecting by age (oldest) is fair: every clause is eventually selected, so with a complete calculus the loop is complete, but searches breadth-first and gets lost. Selecting by weight (symbol count, shortest) pursues small clauses, which approach and subsume the most. With a finite signature it is also theoretically fair, since up to renaming only finitely many clauses have each weight; but that number grows quickly, and a needed heavy clause can wait many iterations. Common practice mixes them: Otter calls it pick_given_ratio, and value 4 selects four by weight and one by age, so the oldest pending clause never waits more than five selections. Vampire adds its limited-resource strategy (Riazanov and Voronkov, 2003): near the time limit it discards clauses it estimates it can no longer process.
The lab quantifies what the figure shows on Schubert’s steamroller (26 clauses, largest with 8 literals). With negative selection, weight finds the proof with 169 given and 215 generated clauses; the 4:1 mix, with 216 and 296; age, with 1030 and 1478. Without selection, with a budget of 1500 generated clauses, none succeeds. The steamroller has a history because unrefined resolution provers stalled on it: Walther (1984) solved it with many-sorted resolution, avoiding inferences between incompatible object classes; Stickel (1986) later collected formulations and solutions, and Pelletier included it as problem 47 in his collection of 75 test problems (1986).
Equality on one page
Nearly all mathematics, and much verification, needs equality. Treating it as another predicate requires adding its axioms: reflexivity, symmetry, transitivity and, for every function and predicate symbol, congruence (, ). It is sound and complete, and disastrous in practice: transitivity and congruences resolve with almost everything.
The alternative is a special rule. Paramodulation (Robinson and Wos, 1969) uses equality to rewrite within another clause: from and , with a subterm unifiable with via , derive . It is still very prolific because it rewrites both directions at any position. Superposition (Bachmair and Ganzinger, 1994) restricts it with a term reduction ordering, such as Knuth–Bendix or lexicographic path ordering: rewrite only a larger term to a smaller one, only in maximal literals and never inside variables. It is complete and at the heart of E, Vampire and SPASS. With it comes demodulation: oriented equalities act as rewrite rules simplifying all clauses, and a unit equality such as eliminates a whole family of clauses at once.
The best-known success is the Robbins conjecture, open since the 1930s: are all Robbins algebras Boolean? McCune’s EQP prover, based on associative and commutative paramodulation, found the proof in 1996 (McCune, Solution of the Robbins problem, Journal of Automated Reasoning, 1997). In the SMT solvers of lesson 13, quantifier-free equality is decided with congruence closure, much cheaper; superposition is needed when equality occurs under quantifiers.
Automated provers and proof assistants
First-order automated provers (Vampire, E, Prover9, SPASS, iProver) receive a problem in a standard format, Sutcliffe’s TPTP, and return a proof or give up. They compete annually in CASC, and all saturation engines use what you just built: clausal form, unification, resolution or superposition, subsumption and a given-clause loop with heuristics, term indexing and, in Vampire, a portfolio of strategies tried in turns with allocated time (Kovács and Voronkov, 2013). Their strength is search: they find lemma combinations in seconds that would take a person time to see. Their limits are semidecidability and combinatorial explosion: they do not reason well by induction, invent auxiliary definitions or handle problems whose proofs are long and conceptual.
Proof assistants (Lean, Isabelle, Coq, now Rocq), seen in discrete mathematics’ proof assistants, reverse the division. A person writes the proof structure and a small kernel checks each step in a much more expressive logic (higher order, dependent types, induction). Automation comes through tactics: simp rewrites, omega decides integer linear arithmetic, aesop searches for proofs, decide evaluates. The bridge is hammers: Isabelle’s Sledgehammer translates the goal and hundreds of relevant lemmas to first order, calls E, Vampire or SMT solvers, and using the list of lemmas used, reconstructs the proof inside Isabelle with Metis, a resolution prover whose inferences the kernel checks. Thus an external program that need not be trusted does the search, and the kernel verifies. Lean 4 tools in the same direction include Duper, a superposition prover producing Lean proof terms.
The current frontier combines both with learning: models choosing the given clause or relevant lemmas, and language models proposing tactics checked by an assistant. You will see this in learning-guided theorem proving in the topic’s last lesson, and language-model-based automated theorem proving. If you keep to this lesson’s Horn part (clauses with one positive literal, like all access-control clauses), the next lesson, logic programming, turns it into a programming language: Prolog’s SLD resolution is resolution with selection on Horn clauses and depth-first search.
Lab: a resolution prover from scratch
We will build all of the above in about four hundred lines of Python: terms and unification, clausal form, resolution with factoring and subsumption, and the given-clause loop. Terms are tuples: a variable is a string beginning with a capital letter ('X') and a compound term or constant is a tuple with the symbol and arguments (('f', 'X', ('a',))).
# Términos como tuplas: una variable es un str que empieza por mayúscula ('X', 'Y1');
# una constante o un término compuesto es una tupla (símbolo, arg1, ..., argn): ('a',), ('f', 'X', ('a',)).
def es_var(t):
return isinstance(t, str)
def resolver(t, s):
"""Sigue la cadena de ligaduras de una variable en la sustitución triangular s."""
while es_var(t) and t in s:
t = s[t]
return t
def aparece(v, t, s):
"""Comprobación de ocurrencia: ¿aparece la variable v en t (bajo s)?"""
t = resolver(t, s)
if es_var(t):
return t == v
return any(aparece(v, a, s) for a in t[1:])
def unificar(a, b, s=None, ocurrencia=True):
"""Extiende s hasta unificar a y b. Devuelve la sustitución (triangular) o None."""
s = dict(s or {})
pendientes = [(a, b)]
while pendientes:
x, y = pendientes.pop()
x, y = resolver(x, s), resolver(y, s)
if x == y:
continue # eliminar ecuación trivial
if es_var(x) or es_var(y):
if not es_var(x):
x, y = y, x # orientar: variable a la izquierda
if ocurrencia and aparece(x, y, s):
return None # X = f(... X ...): no hay unificador
s[x] = y # eliminar variable
elif x[0] != y[0] or len(x) != len(y):
return None # conflicto de símbolos
else:
pendientes.extend(zip(x[1:], y[1:])) # descomponer
return s
def aplicar(t, s):
t = resolver(t, s)
if es_var(t):
return t
return (t[0],) + tuple(aplicar(a, s) for a in t[1:])
def renombrar_t(t, ren):
"""Sustitución simultánea de un solo paso (para renombrar variables: no encadena)."""
if es_var(t):
return ren.get(t, t)
return (t[0],) + tuple(renombrar_t(a, ren) for a in t[1:])
def texto(t):
if es_var(t):
return t
return t[0] if len(t) == 1 else f"{t[0]}({', '.join(texto(a) for a in t[1:])})"
def mgu(a, b, ocurrencia=True):
s = unificar(a, b, ocurrencia=ocurrencia)
if s is None:
return None
return {v: texto(aplicar(v, s)) for v in s} # forma resuelta (idempotente)
t1, t2 = ('f', 'X', ('g', 'Y')), ('f', ('h', 'Z'), ('g', 'X'))
print(texto(t1), "=", texto(t2), " mgu:", mgu(t1, t2))
print("X = f(X):", mgu('X', ('f', 'X')), " sin comprobación:", unificar('X', ('f', 'X'), ocurrencia=False))
# (aplicar esa sustitución a X no termina: X -> f(X) -> f(f(X)) -> ...)
print("f(a, X) = g(Y):", mgu(('f', ('a',), 'X'), ('g', 'Y')))
# Sin comprobación de ocurrencia, una «prueba» falsa: p(X, X) y ¬p(Y, f(Y)) no son contradictorias
# (en los naturales, con p la igualdad y f el sucesor, las dos son ciertas), pero se «unifican».
s = unificar(('p', 'X', 'X'), ('p', 'Y', ('f', 'Y')), ocurrencia=False)
print("p(X,X) frente a p(Y,f(Y)) sin comprobación:", s, " ¿ciclo? Y ->", s.get('Y'))
# Términos que crecen exponencialmente: p(X1..Xn) = p(f(X0,X0), ..., f(X_{n-1},X_{n-1}))
def tam(t):
return 1 if es_var(t) else 1 + sum(tam(a) for a in t[1:])
for n in (5, 10, 15):
izq = ('p',) + tuple(f'X{i}' for i in range(1, n + 1))
der = ('p',) + tuple(('f', f'X{i}', f'X{i}') for i in range(n))
s = unificar(izq, der)
print(f"n = {n:2d}: {len(s)} ligaduras; tamaño de X{n} aplicado: {tam(aplicar(f'X{n}', s))} nodos")unificar is Robinson’s version with triangular substitution: it stores and without composing them, and resolver follows the chain when reading. It is the same logic as Martelli–Montanari (each branch is one of its rules, commented alongside) without the cost of substituting into every equation at every step. The output confirms three things: the example’s mgu binds and to ; without an occurs check is accepted; and in the exponential family there are only bindings, but the applied term has nodes (65535 with ). Triangular representation avoids writing it.
Now clausal form. The parser reads TPTP’s FOF syntax (~, &, |, =>, <=>, ![X]: for all, ?[X]: exists), as real provers do.
import re
# Sintaxis FOF de TPTP: ~ & | => <=>, ![X,Y]: (para todo), ?[X]: (existe).
# Variables en mayúscula; constantes, funciones y predicados en minúscula.
TOKEN = re.compile(r"\s*(<=>|=>|[()\[\],:~&|!?]|[A-Za-z_][A-Za-z0-9_]*)")
def parsear(texto_formula):
tk, pos, s = [], 0, texto_formula.strip()
while pos < len(s):
m = TOKEN.match(s, pos)
if not m:
raise SyntaxError(f"no entiendo {s[pos:pos + 12]!r}")
tk.append(m.group(1))
pos = m.end()
i = 0
def mira():
return tk[i] if i < len(tk) else None
def toma(esperado=None):
nonlocal i
t = tk[i]
if esperado and t != esperado:
raise SyntaxError(f"esperaba {esperado!r} y encontré {t!r}")
i += 1
return t
def termino():
nombre = toma()
if mira() != '(':
return nombre if nombre[0].isupper() else (nombre,)
toma('(')
args = [termino()]
while mira() == ',':
toma(',')
args.append(termino())
toma(')')
return (nombre, *args)
def unitaria():
t = mira()
if t == '~':
toma()
return ('no', unitaria())
if t in ('!', '?'):
toma(); toma('[')
vs = [toma()]
while mira() == ',':
toma(',')
vs.append(toma())
toma(']'); toma(':')
f = unitaria()
for v in reversed(vs):
f = ('todo' if t == '!' else 'existe', v, f)
return f
if t == '(':
toma('(')
f = binaria()
toma(')')
return f
return ('atomo', termino())
def binaria():
f = unitaria()
op = mira()
if op in ('&', '|'):
while mira() == op:
toma()
f = ('y' if op == '&' else 'o', f, unitaria())
elif op in ('=>', '<=>'):
toma()
f = ('implica' if op == '=>' else 'equivale', f, unitaria())
return f
f = binaria()
if i != len(tk):
raise SyntaxError(f"sobra {' '.join(tk[i:])}")
return f
def fnn(f, positiva=True):
"""Forma normal negativa: sin => ni <=>, y negaciones solo delante de átomos."""
k = f[0]
if k == 'atomo':
return f if positiva else ('no', f)
if k == 'no':
return fnn(f[1], not positiva)
if k == 'implica':
return fnn(('o', ('no', f[1]), f[2]), positiva)
if k == 'equivale':
return fnn(('y', ('implica', f[1], f[2]), ('implica', f[2], f[1])), positiva)
if k in ('y', 'o'):
op = k if positiva else {'y': 'o', 'o': 'y'}[k]
return (op, fnn(f[1], positiva), fnn(f[2], positiva))
q = k if positiva else {'todo': 'existe', 'existe': 'todo'}[k] # ¬∀ = ∃¬ y ¬∃ = ∀¬
return (q, f[1], fnn(f[2], positiva))
contador = [0]
def nuevo(prefijo):
contador[0] += 1
return f"{prefijo}{contador[0]}"
def skolemizar(f, universales=(), ren=None):
"""Sobre la FNN: renombra cada variable ligada y cambia cada ∃ por un término de Skolem
cuyos argumentos son las variables universales en cuyo alcance está."""
ren = ren or {}
k = f[0]
if k == 'atomo':
return ('atomo', renombrar_t(f[1], ren))
if k == 'no':
return ('no', skolemizar(f[1], universales, ren))
if k in ('y', 'o'):
return (k, skolemizar(f[1], universales, ren), skolemizar(f[2], universales, ren))
if k == 'todo':
v = nuevo('X')
return skolemizar(f[2], universales + (v,), {**ren, f[1]: v})
termino_skolem = (nuevo('sk'),) + universales # k = 'existe'
return skolemizar(f[2], universales, {**ren, f[1]: termino_skolem})
def fnc(f):
"""Fórmula sin cuantificadores en FNN -> lista de cláusulas (listas de literales (signo, átomo))."""
k = f[0]
if k == 'atomo':
return [[(True, f[1])]]
if k == 'no':
return [[(False, f[1][1])]]
if k == 'y':
return fnc(f[1]) + fnc(f[2])
return [a + b for a in fnc(f[1]) for b in fnc(f[2])] # distributividad de ∨ sobre ∧
def variables(t, acc):
if es_var(t):
if t not in acc:
acc.append(t)
else:
for a in t[1:]:
variables(a, acc)
return acc
def normalizar(literales, s=None):
"""Aplica s, quita literales repetidos, ordena y renombra las variables a V0, V1, ..."""
s = s or {}
clave = lambda l: (texto(l[1]), l[0])
lits = sorted({(sg, aplicar(a, s)) for sg, a in literales}, key=clave)
vs = []
for _, a in lits:
variables(a, vs)
ren = {v: f"V{i}" for i, v in enumerate(vs)}
return tuple(sorted(((sg, renombrar_t(a, ren)) for sg, a in lits), key=clave))
def tautologia(C):
return any((not sg, a) in C for sg, a in C)
def clausular(formula, conjetura=False):
f = parsear(formula)
if conjetura:
f = ('no', f) # refutación: se niega la conjetura
cls = [normalizar(c) for c in fnc(skolemizar(fnn(f)))]
return [c for c in dict.fromkeys(cls) if not tautologia(c)]
def texto_clausula(C):
return ' ∨ '.join(('' if sg else '¬') + texto(a) for sg, a in C) if C else '□'
# El problema de AIMA: ¿mató Curiosidad al gato Tuna?
CURIOSIDAD = [
"![X]: ((![Y]: (animal(Y) => ama(X, Y))) => (?[Y]: ama(Y, X)))", # quien ama a todos los animales es amado por alguien
"![X]: ((?[Z]: (animal(Z) & mata(X, Z))) => (![Y]: ~ama(Y, X)))", # quien mata a un animal no es amado por nadie
"![X]: (animal(X) => ama(jack, X))", # Jack ama a todos los animales
"mata(jack, tuna) | mata(curiosidad, tuna)",
"gato(tuna)",
"![X]: (gato(X) => animal(X))",
]
CONJETURA_CURIOSIDAD = "mata(curiosidad, tuna)"
for f in CURIOSIDAD + [CONJETURA_CURIOSIDAD]:
cls = clausular(f, conjetura=(f == CONJETURA_CURIOSIDAD))
print(f"{f}\n -> " + "\n -> ".join(texto_clausula(c) for c in cls))
# El error típico: Skolem sin argumentos. ∀x ∃y ama(y, x) («todos tienen a alguien que los ama»)
# NO es lo mismo que ama(c, x) («hay uno que ama a todos»).
print("\ncorrecta:", [texto_clausula(c) for c in clausular("![X]: ?[Y]: ama(Y, X)")])
print("otro orden:", [texto_clausula(c) for c in clausular("?[Y]: ![X]: ama(Y, X)")])Skolemization works directly on NNF, without prenex form: it carries the list of universals whose scope contains the current formula, exactly the Skolem term arguments. The first sentence gives the two clauses of the derivation above; the second, , without Skolem functions, because its is in an implication antecedent and becomes universal. The last two lines distinguish quantifier orders: gives a function of ; , a constant.
Now resolution, factoring and subsumption.
def renombrar(C, sufijo):
"""Variables nuevas para C: las de cada cláusula son independientes (separar variables)."""
vs = []
for _, a in C:
variables(a, vs)
ren = {v: v + sufijo for v in vs}
return tuple((sg, renombrar_t(a, ren)) for sg, a in C)
from functools import lru_cache
@lru_cache(maxsize=None)
def elegibles(C, seleccion):
"""Índices de los literales sobre los que se puede resolver. Con selección negativa,
si C tiene literales negativos solo cuenta uno (el de más peso); si no, todos."""
if seleccion:
negativos = [i for i, (sg, _) in enumerate(C) if not sg]
if negativos:
return (max(negativos, key=lambda i: (peso_t(C[i][1]), -i)),)
return tuple(range(len(C)))
def resolventes(C, D, seleccion=False):
"""Todas las resolventes binarias de C y D (D con variables renombradas)."""
pares = [(i, j) for i in elegibles(C, seleccion) for j in elegibles(D, seleccion)
if C[i][0] != D[j][0] and C[i][1][0] == D[j][1][0]] # signos opuestos, mismo predicado
if not pares:
return
D = renombrar(D, "'")
for i, j in pares:
s = unificar(C[i][1], D[j][1])
if s is not None:
yield normalizar(C[:i] + C[i + 1:] + D[:j] + D[j + 1:], s)
def factores(C, seleccion=False):
"""Factores de C: unifica dos literales del mismo signo y quita uno."""
if seleccion and any(not sg for sg, _ in C):
return # con selección solo se factorizan las positivas
for i in range(len(C)):
for j in range(i + 1, len(C)):
(si, ai), (sj, aj) = C[i], C[j]
if si == sj and ai[0] == aj[0]:
s = unificar(ai, aj)
if s is not None:
yield normalizar(C[:j] + C[j + 1:], s)
def encajar(p, t, s):
"""Emparejamiento: liga solo las variables del patrón p; las de t son constantes."""
if es_var(p):
if p in s:
return s if s[p] == t else None
return {**s, p: t}
if es_var(t) or p[0] != t[0] or len(p) != len(t):
return None
for a, b in zip(p[1:], t[1:]):
s = encajar(a, b, s)
if s is None:
return None
return s
@lru_cache(maxsize=None)
def firma(C):
return frozenset((sg, a[0]) for sg, a in C)
def subsume(C, D):
"""C subsume a D si Cσ ⊆ D para alguna σ y C no tiene más literales que D."""
if len(C) > len(D) or not firma(C) <= firma(D):
return False # filtro barato: signos y predicados
def busca(i, s):
if i == len(C):
return True
sc, ac = C[i]
for sd, ad in D:
if sc == sd and ac[0] == ad[0]:
s2 = encajar(ac, ad, s)
if s2 is not None and busca(i + 1, s2):
return True
return False
return busca(0, {})
def peso_t(t):
return 1 if es_var(t) else 1 + sum(peso_t(a) for a in t[1:])
def peso(C):
return sum(peso_t(a) for _, a in C)
cl = lambda s: normalizar([(not l.strip().startswith('~'), parsear(l.strip().lstrip('~'))[1])
for l in s.split('|')])
# 1. Sin renombrar, p(X) y ¬p(f(X)) no resuelven (X = f(X) falla); renombrando, sí.
C, D = cl("p(X)"), cl("~p(f(X))")
print("sin renombrar:", unificar(C[0][1], D[0][1]), " renombrando:", [texto_clausula(r) for r in resolventes(C, D)])
# 2. La factorización es necesaria: {p(X) ∨ p(Y), ¬p(U) ∨ ¬p(V)} es insatisfacible...
A, B = cl("p(X) | p(Y)"), cl("~p(U) | ~p(V)")
def saturar(clausulas, con_factores, maximo=60):
S = list(dict.fromkeys(clausulas))
nuevas = True
while nuevas and len(S) < maximo:
nuevas = False
for C in list(S):
hijos = [R for D in list(S) for R in resolventes(C, D)]
if con_factores:
hijos += list(factores(C))
for R in hijos:
if not tautologia(R) and not any(subsume(E, R) for E in S):
S.append(R); nuevas = True
if not R:
return S
return S
for con in (False, True):
S = saturar([A, B], con)
print(f"factorización={con}: {len(S)} cláusulas, ¿vacía? {() in S}, tamaños {sorted({len(c) for c in S})}")
# 3. Subsunción: p(X) ∨ p(Y) «subsume como conjunto» a su propio factor p(X), pero no cuenta:
print("p(X)∨p(Y) subsume a p(Z)?", subsume(A, cl("p(Z)")), " p(Z) subsume a p(a) ∨ q(b)?", subsume(cl("p(Z)"), cl("p(a) | q(b)")))The three checks reproduce the resolution section’s arguments. Without renaming, and do not unify; renaming yields . Without factoring, saturation of ends with 2 clauses, all two-literal and without : a saturated unsatisfiable set, concrete proof that the calculus without factoring is incomplete. With factoring appears. Subsumption respects the size condition.
The given-clause loop, with three selection heuristics and refinements as options:
import heapq
from collections import Counter
def demostrar(axiomas, negadas, eleccion='peso', proporcion=4, soporte=False, seleccion=True,
subsuncion=True, max_generadas=5000):
"""Bucle de la cláusula dada (variante DISCOUNT). Devuelve (prueba o None, estadísticas, motivo)."""
info = [] # id -> (cláusula, padres)
procesadas = []
por_peso, por_edad, vivas = [], [], set()
st = Counter()
def pendiente(C, padres):
info.append((C, padres)); cid = len(info) - 1
vivas.add(cid)
heapq.heappush(por_peso, (peso(C), cid))
heapq.heappush(por_edad, cid)
for C in axiomas:
if soporte: # conjunto de soporte: los axiomas no se resuelven entre sí
info.append((C, 'axioma')); procesadas.append(len(info) - 1)
else:
pendiente(C, 'axioma')
for C in negadas:
pendiente(C, 'conjetura negada')
n = 0
while vivas:
if st['generadas'] >= max_generadas:
return None, st, 'presupuesto agotado'
por_edad_ahora = eleccion == 'edad' or (eleccion == 'mixta' and n % (proporcion + 1) == proporcion)
cola = por_edad if por_edad_ahora else por_peso
while True:
x = heapq.heappop(cola)
cid = x if por_edad_ahora else x[1]
if cid in vivas:
break
vivas.discard(cid); n += 1
G = info[cid][0]
if subsuncion and any(subsume(info[p][0], G) for p in procesadas):
st['subsumidas'] += 1
continue
st['dadas'] += 1
if subsuncion: # subsunción hacia atrás: G elimina procesadas más débiles
quedan = [p for p in procesadas if not subsume(G, info[p][0])]
st['eliminadas'] += len(procesadas) - len(quedan)
procesadas = quedan
procesadas.append(cid)
hijos = [(F, (cid,)) for F in factores(G, seleccion)]
for p in procesadas:
hijos += [(R, (cid, p)) for R in resolventes(G, info[p][0], seleccion)]
for R, padres in hijos:
st['generadas'] += 1
if not R:
info.append((R, padres))
return (len(info) - 1, info), st, 'refutación'
if tautologia(R):
st['tautologías'] += 1
elif subsuncion and any(subsume(info[p][0], R) for p in procesadas):
st['subsumidas'] += 1
else:
st['retenidas'] += 1
pendiente(R, padres)
return None, st, 'saturado sin cláusula vacía'
def imprimir_prueba(prueba):
cid, info = prueba
usados, pila = [], [cid]
while pila:
c = pila.pop()
if c in usados:
continue
usados.append(c)
if isinstance(info[c][1], tuple):
pila.extend(info[c][1])
for c in sorted(usados):
C, padres = info[c]
origen = padres if isinstance(padres, str) else 'de ' + ', '.join(f'[{p}]' for p in padres)
print(f" [{c}] {texto_clausula(C):55s} {origen}")
return len(usados)
def clausular_problema(axiomas, conjetura):
return [c for f in axiomas for c in clausular(f)], clausular(conjetura, conjetura=True)
ax, neg = clausular_problema(CURIOSIDAD, CONJETURA_CURIOSIDAD)
prueba, st, motivo = demostrar(ax, neg)
print(motivo, dict(st))
print("cláusulas en la prueba:", imprimir_prueba(prueba))
ACCESO = [
"miembro(ana, desarrollo)",
"hereda(desarrollo, plantilla)",
"![U, G, H]: ((miembro(U, G) & hereda(G, H)) => miembro(U, H))",
"![U, G, R]: ((miembro(U, G) & permiso(G, R)) => puede_leer(U, R))",
"![G, R, D]: ((permiso(G, D) & dentro(R, D)) => permiso(G, R))",
"permiso(plantilla, documentos)",
"dentro(informe, documentos)",
]
ax2, neg2 = clausular_problema(ACCESO, "puede_leer(ana, informe)")
prueba, st, motivo = demostrar(ax2, neg2)
print("\ncontrol de accesos:", motivo, dict(st))
print("cláusulas en la prueba:", imprimir_prueba(prueba))
# Sin el permiso de la plantilla la conjetura es falsa y el conjunto se satura
prueba, st, motivo = demostrar([c for c in ax2 if 'plantilla' not in texto_clausula(c) or 'hereda' in texto_clausula(c)], neg2)
print("sin permiso(plantilla, documentos):", motivo, dict(st))The AIMA proof uses 15 clauses: the 8 starting ones and 7 resolvents, the same found by hand in the refutation figure, and the loop finds it generating only 12 clauses. Access control works too: 7 resolvents chain group and permission inheritance. Without fact permiso(plantilla, documentos) the conjecture no longer follows, and as the problem has no functions (not even Skolem functions), the loop saturates: with complete negative selection, this proves the conjecture does not follow.
import time
APISONADORA = [
"![X]: (lobo(X) => animal(X))", "?[X]: lobo(X)",
"![X]: (zorro(X) => animal(X))", "?[X]: zorro(X)",
"![X]: (ave(X) => animal(X))", "?[X]: ave(X)",
"![X]: (oruga(X) => animal(X))", "?[X]: oruga(X)",
"![X]: (caracol(X) => animal(X))", "?[X]: caracol(X)",
"?[X]: grano(X)", "![X]: (grano(X) => planta(X))",
# todo animal come todas las plantas, o come todos los animales mucho menores que él que comen alguna planta
"![X]: (animal(X) => ((![Y]: (planta(Y) => come(X, Y))) | (![Y]: ((animal(Y) & menor(Y, X) & (?[Z]: (planta(Z) & come(Y, Z)))) => come(X, Y)))))",
"![X, Y]: ((ave(Y) & (caracol(X) | oruga(X))) => menor(X, Y))",
"![X, Y]: ((ave(X) & zorro(Y)) => menor(X, Y))",
"![X, Y]: ((zorro(X) & lobo(Y)) => menor(X, Y))",
"![X, Y]: ((lobo(X) & (zorro(Y) | grano(Y))) => ~come(X, Y))",
"![X, Y]: ((ave(X) & oruga(Y)) => come(X, Y))",
"![X, Y]: ((ave(X) & caracol(Y)) => ~come(X, Y))",
"![X]: ((oruga(X) | caracol(X)) => (?[Y]: (planta(Y) & come(X, Y))))",
]
CONJETURA_APISONADORA = "?[X, Y]: (animal(X) & animal(Y) & (?[Z]: (grano(Z) & come(Y, Z) & come(X, Y))))"
ax3, neg3 = clausular_problema(APISONADORA, CONJETURA_APISONADORA)
print(len(ax3) + len(neg3), "cláusulas; la más larga tiene", max(len(c) for c in ax3), "literales:")
print(" ", texto_clausula(max(ax3, key=len)))
def fila(nombre, eleccion, seleccion, soporte=False, presupuesto=5000):
t0 = time.perf_counter()
prueba, st, motivo = demostrar(ax3, neg3, eleccion=eleccion, seleccion=seleccion, soporte=soporte,
max_generadas=presupuesto)
print(f"{nombre:10s} {eleccion:6s} {'sí' if soporte else 'no':8s} {motivo:28s} "
f"{st['dadas']:6d} {st['generadas']:9d} {st['retenidas']:9d} {st['subsumidas']:10d} {time.perf_counter() - t0:6.2f}")
return prueba
print(f"{'resolución':10s} {'elige':6s} {'soporte':8s} {'resultado':28s} {'dadas':>6s} {'generadas':>9s} {'retenidas':>9s} {'subsumidas':>10s} {'s':>6s}")
for eleccion in ('peso', 'mixta', 'edad'):
fila('selección', eleccion, True)
fila('selección', 'peso', True, soporte=True)
prueba, st, motivo = demostrar(ax3, neg3, eleccion='peso', seleccion=True)
print()
print("la prueba por peso usa", imprimir_prueba(prueba), "cláusulas")The table summarizes the strategies section: 169, 216 and 1030 given clauses for weight, mix and age, and false saturation from combining with set of support. The proof follows a person’s reasoning: the bird eats plants (because it does not eat snails, which are small and eat plants), so it eats grain; the wolf does not eat grain, so it eats every small animal that eats plants, and since it does not eat the fox, the fox does not eat plants; therefore the fox eats small animals that eat plants, including the bird. The fox eats an animal that eats grain.
Without selection, with unrestricted binary resolution, the same budget is exhausted:
for eleccion in ('peso', 'mixta', 'edad'):
fila('binaria', eleccion, False, presupuesto=1500)
# Una conjetura falsa cuyo contraejemplo es infinito: un orden estricto sin máximo, ¿tiene mínimo?
ORDEN = ["![X]: ~r(X, X)", "![X, Y, Z]: ((r(X, Y) & r(Y, Z)) => r(X, Z))", "![X]: ?[Y]: r(X, Y)"]
ax4, neg4 = clausular_problema(ORDEN, "?[X]: ![Y]: ~r(Y, X)")
for presupuesto in (200, 400, 800):
prueba, st, motivo = demostrar(ax4, neg4, max_generadas=presupuesto)
print(f"orden sin mínimo, presupuesto {presupuesto}: {motivo}, {st['dadas']} dadas, {st['retenidas']} retenidas")Binary resolution does not reach the proof with 1500 generated clauses under any of the three choices; by age it generates them with just 49 given clauses, because each produces dozens of resolvents. The last part is the common mistake of expecting the prover to stop. “Every strict order without a maximum has a minimum element” is false (the integers with have no minimum), but all its countermodels are infinite: a strict order without a maximum on a finite set is impossible. The loop generates , , … endlessly, and doubling the budget only increases retained clauses. No budget turns that silence into an answer.
Finally, return to Herbrand with the same pieces: generate levels of , instantiate and pass the instances to a minimal DPLL.
from itertools import product
def firma_de(clausulas):
"""Constantes y funciones (con aridad) que aparecen en los argumentos de los átomos."""
cons, funs = set(), set()
def mira(t):
if es_var(t):
return
(cons if len(t) == 1 else funs).add((t[0], len(t) - 1))
for a in t[1:]:
mira(a)
for C in clausulas:
for _, a in C:
for t in a[1:]:
mira(t)
return sorted(cons) or [('c0', 0)], sorted(funs) # sin constantes, se añade una
def herbrand(clausulas, nivel):
"""H_k: términos cerrados de profundidad <= k."""
cons, funs = firma_de(clausulas)
H = {(c,) for c, _ in cons}
for _ in range(nivel):
H |= {(f,) + args for f, n in funs for args in product(sorted(H), repeat=n)}
return sorted(H, key=lambda t: (len(texto(t)), texto(t)))
def variables_de(C):
vs = []
for _, a in C:
variables(a, vs)
return vs
def instancias(clausulas, H):
out = set()
for C in clausulas:
vs = variables_de(C)
for valores in product(H, repeat=len(vs)):
s = dict(zip(vs, valores))
out.add(frozenset((sg, texto(aplicar(a, s))) for sg, a in C))
return out
def dpll(F):
"""F: conjunto de cláusulas proposicionales (frozensets de (signo, átomo)). ¿Satisfacible?"""
F = set(F)
while True: # propagación unitaria
if frozenset() in F:
return False
unit = next((next(iter(C)) for C in F if len(C) == 1), None)
if unit is None:
break
F = {C - {(not unit[0], unit[1])} for C in F if unit not in C}
if not F:
return True
sg, at = next(iter(next(iter(F))))
return any(dpll(F | {frozenset([(v, at)])}) for v in (True, False))
def gilmore(clausulas, max_nivel=5, max_instancias=20000):
for k in range(max_nivel + 1):
H = herbrand(clausulas, k)
n = sum(len(H) ** len(variables_de(C)) for C in clausulas)
if n > max_instancias:
print(f" nivel {k}: |H| = {len(H)}, harían falta {n} instancias: me paro (¿satisfacible? no lo sé)")
return
sat = dpll(instancias(clausulas, H))
print(f" nivel {k}: |H| = {len(H):4d}, {n:6d} instancias, {'satisfacibles' if sat else 'INSATISFACIBLES'}")
if not sat:
return k
if len(herbrand(clausulas, k + 1)) == len(H):
print(" el universo de Herbrand es finito y ya está entero: el conjunto es satisfacible")
return
problemas = {
"insatisfacible": ["p(a)", "~p(X) | p(f(X))", "~p(f(f(a)))"],
"satisfacible con funciones": ["p(a)", "~p(X) | p(f(X))", "~q(a)"],
"satisfacible sin funciones": ["p(a) | q(b)", "~p(X) | r(X, b)", "~r(a, Y) | ~q(Y)"],
"comprobación de ocurrencia": ["p(X, X)", "~p(Y, f(Y))"],
}
for nombre, cls in problemas.items():
print(nombre + ":")
gilmore([cl(c) for c in cls])
print("curiosidad (AIMA), en forma clausal:")
gilmore(ax + neg)
print("apisonadora de Schubert:")
gilmore(ax3 + neg3, max_instancias=30000)The numbers are those of the Herbrand figure: the chain is refuted at level 1, as is the AIMA base (9 terms, 768 instances), and the steamroller needs 23,742 level-1 instances versus 215 clauses generated by the loop with selection. The “occurs check” set, , is satisfiable at every level: semantic confirmation that produced by unification without checking was false.
Compare with real provers
The next cell writes the same problems in TPTP format and solves them with Vampire or E if installed (find them on each project’s page; neither is distributed by pip), and always with Z3, the SMT solver from lessons 13 and 14, which accepts quantifiers and handles them by instantiation instead of resolution. It adds two false conjectures: one with a finite countermodel and the order without a minimum.
import re, shutil, subprocess, tempfile, time
from pathlib import Path
import z3
ACCESO = [
"miembro(ana, desarrollo)", "hereda(desarrollo, plantilla)",
"![U, G, H]: ((miembro(U, G) & hereda(G, H)) => miembro(U, H))",
"![U, G, R]: ((miembro(U, G) & permiso(G, R)) => puede_leer(U, R))",
"![G, R, D]: ((permiso(G, D) & dentro(R, D)) => permiso(G, R))",
"permiso(plantilla, documentos)", "dentro(informe, documentos)",
]
CURIOSIDAD = [
"![X]: ((![Y]: (animal(Y) => ama(X, Y))) => (?[Y]: ama(Y, X)))",
"![X]: ((?[Z]: (animal(Z) & mata(X, Z))) => (![Y]: ~ama(Y, X)))",
"![X]: (animal(X) => ama(jack, X))",
"mata(jack, tuna) | mata(curiosidad, tuna)", "gato(tuna)", "![X]: (gato(X) => animal(X))",
]
APISONADORA = [
"![X]: (lobo(X) => animal(X))", "?[X]: lobo(X)", "![X]: (zorro(X) => animal(X))", "?[X]: zorro(X)",
"![X]: (ave(X) => animal(X))", "?[X]: ave(X)", "![X]: (oruga(X) => animal(X))", "?[X]: oruga(X)",
"![X]: (caracol(X) => animal(X))", "?[X]: caracol(X)", "?[X]: grano(X)", "![X]: (grano(X) => planta(X))",
"![X]: (animal(X) => ((![Y]: (planta(Y) => come(X, Y))) | (![Y]: ((animal(Y) & menor(Y, X) & (?[Z]: (planta(Z) & come(Y, Z)))) => come(X, Y)))))",
"![X, Y]: ((ave(Y) & (caracol(X) | oruga(X))) => menor(X, Y))",
"![X, Y]: ((ave(X) & zorro(Y)) => menor(X, Y))",
"![X, Y]: ((zorro(X) & lobo(Y)) => menor(X, Y))",
"![X, Y]: ((lobo(X) & (zorro(Y) | grano(Y))) => ~come(X, Y))",
"![X, Y]: ((ave(X) & oruga(Y)) => come(X, Y))",
"![X, Y]: ((ave(X) & caracol(Y)) => ~come(X, Y))",
"![X]: ((oruga(X) | caracol(X)) => (?[Y]: (planta(Y) & come(X, Y))))",
]
PROBLEMAS = {
"acceso": (ACCESO, "puede_leer(ana, informe)"),
"curiosidad": (CURIOSIDAD, "mata(curiosidad, tuna)"),
"apisonadora": (APISONADORA, "?[X, Y]: (animal(X) & animal(Y) & (?[Z]: (grano(Z) & come(Y, Z) & come(X, Y))))"),
"conjetura falsa": (ACCESO, "puede_leer(ana, nominas)"),
# orden estricto sin máximo: solo tiene modelos infinitos. ¿Tiene un elemento mínimo? En N sí, en Z no.
"sin modelo finito": (["![X]: ~r(X, X)", "![X, Y, Z]: ((r(X, Y) & r(Y, Z)) => r(X, Z))", "![X]: ?[Y]: r(X, Y)"],
"?[X]: ![Y]: ~r(Y, X)"),
}
def tptp(axiomas, conjetura):
lineas = [f"fof(a{i}, axiom, {f})." for i, f in enumerate(axiomas)]
return "\n".join(lineas + [f"fof(objetivo, conjecture, {conjetura})."]) + "\n"
# --- De la sintaxis FOF de TPTP a Z3 (un solo tipo U, funciones y predicados no interpretados) ---
U = z3.DeclareSort('U')
def a_z3(texto_formula, simbolos):
tk = re.findall(r"<=>|=>|[()\[\],:~&|!?]|[A-Za-z_][A-Za-z0-9_]*", texto_formula)
pos = [0]
def mira():
return tk[pos[0]] if pos[0] < len(tk) else None
def toma():
pos[0] += 1
return tk[pos[0] - 1]
def termino(ligadas, es_atomo=False):
nombre = toma()
args = []
if mira() == '(':
toma(); args.append(termino(ligadas))
while mira() == ',':
toma(); args.append(termino(ligadas))
toma()
if nombre in ligadas:
return ligadas[nombre]
clave = (nombre, len(args), es_atomo)
if clave not in simbolos:
rango = z3.BoolSort() if es_atomo else U
simbolos[clave] = z3.Function(nombre, *([U] * len(args)), rango) if args else z3.Const(nombre, rango)
f = simbolos[clave]
return f(*args) if args else f
def unitaria(lig):
t = mira()
if t == '~':
toma(); return z3.Not(unitaria(lig))
if t in ('!', '?'):
toma(); toma()
vs = [toma()]
while mira() == ',':
toma(); vs.append(toma())
toma(); toma()
nuevas = {v: z3.Const(f"{v}_{len(simbolos)}_{pos[0]}", U) for v in vs}
cuerpo = unitaria({**lig, **nuevas})
return (z3.ForAll if t == '!' else z3.Exists)(list(nuevas.values()), cuerpo)
if t == '(':
toma(); f = binaria(lig); toma(); return f
return termino(lig, es_atomo=True)
def binaria(lig):
f = unitaria(lig)
op = mira()
if op in ('&', '|'):
partes = [f]
while mira() == op:
toma(); partes.append(unitaria(lig))
return z3.And(partes) if op == '&' else z3.Or(partes)
if op in ('=>', '<=>'):
toma(); g = unitaria(lig)
return z3.Implies(f, g) if op == '=>' else f == g
return f
return binaria({})
carpeta = Path(tempfile.mkdtemp())
externos = {nombre: shutil.which(nombre) for nombre in ("vampire", "eprover")}
print("demostradores externos encontrados:", {k: v for k, v in externos.items() if v} or "ninguno")
for nombre, (axiomas, conjetura) in PROBLEMAS.items():
fichero = carpeta / f"{nombre.replace(' ', '_')}.p"
fichero.write_text(tptp(axiomas, conjetura), encoding="utf-8")
simbolos = {}
s = z3.Solver()
s.set("timeout", 5000)
for f in axiomas:
s.add(a_z3(f, simbolos))
s.add(z3.Not(a_z3(conjetura, simbolos)))
t0 = time.perf_counter()
r = s.check()
dt = time.perf_counter() - t0
est = s.statistics()
inst = est.get_key_value("quant instantiations") if "quant instantiations" in est.keys() else 0
veredicto = {"unsat": "teorema (refutación)", "sat": "no es teorema (hay modelo)"}.get(str(r), str(r))
print(f"{nombre:17s} Z3: {veredicto:28s} {dt * 1000:7.1f} ms instanciaciones de cuantificadores: {inst}")
if str(r) == "sat":
print(" tamaño del universo del contramodelo:", len(s.model().get_universe(U)))
for prog, ruta in externos.items():
if not ruta:
continue
orden = [ruta, "--mode", "casc", "-t", "10", str(fichero)] if prog == "vampire" else \
[ruta, "--auto", "--soft-cpu-limit=10", "-s", str(fichero)]
t0 = time.perf_counter()
salida = subprocess.run(orden, capture_output=True, text=True, timeout=60).stdout
estado = re.search(r"SZS status (\w+)", salida)
print(f" {prog}: {estado.group(1) if estado else '?'} en {time.perf_counter() - t0:.2f} s")
print("\nficheros TPTP en", carpeta)
print(tptp(*PROBLEMAS["acceso"]))npm run lab and open the connection link.In our run (without Vampire or E installed), Z3 refutes all three theorems in milliseconds, with 5, 17 and 339 quantifier instantiations for access control, AIMA and the steamroller; exact numbers depend on the Z3 version. For the false access-control conjecture it finds a finite countermodel of 6 elements: its model-based quantifier instantiation engine (MBQI, lesson 14) builds candidate models and, if they fit, answers “not a theorem”, which our loop only achieves when it saturates. With the order without a minimum it exhausts 5 seconds and returns unknown: there is no finite model to find and no instantiation leads to contradiction. Semidecidability from another engine’s perspective. Compare with your prover: for the steamroller, 339 instances in Z3 versus 215 clauses generated by the loop with selection and 23,742 Gilmore ground instances. If you install Vampire, line SZS status Theorem is the standard TPTP verdict; CounterSatisfiable indicates a false conjecture with a countermodel found.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. How do you prove that if , then ?
Step 1 of 4. Where do you begin?
More than one answer may be correct.
More than one answer may be correct.
unify(t1, t2) using the Martelli–Montanari algorithm: maintain a list of pending equations and an idempotent substitution in solved form (no bound variable appears in values). Return a variable → term dictionary with the most general unifier, or None if none exists. Terms are as in the lab: a variable is a str starting with an uppercase letter and a compound term or constant is a tuple (símbolo, *argumentos). Tests check direct and indirect cycles, shared variables, symbol and arity conflicts, idempotence, and 300 random pairs compared with a reference mgu up to renaming.def es_var(t):
return isinstance(t, str)
def unify(t1, t2):
"""Unificador más general idempotente de t1 y t2, o None."""
E = [(t1, t2)] # ecuaciones pendientes
sigma = {} # sustitución resuelta
# tu código: aplica las reglas (eliminar trivial, orientar, ocurrencia,
# eliminar variable, conflicto, descomponer) hasta vaciar E
return NoneSummary
- A knowledge-based agent separates what it knows (TELL) from how it decides (ASK, logical entailment). Model checking works only for small finite domains; syntactic refutation works whenever the conjecture follows.
- Clausal form uses NNF, renaming, Skolemization (with universals dominating each existential as arguments) and CNF. It preserves satisfiability, not equivalence, so negate the conjecture first.
- Herbrand’s theorem: a clause set is unsatisfiable if and only if some finite set of its ground instances is. This gives a procedure terminating on theorems that may not terminate otherwise: first-order entailment is semidecidable and undecidable.
- Unification computes the mgu or detects none exists. Without the occurs check the prover becomes unsound; with terms as trees the result may be exponential, hence shared subterms.
- Binary resolution plus factoring on clauses with separated variables is sound and refutationally complete (lifting lemma). Omitting renaming or factoring makes it incomplete.
- Real provers use a given-clause loop with refinements (selection, orders, set of support), redundancy deletion (subsumption) and a heuristic mixing weight and age. On the steamroller, selection and weight make the difference between 215 generated clauses and not succeeding with 1500.
- Equality uses superposition, paramodulation restricted by a term order. Proof assistants use these provers as oracles and check their work with a small kernel.