{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "189c5f46",
   "metadata": {},
   "source": [
    "# The whole proof in tactics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5cd28f8c",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "# code: kernel/ (the English version, with the Boole Lab)\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",
    "sys.setrecursionlimit(20000)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dd7588b5",
   "metadata": {},
   "source": [
    "Winker's condition is only half of the way. To derive from the three laws A1, A2, R Huntington's equation\n",
    "\n",
    "$$\n",
    "n(n(x) + n(y)) + n(n(x) + y) = x,\n",
    "$$\n",
    "\n",
    "and with it a Boolean algebra, three more stages are needed. In this part we put the whole proof together —\n",
    "following Mann's plan and the formalization in mathlib — and measure how much it weighs.\n",
    "\n",
    "| Stage | What it proves | In mathlib | Here |\n",
    "|---|---|---|---|\n",
    "| 1 | Winker's condition $q + 2a = 2a$ | `mann_44` … `winker` | 12 theorems, `winker_by_hand` |\n",
    "| 2 | lemmas with hypotheses | `mann_33` … `mann_40` | `hypothetical_lemmas`: class `Hypothetical` |\n",
    "| 3 | from $A + B = B$ an element $e$ with $e + e = e$ | `exists_idempotent` | `idempotent_section`: class `Section` |\n",
    "| 4 | from $e + e = e$ a zero, $n(n(x)) = x$, Huntington's equation | `exists_zero`, `neg_neg`, `huntington` | `huntington_section` |\n",
    "| 5 | the sections used for the real terms | — | `robbins_theorem` |\n",
    "\n",
    "Stages 2–5 need two ideas that were not in part 1: lemmas with hypotheses and abbreviations for long terms. Both are\n",
    "forms of compression.\n",
    "\n",
    "## Lemmas with hypotheses\n",
    "\n",
    "Mann's lemma 35 says: *if* $n(a + n(b)) = c$, *then* $n(n(a + b) + c) = a$. In Lean this is a function: it takes a\n",
    "proof of the hypothesis and returns a proof of the conclusion. Our kernel has no implication — it knows only equations\n",
    "with variables. We manage like this:\n",
    "\n",
    "1. we prove the lemma **once**, in a separate kernel in which $a, b, c$ are constants and the hypothesis is an axiom\n",
    "   `h1`;\n",
    "2. to **use** it for concrete terms and a proof of the hypothesis, we substitute them into that one proof: the\n",
    "   constants are replaced by terms, and every use of the axiom `h1` — by the proof of the hypothesis (the function\n",
    "   `transport`);\n",
    "3. the kernel checks the result from scratch, like any other proof."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cefe8f28",
   "metadata": {},
   "outputs": [],
   "source": [
    "from robbins import theory, Hypothetical, Goal, nodes\n",
    "from robbins_proof import winker_by_hand\n",
    "from syntax import show_equation\n",
    "\n",
    "K = theory()\n",
    "M35 = Hypothetical(K, \"mann_35\", \"abc\", [\"n(a + n(b)) = c\"], \"n(n(a + b) + c) = a\",\n",
    "                   lambda g: (g.rw(\"← h1\"), g.rw(\"R a b\")))\n",
    "print(\"proof with constants — nodes:\", nodes(M35.proof))\n",
    "\n",
    "# use: a := x + y, b := y, c := n(x + y + n(y)); the hypothesis is then plain reflexivity\n",
    "hypothesis_proof = Goal(K, \"n(x + y + n(y)) = n(x + y + n(y))\").rfl().qed()\n",
    "proof = M35({\"a\": \"x + y\", \"b\": \"y\", \"c\": \"n(x + y + n(y))\"}, hypothesis_proof)\n",
    "print(\"kernel:\", show_equation(K.conclusion(proof)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "840a4bde",
   "metadata": {},
   "source": [
    "Mathlib proves lemma 36 by induction on $k$ (for every $k \\ge 1$). Our kernel knows no induction, but further on only\n",
    "$k = 1, 2, 3$ are needed — so we unroll the induction: the proof for $k$ uses the proof for $k - 1$ as the hypothesis\n",
    "of lemma 35. This is an ordinary loop in Python:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1eab9ba3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import inspect\n",
    "from robbins_proof import hypothetical_lemmas\n",
    "\n",
    "source = inspect.getsource(hypothetical_lemmas)\n",
    "print(source[source.index(\"    def lemma_36\"):source.index(\"    c = \")])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17db9667",
   "metadata": {},
   "source": [
    "Such a lemma is a compressed fragment of a proof: it stands in the script once, and in the proof object it appears as\n",
    "many times as it is used. Lean pays less: its kernel knows implication, so a lemma with hypotheses is a constant that\n",
    "is checked once, and every use is one application of a function. Our kernel checks every copy separately.\n",
    "\n",
    "## Abbreviations for long terms: sections\n",
    "\n",
    "In stage 3 the pair $A + B = B$ gives an element $e$ with $e + e = e$:\n",
    "\n",
    "$$\n",
    "N = n(A + n(B)), \\quad c = B + 2N, \\quad d = c + n(c + n(c)), \\quad e = 3d .\n",
    "$$\n",
    "\n",
    "Stage 1 gives such a pair for $A = q = n(n(3a) + a)$ and $B = 2a$. Let us substitute it and look at $e$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2aa93901",
   "metadata": {},
   "outputs": [],
   "source": [
    "from robbins_proof import E, Q\n",
    "from syntax import term, show\n",
    "from kernel import subst\n",
    "from ac import symbols\n",
    "\n",
    "e_real = subst(term(E), {\"A\": term(Q), \"B\": term(\"a + a\")})\n",
    "print(f\"e with constants A, B: {symbols(term(E))} symbols\")\n",
    "print(f\"e for A = q, B = 2a: {symbols(e_real)} symbols\")\n",
    "print(show(e_real)[:300], \"…\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "515548fd",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert symbols(e_real) == 329"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffc8be04",
   "metadata": {},
   "source": [
    "Nobody writes such terms in a proof. In Lean, mathlib introduces names: `obtain ⟨a, b, h⟩ := winker` gives constants\n",
    "$a, b$ with the hypothesis $a + b = b$, and `set d := …` — an abbreviation. Our counterpart is a **section** (class\n",
    "`Section`): a group of lemmas about constants that satisfy hypotheses. We prove the lemmas of a section with short\n",
    "constants, and then the method `use` writes all of them down again — with the constants replaced by the real terms.\n",
    "This is the whole proof:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30c88e68",
   "metadata": {},
   "outputs": [],
   "source": [
    "from robbins_proof import robbins_theorem\n",
    "\n",
    "print(inspect.getsource(robbins_theorem))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "088e39e2",
   "metadata": {},
   "source": [
    "Let us run it stage by stage and measure the time:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29dd4fc0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "from kernel import Inst\n",
    "from robbins_proof import idempotent_section, huntington_section\n",
    "\n",
    "timings = {}\n",
    "start = time.perf_counter()\n",
    "K = theory()\n",
    "winker_by_hand(K)\n",
    "timings[\"1. Winker's condition\"] = time.perf_counter() - start\n",
    "start = time.perf_counter()\n",
    "M = hypothetical_lemmas(K)\n",
    "timings[\"2. lemmas with hypotheses\"] = time.perf_counter() - start\n",
    "start = time.perf_counter()\n",
    "WS = idempotent_section(K, M)\n",
    "ES = huntington_section(K)\n",
    "timings[\"3–4. sections with constants\"] = time.perf_counter() - start\n",
    "start = time.perf_counter()\n",
    "ES.use(WS, {\"e\": E}, Inst(\"idem\", ()))\n",
    "WS.use(K, {\"A\": Q, \"B\": \"a + a\"}, Inst(\"winker\", (\"a\",)))\n",
    "timings[\"5. sections used\"] = time.perf_counter() - start\n",
    "for stage, seconds in timings.items():\n",
    "    print(f\"{stage:26} {seconds:6.2f} s\")\n",
    "print()\n",
    "print(\"theorem:   \", show_equation(K.facts[\"huntington\"][1:]))\n",
    "print(\"assumptions:\", sorted(K.assumptions[\"huntington\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e678d474",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert K.assumptions[\"huntington\"] == {\"A1\", \"A2\", \"R\"}\n",
    "assert sum(timings.values()) < 30"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32018384",
   "metadata": {},
   "source": [
    "The kernel accepted Huntington's equation, and the only assumptions the proof uses are A1, A2 and R. The whole proof,\n",
    "from the Robbins equation to Huntington's equation, was checked by our kernel from lecture 3 in a few seconds.\n",
    "\n",
    "Abbreviations have their price only when written out: stage 5 writes the lemmas down again with long terms. Let us\n",
    "count the \"mass\" of a proof — the total number of symbols in all terms written down in the proof object. We compare\n",
    "the lemmas of section ES (the zero, $n(n(x)) = x$, Huntington's equation and the auxiliary lemmas) in two versions:\n",
    "with the constant $e$ and with the real $e$ of 329 symbols substituted."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "97af75c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "from kernel import Refl, Symm, Trans, CongrArg\n",
    "\n",
    "def masa(proof):\n",
    "    \"\"\"The number of symbols in all terms written down in a proof.\"\"\"\n",
    "    stack, sum_term = [proof], 0\n",
    "    while stack:\n",
    "        d = stack.pop()\n",
    "        if isinstance(d, Refl):\n",
    "            sum_term += symbols(d.t)\n",
    "        elif isinstance(d, Inst):\n",
    "            sum_term += sum(symbols(a) for a in d.args)\n",
    "        elif isinstance(d, CongrArg):\n",
    "            sum_term += symbols(d.C)\n",
    "            stack.append(d.p)\n",
    "        elif isinstance(d, Symm):\n",
    "            stack.append(d.p)\n",
    "        else:\n",
    "            stack += [d.p, d.q]\n",
    "    return sum_term\n",
    "\n",
    "es_names = [name for name, *_ in ES.lemmas]\n",
    "for where, kernel_ in [(\"with constant e\", ES.kernel), (\"with the real e\", K)]:\n",
    "    w = sum(nodes(kernel_.proofs[n]) for n in es_names)\n",
    "    m = sum(masa(kernel_.proofs[n]) for n in es_names)\n",
    "    print(f\"{len(es_names)} lemmas {where:16} nodes {w:5}, symbols in terms {m:8,}\".replace(\",\", \" \"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1fb98c36",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert sum(nodes(ES.kernel.proofs[n]) for n in es_names) == sum(nodes(K.proofs[n]) for n in es_names)\n",
    "assert sum(masa(K.proofs[n]) for n in es_names) > 50 * sum(masa(ES.kernel.proofs[n]) for n in es_names)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1402eb5b",
   "metadata": {},
   "source": [
    "The number of nodes does not change — it is the same proof. Only what is written in it grows: every $e$ becomes a long\n",
    "term, and there are dozens of times more symbols. If we wrote the proof with the real terms from the start, the\n",
    "tactics would sort sums of more than a dozen summands, and the proof itself — not only its notation — would be much\n",
    "bigger. An abbreviation (a section in our code, `set` and `obtain` in Lean) is compression of **terms**, just as\n",
    "a lemma is compression of **proofs**.\n",
    "\n",
    "## How much a proof weighs\n",
    "\n",
    "Now we can measure the whole proof in three ways:\n",
    "\n",
    "* **the script** — what we write: the lines of the module `robbins_proof` (without comments and descriptions);\n",
    "* **the proof object** — what the kernel checks: the nodes of the proofs of all theorems that Huntington's equation\n",
    "  uses; a use of a lemma is one `Inst` node;\n",
    "* **the tree without lemmas** — the same proof if every use of a lemma were replaced by its proof, and so on, until\n",
    "  only axioms remain (the function `expanded` counts this exactly, without building the tree)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13427900",
   "metadata": {},
   "outputs": [],
   "source": [
    "import io\n",
    "import tokenize\n",
    "import robbins_proof\n",
    "from robbins import lemmas_used, expanded\n",
    "\n",
    "def code_lines(module):\n",
    "    \"\"\"Lines with code: without empty lines, comments and docstrings.\"\"\"\n",
    "    content = inspect.getsource(module)\n",
    "    docs = set()\n",
    "    previous = None\n",
    "    for t in tokenize.generate_tokens(io.StringIO(content).readline):\n",
    "        if t.type == tokenize.STRING and previous in (tokenize.INDENT, tokenize.NEWLINE, None):\n",
    "            docs.update(range(t.start[0], t.end[0] + 1))\n",
    "        if t.type not in (tokenize.NL, tokenize.COMMENT):\n",
    "            previous = t.type\n",
    "    return sum(1 for i, w in enumerate(content.splitlines(), 1)\n",
    "               if w.strip() and not w.strip().startswith(\"#\") and i not in docs)\n",
    "\n",
    "used = lemmas_used(K, \"huntington\") | {\"huntington\"}\n",
    "script = code_lines(robbins_proof)\n",
    "obj = sum(nodes(K.proofs[n]) for n in used)\n",
    "tree = expanded(K, K.proofs[\"huntington\"])\n",
    "print(f\"script:              {script:>15,} lines\".replace(\",\", \" \"))\n",
    "print(f\"proof object:        {obj:>15,} nodes in {len(used)} theorems\".replace(\",\", \" \"))\n",
    "print(f\"tree without lemmas: {tree:>15,} nodes\".replace(\",\", \" \"))\n",
    "print(f\"lemmas compress {tree / obj:,.0f} times; tactics {obj / script:,.0f} times\".replace(\",\", \" \"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "92cb8758",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert len(used) == 34 and 10 ** 8 < tree < 10 ** 9\n",
    "assert 10_000 < tree / obj < 50_000\n",
    "assert 20 < obj / script < 100\n",
    "WEIGHT = (script, obj, tree)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b87a6e3",
   "metadata": {},
   "source": [
    "More than half a billion nodes in the tree without lemmas — tens of thousands of times more than in the object the\n",
    "kernel really checks. A lemma used many times, inside other lemmas used many times, multiplies in the tree as in\n",
    "exponentiation. The second level of compression are tactics: every line of the script stands on average for several\n",
    "dozen nodes of the proof object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b435b4d5",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "labels = [\"EQP steps (condition 1)\", \"script (lines)\", \"proof object (nodes)\", \"tree without lemmas (nodes)\"]\n",
    "values = [12, script, obj, tree]\n",
    "fig, ax = plt.subplots(figsize=(7.5, 2.6))\n",
    "ax.barh(labels[::-1], values[::-1], color=\"#059669\", height=0.5)\n",
    "ax.set_xscale(\"log\")\n",
    "for i, w in enumerate(values[::-1]):\n",
    "    ax.text(w * 1.3, i, f\"{w:,}\".replace(\",\", \" \"), va=\"center\", fontsize=9, color=\"#1f2937\")\n",
    "ax.set_xlim(1, tree * 40)\n",
    "ax.set_xlabel(\"size (logarithmic scale)\")\n",
    "ax.spines[[\"top\", \"right\"]].set_visible(False)\n",
    "ax.grid(axis=\"x\", color=\"#e5e7eb\", linewidth=0.8)\n",
    "ax.set_axisbelow(True)\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "930cb2f2",
   "metadata": {},
   "source": [
    "## By hand or with `auto`?\n",
    "\n",
    "The same proof can be assembled with stage 1 written by the tactic `auto` (part 2). Let us compare:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8521bfdb",
   "metadata": {},
   "outputs": [],
   "source": [
    "for by_auto in (False, True):\n",
    "    start = time.perf_counter()\n",
    "    K2 = robbins_theorem(by_auto=by_auto)\n",
    "    seconds = time.perf_counter() - start\n",
    "    used2 = lemmas_used(K2, \"huntington\") | {\"huntington\"}\n",
    "    print(f\"by_auto={by_auto!s:5}  {seconds:5.2f} s, object {sum(nodes(K2.proofs[n]) for n in used2):6} nodes, \"\n",
    "          f\"assumptions {sorted(K2.assumptions['huntington'])}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d4f8260",
   "metadata": {},
   "source": [
    "The result is the same, the proof object similar, and the script of stage 1 contains not a single hint about where\n",
    "and with what to expand. This is the third kind of compression: search replaces creative decisions — but only where\n",
    "there are few of them.\n",
    "\n",
    "## What next: from Huntington to Boolean algebra\n",
    "\n",
    "Huntington's equation together with A1 and A2 is one more set of axioms for Boolean algebra (E. V. Huntington, 1933).\n",
    "In mathlib the last lines of the file `Robbins.lean` build from it a full instance `BooleanAlgebra`: zero, one, the\n",
    "product $x \\cdot y = n(n(x) + n(y))$ and the distributive laws. In our course Huntington's axioms of 1904, H1–H8, and\n",
    "their consequences are in {doc}`../wyklady/w03_3_taktyki` and in the Boole Lab library; associativity from H1–H8 — in\n",
    "{ref}`w03-lacznosc`. Joining these two roads is a good exercise (see {doc}`k5_scenariusze`)."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
