Sparse Operators¶
SparseOperator is a sparse matrix whose sparsity pattern is a static,
host-side, hashable SparsityPattern; only the non-zero values are traced.
Every matrix a GMRF / INLA workflow factorises — a prior precision, a graph
Laplacian, the Laplace Hessian \(Q + A^\top W A\) — has a pattern known before
any value is, so all symbolic work (canonical ordering, transposition, pattern
unions, the pattern of a congruence) runs once per pattern on the host and is
reused across jit calls, Newton steps, hyperparameter values and vmap-ped
datasets. Changing the values never retraces; changing the pattern does.
The pattern of the Laplace Hessian is known in advance:
A FEM projector row touches the vertices of one triangle, which are already neighbours in \(Q\), so the pattern does not grow; each fixed effect adds one dense row and column.
Storage. Patterns are canonical: sorted row-major, duplicates merged, and
the diagonal of a square matrix always present. symmetric=True stores the
lower triangle only; from_coo(..., symmetric=True) takes each off-diagonal
pair once (edge-once graph storage) and mirrors it.
Dispatch.
| Primitive | Behaviour |
|---|---|
diag |
Exact, read from the pattern |
solve |
SparseCholeskySolver when the caller passes it (strategies, dispatch_solve); an explicit lineax solver wins; otherwise CG when PSD-tagged and larger than AutoSolver.size_threshold, dense below |
logdet |
SparseCholeskySolver when passed; otherwise SLQLogdet when PSD-tagged and large, dense below |
diag_inv |
Takahashi through the sparse factor with solver=SparseCholeskySolver(...) (any size) or method="cholesky"; "auto" uses it for N ≤ 2048 and Hutchinson above |
eig(rank=) |
Lanczos on the matvec |
cholesky |
A SparseCholeskyFactor (RCM ordering, cached symbolic analysis) |
There is no size heuristic for the exact path: the caller knows N and
chooses SparseCholeskySolver; AutoSolver keeps CG for large PSD
operators.
JacobiPreconditioner works through the exact diagonal, which is usually
enough for a graph Laplacian plus a diagonal shift.
Example. An ICAR structure matrix from an edge list, then the Laplace Hessian rebuilt on its precomputed pattern at each Newton step:
import equinox as eqx
import jax.numpy as jnp
import lineax as lx
import numpy as np
import gaussx as gx
# Path graph 0 - 1 - 2 - 3, each edge once, host-side indices
N = 4
senders, receivers = np.array([1, 2, 3]), np.array([0, 1, 2])
w = np.ones(3)
deg = np.bincount(senders, w, N) + np.bincount(receivers, w, N)
R = gx.SparseOperator.from_coo(
np.r_[np.arange(N), senders],
np.r_[np.arange(N), receivers],
jnp.asarray(np.r_[deg, -w]),
(N, N),
symmetric=True,
tags=frozenset({lx.positive_semidefinite_tag}),
)
tau = 2.0
Q = eqx.tree_at(lambda op: op.values, R, tau * R.values) # same static pattern
# Observation projector A (2 observations) and Newton weights w_t
A = gx.SparseOperator.from_coo(
np.array([0, 0, 1]), np.array([0, 1, 3]), jnp.array([0.5, 0.5, 1.0]), (2, N)
)
w_t = jnp.array([1.0, 2.0])
H = Q.union(Q.congruence(A, w_t), tags=lx.positive_semidefinite_tag) # Q + Aᵀ diag(w_t) A
x = gx.solve(H, jnp.ones(N))
Sparse Cholesky¶
Cholesky is Gaussian elimination: eliminating node \(j\) connects its not-yet-eliminated neighbours, so the column patterns of \(P Q P^\top = L L^\top\) follow the elimination tree,
That depends only on the pattern and the ordering, so symbolic_cholesky
runs once on the host (NumPy / SciPy) and is cached per SparsityPattern.
sparse_cholesky then traces only the values: it jits, vmaps over
values and is differentiable.
- Ordering.
"rcm"(reverse Cuthill–McKee, the default) minimises the bandwidth;"natural"keeps the given order;"amd"(approximate minimum degree, through CHOLMOD) minimises fill. - Numeric phase. After RCM on a mesh the factor fills a narrow band, so
\(L\) is block tridiagonal in bandwidth-sized blocks and dense block kernels
do the work. Otherwise a left-looking
lax.scanover columns gathers fixed-size windows from the CSC arrays (columns bucketed by length, so a few long separator columns do not pad all the short ones). Either waySparseCholeskyFactor.valuesholds \(L\) on its exact CSC pattern. - Takahashi. The backward recursion
\(Z_{ij} = \delta_{ij}/L_{jj}^2 - L_{jj}^{-1}\sum_{k>j,\,k\in\operatorname{struct}(L_{:,j})} L_{kj} Z_{ki}\)
evaluates \(Z = Q^{-1}\) exactly on \(\operatorname{pattern}(L + L^\top)\),
which contains \(\operatorname{pattern}(Q)\), at about the cost of the
factorisation.
selected_inverse()returns it as aSparseOperatorin the original order;diag_inv()gives the marginal variances. - Gradients. \(d\log|Q| = \operatorname{tr}(Q^{-1}dQ)\), so the
log-determinant's cotangent is \(Z\) on \(\operatorname{pattern}(Q)\): one
Takahashi sweep, never \(Q^{-1}\). For \(x = Q^{-1}b\):
\(\bar b = Q^{-1}\bar x\) and \(\bar Q = -\bar b\,x^\top\), symmetrised. With
symmetric=Truestorage an off-diagonal stored value sets \(Q_{ij}\) and \(Q_{ji}\), so its gradient is doubled (\(2Z_{ij}\)); general storage is factored as \(\tfrac12(Q + Q^\top)\) and each stored value gets \(Z_{ij}\).solve_lower_transpose(sampling, \(x = P^\top L^{-\top} z\)) anddiag_invare differentiated by JAX through the factorisation. - CHOLMOD backend (opt-in,
pip install scikit-sparse, which needs SuiteSparse; not a dependency of gaussx).backend="cholmod"runs only the numeric factorisation in CHOLMOD throughjax.pure_callback, on the same symbolic pattern; the solves, Takahashi and the gradients are the same JAX code, so both backends give identical gradients. CPU only, andvmapcalls CHOLMOD once per batch element.
Scale. Measured on triangulated square meshes (the P1 FEM 7-point
stencil), CPU, float64, jit-compiled, after compilation:
| Nodes | Ordering / backend | nnz(L) | Fill vs tril(Q) | logdet |
value_and_grad(logdet) |
diag_inv |
|---|---|---|---|---|---|---|
| 10,000 | RCM / JAX (banded) | 681,550 | 17.2 | 1.0 s | 1.1 s | 0.9 s |
| 40,000 | RCM / JAX (banded) | 5,393,100 | 33.9 | 1.1 s | 1.6 s | 1.5 s |
| 99,856 | RCM / JAX (banded) | 21,185,746 | 53.2 | 3.3 s | 5.7 s | 11 s |
| 10,000 | AMD / JAX (windows) | 295,884 | 7.5 | 1.7 s | 3.4 s | 3.2 s |
| 10,000 | AMD / CHOLMOD | 295,884 | 7.5 | 0.07 s | 1.7 s | 1.6 s |
| 40,000 | AMD / CHOLMOD | 1,569,916 | 9.9 | 0.5 s | 15 s | 17 s |
| 99,856 | AMD / CHOLMOD | 4,748,667 | 11.9 | 1.8 s | ~2 min | ~2 min |
Timings are from a shared 16-core machine and are indicative only. The symbolic analysis is a one-off host cost (about 0.3 s at 10⁴ nodes and 8 s at 10⁵ with RCM).
- 2-D meshes up to about \(10^5\) nodes: RCM with the JAX backend.
- Beyond that, or when the fill of RCM is prohibitive: AMD through
CHOLMOD (much less fill; its
logdetis fast, but gradients and marginal variances run the JAX Takahashi on the AMD pattern, which gathers windows and is the slower path). - Beyond that: the iterative backend (CG, SLQ, Hutchinson).
Supernodes and level scheduling (GPU parallelism over independent subtrees) are follow-ups.
Example. A Matérn-like SPDE precision \(Q(\kappa) = \kappa^2 I + G\) on a 40k-node mesh: analyse once, factor for many \(\kappa\), differentiate the log-determinant.
import jax
import jax.numpy as jnp
import numpy as np
import gaussx as gx
# Stiffness-like graph Laplacian G of a triangulated 200 x 200 square
side = 200
n = side * side
i = np.arange(n)
right = i[i % side != side - 1] # nodes with a right neighbour
down = i[i < n - side] # nodes with a neighbour below
diagonal = right[right < n - side] # one diagonal per cell
senders = np.r_[right + 1, down + side, diagonal + side + 1]
receivers = np.r_[right, down, diagonal]
w = np.ones(senders.size)
deg = np.bincount(senders, w, n) + np.bincount(receivers, w, n)
G = gx.SparseOperator.from_coo(
np.r_[np.arange(n), senders],
np.r_[np.arange(n), receivers],
jnp.asarray(np.r_[deg, -w]),
(n, n),
symmetric=True,
)
sym = gx.symbolic_cholesky(G.pattern) # host, once: RCM, banded layout
def logdet(log_kappa):
Q = G.add_diagonal(jnp.full(n, jnp.exp(2 * log_kappa))) # same pattern
return gx.sparse_cholesky(Q, sym).logdet()
jax.vmap(logdet)(jnp.linspace(-1.0, 1.0, 16)) # 16 factorisations, one analysis
jax.grad(logdet)(0.0) # d log|Q| / d log κ, through one Takahashi sweep
Structured linear algebra and Gaussian primitives for JAX.
SparseOperator
¶
Bases: AbstractLinearOperator
Sparse matrix with a static SparsityPattern and traced values.
Only values is a pytree leaf, so jit, grad and vmap act on
the non-zeros while the pattern stays a compile-time constant. Changing
the values (eqx.tree_at(lambda op: op.values, Q, new_values)) never
retraces; changing the pattern does.
The primitives dispatch on it: gaussx.diag reads the diagonal from the
pattern; gaussx.solve uses CG for large positive semidefinite operators
(AutoSolver rules) and a dense solve otherwise; gaussx.logdet uses
SLQLogdet for large PSD operators; gaussx.eig with rank= runs
Lanczos on the matvec; gaussx.cholesky returns a sparse
SparseCholeskyFactor. For exact solves, log-determinants and marginal
variances through that factor, pass SparseCholeskySolver.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Float[ArrayLike, ' nnz']
|
Stored non-zeros in the pattern's canonical order, shape
|
required |
pattern
|
SparsityPattern
|
The static sparsity pattern. |
required |
tags
|
object | frozenset[object]
|
Lineax tags. |
frozenset()
|
Example
import numpy as np
# ICAR structure matrix of the path graph 0 - 1 - 2 (edges once)
senders, receivers = np.array([1, 2]), np.array([0, 1])
deg = np.bincount(np.r_[senders, receivers], minlength=3)
R = gaussx.SparseOperator.from_coo(
np.r_[np.arange(3), senders],
np.r_[np.arange(3), receivers],
jnp.asarray(np.r_[deg, -np.ones(2)]),
(3, 3),
symmetric=True,
)
R.mv(jnp.ones(3)) # [0, 0, 0]: constants are in the null space
Source code in src/gaussx/_operators/_sparse.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 | |
from_coo(rows: ArrayLike, cols: ArrayLike, values: Float[ArrayLike, ' k'], shape: tuple[int, int], *, symmetric: bool = False, tags: object | frozenset[object] = frozenset()) -> SparseOperator
classmethod
¶
Build from coordinate (COO) triplets.
rows and cols must be concrete (host) integer arrays; only
values may be traced. Duplicate coordinates are summed, and the
diagonal of a square matrix is added with zeros where missing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
ArrayLike
|
Row indices, shape |
required |
cols
|
ArrayLike
|
Column indices, shape |
required |
values
|
Float[ArrayLike, ' k']
|
Entry values, shape |
required |
shape
|
tuple[int, int]
|
Matrix shape |
required |
symmetric
|
bool
|
The matrix is symmetric and each off-diagonal pair is
given once (either |
False
|
tags
|
object | frozenset[object]
|
Lineax tags. |
frozenset()
|
Returns:
| Type | Description |
|---|---|
SparseOperator
|
The operator, with values in the pattern's canonical order. |
Source code in src/gaussx/_operators/_sparse.py
to_bcoo() -> jsparse.BCOO
¶
The full matrix as a jax.experimental.sparse.BCOO array.
A symmetric pattern is expanded to both triangles.
Returns:
| Type | Description |
|---|---|
BCOO
|
A |
Source code in src/gaussx/_operators/_sparse.py
diagonal() -> Float[Array, ' k']
¶
The diagonal, read from the pattern (no densification).
Returns:
| Type | Description |
|---|---|
Float[Array, ' k']
|
|
Source code in src/gaussx/_operators/_sparse.py
add_diagonal(d: Float[Array, ' n'], *, tags: object | frozenset[object] | None = None) -> SparseOperator
¶
A + diag(d) on the same pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
Float[Array, ' n']
|
Diagonal to add, shape |
required |
tags
|
object | frozenset[object] | None
|
Tags of the result. By default only symmetry is kept,
since an arbitrary |
None
|
Returns:
| Type | Description |
|---|---|
SparseOperator
|
The shifted operator, with the identical pattern. |
Source code in src/gaussx/_operators/_sparse.py
union(other: SparseOperator, *, tags: object | frozenset[object] | None = None) -> SparseOperator
¶
A + B on the union of the two patterns.
The union pattern and the scatter positions are computed on the host once per pair of patterns (and cached); only the values are added in JAX. Two symmetric patterns stay symmetric; otherwise the symmetric operand is expanded to both triangles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
SparseOperator
|
Operator of the same shape. |
required |
tags
|
object | frozenset[object] | None
|
Tags of the result. Defaults to the tags both operands share
(a sum of PSD operators is PSD), minus |
None
|
Returns:
| Type | Description |
|---|---|
SparseOperator
|
The sum, on the union pattern. |
Source code in src/gaussx/_operators/_sparse.py
congruence(A: SparseOperator, w: Float[Array, ' m'], *, tags: object | frozenset[object] | None = None) -> SparseOperator
¶
Aᵀ diag(w) A on the union of self's pattern and AᵀA's.
(AᵀWA)_{ij} = Σ_k A_{ki} w_k A_{kj} is non-zero only where columns
i and j share a row of A. That pattern, unioned with this
operator's own, and the index triples (p, q, k) feeding each entry
are computed on the host once per (pattern, A.pattern); the values
are one segment_sum in JAX. Because the result already lives on
self's pattern (padded with zeros), self.union(result) is an
aligned add, and a projector whose rows only touch neighbours in
self (a FEM projector on a mesh precision) leaves the pattern
unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
A
|
SparseOperator
|
Operator of shape |
required |
w
|
Float[Array, ' m']
|
Row weights, shape |
required |
tags
|
object | frozenset[object] | None
|
Tags of the result. Defaults to symmetry only ( |
None
|
Returns:
| Type | Description |
|---|---|
SparseOperator
|
The congruence, symmetric storage iff |
Source code in src/gaussx/_operators/_sparse.py
SparsityPattern
¶
Static, hashable sparsity pattern of a (m, n) matrix.
The index arrays live on the host (NumPy) and are canonicalised on construction:
- duplicate
(row, col)pairs are merged; - entries are sorted row-major (by row, then column);
- for a square pattern the diagonal is always present, so
diag,add_diagonaland a later Cholesky never change the pattern; - with
symmetric=Trueonly the lower triangle (row >= col) is stored, and an upper-triangle pair(i, j)is stored as(j, i).
The hash is a content hash (SHA-256 of the canonical index arrays, the shape and the symmetry flag), so it is stable across processes and can key a cache of symbolic analyses. The index arrays are read-only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
ArrayLike
|
Row indices, shape |
required |
cols
|
ArrayLike
|
Column indices, shape |
required |
shape
|
tuple[int, int]
|
Matrix shape |
required |
symmetric
|
bool
|
Store the lower triangle of a symmetric matrix. Requires a
square |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the index arrays differ in length, are not rank 1, are
out of range, or |
Example
Source code in src/gaussx/_operators/_sparse.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | |
SymbolicCholesky
¶
Symbolic Cholesky factor of a symmetric sparsity pattern.
For the permuted matrix A = P Q Pᵀ (A[k, l] = Q[perm[k], perm[l]])
it holds the elimination tree and the pattern of L (A = L Lᵀ) in
compressed sparse column (CSC) form, with each column's rows sorted so the
diagonal comes first, together with the static index plans the numeric
phase, the triangular solves and the Takahashi recursion gather through.
The column patterns follow the elimination tree,
Build it with gaussx.symbolic_cholesky (cached), not directly. It is
hashable and compared by (pattern, ordering, backend, banded), so it sits in
a static field and causes no retrace for equal inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
SparsityPattern
|
Square sparsity pattern to analyse. |
required |
ordering
|
Ordering
|
Name of the ordering that produced |
required |
backend
|
Backend
|
Numeric backend, |
required |
perm
|
ndarray
|
Fill-reducing permutation, |
required |
banded
|
bool | None
|
Force the banded ( |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
pattern |
The pattern it was computed for. |
|
ordering |
The fill-reducing ordering used. |
|
backend |
The numeric backend ( |
|
n |
Matrix size. |
|
perm |
|
|
iperm |
The inverse permutation, |
|
parent |
Elimination tree, |
|
colptr |
CSC column pointers of |
|
rowidx |
CSC row indices of |
|
colidx |
Column of each entry of |
|
nnz |
Number of entries of |
|
nnz_lower |
Number of entries in the lower triangle of |
|
max_col |
Longest column of |
|
max_row |
Longest row of |
|
banded |
Whether the numeric phase and Takahashi run on dense
|
|
block_size |
The bandwidth of |
Source code in src/gaussx/_sparse/_symbolic.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
fill_ratio: float
property
¶
nnz(L) / nnz(tril(Q)): how much the factor fills in.
inverse_plan: tuple[SparsityPattern, np.ndarray]
cached
property
¶
Pattern of L + Lᵀ in the original order, and the gather into it.
Returns (pattern, index): the symmetric (lower-triangle) pattern of
Pᵀ (L + Lᵀ) P, and index such that its canonical values are
z[index] for z on L's CSC pattern.
SparseCholeskyFactor
¶
Bases: Module
Sparse Cholesky factor P Q Pᵀ = L Lᵀ on a static symbolic pattern.
Built by gaussx.sparse_cholesky (or gaussx.cholesky on a
SparseOperator). values are the entries of L on the CSC pattern
of symbolic; matrix_values are those of the factored matrix (its
lower triangle, permuted, on the same pattern), the input that
logdet and solve differentiate through their custom VJPs:
logdet: \(d\log|Q| = \operatorname{tr}(Q^{-1}dQ)\), so the cotangent is \(Q^{-1}\) onpattern(Q), which Takahashi evaluates in one sweep;solve: \(\bar b = Q^{-1}\bar x\) and \(\bar Q = -\bar b\,x^\top\), symmetrised on the pattern.
Gradients reach the operator's stored values per stored value: with
symmetric=True storage an off-diagonal value sets Q_ij and
Q_ji, so its cotangent is doubled (2 Z_ij); general storage
factors ½(Q + Qᵀ) and each stored value gets Z_ij. The other
methods are differentiated by JAX through the factorisation.
Attributes:
| Name | Type | Description |
|---|---|---|
values |
Float[Array, ' nnz_L']
|
|
matrix_values |
Float[Array, ' nnz_L']
|
Lower triangle of |
symbolic |
SymbolicCholesky
|
The static symbolic analysis. |
Examples:
import jax.numpy as jnp
import numpy as np
import gaussx
# Precision of a path graph 0 - 1 - 2 - 3 plus a unit shift
n = 4
Q = gaussx.SparseOperator.from_coo(
np.r_[np.arange(n), np.arange(1, n)],
np.r_[np.arange(n), np.arange(n - 1)],
jnp.r_[jnp.array([2.0, 3.0, 3.0, 2.0]), -jnp.ones(n - 1)],
(n, n),
symmetric=True,
)
factor = gaussx.sparse_cholesky(Q)
dense = Q.as_matrix()
assert jnp.allclose(factor.logdet(), jnp.linalg.slogdet(dense)[1])
b = jnp.ones(n)
assert jnp.allclose(factor.solve(b), jnp.linalg.solve(dense, b))
assert jnp.allclose(factor.diag_inv(), jnp.diag(jnp.linalg.inv(dense)))
Source code in src/gaussx/_sparse/_factor.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | |
solve(b: Float[Array, ' n']) -> Float[Array, ' n']
¶
Q⁻¹ b = Pᵀ L⁻ᵀ L⁻¹ P b.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
b
|
Float[Array, ' n']
|
Right-hand side, shape |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, ' n']
|
The solution, shape |
Source code in src/gaussx/_sparse/_factor.py
logdet() -> Float[Array, '']
¶
log|Q| = 2 Σ_j log L_jj.
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
The log-determinant (NaN if |
solve_lower_transpose(z: Float[Array, ' n']) -> Float[Array, ' n']
¶
x = Pᵀ L⁻ᵀ z: with z ~ N(0, I), x ~ N(0, Q⁻¹).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Float[Array, ' n']
|
Shape |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, ' n']
|
|
Source code in src/gaussx/_sparse/_factor.py
selected_inverse() -> SparseOperator
¶
Q⁻¹ on the pattern of L + Lᵀ, in the original order.
The pattern contains pattern(Q). Like the block selected inverse,
the result holds entries of Q⁻¹; it is not an operator equal to
Q⁻¹ (whose other entries are not zero).
Returns:
| Type | Description |
|---|---|
SparseOperator
|
A symmetric |
Source code in src/gaussx/_sparse/_factor.py
diag_inv() -> Float[Array, ' n']
¶
diag(Q⁻¹), the marginal variances, by one Takahashi sweep.
Returns:
| Type | Description |
|---|---|
Float[Array, ' n']
|
Shape |
Source code in src/gaussx/_sparse/_factor.py
symbolic_cholesky(pattern: SparsityPattern, *, ordering: Ordering = 'rcm', backend: Backend = 'jax') -> SymbolicCholesky
¶
Symbolic analysis of a sparse Cholesky factorisation (host, cached).
Computes a fill-reducing permutation, the elimination tree and the
pattern of the factor L of P Q Pᵀ = L Lᵀ, plus the static,
padded index plans that gaussx.sparse_cholesky and the Takahashi
selected inverse gather through. It depends only on the pattern, so it
runs once on the host and is cached per (pattern, ordering, backend)
(the pattern's content hash): later calls, under jit or not, are a
dictionary lookup.
A symmetric pattern stores the lower triangle; a general pattern is
symmetrised structurally, and its factor is that of the symmetric part
½(Q + Qᵀ).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
SparsityPattern
|
Square sparsity pattern of the matrix to factor. |
required |
ordering
|
Ordering
|
|
'rcm'
|
backend
|
Backend
|
|
'jax'
|
Returns:
| Type | Description |
|---|---|
SymbolicCholesky
|
The cached |
Raises:
| Type | Description |
|---|---|
ValueError
|
For a non-square pattern or an unknown option. |
ImportError
|
For |
Examples:
import numpy as np
import gaussx
# Path graph 0 - 1 - 2 - 3 - 4 (lower triangle, edges once)
p = gaussx.SparsityPattern(
np.arange(1, 5), np.arange(4), (5, 5), symmetric=True
)
sym = gaussx.symbolic_cholesky(p)
assert sym.nnz == 9 # a tridiagonal matrix does not fill in
assert gaussx.symbolic_cholesky(p) is sym # cached per pattern
Source code in src/gaussx/_sparse/_symbolic.py
sparse_cholesky(op: SparseOperator, symbolic: SymbolicCholesky | None = None) -> SparseCholeskyFactor
¶
Sparse Cholesky factorisation of a symmetric positive-definite operator.
The symbolic analysis (ordering, elimination tree, pattern of L) is
host-side and cached per pattern; pass one from gaussx.symbolic_cholesky
to choose the ordering or backend, or to reuse it explicitly. The numeric
phase is traced: it jits, vmaps over op.values and is
differentiable. With the JAX backend it is a left-looking lax.scan
over columns, sequential in n and O(Σ_j |struct(L_{:,j})|²) work.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
op
|
SparseOperator
|
Symmetric positive-definite operator. A general (non-symmetric)
pattern is factored as |
required |
symbolic
|
SymbolicCholesky | None
|
Symbolic analysis of |
None
|
Returns:
| Type | Description |
|---|---|
SparseCholeskyFactor
|
The factor. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Examples:
import equinox as eqx
import jax
import jax.numpy as jnp
import numpy as np
import gaussx
# A 1-D random-walk precision τ R + I: analyse once, factor for many τ
n = 6
R = gaussx.SparseOperator.from_coo(
np.r_[np.arange(n), np.arange(1, n)],
np.r_[np.arange(n), np.arange(n - 1)],
jnp.r_[jnp.array([1.0] + [2.0] * (n - 2) + [1.0]), -jnp.ones(n - 1)],
(n, n),
symmetric=True,
)
sym = gaussx.symbolic_cholesky(R.pattern) # host, once
def logdet(log_tau):
Q = eqx.tree_at(lambda op: op.values, R, jnp.exp(log_tau) * R.values)
return gaussx.sparse_cholesky(Q.add_diagonal(jnp.ones(n)), sym).logdet()
values = jax.vmap(logdet)(jnp.linspace(-1.0, 1.0, 4))
slope = jax.grad(logdet)(0.0) # through one Takahashi sweep