কম্পিউটার বিজ্ঞান · বই 3 · স্নাতক প্রথম বর্ষ

University Computer Science — Year 1

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: 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, pp, qq, ana\mathit{ana}, that stands for a statement which is either true or false. The connectives are ¬\neg (not), of arity one, and ∧\wedge (and), ∨\vee (or), →\rightarrow (implies) and ↔\leftrightarrow (if and only if), of arity two. The propositional formulas are defined inductively: every variable is a formula; if φ\varphi is a formula, so is ¬φ\neg\varphi; if φ\varphi and ψ\psi are formulas, so are (φ∧ψ)(\varphi \wedge \psi), (φ∨ψ)(\varphi \vee \psi), (φ→ψ)(\varphi \rightarrow \psi) and (φ↔ψ)(\varphi \leftrightarrow \psi); 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: ¬\neg binds tighter than ∧\wedge, which binds tighter than ∨\vee, then →\rightarrow and ↔\leftrightarrow; ∧\wedge and ∨\vee group to the left, →\rightarrow to the right, so that p→q→rp \rightarrow q \rightarrow r means p→(q→r)p \rightarrow (q \rightarrow r).

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
Listing 10.1. Formulas as Python data code/bachelor-1/10-propositional-logic/listings/formula.py

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, 1+size(φ)1 + \text{size}(\varphi) for ¬φ\neg\varphi, 1+size(φ)+size(ψ)1 + \text{size}(\varphi) + \text{size}(\psi) for a binary connective. Its height is the length of the longest path from the root to a leaf: 0 for a variable, 1+height(φ)1 + \text{height}(\varphi), and 1+max⁡(height(φ),height(ψ))1 + \max(\text{height}(\varphi), \text{height}(\psi)).

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))
Listing 10.2. Size and height, by induction on the formula code/bachelor-1/10-propositional-logic/listings/formula.py

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)
Output 10.1. A formula, its tree printed with indentation, its size, height and subformulas, and six formulas written with only the necessary parentheses.
The tree of (p q) (q r). Its size counts nodes, its height the links on the longest path from the root. The root’s connective, , says what kind of formula it is: a conjunction.
The tree of (p→q)∧¬(q∨r)(p \rightarrow q) \wedge \neg(q \vee r). Its size counts nodes, its height the links on the longest path from the root. The root’s connective, ∧\wedge, says what kind of formula it is: a conjunction.

10.2 Valuations and truth

Definition 10.3 (Valuation, truth value)

A valuation assigns to each variable a value, true (T\mathrm{T}) or false (F\mathrm{F}). The truth value of a formula under a valuation vv is defined by induction: a variable has the value vv gives it; ¬φ\neg\varphi is true when φ\varphi is false; φ∧ψ\varphi \wedge \psi when both are true; φ∨ψ\varphi \vee \psi when at least one is; φ→ψ\varphi \rightarrow \psi unless φ\varphi is true and ψ\psi false; φ↔ψ\varphi \leftrightarrow \psi 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)))
Listing 10.3. Truth values, valuations and models code/bachelor-1/10-propositional-logic/listings/evaluate.py

The truth value of a formula depends only on the values of its own variables, so with nn variables a formula has 2n2^n 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
Output 10.2. Two truth values, the only model of the formula, and five formulas classified.

Definition 10.5 (Logical equivalence, logical consequence)

Two formulas are logically equivalent, written φ≡ψ\varphi \equiv \psi, if they have the same truth value under every valuation. A formula φ\varphi is a logical consequence of a set of formulas Γ\Gamma, written Γ⊨φ\Gamma \models \varphi, if every model of Γ\Gamma is a model of φ\varphi.

