Examples

Complete, runnable programs: copy one into a file and run it. Each needs only pip install "peigentux[sparse]". Outputs are from macOS on Apple silicon; the last digits can differ on other platforms.

Dense linear algebra

Solve, QR, SVD and norms

Dense routines mirror numpy.linalg: same shapes, same conventions.

python
import numpy as np
from peigen import linalg

rng = np.random.default_rng(0)
A = rng.standard_normal((500, 500)) + 50 * np.eye(500)
B = rng.standard_normal((500, 3))

X = linalg.solve(A, B)            # LU with partial pivoting (LAPACK dgesv)
print(np.allclose(A @ X, B))      # True

Q, R = linalg.qr(A)               # Householder QR: A = Q @ R
U, s, Vt = linalg.svd(A)          # singular values in descending order
print(f"cond(A) = {s[0] / s[-1]:.2f}")
print(f"||A||_F = {linalg.norm(A):.1f}")
Output:
True
cond(A) = 3.89
||A||_F = 1223.6

Least-squares curve fit

Fit a quadratic with QR, or with the SVD when the design matrix may be rank deficient.

python
import numpy as np
from peigen import decomp

rng = np.random.default_rng(1)
t = np.linspace(0.0, 1.0, 200)
y = 3.0 - 2.0 * t + 0.5 * t**2 + 0.01 * rng.standard_normal(t.size)
A = np.vander(t, 3, increasing=True)   # columns: 1, t, t^2

coef = decomp.QR(A).solve(y)           # least squares via QR (A has full column rank)
print(coef.round(2))                   # [ 3.  -2.   0.5]

svd = decomp.SVD(A)                    # minimum-norm least squares; also handles rank deficiency
print(svd.solve(y).round(2))
Output:
[ 3.  -2.   0.5]
[ 3.  -2.   0.5]

Principal components with eigh

Eigen-decompose a covariance matrix. eigh reads one triangle and returns eigenvalues in ascending order.

python
import numpy as np
from peigen import linalg

rng = np.random.default_rng(2)
latent = rng.standard_normal((2000, 2))                    # 2 hidden factors ...
X = latent @ rng.standard_normal((2, 6)) + 0.1 * rng.standard_normal((2000, 6))  # ... seen in 6 features
C = np.cov(X, rowvar=False)

w, V = linalg.eigh(C)                 # ascending eigenvalues, orthonormal eigenvectors (columns)
w, V = w[::-1], V[:, ::-1]            # largest first
print((w / w.sum()).round(3))         # first two components carry almost all the variance
scores = (X - X.mean(axis=0)) @ V[:, :2]
print(scores.shape)                   # (2000, 2)
Output:
[0.519 0.479 0.001 0.001 0.001 0.001]
(2000, 2)

Sparse direct solvers

Poisson equation: factor once, solve many times

The basic sparse Cholesky workflow. One factorization serves any number of right-hand sides, and a 2D b is solved in one blocked pass.

python
import numpy as np
import scipy.sparse as sp
from peigen import sparse

def laplacian_2d(m):
    """5-point finite-difference Laplacian on an m x m grid (symmetric positive definite)."""
    t = sp.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(m, m))
    i = sp.eye(m)
    return (sp.kron(i, t) + sp.kron(t, i)).tocsc()

K = laplacian_2d(200)            # 40,000 x 40,000
fac = sparse.cholesky(K)         # AMD ordering + L D L^T, computed once

b = np.ones(K.shape[0])
x = fac.solve(b)
print(f"residual: {np.linalg.norm(K @ x - b):.1e}")

B = np.random.default_rng(0).standard_normal((K.shape[0], 32))
X = fac.solve(B)                 # 32 right-hand sides in one blocked pass
print(X.shape, f"nnz(L) = {fac.factor_nnz:,}")
Output:
residual: 3.7e-10
(40000, 32) nnz(L) = 1,099,835

Time stepping with refactorize and shift

Implicit Euler needs I + dt·K. Factor K + I/dt through shift, then change the step size without repeating the symbolic analysis.

python
import numpy as np
import scipy.sparse as sp
from peigen import sparse

# Implicit Euler for u' = -K u:  (I + dt K) u_new = u,  i.e.  (K + I/dt) u_new = u / dt
m = 100
t = sp.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(m, m))
K = (sp.kron(sp.eye(m), t) + sp.kron(t, sp.eye(m))).tocsc() * m**2   # -Laplacian, h = 1/m

