Satisfiability and SAT
The satisfiability problem (SAT) asks: given a propositional formula, is there an assignment of truth values that makes it true? It looks like a small question about truth tables, but it is one of the central problems of computer science. Scheduling, hardware verification, package dependency resolution and puzzle solving can all be written as SAT instances.
Brute force is exponential
A formula with variables has assignments. Checking each one is easy, but the count explodes: 30 variables give about a billion assignments, 100 variables give . No known algorithm solves every SAT instance in time polynomial in . Whether one exists is the famous P vs NP question: SAT is NP-complete, so a fast SAT algorithm would give fast algorithms for thousands of other problems.
from itertools import product
def brute_sat(clauses, n):
"""clauses: list of lists of ints; k means x_k, -k means not x_k (variables 1..n)."""
tried = 0
for bits in product([False, True], repeat=n):
tried += 1
if all(any(bits[abs(l) - 1] == (l > 0) for l in c) for c in clauses):
return bits, tried
return None, tried
# (x1 or x2) and (not x1 or x3) and (not x2 or not x3) and (not x3 or x1)
cnf = [[1, 2], [-1, 3], [-2, -3], [-3, 1]]
print(brute_sat(cnf, 3))
print(brute_sat([[1], [-1, 2], [-2]], 2)) # unsatisfiable((False, True, False), 3)
(None, 4)
The clauses use the DIMACS convention that real SAT solvers read: variable is the integer k, its negation is -k, and a formula is a list of clauses in CNF.
Smarter search: DPLL
Practical solvers do not try assignments blindly. The DPLL algorithm (Davis, Putnam, Logemann, Loveland) searches a tree of partial assignments with two tricks:
- Unit propagation: if a clause has only one unassigned literal and all others are false, that literal must be true.
- Backtracking: choose a variable, try a value, and undo it as soon as a clause becomes all false.
Modern CDCL solvers add clause learning on top and handle industrial formulas with millions of variables.
def dpll(clauses, assign=None):
assign = dict(assign or {})
while True: # unit propagation
simplified = []
for c in clauses:
if any(assign.get(abs(l)) == (l > 0) for l in c):
continue # clause already true
rest = [l for l in c if abs(l) not in assign]
if not rest:
return None # clause false: conflict
simplified.append(rest)
clauses = simplified
units = [c[0] for c in clauses if len(c) == 1]
if not units:
break
assign[abs(units[0])] = units[0] > 0
if not clauses:
return assign
v = abs(clauses[0][0]) # branch on a variable
for val in (True, False):
result = dpll(clauses, {**assign, v: val})
if result is not None:
return result
return None
print(dpll([[1, 2], [-1, 3], [-2, -3], [-3, 1]]))
print(dpll([[1], [-1, 2], [-2]])){1: True, 3: True, 2: False}
None
Encoding a problem as SAT
Example: graph 3-coloring. Color the vertices of a graph with colors 0, 1, 2 so that adjacent vertices differ. Use a variable meaning "vertex has color ". The constraints are clauses:
- each vertex gets a color: ;
- adjacent differ: for every color .
A vertex with two colors is harmless (pick either), so "at most one color" clauses are optional.
def dpll(clauses, assign=None):
assign = dict(assign or {})
while True:
simp = []
for c in clauses:
if any(assign.get(abs(l)) == (l > 0) for l in c):
continue
rest = [l for l in c if abs(l) not in assign]
if not rest:
return None
simp.append(rest)
clauses = simp
units = [c[0] for c in clauses if len(c) == 1]
if not units:
break
assign[abs(units[0])] = units[0] > 0
if not clauses:
return assign
v = abs(clauses[0][0])
for val in (True, False):
r = dpll(clauses, {**assign, v: val})
if r is not None:
return r
return None
def color_cnf(n, edges, k=3):
var = lambda v, c: v * k + c + 1
cnf = [[var(v, c) for c in range(k)] for v in range(n)]
cnf += [[-var(u, c), -var(v, c)] for u, v in edges for c in range(k)]
return cnf, var
wheel5 = [(i, (i + 1) % 5) for i in range(5)] + [(i, 5) for i in range(5)] # 5-cycle + hub
square = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 4), (1, 4), (2, 4), (3, 4)] # 4-cycle + hub
for name, n, edges in [("wheel with 5 rim vertices", 6, wheel5), ("wheel with 4 rim vertices", 5, square)]:
cnf, var = color_cnf(n, edges)
sol = dpll(cnf)
if sol is None:
print(name, ": not 3-colorable")
else:
colors = [next(c for c in range(3) if sol.get(var(v, c))) for v in range(n)]
print(name, ": colors", colors)wheel with 5 rim vertices : not 3-colorable
wheel with 4 rim vertices : colors [0, 1, 0, 1, 2]
The 5-cycle needs 3 colors by itself (an odd cycle), so the hub, adjacent to all of them, would need a fourth. The 4-cycle needs only 2, leaving the third color for the hub.
In software
Package managers (Conda, some Linux distributions' dependency resolvers, Dart's pub) turn "install these packages with compatible versions" into a SAT-like problem. Hardware companies verify chip designs with SAT, and tools like Z3 (an SMT solver, SAT plus arithmetic) check program properties and find bugs.
Exercises
Exercise 1: Satisfiable?
Is satisfiable?
Answer
No.
Solution
The four clauses rule out the four assignments one each: rules out FF, rules out TF, rules out FT, and rules out TT. Nothing remains.
Exercise 2: Unit propagation by hand
Apply unit propagation to . What is forced?
Answer
are forced true; the last clause becomes and needs a choice.
Solution
is a unit clause, so . Then becomes the unit , so . Then . The last clause shrinks to , which has two literals, so propagation stops and the solver branches.
Exercise 3: Encode "exactly one" (code)
Write CNF clauses saying exactly one of is true, and count the satisfying assignments by brute force.
Answer
Clauses ; 3 satisfying assignments.
Solution
"At least one" is one clause; "at most one" says no two are true together, one clause per pair.
from itertools import product
cnf = [[1, 2, 3], [-1, -2], [-1, -3], [-2, -3]]
sols = [b for b in product([False, True], repeat=3)
if all(any(b[abs(l) - 1] == (l > 0) for l in c) for c in cnf)]
print(len(sols), sols)3 [(False, False, True), (False, True, False), (True, False, False)]
Test yourself
How many assignments must brute force check, in the worst case, for a formula with 40 variables?
- 40
In DIMACS notation, what does the clause [-2, 5] mean?
What does unit propagation do?
- Assigns every variable true
- Sets a literal true when it is the only remaining way to satisfy a clause
- Removes all clauses
- Counts satisfying assignments