Thus φ\varphi is a tautology exactly when φ≡p∨¬p\varphi \equiv p \vee \neg p, and φ≡ψ\varphi \equiv \psi exactly when φ↔ψ\varphi \leftrightarrow \psi is a tautology. {p,p→q}⊨q\{p, p \rightarrow q\} \models q: in every model of the two formulas, qq is true. The formula ((p→q)→p)→p((p \rightarrow q) \rightarrow p) \rightarrow p 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))
Listing 10.4. A truth table, and one conjunction per true row code/bachelor-1/10-propositional-logic/listings/truth_table.py
$ 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)
Output 10.3. The truth table of (p→q)∧(q∨r)(p \rightarrow q) \wedge (q \vee r) and the disjunction read from its true rows.
The complete DNF of = (p q) (q r). Each true row becomes the conjunction of literals true exactly on that row; their disjunction is true exactly on the true rows, so it is equivalent to .
The complete DNF of φ=(p→q)∧(q∨r)\varphi = (p \rightarrow q) \wedge (q \vee r). Each true row becomes the conjunction of literals true exactly on that row; their disjunction is true exactly on the true rows, so it is equivalent to φ\varphi.

10.3 Equivalence and normal forms

The following equivalences hold for all formulas φ\varphi, ψ\psi, χ\chi; each is checked by a truth table of four or eight rows.

  • Double negation: ¬¬φ≡φ\neg\neg\varphi \equiv \varphi. Excluded middle: φ∨¬φ\varphi \vee \neg\varphi is a tautology.
  • De Morgan’s laws: ¬(φ∧ψ)≡¬φ∨¬ψ\neg(\varphi \wedge \psi) \equiv \neg\varphi \vee \neg\psi and ¬(φ∨ψ)≡¬φ∧¬ψ\neg(\varphi \vee \psi) \equiv \neg\varphi \wedge \neg\psi.
  • Distributivity: φ∨(ψ∧χ)≡(φ∨ψ)∧(φ∨χ)\varphi \vee (\psi \wedge \chi) \equiv (\varphi \vee \psi) \wedge (\varphi \vee \chi), and the same with ∧\wedge and ∨\vee exchanged.
  • Implication and equivalence rewritten: φ→ψ≡¬φ∨ψ\varphi \rightarrow \psi \equiv \neg\varphi \vee \psi and φ↔ψ≡(φ→ψ)∧(ψ→φ)\varphi \leftrightarrow \psi \equiv (\varphi \rightarrow \psi) \wedge (\psi \rightarrow \varphi).

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: pp, ¬p\neg p. A clause is a disjunction of literals, p∨¬q∨rp \vee \neg q \vee r, 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 ∧\wedge, ∨\vee and ¬\neg, and ¬\neg 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), "|", "&")
Listing 10.5. Negation normal form, then CNF and DNF by distribution code/bachelor-1/10-propositional-logic/listings/normal_forms.py

nnf rewrites →\rightarrow and ↔\leftrightarrow, 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)
Output 10.4. Two formulas in their normal forms; the simplified forms drop the sets that hold a literal and its negation.

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}")
Listing 10.6. A formula of size 4n−14n - 1 and its CNF code/bachelor-1/10-propositional-logic/listings/blowup.py
$ 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
Output 10.5. The CNF doubles with each pair: no clause is redundant.

Proposition 10.8 (An exponential CNF)

Every CNF equivalent to φn=(x1∧y1)∨⋯∨(xn∧yn)\varphi_n = (x_1 \wedge y_1) \vee \dots \vee (x_n \wedge y_n) has at least 2n2^n clauses.

Proof. Let CC be an equivalent CNF. For each choice s=(s1,…,sn)s = (s_1, \dots, s_n) of one variable si∈{xi,yi}s_i \in \{x_i, y_i\} per pair, let vsv_s make the chosen variables false and the others true. Each pair has a false variable, so φn\varphi_n is false under vsv_s, and so is CC: some clause cc of CC is false under vsv_s, which means its positive literals are among s1,…,sns_1, \dots, s_n. Now fix ii and let uu be vsv_s with sis_i made true. Pair ii is now true, so φn\varphi_n and every clause of CC are true under uu. The clause cc changed from false to true, so it contains a literal whose value changed: only sis_i changed, and from false to true, so cc contains the literal sis_i. This holds for every ii, so the positive literals of cc are exactly s1,…,sns_1, \dots, s_n. Two different choices give clauses with different positive literals, hence different clauses: there are at least 2n2^n 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, kk-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. kk-SAT is the same problem for sets of clauses with at most kk literals each.

