{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "93d91ad1",
   "metadata": {},
   "source": [
    "# Part 5. NumPy: the loop moved to C\n",
    "\n",
    "A loop in Python pays for every step: the interpreter reads an instruction, checks the types of the\n",
    "objects, and creates a new object for the result. A NumPy array stores numbers of a single type\n",
    "next to one another in memory, and operations on whole arrays are carried out by loops written in\n",
    "C. This style is called **vectorization**. The programmer is lazy in the best sense: instead of\n",
    "writing a loop, they describe an operation on the whole array, and NumPy writes the loop. In this\n",
    "part we rewrite examples from Lecture 5 (Horner’s scheme, quadrature, Newton basins, the Monte\n",
    "Carlo method) and from Lab 8 (the Game of Life) in this style. At the end we collect the pitfalls:\n",
    "places where NumPy does not help or silently changes the result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44e59a04",
   "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": "d41b0c8a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "import random\n",
    "import sys\n",
    "import tracemalloc\n",
    "\n",
    "import numpy as np\n",
    "from scipy import integrate, signal\n",
    "\n",
    "srodowisko(\"numpy\", \"scipy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7557c6be",
   "metadata": {},
   "source": [
    "## List vs. array\n",
    "\n",
    "A list of `float` numbers is an array of pointers to separate objects, and every `float` object\n",
    "occupies $24$ bytes of memory. A NumPy array of type `float64` takes $8$ bytes per number, with no\n",
    "pointers. Let us compare the memory and the time needed to square a million numbers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "18dbe394",
   "metadata": {},
   "outputs": [],
   "source": [
    "lista = [0.1 * k for k in range(10**6)]\n",
    "tablica = np.array(lista)\n",
    "pamiec_listy = sys.getsizeof(lista) + sum(map(sys.getsizeof, lista))\n",
    "print(\"lista:  \", pamiec_listy, \"bajtów\")\n",
    "print(\"tablica:\", tablica.nbytes, \"bajtów + nagłówek\",\n",
    "      sys.getsizeof(tablica) - tablica.nbytes)\n",
    "\n",
    "\n",
    "def te_same(a, b):\n",
    "    \"\"\"Czy dwa wyniki (listy albo tablice) są identyczne co do bitu?\"\"\"\n",
    "    return np.array_equal(np.asarray(a), np.asarray(b))\n",
    "\n",
    "\n",
    "czasy_kwadraty = porownaj({\"lista składana\": lambda: [v * v for v in lista],\n",
    "                           \"tablica NumPy\": lambda: tablica * tablica},\n",
    "                          zgodne=te_same)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11dc745e",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "r = czasy_kwadraty[\"lista składana\"] / czasy_kwadraty[\"tablica NumPy\"]\n",
    "upewnij(30 < r < 1000,\n",
    "        \"tablica liczy kwadraty kilkadziesiąt–kilkaset razy szybciej\")\n",
    "upewnij(pamiec_listy > 3 * tablica.nbytes,\n",
    "        \"tablica zajmuje kilka razy mniej pamięci\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b30b8446",
   "metadata": {},
   "source": [
    "The array takes several times less memory, and it computes the squares tens to hundreds of times\n",
    "faster (the last column of the table). Moreover, the results are **identical** down to the bit:\n",
    "both programs perform the same multiplications of `float64` numbers, only in a different loop.\n",
    "\n",
    "## Horner’s scheme on the whole grid\n",
    "\n",
    "In Lecture 5 (§5.1) we plotted the values of the polynomial\n",
    "$(x-1)^7$ computed by Horner’s scheme near its root, point by point:\n",
    "`[p7(t) for t in ts]`. The function `horner` uses only multiplication and addition, so it also\n",
    "works unchanged on an array: instead of a number $t$ it receives an array of all the points at\n",
    "once. This is so-called *duck typing*. The function does not care about the type of its argument,\n",
    "only about whether it can be multiplied and added."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae977ee1",
   "metadata": {},
   "outputs": [],
   "source": [
    "wsp7 = [1, -7, 21, -35, 35, -21, 7, -1]          # (x - 1)^7\n",
    "\n",
    "\n",
    "def horner(wsp, t):\n",
    "    s = 0\n",
    "    for c in wsp:\n",
    "        s = s * t + c\n",
    "    return s\n",
    "\n",
    "\n",
    "ts = np.linspace(0.99, 1.01, 100001)\n",
    "ts_lista = ts.tolist()\n",
    "def horner_punkt_po_punkcie():\n",
    "    return np.array([horner(wsp7, t) for t in ts_lista])\n",
    "\n",
    "\n",
    "czasy_horner = porownaj({\"punkt po punkcie\": horner_punkt_po_punkcie,\n",
    "                         \"horner(wsp7, tablica)\": lambda: horner(wsp7, ts),\n",
    "                         \"np.polyval\": lambda: np.polyval(wsp7, ts)},\n",
    "                        zgodne=np.array_equal)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44d631d4",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "r = czasy_horner[\"punkt po punkcie\"] / czasy_horner[\"horner(wsp7, tablica)\"]\n",
    "upewnij(20 < r < 100, \"Horner na tablicy jest kilkadziesiąt razy szybszy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43f550c5",
   "metadata": {},
   "source": [
    "The same function called once on an array is several dozen times faster than a hundred thousand\n",
    "calls on numbers. The loop over the $8$ coefficients stayed in Python, but the loop over the points\n",
    "moved to NumPy. The ready-made `np.polyval` computes with the same scheme and gives the same bits\n",
    "(`zgodne=np.array_equal`).\n",
    "\n",
    "## Quadrature\n",
    "\n",
    "In Lecture 5 (§5.4) the trapezoidal rule comes in two\n",
    "versions: with a generator inside `sum` and with an array (`trapezy_wekt`). Let us compare them,\n",
    "together with the ready-made function `scipy.integrate.trapezoid`, for $\\int_0^1 e^x\\,dx$ and a\n",
    "million subintervals."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "89d08531",
   "metadata": {},
   "outputs": [],
   "source": [
    "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",
    "def trapezy_wekt(f, a, b, n):\n",
    "    ys = f(np.linspace(a, b, n + 1))\n",
    "    return (b - a) / n * (ys.sum() - (ys[0] + ys[-1]) / 2)\n",
    "\n",
    "\n",
    "def trapezy_scipy(f, a, b, n):\n",
    "    xs = np.linspace(a, b, n + 1)\n",
    "    return integrate.trapezoid(f(xs), xs)\n",
    "\n",
    "\n",
    "n = 10**6\n",
    "czasy_trapezy = porownaj({\n",
    "    \"generator i math.exp\": lambda: trapezy(math.exp, 0, 1, n),\n",
    "    \"tablica i np.exp\": lambda: trapezy_wekt(np.exp, 0, 1, n),\n",
    "    \"scipy.integrate.trapezoid\": lambda: trapezy_scipy(np.exp, 0, 1, n)},\n",
    "    zgodne=lambda a, b: abs(a - b) < 1e-12)\n",
    "roznica = trapezy(math.exp, 0, 1, n) - trapezy_wekt(np.exp, 0, 1, n)\n",
    "blad = trapezy_wekt(np.exp, 0, 1, n) - (math.e - 1)\n",
    "print(f\"różnica wersji: {roznica:.1e},  błąd metody: {blad:.4e},\",\n",
    "      f\" wzór h²(e-1)/12: {(1 / n)**2 / 12 * (math.e - 1):.4e}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64c20a14",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_trapezy[\"generator i math.exp\"]\n",
    "        > 5 * czasy_trapezy[\"tablica i np.exp\"],\n",
    "        \"wersja z tablicą jest wielokrotnie szybsza\")\n",
    "upewnij(abs(roznica) < 1e-2 * abs(blad),\n",
    "        \"różnica wersji jest o kilka rzędów mniejsza od błędu metody\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d81b848",
   "metadata": {},
   "source": [
    "The array version is many times faster. The results differ only in the last digits, because the\n",
    "terms are summed in a different order. This difference is several orders of magnitude smaller than\n",
    "the error of the trapezoidal rule itself, which agrees with the formula $h^2(e-1)/12$ from\n",
    "Lecture 5.\n",
    "\n",
    "## Newton basins: vectorizing over the starting points\n",
    "\n",
    "Newton’s method is sequential by nature: the step $x_{k+1}$ depends on $x_k$, so the steps cannot\n",
    "be performed all at once. In Lecture 5 (§5.2), however, we plotted the basins\n",
    "of attraction of the roots of $z^3=1$, that is, the outcome of the method for **every** starting\n",
    "point of a grid. Different starting points are independent of one another. So we vectorize over\n",
    "the points: a single array of complex numbers holds all the points of the grid, and we perform each\n",
    "Newton step on the whole array at once."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "51bbb81e",
   "metadata": {},
   "outputs": [],
   "source": [
    "PIERW = np.exp(2j * np.pi * np.arange(3) / 3)\n",
    "\n",
    "\n",
    "def basen_punktu(z, iteracje=40):\n",
    "    \"\"\"Numer pierwiastka (0, 1, 2) albo 3, gdy metoda nie zbiega.\"\"\"\n",
    "    for _ in range(iteracje):\n",
    "        if z == 0:\n",
    "            return 3\n",
    "        z = z - (z**3 - 1) / (3 * z**2)\n",
    "    for k, r in enumerate(PIERW.tolist()):\n",
    "        if abs(z - r) < 1e-6:\n",
    "            return k\n",
    "    return 3\n",
    "\n",
    "\n",
    "def baseny_petla(n, iteracje=40):\n",
    "    xs = np.linspace(-2, 2, n).tolist()\n",
    "    return [[basen_punktu(complex(x, y), iteracje) for x in xs]\n",
    "            for y in reversed(xs)]\n",
    "\n",
    "\n",
    "def baseny_numpy(n, iteracje=40):\n",
    "    xs = np.linspace(-2, 2, n)\n",
    "    z = xs[None, :] + 1j * xs[::-1, None]\n",
    "    with np.errstate(divide=\"ignore\", invalid=\"ignore\"):\n",
    "        for _ in range(iteracje):\n",
    "            z = z - (z**3 - 1) / (3 * z**2)\n",
    "    odl = np.abs(z[..., None] - PIERW)\n",
    "    return np.where(odl.min(axis=-1) < 1e-6, odl.argmin(axis=-1), 3)\n",
    "\n",
    "\n",
    "czasy_baseny = porownaj({\"punkt po punkcie\": baseny_petla,\n",
    "                         \"cała siatka naraz\": baseny_numpy}, 200,\n",
    "                        zgodne=te_same)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "31afa7ae",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_baseny[\"punkt po punkcie\"]\n",
    "        > 5 * czasy_baseny[\"cała siatka naraz\"],\n",
    "        \"siatka naraz jest wielokrotnie szybsza\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "068efede",
   "metadata": {},
   "source": [
    "Both versions assign the same root to each of the $40{,}000$ points, and both perform\n",
    "$40$ steps for every point. The array version is many times faster, because the loop over the\n",
    "points runs in C. This is a general rule: **vectorize over independent tasks**\n",
    "(points, samples, test cases), not over steps that depend on one another.\n",
    "\n",
    "## The Game of Life\n",
    "\n",
    "In Lab 8 a step of the Game of Life is computed by the function `krok_zycia`. For every cell it\n",
    "sums the eight neighbors, shifting the whole board with the function `np.roll` (the board is\n",
    "wrapped into a torus). Let us compare it with two other versions. The first is plain loops over\n",
    "the cells. The second is a convolution with the neighborhood mask, using the function\n",
    "`scipy.signal.convolve2d`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9e21a0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def krok_zycia(P):\n",
    "    \"\"\"Krok gry w życie na planszy zwiniętej w torus (laboratorium 8).\"\"\"\n",
    "    sasiedzi = sum(np.roll(np.roll(P, i, 0), j, 1)\n",
    "                   for i in (-1, 0, 1) for j in (-1, 0, 1) if (i, j) != (0, 0))\n",
    "    return ((sasiedzi == 3) | ((P == 1) & (sasiedzi == 2))).astype(np.uint8)\n",
    "\n",
    "\n",
    "def krok_zycia_petle(P):\n",
    "    n, m = len(P), len(P[0])\n",
    "    nowa = [[0] * m for _ in range(n)]\n",
    "    for w in range(n):\n",
    "        for k in range(m):\n",
    "            s = 0\n",
    "            for i in (-1, 0, 1):\n",
    "                for j in (-1, 0, 1):\n",
    "                    if (i, j) != (0, 0):\n",
    "                        s += P[(w + i) % n][(k + j) % m]\n",
    "            nowa[w][k] = 1 if s == 3 or (P[w][k] == 1 and s == 2) else 0\n",
    "    return nowa\n",
    "\n",
    "\n",
    "MASKA = np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]])\n",
    "\n",
    "\n",
    "def krok_zycia_splot(P):\n",
    "    s = signal.convolve2d(P, MASKA, mode=\"same\", boundary=\"wrap\")\n",
    "    return ((s == 3) | ((P == 1) & (s == 2))).astype(np.uint8)\n",
    "\n",
    "\n",
    "plansza = (np.random.default_rng(8).random((200, 200)) < 0.3).astype(np.uint8)\n",
    "plansza_lista = plansza.tolist()\n",
    "czasy_zycie = porownaj({\n",
    "    \"pętle po komórkach\": lambda: krok_zycia_petle(plansza_lista),\n",
    "    \"np.roll (laboratorium 8)\": lambda: krok_zycia(plansza),\n",
    "    \"scipy.signal.convolve2d\": lambda: krok_zycia_splot(plansza)},\n",
    "    zgodne=te_same)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84cd54a1",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_zycie[\"pętle po komórkach\"]\n",
    "        > 100 * czasy_zycie[\"np.roll (laboratorium 8)\"],\n",
    "        \"np.roll jest ponad sto razy szybsze od pętli\")\n",
    "upewnij(czasy_zycie[\"np.roll (laboratorium 8)\"]\n",
    "        < czasy_zycie[\"scipy.signal.convolve2d\"],\n",
    "        \"np.roll jest szybsze od convolve2d\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0dce0f0",
   "metadata": {},
   "source": [
    "Eight shifts of the whole board are more than a hundred times faster than the loops over the\n",
    "cells. Interestingly, they also beat SciPy’s ready-made convolution. The function `convolve2d` is\n",
    "general: it works for any mask and any numbers. Eight shifts and additions of arrays of type\n",
    "`uint8` are simpler. A ready-made function is a good first choice, but not always the fastest one,\n",
    "and only a measurement can tell.\n",
    "\n",
    "## The Monte Carlo method\n",
    "\n",
    "In Lecture 5 we estimated the area of the lemniscate $(x^2+y^2)^2=2(x^2-y^2)$ by drawing random\n",
    "points in the rectangle $[-\\sqrt2,\\sqrt2]\\times[-\\tfrac12,\\tfrac12]$ and counting the hits. The\n",
    "area is exactly $2$. We compare drawing point by point with the `random` module against drawing a\n",
    "whole array at once with the generator `np.random.default_rng`. The two programs draw different\n",
    "numbers, so we compare the results with the exact value, not with each other."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca5d2d49",
   "metadata": {},
   "outputs": [],
   "source": [
    "S2 = math.sqrt(2)\n",
    "\n",
    "\n",
    "def monte_carlo_petla(N):\n",
    "    los, trafienia = random.Random(1), 0\n",
    "    for _ in range(N):\n",
    "        x, y = los.uniform(-S2, S2), los.uniform(-0.5, 0.5)\n",
    "        trafienia += (x * x + y * y)**2 <= 2 * (x * x - y * y)\n",
    "    return trafienia / N * 2 * S2\n",
    "\n",
    "\n",
    "def monte_carlo_numpy(N):\n",
    "    los = np.random.default_rng(1)\n",
    "    x, y = los.uniform(-S2, S2, N), los.uniform(-0.5, 0.5, N)\n",
    "    return float(((x * x + y * y)**2 <= 2 * (x * x - y * y)).mean() * 2 * S2)\n",
    "\n",
    "\n",
    "czasy_mc = porownaj({\"punkt po punkcie\": monte_carlo_petla,\n",
    "                     \"tablica naraz\": monte_carlo_numpy}, 10**6,\n",
    "                    zgodne=lambda a, b: max(abs(a - 2), abs(b - 2)) < 0.01)\n",
    "oszacowania = (monte_carlo_petla(10**6), monte_carlo_numpy(10**6))\n",
    "p_traf = 2 / (2 * S2)\n",
    "print(\"oszacowania:\", oszacowania, \" typowy błąd:\",\n",
    "      f\"{2 * S2 * math.sqrt(p_traf * (1 - p_traf) / 10**6):.1e}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94041d69",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_mc[\"punkt po punkcie\"] > 5 * czasy_mc[\"tablica naraz\"],\n",
    "        \"losowanie tablicy naraz jest wielokrotnie szybsze\")\n",
    "upewnij(all(abs(o - 2) < 5e-3 for o in oszacowania),\n",
    "        \"oba oszacowania mają błąd rzędu 10^-3\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3b5783d6",
   "metadata": {},
   "source": [
    "Drawing the whole array at once is many times faster. Both estimates have an error of order\n",
    "$10^{-3}$, in line with the typical error of the Monte Carlo method for a million points.\n",
    "\n",
    "## Pitfalls\n",
    "\n",
    "NumPy speeds up operations on **whole arrays**. Outside this case it can slow a program down or\n",
    "silently change the result. Here are five pitfalls.\n",
    "\n",
    "**`np.vectorize` does not vectorize.** The name is misleading: `np.vectorize(f)` creates a\n",
    "function that accepts arrays, but inside it calls `f` in a Python loop, element by element. The\n",
    "NumPy documentation says so explicitly: the function is provided for convenience, not for speed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4360e8c2",
   "metadata": {},
   "outputs": [],
   "source": [
    "horner7 = np.vectorize(lambda t: horner(wsp7, t))\n",
    "czasy_wektoryzuj = porownaj({\n",
    "    \"lista składana\": horner_punkt_po_punkcie,\n",
    "    \"np.vectorize\": lambda: horner7(ts),\n",
    "    \"prawdziwa wektoryzacja\": lambda: horner(wsp7, ts)},\n",
    "    zgodne=np.array_equal)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10083314",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "r = czasy_wektoryzuj[\"lista składana\"] / czasy_wektoryzuj[\"np.vectorize\"]\n",
    "upewnij(0.4 < r < 2.5, \"np.vectorize jest tak wolne jak lista składana\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "659c5ebb",
   "metadata": {},
   "source": [
    "**NumPy on single numbers.** NumPy functions called on an ordinary number are slower than the\n",
    "functions from the `math` module, because every time they prepare an array computation: they check\n",
    "the type of the argument and create a result of type `np.float64`. In a loop over\n",
    "numbers (bisection, Newton’s method for a single point) it is better to use `math`. Similarly,\n",
    "`np.sum(lista)` pays for converting the list into an array at every call:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "214e8f1c",
   "metadata": {},
   "outputs": [],
   "source": [
    "czasy_skalar = porownaj({\"math.exp(0.7)\": lambda: math.exp(0.7),\n",
    "                         \"np.exp(0.7)\": lambda: np.exp(0.7)},\n",
    "                        zgodne=lambda a, b: a == b)\n",
    "czasy_konwersja = porownaj({\"sum(lista)\": lambda: sum(lista),\n",
    "                            \"np.sum(lista)\": lambda: np.sum(lista),\n",
    "                            \"tablica.sum()\": lambda: tablica.sum()},\n",
    "                           zgodne=lambda a, b: abs(a - b) < 1e-3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85707d14",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_skalar[\"np.exp(0.7)\"] > czasy_skalar[\"math.exp(0.7)\"],\n",
    "        \"np.exp na liczbie jest wolniejsze od math.exp\")\n",
    "upewnij(czasy_konwersja[\"np.sum(lista)\"] > czasy_konwersja[\"sum(lista)\"]\n",
    "        > czasy_konwersja[\"tablica.sum()\"],\n",
    "        \"np.sum na liście jest wolniejsze od sum, a tablica.sum najszybsze\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3bfd5853",
   "metadata": {},
   "source": [
    "So we convert the data into an array **once** and then work on the array. `np.sum` called on a\n",
    "list is slower even than the plain `sum`.\n",
    "\n",
    "**Integer overflow.** Python integers are unbounded. NumPy integer arrays have a fixed width,\n",
    "usually $64$ bits, and on overflow they compute modulo $2^{64}$, **without a warning**. An example\n",
    "from the instructor’s study, and the factorial from Lecture 1:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6588260d",
   "metadata": {},
   "outputs": [],
   "source": [
    "with np.errstate(over=\"raise\"):       # nie pomoże: to nie są liczby float\n",
    "    wyniki = {\"sum([2**62, 2**62])\": sum([2**62, 2**62]),\n",
    "              \"np.array([2**62, 2**62]).sum()\": np.array([2**62, 2**62]).sum(),\n",
    "              \"math.factorial(25)\": math.factorial(25),\n",
    "              \"np.prod(np.arange(1, 26))\": np.prod(np.arange(1, 26))}\n",
    "for opis, wartosc in wyniki.items():\n",
    "    print(f\"{opis:30} = {wartosc}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c14dc7eb",
   "metadata": {},
   "source": [
    "The product of the numbers from $1$ to $25$ in NumPy is simply wrong, and nothing signals it. The\n",
    "setting `np.errstate(over=\"raise\")` controls only floating-point errors. It does not detect integer\n",
    "overflow in NumPy arrays. For integers\n",
    "that may exceed $2^{63}$ we stay with Python integers, or we use arrays of type\n",
    "`object`, which store Python integers but lose NumPy’s speed.\n",
    "\n",
    "**Memory in broadcasting.** Broadcasting `x[:, None] - x[None, :]` creates an array of all $n^2$\n",
    "differences. Let us compute the sum of all pairwise distances $\\sum_{i<j}|x_i-x_j|$\n",
    "for $n=3000$ points in three ways: with the whole matrix of differences, in blocks of $256$ rows,\n",
    "as in the instructor’s study, and with a formula. If $y_0\\le y_1\\le\\dots\\le y_{n-1}$ are the same\n",
    "numbers after sorting, then $y_k$ is greater than $k$ of the numbers and smaller than $n-1-k$ of\n",
    "them, so\n",
    "\n",
    "$$\n",
    "\\sum_{i<j}|x_i-x_j|=\\sum_{k=0}^{n-1}\\bigl(2k-(n-1)\\bigr)\\,y_k .\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae4d013b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def odleglosci_macierz(x):\n",
    "    return float(np.abs(x[:, None] - x[None, :]).sum() / 2)\n",
    "\n",
    "\n",
    "def odleglosci_blokami(x, b=256):\n",
    "    s = 0.0\n",
    "    for i in range(0, len(x), b):\n",
    "        s += np.abs(x[i:i + b, None] - x[None, :]).sum()\n",
    "    return float(s / 2)\n",
    "\n",
    "\n",
    "def odleglosci_wzor(x):\n",
    "    y = np.sort(x)\n",
    "    return float(np.dot(y, 2 * np.arange(len(y)) - (len(y) - 1)))\n",
    "\n",
    "\n",
    "def szczyt_pamieci(f, *args):\n",
    "    tracemalloc.start()\n",
    "    f(*args)\n",
    "    szczyt = tracemalloc.get_traced_memory()[1]\n",
    "    tracemalloc.stop()\n",
    "    return szczyt\n",
    "\n",
    "\n",
    "x = np.random.default_rng(7).random(3000)\n",
    "ODLEGLOSCI = {\"macierz różnic\": odleglosci_macierz,\n",
    "              \"bloki po 256 wierszy\": odleglosci_blokami,\n",
    "              \"wzór po posortowaniu\": odleglosci_wzor}\n",
    "czasy_pary = porownaj(ODLEGLOSCI, x,\n",
    "                      zgodne=lambda a, b: abs(a - b) < 1e-9 * abs(b))\n",
    "pamiec_pary = {f.__name__: szczyt_pamieci(f, x) for f in ODLEGLOSCI.values()}\n",
    "for nazwa, bajty in pamiec_pary.items():\n",
    "    print(f\"{nazwa:20} szczyt pamięci: {bajty / 2**20:7.2f} MiB\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5a444b4b",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(pamiec_pary[\"odleglosci_macierz\"] > 100 * 2**20,\n",
    "        \"szczyt pamięci macierzy różnic przekracza 100 MiB\")\n",
    "upewnij(pamiec_pary[\"odleglosci_macierz\"]\n",
    "        > 5 * pamiec_pary[\"odleglosci_blokami\"]\n",
    "        > 5 * pamiec_pary[\"odleglosci_wzor\"],\n",
    "        \"bloki zmniejszają pamięć wielokrotnie, a wzór jeszcze bardziej\")\n",
    "upewnij(czasy_pary[\"macierz różnic\"] > 10 * czasy_pary[\"wzór po posortowaniu\"],\n",
    "        \"wzór jest wielokrotnie szybszy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8797927d",
   "metadata": {},
   "source": [
    "The peak memory of the matrix of differences for $n=3000$ exceeds a hundred megabytes, and for\n",
    "$n=10^5$ the matrix would already need $8\\cdot10^{10}$ bytes, that is, $80$ GB. Blocks limit the\n",
    "memory to $8bn$ bytes, but they still perform $n^2$ subtractions. The formula after sorting needs\n",
    "$O(n\\log n)$ operations and takes almost no memory. Once again mathematics wins, just as in\n",
    "{doc}`part 2 <p2_algorytm>`.\n",
    "\n",
    "## Summary\n",
    "\n",
    "Let us collect the speedups obtained in this part. Each time we replaced a loop in Python with an\n",
    "operation on a whole array."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d75c538",
   "metadata": {},
   "outputs": [],
   "source": [
    "zestawienie = {\n",
    "    \"kwadraty miliona liczb\": czasy_kwadraty,\n",
    "    \"Horner, 10⁵ punktów\": czasy_horner,\n",
    "    \"trapezy, n = 10⁶\": czasy_trapezy,\n",
    "    \"baseny Newtona 200×200\": czasy_baseny,\n",
    "    \"gra w życie 200×200\": czasy_zycie,\n",
    "    \"Monte Carlo, 10⁶ punktów\": czasy_mc,\n",
    "}\n",
    "przyspieszenia = {nazwa: list(t.values())[0] / min(t.values())\n",
    "                  for nazwa, t in zestawienie.items()}\n",
    "for nazwa, r in przyspieszenia.items():\n",
    "    print(f\"{nazwa:26} najszybsza wersja tablicowa: {krotnosc(r):>6}\")\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(8, 3.2))\n",
    "nazwy = list(przyspieszenia)[::-1]\n",
    "wartosci = [przyspieszenia[k] for k in nazwy]\n",
    "ax.scatter(wartosci, range(len(nazwy)), s=70, color=INDYGO,\n",
    "           edgecolors=\"white\", linewidths=2, zorder=3)\n",
    "for i, v in enumerate(wartosci):\n",
    "    ax.annotate(krotnosc(v), (v, i), xytext=(9, 0), textcoords=\"offset points\",\n",
    "                va=\"center\", fontsize=9, color=TUSZ)\n",
    "ax.set_yticks(range(len(nazwy)), nazwy)\n",
    "ax.set_xscale(\"log\")\n",
    "ax.set_xlim(1, max(przyspieszenia.values()) * 6)\n",
    "ax.xaxis.set_major_formatter(FuncFormatter(lambda v, _: f\"{v:g}×\"))\n",
    "ax.xaxis.set_minor_formatter(NullFormatter())\n",
    "ax.axvline(1, color=SZARY, lw=1)\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(\"Ile razy szybciej z tablicami NumPy\", loc=\"left\", fontsize=11)\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f8dba2c0",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(10 < min(przyspieszenia.values())\n",
    "        and max(przyspieszenia.values()) < 1000,\n",
    "        \"przyspieszenia wynoszą od kilkunastu do kilkuset razy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "208c90b4",
   "metadata": {},
   "source": [
    "* A NumPy array stores numbers of a single type next to one another, and operations on whole\n",
    "  arrays are carried out by loops in C. The speedup is usually from a dozen or so to a few hundred\n",
    "  times.\n",
    "* Vectorize **over independent tasks**: grid points, samples, cells of the board.\n",
    "  Steps that depend on one another (the Newton iteration for a single point) cannot be performed\n",
    "  all at once.\n",
    "* Often it is enough to call the same function on an array (*duck typing*), as with `horner`.\n",
    "* Pitfalls: `np.vectorize` is a loop, NumPy functions on single numbers are slower than\n",
    "  `math`, converting a list into an array has a cost, integers **overflow without a warning**,\n",
    "  and broadcasting can take $n^2$ memory.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. ★ Write an array version of the function `srodki(f, a, b, n)` (the midpoint rule)\n",
    "   and compare it with the generator version for $n=10^6$.\n",
    "2. ★ Compute $\\sum_{k=1}^{n}k^2$ in NumPy for $n=3\\cdot10^6$ on the array `np.arange(1, n + 1)`\n",
    "   and compare it with the formula $n(n+1)(2n+1)/6$ in Python integers. Explain the difference.\n",
    "   Fix the NumPy version by choosing a suitable array type.\n",
    "3. ★★ For the Game of Life, measure the time of $100$ steps on a $500\\times500$ board with the\n",
    "   `np.roll` version and with the loops (for the loops, measure one step and estimate). How many\n",
    "   steps per second does each version give?\n",
    "4. ★★ Prove the formula for $\\sum_{i<j}|x_i-x_j|$ in terms of the sorted values. How many\n",
    "   operations does the version with sorting perform, and how many the matrix of differences?"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
