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