علوم الحاسوب · الكتاب 5 · السنة الجامعية 3

University Computer Science — Year 3

هذا الكتاب غير متوفر بعد باللغة العربية. النسخ المتوفرة: English.

University Computer Science — Year 3 · السنة الجامعية 3

18Approximation and Exact Methods for Hard Problems

Chapter 17 showed that vertex cover, the travelling salesman problem and satisfiability are NP-complete: no algorithm is known that solves every instance in polynomial time. Yet delivery vans get routed and chips get verified every day. This chapter is about how. There are two ways out. An approximation algorithm runs in polynomial time and proves how far from the optimum it can be. An exact method searches, but prunes so much that real instances finish: branch and bound with a relaxation, and the clause-learning solvers that decide formulas with millions of clauses. Between them sit Horn formulas, a special case that is easy, and local search, which is often good and promises nothing. Every method is run against the exact optimum on small instances, and the gaps are measured.

You already know

A matching of a graph is a set of edges no two of which share a vertex (Year 2 volume). A minimum spanning tree connects all the vertices of a weighted graph with the least total weight, and Prim’s algorithm finds one (Year 1 volume). Branch and bound explores a tree of partial choices and cuts a branch as soon as a bound shows it cannot beat the best solution found so far; backtracking undoes the last choice when it fails (Year 1 volume). Unit propagation sets the last literal of a clause whose other literals are all false (Year 1 volume). The DPLL solver dpll.py of Chapter 17 propagates units, then branches on a variable.

18.1 Approximation ratios

Definition 18.1 (Approximation algorithm, approximation ratio, maximal matching)

For a minimisation problem, an approximation algorithm with approximation ratio ρ≥1\rho \ge 1 runs in polynomial time and returns, on every instance, a solution of cost at most ρ\rho times the optimum. A maximal matching is a matching to which no edge can be added; it need not be a matching of largest size.

The ratio is a promise about the worst instance, proved against an optimum the algorithm never sees. The proof always goes through a lower bound on the optimum that is easy to compute.

Theorem 18.2 (Vertex cover by matching)

Taking both ends of every edge of a maximal matching gives a vertex cover at most twice the smallest, and the factor 2 is reached.

The cover covers every edge, since an uncovered edge could be added to the matching. And any cover must contain one end of each matched edge, which share no vertex: the smallest cover has at least as many vertices as the matching has edges, half of what the algorithm takes. Exercise 18.7 completes the proof; the figure after the output shows a tight case.

def matching_cover(edges):
    cover = set()
    for u, v in edges:  # an edge with no end covered yet joins the matching
        if u not in cover and v not in cover:
            cover |= {u, v}
    return cover
Listing 18.1. Vertex cover from a maximal matching built greedily, edge by edge. code/bachelor-3/18-hard-problems/listings/vertex_cover.py
$ python vertex_cover.py
 n   edges   matching cover   minimum   ratio
 8      10                6         4   1.50
10      12                8         5   1.60
12      16               10         6   1.67
14      36               12         9   1.33
5 disjoint edges: matching cover 10, minimum 5
Output 18.1. Against the exact minimum on four random graphs, and on disjoint edges, where the factor 2 is reached.
A tight case of : in the complete bipartite graph on 3 + 3 vertices the matching may be perfect, and the algorithm takes 6 vertices where 3 suffice.
A tight case of Theorem 18.2: in the complete bipartite graph on 3+33 + 3 vertices the matching may be perfect, and the algorithm takes 6 vertices where 3 suffice.

18.1.1 Set cover

Definition 18.3 (Set cover problem)

The set cover problem: given a universe UU of nn elements and sets S1,…,SkS_1, \ldots, S_k whose union is UU, choose as few sets as possible whose union is UU.

Vertex cover is the special case where the elements are edges and each set is the edges at one vertex. The greedy algorithm takes, again and again, the set covering most of what is still uncovered.

def greedy(universe, sets):
    uncovered, chosen = set(universe), []
    while uncovered:
        i = max(range(len(sets)), key=lambda i: len(sets[i] & uncovered))
        chosen.append(i)
        uncovered -= sets[i]
    return chosen
Listing 18.2. Greedy set cover. code/bachelor-3/18-hard-problems/listings/set_cover.py

Theorem 18.4 (Greedy set cover)

The greedy algorithm returns a cover at most H(n)=1+12+⋯+1nH(n) = 1 + \frac{1}{2} + \cdots + \frac{1}{n} times the smallest, and H(n)≤ln⁡n+1H(n) \le \ln n + 1.

The bound is due to David Johnson in 1974 and László Lovász in 1975; Exercise 18.10 proves it by charging each element a share of the set that covers it first.

$ python set_cover.py
greedy: [2, 3, 4]  exact: [0, 1]
68 random instances: mean ratio 1.048, worst 1.400
Output 18.2. An instance built to fool greedy, which takes the largest set first and needs 3 where 2 suffice; and random instances, where greedy is usually optimal.

18.1.2 The travelling salesman

Definition 18.5 (Metric travelling salesman problem, tree doubling)

The metric travelling salesman problem asks for a shortest tour through nn points whose distances satisfy the triangle inequality d(a,c)≤d(a,b)+d(b,c)d(a, c) \le d(a, b) + d(b, c). Tree doubling walks round a minimum spanning tree, going down and up each edge once, and skips every point already visited.

Theorem 18.6 (Tree doubling)

On metric instances, tree doubling returns a tour at most twice the shortest.

