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.pysTiles is on CRAN. The solver library is a separate download, installed once:
install.packages("sTiles")
sTiles::sTiles_install_library()
The development version is on r-universe:
install.packages("sTiles", repos = c("https://esmail-abdulfattah.r-universe.dev", "https://cloud.r-project.org")).
To run the examples:
git clone --depth 1 https://github.com/esmail-abdulfattah/sTiles.git
cd sTiles/examples/r
Rscript 01_quickstart.R
From RStudio, set the working directory to examples/r before sourcing a file.
Requires Julia 1.10 or later. In package mode (press ]):
pkg> add https://github.com/esmail-abdulfattah/sTiles:julia
The solver library is downloaded when the package first loads and cached in
~/.cache/sTiles.
To run the examples:
git clone --depth 1 https://github.com/esmail-abdulfattah/sTiles.git
cd sTiles/examples/julia
julia 01_quickstart.jl
If Julia crashes on using SparseArrays, an LD_LIBRARY_PATH set in
your shell (often by Intel oneAPI) is shadowing Julia's own libraries; run
env -u LD_LIBRARY_PATH julia ....
Download the archive for your platform from the download page and unpack it. It contains:
include/stiles.h header lib/libstiles.so library (.dylib on macOS, .dll on Windows) lib/pkgconfig/stiles.pc pkg-config file BUILDINFO compiler, flags and BLAS used for the build
Below, STILES is the path of the unpacked folder. To build and run the examples:
git clone --depth 1 https://github.com/esmail-abdulfattah/sTiles.git
cd sTiles/examples/c
make STILES=$HOME/libstiles-linux-x86_64
./01_quickstart
make STILES=... run builds and runs all six. common.h contains
helpers shared by the examples (error check, test matrix, residual, timer); it is not part of sTiles.
Compiling your own program
Linux:
gcc -O2 app.c -I$STILES/include \
-L$STILES/lib -Wl,-rpath,$STILES/lib -lstiles -lm -o app
macOS:
clang -O2 app.c -I$STILES/include \
-L$STILES/lib -Wl,-rpath,$STILES/lib -lstiles -o app
Windows, from an MSYS2 UCRT64 shell (the DLLs are found through PATH):
gcc -O2 app.c -I$STILES/include -L$STILES/lib -lstiles -o app.exe
PATH="$STILES/lib:$PATH" ./app.exe
With pkg-config:
export PKG_CONFIG_PATH=$STILES/lib/pkgconfig
gcc -O2 app.c $(pkg-config --cflags --libs stiles) -Wl,-rpath,$STILES/lib -o app
With CMake (cmake -DSTILES=/path/to/archive -B build && cmake --build build):
cmake_minimum_required(VERSION 3.16)
project(app C)
find_path(STILES_INCLUDE stiles.h PATHS ${STILES}/include REQUIRED)
find_library(STILES_LIB stiles PATHS ${STILES}/lib REQUIRED)
add_executable(app app.c)
target_include_directories(app PRIVATE ${STILES_INCLUDE})
target_link_libraries(app PRIVATE ${STILES_LIB} m)
The rpath lets the program find the library at run time without
LD_LIBRARY_PATH. The header has extern "C" guards, so C++ code
includes and links it the same way.
Order of calls
For one matrix (group 0, call 0):
sTiles_create | create the handle: number of matrices, cores, whether the selected inverse is needed |
sTiles_assign_graph_one_call | give the sparsity pattern (lower triangle, 0-based) |
sTiles_init_group | analysis: ordering and tile layout |
sTiles_assign_values | give the values, in the same order as the pattern |
sTiles_bind | start the worker threads |
sTiles_chol, sTiles_selinv, sTiles_solve_* | compute |
sTiles_unbind | stop the worker threads |
sTiles_get_logdet, sTiles_get_selinv_* | read results |
sTiles_quit | free everything |
To factorize new values with the same pattern, repeat from sTiles_assign_values
to sTiles_unbind (example 04). All functions are documented in the
API reference.
Notes
- sTiles reads only the lower triangle of Q. Pass it in coordinate form (row ≥ col), diagonal included.
- Indices are 0-based1-based1-based0-based and refer to the original ordering of Q.
- The number of threads defaults to 1. The examples use 2.
- The selected inverse must be requested when the factorization is created
(
inverse=Trueinverse = TRUEinverse = trueget_inverse[0] = true). - Only one factorization can be open per process. Close it
(
s.close()or awithblocksTiles_close(s)close(F)sTiles_quit()) before creating the next one. - Examples 01–05 use a tridiagonal matrix with 4 on the diagonal and −1 off the diagonal.
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]
# Factorize a sparse SPD matrix, then get the log-determinant, solve a
# linear system and read the marginal variances.
#
# Rscript 01_quickstart.R
library(sTiles)
library(Matrix)
# A 1000 x 1000 tridiagonal matrix: 4 on the diagonal, -1 next to it.
n <- 1000
Q <- bandSparse(n, k = c(0, 1), diagonals = list(rep(4, n), rep(-1, n - 1)),
symmetric = TRUE)
# inverse = TRUE reserves room for the selected inverse (the variances below).
s <- sTiles(Q, cores = 2, inverse = TRUE)
cat(sprintf("log|Q| = %.6f\n", sTiles_logdet(s)))
b <- rep(1, n)
x <- sTiles_solve(s, b) # x = Q^-1 b
cat(sprintf("max |Q x - b| = %.1e\n", max(abs(Q %*% x - b))))
v <- sTiles_selinv_diag(s) # diag(Q^-1), the marginal variances
cat("first variances =", round(v[1:3], 6), "\n")
sTiles_close(s) # free the factorization now
Output:
log|Q| = 1317.032401 max |Q x - b| = 4.4e-16 first variances = 0.267949 0.287187 0.288568
examples/julia/01_quickstart.jl
# Factorize a sparse SPD matrix, then get the log-determinant, solve a
# linear system and read the marginal variances.
#
# julia 01_quickstart.jl
using sTiles, LinearAlgebra, SparseArrays, Printf
# A 1000 x 1000 tridiagonal matrix: 4 on the diagonal, -1 next to it.
n = 1000
Q = spdiagm(-1 => fill(-1.0, n - 1), 0 => fill(4.0, n), 1 => fill(-1.0, n - 1))
# inverse = true reserves room for the selected inverse (the variances below).
F = sTiles.cholesky(Q; cores = 2, inverse = true)
@printf("log|Q| = %.6f\n", logdet(F))
b = ones(n)
x = F \ b # x = Q^-1 b
@printf("max |Q x - b| = %.1e\n", maximum(abs.(Q * x - b)))
v = selinv_diag(F) # diag(Q^-1), the marginal variances
println("first variances = ", round.(v[1:3]; digits = 6))
close(F) # free memory and threads now
Output:
log|Q| = 1317.032401 max |Q x - b| = 4.4e-16 first variances = [0.267949, 0.287187, 0.288568]
/* Factorize a sparse SPD matrix, then get the log-determinant, solve a
* linear system and read the marginal variances.
*
* make 01_quickstart && ./01_quickstart
*/
#include "stiles.h"
#include "common.h"
int main(void)
{
/* A 1000 x 1000 tridiagonal matrix: 4 on the diagonal, -1 next to it. */
lower_coo Q = tridiagonal(1000, 4.0, -1.0);
int n = Q.n;
/* 0. Print errors only (the default also prints [TIME] progress rows). */
sTiles_set_log_level(-1);
/* 1. Create a handle: one group (one sparsity pattern) holding one call
* (one matrix), on 2 cores, standard Cholesky, with the selected
* inverse enabled. Every call below then names group 0, call 0. */
void *h = NULL;
int calls[] = {1}, cores[] = {2}, variant[] = {0};
bool inverse[] = {true};
CHECK(sTiles_create(&h, 1, calls, cores, variant, inverse));
/* 2. Analysis: hand over the pattern, then compute the ordering and tile
* layout. sTiles keeps the rows/cols arrays: free them only at the end. */
CHECK(sTiles_assign_graph_one_call(0, 0, &h, n, Q.nnz, Q.rows, Q.cols));
CHECK(sTiles_init_group(0, &h));
/* 3. Numeric phase: values in the same order as rows/cols, then the
* Cholesky factorization and the selected inverse. Work runs between
* bind and unbind, which start and park the thread team. */
CHECK(sTiles_assign_values(0, 0, &h, Q.vals));
sTiles_bind(0, 0, &h);
CHECK(sTiles_chol(0, 0, &h));
CHECK(sTiles_selinv(0, 0, &h));
sTiles_unbind(0, 0, &h);
/* 4. Results. */
printf("log|Q| = %.6f\n", sTiles_get_logdet(0, 0, &h));
double *b = malloc(n * sizeof *b), *x = malloc(n * sizeof *x);
for (int i = 0; i < n; i++) b[i] = x[i] = 1.0;
sTiles_bind(0, 0, &h);
CHECK(sTiles_solve_LLT(0, 0, &h, x, 1)); /* x = Q^-1 b, in place */
sTiles_unbind(0, 0, &h);
printf("max |Q x - b| = %.1e\n", max_residual(&Q, x, b));
double *v = malloc(n * sizeof *v); /* diag(Q^-1) */
sTiles_get_selinv_diag(0, 0, &h, n, v);
printf("first variances = %.6f %.6f %.6f\n", v[0], v[1], v[2]);
/* 5. Release the solver, then your arrays. */
sTiles_quit();
free(b); free(x); free(v);
free_coo(&Q);
return 0;
}
Output:
log|Q| = 1317.032401 max |Q x - b| = 3.9e-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.
"""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
# Solve Q x = b for one right-hand side, then for several at once.
#
# Rscript 02_solve.R
library(sTiles)
library(Matrix)
n <- 1000
Q <- bandSparse(n, k = c(0, 1), diagonals = list(rep(4, n), rep(-1, n - 1)),
symmetric = TRUE)
s <- sTiles(Q, cores = 2)
# One right-hand side: a vector of length n.
b <- as.numeric(1:n)
x <- sTiles_solve(s, b)
cat(sprintf("one rhs: length(x) = %d, max |Q x - b| = %.1e\n",
length(x), max(abs(Q %*% x - b))))
# 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.
set.seed(0)
B <- matrix(rnorm(n * 5), n, 5)
X <- sTiles_solve(s, B)
cat(sprintf("five rhs: dim(X) = %d x %d, max |Q X - B| = %.1e\n",
nrow(X), ncol(X), max(abs(Q %*% X - B))))
sTiles_close(s)
Output:
one rhs: length(x) = 1000, max |Q x - b| = 5.7e-13 five rhs: dim(X) = 1000 x 5, max |Q X - B| = 1.3e-15
# Solve Q x = b for one right-hand side, then for several at once.
#
# julia 02_solve.jl
using sTiles, LinearAlgebra, SparseArrays, Printf, Random
n = 1000
Q = spdiagm(-1 => fill(-1.0, n - 1), 0 => fill(4.0, n), 1 => fill(-1.0, n - 1))
F = sTiles.cholesky(Q; cores = 2)
# One right-hand side: a vector of length n.
b = collect(1.0:n)
x = F \ b
@printf("one rhs: length(x) = %d, max |Q x - b| = %.1e\n",
length(x), maximum(abs.(Q * x - b)))
# 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 = randn(MersenneTwister(0), n, 5)
X = F \ B
@printf("five rhs: size(X) = %s, max |Q X - B| = %.1e\n",
size(X), maximum(abs.(Q * X - B)))
close(F)
Output:
one rhs: length(x) = 1000, max |Q x - b| = 5.7e-13 five rhs: size(X) = (1000, 5), max |Q X - B| = 1.1e-15
/* Solve Q x = b for one right-hand side, then for several at once.
*
* make 02_solve && ./02_solve
*/
#include "stiles.h"
#include "common.h"
int main(void)
{
lower_coo Q = tridiagonal(1000, 4.0, -1.0);
int n = Q.n;
/* Handle, analysis and Cholesky, as in 01_quickstart.c (no inverse). */
sTiles_set_log_level(-1);
void *h = NULL;
int calls[] = {1}, cores[] = {2}, variant[] = {0};
bool inverse[] = {false};
CHECK(sTiles_create(&h, 1, calls, cores, variant, inverse));
CHECK(sTiles_assign_graph_one_call(0, 0, &h, n, Q.nnz, Q.rows, Q.cols));
CHECK(sTiles_init_group(0, &h));
CHECK(sTiles_assign_values(0, 0, &h, Q.vals));
sTiles_bind(0, 0, &h);
CHECK(sTiles_chol(0, 0, &h));
/* One right-hand side. The solve overwrites its input with the solution,
* so keep a copy of b if you still need it. */
double *b = malloc(n * sizeof *b), *x = malloc(n * sizeof *x);
for (int i = 0; i < n; i++) b[i] = x[i] = i + 1.0;
CHECK(sTiles_solve_LLT(0, 0, &h, x, 1));
printf("one rhs: max |Q x - b| = %.1e\n", max_residual(&Q, x, b));
/* Several right-hand sides: an n x k array stored column by column
* (column j starts at B + j*n), all solved in one call. */
int k = 5;
double *B = malloc((size_t)n * k * sizeof *B), *X = malloc((size_t)n * k * sizeof *X);
for (int i = 0; i < n * k; i++) B[i] = X[i] = (double)rand() / RAND_MAX - 0.5;
CHECK(sTiles_solve_LLT(0, 0, &h, X, k));
double worst = 0.0;
for (int j = 0; j < k; j++) {
double r = max_residual(&Q, X + (size_t)j * n, B + (size_t)j * n);
if (r > worst) worst = r;
}
printf("five rhs: max |Q X - B| = %.1e\n", worst);
sTiles_unbind(0, 0, &h);
sTiles_quit();
free(b); free(x); free(B); free(X);
free_coo(&Q);
return 0;
}
Output:
one rhs: max |Q x - b| = 4.5e-13 five rhs: max |Q X - B| = 3.1e-16
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 ]
examples/r/03_selected_inverse.R
# Read entries of solve(Q) without forming the dense inverse: the diagonal,
# single entries, a row, and the whole inverse on the pattern of Q.
# Checked here against the dense inverse.
#
# Rscript 03_selected_inverse.R
library(sTiles)
library(Matrix)
n <- 200
Q <- bandSparse(n, k = c(0, 1), diagonals = list(rep(4, n), rep(-1, n - 1)),
symmetric = TRUE)
Qinv <- solve(as.matrix(Q)) # only to check the answers
s <- sTiles(Q, cores = 2, inverse = TRUE)
sTiles_selinv(s) # optional: otherwise runs on first query
d <- sTiles_selinv_diag(s) # all n variances
cat(sprintf("diagonal: max error = %.1e\n", max(abs(d - diag(Qinv)))))
# One entry. Indices are 1-based, in the original ordering of Q.
cat(sprintf("Qinv[11, 12] = %.6f (dense: %.6f)\n",
sTiles_selinv_elm(s, 11, 12), Qinv[11, 12]))
# 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.
cat(sprintf("Qinv[11, 151] = %.1f (dense: %.1e, outside the pattern)\n",
sTiles_selinv_elm(s, 11, 151), Qinv[11, 151]))
# A row restricted to chosen columns, e.g. the neighbours of node 11.
cat("row 11 at c(10, 11, 12) =", round(sTiles_selinv_row(s, 11, c(10, 11, 12)), 6), "\n")
# The inverse at every non-zero of Q, as a sparse matrix.
Z <- sTiles_selinv_matrix(s)
print(Z[1:3, 1:3])
sTiles_close(s)
Output:
diagonal: max error = 1.7e-16
Qinv[11, 12] = 0.077350 (dense: 0.077350)
Qinv[11, 151] = 0.0 (dense: 2.4e-81, outside the pattern)
row 11 at c(10, 11, 12) = 0.07735 0.288675 0.07735
3 x 3 sparse Matrix of class "dsCMatrix"
[1,] 0.26794919 0.07179677 .
[2,] 0.07179677 0.28718708 0.07695155
[3,] . 0.07695155 0.28856830
examples/julia/03_selected_inverse.jl
# Read entries of Q^-1 without forming the dense inverse: the diagonal,
# single entries, and a row. Checked here against the dense inverse.
#
# julia 03_selected_inverse.jl
using sTiles, LinearAlgebra, SparseArrays, Printf
n = 200
Q = spdiagm(-1 => fill(-1.0, n - 1), 0 => fill(4.0, n), 1 => fill(-1.0, n - 1))
Qinv = inv(Matrix(Q)) # only to check the answers
F = sTiles.cholesky(Q; cores = 2, inverse = true)
selinv!(F) # optional: otherwise runs on first query
d = selinv_diag(F) # all n variances
@printf("diagonal: max error = %.1e\n", maximum(abs.(d - diag(Qinv))))
# One entry. Indices are 1-based, in the original ordering of Q.
@printf("Qinv[11, 12] = %.6f (dense: %.6f)\n", selinv_elm(F, 11, 12), Qinv[11, 12])
# 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.
@printf("Qinv[11, 151] = %.1f (dense: %.1e, outside the pattern)\n",
selinv_elm(F, 11, 151), Qinv[11, 151])
# A row restricted to chosen columns, e.g. the neighbours of node 11.
println("row 11 at [10, 11, 12] = ", round.(selinv_row(F, 11, [10, 11, 12]); digits = 6))
close(F)
Output:
diagonal: max error = 1.7e-16 Qinv[11, 12] = 0.077350 (dense: 0.077350) Qinv[11, 151] = 0.0 (dense: 2.4e-81, outside the pattern) row 11 at [10, 11, 12] = [0.07735, 0.288675, 0.07735]
examples/c/03_selected_inverse.c
/* Read entries of Q^-1 without forming the dense inverse: the diagonal and
* single entries.
*
* make 03_selected_inverse && ./03_selected_inverse
*/
#include "stiles.h"
#include "common.h"
int main(void)
{
lower_coo Q = tridiagonal(200, 4.0, -1.0);
int n = Q.n;
/* The selected inverse needs inverse = true at creation. */
sTiles_set_log_level(-1);
void *h = NULL;
int calls[] = {1}, cores[] = {2}, variant[] = {0};
bool inverse[] = {true};
CHECK(sTiles_create(&h, 1, calls, cores, variant, inverse));
CHECK(sTiles_assign_graph_one_call(0, 0, &h, n, Q.nnz, Q.rows, Q.cols));
CHECK(sTiles_init_group(0, &h));
CHECK(sTiles_assign_values(0, 0, &h, Q.vals));
sTiles_bind(0, 0, &h);
CHECK(sTiles_chol(0, 0, &h));
CHECK(sTiles_selinv(0, 0, &h)); /* after the Cholesky */
sTiles_unbind(0, 0, &h);
/* All n variances in one call. */
double *d = malloc(n * sizeof *d);
sTiles_get_selinv_diag(0, 0, &h, n, d);
printf("diag(Qinv)[0..2] = %.6f %.6f %.6f\n", d[0], d[1], d[2]);
/* One entry. Indices are 0-based, in the original ordering of Q. */
printf("Qinv[10, 11] = %.6f\n", sTiles_get_selinv_elm(0, 0, 10, 11, &h));
/* 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. */
printf("Qinv[10, 150] = %.1f (outside the pattern)\n",
sTiles_get_selinv_elm(0, 0, 10, 150, &h));
sTiles_quit();
free(d);
free_coo(&Q);
return 0;
}
Output:
diag(Qinv)[0..2] = 0.267949 0.287187 0.288568 Qinv[10, 11] = 0.077350 Qinv[10, 150] = 0.0 (outside the pattern)
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
examples/r/04_reuse_analysis.R
# Analyze the sparsity pattern once, then factorize many matrices that
# share it. This is the loop of a hyperparameter search or an optimizer.
#
# Rscript 04_reuse_analysis.R
library(sTiles)
library(Matrix)
n <- 100000
T <- bandSparse(n, k = c(0, 1), diagonals = list(rep(2, n), rep(-1, n - 1)),
symmetric = TRUE)
I <- Diagonal(n)
build_Q <- function(kappa) 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), cores = 2)
cat(sprintf("analysis: %.3f s (paid once)\n", sTiles_summary(s)$analyze_time))
# Step 2, per value set: numeric Cholesky only.
for (kappa in c(0.1, 1, 10)) {
sTiles_update(s, build_Q(kappa))
cat(sprintf("kappa = %5.1f log|Q| = %12.4f cholesky: %.4f s\n",
kappa, sTiles_logdet(s), sTiles_summary(s)$chol_time))
}
sTiles_close(s)
Output:
analysis: 0.448 s (paid once) kappa = 0.1 log|Q| = 31493.2364 cholesky: 0.0079 s kappa = 1.0 log|Q| = 96242.5227 cholesky: 0.0042 s kappa = 10.0 log|Q| = 247788.8801 cholesky: 0.0072 s
examples/julia/04_reuse_analysis.jl
# Analyze the sparsity pattern once, then factorize many matrices that
# share it. This is the loop of a hyperparameter search or an optimizer.
#
# julia 04_reuse_analysis.jl
using sTiles, LinearAlgebra, SparseArrays, Printf
n = 100_000
T = spdiagm(-1 => fill(-1.0, n - 1), 0 => fill(2.0, n), 1 => fill(-1.0, n - 1))
build_Q(kappa) = 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.
F = sTiles.analyze(build_Q(1.0); cores = 2)
@printf("analysis: %.3f s (paid once)\n", sTiles.analyze_time(F))
# Step 2, per value set: numeric Cholesky only.
for kappa in (0.1, 1.0, 10.0)
sTiles.update!(F, build_Q(kappa))
@printf("kappa = %5.1f log|Q| = %12.4f cholesky: %.4f s\n",
kappa, logdet(F), sTiles.chol_time(F))
end
close(F)
Output:
analysis: 0.422 s (paid once) kappa = 0.1 log|Q| = 31493.2364 cholesky: 0.0088 s kappa = 1.0 log|Q| = 96242.5227 cholesky: 0.0040 s kappa = 10.0 log|Q| = 247788.8801 cholesky: 0.0034 s
examples/c/04_reuse_analysis.c
/* Analyze the sparsity pattern once, then factorize many matrices that
* share it. This is the loop of a hyperparameter search or an optimizer.
*
* make 04_reuse_analysis && ./04_reuse_analysis
*/
#include "stiles.h"
#include "common.h"
int main(void)
{
/* T: tridiagonal with 2 on the diagonal and -1 next to it. The matrices
* below are Q(kappa) = T + kappa I: same non-zeros, different values. */
lower_coo T = tridiagonal(100000, 2.0, -1.0);
int n = T.n;
double *vals = malloc(T.nnz * sizeof *vals);
sTiles_set_log_level(-1);
void *h = NULL;
int calls[] = {1}, cores[] = {2}, variant[] = {0};
bool inverse[] = {false};
CHECK(sTiles_create(&h, 1, calls, cores, variant, inverse));
/* Step 1, once: ordering and tile layout. They depend only on WHERE the
* non-zeros are, not on their values. */
double t0 = now();
CHECK(sTiles_assign_graph_one_call(0, 0, &h, n, T.nnz, T.rows, T.cols));
CHECK(sTiles_init_group(0, &h));
printf("analysis: %.3f s (paid once)\n", now() - t0);
/* Step 2, per value set: new values in the same order, numeric Cholesky. */
double kappas[] = {0.1, 1.0, 10.0};
for (int r = 0; r < 3; r++) {
for (int k = 0; k < T.nnz; k++)
vals[k] = T.vals[k] + (T.rows[k] == T.cols[k] ? kappas[r] : 0.0);
CHECK(sTiles_assign_values(0, 0, &h, vals));
sTiles_bind(0, 0, &h);
CHECK(sTiles_chol(0, 0, &h));
sTiles_unbind(0, 0, &h);
printf("kappa = %5.1f log|Q| = %12.4f cholesky: %.4f s\n", kappas[r],
sTiles_get_logdet(0, 0, &h), sTiles_get_chol_timing(0, 0, &h));
}
sTiles_quit();
free(vals);
free_coo(&T);
return 0;
}
Output:
analysis: 0.530 s (paid once) kappa = 0.1 log|Q| = 31493.2364 cholesky: 0.0075 s kappa = 1.0 log|Q| = 96242.5227 cholesky: 0.0065 s kappa = 10.0 log|Q| = 247788.8801 cholesky: 0.0054 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
# Draw samples from N(0, solve(Q)), the Gaussian with precision matrix Q.
#
# If Q = C t(C), then x = solve(t(C), z) with z ~ N(0, I) has covariance
# solve(Q). sTiles_solve(s, z, "Lt") computes exactly that, in the original
# ordering of Q.
#
# Rscript 05_sampling.R
library(sTiles)
library(Matrix)
n <- 1000
Q <- bandSparse(n, k = c(0, 1), diagonals = list(rep(4, n), rep(-1, n - 1)),
symmetric = TRUE)
set.seed(1)
s <- sTiles(Q, cores = 2, inverse = TRUE)
Z <- matrix(rnorm(n * 10000), n, 10000) # 10 000 draws, one per column
X <- sTiles_solve(s, Z, system = "Lt") # each column ~ N(0, solve(Q))
# Check: the sample variances match the exact ones from the selected inverse.
exact <- sTiles_selinv_diag(s)
cat(sprintf("exact variance of x[1] = %.4f\n", exact[1]))
cat(sprintf("sample variance of x[1] = %.4f\n", var(X[1, ])))
# With a mean mu, a draw from N(mu, solve(Q)) is mu + X[, k].
sTiles_close(s)
Output:
exact variance of x[1] = 0.2679 sample variance of x[1] = 0.2725
# Draw samples from N(0, Q^-1), the Gaussian with precision matrix Q.
#
# If Q = C C', then x = C' \ z with z ~ N(0, I) has covariance Q^-1.
# solve(F, z; system = :Lt) computes exactly that, in the original ordering
# of Q.
#
# julia 05_sampling.jl
using sTiles, LinearAlgebra, SparseArrays, Printf, Random, Statistics
n = 1000
Q = spdiagm(-1 => fill(-1.0, n - 1), 0 => fill(4.0, n), 1 => fill(-1.0, n - 1))
F = sTiles.cholesky(Q; cores = 2, inverse = true)
Z = randn(MersenneTwister(1), n, 10_000) # 10 000 draws, one per column
X = solve(F, Z; system = :Lt) # each column ~ N(0, Q^-1)
# Check: the sample variances match the exact ones from the selected inverse.
exact = selinv_diag(F)
@printf("exact variance of x[1] = %.4f\n", exact[1])
@printf("sample variance of x[1] = %.4f\n", var(X[1, :]))
# With a mean mu, a draw from N(mu, Q^-1) is mu + X[:, k].
close(F)
Output:
exact variance of x[1] = 0.2679 sample variance of x[1] = 0.2709
/* 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.
* sTiles_solve_LT computes exactly that, in the original ordering of Q.
*
* make 05_sampling && ./05_sampling
*/
#include "stiles.h"
#include "common.h"
/* A standard normal draw (Box-Muller). Use your own generator in practice. */
static double randn(void)
{
double u1 = (rand() + 1.0) / (RAND_MAX + 2.0), u2 = rand() / (RAND_MAX + 1.0);
return sqrt(-2.0 * log(u1)) * cos(2.0 * 3.141592653589793 * u2);
}
int main(void)
{
lower_coo Q = tridiagonal(1000, 4.0, -1.0);
int n = Q.n, draws = 10000;
sTiles_set_log_level(-1);
void *h = NULL;
int calls[] = {1}, cores[] = {2}, variant[] = {0};
bool inverse[] = {true};
CHECK(sTiles_create(&h, 1, calls, cores, variant, inverse));
CHECK(sTiles_assign_graph_one_call(0, 0, &h, n, Q.nnz, Q.rows, Q.cols));
CHECK(sTiles_init_group(0, &h));
CHECK(sTiles_assign_values(0, 0, &h, Q.vals));
sTiles_bind(0, 0, &h);
CHECK(sTiles_chol(0, 0, &h));
CHECK(sTiles_selinv(0, 0, &h));
/* n x draws standard normals, column by column; one call turns every
* column into a draw from N(0, Q^-1), in place. */
srand(1);
double *X = malloc((size_t)n * draws * sizeof *X);
for (size_t i = 0; i < (size_t)n * draws; i++) X[i] = randn();
CHECK(sTiles_solve_LT(0, 0, &h, X, draws));
sTiles_unbind(0, 0, &h);
/* Check: the sample variance of x[0] matches the exact one. */
double sum = 0.0, sum2 = 0.0;
for (int k = 0; k < draws; k++) {
double x0 = X[(size_t)k * n];
sum += x0; sum2 += x0 * x0;
}
double mean = sum / draws;
printf("exact variance of x[0] = %.4f\n", sTiles_get_selinv_elm(0, 0, 0, 0, &h));
printf("sample variance of x[0] = %.4f\n", (sum2 - draws * mean * mean) / (draws - 1));
sTiles_quit();
free(X);
free_coo(&Q);
return 0;
}
Output:
exact variance of x[0] = 0.2679 sample variance of x[0] = 0.2762
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
# Factorize your own matrix, read from a Matrix Market (.mtx) file.
#
# Rscript 06_matrix_market.R # uses ../data/grid40.mtx
# Rscript 06_matrix_market.R my_matrix.mtx
library(sTiles)
library(Matrix)
args <- commandArgs(trailingOnly = TRUE)
path <- if (length(args) > 0) args[1] else "../data/grid40.mtx"
# readMM keeps a "symmetric" file symmetric; sTiles reads only the lower
# triangle, so a full matrix works as well.
Q <- readMM(path)
cat(sprintf("%s: %d x %d, %d stored non-zeros\n",
basename(path), nrow(Q), ncol(Q), length(Q@x)))
s <- sTiles(Q, cores = 2)
cat(sprintf("log|Q| = %.6f\n", sTiles_logdet(s)))
info <- sTiles_summary(s) # print(info) shows the full report
cat(sprintf("non-zeros in L = %.0f, analysis %.3f s, cholesky %.4f s\n",
info$nnz_factor, info$analyze_time, info$chol_time))
sTiles_close(s)
Output:
grid40.mtx: 1600 x 1600, 4720 stored non-zeros log|Q| = 1965.308933 non-zeros in L = 20771, analysis 0.034 s, cholesky 0.0009 s
examples/julia/06_matrix_market.jl
# Factorize your own matrix, read from a Matrix Market (.mtx) file.
#
# julia 06_matrix_market.jl # uses ../data/grid40.mtx
# julia 06_matrix_market.jl my_matrix.mtx
using sTiles, LinearAlgebra, SparseArrays, Printf
# A small reader for "coordinate real" files, so the example needs no extra
# package. (MatrixMarket.jl does the same with `mmread(path)`.)
function read_mtx(path)
lines = filter(l -> !startswith(l, "%"), readlines(path))
n, m, _ = parse.(Int, split(lines[1]))
I, J, V = Int[], Int[], Float64[]
for l in lines[2:end]
f = split(l)
push!(I, parse(Int, f[1])); push!(J, parse(Int, f[2])); push!(V, parse(Float64, f[3]))
end
return sparse(I, J, V, n, m) # sTiles reads only the lower triangle
end
path = isempty(ARGS) ? joinpath(@__DIR__, "..", "data", "grid40.mtx") : ARGS[1]
Q = read_mtx(path)
@printf("%s: %d x %d, %d stored non-zeros\n", basename(path), size(Q)..., nnz(Q))
F = sTiles.cholesky(Q; cores = 2)
@printf("log|Q| = %.6f\n", logdet(F))
@printf("non-zeros in L = %d, analysis %.3f s, cholesky %.4f s\n",
nnz(F), sTiles.analyze_time(F), sTiles.chol_time(F))
close(F)
Output:
grid40.mtx: 1600 x 1600, 4720 stored non-zeros log|Q| = 1965.308933 non-zeros in L = 20771, analysis 0.032 s, cholesky 0.0010 s
/* Factorize your own matrix, read from a Matrix Market (.mtx) file.
*
* make 06_matrix_market && ./06_matrix_market # ../data/grid40.mtx
* ./06_matrix_market my_matrix.mtx
*/
#include <string.h>
#include "stiles.h"
#include "common.h"
/* Read a "coordinate real" .mtx file and keep its lower triangle, 0-based.
* A "symmetric" file stores one triangle already; a general one stores both,
* and the upper entries are dropped. */
static lower_coo read_mtx(const char *path)
{
FILE *f = fopen(path, "r");
if (!f) { perror(path); exit(1); }
char line[1024];
do {
if (!fgets(line, sizeof line, f)) { fprintf(stderr, "%s: empty\n", path); exit(1); }
} while (line[0] == '%');
int m, entries;
lower_coo A = {0};
sscanf(line, "%d %d %d", &A.n, &m, &entries);
A.rows = malloc(entries * sizeof *A.rows);
A.cols = malloc(entries * sizeof *A.cols);
A.vals = malloc(entries * sizeof *A.vals);
for (int e = 0; e < entries; e++) {
int i, j; double v;
if (fscanf(f, "%d %d %lf", &i, &j, &v) != 3) { fprintf(stderr, "%s: bad entry\n", path); exit(1); }
if (i < j) continue;
A.rows[A.nnz] = i - 1; A.cols[A.nnz] = j - 1; A.vals[A.nnz] = v; A.nnz++;
}
fclose(f);
return A;
}
int main(int argc, char **argv)
{
const char *path = argc > 1 ? argv[1] : "../data/grid40.mtx";
lower_coo Q = read_mtx(path);
printf("%s: %d x %d, %d entries in the lower triangle\n", path, Q.n, Q.n, Q.nnz);
sTiles_set_log_level(-1);
void *h = NULL;
int calls[] = {1}, cores[] = {2}, variant[] = {0};
bool inverse[] = {false};
CHECK(sTiles_create(&h, 1, calls, cores, variant, inverse));
double t0 = now();
CHECK(sTiles_assign_graph_one_call(0, 0, &h, Q.n, Q.nnz, Q.rows, Q.cols));
CHECK(sTiles_init_group(0, &h));
double analysis = now() - t0;
CHECK(sTiles_assign_values(0, 0, &h, Q.vals));
sTiles_bind(0, 0, &h);
CHECK(sTiles_chol(0, 0, &h));
sTiles_unbind(0, 0, &h);
printf("log|Q| = %.6f\n", sTiles_get_logdet(0, 0, &h));
printf("non-zeros in L = %lld, analysis %.3f s, cholesky %.4f s\n",
sTiles_get_nnz_factor(0, 0, &h), analysis, sTiles_get_chol_timing(0, 0, &h));
sTiles_quit();
free_coo(&Q);
return 0;
}
Output:
../data/grid40.mtx: 1600 x 1600, 4720 entries in the lower triangle log|Q| = 1965.308933 non-zeros in L = 20771, analysis 0.040 s, cholesky 0.0012 s