Examples

Six examples, each written in Python, R, Julia and C. The source files are in examples/ in the repository; the output shown under each one is what it prints.

Installation

Requires Python 3.8 or later. NumPy and SciPy are installed as dependencies.

pip install sTiles

The solver library for your platform is downloaded on first use and cached in ~/.cache/sTiles. python -m sTiles info shows the version and location of the solver in use.

To run the examples:

git clone --depth 1 https://github.com/esmail-abdulfattah/sTiles.git
cd sTiles/examples/python
python 01_quickstart.py

Notes

Examples

01. Quickstart

Factorize Q, then compute log|Q|, solve Q x = b and get the marginal variances diag(Q-1).

examples/python/01_quickstart.py

"""Factorize a sparse SPD matrix, then get the log-determinant, solve a
linear system and read the marginal variances.

    python 01_quickstart.py
"""
import numpy as np
import scipy.sparse as sp
from sTiles import sTiles

# A 1000 x 1000 tridiagonal matrix: 4 on the diagonal, -1 next to it.
n = 1000
Q = sp.diags([-1.0, 4.0, -1.0], [-1, 0, 1], shape=(n, n), format="csc")

# inverse=True reserves room for the selected inverse (the variances below).
with sTiles(Q, cores=2, inverse=True) as s:
    print(f"log|Q|            = {s.logdet:.6f}")

    b = np.ones(n)
    x = s.solve(b)                       # x = Q^-1 b
    print(f"max |Q x - b|     = {np.abs(Q @ x - b).max():.1e}")

    v = s.selinv_diag()                  # diag(Q^-1), the marginal variances
    print(f"first variances   = {v[:3].round(6)}")
# Leaving the with-block frees the factorization.

Output:

log|Q|            = 1317.032401
max |Q x - b|     = 4.4e-16
first variances   = [0.267949 0.287187 0.288568]

02. Solving linear systems

Solve Q x = b for one right-hand side, and for several at once by passing a matrix with one column per right-hand side. In C the solve overwrites its input.

examples/python/02_solve.py

"""Solve Q x = b for one right-hand side, then for several at once.

    python 02_solve.py
"""
import numpy as np
import scipy.sparse as sp
from sTiles import sTiles

n = 1000
Q = sp.diags([-1.0, 4.0, -1.0], [-1, 0, 1], shape=(n, n), format="csc")

with sTiles(Q, cores=2) as s:
    # One right-hand side: a vector of length n.
    b = np.arange(1.0, n + 1)
    x = s.solve(b)
    print(f"one rhs:   x.shape = {x.shape}, max |Q x - b| = {np.abs(Q @ x - b).max():.1e}")

    # Several right-hand sides: an n x k matrix, one column each.
    # All columns are solved in one call, which is faster than a loop.
    B = np.random.default_rng(0).standard_normal((n, 5))
    X = s.solve(B)
    print(f"five rhs:  X.shape = {X.shape}, max |Q X - B| = {np.abs(Q @ X - B).max():.1e}")

Output:

one rhs:   x.shape = (1000,), max |Q x - b| = 5.7e-13
five rhs:  X.shape = (1000, 5), max |Q X - B| = 1.3e-15

03. Selected inverse

Entries of Q-1 without the dense inverse. Values are exact on the pattern of the Cholesky factor (this includes the diagonal and the non-zeros of Q) and 0 outside it.

examples/python/03_selected_inverse.py

"""Read entries of Q^-1 without forming the dense inverse: the diagonal,
single entries, and a row. Checked here against numpy's dense inverse.

    python 03_selected_inverse.py
"""
import numpy as np
import scipy.sparse as sp
from sTiles import sTiles

n = 200
Q = sp.diags([-1.0, 4.0, -1.0], [-1, 0, 1], shape=(n, n), format="csc")
Qinv = np.linalg.inv(Q.toarray())        # only to check the answers

with sTiles(Q, cores=2, inverse=True) as s:
    s.selinv()                           # optional: otherwise runs on first query

    d = s.selinv_diag()                  # all n variances
    print(f"diagonal:   max error = {np.abs(d - np.diag(Qinv)).max():.1e}")

    # One entry. Indices are 0-based, in the original ordering of Q.
    print(f"Qinv[10, 11] = {s.selinv_elm(10, 11):.6f}   (dense: {Qinv[10, 11]:.6f})")

    # Entries are exact inside the pattern of the Cholesky factor, which
    # sTiles stores in whole tiles, and 0 outside it. Ask only for entries
    # you know are in the pattern: the diagonal and the non-zeros of Q are.
    print(f"Qinv[10, 150] = {s.selinv_elm(10, 150):.1f}   (dense: {Qinv[10, 150]:.1e}, outside the pattern)")

    # A row restricted to chosen columns, e.g. the neighbours of node 10.
    row = s.selinv_row(10, [9, 10, 11])
    print(f"row 10 at [9, 10, 11] = {row.round(6)}")