Proof. Removing one edge from a shortest tour leaves a spanning tree, so the minimum spanning tree weighs at most the optimum T∗T^*. The walk round the tree crosses every edge twice, a closed walk of length 2 MST≤2T∗2\,\mathrm{MST} \le 2T^* through every point. Skipping a visited point replaces two steps a→b→ca \to b \to c by a→ca \to c, which is no longer by the triangle inequality. So the tour is at most 2T∗2T^*. ∎

Walking round the tree and skipping repeats visits the points in preorder, which is what tree_doubling computes. Nicos Christofides published in 1976 a refinement within 3/23/2 of the optimum, which adds a minimum matching on the odd-degree vertices of the tree instead of doubling it; Anatoliy Serdyukov found it independently. It is told here, not built. The exact answer for a few places comes from the Held–Karp dynamic program of 1962: for each set SS of places and each j∈Sj \in S, the shortest path from place 0 through all of SS ending at jj.

def held_karp(points):
    """Exact: best[(S, j)] = shortest path from 0 through the set S, ending at j."""
    n = len(points)
    d = [[dist(p, q) for q in points] for p in points]
    best = {(1 << j, j): (d[0][j], 0) for j in range(1, n)}
    for size in range(2, n):
        for s in range(1 << n):
            if s & 1 or bin(s).count("1") != size:
                continue
            for j in range(1, n):
                if s >> j & 1:
                    rest = s & ~(1 << j)
                    best[(s, j)] = min((best[(rest, k)][0] + d[k][j], k)
                                       for k in range(1, n) if rest >> k & 1)
    full = (1 << n) - 2
    _, j = min((best[(full, j)][0] + d[j][0], j) for j in range(1, n))
    tour, s = [], full
    while j:
        tour.append(j)
        s, j = s & ~(1 << j), best[(s, j)][1]
    return [0] + tour[::-1]
Listing 18.3. Held–Karp: exact, in time about n22nn^2 2^n. code/bachelor-3/18-hard-problems/listings/tsp.py
def tree_doubling(points):
    """Walk round the minimum spanning tree, skipping the vertices already visited:
    the preorder of the tree."""
    children, tour, stack = minimum_spanning_tree(points), [], [0]
    while stack:
        v = stack.pop()
        tour.append(v)
        stack.extend(reversed(children[v]))
    return tour
Listing 18.4. Tree doubling: the preorder of the minimum spanning tree. code/bachelor-3/18-hard-problems/listings/tsp.py

The delivery van of Brenmoor serves 12 of the town’s places, with straight-line distances between them.

The van’s 12 places. Left: the minimum spanning tree (grey, 11,367 m) and the tour tree doubling takes from it (18,427 m). Right: the optimal tour (16,635 m), from Held–Karp.
The van’s 12 places. Left: the minimum spanning tree (grey, 11,367 m) and the tour tree doubling takes from it (18,427 m). Right: the optimal tour (16,635 m), from Held–Karp.
$ python tsp_demo.py
12 places: optimum 16,635 m
  tree doubling 18,427 m (ratio 1.108)
  then 2-opt    17,617 m (ratio 1.059)
200 instances, tree doubling: mean ratio 1.216, worst 1.456, optimal in 3
200 instances, then 2-opt   : mean ratio 1.022, worst 1.156, optimal in 103
Output 18.3. The van’s tour, then 200 seeded choices of 12 places out of 30: tree doubling stays well inside its factor 2, and 2-opt (Section 18.5) closes most of the gap.

18.1.3 Problems with no good ratio

Definition 18.7 (Inapproximability)

A problem shows inapproximability at ratio ρ\rho when no polynomial-time algorithm achieves ratio ρ\rho unless P=NP\mathrm{P} = \mathrm{NP}.

Without the triangle inequality the travelling salesman has no constant ratio at all: an algorithm with ratio ρ\rho would decide whether a graph has a Hamiltonian cycle. Give the graph’s edges length 1 and every other pair length ρn+1\rho n + 1. A Hamiltonian cycle is a tour of length nn; any other tour uses a non-edge and costs more than ρn\rho n; so the algorithm’s tour has length at most ρn\rho n exactly when the graph has a Hamiltonian cycle (Exercise 18.11). Stronger results of this kind, showing that a constant ratio below some threshold is NP-hard even for problems that have one above it, come from the theory of probabilistically checkable proofs, which this book does not cover.

18.2 Branch and bound with a relaxation

Definition 18.8 (Relaxed problem, relaxation bound)

A relaxed problem drops or weakens a constraint, so that every solution of the original is still a solution and its optimum is at least as good. When it is easy to solve, its optimum is a relaxation bound: no solution of the original can beat it.

In the 0-1 knapsack problem each item is taken whole or left. Allowing fractions of items gives the fractional knapsack, solved by taking items in decreasing order of value per kilogram and cutting the first that does not fit: an item of higher value per kilogram can always replace an equal weight of a lower one without losing value, so the greedy filling is optimal for the relaxed problem. Its value bounds what the rest of the bag can still add. Linear programming relaxations, which drop the integrality of the variables of an integer program, are the general form, and are told here, not built.

def fractional_bound(items, i, room, value):
    """The best value of the relaxed problem, where items may be cut."""
    for w, v in items[i:]:
        if w <= room:
            room, value = room - w, value + v
        else:
            return value + v * room / w
    return value