Trying the 2n2^n valuations answers it, and models in Listing 10.3 does exactly that; with 49 variables it would try more than 5×10145 \times 10^{14} 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 SS:

  1. If SS is empty, it is satisfied: return the empty valuation. If SS contains the empty clause, it is unsatisfiable: return “none”.
  2. Otherwise choose a variable xx of SS. Make xx true: remove the clauses that contain xx, and remove the literal ¬x\neg x from the others. Decide the result recursively; if it has a model, add xx true to it and return it.
  3. Otherwise make xx 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
Listing 10.7. Quine’s algorithm, counting its nodes code/bachelor-1/10-propositional-logic/listings/quine.py
$ 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
Output 10.6. An unsatisfiable set of four clauses and a satisfiable one; seven calls each.

Proposition 10.12 (Correctness of Quine’s algorithm)

On every finite set of clauses SS, Quine’s algorithm terminates, returns a valuation of some variables that satisfies every clause of SS if SS is satisfiable (the other variables may take any value), and returns “none” otherwise.

Proof. By induction on the number nn of variables of SS. If n=0n = 0, SS is empty or holds only empty clauses, and step 1 answers correctly. Let n≥1n \geq 1, and suppose step 1 does not apply. Let SxS_x and S¬xS_{\neg x} be the sets obtained by making xx true and false; each has at most n−1n - 1 variables, so by induction the recursive calls terminate and answer correctly. A valuation vv with v(x)=Tv(x) = \mathrm{T} satisfies SS exactly when it satisfies SxS_x: the removed clauses contain xx and are true, and the removed literals ¬x\neg x are false and change nothing. The same holds with F\mathrm{F} and S¬xS_{\neg x}. Every valuation gives xx one of the two values, so SS is satisfiable exactly when SxS_x or S¬xS_{\neg x} is, and the returned valuation, extended with the value of xx, satisfies SS. ∎

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 2n+12^{n + 1} 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 xx often creates unit clauses: ¬x∨y\neg x \vee y becomes yy as soon as xx 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, ana\mathit{ana} 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")
Listing 10.8. Who can come to dinner? code/bachelor-1/10-propositional-logic/listings/puzzle.py
$ 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
Output 10.7. Two guest lists out of sixteen; not everyone can come.
Quine’s algorithm on the CNF of the dinner (initials for the names). The six nodes are the six calls counted in ; the dashed branches are never visited, since a model was found first. The model read on the path: a, b, d true, c false.
Quine’s algorithm on the CNF of the dinner (initials for the names). The six nodes are the six calls counted in Output 10.7; the dashed branches are never visited, since a model was found first. The model read on the path: aa, bb, dd true, cc false.

Definition 10.14 (Colouring of a graph)

A colouring of a graph with kk colours gives each vertex one of kk colours so that the two ends of every edge have different colours; a graph that has one is kk-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 red5\mathit{red}_5 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))
Listing 10.9. Colouring the friendship graph by SAT code/bachelor-1/10-propositional-logic/listings/colouring.py
$ 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
Output 10.8. Two colours are not enough; three are, and the model is read back as three tables.
The friendship graph coloured by the model of : red, green and blue. No edge joins two vertices of the same colour. Two colours fail because the graph has a cycle of odd length (the friends 1, 5 and 12 form a triangle), which cannot alternate between two colours.
The friendship graph coloured by the model of Output 10.8: red, green and blue. No edge joins two vertices of the same colour. Two colours fail because the graph has a cycle of odd length (the friends 1, 5 and 12 form a triangle), which cannot alternate between two colours.

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 ¬(p∧q)→(r∨¬p)\neg(p \wedge q) \rightarrow (r \vee \neg p) when pp is true and qq, rr are false.

Solution

Solution of Exercise 10.1.

p∧qp \wedge q is false, so ¬(p∧q)\neg(p \wedge q) is true; ¬p\neg p is false and rr is false, so r∨¬pr \vee \neg p 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
Output 10.12. The check. Some lines are left out.

