"""The Boole Lab solver: a proof of every true equation (for hint and auto). The solver lies OUTSIDE the kernel, like the tactics. It returns a chain of steps, and the lab (lab.py) turns it into ordinary rw / nth_rw lines; the kernel checks every proof at qed anyway. A step is a tuple (path, fact, backward, arguments): the subterm at the path (argument numbers from the root) is an instance of one side of the fact — the left one, or the right one when backward — and we replace it by the instance of the other side. Two strategies (the lab adds breadth-first search to them): * a library proof — the goal is an instance of a theorem, also of one that may not yet be used in an exercise. Then we put in place of the step the proof of that theorem: the tree accepted by the kernel, flattened into a chain (flatten); * the normal form — both sides are brought to a sorted sum of full products of the variables and their complements (minterms). Two terms are equal in every Boolean algebra exactly when they have the same form, so this strategy finds a proof of EVERY true equation. It is a decision procedure, not a heuristic; its proofs can be long. Steps with theorems outside the allowed ones are expanded into their proofs (recursively) until only allowed facts remain — in the worst case the axioms H1–H8 (Expander). """ import time import tactics as tac from kernel import CongrArg, Inst, Refl, Symm, Trans, subst STEP_LIMIT = 3000 # a longer chain: the strategy gives up SIZE_LIMIT = 2000 # a larger term on the way: likewise class TooBig(Exception): """A chain or a term exceeded the limit.""" class OutOfTime(TooBig): """The time for searching is up.""" class Deadline: """The moment after which strategies give up (None: no limit).""" def __init__(self, seconds=None): self.end = None if seconds is None else \ time.perf_counter() + seconds def check(self): if self.end is not None and time.perf_counter() > self.end: raise OutOfTime() NO_DEADLINE = Deadline() # --- terms and steps --------------------------------------------------------- def term_size(t): return 1 if isinstance(t, str) else 1 + sum(map(term_size, t[1:])) def subterm_at(t, path): """The subterm at the path.""" for i in path: t = t[i] return t def replace_at(t, path, u): """The term t with the subterm at the path replaced by u.""" if not path: return u i = path[0] return t[:i] + (replace_at(t[i], path[1:], u),) + t[i + 1:] def positions(t, path=()): """Pairs (path, subterm) in prefix order.""" yield path, t if not isinstance(t, str): for i, a in enumerate(t[1:], start=1): yield from positions(a, path + (i,)) def leaves(t): if isinstance(t, str): return {t} return set().union(*map(leaves, t[1:])) def occurrences(t, u, path=()): """Paths of the occurrences of u in t, in prefix order.""" if t == u: return [path] if isinstance(t, str): return [] result = [] for i, a in enumerate(t[1:], start=1): result += occurrences(a, u, path + (i,)) return result def reverse_steps(steps): """The chain b → a from the chain a → b.""" return [(s, f, not w, a) for s, f, w, a in reversed(steps)] def apply_step(kernel, t, step): """The term after a step; ValueError when the step does not fit t.""" path, fact, backward, args = step vs, l, r = kernel.facts[fact] s = dict(zip(vs, args)) a, b = (r, l) if backward else (l, r) try: u = subterm_at(t, path) except (IndexError, TypeError): raise ValueError(f"{fact}: wrong path {path}") from None if u != subst(a, s): raise ValueError(f"{fact}: the step does not fit the term") return replace_at(t, path, subst(b, s)) def replay(kernel, t, steps): """The terms t, t₁, …, tₙ after the consecutive steps.""" terms = [t] for step in steps: terms.append(apply_step(kernel, terms[-1], step)) return terms def segment(terms, steps, goal): """The piece of the chain from goal[0] to goal[1] when both lie on the chain (terms[i] is the term after i steps), or None.""" lefts = [i for i, t in enumerate(terms) if t == goal[0]] rights = [j for j, t in enumerate(terms) if t == goal[1]] if not lefts or not rights: return None _, i, j = min((abs(i - j), i, j) for i in lefts for j in rights) return steps[i:j] if i <= j else reverse_steps(steps[j:i]) def without_loops(terms, steps): """Steps without detours: when the chain returns to a term, we cut out the loop.""" last = {t: i for i, t in enumerate(terms)} result, i = [], 0 while i < len(steps): if last[terms[i]] > i: i = last[terms[i]] continue result.append(steps[i]) i += 1 return result # --- library proofs ---------------------------------------------------------- def flatten(d): """A chain of steps from a proof tree: from the left side of the conclusion to the right one. Inst is one step at the root, CongrArg moves the steps into every occurrence of the hole, Symm reverses a chain and Trans glues two.""" if isinstance(d, Inst): return [((), d.name, False, tuple(d.args))] if isinstance(d, Refl): return [] if isinstance(d, Symm): return reverse_steps(flatten(d.p)) if isinstance(d, Trans): return flatten(d.p) + flatten(d.q) if isinstance(d, CongrArg): steps = flatten(d.p) return [(sc + s, f, w, a) for sc in occurrences(d.C, d.z) for s, f, w, a in steps] raise TypeError(f"not a proof: {d!r}") class Expander: """Replaces steps with theorems outside the allowed ones by their proofs. `proofs` is a dict name -> tree accepted by the kernel (the library and the user's theorems). Facts are only ever added, so chains can be remembered: the key is the name and the set of allowed facts.""" def __init__(self, kernel, proofs): self.kernel, self.proofs = kernel, proofs self._memo = {} def chain(self, name, allowed, deadline=NO_DEADLINE): """A proof of the theorem (in its variables) from allowed facts.""" key = (name, allowed) if key not in self._memo: self._memo[key] = None # so far: too long try: self._memo[key] = self.expand( flatten(self.proofs[name]), allowed, deadline) except OutOfTime: # time ran out, not the limit del self._memo[key] raise if self._memo[key] is None: raise TooBig(name) return self._memo[key] def expand(self, steps, allowed, deadline=NO_DEADLINE): result = [] for step in steps: path, fact, backward, args = step if fact in allowed: result.append(step) continue if fact not in self.proofs: # an axiom outside the task raise KeyError(fact) deadline.check() s = dict(zip(self.kernel.facts[fact][0], args)) new = [(path + p, f, w, tuple(subst(x, s) for x in a)) for p, f, w, a in self.chain(fact, allowed, deadline)] result += reverse_steps(new) if backward else new if len(result) > STEP_LIMIT: raise TooBig(fact) return result def bridge_rules(kernel): """All facts in both directions, but only those whose source side is not a bare variable and binds all the variables of the fact (no "blowing up" like x = x + 0).""" result = {} for name, (vs, l, r) in kernel.facts.items(): ren = {x: "?" + x for x in vs} free = tuple(ren.values()) for backward, a in ((False, l), (True, r)): pat = subst(a, ren) if isinstance(pat, str) or not set(free) <= leaves(pat): continue result.setdefault(pat[0], []).append((name, backward, pat, free, vs)) return result def neighbours(kernel, t, rules): """{term: step} — all rewrites of one subterm of t.""" result = {} for path, u in positions(t): if isinstance(u, str): continue for fact, backward, pat, free, vs in rules.get(u[0], ()): s = tac.match_pattern(pat, u, free, {}) if s is not None: step = (path, fact, backward, tuple(s[x] for x in free)) result.setdefault(apply_step(kernel, t, step), step) return result def instances(kernel, goal): """Steps ((), fact, backward, args) that close the goal l = r alone.""" L, R = goal for name, (vs, l, r) in kernel.facts.items(): ren = {x: "?" + x for x in vs} free = tuple(ren.values()) for backward, (a, b) in ((False, (l, r)), (True, (r, l))): s = tac.match_pattern(subst(a, ren), L, free, {}) if s is not None: s = tac.match_pattern(subst(b, ren), R, free, s) if s is not None and len(s) == len(free): yield (), name, backward, tuple(s["?" + x] for x in vs) # --- the normal form --------------------------------------------------------- # Directed rules (fact, backward): each one shrinks the term or pushes the # complement down, so rewriting with them terminates. The names are the # English library names; NormalForm(kernel, names) maps them to the names # the facts have in the kernel (in the Polish lab: Polish names). SIMPLIFY = [ ("de_morgan_add", False), ("de_morgan_mul", False), ("compl_compl", False), ("compl_zero", False), ("compl_one", False), ("H5", False), ("zero_add", False), ("H6", False), ("one_mul", False), ("add_one", False), ("one_add", False), ("mul_zero", False), ("zero_mul", False), ("H7", False), ("compl_add", False), ("H8", False), ("compl_mul", False), ("add_idem", False), ("mul_idem", False), ("absorb", False), ("absorb_right", False), ("absorb_mul", False), ("absorb_mul_right", False), ("add_compl_mul", False), ("compl_add_mul", False), ("mul_compl_add", False), ("compl_mul_add", False), ] DISTRIBUTE = [("H4", False), ("add_mul", False)] FLATTEN = [("add_assoc", False), ("mul_assoc", False)] ZEROS = [("H5", False), ("zero_add", False), ("mul_zero", False), ("zero_mul", False)] COMM = {"+": "H1", "*": "H2"} # x ∘ y = y ∘ x ASSOC = {"+": "add_assoc", "*": "mul_assoc"} # x ∘ (y ∘ z) = … RIGHT_COMM = {"+": "add_right_comm", "*": "mul_right_comm"} IDEM = {"+": "add_idem", "*": "mul_idem"} # x ∘ x = x def operands(t, op): """The operands of a chain a₁ op a₂ op … op aₖ nested to the left.""" result = [] while not isinstance(t, str) and t[0] == op: result.append(t[2]) t = t[1] result.append(t) return result[::-1] def operand_path(path, k, i): """The path of the i-th (from 0) of k operands of a chain at `path`.""" return path + (1,) * (k - 1 - i) + ((2,) if i else ()) def literal_key(t): """The order x, n(x), y, n(y), …; other terms (there should be none) go last, so that the comparison always works.""" if isinstance(t, str): return (0, t, 0) if t[0] == "n" and isinstance(t[1], str): return (0, t[1], 1) return (1, repr(t), 0) def product_key(t): return tuple(map(literal_key, operands(t, "*"))) class NormalForm: """A proof via the normal form (a sum of minterms). Stages for each side: (a) complements go down (De Morgan, involution), constants and obvious repetitions vanish; (b) distributivity: a sum of products; (c) associativity: chains nested to the left, sorted (commutativity), without repetitions, products with x and n(x) vanish; (d) every product without the variable v splits into p * v + p * n(v); then (c) again.""" def __init__(self, kernel, names=None): self.kernel = kernel self.names = names or {} # English name -> name in kernel needed = {f for group in (SIMPLIFY, DISTRIBUTE, FLATTEN, ZEROS) for f, _ in group} for table in (COMM, ASSOC, RIGHT_COMM, IDEM): needed |= set(table.values()) self.ready = {self._n(f) for f in needed} <= set(kernel.facts) self._bridge = None self.deadline = NO_DEADLINE if self.ready: self.simplify = self._rules(SIMPLIFY) self.distribute = self._rules(SIMPLIFY + DISTRIBUTE) self.flatten = self._rules(FLATTEN) self.zeros = self._rules(ZEROS) def _n(self, name): return self.names.get(name, name) def _rules(self, rules): result = {} for fact, backward in rules: fact = self._n(fact) vs, l, r = self.kernel.facts[fact] ren = {x: "?" + x for x in vs} pat = subst(r if backward else l, ren) result.setdefault(pat[0], []).append( (fact, backward, pat, tuple(ren.values()), vs)) return result def step(self, path, fact, backward, args): k = (tuple(path), self._n(fact), backward, tuple(args)) self.t = apply_step(self.kernel, self.t, k) self.steps.append(k) self.terms.append(self.t) if len(self.steps) > STEP_LIMIT or \ term_size(self.t) > SIZE_LIMIT: raise TooBig() self.deadline.check() def try_rules(self, path, rules): u = subterm_at(self.t, path) if isinstance(u, str): return False for fact, backward, pat, free, vs in rules.get(u[0], ()): s = tac.match_pattern(pat, u, free, {}) if s is not None: self.step(path, fact, backward, [s["?" + x] for x in vs]) return True return False def exhaust(self, rules, path=()): """From the top: rules at the node, then in the children; a node returns to the queue when one of its children changed.""" changed = False while True: while self.try_rules(path, rules): changed = True u = subterm_at(self.t, path) if isinstance(u, str): return changed children = False for i in range(1, len(u)): children = self.exhaust(rules, path + (i,)) or children if not children: return changed changed = True def sort_chain(self, P, op, key): """Sorts (bubble sort) the op chain rooted at the path P and removes repetitions. In a product the pair v, n(v) makes the whole product zero — then the result is False.""" while True: el = operands(subterm_at(self.t, P), op) k = len(el) for i in range(k - 1): a, b = el[i], el[i + 1] ka, kb = key(a), key(b) zero = op == "*" and b == ("n", a) if ka < kb and not zero: continue node = P + (1,) * (k - 2 - i) # (… op a) op b rest = subterm_at(self.t, node + (1, 1)) if i else None if ka > kb: # swap a and b if i: self.step(node, RIGHT_COMM[op], False, (rest, a, b)) else: self.step(node, COMM[op], False, (a, b)) break if i: # rest op (a op b) self.step(node, ASSOC[op], True, (rest, a, b)) node += (2,) if not zero: # a op a = a self.step(node, IDEM[op], False, (a,)) break self.step(node, "H8", False, (a,)) # a * n(a) = 0 self.exhaust(self.zeros, P) return False else: return True def tidy(self): """Sorts every product, removes zeros, sorts the sum.""" i = 0 while self.t not in ("0", "1"): el = operands(self.t, "+") if i >= len(el): self.sort_chain((), "+", product_key) return if self.sort_chain(operand_path((), len(el), i), "*", literal_key): i += 1 else: self.exhaust(self.zeros) # a zero leaves the sum def complete(self, variables): """A product p without the variable v: p = p * 1 = p * (v + n(v)) = p * v + p * n(v). The constant 1 is the sum v + n(v).""" if self.t == "0" or not variables: return if self.t == "1": self.step((), "H7", True, (variables[0],)) while True: el = operands(self.t, "+") for i, e in enumerate(el): missing = [v for v in variables if v not in tac.variables(e)] if missing: break else: return v, sc = missing[0], operand_path((), len(el), i) self.step(sc, "H6", True, (e,)) self.step(sc + (2,), "H7", True, (v,)) self.step(sc, "H4", False, (e, v, ("n", v))) self.exhaust(self.flatten) for j in (i, i + 1): k = len(operands(self.t, "+")) self.sort_chain(operand_path((), k, j), "*", literal_key) def normalize(self, t, variables): """(form, steps, terms on the way, index of the sum of products before the minterms) for one side.""" self.t, self.steps, self.terms = t, [], [t] self.exhaust(self.simplify) self.exhaust(self.distribute) self.exhaust(self.flatten) self.tidy() sums = len(self.steps) self.complete(variables) self.tidy() return self.t, self.steps, self.terms, sums def bridge(self, a, b): """One or two steps with any fact from a to b (or None) — e.g. consensus or absorption between sums of products.""" if self._bridge is None or self._bridge[0] != len(self.kernel.facts): self._bridge = (len(self.kernel.facts), bridge_rules(self.kernel)) rules = self._bridge[1] if term_size(a) + term_size(b) > 160: return None na = neighbours(self.kernel, a, rules) if b in na: return [na[b]] nb = neighbours(self.kernel, b, rules) for u, k in na.items(): if u in nb: return [k] + reverse_steps([nb[u]]) return None def proof(self, l, r, deadline=NO_DEADLINE): """A chain l → r, or None (when the forms differ, the equation is false). The chains of both sides are joined at their first common term, often long before the minterms, and the sums of products (before the minterms) we try to join by a short bridge.""" if not self.ready: return None self.deadline = deadline variables = sorted(set(tac.variables(l)) | set(tac.variables(r))) nl, kl, tl, sl = self.normalize(l, variables) nr, kr, tr, sr = self.normalize(r, variables) if nl != nr: return None index_of = {} for j, t in enumerate(tr): index_of.setdefault(t, j) _, i, j = min((i + index_of[t], i, index_of[t]) for i, t in enumerate(tl) if t in index_of) result = kl[:i] + reverse_steps(kr[:j]) if tl[sl] != tr[sr] and sl + sr + 2 < len(result): bridge = self.bridge(tl[sl], tr[sr]) if bridge is not None and sl + sr + len(bridge) < len(result): result = kl[:sl] + bridge + reverse_steps(kr[:sr]) return result