Course page › Code of Lecture 3 › theories.py · 417 lines
raw file

Other axiom systems for the Boole Lab (bl theory) and finite models.

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

1"""Other axiom systems for the Boole Lab (bl theory) and finite models.
2
3The Boolean theory of the lecture (axioms H1–H8 and the library) is the
4default. Every other theory has its own signature and axioms, and the lab
5starts a fresh kernel for it:
6
7* dn1 — Boolean algebra from ONE equation in + and n (DN1: W. McCune,
8 R. Veroff, B. Fitelson, K. Harris, A. Feist, L. Wos, "Short Single
9 Axioms for Boolean Algebra", J. Automated Reasoning 29, 2002);
10* sheffer — Boolean algebra from ONE equation in the Sheffer stroke (Sh1,
11 the same paper: a shortest single axiom, length 15);
12* sheffer2 — R. Veroff's shortest 2-basis in the Sheffer stroke (J.
13 Automated Reasoning 31, 2003): (x | y) | (x | (y | z)) = x (his
14 equation 26a, here V) and commutativity;
15* weak — commutativity and (x | x) | (x | y) = x: Boolean equations
16 that are NOT a basis. The three-element model M1 from Veroff's paper
17 satisfies them but not x | (x | x) = y | (y | y); a Boolean algebra
18 has 2^k elements anyway;
19* median — median algebra: majority, two symmetries and associativity,
20 as in R. Veroff and W. McCune's notes "Median Algebra Proof" (2005).
21 Both distributive laws follow; a first-order proof of that was found
22 by Otter and Prover9 for a problem that came to them from D. Knuth;
23* robbins — Robbins algebra (A1, A2 and the Robbins equation R), and four
24 theories with constants and a hypothesis for the stages of its proof:
25 robbins_ab (A + B = B, Mann), robbins_e (e + e = e, Mann), robbins_cd
26 (D + C = C, McCune's Lemma 1) and robbins_c (C + C = C, his Lemma 0).
27 The variants of the proof and their scripts are in robbins_lab.py.
28
29Deriving the usual laws from these axioms is hard: the published
30derivations were found by automated provers (a 57-step Otter derivation
31of the Robbins basis from DN1, 66 steps from Sh1 to Sheffer's three
32axioms). The lab gives the setting and the models; derivations are the
33reader's challenge, and a model in which an equation fails shows at once
34that it does not follow from the axioms (soundness of the kernel).
35
36A model is a finite set with operation tables; `counterexample` looks for
37a valuation that falsifies an equation in a model. Terms are the kernel's
38tuples; a symbol of a theory, e.g. nand or med, is applied as
39('nand', a, b).
40"""
41
42import re
43from itertools import product
44
45M1_TABLE = ((2, 2, 2), # Veroff's M1: rows x, columns y, value x | y
46 (2, 1, 1),
47 (2, 1, 0))
48
49MODELS = {
50 "B2": {
51 "elements": (0, 1),
52 "ops": {"+": lambda a, b: a | b, "*": lambda a, b: a & b,
53 "n": lambda a: 1 - a, "0": 0, "1": 1,
54 "nand": lambda a, b: 1 - (a & b),
55 "med": lambda a, b, c: (a & b) | (a & c) | (b & c)},
56 "desc_pl": "dwuelementowa algebra Boole'a {0, 1}",
57 "desc_en": "the two-element Boolean algebra {0, 1}",
58 },
59 "M1": {
60 "elements": (0, 1, 2),
61 "ops": {"nand": lambda a, b: M1_TABLE[a][b]},
62 "desc_pl": "trzyelementowa tabelka kreski z pracy Veroffa",
63 "desc_en": "Veroff's three-element stroke table",
64 },
65 "C3": {
66 "elements": (0, 1, 2),
67 "ops": {"med": lambda a, b, c: sorted((a, b, c))[1]},
68 "desc_pl": "mediana na łańcuchu 0 < 1 < 2",
69 "desc_en": "the median on the chain 0 < 1 < 2",
70 },
71}
72
73for _model, _constants in (("B2ab", {"A": 0, "B": 1, "c": 1, "d": 1}),
74 ("B2e", {"e": 1}),
75 ("B2cd", {"C": 1, "D": 0}),
76 ("B2c", {"C": 1})):
77 MODELS[_model] = {
78 "elements": (0, 1),
79 "ops": {**MODELS["B2"]["ops"], **_constants},
80 "desc_pl": "algebra {0, 1}, " + ", ".join(
81 f"{k} = {v}" for k, v in _constants.items()),
82 "desc_en": "the algebra {0, 1}, " + ", ".join(
83 f"{k} = {v}" for k, v in _constants.items()),
84 }
85
86DN1 = "n(n(n(x + y) + z) + n(x + n(n(z) + n(z + u)))) = z"
87SH1 = "nand(nand(x, nand(nand(y, x), x)), nand(y, nand(z, x))) = y"
88
89ROBBINS = [("A1", "x + y = y + x"), ("A2", "x + y + z = x + (y + z)"),
90 ("R", "n(n(x + y) + n(x + n(y))) = x")]
91
92THEORIES = {
93 "dn1": {
94 "name_pl": "dn1",
95 "title_pl": "algebra Boole'a z jednego równania DN1 (+, n)",
96 "title_en": "Boolean algebra from the single equation DN1 (+, n)",
97 "signature": {"+": 2, "n": 1},
98 "functions": {},
99 "axioms": [("DN1", DN1)],
100 "models": ["B2"],
101 "lean_class": "DN1Algebra",
102 "challenges": ["x + y = y + x", "n(n(x)) = x",
103 "x + y + z = x + (y + z)",
104 "n(n(x + y) + n(x + n(y))) = x"],
105 },
106 "sheffer": {
107 "name_pl": "sheffer",
108 "title_pl": "algebra Boole'a z jednego równania Sh1 (kreska Sheffera)",
109 "title_en": "Boolean algebra from the single equation Sh1 "
110 "(the Sheffer stroke)",
111 "signature": {"nand": 2},
112 "functions": {"nand": 2},
113 "axioms": [("Sh1", SH1)],
114 "models": ["B2", "M1"],
115 "lean_class": "ShefferAlgebra",
116 "challenges": ["nand(x, y) = nand(y, x)",
117 "nand(nand(x, y), nand(x, nand(y, z))) = x"],
118 },
119 "sheffer2": {
120 "name_pl": "sheffer2",
121 "title_pl": "najkrótsza baza z dwóch równań (Veroff)",
122 "title_en": "the shortest 2-basis (Veroff)",
123 "signature": {"nand": 2},
124 "functions": {"nand": 2},
125 "axioms": [("V", "nand(nand(x, y), nand(x, nand(y, z))) = x"),
126 ("comm", "nand(x, y) = nand(y, x)")],
127 "models": ["B2", "M1"],
128 "lean_class": "Sheffer2Algebra",
129 "challenges": ["nand(nand(x, x), nand(x, y)) = x",
130 "nand(x, nand(x, x)) = nand(y, nand(y, y))", SH1],
131 },
132 "weak": {
133 "name_pl": "slaba",
134 "title_pl": "dwa prawdziwe równania kreski, które NIE są bazą",
135 "title_en": "two true stroke equations that are NOT a basis",
136 "signature": {"nand": 2},
137 "functions": {"nand": 2},
138 "axioms": [("W", "nand(nand(x, x), nand(x, y)) = x"),
139 ("comm", "nand(x, y) = nand(y, x)")],
140 "models": ["B2", "M1"],
141 "lean_class": "WeakSheffer",
142 "challenges": ["nand(nand(x, x), nand(x, x)) = x",
143 "nand(x, nand(x, x)) = nand(y, nand(y, y))",
144 "nand(nand(x, y), nand(x, nand(y, z))) = x"],
145 },
146 "median": {
147 "name_pl": "mediana",
148 "title_pl": "algebra mediany (aksjomaty Veroffa i McCune'a)",
149 "title_en": "median algebra (Veroff and McCune's axioms)",
150 "signature": {"med": 3},
151 "functions": {"med": 3},
152 "axioms": [("maj", "med(x, x, y) = x"),
153 ("rot", "med(x, y, z) = med(z, x, y)"),
154 ("swap", "med(x, y, z) = med(x, z, y)"),
155 ("assoc", "med(med(x, w, y), w, z) = "
156 "med(x, w, med(y, w, z))")],
157 "models": ["B2", "C3"],
158 "lean_class": "MedianAlgebra",
159 "challenges": ["med(x, y, x) = x", "med(x, y, z) = med(y, x, z)",
160 "med(med(x, y, z), u, v) = "
161 "med(x, med(y, u, v), med(z, u, v))",
162 "med(med(x, y, z), u, v) = "
163 "med(x, y, med(z, u, v))"],
164 },
165 "robbins": {
166 "name_pl": "robbins",
167 "title_pl": "algebra Robbinsa: A1, A2 i równanie Robbinsa",
168 "title_en": "Robbins algebra: A1, A2 and the Robbins equation",
169 "signature": {"+": 2, "n": 1},
170 "functions": {},
171 "axioms": ROBBINS,
172 "models": ["B2"],
173 "lean_class": "RobbinsAlgebra",
174 "ac": ("A1", "A2"),
175 "challenges": [],
176 },
177 "robbins_ab": {
178 "name_pl": "robbins_ab",
179 "title_pl": "algebra Robbinsa z parą A + B = B (Mann, etap 3)",
180 "title_en": "Robbins algebra with a pair A + B = B (Mann, stage 3)",
181 "signature": {"+": 2, "n": 1, "A": 0, "B": 0, "c": 0, "d": 0},
182 "functions": {},
183 # c and d abbreviate long terms, as Lean's set c := ... with hc
184 "axioms": ROBBINS + [("h", "A + B = B"),
185 ("hc", "c = B + (n(A + n(B)) + n(A + n(B)))"),
186 ("hd", "d = c + n(c + n(c))")],
187 "models": ["B2ab"],
188 "lean_class": "RobbinsPair",
189 "ac": ("A1", "A2"),
190 "challenges": [],
191 },
192 "robbins_e": {
193 "name_pl": "robbins_e",
194 "title_pl": "algebra Robbinsa z elementem e + e = e (Mann, etap 4)",
195 "title_en": "Robbins algebra with an element e + e = e "
196 "(Mann, stage 4)",
197 "signature": {"+": 2, "n": 1, "e": 0},
198 "functions": {},
199 "axioms": ROBBINS + [("h", "e + e = e")],
200 "models": ["B2e"],
201 "lean_class": "RobbinsIdempotent",
202 "ac": ("A1", "A2"),
203 "challenges": [],
204 },
205 "robbins_cd": {
206 "name_pl": "robbins_cd",
207 "title_pl": "algebra Robbinsa z parą D + C = C (lemat 1 McCune'a)",
208 "title_en": "Robbins algebra with a pair D + C = C "
209 "(McCune's Lemma 1)",
210 "signature": {"+": 2, "n": 1, "C": 0, "D": 0},
211 "functions": {},
212 "axioms": ROBBINS + [("h", "D + C = C")],
213 "models": ["B2cd"],
214 "lean_class": "RobbinsWinker",
215 "ac": ("A1", "A2"),
216 "challenges": [],
217 },
218 "robbins_c": {
219 "name_pl": "robbins_c",
220 "title_pl": "algebra Robbinsa z elementem C + C = C "
221 "(lemat 0 McCune'a)",
222 "title_en": "Robbins algebra with an element C + C = C "
223 "(McCune's Lemma 0)",
224 "signature": {"+": 2, "n": 1, "C": 0},
225 "functions": {},
226 "axioms": ROBBINS + [("h", "C + C = C")],
227 "models": ["B2c"],
228 "lean_class": "RobbinsIdempotentC",
229 "ac": ("A1", "A2"),
230 "challenges": [],
231 },
232}
233
234
235_TOKEN = re.compile(r"\s*(?:(\d+)|([A-Za-z_][A-Za-z0-9_]*)|(.))")
236
237
238def parse_term(text, signature):
239 """A term of a theory: + and * are infix (if in the signature), every
240 other symbol of arity k >= 1 is applied as f(a1, ..., ak), constants
241 are symbols of arity 0, other names are variables."""
242 toks = [m.group(1) or m.group(2) or m.group(3)
243 for m in _TOKEN.finditer(text) if m.group(0).strip()]
244 pos = 0
245
246 def peek():
247 return toks[pos] if pos < len(toks) else None
248
249 def take(expected=None):
250 nonlocal pos
251 z = peek()
252 if z is None or (expected and z != expected):
253 raise SyntaxError(f"in {text!r}: expected "
254 f"{expected or 'an expression'}, got {z!r}")
255 pos += 1
256 return z
257
258 def infix(op, lower):
259 t = lower()
260 while peek() == op and op in signature:
261 take()
262 t = (op, t, lower())
263 return t
264
265 def sum_term():
266 return infix("+", product_term)
267
268 def product_term():
269 return infix("*", atom)
270
271 def atom():
272 z = take()
273 if z == "(":
274 t = sum_term()
275 take(")")
276 return t
277 k = signature.get(z)
278 if k == 0:
279 return z
280 if k and peek() == "(":
281 take("(")
282 args = [sum_term()]
283 while peek() == ",":
284 take()
285 args.append(sum_term())
286 take(")")
287 if len(args) != k:
288 raise SyntaxError(f"in {text!r}: {z} takes {k} "
289 f"arguments, got {len(args)}")
290 return (z, *args)
291 if z.isidentifier() and z not in signature:
292 return z
293 raise SyntaxError(f"in {text!r}: unexpected {z!r}")
294
295 t = sum_term()
296 if peek() is not None:
297 raise SyntaxError(f"in {text!r}: unexpected {peek()!r} at the end")
298 return t
299
300
301def parse_equation(text, signature):
302 """'nand(x, y) = nand(y, x)' -> (left, right) in the signature."""
303 if text.count("=") != 1:
304 raise SyntaxError(f"in {text!r}: expected one '='")
305 left, right = text.split("=")
306 return parse_term(left, signature), parse_term(right, signature)
307
308
309def axioms(theory):
310 """The axioms of a theory as [(name, (left, right))]."""
311 info = THEORIES[theory]
312 return [(name, parse_equation(text, info["signature"]))
313 for name, text in info["axioms"]]
314
315
316def models(theory):
317 """The models of a theory: (model, axioms failing there)."""
318 return [(m, failing_axioms(axioms(theory), m))
319 for m in THEORIES[theory]["models"]]
320
321
322def length(t):
323 """Length of a term as in McCune et al.: symbols and variable
324 occurrences, without parentheses (an equation adds 1 for '=')."""
325 if isinstance(t, str):
326 return 1
327 return 1 + sum(length(a) for a in t[1:])
328
329
330def variables_of(t, result=None):
331 """Variables of a term in the order of first occurrence."""
332 result = [] if result is None else result
333 if isinstance(t, str):
334 if t.isidentifier() and t not in result:
335 result.append(t)
336 else:
337 for a in t[1:]:
338 variables_of(a, result)
339 return result
340
341
342def value(t, model, v):
343 """The value of a term in a model under the valuation v."""
344 ops = MODELS[model]["ops"]
345 if isinstance(t, str):
346 return ops[t] if t in ops else v[t]
347 return ops[t[0]](*(value(a, model, v) for a in t[1:]))
348
349
350def counterexample(l, r, model, names=None):
351 """A valuation under which l ≠ r in the model, or None."""
352 ops = MODELS[model]["ops"]
353 names = names or [v for v in variables_of(r, variables_of(l))
354 if v not in ops]
355 for values in product(MODELS[model]["elements"], repeat=len(names)):
356 v = dict(zip(names, values))
357 if value(l, model, v) != value(r, model, v):
358 return v
359 return None
360
361
362def failing_axioms(axioms, model):
363 """Names of the axioms (name, (l, r)) that fail in the model."""
364 return [name for name, (l, r) in axioms
365 if counterexample(l, r, model) is not None]
366
367
368def lean_term(t, prec=0):
369 """A term in Lean notation, also with the symbols of other theories:
370 nand x y, med x y z; + and * as operators, n as a function."""
371 if isinstance(t, str):
372 return t
373 f = t[0]
374 if f == "+":
375 s = f"{lean_term(t[1], 0)} + {lean_term(t[2], 1)}"
376 return f"({s})" if prec >= 1 else s
377 if f == "*":
378 s = f"{lean_term(t[1], 1)} * {lean_term(t[2], 2)}"
379 return f"({s})" if prec >= 2 else s
380 s = " ".join([f] + [lean_term(a, 3) for a in t[1:]])
381 return f"({s})" if prec >= 3 else s
382
383
384def lean_class(theory, axioms):
385 """The Lean class of a theory: its operations and axioms as fields."""
386 info = THEORIES[theory]
387 extends = [c for s, c in (("+", "Add"), ("*", "Mul"))
388 if s in info["signature"]]
389 head = f"class {info['lean_class']} (α : Type)"
390 if extends:
391 head += " extends " + ", ".join(f"{c} α" for c in extends)
392 lines = [head + " where"]
393 for s, k in info["signature"].items():
394 if s.isidentifier():
395 lines.append(f" {s} : " + " → ".join(["α"] * (k + 1)))
396 for name, (l, r) in axioms:
397 vs = [v for v in variables_of(r, variables_of(l))
398 if v not in info["signature"]]
399 quantifier = f"∀ {' '.join(vs)} : α, " if vs else ""
400 lines.append(f" {name} : {quantifier}"
401 f"{lean_term(l)} = {lean_term(r)}")
402 if "ac" in info: # ac_nf and ac_rfl need these two instances
403 c, comm, assoc = info["lean_class"], *info["ac"]
404 lines += ["",
405 f"instance {{α : Type}} [{c} α] : Std.Associative "
406 f"(α := α) (· + ·) := ⟨{c}.{assoc}⟩",
407 f"instance {{α : Type}} [{c} α] : Std.Commutative "
408 f"(α := α) (· + ·) := ⟨{c}.{comm}⟩",
409 "",
410 "/-- The lab's ac_rfl: equal up to A1 and A2, also inside "
411 "n(...). One ac_nf",
412 "normalizes one level of n at a time, so it is repeated; "
413 "done makes it",
414 "fail when the sides are not equal. -/",
415 "macro \"ac_rfl_deep\" : tactic =>",
416 " `(tactic| ((iterate 10 (try ac_nf)) <;> done))"]
417 return "\n".join(lines) + "\n"