def branch_and_bound(items, capacity, use_bound):
    items = sorted(items, key=lambda it: it[1] / it[0], reverse=True)
    best, nodes = 0, 0

    def explore(i, room, value):
        nonlocal best, nodes
        nodes += 1
        best = max(best, value)
        if i == len(items):
            return
        if use_bound and fractional_bound(items, i, room, value) <= best:
            return  # prune: this branch cannot beat the best
        w, v = items[i]
        if w <= room:
            explore(i + 1, room - w, value + v)  # take item i
        explore(i + 1, room, value)  # leave it
    explore(0, capacity, 0)
    return best, nodes
Listing 18.5. Branch and bound for the 0-1 knapsack, with and without the fractional bound. code/bachelor-3/18-hard-problems/listings/knapsack_bb.py
$ python knapsack_bb.py
 n   best value   nodes, no bound   nodes, fractional bound
10          229             1,365                        25
14          346            20,702                        69
18          466           321,858                        55
22          597         5,081,541                       162
Output 18.4. Nodes of the search tree on random instances, bag half the total weight. Without the bound the tree grows by about 16 for every four items; with it, it stays below two hundred.

For the travelling salesman, a good relaxation of a tour is a 1-tree: a spanning tree of all places but the first, plus the two shortest edges at the first. A tour is a 1-tree, so the cheapest 1-tree is a lower bound, 13,594 m for the van against an optimum of 16,635 m (Exercise 18.6).

18.3 Satisfiability solvers that learn

dpll.py branches on a variable, propagates units, and on a contradiction backtracks to its last choice. Davis and Putnam published a resolution-based procedure in 1960; the branching procedure is from Davis, Logemann and Loveland, published in 1962.

Modern solvers keep the branching and add three ideas: cheap propagation, learning a clause from each contradiction, and jumping back further than one choice.

Definition 18.9 (Watched literals, solver implication graph, conflict clause, clause learning, unique implication point, backjumping, CDCL solver)

  • Watched literals: each clause watches two of its literals that are not false; it is looked at only when one of them becomes false, to find another or to propagate.
  • The solver implication graph has a vertex per assigned literal, labelled with its decision level, and an edge from each false literal of a clause to the literal that clause implied; a conflict clause has all its literals false.
  • Clause learning adds to the formula a clause implied by it that rules out the cause of a conflict. A unique implication point is a literal of the current level through which every path from that level’s decision to the conflict passes; the first one is the nearest to the conflict.
  • Backjumping undoes every assignment above a level that may be several levels below the current one.
  • A CDCL solver (conflict-driven clause learning) combines the four.

Take the clauses c1=¬x2∨x3c_1 = \neg x_2 \vee x_3, c2=¬x1∨¬x3∨x4c_2 = \neg x_1 \vee \neg x_3 \vee x_4, c3=¬x3∨x5c_3 = \neg x_3 \vee x_5, c4=¬x4∨¬x5c_4 = \neg x_4 \vee \neg x_5, and decide x1x_1 at level 1, then x2x_2 at level 2. Propagation sets x3x_3, then x4x_4 and x5x_5, and c4c_4 is falsified. Resolving c4c_4 with the reason of x5x_5 gives ¬x4∨¬x3\neg x_4 \vee \neg x_3; with the reason of x4x_4, ¬x1∨¬x3\neg x_1 \vee \neg x_3. One literal of level 2 is left, x3x_3: the first unique implication point. The learned clause ¬x1∨¬x3\neg x_1 \vee \neg x_3 says that x1x_1 and x3x_3 cannot both hold; the solver jumps back to level 1, where the clause is unit and sets x3x_3 false, without ever trying x2x_2 again.

The solver implication graph of the example. Decisions are shaded; “@2” is the decision level. Every path from x_2 to the conflict passes through x_3. The literals with an edge across the cut, x_1 and x_3, give the learned clause x_1 x_3.
The solver implication graph of the example. Decisions are shaded; “@2” is the decision level. Every path from x2x_2 to the conflict passes through x3x_3. The literals with an edge across the cut, x1x_1 and x3x_3, give the learned clause ¬x1∨¬x3\neg x_1 \vee \neg x_3.

cdcl.py implements this in about 140 lines. It decides the most active variable, the one met most often in recent conflicts, and tries it false first.

    def propagate(self):
        """Unit propagation through the watches; returns a falsified clause or None."""
        while self.head < len(self.trail):
            falsified = -self.trail[self.head]
            self.head += 1
            watching = self.watches.get(falsified, [])
            self.watches[falsified] = []
            for k, ci in enumerate(watching):
                c = self.clauses[ci]
                if c[0] == falsified:
                    c[0], c[1] = c[1], c[0]
                if self.true(c[0]):
                    self.watches[falsified].append(ci)
                    continue
                for j in range(2, len(c)):  # look for another literal to watch
                    if not self.false(c[j]):
                        c[1], c[j] = c[j], c[1]
                        self.watches.setdefault(c[1], []).append(ci)
                        break
                else:
                    self.watches[falsified].append(ci)
                    if self.false(c[0]):  # every literal false: a conflict
                        self.watches[falsified] += watching[k + 1:]
                        return c
                    self.assign(c[0], ci)  # unit: c[0] is implied
        return None
