এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Computer Science — Year 1 · স্নাতক প্রথম বর্ষ
10Propositional Logic
Four friends are invited to dinner, and each has a condition. Ana comes only if Ben comes. Ben and Cyd will not both come. Cyd or Dee must come, but Dee will not come without Ana. Who can come? Four people make sixteen possible guest lists, few enough to try by hand; seven people with a dozen conditions make thousands, and the schedules, circuits and configurations that programs check daily make more lists than any computer could ever try. This chapter writes such conditions as formulas, represents the formulas as trees in Python, evaluates them, rewrites them into standard forms, and decides with a short recursive algorithm whether any list satisfies them all.
You already know
A statement is true or false; not, and, or, if … then and if and only if combine statements, and a truth table gives the value of a combination for every value of its parts. Logic gates compute the same operations on bits.
10.1 Formulas as trees
Definition 10.1 (Propositional variable, connective, formula)
A propositional variable is a name, , , , that stands for a statement which is either true or false. The connectives are (not), of arity one, and (and), (or), (implies) and (if and only if), of arity two. The propositional formulas are defined inductively: every variable is a formula; if is a formula, so is ; if and are formulas, so are , , and ; and nothing else is.
A formula is a tree: a variable is a leaf, and a connective is a node whose children are the formulas it combines. Parentheses exist only to write the tree on one line; the usual conventions drop some of them: binds tighter than , which binds tighter than , then and ; and group to the left, to the right, so that means .
class Formula:
"""Python's operators build formulas: ~p, p & q, p | q, p >> q (implies)."""
def __invert__(self):
return Not(self)
def __and__(self, other):
return Bin("&", self, other)
def __or__(self, other):
return Bin("|", self, other)
def __rshift__(self, other):
return Bin("->", self, other)
def __str__(self):
return show(self)
@dataclass(frozen=True)
class Var(Formula):
name: str
@dataclass(frozen=True)
class Not(Formula):
sub: Formula
@dataclass(frozen=True)
class Bin(Formula):
op: str # "&", "|", "->" or "<->"
left: Formula
right: Formula
Each kind of node is a class, and Python’s operators build trees: ~p is Not(p), p & q is Bin("&", p, q), and p >> q, borrowed for implication, is Bin("->", p, q). Python’s own precedence puts >> above &, so the listings always put an implication between parentheses. The classes are frozen, so that a formula cannot change once built and can be put in a set.
Definition 10.2 (Subformula, size, height)
The subformulas of a formula are the formulas of the subtrees of its tree, itself included. The size of a formula is the number of nodes of its tree: 1 for a variable, for , for a binary connective. Its height is the length of the longest path from the root to a leaf: 0 for a variable, , and .
def size(f):
match f:
case Var():
return 1
case Not(sub):
return 1 + size(sub)
case Bin(_, left, right):
return 1 + size(left) + size(right)
def height(f):
match f:
case Var():
return 0
case Not(sub):
return 1 + height(sub)
case Bin(_, left, right):
return 1 + max(height(left), height(right))
The definitions follow the inductive definition of formulas, one case per rule, and so do the functions, with Python’s match: a function defined this way is defined on every formula, since every formula is built by the rules. The next chapter proves properties of such functions by the same induction (Chapter 11); for instance that the height is always smaller than the size.
$ python formula.py
formula: (p -> q) & ~(q | r)
&
->
p
q
~
|
q
r
size 8 height 3 variables ['p', 'q', 'r']
7 subformulas: ['p', 'q', 'r', 'q | r', 'p -> q', '~(q | r)', '(p -> q) & ~(q | r)']
p & (q & r)
p & q & r
p -> q -> r
(p -> q) -> r
~(p | q) | ~p
p <-> (q <-> r)
10.2 Valuations and truth
Definition 10.3 (Valuation, truth value)
A valuation assigns to each variable a value, true () or false (). The truth value of a formula under a valuation is defined by induction: a variable has the value gives it; is true when is false; when both are true; when at least one is; unless is true and false; when both have the same value.
TABLES = {"&": lambda a, b: a and b, "|": lambda a, b: a or b,
"->": lambda a, b: (not a) or b, "<->": lambda a, b: a == b}
def value(f, v):
"""v maps each variable name of f to True or False."""
match f:
case Var(name):
return v[name]
case Not(sub):
return not value(sub, v)
case Bin(op, left, right):
return TABLES[op](value(left, v), value(right, v))
def valuations(names):
"""All 2**len(names) valuations of the names, in the order of a truth table."""
for bits in product([False, True], repeat=len(names)):
yield dict(zip(names, bits))
def models(f):
return [v for v in valuations(variables(f)) if value(f, v)]
def is_tautology(f):
return len(models(f)) == 2 ** len(variables(f))
def is_satisfiable(f):
return any(value(f, v) for v in valuations(variables(f)))
The truth value of a formula depends only on the values of its own variables, so with variables a formula has valuations to consider: the rows of its truth table, which valuations lists in the usual order, false before true, with the last variable changing fastest.
Definition 10.4 (Model, satisfiable, tautology, antilogy)
A valuation under which a formula is true is a model of it. A formula is satisfiable if it has a model, a tautology if every valuation is a model, and an antilogy (or contradiction) if none is. A valuation is a model of a set of formulas if it is a model of each.
$ python evaluate.py
(p -> q) & ~(q | r) under p=F q=F r=F: True
(p -> q) & ~(q | r) under p=T q=F r=F: False
models of (p -> q) & ~(q | r) : [{'p': False, 'q': False, 'r': False}]
p | ~p tautology True satisfiable True
p & ~p tautology False satisfiable False
(p -> q) | (q -> p) tautology True satisfiable True
((p -> q) -> p) -> p tautology True satisfiable True
p -> p & q tautology False satisfiable True
Definition 10.5 (Logical equivalence, logical consequence)
Two formulas are logically equivalent, written , if they have the same truth value under every valuation. A formula is a logical consequence of a set of formulas , written , if every model of is a model of .
Thus is a tautology exactly when , and exactly when is a tautology. : in every model of the two formulas, is true. The formula of Output 10.2 is a tautology although nothing in its shape suggests it; only the valuations tell.
def truth_table(f):
names = variables(f)
rows = [" ".join(names) + " | " + str(f)]
for v in valuations(names):
bits = " ".join("TF"[not v[n]] for n in names)
rows.append(f"{bits} | {'TF'[not value(f, v)]}")
return rows
def complete_dnf(f):
"""One conjunction of literals per true row: the formula's complete DNF."""
terms = []
for v in valuations(variables(f)):
if value(f, v):
terms.append(" & ".join(n if v[n] else "~" + n for n in sorted(v)))
return " | ".join(f"({t})" for t in terms) if terms else "false: no row is true"
if __name__ == "__main__":
p, q, r = Var("p"), Var("q"), Var("r")
f = (p >> q) & (q | r)
print("\n".join(truth_table(f)))
print("complete DNF:", complete_dnf(f))
$ python truth_table.py
p q r | (p -> q) & (q | r)
F F F | F
F F T | T
F T F | T
F T T | T
T F F | F
T F T | F
T T F | T
T T T | T
complete DNF: (~p & ~q & r) | (~p & q & ~r) | (~p & q & r) | (p & q & ~r) | (p & q & r)
10.3 Equivalence and normal forms
The following equivalences hold for all formulas , , ; each is checked by a truth table of four or eight rows.
- Double negation: . Excluded middle: is a tautology.
- De Morgan’s laws: and .
- Distributivity: , and the same with and exchanged.
- Implication and equivalence rewritten: and .
Replacing a subformula by an equivalent one gives an equivalent formula, since the truth value of a formula depends only on the truth values of its subformulas. Applied in a fixed order, these laws bring every formula into a standard shape.
Definition 10.6 (Literal, clause)
A literal is a variable or the negation of a variable: , . A clause is a disjunction of literals, , and is true when at least one of its literals is; the empty clause, with no literal, is false.
Definition 10.7 (Negation normal form, CNF, DNF)
A formula is in negation normal form if it uses only , and , and only in front of variables. It is in conjunctive normal form (CNF) if it is a conjunction of clauses, and in disjunctive normal form (DNF) if it is a disjunction of conjunctions of literals.
def nnf(f, positive=True):
"""An equivalent formula of & and | over literals (of ~f if not positive)."""
match f:
case Var():
return f if positive else Not(f)
case Not(sub):
return nnf(sub, not positive)
case Bin("->", a, b):
return nnf(~a | b, positive)
case Bin("<->", a, b):
return nnf((a >> b) & (b >> a), positive)
case Bin(op, a, b): # & or |; De Morgan swaps them under a negation
if not positive:
op = "|" if op == "&" else "&"
return Bin(op, nnf(a, positive), nnf(b, positive))
def literal(g):
return g.name if isinstance(g, Var) else "~" + g.sub.name
def distribute(g, outer, inner):
"""g in NNF, as a list of sets of literals: an `outer` of `inner`s."""
match g:
case Bin(op, a, b) if op == outer:
return distribute(a, outer, inner) + distribute(b, outer, inner)
case Bin(op, a, b) if op == inner:
return [x | y for x in distribute(a, outer, inner)
for y in distribute(b, outer, inner)]
case _:
return [frozenset([literal(g)])]
def cnf(f):
return distribute(nnf(f), "&", "|")
def dnf(f):
return distribute(nnf(f), "|", "&")
nnf rewrites and , then pushes each negation down to the variables with De Morgan’s laws, carrying a flag that says whether the current subtree is negated. distribute then turns a formula in negation normal form into a list of sets of literals: for a CNF, a conjunction concatenates the clauses of its two sides, and a disjunction takes every union of a clause from the left with a clause from the right, which is distributivity applied as often as needed.
$ python normal_forms.py
formula: ~((p -> q) | r)
NNF: p & ~q & ~r
CNF: (p) & (~q) & (~r)
CNF simplified: (p) & (~q) & (~r)
DNF: (p & ~q & ~r)
DNF simplified: (p & ~q & ~r)
formula: (p <-> q) | r
NNF: (~p | q) & (~q | p) | r
CNF: (~p | q | r) & (p | ~q | r)
CNF simplified: (~p | q | r) & (p | ~q | r)
DNF: (~p & ~q) | (p & ~p) | (q & ~q) | (p & q) | (r)
DNF simplified: (~p & ~q) | (p & q) | (r)
Every formula has an equivalent CNF and an equivalent DNF, as these functions show, and as the truth table already showed for the DNF (the antilogy has the empty disjunction, and the tautology the empty conjunction). But the price can be high.
def pairs(n):
terms = [Var(f"x{i}") & Var(f"y{i}") for i in range(1, n + 1)]
return reduce(lambda a, b: a | b, terms)
if __name__ == "__main__":
print("formula for n = 3:", pairs(3))
print(" n size clauses simplified")
for n in range(1, 11):
f = pairs(n)
print(f"{n:2d} {size(f):5d} {len(cnf(f)):8d} {len(simplify(cnf(f))):11d}")
$ python blowup.py
formula for n = 3: x1 & y1 | x2 & y2 | x3 & y3
n size clauses simplified
1 3 2 2
2 7 4 4
3 11 8 8
4 15 16 16
5 19 32 32
6 23 64 64
7 27 128 128
8 31 256 256
9 35 512 512
10 39 1024 1024
Proposition 10.8 (An exponential CNF)
Every CNF equivalent to has at least clauses.
Proof. Let be an equivalent CNF. For each choice of one variable per pair, let make the chosen variables false and the others true. Each pair has a false variable, so is false under , and so is : some clause of is false under , which means its positive literals are among . Now fix and let be with made true. Pair is now true, so and every clause of are true under . The clause changed from false to true, so it contains a literal whose value changed: only changed, and from false to true, so contains the literal . This holds for every , so the positive literals of are exactly . Two different choices give clauses with different positive literals, hence different clauses: there are at least of them. ∎
A formula of size 39 needs a CNF of 1024 clauses; one of size 399 needs more clauses than any computer can hold. Yet the next section’s algorithm wants a CNF. The way out is to stop asking for an equivalent formula.
Definition 10.9 (Equisatisfiable formulas)
Two formulas, or sets of clauses, are equisatisfiable if both are satisfiable or neither is. Equivalent formulas are equisatisfiable; equisatisfiable formulas need not even have the same variables.
The problem of this chapter builds, for every formula, an equisatisfiable CNF of size proportional to the formula’s, by adding one new variable per connective: Tseitin’s encoding, named after the logician Grigori Tseitin.
10.4 Satisfiability
Definition 10.10 (Satisfiability problem, -SAT)
The satisfiability problem (SAT) asks, given a formula, usually as a set of clauses, whether it has a model, and if so for one. -SAT is the same problem for sets of clauses with at most literals each.
Trying the valuations answers it, and models in Listing 10.3 does exactly that; with 49 variables it would try more than valuations. A better method stops as soon as part of a valuation decides the answer.
Method 10.11 (Quine’s algorithm)
To decide a set of clauses :
- If is empty, it is satisfied: return the empty valuation. If contains the empty clause, it is unsatisfiable: return “none”.
- Otherwise choose a variable of . Make true: remove the clauses that contain , and remove the literal from the others. Decide the result recursively; if it has a model, add true to it and return it.
- Otherwise make false in the same way, and decide again.
The algorithm is named after the logician Willard Van Orman Quine; it is also called splitting.
def neg(lit):
return lit[1:] if lit.startswith("~") else "~" + lit
def assign(clauses, lit):
"""Make lit true: the clauses holding lit are satisfied and vanish,
and ~lit, now false, leaves the others."""
return [c - {neg(lit)} for c in clauses if lit not in c]
def quine(clauses, stats):
"""A set of literals whose truth satisfies every clause, or None if no
valuation does. stats["nodes"] counts the calls (the search-tree nodes)."""
stats["nodes"] += 1
if not clauses:
return set() # nothing left to satisfy
if frozenset() in clauses:
return None # an empty clause: every literal of it was made false
x = min(clauses[0], key=lambda lit: lit.lstrip("~")).lstrip("~")
for lit in (x, neg(x)):
model = quine(assign(clauses, lit), stats)
if model is not None:
return model | {lit}
return None
$ python quine.py
p q, ~p q, p ~q, ~p ~q model None nodes 7
p q r, ~p, ~q, r ~s, s ~r model ['r', 's', '~p', '~q'] nodes 7
Proposition 10.12 (Correctness of Quine’s algorithm)
On every finite set of clauses , Quine’s algorithm terminates, returns a valuation of some variables that satisfies every clause of if is satisfiable (the other variables may take any value), and returns “none” otherwise.
Proof. By induction on the number of variables of . If , is empty or holds only empty clauses, and step 1 answers correctly. Let , and suppose step 1 does not apply. Let and be the sets obtained by making true and false; each has at most variables, so by induction the recursive calls terminate and answer correctly. A valuation with satisfies exactly when it satisfies : the removed clauses contain and are true, and the removed literals are false and change nothing. The same holds with and . Every valuation gives one of the two values, so is satisfiable exactly when or is, and the returned valuation, extended with the value of , satisfies . ∎
The search is a binary tree whose nodes are the calls; stats counts them. In the worst case the tree is complete and has about nodes, no better than the truth table; in practice whole subtrees are never visited, because a clause becomes empty early or the clauses run out.
Definition 10.13 (Unit propagation)
A unit clause is a clause of one literal. Unit propagation makes the literal of each unit clause true, without trying the other value, and repeats while unit clauses remain: a valuation that makes the literal false falsifies the clause, so no model is lost.
Splitting on often creates unit clauses: becomes as soon as is true. Propagating them before choosing the next variable cuts the tree a great deal (Exercise 10.11). Solvers used in industry add many refinements to this algorithm, and decide sets of millions of clauses that come from circuits, schedules and programs.
10.5 Modelling with formulas
The dinner of the opening question has one variable per friend, meaning “Ana comes”, and one formula per condition.
ana, ben, cyd, dee = Var("ana"), Var("ben"), Var("cyd"), Var("dee")
rules = [ana >> ben, # Ana comes only if Ben comes
~(ben & cyd), # Ben and Cyd will not both come
(cyd | dee) & (dee >> ana)] # Cyd or Dee comes; Dee only with Ana
dinner = rules[0] & rules[1] & rules[2]
clauses = cnf(dinner)
if __name__ == "__main__":
print("formula:", dinner)
for v in models(dinner):
print("model:", ", ".join(name for name in v if v[name]))
print("CNF:", show_sets(clauses, "&", "|"))
stats = {"nodes": 0}
model = quine(clauses, stats)
print("Quine's algorithm:", sorted(model), "after", stats["nodes"], "nodes")
everyone = dinner & ana & ben & cyd & dee
print("everyone comes:", models(everyone) or "no model")
$ python puzzle.py
formula: (ana -> ben) & ~(ben & cyd) & ((cyd | dee) & (dee -> ana))
model: cyd
model: ana, ben, dee
CNF: (~ana | ben) & (~ben | ~cyd) & (cyd | dee) & (ana | ~dee)
Quine's algorithm: ['ana', 'ben', 'dee', '~cyd'] after 6 nodes
everyone comes: no model
Definition 10.14 (Colouring of a graph)
A colouring of a graph with colours gives each vertex one of colours so that the two ends of every edge have different colours; a graph that has one is -colourable.
The town’s 39 friends are to be seated at three tables so that no two friends share a table, to make them meet new people: a 3-colouring of the friendship graph. The variable says that person 5 is red; each person gets some colour, and each friendship forbids, for each colour, that both friends have it.
def colouring_cnf(people, edges, colours):
"""Variable red5 says: person 5 is red."""
clauses = [frozenset(f"{c}{p}" for c in colours) for p in people] # some colour
for a, b in edges: # two friends never share a colour
clauses += [frozenset([f"~{c}{a}", f"~{c}{b}"]) for c in colours]
return clauses
if __name__ == "__main__":
edges = friendships()
people = sorted({p for edge in edges for p in edge})
for k in (2, 3):
clauses, stats = colouring_cnf(people, edges, COLOURS[:k]), {"nodes": 0}
model = quine(clauses, stats)
print(f"{k} colours: {len(people) * k} variables, {len(clauses)} clauses,",
"satisfiable" if model is not None else "unsatisfiable",
f"({stats['nodes']} nodes)")
print("model checked:", satisfies(model, clauses))
colour = {p: next(c for c in COLOURS if f"{c}{p}" in model) for p in people}
for c in COLOURS:
print(f"{c:5}:", *[p for p in people if colour[p] == c])
print("friends of equal colour:", sum(colour[a] == colour[b] for a, b in edges))
$ python colouring.py
2 colours: 78 variables, 139 clauses, unsatisfiable (253 nodes)
3 colours: 117 variables, 189 clauses, satisfiable (185 nodes)
model checked: True
red : 3 4 7 10 12 13 14 15 16 23 34 37 38 39
green: 5 9 11 19 20 21 27 28 31 32 35
blue : 1 2 6 8 17 18 22 24 25 26 29 30 33 36
friends of equal colour: 0
The clauses do not say that a person has at most one colour. They need not: in a model where a person has two, either colour can be kept, and the program keeps the first. Leaving out clauses that cannot change the answer keeps the encoding small; adding them makes the model easier to read. Either way, the model is checked against the clauses before it is used, and the colouring against the edges.
Safe use
A model is only as good as the encoding. A forgotten rule gives models that obey the formula and not the world; a wrong rule can make the formula unsatisfiable and the problem seem impossible. Check a model against the original constraints with a separate program, and test the encoding on cases small enough to enumerate.
10.6 Exercises
Exercise 10.1 ★
Give the truth value of when is true and , are false.
Solution
Solution of Exercise 10.1.
is false, so is true; is false and is false, so is false. An implication from true to false is false: the formula is false.
1. ~(p & q) -> r | ~p under p=T q=F r=F: False
Exercise 10.2 ★
Draw the tree of . Give its size, its height and the number of its subformulas.
Solution
Solution of Exercise 10.2.
The root is ; its left child is , with children (over and over ) and ; its right child is over over . Ten nodes: size 10. The longest path, , , , , , has four links: height 4. The subformulas are , , , , , , , and the formula: nine, the two leaves being one formula.
2. (p | ~q -> r) & ~~p size 10 height 4 subformulas 9
Exercise 10.3 ★
Which of these formulas are tautologies, which are antilogies, and which are neither? (a) ; (b) ; (c) ; (d) .
Solution
Solution of Exercise 10.3.
(a) A tautology: its right side is false only when is false and true, which makes false too (contraposition). (b) Neither: false for false and true, true for both true. (c) A tautology: if is false, is true. (d) An antilogy: is false only if is true and false, which needs false.
3. (p -> q) -> ~q -> ~p : tautology
3. (p -> q) -> q -> p : satisfiable
3. p | (p -> q) : tautology
3. ~(p -> q -> p) : antilogy
Exercise 10.4 ★
Predict what the program prints, simplified forms included.
p, q, r = Var("p"), Var("q"), Var("r")
f = ~(p & (q | ~r))
print("formula:", f)
print("NNF:", nnf(f))
print("CNF:", show_sets(simplify(cnf(f)), "&", "|"))
print("DNF:", show_sets(simplify(dnf(f)), "|", "&"))
Solution
Solution of Exercise 10.4.
formula: ~(p & (q | ~r))
NNF: ~p | ~q & r
CNF: (~p | ~q) & (~p | r)
DNF: (~p) | (~q & r)
De Morgan turns the negated conjunction into , then . The DNF is this formula itself; the CNF distributes over the conjunction.
Exercise 10.5 ★★
A student’s evaluator reads as “if then ”, with the table below. Find the error from the printed rows, explain why p >> p is no longer a tautology, and correct the table.
TABLES = {"&": lambda a, b: a and b, "|": lambda a, b: a or b,
"->": lambda a, b: b if a else False, # "if a then b"
"<->": lambda a, b: a == b}
p -> q F F F T
p -> p F F T T
(p -> q) | (q -> p) F F F T
Solution
Solution of Exercise 10.5.
The rows of are F, F, F, T where they should be T, T, F, T: the student makes the implication false whenever is false, as if it were . Then is false when is, and is no tautology. An implication with a false premise is true: the entry must be lambda a, b: b if a else True, that is (not a) or b.
Exercise 10.6 ★★
This converter puts all the literals of a disjunction in one clause. Find a formula on which it is wrong, explain the mistake with distributivity, and say on which formulas it is right.
def literals(g):
if isinstance(g, Bin):
return literals(g.left) | literals(g.right)
return frozenset([literal(g)])
def cnf_wrong(f):
g = nnf(f)
if isinstance(g, Bin) and g.op == "&":
return cnf_wrong(g.left) + cnf_wrong(g.right)
return [literals(g)] # a disjunction: all its literals in one clause
formula: p | q & r CNF given: (p | q | r)
differ at {'p': False, 'q': False, 'r': True}
differ at {'p': False, 'q': True, 'r': False}
Solution
Solution of Exercise 10.6.
On it gives the single clause , true for and false and true, where the formula is false. Distributivity gives : a conjunction under a disjunction must be distributed, not flattened. The converter is right on the formulas whose negation normal form has no below a , which are already conjunctions of clauses, and wrong on most others (not all: on it happens to be right).
Exercise 10.7 ★★
Write is_consequence(gamma, phi), which decides by trying every valuation of the variables of and . Test it on , on , and on ; explain the last one.
Solution
Solution of Exercise 10.7.
def is_consequence(gamma, phi):
"""True when every valuation making all of gamma true makes phi true."""
names = sorted(set(variables(phi)).union(*(variables(g) for g in gamma)))
for v in valuations(names):
if all(value(g, v) for g in gamma) and not value(phi, v):
return False # a counter-model
return True
has no model, so “every model of it is a model of ” holds for want of a counterexample: from a contradiction anything follows. The test tests/test_formula.py checks the three cases, and on random formulas that exactly when the conjunction of implies is a tautology.
Exercise 10.8 ★★
Write exactly_one(lits), which returns clauses true exactly when one of the given literals is true, and test it by counting the models for up to six literals.
Solution
Solution of Exercise 10.8.
def exactly_one(lits):
"""One clause says "at least one"; one clause per pair says "not both"."""
at_least = [frozenset(lits)]
at_most = [frozenset([neg(a), neg(b)]) for a, b in combinations(lits, 2)]
return at_least + at_most
The test tests/test_formula.py tries every valuation for : the models are exactly the valuations with one literal true.
Exercise 10.9 ★★
Count the clauses of the encoding of Exercise 10.8 for literals, and their literals. How many clauses say that each of the 7 members of a committee has exactly one of 7 seats and each seat exactly one member?
Exercise 10.10 ★★★
Prove that every formula is equivalent to a formula that uses only the connectives and , by induction on the formula. What is the size of the result, as a function of the size of the original, if the original has no ? Why does cause a problem?
Solution
Solution of Exercise 10.10.
Define by induction: , , , , , . By induction, uses only and , and : for a variable it is the same formula; for each connective, the induction hypothesis gives and , and De Morgan’s laws and the rewriting of implication give the equivalence of the two sides. Without , each connective adds at most four nodes where it had one, and by induction . A copies and twice, so nested equivalences double the size at each level: the result can be exponential in the height.
Exercise 10.11 ★★★
Write quine_units, Quine’s algorithm with unit propagation before each choice, counting its nodes. Compare its node counts with those of quine on the dinner, the colourings with two and three colours, and the committee of the problem, satisfiable and not.
Solution
Solution of Exercise 10.11.
def quine_units(clauses, stats):
stats["nodes"] += 1
forced = set()
while frozenset() not in clauses:
unit = next((c for c in clauses if len(c) == 1), None)
if unit is None:
break
(lit,) = unit # a clause of one literal: that literal must be true
forced.add(lit)
clauses = assign(clauses, lit)
if frozenset() in clauses:
return None
if not clauses:
return forced
x = min(clauses[0], key=lambda lit: lit.lstrip("~")).lstrip("~")
for lit in (x, neg(x)):
model = quine_units(assign(clauses, lit), stats)
if model is not None:
return model | forced | {lit}
return None
$ python quine_units.py
CNF clauses plain units satisfiable
dinner 4 6 2 True
2 colours 139 253 3 False
3 colours 189 185 25 True
committee 533 3219 2 True
committee + 1 588 182667 21 False
The two always agree, which the program asserts and the test tests/test_quine.py checks on 300 random sets of clauses against brute force. With units, a choice is made only when nothing is forced: on the committee, the units settle almost everything, and a contradiction is found as soon as the forced literals clash.
Exercise 10.12 ★★★
Prove that is a tautology if and only if is unsatisfiable, and deduce a way to test a tautology with Quine’s algorithm. Then prove that unit propagation never turns a satisfiable set of clauses into an unsatisfiable one, nor the converse.
Solution
Solution of Exercise 10.12.
is a tautology when every valuation makes it true, that is when no valuation makes true: when has no model. To test , run Quine’s algorithm on a CNF of (or on Tseitin’s encoding of , which is equisatisfiable): is a tautology if the answer is “none”, and otherwise the model returned is a valuation where is false. Unit propagation on a unit clause replaces by , with made true. A model of makes true, since is a clause of , and is then a model of ; a model of , with made true, is a model of (as in the proof of Proposition 10.12). So and are equisatisfiable, and so are the sets before and after each step of propagation.
10.7 Problem: Seating the committee
Problem 10.1
Weekend problem — Seating the committee
Seven members of the town’s library committee, Alma, Boris, Chloe, Dmitri, Elena, Farid and Greta (initials A to G), sit in a row of seven seats, numbered 1 to 7. Six rules constrain the seating: Alma sits next to Boris; Chloe does not sit next to Dmitri; Elena sits at an end; Greta, who chairs, sits in the middle seat; Farid sits next to Greta; Chloe sits next to Elena. The variable C6 says that Chloe sits in seat 6. The program writes the rules as formulas, turns them into clauses by Tseitin’s encoding, adds the clauses of Exercise 10.8 for the seats, solves, and checks the answer against all seatings.
GATES = { # the clauses of t <-> (a op b)
"&": lambda t, a, b: [[neg(t), a], [neg(t), b], [t, neg(a), neg(b)]],
"|": lambda t, a, b: [[neg(t), a, b], [t, neg(a)], [t, neg(b)]],
"->": lambda t, a, b: [[neg(t), neg(a), b], [t, a], [t, neg(b)]],
"<->": lambda t, a, b: [[neg(t), neg(a), b], [neg(t), a, neg(b)],
[t, a, b], [t, neg(a), neg(b)]],
}
def tseitin(f, prefix="t"):
clauses, names = [], {}
def literal(g):
"""A literal that is true exactly when g is, given the gate clauses."""
match g:
case Var(name):
return name
case Not(sub):
return neg(literal(sub))
case Bin(op, left, right):
if g not in names: # equal subformulas share one variable
a, b = literal(left), literal(right)
names[g] = t = f"{prefix}{len(names) + 1}"
clauses.extend(frozenset(c) for c in GATES[op](t, a, b))
return names[g]
clauses.append(frozenset([literal(f)])) # and the formula itself is true
return clauses
def at(m, s): # the variable "member m sits in seat s"
return Var(f"{m}{s}")
def any_of(fs):
return reduce(lambda a, b: a | b, fs)
def next_to(x, y):
return any_of([at(x, s) & any_of([at(y, t) for t in (s - 1, s + 1) if t in SEATS])
for s in SEATS])
RULES = {"Alma next to Boris": next_to("A", "B"),
"Chloe not next to Dmitri": ~next_to("C", "D"),
"Elena at an end": at("E", 1) | at("E", 7),
"Greta in the middle": at("G", 4),
"Farid next to Greta": next_to("F", "G"),
"Chloe next to Elena": next_to("C", "E")}
def seating_clauses(rules):
clauses = []
for m in MEMBERS:
clauses += exactly_one([f"{m}{s}" for s in SEATS])
for s in SEATS:
clauses += exactly_one([f"{m}{s}" for m in MEMBERS])
for k, f in enumerate(rules.values()):
clauses += tseitin(f, prefix=f"r{k + 1}t")
return clauses
$ python committee.py
Alma next to Boris size 37 naive CNF 128 clauses Tseitin 55 clauses
Chloe not next to Dmitri size 38 naive CNF 12 clauses Tseitin 55 clauses
Elena at an end size 3 naive CNF 1 clauses Tseitin 4 clauses
Greta in the middle size 1 naive CNF 1 clauses Tseitin 1 clauses
Farid next to Greta size 37 naive CNF 128 clauses Tseitin 55 clauses
Chloe next to Elena size 37 naive CNF 128 clauses Tseitin 55 clauses
533 clauses in all
satisfiable: True | nodes: 3219 | checked: True
seating: ABDGFCE
8 seatings out of 5040 obey the rules: ABDGFCE BADGFCE DABGFCE DBAGFCE ECFGABD ECFGBAD ECFGDAB ECFGDBA
with Farid next to Elena: None | nodes: 182667 | by permutations: 0
Part I — The encoding.
- How many variables describe a seating? How many valuations do they have, and how many of them are seatings?
- Write the rule “Alma sits next to Boris” as
next_tobuilds it, for seats 1, 2 and 7 only. - Check that the formula of “Alma next to Boris” has size 37: count its variables and its connectives.
- Why is “Chloe not next to Dmitri” of size 38?
- How many clauses do the seat constraints produce, members and seats together?
- Check the total of 533 clauses.
Part II — Normal forms and their cost.
- The naive CNF of “Alma next to Boris” has 128 clauses. Explain the number by distributivity.
- Why does the naive CNF of “Chloe not next to Dmitri” have only 12 clauses? Write two of them.
- Is the formula of “Alma next to Boris” in DNF? Is “Elena at an end”?
- With the seat clauses in force, “Alma next to Boris” is equivalent to a formula of fewer clauses: . Explain why, and count its clauses.
- By Proposition 10.8, which kind of rule would make the naive CNF unusable?
- Why do the seat constraints need no Tseitin variable?
Part III — Tseitin’s encoding.
- Check that the three clauses of the
&gate say , by a truth table of eight rows. - Why does a negation need no new variable, and why can equal subformulas share one?
- Show that from any model of one obtains a model of
tseitin(f), by giving each new variable the value of its subformula. - Show that any model of
tseitin(f)is a model of on the variables of . - Deduce that and
tseitin(f)are equisatisfiable, though not equivalent. - Prove Tseitin’s theorem: a formula of size has an equisatisfiable CNF of at most clauses, each of at most three literals. Check the bound on the six rules.
Part IV — Solving and reading back.
- Read the seating from the output and check each rule on it.
- Why do the eight seatings come in pairs? What does each pair have in common?
- Plain Quine’s algorithm took 3219 nodes. In Exercise 10.11, with unit propagation, it takes 2. Which unit clause starts the propagation?
- Show by hand, without any search, that adding “Farid sits next to Elena” makes the rules unsatisfiable.
- Why did the plain algorithm need 182667 nodes to reach the same conclusion?
- State the named result of the problem, Tseitin’s theorem, and the committee’s count.
Solution
Solution of Problem 10.1.
1. 49 variables, valuations, of which describe seatings, one true variable per member and per seat.
2. .
3. Variables: the seven , and one neighbour for seats 1 and 7, two for the five others: leaves. Connectives: five inner , seven , six outer : 18. .
4. It is the same formula with at the root.
5. Each of the 14 groups (7 members, 7 seats) gives 22 clauses: 308.
6. .
7. The formula is a disjunction of seven conjunctions of two parts, and the part about . A clause of the CNF takes one part from each conjunction: choices (the parts about are themselves disjunctions, which merge into the clause).
8. The negation of a disjunction is the conjunction of the negations: , two clauses for each of the five middle seats and one for each end: 12. For instance and .
9. No: the disjunctions sit inside the conjunctions. “Elena at an end”, , is a disjunction of literals: in DNF, and in CNF as a single clause.
10. Alma sits in exactly one seat , and the rule asks that Boris sit next to that one: for every seat, if Alma is there, Boris is beside it, . Seven clauses, equivalent to the rule only together with the seat clauses.
11. A rule that combines independent alternatives, such as “at least one of the pairs (A, B), (C, D), (E, F) sits side by side”: a disjunction of disjunctions of conjunctions, whose naive CNF multiplies the counts of its parts.
12. They are clauses already.
13. If is true, the first two clauses need and true, and the third holds. If is false, the first two hold and the third needs . So the three clauses hold exactly in the four rows where , of the eight rows of .
14. The literal is true exactly when is false, so the negation of the literal of stands for without any clause. Equal subformulas have equal truth values under every valuation, so one variable can stand for both.
15. Give each new variable the truth value, under the model, of the subformula it stands for. Each gate’s clauses say , which then holds, and the last clause, the literal of , is true because is.
16. By induction on the subformulas of : under a model of the clauses, the literal of has the truth value of . For a variable it is the variable; for a negation, the negated literal; for a binary connective, the gate’s clauses force to the value of . The last clause makes the literal of true, so is true.
17. By 15, if is satisfiable so are the clauses; by 16, the converse. They are not equivalent: they do not have the same variables, and a model of with wrong values for the new variables is not a model of the clauses.
18. Tseitin’s theorem. Let have leaves, binary connectives and negations, so . A tree whose inner nodes have one or two children has leaves (each binary node adds one branch). The encoding makes at most 4 clauses per binary connective and one for the root: at most clauses, each of at most three literals, and it is computed in one pass over the tree. The six rules: , , , , and .
19. ABDGFCE: Alma 1 and Boris 2 are neighbours; Chloe 6 and Dmitri 3 are not; Elena is at seat 7, an end; Greta at 4, the middle; Farid at 5, next to Greta; Chloe at 6, next to Elena.
20. The rules do not change when the row is read from the other end (seat becomes seat ): ends, middle and neighbours stay what they are. Each seating and its mirror image form a pair, such as ABDGFCE and ECFGDBA: the same neighbours, in reverse order.
21. The rule “Greta in the middle” is the single variable G4, whose encoding is the unit clause G4. Propagating it makes Greta absent from every other seat, and every other member absent from seat 4, and so on through the rules.
22. Elena sits at an end, which has a single neighbouring seat. Chloe and Farid must both sit next to her, so both in that seat, which holds one member. No seating obeys the rules, and the 5040 permutations confirm it.
23. It chooses variables in the order of their names, A1, A2, …, which say nothing about Chloe, Elena and Farid; the clash appears only deep in each branch, after many useless choices, and every branch must be refuted. Unit propagation follows the consequences of each choice at once and finds the clash in 21 nodes.
24. Tseitin’s theorem. Every formula of size has an equisatisfiable CNF of at most clauses, each of at most three literals, computed in one pass over its tree. The committee’s six rules, of sizes 37, 38, 3, 1, 37 and 37, give 225 clauses where the bound allows 300; with the 308 seat clauses, 533 clauses in all, whose model Quine’s algorithm found and the 5040 seatings confirmed.
এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ
- Colouring of a graph
- Equisatisfiable formulas
- Literal, clause
- Logical equivalence, logical consequence
- Model, satisfiable, tautology, antilogy
- Negation normal form, CNF, DNF
- Propositional variable, connective, formula
- Satisfiability problem, k-SAT
- Subformula, size, height
- Unit propagation
- Valuation, truth value