Boolean satisfiability (SAT)
布尔可满足性
Write Boolean rules, audit CNF encodings, and separate a satisfying witness from complete enumeration.
satCan these switches satisfy every rule?
Imagine a small workshop with three switches. Switches x and y enable two optional modules; z powers their shared cooling unit. At least one module must be enabled. Whenever either module is enabled, cooling must also be on. We want one consistent setting, or evidence that none exists.
Write true as 1 and false as 0. The symbol means inclusive OR, means AND, and means NOT. “If x, then z” becomes : it fails only when x is on and z is off. The workshop rules are
Try (x,y,z)=(0,1,1). Every parenthesis is true, so this setting is a satisfying assignment, also called a model of the formula. In this original example, the full list is (0,1,1), (1,0,1) and (1,1,1). Cooling is on in all three. Adding the rule makes the requirements impossible.
Boolean satisfiability, abbreviated SAT, asks whether any Boolean assignment satisfies a formula. A literal is a variable or its negation; a clause is an OR of literals. A conjunction of clauses is in conjunctive normal form, or CNF. These definitions connect rule writing to a solver’s input. Waterloo: satisfiability and CNF
SAT is a decision problem. Finding one setting supplies a witness for “yes”; listing every setting and counting settings are different tasks. The program below deliberately lists all models, so it can check small encodings used by a faster solver. Here “model” means an assignment satisfying rules, not a trained neural network.
Check the formula, then check its encoding
Let variables be numbered and let be a full assignment. A positive integer i denotes the literal and a negative integer −i denotes . Our evaluator is the direct definition
An empty conjunction is true; an empty disjunction is false. Thus a CNF with no clauses accepts all assignments, while one containing an empty clause accepts none. These are different objects. A repeated literal or clause changes no truth value. A clause containing both x and is always true, but it does not force x to either value.
There are exactly full assignments. Evaluating every one proves completeness of an enumeration: each assignment appears once, and the predicate accepts exactly the models. An empty complete list establishes UNSAT. An empty prefix of the truth table establishes no such result. Even with a short witness, proving that all assignments fail may require different work; the truth-table procedure here makes no claim about the fastest possible SAT algorithm. Waterloo: truth-table search
CNF-SAT is NP-complete under polynomial-time many-one reductions. NP means nondeterministic polynomial time; a satisfiable formula has a polynomial-size witness checkable in polynomial time. Unused variables need not be written in that certificate. Completeness additionally means every problem in NP can be translated to CNF-SAT in polynomial time while preserving the yes/no answer. A polynomial-time algorithm for all CNF-SAT instances would therefore imply P = NP. Neither this theorem nor our enumerator proves that every SAT algorithm needs exponential time. Cook: formal problem description, pp.2, 4–5
A second issue arises before search. Suppose a workshop has k independent module pairs, and at least one pair must have both members enabled:
Repeatedly distributing OR over AND produces one clause for every choice of one member from each pair: clauses, each containing k literals. Introducing fresh variables for subformulas avoids this expansion. A definitional Tseitin encoding constrains each new variable to equal its subformula and requires the output to be true. Eisner: conversion and Tseitin transformation
For this family, introduce . Its three clauses are
The first two clauses say that a true output requires two true inputs. The third says that two true inputs require a true output. Checking the four input pairs proves the biconditional. It also proves a stronger property than simply preserving the yes/no answer:
Here a contains the original 2k variables. To extend a, set each auxiliary output to its pair’s AND. Conversely, any model of G obeys those definitions, and its output clause makes at least one original pair true. This argument establishes projection preservation and unique extension for this encoding. Equisatisfiability alone means that both formulas have the same satisfiable/unsatisfiable answer; it does not imply those stronger properties for an arbitrary encoding.
The following counts are direct calculations for this family. G has 3k variables, 3k+1 clauses and 8k literal occurrences. The final clause can be longer than three literals; this compact family encoding is CNF, not necessarily 3-CNF. Among the assignments to original pairs, make no pair entirely true. Therefore both our distributed formula and our uniquely extending encoding have models. Adding a completely free auxiliary bit would double the full model count without changing the projected solutions.
Keep the answer and enumeration completeness separate
This complete Python 3.10+ program uses only the standard library. enumerate_cnf accepts an explicit variable count and a finite list or tuple of clauses, each itself a list or tuple of signed integer literals. It validates and copies the input without simplifying it. Variable count, literals and budget reject Booleans; literal zero and out-of-range IDs are invalid. Signed integer clause lists also appear in PySAT’s official CNF interface, but this code is our own truth-table baseline. PySAT formula API
budget counts full assignments tested; it excludes validation and output storage. None means no limit. verdict='SAT' requires a returned witness, even when complete is false. UNSAT requires an empty complete list. UNKNOWN means no witness has yet been found and enumeration is incomplete. The code deliberately performs no preliminary contradiction detection: even an explicit empty clause returns UNKNOWN at budget 0. That is a limitation of this procedure, not uncertainty about the clause’s mathematical meaning.
Assignments follow lexicographic order with False before True. The program retains all n variables even when some do not occur in clauses. holds is an internal helper for normalized clauses and a full Boolean tuple, not an independently validated public API. block returns a clause false at precisely one full assignment; it will be useful when checking model enumeration.
from itertools import product
def normalize(n, clauses):
if type(n) is not int or n < 0:
raise ValueError('n must be a nonnegative integer')
if type(clauses) not in (list, tuple):
raise ValueError('clauses must be a finite list or tuple')
result = []
for clause in clauses:
if type(clause) not in (list, tuple):
raise ValueError('each clause must be a list or tuple')
if any(type(lit) is not int or lit == 0 or abs(lit) > n for lit in clause):
raise ValueError('literals must be signed integers from 1 to n')
result.append(tuple(clause))
return tuple(result)
def holds(clauses, values):
# Internal helper: normalized clauses and a full Boolean tuple are required.
return all(any(values[abs(lit) - 1] == (lit > 0) for lit in clause)
for clause in clauses)
def enumerate_cnf(n, clauses, budget=None):
clauses = normalize(n, clauses)
if budget is not None and (type(budget) is not int or budget < 0):
raise ValueError('budget must be None or a nonnegative integer')
models, tested = [], 0
complete = True
for values in product((False, True), repeat=n):
if budget is not None and tested >= budget:
complete = False
break
tested += 1
if holds(clauses, values):
models.append(values)
verdict = 'SAT' if models else ('UNSAT' if complete else 'UNKNOWN')
return {'verdict': verdict, 'complete': complete,
'models': models, 'tested': tested}
def pair_formula(k, auxiliary=False):
# F_k = OR_i (x_i AND y_i); pairs use variable IDs 1..2k.
if type(k) is not int or k < 1 or type(auxiliary) is not bool:
raise ValueError('k must be positive; auxiliary must be Boolean')
pairs = [(2*i + 1, 2*i + 2) for i in range(k)]
if not auxiliary:
return 2*k, tuple(product(*pairs))
clauses, outputs = [], []
for i, (x, y) in enumerate(pairs):
u = 2*k + i + 1
outputs.append(u)
clauses.extend([(-u, x), (-u, y), (u, -x, -y)])
clauses.append(tuple(outputs))
return 3*k, tuple(clauses)
def block(values):
# This clause is false at exactly this assignment, for its full variable list.
if type(values) not in (list, tuple) or any(type(v) is not bool for v in values):
raise ValueError('values must be a Boolean list or tuple')
return tuple(-(i + 1) if v else i + 1 for i, v in enumerate(values))
clauses = ((1, 2), (-1, 3), (-2, 3))
for budget in (0, 3, 4, 8):
result = enumerate_cnf(3, clauses, budget)
print(budget, result['verdict'], result['complete'],
result['tested'], len(result['models']))
for auxiliary in (False, True):
n, cnf = pair_formula(3, auxiliary)
result = enumerate_cnf(n, cnf)
print('pair', auxiliary, n, len(cnf), sum(map(len, cnf)),
result['tested'], len(result['models']))
The first four output rows are:
0 UNKNOWN False 0 0
3 UNKNOWN False 3 0
4 SAT False 4 1
8 SAT True 8 3
The columns are budget, verdict, completeness, assignments tested and models found. The fourth candidate is (False, True, True), our first workshop solution. Finding it proves SAT but leaves half the truth table unexamined. At budget 8, all eight assignments were tested; reaching the budget exactly does not make an already exhausted enumeration incomplete.
For k = 3, the distributed formula reports six variables, eight clauses, 24 literal occurrences, 64 tested assignments and 37 models. The auxiliary version reports nine variables, ten clauses, 24 occurrences, 512 tested assignments and the same 37 models. The linear-size representation does not make this brute-force enumerator faster: it explicitly explores the auxiliary assignments too. At larger k, the formula-size difference grows, while the algorithm remains intentionally simple.
An encoding can be small and still be wrong
Dropping half a definition can change the projected answer. For a single pair x AND y, retaining only and the unit clause u permits every input pair: u can be true even when an input is false. The reverse implication , together with u, does suffice for this particular positive root. Whether an implication direction is sufficient depends on how the subformula is used. The full biconditional above makes its invariant easy to check.
For model enumeration, blocking a complete assignment a uses the disjunction of the opposite value at each position. That clause excludes exactly a. If auxiliaries have multiple extensions, blocking all variables excludes just one extension; blocking only original variables excludes every extension of the same original setting. Decide which set you mean to enumerate before comparing counts.
Let m be the number of clauses, L the number of literal occurrences, and S the number of returned models. Copying and validation cost . With ordinary constant-time Boolean indexing and literal operations, exhaustive evaluation costs : candidate tuples require work too, including when the formula has no literals. The stored formula, iteration state and output use space. These are bounds for this program, with Python integer bit costs abstracted away. Returning every model can itself require exponential output.
This baseline neither propagates unit clauses nor learns conflicts. Later algorithms can avoid visiting large parts of the truth table. Their correctness still depends on preserving the same semantics. SAT also asks only whether encoded rules are jointly possible; it does not choose the cheapest workshop setting, verify that the rules describe reality, or express a numeric variable without an encoding. Compare the general finite-domain model in constraint satisfaction and the search invariants in backtracking.
Make a solver’s claim precise
- Add the unit clause
(-3,)to the workshop formula. Predict the verdict and completeness at budgets 4 and 8. Explain why an empty model list is insufficient by itself. - For k = 4, calculate the variables, clauses, literal occurrences, candidate assignments and model counts of both pair encodings. Is the auxiliary encoding necessarily smaller for this k?
- Encode only
((3, -1, -2), (3,))for x AND y with output u. List the accepted original pairs. Then repair the encoding using the full definition. - Apply
blockto the three workshop models, append those three clauses, and enumerate again. What happens for zero variables with no clauses, at budgets 0 and 1? What doesblock(())produce?
Worked answers
1. There is no solution: at least one module needs cooling, while the new clause forbids cooling. At budget 4 the program returns UNKNOWN, incomplete, zero models; at budget 8 it returns UNSAT, complete, zero models. The difference is whether untested assignments remain.
2. Distributed: 8 variables, 16 clauses, 64 occurrences, 256 candidates and models. Auxiliary: 12 variables, 13 clauses, 32 occurrences, 4096 candidates and 175 models. It has fewer clauses and occurrences here but more variables. “Smaller” needs a stated measure; neither size measure promises faster brute-force search.
3. All four input pairs are accepted, always with u = true. Add (-3, 1) and (-3, 2). Now only (True, True) is accepted, with the unique extension u = true.
4. Each added clause removes one existing model; the resulting formula is UNSAT after complete enumeration. With zero variables there is one assignment, the empty tuple. At budget 0 the empty formula returns UNKNOWN/incomplete; at budget 1 it returns SAT/complete with [()]. block(()) is the empty clause, which excludes that sole assignment.
Use a tiny oracle before trusting a large solver
A useful experiment separates modeling from solving. Generate small module-pair formulas, calculate the intended Boolean function directly, and compare every original assignment with the projections of the CNF models. Test a wrong implication direction and a fresh variable accidentally reusing an input ID. Checking only whether both encodings return SAT would miss many such bugs.
For larger experiments, PySAT’s project exposes interfaces to native SAT solvers and several families of encodings. Pin the library and backend when recording an experiment; input interpretation, a SAT witness and a solver’s UNSAT result are distinct things to verify. No PySAT backend is installed or benchmarked by this article, and its implementation is not copied into the example.
The tests accompanying this chapter use truth-function bit masks to check the enumerator, including empty clauses, unused variables and incomplete budgets. They also count auxiliary extensions, verify blocking clauses and compare the two pair encodings with the original pair predicate. This gives the small examples a reproducible reference result before introducing DPLL or conflict-driven learning; those topics remain in the knowledge catalogue.
Make a prediction, then check
At budget 4 the workshop formula returns SAT, complete=false and one model. What follows?
Learning objectives
- Build an executable evaluator from literals, clauses and empty-formula semantics; distinguish a SAT witness, exhausted UNSAT and incomplete enumeration.
- Derive the pair-family auxiliary encoding, prove projection preservation and unique extension, and audit representation size, candidate counts and model counts.
Prerequisites & connections
Explore related knowledge →References
- Satisfiability Solving: Computational Discrete Mathematics
Curtis Bright - How to Convert a Formula to CNF
Jason Eisner - PySAT: Boolean formula manipulation (pysat.formula)
PySAT developers - PySAT: SAT technology in Python
PySAT developers - The P versus NP Problem
Stephen Cook
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent finite-state oracles, bilingual review and second-agent cross-checks; not independent human peer review.
- Reread both locales, six sections, four answers and input/budget contracts. Display equations and complete program correspond; strict MDX/KaTeX compilation and rendered emphasis checks passed. Definitional encoding, unique extension, counts and complexity include input, candidate generation and complete output.
- Eight independent tests passed: 512 two-variable CNFs × seven budgets against truth-function bit masks; 500 random unsimplified formulas and reversed clauses; k=1..4 encoding projections, unique extensions and 4^k−3^k counts; all blocking clauses for n=0..6; wrong implications/free auxiliary bits, empty formulas/clauses/unused variables, input preservation and bilingual program identity.
- Reread both complete articles, program, eight tests and metadata. Checked literals/clauses/CNF, empty conjunction/disjunction, duplicates/tautologies, unused variables, SAT witnesses versus complete, exhausted UNSAT versus UNKNOWN. UNKNOWN at budget0 even with an empty clause is an explicit procedural limitation; zero variables still have one empty assignment, and an exact exhaustive budget reports complete.
- Built an independent exact multilinear Boolean-polynomial reference with integer coefficients and x²=x. Each clause is1 minus the product of falsified-literal indicators, and clause polynomials multiply into the CNF indicator. It does not use the author’s truth bit masks, holds or per-clause Boolean evaluation as the oracle. All3,304 three-variable CNFs (at most3 of27 canonical clauses) ×11 budgets=36,344 cases matched; another200 random unsimplified formulas with repeated/tautological literals passed.
- For k=1..4 independently formed1−∏(1−xiyi), then exactly summed auxiliary variables out of the encoded polynomial. Coefficients equal the original indicator, so each base assignment has exactly zero or one extension. Checked2k/2^k/k2^k versus3k/(3k+1)/8k representation counts,2^(2k)/2^(3k) candidates and4^k−3^k models. The wrong implication marginal is constant1; the repaired marginal is xy; a free auxiliary bit doubles full counts.
- Checked255 full-assignment blocking clauses for n=0..7 by polynomials, each excluding only its designated assignment;70 empty-formula/empty-clause budget cases for n=0..6 passed. Verified projection versus full-extension blocking, that equisatisfiability does not imply projection preservation, the qualified sufficiency of one implication at this particular positive root, and the potentially long non-3-CNF output clause.
- Checked validation/copy O(1+m+L), candidate generation and exhaustive evaluation O(2^n(1+n+m+L)), and O(1+m+L+n+S(1+n)) storage including empty tuples and full output. Unit-cost literal/index operations and Python bit-cost abstraction are explicit. A shorter encoding is not claimed to make this enumerator faster, and no universal exponential SAT lower bound is asserted.
- All eight supplied tests ran successfully; the independent polynomial checks extract code directly from draft MDX, avoiding snapshot ambiguity from the supplied published-path-first loader. Both code blocks equal example.py; five display equations, six anchors and four answered exercises correspond. Independently compiled with current project math plugins and strict KaTeX and actually rendered both locales with React; formulas and Chinese parenthetical strong are correct, with no literal ** or KaTeX errors. No author files/repository were changed and no whole-site check/build or browser visual QA ran; this is second-agent AI technical review, not human expert review.
- Independently reviewed the added NP-completeness paragraph: both locales correctly distinguish nondeterministic polynomial time, short certificates and polynomial many-one completeness. Unused variables need not appear in the certificate, avoiding the explicit-n versus occurring-variable encoding issue. Membership plus identity embedding of3-SAT supports CNF-SAT completeness; a polynomial algorithm for all instances would imply P=NP, with no exponential lower-bound claim. Both updated locales passed strict MDX/HTML again. Code, tests and five display equations are unchanged, so prior numerical verification applies to the identical code.
- Promotion preserves full prose, equations, program and exercises. Test loading alone changes from temporary drafts to repository articles; implementation and oracle logic are unchanged. Final review binds both MDX SHA-256 hashes.
- Static link checking found the final catalogue URL used nonexistent /topics/. Changed only that target to the actual /catalogue/ route in both locales; prose, equations, complete code and answers are unchanged, with rebuild and link verification to follow.
- Once DPLL and CDCL were complete, linked the existing topic names in both final paragraphs directly to their articles. Only link markup/targets were added; reversing them reproduces each entire old file. All old arguments, equations, program, exercises and review evidence remain.
Source locations checked:
- Satisfiability Solving: Computational Discrete Mathematics · Read sections Boolean Logic, The Satisfiability Problem and CNF, lines 11–61, plus Tseitin lines 114–149. Definitions and truth-table baseline are cited; workshop semantics and verdict/completeness examples are independently constructed.
- How to Convert a Formula to CNF · Read lines 66–79 for exponential distributive expansion and switching-variable contrast, and 138–148 for full subformula definitions, output requirement, linear representation and modification date. Pair family is acknowledged standard; exact 3k+1/8k counts and unique extension proof independently checked.
- PySAT: Boolean formula manipulation (pysat.formula) · Read CNF constructor/from_clauses integer-list examples lines 257–315 and 376–394, from_string DIMACS lines 439–460 and negate auxiliary-variable definition 463–487. Own baseline accepts no DIMACS terminator zero and is not PySAT execution.
- PySAT: SAT technology in Python · Read README introduction/features lines 181–214, usage 242–275, and License 368–370. Only general solver/encoding interface statement and link reference used; no versions, performance or backend-license claims made.
- The P versus NP Problem · Actually read printed p.2 lines46–66 for polynomial checking relations and bounded witnesses, p.4 lines181–199 for reductions/completeness, and p.5 lines200–239 for the P=NP implication, SAT witness and NP-completeness including 3-SAT. CNF-SAT hardness follows since 3-SAT is a restricted CNF case; unused variables can be omitted from a decision certificate. No complete proof of Cook's theorem or exponential lower bound is claimed.
- Satisfiability Solving: Computational Discrete Mathematics · Independently opened Curtis Bright’s Waterloo SAT page; read Boolean/SAT/CNF definitions and truth-table discussion, blocking clause construction (lines64–85), distributive expansion (88–113), and Tseitin definitions/output condition (114–150). Checked the article’s distinctions between decision, complete enumeration, full equivalence, projection preservation and mere equisatisfiability; did not reuse source code or its circuit example.
- How to Convert a Formula to CNF · Independently opened Jason Eisner’s page and read CNF definition/distributive conversion (lines20–61), exponential expansion and switching-variable alternative (66–79), and definitional Tseitin paragraph (138–142); confirmed footer modification date2026-02-01 at line148. The exact pair counts and unique-extension property were checked independently, not assumed from a generic equisatisfiability statement. Did not obtain or claim to read Tseitin’s original paper.
- PySAT: Boolean formula manipulation (pysat.formula) · Independently read official CNF/from_clauses API (lines257–315 and376–386), including signed integer clause-list examples and copy behavior. Page title shows1.9.dev15 at access time; no claim of package installation, backend execution, performance verification or release timing before the edition cutoff. The article correctly uses its own list-based interface without DIMACS zero terminators.
- PySAT: SAT technology in Python · Independently read official README introduction and features (lines181–214) for native solver interfaces and cardinality encodings, plus License section (368–370) for the top-level MIT statement. Only linked tool context is claimed; no backend license is inferred from the top-level license and no library/backend was installed or benchmarked.
- The P versus NP Problem · Independently opened official Clay12-page Stephen Cook problem description. Read printed p.2 lines46–66 for NP as nondeterministic polynomial time and polynomial checking relations/witness length; printed p.4 lines181–199 for polynomial many-one reductions and NP-completeness; printed p.5 lines200–239 for P=NP implication, propositional SAT checking and NP-complete3-SAT. CNF-SAT membership follows by checking assignments to occurring variables, and hardness follows by identity embedding of3-SAT into CNF. Did not read the1971 original; no publication date is inferred from the2022/06 hosting path, nor current algorithm/quantum claims adopted from the old text.
Related topics