Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name = "AppleAccelerate"
uuid = "13e28ba4-7ad8-5781-acae-3021b1ed3924"
version = "0.8.0"
version = "0.9.0"

[deps]
Libdl = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
Expand Down
2 changes: 1 addition & 1 deletion docs/src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ nothing # hide
```@example quickstart-sparse
using AppleAccelerate, LinearAlgebra, SparseArrays
S = sprandn(500, 500, 0.01); S = S*S' + 500I # symmetric positive-definite
As = AppleAccelerate.AASparseMatrix(SparseMatrixCSC{Float64,Int64}(S))
As = AppleAccelerate.AASparseMatrix(Symmetric(SparseMatrixCSC{Float64,Int64}(S), :L))
xs = AppleAccelerate.solve(AppleAccelerate.cholesky(As), randn(500))
nothing # hide
```
Expand Down
45 changes: 37 additions & 8 deletions docs/src/sparse.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ g = AppleAccelerate.factor(S, :ldlt) # pick the kind: :cholesky,
AppleAccelerate.inertia(g) # pivot signs of the LDLᵀ
```

`factor(A)` picks Cholesky for a Hermitian matrix, LU for a square one (macOS
15.5+) and QR otherwise. Element types other than `Float32`/`Float64`/`ComplexF32`/
`factor(S)` picks Cholesky for a Hermitian matrix, LU for a square one (macOS
15.5+) and QR otherwise. Like `factorize`, `factor` and `solve` test a
`SparseMatrixCSC` for symmetry, and for Cholesky and LDLᵀ store a symmetric
(Hermitian) one as its lower triangle. Element types other than `Float32`/`Float64`/`ComplexF32`/
`ComplexF64` are converted to `Float64`/`ComplexF64`, and `solve` promotes the
matrix and right-hand side to a common type.

Expand Down Expand Up @@ -71,11 +73,37 @@ julia> SparseMatrixCSC(B) == sparse(rows, cols, vals, 3, 3)
true
```

The `SparseMatrixCSC` constructor automatically detects symmetric/Hermitian and
triangular structure and sets the appropriate Apple Accelerate attributes. The COO
The `SparseMatrixCSC` constructor stores the matrix as it is, without testing it
for structure; pass `attributes` (e.g. `ATT_TRI_LOWER`) to set it. The COO
constructor uses Accelerate's `SparseConvertFromCoordinate` and accepts
`Float32`/`Float64` and (macOS 15.5+) `ComplexF32`/`ComplexF64` values.

A symmetric or Hermitian matrix, which Cholesky and LDLᵀ need, is given by one
triangle, wrapped in `Symmetric` or `Hermitian`: `AASparseMatrix(Symmetric(S, :L))`
(or `:U`) stores only that triangle of `S`, with the symmetric (Hermitian)
attributes, without testing `S` for symmetry, so the lower triangle of a symmetric
matrix can be wrapped as is. As in `Symmetric`,
the other triangle of `S` is ignored, and as in `Hermitian`, so is the imaginary part
of a Hermitian matrix's diagonal.

```@example sparse
using LinearAlgebra

L = tril(sprandn(100, 100, 0.05) + 10I) # the lower triangle of a symmetric matrix
A = AASparseMatrix(Symmetric(L, :L))
F = AppleAccelerate.factor(A, :ldlt)
nothing # hide
```

!!! note
libSparse's LU does not read one-triangle symmetric storage correctly, so use
Cholesky or LDLᵀ for such matrices; `factor(A)` picks one of them.

!!! compat "AppleAccelerate 0.9"
Until 0.9, `AASparseMatrix(::SparseMatrixCSC)` tested the matrix and stored a
symmetric (Hermitian) one as its lower triangle, and tagged a triangular one.
Wrap it in `Symmetric` or `Hermitian` instead.

### Matrix operations

