"""The Robbins problem with tactics (deep dive: compression). A Robbins algebra has a sum and a complement n(x) with three laws: A1 x + y = y + x A2 x + y + z = x + (y + z) R n(n(x + y) + n(x + n(y))) = x (Robbins, 1933) Every proof here is a tree of the five kernel rules. The tactics below write those trees for us, in the style of Lean's tactic blocks: g = Goal(K, "n(n(n(a + b) + n(a) + b) + b) = n(a + b)") g.nth_rw(2, "← R (n(a + b)) (n(a) + b)") g.nth_rw(3, "← R b a") g.ac() proof = g.qed() nth_rw k rewrites the k-th occurrence, rw every occurrence (as in Lean); "← R x y" uses the law from right to left; ac closes a goal whose sides differ only by A1 and A2 (module ac); rw_ac, ac_simp and auto rewrite modulo A1 and A2. Our kernel has no implication, so a lemma with hypotheses (Hypothetical) and a group of lemmas about constants (Section, like a section of Lean with `variable`) are proved once with constants and written down again for every use; the kernel checks every copy. """ from itertools import combinations from kernel import Kernel, Refl, Symm, Trans, CongrArg, Inst, subst from syntax import term, equation, show, show_equation from tactics import TacticError, match_pattern, variables, trans, symm, fresh from ac import (brief, order_key, Steps, ac_proof, ac_match, ac_match_part, at, is_sum, chain, addends, normal) SIGNATURE = {"+": 2, "n": 1} AXIOMS = [("A1", "x + y = y + x"), ("A2", "x + y + z = x + (y + z)"), ("R", "n(n(x + y) + n(x + n(y))) = x")] class Library(Kernel): """The kernel that also keeps the proofs of its theorems, so that we can measure them. The checking is the kernel's own, unchanged.""" def __init__(self, signature): super().__init__(signature) self.proofs = {} # name -> proof def theorem(self, name, variables, l, r, proof): super().theorem(name, variables, l, r, proof) self.proofs[name] = proof def theory(): """A kernel with the three laws of a Robbins algebra.""" K = Library(SIGNATURE) for name, text in AXIOMS: l, r = equation(text) K.axiom(name, variables(r, variables(l)), l, r) return K def times(k, a="a"): """k·a = a + a + ... + a (k summands), as text: times(3) = 'a + a + a'.""" return " + ".join([f"({a})" if "+" in a else a] * k) def _words(text): """'← R (a + b) c' -> ['←', 'R', '(a + b)', 'c']: split at spaces outside parentheses.""" words, depth, now = [], 0, "" for c in text.replace("←", " ← "): if c == " " and depth == 0: if now: words.append(now) now = "" continue depth += (c == "(") - (c == ")") now += c return words + ([now] if now else []) def positions(t, path=()): """Paths of all subterms in Lean's order: the term, then its arguments from left to right.""" yield path if not isinstance(t, str): for i, a in enumerate(t[1:], 1): yield from positions(a, path + (i,)) class Goal: """The goal l = r of a proof in progress, with the rewrites so far (a proof l0 = l and a proof r0 = r) and the local hypotheses.""" def __init__(self, kernel, statement, hypotheses=None): l, r = (equation(statement) if isinstance(statement, str) else statement) self.kernel = kernel self.sides = [Steps(kernel, l), Steps(kernel, r)] self.hypotheses = dict(hypotheses or {}) # name -> proof self.closing = None self.tactics = 0 # tactic calls so far self.equations = {} # id(proof) -> equation def goal(self): return self.sides[0].now, self.sides[1].now def __str__(self): return brief(show_equation(self.goal())) # --- reading a rule: a law, a lemma or a hypothesis --------------------- def rule(self, text): """'← R (a + b) c' -> (pattern, result, free, proof of instance). Arguments may be left out at the end or written _; they are then found by matching the pattern against the goal.""" words = _words(text) backward = words[0] == "←" if backward: words = words[1:] name, args = words[0], words[1:] if name in self.hypotheses: proof = self.hypotheses[name] l, r = self._known(proof) if backward: l, r, proof = r, l, symm(proof) return l, r, (), lambda s: proof if name not in self.kernel.facts: raise TacticError(f"unknown fact or hypothesis {name}") names, l, r = self.kernel.facts[name] given = {v: term(a) for v, a in zip(names, args) if a != "_"} if len(args) > len(names): raise TacticError(f"{name}: too many arguments") # the fact's own variables get names unlike those of the goal, so # that `R y _` does not mix the goal's y with the fact's y apart = _apart([v for v in names if v not in given], *(given[v] for v in given), *self.goal()) both = {**given, **apart} l, r = subst(l, both), subst(r, both) if backward: l, r = r, l free = tuple(apart[v] for v in apart) def proof(s): p = Inst(name, tuple(given[v] if v in given else s.get(apart[v], apart[v]) for v in names)) return Symm(p) if backward else p return l, r, free, proof def _known(self, proof): """The equation of a proof, computed once per proof.""" if id(proof) not in self.equations: self.equations[id(proof)] = (proof, self.kernel.conclusion(proof)) return self.equations[id(proof)][1] def _instance(self, pattern, free, sides): """The first match of the pattern in the goal (Lean's order).""" for i in sides: t = self.sides[i].now for path in positions(t): s = match_pattern(pattern, at(t, path), set(free), {}) if s is not None: return s raise TacticError(f"no {brief(show(pattern))} in {self}") # --- tactics ----------------------------------------------------------- def rw(self, *rules, side=None): """rw [r₁, r₂, …]: each rule rewrites every occurrence of its first match; side='lhs' or 'rhs' rewrites in one side only.""" for text in rules: self._rewrite(text, None, side) return self def nth_rw(self, k, *rules, side=None): """nth_rw k [r₁, …]: only the k-th occurrence (counted in Lean's order through the left side, then the right side).""" for text in rules: self._rewrite(text, k, side) return self def _rewrite(self, text, k, side): self.tactics += 1 pattern, result, free, proof = self.rule(text) sides = {None: (0, 1), "lhs": (0,), "rhs": (1,)}[side] s = self._instance(pattern, free, sides) u, p = subst(pattern, s), proof(s) w = subst(result, s) found = [] # (side, path) for i in sides: t = self.sides[i].now inside = None for path in positions(t): if (k is None and inside is not None and path[:len(inside)] == inside): continue # rw: not inside a match if at(t, path) == u: found.append((i, path)) inside = path if k is not None: if k > len(found): raise TacticError(f"nth_rw {k}: only {len(found)} " f"occurrences of {brief(show(u))}") found = [found[k - 1]] for i, path in found: self.sides[i].step(path, p, (u, w)) def rw_ac(self, *rules, side=None): """rw modulo A1 and A2: the rule's left side may sit in the goal reordered, or as a part of a longer sum — e.g. b + a inside c + (a + d + b). Missing arguments are found by matching modulo A1 and A2. The goal is first brought to the normal form, the summands are regrouped so that the pattern stands alone, then the rule rewrites it once (the first match in Lean's order).""" for text in rules: self.tactics += 1 if not self._rewrite_ac(text, side): raise TacticError(f"rw_ac [{text}]: no match (up to A1, " f"A2) in {self}") return self def _rewrite_ac(self, text, side): pattern, result, free, proof = self.rule(text) free = set(free) for i in {None: (0, 1), "lhs": (0,), "rhs": (1,)}[side]: steps = self.sides[i] t = normal(steps.now) for path in positions(t): v = at(t, path) found = next(ac_match(pattern, v, free, {}), None) rest = None if found is None and is_sum(pattern) \ and _whole_sum(t, path): for s, left in ac_match_part(pattern, addends(v), free, {}): if left: found, rest = s, left break if found is None: continue u = subst(pattern, found) if rest is None: regrouped, where = _put(t, path, u), path else: regrouped = _put(t, path, ("+", chain(rest), u)) where = path + (2,) steps.step((), ac_proof(self.kernel, steps.now, regrouped), (steps.now, regrouped)) w = subst(result, found) steps.step(where, proof(found), (u, w)) return True return False def ac_simp(self, *rules, limit=50): """simp modulo A1 and A2: rewrite with the rules (in the given direction) as long as one of them applies, then close the goal if the sides agree up to A1 and A2.""" for _ in range(limit): if not any(self._rewrite_ac(text, None) for text in rules): break else: raise TacticError(f"ac_simp: more than {limit} rewrites") self.tactics += 1 l, r = self.goal() if normal(l) == normal(r): self.closing = ac_proof(self.kernel, l, r) return self def exact_ac(self, proof): """Close the goal with a proof of an equation that differs from the goal only by A1 and A2.""" self.tactics += 1 a, b = self._known(proof) l, r = self.goal() self.closing = trans(ac_proof(self.kernel, l, a), proof, ac_proof(self.kernel, b, r)) or proof return self def auto(self, *rules, pool=2, limit=200_000, depth=1): """Find the creative steps by search: at most `depth` rewrites on each side (meet in the middle), then ac. Rules: "R" contracts (finds the pattern modulo A1, A2), "← R" expands a part x of the goal to n(n(x + y) + n(x + n(y))) with y taken from the terms of the goal and their sums of up to `pool` summands; other rules are rewrites modulo A1, A2. Mathlib writes such steps by hand: nth_rw 2 [← robbins (-(a + b)) (-a + b)].""" self.tactics += 1 rules = rules or ("R", "← R") l, r = self.goal() nl, nr = normal(l), normal(r) if nl == nr: self.closing = ac_proof(self.kernel, l, r) return self terms = _pool(nl, nr, pool) tables = ({nl: None}, {nr: None}) # term -> (previous, move) layers = [[nl], [nr]] meet = None for _ in range(depth): for side in (0, 1): table, layer = tables[side], [] for t in layers[side]: for u, move in self._moves(t, rules, terms, limit).items(): if u not in table: table[u] = (t, move) layer.append(u) if len(table) > limit: raise TacticError("auto: too many possibilities") layers[side] = layer left, right = tables if nr in left: meet = nr elif nl in right: meet = nl else: meet = next((t for t in left if t in right), None) if meet is not None: break if meet is None: raise TacticError( f"auto: no proof with {depth} step(s) on " f"each side for {self}") for side in (0, 1): path, t = [], meet while tables[side].get(t) is not None: t, move = tables[side][t] path.append(move) for regrouped, where, p, equation in reversed(path): steps = self.sides[side] steps.step((), ac_proof(self.kernel, steps.now, regrouped), (steps.now, regrouped)) steps.step(where, p, equation) self.closing = ac_proof(self.kernel, *self.goal()) return self def _moves(self, t, rules, terms, limit): """{normal form after one rewrite: (term before the rewrite, where, proof of the rewrite, its equation)} for the term t.""" found = {} for text in rules: pattern, result, free, proof = self.rule(text) for regrouped, where, s in _places(t, pattern, set(free), terms): u, w = subst(pattern, s), subst(result, s) new = normal(_put(regrouped, where, w)) if new not in found: found[new] = (regrouped, where, proof(s), (u, w)) if len(found) > limit: raise TacticError("auto: too many possibilities") return found def ac(self): """Close the goal: the sides differ only by A1 and A2.""" self.tactics += 1 self.closing = ac_proof(self.kernel, *self.goal()) return self def rfl(self): self.tactics += 1 l, r = self.goal() if l != r: raise TacticError(f"rfl: {self}") self.closing = None return self def exact(self, proof): """Close the goal with a proof of exactly this equation.""" self.tactics += 1 if self._known(proof) != self.goal(): raise TacticError(f"exact: the proof does not fit {self}") self.closing = proof return self def fact(self, text): """The proof of one instance: fact('mann_44 a (b + c)').""" pattern, result, free, proof = self.rule(text) if free: raise TacticError(f"{text}: give all arguments") return proof({}) def have(self, name, proof): """A local hypothesis: a proof of an equation, used by rw.""" self.hypotheses[name] = proof return self def qed(self): """The proof of the original goal: rewrites, closing, rewrites.""" l, r = self.goal() if l != r and self.closing is None: raise TacticError(f"unfinished: {self}") left, right = self.sides return (trans(left.proof, self.closing, symm(right.proof)) or Refl(left.start)) def _whole_sum(t, path): """Is the subterm at the path a whole sum (not a part of a longer one)?""" if not is_sum(at(t, path)): return False return not path or not is_sum(at(t, path[:-1])) def _apart(names, *terms): """New names x_, y_, ... for the variables `names`, unlike all variables of the terms.""" taken = set() for t in terms: taken.update(variables(t)) result = {} for v in names: i, candidate = 0, v + "_" while candidate in taken: i += 1 candidate = f"{v}_{i}" taken.add(candidate) result[v] = candidate return result def _parts(ts, most): """Sums of 2..most summands taken from the list ts (as normal forms).""" seen = set() for k in range(2, min(most, len(ts)) + 1): for bundle in combinations(sorted(ts, key=order_key), k): if bundle not in seen: seen.add(bundle) yield chain(list(bundle)) def _pool(nl, nr, most): """Candidate terms for a variable that matching does not fix: all subterms of the goal and sums of up to `most` summands of its sums.""" terms = set() for t in (nl, nr): for path in positions(t): v = at(t, path) terms.add(v) if _whole_sum(t, path): terms.update(_parts(addends(v), most)) return sorted(terms, key=order_key) def _places(t, pattern, free, terms): """Where the pattern fits in the normal form t: (the term with the match standing alone, path of the match, substitution). A variable left free by matching takes every value from `terms`.""" for path in positions(t): v = at(t, path) options = [(s, None) for s in ac_match(pattern, v, free, {})] if _whole_sum(t, path): ts = addends(v) if isinstance(pattern, str) and pattern in free: for bundle in _parts(ts, len(ts) - 1): # a part of the sum options.append(({pattern: bundle}, _minus(ts, addends(bundle)))) elif is_sum(pattern): options += [(s, left) for s, left in ac_match_part(pattern, ts, free, {}) if left] for s, rest in options: missing = [x for x in sorted(free) if x not in s] for values in _choices(missing, terms): s2 = {**s, **values} u = subst(pattern, s2) if rest is None: yield _put(t, path, u), path, s2 else: yield (_put(t, path, ("+", chain(rest), u)), path + (2,), s2) def _choices(missing, terms): if not missing: yield {} return for value in terms: for others in _choices(missing[1:], terms): yield {missing[0]: value, **others} def _minus(whole, part): """The multiset difference whole − part, or None if part ⊄ whole.""" rest = list(whole) for x in part: if x not in rest: return None rest.remove(x) return rest def _put(t, path, u): if not path: return u i = path[0] return t[:i] + (_put(t[i], path[1:], u),) + t[i + 1:] def rewrite_at(kernel, proof, *rules, hypotheses=None, ac=False): """rw [...] at h: the hypothesis u = w becomes u' = w'.""" g = Goal(kernel, kernel.conclusion(proof), hypotheses) (g.rw_ac if ac else g.rw)(*rules) left, right = g.sides return trans(symm(left.proof), proof, right.proof) or proof def congr_n(proof): """From a proof of u = w a proof of n(u) = n(w).""" return CongrArg("z", ("n", "z"), proof) class Hypothetical: """A lemma with hypotheses, e.g. (Mann's lemma 35): if n(a + n(b)) = c, then n(n(a + b) + c) = a. Our kernel has no implication, so the lemma is proved once in a kernel where a, b, c are constants and the hypotheses are axioms h1, h2, ... To use it for terms and proofs of the hypotheses we substitute them into that one proof; the kernel checks the result again wherever it is used.""" def __init__(self, base, name, constants, hypotheses, statement, script): K = Library({**base.signature, **{c: 0 for c in constants}}) K.facts, K.assumptions = dict(base.facts), dict(base.assumptions) for i, text in enumerate(hypotheses, 1): K.axiom(f"h{i}", (), *equation(text)) g = Goal(K, statement) script(g) self.proof = g.qed() K.theorem(name, (), *equation(statement), self.proof) self.kernel, self.name, self.constants = K, name, tuple(constants) self.hypotheses = [equation(text) for text in hypotheses] self.tactics = g.tactics def __call__(self, values, *proofs): """The proof for the terms `values` (constant -> term or text) from proofs of the hypotheses, in the order h1, h2, ...""" values = {c: term(v) if isinstance(v, str) else v for c, v in values.items()} if set(values) != set(self.constants) or \ len(proofs) != len(self.hypotheses): raise TacticError(f"{self.name}: wrong arguments") return transport(self.proof, values, {f"h{i}": p for i, p in enumerate(proofs, 1)}) class Section: """Lemmas about constants that satisfy hypotheses — in Lean a section with `variable (e : α) (h1 : e + e = e)`. Each lemma is proved once, with the short constant e instead of a long term; `use` writes all of them down again in another kernel, with terms for the constants and proofs for the hypotheses (the kernel checks everything again).""" def __init__(self, base, constants, hypotheses): K = Library({**base.signature, **{c: 0 for c in constants}}) K.facts, K.assumptions = dict(base.facts), dict(base.assumptions) for i, text in enumerate(hypotheses, 1): K.axiom(f"h{i}", (), *equation(text)) self.kernel, self.constants = K, tuple(constants) self.lemmas = [] # (name, variables, l, r, proof) self.tactics = {} # name -> tactic calls def lemma(self, name, statement, script): g = Goal(self.kernel, statement) script(g) proof = g.qed() l, r = equation(statement) if isinstance(statement, str) \ else statement names = [v for v in variables(r, variables(l)) if self.kernel.is_var(v)] self.kernel.theorem(name, names, l, r, proof) self.lemmas.append((name, tuple(names), l, r, proof)) self.tactics[name] = g.tactics return proof def include(self, name, names, l, r, proof): """A lemma proved elsewhere (another section used in this one).""" self.kernel.theorem(name, names, l, r, proof) self.lemmas.append((name, tuple(names), l, r, proof)) def use(self, place, values, *proofs, prefix=""): """All lemmas of the section in `place` (a kernel or a section), as prefix + name. A term put for a constant may bring new variables (e.g. a in q(a)); they become variables of the lemmas too, and every use of a lemma passes them on unchanged.""" kernel = place.kernel if isinstance(place, Section) else place values = {c: term(v) if isinstance(v, str) else v for c, v in values.items()} hypotheses = {f"h{i}": p for i, p in enumerate(proofs, 1)} renamed = {} for name, names, l, r, proof in self.lemmas: l2, r2 = subst(l, values), subst(r, values) new = [v for v in variables(r2, variables(l2)) if kernel.is_var(v)] p = transport(proof, values, hypotheses, renamed) renamed[name] = (prefix + name, names, tuple(new)) if isinstance(place, Section): place.include(prefix + name, new, l2, r2, p) else: kernel.theorem(prefix + name, new, l2, r2, p) def transport(proof, values, hypotheses, renamed=None): """The proof with constants replaced by terms and the axioms h1, ... by proofs. A CongrArg hole gets a fresh name, so that the variables of the new terms cannot be caught by it.""" taken = [values[c] for c in values] def tr(d): match d: case Refl(t): return Refl(subst(t, values)) case Symm(p): return Symm(tr(p)) case Trans(p, q): return Trans(tr(p), tr(q)) case CongrArg(z, C, p): z2 = fresh(C, *taken) return CongrArg(z2, subst(C, {**values, z: z2}), tr(p)) case Inst(name, args): if name in hypotheses: return hypotheses[name] args = tuple(subst(a, values) for a in args) if renamed and name in renamed: # a lemma of a section new_name, earlier, new = renamed[name] given = dict(zip(earlier, args)) return Inst(new_name, tuple(given.get(v, v) for v in new)) return Inst(name, args) raise TacticError(f"not a proof: {d!r}") return tr(proof) def lemma(kernel, name, statement, script): """A theorem: the script (a function of the goal) proves it, then the kernel checks the proof and adds the theorem.""" g = Goal(kernel, statement) script(g) proof = g.qed() l, r = equation(statement) kernel.theorem(name, variables(r, variables(l)), l, r, proof) return proof, g.tactics # --- how big is a proof? --------------------------------------------------- def nodes(proof): """Rule applications in a proof tree; a use of a lemma counts once.""" match proof: case Refl(_) | Inst(_, _): return 1 case Symm(p) | CongrArg(_, _, p): return 1 + nodes(p) case Trans(p, q): return 1 + nodes(p) + nodes(q) raise TacticError(f"not a proof: {proof!r}") def expanded(kernel, proof, memo=None): """Rule applications if every lemma were replaced by its own proof, again and again, down to the axioms: the size of the proof without lemmas. The number is exact (Python integers have no limit).""" memo = {} if memo is None else memo def size(d): match d: case Refl(_): return 1 case Inst(name, _): if name not in kernel.proofs: return 1 # an axiom if name not in memo: memo[name] = size(kernel.proofs[name]) return memo[name] case Symm(p) | CongrArg(_, _, p): return 1 + size(p) case Trans(p, q): return 1 + size(p) + size(q) raise TacticError(f"not a proof: {d!r}") return size(proof) def lemmas_used(kernel, name, seen=None): """All theorems that the proof of `name` needs, directly or not.""" seen = set() if seen is None else seen for d in _insts(kernel.proofs[name]): if d in kernel.proofs and d not in seen: seen.add(d) lemmas_used(kernel, d, seen) return seen def _insts(proof): stack, names = [proof], set() while stack: d = stack.pop() match d: case Inst(name, _): names.add(name) case Symm(p) | CongrArg(_, _, p): stack.append(p) case Trans(p, q): stack += [p, q] return names __all__ = ["theory", "Library", "Goal", "lemma", "Hypothetical", "Section", "transport", "rewrite_at", "congr_n", "times", "nodes", "expanded", "lemmas_used", "SIGNATURE", "AXIOMS"]