{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "428db1f5",
   "metadata": {},
   "source": [
    "# The shortest proof: EQP's twelve equations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77abaaba",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "# code: kernel/ (the English version);\n",
    "# obce/ — other people's proofs, fetched by obce/pobierz.py\n",
    "for directory in [Path.cwd(), *Path.cwd().parents]:\n",
    "    if (directory / \"kernel\" / \"robbins.py\").is_file():\n",
    "        ROOT = directory\n",
    "        break\n",
    "sys.path.insert(0, str(ROOT / \"kernel\"))\n",
    "sys.path.append(str(ROOT / \"kernel\"))\n",
    "FOREIGN = ROOT / \"obce\"\n",
    "if not (FOREIGN / \"mccune\" / \"eqp-lemma3.proof.txt\").is_file():\n",
    "    raise FileNotFoundError(\"no files in obce/: run .venv/bin/python obce/pobierz.py\")\n",
    "sys.setrecursionlimit(20000)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6073af66",
   "metadata": {},
   "source": [
    "In {ref}`w03-robbins` we told the story of the Robbins problem: the three equations\n",
    "\n",
    "$$\n",
    "x + y = y + x, \\qquad x + y + z = x + (y + z), \\qquad n(n(x + y) + n(x + n(y))) = x\n",
    "$$\n",
    "\n",
    "(commutativity A1, associativity A2 and the Robbins equation R) are enough to build a Boolean algebra. The proof was\n",
    "found in 1996 by William McCune's program EQP. Now we look at the proof itself as an object: how many steps it has,\n",
    "what it is made of, and how to write it down compactly, so that our kernel from lecture 3 checks every detail of it.\n",
    "\n",
    "## How many steps does a proof have?\n",
    "\n",
    "The question \"how many steps\" has no single answer: everything depends on what counts as a step. After the first\n",
    "success McCune came back to the problem and ran several new searches. In the paper *Solution of the Robbins Problem*\n",
    "(Journal of Automated Reasoning, 1997, Table I) he gives the lengths of the proofs found, in EQP steps. One EQP step\n",
    "is one new equation: one equation substituted into another (paramodulation) together with simplifications.\n",
    "\n",
    "| Search | Condition 2 (Winker) | Condition 1 (Winker) | Huntington's equation |\n",
    "|---|---|---|---|\n",
    "| m5-70 (October 1996, the first proof) | 15 steps, 7.85 days | — | — |\n",
    "| m5-60a, m5-60b | 15 | 17 | 194 |\n",
    "| m5-50, m5-50b | **8** | **12** | 86 |\n",
    "\n",
    "Winker's conditions are $\\exists C, D\\colon n(C + D) = n(C)$ (condition 2) and $\\exists C, D\\colon C + D = C$\n",
    "(condition 1). Each of them suffices for a Robbins algebra to be Boolean, but that part — Winker's lemmas — still\n",
    "has to be proved separately. McCune writes that in all searches the first proof found and the shortest one were of\n",
    "condition 2; condition 1 appeared a few steps later. We know of no shorter published computer proof, so we say it\n",
    "carefully: this is **the shortest published proof known to us**.\n",
    "\n",
    "McCune published the files with the EQP proofs on his web page. The script `obce/pobierz.py` fetches them together\n",
    "with other proofs of this theorem (licences and sources are in `obce/ZRODLO.md`). The files have no licence, so we do\n",
    "not copy them here — we only read them and count. A line of an EQP proof has a number, a weight, a justification and\n",
    "an equation; the justification `para(a,b)` means \"substitute equation no. a into equation no. b\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56ccef10",
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "\n",
    "def eqp_parents(justification):\n",
    "    \"\"\"Numbers of the equations a new one comes from: para(a,b), demod([c,d]), back_demod(e).\"\"\"\n",
    "    numbers = []\n",
    "    for a, b in re.findall(r\"para\\((\\d+),(\\d+)\\)\", justification):\n",
    "        numbers += [int(a), int(b)]\n",
    "    for listed in re.findall(r\"demod\\(\\[([\\d,]+)\\]\\)\", justification):\n",
    "        numbers += [int(x) for x in listed.split(\",\")]\n",
    "    numbers += [int(x) for x in re.findall(r\"back_demod\\((\\d+)\\)\", justification)]\n",
    "    return numbers\n",
    "\n",
    "\n",
    "def read_eqp(file):\n",
    "    \"\"\"Lines of an EQP proof: number -> (numbers of the parents, equation as text, derived or not).\"\"\"\n",
    "    lines = {}\n",
    "    for row in (FOREIGN / \"mccune\" / file).read_text().splitlines():\n",
    "        m = re.match(r\"(\\d+) \\(wt=\\d+\\) \\[(.*?)\\] (.*)\\.$\", row.strip())\n",
    "        if m:\n",
    "            justification = m.group(2)\n",
    "            lines[int(m.group(1))] = (eqp_parents(justification), m.group(3), bool(justification))\n",
    "    return lines\n",
    "\n",
    "\n",
    "proofs = {\"October 1996 (condition 2)\": \"eqp-theorem.proof.txt\",\n",
    "          \"November 1996, m5-50 (condition 1)\": \"eqp-lemma3.proof.txt\",\n",
    "          \"November 1996, m5-50 (Huntington's equation)\": \"eqp-hunt.proof.txt\"}\n",
    "eqp_steps = {}\n",
    "for verdict, file in proofs.items():\n",
    "    lines = read_eqp(file)\n",
    "    eqp_steps[file] = [n for n, (_, _, derived) in lines.items() if derived]\n",
    "    print(f\"{verdict}: {len(eqp_steps[file])} derived equations\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dfe8c7c9",
   "metadata": {},
   "source": [
    "The numbers agree with the table: 15 steps in the first proof and 12 in the proof of condition 1. In the proof of\n",
    "Huntington's equation one of the derived equations is the negation of the goal, which EQP drives to a contradiction —\n",
    "so there are 86 equations, as in the table."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "525497b5",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert len(eqp_steps[\"eqp-theorem.proof.txt\"]) == 15\n",
    "assert len(eqp_steps[\"eqp-lemma3.proof.txt\"]) == 12\n",
    "_hunt = read_eqp(\"eqp-hunt.proof.txt\")\n",
    "assert len(eqp_steps[\"eqp-hunt.proof.txt\"]) == 87\n",
    "assert sum(1 for n in eqp_steps[\"eqp-hunt.proof.txt\"] if not _hunt[n][1].startswith(\"-(\")) == 86"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c456b491",
   "metadata": {},
   "source": [
    "Where do the \"8 steps\" for condition 2 come from? McCune notes that one of the equations in the proof of\n",
    "condition 1 already satisfies condition 2. Let us count how many derived equations it uses — directly or through\n",
    "other equations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "438baafc",
   "metadata": {},
   "outputs": [],
   "source": [
    "lines = read_eqp(\"eqp-lemma3.proof.txt\")\n",
    "\n",
    "def ancestors(number):\n",
    "    \"\"\"Derived equations that equation `number` uses (itself included).\"\"\"\n",
    "    parents, _, derived = lines[number]\n",
    "    result = {number} if derived else set()\n",
    "    for r in parents:\n",
    "        result |= ancestors(r)\n",
    "    return result\n",
    "\n",
    "print(sorted(ancestors(8855)), len(ancestors(8855)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b65bc58",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert len(ancestors(8855)) == 8"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f525aed",
   "metadata": {},
   "source": [
    "Eight equations, the last of which, no. 8855, is $n(q + 5x) = n(3x)$ for $q = n(n(3x) + x)$: condition 2 for $C = 3x$\n",
    "and $D = q + 2x$. Four more equations lead to condition 1.\n",
    "\n",
    "## The twelve equations are Mann's lemmas\n",
    "\n",
    "EQP proofs are hard to read: the program itself chooses what to combine with what, and it applies associativity and\n",
    "commutativity invisibly. Allen L. Mann rewrote McCune's proof for people (*A Complete Proof of the Robbins\n",
    "Conjecture*, 2003). His lemmas 44–54 then went into the formalizations in Isabelle (M. Wampler-Doty, 2010) and in\n",
    "Lean's mathlib library (J. Tan, 2026, file `Archive/Robbins.lean`, Apache 2.0 licence). The same statements, in our\n",
    "notation ($n$ is the complement, `a + a + a` is $3a$), are in the module `robbins_proof`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6041b8da",
   "metadata": {},
   "outputs": [],
   "source": [
    "from robbins_proof import STATEMENTS\n",
    "\n",
    "for name, formula in STATEMENTS.items():\n",
    "    print(f\"{name:8} {formula}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "833d6656",
   "metadata": {},
   "source": [
    "Let us check that these are exactly the twelve equations from the EQP file. We count two equations as the same if,\n",
    "after renaming the variables (EQP writes $x, y, z, u$, Mann $a, b, c, d$), they have the same normal form with respect\n",
    "to A1 and A2 — the normal form is the subject of the next part; for now it is enough that the function `normal` sorts\n",
    "the summands of sums."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a72aaf78",
   "metadata": {},
   "outputs": [],
   "source": [
    "from itertools import permutations\n",
    "from kernel import subst, term_vars\n",
    "from syntax import term, equation\n",
    "from ac import normal\n",
    "\n",
    "def te_same(r1, r2):\n",
    "    \"\"\"The same equations up to the names of variables, A1 and A2 (also with the sides swapped).\"\"\"\n",
    "    (l1, p1), (l2, p2) = r1, r2\n",
    "    z1 = sorted(term_vars(l1) | term_vars(p1))\n",
    "    z2 = sorted(term_vars(l2) | term_vars(p2))\n",
    "    if len(z1) != len(z2):\n",
    "        return False\n",
    "    goal = (normal(l2), normal(p2))\n",
    "    for z in permutations(z2):\n",
    "        s = dict(zip(z1, z))\n",
    "        pair = (normal(subst(l1, s)), normal(subst(p1, s)))\n",
    "        if pair == goal or pair[::-1] == goal:\n",
    "            return True\n",
    "    return False\n",
    "\n",
    "counterparts = {}\n",
    "for number in eqp_steps[\"eqp-lemma3.proof.txt\"]:\n",
    "    r_eqp = equation(lines[number][1])\n",
    "    names = [name for name, formula in STATEMENTS.items() if te_same(r_eqp, equation(formula))]\n",
    "    counterparts[number] = names\n",
    "    print(number, \"->\", \", \".join(names) or \"?\", \"  parents:\", lines[number][0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e9ede334",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert [v for v in counterparts.values()] == [[n] for n in STATEMENTS]\n",
    "assert counterparts[8855] == [\"mann_51\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9297c3f",
   "metadata": {},
   "source": [
    "Every EQP equation has its lemma, and the order agrees: Mann's proof is EQP's proof written out as lemmas. EQP writes\n",
    "the Robbins equation as $n(n(n(x) + y) + n(x + y)) = y$ — our R after swapping $x \\leftrightarrow y$ and reordering\n",
    "the summands:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50e1488e",
   "metadata": {},
   "outputs": [],
   "source": [
    "r_eqp = equation(lines[7][1])\n",
    "print(lines[7][1], \"  the same as R:\", te_same(r_eqp, equation(\"n(n(x + y) + n(x + n(y))) = x\")))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc02bee8",
   "metadata": {},
   "source": [
    "## An EQP step in our kernel\n",
    "\n",
    "The first equation, `para(7,7)`, is the Robbins equation substituted into itself. In mathlib the same lemma has\n",
    "a proof of three Lean tactics:\n",
    "\n",
    "```text\n",
    "lemma mann_44 : -(-(-(a + b) + -a + b) + b) = -(a + b) := by\n",
    "  nth_rw 2 [← robbins (-(a + b)) (-a + b)]\n",
    "  nth_rw 3 [← robbins b a]\n",
    "  congr 2 <;> ac_rfl\n",
    "```\n",
    "\n",
    "(Excerpt from `Archive/Robbins.lean`, © 2026 Jeremy Tan, Apache 2.0 licence.) The first two lines are the creative\n",
    "part: twice we \"expand\" an expression with the Robbins equation from right to left — we replace $x$ by\n",
    "$n(n(x + y) + n(x + n(y)))$ — and we have to choose well where and with which $y$. The third line is bookkeeping:\n",
    "both sides are already equal up to the order of summands, and `ac_rfl` checks it. Our module `robbins` has the same\n",
    "tactics — except that each of them leaves behind an ordinary proof made of the five kernel rules:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a70b8c50",
   "metadata": {},
   "outputs": [],
   "source": [
    "from robbins import theory, Goal, nodes\n",
    "from syntax import show_equation\n",
    "\n",
    "K = theory()\n",
    "g = Goal(K, STATEMENTS[\"mann_44\"])\n",
    "g.nth_rw(2, \"← R (n(a + b)) (n(a) + b)\")\n",
    "print(\"after the 1st expansion:\", g)\n",
    "g.nth_rw(3, \"← R b a\")\n",
    "print(\"after the 2nd expansion:\", g)\n",
    "g.ac()\n",
    "proof = g.qed()\n",
    "print(\"the kernel accepts:\", show_equation(K.conclusion(proof)), \"| proof nodes:\", nodes(proof))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "229842fb",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert nodes(proof) == 48"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71f9163d",
   "metadata": {},
   "source": [
    "The script has three tactics, and the proof the kernel gets has 48 nodes (rule applications). Most of them are the\n",
    "work of `ac`: swaps of neighbouring summands, each written as an `Inst` of axiom A1 or A2, put into the context by\n",
    "`CongrArg` and joined by `Trans`. In EQP this bookkeeping is not visible at all — the program has associativity and\n",
    "commutativity built into unification.\n",
    "\n",
    "The whole stage 1 of the proof — twelve lemmas, from `mann_44` to Winker's condition — is written in the function\n",
    "`winker_by_hand`. Each lemma is a few tactic calls, just as in mathlib:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "227c911d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from robbins_proof import winker_by_hand\n",
    "import inspect\n",
    "\n",
    "print(inspect.getsource(winker_by_hand))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0dcbce91",
   "metadata": {},
   "source": [
    "Running it adds twelve theorems to the kernel. For each we show how many nodes the proof checked by the kernel has\n",
    "(a use of an earlier lemma counts once) and which assumptions it uses."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f12b6dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "from robbins import lemma\n",
    "import time\n",
    "\n",
    "K = theory()\n",
    "start = time.perf_counter()\n",
    "winker_by_hand(K)\n",
    "elapsed = time.perf_counter() - start\n",
    "for name in STATEMENTS:\n",
    "    print(f\"{name:8} {nodes(K.proofs[name]):5} nodes   assumptions: {sorted(K.assumptions[name])}\")\n",
    "sum_term = sum(nodes(K.proofs[n]) for n in STATEMENTS)\n",
    "print(f\"together {sum_term} nodes, {elapsed:.2f} s\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7f27c707",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert all(K.assumptions[n] == {\"A1\", \"A2\", \"R\"} for n in STATEMENTS)\n",
    "assert 1500 < sum_term < 3000\n",
    "WINKER_NODES = sum_term"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c561520",
   "metadata": {},
   "source": [
    "EQP's twelve equations are twelve theorems of our kernel, each checked from the axioms A1, A2 and R only. The last\n",
    "one, `winker`, is condition 1: $q + 2a = 2a$, that is $C + D = C$ for $C = 2a$ and $D = q = n(n(3a) + a)$.\n",
    "\n",
    "## The same proof without built-in associativity\n",
    "\n",
    "EQP could not write its proof in a form another program could check. So McCune reproduced the proofs with the\n",
    "program Otter, in which associativity and commutativity are ordinary axioms. Otter prints the length of the proof at\n",
    "the top of the file; let us also count how many steps use the commutativity and associativity axioms directly (in\n",
    "Otter's files these are the input lines `x+y=y+x` and `(x+y)+z=x+y+z`):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1597401d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def read_otter(file):\n",
    "    \"\"\"(length according to Otter, steps with a justification, steps that use A1 or A2).\"\"\"\n",
    "    content = (FOREIGN / \"mccune\" / file).read_text()\n",
    "    length = int(re.search(r\"Length of proof is (\\d+)\", content).group(1))\n",
    "    lines = re.findall(r\"^(\\d+) \\[(.*?)\\] (.*)\\.$\", content, re.M)\n",
    "    ac = {int(n) for n, uz, r in lines if not uz and r.replace(\" \", \"\") in (\"x+y=y+x\", \"(x+y)+z=x+y+z\")}\n",
    "    steps = [uz for n, uz, r in lines if uz]\n",
    "    z_ac = [uz for uz in steps\n",
    "            if ac & {int(x.split(\".\")[0]) for x in uz.split(\",\") if x[:1].isdigit()}]\n",
    "    return length, len(steps), len(z_ac)\n",
    "\n",
    "\n",
    "for file in [\"otter-lemma3.proof.txt\", \"otter-theorem.proof.txt\"]:\n",
    "    length, steps, z_ac = read_otter(file)\n",
    "    print(f\"{file}: length {length}, steps with a justification {steps}, of these with A1 or A2: {z_ac}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "642d502c",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "_d3 = read_otter(\"otter-lemma3.proof.txt\")\n",
    "_dt = read_otter(\"otter-theorem.proof.txt\")\n",
    "assert (_d3[0], _dt[0]) == (40, 34)\n",
    "assert _d3[1:] == (41, 28)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98625048",
   "metadata": {},
   "source": [
    "The same condition 1 that EQP proves in 12 steps takes Otter 40, and 28 of the 41 lines with a justification use\n",
    "commutativity or associativity directly. The difference is exactly the bookkeeping: in EQP it sits in the unification\n",
    "algorithm, in Otter — in explicit steps, and with us — in the tactic `ac`.\n",
    "\n",
    "This is the first lesson about compression. **The shortest proof is short because the prover has well-chosen tools.**\n",
    "EQP had a built-in \"tactic\" for associativity and commutativity, so its proof consists of creative steps only. Our\n",
    "kernel has no such tactic and does not need one: it is enough that the script has it, and the kernel checks\n",
    "everything this tactic wrote. In the next part we will see how to build such a tactic.\n",
    "\n",
    "## References and places worth a visit\n",
    "\n",
    "* W. McCune, *Solution of the Robbins Problem*, Journal of Automated Reasoning 19(3), 263–276 (1997),\n",
    "  [DOI](https://doi.org/10.1023/A:1005843212881); Table I in §5. The EQP and Otter proofs:\n",
    "  [McCune's page](https://www.cs.unm.edu/~mccune/papers/robbins/) and [the paper's page](https://www.cs.unm.edu/~mccune/papers/robbins/jar.html).\n",
    "* A. L. Mann, *A Complete Proof of the Robbins Conjecture* (2003) — the original disappeared from the author's page;\n",
    "  [copy in the Internet Archive](http://web.archive.org/web/20241113144212/https://math.colgate.edu/~amann/MA/robbins_complete.pdf).\n",
    "* J. Tan, [`Archive/Robbins.lean`](https://github.com/leanprover-community/mathlib4/blob/master/Archive/Robbins.lean)\n",
    "  in the mathlib library (2026, Apache 2.0) — a formalization in Lean 4, following the Isabelle version of\n",
    "  [M. Wampler-Doty](https://www.isa-afp.org/entries/Robbins-Conjecture.html) (2010, BSD licence).\n",
    "* S. Winker, *Robbins algebra: Conditions that make a near-Boolean algebra Boolean*, Journal of Automated Reasoning\n",
    "  6(4), 465–489 (1990), [DOI](https://doi.org/10.1007/BF00244359)."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
