{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6b6c5413",
   "metadata": {},
   "source": [
    "# Scenarios: building tactics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1b1ec9c1",
   "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": "dd50dc40",
   "metadata": {},
   "source": [
    "The tactics of the previous parts are written in Python. In the Boole Lab and in the Tactic Lab tactics are composed\n",
    "differently: from ready steps (`rw`, `nth_rw`, `exact`, …) and combinators as in Lean 4 (`first | … | …`, `try`,\n",
    "`repeat`, `<;>`, …). The scenarios below go the same way as the chapter — from a script, through a tactic, to what the\n",
    "kernel sees — only on smaller examples from Boolean algebra (Huntington's axioms H1–H8 from lecture 3). We run every\n",
    "scenario here with the Boole Lab engine (`Session`), so the results are real; the same can be typed in the applet's\n",
    "terminal:\n",
    "\n",
    "* [Boole Lab](https://bnaskrecki.faculty.wmi.amu.edu.pl/math-comp/en/applets/boole-lab.html) — a terminal with the\n",
    "  kernel and the library of theorems, a tactic workshop (the \"workshop\" button);\n",
    "* [Tactic Lab](https://bnaskrecki.faculty.wmi.amu.edu.pl/math-comp/en/applets/tactic-lab.html) — a tactic as a\n",
    "  flowchart, a run on a goal and layers: flow, insides of tactics, kernel rules."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad3d705b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import textwrap\n",
    "from lab import Session\n",
    "\n",
    "lab = Session(\"en\")          # one session for the whole chapter: theorems thm1, thm2, ...\n",
    "\n",
    "def session(*commands):\n",
    "    \"\"\"Runs Boole Lab commands, prints the replies and returns them as a list of strings.\"\"\"\n",
    "    replies = []\n",
    "    for command in commands:\n",
    "        print(\"> \" + command)\n",
    "        replies.append(lab.run(command).text())\n",
    "        for row in replies[-1].splitlines():\n",
    "            print(textwrap.fill(row, 100, subsequent_indent=\"      \"))\n",
    "    return replies"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79cdc436",
   "metadata": {},
   "source": [
    "## Scenario 1: the script and the proof object\n",
    "\n",
    "A proof in the Boole Lab starts with `bl prove` and ends with `qed`: then the kernel receives the whole proof and says\n",
    "how many nodes it has. The example tactic `units` removes \"$+\\,0$\" and \"$\\cdot\\,1$\" — in the script it is one word, in\n",
    "the proof a few steps:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6d83c4b8",
   "metadata": {},
   "outputs": [],
   "source": [
    "out = session(\"bl prove x + 0 + x * 1 = x\", \"units; rw [add_idem]\", \"qed\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3da231f0",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert \"3 steps\" in out[1] and \"proof tree: 7 nodes\" in out[2]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8dd288ac",
   "metadata": {},
   "source": [
    "The line `⚙ 3 steps` says what the tactic really did: two rewrites with the axioms H5 and H6 and one with the theorem\n",
    "`add_idem`. The script has two words, the proof for the kernel — seven nodes. It is the same relation as in the Robbins\n",
    "proof, only on a small scale.\n",
    "\n",
    "## Scenario 2: a tactic made of tactics and its measure\n",
    "\n",
    "The command `bl tactic` defines your own tactic. The Boole Lab immediately draws its structure and analyses it: will\n",
    "`repeat` stop, is some alternative of `first` unreachable, does `try` hide a failure."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a8980ad1",
   "metadata": {},
   "outputs": [],
   "source": [
    "out = session(\"bl tactic tidy := repeat (first | rw [H5] | rw [H6])\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b297abee",
   "metadata": {},
   "source": [
    "The analysis found a **measure of progress**: every turn of the loop decreases the sum of the sizes of the goals (H5\n",
    "and H6 shorten the term by two symbols), and a natural number cannot go down forever. Let us check the tactic on\n",
    "a goal — `bl trace` runs it as a dry run and shows every turn:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a8e3464",
   "metadata": {},
   "outputs": [],
   "source": [
    "out = session(\"bl prove (x + 0) * 1 + 0 = x\", \"bl trace tidy\", \"tidy\", \"qed\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06d8aab1",
   "metadata": {},
   "source": [
    "In the Tactic Lab the same tactic is a flowchart: a `repeat` frame with a loop, inside it a `first` ladder with two\n",
    "`rw` cards. A run highlights the edges the goal went through.\n",
    "\n",
    "## Scenario 3: a tactic that loops\n",
    "\n",
    "Commutativity $x + y = y + x$ does not shorten the term. A tactic \"swap as long as you can\" therefore has no measure\n",
    "of progress:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46b793d6",
   "metadata": {},
   "outputs": [],
   "source": [
    "out = session(\"bl tactic loop := repeat rw [H1]\", \"bl prove x + y + z = z + (y + x)\", \"loop\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "067ea27f",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert \"may loop\" in out[0] and \"repeat loops\" in out[2]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22f56074",
   "metadata": {},
   "source": [
    "The Boole Lab warned already at the definition (the rule \"keeps the size of the goal\"), and when run it detected that\n",
    "after two turns the goal came back to its original form: $x + y + z \\to z + (x + y) \\to x + y + z$. In Lean such a\n",
    "tactic would go round until the time limit.\n",
    "\n",
    "This is the difference between `repeat rw [H1]` and our tactic `ac` from part 2: `ac` also uses commutativity, but\n",
    "only when a swap of neighbours **repairs the order**. Its measure of progress is the number of inversions — pairs of\n",
    "summands in the wrong order. Every swap decreases it by exactly one:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "885d5566",
   "metadata": {},
   "outputs": [],
   "source": [
    "from robbins import theory\n",
    "from syntax import term, show\n",
    "from ac import Steps, addends, order_key\n",
    "import ac\n",
    "\n",
    "def inversions(t):\n",
    "    s = addends(t)\n",
    "    return sum(order_key(s[i]) > order_key(s[j]) for i in range(len(s)) for j in range(i + 1, len(s)))\n",
    "\n",
    "K = theory()\n",
    "steps = Steps(K, term(\"e + d + c + b + a\"))\n",
    "ac._sort(steps, (), \"A1\", \"A2\")\n",
    "states = [steps.start] + [K.conclusion(k)[1] for k in steps.pieces]\n",
    "print(\" → \".join(str(inversions(t)) for t in states))\n",
    "print(\"rewrites:\", steps.count, \"| inversions at the start:\", inversions(steps.start))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a8c51172",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "_inv = [inversions(t) for t in states]\n",
    "assert _inv[0] == 10 and _inv[-1] == 0 and all(b - a in (0, -1) for a, b in zip(_inv, _inv[1:]))\n",
    "assert steps.count == 22 and sum(1 for a, b in zip(_inv, _inv[1:]) if b < a) == 10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce22d9ac",
   "metadata": {},
   "source": [
    "Ten inversions, 22 rewrites: a swap of the first two summands is one step A1, every further one — three steps (A2, A1,\n",
    "A2 backwards). The number of inversions drops by one at every step with A1 and does not change at the steps with A2.\n",
    "The tactic stops for sure, because there are finitely many inversions — and that is the whole difference between\n",
    "`loop` and `ac`.\n",
    "\n",
    "## Scenario 4: what the kernel sees\n",
    "\n",
    "The command `bl lean` shows a proof in Lean notation, and your own tactics — as Lean macros. For the theorem of the\n",
    "second scenario:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84a8438f",
   "metadata": {},
   "outputs": [],
   "source": [
    "out = session(\"bl lean thm2\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "baf5f5e2",
   "metadata": {},
   "source": [
    "The macro is exactly our tactic: Lean expands it when checking into the same rewrites. Neither the Boole Lab nor Lean\n",
    "trust the tactic — they trust the kernel, which checks the result. In the Tactic Lab the same run can be watched on\n",
    "three layers: the flow through the combinators, the insides of named tactics and single kernel rules.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. **The cost of the tactic `ac`.** For random sums of $k$ different summands count the nodes of the proof `ac_proof`\n",
    "   and the number of inversions. Check that there are about nine times more nodes than inversions, and explain where\n",
    "   the constant comes from.\n",
    "2. **Two steps on one side.** Extend `auto` so that it allows two rewrites on one side of the goal. Which of the lemmas\n",
    "   `mann_50` … `mann_54` then go through without hints? How long does the search take?\n",
    "3. **Your own `ac` in the Boole Lab.** The Boole Lab has no tactic `ac`. Try to compose a tactic from `rw` steps and\n",
    "   combinators that orders a sum of two summands, and explain why for longer sums an order (like `order_key`) is\n",
    "   needed, which the combinators do not know.\n",
    "4. **The de Bruijn factor.** F. Wiedijk measures how many times longer a formal proof is than the mathematical text by\n",
    "   comparing file sizes after compression (`gzip`). Compare in this way lemmas 44–54 in `obce/mathlib4/Robbins.lean`\n",
    "   with our module `robbins_proof` and with the EQP proof. What does such a number measure, and what does it not?\n",
    "5. **From Huntington to H1–H8.** From Huntington's equation, A1 and A2 derive in our kernel the axioms H1–H8 of\n",
    "   lecture 3: define $x \\cdot y = n(n(x) + n(y))$, $1 = a + n(a)$, $0 = n(1)$ and prove the axioms one by one. Which\n",
    "   tactics of this chapter will you use most?\n",
    "6. **Compression in numbers.** For the proof of part 3 count how many times each lemma occurs in the tree without\n",
    "   lemmas (a function similar to `expanded`). Which lemma \"weighs\" the most, and which repeats most often?\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).\n",
    "* F. Wiedijk, [*The De Bruijn Factor*](https://www.cs.ru.nl/~freek/factor/) (TPHOLs 2000).\n",
    "* F. Baader, T. Nipkow, *Term Rewriting and All That*, Cambridge University Press (1998) — rewriting modulo\n",
    "  associativity and commutativity, termination measures.\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",
    "  (2025) — on proofs that nobody compressed into understandable lemmas."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
