Module contents
Lesson 11 of 23Core 110 min

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

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:

  1. 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.
  2. 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.
  3. 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:

DomainWhat is encodedDocumented case
Hardware verificationCircuit unrolled kk steps and negated property: a model is a failureBounded model checking (Biere, Cimatti, Clarke and Zhu, 1999)
Package managersOne variable per package version; dependencies and conflicts as clausesEclipse p2 resolves dependencies using Sat4j (Le Berre and Rapicault, 2009); deciding package installability is NP-complete (Mancinelli et al., 2006)
CryptanalysisBitwise operations of a hash function with fixed outputMD4 and MD5 collisions found with SAT solvers (Mironov and Zhang, 2006); CryptoMiniSat adds XOR clauses for such problems (Soos, Nohl and Castelluccia, 2009)
PlanningStates and actions at each step of a fixed-length planPlanning as satisfiability (Kautz and Selman, 1992)
Product configurationRules relating product optionsValidation of Mercedes-Benz passenger-car configuration data (Sinz, Kaiser and Küchlin, 2003)
MathematicsA finite combinatorial conjectureBoolean 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 kk.” This is where we begin.

From CSP to SAT: three encodings

A constraint satisfaction problem has variables vv with finite domains D(v)D(v) and constraints; here, binary ones: a constraint between uu and ww is a set of allowed pairs R⊆D(u)×D(w)R \subseteq D(u) \times D(w). For value aa of uu, its support in ww is sop⁡(a)={b∈D(w):(a,b)∈R}\operatorname{sop}(a) = \{b \in D(w) : (a, b) \in R\}. 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 x+y≤cx + y \le c each clause is (x≤a−1)∨(y≤c−a)(x \le a - 1) \lor (y \le c - a): “if x≥ax \ge a, then y≤c−ay \le c - a.” And x<yx < y, namely x−y≤−1x - y \le -1, gives (x≤a−1)∨¬(y≤a)(x \le a - 1) \lor \lnot(y \le a): “if x≥ax \ge a, then y≥a+1y \ge a + 1.” 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: x,y∈{1,…,6}x, y \in \{1, \dots, 6\} with x<yx < y and x+y=7x + y = 7, whose solutions are (1,6)(1, 6), (2,5)(2, 5) and (3,4)(3, 4).

InteractiveThree encodings, three propagations

Constraint network and AC-3

x < yx + y = 7xy
x
y

Final domains after AC-3: x ∈ {1, 2, 3, 4, 5}, y ∈ {2, 3, 4, 5, 6}

CNF direct and unit propagation

12 variables, 65 clauses: 2 at least one, 30 at most one, 33 conflict

x
y
Propagation deduces nothing.
  • removed by you
  • removed by AC-3
  • removed by unit propagation
  • fixed value
Encoding
When selecting a value
AC-3 removes2 values
Unit propagation (direct) removes0 values
Variables / clauses excluding yours: direct · support · order12/65 · 12/56 · 10/24
AC-3 removes x = 6, y = 1 but unit propagation does not (red ring).
Left: the constraint network and what AC-3 removes (red); right: the chosen encoding's CNF and what unit propagation derives (orange), with a trace of firing clauses. Initially, with direct encoding, AC-3 already removes x=6x = 6 and y=1y = 1, while propagation deduces nothing. Switch to support encoding. Return to direct and assign x=2x = 2: now it propagates. Then try ‘Bound: remove y=6y = 6’ and ‘Hole: remove y=4y = 4’ with order encoding: which does it see?

What you just saw has a name, and all three results are proven.

