Sparse Linear Algebra (libSparse)
AppleAccelerate wraps Apple's Sparse Solvers library for sparse matrix operations and direct solvers.
AASparseMatrix
A wrapper around Apple's SparseMatrix format. Construct it either from Julia's SparseMatrixCSC or directly from coordinate (COO) triplets.
using AppleAccelerate, SparseArrays
import AppleAccelerate: AASparseMatrix, muladd!
A_jl = sprandn(100, 100, 0.05)
A = AASparseMatrix(A_jl)
x = randn(100)
y = A * x # Sparse matrix-vector multiplyYou can also build straight from coordinate (COO) triplets with 1-based indices, like SparseArrays.sparse(I, J, V, m, n) (duplicate coordinates are summed):
using AppleAccelerate, SparseArrays
import AppleAccelerate: AASparseMatrix
I = [1, 2, 3, 1]; J = [1, 2, 3, 3]; V = [10.0, 20.0, 30.0, 5.0]
B = AASparseMatrix(I, J, V, 3, 3)
@assert SparseMatrixCSC(B) ≈ sparse(I, J, V, 3, 3)The SparseMatrixCSC constructor automatically detects symmetric/Hermitian and triangular structure and sets the appropriate Apple Accelerate attributes. The COO constructor uses Accelerate's SparseConvertFromCoordinate and accepts Float32/Float64 and (macOS 15.5+) ComplexF32/ComplexF64 values.
Matrix operations
| Function | Description |
|---|---|
AASparseMatrix | Construct from a SparseMatrixCSC or from COO triplets (I, J, V, m, n) |
A * x | Sparse matrix-vector or matrix-matrix multiply |
alpha * A * x | Scaled sparse multiply |
muladd! | Multiply-add: y += A * x or y += alpha * A * x |
transpose(A) | Transpose (sets flag, no copy) |
adjoint(A) / A' | Conjugate transpose (complex; equals transpose for real) |
Query functions
| Function | Description |
|---|---|
size(A) | Matrix dimensions |
eltype(A) | Element type |
issymmetric(A) | Check if symmetric |
istriu(A) | Check if upper triangular |
istril(A) | Check if lower triangular |
A[i, j] | Element access |
Complex-valued matrices
The entire sparse surface accepts ComplexF32/ComplexF64 in addition to Float32/Float64 (complex requires macOS 15.5+): the SparseMatrixCSC and COO constructors, direct factorizations (Cholesky/LDLᵀ/LU/QR), solve/solve!/ ldiv!, refactor!, SparseMultiply/muladd!, transpose/adjoint, the iterative solvers (:cg/:gmres/:lsmr) with preconditioners, sub-factor extraction, the preallocated-workspace solve, partial-LU update, and introspection.
Complex matrices differ from real ones in two ways:
- Cholesky and CG use the Hermitian path. For a complex matrix,
cholesky(A)andsolve(A, b; method = :cg)requireAto be Hermitian positive-definite (A == A'), and dispatch to libSparse's Hermitian factorization — not the (complex-)symmetric one. ASparseMatrixCSC{Complex}that satisfiesishermitianis auto-tagged Hermitian when wrapped. adjoint(A') andtransposeare distinct.adjointconjugates as well as transposes; both are attribute-flag views that share the underlying CSC data.
using AppleAccelerate, SparseArrays, LinearAlgebra
import AppleAccelerate: AASparseMatrix, cholesky, solve
M = sprandn(ComplexF64, 60, 60, 0.05)
H = AASparseMatrix(SparseMatrixCSC(M * M' + 60I)) # Hermitian positive-definite
b = randn(ComplexF64, 60)
x = solve(cholesky(H), b) # Hermitian Cholesky
@assert x ≈ Matrix(H) \ bAAFactorization
Wraps Apple's SparseOpaqueFactorization. Lazy factorization wrapper: the factorization is computed on the first call to solve or by explicitly calling factor!.
import AppleAccelerate: AAFactorization, solve, solve!, factor!
A = sprandn(100, 100, 0.1) + 20I
f = AAFactorization(A)
# Factorization computed lazily on first solve
b = randn(100)
x = solve(f, b)
# Or explicitly
factor!(f)
x = solve(f, b)Factorization types
| Type | Use case |
|---|---|
SparseFactorizationQR | Default for non-symmetric matrices |
SparseFactorizationCholesky | Default for symmetric positive definite |
SparseFactorizationLDLT | Symmetric indefinite (default LDLT) |
SparseFactorizationLDLTUnpivoted | Symmetric indefinite, no pivoting |
SparseFactorizationLDLTSBK | Symmetric indefinite, Bunch-Kaufman |
SparseFactorizationLDLTTPP | Symmetric indefinite, threshold partial pivoting |
SparseFactorizationCholeskyAtA | Cholesky of A'A (for least squares) |
Solve functions
| Function | Description |
|---|---|
AAFactorization | Lazy factorization wrapper |
solve(f, b) | Solve Ax = b, returns new vector/matrix |
solve!(f, xb) | Solve in-place (xb is overwritten with solution) |
f \ b | Equivalent to solve(f, b) |
ldiv!(f, xb) | Equivalent to solve!(f, xb) |
ldiv!(x, f, b) | Solve Ax = b, store result in x |
factor!(f) | Explicitly compute the factorization |
factor!(f, type) | Compute factorization with specific type |
factorize(A::AASparseMatrix) | Create an AAFactorization from a sparse matrix |
Factorization conveniences
For matrices wrapped as an AASparseMatrix, the usual LinearAlgebra factorization spellings build an AAFactorization of the requested kind:
import AppleAccelerate: AASparseMatrix
A = AASparseMatrix(sprandn(100, 100, 0.1) + 20I)
F = lu(A) # AAFactorization (LU; requires macOS 15.5+)
G = qr(A) # QR (also works for rectangular / least-squares)cholesky(A) and ldlt(A) are available for symmetric/Hermitian matrices.
These methods dispatch on AppleAccelerate's own AASparseMatrix, not on SparseMatrixCSC, so they do not override Julia's built-in lu(::SparseMatrixCSC) / cholesky / qr / ldlt (UMFPACK/CHOLMOD/SPQR). You opt in to the Accelerate solvers by wrapping your matrix in AASparseMatrix first, e.g. lu(AASparseMatrix(A)).
Reusing a factorization: refactor!
When a matrix changes its values but not its sparsity pattern — the common case in Newton iterations, implicit time stepping, and parameter sweeps — refactor! recomputes the numeric factorization in place while reusing the existing symbolic factorization (the fill-reducing ordering and sparsity analysis). This is substantially cheaper than building a fresh AAFactorization.
import AppleAccelerate: AAFactorization, refactor!, solve
P = sprandn(100, 100, 0.05) + 20I
F = AAFactorization(P)
solve(F, randn(100)) # forces the first (full) factorization
# Same sparsity pattern, new values:
P2 = copy(P); P2.nzval .*= 1.5
refactor!(F, P2) # reuses the symbolic factorization
x = solve(F, randn(100))F must already hold a completed factorization (call factor!/solve once first), and A must have the same number of stored nonzeros as the original matrix.
For LU/Cholesky/LDLᵀ factorizations you can equivalently use the LinearAlgebra-style spellings that mirror how SparseArrays exposes symbolic reuse — lu!(F, A), cholesky!(F, A), ldlt!(F, A). Each requires F to already hold a factorization of the matching kind and delegates to refactor!. QR reuse has no stdlib spelling, so use refactor! directly for it.
Round-tripping to SparseMatrixCSC
An AASparseMatrix can be materialized back to a standard Julia SparseMatrixCSC. The transpose/adjoint/symmetric/Hermitian/triangular attribute bits are honored, so the result equals the logical matrix the wrapper represents:
A = AASparseMatrix(sprandn(50, 50, 0.1))
B = SparseMatrixCSC(A)
@assert B ≈ SparseMatrixCSC(A) # round-trips the logical matrixIterative solvers (CG / GMRES / LSMR)
Krylov iterative solvers are available through solve with a method keyword, dispatching on AASparseMatrix (or a SparseMatrixCSC directly). Choose :cg for symmetric positive-definite systems, :gmres for square non-symmetric or indefinite systems, and :lsmr for rectangular or singular least-squares systems.
import AppleAccelerate: AASparseMatrix, solve
M = sprandn(200, 200, 0.02)
A = AASparseMatrix(M * M' + 200I) # SPD
b = randn(200)
x = solve(A, b; method = :cg, rtol = 1e-10)atol/rtol set the convergence tolerances (0 selects the library default), maxiter caps iterations (0 → 100). GMRES accepts variant (:dqgmres/:gmres/:fgmres) and nvec; LSMR accepts lambda (Tikhonov damping) and nvec.
Preconditioners
Pass preconditioner = :diagonal or :diagscaling to solve, or build a reusable AAPreconditioner handle:
import AppleAccelerate: AASparseMatrix, AAPreconditioner, solve
A = AASparseMatrix(let M = sprandn(200, 200, 0.02); M * M' + 200I end)
P = AAPreconditioner(A; kind = :diagonal)
x = solve(A, randn(200); method = :cg, preconditioner = P, rtol = 1e-10)Preallocated / thread-safe solve workspace
For repeated or concurrent solves that reuse a factorization, a solve! overload takes a caller-owned scratch buffer sized with solve_workspace_size, avoiding the per-call internal allocation. Each concurrent thread must use its own workspace and its own solution buffer.
import AppleAccelerate: AAFactorization, factor!, solve!, solve_workspace_size
f = AAFactorization(sprandn(100, 100, 0.1) + 20I)
factor!(f)
ws = Vector{UInt8}(undef, solve_workspace_size(f, 1))
b = randn(100); x = similar(b)
solve!(f, b, x, ws)Sub-factor extraction (Q, R, L, D, P)
Individual factors of a factorization can be extracted with subfactor and applied with * (multiply) or \ (solve). For example, from a QR factorization, R is upper-triangular and Q is orthogonal:
import AppleAccelerate: AAFactorization, factor!, subfactor,
SparseFactorizationQR, SparseSubfactorR, SparseSubfactorQ
A = sprandn(40, 15, 0.3)
f = AAFactorization(A)
factor!(f, SparseFactorizationQR)
R = subfactor(f, SparseSubfactorR) # 15×15 upper-triangular
Q = subfactor(f, SparseSubfactorQ) # 40×15 orthogonal
y = randn(15)
@assert R * (R \ y) ≈ yPartial LU update
For a pivotless LU factorization, update_partial_lu! applies a partial refactorization when only a few entries change — recomputing only the L/U values a from-scratch LU would alter (requires macOS 15.5+). Distinct from refactor!, which recomputes the entire numeric factorization.
Introspection
numeric_options and symbolic_options read back the options libSparse recorded for a completed factorization.
Iterative / advanced solve functions
| Function | Description |
|---|---|
solve(A::AASparseMatrix, b; method, …) | Iterative CG/GMRES/LSMR solve |
AAPreconditioner | Diagonal / diagonal-scaling preconditioner |
solve_workspace_size | Bytes needed for a preallocated-workspace solve |
solve!(f, b, x, ws) | Solve reusing a caller-owned workspace buffer |
subfactor | Extract a Q/R/L/D/P sub-factor to apply with * / \ |
update_partial_lu! | Partial LU refactorization for a low-rank change |
numeric_options | Read back numeric-factor options |
symbolic_options | Read back symbolic-factor options |
AppleAccelerate.AASparseMatrix — Type
Matrix wrapper, containing the Apple sparse matrix struct and the pointed-to data. Construct from a SparseMatrixCSC.
Multiplication (*) and multiply-add (muladd!) with both Vector and Matrix objects are working. transpose creates a new matrix structure with the opposite transpose flag, that references the same CSC data.
AppleAccelerate.AAFactorization — Type
Factorization object.
Create via f = AAFactorization(A::SparseMatrixCSC{T, Int64}). Calls to solve, ldiv, and their in-place versions require explicitly passing in the factorization object as the first argument. On construction, the struct stores a placeholder yet-to-be-factored object: the factorization is computed upon the first call to solve, or by explicitly calling factor!. If the matrix is symmetric, it defaults to a Cholesky factorization; otherwise, it defaults to QR.
AppleAccelerate.muladd! — Function
Computes y += A*x in place. Note that this modifies its LAST argument.
Computes y += alphaAx in place. Note that this modifies its LAST argument.
AppleAccelerate.factor! — Function
factor!(f::AAFactorization, [type::SparseFactorization_t])Explicitly compute the factorization. If type is not specified, the default is chosen from the matrix's kind attribute:
- Hermitian (real symmetric or complex Hermitian) → Cholesky
- square, non-Hermitian → LU (macOS 15.5+; falls back to QR on older systems)
- rectangular → QR
Called automatically by solve if the factorization has not yet been computed.
When the user leaves the factorization type unspecified and passes a complex symmetric (but not Hermitian) matrix, we default to LU factorization.
On older versions of MacOS, Apple's SparseFactorizationLDLT errors on complex symmetric (non-Hermitian) matrices, reporting "Cannot perform Hermitian matrix factorization of non-Hermitian matrix." On newer versions, it accepts the call and performs a true LDLᵀ (not LDLᴴ). This behavior isn't documented by Apple; the exact version threshold is unknown.
AppleAccelerate.solve — Function
solve(f::AAFactorization, b::StridedVecOrMat)Solve the linear system Ax = b using Apple's Sparse Solvers, returning the solution x. The factorization is computed lazily on the first call if not already factored. Equivalent to f \ b.
solve(A::AASparseMatrix, b; method, preconditioner = :none,
atol = 0, rtol = 0, maxiter = 0, nvec = 0, variant = :dqgmres, lambda = 0)Solve A x = b with an iterative Krylov method instead of a direct factorization, returning x. method (required) is one of:
:cg— conjugate gradient;Amust be symmetric positive-definite.:gmres— GMRES; for square non-symmetric / indefinite systems.variantis:dqgmres(default),:gmres, or:fgmres;nvecsets the number of orthogonalization vectors.:lsmr— LSMR least-squares; for rectangular or singular systems.lambdaapplies Tikhonov damping.
atol/rtol are the absolute/relative convergence tolerances (0 selects the library default), maxiter the iteration cap (0 → 100). preconditioner may be :none, :diagonal, :diagscaling, or an AAPreconditioner. b may be a vector or a matrix (multiple right-hand sides). Float32/Float64, and (macOS 15.5+) ComplexF32/ComplexF64 — for complex, :cg requires a Hermitian positive-definite matrix.
AppleAccelerate.solve! — Function
solve!(f::AAFactorization, xb::StridedVecOrMat)Solve the linear system Ax = b in-place, overwriting xb with the solution. On input xb contains the right-hand side b; on output it contains the solution x. Equivalent to ldiv!(f, xb).
solve!(f::AAFactorization, b, x, workspace::Vector{UInt8})Solve A x = b writing the result into x, using the caller-supplied workspace scratch buffer instead of allocating internally — for repeated or concurrent solves that reuse a factorization without per-call allocation. Size workspace with solve_workspace_size(f, size(b, 2)). Each concurrent thread must use its own workspace and its own x. Returns x.
solve!(f::AAFactorization, xb, workspace::Vector{UInt8})In-place variant: xb holds the right-hand side on input and the solution on output (square systems only).
AppleAccelerate.refactor! — Function
refactor!(f::AAFactorization, A::AASparseMatrix)
refactor!(f::AAFactorization, A::SparseMatrixCSC)Recompute the numeric factorization stored in f using the values of A, reusing the existing symbolic factorization (the fill-reducing ordering and sparsity analysis). A must have the same sparsity pattern as the matrix f was originally factored from; only its numeric values may differ.
This is substantially cheaper than building a fresh AAFactorization whenever a matrix changes values but not structure — the common case in Newton iterations, implicit time stepping, and parameter sweeps.
For LU/Cholesky/LDLᵀ factorizations you can equivalently use the LinearAlgebra-style spellings lu!(f, A), cholesky!(f, A), and ldlt!(f, A) (matching SparseArrays' symbolic-reuse API); they require f to already hold a factorization of the matching kind and delegate here. QR reuse has no stdlib spelling, so use refactor! directly for it.
f must already hold a completed factorization (call factor! or solve at least once first); otherwise an ArgumentError is thrown. The factorization object f is mutated in place and returned. After refactor!, f references A's data, so keep A alive as long as f is used.
Apple's libSparse does not validate that the new pattern matches the old one. Passing a matrix with a different sparsity pattern is undefined behavior. The dimensions and stored nonzero count are checked here as a cheap guard, but an identical count with a different pattern will not be caught.
AppleAccelerate.AAPreconditioner — Type
Opaque preconditioner handle for the iterative solvers. Build with AAPreconditioner. Wraps a libSparse SparseOpaquePreconditioner; the backing memory is released by a finalizer.
AppleAccelerate.solve_workspace_size — Function
solve_workspace_size(f::AAFactorization, nrhs = 1) -> IntNumber of bytes of scratch a workspace buffer must hold for a solve!-with-workspace call on f with nrhs right-hand sides. The factorization must already be computed (call factor! first). Use to size the workspace argument of the preallocated-workspace solve!.
AppleAccelerate.subfactor — Function
subfactor(f::AAFactorization, which) -> AASubfactorExtract an individual factor of the factorization f for direct application. which is one of the SparseSubfactor* constants: SparseSubfactorQ/SparseSubfactorR (from QR), SparseSubfactorL/SparseSubfactorD/SparseSubfactorP (from Cholesky/LDLᵀ). f is factored if necessary. Apply the result with sub * x (multiply by the factor) or sub \ b (solve against it). Float32/Float64, and (macOS 15.5+) ComplexF32/ComplexF64.
AppleAccelerate.update_partial_lu! — Function
update_partial_lu!(f::AAFactorization, updated, A_new)Apply a partial LU refactorization to f in place: recompute only the factor values that a from-scratch LU of A_new would change, given that just the entries listed in updated differ from the originally-factored matrix. updated is a vector of 1-based (row, col) tuples of the modified positions; A_new is a full copy of the matrix with those entries at their new values and the same sparsity pattern as the original.
f must hold a pivotless LU factorization (SparseFactorizationLUUnpivoted, SparseFactorizationLUSPP, or SparseFactorizationLUTPP) — build it with factor!(f, SparseFactorizationLUUnpivoted). Requires macOS 15.5+. Float32/Float64/ComplexF32/ComplexF64. Returns f.
Distinct from refactor!, which recomputes the entire numeric factorization.
AppleAccelerate.numeric_options — Function
numeric_options(f::AAFactorization) -> SparseNumericFactorOptionsRead back the numeric-factorization options (scaling method, pivot/zero tolerances) that libSparse recorded for the completed factorization f. f must already be factored. Float32/Float64/ComplexF32/ComplexF64.
AppleAccelerate.symbolic_options — Function
symbolic_options(f::AAFactorization) -> SparseSymbolicFactorOptionsRead back the symbolic-factorization options (ordering method, etc.) recorded for the completed factorization f.