{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "be23fc0f",
   "metadata": {},
   "source": [
    "# Heavy code: Lean, Isabelle, Mizar"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79b24164",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "# code: kernel/; obce/ — other people's proofs (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 / \"mathlib4\" / \"Robbins.lean\").is_file():\n",
    "    raise FileNotFoundError(\"no files in obce/: run .venv/bin/python obce/pobierz.py\")\n",
    "sys.setrecursionlimit(20000)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "062cf8d4",
   "metadata": {},
   "source": [
    "The Robbins theorem has been formalized in several proof assistants. Each formalization is several hundred lines of\n",
    "code — a decent piece of \"heavy\" code with proofs in Boolean algebra. The script `obce/pobierz.py` fetches four of them\n",
    "(in pinned versions, with SHA-256 checksums checked) together with the Otter and EQP proofs:\n",
    "\n",
    "| File | System | Author, year | Licence |\n",
    "|---|---|---|---|\n",
    "| `mathlib4/Robbins.lean` | Lean 4, mathlib | J. Tan, 2026 | Apache 2.0 |\n",
    "| `mathlib3/robbins.lean` | Lean 3, a mathlib branch | B. Mehta, 2021 | Apache 2.0 |\n",
    "| `afp/Robbins_Conjecture.thy` | Isabelle/HOL, Archive of Formal Proofs | M. Wampler-Doty, 2010 | BSD |\n",
    "| `mizar/robbins1.miz` | Mizar, Mizar Mathematical Library | A. Grabowski, 2001 | GPL 3 or CC BY-SA 3.0 |\n",
    "\n",
    "In this part we treat these files as data: we count what they are made of and look for places that the tactics of\n",
    "part 2 could compress.\n",
    "\n",
    "## Four proofs of one theorem\n",
    "\n",
    "First the size. We remove comments and descriptions, because they are not part of the proof; we count lines of code\n",
    "and theorems (lemmas, theorems, definitions):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "deb64437",
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "\n",
    "def without_comments(content, system):\n",
    "    \"\"\"The code without comments and description blocks.\"\"\"\n",
    "    if system == \"lean\":\n",
    "        content = re.sub(r\"/-.*?-/\", \"\", content, flags=re.S)\n",
    "        marker = \"--\"\n",
    "    elif system == \"isabelle\":\n",
    "        content = re.sub(r\"\\(\\*.*?\\*\\)\", \"\", content, flags=re.S)\n",
    "        content = re.sub(r\"\\b(?:text|section|subsection)\\s*\\\\<open>.*?\\\\<close>\", \"\", content, flags=re.S)\n",
    "        marker = None\n",
    "    else:\n",
    "        marker = \"::\"\n",
    "    return [w for w in content.splitlines() if w.strip() and not (marker and w.strip().startswith(marker))]\n",
    "\n",
    "FILES = {\n",
    "    \"Lean 4 (mathlib)\": (\"mathlib4/Robbins.lean\", \"lean\", r\"^(?:private )?(?:lemma|theorem|def|instance)\\b\"),\n",
    "    \"Lean 3\": (\"mathlib3/robbins.lean\", \"lean\", r\"^(?:private )?(?:lemma|theorem|def|instance)\\b\"),\n",
    "    \"Isabelle (AFP)\": (\"afp/Robbins_Conjecture.thy\", \"isabelle\", r\"^\\s*(?:lemma|theorem|corollary|definition)\\b\"),\n",
    "    \"Mizar (MML)\": (\"mizar/robbins1.miz\", \"mizar\", r\"^\\s*(?:theorem|definition)\\b\"),\n",
    "}\n",
    "loc = {}\n",
    "for name, (file, system, declaration) in FILES.items():\n",
    "    content = (FOREIGN / file).read_text()\n",
    "    loc[name] = \"\\n\".join(without_comments(content, system))\n",
    "    print(f\"{name:18} {len(content.splitlines()):5} lines, of these code {len(loc[name].splitlines()):5}, \"\n",
    "          f\"theorems and definitions {len(re.findall(declaration, content, re.M)):3}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ebcbbd56",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "_w = {n: len(k.splitlines()) for n, k in loc.items()}\n",
    "assert _w[\"Lean 4 (mathlib)\"] < _w[\"Lean 3\"] < _w[\"Isabelle (AFP)\"] < _w[\"Mizar (MML)\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6bedfcc1",
   "metadata": {},
   "source": [
    "The same theorem (the Isabelle and Lean 4 versions follow Mann's proof, the Mizar version — the work of McCune,\n",
    "Huntington and Dahn) takes from about three hundred to almost two thousand lines. The difference comes from the tools:\n",
    "what the system can do by itself and what has to be spelled out for it.\n",
    "\n",
    "## Lean 4: expansions written by hand, bookkeeping in `ac_rfl`\n",
    "\n",
    "The author of the mathlib version deliberately does not use the automation `grind` — in the description of the file\n",
    "he writes that he wants Mann's manipulations to stay visible, so he allows only `ac_rfl` for reordering summands and\n",
    "`lia` for comparing numbers. Let us count the tactics:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab9843a1",
   "metadata": {},
   "outputs": [],
   "source": [
    "lean4 = loc[\"Lean 4 (mathlib)\"]\n",
    "for tactic in [\"rw\", \"nth_rw\", \"rwa\", \"simp_rw\", \"ac_rfl\", \"conv_lhs\", \"conv_rhs\", \"lia\", \"grind\"]:\n",
    "    print(f\"{tactic:8} {len(re.findall(rf'\\b{tactic}\\b', lean4)):3}\")\n",
    "print(\"expansions ← robbins:\", len(re.findall(r\"← robbins\\b\", lean4)))\n",
    "content4 = (FOREIGN / \"mathlib4/Robbins.lean\").read_text()\n",
    "lemmas_44_49 = content4[content4.index(\"lemma mann_44\"):content4.index(\"def q : α\")]\n",
    "print(\"  of these in lemmas 44–49:\", len(re.findall(r\"← robbins\\b\", lemmas_44_49)))\n",
    "print(\"add_comm:\", len(re.findall(r\"\\badd_comm\\b\", lean4)), \" add_assoc:\", len(re.findall(r\"\\badd_assoc\\b\", lean4)),\n",
    "      \" show … by ac_rfl:\", len(re.findall(r\"show [^\\n]*by ac_rfl\", lean4)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "53495794",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert len(re.findall(r\"\\bac_rfl\\b\", lean4)) == 33\n",
    "assert len(re.findall(r\"← robbins\\b\", lean4)) == 25\n",
    "assert len(re.findall(r\"\\bgrind\\b\", lean4)) == 0\n",
    "assert len(re.findall(r\"← robbins\\b\", lemmas_44_49)) == 7\n",
    "assert (len(re.findall(r\"\\badd_comm\\b\", lean4)), len(re.findall(r\"\\badd_assoc\\b\", lean4)),\n",
    "        len(re.findall(r\"show [^\\n]*by ac_rfl\", lean4))) == (38, 28, 7)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4493df3c",
   "metadata": {},
   "source": [
    "Thirty-three times `ac_rfl` — this is the bookkeeping of associativity and commutativity, like our `ac`. Twenty-five\n",
    "times `← robbins` with arguments given by hand — these are the creative expansions that the tactic `auto` found in\n",
    "part 2. For lemmas 44–49 (seven of these expansions) `auto` reproduces them by itself; in the others the space of\n",
    "possibilities is too large and a hint pays off. On top of that come several dozen manual reorderings: `add_comm` and\n",
    "`add_assoc` inside `rw` and `show … by ac_rfl` before a rewrite — this is a job for the tactic `rw_ac`.\n",
    "\n",
    "## Isabelle: chains of reorderings and `metis`\n",
    "\n",
    "Wampler-Doty's version is written in the Isar language: a proof is a chain of equations `also … have … finally`, and\n",
    "every step is justified by the automation `metis` or `simp`. Some steps are pure reorderings of summands:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d4e86ec1",
   "metadata": {},
   "outputs": [],
   "source": [
    "isabelle = loc[\"Isabelle (AFP)\"]\n",
    "print(\"metis calls:\", len(re.findall(r\"\\bmetis\\b\", isabelle)))\n",
    "print(\"also steps:   \", len(re.findall(r\"\\balso\\b\", isabelle)))\n",
    "only_ac = re.findall(r\"also from (?:sup_assoc|sup_comm) have\", isabelle)\n",
    "print(\"also steps justified only by associativity or commutativity:\", len(only_ac))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca09088c",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert len(re.findall(r\"\\bmetis\\b\", isabelle)) == 110 and len(only_ac) == 30"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19d43183",
   "metadata": {},
   "source": [
    "Here is a fragment of such a chain (© M. Wampler-Doty, Archive of Formal Proofs, BSD licence; `\\<squnion>` is the sum,\n",
    "`-` the complement, `\\<dots>` — the right side of the previous step):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6cb56c22",
   "metadata": {},
   "outputs": [],
   "source": [
    "lines = (FOREIGN / \"afp/Robbins_Conjecture.thy\").read_text().splitlines()\n",
    "start = next(i for i, w in enumerate(lines) if \"also from sup_assoc have\" in w)\n",
    "print(\"\\n\".join(w[:110] for w in lines[start:start + 6]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f91eea2",
   "metadata": {},
   "source": [
    "Every `also from sup_assoc have` rewrites one bracket — exactly what our tactic `ac` does in one step of a script.\n",
    "Thirty such steps in chains of equations would disappear if the system had a tactic closing \"equal up to A1 and A2\"\n",
    "(Isabelle has such tools — simplification with AC rules — but the author did not use them here).\n",
    "\n",
    "On the other hand `metis` is the most radical solution: an automated prover (resolution) called as a tactic. It\n",
    "searches for a proof of a step from the given facts by itself, and turns the result into a proof checked by Isabelle's\n",
    "kernel. It is the same idea as our tactic `auto`, only much stronger. The script is short, but one cannot see *why*\n",
    "the step is true — and when the facts change, `metis` may stop finding the proof.\n",
    "\n",
    "## Mizar: everything explicit\n",
    "\n",
    "Mizar has no tactics in Lean's sense. A proof is a text in which every equational step `.=` has a justification\n",
    "`by …`, and the checker verifies that the step follows from the given facts by simple reasoning. Associativity and\n",
    "commutativity therefore have to be cited every time: in Mizar these are the definitions `LATTICES:def 5`\n",
    "(associativity of the sum) and `LATTICES:def 4` (commutativity)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fdf95147",
   "metadata": {},
   "outputs": [],
   "source": [
    "mizar = (FOREIGN / \"mizar/robbins1.miz\").read_text()\n",
    "equation_steps = sum(1 for w in mizar.splitlines() if w.strip().startswith(\".=\"))\n",
    "only_ac_lines = 0\n",
    "for w in mizar.splitlines():\n",
    "    m = re.search(r\"\\bby\\s+([^;]*?)\\s*;?\\s*$\", w)\n",
    "    if m and {x.strip() for x in m.group(1).split(\",\") if x.strip()} <= {\"LATTICES:def 4\", \"LATTICES:def 5\"}:\n",
    "        only_ac_lines += 1\n",
    "print(\"steps .= :\", equation_steps)\n",
    "print(\"lines justified only by associativity or commutativity:\", only_ac_lines)\n",
    "start = next(i for i, w in enumerate(mizar.splitlines()) if \".= ABC + (D + E + (F + GH)) by LATTICES:def 5\" in w)\n",
    "print(\"\\n\".join(mizar.splitlines()[start - 2:start + 5]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ebe052ce",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert equation_steps == 319 and only_ac_lines == 81"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "807be5d7",
   "metadata": {},
   "source": [
    "(Fragment of theorem 4.32 of `robbins1.miz`; © Association of Mizar Users, A. Grabowski, licence GPL 3 or CC BY-SA\n",
    "3.0.) Five steps in a row regroup the same sum of eight summands. In Mizar one compresses differently: instead of\n",
    "tactics there are abbreviations `set A = …` (visible above: `ABC`, `GH`) and auxiliary lemmas. In return the proof can\n",
    "be read without running anything — that is why it is the longest.\n",
    "\n",
    "## Machine proofs\n",
    "\n",
    "Proofs found by programs are measured in inference steps. Let us count them in the downloaded files, together with the\n",
    "proof by Robert Veroff (2002) — one continuous derivation of Huntington's equation in Otter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c466ed0",
   "metadata": {},
   "outputs": [],
   "source": [
    "def otter_length(file):\n",
    "    return int(re.search(r\"Length of proof is (\\d+)\", (FOREIGN / file).read_text()).group(1))\n",
    "\n",
    "def eqp_steps(file):\n",
    "    lines = re.findall(r\"^\\d+ \\(wt=\\d+\\) \\[(.*?)\\] (.*)\\.$\", (FOREIGN / file).read_text(), re.M)\n",
    "    return sum(1 for justification, eq_text in lines if justification and not eq_text.startswith(\"-(\"))\n",
    "\n",
    "machine = {\n",
    "    \"EQP, condition 1 (m5-50)\": eqp_steps(\"mccune/eqp-lemma3.proof.txt\"),\n",
    "    \"EQP, Huntington's equation directly (m5-50)\": eqp_steps(\"mccune/eqp-hunt.proof.txt\"),\n",
    "    \"Otter, condition 1\": otter_length(\"mccune/otter-lemma3.proof.txt\"),\n",
    "    \"Otter (Veroff 2002), Huntington's equation directly\": otter_length(\"veroff/r2h.pf\"),\n",
    "}\n",
    "for verdict, n in machine.items():\n",
    "    print(f\"{verdict:50} {n:4} steps\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bffe6b99",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert list(machine.values()) == [12, 86, 40, 142]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b35a76e",
   "metadata": {},
   "source": [
    "Again: EQP has associativity and commutativity built in, Otter does not — and the Otter proof is longer, although it\n",
    "proves the same.\n",
    "\n",
    "Other theorems about Boolean algebras have long machine proofs too. In January 2025 Stephen Wolfram described (*Who\n",
    "Can Understand the Proof? A Window on Formalized Mathematics*) a proof of his single axiom for Boolean algebra with the\n",
    "NAND operation, found by a program: 307 steps, of which the derivation of commutativity alone takes 104. Of the 101\n",
    "lemmas of this proof, 47 come from substitution and 54 from \"bisubstitution\" (critical pairs) — and none of them has a\n",
    "name that would tell a human anything. It is the opposite end from mathlib: a complete proof, but without a structure\n",
    "one can understand.\n",
    "\n",
    "## What would compress it\n",
    "\n",
    "Let us collect what the numbers showed:\n",
    "\n",
    "| Repeated pattern | Where | How many | The tactic that swallows it |\n",
    "|---|---|---|---|\n",
    "| reordering summands | Isabelle (`also from sup_assoc`), Mizar (`by LATTICES:def 5`), Otter | 30, 81, 28 of 41 | `ac` (part 2) |\n",
    "| reordering before `rw` | Lean (`add_comm`, `add_assoc`, `show … by ac_rfl`) | 38, 28, 7 | `rw_ac` |\n",
    "| creative expansion with the Robbins equation | Lean (`← robbins x y`) | 25 | `auto` — for 7 of them |\n",
    "| the same proof for different $k$ | Lean (`Nat.le_induction`), Isabelle (`induct`) | lemma 36 | a loop (unrolled induction) |\n",
    "| long witness terms | all | $e$ has 329 symbols | abbreviations: `set`, `obtain`, sections |\n",
    "\n",
    "The conclusion is more general than the Robbins problem. **A good formal proof is a compressed proof**: repeated\n",
    "fragments have been turned into lemmas, bookkeeping into tactics, and long terms into abbreviations. When compression\n",
    "is missing (Mizar, Otter), the proof is long, but every step can be seen. When automation does all the work (`metis`),\n",
    "the script is short, but one cannot see why a step holds. And a machine proof without named lemmas (Wolfram) can be long\n",
    "and incomprehensible at the same time. The art is to compress the bookkeeping and to leave the ideas in sight.\n",
    "\n",
    "## References and places worth a visit\n",
    "\n",
    "* J. Tan, [`Archive/Robbins.lean`](https://github.com/leanprover-community/mathlib4/blob/master/Archive/Robbins.lean)\n",
    "  (mathlib, 2026) and B. Mehta, the Lean 3 version in a mathlib branch (2021).\n",
    "* M. Wampler-Doty, [*A Complete Proof of the Robbins Conjecture*](https://www.isa-afp.org/entries/Robbins-Conjecture.html),\n",
    "  Archive of Formal Proofs (2010).\n",
    "* A. Grabowski, [*Robbins Algebras vs. Boolean Algebras*](https://fm.mizar.org/2001-9/pdf9-4/robbins1.pdf),\n",
    "  Formalized Mathematics 9(4), 681–690 (2001); in the MML as\n",
    "  [ROBBINS1](https://mizar.uwb.edu.pl/version/current/html/robbins1.html).\n",
    "* R. Veroff, [a page on the Robbins problem](https://www.cs.unm.edu/~veroff/ROBBINS/) with a derivation of\n",
    "  Huntington's equation in Otter.\n",
    "* S. Wolfram, [*Who Can Understand the Proof? A Window on Formalized Mathematics*](https://writings.stephenwolfram.com/2025/01/who-can-understand-the-proof-a-window-on-formalized-mathematics/)\n",
    "  (9 January 2025).\n",
    "* F. Wiedijk, [*The De Bruijn Factor*](https://www.cs.ru.nl/~freek/factor/) (TPHOLs 2000) — how to measure how many\n",
    "  times longer a formal proof is than the mathematical text (it comes out at about four)."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