The first point follows from clause shape. A conflict clause ¬xu,a∨¬xw,b\lnot x_{u,a} \lor \lnot x_{w,b} can become unit only when one literal is false, namely when xu,ax_{u,a} or xw,bx_{w,b} is true, which occurs only when the variable is assigned (directly or because ALO leaves one value). A value with no support, like x=6x = 6 in the example, never triggers anything: no clause says “x=6x = 6 needs something.” Support encoding says exactly that: the x=6x = 6 clause with x<yx < y is ¬xx,6\lnot x_{x,6}, 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 xx‘s lower bound rises to aa, literal (x≤a−1)(x \le a - 1) is false and clause (x≤a−1)∨(y≤c−a)(x \le a - 1) \lor (y \le c - a) is unit: it deduces upper bound y≤c−ay \le c - a, precisely what interval propagation with x+y≤cx + y \le c would do; order axioms copy that bound to every py,bp_{y,b} with b≥c−ab \ge c - a. Conversely, every propagated literal is a bound implied by a clause, so nothing extra is deduced. A hole is a clause (y≤3)∨¬(y≤4)(y \le 3) \lor \lnot(y \le 4) acting only when a bound reaches it: hence removing y=4y = 4 makes AC-3 remove x=3x = 3 but order encoding does not.

Size moves opposite to strength. For a binary constraint with domains of size dd, direct encoding has one binary clause per forbidden pair (up to d2d^2), support has 2d2d clauses of up to d+1d + 1 literals, and order needs O(d)\bigO(d) binary clauses for x+y≤cx + y \le c plus d−2d - 2 axioms per variable, with d−1d - 1 variables per integer instead of dd. 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.

[ ]Direct and support encodings in DIMACSBrowser
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 x∈{2,4}x \in \{2, 4\}, y∈{3,5}y \in \{3, 5\}. Decoding by reading “the true value” of each variable yields x=4x = 4, y=5y = 5, violating x+y=7x + y = 7.

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.

[ ]Propagation versus AC-3, value by valueBrowser
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:

[ ]Order encoding and bounds consistencyBrowser
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 −3-3 and 22) unit propagation deduces exactly the same bounds as interval propagation after tightening a random bound.

Cardinality and pseudo-Boolean constraints

“At most kk of these nn variables” appears everywhere: shift capacities, machine counts, change budgets. In cardinality encoding you saw two basic solutions: without auxiliaries, one clause per subset of k+1k + 1 variables, (nk+1)\binom{n}{k+1} total; and Sinz’s sequential counter, with 2nk+n−3k−12nk + n - 3k - 1 clauses and (n−1)k(n - 1)k 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 kk,” GAC means something concrete: once kk inputs are true, propagation sets all others false, and with k+1k + 1 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 r1,…,rmr_1, \dots, r_m meaning “at least tt of my inputs are true.” Leaves are xix_i themselves. A node with children whose outputs are a1,…,apa_1, \dots, a_p and b1,…,bqb_1, \dots, b_q adds: if at least ii on the left and jj on the right are true, at least i+ji + j at the node are true,

¬ai∨¬bj∨ri+j,0≤i≤p, 0≤j≤q, 1≤i+j≤m,\lnot a_i \lor \lnot b_j \lor r_{i+j}, \qquad 0 \le i \le p,\ 0 \le j \le q,\ 1 \le i + j \le m,

where a0a_0 and b0b_0 are understood true and their literals omitted. For “at most kk,” add root unit ¬rk+1\lnot r_{k+1}. The original stores all outputs (mm equal to the segment’s input count); the truncated version keeps m=min⁡(taman˜o,k+1)m = \min(\text{tamaño}, k + 1), since distinguishing “k+1k + 1” from “more than k+1k + 1” is unnecessary. For “at least kk” use clauses in the other direction, ai+1∨bj+1∨¬ri+j+1a_{i+1} \lor b_{j+1} \lor \lnot r_{i+j+1}.

InteractiveInside the totalizer
1x10x220x31x4240x51x620x70x8248¬r4
step 24 / 24

Step 24: propagation forces x7 = 0.

  • true “at least t” bit
  • false bit
  • input forced to 0 by propagation
  • bound: the root’s k + 1 bit is false
