Skip to content

Commit 098c54e

Browse files
lkdvosclaude
andcommitted
Integrate MatrixFunctionViaTaylor with the exponential interface
Register a pure-Julia scaling-and-squaring Taylor algorithm as `MatrixFunctionViaTaylor` and fit it to the exponential interface: the `(τ, A)` forms reuse the existing generic method, and it becomes the default algorithm for all dense matrices (`DiagonalAlgorithm` still handles `Diagonal`). Being LAPACK-free, it also covers arbitrary precision, where `LinearAlgebra.exp` has no method. The truncation order and number of squarings are chosen to minimize the Paterson-Stockmeyer matrix-multiplication count under the Taylor remainder bound, the polynomial is evaluated with incrementally built coefficients, and squaring reuses a ping-pong buffer. `balance!` is rewritten as a clean, type-generic Parlett-Reinsch scaling and wired in as an optional preprocessing step. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent a3f1696 commit 098c54e

6 files changed

Lines changed: 172 additions & 112 deletions

File tree

‎src/MatrixAlgebraKit.jl‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ export LAPACK_HouseholderQR, LAPACK_HouseholderLQ, LAPACK_Simple, LAPACK_Expert,
4141
export GLA_HouseholderQR, GLA_QRIteration, GS_QRIteration
4242
export LQViaTransposedQR
4343
export PolarViaSVD, PolarNewton
44-
export MatrixFunctionViaLA, MatrixFunctionViaEig, MatrixFunctionViaEigh
44+
export MatrixFunctionViaLA, MatrixFunctionViaEig, MatrixFunctionViaEigh, MatrixFunctionViaTaylor
4545
export DefaultAlgorithm
4646
export DiagonalAlgorithm
4747
export NativeBlocked
@@ -94,6 +94,7 @@ include("common/safemethods.jl")
9494
include("common/view.jl")
9595
include("common/regularinv.jl")
9696
include("common/matrixproperties.jl")
97+
include("common/balancing.jl")
9798
include("common/utility.jl")
9899

99100
include("yalapack.jl")

‎src/common/balancing.jl‎

Lines changed: 40 additions & 108 deletions
Original file line numberDiff line numberDiff line change
@@ -1,125 +1,57 @@
11
"""
2-
balance!(A::AbstractMatrix{T}; radix=convert(T, 2)) where T
2+
balance!(A::AbstractMatrix; radix=2) -> A, scale
33
4-
A pure Julia implementation of the GEBAL algorithm.
5-
Balances a matrix to improve eigenvalue accuracy.
4+
Balance the square matrix `A` in place through a diagonal similarity `A ← D⁻¹ A D` that
5+
reduces its norm, using the scaling phase of the Parlett–Reinsch algorithm (as in LAPACK's
6+
`gebal`). The returned `scale` holds the diagonal of `D`, so that a matrix function of the
7+
original input can be recovered from a matrix function `f` of the balanced matrix through
8+
`D f(D⁻¹AD) D⁻¹`, i.e. `expA[i, j] = scale[i] * f(B)[i, j] / scale[j]`.
69
"""
7-
function balance!(A::AbstractMatrix{T}; radix=convert(T, 2)) where T
10+
function balance!(A::AbstractMatrix{T}; radix::Integer = 2) where {T}
811
n = LinearAlgebra.checksquare(A)
9-
10-
scale = ones(real(T), n)
11-
low = 1
12-
high = n
13-
converged = false
14-
15-
# --- Step 1: Permutation (Search for isolated eigenvalues) ---
16-
# (Simplified for brevity; most performance gain comes from scaling)
17-
# In a full GEBAL, we would swap rows/cols to move zeros to the corners.
12+
R = real(T)
13+
scale = ones(R, n)
14+
β = convert(R, radix)
15+
β² = β * β
1816