Output:

diagonal:   max error = 1.7e-16
Qinv[10, 11] = 0.077350   (dense: 0.077350)
Qinv[10, 150] = 0.0   (dense: 2.4e-81, outside the pattern)
row 10 at [9, 10, 11] = [0.07735  0.288675 0.07735 ]

04. Reusing the analysis

The ordering and tile layout depend only on the sparsity pattern. Compute them once and refactorize for each new set of values with the same pattern. Timings depend on the machine.

examples/python/04_reuse_analysis.py

"""Analyze the sparsity pattern once, then factorize many matrices that
share it. This is the loop of a hyperparameter search or an optimizer.

    python 04_reuse_analysis.py
"""
import scipy.sparse as sp
from sTiles import sTiles

n = 100_000
T = sp.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(n, n), format="csc")
I = sp.identity(n, format="csc")

def build_Q(kappa):
    return T + kappa * I                 # same non-zero pattern for every kappa

# Step 1, once: ordering and tile layout. They depend only on WHERE the
# non-zeros are, not on their values.
s = sTiles.analyze(build_Q(1.0), cores=2)
print(f"analysis:  {s.analyze_time:.3f} s  (paid once)")

# Step 2, per value set: numeric Cholesky only.
for kappa in [0.1, 1.0, 10.0]:
    s.update(build_Q(kappa))
    print(f"kappa = {kappa:5.1f}   log|Q| = {s.logdet:12.4f}   cholesky: {s.chol_time:.4f} s")

s.close()

Output:

analysis:  0.454 s  (paid once)
kappa =   0.1   log|Q| =   31493.2364   cholesky: 0.0076 s
kappa =   1.0   log|Q| =   96242.5227   cholesky: 0.0061 s
kappa =  10.0   log|Q| =  247788.8801   cholesky: 0.0057 s

05. Sampling from N(0, Q-1)

With Q = C CT, x = C-T z has covariance Q-1 when z ~ N(0, I). The backward solve computes this. Sample variances differ slightly between languages because each uses its own random numbers.

examples/python/05_sampling.py

"""Draw samples from N(0, Q^-1), the Gaussian with precision matrix Q.

If Q = C C^T, then x = C^-T z with z ~ N(0, I) has covariance Q^-1.
solve(z, "Lt") computes exactly that, in the original ordering of Q.

    python 05_sampling.py
"""
import numpy as np
import scipy.sparse as sp
from sTiles import sTiles

n = 1000
Q = sp.diags([-1.0, 4.0, -1.0], [-1, 0, 1], shape=(n, n), format="csc")
rng = np.random.default_rng(1)

with sTiles(Q, cores=2, inverse=True) as s:
    Z = rng.standard_normal((n, 10_000))  # 10 000 draws, one per column
    X = s.solve(Z, "Lt")                   # each column ~ N(0, Q^-1)

    # Check: the sample variances match the exact ones from the selected inverse.
    exact = s.selinv_diag()
    print(f"exact variance of x[0]   = {exact[0]:.4f}")
    print(f"sample variance of x[0]  = {X[0].var():.4f}")

    # With a mean mu, a draw from N(mu, Q^-1) is mu + X[:, k].

Output:

exact variance of x[0]   = 0.2679
sample variance of x[0]  = 0.2713

06. Reading a Matrix Market file

Factorize a matrix read from a .mtx file. Without an argument it reads examples/data/grid40.mtx (a 1600 × 1600 grid Laplacian).

examples/python/06_matrix_market.py

"""Factorize your own matrix, read from a Matrix Market (.mtx) file.

    python 06_matrix_market.py                  # uses ../data/grid40.mtx
    python 06_matrix_market.py my_matrix.mtx
"""
import sys
from pathlib import Path

import scipy.io
from sTiles import sTiles

path = Path(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).parent / "../data/grid40.mtx")

# mmread expands a "symmetric" file to the full matrix; sTiles reads only the
# lower triangle, so either form works.
Q = scipy.io.mmread(path).tocsc()
print(f"{path.name}: {Q.shape[0]} x {Q.shape[1]}, {Q.nnz} non-zeros")

with sTiles(Q, cores=2) as s:
    print(f"log|Q| = {s.logdet:.6f}")
    info = s.summary()
    print(f"non-zeros in L = {info['nnz_factor']}, "
          f"analysis {info['analyze_time']:.3f} s, cholesky {info['chol_time']:.4f} s")

Output:

grid40.mtx: 1600 x 1600, 7840 non-zeros
log|Q| = 1965.308933
non-zeros in L = 20771, analysis 0.030 s, cholesky 0.0011 s