{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8a6ce4b9",
   "metadata": {},
   "source": [
    "# Part 6. Ready-made algorithms: SciPy and linear algebra\n",
    "\n",
    "In part 5 we moved **our own** algorithms into NumPy. The next rung of laziness is to use\n",
    "algorithms that someone has already written and refined. NumPy and SciPy rely on libraries that\n",
    "have been developed for decades: LAPACK and BLAS (linear algebra), QUADPACK (integration), and\n",
    "many others. They are faster than the simple implementations from the lectures, because they take\n",
    "care of the CPU cache and of vector instructions. They are often also more accurate, because they\n",
    "choose pivots, estimate the error, and recognize special cases. We write the implementations from\n",
    "Lectures 5 and 6 in order to understand the methods. In actual computations we use libraries,\n",
    "unless we need a result that is **exact** or **verifiable**. Then we return to rational numbers,\n",
    "but it will turn out that even here it is possible to be lazy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8a5622e6",
   "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": "25e5e106",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "from fractions import Fraction\n",
    "\n",
    "import numpy as np\n",
    "import scipy.integrate\n",
    "import scipy.optimize\n",
    "import scipy.special\n",
    "import sympy as sp\n",
    "from scipy.interpolate import BarycentricInterpolator\n",
    "\n",
    "srodowisko(\"numpy\", \"scipy\", \"sympy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c36ca0e",
   "metadata": {},
   "source": [
    "## Gaussian elimination vs. `numpy.linalg.solve`\n",
    "\n",
    "In Lecture 6 (§6.1) we wrote Gaussian elimination\n",
    "with partial pivoting. The same function works on `float` and `Fraction` numbers.\n",
    "Let us compare it on `float` numbers with the function `np.linalg.solve`. That function calls\n",
    "a routine from the LAPACK library: LU decomposition with partial pivoting, performed in blocks so\n",
    "that most of the work is matrix multiplication."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b780c6bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "def eliminacja(A, b):\n",
    "    \"\"\"Eliminacja Gaussa z częściowym wyborem elementu głównego (wykład 6).\"\"\"\n",
    "    n = len(A)\n",
    "    M = [list(w) + [bi] for w, bi in zip(A, b)]\n",
    "    for k in range(n):\n",
    "        p = max(range(k, n), key=lambda i: abs(M[i][k]))\n",
    "        M[k], M[p] = M[p], M[k]\n",
    "        for i in range(k + 1, n):\n",
    "            m = M[i][k] / M[k][k]\n",
    "            M[i] = [a - m * c for a, c in zip(M[i], M[k])]\n",
    "    x = [0] * n\n",
    "    for i in reversed(range(n)):\n",
    "        s = M[i][n] - sum(M[i][j] * x[j] for j in range(i + 1, n))\n",
    "        x[i] = s / M[i][i]\n",
    "    return x\n",
    "\n",
    "\n",
    "los = np.random.default_rng(2026)\n",
    "\n",
    "\n",
    "def uklad(n):\n",
    "    \"\"\"Losowy układ z całkowitymi współczynnikami od -9 do 9.\"\"\"\n",
    "    return los.integers(-9, 10, (n, n)), los.integers(-9, 10, n)\n",
    "\n",
    "\n",
    "rozmiary = [25, 50, 100, 200]\n",
    "czasy_python, czasy_lapack = [], []\n",
    "for n in rozmiary:\n",
    "    A, b = uklad(n)\n",
    "    Af, bf = A.astype(float), b.astype(float)\n",
    "    Al, bl = Af.tolist(), bf.tolist()\n",
    "    assert np.allclose(eliminacja(Al, bl), np.linalg.solve(Af, bf))\n",
    "    czasy_python.append(zmierz(eliminacja, Al, bl))\n",
    "    czasy_lapack.append(zmierz(np.linalg.solve, Af, bf))\n",
    "    t_py, t_la = czasy_python[-1], czasy_lapack[-1]\n",
    "    print(f\"n = {n:3}:  Python {czas(t_py):>9}   LAPACK {czas(t_la):>9}\",\n",
    "          f\"  przyspieszenie {krotnosc(t_py / t_la):>6}\")\n",
    "wykres_skalowania(rozmiary, {\"eliminacja Gaussa w Pythonie\": czasy_python,\n",
    "                             \"np.linalg.solve (LAPACK)\": czasy_lapack},\n",
    "                  \"Rozwiązanie układu n × n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4cbae746",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "przysp = [p / l for p, l in zip(czasy_python, czasy_lapack)]\n",
    "upewnij(przysp[-1] > 100 and przysp[-1] > przysp[0],\n",
    "        \"LAPACK jest dla n = 200 ponad sto razy szybszy, \"\n",
    "        \"a przewaga rośnie z n\")\n",
    "nachylenie = math.log(czasy_python[-1] / czasy_python[-2]) / math.log(2)\n",
    "upewnij(2.4 < nachylenie < 3.6, \"czas eliminacji w Pythonie rośnie jak n³\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17084f60",
   "metadata": {},
   "source": [
    "The time of the elimination in Python grows like $n^3$: a system twice as large means\n",
    "a computation about eight times longer, and a slope of $3$ on the log-log plot. LAPACK performs\n",
    "the same number of operations, but its advantage grows with $n$ and for $n=200$ exceeds a factor\n",
    "of a hundred. For small systems, LAPACK’s time is largely the fixed cost of the call. For large\n",
    "ones, what counts is that the routine performs the operations in blocks that fit in the CPU cache.\n",
    "\n",
    "## Matrix multiplication: three loops and `@`\n",
    "\n",
    "Matrix multiplication is the most thoroughly optimized operation in numerical computing. The\n",
    "`dgemm` routine from the BLAS library, called by the `@` operator, has versions written separately\n",
    "for many processors. In the instructor’s study, single-threaded BLAS turned out to be many times\n",
    "faster even than carefully written C code running on four cores. Let us compare three loops in\n",
    "Python, a neater version with `zip` and `sum`, and the `@` operator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91d4aed8",
   "metadata": {},
   "outputs": [],
   "source": [
    "def mnozenie_petle(A, B):\n",
    "    n, m, p = len(A), len(B), len(B[0])\n",
    "    C = [[0.0] * p for _ in range(n)]\n",
    "    for i in range(n):\n",
    "        for j in range(p):\n",
    "            s = 0.0\n",
    "            for k in range(m):\n",
    "                s += A[i][k] * B[k][j]\n",
    "            C[i][j] = s\n",
    "    return C\n",
    "\n",
    "\n",
    "def mnozenie_zip(A, B):\n",
    "    kolumny = list(zip(*B))\n",
    "    return [[sum(a * b for a, b in zip(wiersz, k)) for k in kolumny]\n",
    "            for wiersz in A]\n",
    "\n",
    "\n",
    "A, B = los.random((120, 120)), los.random((120, 120))\n",
    "Al, Bl = A.tolist(), B.tolist()\n",
    "czasy_mnozenie = porownaj({\"trzy pętle\": lambda: mnozenie_petle(Al, Bl),\n",
    "                           \"zip i sum\": lambda: mnozenie_zip(Al, Bl),\n",
    "                           \"A @ B (BLAS)\": lambda: A @ B},\n",
    "                          zgodne=lambda X, Y: np.allclose(X, Y))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b2698d13",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_mnozenie[\"trzy pętle\"] > 1000 * czasy_mnozenie[\"A @ B (BLAS)\"],\n",
    "        \"BLAS mnoży ponad tysiąc razy szybciej\")\n",
    "upewnij(0.5 < czasy_mnozenie[\"trzy pętle\"] / czasy_mnozenie[\"zip i sum\"] < 2,\n",
    "        \"zgrabniejszy zapis w Pythonie nie zmienia rzędu czasu\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0faaaa81",
   "metadata": {},
   "source": [
    "The `@` operator is more than a thousand times faster than the loops. The neater notation with\n",
    "`zip` and `sum` does not help: it changes the way the code is written, but not the fact that each\n",
    "of the $120^3$ multiplications is executed by the interpreter.\n",
    "\n",
    "## Exact computation: rational numbers and checking\n",
    "\n",
    "In Lecture 6 we also solved systems exactly, with `Fraction` numbers, because an approximation in\n",
    "`float` numbers can be worthless, as for the Hilbert matrix. Exact computation is slower: the\n",
    "numerators and denominators grow, and multiplying long numbers is costly. Let us compare our\n",
    "elimination on `Fraction` numbers with the `LUsolve` method from SymPy. Let us also measure how\n",
    "much it costs to **check** a given solution, that is, to multiply out $Ax$ and compare it with\n",
    "$b$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aca14f9b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sympy.core.cache import clear_cache\n",
    "\n",
    "\n",
    "def sprawdz(A, x, b):\n",
    "    \"\"\"Kontroler: czy A x = b dokładnie?\"\"\"\n",
    "    return all(sum(a * xi for a, xi in zip(w, x)) == bi for w, bi in zip(A, b))\n",
    "\n",
    "\n",
    "def lu_sympy(As, bs):\n",
    "    clear_cache()                  # bez pamięci podręcznej (zob. część 1)\n",
    "    return As.LUsolve(bs)\n",
    "\n",
    "\n",
    "wiersze = []\n",
    "for n in (20, 40):\n",
    "    A, b = uklad(n)\n",
    "    Aq = [[Fraction(int(a)) for a in w] for w in A]\n",
    "    bq = [Fraction(int(v)) for v in b]\n",
    "    x = eliminacja(Aq, bq)\n",
    "    assert sprawdz(Aq, x, bq)\n",
    "    t_rozw, t_spr = zmierz(eliminacja, Aq, bq), zmierz(sprawdz, Aq, x, bq)\n",
    "    As, bs = sp.Matrix(A.tolist()), sp.Matrix(b.tolist())\n",
    "    assert list(lu_sympy(As, bs)) == x\n",
    "    t_sympy = zmierz(lu_sympy, As, bs)\n",
    "    cyfry = max(len(str(v.denominator)) for v in x)\n",
    "    wiersze.append((n, t_rozw, t_sympy, t_spr, cyfry))\n",
    "print(f\"{'n':>3} {'Fraction':>10} {'SymPy LUsolve':>14} {'sprawdzenie':>12}\"\n",
    "      f\" {'rozw./spr.':>11} {'cyfry mianownika':>17}\")\n",
    "for n, t_rozw, t_sympy, t_spr, cyfry in wiersze:\n",
    "    print(f\"{n:3} {czas(t_rozw):>10} {czas(t_sympy):>14} {czas(t_spr):>12}\"\n",
    "          f\" {krotnosc(t_rozw / t_spr):>11} {cyfry:>17}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "655198bf",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(all(t_sympy > t_rozw for _, t_rozw, t_sympy, _, _ in wiersze),\n",
    "        \"SymPy LUsolve jest wolniejsze od eliminacji na Fraction\")\n",
    "r20, r40 = (t_rozw / t_spr for _, t_rozw, _, t_spr, _ in wiersze)\n",
    "upewnij(r20 > 3 and r40 > r20,\n",
    "        \"sprawdzenie jest wielokrotnie tańsze, a przewaga rośnie z n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3810c886",
   "metadata": {},
   "source": [
    "Two conclusions. A general-purpose symbolic library is not always the fastest: `LUsolve` in SymPy\n",
    "is slower than a dozen or so lines on `Fraction` numbers, among other reasons because in SymPy\n",
    "every number is an expression object. The second conclusion is more important. **Checking**\n",
    "a solution is many times cheaper than finding it, and the advantage grows with $n$: solving\n",
    "requires on the order of $n^3$ operations, checking on the order of $n^2$. This is the same\n",
    "asymmetry on which the whole course rests: a result may be found by a fast and complicated program\n",
    "(a library, a heuristic, a language model), and trust comes from a simple checker.\n",
    "\n",
    "## Roots of equations: bisection vs. `brentq`\n",
    "\n",
    "Bisection from Lecture 5 (§5.1) needs about\n",
    "$\\log_2\\bigl((b-a)/\\varepsilon\\bigr)$ function values. Brent’s method (`scipy.optimize.brentq`)\n",
    "also maintains an interval with a sign change, so it is just as reliable. As long as it can,\n",
    "however, it takes interpolation steps, which converge much faster. When the function is cheap,\n",
    "this does not matter. When each of its values is expensive, the number of calls determines the\n",
    "time. We look for $t$ such that $\\int_0^t e^{-x^2}\\,dx=\\tfrac12$. Each value of the function is\n",
    "an integral computed numerically."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f6895b4",
   "metadata": {},
   "outputs": [],
   "source": [
    "wywolania = 0\n",
    "\n",
    "\n",
    "def f(t):\n",
    "    global wywolania\n",
    "    wywolania += 1\n",
    "    return scipy.integrate.quad(lambda x: math.exp(-x * x), 0, t)[0] - 0.5\n",
    "\n",
    "\n",
    "def bisekcja(f, a, b, eps):\n",
    "    fa = f(a)\n",
    "    while b - a > eps:\n",
    "        m = (a + b) / 2\n",
    "        fm = f(m)\n",
    "        if (fa < 0) == (fm < 0):\n",
    "            a, fa = m, fm\n",
    "        else:\n",
    "            b = m\n",
    "    return (a + b) / 2\n",
    "\n",
    "\n",
    "dokladnie = scipy.special.erfinv(1 / math.sqrt(math.pi))  # erf(t) = 1/√π\n",
    "METODY = {\"bisekcja\": lambda: bisekcja(f, 0.0, 2.0, 1e-12),\n",
    "          \"brentq\": lambda: scipy.optimize.brentq(f, 0.0, 2.0, xtol=1e-12)}\n",
    "for nazwa, metoda in METODY.items():\n",
    "    wywolania = 0\n",
    "    t = metoda()\n",
    "    print(f\"{nazwa:9} t = {t:.15f}  błąd {abs(t - dokladnie):.1e}\",\n",
    "          f\" wartości f: {wywolania}\")\n",
    "czasy_pierwiastek = porownaj(METODY, zgodne=lambda a, b: abs(a - b) < 1e-11)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ade6bf6a",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_pierwiastek[\"bisekcja\"] > 2 * czasy_pierwiastek[\"brentq\"],\n",
    "        \"brentq jest kilka razy szybsze, bo liczy f kilka razy rzadziej\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f261d661",
   "metadata": {},
   "source": [
    "Brent’s method needs several times fewer function values and is therefore several times faster.\n",
    "We compare the result with a formula: $\\int_0^t e^{-x^2}dx=\\tfrac{\\sqrt\\pi}{2}\\operatorname{erf}(t)$,\n",
    "so $t=\\operatorname{erf}^{-1}(1/\\sqrt\\pi)$, and the inverse of $\\operatorname{erf}$ is available in\n",
    "`scipy.special`.\n",
    "\n",
    "## Interpolation: Lagrange’s formula vs. the barycentric form\n",
    "\n",
    "In Lecture 5 (§5.3) we computed the interpolating polynomial for\n",
    "Runge’s function with the `BarycentricInterpolator` class from SciPy. Lagrange’s formula applied\n",
    "directly, $p(t)=\\sum_i y_i\\prod_{j\\ne i}\\frac{t-x_j}{x_i-x_j}$, requires on the order of $n^2$\n",
    "operations at each point $t$. The barycentric form computes the weights\n",
    "$w_i=1/\\prod_{j\\ne i}(x_i-x_j)$ once, and after that on the order of $n$ operations suffice at\n",
    "each point:\n",
    "\n",
    "$$\n",
    "p(t)=\\frac{\\sum_i \\frac{w_i}{t-x_i}\\,y_i}{\\sum_i \\frac{w_i}{t-x_i}} .\n",
    "$$\n",
    "\n",
    "Moreover, it is numerically stable (J.-P. Berrut, L. N. Trefethen, *Barycentric Lagrange\n",
    "Interpolation*, SIAM Review 2004)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e284fe5",
   "metadata": {},
   "outputs": [],
   "source": [
    "def runge(t):\n",
    "    return 1 / (1 + 25 * t**2)\n",
    "\n",
    "\n",
    "def lagrange(X, Y, t):\n",
    "    s = 0.0\n",
    "    for i, (xi, yi) in enumerate(zip(X, Y)):\n",
    "        l = 1.0\n",
    "        for j, xj in enumerate(X):\n",
    "            if j != i:\n",
    "                l *= (t - xj) / (xi - xj)\n",
    "        s += yi * l\n",
    "    return s\n",
    "\n",
    "\n",
    "n = 40\n",
    "X = np.cos((2 * np.arange(n + 1) + 1) * np.pi / (2 * n + 2))  # Czebyszew\n",
    "Y = runge(X)\n",
    "siatka = np.linspace(-1, 1, 2001)\n",
    "Xl, Yl, sl = X.tolist(), Y.tolist(), siatka.tolist()\n",
    "czasy_interp = porownaj({\n",
    "    \"wzór Lagrange'a\": lambda: np.array([lagrange(Xl, Yl, t) for t in sl]),\n",
    "    \"BarycentricInterpolator\": lambda: BarycentricInterpolator(X, Y)(siatka)},\n",
    "    zgodne=lambda a, b: np.allclose(a, b, rtol=0, atol=1e-12))\n",
    "blad = np.max(np.abs(BarycentricInterpolator(X, Y)(siatka) - runge(siatka)))\n",
    "print(f\"największy błąd interpolacji: {blad:.2e}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bae7764b",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_interp[\"wzór Lagrange'a\"]\n",
    "        > 100 * czasy_interp[\"BarycentricInterpolator\"],\n",
    "        \"postać barycentryczna jest ponad sto razy szybsza\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "692b8807",
   "metadata": {},
   "source": [
    "The barycentric form is more than a hundred times faster. Both programs give the same values up\n",
    "to $10^{-12}$.\n",
    "\n",
    "## Integration: the trapezoidal rule vs. `quad`\n",
    "\n",
    "The function `scipy.integrate.quad` uses the QUADPACK library. It applies a high-order\n",
    "Gauss–Kronrod quadrature and subdivides the interval only where the error estimate is too large.\n",
    "Let us count how many function values it needs for $\\int_0^1 e^{-x^2}dx$ and compare this with\n",
    "the trapezoidal rule from Lecture 5."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75c9b222",
   "metadata": {},
   "outputs": [],
   "source": [
    "wartosci = 0\n",
    "\n",
    "\n",
    "def g(x):\n",
    "    global wartosci\n",
    "    wartosci += 1\n",
    "    return math.exp(-x * x)\n",
    "\n",
    "\n",
    "def trapezy(f, a, b, n):\n",
    "    h = (b - a) / n\n",
    "    return h * (f(a) / 2 + sum(f(a + i * h) for i in range(1, n)) + f(b) / 2)\n",
    "\n",
    "\n",
    "dokladnie = math.sqrt(math.pi) / 2 * math.erf(1)\n",
    "print(f\"{'metoda':18} {'wartości f':>10} {'błąd':>9}\")\n",
    "for n in (10, 100, 1000, 10000):\n",
    "    wartosci = 0\n",
    "    blad = abs(trapezy(g, 0, 1, n) - dokladnie)\n",
    "    print(f\"{'trapezy, n = ' + str(n):18} {wartosci:10} {blad:9.1e}\")\n",
    "wartosci = 0\n",
    "wynik, oszacowanie = scipy.integrate.quad(g, 0, 1)\n",
    "wartosci_quad = wartosci\n",
    "print(f\"{'quad':18} {wartosci:10} {abs(wynik - dokladnie):9.1e}\",\n",
    "      f\"  (oszacowanie błędu: {oszacowanie:.1e})\")\n",
    "czasy_calka = porownaj({\"trapezy, n = 10000\": lambda: trapezy(g, 0, 1, 10000),\n",
    "                        \"quad\": lambda: scipy.integrate.quad(g, 0, 1)[0]},\n",
    "                       zgodne=lambda a, b: abs(a - b) < 1e-8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2300a76b",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_calka[\"trapezy, n = 10000\"] > 20 * czasy_calka[\"quad\"],\n",
    "        \"quad jest wielokrotnie szybsze i dokładniejsze\")\n",
    "upewnij(10 <= wartosci_quad < 100 and abs(wynik - dokladnie) < 1e-15,\n",
    "        \"quad osiąga dokładność maszynową po kilkudziesięciu wartościach\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3f12a826",
   "metadata": {},
   "source": [
    "The trapezoidal rule needs ten thousand function values to reach an error on the order of\n",
    "$10^{-10}$. The function `quad` reaches machine precision after a few dozen values (the exact\n",
    "number is in the table) and reports an error estimate. The trapezoidal rule does have its\n",
    "advantages, though. It works on measured data, when the function values are known only at fixed\n",
    "points. For periodic functions integrated over a full period, it is surprisingly accurate, as the\n",
    "Euler–Maclaurin formula from Lab 7 shows.\n",
    "\n",
    "## Summary\n",
    "\n",
    "* The LAPACK and BLAS libraries (through `np.linalg` and the `@` operator) solve systems and\n",
    "  multiply matrices hundreds and thousands of times faster than loops in Python. The advantage\n",
    "  grows with the size.\n",
    "* SciPy’s ready-made methods (`brentq`, `BarycentricInterpolator`, `quad`) are not only faster:\n",
    "  they compute fewer function values, they are stable, and they estimate the error.\n",
    "* When we need an exact result, we compute with rational numbers. A general-purpose symbolic\n",
    "  library can then be slower than simple code on `Fraction`.\n",
    "* **Checking is cheaper than computing**: we verify the result of a fast, complicated program with\n",
    "  a simple checker.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. ★ Measure `np.linalg.inv(A) @ b` and `np.linalg.solve(A, b)` for $n=500$. Which version is\n",
    "   faster? Also compare the norms of the residuals $\\|Ax-b\\|$.\n",
    "2. ★ Compute the number of function values in bisection from the formula\n",
    "   $\\lceil\\log_2((b-a)/\\varepsilon)\\rceil+1$ and compare it with the counter `wywolania`.\n",
    "3. ★★ Write your own barycentric interpolation function (the weights and the formula from the\n",
    "   text) and compare it with `BarycentricInterpolator`. What happens when $t$ is equal to one of\n",
    "   the nodes?\n",
    "4. ★★ Solve the system with the Hilbert matrix $H_{12}$ exactly, and then check the solution with\n",
    "   the checker `sprawdz`. Measure both times."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
