Resolution and DPLL: proving unsatisfiability
How to prove a formula has no solution: the resolution rule, its soundness and refutational completeness, and DPLL, whose failed runs are tree-like resolution refutations. The lesson studies limitations (Haken's exponential pigeonhole bound) and the random 3-SAT phase transition, preparing for CDCL in m10.
After this lesson you can
- Construct resolution refutations and prove their soundness.
- Prove refutational completeness of resolution by induction on the number of variables.
- Implement DPLL with unit propagation, pure literals, and branching heuristics, and prove correctness and termination.
- Extract an independently verifiable resolution certificate from an unsatisfiable run.
- Explain Haken's lower bound and the random 3-SAT phase transition using the first-moment method.
Before you start
Motivation: “no” needs a proof
In the previous lesson you convert a problem to a CNF formula and give it to a SAT solver. If it says “satisfiable,” it gives an assignment you can check in linear time: no trust is needed. But many important questions are answered “no”:
- Circuit equivalence. The miter of an optimized multiplier and the original (the circuit comparing outputs and activating if any differ) is unsatisfiable exactly when both compute the same thing. Here “no” is good news, and must be justified.
- Software and protocol verification. A property holds through depth if the BMC formula seeking a counterexample has no model.
- Mathematics. The Boolean Pythagorean triples problem was settled in 2016 with an unsatisfiable formula and a 200 TB proof.
- Logical consequence. By the definition of consequence, if and only if is unsatisfiable. Every deductive argument is, at heart, a refutation.
When a solver says “unsatisfiable” it cannot show something checked by one evaluation: it claims none of the assignments works. To avoid having to trust it, a proof system is needed: simple, mechanically checkable rules allowing “no” to be written as a chain of verifiable steps. This lesson studies the system used by modern solvers, resolution, and the classical algorithm exploiting it, DPLL. The questions are those for any proof system (the soundness and completeness of natural deduction): does it prove only true things? Does it prove all of them? How long is the shortest proof? The last has an uncomfortable answer: simple formulas such as the pigeonhole principle necessarily have exponential resolution refutations.
The resolution rule
Recall that a clause is a disjunction of literals and a CNF formula is a conjunction of clauses. From here write a clause as the set of its literals and a CNF as the set of its clauses: order and repetition do not change meaning. The clause with no literals, , is the empty disjunction, false under every assignment (it has no literal that could make it true). A clause set containing is therefore unsatisfiable, while the empty clause set is trivially satisfiable.
The rule condenses reasoning by cases. If is true, the second premise forces ; if false, the first forces . Whatever is, one holds. Familiar special cases: from and obtain (modus ponens), from and obtain (transitivity of implication, computed by the 2-SAT graph), and from unit clauses and obtain .
The first claim is the case argument above, which you will work through carefully in the first exercise. The second follows by induction on derivation length: if satisfied , it would satisfy every , in particular , which has no models. Two observations before continuing:
- The resolvent is weaker than the premises. From one cannot recover and : adding the resolvent to does not change models, but removing premises can add models. Resolution always moves toward consequences.
- One pivot only. If and have another complementary pair, and , the resolvent contains : a tautology, always true and useless. Resolving “on both variables at once” to obtain from and would be incorrect: those clauses are satisfied with , .
Notice two things in the figure. First, in the cycle (, implications and ), resolving the first thing seen is not enough: a plan is needed, and some resolvents lead nowhere. Second, resolution is not complete for consequence: from follows , but no resolution produces it because there is nothing to resolve. Refutation is complete: to prove , refute , which is immediate.
Refutational completeness
Does every unsatisfiable formula have a refutation? Yes, and the most direct proof is an algorithm: eliminate variables one by one without losing unsatisfiability. This is the idea of the Davis and Putnam procedure (1960).
no longer mentions , and each clause is in or derived from in one step.
This is the refutational completeness theorem, proved by induction on the number of variables of .
Proof
Assume has no tautologies: removing them does not change models.
Case . The only clause without variables is . Since the empty clause set is satisfiable, , so and the refutation is the one-clause sequence .
Step. Let be unsatisfiable with variables, one of them, and , which has at most variables. Show is unsatisfiable by the contrapositive: if an assignment of the other variables satisfies , it extends to a model of .
- It satisfies , whose clauses do not contain .
- If every clause of has true under , set : all clauses of hold (by their ) and all of hold (by ).
- Otherwise some has false under , so set , satisfying . For each , resolvent is true under . If it is in , because satisfies ; if discarded as tautological, because it contains a pair , , and since is false, is false, is true, and so is . In both cases, since is false, is true and clause holds.
Thus is unsatisfiable and, by induction, has a refutation . Each is in or resolved from two earlier clauses. Those of not in are resolvents of two clauses of : writing those premises first gives a sequence starting only from clauses of and ending in . It refutes .
∎The proof is constructive in both directions, as the figure shows. If is unsatisfiable, eliminating all variables produces and a refutation. If satisfiable, elimination ends with the empty set and the proof’s second point, read backwards, constructs a model: traverse variables in reverse elimination order and set each to 1 only if some clause removed at its step has false. This is the figure’s “saturation,” and why its reconstructed model always passes the check.
DPLL: branch, propagate, backtrack
The alternative of Davis, Logemann, and Loveland (1962) trades memory for time. Instead of eliminating by combining clauses, try both its values: is satisfiable if and only if or is, where is the restriction of by literal : remove clauses containing (already satisfied) and delete from the rest. Generally is restriction by partial assignment , literal by literal. The resulting search is a binary tree of depth at most , pruned by two rules.
The name joins the four authors: Davis and Putnam for propagation and pure-literal rules, already present in the 1960 procedure, and Logemann and Loveland for branching. Each rule’s correctness takes a line to see, and the pure-literal rule is the interesting one:
Proof
Termination. Use the number of free variables as a variant function. Steps 3 and 4 assign a variable and branching calls twice with one fewer free variable, so recursion depth is at most and the tree is finite.
Correctness. By induction on the number of free variables, as in correctness of recursive algorithms, it suffices to see that each step preserves satisfiability of :
- Conflict and success are definitions: has no models and the empty clause set is satisfied by any assignment.
- Propagation. If is a unit clause of , every model of makes true, so and have exactly the same models except for the variable of .
- Pure literal. If models , assignment agreeing with except that it makes true is also a model: clauses with hold, none contains , and the rest do not depend on that variable. Thus is satisfiable if and only if is.
- Branching. Every assignment gives a value, so is satisfiable if and only if one of the two restrictions is.
If a call returns an assignment, it is a model by construction (step 2 is reached only when all clauses are satisfied).
∎The pure-literal rule only preserves satisfiability: and do not have the same models, because the second no longer requires anything of clauses containing . That suffices for decision but not for counting or enumerating models. Unit propagation, by contrast, preserves exactly the models and alone decides some classes: for Horn formulas, if propagation from the empty assignment gives no conflict, setting all remaining free variables to 0 yields a model.
Branching heuristics
Correctness does not depend on the variable chosen in step 5, but tree size does, greatly. Three classical rules, all computed on still-unsatisfied clauses:
- Fixed order: the first free variable, The baseline for assessing the others.
- Most frequent: the variable with most occurrences, in its most frequent polarity. It satisfies many clauses at once and shortens as many others.
- Jeroslow–Wang: the literal maximizing , where is the number of free literals in (in the two-sided version, the variable maximizing , with the polarity of greater ). The weight has a probabilistic reading: a random assignment falsifies a clause of free literals with probability , so prioritizes short clauses, close to becoming unit or empty.
The next section asks what remains of a run ending without a model. The answer turns DPLL into a proof system.
The DPLL tree is a refutation
A DPLL run on an unsatisfiable formula traverses a rooted tree: each node is a call with its incoming partial assignment; each internal node has two children, one per branching-variable polarity; and each leaf is a conflict. The whole tree says “I tried everything,” but checking it would require repeating the search. The next theorem turns it into something checkable step by step.
Proof
Construct bottom-up. Call the assignment of after its own implications (propagations and pure literals), namely extended by them.
Leaves. At a conflict, a clause has all literals false under . Take .
Decisions. If branches on with children assigned and and clauses and : if contains and contains , take , whose literals were all false under (those of except , false under and without variable ; likewise for ). If does not contain , it is already falsified by and we take ; similarly for .
Propagations. Traverse implications of from last to first. If was propagated using reason clause , with false at that time, and current clause contains , replace it by its resolvent with on the variable of , whose literals are those of except and those of , all false without counting . If it does not contain , do nothing.
Pure literals. No resolution is needed here. does not contain , which is true under ; nor can it contain . All clauses of used in the subtree of are conflicts or reasons and were unsatisfied when used; since satisfaction only increases as assignments extend, they were also unsatisfied when the pure-literal rule was applied. Purity of means no unsatisfied clause contained , so none used contains it, and resolution invents no literals: neither does .
After processing implications of , is falsified by , as required. Each resolution uses a child’s clause once: the proof is tree-like.
∎Three consequences of this theorem guide the rest of the lesson.
- A failed run is information. It is false that DPLL “only helps if it finds a model”: its search tree, traversed postorder, is an unsatisfiability proof checkable without repeating the search.
- DPLL is tree-like resolution. The extracted refutation uses each derived clause once (if needed twice, it is derived twice). This restricted system is tree-like resolution, and the refutation has at most DPLL tree size multiplied by : each node contributes one resolution for its decision and, per propagated literal, another with its reason clause. The converse also holds: a tree-like refutation yields a DPLL run with suitable branches and no larger tree. Without learning, DPLL and tree-like resolution have equal power, and any lower bound for the latter applies to the former under any heuristic.
- Propagation order does not matter; the heuristic does. If propagation finds no conflict, the implied-literal set is the same in every order (the unit rule’s least fixed point). If it finds one, any other order also does (every literal implied before conflict lies in that least fixed point), so the tree does not change; which clause becomes empty, and thus the refutation, may vary. Branching-variable choice changes the tree: with 5 pigeons and 4 holes, fixed order needs 103 nodes and Jeroslow–Wang 47.
Self-checking certificates
A modern solver is a program of tens of thousands of lines with aggressive optimizations, and solvers have had bugs. So we do not take “unsatisfiable” on faith: we ask for a certificate. The theorem supplies the idea: while searching, the solver writes deduced clauses, and a much smaller independent checker verifies that each follows from earlier ones and the last is . The standard DRAT format (deletion resolution asymmetric tautology) does not write resolution steps one by one. Each added clause is justified because unit propagation on previous clauses plus conflicts (guaranteeing is derived by resolution, using exactly the resolutions seen in propagation), and the format also has a more general rule justifying preprocessing. SAT competitions have required these certificates for unsatisfiable answers since the mid-2010s, and formally verified checkers exist. See DRAT proofs; this course’s checker below fits in fifteen lines.
Proof complexity: pigeonhole
If every unsatisfiable formula has a refutation, the next question is its size. Proof complexity studies the shortest proof size in a given system as a function of formula size. Its motivation is fundamental: Cook and Reckhow proved in 1979 that a proof system in which every unsatisfiable formula has a polynomial-size refutation checkable in polynomial time exists if and only if (the class of “no” answers with short certificates, coNP). Proving superpolynomial lower bounds for increasingly strong systems is one attack on that question, and resolution was the first natural system to fall.
The pigeonhole formula says pigeons fit in holes without sharing. With variable for “pigeon is in hole ”:
It has variables and clauses: cubic size. It is unsatisfiable by the pigeonhole principle, and the human proof is one line: count occupied (pigeon, hole) pairs; there are at least by the first clauses and at most by the second.
Haken’s proof (1985) was the first exponential lower bound for general resolution (not only tree-like). Beame and Pitassi’s simplified version (1996) rests on three ideas worth knowing even without reproducing the calculations:
- Critical assignments. It suffices to consider assignments placing pigeons in distinct holes and leaving one out, . There are , each falsifying exactly one formula clause, that of pigeon . A correct refutation must “locate” each failure: each critical assignment traverses the refutation from toward the leaves, always through a premise it also falsifies, to its pigeon’s clause.
- Wide clauses. Replacing each with the disjunction of with (equivalent on critical assignments) makes each clause monotone, and every refutation is shown to contain a clause that, transformed this way, mentions on the order of variables: at some point the proof must reason about a constant fraction of pigeons at once.
- Random restrictions. If there were few wide clauses, randomly placing some pigeons in holes would eliminate them all with positive probability, leaving a refutation with no wide clauses of a smaller pigeonhole instance, forbidden by point 2.
The figure’s counts are exact: the DPLL tree on has conflict leaves and nodes (6, 24, 120, …, 362 880 conflicts for ), whereas a random 90-variable formula at the threshold is solved with a few hundred nodes. The explanation is not pigeonhole size but that resolution cannot count: its lines are disjunctions of literals, and the claim “at most of these variables are true,” written this way, needs many clauses. A human reasons with numbers; resolution must reason by cases.
Difficulty depends on the system. In cutting planes (Cook, Coullard, and Turán, 1987), whose lines are linear inequalities with integer coefficients, the counting argument is written directly and pigeonhole has polynomial refutations. In extended resolution, which allows fresh variables defined by formulas (like Tseitin auxiliaries), Cook found polynomial refutations in 1976. In practice encoding matters as much as the system: as seen in problem encoding, breaking hole symmetry puts pigeonhole within reach of unit propagation without a single decision.
Random 3-SAT and the phase transition
Pigeonhole is hard because of its structure. What are “typical” formulas like? The most studied model has fixed clause length.
With few clauses per variable, almost every formula is satisfiable; with many, almost none. The surprising thing is how abrupt the change is. Experiments by Mitchell, Selman, and Levesque (1992) showed that satisfiability probability falls from 100% to 0% in a narrow window around , narrowing as grows, and that DPLL cost peaks sharply in the same window: formulas are easy on the left (almost any path leads to a model), hard at the threshold, and easy again on the right (contradictions appear early). This behavior is the random SAT phase transition.
The first-moment bound
An upper bound on the threshold comes from an expectation calculation. Let be the number of models of . For a fixed assignment , a random clause is falsified exactly when its signs oppose those of , with probability ; since clauses are independent, satisfies the formula with probability . Summing over assignments, by linearity of expectation,
By Markov’s inequality, , which tends to 0 when the base is below 1, namely when
For the ratio is : above it almost no formula is satisfiable. For large , and the bound is .
The bound is far from the observed threshold. Between and , grows exponentially with yet almost no formula has models: the mean is dominated by a few formulas with many (a lottery effect). Refinements of the same method lowered the upper bound to (Díaz, Kirousis, Mitsche and Pérez-Giménez, 2009), and analysis of simple algorithms finding models with high probability gives lower bound (Hajiaghayi and Sorkin, 2003; Kaporis, Kirousis and Lalas, 2006).
What is proved and what is not
- The transition is sharp, proved by Friedgut (1999): for each there is a sequence such that satisfiability probability moves from near 1 to near 0 in a window around it. His theorem does not rule out oscillating with without converging.
- For the threshold exists and is exactly 1 (Chvátal and Reed, 1992; Goerdt, 1996). The first-moment bound is much higher.
- For large , Ding, Sly, and Sun proved the threshold exists and equals the statistical physics prediction , for every above a constant not made explicit in the proof.
- For , value is the statistical physics cavity-method prediction (Mézard, Parisi, and Zecchina, 2002), consistent with all experiments. No proof that the threshold exists is known.
Bridge to CDCL
DPLL has a flaw visible in the refutation theorem: each subtree is forgotten when it closes. If the same cause of conflict appears in two branches, it is rediscovered twice because a tree-like proof cannot reuse a clause. Modern solvers (CDCL, conflict-driven clause learning) fix exactly this:
- On conflict, instead of returning to the last decision, they analyze the conflict: resolve the empty clause backwards with reason clauses of propagated literals until obtaining a clause mentioning only one literal from the last decision level. This is our proof’s propagation step applied selectively (see 1UIP conflict analysis).
- They learn that clause, adding it to the formula for propagation during the rest of the search. A learned clause is reused in many branches, so the resulting proof is a directed acyclic graph rather than a tree: general resolution.
- They jump back several levels at once (nonchronological backjumping), choose variables by recent conflict activity (VSIDS), and occasionally restart search while retaining learned clauses.
The theoretical result is clean: CDCL with restarts polynomially simulates general resolution (Pipatsrisawat and Darwiche, 2011), while DPLL is limited to tree-like resolution, which can be exponentially worse. Conversely, CDCL inherits resolution lower bounds, so pigeonhole remains exponential for any CDCL solver, as measured with PySAT below.
Implementation from scratch
First, Davis–Putnam resolution and elimination, with model reconstruction from the completeness proof. Clauses are frozenset of integers in DIMACS convention ( is 3 and , -3), and the variable eliminated at each step is the one causing the least set growth.
from itertools import combinations
import time
def resolvente(C, D, v):
"""Resolvente de C (contiene v) y D (contiene -v) sobre la variable v."""
assert v in C and -v in D
return frozenset((C - {v}) | (D - {-v}))
def es_tautologia(C):
return any(-l in C for l in C)
def davis_putnam(F):
"""Eliminación de variables. Devuelve (satisfacible, modelo o None, tamaños del conjunto)."""
S = {frozenset(c) for c in F}
S = {C for C in S if not es_tautologia(C)}
pila, tam = [], [len(S)]
while S and frozenset() not in S:
def coste(v): # cuánto crece el conjunto al eliminar v
p = sum(v in C for C in S)
q = sum(-v in C for C in S)
return p * q - p - q
v = min(sorted({abs(l) for C in S for l in C}), key=coste)
P = [C for C in S if v in C]
N = [C for C in S if -v in C]
R = {resolvente(C, D, v) for C in P for D in N}
S = (S - set(P) - set(N)) | {C for C in R if not es_tautologia(C)}
pila.append((v, P))
tam.append(len(S))
if frozenset() in S:
return False, None, tam
val = {} # reconstrucción hacia atrás
verdadero = lambda l: val.get(abs(l), False) == (l > 0)
for v, P in reversed(pila): # v es verdadera solo si alguna C ∨ v lo exige
val[v] = any(not any(verdadero(l) for l in C if abs(l) != v) for C in P)
return True, val, tam
def php(p, h):
"""p palomas en h huecos; la variable de (i, j), desde 0, es i*h + j + 1."""
x = lambda i, j: i * h + j + 1
F = [[x(i, j) for j in range(h)] for i in range(p)]
F += [[-x(a, j), -x(b, j)] for j in range(h) for a, b in combinations(range(p), 2)]
return F
ejemplos = {
"cuatro cláusulas": [[1, 2], [1, -2], [-1, 3], [-1, -3]],
"ciclo": [[1, 2, 3], [-1, 2], [-2, 3], [-3, 1], [-1, -2, -3]],
"palomar 3 en 2": php(3, 2),
"satisfacible": [[1, 2], [-1, 3], [-2, -3], [3, 4], [-1, -4], [-2, 4]],
}
for nombre, F in ejemplos.items():
sat, modelo, tam = davis_putnam(F)
linea = f"{nombre:17s} {'SAT ' if sat else 'UNSAT'} tamaños {tam}"
if sat:
n = max(abs(l) for c in F for l in c)
nu = {v: modelo.get(v, False) for v in range(1, n + 1)}
ok = all(any(nu[abs(l)] == (l > 0) for l in C) for C in F)
linea += f" modelo {[int(nu[v]) for v in nu]}, ¿satisface F? {ok}"
print(linea)
for h in (3, 4):
t0 = time.perf_counter()
sat, _, tam = davis_putnam(php(h + 1, h))
print(f"PHP({h + 1}, {h}): {tam[0]} cláusulas al empezar, máximo {max(tam)} durante la eliminación"
f" ({time.perf_counter() - t0:.2f} s)")In the figure’s four examples, elimination finishes in three to six rounds and reconstructs a valid model in the satisfiable case. Pigeonhole already shows the memory problem: with 5 pigeons the set reaches 113 clauses, more than twice the starting 45 (with 6 pigeons it would grow from 81 to over 2400 and take too long in the browser).
Now DPLL with three rules, three heuristics, and line-by-line extraction of the theorem’s refutation: each node returns the line index whose clause its incoming assignment falsifies. Checker verifica is deliberately independent: it only knows what a resolvent is.
import random
def dpll(F, n, unit=True, pure=False, heur="jw"):
"""Devuelve ("SAT", modelo, estadísticas) o ("UNSAT", refutación, estadísticas).
La refutación es una lista de líneas (cláusula, premisas): premisas None si la cláusula es de F,
o (i, j) si es el resolvente de las líneas i y j. La última línea es la cláusula vacía."""
F = [tuple(sorted(set(c), key=abs)) for c in F]
val = [0] * (n + 1) # 0 libre, 1 verdadera, -1 falsa
valor = lambda l: val[l] if l > 0 else -val[-l]
lineas, de_F = [], {}
est = dict(nodos=0, decisiones=0, propagaciones=0, puros=0, conflictos=0)
def axioma(i):
if i not in de_F:
de_F[i] = len(lineas)
lineas.append((frozenset(F[i]), None))
return de_F[i]
def resuelve(a, b, v):
C, D = lineas[a][0], lineas[b][0]
lineas.append((frozenset((C | D) - {v, -v}), (a, b)))
return len(lineas) - 1
def elige():
puntos = {}
for c in F:
if any(valor(l) == 1 for l in c):
continue
libres = [l for l in c if valor(l) == 0]
for l in libres:
puntos[l] = puntos.get(l, 0.0) + (2.0 ** -len(libres) if heur == "jw" else 1.0)
if heur == "orden":
return min(abs(l) for l in puntos)
v = max(sorted({abs(l) for l in puntos}), key=lambda v: puntos.get(v, 0) + puntos.get(-v, 0))
return v if puntos.get(v, 0) >= puntos.get(-v, 0) else -v
def nodo():
"""Un modelo (lista de literales) o el índice de una línea falsificada por la asignación de llegada."""
est["nodos"] += 1
impl = [] # (literal, cláusula razón, o None si es puro)
try:
while True:
conflicto, unitaria, todas = None, None, True
for i, c in enumerate(F):
if any(valor(l) == 1 for l in c):
continue
todas = False
libres = [l for l in c if valor(l) == 0]
if not libres:
conflicto = i
break
if len(libres) == 1 and unitaria is None:
unitaria = (libres[0], i)
if conflicto is not None:
est["conflictos"] += 1
k = axioma(conflicto)
break
if todas:
return [v if val[v] >= 0 else -v for v in range(1, n + 1)]
if unit and unitaria:
l, i = unitaria
val[abs(l)] = 1 if l > 0 else -1
impl.append((l, i))
est["propagaciones"] += 1
continue
if pure:
signos = {}
for c in F:
if not any(valor(l) == 1 for l in c):
for l in c:
if valor(l) == 0:
signos.setdefault(abs(l), set()).add(l > 0)
puros = [v if s == {True} else -v for v, s in sorted(signos.items()) if len(s) == 1]
if puros:
val[abs(puros[0])] = 1 if puros[0] > 0 else -1
impl.append((puros[0], None))
est["puros"] += 1
continue
l = elige() # ramificación
hijos = []
for b in (l, -l):
est["decisiones"] += 1
val[abs(b)] = 1 if b > 0 else -1
r = nodo()
val[abs(b)] = 0
if isinstance(r, list):
return r
hijos.append(r)
k1, k0 = hijos
if -l in lineas[k1][0] and l in lineas[k0][0]:
k = resuelve(k1, k0, abs(l))
else:
k = k0 if -l in lineas[k1][0] else k1 # la que no menciona la variable
break
for l, i in reversed(impl): # propagaciones, de la última a la primera
if i is not None and -l in lineas[k][0]:
k = resuelve(k, axioma(i), abs(l))
return k
finally:
for l, _ in impl:
val[abs(l)] = 0
r = nodo()
if isinstance(r, list):
return "SAT", r, est
return "UNSAT", poda(lineas, r), est
def poda(lineas, final):
"""Conserva las líneas de las que depende `final` y las renumera; `final` queda la última."""
usadas, pila = set(), [final]
while pila:
i = pila.pop()
if i not in usadas:
usadas.add(i)
if lineas[i][1]:
pila.extend(lineas[i][1])
orden = sorted(usadas)
nuevo = {i: k for k, i in enumerate(orden)}
return [(lineas[i][0], None if lineas[i][1] is None else tuple(nuevo[j] for j in lineas[i][1])) for i in orden]
def verifica(F, prueba):
"""Comprobador independiente: no sabe nada de DPLL, solo qué es un resolvente."""
base = {frozenset(c) for c in F}
for k, (C, prem) in enumerate(prueba):
if prem is None:
assert C in base, f"línea {k}: {set(C)} no está en la fórmula"
continue
i, j = prem
assert i < k and j < k, f"línea {k}: usa líneas posteriores"
A, B = prueba[i][0], prueba[j][0]
piv = [l for l in A if -l in B]
assert len(piv) == 1, f"línea {k}: {len(piv)} pares complementarios"
assert C == (A | B) - {piv[0], -piv[0]}, f"línea {k}: no es el resolvente"
assert prueba[-1][0] == frozenset(), "la última línea no es la cláusula vacía"
return True
def aleatoria(n, m, k=3, semilla=0):
rng = random.Random(semilla)
return [[v if rng.random() < 0.5 else -v for v in rng.sample(range(1, n + 1), k)] for _ in range(m)]
casos = [("PHP(4, 3)", php(4, 3), 12), ("PHP(5, 4)", php(5, 4), 20), ("3-SAT, n = 20, m = 110", aleatoria(20, 110, semilla=3), 20)]
for nombre, F, n in casos:
for unit in (True, False):
res, prueba, est = dpll(F, n, unit=unit)
ok = verifica(F, prueba) if res == "UNSAT" else None
print(f"{nombre:23s} propagación {'sí' if unit else 'no'}: {res}, {est['nodos']:4d} nodos, "
f"{est['conflictos']:3d} conflictos, refutación de {len(prueba):3d} líneas, verificada: {ok}")Unit propagation shrinks the tree by a factor of 8 to 13 in the three cases. The refutation, by contrast, barely changes: with propagation it is longer than its tree (each propagated literal can add a resolution and its reason clause), but even somewhat shorter than without propagation (64 lines versus 69 for PHP(4, 3)). PHP(4, 3)‘s 11 nodes and 64 lines match the interactive, which implements the same algorithm in TypeScript.
With the solver written, compare heuristics and measure pigeonhole growth.
G = aleatoria(25, 130, semilla=11)
print("nodos del árbol según la heurística")
for heur in ("orden", "frecuente", "jw"):
a = dpll(php(5, 4), 20, heur=heur)[2]["nodos"]
r, _, est = dpll(G, 25, heur=heur)
print(f" {heur:10s} PHP(5, 4): {a:4d} 3-SAT con 25 variables ({r}): {est['nodos']:3d}")
print("\npalomar PHP(n + 1, n), propagación unitaria y Jeroslow-Wang")
import math
for h in range(2, 7):
r, prueba, est = dpll(php(h + 1, h), h * (h + 1))
assert verifica(php(h + 1, h), prueba)
print(f" n = {h}: {est['nodos']:5d} nodos = 2·{h}! − 1 = {2 * math.factorial(h) - 1:5d}; "
f"{est['conflictos']:4d} conflictos; refutación de {len(prueba):5d} líneas")Fixed order yields a tree over twice as large as Jeroslow–Wang for pigeonhole and over four times larger for the random formula. Pigeonhole shows its structure: exactly conflicts and nodes. Unit propagation fills each pigeon’s last free hole itself, leaving enumeration of pigeon-to-hole assignments; the refutation grows proportionally, four to five times the tree from onward.
With libraries: sympy and PySAT
Sympy’s satisfiable with algorithm="dpll2" is DPLL with watched literals and clause learning: a small CDCL. Pass it integer-encoded CNF, as in the previous lesson, so it does not reconstruct a symbolic expression.
import time, statistics
from sympy import Symbol
from sympy.logic.inference import satisfiable
from sympy.assumptions.cnf import EncodedCNF
def con_sympy(F, n):
enc = EncodedCNF([set(c) for c in F], {Symbol(f"v{i}"): i for i in range(1, n + 1)})
return satisfiable(enc, algorithm="dpll2") is not False
for h in (4, 5):
F, n = php(h + 1, h), h * (h + 1)
t0 = time.perf_counter(); s = con_sympy(F, n); ts = time.perf_counter() - t0
t0 = time.perf_counter(); r = dpll(F, n)[0]; tn = time.perf_counter() - t0
print(f"PHP({h + 1}, {h}): sympy {'SAT' if s else 'UNSAT'} en {ts:.3f} s; nuestro DPLL {r} en {tn:.3f} s")
n, ts, tn = 50, [], []
for s in range(6):
F = aleatoria(n, round(4.26 * n), semilla=100 + s)
t0 = time.perf_counter(); a = con_sympy(F, n); ts.append(time.perf_counter() - t0)
t0 = time.perf_counter(); b = dpll(F, n)[0]; tn.append(time.perf_counter() - t0)
assert a == (b == "SAT"), "los dos resolvedores discrepan"
print(f"3-SAT con n = {n} en el umbral: mediana sympy {statistics.median(ts) * 1e3:.0f} ms, "
f"nuestro DPLL {statistics.median(tn) * 1e3:.0f} ms (coinciden en las 6 respuestas)")Answers agree and the timing difference is in constants: our DPLL scans all clauses at each step, while sympy uses watched literals, which inspect only clauses affected by each assignment (the trick studied as two watched literals). For pigeonhole, learning does not help: Haken’s bounds apply to any resolution-based method.
PySAT provides access to industrial CDCL solvers and also runs in the browser. Measure conflicts, machine-independent, against the of our DPLL, and solve random formulas of a size our Python DPLL could not handle.
import time, math
from pysat.solvers import Solver
def cdcl(F, nombre="cadical153"):
with Solver(name=nombre, bootstrap_with=F) as s:
t0 = time.perf_counter()
r = s.solve()
return r, s.accum_stats()["conflicts"], time.perf_counter() - t0
print("palomar: conflictos de CDCL frente a los n! de nuestro DPLL")
for h in range(5, 8):
r, c, t = cdcl(php(h + 1, h))
print(f" n = {h:2d}: {'SAT' if r else 'UNSAT'} CaDiCaL {c:7d} conflictos ({t:.2f} s) n! = {math.factorial(h):8d}")
print("\n3-SAT aleatorio en el umbral (α = 4.26) con CaDiCaL")
for n in (100, 150):
filas = [cdcl(aleatoria(n, round(4.26 * n), semilla=7 * n + s)) for s in range(3)]
print(f" n = {n}: " + ", ".join(f"{'SAT' if r else 'UNSAT'} {c} conflictos" for r, c, _ in filas))On pigeonhole, CaDiCaL processes about 25 000 conflicts per second in the browser, five times our Python DPLL on 6 pigeons, but the number of conflicts is of the same order as and grows similarly: with more time, the series continues with 37 288 conflicts for (versus ), 319 668 for , and 2 657 952 for , about five minutes in the browser. Learning turns the tree proof into a general proof, and general resolution remains subject to Haken’s theorem. In random 3-SAT at the threshold, a few hundred variables already cost thousands of conflicts, growing rapidly with (with , up to 13 000; with , hundreds of thousands): random threshold instances are hard for all known solvers. Do not extrapolate in the opposite direction: industrial instances with millions of variables have very different structure (modularity, few variables deciding much) and CDCL often solves them in seconds.
Common mistakes
Exercises
Step 1 of 4. Where do you start?
Step 1 of 4. Base case, . Why is there a refutation?
More than one answer may be correct.
dpll_cert(F, n), where F is a list of clauses (lists of DIMACS integers with variables from 1 to n). If F is satisfiable, return ('SAT', modelo), where modelo is a list of n literals (v or -v) satisfying every clause. Otherwise return ('UNSAT', prueba): a list of lines (clausula, premisas) where premisas is None if the clause is in F, or a pair (i, j) of indices of earlier lines of which it is a resolvent, and whose last clause is empty. Use unit propagation; the heuristic is up to you. Tests check the proof with an independent verifier.def dpll_cert(F, n):
"""('SAT', modelo) o ('UNSAT', prueba) con prueba = [(clausula, premisas), ...]."""
# tu código: propagación unitaria, ramificación y vuelta atrás,
# y en cada nodo la cláusula falsificada por la asignación de llegada
return ('SAT', list(range(1, n + 1)))Summary
- The resolution rule derives, from and , ; it is sound (case analysis on the pivot) and eliminates just one complementary pair.
- It is refutationally complete: eliminating variables one by one (Davis–Putnam) preserves unsatisfiability and ends at ; for a satisfiable formula, reading the same elimination backward constructs a model. Its drawback is size: each elimination can add clauses.
- DPLL branches instead of eliminating, with unit propagation (which preserves models) and pure literals (which preserve only satisfiability). It terminates because each call has one fewer free variable; the branching heuristic (Jeroslow–Wang, most frequent) determines tree size.
- A failed DPLL run is a tree-like refutation: each node carries a clause falsified by its assignment, the root carries , and an independent checker verifies it. This is the idea behind industrial solvers’ DRAT certificates.
- Haken: every refutation of has exponential size, because resolution cannot count. DPLL needs exactly conflicts with our heuristic, and CDCL also grows exponentially.
- In random 3-SAT, satisfiability drops sharply near (empirical) and DPLL cost peaks there. The first moment gives the bound ; existence of the threshold is proved only for and large .
- CDCL is DPLL that learns: conflict analysis is resolution with reason clauses, and reusing what is learned turns the tree proof into general resolution.