licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 8997 | # [-Q - ρI Aᵀ I -I ][ Δx ] [ -rc ]
# [ A δI 0 0 ][ Δy ] [ -rb ]
# [ S_l 0 X-L 0 ][Δs_l] = [σμe - (X-L)S_le]
# [ -S_u 0 0 U-X][Δs_u] [σμe + (U-X)S_ue]
export K3KrylovParams
"""
Type to use the K3 formulation with a Krylov method, using the package
[`Krylov.jl`](https://github.com/JuliaSmoothOptimizers/Krylov.jl).
The outer constructor
K3KrylovParams(; uplo = :L, kmethod = :qmr, preconditioner = Identity(),
rhs_scale = true,
atol0 = 1.0e-4, rtol0 = 1.0e-4,
atol_min = 1.0e-10, rtol_min = 1.0e-10,
ρ0 = sqrt(eps()) * 1e5, δ0 = sqrt(eps()) * 1e5,
ρ_min = 1e3 * sqrt(eps()), δ_min = 1e4 * sqrt(eps()),
itmax = 0, mem = 20)
creates a [`RipQP.SolverParams`](@ref).
The available methods are:
- `:qmr`
- `:bicgstab`
- `:usymqr`
"""
mutable struct K3KrylovParams{T, PT} <: NewtonKrylovParams{T, PT}
uplo::Symbol
kmethod::Symbol
preconditioner::PT
rhs_scale::Bool
atol0::T
rtol0::T
atol_min::T
rtol_min::T
ρ0::T
δ0::T
ρ_min::T
δ_min::T
itmax::Int
mem::Int
end
function K3KrylovParams{T}(;
uplo::Symbol = :L,
kmethod::Symbol = :qmr,
preconditioner::AbstractPreconditioner = Identity(),
rhs_scale::Bool = true,
atol0::T = eps(T)^(1 / 4),
rtol0::T = eps(T)^(1 / 4),
atol_min::T = sqrt(eps(T)),
rtol_min::T = sqrt(eps(T)),
ρ0::T = T(sqrt(eps()) * 1e5),
δ0::T = T(sqrt(eps()) * 1e5),
ρ_min::T = T(1e3 * sqrt(eps())),
δ_min::T = T(1e4 * sqrt(eps())),
itmax::Int = 0,
mem::Int = 20,
) where {T <: Real}
return K3KrylovParams(
uplo,
kmethod,
preconditioner,
rhs_scale,
atol0,
rtol0,
atol_min,
rtol_min,
ρ0,
δ0,
ρ_min,
δ_min,
itmax,
mem,
)
end
K3KrylovParams(; kwargs...) = K3KrylovParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK3Krylov{T <: Real, S, L <: LinearOperator, Ksol <: KrylovSolver} <:
PreallocatedDataNewtonKrylov{T, S}
rhs::S
rhs_scale::Bool
regu::Regularization{T}
ρv::Vector{T}
δv::Vector{T}
K::L # augmented matrix (LinearOperator)
KS::Ksol
kiter::Int
atol::T
rtol::T
atol_min::T
rtol_min::T
itmax::Int
end
function opK3prod!(
res::AbstractVector{T},
nvar::Int,
ncon::Int,
ilow::Vector{Int},
iupp::Vector{Int},
nlow::Int,
x_m_lvar::AbstractVector{T},
uvar_m_x::AbstractVector{T},
s_l::AbstractVector{T},
s_u::AbstractVector{T},
Q::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
A::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
ρv::AbstractVector{T},
δv::AbstractVector{T},
v::AbstractVector{T},
α::T,
β::T,
uplo::Symbol,
) where {T}
@views mul!(res[1:nvar], Q, v[1:nvar], -α, β)
res[1:nvar] .-= @views (α * ρv[1]) .* v[1:nvar]
@. res[ilow] += @views α * v[(nvar + ncon + 1):(nvar + ncon + nlow)]
@. res[iupp] -= @views α * v[(nvar + ncon + nlow + 1):end]
if uplo == :U
@views mul!(res[1:nvar], A, v[(nvar + 1):(nvar + ncon)], α, one(T))
@views mul!(res[(nvar + 1):(nvar + ncon)], A', v[1:nvar], α, β)
else
@views mul!(res[1:nvar], A', v[(nvar + 1):(nvar + ncon)], α, one(T))
@views mul!(res[(nvar + 1):(nvar + ncon)], A, v[1:nvar], α, β)
end
res[(nvar + 1):(nvar + ncon)] .+= @views (α * δv[1]) .* v[(nvar + 1):(nvar + ncon)]
if β == 0
@. res[(nvar + ncon + 1):(nvar + ncon + nlow)] =
@views α * (s_l * v[ilow] + x_m_lvar * v[(nvar + ncon + 1):(nvar + ncon + nlow)])
@. res[(nvar + ncon + nlow + 1):end] =
@views α * (-s_u * v[iupp] + uvar_m_x * v[(nvar + ncon + nlow + 1):end])
else
@. res[(nvar + ncon + 1):(nvar + ncon + nlow)] =
@views α * (s_l * v[ilow] + x_m_lvar * v[(nvar + ncon + 1):(nvar + ncon + nlow)]) +
β * res[(nvar + ncon + 1):(nvar + ncon + nlow)]
@. res[(nvar + ncon + nlow + 1):end] =
@views α * (-s_u * v[iupp] + uvar_m_x * v[(nvar + ncon + nlow + 1):end]) +
β * res[(nvar + ncon + nlow + 1):end]
end
end
function opK3tprod!(
res::AbstractVector{T},
nvar::Int,
ncon::Int,
ilow::Vector{Int},
iupp::Vector{Int},
nlow::Int,
x_m_lvar::AbstractVector{T},
uvar_m_x::AbstractVector{T},
s_l::AbstractVector{T},
s_u::AbstractVector{T},
Q::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
A::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
ρv::AbstractVector{T},
δv::AbstractVector{T},
v::AbstractVector{T},
α::T,
β::T,
uplo::Symbol,
) where {T}
@views mul!(res[1:nvar], Q, v[1:nvar], -α, β)
res[1:nvar] .-= @views (α * ρv[1]) .* v[1:nvar]
@. res[ilow] += @views α * s_l * v[(nvar + ncon + 1):(nvar + ncon + nlow)]
@. res[iupp] -= @views α * s_u * v[(nvar + ncon + nlow + 1):end]
if uplo == :U
@views mul!(res[1:nvar], A, v[(nvar + 1):(nvar + ncon)], α, one(T))
@views mul!(res[(nvar + 1):(nvar + ncon)], A', v[1:nvar], α, β)
else
@views mul!(res[1:nvar], A', v[(nvar + 1):(nvar + ncon)], α, one(T))
@views mul!(res[(nvar + 1):(nvar + ncon)], A, v[1:nvar], α, β)
end
res[(nvar + 1):(nvar + ncon)] .+= @views (α * δv[1]) .* v[(nvar + 1):(nvar + ncon)]
if β == 0
@. res[(nvar + ncon + 1):(nvar + ncon + nlow)] =
@views α * (v[ilow] + x_m_lvar * v[(nvar + ncon + 1):(nvar + ncon + nlow)])
@. res[(nvar + ncon + nlow + 1):end] =
@views α * (-v[iupp] + uvar_m_x * v[(nvar + ncon + nlow + 1):end])
else
@. res[(nvar + ncon + 1):(nvar + ncon + nlow)] =
@views α * (v[ilow] + x_m_lvar * v[(nvar + ncon + 1):(nvar + ncon + nlow)]) +
β * res[(nvar + ncon + 1):(nvar + ncon + nlow)]
@. res[(nvar + ncon + nlow + 1):end] =
@views α * (-v[iupp] + uvar_m_x * v[(nvar + ncon + nlow + 1):end]) +
β * res[(nvar + ncon + nlow + 1):end]
end
end
function PreallocatedData(
sp::K3KrylovParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
if iconf.mode == :mono
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), :classic)
else
regu =
Regularization(T(sp.ρ0), T(sp.δ0), T(sqrt(eps(T)) * 1e0), T(sqrt(eps(T)) * 1e0), :classic)
end
ρv = [regu.ρ]
δv = [regu.δ] # put it in a Vector so that we can modify it without modifying opK2prod!
K = LinearOperator(
T,
id.nvar + id.ncon + id.nlow + id.nupp,
id.nvar + id.ncon + id.nlow + id.nupp,
false,
false,
(res, v, α, β) -> opK3prod!(
res,
id.nvar,
id.ncon,
id.ilow,
id.iupp,
id.nlow,
itd.x_m_lvar,
itd.uvar_m_x,
pt.s_l,
pt.s_u,
fd.Q,
fd.A,
ρv,
δv,
v,
α,
β,
fd.uplo,
),
(res, v, α, β) -> opK3tprod!(
res,
id.nvar,
id.ncon,
id.ilow,
id.iupp,
id.nlow,
itd.x_m_lvar,
itd.uvar_m_x,
pt.s_l,
pt.s_u,
fd.Q,
fd.A,
ρv,
δv,
v,
α,
β,
fd.uplo,
),
)
rhs = similar(fd.c, id.nvar + id.ncon + id.nlow + id.nupp)
KS = init_Ksolver(K, rhs, sp)
return PreallocatedDataK3Krylov(
rhs,
sp.rhs_scale,
regu,
ρv,
δv,
K, #K
KS,
0,
T(sp.atol0),
T(sp.rtol0),
T(sp.atol_min),
T(sp.rtol_min),
sp.itmax,
)
end
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK3Krylov{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
if step == :aff
Δs_l = dda.Δs_l_aff
Δs_u = dda.Δs_u_aff
else
Δs_l = itd.Δs_l
Δs_u = itd.Δs_u
end
pad.rhs[1:(id.nvar + id.ncon)] .= dd
pad.rhs[(id.nvar + id.ncon + 1):(id.nvar + id.ncon + id.nlow)] .= Δs_l
pad.rhs[(id.nvar + id.ncon + id.nlow + 1):end] .= Δs_u
if pad.rhs_scale
rhsNorm = kscale!(pad.rhs)
end
(step !== :cc) && (pad.kiter = 0)
ksolve!(
pad.KS,
pad.K,
pad.rhs,
I,
verbose = 0,
atol = pad.atol,
rtol = pad.rtol,
itmax = pad.itmax,
)
update_kresiduals_history!(res, pad.K, pad.KS.x, pad.rhs)
pad.kiter += niterations(pad.KS)
if pad.rhs_scale
kunscale!(pad.KS.x, rhsNorm)
end
dd .= @views pad.KS.x[1:(id.nvar + id.ncon)]
Δs_l .= @views pad.KS.x[(id.nvar + id.ncon + 1):(id.nvar + id.ncon + id.nlow)]
Δs_u .= @views pad.KS.x[(id.nvar + id.ncon + id.nlow + 1):end]
return 0
end
function update_pad!(
pad::PreallocatedDataK3Krylov{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
update_krylov_tol!(pad)
pad.ρv[1] = pad.regu.ρ
pad.δv[1] = pad.regu.δ
# update_preconditioner!(pad.pdat, pad, itd, pt, id, fd, cnts)
return 0
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 7421 | # K3S
#
# [-Q - ρI Aᵀ I -I ][ Δx ] [ -rc ]
# [ A δI 0 0 ][ Δy ] [ -rb ]
# [ I 0 S_l⁻¹(X-L) 0 ][Δs_l2] = [-(x-l) + σμS_l⁻¹e]
# [ -I 0 0 S_u⁻¹(U-X) ][Δs_u2] [-(u-x) + σμS_u⁻¹e]
export K3SKrylovParams
"""
Type to use the K3S formulation with a Krylov method, using the package
[`Krylov.jl`](https://github.com/JuliaSmoothOptimizers/Krylov.jl).
The outer constructor
K3SKrylovParams(; uplo = :L, kmethod = :minres, preconditioner = Identity(),
rhs_scale = true,
atol0 = 1.0e-4, rtol0 = 1.0e-4,
atol_min = 1.0e-10, rtol_min = 1.0e-10,
ρ0 = sqrt(eps()) * 1e5, δ0 = sqrt(eps()) * 1e5,
ρ_min = 1e3 * sqrt(eps()), δ_min = 1e4 * sqrt(eps()),
itmax = 0, mem = 20)
creates a [`RipQP.SolverParams`](@ref).
The available methods are:
- `:minres`
- `:minres_qlp`
- `:symmlq`
"""
mutable struct K3SKrylovParams{T, PT} <: NewtonKrylovParams{T, PT}
uplo::Symbol
kmethod::Symbol
preconditioner::PT
rhs_scale::Bool
atol0::T
rtol0::T
atol_min::T
rtol_min::T
ρ0::T
δ0::T
ρ_min::T
δ_min::T
itmax::Int
mem::Int
end
function K3SKrylovParams{T}(;
uplo::Symbol = :L,
kmethod::Symbol = :minres,
preconditioner::AbstractPreconditioner = Identity(),
rhs_scale::Bool = true,
atol0::T = eps(T)^(1 / 4),
rtol0::T = eps(T)^(1 / 4),
atol_min::T = sqrt(eps(T)),
rtol_min::T = sqrt(eps(T)),
ρ0::T = T(sqrt(eps()) * 1e5),
δ0::T = T(sqrt(eps()) * 1e5),
ρ_min::T = T(1e2 * sqrt(eps())),
δ_min::T = T(1e2 * sqrt(eps())),
itmax::Int = 0,
mem::Int = 20,
) where {T <: Real}
return K3SKrylovParams(
uplo,
kmethod,
preconditioner,
rhs_scale,
atol0,
rtol0,
atol_min,
rtol_min,
ρ0,
δ0,
ρ_min,
δ_min,
itmax,
mem,
)
end
K3SKrylovParams(; kwargs...) = K3SKrylovParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK3SKrylov{
T <: Real,
S,
L <: LinearOperator,
Pr <: PreconditionerData,
Ksol <: KrylovSolver,
} <: PreallocatedDataNewtonKrylov{T, S}
pdat::Pr
rhs::S
rhs_scale::Bool
regu::Regularization{T}
ρv::Vector{T}
δv::Vector{T}
x_m_lvar_div_s_l::S
uvar_m_x_div_s_u::S
K::L # augmented matrix (LinearOperator)
KS::Ksol
kiter::Int
atol::T
rtol::T
atol_min::T
rtol_min::T
itmax::Int
end
function opK3Sprod!(
res::AbstractVector{T},
nvar::Int,
ncon::Int,
ilow::Vector{Int},
iupp::Vector{Int},
nlow::Int,
x_m_lvar_div_s_l::AbstractVector{T},
uvar_m_x_div_s_u::AbstractVector{T},
Q::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
A::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
ρv::AbstractVector{T},
δv::AbstractVector{T},
v::AbstractVector{T},
α::T,
β::T,
uplo::Symbol,
) where {T}
@views mul!(res[1:nvar], Q, v[1:nvar], -α, β)
res[1:nvar] .-= @views (α * ρv[1]) .* v[1:nvar]
@. res[ilow] += @views α * v[(nvar + ncon + 1):(nvar + ncon + nlow)]
@. res[iupp] -= @views α * v[(nvar + ncon + nlow + 1):end]
if uplo == :U
@views mul!(res[1:nvar], A, v[(nvar + 1):(nvar + ncon)], α, one(T))
@views mul!(res[(nvar + 1):(nvar + ncon)], A', v[1:nvar], α, β)
else
@views mul!(res[1:nvar], A', v[(nvar + 1):(nvar + ncon)], α, one(T))
@views mul!(res[(nvar + 1):(nvar + ncon)], A, v[1:nvar], α, β)
end
res[(nvar + 1):(nvar + ncon)] .+= @views (α * δv[1]) .* v[(nvar + 1):(nvar + ncon)]
if β == 0
@. res[(nvar + ncon + 1):(nvar + ncon + nlow)] =
@views α * (v[ilow] + x_m_lvar_div_s_l * v[(nvar + ncon + 1):(nvar + ncon + nlow)])
@. res[(nvar + ncon + nlow + 1):end] =
@views α * (-v[iupp] + uvar_m_x_div_s_u * v[(nvar + ncon + nlow + 1):end])
else
@. res[(nvar + ncon + 1):(nvar + ncon + nlow)] =
@views α * (v[ilow] + x_m_lvar_div_s_l * v[(nvar + ncon + 1):(nvar + ncon + nlow)]) +
β * res[(nvar + ncon + 1):(nvar + ncon + nlow)]
@. res[(nvar + ncon + nlow + 1):end] =
@views α * (-v[iupp] + uvar_m_x_div_s_u * v[(nvar + ncon + nlow + 1):end]) +
β * res[(nvar + ncon + nlow + 1):end]
end
end
function PreallocatedData(
sp::K3SKrylovParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
if iconf.mode == :mono
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), :classic)
else
regu =
Regularization(T(sp.ρ0), T(sp.δ0), T(sqrt(eps(T)) * 1e0), T(sqrt(eps(T)) * 1e0), :classic)
end
ρv = [regu.ρ]
δv = [regu.δ] # put it in a Vector so that we can modify it without modifying opK2prod!
x_m_lvar_div_s_l = itd.x_m_lvar ./ pt.s_l
uvar_m_x_div_s_u = itd.uvar_m_x ./ pt.s_u
K = LinearOperator(
T,
id.nvar + id.ncon + id.nlow + id.nupp,
id.nvar + id.ncon + id.nlow + id.nupp,
true,
true,
(res, v, α, β) -> opK3Sprod!(
res,
id.nvar,
id.ncon,
id.ilow,
id.iupp,
id.nlow,
x_m_lvar_div_s_l,
uvar_m_x_div_s_u,
fd.Q,
fd.A,
ρv,
δv,
v,
α,
β,
fd.uplo,
),
)
rhs = similar(fd.c, id.nvar + id.ncon + id.nlow + id.nupp)
KS = init_Ksolver(K, rhs, sp)
pdat = PreconditionerData(sp, id, fd, regu, K)
return PreallocatedDataK3SKrylov(
pdat,
rhs,
sp.rhs_scale,
regu,
ρv,
δv,
x_m_lvar_div_s_l,
uvar_m_x_div_s_u,
K, #K
KS,
0,
T(sp.atol0),
T(sp.rtol0),
T(sp.atol_min),
T(sp.rtol_min),
sp.itmax,
)
end
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK3SKrylov{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
if step == :aff
Δs_l = dda.Δs_l_aff
Δs_u = dda.Δs_u_aff
else
Δs_l = itd.Δs_l
Δs_u = itd.Δs_u
end
pad.rhs[1:(id.nvar + id.ncon)] .= dd
@. pad.rhs[(id.nvar + id.ncon + 1):(id.nvar + id.ncon + id.nlow)] = Δs_l / pt.s_l
@. pad.rhs[(id.nvar + id.ncon + id.nlow + 1):end] = Δs_u / pt.s_u
if pad.rhs_scale
rhsNorm = kscale!(pad.rhs)
end
(step !== :cc) && (pad.kiter = 0)
ksolve!(
pad.KS,
pad.K,
pad.rhs,
pad.pdat.P,
verbose = 0,
atol = pad.atol,
rtol = pad.rtol,
itmax = pad.itmax,
)
update_kresiduals_history!(res, pad.K, pad.KS.x, pad.rhs)
pad.kiter += niterations(pad.KS)
if pad.rhs_scale
kunscale!(pad.KS.x, rhsNorm)
end
dd .= @views pad.KS.x[1:(id.nvar + id.ncon)]
Δs_l .= @views pad.KS.x[(id.nvar + id.ncon + 1):(id.nvar + id.ncon + id.nlow)]
Δs_u .= @views pad.KS.x[(id.nvar + id.ncon + id.nlow + 1):end]
return 0
end
function update_pad!(
pad::PreallocatedDataK3SKrylov{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
update_krylov_tol!(pad)
pad.ρv[1] = pad.regu.ρ
pad.δv[1] = pad.regu.δ
@. pad.x_m_lvar_div_s_l = itd.x_m_lvar / pt.s_l
@. pad.uvar_m_x_div_s_u = itd.uvar_m_x / pt.s_u
update_preconditioner!(pad.pdat, pad, itd, pt, id, fd, cnts)
return 0
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 11170 | # K3S
#
# [-Q - ρI Aᵀ I -I ][ Δx ] [ -rc ]
# [ A δI 0 0 ][ Δy ] [ -rb ]
# [ I 0 S_l⁻¹(X-L) 0 ][Δs_l2] = [-(x-l) + σμS_l⁻¹e]
# [ -I 0 0 S_u⁻¹(U-X) ][Δs_u2] [-(u-x) + σμS_u⁻¹e]
export K3SStructuredParams
"""
Type to use the K3S formulation with a Krylov method, using the package
[`Krylov.jl`](https://github.com/JuliaSmoothOptimizers/Krylov.jl).
The outer constructor
K3SStructuredParams(; uplo = :U, kmethod = :trimr, rhs_scale = true,
atol0 = 1.0e-4, rtol0 = 1.0e-4,
atol_min = 1.0e-10, rtol_min = 1.0e-10,
ρ0 = sqrt(eps()) * 1e3, δ0 = sqrt(eps()) * 1e4,
ρ_min = 1e4 * sqrt(eps()), δ_min = 1e4 * sqrt(eps()),
itmax = 0, mem = 20)
creates a [`RipQP.SolverParams`](@ref).
The available methods are:
- `:tricg`
- `:trimr`
- `:gpmr`
The `mem` argument sould be used only with `gpmr`.
"""
mutable struct K3SStructuredParams{T} <: NewtonParams{T}
uplo::Symbol
kmethod::Symbol
rhs_scale::Bool
atol0::T
rtol0::T
atol_min::T
rtol_min::T
ρ0::T
δ0::T
ρ_min::T
δ_min::T
itmax::Int
mem::Int
end
function K3SStructuredParams{T}(;
uplo::Symbol = :U,
kmethod::Symbol = :trimr,
rhs_scale::Bool = true,
atol0::T = eps(T)^(1 / 4),
rtol0::T = eps(T)^(1 / 4),
atol_min::T = sqrt(eps(T)),
rtol_min::T = sqrt(eps(T)),
ρ0::T = T(sqrt(eps()) * 1e3),
δ0::T = T(sqrt(eps()) * 1e4),
ρ_min::T = T(1e4 * sqrt(eps())),
δ_min::T = T(1e4 * sqrt(eps())),
itmax::Int = 0,
mem::Int = 20,
) where {T <: Real}
return K3SStructuredParams(
uplo,
kmethod,
rhs_scale,
atol0,
rtol0,
atol_min,
rtol_min,
ρ0,
δ0,
ρ_min,
δ_min,
itmax,
mem,
)
end
K3SStructuredParams(; kwargs...) = K3SStructuredParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK3SStructured{
T <: Real,
S,
L1 <: LinearOperator,
L2 <: LinearOperator,
L3 <: LinearOperator,
Ksol <: KrylovSolver,
} <: PreallocatedDataNewtonKrylovStructured{T, S}
rhs1::S
rhs2::S
rhs_scale::Bool
regu::Regularization{T}
δv::Vector{T}
AI::L1
Qreg::AbstractMatrix{T} # regularized Q
QregF::LDLFactorizations.LDLFactorization{T, Int, Int, Int}
Qregop::L2 # factorized matrix Qreg
opBR::L3
KS::Ksol
kiter::Int
atol::T
rtol::T
atol_min::T
rtol_min::T
itmax::Int
end
function opAIprod!(
res::AbstractVector{T},
nvar::Int,
ncon::Int,
ilow::Vector{Int},
iupp::Vector{Int},
nlow::Int,
s_l::AbstractVector{T},
s_u::AbstractVector{T},
A::AbstractMatrix{T},
v::AbstractVector{T},
α::T,
β::T,
uplo::Symbol,
) where {T}
if β == 0
@. res[(ncon + 1):(ncon + nlow)] = @views α * v[ilow]
@. res[(ncon + nlow + 1):end] = @views -α * v[iupp]
else
@. res[(ncon + 1):(ncon + nlow)] = @views α * v[ilow] + β * res[(ncon + 1):(ncon + nlow)]
@. res[(ncon + nlow + 1):end] = @views -α * v[iupp] + β * res[(ncon + nlow + 1):end]
end
if uplo == :U
@views mul!(res[1:ncon], A', v, α, β)
else
@views mul!(res[1:ncon], A, v, α, β)
end
end
function opAItprod!(
res::AbstractVector{T},
nvar::Int,
ncon::Int,
ilow::Vector{Int},
iupp::Vector{Int},
nlow::Int,
s_l::AbstractVector{T},
s_u::AbstractVector{T},
A::AbstractMatrix{T},
v::AbstractVector{T},
α::T,
β::T,
uplo::Symbol,
) where {T}
if uplo == :U
@views mul!(res, A, v[1:ncon], α, β)
else
@views mul!(res, A', v[1:ncon], α, β)
end
@. res[ilow] += @views α * v[(ncon + 1):(ncon + nlow)]
@. res[iupp] -= @views α * v[(ncon + nlow + 1):end]
end
function opBRK3Sprod!(
res::AbstractVector{T},
ncon::Int,
nlow::Int,
x_m_lvar::AbstractVector{T},
uvar_m_x::AbstractVector{T},
s_l::AbstractVector{T},
s_u::AbstractVector{T},
δv::AbstractVector{T},
v::AbstractVector{T},
α::T,
β::T,
) where {T <: Real}
if β == zero(T)
res[1:ncon] .= @views (α / δv[1]) .* v[1:ncon]
@. res[(ncon + 1):(ncon + nlow)] = @views α * s_l / x_m_lvar * v[(ncon + 1):(ncon + nlow)]
@. res[(ncon + nlow + 1):end] = @views α * s_u / uvar_m_x * v[(ncon + nlow + 1):end]
else
res[1:ncon] .= @views (α / δv[1]) .* v[1:ncon] .+ β .* res[1:ncon]
@. res[(ncon + 1):(ncon + nlow)] =
@views α * s_l / x_m_lvar * v[(ncon + 1):(ncon + nlow)] + β * res[(ncon + 1):(ncon + nlow)]
@. res[(ncon + nlow + 1):end] =
@views α * s_u / uvar_m_x * v[(ncon + nlow + 1):end] + β * res[(ncon + nlow + 1):end]
end
end
function update_kresiduals_historyK3S!(
res::AbstractResiduals{T},
Qreg::AbstractMatrix{T},
AI::AbstractLinearOperator{T},
δ::T,
solx::AbstractVector{T},
soly::AbstractVector{T},
rhs1::AbstractVector{T},
rhs2::AbstractVector{T},
s_l::AbstractVector{T},
s_u::AbstractVector{T},
x_m_lvar::AbstractVector{T},
uvar_m_x::AbstractVector{T},
nvar::Int,
ncon::Int,
nlow::Int,
ilow::Vector{Int},
iupp::Vector{Int},
) where {T <: Real}
if typeof(res) <: ResidualsHistory
@views mul!(res.Kres[1:nvar], Symmetric(Qreg, :U), solx)
@views mul!(res.Kres[1:nvar], AI', soly, one(T), one(T))
@views mul!(res.Kres[(nvar + 1):end], AI, solx)
@. res.Kres[(nvar + 1):(nvar + ncon)] += @views δ * soly[1:ncon]
@. res.Kres[(nvar + ncon + 1):(nvar + ncon + nlow)] +=
@views solx[ilow] + x_m_lvar * soly[(ncon + 1):(ncon + nlow)] / s_l
@. res.Kres[(nvar + ncon + nlow + 1):end] +=
@views -solx[iupp] + uvar_m_x * soly[(ncon + nlow + 1):end] / s_u
res.Kres[1:nvar] .-= rhs1
res.Kres[(nvar + 1):end] .-= rhs2
end
end
function PreallocatedData(
sp::K3SStructuredParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
if iconf.mode == :mono
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), :classic)
else
regu =
Regularization(T(sp.ρ0), T(sp.δ0), T(sqrt(eps(T)) * 1e0), T(sqrt(eps(T)) * 1e0), :classic)
end
δv = [regu.δ] # put it in a Vector so that we can modify it without modifying opK2prod!
# LinearOperator to compute [A I -I] v
AI = LinearOperator(
T,
id.ncon + id.nlow + id.nupp,
id.nvar,
false,
false,
(res, v, α, β) -> opAIprod!(
res,
id.nvar,
id.ncon,
id.ilow,
id.iupp,
id.nlow,
pt.s_l,
pt.s_u,
fd.A,
v,
α,
β,
fd.uplo,
),
(res, v, α, β) -> opAItprod!(
res,
id.nvar,
id.ncon,
id.ilow,
id.iupp,
id.nlow,
pt.s_l,
pt.s_u,
fd.A,
v,
α,
β,
fd.uplo,
),
)
Qreg = fd.Q + regu.ρ_min * I
QregF = ldl(Symmetric(Qreg, :U))
rhs1 = similar(fd.c, id.nvar)
rhs2 = similar(fd.c, id.ncon + id.nlow + id.nupp)
kstring = string(sp.kmethod)
if sp.kmethod == :gpmr
# operator to model the square root of the inverse of Q
QregF.d .= sqrt.(QregF.d)
Qregop = LinearOperator(
T,
id.nvar,
id.nvar,
false,
false,
(res, v) -> ld_div!(res, QregF, v),
(res, v) -> dlt_div!(res, QregF, v),
)
# operator to model the square root of the inverse of the bottom right block of K3.5
opBR = LinearOperator(
T,
id.ncon + id.nlow + id.nupp,
id.ncon + id.nlow + id.nupp,
true,
true,
(res, v, α, β) -> opsqrtBRK3Sprod!(
res,
id.ncon,
id.nlow,
itd.x_m_lvar,
itd.uvar_m_x,
pt.s_l,
pt.s_u,
δv,
v,
α,
β,
),
)
else
# operator to model the inverse of Q
Qregop = LinearOperator(T, id.nvar, id.nvar, true, true, (res, v) -> ldiv!(res, QregF, v))
# operator to model the inverse of the bottom right block of K3.5
opBR = LinearOperator(
T,
id.ncon + id.nlow + id.nupp,
id.ncon + id.nlow + id.nupp,
true,
true,
(res, v, α, β) -> opBRK3Sprod!(
res,
id.ncon,
id.nlow,
itd.x_m_lvar,
itd.uvar_m_x,
pt.s_l,
pt.s_u,
δv,
v,
α,
β,
),
)
end
KS = init_Ksolver(AI', rhs1, sp)
return PreallocatedDataK3SStructured(
rhs1,
rhs2,
sp.rhs_scale,
regu,
δv,
AI,
Qreg,
QregF,
Qregop,
opBR,
KS,
0,
T(sp.atol0),
T(sp.rtol0),
T(sp.atol_min),
T(sp.rtol_min),
sp.itmax,
)
end
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK3SStructured{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
Δs_l = itd.Δs_l
Δs_u = itd.Δs_u
pad.rhs1 .= @views step == :init ? fd.c : dd[1:(id.nvar)]
if step == :init && all(pad.rhs1 .== zero(T))
pad.rhs1 .= one(T)
end
pad.rhs2[1:(id.ncon)] .=
@views (step == :init && all(dd[(id.nvar + 1):end] .== zero(T))) ? one(T) :
dd[(id.nvar + 1):end]
pad.rhs2[(id.ncon + 1):(id.ncon + id.nlow)] .= (step == :init) ? one(T) : Δs_l ./ pt.s_l
pad.rhs2[(id.ncon + id.nlow + 1):end] .= (step == :init) ? one(T) : Δs_u ./ pt.s_u
if pad.rhs_scale
rhsNorm = sqrt(norm(pad.rhs1)^2 + norm(pad.rhs2)^2)
pad.rhs1 ./= rhsNorm
pad.rhs2 ./= rhsNorm
end
(step !== :cc) && (pad.kiter = 0)
ksolve!(
pad.KS,
pad.AI',
pad.rhs1,
pad.rhs2,
pad.Qregop,
pad.opBR,
verbose = 0,
atol = pad.atol,
rtol = pad.rtol,
itmax = pad.itmax,
)
update_kresiduals_historyK3S!(
res,
pad.Qreg,
pad.AI,
pad.regu.δ,
pad.KS.x,
pad.KS.y,
pad.rhs1,
pad.rhs2,
pt.s_l,
pt.s_u,
itd.x_m_lvar,
itd.uvar_m_x,
id.nvar,
id.ncon,
id.nlow,
id.ilow,
id.iupp,
)
pad.kiter += niterations(pad.KS)
if pad.rhs_scale
kunscale!(pad.KS.x, rhsNorm)
kunscale!(pad.KS.y, rhsNorm)
end
dd[1:(id.nvar)] .= @views pad.KS.x
dd[(id.nvar + 1):end] .= @views pad.KS.y[1:(id.ncon)]
Δs_l .= @views pad.KS.y[(id.ncon + 1):(id.ncon + id.nlow)]
Δs_u .= @views pad.KS.y[(id.ncon + id.nlow + 1):end]
return 0
end
# function update_upper_Qreg!(Qreg, Q, ρ)
# n = size(Qreg, 1)
# nnzQ = nnz(Q)
# if nnzQ > 0
# for i=1:n
# diag_idx = Qreg.colptr[i+1] - 1
# ptrQ = Q.colptr[i+1] - 1
# Qreg.nzval[diag_idx] = (ptrQ ≤ nnzQ && Q.rowval[ptrQ] == i) ? Q.nzval[ptrQ] + ρ : ρ
# end
# end
# end
function update_pad!(
pad::PreallocatedDataK3SStructured{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
# if cnts.k == 4
# update_upper_Qreg!(pad.Qreg, fd.Q, pad.regu.ρ)
# pad.Qreg[diagind(pad.Qreg)] .= fd.Q[diagind(fd.Q)] .+ pad.regu.ρ
# ldl_factorize!(Symmetric(pad.Qreg, :U), pad.QregF)
# end
update_krylov_tol!(pad)
pad.δv[1] = pad.regu.δ
return 0
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 7391 | # K3.5 = D K3 D⁻¹ ,
# [ I 0 0 0 ]
# D² = [ 0 I 0 0 ]
# [ 0 0 S_l⁻¹ 0 ]
# [ 0 0 0 S_u⁻¹]
#
# [-Q - ρI Aᵀ √S_l -√S_u ][ Δx ] [ -rc ]
# [ A δI 0 0 ][ Δy ] [ -rb ]
# [ √S_l 0 X-L 0 ][Δs_l2] = D [σμe - (X-L)S_le]
# [ -√S_u 0 0 U-X ][Δs_u2] [σμe + (U-X)S_ue]
export K3_5KrylovParams
"""
Type to use the K3.5 formulation with a Krylov method, using the package
[`Krylov.jl`](https://github.com/JuliaSmoothOptimizers/Krylov.jl).
The outer constructor
K3_5KrylovParams(; uplo = :L, kmethod = :minres, preconditioner = Identity(),
rhs_scale = true,
atol0 = 1.0e-4, rtol0 = 1.0e-4,
atol_min = 1.0e-10, rtol_min = 1.0e-10,
ρ0 = sqrt(eps()) * 1e5, δ0 = sqrt(eps()) * 1e5,
ρ_min = 1e3 * sqrt(eps()), δ_min = 1e4 * sqrt(eps()),
itmax = 0, mem = 20)
creates a [`RipQP.SolverParams`](@ref).
The available methods are:
- `:minres`
- `:minres_qlp`
- `:symmlq`
"""
mutable struct K3_5KrylovParams{T, PT} <: NewtonKrylovParams{T, PT}
uplo::Symbol
kmethod::Symbol
preconditioner::PT
rhs_scale::Bool
atol0::T
rtol0::T
atol_min::T
rtol_min::T
ρ0::T
δ0::T
ρ_min::T
δ_min::T
itmax::Int
mem::Int
end
function K3_5KrylovParams{T}(;
uplo::Symbol = :L,
kmethod::Symbol = :minres,
preconditioner::AbstractPreconditioner = Identity(),
rhs_scale::Bool = true,
atol0::T = eps(T)^(1 / 4),
rtol0::T = eps(T)^(1 / 4),
atol_min::T = sqrt(eps(T)),
rtol_min::T = sqrt(eps(T)),
ρ0::T = eps(T)^(1 / 8),
δ0::T = eps(T)^(1 / 8),
ρ_min::T = T(1e3 * sqrt(eps())),
δ_min::T = T(1e4 * sqrt(eps())),
itmax::Int = 0,
mem::Int = 20,
) where {T <: Real}
return K3_5KrylovParams(
uplo,
kmethod,
preconditioner,
rhs_scale,
atol0,
rtol0,
atol_min,
rtol_min,
ρ0,
δ0,
ρ_min,
δ_min,
itmax,
mem,
)
end
K3_5KrylovParams(; kwargs...) = K3_5KrylovParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK3_5Krylov{
T <: Real,
S,
L <: LinearOperator,
Pr <: PreconditionerData,
Ksol <: KrylovSolver,
} <: PreallocatedDataNewtonKrylov{T, S}
pdat::Pr
rhs::S
rhs_scale::Bool
regu::Regularization{T}
ρv::Vector{T}
δv::Vector{T}
K::L # augmented matrix (LinearOperator)
KS::Ksol
kiter::Int
atol::T
rtol::T
atol_min::T
rtol_min::T
itmax::Int
end
function opK3_5prod!(
res::AbstractVector{T},
nvar::Int,
ncon::Int,
ilow::Vector{Int},
iupp::Vector{Int},
nlow::Int,
x_m_lvar::AbstractVector{T},
uvar_m_x::AbstractVector{T},
s_l::AbstractVector{T},
s_u::AbstractVector{T},
Q::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
A::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
ρv::AbstractVector{T},
δv::AbstractVector{T},
v::AbstractVector{T},
α::T,
β::T,
uplo::Symbol,
) where {T}
@views mul!(res[1:nvar], Q, v[1:nvar], -α, β)
res[1:nvar] .-= @views (α * ρv[1]) .* v[1:nvar]
@. res[ilow] += @views α * sqrt(s_l) * v[(nvar + ncon + 1):(nvar + ncon + nlow)]
@. res[iupp] -= @views α * sqrt(s_u) * v[(nvar + ncon + nlow + 1):end]
if uplo == :U
@views mul!(res[1:nvar], A, v[(nvar + 1):(nvar + ncon)], α, one(T))
@views mul!(res[(nvar + 1):(nvar + ncon)], A', v[1:nvar], α, β)
else
@views mul!(res[1:nvar], A', v[(nvar + 1):(nvar + ncon)], α, one(T))
@views mul!(res[(nvar + 1):(nvar + ncon)], A, v[1:nvar], α, β)
end
res[(nvar + 1):(nvar + ncon)] .+= @views (α * δv[1]) .* v[(nvar + 1):(nvar + ncon)]
if β == 0
@. res[(nvar + ncon + 1):(nvar + ncon + nlow)] =
@views α * (sqrt(s_l) * v[ilow] + x_m_lvar * v[(nvar + ncon + 1):(nvar + ncon + nlow)])
@. res[(nvar + ncon + nlow + 1):end] =
@views α * (-sqrt(s_u) * v[iupp] + uvar_m_x * v[(nvar + ncon + nlow + 1):end])
else
@. res[(nvar + ncon + 1):(nvar + ncon + nlow)] =
@views α * (sqrt(s_l) * v[ilow] + x_m_lvar * v[(nvar + ncon + 1):(nvar + ncon + nlow)]) +
β * res[(nvar + ncon + 1):(nvar + ncon + nlow)]
@. res[(nvar + ncon + nlow + 1):end] =
@views α * (-sqrt(s_u) * v[iupp] + uvar_m_x * v[(nvar + ncon + nlow + 1):end]) +
β * res[(nvar + ncon + nlow + 1):end]
end
end
function PreallocatedData(
sp::K3_5KrylovParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
if iconf.mode == :mono
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), :classic)
else
regu =
Regularization(T(sp.ρ0), T(sp.δ0), T(sqrt(eps(T)) * 1e0), T(sqrt(eps(T)) * 1e0), :classic)
end
ρv = [regu.ρ]
δv = [regu.δ] # put it in a Vector so that we can modify it without modifying opK2prod!
K = LinearOperator(
T,
id.nvar + id.ncon + id.nlow + id.nupp,
id.nvar + id.ncon + id.nlow + id.nupp,
true,
true,
(res, v, α, β) -> opK3_5prod!(
res,
id.nvar,
id.ncon,
id.ilow,
id.iupp,
id.nlow,
itd.x_m_lvar,
itd.uvar_m_x,
pt.s_l,
pt.s_u,
fd.Q,
fd.A,
ρv,
δv,
v,
α,
β,
fd.uplo,
),
)
rhs = similar(fd.c, id.nvar + id.ncon + id.nlow + id.nupp)
KS = init_Ksolver(K, rhs, sp)
pdat = PreconditionerData(sp, id, fd, regu, K)
return PreallocatedDataK3_5Krylov(
pdat,
rhs,
sp.rhs_scale,
regu,
ρv,
δv,
K, #K
KS,
0,
T(sp.atol0),
T(sp.rtol0),
T(sp.atol_min),
T(sp.rtol_min),
sp.itmax,
)
end
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK3_5Krylov{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
if step == :aff
Δs_l = dda.Δs_l_aff
Δs_u = dda.Δs_u_aff
else
Δs_l = itd.Δs_l
Δs_u = itd.Δs_u
end
pad.rhs[1:(id.nvar + id.ncon)] .= dd
@. pad.rhs[(id.nvar + id.ncon + 1):(id.nvar + id.ncon + id.nlow)] = Δs_l / sqrt(pt.s_l)
@. pad.rhs[(id.nvar + id.ncon + id.nlow + 1):end] = Δs_u / sqrt(pt.s_u)
if pad.rhs_scale
rhsNorm = kscale!(pad.rhs)
end
(step !== :cc) && (pad.kiter = 0)
ksolve!(
pad.KS,
pad.K,
pad.rhs,
pad.pdat.P,
verbose = 0,
atol = pad.atol,
rtol = pad.rtol,
itmax = pad.itmax,
)
update_kresiduals_history!(res, pad.K, pad.KS.x, pad.rhs)
pad.kiter += niterations(pad.KS)
if pad.rhs_scale
kunscale!(pad.KS.x, rhsNorm)
end
dd .= @views pad.KS.x[1:(id.nvar + id.ncon)]
@. Δs_l = @views pad.KS.x[(id.nvar + id.ncon + 1):(id.nvar + id.ncon + id.nlow)] * sqrt(pt.s_l)
@. Δs_u = @views pad.KS.x[(id.nvar + id.ncon + id.nlow + 1):end] * sqrt(pt.s_u)
return 0
end
function update_pad!(
pad::PreallocatedDataK3_5Krylov{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
update_krylov_tol!(pad)
pad.ρv[1] = pad.regu.ρ
pad.δv[1] = pad.regu.δ
update_preconditioner!(pad.pdat, pad, itd, pt, id, fd, cnts)
return 0
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 11084 | # K3.5 = D K3 D⁻¹ ,
# [ I 0 0 0 ]
# D² = [ 0 I 0 0 ]
# [ 0 0 S_l⁻¹ 0 ]
# [ 0 0 0 S_u⁻¹]
#
# [-Q - ρI Aᵀ √S_l -√S_u ][ Δx ] [ -rc ]
# [ A δI 0 0 ][ Δy ] [ -rb ]
# [ √S_l 0 X-L 0 ][Δs_l2] = D [σμe - (X-L)S_le]
# [ -√S_u 0 0 U-X ][Δs_u2] [σμe + (U-X)S_ue]
export K3_5StructuredParams
"""
Type to use the K3.5 formulation with a Krylov method, using the package
[`Krylov.jl`](https://github.com/JuliaSmoothOptimizers/Krylov.jl).
The outer constructor
K3_5StructuredParams(; uplo = :U, kmethod = :trimr, rhs_scale = true,
atol0 = 1.0e-4, rtol0 = 1.0e-4,
atol_min = 1.0e-10, rtol_min = 1.0e-10,
ρ0 = sqrt(eps()) * 1e3, δ0 = sqrt(eps()) * 1e4,
ρ_min = 1e4 * sqrt(eps()), δ_min = 1e4 * sqrt(eps()),
itmax = 0, mem = 20)
creates a [`RipQP.SolverParams`](@ref).
The available methods are:
- `:tricg`
- `:trimr`
- `:gpmr`
The `mem` argument sould be used only with `gpmr`.
"""
mutable struct K3_5StructuredParams{T} <: NewtonParams{T}
uplo::Symbol
kmethod::Symbol
rhs_scale::Bool
atol0::T
rtol0::T
atol_min::T
rtol_min::T
ρ0::T
δ0::T
ρ_min::T
δ_min::T
itmax::Int
mem::Int
end
function K3_5StructuredParams{T}(;
uplo::Symbol = :U,
kmethod::Symbol = :trimr,
rhs_scale::Bool = true,
atol0::T = eps(T)^(1 / 4),
rtol0::T = eps(T)^(1 / 4),
atol_min::T = 1.0e-10,
rtol_min::T = 1.0e-10,
ρ0::T = T(sqrt(eps()) * 1e3),
δ0::T = T(sqrt(eps()) * 1e4),
ρ_min::T = T(1e4 * sqrt(eps())),
δ_min::T = T(1e4 * sqrt(eps())),
itmax::Int = 0,
mem::Int = 20,
) where {T <: Real}
return K3_5StructuredParams(
uplo,
kmethod,
rhs_scale,
atol0,
rtol0,
atol_min,
rtol_min,
ρ0,
δ0,
ρ_min,
δ_min,
itmax,
mem,
)
end
K3_5StructuredParams(; kwargs...) = K3_5StructuredParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK3_5Structured{
T <: Real,
S,
L1 <: LinearOperator,
L2 <: LinearOperator,
L3 <: LinearOperator,
Ksol <: KrylovSolver,
} <: PreallocatedDataNewtonKrylovStructured{T, S}
rhs1::S
rhs2::S
rhs_scale::Bool
regu::Regularization{T}
δv::Vector{T}
As::L1
Qreg::AbstractMatrix{T} # regularized Q
QregF::LDLFactorizations.LDLFactorization{T, Int, Int, Int}
Qregop::L2 # factorized matrix Qreg
opBR::L3
KS::Ksol
kiter::Int
atol::T
rtol::T
atol_min::T
rtol_min::T
itmax::Int
end
function opAsprod!(
res::AbstractVector{T},
nvar::Int,
ncon::Int,
ilow::Vector{Int},
iupp::Vector{Int},
nlow::Int,
s_l::AbstractVector{T},
s_u::AbstractVector{T},
A::AbstractMatrix{T},
v::AbstractVector{T},
α::T,
β::T,
uplo::Symbol,
) where {T}
if β == 0
@. res[(ncon + 1):(ncon + nlow)] = @views α * sqrt(s_l) * v[ilow]
@. res[(ncon + nlow + 1):end] = @views -α * sqrt(s_u) * v[iupp]
else
@. res[(ncon + 1):(ncon + nlow)] =
@views α * sqrt(s_l) * v[ilow] + β * res[(ncon + 1):(ncon + nlow)]
@. res[(ncon + nlow + 1):end] = @views -α * sqrt(s_u) * v[iupp] + β * res[(ncon + nlow + 1):end]
end
if uplo == :U
@views mul!(res[1:ncon], A', v, α, β)
else
@views mul!(res[1:ncon], A, v, α, β)
end
end
function opAstprod!(
res::AbstractVector{T},
nvar::Int,
ncon::Int,
ilow::Vector{Int},
iupp::Vector{Int},
nlow::Int,
s_l::AbstractVector{T},
s_u::AbstractVector{T},
A::AbstractMatrix{T},
v::AbstractVector{T},
α::T,
β::T,
uplo::Symbol,
) where {T}
if uplo == :U
@views mul!(res, A, v[1:ncon], α, β)
else
@views mul!(res, A', v[1:ncon], α, β)
end
@. res[ilow] += @views α * sqrt(s_l) * v[(ncon + 1):(ncon + nlow)]
@. res[iupp] -= @views α * sqrt(s_u) * v[(ncon + nlow + 1):end]
end
function opBRK3_5prod!(
res::AbstractVector{T},
ncon::Int,
nlow::Int,
x_m_lvar::AbstractVector{T},
uvar_m_x::AbstractVector{T},
δv::AbstractVector{T},
v::AbstractVector{T},
α::T,
β::T,
) where {T <: Real}
if β == zero(T)
res[1:ncon] .= @views (α / δv[1]) .* v[1:ncon]
@. res[(ncon + 1):(ncon + nlow)] = @views α / x_m_lvar * v[(ncon + 1):(ncon + nlow)]
@. res[(ncon + nlow + 1):end] = @views α / uvar_m_x * v[(ncon + nlow + 1):end]
else
res[1:ncon] .= @views (α / δv[1]) .* v[1:ncon] .+ β .* res[1:ncon]
@. res[(ncon + 1):(ncon + nlow)] =
@views α / x_m_lvar * v[(ncon + 1):(ncon + nlow)] + β * res[(ncon + 1):(ncon + nlow)]
@. res[(ncon + nlow + 1):end] =
@views α / uvar_m_x * v[(ncon + nlow + 1):end] + β * res[(ncon + nlow + 1):end]
end
end
function update_kresiduals_history!(
res::AbstractResiduals{T},
Qreg::AbstractMatrix{T},
As::AbstractLinearOperator{T},
δ::T,
solx::AbstractVector{T},
soly::AbstractVector{T},
rhs1::AbstractVector{T},
rhs2::AbstractVector{T},
s_l::AbstractVector{T},
s_u::AbstractVector{T},
x_m_lvar::AbstractVector{T},
uvar_m_x::AbstractVector{T},
nvar::Int,
ncon::Int,
nlow::Int,
ilow::Vector{Int},
iupp::Vector{Int},
) where {T <: Real}
if typeof(res) <: ResidualsHistory
@views mul!(res.Kres[1:nvar], Symmetric(Qreg, :U), solx)
@views mul!(res.Kres[1:nvar], As', soly, one(T), one(T))
@views mul!(res.Kres[(nvar + 1):end], As, solx)
@. res.Kres[(nvar + 1):(nvar + ncon)] += @views δ * soly[1:ncon]
@. res.Kres[(nvar + ncon + 1):(nvar + ncon + nlow)] +=
@views s_l * solx[ilow] + x_m_lvar * soly[(ncon + 1):(ncon + nlow)]
@. res.Kres[(nvar + ncon + nlow + 1):end] +=
@views -s_u * solx[iupp] + uvar_m_x * soly[(ncon + nlow + 1):end]
res.Kres[1:nvar] .-= rhs1
res.Kres[(nvar + 1):end] .-= rhs2
end
end
function PreallocatedData(
sp::K3_5StructuredParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
if iconf.mode == :mono
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), :classic)
else
regu =
Regularization(T(sp.ρ0), T(sp.δ0), T(sqrt(eps(T)) * 1e0), T(sqrt(eps(T)) * 1e0), :classic)
end
δv = [regu.δ] # put it in a Vector so that we can modify it without modifying opK2prod!
# LinearOperator to compute [A √S_l -√S_u] v
As = LinearOperator(
T,
id.ncon + id.nlow + id.nupp,
id.nvar,
false,
false,
(res, v, α, β) -> opAsprod!(
res,
id.nvar,
id.ncon,
id.ilow,
id.iupp,
id.nlow,
pt.s_l,
pt.s_u,
fd.A,
v,
α,
β,
fd.uplo,
),
(res, v, α, β) -> opAstprod!(
res,
id.nvar,
id.ncon,
id.ilow,
id.iupp,
id.nlow,
pt.s_l,
pt.s_u,
fd.A,
v,
α,
β,
fd.uplo,
),
)
Qreg = fd.Q + regu.ρ_min * I
QregF = ldl(Symmetric(Qreg, :U))
rhs1 = similar(fd.c, id.nvar)
rhs2 = similar(fd.c, id.ncon + id.nlow + id.nupp)
if sp.kmethod == :gpmr
# operator to model the square root of the inverse of Q
QregF.d .= sqrt.(QregF.d)
Qregop = LinearOperator(
T,
id.nvar,
id.nvar,
false,
false,
(res, v) -> ld_div!(res, QregF, v),
(res, v) -> dlt_div!(res, QregF, v),
)
# operator to model the square root of the inverse of the bottom right block of K3.5
opBR = LinearOperator(
T,
id.ncon + id.nlow + id.nupp,
id.ncon + id.nlow + id.nupp,
true,
true,
(res, v, α, β) ->
opsqrtBRK3_5prod!(res, id.ncon, id.nlow, itd.x_m_lvar, itd.uvar_m_x, δv, v, α, β),
)
else
# operator to model the inverse of Q
Qregop = LinearOperator(T, id.nvar, id.nvar, true, true, (res, v) -> ldiv!(res, QregF, v))
# operator to model the inverse of the bottom right block of K3.5
opBR = LinearOperator(
T,
id.ncon + id.nlow + id.nupp,
id.ncon + id.nlow + id.nupp,
true,
true,
(res, v, α, β) ->
opBRK3_5prod!(res, id.ncon, id.nlow, itd.x_m_lvar, itd.uvar_m_x, δv, v, α, β),
)
end
KS = init_Ksolver(As', rhs1, sp)
return PreallocatedDataK3_5Structured(
rhs1,
rhs2,
sp.rhs_scale,
regu,
δv,
As,
Qreg,
QregF,
Qregop,
opBR,
KS,
0,
T(sp.atol0),
T(sp.rtol0),
T(sp.atol_min),
T(sp.rtol_min),
sp.itmax,
)
end
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK3_5Structured{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
Δs_l = itd.Δs_l
Δs_u = itd.Δs_u
pad.rhs1 .= @views step == :init ? fd.c : dd[1:(id.nvar)]
if step == :init && all(pad.rhs1 .== zero(T))
pad.rhs1 .= one(T)
end
pad.rhs2[1:(id.ncon)] .=
@views (step == :init && all(dd[(id.nvar + 1):end] .== zero(T))) ? one(T) :
dd[(id.nvar + 1):end]
pad.rhs2[(id.ncon + 1):(id.ncon + id.nlow)] .= (step == :init) ? one(T) : Δs_l ./ sqrt.(pt.s_l)
pad.rhs2[(id.ncon + id.nlow + 1):end] .= (step == :init) ? one(T) : Δs_u ./ sqrt.(pt.s_u)
if pad.rhs_scale
rhsNorm = sqrt(norm(pad.rhs1)^2 + norm(pad.rhs2)^2)
pad.rhs1 ./= rhsNorm
pad.rhs2 ./= rhsNorm
end
(step !== :cc) && (pad.kiter = 0)
ksolve!(
pad.KS,
pad.As',
pad.rhs1,
pad.rhs2,
pad.Qregop,
pad.opBR,
verbose = 0,
atol = pad.atol,
rtol = pad.rtol,
itmax = pad.itmax,
)
update_kresiduals_history!(
res,
pad.Qreg,
pad.As,
pad.regu.δ,
pad.KS.x,
pad.KS.y,
pad.rhs1,
pad.rhs2,
pt.s_l,
pt.s_u,
itd.x_m_lvar,
itd.uvar_m_x,
id.nvar,
id.ncon,
id.nlow,
id.ilow,
id.iupp,
)
pad.kiter += niterations(pad.KS)
if pad.rhs_scale
kunscale!(pad.KS.x, rhsNorm)
kunscale!(pad.KS.y, rhsNorm)
end
dd[1:(id.nvar)] .= @views pad.KS.x
dd[(id.nvar + 1):end] .= @views pad.KS.y[1:(id.ncon)]
@. Δs_l = @views pad.KS.y[(id.ncon + 1):(id.ncon + id.nlow)] * sqrt(pt.s_l)
@. Δs_u = @views pad.KS.y[(id.ncon + id.nlow + 1):end] * sqrt(pt.s_u)
return 0
end
# function update_upper_Qreg!(Qreg, Q, ρ)
# n = size(Qreg, 1)
# nnzQ = nnz(Q)
# if nnzQ > 0
# for i=1:n
# diag_idx = Qreg.colptr[i+1] - 1
# ptrQ = Q.colptr[i+1] - 1
# Qreg.nzval[diag_idx] = (ptrQ ≤ nnzQ && Q.rowval[ptrQ] == i) ? Q.nzval[ptrQ] + ρ : ρ
# end
# end
# end
function update_pad!(
pad::PreallocatedDataK3_5Structured{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
# if cnts.k == 4
# update_upper_Qreg!(pad.Qreg, fd.Q, pad.regu.ρ)
# pad.Qreg[diagind(pad.Qreg)] .= fd.Q[diagind(fd.Q)] .+ pad.regu.ρ
# ldl_factorize!(Symmetric(pad.Qreg, :U), pad.QregF)
# end
update_krylov_tol!(pad)
pad.δv[1] = pad.regu.δ
return 0
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 2898 | function ld_solve!(n, b::AbstractVector, Lp, Li, Lx, D, P)
@views y = b[P]
LDLFactorizations.ldl_lsolve!(n, y, Lp, Li, Lx)
LDLFactorizations.ldl_dsolve!(n, y, D)
return b
end
function dlt_solve!(n, b::AbstractVector, Lp, Li, Lx, D, P)
@views y = b[P]
LDLFactorizations.ldl_dsolve!(n, y, D)
LDLFactorizations.ldl_ltsolve!(n, y, Lp, Li, Lx)
return b
end
function ld_div!(
y::AbstractVector{T},
LDL::LDLFactorizations.LDLFactorization{Tf, Ti, Tn, Tp},
b::AbstractVector{T},
) where {T <: Real, Tf <: Real, Ti <: Integer, Tn <: Integer, Tp <: Integer}
y .= b
LDL.__factorized || throw(LDLFactorizations.SQDException(error_string))
ld_solve!(LDL.n, y, LDL.Lp, LDL.Li, LDL.Lx, LDL.d, LDL.P)
end
function dlt_div!(
y::AbstractVector{T},
LDL::LDLFactorizations.LDLFactorization{Tf, Ti, Tn, Tp},
b::AbstractVector{T},
) where {T <: Real, Tf <: Real, Ti <: Integer, Tn <: Integer, Tp <: Integer}
y .= b
LDL.__factorized || throw(LDLFactorizations.SQDException(error_string))
dlt_solve!(LDL.n, y, LDL.Lp, LDL.Li, LDL.Lx, LDL.d, LDL.P)
end
function opsqrtBRK3_5prod!(
res::AbstractVector{T},
ncon::Int,
nlow::Int,
x_m_lvar::AbstractVector{T},
uvar_m_x::AbstractVector{T},
δv::AbstractVector{T},
v::AbstractVector{T},
α::T,
β::T,
) where {T <: Real}
if β == zero(T)
res[1:ncon] .= @views (α / sqrt(δv[1])) .* v[1:ncon]
@. res[(ncon + 1):(ncon + nlow)] = @views α / sqrt(x_m_lvar) * v[(ncon + 1):(ncon + nlow)]
@. res[(ncon + nlow + 1):end] = @views α / sqrt(uvar_m_x) * v[(ncon + nlow + 1):end]
else
res[1:ncon] .= @views (α / sqrt.(δv[1])) .* v[1:ncon] .+ β .* res[1:ncon]
@. res[(ncon + 1):(ncon + nlow)] =
@views α / sqrt(x_m_lvar) * v[(ncon + 1):(ncon + nlow)] + β * res[(ncon + 1):(ncon + nlow)]
@. res[(ncon + nlow + 1):end] .=
@views α / sqrt(uvar_m_x) * v[(ncon + nlow + 1):end] + β * res[(ncon + nlow + 1):end]
end
end
function opsqrtBRK3Sprod!(
res::AbstractVector{T},
ncon::Int,
nlow::Int,
x_m_lvar::AbstractVector{T},
uvar_m_x::AbstractVector{T},
s_l::AbstractVector{T},
s_u::AbstractVector{T},
δv::AbstractVector{T},
v::AbstractVector{T},
α::T,
β::T,
) where {T <: Real}
if β == zero(T)
res[1:ncon] .= @views (α / sqrt.(δv[1])) .* v[1:ncon]
@. res[(ncon + 1):(ncon + nlow)] =
@views α * sqrt(s_l) / sqrt(x_m_lvar) * v[(ncon + 1):(ncon + nlow)]
@. res[(ncon + nlow + 1):end] = @views α * sqrt(s_u) / sqrt(uvar_m_x) * v[(ncon + nlow + 1):end]
else
res[1:ncon] .= @views (α / sqrt.(δv[1])) .* v[1:ncon] .+ β .* res[1:ncon]
@. res[(ncon + 1):(ncon + nlow)] =
@views α * sqrt(s_l) / sqrt(x_m_lvar) * v[(ncon + 1):(ncon + nlow)] +
β * res[(ncon + 1):(ncon + nlow)]
@. res[(ncon + nlow + 1):end] =
@views α * sqrt(s_u) / sqrt(uvar_m_x) * v[(ncon + nlow + 1):end] +
β * res[(ncon + nlow + 1):end]
end
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 659 | abstract type NewtonParams{T} <: SolverParams{T} end
abstract type NewtonKrylovParams{T, PT <: AbstractPreconditioner} <: NewtonParams{T} end
abstract type PreallocatedDataNewton{T <: Real, S} <: PreallocatedData{T, S} end
abstract type PreallocatedDataNewtonKrylov{T <: Real, S} <: PreallocatedDataNewton{T, S} end
uses_krylov(pad::PreallocatedDataNewtonKrylov) = true
abstract type PreallocatedDataNewtonKrylovStructured{T <: Real, S} <: PreallocatedDataNewton{T, S} end
include("K3Krylov.jl")
include("K3SKrylov.jl")
include("K3_5Krylov.jl")
# utils for K3_5 gpmr
include("K3_5gpmr_utils.jl")
include("K3SStructured.jl")
include("K3_5Structured.jl")
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 7792 | export K2KrylovParams
"""
Type to use the K2 formulation with a Krylov method, using the package
[`Krylov.jl`](https://github.com/JuliaSmoothOptimizers/Krylov.jl).
The outer constructor
K2KrylovParams(; uplo = :L, kmethod = :minres, preconditioner = Identity(),
rhs_scale = true, form_mat = false, equilibrate = false,
atol0 = 1.0e-4, rtol0 = 1.0e-4,
atol_min = 1.0e-10, rtol_min = 1.0e-10,
ρ0 = sqrt(eps()) * 1e5, δ0 = sqrt(eps()) * 1e5,
ρ_min = 1e2 * sqrt(eps()), δ_min = 1e2 * sqrt(eps()),
itmax = 0, memory = 20)
creates a [`RipQP.SolverParams`](@ref).
"""
mutable struct K2KrylovParams{T, PT, FT <: DataType} <: AugmentedKrylovParams{T, PT}
uplo::Symbol
kmethod::Symbol
preconditioner::PT
rhs_scale::Bool
form_mat::Bool
equilibrate::Bool
atol0::T
rtol0::T
atol_min::T
rtol_min::T
ρ0::T
δ0::T
ρ_min::T
δ_min::T
itmax::Int
mem::Int
Tir::FT
end
function K2KrylovParams{T}(;
uplo::Symbol = :L,
kmethod::Symbol = :minres,
preconditioner::AbstractPreconditioner = Identity(),
rhs_scale::Bool = true,
form_mat::Bool = false,
equilibrate::Bool = false,
atol0::T = T(eps(T)^(1 / 4)),
rtol0::T = T(eps(T)^(1 / 4)),
atol_min::T = sqrt(eps(T)),
rtol_min::T = sqrt(eps(T)),
ρ0::T = T(sqrt(eps()) * 1e5),
δ0::T = T(sqrt(eps()) * 1e5),
ρ_min::T = T(1e2 * sqrt(eps(T))),
δ_min::T = T(1e2 * sqrt(eps(T))),
itmax::Int = 0,
mem::Int = 20,
Tir::DataType = T,
) where {T <: Real}
if equilibrate && !form_mat
error("use form_mat = true to use equilibration")
end
if typeof(preconditioner) <: LDL
if !form_mat
form_mat = true
@info "changed form_mat to true to use this preconditioner"
end
uplo_fact = get_uplo(preconditioner.fact_alg)
if uplo != uplo_fact
uplo = uplo_fact
@info "changed uplo to :$uplo_fact to use this preconditioner"
end
end
return K2KrylovParams(
uplo,
kmethod,
preconditioner,
rhs_scale,
form_mat,
equilibrate,
atol0,
rtol0,
atol_min,
rtol_min,
ρ0,
δ0,
ρ_min,
δ_min,
itmax,
mem,
Tir,
)
end
K2KrylovParams(; kwargs...) = K2KrylovParams{Float64}(; kwargs...)
mutable struct MatrixTools{T}
diag_Q::SparseVector{T, Int} # Q diag
diagind_K::Vector{Int}
Deq::Diagonal{T, Vector{T}}
C_eq::Diagonal{T, Vector{T}}
end
convert(::Type{MatrixTools{T}}, mt::MatrixTools) where {T} = MatrixTools(
convert(SparseVector{T, Int}, mt.diag_Q),
mt.diagind_K,
Diagonal(convert(Vector{T}, mt.Deq.diag)),
Diagonal(convert(Vector{T}, mt.C_eq.diag)),
)
mutable struct PreallocatedDataK2Krylov{
T <: Real,
S,
M <: Union{LinearOperator{T}, AbstractMatrix{T}},
MT <: Union{MatrixTools{T}, Int},
Pr <: PreconditionerData,
Ksol <: KrylovSolver,
} <: PreallocatedDataAugmentedKrylov{T, S}
pdat::Pr
D::S # temporary top-left diagonal
rhs::S
rhs_scale::Bool
equilibrate::Bool
regu::Regularization{T}
δv::Vector{T}
K::M # augmented matrix
mt::MT
KS::Ksol
kiter::Int
atol::T
rtol::T
atol_min::T
rtol_min::T
itmax::Int
end
function opK2prod!(
res::AbstractVector{T},
nvar::Int,
Q::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
D::AbstractVector{T},
A::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
δv::AbstractVector{T},
v::AbstractVector{T},
α::T,
β::T,
uplo::Symbol,
) where {T}
@views mul!(res[1:nvar], Q, v[1:nvar], -α, β)
@. res[1:nvar] += @views α * D * v[1:nvar]
if uplo == :U
@views mul!(res[1:nvar], A, v[(nvar + 1):end], α, one(T))
@views mul!(res[(nvar + 1):end], A', v[1:nvar], α, β)
else
@views mul!(res[1:nvar], A', v[(nvar + 1):end], α, one(T))
@views mul!(res[(nvar + 1):end], A, v[1:nvar], α, β)
end
res[(nvar + 1):end] .+= @views (α * δv[1]) .* v[(nvar + 1):end]
end
function PreallocatedData(
sp::K2KrylovParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
D = similar(fd.c, id.nvar)
if iconf.mode == :mono
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), :classic)
D .= -T(1.0e0) / 2
else
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), :hybrid)
D .= -T(1.0e-2)
end
δv = [regu.δ] # put it in a Vector so that we can modify it without modifying opK2prod!
if sp.form_mat
K, diagind_K, diag_Q = get_K2_matrixdata(id, D, fd.Q, fd.A, regu, sp.uplo, T)
if sp.equilibrate
Deq = Diagonal(Vector{T}(undef, id.nvar + id.ncon))
Deq.diag .= one(T)
C_eq = Diagonal(Vector{T}(undef, id.nvar + id.ncon))
else
Deq = Diagonal(Vector{T}(undef, 0))
C_eq = Diagonal(Vector{T}(undef, 0))
end
mt = MatrixTools(diag_Q, diagind_K, Deq, C_eq)
else
K = LinearOperator(
T,
id.nvar + id.ncon,
id.nvar + id.ncon,
true,
true,
(res, v, α, β) -> opK2prod!(res, id.nvar, fd.Q, D, fd.A, δv, v, α, β, fd.uplo),
)
mt = 0
end
rhs = similar(fd.c, id.nvar + id.ncon)
KS = @timeit_debug to "krylov solver setup" init_Ksolver(K, rhs, sp)
pdat = @timeit_debug to "preconditioner setup" PreconditionerData(sp, id, fd, regu, D, K)
return PreallocatedDataK2Krylov(
pdat,
D,
rhs,
sp.rhs_scale,
sp.equilibrate,
regu,
δv,
K, #K
mt,
KS,
0,
T(sp.atol0),
T(sp.rtol0),
T(sp.atol_min),
T(sp.rtol_min),
sp.itmax,
)
end
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK2Krylov{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
pad.rhs .= pad.equilibrate ? dd .* pad.mt.Deq.diag : dd
if pad.rhs_scale
rhsNorm = kscale!(pad.rhs)
end
if step !== :cc
out = @timeit_debug to "preconditioner update" update_preconditioner!(
pad.pdat,
pad,
itd,
pt,
id,
fd,
cnts,
)
pad.kiter = 0
out == 1 && return out
end
@timeit_debug to "Krylov solve" ksolve!(
pad.KS,
pad.K,
pad.rhs,
pad.pdat.P,
verbose = 0,
atol = pad.atol,
rtol = pad.rtol,
itmax = pad.itmax,
)
pad.kiter += niterations(pad.KS)
update_kresiduals_history!(res, pad.K, pad.KS.x, pad.rhs)
if pad.rhs_scale
kunscale!(pad.KS.x, rhsNorm)
end
if pad.equilibrate
if typeof(pad.K) <: Symmetric{T, <:Union{SparseMatrixCSC{T}, SparseMatrixCOO{T}}} &&
step !== :aff
rdiv!(pad.K.data, pad.mt.Deq)
ldiv!(pad.mt.Deq, pad.K.data)
end
pad.KS.x .*= pad.mt.Deq.diag
end
dd .= pad.KS.x
return 0
end
function update_pad!(
pad::PreallocatedDataK2Krylov{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
update_krylov_tol!(pad)
update_D!(pad.D, itd.x_m_lvar, itd.uvar_m_x, pt.s_l, pt.s_u, pad.regu.ρ, id.ilow, id.iupp)
pad.δv[1] = pad.regu.δ
if typeof(pad.K) <: Symmetric{T, <:Union{SparseMatrixCSC{T}, SparseMatrixCOO{T}}}
pad.D[pad.mt.diag_Q.nzind] .-= pad.mt.diag_Q.nzval
update_diag_K11!(pad.K, pad.D, pad.mt.diagind_K, id.nvar)
update_diag_K22!(pad.K, pad.regu.δ, pad.mt.diagind_K, id.nvar, id.ncon)
if pad.equilibrate
@timeit_debug to "equilibration" equilibrate!(
pad.K,
pad.mt.Deq,
pad.mt.C_eq;
ϵ = T(1.0e-2),
max_iter = 15,
)
end
end
return 0
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 15313 | # Formulation K2: (if regul==:classic, adds additional regularization parmeters -ρ (top left) and δ (bottom right))
# [-Q - D A' ] [x] = rhs
# [ A 0 ] [y]
export K2LDLParams
"""
Type to use the K2 formulation with a LDLᵀ factorization.
The package [`LDLFactorizations.jl`](https://github.com/JuliaSmoothOptimizers/LDLFactorizations.jl)
is used by default.
The outer constructor
sp = K2LDLParams(; fact_alg = LDLFact(regul = :classic),
ρ0 = sqrt(eps()) * 1e5, δ0 = sqrt(eps()) * 1e5,
ρ_min = sqrt(eps()), δ_min = sqrt(eps()),
safety_dist_bnd = true)
creates a [`RipQP.SolverParams`](@ref).
`regul = :dynamic` uses a dynamic regularization (the regularization is only added if the LDLᵀ factorization
encounters a pivot that has a small magnitude).
`regul = :none` uses no regularization (not recommended).
When `regul = :classic`, the parameters `ρ0` and `δ0` are used to choose the initial regularization values.
`fact_alg` should be a [`RipQP.AbstractFactorization`](@ref).
`safety_dist_bnd = true`: boolean used to determine if the regularization values should be updated
(or if the algorithm should transition to another solver in multi mode) if the variables are too close
from their bound.
"""
mutable struct K2LDLParams{T, Fact} <: AugmentedParams{T}
uplo::Symbol
fact_alg::Fact
ρ0::T
δ0::T
ρ_min::T
δ_min::T
safety_dist_bnd::Bool
function K2LDLParams(
fact_alg::AbstractFactorization,
ρ0::T,
δ0::T,
ρ_min::T,
δ_min::T,
safety_dist_bnd::Bool,
) where {T}
return new{T, typeof(fact_alg)}(
get_uplo(fact_alg),
fact_alg,
ρ0,
δ0,
ρ_min,
δ_min,
safety_dist_bnd,
)
end
end
K2LDLParams{T}(;
fact_alg::AbstractFactorization = LDLFact(:classic),
ρ0::T = (T == Float16) ? one(T) : T(sqrt(eps()) * 1e5),
δ0::T = (T == Float16) ? one(T) : T(sqrt(eps()) * 1e5),
ρ_min::T = (T == Float64) ? 1e-5 * sqrt(eps()) : sqrt(eps(T)),
δ_min::T = (T == Float64) ? 1e0 * sqrt(eps()) : sqrt(eps(T)),
safety_dist_bnd::Bool = true,
) where {T} = K2LDLParams(fact_alg, ρ0, δ0, ρ_min, δ_min, safety_dist_bnd)
K2LDLParams(; kwargs...) = K2LDLParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK2LDL{T <: Real, S, F, M <: AbstractMatrix{T}} <:
PreallocatedDataAugmentedLDL{T, S}
D::S # temporary top-left diagonal
regu::Regularization{T}
safety_dist_bnd::Bool
diag_Q::SparseVector{T, Int} # Q diagonal
K::Symmetric{T, M} # augmented matrix
K_fact::F # factorized matrix
fact_fail::Bool # true if factorization failed
diagind_K::Vector{Int} # diagonal indices of J
end
solver_name(pad::PreallocatedDataK2LDL) =
string(string(typeof(pad).name.name)[17:end], " with $(typeof(pad.K_fact).name.name)")
# outer constructor
function PreallocatedData(
sp::K2LDLParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
D = similar(fd.c, id.nvar)
D .= -T(1.0e0) / 2
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), sp.fact_alg.regul)
K, diagind_K, diag_Q = get_K2_matrixdata(id, D, fd.Q, fd.A, regu, sp.uplo, T)
K_fact = init_fact(K, sp.fact_alg)
if regu.regul == :dynamic || regu.regul == :hybrid
Amax = @views norm(K.data.nzval[diagind_K], Inf)
# regu.ρ, regu.δ = T(eps(T)^(3 / 4)), T(eps(T)^(0.45)) # ρ and δ kept for hybrid mode
K_fact.LDL.r1, K_fact.LDL.r2 = -T(eps(T)^(3 / 4)), T(eps(T)^(0.45))
K_fact.LDL.tol = Amax * T(eps(T))
K_fact.LDL.n_d = id.nvar
elseif regu.regul == :none
regu.ρ, regu.δ = zero(T), zero(T)
end
return PreallocatedDataK2LDL(
D,
regu,
sp.safety_dist_bnd,
diag_Q, #diag_Q
K, #K
K_fact, #K_fact
false,
diagind_K, #diagind_K
)
end
init_pad!(pad::PreallocatedDataK2LDL) = generic_factorize!(pad.K, pad.K_fact)
# function used to solve problems
# solver LDLFactorization
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK2LDL{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
ldiv!(pad.K_fact, dd)
return 0
end
function update_pad!(
pad::PreallocatedDataK2LDL{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if (pad.regu.regul == :classic || pad.regu.regul == :hybrid) && cnts.k != 0
# update ρ and δ values, check K diag magnitude
out = update_regu_diagK2!(
pad.regu,
pad.K,
pad.diagind_K,
itd.μ,
id.nvar,
cnts,
safety_dist_bnd = pad.safety_dist_bnd,
)
out == 1 && return out
end
update_K!(
pad.K,
pad.D,
pad.regu,
pt.s_l,
pt.s_u,
itd.x_m_lvar,
itd.uvar_m_x,
id.ilow,
id.iupp,
pad.diag_Q,
pad.diagind_K,
id.nvar,
id.ncon,
)
out = factorize_K2!(
pad.K,
pad.K_fact,
pad.D,
pad.diag_Q,
pad.diagind_K,
pad.regu,
pt.s_l,
pt.s_u,
itd.x_m_lvar,
itd.uvar_m_x,
id.ilow,
id.iupp,
id.ncon,
id.nvar,
cnts,
itd.qp,
) # update D and factorize K
if out == 1
pad.fact_fail = true
return out
end
return 0
end
# Init functions for the K2 system when uplo = U
function fill_K2_U!(
K_colptr,
K_rowval,
K_nzval,
D,
Q_colptr,
Q_rowval,
Q_nzval,
A_colptr,
A_rowval,
A_nzval,
δ,
ncon,
nvar,
regul,
)
added_coeffs_diag = 0 # we add coefficients that do not appear in Q in position i,i if Q[i,i] = 0
nnz_Q = length(Q_rowval)
@inbounds for j = 1:nvar # Q coeffs, tmp diag coefs.
K_colptr[j + 1] = Q_colptr[j + 1] + added_coeffs_diag # add previously added diagonal elements
for k = Q_colptr[j]:(Q_colptr[j + 1] - 1)
nz_idx = k + added_coeffs_diag
K_rowval[nz_idx] = Q_rowval[k]
K_nzval[nz_idx] = -Q_nzval[k]
end
k = Q_colptr[j + 1] - 1
if k ≤ nnz_Q && k != 0 && Q_rowval[k] == j
nz_idx = K_colptr[j + 1] - 1
K_rowval[nz_idx] = j
K_nzval[nz_idx] = D[j] - Q_nzval[k]
else
added_coeffs_diag += 1
K_colptr[j + 1] += 1
nz_idx = K_colptr[j + 1] - 1
K_rowval[nz_idx] = j
K_nzval[nz_idx] = D[j]
end
end
countsum = K_colptr[nvar + 1] # current value of K_colptr[Q.n+j+1]
nnz_top_left = countsum # number of coefficients + 1 already added
@inbounds for j = 1:ncon
countsum += A_colptr[j + 1] - A_colptr[j]
if (regul == :classic || regul == :hybrid) && δ > 0
countsum += 1
end
K_colptr[nvar + j + 1] = countsum
for k = A_colptr[j]:(A_colptr[j + 1] - 1)
nz_idx =
((regul == :classic || regul == :hybrid) && δ > 0) ? k + nnz_top_left + j - 2 :
k + nnz_top_left - 1
K_rowval[nz_idx] = A_rowval[k]
K_nzval[nz_idx] = A_nzval[k]
end
if (regul == :classic || regul == :hybrid) && δ > 0
nz_idx = K_colptr[nvar + j + 1] - 1
K_rowval[nz_idx] = nvar + j
K_nzval[nz_idx] = δ
end
end
end
# Init functions for the K2 system when uplo = U
function fill_K2_L!(
K_colptr,
K_rowval,
K_nzval,
D,
Q_colptr,
Q_rowval,
Q_nzval,
A_colptr,
A_rowval,
A_nzval,
δ,
ncon,
nvar,
regul,
)
added_coeffs_diag = 0 # we add coefficients that do not appear in Q in position i,i if Q[i,i] = 0
nnz_Q = length(Q_rowval)
@inbounds for j = 1:nvar # Q coeffs, tmp diag coefs.
k = Q_colptr[j]
K_deb_ptr = K_colptr[j]
if k ≤ nnz_Q && k != 0 && Q_rowval[k] == j
added_diagj = false
K_rowval[K_deb_ptr] = j
K_nzval[K_deb_ptr] = D[j] - Q_nzval[k]
else
added_diagj = true
added_coeffs_diag += 1
K_rowval[K_deb_ptr] = j
K_nzval[K_deb_ptr] = D[j]
end
nb_col_elements = 1
deb = added_diagj ? Q_colptr[j] : (Q_colptr[j] + 1) # if already addded a new Kjj, do not add Qjj
for k = deb:(Q_colptr[j + 1] - 1)
nz_idx = K_deb_ptr + nb_col_elements
nb_col_elements += 1
K_rowval[nz_idx] = Q_rowval[k]
K_nzval[nz_idx] = -Q_nzval[k]
end
# nb_elemsj_bloc11 = nb_col_elements
for k = A_colptr[j]:(A_colptr[j + 1] - 1)
nz_idx = K_deb_ptr + nb_col_elements
nb_col_elements += 1
K_rowval[nz_idx] = A_rowval[k] + nvar
K_nzval[nz_idx] = A_nzval[k]
end
K_colptr[j + 1] = K_colptr[j] + nb_col_elements
end
if (regul == :classic || regul == :hybrid) && δ > 0
@inbounds for j = 1:ncon
K_prevptr = K_colptr[nvar + j]
K_colptr[nvar + j + 1] = K_prevptr + 1
K_rowval[K_prevptr] = nvar + j
K_nzval[K_prevptr] = δ
end
end
end
function create_K2(
id::QM_IntData,
D::AbstractVector,
Q::SparseMatrixCSC,
A::SparseMatrixCSC,
diag_Q::SparseVector,
regu::Regularization,
uplo::Symbol,
::Type{T},
) where {T}
# for classic regul only
n_nz = length(D) - length(diag_Q.nzind) + length(A.nzval) + length(Q.nzval)
if (regu.regul == :classic || regu.regul == :hybrid) && regu.δ > 0
n_nz += id.ncon
end
K_colptr = Vector{Int}(undef, id.ncon + id.nvar + 1)
K_colptr[1] = 1
K_rowval = Vector{Int}(undef, n_nz)
K_nzval = Vector{T}(undef, n_nz)
if uplo == :L
# [-Q -D 0]
# [ A δI]
fill_K2_L!(
K_colptr,
K_rowval,
K_nzval,
D,
Q.colptr,
Q.rowval,
Q.nzval,
A.colptr,
A.rowval,
A.nzval,
regu.δ,
id.ncon,
id.nvar,
regu.regul,
)
else
# [-Q -D A]
# [0 δI]
fill_K2_U!(
K_colptr,
K_rowval,
K_nzval,
D,
Q.colptr,
Q.rowval,
Q.nzval,
A.colptr,
A.rowval,
A.nzval,
regu.δ,
id.ncon,
id.nvar,
regu.regul,
)
end
return Symmetric(
SparseMatrixCSC{T, Int}(id.ncon + id.nvar, id.ncon + id.nvar, K_colptr, K_rowval, K_nzval),
uplo,
)
end
function create_K2(
id::QM_IntData,
D::AbstractVector,
Q::SparseMatrixCOO,
A::SparseMatrixCOO,
diag_Q::SparseVector,
regu::Regularization,
uplo::Symbol,
::Type{T},
) where {T}
nvar, ncon = id.nvar, id.ncon
δ = regu.δ
nnz_Q, nnz_A = nnz(Q), nnz(A)
Qrows, Qcols, Qvals = Q.rows, Q.cols, Q.vals
Arows, Acols, Avals = A.rows, A.cols, A.vals
nnz_tot = nnz_A + nnz_Q + nvar + id.ncon - length(diag_Q.nzind)
rows = Vector{Int}(undef, nnz_tot)
cols = Vector{Int}(undef, nnz_tot)
vals = Vector{T}(undef, nnz_tot)
kQ, kA = 1, 1
current_col = 1
added_diag_col = false # true if K[j, j] has been filled
for k = 1:nnz_tot
if current_col > nvar
rows[k] = current_col
cols[k] = current_col
vals[k] = δ
elseif !added_diag_col # add diagonal
rows[k] = current_col
cols[k] = current_col
if kQ ≤ nnz_Q && Qrows[kQ] == Qcols[kQ] == current_col
vals[k] = -Qvals[kQ] + D[current_col]
kQ += 1
else
vals[k] = D[current_col]
end
added_diag_col = true
elseif kQ ≤ nnz_Q && Qcols[kQ] == current_col
rows[k] = Qrows[kQ]
cols[k] = Qcols[kQ]
vals[k] = -Qvals[kQ]
kQ += 1
elseif kA ≤ nnz_A && Acols[kA] == current_col
rows[k] = Arows[kA] + nvar
cols[k] = Acols[kA]
vals[k] = Avals[kA]
kA += 1
end
if (kQ > nnz_Q || Qcols[kQ] != current_col) && (kA > nnz_A || Acols[kA] != current_col)
current_col += 1
added_diag_col = false
end
end
return Symmetric(SparseMatrixCOO(nvar + ncon, nvar + ncon, rows, cols, vals), uplo)
end
function get_K2_matrixdata(
id::QM_IntData,
D::AbstractVector,
Q::Symmetric,
A::AbstractSparseMatrix,
regu::Regularization,
uplo::Symbol,
::Type{T},
) where {T}
diag_Q = get_diag_Q(Q)
K = create_K2(id, D, Q.data, A, diag_Q, regu, uplo, T)
diagind_K = get_diagind_K(K, uplo)
return K, diagind_K, diag_Q
end
function update_D!(
D::AbstractVector{T},
x_m_lvar::AbstractVector{T},
uvar_m_x::AbstractVector{T},
s_l::AbstractVector{T},
s_u::AbstractVector{T},
ρ::T,
ilow,
iupp,
) where {T}
D .= -ρ
@. D[ilow] -= s_l / x_m_lvar
@. D[iupp] -= s_u / uvar_m_x
end
function update_diag_K11!(K::Symmetric{T, <:SparseMatrixCSC}, D, diagind_K, nvar) where {T}
K.data.nzval[view(diagind_K, 1:nvar)] = D
end
function update_diag_K11!(K::Symmetric{T, <:SparseMatrixCOO}, D, diagind_K, nvar) where {T}
K.data.vals[view(diagind_K, 1:nvar)] = D
end
function update_diag_K22!(K::Symmetric{T, <:SparseMatrixCSC}, δ, diagind_K, nvar, ncon) where {T}
K.data.nzval[view(diagind_K, (nvar + 1):(ncon + nvar))] .= δ
end
function update_diag_K22!(K::Symmetric{T, <:SparseMatrixCOO}, δ, diagind_K, nvar, ncon) where {T}
K.data.vals[view(diagind_K, (nvar + 1):(ncon + nvar))] .= δ
end
function update_K!(
K::Symmetric{T},
D::AbstractVector{T},
regu::Regularization,
s_l::AbstractVector{T},
s_u::AbstractVector{T},
x_m_lvar::AbstractVector{T},
uvar_m_x::AbstractVector{T},
ilow,
iupp,
diag_Q::AbstractSparseVector{T},
diagind_K,
nvar,
ncon,
) where {T}
if regu.regul == :classic || regu.regul == :hybrid
ρ = regu.ρ
if regu.δ > 0
update_diag_K22!(K, regu.δ, diagind_K, nvar, ncon)
end
else
ρ = zero(T)
end
update_D!(D, x_m_lvar, uvar_m_x, s_l, s_u, ρ, ilow, iupp)
D[diag_Q.nzind] .-= diag_Q.nzval
update_diag_K11!(K, D, diagind_K, nvar)
end
function update_K_dynamic!(
K::Symmetric{T},
K_fact::LDLFactorizations.LDLFactorization{Tlow},
regu::Regularization{Tlow},
diagind_K,
cnts::Counters,
qp::Bool,
) where {T, Tlow}
Amax = @views norm(K.data.nzval[diagind_K], Inf)
if Amax > T(1e6) / K_fact.r2 && cnts.c_regu_dim < 8
if Tlow == Float32 && regu.regul == :dynamic
return one(Int) # update to Float64
elseif (qp || cnts.c_regu_dim < 4) && regu.regul == :dynamic
cnts.c_regu_dim += 1
regu.δ /= 10
K_fact.r2 = regu.δ
end
end
K_fact.tol = Tlow(Amax * eps(Tlow))
end
# iteration functions for the K2 system
function factorize_K2!(
K::Symmetric{T},
K_fact::FactorizationData{Tlow},
D::AbstractVector{T},
diag_Q::AbstractSparseVector{T},
diagind_K,
regu::Regularization{Tlow},
s_l::AbstractVector{T},
s_u::AbstractVector{T},
x_m_lvar::AbstractVector{T},
uvar_m_x::AbstractVector{T},
ilow,
iupp,
ncon,
nvar,
cnts::Counters,
qp::Bool,
) where {T, Tlow}
if (regu.regul == :dynamic || regu.regul == :hybrid) && K_fact isa LDLFactorizationData
update_K_dynamic!(K, K_fact.LDL, regu, diagind_K, cnts, qp)
@timeit_debug to "factorize" generic_factorize!(K, K_fact)
elseif regu.regul == :classic
@timeit_debug to "factorize" generic_factorize!(K, K_fact)
while !RipQP.factorized(K_fact)
out = update_regu_trycatch!(regu, cnts)
out == 1 && return out
cnts.c_catch += 1
cnts.c_catch >= 10 && return 1
update_K!(K, D, regu, s_l, s_u, x_m_lvar, uvar_m_x, ilow, iupp, diag_Q, diagind_K, nvar, ncon)
@timeit_debug to "factorize" generic_factorize!(K, K_fact)
end
else # no Regularization
@timeit_debug to "factorize" generic_factorize!(K, K_fact)
end
return 0 # factorization succeeded
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 3269 | # Formulation K2: (if regul==:classic, adds additional regularization parmeters -ρ (top left) and δ (bottom right))
# [-Q - D A' ] [x] = rhs
# [ A 0 ] [y]
export K2LDLDenseParams
"""
Type to use the K2 formulation with a LDLᵀ factorization.
The outer constructor
sp = K2LDLDenseParams(; ρ0 = sqrt(eps()) * 1e5, δ0 = sqrt(eps()) * 1e5)
creates a [`RipQP.SolverParams`](@ref).
"""
mutable struct K2LDLDenseParams{T} <: AugmentedParams{T}
uplo::Symbol
fact_alg::Symbol
ρ0::T
δ0::T
end
function K2LDLDenseParams(;
fact_alg::Symbol = :bunchkaufman,
ρ0::Float64 = sqrt(eps()) * 1e5,
δ0::Float64 = sqrt(eps()) * 1e5,
)
uplo = :L # mandatory for LDL fact
return K2LDLDenseParams(uplo, fact_alg, ρ0, δ0)
end
mutable struct PreallocatedDataK2LDLDense{T <: Real, S, M <: AbstractMatrix{T}} <:
PreallocatedDataAugmentedLDL{T, S}
D::S # temporary top-left diagonal
regu::Regularization{T}
K::M # augmented matrix
fact_alg::Symbol
end
# outer constructor
function PreallocatedData(
sp::K2LDLDenseParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
D = similar(fd.c, id.nvar)
if iconf.mode == :mono
regu = Regularization(T(sp.ρ0), T(sp.δ0), 1e-5 * sqrt(eps(T)), 1e0 * sqrt(eps(T)), :classic)
D .= -T(1.0e0) / 2
else
regu =
Regularization(T(sp.ρ0), T(sp.δ0), T(sqrt(eps(T)) * 1e0), T(sqrt(eps(T)) * 1e0), :classic)
D .= -T(1.0e-2)
end
K = Symmetric(zeros(T, id.nvar + id.ncon, id.nvar + id.ncon), :L)
K.data[1:(id.nvar), 1:(id.nvar)] .= .-fd.Q.data .+ Diagonal(D)
K.data[(id.nvar + 1):(id.nvar + id.ncon), 1:(id.nvar)] .= fd.A
K.data[view(diagind(K), (id.nvar + 1):(id.nvar + id.ncon))] .= regu.δ
if sp.fact_alg == :bunchkaufman
bunchkaufman!(K)
elseif sp.fact_alg == :ldl
ldl_dense!(K)
end
return PreallocatedDataK2LDLDense(
D,
regu,
K, #K
sp.fact_alg,
)
end
# function used to solve problems
# solver LDLFactorization
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK2LDLDense{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
ldiv_dense!(pad.K, dd)
return 0
end
function update_pad!(
pad::PreallocatedDataK2LDLDense{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
pad.D .= -pad.regu.ρ
@. pad.D[id.ilow] -= pt.s_l / itd.x_m_lvar
@. pad.D[id.iupp] -= pt.s_u / itd.uvar_m_x
pad.K.data[1:(id.nvar), 1:(id.nvar)] .= .-fd.Q.data .+ Diagonal(pad.D)
pad.K.data[(id.nvar + 1):(id.nvar + id.ncon), 1:(id.nvar)] .= fd.A
pad.K.data[(id.nvar + 1):(id.nvar + id.ncon), (id.nvar + 1):(id.nvar + id.ncon)] .= zero(T)
pad.K.data[view(diagind(pad.K), (id.nvar + 1):(id.nvar + id.ncon))] .= pad.regu.δ
if pad.fact_alg == :bunchkaufman
bunchkaufman!(pad.K)
elseif pad.fact_alg == :ldl
ldl_dense!(pad.K)
end
return 0
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 5127 | export K2StructuredParams
"""
Type to use the K2 formulation with a structured Krylov method, using the package
[`Krylov.jl`](https://github.com/JuliaSmoothOptimizers/Krylov.jl).
This only works for solving Linear Problems.
The outer constructor
K2StructuredParams(; uplo = :L, kmethod = :trimr, rhs_scale = true,
atol0 = 1.0e-4, rtol0 = 1.0e-4,
atol_min = 1.0e-10, rtol_min = 1.0e-10,
ρ_min = 1e2 * sqrt(eps()), δ_min = 1e2 * sqrt(eps()),
itmax = 0, mem = 20)
creates a [`RipQP.SolverParams`](@ref).
The available methods are:
- `:tricg`
- `:trimr`
- `:gpmr`
The `mem` argument sould be used only with `gpmr`.
"""
mutable struct K2StructuredParams{T} <: AugmentedParams{T}
uplo::Symbol
kmethod::Symbol
rhs_scale::Bool
atol0::T
rtol0::T
atol_min::T
rtol_min::T
ρ_min::T
δ_min::T
itmax::Int
mem::Int
end
function K2StructuredParams{T}(;
uplo::Symbol = :L,
kmethod::Symbol = :trimr,
rhs_scale::Bool = true,
atol0::T = eps(T)^(1 / 4),
rtol0::T = eps(T)^(1 / 4),
atol_min::T = sqrt(eps(T)),
rtol_min::T = sqrt(eps(T)),
ρ_min::T = T(1e2 * sqrt(eps(T))),
δ_min::T = T(1e2 * sqrt(eps(T))),
itmax::Int = 0,
mem::Int = 20,
) where {T <: Real}
return K2StructuredParams(
uplo,
kmethod,
rhs_scale,
atol0,
rtol0,
atol_min,
rtol_min,
ρ_min,
δ_min,
itmax,
mem,
)
end
K2StructuredParams(; kwargs...) = K2StructuredParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK2Structured{T <: Real, S, Ksol <: KrylovSolver} <:
PreallocatedDataAugmentedKrylovStructured{T, S}
E::S # temporary top-left diagonal
invE::S
ξ1::S
ξ2::S
rhs_scale::Bool
regu::Regularization{T}
KS::Ksol
kiter::Int
atol::T
rtol::T
atol_min::T
rtol_min::T
itmax::Int
end
function PreallocatedData(
sp::K2StructuredParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
E = similar(fd.c, id.nvar)
if iconf.mode == :mono
regu =
Regularization(T(sqrt(eps()) * 1e5), T(sqrt(eps()) * 1e5), T(sp.ρ_min), T(sp.δ_min), :classic)
E .= T(1.0e0) / 2
else
regu = Regularization(
T(sqrt(eps()) * 1e5),
T(sqrt(eps()) * 1e5),
T(sqrt(eps(T)) * 1e0),
T(sqrt(eps(T)) * 1e0),
:classic,
)
E .= T(1.0e-2)
end
if regu.δ_min == zero(T) # gsp for gpmr
regu.δ = zero(T)
end
invE = similar(E)
invE .= one(T) ./ E
ξ1 = similar(fd.c, id.nvar)
ξ2 = similar(fd.c, id.ncon)
KS = init_Ksolver(fd.A', fd.b, sp)
return PreallocatedDataK2Structured(
E,
invE,
ξ1,
ξ2,
sp.rhs_scale,
regu,
KS,
0,
T(sp.atol0),
T(sp.rtol0),
T(sp.atol_min),
T(sp.rtol_min),
sp.itmax,
)
end
function update_kresiduals_history!(
res::AbstractResiduals{T},
E::AbstractVector{T},
A::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
δ::T,
solx::AbstractVector{T},
soly::AbstractVector{T},
ξ1::AbstractVector{T},
ξ2::AbstractVector{T},
nvar::Int,
) where {T <: Real}
if typeof(res) <: ResidualsHistory
@views mul!(res.Kres[1:nvar], A', soly)
@. res.Kres[1:nvar] += -E * solx - ξ1
@views mul!(res.Kres[(nvar + 1):end], A, solx)
@. res.Kres[(nvar + 1):end] += δ * soly - ξ2
end
end
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK2Structured{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
pad.ξ1 .= @views step == :init ? fd.c : dd[1:(id.nvar)]
pad.ξ2 .= @views (step == :init && all(dd[(id.nvar + 1):end] .== zero(T))) ? one(T) :
dd[(id.nvar + 1):end]
if pad.rhs_scale
rhsNorm = sqrt(norm(pad.ξ1)^2 + norm(pad.ξ2)^2)
pad.ξ1 ./= rhsNorm
pad.ξ2 ./= rhsNorm
end
(step !== :cc) && (pad.kiter = 0)
ksolve!(
pad.KS,
fd.A',
pad.ξ1,
pad.ξ2,
Diagonal(pad.invE),
(one(T) / pad.regu.δ) .* I,
verbose = 0,
atol = pad.atol,
rtol = pad.rtol,
gsp = (pad.regu.δ == zero(T)),
itmax = pad.itmax,
)
update_kresiduals_history!(
res,
pad.E,
fd.A,
pad.regu.δ,
pad.KS.x,
pad.KS.y,
pad.ξ1,
pad.ξ2,
id.nvar,
)
pad.kiter += niterations(pad.KS)
if pad.rhs_scale
kunscale!(pad.KS.x, rhsNorm)
kunscale!(pad.KS.y, rhsNorm)
end
dd[1:(id.nvar)] .= pad.KS.x
dd[(id.nvar + 1):end] .= pad.KS.y
return 0
end
function update_pad!(
pad::PreallocatedDataK2Structured{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
update_krylov_tol!(pad)
pad.E .= pad.regu.ρ
@. pad.E[id.ilow] += pt.s_l / itd.x_m_lvar
@. pad.E[id.iupp] += pt.s_u / itd.uvar_m_x
@. pad.invE = one(T) / pad.E
return 0
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 6304 | export K2_5KrylovParams
"""
Type to use the K2.5 formulation with a Krylov method, using the package
[`Krylov.jl`](https://github.com/JuliaSmoothOptimizers/Krylov.jl).
The outer constructor
K2_5KrylovParams(; uplo = :L, kmethod = :minres, preconditioner = Identity(),
rhs_scale = true,
atol0 = 1.0e-4, rtol0 = 1.0e-4,
atol_min = 1.0e-10, rtol_min = 1.0e-10,
ρ0 = sqrt(eps()) * 1e5, δ0 = sqrt(eps()) * 1e5,
ρ_min = 1e2 * sqrt(eps()), δ_min = 1e2 * sqrt(eps()),
itmax = 0, mem = 20)
creates a [`RipQP.SolverParams`](@ref).
The available methods are:
- `:minres`
- `:minres_qlp`
- `:symmlq`
"""
mutable struct K2_5KrylovParams{T, PT} <: AugmentedKrylovParams{T, PT}
uplo::Symbol
kmethod::Symbol
preconditioner::PT
rhs_scale::Bool
atol0::T
rtol0::T
atol_min::T
rtol_min::T
ρ0::T
δ0::T
ρ_min::T
δ_min::T
itmax::Int
mem::Int
end
function K2_5KrylovParams{T}(;
uplo::Symbol = :L,
kmethod::Symbol = :minres,
preconditioner::AbstractPreconditioner = Identity(),
rhs_scale::Bool = true,
atol0::T = 1.0e-4,
rtol0::T = 1.0e-4,
atol_min::T = 1.0e-10,
rtol_min::T = 1.0e-10,
ρ0::T = sqrt(eps()) * 1e5,
δ0::T = sqrt(eps()) * 1e5,
ρ_min::T = 1e2 * sqrt(eps()),
δ_min::T = 1e3 * sqrt(eps()),
itmax::Int = 0,
mem::Int = 20,
) where {T <: Real}
return K2_5KrylovParams(
uplo,
kmethod,
preconditioner,
rhs_scale,
atol0,
rtol0,
atol_min,
rtol_min,
ρ0,
δ0,
ρ_min,
δ_min,
itmax,
mem,
)
end
K2_5KrylovParams(; kwargs...) = K2_5KrylovParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK2_5Krylov{
T <: Real,
S,
L <: LinearOperator,
Pr <: PreconditionerData,
Ksol <: KrylovSolver,
} <: PreallocatedDataAugmentedKrylov{T, S}
pdat::Pr
D::S # temporary top-left diagonal
sqrtX1X2::S # vector to scale K2 to K2.5
tmp1::S # temporary vector for products
tmp2::S # temporary vector for products
rhs::S
rhs_scale::Bool
regu::Regularization{T}
δv::Vector{T}
K::L # augmented matrix
KS::Ksol
kiter::Int
atol::T
rtol::T
atol_min::T
rtol_min::T
itmax::Int
end
function opK2_5prod!(
res::AbstractVector{T},
nvar::Int,
Q::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
D::AbstractVector{T},
A::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
sqrtX1X2::AbstractVector{T},
tmp1::AbstractVector{T},
tmp2::AbstractVector{T},
δv::AbstractVector{T},
v::AbstractVector{T},
α::T,
β::T,
uplo::Symbol,
) where {T}
@. tmp2 = @views sqrtX1X2 * v[1:nvar]
mul!(tmp1, Q, tmp2, -α, zero(T))
@. tmp1 = @views sqrtX1X2 * tmp1 + α * D * v[1:nvar]
if β == zero(T)
res[1:nvar] .= tmp1
else
@. res[1:nvar] = @views tmp1 + β * res[1:nvar]
end
if uplo == :U
@views mul!(tmp1, A, v[(nvar + 1):end], α, zero(T))
@. res[1:nvar] += sqrtX1X2 * tmp1
@views mul!(res[(nvar + 1):end], A', tmp2, α, β)
else
@views mul!(tmp1, A', v[(nvar + 1):end], α, zero(T))
@. res[1:nvar] += sqrtX1X2 * tmp1
@views mul!(res[(nvar + 1):end], A, tmp2, α, β)
end
res[(nvar + 1):end] .+= @views (α * δv[1]) .* v[(nvar + 1):end]
end
function PreallocatedData(
sp::K2_5KrylovParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
D = similar(fd.c, id.nvar)
if iconf.mode == :mono
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), :classic)
D .= -T(1.0e0) / 2
else
regu =
Regularization(T(sp.ρ0), T(sp.δ0), T(sqrt(eps(T)) * 1e0), T(sqrt(eps(T)) * 1e0), :classic)
D .= -T(1.0e-2)
end
sqrtX1X2 = fill!(similar(D), one(T))
tmp1 = similar(D)
tmp2 = similar(D)
δv = [regu.δ] # put it in a Vector so that we can modify it without modifying opK2prod!
K = LinearOperator(
T,
id.nvar + id.ncon,
id.nvar + id.ncon,
true,
true,
(res, v, α, β) ->
opK2_5prod!(res, id.nvar, fd.Q, D, fd.A, sqrtX1X2, tmp1, tmp2, δv, v, α, β, fd.uplo),
)
rhs = similar(fd.c, id.nvar + id.ncon)
KS = init_Ksolver(K, rhs, sp)
pdat = PreconditionerData(sp, id, fd, regu, D, K)
return PreallocatedDataK2_5Krylov(
pdat,
D,
sqrtX1X2,
tmp1,
tmp2,
rhs,
sp.rhs_scale,
regu,
δv,
K, #K
KS, #K_fact
0,
T(sp.atol0),
T(sp.rtol0),
T(sp.atol_min),
T(sp.rtol_min),
sp.itmax,
)
end
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK2_5Krylov{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
# erase dda.Δxy_aff only for affine predictor step with PC method
@. pad.rhs[1:(id.nvar)] = @views dd[1:(id.nvar)] * pad.sqrtX1X2
pad.rhs[(id.nvar + 1):end] .= @views dd[(id.nvar + 1):end]
if pad.rhs_scale
rhsNorm = kscale!(pad.rhs)
end
(step !== :cc) && (pad.kiter = 0)
ksolve!(
pad.KS,
pad.K,
pad.rhs,
pad.pdat.P,
verbose = 0,
atol = pad.atol,
rtol = pad.rtol,
itmax = pad.itmax,
)
update_kresiduals_history!(res, pad.K, pad.KS.x, pad.rhs)
pad.kiter += niterations(pad.KS)
if pad.rhs_scale
kunscale!(pad.KS.x, rhsNorm)
end
pad.KS.x[1:(id.nvar)] .*= pad.sqrtX1X2
dd .= pad.KS.x
return 0
end
function update_pad!(
pad::PreallocatedDataK2_5Krylov{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
update_krylov_tol!(pad)
# K2.5
pad.sqrtX1X2 .= one(T)
@. pad.sqrtX1X2[id.ilow] *= sqrt(itd.x_m_lvar)
@. pad.sqrtX1X2[id.iupp] *= sqrt(itd.uvar_m_x)
pad.D .= zero(T)
pad.D[id.ilow] .-= pt.s_l
pad.D[id.iupp] .*= itd.uvar_m_x
pad.tmp1 .= zero(T)
pad.tmp1[id.iupp] .-= pt.s_u
pad.tmp1[id.ilow] .*= itd.x_m_lvar
@. pad.D += pad.tmp1 - pad.regu.ρ
pad.δv[1] = pad.regu.δ
update_preconditioner!(pad.pdat, pad, itd, pt, id, fd, cnts)
return 0
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 8465 | # Formulation K2: (if regul==:classic, adds additional Regularization parmeters -ρ (top left) and δ (bottom right))
# [-Q_X - D sqrt(X1X2)A' ] [̃x] = rhs
# [ A sqrt(X1x2) 0 ] [y]
# where Q_X = sqrt(X1X2) Q sqrt(X1X2) and D = s_l X2 + s_u X1
# and Δ x = sqrt(X1 X2) Δ ̃x
export K2_5LDLParams
"""
Type to use the K2.5 formulation with a LDLᵀ factorization.
The package [`LDLFactorizations.jl`](https://github.com/JuliaSmoothOptimizers/LDLFactorizations.jl)
is used by default.
The outer constructor
sp = K2_5LDLParams(; fact_alg = LDLFact(regul = :classic), ρ0 = sqrt(eps()) * 1e5, δ0 = sqrt(eps()) * 1e5)
creates a [`RipQP.SolverParams`](@ref).
`regul = :dynamic` uses a dynamic regularization (the regularization is only added if the LDLᵀ factorization
encounters a pivot that has a small magnitude).
`regul = :none` uses no regularization (not recommended).
When `regul = :classic`, the parameters `ρ0` and `δ0` are used to choose the initial regularization values.
`fact_alg` should be a [`RipQP.AbstractFactorization`](@ref).
"""
mutable struct K2_5LDLParams{T, Fact} <: AugmentedParams{T}
uplo::Symbol
fact_alg::Fact
ρ0::T
δ0::T
ρ_min::T
δ_min::T
function K2_5LDLParams(
fact_alg::AbstractFactorization,
ρ0::T,
δ0::T,
ρ_min::T,
δ_min::T,
) where {T}
return new{T, typeof(fact_alg)}(get_uplo(fact_alg), fact_alg, ρ0, δ0, ρ_min, δ_min)
end
end
K2_5LDLParams{T}(;
fact_alg::AbstractFactorization = LDLFact(:classic),
ρ0::T = (T == Float64) ? sqrt(eps()) * 1e5 : one(T),
δ0::T = (T == Float64) ? sqrt(eps()) * 1e5 : one(T),
ρ_min::T = (T == Float64) ? 1e-5 * sqrt(eps()) : sqrt(eps(T)),
δ_min::T = (T == Float64) ? 1e0 * sqrt(eps()) : sqrt(eps(T)),
) where {T} = K2_5LDLParams(fact_alg, ρ0, δ0, ρ_min, δ_min)
K2_5LDLParams(; kwargs...) = K2_5LDLParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK2_5LDL{T <: Real, S, M, F <: FactorizationData{T}} <:
PreallocatedDataAugmentedLDL{T, S}
D::S # temporary top-left diagonal
regu::Regularization{T}
diag_Q::SparseVector{T, Int} # Q diagonal
K::Symmetric{T, M} # augmented matrix
K_fact::F # factorized matrix
fact_fail::Bool # true if factorization failed
diagind_K::Vector{Int} # diagonal indices of J
K_scaled::Bool # true if K is scaled with X1X2
end
solver_name(pad::PreallocatedDataK2_5LDL) =
string(string(typeof(pad).name.name)[17:end], " with $(typeof(pad.K_fact).name.name)")
function PreallocatedData(
sp::K2_5LDLParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
D = similar(fd.c, id.nvar)
D .= -T(1.0e0) / 2
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), sp.fact_alg.regul)
K, diagind_K, diag_Q = get_K2_matrixdata(id, D, fd.Q, fd.A, regu, sp.uplo, T)
K_fact = init_fact(K, sp.fact_alg)
if regu.regul == :dynamic
Amax = @views norm(K.data.nzval[diagind_K], Inf)
regu.ρ, regu.δ = T(eps(T)^(3 / 4)), T(eps(T)^(0.45))
K_fact.LDL.r1, K_fact.LDL.r2 = -regu.ρ, regu.δ
K_fact.LDL.tol = Amax * T(eps(T))
K_fact.LDL.n_d = id.nvar
elseif regu.regul == :none
regu.ρ, regu.δ = zero(T), zero(T)
end
generic_factorize!(K, K_fact)
return PreallocatedDataK2_5LDL(
D,
regu,
diag_Q, #diag_Q
K, #K
K_fact, #K_fact
false,
diagind_K, #diagind_K
false,
)
end
# solver LDLFactorization
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK2_5LDL{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
if pad.K_scaled
dd[1:(id.nvar)] .*= pad.D
ldiv!(pad.K_fact, dd)
dd[1:(id.nvar)] .*= pad.D
else
ldiv!(pad.K_fact, dd)
end
if step == :cc || step == :IPF # update regularization and restore K. Cannot be done in update_pad since x-lvar and uvar-x will change.
out = 0
if pad.regu.regul == :classic # update ρ and δ values, check K diag magnitude
out = update_regu_diagK2_5!(pad.regu, pad.D, itd.μ, cnts)
end
# restore J for next iteration
if pad.K_scaled
pad.D .= one(T)
@. pad.D[id.ilow] /= sqrt(itd.x_m_lvar)
@. pad.D[id.iupp] /= sqrt(itd.uvar_m_x)
lrmultilply_K!(pad.K, pad.D, id.nvar)
pad.K_scaled = false
end
out == 1 && return out
end
return 0
end
function update_pad!(
pad::PreallocatedDataK2_5LDL{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
pad.K_scaled = false
update_K!(
pad.K,
pad.D,
pad.regu,
pt.s_l,
pt.s_u,
itd.x_m_lvar,
itd.uvar_m_x,
id.ilow,
id.iupp,
pad.diag_Q,
pad.diagind_K,
id.nvar,
id.ncon,
)
out = factorize_K2_5!(
pad.K,
pad.K_fact,
pad.D,
pad.diag_Q,
pad.diagind_K,
pad.regu,
pt.s_l,
pt.s_u,
itd.x_m_lvar,
itd.uvar_m_x,
id.ilow,
id.iupp,
id.ncon,
id.nvar,
cnts,
itd.qp,
)
out == 1 && return out
pad.K_scaled = true
return out
end
function lrmultilply_K_CSC!(K_colptr, K_rowval, K_nzval::Vector{T}, v::Vector{T}, nvar) where {T}
@inbounds @simd for i = 1:nvar
for idx_row = K_colptr[i]:(K_colptr[i + 1] - 1)
K_nzval[idx_row] *= v[i] * v[K_rowval[idx_row]]
end
end
n = length(K_colptr)
@inbounds @simd for i = (nvar + 1):(n - 1)
for idx_row = K_colptr[i]:(K_colptr[i + 1] - 1)
if K_rowval[idx_row] <= nvar
K_nzval[idx_row] *= v[K_rowval[idx_row]] # multiply row i by v[i]
end
end
end
end
lrmultilply_K!(K::Symmetric{T, SparseMatrixCSC{T, Int}}, v::Vector{T}, nvar) where {T} =
lrmultilply_K_CSC!(K.data.colptr, K.data.rowval, K.data.nzval, v, nvar)
function lrmultilply_K!(K::Symmetric{T, SparseMatrixCOO{T, Int}}, v::Vector{T}, nvar) where {T}
lmul!(v, K.data)
rmul!(K.data, v)
end
function X1X2_to_D!(
D::AbstractVector{T},
x_m_lvar::AbstractVector{T},
uvar_m_x::AbstractVector{T},
ilow,
iupp,
) where {T}
D .= one(T)
D[ilow] .*= sqrt.(x_m_lvar)
D[iupp] .*= sqrt.(uvar_m_x)
end
function update_Dsquare_diag_K11!(K::SparseMatrixCSC, D, diagind_K, nvar)
K.data.nzval[view(diagind_K, 1:nvar)] .*= D .^ 2
end
function update_Dsquare_diag_K11!(K::SparseMatrixCOO, D, diagind_K, nvar)
K.data.vals[view(diagind_K, 1:nvar)] .*= D .^ 2
end
# iteration functions for the K2.5 system
function factorize_K2_5!(
K::Symmetric{T},
K_fact::FactorizationData{T},
D::AbstractVector{T},
diag_Q::AbstractSparseVector{T},
diagind_K,
regu::Regularization{T},
s_l::AbstractVector{T},
s_u::AbstractVector{T},
x_m_lvar::AbstractVector{T},
uvar_m_x::AbstractVector{T},
ilow,
iupp,
ncon,
nvar,
cnts::Counters,
qp::Bool,
) where {T}
X1X2_to_D!(D, x_m_lvar, uvar_m_x, ilow, iupp)
lrmultilply_K!(K, D, nvar)
if regu.regul == :dynamic
# Amax = @views norm(K.nzval[diagind_K], Inf)
Amax = minimum(D)
if Amax < sqrt(eps(T)) && cnts.c_regu_dim < 8
if cnts.last_sp
# restore K for next iteration
X1X2_to_D!(D, x_m_lvar, uvar_m_x, ilow, iupp)
lrmultilply_K!(K, D, nvar)
return one(Int) # update to Float64
elseif qp || cnts.c_regu_dim < 4
cnts.c_regu_dim += 1
regu.δ /= 10
K_fact.LDL.r2 = max(sqrt(Amax), regu.δ)
# regu.ρ /= 10
end
end
K_fact.LDL.tol = min(Amax, T(eps(T)))
generic_factorize!(K, K_fact)
elseif regu.regul == :classic
generic_factorize!(K, K_fact)
while !RipQP.factorized(K_fact)
out = update_regu_trycatch!(regu, cnts)
if out == 1
# restore J for next iteration
X1X2_to_D!(D, x_m_lvar, uvar_m_x, ilow, iupp)
lrmultilply_K!(K, D, nvar)
return out
end
cnts.c_catch += 1
cnts.c_catch >= 4 && return 1
update_K!(K, D, regu, s_l, s_u, x_m_lvar, uvar_m_x, ilow, iupp, diag_Q, diagind_K, nvar, ncon)
X1X2_to_D!(D, x_m_lvar, uvar_m_x, ilow, iupp)
K.data.nzval[view(diagind_K, 1:nvar)] .*= D .^ 2
update_diag_K22!(K, regu.δ, diagind_K, nvar, ncon)
generic_factorize!(K, K_fact)
end
else # no Regularization
generic_factorize!(K, K_fact)
end
return 0 # factorization succeeded
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 5423 | export K2_5StructuredParams
"""
Type to use the K2.5 formulation with a structured Krylov method, using the package
[`Krylov.jl`](https://github.com/JuliaSmoothOptimizers/Krylov.jl).
This only works for solving Linear Problems.
The outer constructor
K2_5StructuredParams(; uplo = :L, kmethod = :trimr, rhs_scale = true,
atol0 = 1.0e-4, rtol0 = 1.0e-4,
atol_min = 1.0e-10, rtol_min = 1.0e-10,
ρ0 = sqrt(eps()) * 1e5, δ0 = sqrt(eps()) * 1e5,
ρ_min = 1e2 * sqrt(eps()), δ_min = 1e2 * sqrt(eps()),
itmax = 0, mem = 20)
creates a [`RipQP.SolverParams`](@ref).
The available methods are:
- `:tricg`
- `:trimr`
- `:gpmr`
The `mem` argument sould be used only with `gpmr`.
"""
mutable struct K2_5StructuredParams{T} <: AugmentedParams{T}
uplo::Symbol
kmethod::Symbol
rhs_scale::Bool
atol0::T
rtol0::T
atol_min::T
rtol_min::T
ρ0::T
δ0::T
ρ_min::T
δ_min::T
itmax::Int
mem::Int
end
function K2_5StructuredParams{T}(;
uplo::Symbol = :L,
kmethod::Symbol = :trimr,
rhs_scale::Bool = true,
atol0::T = eps(T)^(1 / 4),
rtol0::T = eps(T)^(1 / 4),
atol_min::T = sqrt(eps(T)),
rtol_min::T = sqrt(eps(T)),
ρ0::T = eps(T)^(1 / 4),
δ0::T = eps(T)^(1 / 4),
ρ_min::T = T(1e2 * sqrt(eps(T))),
δ_min::T = T(1e2 * sqrt(eps(T))),
itmax::Int = 0,
mem::Int = 20,
) where {T <: Real}
return K2_5StructuredParams(
uplo,
kmethod,
rhs_scale,
atol0,
rtol0,
atol_min,
rtol_min,
ρ0,
δ0,
ρ_min,
δ_min,
itmax,
mem,
)
end
K2_5StructuredParams(; kwargs...) = K2_5StructuredParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK2_5Structured{
T <: Real,
S,
Ksol <: KrylovSolver,
L <: AbstractLinearOperator{T},
} <: PreallocatedDataAugmentedKrylovStructured{T, S}
E::S # temporary top-left diagonal
invE::S
sqrtX1X2::S # vector to scale K2 to K2.5
AsqrtX1X2::L
ξ1::S
ξ2::S
rhs_scale::Bool
regu::Regularization{T}
KS::Ksol
kiter::Int
atol::T
rtol::T
atol_min::T
rtol_min::T
itmax::Int
end
function opAsqrtX1X2tprod!(res, A, v, α, β, sqrtX1X2)
mul!(res, transpose(A), v, α, β)
res .*= sqrtX1X2
end
function PreallocatedData(
sp::K2_5StructuredParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
E = similar(fd.c, id.nvar)
if iconf.mode == :mono
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), :classic)
E .= T(1.0e0) / 2
else
regu =
Regularization(T(sp.ρ0), T(sp.δ0), T(sqrt(eps(T)) * 1e0), T(sqrt(eps(T)) * 1e0), :classic)
E .= T(1.0e-2)
end
if regu.δ_min == zero(T) # gsp for gpmr
regu.δ = zero(T)
end
invE = similar(E)
@. invE = one(T) / E
sqrtX1X2 = fill!(similar(fd.c), one(T))
ξ1 = similar(fd.c, id.nvar)
ξ2 = similar(fd.c, id.ncon)
KS = init_Ksolver(fd.A', fd.b, sp)
AsqrtX1X2 = LinearOperator(
T,
id.ncon,
id.nvar,
false,
false,
(res, v, α, β) -> mul!(res, fd.A, v .* sqrtX1X2, α, β),
(res, v, α, β) -> opAsqrtX1X2tprod!(res, fd.A, v, α, β, sqrtX1X2),
)
return PreallocatedDataK2_5Structured(
E,
invE,
sqrtX1X2,
AsqrtX1X2,
ξ1,
ξ2,
sp.rhs_scale,
regu,
KS,
0,
T(sp.atol0),
T(sp.rtol0),
T(sp.atol_min),
T(sp.rtol_min),
sp.itmax,
)
end
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK2_5Structured{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
pad.ξ1 .= @views step == :init ? fd.c : dd[1:(id.nvar)] .* pad.sqrtX1X2
pad.ξ2 .= @views (step == :init && all(dd[(id.nvar + 1):end] .== zero(T))) ? one(T) :
dd[(id.nvar + 1):end]
if pad.rhs_scale
rhsNorm = sqrt(norm(pad.ξ1)^2 + norm(pad.ξ2)^2)
pad.ξ1 ./= rhsNorm
pad.ξ2 ./= rhsNorm
end
(step !== :cc) && (pad.kiter = 0)
ksolve!(
pad.KS,
pad.AsqrtX1X2',
pad.ξ1,
pad.ξ2,
Diagonal(pad.invE),
(one(T) / pad.regu.δ) .* I,
verbose = 0,
atol = pad.atol,
rtol = pad.rtol,
gsp = (pad.regu.δ == zero(T)),
itmax = pad.itmax,
)
update_kresiduals_history!(
res,
pad.E,
fd.A,
pad.regu.δ,
pad.KS.x,
pad.KS.y,
pad.ξ1,
pad.ξ2,
id.nvar,
)
pad.kiter += niterations(pad.KS)
if pad.rhs_scale
kunscale!(pad.KS.x, rhsNorm)
kunscale!(pad.KS.y, rhsNorm)
end
@. dd[1:(id.nvar)] = pad.KS.x * pad.sqrtX1X2
dd[(id.nvar + 1):end] .= pad.KS.y
return 0
end
function update_pad!(
pad::PreallocatedDataK2_5Structured{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
update_krylov_tol!(pad)
pad.sqrtX1X2 .= one(T)
@. pad.sqrtX1X2[id.ilow] *= sqrt(itd.x_m_lvar)
@. pad.sqrtX1X2[id.iupp] *= sqrt(itd.uvar_m_x)
pad.E .= pad.regu.ρ
@. pad.E[id.ilow] += pt.s_l / itd.x_m_lvar
@. pad.E[id.iupp] += pt.s_u / itd.uvar_m_x
@. pad.E *= pad.sqrtX1X2^2
@. pad.invE = one(T) / pad.E
return 0
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 845 | abstract type AugmentedParams{T} <: SolverParams{T} end
abstract type AugmentedKrylovParams{T, PT <: AbstractPreconditioner} <: AugmentedParams{T} end
abstract type PreallocatedDataAugmented{T <: Real, S} <: PreallocatedData{T, S} end
abstract type PreallocatedDataAugmentedLDL{T <: Real, S} <: PreallocatedDataAugmented{T, S} end
uses_krylov(pad::PreallocatedDataAugmentedLDL) = false
include("K2LDL.jl")
include("K2_5LDL.jl")
include("K2LDLDense.jl")
abstract type PreallocatedDataAugmentedKrylov{T <: Real, S} <: PreallocatedDataAugmented{T, S} end
uses_krylov(pad::PreallocatedDataAugmentedKrylov) = true
abstract type PreallocatedDataAugmentedKrylovStructured{T <: Real, S} <:
PreallocatedDataAugmented{T, S} end
include("K2Krylov.jl")
include("K2_5Krylov.jl")
include("K2Structured.jl")
include("K2_5Structured.jl")
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 11879 | export LDLGPU
"""
preconditioner = LDLGPU(; T = Float32, pos = :C, warm_start = true)
Preconditioner for [`K2KrylovParams`](@ref) using a LDL factorization in precision `T`.
The `pos` argument is used to choose the type of preconditioning with an unsymmetric Krylov method.
It can be `:C` (center), `:L` (left) or `:R` (right).
The `warm_start` argument tells RipQP to solve the system with the LDL factorization before using the Krylov method with the LDLFactorization as a preconditioner.
"""
mutable struct LDLGPU{FloatType <: DataType} <: AbstractPreconditioner
T::FloatType
pos::Symbol # :L (left), :R (right) or :C (center)
warm_start::Bool
end
LDLGPU(; T::DataType = Float32, pos = :C, warm_start = true) = LDLGPU(T, pos, warm_start)
mutable struct LDLGPUData{
T <: Real,
S,
Tlow,
Op <: Union{LinearOperator, LRPrecond},
F <: FactorizationData{Tlow},
} <: PreconditionerData{T, S}
K::Symmetric{T, SparseMatrixCSC{T, Int}}
L::UnitLowerTriangular{Tlow, CUDA.CUSPARSE.CuSparseMatrixCSC{Tlow, Int32}} # T or Tlow?
d::CUDA.CuVector{Tlow, CUDA.Mem.DeviceBuffer}
tmp_res::CUDA.CuVector{Tlow, CUDA.Mem.DeviceBuffer}
tmp_v::CUDA.CuVector{Tlow, CUDA.Mem.DeviceBuffer}
regu::Regularization{Tlow}
K_fact::F # factorized matrix
fact_fail::Bool # true if factorization failed
warm_start::Bool
P::Op
end
precond_name(pdat::LDLGPUData{T, S, Tlow}) where {T, S, Tlow} =
string(Tlow, " ", string(typeof(pdat).name.name)[1:(end - 4)])
lowtype(pdat::LDLGPUData{T, S, Tlow}) where {T, S, Tlow} = Tlow
function ldl_ldiv_gpu!(res, L, d, x, P, Pinv, tmp_res, tmp_v)
@views copyto!(tmp_res, x[P])
ldiv!(tmp_v, L, tmp_res)
tmp_v ./= d
ldiv!(tmp_res, L', tmp_v)
@views copyto!(res, tmp_res[Pinv])
end
function PreconditionerData(
sp::AugmentedKrylovParams{<:Real, <:LDLGPU},
id::QM_IntData,
fd::QM_FloatData{T},
regu::Regularization{T},
D::AbstractVector{T},
K,
) where {T <: Real}
Tlow = sp.preconditioner.T
@assert fd.uplo == :U
regu_precond = Regularization(
-Tlow(eps(Tlow)^(3 / 4)),
Tlow(eps(Tlow)^(0.45)),
sqrt(eps(Tlow)),
sqrt(eps(Tlow)),
:dynamic,
)
K_fact = @timeit_debug to "LDL analyze" init_fact(K, LDLFact(), Tlow)
K_fact.LDL.r1, K_fact.LDL.r2 = regu_precond.ρ, regu_precond.δ
K_fact.LDL.tol = Tlow(eps(Tlow))
K_fact.LDL.n_d = id.nvar
generic_factorize!(K, K_fact)
L = UnitLowerTriangular(
CUDA.CUSPARSE.CuSparseMatrixCSC(
CuVector(K_fact.LDL.Lp),
CuVector(K_fact.LDL.Li),
CuVector{Tlow}(K_fact.LDL.Lx),
size(K),
),
)
if !(
sp.kmethod == :gmres || sp.kmethod == :dqgmres || sp.kmethod == :gmresir || sp.kmethod == :ir
)
d = abs.(CuVector(K_fact.LDL.d))
else
d = CuVector(K_fact.LDL.d)
end
tmp_res = similar(d)
tmp_v = similar(d)
P = LinearOperator(
Tlow,
id.nvar + id.ncon,
id.nvar + id.ncon,
true,
true,
(res, v, α, β) -> ldl_ldiv_gpu!(res, L, d, v, K_fact.LDL.P, K_fact.LDL.pinv, tmp_res, tmp_v),
)
return LDLGPUData{T, typeof(fd.c), Tlow, typeof(P), typeof(K_fact)}(
K,
L,
d,
tmp_res,
tmp_v,
regu_precond,
K_fact,
false,
sp.preconditioner.warm_start,
P,
)
end
function update_preconditioner!(
pdat::LDLGPUData{T},
pad::PreallocatedData{T},
itd::IterData{T},
pt::Point{T},
id::QM_IntData,
fd::Abstract_QM_FloatData{T},
cnts::Counters,
) where {T <: Real}
Tlow = lowtype(pad.pdat)
pad.pdat.regu.ρ, pad.pdat.regu.δ =
max(pad.regu.ρ, sqrt(eps(Tlow))), max(pad.regu.ρ, sqrt(eps(Tlow)))
out = factorize_K2!(
pad.pdat.K,
pad.pdat.K_fact,
pad.D,
pad.mt.diag_Q,
pad.mt.diagind_K,
pad.pdat.regu,
pt.s_l,
pt.s_u,
itd.x_m_lvar,
itd.uvar_m_x,
id.ilow,
id.iupp,
id.ncon,
id.nvar,
cnts,
itd.qp,
) # update D and factorize K
copyto!(pad.pdat.L.data.nzVal, pad.pdat.K_fact.LDL.Lx)
copyto!(pad.pdat.d, pad.pdat.K_fact.LDL.d)
if !(
typeof(pad.KS) <: GmresSolver ||
typeof(pad.KS) <: DqgmresSolver ||
typeof(pad.KS) <: GmresIRSolver ||
typeof(pad.KS) <: IRSolver
)
@. pad.pdat.d = abs(pad.pdat.d)
end
if out == 1
pad.pdat.fact_fail = true
return out
end
if pad.pdat.warm_start
ldl_ldiv_gpu!(
pad.KS.x,
pdat.L,
pdat.d,
pad.rhs,
pdat.K_fact.LDL.P,
pdat.K_fact.LDL.pinv,
pdat.tmp_res,
pdat.tmp_v,
)
warm_start!(pad.KS, pad.KS.x)
end
end
mutable struct K2KrylovGPUParams{T, PT} <: AugmentedKrylovParams{T, PT}
uplo::Symbol
kmethod::Symbol
preconditioner::PT
rhs_scale::Bool
equilibrate::Bool
atol0::T
rtol0::T
atol_min::T
rtol_min::T
ρ0::T
δ0::T
ρ_min::T
δ_min::T
itmax::Int
mem::Int
verbose::Int
end
function K2KrylovGPUParams{T}(;
uplo::Symbol = :U,
kmethod::Symbol = :minres,
preconditioner::AbstractPreconditioner = Identity(),
rhs_scale::Bool = true,
equilibrate::Bool = true,
atol0::T = T(1.0e-4),
rtol0::T = T(1.0e-4),
atol_min::T = T(1.0e-10),
rtol_min::T = T(1.0e-10),
ρ0::T = T(sqrt(eps()) * 1e5),
δ0::T = T(sqrt(eps()) * 1e5),
ρ_min::T = 1e2 * sqrt(eps(T)),
δ_min::T = 1e2 * sqrt(eps(T)),
itmax::Int = 0,
mem::Int = 20,
verbose::Int = 0,
) where {T <: Real}
return K2KrylovGPUParams(
uplo,
kmethod,
preconditioner,
rhs_scale,
equilibrate,
atol0,
rtol0,
atol_min,
rtol_min,
ρ0,
δ0,
ρ_min,
δ_min,
itmax,
mem,
verbose,
)
end
K2KrylovGPUParams(; kwargs...) = K2KrylovGPUParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK2KrylovGPU{
T <: Real,
S,
M <: Union{LinearOperator{T}, AbstractMatrix{T}},
MT <: Union{MatrixTools{T}, Int},
Pr <: PreconditionerData,
Ksol <: KrylovSolver,
} <: PreallocatedDataAugmentedKrylov{T, S}
pdat::Pr
D::S # temporary top-left diagonal
Dcpu::Vector{T}
rhs::S
rhs_scale::Bool
equilibrate::Bool
regu::Regularization{T}
δv::Vector{T}
K::M # augmented matrix
Kcpu::Symmetric{T, SparseMatrixCSC{T, Int}}
diagQnz::S
mt::MT
deq::S
KS::Ksol
kiter::Int
atol::T
rtol::T
atol_min::T
rtol_min::T
itmax::Int
verbose::Int
end
function opK2eqprod!(
res::AbstractVector{T},
nvar::Int,
Q::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
D::AbstractVector{T},
A::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
δv::AbstractVector{T},
deq::AbstractVector{T},
v::AbstractVector{T},
vtmp::AbstractVector{T},
uplo::Symbol,
equilibrate::Bool,
) where {T}
equilibrate && (vtmp .= deq .* v)
@views mul!(res[1:nvar], Q, vtmp[1:nvar], -one(T), zero(T))
@. res[1:nvar] += @views D * vtmp[1:nvar]
if uplo == :U
@views mul!(res[1:nvar], A, vtmp[(nvar + 1):end], one(T), one(T))
@views mul!(res[(nvar + 1):end], A', vtmp[1:nvar], one(T), zero(T))
else
@views mul!(res[1:nvar], A', vtmp[(nvar + 1):end], one(T), one(T))
@views mul!(res[(nvar + 1):end], A, vtmp[1:nvar], one(T), zero(T))
end
res[(nvar + 1):end] .+= @views δv[1] .* vtmp[(nvar + 1):end]
equilibrate && (res .*= deq)
end
function PreallocatedData(
sp::K2KrylovGPUParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
@assert fd.uplo == :U
# init Regularization values
D = similar(fd.c, id.nvar)
if iconf.mode == :mono
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), :classic)
D .= -T(1.0e0) / 2
else
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), :hybrid)
D .= -T(1.0e-2)
end
Dcpu = Vector(D)
δv = [regu.δ] # put it in a Vector so that we can modify it without modifying opK2prod!
Kcpu, diagind_K, diag_Q = get_K2_matrixdata(id, Dcpu, fd.Q, fd.A, regu, sp.uplo, T)
if sp.equilibrate
Deq = Diagonal(Vector{T}(undef, id.nvar + id.ncon))
Deq.diag .= one(T)
C_eq = Diagonal(Vector{T}(undef, id.nvar + id.ncon))
else
Deq = Diagonal(Vector{T}(undef, 0))
C_eq = Diagonal(Vector{T}(undef, 0))
end
mt = MatrixTools(diag_Q, diagind_K, Deq, C_eq)
deq = CuVector(Deq.diag)
vtmp = similar(D, id.nvar + id.ncon)
K = LinearOperator(
T,
id.nvar + id.ncon,
id.nvar + id.ncon,
true,
true,
(res, v, α, β) ->
opK2eqprod!(res, id.nvar, fd.Q, D, fd.A, δv, deq, v, vtmp, fd.uplo, sp.equilibrate),
)
diagQnz = similar(deq, length(diag_Q.nzval))
copyto!(diagQnz, diag_Q.nzval)
rhs = similar(fd.c, id.nvar + id.ncon)
KS = @timeit_debug to "krylov solver setup" init_Ksolver(K, rhs, sp)
pdat = @timeit_debug to "preconditioner setup" PreconditionerData(sp, id, fd, regu, D, Kcpu)
return PreallocatedDataK2KrylovGPU(
pdat,
D,
Dcpu,
rhs,
sp.rhs_scale,
sp.equilibrate,
regu,
δv,
K, #K
Kcpu,
diagQnz,
mt,
deq,
KS,
0,
T(sp.atol0),
T(sp.rtol0),
T(sp.atol_min),
T(sp.rtol_min),
sp.itmax,
sp.verbose,
)
end
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK2KrylovGPU{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
pad.rhs .= pad.equilibrate ? dd .* pad.deq : dd
if pad.rhs_scale
rhsNorm = kscale!(pad.rhs)
end
if step !== :cc
@timeit_debug to "preconditioner update" update_preconditioner!(
pad.pdat,
pad,
itd,
pt,
id,
fd,
cnts,
)
end
@timeit_debug to "Krylov solve" ksolve!(
pad.KS,
pad.K,
pad.rhs,
pad.pdat.P,
verbose = pad.verbose,
atol = pad.atol,
rtol = pad.rtol,
itmax = pad.itmax,
)
pad.kiter += niterations(pad.KS)
update_kresiduals_history!(res, pad.K, pad.KS.x, pad.rhs)
if pad.rhs_scale
kunscale!(pad.KS.x, rhsNorm)
end
if pad.equilibrate
if typeof(pad.Kcpu) <: Symmetric{T, SparseMatrixCSC{T, Int}} && step !== :aff
rdiv!(pad.Kcpu.data, pad.mt.Deq)
ldiv!(pad.mt.Deq, pad.Kcpu.data)
end
pad.KS.x .*= pad.deq
end
dd .= pad.KS.x
return 0
end
function update_pad!(
pad::PreallocatedDataK2KrylovGPU{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
update_krylov_tol!(pad)
update_D!(pad.D, itd.x_m_lvar, itd.uvar_m_x, pt.s_l, pt.s_u, pad.regu.ρ, id.ilow, id.iupp)
pad.δv[1] = pad.regu.δ
pad.D[pad.mt.diag_Q.nzind] .-= pad.diagQnz
copyto!(pad.Dcpu, pad.D)
update_diag_K11!(pad.Kcpu, pad.Dcpu, pad.mt.diagind_K, id.nvar)
update_diag_K22!(pad.Kcpu, pad.regu.δ, pad.mt.diagind_K, id.nvar, id.ncon)
if pad.equilibrate
pad.mt.Deq.diag .= one(T)
@timeit_debug to "equilibration" equilibrate!(
pad.Kcpu,
pad.mt.Deq,
pad.mt.C_eq;
ϵ = T(1.0e-2),
max_iter = 15,
)
copyto!(pad.deq, pad.mt.Deq.diag)
end
return 0
end
function get_K2_matrixdata(
id::QM_IntData,
D::AbstractVector,
Q::Symmetric,
A::CUDA.CUSPARSE.AbstractCuSparseMatrix,
regu::Regularization,
uplo::Symbol,
::Type{T},
) where {T}
Qcpu = Symmetric(SparseMatrixCSC(Q.data), uplo)
Acpu = SparseMatrixCSC(A)
diag_Q = get_diag_Q(Qcpu)
K = create_K2(id, D, Qcpu.data, Acpu, diag_Q, regu, uplo, T)
diagind_K = get_diagind_K(K, uplo)
return K, diagind_K, diag_Q
end
# function get_mat_QPData(A::CUDA.CUSPARSE.CuSparseMatrixCSC, H, nvar::Int, ncon::Int, uplo::Symbol)
# fdA = uplo == :U ? CUDA.CUSPARSE.CuSparseMatrixCSC(SparseMatrixCSC(transpose(SparseMatrixCSC(A)))) : A
# fdH = uplo == :U ? CUDA.CUSPARSE.CuSparseMatrixCSC(SparseMatrixCSC(transpose(SparseMatrixCSC(H)))) : H
# return fdA, Symmetric(fdH, uplo)
# end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 4526 | # (A D⁻¹ Aᵀ + δI) Δy = A D⁻¹ ξ₁ + ξ₂
# where D = s_l (x - lvar)⁻¹ + s_u (uvar - x)⁻¹ + ρI,
# and the right hand side of K2 is rhs = [ξ₁]
# [ξ₂]
export K1CholParams
"""
Type to use the K1 formulation with a Cholesky factorization.
The outer constructor
sp = K1CholParams(; fact_alg = LDLFact(regul = :classic),
ρ0 = sqrt(eps()) * 1e5, δ0 = sqrt(eps()) * 1e5,
ρ_min = sqrt(eps()), δ_min = sqrt(eps()))
creates a [`RipQP.SolverParams`](@ref).
"""
mutable struct K1CholParams{T, Fact} <: NormalParams{T}
uplo::Symbol
fact_alg::Fact
ρ0::T
δ0::T
ρ_min::T
δ_min::T
function K1CholParams(fact_alg::AbstractFactorization, ρ0::T, δ0::T, ρ_min::T, δ_min::T) where {T}
return new{T, typeof(fact_alg)}(get_uplo(fact_alg), fact_alg, ρ0, δ0, ρ_min, δ_min)
end
end
K1CholParams{T}(;
fact_alg::AbstractFactorization = LDLFact(:classic),
ρ0::T = (T == Float16) ? one(T) : T(sqrt(eps()) * 1e5),
δ0::T = (T == Float16) ? one(T) : T(sqrt(eps()) * 1e5),
ρ_min::T = sqrt(eps(T)) * 10,
δ_min::T = sqrt(eps(T)) * 10,
) where {T} = K1CholParams(fact_alg, ρ0, δ0, ρ_min, δ_min)
K1CholParams(; kwargs...) = K1CholParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK1Chol{T <: Real, S, M <: AbstractMatrix{T}, F} <:
PreallocatedDataNormalChol{T, S}
D::S
regu::Regularization{T}
K::Symmetric{T, M} # augmented matrix
K_fact::F # factorized matrix
diagind_K::Vector{Int} # diagonal indices of J
rhs::S
ξ1tmp::S
Aj::S
end
# outer constructor
function PreallocatedData(
sp::K1CholParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
D = similar(fd.c, id.nvar)
D .= T(1.0e0) / 2
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), sp.fact_alg.regul)
if sp.uplo == :L
K = fd.A * fd.A' + regu.δ * I
K = Symmetric(tril(K), sp.uplo)
elseif sp.uplo == :U
K = fd.A' * fd.A + regu.δ * I
K = Symmetric(triu(K), sp.uplo)
end
diagind_K = get_diagind_K(K, sp.uplo)
K_fact = init_fact(K, sp.fact_alg)
generic_factorize!(K, K_fact)
rhs = similar(D, id.ncon)
ξ1tmp = similar(D)
Aj = similar(D)
return PreallocatedDataK1Chol(D, regu, K, K_fact, diagind_K, rhs, ξ1tmp, Aj)
end
# function used to solve problems
# solver LDLFactorization
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK1Chol{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
@. pad.ξ1tmp = @views dd[1:(id.nvar)] / pad.D
if fd.uplo == :L
mul!(pad.rhs, fd.A, pad.ξ1tmp)
else
mul!(pad.rhs, fd.A', pad.ξ1tmp)
end
pad.rhs .+= @views dd[(id.nvar + 1):end]
ldiv!(pad.K_fact, pad.rhs)
if fd.uplo == :U
@views mul!(dd[1:(id.nvar)], fd.A, pad.rhs, one(T), -one(T))
else
@views mul!(dd[1:(id.nvar)], fd.A', pad.rhs, one(T), -one(T))
end
dd[1:(id.nvar)] ./= pad.D
dd[(id.nvar + 1):end] .= pad.rhs
return 0
end
function update_pad!(
pad::PreallocatedDataK1Chol{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
pad.D .= pad.regu.ρ
@. pad.D[id.ilow] += pt.s_l / itd.x_m_lvar
@. pad.D[id.iupp] += pt.s_u / itd.uvar_m_x
updateK1!(pad.K, pad.D, fd.A, pad.Aj, pad.regu.δ, id.ncon)
generic_factorize!(pad.K, pad.K_fact)
return 0
end
# (AAᵀ)_(i,j) = ∑ A_(i,k) D_(k,k) A_(j,k)
# transpose A if uplo = U
function updateK1!(
K::Symmetric{T, <:SparseMatrixCSC{T}},
D::AbstractVector{T},
A::SparseMatrixCSC{T},
Aj,
δ,
ncon,
) where {T}
K_colptr, K_rowval, K_nzval = K.data.colptr, K.data.rowval, K.data.nzval
A_colptr, A_rowval, A_nzval = A.colptr, A.rowval, A.nzval
for j = 1:ncon
Aj .= zero(T)
for kA = A_colptr[j]:(A_colptr[j + 1] - 1)
k = A_rowval[kA]
Aj[k] = A_nzval[kA] / D[k]
end
# Aj is col j of A divided by D
for k2 = K_colptr[j]:(K_colptr[j + 1] - 1)
i = K_rowval[k2]
i ≤ j || continue
K_nzval[k2] = (i == j) ? δ : zero(T)
for l = A_colptr[i]:(A_colptr[i + 1] - 1)
k = A_rowval[l]
K_nzval[k2] += A_nzval[l] * Aj[k]
end
end
end
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 3325 | # (A D⁻¹ Aᵀ + δI) Δy = A D⁻¹ ξ₁ + ξ₂
# where D = s_l (x - lvar)⁻¹ + s_u (uvar - x)⁻¹ + ρI,
# and the right hand side of K2 is rhs = [ξ₁]
# [ξ₂]
export K1CholDenseParams
"""
Type to use the K1 formulation with a dense Cholesky factorization.
The input QuadraticModel should have `lcon .== ucon`.
The outer constructor
sp = K1CholDenseParams(; ρ0 = sqrt(eps()) * 1e5, δ0 = sqrt(eps()) * 1e5)
creates a [`RipQP.SolverParams`](@ref).
"""
mutable struct K1CholDenseParams{T} <: NormalParams{T}
uplo::Symbol
ρ0::T
δ0::T
end
function K1CholDenseParams{T}(;
ρ0::T = T(sqrt(eps()) * 1e5),
δ0::T = T(sqrt(eps()) * 1e5),
) where {T}
uplo = :L # mandatory for LDL fact
return K1CholDenseParams(uplo, ρ0, δ0)
end
K1CholDenseParams(; kwargs...) = K1CholDenseParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK1CholDense{T <: Real, S, M <: AbstractMatrix{T}} <:
PreallocatedDataNormalChol{T, S}
D::S # temporary top-left diagonal
invD::Diagonal{T, S}
AinvD::M
rhs::S
regu::Regularization{T}
K::M # augmented matrix
diagindK::StepRange{Int, Int}
tmpldiv::S
end
# outer constructor
function PreallocatedData(
sp::K1CholDenseParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
D = similar(fd.c, id.nvar)
if iconf.mode == :mono
regu = Regularization(T(sp.ρ0), T(sp.δ0), 1e-5 * sqrt(eps(T)), 1e0 * sqrt(eps(T)), :classic)
D .= T(1.0e0) / 2
else
regu =
Regularization(T(sp.ρ0), T(sp.δ0), T(sqrt(eps(T)) * 1e0), T(sqrt(eps(T)) * 1e0), :classic)
D .= T(1.0e-2)
end
invD = Diagonal(one(T) ./ D)
AinvD = fd.A * invD
K = AinvD * fd.A'
diagindK = diagind(K)
K[diagindK] .+= regu.δ
cholesky!(Symmetric(K))
return PreallocatedDataK1CholDense(
D,
invD,
AinvD,
similar(D, id.ncon),
regu,
K, #K
diagindK,
similar(D, id.ncon),
)
end
# function used to solve problems
# solver LDLFactorization
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK1CholDense{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
pad.rhs .= @views dd[(id.nvar + 1):end]
@views mul!(pad.rhs, pad.AinvD, dd[1:(id.nvar)], one(T), one(T))
ldiv!(pad.tmpldiv, UpperTriangular(pad.K)', pad.rhs)
ldiv!(pad.rhs, UpperTriangular(pad.K), pad.tmpldiv)
@views mul!(dd[1:(id.nvar)], fd.A', pad.rhs, one(T), -one(T))
dd[1:(id.nvar)] ./= pad.D
dd[(id.nvar + 1):end] .= pad.rhs
return 0
end
function update_pad!(
pad::PreallocatedDataK1CholDense{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
pad.D .= pad.regu.ρ
@. pad.D[id.ilow] += pt.s_l / itd.x_m_lvar
@. pad.D[id.iupp] += pt.s_u / itd.uvar_m_x
@. pad.invD.diag = one(T) / pad.D
mul!(pad.AinvD, fd.A, pad.invD)
mul!(pad.K, pad.AinvD, fd.A')
pad.K[pad.diagindK] .+= pad.regu.δ
cholesky!(Symmetric(pad.K))
return 0
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 5572 | # (A D⁻¹ Aᵀ + δI) Δy = A D⁻¹ ξ₁ + ξ₂
# where D = s_l (x - lvar)⁻¹ + s_u (uvar - x)⁻¹ + ρI,
# and the right hand side of K2 is rhs = [ξ₁]
# [ξ₂]
export K1KrylovParams
"""
Type to use the K1 formulation with a Krylov method, using the package
[`Krylov.jl`](https://github.com/JuliaSmoothOptimizers/Krylov.jl).
The outer constructor
K1KrylovParams(; uplo = :L, kmethod = :cg, preconditioner = Identity(),
rhs_scale = true,
atol0 = 1.0e-4, rtol0 = 1.0e-4,
atol_min = 1.0e-10, rtol_min = 1.0e-10,
ρ0 = sqrt(eps()) * 1e5, δ0 = sqrt(eps()) * 1e5,
ρ_min = 1e2 * sqrt(eps()), δ_min = 1e2 * sqrt(eps()),
itmax = 0, mem = 20)
creates a [`RipQP.SolverParams`](@ref).
The available methods are:
- `:cg`
- `:cg_lanczos`
- `:cr`
- `:minres`
- `:minres_qlp`
- `:symmlq`
"""
mutable struct K1KrylovParams{T, PT} <: NormalKrylovParams{T, PT}
uplo::Symbol
kmethod::Symbol
preconditioner::PT
rhs_scale::Bool
atol0::T
rtol0::T
atol_min::T
rtol_min::T
ρ0::T
δ0::T
ρ_min::T
δ_min::T
itmax::Int
mem::Int
end
function K1KrylovParams{T}(;
uplo::Symbol = :L,
kmethod::Symbol = :cg,
preconditioner::AbstractPreconditioner = Identity(),
rhs_scale::Bool = true,
atol0::T = eps(T)^(1 / 4),
rtol0::T = eps(T)^(1 / 4),
atol_min::T = sqrt(eps(T)),
rtol_min::T = sqrt(eps(T)),
ρ0::T = T(sqrt(eps()) * 1e5),
δ0::T = T(sqrt(eps()) * 1e5),
ρ_min::T = T(1e3 * sqrt(eps())),
δ_min::T = T(1e4 * sqrt(eps())),
itmax::Int = 0,
mem::Int = 20,
) where {T <: Real}
return K1KrylovParams(
uplo,
kmethod,
preconditioner,
rhs_scale,
atol0,
rtol0,
atol_min,
rtol_min,
ρ0,
δ0,
ρ_min,
δ_min,
itmax,
mem,
)
end
K1KrylovParams(; kwargs...) = K1KrylovParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK1Krylov{T <: Real, S, L <: LinearOperator, Ksol <: KrylovSolver} <:
PreallocatedDataNormalKrylov{T, S}
D::S
rhs::S
rhs_scale::Bool
regu::Regularization{T}
δv::Vector{T}
K::L # augmented matrix (LinearOperator)
KS::Ksol
kiter::Int
atol::T
rtol::T
atol_min::T
rtol_min::T
itmax::Int
end
function opK1prod!(
res::AbstractVector{T},
D::AbstractVector{T},
A::Union{AbstractMatrix{T}, AbstractLinearOperator{T}},
δv::AbstractVector{T},
v::AbstractVector{T},
vtmp::AbstractVector{T},
α::T,
β::T,
uplo::Symbol,
) where {T}
if uplo == :U
mul!(vtmp, A, v)
vtmp ./= D
mul!(res, A', vtmp, α, β)
res .+= (α * δv[1]) .* v
else
mul!(vtmp, A', v)
vtmp ./= D
mul!(res, A, vtmp, α, β)
res .+= (α * δv[1]) .* v
end
end
function PreallocatedData(
sp::K1KrylovParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
D = similar(fd.c, id.nvar)
# init Regularization values
if iconf.mode == :mono
regu = Regularization(T(sp.ρ0), T(sp.δ0), T(sp.ρ_min), T(sp.δ_min), :classic)
# Regularization(T(0.), T(0.), T(sp.ρ_min), T(sp.δ_min), :classic)
D .= T(1.0e0) / 2
else
regu =
Regularization(T(sp.ρ0), T(sp.δ0), T(sqrt(eps(T)) * 1e0), T(sqrt(eps(T)) * 1e0), :classic)
D .= T(1.0e-2)
end
δv = [regu.δ] # put it in a Vector so that we can modify it without modifying opK2prod!
K = LinearOperator(
T,
id.ncon,
id.ncon,
true,
true,
(res, v, α, β) -> opK1prod!(res, D, fd.A, δv, v, similar(fd.c), α, β, fd.uplo),
)
rhs = similar(fd.c, id.ncon)
KS = init_Ksolver(K, rhs, sp)
return PreallocatedDataK1Krylov(
D,
rhs,
sp.rhs_scale,
regu,
δv,
K, #K
KS,
0,
T(sp.atol0),
T(sp.rtol0),
T(sp.atol_min),
T(sp.rtol_min),
sp.itmax,
)
end
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK1Krylov{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
pad.rhs .= @views dd[(id.nvar + 1):end]
if fd.uplo == :U
@views mul!(pad.rhs, fd.A', dd[1:(id.nvar)] ./ pad.D, one(T), one(T))
else
@views mul!(pad.rhs, fd.A, dd[1:(id.nvar)] ./ pad.D, one(T), one(T))
end
if pad.rhs_scale
rhsNorm = kscale!(pad.rhs)
end
(step !== :cc) && (pad.kiter = 0)
ksolve!(
pad.KS,
pad.K,
pad.rhs,
I,
verbose = 0,
atol = pad.atol,
rtol = pad.rtol,
itmax = pad.itmax,
)
update_kresiduals_history!(res, pad.K, pad.KS.x, pad.rhs)
pad.kiter += niterations(pad.KS)
if pad.rhs_scale
kunscale!(pad.KS.x, rhsNorm)
end
if fd.uplo == :U
@views mul!(dd[1:(id.nvar)], fd.A, pad.KS.x, one(T), -one(T))
else
@views mul!(dd[1:(id.nvar)], fd.A', pad.KS.x, one(T), -one(T))
end
dd[1:(id.nvar)] ./= pad.D
dd[(id.nvar + 1):end] .= pad.KS.x
return 0
end
function update_pad!(
pad::PreallocatedDataK1Krylov{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
update_krylov_tol!(pad)
pad.δv[1] = pad.regu.δ
pad.D .= pad.regu.ρ
@. pad.D[id.ilow] += pt.s_l / itd.x_m_lvar
@. pad.D[id.iupp] += pt.s_u / itd.uvar_m_x
pad.δv[1] = pad.regu.δ
# update_preconditioner!(pad.pdat, pad, itd, pt, id, fd, cnts)
return 0
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 5085 | export K1_1StructuredParams
"""
Type to use the K1.1 formulation with a structured Krylov method, using the package
[`Krylov.jl`](https://github.com/JuliaSmoothOptimizers/Krylov.jl).
This only works for solving Linear Problems.
The outer constructor
K1_1StructuredParams(; uplo = :L, kmethod = :lsqr, rhs_scale = true,
atol0 = 1.0e-4, rtol0 = 1.0e-4,
atol_min = 1.0e-10, rtol_min = 1.0e-10,
ρ_min = 1e3 * sqrt(eps()), δ_min = 1e4 * sqrt(eps()),
itmax = 0, mem = 20)
creates a [`RipQP.SolverParams`](@ref).
The available methods are:
- `:lslq`
- `:lsqr`
- `:lsmr`
"""
mutable struct K1_1StructuredParams{T} <: NormalParams{T}
uplo::Symbol
kmethod::Symbol
rhs_scale::Bool
atol0::T
rtol0::T
atol_min::T
rtol_min::T
ρ_min::T
δ_min::T
itmax::Int
mem::Int
end
function K1_1StructuredParams{T}(;
uplo::Symbol = :L,
kmethod::Symbol = :lsqr,
rhs_scale::Bool = true,
atol0::T = eps(T)^(1 / 4),
rtol0::T = eps(T)^(1 / 4),
atol_min::T = sqrt(eps(T)) / 100,
rtol_min::T = sqrt(eps(T)) / 100,
ρ_min::T = T(1e3 * sqrt(eps())),
δ_min::T = T(1e4 * sqrt(eps())),
itmax::Int = 0,
mem::Int = 20,
) where {T <: Real}
return K1_1StructuredParams(
uplo,
kmethod,
rhs_scale,
atol0,
rtol0,
atol_min,
rtol_min,
ρ_min,
δ_min,
itmax,
mem,
)
end
K1_1StructuredParams(; kwargs...) = K1_1StructuredParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK1_1Structured{T <: Real, S, Ksol <: KrylovSolver} <:
PreallocatedDataNormalKrylovStructured{T, S}
E::S # temporary top-left diagonal
invE::S
ξ1::S
ξ2::S # todel
Δy0::S
ξ12::S # todel
rhs_scale::Bool
regu::Regularization{T}
KS::Ksol
kiter::Int
atol::T
rtol::T
atol_min::T
rtol_min::T
itmax::Int
end
function PreallocatedData(
sp::K1_1StructuredParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
E = similar(fd.c, id.nvar)
if iconf.mode == :mono
regu =
Regularization(T(sqrt(eps()) * 1e5), T(sqrt(eps()) * 1e5), T(sp.ρ_min), T(sp.δ_min), :classic)
E .= T(1.0e0) / 2
else
regu = Regularization(
T(sqrt(eps()) * 1e5),
T(sqrt(eps()) * 1e5),
T(sqrt(eps(T)) * 1e0),
T(sqrt(eps(T)) * 1e0),
:classic,
)
E .= T(1.0e-2)
end
if regu.δ_min == zero(T) # gsp for gpmr
regu.δ = zero(T)
end
invE = similar(E)
invE .= one(T) ./ E
ξ1 = similar(fd.c, id.nvar)
ξ2 = similar(fd.c, id.ncon)
Δy0 = similar(fd.c, id.ncon)
ξ12 = similar(fd.c, id.nvar)
KS = init_Ksolver(fd.uplo == :U ? fd.A : fd.A', ξ12, sp)
return PreallocatedDataK1_1Structured(
E,
invE,
ξ1,
ξ2,
Δy0,
ξ12,
sp.rhs_scale,
regu,
KS,
0,
T(sp.atol0),
T(sp.rtol0),
T(sp.atol_min),
T(sp.rtol_min),
sp.itmax,
)
end
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK1_1Structured{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
@assert typeof(dda) <: DescentDirectionAllocsIPF
pad.ξ1 .= @views step == :init ? fd.c : dd[1:(id.nvar)]
pad.ξ2 .= @views (step == :init && all(dd[(id.nvar + 1):end] .== zero(T))) ? one(T) :
dd[(id.nvar + 1):end]
if pad.regu.δ == zero(T)
pad.Δy0 .= zero(T)
else
@. pad.Δy0 = -pad.ξ2 / pad.regu.δ
end
if fd.uplo == :U
mul!(pad.ξ12, fd.A, pad.Δy0)
else
mul!(pad.ξ12, fd.A', pad.Δy0)
end
pad.ξ12 .+= pad.ξ1
if pad.rhs_scale
ξ12Norm = kscale!(pad.ξ12)
end
(step !== :cc) && (pad.kiter = 0)
ksolve!(
pad.KS,
fd.uplo == :U ? fd.A : fd.A',
pad.ξ12,
Diagonal(pad.invE),
pad.regu.δ,
verbose = 0,
atol = pad.atol,
rtol = pad.rtol,
itmax = pad.itmax,
)
if pad.rhs_scale
kunscale!(pad.KS.x, ξ12Norm)
end
@. dd[(id.nvar + 1):end] = pad.KS.x - pad.Δy0
if fd.uplo == :U
@views mul!(pad.ξ1, fd.A, dd[(id.nvar + 1):end], one(T), -one(T))
else
@views mul!(pad.ξ1, fd.A', dd[(id.nvar + 1):end], one(T), -one(T))
end
@. dd[1:(id.nvar)] = pad.ξ1 / pad.E
update_kresiduals_history_K1struct!(
res,
fd.uplo == :U ? fd.A' : fd.A,
pad.E,
pad.invE, # tmp storage vector
pad.regu.δ,
pad.KS.x,
pad.ξ12,
:K1_1,
)
pad.kiter += niterations(pad.KS)
return 0
end
function update_pad!(
pad::PreallocatedDataK1_1Structured{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
update_krylov_tol!(pad)
pad.E .= pad.regu.ρ
@. pad.E[id.ilow] += pt.s_l / itd.x_m_lvar
@. pad.E[id.iupp] += pt.s_u / itd.uvar_m_x
@. pad.invE = one(T) / pad.E
return 0
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 4892 | export K1_2StructuredParams
"""
Type to use the K1.2 formulation with a structured Krylov method, using the package
[`Krylov.jl`](https://github.com/JuliaSmoothOptimizers/Krylov.jl).
This only works for solving Linear Problems.
The outer constructor
K1_2StructuredParams(; uplo = :L, kmethod = :craig, rhs_scale = true,
atol0 = 1.0e-4, rtol0 = 1.0e-4,
atol_min = 1.0e-10, rtol_min = 1.0e-10,
ρ_min = 1e3 * sqrt(eps()), δ_min = 1e4 * sqrt(eps()),
itmax = 0, mem = 20)
creates a [`RipQP.SolverParams`](@ref).
The available methods are:
- `:lnlq`
- `:craig`
- `:craigmr`
"""
mutable struct K1_2StructuredParams{T} <: NormalParams{T}
uplo::Symbol
kmethod::Symbol
rhs_scale::Bool
atol0::T
rtol0::T
atol_min::T
rtol_min::T
ρ_min::T
δ_min::T
itmax::Int
mem::Int
end
function K1_2StructuredParams{T}(;
uplo::Symbol = :L,
kmethod::Symbol = :craig,
rhs_scale::Bool = true,
atol0::T = eps(T)^(1 / 4),
rtol0::T = eps(T)^(1 / 4),
atol_min::T = sqrt(eps(T)),
rtol_min::T = sqrt(eps(T)),
ρ_min::T = T(1e3 * sqrt(eps())),
δ_min::T = T(1e4 * sqrt(eps())),
itmax::Int = 0,
mem::Int = 20,
) where {T <: Real}
return K1_2StructuredParams(
uplo,
kmethod,
rhs_scale,
atol0,
rtol0,
atol_min,
rtol_min,
ρ_min,
δ_min,
itmax,
mem,
)
end
K1_2StructuredParams(; kwargs...) = K1_2StructuredParams{Float64}(; kwargs...)
mutable struct PreallocatedDataK1_2Structured{T <: Real, S, Ksol <: KrylovSolver} <:
PreallocatedDataNormalKrylovStructured{T, S}
E::S # temporary top-left diagonal
invE::S
ξ1::S
ξ2::S # todel
Δx0::S
ξ22::S # todel
rhs_scale::Bool
regu::Regularization{T}
KS::Ksol
kiter::Int
atol::T
rtol::T
atol_min::T
rtol_min::T
itmax::Int
end
function PreallocatedData(
sp::K1_2StructuredParams,
fd::QM_FloatData{T},
id::QM_IntData,
itd::IterData{T},
pt::Point{T},
iconf::InputConfig{Tconf},
) where {T <: Real, Tconf <: Real}
# init Regularization values
E = similar(fd.c, id.nvar)
if iconf.mode == :mono
regu =
Regularization(T(sqrt(eps()) * 1e5), T(sqrt(eps()) * 1e5), T(sp.ρ_min), T(sp.δ_min), :classic)
E .= T(1.0e0) / 2
else
regu = Regularization(
T(sqrt(eps()) * 1e5),
T(sqrt(eps()) * 1e5),
T(sqrt(eps(T)) * 1e0),
T(sqrt(eps(T)) * 1e0),
:classic,
)
E .= T(1.0e-2)
end
if regu.δ_min == zero(T) # gsp for gpmr
regu.δ = zero(T)
end
invE = similar(E)
invE .= one(T) ./ E
ξ1 = similar(fd.c, id.nvar)
ξ2 = similar(fd.c, id.ncon)
Δx0 = similar(fd.c, id.nvar)
ξ22 = similar(fd.c, id.ncon)
KS = init_Ksolver(fd.uplo == :U ? fd.A' : fd.A, ξ22, sp)
return PreallocatedDataK1_2Structured(
E,
invE,
ξ1,
ξ2,
Δx0,
ξ22,
sp.rhs_scale,
regu,
KS,
0,
T(sp.atol0),
T(sp.rtol0),
T(sp.atol_min),
T(sp.rtol_min),
sp.itmax,
)
end
function solver!(
dd::AbstractVector{T},
pad::PreallocatedDataK1_2Structured{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
step::Symbol,
) where {T <: Real}
@assert typeof(dda) <: DescentDirectionAllocsIPF
pad.ξ1 .= @views step == :init ? fd.c : dd[1:(id.nvar)]
pad.ξ2 .= @views (step == :init && all(dd[(id.nvar + 1):end] .== zero(T))) ? one(T) :
dd[(id.nvar + 1):end]
pad.Δx0 .= pad.ξ1 ./ pad.E
if fd.uplo == :U
mul!(pad.ξ22, fd.A', pad.Δx0)
else
mul!(pad.ξ22, fd.A, pad.Δx0)
end
pad.ξ22 .+= pad.ξ2
if pad.rhs_scale
ξ22Norm = kscale!(pad.ξ22)
end
(step !== :cc) && (pad.kiter = 0)
ksolve!(
pad.KS,
fd.uplo == :U ? fd.A' : fd.A,
pad.ξ22,
Diagonal(pad.invE),
pad.regu.δ,
verbose = 0,
atol = pad.atol,
rtol = pad.rtol,
itmax = pad.itmax,
)
if pad.rhs_scale
kunscale!(pad.KS.x, ξ22Norm)
kunscale!(pad.KS.y, ξ22Norm)
end
dd[(id.nvar + 1):end] .= pad.KS.y
@. dd[1:(id.nvar)] = pad.KS.x - pad.Δx0
update_kresiduals_history_K1struct!(
res,
fd.uplo == :U ? fd.A' : fd.A,
pad.E,
pad.invE, # tmp storage vector
pad.regu.δ,
pad.KS.y,
pad.ξ22,
:K1_2,
)
# kunscale!(pad.KS.x, rhsNorm)
pad.kiter += niterations(pad.KS)
return 0
end
function update_pad!(
pad::PreallocatedDataK1_2Structured{T},
dda::DescentDirectionAllocs{T},
pt::Point{T},
itd::IterData{T},
fd::Abstract_QM_FloatData{T},
id::QM_IntData,
res::AbstractResiduals{T},
cnts::Counters,
) where {T <: Real}
if cnts.k != 0
update_regu!(pad.regu)
end
update_krylov_tol!(pad)
pad.E .= pad.regu.ρ
@. pad.E[id.ilow] += pt.s_l / itd.x_m_lvar
@. pad.E[id.iupp] += pt.s_u / itd.uvar_m_x
@. pad.invE = one(T) / pad.E
return 0
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 754 | abstract type NormalParams{T} <: SolverParams{T} end
abstract type NormalKrylovParams{T, PT <: AbstractPreconditioner} <: NormalParams{T} end
abstract type PreallocatedDataNormal{T <: Real, S} <: PreallocatedData{T, S} end
abstract type PreallocatedDataNormalChol{T <: Real, S} <: PreallocatedDataNormal{T, S} end
uses_krylov(pad::PreallocatedDataNormalChol) = false
include("K1CholDense.jl")
include("K1Chol.jl")
abstract type PreallocatedDataNormalKrylov{T <: Real, S} <: PreallocatedDataNormal{T, S} end
uses_krylov(pad::PreallocatedDataNormalKrylov) = true
abstract type PreallocatedDataNormalKrylovStructured{T <: Real, S} <: PreallocatedDataNormal{T, S} end
include("K1Krylov.jl")
include("K1_1Structured.jl")
include("K1_2Structured.jl")
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 3640 | export AbstractFactorization, LDLFact, HSLMA57Fact, HSLMA97Fact, CholmodFact, QDLDLFact, LLDLFact
import LinearAlgebra.ldiv!
"""
Abstract type to select a factorization algorithm.
"""
abstract type AbstractFactorization end
abstract type FactorizationData{T} end
function ldiv!(res::AbstractVector, K_fact::FactorizationData, v::AbstractVector)
res .= v
ldiv!(K_fact, res)
end
function factorized end
"""
fact_alg = LDLFact(; regul = :classic)
Choose [`LDLFactorizations.jl`](https://github.com/JuliaSmoothOptimizers/LDLFactorizations.jl) to compute factorizations.
"""
struct LDLFact <: AbstractFactorization
regul::Symbol
function LDLFact(regul::Symbol)
regul == :classic ||
regul == :dynamic ||
regul == :hybrid ||
regul == :none ||
error("regul should be :classic or :dynamic or :hybrid or :none")
return new(regul)
end
end
LDLFact(; regul::Symbol = :classic) = LDLFact(regul)
include("ldlfact_utils.jl")
"""
fact_alg = CholmodFact(; regul = :classic)
Choose `ldlt` from Cholmod to compute factorizations.
`using SuiteSparse` should be used before `using RipQP`.
"""
struct CholmodFact <: AbstractFactorization
regul::Symbol
function CholmodFact(regul::Symbol)
regul == :classic || regul == :none || error("regul should be :classic or :none")
return new(regul)
end
end
CholmodFact(; regul::Symbol = :classic) = CholmodFact(regul)
"""
fact_alg = QDLDLFact(; regul = :classic)
Choose [`QDLDL.jl`](https://github.com/oxfordcontrol/QDLDL.jl) to compute factorizations.
`using QDLDL` should be used before `using RipQP`.
"""
struct QDLDLFact <: AbstractFactorization
regul::Symbol
function QDLDLFact(regul::Symbol)
regul == :classic || regul == :none || error("regul should be :classic or :none")
return new(regul)
end
end
QDLDLFact(; regul::Symbol = :classic) = QDLDLFact(regul)
"""
fact_alg = HSLMA57Fact(; regul = :classic)
Choose [`HSL.jl`](https://github.com/JuliaSmoothOptimizers/HSL.jl) MA57 to compute factorizations.
`using HSL` should be used before `using RipQP`.
"""
struct HSLMA57Fact <: AbstractFactorization
regul::Symbol
sqd::Bool
function HSLMA57Fact(regul::Symbol, sqd::Bool)
regul == :classic || regul == :none || error("regul should be :classic or :none")
return new(regul, sqd)
end
end
HSLMA57Fact(; regul::Symbol = :classic, sqd::Bool = true) = HSLMA57Fact(regul, sqd)
if LIBHSL_isfunctional()
include("ma57fact_utils.jl")
end
"""
fact_alg = HSLMA97Fact(; regul = :classic)
Choose [`HSL.jl`](https://github.com/JuliaSmoothOptimizers/HSL.jl) MA57 to compute factorizations.
`using HSL` should be used before `using RipQP`.
"""
struct HSLMA97Fact <: AbstractFactorization
regul::Symbol
function HSLMA97Fact(regul::Symbol)
regul == :classic || regul == :none || error("regul should be :classic or :none")
return new(regul)
end
end
HSLMA97Fact(; regul::Symbol = :classic) = HSLMA97Fact(regul)
if LIBHSL_isfunctional()
include("ma97fact_utils.jl")
end
"""
fact_alg = LLDLFact(; regul = :classic, mem = 0, droptol = 0.0)
Choose [`LimitedLDLFactorizations.jl`](https://github.com/JuliaSmoothOptimizers/LimitedLDLFactorizations.jl) to compute factorizations.
"""
struct LLDLFact <: AbstractFactorization
regul::Symbol
mem::Int
droptol::Float64
function LLDLFact(regul::Symbol, mem::Int, droptol::Float64)
regul == :classic || regul == :none || error("regul should be :classic or :none")
return new(regul, mem, droptol)
end
end
LLDLFact(; regul::Symbol = :classic, mem::Int = 0, droptol::Float64 = 0.0) =
LLDLFact(regul, mem, droptol)
include("lldlfact_utils.jl")
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 988 | using .SuiteSparse
get_uplo(fact_alg::CholmodFact) = :U
mutable struct CholmodFactorization{T} <: FactorizationData{T}
F::SuiteSparse.CHOLMOD.Factor{T}
initialized::Bool
factorized::Bool
end
init_fact(K::Symmetric{T, SparseMatrixCSC{T, Int}}, fact_alg::CholmodFact, ::Type{T}) where {T} =
CholmodFactorization(ldlt(K), false, true)
init_fact(K::Symmetric{T, SparseMatrixCSC{T, Int}}, fact_alg::CholmodFact) where {T} =
CholmodFactorization(ldlt(K), false, true)
function generic_factorize!(
K::Symmetric{T, SparseMatrixCSC{T, Int}},
K_fact::CholmodFactorization{T},
) where {T}
if K_fact.initialized
K_fact.factorized = false
try
ldlt!(K_fact.F, K)
K_fact.factorized = true
catch
K_fact.factorized = false
end
end
!K_fact.initialized && (K_fact.initialized = true)
end
RipQP.factorized(K_fact::CholmodFactorization) = K_fact.factorized
function ldiv!(K_fact::CholmodFactorization, dd::AbstractVector)
dd .= K_fact.F \ dd
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 1671 | get_uplo(fact_alg::LDLFact) = :U
mutable struct LDLFactorizationData{T} <: FactorizationData{T}
LDL::LDLFactorizations.LDLFactorization{T, Int, Int, Int}
end
init_fact(K::Symmetric{T, SparseMatrixCSC{T, Int}}, fact_alg::LDLFact) where {T} =
LDLFactorizationData(ldl_analyze(K))
init_fact(K::Symmetric{T, SparseMatrixCSC{T, Int}}, fact_alg::LDLFact, ::Type{Tf}) where {T, Tf} =
LDLFactorizationData(ldl_analyze(K, Tf))
generic_factorize!(K::Symmetric, K_fact::LDLFactorizationData) = ldl_factorize!(K, K_fact.LDL)
RipQP.factorized(K_fact::LDLFactorizationData) = LDLFactorizations.factorized(K_fact.LDL)
ldiv!(K_fact::LDLFactorizationData, dd::AbstractVector) = ldiv!(K_fact.LDL, dd)
# used only for preconditioner
function abs_diagonal!(K_fact::LDLFactorizationData)
K_fact.LDL.d .= abs.(K_fact.LDL.d)
end
# LDLFactorization conversion function
function convertldl(::Type{T}, K_fact::LDLFactorizationData{T_old}) where {T, T_old}
if T == T_old
return K_fact
else
return LDLFactorizationData(
LDLFactorizations.LDLFactorization(
K_fact.LDL.__analyzed,
K_fact.LDL.__factorized,
K_fact.LDL.__upper,
K_fact.LDL.n,
K_fact.LDL.parent,
K_fact.LDL.Lnz,
K_fact.LDL.flag,
K_fact.LDL.P,
K_fact.LDL.pinv,
K_fact.LDL.Lp,
K_fact.LDL.Cp,
K_fact.LDL.Ci,
K_fact.LDL.Li,
convert(Array{T}, K_fact.LDL.Lx),
convert(Array{T}, K_fact.LDL.d),
convert(Array{T}, K_fact.LDL.Y),
K_fact.LDL.pattern,
T(K_fact.LDL.r1),
T(K_fact.LDL.r2),
T(K_fact.LDL.tol),
K_fact.LDL.n_d,
),
)
end
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 968 | get_uplo(fact_alg::LLDLFact) = :L
mutable struct LLDLFactorizationData{T, F <: LimitedLDLFactorization} <: FactorizationData{T}
LLDL::F
mem::Int
droptol::T
end
init_fact(K::Symmetric{T, SparseMatrixCSC{T, Int}}, fact_alg::LLDLFact) where {T} =
LLDLFactorizationData(lldl(K.data, memory = fact_alg.mem), fact_alg.mem, T(fact_alg.droptol))
init_fact(K::Symmetric{T, SparseMatrixCSC{T, Int}}, fact_alg::LLDLFact, ::Type{Tf}) where {T, Tf} =
LLDLFactorizationData(lldl(K.data, Tf, memory = fact_alg.mem), fact_alg.mem, Tf(fact_alg.droptol))
generic_factorize!(K::Symmetric, K_fact::LLDLFactorizationData) =
lldl_factorize!(K_fact.LLDL, K.data)
RipQP.factorized(K_fact::LLDLFactorizationData) = LimitedLDLFactorizations.factorized(K_fact.LLDL)
ldiv!(K_fact::LLDLFactorizationData, dd::AbstractVector) = ldiv!(K_fact.LLDL, dd)
# used only for preconditioner
function abs_diagonal!(K_fact::LLDLFactorizationData)
K_fact.LLDL.D .= abs.(K_fact.LLDL.D)
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 2413 | get_uplo(fact_alg::HSLMA57Fact) = :L
mutable struct Ma57Factorization{T} <: FactorizationData{T}
ma57::Ma57{T}
work::Vector{T}
end
function init_fact(K::Symmetric{T, SparseMatrixCOO{T, Int}}, fact_alg::HSLMA57Fact) where {T}
K_fact = Ma57Factorization(
ma57_coord(size(K, 1), K.data.rows, K.data.cols, K.data.vals, sqd = fact_alg.sqd),
Vector{T}(undef, size(K, 1)),
)
return K_fact
end
function init_fact(
K::Symmetric{T, SparseMatrixCOO{T, Int}},
fact_alg::HSLMA57Fact,
::Type{Tf},
) where {T, Tf}
K_fact = Ma57Factorization(
ma57_coord(size(K, 1), K.data.rows, K.data.cols, Tf.(K.data.vals), sqd = fact_alg.sqd),
Vector{Tf}(undef, size(K, 1)),
)
return K_fact
end
function generic_factorize!(
K::Symmetric{T, SparseMatrixCOO{T, Int}},
K_fact::Ma57Factorization,
) where {T}
copyto!(K_fact.ma57.vals, K.data.vals)
ma57_factorize!(K_fact.ma57)
end
RipQP.factorized(K_fact::Ma57Factorization) = (K_fact.ma57.info.info[1] == 0)
ldiv!(K_fact::Ma57Factorization{T}, dd::AbstractVector{T}) where {T} =
ma57_solve!(K_fact.ma57, dd, K_fact.work)
function abs_diagonal!(K_fact::Ma57Factorization)
K_fact
end
convertldl(T::DataType, K_fact::Ma57Factorization) = Ma57Factorization(
Ma57(
K_fact.ma57.n,
K_fact.ma57.nz,
K_fact.ma57.rows,
K_fact.ma57.cols,
convert(Array{T}, K_fact.ma57.vals),
Ma57_Control(K_fact.ma57.control.icntl, convert(Array{T}, K_fact.ma57.control.cntl)),
Ma57_Info(
K_fact.ma57.info.info,
convert(Array{T}, K_fact.ma57.info.rinfo),
K_fact.ma57.info.largest_front,
K_fact.ma57.info.num_2x2_pivots,
K_fact.ma57.info.num_delayed_pivots,
K_fact.ma57.info.num_negative_eigs,
K_fact.ma57.info.rank,
K_fact.ma57.info.num_pivot_sign_changes,
T(K_fact.ma57.info.backward_error1),
T(K_fact.ma57.info.backward_error2),
T(K_fact.ma57.info.matrix_inf_norm),
T(K_fact.ma57.info.solution_inf_norm),
T(K_fact.ma57.info.scaled_residuals),
T(K_fact.ma57.info.cond1),
T(K_fact.ma57.info.cond2),
T(K_fact.ma57.info.error_inf_norm),
),
T(K_fact.ma57.multiplier),
K_fact.ma57.__lkeep,
K_fact.ma57.__keep,
K_fact.ma57.__lfact,
convert(Array{T}, K_fact.ma57.__fact),
K_fact.ma57.__lifact,
K_fact.ma57.__ifact,
K_fact.ma57.iwork_fact,
K_fact.ma57.iwork_solve,
),
convert(Array{T}, K_fact.work),
)
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 2977 | get_uplo(fact_alg::HSLMA97Fact) = :L
mutable struct Ma97Factorization{T} <: FactorizationData{T}
ma97::Ma97{T}
end
function init_fact(
K::Symmetric{T, SparseMatrixCSC{T, Int}},
fact_alg::HSLMA97Fact,
::Type{T},
) where {T}
return Ma97Factorization(
ma97_csc(size(K, 1), Int32.(K.data.colptr), Int32.(K.data.rowval), K.data.nzval),
)
end
function init_fact(K::Symmetric{T, SparseMatrixCSC{T, Int}}, fact_alg::HSLMA97Fact) where {T}
return Ma97Factorization(
ma97_csc(size(K, 1), Int32.(K.data.colptr), Int32.(K.data.rowval), K.data.nzval),
)
end
function generic_factorize!(
K::Symmetric{T, SparseMatrixCSC{T, Int}},
K_fact::Ma97Factorization,
) where {T}
copyto!(K_fact.ma97.nzval, K.data.nzval)
ma97_factorize!(K_fact.ma97)
end
RipQP.factorized(K_fact::Ma97Factorization) = (K_fact.ma97.info.flag == 0)
ldiv!(K_fact::Ma97Factorization{T}, dd::AbstractVector{T}) where {T} = ma97_solve!(K_fact.ma97, dd)
function abs_diagonal!(K_fact::Ma97Factorization)
K_fact
end
# function convertldl(T::DataType, K_fact::Ma97Factorization)
# K_fact2 = Ma97Factorization(
# Ma97{T, T}(
# K_fact.ma97.__akeep,
# K_fact.ma97.__fkeep,
# K_fact.ma97.n,
# K_fact.ma97.colptr,
# K_fact.ma97.rowval,
# convert(Array{T}, K_fact.ma97.nzval),
# Ma97_Control{T}(
# K_fact.ma97.control.f_arrays,
# K_fact.ma97.control.action,
# K_fact.ma97.control.nemin,
# T(K_fact.ma97.control.multiplier),
# K_fact.ma97.control.ordering,
# K_fact.ma97.control.print_level,
# K_fact.ma97.control.scaling,
# T(K_fact.ma97.control.small),
# T(K_fact.ma97.control.u),
# K_fact.ma97.control.unit_diagnostics,
# K_fact.ma97.control.unit_error,
# K_fact.ma97.control.unit_warning,
# K_fact.ma97.control.factor_min,
# K_fact.ma97.control.solve_blas3,
# K_fact.ma97.control.solve_min,
# K_fact.ma97.control.solve_mf,
# T(K_fact.ma97.control.consist_tol),
# K_fact.ma97.control.ispare,
# convert(Array{T}, K_fact.ma97.control.rspare),
# ),
# Ma97_Info{T}(
# K_fact.ma97.info.flag,
# K_fact.ma97.info.flag68,
# K_fact.ma97.info.flag77,
# K_fact.ma97.info.matrix_dup,
# K_fact.ma97.info.matrix_rank,
# K_fact.ma97.info.matrix_outrange,
# K_fact.ma97.info.matrix_missing_diag,
# K_fact.ma97.info.maxdepth,
# K_fact.ma97.info.maxfront,
# K_fact.ma97.info.num_delay,
# K_fact.ma97.info.num_factor,
# K_fact.ma97.info.num_flops,
# K_fact.ma97.info.num_neg,
# K_fact.ma97.info.num_sup,
# K_fact.ma97.info.num_two,
# K_fact.ma97.info.ordering,
# K_fact.ma97.info.stat,
# K_fact.ma97.info.ispare,
# convert(Array{T}, K_fact.ma97.info.rspare),
# ),
# ),
# )
# HSL.ma97_finalize(K_fact2.ma97)
# return K_fact2
# end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 1162 | using .QDLDL
get_uplo(fact_alg::QDLDLFact) = :U
mutable struct QDLDLFactorization{T} <: FactorizationData{T}
F::QDLDL.QDLDLFactorisation{T, Int}
initialized::Bool
diagindK::Vector{Int}
factorized::Bool
end
init_fact(K::Symmetric{T, SparseMatrixCSC{T, Int}}, fact_alg::QDLDLFact, ::Type{T}) where {T} =
QDLDLFactorization(QDLDL.qdldl(K.data), false, get_diagind_K(K, :U), true)
init_fact(K::Symmetric{T, SparseMatrixCSC{T, Int}}, fact_alg::QDLDLFact) where {T} =
QDLDLFactorization(QDLDL.qdldl(K.data), false, get_diagind_K(K, :U), true)
function generic_factorize!(
K::Symmetric{T, SparseMatrixCSC{T, Int}},
K_fact::QDLDLFactorization{T},
) where {T}
if K_fact.initialized
QDLDL.update_values!(K_fact.F, K_fact.diagindK, view(K.data.nzval, K_fact.diagindK))
K_fact.factorized = false
try
QDLDL.refactor!(K_fact.F)
K_fact.factorized = true
catch
K_fact.factorized = false
end
end
!K_fact.initialized && (K_fact.initialized = true)
end
RipQP.factorized(K_fact::QDLDLFactorization) = K_fact.factorized
function ldiv!(K_fact::QDLDLFactorization, dd::AbstractVector)
QDLDL.solve!(K_fact.F, dd)
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 803 | function convertpad(
::Type{<:PreallocatedData{T}},
pad::PreallocatedDataK1CholDense{T0, S0, M0},
sp_old::K1CholDenseParams,
sp_new::Union{Nothing, K1CholDenseParams},
id::QM_IntData,
fd::Abstract_QM_FloatData,
) where {T <: Real, T0 <: Real, S0, M0}
S = change_vector_eltype(S0, T)
pad = PreallocatedDataK1CholDense(
convert(S, pad.D),
Diagonal(convert(S, pad.invD.diag)),
convert_mat(pad.AinvD, T),
convert(S, pad.rhs),
convert(Regularization{T}, pad.regu),
convert_mat(pad.K, T),
pad.diagindK,
convert(S, pad.tmpldiv),
)
if T == Float64 && T0 == Float64
pad.regu.ρ_min, pad.regu.δ_min = T(sqrt(eps()) * 1e0), T(sqrt(eps()) * 1e0)
else
pad.regu.ρ_min, pad.regu.δ_min = T(sqrt(eps(T)) * 1e1), T(sqrt(eps(T)) * 1e1)
end
return pad
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 4011 | function convertpad(
::Type{<:PreallocatedData{T}},
pad::PreallocatedDataK2LDL{T_old},
sp_old::K2LDLParams,
sp_new::K2KrylovParams,
id::QM_IntData,
fd::Abstract_QM_FloatData,
) where {T <: Real, T_old <: Real}
D = convert(Array{T}, pad.D)
regu = convert(Regularization{T}, pad.regu)
regu.ρ_min = T(sp_new.ρ_min)
regu.δ_min = T(sp_new.δ_min)
K = Symmetric(convert(eval(typeof(pad.K.data).name.name){T, Int}, pad.K.data), sp_new.uplo)
rhs = similar(D, id.nvar + id.ncon)
δv = [regu.δ]
if sp_new.equilibrate
Deq = Diagonal(similar(D, id.nvar + id.ncon))
Deq.diag .= one(T)
C_eq = Diagonal(similar(D, id.nvar + id.ncon))
else
Deq = Diagonal(similar(D, 0))
C_eq = Diagonal(similar(D, 0))
end
mt = MatrixTools(convert(SparseVector{T, Int}, pad.diag_Q), pad.diagind_K, Deq, C_eq)
regu_precond = pad.regu
regu_precond.regul = :dynamic
pdat = PreconditionerData(sp_new, pad.K_fact, id.nvar, id.ncon, regu_precond, K)
KS = init_Ksolver(K, rhs, sp_new)
return PreallocatedDataK2Krylov(
pdat,
D,
rhs,
sp_new.rhs_scale,
sp_new.equilibrate,
regu,
δv,
K, #K
mt,
KS,
0,
T(sp_new.atol0),
T(sp_new.rtol0),
T(sp_new.atol_min),
T(sp_new.rtol_min),
sp_new.itmax,
)
end
function convertpad(
::Type{<:PreallocatedData{T}},
pad::PreallocatedDataK2Krylov{T_old},
sp_old::K2KrylovParams,
sp_new::K2KrylovParams,
id::QM_IntData,
fd::Abstract_QM_FloatData,
) where {T <: Real, T_old <: Real}
D = convert(Array{T}, pad.D)
regu = convert(Regularization{T}, pad.regu)
regu.ρ_min = T(sp_new.ρ_min)
regu.δ_min = T(sp_new.δ_min)
K = Symmetric(convert(eval(typeof(pad.K.data).name.name){T, Int}, pad.K.data), sp_new.uplo)
rhs = similar(D, id.nvar + id.ncon)
δv = [regu.δ]
if !(sp_old.equilibrate) && sp_new.equilibrate
Deq = Diagonal(similar(D, id.nvar + id.ncon))
C_eq = Diagonal(similar(D, id.nvar + id.ncon))
mt = MatrixTools(convert(SparseVector{T, Int}, pad.mt.diag_Q), pad.mt.diagind_K, Deq, C_eq)
else
mt = convert(MatrixTools{T}, pad.mt)
mt.Deq.diag .= one(T)
end
sp_new.equilibrate && (mt.Deq.diag .= one(T))
regu_precond = convert(Regularization{sp_new.preconditioner.T}, pad.regu)
regu_precond.regul = :dynamic
if typeof(sp_old.preconditioner.fact_alg) == LLDLFact ||
typeof(sp_old.preconditioner.fact_alg) != typeof(sp_new.preconditioner.fact_alg)
if get_uplo(sp_old.preconditioner.fact_alg) != get_uplo(sp_new.preconditioner.fact_alg)
# transpose if new factorization does not use the same uplo
K = Symmetric(SparseMatrixCSC(K.data'), sp_new.uplo)
mt.diagind_K = get_diagind_K(K, sp_new.uplo)
end
K_fact = init_fact(K, sp_new.preconditioner.fact_alg)
else
K_fact = convertldl(sp_new.preconditioner.T, pad.pdat.K_fact)
end
pdat = PreconditionerData(sp_new, K_fact, id.nvar, id.ncon, regu_precond, K)
KS = init_Ksolver(K, rhs, sp_new)
return PreallocatedDataK2Krylov(
pdat,
D,
rhs,
sp_new.rhs_scale,
sp_new.equilibrate,
regu,
δv,
K, #K
mt,
KS,
0,
T(sp_new.atol0),
T(sp_new.rtol0),
T(sp_new.atol_min),
T(sp_new.rtol_min),
sp_new.itmax,
)
end
function convertpad(
::Type{<:PreallocatedData{T}},
pad::PreallocatedDataK2Krylov{T_old},
sp_old::K2KrylovParams,
sp_new::K2LDLParams,
id::QM_IntData,
fd::Abstract_QM_FloatData,
) where {T <: Real, T_old <: Real}
D = convert(Array{T}, pad.D)
regu = convert(Regularization{T}, pad.regu)
regu.ρ_min = T(sp_new.ρ_min)
regu.δ_min = T(sp_new.δ_min)
regu.ρ *= 10
regu.δ *= 10
regu.regul = sp_new.fact_alg.regul
K_fact = convertldl(T, pad.pdat.K_fact)
K = Symmetric(convert(eval(typeof(pad.K.data).name.name){T, Int}, pad.K.data), sp_new.uplo)
return PreallocatedDataK2LDL(
D,
regu,
sp_new.safety_dist_bnd,
convert(SparseVector{T, Int}, pad.mt.diag_Q), #diag_Q
K, #K
K_fact, #K_fact
false,
pad.mt.diagind_K, #diagind_K
)
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 828 | function convertpad(
::Type{<:PreallocatedData{T}},
pad::PreallocatedDataK2LDL{T_old},
sp_old::K2LDLParams,
sp_new::K2LDLParams,
id::QM_IntData,
fd::Abstract_QM_FloatData,
) where {T <: Real, T_old <: Real}
pad = PreallocatedDataK2LDL(
convert(Array{T}, pad.D),
convert(Regularization{T}, pad.regu),
sp_new.safety_dist_bnd,
convert(SparseVector{T, Int}, pad.diag_Q),
Symmetric(convert_mat(pad.K.data, T), Symbol(pad.K.uplo)),
convertldl(T, pad.K_fact),
pad.fact_fail,
pad.diagind_K,
)
if pad.regu.regul == :classic
pad.regu.ρ_min, pad.regu.δ_min = T(sp_new.ρ_min), T(sp_new.ρ_min)
elseif pad.regu.regul == :dynamic
pad.regu.ρ, pad.regu.δ = T(eps(T)^(3 / 4)), T(eps(T)^(0.45))
pad.K_fact.LDL.r1, pad.K_fact.LDL.r2 = -pad.regu.ρ, pad.regu.δ
end
return pad
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 1065 | function convertpad(
::Type{<:PreallocatedData{T}},
pad::PreallocatedDataK2_5LDL{T_old},
sp_old::K2_5LDLParams,
sp_new::Union{Nothing, K2_5LDLParams},
id::QM_IntData,
fd::Abstract_QM_FloatData,
) where {T <: Real, T_old <: Real}
pad = PreallocatedDataK2_5LDL(
convert(Array{T}, pad.D),
convert(Regularization{T}, pad.regu),
convert(SparseVector{T, Int}, pad.diag_Q),
Symmetric(convert(SparseMatrixCSC{T, Int}, pad.K.data), Symbol(pad.K.uplo)),
convertldl(T, pad.K_fact),
pad.fact_fail,
pad.diagind_K,
pad.K_scaled,
)
if pad.regu.regul == :classic
if T == Float64 && typeof(sp_new) == Nothing
pad.regu.ρ_min, pad.regu.δ_min = T(sqrt(eps()) * 1e-5), T(sqrt(eps()) * 1e0)
else
pad.regu.ρ_min, pad.regu.δ_min = T(sqrt(eps(T)) * 1e1), T(sqrt(eps(T)) * 1e1)
end
pad.regu.ρ /= 10
pad.regu.δ /= 10
elseif pad.regu.regul == :dynamic
pad.regu.ρ, pad.regu.δ = T(eps(T)^(3 / 4)), T(eps(T)^(0.45))
pad.K_fact.LDL.r1, pad.K_fact.LDL.r2 = -pad.regu.ρ, pad.regu.δ
end
return pad
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 135 | include("K2LDL_transitions.jl")
include("K2Krylov_transitions.jl")
include("K2_5LDL_transitions.jl")
include("K1dense_transitions.jl")
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 791 | using HSL, LinearOperators, LLSModels, NLPModelsModifiers, QPSReader, QuadraticModels
using DelimitedFiles, DoubleFloats, LinearAlgebra, MatrixMarket, SparseArrays, Test
using SuiteSparse # test cholmod
using RipQP
qps1 = readqps("QAFIRO.SIF") #lower bounds
qps2 = readqps("HS21.SIF") # low/upp bounds
qps3 = readqps("HS52.SIF") # free bounds
qps4 = readqps("AFIRO.SIF") # LP
qps5 = readqps("HS35MOD.SIF") # fixed variables
Q = [
6.0 2.0 1.0
2.0 5.0 2.0
1.0 2.0 4.0
]
c = [-8.0; -3; -3]
A = [
1.0 0.0 1.0
0.0 2.0 1.0
]
b = [0.0; 3]
l = [0.0; 0; 0]
u = [Inf; Inf; Inf]
include("solvers/test_augmented.jl")
include("solvers/test_newton.jl")
include("solvers/test_normal.jl")
include("test_multi.jl")
include("test_alternative_methods.jl")
include("test_alternative_problems.jl")
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 3565 | @testset "dynamic_regularization" begin
stats1 = ripqp(
QuadraticModel(qps1),
sp = K2LDLParams(fact_alg = LDLFact(regul = :dynamic)),
history = true,
display = false,
)
@test isapprox(stats1.objective, -1.59078179, atol = 1e-2)
@test stats1.status == :first_order
stats2 = ripqp(
QuadraticModel(qps2),
sp = K2LDLParams(fact_alg = LDLFact(regul = :dynamic)),
display = false,
)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-2)
@test stats2.status == :first_order
stats3 = ripqp(
QuadraticModel(qps3),
sp = K2LDLParams(fact_alg = LDLFact(regul = :dynamic)),
display = false,
)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-2)
@test stats3.status == :first_order
end
@testset "centrality_corrections" begin
stats1 = ripqp(QuadraticModel(qps1), kc = -1, display = false) # automatic centrality corrections computation
@test isapprox(stats1.objective, -1.59078179, atol = 1e-2)
@test stats1.status == :first_order
stats2 = ripqp(QuadraticModel(qps2), kc = 2, display = false)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-2)
@test stats2.status == :first_order
stats3 = ripqp(QuadraticModel(qps3), kc = 2, display = false)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-2)
@test stats3.status == :first_order
end
@testset "refinement" begin
stats1 = ripqp(QuadraticModel(qps1), mode = :zoom, display = false) # automatic centrality corrections computation
@test isapprox(stats1.objective, -1.59078179, atol = 1e-2)
@test stats1.status == :first_order
stats1 = ripqp(QuadraticModel(qps1), mode = :ref, display = false) # automatic centrality corrections computation
@test isapprox(stats1.objective, -1.59078179, atol = 1e-2)
@test stats1.status == :first_order
stats2 = ripqp(QuadraticModel(qps2), mode = :multizoom, scaling = false, display = false)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-2)
@test stats2.status == :first_order
stats3 = ripqp(QuadraticModel(qps3), mode = :multiref, display = false)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-2)
@test stats3.status == :first_order
end
@testset "IPF" begin
stats1 = ripqp(QuadraticModel(qps1), display = false, solve_method = IPF(), mode = :multi)
@test isapprox(stats1.objective, -1.59078179, atol = 1e-2)
@test stats1.status == :first_order
stats2 = ripqp(QuadraticModel(qps2), display = false, solve_method = IPF())
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-2)
@test stats2.status == :first_order
stats2 = ripqp(
QuadraticModel(qps2),
display = false,
solve_method = IPF(),
sp = K2_5LDLParams(),
mode = :zoom,
)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-2)
@test stats2.status == :first_order
stats1 = ripqp(
QuadraticModel(qps1),
display = false,
perturb = true,
solve_method = IPF(),
mode = :multiref,
)
@test isapprox(stats1.objective, -1.59078179, atol = 1e-2)
@test stats1.status == :first_order
stats2 = ripqp(
QuadraticModel(qps2),
display = false,
solve_method = IPF(),
mode = :multizoom,
sp = K2_5LDLParams(),
)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-2)
@test stats2.status == :first_order
stats2 = ripqp(
QuadraticModel(qps2),
display = false,
solve_method = IPF(),
mode = :zoom,
sp = K2LDLParams(fact_alg = LDLFact(regul = :dynamic)),
)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-2)
@test stats2.status == :first_order
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 4115 | @testset "LLS" begin
# least-square problem without constraints
m, n = 20, 10
A = rand(m, n)
b = rand(m)
nls = LLSModel(A, b)
statsnls = ripqp(nls, itol = InputTol(ϵ_rb = sqrt(eps()), ϵ_rc = sqrt(eps())), display = false)
x, r = statsnls.solution, statsnls.solver_specific[:r]
@test norm(x - A \ b) ≤ norm(b) * sqrt(eps()) * 100
@test norm(A * x - b - r) ≤ norm(b) * sqrt(eps()) * 100
# least-square problem with constraints
A = rand(m, n)
b = rand(m)
lcon, ucon = zeros(m), fill(Inf, m)
C = ones(m, n)
lvar, uvar = fill(-10.0, n), fill(200.0, n)
nls = LLSModel(A, b, lvar = lvar, uvar = uvar, C = C, lcon = lcon, ucon = ucon)
statsnls = ripqp(nls, display = false)
x, r = statsnls.solution, statsnls.solver_specific[:r]
@test length(r) == m
@test norm(A * x - b - r) ≤ norm(b) * sqrt(eps())
end
@testset "matrixwrite" begin
stats1 = ripqp(
QuadraticModel(qps1),
display = false,
w = SystemWrite(write = true, name = "test_", kfirst = 4, kgap = 1000),
)
@test isapprox(stats1.objective, -1.59078179, atol = 1e-2)
@test stats1.status == :first_order
K = MatrixMarket.mmread("test_K_iter4.mtx")
rhs_aff = readdlm("test_rhs_iter4_aff.rhs", Float64)[:]
rhs_cc = readdlm("test_rhs_iter4_cc.rhs", Float64)[:]
@test size(K, 1) == size(K, 2) == length(rhs_aff) == length(rhs_cc)
end
function QuadraticModelMaximize(qps, x0 = zeros(qps.nvar))
QuadraticModel(
-qps.c,
qps.qrows,
qps.qcols,
-qps.qvals,
Arows = qps.arows,
Acols = qps.acols,
Avals = qps.avals,
lcon = qps.lcon,
ucon = qps.ucon,
lvar = qps.lvar,
uvar = qps.uvar,
c0 = -qps.c0,
x0 = x0,
minimize = false,
)
end
@testset "maximize" begin
stats1 = ripqp(QuadraticModelMaximize(qps1), display = false)
@test isapprox(stats1.objective, 1.59078179, atol = 1e-2)
@test stats1.status == :first_order
stats2 = ripqp(QuadraticModelMaximize(qps2), ps = false, display = false)
@test isapprox(stats2.objective, 9.99599999e1, atol = 1e-2)
@test stats2.status == :first_order
stats3 = ripqp(QuadraticModelMaximize(qps3), display = false)
@test isapprox(stats3.objective, -5.32664756, atol = 1e-2)
@test stats3.status == :first_order
end
@testset "presolve" begin
qp = QuadraticModel(zeros(2), zeros(2, 2), lvar = zeros(2), uvar = zeros(2))
stats_ps = ripqp(qp)
@test stats_ps.status == :first_order
@test stats_ps.solution == [0.0; 0.0]
stats5 = ripqp(QuadraticModel(qps5), display = false)
@test isapprox(stats5.objective, 0.250000001, atol = 1e-2)
@test stats5.status == :first_order
stats5 = ripqp(QuadraticModel(qps5), sp = K2KrylovParams(), display = false)
@test isapprox(stats5.objective, 0.250000001, atol = 1e-2)
@test stats5.status == :first_order
end
qp_linop = QuadraticModel(
c,
LinearOperator(Q),
A = LinearOperator(A),
lcon = b,
ucon = b,
lvar = l,
uvar = u,
c0 = 0.0,
name = "QM_LINOP",
)
qp_dense = QuadraticModel(
c,
Symmetric(tril(Q), :L),
A = A,
lcon = b,
ucon = b,
lvar = l,
uvar = u,
c0 = 0.0,
name = "QM_LINOP",
)
@testset "Dense and LinearOperator QPs" begin
stats_linop = ripqp(
qp_linop,
sp = K2KrylovParams(kmethod = :gmres),
ps = false,
scaling = false,
display = false,
)
@test isapprox(stats_linop.objective, 1.1249999990782493, atol = 1e-2)
@test stats_linop.status == :first_order
stats_dense = ripqp(qp_dense, sp = K2KrylovParams(kmethod = :gmres, uplo = :U))
@test isapprox(stats_dense.objective, 1.1249999990782493, atol = 1e-2)
@test stats_dense.status == :first_order
for fact_alg in [:bunchkaufman, :ldl]
stats_dense = ripqp(
qp_dense,
sp = K2LDLDenseParams(fact_alg = fact_alg, ρ0 = 0.0, δ0 = 0.0),
ps = false,
scaling = false,
display = false,
)
@test isapprox(stats_dense.objective, 1.1249999990782493, atol = 1e-2)
@test stats_dense.status == :first_order
end
# test conversion
stats_dense = ripqp(qp_dense)
@test isapprox(stats_dense.objective, 1.1249999990782493, atol = 1e-2)
@test stats_dense.status == :first_order
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 3400 | function createQuadraticModelT(qpdata; T = Double64, name = "qp_pb")
return QuadraticModel(
convert(Array{T}, qpdata.c),
qpdata.qrows,
qpdata.qcols,
convert(Array{T}, qpdata.qvals),
Arows = qpdata.arows,
Acols = qpdata.acols,
Avals = convert(Array{T}, qpdata.avals),
lcon = convert(Array{T}, qpdata.lcon),
ucon = convert(Array{T}, qpdata.ucon),
lvar = convert(Array{T}, qpdata.lvar),
uvar = convert(Array{T}, qpdata.uvar),
c0 = T(qpdata.c0),
x0 = zeros(T, length(qpdata.c)),
name = name,
)
end
@testset "multi_mode" begin
stats1 = ripqp(QuadraticModel(qps1), mode = :multi, display = false)
@test isapprox(stats1.objective, -1.59078179, atol = 1e-2)
@test stats1.status == :first_order
stats2 = ripqp(QuadraticModel(qps2), mode = :multi, display = false)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-2)
@test stats2.status == :first_order
stats3 = ripqp(QuadraticModel(qps3), mode = :multi, display = false)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-2)
@test stats3.status == :first_order
end
@testset "Float16, Float32, Float128, BigFloat" begin
qm16 = QuadraticModel(
Float16.(c),
Float16.(tril(Q)),
A = Float16.(A),
lcon = Float16.(b),
ucon = Float16.(b),
lvar = Float16.(l),
uvar = Float16.(u),
c0 = Float16(0.0),
x0 = zeros(Float16, 3),
name = "QM16",
)
stats_dense = ripqp(qm16, itol = InputTol(Float16), display = false, ps = false)
@test isapprox(stats_dense.objective, 1.1249999990782493, atol = 1e-2)
@test stats_dense.status == :first_order
for T ∈ [Float32, Double64]
qmT_2 = createQuadraticModelT(qps2, T = T)
stats2 = ripqp(qmT_2, display = false)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-2)
@test stats2.status == :first_order
end
qm128_1 = createQuadraticModelT(qps1, T = BigFloat)
stats1 = ripqp(
qm128_1,
itol = InputTol(BigFloat, ϵ_rb1 = BigFloat(0.1), ϵ_rb2 = BigFloat(0.01)),
mode = :multi,
normalize_rtol = false,
display = false,
)
@test isapprox(stats1.objective, -1.59078179, atol = 1e-2)
@test stats1.status == :first_order
end
@testset "multi solvers" begin
for mode ∈ [:multi, :multizoom, :multiref]
stats1 = ripqp(
QuadraticModel(qps1),
mode = mode,
solve_method = IPF(),
sp2 = K2KrylovParams(uplo = :U, kmethod = :gmres, preconditioner = LDL()),
display = false,
)
@test isapprox(stats1.objective, -1.59078179, atol = 1e-2)
@test stats1.status == :first_order
end
qm128_1 = createQuadraticModelT(qps1, T = Double64)
stats1 = ripqp(
qm128_1,
mode = :multi,
solve_method = IPF(),
sp = K2KrylovParams(
uplo = :U,
form_mat = true,
equilibrate = false,
preconditioner = LDL(T = Float64),
ρ_min = sqrt(eps()),
δ_min = sqrt(eps()),
),
sp2 = K2KrylovParams{Double64}(
uplo = :U,
form_mat = true,
equilibrate = false,
preconditioner = LDL(T = Float64),
atol_min = Double64(1.0e-18),
rtol_min = Double64(1.0e-18),
ρ_min = sqrt(eps(Double64)),
δ_min = sqrt(eps(Double64)),
),
display = true,
itol = InputTol(Double64, ϵ_rb = Double64(1.0e-12), ϵ_rc = Double64(1.0e-12)),
)
@test isapprox(stats1.objective, -1.59078179, atol = 1e-2)
@test stats1.status == :first_order
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 6891 | @testset "mono_mode" begin
stats1 = ripqp(QuadraticModel(qps1), ps = false)
@test isapprox(stats1.objective, -1.59078179, atol = 1e-2)
@test stats1.status == :first_order
stats2 = ripqp(QuadraticModel(qps2), sp = K2LDLParams(fact_alg = CholmodFact()), display = false)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-2)
@test stats1.status == :first_order
if LIBHSL_isfunctional()
stats2 =
ripqp(QuadraticModel(qps2), sp = K2LDLParams(fact_alg = HSLMA57Fact()), display = false)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-2)
@test stats1.status == :first_order
end
if LIBHSL_isfunctional()
stats2 =
ripqp(QuadraticModel(qps2), sp = K2LDLParams(fact_alg = HSLMA97Fact()), display = false)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-2)
@test stats1.status == :first_order
end
stats3 = ripqp(QuadraticModel(qps3), display = false)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-2)
@test stats3.status == :first_order
stats4 = ripqp(QuadraticModel(qps4), display = false)
@test isapprox(stats4.objective, -4.6475314286e02, atol = 1e-2)
@test stats4.status == :first_order
end
@testset "K2_5" begin
stats1 = ripqp(QuadraticModel(qps1), display = false, sp = K2_5LDLParams())
@test isapprox(stats1.objective, -1.59078179, atol = 1e-2)
@test stats1.status == :first_order
stats2 = ripqp(QuadraticModel(qps2), display = false, sp = K2_5LDLParams(), mode = :multi)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-2)
@test stats2.status == :first_order
stats3 = ripqp(
QuadraticModel(qps3),
display = false,
sp = K2_5LDLParams(fact_alg = LDLFact(regul = :dynamic)),
)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-2)
@test stats3.status == :first_order
end
@testset "KrylovK2" begin
for precond in [Identity(), Jacobi(), Equilibration()]
for kmethod in [:minres, :minres_qlp, :symmlq]
stats2 = ripqp(
QuadraticModel(qps2),
display = false,
sp = K2KrylovParams(uplo = :L, kmethod = kmethod, preconditioner = precond),
history = true,
itol = InputTol(
max_iter = 50,
max_time = 40.0,
ϵ_rc = 1.0e-3,
ϵ_rb = 1.0e-3,
ϵ_pdd = 1.0e-3,
),
)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-1)
@test stats2.status == :first_order
end
end
stats3 = ripqp(
QuadraticModel(qps3),
display = false,
sp = K2KrylovParams(
uplo = :U,
kmethod = :minres_qlp,
preconditioner = Equilibration(),
form_mat = true,
),
itol = InputTol(max_iter = 50, max_time = 40.0, ϵ_rc = 1.0e-2, ϵ_rb = 1.0e-2, ϵ_pdd = 1.0e-2),
)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-1)
@test stats3.status == :first_order
for T in [Float32, Float64]
for precond in
[LDL(T = T, pos = :C), LDL(T = T, warm_start = false, pos = :L), LDL(T = T, pos = :R)]
stats2 = ripqp(
QuadraticModel(qps2),
display = false,
sp = K2KrylovParams(
uplo = :U,
kmethod = :gmres,
preconditioner = precond,
rhs_scale = true,
form_mat = true,
equilibrate = true,
),
solve_method = IPF(),
)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-1)
@test stats2.status == :first_order
end
end
stats3 = ripqp(
QuadraticModel(qps3),
display = true,
sp = K2KrylovParams(
uplo = :U,
kmethod = :minres,
preconditioner = LDL(),
rhs_scale = true,
form_mat = true,
equilibrate = true,
),
solve_method = IPF(),
)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-1)
@test stats3.status == :first_order
stats3 = ripqp(
QuadraticModel(qps3),
display = false,
sp = K2KrylovParams(
uplo = :L,
kmethod = :minres,
preconditioner = LDL(fact_alg = LLDLFact()),
rhs_scale = true,
form_mat = true,
equilibrate = true,
),
solve_method = IPF(),
)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-1)
@test stats3.status == :first_order
end
@testset "KrylovK2_5" begin
for kmethod in [:minres, :dqgmres]
stats1 = ripqp(
QuadraticModel(qps1),
display = false,
sp = K2_5KrylovParams(kmethod = kmethod, preconditioner = Identity()),
solve_method = IPF(),
history = true,
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-2, ϵ_rb = 1.0e-2, ϵ_pdd = 1.0e-2),
)
@test isapprox(stats1.objective, -1.59078179, atol = 1e-1)
@test stats1.status == :first_order
stats3 = ripqp(
QuadraticModel(qps3),
display = false,
sp = K2_5KrylovParams(kmethod = kmethod, preconditioner = Jacobi()),
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-2, ϵ_rb = 1.0e-2, ϵ_pdd = 1.0e-2),
)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-1)
@test stats3.status == :first_order
end
end
@testset "K2 structured LP" begin
for kmethod in [:gpmr, :trimr]
for δ_min in [1.0e-2, 0.0]
stats4 = ripqp(
QuadraticModel(qps4),
display = false,
sp = K2StructuredParams(kmethod = kmethod, δ_min = δ_min),
solve_method = IPF(),
itol = InputTol(
max_iter = 50,
max_time = 20.0,
ϵ_rc = 1.0e-4,
ϵ_rb = 1.0e-4,
ϵ_pdd = 1.0e-4,
),
)
@test isapprox(stats4.objective, -4.6475314286e02, atol = 1e-1)
@test stats4.status == :first_order
end
end
stats4 = ripqp(
QuadraticModel(qps4),
display = false,
sp = K2StructuredParams(kmethod = :tricg),
solve_method = IPF(),
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-4, ϵ_rb = 1.0e-4, ϵ_pdd = 1.0e-4),
)
@test isapprox(stats4.objective, -4.6475314286e02, atol = 1e-1)
@test stats4.status == :first_order
end
@testset "K2.5 structured LP" begin
for kmethod in [:gpmr, :trimr]
for δ_min in [1.0e-2, 0.0]
stats4 = ripqp(
QuadraticModel(qps4),
display = false,
solve_method = IPF(),
sp = K2_5StructuredParams(kmethod = kmethod, δ_min = δ_min),
itol = InputTol(
max_iter = 50,
max_time = 20.0,
ϵ_rc = 1.0e-4,
ϵ_rb = 1.0e-4,
ϵ_pdd = 1.0e-4,
),
)
@test isapprox(stats4.objective, -4.6475314286e02, atol = 1e-1)
@test stats4.status == :first_order
end
end
stats4 = ripqp(
QuadraticModel(qps4),
display = false,
sp = K2_5StructuredParams(kmethod = :tricg),
solve_method = IPF(),
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-4, ϵ_rb = 1.0e-4, ϵ_pdd = 1.0e-4),
)
@test isapprox(stats4.objective, -4.6475314286e02, atol = 1e-1)
@test stats4.status == :first_order
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 4470 | @testset "Krylov K3" begin
for kmethod in [:bilq, :bicgstab, :usymlq, :usymqr, :qmr, :diom, :fom, :gmres, :dqgmres]
stats2 = ripqp(
QuadraticModel(qps2),
display = false,
sp = K3KrylovParams(kmethod = kmethod),
solve_method = IPF(),
history = true,
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-4, ϵ_rb = 1.0e-4, ϵ_pdd = 1.0e-4),
)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-1)
@test stats2.status == :first_order
end
stats3 = ripqp(
QuadraticModel(qps3),
display = false,
sp = K3KrylovParams(uplo = :U, kmethod = :gmres),
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-4, ϵ_rb = 1.0e-4, ϵ_pdd = 1.0e-4),
)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-1)
@test stats3.status == :first_order
end
@testset "KrylovK3_5" begin
stats2 = ripqp(
QuadraticModel(qps2),
display = false,
sp = K3_5KrylovParams(uplo = :U, kmethod = :minres),
solve_method = IPF(),
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-3, ϵ_rb = 1.0e-3, ϵ_pdd = 1.0e-3),
)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e-1)
@test stats2.status == :first_order
for kmethod in [:minres, :gmres]
stats2 = ripqp(
QuadraticModel(qps2),
display = false,
sp = K3_5KrylovParams(uplo = :U, kmethod = kmethod, preconditioner = Equilibration()),
solve_method = IPF(),
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-2, ϵ_rb = 1.0e-2, ϵ_pdd = 1.0e-2),
)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e0)
@test stats2.status == :first_order
stats3 = ripqp(
QuadraticModel(qps3),
display = false,
sp = K3_5KrylovParams(kmethod = kmethod, preconditioner = Equilibration()),
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-2, ϵ_rb = 1.0e-2, ϵ_pdd = 1.0e-2),
)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-1)
@test stats3.status == :first_order
end
end
@testset "KrylovK3S" begin
stats2 = ripqp(
QuadraticModel(qps2),
display = true,
sp = K3SKrylovParams(uplo = :U, kmethod = :minres_qlp),
solve_method = IPF(),
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-2, ϵ_rb = 1.0e-2, ϵ_pdd = 1.0e-2),
)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e0)
@test stats2.status == :first_order
stats3 = ripqp(
QuadraticModel(qps3),
display = false,
sp = K3SKrylovParams(kmethod = :minres_qlp),
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-2, ϵ_rb = 1.0e-2, ϵ_pdd = 1.0e-2),
)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-1)
@test stats3.status == :first_order
stats2 = ripqp(
QuadraticModel(qps2),
display = false,
sp = K3SKrylovParams(uplo = :U, kmethod = :minres, preconditioner = Equilibration()),
solve_method = IPF(),
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-2, ϵ_rb = 1.0e-2, ϵ_pdd = 1.0e-2),
)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e0)
@test stats2.status == :first_order
stats3 = ripqp(
QuadraticModel(qps3),
display = false,
sp = K3SKrylovParams(kmethod = :minres, preconditioner = Equilibration()),
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-2, ϵ_rb = 1.0e-2, ϵ_pdd = 1.0e-2),
)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-1)
@test stats3.status == :first_order
end
@testset "K3_5 structured" begin
for kmethod in [:gpmr, :trimr]
stats2 = ripqp(
QuadraticModel(qps2),
display = false,
sp = K3_5StructuredParams(kmethod = kmethod),
solve_method = IPF(),
history = true,
itol = InputTol(
max_iter = 100,
max_time = 20.0,
ϵ_rc = 1.0e-2,
ϵ_rb = 1.0e-2,
ϵ_pdd = 1.0e-2,
),
)
@test isapprox(stats2.objective, -9.99599999e1, atol = 1e0)
@test stats2.status == :first_order
end
end
@testset "K3S structured" begin
for kmethod in [:gpmr, :trimr]
stats3 = ripqp(
QuadraticModel(qps3),
display = false,
sp = K3SStructuredParams(kmethod = kmethod),
solve_method = IPF(),
history = true,
itol = InputTol(
max_iter = 100,
max_time = 20.0,
ϵ_rc = 1.0e-2,
ϵ_rb = 1.0e-2,
ϵ_pdd = 1.0e-2,
),
)
@test isapprox(stats3.objective, 5.32664756, atol = 1e-1)
@test stats3.status == :first_order
end
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | code | 3962 | @testset "K1 Chol" begin
stats4 = ripqp(
QuadraticModel(qps4),
display = false,
sp = K1CholParams(),
solve_method = PC(),
history = true,
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-6, ϵ_rb = 1.0e-6, ϵ_pdd = 1.0e-6),
)
@test isapprox(stats4.objective, -4.6475314286e02, atol = 1e-2)
@test stats4.status == :first_order
end
@testset "Krylov K1" begin
for kmethod in [:cg, :cg_lanczos, :cr]
stats4 = ripqp(
QuadraticModel(qps4),
display = true,
sp = K1KrylovParams(kmethod = kmethod),
solve_method = IPF(),
history = true,
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-6, ϵ_rb = 1.0e-6, ϵ_pdd = 1.0e-6),
)
@test isapprox(stats4.objective, -4.6475314286e02, atol = 1e-2)
@test stats4.status == :first_order
end
stats4 = ripqp(
QuadraticModel(qps4),
display = false,
sp = K1KrylovParams(uplo = :U),
solve_method = PC(),
history = true,
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-6, ϵ_rb = 1.0e-6, ϵ_pdd = 1.0e-6),
)
@test isapprox(stats4.objective, -4.6475314286e02, atol = 1e-2)
@test stats4.status == :first_order
end
@testset "Krylov K1.1 Structured" begin
for kmethod in [:lsqr, :lsmr]
stats4 = ripqp(
QuadraticModel(qps4),
display = false,
sp = K1_1StructuredParams(kmethod = kmethod),
solve_method = IPF(),
history = true,
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-6, ϵ_rb = 1.0e-6, ϵ_pdd = 1.0e-6),
)
@test isapprox(stats4.objective, -4.6475314286e02, atol = 1e-1)
@test stats4.status == :first_order
end
stats4 = ripqp(
QuadraticModel(qps4),
display = false,
sp = K1_1StructuredParams(uplo = :U),
solve_method = IPF(),
history = true,
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-6, ϵ_rb = 1.0e-6, ϵ_pdd = 1.0e-6),
)
@test isapprox(stats4.objective, -4.6475314286e02, atol = 1e-2)
@test stats4.status == :first_order
end
@testset "Krylov K1.2 Structured" begin
for kmethod in [:lnlq, :craig, :craigmr]
stats4 = ripqp(
QuadraticModel(qps4),
display = false,
sp = K1_2StructuredParams(kmethod = kmethod),
solve_method = IPF(),
history = true,
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-6, ϵ_rb = 1.0e-6, ϵ_pdd = 1.0e-6),
)
@test isapprox(stats4.objective, -4.6475314286e02, atol = 1e-1)
@test stats4.status == :first_order
end
stats4 = ripqp(
QuadraticModel(qps4),
display = false,
sp = K1_2StructuredParams(uplo = :U),
solve_method = IPF(),
history = true,
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-6, ϵ_rb = 1.0e-6, ϵ_pdd = 1.0e-6),
)
@test isapprox(stats4.objective, -4.6475314286e02, atol = 1e-2)
@test stats4.status == :first_order
end
@testset "Krylov K1 Dense" begin
sm_dense4 = SlackModel(QuadraticModel(qps4))
qm_dense4 = QuadraticModel(
sm_dense4.data.c,
Matrix(sm_dense4.data.H),
A = Matrix(sm_dense4.data.A),
lcon = sm_dense4.meta.lcon,
ucon = sm_dense4.meta.ucon,
lvar = sm_dense4.meta.lvar,
uvar = sm_dense4.meta.uvar,
)
stats4 = ripqp(
qm_dense4,
display = false,
sp = K1CholDenseParams(),
solve_method = PC(),
ps = false,
scaling = false,
history = false,
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-6, ϵ_rb = 1.0e-6, ϵ_pdd = 1.0e-6),
)
@test isapprox(stats4.objective, -4.6475314286e02, atol = 1e-2)
@test stats4.status == :first_order
stats4 = ripqp(
qm_dense4,
display = true,
sp = K1CholDenseParams(),
solve_method = PC(),
mode = :multi,
ps = false,
scaling = false,
history = false,
itol = InputTol(max_iter = 50, max_time = 20.0, ϵ_rc = 1.0e-6, ϵ_rb = 1.0e-6, ϵ_pdd = 1.0e-6),
)
@test isapprox(stats4.objective, -4.6475314286e02, atol = 1e-2)
@test stats4.status == :first_order
end
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | docs | 2294 | # RipQP
[](https://doi.org/10.5281/zenodo.4309783)

[](https://cirrus-ci.com/github/JuliaSmoothOptimizers/RipQP.jl)
[](https://JuliaSmoothOptimizers.github.io/RipQP.jl/dev)
[](https://JuliaSmoothOptimizers.github.io/RipQP.jl/stable)
[](https://codecov.io/gh/JuliaSmoothOptimizers/RipQP.jl)
A package to optimize linear and quadratic problems in QuadraticModel format
(see https://github.com/JuliaSmoothOptimizers/QuadraticModels.jl).
By default, RipQP iterates in the floating-point type of its input QuadraticModel, but it can also perform operations in several floating-point systems if some parameters are modified (see the [documentation](https://JuliaSmoothOptimizers.github.io/RipQP.jl/stable) for more information).
# Basic usage
In this example, we use QPSReader to read a quadratic problem (QAFIRO) from the
Maros and Meszaros dataset.
```julia
using QPSReader, QuadraticModels
using RipQP
qps = readqps("QAFIRO.SIF")
qm = QuadraticModel(qps)
stats = ripqp(qm)
```
To use the multi precision mode (default to :mono) and change the maximum number of iterations:
```julia
stats = ripqp(qm, mode=:multi, itol = InputTol(max_iter=100))
```
## Bug reports and discussions
If you think you found a bug, feel free to open an [issue](https://github.com/JuliaSmoothOptimizers/RipQP.jl/issues).
Focused suggestions and requests can also be opened as issues. Before opening a pull request, start an issue or a discussion on the topic, please.
If you want to ask a question not suited for a bug report, feel free to start a discussion [here](https://github.com/JuliaSmoothOptimizers/Organization/discussions). This forum is for general discussion about this repository and the [JuliaSmoothOptimizers](https://github.com/JuliaSmoothOptimizers) organization, so questions about any of our packages are welcome.
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | docs | 619 | ## RipQP
```@docs
ripqp
```
## Input Types
```@docs
InputTol
SystemWrite
```
## Solvers
```@docs
SolverParams
K2LDLParams
K2_5LDLParams
K2KrylovParams
K2_5KrylovParams
K2StructuredParams
K2_5StructuredParams
K3KrylovParams
K3SKrylovParams
K3SStructuredParams
K3_5KrylovParams
K3_5StructuredParams
K1CholParams
K1KrylovParams
K1CholDenseParams
K2LDLDenseParams
K1_1StructuredParams
K1_2StructuredParams
```
## Preconditioners
```@docs
AbstractPreconditioner
Identity
Jacobi
Equilibration
LDL
```
## Factorizations
```@docs
AbstractFactorization
LDLFact
CholmodFact
QDLDLFact
HSLMA57Fact
HSLMA97Fact
LLDLFact
``` | RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | docs | 1531 | # [RipQP.jl documentation](@id Home)
This package provides a solver for minimizing convex quadratic problems, of the form:
```math
\min \frac{1}{2} x^T Q x + c^T x + c_0, ~~~~ s.t. ~~ \ell con \le A x \le ucon, ~~ \ell \le x \le u,
```
where Q is positive semi-definite and the bounds on x and Ax can be infinite.
RipQP uses Interior Point Methods and incorporates several linear algebra and optimization techniques.
It can run in several floating-point systems, and is able to switch between floating-point systems during the
resolution of a problem.
The user should be able to write its own solver to compute the direction of descent that should be used
at each iterate of RipQP.
RipQP can also solve constrained linear least squares problems:
```math
\min \frac{1}{2} \| A x - b \|^2, ~~~~ s.t. ~~ c_L \le C x \le c_U, ~~ \ell \le x \le u.
```
## Bug reports and discussions
If you think you found a bug, feel free to open an [issue](https://github.com/JuliaSmoothOptimizers/RipQP.jl/issues).
Focused suggestions and requests can also be opened as issues. Before opening a pull request, start an issue or a discussion on the topic, please.
If you want to ask a question not suited for a bug report, feel free to start a discussion [here](https://github.com/JuliaSmoothOptimizers/Organization/discussions). This forum is for general discussion about this repository and the [JuliaSmoothOptimizers](https://github.com/JuliaSmoothOptimizers) organization, so questions about any of our packages are welcome.
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | docs | 2412 | # Multi-precision
## Solving precision
You can use RipQP in several floating-point systems.
The algorithm will run in the precision of the input `QuadraticModel`.
For example, if you have a `QuadraticModel` `qm32` in `Float32`, then
```julia
stats = ripqp(qm32)
```
will solve this problem in `Float32`.
The stopping criteria of [`RipQP.InputTol`](@ref) will be adapted to the preicison of the `QuadraticModel` to solve.
## Multi-precision
You can use the multi-precision mode to solve a problem with a warm-start in a lower floating-point system.
[`RipQP.InputTol`](@ref) contains intermediate parameters that are used to decide when to transition from a lower precision to a higher precision.
```julia
stats = ripqp(qm, mode = :multi, itol = InputTol(ϵ_pdd1 = 1.0e-2))
```
`ϵ_pdd1` is used for the transition from `Float32` to `Float64`, while `ϵ_pdd` is used at the end of the algorithm.
## Refinement of the Quadratic Problem
Instead of just increasing the precision of the algorithm for the transition between precisions, it is possible to solve a refined quadratic problem.
References:
* T. Weber, S. Sager, A. Gleixner [*Solving quadratic programs to high precision using scaled iterative refinement*](https://doi.org/10.1007/s12532-019-00154-6), Mathematical Programming Computation, 49(6), pp. 421-455, 2019.
* D. Ma, L. Yang, R. M. T. Fleming, I. Thiele, B. O. Palsson, M. A. Saunders [*Reliable and efficient solution of genome-scale models of Metabolism and macromolecular Expression*](https://doi.org/10.1038/srep40863), Scientific Reports 7, 40863, 2017.
```julia
stats = ripqp(qm, mode = :multiref, itol = InputTol(ϵ_pdd1 = 1.0e-2))
stats = ripqp(qm, mode = :multizoom, itol = InputTol(ϵ_pdd1 = 1.0e-2))
```
The two presented algorithms follow the procedure described in each of the two above references.
## Switching solvers when increasing precision
Instead of using the same solver after the transition between two floating-point systems, it is possible to switch to another solver, if a conversion function from the old solver to the new solvers is implemented.
```julia
stats = ripqp(qm, mode = :multiref, solve_method = IPF(),
sp = K2LDLParams(),
sp2 = K2KrylovParams(uplo = :U, preconditioner = LDL(T = Float32)))
# start with K2LDL in Float32, then transition to Float64,
# then use K2Krylov in Float64 with a LDL preconditioner in Float32.
``` | RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | docs | 96 | # Reference
## Contents
```@contents
Pages = ["reference.md"]
```
## Index
```@index
``` | RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | docs | 6490 | # Switching solvers
## Solve method
By default, RipQP uses a predictor-corrector algorithm that solves two linear systems per interior-point iteration.
This is efficient when using a factorization to solve the interior-point system.
It is also possible to use an infeasible path-following algorithm, which is efficient when solving each system is more expensive (for example when using a Krylov method without preconditioner).
```julia
stats = ripqp(qm, solve_method = PC()) # predictor-corrector (default)
stats = ripqp(qm, solve_method = IPF()) # infeasible path-following
```
## Choosing a solver
It is possible to choose different solvers to solve the interior-point system.
All these solvers can be called with a structure that is a subtype of a [`RipQP.SolverParams`](@ref).
The default solver is [`RipQP.K2LDLParams`](@ref).
There are a lot of solvers that are implemented using Krylov methods from [`Krylov.jl`](https://github.com/JuliaSmoothOptimizers/Krylov.jl).
For example:
```julia
stats = ripqp(qm, sp = K2KrylovParams())
```
These solvers are usually less efficient, but they can be used with a preconditioner to improve the performances.
All these preconditioners can be called with a structure that is a subtype of an [`AbstractPreconditioner`](@ref).
By default, most Krylov solvers use the [`RipQP.Identity`](@ref) preconditioner, but is possible to use for example
a LDL factorization [`RipQP.LDL`](@ref).
The Krylov method then acts as form of using iterative refinement to a LDL factorization of K2:
```julia
stats = ripqp(qm, sp = K2KrylovParams(uplo = :U, preconditioner = LDL()))
# uplo = :U is mandatory with this preconditioner
```
It is also possible to change the Krylov method used to solve the system:
```julia
stats = ripqp(qm, sp = K2KrylovParams(uplo = :U, kmethod = :gmres, preconditioner = LDL()))
```
## Logging for Krylov Solver
Solvers using a Krylov method have two more log columns.
The first one is the number of iterations to solve the interior-point system with the Krylov method, and the second one is a character indication the output status of the Krylov method.
The different characters are `'u'` for user-requested exit (callback), `'i'` for maximum number of iterations exceeded, and `'s'` otherwise.
## Advanced: write your own solver
You can use your own solver to compute the direction of descent inside RipQP at each iteration.
Here is a basic example using the package [`LDLFactorizations.jl`](https://github.com/JuliaSmoothOptimizers/LDLFactorizations.jl).
First, you will need a [`RipQP.SolverParams`](@ref) to define parameters for your solver:
```julia
using RipQP, LinearAlgebra, LDLFactorizations, SparseArrays
struct K2basicLDLParams{T<:Real} <: SolverParams
uplo :: Symbol # mandatory, tells RipQP which triangle of the augmented system to store
ρ :: T # dual regularization
δ :: T # primal regularization
end
```
Then, you will have to create a type that allocates space for your solver, and a constructor using the following parameters:
```julia
mutable struct PreallocatedDataK2basic{T<:Real, S} <: RipQP.PreallocatedDataAugmented{T, S}
D :: S # temporary top-left diagonal of the K2 system
ρ :: T # dual regularization
δ :: T # primal regularization
K :: SparseMatrixCSC{T,Int} # K2 matrix
K_fact :: LDLFactorizations.LDLFactorization{T,Int,Int,Int} # factorized K2
end
```
Now you need to write a `RipQP.PreallocatedData` function that returns your type:
```julia
function RipQP.PreallocatedData(sp :: SolverParams, fd :: RipQP.QM_FloatData{T},
id :: RipQP.QM_IntData, itd :: RipQP.IterData{T},
pt :: RipQP.Point{T},
iconf :: InputConfig{Tconf}) where {T<:Real, Tconf<:Real}
ρ, δ = T(sp.ρ), T(sp.δ)
K = spzeros(T, id.ncon+id.nvar, id.ncon + id.nvar)
K[1:id.nvar, 1:id.nvar] = .-fd.Q .- ρ .* Diagonal(ones(T, id.nvar))
# A = Aᵀ of the input QuadraticModel since we use the upper triangle:
K[1:id.nvar, id.nvar+1:end] = fd.A
K[diagind(K)[id.nvar+1:end]] .= δ
K_fact = ldl_analyze(Symmetric(K, :U))
@assert sp.uplo == :U # LDLFactorizations does not work with the lower triangle
K_fact = ldl_factorize!(Symmetric(K, :U), K_fact)
K_fact.__factorized = true
return PreallocatedDataK2basic(zeros(T, id.nvar),
ρ,
δ,
K, #K
K_fact #K_fact
)
end
```
Then, you need to write a `RipQP.update_pad!` function that will update the `RipQP.PreallocatedData`
struct before computing the direction of descent.
```julia
function RipQP.update_pad!(pad :: PreallocatedDataK2basic{T}, dda :: RipQP.DescentDirectionAllocs{T},
pt :: RipQP.Point{T}, itd :: RipQP.IterData{T},
fd :: RipQP.Abstract_QM_FloatData{T}, id :: RipQP.QM_IntData,
res :: RipQP.Residuals{T}, cnts :: RipQP.Counters) where {T<:Real}
# update the diagonal of K2
pad.D .= -pad.ρ
pad.D[id.ilow] .-= pt.s_l ./ itd.x_m_lvar
pad.D[id.iupp] .-= pt.s_u ./ itd.uvar_m_x
pad.D .-= fd.Q[diagind(fd.Q)]
pad.K[diagind(pad.K)[1:id.nvar]] = pad.D
pad.K[diagind(pad.K)[id.nvar+1:end]] .= pad.δ
# factorize K2
ldl_factorize!(Symmetric(pad.K, :U), pad.K_fact)
end
```
Finally, you need to write a `RipQP.solver!` function that compute directions of descent.
Note that this function solves in-place the linear system by overwriting the direction of descent.
That is why the direction of descent `dd` contains the right hand side of the linear system to solve.
```julia
function RipQP.solver!(dd :: AbstractVector{T}, pad :: PreallocatedDataK2basic{T},
dda :: RipQP.DescentDirectionAllocsPC{T}, pt :: RipQP.Point{T},
itd :: RipQP.IterData{T}, fd :: RipQP.Abstract_QM_FloatData{T},
id :: RipQP.QM_IntData, res :: RipQP.Residuals{T},
cnts :: RipQP.Counters, step :: Symbol) where {T<:Real}
ldiv!(pad.K_fact, dd)
return 0
end
```
Then, you can use your solver:
```julia
using QuadraticModels, QPSReader
qm = QuadraticModel(readqps("QAFIRO.SIF"))
stats1 = ripqp(qm, sp = K2basicLDLParams(:U, 1.0e-6, 1.0e-6))
```
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.4 | a734ff1ea463d482c7fad756d128810e829bd44b | docs | 3298 | # Tutorial
## Input
RipQP uses the package [QuadraticModels.jl](https://github.com/JuliaSmoothOptimizers/QuadraticModels.jl) to model
convex quadratic problems.
Here is a basic example:
```@example QM
using QuadraticModels, LinearAlgebra, SparseMatricesCOO
Q = [6. 2. 1.
2. 5. 2.
1. 2. 4.]
c = [-8.; -3; -3]
A = [1. 0. 1.
0. 2. 1.]
b = [0.; 3]
l = [-1.0;0;0]
u = [Inf; Inf; Inf]
QM = QuadraticModel(
c,
SparseMatrixCOO(tril(Q)),
A=SparseMatrixCOO(A),
lcon=b,
ucon=b,
lvar=l,
uvar=u,
c0=0.,
name="QM"
)
```
Once your `QuadraticModel` is loaded, you can simply solve it RipQP:
```@example QM
using RipQP
stats = ripqp(QM)
println(stats)
```
The `stats` output is a
[GenericExecutionStats](https://jso.dev/SolverCore.jl/dev/reference/#SolverCore.GenericExecutionStats).
It is also possible to use the package [QPSReader.jl](https://github.com/JuliaSmoothOptimizers/QPSReader.jl) in order to
read convex quadratic problems in MPS or SIF formats: (download [QAFIRO](https://raw.githubusercontent.com/JuliaSmoothOptimizers/RipQP.jl/main/test/QAFIRO.SIF))
```@example QM
using QPSReader, QuadraticModels
QM = QuadraticModel(readqps("assets/QAFIRO.SIF"))
```
## Logging
RipQP displays some logs at each iterate.
```@example QM
stats = ripqp(QM)
println(stats)
```
You can deactivate logging with
```@example QM
stats = ripqp(QM, display = false)
println(stats)
```
It is also possible to get a history of several quantities such as the primal and dual residuals and the relative primal-dual gap. These quantites are available in the dictionary `solver_specific` of the `stats`.
```@example QM
stats = ripqp(QM, display = false, history = true)
pddH = stats.solver_specific[:pddH]
```
## Change configuration and tolerances
You can use `RipQP` without presolve and scaling with:
```julia
stats = ripqp(QM, ps=false, scaling = false)
```
You can also change the [`RipQP.InputTol`](https://jso.dev/RipQP.jl/stable/API/#RipQP.InputTol) type to change the tolerances for the stopping criteria:
```@example QM
stats = ripqp(QM, itol = InputTol(max_iter = 5))
println(stats)
```
## Save the Interior-Point system
At every iteration, RipQP solves two linear systems with the default Predictor-Corrector method (the affine system and the corrector-centering system), or one linear system with the Infeasible Path-Following method.
To save these systems, you can use:
```julia
w = SystemWrite(write = true, name="test_", kfirst = 4, kgap=3)
stats = ripqp(QM, w = w)
```
This will save one matrix and the associated two right hand sides of the PC method every three iterations starting at iteration four.
Then, you can read the saved files with:
```julia
using DelimitedFiles, MatrixMarket
K = MatrixMarket.mmread("test_K_iter4.mtx")
rhs_aff = readdlm("test_rhs_iter4_aff.rhs", Float64)[:]
rhs_cc = readdlm("test_rhs_iter4_cc.rhs", Float64)[:];
```
## Timers
You can see the elapsed time with:
```julia
stats.elapsed_time
```
For more advance timers you can use [TimerOutputs.jl](https://github.com/KristofferC/TimerOutputs.jl):
```julia
using TimerOutputs
TimerOutputs.enable_debug_timings(RipQP)
reset_timer!(RipQP.to)
stats = ripqp(QM)
TimerOutputs.complement!(RipQP.to) # print complement of timed sections
show(RipQP.to, sortby = :firstexec)
```
| RipQP | https://github.com/JuliaSmoothOptimizers/RipQP.jl.git |
|
[
"MIT"
] | 0.6.0 | a895ade45ba4b5255d4c7880dda3492c37d27d65 | code | 1024 | using HarmonicOrthogonalPolynomials, Plot
plotly()
G = HarmonicOrthogonalPolynomials.grid(SphericalHarmonic()[:,Block.(Base.OneTo(10))])
n,m = size(G)
g = append!(vec(G), [SphericalCoordinate(0,0), SphericalCoordinate(π,0)])
x,y,z = ntuple(k ->getindex.(g,k), 3);
N = length(g)
i = [range(0; length=m, step=n); ]
j = [range(n; length=m-1, step=n); 0]
k = fill(N-2, m)
for ν = range(0; length=m-1, step=n)
append!(i, range(ν; length=n-1))
append!(i, range(ν+n; length=n-1))
append!(j, range(ν+1; length=n-1))
append!(j, range(ν+1; length=n-1))
append!(k, range(ν+n; length=n-1))
append!(k, range(ν+n+1; length=n-1))
end
append!(i, range(n*(m-1); length=n-1))
append!(i, range(0; length=n-1))
append!(j, range(n*(m-1)+1; length=n-1))
append!(j, range(n*(m-1)+1; length=n-1))
append!(k, range(0; length=n-1))
append!(k, range(1; length=n-1))
append!(i, [range(2n-1; length=m-1, step=n); n-1])
append!(j, range(n-1; length=m, step=n))
append!(k, fill(N-1, m))
mesh3d(x,y,z; connections = (i,j,k)) | HarmonicOrthogonalPolynomials | https://github.com/JuliaApproximation/HarmonicOrthogonalPolynomials.jl.git |
|
[
"MIT"
] | 0.6.0 | a895ade45ba4b5255d4c7880dda3492c37d27d65 | code | 6497 | module HarmonicOrthogonalPolynomials
using FastTransforms, LinearAlgebra, ClassicalOrthogonalPolynomials, ContinuumArrays, DomainSets,
BlockArrays, BlockBandedMatrices, InfiniteArrays, StaticArrays, QuasiArrays, Base, SpecialFunctions
import Base: OneTo, oneto, axes, getindex, convert, to_indices, tail, eltype, *, ==, ^, copy, -, abs, resize!
import BlockArrays: block, blockindex, unblock, BlockSlice
import DomainSets: indomain, Sphere
import LinearAlgebra: norm, factorize
import QuasiArrays: to_quasi_index, SubQuasiArray, *
import ContinuumArrays: TransformFactorization, @simplify, ProjectionFactorization, plan_grid_transform, plan_transform, grid, grid_layout, plotgrid_layout, AbstractBasisLayout, MemoryLayout
import ClassicalOrthogonalPolynomials: checkpoints, _sum, cardinality, increasingtruncations
import BlockBandedMatrices: BlockRange1, _BandedBlockBandedMatrix
import FastTransforms: Plan, interlace
import QuasiArrays: LazyQuasiMatrix, LazyQuasiArrayStyle
import InfiniteArrays: InfStepRange, RangeCumsum
export SphericalHarmonic, UnitSphere, SphericalCoordinate, RadialCoordinate, Block, associatedlegendre, RealSphericalHarmonic, sphericalharmonicy, Laplacian, AbsLaplacianPower, abs, -, ^, AngularMomentum
cardinality(::Sphere) = ℵ₁
include("multivariateops.jl")
include("spheretrav.jl")
include("coordinates.jl")
# roughly try to double the computational time each iteration
increasingtruncations(::BlockedOneTo{Int,<:RangeCumsum{Int,<:AbstractRange}}) = broadcast(n -> Block.(oneto((2^(n ÷ 2)) ÷ 2)), 4:2:∞)
checkpoints(::UnitSphere{T}) where T = [SphericalCoordinate{T}(0.1,0.2), SphericalCoordinate{T}(0.3,0.4)]
abstract type AbstractSphericalHarmonic{T} <: MultivariateOrthogonalPolynomial{3,T} end
struct RealSphericalHarmonic{T} <: AbstractSphericalHarmonic{T} end
struct SphericalHarmonic{T} <: AbstractSphericalHarmonic{T} end
SphericalHarmonic() = SphericalHarmonic{ComplexF64}()
RealSphericalHarmonic() = RealSphericalHarmonic{Float64}()
axes(S::AbstractSphericalHarmonic{T}) where T = (Inclusion{SphericalCoordinate{real(T)}}(UnitSphere{real(T)}()), blockedrange(1:2:∞))
associatedlegendre(m) = ((-1)^m*prod(1:2:(2m-1)))*(UltrasphericalWeight((m+1)/2).*Ultraspherical(m+1/2))
lgamma(n) = logabsgamma(n)[1]
function sphericalharmonicy(ℓ, m, θ, φ)
m̃ = abs(m)
exp((lgamma(ℓ+m̃+1)+lgamma(ℓ-m̃+1)-2lgamma(ℓ+1))/2)*sqrt((2ℓ+1)/(4π)) * exp(im*m*φ) * sin(θ/2)^m̃ * cos(θ/2)^m̃ * jacobip(ℓ-m̃,m̃,m̃,cos(θ))
end
function getindex(S::SphericalHarmonic{T}, x::SphericalCoordinate, K::BlockIndex{1}) where T
ℓ = Int(block(K))
k = blockindex(K)
m = k-ℓ
convert(T, sphericalharmonicy(ℓ-1, m, x.θ, x.φ))::T
end
==(::SphericalHarmonic{T},::SphericalHarmonic{T}) where T = true
==(::RealSphericalHarmonic{T},::RealSphericalHarmonic{T}) where T = true
# function getindex(S::RealSphericalHarmonic{T}, x::ZSphericalCoordinate, K::BlockIndex{1}) where T
# # sorts entries by ...-2,-1,0,1,2... scheme
# ℓ = Int(block(K))
# k = blockindex(K)
# m = k-ℓ
# m̃ = abs(m)
# indepm = (-1)^m̃*exp((lgamma(ℓ-m̃)-lgamma(ℓ+m̃))/2)*sqrt((2ℓ-1)/(2π))*associatedlegendre(m̃)[x.z,ℓ-m̃]
# m>0 && return cos(m*x.φ)*indepm
# m==0 && return cos(m*x.φ)/sqrt(2)*indepm
# m<0 && return sin(m̃*x.φ)*indepm
# end
function getindex(S::RealSphericalHarmonic{T}, x::SphericalCoordinate, K::BlockIndex{1}) where T
# starts with m=0, then alternates between sin and cos terms (beginning with sin).
ℓ = Int(block(K))
m = blockindex(K)-1
z = cos(x.θ)
if iszero(m)
return sqrt((2ℓ-1)/(4*π))*associatedlegendre(0)[z,ℓ]
elseif isodd(m)
m = (m+1)÷2
return sin(m*x.φ)*(-1)^m*exp((lgamma(ℓ-m)-lgamma(ℓ+m))/2)*sqrt((2ℓ-1)/(2*π))*associatedlegendre(m)[z,ℓ-m]
else
m = m÷2
return cos(m*x.φ)*(-1)^m*exp((lgamma(ℓ-m)-lgamma(ℓ+m))/2)*sqrt((2ℓ-1)/(2*π))*associatedlegendre(m)[z,ℓ-m]
end
end
getindex(S::AbstractSphericalHarmonic, x::StaticVector{3}, K::BlockIndex{1}) = S[SphericalCoordinate(x), K]
getindex(S::AbstractSphericalHarmonic, x::StaticVector{3}, K::Block{1}) = S[x, axes(S,2)[K]]
getindex(S::AbstractSphericalHarmonic, x::StaticVector{3}, KR::BlockOneTo) = mortar([S[x, K] for K in KR])
getindex(S::AbstractSphericalHarmonic, x::StaticVector{3}, k::Int) = S[x, findblockindex(axes(S,2), k)]
getindex(S::AbstractSphericalHarmonic, x::StaticVector{3}, kr::AbstractUnitRange{Int}) = [S[x, k] for k in kr]
# @simplify *(Ac::QuasiAdjoint{<:Any,<:SphericalHarmonic}, B::SphericalHarmonic) =
##
# Expansion
##
function grid(S::AbstractSphericalHarmonic, B::Block{1})
N = Int(B)
T = real(eltype(S))
# The colatitudinal grid (mod $\pi$):
θ = ((1:N) .- one(T)/2)/N
# The longitudinal grid (mod $\pi$):
M = 2*N-1
φ = (0:M-1)*2/convert(T, M)
SphericalCoordinate.(π*θ, π*φ')
end
struct SphericalHarmonicTransform{T} <: Plan{T}
sph2fourier::FastTransforms.FTPlan{T,2,FastTransforms.SPINSPHERE}
analysis::FastTransforms.FTPlan{T,2,FastTransforms.SPINSPHEREANALYSIS}
end
struct RealSphericalHarmonicTransform{T} <: Plan{T}
sph2fourier::FastTransforms.FTPlan{T,2,FastTransforms.SPHERE}
analysis::FastTransforms.FTPlan{T,2,FastTransforms.SPHEREANALYSIS}
end
SphericalHarmonicTransform{T}(N::Int) where T<:Complex = SphericalHarmonicTransform{T}(plan_spinsph2fourier(T, N, 0), plan_spinsph_analysis(T, N, 2N-1, 0))
RealSphericalHarmonicTransform{T}(N::Int) where T<:Real = RealSphericalHarmonicTransform{T}(plan_sph2fourier(T, N), plan_sph_analysis(T, N, 2N-1))
*(P::SphericalHarmonicTransform{T}, f::Matrix{T}) where T = SphereTrav(P.sph2fourier \ (P.analysis * f))
*(P::RealSphericalHarmonicTransform{T}, f::Matrix{T}) where T = RealSphereTrav(P.sph2fourier \ (P.analysis * f))
plan_transform(P::SphericalHarmonic{T}, (N,)::Tuple{Block{1}}, dims=1) where T = SphericalHarmonicTransform{T}(Int(N))
plan_transform(P::RealSphericalHarmonic{T}, (N,)::Tuple{Block{1}}, dims=1) where T = RealSphericalHarmonicTransform{T}(Int(N))
grid(P::MultivariateOrthogonalPolynomial, n::Int) = grid(P, findblock(axes(P,2),n))
plan_transform(P::MultivariateOrthogonalPolynomial, Bs::NTuple{N,Int}, dims=ntuple(identity,Val(N))) where N = plan_transform(P, findblock.(Ref(axes(P,2)), Bs), dims)
function _sum(A::AbstractSphericalHarmonic{T}, dims) where T
@assert dims == 1
BlockedArray(Hcat(sqrt(4convert(T, π)), Zeros{T}(1,∞)), (Base.OneTo(1),axes(A,2)))
end
include("laplace.jl")
include("angularmomentum.jl")
end # module
| HarmonicOrthogonalPolynomials | https://github.com/JuliaApproximation/HarmonicOrthogonalPolynomials.jl.git |
|
[
"MIT"
] | 0.6.0 | a895ade45ba4b5255d4c7880dda3492c37d27d65 | code | 1698 | #########
# AngularMomentum
# Applies the partial derivative with respect to the last angular variable in the coordinate system.
# For example, in polar coordinates (r, θ) in ℝ² or cylindrical coordinates (r, θ, z) in ℝ³, we apply ∂ / ∂θ = (x ∂ / ∂y - y ∂ / ∂x).
# In spherical coordinates (ρ, θ, φ) in ℝ³, we apply ∂ / ∂φ = (x ∂ / ∂y - y ∂ / ∂x).
#########
struct AngularMomentum{T,Ax<:Inclusion} <: LazyQuasiMatrix{T}
axis::Ax
end
AngularMomentum{T}(axis::Inclusion) where T = AngularMomentum{T,typeof(axis)}(axis)
AngularMomentum{T}(domain) where T = AngularMomentum{T}(Inclusion(domain))
AngularMomentum(axis) = AngularMomentum{eltype(eltype(axis))}(axis)
axes(A::AngularMomentum) = (A.axis, A.axis)
==(a::AngularMomentum, b::AngularMomentum) = a.axis == b.axis
copy(A::AngularMomentum) = AngularMomentum(copy(A.axis))
^(A::AngularMomentum, k::Integer) = ApplyQuasiArray(^, A, k)
@simplify function *(A::AngularMomentum, P::SphericalHarmonic)
# Spherical harmonics are the eigenfunctions of the angular momentum operator on the unit sphere
T = real(eltype(P))
k = mortar(Base.OneTo.(1:2:∞))
m = T.((-1) .^ (k .- 1) .* k .÷ 2)
P * Diagonal(im .* m)
end
#=
@simplify function *(A::AngularMomentum, P::RealSphericalHarmonic)
# The angular momentum operator applied to real spherical harmonics negates orders
T = real(eltype(P))
n = mortar(Fill.(oneto(∞),1:2:∞))
k = mortar(Base.OneTo.(0:2:∞))
m = T.(iseven.(k) .* (k .÷ 2))
dat = BlockedArray(Vcat(
(-m)', # n, k-1
(0 .* m)', # n, k
(m)', # n, k+1
), (blockedrange(Fill(3, 1)), axes(n,1)))
P * _BandedBlockBandedMatrix(dat', axes(k,1), (0,0), (1,1))
end
=#
| HarmonicOrthogonalPolynomials | https://github.com/JuliaApproximation/HarmonicOrthogonalPolynomials.jl.git |
|
[
"MIT"
] | 0.6.0 | a895ade45ba4b5255d4c7880dda3492c37d27d65 | code | 3768 | ###
# RadialCoordinate
####
"""
RadialCoordinate(r, θ)
represents the 2-vector [r*cos(θ),r*sin(θ)]
"""
struct RadialCoordinate{T} <: StaticVector{2,T}
r::T
θ::T
RadialCoordinate{T}(r::T, θ::T) where T = new{T}(r, θ)
end
RadialCoordinate{T}(r, θ) where T = RadialCoordinate{T}(convert(T,r), convert(T,θ))
RadialCoordinate(r::T, θ::V) where {T<:Real,V<:Real} = RadialCoordinate{float(promote_type(T,V))}(r, θ)
function RadialCoordinate(xy::StaticVector{2})
x,y = xy
RadialCoordinate(norm(xy), atan(y,x))
end
StaticArrays.SVector(rθ::RadialCoordinate) = SVector(rθ.r * cos(rθ.θ), rθ.r * sin(rθ.θ))
getindex(R::RadialCoordinate, k::Int) = SVector(R)[k]
norm(rθ::RadialCoordinate) = rθ.r
###
# SphericalCoordinate
###
abstract type AbstractSphericalCoordinate{T} <: StaticVector{3,T} end
norm(::AbstractSphericalCoordinate{T}) where T = real(one(T))
Base.in(::AbstractSphericalCoordinate, ::UnitSphere{T}) where T = true
"""
SphericalCoordinate(θ, φ)
represents a point in the unit sphere as a `StaticVector{3}` in
spherical coordinates where the pole is `SphericalCoordinate(0,φ) == SVector(0,0,1)`
and `SphericalCoordinate(π/2,0) == SVector(1,0,0)`.
"""
struct SphericalCoordinate{T} <: AbstractSphericalCoordinate{T}
θ::T
φ::T
SphericalCoordinate{T}(θ::T, φ::T) where T = new{T}(θ, φ)
end
SphericalCoordinate{T}(θ, φ) where T = SphericalCoordinate{T}(convert(T,θ), convert(T,φ))
SphericalCoordinate(θ::V, φ::T) where {T<:Real,V<:Real} = SphericalCoordinate{float(promote_type(T,V))}(θ, φ)
SphericalCoordinate(S::SphericalCoordinate) = S
"""
ZSphericalCoordinate(φ, z)
represents a point in the unit sphere as a `StaticVector{3}` in
where `z` is specified while the angle coordinate is given by spherical coordinates where the pole is `SVector(0,0,1)`.
"""
struct ZSphericalCoordinate{T} <: AbstractSphericalCoordinate{T}
φ::T
z::T
function ZSphericalCoordinate{T}(φ::T, z::T) where T
-1 ≤ z ≤ 1 || throw(ArgumentError("z must be between -1 and 1"))
new{T}(φ, z)
end
end
ZSphericalCoordinate(φ::T, z::V) where {T,V} = ZSphericalCoordinate{promote_type(T,V)}(φ,z)
ZSphericalCoordinate(S::SphericalCoordinate) = ZSphericalCoordinate(S.φ, cos(S.θ))
ZSphericalCoordinate{T}(S::SphericalCoordinate) where T = ZSphericalCoordinate{T}(S.φ, cos(S.θ))
SphericalCoordinate(S::ZSphericalCoordinate) = SphericalCoordinate(acos(S.z), S.φ)
SphericalCoordinate{T}(S::ZSphericalCoordinate) where T = SphericalCoordinate{T}(acos(S.z), S.φ)
function getindex(S::SphericalCoordinate, k::Int)
k == 1 && return sin(S.θ) * cos(S.φ)
k == 2 && return sin(S.θ) * sin(S.φ)
k == 3 && return cos(S.θ)
throw(BoundsError(S, k))
end
function getindex(S::ZSphericalCoordinate, k::Int)
k == 1 && return sqrt(1-S.z^2) * cos(S.φ)
k == 2 && return sqrt(1-S.z^2) * sin(S.φ)
k == 3 && return S.z
throw(BoundsError(S, k))
end
convert(::Type{SVector{3,T}}, S::SphericalCoordinate) where T = SVector{3,T}(sin(S.θ)*cos(S.φ), sin(S.θ)*sin(S.φ), cos(S.θ))
convert(::Type{SVector{3,T}}, S::ZSphericalCoordinate) where T = SVector{3,T}(sqrt(1-S.z^2)*cos(S.φ), sqrt(1-S.z^2)*sin(S.φ), S.z)
convert(::Type{SVector{3}}, S::SphericalCoordinate) = SVector(sin(S.θ)*cos(S.φ), sin(S.θ)*sin(S.φ), cos(S.θ))
convert(::Type{SVector{3}}, S::ZSphericalCoordinate) = SVector(sqrt(1-S.z^2)*cos(S.φ), sqrt(1-S.z^2)*sin(S.φ), S.z)
convert(::Type{SphericalCoordinate}, S::ZSphericalCoordinate) = SphericalCoordinate(S)
convert(::Type{SphericalCoordinate{T}}, S::ZSphericalCoordinate) where T = SphericalCoordinate{T}(S)
convert(::Type{ZSphericalCoordinate}, S::SphericalCoordinate) = ZSphericalCoordinate(S)
convert(::Type{ZSphericalCoordinate{T}}, S::SphericalCoordinate) where T = ZSphericalCoordinate{T}(S)
| HarmonicOrthogonalPolynomials | https://github.com/JuliaApproximation/HarmonicOrthogonalPolynomials.jl.git |
|
[
"MIT"
] | 0.6.0 | a895ade45ba4b5255d4c7880dda3492c37d27d65 | code | 1225 | # Laplacian
struct Laplacian{T,D} <: LazyQuasiMatrix{T}
axis::Inclusion{T,D}
end
Laplacian{T}(axis::Inclusion{<:Any,D}) where {T,D} = Laplacian{T,D}(axis)
# Laplacian{T}(domain) where T = Laplacian{T}(Inclusion(domain))
# Laplacian(axis) = Laplacian{eltype(axis)}(axis)
axes(D::Laplacian) = (D.axis, D.axis)
==(a::Laplacian, b::Laplacian) = a.axis == b.axis
copy(D::Laplacian) = Laplacian(copy(D.axis))
@simplify function *(Δ::Laplacian, P::AbstractSphericalHarmonic)
# Spherical harmonics are the eigenfunctions of the Laplace operator on the unit sphere
P * Diagonal(mortar(Fill.((-(0:∞)-(0:∞).^2), 1:2:∞)))
end
# Negative fractional Laplacian (-Δ)^α or equiv. abs(Δ)^α
struct AbsLaplacianPower{T,D,A} <: LazyQuasiMatrix{T}
axis::Inclusion{T,D}
α::A
end
AbsLaplacianPower{T}(axis::Inclusion{<:Any,D},α) where {T,D} = AbsLaplacianPower{T,D,typeof(α)}(axis,α)
axes(D:: AbsLaplacianPower) = (D.axis, D.axis)
==(a:: AbsLaplacianPower, b:: AbsLaplacianPower) = a.axis == b.axis && a.α == b.α
copy(D:: AbsLaplacianPower) = AbsLaplacianPower(copy(D.axis), D.α)
abs(Δ::Laplacian) = AbsLaplacianPower(axes(Δ,1),1)
-(Δ::Laplacian) = abs(Δ)
^(D::AbsLaplacianPower, k) = AbsLaplacianPower(D.axis, D.α*k) | HarmonicOrthogonalPolynomials | https://github.com/JuliaApproximation/HarmonicOrthogonalPolynomials.jl.git |
|
[
"MIT"
] | 0.6.0 | a895ade45ba4b5255d4c7880dda3492c37d27d65 | code | 5159 |
#########
# PartialDerivative{k}
# takes a partial derivative in the k-th index.
#########
struct PartialDerivative{k,T,Ax<:Inclusion} <: LazyQuasiMatrix{T}
axis::Ax
end
PartialDerivative{k,T}(axis::Inclusion) where {k,T} = PartialDerivative{k,T,typeof(axis)}(axis)
PartialDerivative{k,T}(domain) where {k,T} = PartialDerivative{k,T}(Inclusion(domain))
PartialDerivative{k}(axis) where k = PartialDerivative{k,eltype(eltype(axis))}(axis)
axes(D::PartialDerivative) = (D.axis, D.axis)
==(a::PartialDerivative{k}, b::PartialDerivative{k}) where k = a.axis == b.axis
copy(D::PartialDerivative{k}) where k = PartialDerivative{k}(copy(D.axis))
^(D::PartialDerivative, k::Integer) = ApplyQuasiArray(^, D, k)
abstract type MultivariateOrthogonalPolynomial{d,T} <: Basis{T} end
const BivariateOrthogonalPolynomial{T} = MultivariateOrthogonalPolynomial{2,T}
struct MultivariateOPLayout{d} <: AbstractBasisLayout end
MemoryLayout(::Type{<:MultivariateOrthogonalPolynomial{d}}) where d = MultivariateOPLayout{d}()
const BlockOneTo = BlockRange{1,Tuple{OneTo{Int}}}
copy(P::MultivariateOrthogonalPolynomial) = P
getindex(P::MultivariateOrthogonalPolynomial{D}, xy::StaticVector{D}, JR::BlockOneTo) where D = error("Overload")
getindex(P::MultivariateOrthogonalPolynomial{D}, xy::StaticVector{D}, J::Block{1}) where D = P[xy, Block.(OneTo(Int(J)))][J]
getindex(P::MultivariateOrthogonalPolynomial{D}, xy::StaticVector{D}, JR::BlockRange{1}) where D = P[xy, Block.(OneTo(Int(maximum(JR))))][JR]
getindex(P::MultivariateOrthogonalPolynomial{D}, xy::StaticVector{D}, Jj::BlockIndex{1}) where D = P[xy, block(Jj)][blockindex(Jj)]
getindex(P::MultivariateOrthogonalPolynomial{D}, xy::StaticVector{D}, j::Integer) where D = P[xy, findblockindex(axes(P,2), j)]
getindex(P::MultivariateOrthogonalPolynomial{D}, xy::StaticVector{D}, jr::AbstractVector{<:Integer}) where D = P[xy, Block.(OneTo(Int(findblock(axes(P,2), maximum(jr)))))][jr]
const FirstInclusion = BroadcastQuasiVector{<:Any, typeof(first), <:Tuple{Inclusion}}
const LastInclusion = BroadcastQuasiVector{<:Any, typeof(last), <:Tuple{Inclusion}}
function Base.broadcasted(::LazyQuasiArrayStyle{2}, ::typeof(*), x::FirstInclusion, P::MultivariateOrthogonalPolynomial)
axes(x,1) == axes(P,1) || throw(DimensionMismatch())
P*jacobimatrix(Val(1), P)
end
function Base.broadcasted(::LazyQuasiArrayStyle{2}, ::typeof(*), x::LastInclusion, P::MultivariateOrthogonalPolynomial)
axes(x,1) == axes(P,1) || throw(DimensionMismatch())
P*jacobimatrix(Val(2), P)
end
"""
forwardrecurrence!(v, A, B, C, (x,y))
evaluates the bivaraite orthogonal polynomials at points `(x,y)` ,
where `A`, `B`, and `C` are `AbstractVector`s containing the recurrence coefficients
matrices. In particular, note that for any OPs we have
P[N+1,x] = (A[N]* [x*I; y*I] + B[N]) * P[N,x] - C[N] * P[N-1,x]
where A[N] is (N+1) x 2N, B[N] and C[N] are (N+1) x N.
"""
# function forwardrecurrence!(v::AbstractBlockVector{T}, A::AbstractVector, B::AbstractVector, C::AbstractVector, xy) where T
# N = blocklength(v)
# N == 0 && return v
# length(A)+1 ≥ N && length(B)+1 ≥ N && length(C)+1 ≥ N || throw(ArgumentError("A, B, C must contain at least $(N-1) entries"))
# v[Block(1)] .= one(T)
# N = 1 && return v
# p_1 = view(v,Block(2))
# p_0 = view(v,Block(1))
# mul!(p_1, B[1], p_0)
# xy_muladd!(xy, A[1], p_0, one(T), p_1)
# @inbounds for n = 2:N-1
# p_2 = view(v,Block(n+1))
# mul!(p_2, B[n], p_1)
# xy_muladd!(xy, A[n], p_1, one(T), p_2)
# muladd!(-one(T), C[n], p_0, one(T), p_2)
# p_1,p_0 = p_2,p_1
# end
# v
# end
# forwardrecurrence(N::Block{1}, A::AbstractVector, B::AbstractVector, C::AbstractVector, xy) =
# forwardrecurrence!(BlockedVector{promote_type(eltype(eltype(A)),eltype(eltype(B)),eltype(eltype(C)),eltype(xy))}(undef, 1:Int(N)), A, B, C, xy)
# use block expansion
ContinuumArrays.transform_ldiv(V::SubQuasiArray{<:Any,2,<:MultivariateOrthogonalPolynomial,<:Tuple{Inclusion,BlockSlice{BlockOneTo}}}, B::AbstractQuasiArray, _) =
factorize(V) \ B
ContinuumArrays._sub_factorize(::Tuple{Any,Any}, (kr,jr)::Tuple{Any,BlockSlice{BlockRange1{OneTo{Int}}}}, L, dims...; kws...) =
TransformFactorization(plan_grid_transform(parent(L), (last(jr.block), dims...), 1)...)
# function factorize(V::SubQuasiArray{<:Any,2,<:MultivariateOrthogonalPolynomial,<:Tuple{Inclusion,AbstractVector{Int}}})
# P = parent(V)
# _,jr = parentindices(V)
# J = findblock(axes(P,2),maximum(jr))
# ProjectionFactorization(factorize(P[:,Block.(OneTo(Int(J)))]), jr)
# end
# Make sure block structure matches. Probably should do this for all block mul
QuasiArrays.mul(A::MultivariateOrthogonalPolynomial, b::AbstractVector) =
ApplyQuasiArray(*, A, BlockedVector(b, (axes(A,2),)))
# plotting
const MAX_PLOT_BLOCKS = 200
grid_layout(::MultivariateOPLayout, S, n::Integer) = grid(S, findblock(axes(S,2), n))
plotgrid_layout(::MultivariateOPLayout, S, n::Integer) = plotgrid(S, findblock(axes(S,2), n))
plotgrid_layout(::MultivariateOPLayout, S, B::Block{1}) = grid(S, min(2B, Block(MAX_PLOT_BLOCKS)))
| HarmonicOrthogonalPolynomials | https://github.com/JuliaApproximation/HarmonicOrthogonalPolynomials.jl.git |
|
[
"MIT"
] | 0.6.0 | a895ade45ba4b5255d4c7880dda3492c37d27d65 | code | 2502 |
###
# SphereTrav
###
"""
SphereTrav(A::AbstractMatrix)
is an anlogue of `DiagTrav` but for coefficients stored according to
FastTransforms.jl spherical harmonics layout
"""
struct SphereTrav{T, AA<:AbstractMatrix{T}} <: AbstractBlockVector{T}
matrix::AA
function SphereTrav{T, AA}(matrix::AA) where {T,AA<:AbstractMatrix{T}}
n,m = size(matrix)
m == 2n-1 || throw(ArgumentError("size must match"))
new{T,AA}(matrix)
end
end
SphereTrav{T}(matrix::AbstractMatrix{T}) where T = SphereTrav{T,typeof(matrix)}(matrix)
SphereTrav(matrix::AbstractMatrix{T}) where T = SphereTrav{T}(matrix)
axes(A::SphereTrav) = (blockedrange(range(1; step=2, length=size(A.matrix,1))),)
function getindex(A::SphereTrav, K::Block{1})
k = Int(K)
m = size(A.matrix,1)
st = stride(A.matrix,2)
# nonnegative terms
p = A.matrix[range(k; step=2*st-1, length=k)]
k == 1 && return p
# negative terms
n = A.matrix[range(k+st-1; step=2*st-1, length=k-1)]
[reverse!(n); p]
end
getindex(A::SphereTrav, k::Int) = A[findblockindex(axes(A,1), k)]
"""
RealSphereTrav(A::AbstractMatrix)
takes coefficients as provided by the spherical harmonics layout of FastTransforms.jl and
makes them accessible sorted such that in each block the m=0 entries are always in first place,
followed by alternating sin and cos terms of increasing |m|.
"""
struct RealSphereTrav{T, AA<:AbstractMatrix{T}} <: AbstractBlockVector{T}
matrix::AA
function RealSphereTrav{T, AA}(matrix::AA) where {T,AA<:AbstractMatrix{T}}
n,m = size(matrix)
m == 2n-1 || throw(ArgumentError("size must match"))
new{T,AA}(matrix)
end
end
RealSphereTrav{T}(matrix::AbstractMatrix{T}) where T = RealSphereTrav{T,typeof(matrix)}(matrix)
RealSphereTrav(matrix::AbstractMatrix{T}) where T = RealSphereTrav{T}(matrix)
axes(A::RealSphereTrav) = (blockedrange(range(1; step=2, length=size(A.matrix,1))),)
function getindex(A::RealSphereTrav, K::Block{1})
k = Int(K)
m = size(A.matrix,1)
st = stride(A.matrix,2)
# nonnegative terms
p = A.matrix[range(k; step=2*st-1, length=k)]
k == 1 && return p
# negative terms
n = A.matrix[range(k+st-1; step=2*st-1, length=k-1)]
interlace(p,n)
end
getindex(A::RealSphereTrav, k::Int) = A[findblockindex(axes(A,1), k)]
for Typ in (:SphereTrav,:RealSphereTrav)
@eval function resize!(A::$Typ, K::Block{1})
k = Int(K)
$Typ(A.matrix[1:k, 1:2k-1])
end
end | HarmonicOrthogonalPolynomials | https://github.com/JuliaApproximation/HarmonicOrthogonalPolynomials.jl.git |
|
[
"MIT"
] | 0.6.0 | a895ade45ba4b5255d4c7880dda3492c37d27d65 | code | 15938 | using HarmonicOrthogonalPolynomials, StaticArrays, Test, InfiniteArrays, LinearAlgebra, BlockArrays, ClassicalOrthogonalPolynomials, QuasiArrays
import HarmonicOrthogonalPolynomials: ZSphericalCoordinate, associatedlegendre, grid, SphereTrav, RealSphereTrav, plotgrid
# @testset "associated legendre" begin
# m = 2
# θ = 0.1
# x = cos(θ)
# @test associatedlegendre(m)[x,1:10] ≈ -(2:11) .* (sin(θ/2)^m * cos(θ/2)^m * Jacobi(m,m)[x,1:10])
# end
@testset "SphereTrav" begin
A = SphereTrav([1 2 3; 4 0 0])
@test A == [1, 2, 4, 3]
@test A[Block(2)] == [2,4,3]
B = SphereTrav([1 2 3 4 5; 6 7 8 0 0; 9 0 0 0 0 ])
@test B == [1, 2, 6, 3, 4, 7, 9, 8, 5]
end
@testset "RadialCoordinate" begin
rθ = RadialCoordinate(0.1,0.2)
@test rθ ≈ SVector(rθ) ≈ [0.1cos(0.2),0.1sin(0.2)]
@test RadialCoordinate(1,0.2) isa RadialCoordinate{Float64}
@test RadialCoordinate(1,1) isa RadialCoordinate{Float64}
@test_throws BoundsError rθ[3]
end
@testset "SphericalCoordinate" begin
θφ = SphericalCoordinate(0.2,0.1)
@test θφ ≈ ZSphericalCoordinate(0.1,cos(0.2))
@test θφ == SVector(θφ)
@test SphericalCoordinate(1,1) isa SphericalCoordinate{Float64}
@test_throws BoundsError θφ[4]
φz = ZSphericalCoordinate(0.1,cos(0.2))
@test φz == SVector(φz)
@test norm(θφ) === norm(φz) === 1.0
@test θφ in UnitSphere()
@test ZSphericalCoordinate(0.1,cos(0.2)) in UnitSphere()
@test convert(SVector{3,Float64}, θφ) ≈ convert(SVector{3}, θφ) ≈
convert(SVector{3,Float64}, φz) ≈ convert(SVector{3}, φz) ≈ θφ
@test ZSphericalCoordinate(θφ) ≡ convert(ZSphericalCoordinate, θφ) ≡ φz
@test SphericalCoordinate(φz) ≡ convert(SphericalCoordinate, φz) ≡ θφ
end
@testset "Evaluation" begin
S = SphericalHarmonic()
@test copy(S) == S
@test eltype(axes(S,1)) == SphericalCoordinate{Float64}
θ,φ = 0.1,0.2
x = SphericalCoordinate(θ,φ)
@test S[x, Block(1)[1]] == S[x,1] == sqrt(1/(4π))
@test view(S,x, Block(1)).indices[1] isa SphericalCoordinate
@test S[x, Block(1)] == [sqrt(1/(4π))]
@test associatedlegendre(0)[0.1,1:2] ≈ [1.0,0.1]
@test associatedlegendre(1)[0.1,1:2] ≈ [-0.9949874371066201,-0.29849623113198603]
@test associatedlegendre(2)[0.1,1] ≈ 2.97
@test S[x,Block(2)] ≈ 0.5sqrt(3/π)*[1/sqrt(2)*sin(θ)exp(-im*φ),cos(θ),1/sqrt(2)*sin(θ)exp(im*φ)]
@test S[x,Block(3)] ≈ [0.25sqrt(15/2π)sin(θ)^2*exp(-2im*φ),
0.5sqrt(15/2π)sin(θ)cos(θ)exp(-im*φ),
0.25sqrt(5/π)*(3cos(θ)^2-1),
0.5sqrt(15/2π)sin(θ)cos(θ)exp(im*φ),
0.25sqrt(15/2π)sin(θ)^2*exp(2im*φ)]
@test S[x,Block(4)] ≈ [0.125sqrt(35/π)sin(θ)^3*exp(-3im*φ),
0.25sqrt(105/2π)sin(θ)^2*cos(θ)*exp(-2im*φ),
0.125sqrt(21/π)sin(θ)*(5cos(θ)^2-1)*exp(-im*φ),
0.25sqrt(7/π)*(5cos(θ)^3-3cos(θ)),
0.125sqrt(21/π)sin(θ)*(5cos(θ)^2-1)*exp(im*φ),
0.25sqrt(105/2π)sin(θ)^2*cos(θ)*exp(2im*φ),
0.125sqrt(35/π)sin(θ)^3*exp(3im*φ)]
@test S[x,Block.(1:4)] == [S[x,Block(1)]; S[x,Block(2)]; S[x,Block(3)]; S[x,Block(4)]]
end
@testset "Real Evaluation" begin
S = SphericalHarmonic()
R = RealSphericalHarmonic()
@test eltype(axes(R,1)) == SphericalCoordinate{Float64}
θ,φ = 0.1,0.2
x = SphericalCoordinate(θ,φ)
@test R[x, Block(1)[1]] ≈ R[x,1] ≈ sqrt(1/(4π))
@test R[x, Block(2)][1] ≈ S[x, Block(2)][2]
# Careful here with the (-1) conventions?
@test R[x, Block(2)][3] ≈ 1/sqrt(2)*(S[x, Block(2)][3]+S[x, Block(2)][1])
@test R[x, Block(2)][2] ≈ im/sqrt(2)*(S[x, Block(2)][1]-S[x, Block(2)][3])
end
@testset "Expansion" begin
@testset "grid" begin
N = 2
S = SphericalHarmonic()[:,Block.(Base.OneTo(N))]
@test size(S,2) == 4
g = grid(S)
@test eltype(g) == SphericalCoordinate{Float64}
@test plotgrid(S) == grid(SphericalHarmonic(), Block(4))
# compare with FastTransforms.jl/examples/sphere.jl
# The colatitudinal grid (mod $\pi$):
N = 2
θ = (0.5:N-0.5)/N
# The longitudinal grid (mod $\pi$):
M = 2*N-1
φ = (0:M-1)*2/M
X = [sinpi(θ)*cospi(φ) for θ in θ, φ in φ]
Y = [sinpi(θ)*sinpi(φ) for θ in θ, φ in φ]
Z = [cospi(θ) for θ in θ, φ in φ]
@test g ≈ SVector.(X, Y, Z)
end
@testset "transform" begin
N = 2
S = SphericalHarmonic()[:,Block.(Base.OneTo(N))]
xyz = axes(S,1)
P = factorize(S)
@test eltype(P) == ComplexF64
c = P \ (xyz -> 1).(xyz)
@test blocksize(c,1) == blocksize(S,2)
@test c == S \ (xyz -> 1).(xyz)
@test (S * c)[SphericalCoordinate(0.1,0.2)] ≈ 1
f = (x,y,z) -> 1 + x + y + z
c = S \ splat(f).(xyz)
u = S * c
p = SphericalCoordinate(0.1,0.2)
@test u[p] ≈ 1+sum(p)
x = grid(SphericalHarmonic(), 5)
P = plan_transform(SphericalHarmonic(), 5)
@test P * splat(f).(x) ≈ [c; zeros(5)]
end
@testset "adaptive" begin
S = SphericalHarmonic()
xyz = axes(S,1)
u = S * (S \ (xyz -> 1).(xyz))
@test u[SphericalCoordinate(0.1,0.2)] ≈ 1
f = c -> exp(-100*c.θ^2)
u = S * (S \ f.(xyz))
r = SphericalCoordinate(0.1,0.2)
@test u[r] ≈ f(r)
f = c -> ((x,y,z) = c; 1 + x + y + z)
u = S * (S \ f.(xyz))
p = SphericalCoordinate(0.1,0.2)
@test u[p] ≈ 1+sum(p)
f = c -> ((x,y,z) = c; exp(x)*cos(y*sin(z)))
u = S * (S \ f.(xyz))
@test u[p] ≈ f(p)
end
end
@testset "Real Expansion" begin
@testset "grid" begin
N = 2
S = RealSphericalHarmonic()[:,Block.(Base.OneTo(N))]
@test size(S,2) == 4
g = grid(S)
@test eltype(g) == SphericalCoordinate{Float64}
# compare with FastTransforms.jl/examples/sphere.jl
# The colatitudinal grid (mod $\pi$):
N = 2
θ = (0.5:N-0.5)/N
# The longitudinal grid (mod $\pi$):
M = 2*N-1
φ = (0:M-1)*2/M
X = [sinpi(θ)*cospi(φ) for θ in θ, φ in φ]
Y = [sinpi(θ)*sinpi(φ) for θ in θ, φ in φ]
Z = [cospi(θ) for θ in θ, φ in φ]
@test g ≈ SVector.(X, Y, Z)
end
@testset "transform" begin
N = 2
S = RealSphericalHarmonic()[:,Block.(Base.OneTo(N))]
xyz = axes(S,1)
P = factorize(S)
@test eltype(P) == Float64
c = P \ (xyz -> 1).(xyz)
@test blocksize(c,1) == blocksize(S,2)
@test c == S \ (xyz -> 1).(xyz)
@test (S * c)[SphericalCoordinate(0.1,0.2)] ≈ 1
f = c -> ((x,y,z) = c; 1 + x + y + z)
u = S * (S \ f.(xyz))
p = SphericalCoordinate(0.1,0.2)
@test u[p] ≈ 1+sum(p)
end
@testset "adaptive" begin
S = RealSphericalHarmonic()
xyz = axes(S,1)
u = S * (S \ (xyz -> 1).(xyz))
@test u[SphericalCoordinate(0.1,0.2)] ≈ 1
f = c -> exp(-100*c.θ^2)
u = S * (S \ f.(xyz))
r = SphericalCoordinate(0.1,0.2)
@test u[r] ≈ f(r)
f = c -> ((x,y,z) = c; 1 + x + y + z)
u = S * (S \ f.(xyz))
p = SphericalCoordinate(0.1,0.2)
@test u[p] ≈ 1+sum(p)
f = c -> ((x,y,z) = c; exp(x)*cos(y*sin(z)))
u = S * (S \ f.(xyz))
@test u[p] ≈ f(p)
end
end
@testset "Laplacian basics" begin
S = SphericalHarmonic()
R = RealSphericalHarmonic()
Sxyz = axes(S,1)
Rxyz = axes(R,1)
SΔ = Laplacian(Sxyz)
RΔ = Laplacian(Rxyz)
@test SΔ isa Laplacian
@test RΔ isa Laplacian
@test *(SΔ,S) isa ApplyQuasiArray
@test *(RΔ,R) isa ApplyQuasiArray
@test copy(SΔ) == SΔ == RΔ == copy(RΔ)
@test axes(SΔ) == axes(RΔ) == (axes(S,1),axes(S,1)) == (axes(R,1),axes(R,1))
@test axes(SΔ) isa Tuple{Inclusion{SphericalCoordinate{Float64}},Inclusion{SphericalCoordinate{Float64}}}
@test axes(RΔ) isa Tuple{Inclusion{SphericalCoordinate{Float64}},Inclusion{SphericalCoordinate{Float64}}}
@test Laplacian{eltype(axes(S,1))}(axes(S,1)) == SΔ
end
@testset "test copy() for SphericalHarmonics" begin
S = SphericalHarmonic()
R = RealSphericalHarmonic()
@test copy(S) == S
@test copy(R) == R
S = SphericalHarmonic()[:,Block.(Base.OneTo(10))]
R = RealSphericalHarmonic()[:,Block.(Base.OneTo(10))]
@test copy(S) == S
@test copy(R) == R
end
@testset "Eigenvalues of spherical Laplacian" begin
S = SphericalHarmonic()
xyz = axes(S,1)
Δ = Laplacian(xyz)
@test Δ isa Laplacian
# define some explicit spherical harmonics
Y_20 = c -> 1/4*sqrt(5/π)*(-1+3*cos(c.θ)^2)
Y_3m3 = c -> 1/8*exp(-3*im*c.φ)*sqrt(35/π)*sin(c.θ)^3
Y_41 = c -> 3/8*exp(im*c.φ)*sqrt(5/π)*cos(c.θ)*(-3+7*cos(c.θ)^2)*sin(c.θ) # note phase difference in definitions
# check that the above correctly represents the respective spherical harmonics
cfsY20 = S \ Y_20.(xyz)
@test cfsY20[Block(3)[3]] ≈ 1
cfsY3m3 = S \ Y_3m3.(xyz)
@test cfsY3m3[Block(4)[1]] ≈ 1
cfsY41 = S \ Y_41.(xyz)
@test cfsY41[Block(5)[6]] ≈ 1
# Laplacian evaluation and correct eigenvalues
@test (Δ*S*cfsY20)[SphericalCoordinate(0.7,0.2)] ≈ -6*Y_20(SphericalCoordinate(0.7,0.2))
@test (Δ*S*cfsY3m3)[SphericalCoordinate(0.1,0.36)] ≈ -12*Y_3m3(SphericalCoordinate(0.1,0.36))
@test (Δ*S*cfsY41)[SphericalCoordinate(1/3,6/7)] ≈ -20*Y_41(SphericalCoordinate(1/3,6/7))
end
@testset "Laplacian of expansions in complex spherical harmonics" begin
S = SphericalHarmonic()
xyz = axes(S,1)
Δ = Laplacian(xyz)
@test Δ isa Laplacian
# define some functions along with the action of the Laplace operator on the unit sphere
f1 = c -> cos(c.θ)^2
Δf1 = c -> -1-3*cos(2*c.θ)
f2 = c -> sin(c.θ)^2-3*cos(c.θ)
Δf2 = c -> 1+6*cos(c.θ)+3*cos(2*c.θ)
f3 = c -> 3*cos(c.φ)*sin(c.θ)-cos(c.θ)^2*sin(c.θ)^2
Δf3 = c -> -1/2-cos(2*c.θ)-5/2*cos(4*c.θ)-6*cos(c.φ)*sin(c.θ)
f4 = c -> cos(c.θ)^3
Δf4 = c -> -3*(cos(c.θ)+cos(3*c.θ))
f5 = c -> 3*cos(c.φ)*sin(c.θ)-2*sin(c.θ)^2
Δf5 = c -> 1-9*cos(c.θ)^2-6*cos(c.φ)*sin(c.θ)+3*sin(c.θ)^2
# compare with HarmonicOrthogonalPolynomials Laplacian
@test (Δ*S*(S\f1.(xyz)))[SphericalCoordinate(2.12,1.993)] ≈ Δf1(SphericalCoordinate(2.12,1.993))
@test (Δ*S*(S\f2.(xyz)))[SphericalCoordinate(3.108,1.995)] ≈ Δf2(SphericalCoordinate(3.108,1.995))
@test (Δ*S*(S\f3.(xyz)))[SphericalCoordinate(0.737,0.239)] ≈ Δf3(SphericalCoordinate(0.737,0.239))
@test (Δ*S*(S\f4.(xyz)))[SphericalCoordinate(0.162,0.162)] ≈ Δf4(SphericalCoordinate(0.162,0.162))
@test (Δ*S*(S\f5.(xyz)))[SphericalCoordinate(0.1111,0.999)] ≈ Δf5(SphericalCoordinate(0.1111,0.999))
end
@testset "Laplacian of expansions in real spherical harmonics" begin
R = RealSphericalHarmonic()
xyz = axes(R,1)
Δ = Laplacian(xyz)
@test Δ isa Laplacian
# define some functions along with the action of the Laplace operator on the unit sphere
f1 = c -> cos(c.θ)^2
Δf1 = c -> -1-3*cos(2*c.θ)
f2 = c -> sin(c.θ)^2-3*cos(c.θ)
Δf2 = c -> 1+6*cos(c.θ)+3*cos(2*c.θ)
f3 = c -> 3*cos(c.φ)*sin(c.θ)-cos(c.θ)^2*sin(c.θ)^2
Δf3 = c -> -1/2-cos(2*c.θ)-5/2*cos(4*c.θ)-6*cos(c.φ)*sin(c.θ)
f4 = c -> cos(c.θ)^3
Δf4 = c -> -3*(cos(c.θ)+cos(3*c.θ))
f5 = c -> 3*cos(c.φ)*sin(c.θ)-2*sin(c.θ)^2
Δf5 = c -> 1-9*cos(c.θ)^2-6*cos(c.φ)*sin(c.θ)+3*sin(c.θ)^2
# compare with HarmonicOrthogonalPolynomials Laplacian
@test (Δ*R*(R\f1.(xyz)))[SphericalCoordinate(2.12,1.993)] ≈ Δf1(SphericalCoordinate(2.12,1.993))
@test (Δ*R*(R\f2.(xyz)))[SphericalCoordinate(3.108,1.995)] ≈ Δf2(SphericalCoordinate(3.108,1.995))
@test (Δ*R*(R\f3.(xyz)))[SphericalCoordinate(0.737,0.239)] ≈ Δf3(SphericalCoordinate(0.737,0.239))
@test (Δ*R*(R\f4.(xyz)))[SphericalCoordinate(0.162,0.162)] ≈ Δf4(SphericalCoordinate(0.162,0.162))
@test (Δ*R*(R\f5.(xyz)))[SphericalCoordinate(0.1111,0.999)] ≈ Δf5(SphericalCoordinate(0.1111,0.999))
end
@testset "Laplacian raised to integer power, adaptive" begin
S = SphericalHarmonic()
xyz = axes(S,1)
@test Laplacian(xyz) isa Laplacian
@test Laplacian(xyz)^2 isa QuasiArrays.ApplyQuasiArray
@test Laplacian(xyz)^3 isa QuasiArrays.ApplyQuasiArray
f1 = c -> cos(c.θ)^2
Δ_f1 = c -> -1-3*cos(2*c.θ)
Δ2_f1 = c -> 6+18*cos(2*c.θ)
Δ3_f1 = c -> -36*(1+3*cos(2*c.θ))
Δ = Laplacian(xyz)
Δ2 = Laplacian(xyz)^2
Δ3 = Laplacian(xyz)^3
t = SphericalCoordinate(0.122,0.993)
@test (Δ*S*(S\f1.(xyz)))[t] ≈ Δ_f1(t)
@test (Δ^2*S*(S\f1.(xyz)))[t] ≈ (Δ*Δ*S*(S\f1.(xyz)))[t] ≈ Δ2_f1(t)
@test (Δ^3*S*(S\f1.(xyz)))[t] ≈ (Δ*Δ*Δ*S*(S\f1.(xyz)))[t] ≈ Δ3_f1(t)
end
@testset "Finite basis Laplacian, complex" begin
S = SphericalHarmonic()[:,Block.(Base.OneTo(10))]
xyz = axes(S,1)
@test Laplacian(xyz) isa Laplacian
@test Laplacian(xyz)^2 isa QuasiArrays.ApplyQuasiArray
@test Laplacian(xyz)^3 isa QuasiArrays.ApplyQuasiArray
f1 = c -> cos(c.θ)^2
Δ_f1 = c -> -1-3*cos(2*c.θ)
Δ2_f1 = c -> 6+18*cos(2*c.θ)
Δ3_f1 = c -> -36*(1+3*cos(2*c.θ))
Δ = Laplacian(xyz)
Δ2 = Laplacian(xyz)^2
Δ3 = Laplacian(xyz)^3
t = SphericalCoordinate(0.122,0.993)
@test (Δ*S*(S\f1.(xyz)))[t] ≈ Δ_f1(t)
@test (Δ^2*S*(S\f1.(xyz)))[t] ≈ (Δ*Δ*S*(S\f1.(xyz)))[t] ≈ Δ2_f1(t)
@test (Δ^3*S*(S\f1.(xyz)))[t] ≈ (Δ*Δ*Δ*S*(S\f1.(xyz)))[t] ≈ Δ3_f1(t)
end
@testset "Finite basis Laplacian, real" begin
S = RealSphericalHarmonic()[:,Block.(Base.OneTo(10))]
xyz = axes(S,1)
@test Laplacian(xyz) isa Laplacian
@test Laplacian(xyz)^2 isa QuasiArrays.ApplyQuasiArray
@test Laplacian(xyz)^3 isa QuasiArrays.ApplyQuasiArray
f1 = c -> cos(c.θ)^2
Δ_f1 = c -> -1-3*cos(2*c.θ)
Δ2_f1 = c -> 6+18*cos(2*c.θ)
Δ3_f1 = c -> -36*(1+3*cos(2*c.θ))
Δ = Laplacian(xyz)
Δ2 = Laplacian(xyz)^2
Δ3 = Laplacian(xyz)^3
t = SphericalCoordinate(0.122,0.993)
@test (Δ*S*(S\f1.(xyz)))[t] ≈ Δ_f1(t)
@test (Δ^2*S*(S\f1.(xyz)))[t] ≈ (Δ*Δ*S*(S\f1.(xyz)))[t] ≈ Δ2_f1(t)
@test (Δ^3*S*(S\f1.(xyz)))[t] ≈ (Δ*Δ*Δ*S*(S\f1.(xyz)))[t] ≈ Δ3_f1(t)
end
@testset "abs(Δ)^α - Basics of absolute Laplacian powers" begin
# Set 1
α = 1/3
S = SphericalHarmonic()
Sxyz = axes(S,1)
SΔα = AbsLaplacianPower(Sxyz,α)
Δ = Laplacian(Sxyz)
@test copy(SΔα) == SΔα
@test SΔα isa AbsLaplacianPower
@test SΔα isa QuasiArrays.LazyQuasiMatrix
@test axes(SΔα) == (axes(S,1),axes(S,1))
@test abs(Δ) == -Δ == AbsLaplacianPower(axes(Δ,1),1)
@test abs(Δ)^α == SΔα
# Set 2
α = 7/13
S = SphericalHarmonic()
Sxyz = axes(S,1)
SΔα = AbsLaplacianPower(Sxyz,α)
Δ = Laplacian(Sxyz)
@test copy(SΔα) == SΔα
@test SΔα isa AbsLaplacianPower
@test SΔα isa QuasiArrays.LazyQuasiMatrix
@test axes(SΔα) == (axes(S,1),axes(S,1))
@test abs(Δ) == -Δ == AbsLaplacianPower(axes(Δ,1),1)
@test abs(Δ)^α == SΔα
end
@testset "sum" begin
S = SphericalHarmonic()
R = RealSphericalHarmonic()
@test sum(S; dims=1)[:,1:10] ≈ sum(R; dims=1)[:,1:10] ≈ [sqrt(4π) zeros(1,9)]
x = axes(S,1)
@test sum(S * (S \ ones(x))) ≈ sum(R * (R \ ones(x))) ≈ 4π
f = x -> cos(x[1]*sin(x[2]+x[3]))
@test sum(S * (S \ f.(x))) ≈ sum(R * (R \ f.(x))) ≈ 11.946489824270322609
end
@testset "Angular momentum" begin
S = SphericalHarmonic()
R = RealSphericalHarmonic()
∂θ = AngularMomentum(axes(S, 1))
@test axes(∂θ) == (axes(S, 1), axes(S, 1))
@test ∂θ == AngularMomentum(axes(R, 1)) == AngularMomentum(axes(S, 1).domain)
@test copy(∂θ) ≡ ∂θ
A = S \ (∂θ * S)
A2 = S \ (∂θ^2 * S)
@test diag(A[1:9, 1:9]) ≈ [0; 0; -im; im; 0; -im; im; -2im; 2im]
N = 20
@test isdiag(A[1:N, 1:N])
@test A[1:N, 1:N]^2 ≈ A2[1:N, 1:N]
end
| HarmonicOrthogonalPolynomials | https://github.com/JuliaApproximation/HarmonicOrthogonalPolynomials.jl.git |
|
[
"MIT"
] | 0.6.0 | a895ade45ba4b5255d4c7880dda3492c37d27d65 | docs | 3694 | # HarmonicOrthogonalPolynomials.jl
A Julia package for working with spherical harmonic expansions and
harmonic polynomials in balls.
[](https://github.com/JuliaApproximation/HarmonicOrthogonalPolynomials.jl/actions)
[](https://codecov.io/gh/JuliaApproximation/HarmonicOrthogonalPolynomials.jl)
A [harmonic polynomial](https://en.wikipedia.org/wiki/Harmonic_polynomial) is a multivariate polynomial that solves Laplace's equation.
[Spherical harmonics](https://en.wikipedia.org/wiki/Spherical_harmonics) are restrictions of harmonic polynomials to the sphere. Importantly they
are orthogonal. This package is primarily an implementation of spherical harmonics (in 2D and 3D) but exploiting their
polynomial features.
Currently this package focusses on support for
3D spherical harmonics. We use the convention of [FastTransforms](https://mikaelslevinsky.github.io/FastTransforms/transforms.html) for real spherical harmonics:
```julia
julia> θ,φ = 0.1,0.2 # θ is polar, φ is azimuthal (physics convention)
julia> sphericalharmonicy(ℓ, m, θ, φ)
0.07521112971423363 + 0.015246050775019674im
```
But we also allow function approximation, building on top of [ContinuumArrays.jl](https://github.com/JuliaApproximation/ContinuumArrays.jl) and [ClassicalOrthogonalPolynomials.jl](https://github.com/JuliaApproximation/ClassicalOrthogonalPolynomials.jl):
```julia
julia> S = SphericalHarmonic() # A quasi-matrix representation of spherical harmonics
SphericalHarmonic{Complex{Float64}}
julia> S[SphericalCoordinate(θ,φ),Block(ℓ+1)] # evaluate all spherical harmonics with specified ℓ
5-element Array{Complex{Float64},1}:
0.003545977402630546 - 0.0014992151996309556im
0.07521112971423363 - 0.015246050775019674im
0.621352880681805 + 0.0im
0.07521112971423363 + 0.015246050775019674im
0.003545977402630546 + 0.0014992151996309556im
julia> 𝐱 = axes(S,1) # represent the unit sphere as a quasi-vector
Inclusion(the 3-dimensional unit sphere)
julia> f = 𝐱 -> ((x,y,z) = 𝐱; exp(x)*cos(y*sin(z))); # function to be approximation
julia> S \ f.(𝐱) # expansion coefficients, adaptively computed
∞-blocked ∞-element BlockedArray{Complex{Float64},1,LazyArrays.CachedArray{Complex{Float64},1,Array{Complex{Float64},1},Zeros{Complex{Float64},1,Tuple{InfiniteArrays.OneToInf{Int64}}}},Tuple{BlockedOneTo{Int,ArrayLayouts.RangeCumsum{Int64,InfiniteArrays.InfStepRange{Int64,Int64}}}}}:
4.05681442931116 + 0.0im
──────────────────────────────────────────────────
1.5777291816142751 + 3.19754060061646e-16im
-8.006900295635809e-17 + 0.0im
1.5777291816142751 - 3.539535261006306e-16im
──────────────────────────────────────────────────
0.3881560551355611 + 5.196884701505137e-17im
-7.035627371746071e-17 + 2.5784941810054987e-18im
-0.30926350498081934 + 0.0im
-6.82462130695514e-17 - 3.515332651034677e-18im
0.3881560551355611 - 6.271963079558218e-17im
──────────────────────────────────────────────────
0.06830566496722756 - 8.852861226980248e-17im
-2.3672451919730833e-17 + 2.642173739237023e-18im
-0.0514592471634392 - 1.5572791163000952e-17im
1.1972144648274198e-16 + 0.0im
-0.05145924716343915 + 1.5264133695821818e-17im
⋮
julia> f̃ = S * (S \ f.(𝐱)); # expansion of f in spherical harmonics
julia> f̃[SphericalCoordinate(θ,φ)] # approximates f
1.1026374731849062 + 4.004893695029451e-16im
``` | HarmonicOrthogonalPolynomials | https://github.com/JuliaApproximation/HarmonicOrthogonalPolynomials.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 4016 | using Manifolds, LinearAlgebra, PGFPlotsX, Colors, Contour, Random
#
# Settings
#
dark_mode = true
line_offset_brightness = 0.25
patch_opacity = 1.0
geo_opacity = dark_mode ? 0.66 : 0.5
geo_line_width = 30
mesh_line_width = 5
mesh_opacity = dark_mode ? 0.5 : 0.7
logo_colors = [(77, 100, 174), (57, 151, 79), (202, 60, 50), (146, 89, 163)] # Julia colors
rgb_logo_colors = map(x -> RGB(x ./ 255...), logo_colors)
rgb_logo_colors_bright =
map(x -> RGB((1 + line_offset_brightness) .* x ./ 255...), logo_colors)
rgb_logo_colors_dark =
map(x -> RGB((1 - line_offset_brightness) .* x ./ 255...), logo_colors)
out_file_prefix = dark_mode ? "logo-interface-dark" : "logo-interface"
out_file_ext = ".svg"
#
# Helping functions
#
polar_to_cart(r, θ) = (r * cos(θ), r * sin(θ))
cart_to_polar(x, y) = (hypot(x, y), atan(y, x))
normal_coord_to_vector(M, x, rθ, B) = get_vector(M, x, collect(polar_to_cart(rθ...)), B)
normal_coord_to_point(M, x, rθ, B) = exp(M, x, normal_coord_to_vector(M, x, rθ, B))
function plot_patch!(ax, M, x, B, r, θs; options = Dict())
push!(
ax,
Plot3(
options,
Coordinates(map(θ -> Tuple(normal_coord_to_point(M, x, [r, θ], B)), θs)),
),
)
return ax
end
function plot_geodesic!(ax, M, x, y; n = 100, options = Dict())
γ = shortest_geodesic(M, x, y)
T = range(0, 1; length = n)
push!(ax, Plot3(options, Coordinates(Tuple.(γ.(T)))))
return ax
end
#
# Prepare document
#
resize!(PGFPlotsX.CUSTOM_PREAMBLE, 0)
push!(PGFPlotsX.CUSTOM_PREAMBLE, raw"\pgfplotsset{scale=6.0}")
push!(PGFPlotsX.CUSTOM_PREAMBLE, raw"\usetikzlibrary{arrows.meta}")
push!(PGFPlotsX.CUSTOM_PREAMBLE, raw"\pgfplotsset{roundcaps/.style={line cap=round}}")
push!(
PGFPlotsX.CUSTOM_PREAMBLE,
raw"\pgfplotsset{meshlinestyle/.style={dash pattern=on 1.8\pgflinewidth off 1.4\pgflinewidth, line cap=round}}",
)
if dark_mode
push!(PGFPlotsX.CUSTOM_PREAMBLE, raw"\pagecolor{black}")
end
S = Sphere(2)
center = normalize([1, 1, 1])
x, y, z = eachrow(Matrix{Float64}(I, 3, 3))
γ1 = shortest_geodesic(S, center, z)
γ2 = shortest_geodesic(S, center, x)
γ3 = shortest_geodesic(S, center, y)
p1 = γ1(1)
p2 = γ2(1)
p3 = γ3(1)
#
# Setup Axes
if dark_mode
tp = @pgf Axis({
axis_lines = "none",
axis_equal,
view = "{135}{35}",
zmin = -0.05,
zmax = 1.0,
xmin = 0.0,
xmax = 1.0,
ymin = 0.0,
ymax = 1.0,
})
else
tp = @pgf Axis({
axis_lines = "none",
axis_equal,
view = "{135}{35}",
zmin = -0.05,
zmax = 1.0,
xmin = 0.0,
xmax = 1.0,
ymin = 0.0,
ymax = 1.0,
})
end
rs = range(0, π / 5; length = 6)
θs = range(0, 2π; length = 100)
#
# Plot manifold patches
patch_colors = rgb_logo_colors[2:end]
patch_colors_line = dark_mode ? rgb_logo_colors_bright[2:end] : rgb_logo_colors_dark[2:end]
base_points = [p1, p2, p3]
basis_vectors = [log(S, p1, p2), log(S, p2, p1), log(S, p3, p1)]
for i in eachindex(base_points)
b = base_points[i]
B = DiagonalizingOrthonormalBasis(basis_vectors[i])
basis = get_basis(S, b, B)
optionsP = @pgf {fill = patch_colors[i], draw = "none", opacity = patch_opacity}
plot_patch!(tp, S, b, basis, π / 5, θs; options = optionsP)
optionsP =
@pgf {fill = dark_mode ? "black" : "white", draw = "none", opacity = patch_opacity}
plot_patch!(tp, S, b, basis, 0.75 * π / 5, θs; options = optionsP)
end
#
# Plot geodesics
options = @pgf {
opacity = geo_opacity,
"meshlinestyle",
no_markers,
roundcaps,
line_width = geo_line_width,
color = dark_mode ? "white" : "black",
}
plot_geodesic!(tp, S, base_points[1], base_points[2]; options = options)
plot_geodesic!(tp, S, base_points[1], base_points[3]; options = options)
plot_geodesic!(tp, S, base_points[2], base_points[3]; options = options)
#
# Export Logo.
out_file = "$(out_file_prefix)$(out_file_ext)"
pgfsave(out_file, tp)
pgfsave("$(out_file_prefix).pdf", tp)
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 3337 | #!/usr/bin/env julia
#
#
if "--help" ∈ ARGS
println(
"""
docs/make.jl
Render the `Manopt.jl` documenation with optinal arguments
Arguments
* `--help` - print this help and exit without rendering the documentation
* `--prettyurls` – toggle the prettyurls part to true (which is otherwise only true on CI)
* `--quarto` – run the Quarto notebooks from the `tutorials/` folder before generating the documentation
this has to be run locally at least once for the `tutorials/*.md` files to exist that are included in
the documentation (see `--exclude-tutorials`) for the alternative.
If they are generated ones they are cached accordingly.
Then you can spare time in the rendering by not passing this argument.
""",
)
exit(0)
end
#
# (a) if docs is not the current active environment, switch to it
# (from https://github.com/JuliaIO/HDF5.jl/pull/1020/)
if Base.active_project() != joinpath(@__DIR__, "Project.toml")
using Pkg
Pkg.activate(@__DIR__)
Pkg.develop(PackageSpec(; path = (@__DIR__) * "/../"))
Pkg.resolve()
Pkg.instantiate()
end
# (b) Did someone say render? Then we render!
if "--quarto" ∈ ARGS
using CondaPkg
CondaPkg.withenv() do
@info "Rendering Quarto"
tutorials_folder = (@__DIR__) * "/../tutorials"
# instantiate the tutorials environment if necessary
Pkg.activate(tutorials_folder)
Pkg.develop(PackageSpec(; path = (@__DIR__) * "/../"))
Pkg.resolve()
Pkg.instantiate()
Pkg.build("IJulia") # build IJulia to the right version.
Pkg.activate(@__DIR__) # but return to the docs one before
return run(`quarto render $(tutorials_folder)`)
end
end
using Documenter
using DocumenterCitations
using ManifoldsBase
# (e) ...finally! make docs
bib = CitationBibliography(joinpath(@__DIR__, "src", "references.bib"); style = :alpha)
makedocs(;
# for development, we disable prettyurls
format = Documenter.HTML(;
prettyurls = (get(ENV, "CI", nothing) == "true") || ("--prettyurls" ∈ ARGS),
assets = ["assets/favicon.ico", "assets/citations.css"],
size_threshold_warn = 200 * 2^10, # raise slightly from 100 to 200 KiB
size_threshold = 300 * 2^10, # raise slightly 200 to to 300 KiB
),
modules = [ManifoldsBase],
authors = "Seth Axen, Mateusz Baran, Ronny Bergmann, and contributors.",
sitename = "ManifoldsBase.jl",
pages = [
"Home" => "index.md",
"How to define a manifold" => "tutorials/implement-a-manifold.md",
"Design principles" => "design.md",
"An abstract manifold" => "types.md",
"Functions on maniolds" => [
"Basic functions" => "functions.md",
"Projections" => "projections.md",
"Retractions" => "retractions.md",
"Vector transports" => "vector_transports.md",
],
"Manifolds" => "manifolds.md",
"Meta-Manifolds" => "metamanifolds.md",
"Decorating/Extending a Manifold" => "decorator.md",
"Bases for tangent spaces" => "bases.md",
"Numerical Verification" => "numerical_verification.md",
"References" => "references.md",
],
plugins = [bib],
)
deploydocs(repo = "github.com/JuliaManifolds/ManifoldsBase.jl.git", push_preview = true)
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 1490 | module ManifoldsBasePlotsExt
if isdefined(Base, :get_extension)
using ManifoldsBase
using Plots
using Printf: @sprintf
import ManifoldsBase: plot_slope
else
# imports need to be relative for Requires.jl-based workflows:
# https://github.com/JuliaArrays/ArrayInterface.jl/pull/387
using ..ManifoldsBase
using ..Plots
using ..ManifoldsBase: @sprintf # is from Printf, but loaded in ManifoldsBase, and since Printf loading works here only on full moon days between 12 and noon, this trick might do it?
import ..ManifoldsBase: plot_slope
end
function ManifoldsBase.plot_slope(
x,
y;
slope = 2,
line_base = 0,
a = 0,
b = 2.0,
i = 1,
j = length(x),
)
fig = plot(
x,
y;
xaxis = :log,
yaxis = :log,
label = "\$E(t)\$",
linewidth = 3,
legend = :topleft,
color = :lightblue,
)
s_line = [exp10(line_base + t * slope) for t in log10.(x)]
plot!(
fig,
x,
s_line;
label = "slope s=$slope",
linestyle = :dash,
color = :black,
linewidth = 2,
)
if (i != 0) && (j != 0)
best_line = [exp10(a + t * b) for t in log10.(x[i:j])]
plot!(
fig,
x[i:j],
best_line;
label = "best slope $(@sprintf("%.4f", b))",
color = :blue,
linestyle = :dot,
linewidth = 2,
)
end
return fig
end
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 707 | module ManifoldsBaseQuaternionsExt
if isdefined(Base, :get_extension)
using ManifoldsBase
using ManifoldsBase: ℍ, QuaternionNumbers
using Quaternions
else
# imports need to be relative for Requires.jl-based workflows:
# https://github.com/JuliaArrays/ArrayInterface.jl/pull/387
using ..ManifoldsBase
using ..ManifoldsBase: ℍ, QuaternionNumbers
using ..Quaternions
end
@inline function ManifoldsBase.allocate_result_type(
::AbstractManifold{ℍ},
f::TF,
args::Tuple{},
) where {TF}
return QuaternionF64
end
@inline function ManifoldsBase.coordinate_eltype(
::AbstractManifold,
p,
𝔽::QuaternionNumbers,
)
return quat(number_eltype(p))
end
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 1979 | module ManifoldsBaseStatisticsExt
if isdefined(Base, :get_extension)
using Statistics
using ManifoldsBase
import ManifoldsBase: find_best_slope_window
else
# imports need to be relative for Requires.jl-based workflows:
# https://github.com/JuliaArrays/ArrayInterface.jl/pull/387
using ..Statistics
using ..ManifoldsBase
import ..ManifoldsBase: find_best_slope_window
end
function ManifoldsBase.find_best_slope_window(
X,
Y,
window = nothing;
slope::Real = 2.0,
slope_tol::Real = 0.1,
)
n = length(X)
if window !== nothing && (any(window .> n))
error(
"One of the window sizes ($(window)) is larger than the length of the signal (n=$n).",
)
end
a_best = 0
b_best = -Inf
i_best = 0
j_best = 0
r_best = 0 # longest interval
for w in (window === nothing ? (2:n) : [window...])
for j in 1:(n - w + 1)
x = X[j:(j + w - 1)]
y = Y[j:(j + w - 1)]
# fit a line a + bx
c = cor(x, y)
b = std(y) / std(x) * c
a = mean(y) - b * mean(x)
# look for the largest interval where b is within slope tolerance
r = (maximum(x) - minimum(x))
if (r > r_best) && abs(b - slope) < slope_tol #longer interval found.
r_best = r
a_best = a
b_best = b
i_best = j
j_best = j + w - 1 #last index (see x and y from before)
end
# not best interval - maybe it is still the (first) best slope?
if r_best == 0 && abs(b - slope) < abs(b_best - slope)
# but do not update `r` since this indicates only a best r
a_best = a
b_best = b
i_best = j
j_best = j + w - 1 #last index (see x and y from before)
end
end
end
return (a_best, b_best, i_best, j_best)
end
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 2045 | module ManifoldsBaseRecursiveArrayToolsExt
if isdefined(Base, :get_extension)
using ManifoldsBase
using RecursiveArrayTools
using ManifoldsBase: AbstractBasis, ProductBasisData, TangentSpaceType
using ManifoldsBase: number_of_components
using Random
import ManifoldsBase:
allocate,
allocate_on,
allocate_result,
default_inverse_retraction_method,
default_retraction_method,
default_vector_transport_method,
_get_dim_ranges,
get_vector,
get_vectors,
inverse_retract,
parallel_transport_direction,
parallel_transport_to,
project,
riemann_tensor,
submanifold_component,
submanifold_components,
vector_transport_direction,
_vector_transport_direction,
_vector_transport_to,
vector_transport_to,
ziptuples
import Base: copyto!, getindex, setindex!, view
else
# imports need to be relative for Requires.jl-based workflows:
# https://github.com/JuliaArrays/ArrayInterface.jl/pull/387
using ..ManifoldsBase
using ..RecursiveArrayTools
using ..ManifoldsBase: AbstractBasis, ProductBasisData, TangentSpaceType
using ..ManifoldsBase: number_of_components
using ..Random
import ..ManifoldsBase:
allocate,
allocate_on,
allocate_result,
default_inverse_retraction_method,
default_retraction_method,
default_vector_transport_method,
_get_dim_ranges,
get_vector,
get_vectors,
inverse_retract,
parallel_transport_direction,
parallel_transport_to,
project,
_retract,
riemann_tensor,
submanifold_component,
submanifold_components,
vector_transport_direction,
_vector_transport_direction,
_vector_transport_to,
vector_transport_to,
ziptuples
import ..Base: copyto!, getindex, setindex!, view
end
include("ProductManifoldRecursiveArrayToolsExt.jl")
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 10516 |
allocate(a::AbstractArray{<:ArrayPartition}) = map(allocate, a)
allocate(x::ArrayPartition) = ArrayPartition(map(allocate, x.x)...)
function allocate(x::ArrayPartition, T::Type)
return ArrayPartition(map(t -> allocate(t, T), submanifold_components(x))...)
end
allocate_on(M::ProductManifold) = ArrayPartition(map(N -> allocate_on(N), M.manifolds)...)
function allocate_on(M::ProductManifold, ::Type{ArrayPartition{T,U}}) where {T,U}
return ArrayPartition(map((N, V) -> allocate_on(N, V), M.manifolds, U.parameters)...)
end
function allocate_on(M::ProductManifold, ft::TangentSpaceType)
return ArrayPartition(map(N -> allocate_on(N, ft), M.manifolds)...)
end
function allocate_on(
M::ProductManifold,
ft::TangentSpaceType,
::Type{ArrayPartition{T,U}},
) where {T,U}
return ArrayPartition(
map((N, V) -> allocate_on(N, ft, V), M.manifolds, U.parameters)...,
)
end
@inline function allocate_result(M::ProductManifold, f)
return ArrayPartition(map(N -> allocate_result(N, f), M.manifolds))
end
function copyto!(M::ProductManifold, q::ArrayPartition, p::ArrayPartition)
map(copyto!, M.manifolds, submanifold_components(q), submanifold_components(p))
return q
end
function copyto!(
M::ProductManifold,
Y::ArrayPartition,
p::ArrayPartition,
X::ArrayPartition,
)
map(
copyto!,
M.manifolds,
submanifold_components(Y),
submanifold_components(p),
submanifold_components(X),
)
return Y
end
function default_retraction_method(M::ProductManifold, ::Type{T}) where {T<:ArrayPartition}
return ProductRetraction(
map(default_retraction_method, M.manifolds, T.parameters[2].parameters)...,
)
end
function default_inverse_retraction_method(
M::ProductManifold,
::Type{T},
) where {T<:ArrayPartition}
return InverseProductRetraction(
map(default_inverse_retraction_method, M.manifolds, T.parameters[2].parameters)...,
)
end
function default_vector_transport_method(
M::ProductManifold,
::Type{T},
) where {T<:ArrayPartition}
return ProductVectorTransport(
map(default_vector_transport_method, M.manifolds, T.parameters[2].parameters)...,
)
end
function Base.exp(M::ProductManifold, p::ArrayPartition, X::ArrayPartition)
return ArrayPartition(
map(
exp,
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
)...,
)
end
function Base.exp(M::ProductManifold, p::ArrayPartition, X::ArrayPartition, t::Number)
return ArrayPartition(
map(
(N, pc, Xc) -> exp(N, pc, Xc, t),
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
)...,
)
end
function get_vector(
M::ProductManifold,
p::ArrayPartition,
Xⁱ,
B::AbstractBasis{𝔽,TangentSpaceType},
) where {𝔽}
dims = map(manifold_dimension, M.manifolds)
@assert length(Xⁱ) == sum(dims)
dim_ranges = _get_dim_ranges(dims)
tXⁱ = map(dr -> (@inbounds view(Xⁱ, dr)), dim_ranges)
ts = ziptuples(M.manifolds, submanifold_components(M, p), tXⁱ)
return ArrayPartition(map((@inline t -> get_vector(t..., B)), ts))
end
function get_vector(
M::ProductManifold,
p::ArrayPartition,
Xⁱ,
B::CachedBasis{𝔽,<:AbstractBasis{𝔽},<:ProductBasisData},
) where {𝔽}
dims = map(manifold_dimension, M.manifolds)
@assert length(Xⁱ) == sum(dims)
dim_ranges = _get_dim_ranges(dims)
tXⁱ = map(dr -> (@inbounds view(Xⁱ, dr)), dim_ranges)
ts = ziptuples(M.manifolds, submanifold_components(M, p), tXⁱ, B.data.parts)
return ArrayPartition(map((@inline t -> get_vector(t...)), ts))
end
function get_vectors(
M::ProductManifold,
p::ArrayPartition,
B::CachedBasis{𝔽,<:AbstractBasis{𝔽},<:ProductBasisData},
) where {𝔽}
N = number_of_components(M)
xparts = submanifold_components(p)
BVs = map(t -> get_vectors(t...), ziptuples(M.manifolds, xparts, B.data.parts))
zero_tvs = map(t -> zero_vector(t...), ziptuples(M.manifolds, xparts))
vs = typeof(ArrayPartition(zero_tvs...))[]
for i in 1:N, k in 1:length(BVs[i])
push!(
vs,
ArrayPartition(zero_tvs[1:(i - 1)]..., BVs[i][k], zero_tvs[(i + 1):end]...),
)
end
return vs
end
ManifoldsBase._get_vector_cache_broadcast(::ArrayPartition) = Val(false)
"""
getindex(p, M::ProductManifold, i::Union{Integer,Colon,AbstractVector})
p[M::ProductManifold, i]
Access the element(s) at index `i` of a point `p` on a [`ProductManifold`](@ref) `M` by
linear indexing.
See also [Array Indexing](https://docs.julialang.org/en/v1/manual/arrays/#man-array-indexing-1) in Julia.
"""
@inline Base.@propagate_inbounds function Base.getindex(
p::ArrayPartition,
M::ProductManifold,
i::Union{Integer,Colon,AbstractVector,Val},
)
return get_component(M, p, i)
end
function inverse_retract(
M::ProductManifold,
p::ArrayPartition,
q::ArrayPartition,
method::InverseProductRetraction,
)
return ArrayPartition(
map(
inverse_retract,
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, q),
method.inverse_retractions,
),
)
end
function Base.log(M::ProductManifold, p::ArrayPartition, q::ArrayPartition)
return ArrayPartition(
map(
log,
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, q),
)...,
)
end
function parallel_transport_direction(
M::ProductManifold,
p::ArrayPartition,
X::ArrayPartition,
d::ArrayPartition,
)
return ArrayPartition(
map(
parallel_transport_direction,
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, d),
),
)
end
function parallel_transport_to(
M::ProductManifold,
p::ArrayPartition,
X::ArrayPartition,
q::ArrayPartition,
)
return ArrayPartition(
map(
parallel_transport_to,
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, q),
),
)
end
function project(M::ProductManifold, p::ArrayPartition)
return ArrayPartition(map(project, M.manifolds, submanifold_components(M, p))...)
end
function project(M::ProductManifold, p::ArrayPartition, X::ArrayPartition)
return ArrayPartition(
map(
project,
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
)...,
)
end
@doc raw"""
rand(M::ProductManifold; parts_kwargs = map(_ -> (;), M.manifolds))
Return a random point on [`ProductManifold`](@ref) `M`. `parts_kwargs` is
a tuple of keyword arguments for `rand` on each manifold in `M.manifolds`.
"""
function Random.rand(
M::ProductManifold;
vector_at = nothing,
parts_kwargs = map(_ -> (;), M.manifolds),
)
if vector_at === nothing
return ArrayPartition(
map((N, kwargs) -> rand(N; kwargs...), M.manifolds, parts_kwargs)...,
)
else
return ArrayPartition(
map(
(N, p, kwargs) -> rand(N; vector_at = p, kwargs...),
M.manifolds,
submanifold_components(M, vector_at),
parts_kwargs,
)...,
)
end
end
function Random.rand(
rng::AbstractRNG,
M::ProductManifold;
vector_at = nothing,
parts_kwargs = map(_ -> (;), M.manifolds),
)
if vector_at === nothing
return ArrayPartition(
map((N, kwargs) -> rand(rng, N; kwargs...), M.manifolds, parts_kwargs)...,
)
else
return ArrayPartition(
map(
(N, p, kwargs) -> rand(rng, N; vector_at = p, kwargs...),
M.manifolds,
submanifold_components(M, vector_at),
parts_kwargs,
)...,
)
end
end
function riemann_tensor(
M::ProductManifold,
p::ArrayPartition,
X::ArrayPartition,
Y::ArrayPartition,
Z::ArrayPartition,
)
return ArrayPartition(
map(
riemann_tensor,
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, Y),
submanifold_components(M, Z),
),
)
end
"""
setindex!(q, p, M::ProductManifold, i::Union{Integer,Colon,AbstractVector})
q[M::ProductManifold,i...] = p
set the element `[i...]` of a point `q` on a [`ProductManifold`](@ref) by linear indexing to `q`.
See also [Array Indexing](https://docs.julialang.org/en/v1/manual/arrays/#man-array-indexing-1) in Julia.
"""
Base.@propagate_inbounds function Base.setindex!(
q::ArrayPartition,
p,
M::ProductManifold,
i::Union{Integer,Colon,AbstractVector,Val},
)
return set_component!(M, q, p, i)
end
@inline submanifold_component(p::ArrayPartition, ::Val{I}) where {I} = p.x[I]
@inline submanifold_components(p::ArrayPartition) = p.x
function vector_transport_direction(
M::ProductManifold,
p::ArrayPartition,
X::ArrayPartition,
d::ArrayPartition,
m::ProductVectorTransport,
)
return ArrayPartition(
map(
vector_transport_direction,
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, d),
m.methods,
),
)
end
function vector_transport_to(
M::ProductManifold,
p::ArrayPartition,
X::ArrayPartition,
q::ArrayPartition,
m::ProductVectorTransport,
)
return ArrayPartition(
map(
vector_transport_to,
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, q),
m.methods,
),
)
end
function vector_transport_to(
M::ProductManifold,
p::ArrayPartition,
X::ArrayPartition,
q::ArrayPartition,
m::ParallelTransport,
)
return ArrayPartition(
map(
(iM, ip, iX, id) -> vector_transport_to(iM, ip, iX, id, m),
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, q),
),
)
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 6082 | """
DefaultManifold <: AbstractManifold
This default manifold illustrates the main features of the interface and provides a skeleton
to build one's own manifold. It is a simplified/shortened variant of `Euclidean` from
`Manifolds.jl`.
This manifold further illustrates how to type your manifold points and tangent vectors. Note
that the interface does not require this, but it might be handy in debugging and educative
situations to verify correctness of involved variables.
# Constructor
DefaultManifold(n::Int...; field = ℝ, parameter::Symbol = :field)
Arguments:
- `n`: shape of array representing points on the manifold.
- `field`: field over which the manifold is defined. Either `ℝ`, `ℂ` or `ℍ`.
- `parameter`: whether a type parameter should be used to store `n`. By default size
is stored in a field. Value can either be `:field` or `:type`.
"""
struct DefaultManifold{𝔽,T} <: AbstractManifold{𝔽}
size::T
end
function DefaultManifold(n::Vararg{Int}; field = ℝ, parameter::Symbol = :field)
size = wrap_type_parameter(parameter, n)
return DefaultManifold{field,typeof(size)}(size)
end
function allocation_promotion_function(
::DefaultManifold{ℂ},
::Union{typeof(get_vector),typeof(get_coordinates)},
::Tuple,
)
return complex
end
change_representer!(M::DefaultManifold, Y, ::EuclideanMetric, p, X) = copyto!(M, Y, p, X)
change_metric!(M::DefaultManifold, Y, ::EuclideanMetric, p, X) = copyto!(M, Y, p, X)
function check_approx(M::DefaultManifold, p, q; kwargs...)
res = isapprox(p, q; kwargs...)
res && return nothing
v = distance(M, p, q)
s = "The two points $p and $q on $M are not (approximately) equal."
return ApproximatelyError(v, s)
end
function check_approx(M::DefaultManifold, p, X, Y; kwargs...)
res = isapprox(X, Y; kwargs...)
res && return nothing
v = norm(M, p, X - Y)
s = "The two tangent vectors $X and $Y in the tangent space at $p on $M are not (approximately) equal."
return ApproximatelyError(v, s)
end
distance(::DefaultManifold, p, q) = norm(p - q)
embed!(::DefaultManifold, q, p) = copyto!(q, p)
embed!(::DefaultManifold, Y, p, X) = copyto!(Y, X)
exp!(::DefaultManifold, q, p, X) = (q .= p .+ X)
for fname in [:get_basis_orthonormal, :get_basis_orthogonal, :get_basis_default]
BD = Dict(
:get_basis_orthonormal => :DefaultOrthonormalBasis,
:get_basis_orthogonal => :DefaultOrthogonalBasis,
:get_basis_default => :DefaultBasis,
)
BT = BD[fname]
@eval function $fname(::DefaultManifold{ℝ}, p, N::RealNumbers)
return CachedBasis($BT(N), [_euclidean_basis_vector(p, i) for i in eachindex(p)])
end
@eval function $fname(::DefaultManifold{ℂ}, p, N::ComplexNumbers)
return CachedBasis(
$BT(N),
[_euclidean_basis_vector(p, i, real) for i in eachindex(p)],
)
end
end
function get_basis_diagonalizing(M::DefaultManifold, p, B::DiagonalizingOrthonormalBasis)
vecs = get_vectors(M, p, get_basis(M, p, DefaultOrthonormalBasis()))
eigenvalues = zeros(real(eltype(p)), manifold_dimension(M))
return CachedBasis(B, DiagonalizingBasisData(B.frame_direction, eigenvalues, vecs))
end
# Complex manifold, real basis -> coefficients c are complex -> reshape
# Real manifold, real basis -> reshape
function get_coordinates_orthonormal!(M::DefaultManifold, c, p, X, N::AbstractNumbers)
return copyto!(c, reshape(X, number_of_coordinates(M, N)))
end
function get_coordinates_diagonalizing!(
M::DefaultManifold,
c,
p,
X,
::DiagonalizingOrthonormalBasis{ℝ},
)
return copyto!(c, reshape(X, number_of_coordinates(M, ℝ)))
end
function get_coordinates_orthonormal!(::DefaultManifold{ℂ}, c, p, X, ::RealNumbers)
m = length(X)
return copyto!(c, [reshape(real(X), m); reshape(imag(X), m)])
end
function get_vector_orthonormal!(M::DefaultManifold, Y, p, c, ::AbstractNumbers)
return copyto!(Y, reshape(c, representation_size(M)))
end
function get_vector_diagonalizing!(
M::DefaultManifold,
Y,
p,
c,
::DiagonalizingOrthonormalBasis{ℝ},
)
return copyto!(Y, reshape(c, representation_size(M)))
end
function get_vector_orthonormal!(M::DefaultManifold{ℂ}, Y, p, c, ::RealNumbers)
n = div(length(c), 2)
return copyto!(Y, reshape(c[1:n] + c[(n + 1):(2n)] * 1im, representation_size(M)))
end
injectivity_radius(::DefaultManifold) = Inf
@inline inner(::DefaultManifold, p, X, Y) = dot(X, Y)
is_flat(::DefaultManifold) = true
log!(::DefaultManifold, Y, p, q) = (Y .= q .- p)
function manifold_dimension(M::DefaultManifold{𝔽}) where {𝔽}
size = get_parameter(M.size)
return prod(size) * real_dimension(𝔽)
end
number_system(::DefaultManifold{𝔽}) where {𝔽} = 𝔽
norm(::DefaultManifold, p, X) = norm(X)
project!(::DefaultManifold, q, p) = copyto!(q, p)
project!(::DefaultManifold, Y, p, X) = copyto!(Y, X)
representation_size(M::DefaultManifold) = get_parameter(M.size)
function Base.show(io::IO, M::DefaultManifold{𝔽,<:TypeParameter}) where {𝔽}
return print(
io,
"DefaultManifold($(join(get_parameter(M.size), ", ")); field = $(𝔽), parameter = :type)",
)
end
function Base.show(io::IO, M::DefaultManifold{𝔽}) where {𝔽}
return print(io, "DefaultManifold($(join(get_parameter(M.size), ", ")); field = $(𝔽))")
end
function parallel_transport_to!(::DefaultManifold, Y, p, X, q)
return copyto!(Y, X)
end
function Random.rand!(::DefaultManifold, pX; σ = one(eltype(pX)), vector_at = nothing)
pX .= randn(size(pX)) .* σ
return pX
end
function Random.rand!(
rng::AbstractRNG,
::DefaultManifold,
pX;
σ = one(eltype(pX)),
vector_at = nothing,
)
pX .= randn(rng, size(pX)) .* σ
return pX
end
function riemann_tensor!(::DefaultManifold, Xresult, p, X, Y, Z)
return fill!(Xresult, 0)
end
sectional_curvature_max(::DefaultManifold) = 0.0
sectional_curvature_min(::DefaultManifold) = 0.0
Weingarten!(::DefaultManifold, Y, p, X, V) = fill!(Y, 0)
zero_vector(::DefaultManifold, p) = zero(p)
zero_vector!(::DefaultManifold, Y, p) = fill!(Y, 0)
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 2496 | """
EmbeddedManifold{𝔽, MT <: AbstractManifold, NT <: AbstractManifold} <: AbstractDecoratorManifold{𝔽}
A type to represent an explicit embedding of a [`AbstractManifold`](@ref) `M` of type `MT` embedded
into a manifold `N` of type `NT`.
By default, an embedded manifold is set to be embedded, but neither isometrically embedded
nor a submanifold.
!!! note
This type is not required if a manifold `M` is to be embedded in one specific manifold `N`.
One can then just implement [`embed!`](@ref) and [`project!`](@ref).
You can further pass functions to the embedding, for example, when it is an isometric embedding,
by using an [`AbstractDecoratorManifold`](@ref).
Only for a second –maybe considered non-default–
embedding, this type should be considered in order to dispatch on different embed
and project methods for different embeddings `N`.
# Fields
* `manifold` the manifold that is an embedded manifold
* `embedding` a second manifold, the first one is embedded into
# Constructor
EmbeddedManifold(M, N)
Generate the `EmbeddedManifold` of the [`AbstractManifold`](@ref) `M` into the
[`AbstractManifold`](@ref) `N`.
"""
struct EmbeddedManifold{𝔽,MT<:AbstractManifold{𝔽},NT<:AbstractManifold} <:
AbstractDecoratorManifold{𝔽}
manifold::MT
embedding::NT
end
@inline active_traits(f, ::EmbeddedManifold, ::Any...) = merge_traits(IsEmbeddedManifold())
function allocate_result(M::EmbeddedManifold, f::typeof(project), x...)
T = allocate_result_type(M, f, x)
return allocate(M, x[1], T, representation_size(base_manifold(M)))
end
"""
decorated_manifold(M::EmbeddedManifold, d::Val{N} = Val(-1))
Return the manifold of `M` that is decorated with its embedding. For this specific
type the internally stored enhanced manifold `M.manifold` is returned.
See also [`base_manifold`](@ref), where this is used to (potentially) completely undecorate the manifold.
"""
decorated_manifold(M::EmbeddedManifold) = M.manifold
"""
get_embedding(M::EmbeddedManifold)
Return the embedding [`AbstractManifold`](@ref) `N` of `M`, if it exists.
"""
function get_embedding(M::EmbeddedManifold)
return M.embedding
end
function project(M::EmbeddedManifold, p)
q = allocate_result(M, project, p)
project!(M, q, p)
return q
end
function show(
io::IO,
M::EmbeddedManifold{𝔽,MT,NT},
) where {𝔽,MT<:AbstractManifold{𝔽},NT<:AbstractManifold}
return print(io, "EmbeddedManifold($(M.manifold), $(M.embedding))")
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 1617 |
"""
abstract type FiberType end
An abstract type for fiber types that can be used within [`Fiber`](@ref).
"""
abstract type FiberType end
@doc raw"""
Fiber{𝔽,TFiber<:FiberType,TM<:AbstractManifold{𝔽},TX} <: AbstractManifold{𝔽}
A fiber of a fiber bundle at a point `p` on the manifold.
This fiber itself is also a `manifold`. For vector fibers it's by default flat and hence
isometric to the [`Euclidean`](https://juliamanifolds.github.io/Manifolds.jl/latest/manifolds/euclidean.html) manifold.
# Fields
* `manifold` – base space of the fiber bundle
* `point` – a point ``p`` from the base space; the fiber corresponds to the preimage
by bundle projection ``\pi^{-1}(\{p\})``.
# Constructor
Fiber(M::AbstractManifold, p, fiber_type::FiberType)
A fiber of type `fiber_type` at point `p` from the manifold `manifold`.
"""
struct Fiber{𝔽,TFiber<:FiberType,TM<:AbstractManifold{𝔽},TX} <: AbstractManifold{𝔽}
manifold::TM
point::TX
fiber_type::TFiber
end
base_manifold(B::Fiber) = B.manifold
function Base.show(io::IO, ::MIME"text/plain", vs::Fiber)
summary(io, vs)
println(io, "\nFiber:")
pre = " "
sf = sprint(show, "text/plain", vs.fiber_type; context = io, sizehint = 0)
sf = replace(sf, '\n' => "\n$(pre)")
sm = sprint(show, "text/plain", vs.manifold; context = io, sizehint = 0)
sm = replace(sm, '\n' => "\n$(pre)")
println(io, pre, sf, sm)
println(io, "Base point:")
sp = sprint(show, "text/plain", vs.point; context = io, sizehint = 0)
sp = replace(sp, '\n' => "\n$(pre)")
return print(io, pre, sp)
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 48040 | module ManifoldsBase
import Base:
isapprox,
exp,
log,
convert,
copy,
copyto!,
angle,
eltype,
fill,
fill!,
isempty,
length,
similar,
show,
+,
-,
*,
==
import LinearAlgebra: ×, dot, norm, det, cross, I, UniformScaling, Diagonal
import Random: rand, rand!
using LinearAlgebra
using Markdown: @doc_str
using Printf: @sprintf
using Random
using Requires
include("maintypes.jl")
include("numbers.jl")
include("Fiber.jl")
include("bases.jl")
include("approximation_methods.jl")
include("retractions.jl")
include("exp_log_geo.jl")
include("projections.jl")
include("metric.jl")
if isdefined(Base, Symbol("@constprop"))
macro aggressive_constprop(ex)
return esc(:(Base.@constprop :aggressive $ex))
end
else
macro aggressive_constprop(ex)
return esc(ex)
end
end
"""
allocate(a)
allocate(a, dims::Integer...)
allocate(a, dims::Tuple)
allocate(a, T::Type)
allocate(a, T::Type, dims::Integer...)
allocate(a, T::Type, dims::Tuple)
allocate(M::AbstractManifold, a)
allocate(M::AbstractManifold, a, dims::Integer...)
allocate(M::AbstractManifold, a, dims::Tuple)
allocate(M::AbstractManifold, a, T::Type)
allocate(M::AbstractManifold, a, T::Type, dims::Integer...)
allocate(M::AbstractManifold, a, T::Type, dims::Tuple)
Allocate an object similar to `a`. It is similar to function `similar`, although
instead of working only on the outermost layer of a nested structure, it maps recursively
through outer layers and calls `similar` on the innermost array-like object only.
Type `T` is the new number element type [`number_eltype`](@ref), if it is not given
the element type of `a` is retained. The `dims` argument can be given for non-nested
allocation and is forwarded to the function `similar`.
It's behavior can be overridden by a specific manifold, for example power manifold with
nested replacing representation can decide that `allocate` for `Array{<:SArray}` returns
another `Array{<:SArray}` instead of `Array{<:MArray}`, as would be done by default.
"""
allocate(a, args...)
allocate(a) = similar(a)
allocate(a, dim1::Integer, dims::Integer...) = similar(a, dim1, dims...)
allocate(a, dims::Tuple) = similar(a, dims)
allocate(a, T::Type) = similar(a, T)
allocate(a, T::Type, dim1::Integer, dims::Integer...) = similar(a, T, dim1, dims...)
allocate(a, T::Type, dims::Tuple) = similar(a, T, dims)
allocate(a::AbstractArray{<:AbstractArray}) = map(allocate, a)
allocate(a::AbstractArray{<:AbstractArray}, T::Type) = map(t -> allocate(t, T), a)
allocate(a::NTuple{N,AbstractArray} where {N}) = map(allocate, a)
allocate(a::NTuple{N,AbstractArray} where {N}, T::Type) = map(t -> allocate(t, T), a)
allocate(::AbstractManifold, a) = allocate(a)
function allocate(::AbstractManifold, a, dim1::Integer, dims::Integer...)
return allocate(a, dim1, dims...)
end
allocate(::AbstractManifold, a, dims::Tuple) = allocate(a, dims)
allocate(::AbstractManifold, a, T::Type) = allocate(a, T)
function allocate(::AbstractManifold, a, T::Type, dim1::Integer, dims::Integer...)
return allocate(a, T, dim1, dims...)
end
allocate(::AbstractManifold, a, T::Type, dims::Tuple) = allocate(a, T, dims)
"""
allocate_on(M::AbstractManifold, [T:::Type])
allocate_on(M::AbstractManifold, F::FiberType, [T:::Type])
Allocate a new point on manifold `M` with optional type given by `T`. Note that `T` is not
number element type as in [`allocate`](@ref) but rather the type of the entire point to be
returned.
If `F` is provided, then an element of the corresponding fiber is allocated, assuming it is
independent of the base point.
To allocate a tangent vector, use ``
# Example
```julia-repl
julia> using ManifoldsBase
julia> M = ManifoldsBase.DefaultManifold(4)
DefaultManifold(4; field = ℝ)
julia> allocate_on(M)
4-element Vector{Float64}:
0.0
0.0
0.0
0.0
julia> allocate_on(M, Array{Float64})
4-element Vector{Float64}:
0.0
0.0
0.0
0.0
julia> allocate_on(M, TangentSpaceType())
4-element Vector{Float64}:
0.0
0.0
0.0
0.0
julia> allocate_on(M, TangentSpaceType(), Array{Float64})
4-element Vector{Float64}:
0.0
0.0
0.0
0.0
```
"""
allocate_on(M::AbstractManifold) = similar(Array{Float64}, representation_size(M))
function allocate_on(M::AbstractManifold, T::Type{<:AbstractArray})
return similar(T, representation_size(M))
end
"""
_pick_basic_allocation_argument(::AbstractManifold, f, x...)
Pick which one of elements of `x` should be used as a basis for allocation in the
`allocate_result(M::AbstractManifold, f, x...)` method. This can be specialized to, for
example, skip `Identity` arguments in Manifolds.jl group-related functions.
"""
function _pick_basic_allocation_argument(::AbstractManifold, f, x...)
return x[1]
end
"""
allocate_result(M::AbstractManifold, f, x...)
Allocate an array for the result of function `f` on [`AbstractManifold`](@ref) `M` and arguments
`x...` for implementing the non-modifying operation using the modifying operation.
Usefulness of passing a function is demonstrated by methods that allocate results of musical
isomorphisms.
"""
@inline function allocate_result(M::AbstractManifold, f, x...)
T = allocate_result_type(M, f, x)
picked = _pick_basic_allocation_argument(M, f, x...)
return allocate(M, picked, T)
end
@inline function allocate_result(M::AbstractManifold, f)
T = allocate_result_type(M, f, ())
rs = representation_size(M)
return allocate_result_array(M, f, T, rs)
end
function allocate_result_array(M::AbstractManifold, f, ::Type, ::Nothing)
msg = "Could not allocate result of function $f on manifold $M."
if base_manifold(M) isa ProductManifold
msg *= " This error could be resolved by importing RecursiveArrayTools.jl. If this is not the case, please open report an issue."
end
return error(msg)
end
function allocate_result_array(::AbstractManifold, f, T::Type, rs::Tuple)
return Array{T}(undef, rs...)
end
"""
allocate_result_type(M::AbstractManifold, f, args::NTuple{N,Any}) where N
Return type of element of the array that will represent the result of function `f` and the
[`AbstractManifold`](@ref) `M` on given arguments `args` (passed as a tuple).
"""
@inline function allocate_result_type(
::AbstractManifold,
f::TF,
args::NTuple{N,Any},
) where {N,TF}
@inline eti_to_one(eti) = one(number_eltype(eti))
return typeof(sum(map(eti_to_one, args)))
end
@inline function allocate_result_type(M::AbstractManifold, f::TF, args::Tuple{}) where {TF}
return allocation_promotion_function(M, f, ())(Float64)
end
"""
angle(M::AbstractManifold, p, X, Y)
Compute the angle between tangent vectors `X` and `Y` at point `p` from the
[`AbstractManifold`](@ref) `M` with respect to the inner product from [`inner`](@ref).
"""
function angle(M::AbstractManifold, p, X, Y)
return acos(real(inner(M, p, X, Y)) / norm(M, p, X) / norm(M, p, Y))
end
"""
are_linearly_independent(M::AbstractManifold, p, X, Y)
Check is vectors `X`, `Y` tangent at `p` to `M` are linearly independent.
"""
function are_linearly_independent(
M::AbstractManifold,
p,
X,
Y;
atol::Real = sqrt(eps(number_eltype(X))),
)
norm_X = norm(M, p, X)
norm_Y = norm(M, p, Y)
innerXY = inner(M, p, X, Y)
return norm_X > atol && norm_Y > atol && !isapprox(abs(innerXY), norm_X * norm_Y)
end
"""
base_manifold(M::AbstractManifold, depth = Val(-1))
Return the internally stored [`AbstractManifold`](@ref) for decorated manifold `M` and the base
manifold for vector bundles or power manifolds. The optional parameter `depth` can be used
to remove only the first `depth` many decorators and return the [`AbstractManifold`](@ref) from that
level, whether its decorated or not. Any negative value deactivates this depth limit.
"""
base_manifold(M::AbstractManifold, ::Val = Val(-1)) = M
"""
check_approx(M::AbstractManifold, p, q; kwargs...)
check_approx(M::AbstractManifold, p, X, Y; kwargs...)
Check whether two elements are approximately equal, either `p`, `q` on the [`AbstractManifold`](@ref)
or the two tangent vectors `X`, `Y` in the tangent space at `p` are approximately the same.
The keyword arguments `kwargs` can be used to set tolerances, similar to Julia's `isapprox`.
This function might use `isapprox` from Julia internally and is similar to [`isapprox`](@ref),
with the difference that is returns an [`ApproximatelyError`](@ref) if the two elements are
not approximately equal, containting a more detailed description/reason.
If the two elements are approximalely equal, this method returns `nothing`.
This method is an internal function and is called by `isapprox` whenever the user specifies
an `error=` keyword therein. [`_isapprox`](@ref) is another related internal function. It is
supposed to provide a fast true/false decision whether points or vectors are equal or not,
while `check_approx` also provides a textual explanation. If no additional explanation
is needed, a manifold may just implement a method of [`_isapprox`](@ref), while it should also
implement `check_approx` if a more detailed explanation could be helpful.
"""
function check_approx(M::AbstractManifold, p, q; kwargs...)
# fall back to classical approx mode - just that we do not have a reason then
res = _isapprox(M, p, q; kwargs...)
# since we can not assume distance to be implemented, we can not provide a default value
res && return nothing
s = "The two points $p and $q on $M are not (approximately) equal."
return ApproximatelyError(s)
end
function check_approx(M::AbstractManifold, p, X, Y; kwargs...)
# fall back to classical mode - just that we do not have a reason then
res = _isapprox(M, p, X, Y; kwargs...)
res && return nothing
s = "The two tangent vectors $X and $Y in the tangent space at $p on $M are not (approximately) equal."
v = try
norm(M, p, X - Y)
catch e
NaN
end
return ApproximatelyError(v, s)
end
"""
check_point(M::AbstractManifold, p; kwargs...) -> Union{Nothing,String}
Return `nothing` when `p` is a point on the [`AbstractManifold`](@ref) `M`. Otherwise, return an
error with description why the point does not belong to manifold `M`.
By default, `check_point` returns `nothing`, i.e. if no checks are implemented, the
assumption is to be optimistic for a point not deriving from the [`AbstractManifoldPoint`](@ref) type.
"""
check_point(M::AbstractManifold, p; kwargs...) = nothing
"""
check_vector(M::AbstractManifold, p, X; kwargs...) -> Union{Nothing,String}
Check whether `X` is a valid tangent vector in the tangent space of `p` on the
[`AbstractManifold`](@ref) `M`. An implementation does not have to validate the point `p`.
If it is not a tangent vector, an error string should be returned.
By default, `check_vector` returns `nothing`, i.e. if no checks are implemented, the
assumption is to be optimistic for tangent vectors not deriving from the [`TVector`](@ref)
type.
"""
check_vector(M::AbstractManifold, p, X; kwargs...) = nothing
"""
check_size(M::AbstractManifold, p)
check_size(M::AbstractManifold, p, X)
Check whether `p` has the right [`representation_size`](@ref) for a [`AbstractManifold`](@ref) `M`.
Additionally if a tangent vector is given, both `p` and `X` are checked to be of
corresponding correct representation sizes for points and tangent vectors on `M`.
By default, `check_size` returns `nothing`, i.e. if no checks are implemented, the
assumption is to be optimistic.
"""
function check_size(M::AbstractManifold, p)
m = representation_size(M)
m === nothing && return nothing # nothing reasonable in size to check
n = size(p)
if length(n) != length(m)
return DomainError(
length(n),
"The point $(p) can not belong to the manifold $(M), since its size $(n) is not equal to the manifolds representation size ($(m)).",
)
end
if n != m
return DomainError(
n,
"The point $(p) can not belong to the manifold $(M), since its size $(n) is not equal to the manifolds representation size ($(m)).",
)
end
end
function check_size(M::AbstractManifold, p, X)
mse = check_size(M, p)
mse === nothing || return mse
m = representation_size(M)
m === nothing && return nothing # without a representation size - nothing to check.
n = size(X)
if length(n) != length(m)
return DomainError(
length(n),
"The tangent vector $(X) can not belong to the manifold $(M), since its size $(n) is not equal to the manifolds representation size ($(m)).",
)
end
if n != m
return DomainError(
n,
"The tangent vector $(X) can not belong to the manifold $(M), since its size $(n) is not equal to the manifodls representation size ($(m)).",
)
end
end
"""
convert(T::Type, M::AbstractManifold, p)
Convert point `p` from manifold `M` to type `T`.
"""
convert(T::Type, ::AbstractManifold, p) = convert(T, p)
"""
convert(T::Type, M::AbstractManifold, p, X)
Convert vector `X` tangent at point `p` from manifold `M` to type `T`.
"""
convert(T::Type, ::AbstractManifold, p, X) = convert(T, p, X)
@doc raw"""
copy(M::AbstractManifold, p)
Copy the value(s) from the point `p` on the [`AbstractManifold`](@ref) `M` into a new point.
See [`allocate_result`](@ref) for the allocation of new point memory and [`copyto!`](@ref) for the copying.
"""
function copy(M::AbstractManifold, p)
q = allocate_result(M, copy, p)
copyto!(M, q, p)
return q
end
function copy(::AbstractManifold, p::Number)
return copy(p)
end
@doc raw"""
copy(M::AbstractManifold, p, X)
Copy the value(s) from the tangent vector `X` at a point `p` on the
[`AbstractManifold`](@ref) `M` into a new tangent vector.
See [`allocate_result`](@ref) for the allocation of new point memory and [`copyto!`](@ref) for the copying.
"""
function copy(M::AbstractManifold, p, X)
# the order of args switched, since the allocation by default takes the type of the first.
Y = allocate_result(M, copy, X, p)
copyto!(M, Y, p, X)
return Y
end
function copy(::AbstractManifold, p, X::Number)
return copy(X)
end
@doc raw"""
copyto!(M::AbstractManifold, q, p)
Copy the value(s) from `p` to `q`, where both are points on the [`AbstractManifold`](@ref) `M`.
This function defaults to calling `copyto!(q, p)`, but it might be useful to overwrite the
function at the level, where also information from `M` can be accessed.
"""
copyto!(::AbstractManifold, q, p) = copyto!(q, p)
@doc raw"""
copyto!(M::AbstractManifold, Y, p, X)
Copy the value(s) from `X` to `Y`, where both are tangent vectors from the tangent space at
`p` on the [`AbstractManifold`](@ref) `M`.
This function defaults to calling `copyto!(Y, X)`, but it might be useful to overwrite the
function at the level, where also information from `p` and `M` can be accessed.
"""
copyto!(::AbstractManifold, Y, p, X) = copyto!(Y, X)
"""
default_type(M::AbstractManifold)
Get the default type of points on manifold `M`.
"""
default_type(M::AbstractManifold) = typeof(allocate_on(M))
"""
default_type(M::AbstractManifold, ft::FiberType)
Get the default type of points from the fiber `ft` of the fiber bundle based on manifold `M`.
For example, call `default_type(MyManifold(), TangentSpaceType())` to get the default type
of a tangent vector.
"""
default_type(M::AbstractManifold, ft::FiberType) = typeof(allocate_on(M, ft))
@doc raw"""
distance(M::AbstractManifold, p, q)
Shortest distance between the points `p` and `q` on the [`AbstractManifold`](@ref) `M`,
i.e.
```math
d(p,q) = \inf_{γ} L(γ),
```
where the infimum is over all piecewise smooth curves ``γ: [a,b] \to \mathcal M``
connecting ``γ(a)=p`` and ``γ(b)=q`` and
```math
L(γ) = \displaystyle\int_{a}^{b} \lVert \dotγ(t)\rVert_{γ(t)} \mathrm{d}t
```
is the length of the curve $γ$.
If ``\mathcal M`` is not connected, i.e. consists of several disjoint components,
the distance between two points from different components should be ``∞``.
"""
distance(M::AbstractManifold, p, q) = norm(M, p, log(M, p, q))
"""
distance(M::AbstractManifold, p, q, m::AbstractInverseRetractionMethod)
Approximate distance between points `p` and `q` on manifold `M` using
[`AbstractInverseRetractionMethod`](@ref) `m`.
"""
function distance(M::AbstractManifold, p, q, m::AbstractInverseRetractionMethod)
return norm(M, p, inverse_retract(M, p, q, m))
end
distance(M::AbstractManifold, p, q, ::LogarithmicInverseRetraction) = distance(M, p, q)
"""
embed(M::AbstractManifold, p)
Embed point `p` from the [`AbstractManifold`](@ref) `M` into the ambient space.
This method is only available for manifolds where implicitly an embedding or ambient space
is given.
Additionally, `embed` includes changing data representation, if applicable, i.e.
if the points on `M` are not represented in the same way as points on the embedding,
the representation is changed accordingly.
The default is set in such a way that memory is allocated and `embed!(M, q, p)` is called.
See also: [`EmbeddedManifold`](@ref), [`project`](@ref project(M::AbstractManifold,p))
"""
function embed(M::AbstractManifold, p)
q = allocate_result(M, embed, p)
embed!(M, q, p)
return q
end
"""
embed!(M::AbstractManifold, q, p)
Embed point `p` from the [`AbstractManifold`](@ref) `M` into an ambient space.
This method is only available for manifolds where implicitly an embedding or ambient space
is given. Not implementing this function means, there is no proper embedding for your manifold.
Additionally, `embed` might include changing data representation, if applicable, i.e.
if points on `M` are not represented in the same way as their counterparts in the embedding,
the representation is changed accordingly.
The default is set in such a way that it assumes that the points on `M` are represented in
their embedding (for example like the unit vectors in a space to represent the sphere) and
hence embedding in the identity by default.
If you have more than one embedding, see [`EmbeddedManifold`](@ref) for defining a second
embedding. If your point `p` is already represented in some embedding,
see [`AbstractDecoratorManifold`](@ref) how you can avoid reimplementing code from the embedded manifold
See also: [`EmbeddedManifold`](@ref), [`project!`](@ref project!(M::AbstractManifold, q, p))
"""
embed!(M::AbstractManifold, q, p) = copyto!(M, q, p)
"""
embed(M::AbstractManifold, p, X)
Embed a tangent vector `X` at a point `p` on the [`AbstractManifold`](@ref) `M` into an ambient space.
This method is only available for manifolds where implicitly an embedding or ambient space
is given. Not implementing this function means, there is no proper embedding for your tangent space(s).
Additionally, `embed` might include changing data representation, if applicable, i.e.
if tangent vectors on `M` are not represented in the same way as their counterparts in the
embedding, the representation is changed accordingly.
The default is set in such a way that memory is allocated and `embed!(M, Y, p. X)` is called.
If you have more than one embedding, see [`EmbeddedManifold`](@ref) for defining a second
embedding. If your tangent vector `X` is already represented in some embedding,
see [`AbstractDecoratorManifold`](@ref) how you can avoid reimplementing code from the embedded manifold
See also: [`EmbeddedManifold`](@ref), [`project`](@ref project(M::AbstractManifold, p, X))
"""
function embed(M::AbstractManifold, p, X)
# the order of args switched, since the allocation by default takes the type of the first.
Y = allocate_result(M, embed, X, p)
embed!(M, Y, p, X)
return Y
end
"""
embed!(M::AbstractManifold, Y, p, X)
Embed a tangent vector `X` at a point `p` on the [`AbstractManifold`](@ref) `M` into the ambient
space and return the result in `Y`.
This method is only available for manifolds where implicitly an embedding or ambient space
is given.
Additionally, `embed!` includes changing data representation, if applicable, i.e.
if the tangents on `M` are not represented in the same way as tangents on the embedding,
the representation is changed accordingly. This is the case for example for Lie groups,
when tangent vectors are represented in the Lie algebra. The embedded tangents are then in
the tangent spaces of the embedded base points.
The default is set in such a way that it assumes that the points on `M` are represented in
their embedding (for example like the unit vectors in a space to represent the sphere) and
hence embedding also for tangent vectors is the identity by default.
See also: [`EmbeddedManifold`](@ref), [`project!`](@ref project!(M::AbstractManifold, Y, p, X))
"""
embed!(M::AbstractManifold, Y, p, X) = copyto!(M, Y, p, X)
"""
embed_project(M::AbstractManifold, p)
Embed `p` from manifold `M` an project it back to `M`. For points from `M` this is identity
but in case embedding is defined for points outside of `M`, this can serve as a way
to for example remove numerical inaccuracies caused by some algorithms.
"""
function embed_project(M::AbstractManifold, p)
return project(M, embed(M, p))
end
"""
embed_project(M::AbstractManifold, p, X)
Embed vector `X` tangent at `p` from manifold `M` an project it back to tangent space
at `p`. For points from that tangent space this is identity but in case embedding is
defined for tangent vectors from outside of it, this can serve as a way to for example remove
numerical inaccuracies caused by some algorithms.
"""
function embed_project(M::AbstractManifold, p, X)
return project(M, p, embed(M, p, X))
end
function embed_project!(M::AbstractManifold, q, p)
return project!(M, q, embed(M, p))
end
function embed_project!(M::AbstractManifold, Y, p, X)
return project!(M, Y, p, embed(M, p, X))
end
@doc raw"""
injectivity_radius(M::AbstractManifold)
Infimum of the injectivity radii `injectivity_radius(M,p)` of all points `p` on the [`AbstractManifold`](@ref).
injectivity_radius(M::AbstractManifold, p)
Return the distance $d$ such that [`exp(M, p, X)`](@ref exp(::AbstractManifold, ::Any, ::Any)) is
injective for all tangent vectors shorter than $d$ (i.e. has an inverse).
injectivity_radius(M::AbstractManifold[, x], method::AbstractRetractionMethod)
injectivity_radius(M::AbstractManifold, x, method::AbstractRetractionMethod)
Distance ``d`` such that
[`retract(M, p, X, method)`](@ref retract(::AbstractManifold, ::Any, ::Any, ::AbstractRetractionMethod))
is injective for all tangent vectors shorter than ``d`` (i.e. has an inverse) for point `p`
if provided or all manifold points otherwise.
In order to dispatch on different retraction methods, please either implement
`_injectivity_radius(M[, p], m::T)` for your retraction `R` or specifically `injectivity_radius_exp(M[, p])` for the exponential map.
By default the variant with a point `p` assumes that the default (without `p`) can ve called as a lower bound.
"""
injectivity_radius(M::AbstractManifold)
injectivity_radius(M::AbstractManifold, p) = injectivity_radius(M)
function injectivity_radius(M::AbstractManifold, p, m::AbstractRetractionMethod)
return _injectivity_radius(M, p, m)
end
function injectivity_radius(M::AbstractManifold, m::AbstractRetractionMethod)
return _injectivity_radius(M, m)
end
function _injectivity_radius(M::AbstractManifold, p, m::AbstractRetractionMethod)
return _injectivity_radius(M, m)
end
function _injectivity_radius(M::AbstractManifold, m::AbstractRetractionMethod)
return _injectivity_radius(M)
end
function _injectivity_radius(M::AbstractManifold)
return injectivity_radius(M)
end
function _injectivity_radius(M::AbstractManifold, p, ::ExponentialRetraction)
return injectivity_radius_exp(M, p)
end
function _injectivity_radius(M::AbstractManifold, ::ExponentialRetraction)
return injectivity_radius_exp(M)
end
injectivity_radius_exp(M, p) = injectivity_radius_exp(M)
injectivity_radius_exp(M) = injectivity_radius(M)
"""
inner(M::AbstractManifold, p, X, Y)
Compute the inner product of tangent vectors `X` and `Y` at point `p` from the
[`AbstractManifold`](@ref) `M`.
"""
inner(M::AbstractManifold, p, X, Y)
"""
is_flat(M::AbstractManifold)
Return true if the [`AbstractManifold`](@ref) `M` is flat, i.e. if its Riemann curvature
tensor is everywhere zero.
"""
is_flat(M::AbstractManifold)
"""
isapprox(M::AbstractManifold, p, q; error::Symbol=:none, kwargs...)
Check if points `p` and `q` from [`AbstractManifold`](@ref) `M` are approximately equal.
The keyword argument can be used to get more information for the case that
the result is false, if the concrete manifold provides such information.
Currently the following are supported
* `:error` - throws an error if `isapprox` evaluates to false, providing possibly a more detailed error.
Note that this turns `isapprox` basically to an `@assert`.
* `:info` – prints the information in an `@info`
* `:warn` – prints the information in an `@warn`
* `:none` (default) – the function just returns `true`/`false`
Keyword arguments can be used to specify tolerances.
"""
function isapprox(M::AbstractManifold, p, q; error::Symbol = :none, kwargs...)
if error === :none
return _isapprox(M, p, q; kwargs...)
else
ma = check_approx(M, p, q; kwargs...)
if ma !== nothing
(error === :error) && throw(ma)
# else: collect and info showerror
io = IOBuffer()
showerror(io, ma)
s = String(take!(io))
(error === :info) && @info s
(error === :warn) && @warn s
return false
end
return true
end
end
"""
isapprox(M::AbstractManifold, p, X, Y; error:Symbol=:none; kwargs...)
Check if vectors `X` and `Y` tangent at `p` from [`AbstractManifold`](@ref) `M` are approximately
equal.
The optional positional argument can be used to get more information for the case that
the result is false, if the concrete manifold provides such information.
Currently the following are supported
* `:error` - throws an error if `isapprox` evaluates to false, providing possibly a more detailed error.
Note that this turns `isapprox` basically to an `@assert`.
* `:info` – prints the information in an `@info`
* `:warn` – prints the information in an `@warn`
* `:none` (default) – the function just returns `true`/`false`
By default these informations are collected by calling [`check_approx`](@ref).
Keyword arguments can be used to specify tolerances.
"""
function isapprox(M::AbstractManifold, p, X, Y; error::Symbol = :none, kwargs...)
if error === :none
return _isapprox(M, p, X, Y; kwargs...)::Bool
else
mat = check_approx(M, p, X, Y; kwargs...)
if mat !== nothing
(error === :error) && throw(mat)
# else: collect and info showerror
io = IOBuffer()
showerror(io, mat)
s = String(take!(io))
(error === :info) && @info s
(error === :warn) && @warn s
return false
end
return true
end
end
"""
_isapprox(M::AbstractManifold, p, q; kwargs...)
An internal function for testing whether points `p` and `q` from manifold `M` are
approximately equal. Returns either `true` or `false` and does not support errors like
[`isapprox`](@ref).
For more details see documentation of [`check_approx`](@ref).
"""
function _isapprox(M::AbstractManifold, p, q; kwargs...)
return isapprox(p, q; kwargs...)
end
"""
_isapprox(M::AbstractManifold, p, X, Y; kwargs...)
An internal function for testing whether tangent vectors `X` and `Y` from tangent space
at point `p` from manifold `M` are approximately equal. Returns either `true` or `false`
and does not support errors like [`isapprox`](@ref).
For more details see documentation of [`check_approx`](@ref).
"""
function _isapprox(M::AbstractManifold, p, X, Y; kwargs...)
return isapprox(X, Y; kwargs...)
end
"""
is_point(M::AbstractManifold, p; error::Symbol = :none, kwargs...)
is_point(M::AbstractManifold, p, throw_error::Bool; kwargs...)
Return whether `p` is a valid point on the [`AbstractManifold`](@ref) `M`.
By default the function calls [`check_point`](@ref), which returns an `ErrorException` or `nothing`.
How to report a potential error can be set using the `error=` keyword
* `:error` - throws an error if `p` is not a point
* `:info` - displays the error message as an `@info`
* `:warn` - displays the error message as a `@warning`
* `:none` (default) – the function just returns `true`/`false`
all other symbols are equivalent to `error=:none`.
The second signature is a shorthand, where the boolean is used for `error=:error` (`true`)
and `error=:none` (default, `false`). This case ignores the `error=` keyword
"""
function is_point(
M::AbstractManifold,
p,
throw_error::Bool;
error::Symbol = :none,
kwargs...,
)
return is_point(M, p; error = throw_error ? :error : :none, kwargs...)
end
function is_point(M::AbstractManifold, p; error::Symbol = :none, kwargs...)
mps = check_size(M, p)
if mps !== nothing
(error === :error) && throw(mps)
if (error === :info) || (error === :warn)
# else: collect and info showerror
io = IOBuffer()
showerror(io, mps)
s = String(take!(io))
(error === :info) && @info s
(error === :warn) && @warn s
end
return false
end
mpe = check_point(M, p; kwargs...)
if mpe !== nothing
(error === :error) && throw(mpe)
if (error === :info) || (error === :warn)
# else: collect and info showerror
io = IOBuffer()
showerror(io, mpe)
s = String(take!(io))
(error === :info) && @info s
(error === :warn) && @warn s
end
return false
end
return true
end
"""
is_vector(M::AbstractManifold, p, X, check_base_point::Bool=true; error::Symbol=:none, kwargs...)
is_vector(M::AbstractManifold, p, X, check_base_point::Bool=true, throw_error::Boolean; kwargs...)
Return whether `X` is a valid tangent vector at point `p` on the [`AbstractManifold`](@ref) `M`.
Returns either `true` or `false`.
If `check_base_point` is set to true, this function also (first) calls [`is_point`](@ref)
on `p`.
Then, the function calls [`check_vector`](@ref) and checks whether the returned
value is `nothing` or an error.
How to report a potential error can be set using the `error=` keyword
* `:error` - throws an error if `X` is not a tangent vector and/or `p` is not point
^ `:info` - displays the error message as an `@info`
* `:warn` - displays the error message as a `@warn`ing.
* `:none` - (default) the function just returns `true`/`false`
all other symbols are equivalent to `error=:none`
The second signature is a shorthand, where `throw_error` is used for `error=:error` (`true`)
and `error=:none` (default, `false`). This case ignores the `error=` keyword.
"""
function is_vector(
M::AbstractManifold,
p,
X,
check_base_point::Bool,
throw_error::Bool;
error::Symbol = :none,
kwargs...,
)
return is_vector(
M,
p,
X,
check_base_point;
error = throw_error ? :error : :none,
kwargs...,
)
end
function is_vector(
M::AbstractManifold,
p,
X,
check_base_point::Bool = true;
error::Symbol = :none,
kwargs...,
)
if check_base_point
# if error, is_point throws, otherwise if not a point return false
!is_point(M, p; error = error, kwargs...) && return false
end
mXs = check_size(M, p, X)
if mXs !== nothing
(error === :error) && throw(mXs)
if (error === :info) || (error === :warn)
# else: collect and info showerror
io = IOBuffer()
showerror(io, mXs)
s = String(take!(io))
(error === :info) && @info s
(error === :warn) && @warn s
end
return false
end
mXe = check_vector(M, p, X; kwargs...)
if mXe !== nothing
(error === :error) && throw(mXe)
if (error === :info) || (error === :warn)
# else: collect and info showerror
io = IOBuffer()
showerror(io, mXe)
s = String(take!(io))
(error === :info) && @info s
(error === :warn) && @warn s
end
return false
end
return true
end
@doc raw"""
manifold_dimension(M::AbstractManifold)
The dimension $n=\dim_{\mathcal M}$ of real space $\mathbb R^n$ to which the neighborhood of
each point of the [`AbstractManifold`](@ref) `M` is homeomorphic.
"""
manifold_dimension(M::AbstractManifold)
"""
mid_point(M::AbstractManifold, p1, p2)
Calculate the middle between the two point `p1` and `p2` from manifold `M`.
By default uses [`log`](@ref), divides the vector by 2 and uses [`exp`](@ref).
"""
function mid_point(M::AbstractManifold, p1, p2)
q = allocate(p1)
return mid_point!(M, q, p1, p2)
end
"""
mid_point!(M::AbstractManifold, q, p1, p2)
Calculate the middle between the two point `p1` and `p2` from manifold `M`.
By default uses [`log`](@ref), divides the vector by 2 and uses [`exp!`](@ref).
Saves the result in `q`.
"""
function mid_point!(M::AbstractManifold, q, p1, p2)
X = log(M, p1, p2)
return exp!(M, q, p1, X / 2)
end
"""
norm(M::AbstractManifold, p, X)
Compute the norm of tangent vector `X` at point `p` from a [`AbstractManifold`](@ref) `M`.
By default this is computed using [`inner`](@ref).
"""
norm(M::AbstractManifold, p, X) = sqrt(max(real(inner(M, p, X, X)), 0))
"""
number_eltype(x)
Numeric element type of the a nested representation of a point or a vector.
To be used in conjuntion with [`allocate`](@ref) or [`allocate_result`](@ref).
"""
number_eltype(x) = eltype(x)
@inline function number_eltype(x::AbstractArray)
return typeof(mapreduce(eti -> one(number_eltype(eti)), +, x))
end
@inline number_eltype(::AbstractArray{T}) where {T<:Number} = T
@inline function number_eltype(::Type{<:AbstractArray{T}}) where {T}
return number_eltype(T)
end
@inline function number_eltype(::Type{<:AbstractArray{T}}) where {T<:Number}
return T
end
@inline function number_eltype(x::Tuple)
@inline eti_to_one(eti) = one(number_eltype(eti))
return typeof(sum(map(eti_to_one, x)))
end
"""
Random.rand(M::AbstractManifold, [d::Integer]; vector_at=nothing)
Random.rand(rng::AbstractRNG, M::AbstractManifold, [d::Integer]; vector_at=nothing)
Generate a random point on manifold `M` (when `vector_at` is `nothing`) or a tangent
vector at point `vector_at` (when it is not `nothing`).
Optionally a random number generator `rng` to be used can be specified. An optional integer
`d` indicates that a vector of `d` points or tangent vectors is to be generated.
!!! note
Usually a uniform distribution should be expected for compact manifolds and a
Gaussian-like distribution for non-compact manifolds and tangent vectors, although it is
not guaranteed. The distribution may change between releases.
`rand` methods for specific manifolds may take additional keyword arguments.
"""
Random.rand(M::AbstractManifold)
function Random.rand(M::AbstractManifold, d::Integer; kwargs...)
return [rand(M; kwargs...) for _ in 1:d]
end
function Random.rand(rng::AbstractRNG, M::AbstractManifold, d::Integer; kwargs...)
return [rand(rng, M; kwargs...) for _ in 1:d]
end
function Random.rand(M::AbstractManifold; vector_at = nothing, kwargs...)
if vector_at === nothing
pX = allocate_result(M, rand)
else
pX = allocate_result(M, rand, vector_at)
end
rand!(M, pX; vector_at = vector_at, kwargs...)
return pX
end
function Random.rand(rng::AbstractRNG, M::AbstractManifold; vector_at = nothing, kwargs...)
if vector_at === nothing
pX = allocate_result(M, rand)
else
pX = allocate_result(M, rand, vector_at)
end
rand!(rng, M, pX; vector_at = vector_at, kwargs...)
return pX
end
@doc raw"""
representation_size(M::AbstractManifold)
The size of an array representing a point on [`AbstractManifold`](@ref) `M`.
Returns `nothing` by default indicating that points are not represented using an
`AbstractArray`.
"""
function representation_size(::AbstractManifold)
return nothing
end
@doc raw"""
riemann_tensor(M::AbstractManifold, p, X, Y, Z)
Compute the value of the Riemann tensor ``R(X_f,Y_f)Z_f`` at point `p`, where
``X_f``, ``Y_f`` and ``Z_f`` are vector fields defined by parallel transport of,
respectively, `X`, `Y` and `Z` to the desired point. All computations are performed
using the connection associated to manifold `M`.
The formula reads ``R(X_f,Y_f)Z_f = \nabla_X\nabla_Y Z - \nabla_Y\nabla_X Z - \nabla_{[X, Y]}Z``,
where ``[X, Y]`` is the Lie bracket of vector fields.
Note that some authors define this quantity with inverse sign.
"""
function riemann_tensor(M::AbstractManifold, p, X, Y, Z)
Xresult = allocate_result(M, riemann_tensor, X)
return riemann_tensor!(M, Xresult, p, X, Y, Z)
end
@doc raw"""
sectional_curvature(M::AbstractManifold, p, X, Y)
Compute the sectional curvature of a manifold ``\mathcal M`` at a point ``p \in \mathcal M``
on two linearly independent tangent vectors at ``p``.
The formula reads
```math
\kappa_p(X, Y) = \frac{⟨R(X, Y, Y), X⟩_p}{\lVert X \rVert^2_p \lVert Y \rVert^2_p - ⟨X, Y⟩^2_p}
```
where ``R(X, Y, Y)`` is the [`riemann_tensor`](@ref) on ``\mathcal M``.
# Input
* `M`: a manifold ``\mathcal M``
* `p`: a point ``p \in \mathcal M``
* `X`: a tangent vector ``X \in T_p \mathcal M``
* `Y`: a tangent vector ``Y \in T_p \mathcal M``
"""
function sectional_curvature(M::AbstractManifold, p, X, Y)
R = riemann_tensor(M, p, X, Y, Y)
return inner(M, p, R, X) / ((norm(M, p, X)^2 * norm(M, p, Y)^2) - (inner(M, p, X, Y)^2))
end
@doc raw"""
sectional_curvature_max(M::AbstractManifold)
Upper bound on sectional curvature of manifold `M`. The formula reads
```math
\omega = \operatorname{sup}_{p\in\mathcal M, X\in T_p\mathcal M, Y\in T_p\mathcal M, ⟨X, Y⟩ ≠ 0} \kappa_p(X, Y)
```
"""
sectional_curvature_max(M::AbstractManifold)
@doc raw"""
sectional_curvature_min(M::AbstractManifold)
Lower bound on sectional curvature of manifold `M`. The formula reads
```math
\omega = \operatorname{inf}_{p\in\mathcal M, X\in T_p\mathcal M, Y\in T_p\mathcal M, ⟨X, Y⟩ ≠ 0} \kappa_p(X, Y)
```
"""
sectional_curvature_min(M::AbstractManifold)
"""
size_to_tuple(::Type{S}) where S<:Tuple
Converts a size given by `Tuple{N, M, ...}` into a tuple `(N, M, ...)`.
"""
Base.@pure size_to_tuple(::Type{S}) where {S<:Tuple} = tuple(S.parameters...)
@doc raw"""
Weingarten!(M, Y, p, X, V)
Compute the Weingarten map ``\mathcal W_p\colon T_p\mathcal M × N_p\mathcal M \to T_p\mathcal M``
in place of `Y`, see [`Weingarten`](@ref).
"""
Weingarten!(M::AbstractManifold, Y, p, X, V)
@doc raw"""
Weingarten(M, p, X, V)
Compute the Weingarten map ``\mathcal W_p\colon T_p\mathcal M × N_p\mathcal M \to T_p\mathcal M``,
where ``N_p\mathcal M`` is the orthogonal complement of the tangent space ``T_p\mathcal M``
of the embedded submanifold ``\mathcal M``, where we denote the embedding by ``\mathcal E``.
The Weingarten map can be defined by restricting the differential of the orthogonal [`project`](@ref)ion
``\operatorname{proj}_{T_p\mathcal M}\colon T_p \mathcal E \to T_p\mathcal M`` with respect to the base point ``p``,
i.e. defining
```math
\mathcal P_X := D_p\operatorname{proj}_{T_p\mathcal M}(Y)[X],
\qquad Y \in T_p \mathcal E, X \in T_p\mathcal M,
```
the Weingarten map can be written as ``\mathcal W_p(X,V) = \mathcal P_X(V)``.
The Weingarten map is named after [Julius Weingarten](https://en.wikipedia.org/wiki/Julius_Weingarten) (1836–1910).
"""
function Weingarten(M::AbstractManifold, p, X, V)
Y = copy(M, p, X)
Weingarten!(M, Y, p, X, V)
return Y
end
@doc raw"""
zero_vector!(M::AbstractManifold, X, p)
Save to `X` the tangent vector from the tangent space ``T_p\mathcal M`` at `p` that
represents the zero vector, i.e. such that retracting `X` to the [`AbstractManifold`](@ref) `M` at
`p` produces `p`.
"""
zero_vector!(M::AbstractManifold, X, p) = log!(M, X, p, p)
@doc raw"""
zero_vector(M::AbstractManifold, p)
Return the tangent vector from the tangent space ``T_p\mathcal M`` at `p` on the
[`AbstractManifold`](@ref) `M`, that represents the zero vector, i.e. such that a retraction at
`p` produces `p`.
"""
function zero_vector(M::AbstractManifold, p)
X = allocate_result(M, zero_vector, p)
zero_vector!(M, X, p)
return X
end
include("errors.jl")
include("parallel_transport.jl")
include("vector_transport.jl")
include("shooting.jl")
include("vector_spaces.jl")
include("point_vector_fallbacks.jl")
include("nested_trait.jl")
include("decorator_trait.jl")
include("numerical_checks.jl")
include("VectorFiber.jl")
include("TangentSpace.jl")
include("ValidationManifold.jl")
include("EmbeddedManifold.jl")
include("DefaultManifold.jl")
include("ProductManifold.jl")
include("PowerManifold.jl")
#
#
# Init
# -----
function __init__()
#
# Error Hints
#
@static if isdefined(Base.Experimental, :register_error_hint) # COV_EXCL_LINE
Base.Experimental.register_error_hint(MethodError) do io, exc, argtypes, kwargs
if exc.f === plot_slope
print(
io,
"""
`plot_slope` has to be implemented using your favourite plotting package.
A default is available when Plots.jl is added to the current environment.
To then get the plotting functionality activated, do
""",
)
printstyled(io, "`using Plots`"; color = :cyan)
end
if exc.f === find_best_slope_window
print(
io,
"""
`find_best_slope_window` has to be implemented using some statistics package
A default is available when Statistics.jl is added to the current environment.
To then get the functionality activated, do
""",
)
printstyled(io, "`using Statistics`"; color = :cyan)
end
end
end
# Extensions in the pre 1.9 fallback using Requires.jl
@static if !isdefined(Base, :get_extension)
@require RecursiveArrayTools = "731186ca-8d62-57ce-b412-fbd966d074cd" begin
include(
"../ext/ManifoldsBaseRecursiveArrayToolsExt/ManifoldsBaseRecursiveArrayToolsExt.jl",
)
end
@require Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" begin
include("../ext/ManifoldsBasePlotsExt.jl")
end
@require Quaternions = "94ee1d12-ae83-5a48-8b1c-48b8ff168ae0" begin
include("../ext/ManifoldsBaseQuaternionsExt.jl")
end
@require Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" begin
include("../ext/ManifoldsBaseStatisticsExt.jl")
end
end
end
#
#
# Export
# ------
#
# (a) Manifolds and general types
export AbstractManifold, AbstractManifoldPoint, TVector, CoTVector, TFVector, CoTFVector
export VectorSpaceFiber
export TangentSpace, TangentSpaceType
export CotangentSpace, CotangentSpaceType
export AbstractDecoratorManifold
export AbstractTrait, IsEmbeddedManifold, IsEmbeddedSubmanifold, IsIsometricEmbeddedManifold
export IsExplicitDecorator
export ValidationManifold, ValidationMPoint, ValidationTVector, ValidationCoTVector
export EmbeddedManifold
export AbstractPowerManifold, PowerManifold
export AbstractPowerRepresentation,
NestedPowerRepresentation, NestedReplacingPowerRepresentation
export ProductManifold
# (b) Generic Estimation Types
export GeodesicInterpolationWithinRadius,
CyclicProximalPointEstimation,
ExtrinsicEstimation,
GradientDescentEstimation,
WeiszfeldEstimation,
AbstractApproximationMethod,
GeodesicInterpolation
# (b) Retraction Types
export AbstractRetractionMethod,
ApproximateInverseRetraction,
CayleyRetraction,
EmbeddedRetraction,
ExponentialRetraction,
NLSolveInverseRetraction,
ODEExponentialRetraction,
QRRetraction,
PadeRetraction,
PolarRetraction,
ProductRetraction,
ProjectionRetraction,
RetractionWithKeywords,
SasakiRetraction,
ShootingInverseRetraction,
SoftmaxRetraction
# (c) Inverse Retraction Types
export AbstractInverseRetractionMethod,
ApproximateInverseRetraction,
CayleyInverseRetraction,
EmbeddedInverseRetraction,
InverseProductRetraction,
LogarithmicInverseRetraction,
NLSolveInverseRetraction,
QRInverseRetraction,
PadeInverseRetraction,
PolarInverseRetraction,
ProjectionInverseRetraction,
InverseRetractionWithKeywords,
SoftmaxInverseRetraction
# (d) Vector Transport Types
export AbstractVectorTransportMethod,
DifferentiatedRetractionVectorTransport,
EmbeddedVectorTransport,
ParallelTransport,
PoleLadderTransport,
ProductVectorTransport,
ProjectionTransport,
ScaledVectorTransport,
SchildsLadderTransport,
VectorTransportDirection,
VectorTransportTo,
VectorTransportWithKeywords
# (e) Basis Types
export CachedBasis,
DefaultBasis,
DefaultOrthogonalBasis,
DefaultOrthonormalBasis,
DiagonalizingOrthonormalBasis,
DefaultOrthonormalBasis,
GramSchmidtOrthonormalBasis,
ProjectedOrthonormalBasis,
VeeOrthogonalBasis
# (f) Error Messages
export OutOfInjectivityRadiusError, ManifoldDomainError
export ApproximatelyError
export CompositeManifoldError, ComponentManifoldError, ManifoldDomainError
# (g) Functions on Manifolds
export ×,
ℝ,
ℂ,
allocate,
allocate_on,
angle,
base_manifold,
base_point,
change_basis,
change_basis!,
change_metric,
change_metric!,
change_representer,
change_representer!,
check_inverse_retraction,
check_retraction,
check_vector_transport,
copy,
copyto!,
default_approximation_method,
default_inverse_retraction_method,
default_retraction_method,
default_type,
default_vector_transport_method,
distance,
exp,
exp!,
embed,
embed!,
embed_project,
embed_project!,
fill,
fill!,
geodesic,
geodesic!,
get_basis,
get_component,
get_coordinates,
get_coordinates!,
get_embedding,
get_vector,
get_vector!,
get_vectors,
hat,
hat!,
injectivity_radius,
inner,
inverse_retract,
inverse_retract!,
isapprox,
is_flat,
is_point,
is_vector,
isempty,
length,
log,
log!,
manifold_dimension,
mid_point,
mid_point!,
norm,
number_eltype,
number_of_coordinates,
number_system,
power_dimensions,
parallel_transport_along,
parallel_transport_along!,
parallel_transport_direction,
parallel_transport_direction!,
parallel_transport_to,
parallel_transport_to!,
project,
project!,
real_dimension,
representation_size,
set_component!,
shortest_geodesic,
shortest_geodesic!,
show,
rand,
rand!,
retract,
retract!,
riemann_tensor,
riemann_tensor!,
sectional_curvature,
sectional_curvature_max,
sectional_curvature_min,
vector_space_dimension,
vector_transport_along,
vector_transport_along!,
vector_transport_direction,
vector_transport_direction!,
vector_transport_to,
vector_transport_to!,
vee,
vee!,
Weingarten,
Weingarten!,
zero_vector,
zero_vector!
end # module
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 55482 | """
AbstractPowerRepresentation
An abstract representation type of points and tangent vectors on a power manifold.
"""
abstract type AbstractPowerRepresentation end
"""
NestedPowerRepresentation
Representation of points and tangent vectors on a power manifold using arrays
of size equal to `TSize` of a [`PowerManifold`](@ref).
Each element of such array stores a single point or tangent vector.
For modifying operations, each element of the outer array is modified in-place, differently
than in [`NestedReplacingPowerRepresentation`](@ref).
"""
struct NestedPowerRepresentation <: AbstractPowerRepresentation end
"""
NestedReplacingPowerRepresentation
Representation of points and tangent vectors on a power manifold using arrays
of size equal to `TSize` of a [`PowerManifold`](@ref).
Each element of such array stores a single point or tangent vector.
For modifying operations, each element of the outer array is replaced using non-modifying
operations, differently than for [`NestedReplacingPowerRepresentation`](@ref).
"""
struct NestedReplacingPowerRepresentation <: AbstractPowerRepresentation end
@doc raw"""
AbstractPowerManifold{𝔽,M,TPR} <: AbstractManifold{𝔽}
An abstract [`AbstractManifold`](@ref) to represent manifolds that are build as powers
of another [`AbstractManifold`](@ref) `M` with representation type `TPR`, a subtype of
[`AbstractPowerRepresentation`](@ref).
"""
abstract type AbstractPowerManifold{
𝔽,
M<:AbstractManifold{𝔽},
TPR<:AbstractPowerRepresentation,
} <: AbstractManifold{𝔽} end
@doc raw"""
PowerManifold{𝔽,TM<:AbstractManifold,TSize,TPR<:AbstractPowerRepresentation} <: AbstractPowerManifold{𝔽,TM}
The power manifold ``\mathcal M^{n_1× n_2 × … × n_d}`` with power geometry.
`TSize` defines the number of elements along each axis, either statically using
`TypeParameter` or storing it in a field.
For example, a manifold-valued time series would be represented by a power manifold with
``d`` equal to 1 and ``n_1`` equal to the number of samples. A manifold-valued image
(for example in diffusion tensor imaging) would be represented by a two-axis power
manifold (``d=2``) with ``n_1`` and ``n_2`` equal to width and height of the image.
While the size of the manifold is static, points on the power manifold
would not be represented by statically-sized arrays.
# Constructor
PowerManifold(M::PowerManifold, N_1, N_2, ..., N_d; parameter::Symbol=:field)
PowerManifold(M::AbstractManifold, NestedPowerRepresentation(), N_1, N_2, ..., N_d; parameter::Symbol=:field)
M^(N_1, N_2, ..., N_d)
Generate the power manifold ``M^{N_1 × N_2 × … × N_d}``.
By default, a [`PowerManifold`](@ref) is expanded further, i.e. for `M=PowerManifold(N, 3)`
`PowerManifold(M, 2)` is equivalent to `PowerManifold(N, 3, 2)`. Points are then 3×2 matrices
of points on `N`.
Providing a [`NestedPowerRepresentation`](@ref) as the second argument to the constructor
can be used to nest manifold, i.e. `PowerManifold(M, NestedPowerRepresentation(), 2)`
represents vectors of length 2 whose elements are vectors of length 3 of points on N
in a nested array representation.
The third signature `M^(...)` is equivalent to the first one, and hence either yields
a combination of power manifolds to _one_ larger power manifold, or a power manifold with the default representation.
Since there is no default [`AbstractPowerRepresentation`](@ref) within this interface, the
`^` operator is only available for `PowerManifold`s and concatenates dimensions.
`parameter`: whether a type parameter should be used to store `n`. By default size
is stored in a field. Value can either be `:field` or `:type`.
"""
struct PowerManifold{𝔽,TM<:AbstractManifold{𝔽},TSize,TPR<:AbstractPowerRepresentation} <:
AbstractPowerManifold{𝔽,TM,TPR}
manifold::TM
size::TSize
end
"""
_parameter_symbol(M::PowerManifold)
Return `:field` if size of [`PowerManifold`](@ref) `M` is stored in a field and `:type`
if in a `TypeParameter`.
"""
_parameter_symbol(::PowerManifold) = :field
function _parameter_symbol(
::PowerManifold{𝔽,<:AbstractManifold{𝔽},<:TypeParameter},
) where {𝔽}
return :type
end
@aggressive_constprop function PowerManifold(
M::AbstractManifold{𝔽},
::TPR,
size::Integer...;
parameter::Symbol = :field,
) where {𝔽,TPR<:AbstractPowerRepresentation}
size_w = wrap_type_parameter(parameter, size)
return PowerManifold{𝔽,typeof(M),typeof(size_w),TPR}(M, size_w)
end
@aggressive_constprop function PowerManifold(
M::PowerManifold{𝔽,TM,TSize,TPR},
size::Integer...;
parameter::Symbol = _parameter_symbol(M),
) where {𝔽,TM<:AbstractManifold{𝔽},TSize,TPR<:AbstractPowerRepresentation}
size_w = wrap_type_parameter(parameter, (get_parameter(M.size)..., size...))
return PowerManifold{𝔽,TM,typeof(size_w),TPR}(M.manifold, size_w)
end
@aggressive_constprop function PowerManifold(
M::PowerManifold{𝔽,TM},
::TPR,
size::Integer...;
parameter::Symbol = _parameter_symbol(M),
) where {𝔽,TM<:AbstractManifold{𝔽},TPR<:AbstractPowerRepresentation}
size_w = wrap_type_parameter(parameter, (get_parameter(M.size)..., size...))
return PowerManifold{𝔽,TM,typeof(size_w),TPR}(M.manifold, size_w)
end
function PowerManifold(
M::PowerManifold{𝔽},
::TPR,
size::Integer...;
parameter::Symbol = _parameter_symbol(M),
) where {𝔽,TPR<:Union{NestedPowerRepresentation,NestedReplacingPowerRepresentation}}
size_w = wrap_type_parameter(parameter, size)
return PowerManifold{𝔽,typeof(M),typeof(size_w),TPR}(M, size_w)
end
"""
PowerBasisData{TB<:AbstractArray}
Data storage for an array of basis data.
"""
struct PowerBasisData{TB<:AbstractArray}
bases::TB
end
const PowerManifoldNested =
AbstractPowerManifold{𝔽,<:AbstractManifold{𝔽},NestedPowerRepresentation} where {𝔽}
const PowerManifoldNestedReplacing = AbstractPowerManifold{
𝔽,
<:AbstractManifold{𝔽},
NestedReplacingPowerRepresentation,
} where {𝔽}
# _access_nested(::AbstractManifold, x, i::Tuple) can be overloaded to achieve
# manifold-specific nested element access (for example to `Identity` on power manifolds).
@inline _access_nested(M::AbstractManifold, x, i::Int) = _access_nested(M, x, (i,))
@inline _access_nested(::AbstractManifold, x, i::Tuple) = _access_nested(x, i)
@inline _access_nested(x, i::Tuple) = x[i...]
function Base.:^(
M::PowerManifold{
𝔽,
TM,
TSize,
<:Union{NestedPowerRepresentation,NestedReplacingPowerRepresentation},
},
size::Integer...,
) where {𝔽,TM<:AbstractManifold{𝔽},TSize}
return PowerManifold(M, size...)
end
function allocate_on(
M::PowerManifold{
𝔽,
TM,
TSize,
<:Union{NestedPowerRepresentation,NestedReplacingPowerRepresentation},
},
) where {𝔽,TM<:AbstractManifold{𝔽},TSize}
return [allocate_on(M.manifold) for _ in get_iterator(M)]
end
function allocate_on(
M::PowerManifold{
𝔽,
TM,
TSize,
<:Union{NestedPowerRepresentation,NestedReplacingPowerRepresentation},
},
::Type{<:Array{U}},
) where {𝔽,TM<:AbstractManifold{𝔽},TSize,U}
return [allocate_on(M.manifold, U) for _ in get_iterator(M)]
end
function allocate_on(
M::PowerManifold{
𝔽,
TM,
TSize,
<:Union{NestedPowerRepresentation,NestedReplacingPowerRepresentation},
},
ft::TangentSpaceType,
) where {𝔽,TM<:AbstractManifold{𝔽},TSize}
return [allocate_on(M.manifold, ft) for _ in get_iterator(M)]
end
function allocate_on(
M::PowerManifold{
𝔽,
TM,
TSize,
<:Union{NestedPowerRepresentation,NestedReplacingPowerRepresentation},
},
ft::TangentSpaceType,
::Type{<:Array{U}},
) where {𝔽,TM<:AbstractManifold{𝔽},TSize,U}
return [allocate_on(M.manifold, ft, U) for _ in get_iterator(M)]
end
"""
_allocate_access_nested(M::PowerManifoldNested, y, i)
Helper function for `allocate_result` on `PowerManifoldNested`. In allocation `y` can be
a number in which case `_access_nested` wouldn't work.
"""
_allocate_access_nested(M::PowerManifoldNested, y, i) = _access_nested(M, y, i)
_allocate_access_nested(::PowerManifoldNested, y::Number, i) = y
function allocate_result(M::PowerManifoldNested, f, x...)
if representation_size(M.manifold) === () && length(x) > 0
return allocate(M, x[1])
else
return [
allocate_result(
M.manifold,
f,
map(y -> _allocate_access_nested(M, y, i), x)...,
) for i in get_iterator(M)
]
end
end
# avoid ambiguities - though usually not used
function allocate_result(
M::PowerManifoldNested,
f::typeof(get_coordinates),
p,
X,
B::AbstractBasis,
)
return invoke(
allocate_result,
Tuple{AbstractManifold,typeof(get_coordinates),Any,Any,AbstractBasis},
M,
f,
p,
X,
B,
)
end
function allocate_result(M::PowerManifoldNestedReplacing, f, x...)
if length(x) == 0
return [allocate_result(M.manifold, f) for _ in get_iterator(M)]
else
return copy(x[1])
end
end
# the following is not used but necessary to avoid ambiguities
function allocate_result(
M::PowerManifoldNestedReplacing,
f::typeof(get_coordinates),
p,
X,
B::AbstractBasis,
)
return invoke(
allocate_result,
Tuple{AbstractManifold,typeof(get_coordinates),Any,Any,AbstractBasis},
M,
f,
p,
X,
B,
)
end
function allocate_result(M::PowerManifoldNested, f::typeof(get_vector), p, X)
return [
allocate_result(M.manifold, f, _access_nested(M, p, i)) for i in get_iterator(M)
]
end
function allocate_result(::PowerManifoldNestedReplacing, ::typeof(get_vector), p, X)
return copy(p)
end
function allocation_promotion_function(M::AbstractPowerManifold, f, args::Tuple)
return allocation_promotion_function(M.manifold, f, args)
end
"""
change_representer(M::AbstractPowerManifold, ::AbstractMetric, p, X)
Since the metric on a power manifold decouples, the change of a representer can be done elementwise
"""
change_representer(::AbstractPowerManifold, ::AbstractMetric, ::Any, ::Any)
function change_representer!(M::AbstractPowerManifold, Y, G::AbstractMetric, p, X)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
change_representer!(
M.manifold,
_write(M, rep_size, Y, i),
G,
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
)
end
return Y
end
"""
change_metric(M::AbstractPowerManifold, ::AbstractMetric, p, X)
Since the metric on a power manifold decouples, the change of metric can be done elementwise.
"""
change_metric(M::AbstractPowerManifold, ::AbstractMetric, ::Any, ::Any)
function change_metric!(M::AbstractPowerManifold, Y, G::AbstractMetric, p, X)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
change_metric!(
M.manifold,
_write(M, rep_size, Y, i),
G,
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
)
end
return Y
end
"""
check_point(M::AbstractPowerManifold, p; kwargs...)
Check whether `p` is a valid point on an [`AbstractPowerManifold`](@ref) `M`,
i.e. each element of `p` has to be a valid point on the base manifold.
If `p` is not a point on `M` a [`CompositeManifoldError`](@ref) consisting of all error messages of the
components, for which the tests fail is returned.
The tolerance for the last test can be set using the `kwargs...`.
"""
function check_point(M::AbstractPowerManifold, p; kwargs...)
rep_size = representation_size(M.manifold)
e = [
(i, check_point(M.manifold, _read(M, rep_size, p, i); kwargs...)) for
i in get_iterator(M)
]
errors = filter((x) -> !(x[2] === nothing), e)
cerr = [ComponentManifoldError(er...) for er in errors]
(length(errors) > 1) && return CompositeManifoldError(cerr)
(length(errors) == 1) && return cerr[1]
return nothing
end
"""
check_power_size(M, p)
check_power_size(M, p, X)
Check whether `p`` has the right size to represent points on `M`` generically, i.e. just
checking the overall sizes, not the individual ones per manifold.
"""
function check_power_size(M::AbstractPowerManifold, p)
d = prod(representation_size(M.manifold)) * prod(power_dimensions(M))
(d != length(p)) && return DomainError(
length(p),
"The point $p can not be a point on $M, since its number of elements does not match the required overall representation size ($d)",
)
return nothing
end
function check_power_size(M::Union{PowerManifoldNested,PowerManifoldNestedReplacing}, p)
d = prod(power_dimensions(M))
(d != length(p)) && return DomainError(
length(p),
"The point $p can not be a point on $M, since its number of elements does not match the power dimensions ($d)",
)
return nothing
end
function check_power_size(M::AbstractPowerManifold, p, X)
d = prod(representation_size(M.manifold)) * prod(power_dimensions(M))
(d != length(X)) && return DomainError(
length(X),
"The tangent vector $X can not belong to a trangent space at on $M, since its number of elements does not match the required overall representation size ($d)",
)
return nothing
end
function check_power_size(M::Union{PowerManifoldNested,PowerManifoldNestedReplacing}, p, X)
d = prod(power_dimensions(M))
(d != length(X)) && return DomainError(
length(X),
"The point $p can not be a point on $M, since its number of elements does not match the power dimensions ($d)",
)
return nothing
end
function check_size(M::AbstractPowerManifold, p)
cps = check_power_size(M, p)
(cps === nothing) || return cps
rep_size = representation_size(M.manifold)
e = [(i, check_size(M.manifold, _read(M, rep_size, p, i))) for i in get_iterator(M)]
errors = filter((x) -> !(x[2] === nothing), e)
cerr = [ComponentManifoldError(er...) for er in errors]
(length(errors) > 1) && return CompositeManifoldError(cerr)
(length(errors) == 1) && return cerr[1]
return nothing
end
function check_size(M::AbstractPowerManifold, p, X)
cps = check_power_size(M, p, X)
(cps === nothing) || return cps
rep_size = representation_size(M.manifold)
e = [
(i, check_size(M.manifold, _read(M, rep_size, p, i), _read(M, rep_size, X, i);)) for i in get_iterator(M)
]
errors = filter((x) -> !(x[2] === nothing), e)
cerr = [ComponentManifoldError(er...) for er in errors]
(length(errors) > 1) && return CompositeManifoldError(cerr)
(length(errors) == 1) && return cerr[1]
return nothing
end
"""
check_vector(M::AbstractPowerManifold, p, X; kwargs... )
Check whether `X` is a tangent vector to `p` an the [`AbstractPowerManifold`](@ref)
`M`, i.e. atfer [`check_point`](@ref)`(M, p)`, and all projections to
base manifolds must be respective tangent vectors.
If `X` is not a tangent vector to `p` on `M` a [`CompositeManifoldError`](@ref) consisting of all error
messages of the components, for which the tests fail is returned.
The tolerance for the last test can be set using the `kwargs...`.
"""
function check_vector(M::AbstractPowerManifold, p, X; kwargs...)
rep_size = representation_size(M.manifold)
e = [
(
i,
check_vector(
M.manifold,
_read(M, rep_size, p, i),
_read(M, rep_size, X, i);
kwargs...,
),
) for i in get_iterator(M)
]
errors = filter((x) -> !(x[2] === nothing), e)
cerr = [ComponentManifoldError(er...) for er in errors]
(length(errors) > 1) && return CompositeManifoldError(cerr)
(length(errors) == 1) && return cerr[1]
return nothing
end
@doc raw"""
copyto!(M::PowerManifoldNested, q, p)
Copy the values elementwise, i.e. call `copyto!(M.manifold, b, a)` for all elements `a` and
`b` of `p` and `q`, respectively.
"""
function copyto!(M::PowerManifoldNested, q, p)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
copyto!(M.manifold, _write(M, rep_size, q, i), _read(M, rep_size, p, i))
end
return q
end
@doc raw"""
copyto!(M::PowerManifoldNested, Y, p, X)
Copy the values elementwise, i.e. call `copyto!(M.manifold, B, a, A)` for all elements
`A`, `a` and `B` of `X`, `p`, and `Y`, respectively.
"""
function copyto!(M::PowerManifoldNested, Y, p, X)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
copyto!(
M.manifold,
_write(M, rep_size, Y, i),
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
)
end
return Y
end
@doc raw"""
default_retraction_method(M::PowerManifold)
Use the default retraction method of the internal `M.manifold` also in defaults of
functions defined for the power manifold, meaning that this is used elementwise.
"""
function default_retraction_method(M::PowerManifold)
return default_retraction_method(M.manifold)
end
function default_retraction_method(M::PowerManifold, t::Type)
return default_retraction_method(M.manifold, eltype(t))
end
@doc raw"""
default_inverse_retraction_method(M::PowerManifold)
Use the default inverse retraction method of the internal `M.manifold` also in defaults of
functions defined for the power manifold, meaning that this is used elementwise.
"""
function default_inverse_retraction_method(M::PowerManifold)
return default_inverse_retraction_method(M.manifold)
end
function default_inverse_retraction_method(M::PowerManifold, t::Type)
return default_inverse_retraction_method(M.manifold, eltype(t))
end
@doc raw"""
default_vector_transport_method(M::PowerManifold)
Use the default vector transport method of the internal `M.manifold` also in defaults of
functions defined for the power manifold, meaning that this is used elementwise.
"""
function default_vector_transport_method(M::PowerManifold)
return default_vector_transport_method(M.manifold)
end
function default_vector_transport_method(M::PowerManifold, t::Type)
return default_vector_transport_method(M.manifold, eltype(t))
end
@doc raw"""
distance(M::AbstractPowerManifold, p, q)
Compute the distance between `q` and `p` on an [`AbstractPowerManifold`](@ref),
i.e. from the element wise distances the Forbenius norm is computed.
"""
function distance(M::AbstractPowerManifold, p, q)
sum_squares = zero(number_eltype(p))
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
sum_squares +=
distance(M.manifold, _read(M, rep_size, p, i), _read(M, rep_size, q, i))^2
end
return sqrt(sum_squares)
end
@doc raw"""
exp(M::AbstractPowerManifold, p, X)
Compute the exponential map from `p` in direction `X` on the [`AbstractPowerManifold`](@ref) `M`,
which can be computed using the base manifolds exponential map elementwise.
"""
exp(::AbstractPowerManifold, ::Any...)
function exp!(M::AbstractPowerManifold, q, p, X)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
exp!(
M.manifold,
_write(M, rep_size, q, i),
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
)
end
return q
end
function exp!(M::PowerManifoldNestedReplacing, q, p, X)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
q[i...] = exp(M.manifold, _read(M, rep_size, p, i), _read(M, rep_size, X, i))
end
return q
end
@doc raw"""
fill(p, M::AbstractPowerManifold)
Create a point on the [`AbstractPowerManifold`](@ref) `M`, where every entry is set to the
point `p`.
!!! note
while usually the manifold is a first argument in all functions in `ManifoldsBase.jl`,
we follow the signature of `fill`, where the power manifold serves are the size information.
"""
function fill(p, M::AbstractPowerManifold)
P = allocate_result(M, rand) # rand finds the right way to allocate our point usually
return fill!(P, p, M)
end
@doc raw"""
fill!(P, p, M::AbstractPowerManifold)
Fill a point `P` on the [`AbstractPowerManifold`](@ref) `M`, setting every entry to `p`.
!!! note
while usually the manifold is the first argument in all functions in `ManifoldsBase.jl`,
we follow the signature of `fill!`, where the power manifold serves are the size information.
"""
function fill!(P, p, M::PowerManifoldNestedReplacing)
for i in get_iterator(M)
P[M, i] = p
end
return P
end
function fill!(P, p, M::AbstractPowerManifold)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
copyto!(M.manifold, _write(M, rep_size, P, i), p)
end
return P
end
function get_basis(M::AbstractPowerManifold, p, B::AbstractBasis)
rep_size = representation_size(M.manifold)
vs = [get_basis(M.manifold, _read(M, rep_size, p, i), B) for i in get_iterator(M)]
return CachedBasis(B, PowerBasisData(vs))
end
function get_basis(M::AbstractPowerManifold, p, B::DiagonalizingOrthonormalBasis)
rep_size = representation_size(M.manifold)
vs = [
get_basis(
M.manifold,
_read(M, rep_size, p, i),
DiagonalizingOrthonormalBasis(_read(M, rep_size, B.frame_direction, i)),
) for i in get_iterator(M)
]
return CachedBasis(B, PowerBasisData(vs))
end
"""
get_component(M::AbstractPowerManifold, p, idx...)
Get the component of a point `p` on an [`AbstractPowerManifold`](@ref) `M` at index `idx`.
"""
function get_component(M::AbstractPowerManifold, p, idx...)
rep_size = representation_size(M.manifold)
return _read(M, rep_size, p, idx)
end
function get_coordinates(M::AbstractPowerManifold, p, X, B::AbstractBasis)
rep_size = representation_size(M.manifold)
vs = [
get_coordinates(M.manifold, _read(M, rep_size, p, i), _read(M, rep_size, X, i), B) for i in get_iterator(M)
]
return reduce(vcat, reshape(vs, length(vs)))
end
function get_coordinates(
M::AbstractPowerManifold,
p,
X,
B::CachedBasis{𝔽,<:AbstractBasis,<:PowerBasisData},
) where {𝔽}
rep_size = representation_size(M.manifold)
vs = [
get_coordinates(
M.manifold,
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_access_nested(M, B.data.bases, i),
) for i in get_iterator(M)
]
return reduce(vcat, reshape(vs, length(vs)))
end
function get_coordinates!(M::AbstractPowerManifold, c, p, X, B::AbstractBasis)
rep_size = representation_size(M.manifold)
dim = manifold_dimension(M.manifold)
v_iter = 1
for i in get_iterator(M)
# TODO: this view is really suboptimal when `dim` can be statically determined
get_coordinates!(
M.manifold,
view(c, v_iter:(v_iter + dim - 1)),
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
B,
)
v_iter += dim
end
return c
end
function get_coordinates!(
M::AbstractPowerManifold,
c,
p,
X,
B::CachedBasis{𝔽,<:AbstractBasis,<:PowerBasisData},
) where {𝔽}
rep_size = representation_size(M.manifold)
dim = manifold_dimension(M.manifold)
v_iter = 1
for i in get_iterator(M)
# TODO: this view is really suboptimal when `dim` can be statically determined
get_coordinates!(
M.manifold,
view(c, v_iter:(v_iter + dim - 1)),
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_access_nested(M, B.data.bases, i),
)
v_iter += dim
end
return c
end
function get_iterator(
::PowerManifold{𝔽,<:AbstractManifold{𝔽},TypeParameter{Tuple{N}}},
) where {𝔽,N}
return Base.OneTo(N)
end
function get_iterator(M::PowerManifold{𝔽,<:AbstractManifold{𝔽},Tuple{Int}}) where {𝔽}
return Base.OneTo(M.size[1])
end
@generated function get_iterator(
::PowerManifold{𝔽,<:AbstractManifold{𝔽},TypeParameter{SizeTuple}},
) where {𝔽,SizeTuple}
size_tuple = size_to_tuple(SizeTuple)
return Base.product(map(Base.OneTo, size_tuple)...)
end
function get_iterator(M::PowerManifold{𝔽,<:AbstractManifold{𝔽},NTuple{N,Int}}) where {𝔽,N}
size_tuple = M.size
return Base.product(map(Base.OneTo, size_tuple)...)
end
function get_vector(
M::AbstractPowerManifold,
p,
c,
B::CachedBasis{𝔽,<:AbstractBasis{𝔽},<:PowerBasisData},
) where {𝔽}
Y = allocate_result(M, get_vector, p, c)
return get_vector!(M, Y, p, c, B)
end
function get_vector!(
M::AbstractPowerManifold,
Y,
p,
c,
B::CachedBasis{𝔽,<:AbstractBasis{𝔽},<:PowerBasisData},
) where {𝔽}
dim = manifold_dimension(M.manifold)
rep_size = representation_size(M.manifold)
v_iter = 1
for i in get_iterator(M)
get_vector!(
M.manifold,
_write(M, rep_size, Y, i),
_read(M, rep_size, p, i),
c[v_iter:(v_iter + dim - 1)],
_access_nested(M, B.data.bases, i),
)
v_iter += dim
end
return Y
end
function get_vector!(
M::PowerManifoldNestedReplacing,
Y,
p,
c,
B::CachedBasis{𝔽,<:AbstractBasis{𝔽},<:PowerBasisData},
) where {𝔽}
dim = manifold_dimension(M.manifold)
rep_size = representation_size(M.manifold)
v_iter = 1
for i in get_iterator(M)
Y[i...] = get_vector(
M.manifold,
_read(M, rep_size, p, i),
c[v_iter:(v_iter + dim - 1)],
_access_nested(M, B.data.bases, i),
)
v_iter += dim
end
return Y
end
function get_vector(M::AbstractPowerManifold, p, c, B::AbstractBasis)
Y = allocate_result(M, get_vector, p, c)
return get_vector!(M, Y, p, c, B)
end
function get_vector!(M::AbstractPowerManifold, Y, p, c, B::AbstractBasis)
dim = manifold_dimension(M.manifold)
rep_size = representation_size(M.manifold)
v_iter = 1
for i in get_iterator(M)
get_vector!(
M.manifold,
_write(M, rep_size, Y, i),
_read(M, rep_size, p, i),
c[v_iter:(v_iter + dim - 1)],
B,
)
v_iter += dim
end
return Y
end
function get_vector!(M::PowerManifoldNestedReplacing, Y, p, c, B::AbstractBasis)
dim = manifold_dimension(M.manifold)
rep_size = representation_size(M.manifold)
v_iter = 1
for i in get_iterator(M)
Y[i...] = get_vector(
M.manifold,
_read(M, rep_size, p, i),
c[v_iter:(v_iter + dim - 1)],
B,
)
v_iter += dim
end
return Y
end
function _get_vectors(
M::PowerManifoldNested,
p,
B::CachedBasis{𝔽,<:AbstractBasis{𝔽},<:PowerBasisData},
) where {𝔽}
zero_tv = zero_vector(M, p)
rep_size = representation_size(M.manifold)
vs = typeof(zero_tv)[]
for i in get_iterator(M)
b_i = _access_nested(M, B.data.bases, i)
p_i = _read(M, rep_size, p, i)
for v in get_vectors(M.manifold, p_i, b_i) #a bit safer than just b_i.data
new_v = copy(M, p, zero_tv)
copyto!(M.manifold, _write(M, rep_size, new_v, i), p_i, v)
push!(vs, new_v)
end
end
return vs
end
function _get_vectors(
M::PowerManifoldNestedReplacing,
p,
B::CachedBasis{𝔽,<:AbstractBasis{𝔽},<:PowerBasisData},
) where {𝔽}
zero_tv = zero_vector(M, p)
vs = typeof(zero_tv)[]
for i in get_iterator(M)
b_i = _access_nested(M, B.data.bases, i)
for v in b_i.data
new_v = copy(M, p, zero_tv)
new_v[i...] = v
push!(vs, new_v)
end
end
return vs
end
"""
getindex(p, M::AbstractPowerManifold, i::Union{Integer,Colon,AbstractVector}...)
p[M::AbstractPowerManifold, i...]
Access the element(s) at index `[i...]` of a point `p` on an [`AbstractPowerManifold`](@ref)
`M` by linear or multidimensional indexing.
See also [Array Indexing](https://docs.julialang.org/en/v1/manual/arrays/#man-array-indexing-1) in Julia.
"""
Base.@propagate_inbounds function Base.getindex(
p::AbstractArray,
M::AbstractPowerManifold,
I::Union{Integer,Colon,AbstractVector}...,
)
return get_component(M, p, I...)
end
"""
getindex(M::TangentSpace{𝔽, AbstractPowerManifold}, i...)
TpM[i...]
Access the `i`th manifold component from an [`AbstractPowerManifold`](@ref)s' tangent space `TpM`.
"""
function Base.getindex(
TpM::TangentSpace{𝔽,<:AbstractPowerManifold},
I::Union{Integer,Colon,AbstractVector}...,
) where {𝔽}
M = base_manifold(TpM)
p = base_point(TpM)
return TangentSpace(M.manifold, p[M, I...])
end
@doc raw"""
injectivity_radius(M::AbstractPowerManifold[, p])
the injectivity radius on an [`AbstractPowerManifold`](@ref) is for the global case
equal to the one of its base manifold. For a given point `p` it's equal to the
minimum of all radii in the array entries.
"""
function injectivity_radius(M::AbstractPowerManifold, p)
radius = 0.0
initialized = false
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
cur_rad = injectivity_radius(M.manifold, _read(M, rep_size, p, i))
if initialized
radius = min(cur_rad, radius)
else
radius = cur_rad
initialized = true
end
end
return radius
end
injectivity_radius(M::AbstractPowerManifold) = injectivity_radius(M.manifold)
function injectivity_radius(M::AbstractPowerManifold, ::AbstractRetractionMethod)
return injectivity_radius(M)
end
@doc raw"""
inner(M::AbstractPowerManifold, p, X, Y)
Compute the inner product of `X` and `Y` from the tangent space at `p` on an
[`AbstractPowerManifold`](@ref) `M`, i.e. for each arrays entry the tangent
vector entries from `X` and `Y` are in the tangent space of the corresponding
element from `p`.
The inner product is then the sum of the elementwise inner products.
"""
function inner(M::AbstractPowerManifold, p, X, Y)
result = zero(number_eltype(X))
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
result += inner(
M.manifold,
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, Y, i),
)
end
return result
end
"""
is_flat(M::AbstractPowerManifold)
Return true if [`AbstractPowerManifold`](@ref) is flat. It is flat if and only if the
wrapped manifold is flat.
"""
is_flat(M::AbstractPowerManifold) = is_flat(M.manifold)
function _isapprox(M::AbstractPowerManifold, p, q; kwargs...)
result = true
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
result &= isapprox(
M.manifold,
_read(M, rep_size, p, i),
_read(M, rep_size, q, i);
kwargs...,
)
end
return result
end
function _isapprox(M::AbstractPowerManifold, p, X, Y; kwargs...)
result = true
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
result &= isapprox(
M.manifold,
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, Y, i);
kwargs...,
)
end
return result
end
@doc raw"""
inverse_retract(M::AbstractPowerManifold, p, q, m::AbstractInverseRetractionMethod)
Compute the inverse retraction from `p` with respect to `q` on an [`AbstractPowerManifold`](@ref) `M`
using an [`AbstractInverseRetractionMethod`](@ref).
Then this method is performed elementwise, so the inverse
retraction method has to be one that is available on the base [`AbstractManifold`](@ref).
"""
inverse_retract(::AbstractPowerManifold, ::Any...)
function inverse_retract(
M::AbstractPowerManifold,
p,
q,
m::AbstractInverseRetractionMethod = default_inverse_retraction_method(M, typeof(p)),
)
X = allocate_result(M, inverse_retract, p, q)
return inverse_retract!(M, X, p, q, m)
end
function inverse_retract!(
M::AbstractPowerManifold,
X,
p,
q,
m::AbstractInverseRetractionMethod = default_inverse_retraction_method(M, typeof(p)),
)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
inverse_retract!(
M.manifold,
_write(M, rep_size, X, i),
_read(M, rep_size, p, i),
_read(M, rep_size, q, i),
m,
)
end
return X
end
function inverse_retract!(
M::PowerManifoldNestedReplacing,
X,
p,
q,
m::AbstractInverseRetractionMethod = default_inverse_retraction_method(M, typeof(p)),
)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
X[i...] = inverse_retract(
M.manifold,
_read(M, rep_size, p, i),
_read(M, rep_size, q, i),
m,
)
end
return X
end
@doc raw"""
log(M::AbstractPowerManifold, p, q)
Compute the logarithmic map from `p` to `q` on the [`AbstractPowerManifold`](@ref) `M`,
which can be computed using the base manifolds logarithmic map elementwise.
"""
log(::AbstractPowerManifold, ::Any...)
function log!(M::AbstractPowerManifold, X, p, q)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
log!(
M.manifold,
_write(M, rep_size, X, i),
_read(M, rep_size, p, i),
_read(M, rep_size, q, i),
)
end
return X
end
function log!(M::PowerManifoldNestedReplacing, X, p, q)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
X[i...] = log(M.manifold, _read(M, rep_size, p, i), _read(M, rep_size, q, i))
end
return X
end
@doc raw"""
manifold_dimension(M::PowerManifold)
Returns the manifold-dimension of an [`PowerManifold`](@ref) `M`
``=\mathcal N = (\mathcal M)^{n_1,…,n_d}``, i.e. with ``n=(n_1,…,n_d)`` the array
size of the power manifold and ``d_{\mathcal M}`` the dimension of the base manifold
``\mathcal M``, the manifold is of dimension
````math
\dim(\mathcal N) = \dim(\mathcal M)\prod_{i=1}^d n_i = n_1n_2⋅…⋅ n_d \dim(\mathcal M).
````
"""
function manifold_dimension(M::PowerManifold)
size = get_parameter(M.size)
return manifold_dimension(M.manifold) * prod(size)
end
function mid_point!(M::AbstractPowerManifold, q, p1, p2)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
mid_point!(
M.manifold,
_write(M, rep_size, q, i),
_read(M, rep_size, p1, i),
_read(M, rep_size, p2, i),
)
end
return q
end
function mid_point!(M::PowerManifoldNestedReplacing, q, p1, p2)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
q[i...] =
mid_point(M.manifold, _read(M, rep_size, p1, i), _read(M, rep_size, p2, i))
end
return q
end
@doc raw"""
norm(M::AbstractPowerManifold, p, X)
Compute the norm of `X` from the tangent space of `p` on an
[`AbstractPowerManifold`](@ref) `M`, i.e. from the element wise norms the
Frobenius norm is computed.
"""
function LinearAlgebra.norm(M::AbstractPowerManifold, p, X)
sum_squares = zero(number_eltype(X))
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
sum_squares +=
norm(M.manifold, _read(M, rep_size, p, i), _read(M, rep_size, X, i))^2
end
return sqrt(sum_squares)
end
function parallel_transport_direction!(M::AbstractPowerManifold, Y, p, X, d)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
parallel_transport_direction!(
M.manifold,
_write(M, rep_size, Y, i),
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, d, i),
)
end
return Y
end
function parallel_transport_direction(M::AbstractPowerManifold, p, X, d)
Y = allocate_result(M, vector_transport_direction, p, X, d)
return parallel_transport_direction!(M, Y, p, X, d)
end
function parallel_transport_direction!(M::PowerManifoldNestedReplacing, Y, p, X, d)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
Y[i...] = parallel_transport_direction(
M.manifold,
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, d, i),
)
end
return Y
end
function parallel_transport_direction(M::PowerManifoldNestedReplacing, p, X, d)
Y = allocate_result(M, parallel_transport_direction, p, X, d)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
Y[i...] = parallel_transport_direction(
M.manifold,
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, d, i),
)
end
return Y
end
function parallel_transport_to(M::AbstractPowerManifold, p, X, q)
Y = allocate_result(M, vector_transport_to, p, X)
return parallel_transport_to!(M, Y, p, X, q)
end
function parallel_transport_to!(M::AbstractPowerManifold, Y, p, X, q)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
vector_transport_to!(
M.manifold,
_write(M, rep_size, Y, i),
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, q, i),
)
end
return Y
end
function parallel_transport_to!(M::PowerManifoldNestedReplacing, Y, p, X, q)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
Y[i...] = parallel_transport_to(
M.manifold,
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, q, i),
)
end
return Y
end
@doc raw"""
power_dimensions(M::PowerManifold)
return the power of `M`,
"""
function power_dimensions(M::PowerManifold)
return get_parameter(M.size)
end
@doc raw"""
project(M::AbstractPowerManifold, p)
Project the point `p` from the embedding onto the [`AbstractPowerManifold`](@ref) `M`
by projecting all components.
"""
project(::AbstractPowerManifold, ::Any)
function project!(M::AbstractPowerManifold, q, p)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
project!(M.manifold, _write(M, rep_size, q, i), _read(M, rep_size, p, i))
end
return q
end
function project!(M::PowerManifoldNestedReplacing, q, p)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
q[i...] = project(M.manifold, _read(M, rep_size, p, i))
end
return q
end
@doc raw"""
project(M::AbstractPowerManifold, p, X)
Project the point `X` onto the tangent space at `p` on the
[`AbstractPowerManifold`](@ref) `M` by projecting all components.
"""
project(::AbstractPowerManifold, ::Any, ::Any)
function project!(M::AbstractPowerManifold, Z, q, Y)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
project!(
M.manifold,
_write(M, rep_size, Z, i),
_read(M, rep_size, q, i),
_read(M, rep_size, Y, i),
)
end
return Z
end
function project!(M::PowerManifoldNestedReplacing, Z, q, Y)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
q[i...] = project(M.manifold, _read(M, rep_size, q, i), _read(M, rep_size, Y, i))
end
return Z
end
function Random.rand!(M::AbstractPowerManifold, pX; vector_at = nothing, kwargs...)
rep_size = representation_size(M.manifold)
if vector_at === nothing
for i in get_iterator(M)
rand!(M.manifold, _write(M, rep_size, pX, i); kwargs...)
end
else
for i in get_iterator(M)
rand!(
M.manifold,
_write(M, rep_size, pX, i);
vector_at = _read(M, rep_size, vector_at, i),
kwargs...,
)
end
end
return pX
end
function Random.rand!(
rng::AbstractRNG,
M::AbstractPowerManifold,
pX;
vector_at = nothing,
kwargs...,
)
rep_size = representation_size(M.manifold)
if vector_at === nothing
for i in get_iterator(M)
rand!(rng, M.manifold, _write(M, rep_size, pX, i); kwargs...)
end
else
for i in get_iterator(M)
rand!(
rng,
M.manifold,
_write(M, rep_size, pX, i);
vector_at = _read(M, rep_size, vector_at, i),
kwargs...,
)
end
end
return pX
end
function Random.rand!(M::PowerManifoldNestedReplacing, pX; vector_at = nothing, kwargs...)
if vector_at === nothing
for i in get_iterator(M)
pX[i...] = rand(M.manifold; kwargs...)
end
else
for i in get_iterator(M)
pX[i...] = rand(M.manifold; vector_at = vector_at[i...], kwargs...)
end
end
return pX
end
function Random.rand!(
rng::AbstractRNG,
M::PowerManifoldNestedReplacing,
pX;
vector_at = nothing,
kwargs...,
)
if vector_at === nothing
for i in get_iterator(M)
pX[i...] = rand(rng, M.manifold; kwargs...)
end
else
for i in get_iterator(M)
pX[i...] = rand(rng, M.manifold; vector_at = vector_at[i...], kwargs...)
end
end
return pX
end
Base.@propagate_inbounds @inline function _read(
M::AbstractPowerManifold,
rep_size::Union{Tuple,Nothing},
x::AbstractArray,
i::Int,
)
return _read(M, rep_size, x, (i,))
end
Base.@propagate_inbounds @inline function _read(
::Union{PowerManifoldNested,PowerManifoldNestedReplacing},
rep_size::Union{Tuple,Nothing},
x::AbstractArray,
i::Tuple,
)
return x[i...]
end
@generated function rep_size_to_colons(rep_size::Tuple)
N = length(rep_size.parameters)
return ntuple(i -> Colon(), N)
end
@doc raw"""
retract(M::AbstractPowerManifold, p, X, method::AbstractRetractionMethod)
Compute the retraction from `p` with tangent vector `X` on an [`AbstractPowerManifold`](@ref) `M`
using a [`AbstractRetractionMethod`](@ref).
Then this method is performed elementwise, so the retraction
method has to be one that is available on the base [`AbstractManifold`](@ref).
"""
retract(::AbstractPowerManifold, ::Any...)
function retract(
M::AbstractPowerManifold,
p,
X,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
q = allocate_result(M, retract, p, X)
return retract!(M, q, p, X, m)
end
function retract!(
M::AbstractPowerManifold,
q,
p,
X,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
retract!(
M.manifold,
_write(M, rep_size, q, i),
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
m,
)
end
return q
end
function retract!(
M::PowerManifoldNestedReplacing,
q,
p,
X,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
q[i...] = retract(M.manifold, _read(M, rep_size, p, i), _read(M, rep_size, X, i), m)
end
return q
end
function retract!(
M::AbstractPowerManifold,
q,
p,
X,
t::Number,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
retract!(
M.manifold,
_write(M, rep_size, q, i),
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
t,
m,
)
end
return q
end
function retract!(
M::PowerManifoldNestedReplacing,
q,
p,
X,
t::Number,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
q[i...] =
retract(M.manifold, _read(M, rep_size, p, i), _read(M, rep_size, X, i), t, m)
end
return q
end
@doc raw"""
riemann_tensor(M::AbstractPowerManifold, p, X, Y, Z)
Compute the Riemann tensor at point from `p` with tangent vectors `X`, `Y` and `Z` on
the [`AbstractPowerManifold`](@ref) `M`.
"""
riemann_tensor(M::AbstractPowerManifold, p, X, Y, Z)
function riemann_tensor!(M::AbstractPowerManifold, Xresult, p, X, Y, Z)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
riemann_tensor!(
M.manifold,
_write(M, rep_size, Xresult, i),
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, Y, i),
_read(M, rep_size, Z, i),
)
end
return Xresult
end
function riemann_tensor!(M::PowerManifoldNestedReplacing, Xresult, p, X, Y, Z)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
Xresult[i...] = riemann_tensor(
M.manifold,
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, Y, i),
_read(M, rep_size, Z, i),
)
end
return Xresult
end
@doc raw"""
sectional_curvature(M::AbstractPowerManifold, p, X, Y)
Compute the sectional curvature of a power manifold manifold ``\mathcal M`` at a point
``p \in \mathcal M`` on two linearly independent tangent vectors at ``p``. It may be 0 for
if projections of `X` and `Y` on subspaces corresponding to component manifolds
are not linearly independent.
"""
function sectional_curvature(M::AbstractPowerManifold, p, X, Y)
curvature = zero(number_eltype(X))
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
p_i = _read(M, rep_size, p, i)
X_i = _read(M, rep_size, X, i)
Y_i = _read(M, rep_size, Y, i)
if are_linearly_independent(M.manifold, p_i, X_i, Y_i)
curvature += sectional_curvature(M.manifold, p_i, X_i, Y_i)
end
end
return curvature
end
@doc raw"""
sectional_curvature_max(M::AbstractPowerManifold)
Upper bound on sectional curvature of [`AbstractPowerManifold`](@ref) `M`. It is the maximum
of sectional curvature of the wrapped manifold and 0 in case there are two or more component
manifolds, as the sectional curvature corresponding to the plane spanned by vectors
`(X_1, 0, ... 0)` and `(0, X_2, 0, ..., 0)` is 0.
"""
function sectional_curvature_max(M::AbstractPowerManifold)
d = prod(power_dimensions(M))
mscm = sectional_curvature_max(M.manifold)
if d > 1
return max(mscm, zero(mscm))
else
return mscm
end
end
@doc raw"""
sectional_curvature_min(M::AbstractPowerManifold)
Lower bound on sectional curvature of [`AbstractPowerManifold`](@ref) `M`. It is the minimum
of sectional curvature of the wrapped manifold and 0 in case there are two or more component
manifolds, as the sectional curvature corresponding to the plane spanned by vectors
`(X_1, 0, ... 0)` and `(0, X_2, 0, ..., 0)` is 0.
"""
function sectional_curvature_min(M::AbstractPowerManifold)
d = prod(power_dimensions(M))
mscm = sectional_curvature_max(M.manifold)
if d > 1
return min(mscm, zero(mscm))
else
return mscm
end
end
"""
set_component!(M::AbstractPowerManifold, q, p, idx...)
Set the component of a point `q` on an [`AbstractPowerManifold`](@ref) `M` at index `idx`
to `p`, which itself is a point on the [`AbstractManifold`](@ref) the power manifold is build on.
"""
function set_component!(M::AbstractPowerManifold, q, p, idx...)
rep_size = representation_size(M.manifold)
return copyto!(_write(M, rep_size, q, idx), p)
end
function set_component!(::PowerManifoldNestedReplacing, q, p, idx...)
return q[idx...] = p
end
"""
setindex!(q, p, M::AbstractPowerManifold, i::Union{Integer,Colon,AbstractVector}...)
q[M::AbstractPowerManifold, i...] = p
Set the element(s) at index `[i...]` of a point `q` on an [`AbstractPowerManifold`](@ref)
`M` by linear or multidimensional indexing to `q`.
See also [Array Indexing](https://docs.julialang.org/en/v1/manual/arrays/#man-array-indexing-1) in Julia.
"""
Base.@propagate_inbounds function Base.setindex!(
q::AbstractArray,
p,
M::AbstractPowerManifold,
I::Union{Integer,Colon,AbstractVector}...,
)
return set_component!(M, q, p, I...)
end
function Base.show(
io::IO,
M::PowerManifold{𝔽,TM,TSize,TPR},
) where {𝔽,TM<:AbstractManifold{𝔽},TSize,TPR<:AbstractPowerRepresentation}
size = get_parameter(M.size)
return print(io, "PowerManifold($(M.manifold), $(TPR()), $(join(size, ", ")))")
end
function Base.show(
io::IO,
M::PowerManifold{𝔽,TM,TypeParameter{TSize},TPR},
) where {𝔽,TM<:AbstractManifold{𝔽},TSize,TPR<:AbstractPowerRepresentation}
size = get_parameter(M.size)
return print(
io,
"PowerManifold($(M.manifold), $(TPR()), $(join(size, ", ")); parameter=:type)",
)
end
function Base.show(
io::IO,
mime::MIME"text/plain",
B::CachedBasis{𝔽,T,D},
) where {T<:AbstractBasis,D<:PowerBasisData,𝔽}
println(io, "$(T()) for a power manifold")
for i in Base.product(map(Base.OneTo, size(B.data.bases))...)
println(io, "Basis for component $i:")
show(io, mime, _access_nested(B.data.bases, i))
println(io)
end
return nothing
end
function vector_transport_direction!(
M::AbstractPowerManifold,
Y,
p,
X,
d,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
vector_transport_direction!(
M.manifold,
_write(M, rep_size, Y, i),
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, d, i),
m,
)
end
return Y
end
function vector_transport_direction(
M::AbstractPowerManifold,
p,
X,
d,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
Y = allocate_result(M, vector_transport_direction, p, X, d)
return vector_transport_direction!(M, Y, p, X, d, m)
end
function vector_transport_direction!(
M::PowerManifoldNestedReplacing,
Y,
p,
X,
d,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
Y[i...] = vector_transport_direction(
M.manifold,
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, d, i),
m,
)
end
return Y
end
function vector_transport_direction(
M::PowerManifoldNestedReplacing,
p,
X,
d,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
Y = allocate_result(M, vector_transport_direction, p, X, d)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
Y[i...] = vector_transport_direction(
M.manifold,
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, d, i),
m,
)
end
return Y
end
@doc raw"""
vector_transport_to(M::AbstractPowerManifold, p, X, q, method::AbstractVectorTransportMethod)
Compute the vector transport the tangent vector `X`at `p` to `q` on the
[`PowerManifold`](@ref) `M` using an [`AbstractVectorTransportMethod`](@ref) `m`.
This method is performed elementwise, i.e. the method `m` has to be implemented on the
base manifold.
"""
vector_transport_to(
::AbstractPowerManifold,
::Any,
::Any,
::Any,
::AbstractVectorTransportMethod,
)
function vector_transport_to(
M::AbstractPowerManifold,
p,
X,
q,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
Y = allocate_result(M, vector_transport_to, p, X)
return vector_transport_to!(M, Y, p, X, q, m)
end
function vector_transport_to!(
M::AbstractPowerManifold,
Y,
p,
X,
q,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
vector_transport_to!(
M.manifold,
_write(M, rep_size, Y, i),
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, q, i),
m,
)
end
return Y
end
function vector_transport_to!(
M::PowerManifoldNestedReplacing,
Y,
p,
X,
q,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
Y[i...] = vector_transport_to(
M.manifold,
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, q, i),
m,
)
end
return Y
end
"""
view(p, M::PowerManifoldNested, i::Union{Integer,Colon,AbstractVector}...)
Get the view of the element(s) at index `[i...]` of a point `p` on an
[`AbstractPowerManifold`](@ref) `M` by linear or multidimensional indexing.
"""
function Base.view(
p::AbstractArray,
M::PowerManifoldNested,
I::Union{Integer,Colon,AbstractVector}...,
)
rep_size = representation_size(M.manifold)
return view(p[I...], rep_size_to_colons(rep_size)...)
end
@doc raw"""
Y = Weingarten(M::AbstractPowerManifold, p, X, V)
Weingarten!(M::AbstractPowerManifold, Y, p, X, V)
Since the metric decouples, also the computation of the Weingarten map
``\mathcal W_p`` can be computed elementwise on the single elements of the [`PowerManifold`](@ref) `M`.
"""
Weingarten(::AbstractPowerManifold, p, X, V)
function Weingarten!(M::AbstractPowerManifold, Y, p, X, V)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
Weingarten!(
M.manifold,
_write(M, rep_size, Y, i),
_read(M, rep_size, p, i),
_read(M, rep_size, X, i),
_read(M, rep_size, V, i),
)
end
return Y
end
@inline function _write(
M::AbstractPowerManifold,
rep_size::Union{Tuple,Nothing},
x::AbstractArray,
i::Int,
)
return _write(M, rep_size, x, (i,))
end
@inline function _is_nested_write_getindex(::PowerManifoldNested, x)
return !isbitstype(eltype(x))
end
@inline function _write(
M::PowerManifoldNested,
::Union{Tuple,Nothing},
x::AbstractArray,
i::Tuple,
)
if _is_nested_write_getindex(M, x)
return x[i...]
else
return view(x, i...)
end
end
function zero_vector!(M::AbstractPowerManifold, X, p)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
zero_vector!(M.manifold, _write(M, rep_size, X, i), _read(M, rep_size, p, i))
end
return X
end
function zero_vector!(M::PowerManifoldNestedReplacing, X, p)
rep_size = representation_size(M.manifold)
for i in get_iterator(M)
X[i...] = zero_vector(M.manifold, _read(M, rep_size, p, i))
end
return X
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 39604 | @doc raw"""
ProductManifold{𝔽,TM<:Tuple} <: AbstractManifold{𝔽}
Product manifold $M_1 × M_2 × … × M_n$ with product geometry.
# Constructor
ProductManifold(M_1, M_2, ..., M_n)
generates the product manifold $M_1 × M_2 × … × M_n$.
Alternatively, the same manifold can be contructed using the `×` operator:
`M_1 × M_2 × M_3`.
"""
struct ProductManifold{𝔽,TM<:Tuple} <: AbstractDecoratorManifold{𝔽}
manifolds::TM
end
function ProductManifold(manifolds::AbstractManifold...)
𝔽 = ManifoldsBase._unify_number_systems((number_system.(manifolds))...)
return ProductManifold{𝔽,typeof(manifolds)}(manifolds)
end
"""
getindex(M::ProductManifold, i)
M[i]
access the `i`th manifold component from the [`ProductManifold`](@ref) `M`.
"""
@inline Base.getindex(M::ProductManifold, i::Integer) = M.manifolds[i]
"""
getindex(M::TangentSpace{𝔽,<:ProductManifold}, i::Integer)
TpM[i]
Access the `i`th manifold component from a [`ProductManifold`](@ref)s' tangent space `TpM`.
"""
function Base.getindex(TpM::TangentSpace{𝔽,<:ProductManifold}, i::Integer) where {𝔽}
M = base_manifold(TpM)
return TangentSpace(M[i], base_point(TpM)[M, i])
end
ProductManifold() = throw(MethodError("No method matching ProductManifold()."))
const PRODUCT_BASIS_LIST = [
VeeOrthogonalBasis,
DefaultBasis,
DefaultBasis{<:Any,TangentSpaceType},
DefaultOrthogonalBasis,
DefaultOrthogonalBasis{<:Any,TangentSpaceType},
DefaultOrthonormalBasis,
DefaultOrthonormalBasis{<:Any,TangentSpaceType},
ProjectedOrthonormalBasis{:gram_schmidt,ℝ},
ProjectedOrthonormalBasis{:svd,ℝ},
]
"""
ProductBasisData
A typed tuple to store tuples of data of stored/precomputed bases for a [`ProductManifold`](@ref).
"""
struct ProductBasisData{T<:Tuple}
parts::T
end
const PRODUCT_BASIS_LIST_CACHED = [CachedBasis]
"""
ProductMetric <: AbstractMetric
A type to represent the product of metrics for a [`ProductManifold`](@ref).
"""
struct ProductMetric <: AbstractMetric end
"""
ProductRetraction(retractions::AbstractRetractionMethod...)
Product retraction of `retractions`. Works on [`ProductManifold`](@ref).
"""
struct ProductRetraction{TR<:Tuple} <: AbstractRetractionMethod
retractions::TR
end
function ProductRetraction(retractions::AbstractRetractionMethod...)
return ProductRetraction{typeof(retractions)}(retractions)
end
"""
InverseProductRetraction(retractions::AbstractInverseRetractionMethod...)
Product inverse retraction of `inverse retractions`. Works on [`ProductManifold`](@ref).
"""
struct InverseProductRetraction{TR<:Tuple} <: AbstractInverseRetractionMethod
inverse_retractions::TR
end
function InverseProductRetraction(inverse_retractions::AbstractInverseRetractionMethod...)
return InverseProductRetraction{typeof(inverse_retractions)}(inverse_retractions)
end
function allocation_promotion_function(M::ProductManifold, f, args::Tuple)
apfs = map(MM -> allocation_promotion_function(MM, f, args), M.manifolds)
return reduce(combine_allocation_promotion_functions, apfs)
end
"""
ProductVectorTransport(methods::AbstractVectorTransportMethod...)
Product vector transport type of `methods`. Works on [`ProductManifold`](@ref).
"""
struct ProductVectorTransport{TR<:Tuple} <: AbstractVectorTransportMethod
methods::TR
end
function ProductVectorTransport(methods::AbstractVectorTransportMethod...)
return ProductVectorTransport{typeof(methods)}(methods)
end
"""
change_representer(M::ProductManifold, ::AbstractMetric, p, X)
Since the metric on a product manifold decouples, the change of a representer can be done elementwise
"""
change_representer(::ProductManifold, ::AbstractMetric, ::Any, ::Any)
function change_representer!(M::ProductManifold, Y, G::AbstractMetric, p, X)
map(
(m, y, P, x) -> change_representer!(m, y, G, P, x),
M.manifolds,
submanifold_components(M, Y),
submanifold_components(M, p),
submanifold_components(M, X),
)
return Y
end
"""
change_metric(M::ProductManifold, ::AbstractMetric, p, X)
Since the metric on a product manifold decouples, the change of metric can be done elementwise.
"""
change_metric(::ProductManifold, ::AbstractMetric, ::Any, ::Any)
function change_metric!(M::ProductManifold, Y, G::AbstractMetric, p, X)
map(
(m, y, P, x) -> change_metric!(m, y, G, P, x),
M.manifolds,
submanifold_components(M, Y),
submanifold_components(M, p),
submanifold_components(M, X),
)
return Y
end
"""
check_point(M::ProductManifold, p; kwargs...)
Check whether `p` is a valid point on the [`ProductManifold`](@ref) `M`.
If `p` is not a point on `M` a [`CompositeManifoldError`](https://juliamanifolds.github.io/ManifoldsBase.jl/stable/functions.html#ManifoldsBase.CompositeManifoldError).consisting of all error messages of the
components, for which the tests fail is returned.
The tolerance for the last test can be set using the `kwargs...`.
"""
function check_point(M::ProductManifold, p; kwargs...)
try
submanifold_components(M, p)
catch e
return DomainError("Point $p does not support submanifold_components")
end
ts = ziptuples(Tuple(1:length(M.manifolds)), M.manifolds, submanifold_components(M, p))
e = [(t[1], check_point(t[2:end]...; kwargs...)) for t in ts]
errors = filter((x) -> !(x[2] === nothing), e)
cerr = [ComponentManifoldError(er...) for er in errors]
(length(errors) > 1) && return CompositeManifoldError(cerr)
(length(errors) == 1) && return cerr[1]
return nothing
end
"""
check_size(M::ProductManifold, p; kwargs...)
Check whether `p` is of valid size on the [`ProductManifold`](@ref) `M`.
If `p` has components of wrong size a [`CompositeManifoldError`](https://juliamanifolds.github.io/ManifoldsBase.jl/stable/functions.html#ManifoldsBase.CompositeManifoldError).consisting of all error messages of the
components, for which the tests fail is returned.
The tolerance for the last test can be set using the `kwargs...`.
"""
function check_size(M::ProductManifold, p)
try
submanifold_components(M, p)
catch e
return DomainError("Point $p does not support submanifold_components")
end
ts = ziptuples(Tuple(1:length(M.manifolds)), M.manifolds, submanifold_components(M, p))
e = [(t[1], check_size(t[2:end]...)) for t in ts]
errors = filter((x) -> !(x[2] === nothing), e)
cerr = [ComponentManifoldError(er...) for er in errors]
(length(errors) > 1) && return CompositeManifoldError(cerr)
(length(errors) == 1) && return cerr[1]
return nothing
end
function check_size(M::ProductManifold, p, X)
try
submanifold_components(M, X)
catch e
return DomainError("Vector $X does not support submanifold_components")
end
ts = ziptuples(
Tuple(1:length(M.manifolds)),
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
)
e = [(t[1], check_size(t[2:end]...)) for t in ts]
errors = filter(x -> !(x[2] === nothing), e)
cerr = [ComponentManifoldError(er...) for er in errors]
(length(errors) > 1) && return CompositeManifoldError(cerr)
(length(errors) == 1) && return cerr[1]
return nothing
end
"""
check_vector(M::ProductManifold, p, X; kwargs... )
Check whether `X` is a tangent vector to `p` on the [`ProductManifold`](@ref)
`M`, i.e. all projections to base manifolds must be respective tangent vectors.
If `X` is not a tangent vector to `p` on `M` a [`CompositeManifoldError`](https://juliamanifolds.github.io/ManifoldsBase.jl/stable/functions.html#ManifoldsBase.CompositeManifoldError).consisting
of all error messages of the components, for which the tests fail is returned.
The tolerance for the last test can be set using the `kwargs...`.
"""
function check_vector(M::ProductManifold, p, X; kwargs...)
try
submanifold_components(M, X)
catch e
return DomainError("Vector $X does not support submanifold_components")
end
ts = ziptuples(
Tuple(1:length(M.manifolds)),
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
)
e = [(t[1], check_vector(t[2:end]...; kwargs...)) for t in ts]
errors = filter(x -> !(x[2] === nothing), e)
cerr = [ComponentManifoldError(er...) for er in errors]
(length(errors) > 1) && return CompositeManifoldError(cerr)
(length(errors) == 1) && return cerr[1]
return nothing
end
@doc raw"""
×(M, N)
cross(M, N)
cross(M1, M2, M3,...)
Return the [`ProductManifold`](@ref) For two `AbstractManifold`s `M` and `N`,
where for the case that one of them is a [`ProductManifold`](@ref) itself,
the other is either prepended (if `N` is a product) or appenden (if `M`) is.
If both are product manifold, they are combined into one product manifold,
keeping the order.
For the case that more than one is a product manifold of these is build with the
same approach as above
"""
cross(::AbstractManifold...)
LinearAlgebra.cross(M::AbstractManifold, N::AbstractManifold) = ProductManifold(M, N)
function LinearAlgebra.cross(M::ProductManifold, N::AbstractManifold)
return ProductManifold(M.manifolds..., N)
end
function LinearAlgebra.cross(M::AbstractManifold, N::ProductManifold)
return ProductManifold(M, N.manifolds...)
end
function LinearAlgebra.cross(M::ProductManifold, N::ProductManifold)
return ProductManifold(M.manifolds..., N.manifolds...)
end
@doc raw"""
×(m, n)
cross(m, n)
cross(m1, m2, m3,...)
Return the [`ProductRetraction`](@ref) For two or more [`AbstractRetractionMethod`](@ref)s,
where for the case that one of them is a [`ProductRetraction`](@ref) itself,
the other is either prepended (if `m` is a product) or appenden (if `n`) is.
If both [`ProductRetraction`](@ref)s, they are combined into one keeping the order.
"""
cross(::AbstractRetractionMethod...)
function LinearAlgebra.cross(m::AbstractRetractionMethod, n::AbstractRetractionMethod)
return ProductRetraction(m, n)
end
function LinearAlgebra.cross(m::ProductRetraction, n::AbstractRetractionMethod)
return ProductRetraction(m.retractions..., n)
end
function LinearAlgebra.cross(m::AbstractRetractionMethod, n::ProductRetraction)
return ProductRetraction(m, n.retractions...)
end
function LinearAlgebra.cross(m::ProductRetraction, n::ProductRetraction)
return ProductRetraction(m.retractions..., n.retractions...)
end
@doc raw"""
×(m, n)
cross(m, n)
cross(m1, m2, m3,...)
Return the [`InverseProductRetraction`](@ref) For two or more [`AbstractInverseRetractionMethod`](@ref)s,
where for the case that one of them is a [`InverseProductRetraction`](@ref) itself,
the other is either prepended (if `r` is a product) or appenden (if `s`) is.
If both [`InverseProductRetraction`](@ref)s, they are combined into one keeping the order.
"""
cross(::AbstractInverseRetractionMethod...)
function LinearAlgebra.cross(
m::AbstractInverseRetractionMethod,
n::AbstractInverseRetractionMethod,
)
return InverseProductRetraction(m, n)
end
function LinearAlgebra.cross(
m::InverseProductRetraction,
n::AbstractInverseRetractionMethod,
)
return InverseProductRetraction(m.inverse_retractions..., n)
end
function LinearAlgebra.cross(
m::AbstractInverseRetractionMethod,
n::InverseProductRetraction,
)
return InverseProductRetraction(m, n.inverse_retractions...)
end
function LinearAlgebra.cross(m::InverseProductRetraction, n::InverseProductRetraction)
return InverseProductRetraction(m.inverse_retractions..., n.inverse_retractions...)
end
@doc raw"""
×(m, n)
cross(m, n)
cross(m1, m2, m3,...)
Return the [`ProductVectorTransport`](@ref) For two or more [`AbstractVectorTransportMethod`](@ref)s,
where for the case that one of them is a [`ProductVectorTransport`](@ref) itself,
the other is either prepended (if `r` is a product) or appenden (if `s`) is.
If both [`ProductVectorTransport`](@ref)s, they are combined into one keeping the order.
"""
cross(::AbstractVectorTransportMethod...)
function LinearAlgebra.cross(
m::AbstractVectorTransportMethod,
n::AbstractVectorTransportMethod,
)
return ProductVectorTransport(m, n)
end
function LinearAlgebra.cross(m::ProductVectorTransport, n::AbstractVectorTransportMethod)
return ProductVectorTransport(m.methods..., n)
end
function LinearAlgebra.cross(m::AbstractVectorTransportMethod, n::ProductVectorTransport)
return ProductVectorTransport(m, n.methods...)
end
function LinearAlgebra.cross(m::ProductVectorTransport, n::ProductVectorTransport)
return ProductVectorTransport(m.methods..., n.methods...)
end
function default_retraction_method(M::ProductManifold)
return ProductRetraction(map(default_retraction_method, M.manifolds)...)
end
function default_inverse_retraction_method(M::ProductManifold)
return InverseProductRetraction(map(default_inverse_retraction_method, M.manifolds)...)
end
function default_vector_transport_method(M::ProductManifold)
return ProductVectorTransport(map(default_vector_transport_method, M.manifolds)...)
end
@doc raw"""
distance(M::ProductManifold, p, q)
Compute the distance between two points `p` and `q` on the [`ProductManifold`](@ref) `M`, which is
the 2-norm of the elementwise distances on the internal manifolds that build `M`.
"""
function distance(M::ProductManifold, p, q)
return sqrt(
sum(
map(
distance,
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, q),
) .^ 2,
),
)
end
@doc raw"""
exp(M::ProductManifold, p, X)
compute the exponential map from `p` in the direction of `X` on the [`ProductManifold`](@ref) `M`,
which is the elementwise exponential map on the internal manifolds that build `M`.
"""
exp(::ProductManifold, ::Any...)
function exp!(M::ProductManifold, q, p, X)
map(
exp!,
M.manifolds,
submanifold_components(M, q),
submanifold_components(M, p),
submanifold_components(M, X),
)
return q
end
function exp!(M::ProductManifold, q, p, X, t::Number)
map(
(N, qc, pc, Xc) -> exp!(N, qc, pc, Xc, t),
M.manifolds,
submanifold_components(M, q),
submanifold_components(M, p),
submanifold_components(M, X),
)
return q
end
function get_basis(M::ProductManifold, p, B::AbstractBasis)
parts = map(t -> get_basis(t..., B), ziptuples(M.manifolds, submanifold_components(p)))
return CachedBasis(B, ProductBasisData(parts))
end
function get_basis(M::ProductManifold, p, B::CachedBasis)
return invoke(get_basis, Tuple{AbstractManifold,Any,CachedBasis}, M, p, B)
end
function get_basis(M::ProductManifold, p, B::DiagonalizingOrthonormalBasis)
vs = map(
ziptuples(
M.manifolds,
submanifold_components(p),
submanifold_components(B.frame_direction),
),
) do t
return get_basis(t[1], t[2], DiagonalizingOrthonormalBasis(t[3]))
end
return CachedBasis(B, ProductBasisData(vs))
end
"""
get_component(M::ProductManifold, p, i)
Get the `i`th component of a point `p` on a [`ProductManifold`](@ref) `M`.
"""
@inline function get_component(M::ProductManifold, p, i)
return submanifold_component(M, p, i)
end
function get_coordinates(M::ProductManifold, p, X, B::AbstractBasis)
reps = map(
t -> get_coordinates(t..., B),
ziptuples(M.manifolds, submanifold_components(M, p), submanifold_components(M, X)),
)
return vcat(reps...)
end
function get_coordinates(
M::ProductManifold,
p,
X,
B::CachedBasis{𝔽,<:AbstractBasis{𝔽},<:ProductBasisData},
) where {𝔽}
reps = map(
get_coordinates,
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
B.data.parts,
)
return vcat(reps...)
end
function get_coordinates!(M::ProductManifold, Xⁱ, p, X, B::AbstractBasis)
dim = manifold_dimension(M)
@assert length(Xⁱ) == dim
i = one(dim)
ts = ziptuples(M.manifolds, submanifold_components(M, p), submanifold_components(M, X))
for t in ts
SM = first(t)
dim = manifold_dimension(SM)
tXⁱ = @inbounds view(Xⁱ, i:(i + dim - 1))
get_coordinates!(SM, tXⁱ, Base.tail(t)..., B)
i += dim
end
return Xⁱ
end
function get_coordinates!(
M::ProductManifold,
Xⁱ,
p,
X,
B::CachedBasis{𝔽,<:AbstractBasis{𝔽},<:ProductBasisData},
) where {𝔽}
dim = manifold_dimension(M)
@assert length(Xⁱ) == dim
i = one(dim)
ts = ziptuples(
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
B.data.parts,
)
for t in ts
SM = first(t)
dim = manifold_dimension(SM)
tXⁱ = @inbounds view(Xⁱ, i:(i + dim - 1))
get_coordinates!(SM, tXⁱ, Base.tail(t)...)
i += dim
end
return Xⁱ
end
function _get_dim_ranges(dims::NTuple{N,Any}) where {N}
dims_acc = accumulate(+, (1, dims...))
return ntuple(i -> (dims_acc[i]:(dims_acc[i] + dims[i] - 1)), Val(N))
end
function get_vector!(M::ProductManifold, X, p, Xⁱ, B::AbstractBasis)
dims = map(manifold_dimension, M.manifolds)
@assert length(Xⁱ) == sum(dims)
dim_ranges = _get_dim_ranges(dims)
tXⁱ = map(dr -> (@inbounds view(Xⁱ, dr)), dim_ranges)
ts = ziptuples(
M.manifolds,
submanifold_components(M, X),
submanifold_components(M, p),
tXⁱ,
)
map(ts) do t
return get_vector!(t..., B)
end
return X
end
function get_vector!(
M::ProductManifold,
X,
p,
Xⁱ,
B::CachedBasis{𝔽,<:AbstractBasis{𝔽},<:ProductBasisData},
) where {𝔽}
dims = map(manifold_dimension, M.manifolds)
@assert length(Xⁱ) == sum(dims)
dim_ranges = _get_dim_ranges(dims)
tXⁱ = map(dr -> (@inbounds view(Xⁱ, dr)), dim_ranges)
ts = ziptuples(
M.manifolds,
submanifold_components(M, X),
submanifold_components(M, p),
tXⁱ,
B.data.parts,
)
map(ts) do t
return get_vector!(t...)
end
return X
end
@doc raw"""
injectivity_radius(M::ProductManifold)
injectivity_radius(M::ProductManifold, x)
Compute the injectivity radius on the [`ProductManifold`](@ref), which is the
minimum of the factor manifolds.
"""
injectivity_radius(::ProductManifold, ::Any...)
function injectivity_radius(M::ProductManifold, p)
return min(map(injectivity_radius, M.manifolds, submanifold_components(M, p))...)
end
function injectivity_radius(M::ProductManifold, p, m::AbstractRetractionMethod)
return min(
map(
(lM, lp) -> injectivity_radius(lM, lp, m),
M.manifolds,
submanifold_components(M, p),
)...,
)
end
function injectivity_radius(M::ProductManifold, p, m::ProductRetraction)
return min(
map(
(lM, lp, lm) -> injectivity_radius(lM, lp, lm),
M.manifolds,
submanifold_components(M, p),
m.retractions,
)...,
)
end
injectivity_radius(M::ProductManifold) = min(map(injectivity_radius, M.manifolds)...)
function injectivity_radius(M::ProductManifold, m::AbstractRetractionMethod)
return min(map(manif -> injectivity_radius(manif, m), M.manifolds)...)
end
function injectivity_radius(M::ProductManifold, m::ProductRetraction)
return min(map((lM, lm) -> injectivity_radius(lM, lm), M.manifolds, m.retractions)...)
end
@doc raw"""
inner(M::ProductManifold, p, X, Y)
compute the inner product of two tangent vectors `X`, `Y` from the tangent space
at `p` on the [`ProductManifold`](@ref) `M`, which is just the sum of the
internal manifolds that build `M`.
"""
function inner(M::ProductManifold, p, X, Y)
subproducts = map(
inner,
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, Y),
)
return sum(subproducts)
end
@doc raw"""
inverse_retract(M::ProductManifold, p, q, m::InverseProductRetraction)
Compute the inverse retraction from `p` with respect to `q` on the [`ProductManifold`](@ref)
`M` using an [`InverseProductRetraction`](@ref), which by default encapsulates a inverse
retraction for each manifold of the product. Then this method is performed elementwise,
so the encapsulated inverse retraction methods have to be available per factor.
"""
inverse_retract(::ProductManifold, ::Any, ::Any, ::Any, ::InverseProductRetraction)
@doc raw"""
inverse_retract(M::ProductManifold, p, q, m::AbstractInverseRetractionMethod)
Compute the inverse retraction from `p` with respect to `q` on the [`ProductManifold`](@ref)
`M` using an [`AbstractInverseRetractionMethod`](@ref), which is used on each manifold of
the product.
"""
inverse_retract(::ProductManifold, ::Any, ::Any, ::Any, ::AbstractInverseRetractionMethod)
function inverse_retract!(M::ProductManifold, Y, p, q, method::InverseProductRetraction)
map(
(iM, iY, ip, iq, im) -> inverse_retract!(iM, iY, ip, iq, im),
M.manifolds,
submanifold_components(M, Y),
submanifold_components(M, p),
submanifold_components(M, q),
method.inverse_retractions,
)
return Y
end
function inverse_retract!(
M::ProductManifold,
Y,
p,
q,
method::IRM,
) where {IRM<:AbstractInverseRetractionMethod}
map(
(iM, iY, ip, iq) -> inverse_retract!(iM, iY, ip, iq, method),
M.manifolds,
submanifold_components(M, Y),
submanifold_components(M, p),
submanifold_components(M, q),
)
return Y
end
function _isapprox(M::ProductManifold, p, q; kwargs...)
return all(
t -> isapprox(t...; kwargs...),
ziptuples(M.manifolds, submanifold_components(M, p), submanifold_components(M, q)),
)
end
function _isapprox(M::ProductManifold, p, X, Y; kwargs...)
return all(
t -> isapprox(t...; kwargs...),
ziptuples(
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, Y),
),
)
end
"""
is_flat(::ProductManifold)
Return true if and only if all component manifolds of [`ProductManifold`](@ref) `M` are flat.
"""
function is_flat(M::ProductManifold)
return all(is_flat, M.manifolds)
end
@doc raw"""
log(M::ProductManifold, p, q)
Compute the logarithmic map from `p` to `q` on the [`ProductManifold`](@ref) `M`,
which can be computed using the logarithmic maps of the manifolds elementwise.
"""
log(::ProductManifold, ::Any...)
function log!(M::ProductManifold, X, p, q)
map(
log!,
M.manifolds,
submanifold_components(M, X),
submanifold_components(M, p),
submanifold_components(M, q),
)
return X
end
@doc raw"""
manifold_dimension(M::ProductManifold)
Return the manifold dimension of the [`ProductManifold`](@ref), which is the sum of the
manifold dimensions the product is made of.
"""
manifold_dimension(M::ProductManifold) = mapreduce(manifold_dimension, +, M.manifolds)
function mid_point!(M::ProductManifold, q, p1, p2)
map(
mid_point!,
M.manifolds,
submanifold_components(M, q),
submanifold_components(M, p1),
submanifold_components(M, p2),
)
return q
end
@doc raw"""
norm(M::ProductManifold, p, X)
Compute the norm of `X` from the tangent space of `p` on the [`ProductManifold`](@ref),
i.e. from the element wise norms the 2-norm is computed.
"""
function LinearAlgebra.norm(M::ProductManifold, p, X)
norms_squared = (
map(
norm,
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
) .^ 2
)
return sqrt(sum(norms_squared))
end
"""
number_of_components(M::ProductManifold{<:NTuple{N,Any}}) where {N}
Calculate the number of manifolds multiplied in the given [`ProductManifold`](@ref) `M`.
"""
number_of_components(::ProductManifold{𝔽,<:NTuple{N,Any}}) where {𝔽,N} = N
function parallel_transport_direction!(M::ProductManifold, Y, p, X, d)
map(
parallel_transport_direction!,
M.manifolds,
submanifold_components(M, Y),
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, d),
)
return Y
end
function parallel_transport_to!(M::ProductManifold, Y, p, X, q)
map(
parallel_transport_to!,
M.manifolds,
submanifold_components(M, Y),
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, q),
)
return Y
end
function project!(M::ProductManifold, q, p)
map(project!, M.manifolds, submanifold_components(M, q), submanifold_components(M, p))
return q
end
function project!(M::ProductManifold, Y, p, X)
map(
project!,
M.manifolds,
submanifold_components(M, Y),
submanifold_components(M, p),
submanifold_components(M, X),
)
return Y
end
function Random.rand!(
M::ProductManifold,
pX;
vector_at = nothing,
parts_kwargs = map(_ -> (;), M.manifolds),
)
return rand!(
Random.default_rng(),
M,
pX;
vector_at = vector_at,
parts_kwargs = parts_kwargs,
)
end
function Random.rand!(
rng::AbstractRNG,
M::ProductManifold,
pX;
vector_at = nothing,
parts_kwargs = map(_ -> (;), M.manifolds),
)
if vector_at === nothing
map(
(N, q, kwargs) -> rand!(rng, N, q; kwargs...),
M.manifolds,
submanifold_components(M, pX),
parts_kwargs,
)
else
map(
(N, X, p, kwargs) -> rand!(rng, N, X; vector_at = p, kwargs...),
M.manifolds,
submanifold_components(M, pX),
submanifold_components(M, vector_at),
parts_kwargs,
)
end
return pX
end
@doc raw"""
retract(M::ProductManifold, p, X, m::ProductRetraction)
Compute the retraction from `p` with tangent vector `X` on the [`ProductManifold`](@ref) `M`
using an [`ProductRetraction`](@ref), which by default encapsulates retractions of the
base manifolds. Then this method is performed elementwise, so the encapsulated retractions
method has to be one that is available on the manifolds.
"""
retract(::ProductManifold, ::Any, ::Any, ::ProductRetraction)
@doc raw"""
retract(M::ProductManifold, p, X, m::AbstractRetractionMethod)
Compute the retraction from `p` with tangent vector `X` on the [`ProductManifold`](@ref) `M`
using the [`AbstractRetractionMethod`](@ref) `m` on every manifold.
"""
retract(::ProductManifold, ::Any, ::Any, ::AbstractRetractionMethod)
function retract!(M::ProductManifold, q, p, X, t::Number, method::ProductRetraction)
map(
(N, qc, pc, Xc, rm) -> retract!(N, qc, pc, Xc, t, rm),
M.manifolds,
submanifold_components(M, q),
submanifold_components(M, p),
submanifold_components(M, X),
method.retractions,
)
return q
end
function retract!(
M::ProductManifold,
q,
p,
X,
t::Number,
method::RTM,
) where {RTM<:AbstractRetractionMethod}
map(
(N, qc, pc, Xc) -> retract!(N, qc, pc, Xc, t, method),
M.manifolds,
submanifold_components(M, q),
submanifold_components(M, p),
submanifold_components(M, X),
)
return q
end
function representation_size(::ProductManifold)
return nothing
end
@doc raw"""
riemann_tensor(M::ProductManifold, p, X, Y, Z)
Compute the Riemann tensor at point from `p` with tangent vectors `X`, `Y` and `Z` on
the [`ProductManifold`](@ref) `M`.
"""
riemann_tensor(M::ProductManifold, p, X, Y, X)
function riemann_tensor!(M::ProductManifold, Xresult, p, X, Y, Z)
map(
riemann_tensor!,
M.manifolds,
submanifold_components(M, Xresult),
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, Y),
submanifold_components(M, Z),
)
return Xresult
end
@doc raw"""
sectional_curvature(M::ProductManifold, p, X, Y)
Compute the sectional curvature of a manifold ``\mathcal M`` at a point ``p \in \mathcal M``
on two linearly independent tangent vectors at ``p``. It may be 0 for a product of non-flat
manifolds if projections of `X` and `Y` on subspaces corresponding to component manifolds
are not linearly independent.
"""
function sectional_curvature(M::ProductManifold, p, X, Y)
curvature = zero(number_eltype(X))
map(
M.manifolds,
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, Y),
) do M_i, p_i, X_i, Y_i
if are_linearly_independent(M_i, p_i, X_i, Y_i)
curvature += sectional_curvature(M_i, p_i, X_i, Y_i)
end
end
return curvature
end
@doc raw"""
sectional_curvature_max(M::ProductManifold)
Upper bound on sectional curvature of [`ProductManifold`](@ref) `M`. It is the maximum of
sectional curvatures of component manifolds and 0 in case there are two or more component
manifolds, as the sectional curvature corresponding to the plane spanned by vectors
`(X_1, 0)` and `(0, X_2)` is 0.
"""
function sectional_curvature_max(M::ProductManifold)
max_sc = mapreduce(sectional_curvature_max, max, M.manifolds)
if length(M.manifolds) > 1
return max(max_sc, zero(max_sc))
else
return max_sc
end
end
@doc raw"""
sectional_curvature_min(M::ProductManifold)
Lower bound on sectional curvature of [`ProductManifold`](@ref) `M`. It is the minimum of
sectional curvatures of component manifolds and 0 in case there are two or more component
manifolds, as the sectional curvature corresponding to the plane spanned by vectors
`(X_1, 0)` and `(0, X_2)` is 0.
"""
function sectional_curvature_min(M::ProductManifold)
min_sc = mapreduce(sectional_curvature_min, min, M.manifolds)
if length(M.manifolds) > 1
return min(min_sc, zero(min_sc))
else
return min_sc
end
end
"""
select_from_tuple(t::NTuple{N, Any}, positions::Val{P})
Selects elements of tuple `t` at positions specified by the second argument.
For example `select_from_tuple(("a", "b", "c"), Val((3, 1, 1)))` returns
`("c", "a", "a")`.
"""
@generated function select_from_tuple(t::NTuple{N,Any}, positions::Val{P}) where {N,P}
for k in P
(k < 0 || k > N) && error("positions must be between 1 and $N")
end
return Expr(:tuple, [Expr(:ref, :t, k) for k in P]...)
end
"""
set_component!(M::ProductManifold, q, p, i)
Set the `i`th component of a point `q` on a [`ProductManifold`](@ref) `M` to `p`, where `p` is a point on the [`AbstractManifold`](https://juliamanifolds.github.io/ManifoldsBase.jl/stable/types.html#ManifoldsBase.AbstractManifold) this factor of the product manifold consists of.
"""
function set_component!(M::ProductManifold, q, p, i)
return copyto!(submanifold_component(M, q, i), p)
end
function _show_submanifold(io::IO, M::AbstractManifold; pre = "")
sx = sprint(show, "text/plain", M, context = io, sizehint = 0)
if occursin('\n', sx)
sx = sprint(show, M, context = io, sizehint = 0)
end
sx = replace(sx, '\n' => "\n$(pre)")
print(io, pre, sx)
return nothing
end
function _show_submanifold_range(io::IO, Ms, range; pre = "")
for i in range
M = Ms[i]
print(io, '\n')
_show_submanifold(io, M; pre = pre)
end
return nothing
end
function _show_product_manifold_no_header(io::IO, M)
n = length(M.manifolds)
sz = displaysize(io)
screen_height, screen_width = sz[1] - 4, sz[2]
half_height = div(screen_height, 2)
inds = 1:n
pre = " "
if n > screen_height
inds = [1:half_height; (n - div(screen_height - 1, 2) + 1):n]
end
if n ≤ screen_height
_show_submanifold_range(io, M.manifolds, 1:n; pre = pre)
else
_show_submanifold_range(io, M.manifolds, 1:half_height; pre = pre)
print(io, "\n$(pre)⋮")
_show_submanifold_range(
io,
M.manifolds,
(n - div(screen_height - 1, 2) + 1):n;
pre = pre,
)
end
return nothing
end
function Base.show(io::IO, ::MIME"text/plain", M::ProductManifold)
n = length(M.manifolds)
print(io, "ProductManifold with $(n) submanifold$(n == 1 ? "" : "s"):")
return _show_product_manifold_no_header(io, M)
end
function Base.show(io::IO, M::ProductManifold)
return print(io, "ProductManifold(", join(M.manifolds, ", "), ")")
end
function Base.show(io::IO, m::ProductRetraction)
return print(io, "ProductRetraction(", join(m.retractions, ", "), ")")
end
function Base.show(io::IO, m::InverseProductRetraction)
return print(io, "InverseProductRetraction(", join(m.inverse_retractions, ", "), ")")
end
function Base.show(io::IO, m::ProductVectorTransport)
return print(io, "ProductVectorTransport(", join(m.methods, ", "), ")")
end
function Base.show(
io::IO,
mime::MIME"text/plain",
B::CachedBasis{𝔽,T,D},
) where {𝔽,T<:AbstractBasis{𝔽},D<:ProductBasisData}
println(io, "$(T) for a product manifold")
for (i, cb) in enumerate(B.data.parts)
println(io, "Basis for component $i:")
show(io, mime, cb)
println(io)
end
return nothing
end
"""
submanifold(M::ProductManifold, i::Integer)
Extract the `i`th factor of the product manifold `M`.
"""
submanifold(M::ProductManifold, i::Integer) = M.manifolds[i]
"""
submanifold(M::ProductManifold, i::Val)
submanifold(M::ProductManifold, i::AbstractVector)
Extract the factor of the product manifold `M` indicated by indices in `i`.
For example, for `i` equal to `Val((1, 3))` the product manifold constructed
from the first and the third factor is returned.
The version with `AbstractVector` is not type-stable, for better preformance use `Val`.
"""
function submanifold(M::ProductManifold, i::Val)
return ProductManifold(select_from_tuple(M.manifolds, i)...)
end
submanifold(M::ProductManifold, i::AbstractVector) = submanifold(M, Val(tuple(i...)))
function vector_transport_direction!(
M::ProductManifold,
Y,
p,
X,
d,
m::ProductVectorTransport,
)
map(
vector_transport_direction!,
M.manifolds,
submanifold_components(M, Y),
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, d),
m.methods,
)
return Y
end
function vector_transport_direction!(
M::ProductManifold,
Y,
p,
X,
d,
m::VTM,
) where {VTM<:AbstractVectorTransportMethod}
map(
(iM, iY, ip, iX, id) -> vector_transport_direction!(iM, iY, ip, iX, id, m),
M.manifolds,
submanifold_components(M, Y),
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, d),
)
return Y
end
@doc raw"""
vector_transport_to(M::ProductManifold, p, X, q, m::ProductVectorTransport)
Compute the vector transport the tangent vector `X` at `p` to `q` on the
[`ProductManifold`](@ref) `M` using a [`ProductVectorTransport`](@ref) `m`.
"""
vector_transport_to(::ProductManifold, ::Any, ::Any, ::Any, ::ProductVectorTransport)
@doc raw"""
vector_transport_to(M::ProductManifold, p, X, q, m::AbstractVectorTransportMethod)
Compute the vector transport the tangent vector `X` at `p` to `q` on the
[`ProductManifold`](@ref) `M` using an [`AbstractVectorTransportMethod`](@ref) `m`
on each manifold.
"""
vector_transport_to(::ProductManifold, ::Any, ::Any, ::Any, ::AbstractVectorTransportMethod)
function vector_transport_to!(M::ProductManifold, Y, p, X, q, m::ProductVectorTransport)
map(
vector_transport_to!,
M.manifolds,
submanifold_components(M, Y),
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, q),
m.methods,
)
return Y
end
function vector_transport_to!(
M::ProductManifold,
Y,
p,
X,
q,
m::AbstractVectorTransportMethod,
)
map(
(iM, iY, ip, iX, iq) -> vector_transport_to!(iM, iY, ip, iX, iq, m),
M.manifolds,
submanifold_components(M, Y),
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, q),
),
return Y
end
@doc raw"""
Y = Weingarten(M::ProductManifold, p, X, V)
Weingarten!(M::ProductManifold, Y, p, X, V)
Since the metric decouples, also the computation of the Weingarten map
``\mathcal W_p`` can be computed elementwise on the single elements of the [`ProductManifold`](@ref) `M`.
"""
Weingarten(::ProductManifold, p, X, V)
function Weingarten!(M::ProductManifold, Y, p, X, V)
map(
Weingarten!,
M.manifolds,
submanifold_components(M, Y),
submanifold_components(M, p),
submanifold_components(M, X),
submanifold_components(M, V),
)
return Y
end
function zero_vector!(M::ProductManifold, X, p)
map(
zero_vector!,
M.manifolds,
submanifold_components(M, X),
submanifold_components(M, p),
)
return X
end
@doc raw"""
submanifold_component(M::AbstractManifold, p, i::Integer)
submanifold_component(M::AbstractManifold, p, ::Val{i}) where {i}
submanifold_component(p, i::Integer)
submanifold_component(p, ::Val{i}) where {i}
Project the product array `p` on `M` to its `i`th component. A new array is returned.
"""
submanifold_component(::Any...)
@inline function submanifold_component(M::AbstractManifold, p, i::Integer)
return submanifold_component(M, p, Val(i))
end
@inline submanifold_component(M::AbstractManifold, p, i::Val) = submanifold_component(p, i)
@inline submanifold_component(p, i::Integer) = submanifold_component(p, Val(i))
@doc raw"""
submanifold_components(M::AbstractManifold, p)
submanifold_components(p)
Get the projected components of `p` on the submanifolds of `M`. The components are returned in a Tuple.
"""
submanifold_components(::Any...)
@inline submanifold_components(::AbstractManifold, p) = submanifold_components(p)
"""
ziptuples(a, b[, c[, d[, e]]])
Zips tuples `a`, `b`, and remaining in a fast, type-stable way. If they have different
lengths, the result is trimmed to the length of the shorter tuple.
"""
@generated function ziptuples(a::NTuple{N,Any}, b::NTuple{M,Any}) where {N,M}
ex = Expr(:tuple)
for i in 1:min(N, M)
push!(ex.args, :((a[$i], b[$i])))
end
return ex
end
@generated function ziptuples(
a::NTuple{N,Any},
b::NTuple{M,Any},
c::NTuple{L,Any},
) where {N,M,L}
ex = Expr(:tuple)
for i in 1:min(N, M, L)
push!(ex.args, :((a[$i], b[$i], c[$i])))
end
return ex
end
@generated function ziptuples(
a::NTuple{N,Any},
b::NTuple{M,Any},
c::NTuple{L,Any},
d::NTuple{K,Any},
) where {N,M,L,K}
ex = Expr(:tuple)
for i in 1:min(N, M, L, K)
push!(ex.args, :((a[$i], b[$i], c[$i], d[$i])))
end
return ex
end
@generated function ziptuples(
a::NTuple{N,Any},
b::NTuple{M,Any},
c::NTuple{L,Any},
d::NTuple{K,Any},
e::NTuple{J,Any},
) where {N,M,L,K,J}
ex = Expr(:tuple)
for i in 1:min(N, M, L, K, J)
push!(ex.args, :((a[$i], b[$i], c[$i], d[$i], e[$i])))
end
return ex
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 9030 |
@doc raw"""
TangentSpace{𝔽,M} = Fiber{𝔽,TangentSpaceType,M} where {𝔽,M<:AbstractManifold{𝔽}}
A manifold for the tangent space ``T_p\mathcal M`` at a point ``p\in\mathcal M``.
This is modelled as an alias for [`VectorSpaceFiber`](@ref) corresponding to
[`TangentSpaceType`](@ref).
# Constructor
TangentSpace(M::AbstractManifold, p)
Return the manifold (vector space) representing the tangent space ``T_p\mathcal M``
at point `p`, ``p\in\mathcal M``.
"""
const TangentSpace{𝔽,M} = Fiber{𝔽,TangentSpaceType,M} where {𝔽,M<:AbstractManifold{𝔽}}
TangentSpace(M::AbstractManifold, p) = Fiber(M, p, TangentSpaceType())
@doc raw"""
CotangentSpace{𝔽,M} = Fiber{𝔽,CotangentSpaceType,M} where {𝔽,M<:AbstractManifold{𝔽}}
A manifold for the Cotangent space ``T^*_p\mathcal M`` at a point ``p\in\mathcal M``.
This is modelled as an alias for [`VectorSpaceFiber`](@ref) corresponding to
[`CotangentSpaceType`](@ref).
# Constructor
CotangentSpace(M::AbstractManifold, p)
Return the manifold (vector space) representing the cotangent space ``T^*_p\mathcal M``
at point `p`, ``p\in\mathcal M``.
"""
const CotangentSpace{𝔽,M} = Fiber{𝔽,CotangentSpaceType,M} where {𝔽,M<:AbstractManifold{𝔽}}
CotangentSpace(M::AbstractManifold, p) = Fiber(M, p, CotangentSpaceType())
function allocate_result(M::TangentSpace, ::typeof(rand))
return zero_vector(M.manifold, M.point)
end
@doc raw"""
base_point(TpM::TangentSpace)
Return the base point of the [`TangentSpace`](@ref).
"""
base_point(TpM::TangentSpace) = TpM.point
# forward both point checks to tangent vector checks
function check_point(TpM::TangentSpace, p; kwargs...)
return check_vector(TpM.manifold, TpM.point, p; kwargs...)
end
function check_size(TpM::TangentSpace, p; kwargs...)
return check_size(TpM.manifold, TpM.point, p; kwargs...)
end
# fix tangent vector checks to use the right base point
function check_vector(TpM::TangentSpace, p, X; kwargs...)
return check_vector(TpM.manifold, TpM.point, X; kwargs...)
end
function check_size(TpM::TangentSpace, p, X; kwargs...)
return check_size(TpM.manifold, TpM.point, X; kwargs...)
end
"""
distance(M::TangentSpace, X, Y)
Distance between vectors `X` and `Y` from the [`TangentSpace`](@ref) `TpM`.
It is calculated as the [`norm`](@ref) (induced by the metric on `TpM`) of their difference.
"""
function distance(TpM::TangentSpace, X, Y)
return norm(TpM.manifold, TpM.point, Y - X)
end
function embed!(TpM::TangentSpace, Y, X)
return embed!(TpM.manifold, Y, TpM.point, X)
end
function embed!(TpM::TangentSpace, W, X, V)
return embed!(TpM.manifold, W, TpM.point, V)
end
@doc raw"""
exp(TpM::TangentSpace, X, V)
Exponential map of tangent vectors `X` from `TpM` and a direction `V`,
which is also from the [`TangentSpace`](@ref) `TpM` since we identify the tangent space of `TpM` with `TpM`.
The exponential map then simplifies to the sum `X+V`.
"""
exp(::TangentSpace, ::Any, ::Any)
function exp!(TpM::TangentSpace, Y, X, V)
copyto!(TpM.manifold, Y, TpM.point, X + V)
return Y
end
fiber_dimension(M::AbstractManifold, ::CotangentSpaceType) = manifold_dimension(M)
fiber_dimension(M::AbstractManifold, ::TangentSpaceType) = manifold_dimension(M)
function get_basis(TpM::TangentSpace, X, B::CachedBasis)
return invoke(
get_basis,
Tuple{AbstractManifold,Any,CachedBasis},
TpM.manifold,
TpM.point,
B,
)
end
function get_basis(TpM::TangentSpace, X, B::AbstractBasis{<:Any,TangentSpaceType})
return get_basis(TpM.manifold, TpM.point, B)
end
function get_coordinates(TpM::TangentSpace, X, V, B::AbstractBasis)
return get_coordinates(TpM.manifold, TpM.point, V, B)
end
function get_coordinates!(TpM::TangentSpace, c, X, V, B::AbstractBasis)
return get_coordinates!(TpM.manifold, c, TpM.point, V, B)
end
function get_vector(TpM::TangentSpace, X, c, B::AbstractBasis)
return get_vector(TpM.manifold, TpM.point, c, B)
end
function get_vector!(TpM::TangentSpace, V, X, c, B::AbstractBasis)
return get_vector!(TpM.manifold, V, TpM.point, c, B)
end
function get_vectors(TpM::TangentSpace, X, B::CachedBasis)
return get_vectors(TpM.manifold, TpM.point, B)
end
@doc raw"""
injectivity_radius(TpM::TangentSpace)
Return the injectivity radius on the [`TangentSpace`](@ref) `TpM`, which is $∞$.
"""
injectivity_radius(::TangentSpace) = Inf
@doc raw"""
inner(M::TangentSpace, X, V, W)
For any ``X ∈ T_p\mathcal M`` we identify the tangent space ``T_X(T_p\mathcal M)``
with ``T_p\mathcal M`` again. Hence an inner product of ``V,W`` is just the inner product of
the tangent space itself. ``⟨V,W⟩_X = ⟨V,W⟩_p``.
"""
function inner(TpM::TangentSpace, X, V, W)
return inner(TpM.manifold, TpM.point, V, W)
end
"""
is_flat(::TangentSpace)
The [`TangentSpace`](@ref) is a flat manifold, so this returns `true`.
"""
is_flat(::TangentSpace) = true
function _isapprox(TpM::TangentSpace, X, Y; kwargs...)
return isapprox(TpM.manifold, TpM.point, X, Y; kwargs...)
end
function _isapprox(TpM::TangentSpace, X, V, W; kwargs...)
return isapprox(TpM.manifold, TpM.point, V, W; kwargs...)
end
"""
log(TpM::TangentSpace, X, Y)
Logarithmic map on the [`TangentSpace`](@ref) `TpM`, calculated as the difference of tangent
vectors `q` and `p` from `TpM`.
"""
log(::TangentSpace, ::Any...)
function log!(TpM::TangentSpace, V, X, Y)
copyto!(TpM, V, TpM.point, Y - X)
return V
end
@doc raw"""
manifold_dimension(TpM::TangentSpace)
Return the dimension of the [`TangentSpace`](@ref) ``T_p\mathcal M`` at ``p∈\mathcal M``,
which is the same as the dimension of the manifold ``\mathcal M``.
"""
function manifold_dimension(TpM::TangentSpace)
return manifold_dimension(TpM.manifold)
end
@doc raw"""
parallel_transport_to(::TangentSpace, X, V, Y)
Transport the tangent vector ``Z ∈ T_X(T_p\mathcal M)`` from `X` to `Y`.
Since we identify ``T_X(T_p\mathcal M) = T_p\mathcal M`` and the tangent space is a vector space,
parallel transport simplifies to the identity, so this function yields ``V`` as a result.
"""
parallel_transport_to(TpM::TangentSpace, X, V, Y)
function parallel_transport_to!(TpM::TangentSpace, W, X, V, Y)
return copyto!(TpM.manifold, W, TpM.point, V)
end
@doc raw"""
project(TpM::TangentSpace, X)
Project the point `X` from embedding of the [`TangentSpace`](@ref) `TpM` onto `TpM`.
"""
project(::TangentSpace, ::Any)
function project!(TpM::TangentSpace, Y, X)
return project!(TpM.manifold, Y, TpM.point, X)
end
@doc raw"""
project(TpM::TangentSpace, X, V)
Project the vector `V` from the embedding of the tangent space `TpM` (identified with ``T_X(T_p\mathcal M)``),
that is project the vector `V` onto the tangent space at `TpM.point`.
"""
project(::TangentSpace, ::Any, ::Any)
function project!(TpM::TangentSpace, W, X, V)
return project!(TpM.manifold, W, TpM.point, V)
end
function Random.rand!(TpM::TangentSpace, X; vector_at = nothing)
rand!(TpM.manifold, X; vector_at = TpM.point)
return X
end
function Random.rand!(rng::AbstractRNG, TpM::TangentSpace, X; vector_at = nothing)
rand!(rng, TpM.manifold, X; vector_at = TpM.point)
return X
end
function representation_size(TpM::TangentSpace)
return representation_size(TpM.manifold)
end
function Base.show(io::IO, ::MIME"text/plain", TpM::TangentSpace)
println(io, "Tangent space to the manifold $(base_manifold(TpM)) at point:")
pre = " "
sp = sprint(show, "text/plain", TpM.point; context = io, sizehint = 0)
sp = replace(sp, '\n' => "\n$(pre)")
return print(io, pre, sp)
end
function Base.show(io::IO, ::MIME"text/plain", cTpM::CotangentSpace)
println(io, "Cotangent space to the manifold $(base_manifold(cTpM)) at point:")
pre = " "
sp = sprint(show, "text/plain", cTpM.point; context = io, sizehint = 0)
sp = replace(sp, '\n' => "\n$(pre)")
return print(io, pre, sp)
end
@doc raw"""
Y = Weingarten(TpM::TangentSpace, X, V, A)
Weingarten!(TpM::TangentSpace, Y, p, X, V)
Compute the Weingarten map ``\mathcal W_X`` at `X` on the [`TangentSpace`](@ref) `TpM` with respect to the
tangent vector ``V \in T_p\mathcal M`` and the normal vector ``A \in N_p\mathcal M``.
Since this a flat space by itself, the result is always the zero tangent vector.
"""
Weingarten(::TangentSpace, ::Any, ::Any, ::Any)
Weingarten!(::TangentSpace, W, X, V, A) = fill!(W, 0)
@doc raw"""
zero_vector(TpM::TangentSpace)
Zero tangent vector in the [`TangentSpace`](@ref) `TpM`,
that is the zero tangent vector at point `TpM.point`.
"""
zero_vector(TpM::TangentSpace) = zero_vector(TpM.manifold, TpM.point)
@doc raw"""
zero_vector(TpM::TangentSpace, X)
Zero tangent vector at point `X` from the [`TangentSpace`](@ref) `TpM`,
that is the zero tangent vector at point `TpM.point`,
since we identify the tangent space ``T_X(T_p\mathcal M)`` with ``T_p\mathcal M``.
"""
zero_vector(::TangentSpace, ::Any...)
function zero_vector!(M::TangentSpace, V, X)
return zero_vector!(M.manifold, V, M.point)
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 14613 | """
ValidationManifold{𝔽,M<:AbstractManifold{𝔽}} <: AbstractDecoratorManifold{𝔽}
A manifold to encapsulate manifolds working on array representations of [`AbstractManifoldPoint`](@ref)s
and [`TVector`](@ref)s in a transparent way, such that for these manifolds it's not
necessary to introduce explicit types for the points and tangent vectors, but they are
encapsulated/stripped automatically when needed.
This manifold is a decorator for a manifold, i.e. it decorates a [`AbstractManifold`](@ref) `M`
with types points, vectors, and covectors.
# Constructor
ValidationManifold(M::AbstractManifold; error::Symbol = :error)
Generate the Validation manifold, where `error` is used as the symbol passed to all checks.
This `:error`s by default but could also be set to `:warn` for example
"""
struct ValidationManifold{𝔽,M<:AbstractManifold{𝔽}} <: AbstractDecoratorManifold{𝔽}
manifold::M
mode::Symbol
end
function ValidationManifold(M::AbstractManifold; error::Symbol = :error)
return ValidationManifold(M, error)
end
"""
ValidationMPoint <: AbstractManifoldPoint
Represent a point on an [`ValidationManifold`](@ref), i.e. on a manifold where data can be
represented by arrays. The array is stored internally and semantically. This distinguished
the value from [`ValidationTVector`](@ref)s and [`ValidationCoTVector`](@ref)s.
"""
struct ValidationMPoint{V} <: AbstractManifoldPoint
value::V
end
"""
ValidationFibreVector{TType<:VectorSpaceType} <: AbstractFibreVector{TType}
Represent a tangent vector to a point on an [`ValidationManifold`](@ref), i.e. on a manifold
where data can be represented by arrays. The array is stored internally and semantically.
This distinguished the value from [`ValidationMPoint`](@ref)s vectors of other types.
"""
struct ValidationFibreVector{TType<:VectorSpaceType,V} <: AbstractFibreVector{TType}
value::V
end
function ValidationFibreVector{TType}(value::V) where {TType,V}
return ValidationFibreVector{TType,V}(value)
end
"""
ValidationTVector = ValidationFibreVector{TangentSpaceType}
Represent a tangent vector to a point on an [`ValidationManifold`](@ref), i.e. on a manifold
where data can be represented by arrays. The array is stored internally and semantically.
This distinguished the value from [`ValidationMPoint`](@ref)s vectors of other types.
"""
const ValidationTVector = ValidationFibreVector{TangentSpaceType}
"""
ValidationCoTVector = ValidationFibreVector{CotangentSpaceType}
Represent a cotangent vector to a point on an [`ValidationManifold`](@ref), i.e. on a manifold
where data can be represented by arrays. The array is stored internally and semantically.
This distinguished the value from [`ValidationMPoint`](@ref)s vectors of other types.
"""
const ValidationCoTVector = ValidationFibreVector{CotangentSpaceType}
@eval @manifold_vector_forwards ValidationFibreVector{TType} TType value
@eval @manifold_element_forwards ValidationMPoint value
@inline function active_traits(f, ::ValidationManifold, ::Any...)
return merge_traits(IsExplicitDecorator())
end
"""
array_value(p)
Return the internal array value of an [`ValidationMPoint`](@ref), [`ValidationTVector`](@ref), or
[`ValidationCoTVector`](@ref) if the value `p` is encapsulated as such. Return `p` if it is
already an array.
"""
array_value(p::AbstractArray) = p
array_value(p::ValidationMPoint) = p.value
array_value(X::ValidationFibreVector) = X.value
decorated_manifold(M::ValidationManifold) = M.manifold
convert(::Type{M}, m::ValidationManifold{𝔽,M}) where {𝔽,M<:AbstractManifold{𝔽}} = m.manifold
function convert(::Type{ValidationManifold{𝔽,M}}, m::M) where {𝔽,M<:AbstractManifold{𝔽}}
return ValidationManifold(m)
end
convert(::Type{V}, p::ValidationMPoint{V}) where {V<:AbstractArray} = p.value
function convert(::Type{ValidationMPoint{V}}, x::V) where {V<:AbstractArray}
return ValidationMPoint{V}(x)
end
function convert(
::Type{V},
X::ValidationFibreVector{TType,V},
) where {TType,V<:AbstractArray}
return X.value
end
function convert(
::Type{ValidationFibreVector{TType,V}},
X::V,
) where {TType,V<:AbstractArray}
return ValidationFibreVector{TType,V}(X)
end
function copyto!(M::ValidationManifold, q::ValidationMPoint, p::ValidationMPoint; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
copyto!(M.manifold, q.value, p.value)
is_point(M, q; error = M.mode, kwargs...)
return q
end
function copyto!(
M::ValidationManifold,
Y::ValidationFibreVector{TType},
p::ValidationMPoint,
X::ValidationFibreVector{TType};
kwargs...,
) where {TType}
is_point(M, p; error = M.mode, kwargs...)
copyto!(M.manifold, Y.value, p.value, X.value)
return p
end
function distance(M::ValidationManifold, p, q; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
is_point(M, q; error = M.mode, kwargs...)
return distance(M.manifold, array_value(p), array_value(q))
end
function exp(M::ValidationManifold, p, X; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
is_vector(M, p, X; error = M.mode, kwargs...)
y = exp(M.manifold, array_value(p), array_value(X))
is_point(M, y; error = M.mode, kwargs...)
return ValidationMPoint(y)
end
function exp!(M::ValidationManifold, q, p, X; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
is_vector(M, p, X; error = M.mode, kwargs...)
exp!(M.manifold, array_value(q), array_value(p), array_value(X))
is_point(M, q; error = M.mode, kwargs...)
return q
end
function get_basis(M::ValidationManifold, p, B::AbstractBasis; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
Ξ = get_basis(M.manifold, array_value(p), B)
bvectors = get_vectors(M, p, Ξ)
N = length(bvectors)
if N != manifold_dimension(M.manifold)
throw(
ErrorException(
"For a basis of the tangent space at $(p) of $(M.manifold), $(manifold_dimension(M)) vectors are required, but get_basis $(B) computed $(N)",
),
)
end
# check that the vectors are linearly independent\
bv_rank = rank(reduce(hcat, bvectors))
if N != bv_rank
throw(
ErrorException(
"For a basis of the tangent space at $(p) of $(M.manifold), $(manifold_dimension(M)) linearly independent vectors are required, but get_basis $(B) computed $(bv_rank)",
),
)
end
map(X -> is_vector(M, p, X; error = M.mode, kwargs...), bvectors)
return Ξ
end
function get_basis(
M::ValidationManifold,
p,
B::Union{AbstractOrthogonalBasis,CachedBasis{𝔽,<:AbstractOrthogonalBasis{𝔽}} where {𝔽}};
kwargs...,
)
is_point(M, p; error = M.mode, kwargs...)
Ξ = invoke(get_basis, Tuple{ValidationManifold,Any,AbstractBasis}, M, p, B; kwargs...)
bvectors = get_vectors(M, p, Ξ)
N = length(bvectors)
for i in 1:N
for j in (i + 1):N
dot_val = real(inner(M, p, bvectors[i], bvectors[j]))
if !isapprox(dot_val, 0; atol = eps(eltype(p)))
throw(
ArgumentError(
"vectors number $i and $j are not orthonormal (inner product = $dot_val)",
),
)
end
end
end
return Ξ
end
function get_basis(
M::ValidationManifold,
p,
B::Union{
AbstractOrthonormalBasis,
<:CachedBasis{𝔽,<:AbstractOrthonormalBasis{𝔽}} where {𝔽},
};
kwargs...,
)
is_point(M, p; error = M.mode, kwargs...)
get_basis_invoke_types = Tuple{
ValidationManifold,
Any,
Union{
AbstractOrthogonalBasis,
CachedBasis{𝔽2,<:AbstractOrthogonalBasis{𝔽2}},
} where {𝔽2},
}
Ξ = invoke(get_basis, get_basis_invoke_types, M, p, B; kwargs...)
bvectors = get_vectors(M, p, Ξ)
N = length(bvectors)
for i in 1:N
Xi_norm = norm(M, p, bvectors[i])
if !isapprox(Xi_norm, 1)
throw(ArgumentError("vector number $i is not normalized (norm = $Xi_norm)"))
end
end
return Ξ
end
function get_coordinates(M::ValidationManifold, p, X, B::AbstractBasis; kwargs...)
is_point(M, p; error = :error, kwargs...)
is_vector(M, p, X; error = :error, kwargs...)
return get_coordinates(M.manifold, p, X, B)
end
function get_coordinates!(M::ValidationManifold, Y, p, X, B::AbstractBasis; kwargs...)
is_vector(M, p, X; error = M.mode, kwargs...)
get_coordinates!(M.manifold, Y, p, X, B)
return Y
end
function get_vector(M::ValidationManifold, p, X, B::AbstractBasis; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
size(X) == (manifold_dimension(M),) || error("Incorrect size of coefficient vector X")
Y = get_vector(M.manifold, p, X, B)
size(Y) == representation_size(M) || error("Incorrect size of tangent vector Y")
return Y
end
function get_vector!(M::ValidationManifold, Y, p, X, B::AbstractBasis; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
size(X) == (manifold_dimension(M),) || error("Incorrect size of coefficient vector X")
get_vector!(M.manifold, Y, p, X, B)
size(Y) == representation_size(M) || error("Incorrect size of tangent vector Y")
return Y
end
injectivity_radius(M::ValidationManifold) = injectivity_radius(M.manifold)
function injectivity_radius(M::ValidationManifold, method::AbstractRetractionMethod)
return injectivity_radius(M.manifold, method)
end
function injectivity_radius(M::ValidationManifold, p; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
return injectivity_radius(M.manifold, array_value(p))
end
function injectivity_radius(
M::ValidationManifold,
p,
method::AbstractRetractionMethod;
kwargs...,
)
is_point(M, p; error = M.mode, kwargs...)
return injectivity_radius(M.manifold, array_value(p), method)
end
function inner(M::ValidationManifold, p, X, Y; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
is_vector(M, p, X; error = M.mode, kwargs...)
is_vector(M, p, Y; error = M.mode, kwargs...)
return inner(M.manifold, array_value(p), array_value(X), array_value(Y))
end
function is_point(M::ValidationManifold, p; kw...)
return is_point(M.manifold, array_value(p); kw...)
end
function is_vector(M::ValidationManifold, p, X, cbp::Bool = true; kw...)
return is_vector(M.manifold, array_value(p), array_value(X), cbp; kw...)
end
function isapprox(M::ValidationManifold, p, q; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
is_point(M, q; error = M.mode, kwargs...)
return isapprox(M.manifold, array_value(p), array_value(q); kwargs...)
end
function isapprox(M::ValidationManifold, p, X, Y; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
is_vector(M, p, X; error = M.mode, kwargs...)
is_vector(M, p, Y; error = M.mode, kwargs...)
return isapprox(M.manifold, array_value(p), array_value(X), array_value(Y); kwargs...)
end
function log(M::ValidationManifold, p, q; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
is_point(M, q; error = M.mode, kwargs...)
X = log(M.manifold, array_value(p), array_value(q))
is_vector(M, p, X; error = M.mode, kwargs...)
return ValidationTVector(X)
end
function log!(M::ValidationManifold, X, p, q; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
is_point(M, q; error = M.mode, kwargs...)
log!(M.manifold, array_value(X), array_value(p), array_value(q))
is_vector(M, p, X; error = M.mode, kwargs...)
return X
end
function mid_point(M::ValidationManifold, p1, p2; kwargs...)
is_point(M, p1; error = M.mode, kwargs...)
is_point(M, p2; error = M.mode, kwargs...)
q = mid_point(M.manifold, array_value(p1), array_value(p2))
is_point(M, q; error = M.mode, kwargs...)
return q
end
function mid_point!(M::ValidationManifold, q, p1, p2; kwargs...)
is_point(M, p1; error = M.mode, kwargs...)
is_point(M, p2; error = M.mode, kwargs...)
mid_point!(M.manifold, array_value(q), array_value(p1), array_value(p2))
is_point(M, q; error = M.mode, kwargs...)
return q
end
number_eltype(::Type{ValidationMPoint{V}}) where {V} = number_eltype(V)
number_eltype(::Type{ValidationFibreVector{TType,V}}) where {TType,V} = number_eltype(V)
function project!(M::ValidationManifold, Y, p, X; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
project!(M.manifold, array_value(Y), array_value(p), array_value(X))
is_vector(M, p, Y; error = M.mode, kwargs...)
return Y
end
function vector_transport_along(
M::ValidationManifold,
p,
X,
c::AbstractVector,
m::AbstractVectorTransportMethod;
kwargs...,
)
is_vector(M, p, X; error = M.mode, kwargs...)
Y = vector_transport_along(M.manifold, array_value(p), array_value(X), c, m)
is_vector(M, c[end], Y; error = M.mode, kwargs...)
return Y
end
function vector_transport_along!(
M::ValidationManifold,
Y,
p,
X,
c::AbstractVector,
m::AbstractVectorTransportMethod;
kwargs...,
)
is_vector(M, p, X; error = M.mode, kwargs...)
vector_transport_along!(
M.manifold,
array_value(Y),
array_value(p),
array_value(X),
c,
m,
)
is_vector(M, c[end], Y; error = M.mode, kwargs...)
return Y
end
function vector_transport_to(
M::ValidationManifold,
p,
X,
q,
m::AbstractVectorTransportMethod;
kwargs...,
)
is_point(M, q; error = M.mode, kwargs...)
is_vector(M, p, X; error = M.mode, kwargs...)
Y = vector_transport_to(M.manifold, array_value(p), array_value(X), array_value(q), m)
is_vector(M, q, Y; error = M.mode, kwargs...)
return Y
end
function vector_transport_to!(
M::ValidationManifold,
Y,
p,
X,
q,
m::AbstractVectorTransportMethod;
kwargs...,
)
is_point(M, q; error = M.mode, kwargs...)
is_vector(M, p, X; error = M.mode, kwargs...)
vector_transport_to!(
M.manifold,
array_value(Y),
array_value(p),
array_value(X),
array_value(q),
m,
)
is_vector(M, q, Y; error = M.mode, kwargs...)
return Y
end
function zero_vector(M::ValidationManifold, p; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
w = zero_vector(M.manifold, array_value(p))
is_vector(M, p, w; error = M.mode, kwargs...)
return w
end
function zero_vector!(M::ValidationManifold, X, p; kwargs...)
is_point(M, p; error = M.mode, kwargs...)
zero_vector!(M.manifold, array_value(X), array_value(p); kwargs...)
is_vector(M, p, X; error = M.mode, kwargs...)
return X
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 408 |
"""
VectorSpaceFiber{𝔽,M,TSpaceType} = Fiber{𝔽,TSpaceType,M}
where {𝔽,M<:AbstractManifold{𝔽},TSpaceType<:VectorSpaceType}
Alias for a [`Fiber`](@ref) when the fiber is a vector space.
"""
const VectorSpaceFiber{𝔽,M,TSpaceType} =
Fiber{𝔽,TSpaceType,M} where {𝔽,M<:AbstractManifold{𝔽},TSpaceType<:VectorSpaceType}
LinearAlgebra.norm(M::VectorSpaceFiber, p, X) = norm(M.manifold, M.point, X)
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 3369 | @doc raw"""
AbstractApproximationMethod
Abstract type for defining estimation methods on manifolds.
"""
abstract type AbstractApproximationMethod end
@doc raw"""
GradientDescentEstimation <: AbstractApproximationMethod
Method for estimation using [📖 gradient descent](https://en.wikipedia.org/wiki/Gradient_descent).
"""
struct GradientDescentEstimation <: AbstractApproximationMethod end
@doc raw"""
CyclicProximalPointEstimation <: AbstractApproximationMethod
Method for estimation using the cyclic proximal point technique, which is based on [📖 proximal maps](https://en.wikipedia.org/wiki/Proximal_operator).
"""
struct CyclicProximalPointEstimation <: AbstractApproximationMethod end
@doc raw"""
EfficientEstimator <: AbstractApproximationMethod
Method for estimation in the best possible sense, see [📖 Efficiency (Statictsics)](https://en.wikipedia.org/wiki/Efficiency_(statistics)) for more details.
This can for example be used when computing the usual mean on an Euclidean space, which is the best estimator.
"""
struct EfficientEstimator <: AbstractApproximationMethod end
@doc raw"""
ExtrinsicEstimation{T} <: AbstractApproximationMethod
Method for estimation in the ambient space with a method of type `T` and projecting the result back
to the manifold.
"""
struct ExtrinsicEstimation{T<:AbstractApproximationMethod} <: AbstractApproximationMethod
extrinsic_estimation::T
end
@doc raw"""
WeiszfeldEstimation <: AbstractApproximationMethod
Method for estimation using the Weiszfeld algorithm, compare for example the computation of the
[📖 Geometric median](https://en.wikipedia.org/wiki/Geometric_median).
"""
struct WeiszfeldEstimation <: AbstractApproximationMethod end
@doc raw"""
GeodesicInterpolation <: AbstractApproximationMethod
Method for estimation based on geodesic interpolation.
"""
struct GeodesicInterpolation <: AbstractApproximationMethod end
@doc raw"""
GeodesicInterpolationWithinRadius{T} <: AbstractApproximationMethod
Method for estimation based on geodesic interpolation that is restricted to some `radius`
# Constructor
GeodesicInterpolationWithinRadius(radius::Real)
"""
struct GeodesicInterpolationWithinRadius{T<:Real} <: AbstractApproximationMethod
radius::T
function GeodesicInterpolationWithinRadius(radius::T) where {T<:Real}
radius > 0 && return new{T}(radius)
return throw(
DomainError("The radius must be strictly postive, received $(radius)."),
)
end
end
@doc raw"""
default_approximation_method(M::AbstractManifold, f)
default_approximation_method(M::AbtractManifold, f, T)
Specify a default estimation method for an [`AbstractManifold`](@ref) and a specific function `f`
and optionally as well a type `T` to distinguish different (point or vector) representations on `M`.
By default, all functions `f` call the signature for just a manifold.
The exceptional functions are:
* `retract` and `retract!` which fall back to [`default_retraction_method`](@ref)
* `inverse_retract` and `inverse_retract!` which fall back to [`default_inverse_retraction_method`](@ref)
* any of the vector transport mehods fall back to [`default_vector_transport_method`](@ref)
"""
default_approximation_method(M::AbstractManifold, f)
default_approximation_method(M::AbstractManifold, f, T) = default_approximation_method(M, f)
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 36759 | """
VectorSpaceType
Abstract type for tangent spaces, cotangent spaces, their tensor products,
exterior products, etc.
Every vector space `fiber` is supposed to provide:
* a method of constructing vectors,
* basic operations: addition, subtraction, multiplication by a scalar
and negation (unary minus),
* `zero_vector(fiber, p)` to construct zero vectors at point `p`,
* `allocate(X)` and `allocate(X, T)` for vector `X` and type `T`,
* `copyto!(X, Y)` for vectors `X` and `Y`,
* `number_eltype(v)` for vector `v`,
* [`vector_space_dimension`](@ref).
Optionally:
* inner product via `inner` (used to provide Riemannian metric on vector
bundles),
* [`flat`](https://juliamanifolds.github.io/Manifolds.jl/stable/features/atlases.html#Manifolds.flat-Tuple{AbstractManifold,%20Any,%20Any}) and [`sharp`](https://juliamanifolds.github.io/Manifolds.jl/stable/features/atlases.html#Manifolds.sharp-Tuple{AbstractManifold,%20Any,%20Any}),
* `norm` (by default uses `inner`),
* [`project`](@ref) (for embedded vector spaces),
* [`representation_size`](@ref),
* broadcasting for basic operations.
"""
abstract type VectorSpaceType <: FiberType end
"""
struct TangentSpaceType <: VectorSpaceType end
A type that indicates that a [`Fiber`](@ref) is a [`TangentSpace`](@ref).
"""
struct TangentSpaceType <: VectorSpaceType end
"""
struct CotangentSpaceType <: VectorSpaceType end
A type that indicates that a [`Fiber`](@ref) is a [`CotangentSpace`](@ref).
"""
struct CotangentSpaceType <: VectorSpaceType end
TCoTSpaceType = Union{TangentSpaceType,CotangentSpaceType}
"""
AbstractBasis{𝔽,VST<:VectorSpaceType}
Abstract type that represents a basis of vector space of type `VST` on a manifold or
a subset of it.
The type parameter `𝔽` denotes the [`AbstractNumbers`](@ref) that will be used
as coefficients in linear combinations of the basis vectors.
# See also
[`VectorSpaceType`](@ref)
"""
abstract type AbstractBasis{𝔽,VST<:VectorSpaceType} end
"""
DefaultBasis{𝔽,VST<:VectorSpaceType}
An arbitrary basis of vector space of type `VST` on a manifold. This will usually
be the fastest basis available for a manifold.
The type parameter `𝔽` denotes the [`AbstractNumbers`](@ref) that will be used
as coefficients in linear combinations of the basis vectors.
# See also
[`VectorSpaceType`](@ref)
"""
struct DefaultBasis{𝔽,VST<:VectorSpaceType} <: AbstractBasis{𝔽,VST}
vector_space::VST
end
function DefaultBasis(𝔽::AbstractNumbers = ℝ, vs::VectorSpaceType = TangentSpaceType())
return DefaultBasis{𝔽,typeof(vs)}(vs)
end
function DefaultBasis{𝔽}(vs::VectorSpaceType = TangentSpaceType()) where {𝔽}
return DefaultBasis{𝔽,typeof(vs)}(vs)
end
function DefaultBasis{𝔽,TangentSpaceType}() where {𝔽}
return DefaultBasis{𝔽,TangentSpaceType}(TangentSpaceType())
end
"""
AbstractOrthogonalBasis{𝔽,VST<:VectorSpaceType}
Abstract type that represents an orthonormal basis of vector space of type `VST` on a
manifold or a subset of it.
The type parameter `𝔽` denotes the [`AbstractNumbers`](@ref) that will be used
as coefficients in linear combinations of the basis vectors.
# See also
[`VectorSpaceType`](@ref)
"""
abstract type AbstractOrthogonalBasis{𝔽,VST<:VectorSpaceType} <: AbstractBasis{𝔽,VST} end
"""
DefaultOrthogonalBasis{𝔽,VST<:VectorSpaceType}
An arbitrary orthogonal basis of vector space of type `VST` on a manifold. This will usually
be the fastest orthogonal basis available for a manifold.
The type parameter `𝔽` denotes the [`AbstractNumbers`](@ref) that will be used
as coefficients in linear combinations of the basis vectors.
# See also
[`VectorSpaceType`](@ref)
"""
struct DefaultOrthogonalBasis{𝔽,VST<:VectorSpaceType} <: AbstractOrthogonalBasis{𝔽,VST}
vector_space::VST
end
function DefaultOrthogonalBasis(
𝔽::AbstractNumbers = ℝ,
vs::VectorSpaceType = TangentSpaceType(),
)
return DefaultOrthogonalBasis{𝔽,typeof(vs)}(vs)
end
function DefaultOrthogonalBasis{𝔽}(vs::VectorSpaceType = TangentSpaceType()) where {𝔽}
return DefaultOrthogonalBasis{𝔽,typeof(vs)}(vs)
end
function DefaultOrthogonalBasis{𝔽,TangentSpaceType}() where {𝔽}
return DefaultOrthogonalBasis{𝔽,TangentSpaceType}(TangentSpaceType())
end
struct VeeOrthogonalBasis{𝔽} <: AbstractOrthogonalBasis{𝔽,TangentSpaceType} end
VeeOrthogonalBasis(𝔽::AbstractNumbers = ℝ) = VeeOrthogonalBasis{𝔽}()
"""
AbstractOrthonormalBasis{𝔽,VST<:VectorSpaceType}
Abstract type that represents an orthonormal basis of vector space of type `VST` on a
manifold or a subset of it.
The type parameter `𝔽` denotes the [`AbstractNumbers`](@ref) that will be used
as coefficients in linear combinations of the basis vectors.
# See also
[`VectorSpaceType`](@ref)
"""
abstract type AbstractOrthonormalBasis{𝔽,VST<:VectorSpaceType} <:
AbstractOrthogonalBasis{𝔽,VST} end
"""
DefaultOrthonormalBasis(𝔽::AbstractNumbers = ℝ, vs::VectorSpaceType = TangentSpaceType())
An arbitrary orthonormal basis of vector space of type `VST` on a manifold. This will usually
be the fastest orthonormal basis available for a manifold.
The type parameter `𝔽` denotes the [`AbstractNumbers`](@ref) that will be used
as coefficients in linear combinations of the basis vectors.
# See also
[`VectorSpaceType`](@ref)
"""
struct DefaultOrthonormalBasis{𝔽,VST<:VectorSpaceType} <: AbstractOrthonormalBasis{𝔽,VST}
vector_space::VST
end
function DefaultOrthonormalBasis(
𝔽::AbstractNumbers = ℝ,
vs::VectorSpaceType = TangentSpaceType(),
)
return DefaultOrthonormalBasis{𝔽,typeof(vs)}(vs)
end
function DefaultOrthonormalBasis{𝔽}(vs::VectorSpaceType = TangentSpaceType()) where {𝔽}
return DefaultOrthonormalBasis{𝔽,typeof(vs)}(vs)
end
function DefaultOrthonormalBasis{𝔽,TangentSpaceType}() where {𝔽}
return DefaultOrthonormalBasis{𝔽,TangentSpaceType}(TangentSpaceType())
end
"""
ProjectedOrthonormalBasis(method::Symbol, 𝔽::AbstractNumbers = ℝ)
An orthonormal basis that comes from orthonormalization of basis vectors
of the ambient space projected onto the subspace representing the tangent space
at a given point.
The type parameter `𝔽` denotes the [`AbstractNumbers`](@ref) that will be used
as coefficients in linear combinations of the basis vectors.
Available methods:
- `:gram_schmidt` uses a modified Gram-Schmidt orthonormalization.
- `:svd` uses SVD decomposition to orthogonalize projected vectors.
The SVD-based method should be more numerically stable at the cost of
an additional assumption (local metric tensor at a point where the
basis is calculated has to be diagonal).
"""
struct ProjectedOrthonormalBasis{Method,𝔽} <: AbstractOrthonormalBasis{𝔽,TangentSpaceType} end
function ProjectedOrthonormalBasis(method::Symbol, 𝔽::AbstractNumbers = ℝ)
return ProjectedOrthonormalBasis{method,𝔽}()
end
@doc raw"""
GramSchmidtOrthonormalBasis{𝔽} <: AbstractOrthonormalBasis{𝔽}
An orthonormal basis obtained from a basis.
# Constructor
GramSchmidtOrthonormalBasis(𝔽::AbstractNumbers = ℝ)
"""
struct GramSchmidtOrthonormalBasis{𝔽} <: AbstractOrthonormalBasis{𝔽,TangentSpaceType} end
GramSchmidtOrthonormalBasis(𝔽::AbstractNumbers = ℝ) = GramSchmidtOrthonormalBasis{𝔽}()
@doc raw"""
DiagonalizingOrthonormalBasis{𝔽,TV} <: AbstractOrthonormalBasis{𝔽,TangentSpaceType}
An orthonormal basis `Ξ` as a vector of tangent vectors (of length determined by
[`manifold_dimension`](@ref)) in the tangent space that diagonalizes the curvature
tensor ``R(u,v)w`` and where the direction `frame_direction` ``v`` has curvature `0`.
The type parameter `𝔽` denotes the [`AbstractNumbers`](@ref) that will be used
as coefficients in linear combinations of the basis vectors.
# Constructor
DiagonalizingOrthonormalBasis(frame_direction, 𝔽::AbstractNumbers = ℝ)
"""
struct DiagonalizingOrthonormalBasis{𝔽,TV} <: AbstractOrthonormalBasis{𝔽,TangentSpaceType}
frame_direction::TV
end
function DiagonalizingOrthonormalBasis(X, 𝔽::AbstractNumbers = ℝ)
return DiagonalizingOrthonormalBasis{𝔽,typeof(X)}(X)
end
struct DiagonalizingBasisData{D,V,ET}
frame_direction::D
eigenvalues::ET
vectors::V
end
const DefaultOrDiagonalizingBasis{𝔽} =
Union{DefaultOrthonormalBasis{𝔽,TangentSpaceType},DiagonalizingOrthonormalBasis{𝔽}}
"""
CachedBasis{𝔽,V,<:AbstractBasis{𝔽}} <: AbstractBasis{𝔽}
A cached version of the given `basis` with precomputed basis vectors. The basis vectors
are stored in `data`, either explicitly (like in cached variants of
[`ProjectedOrthonormalBasis`](@ref)) or implicitly.
# Constructor
CachedBasis(basis::AbstractBasis, data)
"""
struct CachedBasis{𝔽,B,V} <:
AbstractBasis{𝔽,TangentSpaceType} where {B<:AbstractBasis{𝔽,TangentSpaceType},V}
data::V
end
function CachedBasis(::B, data::V) where {V,𝔽,B<:AbstractBasis{𝔽,<:TangentSpaceType}}
return CachedBasis{𝔽,B,V}(data)
end
function CachedBasis(basis::CachedBasis) # avoid double encapsulation
return basis
end
function CachedBasis(
basis::DiagonalizingOrthonormalBasis,
eigenvalues::ET,
vectors::T,
) where {ET<:AbstractVector,T<:AbstractVector}
data = DiagonalizingBasisData(basis.frame_direction, eigenvalues, vectors)
return CachedBasis(basis, data)
end
# forward declarations
function get_coordinates end
function get_vector end
const all_uncached_bases{T} = Union{
AbstractBasis{<:Any,T},
DefaultBasis{<:Any,T},
DefaultOrthogonalBasis{<:Any,T},
DefaultOrthonormalBasis{<:Any,T},
}
function allocate_on(M::AbstractManifold, ::TangentSpaceType)
return similar(Array{Float64}, representation_size(M))
end
function allocate_on(M::AbstractManifold, ::TangentSpaceType, T::Type{<:AbstractArray})
return similar(T, representation_size(M))
end
"""
allocate_coordinates(M::AbstractManifold, p, T, n::Int)
Allocate vector of coordinates of length `n` of type `T` of a vector at point `p`
on manifold `M`.
"""
allocate_coordinates(::AbstractManifold, p, T, n::Int) = allocate(p, T, n)
function allocate_coordinates(M::AbstractManifold, p::Int, T, n::Int)
return (representation_size(M) == () && n == 0) ? zero(T) : zeros(T, n)
end
function allocate_result(
M::AbstractManifold,
f::typeof(get_coordinates),
p,
X,
basis::AbstractBasis{𝔽},
) where {𝔽}
T = coordinate_eltype(M, p, 𝔽)
return allocate_coordinates(M, p, T, number_of_coordinates(M, basis))
end
@inline function allocate_result_type(
M::AbstractManifold,
f::typeof(get_vector),
args::Tuple{Any,Vararg{Any}},
)
apf = allocation_promotion_function(M, f, args)
return apf(
invoke(allocate_result_type, Tuple{AbstractManifold,Any,typeof(args)}, M, f, args),
)
end
"""
allocation_promotion_function(M::AbstractManifold, f, args::Tuple)
Determine the function that must be used to ensure that the allocated representation is of
the right type. This is needed for [`get_vector`](@ref) when a point on a complex manifold
is represented by a real-valued vectors with a real-coefficient basis, so that
a complex-valued vector representation is allocated.
"""
allocation_promotion_function(M::AbstractManifold, f, args::Tuple) = identity
"""
change_basis(M::AbstractManifold, p, c, B_in::AbstractBasis, B_out::AbstractBasis)
Given a vector with coordinates `c` at point `p` from manifold `M` in basis `B_in`,
compute coordinates of the same vector in basis `B_out`.
"""
function change_basis(M::AbstractManifold, p, c, B_in::AbstractBasis, B_out::AbstractBasis)
return get_coordinates(M, p, get_vector(M, p, c, B_in), B_out)
end
function change_basis!(
M::AbstractManifold,
c_out,
p,
c,
B_in::AbstractBasis,
B_out::AbstractBasis,
)
return get_coordinates!(M, c_out, p, get_vector(M, p, c, B_in), B_out)
end
function combine_allocation_promotion_functions(f::T, ::T) where {T}
return f
end
function combine_allocation_promotion_functions(::typeof(complex), ::typeof(identity))
return complex
end
function combine_allocation_promotion_functions(::typeof(identity), ::typeof(complex))
return complex
end
"""
coordinate_eltype(M::AbstractManifold, p, 𝔽::AbstractNumbers)
Get the element type for 𝔽-field coordinates of the tangent space at a point `p` from
manifold `M`. This default assumes that usually complex bases of complex manifolds have
real coordinates but it can be overridden by a more specific method.
"""
@inline function coordinate_eltype(::AbstractManifold, p, 𝔽::ComplexNumbers)
return complex(float(number_eltype(p)))
end
@inline function coordinate_eltype(::AbstractManifold, p, ::RealNumbers)
return real(float(number_eltype(p)))
end
@doc raw"""
dual_basis(M::AbstractManifold, p, B::AbstractBasis)
Get the dual basis to `B`, a basis of a vector space at point `p` from manifold `M`.
The dual to the ``i``th vector ``v_i`` from basis `B` is a vector ``v^i`` from the dual space
such that ``v^i(v_j) = δ^i_j``, where ``δ^i_j`` is the Kronecker delta symbol:
````math
δ^i_j = \begin{cases}
1 & \text{ if } i=j, \\
0 & \text{ otherwise.}
\end{cases}
````
"""
dual_basis(M::AbstractManifold, p, B::AbstractBasis) = _dual_basis(M, p, B)
function _dual_basis(
::AbstractManifold,
p,
::DefaultOrthonormalBasis{𝔽,TangentSpaceType},
) where {𝔽}
return DefaultOrthonormalBasis{𝔽}(CotangentSpaceType())
end
function _dual_basis(
::AbstractManifold,
p,
::DefaultOrthonormalBasis{𝔽,CotangentSpaceType},
) where {𝔽}
return DefaultOrthonormalBasis{𝔽}(TangentSpaceType())
end
# if `p` has complex eltype but you'd like to have real basis vectors,
# you can pass `real` as a third argument to get that
function _euclidean_basis_vector(p::StridedArray, i, eltype_transform = identity)
X = zeros(eltype_transform(eltype(p)), size(p)...)
X[i] = 1
return X
end
function _euclidean_basis_vector(p, i, eltype_transform = identity)
# when p is for example a SArray
X = similar(p, eltype_transform(eltype(p)))
fill!(X, zero(eltype(X)))
X[i] = 1
return X
end
"""
get_basis(M::AbstractManifold, p, B::AbstractBasis; kwargs...) -> CachedBasis
Compute the basis vectors of the tangent space at a point on manifold `M`
represented by `p`.
Returned object derives from [`AbstractBasis`](@ref) and may have a field `.vectors`
that stores tangent vectors or it may store them implicitly, in which case
the function [`get_vectors`](@ref) needs to be used to retrieve the basis vectors.
See also: [`get_coordinates`](@ref), [`get_vector`](@ref)
"""
function get_basis(M::AbstractManifold, p, B::AbstractBasis; kwargs...)
return _get_basis(M, p, B; kwargs...)
end
function _get_basis(::AbstractManifold, ::Any, B::CachedBasis)
return B
end
function _get_basis(M::AbstractManifold, p, B::ProjectedOrthonormalBasis{:svd,ℝ})
S = representation_size(M)
PS = prod(S)
dim = manifold_dimension(M)
# projection
# TODO: find a better way to obtain a basis of the ambient space
Xs = [
convert(Vector, reshape(project(M, p, _euclidean_basis_vector(p, i)), PS)) for
i in eachindex(p)
]
O = reduce(hcat, Xs)
# orthogonalization
# TODO: try using rank-revealing QR here
decomp = svd(O)
rotated = Diagonal(decomp.S) * decomp.Vt
vecs = [collect(reshape(rotated[i, :], S)) for i in 1:dim]
# normalization
for i in 1:dim
i_norm = norm(M, p, vecs[i])
vecs[i] /= i_norm
end
return CachedBasis(B, vecs)
end
function _get_basis(
M::AbstractManifold,
p,
B::ProjectedOrthonormalBasis{:gram_schmidt,ℝ};
kwargs...,
)
E = [project(M, p, _euclidean_basis_vector(p, i)) for i in eachindex(p)]
V = gram_schmidt(M, p, E; kwargs...)
return CachedBasis(B, V)
end
function _get_basis(M::AbstractManifold, p, B::VeeOrthogonalBasis)
return get_basis_vee(M, p, number_system(B))
end
function get_basis_vee(M::AbstractManifold, p, N)
return get_basis(M, p, DefaultOrthogonalBasis(N))
end
function _get_basis(M::AbstractManifold, p, B::DefaultBasis)
return get_basis_default(M, p, number_system(B))
end
function get_basis_default(M::AbstractManifold, p, N)
return get_basis(M, p, DefaultOrthogonalBasis(N))
end
function _get_basis(M::AbstractManifold, p, B::DefaultOrthogonalBasis)
return get_basis_orthogonal(M, p, number_system(B))
end
function get_basis_orthogonal(M::AbstractManifold, p, N)
return get_basis(M, p, DefaultOrthonormalBasis(N))
end
function _get_basis(M::AbstractManifold, p, B::DiagonalizingOrthonormalBasis)
return get_basis_diagonalizing(M, p, B)
end
function get_basis_diagonalizing end
function _get_basis(M::AbstractManifold, p, B::DefaultOrthonormalBasis)
return get_basis_orthonormal(M, p, number_system(B))
end
function get_basis_orthonormal(M::AbstractManifold, p, N::AbstractNumbers; kwargs...)
B = DefaultOrthonormalBasis(N)
dim = number_of_coordinates(M, B)
Eltp = coordinate_eltype(M, p, N)
p0 = zero(Eltp)
p1 = one(Eltp)
return CachedBasis(
B,
[get_vector(M, p, [ifelse(i == j, p1, p0) for j in 1:dim], B) for i in 1:dim],
)
end
@doc raw"""
get_coordinates(M::AbstractManifold, p, X, B::AbstractBasis)
get_coordinates(M::AbstractManifold, p, X, B::CachedBasis)
Compute a one-dimensional vector of coefficients of the tangent vector `X`
at point denoted by `p` on manifold `M` in basis `B`.
Depending on the basis, `p` may not directly represent a point on the manifold.
For example if a basis transported along a curve is used, `p` may be the coordinate
along the curve. If a [`CachedBasis`](@ref) is provided, their stored vectors are used,
otherwise the user has to provide a method to compute the coordinates.
For the [`CachedBasis`](@ref) keep in mind that the reconstruction with [`get_vector`](@ref)
requires either a dual basis or the cached basis to be selfdual, for example orthonormal
See also: [`get_vector`](@ref), [`get_basis`](@ref)
"""
function get_coordinates(M::AbstractManifold, p, X, B::AbstractBasis)
return _get_coordinates(M, p, X, B)
end
function _get_coordinates(M::AbstractManifold, p, X, B::VeeOrthogonalBasis)
return get_coordinates_vee(M, p, X, number_system(B))
end
function get_coordinates_vee(M::AbstractManifold, p, X, N)
return get_coordinates(M, p, X, DefaultOrthogonalBasis(N))
end
function _get_coordinates(M::AbstractManifold, p, X, B::DefaultBasis)
return get_coordinates_default(M, p, X, number_system(B))
end
function get_coordinates_default(M::AbstractManifold, p, X, N::AbstractNumbers)
return get_coordinates(M, p, X, DefaultOrthogonalBasis(N))
end
function _get_coordinates(M::AbstractManifold, p, X, B::DefaultOrthogonalBasis)
return get_coordinates_orthogonal(M, p, X, number_system(B))
end
function get_coordinates_orthogonal(M::AbstractManifold, p, X, N)
return get_coordinates_orthonormal(M, p, X, N)
end
function _get_coordinates(M::AbstractManifold, p, X, B::DefaultOrthonormalBasis)
return get_coordinates_orthonormal(M, p, X, number_system(B))
end
function get_coordinates_orthonormal(M::AbstractManifold, p, X, N)
c = allocate_result(M, get_coordinates, p, X, DefaultOrthonormalBasis(N))
return get_coordinates_orthonormal!(M, c, p, X, N)
end
function _get_coordinates(M::AbstractManifold, p, X, B::DiagonalizingOrthonormalBasis)
return get_coordinates_diagonalizing(M, p, X, B)
end
function get_coordinates_diagonalizing(
M::AbstractManifold,
p,
X,
B::DiagonalizingOrthonormalBasis,
)
c = allocate_result(M, get_coordinates, p, X, B)
return get_coordinates_diagonalizing!(M, c, p, X, B)
end
function _get_coordinates(M::AbstractManifold, p, X, B::CachedBasis)
return get_coordinates_cached(M, number_system(M), p, X, B, number_system(B))
end
function get_coordinates_cached(
M::AbstractManifold,
::ComplexNumbers,
p,
X,
B::CachedBasis,
::ComplexNumbers,
)
return map(vb -> conj(inner(M, p, X, vb)), get_vectors(M, p, B))
end
function get_coordinates_cached(
M::AbstractManifold,
::𝔽,
p,
X,
C::CachedBasis,
::RealNumbers,
) where {𝔽}
return map(vb -> real(inner(M, p, X, vb)), get_vectors(M, p, C))
end
function get_coordinates!(M::AbstractManifold, Y, p, X, B::AbstractBasis)
return _get_coordinates!(M, Y, p, X, B)
end
function _get_coordinates!(M::AbstractManifold, Y, p, X, B::VeeOrthogonalBasis)
return get_coordinates_vee!(M, Y, p, X, number_system(B))
end
function get_coordinates_vee!(M::AbstractManifold, Y, p, X, N)
return get_coordinates!(M, Y, p, X, DefaultOrthogonalBasis(N))
end
function _get_coordinates!(M::AbstractManifold, Y, p, X, B::DefaultBasis)
return get_coordinates_default!(M, Y, p, X, number_system(B))
end
function get_coordinates_default!(M::AbstractManifold, Y, p, X, N)
return get_coordinates!(M, Y, p, X, DefaultOrthogonalBasis(N))
end
function _get_coordinates!(M::AbstractManifold, Y, p, X, B::DefaultOrthogonalBasis)
return get_coordinates_orthogonal!(M, Y, p, X, number_system(B))
end
function get_coordinates_orthogonal!(M::AbstractManifold, Y, p, X, N)
return get_coordinates!(M, Y, p, X, DefaultOrthonormalBasis(N))
end
function _get_coordinates!(M::AbstractManifold, Y, p, X, B::DefaultOrthonormalBasis)
return get_coordinates_orthonormal!(M, Y, p, X, number_system(B))
end
function get_coordinates_orthonormal! end
function _get_coordinates!(M::AbstractManifold, Y, p, X, B::DiagonalizingOrthonormalBasis)
return get_coordinates_diagonalizing!(M, Y, p, X, B)
end
function get_coordinates_diagonalizing! end
function _get_coordinates!(M::AbstractManifold, Y, p, X, B::CachedBasis)
return get_coordinates_cached!(M, number_system(M), Y, p, X, B, number_system(B))
end
function get_coordinates_cached!(
M::AbstractManifold,
::ComplexNumbers,
Y,
p,
X,
B::CachedBasis,
::ComplexNumbers,
)
map!(vb -> conj(inner(M, p, X, vb)), Y, get_vectors(M, p, B))
return Y
end
function get_coordinates_cached!(
M::AbstractManifold,
::𝔽,
Y,
p,
X,
C::CachedBasis,
::RealNumbers,
) where {𝔽}
map!(vb -> real(inner(M, p, X, vb)), Y, get_vectors(M, p, C))
return Y
end
"""
X = get_vector(M::AbstractManifold, p, c, B::AbstractBasis)
Convert a one-dimensional vector of coefficients in a basis `B` of
the tangent space at `p` on manifold `M` to a tangent vector `X` at `p`.
Depending on the basis, `p` may not directly represent a point on the manifold.
For example if a basis transported along a curve is used, `p` may be the coordinate
along the curve.
For the [`CachedBasis`](@ref) keep in mind that the reconstruction from [`get_coordinates`](@ref)
requires either a dual basis or the cached basis to be selfdual, for example orthonormal
See also: [`get_coordinates`](@ref), [`get_basis`](@ref)
"""
@inline function get_vector(M::AbstractManifold, p, c, B::AbstractBasis)
return _get_vector(M, p, c, B)
end
@inline function _get_vector(M::AbstractManifold, p, c, B::VeeOrthogonalBasis)
return get_vector_vee(M, p, c, number_system(B))
end
@inline function get_vector_vee(M::AbstractManifold, p, c, N)
return get_vector(M, p, c, DefaultOrthogonalBasis(N))
end
@inline function _get_vector(M::AbstractManifold, p, c, B::DefaultBasis)
return get_vector_default(M, p, c, number_system(B))
end
@inline function get_vector_default(M::AbstractManifold, p, c, N)
return get_vector(M, p, c, DefaultOrthogonalBasis(N))
end
@inline function _get_vector(M::AbstractManifold, p, c, B::DefaultOrthogonalBasis)
return get_vector_orthogonal(M, p, c, number_system(B))
end
@inline function get_vector_orthogonal(M::AbstractManifold, p, c, N)
return get_vector_orthonormal(M, p, c, N)
end
function _get_vector(M::AbstractManifold, p, c, B::DefaultOrthonormalBasis)
return get_vector_orthonormal(M, p, c, number_system(B))
end
function get_vector_orthonormal(M::AbstractManifold, p, c, N)
B = DefaultOrthonormalBasis(N)
Y = allocate_result(M, get_vector, p, c)
return get_vector!(M, Y, p, c, B)
end
@inline function _get_vector(M::AbstractManifold, p, c, B::DiagonalizingOrthonormalBasis)
return get_vector_diagonalizing(M, p, c, B)
end
function get_vector_diagonalizing(
M::AbstractManifold,
p,
c,
B::DiagonalizingOrthonormalBasis,
)
Y = allocate_result(M, get_vector, p, c)
return get_vector!(M, Y, p, c, B)
end
@inline function _get_vector(M::AbstractManifold, p, c, B::CachedBasis)
return get_vector_cached(M, p, c, B)
end
_get_vector_cache_broadcast(::Any) = Val(true)
function get_vector_cached(M::AbstractManifold, p, X, B::CachedBasis)
# quite convoluted but:
# 1) preserves the correct `eltype`
# 2) guarantees a reasonable array type `Y`
# (for example scalar * `SizedValidation` is an `SArray`)
bvectors = get_vectors(M, p, B)
if _get_vector_cache_broadcast(bvectors[1]) === Val(false)
Xt = X[1] * bvectors[1]
for i in 2:length(X)
copyto!(Xt, Xt + X[i] * bvectors[i])
end
else
Xt = X[1] .* bvectors[1]
for i in 2:length(X)
Xt .+= X[i] .* bvectors[i]
end
end
return Xt
end
@inline function get_vector!(M::AbstractManifold, Y, p, c, B::AbstractBasis)
return _get_vector!(M, Y, p, c, B)
end
@inline function _get_vector!(M::AbstractManifold, Y, p, c, B::VeeOrthogonalBasis)
return get_vector_vee!(M, Y, p, c, number_system(B))
end
@inline get_vector_vee!(M, Y, p, c, N) = get_vector!(M, Y, p, c, DefaultOrthogonalBasis(N))
@inline function _get_vector!(M::AbstractManifold, Y, p, c, B::DefaultBasis)
return get_vector_default!(M, Y, p, c, number_system(B))
end
@inline function get_vector_default!(M::AbstractManifold, Y, p, c, N)
return get_vector!(M, Y, p, c, DefaultOrthogonalBasis(N))
end
@inline function _get_vector!(M::AbstractManifold, Y, p, c, B::DefaultOrthogonalBasis)
return get_vector_orthogonal!(M, Y, p, c, number_system(B))
end
@inline function get_vector_orthogonal!(M::AbstractManifold, Y, p, c, N)
return get_vector!(M, Y, p, c, DefaultOrthonormalBasis(N))
end
@inline function _get_vector!(M::AbstractManifold, Y, p, c, B::DefaultOrthonormalBasis)
return get_vector_orthonormal!(M, Y, p, c, number_system(B))
end
function get_vector_orthonormal! end
@inline function _get_vector!(
M::AbstractManifold,
Y,
p,
c,
B::DiagonalizingOrthonormalBasis,
)
return get_vector_diagonalizing!(M, Y, p, c, B)
end
function get_vector_diagonalizing! end
@inline function _get_vector!(M::AbstractManifold, Y, p, c, B::CachedBasis)
return get_vector_cached!(M, Y, p, c, B)
end
function get_vector_cached!(M::AbstractManifold, Y, p, X, B::CachedBasis)
# quite convoluted but:
# 1) preserves the correct `eltype`
# 2) guarantees a reasonable array type `Y`
# (for example scalar * `SizedValidation` is an `SArray`)
bvectors = get_vectors(M, p, B)
return if _get_vector_cache_broadcast(bvectors[1]) === Val(false)
Xt = X[1] * bvectors[1]
copyto!(Y, Xt)
for i in 2:length(X)
copyto!(Y, Y + X[i] * bvectors[i])
end
return Y
else
Xt = X[1] .* bvectors[1]
copyto!(Y, Xt)
for i in 2:length(X)
Y .+= X[i] .* bvectors[i]
end
return Y
end
end
"""
get_vectors(M::AbstractManifold, p, B::AbstractBasis)
Get the basis vectors of basis `B` of the tangent space at point `p`.
"""
function get_vectors(M::AbstractManifold, p, B::AbstractBasis)
return _get_vectors(M, p, B)
end
function _get_vectors(::AbstractManifold, ::Any, B::CachedBasis)
return _get_vectors(B)
end
_get_vectors(B::CachedBasis{𝔽,<:AbstractBasis,<:AbstractArray}) where {𝔽} = B.data
function _get_vectors(B::CachedBasis{𝔽,<:AbstractBasis,<:DiagonalizingBasisData}) where {𝔽}
return B.data.vectors
end
@doc raw"""
gram_schmidt(M::AbstractManifold{𝔽}, p, B::AbstractBasis{𝔽}) where {𝔽}
gram_schmidt(M::AbstractManifold, p, V::AbstractVector)
Compute an ONB in the tangent space at `p` on the [`AbstractManifold`](@ref} `M` from either an
[`AbstractBasis`](@ref) basis ´B´ or a set of (at most) [`manifold_dimension`](@ref)`(M)`
many vectors.
Note that this method requires the manifold and basis to work on the same
[`AbstractNumbers`](@ref) `𝔽`, i.e. with real coefficients.
The method always returns a basis, i.e. linearly dependent vectors are removed.
# Keyword arguments
* `warn_linearly_dependent` (`false`) – warn if the basis vectors are not linearly
independent
* `skip_linearly_dependent` (`false`) – whether to just skip (`true`) a vector that
is linearly dependent to the previous ones or to stop (`false`, default) at that point
* `return_incomplete_set` (`false`) – throw an error if the resulting set of vectors is not
a basis but contains less vectors
further keyword arguments can be passed to set the accuracy of the independence test.
Especially `atol` is raised slightly by default to `atol = 5*1e-16`.
# Return value
When a set of vectors is orthonormalized a set of vectors is returned.
When an [`AbstractBasis`](@ref) is orthonormalized, a [`CachedBasis`](@ref) is returned.
"""
function gram_schmidt(
M::AbstractManifold{𝔽},
p,
B::AbstractBasis{𝔽};
warn_linearly_dependent = false,
return_incomplete_set = false,
skip_linearly_dependent = false,
kwargs...,
) where {𝔽}
V = gram_schmidt(
M,
p,
get_vectors(M, p, B);
warn_linearly_dependent = warn_linearly_dependent,
skip_linearly_dependent = skip_linearly_dependent,
return_incomplete_set = return_incomplete_set,
kwargs...,
)
return CachedBasis(GramSchmidtOrthonormalBasis(𝔽), V)
end
function gram_schmidt(
M::AbstractManifold,
p,
V::AbstractVector;
atol = eps(number_eltype(first(V))),
warn_linearly_dependent = false,
return_incomplete_set = false,
skip_linearly_dependent = false,
kwargs...,
)
N = length(V)
Ξ = empty(V)
dim = manifold_dimension(M)
N < dim && @warn "Input only has $(N) vectors, but manifold dimension is $(dim)."
@inbounds for n in 1:N
Ξₙ = copy(M, p, V[n])
for k in 1:length(Ξ)
Ξₙ .-= real(inner(M, p, Ξ[k], Ξₙ)) .* Ξ[k]
end
nrmΞₙ = norm(M, p, Ξₙ)
if isapprox(nrmΞₙ / dim, 0; atol = atol, kwargs...)
warn_linearly_dependent &&
@warn "Input vector $(n) lies in the span of the previous ones."
!skip_linearly_dependent && throw(
ErrorException("Input vector $(n) lies in the span of the previous ones."),
)
else
push!(Ξ, Ξₙ ./ nrmΞₙ)
end
if length(Ξ) == dim
(n < N) &&
@warn "More vectors ($(N)) entered than the dimension of the manifold ($dim). All vectors after the $n th ignored."
return Ξ
end
end
if return_incomplete_set # if we rech this point - length(Ξ) < dim
return Ξ
else
throw(
ErrorException(
"gram_schmidt found only $(length(Ξ)) orthonormal basis vectors, but manifold dimension is $(dim).",
),
)
end
end
@doc raw"""
hat(M::AbstractManifold, p, Xⁱ)
Given a basis ``e_i`` on the tangent space at a point `p` and tangent
component vector ``X^i ∈ ℝ``, compute the equivalent vector representation
``X=X^i e_i``, where Einstein summation notation is used:
````math
∧ : X^i ↦ X^i e_i
````
For array manifolds, this converts a vector representation of the tangent
vector to an array representation. The [`vee`](@ref) map is the `hat` map's
inverse.
"""
@inline hat(M::AbstractManifold, p, X) = get_vector(M, p, X, VeeOrthogonalBasis(ℝ))
@inline hat!(M::AbstractManifold, Y, p, X) = get_vector!(M, Y, p, X, VeeOrthogonalBasis(ℝ))
"""
number_of_coordinates(M::AbstractManifold, B::AbstractBasis)
number_of_coordinates(M::AbstractManifold, ::𝔾)
Compute the number of coordinates in basis of field type `𝔾` on a manifold `M`.
This also corresponds to the number of vectors represented by `B`,
or stored within `B` in case of a [`CachedBasis`](@ref).
"""
function number_of_coordinates(M::AbstractManifold, ::AbstractBasis{𝔾}) where {𝔾}
return number_of_coordinates(M, 𝔾)
end
function number_of_coordinates(M::AbstractManifold, f::𝔾) where {𝔾}
return div(manifold_dimension(M), real_dimension(f))
end
"""
number_system(::AbstractBasis)
The number system for the vectors of the given basis.
"""
number_system(::AbstractBasis{𝔽}) where {𝔽} = 𝔽
"""
requires_caching(B::AbstractBasis)
Return whether basis `B` can be used in [`get_vector`](@ref) and [`get_coordinates`](@ref)
without calling [`get_basis`](@ref) first.
"""
requires_caching(::AbstractBasis) = true
requires_caching(::CachedBasis) = false
requires_caching(::DefaultBasis) = false
requires_caching(::DefaultOrthogonalBasis) = false
requires_caching(::DefaultOrthonormalBasis) = false
function _show_basis_vector(io::IO, X; pre = "", head = "")
sX = sprint(show, "text/plain", X, context = io, sizehint = 0)
sX = replace(sX, '\n' => "\n$(pre)")
return print(io, head, pre, sX)
end
function _show_basis_vector_range(io::IO, Ξ, range; pre = "", sym = "E")
for i in range
_show_basis_vector(io, Ξ[i]; pre = pre, head = "\n$(sym)$(i) =\n")
end
return nothing
end
function _show_basis_vector_range_noheader(io::IO, Ξ; max_vectors = 4, pre = "", sym = "E")
nv = length(Ξ)
return if nv ≤ max_vectors
_show_basis_vector_range(io, Ξ, 1:nv; pre = " ", sym = " E")
else
halfn = div(max_vectors, 2)
_show_basis_vector_range(io, Ξ, 1:halfn; pre = " ", sym = " E")
print(io, "\n ⋮")
_show_basis_vector_range(io, Ξ, (nv - halfn + 1):nv; pre = " ", sym = " E")
end
end
function show(io::IO, ::DefaultBasis{𝔽}) where {𝔽}
return print(io, "DefaultBasis($(𝔽))")
end
function show(io::IO, ::DefaultOrthogonalBasis{𝔽}) where {𝔽}
return print(io, "DefaultOrthogonalBasis($(𝔽))")
end
function show(io::IO, ::DefaultOrthonormalBasis{𝔽}) where {𝔽}
return print(io, "DefaultOrthonormalBasis($(𝔽))")
end
function show(io::IO, ::GramSchmidtOrthonormalBasis{𝔽}) where {𝔽}
return print(io, "GramSchmidtOrthonormalBasis($(𝔽))")
end
function show(io::IO, ::ProjectedOrthonormalBasis{method,𝔽}) where {method,𝔽}
return print(io, "ProjectedOrthonormalBasis($(repr(method)), $(𝔽))")
end
function show(io::IO, ::MIME"text/plain", onb::DiagonalizingOrthonormalBasis)
println(
io,
"DiagonalizingOrthonormalBasis($(number_system(onb))) with eigenvalue 0 in direction:",
)
sk = sprint(show, "text/plain", onb.frame_direction, context = io, sizehint = 0)
sk = replace(sk, '\n' => "\n ")
return print(io, sk)
end
function show(
io::IO,
::MIME"text/plain",
B::CachedBasis{𝔽,T,D},
) where {𝔽,T<:AbstractBasis,D}
try
vectors = _get_vectors(B)
print(
io,
"Cached basis of type $T with $(length(vectors)) basis vector$(length(vectors) == 1 ? "" : "s"):",
)
return _show_basis_vector_range_noheader(
io,
vectors;
max_vectors = 4,
pre = " ",
sym = " E",
)
catch e
# in case _get_vectors(B) is not defined
print(io, "Cached basis of type $T")
end
end
function show(
io::IO,
::MIME"text/plain",
B::CachedBasis{𝔽,T,D},
) where {𝔽,T<:DiagonalizingOrthonormalBasis,D<:DiagonalizingBasisData}
vectors = _get_vectors(B)
nv = length(vectors)
sk = sprint(show, "text/plain", T(B.data.frame_direction), context = io, sizehint = 0)
sk = replace(sk, '\n' => "\n ")
print(io, sk)
println(io, "\nand $(nv) basis vector$(nv == 1 ? "" : "s").")
print(io, "Basis vectors:")
_show_basis_vector_range_noheader(io, vectors; max_vectors = 4, pre = " ", sym = " E")
println(io, "\nEigenvalues:")
sk = sprint(show, "text/plain", B.data.eigenvalues, context = io, sizehint = 0)
sk = replace(sk, '\n' => "\n ")
return print(io, ' ', sk)
end
@doc raw"""
vee(M::AbstractManifold, p, X)
Given a basis ``e_i`` on the tangent space at a point `p` and tangent
vector `X`, compute the vector components ``X^i ∈ ℝ``, such that ``X = X^i e_i``, where
Einstein summation notation is used:
````math
\vee : X^i e_i ↦ X^i
````
For array manifolds, this converts an array representation of the tangent
vector to a vector representation. The [`hat`](@ref) map is the `vee` map's
inverse.
"""
vee(M::AbstractManifold, p, X) = get_coordinates(M, p, X, VeeOrthogonalBasis(ℝ))
function vee!(M::AbstractManifold, Y, p, X)
return get_coordinates!(M, Y, p, X, VeeOrthogonalBasis(ℝ))
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 25422 | #
# Base pass-ons
#
manifold_dimension(M::AbstractDecoratorManifold) = manifold_dimension(base_manifold(M))
#
# Traits - each passed to a function that is properly documented
#
"""
IsEmbeddedManifold <: AbstractTrait
A trait to declare an [`AbstractManifold`](@ref) as an embedded manifold.
"""
struct IsEmbeddedManifold <: AbstractTrait end
"""
IsIsometricManifoldEmbeddedManifold <: AbstractTrait
A Trait to determine whether an [`AbstractDecoratorManifold`](@ref) `M` is
an isometrically embedded manifold.
It is a special case of the [`IsEmbeddedManifold`](@ref) trait, i.e. it has all properties of this trait.
Here, additionally, netric related functions like [`inner`](@ref) and [`norm`](@ref) are passed to the embedding
"""
struct IsIsometricEmbeddedManifold <: AbstractTrait end
parent_trait(::IsIsometricEmbeddedManifold) = IsEmbeddedManifold()
"""
IsEmbeddedSubmanifold <: AbstractTrait
A trait to determine whether an [`AbstractDecoratorManifold`](@ref) `M` is an embedded submanifold.
It is a special case of the [`IsIsometricEmbeddedManifold`](@ref) trait, i.e. it has all properties of
this trait.
In this trait, additionally to the isometric embedded manifold, all retractions, inverse retractions,
and vectors transports, especially [`exp`](@ref), [`log`](@ref), and [`parallel_transport_to`](@ref)
are passed to the embedding.
"""
struct IsEmbeddedSubmanifold <: AbstractTrait end
parent_trait(::IsEmbeddedSubmanifold) = IsIsometricEmbeddedManifold()
#
# Generic Decorator functions
@doc raw"""
decorated_manifold(M::AbstractDecoratorManifold)
For a manifold `M` that is decorated with some properties, this function returns
the manifold without that manifold, i.e. the manifold that _was decorated_.
"""
decorated_manifold(M::AbstractDecoratorManifold)
decorated_manifold(M::AbstractManifold) = M
@trait_function decorated_manifold(M::AbstractDecoratorManifold)
#
# Implemented Traits
function base_manifold(M::AbstractDecoratorManifold, depth::Val{N} = Val(-1)) where {N}
# end recursion I: depth is 0
N == 0 && return M
# end recursion II: M is equal to its decorated manifold (avoid stack overflow)
D = decorated_manifold(M)
M === D && return M
# indefinite many steps for negative values of M
N < 0 && return base_manifold(D, depth)
# reduce depth otherwise
return base_manifold(D, Val(N - 1))
end
#
# Embedded specifix functions.
"""
get_embedding(M::AbstractDecoratorManifold)
get_embedding(M::AbstractDecoratorManifold, p)
Specify the embedding of a manifold that has abstract decorators.
the embedding might depend on a point representation, where different point representations
are distinguished as subtypes of [`AbstractManifoldPoint`](@ref).
A unique or default representation might also just be an `AbstractArray`.
"""
get_embedding(M::AbstractDecoratorManifold, p) = get_embedding(M)
#
# -----------------------------------------------------------------------------------------
# This is one new function
# Introduction and default fallbacks could become a macro?
# Introduce trait
@inline function allocate_result(
M::AbstractDecoratorManifold,
f::TF,
x::Vararg{Any,N},
) where {TF,N}
return allocate_result(trait(allocate_result, M, f, x...), M, f, x...)
end
# disambiguation
@invoke_maker 1 AbstractManifold allocate_result(
M::AbstractDecoratorManifold,
f::typeof(get_coordinates),
p,
X,
B::AbstractBasis,
)
# Introduce fallback
@inline function allocate_result(
::EmptyTrait,
M::AbstractManifold,
f::TF,
x::Vararg{Any,N},
) where {TF,N}
return invoke(
allocate_result,
Tuple{AbstractManifold,typeof(f),typeof(x).parameters...},
M,
f,
x...,
)
end
# Introduce automatic forward
@inline function allocate_result(
t::TraitList,
M::AbstractManifold,
f::TF,
x::Vararg{Any,N},
) where {TF,N}
return allocate_result(next_trait(t), M, f, x...)
end
function allocate_result(
::TraitList{IsEmbeddedManifold},
M::AbstractDecoratorManifold,
f::typeof(embed),
x::Vararg{Any,N},
) where {N}
T = allocate_result_type(get_embedding(M, x[1]), f, x)
return allocate(M, x[1], T, representation_size(get_embedding(M, x[1])))
end
function allocate_result(
::TraitList{IsEmbeddedManifold},
M::AbstractDecoratorManifold,
f::typeof(project),
x::Vararg{Any,N},
) where {N}
T = allocate_result_type(get_embedding(M, x[1]), f, x)
return allocate(M, x[1], T, representation_size(M))
end
@inline function allocate_result(
::TraitList{IsExplicitDecorator},
M::AbstractDecoratorManifold,
f::TF,
x::Vararg{Any,N},
) where {TF,N}
return allocate_result(decorated_manifold(M), f, x...)
end
@trait_function change_metric(M::AbstractDecoratorManifold, G::AbstractMetric, X, p)
@trait_function change_metric!(M::AbstractDecoratorManifold, Y, G::AbstractMetric, X, p)
@trait_function change_representer(M::AbstractDecoratorManifold, G::AbstractMetric, X, p)
@trait_function change_representer!(
M::AbstractDecoratorManifold,
Y,
G::AbstractMetric,
X,
p,
)
# Introduce Deco Trait | automatic foward | fallback
@trait_function check_size(M::AbstractDecoratorManifold, p)
# Embedded
function check_size(::TraitList{IsEmbeddedManifold}, M::AbstractDecoratorManifold, p)
mpe = check_size(get_embedding(M, p), embed(M, p))
if mpe !== nothing
return ManifoldDomainError(
"$p is not a point on $M because it is not a valid point in its embedding.",
mpe,
)
end
return nothing
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function check_size(M::AbstractDecoratorManifold, p, X)
# Embedded
function check_size(::TraitList{IsEmbeddedManifold}, M::AbstractDecoratorManifold, p, X)
mpe = check_size(get_embedding(M, p), embed(M, p), embed(M, p, X))
if mpe !== nothing
return ManifoldDomainError(
"$X is not a tangent vector at $p on $M because it is not a valid tangent vector in its embedding.",
mpe,
)
end
return nothing
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function copyto!(M::AbstractDecoratorManifold, q, p)
@trait_function copyto!(M::AbstractDecoratorManifold, Y, p, X)
# Introduce Deco Trait | automatic foward | fallback
@trait_function embed(M::AbstractDecoratorManifold, p)
# EmbeddedManifold
function embed(::TraitList{IsEmbeddedManifold}, M::AbstractDecoratorManifold, p)
q = allocate_result(M, embed, p)
return embed!(M, q, p)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function embed!(M::AbstractDecoratorManifold, q, p)
# EmbeddedManifold
function embed!(::TraitList{IsEmbeddedManifold}, M::AbstractDecoratorManifold, q, p)
return copyto!(M, q, p)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function embed(M::AbstractDecoratorManifold, p, X)
# EmbeddedManifold
function embed(::TraitList{IsEmbeddedManifold}, M::AbstractDecoratorManifold, p, X)
q = allocate_result(M, embed, p, X)
return embed!(M, q, p, X)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function embed!(M::AbstractDecoratorManifold, Y, p, X)
# EmbeddedManifold
function embed!(::TraitList{IsEmbeddedManifold}, M::AbstractDecoratorManifold, Y, p, X)
return copyto!(M, Y, p, X)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function exp(M::AbstractDecoratorManifold, p, X)
@trait_function exp(M::AbstractDecoratorManifold, p, X, t::Number)
# EmbeddedSubManifold
function exp(::TraitList{IsEmbeddedSubmanifold}, M::AbstractDecoratorManifold, p, X)
return exp(get_embedding(M, p), p, X)
end
function exp(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
p,
X,
t::Number,
)
return exp(get_embedding(M, p), p, X, t)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function exp!(M::AbstractDecoratorManifold, q, p, X)
@trait_function exp!(M::AbstractDecoratorManifold, q, p, X, t::Number)
# EmbeddedSubManifold
function exp!(::TraitList{IsEmbeddedSubmanifold}, M::AbstractDecoratorManifold, q, p, X)
return exp!(get_embedding(M, p), q, p, X)
end
function exp!(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
q,
p,
X,
t::Number,
)
return exp!(get_embedding(M, p), q, p, X, t)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function get_basis(M::AbstractDecoratorManifold, p, B::AbstractBasis)
# Introduce Deco Trait | automatic foward | fallback
@trait_function get_coordinates(M::AbstractDecoratorManifold, p, X, B::AbstractBasis)
# Introduce Deco Trait | automatic foward | fallback
@trait_function get_coordinates!(M::AbstractDecoratorManifold, Y, p, X, B::AbstractBasis)
# Introduce Deco Trait | automatic foward | fallback
@trait_function get_vector(M::AbstractDecoratorManifold, p, c, B::AbstractBasis)
# Introduce Deco Trait | automatic foward | fallback
@trait_function get_vector!(M::AbstractDecoratorManifold, Y, p, c, B::AbstractBasis)
# Introduce Deco Trait | automatic foward | fallback
@trait_function get_vectors(M::AbstractDecoratorManifold, p, B::AbstractBasis)
@trait_function injectivity_radius(M::AbstractDecoratorManifold)
function injectivity_radius(
::TraitList{IsIsometricEmbeddedManifold},
M::AbstractDecoratorManifold,
)
return injectivity_radius(get_embedding(M))
end
@trait_function injectivity_radius(M::AbstractDecoratorManifold, p)
function injectivity_radius(
::TraitList{IsIsometricEmbeddedManifold},
M::AbstractDecoratorManifold,
p,
)
return injectivity_radius(get_embedding(M, p), p)
end
@trait_function injectivity_radius(
M::AbstractDecoratorManifold,
m::AbstractRetractionMethod,
)
function injectivity_radius(
::TraitList{IsIsometricEmbeddedManifold},
M::AbstractDecoratorManifold,
m::AbstractRetractionMethod,
)
return injectivity_radius(get_embedding(M), m)
end
@trait_function injectivity_radius(
M::AbstractDecoratorManifold,
p,
m::AbstractRetractionMethod,
)
function injectivity_radius(
::TraitList{IsIsometricEmbeddedManifold},
M::AbstractDecoratorManifold,
p,
m::AbstractRetractionMethod,
)
return injectivity_radius(get_embedding(M, p), p, m)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function inner(M::AbstractDecoratorManifold, p, X, Y)
# Isometric Embedded submanifold
function inner(
::TraitList{IsIsometricEmbeddedManifold},
M::AbstractDecoratorManifold,
p,
X,
Y,
)
return inner(get_embedding(M, p), p, X, Y)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function inverse_retract(
M::AbstractDecoratorManifold,
p,
q,
m::AbstractInverseRetractionMethod = default_inverse_retraction_method(M, typeof(p)),
)
# Transparent for Submanifolds
function inverse_retract(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
p,
q,
m::AbstractInverseRetractionMethod = default_inverse_retraction_method(M, typeof(p)),
)
return inverse_retract(get_embedding(M, p), p, q, m)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function inverse_retract!(M::AbstractDecoratorManifold, X, p, q)
@trait_function inverse_retract!(
M::AbstractDecoratorManifold,
X,
p,
q,
m::AbstractInverseRetractionMethod,
)
function inverse_retract!(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
X,
p,
q,
m::AbstractInverseRetractionMethod = default_inverse_retraction_method(M, typeof(p)),
)
return inverse_retract!(get_embedding(M, p), X, p, q, m)
end
@trait_function isapprox(M::AbstractDecoratorManifold, p, q; kwargs...)
@trait_function isapprox(M::AbstractDecoratorManifold, p, X, Y; kwargs...)
@trait_function is_flat(M::AbstractDecoratorManifold)
# Introduce Deco Trait | automatic foward | fallback
@trait_function is_point(M::AbstractDecoratorManifold, p; kwargs...)
# Embedded
function is_point(
::TraitList{IsEmbeddedManifold},
M::AbstractDecoratorManifold,
p;
error::Symbol = :none,
kwargs...,
)
# to be safe check_size first
es = check_size(M, p)
if es !== nothing
(error === :error) && throw(es)
s = "$(typeof(es)) with $(es)"
(error === :info) && @info s
(error === :warn) && @warn s
return false
end
try
pt = is_point(get_embedding(M, p), embed(M, p); error = error, kwargs...)
!pt && return false # no error thrown (deactivated) but returned false -> return false
catch e
if e isa DomainError || e isa AbstractManifoldDomainError
e = ManifoldDomainError(
"$p is not a point on $M because it is not a valid point in its embedding.",
e,
)
end
throw(e) #an error occured that we do not handle ourselves -> rethrow.
end
mpe = check_point(M, p; kwargs...)
if mpe !== nothing
(error === :error) && throw(mpe)
# else: collect and info showerror
io = IOBuffer()
showerror(io, mpe)
s = String(take!(io))
(error === :info) && @info s
(error === :warn) && @warn s
return false
end
return true
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function is_vector(M::AbstractDecoratorManifold, p, X, cbp::Bool = true; kwargs...)
# EmbeddedManifold
# I am not yet sure how to properly document this embedding behaviour here in a docstring.
function is_vector(
::TraitList{IsEmbeddedManifold},
M::AbstractDecoratorManifold,
p,
X,
check_base_point::Bool = true;
error::Symbol = :none,
kwargs...,
)
es = check_size(M, p, X)
if es !== nothing
(error === :error) && throw(es)
# else: collect and info showerror
io = IOBuffer()
showerror(io, es)
s = String(take!(io))
(error === :info) && @info s
(error === :warn) && @warn s
return false
end
if check_base_point
try
ep = is_point(M, p; error = error, kwargs...)
!ep && return false
catch e
if e isa DomainError || e isa AbstractManifoldDomainError
ManifoldDomainError(
"$X is not a tangent vector to $p on $M because $p is not a valid point on $p",
e,
)
end
throw(e)
end
end
try
tv = is_vector(
get_embedding(M, p),
embed(M, p),
embed(M, p, X),
check_base_point;
error = error,
kwargs...,
)
!tv && return false # no error thrown (deactivated) but returned false -> return false
catch e
if e isa DomainError || e isa AbstractManifoldDomainError
e = ManifoldDomainError(
"$X is not a tangent vector to $p on $M because it is not a valid tangent vector in its embedding.",
e,
)
end
throw(e)
end
# Check (additional) local stuff
mXe = check_vector(M, p, X; kwargs...)
mXe === nothing && return true
(error === :error) && throw(mXe)
# else: collect and info showerror
io = IOBuffer()
showerror(io, mXe)
s = String(take!(io))
(error === :info) && @info s
(error === :warn) && @warn s
return false
end
@trait_function norm(M::AbstractDecoratorManifold, p, X)
function norm(::TraitList{IsIsometricEmbeddedManifold}, M::AbstractDecoratorManifold, p, X)
return norm(get_embedding(M, p), p, X)
end
@trait_function log(M::AbstractDecoratorManifold, p, q)
function log(::TraitList{IsEmbeddedSubmanifold}, M::AbstractDecoratorManifold, p, q)
return log(get_embedding(M, p), p, q)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function log!(M::AbstractDecoratorManifold, X, p, q)
function log!(::TraitList{IsEmbeddedSubmanifold}, M::AbstractDecoratorManifold, X, p, q)
return log!(get_embedding(M, p), X, p, q)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function parallel_transport_along(
M::AbstractDecoratorManifold,
p,
X,
c::AbstractVector,
)
# EmbeddedSubManifold
function parallel_transport_along(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
p,
X,
c::AbstractVector,
)
return parallel_transport_along(get_embedding(M, p), p, X, c)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function parallel_transport_along!(
M::AbstractDecoratorManifold,
Y,
p,
X,
c::AbstractVector,
)
# EmbeddedSubManifold
function parallel_transport_along!(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
Y,
p,
X,
c::AbstractVector,
)
return parallel_transport_along!(get_embedding(M, p), Y, p, X, c)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function parallel_transport_direction(M::AbstractDecoratorManifold, p, X, q)
# EmbeddedSubManifold
function parallel_transport_direction(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
p,
X,
q,
)
return parallel_transport_direction(get_embedding(M, p), p, X, q)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function parallel_transport_direction!(M::AbstractDecoratorManifold, Y, p, X, q)
# EmbeddedSubManifold
function parallel_transport_direction!(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
Y,
p,
X,
q,
)
return parallel_transport_direction!(get_embedding(M, p), Y, p, X, q)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function parallel_transport_to(M::AbstractDecoratorManifold, p, X, q)
# EmbeddedSubManifold
function parallel_transport_to(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
p,
X,
q,
)
return parallel_transport_to(get_embedding(M, p), p, X, q)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function parallel_transport_to!(M::AbstractDecoratorManifold, Y, p, X, q)
# EmbeddedSubManifold
function parallel_transport_to!(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
Y,
p,
X,
q,
)
return parallel_transport_to!(get_embedding(M, p), Y, p, X, q)
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function project(M::AbstractDecoratorManifold, p)
# Introduce Deco Trait | automatic foward | fallback
@trait_function project!(M::AbstractDecoratorManifold, q, p)
# Introduce Deco Trait | automatic foward | fallback
@trait_function project(M::AbstractDecoratorManifold, p, X)
# Introduce Deco Trait | automatic foward | fallback
@trait_function project!(M::AbstractDecoratorManifold, Y, p, X)
@trait_function Random.rand(M::AbstractDecoratorManifold; kwargs...)
@trait_function Random.rand!(M::AbstractDecoratorManifold, p; kwargs...)
@trait_function Random.rand(rng::AbstractRNG, M::AbstractDecoratorManifold; kwargs...) :() 2
@trait_function Random.rand!(rng::AbstractRNG, M::AbstractDecoratorManifold, p; kwargs...) :() 2
# Introduce Deco Trait | automatic foward | fallback
@trait_function representation_size(M::AbstractDecoratorManifold) (no_empty,)
# Isometric Embedded submanifold
function representation_size(::TraitList{IsEmbeddedManifold}, M::AbstractDecoratorManifold)
return representation_size(get_embedding(M))
end
function representation_size(::EmptyTrait, M::AbstractDecoratorManifold)
return representation_size(decorated_manifold(M))
end
# Introduce Deco Trait | automatic foward | fallback
@trait_function retract(
M::AbstractDecoratorManifold,
p,
X,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
@trait_function retract(
M::AbstractDecoratorManifold,
p,
X,
t::Number,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
function retract(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
p,
X,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
return retract(get_embedding(M, p), p, X, m)
end
function retract(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
p,
X,
t::Number,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
return retract(get_embedding(M, p), p, X, t, m)
end
@trait_function retract!(
M::AbstractDecoratorManifold,
q,
p,
X,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
@trait_function retract!(
M::AbstractDecoratorManifold,
q,
p,
X,
t::Number,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
function retract!(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
q,
p,
X,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
return retract!(get_embedding(M, p), q, p, X, m)
end
function retract!(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
q,
p,
X,
t::Number,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
return retract!(get_embedding(M, p), q, p, X, t, m)
end
@trait_function vector_transport_along(
M::AbstractDecoratorManifold,
q,
p,
X,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
function vector_transport_along(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
p,
X,
c,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
return vector_transport_along(get_embedding(M, p), p, X, c, m)
end
@trait_function vector_transport_along!(
M::AbstractDecoratorManifold,
Y,
p,
X,
c::AbstractVector,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
function vector_transport_along!(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
Y,
p,
X,
c::AbstractVector,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
return vector_transport_along!(get_embedding(M, p), Y, p, X, c, m)
end
@trait_function vector_transport_direction(
M::AbstractDecoratorManifold,
p,
X,
d,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
function vector_transport_direction(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
p,
X,
d,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
return vector_transport_direction(get_embedding(M, p), p, X, d, m)
end
@trait_function vector_transport_direction!(
M::AbstractDecoratorManifold,
Y,
p,
X,
d,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
function vector_transport_direction!(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
Y,
p,
X,
d,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
return vector_transport_direction!(get_embedding(M, p), Y, p, X, d, m)
end
@trait_function vector_transport_to(
M::AbstractDecoratorManifold,
p,
X,
q,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
function vector_transport_to(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
p,
X,
q,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
return vector_transport_to(get_embedding(M, p), p, X, q, m)
end
@trait_function vector_transport_to!(
M::AbstractDecoratorManifold,
Y,
p,
X,
q,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
function vector_transport_to!(
::TraitList{IsEmbeddedSubmanifold},
M::AbstractDecoratorManifold,
Y,
p,
X,
q,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
return vector_transport_to!(get_embedding(M, p), Y, p, X, q, m)
end
@trait_function Weingarten(M::AbstractDecoratorManifold, p, X, V)
@trait_function Weingarten!(M::AbstractDecoratorManifold, Y, p, X, V)
@trait_function zero_vector(M::AbstractDecoratorManifold, p)
function zero_vector(::TraitList{IsEmbeddedManifold}, M::AbstractDecoratorManifold, p)
return zero_vector(get_embedding(M, p), p)
end
@trait_function zero_vector!(M::AbstractDecoratorManifold, X, p)
function zero_vector!(::TraitList{IsEmbeddedManifold}, M::AbstractDecoratorManifold, X, p)
return zero_vector!(get_embedding(M, p), X, p)
end
# Trait recursion breaking
# An unfortunate consequence of Julia's method recursion limitations
# Add more traits and functions as needed
for trait_type in [TraitList{IsEmbeddedManifold}, TraitList{IsEmbeddedSubmanifold}]
@eval begin
@next_trait_function $trait_type isapprox(
M::AbstractDecoratorManifold,
p,
q;
kwargs...,
)
@next_trait_function $trait_type isapprox(
M::AbstractDecoratorManifold,
p,
X,
Y;
kwargs...,
)
end
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 4214 | """
AbstractManifoldDomainError <: Exception
An absytract Case for Errors when checking validity of points/vectors on mainfolds
"""
abstract type AbstractManifoldDomainError <: Exception end
@doc """
ApproximatelyError{V,S} <: Exception
Store an error that occurs when two data structures, e.g. points or tangent vectors.
# Fields
* `val` amount the two approximate elements are apart – is set to `NaN` if this is not known
* `msg` a message providing more detail about the performed test and why it failed.
# Constructors
ApproximatelyError(val::V, msg::S) where {V,S}
Generate an Error with value `val` and message `msg`.
ApproximatelyError(msg::S) where {S}
Generate a message without a value (using `val=NaN` internally) and message `msg`.
"""
struct ApproximatelyError{V,S} <: Exception
val::V
msg::S
end
ApproximatelyError(msg::S) where {S} = ApproximatelyError{Float64,S}(NaN, msg)
function Base.show(io::IO, ex::ApproximatelyError)
isnan(ex.val) && return print(io, "ApproximatelyError(\"$(ex.msg)\")")
return print(io, "ApproximatelyError($(ex.val), \"$(ex.msg)\")")
end
function Base.showerror(io::IO, ex::ApproximatelyError)
isnan(ex.val) && return print(io, "ApproximatelyError\n$(ex.msg)\n")
return print(io, "ApproximatelyError with $(ex.val)\n$(ex.msg)\n")
end
@doc """
CompnentError{I,E} <: Exception
Store an error that occured in a component, where the additional `index` is stored.
# Fields
* `index::I` index where the error occured`
* `error::E` error that occured.
"""
struct ComponentManifoldError{I,E} <: AbstractManifoldDomainError where {I,E<:Exception}
index::I
error::E
end
function ComponentManifoldError(i::I, e::E) where {I,E<:Exception}
return ComponentManifoldError{I,E}(i, e)
end
@doc """
CompositeManifoldError{T} <: Exception
A composite type to collect a set of errors that occured. Mainly used in conjunction
with [`ComponentManifoldError`](@ref) to store a set of errors that occured.
# Fields
* `errors` a `Vector` of `<:Exceptions`.
"""
struct CompositeManifoldError{T} <: AbstractManifoldDomainError where {T<:Exception}
errors::Vector{T}
end
CompositeManifoldError() = CompositeManifoldError{Exception}(Exception[])
function CompositeManifoldError(errors::Vector{T}) where {T<:Exception}
return CompositeManifoldError{T}(errors)
end
isempty(c::CompositeManifoldError) = isempty(c.errors)
length(c::CompositeManifoldError) = length(c.errors)
function Base.show(io::IO, ex::ComponentManifoldError)
return print(io, "ComponentManifoldError($(ex.index), $(ex.error))")
end
function Base.show(io::IO, ex::CompositeManifoldError)
print(io, "CompositeManifoldError(")
if !isempty(ex)
print(io, "[")
start = true
for e in ex.errors
show(io, e)
print(io, ", ")
end
print(io, "]")
end
return print(io, ")")
end
function Base.showerror(io::IO, ex::ComponentManifoldError)
print(io, "At #$(ex.index): ")
return showerror(io, ex.error)
end
function Base.showerror(io::IO, ex::CompositeManifoldError)
return if !isempty(ex)
print(io, "CompositeManifoldError: ")
showerror(io, ex.errors[1])
remaining = length(ex) - 1
if remaining > 0
print(io, string("\n\n...and ", remaining, " more error(s).\n"))
end
else
print(io, "CompositeManifoldError()\n")
end
end
"""
OutOfInjectivityRadiusError
An error thrown when a function (for example [`log`](@ref)arithmic map or
[`inverse_retract`](@ref)) is given arguments outside of its [`injectivity_radius`](@ref).
"""
struct OutOfInjectivityRadiusError <: Exception end
"""
ManifoldDomainError{<:Exception} <: Exception
An error to represent a nested (Domain) error on a manifold, for example
if a point or tangent vector is invalid because its representation in some
embedding is already invalid.
"""
struct ManifoldDomainError{E} <: AbstractManifoldDomainError where {E<:Exception}
outer_text::String
error::E
end
function Base.showerror(io::IO, ex::ManifoldDomainError)
print(io, "ManifoldDomainError: $(ex.outer_text)\n")
return showerror(io, ex.error)
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 8626 | @doc raw"""
exp(M::AbstractManifold, p, X)
exp(M::AbstractManifold, p, X, t::Number = 1)
Compute the exponential map of tangent vector `X`, optionally scaled by `t`, at point `p`
from the manifold [`AbstractManifold`](@ref) `M`, i.e.
```math
\exp_p X = γ_{p,X}(1),
```
where ``γ_{p,X}`` is the unique geodesic starting in ``γ(0)=p`` such that ``\dot γ(0) = X``.
See also [`shortest_geodesic`](@ref), [`retract`](@ref).
"""
function exp(M::AbstractManifold, p, X)
q = allocate_result(M, exp, p, X)
exp!(M, q, p, X)
return q
end
function exp(M::AbstractManifold, p, X, t::Number)
q = allocate_result(M, exp, p, X, t)
exp!(M, q, p, X, t)
return q
end
"""
exp!(M::AbstractManifold, q, p, X)
exp!(M::AbstractManifold, q, p, X, t::Number = 1)
Compute the exponential map of tangent vector `X`, optionally scaled by `t`, at point `p`
from the manifold [`AbstractManifold`](@ref) `M`.
The result is saved to `q`.
If you want to implement exponential map for your manifold, you should implement the
method with `t`, that is `exp!(M::MyManifold, q, p, X, t::Number)`.
See also [`exp`](@ref).
"""
exp!(M::AbstractManifold, q, p, X)
exp!(M::AbstractManifold, q, p, X, t::Number) = exp!(M, q, p, t * X)
@doc raw"""
geodesic(M::AbstractManifold, p, X) -> Function
Get the geodesic with initial point `p` and velocity `X` on the [`AbstractManifold`](@ref) `M`.
A geodesic is a curve of zero acceleration. That is for the curve ``γ_{p,X}: I → \mathcal M``,
with ``γ_{p,X}(0) = p`` and ``\dot γ_{p,X}(0) = X`` a geodesic further fulfills
```math
∇_{\dot γ_{p,X}(t)} \dot γ_{p,X}(t) = 0,
```
i.e. the curve is acceleration free with respect to the Riemannian metric.
This yields, that the curve has constant velocity that is locally distance-minimizing.
This function returns a function of (time) `t`.
"""
geodesic(M::AbstractManifold, p, X) = t -> exp(M, p, X, t)
@doc raw"""
geodesic(M::AbstractManifold, p, X, t::Real)
Evaluate the geodesic ``γ_{p,X}: I → \mathcal M``,
with ``γ_{p,X}(0) = p`` and ``\dot γ_{p,X}(0) = X`` a geodesic further fulfills
```math
∇_{\dot γ_{p,X}(t)} \dot γ_{p,X}(t) = 0,
```
at time `t`.
"""
geodesic(M::AbstractManifold, p, X, t::Real) = exp(M, p, X, t)
@doc raw"""
geodesic(M::AbstractManifold, p, X, T::AbstractVector) -> AbstractVector
Evaluate the geodesic ``γ_{p,X}: I → \mathcal M``,
with ``γ_{p,X}(0) = p`` and ``\dot γ_{p,X}(0) = X`` a geodesic further fulfills
```math
∇_{\dot γ_{p,X}(t)} \dot γ_{p,X}(t) = 0,
```
at time points `t` from `T`.
"""
geodesic(M::AbstractManifold, p, X, T::AbstractVector) = map(t -> exp(M, p, X, t), T)
@doc raw"""
geodesic!(M::AbstractManifold, p, X) -> Function
Get the geodesic with initial point `p` and velocity `X` on the [`AbstractManifold`](@ref) `M`.
A geodesic is a curve of zero acceleration. That is for the curve ``γ_{p,X}: I → \mathcal M``,
with ``γ_{p,X}(0) = p`` and ``\dot γ_{p,X}(0) = X`` a geodesic further fulfills
```math
∇_{\dot γ_{p,X}(t)} \dot γ_{p,X}(t) = 0,
```
i.e. the curve is acceleration free with respect to the Riemannian metric.
This yields that the curve has constant velocity and is locally distance-minimizing.
This function returns a function `(q,t)` of (time) `t` that mutates `q``.
"""
geodesic!(M::AbstractManifold, p, X) = (q, t) -> exp!(M, q, p, X, t)
@doc raw"""
geodesic!(M::AbstractManifold, q, p, X, t::Real)
Get the geodesic with initial point `p` and velocity `X` on the [`AbstractManifold`](@ref) `M`.
A geodesic is a curve of zero acceleration. That is for the curve ``γ_{p,X}: I → \mathcal M``,
with ``γ_{p,X}(0) = p`` and ``\dot γ_{p,X}(0) = X`` a geodesic further fulfills
```math
∇_{\dot γ_{p,X}(t)} \dot γ_{p,X}(t) = 0,
```
i.e. the curve is acceleration free with respect to the Riemannian metric.
This function evaluates the geodeic at `t` in place of `q`.
"""
geodesic!(M::AbstractManifold, q, p, X, t::Real) = exp!(M, q, p, X, t)
@doc raw"""
geodesic!(M::AbstractManifold, Q, p, X, T::AbstractVector) -> AbstractVector
Get the geodesic with initial point `p` and velocity `X` on the [`AbstractManifold`](@ref) `M`.
A geodesic is a curve of zero acceleration. That is for the curve ``γ_{p,X}: I → \mathcal M``,
with ``γ_{p,X}(0) = p`` and ``\dot γ_{p,X}(0) = X`` a geodesic further fulfills
```math
∇_{\dot γ_{p,X}(t)} \dot γ_{p,X}(t) = 0,
```
i.e. the curve is acceleration free with respect to the Riemannian metric.
This function evaluates the geodeic at time points `t` fom `T` in place of `Q`.
"""
function geodesic!(M::AbstractManifold, Q, p, X, T::AbstractVector)
for (q, t) in zip(Q, T)
exp!(M, q, p, X, t)
end
return Q
end
"""
log(M::AbstractManifold, p, q)
Compute the logarithmic map of point `q` at base point `p` on the [`AbstractManifold`](@ref) `M`.
The logarithmic map is the inverse of the [`exp`](@ref)onential map.
Note that the logarithmic map might not be globally defined.
See also [`inverse_retract`](@ref).
"""
function log(M::AbstractManifold, p, q)
X = allocate_result(M, log, p, q)
log!(M, X, p, q)
return X
end
"""
log!(M::AbstractManifold, X, p, q)
Compute the logarithmic map of point `q` at base point `p` on the [`AbstractManifold`](@ref) `M`.
The result is saved to `X`.
The logarithmic map is the inverse of the [`exp!`](@ref)onential map.
Note that the logarithmic map might not be globally defined.
see also [`log`](@ref) and [`inverse_retract!`](@ref),
"""
log!(M::AbstractManifold, X, p, q)
@doc raw"""
shortest_geodesic(M::AbstractManifold, p, q) -> Function
Get a [`geodesic`](@ref) $γ_{p,q}(t)$ whose length is the shortest path between the
points `p`and `q`, where $γ_{p,q}(0)=p$ and $γ_{p,q}(1)=q$.
When there are multiple shortest geodesics, a deterministic choice will be returned.
This function returns a function of time, which may be a `Real` or an `AbstractVector`.
"""
shortest_geodesic(M::AbstractManifold, p, q) = geodesic(M, p, log(M, p, q))
@doc raw"""
shortest_geodesic(M::AabstractManifold, p, q, t::Real)
Evaluate a [`geodesic`](@ref) $γ_{p,q}(t)$ whose length is the shortest path between the
points `p`and `q`, where $γ_{p,q}(0)=p$ and $γ_{p,q}(1)=q$ at time `t`.
When there are multiple shortest geodesics, a deterministic choice will be returned.
"""
shortest_geodesic(M::AbstractManifold, p, q, t::Real) = geodesic(M, p, log(M, p, q), t)
@doc raw"""
shortest_geodesic(M::AbstractManifold, p, q, T::AbstractVector) -> AbstractVector
Evaluate a [`geodesic`](@ref) $γ_{p,q}(t)$ whose length is the shortest path between the
points `p`and `q`, where $γ_{p,q}(0)=p$ and $γ_{p,q}(1)=q$ at time points `T`.
When there are multiple shortest geodesics, a deterministic choice will be returned.
"""
function shortest_geodesic(M::AbstractManifold, p, q, T::AbstractVector)
return geodesic(M, p, log(M, p, q), T)
end
@doc raw"""
shortest_geodesic!(M::AbstractManifold, p, q) -> Function
Get a [`geodesic`](@ref) $γ_{p,q}(t)$ whose length is the shortest path between the
points `p`and `q`, where $γ_{p,q}(0)=p$ and $γ_{p,q}(1)=q$. When there are
multiple shortest geodesics, a deterministic choice will be returned.
This function returns a function `(r,t) -> ... ` of time `t` which works in place of `r`.
Further variants
shortest_geodesic!(M::AabstractManifold, r, p, q, t::Real)
shortest_geodesic!(M::AbstractManifold, R, p, q, T::AbstractVector) -> AbstractVector
mutate (and return) the point `r` and the vector of points `R`, respectively,
returning the point at time `t` or points at times `t` in `T` along the shortest [`geodesic`](@ref).
"""
shortest_geodesic!(M::AbstractManifold, p, q) = geodesic!(M, p, log(M, p, q))
@doc raw"""
shortest_geodesic!(M::AabstractManifold, r, p, q, t::Real)
Evaluate a [`geodesic`](@ref) $γ_{p,q}(t)$ whose length is the shortest path between the
points `p`and `q`, where $γ_{p,q}(0)=p$ and $γ_{p,q}(1)=q$ at `t` in place of `r`.
When there are multiple shortest geodesics, a deterministic choice will be taken.
"""
function shortest_geodesic!(M::AbstractManifold, r, p, q, t::Real)
return geodesic!(M, r, p, log(M, p, q), t)
end
@doc raw"""
shortest_geodesic!(M::AbstractManifold, R, p, q, T::AbstractVector) -> AbstractVector
Evaluate a [`geodesic`](@ref) $γ_{p,q}(t)$ whose length is the shortest path between the
points `p`and `q`, where $γ_{p,q}(0)=p$ and $γ_{p,q}(1)=q$ at all `t` from `T` in place of `R`.
When there are multiple shortest geodesics, a deterministic choice will be taken.
"""
function shortest_geodesic!(M::AbstractManifold, R, p, q, T::AbstractVector)
return geodesic!(M, R, p, log(M, p, q), T)
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 2688 | """
AbstractManifold{𝔽}
A type to represent a (Riemannian) manifold.
The [`AbstractManifold`](@ref) is a central type of this interface.
It allows to distinguish different implementations of functions like the [`exp`](@ref)onential and
[`log`](@ref)arithmic map for different manifolds.
Usually, the manifold is the first parameter in any of these functions within `ManifoldsBase.jl`.
Based on these, say “elementary” functions, as the two mentioned above, more general functions are built,
for example the [`shortest_geodesic`](@ref) and the [`geodesic`](@ref).
These should only be overwritten (reimplemented) if for a certain manifold specific, more efficient implementations are possible, that do not just call the elementary functions.
The [`AbstractManifold`] is parametrized by [`AbstractNumbers`](@ref) to distinguish for example
real (ℝ) and complex (ℂ) manifolds.
For subtypes the preferred order of parameters is: size and simple value parameters,
followed by the [`AbstractNumbers`](@ref) `field`, followed by data type parameters,
which might depend on the abstract number field type.
"""
abstract type AbstractManifold{𝔽} end
"""
AbstractManifoldPoint
Type for a point on a manifold.
While an [`AbstractManifold`](@ref) does not necessarily require this
type, for example when it is implemented for `Vector`s or `Matrix` type elements, this type
can be used either
* for more complicated representations,
* semantic verification, or
* when dispatching on different representations of points on a manifold.
Since semantic verification and different representations usually might still only store a
matrix internally, it is possible to use [`@manifold_element_forwards`](@ref) and
[`@default_manifold_fallbacks`](@ref) to reduce implementation overhead.
"""
abstract type AbstractManifoldPoint end
"""
TypeParameter{T}
Represents numeric parameters of a manifold type as type parameters, allowing for static
specialization of methods.
"""
struct TypeParameter{T} end
TypeParameter(t::NTuple) = TypeParameter{Tuple{t...}}()
get_parameter(::TypeParameter{T}) where {T} = tuple(T.parameters...)
get_parameter(P) = P
"""
wrap_type_parameter(parameter::Symbol, data)
Wrap `data` in `TypeParameter` if `parameter` is `:type` or return `data` unchanged
if `parameter` is `:field`. Intended for use in manifold constructors, see
[`DefaultManifold`](@ref) for an example.
"""
@inline function wrap_type_parameter(parameter::Symbol, data)
if parameter === :field
return data
elseif parameter === :type
TypeParameter(data)
else
throw(ArgumentError("Parameter can be either :field or :type. Given: $parameter"))
end
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 3682 | @doc raw"""
AbstractMetric
Abstract type for the pseudo-Riemannian metric tensor ``g``, a family of smoothly
varying inner products on the tangent space. See [`inner`](@ref).
# Functor
(metric::Metric)(M::AbstractManifold)
(metric::Metric)(M::MetricManifold)
Generate the `MetricManifold` that wraps the manifold `M` with given `metric`.
This works for both a variable containing the metric as well as a subtype `T<:AbstractMetric`,
where a zero parameter constructor `T()` is availabe.
If `M` is already a metric manifold, the inner manifold with the new `metric` is returned.
"""
abstract type AbstractMetric end
@doc raw"""
RiemannianMetric <: AbstractMetric
Abstract type for Riemannian metrics, a family of positive definite inner
products. The positive definite property means that for ``X ∈ T_p \mathcal M``, the
inner product ``g(X, X) > 0`` whenever ``X`` is not the zero vector.
"""
abstract type RiemannianMetric <: AbstractMetric end
"""
EuclideanMetric <: RiemannianMetric
A general type for any manifold that employs the Euclidean Metric, for example
the [`Euclidean`](https://juliamanifolds.github.io/Manifolds.jl/latest/manifolds/euclidean.html) manifold itself, or the [`Sphere`](https://juliamanifolds.github.io/Manifolds.jl/latest/manifolds/sphere.html), where every
tangent space (as a plane in the embedding) uses this metric (in the embedding).
Since the metric is independent of the field type, this metric is also used for
the Hermitian metrics, i.e. metrics that are analogous to the `EuclideanMetric`
but where the field type of the manifold is `ℂ`.
This metric is the default metric for example for the [`Euclidean`](https://juliamanifolds.github.io/Manifolds.jl/latest/manifolds/euclidean.html) manifold.
"""
struct EuclideanMetric <: RiemannianMetric end
@doc raw"""
change_metric(M::AbstractcManifold, G2::AbstractMetric, p, X)
On the [`AbstractManifold`](@ref) `M` with implicitly given metric ``g_1``
and a second [`AbstractMetric`](@ref)
``g_2`` this function performs a change of metric in the
sense that it returns the tangent vector ``Z=BX`` such that the linear map ``B`` fulfills
```math
g_2(Y_1,Y_2) = g_1(BY_1,BY_2) \quad \text{for all } Y_1, Y_2 ∈ T_p\mathcal M.
```
"""
function change_metric(M::AbstractManifold, G::AbstractMetric, p, X)
Y = allocate_result(M, change_metric, X, p) # this way we allocate a tangent
return change_metric!(M, Y, G, p, X)
end
@doc raw"""
change_metric!(M::AbstractcManifold, Y, G2::AbstractMetric, p, X)
Compute the [`change_metric`](@ref) in place of `Y`.
"""
change_metric!(M::AbstractManifold, Y, G::AbstractMetric, p, X)
@doc raw"""
change_representer(M::AbstractManifold, G2::AbstractMetric, p, X)
Convert the representer `X` of a linear function (in other words a cotangent vector at `p`)
in the tangent space at `p` on the [`AbstractManifold`](@ref) `M` given with respect to the
[`AbstractMetric`](@ref) `G2` into the representer with respect to the (implicit) metric of `M`.
In order to convert `X` into the representer with respect to the (implicitly given) metric ``g_1`` of `M`,
we have to find the conversion function ``c: T_p\mathcal M \to T_p\mathcal M`` such that
```math
g_2(X,Y) = g_1(c(X),Y)
```
"""
function change_representer(M::AbstractManifold, G::AbstractMetric, p, X)
Y = allocate_result(M, change_representer, X, p) # this way we allocate a tangent
return change_representer!(M, Y, G, p, X)
end
@doc raw"""
change_representer!(M::AbstractcManifold, Y, G2::AbstractMetric, p, X)
Compute the [`change_metric`](@ref) in place of `Y`.
"""
change_representer!(M::AbstractManifold, Y, G::AbstractMetric, p, X)
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 12061 | @doc raw"""
AbstractDecoratorManifold{𝔽} <: AbstractManifold{𝔽}
Declare a manifold to be an abstract decorator.
A manifold which is a subtype of is a __decorated manifold__, i.e. has
* certain additional properties or
* delegates certain properties to other manifolds.
Most prominently, a manifold might be an embedded manifold, i.e. points on a manifold ``\mathcal M``
are represented by (some, maybe not all) points on another manifold ``\mathcal N``.
Depending on the type of embedding, several functions are dedicated to the embedding.
For example if the embedding is isometric, then the [`inner`](@ref) does not have to be
implemented for ``\mathcal M`` but can be automatically implemented by deligation to ``\mathcal N``.
This is modelled by the `AbstractDecoratorManifold` and traits. These are mapped to functions,
which determine the types of transparencies.
"""
abstract type AbstractDecoratorManifold{𝔽} <: AbstractManifold{𝔽} end
"""
AbstractTrait
An abstract trait type to build a sequence of traits
"""
abstract type AbstractTrait end
"""
EmptyTrait <: AbstractTrait
A Trait indicating that no feature is present.
"""
struct EmptyTrait <: AbstractTrait end
"""
IsExplicitDecorator <: AbstractTrait
Specify that a certain type should dispatch per default to its [`decorated_manifold`](@ref).
!!! note
Any decorator _behind_ this decorator might not have any effect, since the function
dispatch is moved to its field at this point. Therefore this decorator should always be
_last_ in the [`TraitList`](@ref).
"""
struct IsExplicitDecorator <: AbstractTrait end
"""
TraitList <: AbstractTrait
Combine two traits into a combined trait. Note that this introduces a preceedence.
the first of the traits takes preceedence if a trait is implemented for both functions.
# Constructor
TraitList(head::AbstractTrait, tail::AbstractTrait)
"""
struct TraitList{T1<:AbstractTrait,T2<:AbstractTrait} <: AbstractTrait
head::T1
tail::T2
end
function Base.show(io::IO, t::TraitList)
return print(io, "TraitList(", t.head, ", ", t.tail, ")")
end
"""
active_traits(f, args...)
Return the list of traits applicable to the given call of function `f``. This function should be
overloaded for specific function calls.
"""
@inline active_traits(f, args...) = EmptyTrait()
"""
merge_traits(t1, t2, trest...)
Merge two traits into a nested list of traits. Note that this takes trait preceedence into account,
i.e. `t1` takes preceedence over `t2` is any operations.
It always returns either ab [`EmptyTrait`](@ref) or a [`TraitList`](@ref).
This means that for
* one argument it just returns the trait itself if it is list-like, or wraps the trait in a
single-element list otherwise,
* two arguments that are list-like, it merges them,
* two arguments of which only the first one is list-like and the second one is not,
it appends the second argument to the list,
* two arguments of which only the second one is list-like, it prepends the first one to
the list,
* two arguments of which none is list-like, it creates a two-element list.
* more than two arguments it recursively performs a left-assiciative recursive reduction
on arguments, that is for example `merge_traits(t1, t2, t3)` is equivalent to
`merge_traits(merge_traits(t1, t2), t3)`
"""
merge_traits()
@inline merge_traits() = EmptyTrait()
@inline merge_traits(t::EmptyTrait) = t
@inline merge_traits(t::TraitList) = t
@inline merge_traits(t::AbstractTrait) = TraitList(t, EmptyTrait())
@inline merge_traits(t1::EmptyTrait, ::EmptyTrait) = t1
@inline merge_traits(::EmptyTrait, t2::AbstractTrait) = merge_traits(t2)
@inline merge_traits(t1::AbstractTrait, t2::EmptyTrait) = TraitList(t1, t2)
@inline merge_traits(t1::AbstractTrait, t2::TraitList) = TraitList(t1, t2)
@inline merge_traits(::EmptyTrait, t2::TraitList) = t2
@inline function merge_traits(t1::AbstractTrait, t2::AbstractTrait)
return TraitList(t1, TraitList(t2, EmptyTrait()))
end
@inline merge_traits(t1::TraitList, ::EmptyTrait) = t1
@inline function merge_traits(t1::TraitList, t2::AbstractTrait)
return TraitList(t1.head, merge_traits(t1.tail, t2))
end
@inline function merge_traits(t1::TraitList, t2::TraitList)
return TraitList(t1.head, merge_traits(t1.tail, t2))
end
@inline function merge_traits(
t1::AbstractTrait,
t2::AbstractTrait,
t3::AbstractTrait,
trest::AbstractTrait...,
)
return merge_traits(merge_traits(t1, t2), t3, trest...)
end
"""
parent_trait(t::AbstractTrait)
Return the parent trait for trait `t`, that is the more general trait whose behaviour it
inherits as a fallback.
"""
@inline parent_trait(::AbstractTrait) = EmptyTrait()
@inline function trait(f::TF, args...) where {TF}
bt = active_traits(f, args...)
return expand_trait(bt)
end
"""
expand_trait(t::AbstractTrait)
Expand given trait into an ordered [`TraitList`](@ref) list of traits with their parent
traits obtained using [`parent_trait`](@ref).
"""
expand_trait(::AbstractTrait)
@inline expand_trait(e::EmptyTrait) = e
@inline expand_trait(t::AbstractTrait) = merge_traits(t, expand_trait(parent_trait(t)))
@inline function expand_trait(t::TraitList)
et1 = expand_trait(t.head)
et2 = expand_trait(t.tail)
return merge_traits(et1, et2)
end
"""
next_trait(t::AbstractTrait)
Return the next trait to consider, which by default is no following trait (i.e. [`EmptyTrait`](@ref)).
Expecially for a a [`TraitList`](@ref) this function returns the (remaining) tail of
the remaining traits.
"""
next_trait(::AbstractTrait) = EmptyTrait()
@inline next_trait(t::TraitList) = t.tail
#! format: off
# turn formatting for for the following functions
# due to the if with returns inside (formatter puts a return upfront the if)
function _split_signature(sig::Expr)
if sig.head == :where
where_exprs = sig.args[2:end]
call_expr = sig.args[1]
elseif sig.head == :call
where_exprs = []
call_expr = sig
else
error("Incorrect syntax in $sig. Expected a :where or :call expression.")
end
fname = call_expr.args[1]
if isa(call_expr.args[2], Expr) && call_expr.args[2].head == :parameters
# we have keyword arguments
callargs = call_expr.args[3:end]
kwargs_list = call_expr.args[2].args
else
callargs = call_expr.args[2:end]
kwargs_list = []
end
argnames = map(callargs) do arg
if isa(arg, Expr) && arg.head === :kw # default val present
arg = arg.args[1]
end
if isa(arg, Expr) && arg.head === :(::) # typed
return arg.args[1]
end
return arg
end
argtypes = map(callargs) do arg
if isa(arg, Expr) && arg.head === :kw # default val present
arg = arg.args[1]
end
if isa(arg, Expr)
return arg.args[2]
else
return Any
end
end
kwargs_call = map(kwargs_list) do kwarg
if kwarg.head === :...
return kwarg
else
if isa(kwarg.args[1], Symbol)
kwargname = kwarg.args[1]
else
kwargname = kwarg.args[1].args[1]
end
return :($kwargname = $kwargname)
end
end
return (;
fname = fname,
where_exprs = where_exprs,
callargs = callargs,
kwargs_list = kwargs_list,
argnames = argnames,
argtypes = argtypes,
kwargs_call = kwargs_call,
)
end
#! format: on
macro invoke_maker(argnum, type, sig)
parts = ManifoldsBase._split_signature(sig)
kwargs_list = parts[:kwargs_list]
callargs = parts[:callargs]
fname = parts[:fname]
where_exprs = parts[:where_exprs]
argnames = parts[:argnames]
argtypes = parts[:argtypes]
kwargs_call = parts[:kwargs_call]
return esc(
quote
function ($fname)($(callargs...); $(kwargs_list...)) where {$(where_exprs...)}
return invoke(
$fname,
Tuple{
$(argtypes[1:(argnum - 1)]...),
$type,
$(argtypes[(argnum + 1):end]...),
},
$(argnames...);
$(kwargs_call...),
)
end
end,
)
end
"""
next_trait_function(trait_type, sig)
Define a special trait-handling method for function indicated by `sig`. It does not change
the result but the presence of such additional methods may prevent method recursion limits
in Julia's inference from being triggered. Some functions may work faster after adding
methods generated by `next_trait_function`.
See the "Trait recursion breaking" section at the bottom of `src/decorator_trait.jl` file
for an example of intended usage.
"""
macro next_trait_function(trait_type, sig)
parts = ManifoldsBase._split_signature(sig)
kwargs_list = parts[:kwargs_list]
callargs = parts[:callargs]
fname = parts[:fname]
where_exprs = parts[:where_exprs]
argnames = parts[:argnames]
kwargs_call = parts[:kwargs_call]
block = quote
@inline function ($fname)(
_t::$trait_type,
$(callargs...);
$(kwargs_list...),
) where {$(where_exprs...)}
return ($fname)(next_trait(_t), $(argnames...); $(kwargs_call...))
end
end
return esc(block)
end
macro trait_function(sig, opts = :(), manifold_arg_no = 1)
parts = ManifoldsBase._split_signature(sig)
kwargs_list = parts[:kwargs_list]
callargs = parts[:callargs]
fname = parts[:fname]
where_exprs = parts[:where_exprs]
argnames = parts[:argnames]
argtypes = parts[:argtypes]
kwargs_call = parts[:kwargs_call]
argnametype_exprs = [:(typeof($(argname))) for argname in argnames]
block = quote
@inline function ($fname)($(callargs...); $(kwargs_list...)) where {$(where_exprs...)}
return ($fname)(trait($fname, $(argnames...)), $(argnames...); $(kwargs_call...))
end
@inline function ($fname)(
_t::ManifoldsBase.TraitList,
$(callargs...);
$(kwargs_list...),
) where {$(where_exprs...)}
return ($fname)(next_trait(_t), $(argnames...); $(kwargs_call...))
end
@inline function ($fname)(
_t::ManifoldsBase.TraitList{ManifoldsBase.IsExplicitDecorator},
$(callargs...);
$(kwargs_list...),
) where {$(where_exprs...)}
arg_manifold = decorated_manifold($(argnames[manifold_arg_no]))
argt_manifold = typeof(arg_manifold)
return invoke(
$fname,
Tuple{
$(argnametype_exprs[1:(manifold_arg_no - 1)]...),
argt_manifold,
$(argnametype_exprs[(manifold_arg_no + 1):end]...),
},
$(argnames[1:(manifold_arg_no - 1)]...),
arg_manifold,
$(argnames[(manifold_arg_no + 1):end]...);
$(kwargs_call...),
)
end
end
if !(:no_empty in opts.args)
block = quote
$block
# See https://discourse.julialang.org/t/extremely-slow-invoke-when-inlined/90665
# for the reasoning behind @noinline
@noinline function ($fname)(
::ManifoldsBase.EmptyTrait,
$(callargs...);
$(kwargs_list...),
) where {$(where_exprs...)}
return invoke(
$fname,
Tuple{
$(argnametype_exprs[1:(manifold_arg_no - 1)]...),
supertype($(argtypes[manifold_arg_no])),
$(argnametype_exprs[(manifold_arg_no + 1):end]...),
},
$(argnames...);
$(kwargs_call...),
)
end
end
end
return esc(block)
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 2881 | """
AbstractNumbers
An abstract type to represent the number system on which a manifold is built.
This provides concrete number types for dispatch. The two most common number types are
the fields [`RealNumbers`](@ref) (`ℝ` for short) and [`ComplexNumbers`](@ref) (`ℂ`).
"""
abstract type AbstractNumbers end
"""
RealNumbers <: AbstractNumbers
ℝ = RealNumbers()
The field of real numbers.
"""
struct RealNumbers <: AbstractNumbers end
"""
ComplexNumbers <: AbstractNumbers
ℂ = ComplexNumbers()
The field of complex numbers.
"""
struct ComplexNumbers <: AbstractNumbers end
"""
QuaternionNumbers <: AbstractNumbers
ℍ = QuaternionNumbers()
The division algebra of quaternions.
"""
struct QuaternionNumbers <: AbstractNumbers end
const ℝ = RealNumbers()
const ℂ = ComplexNumbers()
const ℍ = QuaternionNumbers()
@inline function allocate_result_type(
::AbstractManifold{ℂ},
f::TF,
args::Tuple{},
) where {TF}
return ComplexF64
end
"""
_unify_number_systems(𝔽s::AbstractNumbers...)
Compute a number system that includes all given number systems (as sub-systems) and is
closed under addition and multiplication.
"""
function _unify_number_systems(a::AbstractNumbers, rest::AbstractNumbers...)
return _unify_number_systems(a, _unify_number_systems(rest...))
end
_unify_number_systems(𝔽::AbstractNumbers) = 𝔽
_unify_number_systems(r::RealNumbers, ::RealNumbers) = r
_unify_number_systems(::RealNumbers, c::ComplexNumbers) = c
_unify_number_systems(::RealNumbers, q::QuaternionNumbers) = q
_unify_number_systems(c::ComplexNumbers, ::RealNumbers) = c
_unify_number_systems(c::ComplexNumbers, ::ComplexNumbers) = c
_unify_number_systems(::ComplexNumbers, q::QuaternionNumbers) = q
_unify_number_systems(q::QuaternionNumbers, ::RealNumbers) = q
_unify_number_systems(q::QuaternionNumbers, ::ComplexNumbers) = q
_unify_number_systems(q::QuaternionNumbers, ::QuaternionNumbers) = q
Base.show(io::IO, ::RealNumbers) = print(io, "ℝ")
Base.show(io::IO, ::ComplexNumbers) = print(io, "ℂ")
Base.show(io::IO, ::QuaternionNumbers) = print(io, "ℍ")
@doc raw"""
real_dimension(𝔽::AbstractNumbers)
Return the real dimension $\dim_ℝ 𝔽$ of the [`AbstractNumbers`](@ref) system `𝔽`.
The real dimension is the dimension of a real vector space with which a number in `𝔽` can be
identified.
For example, [`ComplexNumbers`](@ref) have a real dimension of 2, and
[`QuaternionNumbers`](@ref) have a real dimension of 4.
"""
function real_dimension(𝔽::AbstractNumbers)
return error("real_dimension not defined for number system $(𝔽)")
end
real_dimension(::RealNumbers) = 1
real_dimension(::ComplexNumbers) = 2
real_dimension(::QuaternionNumbers) = 4
@doc raw"""
number_system(M::AbstractManifold{𝔽})
Return the number system the manifold `M` is based on, i.e. the parameter `𝔽`.
"""
number_system(M::AbstractManifold{𝔽}) where {𝔽} = 𝔽
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 15714 |
@doc raw"""
check_inverse_retraction(
M::AbstractManifold,
inverse_rectraction_method::AbstractInverseRetractionMethod,
p=rand(M),
X=rand(M; vector_at=p);
#
exactness_tol::Real = 1e-12,
io::Union{IO,Nothing} = nothing,
limits::Tuple = (-8.0, 0.0),
log_range::AbstractVector = range(limits[1], limits[2]; length=N),
N::Int = 101,
name::String = "inverse retraction",
plot::Bool = false,
second_order::Bool = true
slope_tol::Real = 0.1,
error::Symbol = :none,
window = nothing,
)
Check numerically wether the inverse retraction `inverse_retraction_method` is correct.
This requires the [`exp`](@ref) and [`norm`](@ref) functions to be implemented for the [`AbstractManifold`](@ref) `M`.
This implements a method similar to [Boumal:2023; Section 4.8 or Section 6.8](@cite).
Note that if the errors are below the given tolerance and the method is exact,
no plot is generated,
# Keyword arguments
* `exactness_tol`: if all errors are below this tolerance, the inverse retraction is considered to be exact
* `io`: provide an `IO` to print the result to
* `limits`: specify the limits in the `log_range`, that is the exponent for the range
* `log_range`: specify the range of points (in log scale) to sample the length of the tangent vector `X`
* `N`: number of points to verify within the `log_range` default range ``[10^{-8},10^{0}]``
* `name`: name to display in the plot
* `plot`: whether to plot the result (see [`plot_slope`](@ref))
The plot is in log-log-scale. This is returned and can then also be saved.
* `second_order`: check whether the retraction is of second order. if set to `false`, first order is checked.
* `slope_tol`: tolerance for the slope (global) of the approximation
* `error`: specify how to report errors: `:none`, `:info`, `:warn`, or `:error` are available
* `window`: specify window sizes within the `log_range` that are used for the slope estimation.
the default is, to use all window sizes `2:N`.
"""
function check_inverse_retraction(
M::AbstractManifold,
inverse_retraction_method::AbstractInverseRetractionMethod,
p = rand(M),
X = rand(M; vector_at = p);
exactness_tol::Real = 1e-12,
io::Union{IO,Nothing} = nothing,
limits = (-8.0, 0.0),
N::Int = 101,
second_order::Bool = true,
name::String = second_order ? "second order inverse retraction" : "inverse retraction",
log_range::AbstractVector = range(limits[1], limits[2]; length = N),
plot::Bool = false,
slope_tol::Real = 0.1,
error::Symbol = :none,
window = nothing,
)
Xn = X ./ norm(M, p, X) # normalize tangent direction
# function for the directional derivative
#
T = exp10.(log_range)
# points `p_i` to evaluate the error function at
points = [exp(M, p, Xn, t) for t in T]
Xs = [t * Xn for t in T]
approx_Xs = [inverse_retract(M, p, q, inverse_retraction_method) for q in points]
errors = [norm(M, p, X - Y) for (X, Y) in zip(Xs, approx_Xs)]
return prepare_check_result(
log_range,
errors,
second_order ? 3.0 : 2.0;
exactness_tol = exactness_tol,
io = io,
name = name,
plot = plot,
slope_tol = slope_tol,
error = error,
window = window,
)
end
@doc raw"""
check_retraction(
M::AbstractManifold,
rectraction_method::AbstractRetractionMethod,
p=rand(M),
X=rand(M; vector_at=p);
#
exactness_tol::Real = 1e-12,
io::Union{IO,Nothing} = nothing,
limits::Tuple = (-8.0, 0.0),
log_range::AbstractVector = range(limits[1], limits[2]; length=N),
N::Int = 101,
name::String = "retraction",
plot::Bool = false,
second_order::Bool = true
slope_tol::Real = 0.1,
error::Symbol = :none,
window = nothing,
)
Check numerically wether the retraction `vector_transport_to` is correct, by selecting
a set of points ``q_i = \exp_p (t_i X)`` where ``t`` takes all values from `log_range`,
to then compare [`parallel_transport_to`](@ref) to the `vector_transport_method`
applied to the vector `Y`.
This requires the [`exp`](@ref), [`parallel_transport_to`](@ref) and [`norm`](@ref) function
to be implemented for the [`AbstractManifold`](@ref) `M`.
This implements a method similar to [Boumal:2023; Section 4.8 or Section 6.8](@cite).
Note that if the errors are below the given tolerance and the method is exact,
no plot is generated,
# Keyword arguments
* `exactness_tol`: if all errors are below this tolerance, the retraction is considered to be exact
* `io`: provide an `IO` to print the result to
* `limits`: specify the limits in the `log_range`, that is the exponent for the range
* `log_range`: specify the range of points (in log scale) to sample the length of the tangent vector `X`
* `N`: number of points to verify within the `log_range` default range ``[10^{-8},10^{0}]``
* `name`: name to display in the plot
* `plot`: whether to plot the result (if `Plots.jl` is loaded).
The plot is in log-log-scale. This is returned and can then also be saved.
* `second_order`: check whether the retraction is of second order. if set to `false`, first order is checked.
* `slope_tol`: tolerance for the slope (global) of the approximation
* `error`: specify how to report errors: `:none`, `:info`, `:warn`, or `:error` are available
* `window`: specify window sizes within the `log_range` that are used for the slope estimation.
the default is, to use all window sizes `2:N`.
"""
function check_retraction(
M::AbstractManifold,
retraction_method::AbstractRetractionMethod,
p = rand(M),
X = rand(M; vector_at = p);
exactness_tol::Real = 1e-12,
io::Union{IO,Nothing} = nothing,
limits::Tuple = (-8.0, 0.0),
N::Int = 101,
second_order::Bool = true,
name::String = second_order ? "second order retraction" : "retraction",
log_range = range(limits[1], limits[2]; length = N),
plot::Bool = false,
slope_tol::Real = 0.1,
error::Symbol = :none,
window = nothing,
)
Xn = X ./ norm(M, p, X) # normalize tangent direction
# function for the directional derivative
#
T = exp10.(log_range)
# points `p_i` to evaluate the error function at
points = [exp(M, p, Xn, t) for t in T]
approx_points = [retract(M, p, Xn, t, retraction_method) for t in T]
errors = [distance(M, p, q) for (p, q) in zip(points, approx_points)]
return prepare_check_result(
log_range,
errors,
second_order ? 3.0 : 2.0;
exactness_tol = exactness_tol,
io = io,
name = name,
plot = plot,
slope_tol = slope_tol,
error = error,
window = window,
)
end
@doc raw"""
check_vector_transport(
M::AbstractManifold,
vector_transport_method::AbstractVectorTransportMethod,
p=rand(M),
X=rand(M; vector_at=p),
Y=rand(M; vector_at=p);
#
exactness_tol::Real = 1e-12,
io::Union{IO,Nothing} = nothing,
limits::Tuple = (-8.0, 0.0),
log_range::AbstractVector = range(limits[1], limits[2]; length=N),
N::Int = 101,
name::String = "inverse retraction",
plot::Bool = false,
second_order::Bool = true
slope_tol::Real = 0.1,
error::Symbol = :none,
window = nothing,
)
Check numerically wether the retraction `vector_transport_to` is correct, by selecting
a set of points ``q_i = \exp_p (t_i X)`` where ``t`` takes all values from `log_range`,
to then compare [`parallel_transport_to`](@ref) to the `vector_transport_method`
applied to the vector `Y`.
This requires the [`exp`](@ref), [`parallel_transport_to`](@ref) and [`norm`](@ref) function
to be implemented for the [`AbstractManifold`](@ref) `M`.
This implements a method similar to [Boumal:2023; Section 4.8 or Section 6.8](@cite).
Note that if the errors are below the given tolerance and the method is exact,
no plot is generated,
# Keyword arguments
* `exactness_tol`: if all errors are below this tolerance, the differential is considered to be exact
* `io`: provide an `IO` to print the result to
* `limits`: specify the limits in the `log_range`, that is the exponent for the range
* `log_range`: specify the range of points (in log scale) to sample the differential line
* `N`: number of points to verify within the `log_range` default range ``[10^{-8},10^{0}]``
* `name`: name to display in the plot
* `plot`: whether to plot the result (if `Plots.jl` is loaded).
The plot is in log-log-scale. This is returned and can then also be saved.
* `second_order`: check whether the retraction is of second order. if set to `false`, first order is checked.
* `slope_tol`: tolerance for the slope (global) of the approximation
* `error`: specify how to report errors: `:none`, `:info`, `:warn`, or `:error` are available
* `window`: specify window sizes within the `log_range` that are used for the slope estimation.
the default is, to use all window sizes `2:N`.
"""
function check_vector_transport(
M::AbstractManifold,
vector_transport_method::AbstractVectorTransportMethod,
p = rand(M),
X = rand(M; vector_at = p),
Y = rand(M; vector_at = p);
exactness_tol::Real = 1e-12,
io::Union{IO,Nothing} = nothing,
limits::Tuple = (-8.0, 0.0),
N::Int = 101,
second_order::Bool = true,
name::String = second_order ? "second order vector transport" : "vector transport",
log_range::AbstractVector = range(limits[1], limits[2]; length = N),
plot::Bool = false,
slope_tol::Real = 0.1,
error::Symbol = :none,
window = nothing,
)
Xn = X ./ norm(M, p, X) # normalize tangent direction
# function for the directional derivative
#
T = exp10.(log_range)
# points `p_i` to evaluate the error function at
points = [exp(M, p, Xn, t) for t in T]
Yv = [vector_transport_to(M, p, Y, q, vector_transport_method) for q in points]
Yp = [parallel_transport_to(M, p, Y, q) for q in points]
errors = [norm(M, q, X - Y) for (q, X, Y) in zip(points, Yv, Yp)]
return prepare_check_result(
log_range,
errors,
second_order ? 3.0 : 2.0;
exactness_tol = exactness_tol,
io = io,
name = name,
plot = plot,
slope_tol = slope_tol,
error = error,
window = window,
)
end
function plot_slope end
"""
plot_slope(x, y;
slope=2,
line_base=0,
a=0,
b=2.0,
i=1,
j=length(x)
)
Plot the result from the verification functions on data `x,y` with two comparison lines
1) `line_base` + t`slope` as the global slope(s) the plot could have
2) `a` + `b*t` on the interval [`x[i]`, `x[j]`] for some (best fitting) comparison slope
!!! note
This function has to be implemented for a certain plotting package.
loading [Plots.jl](https://docs.juliaplots.org/stable/) provides a default implementation.
"""
plot_slope(x, y)
"""
prepare_check_result(
log_range::AbstractVector,
errors::AbstractVector,
slope::Real;
exactness_to::Real = 1e3*eps(eltype(errors)),
io::Union{IO,Nothing} = nothing
name::String = "estimated slope",
plot::Bool = false,
slope_tol::Real = 0.1,
error::Symbol = :none,
)
Given a range of values `log_range`, with computed `errors`,
verify whether this yields a slope of `slope` in log-scale
Note that if the errors are below the given tolerance and the method is exact,
no plot is be generated,
# Keyword arguments
* `exactness_tol`: is all errors are below this tolerance, the verification is considered to be exact
* `io`: provide an `IO` to print the result to
* `name`: name to display in the plot title
* `plot`: whether to plot the result, see [`plot_slope`](@ref)
The plot is in log-log-scale. This is returned and can then also be saved.
* `slope_tol`: tolerance for the slope (global) of the approximation
* `error`: specify how to handle errors, `:none`, `:info`, `:warn`, `:error`
"""
function prepare_check_result(
log_range::AbstractVector,
errors::AbstractVector,
slope::Real;
io::Union{IO,Nothing} = nothing,
name::String = "estimated slope",
slope_tol::Real = 1e-1,
plot::Bool = false,
error::Symbol = :none,
window = nothing,
exactness_tol::Real = 1e3 * eps(eltype(errors)),
)
if max(errors...) < exactness_tol
(io !== nothing) && print(
io,
"All errors are below the exactness tolerance $(exactness_tol). Your check can be considered exact, hence there is no use to check for a slope.\n",
)
return true
end
x = log_range[errors .> 0]
T = exp10.(x)
y = log10.(errors[errors .> 0])
(a, b) = find_best_slope_window(x, y, length(x))[1:2]
if isapprox(b, slope; atol = slope_tol)
plot && return plot_slope(
T,
errors[errors .> 0];
slope = slope,
line_base = errors[1],
a = a,
b = b,
i = 1,
j = length(y),
)
(io !== nothing) && print(
io,
"Your $name's slope is globally $(@sprintf("%.4f", b)), so within $slope ± $(slope_tol).\n",
)
return true
end
# otherwise
# find best contiguous window of length w
(ab, bb, ib, jb) = find_best_slope_window(x, y, window; slope_tol = slope_tol)
msg = "The $(name) fits best on [$(T[ib]),$(T[jb])] with slope $(@sprintf("%.4f", bb)), but globally your slope $(@sprintf("%.4f", b)) is outside of the tolerance $slope ± $(slope_tol).\n"
(io !== nothing) && print(io, msg)
plot && return plot_slope(
T,
errors[errors .> 0];
slope = slope,
line_base = errors[1],
a = ab,
b = bb,
i = ib,
j = jb,
)
(error === :info) && @info msg
(error === :warn) && @warn msg
(error === :error) && throw(ErrorException(msg))
return false
end
function find_best_slope_window end
"""
(a, b, i, j) = find_best_slope_window(X, Y, window=nothing; slope::Real=2.0, slope_tol::Real=0.1)
Check data X,Y for the largest contiguous interval (window) with a regression line fitting “best”.
Among all intervals with a slope within `slope_tol` to `slope` the longest one is taken.
If no such interval exists, the one with the slope closest to `slope` is taken.
If the window is set to `nothing` (default), all window sizes `2,...,length(X)` are checked.
You can also specify a window size or an array of window sizes.
For each window size, all its translates in the data is checked.
For all these (shifted) windows the regression line is computed (with `a,b` in `a + t*b`)
and the best line is computed.
From the best line the following data is returned
* `a`, `b` specifying the regression line `a + t*b`
* `i`, `j` determining the window, i.e the regression line stems from data `X[i], ..., X[j]`
!!! note
This function has to be implemented using some statistics package.
loading [Statistics.jl](https://github.com/JuliaStats/Statistics.jl) provides a default implementation.
"""
find_best_slope_window(X, Y, window = nothing)
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 2214 | function parallel_transport_along! end
@doc raw"""
Y = parallel_transport_along(M::AbstractManifold, p, X, c)
Compute the parallel transport of the vector `X` from the tangent space at `p`
along the curve `c`.
To be precise let ``c(t)`` be a curve ``c(0)=p`` for [`vector_transport_along`](@ref) ``\mathcal P^cY``
THen In the result ``Y\in T_p\mathcal M`` is the vector ``X`` from the tangent space at ``p=c(0)``
to the tangent space at ``c(1)``.
Let ``Z\colon [0,1] \to T\mathcal M``, ``Z(t)\in T_{c(t)}\mathcal M`` be a smooth vector field
along the curve ``c`` with ``Z(0) = Y``, such that ``Z`` is _parallel_, i.e.
its covariant derivative ``\frac{\mathrm{D}}{\mathrm{d}t}Z`` is zero. Note that such a ``Z`` always exists and is unique.
Then the parallel transport is given by ``Z(1)``.
"""
function parallel_transport_along(M::AbstractManifold, p, X, c::AbstractVector; kwargs...)
Y = allocate_result(M, vector_transport_along, X, p)
return parallel_transport_along!(M, Y, p, X, c; kwargs...)
end
function parallel_transport_direction!(M::AbstractManifold, Y, p, X, d; kwargs...)
return parallel_transport_to!(M, Y, p, X, exp(M, p, d); kwargs...)
end
@doc raw"""
parallel_transport_direction(M::AbstractManifold, p, X, d)
Compute the [`parallel_transport_along`](@ref) the curve ``c(t) = γ_{p,q}(t)``,
i.e. the * the unique geodesic ``c(t)=γ_{p,X}(t)`` from ``γ_{p,d}(0)=p`` into direction ``\dot γ_{p,d}(0)=d``, of the tangent vector `X`.
By default this function calls [`parallel_transport_to`](@ref)`(M, p, X, q)`, where ``q=\exp_pX``.
"""
function parallel_transport_direction(M::AbstractManifold, p, X, d; kwargs...)
return parallel_transport_to(M, p, X, exp(M, p, d); kwargs...)
end
function parallel_transport_to! end
@doc raw"""
parallel_transport_to(M::AbstractManifold, p, X, q)
Compute the [`parallel_transport_along`](@ref) the curve ``c(t) = γ_{p,q}(t)``,
i.e. the (assumed to be unique) [`geodesic`](@ref) connecting `p` and `q`, of the tangent vector `X`.
"""
function parallel_transport_to(M::AbstractManifold, p, X, q; kwargs...)
Y = allocate_result(M, vector_transport_to, X, p, q)
return parallel_transport_to!(M, Y, p, X, q; kwargs...)
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 21658 |
"""
manifold_element_forwards(T, field::Symbol)
manifold_element_forwards(T, Twhere, field::Symbol)
Introduce basic fallbacks for type `T` (which can be a subtype of `Twhere`) that represents
points or vectors for a manifold.
Fallbacks will work by forwarding to the field passed in `field``
List of forwarded functions:
* [`allocate`](@ref),
* [`copy`](@ref),
* [`copyto!`](@ref),
* [`number_eltype`](@ref) (only for values, not the type itself),
* `similar`,
* `size`,
* `==`.
"""
macro manifold_element_forwards(T, field::Symbol)
return esc(quote
ManifoldsBase.@manifold_element_forwards ($T) _unused ($field)
end)
end
macro manifold_element_forwards(T, Twhere, field::Symbol)
TWT = if Twhere === :_unused
T
else
:($T where {$Twhere})
end
code = quote
function ManifoldsBase.number_eltype(p::$TWT)
return typeof(one(eltype(p.$field)))
end
Base.size(p::$TWT) = size(p.$field)
end
if Twhere === :_unused
push!(
code.args,
quote
ManifoldsBase.allocate(p::$T) = $T(allocate(p.$field))
function ManifoldsBase.allocate(p::$T, ::Type{P}) where {P}
return $T(allocate(p.$field, P))
end
function ManifoldsBase.allocate(p::$T, ::Type{P}, dims::Tuple) where {P}
return $T(allocate(p.$field, P, dims))
end
@inline Base.copy(p::$T) = $T(copy(p.$field))
function Base.copyto!(q::$T, p::$T)
copyto!(q.$field, p.$field)
return q
end
Base.similar(p::$T) = $T(similar(p.$field))
Base.similar(p::$T, ::Type{P}) where {P} = $T(similar(p.$field, P))
Base.:(==)(p::$T, q::$T) = (p.$field == q.$field)
end,
)
else
push!(
code.args,
quote
ManifoldsBase.allocate(p::$T) where {$Twhere} = $T(allocate(p.$field))
function ManifoldsBase.allocate(p::$T, ::Type{P}) where {P,$Twhere}
return $T(allocate(p.$field, P))
end
function ManifoldsBase.allocate(
p::$T,
::Type{P},
dims::Tuple,
) where {P,$Twhere}
return $T(allocate(p.$field, P, dims))
end
@inline Base.copy(p::$T) where {$Twhere} = $T(copy(p.$field))
function Base.copyto!(q::$T, p::$T) where {$Twhere}
copyto!(q.$field, p.$field)
return q
end
Base.similar(p::$T) where {$Twhere} = $T(similar(p.$field))
Base.similar(p::$T, ::Type{P}) where {P,$Twhere} = $T(similar(p.$field, P))
Base.:(==)(p::$T, q::$T) where {$Twhere} = (p.$field == q.$field)
end,
)
end
return esc(code)
end
"""
default_manifold_fallbacks(TM, TP, TV, pfield::Symbol, vfield::Symbol)
Introduce default fallbacks for all basic functions on manifolds, for manifold of type `TM`,
points of type `TP`, tangent vectors of type `TV`, with forwarding to fields `pfield` and
`vfield` for point and tangent vector functions, respectively.
"""
macro default_manifold_fallbacks(TM, TP, TV, pfield::Symbol, vfield::Symbol)
block = quote
function ManifoldsBase.allocate_result(::$TM, ::typeof(log), p::$TP, ::$TP)
a = allocate(p.$vfield)
return $TV(a)
end
function ManifoldsBase.allocate_result(
::$TM,
::typeof(inverse_retract),
p::$TP,
::$TP,
)
a = allocate(p.$vfield)
return $TV(a)
end
function ManifoldsBase.allocate_coordinates(M::$TM, p::$TP, T, n::Int)
return ManifoldsBase.allocate_coordinates(M, p.$pfield, T, n)
end
function ManifoldsBase.angle(M::$TM, p::$TP, X::$TV, Y::$TV)
return ManifoldsBase.angle(M, p.$pfield, X.$vfield, Y.$vfield)
end
function ManifoldsBase.check_point(M::$TM, p::$TP; kwargs...)
return ManifoldsBase.check_point(M, p.$pfield; kwargs...)
end
function ManifoldsBase.check_vector(M::$TM, p::$TP, X::$TV; kwargs...)
return ManifoldsBase.check_vector(M, p.$pfield, X.$vfield; kwargs...)
end
function ManifoldsBase.check_approx(M::$TM, p::$TP, q::$TP; kwargs...)
return ManifoldsBase.check_approx(M, p.$pfield, q.$pfield; kwargs...)
end
function ManifoldsBase.check_approx(M::$TM, p::$TP, X::$TV, Y::$TV; kwargs...)
return ManifoldsBase.check_approx(M, p.$pfield, X.$vfield, Y.$vfield; kwargs...)
end
function ManifoldsBase.distance(M::$TM, p::$TP, q::$TP)
return ManifoldsBase.distance(M, p.$pfield, q.$pfield)
end
function ManifoldsBase.embed!(M::$TM, q::$TP, p::$TP)
ManifoldsBase.embed!(M, q.$pfield, p.$pfield)
return q
end
function ManifoldsBase.embed!(M::$TM, Y::$TV, p::$TP, X::$TV)
ManifoldsBase.embed!(M, Y.$vfield, p.$pfield, X.$vfield)
return Y
end
function ManifoldsBase.exp!(M::$TM, q::$TP, p::$TP, X::$TV)
ManifoldsBase.exp!(M, q.$pfield, p.$pfield, X.$vfield)
return q
end
function ManifoldsBase.inner(M::$TM, p::$TP, X::$TV, Y::$TV)
return ManifoldsBase.inner(M, p.$pfield, X.$vfield, Y.$vfield)
end
function ManifoldsBase.inverse_retract!(
M::$TM,
X::$TV,
p::$TP,
q::$TP,
m::LogarithmicInverseRetraction,
)
ManifoldsBase.inverse_retract!(M, X.$vfield, p.$pfield, q.$pfield, m)
return X
end
function ManifoldsBase.isapprox(M::$TM, p::$TP, q::$TP; kwargs...)
return ManifoldsBase.isapprox(M, p.$pfield, q.$pfield; kwargs...)
end
function ManifoldsBase.isapprox(M::$TM, p::$TP, X::$TV, Y::$TV; kwargs...)
return ManifoldsBase.isapprox(M, p.$pfield, X.$vfield, Y.$vfield; kwargs...)
end
function ManifoldsBase.log!(M::$TM, X::$TV, p::$TP, q::$TP)
ManifoldsBase.log!(M, X.$vfield, p.$pfield, q.$pfield)
return X
end
function ManifoldsBase.norm(M::$TM, p::$TP, X::$TV)
return ManifoldsBase.norm(M, p.$pfield, X.$vfield)
end
function ManifoldsBase.retract!(
M::$TM,
q::$TP,
p::$TP,
X::$TV,
m::ExponentialRetraction,
)
ManifoldsBase.retract!(M, q.$pfield, p.$pfield, X.$vfield, m)
return q
end
function ManifoldsBase.vector_transport_along!(
M::$TM,
Y::$TV,
p::$TP,
X::$TV,
c::AbstractVector,
)
ManifoldsBase.vector_transport_along!(M, Y.$vfield, p.$pfield, X.$vfield, c)
return Y
end
function ManifoldsBase.zero_vector(M::$TM, p::$TP)
return $TV(zero_vector(M, p.$pfield))
end
function ManifoldsBase.zero_vector!(M::$TM, X::$TV, p::$TP)
ManifoldsBase.zero_vector!(M, X.$vfield, p.$pfield)
return X
end
end
for f_postfix in [:default, :orthogonal, :orthonormal, :vee, :cached, :diagonalizing]
ca = Symbol("get_coordinates_$(f_postfix)")
cm = Symbol("get_coordinates_$(f_postfix)!")
va = Symbol("get_vector_$(f_postfix)")
vm = Symbol("get_vector_$(f_postfix)!")
B_types = if f_postfix in [:default, :orthogonal, :orthonormal, :vee]
[:AbstractNumbers, :RealNumbers, :ComplexNumbers]
elseif f_postfix === :cached
[:CachedBasis]
elseif f_postfix === :diagonalizing
[:DiagonalizingOrthonormalBasis]
else
[:Any]
end
for B_type in B_types
push!(
block.args,
quote
function ManifoldsBase.$ca(M::$TM, p::$TP, X::$TV, B::$B_type)
return ManifoldsBase.$ca(M, p.$pfield, X.$vfield, B)
end
function ManifoldsBase.$cm(M::$TM, Y, p::$TP, X::$TV, B::$B_type)
ManifoldsBase.$cm(M, Y, p.$pfield, X.$vfield, B)
return Y
end
function ManifoldsBase.$va(M::$TM, p::$TP, X, B::$B_type)
return $TV(ManifoldsBase.$va(M, p.$pfield, X, B))
end
function ManifoldsBase.$vm(M::$TM, Y::$TV, p::$TP, X, B::$B_type)
ManifoldsBase.$vm(M, Y.$vfield, p.$pfield, X, B)
return Y
end
end,
)
end
end
for f_postfix in [:polar, :project, :qr, :softmax]
rm = Symbol("retract_$(f_postfix)!")
push!(
block.args,
quote
function ManifoldsBase.$rm(M::$TM, q, p::$TP, X::$TV, t::Number)
ManifoldsBase.$rm(M, q.$pfield, p.$pfield, X.$vfield, t)
return q
end
end,
)
end
push!(
block.args,
quote
function ManifoldsBase.retract_exp_ode!(
M::$TM,
q::$TP,
p::$TP,
X::$TV,
t::Number,
m::AbstractRetractionMethod,
B::ManifoldsBase.AbstractBasis,
)
ManifoldsBase.retract_exp_ode!(M, q.$pfield, p.$pfield, X.$vfield, t, m, B)
return q
end
function ManifoldsBase.retract_pade!(
M::$TM,
q::$TP,
p::$TP,
X::$TV,
t::Number,
m::PadeRetraction,
)
ManifoldsBase.retract_pade!(M, q.$pfield, p.$pfield, X.$vfield, t, m)
return q
end
function ManifoldsBase.retract_embedded!(
M::$TM,
q::$TP,
p::$TP,
X::$TV,
t::Number,
m::AbstractRetractionMethod,
)
ManifoldsBase.retract_embedded!(M, q.$pfield, p.$pfield, X.$vfield, t, m)
return q
end
function ManifoldsBase.retract_sasaki!(
M::$TM,
q::$TP,
p::$TP,
X::$TV,
t::Number,
m::SasakiRetraction,
)
ManifoldsBase.retract_sasaki!(M, q.$pfield, p.$pfield, X.$vfield, t, m)
return q
end
end,
)
for f_postfix in [:polar, :project, :qr, :softmax]
rm = Symbol("inverse_retract_$(f_postfix)!")
push!(block.args, quote
function ManifoldsBase.$rm(M::$TM, Y::$TV, p::$TP, q::$TP)
ManifoldsBase.$rm(M, Y.$vfield, p.$pfield, q.$pfield)
return Y
end
end)
end
push!(
block.args,
quote
function ManifoldsBase.inverse_retract_embedded!(
M::$TM,
X::$TV,
p::$TP,
q::$TP,
m::AbstractInverseRetractionMethod,
)
ManifoldsBase.inverse_retract_embedded!(
M,
X.$vfield,
p.$pfield,
q.$pfield,
m,
)
return X
end
function ManifoldsBase.inverse_retract_nlsolve!(
M::$TM,
X::$TV,
p::$TP,
q::$TP,
m::NLSolveInverseRetraction,
)
ManifoldsBase.inverse_retract_nlsolve!(
M,
X.$vfield,
p.$pfield,
q.$pfield,
m,
)
return X
end
end,
)
# forward vector transports
for sub in [:project, :diff, :embedded]
# project & diff
vtam = Symbol("vector_transport_along_$(sub)!")
vttm = Symbol("vector_transport_to_$(sub)!")
push!(
block.args,
quote
function ManifoldsBase.$vtam(
M::$TM,
Y::$TV,
p::$TP,
X::$TV,
c::AbstractVector,
)
ManifoldsBase.$vtam(M, Y.$vfield, p.$pfield, X.$vfield, c)
return Y
end
function ManifoldsBase.$vttm(M::$TM, Y::$TV, p::$TP, X::$TV, q::$TP)
ManifoldsBase.$vttm(M, Y.$vfield, p.$pfield, X.$vfield, q.$pfield)
return Y
end
end,
)
end
# parallel transports
push!(
block.args,
quote
function ManifoldsBase.parallel_transport_along(
M::$TM,
p::$TP,
X::$TV,
c::AbstractVector,
)
return $TV(
ManifoldsBase.parallel_transport_along(M, p.$pfield, X.$vfield, c),
)
end
function ManifoldsBase.parallel_transport_along!(
M::$TM,
Y::$TV,
p::$TP,
X::$TV,
c::AbstractVector,
)
ManifoldsBase.parallel_transport_along!(
M,
Y.$vfield,
p.$pfield,
X.$vfield,
c,
)
return Y
end
function ManifoldsBase.parallel_transport_direction(
M::$TM,
p::$TP,
X::$TV,
d::$TV,
)
return $TV(
ManifoldsBase.parallel_transport_direction(
M,
p.$pfield,
X.$vfield,
d.$vfield,
),
)
end
function ManifoldsBase.parallel_transport_direction!(
M::$TM,
Y::$TV,
p::$TP,
X::$TV,
d::$TV,
)
ManifoldsBase.parallel_transport_direction!(
M,
Y.$vfield,
p.$pfield,
X.$vfield,
d.$vfield,
)
return Y
end
function ManifoldsBase.parallel_transport_to(M::$TM, p::$TP, X::$TV, q::$TP)
return $TV(
ManifoldsBase.parallel_transport_to(M, p.$pfield, X.$vfield, q.$pfield),
)
end
function ManifoldsBase.parallel_transport_to!(
M::$TM,
Y::$TV,
p::$TP,
X::$TV,
q::$TP,
)
ManifoldsBase.parallel_transport_to!(
M,
Y.$vfield,
p.$pfield,
X.$vfield,
q.$pfield,
)
return Y
end
end,
)
return esc(block)
end
@doc raw"""
manifold_vector_forwards(T, field::Symbol)
manifold_vector_forwards(T, Twhere, field::Symbol)
Introduce basic fallbacks for type `T` that represents vectors from a vector bundle for a
manifold. `Twhere` is put into `where` clause of each method. Fallbacks work by forwarding
to field passed as `field`.
List of forwarded functions:
* basic arithmetic (`*`, `/`, `\`, `+`, `-`),
* all things from [`@manifold_element_forwards`](@ref),
* broadcasting support.
# example
@eval @manifold_vector_forwards ValidationFibreVector{TType} TType value
"""
macro manifold_vector_forwards(T, field::Symbol)
return esc(quote
ManifoldsBase.@manifold_vector_forwards ($T) _unused ($field)
end)
end
macro manifold_vector_forwards(T, Twhere, field::Symbol)
TWT = if Twhere === :_unused
T
else
:($T where {$Twhere})
end
code = quote
@eval ManifoldsBase.@manifold_element_forwards $T $Twhere $field
Base.axes(p::$TWT) = axes(p.$field)
Broadcast.broadcastable(X::$TWT) = X
Base.@propagate_inbounds function Broadcast._broadcast_getindex(X::$TWT, I)
return X.$field
end
end
broadcast_copyto_code = quote
axes(dest) == axes(bc) || Broadcast.throwdm(axes(dest), axes(bc))
# Performance optimization: broadcast!(identity, dest, A) is equivalent to copyto!(dest, A) if indices match
if bc.f === identity && bc.args isa Tuple{$T} # only a single input argument to broadcast!
A = bc.args[1]
if axes(dest) == axes(A)
return copyto!(dest, A)
end
end
bc′ = Broadcast.preprocess(dest, bc)
# Performance may vary depending on whether `@inbounds` is placed outside the
# for loop or not. (cf. https://github.com/JuliaLang/julia/issues/38086)
copyto!(dest.$field, bc′[1])
return dest
end
if Twhere === :_unused
push!(
code.args,
quote
Base.:*(X::$T, s::Number) = $T(X.$field * s)
Base.:*(s::Number, X::$T) = $T(s * X.$field)
Base.:/(X::$T, s::Number) = $T(X.$field / s)
Base.:\(s::Number, X::$T) = $T(s \ X.$field)
Base.:-(X::$T) = $T(-X.$field)
Base.:+(X::$T) = $T(X.$field)
Base.zero(X::$T) = $T(zero(X.$field))
Base.:+(X::$T, Y::$T) = $T(X.$field + Y.$field)
Base.:-(X::$T, Y::$T) = $T(X.$field - Y.$field)
function Broadcast.BroadcastStyle(::Type{<:$T})
return Broadcast.Style{$T}()
end
function Broadcast.BroadcastStyle(
::Broadcast.AbstractArrayStyle{0},
b::Broadcast.Style{$T},
)
return b
end
function Broadcast.instantiate(
bc::Broadcast.Broadcasted{Broadcast.Style{$T},Nothing},
)
return bc
end
function Broadcast.instantiate(
bc::Broadcast.Broadcasted{Broadcast.Style{$T}},
)
Broadcast.check_broadcast_axes(bc.axes, bc.args...)
return bc
end
@inline function Base.copy(bc::Broadcast.Broadcasted{Broadcast.Style{$T}})
return $T(Broadcast._broadcast_getindex(bc, 1))
end
@inline function Base.copyto!(
dest::$T,
bc::Broadcast.Broadcasted{Broadcast.Style{$T}},
)
return $broadcast_copyto_code
end
end,
)
else
push!(
code.args,
quote
Base.:*(X::$T, s::Number) where {$Twhere} = $T(X.$field * s)
Base.:*(s::Number, X::$T) where {$Twhere} = $T(s * X.$field)
Base.:/(X::$T, s::Number) where {$Twhere} = $T(X.$field / s)
Base.:\(s::Number, X::$T) where {$Twhere} = $T(s \ X.$field)
Base.:-(X::$T) where {$Twhere} = $T(-X.$field)
Base.:+(X::$T) where {$Twhere} = $T(X.$field)
Base.zero(X::$T) where {$Twhere} = $T(zero(X.$field))
Base.:+(X::$T, Y::$T) where {$Twhere} = $T(X.$field + Y.$field)
Base.:-(X::$T, Y::$T) where {$Twhere} = $T(X.$field - Y.$field)
function Broadcast.BroadcastStyle(::Type{<:$T}) where {$Twhere}
return Broadcast.Style{$T}()
end
function Broadcast.BroadcastStyle(
::Broadcast.AbstractArrayStyle{0},
b::Broadcast.Style{$T},
) where {$Twhere}
return b
end
function Broadcast.instantiate(
bc::Broadcast.Broadcasted{Broadcast.Style{$T},Nothing},
) where {$Twhere}
return bc
end
function Broadcast.instantiate(
bc::Broadcast.Broadcasted{Broadcast.Style{$T}},
) where {$Twhere}
Broadcast.check_broadcast_axes(bc.axes, bc.args...)
return bc
end
@inline function Base.copy(
bc::Broadcast.Broadcasted{Broadcast.Style{$T}},
) where {$Twhere}
return $T(Broadcast._broadcast_getindex(bc, 1))
end
@inline function Base.copyto!(
dest::$T,
bc::Broadcast.Broadcasted{Broadcast.Style{$T}},
) where {$Twhere}
return $broadcast_copyto_code
end
end,
)
end
return esc(code)
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 2998 | """
project(M::AbstractManifold, p)
Project point `p` from the ambient space of the [`AbstractManifold`](@ref) `M` to `M`.
This method is only available for manifolds where implicitly an embedding or ambient space
is given. Additionally, the projection includes changing data representation, if applicable,
i.e. if the points on `M` are not represented in the same array data, the data is changed
accordingly.
See also: [`EmbeddedManifold`](@ref), [`embed`](@ref embed(M::AbstractManifold, p))
"""
function project(M::AbstractManifold, p)
q = allocate_result(M, project, p)
project!(M, q, p)
return q
end
"""
project!(M::AbstractManifold, q, p)
Project point `p` from the ambient space onto the [`AbstractManifold`](@ref) `M`. The result is
storedin `q`.
This method is only available for manifolds where implicitly an embedding or ambient space
is given. Additionally, the projection includes changing data representation, if applicable,
i.e. if the points on `M` are not represented in the same array data, the data is changed
accordingly.
See also: [`EmbeddedManifold`](@ref), [`embed!`](@ref embed!(M::AbstractManifold, q, p))
"""
project!(::AbstractManifold, q, p)
"""
project(M::AbstractManifold, p, X)
Project ambient space representation of a vector `X` to a tangent vector at point `p` on
the [`AbstractManifold`](@ref) `M`.
This method is only available for manifolds where implicitly an embedding or ambient space
is given.
Additionally, `project` includes changing data representation, if applicable, i.e.
if the tangents on `M` are not represented in the same way as points on the embedding,
the representation is changed accordingly. This is the case for example for Lie groups,
when tangent vectors are represented in the Lie algebra. after projection the change to the
Lie algebra is perfomed, too.
See also: [`EmbeddedManifold`](@ref), [`embed`](@ref embed(M::AbstractManifold, p, X))
"""
function project(M::AbstractManifold, p, X)
# Note that the order is switched,
# since the allocation by default takes the type of the first.
Y = allocate_result(M, project, X, p)
project!(M, Y, p, X)
return Y
end
"""
project!(M::AbstractManifold, Y, p, X)
Project ambient space representation of a vector `X` to a tangent vector at point `p` on
the [`AbstractManifold`](@ref) `M`. The result is saved in vector `Y`.
This method is only available for manifolds where implicitly an embedding or ambient space
is given.
Additionally, `project!` includes changing data representation, if applicable, i.e.
if the tangents on `M` are not represented in the same way as points on the embedding,
the representation is changed accordingly. This is the case for example for Lie groups,
when tangent vectors are represented in the Lie algebra. after projection the change to the
Lie algebra is perfomed, too.
See also: [`EmbeddedManifold`](@ref), [`embed!`](@ref embed!(M::AbstractManifold, Y, p, X))
"""
project!(::AbstractManifold, Y, p, X)
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 30936 | """
AbstractInverseRetractionMethod <: AbstractApproximationMethod
Abstract type for methods for inverting a retraction (see [`inverse_retract`](@ref)).
"""
abstract type AbstractInverseRetractionMethod <: AbstractApproximationMethod end
"""
AbstractRetractionMethod <: AbstractApproximationMethod
Abstract type for methods for [`retract`](@ref)ing a tangent vector to a manifold.
"""
abstract type AbstractRetractionMethod <: AbstractApproximationMethod end
"""
ApproximateInverseRetraction <: AbstractInverseRetractionMethod
An abstract type for representing approximate inverse retraction methods.
"""
abstract type ApproximateInverseRetraction <: AbstractInverseRetractionMethod end
"""
ApproximateRetraction <: AbstractRetractionMethod
An abstract type for representing approximate retraction methods.
"""
abstract type ApproximateRetraction <: AbstractRetractionMethod end
@doc raw"""
EmbeddedRetraction{T<:AbstractRetractionMethod} <: AbstractRetractionMethod
Compute a retraction by using the retraction of type `T` in the embedding and projecting the result.
# Constructor
EmbeddedRetraction(r::AbstractRetractionMethod)
Generate the retraction with retraction `r` to use in the embedding.
"""
struct EmbeddedRetraction{T<:AbstractRetractionMethod} <: AbstractRetractionMethod
retraction::T
end
"""
ExponentialRetraction <: AbstractRetractionMethod
Retraction using the exponential map.
"""
struct ExponentialRetraction <: AbstractRetractionMethod end
@doc raw"""
ODEExponentialRetraction{T<:AbstractRetractionMethod, B<:AbstractBasis} <: AbstractRetractionMethod
Approximate the exponential map on the manifold by evaluating the ODE descripting the geodesic at 1,
assuming the default connection of the given manifold by solving the ordinary differential
equation
```math
\frac{d^2}{dt^2} p^k + Γ^k_{ij} \frac{d}{dt} p_i \frac{d}{dt} p_j = 0,
```
where ``Γ^k_{ij}`` are the Christoffel symbols of the second kind, and
the Einstein summation convention is assumed.
# Constructor
ODEExponentialRetraction(
r::AbstractRetractionMethod,
b::AbstractBasis=DefaultOrthogonalBasis(),
)
Generate the retraction with a retraction to use internally (for some approaches)
and a basis for the tangent space(s).
"""
struct ODEExponentialRetraction{T<:AbstractRetractionMethod,B<:AbstractBasis} <:
AbstractRetractionMethod
retraction::T
basis::B
end
function ODEExponentialRetraction(r::T) where {T<:AbstractRetractionMethod}
return ODEExponentialRetraction(r, DefaultOrthonormalBasis())
end
function ODEExponentialRetraction(::T, b::CachedBasis) where {T<:AbstractRetractionMethod}
return throw(
DomainError(
b,
"Cached Bases are currently not supported, since the basis has to be implemented in a surrounding of the start point as well.",
),
)
end
function ODEExponentialRetraction(r::ExponentialRetraction, ::AbstractBasis)
return throw(
DomainError(
r,
"You can not use the exponential map as an inner method to solve the ode for the exponential map.",
),
)
end
function ODEExponentialRetraction(r::ExponentialRetraction, ::CachedBasis)
return throw(
DomainError(
r,
"Neither the exponential map nor a Cached Basis can be used with this retraction type.",
),
)
end
"""
PolarRetraction <: AbstractRetractionMethod
Retractions that are based on singular value decompositions of the matrix / matrices
for point and tangent vectors.
!!! note "Technical Note"
Though you would call e.g. [`retract`](@ref)`(M, p, X, PolarRetraction())`,
to implement a polar retraction, define [`retract_polar!`](@ref)`(M, q, p, X, t)`
for your manifold `M`.
"""
struct PolarRetraction <: AbstractRetractionMethod end
"""
ProjectionRetraction <: AbstractRetractionMethod
Retractions that are based on projection and usually addition in the embedding.
!!! note "Technical Note"
Though you would call e.g. [`retract`](@ref)`(M, p, X, ProjectionRetraction())`,
to implement a projection retraction, define [`retract_project!`](@ref)`(M, q, p, X, t)` for your manifold `M`.
"""
struct ProjectionRetraction <: AbstractRetractionMethod end
"""
QRRetraction <: AbstractRetractionMethod
Retractions that are based on a QR decomposition of the
matrix / matrices for point and tangent vector on a [`AbstractManifold`](@ref)
!!! note "Technical Note"
Though you would call e.g. [`retract`](@ref)`(M, p, X, QRRetraction())`,
to implement a QR retraction, define [`retract_qr!`](@ref)`(M, q, p, X, t)` for your manifold `M`.
"""
struct QRRetraction <: AbstractRetractionMethod end
"""
RetractionWithKeywords{R<:AbstractRetractionMethod,K} <: AbstractRetractionMethod
Since retractions might have keywords, this type is a way to set them as an own type to be
used as a specific retraction.
Another reason for this type is that we dispatch on the retraction first and only the
last layer would be implemented with keywords, so this way they can be passed down.
## Fields
* `retraction` the retraction that is decorated with keywords
* `kwargs` the keyword arguments
Note that you can nest this type. Then the most outer specification of a keyword is used.
## Constructor
RetractionWithKeywords(m::T; kwargs...) where {T <: AbstractRetractionMethod}
Specify the subtype `T <: `[`AbstractRetractionMethod`](@ref) to have keywords `kwargs...`.
"""
struct RetractionWithKeywords{T<:AbstractRetractionMethod,K} <: AbstractRetractionMethod
retraction::T
kwargs::K
end
function RetractionWithKeywords(m::T; kwargs...) where {T<:AbstractRetractionMethod}
return RetractionWithKeywords{T,typeof(kwargs)}(m, kwargs)
end
@doc raw"""
struct SasakiRetraction <: AbstractRetractionMethod end
Exponential map on [`TangentBundle`](https://juliamanifolds.github.io/Manifolds.jl/stable/manifolds/vector_bundle.html#Manifolds.TangentBundle) computed via Euler integration as described
in [MuralidharanFletcher:2012](@cite). The system of equations for ``\gamma : ℝ \to T\mathcal M`` such that
``\gamma(1) = \exp_{p,X}(X_M, X_F)`` and ``\gamma(0)=(p, X)`` reads
```math
\dot{\gamma}(t) = (\dot{p}(t), \dot{X}(t)) = (R(X(t), \dot{X}(t))\dot{p}(t), 0)
```
where ``R`` is the Riemann curvature tensor (see [`riemann_tensor`](@ref)).
# Constructor
SasakiRetraction(L::Int)
In this constructor `L` is the number of integration steps.
"""
struct SasakiRetraction <: AbstractRetractionMethod
L::Int
end
"""
SoftmaxRetraction <: AbstractRetractionMethod
Describes a retraction that is based on the softmax function.
!!! note "Technical Note"
Though you would call e.g. [`retract`](@ref)`(M, p, X, SoftmaxRetraction())`,
to implement a softmax retraction, define [`retract_softmax!`](@ref)`(M, q, p, X, t)` for your manifold `M`.
"""
struct SoftmaxRetraction <: AbstractRetractionMethod end
@doc raw"""
PadeRetraction{m} <: AbstractRetractionMethod
A retraction based on the Padé approximation of order ``m``
# Constructor
PadeRetraction(m::Int)
!!! note "Technical Note"
Though you would call e.g. [`retract`](@ref)`(M, p, X, PadeRetraction(m))`,
to implement a Padé retraction, define [`retract_pade!`](@ref)`(M, q, p, X, t, m)` for your manifold `M`.
"""
struct PadeRetraction{m} <: AbstractRetractionMethod end
function PadeRetraction(m::Int)
(m < 1) && error(
"The Padé based retraction is only available for positive orders, not for order $m.",
)
return PadeRetraction{m}()
end
@doc raw"""
CayleyRetraction <: AbstractRetractionMethod
A retraction based on the Cayley transform, which is realized by using the
[`PadeRetraction`](@ref)`{1}`.
!!! note "Technical Note"
Though you would call e.g. [`retract`](@ref)`(M, p, X, CayleyRetraction())`,
to implement a caley retraction, define [`retract_cayley!`](@ref)`(M, q, p, X, t)` for your manifold `M`.
By default both these functions fall back to calling a [`PadeRetraction`](@ref)`(1)`.
"""
const CayleyRetraction = PadeRetraction{1}
@doc raw"""
EmbeddedInverseRetraction{T<:AbstractInverseRetractionMethod} <: AbstractInverseRetractionMethod
Compute an inverse retraction by using the inverse retraction of type `T` in the embedding and projecting the result
# Constructor
EmbeddedInverseRetraction(r::AbstractInverseRetractionMethod)
Generate the inverse retraction with inverse retraction `r` to use in the embedding.
"""
struct EmbeddedInverseRetraction{T<:AbstractInverseRetractionMethod} <:
AbstractInverseRetractionMethod
inverse_retraction::T
end
"""
LogarithmicInverseRetraction <: AbstractInverseRetractionMethod
Inverse retraction using the [`log`](@ref)arithmic map.
"""
struct LogarithmicInverseRetraction <: AbstractInverseRetractionMethod end
@doc raw"""
PadeInverseRetraction{m} <: AbstractInverseRetractionMethod
An inverse retraction based on the Padé approximation of order ``m`` for the retraction.
!!! note "Technical Note"
Though you would call e.g. [`inverse_retract`](@ref)`(M, p, q, PadeInverseRetraction(m))`,
to implement an inverse Padé retraction, define [`inverse_retract_pade!`](@ref)`(M, X, p, q, m)` for your manifold `M`.
"""
struct PadeInverseRetraction{m} <: AbstractInverseRetractionMethod end
function PadeInverseRetraction(m::Int)
(m < 1) && error(
"The Padé based inverse retraction is only available for positive orders, not for order $m.",
)
return PadeInverseRetraction{m}()
end
@doc raw"""
CayleyInverseRetraction <: AbstractInverseRetractionMethod
A retraction based on the Cayley transform, which is realized by using the
[`PadeRetraction`](@ref)`{1}`.
!!! note "Technical Note"
Though you would call e.g. [`inverse_retract`](@ref)`(M, p, q, CayleyInverseRetraction())`,
to implement an inverse caley retraction, define [`inverse_retract_cayley!`](@ref)`(M, X, p, q)` for your manifold `M`.
By default both these functions fall back to calling a [`PadeInverseRetraction`](@ref)`(1)`.
"""
const CayleyInverseRetraction = PadeInverseRetraction{1}
"""
PolarInverseRetraction <: AbstractInverseRetractionMethod
Inverse retractions that are based on a singular value decomposition of the
matrix / matrices for point and tangent vector on a [`AbstractManifold`](@ref)
!!! note "Technical Note"
Though you would call e.g. [`inverse_retract`](@ref)`(M, p, q, PolarInverseRetraction())`,
to implement an inverse polar retraction, define [`inverse_retract_polar!`](@ref)`(M, X, p, q)` for your manifold `M`.
"""
struct PolarInverseRetraction <: AbstractInverseRetractionMethod end
"""
ProjectionInverseRetraction <: AbstractInverseRetractionMethod
Inverse retractions that are based on a projection (or its inversion).
!!! note "Technical Note"
Though you would call e.g. [`inverse_retract`](@ref)`(M, p, q, ProjectionInverseRetraction())`,
to implement an inverse projection retraction, define [`inverse_retract_project!`](@ref)`(M, X, p, q)` for your manifold `M`.
"""
struct ProjectionInverseRetraction <: AbstractInverseRetractionMethod end
"""
QRInverseRetraction <: AbstractInverseRetractionMethod
Inverse retractions that are based on a QR decomposition of the
matrix / matrices for point and tangent vector on a [`AbstractManifold`](@ref)
!!! note "Technical Note"
Though you would call e.g. [`inverse_retract`](@ref)`(M, p, q, QRInverseRetraction())`,
to implement an inverse QR retraction, define [`inverse_retract_qr!`](@ref)`(M, X, p, q)` for your manifold `M`.
"""
struct QRInverseRetraction <: AbstractInverseRetractionMethod end
"""
NLSolveInverseRetraction{T<:AbstractRetractionMethod,TV,TK} <:
ApproximateInverseRetraction
An inverse retraction method for approximating the inverse of a retraction using `NLsolve`.
# Constructor
NLSolveInverseRetraction(
method::AbstractRetractionMethod[, X0];
project_tangent=false,
project_point=false,
nlsolve_kwargs...,
)
Constructs an approximate inverse retraction for the retraction `method` with initial guess
`X0`, defaulting to the zero vector. If `project_tangent` is `true`, then the tangent
vector is projected before the retraction using `project`. If `project_point` is `true`,
then the resulting point is projected after the retraction. `nlsolve_kwargs` are keyword
arguments passed to `NLsolve.nlsolve`.
"""
struct NLSolveInverseRetraction{TR<:AbstractRetractionMethod,TV,TK} <:
ApproximateInverseRetraction
retraction::TR
X0::TV
project_tangent::Bool
project_point::Bool
nlsolve_kwargs::TK
function NLSolveInverseRetraction(m, X0, project_point, project_tangent, nlsolve_kwargs)
return new{typeof(m),typeof(X0),typeof(nlsolve_kwargs)}(
m,
X0,
project_point,
project_tangent,
nlsolve_kwargs,
)
end
end
function NLSolveInverseRetraction(
m,
X0 = nothing;
project_tangent::Bool = false,
project_point::Bool = false,
nlsolve_kwargs...,
)
return NLSolveInverseRetraction(m, X0, project_point, project_tangent, nlsolve_kwargs)
end
"""
InverseRetractionWithKeywords{R<:AbstractRetractionMethod,K} <: AbstractInverseRetractionMethod
Since inverse retractions might have keywords, this type is a way to set them as an own type to be
used as a specific inverse retraction.
Another reason for this type is that we dispatch on the inverse retraction first and only the
last layer would be implemented with keywords, so this way they can be passed down.
## Fields
* `inverse_retraction` the inverse retraction that is decorated with keywords
* `kwargs` the keyword arguments
Note that you can nest this type. Then the most outer specification of a keyword is used.
## Constructor
InverseRetractionWithKeywords(m::T; kwargs...) where {T <: AbstractInverseRetractionMethod}
Specify the subtype `T <: `[`AbstractInverseRetractionMethod`](@ref) to have keywords `kwargs...`.
"""
struct InverseRetractionWithKeywords{T<:AbstractInverseRetractionMethod,K} <:
AbstractInverseRetractionMethod
inverse_retraction::T
kwargs::K
end
function InverseRetractionWithKeywords(
m::T;
kwargs...,
) where {T<:AbstractInverseRetractionMethod}
return InverseRetractionWithKeywords{T,typeof(kwargs)}(m, kwargs)
end
"""
SoftmaxInverseRetraction <: AbstractInverseRetractionMethod
Describes an inverse retraction that is based on the softmax function.
!!! note "Technical Note"
Though you would call e.g. [`inverse_retract`](@ref)`(M, p, q, SoftmaxInverseRetraction())`,
to implement an inverse softmax retraction, define [`inverse_retract_softmax!`](@ref)`(M, X, p, q)` for your manifold `M`.
"""
struct SoftmaxInverseRetraction <: AbstractInverseRetractionMethod end
"""
default_inverse_retraction_method(M::AbstractManifold)
default_inverse_retraction_method(M::AbstractManifold, ::Type{T}) where {T}
The [`AbstractInverseRetractionMethod`](@ref) that is used when calling
[`inverse_retract`](@ref) without specifying the inverse retraction method.
By default, this is the [`LogarithmicInverseRetraction`](@ref).
This method can also be specified more precisely with a point type `T`, for the case
that on a `M` there are two different representations of points, which provide
different inverse retraction methods.
"""
default_inverse_retraction_method(::AbstractManifold) = LogarithmicInverseRetraction()
function default_inverse_retraction_method(M::AbstractManifold, ::Type{T}) where {T}
return default_inverse_retraction_method(M)
end
"""
default_retraction_method(M::AbstractManifold)
default_retraction_method(M::AbstractManifold, ::Type{T}) where {T}
The [`AbstractRetractionMethod`](@ref) that is used when calling [`retract`](@ref) without
specifying the retraction method. By default, this is the [`ExponentialRetraction`](@ref).
This method can also be specified more precisely with a point type `T`, for the case
that on a `M` there are two different representations of points, which provide
different retraction methods.
"""
default_retraction_method(::AbstractManifold) = ExponentialRetraction()
function default_retraction_method(M::AbstractManifold, ::Type{T}) where {T}
return default_retraction_method(M)
end
"""
inverse_retract(M::AbstractManifold, p, q)
inverse_retract(M::AbstractManifold, p, q, method::AbstractInverseRetractionMethod
Compute the inverse retraction, a cheaper, approximate version of the
[`log`](@ref)arithmic map), of points `p` and `q` on the [`AbstractManifold`](@ref) `M`.
Inverse retraction method can be specified by the last argument, defaulting to
[`default_inverse_retraction_method`](@ref)`(M)`.
For available inverse retractions on certain manifolds see the documentation on the
corresponding manifold.
See also [`retract`](@ref).
"""
function inverse_retract(
M::AbstractManifold,
p,
q,
m::AbstractInverseRetractionMethod = default_inverse_retraction_method(M, typeof(p)),
)
return _inverse_retract(M, p, q, m)
end
function _inverse_retract(M::AbstractManifold, p, q, ::LogarithmicInverseRetraction)
return log(M, p, q)
end
function _inverse_retract(M::AbstractManifold, p, q, m::AbstractInverseRetractionMethod)
X = allocate_result(M, inverse_retract, p, q)
return inverse_retract!(M, X, p, q, m)
end
"""
inverse_retract!(M::AbstractManifold, X, p, q[, method::AbstractInverseRetractionMethod])
Compute the inverse retraction, a cheaper, approximate version of the
[`log`](@ref)arithmic map), of points `p` and `q` on the [`AbstractManifold`](@ref) `M`.
Result is saved to `X`.
Inverse retraction method can be specified by the last argument, defaulting to
[`default_inverse_retraction_method`](@ref)`(M)`. See the documentation of respective manifolds for
available methods.
See also [`retract!`](@ref).
"""
function inverse_retract!(
M::AbstractManifold,
X,
p,
q,
m::AbstractInverseRetractionMethod = default_inverse_retraction_method(M, typeof(p)),
)
return _inverse_retract!(M, X, p, q, m)
end
function _inverse_retract!(
M::AbstractManifold,
X,
p,
q,
::LogarithmicInverseRetraction;
kwargs...,
)
return log!(M, X, p, q; kwargs...)
end
#
# dispatch to lower level
function _inverse_retract!(
M::AbstractManifold,
X,
p,
q,
::CayleyInverseRetraction;
kwargs...,
)
return inverse_retract_cayley!(M, X, p, q; kwargs...)
end
function _inverse_retract!(
M::AbstractManifold,
X,
p,
q,
m::EmbeddedInverseRetraction;
kwargs...,
)
return inverse_retract_embedded!(M, X, p, q, m.inverse_retraction; kwargs...)
end
function _inverse_retract!(
M::AbstractManifold,
X,
p,
q,
m::NLSolveInverseRetraction;
kwargs...,
)
return inverse_retract_nlsolve!(M, X, p, q, m; kwargs...)
end
function _inverse_retract!(
M::AbstractManifold,
X,
p,
q,
m::PadeInverseRetraction;
kwargs...,
)
return inverse_retract_pade!(M, X, p, q, m; kwargs...)
end
function _inverse_retract!(
M::AbstractManifold,
X,
p,
q,
::PolarInverseRetraction;
kwargs...,
)
return inverse_retract_polar!(M, X, p, q; kwargs...)
end
function _inverse_retract!(
M::AbstractManifold,
X,
p,
q,
::ProjectionInverseRetraction;
kwargs...,
)
return inverse_retract_project!(M, X, p, q; kwargs...)
end
function _inverse_retract!(M::AbstractManifold, X, p, q, ::QRInverseRetraction; kwargs...)
return inverse_retract_qr!(M, X, p, q; kwargs...)
end
function _inverse_retract!(
M::AbstractManifold,
X,
p,
q,
m::InverseRetractionWithKeywords;
kwargs...,
)
return _inverse_retract!(M, X, p, q, m.inverse_retraction; kwargs..., m.kwargs...)
end
function _inverse_retract!(
M::AbstractManifold,
X,
p,
q,
::SoftmaxInverseRetraction;
kwargs...,
)
return inverse_retract_softmax!(M, X, p, q; kwargs...)
end
"""
inverse_retract_embedded!(M::AbstractManifold, X, p, q, m::AbstractInverseRetractionMethod)
Compute the in-place variant of the [`EmbeddedInverseRetraction`](@ref) using
the [`AbstractInverseRetractionMethod`](@ref) `m` in the embedding (see [`get_embedding`](@ref))
and projecting the result back.
"""
function inverse_retract_embedded!(
M::AbstractManifold,
X,
p,
q,
m::AbstractInverseRetractionMethod,
)
return project!(
M,
X,
p,
inverse_retract(
get_embedding(M),
embed(get_embedding(M), p),
embed(get_embedding(M), q),
m,
),
)
end
"""
inverse_retract_cayley!(M::AbstractManifold, X, p, q)
Compute the in-place variant of the [`CayleyInverseRetraction`](@ref),
which by default calls the first order [`PadeInverseRetraction`§(@ref).
"""
function inverse_retract_cayley!(M::AbstractManifold, X, p, q; kwargs...)
return inverse_retract_pade!(M, X, p, q, 1; kwargs...)
end
"""
inverse_retract_pade!(M::AbstractManifold, p, q, n)
Compute the in-place variant of the [`PadeInverseRetraction`](@ref)`(n)`,
"""
inverse_retract_pade!(M::AbstractManifold, p, q, n)
function inverse_retract_pade! end
"""
inverse_retract_qr!(M::AbstractManifold, X, p, q)
Compute the in-place variant of the [`QRInverseRetraction`](@ref).
"""
inverse_retract_qr!(M::AbstractManifold, X, p, q)
function inverse_retract_qr! end
"""
inverse_retract_project!(M::AbstractManifold, X, p, q)
Compute the in-place variant of the [`ProjectionInverseRetraction`](@ref).
"""
inverse_retract_project!(M::AbstractManifold, X, p, q)
function inverse_retract_project! end
"""
inverse_retract_polar!(M::AbstractManifold, X, p, q)
Compute the in-place variant of the [`PolarInverseRetraction`](@ref).
"""
inverse_retract_polar!(M::AbstractManifold, X, p, q)
function inverse_retract_polar! end
"""
inverse_retract_nlsolve!(M::AbstractManifold, X, p, q, m::NLSolveInverseRetraction)
Compute the in-place variant of the [`NLSolveInverseRetraction`](@ref) `m`.
"""
inverse_retract_nlsolve!(M::AbstractManifold, X, p, q, m::NLSolveInverseRetraction)
function inverse_retract_nlsolve! end
"""
inverse_retract_softmax!(M::AbstractManifold, X, p, q)
Compute the in-place variant of the [`SoftmaxInverseRetraction`](@ref).
"""
inverse_retract_softmax!(M::AbstractManifold, X, p, q)
function inverse_retract_softmax! end
@doc raw"""
retract(M::AbstractManifold, p, X, method::AbstractRetractionMethod=default_retraction_method(M, typeof(p)))
retract(M::AbstractManifold, p, X, t::Number=1, method::AbstractRetractionMethod=default_retraction_method(M, typeof(p)))
Compute a retraction, a cheaper, approximate version of the [`exp`](@ref)onential map,
from `p` into direction `X`, scaled by `t`, on the [`AbstractManifold`](@ref) `M`.
A retraction ``\operatorname{retr}_p: T_p\mathcal M → \mathcal M`` is a smooth map that fulfils
1. ``\operatorname{retr}_p(0) = p``
2. ``D\operatorname{retr}_p(0): T_p\mathcal M \to T_p\mathcal M`` is the identity map,
i.e. ``D\operatorname{retr}_p(0)[X]=X`` holds for all ``X\in T_p\mathcal M``,
where ``D\operatorname{retr}_p`` denotes the differential of the retraction
The retraction is called of second order if for all ``X`` the curves ``c(t) = R_p(tX)``
have a zero acceleration at ``t=0``, i.e. ``c''(0) = 0``.
Retraction method can be specified by the last argument, defaulting to
[`default_retraction_method`](@ref)`(M)`. For further available retractions see the documentation of respective manifolds.
Locally, the retraction is invertible. For the inverse operation, see [`inverse_retract`](@ref).
"""
function retract(
M::AbstractManifold,
p,
X,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
return _retract(M, p, X, one(number_eltype(X)), m)
end
function retract(
M::AbstractManifold,
p,
X,
t::Number,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
return _retract(M, p, X, t, m)
end
function _retract(M::AbstractManifold, p, X, t::Number, ::ExponentialRetraction)
return exp(M, p, X, t)
end
function _retract(M::AbstractManifold, p, X, t, m::AbstractRetractionMethod)
q = allocate_result(M, retract, p, X)
return retract!(M, q, p, X, t, m)
end
"""
retract!(M::AbstractManifold, q, p, X)
retract!(M::AbstractManifold, q, p, X, t::Real=1)
retract!(M::AbstractManifold, q, p, X, method::AbstractRetractionMethod)
retract!(M::AbstractManifold, q, p, X, t::Real=1, method::AbstractRetractionMethod)
Compute a retraction, a cheaper, approximate version of the [`exp`](@ref)onential map,
from `p` into direction `X`, scaled by `t`, on the [`AbstractManifold`](@ref) manifold `M`.
Result is saved to `q`.
Retraction method can be specified by the last argument, defaulting to
[`default_retraction_method`](@ref)`(M)`. See the documentation of respective manifolds for available
methods.
See [`retract`](@ref) for more details.
"""
function retract!(
M::AbstractManifold,
q,
p,
X,
t::Number,
m::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
return _retract!(M, q, p, X, t, m)
end
function retract!(
M::AbstractManifold,
q,
p,
X,
method::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
)
return retract!(M, q, p, X, one(number_eltype(X)), method)
end
# dispatch to lower level
function _retract!(M::AbstractManifold, q, p, X, t, ::CayleyRetraction; kwargs...)
return retract_cayley!(M, q, p, X, t; kwargs...)
end
function _retract!(M::AbstractManifold, q, p, X, t, m::EmbeddedRetraction; kwargs...)
return retract_embedded!(M, q, p, X, t, m.retraction; kwargs...)
end
function _retract!(M::AbstractManifold, q, p, X, t, ::ExponentialRetraction; kwargs...)
return exp!(M, q, p, X, t; kwargs...)
end
function _retract!(M::AbstractManifold, q, p, X, t, m::ODEExponentialRetraction; kwargs...)
return retract_exp_ode!(M, q, p, X, t, m.retraction, m.basis; kwargs...)
end
function _retract!(M::AbstractManifold, q, p, X, t, ::PolarRetraction; kwargs...)
return retract_polar!(M, q, p, X, t; kwargs...)
end
function _retract!(M::AbstractManifold, q, p, X, t, ::ProjectionRetraction; kwargs...)
return retract_project!(M, q, p, X, t; kwargs...)
end
function _retract!(M::AbstractManifold, q, p, X, t, ::QRRetraction; kwargs...)
return retract_qr!(M, q, p, X, t; kwargs...)
end
function _retract!(M::AbstractManifold, q, p, X, t::Number, m::SasakiRetraction)
return retract_sasaki!(M, q, p, X, t, m)
end
function _retract!(M::AbstractManifold, q, p, X, t::Number, ::SoftmaxRetraction; kwargs...)
return retract_softmax!(M, q, p, X, t; kwargs...)
end
function _retract!(M::AbstractManifold, q, p, X, t, m::PadeRetraction; kwargs...)
return retract_pade!(M, q, p, X, t, m; kwargs...)
end
function _retract!(M::AbstractManifold, q, p, X, t, m::RetractionWithKeywords; kwargs...)
return _retract!(M, q, p, X, t, m.retraction; kwargs..., m.kwargs...)
end
"""
retract_embedded!(M::AbstractManifold, q, p, X, t, m::AbstractRetractionMethod)
Compute the in-place variant of the [`EmbeddedRetraction`](@ref) using
the [`AbstractRetractionMethod`](@ref) `m` in the embedding (see [`get_embedding`](@ref))
and projecting the result back.
"""
function retract_embedded!(
M::AbstractManifold,
q,
p,
X,
t,
m::AbstractRetractionMethod;
kwargs...,
)
return project!(
M,
q,
retract(
get_embedding(M),
embed(get_embedding(M), p),
embed(get_embedding(M), p, X),
t,
m;
kwargs...,
),
)
end
"""
retract_cayley!(M::AbstractManifold, q, p, X, t)
Compute the in-place variant of the [`CayleyRetraction`](@ref),
which by default falls back to calling the first order [`PadeRetraction`](@ref).
"""
function retract_cayley!(M::AbstractManifold, q, p, X, t; kwargs...)
return retract_pade!(M, q, p, X, t, PadeRetraction(1); kwargs...)
end
"""
retract_exp_ode!(M::AbstractManifold, q, p, X, t, m::AbstractRetractionMethod, B::AbstractBasis)
Compute the in-place variant of the [`ODEExponentialRetraction`](@ref)`(m, B)`.
"""
function retract_exp_ode!(
M::AbstractManifold,
q,
p,
X,
t,
m::AbstractRetractionMethod,
B::AbstractBasis,
)
return retract_exp_ode!(
M::AbstractManifold,
q,
p,
t * X,
m::AbstractRetractionMethod,
B::AbstractBasis,
)
end
"""
retract_pade!(M::AbstractManifold, q, p, X, t, m::PadeRetraction)
Compute the in-place variant of the [`PadeRetraction`](@ref) `m`.
"""
function retract_pade!(M::AbstractManifold, q, p, X, t, m::PadeRetraction)
return retract_pade!(M, q, p, t * X)
end
"""
retract_project!(M::AbstractManifold, q, p, X, t)
Compute the in-place variant of the [`ProjectionRetraction`](@ref).
"""
function retract_project!(M::AbstractManifold, q, p, X, t)
return retract_project!(M, q, p, t * X)
end
"""
retract_polar!(M::AbstractManifold, q, p, X, t)
Compute the in-place variant of the [`PolarRetraction`](@ref).
"""
function retract_polar!(M::AbstractManifold, q, p, X, t)
return retract_polar!(M, q, p, t * X)
end
"""
retract_qr!(M::AbstractManifold, q, p, X, t)
Compute the in-place variant of the [`QRRetraction`](@ref).
"""
function retract_qr!(M::AbstractManifold, q, p, X, t)
return retract_qr!(M, q, p, t * X)
end
"""
retract_softmax!(M::AbstractManifold, q, p, X, t)
Compute the in-place variant of the [`SoftmaxRetraction`](@ref).
"""
function retract_softmax!(M::AbstractManifold, q, p, X, t::Number)
return retract_softmax!(M, q, p, t * X)
end
"""
retract_sasaki!(M::AbstractManifold, q, p, X, t::Number, m::SasakiRetraction)
Compute the in-place variant of the [`SasakiRetraction`](@ref) `m`.
"""
retract_sasaki!(M::AbstractManifold, q, p, X, t::Number, m::SasakiRetraction)
function retract_sasaki! end
Base.show(io::IO, ::CayleyRetraction) = print(io, "CayleyRetraction()")
Base.show(io::IO, ::PadeRetraction{m}) where {m} = print(io, "PadeRetraction($m)")
#
# default estimation methods pass down with and without the point type
function default_approximation_method(M::AbstractManifold, ::typeof(inverse_retract))
return default_inverse_retraction_method(M)
end
function default_approximation_method(M::AbstractManifold, ::typeof(inverse_retract), T)
return default_inverse_retraction_method(M, T)
end
function default_approximation_method(M::AbstractManifold, ::typeof(retract))
return default_retraction_method(M)
end
function default_approximation_method(M::AbstractManifold, ::typeof(retract), T)
return default_retraction_method(M, T)
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 3297 | """
ShootingInverseRetraction <: ApproximateInverseRetraction
Approximating the inverse of a retraction using the shooting method.
This implementation of the shooting method works by using another inverse retraction to form
the first guess of the vector. This guess is updated by shooting the vector, guessing the
vector pointing from the shooting result to the target point, and transporting this vector
update back to the initial point on a discretized grid. This process is repeated until the
norm of the vector update falls below a specified tolerance or the maximum number of
iterations is reached.
# Fields
- `retraction::AbstractRetractionMethod`: The retraction whose inverse is approximated.
- `initial_inverse_retraction::AbstractInverseRetractionMethod`: The inverse retraction used
to form the initial guess of the vector.
- `vector_transport::AbstractVectorTransportMethod`: The vector transport used to transport
the initial guess of the vector.
- `num_transport_points::Int`: The number of discretization points used for vector
transport in the shooting method. 2 is the minimum number of points, including just the
endpoints.
- `tolerance::Real`: The tolerance for the shooting method.
- `max_iterations::Int`: The maximum number of iterations for the shooting method.
"""
struct ShootingInverseRetraction{
R<:AbstractRetractionMethod,
IR<:AbstractInverseRetractionMethod,
VT<:AbstractVectorTransportMethod,
T<:Real,
} <: ApproximateInverseRetraction
retraction::R
initial_inverse_retraction::IR
vector_transport::VT
num_transport_points::Int
tolerance::T
max_iterations::Int
end
function _inverse_retract!(M::AbstractManifold, X, p, q, m::ShootingInverseRetraction)
return inverse_retract_shooting!(M, X, p, q, m)
end
"""
inverse_retract_shooting!(M::AbstractManifold, X, p, q, m::ShootingInverseRetraction)
Approximate the inverse of a retraction using the shooting method.
"""
function inverse_retract_shooting!(
M::AbstractManifold,
X,
p,
q,
m::ShootingInverseRetraction,
)
inverse_retract!(M, X, p, q, m.initial_inverse_retraction)
gap = norm(M, p, X)
gap < m.tolerance && return X
T = real(Base.promote_type(number_eltype(X), number_eltype(p), number_eltype(q)))
transport_grid = range(one(T), zero(T); length = m.num_transport_points)[2:(end - 1)]
ΔX = allocate(X)
ΔXnew = tX = allocate(ΔX)
retr_tX = allocate_result(M, retract, p, X)
if m.num_transport_points > 2
retr_tX_new = allocate_result(M, retract, p, X)
end
iteration = 1
while (gap > m.tolerance) && (iteration < m.max_iterations)
retract!(M, retr_tX, p, X, m.retraction)
inverse_retract!(M, ΔX, retr_tX, q, m.initial_inverse_retraction)
gap = norm(M, retr_tX, ΔX)
for t in transport_grid
tX .= t .* X
retract!(M, retr_tX_new, p, tX, m.retraction)
vector_transport_to!(M, ΔXnew, retr_tX, ΔX, retr_tX_new, m.vector_transport)
# realias storage
retr_tX, retr_tX_new, ΔX, ΔXnew, tX = retr_tX_new, retr_tX, ΔXnew, ΔX, ΔX
end
vector_transport_to!(M, ΔXnew, retr_tX, ΔX, p, m.vector_transport)
X .+= ΔXnew
iteration += 1
end
return X
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 4417 |
"""
FVector(type::VectorSpaceType, data, basis::AbstractBasis)
Decorator indicating that the vector `data` contains coordinates of a vector from a fiber
of a vector bundle of type `type`. `basis` is an object describing the basis of that space
in which the coordinates are given.
Conversion between `FVector` representation and the default representation of an object
(for example a tangent vector) for a manifold should be done using [`get_coordinates`](@ref)
and [`get_vector`](@ref).
# Examples
```julia-repl
julia> using Manifolds
julia> M = Sphere(2)
Sphere(2, ℝ)
julia> p = [1.0, 0.0, 0.0]
3-element Vector{Float64}:
1.0
0.0
0.0
julia> X = [0.0, 2.0, -1.0]
3-element Vector{Float64}:
0.0
2.0
-1.0
julia> B = DefaultOrthonormalBasis()
DefaultOrthonormalBasis(ℝ)
julia> fX = TFVector(get_coordinates(M, p, X, B), B)
TFVector([2.0, -1.0], DefaultOrthonormalBasis(ℝ))
julia> X_back = get_vector(M, p, fX.data, fX.basis)
3-element Vector{Float64}:
-0.0
2.0
-1.0
```
"""
struct FVector{TType<:VectorSpaceType,TData,TBasis<:AbstractBasis}
type::TType
data::TData
basis::TBasis
end
const TFVector = FVector{TangentSpaceType}
const CoTFVector = FVector{CotangentSpaceType}
function TFVector(data, basis::AbstractBasis)
return TFVector{typeof(data),typeof(basis)}(TangentSpaceType(), data, basis)
end
function CoTFVector(data, basis::AbstractBasis)
return CoTFVector{typeof(data),typeof(basis)}(CotangentSpaceType(), data, basis)
end
function Base.show(io::IO, fX::TFVector)
return print(io, "TFVector(", fX.data, ", ", fX.basis, ")")
end
function Base.show(io::IO, fX::CoTFVector)
return print(io, "CoTFVector(", fX.data, ", ", fX.basis, ")")
end
"""
AbstractFibreVector{TType<:VectorSpaceType}
Type for a vector from a vector space (fibre of a vector bundle) of type `TType` of a manifold.
While a [`AbstractManifold`](@ref) does not necessarily require this type, for example when it is
implemented for `Vector`s or `Matrix` type elements, this type can be used for more
complicated representations, semantic verification, or even dispatch for different
representations of tangent vectors and their types on a manifold.
You may use macro [`@manifold_vector_forwards`](@ref) to introduce commonly used method
definitions for your subtype of `AbstractFibreVector`.
"""
abstract type AbstractFibreVector{TType<:VectorSpaceType} end
"""
TVector = AbstractFibreVector{TangentSpaceType}
Type for a tangent vector of a manifold. While a [`AbstractManifold`](@ref) does not necessarily
require this type, for example when it is implemented for `Vector`s or `Matrix` type
elements, this type can be used for more complicated representations, semantic verification,
or even dispatch for different representations of tangent vectors and their types on a
manifold.
"""
const TVector = AbstractFibreVector{TangentSpaceType}
"""
CoTVector = AbstractFibreVector{CotangentSpaceType}
Type for a cotangent vector of a manifold. While a [`AbstractManifold`](@ref) does not necessarily
require this type, for example when it is implemented for `Vector`s or `Matrix` type
elements, this type can be used for more complicated representations, semantic verification,
or even dispatch for different representations of cotangent vectors and their types on a
manifold.
"""
const CoTVector = AbstractFibreVector{CotangentSpaceType}
Base.:+(X::FVector, Y::FVector) = FVector(X.type, X.data + Y.data, X.basis)
Base.:-(X::FVector, Y::FVector) = FVector(X.type, X.data - Y.data, X.basis)
Base.:-(X::FVector) = FVector(X.type, -X.data, X.basis)
Base.:*(a::Number, X::FVector) = FVector(X.type, a * X.data, X.basis)
allocate(x::FVector) = FVector(x.type, allocate(x.data), x.basis)
allocate(x::FVector, ::Type{T}) where {T} = FVector(x.type, allocate(x.data, T), x.basis)
function Base.copyto!(X::FVector, Y::FVector)
copyto!(X.data, Y.data)
return X
end
function number_eltype(
::Type{FVector{TType,TData,TBasis}},
) where {TType<:VectorSpaceType,TData,TBasis}
return number_eltype(TData)
end
number_eltype(v::FVector) = number_eltype(v.data)
"""
vector_space_dimension(M::AbstractManifold, V::VectorSpaceType)
Dimension of the vector space of type `V` on manifold `M`.
"""
vector_space_dimension(::AbstractManifold, ::VectorSpaceType)
function vector_space_dimension(M::AbstractManifold, ::TCoTSpaceType)
return manifold_dimension(M)
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 41048 |
"""
AbstractVectorTransportMethod <: AbstractApproximationMethod
Abstract type for methods for transporting vectors. Such vector transports are not
necessarily linear.
# See also
[`AbstractLinearVectorTransportMethod`](@ref)
"""
abstract type AbstractVectorTransportMethod <: AbstractApproximationMethod end
"""
AbstractLinearVectorTransportMethod <: AbstractVectorTransportMethod
Abstract type for linear methods for transporting vectors, that is transport of a linear
combination of vectors is a linear combination of transported vectors.
"""
abstract type AbstractLinearVectorTransportMethod <: AbstractVectorTransportMethod end
@doc raw"""
DifferentiatedRetractionVectorTransport{R<:AbstractRetractionMethod} <:
AbstractVectorTransportMethod
A type to specify a vector transport that is given by differentiating a retraction.
This can be introduced in two ways. Let ``\mathcal M`` be a Riemannian manifold,
``p∈\mathcal M`` a point, and ``X,Y∈ T_p\mathcal M`` denote two tangent vectors at ``p``.
Given a retraction (cf. [`AbstractRetractionMethod`](@ref)) ``\operatorname{retr}``,
the vector transport of `X` in direction `Y` (cf. [`vector_transport_direction`](@ref))
by differentiation this retraction, is given by
```math
\mathcal T^{\operatorname{retr}}_{p,Y}X
= D_Y\operatorname{retr}_p(Y)[X]
= \frac{\mathrm{d}}{\mathrm{d}t}\operatorname{retr}_p(Y+tX)\Bigr|_{t=0}.
```
see [AbsilMahonySepulchre:2008](@cite), Section 8.1.2 for more details.
This can be phrased similarly as a [`vector_transport_to`](@ref) by introducing
``q=\operatorname{retr}_pX`` and defining
```math
\mathcal T^{\operatorname{retr}}_{q \gets p}X = \mathcal T^{\operatorname{retr}}_{p,Y}X
```
which in practice usually requires the [`inverse_retract`](@ref) to exists in order to
compute ``Y = \operatorname{retr}_p^{-1}q``.
# Constructor
DifferentiatedRetractionVectorTransport(m::AbstractRetractionMethod)
"""
struct DifferentiatedRetractionVectorTransport{R<:AbstractRetractionMethod} <:
AbstractLinearVectorTransportMethod
retraction::R
end
@doc raw"""
EmbeddedVectorTransport{T<:AbstractVectorTransportMethod} <: AbstractVectorTransportMethod
Compute a vector transport by using the vector transport of type `T` in the embedding and projecting the result.
# Constructor
EmbeddedVectorTransport(vt::AbstractVectorTransportMethod)
Generate the vector transport with vector transport `vt` to use in the embedding.
"""
struct EmbeddedVectorTransport{T<:AbstractVectorTransportMethod} <:
AbstractVectorTransportMethod
vector_transport::T
end
@doc raw"""
ParallelTransport <: AbstractVectorTransportMethod
Compute the vector transport by parallel transport, see
[`parallel_transport_to`](@ref)
"""
struct ParallelTransport <: AbstractLinearVectorTransportMethod end
"""
ProjectionTransport <: AbstractVectorTransportMethod
Specify to use projection onto tangent space as vector transport method within
[`vector_transport_to`](@ref), [`vector_transport_direction`](@ref), or
[`vector_transport_along`](@ref). See [`project`](@ref) for details.
"""
struct ProjectionTransport <: AbstractLinearVectorTransportMethod end
@doc raw"""
PoleLadderTransport <: AbstractVectorTransportMethod
Specify to use [`pole_ladder`](@ref) as vector transport method within
[`vector_transport_to`](@ref), [`vector_transport_direction`](@ref), or
[`vector_transport_along`](@ref), i.e.
Let $X∈ T_p\mathcal M$ be a tangent vector at $p∈\mathcal M$ and $q∈\mathcal M$ the
point to transport to. Then $x = \exp_pX$ is used to call
`y = `[`pole_ladder`](@ref)`(M, p, x, q)` and the resulting vector is obtained by computing
$Y = -\log_qy$.
The [`PoleLadderTransport`](@ref) posesses two advantages compared to
[`SchildsLadderTransport`](@ref):
* it is cheaper to evaluate, if you want to transport several vectors, since the
mid point $c$ then stays unchanged.
* while both methods are exact if the curvature is zero, pole ladder is even exact in
symmetric Riemannian manifolds [Pennec:2018](@cite)
The pole ladder was was proposed in [LorenziPennec:2013](@cite). Its name stems from the fact that
it resembles a pole ladder when applied to a sequence of points usccessively.
# Constructor
````julia
PoleLadderTransport(
retraction = ExponentialRetraction(),
inverse_retraction = LogarithmicInverseRetraction(),
)
````
Construct the classical pole ladder that employs exp and log, i.e. as proposed
in[LorenziPennec:2013](@cite). For an even cheaper transport the inner operations can be
changed to an [`AbstractRetractionMethod`](@ref) `retraction` and an
[`AbstractInverseRetractionMethod`](@ref) `inverse_retraction`, respectively.
"""
struct PoleLadderTransport{
RT<:AbstractRetractionMethod,
IRT<:AbstractInverseRetractionMethod,
} <: AbstractLinearVectorTransportMethod
retraction::RT
inverse_retraction::IRT
function PoleLadderTransport(
retraction = ExponentialRetraction(),
inverse_retraction = LogarithmicInverseRetraction(),
)
return new{typeof(retraction),typeof(inverse_retraction)}(
retraction,
inverse_retraction,
)
end
end
@doc raw"""
ScaledVectorTransport{T} <: AbstractVectorTransportMethod
Introduce a scaled variant of any [`AbstractVectorTransportMethod`](@ref) `T`,
as introduced in [SatoIwai:2013](@cite) for some ``X∈ T_p\mathcal M`` as
```math
\mathcal T^{\mathrm{S}}(X) = \frac{\lVert X\rVert_p}{\lVert \mathcal T(X)\rVert_q}\mathcal T(X).
```
Note that the resulting point `q` has to be known, i.e. for [`vector_transport_direction`](@ref)
the curve or more precisely its end point has to be known (via an exponential map or a
retraction). Therefore a default implementation is only provided for the [`vector_transport_to`](@ref)
# Constructor
ScaledVectorTransport(m::AbstractVectorTransportMethod)
"""
struct ScaledVectorTransport{T<:AbstractVectorTransportMethod} <:
AbstractVectorTransportMethod
method::T
end
@doc raw"""
SchildsLadderTransport <: AbstractVectorTransportMethod
Specify to use [`schilds_ladder`](@ref) as vector transport method within
[`vector_transport_to`](@ref), [`vector_transport_direction`](@ref), or
[`vector_transport_along`](@ref), i.e.
Let $X∈ T_p\mathcal M$ be a tangent vector at $p∈\mathcal M$ and $q∈\mathcal M$ the
point to transport to. Then
````math
P^{\mathrm{S}}_{q\gets p}(X) =
\log_q\bigl( \operatorname{retr}_p ( 2\operatorname{retr}_p^{-1}c ) \bigr),
````
where $c$ is the mid point between $q$ and $d=\exp_pX$.
This method employs the internal function [`schilds_ladder`](@ref)`(M, p, d, q)` that avoids
leaving the manifold.
The name stems from the image of this paralleltogram in a repeated application yielding the
image of a ladder. The approximation was proposed in [EhlersPiraniSchild:1972](@cite).
# Constructor
````julia
SchildsLadderTransport(
retraction = ExponentialRetraction(),
inverse_retraction = LogarithmicInverseRetraction(),
)
````
Construct the classical Schilds ladder that employs exp and log, i.e. as proposed
in [EhlersPiraniSchild:1972](@cite). For an even cheaper transport these inner operations can be
changed to an [`AbstractRetractionMethod`](@ref) `retraction` and an
[`AbstractInverseRetractionMethod`](@ref) `inverse_retraction`, respectively.
"""
struct SchildsLadderTransport{
RT<:AbstractRetractionMethod,
IRT<:AbstractInverseRetractionMethod,
} <: AbstractLinearVectorTransportMethod
retraction::RT
inverse_retraction::IRT
function SchildsLadderTransport(
retraction = ExponentialRetraction(),
inverse_retraction = LogarithmicInverseRetraction(),
)
return new{typeof(retraction),typeof(inverse_retraction)}(
retraction,
inverse_retraction,
)
end
end
@doc raw"""
VectorTransportDirection{VM<:AbstractVectorTransportMethod,RM<:AbstractRetractionMethod}
<: AbstractVectorTransportMethod
Specify a [`vector_transport_direction`](@ref) using a [`AbstractVectorTransportMethod`](@ref)
with explicitly using the [`AbstractRetractionMethod`](@ref) to determine the point in
the specified direction where to transsport to.
Note that you only need this for the non-default (non-implicit) second retraction method
associated to a vector transport, i.e. when a first implementation assumed
an implicit associated retraction.
"""
struct VectorTransportDirection{
VM<:AbstractVectorTransportMethod,
RM<:AbstractRetractionMethod,
} <: AbstractVectorTransportMethod
retraction::RM
vector_transport::VM
function VectorTransportDirection(
vector_transport = ParallelTransport(),
retraction = ExponentialRetraction(),
)
return new{typeof(vector_transport),typeof(retraction)}(
retraction,
vector_transport,
)
end
end
@doc raw"""
VectorTransportTo{VM<:AbstractVectorTransportMethod,RM<:AbstractRetractionMethod}
<: AbstractVectorTransportMethod
Specify a [`vector_transport_to`](@ref) using a [`AbstractVectorTransportMethod`](@ref)
with explicitly using the [`AbstractInverseRetractionMethod`](@ref) to determine the direction
that transports from in `p`to `q`.
Note that you only need this for the non-default (non-implicit) second retraction method
associated to a vector transport, i.e. when a first implementation assumed
an implicit associated retraction.
"""
struct VectorTransportTo{
VM<:AbstractVectorTransportMethod,
IM<:AbstractInverseRetractionMethod,
} <: AbstractVectorTransportMethod
inverse_retraction::IM
vector_transport::VM
function VectorTransportTo(
vector_transport = ParallelTransport(),
inverse_retraction = LogarithmicInverseRetraction(),
)
return new{typeof(vector_transport),typeof(inverse_retraction)}(
inverse_retraction,
vector_transport,
)
end
end
"""
VectorTransportWithKeywords{V<:AbstractVectorTransportMethod, K} <: AbstractVectorTransportMethod
Since vector transports might have keywords, this type is a way to set them as an own type to be
used as a specific vector transport.
Another reason for this type is that we dispatch on the vector transport first and only the
last layer would be implemented with keywords, so this way they can be passed down.
## Fields
* `vector_transport` the vector transport that is decorated with keywords
* `kwargs` the keyword arguments
Note that you can nest this type. Then the most outer specification of a keyword is used.
## Constructor
VectorTransportWithKeywords(m::T; kwargs...) where {T <: AbstractVectorTransportMethod}
Specify the subtype `T <: `[`AbstractVectorTransportMethod`](@ref) to have keywords `kwargs...`.
"""
struct VectorTransportWithKeywords{T<:AbstractVectorTransportMethod,K} <:
AbstractVectorTransportMethod
vector_transport::T
kwargs::K
end
function VectorTransportWithKeywords(
m::T;
kwargs...,
) where {T<:AbstractVectorTransportMethod}
return VectorTransportWithKeywords{T,typeof(kwargs)}(m, kwargs)
end
"""
default_vector_transport_method(M::AbstractManifold)
default_vector_transport_method(M::AbstractManifold, ::Type{T}) where {T}
The [`AbstractVectorTransportMethod`](@ref) that is used when calling
[`vector_transport_along`](@ref), [`vector_transport_to`](@ref), or
[`vector_transport_direction`](@ref) without specifying the vector transport method.
By default, this is [`ParallelTransport`](@ref).
This method can also be specified more precisely with a point type `T`, for the case
that on a `M` there are two different representations of points, which provide
different vector transport methods.
"""
function default_vector_transport_method(::AbstractManifold)
return ParallelTransport()
end
function default_vector_transport_method(M::AbstractManifold, ::Type{T}) where {T}
return default_vector_transport_method(M)
end
@doc raw"""
pole_ladder(
M,
p,
d,
q,
c = mid_point(M, p, q);
retraction=default_retraction_method(M, typeof(p)),
inverse_retraction=default_inverse_retraction_method(M, typeof(p))
)
Compute an inner step of the pole ladder, that can be used as a [`vector_transport_to`](@ref).
Let $c = \gamma_{p,q}(\frac{1}{2})$ mid point between `p` and `q`, then the pole ladder is
given by
````math
\operatorname{Pl}(p,d,q) = \operatorname{retr}_d (2\operatorname{retr}_d^{-1}c)
````
Where the classical pole ladder employs $\operatorname{retr}_d=\exp_d$
and $\operatorname{retr}_d^{-1}=\log_d$ but for an even cheaper transport these can be set
to different [`AbstractRetractionMethod`](@ref) and [`AbstractInverseRetractionMethod`](@ref).
When you have $X=log_pd$ and $Y = -\log_q \operatorname{Pl}(p,d,q)$,
you will obtain the [`PoleLadderTransport`](@ref). When performing multiple steps, this
method avoids the switching to the tangent space. Keep in mind that after $n$ successive
steps the tangent vector reads $Y_n = (-1)^n\log_q \operatorname{Pl}(p_{n-1},d_{n-1},p_n)$.
It is cheaper to evaluate than [`schilds_ladder`](@ref), sinc if you want to form multiple
ladder steps between `p` and `q`, but with different `d`, there is just one evaluation of a geodesic
each., since the center `c` can be reused.
"""
function pole_ladder(
M,
p,
d,
q,
c = mid_point(M, p, q);
retraction = default_retraction_method(M, typeof(p)),
inverse_retraction = default_inverse_retraction_method(M, typeof(p)),
)
return retract(M, d, 2 * inverse_retract(M, d, c, inverse_retraction), retraction)
end
@doc raw"""
pole_ladder(
M,
pl,
p,
d,
q,
c = mid_point(M, p, q),
X = allocate_result_type(M, log, d, c);
retraction = default_retraction_method(M, typeof(p)),
inverse_retraction = default_inverse_retraction_method(M, typeof(p)),
)
Compute the [`pole_ladder`](@ref), i.e. the result is saved in `pl`.
`X` is used for storing intermediate inverse retraction.
"""
function pole_ladder!(
M,
pl,
p,
d,
q,
c = mid_point(M, p, q),
X = allocate_result(M, log, d, c);
retraction = default_retraction_method(M, typeof(p)),
inverse_retraction = default_inverse_retraction_method(M, typeof(p)),
)
inverse_retract!(M, X, d, c, inverse_retraction)
X *= 2
return retract!(M, pl, d, X, retraction)
end
@doc raw"""
schilds_ladder(
M,
p,
d,
q,
c = mid_point(M, q, d);
retraction = default_retraction_method(M, typeof(p)),
inverse_retraction = default_inverse_retraction_method(M, typeof(p)),
)
Perform an inner step of schilds ladder, which can be used as a
[`vector_transport_to`](@ref), see [`SchildsLadderTransport`](@ref).
Let $c = \gamma_{q,d}(\frac{1}{2})$ denote the mid point
on the shortest geodesic connecting $q$ and the point $d$. Then Schild's ladder reads as
````math
\operatorname{Sl}(p,d,q) = \operatorname{retr}_p( 2\operatorname{retr}_p^{-1} c)
````
Where the classical Schilds ladder employs $\operatorname{retr}_d=\exp_d$
and $\operatorname{retr}_d^{-1}=\log_d$ but for an even cheaper transport these can be set
to different [`AbstractRetractionMethod`](@ref) and [`AbstractInverseRetractionMethod`](@ref).
In consistency with [`pole_ladder`](@ref) you can change the way the mid point is computed
using the optional parameter `c`, but note that here it's the mid point between `q` and `d`.
When you have $X=log_pd$ and $Y = \log_q \operatorname{Sl}(p,d,q)$,
you will obtain the [`PoleLadderTransport`](@ref).
Then the approximation to the transported vector is given by $\log_q\operatorname{Sl}(p,d,q)$.
When performing multiple steps, this method avoidsd the switching to the tangent space.
Hence after $n$ successive steps the tangent vector reads
$Y_n = \log_q \operatorname{Pl}(p_{n-1},d_{n-1},p_n)$.
"""
function schilds_ladder(
M,
p,
d,
q,
c = mid_point(M, q, d);
retraction = default_retraction_method(M, typeof(p)),
inverse_retraction = default_inverse_retraction_method(M, typeof(p)),
)
return retract(M, p, 2 * inverse_retract(M, p, c, inverse_retraction), retraction)
end
@doc raw"""
schilds_ladder!(
M,
sl
p,
d,
q,
c = mid_point(M, q, d),
X = allocate_result_type(M, log, d, c);
retraction = default_retraction_method(M, typeof(p)),
inverse_retraction = default_inverse_retraction_method(M, typeof(p)),
)
Compute [`schilds_ladder`](@ref) and return the value in the parameter `sl`.
If the required mid point `c` was computed before, it can be passed using `c`,
and the allocation of new memory can be avoided providing a tangent vector `X`
for the interims result.
"""
function schilds_ladder!(
M,
sl,
p,
d,
q,
c = mid_point(M, q, d),
X = allocate_result(M, log, d, c);
retraction = default_retraction_method(M, typeof(p)),
inverse_retraction = default_inverse_retraction_method(M, typeof(p)),
)
inverse_retract!(M, X, p, c, inverse_retraction)
X *= 2
return retract!(M, sl, p, X, retraction)
end
function show(io::IO, ::ParallelTransport)
return print(io, "ParallelTransport()")
end
function show(io::IO, m::ScaledVectorTransport)
return print(io, "ScaledVectorTransport($(m.method))")
end
"""
vector_transport_along(M::AbstractManifold, p, X, c)
vector_transport_along(M::AbstractManifold, p, X, c, m::AbstractVectorTransportMethod)
Transport a vector `X` from the tangent space at a point `p` on the [`AbstractManifold`](@ref) `M`
along the curve represented by `c` using the `method`, which defaults to
[`default_vector_transport_method`](@ref)`(M)`.
"""
function vector_transport_along(
M::AbstractManifold,
p,
X,
c,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
return _vector_transport_along(M, p, X, c, m)
end
function _vector_transport_along(
M::AbstractManifold,
p,
X,
c,
::ParallelTransport;
kwargs...,
)
return parallel_transport_along(M, p, X, c; kwargs...)
end
function _vector_transport_along(
M::AbstractManifold,
p,
X,
c,
m::VectorTransportWithKeywords;
kwargs...,
)
return _vector_transport_along(M, p, X, c, m.vector_transport; kwargs..., m.kwargs...)
end
function _vector_transport_along(
M::AbstractManifold,
p,
X,
c,
m::AbstractVectorTransportMethod;
kwargs...,
)
Y = allocate_result(M, vector_transport_along, X, p)
return vector_transport_along!(M, Y, p, X, c, m; kwargs...)
end
@doc raw"""
vector_transport_along_diff!(M::AbstractManifold, Y, p, X, c, m::AbstractRetractionMethod)
Compute the vector transport of `X` from ``T_p\mathcal M`` along the curve `c`
using the differential of the [`AbstractRetractionMethod`](@ref) `m` in place of `Y`.
"""
vector_transport_along_diff!(M::AbstractManifold, Y, p, X, c, m)
function vector_transport_along_diff! end
@doc raw"""
vector_transport_along_project!(M::AbstractManifold, Y, p, X, c::AbstractVector)
Compute the vector transport of `X` from ``T_p\mathcal M`` along the curve `c`
using a projection. The result is computed in place of `Y`.
"""
vector_transport_along_project!(M::AbstractManifold, Y, p, X, c::AbstractVector)
function vector_transport_along_project! end
"""
vector_transport_along!(M::AbstractManifold, Y, p, X, c::AbstractVector)
vector_transport_along!(M::AbstractManifold, Y, p, X, c::AbstractVector, m::AbstractVectorTransportMethod)
Transport a vector `X` from the tangent space at a point `p` on the [`AbstractManifold`](@ref) `M`
along the curve represented by `c` using the `method`, which defaults to
[`default_vector_transport_method`](@ref)`(M)`. The result is saved to `Y`.
"""
function vector_transport_along!(
M::AbstractManifold,
Y,
p,
X,
c::AbstractVector,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
return _vector_transport_along!(M, Y, p, X, c, m)
end
function parallel_transport_along!(
M::AbstractManifold,
Y,
p,
X,
c::AbstractVector;
kwargs...,
)
n = length(c)
if n == 0
copyto!(Y, X)
else
parallel_transport_to!(M, Y, p, X, c[1]; kwargs...)
for i in 1:(length(c) - 1)
parallel_transport_to!(M, Y, c[i], Y, c[i + 1]; kwargs...)
end
end
return Y
end
function _vector_transport_along!(
M::AbstractManifold,
Y,
p,
X,
c::AbstractVector,
::ParallelTransport;
kwargs...,
)
return parallel_transport_along!(M, Y, p, X, c; kwargs...)
end
function _vector_transport_along!(
M::AbstractManifold,
Y,
p,
X,
c::AbstractVector,
m::DifferentiatedRetractionVectorTransport;
kwargs...,
)
return vector_transport_along_diff!(M, Y, p, X, c, m.retraction; kwargs...)
end
function _vector_transport_along!(
M::AbstractManifold,
Y,
p,
X,
c::AbstractVector,
::ProjectionTransport;
kwargs...,
)
return vector_transport_along_project!(M, Y, p, X, c; kwargs...)
end
function _vector_transport_along!(
M::AbstractManifold,
Y,
p,
X,
c,
m::VectorTransportWithKeywords;
kwargs...,
)
return _vector_transport_along!(
M,
Y,
p,
X,
c,
m.vector_transport;
kwargs...,
m.kwargs...,
)
end
function _vector_transport_along!(
M::AbstractManifold,
Y,
p,
X,
c::AbstractVector,
m::EmbeddedVectorTransport;
kwargs...,
)
return vector_transport_along_embedded!(M, Y, p, X, c, m.vector_transport; kwargs...)
end
@doc raw"""
vector_transport_along_embedded!(M::AbstractManifold, Y, p, X, c, m::AbstractVectorTransportMethod; kwargs...)
Compute the vector transport of `X` from ``T_p\mathcal M`` along the curve `c`
using the vector transport method `m` in the embedding and projecting the result back on
the corresponding tangent space. The result is computed in place of `Y`.
"""
vector_transport_along_embedded!(
M::AbstractManifold,
Y,
p,
X,
c,
::AbstractVectorTransportMethod,
)
function vector_transport_along_embedded! end
@doc raw"""
function vector_transport_along(
M::AbstractManifold,
p,
X,
c::AbstractVector,
m::PoleLadderTransport
)
Compute the vector transport along a discretized curve using
[`PoleLadderTransport`](@ref) succesively along the sampled curve.
This method is avoiding additional allocations as well as inner exp/log by performing all
ladder steps on the manifold and only computing one tangent vector in the end.
"""
vector_transport_along(
M::AbstractManifold,
Y,
p,
X,
c::AbstractVector,
m::PoleLadderTransport,
)
function _vector_transport_along!(
M::AbstractManifold,
Y,
p,
X,
c::AbstractVector,
m::PoleLadderTransport;
kwargs...,
)
clen = length(c)
if clen == 0
copyto!(Y, X)
else
d = retract(M, p, X, m.retraction)
mp = mid_point(M, p, c[1])
pole_ladder!(
M,
d,
p,
d,
c[1],
mp,
Y;
retraction = m.retraction,
inverse_retraction = m.inverse_retraction,
kwargs...,
)
for i in 1:(clen - 1)
# precompute mid point inplace
ci = c[i]
cip1 = c[i + 1]
mid_point!(M, mp, ci, cip1)
# compute new ladder point
pole_ladder!(
M,
d,
ci,
d,
cip1,
mp,
Y;
retraction = m.retraction,
inverse_retraction = m.inverse_retraction,
kwargs...,
)
end
inverse_retract!(M, Y, c[clen], d, m.inverse_retraction)
Y *= (-1)^clen
end
return Y
end
@doc raw"""
vector_transport_along(
M::AbstractManifold,
p,
X,
c::AbstractVector,
m::SchildsLadderTransport
)
Compute the vector transport along a discretized curve using
[`SchildsLadderTransport`](@ref) succesively along the sampled curve.
This method is avoiding additional allocations as well as inner exp/log by performing all
ladder steps on the manifold and only computing one tangent vector in the end.
"""
vector_transport_along(
M::AbstractManifold,
p,
X,
c::AbstractVector,
m::SchildsLadderTransport,
)
function _vector_transport_along!(
M::AbstractManifold,
Y,
p,
X,
c::AbstractVector,
m::SchildsLadderTransport;
kwargs...,
)
clen = length(c)
if clen == 0
copyto!(Y, X)
else
d = retract(M, p, X, m.retraction)
mp = mid_point(M, c[1], d)
schilds_ladder!(
M,
d,
p,
d,
c[1],
mp,
Y;
retraction = m.retraction,
inverse_retraction = m.inverse_retraction,
kwargs...,
)
for i in 1:(clen - 1)
ci = c[i]
cip1 = c[i + 1]
# precompute mid point inplace
mid_point!(M, mp, cip1, d)
# compute new ladder point
schilds_ladder!(
M,
d,
ci,
d,
cip1,
mp,
Y;
retraction = m.retraction,
inverse_retraction = m.inverse_retraction,
kwargs...,
)
end
inverse_retract!(M, Y, c[clen], d, m.inverse_retraction)
end
return Y
end
@doc raw"""
vector_transport_direction(M::AbstractManifold, p, X, d)
vector_transport_direction(M::AbstractManifold, p, X, d, m::AbstractVectorTransportMethod)
Given an [`AbstractManifold`](@ref) ``\mathcal M`` the vector transport is a generalization of the
[`parallel_transport_direction`](@ref) that identifies vectors from different tangent spaces.
More precisely using [AbsilMahonySepulchre:2008](@cite), Def. 8.1.1, a vector transport
``T_{p,d}: T_p\mathcal M \to T_q\mathcal M``, ``p∈ \mathcal M``, ``Y∈ T_p\mathcal M`` is a smooth mapping
associated to a retraction ``\operatorname{retr}_p(Y) = q`` such that
1. (associated retraction) ``\mathcal T_{p,d}X ∈ T_q\mathcal M`` if and only if ``q = \operatorname{retr}_p(d)``.
2. (consistency) ``\mathcal T_{p,0_p}X = X`` for all ``X∈T_p\mathcal M``
3. (linearity) ``\mathcal T_{p,d}(αX+βY) = α\mathcal T_{p,d}X + β\mathcal T_{p,d}Y``
For the [`AbstractVectorTransportMethod`](@ref) we might even omit the third point.
The [`AbstractLinearVectorTransportMethod`](@ref)s are linear.
# Input Parameters
* `M` a manifold
* `p` indicating the tangent space of
* `X` the tangent vector to be transported
* `d` indicating a transport direction (and distance through its length)
* `m` an [`AbstractVectorTransportMethod`](@ref), by default [`default_vector_transport_method`](@ref), so usually [`ParallelTransport`](@ref)
Usually this method requires a [`AbstractRetractionMethod`](@ref) as well.
By default this is assumed to be the [`default_retraction_method`](@ref) or
implicitly given (and documented) for a vector transport.
To explicitly distinguish different retractions for a vector transport,
see [`VectorTransportDirection`](@ref).
Instead of spcifying a start direction `d` one can equivalently also specify a target tanget space
``T_q\mathcal M``, see [`vector_transport_to`](@ref).
By default [`vector_transport_direction`](@ref) falls back to using [`vector_transport_to`](@ref),
using the [`default_retraction_method`](@ref) on `M`.
"""
function vector_transport_direction(
M::AbstractManifold,
p,
X,
d,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
return _vector_transport_direction(M, p, X, d, m)
end
function _vector_transport_direction(
M::AbstractManifold,
p,
X,
d,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p));
kwargs...,
)
# allocate first
Y = allocate_result(M, vector_transport_direction, X, p, d)
return vector_transport_direction!(M, Y, p, X, d, m; kwargs...)
end
function _vector_transport_direction(
M::AbstractManifold,
p,
X,
d,
m::VectorTransportDirection;
kwargs...,
)
mv =
length(kwargs) > 0 ? VectorTransportWithKeywords(m.vector_transport; kwargs...) :
m.vector_transport
mr = m.retraction
return vector_transport_to(M, p, X, retract(M, p, d, mr), mv)
end
function _vector_transport_direction(
M::AbstractManifold,
p,
X,
d,
m::VectorTransportWithKeywords;
kwargs...,
)
return _vector_transport_direction(
M,
p,
X,
d,
m.vector_transport;
kwargs...,
m.kwargs...,
)
end
"""
vector_transport_direction!(M::AbstractManifold, Y, p, X, d)
vector_transport_direction!(M::AbstractManifold, Y, p, X, d, m::AbstractVectorTransportMethod)
Transport a vector `X` from the tangent space at a point `p` on the [`AbstractManifold`](@ref) `M`
in the direction indicated by the tangent vector `d` at `p`. By default, [`retract`](@ref) and
[`vector_transport_to!`](@ref) are used with the `m` and `r`, which default
to [`default_vector_transport_method`](@ref)`(M)` and [`default_retraction_method`](@ref)`(M)`, respectively.
The result is saved to `Y`.
See [`vector_transport_direction`](@ref) for more details.
"""
function vector_transport_direction!(
M::AbstractManifold,
Y,
p,
X,
d,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p));
kwargs...,
)
return _vector_transport_direction!(M, Y, p, X, d, m; kwargs...)
end
function _vector_transport_direction!(
M::AbstractManifold,
Y,
p,
X,
d,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p));
kwargs...,
)
r = default_retraction_method(M, typeof(p))
v = length(kwargs) > 0 ? VectorTransportWithKeywords(m; kwargs...) : m
return vector_transport_to!(M, Y, p, X, retract(M, p, d, r), v)
end
function _vector_transport_direction!(
M::AbstractManifold,
Y,
p,
X,
d,
m::VectorTransportDirection;
kwargs...,
)
v =
length(kwargs) > 0 ? VectorTransportWithKeywords(m.vector_transport; kwargs...) :
m.vector_transport
return vector_transport_to!(M, Y, p, X, retract(M, p, d, m.retraction), v)
end
function _vector_transport_direction!(
M::AbstractManifold,
Y,
p,
X,
d,
m::DifferentiatedRetractionVectorTransport;
kwargs...,
)
return vector_transport_direction_diff!(M, Y, p, X, d, m.retraction; kwargs...)
end
function _vector_transport_direction!(
M::AbstractManifold,
Y,
p,
X,
d,
m::EmbeddedVectorTransport;
kwargs...,
)
return vector_transport_direction_embedded!(
M,
Y,
p,
X,
d,
m.vector_transport;
kwargs...,
)
end
@doc raw"""
vector_transport_direction_diff!(M::AbstractManifold, Y, p, X, d, m::AbstractRetractionMethod)
Compute the vector transport of `X` from ``T_p\mathcal M`` into the direction `d`
using the differential of the [`AbstractRetractionMethod`](@ref) `m` in place of `Y`.
"""
vector_transport_direction_diff!(M, Y, p, X, d, m)
function vector_transport_direction_diff! end
function _vector_transport_direction!(
M::AbstractManifold,
Y,
p,
X,
d,
::ParallelTransport;
kwargs...,
)
return parallel_transport_direction!(M, Y, p, X, d; kwargs...)
end
function _vector_transport_direction!(
M::AbstractManifold,
Y,
p,
X,
d,
m::VectorTransportWithKeywords;
kwargs...,
)
return _vector_transport_direction!(
M,
Y,
p,
X,
d,
m.vector_transport;
kwargs...,
m.kwargs...,
)
end
@doc raw"""
vector_transport_direction_embedded!(M::AbstractManifold, Y, p, X, d, m::AbstractVectorTransportMethod)
Compute the vector transport of `X` from ``T_p\mathcal M`` into the direction `d`
using the [`AbstractRetractionMethod`](@ref) `m` in the embedding.
The default implementataion requires one allocation for the points and tangent vectors in the
embedding and the resulting point, but the final projection is performed in place of `Y`
"""
function vector_transport_direction_embedded!(
M::AbstractManifold,
Y,
p,
X,
d,
m::AbstractVectorTransportMethod,
)
p_e = embed(M, p)
d_e = embed(M, d)
X_e = embed(M, p, X)
Y_e = vector_transport_direction(get_embedding(M), p_e, X_e, d_e, m)
q = exp(M, p, d)
return project!(M, Y, q, Y_e)
end
@doc raw"""
vector_transport_to(M::AbstractManifold, p, X, q)
vector_transport_to(M::AbstractManifold, p, X, q, m::AbstractVectorTransportMethod)
vector_transport_to(M::AbstractManifold, p, X, q, m::AbstractVectorTransportMethod)
Transport a vector `X` from the tangent space at a point `p` on the [`AbstractManifold`](@ref) `M`
along a curve implicitly given by an [`AbstractRetractionMethod`](@ref) associated to `m`.
By default `m` is the [`default_vector_transport_method`](@ref)`(M)`.
To explicitly specify a (different) retraction to the implicitly assumeed retraction, see [`VectorTransportTo`](@ref).
Note that some vector transport methods might also carry their own retraction they are associated to,
like the [`DifferentiatedRetractionVectorTransport`](@ref) and some are even independent of the retraction, for example the [`ProjectionTransport`](@ref).
This method is equivalent to using ``d = \operatorname{retr}^{-1}_p(q)`` in [`vector_transport_direction`](@ref)`(M, p, X, q, m, r)`,
where you can find the formal definition. This is the fallback for [`VectorTransportTo`](@ref).
"""
function vector_transport_to(
M::AbstractManifold,
p,
X,
q,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
return _vector_transport_to(M, p, X, q, m)
end
function _vector_transport_to(M::AbstractManifold, p, X, q, m::VectorTransportTo; kwargs...)
d = inverse_retract(M, p, q, m.inverse_retraction)
v =
length(kwargs) > 0 ? VectorTransportWithKeywords(m.vector_transport; kwargs...) :
m.vector_transport
return vector_transport_direction(M, p, X, d, v)
end
function _vector_transport_to(M::AbstractManifold, p, X, q, ::ParallelTransport; kwargs...)
return parallel_transport_to(M, p, X, q; kwargs...)
end
function _vector_transport_to(
M::AbstractManifold,
p,
X,
q,
m::AbstractVectorTransportMethod;
kwargs...,
)
Y = allocate_result(M, vector_transport_to, X, p)
return vector_transport_to!(M, Y, p, X, q, m; kwargs...)
end
function _vector_transport_to(
M::AbstractManifold,
p,
X,
q,
m::VectorTransportWithKeywords;
kwargs...,
)
return _vector_transport_to(M, p, X, q, m.vector_transport; kwargs..., m.kwargs...)
end
"""
vector_transport_to!(M::AbstractManifold, Y, p, X, q)
vector_transport_to!(M::AbstractManifold, Y, p, X, q, m::AbstractVectorTransportMethod)
Transport a vector `X` from the tangent space at a point `p` on the [`AbstractManifold`](@ref) `M`
to `q` using the [`AbstractVectorTransportMethod`](@ref) `m` and the [`AbstractRetractionMethod`](@ref) `r`.
The result is computed in `Y`.
See [`vector_transport_to`](@ref) for more details.
"""
function vector_transport_to!(
M::AbstractManifold,
Y,
p,
X,
q,
m::AbstractVectorTransportMethod = default_vector_transport_method(M, typeof(p)),
)
return _vector_transport_to!(M, Y, p, X, q, m)
end
function _vector_transport_to!(
M::AbstractManifold,
Y,
p,
X,
q,
m::VectorTransportTo;
kwargs...,
)
d = inverse_retract(M, p, q, m.inverse_retraction)
return _vector_transport_direction!(M, Y, p, X, d, m.vector_transport; kwargs...)
end
function _vector_transport_to!(
M::AbstractManifold,
Y,
p,
X,
q,
::ParallelTransport;
kwargs...,
)
return parallel_transport_to!(M, Y, p, X, q; kwargs...)
end
function _vector_transport_to!(
M::AbstractManifold,
Y,
p,
X,
q,
m::DifferentiatedRetractionVectorTransport;
kwargs...,
)
return vector_transport_to_diff!(M, Y, p, X, q, m.retraction; kwargs...)
end
function _vector_transport_to!(
M::AbstractManifold,
Y,
p,
X,
q,
m::EmbeddedVectorTransport;
kwargs...,
)
return vector_transport_to_embedded!(M, Y, p, X, q, m.vector_transport; kwargs...)
end
function _vector_transport_to!(
M::AbstractManifold,
Y,
p,
X,
q,
::ProjectionTransport;
kwargs...,
)
return vector_transport_to_project!(M, Y, p, X, q; kwargs...)
end
function _vector_transport_to!(
M::AbstractManifold,
Y,
p,
X,
q,
m::PoleLadderTransport;
kwargs...,
)
inverse_retract!(
M,
Y,
q,
pole_ladder(
M,
p,
retract(M, p, X, m.retraction),
q;
retraction = m.retraction,
inverse_retraction = m.inverse_retraction,
kwargs...,
),
m.inverse_retraction,
)
copyto!(Y, -Y)
return Y
end
function _vector_transport_to!(
M::AbstractManifold,
Y,
p,
X,
q,
m::ScaledVectorTransport;
kwargs...,
)
v = length(kwargs) > 0 ? VectorTransportWithKeywords(m.method; kwargs...) : m.method
vector_transport_to!(M, Y, p, X, q, v)
Y .*= norm(M, p, X) / norm(M, q, Y)
return Y
end
function _vector_transport_to!(
M::AbstractManifold,
Y,
p,
X,
q,
m::VectorTransportWithKeywords;
kwargs...,
)
return _vector_transport_to!(M, Y, p, X, q, m.vector_transport; kwargs..., m.kwargs...)
end
function _vector_transport_to!(
M::AbstractManifold,
Y,
p,
X,
q,
m::SchildsLadderTransport;
kwargs...,
)
return inverse_retract!(
M,
Y,
q,
schilds_ladder(
M,
p,
retract(M, p, X, m.retraction),
q;
retraction = m.retraction,
inverse_retraction = m.inverse_retraction,
kwargs...,
),
m.inverse_retraction,
)
end
@doc raw"""
vector_transport_to_diff(M::AbstractManifold, p, X, q, r)
Compute a vector transport by using a [`DifferentiatedRetractionVectorTransport`](@ref) `r` in place of `Y`.
"""
vector_transport_to_diff!(M::AbstractManifold, Y, p, X, q, r)
function vector_transport_to_diff! end
@doc raw"""
vector_transport_to_embedded!(M::AbstractManifold, Y, p, X, q, m::AbstractRetractionMethod)
Compute the vector transport of `X` from ``T_p\mathcal M`` to the point `q`
using the of the [`AbstractRetractionMethod`](@ref) `m` in th embedding.
The default implementataion requires one allocation for the points and tangent vectors in the
embedding and the resulting point, but the final projection is performed in place of `Y`
"""
function vector_transport_to_embedded!(M::AbstractManifold, Y, p, X, q, m)
p_e = embed(M, p)
X_e = embed(M, p, X)
q_e = embed(M, q)
Y_e = vector_transport_to(get_embedding(M), p_e, X_e, q_e, m)
return project!(M, Y, q, Y_e)
end
@doc raw"""
vector_transport_to_project!(M::AbstractManifold, Y, p, X, q)
Compute a vector transport by projecting ``X\in T_p\mathcal M`` onto the tangent
space ``T_q\mathcal M`` at ``q`` in place of `Y`.
"""
function vector_transport_to_project!(M::AbstractManifold, Y, p, X, q; kwargs...)
# Note that we have to use embed (not embed!) since we do not have memory to store this embedded value in
return project!(M, Y, q, embed(M, p, X); kwargs...)
end
# default estimation fallbacks with and without the T
function default_approximation_method(
M::AbstractManifold,
::typeof(vector_transport_direction),
)
return default_vector_transport_method(M)
end
function default_approximation_method(M::AbstractManifold, ::typeof(vector_transport_along))
return default_vector_transport_method(M)
end
function default_approximation_method(M::AbstractManifold, ::typeof(vector_transport_to))
return default_vector_transport_method(M)
end
function default_approximation_method(
M::AbstractManifold,
::typeof(vector_transport_direction),
T,
)
return default_vector_transport_method(M, T)
end
function default_approximation_method(
M::AbstractManifold,
::typeof(vector_transport_along),
T,
)
return default_vector_transport_method(M, T)
end
function default_approximation_method(M::AbstractManifold, ::typeof(vector_transport_to), T)
return default_vector_transport_method(M, T)
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 17291 | """
ManifoldsBaseTestUtils
A small module to collect common definitions and functions used in (several) tests of
`ManifoldsBase.jl`.
* A `TestSphere`
*
"""
module ManifoldsBaseTestUtils
using ManifoldsBase, LinearAlgebra, Random
using ManifoldsBase: ℝ, ℂ, AbstractManifold, DefaultManifold, EuclideanMetric
using ManifoldsBase: AbstractNumbers, RealNumbers, ComplexNumbers
using ManifoldsBase:
@manifold_element_forwards, @manifold_vector_forwards, @default_manifold_fallbacks
import Base: +, *, -
#
#
# minimal implementation of the sphere – to test a few more involved Riemannian functions
struct TestSphere{N,𝔽} <: AbstractManifold{𝔽} end
TestSphere(N::Int, 𝔽 = ℝ) = TestSphere{N,𝔽}()
function ManifoldsBase.change_metric!(
M::TestSphere,
Y,
::ManifoldsBase.EuclideanMetric,
p,
X,
)
return copyto!(M, Y, p, X)
end
function ManifoldsBase.change_representer!(
M::TestSphere,
Y,
::ManifoldsBase.EuclideanMetric,
p,
X,
)
return copyto!(M, Y, p, X)
end
function ManifoldsBase.check_point(M::TestSphere, p; kwargs...)
if !isapprox(norm(p), 1.0; kwargs...)
return DomainError(
norm(p),
"The point $(p) does not lie on the $(M) since its norm is not 1.",
)
end
return nothing
end
function ManifoldsBase.check_vector(M::TestSphere, p, X; kwargs...)
if !isapprox(abs(real(dot(p, X))), 0.0; kwargs...)
return DomainError(
abs(dot(p, X)),
"The vector $(X) is not a tangent vector to $(p) on $(M), since it is not orthogonal in the embedding.",
)
end
return nothing
end
function ManifoldsBase.exp!(M::TestSphere, q, p, X)
return exp!(M, q, p, X, one(number_eltype(X)))
end
function ManifoldsBase.exp!(::TestSphere, q, p, X, t::Number)
θ = abs(t) * norm(X)
if θ == 0
copyto!(q, p)
else
X_scale = t * sin(θ) / θ
q .= p .* cos(θ) .+ X .* X_scale
end
return q
end
function ManifoldsBase.get_basis_diagonalizing(
M::TestSphere{n},
p,
B::DiagonalizingOrthonormalBasis{ℝ},
) where {n}
A = zeros(n + 1, n + 1)
A[1, :] = transpose(p)
A[2, :] = transpose(B.frame_direction)
V = nullspace(A)
κ = ones(n)
if !iszero(B.frame_direction)
# if we have a nonzero direction for the geodesic, add it and it gets curvature zero from the tensor
V = hcat(B.frame_direction / norm(M, p, B.frame_direction), V)
κ[1] = 0 # no curvature along the geodesic direction, if x!=y
end
T = typeof(similar(B.frame_direction))
Ξ = [convert(T, V[:, i]) for i in 1:n]
return CachedBasis(B, κ, Ξ)
end
@inline function nzsign(z, absz = abs(z))
psignz = z / absz
return ifelse(iszero(absz), one(psignz), psignz)
end
function ManifoldsBase.get_coordinates_orthonormal!(M::TestSphere, Y, p, X, ::RealNumbers)
n = manifold_dimension(M)
p1 = p[1]
cosθ = abs(p1)
λ = nzsign(p1, cosθ)
pend, Xend = view(p, 2:(n + 1)), view(X, 2:(n + 1))
factor = λ * X[1] / (1 + cosθ)
Y .= Xend .- pend .* factor
return Y
end
function ManifoldsBase.get_vector_orthonormal!(M::TestSphere, Y, p, X, ::RealNumbers)
n = manifold_dimension(M)
p1 = p[1]
cosθ = abs(p1)
λ = nzsign(p1, cosθ)
pend = view(p, 2:(n + 1))
pX = dot(pend, X)
factor = pX / (1 + cosθ)
Y[1] = -λ * pX
Y[2:(n + 1)] .= X .- pend .* factor
return Y
end
ManifoldsBase.injectivity_radius(::TestSphere) = π
ManifoldsBase.inner(::TestSphere, p, X, Y) = dot(X, Y)
function ManifoldsBase.inverse_retract_project!(M::TestSphere, X, p, q)
X .= q .- p
project!(M, X, p, X)
return X
end
ManifoldsBase.is_flat(M::TestSphere) = manifold_dimension(M) == 1
function ManifoldsBase.log!(::TestSphere, X, p, q)
cosθ = clamp(real(dot(p, q)), -1, 1)
X .= q .- p .* cosθ
nrmX = norm(X)
if nrmX > 0
X .*= acos(cosθ) / nrmX
end
return X
end
ManifoldsBase.manifold_dimension(::TestSphere{N}) where {N} = N
function ManifoldsBase.parallel_transport_to!(::TestSphere, Y, p, X, q)
m = p .+ q
mnorm2 = real(dot(m, m))
factor = 2 * real(dot(X, q)) / mnorm2
Y .= X .- m .* factor
return Y
end
function ManifoldsBase.project!(::TestSphere, q, p)
q .= p ./ norm(p)
return q
end
function ManifoldsBase.project!(::TestSphere, Y, p, X)
Y .= X .- p .* real(dot(p, X))
return Y
end
function Random.rand!(M::TestSphere, pX; vector_at = nothing, σ = one(eltype(pX)))
return rand!(Random.default_rng(), M, pX; vector_at = vector_at, σ = σ)
end
function Random.rand!(
rng::AbstractRNG,
M::TestSphere,
pX;
vector_at = nothing,
σ = one(eltype(pX)),
)
if vector_at === nothing
project!(M, pX, randn(rng, eltype(pX), representation_size(M)))
else
n = σ * randn(rng, eltype(pX), size(pX)) # Gaussian in embedding
project!(M, pX, vector_at, n) #project to TpM (keeps Gaussianness)
end
return pX
end
ManifoldsBase.representation_size(::TestSphere{N}) where {N} = (N + 1,)
function ManifoldsBase.retract_project!(M::TestSphere, q, p, X, t::Number)
q .= p .+ t .* X
project!(M, q, q)
return q
end
function ManifoldsBase.riemann_tensor!(M::TestSphere, Xresult, p, X, Y, Z)
innerZX = inner(M, p, Z, X)
innerZY = inner(M, p, Z, Y)
Xresult .= innerZY .* X .- innerZX .* Y
return Xresult
end
function ManifoldsBase.sectional_curvature_max(M::TestSphere)
return ifelse(manifold_dimension(M) == 1, 0.0, 1.0)
end
function ManifoldsBase.sectional_curvature_min(M::TestSphere)
return ifelse(manifold_dimension(M) == 1, 0.0, 1.0)
end
# from Absil, Mahony, Trumpf, 2013 https://sites.uclouvain.be/absil/2013-01/Weingarten_07PA_techrep.pdf
function ManifoldsBase.Weingarten!(::TestSphere, Y, p, X, V)
return Y .= -X * p' * V
end
#
#
# minimal implementation of SPD (for its nontrivial metric conversion)
# ---
struct TestSPD <: AbstractManifold{ℝ}
n::Int
end
function ManifoldsBase.change_metric!(::TestSPD, Y, ::EuclideanMetric, p, X)
Y .= p * X
return Y
end
function ManifoldsBase.change_representer!(::TestSPD, Y, ::EuclideanMetric, p, X)
Y .= p * X * p
return Y
end
function ManifoldsBase.inner(::TestSPD, p, X, Y)
F = cholesky(Symmetric(convert(AbstractMatrix, p)))
return dot((F \ Symmetric(X)), (Symmetric(Y) / F))
end
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 ManifoldsBase.log!(::TestSPD, X, p, q)
(p_sqrt, p_sqrt_inv) = spd_sqrt_and_sqrt_inv(p)
T = Symmetric(p_sqrt_inv * convert(AbstractMatrix, q) * p_sqrt_inv)
e2 = eigen(T)
Se = Diagonal(log.(max.(e2.values, eps())))
pUe = p_sqrt * e2.vectors
return mul!(X, pUe, Se * transpose(pUe))
end
ManifoldsBase.representation_size(M::TestSPD) = (M.n, M.n)
#
#
# A simple Manifold based on a projection onto a subspace
struct ProjManifold <: AbstractManifold{ℝ} end
ManifoldsBase.inner(::ProjManifold, p, X, Y) = dot(X, Y)
ManifoldsBase.project!(::ProjManifold, Y, p, X) = (Y .= X .- dot(p, X) .* p)
ManifoldsBase.representation_size(::ProjManifold) = (2, 3)
ManifoldsBase.manifold_dimension(::ProjManifold) = 5
ManifoldsBase.get_vector_orthonormal(::ProjManifold, p, X, N) = reverse(X)
#
#
# A second simple Manifold based on a projection onto a subspace
struct ProjectionTestManifold <: AbstractManifold{ℝ} end
ManifoldsBase.inner(::ProjectionTestManifold, ::Any, X, Y) = dot(X, Y)
function ManifoldsBase.project!(::ProjectionTestManifold, Y, p, X)
Y .= X .- dot(p, X) .* p
Y[end] = 0
return Y
end
ManifoldsBase.manifold_dimension(::ProjectionTestManifold) = 100
#
# Thre Non-Things to check for the correct errors in case functions are not implemented
struct NonManifold <: AbstractManifold{ℝ} end
struct NonBasis <: ManifoldsBase.AbstractBasis{ℝ,TangentSpaceType} end
struct NonMPoint <: AbstractManifoldPoint end
struct NonTVector <: TVector end
struct NonCoTVector <: CoTVector end
struct NotImplementedRetraction <: AbstractRetractionMethod end
struct NotImplementedInverseRetraction <: AbstractInverseRetractionMethod end
*(t::Float64, X::NonTVector) = X
struct NonBroadcastBasisThing{T}
v::T
end
+(a::NonBroadcastBasisThing, b::NonBroadcastBasisThing) = NonBroadcastBasisThing(a.v + b.v)
*(α, a::NonBroadcastBasisThing) = NonBroadcastBasisThing(α * a.v)
-(a::NonBroadcastBasisThing, b::NonBroadcastBasisThing) = NonBroadcastBasisThing(a.v - b.v)
function ManifoldsBase.isapprox(a::NonBroadcastBasisThing, b::NonBroadcastBasisThing)
return isapprox(a.v, b.v)
end
function ManifoldsBase.number_eltype(a::NonBroadcastBasisThing)
return typeof(reduce(+, one(number_eltype(eti)) for eti in a.v))
end
ManifoldsBase.allocate(a::NonBroadcastBasisThing) = NonBroadcastBasisThing(allocate(a.v))
function ManifoldsBase.allocate(a::NonBroadcastBasisThing, ::Type{T}) where {T}
return NonBroadcastBasisThing(allocate(a.v, T))
end
function ManifoldsBase.allocate(::NonBroadcastBasisThing, ::Type{T}, s::Integer) where {T}
return Vector{T}(undef, s)
end
function Base.copyto!(a::NonBroadcastBasisThing, b::NonBroadcastBasisThing)
copyto!(a.v, b.v)
return a
end
function ManifoldsBase.log!(
::DefaultManifold,
v::NonBroadcastBasisThing,
x::NonBroadcastBasisThing,
y::NonBroadcastBasisThing,
)
return copyto!(v, y - x)
end
function ManifoldsBase.exp!(
::DefaultManifold,
y::NonBroadcastBasisThing,
x::NonBroadcastBasisThing,
v::NonBroadcastBasisThing,
)
return copyto!(y, x + v)
end
function ManifoldsBase.get_basis_orthonormal(
::DefaultManifold{ℝ},
p::NonBroadcastBasisThing,
𝔽::RealNumbers,
)
return CachedBasis(
DefaultOrthonormalBasis(𝔽),
[
NonBroadcastBasisThing(ManifoldsBase._euclidean_basis_vector(p.v, i)) for
i in eachindex(p.v)
],
)
end
function ManifoldsBase.get_basis_orthogonal(
::DefaultManifold{ℝ},
p::NonBroadcastBasisThing,
𝔽::RealNumbers,
)
return CachedBasis(
DefaultOrthogonalBasis(𝔽),
[
NonBroadcastBasisThing(ManifoldsBase._euclidean_basis_vector(p.v, i)) for
i in eachindex(p.v)
],
)
end
function ManifoldsBase.get_basis_default(
::DefaultManifold{ℝ},
p::NonBroadcastBasisThing,
N::ManifoldsBase.RealNumbers,
)
return CachedBasis(
DefaultBasis(N),
[
NonBroadcastBasisThing(ManifoldsBase._euclidean_basis_vector(p.v, i)) for
i in eachindex(p.v)
],
)
end
function ManifoldsBase.get_coordinates_orthonormal!(
M::DefaultManifold,
Y,
::NonBroadcastBasisThing,
X::NonBroadcastBasisThing,
::RealNumbers,
)
copyto!(Y, reshape(X.v, manifold_dimension(M)))
return Y
end
function ManifoldsBase.get_vector_orthonormal!(
M::DefaultManifold,
Y::NonBroadcastBasisThing,
::NonBroadcastBasisThing,
X,
::RealNumbers,
)
copyto!(Y.v, reshape(X, representation_size(M)))
return Y
end
function ManifoldsBase.inner(
::DefaultManifold,
::NonBroadcastBasisThing,
X::NonBroadcastBasisThing,
Y::NonBroadcastBasisThing,
)
return dot(X.v, Y.v)
end
ManifoldsBase._get_vector_cache_broadcast(::NonBroadcastBasisThing) = Val(false)
DiagonalizingBasisProxy() = DiagonalizingOrthonormalBasis([1.0, 0.0, 0.0])
#
#
# Vector Space types
struct TestVectorSpaceType <: ManifoldsBase.VectorSpaceType end
struct TestFiberType <: ManifoldsBase.FiberType end
function ManifoldsBase.fiber_dimension(M::AbstractManifold, ::TestFiberType)
return 2 * manifold_dimension(M)
end
function ManifoldsBase.vector_space_dimension(M::AbstractManifold, ::TestVectorSpaceType)
return 2 * manifold_dimension(M)
end
#
#
# DefaultManifold with a few artificiual retrations
struct CustomDefinedRetraction <: ManifoldsBase.AbstractRetractionMethod end
struct CustomUndefinedRetraction <: ManifoldsBase.AbstractRetractionMethod end
struct CustomDefinedKeywordRetraction <: ManifoldsBase.AbstractRetractionMethod end
struct CustomDefinedKeywordInverseRetraction <:
ManifoldsBase.AbstractInverseRetractionMethod end
struct CustomDefinedInverseRetraction <: ManifoldsBase.AbstractInverseRetractionMethod end
struct DefaultPoint{T} <: AbstractManifoldPoint
value::T
end
Base.convert(::Type{DefaultPoint{T}}, v::T) where {T} = DefaultPoint(v)
Base.eltype(p::DefaultPoint) = eltype(p.value)
Base.length(p::DefaultPoint) = length(p.value)
struct DefaultTVector{T} <: TVector
value::T
end
Base.convert(::Type{DefaultTVector{T}}, ::DefaultPoint, v::T) where {T} = DefaultTVector(v)
Base.eltype(X::DefaultTVector) = eltype(X.value)
function Base.fill!(X::DefaultTVector, x)
fill!(X.value, x)
return X
end
function ManifoldsBase.allocate_result_type(
::DefaultManifold,
::typeof(log),
::Tuple{DefaultPoint,DefaultPoint},
)
return DefaultTVector
end
function ManifoldsBase.allocate_result_type(
::DefaultManifold,
::typeof(inverse_retract),
::Tuple{DefaultPoint,DefaultPoint},
)
return DefaultTVector
end
ManifoldsBase.@manifold_element_forwards DefaultPoint value
ManifoldsBase.@manifold_vector_forwards DefaultTVector value
ManifoldsBase.@default_manifold_fallbacks ManifoldsBase.DefaultManifold DefaultPoint DefaultTVector value value
function ManifoldsBase._injectivity_radius(::DefaultManifold, ::CustomDefinedRetraction)
return 10.0
end
function ManifoldsBase._retract!(
M::DefaultManifold,
q,
p,
X,
t::Number,
::CustomDefinedKeywordRetraction;
kwargs...,
)
return retract_custom_kw!(M, q, p, X, t; kwargs...)
end
function retract_custom_kw!(
::DefaultManifold,
q::DefaultPoint,
p::DefaultPoint,
X::DefaultTVector,
t::Number;
scale = 2.0,
)
q.value .= scale .* p.value .+ t .* X.value
return q
end
function ManifoldsBase._inverse_retract!(
M::DefaultManifold,
X,
p,
q,
::CustomDefinedKeywordInverseRetraction;
kwargs...,
)
return inverse_retract_custom_kw!(M, X, p, q; kwargs...)
end
function inverse_retract_custom_kw!(
::DefaultManifold,
X::DefaultTVector,
p::DefaultPoint,
q::DefaultPoint;
scale = 2.0,
)
X.value .= q.value - scale * p.value
return X
end
function ManifoldsBase.retract!(
::DefaultManifold,
q::DefaultPoint,
p::DefaultPoint,
X::DefaultTVector,
t::Number,
::CustomDefinedRetraction,
)
q.value .= 2 .* p.value .+ t * X.value
return q
end
function ManifoldsBase.inverse_retract!(
::DefaultManifold,
X::DefaultTVector,
p::DefaultPoint,
q::DefaultPoint,
::CustomDefinedInverseRetraction,
)
X.value .= q.value .- 2 .* p.value
return X
end
struct MatrixVectorTransport{T} <: AbstractVector{T}
m::Matrix{T}
end
# dummy retractions, inverse retracions for fallback tests - mutating should be enough
ManifoldsBase.retract_polar!(::DefaultManifold, q, p, X, t::Number) = (q .= p .+ t .* X)
ManifoldsBase.retract_project!(::DefaultManifold, q, p, X, t::Number) = (q .= p .+ t .* X)
ManifoldsBase.retract_qr!(::DefaultManifold, q, p, X, t::Number) = (q .= p .+ t .* X)
function ManifoldsBase.retract_exp_ode!(
::DefaultManifold,
q,
p,
X,
t::Number,
m::AbstractRetractionMethod,
B::ManifoldsBase.AbstractBasis,
)
return (q .= p .+ t .* X)
end
function ManifoldsBase.retract_pade!(
::DefaultManifold,
q,
p,
X,
t::Number,
m::PadeRetraction,
)
return (q .= p .+ t .* X)
end
function ManifoldsBase.retract_sasaki!(
::DefaultManifold,
q,
p,
X,
t::Number,
::SasakiRetraction,
)
return (q .= p .+ t .* X)
end
ManifoldsBase.retract_softmax!(::DefaultManifold, q, p, X, t::Number) = (q .= p .+ t .* X)
ManifoldsBase.get_embedding(M::DefaultManifold) = M # dummy embedding
ManifoldsBase.inverse_retract_polar!(::DefaultManifold, Y, p, q) = (Y .= q .- p)
ManifoldsBase.inverse_retract_project!(::DefaultManifold, Y, p, q) = (Y .= q .- p)
ManifoldsBase.inverse_retract_qr!(::DefaultManifold, Y, p, q) = (Y .= q .- p)
ManifoldsBase.inverse_retract_softmax!(::DefaultManifold, Y, p, q) = (Y .= q .- p)
function ManifoldsBase.inverse_retract_nlsolve!(
::DefaultManifold,
Y,
p,
q,
m::NLSolveInverseRetraction,
)
return (Y .= q .- p)
end
function ManifoldsBase.vector_transport_along_project!(
::DefaultManifold,
Y,
p,
X,
c::AbstractVector,
)
return (Y .= X)
end
Base.getindex(x::MatrixVectorTransport, i) = x.m[:, i]
Base.size(x::MatrixVectorTransport) = (size(x.m, 2),)
export CustomDefinedInverseRetraction, CustomDefinedKeywordInverseRetraction
export CustomDefinedKeywordRetraction, CustomDefinedRetraction, CustomUndefinedRetraction
export DefaultPoint, DefaultTVector
export DiagonalizingBasisProxy
export MatrixVectorTransport
export NonManifold, NonBasis, NonBroadcastBasisThing
export NonMPoint, NonTVector, NonCoTVector
export NotImplementedRetraction, NotImplementedInverseRetraction
export ProjManifold, ProjectionTestManifold
export TestSphere, TestSPD
export TestVectorSpaceType, TestFiberType
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 3902 | using ManifoldsBase
using Test
using ManifoldsBase:
combine_allocation_promotion_functions, allocation_promotion_function, ℝ, ℂ, ℍ
using Quaternions
struct AllocManifold{𝔽} <: AbstractManifold{𝔽} end
AllocManifold() = AllocManifold{ℝ}()
function ManifoldsBase.exp!(::AllocManifold, v, x, y)
v[1] .= x[1] .+ y[1]
v[2] .= x[2] .+ y[2]
v[3] .= x[3] .+ y[3]
return v
end
struct AllocManifold2 <: AbstractManifold{ℝ} end
ManifoldsBase.representation_size(::AllocManifold2) = (2, 3)
struct AllocManifold3 <: AbstractManifold{ℂ} end
ManifoldsBase.representation_size(::AllocManifold3) = (2, 3)
struct AllocManifold4 <: AbstractManifold{ℍ} end
ManifoldsBase.representation_size(::AllocManifold4) = (2, 3)
@testset "Allocation" begin
a = [[1.0], [2.0], [3.0]]
b = [[2.0], [3.0], [-3.0]]
M = AllocManifold()
v = exp(M, a, b)
@test v ≈ [[3.0], [5.0], [0.0]]
@test allocate(([1.0], [2.0])) isa Tuple{Vector{Float64},Vector{Float64}}
@test allocate(([1.0], [2.0]), Int) isa Tuple{Vector{Int},Vector{Int}}
@test allocate([[1.0], [2.0]]) isa Vector{Vector{Float64}}
@test allocate([[1.0], [2.0]], Int) isa Vector{Vector{Int}}
@test allocate(M, a, 5) isa Vector{Vector{Float64}}
@test length(allocate(M, a, 5)) == 5
@test allocate(M, a, (5,)) isa Vector{Vector{Float64}}
@test length(allocate(M, a, (5,))) == 5
@test allocate(M, a, Int, (5,)) isa Vector{Int}
@test length(allocate(M, a, Int, (5,))) == 5
@test allocate(M, a, Int, 5) isa Vector{Int}
@test length(allocate(M, a, Int, 5)) == 5
a1 = allocate([1], 2, 3)
@test a1 isa Matrix{Int}
@test size(a1) == (2, 3)
a2 = allocate([1], (2, 3))
@test a2 isa Matrix{Int}
@test size(a2) == (2, 3)
a3 = allocate([1], Float64, 2, 3)
@test a3 isa Matrix{Float64}
@test size(a3) == (2, 3)
a4 = allocate([1], Float64, (2, 3))
@test a4 isa Matrix{Float64}
@test size(a4) == (2, 3)
@test allocation_promotion_function(M, exp, (a, b)) === identity
@test combine_allocation_promotion_functions(identity, identity) === identity
@test combine_allocation_promotion_functions(identity, complex) === complex
@test combine_allocation_promotion_functions(complex, identity) === complex
@test combine_allocation_promotion_functions(complex, complex) === complex
@test number_eltype([2.0]) === Float64
@test number_eltype([[2.0], [3]]) === Float64
@test number_eltype([[2], [3.0]]) === Float64
@test number_eltype([[2], [3]]) === Int
@test number_eltype(([2.0], [3])) === Float64
@test number_eltype(([2], [3.0])) === Float64
@test number_eltype(([2], [3])) === Int
@test number_eltype(Any[[2.0], [3.0]]) === Float64
@test number_eltype(typeof([[1.0, 2.0]])) === Float64
M2 = AllocManifold2()
alloc2 = ManifoldsBase.allocate_result(M2, rand)
@test alloc2 isa Matrix{Float64}
@test size(alloc2) == representation_size(M2)
@test ManifoldsBase.allocate_result(AllocManifold3(), rand) isa Matrix{ComplexF64}
@test ManifoldsBase.allocate_result(AllocManifold4(), rand) isa Matrix{QuaternionF64}
an = allocate_on(M2)
@test an isa Matrix{Float64}
@test size(an) == representation_size(M2)
an = allocate_on(M2, Array{Float32})
@test an isa Matrix{Float32}
@test size(an) == representation_size(M2)
an = allocate_on(M2, TangentSpaceType())
@test an isa Matrix{Float64}
@test size(an) == representation_size(M2)
an = allocate_on(M2, TangentSpaceType(), Array{Float32})
@test an isa Matrix{Float32}
@test size(an) == representation_size(M2)
@test default_type(M2) === Matrix{Float64}
@test default_type(M2, TangentSpaceType()) === Matrix{Float64}
@test ManifoldsBase.coordinate_eltype(M, fill(true, 2, 3), ℝ) === Float64
@test ManifoldsBase.coordinate_eltype(AllocManifold4(), a4, ℍ) === QuaternionF64
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 17598 | using LinearAlgebra
using ManifoldsBase
using ManifoldsBase: DefaultManifold, ℝ, ℂ, RealNumbers, ComplexNumbers
using ManifoldsBase: CotangentSpaceType, TangentSpaceType
using ManifoldsBase: FVector
using Test
s = @__DIR__
!(s in LOAD_PATH) && (push!(LOAD_PATH, s))
using ManifoldsBaseTestUtils
@testset "Bases" begin
@testset "Projected and arbitrary orthonormal basis" begin
M = ProjManifold()
x = [
sqrt(2)/2 0.0 0.0
0.0 sqrt(2)/2 0.0
]
for pB in
(ProjectedOrthonormalBasis(:svd), ProjectedOrthonormalBasis(:gram_schmidt))
if pB isa ProjectedOrthonormalBasis{:gram_schmidt,ℝ}
pb = @test_logs (
:warn,
"Input vector 4 lies in the span of the previous ones.",
) get_basis(
M,
x,
pB;
warn_linearly_dependent = true,
skip_linearly_dependent = true,
) # skip V4, wich is -V1 after proj.
@test_throws ErrorException get_basis(M, x, pB) # error
else
pb = get_basis(M, x, pB) # skips V4 automatically
end
@test number_system(pb) == ℝ
N = manifold_dimension(M)
@test isa(pb, CachedBasis)
@test CachedBasis(pb) === pb
@test !ManifoldsBase.requires_caching(pb)
@test length(get_vectors(M, x, pb)) == N
# test orthonormality
for i in 1:N
@test norm(M, x, get_vectors(M, x, pb)[i]) ≈ 1
for j in (i + 1):N
@test inner(M, x, get_vectors(M, x, pb)[i], get_vectors(M, x, pb)[j]) ≈
0 atol = 1e-15
end
end
end
aonb = get_basis(M, x, DefaultOrthonormalBasis())
@test size(get_vectors(M, x, aonb)) == (5,)
@test get_vectors(M, x, aonb)[1] ≈ [0, 0, 0, 0, 1]
@testset "Gram-Schmidt" begin
# for a basis
M = ManifoldsBase.DefaultManifold(3)
p = zeros(3)
V = [[2.0, 0.0, 0.0], [1.1, 2.2, 0.0], [0.0, 3.3, 4.4]]
b1 = ManifoldsBase.gram_schmidt(M, p, V)
b2 = ManifoldsBase.gram_schmidt(M, zeros(3), CachedBasis(DefaultBasis(), V))
@test b1 == get_vectors(M, p, b2)
# projected gram schmidt
tm = ProjectionTestManifold()
bt = ProjectedOrthonormalBasis(:gram_schmidt)
p = [sqrt(2) / 2, 0.0, sqrt(2) / 2, 0.0, 0.0]
@test_logs (:warn, "Input only has 5 vectors, but manifold dimension is 100.") (@test_throws ErrorException get_basis(
tm,
p,
bt,
))
b = @test_logs (
:warn,
"Input only has 5 vectors, but manifold dimension is 100.",
) get_basis(
tm,
p,
bt;
return_incomplete_set = true,
skip_linearly_dependent = true, #skips 3 and 5
)
@test length(get_vectors(tm, p, b)) == 3
@test_logs (:warn, "Input only has 1 vectors, but manifold dimension is 3.") (@test_throws ErrorException ManifoldsBase.gram_schmidt(
M,
p,
[V[1]],
))
@test_throws ErrorException ManifoldsBase.gram_schmidt(
M,
p,
[V[1], V[1], V[1]];
skip_linearly_dependent = true,
)
end
end
@testset "ManifoldsBase.jl stuff" begin
@testset "Errors" begin
m = NonManifold()
onb = DefaultOrthonormalBasis()
@test_throws MethodError get_basis(m, [0], onb)
@test_throws MethodError get_basis(m, [0], NonBasis())
@test_throws MethodError get_coordinates(m, [0], [0], onb)
@test_throws MethodError get_coordinates!(m, [0], [0], [0], onb)
@test_throws MethodError get_vector(m, [0], [0], onb)
@test_throws MethodError get_vector!(m, [0], [0], [0], onb)
@test_throws MethodError get_vectors(m, [0], NonBasis())
end
M = DefaultManifold(3)
@test sprint(
show,
"text/plain",
CachedBasis(NonBasis(), NonBroadcastBasisThing([])),
) == "Cached basis of type NonBasis"
@testset "Constructors" begin
@test DefaultBasis{ℂ,TangentSpaceType}() === DefaultBasis(ℂ)
@test DefaultOrthogonalBasis{ℂ,TangentSpaceType}() === DefaultOrthogonalBasis(ℂ)
@test DefaultOrthonormalBasis{ℂ,TangentSpaceType}() ===
DefaultOrthonormalBasis(ℂ)
@test DefaultBasis{ℂ}(CotangentSpaceType()) ===
DefaultBasis(ℂ, CotangentSpaceType())
@test DefaultOrthogonalBasis{ℂ}(CotangentSpaceType()) ===
DefaultOrthogonalBasis(ℂ, CotangentSpaceType())
@test DefaultOrthonormalBasis{ℂ}(CotangentSpaceType()) ===
DefaultOrthonormalBasis(ℂ, CotangentSpaceType())
end
_pts = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
@testset "basis representation" for BT in (
DefaultBasis,
DefaultOrthonormalBasis,
DefaultOrthogonalBasis,
DiagonalizingBasisProxy,
),
pts in (_pts, map(NonBroadcastBasisThing, _pts))
if BT == DiagonalizingBasisProxy && pts !== _pts
continue
end
v1 = log(M, pts[1], pts[2])
@test ManifoldsBase.number_of_coordinates(M, BT()) == 3
vb = get_coordinates(M, pts[1], v1, BT())
@test isa(vb, AbstractVector)
vbi = get_vector(M, pts[1], vb, BT())
@test isapprox(M, pts[1], v1, vbi)
b = get_basis(M, pts[1], BT())
if BT != DiagonalizingBasisProxy
if pts[1] isa Array
@test isa(
b,
CachedBasis{ℝ,BT{ℝ,TangentSpaceType},Vector{Vector{Float64}}},
)
else
@test isa(
b,
CachedBasis{
ℝ,
BT{ℝ,TangentSpaceType},
Vector{NonBroadcastBasisThing{Vector{Float64}}},
},
)
end
end
@test get_basis(M, pts[1], b) === b
N = manifold_dimension(M)
@test length(get_vectors(M, pts[1], b)) == N
# check orthonormality
if BT isa DefaultOrthonormalBasis && pts[1] isa Vector
for i in 1:N
@test norm(M, pts[1], get_vectors(M, pts[1], b)[i]) ≈ 1
for j in (i + 1):N
@test inner(
M,
pts[1],
get_vectors(M, pts[1], b)[i],
get_vectors(M, pts[1], b)[j],
) ≈ 0
end
end
# check that the coefficients correspond to the basis
for i in 1:N
@test inner(M, pts[1], v1, get_vectors(M, pts[1], b)[i]) ≈ vb[i]
end
end
if BT != DiagonalizingBasisProxy
@test get_coordinates(M, pts[1], v1, b) ≈
get_coordinates(M, pts[1], v1, BT())
@test get_vector(M, pts[1], vb, b) ≈ get_vector(M, pts[1], vb, BT())
end
v1c = Vector{Float64}(undef, 3)
get_coordinates!(M, v1c, pts[1], v1, b)
@test v1c ≈ get_coordinates(M, pts[1], v1, b)
v1cv = allocate(v1)
get_vector!(M, v1cv, pts[1], v1c, b)
@test isapprox(M, pts[1], v1, v1cv)
end
@testset "() Manifolds" begin
M = ManifoldsBase.DefaultManifold()
ManifoldsBase.allocate_coordinates(M, 1, Float64, 0) == 0.0
ManifoldsBase.allocate_coordinates(M, 1, Float64, 1) == zeros(Float64, 1)
ManifoldsBase.allocate_coordinates(M, 1, Float64, 2) == zeros(Float64, 2)
end
end
@testset "Complex DefaultManifold with real and complex Cached Bases" begin
M = ManifoldsBase.DefaultManifold(3; field = ℂ)
p = [1.0, 2.0im, 3.0]
X = [1.2, 2.2im, 2.3im]
b = [Matrix{Float64}(I, 3, 3)[:, i] for i in 1:3]
bℂ = [b..., (b .* 1im)...]
Bℝ = CachedBasis(DefaultOrthonormalBasis{ℂ}(), b)
aℝ = get_coordinates(M, p, X, Bℝ)
Yℝ = get_vector(M, p, aℝ, Bℝ)
@test Yℝ ≈ X
@test ManifoldsBase.number_of_coordinates(M, Bℝ) == 3
Bℂ = CachedBasis(DefaultOrthonormalBasis{ℝ}(), bℂ)
aℂ = get_coordinates(M, p, X, Bℂ)
Yℂ = get_vector(M, p, aℂ, Bℂ)
@test Yℂ ≈ X
@test ManifoldsBase.number_of_coordinates(M, Bℂ) == 6
@test change_basis(M, p, aℝ, Bℝ, Bℂ) ≈ aℂ
aℂ_sim = similar(aℂ)
change_basis!(M, aℂ_sim, p, aℝ, Bℝ, Bℂ)
@test aℂ_sim ≈ aℂ
end
@testset "Basis show methods" begin
@test sprint(show, DefaultBasis()) == "DefaultBasis(ℝ)"
@test sprint(show, DefaultOrthogonalBasis()) == "DefaultOrthogonalBasis(ℝ)"
@test sprint(show, DefaultOrthonormalBasis()) == "DefaultOrthonormalBasis(ℝ)"
@test sprint(show, DefaultOrthonormalBasis(ℂ)) == "DefaultOrthonormalBasis(ℂ)"
@test sprint(show, GramSchmidtOrthonormalBasis(ℂ)) ==
"GramSchmidtOrthonormalBasis(ℂ)"
@test sprint(show, ProjectedOrthonormalBasis(:svd)) ==
"ProjectedOrthonormalBasis(:svd, ℝ)"
@test sprint(show, ProjectedOrthonormalBasis(:gram_schmidt, ℂ)) ==
"ProjectedOrthonormalBasis(:gram_schmidt, ℂ)"
diag_onb = DiagonalizingOrthonormalBasis(Float64[1, 2, 3])
@test sprint(show, "text/plain", diag_onb) == """
DiagonalizingOrthonormalBasis(ℝ) with eigenvalue 0 in direction:
3-element $(sprint(show, Vector{Float64})):
1.0
2.0
3.0"""
M = DefaultManifold(2, 3)
x = collect(reshape(1.0:6.0, (2, 3)))
pb = get_basis(M, x, DefaultOrthonormalBasis())
B2 = DefaultOrthonormalBasis(ManifoldsBase.ℝ, ManifoldsBase.CotangentSpaceType())
pb2 = get_basis(M, x, B2)
test_basis_string = """
Cached basis of type $(sprint(show, typeof(DefaultOrthonormalBasis()))) with 6 basis vectors:
E1 =
2×3 $(sprint(show, Matrix{Float64})):
1.0 0.0 0.0
0.0 0.0 0.0
E2 =
2×3 $(sprint(show, Matrix{Float64})):
0.0 0.0 0.0
1.0 0.0 0.0
⋮
E5 =
2×3 $(sprint(show, Matrix{Float64})):
0.0 0.0 1.0
0.0 0.0 0.0
E6 =
2×3 $(sprint(show, Matrix{Float64})):
0.0 0.0 0.0
0.0 0.0 1.0"""
@test sprint(show, "text/plain", pb) == test_basis_string
@test sprint(show, "text/plain", pb2) == test_basis_string
b = DiagonalizingOrthonormalBasis(get_vectors(M, x, pb)[1])
dpb = CachedBasis(b, Float64[1, 2, 3, 4, 5, 6], get_vectors(M, x, pb))
@test sprint(show, "text/plain", dpb) == """
DiagonalizingOrthonormalBasis(ℝ) with eigenvalue 0 in direction:
2×3 $(sprint(show, Matrix{Float64})):
1.0 0.0 0.0
0.0 0.0 0.0
and 6 basis vectors.
Basis vectors:
E1 =
2×3 $(sprint(show, Matrix{Float64})):
1.0 0.0 0.0
0.0 0.0 0.0
E2 =
2×3 $(sprint(show, Matrix{Float64})):
0.0 0.0 0.0
1.0 0.0 0.0
⋮
E5 =
2×3 $(sprint(show, Matrix{Float64})):
0.0 0.0 1.0
0.0 0.0 0.0
E6 =
2×3 $(sprint(show, Matrix{Float64})):
0.0 0.0 0.0
0.0 0.0 1.0
Eigenvalues:
6-element $(sprint(show, Vector{Float64})):
1.0
2.0
3.0
4.0
5.0
6.0"""
M = DefaultManifold(1, 1, 1)
x = reshape(Float64[1], (1, 1, 1))
pb = get_basis(M, x, DefaultOrthonormalBasis())
@test sprint(show, "text/plain", pb) == """
Cached basis of type $(sprint(show, typeof(DefaultOrthonormalBasis()))) with 1 basis vector:
E1 =
1×1×1 $(sprint(show, Array{Float64,3})):
[:, :, 1] =
1.0"""
dpb = CachedBasis(
DiagonalizingOrthonormalBasis(get_vectors(M, x, pb)),
Float64[1],
get_vectors(M, x, pb),
)
@test sprint(show, "text/plain", dpb) == """
DiagonalizingOrthonormalBasis(ℝ) with eigenvalue 0 in direction:
1-element $(sprint(show, Vector{Array{Float64,3}})):
$(sprint(show, dpb.data.frame_direction[1]))
and 1 basis vector.
Basis vectors:
E1 =
1×1×1 $(sprint(show, Array{Float64,3})):
[:, :, 1] =
1.0
Eigenvalues:
1-element $(sprint(show, Vector{Float64})):
1.0"""
end
@testset "Bases of cotangent spaces" begin
b1 = DefaultOrthonormalBasis(ℝ, CotangentSpaceType())
@test b1.vector_space == CotangentSpaceType()
b2 = DefaultOrthogonalBasis(ℝ, CotangentSpaceType())
@test b2.vector_space == CotangentSpaceType()
b3 = DefaultBasis(ℝ, CotangentSpaceType())
@test b3.vector_space == CotangentSpaceType()
M = DefaultManifold(2; field = ℂ)
p = [1.0, 2.0im]
b1_d = ManifoldsBase.dual_basis(M, p, b1)
@test b1_d isa DefaultOrthonormalBasis
@test b1_d.vector_space == TangentSpaceType()
b1_d_d = ManifoldsBase.dual_basis(M, p, b1_d)
@test b1_d_d isa DefaultOrthonormalBasis
@test b1_d_d.vector_space == CotangentSpaceType()
end
@testset "Complex Basis - Mutating cases" begin
Mc = ManifoldsBase.DefaultManifold(2, field = ManifoldsBase.ℂ)
p = [1.0, 1.0im]
X = [2.0, 1.0im]
Bc = DefaultOrthonormalBasis(ManifoldsBase.ℂ)
CBc = get_basis(Mc, p, Bc)
@test CBc.data == [[1.0, 0.0], [0.0, 1.0]]
B = DefaultOrthonormalBasis(ManifoldsBase.ℝ)
CB = get_basis(Mc, p, B)
@test CB.data == [[1.0, 0.0], [0.0, 1.0], [1.0im, 0.0], [0.0, 1.0im]]
@test get_coordinates(Mc, p, X, CB) == [2.0, 0.0, 0.0, 1.0]
@test get_coordinates(Mc, p, X, CBc) == [2.0, 1.0im]
# ONB
cc = zeros(4)
@test get_coordinates!(Mc, cc, p, X, B) == [2.0, 0.0, 0.0, 1.0]
@test cc == [2.0, 0.0, 0.0, 1.0]
c = zeros(ComplexF64, 2)
@test get_coordinates!(Mc, c, p, X, Bc) == [2.0, 1.0im]
@test c == [2.0, 1.0im]
# Cached
@test get_coordinates!(Mc, cc, p, X, CB) == [2.0, 0.0, 0.0, 1.0]
@test cc == [2.0, 0.0, 0.0, 1.0]
@test get_coordinates!(Mc, c, p, X, CBc) == [2.0, 1.0im]
@test c == [2.0, 1.0im]
end
@testset "FVector" begin
@test sprint(show, TangentSpaceType()) == "TangentSpaceType()"
@test sprint(show, CotangentSpaceType()) == "CotangentSpaceType()"
tvs = ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0])
fv_tvs = map(v -> TFVector(v, DefaultOrthonormalBasis()), tvs)
fv1 = fv_tvs[1]
tv1s = allocate(fv_tvs[1])
@test isa(tv1s, FVector)
@test tv1s.type == TangentSpaceType()
@test size(tv1s.data) == size(tvs[1])
@test number_eltype(tv1s) == number_eltype(tvs[1])
@test number_eltype(tv1s) == number_eltype(typeof(tv1s))
@test isa(fv1 + fv1, FVector)
@test (fv1 + fv1).type == TangentSpaceType()
@test isa(fv1 - fv1, FVector)
@test (fv1 - fv1).type == TangentSpaceType()
@test isa(-fv1, FVector)
@test (-fv1).type == TangentSpaceType()
@test isa(2 * fv1, FVector)
@test (2 * fv1).type == TangentSpaceType()
tv1s_32 = allocate(fv_tvs[1], Float32)
@test isa(tv1s, FVector)
@test eltype(tv1s_32.data) === Float32
copyto!(tv1s, fv_tvs[2])
@test isapprox(tv1s.data, fv_tvs[2].data)
@test sprint(show, fv1) == "TFVector([1.0, 0.0, 0.0], $(fv1.basis))"
cofv1 = CoTFVector(tvs[1], DefaultOrthonormalBasis(ℝ, CotangentSpaceType()))
@test cofv1 isa CoTFVector
@test sprint(show, cofv1) == "CoTFVector([1.0, 0.0, 0.0], $(fv1.basis))"
end
@testset "vector_space_dimension" begin
M = ManifoldsBase.DefaultManifold(3)
MC = ManifoldsBase.DefaultManifold(3; field = ℂ)
@test ManifoldsBase.vector_space_dimension(M, TangentSpaceType()) == 3
@test ManifoldsBase.vector_space_dimension(M, CotangentSpaceType()) == 3
@test ManifoldsBase.vector_space_dimension(MC, TangentSpaceType()) == 6
@test ManifoldsBase.vector_space_dimension(MC, CotangentSpaceType()) == 6
end
@testset "requires_caching" begin
@test ManifoldsBase.requires_caching(ProjectedOrthonormalBasis(:svd))
@test !ManifoldsBase.requires_caching(DefaultBasis())
@test !ManifoldsBase.requires_caching(DefaultOrthogonalBasis())
@test !ManifoldsBase.requires_caching(DefaultOrthonormalBasis())
end
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 949 | using ManifoldsBase
import ManifoldsBase: representation_size, manifold_dimension, inner
using LinearAlgebra
using Test
struct ComplexEuclidean{N} <: AbstractManifold{ℂ} where {N} end
ComplexEuclidean(n::Int) = ComplexEuclidean{n}()
representation_size(::ComplexEuclidean{N}) where {N} = (N,)
manifold_dimension(::ComplexEuclidean{N}) where {N} = 2N
@inline inner(::ComplexEuclidean, x, v, w) = dot(v, w)
@testset "Complex Euclidean" begin
M = ComplexEuclidean(3)
x = complex.([1.0, 2.0, 3.0], [4.0, 5.0, 6.0])
v1 = complex.([0.1, 0.2, 0.3], [0.4, 0.5, 0.6])
v2 = complex.([0.3, 0.2, 0.1], [0.6, 0.5, 0.4])
@test norm(M, x, v1) isa Real
@test norm(M, x, v1) ≈ norm(v1)
@test angle(M, x, v1, v2) isa Real
@test angle(M, x, v1, v2) ≈ acos(real(dot(v1, v2)) / norm(v1) / norm(v2))
vv1 = vcat(reim(v1)...)
vv2 = vcat(reim(v2)...)
@test angle(M, x, v1, v2) ≈ acos(dot(normalize(vv1), normalize(vv2)))
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 5598 | using Test
using ManifoldsBase
using ManifoldsBase: AbstractTrait, TraitList, EmptyTrait, trait, merge_traits
using ManifoldsBase: expand_trait, next_trait
import ManifoldsBase: active_traits, parent_trait
struct IsCool <: AbstractTrait end
struct IsNice <: AbstractTrait end
abstract type AbstractA end
abstract type DecoA <: AbstractA end
# A few concrete types
struct A <: AbstractA end
struct A1 <: DecoA end
struct A2 <: DecoA end
struct A3 <: DecoA end
struct A4 <: DecoA end
struct A5 <: DecoA end
# just some function
f(::AbstractA, x) = x + 2
g(::DecoA, x, y) = x + y
struct IsGreat <: AbstractTrait end # a special case of IsNice
parent_trait(::IsGreat) = IsNice()
active_traits(f, ::A1, ::Any) = merge_traits(IsNice())
active_traits(f, ::A2, ::Any) = merge_traits(IsCool())
active_traits(f, ::A3, ::Any) = merge_traits(IsCool(), IsNice())
active_traits(f, ::A5, ::Any) = merge_traits(IsGreat())
f(a::DecoA, b) = f(trait(f, a, b), a, b)
f(::TraitList{IsNice}, a, b) = g(a, b, 3)
f(::TraitList{IsCool}, a, b) = g(a, b, 5)
# generic forward to the next trait to be looked at
f(t::TraitList, a, b) = f(next_trait(t), a, b)
# generic fallback when no traits are defined
f(::EmptyTrait, a, b) = invoke(f, Tuple{AbstractA,typeof(b)}, a, b)
@testset "Decorator trait tests" begin
t = ManifoldsBase.EmptyTrait()
t2 = ManifoldsBase.TraitList(t, t)
@test merge_traits() == t
@test merge_traits(t) == t
@test merge_traits(t, t) == t
@test merge_traits(t2) == t2
@test merge_traits(
merge_traits(IsGreat(), IsNice()),
merge_traits(IsGreat(), IsNice()),
) === merge_traits(IsGreat(), IsNice(), IsGreat(), IsNice())
@test expand_trait(merge_traits(IsGreat(), IsCool())) ===
merge_traits(IsGreat(), IsNice(), IsCool())
@test expand_trait(merge_traits(IsCool(), IsGreat())) ===
merge_traits(IsCool(), IsGreat(), IsNice())
@test string(merge_traits(IsGreat(), IsNice())) ==
"TraitList(IsGreat(), TraitList(IsNice(), EmptyTrait()))"
global f
@test f(A(), 0) == 2
@test f(A2(), 0) == 5
@test f(A3(), 0) == 5
@test f(A4(), 0) == 2
@test f(A5(), 890) == 893
f(::TraitList{IsGreat}, a, b) = g(a, b, 54)
@test f(A5(), 890) == 944
@test next_trait(EmptyTrait()) === EmptyTrait()
end
#
# A Manifold decorator test - check that EmptyTrait cases call Abstract and those fail with
# MethodError due to ambiguities (between Abstract and Decorator)
struct NonDecoratorManifold <: AbstractDecoratorManifold{ManifoldsBase.ℝ} end
ManifoldsBase.representation_size(::NonDecoratorManifold) = (2,)
@testset "Testing a NonDecoratorManifold - emptytrait fallbacks" begin
M = NonDecoratorManifold()
p = [2.0, 1.0]
q = similar(p)
X = [1.0, 0.0]
Y = similar(X)
@test ManifoldsBase.check_size(M, p) === nothing
@test ManifoldsBase.check_size(M, p, X) === nothing
# default to identity
@test embed(M, p) == p
@test embed!(M, q, p) == p
@test embed(M, p, X) == X
@test embed!(M, Y, p, X) == X
# the following is implemented but passes to the second and hence fails
@test_throws MethodError exp(M, p, X)
@test_throws MethodError exp(M, p, X, 2.0)
@test_throws MethodError exp!(M, q, p, X)
@test_throws MethodError exp!(M, q, p, X, 2.0)
@test_throws MethodError retract(M, p, X)
@test_throws MethodError retract(M, p, X, 2.0)
@test_throws MethodError retract!(M, q, p, X)
@test_throws MethodError retract!(M, q, p, X, 2.0)
@test_throws MethodError log(M, p, q)
@test_throws MethodError log!(M, Y, p, q)
@test_throws MethodError inverse_retract(M, p, q)
@test_throws MethodError inverse_retract!(M, Y, p, q)
@test_throws MethodError parallel_transport_along(M, p, X, :curve)
@test_throws MethodError parallel_transport_along!(M, Y, p, X, :curve)
@test_throws MethodError parallel_transport_direction(M, p, X, X)
@test_throws MethodError parallel_transport_direction!(M, Y, p, X, X)
@test_throws MethodError parallel_transport_to(M, p, X, q)
@test_throws MethodError parallel_transport_to!(M, Y, p, X, q)
@test_throws MethodError vector_transport_along(M, p, X, :curve)
@test_throws MethodError vector_transport_along!(M, Y, p, X, :curve)
end
# With even less, check that representation size stack overflows
struct NonDecoratorNonManifold <: AbstractDecoratorManifold{ManifoldsBase.ℝ} end
@testset "Testing a NonDecoratorNonManifold - emptytrait fallback Errors" begin
N = NonDecoratorNonManifold()
@test_throws StackOverflowError representation_size(N)
end
h(::AbstractA, x::Float64, y; a = 1) = x + y - a
h(::DecoA, x, y) = x + y
ManifoldsBase.@invoke_maker 1 AbstractA h(A::DecoA, x::Float64, y)
@testset "@invoke_maker" begin
@test h(A1(), 1.0, 2) == 2
sig = ManifoldsBase._split_signature(:(fname(x::T; k::Float64 = 1) where {T}))
@test sig.fname == :fname
@test sig.where_exprs == Any[:T]
@test sig.callargs == Any[:(x::T)]
@test sig.kwargs_list == Any[:($(Expr(:kw, :(k::Float64), 1)))]
@test sig.argnames == [:x]
@test sig.argtypes == [:T]
@test sig.kwargs_call == Expr[:(k = k)]
@test_throws ErrorException ManifoldsBase._split_signature(:(a = b))
sig2 = ManifoldsBase._split_signature(:(fname(x; kwargs...)))
@test sig2.kwargs_call == Expr[:(kwargs...)]
sig3 = ManifoldsBase._split_signature(:(fname(x::T, y::Int = 10; k1 = 1) where {T}))
@test sig3.kwargs_call == Expr[:(k1 = k1)]
@test sig3.callargs[2] == :($(Expr(:kw, :(y::Int), 10)))
@test sig3.argnames == [:x, :y]
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 30499 | using ManifoldsBase
using DoubleFloats
using ForwardDiff
using LinearAlgebra
using Random
using ReverseDiff
using StaticArrays
using Test
s = @__DIR__
!(s in LOAD_PATH) && (push!(LOAD_PATH, s))
using ManifoldsBaseTestUtils
@testset "Testing Default (Euclidean)" begin
M = ManifoldsBase.DefaultManifold(3)
types = [
Vector{Float64},
SizedVector{3,Float64,Vector{Float64}},
MVector{3,Float64},
Vector{Float32},
SizedVector{3,Float32,Vector{Float32}},
MVector{3,Float32},
Vector{Double64},
MVector{3,Double64},
SizedVector{3,Double64,Vector{Double64}},
DefaultPoint{Vector{Float64}},
]
@test repr(M) == "DefaultManifold(3; field = ℝ)"
@test isa(manifold_dimension(M), Integer)
@test manifold_dimension(M) ≥ 0
@test base_manifold(M) == M
@test number_system(M) == ManifoldsBase.ℝ
@test ManifoldsBase.representation_size(M) == (3,)
p = zeros(3)
m = PolarRetraction()
@test injectivity_radius(M) == Inf
@test injectivity_radius(M, p) == Inf
@test injectivity_radius(M, m) == Inf
@test injectivity_radius(M, p, m) == Inf
@test default_retraction_method(M) == ExponentialRetraction()
@test default_inverse_retraction_method(M) == LogarithmicInverseRetraction()
@test is_flat(M)
rm = ManifoldsBase.ExponentialRetraction()
irm = ManifoldsBase.LogarithmicInverseRetraction()
# Representation sizes not equal
@test ManifoldsBase.check_size(M, zeros(3, 3)) isa DomainError
@test ManifoldsBase.check_size(M, zeros(3), zeros(3, 3)) isa DomainError
rm2 = CustomDefinedRetraction()
rm3 = CustomUndefinedRetraction()
for T in types
@testset "Type $T" begin
pts = convert.(Ref(T), [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])
@test injectivity_radius(M, pts[1]) == Inf
@test injectivity_radius(M, pts[1], rm) == Inf
@test injectivity_radius(M, rm) == Inf
@test injectivity_radius(M, rm2) == 10
@test injectivity_radius(M, pts[1], rm2) == 10
tv1 = log(M, pts[1], pts[2])
for pt in pts
@test is_point(M, pt)
end
@test is_vector(M, pts[1], tv1; atol = eps(eltype(pts[1])))
tv2 = log(M, pts[2], pts[1])
tv3 = log(M, pts[2], pts[3])
@test isapprox(M, pts[2], exp(M, pts[1], tv1))
@test_logs (:info,) !isapprox(M, pts[1], pts[2]; error = :info)
@test isapprox(M, pts[1], pts[1]; error = :info)
@test_logs (:info,) !isapprox(
M,
pts[1],
convert(T, [NaN, NaN, NaN]);
error = :info,
)
@test isapprox(M, pts[1], exp(M, pts[1], tv1, 0))
@test isapprox(M, pts[2], exp(M, pts[1], tv1, 1))
@test isapprox(M, pts[1], exp(M, pts[2], tv2))
if T <: Array
@test_throws ApproximatelyError isapprox(M, pts[1], pts[2]; error = :error)
@test_throws ApproximatelyError isapprox(
M,
pts[2],
tv2,
tv3;
error = :error,
)
end
# test lower level fallbacks
@test ManifoldsBase.check_approx(M, pts[1], pts[2]) isa ApproximatelyError
@test ManifoldsBase.check_approx(M, pts[1], pts[1]) === nothing
@test ManifoldsBase.check_approx(M, pts[2], tv2, tv2) === nothing
@test is_point(M, retract(M, pts[1], tv1))
@test isapprox(M, pts[1], retract(M, pts[1], tv1, 0))
@test is_point(M, retract(M, pts[1], tv1, rm))
@test isapprox(M, pts[1], retract(M, pts[1], tv1, 0, rm))
new_pt = exp(M, pts[1], tv1)
retract!(M, new_pt, pts[1], tv1)
@test is_point(M, new_pt)
@test !isapprox(M, pts[1], [1, 2, 3], [3, 2, 4]; error = :other)
for p in pts
X_p_zero = zero_vector(M, p)
X_p_nan = NaN * X_p_zero
@test isapprox(M, p, X_p_zero, log(M, p, p); atol = eps(eltype(p)))
if T <: Array
@test_logs (:info,) !isapprox(
M,
p,
X_p_zero,
X_p_nan;
atol = eps(eltype(p)),
error = :info,
)
@test isapprox(
M,
p,
X_p_zero,
log(M, p, p);
atol = eps(eltype(p)),
error = :info,
)
end
@test isapprox(
M,
p,
X_p_zero,
inverse_retract(M, p, p);
atol = eps(eltype(p)),
)
@test isapprox(
M,
p,
X_p_zero,
inverse_retract(M, p, p, irm);
atol = eps(eltype(p)),
)
end
zero_vector!(M, tv1, pts[1])
@test isapprox(M, pts[1], tv1, zero_vector(M, pts[1]))
log!(M, tv1, pts[1], pts[2])
@test norm(M, pts[1], tv1) ≈ sqrt(inner(M, pts[1], tv1, tv1))
@test isapprox(M, exp(M, pts[1], tv1, 1), pts[2])
@test isapprox(M, exp(M, pts[1], tv1, 0), pts[1])
@test distance(M, pts[1], pts[2]) ≈ norm(M, pts[1], tv1)
@test distance(M, pts[1], pts[2], LogarithmicInverseRetraction()) ≈
norm(M, pts[1], tv1)
@test mid_point(M, pts[1], pts[2]) == convert(T, [0.5, 0.5, 0.0])
midp = allocate(pts[1])
@test mid_point!(M, midp, pts[1], pts[2]) === midp
@test midp == convert(T, [0.5, 0.5, 0.0])
@test riemann_tensor(M, pts[1], tv1, tv2, tv1) == zero(tv1)
tv_rt = allocate(tv1)
@test riemann_tensor!(M, tv_rt, pts[1], tv1, tv2, tv1) === tv_rt
@test tv_rt == zero(tv1)
@test sectional_curvature(M, pts[1], tv1, log(M, pts[1], pts[3])) == 0.0
@test sectional_curvature_max(M) == 0.0
@test sectional_curvature_min(M) == 0.0
q = copy(M, pts[1])
Ts = [0.0, 1.0 / 2, 1.0]
@testset "Geodesic interface test" begin
@test isapprox(M, geodesic(M, pts[1], tv1)(0.0), pts[1])
@test isapprox(M, geodesic(M, pts[1], tv1)(1.0), pts[2])
g! = geodesic!(M, pts[1], tv1)
g!(q, 0.0)
isapprox(M, q, pts[1])
g!(q, 0.0)
isapprox(M, q, pts[2])
geodesic!(M, q, pts[1], tv1, 1.0 / 2)
isapprox(M, q, midp)
@test isapprox(M, geodesic(M, pts[1], tv1, 1.0), pts[2])
@test isapprox(M, geodesic(M, pts[1], tv1, 1.0 / 2), midp)
@test isapprox(M, shortest_geodesic(M, pts[1], pts[2])(0.0), pts[1])
@test isapprox(M, shortest_geodesic(M, pts[1], pts[2])(1.0), pts[2])
sg! = shortest_geodesic!(M, pts[1], pts[2])
sg!(q, 0.0)
isapprox(M, q, pts[1])
sg!(q, 1.0)
isapprox(M, q, pts[2])
@test isapprox(M, shortest_geodesic(M, pts[1], pts[2], 0.0), pts[1])
@test isapprox(M, shortest_geodesic(M, pts[1], pts[2], 1.0), pts[2])
shortest_geodesic!(M, q, pts[1], pts[2], 0.5)
isapprox(M, q, midp)
@test all(
isapprox.(Ref(M), geodesic(M, pts[1], tv1, Ts), [pts[1], midp, pts[2]]),
)
@test all(
isapprox.(
Ref(M),
shortest_geodesic(M, pts[1], pts[2], Ts),
[pts[1], midp, pts[2]],
),
)
Q = [copy(M, q), copy(M, q), copy(M, q)]
geodesic!(M, Q, pts[1], tv1, Ts)
@test all(isapprox.(Ref(M), Q, [pts[1], midp, pts[2]]))
shortest_geodesic!(M, Q, pts[1], pts[2], Ts)
@test all(isapprox.(Ref(M), Q, [pts[1], midp, pts[2]]))
end
@testset "basic linear algebra in tangent space" begin
@test isapprox(
M,
pts[1],
0 * tv1,
zero_vector(M, pts[1]);
atol = eps(eltype(pts[1])),
)
@test isapprox(M, pts[1], 2 * tv1, tv1 + tv1)
@test isapprox(M, pts[1], 0 * tv1, tv1 - tv1)
@test isapprox(M, pts[1], (-1) * tv1, -tv1)
end
@testset "Change Representer and Metric" begin
G = ManifoldsBase.EuclideanMetric()
p = pts[1]
for X in [tv1, tv2, tv3]
@test change_representer(M, G, p, X) == X
Y = similar(X)
change_representer!(M, Y, G, p, X)
@test isapprox(M, p, Y, X)
@test change_metric(M, G, p, X) == X
Z = similar(X)
change_metric!(M, Z, G, p, X)
@test isapprox(M, p, Z, X)
end
end
@testset "Hat and vee in the tangent space" begin
X = log(M, pts[1], pts[2])
a = vee(M, pts[1], X)
b = similar(a)
vee!(M, b, pts[1], X)
Y = hat(M, pts[1], a)
Z = similar(Y)
hat!(M, Z, pts[1], a)
@test a == b
@test X == Y
@test Z == X
@test a == ((T <: DefaultPoint) ? vec(X.value) : vec(X))
end
@testset "broadcasted linear algebra in tangent space" begin
@test isapprox(M, pts[1], 3 * tv1, 2 .* tv1 .+ tv1)
@test isapprox(M, pts[1], -tv1, tv1 .- 2 .* tv1)
@test isapprox(M, pts[1], -tv1, .-tv1)
v = similar(tv1)
v .= 2 .* tv1 .+ tv1
@test isapprox(M, pts[1], v, 3 * tv1)
end
@testset "project test" begin
# point
@test isapprox(M, pts[1], project(M, pts[1]))
pt = similar(pts[1])
project!(M, pt, pts[1])
@test isapprox(M, pt, pts[1])
@test isapprox(M, pts[1], embed(M, pts[1]))
pt = similar(pts[1])
embed!(M, pt, pts[1])
@test isapprox(M, pt, pts[1])
# tangents
@test isapprox(M, pts[1], tv1, project(M, pts[1], tv1))
tv = similar(tv1)
project!(M, tv, pts[1], tv1)
@test isapprox(M, pts[1], tv, tv1)
@test isapprox(M, pts[1], tv1, embed(M, pts[1], tv1))
tv = similar(tv1)
embed!(M, tv, pts[1], tv1)
@test isapprox(M, pts[1], tv, tv1)
@test Weingarten(M, pts[1], tv, tv) == zero_vector(M, pts[1])
end
@testset "randon tests" begin
Random.seed!(23)
pr = rand(M)
@test is_point(M, pr, true)
Xr = rand(M; vector_at = pr)
@test is_vector(M, pr, Xr, true)
rng = MersenneTwister(42)
P = rand(M, 3)
@test length(P) == 3
@test all([is_point(M, pj) for pj in P])
Xv = rand(M, 3; vector_at = pr)
@test length(Xv) == 3
@test all([is_point(M, Xj) for Xj in Xv])
# and the same again with rng upfront
rng = MersenneTwister(42)
pr = rand(rng, M)
@test is_point(M, pr, true)
Xr = rand(rng, M; vector_at = pr)
@test is_vector(M, pr, Xr, true)
rng = MersenneTwister(42)
P = rand(rng, M, 3)
@test length(P) == 3
@test all([is_point(M, pj) for pj in P])
Xv = rand(rng, M, 3; vector_at = pr)
@test length(Xv) == 3
@test all([is_point(M, Xj) for Xj in Xv])
end
@testset "vector transport" begin
# test constructor
@test default_vector_transport_method(M) == ParallelTransport()
X1 = log(M, pts[1], pts[2])
X2 = log(M, pts[1], pts[3])
X1t1 = vector_transport_to(M, pts[1], X1, pts[3])
X1t2 = zero(X1t1)
vector_transport_to!(M, X1t2, pts[1], X1, X2, ProjectionTransport())
X1t3 = vector_transport_direction(M, pts[1], X1, X2)
@test ManifoldsBase.is_vector(M, pts[3], X1t1)
@test ManifoldsBase.is_vector(M, pts[3], X1t3)
@test isapprox(M, pts[3], X1t1, X1t3)
# along a `Vector` of points
c = [pts[1], pts[1]]
X1t4 = vector_transport_along(M, pts[1], X1, c)
@test isapprox(M, pts[1], X1, X1t4)
X1t5 = allocate(X1)
vector_transport_along!(M, X1t5, pts[1], X1, c)
@test isapprox(M, pts[1], X1, X1t5)
# transport along more than one interims point
@test vector_transport_along(M, pts[1], X1, pts[2:3]) == X1
X1t6 = allocate(X1)
vector_transport_along!(M, X1t6, pts[1], X1, pts[2:3])
@test isapprox(M, pts[1], X1, X1t6)
# along a custom type of points
if T <: DefaultPoint
S = eltype(pts[1].value)
mat = reshape(pts[1].value, length(pts[1].value), 1)
else
S = eltype(pts[1])
mat = reshape(pts[1], length(pts[1]), 1)
end
c2 = MatrixVectorTransport{S}(mat)
X1t4c2 = vector_transport_along(M, pts[1], X1, c2)
@test isapprox(M, pts[1], X1, X1t4c2)
X1t5c2 = allocate(X1)
vector_transport_along!(M, X1t5c2, pts[1], X1, c2)
@test isapprox(M, pts[1], X1, X1t5c2)
# On Euclidean Space Schild & Pole are identity
@test vector_transport_to(
M,
pts[1],
X2,
pts[2],
SchildsLadderTransport(),
) == X2
@test vector_transport_to(M, pts[1], X2, pts[2], PoleLadderTransport()) ==
X2
@test vector_transport_to(
M,
pts[1],
X2,
pts[2],
ScaledVectorTransport(ParallelTransport()),
) == X2
# along is also the identity
c = [
mid_point(M, pts[1], pts[2]),
pts[2],
mid_point(M, pts[2], pts[3]),
pts[3],
]
Xtmp = allocate(X2)
@test vector_transport_along(M, pts[1], X2, c, SchildsLadderTransport()) ==
X2
@test vector_transport_along!(
M,
Xtmp,
pts[1],
X2,
c,
SchildsLadderTransport(),
) == X2
@test vector_transport_along(M, pts[1], X2, c, PoleLadderTransport()) == X2
@test vector_transport_along!(
M,
Xtmp,
pts[1],
X2,
c,
PoleLadderTransport(),
) == X2
@test vector_transport_along(M, pts[1], X2, c, ParallelTransport()) == X2
@test vector_transport_along!(
M,
Xtmp,
pts[1],
X2,
c,
ParallelTransport(),
) == X2
@test ManifoldsBase._vector_transport_along!(
M,
Xtmp,
pts[1],
X2,
c,
ParallelTransport(),
) == X2
@test vector_transport_along(M, pts[1], X2, c, ProjectionTransport()) == X2
@test vector_transport_along!(
M,
Xtmp,
pts[1],
X2,
c,
ProjectionTransport(),
) == X2
# check mutating ones with defaults
p = allocate(pts[1])
ManifoldsBase.pole_ladder!(M, p, pts[1], pts[2], pts[3])
# -log_p3 p == log_p1 p2
@test isapprox(M, pts[3], -log(M, pts[3], p), log(M, pts[1], pts[2]))
ManifoldsBase.schilds_ladder!(M, p, pts[1], pts[2], pts[3])
@test isapprox(M, pts[3], log(M, pts[3], p), log(M, pts[1], pts[2]))
@test repr(ParallelTransport()) == "ParallelTransport()"
@test repr(ScaledVectorTransport(ParallelTransport())) ==
"ScaledVectorTransport(ParallelTransport())"
end
@testset "ForwardDiff support" begin
exp_f(t) = distance(M, pts[1], exp(M, pts[1], t * tv1))
d12 = distance(M, pts[1], pts[2])
for t in 0.1:0.1:0.9
@test d12 ≈ ForwardDiff.derivative(exp_f, t)
end
retract_f(t) = distance(M, pts[1], retract(M, pts[1], t * tv1))
for t in 0.1:0.1:0.9
@test ForwardDiff.derivative(retract_f, t) ≥ 0
end
end
isa(pts[1], Union{Vector,SizedVector}) && @testset "ReverseDiff support" begin
exp_f(t) = distance(M, pts[1], exp(M, pts[1], t[1] * tv1))
d12 = distance(M, pts[1], pts[2])
for t in 0.1:0.1:0.9
@test d12 ≈ ReverseDiff.gradient(exp_f, [t])[1]
end
retract_f(t) = distance(M, pts[1], retract(M, pts[1], t[1] * tv1))
for t in 0.1:0.1:0.9
@test ReverseDiff.gradient(retract_f, [t])[1] ≥ 0
end
end
end
end
@testset "mid_point on 0-index arrays" begin
M = ManifoldsBase.DefaultManifold(1)
p1 = fill(0.0)
p2 = fill(1.0)
@test isapprox(M, fill(0.5), mid_point(M, p1, p2))
end
@testset "Retraction" begin
a = NLSolveInverseRetraction(ExponentialRetraction())
@test a.retraction isa ExponentialRetraction
end
@testset "copy of points and vectors" begin
M = ManifoldsBase.DefaultManifold(2)
for (p, X) in (
([2.0, 3.0], [4.0, 5.0]),
(DefaultPoint([2.0, 3.0]), DefaultTVector([4.0, 5.0])),
)
q = similar(p)
copyto!(M, q, p)
@test p == q
r = copy(M, p)
@test r == p
Y = similar(X)
copyto!(M, Y, p, X)
@test Y == X
Z = copy(M, p, X)
@test Z == X
end
p1 = DefaultPoint([2.0, 3.0])
p2 = copy(p1)
@test (p1 == p2) && (p1 !== p2)
end
@testset "further vector and point automatic forwards" begin
M = ManifoldsBase.DefaultManifold(3)
p = DefaultPoint([1.0, 0.0, 0.0])
q = DefaultPoint([0.0, 0.0, 0.0])
X = DefaultTVector([0.0, 1.0, 0.0])
Y = DefaultTVector([1.0, 0.0, 0.0])
@test angle(M, p, X, Y) ≈ π / 2
@test inverse_retract(M, p, q, LogarithmicInverseRetraction()) == -Y
@test retract(M, q, Y, CustomDefinedRetraction()) == p
@test retract(M, q, Y, 1.0, CustomDefinedRetraction()) == p
@test retract(M, q, Y, ExponentialRetraction()) == p
@test retract(M, q, Y, 1.0, ExponentialRetraction()) == p
# rest not implemented - so they also fall back even onto mutating
Z = similar(Y)
r = similar(p)
# test passthrough using the dummy implementations
for retr in [
PolarRetraction(),
ProjectionRetraction(),
QRRetraction(),
SoftmaxRetraction(),
ODEExponentialRetraction(PolarRetraction(), DefaultBasis()),
PadeRetraction(2),
EmbeddedRetraction(ExponentialRetraction()),
SasakiRetraction(5),
]
@test retract(M, q, Y, retr) == DefaultPoint(q.value + Y.value)
@test retract(M, q, Y, 0.5, retr) == DefaultPoint(q.value + 0.5 * Y.value)
@test retract!(M, r, q, Y, retr) == DefaultPoint(q.value + Y.value)
@test retract!(M, r, q, Y, 0.5, retr) == DefaultPoint(q.value + 0.5 * Y.value)
end
mRK = RetractionWithKeywords(CustomDefinedKeywordRetraction(); scale = 3.0)
pRK = allocate(p, eltype(p.value), size(p.value))
@test retract(M, p, X, mRK) == DefaultPoint(3 * p.value + X.value)
@test retract(M, p, X, 0.5, mRK) == DefaultPoint(3 * p.value + 0.5 * X.value)
@test retract!(M, pRK, p, X, mRK) == DefaultPoint(3 * p.value + X.value)
@test retract!(M, pRK, p, X, 0.5, mRK) == DefaultPoint(3 * p.value + 0.5 * X.value)
mIRK = InverseRetractionWithKeywords(
CustomDefinedKeywordInverseRetraction();
scale = 3.0,
)
XIRK = allocate(X, eltype(X.value), size(X.value))
@test inverse_retract(M, p, pRK, mIRK) == DefaultTVector(pRK.value - 3 * p.value)
@test inverse_retract!(M, XIRK, p, pRK, mIRK) ==
DefaultTVector(pRK.value - 3 * p.value)
p2 = allocate(p, eltype(p.value), size(p.value))
@test size(p2.value) == size(p.value)
X2 = allocate(X, eltype(X.value), size(X.value))
@test size(X2.value) == size(X.value)
X3 = ManifoldsBase.allocate_result(M, log, p, q)
@test log!(M, X3, p, q) == log(M, p, q)
@test X3 == log(M, p, q)
@test log!(M, X3, p, q) == log(M, p, q)
@test X3 == log(M, p, q)
@test inverse_retract(M, p, q, CustomDefinedInverseRetraction()) == -2 * Y
@test distance(M, p, q, CustomDefinedInverseRetraction()) == 2.0
X4 = ManifoldsBase.allocate_result(M, inverse_retract, p, q)
@test inverse_retract!(M, X4, p, q) == inverse_retract(M, p, q)
@test X4 == inverse_retract(M, p, q)
# rest not implemented but check passthrough
for r in [
PolarInverseRetraction,
ProjectionInverseRetraction,
QRInverseRetraction,
SoftmaxInverseRetraction,
]
@test inverse_retract(M, q, p, r()) == DefaultTVector(p.value - q.value)
@test inverse_retract!(M, Z, q, p, r()) == DefaultTVector(p.value - q.value)
end
@test inverse_retract(
M,
q,
p,
EmbeddedInverseRetraction(LogarithmicInverseRetraction()),
) == DefaultTVector(p.value - q.value)
@test inverse_retract(M, q, p, NLSolveInverseRetraction(ExponentialRetraction())) ==
DefaultTVector(p.value - q.value)
@test inverse_retract!(
M,
Z,
q,
p,
EmbeddedInverseRetraction(LogarithmicInverseRetraction()),
) == DefaultTVector(p.value - q.value)
@test inverse_retract!(
M,
Z,
q,
p,
NLSolveInverseRetraction(ExponentialRetraction()),
) == DefaultTVector(p.value - q.value)
c = ManifoldsBase.allocate_coordinates(M, p, Float64, manifold_dimension(M))
@test c isa Vector
@test length(c) == 3
@test 2.0 \ X == DefaultTVector(2.0 \ X.value)
@test X + Y == DefaultTVector(X.value + Y.value)
@test +X == X
@test (Y .= X) === Y
# vector transport pass through
@test vector_transport_to(M, p, X, q, ProjectionTransport()) == X
@test vector_transport_direction(M, p, X, X, ProjectionTransport()) == X
@test vector_transport_to!(M, Y, p, X, q, ProjectionTransport()) == X
@test vector_transport_direction!(M, Y, p, X, X, ProjectionTransport()) == X
@test vector_transport_along(M, p, X, [p], ProjectionTransport()) == X
@test vector_transport_along!(M, Z, p, X, [p], ProjectionTransport()) == X
@test vector_transport_to(M, p, X, :q, ProjectionTransport()) == X
@test parallel_transport_to(M, p, X, q) == X
@test parallel_transport_direction(M, p, X, X) == X
@test parallel_transport_along(M, p, X, []) == X
@test parallel_transport_to!(M, Y, p, X, q) == X
@test parallel_transport_direction!(M, Y, p, X, X) == X
@test parallel_transport_along!(M, Y, p, X, []) == X
# convert with manifold
@test convert(typeof(p), M, p.value) == p
@test convert(typeof(X), M, p, X.value) == X
end
@testset "DefaultManifold and ONB" begin
M = ManifoldsBase.DefaultManifold(3)
p = [1.0f0, 0.0f0, 0.0f0]
CB = get_basis(M, p, DefaultOrthonormalBasis())
# make sure the right type is propagated
@test CB.data isa Vector{Vector{Float32}}
@test CB.data ==
[[1.0f0, 0.0f0, 0.0f0], [0.0f0, 1.0f0, 0.0f0], [0.0f0, 0.0f0, 1.0f0]]
# test complex point -> real coordinates
MC = ManifoldsBase.DefaultManifold(3; field = ManifoldsBase.ℂ)
p = [1.0im, 2.0im, -1.0im]
CB = get_basis(MC, p, DefaultOrthonormalBasis(ManifoldsBase.ℂ))
@test CB.data == [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
@test CB.data isa Vector{Vector{Float64}}
@test ManifoldsBase.coordinate_eltype(MC, p, ManifoldsBase.ℂ) === ComplexF64
@test ManifoldsBase.coordinate_eltype(MC, p, ManifoldsBase.ℝ) === Float64
CBR = get_basis(MC, p, DefaultOrthonormalBasis())
@test CBR.data == [
[1.0 + 0.0im, 0.0 + 0.0im, 0.0 + 0.0im],
[0.0 + 0.0im, 1.0 + 0.0im, 0.0 + 0.0im],
[0.0 + 0.0im, 0.0 + 0.0im, 1.0 + 0.0im],
[0.0 + 1.0im, 0.0 + 0.0im, 0.0 + 0.0im],
[0.0 + 0.0im, 0.0 + 1.0im, 0.0 + 0.0im],
[0.0 + 0.0im, 0.0 + 0.0im, 0.0 + 1.0im],
]
end
@testset "Show methods" begin
@test repr(CayleyRetraction()) == "CayleyRetraction()"
@test repr(PadeRetraction(2)) == "PadeRetraction(2)"
end
@testset "Further TestArrayRepresentation" begin
M = ManifoldsBase.DefaultManifold(3)
p = [1.0, 0.0, 0.0]
X = [1.0, 0.0, 0.0]
@test is_point(M, p, true)
@test is_vector(M, p, X, true)
pF = [1.0, 0.0]
XF = [0.0, 0.0]
m = ExponentialRetraction()
@test_throws DomainError is_point(M, pF, true)
@test_throws DomainError is_vector(M, p, XF; error = :error)
@test_throws DomainError is_vector(M, pF, XF, true; error = :error)
@test injectivity_radius(M) == Inf
@test injectivity_radius(M, p) == Inf
@test injectivity_radius(M, p, m) == Inf
@test injectivity_radius(M, m) == Inf
end
@testset "performance" begin
@allocated isapprox(M, SA[1, 2], SA[3, 4]) == 0
end
@testset "scalars" begin
M = ManifoldsBase.DefaultManifold()
p = 1.0
X = 2.0
@test copy(M, p) === p
@test copy(M, p, X) === X
end
@testset "static (size in type parameter)" begin
MS = ManifoldsBase.DefaultManifold(3; parameter = :type)
@test (@inferred representation_size(MS)) == (3,)
@test repr(MS) == "DefaultManifold(3; field = ℝ, parameter = :type)"
@test_throws ArgumentError ManifoldsBase.DefaultManifold(3; parameter = :foo)
end
@testset "complex vee and hat" begin
MC = ManifoldsBase.DefaultManifold(3; field = ManifoldsBase.ℂ)
p = [1im, 2 + 2im, 3.0]
@test isapprox(vee(MC, p, [1 + 2im, 3 + 4im, 5 + 6im]), [1, 3, 5, 2, 4, 6])
@test isapprox(hat(MC, p, [1, 3, 5, 2, 4, 6]), [1 + 2im, 3 + 4im, 5 + 6im])
end
ManifoldsBase.default_approximation_method(
::ManifoldsBase.DefaultManifold,
::typeof(exp),
) = GradientDescentEstimation()
@testset "Estimation Method defaults" begin
M = ManifoldsBase.DefaultManifold(3)
# Point generic type fallback
@test default_approximation_method(M, exp, Float64) ==
default_approximation_method(M, exp)
# Retraction
@test default_approximation_method(M, retract) == default_retraction_method(M)
@test default_approximation_method(M, retract, DefaultPoint) ==
default_retraction_method(M)
# Inverse Retraction
@test default_approximation_method(M, inverse_retract) ==
default_inverse_retraction_method(M)
@test default_approximation_method(M, inverse_retract, DefaultPoint) ==
default_inverse_retraction_method(M)
# Vector Transsports – all 3: to
@test default_approximation_method(M, vector_transport_to) ==
default_vector_transport_method(M)
@test default_approximation_method(M, vector_transport_to, DefaultPoint) ==
default_vector_transport_method(M)
# along
@test default_approximation_method(M, vector_transport_along) ==
default_vector_transport_method(M)
@test default_approximation_method(M, vector_transport_along, DefaultPoint) ==
default_vector_transport_method(M)
@test default_approximation_method(M, vector_transport_direction) ==
default_vector_transport_method(M)
@test default_approximation_method(M, vector_transport_direction, DefaultPoint) ==
default_vector_transport_method(M)
end
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 3411 | using ManifoldsBase
using ManifoldsBase: ℝ
using Test
struct ErrorTestManifold <: AbstractManifold{ℝ} end
function ManifoldsBase.check_size(::ErrorTestManifold, p)
size(p) != (2,) && return DomainError(size(p), "size $p not (2,)")
return nothing
end
function ManifoldsBase.check_size(::ErrorTestManifold, p, X)
size(X) != (2,) && return DomainError(size(X), "size $X not (2,)")
return nothing
end
function ManifoldsBase.check_point(::ErrorTestManifold, x)
if any(u -> u < 0, x)
return DomainError(x, "<0")
end
return nothing
end
function ManifoldsBase.check_vector(M::ErrorTestManifold, x, v)
mpe = ManifoldsBase.check_point(M, x)
mpe === nothing || return mpe
if any(u -> u < 0, v)
return DomainError(v, "<0")
end
return nothing
end
@testset "Domain errors" begin
M = ErrorTestManifold()
@test isa(ManifoldsBase.check_point(M, [-1, 1]), DomainError)
@test isa(ManifoldsBase.check_size(M, [-1, 1, 1]), DomainError)
@test isa(ManifoldsBase.check_size(M, [-1, 1], [1, 1, 1]), DomainError)
@test ManifoldsBase.check_point(M, [1, 1]) === nothing
@test !is_point(M, [-1, 1])
@test !is_point(M, [1, 1, 1]) # checksize fails
@test_throws DomainError is_point(M, [-1, 1, 1], true) # checksize errors
@test_throws DomainError is_point(M, [-1, 1, 1]; error = :error) # checksize errors
cs = "DomainError with (3,):\nsize [-1, 1, 1] not (2,)"
@test_logs (:info, cs) is_point(M, [-1, 1, 1]; error = :info)
@test_logs (:warn, cs) is_point(M, [-1, 1, 1]; error = :warn)
@test is_point(M, [1, 1])
@test is_point(M, [1, 1]; error = :error)
@test_throws DomainError is_point(M, [-1, 1], true)
@test_throws DomainError is_point(M, [-1, 1]; error = :error)
ps = "DomainError with [-1, 1]:\n<0"
@test_logs (:info, ps) is_point(M, [-1, 1]; error = :info)
@test_logs (:warn, ps) is_point(M, [-1, 1]; error = :warn)
@test isa(ManifoldsBase.check_vector(M, [1, 1], [-1, 1]), DomainError)
@test ManifoldsBase.check_vector(M, [1, 1], [1, 1]) === nothing
@test !is_vector(M, [1, 1], [-1, 1])
@test !is_vector(M, [1, 1], [1, 1, 1])
@test_throws DomainError is_vector(M, [1, 1], [-1, 1, 1], false, true)
@test_throws DomainError is_vector(M, [1, 1], [-1, 1, 1]; error = :error)
vs = "DomainError with (3,):\nsize [-1, 1, 1] not (2,)"
@test_logs (:info, vs) is_vector(M, [1, 1], [-1, 1, 1]; error = :info)
@test_logs (:warn, vs) is_vector(M, [1, 1], [-1, 1, 1]; error = :warn)
@test !is_vector(M, [1, 1, 1], [1, 1, 1], false)
@test_throws DomainError is_vector(M, [1, 1, 1], [1, 1], true, true)
@test_throws DomainError is_vector(M, [1, 1, 1], [1, 1], true; error = :error)
ps2 = "DomainError with (3,):\nsize [1, 1, 1] not (2,)"
@test_logs (:info, ps2) is_vector(M, [1, 1, 1], [1, 1], true; error = :info)
@test_logs (:warn, ps2) is_vector(M, [1, 1, 1], [1, 1], true; error = :warn)
@test is_vector(M, [1, 1], [1, 1])
@test is_vector(M, [1, 1], [1, 1]; error = :none)
@test_throws DomainError is_vector(M, [1, 1], [-1, 1]; error = :error)
@test_throws DomainError is_vector(M, [1, 1], [-1, 1], true; error = :error)
ps3 = "DomainError with [-1, 1]:\n<0"
@test_logs (:info, ps3) is_vector(M, [1, 1], [-1, 1], true; error = :info)
@test_logs (:warn, ps3) is_vector(M, [1, 1], [-1, 1], true; error = :warn)
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 18782 | using ManifoldsBase, Test
using ManifoldsBase: DefaultManifold, ℝ
#
# A first artificial (not real) manifold that is modelled as a submanifold
# half plane with euclidean metric is not a manifold but should test all things correctly here
#
struct HalfPlaneManifold <: AbstractDecoratorManifold{ℝ} end
struct PosQuadrantManifold <: AbstractDecoratorManifold{ℝ} end
ManifoldsBase.get_embedding(::HalfPlaneManifold) = ManifoldsBase.DefaultManifold(1, 3)
ManifoldsBase.decorated_manifold(::HalfPlaneManifold) = ManifoldsBase.DefaultManifold(2)
ManifoldsBase.representation_size(::HalfPlaneManifold) = (3,)
ManifoldsBase.get_embedding(::PosQuadrantManifold) = HalfPlaneManifold()
ManifoldsBase.representation_size(::PosQuadrantManifold) = (3,)
function ManifoldsBase.check_point(::HalfPlaneManifold, p)
return p[1] > 0 ? nothing : DomainError(p[1], "p[1] ≤ 0")
end
function ManifoldsBase.check_vector(::HalfPlaneManifold, p, X)
return X[1] > 0 ? nothing : DomainError(X[1], "X[1] ≤ 0")
end
function ManifoldsBase.check_point(::PosQuadrantManifold, p)
return p[2] > 0 ? nothing : DomainError(p[1], "p[2] ≤ 0")
end
function ManifoldsBase.check_vector(::PosQuadrantManifold, p, X)
return X[2] > 0 ? nothing : DomainError(X[1], "X[2] ≤ 0")
end
ManifoldsBase.embed(::HalfPlaneManifold, p) = reshape(p, 1, :)
ManifoldsBase.embed(::HalfPlaneManifold, p, X) = reshape(X, 1, :)
ManifoldsBase.project!(::HalfPlaneManifold, q, p) = (q .= [p[1] p[2] 0.0])
ManifoldsBase.project!(::HalfPlaneManifold, Y, p, X) = (Y .= [X[1] X[2] 0.0])
function ManifoldsBase.get_coordinates_orthonormal!(
::HalfPlaneManifold,
Y,
p,
X,
::ManifoldsBase.RealNumbers,
)
return (Y .= [X[1], X[2]])
end
function ManifoldsBase.get_vector_orthonormal!(
::HalfPlaneManifold,
Y,
p,
c,
::ManifoldsBase.RealNumbers,
)
return (Y .= [c[1] c[2] 0.0])
end
function ManifoldsBase.active_traits(f, ::HalfPlaneManifold, args...)
return ManifoldsBase.merge_traits(ManifoldsBase.IsEmbeddedSubmanifold())
end
function ManifoldsBase.active_traits(f, ::PosQuadrantManifold, args...)
return ManifoldsBase.merge_traits(ManifoldsBase.IsEmbeddedSubmanifold())
end
#
# A second manifold that is modelled as just isometrically embedded but not a submanifold
#
struct AnotherHalfPlanemanifold <: AbstractDecoratorManifold{ℝ} end
ManifoldsBase.get_embedding(::AnotherHalfPlanemanifold) = ManifoldsBase.DefaultManifold(3)
function ManifoldsBase.decorated_manifold(::AnotherHalfPlanemanifold)
return ManifoldsBase.DefaultManifold(2)
end
ManifoldsBase.representation_size(::AnotherHalfPlanemanifold) = (2,)
function ManifoldsBase.active_traits(f, ::AnotherHalfPlanemanifold, args...)
return ManifoldsBase.merge_traits(ManifoldsBase.IsIsometricEmbeddedManifold())
end
function ManifoldsBase.embed!(::AnotherHalfPlanemanifold, q, p)
q[1:2] .= p
q[3] = 0
return q
end
function ManifoldsBase.embed!(::AnotherHalfPlanemanifold, Y, p, X)
Y[1:2] .= X
Y[3] = 0
return Y
end
function ManifoldsBase.project!(::AnotherHalfPlanemanifold, q, p)
return q .= [p[1], p[2]]
end
function ManifoldsBase.project!(::AnotherHalfPlanemanifold, Y, p, X)
return Y .= [X[1], X[2]]
end
function ManifoldsBase.exp!(::AnotherHalfPlanemanifold, q, p, X)
return q .= p .+ X
end
function ManifoldsBase.vector_transport_along_embedded!(
::AnotherHalfPlanemanifold,
Y,
p,
X,
c,
::ParallelTransport,
)
return Y .= X .+ 1 # +1 for check
end
#
# Third example - explicitly mention an embedding.
#
function ManifoldsBase.embed!(
::EmbeddedManifold{𝔽,DefaultManifold{𝔽,nL},DefaultManifold{𝔽2,mL}},
q,
p,
) where {nL,mL,𝔽,𝔽2}
n = size(p)
ln = length(n)
m = size(q)
lm = length(m)
(length(n) > length(m)) && throw(
DomainError(
"Invalid embedding, since Euclidean dimension ($(n)) is longer than embedding dimension $(m).",
),
)
any(n .> m[1:ln]) && throw(
DomainError(
"Invalid embedding, since Euclidean dimension ($(n)) has entry larger than embedding dimensions ($(m)).",
),
)
fill!(q, 0)
q[map(ind_n -> Base.OneTo(ind_n), n)..., ntuple(_ -> 1, lm - ln)...] .= p
return q
end
function ManifoldsBase.project!(
::EmbeddedManifold{𝔽,DefaultManifold{𝔽,nL},DefaultManifold{𝔽2,mL}},
q,
p,
) where {nL,mL,𝔽,𝔽2}
n = size(p)
ln = length(n)
m = size(q)
lm = length(m)
(length(n) < length(m)) && throw(
DomainError(
"Invalid embedding, since Euclidean dimension ($(n)) is longer than embedding dimension $(m).",
),
)
any(n .< m[1:ln]) && throw(
DomainError(
"Invalid embedding, since Euclidean dimension ($(n)) has entry larger than embedding dimensions ($(m)).",
),
)
# fill q with the „top left edge“ of p.
q .= p[map(i -> Base.OneTo(i), m)..., ntuple(_ -> 1, lm - ln)...]
return q
end
#
# A manifold that is a submanifold but otherwise has not implementations
#
struct NotImplementedEmbeddedSubManifold <: AbstractDecoratorManifold{ℝ} end
function ManifoldsBase.get_embedding(::NotImplementedEmbeddedSubManifold)
return ManifoldsBase.DefaultManifold(3)
end
function ManifoldsBase.decorated_manifold(::NotImplementedEmbeddedSubManifold)
return ManifoldsBase.DefaultManifold(2)
end
function ManifoldsBase.active_traits(f, ::NotImplementedEmbeddedSubManifold, args...)
return ManifoldsBase.merge_traits(ManifoldsBase.IsEmbeddedSubmanifold())
end
#
# A manifold that is isometrically embedded but has no implementations
#
struct NotImplementedIsometricEmbeddedManifold <: AbstractDecoratorManifold{ℝ} end
function ManifoldsBase.active_traits(f, ::NotImplementedIsometricEmbeddedManifold, args...)
return ManifoldsBase.merge_traits(ManifoldsBase.IsIsometricEmbeddedManifold())
end
#
# A manifold that is an embedded manifold but not isometric and has no other implementation
#
struct NotImplementedEmbeddedManifold <: AbstractDecoratorManifold{ℝ} end
function ManifoldsBase.active_traits(f, ::NotImplementedEmbeddedManifold, args...)
return ManifoldsBase.merge_traits(ManifoldsBase.IsEmbeddedManifold())
end
#
# A Manifold with a fallback
#
struct FallbackManifold <: AbstractDecoratorManifold{ℝ} end
function ManifoldsBase.active_traits(f, ::FallbackManifold, args...)
return ManifoldsBase.merge_traits(ManifoldsBase.IsExplicitDecorator())
end
ManifoldsBase.decorated_manifold(::FallbackManifold) = DefaultManifold(3)
@testset "Embedded Manifolds" begin
@testset "EmbeddedManifold basic tests" begin
M = EmbeddedManifold(
ManifoldsBase.DefaultManifold(2),
ManifoldsBase.DefaultManifold(3),
)
@test repr(M) ==
"EmbeddedManifold($(sprint(show, M.manifold)), $(sprint(show, M.embedding)))"
@test base_manifold(M) == ManifoldsBase.DefaultManifold(2)
@test base_manifold(M, Val(0)) == M
@test base_manifold(M, Val(1)) == ManifoldsBase.DefaultManifold(2)
@test base_manifold(M, Val(2)) == ManifoldsBase.DefaultManifold(2)
@test get_embedding(M) == ManifoldsBase.DefaultManifold(3)
@test get_embedding(M, [1, 2, 3]) == ManifoldsBase.DefaultManifold(3)
end
@testset "HalfPlanemanifold" begin
M = HalfPlaneManifold()
N = PosQuadrantManifold()
@test repr(M) == "HalfPlaneManifold()"
@test get_embedding(M) == ManifoldsBase.DefaultManifold(1, 3)
@test representation_size(M) == (3,)
# Check point checks using embedding
@test is_point(M, [1 0.1 0.1], true)
@test !is_point(M, [-1, 0, 0]) #wrong dim (3,1)
@test_throws DomainError is_point(M, [-1, 0, 0], true)
@test !is_point(M, [-1, 0, 0])
@test !is_point(M, [1, 0.1]) # size (from embedding)
@test_throws ManifoldDomainError is_point(M, [1, 0.1], true)
@test !is_point(M, [1, 0.1])
@test is_point(M, [1 0 0], true)
@test !is_point(M, [-1 0 0]) # right size but <0 1st
@test_throws DomainError is_point(M, [-1 0 0], true) # right size but <0 1st
@test !is_vector(M, [1 0 0], [1]) # right point, wrong size vector
@test_throws ManifoldDomainError is_vector(M, [1 0 0], [1]; error = :error)
@test !is_vector(M, [1 0 0], [1])
@test_throws DomainError is_vector(M, [1 0 0], [-1 0 0]; error = :error) # right point, vec 1st <0
@test !is_vector(M, [1 0 0], [-1 0 0])
@test is_vector(M, [1 0 0], [1 0 1], true)
@test !is_vector(M, [-1, 0, 0], [0, 0, 0])
@test_throws DomainError is_vector(M, [-1, 0, 0], [0, 0, 0]; error = :error)
@test_throws DomainError is_vector(M, [1, 0, 0], [-1, 0, 0]; error = :error)
@test !is_vector(M, [-1, 0, 0], [0, 0, 0])
@test !is_vector(M, [1, 0, 0], [-1, 0, 0])
# check manifold domain error from embedding to obtain ManifoldDomainErrors
@test !is_point(N, [0, 0, 0])
@test_throws ManifoldDomainError is_point(N, [0, 0, 0]; error = :error)
@test !is_vector(N, [1, 1, 0], [0, 0, 0])
@test_throws ManifoldDomainError is_vector(N, [1, 1, 0], [0, 0, 0]; error = :error)
p = [1.0 1.0 0.0]
q = [1.0 0.0 0.0]
X = q - p
@test ManifoldsBase.check_size(M, p) === nothing
@test ManifoldsBase.check_size(M, p, X) === nothing
@test ManifoldsBase.check_size(M, [1, 2]) isa ManifoldDomainError
@test ManifoldsBase.check_size(M, [1 2 3 4]) isa ManifoldDomainError
@test ManifoldsBase.check_size(M, p, [1, 2]) isa ManifoldDomainError
@test ManifoldsBase.check_size(M, p, [1 2 3 4]) isa ManifoldDomainError
@test embed(M, p) == p
pE = similar(p)
embed!(M, pE, p)
@test pE == p
P = [1.0 1.0 2.0]
Q = similar(P)
@test project!(M, Q, P) == project!(M, Q, P)
@test project!(M, Q, P) == embed_project!(M, Q, P)
@test project!(M, Q, P) == [1.0 1.0 0.0]
@test isapprox(M, p, zero_vector(M, p), [0 0 0])
XZ = similar(X)
zero_vector!(M, XZ, p)
@test isapprox(M, p, XZ, [0 0 0])
XE = similar(X)
embed!(M, XE, p, X)
XE2 = embed(M, p, X)
@test X == XE
@test XE == XE2
@test log(M, p, q) == q - p
Y = similar(p)
log!(M, Y, p, q)
@test Y == q - p
@test exp(M, p, X) == q
@test exp(M, p, X, 1.0) == q
r = similar(p)
exp!(M, r, p, X)
@test r == q
exp!(M, r, p, X, 1.0)
@test r == q
@test distance(M, p, r) == norm(r - p)
@test retract(M, p, X) == q
@test retract(M, p, X, 1.0) == q
q2 = similar(q)
@test retract!(M, q2, p, X) == q
@test retract!(M, q2, p, X, 1.0) == q
@test q2 == q
@test inverse_retract(M, p, q) == X
Y = similar(X)
@test inverse_retract!(M, Y, p, q) == X
@test Y == X
@test vector_transport_along(M, p, X, []) == X
@test vector_transport_along!(M, Y, p, X, []) == X
@test parallel_transport_along(M, p, X, []) == X
@test parallel_transport_along!(M, Y, p, X, []) == X
@test parallel_transport_direction(M, p, X, X) == X
@test parallel_transport_direction!(M, Y, p, X, X) == X
@test parallel_transport_to(M, p, X, q) == X
@test parallel_transport_to!(M, Y, p, X, q) == X
@test get_basis(M, p, DefaultOrthonormalBasis()) isa CachedBasis
Xc = [X[1], X[2]]
Yc = similar(Xc)
@test get_coordinates(M, p, X, DefaultOrthonormalBasis()) == Xc
@test get_coordinates!(M, Yc, p, X, DefaultOrthonormalBasis()) == Xc
@test get_vector(M, p, Xc, DefaultOrthonormalBasis()) == X
@test get_vector!(M, Y, p, Xc, DefaultOrthonormalBasis()) == X
end
@testset "AnotherHalfPlanemanifold" begin
M = AnotherHalfPlanemanifold()
p = [1.0, 2.0]
pe = embed(M, p)
@test pe == [1.0, 2.0, 0.0]
X = [2.0, 3.0]
Xe = embed(M, pe, X)
@test Xe == [2.0, 3.0, 0.0]
@test project(M, pe) == p
@test embed_project(M, p) == p
@test embed_project(M, p, X) == X
Xs = similar(X)
@test embed_project!(M, Xs, p, X) == X
@test project(M, pe, Xe) == X
# isometric passtthrough
@test injectivity_radius(M) == Inf
@test injectivity_radius(M, p) == Inf
@test injectivity_radius(M, p, ExponentialRetraction()) == Inf
@test injectivity_radius(M, ExponentialRetraction()) == Inf
# test vector transports in the embedding
m = EmbeddedVectorTransport(ParallelTransport())
q = [2.0, 2.0]
@test vector_transport_to(M, p, X, q, m) == X #since its PT on R^3
@test vector_transport_direction(M, p, X, q, m) == X
@test vector_transport_along(M, p, X, [], m) == X .+ 1 #as specified in definition above
end
@testset "Test nonimplemented fallbacks" begin
@testset "Submanifold Embedding Fallbacks & Error Tests" begin
M = NotImplementedEmbeddedSubManifold()
A = zeros(2)
# for a submanifold quite a lot of functions are passed on
@test ManifoldsBase.check_point(M, [1, 2]) === nothing
@test ManifoldsBase.check_vector(M, [1, 2], [3, 4]) === nothing
@test norm(M, [1, 2], [2, 3]) ≈ sqrt(13)
@test distance(M, [1, 2], [3, 4]) ≈ sqrt(8)
@test inner(M, [1, 2], [2, 3], [2, 3]) == 13
@test manifold_dimension(M) == 2 # since base is defined is defined
@test_throws MethodError project(M, [1, 2])
@test_throws MethodError project(M, [1, 2], [2, 3]) == [2, 3]
@test_throws MethodError project!(M, A, [1, 2], [2, 3])
@test vector_transport_direction(M, [1, 2], [2, 3], [3, 4]) == [2, 3]
vector_transport_direction!(M, A, [1, 2], [2, 3], [3, 4])
@test A == [2, 3]
@test vector_transport_to(M, [1, 2], [2, 3], [3, 4]) == [2, 3]
vector_transport_to!(M, A, [1, 2], [2, 3], [3, 4])
@test A == [2, 3]
@test @inferred !isapprox(M, [1, 2], [2, 3])
@test @inferred !isapprox(M, [1, 2], [2, 3], [4, 5])
end
@testset "Isometric Embedding Fallbacks & Error Tests" begin
M2 = NotImplementedIsometricEmbeddedManifold()
@test base_manifold(M2) == M2
A = zeros(2)
# Check that all of these report not to be implemented, i.e.
@test_throws MethodError exp(M2, [1, 2], [2, 3])
@test_throws MethodError exp(M2, [1, 2], [2, 3], 1.0)
@test_throws MethodError exp!(M2, A, [1, 2], [2, 3])
@test_throws MethodError exp!(M2, A, [1, 2], [2, 3], 1.0)
@test_throws MethodError retract(M2, [1, 2], [2, 3])
@test_throws MethodError retract(M2, [1, 2], [2, 3], 1.0)
@test_throws MethodError retract!(M2, A, [1, 2], [2, 3])
@test_throws MethodError retract!(M2, A, [1, 2], [2, 3], 1.0)
@test_throws MethodError log(M2, [1, 2], [2, 3])
@test_throws MethodError log!(M2, A, [1, 2], [2, 3])
@test_throws MethodError inverse_retract(M2, [1, 2], [2, 3])
@test_throws MethodError inverse_retract!(M2, A, [1, 2], [2, 3])
@test_throws MethodError distance(M2, [1, 2], [2, 3])
@test_throws StackOverflowError manifold_dimension(M2)
@test_throws MethodError project(M2, [1, 2])
@test_throws MethodError project!(M2, A, [1, 2])
@test_throws MethodError project(M2, [1, 2], [2, 3])
@test_throws MethodError project!(M2, A, [1, 2], [2, 3])
@test_throws MethodError vector_transport_along(M2, [1, 2], [2, 3], [[1, 2]])
@test_throws MethodError vector_transport_along(
M2,
[1, 2],
[2, 3],
[[1, 2]],
ParallelTransport(),
)
@test vector_transport_along!(M2, A, [1, 2], [2, 3], []) == [2, 3]
@test A == [2, 3]
@test_throws MethodError vector_transport_direction(M2, [1, 2], [2, 3], [3, 4])
@test_throws MethodError vector_transport_direction!(
M2,
A,
[1, 2],
[2, 3],
[3, 4],
)
@test_throws MethodError vector_transport_to(M2, [1, 2], [2, 3], [3, 4])
@test_throws MethodError vector_transport_to!(M2, A, [1, 2], [2, 3], [3, 4])
end
@testset "Nonisometric Embedding Fallback Error Rests" begin
M3 = NotImplementedEmbeddedManifold()
@test_throws MethodError inner(M3, [1, 2], [2, 3], [2, 3])
@test_throws StackOverflowError manifold_dimension(M3)
@test_throws MethodError distance(M3, [1, 2], [2, 3])
@test_throws MethodError norm(M3, [1, 2], [2, 3])
@test_throws MethodError embed(M3, [1, 2], [2, 3])
@test_throws MethodError embed(M3, [1, 2])
@test @inferred !isapprox(M3, [1, 2], [2, 3])
@test @inferred !isapprox(M3, [1, 2], [2, 3], [4, 5])
end
end
@testset "Explicit Embeddings using EmbeddedManifold" begin
M = DefaultManifold(3, 3)
N = DefaultManifold(4, 4)
O = EmbeddedManifold(M, N)
# first test with same length of sizes
p = ones(3, 3)
q = zeros(4, 4)
qT = zeros(4, 4)
qT[1:3, 1:3] .= 1.0
embed!(O, q, p)
@test norm(qT - q) == 0
qM = embed(O, p)
@test norm(project(O, qM) - p) == 0
@test norm(qT - qM) == 0
# test with different sizes, check that it only fills first element
q2 = zeros(4, 4, 3)
q2T = zeros(4, 4, 3)
q2T[1:3, 1:3, 1] .= 1.0
embed!(O, q2, p)
@test norm(q2T - q2) == 0
O2 = EmbeddedManifold(M, DefaultManifold(4, 4, 3))
q2M = embed(O2, p)
@test norm(q2T - q2M) == 0
# wrong size error checks
@test_throws DomainError embed!(O, zeros(3, 3), zeros(3, 3, 5))
@test_throws DomainError embed!(O, zeros(3, 3), zeros(4, 4))
@test_throws DomainError project!(O, zeros(3, 3, 5), zeros(3, 3))
@test_throws DomainError project!(O, zeros(4, 4), zeros(3, 3))
end
@testset "Explicit Fallback" begin
M = FallbackManifold()
# test the explicit fallback to DefaultManifold(3)
@test inner(M, [1, 0, 0], [1, 2, 3], [0, 1, 0]) == 2
@test is_point(M, [1, 0, 0])
@test ManifoldsBase.allocate_result(M, exp, [1.0, 0.0, 2.0]) isa Vector
end
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 5603 | using ManifoldsBase, Test
using Test
@testset "AbstractManifold with empty implementation" begin
M = NonManifold()
p = NonMPoint()
v = NonTVector()
@test base_manifold(M) === M
@test number_system(M) === ℝ
@test representation_size(M) === nothing
@test_throws MethodError manifold_dimension(M)
# by default isapprox compares given points or vectors
@test isapprox(M, [0], [0])
@test isapprox(M, [0], [0]; atol = 1e-6)
@test !isapprox(M, [0], [1])
@test !isapprox(M, [0], [1]; atol = 1e-6)
@test isapprox(M, [0], [0], [0])
@test isapprox(M, [0], [0], [0]; atol = 1e-6)
@test !isapprox(M, [0], [0], [1])
@test !isapprox(M, [0], [0], [1]; atol = 1e-6)
exp_retr = ManifoldsBase.ExponentialRetraction()
@test_throws MethodError retract!(M, p, p, v)
@test_throws MethodError retract!(M, p, p, v, exp_retr)
@test_throws MethodError retract!(M, p, p, [0.0], 0.0)
@test_throws MethodError retract!(M, p, p, [0.0], 0.0, exp_retr)
@test_throws MethodError retract!(M, [0], [0], [0])
@test_throws MethodError retract!(M, [0], [0], [0], exp_retr)
@test_throws MethodError retract!(M, [0], [0], [0], 0.0)
@test_throws MethodError retract!(M, [0], [0], [0], 0.0, exp_retr)
@test_throws MethodError retract(M, [0], [0])
@test_throws MethodError retract(M, [0], [0], exp_retr)
@test_throws MethodError retract(M, [0], [0], 0.0)
@test_throws MethodError retract(M, [0], [0], 0.0, exp_retr)
@test_throws MethodError retract(M, [0.0], [0.0])
@test_throws MethodError retract(M, [0.0], [0.0], exp_retr)
@test_throws MethodError retract(M, [0.0], [0.0], 0.0)
@test_throws MethodError retract(M, [0.0], [0.0], 0.0, exp_retr)
@test_throws MethodError retract(M, [0.0], [0.0], NotImplementedRetraction())
log_invretr = ManifoldsBase.LogarithmicInverseRetraction()
@test_throws MethodError inverse_retract!(M, p, p, p)
@test_throws MethodError inverse_retract!(M, p, p, p, log_invretr)
@test_throws MethodError inverse_retract!(M, [0], [0], [0])
@test_throws MethodError inverse_retract!(M, [0], [0], [0], log_invretr)
@test_throws MethodError inverse_retract(M, [0], [0])
@test_throws MethodError inverse_retract(M, [0], [0], log_invretr)
@test_throws MethodError inverse_retract(M, [0.0], [0.0])
@test_throws MethodError inverse_retract(M, [0.0], [0.0], log_invretr)
@test_throws MethodError inverse_retract(
M,
[0.0],
[0.0],
NotImplementedInverseRetraction(),
)
@test_throws MethodError project!(M, p, [0])
@test_throws MethodError project!(M, [0], [0])
@test_throws MethodError project(M, [0])
@test_throws MethodError project!(M, v, p, [0.0])
@test_throws MethodError project!(M, [0], [0], [0])
@test_throws MethodError project(M, [0], [0])
@test_throws MethodError project(M, [0.0], [0.0])
@test_throws MethodError inner(M, p, v, v)
@test_throws MethodError inner(M, [0], [0], [0])
@test_throws MethodError norm(M, p, v)
@test_throws MethodError norm(M, [0], [0])
@test_throws MethodError angle(M, p, v, v)
@test_throws MethodError angle(M, [0], [0], [0])
@test_throws MethodError distance(M, [0.0], [0.0])
@test_throws MethodError exp!(M, p, p, v)
@test_throws MethodError exp!(M, p, p, v, 0.0)
@test_throws MethodError exp!(M, [0], [0], [0])
@test_throws MethodError exp!(M, [0], [0], [0], 0.0)
@test_throws MethodError exp(M, [0], [0])
@test_throws MethodError exp(M, [0], [0], 0.0)
@test_throws MethodError exp(M, [0.0], [0.0])
@test_throws MethodError exp(M, [0.0], [0.0], 0.0)
@test_throws MethodError embed!(M, p, [0]) # no copy for NoPoint p
@test embed!(M, [0], [0]) == [0]
@test embed(M, [0]) == [0]
# Identity
@test_throws MethodError embed!(M, v, p, [0.0]) # no copyto
@test embed!(M, [0], [0], [0]) == [0]
@test_throws MethodError embed(M, [0], v) # no copyto
@test embed(M, [0.0], [0.0]) == [0.0]
@test_throws MethodError log!(M, v, p, p)
@test_throws MethodError log!(M, [0], [0], [0])
@test_throws MethodError log(M, [0.0], [0.0])
@test_throws MethodError vector_transport_to!(M, [0], [0], [0], [0])
@test_throws MethodError vector_transport_to(M, [0], [0], [0])
@test_throws MethodError vector_transport_to!(M, [0], [0], [0], ProjectionTransport())
@test_throws MethodError vector_transport_direction!(M, [0], [0], [0], [0])
@test_throws MethodError vector_transport_direction(M, [0], [0], [0])
@test_throws MethodError ManifoldsBase.vector_transport_along!(M, [0], [0], [0], x -> x)
@test_throws MethodError vector_transport_along(M, [0], [0], x -> x)
@test_throws MethodError injectivity_radius(M)
@test_throws MethodError injectivity_radius(M, [0])
@test_throws MethodError injectivity_radius(M, [0], exp_retr)
@test_throws MethodError injectivity_radius(M, exp_retr)
@test_throws MethodError zero_vector!(M, [0], [0])
@test_throws MethodError zero_vector(M, [0])
@test ManifoldsBase.check_point(M, [0]) === nothing
@test ManifoldsBase.check_point(M, p) === nothing
@test is_point(M, [0])
@test ManifoldsBase.check_point(M, [0]) === nothing
@test ManifoldsBase.check_vector(M, [0], [0]) === nothing
@test ManifoldsBase.check_vector(M, p, v) === nothing
@test is_vector(M, [0], [0])
@test ManifoldsBase.check_vector(M, [0], [0]) === nothing
@test_throws MethodError hat!(M, [0], [0], [0])
@test_throws MethodError vee!(M, [0], [0], [0])
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
|
[
"MIT"
] | 0.15.17 | 4259c5f29dbe9d7441ec0f5ce31c2a6895285495 | code | 1272 | #
# Test specific error methods
#
using ManifoldsBase
using Test
@testset "Test specific Errors and their format." begin
e = DomainError(1.0, "Norm not zero.") # a dummy
e2 = ComponentManifoldError(1, e)
s1 = sprint(showerror, e)
s2 = sprint(showerror, e2)
@test s2 == "At #1: $(s1)"
e3 = CompositeManifoldError()
s3 = sprint(showerror, e3)
@test s3 == "CompositeManifoldError()\n"
@test length(e3) == 0
@test isempty(e3)
@test repr(e3) == "CompositeManifoldError()"
e4 = CompositeManifoldError([e2])
@test repr(e4) == "CompositeManifoldError([$(repr(e2)), ])"
s4 = sprint(showerror, e4)
@test s4 == "CompositeManifoldError: $(s2)"
eV = [e2, e2]
e5 = CompositeManifoldError(eV)
@test repr(e5) == "CompositeManifoldError([$(repr(e2)), $(repr(e2)), ])"
s5 = sprint(showerror, e5)
@test s5 == "CompositeManifoldError: $(s2)\n\n...and $(length(eV)-1) more error(s).\n"
e6 = ManifoldDomainError("A.", e)
s6 = sprint(showerror, e6)
@test s6 == "ManifoldDomainError: A.\n$(s1)"
e7 = ApproximatelyError(1.0, "M.")
s7 = sprint(showerror, e7)
@test s7 == "ApproximatelyError with 1.0\nM.\n"
p7 = sprint(show, e7)
@test p7 == "ApproximatelyError(1.0, \"M.\")"
end
| ManifoldsBase | https://github.com/JuliaManifolds/ManifoldsBase.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.