{ "cells": [ { "cell_type": "markdown", "id": "3b2bf40b20f245689b215b139810998b", "metadata": {}, "source": [ "# Sparse direct solvers: orderings, fill-in, and the solve pipeline\n", "\n", "A sparse direct solver factors `A` into triangular factors and then solves by\n", "substitution. Elimination is not free in a sparse matrix. Eliminating one\n", "unknown couples every pair of its neighbours, so the factors pick up nonzeros\n", "where `A` had none. That **fill-in** decides how much memory the factorization\n", "needs and how long it takes. The amount of fill depends almost entirely on the\n", "**order** in which the unknowns are eliminated.\n", "\n", "This notebook follows MATLAB's\n", "[`colamd` example](https://www.mathworks.com/help/matlab/ref/colamd.html) with\n", "mtl5, then goes further:\n", "\n", "1. **The matrix.** Load `west0479` and look at its pattern.\n", "2. **Orderings and fill.** Reorder it four ways, factor each, and look at the\n", " factors themselves.\n", "3. **A symmetric problem.** Show that the winning ordering depends on the\n", " matrix's structure.\n", "4. **The solve pipeline.** Separate analyze, factor, refactor and solve, and\n", " show what reusing the analysis saves.\n", "\n", "It needs the `notebooks` extra (`pip install -e \".[notebooks]\"`) for matplotlib\n", "and SciPy. Every number printed here is computed when the notebook runs, and CI\n", "runs it, so the `assert` cells catch an ordering that stops reducing fill." ] }, { "cell_type": "code", "execution_count": null, "id": "a2b674ff37554c3f98254e9343eab804", "metadata": {}, "outputs": [], "source": [ "import time\n", "\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import scipy.sparse as sp\n", "import scipy.sparse.linalg as spla\n", "from matplotlib.colors import ListedColormap\n", "\n", "import mtl5\n", "import mtl5.sparse as ms\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", " \"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", "\n", "# Spy figures render at this resolution, so that each matrix row gets about\n", "# two pixels: a pattern drawn below one pixel per row smears neighbours together.\n", "SPY_DPI = 200\n", "\n", "\n", "def spy(ax, M, title, color=SERIES[0]):\n", " # MATLAB-style spy plot of an MTL5 or SciPy sparse matrix, drawn as an image\n", " # with one cell per matrix entry, so two nonzeros never overlap. Markers\n", " # sized in points (matplotlib's ax.spy) span several rows at this scale.\n", " # Every STORED entry is drawn, including ones whose value is exactly zero:\n", " # storage and work are spent on them.\n", " S = (ms.to_scipy(M) if not sp.issparse(M) else M).tocoo()\n", " pattern = np.zeros(S.shape, dtype=bool)\n", " pattern[S.row, S.col] = True\n", " ax.imshow(pattern, cmap=ListedColormap([SURFACE, color]), interpolation=\"none\")\n", " ax.set_title(f\"{title}\\nnz = {S.nnz:,}\", fontsize=9)\n", " ax.set_xticks([])\n", " ax.set_yticks([])\n", "\n", "\n", "def best_time(fn, repeats=5):\n", " # Best wall time of `repeats` calls, in milliseconds, and the last result.\n", " best, out = float(\"inf\"), None\n", " for _ in range(repeats):\n", " t = time.perf_counter()\n", " out = fn()\n", " best = min(best, time.perf_counter() - t)\n", " return best * 1e3, out\n", "\n", "\n", "print(\"mtl5\", mtl5.__version__, \"| orderings:\", ms.orderings())" ] }, { "cell_type": "markdown", "id": "2ddee59f13e948a39eb7415d8907924a", "metadata": {}, "source": [ "## 1. The matrix\n", "\n", "`west0479` is a Harwell-Boeing test matrix of order 479. It models an\n", "eight-stage Westerberg chemical distillation column, and it is unsymmetric.\n", "The file in `data/` is the one Matrix Market distributes; `data/README.md`\n", "gives the source.\n", "\n", "The file stores 1910 entries, and 22 of them are explicit zeros. A stored zero\n", "still occupies a slot in the factorization, so drop the zeros first.\n", "MATLAB's `load west0479` reports 1887 nonzeros, which differs from the 1888\n", "here by a single entry." ] }, { "cell_type": "code", "execution_count": null, "id": "dd31404c367c4a4fb211c647f87e2332", "metadata": {}, "outputs": [], "source": [ "A_file = mtl5.io.mm_read(\"data/west0479.mtx\")\n", "S = ms.to_scipy(A_file)\n", "stored, explicit_zeros = S.nnz, int((S.data == 0).sum())\n", "S.eliminate_zeros()\n", "A = ms.from_scipy(S)\n", "n = A.shape[0]\n", "\n", "print(f\"order {n}, {stored} stored entries, {explicit_zeros} explicit zeros -> nnz(A) = {A.nnz}\")\n", "assert A.nnz == stored - explicit_zeros == 1888\n", "\n", "fig, ax = plt.subplots(figsize=(5, 5.2), dpi=SPY_DPI)\n", "spy(ax, A, \"west0479\")\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "0061f59cc6cb484aa15dd98fa16824c0", "metadata": {}, "source": [ "The eight column stages are visible as repeated blocks along the diagonal,\n", "coupled by a few long-range entries.\n", "\n", "## 2. Orderings and fill-in\n", "\n", "`mtl5.sparse.splu` factors a column-permuted matrix with threshold partial\n", "pivoting:\n", "\n", "$$A[\\text{row\\_perm}][:,\\ \\text{col\\_perm}] = L\\,U$$\n", "\n", "The **column** permutation comes from the fill-reducing ordering, chosen before\n", "any arithmetic. The **row** permutation comes from pivoting, chosen during the\n", "factorization for numerical stability. `mtl5.sparse.ordering(A, name)` returns\n", "the column permutation on its own, so you can look at it before factoring.\n", "\n", "| Ordering | What it minimizes | Natural fit |\n", "|---|---|---|\n", "| `natural` | nothing: the identity | a baseline |\n", "| `colamd` | approximate minimum degree on the pattern of $A^TA$ | LU and QR of unsymmetric matrices: the fill of LU with partial pivoting is bounded by the Cholesky factor of $A^TA$ |\n", "| `amd` | approximate minimum degree on the pattern of $A + A^T$ | Cholesky and $LDL^T$, and LU of matrices with a nearly symmetric pattern and a strong diagonal |\n", "| `rcm` | bandwidth (reverse Cuthill-McKee) | banded or profile storage; not fill directly |\n", "\n", "A permutation moves entries but never changes how many there are:" ] }, { "cell_type": "code", "execution_count": null, "id": "c4f716d10e9d4c5fb990e3f3856d3c20", "metadata": {}, "outputs": [], "source": [ "ORDERINGS = [\"natural\", \"colamd\", \"amd\", \"rcm\"]\n", "perms = {o: ms.ordering(A, o) for o in ORDERINGS}\n", "\n", "fig, axes = plt.subplots(2, 2, figsize=(9.5, 10), dpi=SPY_DPI)\n", "for ax, o, c in zip(axes.flat, ORDERINGS, SERIES):\n", " spy(ax, S[:, perms[o]], f\"A[:, p] ({o})\", color=c)\n", "plt.tight_layout()\n", "plt.show()\n", "\n", "assert all(S[:, p].nnz == A.nnz for p in perms.values())" ] }, { "cell_type": "markdown", "id": "c291837e5bdd45db80cd44ab7107bf7e", "metadata": {}, "source": [ "The factors are where the orderings differ. Since #126 every factor object\n", "exposes `L`, `U`, `row_perm` and `col_perm`, so the fill can be counted and\n", "looked at, not just inferred from `.nnz`." ] }, { "cell_type": "code", "execution_count": null, "id": "249df917773b4db29c13356b90c28b1b", "metadata": {}, "outputs": [], "source": [ "b = S @ np.ones(n)\n", "lus, rows = {}, []\n", "for o in ORDERINGS:\n", " ms_factor, lu = best_time(lambda o=o: ms.splu(A, ordering=o))\n", " x = lu.solve(b).to_numpy()\n", " rows.append((o, lu.L.nnz, lu.U.nnz, lu.nnz, lu.nnz / A.nnz, ms_factor, np.abs(x - 1).max()))\n", " lus[o] = lu\n", "\n", "header = (\"ordering\", \"nnz(L)\", \"nnz(U)\", \"nnz(L+U)\", \"fill\", \"factor\", \"max|x-1|\")\n", "print(\"{:>8} {:>8} {:>8} {:>9} {:>6} {:>9} {:>9}\".format(*header))\n", "for o, nl, nu, nlu, ratio, t, err in rows:\n", " print(f\"{o:>8} {nl:8,} {nu:8,} {nlu:9,} {ratio:5.1f}x {t:7.2f}ms {err:9.1e}\")\n", "\n", "# Fill regressions fail CI here. The solution check uses an absolute error: west0479\n", "# is badly conditioned, so 1e-9 is what a backward-stable solve delivers on it.\n", "assert lus[\"colamd\"].nnz < lus[\"natural\"].nnz / 2\n", "assert lus[\"colamd\"].nnz < min(lus[\"amd\"].nnz, lus[\"rcm\"].nnz)\n", "assert all(err < 1e-7 for *_, err in rows)" ] }, { "cell_type": "markdown", "id": "aa12f2c6f94a4b4783db17830b3dea31", "metadata": {}, "source": [ "Every ordering solves the system to the same accuracy. What they change is the\n", "cost: `colamd` cuts the factors to about a third of the natural ordering's\n", "fill. This is MATLAB's `spy(lu(A))` against `spy(lu(A(:,p)))`:" ] }, { "cell_type": "code", "execution_count": null, "id": "c241fe28ee14447fb65e5cf4bba714cd", "metadata": {}, "outputs": [], "source": [ "def pattern(M):\n", " # The stored pattern with every value set to 1, so that adding two patterns\n", " # cannot cancel an entry or drop a stored zero.\n", " S = ms.to_scipy(M).tocsr()\n", " return sp.csr_matrix((np.ones(S.nnz), S.indices, S.indptr), shape=S.shape)\n", "\n", "\n", "fig, axes = plt.subplots(2, 2, figsize=(9.5, 10), dpi=SPY_DPI)\n", "for ax, o, c in zip(axes.flat, ORDERINGS, SERIES):\n", " lu = lus[o]\n", " LU = pattern(lu.L) + pattern(lu.U) # the diagonals overlap: L + U - I\n", " assert LU.nnz == lu.nnz - n\n", " spy(ax, LU, f\"L + U - I ({o})\", color=c)\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "003bd1da1d354adbb03b3f3aa5f5c7a6", "metadata": {}, "source": [ "Some of those stored entries are exactly zero: the elimination cancelled\n", "them. They are still fill. The solver allocated them and computed them, and\n", "their positions are fixed by the pattern alone. The count and the plots\n", "therefore include them:" ] }, { "cell_type": "code", "execution_count": null, "id": "3ada72fef35d4bc7964f8a2e0d24be04", "metadata": {}, "outputs": [], "source": [ "for o in (\"natural\", \"colamd\"):\n", " lu = lus[o]\n", " zeros = int((ms.to_scipy(lu.L).data == 0).sum() + (ms.to_scipy(lu.U).data == 0).sum())\n", " print(f\"{o:>8}: {lu.nnz:6,} stored in L and U, {zeros:5,} of them exactly zero\")" ] }, { "cell_type": "markdown", "id": "73f8a739b04b4b64a9bf4ba5e0e0a1b6", "metadata": {}, "source": [ "The factors also satisfy the identity exactly as documented. Reconstructing\n", "`A` from them is a direct check that the permutations are the ones returned:" ] }, { "cell_type": "code", "execution_count": null, "id": "cda2ce6318b74755830e8dd96b18fcbf", "metadata": {}, "outputs": [], "source": [ "lu = lus[\"colamd\"]\n", "L, U = ms.to_scipy(lu.L), ms.to_scipy(lu.U)\n", "PAQ = S[lu.row_perm][:, lu.col_perm]\n", "rel = spla.norm(L @ U - PAQ) / spla.norm(S)\n", "print(f\"||A[row_perm][:, col_perm] - L U|| / ||A|| = {rel:.1e}\")\n", "print(f\"num_perturbed = {lu.num_perturbed}\")\n", "assert lu.num_perturbed == 0 and rel < 1e-14" ] }, { "cell_type": "markdown", "id": "72d061faeca743d9b01e3bf9262ef882", "metadata": {}, "source": [ "### Comparing with MATLAB and SciPy\n", "\n", "MATLAB's page reports 15,918 nonzeros for `lu(A)` and 5,920 for\n", "`lu(A(:,p))`. Two things make the raw counts differ from the ones above:\n", "\n", "- **Counting.** MATLAB's single-output `lu` returns `L + U - I`, so each\n", " diagonal entry is counted once. `L` here stores its unit diagonal, so\n", " subtract `n` to compare.\n", "- **Pivoting.** MATLAB, SciPy (SuperLU) and mtl5 (Gilbert-Peierls LU) pick\n", " different pivots and break ties differently, so the factors differ. The\n", " natural ordering is the most sensitive, because without fill reduction every\n", " pivot choice spreads further.\n", "\n", "What carries over between implementations is the size of the effect: column\n", "minimum degree cuts the fill roughly threefold." ] }, { "cell_type": "code", "execution_count": null, "id": "d6d4a027083d41119ca4e9a07419c92a", "metadata": {}, "outputs": [], "source": [ "matlab = {\"natural\": 15918, \"colamd\": 5920}\n", "scipy_spec = {\"natural\": \"NATURAL\", \"colamd\": \"COLAMD\"}\n", "\n", "print(f\"{'ordering':>8} {'mtl5':>8} {'SciPy':>8} {'MATLAB':>8} nnz(L+U-I)\")\n", "counts = {}\n", "for o in (\"natural\", \"colamd\"):\n", " f = spla.splu(S.tocsc(), permc_spec=scipy_spec[o])\n", " counts[o] = (lus[o].nnz - n, f.L.nnz + f.U.nnz - n, matlab[o])\n", " print(f\"{o:>8} {counts[o][0]:8,} {counts[o][1]:8,} {counts[o][2]:8,}\")\n", "\n", "for name, i in ((\"mtl5\", 0), (\"SciPy\", 1), (\"MATLAB\", 2)):\n", " print(f\"{name:>6}: colamd cuts fill {counts['natural'][i] / counts['colamd'][i]:.1f}x\")" ] }, { "cell_type": "markdown", "id": "b164de531e50474a9f027d9970bea4eb", "metadata": {}, "source": [ "### KLU: factor only what has to be factored\n", "\n", "KLU (Davis and Palamadai Natarajan, 2010) does not order and factor the whole\n", "matrix. It first permutes A to *block triangular form*,\n", "B = P·R·A·Q, using a Dulmage–Mendelsohn decomposition. Here R is the row\n", "scaling. B is block upper triangular, so solving with it needs only the\n", "diagonal blocks factored: the blocks above them enter the block\n", "back-substitution as they are, and they never fill.\n", "\n", "`ms.klu` exposes that structure rather than a single L and U, which it does\n", "not have:\n", "- `row_perm`, `col_perm` and `row_scale` give P, Q and R;\n", "- `block_starts` gives the block boundaries, and `B` the permuted matrix;\n", "- `block(i)` gives diagonal block i's own `L`, `U`, `row_perm` and\n", " `col_perm`.\n", "\n", "Reordering each diagonal block by its own pivots shows everything KLU stores\n", "for `west0479`:" ] }, { "cell_type": "code", "execution_count": null, "id": "8ebbdb4523a846c79395e7a0897bb5c0", "metadata": {}, "outputs": [], "source": [ "k = ms.klu(A)\n", "starts, sizes = k.block_starts, np.diff(k.block_starts)\n", "B = ms.to_scipy(k.B).tocsr()\n", "blocks = [k.block(i) for i in range(k.nblocks)]\n", "\n", "# Order each diagonal block by its own pivots: B's diagonal blocks then equal L_i U_i.\n", "R = np.concatenate([starts[i] + blk[\"row_perm\"] for i, blk in enumerate(blocks)])\n", "C = np.concatenate([starts[i] + blk[\"col_perm\"] for i, blk in enumerate(blocks)])\n", "B2 = B[R][:, C].tocoo()\n", "block_of = np.repeat(np.arange(k.nblocks), sizes)\n", "upper = block_of[B2.row] < block_of[B2.col]\n", "assert not np.any(block_of[B2.row] > block_of[B2.col]) # block upper triangular\n", "\n", "# Everything KLU stores: the off-diagonal blocks of B, and L_i + U_i - I per block.\n", "rows, cols = [B2.row[upper]], [B2.col[upper]]\n", "for i, blk in enumerate(blocks):\n", " LU = (pattern(blk[\"L\"]) + pattern(blk[\"U\"])).tocoo()\n", " rows.append(starts[i] + LU.row)\n", " cols.append(starts[i] + LU.col)\n", " Bi = B[starts[i] : starts[i + 1], starts[i] : starts[i + 1]].toarray()\n", " Li, Ui = ms.to_scipy(blk[\"L\"]).toarray(), ms.to_scipy(blk[\"U\"]).toarray()\n", " Bi_p = Bi[blk[\"row_perm\"]][:, blk[\"col_perm\"]]\n", " assert np.abs(Li @ Ui - Bi_p).max() <= 1e-12 * np.abs(Bi).max()\n", "r_all, c_all = np.concatenate(rows), np.concatenate(cols)\n", "stored = sp.csr_matrix((np.ones(len(r_all)), (r_all, c_all)), shape=(n, n))\n", "\n", "fig, axes = plt.subplots(1, 2, figsize=(9.5, 5.2), dpi=SPY_DPI)\n", "spy(axes[0], k.B, f\"B = P R A Q: {k.nblocks} diagonal blocks\", color=SERIES[0])\n", "spy(axes[1], stored, \"KLU's factors + off-diagonal blocks\", color=SERIES[1])\n", "plt.tight_layout()\n", "plt.show()\n", "\n", "singletons = int((sizes == 1).sum())\n", "print(f\"{k.nblocks} blocks: {singletons} of size 1, largest {sizes.max()}\")\n", "print(\n", " f\"KLU stores {stored.nnz:,} entries; splu(colamd) stores L + U - I = {lus['colamd'].nnz - n:,}\"\n", ")\n", "assert stored.nnz == k.nnz - n + int(upper.sum())\n", "assert stored.nnz < lus[\"colamd\"].nnz - n\n", "assert singletons > 100 and sizes.max() < n" ] }, { "cell_type": "markdown", "id": "0a91eafa379b4f38a89e0f2fea291afd", "metadata": {}, "source": [ "Most of `west0479` is not coupled at all: more than a hundred of its rows\n", "are 1×1 blocks, whose factor is the matrix entry itself. Only one block, of\n", "308 rows, needs a real sparse LU, and KLU orders it with AMD on its own. The\n", "entries above the diagonal blocks are stored as they are, with no fill. That\n", "is why KLU stores fewer entries than the best whole-matrix ordering. It is\n", "also why KLU is the solver for circuit matrices, which are highly reducible\n", "in the same way." ] }, { "cell_type": "markdown", "id": "7e976364c46d4db988f1940056803b17", "metadata": {}, "source": [ "## 3. A symmetric problem: a different winner\n", "\n", "`colamd` won above because `west0479` is unsymmetric. Now take the 2-D Poisson\n", "matrix on an 80 × 80 grid: 6,400 unknowns, symmetric positive definite.\n", "\n", "- Here $A + A^T$ is just the pattern of $A$, so `amd` orders the true\n", " elimination graph.\n", "- `colamd` orders $A^TA$ instead. For a symmetric $A$ that is the pattern of\n", " $A^2$, which couples neighbours of neighbours. It is a denser graph than the\n", " one the factorization actually eliminates.\n", "- Because the matrix is SPD, Cholesky applies too: it needs no pivoting and\n", " stores only `L`." ] }, { "cell_type": "code", "execution_count": null, "id": "44cb53d5eb2f49d0ae87524018d9666b", "metadata": {}, "outputs": [], "source": [ "P = mtl5.generators.poisson2d(80, 80)\n", "SP = ms.to_scipy(P).tocsr()\n", "N = P.shape[0]\n", "print(f\"poisson2d(80, 80): n = {N:,}, nnz(A) = {P.nnz:,}\")\n", "\n", "lu_p, chol_p = {}, {}\n", "print(f\"{'ordering':>8} {'LU nnz':>10} {'LU factor':>10} {'Cholesky nnz':>13} {'Chol factor':>12}\")\n", "for o in ORDERINGS:\n", " t_lu, lu_p[o] = best_time(lambda o=o: ms.splu(P, ordering=o), repeats=3)\n", " t_ch, chol_p[o] = best_time(lambda o=o: ms.cholesky(P, ordering=o), repeats=3)\n", " print(f\"{o:>8} {lu_p[o].nnz:10,} {t_lu:8.1f}ms {chol_p[o].nnz:13,} {t_ch:10.1f}ms\")\n", "\n", "assert lu_p[\"amd\"].nnz < lu_p[\"colamd\"].nnz < lu_p[\"natural\"].nnz\n", "assert chol_p[\"amd\"].nnz < chol_p[\"natural\"].nnz / 3" ] }, { "cell_type": "markdown", "id": "d680500b48b0416797fd9267946630f8", "metadata": {}, "source": [ "The ranking has flipped: `amd` gives the least fill, and `colamd` is now\n", "second. The Cholesky factors show why the orderings differ. They are drawn here\n", "for a 24 × 24 grid, where the structure is visible at this size. `natural` keeps\n", "the fill inside a band as wide as the grid, and fills the band completely.\n", "`rcm` does the same inside a profile that narrows toward both ends. `amd` eliminates in an order that never lets\n", "fill accumulate in one place:" ] }, { "cell_type": "code", "execution_count": null, "id": "2f1782d1f8424cdd9056174c2595c3f2", "metadata": {}, "outputs": [], "source": [ "small = mtl5.generators.poisson2d(24, 24)\n", "fig, axes = plt.subplots(1, 3, figsize=(14, 5.2), dpi=SPY_DPI)\n", "for ax, o, c in zip(axes, (\"natural\", \"rcm\", \"amd\"), (SERIES[0], SERIES[3], SERIES[2])):\n", " L = ms.cholesky(small, ordering=o).L\n", " spy(ax, L, f\"Cholesky L ({o}, n = 576)\", color=c)\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "62a1ba0f0b634675b3795467f4067ef1", "metadata": {}, "source": [ "That gives a rule of thumb, which the factorizations' default `ordering=`\n", "arguments already follow:\n", "\n", "| Matrix | Factorization | Ordering (default) |\n", "|---|---|---|\n", "| symmetric positive definite | `cholesky`, `supernodal_ldlt` | `amd` |\n", "| symmetric indefinite | `ldlt`, `supernodal_ldlt` | `amd` |\n", "| unsymmetric | `splu`, `supernodal_lu`, `qr` | `colamd` |\n", "| unsymmetric, nearly symmetric pattern, strong diagonal | `splu` | try `amd` |\n", "| a narrow band or profile is the goal | any | `rcm` |\n", "\n", "When in doubt, measure: `ms.splu(A, ordering=o).nnz` for each `o` in\n", "`ms.orderings()` costs a few factorizations and settles it.\n", "\n", "## 4. The solve pipeline\n", "\n", "A direct solve has four stages, and they have very different costs:\n", "\n", "1. **Ordering.** A fill-reducing permutation, from the pattern alone.\n", "2. **Symbolic analysis.** The structure of the factors (elimination tree,\n", " column counts), again from the pattern alone.\n", "3. **Numeric factorization.** The arithmetic. For LU this includes pivoting.\n", "4. **Solve.** Two triangular substitutions per right-hand side.\n", "\n", "Constructing a factor object runs stages 1 to 3. `solve()` runs stage 4, and is\n", "cheap enough to call for many right-hand sides. `refactor(A_new)` reruns\n", "**only stage 3**, for a matrix with the same pattern. It reuses the ordering,\n", "the symbolic structure and, for LU, the pivot sequence." ] }, { "cell_type": "code", "execution_count": null, "id": "a0650c14b09f4270ae30438d578c96b8", "metadata": {}, "outputs": [], "source": [ "lu = lu_p[\"amd\"]\n", "t_factor, _ = best_time(lambda: ms.splu(P, ordering=\"amd\"), repeats=3)\n", "t_refactor, _ = best_time(lambda: lu.refactor(P), repeats=3)\n", "t_solve, _ = best_time(lambda: lu.solve(np.ones(N)), repeats=10)\n", "\n", "print(f\"factor (stages 1-3) {t_factor:7.2f} ms\")\n", "print(f\"refactor (stage 3) {t_refactor:7.2f} ms {t_factor / t_refactor:4.1f}x cheaper\")\n", "print(f\"solve (stage 4) {t_solve:7.2f} ms {t_factor / t_solve:4.0f}x cheaper\")" ] }, { "cell_type": "markdown", "id": "6d4b34021826402b842ef24a8709179f", "metadata": {}, "source": [ "`refactor()` is built for problems whose values change while the pattern\n", "stays fixed: implicit time stepping, Newton iterations, circuit transients,\n", "parameter sweeps. Here twenty steps of $(A + c_k I)\\,x = b$ are solved two ways.\n", "In the first, each step is factored from scratch. In the second, one factor\n", "object is refactored at every step." ] }, { "cell_type": "code", "execution_count": null, "id": "3094e7a6a3534ef38031b932aa6d61e1", "metadata": {}, "outputs": [], "source": [ "eye = sp.identity(N, format=\"csr\")\n", "systems = [(SP + 0.1 * k * eye).tocsr() for k in range(1, 21)]\n", "assert all(\n", " np.array_equal(M.indptr, SP.indptr) and np.array_equal(M.indices, SP.indices) for M in systems\n", "), \"refactor() needs the same sparsity pattern at every step\"\n", "mats = [ms.from_scipy(M) for M in systems]\n", "rhs = [M @ np.ones(N) for M in systems]\n", "\n", "\n", "def run_fresh():\n", " return [ms.splu(M, ordering=\"amd\").solve(r) for M, r in zip(mats, rhs)]\n", "\n", "\n", "def run_reuse():\n", " lu = ms.splu(mats[0], ordering=\"amd\") # the initial factorization is timed too\n", " out = []\n", " for M, r in zip(mats, rhs):\n", " lu.refactor(M) # the first step refactors the same values: one wasted refactor\n", " out.append(lu.solve(r))\n", " return out\n", "\n", "\n", "# Both workloads do a factorization and a solve per step. Running one always\n", "# first would hand the other a warm cache and allocator, so the rounds\n", "# alternate which goes first, and each method's best round is reported, as in\n", "# the other timings. The solutions are checked after the timers.\n", "t_fresh = t_reuse = float(\"inf\")\n", "for round_ in range(3):\n", " order = (run_fresh, run_reuse) if round_ % 2 == 0 else (run_reuse, run_fresh)\n", " for fn in order:\n", " t = time.perf_counter()\n", " out = fn()\n", " elapsed = time.perf_counter() - t\n", " if fn is run_fresh:\n", " t_fresh, fresh = min(t_fresh, elapsed), out\n", " else:\n", " t_reuse, reused = min(t_reuse, elapsed), out\n", "\n", "residuals = [\n", " np.linalg.norm(Ms @ x.to_numpy() - r) / np.linalg.norm(r)\n", " for Ms, r, x in zip(systems + systems, rhs + rhs, fresh + reused)\n", "]\n", "\n", "print(f\"20 steps, factor each step: {t_fresh * 1e3:6.0f} ms\")\n", "print(f\"20 steps, refactor: {t_reuse * 1e3:6.0f} ms ({t_fresh / t_reuse:.1f}x faster)\")\n", "print(f\"worst relative residual: {max(residuals):.1e}\")\n", "assert max(residuals) < 1e-12" ] }, { "cell_type": "markdown", "id": "62b35bc4a0d64574b585c8bf387bb939", "metadata": {}, "source": [ "The reused pivot sequence is also `refactor()`'s limit. The pivots were chosen\n", "for the first matrix's values. If the values drift far enough that one of\n", "those pivots becomes small, the refactored solve loses accuracy. `refactor()`\n", "does not re-pivot for you. A cheap residual check, as above, is how you notice,\n", "and a fresh `splu()` is the remedy.\n", "\n", "## Summary\n", "\n", "- Fill-in, not the nonzeros of `A`, decides the cost of a direct solve, and\n", " the elimination order decides the fill.\n", "- Choose the ordering for the structure: `colamd` for unsymmetric LU and QR,\n", " `amd` for symmetric factorizations, `rcm` when a narrow band is the goal.\n", " The defaults follow this.\n", "- The factors are inspectable. `L`, `U`, `row_perm` and `col_perm` satisfy\n", " `A[row_perm][:, col_perm] == L @ U`. KLU exposes its block triangular\n", " form instead: `B`, the BTF permutations and each block's factors through\n", " `block(i)`. For plots without matplotlib,\n", " `mtl5.io.spy(M, \"file.png\")` writes the pattern to a PNG.\n", "- Analysis is a one-time cost when the pattern is fixed: use `refactor()`,\n", " and keep `solve()` for each new right-hand side.\n", "\n", "Still to come in the sparse direct guide (#125): choosing a factorization, and\n", "mixed-precision direct solves (a float32 factor refined with\n", "`mtl5.mixed.iterative_refine`)." ] }, { "cell_type": "markdown", "id": "api-reference", "metadata": {}, "source": [ "API reference: [`mtl5.io.mm_read`](https://stillwater-sc.github.io/mtl5-python/api/generated/mtl5.io.mm_read.html), [`mtl5.sparse.splu`](https://stillwater-sc.github.io/mtl5-python/api/generated/mtl5.sparse.splu.html), [`mtl5.sparse.cholesky`](https://stillwater-sc.github.io/mtl5-python/api/generated/mtl5.sparse.cholesky.html), [`mtl5.sparse.ordering`](https://stillwater-sc.github.io/mtl5-python/api/generated/mtl5.sparse.ordering.html), [`mtl5.sparse.orderings`](https://stillwater-sc.github.io/mtl5-python/api/generated/mtl5.sparse.orderings.html), [`mtl5.sparse.colamd`](https://stillwater-sc.github.io/mtl5-python/api/generated/mtl5.sparse.colamd.html), [`mtl5.sparse.amd`](https://stillwater-sc.github.io/mtl5-python/api/generated/mtl5.sparse.amd.html), [`mtl5.sparse.rcm`](https://stillwater-sc.github.io/mtl5-python/api/generated/mtl5.sparse.rcm.html), [`mtl5.sparse.to_scipy`](https://stillwater-sc.github.io/mtl5-python/api/generated/mtl5.sparse.to_scipy.html).\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10" } }, "nbformat": 4, "nbformat_minor": 5 }