8
3
Inputs at 1 · free · forced to 03 · 5 · 5
Full totalizer (GAC): aux. · clauses24 · 53
Truncated totalizer (GAC): aux. · clauses20 · 43
Sinz sequential counter (GAC): aux. · clauses21 · 46
No auxiliaries (GAC): C(8, 4) clauses70
Exactly k = 3 inputs are 1 and propagation forces the 5 free ones to 0: generalized arc consistency.
Unary-counter tree for ‘at most kk’. Each row is a node: cell tt lights when propagation deduces at least tt inputs are true, and is crossed out when it deduces otherwise. Initially exactly k=3k = 3 inputs are 1 and propagation has already descended from root bound ¬r4\lnot r_4 to the leaves: all five free inputs are forced to 0. Replay the deductions (first upward, then downward). Turn an input off, turn one more on, move kk and compare size readings with the sequential counter and encoding without auxiliaries.
Proof

Fix a partial input assignment and let c(ν)c(\nu) count true inputs below node ν\nu.

Upward. Induction from leaves makes outputs rtr_t of ν\nu true for every t≤min⁡(c(ν),m)t \le \min(c(\nu), m). At a leaf this is the hypothesis. At an internal node, if t≤min⁡(c(ν),m)t \le \min(c(\nu), m), write t=i+jt = i + j with i≤min⁡(cL,p)i \le \min(c_L, p) and j≤min⁡(cR,q)j \le \min(c_R, q) (possible because cL+cR=c(ν)c_L + c_R = c(\nu) and, if a child is truncated, its pp is already at least k+1≥mk + 1 \ge m); by induction aia_i and bjb_j are true and clause ¬ai∨¬bj∨rt\lnot a_i \lor \lnot b_j \lor r_t forces rtr_t. In particular, with c(raıˊz)≥k+1c(\text{raíz}) \ge k + 1 propagation makes rk+1r_{k+1} true and clashes with ¬rk+1\lnot r_{k+1}: conflict.

Downward. Suppose c(raıˊz)=kc(\text{raíz}) = k. Inducting from the root, for every node ν\nu with c(ν)+1≤mc(\nu) + 1 \le m propagation sets output rc(ν)+1r_{c(\nu)+1} false. At the root this is the unit clause. At an internal node with rc+1r_{c+1} false, the left child has acLa_{c_L} true by the upward pass (or cL=0c_L = 0 and the literal is absent), and clause ¬acL∨¬bcR+1∨rc+1\lnot a_{c_L} \lor \lnot b_{c_R + 1} \lor r_{c+1}, present because cL+cR+1=c+1≤mc_L + c_R + 1 = c + 1 \le m, makes ¬bcR+1\lnot b_{c_R+1} unit; likewise with roles swapped. If all a child’s inputs are true, no c+1c + 1 output needs to be set false. Reaching a free leaf, c=0c = 0 and its “output 1,” the input itself, becomes false.

Finally, propagation never deduces a falsehood, because all clauses follow from counter semantics. Thus with c<kc < k true it deduces nothing about inputs (none is implied), with c=kc = k it forces all remaining inputs to 0, and with c>kc > k it reaches conflict.

∎

Size follows by counting levels. In the full version, the level whose nodes cover ss inputs has n/sn/s nodes, each with ss outputs and about (s/2+1)2(s/2 + 1)^2 clauses: nn variables and on the order of ns/4ns/4 clauses per level, i.e. O(nlog⁡n)\bigO(n \log n) variables and O(n2)\bigO(n^2) clauses total, as Bailleux and Boufkhad give. Truncated, levels with s>ks > k contribute at most (n/s)(k+2)2(n/s)(k + 2)^2 clauses, a geometric series, and totals drop to O(nk)\bigO(nk) clauses and O(nlog⁡k)\bigO(n \log k) variables. With n=100n = 100 and k=5k = 5, 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 (1006)≈1.19×109\binom{100}{6} \approx 1.19 \times 10^9 clauses.