Exercise 10.2 ★

Draw the tree of ((p∨¬q)→r)∧¬¬p((p \vee \neg q) \rightarrow r) \wedge \neg\neg p. Give its size, its height and the number of its subformulas.

Solution

Solution of Exercise 10.2.

The root is ∧\wedge; its left child is →\rightarrow, with children ∨\vee (over pp and ¬\neg over qq) and rr; its right child is ¬\neg over ¬\neg over pp. Ten nodes: size 10. The longest path, ∧\wedge, →\rightarrow, ∨\vee, ¬\neg, qq, has four links: height 4. The subformulas are pp, qq, ¬q\neg q, p∨¬qp \vee \neg q, rr, (p∨¬q)→r(p \vee \neg q) \rightarrow r, ¬p\neg p, ¬¬p\neg\neg p and the formula: nine, the two leaves pp being one formula.

2. (p | ~q -> r) & ~~p size 10 height 4 subformulas 9
Output 10.13. The check. Some lines are left out.

Exercise 10.3 ★

Which of these formulas are tautologies, which are antilogies, and which are neither? (a) (p→q)→(¬q→¬p)(p \rightarrow q) \rightarrow (\neg q \rightarrow \neg p); (b) (p→q)→(q→p)(p \rightarrow q) \rightarrow (q \rightarrow p); (c) p∨(p→q)p \vee (p \rightarrow q); (d) ¬(p→(q→p))\neg(p \rightarrow (q \rightarrow p)).

Solution

Solution of Exercise 10.3.

(a) A tautology: its right side is false only when qq is false and pp true, which makes p→qp \rightarrow q false too (contraposition). (b) Neither: false for pp false and qq true, true for both true. (c) A tautology: if pp is false, p→qp \rightarrow q is true. (d) An antilogy: p→(q→p)p \rightarrow (q \rightarrow p) is false only if pp is true and q→pq \rightarrow p false, which needs pp false.

3. (p -> q) -> ~q -> ~p : tautology
3. (p -> q) -> q -> p : satisfiable
3. p | (p -> q) : tautology
3. ~(p -> q -> p) : antilogy
Output 10.14. The check. Some lines are left out.

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)), "|", "&"))
Listing 10.10. Three normal forms code/bachelor-1/10-propositional-logic/listings/exo_nf.py
Solution

Solution of Exercise 10.4.

formula: ~(p & (q | ~r))
NNF: ~p | ~q & r
CNF: (~p | ~q) & (~p | r)
DNF: (~p) | (~q & r)
Output 10.15. The three forms. Some lines are left out.

De Morgan turns the negated conjunction into ¬p∨¬(q∨¬r)\neg p \vee \neg(q \vee \neg r), then ¬p∨(¬q∧r)\neg p \vee (\neg q \wedge r). The DNF is this formula itself; the CNF distributes ¬p\neg p over the conjunction.

Exercise 10.5 ★★

A student’s evaluator reads p→qp \rightarrow q as “if pp then qq”, 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}
Listing 10.11. The implication of the student code/bachelor-1/10-propositional-logic/listings/exo_imp.py
p -> q               F F F T
p -> p               F F T T
(p -> q) | (q -> p)  F F F T
Output 10.9. Rows for (F,F), (F,T), (T,F), (T,T). Some lines are left out.
Solution

Solution of Exercise 10.5.

The rows of p→qp \rightarrow q are F, F, F, T where they should be T, T, F, T: the student makes the implication false whenever pp is false, as if it were p∧qp \wedge q. Then p→pp \rightarrow p is false when pp 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
Listing 10.12. A converter that does not distribute code/bachelor-1/10-propositional-logic/listings/exo_cnf_bug.py
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}
Output 10.10. Its answer on p∨(q∧r)p \vee (q \wedge r). Some lines are left out.
Solution

Solution of Exercise 10.6.

