TExcelTAD
Home › Discrete Mathematics › Satisfiability and SAT

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 nn variables has 2n2^n assignments. Checking each one is easy, but the count explodes: 30 variables give about a billion assignments, 100 variables give 2100≈1.3×10302^{100} \approx 1.3 \times 10^{30}. No known algorithm solves every SAT instance in time polynomial in nn. 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.

python · try it yourself
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 kk 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:

  1. Unit propagation: if a clause has only one unassigned literal and all others are false, that literal must be true.
  2. 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.

python · try it yourself
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 xv,cx_{v,c} meaning "vertex vv has color cc". The constraints are clauses:

  • each vertex gets a color: xv,0∨xv,1∨xv,2x_{v,0} \lor x_{v,1} \lor x_{v,2};
  • adjacent u,vu, v differ: ¬xu,c∨¬xv,c\neg x_{u,c} \lor \neg x_{v,c} for every color cc.

A vertex with two colors is harmless (pick either), so "at most one color" clauses are optional.

python · try it yourself
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 (x1∨x2)∧(¬x1∨x2)∧(x1∨¬x2)∧(¬x1∨¬x2)(x_1 \lor x_2) \land (\neg x_1 \lor x_2) \land (x_1 \lor \neg x_2) \land (\neg x_1 \lor \neg x_2) satisfiable?

Answer

No.

Solution

The four clauses rule out the four assignments one each: (x1∨x2)(x_1 \lor x_2) rules out FF, (¬x1∨x2)(\neg x_1 \lor x_2) rules out TF, (x1∨¬x2)(x_1 \lor \neg x_2) rules out FT, and (¬x1∨¬x2)(\neg x_1 \lor \neg x_2) rules out TT. Nothing remains.

Exercise 2: Unit propagation by hand

Apply unit propagation to x1∧(¬x1∨x2)∧(¬x2∨x3)∧(¬x3∨x4∨x5)x_1 \land (\neg x_1 \lor x_2) \land (\neg x_2 \lor x_3) \land (\neg x_3 \lor x_4 \lor x_5). What is forced?

Answer

x1,x2,x3x_1, x_2, x_3 are forced true; the last clause becomes x4∨x5x_4 \lor x_5 and needs a choice.

Solution

x1x_1 is a unit clause, so x1=Tx_1 = T. Then (¬x1∨x2)(\neg x_1 \lor x_2) becomes the unit x2x_2, so x2=Tx_2 = T. Then x3=Tx_3 = T. The last clause shrinks to x4∨x5x_4 \lor x_5, which has two literals, so propagation stops and the solver branches.

Exercise 3: Encode "exactly one" (code)

Write CNF clauses saying exactly one of x1,x2,x3x_1, x_2, x_3 is true, and count the satisfying assignments by brute force.

Answer

Clauses [1,2,3],[−1,−2],[−1,−3],[−2,−3][1, 2, 3], [-1, -2], [-1, -3], [-2, -3]; 3 satisfying assignments.

Solution

"At least one" is one clause; "at most one" says no two are true together, one clause per pair.

python · try it yourself
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?

  1. 40
  2. 40240^2
  3. 2402^{40}
  4. 40!40!

In DIMACS notation, what does the clause [-2, 5] mean?

  1. x2∧x5x_2 \land x_5
  2. ¬x2∨x5\neg x_2 \lor x_5
  3. x2−x5x_2 - x_5
  4. ¬x2∧x5\neg x_2 \land x_5

What does unit propagation do?

  1. Assigns every variable true
  2. Sets a literal true when it is the only remaining way to satisfy a clause
  3. Removes all clauses
  4. Counts satisfying assignments