Listing 18.6. Propagation with two watched literals: a clause is visited only when a watched literal becomes false. code/bachelor-3/18-hard-problems/listings/cdcl.py
    def analyse(self, conflict):
        """First UIP: resolve the conflict clause with the reasons of its literals of
        the current level, latest first, until one literal of that level is left."""
        level, seen, learned, count = self.decision_level(), set(), [], 0
        clause, i = conflict, len(self.trail) - 1
        while True:
            for lit in clause:
                v = abs(lit)
                if v in seen or self.level[v] == 0:
                    continue
                seen.add(v)
                self.activity[v] += 1
                if self.level[v] == level:
                    count += 1  # still to be resolved away
                else:
                    learned.append(lit)
            while abs(self.trail[i]) not in seen:
                i -= 1
            uip = self.trail[i]
            i, count = i - 1, count - 1
            if count == 0:
                break
            clause = [x for x in self.clauses[self.reason[abs(uip)]] if x != uip]
        learned.insert(0, -uip)  # the learned clause: not uip, or the earlier literals
        back = max((self.level[abs(x)] for x in learned[1:]), default=0)
        return learned, back
Listing 18.7. Conflict analysis to the first unique implication point. code/bachelor-3/18-hard-problems/listings/cdcl.py
    def solve(self):
        if self.unsat or self.propagate() is not None:
            return None, self.stats
        while True:
            conflict = self.propagate()
            if conflict is not None:
                self.stats["conflicts"] += 1
                if self.decision_level() == 0:
                    return None, self.stats
                learned, back = self.analyse(conflict)
                self.backjump(back)
                # watch the asserting literal and the latest of the others
                learned[1:] = sorted(learned[1:], key=lambda x: -self.level[abs(x)])
                ci = self.add(learned) if len(learned) > 1 else None
                self.assign(learned[0], ci)
                self.stats["learned"] += 1
                if self.restart_now() and self.limits:
                    self.backjump(0)  # keep the learned clauses, forget the decisions
                continue
            free = [v for v in range(1, self.n + 1) if v not in self.value]
            if not free:
                return dict(self.value), self.stats
            v = max(free, key=lambda v: (self.activity[v], -v))  # most active variable
            self.stats["decisions"] += 1
            self.limits.append(len(self.trail))
            self.assign(-v, None)  # try false first
Listing 18.8. The main loop: propagate, learn and backjump on a conflict, decide otherwise. code/bachelor-3/18-hard-problems/listings/cdcl.py

The learned clause is asserting: after the backjump, all its literals but one are false, so propagation sets that one at once. Conflict-driven clause learning was proposed by J. P. Marques-Silva and Karem Sakallah in 1996 and 1999, in the GRASP solver; the Chaff solver of 2001 engineered DPLL with such enhancements for speed.

Restarting the search from level 0 while keeping the learned clauses, now and then, is the last common ingredient (Exercise 18.12).

The two solvers are compared below in decisions and conflicts, which do not depend on the machine. The pigeonhole formulas put n+1n + 1 pigeons in nn holes, one hole each, and are unsatisfiable. Random 3-SAT formulas are taken at 4.26 clauses per variable, where Selman, Mitchell and Levesque, measuring the work of DPLL, found them passing from almost always satisfiable to almost always unsatisfiable (1996).

def pigeonhole(n):
    """Variable p(i, j): pigeon i in hole j. Every pigeon somewhere, no hole shared."""
    def p(i, j):
        return i * n + j + 1
    clauses = [[p(i, j) for j in range(n)] for i in range(n + 1)]
    clauses += [[-p(i, j), -p(k, j)] for j in range(n)
                for i in range(n + 1) for k in range(i + 1, n + 1)]
    return clauses, (n + 1) * n
Listing 18.9. The pigeonhole formula. code/bachelor-3/18-hard-problems/listings/sat_compare.py
$ python sat_compare.py
instance           answer   DPLL dec.  DPLL confl.   CDCL dec.  CDCL confl.
pigeonhole 5 in 4   UNSAT          23          24          39          29
pigeonhole 6 in 5   UNSAT         119         120         177         142
pigeonhole 7 in 6   UNSAT         719         720         668         532
pigeonhole 8 in 7   UNSAT       5,039       5,040       2,209       1,671
random n = 30       UNSAT          82          83          30          28
random n = 50         SAT          19           8          14           2
random n = 70       UNSAT         920         921         163         134
Output 18.5. Plain DPLL against CDCL. On pigeonhole formulas DPLL makes exactly n!−1n! - 1 decisions for nn holes.

At small sizes the learning costs more than it saves; from 7 holes and on random formulas of 70 variables, CDCL makes 2 to 6 times fewer decisions, and the gap widens with the size. CDCL’s counts still grow fast on pigeonhole formulas: each learned clause is a step of a proof that the formula is unsatisfiable, and when every such proof is long, so is the search.

18.4 Horn clauses

Definition 18.10 (Horn clause, Horn-SAT, forward chaining)

A Horn clause has at most one positive literal: ¬a1∨⋯∨¬ak∨b\neg a_1 \vee \cdots \vee \neg a_k \vee b is the rule “if a1,…,aka_1, \ldots, a_k then bb”; with no positive literal it is a constraint, and with no negative one a fact. Horn-SAT is SAT for formulas of Horn clauses. Forward chaining applies the rules to the known facts until no new fact appears.

Theorem 18.11 (Horn-SAT is in P)

Set every variable false, then repeatedly make true the conclusion of a rule whose premises are all true. The formula is satisfiable if and only if no constraint ends with all its premises true, and then the resulting assignment satisfies it. With a counter per clause this takes time linear in the size of the formula.