Asín, Nieuwenhuis, Oliveras and Rodríguez-Carbonell’s (2011) cardinality networks reduce clauses and variables to O(nlog⁡2k)\bigO(n \log^2 k) while maintaining GAC: they use merge networks computing only the first sorted outputs. Asymptotically, for large kk they grow far less than the O(nk)\bigO(nk) clauses of the truncated totalizer and sequential counter.

Pseudo-Boolean constraints

A pseudo-Boolean (PB) constraint is ∑iwixi≤K\sum_i w_i x_i \le K 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 (i,s)(i, s) means “what remains from xix_i fits slack ss.” Its low child is (i+1,s)(i + 1, s) and high child (i+1,s−wi)(i + 1, s - w_i); nodes with s<0s < 0 are the false terminal, and those whose ss is at least the sum of remaining weights the true terminal. Two clauses per node suffice: ¬n∨nbajo\lnot n \lor n_{\text{bajo}} and ¬n∨¬xi∨nalto\lnot n \lor \lnot x_i \lor n_{\text{alto}}. 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 ∑iwixi\sum_i w_i x_i 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 TT be the true-input set and Ri(s)R_i(s) the assertion “∑l≥i, l∈Twl>s\sum_{l \ge i,\, l \in T} w_l > s”: what is already 1 from xix_i does not fit slack ss.

Falsity upward. Every node (i,s)(i, s) with Ri(s)R_i(s) becomes false. Induct backward: if s<0s < 0 it is the false terminal; the true terminal cannot satisfy Ri(s)R_i(s) because its ss covers all remaining weights. If xi∈Tx_i \in T, high child (i+1,s−wi)(i + 1, s - w_i) satisfies Ri+1(s−wi)R_{i+1}(s - w_i), is false by induction, and ¬n∨¬xi∨nalto\lnot n \lor \lnot x_i \lor n_{\text{alto}} makes nn false. If xi∉Tx_i \notin T, low child (i+1,s)(i + 1, s) satisfies Ri+1(s)R_{i+1}(s) and clause ¬n∨nbajo\lnot n \lor n_{\text{bajo}} makes nn false.

Truth downward. The root is true, and from each true node (i,s)(i, s) propagation makes its low child true and, if xi∈Tx_i \in T, its high child. Thus for every jj node (j,sj)(j, s_j) with sj=K−∑l<j, l∈Twls_j = K - \sum_{l < j,\, l \in T} w_l is true.

If ∑Tw>K\sum_{T} w > K, the root satisfies R1(K)R_1(K) and is both false and true: conflict. Otherwise let xjx_j be free and setting it to 1 violate the constraint, namely wj+∑l>j, l∈Twl>sjw_j + \sum_{l > j,\, l \in T} w_l > s_j. Then high child (j+1,sj−wj)(j + 1, s_j - w_j) satisfies Rj+1R_{j+1} and is false, node (j,sj)(j, s_j) is true, and clause ¬n∨¬xj∨nalto\lnot n \lor \lnot x_j \lor n_{\text{alto}} makes ¬xj\lnot x_j 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:

[ ]Totalizer, decision diagram and adders: which maintains GAC?Browser
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 5y1+4y2+3y3+3y4+2y5+y6≤95y_1 + 4y_2 + 3y_3 + 3y_4 + 2y_5 + y_6 \le 9 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 ≥2\ge 2 cannot be unit or conflicting while it has two nonfalse literals. Watching two suffices.

InteractiveWatched literals
Trail:level 1: x₁
C1¬x₁x₂x₃x₄moves the watch
C2¬x₁¬x₂x₅moves the watch
C3¬x₂¬x₅x₆
C4x₁x₃x₅x₆satisfied
C5¬x₃¬x₄¬x₆
C6¬x₅¬x₆x₃x₄
C7x₂¬x₄x₅¬x₆
C8¬x₂¬x₃x₄¬x₆
  • watched literal (thick border)
  • true
  • visited: moves watch
  • visited: propagates
  • visited: conflict
