Satisfiability: CNF, the Tseitin transformation and problem encodings
SAT as a problem and modeling language: certificates, linear-size Tseitin conversion to CNF, encodings of practical problems (coloring, Sudoku, bounded-horizon planning), cardinality constraints, the polynomial cases 2-SAT and Horn-SAT, and bounded verification of programs and circuits. This bridges to the SAT and SMT solvers of m10.
After this lesson you can
- Explain SAT, its certificates, and the relation between validity and unsatisfiability.
- Apply the Tseitin transformation and prove that it preserves satisfiability with linear size.
- Encode combinatorial problems in CNF with efficient cardinality constraints.
- Solve 2-SAT with an implication graph and Horn-SAT with unit propagation.
- Formulate circuit equivalence and bounded program verification as SAT instances.
Before you start
Motivation: one solver, many problems
A SAT solver does one thing: it receives a list of clauses over Boolean variables and returns an assignment satisfying them all, or reports that none exists. This seems modest. But that one question, well formulated, answers many others:
- Planning. Is there a sequence of at most 20 actions taking a robotic warehouse from its initial state to its goal? Use a variable for every fact and action at every time, and clauses saying what each action requires and changes.
- Hardware verification. After optimizing a multiplier, does it still compute the same result as the original for all possible inputs? Ask whether an input exists on which they differ.
- Finding software bugs. Can this loop, executed at most 50 times, overflow an index? Tools such as CBMC translate C programs into formulas and ask the solver for an execution violating the assertion.
- Package dependencies. Choosing compatible versions of hundreds of packages means satisfying constraints such as “if I install A 2.1, I need B ≥ 1.4 and not C.” DNF and zypper’s dependency resolver, libsolv, is a SAT solver.
- Mathematics. In 2016 Heule, Kullmann, and Marek used a solver to prove that the integers from 1 to 7825 cannot be colored in two colors without a monochromatic Pythagorean triple, while those up to 7824 can. The unsatisfiability certificate occupied about 200 TB (Heule, Kullmann and Marek, 2016).
There are direct connections to what you will build later. Formal verification of ReLU neural networks is formulated as SAT, SMT, or integer programming (covered in m30), and language-model agents increasingly delegate to an exact solver when an answer must be correct and checkable, such as an executable verifier.
In every case the human work is modeling: choose variables with precise meanings and write constraints as clauses so every solution corresponds to an answer and every answer to a solution. This lesson covers exactly that: what the problem is, how to convert any formula or circuit to CNF without size explosion, how to encode combinatorial problems and cardinality constraints, which cases are solvable in linear time, and how SAT verifies hardware and software. The next lesson, resolution and DPLL, opens the solver’s box.
The SAT problem
Recall conjunctive normal form from lesson 1: a literal is a variable or its negation ; a clause is a disjunction of literals, treated as a set; a CNF is a conjunction of clauses, treated as a set of clauses. An assignment satisfies a clause if it makes at least one literal true, and satisfies the CNF if it satisfies every clause.
Three observations establish the setting.
A model is a cheap certificate. Checking that satisfies costs , where is the total number of literal occurrences: scan each clause until a true literal is found. Finding a model can be hard; verifying one is not. Thus a solver reporting “satisfiable” need not be trusted: it gives the assignment and you check it.
No short unsatisfiability certificates are known. To convince you there is no model, the solver cannot show an assignment. It can give a proof (a resolution refutation, covered next lesson, or its industrial version, DRAT proofs), but no proof system is known in which every unsatisfiable formula has a polynomial-size proof: existence of one is equivalent to (Cook and Reckhow, 1979). The 200 TB Pythagorean certificate is not anomalous: in the worst case that is to be expected.
Validity and consequence reduce to unsatisfiability. By lesson 1, is valid if and only if is unsatisfiable, and if and only if is unsatisfiable. Thus a SAT solver is also a prover: negate a claim and ask for a model; if none exists, it is proved.
The DIMACS format
Solvers read the same text format, DIMACS CNF. Variables are integers ; literal is written i and , -i; each clause is a line ending in 0; header p cnf n m declares variables and clauses, and lines starting with c are comments.
c (p ∨ ¬q) ∧ (q ∨ r) ∧ (¬p ∨ ¬r) ∧ (q ∨ ¬r)
p cnf 3 4
1 -2 0
2 3 0
-1 -3 0
2 -3 0
A solver responds s SATISFIABLE followed by v 1 2 -3 0 (model , ), or s UNSATISFIABLE. The simplicity is deliberate: anything you want solved must reach this form, and the rest of the lesson covers how to get there correctly.
The hard and the easy
The proof of the Cook–Levin theorem and the theory of NP-completeness are in m08. Two practical consequences matter here. First, no polynomial-time algorithm is expected for SAT in general, and the best known worst-case algorithms for 3-SAT remain exponential (on the order of ). Second, more surprisingly, modern solvers (CDCL, covered in conflict analysis) routinely solve industrial instances with hundreds of thousands of variables. Worst cases exist, but structured problems rarely are worst cases. Below are two islands without this difficulty: 2-SAT and Horn-SAT are decided in linear time.
Tseitin transformation: CNF without explosion
Almost nothing arrives in CNF. A circuit, a specification, a program condition: all are arbitrary formulas. Lesson 1’s conversion using De Morgan’s laws and distributivity produces an equivalent CNF, but there you proved has no equivalent CNF with fewer than clauses. Parity is worse: every equivalent CNF needs its clauses of literals, one for each even-parity assignment it must exclude (any clause with fewer than literals would also exclude odd-parity assignments).
The way out is to give up equivalence and retain what SAT needs. G. S. Tseitin’s idea (1968) is to give each subformula a name: a new variable per binary connective, with a few clauses forcing to equal the subformula.
For an AND gate, decomposes into two implications, each already nearly in CNF:
The other connectives follow similarly:
| Gate | Clauses for | Clauses for |
|---|---|---|
| , | ||
| , | ||
| , | , | |
| , |
Negation needs no variable: is already a literal, so a negated subformula is represented by its gate’s negated literal. Finally add the unit clause containing the root variable, requiring the entire formula to be true.
Proof
(1) Use structural induction on subformulas, leaves to root. For a variable, and there is no choice. For , equals by hypothesis. For , the defining clauses are equivalent to ; since and already have forced values and , the only choice of satisfying them is . Identical subformulas have the same forced value, so sharing the variable causes no conflict.
(2) Any model of satisfies the definitions, so by (1) it equals the extension of its restriction , and the root clause says . Conversely, if , extension satisfies the definitions and . Correspondence is a bijection between models.
(3) Each binary connective contributes at most 4 clauses of at most 3 literals (the table), and the root contributes one; negations contribute nothing. A traversal of the tree of with a dictionary to detect repeated subformulas constructs everything in linear time.
∎Three consequences used daily:
- SAT reduces to 3-SAT in linear time. Every clause of has at most 3 literals. This is the reduction of SAT to 3-SAT.
- Circuits translate directly. A Boolean circuit is a DAG of gates: one variable per gate yields a CNF linear in circuit size, which may be exponentially smaller than the equivalent formula tree. Hardware verifiers do this, usually over AND-inverter graphs (AIGs) with shared substructures.
- Model count is preserved. By (2), counting models of means counting those of . This underlies model counters used in probabilistic inference.
Plaisted–Greenbaum: half the clauses
If a subformula occurs only under an even number of negations (positive polarity), half suffices: the solver may set when the subformula is true, but that never helps satisfy the root because is monotone increasing in that subformula. With negative polarity the other half suffices, and with both (under or ) both are required. This is Plaisted and Greenbaum’s encoding (1986). It remains equisatisfiable with fewer clauses, but no longer preserves model count: in the figure, “mixed connectives” goes from 5 models to 7. In practice, the saving in clauses is sometimes offset by worse propagation, and many solvers prefer the full version.
Encoding problems
Encoding a problem in SAT always has three steps: choose variables and their meanings, write each constraint as clauses, and decode the model. Encoding problems in SAT is an art with rules: correctness is proved (each model is a solution and each solution yields a model), and efficiency depends on how much unit propagation deduces from clauses. Every solver repeatedly applies this inference rule between decisions: if all literals of a clause are false except one, the last must be true; if all are false, there is a conflict. The next lesson studies it in depth; here it suffices to know it is cheap and chains.
Graph coloring
To decide whether a graph admits a coloring with colors, use a variable per (vertex, color) pair, meaning “ has color ,” and two families:
There are clauses. Notice what is not needed: saying each vertex has at most one color. If a model gives a vertex several colors, keeping any one still satisfies edge clauses, because removing a color cannot create a conflict. Adding that family is not an error, but is redundant. The Petersen graph, for example, gives an unsatisfiable CNF with 2 colors (it has odd cycles) and a satisfiable one with 3.
N queens and Sudoku
To place nonattacking queens, says “there is a queen in row and column .” Each row has at least one queen (one -literal clause), and each row, column, and diagonal has at most one (one binary clause per pair of squares). Counting, a diagonal of length contributes pairs, and the staircase identity gives , so the total is
Sudoku uses , “cell contains ”: variables. There are several candidate families: each cell has at least and at most one value; every row, column, and block contains each value at least and at most once; and clues as unit clauses. Are they all needed? No.
Proof
Fix a row and count in two ways the number of (cell, value) pairs in that row with . By cells: each of the 9 cells has at least one value, so . By values: each of the 9 values appears at most once in the row, so . Thus , and since each cell contributes at least 1 and the total is 9, each contributes exactly 1. By the same equality, each value contributes exactly 1: it appears. This is the pigeonhole principle in both directions. The same argument works for columns and blocks.
∎The minimal encoding has clauses and the extended encoding, with redundant families, . Yet the extended version is often better for the solver: the clause “5 is in some cell of row 3” becomes unit as soon as the other cells are ruled out, directly propagating the rule enthusiasts call “hidden single.” In the minimal version this deduction needs the theorem’s counting argument, which unit propagation cannot perform. General lesson: redundant clauses do not change the solution set, but can greatly change what the solver deduces without search.
Bounded-horizon planning
The same pattern works for problems with time. A planning problem has facts (the box is in room 2, the arm is free) and actions with preconditions and effects. Fix horizon and create variables , “fact is true at time ,” and , “action is executed at step .” Clauses state: the initial state (units at ), goal (units at ), each action implies its preconditions at () and effects at ( for additions, for deletions), at most one action per step, and frame axioms: if a fact changes between and , an action changing it was executed. For a fact becoming true, , and for one becoming false, . A model is a plan of at most actions (steps without action change nothing); if no model exists, no plan that short exists and one tries . This is SATPLAN’s idea (Kautz and Selman, 1992), revisited in planning as satisfiability. Forgetting frame axioms is the classic error: without them facts appear and disappear between steps and the solver finds impossible plans.
Breaking symmetries
An encoding is symmetric if some permutation of variables maps models to models. In coloring, permuting the colors is such a symmetry: every coloring has copies. If the instance is satisfiable this matters little, but if unsatisfiable the solver may have to refute each copy separately, multiplying worst-case search by . The remedy is to add clauses removing copies without eliminating every copy of any solution:
- In coloring, if is a clique, fix its colors: the first vertex of takes color 1, the second 2, and so on. Without a known clique, a weaker rule works: vertex (in a fixed order) may only use colors . This is correct because, renaming colors by first occurrence, vertex uses at most color number .
- In N queens, use left–right reflection: require the first-row queen in the left half (or center column, if is odd). With even , no solution is its own reflection, so the solution count is exactly halved.
- In the pigeonhole problem (put pigeons in holes), holes are interchangeable: pigeon may only go into holes .
The effect can be enormous. Pigeonhole is the extreme example: Haken proved in 1985 that every resolution refutation of has size exponential in (a proof complexity result), so no resolution-based solver can do well. With the symmetry breaking above, however, unit propagation refutes it without a single decision: pigeon 1 goes to hole 1, 2 to 2, and has nowhere to go. You will measure this below.
Cardinality constraints
“At least one,” “at most one,” and “exactly one” constraints appear in almost every encoding, and the general version, “at most of these variables,” in planning (at most machines at once), configuration, and optimization. Writing them well can determine whether a CNF fits in memory.
At least one is one clause: . Pairwise at most one consists of clauses : quadratic, with no fresh variables and the best possible propagation (as soon as one is true, all others become false). For at most , the direct generalization forbids each subset of true variables, with clauses: with and that is .
The clauses read as a unary adder circuit advancing left to right: the counter retains what it had (carry), rises one step when is true (addition), and the cutoff clause forbids being true when were already true earlier.
Proof
Write . If , extension satisfies every clause: carry because ; addition because and give ; units because ; and cutoff because and would give . Conversely, in any model induction on proves (addition and carry clauses push each step upward). If , let be the position of true variable number : then , hence and , and the cutoff clause of is false. For the second part, let be positions of true variables. Forward, and force by addition, and carry copies it rightward; thus for every , and cutoff at leaves unit. Backward, cutoff at gives , carry read backwards () takes it leftward, and at each addition read backwards ( and ) gives : in total for every . If (with ), then and , and the addition clause at , or if , leaves unit.
∎The table summarizes cost for “at most one” (), where the counter has clauses with auxiliaries:
| pairwise, | counter, | |
|---|---|---|
| 5 | 10 | 11 |
| 10 | 45 | 26 |
| 100 | 4950 | 296 |
| 1000 | 499 500 | 2996 |
Below pairwise encoding wins, and in practice it is used up to : binary clauses are cheapest to propagate. Many other encodings trade off clauses, variables, and propagation strength differently (commander, product, binary with auxiliaries, totalizers, sorting networks), and libraries provide them all. “At least ” is “at most ” of the negations, and “exactly ” is the conjunction of both.
Tractable cases: 2-SAT and Horn-SAT
2-SAT and the implication graph
If every clause has at most two literals, clause states exactly two implications: and . This turns the problem into a graph problem.
The graph has a symmetry governing everything: edge exists if and only if edge exists (both come from the same clause). Therefore there is a path if and only if there is a path . Every edge is an implication satisfied by every model: if is true in a model, is too, and by induction on length the same holds for paths.
Proof
If and share a component, paths and exist. In a model with , the first path forces ; with , and the second forces . There is no model.
Now suppose no variable shares a component with its negation. The condensation is a DAG and has a topological order; write for the position of the component of literal . If is an edge, (equal if in the same component). Assignment is well-defined because , and gives opposite values to and . It remains to show no edge has and , equivalent to all clauses being satisfied. Otherwise and . The symmetric edge gives , and chaining,
a contradiction. Tarjan’s algorithm computes components in and numbers them in reverse topological order, so no separate step is needed for .
∎Why does this work with two literals but not three? Resolving two binary clauses, and , gives another binary clause : it composes implications . There are possible binary clauses, so resolution closure is polynomial, and the graph computes it implicitly. With three-literal clauses, a resolvent of two can have four literals, and that growth opens the door to NP-completeness. The boundary is fine: maximizing the number of satisfied clauses of a 2-CNF (MAX-2-SAT) is already NP-hard.
Horn-SAT and the least model
Horn formulas are the logic of rules: Datalog, Prolog without negation, permission systems (“if you are an editor, you may publish”), and type inference. They are decided by the simplest imaginable algorithm: unit propagation from all false. Start every variable at 0; while a rule or fact has all premises at 1 and its conclusion at 0, set the conclusion to 1. If a constraint ever has all its premises at 1, the formula is unsatisfiable; if the process stops without that, the result is a model.
The proof is the lesson’s last guided exercise. The key idea is that every variable the algorithm sets to 1 is forced: true in every model, by induction on the order in which it is added. This gives both correctness of “unsatisfiable” and minimality. The least model is unique and is the intersection of all models, something absent for general formulas: has two minimal models, and . This same structure, extended to arithmetic, gives constrained Horn clauses used to verify programs today.
Bounded verification
Circuit equivalence with a miter
You have two circuits and with the same inputs and outputs and : the original and one produced by a synthesis tool, manual optimization, or compiler. Do they compute the same thing? With one cannot test all inputs. The standard construction is the miter: join corresponding outputs with XOR and combine them with OR,
and ask whether is satisfiable. If so, the model contains a concrete input on which the circuits differ: a counterexample that can be simulated and debugged. Otherwise they are equivalent, and the solver’s refutation is the proof. This is the practical version of the question from the BDD lesson; BDDs are canonical but may grow exponentially (multipliers are the typical case), and industry combines both techniques.
The modification “Majority: OR for XOR” illustrates something common in circuit optimization: in carry , can be replaced by without changing the function because the case where they differ () is already covered by the first term. Then the two terms are mutually exclusive, so the final OR can be replaced by XOR. Alone, the second change is a bug; together with the first, it is not. Reasoning by hand is fragile; the miter decides it.
Unrolling a system: BMC
A system evolving over time (a sequential circuit, a program with a loop, a protocol) is described by a state-variable vector , initial predicate , transition relation , and safety property that should always hold. Bounded model checking (BMC; Biere, Cimatti, Clarke, and Zhu, 1999) copies state variables times and asks about the formula
It is satisfiable if and only if an execution of at most steps violates the property, and the model is that execution step by step. In a program, integer variables are represented as bit vectors (32 Boolean variables per int), each operation as a circuit (adder, comparator), and the loop is unrolled times. This is how CBMC and related tools work.
An example you will implement: x = 0; repetir: x = x + 3 with 4-bit x (arithmetic modulo 16) and property . With , is unsatisfiable. With , the solver returns trace . The bug existed all along, but at 13 steps.
k-induction: the bridge to invariants
The usual way to go from “no bug through ” to “no bug ever” is induction. A property is an inductive invariant if it holds initially and is preserved at every step. Both conditions are SAT questions:
The step is checked from any state satisfying , not just reachable states. Thus a true property need not be inductive: in x = 0; repetir: x = x + 2, property is true (x is always even), but the step fails on unreachable state , which satisfies and goes to 15. This is exactly the problem of strengthening the induction hypothesis: strengthening to “x is even” makes the property inductive.
k-induction (Sheeran, Singh, and Stålmarck, 2000) generalizes the step: if holds in consecutive states linked by , it holds in the next. The base is . In the example, the step fails for (with odd chain as an induction counterexample) and holds for : eight consecutive odd numbers traverse all odd numbers modulo 16, including 15. Thus is 8-inductive, proved without inventing an invariant. Requiring path states to be distinct makes k-induction complete for finite systems, though the needed can be enormous; current methods such as IC3 (Bradley, 2011) incrementally construct the strengthened invariant with a SAT solver.
Implementation from scratch
Start with infrastructure: a class CNF with variables numbered as in DIMACS, reading and writing that format, a certificate checker, and a function solve delegating to sympy’s DPLL (satisfiable with algorithm="dpll2"). Passing CNF already encoded as integers avoids sympy rebuilding a symbolic expression with thousands of clauses.
from sympy import Symbol
from sympy.logic.inference import satisfiable
from sympy.assumptions.cnf import EncodedCNF
class CNF:
"""CNF con variables 1..n (convenio DIMACS): un literal es +v o -v."""
def __init__(self):
self.n = 0
self.clauses = []
self.names = {}
def new_var(self, name=None):
self.n += 1
if name is not None:
self.names[self.n] = name
return self.n
def add(self, clause):
self.clauses.append(list(clause))
def to_dimacs(self):
lines = [f"p cnf {self.n} {len(self.clauses)}"]
lines += [" ".join(map(str, c)) + " 0" for c in self.clauses]
return "\n".join(lines) + "\n"
@classmethod
def from_dimacs(cls, text):
f, lits = cls(), []
for line in text.splitlines():
line = line.strip()
if not line or line[0] in "c%":
continue
if line.startswith("p"):
f.n = int(line.split()[2])
continue
for tok in line.split():
if tok == "0":
f.add(lits)
lits = []
else:
lits.append(int(tok))
return f
def __repr__(self):
return f"CNF({self.n} variables, {len(self.clauses)} cláusulas)"
def satisfies(clauses, model):
"""model: conjunto de literales verdaderos. Mira cada literal una vez: tiempo lineal."""
return all(any(l in model for l in c) for c in clauses)
def solve(cnf):
"""DPLL de sympy (dpll2). Devuelve el modelo como conjunto de literales, o None si es insatisfacible."""
enc = EncodedCNF([set(c) for c in cnf.clauses], {Symbol(f"v{i}"): i for i in range(1, cnf.n + 1)})
m = satisfiable(enc, algorithm="dpll2")
if m is False:
return None
return {i if m.get(Symbol(f"v{i}"), False) else -i for i in range(1, cnf.n + 1)}
texto = """c (p ∨ ¬q) ∧ (q ∨ r) ∧ (¬p ∨ ¬r) ∧ (q ∨ ¬r)
p cnf 3 4
1 -2 0
2 3 0
-1 -3 0
2 -3 0
"""
F = CNF.from_dimacs(texto)
print(F, " ida y vuelta idéntica:", F.to_dimacs() == texto.split("\n", 1)[1])
m = solve(F)
print("modelo:", sorted(m, key=abs), " ¿certificado válido?", satisfies(F.clauses, m))
print("un certificado falso:", satisfies(F.clauses, {1, -2, 3}))
# validez = insatisfacibilidad de la negación: ((p → q) ∧ (q → r)) → (p → r)
G = CNF()
p, q, r = G.new_var("p"), G.new_var("q"), G.new_var("r")
for c in ([-p, q], [-q, r], [p], [-r]): # la negación del condicional, ya en CNF
G.add(c)
print("¿la negación del silogismo tiene modelo?", solve(G))Hypothetical syllogism is valid because its negation has no model. Now Tseitin on a tuple syntax tree with shared subformulas, and two checks: model count is preserved (by brute force on small instances), and size grows linearly compared with distribution of to_cnf.
from itertools import product
from sympy import symbols, Xor
from sympy.logic.boolalg import to_cnf
# cláusulas de definición g ↔ (a op b): tres para AND, OR y →; cuatro para XOR e IFF
GATE = {
"and": lambda g, a, b: [[-g, a], [-g, b], [g, -a, -b]],
"or": lambda g, a, b: [[-g, a, b], [g, -a], [g, -b]],
"xor": lambda g, a, b: [[-g, a, b], [-g, -a, -b], [g, -a, b], [g, a, -b]],
"iff": lambda g, a, b: [[-g, -a, b], [-g, a, -b], [g, a, b], [g, -a, -b]],
"imp": lambda g, a, b: [[-g, -a, b], [g, a], [g, -b]],
}
def tseitin(f):
"""f: árbol ('var', nombre) | ('not', f) | (op, f, g). Devuelve (cnf, {nombre: variable})."""
cnf, inputs, memo = CNF(), {}, {}
def lit(e):
if e[0] == "var":
if e[1] not in inputs:
inputs[e[1]] = cnf.new_var(e[1])
return inputs[e[1]]
if e[0] == "not":
return -lit(e[1]) # la negación no crea variable
a, b = lit(e[1]), lit(e[2])
if (e[0], a, b) not in memo: # subfórmulas idénticas comparten puerta
g = memo[(e[0], a, b)] = cnf.new_var()
for c in GATE[e[0]](g, a, b):
cnf.add(c)
return memo[(e[0], a, b)]
cnf.add([lit(f)]) # la raíz tiene que ser verdadera
return cnf, inputs
def evaluate(e, env):
if e[0] == "var":
return env[e[1]]
if e[0] == "not":
return not evaluate(e[1], env)
a, b = evaluate(e[1], env), evaluate(e[2], env)
return {"and": a and b, "or": a or b, "xor": a != b, "iff": a == b, "imp": (not a) or b}[e[0]]
def count_models(cnf):
"""Fuerza bruta sobre las 2^n valoraciones: solo para comprobar en pequeño."""
return sum(all(any((l > 0) == bits[abs(l) - 1] for l in c) for c in cnf.clauses)
for bits in product([False, True], repeat=cnf.n))
V = lambda s: ("var", s)
ab = ("and", V("a"), V("b"))
ejemplos = {
"multiplexor": ("or", ("and", V("s"), V("a")), ("and", ("not", V("s")), V("b"))),
"mezcla": ("or", ("not", ("imp", V("p"), V("q"))), ("iff", V("q"), V("r"))),
"compartida": ("or", ab, ("and", ("not", ab), V("c"))),
"insatisfacible": ("and", ("and", ("or", V("a"), V("b")), ("not", V("a"))), ("not", V("b"))),
}
for nombre, f in ejemplos.items():
cnf, inputs = tseitin(f)
names = list(inputs)
modelos_f = sum(evaluate(f, dict(zip(names, bits))) for bits in product([False, True], repeat=len(names)))
print(f"{nombre:15s} {cnf.n - len(inputs)} puertas, {len(cnf.clauses):2d} cláusulas;"
f" modelos de φ: {modelos_f}, modelos de la CNF: {count_models(cnf)}")
print("\n n to_cnf Tseitin (paridad x1 ⊕ ... ⊕ xn)")
for n in (2, 4, 6, 8, 10):
dist = len(to_cnf(Xor(*symbols(f"x1:{n + 1}"))).args)
f = V("x1")
for i in range(2, n + 1):
f = ("xor", f, V(f"x{i}"))
print(f"{n:3d} {dist:8d} {len(tseitin(f)[0].clauses):9d}")In “shared,” subformula appears twice and receives one variable: three gates instead of four. The to_cnf column is , parity’s lower bound, and Tseitin’s is .
The text’s encodings, with “at most one” by pairs and sequential counter (case ; the general case is an exercise).
import time
from itertools import combinations
def at_least_one(cnf, xs):
cnf.add(xs)
def at_most_one_pairs(cnf, xs):
"""C(n, 2) cláusulas binarias, sin variables nuevas."""
for a, b in combinations(xs, 2):
cnf.add([-a, -b])
def at_most_one_seq(cnf, xs):
"""Contador secuencial con k = 1: 3n − 4 cláusulas y n − 1 auxiliares."""
n = len(xs)
if n <= 1:
return
s = [cnf.new_var() for _ in range(n - 1)] # s[i]: «alguna de x_1..x_{i+1} es verdadera»
cnf.add([-xs[0], s[0]])
for i in range(1, n - 1):
cnf.add([-xs[i], s[i]])
cnf.add([-s[i - 1], s[i]])
cnf.add([-xs[i], -s[i - 1]])
cnf.add([-xs[n - 1], -s[n - 2]])
def coloring(n_vertices, edges, k, break_symmetry=False):
cnf = CNF()
x = [[cnf.new_var() for _ in range(k)] for _ in range(n_vertices)]
for v in range(n_vertices):
at_least_one(cnf, x[v]) # «a lo sumo un color» sobra
for u, v in edges:
for c in range(k):
cnf.add([-x[u][c], -x[v][c]])
if break_symmetry: # el vértice i solo usa los colores 0..i
for v in range(n_vertices):
for c in range(v + 1, k):
cnf.add([-x[v][c]])
return cnf, x
petersen = [(i, (i + 1) % 5) for i in range(5)] + [(i, i + 5) for i in range(5)] + [(5 + i, 5 + (i + 2) % 5) for i in range(5)]
for k in (2, 3):
cnf, x = coloring(10, petersen, k)
m = solve(cnf)
if m is None:
print(f"Petersen con {k} colores: {cnf} -> insatisfacible")
else:
col = [min(c for c in range(k) if x[v][c] in m) for v in range(10)] # si hay varios, vale cualquiera
print(f"Petersen con {k} colores: {cnf} -> {col}, válida: {all(col[u] != col[v] for u, v in petersen)}")
def queens(N):
cnf = CNF()
x = [[cnf.new_var() for _ in range(N)] for _ in range(N)]
for r in range(N):
at_least_one(cnf, x[r])
at_most_one_pairs(cnf, x[r])
for c in range(N):
at_most_one_pairs(cnf, [x[r][c] for r in range(N)])
for d in range(-(N - 1), N):
at_most_one_pairs(cnf, [x[r][r - d] for r in range(N) if 0 <= r - d < N])
for s in range(2 * N - 1):
at_most_one_pairs(cnf, [x[r][s - r] for r in range(N) if 0 <= s - r < N])
return cnf, x
cnf, x = queens(8)
m = solve(cnf)
print("\n8 reinas:", cnf, " columna de cada fila:", [next(c for c in range(8) if x[r][c] in m) for r in range(8)])
def sudoku(grid, extended=False):
"""grid: 81 caracteres con '.' en las vacías. Codificación mínima o extendida."""
cnf = CNF()
x = [[[cnf.new_var() for _ in range(9)] for _ in range(9)] for _ in range(9)]
groups = [[(r, c) for c in range(9)] for r in range(9)] + [[(r, c) for r in range(9)] for c in range(9)]
groups += [[(3 * (b // 3) + i // 3, 3 * (b % 3) + i % 3) for i in range(9)] for b in range(9)]
for r in range(9):
for c in range(9):
at_least_one(cnf, x[r][c])
if extended:
at_most_one_pairs(cnf, x[r][c])
for g in groups:
for v in range(9):
at_most_one_pairs(cnf, [x[r][c][v] for r, c in g])
if extended:
at_least_one(cnf, [x[r][c][v] for r, c in g])
for i, ch in enumerate(grid):
if ch != ".":
cnf.add([x[i // 9][i % 9][int(ch) - 1]])
return cnf, x
grid = "53..7....6..195....98....6.8...6...34..8.3..17...2...6.6....28....419..5....8..79"
for ext in (False, True):
cnf, x = sudoku(grid, ext)
t0 = time.perf_counter()
m = solve(cnf)
sol = "".join(str(1 + next(v for v in range(9) if x[r][c][v] in m)) for r in range(9) for c in range(9))
print(f"Sudoku {'extendido' if ext else 'mínimo '}: {cnf}, {time.perf_counter() - t0:.2f} s; primera fila {sol[:9]}")
print("\n n pares C(n,2) contador 3n−4")
for n in (5, 10, 50, 100, 1000):
a, b = CNF(), CNF()
at_most_one_pairs(a, [a.new_var() for _ in range(n)])
at_most_one_seq(b, [b.new_var() for _ in range(n)])
print(f"{n:5d} {len(a.clauses):13d} {len(b.clauses):12d} (+{b.n - n} auxiliares)")The counts match the text: 736 clauses for 8 queens and 8829 plus 30 clues for minimal Sudoku. This Sudoku is solved almost entirely by propagation with both encodings.
For 2-SAT first use networkx (components, condensation, and topological order already implemented); the iterative linear from-scratch version is an exercise. Horn-SAT is written in full, with pending-premise counters.
import random
import networkx as nx
from itertools import product
def two_sat_nx(n, clauses):
"""2-SAT con networkx: grafo de implicaciones, condensación y orden topológico."""
G = nx.DiGraph()
G.add_nodes_from([l for v in range(1, n + 1) for l in (v, -v)])
for a, b in clauses:
G.add_edge(-a, b)
G.add_edge(-b, a)
C = nx.condensation(G) # DAG de componentes; mapping: literal -> componente
comp = C.graph["mapping"]
if any(comp[v] == comp[-v] for v in range(1, n + 1)):
return None
rank = {c: i for i, c in enumerate(nx.topological_sort(C))}
return {v: rank[comp[v]] > rank[comp[-v]] for v in range(1, n + 1)} # verdadera si va después
def brute(n, clauses):
return any(all((a > 0) == bits[abs(a) - 1] or (b > 0) == bits[abs(b) - 1] for a, b in clauses)
for bits in product([False, True], repeat=n))
rng = random.Random(0)
errores = 0
for _ in range(300):
n = rng.randint(2, 9)
cl = [tuple(rng.choice([-1, 1]) * rng.randint(1, n) for _ in range(2)) for _ in range(rng.randint(1, 3 * n))]
m = two_sat_nx(n, cl)
errores += (m is not None) != brute(n, cl)
errores += m is not None and not all(m[abs(a)] == (a > 0) or m[abs(b)] == (b > 0) for a, b in cl)
print("2-SAT frente a fuerza bruta en 300 instancias: errores =", errores)
# 2-SAT aleatorio con m = c·n cláusulas: el umbral está en c = 1
n = 400
for c in (0.6, 0.9, 1.0, 1.1, 1.4):
sat = sum(two_sat_nx(n, [tuple(rng.choice([-1, 1]) * rng.randint(1, n) for _ in range(2)) for _ in range(int(c * n))]) is not None
for _ in range(20))
print(f"m/n = {c:.1f}: satisfacibles {sat:2d}/20")
def horn_sat(n, clauses):
"""Propagación unitaria con contadores (Dowling y Gallier), tiempo lineal.
Devuelve el modelo mínimo (conjunto de variables verdaderas) o None."""
pending = [sum(1 for l in c if l < 0) for c in clauses] # premisas todavía no satisfechas
occurs = {} # variable -> cláusulas donde es premisa
for i, c in enumerate(clauses):
for l in c:
if l < 0:
occurs.setdefault(-l, []).append(i)
true, queue = set(), [i for i, k in enumerate(pending) if k == 0]
while queue:
i = queue.pop()
head = [l for l in clauses[i] if l > 0]
if not head:
return None # restricción con todas sus premisas ciertas
if head[0] in true:
continue
true.add(head[0])
for j in occurs.get(head[0], []):
pending[j] -= 1
if pending[j] == 0:
queue.append(j)
return true
# un sistema de permisos: hechos, reglas y una restricción
nombres = ["admin", "editor", "lector", "borrar", "publicar", "leer", "auditado"]
v = {s: i + 1 for i, s in enumerate(nombres)}
reglas = [[v["editor"]], [-v["admin"], v["editor"]], [-v["editor"], v["lector"]], [-v["editor"], v["publicar"]],
[-v["admin"], v["borrar"]], [-v["lector"], v["leer"]], [-v["borrar"], v["auditado"]],
[-v["publicar"], -v["borrar"]]] # nadie puede publicar y borrar a la vez
print("\nmodelo mínimo:", sorted(nombres[i - 1] for i in horn_sat(len(nombres), reglas)))
print("con el hecho «admin»:", horn_sat(len(nombres), reglas + [[v["admin"]]]))
fallos = 0
for _ in range(300):
n = rng.randint(2, 8)
cl = []
for _ in range(rng.randint(1, 12)):
body = rng.sample(range(1, n + 1), rng.randint(0, min(3, n)))
head = [h for h in [rng.randint(1, n)] if h not in body] if rng.random() < 0.8 else []
cl.append([-b for b in body] + head)
mm = horn_sat(n, cl)
modelos = [{i + 1 for i in range(n) if bits[i]} for bits in product([False, True], repeat=n)
if all(any((l > 0) == bits[abs(l) - 1] for l in c) for c in cl)]
fallos += (mm is None) != (not modelos) or (mm is not None and (mm not in modelos or not all(mm <= M for M in modelos)))
print("modelo mínimo frente a fuerza bruta en 300 fórmulas de Horn: fallos =", fallos)The random 2-SAT threshold at is a theorem (Chvátal and Reed, 1992; Goerdt, 1996), and with the transition is already clear; the 3-SAT transition around is harder and is the next lesson’s topic. In the permission system, the least model is exactly what follows from the rules, and the “admin” fact makes the policy inconsistent: an administrator is an editor and can therefore publish, and can also delete.
Now the miter. Construct CNF gate by gate with a subclass of CNF and compare a ripple-carry adder with a Kogge–Stone parallel-prefix adder, the structure processors use so carry need not traverse every bit.
import time
class Circuit(CNF):
"""CNF construida puerta a puerta: cada puerta crea su variable y sus cláusulas de Tseitin."""
def gate(self, op, a, b):
g = self.new_var()
for c in GATE[op](g, a, b):
self.add(c)
return g
def AND(self, a, b): return self.gate("and", a, b)
def OR(self, a, b): return self.gate("or", a, b)
def XOR(self, a, b): return self.gate("xor", a, b)
def OR_all(self, xs):
z = self.new_var()
self.add([-z] + xs)
for x in xs:
self.add([z, -x])
return z
def ripple_carry(C, a, b):
s, c = [], None
for i in range(len(a)):
p = C.XOR(a[i], b[i])
if c is None:
s.append(p)
c = C.AND(a[i], b[i])
else:
s.append(C.XOR(p, c))
c = C.OR(C.AND(a[i], b[i]), C.AND(p, c))
return s + [c]
def kogge_stone(C, a, b, bug=None):
"""Prefijos paralelos: (G, P) de bloques cada vez más largos en log2(n) niveles."""
n = len(a)
p = [C.XOR(a[i], b[i]) for i in range(n)]
G, P = [C.AND(a[i], b[i]) for i in range(n)], p[:]
d = 1
while d < n:
G2, P2 = G[:], P[:]
for i in range(d, n):
G2[i] = C.OR(G[i], C.AND(P[i], G[i - d]))
P2[i] = C.OR(P[i], P[i - d]) if bug == (d, i) else C.AND(P[i], P[i - d]) # el fallo
G, P, d = G2, P2, 2 * d
return [p[0]] + [C.XOR(p[i], G[i - 1]) for i in range(1, n)] + [G[n - 1]]
def miter(n, bug=None):
C = Circuit()
a = [C.new_var(f"a{i}") for i in range(n)]
b = [C.new_var(f"b{i}") for i in range(n)]
out1, out2 = ripple_carry(C, a, b), kogge_stone(C, a, b, bug)
C.add([C.OR_all([C.XOR(u, v) for u, v in zip(out1, out2)])]) # «alguna salida difiere»
return C, a, b
def ks_int(A, B, n, bug=None):
"""El mismo Kogge-Stone simulado con enteros, para comprobar el contraejemplo por otra vía."""
p = [(A >> i ^ B >> i) & 1 for i in range(n)]
G, P, d = [(A >> i & B >> i) & 1 for i in range(n)], p[:], 1
while d < n:
G2, P2 = G[:], P[:]
for i in range(d, n):
G2[i] = G[i] | (P[i] & G[i - d])
P2[i] = (P[i] | P[i - d]) if bug == (d, i) else (P[i] & P[i - d])
G, P, d = G2, P2, 2 * d
bits = [p[0]] + [p[i] ^ G[i - 1] for i in range(1, n)] + [G[n - 1]]
return sum(bit << i for i, bit in enumerate(bits))
n = 5
for bug in (None, (1, 2)):
C, a, b = miter(n, bug)
t0 = time.perf_counter()
m = solve(C)
t = time.perf_counter() - t0
if m is None:
print(f"sin fallo: {C} -> insatisfacible en {t:.2f} s: equivalentes para las {4 ** n} entradas")
else:
A = sum(1 << i for i, x in enumerate(a) if x in m)
B = sum(1 << i for i, x in enumerate(b) if x in m)
print(f"fallo {bug}: {C} -> contraejemplo a = {A}, b = {B} en {t:.2f} s")
print(f" simulación: {A} + {B} = {A + B}, el sumador defectuoso da {ks_int(A, B, n, bug)}")
malas = sum(ks_int(x, y, n, bug) != x + y for x in range(2 ** n) for y in range(2 ** n))
print(f" entradas que lo delatan: {malas} de {4 ** n}")Sympy’s DPLL, without industrial solver heuristics, already takes a fraction of a second for 5 bits, and time grows quickly with bit count. Below, PySAT solves the same 64-bit miter in a couple of seconds, even in the browser.
Finally, BMC and k-induction on the text’s two programs, with 4-bit x. Adding a constant uses a ripple-carry adder in which the constant removes half the gates.
BITS = 4
def add_const(C, x, k):
"""x + k módulo 2^BITS con k constante."""
out, carry = [], None
for i in range(BITS):
if (k >> i) & 1:
out.append(-x[i] if carry is None else -C.XOR(x[i], carry))
carry = x[i] if carry is None else C.OR(x[i], carry)
else:
out.append(x[i] if carry is None else C.XOR(x[i], carry))
carry = None if carry is None else C.AND(x[i], carry)
return out
def equals_const(C, x, k):
lits = [x[i] if (k >> i) & 1 else -x[i] for i in range(BITS)]
g = lits[0]
for l in lits[1:]:
g = C.AND(g, l)
return g
def unroll(C, x0, k, step):
xs = [x0]
for _ in range(k):
xs.append(add_const(C, xs[-1], step))
return xs
def decode(m, xs):
return [sum(1 << i for i in range(BITS) if x[i] in m) for x in xs]
def bmc(k, step, bad, init=0):
"""¿Hay una ejecución de como mucho k pasos desde x = init que llegue a x = bad?"""
C = Circuit()
x0 = [C.new_var() for _ in range(BITS)]
for i in range(BITS):
C.add([x0[i] if (init >> i) & 1 else -x0[i]])
xs = unroll(C, x0, k, step)
C.add([C.OR_all([equals_const(C, x, bad) for x in xs])])
m = solve(C)
return None if m is None else decode(m, xs)
# x = 0; repetir: x = x + 3 (mod 16). Propiedad: x != 7
for k in (4, 8, 12, 13):
traza = bmc(k, 3, 7)
print(f"BMC con k = {k:2d}:", "sin contraejemplo" if traza is None else f"contraejemplo {traza}")
def k_induction_step(k, step, bad):
"""Paso inductivo: k estados buenos consecutivos seguidos de uno malo, desde un estado cualquiera."""
C = Circuit()
xs = unroll(C, [C.new_var() for _ in range(BITS)], k, step)
for x in xs[:-1]:
C.add([-equals_const(C, x, bad)])
C.add([equals_const(C, xs[-1], bad)])
m = solve(C)
return None if m is None else decode(m, xs)
# x = 0; repetir: x = x + 2. Propiedad: x != 15 (cierta: x siempre es par)
print()
for k in range(1, 9):
cti = k_induction_step(k, 2, 15)
base = bmc(k - 1, 2, 15)
print(f"k = {k}: base {'falla' if base else 'ok'};",
"paso inductivo ok: demostrada" if cti is None else f"contraejemplo a la inducción {cti}")Notice every induction counterexample starts at an odd value: states satisfying the property but unreachable. k-induction rules them out by lengthening the window; strengthening (“x is even”) rules them out at once with .
The professional version: PySAT
PySAT (Ignatiev, Morgado, and Marques-Silva) provides Python access to industrial CDCL solvers (CaDiCaL, Glucose, MiniSat, and others) and implemented cardinality encodings. It also runs in the browser compiled to WebAssembly, so the following cells are as executable as the previous ones. First, the same miters at scale, and “at most ” encodings of pysat.card versus the sequential-counter formula.
import time
from pysat.solvers import Solver
from pysat.card import CardEnc, EncType
def run(clauses, name="cadical153", budget=None):
with Solver(name=name, bootstrap_with=clauses) as s:
t0 = time.perf_counter()
if budget is None:
r = s.solve()
else:
s.conf_budget(budget)
r = s.solve_limited()
return r, time.perf_counter() - t0, s.accum_stats(), s.get_model() if r else None
for n in (8, 16, 32, 64):
C, a, b = miter(n)
r, t, st, _ = run(C.clauses)
C2, a2, b2 = miter(n, bug=(2, n // 2 + 1))
r2, t2, st2, model = run(C2.clauses)
A = sum(1 << i for i, x in enumerate(a2) if model[x - 1] > 0)
B = sum(1 << i for i, x in enumerate(b2) if model[x - 1] > 0)
print(f"{n:2d} bits: {C.n:5d} variables, {len(C.clauses):6d} cláusulas; equivalentes: {not r} "
f"({st['conflicts']} conflictos, {t:.2f} s); con fallo: a + b = {A + B}, sumador {ks_int(A, B, n, (2, n // 2 + 1))}")
print("\n«a lo sumo k» con n = 100: cláusulas según la codificación")
n, lits = 100, list(range(1, 101))
for k in (1, 5, 20):
row = []
for nombre, enc in [("pares", EncType.pairwise), ("contador", EncType.seqcounter), ("totalizador", EncType.totalizer),
("red de cardinalidad", EncType.cardnetwrk)]:
if enc == EncType.pairwise and k > 1:
continue
f = CardEnc.atmost(lits=lits, bound=k, top_id=n, encoding=enc)
row.append(f"{nombre} {len(f.clauses)}")
print(f"k = {k:2d}: " + ", ".join(row) + f" (fórmula del contador: {2 * n * k + n - 3 * k - 1})")The 64-bit miter, with 1665 variables and almost 5000 clauses, is proved unsatisfiable with a few thousand conflicts, and the faulty-adder miter returns a concrete miscomputed sum checkable by hand. For , PySAT’s seqcounter encoding has exactly the formula’s clauses; for larger , PySAT implements a counter variant with somewhat fewer clauses than Sinz’s. Cardinality networks grow as rather than , so eventually win as grows (with and they already match the counter); the totalizer builds the full unary counter and its size does not depend on .
Now symmetry breaking. Measure conflicts rather than time because it is deterministic and machine-independent; use a conflict budget to avoid waiting indefinitely.
def php(p, h, sym=False):
"""p palomas en h huecos: cada paloma en algún hueco, cada hueco con a lo sumo una paloma."""
v = lambda i, j: i * h + j + 1
cl = [[v(i, j) for j in range(h)] for i in range(p)]
for j in range(h):
for a_, b_ in combinations(range(p), 2):
cl.append([-v(a_, j), -v(b_, j)])
if sym: # los huecos son intercambiables: la paloma i usa los huecos 0..i
cl += [[-v(i, j)] for i in range(p) for j in range(i + 1, h)]
return cl
print("palomar PHP(n+1, n): conflictos hasta demostrar la insatisfacibilidad")
for nh in (5, 6, 7, 8):
r0, _, s0, _ = run(php(nh + 1, nh), budget=100_000)
r1, _, s1, _ = run(php(nh + 1, nh, sym=True), budget=100_000)
estado = "insatisfacible" if r0 is False else "sin respuesta"
print(f"n = {nh}: sin romper la simetría {s0['conflicts']:6d} conflictos ({estado});"
f" rompiéndola {s1['conflicts']} conflicto y {s1['decisions']} decisiones")
def mycielski(k):
"""Grafo de Mycielski M_k: sin triángulos y con número cromático k."""
n, E = 2, [(0, 1)]
for _ in range(k - 2):
E = E + [(a_, n + b_) for a_, b_ in E] + [(b_, n + a_) for a_, b_ in E] + [(n + i, 2 * n) for i in range(n)]
n = 2 * n + 1
return n, E
nv, E = mycielski(5)
for sym in (False, True):
cnf, _ = coloring(nv, E, 4, break_symmetry=sym)
r, t, st, _ = run(cnf.clauses, budget=500_000)
print(f"Mycielski M5 ({nv} vértices, χ = 5) con 4 colores, simetría {'rota' if sym else 'intacta'}: "
f"{'insatisfacible' if r is False else 'sin respuesta'} tras {st['conflicts']} conflictos")With symmetry intact, pigeonhole conflicts multiply six- or sevenfold for each extra hole, the exponential growth predicted by Haken’s theorem; breaking symmetry lets unit propagation reach a contradiction without decisions (the only conflict is the final one). In the triangle-free Mycielski graph (so no large clique can be fixed), the weak rule “vertex uses at most colors” already reduces conflicts by an order of magnitude.
| Tool | Purpose |
|---|---|
pysat.solvers.Solver | CDCL solvers (CaDiCaL, Glucose, MiniSat…), with incremental solving and assumptions |
pysat.card, pysat.pb | cardinality and pseudo-Boolean constraint encodings |
pysat.formula.CNF | DIMACS reading and writing |
| CaDiCaL, Kissat (command line) | competition reference solvers over DIMACS files |
| z3, cvc5 | SMT: SAT plus theories (arithmetic, bit vectors, arrays); covered in SMT theories |
| OR-Tools CP-SAT | constraint programming and optimization over a SAT core |
Common mistakes
Exercises
Step 1 of 4. Which auxiliary claim should be proved first?
Step 1 of 4. Which invariant do you prove first?
at_most_k_seq(n, k), returning (clauses, nvars): the Sinz sequential counter clauses (lists of DIMACS integers) for ‘at most k of ’, with original variables numbered 1 through n and auxiliary starting at n + 1, and the total variable count. For it must have exactly clauses. If k >= n no clauses are needed, and if k == 0, negate them all. Tests enumerate, for , that assignments to extending to a model are exactly those with at most k true variables.def at_most_k_seq(n, k):
"""Cláusulas del contador secuencial de Sinz para «a lo sumo k de x_1..x_n».
Variables originales 1..n; auxiliares s_{i,j} desde n + 1. Devuelve (cláusulas, número total de variables)."""
clauses = []
# tu código: s_{i,j} significa «al menos j verdaderas entre x_1..x_i»
return clauses, ntwo_sat(n, clauses) for a 2-CNF over , given as a list of pairs (a, b) of DIMACS literals (a unit clause arrives as (a, a)). Return ('SAT', modelo) with Boolean modelo[v] for v = 1..n, or ('UNSAT', v) with a variable v such that and lie in the same strongly connected component of the implication graph. Compute components using iterative Tarjan or Kosaraju: tests include a chain of 5000 implications, which would exhaust a recursive stack. Do not use networkx.def two_sat(n, clauses):
"""clauses: pares (a, b) de literales DIMACS sobre x_1..x_n.
Devuelve ('SAT', modelo) con modelo[v] in {True, False} para v = 1..n,
o ('UNSAT', v) con x_v y ¬x_v en la misma componente fuertemente conexa."""
# 1. grafo de implicaciones: (a ∨ b) da ¬a → b y ¬b → a
# 2. componentes fuertemente conexas (iterativo: hay instancias de miles de literales)
# 3. conflicto o asignación según el orden topológico
return ("SAT", {v: False for v in range(1, n + 1)})Summary
- SAT asks whether a CNF has a model. A model is a certificate checked in linear time; unsatisfiability requires a generally long proof. Validity and consequence reduce to unsatisfiability. SAT and 3-SAT are NP-complete (Cook–Levin).
- Tseitin gives each gate a variable defined by 3 or 4 clauses: the resulting CNF is equisatisfiable (not equivalent), preserves model count, and has at most clauses of 3 literals. Plaisted–Greenbaum uses only the needed polarity.
- Encoding means choosing meaningful variables and writing each constraint as clauses. Some families are redundant (at most one color, at most one value per cell) and can be proved unnecessary, but redundant clauses can greatly improve propagation. Breaking symmetries is essential on unsatisfiable instances.
- Pairwise “at most one” costs clauses; Sinz’s sequential counter expresses “at most ” with clauses, auxiliaries, and complete propagation.
- 2-SAT is decided in linear time using strongly connected components of the implication graph; Horn-SAT uses unit propagation, which also constructs the least model.
- A miter turns circuit equivalence into a SAT question whose model is an input distinguishing the circuits. BMC unrolls a system steps and finds bugs up to that depth without proving anything beyond it; k-induction, analogous to inductive invariants, closes the proof.