On p∨(q∧r)p \vee (q \wedge r) it gives the single clause p∨q∨rp \vee q \vee r, true for pp and qq false and rr true, where the formula is false. Distributivity gives (p∨q)∧(p∨r)(p \vee q) \wedge (p \vee r): a conjunction under a disjunction must be distributed, not flattened. The converter is right on the formulas whose negation normal form has no ∧\wedge below a ∨\vee, which are already conjunctions of clauses, and wrong on most others (not all: on p∨(q∧q)p \vee (q \wedge q) it happens to be right).

Exercise 10.7 ★★

Write is_consequence(gamma, phi), which decides Γ⊨φ\Gamma \models \varphi by trying every valuation of the variables of Γ\Gamma and φ\varphi. Test it on {p,p→q}⊨q\{p, p \rightarrow q\} \models q, on {q,p→q}⊭p\{q, p \rightarrow q\} \not\models p, and on {p,¬p}⊨q\{p, \neg p\} \models q; 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
Logical consequence by brute force code/bachelor-1/10-propositional-logic/exercises/consequence.py

{p,¬p}\{p, \neg p\} has no model, so “every model of it is a model of qq” 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 Γ⊨φ\Gamma \models \varphi exactly when the conjunction of Γ\Gamma implies φ\varphi 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
Exactly one, pairwise code/bachelor-1/10-propositional-logic/listings/exactly.py

The test tests/test_formula.py tries every valuation for n≤6n \leq 6: the models are exactly the nn valuations with one literal true.

Exercise 10.9 ★★

Count the clauses of the encoding of Exercise 10.8 for nn 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?

Solution

Solution of Exercise 10.9.

One clause of nn literals for “at least one”, and one clause of two literals per pair: n(n−1)/2+1n(n - 1)/2 + 1 clauses, with n+n(n−1)=n2n + n(n - 1) = n^2 literals. For the committee, 7 groups of members and 7 groups of seats of 7 literals each: 14×22=30814 \times 22 = 308 clauses.

Exercise 10.10 ★★★

Prove that every formula is equivalent to a formula that uses only the connectives ¬\neg and ∧\wedge, 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 ↔\leftrightarrow? Why does ↔\leftrightarrow cause a problem?

Solution

Solution of Exercise 10.10.

Define TT by induction: T(p)=pT(p) = p, T(¬φ)=¬T(φ)T(\neg\varphi) = \neg T(\varphi), T(φ∧ψ)=T(φ)∧T(ψ)T(\varphi \wedge \psi) = T(\varphi) \wedge T(\psi), T(φ∨ψ)=¬(¬T(φ)∧¬T(ψ))T(\varphi \vee \psi) = \neg(\neg T(\varphi) \wedge \neg T(\psi)), T(φ→ψ)=¬(T(φ)∧¬T(ψ))T(\varphi \rightarrow \psi) = \neg(T(\varphi) \wedge \neg T(\psi)), T(φ↔ψ)=T((φ→ψ)∧(ψ→φ))T(\varphi \leftrightarrow \psi) = T((\varphi \rightarrow \psi) \wedge (\psi \rightarrow \varphi)). By induction, T(φ)T(\varphi) uses only ¬\neg and ∧\wedge, and T(φ)≡φT(\varphi) \equiv \varphi: for a variable it is the same formula; for each connective, the induction hypothesis gives T(φ)≡φT(\varphi) \equiv \varphi and T(ψ)≡ψT(\psi) \equiv \psi, and De Morgan’s laws and the rewriting of implication give the equivalence of the two sides. Without ↔\leftrightarrow, each connective adds at most four nodes where it had one, and by induction size(T(φ))≤4 size(φ)−3\text{size}(T(\varphi)) \leq 4\,\text{size}(\varphi) - 3. A ↔\leftrightarrow copies φ\varphi and ψ\psi 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
Quine’s algorithm with unit propagation code/bachelor-1/10-propositional-logic/listings/quine_units.py
$ 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
Output 10.16. The two algorithms on five sets of clauses.

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 φ\varphi is a tautology if and only if ¬φ\neg\varphi 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.

