"""Other axiom systems for the Boole Lab (bl theory) and finite models. The Boolean theory of the lecture (axioms H1–H8 and the library) is the default. Every other theory has its own signature and axioms, and the lab starts a fresh kernel for it: * dn1 — Boolean algebra from ONE equation in + and n (DN1: W. McCune, R. Veroff, B. Fitelson, K. Harris, A. Feist, L. Wos, "Short Single Axioms for Boolean Algebra", J. Automated Reasoning 29, 2002); * sheffer — Boolean algebra from ONE equation in the Sheffer stroke (Sh1, the same paper: a shortest single axiom, length 15); * sheffer2 — R. Veroff's shortest 2-basis in the Sheffer stroke (J. Automated Reasoning 31, 2003): (x | y) | (x | (y | z)) = x (his equation 26a, here V) and commutativity; * weak — commutativity and (x | x) | (x | y) = x: Boolean equations that are NOT a basis. The three-element model M1 from Veroff's paper satisfies them but not x | (x | x) = y | (y | y); a Boolean algebra has 2^k elements anyway; * median — median algebra: majority, two symmetries and associativity, as in R. Veroff and W. McCune's notes "Median Algebra Proof" (2005). Both distributive laws follow; a first-order proof of that was found by Otter and Prover9 for a problem that came to them from D. Knuth; * robbins — Robbins algebra (A1, A2 and the Robbins equation R), and four theories with constants and a hypothesis for the stages of its proof: robbins_ab (A + B = B, Mann), robbins_e (e + e = e, Mann), robbins_cd (D + C = C, McCune's Lemma 1) and robbins_c (C + C = C, his Lemma 0). The variants of the proof and their scripts are in robbins_lab.py. Deriving the usual laws from these axioms is hard: the published derivations were found by automated provers (a 57-step Otter derivation of the Robbins basis from DN1, 66 steps from Sh1 to Sheffer's three axioms). The lab gives the setting and the models; derivations are the reader's challenge, and a model in which an equation fails shows at once that it does not follow from the axioms (soundness of the kernel). A model is a finite set with operation tables; `counterexample` looks for a valuation that falsifies an equation in a model. Terms are the kernel's tuples; a symbol of a theory, e.g. nand or med, is applied as ('nand', a, b). """ import re from itertools import product M1_TABLE = ((2, 2, 2), # Veroff's M1: rows x, columns y, value x | y (2, 1, 1), (2, 1, 0)) MODELS = { "B2": { "elements": (0, 1), "ops": {"+": lambda a, b: a | b, "*": lambda a, b: a & b, "n": lambda a: 1 - a, "0": 0, "1": 1, "nand": lambda a, b: 1 - (a & b), "med": lambda a, b, c: (a & b) | (a & c) | (b & c)}, "desc_pl": "dwuelementowa algebra Boole'a {0, 1}", "desc_en": "the two-element Boolean algebra {0, 1}", }, "M1": { "elements": (0, 1, 2), "ops": {"nand": lambda a, b: M1_TABLE[a][b]}, "desc_pl": "trzyelementowa tabelka kreski z pracy Veroffa", "desc_en": "Veroff's three-element stroke table", }, "C3": { "elements": (0, 1, 2), "ops": {"med": lambda a, b, c: sorted((a, b, c))[1]}, "desc_pl": "mediana na łańcuchu 0 < 1 < 2", "desc_en": "the median on the chain 0 < 1 < 2", }, } for _model, _constants in (("B2ab", {"A": 0, "B": 1, "c": 1, "d": 1}), ("B2e", {"e": 1}), ("B2cd", {"C": 1, "D": 0}), ("B2c", {"C": 1})): MODELS[_model] = { "elements": (0, 1), "ops": {**MODELS["B2"]["ops"], **_constants}, "desc_pl": "algebra {0, 1}, " + ", ".join( f"{k} = {v}" for k, v in _constants.items()), "desc_en": "the algebra {0, 1}, " + ", ".join( f"{k} = {v}" for k, v in _constants.items()), } DN1 = "n(n(n(x + y) + z) + n(x + n(n(z) + n(z + u)))) = z" SH1 = "nand(nand(x, nand(nand(y, x), x)), nand(y, nand(z, x))) = y" ROBBINS = [("A1", "x + y = y + x"), ("A2", "x + y + z = x + (y + z)"), ("R", "n(n(x + y) + n(x + n(y))) = x")] THEORIES = { "dn1": { "name_pl": "dn1", "title_pl": "algebra Boole'a z jednego równania DN1 (+, n)", "title_en": "Boolean algebra from the single equation DN1 (+, n)", "signature": {"+": 2, "n": 1}, "functions": {}, "axioms": [("DN1", DN1)], "models": ["B2"], "lean_class": "DN1Algebra", "challenges": ["x + y = y + x", "n(n(x)) = x", "x + y + z = x + (y + z)", "n(n(x + y) + n(x + n(y))) = x"], }, "sheffer": { "name_pl": "sheffer", "title_pl": "algebra Boole'a z jednego równania Sh1 (kreska Sheffera)", "title_en": "Boolean algebra from the single equation Sh1 " "(the Sheffer stroke)", "signature": {"nand": 2}, "functions": {"nand": 2}, "axioms": [("Sh1", SH1)], "models": ["B2", "M1"], "lean_class": "ShefferAlgebra", "challenges": ["nand(x, y) = nand(y, x)", "nand(nand(x, y), nand(x, nand(y, z))) = x"], }, "sheffer2": { "name_pl": "sheffer2", "title_pl": "najkrótsza baza z dwóch równań (Veroff)", "title_en": "the shortest 2-basis (Veroff)", "signature": {"nand": 2}, "functions": {"nand": 2}, "axioms": [("V", "nand(nand(x, y), nand(x, nand(y, z))) = x"), ("comm", "nand(x, y) = nand(y, x)")], "models": ["B2", "M1"], "lean_class": "Sheffer2Algebra", "challenges": ["nand(nand(x, x), nand(x, y)) = x", "nand(x, nand(x, x)) = nand(y, nand(y, y))", SH1], }, "weak": { "name_pl": "slaba", "title_pl": "dwa prawdziwe równania kreski, które NIE są bazą", "title_en": "two true stroke equations that are NOT a basis", "signature": {"nand": 2}, "functions": {"nand": 2}, "axioms": [("W", "nand(nand(x, x), nand(x, y)) = x"), ("comm", "nand(x, y) = nand(y, x)")], "models": ["B2", "M1"], "lean_class": "WeakSheffer", "challenges": ["nand(nand(x, x), nand(x, x)) = x", "nand(x, nand(x, x)) = nand(y, nand(y, y))", "nand(nand(x, y), nand(x, nand(y, z))) = x"], }, "median": { "name_pl": "mediana", "title_pl": "algebra mediany (aksjomaty Veroffa i McCune'a)", "title_en": "median algebra (Veroff and McCune's axioms)", "signature": {"med": 3}, "functions": {"med": 3}, "axioms": [("maj", "med(x, x, y) = x"), ("rot", "med(x, y, z) = med(z, x, y)"), ("swap", "med(x, y, z) = med(x, z, y)"), ("assoc", "med(med(x, w, y), w, z) = " "med(x, w, med(y, w, z))")], "models": ["B2", "C3"], "lean_class": "MedianAlgebra", "challenges": ["med(x, y, x) = x", "med(x, y, z) = med(y, x, z)", "med(med(x, y, z), u, v) = " "med(x, med(y, u, v), med(z, u, v))", "med(med(x, y, z), u, v) = " "med(x, y, med(z, u, v))"], }, "robbins": { "name_pl": "robbins", "title_pl": "algebra Robbinsa: A1, A2 i równanie Robbinsa", "title_en": "Robbins algebra: A1, A2 and the Robbins equation", "signature": {"+": 2, "n": 1}, "functions": {}, "axioms": ROBBINS, "models": ["B2"], "lean_class": "RobbinsAlgebra", "ac": ("A1", "A2"), "challenges": [], }, "robbins_ab": { "name_pl": "robbins_ab", "title_pl": "algebra Robbinsa z parą A + B = B (Mann, etap 3)", "title_en": "Robbins algebra with a pair A + B = B (Mann, stage 3)", "signature": {"+": 2, "n": 1, "A": 0, "B": 0, "c": 0, "d": 0}, "functions": {}, # c and d abbreviate long terms, as Lean's set c := ... with hc "axioms": ROBBINS + [("h", "A + B = B"), ("hc", "c = B + (n(A + n(B)) + n(A + n(B)))"), ("hd", "d = c + n(c + n(c))")], "models": ["B2ab"], "lean_class": "RobbinsPair", "ac": ("A1", "A2"), "challenges": [], }, "robbins_e": { "name_pl": "robbins_e", "title_pl": "algebra Robbinsa z elementem e + e = e (Mann, etap 4)", "title_en": "Robbins algebra with an element e + e = e " "(Mann, stage 4)", "signature": {"+": 2, "n": 1, "e": 0}, "functions": {}, "axioms": ROBBINS + [("h", "e + e = e")], "models": ["B2e"], "lean_class": "RobbinsIdempotent", "ac": ("A1", "A2"), "challenges": [], }, "robbins_cd": { "name_pl": "robbins_cd", "title_pl": "algebra Robbinsa z parą D + C = C (lemat 1 McCune'a)", "title_en": "Robbins algebra with a pair D + C = C " "(McCune's Lemma 1)", "signature": {"+": 2, "n": 1, "C": 0, "D": 0}, "functions": {}, "axioms": ROBBINS + [("h", "D + C = C")], "models": ["B2cd"], "lean_class": "RobbinsWinker", "ac": ("A1", "A2"), "challenges": [], }, "robbins_c": { "name_pl": "robbins_c", "title_pl": "algebra Robbinsa z elementem C + C = C " "(lemat 0 McCune'a)", "title_en": "Robbins algebra with an element C + C = C " "(McCune's Lemma 0)", "signature": {"+": 2, "n": 1, "C": 0}, "functions": {}, "axioms": ROBBINS + [("h", "C + C = C")], "models": ["B2c"], "lean_class": "RobbinsIdempotentC", "ac": ("A1", "A2"), "challenges": [], }, } _TOKEN = re.compile(r"\s*(?:(\d+)|([A-Za-z_][A-Za-z0-9_]*)|(.))") def parse_term(text, signature): """A term of a theory: + and * are infix (if in the signature), every other symbol of arity k >= 1 is applied as f(a1, ..., ak), constants are symbols of arity 0, other names are variables.""" toks = [m.group(1) or m.group(2) or m.group(3) for m in _TOKEN.finditer(text) if m.group(0).strip()] pos = 0 def peek(): return toks[pos] if pos < len(toks) else None def take(expected=None): nonlocal pos z = peek() if z is None or (expected and z != expected): raise SyntaxError(f"in {text!r}: expected " f"{expected or 'an expression'}, got {z!r}") pos += 1 return z def infix(op, lower): t = lower() while peek() == op and op in signature: take() t = (op, t, lower()) return t def sum_term(): return infix("+", product_term) def product_term(): return infix("*", atom) def atom(): z = take() if z == "(": t = sum_term() take(")") return t k = signature.get(z) if k == 0: return z if k and peek() == "(": take("(") args = [sum_term()] while peek() == ",": take() args.append(sum_term()) take(")") if len(args) != k: raise SyntaxError(f"in {text!r}: {z} takes {k} " f"arguments, got {len(args)}") return (z, *args) if z.isidentifier() and z not in signature: return z raise SyntaxError(f"in {text!r}: unexpected {z!r}") t = sum_term() if peek() is not None: raise SyntaxError(f"in {text!r}: unexpected {peek()!r} at the end") return t def parse_equation(text, signature): """'nand(x, y) = nand(y, x)' -> (left, right) in the signature.""" if text.count("=") != 1: raise SyntaxError(f"in {text!r}: expected one '='") left, right = text.split("=") return parse_term(left, signature), parse_term(right, signature) def axioms(theory): """The axioms of a theory as [(name, (left, right))].""" info = THEORIES[theory] return [(name, parse_equation(text, info["signature"])) for name, text in info["axioms"]] def models(theory): """The models of a theory: (model, axioms failing there).""" return [(m, failing_axioms(axioms(theory), m)) for m in THEORIES[theory]["models"]] def length(t): """Length of a term as in McCune et al.: symbols and variable occurrences, without parentheses (an equation adds 1 for '=').""" if isinstance(t, str): return 1 return 1 + sum(length(a) for a in t[1:]) def variables_of(t, result=None): """Variables of a term in the order of first occurrence.""" result = [] if result is None else result if isinstance(t, str): if t.isidentifier() and t not in result: result.append(t) else: for a in t[1:]: variables_of(a, result) return result def value(t, model, v): """The value of a term in a model under the valuation v.""" ops = MODELS[model]["ops"] if isinstance(t, str): return ops[t] if t in ops else v[t] return ops[t[0]](*(value(a, model, v) for a in t[1:])) def counterexample(l, r, model, names=None): """A valuation under which l ≠ r in the model, or None.""" ops = MODELS[model]["ops"] names = names or [v for v in variables_of(r, variables_of(l)) if v not in ops] for values in product(MODELS[model]["elements"], repeat=len(names)): v = dict(zip(names, values)) if value(l, model, v) != value(r, model, v): return v return None def failing_axioms(axioms, model): """Names of the axioms (name, (l, r)) that fail in the model.""" return [name for name, (l, r) in axioms if counterexample(l, r, model) is not None] def lean_term(t, prec=0): """A term in Lean notation, also with the symbols of other theories: nand x y, med x y z; + and * as operators, n as a function.""" if isinstance(t, str): return t f = t[0] if f == "+": s = f"{lean_term(t[1], 0)} + {lean_term(t[2], 1)}" return f"({s})" if prec >= 1 else s if f == "*": s = f"{lean_term(t[1], 1)} * {lean_term(t[2], 2)}" return f"({s})" if prec >= 2 else s s = " ".join([f] + [lean_term(a, 3) for a in t[1:]]) return f"({s})" if prec >= 3 else s def lean_class(theory, axioms): """The Lean class of a theory: its operations and axioms as fields.""" info = THEORIES[theory] extends = [c for s, c in (("+", "Add"), ("*", "Mul")) if s in info["signature"]] head = f"class {info['lean_class']} (α : Type)" if extends: head += " extends " + ", ".join(f"{c} α" for c in extends) lines = [head + " where"] for s, k in info["signature"].items(): if s.isidentifier(): lines.append(f" {s} : " + " → ".join(["α"] * (k + 1))) for name, (l, r) in axioms: vs = [v for v in variables_of(r, variables_of(l)) if v not in info["signature"]] quantifier = f"∀ {' '.join(vs)} : α, " if vs else "" lines.append(f" {name} : {quantifier}" f"{lean_term(l)} = {lean_term(r)}") if "ac" in info: # ac_nf and ac_rfl need these two instances c, comm, assoc = info["lean_class"], *info["ac"] lines += ["", f"instance {{α : Type}} [{c} α] : Std.Associative " f"(α := α) (· + ·) := ⟨{c}.{assoc}⟩", f"instance {{α : Type}} [{c} α] : Std.Commutative " f"(α := α) (· + ·) := ⟨{c}.{comm}⟩", "", "/-- The lab's ac_rfl: equal up to A1 and A2, also inside " "n(...). One ac_nf", "normalizes one level of n at a time, so it is repeated; " "done makes it", "fail when the sides are not equal. -/", "macro \"ac_rfl_deep\" : tactic =>", " `(tactic| ((iterate 10 (try ac_nf)) <;> done))"] return "\n".join(lines) + "\n"