{ "cells": [ { "cell_type": "markdown", "id": "7fb27b941602401d91542211134fc71a", "metadata": {}, "source": [ "# Test-matrix generators\n", "\n", "`mtl5.generators` is a catalog of matrices with **known pathologies** — the inputs\n", "a numerical experiment actually wants. Each one is famous for a specific reason:\n", "an exactly-known spectrum you can check against, conditioning that grows on\n", "command, or a structure that defeats a particular algorithm.\n", "\n", "The reason they live in `mtl5` rather than being a few lines of NumPy is `dtype=`:\n", "every dense generator can hand you its matrix in any of the bound number systems,\n", "which is what makes a mixed-precision experiment a one-liner.\n", "\n", "> Run with `pip install -e '.[notebooks]'`." ] }, { "cell_type": "code", "execution_count": null, "id": "acae54e37e7d407bbb7b55eff062a284", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "import mtl5\n", "\n", "g = mtl5.generators\n", "\n", "# Chart styling: recessive axes and grid, ink for text, validated categorical hues.\n", "SURFACE = \"#fcfcfb\"\n", "INK, INK_2 = \"#0b0b0b\", \"#52514e\"\n", "SERIES = [\"#2a78d6\", \"#eb6834\", \"#1baf7a\", \"#eda100\"]\n", "\n", "plt.rcParams.update(\n", " {\n", " \"figure.facecolor\": SURFACE,\n", " \"axes.facecolor\": SURFACE,\n", " \"axes.edgecolor\": \"#d8d7d2\",\n", " \"axes.labelcolor\": INK_2,\n", " \"axes.titlecolor\": INK,\n", " \"axes.spines.top\": False,\n", " \"axes.spines.right\": False,\n", " \"grid.color\": \"#e8e7e2\",\n", " \"grid.linewidth\": 0.8,\n", " \"text.color\": INK,\n", " \"xtick.color\": INK_2,\n", " \"ytick.color\": INK_2,\n", " \"font.size\": 10,\n", " \"figure.dpi\": 120,\n", " }\n", ")\n", "\n", "print(mtl5.__version__, \"|\", len(g.testsuite_names()), \"catalog entries\")" ] }, { "cell_type": "markdown", "id": "9a63283cbaf04dbcab1f6479b197f3a8", "metadata": {}, "source": [ "## 1. Matrices with an exactly known answer\n", "\n", "The most useful property a test matrix can have is a spectrum you know in closed\n", "form, because then you can check a solver without trusting a second solver.\n", "\n", "**Clement** is tridiagonal with eigenvalues exactly `-(n-1), -(n-3), …, n-1`." ] }, { "cell_type": "code", "execution_count": null, "id": "8dd0d8092fe74a7c96281538738b07e2", "metadata": {}, "outputs": [], "source": [ "for n in (5, 7, 9):\n", " got = np.sort(np.linalg.eigvals(g.clement(n).to_numpy()).real)\n", " want = np.arange(-(n - 1), n, 2, dtype=float)\n", " print(f\"clement({n}) max|error| = {np.abs(got - want).max():.2e} {np.round(got, 6)}\")" ] }, { "cell_type": "markdown", "id": "72eea5119410473aa328ad9291626812", "metadata": {}, "source": [ "**Wilkinson** puts pairs of nearly-equal eigenvalues next to each other — the\n", "classic stress test for whether an eigensolver separates a tight cluster.\n", "**Rosser** packs a double eigenvalue, a zero eigenvalue, and two that differ only\n", "in the last bits into one 8×8 matrix." ] }, { "cell_type": "code", "execution_count": null, "id": "8edb47106e1a46a883d545849b8ab81b", "metadata": {}, "outputs": [], "source": [ "W = g.wilkinson(21).to_numpy()\n", "ev = np.sort(np.linalg.eigvalsh(W))\n", "gaps = np.diff(ev)\n", "print(f\"wilkinson(21): tightest eigenvalue gap = {gaps.min():.3e}\")\n", "\n", "R = g.rosser().to_numpy()\n", "rev = np.sort(np.linalg.eigvals(R).real)\n", "print(f\"rosser(): smallest |eigenvalue| = {np.abs(rev).min():.3e} (exactly zero)\")\n", "print(f\" closest pair differs by {np.diff(rev).min():.3e}\")" ] }, { "cell_type": "markdown", "id": "10185d26023b46108eb7d9f57d49d2b3", "metadata": {}, "source": [ "## 2. Conditioning on demand\n", "\n", "**Hilbert** is the canonical ill-conditioned matrix: `H[i,j] = 1/(i+j+1)`. Its\n", "condition number grows roughly geometrically, so it runs out of float64 by about\n", "n = 12 — every digit is gone." ] }, { "cell_type": "code", "execution_count": null, "id": "8763a12b2bbd4a93a75aff182afb95dc", "metadata": {}, "outputs": [], "source": [ "ns = list(range(2, 13))\n", "conds = [np.linalg.cond(g.hilbert(n).to_numpy()) for n in ns]\n", "\n", "fig, ax = plt.subplots(figsize=(6.4, 3.4))\n", "ax.set_yscale(\"log\")\n", "ax.grid(True, axis=\"y\", zorder=0)\n", "ax.set_axisbelow(True)\n", "ax.plot(ns, conds, color=SERIES[0], linewidth=2, marker=\"o\", markersize=4.5, zorder=3)\n", "ax.axhline(1 / np.finfo(float).eps, color=INK_2, linewidth=1, linestyle=\"--\", zorder=2)\n", "ax.annotate(\n", " \"1/eps — float64 exhausted\",\n", " xy=(ns[0], 1 / np.finfo(float).eps),\n", " xytext=(0, 5),\n", " textcoords=\"offset points\",\n", " color=INK_2,\n", " fontsize=9,\n", ")\n", "ax.set_xlabel(\"n\")\n", "ax.set_ylabel(\"condition number\")\n", "ax.set_title(\"Hilbert matrix conditioning\", loc=\"left\", fontweight=\"bold\")\n", "fig.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "7623eae2785240b9bd12b16a66d81610", "metadata": {}, "source": [ "## 3. Matrices built to order\n", "\n", "Rather than hunting for a matrix with the properties you want, state them.\n", "`randspd` and `randsym` take the spectrum you ask for; `randsvd` takes the\n", "condition number." ] }, { "cell_type": "code", "execution_count": null, "id": "7cdc8c89c7104fffa095e18ddfef8986", "metadata": {}, "outputs": [], "source": [ "target = [1.0, 10.0, 100.0, 1000.0]\n", "A = g.randspd(4, target).to_numpy()\n", "print(\"randspd requested\", target)\n", "print(\" got \", np.round(np.sort(np.linalg.eigvalsh(A)), 10))\n", "\n", "# randsym allows negative eigenvalues — a controlled *indefinite* matrix, which\n", "# is exactly what you need to test a solver's failure path.\n", "indef = [-5.0, -1.0, 2.0, 7.0]\n", "S = g.randsym(4, indef).to_numpy()\n", "print(\"\\nrandsym requested\", indef)\n", "print(\" got \", np.round(np.sort(np.linalg.eigvalsh(S)), 10))\n", "\n", "print()\n", "for kappa in (1e3, 1e6, 1e9, 1e12):\n", " got = np.linalg.cond(g.randsvd(16, 16, kappa).to_numpy())\n", " print(f\"randsvd kappa={kappa:.0e} -> measured {got:.4e}\")" ] }, { "cell_type": "markdown", "id": "b118ea5561624da68c537baed56e602f", "metadata": {}, "source": [ "## 4. The point: the same matrix in any precision\n", "\n", "Every dense generator takes `dtype=`. Generation happens in float64 and `dtype=`\n", "rounds — the right semantics for a test matrix, since these are defined over the\n", "reals and you want the correctly rounded representation of the exact entry.\n", "\n", "Below: solve `H x = b` for a known `x` of all ones, as the precision narrows." ] }, { "cell_type": "code", "execution_count": null, "id": "938c804e27f84196a10c8828c723f798", "metadata": {}, "outputs": [], "source": [ "DTYPES = [\"f64\", \"f32\", \"posit32\", \"posit16\"]\n", "sizes = list(range(2, 13))\n", "errors = {d: [] for d in DTYPES}\n", "\n", "for n in sizes:\n", " xt = np.ones(n)\n", " b = g.hilbert(n).to_numpy() @ xt\n", " for d in DTYPES:\n", " x = mtl5.solve(g.hilbert(n, dtype=d), mtl5.convert(b, d)).to_numpy()\n", " errors[d].append(np.linalg.norm(np.asarray(x, dtype=float) - xt) / np.linalg.norm(xt))\n", "\n", "print(f\"{'n':>3} \" + \"\".join(f\"{d:>11}\" for d in DTYPES))\n", "for i, n in enumerate(sizes):\n", " print(f\"{n:>3} \" + \"\".join(f\"{errors[d][i]:>11.1e}\" for d in DTYPES))" ] }, { "cell_type": "code", "execution_count": null, "id": "504fb2a444614c0babb325280ed9130a", "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots(figsize=(7.2, 3.8))\n", "ax.set_yscale(\"log\")\n", "ax.grid(True, axis=\"y\", zorder=0)\n", "ax.set_axisbelow(True)\n", "\n", "# The four lines converge at the right, so end-of-line labels would collide.\n", "# Identity is carried by the legend plus the numeric table printed above — the\n", "# table is also the relief for the two hues below 3:1 on this surface.\n", "for slot, d in enumerate(DTYPES):\n", " ax.plot(\n", " sizes,\n", " errors[d],\n", " color=SERIES[slot],\n", " linewidth=2,\n", " marker=\"o\",\n", " markersize=4.5,\n", " label=d,\n", " zorder=3,\n", " )\n", "\n", "ax.axhline(1.0, color=INK_2, linewidth=1, linestyle=\"--\", zorder=2)\n", "ax.annotate(\n", " \"100% error — no digits left\",\n", " xy=(sizes[0], 1.0),\n", " xytext=(2, 7),\n", " textcoords=\"offset points\",\n", " color=INK_2,\n", " fontsize=9,\n", " ha=\"left\",\n", ")\n", "ax.set_xlabel(\"Hilbert matrix size n\")\n", "ax.set_ylabel(\"relative error of the solve\")\n", "ax.set_title(\"Solving H x = b as precision narrows\", loc=\"left\", fontweight=\"bold\")\n", "ax.set_xlim(sizes[0] - 0.3, sizes[-1] + 0.3)\n", "ax.legend(frameon=False, loc=\"lower right\", labelcolor=INK_2, ncols=2)\n", "fig.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "59bbdb311c014d738909a11f9e486628", "metadata": {}, "source": [ "Two things worth reading off that chart.\n", "\n", "float64 itself is useless past about n = 11 — this matrix defeats *any* precision\n", "eventually, which is the point of having it.\n", "\n", "And **posit32 beats float32 at small n** despite both being 32 bits: posits taper,\n", "spending more significand near 1 where these entries live. That is the kind of\n", "comparison this package exists to make cheap to run." ] }, { "cell_type": "markdown", "id": "b43b363d81ae4b689946ece5c682cd59", "metadata": {}, "source": [ "## 5. A generator as a failure-path test\n", "\n", "A Kalman covariance update can push a matrix out of positive-definiteness in low\n", "precision. Cholesky takes square roots and refuses; LDLᵀ has none and survives,\n", "recording the bad direction in `D`. Both are available for every element type, so\n", "the comparison can be run in the precision where it actually bites." ] }, { "cell_type": "code", "execution_count": null, "id": "8a65eabff63a45729fe45fb5ade58bdc", "metadata": {}, "outputs": [], "source": [ "P = np.eye(6)\n", "P[3, 3] = -1e-3 # one direction has gone negative\n", "\n", "for d in (\"f64\", \"posit32\", \"posit16\", \"fp16\"):\n", " M = mtl5.convert(P, d)\n", " try:\n", " mtl5.cholesky(M)\n", " chol = \"succeeded\"\n", " except RuntimeError:\n", " chol = \"refused (not SPD)\"\n", " D = mtl5.ldlt(M).diagonal()\n", " print(f\"{d:8s} cholesky: {chol:22s} ldlt: ok, {(D < 0).sum()} negative pivot(s)\")" ] }, { "cell_type": "markdown", "id": "c3933fab20d04ec698c2621248eb3be0", "metadata": {}, "source": [ "## 6. Sparse generators\n", "\n", "`laplacian_1d`, `laplacian_2d` and `poisson2d` return CSR directly — the\n", "structured systems the iterative and direct solvers are usually benchmarked on." ] }, { "cell_type": "code", "execution_count": null, "id": "4dd4641cc4064e0191573fe9c69df29b", "metadata": {}, "outputs": [], "source": [ "import mtl5.sparse as ms\n", "\n", "L = g.laplacian_2d(16, 16)\n", "print(L, \" density =\", f\"{L.nnz / (L.shape[0] * L.shape[1]):.3%}\")\n", "\n", "dense = ms.to_scipy(L).toarray()\n", "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7.6, 3.6))\n", "ax1.spy(dense, markersize=0.7, color=SERIES[0])\n", "ax1.set_title(\"laplacian_2d(16, 16) pattern\", loc=\"left\", fontweight=\"bold\")\n", "ax1.tick_params(labelsize=8)\n", "\n", "# The fill an ordering avoids: factor it and look at L+U.\n", "fills = {name: ms.splu(L, ordering=name).nnz for name in ms.orderings()}\n", "names, vals = list(fills), list(fills.values())\n", "bars = ax2.barh(names, vals, color=SERIES[0], height=0.5, zorder=3)\n", "ax2.bar_label(bars, fmt=\"%d\", padding=4, color=INK_2, fontsize=9)\n", "ax2.grid(True, axis=\"x\", zorder=0)\n", "ax2.set_axisbelow(True)\n", "ax2.invert_yaxis()\n", "ax2.set_xlabel(\"nonzeros in L+U\")\n", "ax2.set_xlim(0, max(vals) * 1.25)\n", "ax2.set_title(\"fill by ordering\", loc=\"left\", fontweight=\"bold\")\n", "fig.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "8309879909854d7188b41380fd92a7c3", "metadata": {}, "source": [ "## 7. Range vectors\n", "\n", "`arange`, `linspace`, `logspace` and `geomspace` follow NumPy, and take `dtype=`.\n", "\n", "Note `geomspace` is a **true geometric progression between its endpoints**, not\n", "`logspace`'s exponents — MTL5 fixed a long-standing bug where the two aliased." ] }, { "cell_type": "code", "execution_count": null, "id": "3ed186c9a28b402fb0bc4494df01f08d", "metadata": {}, "outputs": [], "source": [ "print(\"linspace(0, 1, 5) \", mtl5.linspace(0, 1, 5).to_numpy())\n", "print(\"arange(0, 10, 3) \", mtl5.arange(0, 10, 3).to_numpy())\n", "print(\"logspace(0, 3, 4) \", mtl5.logspace(0, 3, 4).to_numpy(), \" (10**0 .. 10**3)\")\n", "print(\"geomspace(1, 1000, 4) \", mtl5.geomspace(1, 1000, 4).to_numpy(), \" (endpoints themselves)\")\n", "\n", "v = mtl5.linspace(0, 1, 9, dtype=\"posit8\")\n", "print(\"\\nlinspace in posit8 \", v.to_numpy())\n", "print(\" exact?\", np.allclose(v.to_numpy(), np.linspace(0, 1, 9)))" ] }, { "cell_type": "markdown", "id": "cb1e1581032b452c9409d6c6813c49d1", "metadata": {}, "source": [ "## 8. The published catalog\n", "\n", "`testsuite_names()` and `testsuite_kappa()` expose MTL5's catalog of named\n", "matrices with published condition numbers — reference values to check a computed\n", "condition number against." ] }, { "cell_type": "code", "execution_count": null, "id": "379cbbc1e968416e875cc15c1202d7eb", "metadata": {}, "outputs": [], "source": [ "names = g.testsuite_names()\n", "print(f\"{len(names)} entries\\n\")\n", "for name in names[:8]:\n", " print(f\" {name:16s} kappa = {g.testsuite_kappa(name):.3e}\")" ] }, { "cell_type": "markdown", "id": "277c27b1587741f2af2001be3712ef0d", "metadata": {}, "source": [ "---\n", "\n", "### Where to go next\n", "\n", "- `mtl5.mixed` — choose the accumulator independently of storage\n", " (`accumulator=\"quire\"` for an exact dot product)\n", "- `mtl5.mixed.lu_iterative_refine` — factor cheap, recover accuracy\n", "- `mtl5.sparse` — seven direct factorizations with analyze/factor/refactor" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10" } }, "nbformat": 4, "nbformat_minor": 5 }