19-
# --- Step 2: Scaling (The Ward Algorithm) ---
17+
converged = false
2018
while !converged
2119
converged = true
22-
for i in low:high
23-
# Calculate row and column norms (excluding diagonal)
24-
row_norm = 0.0
25-
col_norm = 0.0
26-
for j in low:high
27-
if i == j continue end
28-
row_norm += abs(A[i, j])
29-
col_norm += abs(A[j, i])
20+
for i in 1:n
21+
colnorm = zero(R)
22+
rownorm = zero(R)
23+
for j in 1:n
24+
j == i && continue
25+
colnorm += abs(A[j, i])
26+
rownorm += abs(A[i, j])
3027
end
31-
32-
# Avoid division by zero
33-
if row_norm == 0 || col_norm == 0
34-
continue
28+
(iszero(colnorm) || iszero(rownorm)) && continue
29+
30+
factor = one(R)
31+
total = colnorm + rownorm
32+
threshold = rownorm / β
33+
while colnorm < threshold
34+
factor *= β
35+
colnorm *= β²
3536
end
36-
37-
# Iterative scaling to bring row and col norms closer
38-
g = row_norm / radix
39-
f = 1.0
40-
s = col_norm + row_norm
41-
42-
# While column norm is significantly smaller than row norm
43-
while col_norm < g
44-
f *= radix
45-
col_norm *= radix^2
37+
threshold = rownorm * β
38+
while colnorm >= threshold
39+
factor /= β
40+
colnorm /= β²
4641
end
47-
48-
# While column norm is significantly larger than row norm
49-
g = row_norm * radix
50-
while col_norm >= g
51-
f /= radix
52-
col_norm /= radix^2
53-
end
54-
55-
# Apply scaling if it's significant
56-
if (col_norm + row_norm) / f < 0.95 * s
57-
converged = false
58-
g = 1.0 / f
59-
scale[i] *= f
60-
# Apply to rows
61-
for j in 1:n
62-
A[i, j] *= g
63-
end
64-
# Apply to columns
65-
for j in 1:n
66-
A[j, i] *= f
67-
end
68-
end
69-
end
70-
end
71-
72-
return A, scale
73-
end
7442

75-
76-
function permute_matrix!(A::AbstractMatrix{T}) where T
77-
n = size(A, 1)
78-
low = 1
79-
high = n
80-
81-
# Simple implementation of the permutation search
82-
# We look for rows/cols that are essentially isolated
83-
84-
# Search from the bottom up (high) and top down (low)
85-
changed = true
86-
while changed
87-
changed = false
88-
89-
# Look for a column with only one non-zero element
90-
for j in high:-1:low
91-
col = A[low:high, j]
92-
if count(!iszero, col) == 1
93-
# Permute this column to the 'high' position
94-
swap_cols!(A, j, high)
95-
swap_rows!(A, j, high)
96-
high -= 1
97-
changed = true
43+
(colnorm + rownorm) < convert(R, 0.95) * factor * total || continue
44+
converged = false
45+
scale[i] *= factor
46+
invfactor = inv(factor)
47+
for j in 1:n
48+
A[i, j] *= invfactor
9849
end
99-
end
100-
101-
# Look for a row with only one non-zero element
102-
for i in low:high
103-
row = A[i, low:high]
104-
if count(!iszero, row) == 1
105-
# Permute this row to the 'low' position
106-
swap_cols!(A, i, low)
107-
swap_rows!(A, i, low)
108-
low += 1
109-
changed = true
50+
for j in 1:n
51+
A[j, i] *= factor
11052
end
11153
end
11254
end
113-
return low, high
114-
end
11555

116-
function swap_rows!(A, i, j)
117-
for k in axes(A, 2)
118-
A[i, k], A[j, k] = A[j, k], A[i, k]
119-
end
56+
return A, scale
12057
end
121-
function swap_cols!(A, i, j)
122-
for k in axes(A, 1)
123-
A[k, i], A[k, j] = A[k, j], A[k, i]
124-
end
125-
end

‎src/implementations/exponential.jl‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,3 +107,99 @@ function exponential!((τ, A)::Tuple{Number, AbstractMatrix}, expA::AbstractMatr
107107
check_input(exponential!, (τ, A), expA, alg)
108108
return map_diagonal!(x -> exp(x * τ), expA, A)
109109
end
110+
111+
# Taylor logic
112+
# ------------
113+
function exponential!(A::AbstractMatrix, expA::AbstractMatrix, alg::MatrixFunctionViaTaylor)
114+
check_input(exponential!, A, expA, alg)
115+
T = eltype(A)
116+
tol = convert(real(T), get(alg.kwargs, :tol, eps(real(T))))
117+
scale = get(alg.kwargs, :balance, true) ? balance!(A)[2] : ones(real(T), size(A, 1))
118+
119+
θ = LinearAlgebra.opnorm(A, 1)
120+
if iszero(θ)
121+
fill!(expA, zero(T))
122+
diagview(expA) .= one(T)
123+
return expA
124+
end
125+
126+
order, squarings = taylor_order_and_squarings(θ, tol)
127+
squarings > 0 && rmul!(A, inv(convert(T, 2)^squarings))
128+
129+
X = taylor_polynomial(A, order)
130+
if squarings > 0
131+
Y = similar(X)
132+
for _ in 1:squarings
133+
mul!(Y, X, X)
134+
X, Y = Y, X
135+
end
136+
end
137+
138+
expA .= scale .* X ./ transpose(scale)
139+
return expA
140+
end
141+
142+
# Truncation order `m` and number of squarings `s` minimizing the Paterson–Stockmeyer
143+
# matrix-multiplication count subject to the Taylor remainder bound `(θ/2ˢ)ᵐ⁺¹/(m+1)! ≤ tol`.
144+
function taylor_order_and_squarings(θ::Real, tol::Real)
145+
log2θ = log2(Float64(θ))
146+
log2tol = log2(Float64(tol))
147+
log2factorial = 0.0
148+
best_order = 1
149+
best_squarings = 0
150+
best_cost = typemax(Int)
151+
for order in 1:100
152+
log2factorial += log2(order + 1)
153+
squarings = max(0, ceil(Int, log2θ - (log2tol + log2factorial) / (order + 1)))
154+
blocksize = ceil(Int, sqrt(order + 1))
155+
cost = (blocksize - 1) + (cld(order + 1, blocksize) - 1) + squarings
156+
if cost < best_cost
157+
best_cost = cost
158+
best_order = order
159+
best_squarings = squarings
160+
end
161+
end
162+
return best_order, best_squarings
163+
end
164+
165+
# Evaluate ∑ₖ₌₀ᵐ Aᵏ/k! via the Paterson–Stockmeyer scheme, returning a freshly allocated matrix.
166+
function taylor_polynomial(A::AbstractMatrix, order::Integer)
167+
T = eltype(A)
168+
blocksize = ceil(Int, sqrt(order + 1))
169+
170+
invfactorial = Vector{T}(undef, order + 1)
171+
invfactorial[1] = one(T)
172+
for k in 1:order
173+
invfactorial[k + 1] = invfactorial[k] / k
174+
end
175+
176+
powers = Vector{typeof(A)}(undef, blocksize)
177+
powers[1] = A
178+
for p in 2:blocksize
179+
powers[p] = powers[p - 1] * A
180+
end
181+
182+
result = similar(A)
183+
block = similar(A)
184+
numblocks = fld(order, blocksize)
185+
taylor_block!(result, powers, invfactorial, numblocks, blocksize, order)
186+
for j in (numblocks - 1):-1:0
187+
mul!(block, result, powers[blocksize])
188+
taylor_block!(result, powers, invfactorial, j, blocksize, order)
189+
result .+= block
190+
end
191+
return result
192+
end
193+
194+
# Sub-polynomial ∑ᵢ₌₀ᵇ⁻¹ c_{jb+i} Aⁱ of degree `blocksize - 1`, written into `out`.
195+
function taylor_block!(out::AbstractMatrix, powers, invfactorial, j::Integer, blocksize::Integer, order::Integer)
196+
base = j * blocksize
197+
fill!(out, zero(eltype(out)))
198+
diagview(out) .= invfactorial[base + 1]
199+
for i in 1:(blocksize - 1)
200+
k = base + i
201+
k > order && break
202+
out .+= invfactorial[k + 1] .* powers[i]
203+
end
204+
return out
205+
end

‎src/interface/exponential.jl‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ Compute the exponential of the square matrix `A` or `τ * A`,
2424
# -------------------
2525
default_exponential_algorithm(A; kwargs...) = default_exponential_algorithm(typeof(A); kwargs...)
2626
function default_exponential_algorithm(T::Type; kwargs...)
27-
return MatrixFunctionViaLA(; kwargs...)
27+
return MatrixFunctionViaTaylor(; kwargs...)
2828
end
2929
function default_exponential_algorithm(::Type{T}; kwargs...) where {T <: Diagonal}
3030
return DiagonalAlgorithm(; kwargs...)

‎src/interface/matrixfunctions.jl‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,18 @@ Algorithm type to denote finding the exponential of `A` via the implementation o
88
"""
99
@algdef MatrixFunctionViaLA
1010

11+
"""
12+
MatrixFunctionViaTaylor(; tol=eps, balance=true)
13+
14+
Algorithm type to denote finding the exponential of `A` through a pure-Julia scaling-and-squaring
15+
evaluation of its Taylor series, following Fasi & Higham (2018).
16+
The truncation order and the number of squarings are chosen to reach a relative accuracy `tol`,
17+
and the Taylor polynomial is evaluated with the Paterson–Stockmeyer scheme.
18+
When `balance` is `true`, `A` is first balanced by a diagonal similarity.
19+
As this algorithm requires no LAPACK support, it also applies at arbitrary precision.
20+
"""
21+
@algdef MatrixFunctionViaTaylor
22+
1123
"""
1224
MatrixFunctionViaEigh(eigh_alg)
1325

‎test/exponential.jl‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ GenericFloats = (Float16, ComplexF16, BigFloat, Complex{BigFloat})
2121
@test expA ≈ expA2
2222
@test A == Ac
2323

24-
algs = (MatrixFunctionViaLA(), MatrixFunctionViaEig(LAPACK_Simple()))
24+
algs = (MatrixFunctionViaLA(), MatrixFunctionViaEig(LAPACK_Simple()), MatrixFunctionViaTaylor())
2525
@testset "algorithm $alg" for alg in algs
2626
expA2 = @constinferred exponential(A, alg)
2727
@test expA ≈ expA2
@@ -46,7 +46,7 @@ end
4646
@test expAτ ≈ expAτ2
4747
@test A == Ac
4848

49-
algs = (MatrixFunctionViaLA(), MatrixFunctionViaEig(LAPACK_Simple()))
49+
algs = (MatrixFunctionViaLA(), MatrixFunctionViaEig(LAPACK_Simple()), MatrixFunctionViaTaylor())
5050
@testset "algorithm $alg" for alg in algs
5151
expAτ2 = @constinferred exponential((τ, A), alg)
5252
@test expAτ ≈ expAτ2
@@ -86,3 +86,22 @@ end
8686
@test expAτ ≈ expAτ2
8787
@test A == Ac
8888
end
89+
90+
@testset "exponential via Taylor for T = $T" for T in GenericFloats
91+
rng = StableRNG(123)
92+
m = 54
93+
94+
A = randn(rng, T, m, m) ./ (2 * m)
95+
τ = randn(rng, T)
96+
Ac = copy(A)
97+
alg = MatrixFunctionViaTaylor()
98+
reltol = max(1.0e-7, sqrt(eps(real(T))))
99+
100+
expA = @constinferred exponential(A, alg)
101+
@test A == Ac
102+
@test isapprox(expA * exponential(-A, alg), I; rtol = reltol)
103+
@test isapprox(ComplexF64.(expA), exp(ComplexF64.(A)); rtol = reltol)
104+
105+
expτA = @constinferred exponential((τ, A), alg)
106+
@test isapprox(ComplexF64.(expτA), exp(ComplexF64(τ) .* ComplexF64.(A)); rtol = reltol)
107+
end

0 commit comments

Comments
 (0)