Decide a literal
Clause visits: watched literals2
Visits: per-clause counters3
Watches moved2
Last undo: watched · countersno undo yet
You decide x₁ = 1.
Eight clauses over x1,…,x6x_1, \dots, x_6; thick-bordered literals are watched. Initially there is already a decision, x1=1x_1 = 1: only the two clauses watching ¬x1\lnot x_1 (C1 and C2) were visited, and both moved their watches. Decide x2x_2 and watch the chain: C2 becomes unit and propagates x5x_5, then C3 propagates x6x_6. Compare visits with the counter scheme, undo the level (how many watches change?) and find a decision sequence leading to conflict.

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 ww is handled on becoming false: either replaced by a nonfalse literal, or the other watch uu was already true (assigned earlier, hence at level ≤\le than ww), or uu is propagated then at the same level as ww. Undoing to level LL unassigns exactly variables at level >L> L. Watches moved in undone levels point to literals that were nonfalse when moved and remain so. If false watch ww had level >L> L, it becomes free and nothing is required. If it had level ≤L\le L, it remains false, but then nivel⁡(u)≤nivel⁡(w)≤L\operatorname{nivel}(u) \le \operatorname{nivel}(w) \le L and uu 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

[ ]Iterative DPLL with trail, levels and watchesBrowser
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.

[ ]Watches versus counters on the same treeBrowser
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.

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 C⊆DC \subseteq D, clause DD is redundant: every model of CC models DD.
  • Self-subsuming resolution. If C=C′∨ℓC = C' \lor \ell and D=D′∨¬ℓD = D' \lor \lnot\ell with C′⊆D′C' \subseteq D', their resolvent is D′D', subsuming DD: replace DD by D′D', one literal shorter.
  • Bounded variable elimination (BVE). Davis–Putnam elimination from resolution, with a brake. Let PP be clauses containing xx and NN those containing ¬x\lnot x. Replace P∪NP \cup N with all non-tautological resolvents {(C∖{x})∪(D∖{¬x}):C∈P,D∈N}\{(C \setminus \{x\}) \cup (D \setminus \{\lnot x\}) : C \in P, D \in N\} only if their number does not exceed ∣P∣+∣N∣\abs{P} + \abs{N}.
  • Failed literal probing. If propagating ℓ\ell leads to conflict, ¬ℓ\lnot\ell follows from the formula and is added as a unit.
Proof

If FF has a model, it satisfies all resolvents (resolution is sound), hence models F′F'. The converse follows from the second part. Clauses of F∖(P∪N)F \setminus (P \cup N) do not mention xx and μ′\mu' satisfies them as μ\mu does. If μ′(x)=0\mu'(x) = 0, every clause of PP has a true literal other than xx, and clauses of NN are satisfied by ¬x\lnot x. If μ′(x)=1\mu'(x) = 1, clauses of PP are satisfied by xx; suppose some D∈ND \in N had all literals other than ¬x\lnot x false. With the C∈PC \in P that caused x=1x = 1, resolvent (C∖{x})∪(D∖{¬x})(C \setminus \{x\}) \cup (D \setminus \{\lnot x\}) would be false under μ\mu. If tautological it cannot be false; otherwise it is in F′F' and μ\mu satisfies it. Contradiction either way.

∎