φ\varphi is a tautology when every valuation makes it true, that is when no valuation makes ¬φ\neg\varphi true: when ¬φ\neg\varphi has no model. To test φ\varphi, run Quine’s algorithm on a CNF of ¬φ\neg\varphi (or on Tseitin’s encoding of ¬φ\neg\varphi, which is equisatisfiable): φ\varphi is a tautology if the answer is “none”, and otherwise the model returned is a valuation where φ\varphi is false. Unit propagation on a unit clause ℓ\ell replaces SS by SℓS_\ell, SS with ℓ\ell made true. A model of SS makes ℓ\ell true, since ℓ\ell is a clause of SS, and is then a model of SℓS_\ell; a model of SℓS_\ell, with ℓ\ell made true, is a model of SS (as in the proof of Proposition 10.12). So SS and SℓS_\ell 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 7!=50407! = 5040 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
Listing 10.13. Tseitin’s encoding: one variable per binary connective code/bachelor-1/10-propositional-logic/listings/tseitin.py
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
Listing 10.14. The committee’s clauses code/bachelor-1/10-propositional-logic/listings/committee.py
$ 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
Output 10.11. Sizes, clause counts, a seating, the check, and one rule too many.

Part I — The encoding.

  1. How many variables describe a seating? How many valuations do they have, and how many of them are seatings?
  2. Write the rule “Alma sits next to Boris” as next_to builds it, for seats 1, 2 and 7 only.
  3. Check that the formula of “Alma next to Boris” has size 37: count its variables and its connectives.
  4. Why is “Chloe not next to Dmitri” of size 38?
  5. How many clauses do the seat constraints produce, members and seats together?
  6. Check the total of 533 clauses.

Part II — Normal forms and their cost.

  1. The naive CNF of “Alma next to Boris” has 128 clauses. Explain the number 272^7 by distributivity.
  2. Why does the naive CNF of “Chloe not next to Dmitri” have only 12 clauses? Write two of them.
  3. Is the formula of “Alma next to Boris” in DNF? Is “Elena at an end”?
  4. With the seat clauses in force, “Alma next to Boris” is equivalent to a formula of fewer clauses: ⋀s(¬As∨Bs−1∨Bs+1)\bigwedge_s (\neg A_s \vee B_{s-1} \vee B_{s+1}). Explain why, and count its clauses.
  5. By Proposition 10.8, which kind of rule would make the naive CNF unusable?
  6. Why do the seat constraints need no Tseitin variable?

Part III — Tseitin’s encoding.

  1. Check that the three clauses of the & gate say t↔(a∧b)t \leftrightarrow (a \wedge b), by a truth table of eight rows.
  2. Why does a negation need no new variable, and why can equal subformulas share one?
  3. Show that from any model of φ\varphi one obtains a model of tseitin(f), by giving each new variable the value of its subformula.
  4. Show that any model of tseitin(f) is a model of φ\varphi on the variables of φ\varphi.
  5. Deduce that φ\varphi and tseitin(f) are equisatisfiable, though not equivalent.
  6. Prove Tseitin’s theorem: a formula of size mm has an equisatisfiable CNF of at most 2m−12m - 1 clauses, each of at most three literals. Check the bound on the six rules.

Part IV — Solving and reading back.

  1. Read the seating from the output and check each rule on it.
  2. Why do the eight seatings come in pairs? What does each pair have in common?
  3. Plain Quine’s algorithm took 3219 nodes. In Exercise 10.11, with unit propagation, it takes 2. Which unit clause starts the propagation?
  4. Show by hand, without any search, that adding “Farid sits next to Elena” makes the rules unsatisfiable.
  5. Why did the plain algorithm need 182667 nodes to reach the same conclusion?
  6. State the named result of the problem, Tseitin’s theorem, and the committee’s count.
Solution

Solution of Problem 10.1.

1. 49 variables, 249≈5.6×10142^{49} \approx 5.6 \times 10^{14} valuations, of which 7!=50407! = 5040 describe seatings, one true variable per member and per seat.

