{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "5a29a0c0",
   "metadata": {},
   "source": [
    "# Tactics that compress"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "22b3fc0a",
   "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": "574e9a24",
   "metadata": {},
   "source": [
    "In the previous part the script of the proof of lemma `mann_44` had three tactics, and the proof checked by the kernel\n",
    "had 48 nodes. A tactic is a program that writes a proof for us. A good tactic turns a long, repetitive fragment of a\n",
    "proof into one word in the script — and this is the compression this chapter is about. The kernel still receives the\n",
    "whole proof, so the tactic need not be trusted: if it makes a mistake, the kernel rejects the result.\n",
    "\n",
    "For the Robbins proof we build four tactics, from the simplest to the cleverest:\n",
    "\n",
    "| Tactic | What it does | Kind |\n",
    "|---|---|---|\n",
    "| `ac` | closes a goal whose sides differ only by the order and brackets of sums | decision procedure: always terminates, never guesses |\n",
    "| `rw_ac` | rewrites with an equation whose left side sits in the goal \"mixed up\" | matching modulo A1, A2 |\n",
    "| `ac_simp` | rewrites with the given equations as long as possible, then `ac` | simplification to the end |\n",
    "| `auto` | finds the creative expansions with the Robbins equation by itself | bounded search |\n",
    "\n",
    "## The tactic `ac`: a normal form with a proof\n",
    "\n",
    "Two terms are equal by commutativity A1 and associativity A2 exactly when they have the same summands, counted with\n",
    "multiplicity — inside every sum, also deep under $n(\\ldots)$. This is easy to check: in every sum we sort the summands\n",
    "in a fixed order and group them to the left. The result is the **normal form**:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a46735dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "from syntax import term, show\n",
    "from ac import normal\n",
    "\n",
    "for text in [\"(b + a) + (c + a)\", \"a + (a + (c + b))\", \"n(b + a) + n(a + n(b + a))\"]:\n",
    "    print(f\"{text:28} ->  {show(normal(term(text)))}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ac06161",
   "metadata": {},
   "source": [
    "Sorting alone is not a proof, though. The tactic `ac` sorts so that every move can be written down with kernel rules:\n",
    "it merges two sorted sums into one, and then puts every summand in its place by swapping neighbours (insertion sort).\n",
    "One swap of neighbours is three steps: A2, then A1 inside, then A2 backwards."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1c0199b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import inspect\n",
    "import ac\n",
    "\n",
    "print(inspect.getsource(ac._insert))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5bb822b3",
   "metadata": {},
   "source": [
    "Every `steps.fact(...)` adds to the proof an instance of an axiom put into the whole term by `CongrArg`. Let us look\n",
    "at the successive terms in a short example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6d71bbc0",
   "metadata": {},
   "outputs": [],
   "source": [
    "from robbins import theory\n",
    "from ac import Steps, ac_proof\n",
    "\n",
    "K = theory()                      # a kernel with the axioms A1, A2, R\n",
    "steps = Steps(K, term(\"c + (b + a)\"))\n",
    "ac._sort(steps, (), \"A1\", \"A2\")\n",
    "print(show(steps.start))\n",
    "for bit in steps.pieces:\n",
    "    print(\"  =\", show(K.conclusion(bit)[1]))\n",
    "print(\"rewrites:\", steps.count)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c2fc151",
   "metadata": {},
   "source": [
    "Every line is the whole term after one rewrite: `CongrArg` puts the change of a subterm into the whole. The kernel\n",
    "gets one proof out of it — the rewrites joined by `Trans`. How much does such bookkeeping cost? Let us count the nodes\n",
    "of the proof for a sum of $k$ different summands written in reverse order — the worst case of insertion sort:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d1112155",
   "metadata": {},
   "outputs": [],
   "source": [
    "from robbins import nodes\n",
    "\n",
    "letters = \"abcdefghijkl\"\n",
    "cost = {}\n",
    "for k in range(2, 11):\n",
    "    backwards = \" + \".join(reversed(letters[:k]))\n",
    "    in_order = \" + \".join(letters[:k])\n",
    "    proof = ac_proof(K, term(backwards), term(in_order))\n",
    "    assert K.conclusion(proof) == (term(backwards), term(in_order))\n",
    "    cost[k] = nodes(proof)\n",
    "    print(f\"k = {k:2}: {cost[k]:4} nodes, per pair of summands {cost[k] / (k * (k - 1) / 2):.1f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e2bb2c52",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert all(cost[k] <= 9 * k * (k - 1) // 2 for k in cost)\n",
    "assert 8 < cost[10] / 45 < 9"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4810aae",
   "metadata": {},
   "source": [
    "The cost grows like $k^2$: each of the $k(k-1)/2$ pairs of summands has to be swapped, every swap is three rewrites,\n",
    "and every rewrite is three nodes in the proof (`Inst`, `CongrArg`, `Trans`) — hence the number of nodes per pair,\n",
    "which approaches 9. The script, on the other hand, always has one word: `ac`. The longer the sums, the bigger the\n",
    "compression.\n",
    "\n",
    "Is `ac` correct? We do not have to prove it. If the tactic has a bug, the kernel rejects its proof. If the normal forms\n",
    "of the two sides differ, the tactic fails — rightly so, because then the equation does not follow from A1 and A2. Let\n",
    "us also test the tactic on random pairs of terms that are equal up to order and brackets:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6c01b3c9",
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "\n",
    "def random_term(rng, depth):\n",
    "    if depth == 0 or rng.random() < 0.3:\n",
    "        return rng.choice(\"abcd\")\n",
    "    if rng.random() < 0.25:\n",
    "        return (\"n\", random_term(rng, depth - 1))\n",
    "    return (\"+\", random_term(rng, depth - 1), random_term(rng, depth - 1))\n",
    "\n",
    "def shuffled(rng, t):\n",
    "    \"\"\"The same term up to A1, A2: summands shuffled, brackets at random.\"\"\"\n",
    "    if isinstance(t, str):\n",
    "        return t\n",
    "    if t[0] == \"n\":\n",
    "        return (\"n\", shuffled(rng, t[1]))\n",
    "    parts = [shuffled(rng, s) for s in ac.addends(t)]\n",
    "    rng.shuffle(parts)\n",
    "    while len(parts) > 1:\n",
    "        i = rng.randrange(len(parts) - 1)\n",
    "        parts[i:i + 2] = [(\"+\", parts[i], parts[i + 1])]\n",
    "    return parts[0]\n",
    "\n",
    "rng = random.Random(2026)\n",
    "pairs = [(t, shuffled(rng, t)) for t in (random_term(rng, 6) for _ in range(500))]\n",
    "accepted = sum(K.conclusion(ac_proof(K, s, t)) == (s, t) for s, t in pairs)\n",
    "print(f\"the kernel accepted {accepted} proofs out of {len(pairs)}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aab6d29b",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert accepted == len(pairs) == 500"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c12aa4d",
   "metadata": {},
   "source": [
    "## Matching modulo associativity and commutativity\n",
    "\n",
    "An ordinary `rw` looks for a pattern literally. In the Robbins proof that is not enough: the left side of a lemma often\n",
    "sits in the goal in a different order or as a part of a longer sum. In mathlib this shows in lines such as\n",
    "`rw [add_comm _ q, mann_47]` — the summands have to be reordered by hand first, so that `rw` works at all.\n",
    "\n",
    "The tactic `rw_ac` matches a pattern **modulo A1 and A2**. A variable of the pattern may then take several summands of\n",
    "a sum. For example, the left side of the Robbins equation matches this term in one way, with $x = a + b$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9018060d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from ac import ac_match\n",
    "\n",
    "pattern = term(\"n(n(x + y) + n(x + n(y)))\")\n",
    "t = normal(term(\"n(n(c + a + b) + n(b + a + n(c)))\"))\n",
    "for s in ac_match(pattern, t, {\"x\", \"y\"}, {}):\n",
    "    print({x: show(v) for x, v in s.items()})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78d95c02",
   "metadata": {},
   "source": [
    "When the pattern fits a part of a sum, `rw_ac` first regroups the summands — the proof of the regrouping is written by\n",
    "`ac` — so that the matching fragment stands alone, and then rewrites it with an ordinary step. In the example the\n",
    "constants $a, b, c, d$ satisfy the hypothesis $a + b = c$, and in the goal $a$ and $b$ are separated by the\n",
    "summand $d$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85592f5e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from robbins import Goal, Section\n",
    "\n",
    "K = theory()\n",
    "S = Section(K, \"abcd\", [\"a + b = c\"])       # constants a, b, c, d and hypothesis h1: a + b = c\n",
    "g = Goal(S.kernel, \"n(b + (d + a)) = n(d + c)\")\n",
    "g.rw_ac(\"h1\")\n",
    "print(g)\n",
    "g.ac()\n",
    "print(\"nodes:\", nodes(g.qed()))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32dbf847",
   "metadata": {},
   "source": [
    "An ordinary `rw [h1]` would find nothing here: the tree of the term has no subtree $a + b$. In the proof of lemma\n",
    "`mann_48` the tactic `rw_ac` replaces in this way the manual `add_comm _ q` of mathlib.\n",
    "\n",
    "## `ac_simp`: rewrite as long as you can\n",
    "\n",
    "Mann's lemmas with hypotheses (part 3) need several rewrites in different places on both sides. Instead of pointing\n",
    "to each, we give a list of equations, and `ac_simp` rewrites with them — each from left to right, modulo A1 and A2 —\n",
    "as long as one of them fits, and finally closes the goal with the tactic `ac`. A simple example: if $e + e = e$ (an\n",
    "idempotent element), every sum made of copies of $e$ and one $x$ simplifies to $e + x$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd2ae78e",
   "metadata": {},
   "outputs": [],
   "source": [
    "S = Section(K, \"e\", [\"e + e = e\"])         # constant e and hypothesis h1: e + e = e\n",
    "S.lemma(\"absorption\", \"e + (x + (e + e)) + e = x + e\", lambda g: g.ac_simp(\"h1\"))\n",
    "print(show(S.kernel.facts[\"absorption\"][1]), \"=\", show(S.kernel.facts[\"absorption\"][2]),\n",
    "      \"| uses of h1 in the proof:\", str(S.kernel.proofs[\"absorption\"]).count(\"'h1'\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "98efa26e",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert str(S.kernel.proofs[\"absorption\"]).count(\"'h1'\") == 3"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33e0b211",
   "metadata": {},
   "source": [
    "The tactic replaced $e + e$ by $e$ three times, although the script never points to a place. Such simplification always ends\n",
    "when every rule shortens the term (here: two copies of $e$ become one). When the rules do not shorten, `ac_simp` could\n",
    "go round in circles — that is why it has a limit on rewrites and fails with a message when it is exceeded, instead of\n",
    "running forever.\n",
    "\n",
    "## `auto`: the creative step from a search\n",
    "\n",
    "The hardest part of the Robbins proof are the expansions: replace $x$ by $n(n(x + y) + n(x + n(y)))$ — but which $x$\n",
    "and which $y$? In mathlib these choices are written out by hand, for example\n",
    "`nth_rw 2 [← robbins (-(a + b)) (-a + b)]`. The tactic `auto` looks for them itself:\n",
    "\n",
    "1. it brings both sides of the goal to the normal form;\n",
    "2. for each side it lists all terms that can be reached with **one** rewrite from the list of rules (the expansion\n",
    "   `← R` with the variable $y$ taken from the subterms of the goal and from short sums of its summands, the\n",
    "   contraction `R`, lemmas in both directions) — each again in normal form;\n",
    "3. it looks for a common element of the two sets: then the goal has the proof \"one step from the left, one from the\n",
    "   right, and `ac` in the middle\".\n",
    "\n",
    "This is a search from both sides at once (meet in the middle). Let us see what `auto` found for `mann_44`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a56b53aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "from kernel import Inst, Symm, Trans, CongrArg\n",
    "from robbins_proof import STATEMENTS\n",
    "\n",
    "def instances(proof, name):\n",
    "    \"\"\"Arguments of all uses of the fact `name` in a proof tree.\"\"\"\n",
    "    stack, result = [proof], []\n",
    "    while stack:\n",
    "        d = stack.pop()\n",
    "        if isinstance(d, Inst) and d.name == name:\n",
    "            result.append(tuple(show(a) for a in d.args))\n",
    "        elif isinstance(d, (Symm, CongrArg)):\n",
    "            stack.append(d.p)\n",
    "        elif isinstance(d, Trans):\n",
    "            stack += [d.p, d.q]\n",
    "    return sorted(set(result))\n",
    "\n",
    "from robbins import lemma\n",
    "\n",
    "K = theory()\n",
    "proof, _ = lemma(K, \"mann_44\", STATEMENTS[\"mann_44\"], lambda g: g.auto())\n",
    "print(\"auto used R for (x, y):\", instances(proof, \"R\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "125fdd19",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert instances(proof, \"R\") == [(\"b\", \"a\"), (\"n(a + b)\", \"b + n(a)\")]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57180d76",
   "metadata": {},
   "source": [
    "Exactly the two expansions that mathlib writes out by hand: $x = b$, $y = a$, and $x = n(a + b)$ with $y = b + n(a)$\n",
    "— that is $n(a) + b$ with the summands in the order of the normal form. The function `winker_by_auto` proves lemmas\n",
    "44–49 like this — the script only says which rules may be used:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "73145f81",
   "metadata": {},
   "outputs": [],
   "source": [
    "from robbins_proof import winker_by_auto, winker_by_hand\n",
    "\n",
    "print(inspect.getsource(winker_by_auto))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64133c93",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "for stage in (winker_by_hand, winker_by_auto):\n",
    "    K = theory()\n",
    "    start = time.perf_counter()\n",
    "    stage(K)\n",
    "    print(f\"{stage.__name__:15} {time.perf_counter() - start:5.2f} s, \"\n",
    "          f\"nodes in 12 lemmas: {sum(nodes(K.proofs[n]) for n in STATEMENTS)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "94c0272d",
   "metadata": {},
   "source": [
    "A script without creative hints is shorter, and the proof for the kernel is almost the same. We pay with time: the\n",
    "search takes longer than carrying out ready hints. And where is `auto` not enough? Lemma `mann_50` needs instances of\n",
    "`mann_49` with four arbitrary arguments and of `mann_44` with two — each would have to be guessed from the pool of\n",
    "candidates. Let us count how many candidates a variable in `mann_50` would have and how many possibilities that gives\n",
    "for four variables at once:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "057d21b8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import robbins\n",
    "\n",
    "from syntax import equation\n",
    "\n",
    "l, p = (normal(t) for t in equation(STATEMENTS[\"mann_50\"]))\n",
    "pool = robbins._pool(l, p, 2)\n",
    "places = len(list(robbins.positions(l))) + len(list(robbins.positions(p)))\n",
    "print(f\"candidates for one variable: {len(pool)}, for four at once: {len(pool) ** 4:,}\".replace(\",\", \" \"))\n",
    "print(f\"places in the goal: {places}, terms to check: {places * len(pool) ** 4:,}\".replace(\",\", \" \"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9959d68",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert places * len(pool) ** 4 > 10 ** 6"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "389f6661",
   "metadata": {},
   "source": [
    "More than a million terms, each to be brought to the normal form — and that for a single step. That is why in lemmas\n",
    "50–54 the script gives the instances itself — as in mathlib — and we leave `auto` for the places where one variable is\n",
    "free. This is a typical compromise: a searching tactic compresses the script, but only where the space of\n",
    "possibilities is small. The rest of the compression comes from a well-chosen lemma — more about that in the next part.\n",
    "\n",
    "## How to design a tactic\n",
    "\n",
    "These four examples show a few principles that fit every tactic — also the ones we compose in the Boole Lab and in\n",
    "the Tactic Lab (see {doc}`k5_scenariusze`):\n",
    "\n",
    "* **Decide or fail fast.** `ac` always terminates and never leaves a goal half done: either it closes it, or it reports\n",
    "  an error. Such a tactic can safely be called at the end of every branch.\n",
    "* **Have a measure of progress.** `ac_simp` terminates because every good rule shortens the term; when the rules do\n",
    "  not shorten, the limit saves us. In the Boole Lab the same role is played by the analysis \"the sum of the sizes of\n",
    "  the goals goes down\".\n",
    "* **Bound the search.** `auto` looks at only one step from each side and at a bounded pool of candidates. When the\n",
    "  pool grows exponentially, a hint is better.\n",
    "* **Do not ask for trust.** Each of these tactics writes an ordinary proof made of five rules. The kernel checks it\n",
    "  just like a proof typed by hand (the de Bruijn criterion, see {ref}`w03-de-bruijn`).\n",
    "* **Compress what repeats.** In the Robbins proof the most frequent thing is the bookkeeping of associativity and\n",
    "  commutativity — and this is exactly what `ac` swallows.\n",
    "\n",
    "## References and places worth a visit\n",
    "\n",
    "* Lean 4: the tactic `ac_rfl` (in mathlib used with the type classes `Std.Associative` and `Std.Commutative`, see\n",
    "  `Archive/Robbins.lean`); mathlib also has `abel` and `ring`, which bring expressions in abelian groups and rings to a\n",
    "  normal form.\n",
    "* F. Baader, T. Nipkow, *Term Rewriting and All That*, Cambridge University Press (1998) — normal forms, rewriting\n",
    "  modulo AC and its termination.\n",
    "* W. McCune, *Solution of the Robbins Problem* (1997) — on unification modulo AC in the program EQP, which does the same\n",
    "  as our tactic `ac`, but inside the search."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