u = np.zeros(m * m)
u[(m // 2) * m + m // 2] = m**2             # unit heat pulse in the middle
dt = 1e-4
fac = sparse.cholesky(K, shift=1.0 / dt)     # factorize K + I/dt

for step in range(40):
    u = fac.solve(u / dt)
    if step == 9:                            # transient has decayed: take bigger steps
        dt *= 10
        fac.refactorize(K, shift=1.0 / dt)   # same pattern: numeric phase only

print(f"remaining heat: {u.sum() / m**2:.4f}")
Output:
remaining heat: 0.8348

Gaussian Markov random field log-likelihood

Log-determinants of sparse precision matrices, the expensive part of GMRF and sparse Gaussian-process likelihoods. refactorize sweeps a hyperparameter cheaply.

python
import numpy as np
import scipy.sparse as sp
from peigen import sparse

# Gaussian Markov random field on a grid: precision Q = L + kappa2 * I (L = graph Laplacian)
m = 150
t = sp.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(m, m))
L = (sp.kron(sp.eye(m), t) + sp.kron(t, sp.eye(m))).tocsc()
n = L.shape[0]
y = np.random.default_rng(0).standard_normal(n)

fac = sparse.cholesky(L, shift=1.0)
for kappa2 in [0.1, 1.0, 10.0]:
    fac.refactorize(L, shift=kappa2)         # Q = L + kappa2 * I, reusing the symbolic analysis
    quad = y @ (L @ y) + kappa2 * (y @ y)    # y^T Q y
    loglik = 0.5 * fac.logdet() - 0.5 * quad - 0.5 * n * np.log(2 * np.pi)
    print(f"kappa2={kappa2:5.1f}  log p(y) = {loglik:,.1f}")
Output:
kappa2=  0.1  log p(y) = -52,765.8
kappa2=  1.0  log p(y) = -59,618.6
kappa2= 10.0  log p(y) = -147,803.2

Equality-constrained QP (KKT system)

Saddle-point matrices are symmetric but indefinite. mode="multifrontal" pivots with 1×1 and 2×2 blocks, and the inertia certifies that the solution is a minimizer.

python
import numpy as np
import scipy.sparse as sp
from peigen import sparse

# minimize 1/2 x^T H x - c^T x  subject to  A x = b
rng = np.random.default_rng(0)
n, m = 500, 50
H = sp.diags([-1.0, 4.0, -1.0], [-1, 0, 1], shape=(n, n))
A = sp.random(m, n, density=0.05, random_state=1) + sp.eye(m, n)
c, b = rng.standard_normal(n), rng.standard_normal(m)

K = sp.bmat([[H, A.T], [A, None]], format="csc")   # symmetric indefinite saddle-point matrix
kkt = sparse.cholesky(K, mode="multifrontal")      # pivoted L D L^T with 1x1 / 2x2 pivots

print(kkt.inertia)        # (500, 50, 0): n positive, m negative -> unique minimizer
sol = kkt.solve(np.concatenate([c, b]))
x, lam = sol[:n], sol[n:]
print(f"constraint violation: {np.abs(A @ x - b).max():.1e}")
Output:
(500, 50, 0)
constraint violation: 1.8e-15

Nonsymmetric systems: sparse LU and BiCGSTAB

For matrices that aren't symmetric, use a reusable sparse LU, or BiCGSTAB when a factorization is too expensive.

python
import numpy as np
import scipy.sparse as sp
from peigen import sparse

# Nonsymmetric: 1D convection-diffusion  -eps u'' + u' = f  (upwind differences)
n, eps = 500, 0.1
h = 1.0 / (n + 1)
diffusion = sp.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(n, n)) * (eps / h**2)
convection = sp.diags([-1.0, 1.0], [-1, 0], shape=(n, n)) / h
A = (diffusion + convection).tocsc()

lu = sparse.factorize(A)                  # Eigen SparseLU, reusable
F = np.ones((n, 4)) * np.arange(1, 5)     # four right-hand sides
U = lu.solve(F)
print(U.shape, f"max residual: {np.abs(A @ U - F).max():.1e}")

u = sparse.solve(A, F[:, 0], method="bicgstab", tol=1e-10, maxiter=20000)
print(f"BiCGSTAB relative residual: {np.linalg.norm(A @ u - F[:, 0]) / np.linalg.norm(F[:, 0]):.1e}")
Output:
(500, 4) max residual: 2.8e-11
BiCGSTAB relative residual: 7.8e-11

Iterative solvers

Conjugate gradient and preconditioners

solve_stats reports the iteration count, which makes comparing preconditioners easy. Jacobi pays off when the diagonal varies a lot.

python
import numpy as np
import scipy.sparse as sp
from peigen import sparse

m = 100
t = sp.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(m, m))
lap = sp.kron(sp.eye(m), t) + sp.kron(t, sp.eye(m))
d = sp.diags(np.random.default_rng(0).uniform(1.0, 5.0, m * m))
K = (d @ lap @ d).tocsc()          # SPD, with a widely varying diagonal
b = np.ones(K.shape[0])

for pre in ["none", "jacobi"]:
    stats = sparse.solve_stats(K, b, method="cg", preconditioner=pre, tol=1e-8)
    print(f"{pre:>6}: {stats['iterations']:4d} iterations")

x = sparse.solve(K, b, method="cg", preconditioner="jacobi", tol=1e-10)
print(f"relative residual: {np.linalg.norm(K @ x - b) / np.linalg.norm(b):.1e}")
Output:
  none:  681 iterations
jacobi:  302 iterations
relative residual: 9.5e-11

Interoperability

Sparse products with any SciPy format

Inputs can be CSR, CSC, COO, or *_array types; they are converted internally and never modified.

python
import numpy as np
import scipy.sparse as sp
from peigen import sparse

A = sp.random(1000, 800, density=0.01, format="csr", random_state=0)   # any SciPy format
B = np.random.default_rng(0).standard_normal((800, 16))

Y = sparse.spmm(A, B)              # sparse @ dense -> ndarray
C = sparse.spspmm(A, A.T)          # sparse @ sparse -> scipy.sparse CSC
print(np.allclose(Y, A @ B), C.format, C.shape)
Output:
True csc (1000, 1000)

Check your build

Confirm which BLAS/LAPACK backend your installed wheel uses:

python
import peigen

peigen.show_build_config()
print(peigen.build_config()["lapack_backend"])