{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ff0b1acc",
   "metadata": {},
   "source": [
    "# Part 7. SymPy: symbolic once, numeric many times\n",
    "\n",
    "SymPy excels at exact computation: it expands, simplifies, differentiates, sums, and proves\n",
    "identities. Each of its operations, however, builds and traverses an expression tree made of Python\n",
    "objects. In Lecture 3 we built such a system ourselves (MiniCAS), so we know how much work hides\n",
    "behind a single substitution. That is why SymPy is very slow when we use it as a calculator in a\n",
    "loop. The rule of this part is: **we do the symbolic computation once** and turn its result into a\n",
    "fast numerical function, which we then call many times. The second rule: when we know what we\n",
    "want, we choose specialized tools instead of general ones (`simplify`, `Rational` in a loop). The\n",
    "examples come from Lectures 3 and 5."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4582b20e",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "# Narzędzia pomiaru czasu — opisane w części 1 tego rozdziału.\n",
    "import platform\n",
    "import statistics\n",
    "import subprocess\n",
    "import sys\n",
    "import textwrap\n",
    "import timeit\n",
    "from importlib.metadata import version\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.ticker import FuncFormatter, LogLocator, NullFormatter\n",
    "\n",
    "INDYGO, BURSZTYN, ZIELEN = \"#4f46e5\", \"#d97706\", \"#059669\"\n",
    "SZARY, TUSZ, SIATKA = \"#94a3b8\", \"#334155\", \"#e2e8f0\"\n",
    "JEDNOSTKI = ((\"s\", 1.0), (\"ms\", 1e-3), (\"µs\", 1e-6), (\"ns\", 1e-9))\n",
    "\n",
    "\n",
    "def zmierz(f, *args, cel=0.02, proby=7):\n",
    "    \"\"\"Mediana czasu jednego wywołania f(*args), w sekundach.\n",
    "\n",
    "    Szybką funkcję wywołujemy w seriach trwających około `cel` sekund, bo\n",
    "    zegar nie zauważy pojedynczego wywołania trwającego ułamek mikrosekundy.\n",
    "    Z `proby` serii bierzemy medianę, odporną na serie zakłócone przez inne\n",
    "    programy.\n",
    "    \"\"\"\n",
    "    zegar = timeit.Timer(lambda: f(*args))\n",
    "    t = zegar.timeit(number=1)          # rozgrzewka i pierwsza ocena\n",
    "    if t > cel:                         # wolna funkcja: trzy wywołania\n",
    "        return statistics.median(zegar.repeat(repeat=3, number=1))\n",
    "    n = 1\n",
    "    while t < cel / 10:                 # zbyt krótka seria: wydłużamy ją\n",
    "        n *= 10\n",
    "        t = zegar.timeit(number=n)\n",
    "    n = max(1, round(n * cel / t))      # seria trwa teraz około `cel` s\n",
    "    return statistics.median(zegar.repeat(repeat=proby, number=n)) / n\n",
    "\n",
    "\n",
    "def czas(s):\n",
    "    \"\"\"Czas w sekundach jako napis z jednostką, np. 1.23 ms.\"\"\"\n",
    "    for jednostka, skala in JEDNOSTKI:\n",
    "        if s >= 0.9995 * skala or jednostka == \"ns\":\n",
    "            v = s / skala\n",
    "            if v >= 99.95:\n",
    "                return f\"{v:.0f} {jednostka}\"\n",
    "            return f\"{v:#.3g} {jednostka}\"\n",
    "\n",
    "\n",
    "def krotnosc(r):\n",
    "    \"\"\"Iloraz czasów jako napis: 340×, 2.5×, 0.81×.\"\"\"\n",
    "    if r >= 10:\n",
    "        return f\"{r:.0f}×\"\n",
    "    return f\"{r:.1f}×\" if r >= 1 else f\"{r:.2f}×\"\n",
    "\n",
    "\n",
    "def porownaj(warianty, *args, zgodne=None):\n",
    "    \"\"\"Mierzy warianty (nazwa → funkcja) na tych samych danych.\n",
    "\n",
    "    Najpierw sprawdza, że wszystkie warianty dają ten sam wynik (operatorem\n",
    "    == albo funkcją `zgodne`): porównujemy tylko programy, które liczą to\n",
    "    samo. Przyspieszenie to czas pierwszego wariantu podzielony przez czas\n",
    "    danego. Zwraca słownik czasów.\n",
    "    \"\"\"\n",
    "    wyniki = {nazwa: f(*args) for nazwa, f in warianty.items()}\n",
    "    wzorzec = next(iter(wyniki.values()))\n",
    "    for nazwa, w in wyniki.items():\n",
    "        if not (zgodne(w, wzorzec) if zgodne else w == wzorzec):\n",
    "            raise AssertionError(f\"wariant „{nazwa}” daje inny wynik\")\n",
    "    czasy = {nazwa: zmierz(f, *args) for nazwa, f in warianty.items()}\n",
    "    baza = next(iter(czasy.values()))\n",
    "    szer = max(len(nazwa) for nazwa in czasy)\n",
    "    wiersze = [f\"{'wariant':{szer}}  {'czas':>9}  {'przyspieszenie':>14}\"]\n",
    "    for nazwa, t in czasy.items():\n",
    "        wiersze.append(f\"{nazwa:{szer}}  {czas(t):>9}\"\n",
    "                       f\"  {krotnosc(baza / t):>14}\")\n",
    "    print(\"\\n\".join(wiersze))\n",
    "    return czasy\n",
    "\n",
    "\n",
    "def srodowisko(*biblioteki):\n",
    "    \"\"\"Wypisuje, na czym mierzymy: procesor, system, Python, biblioteki.\"\"\"\n",
    "    if sys.platform == \"darwin\":\n",
    "        procesor = subprocess.run(\n",
    "            [\"sysctl\", \"-n\", \"machdep.cpu.brand_string\"],\n",
    "            capture_output=True, text=True).stdout.strip()\n",
    "        system = f\"macOS {platform.mac_ver()[0]}\"\n",
    "    else:\n",
    "        procesor = platform.processor()\n",
    "        system = f\"{platform.system()} {platform.release()}\"\n",
    "    opis = [procesor or platform.machine(), system,\n",
    "            f\"Python {platform.python_version()}\"]\n",
    "    opis += [f\"{b} {version(b)}\" for b in biblioteki]\n",
    "    print(textwrap.fill(\"Pomiary: \" + \", \".join(opis), width=79,\n",
    "                        subsequent_indent=\"  \"))\n",
    "\n",
    "\n",
    "def upewnij(warunek, tresc):\n",
    "    \"\"\"Pilnuje zdań z tekstu rozdziału.\n",
    "\n",
    "    Gdy pomiar przeczy zdaniu, budowa książki się zatrzymuje.\n",
    "    \"\"\"\n",
    "    if not warunek:\n",
    "        raise AssertionError(f\"Tekst rozdziału twierdzi: {tresc}. \"\n",
    "                             \"Pomiar temu przeczy.\")\n",
    "\n",
    "\n",
    "def _os_czasu(v, _):\n",
    "    for jednostka, skala in JEDNOSTKI:\n",
    "        if v >= 0.9995 * skala:\n",
    "            return f\"{v / skala:.0f} {jednostka}\"\n",
    "    return f\"{v / 1e-9:g} ns\"\n",
    "\n",
    "\n",
    "def wykres_czasow(czasy, tytul):\n",
    "    \"\"\"Czasy wariantów na osi logarytmicznej; najszybszy jest wyróżniony.\"\"\"\n",
    "    nazwy = list(czasy)[::-1]           # pierwszy wariant na górze\n",
    "    t = [czasy[nazwa] for nazwa in nazwy]\n",
    "    fig, ax = plt.subplots(figsize=(8, 0.42 * len(nazwy) + 1.2))\n",
    "    ax.scatter(t, range(len(nazwy)), s=70, zorder=3, edgecolors=\"white\",\n",
    "               linewidths=2, c=[INDYGO if v == min(t) else SZARY for v in t])\n",
    "    for i, v in enumerate(t):\n",
    "        ax.annotate(czas(v), (v, i), xytext=(9, 0), va=\"center\",\n",
    "                    textcoords=\"offset points\", fontsize=9, color=TUSZ)\n",
    "    ax.set_yticks(range(len(nazwy)), nazwy)\n",
    "    ax.set_xscale(\"log\")\n",
    "    ax.set_xlim(min(t) / 3, max(t) * 8)  # miejsce na etykiety\n",
    "    ax.xaxis.set_major_locator(LogLocator(base=10))\n",
    "    ax.xaxis.set_major_formatter(FuncFormatter(_os_czasu))\n",
    "    ax.xaxis.set_minor_formatter(NullFormatter())\n",
    "    ax.grid(axis=\"x\", color=SIATKA, lw=1)\n",
    "    ax.set_axisbelow(True)\n",
    "    for bok in (\"top\", \"right\", \"left\"):\n",
    "        ax.spines[bok].set_visible(False)\n",
    "    ax.tick_params(axis=\"y\", length=0)\n",
    "    ax.set_title(tytul, loc=\"left\", fontsize=11)\n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "def wykres_skalowania(rozmiary, serie, tytul, opis_x=\"n\"):\n",
    "    \"\"\"Czas w zależności od rozmiaru danych, obie osie logarytmiczne.\"\"\"\n",
    "    fig, ax = plt.subplots(figsize=(8, 4))\n",
    "    style = zip(serie.items(), (INDYGO, BURSZTYN, ZIELEN), \"osD\")\n",
    "    for (nazwa, czasy_serii), kolor, znak in style:\n",
    "        ax.loglog(rozmiary, czasy_serii, \"-\", marker=znak, color=kolor,\n",
    "                  lw=2, ms=6, label=nazwa)\n",
    "    ax.set_xticks(rozmiary, [str(n) for n in rozmiary])\n",
    "    ax.xaxis.set_minor_formatter(NullFormatter())\n",
    "    ax.yaxis.set_major_formatter(FuncFormatter(_os_czasu))\n",
    "    ax.yaxis.set_minor_formatter(NullFormatter())\n",
    "    ax.set_xlabel(opis_x)\n",
    "    ax.grid(color=SIATKA, lw=1)\n",
    "    ax.set_axisbelow(True)\n",
    "    for bok in (\"top\", \"right\"):\n",
    "        ax.spines[bok].set_visible(False)\n",
    "    ax.legend(loc=\"best\", frameon=False, fontsize=9)\n",
    "    ax.set_title(tytul, loc=\"left\", fontsize=11)\n",
    "    plt.tight_layout()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5495e80b",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "import sys, pathlib\n",
    "# pakiet MiniCAS z wykładu 3: katalog minicas/ repozytorium kursu\n",
    "for katalog in pathlib.Path.cwd().parents:\n",
    "    if (katalog / \"minicas\" / \"minicas\").is_dir():\n",
    "        sys.path.insert(0, str(katalog / \"minicas\"))\n",
    "        break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "739185bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "import inspect\n",
    "import math\n",
    "import random\n",
    "from fractions import Fraction\n",
    "\n",
    "import numpy as np\n",
    "import sympy as sp\n",
    "from sympy.core.cache import clear_cache\n",
    "\n",
    "import minicas\n",
    "\n",
    "srodowisko(\"numpy\", \"sympy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "999b4c93",
   "metadata": {},
   "source": [
    "## Values of an expression at many points\n",
    "\n",
    "In Lecture 3 (§3.4) we evaluated the expression $\\sin(x+1)+\\cos(x+1)$ at a thousand random points\n",
    "in two ways: with the MiniCAS interpreter, which traverses the expression tree at every point, and\n",
    "with a virtual machine, for which the MiniCAS compiler translates the tree once. Let us add SymPy\n",
    "to the comparison: substitution with `subs` followed by `evalf`, the value `evalf(subs=...)`, and\n",
    "the function `sp.lambdify`, which turns an expression into an ordinary Python function. The\n",
    "functions that use SymPy clear SymPy’s cache before each call (see {doc}`part 1 <p1_pomiar>`),\n",
    "because otherwise we would be measuring the retrieval of stored results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4468da5",
   "metadata": {},
   "outputs": [],
   "source": [
    "x = sp.symbols(\"x\")\n",
    "w = sp.sin(x + 1) + sp.cos(x + 1)\n",
    "w_minicas = minicas.parse(\"sin(x+1) + cos(x+1)\")\n",
    "program = minicas.compile_expr(w_minicas)\n",
    "f_math = sp.lambdify(x, w, \"math\")\n",
    "f_numpy = sp.lambdify(x, w, \"numpy\")\n",
    "\n",
    "random.seed(20261025)                       # te same punkty co na wykładzie 3\n",
    "punkty = [random.uniform(-10, 10) for _ in range(1000)]\n",
    "punkty_tablica = np.array(punkty)\n",
    "\n",
    "\n",
    "def sympy_subs(ts):\n",
    "    clear_cache()\n",
    "    return [float(w.subs(x, t).evalf()) for t in ts]\n",
    "\n",
    "\n",
    "def sympy_evalf(ts):\n",
    "    clear_cache()\n",
    "    return [float(w.evalf(subs={x: t})) for t in ts]\n",
    "\n",
    "\n",
    "czasy_wartosci = porownaj({\n",
    "    \"SymPy: subs i evalf\": lambda: sympy_subs(punkty),\n",
    "    \"SymPy: evalf(subs=...)\": lambda: sympy_evalf(punkty),\n",
    "    \"MiniCAS: interpreter drzewa\":\n",
    "        lambda: [minicas.numeric(w_minicas, {\"x\": t}) for t in punkty],\n",
    "    \"MiniCAS: maszyna wirtualna\":\n",
    "        lambda: [program.run({\"x\": t}, exact=False) for t in punkty],\n",
    "    \"lambdify(..., 'math')\": lambda: [f_math(t) for t in punkty],\n",
    "    \"lambdify(..., 'numpy')\": lambda: f_numpy(punkty_tablica),\n",
    "}, zgodne=lambda a, b: np.allclose(np.asarray(a, dtype=float),\n",
    "                                   np.asarray(b, dtype=float),\n",
    "                                   rtol=1e-12, atol=1e-12))\n",
    "wykres_czasow(czasy_wartosci, \"sin(x+1) + cos(x+1) w 1000 punktów\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4efe67a3",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "c = czasy_wartosci\n",
    "upewnij(c[\"SymPy: subs i evalf\"] > c[\"MiniCAS: interpreter drzewa\"]\n",
    "        > c[\"MiniCAS: maszyna wirtualna\"] > c[\"lambdify(..., 'math')\"]\n",
    "        > c[\"lambdify(..., 'numpy')\"],\n",
    "        \"kolejność: subs, interpreter, maszyna wirtualna, lambdify\")\n",
    "upewnij(c[\"SymPy: subs i evalf\"] > 1000 * c[\"lambdify(..., 'math')\"],\n",
    "        \"lambdify jest ponad tysiąc razy szybsze od subs\")\n",
    "upewnij(2000 < c[\"SymPy: subs i evalf\"] / c[\"lambdify(..., 'numpy')\"] < 50000,\n",
    "        \"między pierwszym a ostatnim wierszem są cztery rzędy wielkości\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c9c7f8c",
   "metadata": {},
   "source": [
    "The difference between the first and the last row is four orders of magnitude. Substitution in\n",
    "SymPy builds a new tree at every point, simplifies it, and only then computes the value. The\n",
    "MiniCAS interpreter is faster, because it only traverses the tree, without building a new one. The\n",
    "MiniCAS virtual machine traverses the tree once, at compile time. The function `lambdify` goes one\n",
    "step further: it writes Python source code and compiles it with the built-in compiler. This can be\n",
    "seen in the code it generated:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "178d28ea",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(inspect.getsource(f_math))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b05097d0",
   "metadata": {},
   "source": [
    "It is the same idea as the compiler from Lecture 3: we turn the expression tree into a program\n",
    "once. Here, however, the program is a Python function executed by the CPython interpreter, and in\n",
    "the `\"numpy\"` version the loop over the points runs in C. SymPy can also translate expressions into\n",
    "code in C and other languages (`sp.ccode`, the `sympy.utilities.codegen` module) or, for high\n",
    "precision, into functions of the mpmath library (`lambdify(..., \"mpmath\")`).\n",
    "\n",
    "Let us return to the profiler example from part 1. The trapezoidal rule with values computed by\n",
    "`subs` spent almost all of its time in SymPy. After replacing `subs` with `lambdify`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1e6cd561",
   "metadata": {},
   "outputs": [],
   "source": [
    "f_calka = sp.exp(-x**2)\n",
    "g_math = sp.lambdify(x, f_calka, \"math\")\n",
    "g_numpy = sp.lambdify(x, f_calka, \"numpy\")\n",
    "\n",
    "\n",
    "def trapezy_subs(n):\n",
    "    clear_cache()\n",
    "    h = sp.Rational(1, n)\n",
    "    ys = [float(f_calka.subs(x, k * h)) for k in range(n + 1)]\n",
    "    return (sum(ys) - (ys[0] + ys[-1]) / 2) / n\n",
    "\n",
    "\n",
    "def trapezy_lambdify(n):\n",
    "    ys = [g_math(k / n) for k in range(n + 1)]\n",
    "    return (sum(ys) - (ys[0] + ys[-1]) / 2) / n\n",
    "\n",
    "\n",
    "def trapezy_numpy(n):\n",
    "    ys = g_numpy(np.linspace(0, 1, n + 1))\n",
    "    return (ys.sum() - (ys[0] + ys[-1]) / 2) / n\n",
    "\n",
    "\n",
    "czasy_trapezy = porownaj({\"subs (część 1)\": trapezy_subs,\n",
    "                          \"lambdify, math\": trapezy_lambdify,\n",
    "                          \"lambdify, numpy\": trapezy_numpy}, 200,\n",
    "                         zgodne=lambda a, b: abs(a - b) < 1e-14)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b1fe8b1",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_trapezy[\"subs (część 1)\"]\n",
    "        > 1000 * czasy_trapezy[\"lambdify, math\"],\n",
    "        \"lambdify przyspiesza trapezy tysiące razy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71d56d64",
   "metadata": {},
   "source": [
    "The same computation is now thousands of times faster. We announced this in\n",
    "{doc}`part 1 <p1_pomiar>` after reading the profile: it pays to speed up the part of the program\n",
    "where the time really goes.\n",
    "\n",
    "## Polynomials: `Poly` instead of expressions\n",
    "\n",
    "A SymPy expression is a general tree: a sum of products of powers. For polynomials, SymPy has a\n",
    "separate representation, the class `Poly`. It stores only the exponents and the coefficients, and\n",
    "it multiplies polynomials with algorithms for polynomials over a specific ring, here over\n",
    "$\\mathbb Z$. This is the same choice that MiniCAS made in Lecture 3 (§3.3): a polynomial is a set\n",
    "of monomials, that is, of exponent tuples with coefficients, not a tree. Let us multiply two\n",
    "polynomials of degree $8$ in three variables:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d7bb61a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "y, z = sp.symbols(\"y z\")\n",
    "e1, e2 = (x + y + z + 1)**8, (x - y + 2*z - 1)**8\n",
    "P1, P2 = sp.Poly(e1, x, y, z), sp.Poly(e2, x, y, z)\n",
    "\n",
    "\n",
    "def iloczyn_expand():\n",
    "    clear_cache()\n",
    "    return sp.expand(e1 * e2)\n",
    "\n",
    "\n",
    "def iloczyn_poly():\n",
    "    clear_cache()\n",
    "    return P1 * P2\n",
    "\n",
    "\n",
    "def iloczyn_poly_z_zamiana():\n",
    "    clear_cache()\n",
    "    return (sp.Poly(e1, x, y, z) * sp.Poly(e2, x, y, z)).as_expr()\n",
    "\n",
    "\n",
    "wynik = iloczyn_expand()\n",
    "assert sp.Poly(wynik, x, y, z) == iloczyn_poly()\n",
    "print(\"jednomianów w iloczynie:\", len(iloczyn_poly().terms()))\n",
    "czasy_poly = porownaj({\n",
    "    \"expand(e1 * e2)\": iloczyn_expand,\n",
    "    \"Poly * Poly\": iloczyn_poly,\n",
    "    \"Poly z zamianą tam i z powrotem\": iloczyn_poly_z_zamiana},\n",
    "    zgodne=lambda a, b: True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4232b561",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(30 < czasy_poly[\"expand(e1 * e2)\"] / czasy_poly[\"Poly * Poly\"] < 1000,\n",
    "        \"Poly mnoży kilkadziesiąt–kilkaset razy szybciej\")\n",
    "upewnij(czasy_poly[\"expand(e1 * e2)\"]\n",
    "        > 5 * czasy_poly[\"Poly z zamianą tam i z powrotem\"],\n",
    "        \"nawet z zamianą Poly jest kilka razy szybsze\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "136824dc",
   "metadata": {},
   "source": [
    "We checked that the results agree before the measurement (`assert`). Multiplication in `Poly` is\n",
    "tens to hundreds of times faster, and even with the conversion of the expression to `Poly` and\n",
    "back, it beats `expand` many times over. When a computation consists of many operations on\n",
    "polynomials (division with remainder, GCD, Gröbner bases), we convert the expression to `Poly`\n",
    "once, at the beginning.\n",
    "\n",
    "## `simplify` or a specific operation\n",
    "\n",
    "The function `sp.simplify` tries many simplification strategies and picks the shortest result. It\n",
    "is convenient but slow, and the form of the result is hard to predict. When we know what we want,\n",
    "we call a specific operation: `cancel` (reducing a fraction), `factor`, `expand`, `together`,\n",
    "`trigsimp`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb0381be",
   "metadata": {},
   "outputs": [],
   "source": [
    "r = (x**6 - 1) / (x**2 - 1)\n",
    "\n",
    "\n",
    "def przez_simplify():\n",
    "    clear_cache()\n",
    "    return sp.simplify(r)\n",
    "\n",
    "\n",
    "def przez_cancel():\n",
    "    clear_cache()\n",
    "    return sp.cancel(r)\n",
    "\n",
    "\n",
    "def przez_factor():\n",
    "    clear_cache()\n",
    "    return sp.factor(r)\n",
    "\n",
    "\n",
    "for f in (przez_simplify, przez_cancel, przez_factor):\n",
    "    print(f\"{f.__name__:15} {f()}\")\n",
    "czasy_upraszczanie = porownaj({\"simplify\": przez_simplify,\n",
    "                               \"cancel\": przez_cancel,\n",
    "                               \"factor\": przez_factor},\n",
    "                              zgodne=lambda a, b: sp.cancel(a - b) == 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eaffa370",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_upraszczanie[\"simplify\"] > 2 * max(czasy_upraszczanie[\"cancel\"],\n",
    "                                                 czasy_upraszczanie[\"factor\"]),\n",
    "        \"simplify jest kilka razy wolniejsze od cancel i factor\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "29589943",
   "metadata": {},
   "source": [
    "Even more important than time is the certainty of the result. In Lecture 5 (§5.3) we proved\n",
    "formulas for sums of powers by checking that $S(n)-S(n-1)-n^p$ is the zero polynomial. The\n",
    "function `udowodnij` did this with `sp.expand(...) == 0`, not with `sp.simplify(...) == 0`. For\n",
    "polynomials, `expand` is a **decision procedure**: a polynomial is zero if and only if nothing is\n",
    "left after expanding and collecting like terms. The function `simplify` is a heuristic. When it\n",
    "does not return zero, we do not know whether the expression is nonzero or `simplify` merely failed\n",
    "to find a way. For expressions with elementary functions, one cannot do better. Richardson’s\n",
    "theorem ({doc}`deep dive <../richardson/richardson>`) says that already for expressions with the\n",
    "sine and the absolute value, there is no algorithm that decides whether an expression is\n",
    "identically zero."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5cac40e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "n, k = sp.symbols(\"n k\", integer=True, positive=True)\n",
    "S = sp.expand(sp.summation(k**10, (k, 1, n)))\n",
    "tozsamosc = S - S.subs(n, n - 1) - n**10\n",
    "\n",
    "\n",
    "def zero_przez_expand():\n",
    "    clear_cache()\n",
    "    return sp.expand(tozsamosc) == 0\n",
    "\n",
    "\n",
    "def zero_przez_simplify():\n",
    "    clear_cache()\n",
    "    return sp.simplify(tozsamosc) == 0\n",
    "\n",
    "\n",
    "czasy_zero = porownaj({\"simplify(...) == 0\": zero_przez_simplify,\n",
    "                       \"expand(...) == 0\": zero_przez_expand})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "31307f8d",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_zero[\"simplify(...) == 0\"]\n",
    "        > 1.5 * czasy_zero[\"expand(...) == 0\"],\n",
    "        \"expand rozstrzyga tożsamość szybciej niż simplify\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97654bda",
   "metadata": {},
   "source": [
    "Here both functions answer correctly, but `expand` does so faster and with a guarantee.\n",
    "\n",
    "## Rational numbers: `Rational`, `Fraction`, and a better algorithm\n",
    "\n",
    "SymPy numbers (`sp.Rational`, `sp.Integer`) are expression objects. Every operation goes through\n",
    "SymPy’s machinery: type checking, ordering of arguments, the cache. In a loop with thousands of\n",
    "operations on numbers, `fractions.Fraction` works better. Better still is to change the algorithm.\n",
    "Let us compute the harmonic number $H_{2000}=1+\\tfrac12+\\dots+\\tfrac1{2000}$ exactly. Summing the\n",
    "fractions one after another reduces the result after every addition, and reduction requires the\n",
    "GCD of ever longer numbers. **Binary splitting** divides the summation range into halves, sums each\n",
    "half recursively as a pair of integers (numerator, denominator) without reducing, and reduces only\n",
    "once, at the end:\n",
    "\n",
    "$$\n",
    "\\sum_{a\\le k<b}\\frac1k=\\frac{P}{Q},\\qquad P=P_1Q_2+P_2Q_1,\\quad Q=Q_1Q_2,\n",
    "$$\n",
    "\n",
    "where $P_1/Q_1$ and $P_2/Q_2$ are the sums over the two halves. At every step, the numbers being\n",
    "multiplied have similar lengths, and it is on such multiplications that fast big-integer\n",
    "arithmetic gains the most."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "18f0c93d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def h_rational(n):\n",
    "    clear_cache()\n",
    "    return sum(sp.Rational(1, k) for k in range(1, n + 1))\n",
    "\n",
    "\n",
    "def h_fraction(n):\n",
    "    return sum(Fraction(1, k) for k in range(1, n + 1))\n",
    "\n",
    "\n",
    "def dzielenie_binarne(a, b):\n",
    "    \"\"\"Suma 1/k dla a <= k < b jako para (licznik, mianownik).\"\"\"\n",
    "    if b - a == 1:\n",
    "        return 1, a\n",
    "    s = (a + b) // 2\n",
    "    p1, q1 = dzielenie_binarne(a, s)\n",
    "    p2, q2 = dzielenie_binarne(s, b)\n",
    "    return p1 * q2 + p2 * q1, q1 * q2\n",
    "\n",
    "\n",
    "def h_binarnie(n):\n",
    "    return Fraction(*dzielenie_binarne(1, n + 1))     # Fraction skraca raz\n",
    "\n",
    "\n",
    "def h_harmonic_od_zera(n):\n",
    "    sp.harmonic.harmonic_cache.clear()     # tego clear_cache nie czyści\n",
    "    clear_cache()\n",
    "    return sp.harmonic(n)\n",
    "\n",
    "\n",
    "def jako_fraction(q):\n",
    "    return Fraction(int(sp.numer(q)), int(sp.denom(q)))\n",
    "\n",
    "\n",
    "czasy_h = porownaj({\"suma sp.Rational\": h_rational,\n",
    "                    \"suma Fraction\": h_fraction,\n",
    "                    \"dzielenie binarne\": h_binarnie,\n",
    "                    \"sp.harmonic od zera\": h_harmonic_od_zera,\n",
    "                    \"sp.harmonic z pamięcią\": sp.harmonic}, 2000,\n",
    "                   zgodne=lambda a, b: jako_fraction(a) == jako_fraction(b))\n",
    "H = h_binarnie(2000)\n",
    "print(f\"H_2000: licznik ma {len(str(H.numerator))} cyfr,\",\n",
    "      f\"mianownik {len(str(H.denominator))}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0f5756f",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "c = czasy_h\n",
    "upewnij(3 < c[\"suma sp.Rational\"] / c[\"suma Fraction\"] < 10,\n",
    "        \"Fraction jest kilka razy szybsze od Rational\")\n",
    "upewnij(c[\"suma Fraction\"] > 1.5 * c[\"dzielenie binarne\"],\n",
    "        \"dzielenie binarne jest szybsze od sumy Fraction\")\n",
    "upewnij(c[\"sp.harmonic od zera\"] > 0.3 * c[\"suma sp.Rational\"],\n",
    "        \"sp.harmonic od zera jest porównywalnie wolne jak suma Rational\")\n",
    "upewnij(c[\"sp.harmonic z pamięcią\"] < 1e-5,\n",
    "        \"sp.harmonic z pamięcią trwa ułamek mikrosekundy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "952c6145",
   "metadata": {},
   "source": [
    "The sum of `Fraction` numbers is several times faster than the sum of `sp.Rational` numbers, and\n",
    "binary splitting is faster still. The advantage of binary splitting grows with $n$ (exercise 3).\n",
    "The same technique is used to compute constants such as $\\pi$ or $e$ to millions of digits\n",
    "(B. Haible, T. Papanikolaou, *Fast multiprecision evaluation of series of rational numbers*, 1998).\n",
    "\n",
    "The last two rows are a cautionary tale about measurement. Computed from scratch, `sp.harmonic`\n",
    "adds up `sp.Rational` numbers one after another, so it is as slow as our sum. The second time,\n",
    "however, it takes a fraction of a microsecond. SymPy remembers all the computed $H_k$ in its own\n",
    "dictionary `sp.harmonic.harmonic_cache`, which `clear_cache` does not clear. Had we not noticed\n",
    "this, we would have declared `sp.harmonic` the fastest algorithm, while measuring nothing but a\n",
    "dictionary lookup.\n",
    "\n",
    "## Summary\n",
    "\n",
    "* We do the symbolic computation **once** and turn the result into a numerical function with\n",
    "  `sp.lambdify`. This speeds up the evaluation thousands of times: `subs` in a loop is the slowest\n",
    "  way to compute values.\n",
    "* `lambdify` is a compiler like the one from Lecture 3: it turns the expression tree into Python\n",
    "  code, and with the `\"numpy\"` module it computes on whole arrays.\n",
    "* For polynomials, we use `Poly`, not general expressions.\n",
    "* Instead of `simplify`, we choose a specific operation (`cancel`, `factor`, `expand`). For\n",
    "  polynomial identities, `expand(...) == 0` is faster and gives a certain answer.\n",
    "* In loops over rational numbers, we use `Fraction`, and a better algorithm (binary splitting)\n",
    "  gives even more.\n",
    "* When timing SymPy, we clear SymPy’s cache (`clear_cache`) and remember that some functions have\n",
    "  caches of their own (`sp.harmonic`).\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. ★ Plot the interpolating polynomial from Lecture 5 at $10^4$ points, computing the values with\n",
    "   `subs` and with `lambdify`. Measure both running times.\n",
    "2. ★ Compare `sp.diff` with `expand` and with `simplify` for the derivative of order $10$ of the\n",
    "   function $e^{x}\\sin x$. Which form of the result is shorter?\n",
    "3. ★★ Compare the `Fraction` sum with binary splitting for $H_n$, $n=10^3, 10^4, 10^5$. How does\n",
    "   the ratio of the running times grow?\n",
    "4. ★★ Time `sp.factor` for $x^n-1$ and $n=60, 120, 240$. Explain the number of factors\n",
    "   (cyclotomic polynomials) and compare it with the number of divisors of $n$.\n",
    "5. ★★ Use `sp.lambdify(x, w, \"mpmath\")` to compute $\\sin(x+1)+\\cos(x+1)$ to $50$ digits at the\n",
    "   point $x=10^{20}$. Compare with the `\"math\"` version. Which one is correct, and why?"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
