Practical SAT: propagating encodings, an efficient DPLL engine and local search
Building on propositional logic, Tseitin, resolution and DPLL from m01, this lesson bridges textbook algorithms and useful solvers. Encode CSPs, cardinalities and pseudo-Boolean constraints so unit propagation performs arc-consistency work; build iterative DPLL with a trail, decision levels and two watched literals as the basis for the next lesson’s CDCL; and study preprocessing and stochastic local search (WalkSAT and probSAT).
After this lesson you can
- Translate CSPs to SAT using direct, support and order encodings and predict the consistency unit propagation achieves in each.
- Encode cardinality and pseudo-Boolean constraints with totalizers and decision diagrams and justify generalized arc consistency under unit propagation.
- Implement iterative DPLL with trail, decision levels and two watched literals, and measure its performance against naive propagation.
- Apply subsumption and bounded variable elimination and reconstruct a model of the original formula.
- Implement WalkSAT and probSAT and explain why local search is incomplete but dominates satisfiable random instances near the threshold.
Before you start
- 10Constraint satisfaction problemBacktracking searchForward checkingArc consistency and AC-3Hill climbingMin-conflicts
- 01Boolean satisfiability problemConjunctive and disjunctive normal formsTseitin transformationCardinality constraint encodingsDPLL algorithmResolutionRandom 3-SAT phase transition
- 08Cook-Levin theorem
From textbook DPLL to a useful solver
In discrete mathematics you saw everything needed to decide SAT. A conjunctive normal form formula is a conjunction of clauses; the SAT problem asks whether an assignment satisfies all of them; the Tseitin transformation converts any circuit to linear-size CNF; resolution is a complete proof system for unsatisfiable formulas; and DPLL traverses the partial-assignment tree using unit propagation and backtracking. SAT is also the canonical NP-complete problem (Cook–Levin), so do not expect a polynomial algorithm. Yet today’s solvers routinely decide industrial formulas with millions of variables.
That lesson’s DPLL, scanning all clauses at each step and backtracking recursively, handles toy formulas. The distance to millions of variables is bridged not by one brilliant idea but four engineering layers, three built here:
- Encode well. One constraint admits many CNFs. Some let unit propagation infer everything locally deducible, others do not. A poor choice multiplies the search tree even if the formula is smaller.
- A motor that wastes nothing. In Chaff, Moskewicz and coauthors measured propagation as over 90 % of solver time on most problems, and lazy propagation with two watched literals gained one to two orders of magnitude over GRASP and SATO (Moskewicz et al., 2001). Here you build that engine with trail and decision levels, the basis of CDCL in the next lesson.
- Simplify before search. Preprocessing removes variables and clauses without changing satisfiability, then reconstructs a model of the original formula.
The fourth layer, learning clauses from conflicts, is CDCL and has its own lesson. At the end you will see a different family, stochastic local search, which cannot prove unsatisfiability but finds models of satisfiable formulas that make DPLL work hard.
Where SAT is used
Almost nobody writes clauses by hand: a program generates them from a problem model. Some established uses:
| Domain | What is encoded | Documented case |
|---|---|---|
| Hardware verification | Circuit unrolled steps and negated property: a model is a failure | Bounded model checking (Biere, Cimatti, Clarke and Zhu, 1999) |
| Package managers | One variable per package version; dependencies and conflicts as clauses | Eclipse p2 resolves dependencies using Sat4j (Le Berre and Rapicault, 2009); deciding package installability is NP-complete (Mancinelli et al., 2006) |
| Cryptanalysis | Bitwise operations of a hash function with fixed output | MD4 and MD5 collisions found with SAT solvers (Mironov and Zhang, 2006); CryptoMiniSat adds XOR clauses for such problems (Soos, Nohl and Castelluccia, 2009) |
| Planning | States and actions at each step of a fixed-length plan | Planning as satisfiability (Kautz and Selman, 1992) |
| Product configuration | Rules relating product options | Validation of Mercedes-Benz passenger-car configuration data (Sinz, Kaiser and Küchlin, 2003) |
| Mathematics | A finite combinatorial conjecture | Boolean Pythagorean triples problem, with a 200 TB proof (Heule, Kullmann and Marek, 2016) |
All share the same pieces: finite-domain variables (a version, color or instant), constraints between them and bounds such as “at most .” This is where we begin.
From CSP to SAT: three encodings
A constraint satisfaction problem has variables with finite domains and constraints; here, binary ones: a constraint between and is a set of allowed pairs . For value of , its support in is . Conversion to SAT requires deciding what Boolean variables mean and how to write constraints.
With two variables Tamura’s rule is easy to read. For each clause is : “if , then .” And , namely , gives : “if , then .” Each clause is a bound-propagation rule written in logic.
All three are correct: their models, read as assignments, are exactly the CSP’s solutions. What changes is size and above all what unit propagation deduces. The interactive puts all three on the same tiny CSP: with and , whose solutions are , and .
What you just saw has a name, and all three results are proven.
The first point follows from clause shape. A conflict clause can become unit only when one literal is false, namely when or is true, which occurs only when the variable is assigned (directly or because ALO leaves one value). A value with no support, like in the example, never triggers anything: no clause says “ needs something.” Support encoding says exactly that: the clause with is , empty of supports and therefore unit from the start. The full proof of the second point is induction on propagation steps, guided in the exercises.
For order encoding, consider the clauses just read. If ‘s lower bound rises to , literal is false and clause is unit: it deduces upper bound , precisely what interval propagation with would do; order axioms copy that bound to every with . Conversely, every propagated literal is a bound implied by a clause, so nothing extra is deduced. A hole is a clause acting only when a bound reaches it: hence removing makes AC-3 remove but order encoding does not.
Size moves opposite to strength. For a binary constraint with domains of size , direct encoding has one binary clause per forbidden pair (up to ), support has clauses of up to literals, and order needs binary clauses for plus axioms per variable, with variables per integer instead of . In the example, excluding your clauses: direct has 12 variables and 65 clauses, support 12 and 56, order 10 and 24. Sugar, Tamura and coauthors’ CSP-to-SAT compiler, uses order encoding: for integer arithmetic it is compact and propagates what matters in linear inequalities, bounds.
Lab 1: a CSP encoder and its verification
The first lab implements all three encodings from scratch, emits DIMACS and checks by enumeration that models projected onto CSP variables are exactly its solutions. It uses the CSP lesson’s representation: domains and binary constraints given by a predicate. DIMACS variables start at 1 because 0 ends clauses.
import itertools, random, time
class CNF:
"""Fórmula en CNF con variables numeradas desde 1 (DIMACS) y nombres legibles."""
def __init__(self):
self.n, self.clauses, self.names, self._vistas = 0, [], {}, set()
def fresh(self):
"""Variable auxiliar nueva, sin nombre."""
self.n += 1
return self.n
def var(self, name):
if name not in self.names:
self.n += 1
self.names[name] = self.n
return self.names[name]
def add(self, *lits):
clave = frozenset(lits)
if clave not in self._vistas: # una CNF es un conjunto: sin cláusulas repetidas
self._vistas.add(clave)
self.clauses.append(list(lits))
def dimacs(self):
lineas = [f"p cnf {self.n} {len(self.clauses)}"]
lineas += [" ".join(map(str, c)) + " 0" for c in self.clauses]
return "\n".join(lineas)
class CSP:
"""Variables con dominios finitos y restricciones binarias (u, w, predicado), como en la lección 9."""
def __init__(self, domains, constraints):
self.dom = {v: list(d) for v, d in domains.items()}
self.cons = constraints
def solutions(self):
vs = list(self.dom)
for vals in itertools.product(*(self.dom[v] for v in vs)):
a = dict(zip(vs, vals))
if all(ok(a[u], a[w]) for u, w, ok in self.cons):
yield a
def encode_direct(csp, support=False, amo=True):
"""Codificación directa (conflictos) o de soporte. x[v, a] significa v = a."""
F = CNF()
X = {(v, a): F.var((v, a)) for v in csp.dom for a in csp.dom[v]}
for v, d in csp.dom.items():
F.add(*[X[v, a] for a in d]) # al menos uno
if amo:
for a, b in itertools.combinations(d, 2):
F.add(-X[v, a], -X[v, b]) # a lo sumo uno
for u, w, ok in csp.cons:
if not support:
for a in csp.dom[u]:
for b in csp.dom[w]:
if not ok(a, b):
F.add(-X[u, a], -X[w, b]) # conflicto
else:
for a in csp.dom[u]:
F.add(-X[u, a], *[X[w, b] for b in csp.dom[w] if ok(a, b)]) # u = a necesita soporte en w
for b in csp.dom[w]:
F.add(-X[w, b], *[X[u, a] for a in csp.dom[u] if ok(a, b)]) # y al revés
decode = lambda model: {v: [a for a in csp.dom[v] if model[X[v, a]]] for v in csp.dom}
return F, X, decode
def unit_propagate(clauses, n, units=()):
"""Propagación unitaria ingenua hasta el punto fijo. Devuelve el vector de valores (None si hay conflicto)."""
val = [0] * (n + 1)
for l in units:
if val[abs(l)] == -(1 if l > 0 else -1):
return None
val[abs(l)] = 1 if l > 0 else -1
cambio = True
while cambio:
cambio = False
for c in clauses:
libres, sat = [], False
for l in c:
x = val[l] if l > 0 else -val[-l]
if x == 1:
sat = True
break
if x == 0:
libres.append(l)
if sat:
continue
if not libres:
return None
if len(libres) == 1:
l = libres[0]
val[abs(l)] = 1 if l > 0 else -1
cambio = True
return val
def ac3(csp, dom):
D = {v: set(d) for v, d in dom.items()}
arcs = [(u, w, ok) for u, w, ok in csp.cons] + [(w, u, (lambda f: lambda b, a: f(a, b))(ok)) for u, w, ok in csp.cons]
cola = list(arcs)
while cola:
u, w, ok = cola.pop()
quitar = {a for a in D[u] if not any(ok(a, b) for b in D[w])}
if quitar:
D[u] -= quitar
if not D[u]:
return None
cola += [arc for arc in arcs if arc[1] == u]
return D
def models(F):
"""Enumera todos los modelos de una CNF pequeña por fuerza bruta."""
for bits in itertools.product([False, True], repeat=F.n):
m = (None,) + bits
if all(any(m[l] if l > 0 else not m[-l] for l in c) for c in F.clauses):
yield m
# el ejemplo del interactivo: x < y y x + y = 7 con dominios 1..6
ejemplo = CSP({"x": range(1, 7), "y": range(1, 7)}, [("x", "y", lambda a, b: a < b), ("x", "y", lambda a, b: a + b == 7)])
sols = sorted(tuple(s.values()) for s in ejemplo.solutions())
for nombre, sup in [("directa", False), ("de soporte", True)]:
F, X, decode = encode_direct(ejemplo, sup)
proy = sorted({tuple(a for (a,) in decode(m).values()) for m in models(F)})
print(f"{nombre:>10}: {F.n} variables, {len(F.clauses)} cláusulas; modelos proyectados = soluciones: {proy == sols} {proy}")
print("primeras líneas DIMACS de la de soporte:")
print("\n".join(encode_direct(ejemplo, True)[0].dimacs().splitlines()[:4]))
# sin las cláusulas «a lo sumo uno»
for nombre, sup in [("directa", False), ("de soporte", True)]:
F, X, decode = encode_direct(ejemplo, sup, amo=False)
ms = [decode(m) for m in models(F)]
dobles = [m for m in ms if any(len(v) > 1 for v in m.values())]
malos = [m for m in dobles if not all(ok(a, b) for _, _, ok in ejemplo.cons for a in m["x"] for b in m["y"])]
print(f"{nombre} sin AMO: {len(ms)} modelos, {len(dobles)} con dos valores en una variable, "
f"{len(malos)} con alguna pareja de valores verdaderos incompatible; ejemplo: {malos[0] if malos else dobles[:1]}")Both encodings have exactly the expected three models. The cell’s last part is a warning: without AMO clauses direct encoding still has only three models in this example because conflict clauses force every pair of true values to be compatible; but support encoding now has 21 models, 18 with two values for one variable and an incompatible pair, such as , . Decoding by reading “the true value” of each variable yields , , violating .
Now propagation strength, measured value by value. Generate random five-variable CSPs with domains of size 4, remove random values and compare what AC-3 removes with what each encoding’s unit propagation sets false.
def removed_by_up(F, X, csp, dom):
"""Valores que la propagación unitaria pone a falso partiendo de los dominios dom (lo quitado, como unitarias)."""
units = [-X[v, a] for v in csp.dom for a in csp.dom[v] if a not in dom[v]]
val = unit_propagate(F.clauses, F.n, units)
if val is None:
return None
return {v: {a for a in dom[v] if val[X[v, a]] == -1} for v in csp.dom}
def random_csp(rng, nvars=5, d=4, p_edge=0.6, tight=0.35):
dom = {f"v{i}": range(d) for i in range(nvars)}
cons = []
for i, j in itertools.combinations(range(nvars), 2):
if rng.random() < p_edge:
prohibidos = {(a, b) for a in range(d) for b in range(d) if rng.random() < tight}
cons.append((f"v{i}", f"v{j}", (lambda P: lambda a, b: (a, b) not in P)(prohibidos)))
return CSP(dom, cons)
rng = random.Random(0)
tot = {"AC-3": 0, "directa": 0, "soporte": 0}
iguales = {"directa": 0, "soporte": 0}
casos = conflictos = 0
for _ in range(60):
csp = random_csp(rng)
codif = {"directa": encode_direct(csp, False), "soporte": encode_direct(csp, True)}
for _ in range(5):
dom = {v: {a for a in d if rng.random() < 0.8} or {rng.choice(list(d))} for v, d in csp.dom.items()}
D = ac3(csp, dom)
if D is None:
conflictos += 1
continue
casos += 1
ac = {v: dom[v] - D[v] for v in dom}
tot["AC-3"] += sum(map(len, ac.values()))
for nombre, (F, X, _) in codif.items():
r = removed_by_up(F, X, csp, dom)
tot[nombre] += sum(map(len, r.values()))
iguales[nombre] += r == ac
print(f"{casos} estados sin vaciado de dominio ({conflictos} con vaciado, descartados)")
print(f"valores eliminados: AC-3 {tot['AC-3']}, propagación en la directa {tot['directa']}, en la de soporte {tot['soporte']}")
print(f"estados en que la propagación elimina exactamente lo mismo que AC-3: directa {iguales['directa']}, soporte {iguales['soporte']}")In the 289 states without an empty domain, AC-3 removes 737 values; support-encoding propagation removes exactly the same in all 289 states, while direct removes only 113 in total and matches AC-3 in just 80 of 289 states. The theorem, measured.
Order encoding on linear constraints and its comparison with bound propagation:
def lit_le(F, P, v, coef, b, lo, hi):
"""Literal de (coef·v ≤ b) en la codificación de orden: True, False o un entero DIMACS."""
if coef > 0:
t = b // coef # v ≤ ⌊b / coef⌋
return True if t >= hi else False if t < lo else P[v, t]
t = -((-b) // coef) # ⌈b / coef⌉ con coef < 0: v ≥ t, es decir, ¬(v ≤ t − 1)
return True if t <= lo else False if t > hi else -P[v, t - 1]
def encode_order(bounds, linear):
"""Codificación de orden (Tamura y otros, 2009). bounds: {v: (lo, hi)}; linear: [({v: coef}, c)] con Σ coef·v ≤ c.
P[v, a] significa v ≤ a, para lo ≤ a < hi."""
F = CNF()
P = {}
for v, (lo, hi) in bounds.items():
for a in range(lo, hi):
P[v, a] = F.var((v, "<=", a))
for a in range(lo, hi - 1):
F.add(-P[v, a], P[v, a + 1]) # v ≤ a implica v ≤ a + 1
for coefs, c in linear:
(u, a1), (w, a2) = coefs.items() # aquí, restricciones de dos variables
lo1, hi1 = bounds[u]
rango = range(a1 * lo1 - 1, a1 * hi1 + 1) if a1 > 0 else range(a1 * hi1 - 1, a1 * lo1 + 1)
for b1 in rango: # Σ b_i = c − k + 1 con k = 2
b2 = c - 1 - b1
l1 = lit_le(F, P, u, a1, b1, *bounds[u])
l2 = lit_le(F, P, w, a2, b2, *bounds[w])
if l1 is True or l2 is True:
continue
F.add(*[l for l in (l1, l2) if l is not False])
def decode(model):
return {v: next((a for a in range(lo, hi) if model[P[v, a]]), hi) for v, (lo, hi) in bounds.items()}
return F, P, decode
def bounds_consistency(bounds, linear):
"""Consistencia de cotas: estrecha [lo, hi] de cada variable hasta el punto fijo (None si se vacía)."""
B = dict(bounds)
cambio = True
while cambio:
cambio = False
for coefs, c in linear:
for v, a in coefs.items():
resto = sum(min(b * B[u][0], b * B[u][1]) for u, b in coefs.items() if u != v)
lo, hi = B[v]
if a > 0:
hi2 = min(hi, (c - resto) // a)
lo2 = lo
else:
lo2 = max(lo, -((c - resto) // -a))
hi2 = hi
if (lo2, hi2) != (lo, hi):
B[v] = (lo2, hi2)
cambio = True
if lo2 > hi2:
return None
return B
# el ejemplo: x < y es x − y ≤ −1; x + y = 7 son dos desigualdades
bnd = {"x": (1, 6), "y": (1, 6)}
lin = [({"x": 1, "y": -1}, -1), ({"x": 1, "y": 1}, 7), ({"x": -1, "y": -1}, -7)]
F, P, decode = encode_order(bnd, lin)
proy = sorted({tuple(decode(m).values()) for m in models(F)})
print(f"de orden: {F.n} variables, {len(F.clauses)} cláusulas; modelos proyectados = soluciones: {proy == sols}")
# ¿iguala la propagación unitaria a la consistencia de cotas? CSP lineales al azar de tres variables
rng = random.Random(1)
igual = total = 0
for _ in range(300):
bounds = {v: (0, rng.randint(3, 7)) for v in "abc"}
linear = []
for u, w in itertools.combinations("abc", 2):
linear.append(({u: rng.choice([1, 2, -1, -2]), w: rng.choice([1, 2, -1, -3])}, rng.randint(-4, 8)))
F, P, _ = encode_order(bounds, linear)
# estrechamos al azar una cota de una variable, como haría una decisión
v = rng.choice("abc")
lo, hi = bounds[v]
t = rng.randint(lo, hi - 1)
nb = dict(bounds)
nb[v] = (lo, t)
BC = bounds_consistency(nb, linear)
val = unit_propagate(F.clauses, F.n, [P[v, t]])
if (BC is None) != (val is None):
total += 1
continue
total += 1
if BC is None:
igual += 1
continue
up = {u: (next((a + 1 for a in range(hi - 1, lo - 1, -1) if val[P[u, a]] == -1), lo), next((a for a in range(lo, hi) if val[P[u, a]] == 1), hi))
for u, (lo, hi) in bounds.items()}
igual += up == BC
print(f"propagación unitaria en la de orden = consistencia de cotas en {igual} de {total} casos")The example’s order encoding has 10 variables and 24 clauses, its models are the three solutions, and in 300 random three-variable linear CSPs (coefficients between and ) unit propagation deduces exactly the same bounds as interval propagation after tightening a random bound.
Cardinality and pseudo-Boolean constraints
“At most of these variables” appears everywhere: shift capacities, machine counts, change budgets. In cardinality encoding you saw two basic solutions: without auxiliaries, one clause per subset of variables, total; and Sinz’s sequential counter, with clauses and auxiliaries. What makes an encoder good? The same yardstick as above, now for Boolean constraints.
Cardinality and pseudo-Boolean encodings are compared on three numbers: auxiliary variables, clauses and whether GAC is maintained. For “at most ,” GAC means something concrete: once inputs are true, propagation sets all others false, and with true reaches the empty clause.
The totalizer
The Bailleux and Boufkhad (2003) totalizer counts in unary with a binary tree. Each node covers an input segment and has outputs meaning “at least of my inputs are true.” Leaves are themselves. A node with children whose outputs are and adds: if at least on the left and on the right are true, at least at the node are true,
where and are understood true and their literals omitted. For “at most ,” add root unit . The original stores all outputs ( equal to the segment’s input count); the truncated version keeps , since distinguishing “” from “more than ” is unnecessary. For “at least ” use clauses in the other direction, .
Proof
Fix a partial input assignment and let count true inputs below node .
Upward. Induction from leaves makes outputs of true for every . At a leaf this is the hypothesis. At an internal node, if , write with and (possible because and, if a child is truncated, its is already at least ); by induction and are true and clause forces . In particular, with propagation makes true and clashes with : conflict.
Downward. Suppose . Inducting from the root, for every node with propagation sets output false. At the root this is the unit clause. At an internal node with false, the left child has true by the upward pass (or and the literal is absent), and clause , present because , makes unit; likewise with roles swapped. If all a child’s inputs are true, no output needs to be set false. Reaching a free leaf, and its “output 1,” the input itself, becomes false.
Finally, propagation never deduces a falsehood, because all clauses follow from counter semantics. Thus with true it deduces nothing about inputs (none is implied), with it forces all remaining inputs to 0, and with it reaches conflict.
∎Size follows by counting levels. In the full version, the level whose nodes cover inputs has nodes, each with outputs and about clauses: variables and on the order of clauses per level, i.e. variables and clauses total, as Bailleux and Boufkhad give. Truncated, levels with contribute at most clauses, a geometric series, and totals drop to clauses and variables. With and , as the later cell calculates, truncated has 358 auxiliaries and 938 clauses versus 672 and 5623 for full and 495 and 1084 for the sequential counter; encoding without auxiliaries needs clauses.
Asín, Nieuwenhuis, Oliveras and Rodríguez-Carbonell’s (2011) cardinality networks reduce clauses and variables to while maintaining GAC: they use merge networks computing only the first sorted outputs. Asymptotically, for large they grow far less than the clauses of the truncated totalizer and sequential counter.
Pseudo-Boolean constraints
A pseudo-Boolean (PB) constraint is with positive integer weights (any linear inequality over literals can be put in this form by negating literals). It is an integer linear programming constraint with 0–1 variables: the same problems can be tackled by an integer-programming solver using continuous relaxation for bounds, or SAT reasoning over clauses. Eén and Sörensson (2006) described three CNF translations and showed that combining them well let MiniSat+ compete with contemporary native PB solvers:
- Decision diagrams. Node means “what remains from fits slack .” Its low child is and high child ; nodes with are the false terminal, and those whose is at least the sum of remaining weights the true terminal. Two clauses per node suffice: and . Propagation is excellent, but the diagram can be exponential: some PB constraints have no polynomial-size reduced diagram for any variable order, and Abío, Nieuwenhuis, Oliveras, Rodríguez-Carbonell and Mayer-Eichberger (2012) avoid this by decomposing coefficients, giving the first polynomial GAC encoding based on diagrams.
- Adders. A binary-adder tree computes in binary and a comparator bounds it. Compact, linear in the total bit count of weights, but propagation loses almost all strength: carries hide information.
- Sorting networks. A middle ground Eén and Sörensson highlighted as especially effective.
The two clauses per node suffice for GAC by a proof like the totalizer’s, with downward and upward passes.
Proof
Fix a partial assignment and let be the true-input set and the assertion “”: what is already 1 from does not fit slack .
Falsity upward. Every node with becomes false. Induct backward: if it is the false terminal; the true terminal cannot satisfy because its covers all remaining weights. If , high child satisfies , is false by induction, and makes false. If , low child satisfies and clause makes false.
Truth downward. The root is true, and from each true node propagation makes its low child true and, if , its high child. Thus for every node with is true.
If , the root satisfies and is both false and true: conflict. Otherwise let be free and setting it to 1 violate the constraint, namely . Then high child satisfies and is false, node is true, and clause makes unit. Since all clauses follow from node semantics, propagation deduces nothing else.
∎The lab checks this and measures the first two translations against the totalizer by traversing all partial input assignments:
from math import comb
def totalizer(F, xs, k, trunc=True):
"""Totalizador de Bailleux y Boufkhad para «a lo sumo k de xs», con salidas truncadas a k + 1 (o completo).
Devuelve la lista de salidas de la raíz: out[t − 1] significa «al menos t de xs son verdaderas»."""
def nodo(lits):
if len(lits) == 1:
return list(lits)
mitad = (len(lits) + 1) // 2
a, b = nodo(lits[:mitad]), nodo(lits[mitad:])
m = min(len(lits), k + 1) if trunc else len(lits)
r = [F.fresh() for t in range(1, m + 1)]
for i in range(len(a) + 1):
for j in range(len(b) + 1):
if 1 <= i + j <= m: # a_i ∧ b_j → r_{i+j}
F.add(*([-a[i - 1]] if i else []), *([-b[j - 1]] if j else []), r[i + j - 1])
return r
out = nodo(list(xs))
if k < len(xs):
F.add(-out[k]) # nunca «al menos k + 1»
return out
def pb_bdd(F, xs, ws, K):
"""Σ ws[i]·xs[i] ≤ K con un diagrama de decisión (Eén y Sörensson, 2006): un nodo por (i, holgura) distinto.
El nodo n(i, s) significa «lo que queda desde i cabe en s». Dos cláusulas por nodo: n → n_bajo y n ∧ x_i → n_alto."""
memo, suf = {}, [0] * (len(ws) + 1)
for i in range(len(ws) - 1, -1, -1):
suf[i] = suf[i + 1] + ws[i]
def nodo(i, s):
if s < 0:
return False
if s >= suf[i]:
return True
if (i, s) in memo:
return memo[i, s]
n = F.fresh()
memo[i, s] = n
bajo, alto = nodo(i + 1, s), nodo(i + 1, s - ws[i])
if bajo is not True:
F.add(-n, *([] if bajo is False else [bajo]))
if alto is not True:
F.add(-n, -xs[i], *([] if alto is False else [alto]))
return n
raiz = nodo(0, K)
if raiz is False:
F.add()
elif raiz is not True:
F.add(raiz)
return len(memo)
def full_adder(F, a, b, c):
"""Sumador completo de Tseitin: devuelve (suma, acarreo) con las 14 cláusulas habituales."""
s, co = F.fresh(), F.fresh()
for x, y, z in itertools.product([1, -1], repeat=3):
par = (x > 0) + (y > 0) + (z > 0)
F.add(-x * a, -y * b, -z * c, s if par % 2 else -s) # suma = a ⊕ b ⊕ c
for x, y in itertools.combinations([a, b, c], 2):
F.add(-x, -y, co)
F.add(x, y, -co)
return s, co
def card_adder(F, xs, k):
"""«a lo sumo k» con un árbol de sumadores binarios y un comparador: compacto, pero sin consistencia de arco."""
cero = F.fresh()
F.add(-cero)
def suma(p, q): # números binarios, bit menos significativo primero
n = max(len(p), len(q))
p, q = p + [cero] * (n - len(p)), q + [cero] * (n - len(q))
res, c = [], cero
for a, b in zip(p, q):
s, c = full_adder(F, a, b, c)
res.append(s)
return res + [c]
nums = [[x] for x in xs]
while len(nums) > 1:
nums = [suma(nums[i], nums[i + 1]) if i + 1 < len(nums) else nums[i] for i in range(0, len(nums), 2)]
S = nums[0]
# S ≤ k: para cada prefijo de bits altos, prohíbe superar k (comparador lexicográfico)
kb = [(k >> i) & 1 for i in range(len(S))]
for i in range(len(S)):
if kb[i] == 0: # si los bits por encima de i coinciden con k, S_i debe ser 0
F.add(*[-S[j] if kb[j] else S[j] for j in range(i + 1, len(S))], -S[i])
return S
def gac_check(build, n, k):
"""Recorre todas las asignaciones parciales de las entradas y cuenta en cuántas la propagación unitaria no deduce
todo lo que implica «a lo sumo k» (consistencia de arco generalizada)."""
F = CNF()
xs = [F.var(("x", i)) for i in range(n)]
build(F, xs, k)
cortos = {"= k": 0, "> k": 0, "espurios": 0}
for estado in itertools.product([0, 1, -1], repeat=n):
unos = estado.count(1)
val = unit_propagate(F.clauses, F.n, [x if e == 1 else -x for x, e in zip(xs, estado) if e])
if unos > k:
cortos["> k"] += val is not None # debería llegar a la cláusula vacía
elif val is None:
cortos["espurios"] += 1 # conflicto sin motivo: sería un error de codificación
elif unos == k:
cortos["= k"] += any(e == 0 and val[x] != -1 for x, e in zip(xs, estado)) # debería forzar las libres a 0
return F, cortos
n, k = 6, 2
print(f"«a lo sumo {k}» de {n}: {3 ** n} asignaciones parciales; {comb(n, k) * 2 ** (n - k)} con exactamente {k} a 1 "
f"y {sum(comb(n, j) * 2 ** (n - j) for j in range(k + 1, n + 1))} con más")
for nombre, build in [("totalizador", totalizer), ("sumadores", card_adder),
("diagrama de decisión", lambda F, xs, k: pb_bdd(F, xs, [1] * len(xs), k))]:
F, cortos = gac_check(build, n, k)
print(f"{nombre:>21}: {F.n - n:3d} auxiliares, {len(F.clauses):3d} cláusulas; la propagación se queda corta en "
f"{cortos['= k']} estados con k a 1 y no ve {cortos['> k']} conflictos; espurios: {cortos['espurios']}")
print(f"{'sin auxiliares':>21}: 0 auxiliares, {comb(n, k + 1):3d} cláusulas (todas las de {k + 1} negados)")
# una restricción pseudobooleana de verdad: pesos distintos
pesos, K = [5, 4, 3, 3, 2, 1], 9
F = CNF()
xs = [F.var(("y", i)) for i in range(len(pesos))]
nodos = pb_bdd(F, xs, pesos, K)
fallos = 0
for estado in itertools.product([0, 1, -1], repeat=len(xs)):
val = unit_propagate(F.clauses, F.n, [x if e == 1 else -x for x, e in zip(xs, estado) if e])
usado = sum(w for w, e in zip(pesos, estado) if e == 1)
if usado > K:
fallos += val is not None
continue
fallos += val is None or any(e == 0 and usado + w > K and val[x] != -1 for x, w, e in zip(xs, pesos, estado))
print(f"5y1 + 4y2 + 3y3 + 3y4 + 2y5 + y6 ≤ 9 con diagrama: {nodos} nodos, {len(F.clauses)} cláusulas; fallos de propagación: {fallos} de {3 ** 6}")
# tamaños con n = 100 y k = 5
n, k = 100, 5
for nombre, tr in [("totalizador completo", False), ("totalizador truncado", True)]:
F = CNF()
xs = [F.var(("x", i)) for i in range(n)]
totalizer(F, xs, k, trunc=tr)
print(f"n = {n}, k = {k}, {nombre}: {F.n - n} auxiliares, {len(F.clauses)} cláusulas")
print(f"n = {n}, k = {k}, contador secuencial: {(n - 1) * k} auxiliares, {2 * n * k + n - 3 * k - 1} cláusulas; "
f"sin auxiliares: {comb(n, k + 1):.3g} cláusulas")For “at most 2 of 6” there are 729 partial assignments: 240 with exactly two inputs 1 and 233 with more. Totalizer and decision diagram fail on none. The adder, with 116 clauses and 17 auxiliaries, fails to force free inputs to 0 in 205 of 240 assignments with two 1s and misses 118 of 233 conflicts (it finds them later after the solver assigns more variables and explores useless branches). No encoding produces spurious conflicts, which would be errors. The diagram for weights has 15 nodes and also fails on none of the 729 states.
The engine: from recursive to iterative DPLL
Discrete mathematics DPLL is recursive: each call copies or restores its assignment and propagation scans every clause. CDCL needs another organization, where assignment is a stack and each literal knows when and why it was assigned.
With these structures DPLL becomes a loop. Propagate to a fixed point. On conflict, find the most recent decision whose opposite branch is untried; if none remains the formula is unsatisfiable; otherwise undo to just before it and assign the opposite literal as an already “flipped” decision. Without conflict, if all variables are assigned there is a model; otherwise decide a literal at a new level. Backtracking is chronological, as in CSP backtracking search: its tree is exactly recursive DPLL’s under the same heuristic because propagation’s fixed point does not depend on unit-processing order.
Three details distinguish this from a mechanical translation of recursion. The trail serves as the recursion stack without copying. Undoing a level costs what is unassigned because its literals occupy a contiguous trail segment. Each literal’s reason and level are unnecessary for DPLL but exactly what CDCL conflict analysis traverses backward in the implication graph. We build them into the engine now.
Lazy propagation: two watched literals
The expensive piece remains. How does the engine know a clause became unit? The classical answer kept counters of false and true literals in every clause: assigning a variable updates every clause containing it, and undoing does so again. If a variable occurs in a hundred clauses, each assignment and unassignment costs a hundred visits even though almost none is near unit.
Chaff observes that a clause of length cannot be unit or conflicting while it has two nonfalse literals. Watching two suffices.
What is extraordinary is not what assignment saves but what undoing costs: nothing. Backtracking changes no watch list. The reason is an invariant.
Proof
(i) If a clause had all literals false except one free and had not been handled, one watch would be false (at most one literal is nonfalse and two are watched); by the invariant the other would be true and the clause satisfied. Contradiction. The same argument excludes a clause with all literals false.
(ii) The invariant holds when the queue empties by how each watch is handled on becoming false: either replaced by a nonfalse literal, or the other watch was already true (assigned earlier, hence at level than ), or is propagated then at the same level as . Undoing to level unassigns exactly variables at level . Watches moved in undone levels point to literals that were nonfalse when moved and remain so. If false watch had level , it becomes free and nothing is required. If it had level , it remains false, but then and remains true. In a clause that has just conflicted, both watches are false at the current level (an earlier-level false watch would already have propagated the other), so undoing that level frees both. No watch needs moving.
∎The following engine is the next lesson’s with one difference: there conflict will be analyzed instead of backtracking chronologically. Clauses store their watches at positions 0 and 1, as in MiniSat, so finding the other watch is immediate.
Lab 2: engine and validation
class Motor:
"""DPLL iterativo: trail, niveles de decisión, cola de propagación y dos literales vigilados.
Literales DIMACS; internamente el literal l tiene índice 2v (positivo) o 2v + 1 (negativo)."""
def __init__(self, n, clauses):
self.n = n
self.clauses = [list(dict.fromkeys(c)) for c in clauses] # sin literales repetidos
self.val = [0] * (n + 1) # 1 verdadera, −1 falsa, 0 libre
self.level = [0] * (n + 1)
self.reason = [None] * (n + 1) # índice de la cláusula que forzó la variable (None si es decisión)
self.trail, self.lim, self.qhead = [], [], 0
self.watches = {} # literal -> índices de las cláusulas que lo vigilan
self.props = self.visits = self.decisions = 0
self.unsat_at_root = False
for i, c in enumerate(self.clauses):
if len(c) == 0:
self.unsat_at_root = True
elif len(c) == 1:
if self.value(c[0]) == -1:
self.unsat_at_root = True
elif self.value(c[0]) == 0:
self.assign(c[0], i)
else:
self.watches.setdefault(c[0], []).append(i) # vigila las dos primeras posiciones
self.watches.setdefault(c[1], []).append(i)
def value(self, l):
v = self.val[abs(l)]
return v if l > 0 else -v
def decision_level(self):
return len(self.lim)
def assign(self, l, reason):
v = abs(l)
self.val[v] = 1 if l > 0 else -1
self.level[v] = len(self.lim)
self.reason[v] = reason
self.trail.append(l)
def propagate(self):
"""Procesa la cola (trail[qhead:]). Devuelve el índice de una cláusula en conflicto, o None.
Invariante: c[0] y c[1] son los literales vigilados de cada cláusula de longitud ≥ 2."""
while self.qhead < len(self.trail):
p = -self.trail[self.qhead] # p acaba de hacerse falso
self.qhead += 1
lista = self.watches.get(p, [])
nueva = []
i = 0
while i < len(lista):
ci = lista[i]
i += 1
self.visits += 1
c = self.clauses[ci]
if c[0] == p: # deja el literal falso en la posición 1
c[0], c[1] = c[1], c[0]
if self.value(c[0]) == 1: # el otro vigilado ya la satisface
nueva.append(ci)
continue
for k in range(2, len(c)): # busca un sustituto que no sea falso
if self.value(c[k]) != -1:
c[1], c[k] = c[k], c[1]
self.watches.setdefault(c[1], []).append(ci)
break
else:
nueva.append(ci) # sigue vigilando p
if self.value(c[0]) == -1: # conflicto: conserva el resto de la lista
nueva.extend(lista[i:])
self.watches[p] = nueva
return ci
self.assign(c[0], ci) # unitaria
self.props += 1
self.watches[p] = nueva
return None
def backtrack(self, lvl):
"""Deshace todos los niveles por encima de lvl. No toca las listas de vigilancia."""
if self.decision_level() <= lvl:
return
inicio = self.lim[lvl]
for l in self.trail[inicio:]:
self.val[abs(l)] = 0
self.reason[abs(l)] = None
del self.trail[inicio:]
del self.lim[lvl:]
self.qhead = len(self.trail)
def decide(self, l):
self.lim.append(len(self.trail))
self.decisions += 1
self.assign(l, None)
def pick(self):
"""Heurística sencilla: la variable libre con más apariciones en cláusulas no satisfechas (como en m01)."""
cuenta = {}
for c in self.clauses:
if any(self.value(l) == 1 for l in c):
continue
for l in c:
if self.value(l) == 0:
cuenta[l] = cuenta.get(l, 0) + 1
if not cuenta:
return next(v for v in range(1, self.n + 1) if self.val[v] == 0)
v = max({abs(l) for l in cuenta}, key=lambda v: (cuenta.get(v, 0) + cuenta.get(-v, 0), -v))
return v if cuenta.get(v, 0) >= cuenta.get(-v, 0) else -v
def solve(self, max_decisions=None):
"""Vuelta atrás cronológica iterativa. flipped[d] dice si la decisión del nivel d + 1 ya probó su otra rama."""
if self.unsat_at_root:
return False
flipped = []
while True:
if self.propagate() is not None:
d = len(flipped) - 1
while d >= 0 and flipped[d]:
d -= 1
if d < 0:
return False # las dos ramas de todas las decisiones fallan
l = self.trail[self.lim[d]] # la decisión del nivel d + 1
self.backtrack(d)
del flipped[d:]
self.lim.append(len(self.trail)) # la rama contraria, en el mismo nivel
self.assign(-l, None)
flipped.append(True)
continue
if len(self.trail) == self.n:
return True
if max_decisions is not None and self.decisions >= max_decisions:
return None
self.decide(self.pick())
flipped.append(False)
def model(self):
return [v if self.val[v] == 1 else -v for v in range(1, self.n + 1)]
def dpll_rec(F, n, val=None):
"""El DPLL recursivo de m01, en su versión mínima: propagación ingenua y ramificación."""
val = dict(val or {})
while True:
unit = None
for c in F:
if any(val.get(abs(l)) == (l > 0) for l in c):
continue
libres = [l for l in c if abs(l) not in val]
if not libres:
return None
if len(libres) == 1:
unit = libres[0]
break
if unit is None:
break
val[abs(unit)] = unit > 0
libre = next((v for v in range(1, n + 1) if v not in val), None)
if libre is None:
return val
for b in (True, False):
r = dpll_rec(F, n, {**val, libre: b})
if r is not None:
return r
return None
def random_ksat(rng, n, m, k=3):
return [[v if rng.random() < 0.5 else -v for v in rng.sample(range(1, n + 1), k)] for _ in range(m)]
def satisfies(F, model):
s = set(model)
return all(any(l in s for l in c) for c in F)
rng = random.Random(0)
t0 = time.perf_counter()
iguales = sat = 0
N_FORM = 1500
for t in range(N_FORM):
n = rng.randint(3, 12)
m = int(rng.uniform(2.0, 7.0) * n)
F = random_ksat(rng, n, m, min(n, rng.choice([2, 3, 3, 4])))
S = Motor(n, F)
r = S.solve()
ref = dpll_rec(F, n) is not None
assert r == ref, (F, r, ref)
if r:
assert satisfies(F, S.model())
sat += 1
iguales += 1
print(f"{iguales} de {N_FORM} fórmulas con el mismo veredicto que el DPLL recursivo ({sat} satisfacibles, "
f"todos los modelos comprobados) en {time.perf_counter() - t0:.1f} s")The 1500 random formulas (3 to 12 variables, clauses of 2 to 4 literals, densities on both sides of the threshold) give the same verdict as recursive DPLL, and each returned model satisfies its formula. Validation against a simple independent implementation is the only reasonable way to trust an engine with such delicate invariants: a misplaced watch raises no error, it only occasionally misses a unit clause.
Now the motivating measurement. Same engine, same heuristic (fixed variable order so propagation dominates time), and two propagators: watches and counters. Since propagation’s fixed point is the same, both traverse the same tree, as the cell checks.
class MotorContadores(Motor):
"""El mismo motor con la propagación de los años noventa: contadores de literales falsos y verdaderos por
cláusula. Cada asignación visita todas las cláusulas de la variable, y cada vuelta atrás, otra vez."""
def __init__(self, n, clauses):
super().__init__(n, [])
self.clauses = [list(dict.fromkeys(c)) for c in clauses]
self.occ = [[] for _ in range(n + 1)]
for i, c in enumerate(self.clauses):
for l in c:
self.occ[abs(l)].append(i)
self.nfalse = [0] * len(self.clauses)
self.ntrue = [0] * len(self.clauses)
self.unsat_at_root = any(len(c) == 0 for c in self.clauses)
self.pending = [i for i, c in enumerate(self.clauses) if len(c) == 1]
def assign(self, l, reason):
super().assign(l, reason)
for ci in self.occ[abs(l)]:
self.visits += 1
if l in self.clauses[ci]:
self.ntrue[ci] += 1
else:
self.nfalse[ci] += 1
self.pending.append(ci)
def propagate(self):
while self.pending:
ci = self.pending.pop()
c = self.clauses[ci]
if self.ntrue[ci]:
continue
k = len(c) - self.nfalse[ci]
if k == 0:
self.pending.clear()
return ci
if k == 1:
l = next(l for l in c if self.value(l) == 0)
self.assign(l, ci)
self.props += 1
self.qhead = len(self.trail)
return None
def backtrack(self, lvl):
if self.decision_level() <= lvl:
return
for l in self.trail[self.lim[lvl]:]:
for ci in self.occ[abs(l)]:
self.visits += 1
if l in self.clauses[ci]:
self.ntrue[ci] -= 1
else:
self.nfalse[ci] -= 1
super().backtrack(lvl)
self.pending.clear()
def static_order(F, n):
"""Orden fijo por número de apariciones: barato, para que el tiempo lo domine la propagación."""
occ = [0] * (n + 1)
for c in F:
for l in c:
occ[abs(l)] += 1
orden = sorted(range(1, n + 1), key=lambda v: -occ[v])
return lambda S: next(-v for v in orden if S.val[v] == 0)
def php(p, h):
v = lambda i, j: i * h + j + 1
F = [[v(i, j) for j in range(h)] for i in range(p)]
F += [[-v(i, j), -v(k, j)] for j in range(h) for i in range(p) for k in range(i + 1, p)]
return F, p * h
rng = random.Random(3)
casos = [("3-SAT, n = 60, α = 4.26", [(random_ksat(rng, 60, 256, 3), 60) for _ in range(3)]),
("5-SAT, n = 26, α = 21", [(random_ksat(rng, 26, 546, 5), 26) for _ in range(3)]),
("palomar, 7 palomas y 6 huecos", [php(7, 6)])]
for nombre, formulas in casos:
fila = {}
for clase in (Motor, MotorContadores):
t0 = time.perf_counter()
props = visits = decs = 0
res = []
for F, n in formulas:
S = clase(n, F)
elegir = static_order(F, n)
S.pick = lambda S=S, e=elegir: e(S)
res.append(S.solve())
props, visits, decs = props + S.props, visits + S.visits, decs + S.decisions
fila[clase.__name__] = (time.perf_counter() - t0, props, visits, decs, res)
(tw, pw, vw, dw, rw), (tc, pc, vc, dc, rc) = fila["Motor"], fila["MotorContadores"]
assert rw == rc and dw == dc # mismo árbol de búsqueda
print(f"{nombre}: el mismo árbol, {dw} decisiones; veredictos {rw}")
print(f" vigilados: {vw:9d} visitas, {pw / tw:7.0f} propagaciones/s, {tw:.2f} s")
print(f" contadores: {vc:9d} visitas, {pc / tc:7.0f} propagaciones/s, {tc:.2f} s"
f" (visitas ×{vc / vw:.1f}, tiempo ×{tc / tw:.1f})")Across all three families the tree is identical and watches win: on random 3-SAT counters make 9.8 times more clause visits; on 5-SAT, 20.1 times; on 7 pigeons in 6 holes, 7.1 times. In Pyodide time watches are about 2 to 6 times faster depending on family, with greatest advantage on 5-SAT and least on pigeonhole (exact timing ratio varies by run; visit ratio does not). This matches expectations: longer clauses give greater advantage (pigeonhole clauses are mostly binary), because counters visit every occurrence and watches only two per clause; time advantage is smaller than visit advantage partly because each watched visit does more work searching for a replacement. In real solvers with learned clauses of tens or hundreds of literals the difference is what Chaff measured.
Preprocessing: simplify before search
Before its first decision, a modern solver spends time simplifying the formula using satisfiability-preserving rules. The main ones combine in SAT preprocessing, for which SatELite is the reference (Eén and Biere, 2005):
- Subsumption. If , clause is redundant: every model of models .
- Self-subsuming resolution. If and with , their resolvent is , subsuming : replace by , one literal shorter.
- Bounded variable elimination (BVE). Davis–Putnam elimination from resolution, with a brake. Let be clauses containing and those containing . Replace with all non-tautological resolvents only if their number does not exceed .
- Failed literal probing. If propagating leads to conflict, follows from the formula and is added as a unit.
Proof
If has a model, it satisfies all resolvents (resolution is sound), hence models . The converse follows from the second part. Clauses of do not mention and satisfies them as does. If , every clause of has a true literal other than , and clauses of are satisfied by . If , clauses of are satisfied by ; suppose some had all literals other than false. With the that caused , resolvent would be false under . If tautological it cannot be false; otherwise it is in and satisfies it. Contradiction either way.
∎The proof says exactly what to save: each eliminated variable’s original clauses ( would suffice) on a stack. At the end traverse it backward, because an eliminated variable’s value can depend on others eliminated later.
Why does BVE work so well on industrial formulas? Tseitin fills them with definitions. If is defined by its three gate clauses, resolvents between two gate clauses are tautological. Eén and Biere go further: when is gate-defined, resolvents between the gate and uses of suffice, and resolvents between two uses are redundant (elimination by substitution). Eliminating then substitutes the definition, as by hand.
The lab applies the four rules to the Tseitin encoding of a random circuit of 120 AND, OR and XOR gates with output forced to 1, solves the remainder with the engine and reconstructs the model:
def preprocess(F, n, frozen=(), max_occ=10):
"""Subsunción, autosubsunción y eliminación acotada de variables (al estilo de SatELite, Eén y Biere 2005).
Devuelve (fórmula simplificada, pila de eliminaciones, estadísticas). frozen: variables que no se eliminan."""
cl = {i: frozenset(c) for i, c in enumerate(F)}
occ = {l: set() for v in range(1, n + 1) for l in (v, -v)}
for i, c in cl.items():
for l in c:
occ[l].add(i)
est = dict(subsumidas=0, reforzadas=0, eliminadas=0)
pila, siguiente = [], len(F)
def quita(i):
for l in cl.pop(i):
occ[l].discard(i)
def mete(c):
nonlocal siguiente
cl[siguiente] = c
for l in c:
occ[l].add(siguiente)
siguiente += 1
def subsume_con(i):
"""Usa la cláusula i para borrar las que contiene y para reforzar las que contienen su variante con un literal negado."""
C = cl[i]
pivote = min(C, key=lambda l: len(occ[l]) + len(occ[-l]))
for j in list(occ[pivote] | occ[-pivote]):
if j == i or j not in cl:
continue
D = cl[j]
if len(D) < len(C):
continue
dif = C - D
if not dif: # C ⊆ D: D sobra
quita(j)
est["subsumidas"] += 1
elif len(dif) == 1 and -next(iter(dif)) in D: # autosubsunción: D pierde el literal opuesto
l = next(iter(dif))
quita(j)
mete(D - {-l})
est["reforzadas"] += 1
for i in sorted(cl, key=lambda i: len(cl[i])):
if i in cl:
subsume_con(i)
candidatas = sorted((v for v in range(1, n + 1) if v not in frozen), key=lambda v: len(occ[v]) * len(occ[-v]))
for v in candidatas:
P, N = [cl[i] for i in occ[v]], [cl[i] for i in occ[-v]]
if len(P) + len(N) == 0 or len(P) > max_occ or len(N) > max_occ:
continue
resolventes = set()
for C in P:
for D in N:
R = (C - {v}) | (D - {-v})
if not any(-l in R for l in R): # descarta las tautologías
resolventes.add(R)
if len(resolventes) > len(P) + len(N):
break
if len(resolventes) > len(P) + len(N): # la fórmula crecería: no se elimina
continue
pila.append((v, P + N)) # lo que hace falta para reconstruir v
for i in list(occ[v] | occ[-v]):
quita(i)
for R in resolventes:
mete(R)
subsume_con(siguiente - 1)
est["eliminadas"] += 1
return [sorted(c, key=abs) for c in cl.values()], pila, est
def reconstruct(model, pila):
"""Recorre la pila al revés: v vale lo que pida alguna de sus cláusulas guardadas que aún no esté satisfecha."""
val = {abs(l): l > 0 for l in model}
for v, guardadas in reversed(pila):
val[v] = False
for C in guardadas:
if v in C and not any(val.get(abs(l)) == (l > 0) for l in C if l != v):
val[v] = True
break
return [v if val.get(v, False) else -v for v in sorted(val)]
def failed_literals(F, n):
"""Sondeo de literales fallidos: si propagar l lleva a conflicto, ¬l es consecuencia de la fórmula."""
unidades = []
for v in range(1, n + 1):
for l in (v, -v):
if unit_propagate(F, n, unidades + [l]) is None:
unidades.append(-l)
break
return unidades
def random_circuit(rng, n_in, n_gates):
"""Tseitin de un circuito aleatorio de puertas AND, OR y XOR de dos entradas, con la salida forzada a 1."""
F, n = [], n_in
nodos = list(range(1, n_in + 1))
for _ in range(n_gates):
a, b = rng.sample(nodos[-12:], 2)
a, b = a if rng.random() < 0.7 else -a, b if rng.random() < 0.7 else -b
n += 1
g, tipo = n, rng.choice(["and", "or", "xor"])
if tipo == "and":
F += [[-g, a], [-g, b], [g, -a, -b]]
elif tipo == "or":
F += [[g, -a], [g, -b], [-g, a, b]]
else:
F += [[-g, a, b], [-g, -a, -b], [g, -a, b], [g, a, -b]]
nodos.append(g)
F.append([n])
return F, n
rng = random.Random(5)
F, n = random_circuit(rng, 16, 120)
G, pila, est = preprocess(F, n)
vars_G = {abs(l) for c in G for l in c}
print(f"original: {n} variables, {len(F)} cláusulas")
print(f"preprocesada: {len(vars_G)} variables, {len(G)} cláusulas; {est}")
S = Motor(n, G)
assert S.solve()
modelo = reconstruct(S.model(), pila)
print("el modelo reconstruido satisface la fórmula original:", satisfies(F, modelo))
sin = [v if S.val[v] == 1 else -v for v in range(1, n + 1)]
print("sin reconstruir, el modelo de la simplificada la satisface:", satisfies(F, sin))
print("literales fallidos encontrados en la simplificada:", len(failed_literals(G, n)))136 variables and 398 clauses become 52 variables and 218 clauses: 75 variables eliminated, 16 clauses subsumed and 26 strengthened by self-subsumption. The reconstructed model satisfies the original formula and the simplified formula’s raw model does not, because eliminated variables received arbitrary values. Probing also finds 20 failed literals in the simplified formula, 20 free units.
Stochastic local search: GSAT, WalkSAT and probSAT
Everything above is systematic search: complete and able to prove unsatisfiability. The alternative gives that up for speed on satisfiable instances. It is local-search hill climbing applied to SAT: state is a complete assignment, objective is the number of false clauses, and a move flips a variable. For variable , its break is the number of clauses made false by flipping it (those where supplies the only true literal), and its make the number made true.
GSAT (Selman, Levesque and Mitchell, 1992) flips the variable with largest make minus break in the whole formula. It gets stuck on plateaus and local minima; its successor changed two things: choose only variables from a false clause, like CSP min-conflicts, and add noise.
WalkSAT has the two things hill climbing lacked. Choosing within a false clause ensures the flip fixes at least that clause: the walk is never entirely blind. Noise enables escape from local minima without restarts. Using break alone without make was WalkSAT’s design choice, and probSAT confirmed it systematically: in random 3-SAT experiments ignoring make entirely was a good choice, and for polynomial break-only selection automatic tuning gave on 1000-variable instances and on 10 000-variable instances, with . For WalkSAT on 3-SAT they used optimal noise measured by Kroc, Sabharwal and Selman (2010).
Incomplete, yet best near the threshold
WalkSAT cannot return “unsatisfiable”: if it finds no model it cannot tell whether none exists or it has not searched enough. It is incomplete. For satisfiable instances there are probabilistic guarantees (Schöning’s 1999 random walk finds a model of satisfiable 3-SAT in expected time up to polynomial factors), but none for the others.
Yet on satisfiable random 3-SAT near the phase-transition threshold, local search works best: Balint and Schöning successfully tested probSAT on random formulas up to variables, ten times larger than the largest in the 2011 SAT competition, and, drawing on Kroc and coauthors’ data, report that optimally tuned WalkSAT appears to scale linearly with near the threshold. Systematic methods are less fortunate: random unsatisfiable formulas of sufficiently large constant density require exponentially sized resolution refutations with high probability (Chvátal and Szemerédi, 1988), and a terminating DPLL tree is one.
Lab 2 continued: WalkSAT and probSAT
First, three satisfiable formulas with and , filtered using the engine (which already finds them costly):
class LocalSearch:
"""Estado compartido de la búsqueda local: valoración, verdaderos por cláusula y lista de cláusulas falsas."""
def __init__(self, F, n, rng):
self.F, self.n, self.rng = F, n, rng
self.occ = {l: [] for v in range(1, n + 1) for l in (v, -v)}
for i, c in enumerate(F):
for l in c:
self.occ[l].append(i)
self.val = [None] + [rng.random() < 0.5 for _ in range(n)]
self.ntrue = [sum(self.true(l) for l in c) for c in F]
self.unsat = [i for i, t in enumerate(self.ntrue) if t == 0]
self.pos = {c: k for k, c in enumerate(self.unsat)}
def true(self, l):
return self.val[l] if l > 0 else not self.val[-l]
def break_(self, v):
"""Cláusulas que pasan a falsas si se voltea v: aquellas en las que v aporta el único literal verdadero."""
tl = v if self.val[v] else -v
return sum(1 for c in self.occ[tl] if self.ntrue[c] == 1)
def flip(self, v):
tl = v if self.val[v] else -v
self.val[v] = not self.val[v]
for c in self.occ[tl]:
self.ntrue[c] -= 1
if self.ntrue[c] == 0:
self.pos[c] = len(self.unsat)
self.unsat.append(c)
for c in self.occ[-tl]:
self.ntrue[c] += 1
if self.ntrue[c] == 1: # sale de la lista en O(1): cambia por la última
k, last = self.pos.pop(c), self.unsat.pop()
if last != c:
self.unsat[k] = last
self.pos[last] = k
def walksat(F, n, p, max_flips, seed):
S = LocalSearch(F, n, random.Random(seed))
for flips in range(max_flips):
if not S.unsat:
return flips
c = S.F[S.rng.choice(S.unsat)]
b = {abs(l): S.break_(abs(l)) for l in c}
mejor = min(b.values())
if mejor == 0: # movimiento gratis: no rompe nada
v = S.rng.choice([v for v in b if b[v] == 0])
elif S.rng.random() < p: # paso aleatorio
v = abs(S.rng.choice(c))
else: # paso voraz
v = S.rng.choice([v for v in b if b[v] == mejor])
S.flip(v)
return None
def probsat(F, n, cb, max_flips, seed, eps=1.0):
"""probSAT con la función polinómica de solo break (Balint y Schöning, 2012): P(v) ∝ (eps + break)^(−cb)."""
S = LocalSearch(F, n, random.Random(seed))
for flips in range(max_flips):
if not S.unsat:
return flips
c = S.F[S.rng.choice(S.unsat)]
vs = [abs(l) for l in c]
pesos = [(eps + S.break_(v)) ** -cb for v in vs]
S.flip(S.rng.choices(vs, weights=pesos)[0])
return None
def median_or_none(xs):
xs = sorted(x if x is not None else float("inf") for x in xs)
m = xs[len(xs) // 2]
return None if m == float("inf") else m# tres fórmulas satisfacibles de 3-SAT con n = 100 y α = 4.2, filtradas con el motor de la lección
rng = random.Random(11)
satis, t0 = [], time.perf_counter()
while len(satis) < 3:
F = random_ksat(rng, 100, 420, 3)
S = Motor(100, F)
if S.solve():
satis.append(F)
print(f"satisfacible: el motor necesita {S.decisions} decisiones")
else:
print(f"insatisfacible, descartada ({S.decisions} decisiones)")
print(f"({time.perf_counter() - t0:.1f} s)")The engine needs 1755, 62 and 1073 decisions; variation among same-size formulas is enormous, as with everything measured near the threshold. Now WalkSAT noise:
print("WalkSAT en las 3 fórmulas, 2 semillas cada una, hasta 6000 volteos")
for p in (0.0, 0.2, 0.4, 0.57, 0.8, 1.0):
r = [walksat(F, 100, p, 6000, s) for F in satis for s in (1, 2)]
ok = sum(x is not None for x in r)
print(f" p = {p:.2f}: {ok}/6 resueltas, mediana de volteos {median_or_none(r)}")With it solves none of 6 runs (pure greedy is stuck in local minima), with it solves 5 of 6 at a median 3048 flips, and with falls back to 2 of 6. The optimum is intermediate, in the range measured by Kroc and coauthors. With 6 runs per point the profile is noisy; the interactive repeats it with more formulas.
print("probSAT (solo break, polinómica, eps = 1) en las mismas fórmulas, hasta 6000 volteos")
for cb in (0.0, 1.0, 2.38, 4.0):
r = [probsat(F, 100, cb, 6000, s) for F in satis for s in (1, 2)]
print(f" cb = {cb:.2f}: {sum(x is not None for x in r)}/6 resueltas, mediana de volteos {median_or_none(r)}")
# lo que la búsqueda local no puede hacer: una fórmula insatisfacible
rng = random.Random(4)
while True:
F = random_ksat(rng, 40, 240, 3)
S = Motor(40, F)
if not S.solve():
break
print(f"\nfórmula con n = 40 y α = 6: el motor demuestra que es insatisfacible con {S.decisions} decisiones")
r = walksat(F, 40, 0.57, 20000, 1)
print(f"WalkSAT tras 20 000 volteos: {'modelo' if r is not None else 'nada'}; ninguna ejecución, por larga que sea, lo certifica")With probSAT is a random walk inside the clause and solves none; with , 3 of 6. In this tiny sample with just 6000 flips it does not beat WalkSAT; Balint and Schöning’s published advantage was measured on hundreds of much larger formulas with their C implementation, and six runs should not be expected to reproduce it. What is clear is dependence on break: without it there is no search. The last line shows the whole family’s limit: the formula with 40 variables and is unsatisfiable (the engine proves it in 17 decisions), and WalkSAT spends 20 000 flips unable to say anything.
Lab 3: encodings and industrial solvers with PySAT
PySAT (Ignatiev, Morgado and Marques-Silva, 2018) provides Python access to industrial CDCL solvers and implemented cardinality encodings, and runs in the browser compiled to WebAssembly, as seen in cardinality encodings. The assignment problem has 24 tasks in 6 shifts, each task in exactly one shift, at most 4 tasks per shift (an “at most 4 of 24” constraint per shift), and conflicting task pairs unable to share a shift. Compare pysat.card encodings with the custom totalizer, solving four instances with CaDiCaL 1.5.3 and Glucose 4. Pseudo-Boolean constraints from pysat.pb need library pypblib, unavailable in the browser; use the lab 1 decision diagram for them.
from pysat.card import CardEnc, EncType
from pysat.formula import IDPool
from pysat.solvers import Solver
def asignacion(rng, tareas, turnos, cap, p_conflicto):
"""Cada tarea en exactamente un turno, a lo sumo cap tareas por turno y dos tareas en conflicto nunca juntas.
Devuelve las cláusulas base y, por turno, los literales sobre los que va la cardinalidad."""
pool = IDPool()
x = lambda t, s: pool.id(("x", t, s))
base = []
for t in range(tareas):
base.append([x(t, s) for s in range(turnos)])
for s1, s2 in itertools.combinations(range(turnos), 2):
base.append([-x(t, s1), -x(t, s2)])
for t1, t2 in itertools.combinations(range(tareas), 2):
if rng.random() < p_conflicto:
for s in range(turnos):
base.append([-x(t1, s), -x(t2, s)])
grupos = [[x(t, s) for t in range(tareas)] for s in range(turnos)]
return base, grupos, pool.top
def con_codificacion(base, grupos, top, cap, enc):
F = [list(c) for c in base]
for lits in grupos:
if enc == "propio":
C = CNF()
C.n = top
totalizer(C, lits, cap)
F += C.clauses
top = C.n
else:
card = CardEnc.atmost(lits=lits, bound=cap, top_id=top, encoding=enc)
F += card.clauses
top = max(top, card.nv)
return F, top
def resolver(F, nombre):
with Solver(name=nombre, bootstrap_with=F) as s:
t0 = time.perf_counter()
r = s.solve()
return r, time.perf_counter() - t0, s.accum_stats()["conflicts"]
codifs = [("contador secuencial", EncType.seqcounter), ("totalizador (PySAT)", EncType.totalizer),
("red de ordenación", EncType.sortnetwrk), ("red de cardinalidad", EncType.cardnetwrk),
("totalizador propio", "propio")]
instancias = [asignacion(random.Random(s), tareas=24, turnos=6, cap=4, p_conflicto=0.3) for s in range(4)]
print("4 instancias: 24 tareas, 6 turnos de capacidad 4, conflictos con probabilidad 0.3")
for nombre, enc in codifs:
tam, filas = None, []
for solver in ("cadical153", "glucose4"):
res = []
for base, grupos, top in instancias:
F, nv = con_codificacion(base, grupos, top, 4, enc)
tam = (nv, len(F))
res.append(resolver(F, solver))
veredictos = "".join("S" if r else "U" for r, _, _ in res)
conf = sorted(c for _, _, c in res)
filas.append(f"{solver}: {veredictos}, conflictos {conf}")
print(f" {nombre:>20} ({tam[0]} var., {tam[1]} cl.) | " + " | ".join(filas))All four instances are satisfiable and all five encodings confirm it. CaDiCaL solves them with very few conflicts (0 to 253) regardless of encoding. Glucose is far more sensitive: with the custom totalizer truncated to outputs, conflicts range from 101 to 208; with the cardinality network, 96 to 6141. Four instances cannot rank encodings generally; they show effort depends on both encoding and solver, with differences over an order of magnitude in bad cases, and size does not predict it: the sorting network, largest at 2442 variables, gives among the fewest Glucose conflicts.
Finally, the lesson’s engine versus CaDiCaL on growing instances of the same problem, logarithmic scale:
import matplotlib.pyplot as plt
# el motor propio frente a CaDiCaL en instancias crecientes del mismo problema (totalizador propio en las dos)
filas = []
for tareas in (8, 12, 16, 20, 24):
base, grupos, top = asignacion(random.Random(100 + tareas), tareas=tareas, turnos=tareas // 4, cap=4, p_conflicto=0.3)
F, nv = con_codificacion(base, grupos, top, 4, "propio")
t0 = time.perf_counter()
S = Motor(nv, F)
r = S.solve(max_decisions=3000)
t_motor = time.perf_counter() - t0
rc, t_cad, conf = resolver(F, "cadical153")
filas.append((tareas, nv, len(F), r, S.decisions, t_motor, rc, conf, t_cad))
print(f"{tareas:2d} tareas: {nv:4d} var., {len(F):5d} cl. | motor: {'SAT' if r else 'UNSAT' if r is False else 'sin acabar'} "
f"con {S.decisions} decisiones en {t_motor:.3f} s | CaDiCaL: {'SAT' if rc else 'UNSAT'} con {conf} conflictos en {t_cad:.4f} s")
fig, ax = plt.subplots(figsize=(6.4, 3.4))
ax.semilogy([f[0] for f in filas], [f[5] for f in filas], "o-", label="motor DPLL de la lección (Python)")
ax.semilogy([f[0] for f in filas], [max(f[8], 1e-5) for f in filas], "s-", label="CaDiCaL (C++ en WebAssembly)")
ax.set_xlabel("tareas")
ax.set_ylabel("tiempo (s, escala log.)")
ax.legend()
plt.show()Both curves grow, but in different worlds: with 24 tasks the engine (Python, no learning) needs 1137 decisions and a few seconds, CaDiCaL 305 conflicts and a few hundredths of a second. Part is language; the other, interesting part is what the engine does not yet do: learn from conflicts, jump back multiple levels and choose variables by activity. That is the next lesson.
Common mistakes
The lesson’s other errors (smallest CNF is not fastest; scanning all clauses during propagation; eliminating without reconstruction; reading WalkSAT failure as unsatisfiability) appear in their sections alongside the explanations.
Exercises
More than one answer may be correct.
Step 1 of 5. Suppose propagation reaches a fixed point without conflict. Why do alive values form arc-consistent domains?
propagate() in the engine. Process queue trail[qhead:]: for each newly assigned literal, traverse clauses watching its negation (watches[p], where p became false), move the watch to a nonfalse literal if available, propagate with assign(c[0], ci) if the clause becomes unit, and return the clause index on conflict (or None otherwise). Each clause’s two watches occupy list positions 0 and 1. Tests compare your fixed point with naive propagation in 1500 cases, check reasons and verify backtrack need not touch watches.class Motor:
def __init__(self, n, clauses):
self.n = n
self.clauses = [list(dict.fromkeys(c)) for c in clauses]
self.val = [0] * (n + 1)
self.level = [0] * (n + 1)
self.reason = [None] * (n + 1)
self.trail, self.lim, self.qhead = [], [], 0
self.watches = {}
self.unsat_at_root = False
for i, c in enumerate(self.clauses):
if len(c) == 0:
self.unsat_at_root = True
elif len(c) == 1:
if self.value(c[0]) == -1:
self.unsat_at_root = True
elif self.value(c[0]) == 0:
self.assign(c[0], i)
else:
self.watches.setdefault(c[0], []).append(i)
self.watches.setdefault(c[1], []).append(i)
def value(self, l):
v = self.val[abs(l)]
return v if l > 0 else -v
def assign(self, l, reason):
self.val[abs(l)] = 1 if l > 0 else -1
self.level[abs(l)] = len(self.lim)
self.reason[abs(l)] = reason
self.trail.append(l)
def decide(self, l):
self.lim.append(len(self.trail))
self.assign(l, None)
def backtrack(self, lvl):
if len(self.lim) <= lvl:
return
inicio = self.lim[lvl]
for l in self.trail[inicio:]:
self.val[abs(l)] = 0
self.reason[abs(l)] = None
del self.trail[inicio:]
del self.lim[lvl:]
self.qhead = len(self.trail)
def propagate(self):
# tu código: procesa trail[qhead:] con dos literales vigilados
self.qhead = len(self.trail)
return Nonecodifica_orden(lx, ux, ly, uy, c) for integers , and constraint . Return (n, clauses, p): n DIMACS variables numbered from 1, the clause list (order axioms and constraint), and function p(v, a) giving the variable for with v in 'x' or 'y' and . An empty clause means no solution. Tests enumerate all models and check one-to-one correspondence with solutions and that unit propagation deduces bounds.def codifica_orden(lx, ux, ly, uy, c):
ids = {}
for v, lo, hi in (("x", lx, ux), ("y", ly, uy)):
for a in range(lo, hi):
ids[v, a] = len(ids) + 1
p = lambda v, a: ids[v, a]
clauses = []
# tu código: axiomas de orden y las cláusulas de x + y <= c
return len(ids), clauses, pSummary
- Direct encoding propagates like forward checking; support like arc consistency; order like bounds consistency, with many fewer clauses. What propagation deduces matters, not size.
- Totalizers, cardinality networks and decision diagrams maintain generalized arc consistency; adders are compact but their propagation falls short in most states.
- The iterative engine stores trail, levels, reasons and propagation queue: undoing a level truncates the trail. Two watched literals restrict visits to clauses watching the falsified literal, and their invariant means backtracking changes no list.
- Bounded variable elimination replaces a variable’s clauses with non-tautological resolvents if no more numerous; the model is reconstructed by reversing the elimination stack.
- WalkSAT and probSAT choose within a false clause guided by break and noise; they are incomplete but dominate satisfiable random instances near the threshold.