Course page › Code of Lecture 3 › solver.py · 532 lines
raw file

The Boole Lab solver: a proof of every true equation (for hint and auto).

Code with colored syntax: click a line number to get a link to it; an underlined name leads to its definition.

1"""The Boole Lab solver: a proof of every true equation (for hint and auto).
2
3The solver lies OUTSIDE the kernel, like the tactics. It returns a chain of
4steps, and the lab (lab.py) turns it into ordinary rw / nth_rw lines; the
5kernel checks every proof at qed anyway. A step is a tuple (path, fact,
6backward, arguments): the subterm at the path (argument numbers from the
7root) is an instance of one side of the fact — the left one, or the right
8one when backward — and we replace it by the instance of the other side.
9
10Two strategies (the lab adds breadth-first search to them):
11
12* a library proof — the goal is an instance of a theorem, also of one that
13 may not yet be used in an exercise. Then we put in place of the step the
14 proof of that theorem: the tree accepted by the kernel, flattened into a
15 chain (flatten);
16* the normal form — both sides are brought to a sorted sum of full
17 products of the variables and their complements (minterms). Two terms are
18 equal in every Boolean algebra exactly when they have the same form, so
19 this strategy finds a proof of EVERY true equation. It is a decision
20 procedure, not a heuristic; its proofs can be long.
21
22Steps with theorems outside the allowed ones are expanded into their proofs
23(recursively) until only allowed facts remain — in the worst case the axioms
24H1–H8 (Expander).
25"""
26
27import time
28
29import tactics as tac
30from kernel import CongrArg, Inst, Refl, Symm, Trans, subst
31
32STEP_LIMIT = 3000 # a longer chain: the strategy gives up
33SIZE_LIMIT = 2000 # a larger term on the way: likewise
34
35
36class TooBig(Exception):
37 """A chain or a term exceeded the limit."""
38
39
40class OutOfTime(TooBig):
41 """The time for searching is up."""
42
43
44class Deadline:
45 """The moment after which strategies give up (None: no limit)."""
46
47 def __init__(self, seconds=None):
48 self.end = None if seconds is None else \
49 time.perf_counter() + seconds
50
51 def check(self):
52 if self.end is not None and time.perf_counter() > self.end:
53 raise OutOfTime()
54
55
56NO_DEADLINE = Deadline()
57
58
59# --- terms and steps ---------------------------------------------------------
60
61def term_size(t):
62 return 1 if isinstance(t, str) else 1 + sum(map(term_size, t[1:]))
63
64
65def subterm_at(t, path):
66 """The subterm at the path."""
67 for i in path:
68 t = t[i]
69 return t
70
71
72def replace_at(t, path, u):
73 """The term t with the subterm at the path replaced by u."""
74 if not path:
75 return u
76 i = path[0]
77 return t[:i] + (replace_at(t[i], path[1:], u),) + t[i + 1:]
78
79
80def positions(t, path=()):
81 """Pairs (path, subterm) in prefix order."""
82 yield path, t
83 if not isinstance(t, str):
84 for i, a in enumerate(t[1:], start=1):
85 yield from positions(a, path + (i,))
86
87
88def leaves(t):
89 if isinstance(t, str):
90 return {t}
91 return set().union(*map(leaves, t[1:]))
92
93
94def occurrences(t, u, path=()):
95 """Paths of the occurrences of u in t, in prefix order."""
96 if t == u:
97 return [path]
98 if isinstance(t, str):
99 return []
100 result = []
101 for i, a in enumerate(t[1:], start=1):
102 result += occurrences(a, u, path + (i,))
103 return result
104
105
106def reverse_steps(steps):
107 """The chain b → a from the chain a → b."""
108 return [(s, f, not w, a) for s, f, w, a in reversed(steps)]
109
110
111def apply_step(kernel, t, step):
112 """The term after a step; ValueError when the step does not fit t."""
113 path, fact, backward, args = step
114 vs, l, r = kernel.facts[fact]
115 s = dict(zip(vs, args))
116 a, b = (r, l) if backward else (l, r)
117 try:
118 u = subterm_at(t, path)
119 except (IndexError, TypeError):
120 raise ValueError(f"{fact}: wrong path {path}") from None
121 if u != subst(a, s):
122 raise ValueError(f"{fact}: the step does not fit the term")
123 return replace_at(t, path, subst(b, s))
124
125
126def replay(kernel, t, steps):
127 """The terms t, t₁, …, tₙ after the consecutive steps."""
128 terms = [t]
129 for step in steps:
130 terms.append(apply_step(kernel, terms[-1], step))
131 return terms
132
133
134def segment(terms, steps, goal):
135 """The piece of the chain from goal[0] to goal[1] when both lie on the
136 chain (terms[i] is the term after i steps), or None."""
137 lefts = [i for i, t in enumerate(terms) if t == goal[0]]
138 rights = [j for j, t in enumerate(terms) if t == goal[1]]
139 if not lefts or not rights:
140 return None
141 _, i, j = min((abs(i - j), i, j) for i in lefts for j in rights)
142 return steps[i:j] if i <= j else reverse_steps(steps[j:i])
143
144
145def without_loops(terms, steps):
146 """Steps without detours: when the chain returns to a term, we cut out
147 the loop."""
148 last = {t: i for i, t in enumerate(terms)}
149 result, i = [], 0
150 while i < len(steps):
151 if last[terms[i]] > i:
152 i = last[terms[i]]
153 continue
154 result.append(steps[i])
155 i += 1
156 return result
157
158
159# --- library proofs ----------------------------------------------------------
160
161def flatten(d):
162 """A chain of steps from a proof tree: from the left side of the
163 conclusion to the right one.
164
165 Inst is one step at the root, CongrArg moves the steps into every
166 occurrence of the hole, Symm reverses a chain and Trans glues two."""
167 if isinstance(d, Inst):
168 return [((), d.name, False, tuple(d.args))]
169 if isinstance(d, Refl):
170 return []
171 if isinstance(d, Symm):
172 return reverse_steps(flatten(d.p))
173 if isinstance(d, Trans):
174 return flatten(d.p) + flatten(d.q)
175 if isinstance(d, CongrArg):
176 steps = flatten(d.p)
177 return [(sc + s, f, w, a) for sc in occurrences(d.C, d.z)
178 for s, f, w, a in steps]
179 raise TypeError(f"not a proof: {d!r}")
180
181
182class Expander:
183 """Replaces steps with theorems outside the allowed ones by their proofs.
184
185 `proofs` is a dict name -> tree accepted by the kernel (the library and
186 the user's theorems). Facts are only ever added, so chains can be
187 remembered: the key is the name and the set of allowed facts."""
188
189 def __init__(self, kernel, proofs):
190 self.kernel, self.proofs = kernel, proofs
191 self._memo = {}
192
193 def chain(self, name, allowed, deadline=NO_DEADLINE):
194 """A proof of the theorem (in its variables) from allowed facts."""
195 key = (name, allowed)
196 if key not in self._memo:
197 self._memo[key] = None # so far: too long
198 try:
199 self._memo[key] = self.expand(
200 flatten(self.proofs[name]), allowed, deadline)
201 except OutOfTime: # time ran out, not the limit
202 del self._memo[key]
203 raise
204 if self._memo[key] is None:
205 raise TooBig(name)
206 return self._memo[key]
207
208 def expand(self, steps, allowed, deadline=NO_DEADLINE):
209 result = []
210 for step in steps:
211 path, fact, backward, args = step
212 if fact in allowed:
213 result.append(step)
214 continue
215 if fact not in self.proofs: # an axiom outside the task
216 raise KeyError(fact)
217 deadline.check()
218 s = dict(zip(self.kernel.facts[fact][0], args))
219 new = [(path + p, f, w, tuple(subst(x, s) for x in a))
220 for p, f, w, a in self.chain(fact, allowed, deadline)]
221 result += reverse_steps(new) if backward else new
222 if len(result) > STEP_LIMIT:
223 raise TooBig(fact)
224 return result
225
226
227def bridge_rules(kernel):
228 """All facts in both directions, but only those whose source side is not
229 a bare variable and binds all the variables of the fact (no "blowing
230 up" like x = x + 0)."""
231 result = {}
232 for name, (vs, l, r) in kernel.facts.items():
233 ren = {x: "?" + x for x in vs}
234 free = tuple(ren.values())
235 for backward, a in ((False, l), (True, r)):
236 pat = subst(a, ren)
237 if isinstance(pat, str) or not set(free) <= leaves(pat):
238 continue
239 result.setdefault(pat[0], []).append((name, backward, pat, free,
240 vs))
241 return result
242
243
244def neighbours(kernel, t, rules):
245 """{term: step} — all rewrites of one subterm of t."""
246 result = {}
247 for path, u in positions(t):
248 if isinstance(u, str):
249 continue
250 for fact, backward, pat, free, vs in rules.get(u[0], ()):
251 s = tac.match_pattern(pat, u, free, {})
252 if s is not None:
253 step = (path, fact, backward, tuple(s[x] for x in free))
254 result.setdefault(apply_step(kernel, t, step), step)
255 return result
256
257
258def instances(kernel, goal):
259 """Steps ((), fact, backward, args) that close the goal l = r alone."""
260 L, R = goal
261 for name, (vs, l, r) in kernel.facts.items():
262 ren = {x: "?" + x for x in vs}
263 free = tuple(ren.values())
264 for backward, (a, b) in ((False, (l, r)), (True, (r, l))):
265 s = tac.match_pattern(subst(a, ren), L, free, {})
266 if s is not None:
267 s = tac.match_pattern(subst(b, ren), R, free, s)
268 if s is not None and len(s) == len(free):
269 yield (), name, backward, tuple(s["?" + x] for x in vs)
270
271
272# --- the normal form ---------------------------------------------------------
273
274# Directed rules (fact, backward): each one shrinks the term or pushes the
275# complement down, so rewriting with them terminates. The names are the
276# English library names; NormalForm(kernel, names) maps them to the names
277# the facts have in the kernel (in the Polish lab: Polish names).
278SIMPLIFY = [
279 ("de_morgan_add", False), ("de_morgan_mul", False),
280 ("compl_compl", False), ("compl_zero", False), ("compl_one", False),
281 ("H5", False), ("zero_add", False), ("H6", False),
282 ("one_mul", False), ("add_one", False), ("one_add", False),
283 ("mul_zero", False), ("zero_mul", False),
284 ("H7", False), ("compl_add", False), ("H8", False), ("compl_mul", False),
285 ("add_idem", False), ("mul_idem", False),
286 ("absorb", False), ("absorb_right", False),
287 ("absorb_mul", False), ("absorb_mul_right", False),
288 ("add_compl_mul", False), ("compl_add_mul", False),
289 ("mul_compl_add", False), ("compl_mul_add", False),
290]
291DISTRIBUTE = [("H4", False), ("add_mul", False)]
292FLATTEN = [("add_assoc", False), ("mul_assoc", False)]
293ZEROS = [("H5", False), ("zero_add", False), ("mul_zero", False),
294 ("zero_mul", False)]
295COMM = {"+": "H1", "*": "H2"} # x ∘ y = y ∘ x
296ASSOC = {"+": "add_assoc", "*": "mul_assoc"} # x ∘ (y ∘ z) = …
297RIGHT_COMM = {"+": "add_right_comm", "*": "mul_right_comm"}
298IDEM = {"+": "add_idem", "*": "mul_idem"} # x ∘ x = x
299
300
301def operands(t, op):
302 """The operands of a chain a₁ op a₂ op … op aₖ nested to the left."""
303 result = []
304 while not isinstance(t, str) and t[0] == op:
305 result.append(t[2])
306 t = t[1]
307 result.append(t)
308 return result[::-1]
309
310
311def operand_path(path, k, i):
312 """The path of the i-th (from 0) of k operands of a chain at `path`."""
313 return path + (1,) * (k - 1 - i) + ((2,) if i else ())
314
315
316def literal_key(t):
317 """The order x, n(x), y, n(y), …; other terms (there should be none)
318 go last, so that the comparison always works."""
319 if isinstance(t, str):
320 return (0, t, 0)
321 if t[0] == "n" and isinstance(t[1], str):
322 return (0, t[1], 1)
323 return (1, repr(t), 0)
324
325
326def product_key(t):
327 return tuple(map(literal_key, operands(t, "*")))
328
329
330class NormalForm:
331 """A proof via the normal form (a sum of minterms).
332
333 Stages for each side: (a) complements go down (De Morgan, involution),
334 constants and obvious repetitions vanish; (b) distributivity: a sum of
335 products; (c) associativity: chains nested to the left, sorted
336 (commutativity), without repetitions, products with x and n(x) vanish;
337 (d) every product without the variable v splits into p * v + p * n(v);
338 then (c) again."""
339
340 def __init__(self, kernel, names=None):
341 self.kernel = kernel
342 self.names = names or {} # English name -> name in kernel
343 needed = {f for group in (SIMPLIFY, DISTRIBUTE,
344 FLATTEN, ZEROS) for f, _ in group}
345 for table in (COMM, ASSOC, RIGHT_COMM, IDEM):
346 needed |= set(table.values())
347 self.ready = {self._n(f) for f in needed} <= set(kernel.facts)
348 self._bridge = None
349 self.deadline = NO_DEADLINE
350 if self.ready:
351 self.simplify = self._rules(SIMPLIFY)
352 self.distribute = self._rules(SIMPLIFY + DISTRIBUTE)
353 self.flatten = self._rules(FLATTEN)
354 self.zeros = self._rules(ZEROS)
355
356 def _n(self, name):
357 return self.names.get(name, name)
358
359 def _rules(self, rules):
360 result = {}
361 for fact, backward in rules:
362 fact = self._n(fact)
363 vs, l, r = self.kernel.facts[fact]
364 ren = {x: "?" + x for x in vs}
365 pat = subst(r if backward else l, ren)
366 result.setdefault(pat[0], []).append(
367 (fact, backward, pat, tuple(ren.values()), vs))
368 return result
369
370 def step(self, path, fact, backward, args):
371 k = (tuple(path), self._n(fact), backward, tuple(args))
372 self.t = apply_step(self.kernel, self.t, k)
373 self.steps.append(k)
374 self.terms.append(self.t)
375 if len(self.steps) > STEP_LIMIT or \
376 term_size(self.t) > SIZE_LIMIT:
377 raise TooBig()
378 self.deadline.check()
379
380 def try_rules(self, path, rules):
381 u = subterm_at(self.t, path)
382 if isinstance(u, str):
383 return False
384 for fact, backward, pat, free, vs in rules.get(u[0], ()):
385 s = tac.match_pattern(pat, u, free, {})
386 if s is not None:
387 self.step(path, fact, backward, [s["?" + x] for x in vs])
388 return True
389 return False
390
391 def exhaust(self, rules, path=()):
392 """From the top: rules at the node, then in the children; a node
393 returns to the queue when one of its children changed."""
394 changed = False
395 while True:
396 while self.try_rules(path, rules):
397 changed = True
398 u = subterm_at(self.t, path)
399 if isinstance(u, str):
400 return changed
401 children = False
402 for i in range(1, len(u)):
403 children = self.exhaust(rules, path + (i,)) or children
404 if not children:
405 return changed
406 changed = True
407
408 def sort_chain(self, P, op, key):
409 """Sorts (bubble sort) the op chain rooted at the path P and removes
410 repetitions. In a product the pair v, n(v) makes the whole product
411 zero — then the result is False."""
412 while True:
413 el = operands(subterm_at(self.t, P), op)
414 k = len(el)
415 for i in range(k - 1):
416 a, b = el[i], el[i + 1]
417 ka, kb = key(a), key(b)
418 zero = op == "*" and b == ("n", a)
419 if ka < kb and not zero:
420 continue
421 node = P + (1,) * (k - 2 - i) # (… op a) op b
422 rest = subterm_at(self.t, node + (1, 1)) if i else None
423 if ka > kb: # swap a and b
424 if i:
425 self.step(node, RIGHT_COMM[op], False, (rest, a, b))
426 else:
427 self.step(node, COMM[op], False, (a, b))
428 break
429 if i: # rest op (a op b)
430 self.step(node, ASSOC[op], True, (rest, a, b))
431 node += (2,)
432 if not zero: # a op a = a
433 self.step(node, IDEM[op], False, (a,))
434 break
435 self.step(node, "H8", False, (a,)) # a * n(a) = 0
436 self.exhaust(self.zeros, P)
437 return False
438 else:
439 return True
440
441 def tidy(self):
442 """Sorts every product, removes zeros, sorts the sum."""
443 i = 0
444 while self.t not in ("0", "1"):
445 el = operands(self.t, "+")
446 if i >= len(el):
447 self.sort_chain((), "+", product_key)
448 return
449 if self.sort_chain(operand_path((), len(el), i), "*",
450 literal_key):
451 i += 1
452 else:
453 self.exhaust(self.zeros) # a zero leaves the sum
454
455 def complete(self, variables):
456 """A product p without the variable v: p = p * 1 = p * (v + n(v))
457 = p * v + p * n(v). The constant 1 is the sum v + n(v)."""
458 if self.t == "0" or not variables:
459 return
460 if self.t == "1":
461 self.step((), "H7", True, (variables[0],))
462 while True:
463 el = operands(self.t, "+")
464 for i, e in enumerate(el):
465 missing = [v for v in variables if v not in tac.variables(e)]
466 if missing:
467 break
468 else:
469 return
470 v, sc = missing[0], operand_path((), len(el), i)
471 self.step(sc, "H6", True, (e,))
472 self.step(sc + (2,), "H7", True, (v,))
473 self.step(sc, "H4", False, (e, v, ("n", v)))
474 self.exhaust(self.flatten)
475 for j in (i, i + 1):
476 k = len(operands(self.t, "+"))
477 self.sort_chain(operand_path((), k, j), "*", literal_key)
478
479 def normalize(self, t, variables):
480 """(form, steps, terms on the way, index of the sum of products
481 before the minterms) for one side."""
482 self.t, self.steps, self.terms = t, [], [t]
483 self.exhaust(self.simplify)
484 self.exhaust(self.distribute)
485 self.exhaust(self.flatten)
486 self.tidy()
487 sums = len(self.steps)
488 self.complete(variables)
489 self.tidy()
490 return self.t, self.steps, self.terms, sums
491
492 def bridge(self, a, b):
493 """One or two steps with any fact from a to b (or None) — e.g.
494 consensus or absorption between sums of products."""
495 if self._bridge is None or self._bridge[0] != len(self.kernel.facts):
496 self._bridge = (len(self.kernel.facts), bridge_rules(self.kernel))
497 rules = self._bridge[1]
498 if term_size(a) + term_size(b) > 160:
499 return None
500 na = neighbours(self.kernel, a, rules)
501 if b in na:
502 return [na[b]]
503 nb = neighbours(self.kernel, b, rules)
504 for u, k in na.items():
505 if u in nb:
506 return [k] + reverse_steps([nb[u]])
507 return None
508
509 def proof(self, l, r, deadline=NO_DEADLINE):
510 """A chain l → r, or None (when the forms differ, the equation is
511 false). The chains of both sides are joined at their first common
512 term, often long before the minterms, and the sums of products
513 (before the minterms) we try to join by a short bridge."""
514 if not self.ready:
515 return None
516 self.deadline = deadline
517 variables = sorted(set(tac.variables(l)) | set(tac.variables(r)))
518 nl, kl, tl, sl = self.normalize(l, variables)
519 nr, kr, tr, sr = self.normalize(r, variables)
520 if nl != nr:
521 return None
522 index_of = {}
523 for j, t in enumerate(tr):
524 index_of.setdefault(t, j)
525 _, i, j = min((i + index_of[t], i, index_of[t])
526 for i, t in enumerate(tl) if t in index_of)
527 result = kl[:i] + reverse_steps(kr[:j])
528 if tl[sl] != tr[sr] and sl + sr + 2 < len(result):
529 bridge = self.bridge(tl[sl], tr[sr])
530 if bridge is not None and sl + sr + len(bridge) < len(result):
531 result = kl[:sl] + bridge + reverse_steps(kr[:sr])
532 return result