Proof. Every variable made true is forced: by induction, it is true in every satisfying assignment. So if a constraint has all its premises true, no assignment satisfies the formula. Otherwise, when the process stops, a rule with all premises true has its conclusion true, a rule with a false premise is satisfied by it, and every constraint has a false premise. The time bound is Exercise 18.8. ∎

William Dowling and Jean Gallier published linear-time algorithms for Horn formulas in 1984. Forward chaining is the same process on rules with variables. Brenmoor’s records list no families, so horn.py makes up parents for the town’s people, seeded, and derives grandparents and ancestors from three rules. Logic programming languages are built on Horn clauses run this way, or backwards from a goal; they are told here, not built.

def horn_sat(clauses, n):
    """Start with every variable false; a clause whose negative literals are all true
    forces its positive one. Each clause keeps a counter of negatives not yet true, so
    every literal is looked at a constant number of times."""
    waiting = [sum(1 for x in c if x < 0) for c in clauses]
    uses = {v: [] for v in range(1, n + 1)}
    for i, c in enumerate(clauses):
        for x in c:
            if x < 0:
                uses[-x].append(i)
    true, queue = set(), [i for i, w in enumerate(waiting) if w == 0]
    while queue:
        c = clauses[queue.pop()]
        head = [x for x in c if x > 0]
        if not head:
            return None  # every premise true, and no conclusion: unsatisfiable
        if head[0] in true:
            continue
        true.add(head[0])
        for i in uses[head[0]]:
            waiting[i] -= 1
            if waiting[i] == 0:
                queue.append(i)
    return {v: v in true for v in range(1, n + 1)}
Listing 18.10. Horn-SAT: a counter of premises still false per clause, and a queue of clauses ready to fire. code/bachelor-3/18-hard-problems/listings/horn.py
RULES = [  # (premises, conclusion); capital letters are variables
    ([("parent", "X", "Y")], ("ancestor", "X", "Y")),
    ([("parent", "X", "Y"), ("ancestor", "Y", "Z")], ("ancestor", "X", "Z")),
    ([("parent", "X", "Y"), ("parent", "Y", "Z")], ("grandparent", "X", "Z")),
]
Listing 18.11. Three rules; capital letters are variables. code/bachelor-3/18-hard-problems/listings/horn.py
$ python horn.py
Horn-SAT: {1: True, 2: True, 3: True, 4: True, 5: False}
with [5] added: None
parent       facts:   190
grandparent  facts:   158
ancestor     facts:   360
rounds until nothing new: 4
for example: Nils is a grandparent of Leo
Output 18.6. A Horn formula and the assignment found, the smallest that satisfies it; adding the fact x5x_5 violates the constraint ¬x4∨¬x5\neg x_4 \vee \neg x_5. Then forward chaining on 190 generated parent facts.

Ancestors take three rounds that add facts, and a fourth that finds nothing new, because the ancestor rule is recursive: each round adds one generation.

18.5 Local search

def two_opt(points, tour):
    """Reverse a segment whenever that shortens the tour, until no reversal does."""
    tour, improved = list(tour), True
    while improved:
        improved = False
        for i in range(1, len(tour) - 1):
            for j in range(i + 1, len(tour)):
                a, b = points[tour[i - 1]], points[tour[i]]
                c, e = points[tour[j]], points[tour[(j + 1) % len(tour)]]
                if dist(a, c) + dist(b, e) < dist(a, b) + dist(c, e) - 1e-9:
                    tour[i:j + 1] = reversed(tour[i:j + 1])
                    improved = True
    return tour
Listing 18.12. 2-opt: reverse a segment while that shortens the tour. code/bachelor-3/18-hard-problems/listings/tsp.py

A tour no 2-opt move improves crosses itself nowhere, since uncrossing two crossing edges shortens a Euclidean tour. On the 200 sets of 12 places (Output 18.3), 2-opt after tree doubling finds the optimum 103 times and stays within 16% of it. There is no guarantee: the 2-opt optimum can be a local optimum far from the best. S. Lin and B. W. Kernighan’s heuristic of 1973 searches tours that differ from the current one in more than two edges; simulated annealing accepts some worsening moves, with a probability that decreases over time, to escape local optima. Both are told here.

def walksat(clauses, n, rng, noise=0.5, max_flips=20_000):
    value = {v: rng.random() < 0.5 for v in range(1, n + 1)}

    def sat(c):
        return any(value[abs(x)] == (x > 0) for x in c)

    def breaks(v):  # clauses satisfied now that flipping v would falsify
        value[v] = not value[v]
        count = sum(1 for c in clauses if v in map(abs, c) and not sat(c))
        value[v] = not value[v]
        return count
    for flips in range(max_flips):
        unsat = [c for c in clauses if not sat(c)]
        if not unsat:
            return value, flips
        c = rng.choice(unsat)
        if rng.random() < noise:
            v = abs(rng.choice(c))  # a random walk step
        else:
            v = min((abs(x) for x in c), key=breaks)  # the greedy step
        value[v] = not value[v]
    return None, max_flips
Listing 18.13. WalkSAT, with half its steps random. code/bachelor-3/18-hard-problems/listings/walksat.py
$ python walksat.py
  n   clauses   CDCL says   WalkSAT flips (5 seeded runs)
 20        80       UNSAT   20,000 20,000 20,000 20,000 20,000
 40       160         SAT      275  2,918    152    568    896
 60       240         SAT      202    342    269    278  1,290
 80       320         SAT    3,704  3,784  9,751    592    385
Output 18.7. WalkSAT on random 3-SAT at 4 clauses per variable, five seeds each. The first formula is unsatisfiable, and WalkSAT spends its whole budget without being able to say so.

WalkSAT is described in Bart Selman, Henry Kautz and Bram Cohen’s paper on local search strategies for satisfiability of 1993.

It finds an assignment of a satisfiable formula often in a few hundred flips, but the counts vary by a factor of 25 from one seed to the next, and on an unsatisfiable formula it can only give up. Local search answers yes; only a complete solver, such as CDCL, answers no.

18.6 Exercises

Exercise 18.1 ★

A path of 7 vertices 1−2−⋯−71 - 2 - \cdots - 7. matching_cover reads the edges in order. Which cover does it return, what is the smallest cover, and what is the ratio?

Solution

Solution of Exercise 18.1.

Edge 1212 joins the matching, 2323 is covered, 3434 joins, 4545 is covered, 5656 joins, 6767 is covered: the cover is {1,…,6}\{1, \ldots, 6\}, six vertices. The smallest cover is {2,4,6}\{2, 4, 6\}: three vertices, since the three disjoint edges 1212, 3434, 5656 need one each. Ratio 6/3=26/3 = 2.

Exercise 18.2 ★

Run greedy set cover by hand on U={1,…,6}U = \{1, \ldots, 6\} with S1={1,2,3,4}S_1 = \{1, 2, 3, 4\}, S2={1,2,5}S_2 = \{1, 2, 5\}, S3={3,4,6}S_3 = \{3, 4, 6\}, S4={5,6}S_4 = \{5, 6\}. Is the result optimal?

Solution

Solution of Exercise 18.2.

S1S_1 covers 4 new elements; then S4S_4 covers 5 and 6 (2 new, against 1 for S2S_2 and 1 for S3S_3). Two sets, {S1,S4}\{S_1, S_4\}, and no single set covers UU: optimal.

Exercise 18.3 ★

Unit-propagate x1∧(¬x1∨x2)∧(¬x2∨¬x3)∧(x3∨x4∨¬x1)∧(¬x4∨x5)x_1 \wedge (\neg x_1 \vee x_2) \wedge (\neg x_2 \vee \neg x_3) \wedge (x_3 \vee x_4 \vee \neg x_1) \wedge (\neg x_4 \vee x_5). Which variables are set, and in which order?

Solution

Solution of Exercise 18.3.

x1x_1 is a unit: true. Then ¬x1∨x2\neg x_1 \vee x_2 is unit: x2x_2 true. Then ¬x2∨¬x3\neg x_2 \vee \neg x_3: x3x_3 false. Then x3∨x4∨¬x1x_3 \vee x_4 \vee \neg x_1: x4x_4 true. Then ¬x4∨x5\neg x_4 \vee x_5: x5x_5 true. Every variable is set, in the order x1,x2,x3,x4,x5x_1, x_2, x_3, x_4, x_5, and every clause holds.

Exercise 18.4 ★

From Output 18.4, predict the number of nodes without the bound for 26 items. Why can the count with the bound go down from 14 to 18 items?

Solution

Solution of Exercise 18.4.

Without the bound the count grows by about 15.5 for every four items, close to 24=162^4 = 16: about 80 million nodes for 26 items. With the bound, the count depends on how close the fractional bound is to the true optimum on the instance, not only on its size; on the instance of 18 items it prunes more of the tree than on that of 14.

Exercise 18.5 ★★

exercises/ex5_learning.py learns only the negation of the unique implication point and jumps back to level 0. Find a satisfiable formula it declares unsatisfiable, explain why the clause it learns is not implied by the formula, and fix it.

Solution

Solution of Exercise 18.5.

On the nine clauses of test_exercise_5_buggy_is_unsound_and_fixed_is_right, satisfiable, the buggy solver answers unsatisfiable. The first-UIP clause is ¬u∨ℓ1∨⋯∨ℓk\neg u \vee \ell_1 \vee \cdots \vee \ell_k, where the ℓi\ell_i are literals of earlier levels; resolution derives it from the formula, so it is implied. Dropping the ℓi\ell_i leaves the unit ¬u\neg u, which says uu is false whatever the earlier decisions; that is implied only if the conflict follows from uu alone, which is not the case when the earlier literals took part. The solver then asserts a consequence of its own decisions as a fact, and later refutes a satisfiable formula. The fix keeps the earlier literals and backjumps to the highest of their levels: Fixed uses the analysis of Listing 18.7 unchanged.

Exercise 18.6 ★★

Write one_tree_bound(points): a minimum spanning tree of all the points but the first, plus the two shortest edges from the first. Prove it never exceeds the shortest tour. It is tested against brute force.

Solution

Solution of Exercise 18.6.

exercises/ex6_one_tree.py uses minimum_spanning_tree on the points but the first and adds the two shortest distances from the first. Any tour consists of the two tour edges at the first point, plus a path through all the others, which is a spanning tree of them: so the tour weighs at least the minimum spanning tree plus the two shortest edges at the first point (test_tours). For the van it gives 13,594 m.

Exercise 18.7 ★★

Prove Theorem 18.2 in full: the result is a cover, it is at most twice the smallest, and the factor 2 is reached for every even number of vertices.

Solution

Solution of Exercise 18.7.

Facts used: a matching’s edges share no vertex; every cover contains an end of every edge.

Let MM be the matching built. An edge uvuv not covered would have neither end in a matched edge, and the loop would have added it to MM: so the result is a cover, of size 2∣M∣2|M|. Any cover CC contains an end of each edge of MM, and these ends are distinct, so ∣C∣≥∣M∣|C| \ge |M|, and 2∣M∣≤2∣C∣2|M| \le 2|C|. Tightness: on kk disjoint edges (2k2k vertices) the algorithm takes all 2k2k vertices and kk suffice; on the complete bipartite graph of the chapter’s figure, the same.

Exercise 18.8 ★★

Prove that horn_sat (Listing 18.10) runs in time linear in the total number of literals.

Solution

Solution of Exercise 18.8.

Facts used: a clause enters the queue only when its counter reaches 0, which happens once.

Building waiting and uses reads every literal once. Each clause is popped from the queue at most once, and its head is found by reading its literals: total, the size of the formula. A variable is made true at most once, and then each clause in which it occurs negatively has its counter decremented once: over all variables, at most the number of negative literals. Every step is constant time, so the whole is linear in the number of literals.

Exercise 18.9 ★★

How many entries does the Held–Karp table hold for nn places, and how many steps does filling it take? Give the numbers for the van’s 12 places, and compare with the number of tours.

Solution

Solution of Exercise 18.9.

One entry per pair (S,j)(S, j) with S⊆{1,…,n−1}S \subseteq \{1, \ldots, n - 1\} and j∈Sj \in S: (n−1)2n−2(n - 1)2^{n - 2} entries, each a minimum over at most n−2n - 2 predecessors, so O(n22n)O(n^2 2^n) steps. For n=12n = 12: 11×210=11,26411 \times 2^{10} = 11{,}264 entries and at most about 11,264×10≈113,00011{,}264 \times 10 \approx 113{,}000 steps (test_van_bounds_and_table_size), against 11!/2=19,958,40011!/2 = 19{,}958{,}400 tours.

Exercise 18.10 ★★★

Prove Theorem 18.4. (When greedy takes a set covering kk new elements, charge each of them 1/k1/k. Show that the elements of any set SS of an optimal cover are charged at most H(∣S∣)H(|S|) in all.)

Solution

Solution of Exercise 18.10.

Facts used: ∑j≤m1/j=H(m)\sum_{j \le m} 1/j = H(m); greedy picks a set covering the most uncovered elements.

When greedy picks a set that covers kk new elements, charge each of them 1/k1/k; the total charge is the number of sets greedy takes. Let SS be a set of an optimal cover, and list its elements in the order greedy covers them, e1,…,eme_1, \ldots, e_m. When eie_i is covered, at least m−i+1m - i + 1 elements of SS are still uncovered, so SS itself would cover that many; greedy’s choice covers at least as many, and eie_i is charged at most 1/(m−i+1)1/(m - i + 1). The elements of SS are charged at most 1/m+⋯+1/1=H(m)≤H(n)1/m + \cdots + 1/1 = H(m) \le H(n). Every element lies in some set of the optimal cover, so the total charge is at most H(n)H(n) times the number of its sets. Finally H(n)≤1+∫1ndx/x=1+ln⁡nH(n) \le 1 + \int_1^n dx/x = 1 + \ln n.

Exercise 18.11 ★★★

Prove that, for every constant ρ≥1\rho \ge 1, no polynomial-time algorithm approximates the general travelling salesman problem within ρ\rho unless P=NP\mathrm{P} = \mathrm{NP}.

Solution

Solution of Exercise 18.11.

Facts used: Hamiltonian cycle is NP-complete (Chapter 17).

Suppose an algorithm AA returns a tour within ρ\rho of the optimum in polynomial time. Given a graph GG on nn vertices, give each edge of GG length 1 and each other pair length ρn+1\rho n + 1; this takes polynomial time. If GG has a Hamiltonian cycle, the optimum is nn and AA returns a tour of length at most ρn\rho n. If not, every tour uses a pair that is not an edge and has length at least ρn+1+(n−1)>ρn\rho n + 1 + (n - 1) > \rho n. So comparing AA’s tour with ρn\rho n decides Hamiltonian cycle, and P=NP\mathrm{P} = \mathrm{NP}. The lengths break the triangle inequality, which is why the metric case escapes.

Exercise 18.12 ★★★

Add restarts to cdcl.py by overriding restart_now: restart after 16⋅ri16 \cdot r_i conflicts in the ii-th run, where rir_i follows the sequence 1,1,2,1,1,2,4,1,1,2,…1, 1, 2, 1, 1, 2, 4, 1, 1, 2, \ldots Explain why the solver stays complete, and measure the conflicts on the random formulas of 60, 80 and 100 variables of seed 18.

Solution

Solution of Exercise 18.12.

exercises/ex12_restarts.py: Restarting counts conflicts and, after 16⋅ri16 \cdot r_i of them, returns true from restart_now, so the main loop backjumps to level 0. The solver stays complete: the learned clauses are kept, each is implied by the formula so no solution is lost, and the run lengths grow without bound, so eventually a run is long enough to finish. Measured (test_exercise_12_counts): 119 conflicts without restarts against 90 with 4 restarts for 60 variables; 289 against 212 with 8 for 80; but 101 against 169 with 6 for 100. Restarts help on some formulas and hurt on others; solvers keep them because they cut the very long runs that an unlucky early decision causes.

18.7 Weekend problem

Problem 18.1

Weekend problem — The delivery van of Brenmoor

A van leaves the Town Square, serves 11 other places and returns. Distances are straight lines between the coordinates of the town’s places, in metres. This problem compares the exact tour, the tour tree doubling guarantees and the tour 2-opt finds, with the counts of Output 18.3.

Part I — The exact tour.

  1. How many different tours visit the 12 places, counting a tour and its reverse once?
  2. Why can Held–Karp fix the Town Square as the start without losing any tour?
  3. State the recurrence for the shortest path from place 0 through a set SS ending at jj.
  4. How many table entries does the program compute for 12 places? (Exercise 18.9.)
  5. Why does the program take a fraction of a second on 12 places, and about how much longer would 24 take?
  6. The optimum is 16,635 m. Is a tour of 16,600 m possible?

Part II — Tree doubling.

  1. Why are straight-line distances a metric?
  2. The minimum spanning tree weighs 11,367 m. Why is that a lower bound on every tour?
  3. What bound on the tree-doubling tour follows from the proof of Theorem 18.6? Is it met?
  4. Where in the proof is the triangle inequality used?
  5. The tree-doubling tour is 18,427 m. What ratio does the van see, and what ratio does the theorem promise?
  6. The 1-tree bound is 13,594 m. Which lower bound is better, and how much better?
  7. With both lower bounds alone, without Held–Karp, what can be said about how close tree doubling is to optimal?

Part III — 2-opt.

  1. Describe one 2-opt move as a change to the list of places.
  2. Why does two_opt stop?
  3. After 2-opt the van’s tour is 17,617 m. Is it a local optimum, and is it the optimum?
  4. Why can a tour with two crossing edges not be 2-optimal?
  5. How many 2-opt moves does one pass over a tour of nn places examine?
  6. Why is 2-opt started from the tree-doubling tour rather than from a random one?

Part IV — Measured over many instances.

  1. Over 200 seeded choices of 12 places out of 30, what are the worst and mean ratios of tree doubling?
  2. Is the worst ratio, 1.456, consistent with the theorem? What would contradict it?
  3. What do 2-opt’s mean ratio of 1.022 and worst of 1.156 add?
  4. In how many instances does 2-opt reach the optimum, and what does that say about local optima?
  5. Why can such measurements never replace the proof of the factor 2?
  6. The van’s company grows to 60 places. Which of the three methods still runs, and which guarantee remains?
Solution

Solution of Problem 18.1.

1. 11!/2=19,958,40011!/2 = 19{,}958{,}400.

2. Every tour passes through the Town Square; rotating it to start there gives the same cycle.

3. With D({j},j)=d(0,j)D(\{j\}, j) = d(0, j),

D(S,j)=min⁡k∈S∖{j}(D(S∖{j},k)+d(k,j)),D(S, j) = \min_{k \in S \setminus \{j\}} \bigl( D(S \setminus \{j\}, k) + d(k, j) \bigr),

and the tour is min⁡jD({1,…,11},j)+d(j,0)\min_j D(\{1, \ldots, 11\}, j) + d(j, 0).

4. 11×210=11,26411 \times 2^{10} = 11{,}264.

5. About 10510^5 steps for 12 places (Exercise 18.9); for 24, 23×222≈10823 \times 2^{22} \approx 10^8 entries of about 22 steps each, some 20,000 times more, minutes in Python, with a table too large for this program’s dictionary.

6. No: Held–Karp is exact, so no tour is shorter than 16,635 m.

7. The straight line is the shortest path between two points, so going through a third point is never shorter.

8. Removing an edge from any tour leaves a spanning tree, which weighs at least the minimum one.

9. At most 2×11,367=22,7342 \times 11{,}367 = 22{,}734 m. Not met: 18,427 m, since the shortcuts save a great deal.

10. In replacing each skip of visited points by a straight segment.

11. 18,427/16,635=1.10818{,}427 / 16{,}635 = 1.108; the theorem promises at most 2.

12. The 1-tree, by 13,594−11,367=2,22713{,}594 - 11{,}367 = 2{,}227 m.

13. The optimum lies between 13,594 and 18,427 m, so tree doubling is within 18,427/13,594=1.3618{,}427 / 13{,}594 = 1.36 of it, a better guarantee for this instance than the factor 2.

14. Choose positions i<ji < j and reverse the places from ii to jj; the edges into and out of the segment change.

15. Each move shortens the tour strictly, and there are finitely many tours.

16. It is a local optimum, since two_opt stops only when no move improves; it is not the optimum, 6% longer.

17. Uncrossing two crossing edges by a 2-opt move shortens the tour, as the two diagonals of a convex quadrilateral add up to more than either pair of opposite sides.

18. The pairs i<ji < j: about n2/2n^2/2.

19. It starts within a factor 2, so fewer moves are needed, and the local optimum reached tends to be good; from a random tour 2-opt also works, but takes more moves.

20. Worst 1.456, mean 1.216.

21. Yes, 1.456≤21.456 \le 2. A ratio above 2 on a metric instance would contradict it, and so would show a bug.

22. After 2-opt the tours are on average 2.2% above the optimum and at worst 15.6%.

23. In 103 of 200: the other 97 stop at a local optimum that is not the best.

24. They cover 200 instances of one kind; the proof covers every metric instance, including those no sample finds.

25. Held–Karp would need about 602×26060^2 \times 2^{60} steps: not feasible. Tree doubling and 2-opt run in a fraction of a second; the factor 2 remains, and the 1-tree bound says how close the tour is on that instance.

المصطلحات المعرَّفة في هذا الفصل

عرض كل المصطلحات (1050) في المسرد