/
SymmetricPositiveDefinite.jl
514 lines (446 loc) · 16.9 KB
/
SymmetricPositiveDefinite.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
@doc raw"""
SymmetricPositiveDefinite{T} <: AbstractDecoratorManifold{ℝ}
The manifold of symmetric positive definite matrices, i.e.
````math
\mathcal P(n) =
\bigl\{
p ∈ ℝ^{n×n}\ \big|\ a^\mathrm{T}pa > 0 \text{ for all } a ∈ ℝ^{n}\backslash\{0\}
\bigr\}
````
The tangent space at ``T_p\mathcal P(n)`` reads
```math
T_p\mathcal P(n) =
\bigl\{
X \in \mathbb R^{n×n} \big|\ X=X^\mathrm{T}
\bigr\},
```
i.e. the set of symmetric matrices,
# Constructor
SymmetricPositiveDefinite(n; parameter::Symbol=:type)
generates the manifold ``\mathcal P(n) \subset ℝ^{n×n}``
"""
struct SymmetricPositiveDefinite{T} <: AbstractDecoratorManifold{ℝ}
size::T
end
function SymmetricPositiveDefinite(n::Int; parameter::Symbol=:type)
size = wrap_type_parameter(parameter, (n,))
return SymmetricPositiveDefinite{typeof(size)}(size)
end
@doc raw"""
SPDPoint <: AbstractManifoldsPoint
Store the result of `eigen(p)` of an SPD matrix and (optionally) ``p^{1/2}`` and ``p^{-1/2}``
to avoid their repeated computations.
This result only has the result of `eigen` as a mandatory storage, the other three
can be stored. If they are not stored they are computed and returned (but then still not stored)
when required.
# Constructor
SPDPoint(p::AbstractMatrix; store_p=true, store_sqrt=true, store_sqrt_inv=true)
Create an SPD point using an symmetric positive defincite matrix `p`, where you can optionally store `p`, `sqrt` and `sqrt_inv`
"""
struct SPDPoint{
P<:Union{AbstractMatrix,Missing},
Q<:Union{AbstractMatrix,Missing},
R<:Union{AbstractMatrix,Missing},
E<:Eigen,
} <: AbstractManifoldPoint
p::P
eigen::E
sqrt::Q
sqrt_inv::R
end
SPDPoint(p::SPDPoint) = p
function SPDPoint(p::AbstractMatrix; store_p=true, store_sqrt=true, store_sqrt_inv=true)
e = eigen(Symmetric(p))
U = e.vectors
S = max.(e.values, floatmin(eltype(e.values)))
if store_sqrt
s_sqrt = Diagonal(sqrt.(S))
p_sqrt = U * s_sqrt * transpose(U)
else
p_sqrt = missing
end
if store_sqrt_inv
s_sqrt_inv = Diagonal(1 ./ sqrt.(S))
p_sqrt_inv = U * s_sqrt_inv * transpose(U)
else
p_sqrt_inv = missing
end
if store_p
q = p
else
q = missing
end
return SPDPoint{typeof(q),typeof(p_sqrt),typeof(p_sqrt_inv),typeof(e)}(
q,
e,
p_sqrt,
p_sqrt_inv,
)
end
convert(::Type{SPDPoint}, p::AbstractMatrix) = SPDPoint(p)
function Base.:(==)(p::SPDPoint, q::SPDPoint)
return p.eigen == q.eigen
end
function active_traits(f, ::SymmetricPositiveDefinite, args...)
return merge_traits(IsEmbeddedManifold(), IsDefaultMetric(AffineInvariantMetric()))
end
function allocate(p::SPDPoint)
return SPDPoint(
ismissing(p.p) ? missing : allocate(p.p),
Eigen(allocate(p.eigen.values), allocate(p.eigen.vectors)),
ismissing(p.sqrt) ? missing : allocate(p.sqrt),
ismissing(p.sqrt_inv) ? missing : allocate(p.sqrt_inv),
)
end
function allocate(p::SPDPoint, ::Type{T}) where {T}
return SPDPoint(
ismissing(p.p) ? missing : allocate(p.p, T),
Eigen(allocate(p.eigen.values, T), allocate(p.eigen.vectors, T)),
ismissing(p.sqrt) ? missing : allocate(p.sqrt, T),
ismissing(p.sqrt_inv) ? missing : allocate(p.sqrt_inv, T),
)
end
function allocate_result(M::SymmetricPositiveDefinite, ::typeof(zero_vector), p::SPDPoint)
return allocate_result(M, zero_vector, convert(AbstractMatrix, p))
end
function allocate_coordinates(M::SymmetricPositiveDefinite, p::SPDPoint, T, n::Int)
return allocate_coordinates(M, convert(AbstractMatrix, p), T, n)
end
function allocate_result(M::SymmetricPositiveDefinite, ::typeof(get_vector), p::SPDPoint, c)
return allocate_result(M, get_vector, convert(AbstractMatrix, p), c)
end
@doc raw"""
check_point(M::SymmetricPositiveDefinite, p; kwargs...)
checks, whether `p` is a valid point on the [`SymmetricPositiveDefinite`](@ref) `M`, i.e. is a matrix
of size `(N,N)`, symmetric and positive definite.
The tolerance for the second to last test can be set using the `kwargs...`.
"""
function check_point(M::SymmetricPositiveDefinite, p; kwargs...)
if !isapprox(norm(p - transpose(p)), 0.0; kwargs...)
return DomainError(
norm(p - transpose(p)),
"The point $(p) does not lie on $(M) since its not a symmetric matrix:",
)
end
if !isposdef(p)
return DomainError(
eigvals(p),
"The point $p does not lie on $(M) since its not a positive definite matrix.",
)
end
return nothing
end
function check_point(M::SymmetricPositiveDefinite, p::SPDPoint; kwargs...)
return check_point(M, convert(AbstractMatrix, p); kwargs...)
end
"""
check_vector(M::SymmetricPositiveDefinite, p, X; kwargs... )
Check whether `X` is a tangent vector to `p` on the [`SymmetricPositiveDefinite`](@ref) `M`,
i.e. atfer [`check_point`](@ref)`(M,p)`, `X` has to be of same dimension as `p`
and a symmetric matrix, i.e. this stores tangent vetors as elements of the corresponding
Lie group.
The tolerance for the last test can be set using the `kwargs...`.
"""
function check_vector(M::SymmetricPositiveDefinite, p, X; kwargs...)
if !isapprox(X, transpose(X); kwargs...)
return DomainError(
X,
"The vector $(X) is not a tangent to a point on $(M) (represented as an element of the Lie algebra) since its not symmetric.",
)
end
return nothing
end
function check_vector(M::SymmetricPositiveDefinite, p::SPDPoint, X; kwargs...)
return check_vector(M, convert(AbstractMatrix, p), X; kwargs...)
end
function check_size(M::SymmetricPositiveDefinite, p::SPDPoint; kwargs...)
return check_size(M, convert(AbstractMatrix, p); kwargs...)
end
function check_size(M::SymmetricPositiveDefinite, p::SPDPoint, X; kwargs...)
return check_size(M, convert(AbstractMatrix, p), X; kwargs...)
end
function Base.copy(p::SPDPoint)
return SPDPoint(
ismissing(p.p) ? missing : copy(p.p),
Eigen(copy(p.eigen.values), copy(p.eigen.vectors)),
ismissing(p.sqrt) ? missing : copy(p.sqrt),
ismissing(p.sqrt_inv) ? missing : copy(p.sqrt_inv),
)
end
#
# Lazy copyto, only copy if both are not missing,
# create from `p` if it is a nonmissing field in q.
#
function copyto!(q::SPDPoint, p::SPDPoint)
if !ismissing(q.p) # we have to fill the Fields
if !ismissing(p.p)
!ismissing(q.p) && copyto!(q.p, p.p)
else # otherwise compute and copy
copyto!(q.p, convert(AbstractMatrix, p))
end
end
copyto!(q.eigen.values, p.eigen.values)
copyto!(q.eigen.vectors, p.eigen.vectors)
if !ismissing(q.sqrt)
if !ismissing(p.sqrt)
copyto!(q.sqrt, p.sqrt)
else # otherwise compute and copy
copyto!(q.sqrt, spd_sqrt(p))
end
end
if !ismissing(q.sqrt_inv)
if !ismissing(p.sqrt_inv)
copyto!(q.sqrt_inv, p.sqrt_inv)
else # otherwise compute and copy
copyto!(q.sqrt_inv, spd_sqrt_inv(p))
end
end
return q
end
embed(::SymmetricPositiveDefinite, p) = p
embed(::SymmetricPositiveDefinite, p::SPDPoint) = convert(AbstractMatrix, p)
embed(::SymmetricPositiveDefinite, p, X) = X
function get_embedding(::SymmetricPositiveDefinite{TypeParameter{Tuple{n}}}) where {n}
return Euclidean(n, n; field=ℝ)
end
function get_embedding(M::SymmetricPositiveDefinite{Tuple{Int}})
n = get_parameter(M.size)[1]
return Euclidean(n, n; field=ℝ, parameter=:field)
end
@doc raw"""
injectivity_radius(M::SymmetricPositiveDefinite[, p])
injectivity_radius(M::MetricManifold{SymmetricPositiveDefinite,AffineInvariantMetric}[, p])
injectivity_radius(M::MetricManifold{SymmetricPositiveDefinite,LogCholeskyMetric}[, p])
Return the injectivity radius of the [`SymmetricPositiveDefinite`](@ref).
Since `M` is a Hadamard manifold with respect to the [`AffineInvariantMetric`](@ref) and the
[`LogCholeskyMetric`](@ref), the injectivity radius is globally ``∞``.
"""
injectivity_radius(::SymmetricPositiveDefinite) = Inf
injectivity_radius(::SymmetricPositiveDefinite, p) = Inf
injectivity_radius(::SymmetricPositiveDefinite, ::AbstractRetractionMethod) = Inf
injectivity_radius(::SymmetricPositiveDefinite, p, ::AbstractRetractionMethod) = Inf
function isapprox(p::SPDPoint, q::SPDPoint; kwargs...)
return isapprox(convert(AbstractMatrix, p), convert(AbstractMatrix, q); kwargs...)
end
"""
is_flat(::SymmetricPositiveDefinite)
Return false. [`SymmetricPositiveDefinite`](@ref) is not a flat manifold.
"""
is_flat(M::SymmetricPositiveDefinite) = false
@doc raw"""
manifold_dimension(M::SymmetricPositiveDefinite)
returns the dimension of
[`SymmetricPositiveDefinite`](@ref) `M` ``=\mathcal P(n), n ∈ ℕ``, i.e.
````math
\dim \mathcal P(n) = \frac{n(n+1)}{2}.
````
"""
function manifold_dimension(M::SymmetricPositiveDefinite)
n = get_parameter(M.size)[1]
return div(n * (n + 1), 2)
end
"""
mean(
M::SymmetricPositiveDefinite,
x::AbstractVector,
[w::AbstractWeights,]
method = GeodesicInterpolation();
kwargs...,
)
Compute the Riemannian [`mean`](@ref mean(M::AbstractManifold, args...)) of `x` using
[`GeodesicInterpolation`](@extref `ManifoldsBase.GeodesicInterpolation`).
"""
mean(::SymmetricPositiveDefinite, ::Any)
function default_approximation_method(::SymmetricPositiveDefinite, ::typeof(mean))
return GeodesicInterpolation()
end
@doc raw"""
convert(::Type{AbstractMatrix}, p::SPDPoint)
return the point `p` as a matrix.
The matrix is either stored within the [`SPDPoint`](@ref) or reconstructed from `p.eigen`.
"""
convert(::Type{AbstractMatrix}, p::SPDPoint) = p.p
function convert(::Type{AbstractMatrix}, p::SPDPoint{Missing})
return (p.eigen.vectors * Diagonal(p.eigen.values) * p.eigen.vectors')
end
@doc raw"""
spd_sqrt(p::AbstractMatrix)
spd_sqrt(p::SPDPoint)
return ``p^{\frac{1}{2}}`` by either computing it (if it is missing or for the `AbstractMatrix`)
or returning the stored value from within the [`SPDPoint`](@ref).
This method assumes that `p` represents an spd matrix.
"""
spd_sqrt(p)
function spd_sqrt(p::AbstractMatrix)
e = eigen(Symmetric(p))
U = e.vectors
S = max.(e.values, floatmin(eltype(e.values)))
Ssqrt = Diagonal(sqrt.(S))
return Symmetric(U * Ssqrt * transpose(U))
end
spd_sqrt(p::SPDPoint) = Symmetric(p.sqrt)
function spd_sqrt(p::SPDPoint{P,Missing}) where {P<:Union{AbstractMatrix,Missing}}
U = p.eigen.vectors
S = max.(p.eigen.values, floatmin(eltype(p.eigen.values)))
Ssqrt = Diagonal(sqrt.(S))
return Symmetric(U * Ssqrt * transpose(U))
end
@doc raw"""
spd_sqrt_inv(p::SPDPoint)
return ``p^{-\frac{1}{2}}`` by either computing it (if it is missing or for the `AbstractMatrix`)
or returning the stored value from within the [`SPDPoint`](@ref).
This method assumes that `p` represents an spd matrix.
"""
spd_sqrt_inv(p::SPDPoint) = Symmetric(p.sqrt_inv)
function spd_sqrt_inv(
p::SPDPoint{P,Q,Missing},
) where {P<:Union{AbstractMatrix,Missing},Q<:Union{AbstractMatrix,Missing}}
U = p.eigen.vectors
S = max.(p.eigen.values, floatmin(eltype(p.eigen.values)))
SsqrtInv = Diagonal(1 ./ sqrt.(S))
return Symmetric(U * SsqrtInv * transpose(U))
end
@doc raw"""
spd_sqrt_and_sqrt_inv(p::AbstractMatrix)
spd_sqrt_and_sqrt_inv(p::SPDPoint)
return ``p^{\frac{1}{2}}`` and ``p^{-\frac{1}{2}}`` by either computing them (if they are missing or for the `AbstractMatrix`)
or returning their stored value from within the [`SPDPoint`](@ref).
Compared to calling single methods [`spd_sqrt`](@ref Manifolds.spd_sqrt) and [`spd_sqrt_inv`](@ref Manifolds.spd_sqrt_inv) this method
only computes the eigenvectors once for the case of the `AbstractMatrix` or if both are missing.
This method assumes that `p` represents an spd matrix.
"""
spd_sqrt_and_sqrt_inv(p)
function spd_sqrt_and_sqrt_inv(p::AbstractMatrix)
e = eigen(Symmetric(p))
U = e.vectors
S = max.(e.values, floatmin(eltype(e.values)))
Ssqrt = Diagonal(sqrt.(S))
SsqrtInv = Diagonal(1 ./ sqrt.(S))
return (Symmetric(U * Ssqrt * transpose(U)), Symmetric(U * SsqrtInv * transpose(U)))
end
function spd_sqrt_and_sqrt_inv(p::SPDPoint{P}) where {P<:Union{Missing,AbstractMatrix}}
return (Symmetric(p.sqrt), Symmetric(p.sqrt_inv))
end
function spd_sqrt_and_sqrt_inv(
p::SPDPoint{P,Q,Missing},
) where {P<:Union{Missing,AbstractMatrix},Q<:AbstractMatrix}
return (Symmetric(p.sqrt), spd_sqrt_inv(p))
end
function spd_sqrt_and_sqrt_inv(
p::SPDPoint{P,Missing,R},
) where {P<:Union{Missing,AbstractMatrix},R<:AbstractMatrix}
return (spd_sqrt(p), Symmetric(p.sqrt_inv))
end
function spd_sqrt_and_sqrt_inv(
p::SPDPoint{P,Missing,Missing},
) where {P<:Union{Missing,AbstractMatrix}}
S = max.(p.eigen.values, floatmin(eltype(p.eigen.values)))
U = p.eigen.vectors
Ssqrt = Diagonal(sqrt.(S))
SsqrtInv = Diagonal(1 ./ sqrt.(S))
return (Symmetric(U * Ssqrt * transpose(U)), Symmetric(U * SsqrtInv * transpose(U)))
end
Base.eltype(p::SPDPoint) = eltype(p.eigen)
@doc raw"""
project(M::SymmetricPositiveDefinite, p, X)
project a matrix from the embedding onto the tangent space ``T_p\mathcal P(n)`` of the
[`SymmetricPositiveDefinite`](@ref) matrices, i.e. the set of symmetric matrices.
"""
project(::SymmetricPositiveDefinite, p, X)
project!(::SymmetricPositiveDefinite, Y, p, X) = (Y .= Symmetric((X + X') / 2))
@doc raw"""
rand(M::SymmetricPositiveDefinite; σ::Real=1)
Generate a random symmetric positive definite matrix on the
`SymmetricPositiveDefinite` manifold `M`.
"""
rand(M::SymmetricPositiveDefinite; σ::Real=1)
function allocate_result(M::SymmetricPositiveDefinite, ::typeof(Random.rand), p::SPDPoint)
return zero_vector(M, p)
end
function Random.rand!(
rng::AbstractRNG,
M::SymmetricPositiveDefinite,
pX;
vector_at=nothing,
σ::Real=one(eltype(pX)) /
(vector_at === nothing ? 1 : norm(convert(AbstractMatrix, vector_at))),
tangent_distr=:Gaussian,
)
N = get_parameter(M.size)[1]
if vector_at === nothing
D = Diagonal(1 .+ rand(rng, N)) # random diagonal matrix
s = qr(σ * randn(rng, N, N)) # random q
if pX isa SPDPoint
pX.eigen.values .= D.diag
pX.eigen.vectors .= s.Q
!ismissing(pX.p) && pX.p .= Symmetric(s.Q * D * transpose(s.Q))
!ismissing(pX.sqrt) && pX.sqrt .= sqrt.(D.diag)
!ismissing(pX.sqrt_inv) && pX.sqrt_inv .= inv.(sqrt.(D.diag))
else
pX .= Symmetric(s.Q * D * transpose(s.Q))
end
elseif tangent_distr === :Gaussian
# generate ONB in TxM
vector_at_matrix = convert(AbstractMatrix, vector_at)
I = one(vector_at_matrix)
B = get_basis(M, vector_at, DiagonalizingOrthonormalBasis(I))
Ξ = get_vectors(M, vector_at, B)
Ξx =
vector_transport_to.(
Ref(M),
Ref(I),
Ξ,
Ref(vector_at_matrix),
Ref(ParallelTransport()),
)
pX .= sum(σ * randn(rng, length(Ξx)) .* Ξx)
elseif tangent_distr === :Rician
C = cholesky(Hermitian(vector_at))
R = C.L + sqrt(σ) * triu(randn(rng, size(vector_at, 1), size(vector_at, 2)), 0)
pX .= R * R'
end
return pX
end
@doc raw"""
representation_size(M::SymmetricPositiveDefinite)
Return the size of an array representing an element on the
[`SymmetricPositiveDefinite`](@ref) manifold `M`, i.e. ``n×n``, the size of such a
symmetric positive definite matrix on ``\mathcal M = \mathcal P(n)``.
"""
function representation_size(M::SymmetricPositiveDefinite)
N = get_parameter(M.size)[1]
return (N, N)
end
function Base.show(io::IO, ::SymmetricPositiveDefinite{TypeParameter{Tuple{n}}}) where {n}
return print(io, "SymmetricPositiveDefinite($(n))")
end
function Base.show(io::IO, M::SymmetricPositiveDefinite{Tuple{Int}})
n = get_parameter(M.size)[1]
return print(io, "SymmetricPositiveDefinite($(n); parameter=:field)")
end
function Base.show(io::IO, ::MIME"text/plain", p::SPDPoint)
pre = " "
summary(io, p)
println(io, "\np:")
sp = sprint(show, "text/plain", p.p; context=io, sizehint=0)
sp = replace(sp, '\n' => "\n$(pre)")
println(io, pre, sp)
println(io, "p^{1/2}:")
sps = sprint(show, "text/plain", p.sqrt; context=io, sizehint=0)
sps = replace(sps, '\n' => "\n$(pre)")
println(io, pre, sps)
println(io, "p^{-1/2}:")
spi = sprint(show, "text/plain", p.sqrt_inv; context=io, sizehint=0)
spi = replace(spi, '\n' => "\n$(pre)")
return print(io, pre, spi)
end
@doc raw"""
zero_vector(M::SymmetricPositiveDefinite, p)
returns the zero tangent vector in the tangent space of the symmetric positive
definite matrix `p` on the [`SymmetricPositiveDefinite`](@ref) manifold `M`.
"""
zero_vector(::SymmetricPositiveDefinite, ::Any)
function zero_vector(M::SymmetricPositiveDefinite, p::SPDPoint)
return zero_vector(M, convert(AbstractMatrix, p))
end
zero_vector!(::SymmetricPositiveDefinite, X, ::Any) = fill!(X, 0)