2. (A1∧B2)∨(A2∧(B1∨B3))∨⋯∨(A7∧B6)(A_1 \wedge B_2) \vee (A_2 \wedge (B_1 \vee B_3)) \vee \dots \vee (A_7 \wedge B_6).

3. Variables: the seven AsA_s, and one neighbour for seats 1 and 7, two for the five others: 7+2+10=197 + 2 + 10 = 19 leaves. Connectives: five inner ∨\vee, seven ∧\wedge, six outer ∨\vee: 18. 19+18=3719 + 18 = 37.

4. It is the same formula with ¬\neg at the root.

5. Each of the 14 groups (7 members, 7 seats) gives 22 clauses: 308.

6. 308+55+55+4+1+55+55=533308 + 55 + 55 + 4 + 1 + 55 + 55 = 533.

7. The formula is a disjunction of seven conjunctions of two parts, AsA_s and the part about BB. A clause of the CNF takes one part from each conjunction: 27=1282^7 = 128 choices (the parts about BB are themselves disjunctions, which merge into the clause).

8. The negation of a disjunction is the conjunction of the negations: ¬(Cs∧(Ds−1∨Ds+1))≡(¬Cs∨¬Ds−1)∧(¬Cs∨¬Ds+1)\neg(C_s \wedge (D_{s-1} \vee D_{s+1})) \equiv (\neg C_s \vee \neg D_{s-1}) \wedge (\neg C_s \vee \neg D_{s+1}), two clauses for each of the five middle seats and one for each end: 12. For instance ¬C1∨¬D2\neg C_1 \vee \neg D_2 and ¬C2∨¬D3\neg C_2 \vee \neg D_3.

9. No: the disjunctions Bs−1∨Bs+1B_{s-1} \vee B_{s+1} sit inside the conjunctions. “Elena at an end”, E1∨E7E_1 \vee E_7, is a disjunction of literals: in DNF, and in CNF as a single clause.

10. Alma sits in exactly one seat ss, and the rule asks that Boris sit next to that one: for every seat, if Alma is there, Boris is beside it, ¬As∨Bs−1∨Bs+1\neg A_s \vee B_{s-1} \vee B_{s+1}. 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 tt is true, the first two clauses need aa and bb true, and the third holds. If tt is false, the first two hold and the third needs ¬a∨¬b\neg a \vee \neg b. So the three clauses hold exactly in the four rows where t=a∧bt = a \wedge b, of the eight rows of (t,a,b)(t, a, b).

14. The literal ¬ℓ\neg\ell is true exactly when ℓ\ell is false, so the negation of the literal of gg stands for ¬g\neg g 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 t↔(aopb)t \leftrightarrow (a \mathbin{\mathrm{op}} b), which then holds, and the last clause, the literal of φ\varphi, is true because φ\varphi is.

16. By induction on the subformulas gg of φ\varphi: under a model of the clauses, the literal of gg has the truth value of gg. For a variable it is the variable; for a negation, the negated literal; for a binary connective, the gate’s clauses force tt to the value of aopba \mathbin{\mathrm{op}} b. The last clause makes the literal of φ\varphi true, so φ\varphi is true.

17. By 15, if φ\varphi 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 φ\varphi with wrong values for the new variables is not a model of the clauses.

18. Tseitin’s theorem. Let φ\varphi have LL leaves, BB binary connectives and NN negations, so m=L+B+Nm = L + B + N. A tree whose inner nodes have one or two children has L=B+1L = B + 1 leaves (each binary node adds one branch). The encoding makes at most 4 clauses per binary connective and one for the root: at most 4B+1=2(2B+1)−1≤2(L+B+N)−1=2m−14B + 1 = 2(2B + 1) - 1 \leq 2(L + B + N) - 1 = 2m - 1 clauses, each of at most three literals, and it is computed in one pass over the tree. The six rules: 55≤7355 \leq 73, 55≤7555 \leq 75, 4≤54 \leq 5, 1≤11 \leq 1, 55≤7355 \leq 73 and 55≤7355 \leq 73.

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 ss becomes seat 8−s8 - s): 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 mm has an equisatisfiable CNF of at most 2m−12m - 1 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.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো