Skip to content

Commit 8fcc601

Browse files
kshyattKatharine Hyatt
andauthored
Add a new truncation strategy to protect degenerate clusters (#312)
* Add a new truncation strategy to protect degenerate clusters * Formatter * Test truncdegenerate for SVD also * Formatter * Rename the strategy to multiplets * Comments --------- Co-authored-by: Katharine Hyatt <katharine.hyatt@ugent.be>
1 parent 0ff3ce5 commit 8fcc601

6 files changed

Lines changed: 182 additions & 3 deletions

File tree

‎docs/src/user_interface/truncations.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,19 @@ combined_trunc = truncrank(10) & trunctol(; atol = 1e-6);
145145
combined_trunc = trunctol(; atol = 1e-6) | truncrank(3);
146146
```
147147

148+
Truncating with a fixed number of values can split a group of (near-)degenerate values, such as
149+
when these degeneracies are due to a symmetry. Wrapping a strategy with [`truncmultiplets`](@ref)
150+
ensures that such groups are either kept or discarded as a whole cluster:
151+
152+
```@docs; canonical=false
153+
truncmultiplets
154+
```
155+
156+
```julia
157+
# Keep at most 10 values, without splitting degenerate groups
158+
degenerate_trunc = truncmultiplets(truncrank(10); rtol = 1e-10);
159+
```
160+
148161
## Truncation Error
149162

150163
When using truncated decompositions such as [`svd_trunc`](@ref), [`eig_trunc`](@ref), or [`eigh_trunc`](@ref), an additional truncation error value is returned.

‎src/MatrixAlgebraKit.jl‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ export CUSOLVER_Simple, CUSOLVER_HouseholderQR, CUSOLVER_QRIteration, CUSOLVER_S
5252
export ROCSOLVER_HouseholderQR, ROCSOLVER_QRIteration, ROCSOLVER_Jacobi,
5353
ROCSOLVER_DivideAndConquer, ROCSOLVER_Bisection
5454

55-
export notrunc, truncrank, trunctol, truncerror, truncfilter
55+
export notrunc, truncrank, trunctol, truncerror, truncfilter, truncmultiplets
5656

5757
@static if VERSION >= v"1.11.0-DEV.469"
5858
eval(
@@ -64,7 +64,8 @@ export notrunc, truncrank, trunctol, truncerror, truncfilter
6464
eval(
6565
Expr(
6666
:public, :TruncationByOrder, :TruncationByFilter, :TruncationByValue,
67-
:TruncationByError, :TruncationIntersection, :TruncationUnion, :truncate
67+
:TruncationByError, :TruncationIntersection, :TruncationUnion, :TruncationMultiplets,
68+
:truncate
6869
)
6970
)
7071
eval(

‎src/implementations/truncation.jl‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,40 @@ _ind_union(A::Base.OneTo, B::Base.OneTo) = Base.OneTo(max(length(A), length(B)))
163163
_ind_union(A::AbstractUnitRange, B::AbstractUnitRange) = union(A, B)
164164
_ind_union(A, B) = union(A, B)
165165

166+
function findtruncated(values::AbstractVector, strategy::TruncationMultiplets)
167+
keep = _ind_to_mask(values, findtruncated(values, strategy.trunc))
168+
perm = sortperm(values; by = abs, rev = true)
169+
return findall(_keep_multiplets!(keep, values, perm, strategy))
170+
end
171+
function findtruncated_svd(values::AbstractVector, strategy::TruncationMultiplets)
172+
# values are already sorted by decreasing magnitude
173+
keep = _ind_to_mask(values, findtruncated_svd(values, strategy.trunc))
174+
return findall(_keep_multiplets!(keep, values, eachindex(values), strategy))
175+
end
176+
177+
_ind_to_mask(values::AbstractVector, ::Colon) = trues(length(values))
178+
_ind_to_mask(values::AbstractVector, ind::AbstractVector{Bool}) = BitVector(ind)
179+
function _ind_to_mask(values::AbstractVector, ind)
180+
keep = falses(length(values))
181+
keep[ind] .= true
182+
return keep
183+
end
184+
185+
# walk the values in sorted order `perm`, and make sure each group of consecutive degenerate
186+
# values is either kept or discarded as a whole cluster
187+
function _keep_multiplets!(keep::AbstractVector{Bool}, values::AbstractVector, perm, strategy::TruncationMultiplets)
188+
σs = abs.(collect(view(values, perm)))
189+
start = firstindex(σs)
190+
for k in eachindex(σs)
191+
if k == lastindex(σs) || σs[k] - σs[k + 1] > max(strategy.atol, strategy.rtol * σs[k])
192+
group = view(perm, start:k)
193+
allequal(view(keep, group)) || (keep[group] .= strategy.mode == :up)
194+
start = k + 1
195+
end
196+
end
197+
return keep
198+
end
199+
166200
# Truncation error
167201
# ----------------
168202
truncation_error(values::AbstractVector, ind) = truncation_error!(copy(values), ind)

‎src/interface/truncation.jl‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,45 @@ Base.:|(::NoTruncation, ::NoTruncation) = notrunc()
270270
Base.:|(::NoTruncation, ::TruncationUnion) = notrunc()
271271
Base.:|(::TruncationUnion, ::NoTruncation) = notrunc()
272272

273+
"""
274+
TruncationMultiplets(trunc::TruncationStrategy, atol::Real, rtol::Real, mode::Symbol)
275+
276+
Truncation strategy that applies `trunc` and then adjusts the selection such that groups of
277+
(near-)degenerate values are never split.
278+
279+
See also [`truncmultiplets`](@ref).
280+
"""
281+
struct TruncationMultiplets{S <: TruncationStrategy, T <: Real} <: TruncationStrategy
282+
trunc::S
283+
atol::T
284+
rtol::T
285+
mode::Symbol
286+
end
287+
function TruncationMultiplets(trunc::TruncationStrategy, atol::Real, rtol::Real, mode::Symbol)
288+
return TruncationMultiplets(trunc, promote(atol, rtol)..., mode)
289+
end
290+
291+
"""
292+
truncmultiplets(strategy::TruncationStrategy; atol::Real=0, rtol::Real=1e-10, mode::Symbol=:down)
293+
294+
Truncation strategy that applies `strategy`, and then makes sure that groups of (near-)degenerate
295+
values are either kept or discarded as a whole.
296+
297+
Values are sorted by decreasing magnitude, and two consecutive values `abs(vᵢ) ≥ abs(vᵢ₊₁)` are
298+
considered degenerate whenever `abs(vᵢ) - abs(vᵢ₊₁) ≤ max(atol, rtol * abs(vᵢ))`. Groups of
299+
degenerate values that are only partially kept by `strategy` are discarded entirely if
300+
`mode = :down`, or kept entirely if `mode = :up`.
301+
302+
This is useful when the degeneracies are due to a symmetry, where splitting a
303+
degenerate group would break the symmetry due to rounding errors.
304+
In particular, `truncmultiplets(truncrank(howmany))` keeps at most `howmany` values for
305+
`mode = :down`, and at least `min(howmany, length(values))` values for `mode = :up`.
306+
"""
307+
function truncmultiplets(strategy::TruncationStrategy; atol::Real = 0, rtol::Real = 1.0e-10, mode::Symbol = :down)
308+
mode in (:down, :up) || throw(ArgumentError(lazy"mode must be `:down` or `:up`, got `$mode`"))
309+
return TruncationMultiplets(strategy, atol, rtol, mode)
310+
end
311+
273312
@doc """
274313
truncation_error(values, ind)
275314
Compute the truncation error as the 2-norm of the values that are not kept by `ind`.

‎test/common/truncate.jl‎

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ using MatrixAlgebraKit
22
using Test
33
using TestExtras
44
using MatrixAlgebraKit: NoTruncation, TruncationIntersection, TruncationUnion,
5-
TruncationByOrder, TruncationByValue, TruncationStrategy, findtruncated, findtruncated_svd
5+
TruncationByOrder, TruncationByValue, TruncationMultiplets, TruncationStrategy,
6+
findtruncated, findtruncated_svd
7+
using LinearAlgebra: Diagonal, norm
68

79
@testset "truncate" begin
810
trunc = @constinferred TruncationStrategy()
@@ -94,3 +96,78 @@ using MatrixAlgebraKit: NoTruncation, TruncationIntersection, TruncationUnion,
9496
@test union2 isa TruncationUnion
9597
@test length(union2.components) == 3
9698
end
99+
100+
@testset "truncmultiplets" begin
101+
trunc = @constinferred truncmultiplets(truncrank(2))
102+
@test trunc isa TruncationMultiplets
103+
@test trunc.trunc == truncrank(2)
104+
@test trunc.atol == 0 && trunc.rtol == 1.0e-10
105+
@test trunc.mode === :down
106+
@test trunc == truncmultiplets(truncrank(2))
107+
@test trunc != truncmultiplets(truncrank(2); mode = :up)
108+
@test_throws ArgumentError truncmultiplets(truncrank(2); mode = :sideways)
109+
110+
# a degenerate group of three values around 0.5, split by truncrank(2) and truncrank(3)
111+
ϵ = 1.0e-14
112+
vals_sorted = [1.0, 0.5 + ϵ, 0.5, -0.5 + ϵ, 0.1]
113+
vals_unsorted = vals_sorted[[3, 5, 1, 4, 2]]
114+
for howmany in (2, 3)
115+
down = truncmultiplets(truncrank(howmany))
116+
up = truncmultiplets(truncrank(howmany); mode = :up)
117+
@test @constinferred(findtruncated_svd(vals_sorted, down)) == [1]
118+
@test @constinferred(findtruncated_svd(vals_sorted, up)) == 1:4
119+
@test sort(vals_unsorted[@constinferred(findtruncated(vals_unsorted, down))]) == [1.0]
120+
@test sort(vals_unsorted[@constinferred(findtruncated(vals_unsorted, up))]) ==
121+
sort(vals_sorted[1:4])
122+
end
123+
124+
# nothing changes if the cut does not split a degenerate cluster
125+
for howmany in (0, 1, 4, 5, 6)
126+
for mode in (:down, :up)
127+
strategy = truncmultiplets(truncrank(howmany); mode)
128+
@test findtruncated_svd(vals_sorted, strategy) ==
129+
findtruncated_svd(vals_sorted, truncrank(howmany))
130+
@test sort(findtruncated(vals_unsorted, strategy)) ==
131+
sort(findtruncated(vals_unsorted, truncrank(howmany)))
132+
end
133+
end
134+
@test findtruncated_svd(vals_sorted, truncmultiplets(notrunc())) == 1:5
135+
@test isempty(findtruncated_svd(Float64[], truncmultiplets(truncrank(2))))
136+
137+
# without tolerance, only exactly degenerate values are grouped
138+
@test findtruncated_svd(vals_sorted, truncmultiplets(truncrank(2); rtol = 0)) == 1:2
139+
@test findtruncated_svd([1.0, 0.5, 0.5, 0.1], truncmultiplets(truncrank(2); rtol = 0)) == [1]
140+
141+
vals_chain = [1.0, 0.9, 0.8, 0.7, 0.1]
142+
@test findtruncated_svd(vals_chain, truncmultiplets(truncrank(2); atol = 0.15)) == Int[]
143+
@test findtruncated_svd(vals_chain, truncmultiplets(truncrank(2); atol = 0.15, mode = :up)) == 1:4
144+
@test findtruncated_svd(vals_chain, truncmultiplets(truncrank(2); rtol = 0.12)) == Int[]
145+
@test findtruncated_svd(vals_chain, truncmultiplets(truncrank(2); rtol = 0.12, mode = :up)) == 1:3
146+
147+
strategy = truncmultiplets(truncrank(3) & trunctol(; atol = 0.2))
148+
@test findtruncated_svd(vals_sorted, strategy) == [1]
149+
strategy = truncmultiplets(trunctol(; atol = 0.5) | truncrank(1); mode = :up)
150+
@test findtruncated_svd(vals_sorted, strategy) == 1:4
151+
strategy = truncmultiplets(truncfilter(x -> x < 0.5 + ϵ / 2); mode = :up)
152+
@test sort(findtruncated(vals_unsorted, strategy)) == sort(findtruncated(vals_unsorted, truncfilter(x -> x < 0.9)))
153+
@test truncmultiplets(truncrank(2)) & trunctol(; atol = 0.2) isa TruncationIntersection
154+
155+
# exactly degenerate singular values
156+
for T in (Float64, ComplexF64)
157+
n = 6
158+
Q₁ = qr_compact(randn(T, n, n))[1]
159+
Q₂ = qr_compact(randn(T, n, n))[1]
160+
Sref = [3.0, 2.0, 2.0, 2.0, 1.0, 0.5]
161+
A = Q₁ * Diagonal(Sref) * Q₂'
162+
for howmany in 2:3
163+
U, S, Vᴴ, ϵ = svd_trunc(A; trunc = truncmultiplets(truncrank(howmany); rtol = 1.0e-8))
164+
@test diagview(S) ≈ Sref[1:1]
165+
@test ϵ ≈ norm(Sref[2:end])
166+
@test U * S * Vᴴ ≈ Sref[1] * Q₁[:, 1] * Q₂[:, 1]'
167+
U, S, Vᴴ, ϵ = svd_trunc(A; trunc = truncmultiplets(truncrank(howmany); rtol = 1.0e-8, mode = :up))
168+
@test diagview(S) ≈ Sref[1:4]
169+
@test ϵ ≈ norm(Sref[5:end])
170+
@test U * S * Vᴴ ≈ Q₁[:, 1:4] * Diagonal(Sref[1:4]) * Q₂[:, 1:4]'
171+
end
172+
end
173+
end

‎test/testsuite/decompositions/svd.jl‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,21 @@ function test_svd_trunc_algs(
686686
@test ϵ2 ≈ norm(diagview(S)[3:4]) atol = atol
687687
@test_throws ArgumentError svd_trunc(A; alg = truncalg, trunc = (; maxrank = 2))
688688
@test_throws ArgumentError svd_trunc_no_error(A; alg = truncalg, trunc = (; maxrank = 2))
689+
690+
# truncmultiplets
691+
Sdiag = similar(A, real(eltype(T)), m4)
692+
copyto!(Sdiag, real(eltype(T))[0.9, 0.3, 0.3, 0.01])
693+
S = Diagonal(Sdiag)
694+
Vᴴ = instantiate_unitary(T, A, m4)
695+
A = U * S * Vᴴ
696+
truncalg = TruncatedAlgorithm(alg, truncmultiplets(truncrank(2); atol = 0.2))
697+
U2, S2, V2ᴴ, ϵ2 = @testinferred svd_trunc(A; alg = truncalg)
698+
@test collect(diagview(S2)) ≈ collect(diagview(S)[1:1])
699+
@test ϵ2 ≈ norm(diagview(S)[2:4]) atol = atol
700+
truncalg = TruncatedAlgorithm(alg, truncmultiplets(truncrank(3); atol = 0.2))
701+
U2, S2, V2ᴴ, ϵ2 = @testinferred svd_trunc(A; alg = truncalg)
702+
@test collect(diagview(S2)) ≈ collect(diagview(S)[1:3])
703+
@test ϵ2 ≈ norm(diagview(S)[4:4]) atol = atol
689704
end
690705
end
691706
end

0 commit comments

Comments
 (0)