The proof says exactly what to save: each eliminated variable’s original clauses (PP 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 x↔(a∧b)x \leftrightarrow (a \land b) is defined by its three gate clauses, resolvents between two gate clauses are tautological. Eén and Biere go further: when xx is gate-defined, resolvents between the gate and uses of xx suffice, and resolvents between two uses are redundant (elimination by substitution). Eliminating xx then substitutes the definition, as by hand.

InteractiveBounded elimination's accounting

The first three clauses are the Tseitin definition of x ↔ (a ∧ b). Formula: (¬x ∨ a) ∧ (¬x ∨ b) ∧ (x ∨ ¬a ∨ ¬b) ∧ (x ∨ c) ∧ (x ∨ ¬d ∨ e) ∧ (¬x ∨ ¬c ∨ d) ∧ (a ∨ c ∨ e) ∧ (¬b ∨ ¬e)

with x ↓ · with ¬x →
(¬x ∨ a)
(¬x ∨ b)
(¬x ∨ ¬c ∨ d)
(x ∨ ¬a ∨ ¬b)
(a ∨ ¬a ∨ ¬b)
(¬a ∨ b ∨ ¬b)
(¬a ∨ ¬b ∨ ¬c ∨ d)
(x ∨ c)
(a ∨ c)
(b ∨ c)
(c ∨ ¬c ∨ d)
(x ∨ ¬d ∨ e)
(a ∨ ¬d ∨ e)
(b ∨ ¬d ∨ e)
(¬c ∨ d ∨ ¬d ∨ e)
  • resolvent to add
  • tautological: not added
Formula
Variable to eliminate
Clauses with x and with ¬x3 + 3 = 6
Resolvents: all · tautological · distinct useful9 · 4 · 5
Eliminated: 6 clauses leave and 5 enter. To reconstruct the model, keep the 3 clauses containing x.
Rows are clauses containing the chosen variable and columns those containing its negation; each cell is their resolvent, crossed out if tautological. With the ‘With a gate’ formula and variable xx, four of nine resolvents are tautological (two from the Tseitin definition of x↔(a∧b)x \leftrightarrow (a \land b) with itself): 6 clauses leave and 5 enter, so xx is eliminated and the formula shrinks. Switch to the unstructured formula with the same xx and try other variables: which are eliminated and why?

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:

[ ]Subsumption, self-subsumption, bounded elimination and reconstructionBrowser
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 vv, its break is the number of clauses made false by flipping it (those where vv 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 cb=2.38c_b = 2.38 on 1000-variable instances and cb=2.16c_b = 2.16 on 10 000-variable instances, with ε=1\varepsilon = 1. For WalkSAT on 3-SAT they used optimal noise p=0.567p = 0.567 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 O((4/3)n)\bigO((4/3)^n) 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 5×1055 \times 10^5 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 nn 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.

InteractiveWalkSAT near the threshold
Experiment
0.50
6
DPLL budget (decisions)
Calculation progress0 %
Proven unsatisfiable by DPLL · solved by WalkSAT0 · 0
Satisfiable with α ≥ 4.1: DPLL / WalkSAT work (median)calculating
Satisfiable with α ≥ 4.1 · not solved by WalkSAT0 · 0
Formulas where DPLL exhausts its budgetNaN
Waiting for DPLL to prove an unsatisfiable formula.
Real browser computation: random 3-SAT formulas with n=200n = 200 and m=αnm = \alpha n, solved by the lesson's DPLL (trail, levels and watches) and WalkSAT. Effort is clause visits, the same unit for both. Above, fractions DPLL proves satisfiable or unsatisfiable and WalkSAT solves; below, median effort on satisfiable formulas, logarithmic scale. Notice WalkSAT never solves one DPLL proves unsatisfiable, and how much less work it does on satisfiable formulas with α≥4.1\alpha \ge 4.1. Switch to the noise sweep: where is the optimum? Lower DPLL's budget to 5000 decisions: which formulas remain undecided?

Lab 2 continued: WalkSAT and probSAT

First, three satisfiable formulas with n=100n = 100 and α=4.2\alpha = 4.2, filtered using the engine (which already finds them costly):

[ ]Local search: incremental state, WalkSAT and probSATBrowser
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
[ ]Three satisfiable formulas near the thresholdBrowser
# 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:

[ ]WalkSAT noiseBrowser
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 p=0p = 0 it solves none of 6 runs (pure greedy is stuck in local minima), with p=0.57p = 0.57 it solves 5 of 6 at a median 3048 flips, and with p=1p = 1 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.

[ ]probSAT and what local search cannot doBrowser
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 cb=0c_b = 0 probSAT is a random walk inside the clause and solves none; with cb=2.38c_b = 2.38, 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 α=6\alpha = 6 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.

[ ]PySAT: five capacity encodings and two solversBrowser
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 k+1k + 1 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:

[ ]The lesson engine versus CaDiCaLBrowser
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

QuizA chain of inequalities
A CSP has x,y,z∈{1,2,3}x, y, z \in \{1, 2, 3\} with x<yx < y and y<zy < z, nothing assigned. Which claims about unit propagation before any decision are true?

More than one answer may be correct.

NumericConflicts for an inequality
Count the direct-encoding clauses for x≠yx \neq y with domains {1,2,3,4}\{1, 2, 3, 4\}, excluding at-least-one and at-most-one clauses.
NumericSupports for an inequality
Count support-encoding clauses for the same x≠yx \neq y constraint with domains {1,2,3,4}\{1, 2, 3, 4\}, again excluding ALO and AMO.
ProofSupport encoding establishes arc consistency
Prove: Let a binary CSP have current domains DD (removed values are unit clauses ¬xv,a\lnot x_{v,a}), and D∗D^* its arc-consistent closure, the greatest arc-consistent subdomain of DD. Under support encoding, if unit propagation ends without conflict, nonfalse values are exactly D∗D^*; it reaches conflict iff D∗D^* empties a domain. Direct encoding does not do this.
0
Call values aa of vv ‘alive’ when their variable xv,ax_{v,a} is not false. Show two inclusions: alive ⊆D∗\subseteq D^* and D∗⊆D^* \subseteq alive.

Step 1 of 5. Suppose propagation reaches a fixed point without conflict. Why do alive values form arc-consistent domains?

NumericA small totalizer
Count clauses of the totalizer truncated to k+1k + 1 outputs for ‘at most 1 of x1,x2,x3,x4x_1, x_2, x_3, x_4’, with a balanced tree (two two-leaf nodes and root), including the bound's unit clause.
QuizCan x be eliminated?
Variable xx appears in three positive clauses, (x∨a∨b)(x \lor a \lor b), (x∨¬a∨c)(x \lor \lnot a \lor c) and (x∨¬b∨¬c)(x \lor \lnot b \lor \lnot c), and four negative ones, (¬x∨a)(\lnot x \lor a), (¬x∨¬a∨b)(\lnot x \lor \lnot a \lor b), (¬x∨c∨d)(\lnot x \lor c \lor d) and (¬x∨¬b∨¬d)(\lnot x \lor \lnot b \lor \lnot d). Under bounded elimination's criterion (do not increase clause count), is xx eliminated?
QuizUndoing with watches
Your two-watched-literal engine is at level 5 and undoes to level 2. What must it do to watch lists?
QuizA million flips
WalkSAT with noise p=0.5p = 0.5 finds no model of your formula after 10610^6 flips. How do you determine whether it is unsatisfiable?
CodePropagate with two watched literals
Complete 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 None
Shift+Enter to run
CodeOrder encoding of a sum
Implement codifica_orden(lx, ux, ly, uy, c) for integers x∈[lx,ux]x \in [l_x, u_x], y∈[ly,uy]y \in [l_y, u_y] and constraint x+y≤cx + y \le c. 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 v≤av \le a with v in 'x' or 'y' and lv≤a<uvl_v \le a < u_v. 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, p
Shift+Enter to run

Summary

Key idea
A useful SAT solver is a chain of engineering decisions: encodings whose unit propagation does arc-consistency work, an engine with trail and watches where undoing costs nothing, preprocessing that eliminates what it can without losing the model, and local search to quickly find what exists.
  • 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.