-
Notifications
You must be signed in to change notification settings - Fork 1
/
Utils.jl
405 lines (340 loc) · 13.4 KB
/
Utils.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
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
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
module Utils
using Arpack
using IterativeSolvers
using LinearAlgebra
using LinearMaps
using Random
using SparseArrays
using Statistics
_mkMat(V) = convert(Matrix, V)
"""
_qrDirect(A)
Obtain and return the Q factor from the (reduced) QR factorization of A.
Overwrites A in-place.
"""
function _qrDirect(A)
return LAPACK.orgqr!(LAPACK.geqrf!(A)...)
end
function _qFactor(A)
return _qrDirect(copy(A))
end
"""
_qr(A)
Obtain and return the Q and R factors from the (reduced) QR factorization
of A.
"""
function _qr(A)
d = size(A)[2]
AA, τ = LAPACK.geqrf!(copy(A)); R = triu(AA)[1:d, :]
return LAPACK.orgqr!(AA, τ), R
end
"""
pick_rand_idx(probs)
Pick a random element from `1:n` given a vector of probabilities `probs`
of length `n`.
"""
function pick_rand(probs)
p = rand(); return findfirst((cumsum(probs) .- p) .>= 0)
end
"""
rayleigh_ritz(A::Union{Array, LinearMap, SparseMatrixCSC}, V0, n_pairs)
Get the `n_pairs` leading Ritz vectors and values for a given matrix `A`
and subspace `V0`.
"""
function rayleigh_ritz(A::Union{Array, LinearMap, SparseMatrixCSC}, V0,
n_pairs)
_, Q, D = schur(Symmetric(V0' * _mkMat(A * V0))); D = real.(D)
inds = sortperm(D, rev=true)[1:n_pairs] # leading indices
return (V0 * Q)[:, inds], D[inds]
end
# convergence test in subspace iteration
function _si_convergence(A::Union{Array, SparseMatrixCSC, LinearMap},
V0, nconv, ϵ)
Vp, D = rayleigh_ritz(A, V0, nconv)
resNorms = sum((_mkMat(A * Vp) - D' .* Vp).^2, dims=1)
return Vp, D, sum(resNorms .<= ϵ^2)
end
"""
subspace_iteration(A, ℓ, iters, ϵ=1e-5; nconv=ℓ, V0=nothing) -> (V, λs, niter)
Run subspace iteration on the matrix `A` for at most `iters` iterations
to compute `nconv` largest eigenpairs, using a block of size `ℓ` and up to
numerical tolerance `ϵ`.
Optionally, start from initial guess `V`.
Returns:
- `V`: the computed Ritz vectors
- `λs`: the computed Ritz values
- `niter`: number of iterations elapsed
"""
function subspace_iteration(A::Union{AbstractArray, SparseMatrixCSC}, ℓ,
iters, ϵ=1e-3; nconv=ℓ, V0=nothing,
Vp::Union{Nothing, Array}=nothing)
opA = LinearMap(X -> A * X, size(A)[1], size(A)[2], issymmetric=true)
return subspace_iteration(opA, ℓ, iters, ϵ, nconv=nconv, V0=V0, Vp=Vp)
end
"""
subspace_iteration(A::LinearMap, ℓ, iters, ϵ=1e-5;
nconv=ℓ, V0=nothing) -> (V, λs, niter)
Run subspace iteration on the operator `A` for at most `iters` iterations
to compute `nconv` largest eigenpairs, using a block of size `ℓ` and up to
numerical tolerance `ϵ`.
Optionally, start from initial guess `V` and orthogonalize against another
subspace `Vp`.
Returns:
- `V`: the computed Ritz vectors
- `λs`: the computed Ritz values
- `niter`: number of iterations elapsed
"""
function subspace_iteration(A::LinearMap, ℓ, iters, ϵ=1e-5; nconv=ℓ,
V0=nothing, Vp::Union{Nothing, Array}=nothing)
n = size(A)[1] # dimension of im(A)
V0 = (V0 == nothing) ? _qrDirect(randn(n, ℓ)) : V0
p = size(V0)[2]
# take care of size discrepancies
if (p < ℓ) # add missing vectors, random sample
Vrem = randn(n, ℓ - p)
V0 = hcat(V0, _qrDirect(Vrem - V0 * (V0' * Vrem)))
elseif (p > ℓ) # drop vectors corresponding to the extremal Schur vals
_, Q, D = schur(Symmetric(V0' * _mkMat(A * V0))); V0[:] = V0 * Q
inds = sortperm(D, rev=true)[1:ℓ]; V0 = V0[:, inds]
end
for i = 1:iters
Vt, λs, numConv = _si_convergence(A, V0, nconv, ϵ)
(numConv == nconv) && return Vt, λs, i+1
V0[:] = _mkMat((Vp == nothing) ? A * V0 : A * (V0 - Vp * (Vp' * V0)))
V0[:] = _qrDirect(V0)
end
return V0, sort(eigvals(Symmetric(V0' * _mkMat(A * V0))), rev=true), iters
end
"""
block_krylov(A::Union{Array, SparseMatrixCSC, LinearMap}, r::Int,
V0::Array{Float64, 2}, ϵ; maxiter=size(A)[1],
Vp::Union{Array, Nothing}) -> (X, λ, niter)
Run the LOBPCG method with initial guess V0 to compute `r`
extremal eigenpairs up to tolerance `ϵ`. Optionally set the maximal
number of iterations `maxiter`, as well as a subspace `Vp` to orthogonalize
against. Return:
- `X`: the Ritz vectors found
- `λ`: the set of computed eigenvalues
- `niter`: number of iterations required to converge to tolerance ϵ
"""
function block_krylov(A::Union{AbstractArray, SparseMatrixCSC, LinearMap},
r::Int, V0::Array{Float64, 2}, ϵ::Real;
maxiter=size(A)[1], Vp::Union{Array, Nothing}=nothing)
p = size(V0)[2]; d = size(A)[2]
if (p < r) # take care of posdef exception
G = randn(d, r - p)
V0 = hcat(V0, _qrDirect(G - V0 * (V0' * G)))
end
# make sure to take LOBPCG's spurious PosDefException into accnt.
try
lRes = lobpcg(A, true, V0, r, tol=ϵ, maxiter=maxiter, C=Vp)
return lRes.X, lRes.λ, first(lRes.iterations)
catch PosDefException
@warn("PosDefException encountered - falling back to `subspace_iteration`")
return subspace_iteration(A, r, maxiter, ϵ, V0=V0, Vp=Vp)
end
end
"""
getMinRatio(λs::Array, n_skip)
Given an array of eigenvalues `λs`, sort them in algebraically decreasing
order and return the index of the minimizing ratio of successive eigvals
as well as the sorted array.
"""
function getMinRatio(λs::Array, n_skip)
sort!(λs, rev=true); ratios = λs[2:end] ./ λs[1:(end-1)]
rIdx = first(filter(x -> x > n_skip, sortperm(ratios)))
return rIdx, λs
end
"""
rand_block_krylov(A, r, ϵ; V0=randn(size(A)[2], r)) -> (K, λs)
Run the randomized Block Krylov method from Musco & Musco's 2015 paper
to compute ``r`` extremal eigenvalues and their eigenvectors.
Return:
- `K`: the resulting subspace
- `λs`: the associated eigenvalues
"""
function rand_block_krylov(A, r::Int, ϵ::Real; V0=randn(size(A)[2], r))
d = size(A)[1]; p = size(V0)[2]
# take care of smaller size - append missing vectors
# and orthogonalize them against given subspace.
if p < r
G = randn(d, r - p)
V0 = hcat(V0, _qrDirect(G - V0 * (V0' * G)))
end
M = A * V0; q = trunc(Int, log2(d / sqrt(ϵ))) + 1
K = fill(0.0, d, q * r)
for i = 1:q
K[:, ((i-1) * r + 1) : (i * r)] = M[:]
M[:] = A * M # update (A)^q Π
end
K = _qrDirect(copy(K)); _, Q, D = schur(Symmetric(K' * (A * K)))
# sort D and pick top `r` corresponding eigenvectors
inds = sortperm(D, rev=true)[1:r]; K[:] = K * Q
return K[:, inds], D[inds]
end
"""
bkvals(A, r::Int, V0, ϵ::Real; σ=0.0, Vp::Union{Array, Nothing}=nothing) -> (λ, niter)
Run the LOBPCG method with initial guess `V0` to compute `r`
extremal eigenvalues. Optionally, apply a shift `σ` and orthogonalize
against a given subspace `Vp`. Return:
- `λ`: the set of computed eigenvalues
- `niter`: number of iterations required to converge to tolerance ϵ
"""
function bkvals(A, r::Int, V0, ϵ::Real; σ=0.0,
Vp::Union{Array, Nothing}=nothing, getVecs=false)
Vnew, λ, niter = block_krylov(A + σ * I, r, V0, ϵ, Vp=Vp)
if getVecs
return Vnew, λ, niter
else
return λ, niter
end
end
"""
bkvals(A, r::Int, ϵ::Real; σ=0.0, Vp::Union{Array, Nothing}=nothing) -> (λ, niter)
Run the LOBPCG method with random Gaussian initial guess to compute
`r` extremal eigenvalues. Optionally, apply a shift `σ` and orthogonalize
against a given subspace `Vp`. Return:
- `λ`: the set of computed eigenvalues
- `niter`: number of iterations required to converge to tolerance `ϵ`.
"""
function bkvals(A, r::Int, ϵ::Real; σ=0.0, Vp::Union{Array, Nothing}=nothing,
getVecs=false)
return bkvals(A, r, randn(size(A)[1], r), ϵ, σ=σ, getVecs=getVecs, Vp=Vp)
end
"""
sivals(A, ℓ::Int, ϵ::Real; nconv=ℓ, V0=nothing, σ=0.0, maxiter=size(A)[1]) -> (λ, niter)
Compute the `nconv` largest eigenvalues of `A` up to tolerance `ϵ`, using
a block size `ℓ`. Optionally, start from an estimate `V0` and apply a
shift `σ`, as well as orthogonalize against a given subspace `Vp`. Return:
- `λ`: the set of computed eigenvalues
- `niter`: the number of iterations required to converge to tolerance `ϵ`.
"""
function sivals(A, ℓ::Int, ϵ::Real; nconv=ℓ, V0=nothing, σ=0.0,
maxiter=size(A)[1], Vp::Union{Array, Nothing}=nothing,
getVecs=false)
Vnew, λ, niter = subspace_iteration(A + σ * I, maxiter, ϵ, nconv=nconv,
V0=V0, Vp=Vp)
if getVecs
return Vnew, λ, niter
else
return λ, niter
end
end
"""
inverse_iteration(A, r, iters; V0=nothing, σ=0.1)
Perform inverse iteration on the matrix ``A + \\sigma I`` for `iters`
iterations starting from a subspace estimate ``V_0``.
"""
function inverse_iteration(A, r, iters; V0=nothing, σ=0.1,
maxiter=nothing, ϵ=nothing)
n = size(A)[1]; Aug = A + σ * I
Vnext = (V0 == nothing) ? _qrDirect(randn(n, r)) : copy(V0)
for i = 1:iters
@simd for j = 1:r
Vnext[:, j] = conjGrad(Aug, Vnext[:, j], maxiter=maxiter, ϵ=ϵ)
end
Vnext[:] = _qrDirect(Vnext) # use conjugate gradient
end
return Vnext, eigvals(Vnext' * A * Vnext)
end
"""
getIterBounds(Δ, ϵ, λr, λr₊) -> (ubBK, ubSI)
Given an estimated initial distance `Δ`, an accuracy level `ϵ` and the
eigenvalues `λr, λr₊`, the ratio of which controls convergence,
returns the corresponding upper bounds for warm-started block
krylov and subspace iteration methods, `ubBK` and `ubSI`.
"""
function getIterBounds(Δ, ϵ, λr, λr₊, n=1)
(Δ <= 0) || (Δ >= 1) && return n, n
Δ0 = Δ / sqrt(1 - Δ^2); ρ = λr / λr₊
predBK = trunc(Int, (1 / sqrt(ρ - 1)) * (log(1 / ϵ) + log(Δ0))) + 1
predSI = trunc(Int, (1 / log(ρ)) * (log(1 / ϵ) + log(Δ0))) + 1
return real(predBK), real(predSI)
end
"""
getBounds(Δ, λr, λr₊, ϵ, γ, n, V0, VHi, r)
Given an estimated initial distance `Δ`, an accuracy level `ϵ`, the
previous eigenvalues `λr, λr₊` as well as the norm of the perturbation
`Enorm` and the decay factor `γ`, returns the corresponding upper bounds
for warm-started block krylov and subspace iteration methods,
`ubBK` and `ubSI`. If the Davis-Kahan bound is not applicable, return
the naive bound `n`, corresponding to the size of the involved matrices.
"""
function getBounds(Δ, E, λr, λr₊, ϵ, γ, n, V0, VHi, r)
(Δ == 0) && return 0, 0, 0, 0 # nothing to do if zero distance
Vall = hcat(V0, VHi)
eNorm_r = norm(E * Vall[:, r]); eNorm_r₊ = norm(E * Vall[:, r+1])
# if Δ not suitable, return naive bound
(Δ > 0.999) && return trunc(Int, n/2), trunc(Int, n/2), eNorm_r, eNorm_r₊
ρ = max((λr - sqrt(2) * eNorm_r) / (λr₊ + sqrt(2) * eNorm_r),
1 + γ)
Δ0 = Δ / sqrt(1 - Δ^2)
predBK = trunc(Int, ceil((1 / sqrt(ρ - 1)) * (log(1 / ϵ) + log(Δ0))))
predSI = trunc(Int, ceil((1 / log(ρ)) * (log(1 / ϵ) + log(Δ0))))
return real(predBK), real(predSI), eNorm_r, eNorm_r₊
end
"""
getIterBounds(Δ, ϵ, λr, λr₊, Enorm, γ, n) -> (ubBK, ubSI)
Given an estimated initial distance `Δ`, an accuracy level `ϵ`, the
previous eigenvalues `λr, λr₊` as well as the norm of the perturbation
`Enorm` and the decay factor `γ`, returns the corresponding upper bounds
for warm-started block krylov and subspace iteration methods,
`ubBK` and `ubSI`. If the Davis-Kahan bound is not applicable, return
the naive bound `n`, corresponding to the size of the involved matrices.
"""
function getIterBounds(Δ, ϵ, λr, λr₊, Enorm, γ, n; r=nothing, δ=nothing)
(Δ == 0) && return n, n
# determine the convergence rate factor
if λr > Enorm
ρ = (λr - Enorm) / (λr₊ + Enorm)
ρ = (ρ ≤ 1) ? 1 + γ : ρ
else
ρ = 1 + γ
end
# if Δ not suitable, return naive bound from Gauss init
if (Δ > 0.999)
if (r == nothing)
return n, n
else
C = log(_compCp(n, r, r, δ) / ϵ)
return trunc(Int, C / sqrt(ρ)), trunc(Int, C / log(ρ))
end
end
Δ0 = Δ / sqrt(1 - Δ^2)
predBK = trunc(Int, (1 / sqrt(ρ - 1)) * (log(1 / ϵ) + log(Δ0))) + 1
predSI = trunc(Int, (1 / log(ρ)) * (log(1 / ϵ) + log(Δ0))) + 1
return real(predBK), real(predSI)
end
"""
davKahProxy(V0, E, ϵ, λ1, λr, λr₊)
Compute the proxy for the Davis-Kahan perturbation distance given the
former subspace estimate `V0`, the perturbation `E`, the previous estimate
accuracy `ϵ`, and the set of (estimated) eigenvalues `λ1, λr, λr₊`.
"""
function davKahProxy(V0, E, ϵ, λ1, λr, λr₊; which=:LM)
eNorm = first(svds(E, nsv=1)[1].S)
evNorm = first(svds(E * V0, nsv=1)[1].S)
numer = 2 * sqrt(ϵ * eNorm^2 + evNorm^2)
denom = (λr - λr₊ - (3 * λ1 * (ϵ^2)))
return (numer / denom)
end
"""
davKahProxy(V0, E, eNorm, ϵ, λ1, λr, λr₊; which=:LM)
Compute the proxy for the Davis-Kahan perturbation distance given the
former subspace estimate `V0`, the perturbation `E` and its spectral
norm `Enorm`, the previous estimate accuracy `ϵ` and the set of (estimated)
eigenvalues `λ1, λr, λr₊`.
"""
function davKahProxy(V0, E, eNorm, ϵ, λ1, λr, λr₊)
evNorm = first(svds(E * V0, nsv=1)[1].S)
numer = 2 * sqrt(ϵ * eNorm^2 + evNorm^2)
denom = λr - λr₊ - (3 * λ1 * (ϵ^2))
return (numer / denom)
end
function _compCp(n, ℓ, r, δ)
p = ℓ - r # "oversampling" factor
Cp = ((exp(1) * sqrt(ℓ)) / (p + 1)) * (2 / δ)^(1 / (p + 1)) * (
sqrt(n - ℓ + p) + sqrt(ℓ) + sqrt(2 * log(2 / δ)))
return Cp
end
end