| Function | Description |
Expand Down Expand Up @@ -127,8 +155,8 @@ Complex matrices differ from real ones in two ways:
- **Cholesky and CG use the Hermitian path.** For a complex matrix, `cholesky(A)`
and `solve(A, b; method = :cg)` require `A` to be **Hermitian** positive-definite
(`A == A'`), and dispatch to libSparse's Hermitian factorization — not the
(complex-)symmetric one. A `SparseMatrixCSC{Complex}` that satisfies `ishermitian`
is auto-tagged Hermitian when wrapped.
(complex-)symmetric one. Wrap a `SparseMatrixCSC{Complex}` in `Hermitian` to store
it as Hermitian: `AASparseMatrix(Hermitian(S, :L))`.
- **`adjoint` (`A'`) and `transpose` are distinct.** `adjoint` conjugates as well as
transposes; both are attribute-flag views that share the underlying CSC data.

Expand All @@ -137,7 +165,7 @@ 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
H = AASparseMatrix(Hermitian(M * M' + 60I, :L)) # Hermitian positive-definite
b = randn(ComplexF64, 60)
x = solve(cholesky(H), b) # Hermitian Cholesky
@assert x ≈ Matrix(H) \ b
Expand Down Expand Up @@ -209,7 +237,8 @@ G = qr(A) # QR (also works for rectangular / least-squares)
nothing # hide
```

`cholesky(A)` and `ldlt(A)` are available for symmetric/Hermitian matrices.
`cholesky(A)` and `ldlt(A)` are available for matrices stored as symmetric (Hermitian),
e.g. `cholesky(AASparseMatrix(Symmetric(S, :L)))`.

!!! note "No type piracy"
These methods dispatch on `AppleAccelerate`'s own `AASparseMatrix`, **not** on
Expand Down
104 changes: 85 additions & 19 deletions src/sparse.jl
Original file line number Diff line number Diff line change
Expand Up @@ -913,14 +913,6 @@ end

function AASparseMatrix(sparseM::SparseMatrixCSC{T, <:Integer},
attributes::att_type = ATT_ORDINARY) where T<:vTypes
if attributes == ATT_ORDINARY
if ishermitian(sparseM)
kind = T <: Complex ? ATT_HERMITIAN : ATT_SYMMETRIC
return AASparseMatrix(tril(sparseM), kind | ATT_LOWER_TRIANGLE)
elseif istril(sparseM) || istriu(sparseM)
attributes = istril(sparseM) ? ATT_TRI_LOWER : ATT_TRI_UPPER
end
end
# NOTE: we deliberately do NOT auto-tag unit-triangular matrices. libSparse
# treats ATT_UNIT_TRIANGULAR as an *implicit* unit diagonal, but we keep the
# stored diagonal in the CSC data, so tagging it would double-count the
Expand All @@ -945,6 +937,40 @@ function AASparseMatrix(sparseM::SparseMatrixCSC{Tv, Ti},
return AASparseMatrix(SparseMatrixCSC{_aa_eltype(Tv), Ti}(sparseM), attributes)
end

"""
AASparseMatrix(S::Symmetric{<:Number, <:SparseMatrixCSC})
AASparseMatrix(H::Hermitian{<:Number, <:SparseMatrixCSC})

Wrap a symmetric (or Hermitian) matrix given by one triangle. Only the triangle that
`S` refers to (`:L` or `:U`) is stored, with the symmetric (Hermitian) attributes,
as libSparse expects for Cholesky and LDLᵀ factorizations; the other triangle of the
parent matrix is ignored, as in `Symmetric`. As in `Hermitian`, so is the imaginary
part of a Hermitian matrix's diagonal. A real `Hermitian` matrix is symmetric.

This is how to get symmetric storage, which Cholesky and LDLᵀ factorizations need:
`AASparseMatrix(::SparseMatrixCSC)` stores the matrix as it is. The matrix is not
tested for symmetry, so the lower triangle of a symmetric matrix can be wrapped as is.
"""
function AASparseMatrix(S::Union{Symmetric{<:Number, <:SparseMatrixCSC},
Hermitian{<:Number, <:SparseMatrixCSC}})
P = parent(S)
Tv = _aa_eltype(eltype(P))
# the stored triangle, copied once into the libSparse element and index types
stored = S.uplo == 'L' ? tril(P) : triu(P)
vals = eltype(stored) === Tv ? nonzeros(stored) : Vector{Tv}(nonzeros(stored))
hermitian = S isa Hermitian && Tv <: Complex
if hermitian
# as in `Hermitian`, the diagonal of a Hermitian matrix is real
for j in 1:size(stored, 2), k in nzrange(stored, j)
rowvals(stored)[k] == j && (vals[k] = real(vals[k]))
end
end
kind = hermitian ? ATT_HERMITIAN : ATT_SYMMETRIC
triangle = S.uplo == 'L' ? ATT_LOWER_TRIANGLE : ATT_UPPER_TRIANGLE
return AASparseMatrix(size(stored)..., Clong.(stored.colptr .- 1),
Cint.(rowvals(stored) .- 1), vals, kind | triangle)
end

"""
AASparseMatrix(I, J, V, m, n, attributes = ATT_ORDINARY)

Expand Down Expand Up @@ -1157,8 +1183,10 @@ 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.
to `solve`, or by explicitly calling `factor!`. If the matrix is stored as symmetric
(Hermitian), it defaults to a Cholesky factorization; otherwise, to LU for a square
matrix (macOS 15.5+) and QR for others. `AAFactorization(::SparseMatrixCSC)` stores a
Hermitian (or real symmetric) matrix so, as [`factor`](@ref) does.
"""
mutable struct AAFactorization{T<:vTypes} <: LinearAlgebra.Factorization{T}
matrixObj::AASparseMatrix{T}
Expand All @@ -1181,7 +1209,22 @@ end
LinearAlgebra.factorize(A::AASparseMatrix{T}) where T<:vTypes = AAFactorization(A)

# julia's LinearAlgebra module doesn't provide similar constructors.
AAFactorization(M::SparseMatrixCSC) = AAFactorization(AASparseMatrix(M))
AAFactorization(M::SparseMatrixCSC) = AAFactorization(_detect_structure(M, SparseFactorizationTBD))

# The `AASparseMatrix` that the `SparseMatrixCSC` conveniences (`factor`, `solve`,
# `AAFactorization`, `refactor!`) factor with `kind`: like `factorize`, they test the
# matrix, and store a Hermitian (or real symmetric) matrix as its lower triangle for the
# factorizations that use it: Cholesky and LDLᵀ, and `:auto`, which then picks Cholesky.
# A complex symmetric (not Hermitian) matrix is stored so only for an explicit LDLᵀ.
function _detect_structure(S::SparseMatrixCSC, kind::SparseFactorization_t)
symmetric_kind = kind == SparseFactorizationTBD || _refactor_family(kind) == :Symmetric
if symmetric_kind && ishermitian(S)
return AASparseMatrix(eltype(S) <: Complex ? Hermitian(S, :L) : Symmetric(S, :L))
elseif symmetric_kind && kind != SparseFactorizationTBD && issymmetric(S)
return AASparseMatrix(Symmetric(S, :L))
end
return AASparseMatrix(S)
end

# ============================================================
# Low-level numeric refactorization kernels
Expand Down Expand Up @@ -1269,7 +1312,9 @@ computed.

!!! note "Complex symmetric (not Hermitian)"
When the user leaves the factorization type unspecified and passes
a complex symmetric (but not Hermitian) matrix, we default to LU factorization.
a complex symmetric (but not Hermitian) matrix, we default to LU factorization,
unless the matrix is stored as one triangle (`AASparseMatrix(Symmetric(S))`):
libSparse's LU does not read that storage correctly, so it gets `LDLᵀ`.

On older versions of MacOS, Apple's `SparseFactorizationLDLT` errors on complex
symmetric (non-Hermitian) matrices, reporting "Cannot
Expand All @@ -1286,7 +1331,10 @@ function factor!(aa_fact::AAFactorization{T},
# non-Hermitian (macOS 15.5+); QR otherwise.
nrow, ncol = size(aa_fact.matrixObj)
lu_ok = something(_macos_version[], v"0.0.0") >= v"15.5"
# A complex symmetric (not Hermitian) matrix stored as one triangle goes
# to LDLᵀ: libSparse's LU does not read the symmetric storage correctly.
kind = ishermitian(aa_fact.matrixObj) ? SparseFactorizationCholesky :
issymmetric(aa_fact.matrixObj) ? SparseFactorizationLDLT :
(nrow == ncol && lu_ok) ? SparseFactorizationLU :
SparseFactorizationQR
end
Expand Down Expand Up @@ -1453,8 +1501,16 @@ function refactor!(aa_fact::AAFactorization{T}, A::AASparseMatrix{T}) where T<:v
return aa_fact
end

refactor!(aa_fact::AAFactorization{T}, A::SparseMatrixCSC{T, Int64}) where T<:vTypes =
refactor!(aa_fact, AASparseMatrix(A))
# stored as the matrix that `aa_fact` holds: one triangle of a symmetric (Hermitian) matrix,
# or both
function refactor!(aa_fact::AAFactorization{T}, A::SparseMatrixCSC{T, Int64}) where T<:vTypes
old = aa_fact.matrixObj
uplo = (old.matrix.structure.attributes & ATT_TRIANGLE_MASK) == ATT_UPPER_TRIANGLE ? :U : :L
B = ishermitian(old) && T <: Complex ? AASparseMatrix(Hermitian(A, uplo)) :
issymmetric(old) ? AASparseMatrix(Symmetric(A, uplo)) :
AASparseMatrix(A)
return refactor!(aa_fact, B)
end

# LinearAlgebra-style spellings of `refactor!`, matching how SparseArrays exposes
# symbolic-factorization reuse (`lu!(F, A)` for UMFPACK, `cholesky!(F, A)` /
Expand Down Expand Up @@ -1840,7 +1896,11 @@ end

function solve(A::SparseMatrixCSC{Tv,Ti}, b::AbstractVecOrMat{<:Number}; kw...) where {Tv<:Number, Ti<:Integer}
T = _aa_eltype(promote_type(Tv, eltype(b)))
AA = AASparseMatrix(Tv === T ? A : SparseMatrixCSC{T,Ti}(A))
S = Tv === T ? A : SparseMatrixCSC{T,Ti}(A)
# the storage of the factorization for a direct solve; for an iterative one, as for `:auto`
kind = get(kw, :method, :direct) === :direct ? _factor_kind(get(kw, :kind, :auto)) :
SparseFactorizationTBD
AA = _detect_structure(S, kind)
return solve(AA, b isa StridedVecOrMat{T} ? b : Array{T}(b); kw...)
end

Expand Down Expand Up @@ -2250,8 +2310,11 @@ completed [`AAFactorization`](@ref), ready for [`solve`](@ref), `\\`, `ldiv!`,

`A` is an [`AASparseMatrix`](@ref) or a plain `SparseMatrixCSC` — any index type,
and any numeric element type (values other than `Float32`/`Float64`/`ComplexF32`/
`ComplexF64` are converted to `Float64`/`ComplexF64`). Symmetric/Hermitian and
triangular structure of a `SparseMatrixCSC` is detected automatically.
`ComplexF64` are converted to `Float64`/`ComplexF64`). Like `factorize`, `factor`
tests a `SparseMatrixCSC` for symmetry: for Cholesky, LDLᵀ and `:auto`, it stores a
Hermitian (or real symmetric) matrix as its lower triangle, as
`AASparseMatrix(Hermitian(S, :L))` does. An `AASparseMatrix` is factored as it is
stored.

`kind` is `:auto` (Cholesky if Hermitian, else LU if square on macOS 15.5+, else
QR), `:cholesky`, `:ldlt`, `:lu` (macOS 15.5+), `:qr`, or any
Expand All @@ -2267,8 +2330,11 @@ function factor(A::AASparseMatrix, kind::Union{Symbol,SparseFactorization_t} = :
factor!(f, _factor_kind(kind))
return f
end
factor(A::SparseMatrixCSC, kind::Union{Symbol,SparseFactorization_t} = :auto) =
factor(AASparseMatrix(A), kind)
function factor(A::SparseMatrixCSC, kind::Union{Symbol,SparseFactorization_t} = :auto)
T = _aa_eltype(eltype(A))
S = eltype(A) === T ? A : SparseMatrixCSC{T}(A)
return factor(_detect_structure(S, _factor_kind(kind)), kind)
end

# ============================================================
# In-place multiply (`mul!`) on AASparseMatrix
Expand Down
Loading
Loading